pi-larva 0.8.11 → 0.8.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,8 +35,8 @@ provides nine child-runtime tools, not registry mutation.
35
35
 
36
36
  External hosts can discover Pi automatically or set `LARVA_PI_CLI_SCRIPT`
37
37
  to the verified Pi package bin script. The server supplies
38
- `externalHostCanSpawn: true`; optional `parent_persona_id` per call, or `LARVA_MCP_PARENT_PERSONA` as fallback, enforces
39
- that resolved parent's `can_spawn` without changing native Pi parent rules.
38
+ `externalHostCanSpawn: true`; see [external-host authority](#external-host-pi-subagent-mcp-server)
39
+ for how root and descendant MCP calls differ from native Pi.
40
40
  Use `wait_for_completion: true` for one delegated task, or accepted receipts
41
41
  plus wait/select for parallel work. MCP wait/select results add
42
42
  `terminal_outputs` to structured content, with captured result text and artifact
@@ -224,7 +224,12 @@ Larva's later hook re-enumerates the tool baseline and reapplies persona policy
224
224
  only when the visible set changed.
225
225
 
226
226
  `subagent-runtime.json` is a closed JSON object with `schema_version: 1` and an
227
- `extension_sources` array. Sources use Pi `-e` semantics: npm/git/URL sources are
227
+ `extension_sources` array. Optional spawn policy keys are
228
+ `root_session_spawn` (`"persona"` by default, or `"allow"` for native Pi roots),
229
+ `max_depth`, and `max_active_runs` (each an integer in `1..100` if present).
230
+ Omitting either limit adds no policy cap. These options do not change PersonaSpec
231
+ or bypass Pi tool policy. Unknown keys or invalid values are rejected.
232
+ Sources use Pi `-e` semantics: npm/git/URL sources are
228
233
  passed through, `pi-agent:` paths resolve inside `PI_CODING_AGENT_DIR` (default
229
234
  `~/.pi/agent`), `~` local paths expand against the runtime home, and relative
230
235
  local paths resolve against the real directory containing the config file.
@@ -709,6 +714,10 @@ persona on the **current branch** then takes precedence over the explicit id;
709
714
  without one, initialization uses the explicit id, the configured default, or
710
715
  `larva:none`. A stored persona's unused explicit model is not validated. Restore
711
716
  uses the current registry definition, with a notice if its digest changed.
717
+ This stored-persona precedence applies to interactive sessions, not
718
+ Larva-launched children: `LARVA_PI_INITIAL_PERSONA_ID` stays authoritative on
719
+ initialization and `switch_session`. Child `get_state` verifies the active
720
+ persona alongside model and thinking before the prompt is sent.
712
721
 
713
722
  Larva reconstructs persona and self-switch mode from
714
723
  `ctx.sessionManager.getBranch()`, never abandoned branches returned by
@@ -1459,12 +1468,15 @@ Native Pi extension invocation continues using its captured native launch identi
1459
1468
  The usual Larva CLI, persona registry, model routing and child capsule settings
1460
1469
  still apply.
1461
1470
 
1462
- External hosts do not need a synthetic parent Pi session. Omit `parent_persona_id`
1463
- to admit any valid resolved target persona, or supply it on `larva_subagent` to
1464
- resolve and enforce that parent's `can_spawn` boolean/whitelist. The optional
1465
- `LARVA_MCP_PARENT_PERSONA` environment setting supplies a default parent ID.
1466
- An admitted parent's ID reaches the child as `LARVA_PI_PARENT_PERSONA_ID`.
1467
- The native extension's active-parent authority checks remain unchanged.
1471
+ An external MCP root needs no synthetic parent Pi session. A per-call
1472
+ `parent_persona_id` overrides `LARVA_MCP_PARENT_PERSONA`; a blank environment
1473
+ value counts as unset. With a selector, the resolved parent's `can_spawn` applies;
1474
+ without one, the host grants root authority. At descendant depths, authority
1475
+ instead binds to `LARVA_PI_INITIAL_PERSONA_ID` and its `can_spawn`; a missing ID
1476
+ or conflicting selector fails admission. An admitted parent's ID reaches the
1477
+ child as `LARVA_PI_PARENT_PERSONA_ID`. Stdio rejects explicitly blank subagent
1478
+ arguments with `LARVA_BAD_INPUT` before importing `larva.ts`; blank
1479
+ `search_mentions` queries still list candidates.
1468
1480
 
1469
1481
  `larva_subagent` defaults to an immediate accepted receipt for parallel fan-out.
1470
1482
  Use `wait_for_completion: true` for a single call that waits for terminal output.
@@ -1533,8 +1545,11 @@ Native Pi has a `larva:none` default for fresh sessions unless an explicit
1533
1545
  startup persona or restorable session persona is present. Loading the extension is
1534
1546
  capability, not identity; it does not imply a hidden `general` persona.
1535
1547
 
1536
- When the active parent persona and Pi tool policy allow subagents, the extension
1537
- exposes these model-facing tools:
1548
+ The extension exposes these model-facing tools subject to Pi tool policy.
1549
+ Native spawn admission also requires an active persona. By default its
1550
+ `can_spawn` applies; `root_session_spawn: "allow"` bypasses only that check at
1551
+ depth 0. See the [six-stage admission order and hard lineage bounds](../../docs/reference/PI_EXTENSION_ASYNC_SUBAGENTS.md#spawn-admission-and-lineage-spec-v4)
1552
+ for `LARVA_PI_SUBAGENT_DEPTH` and `LARVA_PI_ANCESTOR_TASK_IDS`.
1538
1553
 
1539
1554
  ```text
1540
1555
  larva_subagent(persona_id, task, task_id?, no_progress_timeout_ms?)
@@ -1748,8 +1763,10 @@ authoritative for this indicator or any orchestration decision.
1748
1763
  non-empty renderer-safe reason bounded to 500 normalized code points. Cancellation
1749
1764
  must target only that child: it must not abort the parent agent, reset every child,
1750
1765
  delete child session files, cancel siblings, accept aliases, or use fuzzy
1751
- matching. The adapter sends child RPC abort, waits 1500 ms, and kills the child
1752
- process only if it has not exited after that grace period. If the model-facing
1766
+ matching. The adapter sends child RPC abort, closes stdin when it settles, and
1767
+ sends at most one `SIGTERM` after 1,500 ms if the child is still alive. See
1768
+ [kernel-pipe self-exit and the descendant capsule manifest](../../docs/reference/PI_EXTENSION_ASYNC_SUBAGENTS.md#session-lifecycle-rules).
1769
+ If the model-facing
1753
1770
  cancel tool returns a terminal result (`cancelled`, `success`, or `failed`), the
1754
1771
  duplicate terminal callback is suppressed; if it returns non-terminal
1755
1772
  `cancelling`, the eventual terminal result still delivers one callback. User
@@ -1762,8 +1779,9 @@ keyed by the public `task_id` once known. `moveSubagentRunToTaskId` transfers
1762
1779
  startup records to that public key, `activeSubagentRunByTaskId` owns exact lookup,
1763
1780
  and `cancelSubagentByTaskId` owns targeted cancellation. Terminal states are
1764
1781
  immutable for control purposes: stale or late child completions must not duplicate
1765
- callbacks or revive cancelled tasks. Same-process duplicate resumes of an active
1766
- `task_id` return `LARVA_SESSION_BUSY`.
1782
+ callbacks or revive cancelled tasks. Resumes targeting an ancestor or a run
1783
+ still owned by this process return `LARVA_SESSION_BUSY`; ownership lasts through
1784
+ cleanup, not just until the terminal result.
1767
1785
 
1768
1786
  Failure and cancellation paths return renderer-safe Pi ToolResult wrappers with
1769
1787
  stable error text in `content` and machine-readable state in `details`. Existing
@@ -1965,7 +1983,11 @@ Every emitted child JSONL record is bounded before Pi's captured raw writer send
1965
1983
  it. Oversized progress and full `agent_end.messages` become bounded metadata;
1966
1984
  `willRetry` and bounded provider/runtime type/message remain. Modern execution
1967
1985
  settles only on `agent_settled`, so retry, compaction retry, and continuation work
1968
- cannot end on an earlier `agent_end`.
1986
+ cannot end on an earlier `agent_end`. The multi-hop settlement barrier also
1987
+ waits for descendant runs and callback continuations, active invocations, and
1988
+ pending persona-switch continuations. Recognized descendant activity relays
1989
+ upward as `larva_subagent_progress` to reset watchdogs without adding text.
1990
+ See the [RPC settlement contract](../../docs/reference/PI_EXTENSION_ASYNC_SUBAGENTS.md#child-rpc-stream-retention-and-memory-safety).
1969
1991
 
1970
1992
  The parent reads stdout with a byte-counted LF decoder rather than Node
1971
1993
  `readline`. It accepts CRLF by stripping one trailing CR, keeps U+2028/U+2029
@@ -2224,6 +2246,11 @@ the reference contract: `prompt_max_65536_utf8_bytes`,
2224
2246
  `terminal_race_first_terminal_state_wins`, `terminal_race_at_most_one_result`,
2225
2247
  and `terminal_race_late_timeout_cancel_stale_ignored`.
2226
2248
 
2249
+ Internal persona invocation shares the hard lineage and lifecycle mechanisms,
2250
+ not the optional spawn policy: `root_session_spawn`, `max_depth`, and
2251
+ `max_active_runs` do not apply. `LARVA_PI_PERSONA_INVOCATION=1` selects bounded
2252
+ projection for RPC records over 1 MiB without disk output artifacts.
2253
+
2227
2254
  See the authoritative design document for the strict event payloads, state
2228
2255
  machine, and boundaries:
2229
2256
  [`../../docs/reference/PI_EXTENSION_PERSONA_INVOCATION.md`](../../docs/reference/PI_EXTENSION_PERSONA_INVOCATION.md).
@@ -1,10 +1,61 @@
1
+ import { lstatSync, readdirSync, rmSync, writeSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, dirname, join } from "node:path";
4
+
1
5
  const BRIDGE_SYMBOL = Symbol.for("larva.pi.child-rpc-frame-preload.v1");
2
6
  const CAPABILITY = "larva-child-rpc-frame-preload-v1";
3
7
  const MAX_RECORD_BYTES = 1_048_576;
8
+ const ABORT_GRACE_MS = 1_500;
9
+
10
+ function removeChildCapsuleRoot(env) {
11
+ const root = env.LARVA_PI_CAPSULE_ROOT;
12
+ if (!root || dirname(root) !== join(env.HOME || homedir(), ".pi", "larva", "runtime") || !/^child-\d+-[a-f0-9]{16}$/.test(basename(root))) return;
13
+ try {
14
+ if (!lstatSync(root).isDirectory()) throw new Error("not an owned directory");
15
+ try {
16
+ const manifests = join(root, "descendants");
17
+ if (!lstatSync(manifests).isDirectory() || readdirSync(manifests).length > 0) return;
18
+ } catch (error) {
19
+ if (error.code !== "ENOENT") throw error;
20
+ }
21
+ rmSync(root, { recursive: true, force: true });
22
+ } catch (error) {
23
+ if (error.code !== "ENOENT") {
24
+ try { writeSync(2, `larva pi: capsule cleanup failed: ${JSON.stringify({ capsule_root: root, reason: error.code ?? "not an owned directory" }).slice(0, 1024)}\n`); }
25
+ catch { /* Diagnostics must not prevent exit. */ }
26
+ }
27
+ }
28
+ }
4
29
 
5
30
  if (globalThis[BRIDGE_SYMBOL] === undefined) {
6
31
  const nativeWrite = process.stdout.write.bind(process.stdout);
7
32
  let transformRecord = null;
33
+ const encode = (records) => records.map((record) => {
34
+ if (typeof record !== "string") throw new TypeError("Larva child RPC preload transform returned a non-string record.");
35
+ const bytes = Buffer.byteLength(record, "utf8");
36
+ if (bytes > MAX_RECORD_BYTES) throw new RangeError(`Larva child RPC preload emitted ${bytes} bytes (limit ${MAX_RECORD_BYTES}).`);
37
+ return `${record}\n`;
38
+ }).join("");
39
+ const emit = (records) => { nativeWrite(encode(records), "utf8"); };
40
+
41
+ // NODE_OPTIONS and the capsule environment also reach resolver/tool subprocesses,
42
+ // including route verification run by the same parent as the child Pi process.
43
+ const capsule = process.env.LARVA_PI_CAPSULE_ROOT;
44
+ const mode = process.argv.indexOf("--mode", 2);
45
+ const isOwnedRpcChild = capsule && (process.ppid === 1 || basename(capsule).startsWith(`child-${process.ppid}-`))
46
+ && mode >= 2 && process.argv[mode + 1] === "rpc" && process.argv.includes("--larva-persona", 2);
47
+ if (process.env.LARVA_PI_LAUNCHED === "1" && isOwnedRpcChild) {
48
+ process.stdin.once("close", () => {
49
+ setTimeout(() => {
50
+ if (process.ppid === 1) removeChildCapsuleRoot(process.env);
51
+ process.exit(143);
52
+ }, ABORT_GRACE_MS).unref();
53
+ });
54
+ // A living parent owns capsule removal on normal exit.
55
+ process.once("exit", () => {
56
+ if (process.ppid === 1) removeChildCapsuleRoot(process.env);
57
+ });
58
+ }
8
59
 
9
60
  const bridge = {
10
61
  version: 1,
@@ -17,6 +68,7 @@ if (globalThis[BRIDGE_SYMBOL] === undefined) {
17
68
  isConfigured() {
18
69
  return transformRecord !== null;
19
70
  },
71
+ emit,
20
72
  };
21
73
  Object.defineProperty(globalThis, BRIDGE_SYMBOL, { value: bridge, configurable: false, enumerable: false, writable: false });
22
74
 
@@ -33,14 +85,6 @@ if (globalThis[BRIDGE_SYMBOL] === undefined) {
33
85
  }
34
86
  const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString(encoding);
35
87
  if (!text.endsWith("\n")) return writeNative(text);
36
- const records = text.slice(0, -1).split("\n");
37
- const transformed = records.map((record) => {
38
- const outbound = transformRecord(record);
39
- if (typeof outbound !== "string") throw new TypeError("Larva child RPC preload transform returned a non-string record.");
40
- const bytes = Buffer.byteLength(outbound, "utf8");
41
- if (bytes > MAX_RECORD_BYTES) throw new RangeError(`Larva child RPC preload emitted ${bytes} bytes (limit ${MAX_RECORD_BYTES}).`);
42
- return outbound;
43
- }).join("\n") + "\n";
44
- return writeNative(transformed);
88
+ return writeNative(encode(text.slice(0, -1).split("\n").flatMap(transformRecord)));
45
89
  });
46
90
  }