@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.10

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 (186) hide show
  1. package/README.md +146 -177
  2. package/dist/agent/channel-runner.d.ts +28 -0
  3. package/dist/agent/channel-runner.js +293 -145
  4. package/dist/agent/commands.d.ts +7 -1
  5. package/dist/agent/commands.js +26 -0
  6. package/dist/agent/index.d.ts +1 -1
  7. package/dist/agent/index.js +1 -1
  8. package/dist/agent/job-manager.d.ts +34 -6
  9. package/dist/agent/job-manager.js +73 -7
  10. package/dist/agent/progress-formatter.js +3 -3
  11. package/dist/agent/prompt/sections.js +46 -7
  12. package/dist/agent/prompt/types.d.ts +9 -0
  13. package/dist/agent/run-queue.d.ts +10 -1
  14. package/dist/agent/run-queue.js +19 -2
  15. package/dist/agent/runner-factory.d.ts +16 -4
  16. package/dist/agent/runner-factory.js +9 -23
  17. package/dist/agent/session-events.js +7 -42
  18. package/dist/agent/session-resource-gate.d.ts +17 -0
  19. package/dist/agent/session-resource-gate.js +33 -2
  20. package/dist/agent/status-render.js +1 -3
  21. package/dist/agent/turn-recovery.d.ts +72 -0
  22. package/dist/agent/turn-recovery.js +193 -0
  23. package/dist/agent/types.d.ts +21 -1
  24. package/dist/agent/types.js +3 -16
  25. package/dist/index.d.ts +2 -1
  26. package/dist/index.js +2 -1
  27. package/dist/main.js +2 -1
  28. package/dist/memory/extraction.js +0 -1
  29. package/dist/memory/maintenance-gates.d.ts +1 -1
  30. package/dist/memory/maintenance-jobs.js +2 -3
  31. package/dist/memory/metadata.d.ts +0 -15
  32. package/dist/memory/metadata.js +0 -7
  33. package/dist/memory/probation.d.ts +1 -5
  34. package/dist/memory/probation.js +2 -6
  35. package/dist/memory/review-log.js +0 -0
  36. package/dist/memory/scheduler.d.ts +1 -0
  37. package/dist/memory/scheduler.js +64 -6
  38. package/dist/models/auth-cli.d.ts +1 -1
  39. package/dist/models/auth-cli.js +3 -2
  40. package/dist/paths.d.ts +0 -6
  41. package/dist/paths.js +0 -6
  42. package/dist/playbooks/agent-delegation.md +48 -22
  43. package/dist/playbooks/background-jobs.md +1 -1
  44. package/dist/playbooks/catalog.d.ts +2 -2
  45. package/dist/playbooks/catalog.js +20 -9
  46. package/dist/playbooks/event-scheduling.md +1 -1
  47. package/dist/playbooks/memory-and-learning.md +1 -1
  48. package/dist/playbooks/outbound-media.md +5 -5
  49. package/dist/playbooks/runtime-orientation.md +8 -3
  50. package/dist/playbooks/task-driving.md +1 -1
  51. package/dist/playbooks/task-planning.md +1 -1
  52. package/dist/runtime/active-session-store.d.ts +42 -0
  53. package/dist/runtime/active-session-store.js +100 -0
  54. package/dist/runtime/app-home.d.ts +32 -0
  55. package/dist/runtime/app-home.js +319 -0
  56. package/dist/runtime/bootstrap.d.ts +30 -36
  57. package/dist/runtime/bootstrap.js +359 -473
  58. package/dist/runtime/channel-event.d.ts +41 -0
  59. package/dist/runtime/channel-event.js +1 -0
  60. package/dist/runtime/delivery.d.ts +3 -2
  61. package/dist/runtime/delivery.js +11 -6
  62. package/dist/runtime/dingtalk.d.ts +16 -28
  63. package/dist/runtime/dingtalk.js +6 -10
  64. package/dist/runtime/durable-dispatch.d.ts +8 -2
  65. package/dist/runtime/durable-dispatch.js +52 -25
  66. package/dist/runtime/events.d.ts +3 -2
  67. package/dist/runtime/events.js +2 -3
  68. package/dist/runtime/project-commands.d.ts +16 -0
  69. package/dist/runtime/project-commands.js +112 -0
  70. package/dist/runtime/project-scope-store.d.ts +31 -0
  71. package/dist/runtime/project-scope-store.js +102 -0
  72. package/dist/runtime/store.d.ts +7 -0
  73. package/dist/runtime/subagent-commands.d.ts +17 -0
  74. package/dist/runtime/subagent-commands.js +360 -0
  75. package/dist/runtime/task-commands.js +7 -3
  76. package/dist/runtime/task-driver.d.ts +7 -7
  77. package/dist/runtime/task-driver.js +1 -4
  78. package/dist/runtime/task-migration.js +1 -1
  79. package/dist/runtime/task-wake.d.ts +54 -0
  80. package/dist/runtime/task-wake.js +99 -0
  81. package/dist/security/config.js +10 -0
  82. package/dist/security/logger.js +10 -1
  83. package/dist/security/path-guard.js +34 -9
  84. package/dist/security/project-scope.d.ts +45 -0
  85. package/dist/security/project-scope.js +107 -0
  86. package/dist/security/types.d.ts +37 -3
  87. package/dist/settings.d.ts +0 -106
  88. package/dist/settings.js +0 -224
  89. package/dist/shared/host-process.d.ts +37 -0
  90. package/dist/shared/host-process.js +112 -0
  91. package/dist/shared/jsonl-appender.d.ts +2 -0
  92. package/dist/shared/jsonl-appender.js +25 -13
  93. package/dist/shared/shell-words.d.ts +9 -0
  94. package/dist/shared/shell-words.js +52 -0
  95. package/dist/shared/types.d.ts +1 -0
  96. package/dist/shared/types.js +10 -1
  97. package/dist/shared/wake-claim.d.ts +23 -0
  98. package/dist/shared/wake-claim.js +26 -0
  99. package/dist/shared/with-timeout.d.ts +14 -0
  100. package/dist/shared/with-timeout.js +38 -0
  101. package/dist/subagents/detached-discovery.d.ts +13 -0
  102. package/dist/subagents/detached-discovery.js +17 -0
  103. package/dist/subagents/discovery.d.ts +74 -1
  104. package/dist/subagents/discovery.js +429 -82
  105. package/dist/subagents/external/claude-code.d.ts +2 -0
  106. package/dist/subagents/external/claude-code.js +158 -0
  107. package/dist/subagents/external/codex-cli.d.ts +2 -0
  108. package/dist/subagents/external/codex-cli.js +133 -0
  109. package/dist/subagents/external/exec.d.ts +2 -0
  110. package/dist/subagents/external/exec.js +44 -0
  111. package/dist/subagents/external/harness.d.ts +121 -0
  112. package/dist/subagents/external/harness.js +109 -0
  113. package/dist/subagents/external/registry.d.ts +2 -0
  114. package/dist/subagents/external/registry.js +11 -0
  115. package/dist/subagents/external/run.d.ts +74 -0
  116. package/dist/subagents/external/run.js +286 -0
  117. package/dist/subagents/external/settlement.d.ts +50 -0
  118. package/dist/subagents/external/settlement.js +123 -0
  119. package/dist/subagents/format.d.ts +16 -0
  120. package/dist/subagents/format.js +31 -0
  121. package/dist/subagents/runs.d.ts +342 -0
  122. package/dist/subagents/runs.js +909 -0
  123. package/dist/subagents/tool.d.ts +68 -6
  124. package/dist/subagents/tool.js +547 -206
  125. package/dist/subagents/verification-outcome.d.ts +26 -0
  126. package/dist/subagents/verification-outcome.js +16 -0
  127. package/dist/subagents/workspace-lease.d.ts +45 -0
  128. package/dist/subagents/workspace-lease.js +61 -0
  129. package/dist/tasks/artifact-subject.js +50 -2
  130. package/dist/tasks/control.d.ts +12 -0
  131. package/dist/tasks/control.js +20 -0
  132. package/dist/tasks/ledger.js +1 -1
  133. package/dist/tasks/store.d.ts +21 -0
  134. package/dist/tasks/store.js +80 -0
  135. package/dist/{shared → tasks}/task-schedule.js +1 -1
  136. package/dist/tasks/verification.d.ts +8 -0
  137. package/dist/tasks/verification.js +10 -2
  138. package/dist/tools/bash.js +4 -4
  139. package/dist/tools/edit.js +3 -3
  140. package/dist/tools/event-manage.js +1 -4
  141. package/dist/tools/grep.js +5 -6
  142. package/dist/tools/index.d.ts +4 -1
  143. package/dist/tools/index.js +25 -3
  144. package/dist/tools/job.js +5 -5
  145. package/dist/tools/memory-manage.js +3 -7
  146. package/dist/tools/read.js +3 -3
  147. package/dist/tools/registry.js +2 -1
  148. package/dist/tools/send-media.js +2 -2
  149. package/dist/tools/session-search.js +0 -1
  150. package/dist/tools/skill-manage.js +3 -3
  151. package/dist/tools/subagent-manage.d.ts +37 -0
  152. package/dist/tools/subagent-manage.js +245 -0
  153. package/dist/tools/task-manage/shared.js +2 -2
  154. package/dist/tools/task-manage.js +1 -4
  155. package/dist/tools/tool-details.d.ts +1 -1
  156. package/dist/tools/web-fetch.js +0 -1
  157. package/dist/tools/write-content.js +3 -3
  158. package/dist/tui/app.d.ts +1 -1
  159. package/dist/tui/app.js +55 -6
  160. package/dist/tui/cli.d.ts +1 -1
  161. package/dist/tui/cli.js +1 -1
  162. package/dist/tui/commands.d.ts +2 -0
  163. package/dist/tui/commands.js +4 -0
  164. package/dist/tui/terminal-media-sender.d.ts +1 -1
  165. package/dist/tui/turn-controller.d.ts +2 -0
  166. package/dist/tui/turn-controller.js +2 -0
  167. package/dist/usage/ledger.d.ts +13 -0
  168. package/dist/usage/ledger.js +15 -2
  169. package/dist/usage/render.js +22 -0
  170. package/examples/sub-agents/README.md +75 -14
  171. package/examples/sub-agents/builder-hard.md +46 -0
  172. package/examples/sub-agents/builder.md +42 -0
  173. package/examples/sub-agents/documenter.md +50 -0
  174. package/examples/sub-agents/explorer.md +16 -13
  175. package/examples/sub-agents/git-committer.md +33 -40
  176. package/examples/sub-agents/log-sifter.md +46 -0
  177. package/examples/sub-agents/planner.md +42 -0
  178. package/examples/sub-agents/reviewer.md +31 -41
  179. package/examples/sub-agents/scout.md +30 -0
  180. package/examples/sub-agents/verifier.md +27 -37
  181. package/examples/sub-agents/worker.md +35 -0
  182. package/package.json +1 -1
  183. package/examples/sub-agents/researcher.md +0 -41
  184. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  185. /package/dist/{shared → tasks}/task-events.js +0 -0
  186. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -1,2 +1,2 @@
1
- export { getOrCreateRunner } from "./runner-factory.js";
1
+ export { createRunner } from "./runner-factory.js";
2
2
  export type { AgentRunner } from "./types.js";
@@ -1 +1 @@
1
- export { getOrCreateRunner } from "./runner-factory.js";
1
+ export { createRunner } from "./runner-factory.js";
@@ -1,5 +1,5 @@
1
1
  import type { Executor } from "../executor.js";
2
- import type { DingTalkEvent } from "../runtime/dingtalk.js";
2
+ import type { ChannelEvent } from "../runtime/channel-event.js";
3
3
  /**
4
4
  * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
5
5
  * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
@@ -24,6 +24,9 @@ export interface JobSnapshot {
24
24
  startedAt: number;
25
25
  durationMs: number;
26
26
  exitCode?: number;
27
+ /** The task this job's completion wake belongs to, if any — lets a caller verify that a
28
+ * `[JOB:<id>] ... belongs to task <taskId>.` wake actually names the job it claims to (T9). */
29
+ taskId?: string;
27
30
  }
28
31
  /** What should happen when the job finishes. */
29
32
  export interface JobWakeContract {
@@ -32,6 +35,19 @@ export interface JobWakeContract {
32
35
  /** The task this job is advancing, surfaced in the wake so the model lands in context. */
33
36
  taskId?: string;
34
37
  }
38
+ interface JobRecord extends JobSnapshot {
39
+ pid: number;
40
+ spillFile: string;
41
+ exitFile: string;
42
+ timeoutSeconds: number;
43
+ contract: JobWakeContract;
44
+ /** When the job reached a terminal status; drives retention of the record and spill file. */
45
+ finishedAt?: number;
46
+ /** Set once the completion wake has been dispatched, so a restart cannot re-announce it. */
47
+ notified?: boolean;
48
+ wakeClaimDispatchId?: string;
49
+ wakeConsumedAt?: number;
50
+ }
35
51
  export interface JobStartOptions {
36
52
  signal?: AbortSignal;
37
53
  notify?: boolean;
@@ -41,7 +57,7 @@ export interface JobManagerOptions {
41
57
  /** Directory for this channel's persisted job records. Omit to run without persistence. */
42
58
  stateDir?: string;
43
59
  /** Delivers the completion wake. Omit to disable waking (sub-agent and test paths). */
44
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
60
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
45
61
  sweepIntervalMs?: number;
46
62
  }
47
63
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
@@ -66,6 +82,7 @@ export declare class ChannelJobManager {
66
82
  private readonly channelId;
67
83
  private readonly executor;
68
84
  private readonly jobs;
85
+ private readonly wakeQueue;
69
86
  private sweepTimer?;
70
87
  private garbageCollectionTimer?;
71
88
  private sweeping;
@@ -89,6 +106,7 @@ export declare class ChannelJobManager {
89
106
  private scheduleGarbageCollection;
90
107
  get channel(): string;
91
108
  runningCount(): number;
109
+ listRunning(): JobRecord[];
92
110
  /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
93
111
  runningTaskIds(): Set<string>;
94
112
  /**
@@ -124,13 +142,17 @@ export declare class ChannelJobManager {
124
142
  /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
125
143
  private finish;
126
144
  /**
127
- * Wake the channel for a finished job. `notified` is persisted before anything else can run
128
- * again, so a restart mid-announce cannot produce a second wake; the dispatch id is stable for
129
- * the same reason (spec 031, D1).
145
+ * Wake the channel for a finished job. `dispatch()` durably persists its own pending record
146
+ * (and is idempotent on dispatch id) before this call can be interrupted, so it is safe to call
147
+ * again after a crash; `notified` is only persisted *after* it returns, so a crash between the
148
+ * two can only cause a redelivery, never a lost wake (spec 040, D7 — this reorders a prior
149
+ * version that persisted `notified` first, which could crash-lose the wake entirely).
130
150
  */
131
151
  private announce;
132
152
  private kill;
133
153
  list(signal?: AbortSignal): Promise<JobSnapshot[]>;
154
+ beginWakeConsumption(id: string, taskId: string, dispatchId: string): Promise<boolean>;
155
+ finishWakeConsumption(id: string, dispatchId: string): Promise<void>;
134
156
  cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
135
157
  id: string;
136
158
  status: JobStatus | "not_found";
@@ -158,7 +180,7 @@ export declare class ChannelJobManager {
158
180
  interface JobRuntimeConfig {
159
181
  /** Root of the per-channel record directories (`<jobsStateDir>/<channelId>/`). */
160
182
  jobsStateDir?: string;
161
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
183
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
162
184
  }
163
185
  /**
164
186
  * Give background jobs their persistence root and their way to wake a channel. Called once from
@@ -174,6 +196,12 @@ export declare function configureJobRuntime(config: JobRuntimeConfig): void;
174
196
  * manager simply has no jobs, and the empty set is the right answer.
175
197
  */
176
198
  export declare function channelJobTaskIds(channelId: string): Set<string>;
199
+ /**
200
+ * Human-readable lines naming this channel's currently running background jobs, for the `/project
201
+ * set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no
202
+ * jobs" reasoning, so it needs no `Executor` either.
203
+ */
204
+ export declare function channelRunningJobLines(channelId: string): string[];
177
205
  export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
178
206
  /**
179
207
  * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
@@ -4,9 +4,11 @@ import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import * as log from "../log.js";
6
6
  import { writeFileAtomically } from "../shared/atomic-file.js";
7
+ import { createSerialQueue } from "../shared/serial-queue.js";
7
8
  import { shellEscape } from "../shared/shell-escape.js";
8
9
  import { errorMessage } from "../shared/text-utils.js";
9
10
  import { isRecord } from "../shared/type-guards.js";
11
+ import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
10
12
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
11
13
  export const MAX_RUNNING_JOBS = 5;
12
14
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
@@ -67,6 +69,7 @@ function toSnapshot(record) {
67
69
  startedAt: record.startedAt,
68
70
  durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
69
71
  exitCode: record.exitCode,
72
+ taskId: record.contract.taskId,
70
73
  };
71
74
  }
72
75
  export class ChannelJobManager {
@@ -74,6 +77,7 @@ export class ChannelJobManager {
74
77
  this.channelId = channelId;
75
78
  this.executor = executor;
76
79
  this.jobs = new Map();
80
+ this.wakeQueue = createSerialQueue();
77
81
  this.sweeping = false;
78
82
  // A bare number keeps the original `sweepIntervalMs` positional form working for tests.
79
83
  this.options = typeof options === "number" ? { sweepIntervalMs: options } : options;
@@ -83,7 +87,7 @@ export class ChannelJobManager {
83
87
  return this.options.stateDir ? join(this.options.stateDir, `${id}.json`) : undefined;
84
88
  }
85
89
  /** Mirror a record to disk. Persistence is best-effort: it must never fail a job operation. */
86
- async persist(record) {
90
+ async persist(record, required = false) {
87
91
  const path = this.recordPath(record.id);
88
92
  if (!path)
89
93
  return;
@@ -93,6 +97,8 @@ export class ChannelJobManager {
93
97
  await chmod(path, 0o600).catch(() => undefined);
94
98
  }
95
99
  catch (error) {
100
+ if (required)
101
+ throw error;
96
102
  log.logWarning(`Failed to persist background job ${record.id}`, errorMessage(error));
97
103
  }
98
104
  }
@@ -144,6 +150,9 @@ export class ChannelJobManager {
144
150
  runningCount() {
145
151
  return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
146
152
  }
153
+ listRunning() {
154
+ return Array.from(this.jobs.values()).filter((job) => job.status === "running");
155
+ }
147
156
  /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
148
157
  runningTaskIds() {
149
158
  const ids = new Set();
@@ -324,16 +333,16 @@ export class ChannelJobManager {
324
333
  this.scheduleGarbageCollection();
325
334
  }
326
335
  /**
327
- * Wake the channel for a finished job. `notified` is persisted before anything else can run
328
- * again, so a restart mid-announce cannot produce a second wake; the dispatch id is stable for
329
- * the same reason (spec 031, D1).
336
+ * Wake the channel for a finished job. `dispatch()` durably persists its own pending record
337
+ * (and is idempotent on dispatch id) before this call can be interrupted, so it is safe to call
338
+ * again after a crash; `notified` is only persisted *after* it returns, so a crash between the
339
+ * two can only cause a redelivery, never a lost wake (spec 040, D7 — this reorders a prior
340
+ * version that persisted `notified` first, which could crash-lose the wake entirely).
330
341
  */
331
342
  async announce(record, signal) {
332
343
  if (!this.options.dispatch || !record.contract.notify || record.notified) {
333
344
  return;
334
345
  }
335
- record.notified = true;
336
- await this.persist(record);
337
346
  const output = await this.readOutput(record.id, signal);
338
347
  const tail = output?.text.slice(-WAKE_OUTPUT_TAIL_BYTES).trim();
339
348
  const exit = record.exitCode !== undefined ? `exit ${record.exitCode}` : record.status;
@@ -350,16 +359,28 @@ export class ChannelJobManager {
350
359
  `Full output: ${record.spillFile}\n` +
351
360
  "Continue whatever was waiting on this job. If it needs no follow-up, respond with exactly [SILENT].",
352
361
  ts: String(Date.now()),
353
- conversationId: "",
354
362
  conversationType: this.channelId.startsWith("group_") ? "2" : "1",
355
363
  dispatchId: `job:${this.channelId}:${record.id}:done`,
364
+ ...(record.contract.taskId
365
+ ? {
366
+ internalWake: {
367
+ kind: "job",
368
+ resourceId: record.id,
369
+ taskId: record.contract.taskId,
370
+ dispatchId: `job:${this.channelId}:${record.id}:done`,
371
+ },
372
+ }
373
+ : {}),
356
374
  };
357
375
  try {
358
376
  await this.options.dispatch(event);
359
377
  }
360
378
  catch (error) {
361
379
  log.logWarning(`Failed to dispatch completion wake for job ${record.id}`, errorMessage(error));
380
+ return;
362
381
  }
382
+ record.notified = true;
383
+ await this.persist(record);
363
384
  }
364
385
  async kill(record, signal) {
365
386
  await this.executor
@@ -372,6 +393,40 @@ export class ChannelJobManager {
372
393
  }
373
394
  return Array.from(this.jobs.values()).map(toSnapshot);
374
395
  }
396
+ async beginWakeConsumption(id, taskId, dispatchId) {
397
+ return this.wakeQueue.run(id, async () => {
398
+ const record = this.jobs.get(id);
399
+ const expected = `job:${this.channelId}:${id}:done`;
400
+ if (!record)
401
+ return false;
402
+ const eligible = record.status !== "running" && record.contract.taskId === taskId && dispatchId === expected;
403
+ const previousClaim = record.wakeClaimDispatchId;
404
+ if (!beginWakeClaim(record, eligible, dispatchId))
405
+ return false;
406
+ try {
407
+ await this.persist(record, true);
408
+ }
409
+ catch (error) {
410
+ record.wakeClaimDispatchId = previousClaim;
411
+ throw error;
412
+ }
413
+ return true;
414
+ });
415
+ }
416
+ async finishWakeConsumption(id, dispatchId) {
417
+ await this.wakeQueue.run(id, async () => {
418
+ const record = this.jobs.get(id);
419
+ if (!record || !finishWakeClaim(record, dispatchId))
420
+ return;
421
+ try {
422
+ await this.persist(record, true);
423
+ }
424
+ catch (error) {
425
+ record.wakeConsumedAt = undefined;
426
+ throw error;
427
+ }
428
+ });
429
+ }
375
430
  async cancel(ids, signal) {
376
431
  const results = [];
377
432
  for (const id of ids) {
@@ -502,6 +557,17 @@ export function configureJobRuntime(config) {
502
557
  export function channelJobTaskIds(channelId) {
503
558
  return managers.get(channelId)?.runningTaskIds() ?? new Set();
504
559
  }
560
+ /**
561
+ * Human-readable lines naming this channel's currently running background jobs, for the `/project
562
+ * set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no
563
+ * jobs" reasoning, so it needs no `Executor` either.
564
+ */
565
+ export function channelRunningJobLines(channelId) {
566
+ const manager = managers.get(channelId);
567
+ if (!manager)
568
+ return [];
569
+ return manager.listRunning().map((job) => `job \`${job.id}\`: ${job.command.slice(0, 80)}`);
570
+ }
505
571
  export function getChannelJobManager(channelId, executor) {
506
572
  let manager = managers.get(channelId);
507
573
  if (!manager) {
@@ -32,11 +32,11 @@ export function formatProgressEntry(kind, text) {
32
32
  const normalized = cleaned.replace(/\n+/g, " ").trim();
33
33
  switch (kind) {
34
34
  case "tool":
35
- return `Running: ${normalized}`;
35
+ return `➜ ${normalized}`;
36
36
  case "thinking":
37
- return `Thinking: ${normalized}`;
37
+ return `✦ ${normalized}`;
38
38
  case "error":
39
- return `Error: ${normalized}`;
39
+ return `✕ ${normalized}`;
40
40
  case "assistant":
41
41
  return normalized;
42
42
  }
@@ -135,15 +135,54 @@ export const SUBAGENTS_SECTION = {
135
135
  "Read agent-delegation.md before non-trivial delegation.",
136
136
  ].join("\n");
137
137
  }
138
- return [
139
- "## Configured Sub-Agents",
140
- "A sub-agent starts blank: state the goal, scope, paths, constraints and acceptance criteria in the task you hand it.",
141
- ...context.subAgents.map((agent) => `- ${agent.name} — ${agent.description}`),
142
- "",
143
- "Read agent-delegation.md before non-trivial delegation, and task-driving.md before independent verification.",
144
- ].join("\n");
138
+ return renderSubAgentDirectory(context.subAgents);
145
139
  },
146
140
  };
141
+ /**
142
+ * Group the catalog by (runtime, workload, mutates) rather than one flat list (spec 040, D11):
143
+ * `description` is the model's primary routing signal, but `workload`/`mutates` are the two
144
+ * machine-checkable dimensions that predict cost and blast radius before the model reads a word
145
+ * of prose. External-before-internal / heavy-before-light / write-before-read is a deterministic
146
+ * tie-break, not a ranking — it just keeps the catalog's group order stable across rebuilds.
147
+ */
148
+ function renderSubAgentDirectory(subAgents) {
149
+ const groups = new Map();
150
+ for (const agent of subAgents) {
151
+ const mutates = agent.mutates ?? "read";
152
+ const key = `${agent.runtime}|${agent.workload}|${mutates}`;
153
+ let group = groups.get(key);
154
+ if (!group) {
155
+ group = { runtime: agent.runtime, workload: agent.workload, mutates, agents: [] };
156
+ groups.set(key, group);
157
+ }
158
+ group.agents.push(agent);
159
+ }
160
+ const sortedGroups = Array.from(groups.values()).sort((a, b) => {
161
+ if (a.runtime !== b.runtime)
162
+ return a.runtime === "external" ? -1 : 1;
163
+ if (a.workload !== b.workload)
164
+ return a.workload === "heavy" ? -1 : 1;
165
+ if (a.mutates !== b.mutates)
166
+ return a.mutates === "write" ? -1 : 1;
167
+ return 0;
168
+ });
169
+ const lines = [
170
+ "## Configured Sub-Agents",
171
+ "A sub-agent starts blank: state the goal, scope, paths, constraints and acceptance criteria in the task you hand it.",
172
+ ];
173
+ for (const group of sortedGroups) {
174
+ // internal is always sync up to SYNC_GRACE_MS, then converts to async by itself (D2) — the
175
+ // model does not choose this, it is just told what to expect.
176
+ const mode = group.runtime === "external" ? "async" : "sync (auto-async past 120s)";
177
+ lines.push("", `${group.runtime} · ${group.workload} · ${group.mutates} · ${mode}`);
178
+ for (const agent of group.agents) {
179
+ const suffix = agent.unavailable ? ` (unavailable: ${agent.unavailable})` : "";
180
+ lines.push(`- ${agent.name} — ${agent.description}${suffix}`);
181
+ }
182
+ }
183
+ lines.push("", "Read agent-delegation.md before non-trivial delegation, and task-driving.md before independent verification.");
184
+ return lines.join("\n");
185
+ }
147
186
  const WORKSPACE_PREAMBLE = "The files below are workspace policy chosen by the user or the team. They direct how you work; they do not override the runtime facts and hard invariants above.";
148
187
  export const SOUL_SECTION = {
149
188
  id: "workspace.soul",
@@ -41,6 +41,15 @@ export interface ToolDescriptor {
41
41
  export interface SubAgentSummary {
42
42
  name: string;
43
43
  description: string;
44
+ /** Defaults to "internal"; drives the D11 directory grouping (runtime · workload · mutates). */
45
+ runtime: "internal" | "external";
46
+ harness?: "claude-code" | "codex-cli" | "exec";
47
+ /** Always resolved (D11 default: external→heavy, internal→light) — never undefined here. */
48
+ workload: "light" | "heavy";
49
+ /** Resolved for internal (inferred from tools) and required for external; undefined only for a malformed record. */
50
+ mutates?: "read" | "write";
51
+ /** Present only when the role is listed but currently cannot be invoked (e.g. missing binary). */
52
+ unavailable?: string;
44
53
  }
45
54
  /** A workspace file (SOUL.md / AGENTS.md) resolved for injection. */
46
55
  export interface LoadedPromptResource {
@@ -1,6 +1,15 @@
1
1
  import type { RunQueue } from "./types.js";
2
+ /**
3
+ * Ceiling on how long `drain()` blocks the caller. The queue carries outbound
4
+ * delivery calls plus whatever a session event enqueued (a resource refresh, a
5
+ * store write); any one of them stalling used to hold `run()`'s epilogue — and
6
+ * therefore the channel's busy state — open with no bound and no log line.
7
+ * Draining continues in the background after the deadline; only the waiter is
8
+ * released.
9
+ */
10
+ export declare const DRAIN_DEADLINE_MS = 60000;
2
11
  export interface CreatedRunQueue {
3
12
  queue: RunQueue;
4
- drain: () => Promise<void>;
13
+ drain: (deadlineMs?: number) => Promise<void>;
5
14
  }
6
15
  export declare function createRunQueue(): CreatedRunQueue;
@@ -1,5 +1,15 @@
1
1
  import * as log from "../log.js";
2
2
  import { errorMessage } from "../shared/text-utils.js";
3
+ import { withTimeout } from "../shared/with-timeout.js";
4
+ /**
5
+ * Ceiling on how long `drain()` blocks the caller. The queue carries outbound
6
+ * delivery calls plus whatever a session event enqueued (a resource refresh, a
7
+ * store write); any one of them stalling used to hold `run()`'s epilogue — and
8
+ * therefore the channel's busy state — open with no bound and no log line.
9
+ * Draining continues in the background after the deadline; only the waiter is
10
+ * released.
11
+ */
12
+ export const DRAIN_DEADLINE_MS = 60_000;
3
13
  export function createRunQueue() {
4
14
  let queueChain = Promise.resolve();
5
15
  const queue = {
@@ -17,8 +27,15 @@ export function createRunQueue() {
17
27
  };
18
28
  return {
19
29
  queue,
20
- drain: async () => {
21
- await queueChain;
30
+ drain: async (deadlineMs = DRAIN_DEADLINE_MS) => {
31
+ try {
32
+ await withTimeout("run queue drain", deadlineMs, async () => {
33
+ await queueChain;
34
+ });
35
+ }
36
+ catch (err) {
37
+ log.logWarning("Run queue drain deadline exceeded; releasing the turn", errorMessage(err));
38
+ }
22
39
  },
23
40
  };
24
41
  }
@@ -1,19 +1,31 @@
1
1
  import type { MediaSender } from "../runtime/channel-context.js";
2
+ import type { PipiclawSettingsManager } from "../settings.js";
2
3
  import type { AgentRunner } from "./types.js";
3
4
  export interface RunnerFactoryPaths {
4
5
  appHomeDir: string;
5
6
  authConfigPath: string;
6
7
  modelsConfigPath: string;
8
+ /**
9
+ * The single app-level settings manager (from `prepareAppServices`), shared across every
10
+ * channel's runner rather than each constructing its own. Keeps `drainErrors()`/diagnostics
11
+ * ordering and `reload()`'s file-stamp guard meaningful instead of racing N independent copies.
12
+ */
13
+ settingsManager: PipiclawSettingsManager;
7
14
  /** Optional, side-effect-free observer used by the behavior-eval harness. */
8
15
  onSessionEvent?: (event: unknown, channelId: string) => void;
9
16
  /**
10
17
  * Transport that can deliver file attachments (the DingTalk bot, or the terminal).
11
- * Present enables the `send_media` tool; absent, the tool is not built. Not part
12
- * of the runner cache key — it is a stable per-process transport handle.
18
+ * Present enables the `send_media` tool; absent, the tool is not built.
13
19
  */
14
20
  mediaSender?: MediaSender;
15
21
  /** Runtime callback that durably enqueues an independent task verifier. */
16
22
  dispatchVerification?: (taskId: string) => Promise<boolean>;
17
23
  }
18
- export declare function getOrCreateRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
19
- export declare function resetRunner(channelId: string, paths?: RunnerFactoryPaths, channelDir?: string): void;
24
+ /**
25
+ * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
26
+ * (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
27
+ * its own lifecycle (the daemon's runtime channel map with LRU eviction; the TUI's single local
28
+ * `const`, one channel per process) — a second cache here just duplicated that ownership and
29
+ * could hold a stale entry the real owner had already disposed.
30
+ */
31
+ export declare function createRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
@@ -1,25 +1,11 @@
1
1
  import { ChannelRunner } from "./channel-runner.js";
2
- const channelRunners = new Map();
3
- function runnerKey(paths, channelId, channelDir) {
4
- return `${paths.appHomeDir}\0${channelDir}\0${channelId}`;
5
- }
6
- export function getOrCreateRunner(channelId, channelDir, paths) {
7
- const key = runnerKey(paths, channelId, channelDir);
8
- const existing = channelRunners.get(key);
9
- if (existing)
10
- return existing;
11
- const runner = new ChannelRunner(channelId, channelDir, paths);
12
- channelRunners.set(key, runner);
13
- return runner;
14
- }
15
- export function resetRunner(channelId, paths, channelDir) {
16
- if (paths && channelDir) {
17
- channelRunners.delete(runnerKey(paths, channelId, channelDir));
18
- return;
19
- }
20
- for (const key of channelRunners.keys()) {
21
- if (key.endsWith(`\0${channelId}`)) {
22
- channelRunners.delete(key);
23
- }
24
- }
2
+ /**
3
+ * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
4
+ * (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
5
+ * its own lifecycle (the daemon's runtime channel map with LRU eviction; the TUI's single local
6
+ * `const`, one channel per process) — a second cache here just duplicated that ownership and
7
+ * could hold a stale entry the real owner had already disposed.
8
+ */
9
+ export function createRunner(channelId, channelDir, paths) {
10
+ return new ChannelRunner(channelId, channelDir, paths);
25
11
  }
@@ -1,5 +1,4 @@
1
1
  import * as log from "../log.js";
2
- import { formatLocalTime } from "../shared/local-time.js";
3
2
  import { extractLabelFromArgs, truncate } from "../shared/text-utils.js";
4
3
  import { isRecord } from "../shared/type-guards.js";
5
4
  import { toolResultDetails } from "../tools/tool-details.js";
@@ -40,7 +39,7 @@ function mergeAssistantUsage(runState, usage) {
40
39
  addUsage(runState.assistantUsage, usage);
41
40
  }
42
41
  export async function handleSessionEvent(event, context) {
43
- const { ctx, logCtx, queue, pendingTools, store, runState, memoryLifecycle, ledger } = context;
42
+ const { ctx, logCtx, queue, pendingTools, runState, memoryLifecycle } = context;
44
43
  const showProgress = ctx.progressStyle !== "none";
45
44
  const finalToCard = ctx.finalDelivery === "card";
46
45
  if (isToolExecutionStartEvent(event)) {
@@ -82,50 +81,16 @@ export async function handleSessionEvent(event, context) {
82
81
  ? event.result.details
83
82
  : null;
84
83
  if (subAgentDetails) {
84
+ // Spec 040, D7: `runs.ts` is the sole settlement/ledger/archive authority for every
85
+ // delegation run, sync or async, so its own `settle()` writes the ledger entry and the
86
+ // archive record exactly once. This handler only folds the run's usage into the current
87
+ // turn's displayed total — a dispatched-placeholder result contributes whatever usage
88
+ // had accrued by the time the grace window elapsed, fine for a live tally; the ledger
89
+ // entry `runs.ts` writes later carries the true total.
85
90
  mergeSubAgentUsage(runState.totalUsage, subAgentDetails);
86
91
  runState.usageSources++;
87
92
  runState.costKnown &&=
88
93
  subAgentDetails.usage.cost.total > 0 || (context.isModelCostKnown?.(subAgentDetails.model) ?? false);
89
- const label = pending?.args &&
90
- typeof pending.args === "object" &&
91
- "label" in pending.args &&
92
- typeof pending.args.label === "string"
93
- ? (pending.args.label ?? "subagent").trim()
94
- : "subagent";
95
- ledger.record({
96
- channelId: logCtx.channelId,
97
- kind: "subagent",
98
- model: subAgentDetails.model,
99
- label,
100
- usage: {
101
- input: subAgentDetails.usage.input,
102
- output: subAgentDetails.usage.output,
103
- cacheRead: subAgentDetails.usage.cacheRead,
104
- cacheWrite: subAgentDetails.usage.cacheWrite,
105
- total: subAgentDetails.usage.total,
106
- },
107
- cost: { ...subAgentDetails.usage.cost },
108
- });
109
- queue.enqueue(() => store?.logSubAgentRun(logCtx.channelId, {
110
- date: formatLocalTime(),
111
- toolCallId: event.toolCallId,
112
- label,
113
- agent: subAgentDetails.agent,
114
- source: subAgentDetails.source,
115
- model: subAgentDetails.model,
116
- tools: [...subAgentDetails.tools],
117
- turns: subAgentDetails.turns,
118
- toolCalls: subAgentDetails.toolCalls,
119
- durationMs: subAgentDetails.durationMs,
120
- failed: subAgentDetails.failed,
121
- failureReason: subAgentDetails.failureReason,
122
- output: resultStr.length > 16000 ? resultStr.slice(0, 16000) : resultStr,
123
- outputTruncated: resultStr.length > 16000,
124
- usage: {
125
- ...subAgentDetails.usage,
126
- cost: { ...subAgentDetails.usage.cost },
127
- },
128
- }) ?? Promise.resolve(), "sub-agent run log");
129
94
  }
130
95
  const details = toolResultDetails(event.result);
131
96
  if (isSkillManageDetails(details)) {
@@ -1,3 +1,14 @@
1
+ /**
2
+ * Serializes session-resource reloads against prompts.
3
+ *
4
+ * A refresh requested mid-prompt is deferred, then started once the prompt
5
+ * settles — but deliberately *not* awaited by that prompt. A reload reloads
6
+ * settings, skills, sub-agents and the SDK session; `/new` in particular defers
7
+ * a full reload into the prompt's epilogue, and awaiting it there kept the turn
8
+ * (and the channel's busy state) open for as long as the slowest step took. The
9
+ * next prompt still waits on `reloadChain`, so no turn ever runs against
10
+ * half-reloaded resources.
11
+ */
1
12
  export declare class SessionResourceGate {
2
13
  private readonly reloadSessionResources;
3
14
  private activePromptCount;
@@ -5,6 +16,12 @@ export declare class SessionResourceGate {
5
16
  private reloadChain;
6
17
  constructor(reloadSessionResources: () => Promise<void>);
7
18
  runPrompt<T>(operation: () => Promise<T>): Promise<T>;
19
+ /**
20
+ * Request a reload. Resolves once the reload has run when the gate is idle;
21
+ * during a prompt it only records the request — the prompt's epilogue starts it.
22
+ */
8
23
  requestRefresh(): Promise<void>;
24
+ /** Await any reload currently in flight (shutdown/tests). Never rejects. */
25
+ whenSettled(): Promise<void>;
9
26
  private flushPendingRefresh;
10
27
  }
@@ -1,3 +1,16 @@
1
+ import * as log from "../log.js";
2
+ import { errorMessage } from "../shared/text-utils.js";
3
+ /**
4
+ * Serializes session-resource reloads against prompts.
5
+ *
6
+ * A refresh requested mid-prompt is deferred, then started once the prompt
7
+ * settles — but deliberately *not* awaited by that prompt. A reload reloads
8
+ * settings, skills, sub-agents and the SDK session; `/new` in particular defers
9
+ * a full reload into the prompt's epilogue, and awaiting it there kept the turn
10
+ * (and the channel's busy state) open for as long as the slowest step took. The
11
+ * next prompt still waits on `reloadChain`, so no turn ever runs against
12
+ * half-reloaded resources.
13
+ */
1
14
  export class SessionResourceGate {
2
15
  constructor(reloadSessionResources) {
3
16
  this.reloadSessionResources = reloadSessionResources;
@@ -13,9 +26,16 @@ export class SessionResourceGate {
13
26
  }
14
27
  finally {
15
28
  this.activePromptCount--;
16
- await this.flushPendingRefresh();
29
+ // Detached: `flushPendingRefresh` has already published the new
30
+ // `reloadChain` by the time it first yields, so the next `runPrompt`
31
+ // orders behind this reload without this turn waiting for it.
32
+ void this.flushPendingRefresh();
17
33
  }
18
34
  }
35
+ /**
36
+ * Request a reload. Resolves once the reload has run when the gate is idle;
37
+ * during a prompt it only records the request — the prompt's epilogue starts it.
38
+ */
19
39
  async requestRefresh() {
20
40
  this.refreshPending = true;
21
41
  if (this.activePromptCount > 0) {
@@ -23,6 +43,10 @@ export class SessionResourceGate {
23
43
  }
24
44
  await this.flushPendingRefresh();
25
45
  }
46
+ /** Await any reload currently in flight (shutdown/tests). Never rejects. */
47
+ async whenSettled() {
48
+ await this.reloadChain;
49
+ }
26
50
  async flushPendingRefresh() {
27
51
  if (!this.refreshPending || this.activePromptCount > 0) {
28
52
  return;
@@ -33,7 +57,14 @@ export class SessionResourceGate {
33
57
  this.refreshPending = true;
34
58
  return;
35
59
  }
36
- await this.reloadSessionResources();
60
+ try {
61
+ await this.reloadSessionResources();
62
+ }
63
+ catch (error) {
64
+ // The chain is awaited by the next prompt and by detached callers, so a
65
+ // failed reload must never reject it: log and carry the previous resources.
66
+ log.logWarning("Session resource reload failed", errorMessage(error));
67
+ }
37
68
  };
38
69
  this.reloadChain = this.reloadChain.then(runReload, runReload);
39
70
  await this.reloadChain;