pi-autonomous-session-control
pi extension package for autonomy-control workflows in pi
Package details
Install pi-autonomous-session-control from npm and Pi will load the resources declared by the package manifest.
$ pi install npm:pi-autonomous-session-control- Package
pi-autonomous-session-control- Version
0.1.5- Published
- May 12, 2026
- Downloads
- 133/mo · 133/wk
- Author
- tryinget
- License
- MIT
- Types
- extension, prompt
- Size
- 376.9 KB
- Dependencies
- 0 dependencies · 3 peers
Pi manifest JSON
{
"extensions": [
"./extensions/self.ts"
],
"prompts": [
"./prompts"
]
}Security note
Pi packages can execute code and influence agent behavior. Review the source before installing third-party packages.
README
summary: "Overview and quickstart for pi-autonomous-session-control." read_when:
- "Starting work in this repository." system4d: container: "Repository scaffold for a pi extension package." compass: "Ship small, safe, testable extension iterations." engine: "Plan -> implement -> verify with docs and hooks in sync." fog: "Unknown runtime integration edge cases until first live sync."
pi-autonomous-session-control
Monorepo-home package for subagent lifecycle hardening, failure recovery, and operator visibility in pi.
Canonical package path: packages/pi-autonomous-session-control
Workspace placement
For workspace-level placement and ownership boundaries, read:
~/ai-society/holdingco/governance-kernel/docs/core/definitions/ai-society-stack-map.md~/ai-society/softwareco/owned/agent-kernel/docs/project/ai-society-convergence-architecture.md~/ai-society/softwareco/owned/pi-extensions/packages/pi-society-orchestrator/docs/project/subagent-execution-boundary-map.md~/ai-society/softwareco/owned/pi-extensions/packages/pi-society-orchestrator/docs/adr/2026-03-11-control-plane-boundaries.md
Short version:
- this package is the strongest current Pi-side execution/runtime owner
- it is not the canonical society-state authority (
ak/AK own that) - it is not the workspace-wide control board (FCOS/governance-kernel own that)
- package-local control-plane coordination belongs in
pi-society-orchestrator
Cross-package execution-boundary packet
If the work is about how ASC should expose its runtime to pi-society-orchestrator, start with the orchestrator-owned packet docs:
../pi-society-orchestrator/docs/project/subagent-execution-boundary-map.md../pi-society-orchestrator/docs/adr/2026-03-11-control-plane-boundaries.md../pi-society-orchestrator/docs/project/2026-03-10-rfc-asc-public-execution-contract.md../pi-society-orchestrator/docs/project/2026-03-10-architecture-convergence-backlog.md
Interpretation:
- the ADR decides that ASC remains the execution-plane owner
- the RFC describes the first public runtime seam ASC should expose
- the backlog / AK tasks describe the implementation order
- this package README describes the current runtime owner reality, not the seam design by itself
Quickstart
Install dependencies:
npm installTest with pi (one-off, doesn't persist):
pi -e ./extensions/self.tsFor active development, rely on auto-discovery:
When you're in this project directory, pi automatically discovers the
package.jsonand loads extensions defined inpi.extensions. No manual install needed.
Local Development vs Global Install
Important: Avoid double-loading by understanding pi's package identity:
| Source | Identity |
|---|---|
| npm package | Package name (pi-autonomous-session-control) |
| git source | Repository URL |
| Local path | Resolved absolute path |
During local development:
- Do NOT add this package to global
~/.pi/agent/settings.json - Rely on project auto-discovery when working in this directory
- Use
pi -e /path/to/packageif you need the extension in another project temporarily
After publishing to npm:
pi install npm:pi-autonomous-session-control
When both exist:
- Local path and npm package are DIFFERENT identities → both load → conflicts
- Solution: During active development, remove the npm entry from global settings
To temporarily disable a global package while developing locally:
# Remove from global settings
pi remove npm:pi-autonomous-session-control
# Or manually edit ~/.pi/agent/settings.json and remove from packages array
To quickly test the extension in another project without installing:
pi -e /path/to/pi-autonomous-session-control
Runtime dependencies and packaged files
This extension expects pi host runtime APIs and declares them as peerDependencies:
@mariozechner/pi-coding-agent@mariozechner/pi-ai
For npm publishing, package.json uses a files whitelist so required runtime artifacts are explicit:
execution.tsextensions/self.tsextensions/self/prompts/examples/policy/security-policy.json
If your extension also needs extra runtime assets, add them to files intentionally.
Shared tech-stack policy now stays root-owned rather than shipping a package-local stack metadata file.
Prompt surfaces and provenance
ASC owns two distinct prompt-related surfaces:
- package-owned prompt assets in
prompts/, exposed throughpackage.json#pi.promptsand shipped with the package install - runtime prompt-envelope provenance returned by
dispatch_subagentresult details when callers provideprompt_name,prompt_content,prompt_tags, andprompt_source
Keep those surfaces separate from repo-root .pi/prompts/* operator prompts in the monorepo root.
Mock/unit prompt-vault contract tests run in the default package check. Live prompt-vault files use the non-default .live.mjs suffix, so npm run check does not discover them and reports zero live prompt-vault skips. The live cross-extension harness is host-dependent and opt-in; run npm run test:live:prompt-vault (or set ASC_RUN_LIVE_PROMPT_VAULT_TESTS=1) to prove the vault_query -> vault_retrieve -> dispatch_subagent chain preserves prompt provenance coherently, including the vault-client-live source label. When no PI_VAULT_CLIENT_DIR / VAULT_CLIENT_DIR override is set, the harness tries the legacy installed extension path and then the monorepo sibling ../pi-vault-client package.
Prompt-vault compatibility self-check
The self-prompt-vault-compat command reports the ASC package version, vault-client version, and prompt-vault schema version. Its ASC floor now comes from a safer feature/manifest policy: source manifests that declare the ASC package name, the public ./execution export, and shipped extensions/self runtime files may use the package source floor (0.1.0), while missing/unparseable or feature-incomplete manifests fall back to the historical prompt-envelope floor (0.1.3). This avoids certifying arbitrary low manifests (for example 0.0.1) solely because their checked package version is low. The Dolt schema probe is timeout-bounded and reports schema unavailable instead of hanging when the prompt-vault DB is slow or wedged.
Capability discovery surfaces
The self tool accepts capability meta-queries such as What can you do?, capability discovery, and capability routing. Its response intentionally distinguishes three surfaces:
selfquery domains: perception, direction, crystallization, protection, and action queries understood by the ASC self mirror.- Toolbox/bundle discovery: use the Pi
toolboxtool to search, explain, activate, deactivate, or inspect extension bundles. ASC does not add or replace that tool. - Repo/lane capability-map routing: use documentation surfaces such as
repo-capability-map.mdandpi-extensions/docs/project/root-capabilities.mdto choose owning repos/packages and read-first docs. These maps are routing guidance, not runtime authority.
Public execution contract
ASC now exposes a supported package-level execution seam for non-tool consumers:
import { createAscExecutionRuntime } from "pi-autonomous-session-control/execution";
const runtime = createAscExecutionRuntime({
sessionsDir: "/tmp/pi-subagent-sessions",
modelProvider: () => "openai-codex/gpt-5.4",
});
const controller = new AbortController();
const result = await runtime.execute(
{
profile: "reviewer",
objective: "Review the staged changes for risk and missing tests.",
},
{ cwd: process.cwd() },
undefined,
controller.signal,
);
modelProvider may also inspect the execution context (for example ctx?.model) when you want public-runtime consumers to mirror the active session model instead of hard-coding one.
What this seam guarantees:
- the same core execution logic now backs both
dispatch_subagentand public runtime consumers - prompt-envelope application, request env policy, lifecycle invariants, runtime-owned concurrency reservation, session-name reservation, result shaping, assistant protocol classification, and abort propagation stay ASC-owned
- result surfaces now use one normalized failure taxonomy: canonical
result.details.status(done,aborted,timed_out,error) plusresult.details.failureKindfor the specific failure branch - a dedicated parity harness now proves those shared semantics stay aligned across the public runtime and the tool path
- downstream consumers should prefer
pi-autonomous-session-control/executionover privateextensions/self/*imports
Current verification split:
- ASC package-local tests prove seam semantics and transport-safety invariants
packages/pi-society-orchestrator/tests/runtime-shared-paths.test.mjsproves the narrow consumer-side adapter still preserves those semantics in repo-local sourcepackages/pi-society-orchestrator/tests/execution-seam-guardrails.test.mjsfail-closes drift back to private ASC imports or a revived orchestrator-local execution pathnpm run test:live:prompt-vaultopts into host-dependent live prompt-vault validation; it runstests/prompt-vault-db-integration.live.mjsandtests/prompt-vault-cross-extension.live.mjsto prove real DB/vault-client coherence with ASC-owned prompt provenance ondispatch_subagent; defaultnpm run checkdoes not discover live prompt-vault filescd packages/pi-society-orchestrator && npm run release:checkproves installed-package/import-graph truth for the packaged orchestrator artifact, including the current bundled ASC bridge while the temporary lifecycle defined in bundled ASC bridge lifecycle remains in force- the first time-boxed execution seam review still counts only one real external runtime consumer today (
pi-society-orchestrator), so no seam widening is justified
Companion package doc:
When using UI APIs (ctx.ui), guard interactive-only behavior with ctx.hasUI so pi -p non-interactive runs stay stable.
Repository checks
Run:
npm run check
check routes to quality:ci via scripts/quality-gate.sh.
It enforces structure validation, Biome lint checks, optional TypeScript typechecks, default unit/mock tests, and npm pack dry-run. Host-dependent live prompt-vault DB / vault-client tests are not discovered by default because they use .live.mjs filenames; run them explicitly when the host has the vault DB, Dolt, and vault-client runtime available:
npm run test:live:prompt-vault
# equivalent env gate for focused node --test runs:
ASC_RUN_LIVE_PROMPT_VAULT_TESTS=1 node --test tests/prompt-vault-db-integration.live.mjs tests/prompt-vault-cross-extension.live.mjs
Quality gate lane (TS)
- formatter/lint baseline:
- biome.jsonc
- .vscode/settings.json (Biome formatter + code actions on save for JS/TS/JSON)
- pinned local binary via
@biomejs/biomeindevDependencies
- scripts/quality-gate.sh stages:
pre-commitpre-pushci
- npm script entry points:
npm run quality:pre-commitnpm run quality:pre-pushnpm run quality:ci
- helper scripts:
npm run fix(auto-fix)npm run lint(check-only)npm run typecheck
- root-owned stack review surface:
Release + security baseline
This package now uses the root-owned monorepo release control plane in component mode. It keeps its own independent release cadence, but the workflows/config live at monorepo root.
Relevant root-owned files:
- CI workflow
- release-check workflow
- release-please workflow
- publish workflow
- release-please config
- release-please manifest
- root component helper
- release-check script
- Security policy
Trusted-publishing defaults now relevant to this package:
- release tags are component-scoped (
pi-autonomous-session-control-vX.Y.Z) - root release-please action is pinned to an immutable v4.4.0 SHA
- root publish and release-check workflows both upgrade npm (
>=11.5.1) for consistent trusted publishing behavior - setup-node uses
package-manager-cache: falseto avoid implicit caching behavior changes from setup-node v5+ - package metadata must include
repository.urlmatching the GitHub repo for npm provenance verification
Recommended before release:
npm run release:check
# quick mode for CI / no local pi smoke
npm run release:check:quick
Optional: add an executable scripts/release-smoke.sh for extension-specific smoke checks.
release-check.sh will run it with isolated PI_CODING_AGENT_DIR and PACKAGE_SPEC env vars.
Before first production release under root automation:
- Confirm/adjust owners in ../../.github/CODEOWNERS.
- Enable branch protection on
main. - Confirm GitHub Actions repo settings:
- workflow permissions:
Read and write - allow GitHub Actions to create/approve PRs
- allowed actions policy permits marketplace actions used by workflows
- workflow permissions:
- Configure npm Trusted Publishing for the monorepo repo + root publish workflow.
- If this is a brand-new npm package, perform one bootstrap token publish first, then add the trusted publisher in npm package settings.
- Let root release-please open the component release PR, then publish from the GitHub release.
Issue + PR intake baseline
Included files:
- Bug report form
- Feature request form
- Docs request form
- Issue template config
- PR template
- Code of conduct
- Support guide
- Top-level contributing guide
Vouch trust gate baseline
Included files:
Default behavior:
- PR workflow runs on
pull_request_target(opened,reopened). require-vouch: trueandauto-close: trueare enabled by default.- Maintainers can comment
vouch,denounce, orunvouchon issues to update trust state. - Vouch actions are SHA pinned for reproducibility and supply-chain review.
Bootstrap step:
- Confirm/adjust entries in .github/VOUCHED.td before enforcing production policy.
Docs discovery
Run:
npm run docs:list
npm run docs:list:workspace
npm run docs:list:json
Wrapper script: scripts/docs-list.sh
Resolution order:
DOCS_LIST_SCRIPT./scripts/docs-list.mjs(if vendored)~/ai-society/core/agent-scripts/scripts/docs-list.mjs
TypeScript lane reference for pi extensions:
uv tool run --from ~/ai-society/core/tech-stack-core tech-stack-core show pi-ts --prefer-repo
Shared lane stance for this monorepo now lives at root in ../../docs/tech-stack.local.md.
Copier lifecycle policy
- Keep
.copier-answers.ymlcommitted. - Do not edit
.copier-answers.ymlmanually. - Run from a clean destination repo (commit or stash pending changes first).
- Use
copier update --trustwhen.copier-answers.ymlincludes_commitand update is supported. - In non-interactive shells/CI, append
--defaultsto update/recopy. - Use
copier recopy --trustwhen update is unavailable (for example local non-VCS source) or cannot reconcile cleanly. - After recopy, re-apply local deltas intentionally and run
npm run check.
Hook behavior
- Git hooks path is configured to
.githooksby scripts/install-hooks.sh. - .githooks/pre-commit runs:
scripts/quality-gate.sh pre-commit- check-only (auto-fix with
npm run fix)
- .githooks/pre-push runs:
scripts/quality-gate.sh pre-push
- Repo-local commit workflow prompt:
Subagent Configuration
The dispatch_subagent tool spawns subagents with configurable model selection:
Model selection priority:
PI_SUBAGENT_MODELenvironment variable (override)- Current session model (
<provider>/<model-id>) when available - Fixed fallback:
openai-codex/gpt-5.4
The child still launches with --no-extensions, but ASC now supports explicit child-only extension bootstrap on top of that minimal base. Empty or whitespace-only requested/effective model selections fail before spawn as structured model_selection_failed results and do not expose internal concurrency counters. When the current model uses a numeric-suffix provider alias such as openai-codex-2, ASC auto-loads pi-multi-pass into the child so the same subscription-backed provider alias remains valid instead of being collapsed to the base provider. ASC also launches the raw child against an isolated copy of the Pi agent dir with a sanitized settings.json, so extensionless child runs do not inherit unrelated global default-model warnings from the parent's configured provider aliases.
Request env policy:
DispatchSubagentRequest.envis a per-dispatch child environment overlay for provenance sidecars only.- Allowed keys must match
PI_PROVENANCE_*(for examplePI_PROVENANCE_REVIEW_LANE_IDorPI_PROVENANCE_OUTPUT_FILE). - All other request env keys, including
PATH,NODE_OPTIONS, andPI_CODING_AGENT_DIR, fail before spawn as structuredenv_policy_failedresults; there is no privileged passthrough escape hatch. - Allowed request env values reach the spawned helper/child process but are not echoed in result details.
Session storage:
PI_SUBAGENT_SESSIONS_DIR— directory for session files (default:./.pi-subagent-sessions)PI_SUBAGENT_CLEAR_ON_SESSION_START— set totrueto clear*.jsonsubagent sessions onsession_start(default: off / non-destructive)PI_SUBAGENT_RESERVE_SESSION_NAMES— set tofalseto disable all session-name reservation mechanisms (in-memory + file-lock) for rollback/debugging (default: enabled)PI_SUBAGENT_FILE_LOCK_SESSION_NAMES— set tofalseto disable only cross-process file-lock reservation while keeping in-memory reservation (default: enabled; ignored whenPI_SUBAGENT_RESERVE_SESSION_NAMES=false)PI_SUBAGENT_LOCK_STALE_AFTER_MS— stale-lock reclamation threshold in milliseconds for orphaned subagent locks that no longer have a live owning PID (default:3600000)PI_SUBAGENT_EVENT_BUFFER_BYTES— buffer for the filtered assistant-only subagent protocol consumed by ASC (default:262144)PI_SUBAGENT_RAW_PI_EVENT_BUFFER_BYTES— raw upstreampi --mode jsonline buffer inside the filter helper before aggregate events are dropped (default:8388608)
Session artifact notes:
- Local session files in
./.pi-subagent-sessionsare runtime artifacts and are gitignored by default. - Unless
PI_SUBAGENT_MODELoverrides it, subagents inherit the current session model when Pi exposes one; the fixed fallbackopenai-codex/gpt-5.4is only used when no current model is available. - When that requested model points at a numeric-suffix provider alias supplied by an extension (for example
openai-codex-2from multi-pass), ASC preserves that exact requested/effective model and auto-loadspi-multi-passinto the child runtime. dispatch_subagentalso acceptsextensions: ["vault-client", "/abs/path/to/ext.ts", ...]so a subagent can opt into specific extension-provided tools without inheriting the full parent extension surface.- Result details now expose both the selected model (
requestedModel/effectiveModel) and the explicit child bootstrap set (loadedExtensions,extensionWarnings). - Subagent transport now runs through a package-local assistant-only JSON filter helper, so large aggregate Pi events (
agent_end,turn_end,tool_execution_end) are dropped before ASC parses the stream. - ASC now treats the helper protocol as authoritative: raw Pi JSON events on the parent seam fail closed instead of being accepted as a compatibility fallback.
- Parent-side execution timeouts now arm only after the helper emits its
transport_readyhandshake, so helper/raw-pibootstrap does not silently consume the configured execution budget. - Helper shutdown now tears down the raw
pichild process group before parent-side force kill, preventing orphaned raw subprocesses on timeout/abort. - Lock files now store lightweight metadata (
pid,ppid,sessionName,createdAt) so dead-parent reservations can be reclaimed automatically; live PIDs are never evicted solely due to age. - Status sidecars (
<session>.status.json) recordrunning|done|error|timeout|aborted|abandoned; dead running sessions are reconciled toabandonedon next startup. - Status sidecars now also keep a bounded
resultPreviewplus the originating liveparentSessionKeywhen available so dashboard/inspection views can stay session-aware without parsing the whole session log. subagent-statusnow reports counts by terminal/runtime status for faster operator diagnosis.- A read-only widget surfaces recent subagent sessions for the current live session only, appears only after this session dispatches a subagent, and auto-clears once entries age past 1 hour.
- If you want long-horizon analysis/retention, set
PI_SUBAGENT_SESSIONS_DIRto a durable external path (for example~/.pi/subagent-sessions). Those local artifacts are bounded replay aids; Pi's native session tree remains the live conversation authority.
Dashboard commands:
/subagent-dashboard— open a read-only summary of recent subagent sessions, including current-session scope and bounded result previews/subagent-inspect <session-name>— open a derived inspection summary with lifecycle metadata, session scope, bounded replay notes, artifact paths, safety notes, and the raw status sidecar for a specific session
Example:
# Use a different model for subagents
PI_SUBAGENT_MODEL=github-copilot/gpt-4o pi
# Force extra child-only extensions for every subagent
PI_SUBAGENT_EXTENSIONS=vault-client,/abs/path/to/custom-extension.ts pi
# Custom session directory
PI_SUBAGENT_SESSIONS_DIR=/tmp/pi-sessions pi
Self memory persistence
self now persists scoped memory domains across sessions:
- Crystallization (
remember/recallpatterns) - Protection (
mark trap/ trap registry)
Persistence behavior:
PI_SELF_MEMORY_PATH— explicit memory snapshot file path override- Default path: sibling of the sessions directory, named
<sessionsDirBase>.self-memory.json- default sessions dir
./.pi-subagent-sessions⇒ default memory file./.pi-subagent-sessions.self-memory.json
- default sessions dir
- Snapshot format is schema-versioned (
schemaVersion: 1) and validated on load - Malformed snapshots fail safe (tool remains usable; snapshot is repaired on next successful scoped persistence)
Current runtime reality
dispatch_subagentis wired, bounded, and backed by session/status artifacts plus the read-only dashboard and inspection commands.- The package-level
pi-autonomous-session-control/executionentrypoint now exposes the supported public execution contract for non-tool consumers. - ASC now carries an owned rewind runtime slice that captures exact rewind points on turn boundaries, integrates with Pi's built-in
/forkand/treelifecycle hooks, and can project bounded restore milestones into Replay Fabric whenASC_REWIND_REPLAY_FABRIC_URLis configured. - Prompt-envelope application, runtime compatibility checks, invariant summaries, failure-memory canary coverage, and Edge Contract Kernel adoption are all live.
- Scoped self-memory persistence is in place; remaining forward-looking work should live in
README.md+next_session_prompt.md, not a separatestatus.mdmirror.
Live package activation
Install the package into Pi from its local package path:
pi install /home/tryinget/ai-society/softwareco/owned/pi-extensions/packages/pi-autonomous-session-control
Then in Pi:
- run
/reload - verify with a real command or tool call from this package