pi-background-tasks

extensionmaintained

Pi extension for durable background shell tasks, read-only delegated agents, local attested Pi runs, and fixed-purpose Fusion workflows through child Pi processes.

by · v2.1.4 · published 1d ago

$ pi install npm:pi-background-tasks
downloads/mo
0
stars
6
last push
1d ago
open issues
1

Signals

license: ISCtestspi manifest: missinginstall size: —deps: 0peer deps: 0

Download trend

27.9K downloads · last 12 weeks (weekly)

README

pi-background-tasks logo: a futuristic dispatcher coordinating parallel work nodes into a completed result

pi-background-tasks

Keep Pi moving while long jobs, delegated investigations, and fixed-purpose multi-model Fusion work run in the background.

npm Pi extension Node License

pi-background-tasks adds background jobs, delegated agents, and multi-model Fusion for Pi:

  • Run long work without blocking: start named shell jobs, keep talking to Pi, and get durable completion notifications when they finish.
  • Delegate context-aware investigation: launch one route-pinned, inspect-only child Pi agent seeded with a frozen projection of the current conversation, then retrieve a hash-verified result.
  • Combine model perspectives through fixed-purpose Fusion: run three candidate children, blind evaluation, optional bounded evaluator repair, and merger for reasoning, investigation, targeted URL research, or validation review.

Architecture diagram showing Pi session, background task registry, delegated child agent, and Fusion candidate/evaluator/merger flow

FactValue
Packagepi-background-tasks
Version2.1.4
Node engine>=22.19.0
Pi entrypoint./extensions/background-tasks.ts
Package imagelogo.png
Surface kindCount
command10
tool11
shortcut2
renderer2
eventbus1
workflow4

Public commands: /bg, /bg-clear, /bg-tasks, /bg-update, /fusion, /fusion-models, /jobs, /kill, /logs, /tasks.

Public tools: bg_delegate, bg_kill, bg_logs, bg_result, bg_run, bg_run_pi_attested, bg_status, fusion_investigate, fusion_reason, fusion_research, fusion_validate.

Full owner map and generated contracts live in docs/INDEX.md.

Why use it?

You want to...Use this package because...
Start a dev server, watch build, migration dry run, or long checkbg_run and /bg return immediately, write durable output files, show a footer dock, and notify on terminal state.
Let Pi keep working instead of sleeping or pollingDefault bg_run completion delivery sends a durable terminal notification and can wake a follow-up turn.
Ask a second agent to inspect the repo with the current conversation as contextbg_delegate starts one isolated child with read/search/list tools only; bg_result verifies the committed result before returning it.
Compare model perspectives without exposing arbitrary parent contextFusion children receive only the workflow input and fixed tool policy; no silent route substitution or fallback is used on delegate/Fusion paths.
Produce local evidence for a direct Pi runbg_run_pi_attested records local same-user-writable artifacts and hashes after a successful structured child Pi task.

Install

Version information comes from package.json. Use npm @latest for normal installs; use git main only when you intentionally want the current repository state.

# Global install from npm
pi install npm:pi-background-tasks@latest

# Project-local install from npm
pi install npm:pi-background-tasks@latest -l

# Git main branch; not a release tag
pi install git:github.com/ismailsaleekh/pi-background-tasks@main

# Project-local git main install
pi install git:github.com/ismailsaleekh/pi-background-tasks@main -l

# Local checkout/package path, run from this package directory
pi install .
pi install . -l

Local paths are loaded from disk without copying; use the path to this package from your current directory.

Quick start: useful in under five minutes

  1. Install and start Pi in a project.

  2. Launch a background command:

    /bg --name "Typecheck watch" npm run typecheck -- --watch
    

    /bg starts a tracked shell task and returns the task id plus output path. User-launched /bg tasks notify in the UI but do not automatically wake a follow-up model turn.

  3. Open the footer dock with Shift↓ or list tasks:

    /jobs
    
  4. Read bounded output only when you need it:

    /logs b12ab34c 20000
    
  5. Let a child agent inspect while you continue:

    {"name":"Config reader","prompt":"Inspect the repository configuration files and report where background task settings are documented. Include file paths and quote only the relevant lines.","capability":"inspect"}
    

    Call this with bg_delegate. When its terminal notification arrives, retrieve the answer deliberately:

    {"taskId":"<task id from bg_delegate>","delivery":"inline"}
    

    Call this with bg_result. Retrieval is hash-verified and never silently truncated.

  6. For a self-contained synthesis, start Fusion in the background:

    {"prompt":"Compare the tradeoffs between a watcher, a one-shot build, and a delegated repo inspection for a large refactor."}
    

    Call this with fusion_reason, or use /fusion <prompt> interactively. The launch returns after durable preflight; wait for its terminal notification, then retrieve the verified result with bg_result.

More walkthrough detail: Getting started.

Pick the right workflow

WorkflowBlocking?ContextTools/network/write boundaryBest forExpected behavior
Ordinary foreground Pi workYesFull current sessionWhatever tools the active session hasShort reads/edits/commands where you want live back-and-forthPi waits for the work before responding.
/bgNoNo model child unless your command starts oneRuns your shell command; not sandboxedUser-started local commands, servers, watchesUI notification and footer tracking; /bg uses notification-only by default.
bg_runNoNo model child unless command starts oneRuns your shell command; not sandboxedAgent-started long commandsReturns task id/output path; defaults to notification plus automatic follow-up wake.
bg_delegate + bg_resultNo launch; retrieval is point-in-timeFrozen visible conversation projectionInspect-only child: read, grep, find, ls, artifact read; no shell, writes, network, recursionContext-aware read-only investigation while parent continuesLaunch returns immediately; result is committed by child and hash-verified by retrieval.
bg_run_pi_attestedNoPrompt passed to one direct child Pi runDirect pi --mode json; no shell command; writes requested report pathEvidence-oriented direct Pi taskEmits local attestation sidecar only after successful completion.
/fusion / fusion_reasonBackground launch; point-in-time bg_result retrievalVersioned conversation projection plus promptCandidates/evaluator/repair/merger run with no toolsSelf-contained reasoning and synthesisReturns after durable preflight; three candidates → blind evaluator → optional bounded repair → merger.
fusion_investigateBackground launch; point-in-time bg_result retrievalClean task input onlyCandidate read-only repo tools; evaluator/repair/merger no toolsIndependent repo investigationRestate needed facts; continue only independent work while the live repository is inspected.
fusion_researchBackground launch; point-in-time bg_result retrievalClean task input onlyCandidate read-only repo tools plus targeted fetch of caller-supplied public URLs onlyURL-backed synthesisTargeted URL retrieval, not web search.
fusion_validateBackground launch; point-in-time bg_result retrievalClean task input onlyAdvisory read-only validation reviewSecond-opinion review of completed workDo not mutate the reviewed scope while it runs; not a substitute for mechanical gates.

See Choose a workflow for a decision tree and tradeoffs.

Copy-paste examples

bg_run: start long shell work

{
  "name": "Docs preview",
  "command": "npm run docs:dev",
  "isAgent": false,
  "timeoutSeconds": 3600
}

Expected: returns immediately with a task id, PID when available, and .pi/tasks/...output. The command runs as an ordinary local shell command with your user permissions; it can invoke networked tools or paid services if the command itself does so.

bg_delegate: context-seeded read-only investigation

{
  "name": "Route audit",
  "prompt": "Inspect the package source and identify where delegate route pinning is enforced. Return file paths, function names, and a short explanation. If a fact exists only in omitted parent tool output, say it is unavailable rather than guessing.",
  "capability": "inspect",
  "autoDeliver": "never"
}

Then retrieve:

{
  "taskId": "<delegate task id>",
  "delivery": "inline"
}

Expected: bg_delegate returns a launch receipt immediately. bg_result returns a typed not-ready result while running; after commit it verifies package identity, seed hash, route, block hashes, and aggregate hash before returning bytes. Oversized answers become explicit artifact references, not truncated inline text.

bg_run_pi_attested: local evidence for one Pi child

{
  "name": "Migration report",
  "provider": "openai-codex",
  "model": "gpt-5.5",
  "prompt": "Inspect the repository and write a concise migration report to reports/migration.md.",
  "reportPath": "reports/migration.md",
  "timeoutSeconds": 1800
}

Expected: launches exactly one direct pi --mode json child using structured provider/model fields. It rejects direct API-key/auth-file launch arguments and only writes the attestation sidecar after successful completion and durable hashes. The attestation is local evidence, not cryptographic proof against a compromised machine or provider.

Fusion tools

{"prompt":"Design a rollback strategy for a risky database migration. Include assumptions and failure modes."}

Use with fusion_reason for self-contained synthesis.

{
  "objective": "Find how background task output is capped and surfaced.",
  "background": ["We are evaluating pi-background-tasks behavior for long-running commands."],
  "deliverable": "File paths, constants, defaults, and user-visible behavior.",
  "scope": ["src"],
  "constraints": ["Read-only inspection only."]
}

Use with fusion_investigate.

{
  "objective": "Summarize the installation syntax Pi documents for packages.",
  "background": ["We need package README install examples to match Pi package docs."],
  "deliverable": "A short summary with caveats.",
  "sources": [
    {"url":"https://github.com/earendil-works/pi-coding-agent","purpose":"Pi package documentation repository"}
  ]
}

Use with fusion_research. Only declared public http(s) URLs may be fetched; this is not a search tool.

{
  "objective": "Review whether a documentation-only change is ready to ship.",
  "background": ["The change edits README and package-local docs only."],
  "changeSummary": "Replaced monolithic README with landing page and moved operational details into docs.",
  "scope": ["README.md", "docs/getting-started.md", "docs/choose-a-workflow.md"],
  "acceptanceCriteria": ["Install commands are accurate", "Safety limitations are explicit", "Examples match public schemas"],
  "verification": {
    "status": "provided",
    "evidence": [{"check":"Focused link check", "outcome":"All local README links resolve"}]
  }
}

Use with fusion_validate for advisory read-only review.

Footer dock

Illustration of the pi-background-tasks footer dock with running and completed tasks

When tasks are running or unseen completions exist, the footer shows a compact bg ... segment. Press Shift↓ to open the focused bottom dock. Use /bg-clear to acknowledge finished-task footer notices in any terminal.

ControlAction
Shift↓Open the dock
/bg-clearClear finished-task notices
/ , PageUp / PageDownMove through list or scroll output tail
Enter / Inspect details
Return to list
kStop selected running task
RRerun selected command
cShow copyable output path
x / Esc / qClose dock

Agent tasks launched through pi -p ... or pi --mode json ... and marked isAgent:true can show task-owned model/context/token/tool telemetry. Missing child telemetry is shown as unavailable, not synthesized as zero.

Architecture, trust, and safety

  • Runtime task files live under .pi/tasks/<session-id>-<pid>/; Fusion artifacts under .pi/fusion/...; delegate artifacts under .pi/delegate/....
  • Shell jobs are tracked by the package, but they are not sandboxed. Treat commands as local processes with your permissions and credentials.
  • Delegate and Fusion child Pi processes are route-pinned where applicable; delegate/Fusion paths do not silently substitute routes.
  • Fusion uses direct child pi --mode text processes, not direct completion APIs. Frontier Fusion routes are admitted only through Pi Anthropic or Codex subscription OAuth; metered frontier API credentials are rejected before child creation.
  • Claude Fusion children load the package-owned Claude Code OAuth attribution provider shared with the repo spawn path, request ttl: "1h" on system/tool/conversation cache breakpoints before serialization, and preserve provider-reported cacheWrite1h evidence. Set PI_CACHE_RETENTION=short|none|long to choose explicitly; malformed attribution, policy, or cache evidence fails before transport. Provider usage is preserved verbatim, but subscription OAuth can report cacheWrite1h = 0 even when a unique cache remains readable beyond five minutes; treat positive cacheWrite1h as definitive and zero as inconclusive on that channel. Anthropic budgeting follows the provider's 200K subscription policy.
  • Fusion research fetches only caller-supplied public http(s) URLs with bounded retrieval. It is not web search and not a secret-exfiltration boundary.
  • Attestation sidecars are local, unsigned, same-user-writable evidence. They are useful for downstream local gates, but not cryptographic proof against local compromise, a compromised Pi binary, or a compromised provider.
  • Metadata, attestations, delegate/Fusion artifacts, and configuration replacements use write/fsync/rename durability patterns. Failed/cancelled stored Fusion runs also have a manifest-bound failure-summary.json containing bounded no-answer evidence metadata and artifact refs only; bg_result returns it as an answer-free typed terminal view after integrity checks. Ordinary task output is closed and drained before terminal publication but is not explicitly fsynced. POSIX directory entries are fsynced after atomic replacement; Windows lacks the same portable directory-entry crash-durability guarantee.

Detailed operations: Configuration.

EventBus and Autopilot integration

Other Pi extensions can control the same BackgroundTaskRegistry through Pi's events bus instead of shelling out or maintaining a second task manager. The public channels are:

PurposeChannel
Requestpi-background-tasks:request:v1
Responsepi-background-tasks:response:v1
Terminal task eventpi-background-tasks:terminal:v1

Operations are capabilities, run, status, logs, and kill. This is the integration point for orchestrators such as Autopilot that need non-blocking package-managed work with bounded logs and correlated terminal events. Consumers must deduplicate terminal frames by task.id: an EventBus listener failure can cause a retried publication.

Documentation map

NeedRead
First install and first taskGetting started
Which workflow/tool to chooseChoose a workflow
Environment variables, shells, output caps, model config, offline behaviorConfiguration
Package QA expectationsTESTING.md and TEST_PLAN.md
Publishing notesPUBLISHING.md
LicenseLICENSE

Contributing

Keep user-facing claims tied to source. If you change public schemas, command behavior, durability, model routing, or environment variables, update these package-local docs in the same change and run focused checks appropriate to the edit.