@chankov/agent-fleet 0.0.1 → 0.0.3

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 (65) hide show
  1. package/.claude/commands/doctor-agent-fleet.md +1 -1
  2. package/.claude/commands/setup-agent-fleet.md +4 -4
  3. package/.opencode/commands/af-doctor-agent-fleet.md +2 -0
  4. package/.opencode/commands/af-setup-agent-fleet.md +1 -1
  5. package/.pi/agents/model-profiles.yaml +12 -12
  6. package/.pi/agents/peers.yaml +26 -22
  7. package/.pi/agents/teams.yaml +2 -2
  8. package/.pi/harnesses/agent-hub/README.md +57 -4
  9. package/.pi/harnesses/agent-hub/index.ts +236 -80
  10. package/.pi/harnesses/agent-hub/research-retention.js +34 -0
  11. package/.pi/harnesses/ask-user-remote/README.md +8 -0
  12. package/.pi/harnesses/ask-user-remote/index.ts +41 -1
  13. package/.pi/harnesses/coms/README.md +11 -0
  14. package/.pi/prompts/doctor-agent-fleet.md +1 -1
  15. package/.pi/prompts/setup-agent-fleet.md +4 -4
  16. package/README.md +133 -354
  17. package/agents/architect.md +4 -2
  18. package/agents/bowser.md +2 -1
  19. package/agents/builder.md +3 -2
  20. package/agents/code-reviewer.md +7 -7
  21. package/agents/deep-researcher.md +3 -3
  22. package/agents/documenter.md +3 -1
  23. package/agents/orchestrator.md +5 -3
  24. package/agents/plan-reviewer.md +5 -5
  25. package/agents/planner.md +7 -7
  26. package/agents/releaser.md +3 -1
  27. package/agents/researcher.md +3 -3
  28. package/agents/security-auditor.md +7 -7
  29. package/agents/test-engineer.md +5 -5
  30. package/agents/web-debugger.md +3 -3
  31. package/agents/web-performance-auditor.md +3 -3
  32. package/bin/snapshot-version.js +17 -1
  33. package/codex/CONDUCTOR.md +148 -0
  34. package/docs/ARCHITECTURE.md +165 -0
  35. package/docs/agent-fleet-setup.md +1 -0
  36. package/docs/claude-code-coms-bridge.md +10 -0
  37. package/docs/codex-remote-conductor.md +170 -0
  38. package/docs/coms-hermes-bridge.md +121 -0
  39. package/docs/getting-started.md +14 -0
  40. package/docs/npm-install.md +2 -0
  41. package/docs/pi-extensions.md +16 -0
  42. package/docs/pi-setup.md +2 -0
  43. package/hermes/README.md +48 -0
  44. package/hermes/skills/hub-conductor/SKILL.md +84 -0
  45. package/hermes/skills/hub-liaison/SKILL.md +84 -0
  46. package/justfile +132 -15
  47. package/package.json +10 -3
  48. package/scripts/codex-conductor.ts +41 -0
  49. package/scripts/codex-remote-control.ts +167 -0
  50. package/scripts/coms-cli.ts +311 -199
  51. package/scripts/coms-hermes-bridge.ts +8 -4
  52. package/scripts/lib/codex-conductor.ts +88 -0
  53. package/scripts/lib/codex-remote-control.ts +480 -0
  54. package/scripts/lib/coms-envelope.ts +51 -6
  55. package/scripts/lib/herdr-layout.ts +35 -7
  56. package/scripts/lib/hermes-bridge-core.ts +4 -4
  57. package/scripts/lib/spawn-stagger.ts +101 -0
  58. package/scripts/lib/team-project.ts +112 -3
  59. package/scripts/lib/team-snapshot.ts +3 -2
  60. package/scripts/team-snapshot.ts +23 -6
  61. package/scripts/team-up.ts +106 -18
  62. package/skills/guided-workspace-setup/SKILL.md +123 -97
  63. package/skills/guided-workspace-setup/companion-manifest.json +33 -0
  64. package/skills/peer-coms/SKILL.md +9 -0
  65. package/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
@@ -24,14 +24,20 @@
24
24
  * /models [profile] — apply a named model profile (.pi/agents/model-profiles.yaml)
25
25
  * /agent-models-substitute <source> <target> — swap one model across all personas
26
26
  * /dispatch-policy — show which members route to coms peers (.pi/agents/dispatch-policy.yaml)
27
- * /agents-kill <name> — SIGTERM a frozen specialist (and its delegation tree)
28
- * /agents-restart <name>— kill + re-run its last task fresh
27
+ * /agents-kill <name|rN|all> — SIGTERM a frozen specialist (and its delegation
28
+ * tree); on a research helper it kills AND removes the
29
+ * card + session ("all" clears every research helper)
30
+ * (aliases: /research-rm rN, /research-clear)
31
+ * /agents-restart <name|rN> — kill + re-run its last task fresh (research: must
32
+ * be finished; runs on a fresh session)
29
33
  * /zoom <name|rN|child> — scrollable read-only view of an agent's stream
30
34
  * (team member, research helper rN, or delegate child id)
31
35
  * /research <task> — spawn a read-only research helper (@persona, --model)
32
- * /research-cont rN ... — resume a finished research helper
33
- * /research-rm rN — remove a research helper (kill if running)
34
- * /research-clear — remove all research helpers
36
+ * /agents-cont rN ... — resume a finished research helper (alias: /research-cont)
37
+ *
38
+ * Finished research helpers are auto-pruned: auto-research pipe helpers as soon
39
+ * as they finish (findings persist as files under findings/), manual/persona
40
+ * helpers beyond the `research-keep` most recent (default 4, overrides file).
35
41
  * /persona — select/reset the dispatcher persona
36
42
  * /handoff <peer> — hand the session off to a coms peer (summarized brief)
37
43
  * /coms — refresh the coms peer pool (--all / --project <name>)
@@ -76,6 +82,7 @@ import { crossCheck, extractAssertionIds, parseStructuredReturn } from "./return
76
82
  import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
77
83
  import { validateEvidence } from "./evidence-rules.js";
78
84
  import { comsRequiredRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
85
+ import { DEFAULT_RESEARCH_KEEP, parseResearchKeep, selectResearchPrunable } from "./research-retention.js";
79
86
  import { readdirSync, readFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync, rmSync } from "fs";
80
87
  import {
81
88
  formatPeerStatus,
@@ -217,12 +224,16 @@ interface AgentState {
217
224
  // team with reconnaissance/search/doc-reading — it never writes and never runs bash.
218
225
  // Keyed by a numeric id surfaced to the operator as the handle `rN`. Ephemeral by
219
226
  // construction: session files live under the same dir as team sessions and are wiped
220
- // on session_start; `/research-clear` removes them mid-session. Resumable via
221
- // `/research-cont` (subcont-style, bumping turnCount).
227
+ // on session_start; finished helpers are auto-pruned per the retention policy
228
+ // (research-retention.js — auto-pipe helpers immediately, older manual ones beyond
229
+ // the `research-keep` cap); `/agents-kill rN` (alias `/research-rm`) kills AND
230
+ // removes one by hand. Resumable via `/agents-cont` (alias `/research-cont`,
231
+ // subcont-style, bumping turnCount) while retained.
222
232
  interface ResearchState {
223
233
  id: number;
224
234
  def: AgentDef; // a `kind: research` persona, or a synthesized def for anon helpers
225
235
  persona: boolean; // true → spawned from a persona; false → ad-hoc anonymous
236
+ ephemeral: boolean; // true → auto-research pipe spawn: pruned as soon as it finishes
226
237
  model: string; // resolved pi model spec (shown on the card)
227
238
  status: "idle" | "running" | "done" | "error";
228
239
  task: string;
@@ -232,6 +243,7 @@ interface ResearchState {
232
243
  contextPct: number;
233
244
  sessionFile: string | null; // set after a successful run → enables `-c` resume
234
245
  turnCount: number;
246
+ finishedAt?: number; // last time a run ended (any status) — LRU key for retention
235
247
  timer?: ReturnType<typeof setInterval>;
236
248
  proc?: ChildProcess;
237
249
  killedByOperator?: boolean;
@@ -369,6 +381,10 @@ function extractNeedsResearch(output: string): string[] {
369
381
  // orientation): canonical files (e.g. Docs/AGENTS.md) or
370
382
  // doc folders. Specialists and research helpers read the
371
383
  // ones relevant to their task; context, not compliance.
384
+ // research-keep: <n>|all — how many finished manual/persona research helpers
385
+ // to retain for /agents-cont resume (LRU, default 4);
386
+ // "all" disables pruning. Auto-research pipe helpers
387
+ // are always pruned as soon as they finish.
372
388
 
373
389
  interface AgentTeamOverrides {
374
390
  language: string;
@@ -380,6 +396,7 @@ interface AgentTeamOverrides {
380
396
  personaDelegateDepth: Record<string, number>;
381
397
  rulesDirs: string[];
382
398
  docsPaths: string[];
399
+ researchKeep: number;
383
400
  warnings: string[];
384
401
  }
385
402
 
@@ -393,6 +410,7 @@ const DEFAULT_OVERRIDES: AgentTeamOverrides = {
393
410
  personaDelegateDepth: {},
394
411
  rulesDirs: [],
395
412
  docsPaths: [],
413
+ researchKeep: DEFAULT_RESEARCH_KEEP,
396
414
  warnings: [],
397
415
  };
398
416
 
@@ -444,6 +462,14 @@ function parseAgentTeamOverrides(cwd: string): AgentTeamOverrides {
444
462
  if (key === "docs" && value) {
445
463
  result.docsPaths = value.split(",").map(s => s.trim()).filter(Boolean);
446
464
  }
465
+ if (key === "research-keep" && value) {
466
+ const keep = parseResearchKeep(value);
467
+ if (keep != null) {
468
+ result.researchKeep = keep;
469
+ } else {
470
+ result.warnings.push(`research-keep "${value}" is not a non-negative integer or "all" — using the default (${DEFAULT_RESEARCH_KEEP})`);
471
+ }
472
+ }
447
473
  const slug = "[a-z0-9]+(?:-[a-z0-9]+)*";
448
474
  const modelKey = key.match(new RegExp(`^model\\.(${slug})$`));
449
475
  if (modelKey && value) result.personaModels[modelKey[1]] = value;
@@ -1723,6 +1749,10 @@ export default function (pi: ExtensionAPI) {
1723
1749
  // alongside the standing team but renders in its own widget row.
1724
1750
  const researchStates: Map<number, ResearchState> = new Map();
1725
1751
  let nextResearchId = 1;
1752
+ // Retention cap for finished durable (manual/persona) helpers — set from the
1753
+ // overrides file's `research-keep:` key at session start (default 4, Infinity
1754
+ // for "all"). Ephemeral auto-pipe helpers ignore the cap: pruned on finish.
1755
+ let researchKeep = DEFAULT_RESEARCH_KEEP;
1726
1756
 
1727
1757
  // ── Execution history (/agents-history) ──────────
1728
1758
  // A tree of every dispatch: orchestrator (dispatcher) turns, the specialists they
@@ -3358,12 +3388,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3358
3388
  return ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "openrouter/google/gemini-3-flash-preview";
3359
3389
  }
3360
3390
 
3361
- function createResearchState(def: AgentDef, persona: boolean, model: string): ResearchState {
3391
+ function createResearchState(def: AgentDef, persona: boolean, model: string, ephemeral = false): ResearchState {
3362
3392
  const id = nextResearchId++;
3363
3393
  const state: ResearchState = {
3364
3394
  id,
3365
3395
  def,
3366
3396
  persona,
3397
+ ephemeral,
3367
3398
  model,
3368
3399
  status: "running",
3369
3400
  task: "",
@@ -3379,6 +3410,22 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3379
3410
  return state;
3380
3411
  }
3381
3412
 
3413
+ // Retention pass, run whenever a helper finishes: drop finished auto-pipe
3414
+ // helpers immediately (their findings persist as files under findings/, their
3415
+ // handles are never resumed) and finished durable helpers beyond the
3416
+ // `research-keep` most recent — so the research row doesn't grow without
3417
+ // bound. Running helpers are untouched; ids stay monotonic (no handle reuse).
3418
+ // /agents-history is unaffected: the timeline holds its own entries.
3419
+ function pruneResearch() {
3420
+ const ids = selectResearchPrunable(Array.from(researchStates.values()), researchKeep);
3421
+ if (ids.length === 0) return;
3422
+ for (const id of ids) {
3423
+ try { unlinkSync(researchSessionPath(id)); } catch {}
3424
+ researchStates.delete(id);
3425
+ }
3426
+ updateResearchWidget();
3427
+ }
3428
+
3382
3429
  // Env plumbing for spawned children: the shared exemptions file (both
3383
3430
  // damage-control variants honor pre-granted exemptions from it) and, when
3384
3431
  // coms is up, the endpoint damage-control-continue escalates blocked path
@@ -3480,11 +3527,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3480
3527
  // The process could not be spawned at all (proc `error` event).
3481
3528
  if (res.spawnError) {
3482
3529
  state.status = "error";
3530
+ state.finishedAt = Date.now();
3483
3531
  state.lastWork = `Error: ${res.spawnError}`;
3484
3532
  state.killedByOperator = false;
3485
3533
  updateResearchWidget();
3486
3534
  state.zoomRender?.(true);
3487
3535
  historyEnd(histEntry, "error");
3536
+ pruneResearch();
3488
3537
  return {
3489
3538
  output: `Error spawning research helper: ${res.spawnError}`,
3490
3539
  exitCode: 1,
@@ -3495,15 +3544,18 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3495
3544
  const full = res.output;
3496
3545
  const code = res.exitCode;
3497
3546
 
3498
- // Operator kill (via /research-rm or /research-clear). Resolve gracefully so
3499
- // a spawn_research tool call awaiting this helper doesn't hang.
3547
+ // Operator kill (via /agents-kill rN|all or its research-* aliases).
3548
+ // Resolve gracefully so a spawn_research tool call awaiting this helper
3549
+ // doesn't hang.
3500
3550
  if (state.killedByOperator) {
3501
3551
  state.killedByOperator = false;
3502
3552
  state.status = "idle";
3553
+ state.finishedAt = Date.now();
3503
3554
  state.lastWork = "(killed by operator)";
3504
3555
  updateResearchWidget();
3505
3556
  state.zoomRender?.(true);
3506
3557
  historyEnd(histEntry, "idle");
3558
+ pruneResearch();
3507
3559
  return {
3508
3560
  output: `Research helper r${state.id} was killed by the operator before it finished.`,
3509
3561
  exitCode: code ?? 143,
@@ -3512,11 +3564,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
3512
3564
  }
3513
3565
 
3514
3566
  state.status = code === 0 ? "done" : "error";
3567
+ state.finishedAt = Date.now();
3515
3568
  if (code === 0) state.sessionFile = sessionPath;
3516
3569
  state.lastWork = full.split("\n").filter((l: string) => l.trim()).pop() || "";
3517
3570
  updateResearchWidget();
3518
3571
  state.zoomRender?.(true);
3519
3572
  historyEnd(histEntry, state.status);
3573
+ pruneResearch();
3520
3574
 
3521
3575
  ctx.ui.notify(
3522
3576
  `Research r${state.id} ${state.status} in ${Math.round(state.elapsed / 1000)}s`,
@@ -4240,7 +4294,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
4240
4294
 
4241
4295
  const answered = await Promise.all(researchQs.map(async (q) => {
4242
4296
  const rDef = anonResearchDef();
4243
- const rState = createResearchState(rDef, false, resolveResearchModel(rDef, undefined, ctx));
4297
+ // Ephemeral: auto-pipe helpers are pruned as soon as they finish —
4298
+ // their findings persist as files, their rN handles are never resumed.
4299
+ const rState = createResearchState(rDef, false, resolveResearchModel(rDef, undefined, ctx), true);
4244
4300
  updateResearchWidget();
4245
4301
  const rRes = await spawnResearch(rState, q, ctx);
4246
4302
  const file = safePathWithin(findingsDir, `${agentKey}-r${rState.id}.md`);
@@ -5942,43 +5998,93 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5942
5998
  return filtered.length > 0 ? filtered : items;
5943
5999
  };
5944
6000
 
5945
- // /research-cont rN <prompt> — resume a finished helper on its existing session.
6001
+ // ── Unified subagent commands ────────────────
6002
+ // Team specialists are addressed by persona name, research helpers by their rN
6003
+ // handle — one command family covers both (mirroring /zoom's target resolution).
6004
+ // The research-* commands remain as aliases of their agents-* counterparts.
6005
+
6006
+ // Resume a finished helper on its existing session. Shared by /agents-cont and
6007
+ // its /research-cont alias.
6008
+ const researchContHandler = async (args: string | undefined, ctx: any) => {
6009
+ widgetCtx = ctx;
6010
+ const trimmed = (args ?? "").trim();
6011
+ const sp = trimmed.indexOf(" ");
6012
+ if (sp === -1) {
6013
+ ctx.ui.notify("Usage: /agents-cont rN <prompt>", "error");
6014
+ return;
6015
+ }
6016
+ const rid = parseResearchHandle(trimmed.slice(0, sp));
6017
+ const prompt = trimmed.slice(sp + 1).trim();
6018
+ const state = rid != null ? researchStates.get(rid) : undefined;
6019
+ if (!state) {
6020
+ ctx.ui.notify(`No research helper "${trimmed.slice(0, sp)}". Use /research to start one.`, "error");
6021
+ return;
6022
+ }
6023
+ if (!prompt) {
6024
+ ctx.ui.notify("Usage: /agents-cont rN <prompt>", "error");
6025
+ return;
6026
+ }
6027
+ if (state.status === "running") {
6028
+ ctx.ui.notify(`Research r${state.id} is still running — wait for it to finish.`, "warning");
6029
+ return;
6030
+ }
6031
+ state.turnCount++;
6032
+ updateResearchWidget();
6033
+ ctx.ui.notify(`Continuing research r${state.id} (Turn ${state.turnCount})…`, "info");
6034
+ spawnResearch(state, prompt, ctx).then(result => deliverResearchFollowUp(state, result));
6035
+ };
6036
+
6037
+ pi.registerCommand("agents-cont", {
6038
+ description: "Continue a finished research helper: /agents-cont rN <prompt>",
6039
+ getArgumentCompletions: researchHandleCompletions,
6040
+ handler: researchContHandler,
6041
+ });
6042
+
5946
6043
  pi.registerCommand("research-cont", {
5947
- description: "Continue a finished research helper: /research-cont rN <prompt>",
6044
+ description: "Continue a finished research helper (alias of /agents-cont): /research-cont rN <prompt>",
5948
6045
  getArgumentCompletions: researchHandleCompletions,
5949
- handler: async (args, ctx) => {
5950
- widgetCtx = ctx;
5951
- const trimmed = (args ?? "").trim();
5952
- const sp = trimmed.indexOf(" ");
5953
- if (sp === -1) {
5954
- ctx.ui.notify("Usage: /research-cont rN <prompt>", "error");
5955
- return;
5956
- }
5957
- const rid = parseResearchHandle(trimmed.slice(0, sp));
5958
- const prompt = trimmed.slice(sp + 1).trim();
5959
- const state = rid != null ? researchStates.get(rid) : undefined;
5960
- if (!state) {
5961
- ctx.ui.notify(`No research helper "${trimmed.slice(0, sp)}". Use /research to start one.`, "error");
5962
- return;
5963
- }
5964
- if (!prompt) {
5965
- ctx.ui.notify("Usage: /research-cont rN <prompt>", "error");
5966
- return;
5967
- }
5968
- if (state.status === "running") {
5969
- ctx.ui.notify(`Research r${state.id} is still running — wait for it to finish.`, "warning");
5970
- return;
5971
- }
5972
- state.turnCount++;
5973
- updateResearchWidget();
5974
- ctx.ui.notify(`Continuing research r${state.id} (Turn ${state.turnCount})…`, "info");
5975
- spawnResearch(state, prompt, ctx).then(result => deliverResearchFollowUp(state, result));
5976
- },
6046
+ handler: researchContHandler,
5977
6047
  });
5978
6048
 
5979
- // /research-rm rN — remove one helper (SIGTERM if running).
6049
+ // Remove one research helper (SIGTERM if running) — the state, its card, and
6050
+ // its session file. Team specialists are standing and cannot be removed.
6051
+ function removeResearchHelper(state: ResearchState, ctx: any) {
6052
+ if (state.proc && state.status === "running") {
6053
+ state.killedByOperator = true;
6054
+ state.proc.kill("SIGTERM");
6055
+ ctx.ui.notify(`Research r${state.id} killed and removed.`, "warning");
6056
+ } else {
6057
+ ctx.ui.notify(`Research r${state.id} removed.`, "info");
6058
+ }
6059
+ try { unlinkSync(researchSessionPath(state.id)); } catch {}
6060
+ researchStates.delete(state.id);
6061
+ updateResearchWidget();
6062
+ }
6063
+
6064
+ // Remove all helpers (SIGTERM any running). Shared by /agents-kill all and /research-clear.
6065
+ function clearResearchHelpers(ctx: any) {
6066
+ let killed = 0;
6067
+ const total = researchStates.size;
6068
+ for (const [, state] of Array.from(researchStates.entries())) {
6069
+ if (state.proc && state.status === "running") {
6070
+ state.killedByOperator = true;
6071
+ state.proc.kill("SIGTERM");
6072
+ killed++;
6073
+ }
6074
+ try { unlinkSync(researchSessionPath(state.id)); } catch {}
6075
+ }
6076
+ researchStates.clear();
6077
+ nextResearchId = 1;
6078
+ updateResearchWidget();
6079
+ const msg = total === 0
6080
+ ? "No research helpers to clear."
6081
+ : `Cleared ${total} research helper${total !== 1 ? "s" : ""}${killed > 0 ? ` (${killed} killed)` : ""}.`;
6082
+ ctx.ui.notify(msg, total === 0 ? "info" : "success");
6083
+ }
6084
+
6085
+ // /research-rm — alias of /agents-kill rN (kill on a research handle removes).
5980
6086
  pi.registerCommand("research-rm", {
5981
- description: "Remove a research helper (kill if running): /research-rm rN",
6087
+ description: "Remove a research helper (alias of /agents-kill rN): /research-rm rN",
5982
6088
  getArgumentCompletions: researchHandleCompletions,
5983
6089
  handler: async (args, ctx) => {
5984
6090
  widgetCtx = ctx;
@@ -5988,41 +6094,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
5988
6094
  ctx.ui.notify(`Usage: /research-rm rN. Known: ${Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ") || "none"}`, "error");
5989
6095
  return;
5990
6096
  }
5991
- if (state.proc && state.status === "running") {
5992
- state.killedByOperator = true;
5993
- state.proc.kill("SIGTERM");
5994
- ctx.ui.notify(`Research r${state.id} killed and removed.`, "warning");
5995
- } else {
5996
- ctx.ui.notify(`Research r${state.id} removed.`, "info");
5997
- }
5998
- try { unlinkSync(researchSessionPath(state.id)); } catch {}
5999
- researchStates.delete(state.id);
6000
- updateResearchWidget();
6097
+ removeResearchHelper(state, ctx);
6001
6098
  },
6002
6099
  });
6003
6100
 
6004
- // /research-clear — remove all helpers (SIGTERM any running).
6101
+ // /research-clear — alias of /agents-kill all.
6005
6102
  pi.registerCommand("research-clear", {
6006
- description: "Remove all research helpers",
6103
+ description: "Remove all research helpers (alias of /agents-kill all)",
6007
6104
  handler: async (_args, ctx) => {
6008
6105
  widgetCtx = ctx;
6009
- let killed = 0;
6010
- const total = researchStates.size;
6011
- for (const [, state] of Array.from(researchStates.entries())) {
6012
- if (state.proc && state.status === "running") {
6013
- state.killedByOperator = true;
6014
- state.proc.kill("SIGTERM");
6015
- killed++;
6016
- }
6017
- try { unlinkSync(researchSessionPath(state.id)); } catch {}
6018
- }
6019
- researchStates.clear();
6020
- nextResearchId = 1;
6021
- updateResearchWidget();
6022
- const msg = total === 0
6023
- ? "No research helpers to clear."
6024
- : `Cleared ${total} research helper${total !== 1 ? "s" : ""}${killed > 0 ? ` (${killed} killed)` : ""}.`;
6025
- ctx.ui.notify(msg, total === 0 ? "info" : "success");
6106
+ clearResearchHelpers(ctx);
6026
6107
  },
6027
6108
  });
6028
6109
 
@@ -6049,16 +6130,60 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6049
6130
  },
6050
6131
  });
6051
6132
 
6133
+ // Completions over both target kinds: team persona names + research handles
6134
+ // (rN), each annotated with status — for the unified /agents-kill and
6135
+ // /agents-restart.
6136
+ const subagentTargetCompletions = (prefix: string): AutocompleteItem[] | null => {
6137
+ const items = [...(agentNameCompletions("") ?? []), ...(researchHandleCompletions("") ?? [])];
6138
+ if (items.length === 0) return null;
6139
+ const filtered = items.filter(i => i.value.toLowerCase().startsWith(prefix.toLowerCase()));
6140
+ return filtered.length > 0 ? filtered : items;
6141
+ };
6142
+
6143
+ // /agents-kill completions additionally offer "all" (research helpers only).
6144
+ const agentsKillCompletions = (prefix: string): AutocompleteItem[] | null => {
6145
+ const targets = subagentTargetCompletions("") ?? [];
6146
+ const items = researchStates.size > 0
6147
+ ? [...targets, { value: "all", label: "all — kill & remove every research helper" }]
6148
+ : targets;
6149
+ if (items.length === 0) return null;
6150
+ const filtered = items.filter(i => i.value.toLowerCase().startsWith(prefix.toLowerCase()));
6151
+ return filtered.length > 0 ? filtered : items;
6152
+ };
6153
+
6052
6154
  pi.registerCommand("agents-kill", {
6053
- description: "Kill a running specialist: /agents-kill <name>",
6054
- getArgumentCompletions: agentNameCompletions,
6155
+ description: "Kill a running specialist, or kill & remove research helper(s): /agents-kill <name|rN|all>",
6156
+ getArgumentCompletions: agentsKillCompletions,
6055
6157
  handler: async (args, ctx) => {
6056
6158
  widgetCtx = ctx;
6057
6159
  const name = args?.trim();
6160
+ // "all" clears every research helper (kill any running). Team specialists
6161
+ // are standing — never touched by "all".
6162
+ if (name?.toLowerCase() === "all") {
6163
+ clearResearchHelpers(ctx);
6164
+ return;
6165
+ }
6166
+ // An rN handle targets a research helper. Research helpers are disposable
6167
+ // by design, so kill also REMOVES — the card, the state, and the session
6168
+ // file go with the process (a finished helper is simply removed).
6169
+ const rid = name ? parseResearchHandle(name) : null;
6170
+ if (rid != null) {
6171
+ const rState = researchStates.get(rid);
6172
+ if (!rState) {
6173
+ const known = Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ");
6174
+ ctx.ui.notify(`No research helper "${name}". Known: ${known || "none"}`, "error");
6175
+ return;
6176
+ }
6177
+ removeResearchHelper(rState, ctx);
6178
+ return;
6179
+ }
6058
6180
  const state = name ? agentStates.get(name.toLowerCase()) : undefined;
6059
6181
  if (!state) {
6060
- const known = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
6061
- ctx.ui.notify(`Usage: /agents-kill <name>. Known: ${known || "none"}`, "error");
6182
+ const known = [
6183
+ ...Array.from(agentStates.values()).map(s => displayName(s.def.name)),
6184
+ ...Array.from(researchStates.values()).map(s => `r${s.id}`),
6185
+ ].join(", ");
6186
+ ctx.ui.notify(`Usage: /agents-kill <name|rN|all>. Known: ${known || "none"}`, "error");
6062
6187
  return;
6063
6188
  }
6064
6189
  if (state.status !== "running" || (!state.proc && !state.comsAbort)) {
@@ -6082,15 +6207,45 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
6082
6207
  });
6083
6208
 
6084
6209
  pi.registerCommand("agents-restart", {
6085
- description: "Kill and re-run a specialist's last task fresh: /agents-restart <name>",
6086
- getArgumentCompletions: agentNameCompletions,
6210
+ description: "Kill and re-run a specialist's (or re-run a finished research helper's) last task fresh: /agents-restart <name|rN>",
6211
+ getArgumentCompletions: subagentTargetCompletions,
6087
6212
  handler: async (args, ctx) => {
6088
6213
  widgetCtx = ctx;
6089
6214
  const name = args?.trim();
6215
+ // An rN handle re-runs a finished helper's last task on a fresh session
6216
+ // (unlike /agents-cont, which resumes the existing one). A running helper
6217
+ // can't be restarted mid-flight — spawnResearch's promise is held by its
6218
+ // original caller, and /agents-kill removes the helper outright.
6219
+ const rid = name ? parseResearchHandle(name) : null;
6220
+ if (rid != null) {
6221
+ const rState = researchStates.get(rid);
6222
+ if (!rState) {
6223
+ const known = Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ");
6224
+ ctx.ui.notify(`No research helper "${name}". Known: ${known || "none"}`, "error");
6225
+ return;
6226
+ }
6227
+ if (rState.status === "running") {
6228
+ ctx.ui.notify(`Research r${rState.id} is still running — wait for it to finish (or /agents-kill r${rState.id} to discard it and /research the task again).`, "warning");
6229
+ return;
6230
+ }
6231
+ if (!rState.task) {
6232
+ ctx.ui.notify(`Research r${rState.id} has no previous task to restart.`, "warning");
6233
+ return;
6234
+ }
6235
+ rState.sessionFile = null;
6236
+ rState.turnCount = 1;
6237
+ updateResearchWidget();
6238
+ ctx.ui.notify(`Restarting research r${rState.id} (fresh)...`, "info");
6239
+ spawnResearch(rState, rState.task, ctx).then(result => deliverResearchFollowUp(rState, result));
6240
+ return;
6241
+ }
6090
6242
  const state = name ? agentStates.get(name.toLowerCase()) : undefined;
6091
6243
  if (!state) {
6092
- const known = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
6093
- ctx.ui.notify(`Usage: /agents-restart <name>. Known: ${known || "none"}`, "error");
6244
+ const known = [
6245
+ ...Array.from(agentStates.values()).map(s => displayName(s.def.name)),
6246
+ ...Array.from(researchStates.values()).map(s => `r${s.id}`),
6247
+ ].join(", ");
6248
+ ctx.ui.notify(`Usage: /agents-restart <name|rN>. Known: ${known || "none"}`, "error");
6094
6249
  return;
6095
6250
  }
6096
6251
  const task = state.task;
@@ -6745,6 +6900,7 @@ ${researchCatalog}`;
6745
6900
  // Load per-project overrides (user-facing language, persona gate, models).
6746
6901
  const overrides = parseAgentTeamOverrides(_ctx.cwd);
6747
6902
  userLanguage = overrides.language;
6903
+ researchKeep = overrides.researchKeep;
6748
6904
  if (overrides.warnings.length > 0) {
6749
6905
  _ctx.ui.notify(`agent-fleet-overrides warnings:\n${overrides.warnings.join("\n")}`, "warning");
6750
6906
  }
@@ -0,0 +1,34 @@
1
+ // Retention policy for finished research helpers. The hub keeps every helper's
2
+ // card (and resumable session) in memory until something removes it; this module
3
+ // decides which finished helpers to drop so the research row doesn't grow without
4
+ // bound over a long session. Pure — the hub owns the actual state map, session
5
+ // files, and widget refresh.
6
+
7
+ export const DEFAULT_RESEARCH_KEEP = 4;
8
+
9
+ // Parse the `research-keep` override value: "all" disables pruning of durable
10
+ // helpers, a non-negative integer keeps that many most-recently-finished ones.
11
+ // Returns null for anything else (caller warns and keeps the default).
12
+ export function parseResearchKeep(value) {
13
+ const v = String(value ?? "").trim().toLowerCase();
14
+ if (v === "all") return Infinity;
15
+ if (/^\d+$/.test(v)) return Number(v);
16
+ return null;
17
+ }
18
+
19
+ // Decide which helper ids to drop. `states`: [{ id, status, finishedAt, ephemeral }].
20
+ // Running helpers are never dropped. Finished ephemeral helpers (auto-research
21
+ // pipe spawns — their findings persist as files under findings/ and their handles
22
+ // are never resumed) are always dropped. Finished durable helpers beyond the
23
+ // `keep` most recently finished are dropped, oldest first.
24
+ export function selectResearchPrunable(states, keep) {
25
+ const capped = keep >= 0 ? keep : DEFAULT_RESEARCH_KEEP;
26
+ const finished = (states || []).filter((s) => s.status !== "running");
27
+ const ephemeral = finished.filter((s) => s.ephemeral).map((s) => s.id);
28
+ const durable = finished
29
+ .filter((s) => !s.ephemeral)
30
+ .sort((a, b) => (b.finishedAt ?? 0) - (a.finishedAt ?? 0));
31
+ // slice(Infinity) → [] — "all" keeps every durable helper.
32
+ const overflow = durable.slice(capped).map((s) => s.id);
33
+ return [...ephemeral, ...overflow];
34
+ }
@@ -2,9 +2,17 @@
2
2
 
3
3
  Harness wrapper for `pi-ask-user` that preserves the stock `ask_user` UI and result shape while optionally racing it against the Hermes `user-remote` coms peer.
4
4
 
5
+ The experimental Codex Remote-Control conductor is **not** an inbound `ask_user` route. It initiates approval-gated outbound delegation from Android; Hermes remains the only phone answer participant in this race. See the [Codex conductor runbook](../../../docs/codex-remote-conductor.md).
6
+
5
7
  - The stock `pi-ask-user` extension is loaded through a capture proxy; its `ask_user` tool is not registered directly.
6
8
  - If no live `user-remote` peer is present at call time, the wrapper calls stock `execute` with the original arguments and signal unchanged.
7
9
  - If `user-remote` is present, the wrapper races local stock UI against the remote coms request using `race-core.js`; first answer wins and local-first emits one best-effort cancel.
8
10
  - If another extension already registered `ask_user`, registration failure is caught and logged as a warning instead of crashing the session.
9
11
 
12
+ ## Double-load protection
13
+
14
+ Do **not** also list `npm:pi-ask-user` in pi settings `packages` (project `.pi/settings.json` or global `~/.pi/agent/settings.json`) — the harness loads the stock extension itself. A settings-listed copy is loaded by pi core outside the harness's control, and if the harness happened to register `ask_user` first, pi core would hard-crash the session with `Tool "ask_user" conflicts` while loading the package (load order between the two is a race).
15
+
16
+ The harness defends against this with a startup preflight: it scans both settings files for a `pi-ask-user` package entry, and if one is found it logs a warning and skips registering its wrapper entirely, so the stock package registers alone and the session survives regardless of load order. The cost is that remote answer racing is disabled until the entry is removed — the warning says so. The try/catch on registration remains as the second layer for the package-first order (or any other extension owning `ask_user`).
17
+
10
18
  Tests use fakes for the stock TUI and coms peer. The abort test proves signal propagation and the stock-shaped `{cancelled:true}` result through a fake captured tool; it does not drive a live TUI overlay.
@@ -6,6 +6,8 @@
6
6
  // peer is live, it races the stock local UI against a remote coms round trip.
7
7
 
8
8
  import * as fs from "node:fs";
9
+ import * as os from "node:os";
10
+ import * as path from "node:path";
9
11
 
10
12
  import { raceAskUser } from "./race-core.js";
11
13
 
@@ -26,6 +28,37 @@ interface InstallOptions {
26
28
  cancelRemote?: (qid: string, reason: string) => Promise<void> | void;
27
29
  warn?: (message: string) => void;
28
30
  createAbortController?: () => AbortController;
31
+ settingsPaths?: string[];
32
+ }
33
+
34
+ // A stock `pi-ask-user` package listed in pi settings is loaded by pi core
35
+ // itself, outside this harness's try/catch. If the harness registers `ask_user`
36
+ // first, the package's later registration makes pi core hard-crash the session
37
+ // with a tool-name conflict. The preflight below detects that configuration and
38
+ // skips the wrapper entirely, so the stock package registers alone regardless
39
+ // of load order.
40
+ const STOCK_PACKAGE_PATTERN = /(^|[/:])pi-ask-user(@[^/]*)?$/;
41
+
42
+ export function defaultSettingsPaths(): string[] {
43
+ return [
44
+ path.join(process.cwd(), ".pi", "settings.json"),
45
+ path.join(os.homedir(), ".pi", "agent", "settings.json"),
46
+ ];
47
+ }
48
+
49
+ export function findStockAskUserPackageEntry(settingsPaths: string[]): { entry: string; settingsPath: string } | null {
50
+ for (const settingsPath of settingsPaths) {
51
+ let packages: unknown;
52
+ try {
53
+ packages = JSON.parse(fs.readFileSync(settingsPath, "utf8"))?.packages;
54
+ } catch {
55
+ continue;
56
+ }
57
+ if (!Array.isArray(packages)) continue;
58
+ const entry = packages.find((pkg) => typeof pkg === "string" && STOCK_PACKAGE_PATTERN.test(pkg));
59
+ if (entry) return { entry, settingsPath };
60
+ }
61
+ return null;
29
62
  }
30
63
 
31
64
  export function captureAskUserTool(stockFactory: (pi: ExtensionLike) => void, pi: ExtensionLike): ToolRegistration {
@@ -228,6 +261,13 @@ export function wrapAskUserTool(stockTool: ToolRegistration, options: InstallOpt
228
261
  }
229
262
 
230
263
  export function installAskUserRemote(pi: ExtensionLike, options: InstallOptions = {}): { registered: boolean; tool?: ToolRegistration } {
264
+ if (options.settingsPaths) {
265
+ const listed = findStockAskUserPackageEntry(options.settingsPaths);
266
+ if (listed) {
267
+ warn(pi, options, `ask-user-remote: "${listed.entry}" is listed in ${listed.settingsPath} "packages"; skipping the ask_user wrapper so the stock package registers without a tool conflict (remote answer racing disabled). Remove the entry — this harness loads pi-ask-user itself.`);
268
+ return { registered: false };
269
+ }
270
+ }
231
271
  if (!options.stockFactory) throw new Error("ask-user-remote: stockFactory is required for synchronous install");
232
272
  const stockTool = captureAskUserTool(options.stockFactory, pi);
233
273
  const wrapped = wrapAskUserTool(stockTool, options);
@@ -248,6 +288,6 @@ async function loadStockFactory(): Promise<(pi: ExtensionLike) => void> {
248
288
 
249
289
  export default function askUserRemote(pi: ExtensionLike): void {
250
290
  void loadStockFactory()
251
- .then((stockFactory) => installAskUserRemote(pi, { stockFactory }))
291
+ .then((stockFactory) => installAskUserRemote(pi, { stockFactory, settingsPaths: defaultSettingsPaths() }))
252
292
  .catch((error) => warn(pi, {}, `ask-user-remote: failed to load pi-ask-user (${error instanceof Error ? error.message : String(error)})`));
253
293
  }
@@ -41,6 +41,17 @@ when you are on the herdr backend.
41
41
  - `coms_list` / `coms_send` / `coms_get` / `coms_await` tools — discover peers and
42
42
  exchange messages
43
43
 
44
+ ## External conductors
45
+
46
+ Two optional phone-facing conductors use this same pool without becoming pane owners:
47
+
48
+ - **Hermes/Telegram** is the inbound `ask_user` route and can also perform bounded coms delegation.
49
+ - **Codex Remote Control** is an experimental outbound-only Android route. Its user-systemd service loads a managed contract from an external user-state workspace, and `scripts/codex-conductor.ts` permits only scoped `list` plus one serialized `send --await`. See the [operator runbook](../../../docs/codex-remote-conductor.md).
50
+
51
+ Both must use the same validated project as the peers they target. Neither conductor may drive Herdr lifecycle.
52
+
53
+ Standalone `coms-cli` queues are project-scoped under `~/.pi/coms/cli/projects/<project>/<name>/`. Legacy name-only queues fail closed until an operator assigns and moves the complete queue; `projects` is a reserved identity name.
54
+
44
55
  ## Pool scope is the reach boundary
45
56
 
46
57
  The pool widget defines who you can reach: `coms_list` and `coms_send` resolve targets through one
@@ -10,6 +10,6 @@ Also flag and offer to rewrite any remaining YAML configs (`teams.yaml`, `peers.
10
10
 
11
11
  Also validate `.ai/agent-fleet-overrides.md` when it exists, against the schema in `docs/agent-fleet-setup.md`: unknown sections, unknown keys in known sections, invalid values for the mechanically parsed `agent-hub` keys, missing `rules:` folders, and `## env` `required:` names that are neither set nor declared in the root `.env`. These findings are advisory only — report them with fix "edit by hand", never edit the overrides file.
12
12
 
13
- Present findings as a `# | Path | Issue | Suggested fix` table and ask the user to pick which fixes to apply.
13
+ Present the findings per the skill's Step 1 interaction contract: print a short text summary (counts per kind, advisory findings as report-only text), then ask one `ask_user` multi-select — *"Which fixes should I apply now?"* — each option titled `<path> — <issue>` with the proposed fix as its description, chunked at ≤ 9 options; empty selection or cancel applies nothing. Without the widget, print a `# | Path | Issue | Suggested fix` table instead and take the picks as text.
14
14
 
15
15
  Never overwrite a regular file — only act on symlinks whose target is missing. Report `repaired`, `deleted`, and `skipped` counts, and append a `## doctor-runs` line to `.ai/agent-fleet-setup.md` with the date, agent, phase (`standalone`), and counts.