@a-t-h-i/bot-lobby 0.6.61 → 0.6.62

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 (100) hide show
  1. package/README.md +3 -7
  2. package/package.json +2 -1
  3. package/prompts/designer.md +25 -15
  4. package/prompts/master.md +284 -491
  5. package/prompts/panel.md +7 -0
  6. package/prompts/planner.md +15 -4
  7. package/prompts/qa.md +5 -1
  8. package/prompts/worker.md +0 -7
  9. package/scripts/builtin/affected_packages.mjs +106 -0
  10. package/scripts/builtin/check_changed.mjs +51 -0
  11. package/scripts/builtin/check_contract_breakage.mjs +118 -0
  12. package/scripts/builtin/circular_dependency_check.mjs +79 -0
  13. package/scripts/builtin/code_duplication_check.mjs +86 -0
  14. package/scripts/builtin/diff_summary.mjs +62 -0
  15. package/scripts/builtin/failure_digest.mjs +107 -0
  16. package/scripts/builtin/find_generated_files.mjs +79 -0
  17. package/scripts/builtin/find_symbol.mjs +81 -0
  18. package/scripts/builtin/find_test_fixtures.mjs +73 -0
  19. package/scripts/builtin/find_tests_for.mjs +12 -0
  20. package/scripts/builtin/lib/common.mjs +267 -0
  21. package/scripts/builtin/outline_file.mjs +77 -0
  22. package/scripts/builtin/project_commands.mjs +49 -0
  23. package/scripts/builtin/recent_changes.mjs +14 -0
  24. package/scripts/builtin/repo_map.mjs +65 -0
  25. package/scripts/builtin/run_changed_tests.mjs +48 -0
  26. package/src/delivery/transport.ts +1 -1
  27. package/src/desk/client-extension.ts +1 -31
  28. package/src/desk/ipc.ts +1 -11
  29. package/src/desk/session.ts +4 -101
  30. package/src/execution/agent-runner.ts +50 -8
  31. package/src/execution/assigned-session.ts +263 -0
  32. package/src/execution/assignment-discovery.ts +128 -0
  33. package/src/execution/assignment-policy.ts +46 -0
  34. package/src/execution/assignment.ts +175 -0
  35. package/src/execution/delegation.ts +9 -94
  36. package/src/execution/pi-runner.ts +99 -9
  37. package/src/harness/instructions.ts +1 -1
  38. package/src/index.ts +3 -0
  39. package/src/knowledge/design-record.ts +394 -0
  40. package/src/knowledge/file-notes.ts +36 -8
  41. package/src/lobby/ask.ts +6 -0
  42. package/src/lobby/exec.ts +28 -0
  43. package/src/lobby/host.ts +1 -11
  44. package/src/lobby/planner.ts +50 -124
  45. package/src/lobby/prompts.ts +1 -7
  46. package/src/lobby/runtime.ts +2 -26
  47. package/src/lobby/service.ts +25 -23
  48. package/src/lobby/topics.ts +0 -2
  49. package/src/master/evidence-freshness.ts +96 -0
  50. package/src/master/master.ts +248 -74
  51. package/src/master/scout-cache.ts +1 -1
  52. package/src/master/scout-lock.ts +44 -0
  53. package/src/master/scout-prefetch.ts +78 -0
  54. package/src/pi/activity.ts +2 -0
  55. package/src/pi/assignment-guard.ts +157 -0
  56. package/src/pi/delegation.ts +2 -21
  57. package/src/pi/model-support.ts +0 -6
  58. package/src/pi/start-task.ts +18 -7
  59. package/src/pi/tools.ts +41 -8
  60. package/src/roles/scout.ts +3 -1
  61. package/src/roles/worker.ts +107 -5
  62. package/src/schemas/configuration.ts +11 -45
  63. package/src/schemas/findings.ts +3 -0
  64. package/src/schemas/task.ts +30 -12
  65. package/src/scripts/library.ts +31 -1
  66. package/src/scripts/pick.ts +31 -15
  67. package/src/state/archive.ts +10 -0
  68. package/src/state/checkpoint.ts +0 -1
  69. package/src/state/gitignore.ts +39 -0
  70. package/src/state/persistence.ts +56 -0
  71. package/src/state/recovery.ts +33 -1
  72. package/src/webui/api/index.ts +6 -35
  73. package/src/webui/api/retention.ts +44 -0
  74. package/src/webui/api/status.ts +4 -6
  75. package/src/webui/dev/fake-service.ts +0 -117
  76. package/src/webui/dev/fixtures.ts +2 -16
  77. package/src/webui/protocol.ts +2 -142
  78. package/src/workflow/draft-assignments.ts +118 -0
  79. package/src/workflow/workflow.ts +271 -214
  80. package/webui/dist/assets/{CodeSurface-BtzJOVyH.js → CodeSurface-D3c12DBE.js} +1 -1
  81. package/webui/dist/assets/{TerminalView-Cz-KNWsq.js → TerminalView-DG4X3Yyr.js} +1 -1
  82. package/webui/dist/assets/index-BDmgr1OS.js +112 -0
  83. package/webui/dist/assets/index-BTyu99rI.css +2 -0
  84. package/webui/dist/build.json +29 -65
  85. package/webui/dist/index.html +2 -2
  86. package/prompts/expert.md +0 -17
  87. package/prompts/goal-check.md +0 -44
  88. package/prompts/pr-review.md +0 -62
  89. package/prompts/splitter.md +0 -58
  90. package/src/execution/worker-trees.ts +0 -396
  91. package/src/lobby/issues.ts +0 -219
  92. package/src/lobby/pr-review.ts +0 -366
  93. package/src/lobby/pulls.ts +0 -250
  94. package/src/lobby/split.ts +0 -262
  95. package/src/master/goal-check.ts +0 -115
  96. package/src/webui/api/gh-error.ts +0 -17
  97. package/src/webui/api/git.ts +0 -98
  98. package/src/webui/api/issues.ts +0 -50
  99. package/webui/dist/assets/index-D5fvY8f8.js +0 -112
  100. package/webui/dist/assets/index-DFvk8ADr.css +0 -2
@@ -7,8 +7,7 @@ import type { AgentRun } from "../schemas/findings.ts";
7
7
  import type { Domain, Role } from "../schemas/agent.ts";
8
8
  import { effortFor } from "../classifier/instance.ts";
9
9
  import { fellShort, profileLabel, routeLabel } from "../classifier/effort.ts";
10
- import { agentProfile, expertProfile } from "../schemas/configuration.ts";
11
- import { loadPrompt } from "../prompts/loader.ts";
10
+ import { agentProfile } from "../schemas/configuration.ts";
12
11
  import { dataRoot, detectProjectRoot, loadConfig } from "../state/project.ts";
13
12
  import { EditLog } from "../state/changes.ts";
14
13
  import { createLiveRun } from "./live-run.ts";
@@ -18,26 +17,13 @@ import { artifactIdentity, startDeskServer, type DeskRequest, type DeskResponse
18
17
  import { assignmentRecord, issueAssignment, loadTask, recordArtifactRef, taskDirFor } from "../state/persistence.ts";
19
18
  import { persistedRunMarks } from "../state/checkpoint.ts";
20
19
  import { TERMINAL_STATES, type AssignmentGrant, type AssignmentRecord, type TaskState } from "../schemas/task.ts";
21
- import { DESK_ENV, DeskSession, deskSessionAt, PEER_TOOLS } from "../desk/session.ts";
20
+ import { DESK_ENV, DeskSession, deskSessionAt } from "../desk/session.ts";
22
21
  import { BOARD_ENV } from "../desk/board.ts";
23
22
  import { mcpGrant } from "../pi/grants.ts";
24
23
 
25
24
  export const MAX_CHILDREN = 5;
26
25
  export const DELEGATE_TOOL = "delegate_subtasks";
27
- export const EXPERT_TOOL = "ask_expert";
28
26
  export const DURABLE_OUTPUT_TOOL = "read_durable_output_artifacts";
29
- /** Consults one step may make: advice on the hard part, not a second worker. */
30
- export const MAX_CONSULTS = 2;
31
- /** Longest an expert may take to answer. */
32
- /** Marks an expert's run, so its host gives it an adviser's note rather than a child's. */
33
- export const EXPERT_ENV = "BOT_LOBBY_EXPERT";
34
-
35
- /** The worker's env without its desk and board: an expert only reads and answers. */
36
- function withoutTeamEnv(env: Record<string, string> | undefined): Record<string, string> {
37
- const { [DESK_ENV.address]: _address, [DESK_ENV.worker]: _worker, [BOARD_ENV]: _board, BOT_LOBBY_BOARD_FROM: _from, ...rest } = env ?? {};
38
- return rest;
39
- }
40
- const EXPERT_TOOLS = ["read", "grep", "find", "ls"];
41
27
  export const AGENT_ENV = "BOT_LOBBY_AGENT_POLICY";
42
28
  export const DELEGATION_ENV = "BOT_LOBBY_DELEGATION";
43
29
 
@@ -48,16 +34,10 @@ export function canDelegate(agent: { role: Role; domain: Domain; depth?: number
48
34
  return agent.role === "reviewer" && agent.domain === "qa";
49
35
  }
50
36
 
51
- /** A task's DESIGN/DEV workers (not their children, nor lobby chat agents) may consult a stronger model, when the setting is on. */
52
- export function canConsult(agent: { runId: string; taskId: string; role: Role; domain: Domain; depth?: number }, enabled: boolean): boolean {
53
- // A lobby chat agent runs as its own task: it is one agent answering the user, not a task's worker.
54
- return enabled && agent.taskId !== agent.runId && (agent.depth ?? 1) === 1 && agent.role === "worker" && (agent.domain === "designer" || agent.domain === "backend");
55
- }
56
-
57
37
  /** One shared child pool per task; parents waiting on children never hold its slots. */
58
38
  /** A child host: no delegation of its own, but durable reads under its own assignment when issued one. */
59
39
  async function childHost(options: PiRunOptions, policy: AgentPolicy, tools: string[], mcpTools: string[], artifactTool: string | undefined) {
60
- const note = options.env?.[EXPERT_ENV] ? "You are advising a worker: read what you need, answer its question, and change nothing." : "You are a child agent. Finish only your assigned brief and report evidence to your parent; you cannot delegate further.";
40
+ const note = "You are a child agent. Finish only your assigned brief and report evidence to your parent; you cannot delegate further.";
61
41
  const access = artifactTool ? options.runtimeAccess : undefined;
62
42
  if (!access) return { tools, mcpTools, env: { ...options.env, [AGENT_ENV]: JSON.stringify(policy), [DELEGATION_ENV]: "" }, note, close: async () => {}, onStart: options.onStart, children: [] as AgentRun[] };
63
43
  const token = randomUUID();
@@ -238,10 +218,9 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
238
218
  const agent = options.agent ?? { runId: id, taskId: id, domain: "backend" as const, role: editable ? "worker" as const : "reviewer" as const };
239
219
  const depth = agent.depth ?? 1;
240
220
  const quota = options.delegationQuota ?? { used: 0 };
241
- const consults = canConsult(agent, config.workflow.consultExpert);
242
221
  // Durable artifact reads appear only when the caller handed the host a live assignment access.
243
222
  const artifactTool = options.runtimeAccess?.authorize("artifact.read") === true ? DURABLE_OUTPUT_TOOL : undefined;
244
- const tools = [...new Set([...baseTools, "codemode", "tool_search", ...(artifactTool ? [artifactTool] : []), ...(canDelegate(agent, quota.used) ? [DELEGATE_TOOL] : []), ...(consults ? [EXPERT_TOOL] : [])])];
223
+ const tools = [...new Set([...baseTools, "codemode", "tool_search", ...(artifactTool ? [artifactTool] : []), ...(canDelegate(agent, quota.used) ? [DELEGATE_TOOL] : [])])];
245
224
  // A caller that passes its profile's grant (even an absent one, meaning every connected tool) wins over the role's.
246
225
  const mcpTools = mcpGrant("mcpTools" in options ? options.mcpTools : agentProfile(config, agent.domain, agent.role).mcpTools, !editable);
247
226
  const policy: AgentPolicy = { tools, mcpTools, readOnly: !editable, depth };
@@ -251,10 +230,10 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
251
230
  let desk = address ? deskSessionAt(address) : undefined;
252
231
  if (address && !desk) throw new Error("The inherited file desk is unavailable.");
253
232
  const board = options.env?.[BOARD_ENV];
254
- // A worker with a checkout of its own (no claims on the batch desk) still needs claims among its children.
255
- const ownedDesk = editable && (!desk || !desk.usesClaims) ? new DeskSession({ cwd: options.cwd, ...(board ? { boardPath: board } : {}) }) : undefined;
233
+ // A worker without a batch desk still needs claims among its children.
234
+ const ownedDesk = editable && !desk ? new DeskSession({ cwd: options.cwd, ...(board ? { boardPath: board } : {}) }) : undefined;
256
235
  if (ownedDesk) await ownedDesk.open();
257
- // Children claim files among themselves; the parent keeps the batch desk (and its peers) when it has one.
236
+ // Children claim files among themselves; the parent keeps the batch desk when it has one.
258
237
  const childDesk = ownedDesk ?? desk;
259
238
  desk ??= ownedDesk;
260
239
  const controller = new AbortController();
@@ -303,7 +282,7 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
303
282
  task: brief,
304
283
  model,
305
284
  thinking,
306
- tools: [...new Set([...tools.filter((tool) => tool !== DELEGATE_TOOL && tool !== EXPERT_TOOL && (tool !== DURABLE_OUTPUT_TOOL || !!childAccess)), ...(childDesk ? childDesk.tools().filter((tool) => !PEER_TOOLS.includes(tool)) : [])])],
285
+ tools: [...new Set([...tools.filter((tool) => tool !== DELEGATE_TOOL && (tool !== DURABLE_OUTPUT_TOOL || !!childAccess)), ...(childDesk ? childDesk.tools() : [])])],
307
286
  mcpTools,
308
287
  ...(childAccess ? { runtimeAccess: childAccess } : {}),
309
288
  signal,
@@ -333,74 +312,10 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
333
312
  }
334
313
  };
335
314
 
336
- // Kept on the quota, which a step's retries share, so a retry does not grant fresh consults.
337
- quota.consults ??= 0;
338
- const consultations = new Map<string, AbortController>();
339
- const consult = async (question: string, signal: AbortSignal): Promise<{ ok: boolean; text: string }> => {
340
- // The oracle resolves the expert (its session model when settings name none); settings alone, then the worker's own, without it.
341
- const settled = options.expert ?? expertProfile(config);
342
- const expert = { model: settled.model ?? options.model, thinking: settled.thinking };
343
- const expertId = randomUUID();
344
- const base: AgentRun = { runId: expertId, parentRunId: id, depth: 2, taskId: agent.taskId, domain: agent.domain, role: "reviewer", instruction: question, stepInstruction: options.task, status: "running", output: "", attempts: 1, startedAt: new Date().toISOString(), thinking: expert.thinking, ...(expert.model ? { model: expert.model } : {}), note: "expert consult", noteKind: "info" };
345
- const live = createLiveRun(base, { onUpdate: update }, new EditLog(options.cwd));
346
- update(base);
347
- let final: AgentRun;
348
- try {
349
- const result = await runPiAgent({
350
- cwd: options.cwd,
351
- agent: { ...agent, runId: expertId, role: "reviewer", depth: 2 },
352
- task: [`A worker asks: ${question}`, `The worker's brief, for context:\n${options.task.slice(0, 8000)}`].join("\n\n"),
353
- systemPrompt: loadPrompt("expert.md"),
354
- tools: EXPERT_TOOLS,
355
- mcpTools: [],
356
- ...(expert.model ? { model: expert.model } : {}),
357
- thinking: expert.thinking,
358
- ...(options.stallTimeoutMs !== undefined ? { stallTimeoutMs: options.stallTimeoutMs } : {}),
359
- ...(options.toolStallTimeoutMs !== undefined ? { toolStallTimeoutMs: options.toolStallTimeoutMs } : {}),
360
- signal,
361
- onEvent: live.onEvent,
362
- // Its own env: the expert is not one of the worker's children, nor on its desk or board.
363
- env: { ...withoutTeamEnv(options.env), [EXPERT_ENV]: "1" },
364
- }, run);
365
- final = { ...live.current(), ...result, finishedAt: new Date().toISOString(), note: undefined, noteKind: undefined };
366
- } catch (error) {
367
- final = { ...live.current(), status: signal.aborted ? "cancelled" : "failed", error: (error as Error).message, finishedAt: new Date().toISOString(), note: undefined, noteKind: undefined };
368
- }
369
- update(final);
370
- if (final.status === "success" && final.output.trim()) return { ok: true, text: final.output.trim().slice(0, 8000) };
371
- // An expert that never answered does not use up a consult.
372
- quota.consults = Math.max(0, (quota.consults ?? 1) - 1);
373
- return { ok: false, text: `The expert did not answer (${final.status}${final.error ? `: ${final.error}` : ""}); carry on with your best reading.` };
374
- };
375
-
376
315
  const token = randomUUID();
377
316
  const server = await startDeskServer(async (request) => {
378
317
  if (request.worker !== token) return { ok: false, text: "Unknown parent agent." };
379
318
  if (request.op === "cancel_delegate") { controller.abort(); return { ok: true, text: "Children cancelled." }; }
380
- if (request.op === "cancel_consult") {
381
- consultations.get(request.consultId ?? "")?.abort();
382
- return { ok: true, text: "Consult cancelled." };
383
- }
384
- if (request.op === "consult") {
385
- if (!consults) return { ok: false, text: "Consulting is off for this agent." };
386
- if ((quota.consults ?? 0) >= MAX_CONSULTS) return { ok: false, text: `You have used your ${MAX_CONSULTS} consults for this step; decide with what you have, or report the open question.` };
387
- const question = (request.text ?? "").trim();
388
- if (!question) return { ok: false, text: "ask_expert needs a question." };
389
- quota.consults = (quota.consults ?? 0) + 1;
390
- // Its own controller, so the worker abandoning its tool call stops this expert and nothing else.
391
- const own = new AbortController();
392
- const parent = childSignal();
393
- const stop = () => own.abort();
394
- parent.addEventListener("abort", stop, { once: true });
395
- const consultId = request.consultId ?? randomUUID();
396
- consultations.set(consultId, own);
397
- try {
398
- return await consult(question.slice(0, 6000), own.signal);
399
- } finally {
400
- consultations.delete(consultId);
401
- parent.removeEventListener("abort", stop);
402
- }
403
- }
404
319
  if (request.op === "artifact") return artifactPage(options.runtimeAccess, request);
405
320
  if (request.op !== "delegate") return { ok: false, text: "Unknown delegation operation." };
406
321
  const signal = childSignal();
@@ -428,7 +343,7 @@ export async function delegationHost(options: PiRunOptions, run: ProcessRunner)
428
343
  tools: desk ? [...new Set([...tools, ...desk.tools()])] : tools,
429
344
  mcpTools,
430
345
  env: { ...options.env, ...(desk ? desk.env(parentDeskId) : {}), [AGENT_ENV]: JSON.stringify({ ...policy, tools: desk ? [...new Set([...tools, ...desk.tools()])] : tools }), [DELEGATION_ENV]: JSON.stringify({ address: server.address, token, ...(options.runtimeAccess ? { assignment: options.runtimeAccess.assignmentId } : {}) }) },
431
- note: `${consults ? `When you are stuck on a hard step after a real attempt, or about to make a choice you are unsure of (a tricky algorithm, a subtle bug, an unfamiliar API), ${EXPERT_TOOL} asks a stronger model for advice, at most ${MAX_CONSULTS} times; it reads the repository and answers, you still do the work. ` : ""}${canDelegate(agent, quota.used) ? `Work directly when you can finish the brief yourself. Use ${DELEGATE_TOOL} only for useful, separable work with disjoint files, at most five children total; children cannot delegate further. Integrate and verify their work yourself. ` : ""}Use codemode for concise parallel calls, inspect failures, and return only useful evidence.${desk?.usesClaims ? " Before edit/write, claim_file; handover_file when finished. Release files before delegating or waiting." : ""}`,
346
+ note: `${canDelegate(agent, quota.used) ? `Work directly when you can finish the brief yourself. Use ${DELEGATE_TOOL} only for useful, separable work with disjoint files, at most five children total; children cannot delegate further. Integrate and verify their work yourself. ` : ""}Use codemode for concise parallel calls, inspect failures, and return only useful evidence.${desk ? " Before edit/write, claim_file; handover_file when finished. Release files before delegating or waiting." : ""}`,
432
347
  onStart: (handle: Parameters<NonNullable<PiRunOptions["onStart"]>>[0]) => {
433
348
  desk?.attach(parentDeskId, { runId: id, steer: handle.steer, annotate: () => {} });
434
349
  options.onStart?.(handle);
@@ -1,12 +1,15 @@
1
1
  import type { AgentRun } from "../schemas/findings.ts";
2
2
  import type { Domain, Role } from "../schemas/agent.ts";
3
- import { delegationHost } from "./delegation.ts";
3
+ import { AGENT_ENV, delegationHost, type AgentPolicy, type RuntimeAccess } from "./delegation.ts";
4
+ import { DESK_TOOLS } from "../desk/session.ts";
5
+ import { ASSIGNMENT_ENV, type AssignmentAttestation, type AssignmentGuardSpec } from "../pi/assignment-guard.ts";
6
+ import { readAssignmentDiscovery } from "./assignment-discovery.ts";
4
7
  import { AUTO_COMPACT_ENV, COMPACT_AT_ENV } from "../pi/quiet.ts";
5
8
  import { fileURLToPath } from "node:url";
6
9
  import { spawn, type ChildProcess } from "node:child_process";
7
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
10
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
11
  import { tmpdir } from "node:os";
9
- import { basename, join } from "node:path";
12
+ import { basename, dirname, join, resolve } from "node:path";
10
13
  import { activityWord } from "../pi/activity.ts";
11
14
  import { skillFiles } from "../pi/grants.ts";
12
15
  import { shortDuration } from "../text.ts";
@@ -15,6 +18,7 @@ import type { AskQuestion, AskResult } from "../ask/types.ts";
15
18
  import type { EffortRouter, RunProfileLike } from "../classifier/effort.ts";
16
19
  import type { HarnessRun } from "../schemas/harness.ts";
17
20
  import { runHarnessAgent } from "../harness/runner.ts";
21
+ import { assignedSessionFile, openAssignedSession, type AssignedSession } from "./assigned-session.ts";
18
22
 
19
23
  /** Live control over one running subagent: queue a steering message for its next turn. */
20
24
  export interface RunHandle {
@@ -28,13 +32,16 @@ export interface RunHandle {
28
32
  export type RelayAsk = (questions: AskQuestion[], signal: AbortSignal) => Promise<AskResult>;
29
33
 
30
34
  export interface PiRunOptions {
35
+ /** Host-owned task conversation, reused across validated assignment revisions. */
36
+ assignedSession?: AssignedSession;
37
+ /** The assignment's validated replacement selection, applied inside the run's existing grants. */
38
+ assignedTools?: string[];
39
+ runtimeAccess?: RuntimeAccess;
31
40
  effort?: EffortRouter;
32
41
  effortProfile?: RunProfileLike;
33
42
  agent?: { runId: string; taskId: string; domain: Domain; role: Role; depth?: number };
34
43
  mcpTools?: string[];
35
- delegationQuota?: { used: number; consults?: number };
36
- /** The model and thinking ask_expert consults on, resolved by the oracle (its session model when settings name none). */
37
- expert?: { model?: string; thinking: string };
44
+ delegationQuota?: { used: number };
38
45
  onChildRun?: (run: AgentRun) => void;
39
46
  cwd: string;
40
47
  task: string;
@@ -323,7 +330,7 @@ export const MCP_RESOURCE_TOOLS: readonly string[] = ["list_mcp_resources", "lis
323
330
 
324
331
  /** Build the `pi` argv for one isolated, headless RPC agent run; the task goes over stdin. */
325
332
  export function buildPiArgs(options: Omit<PiRunOptions, "task"> & { systemPromptFile?: string; skillFiles?: string[] }): string[] {
326
- const args = ["--mode", "rpc", "--no-session", "--no-prompt-templates", "--no-themes", "--extension", fileURLToPath(new URL("../index.ts", import.meta.url))];
333
+ const args = ["--mode", "rpc", ...(options.assignedSession ? ["--session", assignedSessionFile(options.assignedSession), "--session-dir", join(options.assignedSession.taskDir, "sessions")] : ["--no-session"]), "--no-prompt-templates", "--no-themes", "--extension", fileURLToPath(new URL("../index.ts", import.meta.url))];
327
334
  if (options.model && options.model !== "inherit") args.push("--model", options.model);
328
335
  if (options.thinking) args.push("--thinking", options.thinking);
329
336
  // A skill grant replaces pi's own discovery with exactly the granted skills.
@@ -331,7 +338,11 @@ export function buildPiArgs(options: Omit<PiRunOptions, "task"> & { systemPrompt
331
338
  args.push("--no-skills");
332
339
  for (const file of options.skillFiles) args.push("--skill", file);
333
340
  }
334
- if (options.tools && options.tools.length > 0) {
341
+ if (options.assignedSession) {
342
+ const selected = [...new Set(options.tools ?? [])].sort();
343
+ args.push(...(selected.length ? ["--tools", selected.join(",")] : ["--no-tools"]));
344
+ if (!selected.some((name) => name.startsWith("mcp__") || MCP_RESOURCE_TOOLS.includes(name))) args.push("--no-mcp");
345
+ } else if (options.tools && options.tools.length > 0) {
335
346
  // pi keeps every MCP tool under --tools unless an entry names one, so name the granted ones (and the resource
336
347
  // tools their servers need), or run without MCP at all when nothing is granted.
337
348
  const mcp = options.mcpTools?.filter((name) => name.startsWith("mcp__")) ?? [];
@@ -655,11 +666,90 @@ function writePromptFile(prompt: string): { file: string; cleanup: () => void }
655
666
  return { file, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
656
667
  }
657
668
 
669
+ function failedRun(error: string): PiRunResult {
670
+ return { status: "failed", output: "", error, usage: { input: 0, output: 0, cost: 0, turns: 0 } };
671
+ }
672
+
673
+ /** The attestation the worker's guard wrote for this revision, or why there is none. */
674
+ function attestationIssue(path: string, revision: number): string | undefined {
675
+ let attestation: AssignmentAttestation;
676
+ try { attestation = JSON.parse(readFileSync(path, "utf8")) as AssignmentAttestation; }
677
+ catch { return "Assigned execution compatibility: the worker's tool guard never attested its declared tools, so the run is not accepted (no unrestricted fallback)."; }
678
+ if (attestation.revision !== revision) return `Assigned execution compatibility: the tool guard attested revision ${attestation.revision}, not ${revision}.`;
679
+ if (!attestation.ok) return `Assigned execution compatibility: ${attestation.unauthorized.join(", ")} stayed declared after the allowlist was reapplied.`;
680
+ return undefined;
681
+ }
682
+
683
+ /**
684
+ * A structured assignment's run: its own task-owned conversation (locked for the
685
+ * process's lifetime, sanitized of restored tool declarations), a replacement tool
686
+ * allowlist, and the in-process guard, whose attestation the run must carry.
687
+ * Third-party harnesses cannot meet this and are refused before any request.
688
+ */
689
+ async function runAssignedAgent(options: PiRunOptions, run: ProcessRunner): Promise<PiRunResult> {
690
+ if (options.harness) return failedRun("Assigned execution compatibility: a third-party harness cannot keep a sanitized task conversation or attest its tool inventory; run this assignment's agent on pi, or dispatch it without a structured assignment.");
691
+ const assigned = options.assignedSession!;
692
+ let session: ReturnType<typeof openAssignedSession>;
693
+ try { session = openAssignedSession(assigned, options.cwd); }
694
+ catch (error) { return failedRun(error instanceof Error ? error.message : String(error)); }
695
+ const attestation = join(dirname(session.file), "attestation.json");
696
+ rmSync(attestation, { force: true });
697
+ const selected = [...new Set(options.assignedTools ?? [])].sort();
698
+ const host = await delegationHost(options, run);
699
+ let prompt: ReturnType<typeof writePromptFile> | undefined;
700
+ try {
701
+ // Replacement, not additive: the host's own extras stay out unless selected, except the file desk's
702
+ // claim/handover protocol, without which a selected edit cannot happen in a shared batch.
703
+ const edits = selected.includes("edit") || selected.includes("write");
704
+ const granted = new Set([...host.tools, ...host.mcpTools, ...(host.mcpTools.length > 0 ? MCP_RESOURCE_TOOLS : [])]);
705
+ const allowed = [...new Set([...selected.filter((name) => granted.has(name)), ...(edits ? host.tools.filter((name) => DESK_TOOLS.includes(name)) : [])])].sort();
706
+ const mcpTools = allowed.filter((name) => name.startsWith("mcp__"));
707
+ const policy = JSON.parse(host.env[AGENT_ENV] ?? "{}") as AgentPolicy;
708
+ const guard: AssignmentGuardSpec = {
709
+ taskDir: assigned.taskDir, assignmentId: assigned.assignmentId, revision: assigned.revision, tools: allowed, cwd: options.cwd,
710
+ files: (assigned.files ?? []).map((file) => ({ path: resolve(options.cwd, file.path), access: file.access })), verification: assigned.verification ?? [], attestation,
711
+ };
712
+ const env = { ...host.env, [AGENT_ENV]: JSON.stringify({ ...policy, tools: allowed, mcpTools }), [ASSIGNMENT_ENV]: JSON.stringify(guard) };
713
+ prompt = writePromptFile([options.systemPrompt, host.note].filter(Boolean).join("\n\n"));
714
+ if (options.signal?.aborted) return { status: "cancelled", output: "", usage: { input: 0, output: 0, cost: 0, turns: 0 } };
715
+ const args = buildPiArgs({ ...options, tools: allowed, mcpTools, systemPromptFile: prompt.file, ...(options.skills ? { skillFiles: skillFiles(options.skills, options.cwd) } : {}) });
716
+ const outcome = await run(args, {
717
+ cwd: options.cwd,
718
+ signal: options.signal,
719
+ prompt: `Task: ${options.task}`,
720
+ env,
721
+ stallTimeoutMs: options.stallTimeoutMs,
722
+ toolStallTimeoutMs: options.toolStallTimeoutMs,
723
+ ...(options.onAsk ? { onAsk: options.onAsk } : {}),
724
+ onStart: host.onStart,
725
+ onEvent: (event) => {
726
+ if (event.type === "tool_execution_start") options.onActivity?.(activityWord(event.toolName));
727
+ options.onEvent?.(event);
728
+ },
729
+ });
730
+ let result = toResult(parsePiStream(outcome.stdout), outcome, options.signal?.aborted === true, options);
731
+ const issue = result.status === "cancelled" ? undefined : attestationIssue(attestation, assigned.revision);
732
+ if (issue) result = { ...result, status: "failed", error: [issue, result.error].filter(Boolean).join(" ") };
733
+ try {
734
+ const ledger = await readAssignmentDiscovery(assigned.taskDir, assigned.assignmentId, assigned.revision);
735
+ session.state.consumedDiscovery = Math.max(session.state.consumedDiscovery, ledger.consumed);
736
+ } catch { /* the ledger's own errors surface on the next dispatch */ }
737
+ session.save();
738
+ await host.close();
739
+ return host.children.length ? { ...result, children: host.children } : result;
740
+ } finally {
741
+ prompt?.cleanup();
742
+ await host.close();
743
+ session.release();
744
+ }
745
+ }
746
+
658
747
  /** Run one isolated subagent and normalise its outcome. */
659
748
  export async function runPiAgent(given: PiRunOptions, run: ProcessRunner = spawnPiProcess): Promise<PiRunResult> {
660
- if (given.harness) return runHarnessAgent({ ...given, harness: given.harness });
661
749
  const compactEnv = { ...(given.autoCompact === false ? { [AUTO_COMPACT_ENV]: "0" } : {}), ...(given.compactAt ? { [COMPACT_AT_ENV]: String(given.compactAt) } : {}) };
662
750
  const options = Object.keys(compactEnv).length ? { ...given, env: { ...given.env, ...compactEnv } } : given;
751
+ if (options.assignedSession) return runAssignedAgent(options, run);
752
+ if (given.harness) return runHarnessAgent({ ...given, harness: given.harness });
663
753
  const host = await delegationHost(options, run);
664
754
  let prompt: ReturnType<typeof writePromptFile> | undefined;
665
755
  try {
@@ -14,7 +14,7 @@ import { HARNESSES } from "./catalog.ts";
14
14
  /** Pi's tool names in the role prompts, and what stands in for them on another harness. */
15
15
  const HARNESS_NOTE = `## Running on another harness
16
16
 
17
- You run in Bot Lobby through a third-party harness, not pi. Where these instructions name pi's tools (read, edit, write, bash, grep, find, ls), use your own equivalents. Bot Lobby's own tools (ask_user_question, ask_expert, the file desk and task board tools, web_search and fetch_content) are not available here: work from the brief, use your own web tools if you have them, and put any open question or blocker in your report instead of asking.`;
17
+ You run in Bot Lobby through a third-party harness, not pi. Where these instructions name pi's tools (read, edit, write, bash, grep, find, ls), use your own equivalents. Bot Lobby's own tools (ask_user_question, the file desk and task board tools, web_search and fetch_content) are not available here: work from the brief, use your own web tools if you have them, and put any open question or blocker in your report instead of asking.`;
18
18
 
19
19
  function toSingleLine(value: string): string {
20
20
  return value.replaceAll(/\s+/g, " ").trim();
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@ import { registerAskTool } from "./ask/tool.ts";
22
22
  import { registerWebTools } from "./web/tools.ts";
23
23
  import { registerToolBudget } from "./pi/tool-budget.ts";
24
24
  import { bindGrants } from "./pi/grants.ts";
25
+ import { registerAssignmentGuard } from "./pi/assignment-guard.ts";
25
26
 
26
27
  export default function (pi: ExtensionAPI): void {
27
28
  registerAgentPermissions(pi);
@@ -60,4 +61,6 @@ export default function (pi: ExtensionAPI): void {
60
61
  registerKnowledgeTools(pi, CONFIG_DIR_NAME);
61
62
  // A subagent given a tool budget (scouts) is warned, then refused, so it reports instead of searching on.
62
63
  if (isSubagentProcess()) registerToolBudget(pi);
64
+ // A worker on a structured assignment: its replacement allowlist, edit scope and discovery ledger.
65
+ if (isSubagentProcess()) registerAssignmentGuard(pi);
63
66
  }