pi-better-server 0.7.2 → 0.8.0

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.
Files changed (47) hide show
  1. package/package.json +1 -1
  2. package/src/runtime/background-tools.ts +146 -6
  3. package/src/runtime/background.ts +2 -2
  4. package/src/runtime/catalog.ts +30 -1
  5. package/src/runtime/ci-recovery.ts +172 -0
  6. package/src/runtime/domain/assignment-inbox.mjs +4 -0
  7. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  8. package/src/runtime/domain/assignment-observation.mjs +1 -0
  9. package/src/runtime/domain/background-service/ci-observation.domain.mjs +134 -0
  10. package/src/runtime/domain/background-service/ci-observation.ts +118 -0
  11. package/src/runtime/domain/background-service/managed-client.domain.mjs +6 -2
  12. package/src/runtime/domain/background-service/managed-client.ts +6 -2
  13. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +47 -7
  14. package/src/runtime/domain/background-service/managed-frontend.ts +36 -6
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +26 -0
  16. package/src/runtime/domain/background-service/observed-waits.ts +24 -0
  17. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  18. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +1 -0
  19. package/src/runtime/domain/catalog/catalog-schema.d.mts +6 -0
  20. package/src/runtime/domain/catalog/catalog-schema.mjs +1 -0
  21. package/src/runtime/domain/catalog/roles/role.supervisor.md +16 -0
  22. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1 -0
  23. package/src/runtime/domain/subagents/catalog-schema.ts +1 -0
  24. package/src/runtime/domain/subagents/index.domain.mjs +6 -2
  25. package/src/runtime/domain/subagents/index.ts +7 -2
  26. package/src/runtime/domain/subagents/output-payload.domain.mjs +3 -1
  27. package/src/runtime/domain/subagents/output-payload.ts +2 -0
  28. package/src/runtime/domain/subagents/package.json +1 -1
  29. package/src/runtime/domain/subagents/roles/role.supervisor.md +16 -0
  30. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +14 -2
  31. package/src/runtime/domain/subagents/shared-catalog.ts +14 -2
  32. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  33. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
  34. package/src/runtime/domain/subagents/supervisor-client.mjs +36 -0
  35. package/src/runtime/domain/subagents/tools.domain.mjs +3 -2
  36. package/src/runtime/domain/subagents/tools.ts +3 -2
  37. package/src/runtime/domain/subagents/workflow-assignment.domain.mjs +25 -0
  38. package/src/runtime/domain/subagents/workflow-assignment.ts +35 -0
  39. package/src/runtime/queries.ts +17 -3
  40. package/src/runtime/query-executor.ts +57 -5
  41. package/src/runtime/query-worker.mjs +6 -1
  42. package/src/runtime/read-model.ts +14 -5
  43. package/src/runtime/shared-read-diagnosis.ts +29 -0
  44. package/src/runtime/supervisor-admission.ts +42 -0
  45. package/src/runtime/supervisor-decisions.ts +60 -0
  46. package/src/server.ts +3 -3
  47. package/src/version.ts +1 -1
@@ -102,6 +102,7 @@ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConn
102
102
  this.revision(); return db; },
103
103
  changes() { this.revision(); return inbox.receive(db, identity); },
104
104
  acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
105
+ get hasPendingChanges() { return inbox.hasPendingChanges; },
105
106
  get changeMetrics() { return inbox.metrics; },
106
107
  get snapshotActive() { return snapshot; },
107
108
  beginSnapshot() {
@@ -74,6 +74,12 @@ export declare const APPROVED_ROLE_DEFAULTS: readonly [{
74
74
  readonly model: "openai/gpt-6-astra";
75
75
  readonly effort: "high";
76
76
  readonly tier: "frontier";
77
+ }, {
78
+ readonly id: "role.supervisor";
79
+ readonly name: "Supervisor";
80
+ readonly model: "openai/gpt-6.1-sol";
81
+ readonly effort: "medium";
82
+ readonly tier: "balanced";
77
83
  }, {
78
84
  readonly id: "role.writer";
79
85
  readonly name: "Writer";
@@ -71,6 +71,7 @@ export const APPROVED_ROLE_DEFAULTS = [
71
71
  { id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
72
72
  { id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
73
73
  { id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
74
+ { id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
74
75
  { id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
75
76
  ];
76
77
  export const DiagnosticCodes = {
@@ -0,0 +1,16 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.supervisor
5
+ name: Supervisor
6
+ description: Diagnoses blocked or stalled Outcomes and reviews scope drift using evidence supplied for the affected owner.
7
+ defaults:
8
+ model: openai/gpt-6.1-sol
9
+ effort: medium
10
+ tier: balanced
11
+ ---
12
+ Start from the current Outcome, acceptance criteria and evidence supplied for this owner. Cite the observations that support your diagnosis. If one fact would distinguish plausible causes, request the smallest authorized read-only check.
13
+
14
+ For a blocker, propose a recovery action, its prerequisites and a check of the original operation. If a CI watcher exits while its remote run is active, suggest resuming observation by the original run ID. For a stall, identify the last change to an acceptance criterion and test why progress stopped. For scope drift, identify necessary investigations and which planned steps the owner can prune.
15
+
16
+ Return the next action and its expected observable result to the execution owner. Consult prior interventions and approvals when supplied. Repeat a recommendation only when the evidence changes what the owner needs to do. Do not restart builds, wake sessions, grant approvals, or change an Outcome. The daemon controls delivery and the execution owner controls recovery.
@@ -71,6 +71,7 @@ export const APPROVED_ROLE_DEFAULTS = [
71
71
  { id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
72
72
  { id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
73
73
  { id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
74
+ { id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
74
75
  { id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
75
76
  ];
76
77
  export const DiagnosticCodes = {
@@ -85,6 +85,7 @@ export const APPROVED_ROLE_DEFAULTS = [
85
85
  { id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
86
86
  { id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
87
87
  { id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
88
+ { id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
88
89
  { id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
89
90
  ] as const;
90
91
 
@@ -47,6 +47,7 @@ import { deliverSubagentPrompt, effectiveSubagentSettings, subagentSettingsTool
47
47
  import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.domain.mjs";
48
48
  import { continuationTimingParams, configuredMaxMinutes, decideTiming, describeTiming, DEFAULT_TIMING_MINUTES, emptyProgress, foldProgress, formatTimingLimits, isTimingMinutes, isProgressRelevantLine, resolveRunTiming, steerText, stuckAlertText, TIMING_ENV, timingParameterSchemas, toolWaitAlertText, validatedTimingMinutes, } from "./timing.domain.mjs";
49
49
  import { readAppendedLines } from "./log-cursor.domain.mjs";
50
+ import { launchWorkflowAssignment } from "./workflow-assignment.domain.mjs";
50
51
  import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode } from "./delegation.domain.mjs";
51
52
  import { resolveExtensions, extensionArgs } from "./extensions.domain.mjs";
52
53
  import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.domain.mjs";
@@ -2786,13 +2787,13 @@ export default function (pi, managed) {
2786
2787
  ctx = captureLaunchContext(ctx);
2787
2788
  restoreDelegationMode(ctx);
2788
2789
  await workerOperations.start();
2789
- return definition.execute(key, params, signal, onUpdate, ctx);
2790
+ return launchWorkflowAssignment(pi, ctx, key, params, args => definition.execute(key, args, signal, onUpdate, ctx));
2790
2791
  } } : { ...definition, async execute(key, params, signal, _onUpdate, ctx) {
2791
2792
  ctx = captureLaunchContext(ctx);
2792
2793
  catalogHostFrom(ctx);
2793
2794
  const { submitManagedLaunch } = await import("./managed-launch-client.domain.mjs");
2794
2795
  void activateWorkObservation();
2795
- return await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, params, signal));
2796
+ return launchWorkflowAssignment(pi, ctx, key, params, async (args) => await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, args, signal)));
2796
2797
  } });
2797
2798
  };
2798
2799
  announceExecutionAdapter(pi, {
@@ -3947,6 +3948,9 @@ export default function (pi, managed) {
3947
3948
  ],
3948
3949
  parameters: Type.Object({
3949
3950
  prompt: Type.String({ description: "The task for the subagent. This is the only context it gets — be self-contained. On a continuation this is the next user turn; the original task and role stay in saved history." }),
3951
+ workflow: Type.Optional(Type.Object({
3952
+ runId: Type.String(), step: Type.String(),
3953
+ }, { description: "Bind this launch to a ready dynamic workflow item. Supply its selected role or agent and inherit catalog skills." })),
3950
3954
  session_name: Type.Optional(Type.String({ description: "Exact name of one saved conversation in the current folder and descendants. Alternative to session_id. Duplicate names report matching session ids instead of choosing a conversation." })),
3951
3955
  session_id: Type.Optional(Type.String({ description: "Native session id of a saved conversation to continue (reported for every launch and attempt). Omit to start a new conversation. A continuation gets a new run id but keeps this session id, history, workspace, and frozen launch recipe." })),
3952
3956
  name: Type.Optional(Type.String({ description: "Short label for the run (e.g. 'reviewer'). Ignored when agent or role is set, except as the direct-role alias when alias is omitted." })),
@@ -82,6 +82,7 @@ import {
82
82
  type TimingStopReason,
83
83
  } from "./timing.ts";
84
84
  import { readAppendedLines, type LogCursor } from "./log-cursor.ts";
85
+ import { launchWorkflowAssignment } from "./workflow-assignment.ts";
85
86
  import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode, type DelegationMode } from "./delegation.ts";
86
87
  import { resolveExtensions, extensionArgs } from "./extensions.ts";
87
88
  import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
@@ -2804,13 +2805,14 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
2804
2805
  ctx = captureLaunchContext(ctx);
2805
2806
  restoreDelegationMode(ctx);
2806
2807
  await workerOperations.start();
2807
- return definition.execute(key, params, signal, onUpdate, ctx);
2808
+ return launchWorkflowAssignment(pi, ctx, key, params, args => definition.execute(key, args, signal, onUpdate, ctx));
2808
2809
  } } : { ...definition, async execute(key, params, signal, _onUpdate, ctx) {
2809
2810
  ctx = captureLaunchContext(ctx);
2810
2811
  catalogHostFrom(ctx);
2811
2812
  const { submitManagedLaunch } = await import("./managed-launch-client.ts");
2812
2813
  void activateWorkObservation();
2813
- return await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, params, signal)) as never;
2814
+ return launchWorkflowAssignment(pi, ctx, key, params, async args =>
2815
+ await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, args, signal)) as never);
2814
2816
  } });
2815
2817
  };
2816
2818
  announceExecutionAdapter(pi, {
@@ -4020,6 +4022,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
4020
4022
  ],
4021
4023
  parameters: Type.Object({
4022
4024
  prompt: Type.String({ description: "The task for the subagent. This is the only context it gets — be self-contained. On a continuation this is the next user turn; the original task and role stay in saved history." }),
4025
+ workflow: Type.Optional(Type.Object({
4026
+ runId: Type.String(), step: Type.String(),
4027
+ }, { description: "Bind this launch to a ready dynamic workflow item. Supply its selected role or agent and inherit catalog skills." })),
4023
4028
  session_name: Type.Optional(Type.String({ description: "Exact name of one saved conversation in the current folder and descendants. Alternative to session_id. Duplicate names report matching session ids instead of choosing a conversation." })),
4024
4029
  session_id: Type.Optional(Type.String({ description: "Native session id of a saved conversation to continue (reported for every launch and attempt). Omit to start a new conversation. A continuation gets a new run id but keeps this session id, history, workspace, and frozen launch recipe." })),
4025
4030
  name: Type.Optional(Type.String({ description: "Short label for the run (e.g. 'reviewer'). Ignored when agent or role is set, except as the direct-role alias when alias is omitted." })),
@@ -521,7 +521,7 @@ export function assembleOrphanedResult(id, meta, healthLine, request = {}, scope
521
521
  statusCursor: ctx.statusCursor,
522
522
  });
523
523
  }
524
- export function assembleSubagentResult(id, meta, request = {}, healthLine = "", scopeKey = defaultScope()) {
524
+ export function assembleSubagentResult(id, meta, request = {}, healthLine = "", scopeKey = defaultScope(), observed) {
525
525
  healthLine = [healthLine, projectionDiagnostic(meta)].filter(Boolean).join("\n");
526
526
  const st = effectiveStatus(meta);
527
527
  if (isRawMode(request.mode) || cursorKind(request.cursor) === "f")
@@ -601,6 +601,8 @@ export function assembleSubagentResult(id, meta, request = {}, healthLine = "",
601
601
  }
602
602
  const exceptional = isRoutineComplete(lifecycle) ? undefined : formatLifecycleDiagnostics(lifecycle);
603
603
  const answer = run.finalText || "";
604
+ if (observed)
605
+ observed.hasFinalAnswer = Boolean(answer.trim());
604
606
  const fallback = !answer
605
607
  ? (run.lastActivity
606
608
  ? `(no final answer parsed; latest activity)\n${run.lastActivity}`
@@ -702,6 +702,7 @@ export function assembleSubagentResult(
702
702
  request: PayloadRequest = {},
703
703
  healthLine = "",
704
704
  scopeKey = defaultScope(),
705
+ observed?: { hasFinalAnswer?: boolean },
705
706
  ): string {
706
707
  healthLine = [healthLine, projectionDiagnostic(meta)].filter(Boolean).join("\n");
707
708
  const st = effectiveStatus(meta);
@@ -782,6 +783,7 @@ export function assembleSubagentResult(
782
783
 
783
784
  const exceptional = isRoutineComplete(lifecycle) ? undefined : formatLifecycleDiagnostics(lifecycle);
784
785
  const answer = run.finalText || "";
786
+ if (observed) observed.hasFinalAnswer = Boolean(answer.trim());
785
787
  const fallback = !answer
786
788
  ? (run.lastActivity
787
789
  ? `(no final answer parsed; latest activity)\n${run.lastActivity}`
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.37.2",
3
+ "version": "0.39.0",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,16 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.supervisor
5
+ name: Supervisor
6
+ description: Diagnoses blocked or stalled Outcomes and reviews scope drift using evidence supplied for the affected owner.
7
+ defaults:
8
+ model: openai/gpt-6.1-sol
9
+ effort: medium
10
+ tier: balanced
11
+ ---
12
+ Start from the current Outcome, acceptance criteria and evidence supplied for this owner. Cite the observations that support your diagnosis. If one fact would distinguish plausible causes, request the smallest authorized read-only check.
13
+
14
+ For a blocker, propose a recovery action, its prerequisites and a check of the original operation. If a CI watcher exits while its remote run is active, suggest resuming observation by the original run ID. For a stall, identify the last change to an acceptance criterion and test why progress stopped. For scope drift, identify necessary investigations and which planned steps the owner can prune.
15
+
16
+ Return the next action and its expected observable result to the execution owner. Consult prior interventions and approvals when supplied. Repeat a recommendation only when the evidence changes what the owner needs to do. Do not restart builds, wake sessions, grant approvals, or change an Outcome. The daemon controls delivery and the execution owner controls recovery.
@@ -5,7 +5,7 @@ import { connectWorkClient } from "./shared-work-client.mjs";
5
5
  import { catalogSnapshotFromWire, defaultUserRoot } from "./catalog-store.domain.mjs";
6
6
  import { catalogHostAuthority } from "./catalog-host-admission.domain.mjs";
7
7
  /** Short-lived catalog connection. No transcript or permission authority travels here. */
8
- export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess, signal) {
8
+ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess, signal, hostAuthority = catalogHostAuthority) {
9
9
  signal?.throwIfAborted();
10
10
  const agentDir = realpathSync(userRoot);
11
11
  let registration;
@@ -22,7 +22,7 @@ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessi
22
22
  throw new Error("Invalid canonical runtime registration");
23
23
  const client = await connectCatalogClient(agentDir, registration.serverDir, undefined, signal);
24
24
  const register = async (setupSignal) => {
25
- const authority = await catalogHostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
25
+ const authority = await hostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
26
26
  setupSignal?.throwIfAborted();
27
27
  await client.request("runtime_register_catalog", { cwd, sessionId: authority?.sessionId ?? sessionId, authority, projectAccess: projectAccess === false ? "deny" : undefined });
28
28
  };
@@ -39,6 +39,18 @@ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessi
39
39
  const wire = await client.request("runtime_get_catalog", { overlay });
40
40
  return catalogSnapshotFromWire(wire);
41
41
  },
42
+ async decision(action, scope, token, answer) {
43
+ await register();
44
+ return client.request("runtime_supervisor_review", { action, scope, token, answer });
45
+ },
46
+ async sharedReadDiagnosis(verifiedIncident) {
47
+ await register();
48
+ return client.request("runtime_supervisor_review", { action: "read-health", verifiedIncident });
49
+ },
50
+ async review(scenario, action, token) {
51
+ await register();
52
+ return client.request("runtime_supervisor_review", { scenario, action, token });
53
+ },
42
54
  async edit(edit) { await register(); return client.request("runtime_edit_catalog", edit); },
43
55
  async scopedAgents(scope) { await register(); return client.request("runtime_get_catalog_scope", { scope }); },
44
56
  async subscribe(changed) {
@@ -6,7 +6,7 @@ import type { AgentSessionOverrides } from "./agent-session-settings.ts";
6
6
  import { catalogHostAuthority } from "./catalog-host-admission.ts";
7
7
 
8
8
  /** Short-lived catalog connection. No transcript or permission authority travels here. */
9
- export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess?: boolean, signal?: AbortSignal) {
9
+ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess?: boolean, signal?: AbortSignal, hostAuthority = catalogHostAuthority) {
10
10
  signal?.throwIfAborted();
11
11
  const agentDir = realpathSync(userRoot);
12
12
  let registration;
@@ -19,7 +19,7 @@ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(
19
19
  if (registration.version !== 1 || registration.agentDir !== agentDir) throw new Error("Invalid canonical runtime registration");
20
20
  const client = await connectCatalogClient(agentDir, registration.serverDir, undefined, signal);
21
21
  const register = async (setupSignal?: AbortSignal) => {
22
- const authority = await catalogHostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
22
+ const authority = await hostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
23
23
  setupSignal?.throwIfAborted();
24
24
  await client.request("runtime_register_catalog", { cwd, sessionId: authority?.sessionId ?? sessionId, authority, projectAccess: projectAccess === false ? "deny" : undefined });
25
25
  };
@@ -32,6 +32,18 @@ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(
32
32
  const wire = await client.request("runtime_get_catalog", { overlay });
33
33
  return catalogSnapshotFromWire(wire);
34
34
  },
35
+ async decision(action: string, scope: Record<string, string>, token?: string, answer?: string) {
36
+ await register();
37
+ return client.request("runtime_supervisor_review", { action, scope, token, answer });
38
+ },
39
+ async sharedReadDiagnosis(verifiedIncident?: string): Promise<{ status: string; incident?: { id: string; recommendation: string } }> {
40
+ await register();
41
+ return client.request("runtime_supervisor_review", { action: "read-health", verifiedIncident });
42
+ },
43
+ async review(scenario: string, action: "begin" | "finish" | "release", token?: string): Promise<{ status: string; token?: string }> {
44
+ await register();
45
+ return client.request("runtime_supervisor_review", { scenario, action, token });
46
+ },
35
47
  async edit(edit: Record<string, unknown>) { await register(); return client.request("runtime_edit_catalog", edit); },
36
48
  async scopedAgents(scope: "user" | "project") { await register(); return client.request("runtime_get_catalog_scope", { scope }); },
37
49
  async subscribe(changed: (snapshot: CatalogSnapshot | undefined) => void) {
@@ -129,6 +129,9 @@ export class AssignmentInbox {
129
129
  throw error;
130
130
  }
131
131
  }
132
+ get hasPendingChanges() {
133
+ return Boolean(this.more || this.db.prepare(`SELECT 1 FROM ${this.prefix}pending LIMIT 1`).get());
134
+ }
132
135
  get metrics() {
133
136
  const pending = this.db.prepare(`SELECT count(*) AS pending, min(since) AS oldestPendingAt FROM ${this.prefix}pending`).get();
134
137
  return { ...this.db.prepare(`SELECT * FROM ${this.prefix}position`).get(),
@@ -102,6 +102,7 @@ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConn
102
102
  this.revision(); return db; },
103
103
  changes() { this.revision(); return inbox.receive(db, identity); },
104
104
  acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
105
+ get hasPendingChanges() { return inbox.hasPendingChanges; },
105
106
  get changeMetrics() { return inbox.metrics; },
106
107
  get snapshotActive() { return snapshot; },
107
108
  beginSnapshot() {
@@ -0,0 +1,36 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/supervisor-client.mjs. Do not edit directly.
2
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { createCatalogHostAdapter } from "./catalog-host-admission.domain.mjs";
4
+ import { createAgentSessionSettings } from "./agent-session-settings.domain.mjs";
5
+ import { openSharedCatalog } from "./shared-catalog.domain.mjs";
6
+ import { resolveSelection } from "./catalog-resolver.domain.mjs";
7
+ export async function openSupervisorClient(pi, ctx, signal) {
8
+ const settings = createAgentSessionSettings(pi);
9
+ settings.restore(ctx);
10
+ // Pi loads extensions independently. Bind this request to its own live host context.
11
+ const host = createCatalogHostAdapter();
12
+ host.noteCatalogHostContext(ctx, () => settings.snapshot());
13
+ let catalog;
14
+ try {
15
+ catalog = await openSharedCatalog(ctx.cwd, getAgentDir(), ctx.sessionManager.getSessionId(), undefined, signal, host.catalogHostAuthority);
16
+ }
17
+ catch (error) {
18
+ host.closeCatalogHost();
19
+ throw error;
20
+ }
21
+ return {
22
+ close() { catalog.close(); host.closeCatalogHost(); },
23
+ review: catalog.review,
24
+ decision: catalog.decision,
25
+ sharedReadDiagnosis: catalog.sharedReadDiagnosis,
26
+ async role() {
27
+ settings.restore(ctx);
28
+ const snapshot = await catalog.get(settings.snapshot());
29
+ const selected = resolveSelection(snapshot, { roleId: "role.supervisor" });
30
+ if (!selected.launchable || !selected.effective)
31
+ return;
32
+ const { instructions, model, effort } = selected.effective;
33
+ return { revision: snapshot.revision, instructions, model: model.value, effort: effort.value };
34
+ },
35
+ };
36
+ }
@@ -475,12 +475,13 @@ export function subagentResultTool(Type, baseSession = {}) {
475
475
  verified: true, waits: inspected.dependencies ?? [], ...{ outcome: inspected.outcome },
476
476
  }) : observed?.assignment;
477
477
  return withAssignmentObservations(assignment ? [{ meta, assignment }] : [], () => {
478
+ const observedAnswer = {};
478
479
  const resultText = (body) => {
479
480
  const evidence = outcome;
480
481
  const operations = evidence?.dependencies?.flatMap((wait) => wait.dependencies.map((dependency) => dependency.operationId)).slice(0, 5) ?? [];
481
482
  const header = evidence?.outcome ? `Outcome r${evidence.outcome.revision}: ${evidence.outcome.outcome}. ${evidence.outcome.reason.slice(0, 256)}${operations.length ? `\nEvidence operations: ${operations.join(", ")}` : ""}\n` : "";
482
483
  const result = subagentResultText(header + body);
483
- return { ...result, details: { ...result.details, outcome, outcomeSupport: meta.outcomeSupport, assignment: assignment ?? assignmentFor(meta, effectiveStatus(meta)), snapshot: observed?.snapshot, ...permissionDetails(p.id, budgetFor("answer", p.maxBytes)) } };
484
+ return { ...result, details: { ...result.details, ...observedAnswer, outcome, outcomeSupport: meta.outcomeSupport, assignment: assignment ?? assignmentFor(meta, effectiveStatus(meta)), snapshot: observed?.snapshot, ...permissionDetails(p.id, budgetFor("answer", p.maxBytes)) } };
484
485
  };
485
486
  if (params.operation_id && outcome) {
486
487
  const evidence = outcome;
@@ -497,7 +498,7 @@ export function subagentResultTool(Type, baseSession = {}) {
497
498
  }
498
499
  return resultText(assembleRunningResult(p.id, meta, p, scopeKey, healthLine));
499
500
  }
500
- return resultText(assembleSubagentResult(p.id, meta, p, healthLine, scopeKey));
501
+ return resultText(assembleSubagentResult(p.id, meta, p, healthLine, scopeKey, observedAnswer));
501
502
  });
502
503
  },
503
504
  };
@@ -542,12 +542,13 @@ export function subagentResultTool(Type: TypeModule, baseSession: SubagentToolSe
542
542
  verified: true, waits: inspected.dependencies ?? [], ...{ outcome: inspected.outcome },
543
543
  }) : observed?.assignment;
544
544
  return withAssignmentObservations(assignment ? [{ meta, assignment }] : [], () => {
545
+ const observedAnswer: { hasFinalAnswer?: boolean } = {};
545
546
  const resultText = (body: string) => {
546
547
  const evidence = outcome as { outcome?: { revision: number; outcome: string; reason: string }; dependencies?: Array<{ dependencies: Array<{ operationId: string }> }> } | null;
547
548
  const operations = evidence?.dependencies?.flatMap((wait) => wait.dependencies.map((dependency) => dependency.operationId)).slice(0, 5) ?? [];
548
549
  const header = evidence?.outcome ? `Outcome r${evidence.outcome.revision}: ${evidence.outcome.outcome}. ${evidence.outcome.reason.slice(0, 256)}${operations.length ? `\nEvidence operations: ${operations.join(", ")}` : ""}\n` : "";
549
550
  const result = subagentResultText(header + body);
550
- return { ...result, details: { ...result.details, outcome, outcomeSupport: meta.outcomeSupport, assignment: assignment ?? assignmentFor(meta, effectiveStatus(meta)), snapshot: observed?.snapshot, ...permissionDetails(p.id, budgetFor("answer", p.maxBytes)) } };
551
+ return { ...result, details: { ...result.details, ...observedAnswer, outcome, outcomeSupport: meta.outcomeSupport, assignment: assignment ?? assignmentFor(meta, effectiveStatus(meta)), snapshot: observed?.snapshot, ...permissionDetails(p.id, budgetFor("answer", p.maxBytes)) } };
551
552
  };
552
553
  if ((params as Record<string, unknown>).operation_id && outcome) {
553
554
  const evidence = outcome as { outcome: { revision: number; outcome: string; reason: string }; logs: Array<{ text: string }> };
@@ -564,7 +565,7 @@ export function subagentResultTool(Type: TypeModule, baseSession: SubagentToolSe
564
565
  }
565
566
  return resultText(assembleRunningResult(p.id, meta, p, scopeKey, healthLine));
566
567
  }
567
- return resultText(assembleSubagentResult(p.id, meta, p, healthLine, scopeKey));
568
+ return resultText(assembleSubagentResult(p.id, meta, p, healthLine, scopeKey, observedAnswer));
568
569
  });
569
570
  },
570
571
  } as ToolDefinition;
@@ -0,0 +1,25 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/workflow-assignment.ts. Do not edit directly.
2
+ export const WORKFLOW_ASSIGNMENT = "pi-better-subagents:workflow-assignment";
3
+ /** Wrap only explicitly workflow-bound launches. The normal spawn path owns all execution permissions. */
4
+ export async function launchWorkflowAssignment(pi, ctx, callId, params, launch) {
5
+ const input = params;
6
+ if (!input.workflow)
7
+ return launch(params);
8
+ const request = { ref: input.workflow, callId, ctx, input };
9
+ pi.events.emit(WORKFLOW_ASSIGNMENT, request);
10
+ if (!request.admission)
11
+ throw new Error(request.error ?? "No active workflow authorized this assignment.");
12
+ const { workflow: _workflow, ...args } = input;
13
+ let result;
14
+ try {
15
+ result = await launch({ ...args, prompt: request.admission.prompt });
16
+ }
17
+ catch (error) {
18
+ request.admission.settled({ error: error instanceof Error ? error.message : String(error) });
19
+ throw error;
20
+ }
21
+ const receipt = result.details;
22
+ request.admission.settled(receipt?.launched && receipt.runId ? { runId: receipt.runId }
23
+ : { error: result.content.find(part => part.type === "text")?.text || "Assignment did not launch." });
24
+ return result;
25
+ }
@@ -0,0 +1,35 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export const WORKFLOW_ASSIGNMENT = "pi-better-subagents:workflow-assignment";
4
+ export interface WorkflowAssignmentRequest {
5
+ ref: { runId: string; step: string };
6
+ callId: string;
7
+ ctx: ExtensionContext;
8
+ input: Record<string, unknown>;
9
+ /** The workflow owner claims the ready item synchronously before launch. */
10
+ admission?: { prompt: string; settled(outcome: { runId?: string; error?: string }): void };
11
+ error?: string;
12
+ }
13
+
14
+ /** Wrap only explicitly workflow-bound launches. The normal spawn path owns all execution permissions. */
15
+ export async function launchWorkflowAssignment<P, R extends { details?: unknown; content: readonly { type: string; text?: string }[] }>(
16
+ pi: ExtensionAPI, ctx: ExtensionContext, callId: string, params: P, launch: (params: P) => Promise<R>,
17
+ ): Promise<R> {
18
+ const input = params as Record<string, unknown>;
19
+ if (!input.workflow) return launch(params);
20
+ const request: WorkflowAssignmentRequest = { ref: input.workflow as WorkflowAssignmentRequest["ref"], callId, ctx, input };
21
+ pi.events.emit(WORKFLOW_ASSIGNMENT, request);
22
+ if (!request.admission) throw new Error(request.error ?? "No active workflow authorized this assignment.");
23
+ const { workflow: _workflow, ...args } = input;
24
+ let result: R;
25
+ try {
26
+ result = await launch({ ...args, prompt: request.admission.prompt } as P);
27
+ } catch (error) {
28
+ request.admission.settled({ error: error instanceof Error ? error.message : String(error) });
29
+ throw error;
30
+ }
31
+ const receipt = result.details as { launched?: boolean; runId?: string } | undefined;
32
+ request.admission.settled(receipt?.launched && receipt.runId ? { runId: receipt.runId }
33
+ : { error: result.content.find(part => part.type === "text")?.text || "Assignment did not launch." });
34
+ return result;
35
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Socket } from "node:net";
2
- import type { WorkReadModel, WorkScope } from "./read-model.ts";
2
+ import type { WorkReadModel, WorkScope, WorkSnapshot } from "./read-model.ts";
3
3
 
4
4
  const eventEncodings = new WeakMap<object, string>();
5
5
  const snapshotEncodings = new WeakMap<object, string>();
@@ -8,6 +8,10 @@ export function snapshotJSON(snapshot: object): string {
8
8
  if (json === undefined) { json = JSON.stringify(snapshot); snapshotEncodings.set(snapshot, json); }
9
9
  return json;
10
10
  }
11
+ // The global sequence may advance while a session's Background rows and deadlines stay unchanged.
12
+ function backgroundNotificationKey(snapshot: WorkSnapshot) {
13
+ return JSON.stringify([snapshot.scopeRevision, snapshot.status, snapshot.reason, snapshot.nextDeadline]);
14
+ }
11
15
  export const queryEncodingMetrics = { serializations: 0, frames: 0, bytes: 0 };
12
16
 
13
17
  export function workScope(input: unknown): WorkScope {
@@ -35,6 +39,7 @@ export class WorkQueries {
35
39
  private dispose?: () => void;
36
40
  private paused = false;
37
41
  private lastSnapshotSeq?: number;
42
+ private lastBackgroundKey?: string;
38
43
  private model: WorkReadModel;
39
44
  private socket: Socket;
40
45
  private maxQueuedBytes: number;
@@ -51,8 +56,10 @@ export class WorkQueries {
51
56
  }
52
57
  private event(event: unknown) {
53
58
  if (this.socket.destroyed || this.paused) return;
54
- if (this.socket.writableLength > this.maxQueuedBytes) { this.paused = true; return; }
55
59
  const snapshot = (event as any)?.type === "runtime_snapshot" ? (event as any).snapshot : undefined;
60
+ const key = snapshot && this.lastBackgroundKey !== undefined ? backgroundNotificationKey(snapshot) : undefined;
61
+ if (key !== undefined && key === this.lastBackgroundKey) return;
62
+ if (this.socket.writableLength > this.maxQueuedBytes) { this.paused = true; return; }
56
63
  let line: string;
57
64
  if (snapshot) {
58
65
  let prefix = eventEncodings.get(snapshot);
@@ -68,7 +75,10 @@ export class WorkQueries {
68
75
  this.socket.write(JSON.stringify({ type: "event", event: { type: "resync_required", reason: "snapshot-too-large: narrow the scope or limit" } }) + "\n");
69
76
  return;
70
77
  }
71
- if (snapshot) this.lastSnapshotSeq = snapshot.seq;
78
+ if (snapshot) {
79
+ this.lastSnapshotSeq = snapshot.seq;
80
+ this.lastBackgroundKey = key;
81
+ }
72
82
  this.socket.write(line);
73
83
  queryEncodingMetrics.frames++; queryEncodingMetrics.bytes += Buffer.byteLength(line);
74
84
  }
@@ -76,11 +86,15 @@ export class WorkQueries {
76
86
  if (command.type === "runtime_unsubscribe") { this.close(); return { unsubscribed: true }; }
77
87
  if (command.type === "runtime_get_metrics") return { ...this.model.metrics };
78
88
  const scope = workScope(command.scope);
89
+ // An explicit read must see new commits. Publication callbacks already observe
90
+ // the reconciled state and must not poll the inbox again for every subscriber.
91
+ if (scope.background && !scope.backgroundHistory) this.model.prepareBackgroundQuery();
79
92
  const snapshot = this.model.snapshot(scope);
80
93
  if (Buffer.byteLength(snapshotJSON(snapshot)) > 4 * 1024 * 1024 - 1024) throw new Error("state-degraded: snapshot exceeds the 4 MiB frame allowance; narrow the scope or limit");
81
94
  if (command.type === "runtime_subscribe") {
82
95
  this.close();
83
96
  this.lastSnapshotSeq = snapshot.seq;
97
+ this.lastBackgroundKey = scope.background && !scope.backgroundHistory ? backgroundNotificationKey(snapshot) : undefined;
84
98
  this.dispose = this.model.onChange(() => {
85
99
  try {
86
100
  this.event({ type: "runtime_snapshot", snapshot: this.model.snapshot({ ...scope, cursor: undefined }) });