@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
@@ -16,13 +16,16 @@ import { buildTaskDigest, TASK_AGENDA_MAX_UNITS } from "../memory/task-digest.js
16
16
  import { getApiKeyForModel } from "../models/api-keys.js";
17
17
  import { createModelRuntime, defaultModel, findExactModelReferenceMatch, formatModelReference, hasKnownModelPricing, resolveInitialModel, wrapModelRegistry, } from "../models/utils.js";
18
18
  import { loadRuntimePlaybookCatalog, selectRuntimePlaybooks } from "../playbooks/catalog.js";
19
+ import { commitActiveSessionRef, resolveActiveSessionFile } from "../runtime/active-session-store.js";
20
+ import { resolveProjectScope } from "../runtime/project-scope-store.js";
19
21
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
20
- import { PipiclawSettingsManager } from "../settings.js";
22
+ import { resolveProjectAccessPolicy } from "../security/project-scope.js";
21
23
  import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
22
24
  import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
23
25
  import { countPromptUnits } from "../shared/prompt-units.js";
24
26
  import { errorMessage } from "../shared/text-utils.js";
25
27
  import { isRecord } from "../shared/type-guards.js";
28
+ import { withTimeout } from "../shared/with-timeout.js";
26
29
  import { discoverSubAgents } from "../subagents/discovery.js";
27
30
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
28
31
  import { createPipiclawTools } from "../tools/index.js";
@@ -39,6 +42,7 @@ import { loadWorkspacePromptResources } from "./prompt/resources.js";
39
42
  import { createRunQueue } from "./run-queue.js";
40
43
  import { handleSessionEvent } from "./session-events.js";
41
44
  import { SessionResourceGate } from "./session-resource-gate.js";
45
+ import { recoverInterruptedTurn } from "./turn-recovery.js";
42
46
  import { getLastAssistantUsage } from "./type-guards.js";
43
47
  import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
44
48
  import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
@@ -65,6 +69,15 @@ function asSdkSettingsManager(manager) {
65
69
  });
66
70
  }
67
71
  const DEFAULT_MAIN_THINKING_LEVEL = "medium";
72
+ /**
73
+ * Ceilings for the two awaited steps of a session-resource reload. Both reach
74
+ * the network (model/auth re-resolution; the SDK session's own reload) and
75
+ * neither carries a timeout of its own, so a stalled provider used to freeze a
76
+ * reload — and, before the gate detached it, the turn that triggered it. On
77
+ * timeout the reload keeps the resources it already had and logs.
78
+ */
79
+ const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
80
+ const SESSION_RELOAD_TIMEOUT_MS = 30_000;
68
81
  export class ChannelRunner {
69
82
  constructor(channelId, channelDir, paths) {
70
83
  this.ledger = getUsageLedger();
@@ -77,6 +90,12 @@ export class ChannelRunner {
77
90
  phase: "idle",
78
91
  stopRequested: false,
79
92
  };
93
+ /**
94
+ * Turns released by `forceEndTurn` whose owner has not called `endTurn` yet.
95
+ * That late release must be swallowed, or it would clear the busy state of
96
+ * whichever turn started in the meantime.
97
+ */
98
+ this.abandonedTurns = 0;
80
99
  /** When the primary model last failed and we switched to the backup. null = on primary. */
81
100
  this.primaryFailedAt = null;
82
101
  // --- Per run ---
@@ -92,13 +111,46 @@ export class ChannelRunner {
92
111
  const executor = createExecutor();
93
112
  this.executor = executor;
94
113
  this.workspaceDir = resolve(dirname(channelDir));
114
+ // Resolve and freeze this generation's ProjectScope (spec 043, D2/D3/D4.2). A channel with
115
+ // no persisted selection gets the app default, materialized as its first selection right
116
+ // here. A selection that no longer resolves safely (deleted directory, re-pointed symlink,
117
+ // or a since-tightened allowlist) fails the whole runner closed rather than silently
118
+ // falling back to a different root (P7) — the fix is `/project set`/`reset` from a plain
119
+ // runtime command path, not a degraded-but-running channel; see project-scope-store.ts.
120
+ const securityConfigForScope = loadSecurityConfigWithDiagnostics(this.appHomeDir);
121
+ const projectAccessResolution = resolveProjectAccessPolicy(securityConfigForScope.config, process.cwd());
122
+ const scopeOutcome = resolveProjectScope(channelDir, projectAccessResolution);
123
+ if (scopeOutcome.kind === "blocked") {
124
+ throw new Error(`[${channelId}] Cannot start channel: ${scopeOutcome.reason}`);
125
+ }
126
+ this.projectScope = scopeOutcome.scope;
95
127
  // Initial skill summaries
96
128
  const initialSkills = loadPipiclawSkills(channelDir);
97
129
  this.currentSkills = initialSkills;
98
- // Create session manager
99
- const contextFile = join(channelDir, "context.jsonl");
100
- this.sessionManager = SessionManager.open(contextFile, channelDir);
101
- this.settingsManager = new PipiclawSettingsManager(this.appHomeDir);
130
+ // Create session manager, opening whichever session this channel's active-session ref
131
+ // (or the context.jsonl default, for a channel that has never run a topology op) names
132
+ // (spec 043, D1).
133
+ const activeSessionFile = resolveActiveSessionFile(channelDir);
134
+ this.sessionManager = SessionManager.open(join(channelDir, activeSessionFile), channelDir);
135
+ // Per-runner recovery barrier (spec 043, D10 point 2): repairs must run against this exact
136
+ // SessionManager instance, before anything else touches it — a second `open()` of the same
137
+ // file would mutate a branch this instance never sees, silently desyncing the two. The
138
+ // daemon's own startup scan (bootstrap.ts) covers channels with no live runner yet; this
139
+ // covers lazy channels, the TUI, and a channel whose file was fixed by hand after the scan
140
+ // already ran and reported it blocked.
141
+ const recoveryOutcome = recoverInterruptedTurn(this.sessionManager, {
142
+ api: defaultModel.api,
143
+ provider: defaultModel.provider,
144
+ model: defaultModel.id,
145
+ });
146
+ if (recoveryOutcome.kind === "blocked") {
147
+ throw new Error(`[${channelId}] Cannot start channel: session left in an unrecoverable state after a restart (${recoveryOutcome.reason}). ` +
148
+ `Back up ${join(channelDir, activeSessionFile)} on the host, move it aside, then use /new to start a fresh session.`);
149
+ }
150
+ if (recoveryOutcome.kind === "repaired") {
151
+ log.logWarning(`[${channelId}] Repaired an interrupted turn on restart`, `toolResults=${recoveryOutcome.appendedToolResults} abortedAssistant=${recoveryOutcome.appendedAbortedAssistant}`);
152
+ }
153
+ this.settingsManager = paths.settingsManager;
102
154
  this.reportSettingsDiagnostics();
103
155
  this.memoryCandidateStore = createMemoryCandidateStore();
104
156
  this.memoryActivityRecorder = createMemoryActivityRecorder({
@@ -145,11 +197,32 @@ export class ChannelRunner {
145
197
  this.turn = { phase: "dispatching", stopRequested: false, taskText };
146
198
  }
147
199
  endTurn() {
200
+ // A turn that `forceEndTurn` already released no longer owns this state.
201
+ if (this.abandonedTurns > 0) {
202
+ this.abandonedTurns--;
203
+ return;
204
+ }
148
205
  this.turn = { phase: "idle", stopRequested: false };
149
206
  }
207
+ forceEndTurn(reason) {
208
+ if (this.turn.phase === "idle") {
209
+ return false;
210
+ }
211
+ log.logWarning(`[${this.channelId}] Force-ending a stuck turn (phase=${this.turn.phase})`, `${reason}; its own teardown is still running and will be ignored when it finishes`);
212
+ this.abandonedTurns++;
213
+ this.turn = { phase: "idle", stopRequested: false };
214
+ return true;
215
+ }
150
216
  isBusy() {
151
217
  return this.turn.phase !== "idle";
152
218
  }
219
+ /** Advance a turn's phase, unless that turn has since been released. */
220
+ setPhase(turn, phase) {
221
+ if (this.turn !== turn) {
222
+ return;
223
+ }
224
+ this.turn.phase = phase;
225
+ }
153
226
  requestStop() {
154
227
  if (this.turn.phase !== "idle") {
155
228
  this.turn.stopRequested = true;
@@ -167,7 +240,10 @@ export class ChannelRunner {
167
240
  if (implicitTurn) {
168
241
  this.beginTurn(ctx.message.text);
169
242
  }
170
- this.turn.phase = "preparing";
243
+ // Every later phase write goes through this reference: once `forceEndTurn`
244
+ // has released this turn, `this.turn` may already belong to the next one.
245
+ const ownTurn = this.turn;
246
+ this.setPhase(ownTurn, "preparing");
171
247
  const runQueue = createRunQueue();
172
248
  this.runState.queue = runQueue.queue;
173
249
  let promptSubmitted = false;
@@ -339,151 +415,173 @@ export class ChannelRunner {
339
415
  });
340
416
  }
341
417
  finally {
342
- this.turn.phase = "finishing";
343
- // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
344
- // string the provider actually received — base sections, pi's tail, and the boundary
345
- // footer the prompt extension appends at before_agent_start.
346
- if (process.env.PIPICLAW_DEBUG) {
347
- const debugContext = {
348
- systemPrompt: this.lastFinalPrompt ?? this.agent.state.systemPrompt,
349
- promptManifest: this.lastPromptBuild
350
- ? buildPromptManifest(this.lastPromptBuild, this.lastFinalPrompt)
351
- : undefined,
352
- messages: this.session.messages,
353
- durableMemoryBootstrap: durableMemoryBootstrapText || undefined,
354
- taskDigest: taskDigestText || undefined,
355
- recalledContext: recalledContextText || undefined,
356
- newUserMessage: promptText,
357
- };
358
- await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarning(`[${this.channelId}] Failed to write last_prompt.json`, errorMessage(error)));
359
- }
360
- if (!promptSubmitted) {
361
- const discarded = this.session.clearQueue();
362
- const discardedCount = discarded.steering.length + discarded.followUp.length;
363
- if (discardedCount > 0) {
364
- log.logWarning(`[${this.channelId}] Discarded ${discardedCount} queued busy message(s) after run setup failed`);
365
- }
418
+ await this.finishTurn({
419
+ ctx,
420
+ ownTurn,
421
+ implicitTurn,
422
+ promptSubmitted,
423
+ runQueue,
424
+ fallbackAttempted,
425
+ fallbackTargetRef,
426
+ promptText,
427
+ durableMemoryBootstrapText,
428
+ taskDigestText,
429
+ recalledContextText,
430
+ });
431
+ }
432
+ return {
433
+ stopReason: this.runState.stopReason,
434
+ errorMessage: this.runState.errorMessage,
435
+ usage: { ...this.runState.totalUsage, cost: { ...this.runState.totalUsage.cost } },
436
+ costKnown: this.runState.usageSources > 0 && this.runState.costKnown,
437
+ durationMs: Date.now() - startedAt,
438
+ silent: this.runState.finalOutcome.kind === "silent",
439
+ };
440
+ }
441
+ /**
442
+ * The epilogue shared by every exit path out of `run()`'s try/catch: debug dump, delivery of
443
+ * whatever final message the turn settled on, usage/ledger accounting, the end-of-turn memory
444
+ * flush, and clearing run state. Pulled out of `run()` itself only to keep that method's main
445
+ * line (prepare → prompt with fallback) readable; every input here is `run()`-local, not
446
+ * instance state, so it is threaded through explicitly rather than promoted to a field.
447
+ */
448
+ async finishTurn(input) {
449
+ const { ctx, ownTurn, implicitTurn, promptSubmitted, runQueue, fallbackAttempted, fallbackTargetRef } = input;
450
+ this.setPhase(ownTurn, "finishing");
451
+ // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
452
+ // string the provider actually received — base sections, pi's tail, and the boundary
453
+ // footer the prompt extension appends at before_agent_start.
454
+ if (process.env.PIPICLAW_DEBUG) {
455
+ const debugContext = {
456
+ systemPrompt: this.lastFinalPrompt ?? this.agent.state.systemPrompt,
457
+ promptManifest: this.lastPromptBuild
458
+ ? buildPromptManifest(this.lastPromptBuild, this.lastFinalPrompt)
459
+ : undefined,
460
+ messages: this.session.messages,
461
+ durableMemoryBootstrap: input.durableMemoryBootstrapText || undefined,
462
+ taskDigest: input.taskDigestText || undefined,
463
+ recalledContext: input.recalledContextText || undefined,
464
+ newUserMessage: input.promptText,
465
+ };
466
+ await writeFile(join(this.channelDir, "last_prompt.json"), JSON.stringify(debugContext, null, 2)).catch((error) => log.logWarning(`[${this.channelId}] Failed to write last_prompt.json`, errorMessage(error)));
467
+ }
468
+ if (!promptSubmitted) {
469
+ const discarded = this.session.clearQueue();
470
+ const discardedCount = discarded.steering.length + discarded.followUp.length;
471
+ if (discardedCount > 0) {
472
+ log.logWarning(`[${this.channelId}] Discarded ${discardedCount} queued busy message(s) after run setup failed`);
366
473
  }
367
- await runQueue.drain();
368
- const finalOutcome = this.runState.finalOutcome;
369
- const finalOutcomeText = getFinalOutcomeText(finalOutcome);
370
- try {
371
- if (this.runState.stopReason === "error" &&
372
- this.runState.errorMessage &&
373
- !this.runState.finalResponseDelivered) {
374
- try {
375
- const baseErrorSummary = this.runState.errorMessage.length > 240
376
- ? `${this.runState.errorMessage.slice(0, 237)}...`
377
- : this.runState.errorMessage;
378
- const compactionSummary = this.runState.lastCompactionError &&
379
- this.runState.lastCompactionError !== this.runState.errorMessage
380
- ? this.runState.lastCompactionError.length > 240
381
- ? `${this.runState.lastCompactionError.slice(0, 237)}...`
382
- : this.runState.lastCompactionError
383
- : undefined;
384
- const detailLines = [`\`${baseErrorSummary}\``];
385
- if (compactionSummary) {
386
- detailLines.push(`恢复尝试:\`${compactionSummary}\``);
387
- }
388
- if (fallbackAttempted && fallbackTargetRef) {
389
- detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
390
- }
391
- await ctx.replaceMessage(`_抱歉,出错了。_\n\n${detailLines.join("\n\n")}`);
474
+ }
475
+ await runQueue.drain();
476
+ const finalOutcome = this.runState.finalOutcome;
477
+ const finalOutcomeText = getFinalOutcomeText(finalOutcome);
478
+ try {
479
+ if (this.runState.stopReason === "error" &&
480
+ this.runState.errorMessage &&
481
+ !this.runState.finalResponseDelivered) {
482
+ try {
483
+ const baseErrorSummary = this.runState.errorMessage.length > 240
484
+ ? `${this.runState.errorMessage.slice(0, 237)}...`
485
+ : this.runState.errorMessage;
486
+ const compactionSummary = this.runState.lastCompactionError && this.runState.lastCompactionError !== this.runState.errorMessage
487
+ ? this.runState.lastCompactionError.length > 240
488
+ ? `${this.runState.lastCompactionError.slice(0, 237)}...`
489
+ : this.runState.lastCompactionError
490
+ : undefined;
491
+ const detailLines = [`\`${baseErrorSummary}\``];
492
+ if (compactionSummary) {
493
+ detailLines.push(`恢复尝试:\`${compactionSummary}\``);
392
494
  }
393
- catch (err) {
394
- const errMsg = errorMessage(err);
395
- log.logWarning("Failed to post error message", errMsg);
495
+ if (fallbackAttempted && fallbackTargetRef) {
496
+ detailLines.push(`已切换备用模型 \`${fallbackTargetRef}\` 重试,仍失败。`);
396
497
  }
498
+ await ctx.replaceMessage(`_抱歉,出错了。_\n\n${detailLines.join("\n\n")}`);
397
499
  }
398
- else if (isSilentOutcome(finalOutcome)) {
399
- try {
400
- await ctx.deleteMessage();
401
- log.logInfo("Silent response - deleted message");
402
- }
403
- catch (err) {
404
- const errMsg = errorMessage(err);
405
- log.logWarning("Failed to delete message for silent response", errMsg);
406
- }
500
+ catch (err) {
501
+ const errMsg = errorMessage(err);
502
+ log.logWarning("Failed to post error message", errMsg);
407
503
  }
408
- else if (this.runState.stopReason === "aborted" && !this.runState.finalResponseDelivered) {
409
- try {
410
- await ctx.deleteMessage();
411
- log.logInfo("Aborted response - discarded active delivery state");
412
- }
413
- catch (err) {
414
- const errMsg = errorMessage(err);
415
- log.logWarning("Failed to discard active delivery state after abort", errMsg);
416
- }
504
+ }
505
+ else if (isSilentOutcome(finalOutcome)) {
506
+ try {
507
+ await ctx.deleteMessage();
508
+ log.logInfo("Silent response - deleted message");
417
509
  }
418
- else if (finalOutcomeText && !this.runState.finalResponseDelivered) {
419
- try {
420
- await ctx.replaceMessage(finalOutcomeText);
421
- }
422
- catch (err) {
423
- const errMsg = errorMessage(err);
424
- log.logWarning("Failed to replace message with final text", errMsg);
425
- }
510
+ catch (err) {
511
+ const errMsg = errorMessage(err);
512
+ log.logWarning("Failed to delete message for silent response", errMsg);
426
513
  }
427
- await ctx.flush();
428
514
  }
429
- finally {
430
- await ctx.close();
515
+ else if (this.runState.stopReason === "aborted" && !this.runState.finalResponseDelivered) {
516
+ try {
517
+ await ctx.deleteMessage();
518
+ log.logInfo("Aborted response - discarded active delivery state");
519
+ }
520
+ catch (err) {
521
+ const errMsg = errorMessage(err);
522
+ log.logWarning("Failed to discard active delivery state after abort", errMsg);
523
+ }
431
524
  }
432
- // Log usage summary. Gated on tokens as well as cost: a local (or pricing-less) model
433
- // bills nothing, and skipping it here left both the log and the ledger empty.
434
- if (this.runState.totalUsage.cost.total > 0 || this.runState.totalUsage.total > 0) {
435
- const lastAssistantMessage = getLastAssistantUsage(this.session.messages);
436
- const contextTokens = lastAssistantMessage
437
- ? lastAssistantMessage.usage.input +
438
- lastAssistantMessage.usage.output +
439
- lastAssistantMessage.usage.cacheRead +
440
- lastAssistantMessage.usage.cacheWrite
441
- : 0;
442
- const currentRunModel = this.session.model ?? this.activeModel;
443
- const contextWindow = currentRunModel.contextWindow || 200000;
444
- log.logUsageSummary(this.runState.logCtx, this.runState.totalUsage, contextTokens, contextWindow);
445
- const responseModel = lastAssistantMessage?.responseModel;
446
- // Ledger turn entry: assistant-only usage (sub-agents recorded separately),
447
- // keeping Σ(entries) == real spend with no double counting.
448
- this.ledger.record({
449
- channelId: this.channelId,
450
- kind: "turn",
451
- model: responseModel ?? formatModelReference(currentRunModel),
452
- usage: {
453
- input: this.runState.assistantUsage.input,
454
- output: this.runState.assistantUsage.output,
455
- cacheRead: this.runState.assistantUsage.cacheRead,
456
- cacheWrite: this.runState.assistantUsage.cacheWrite,
457
- total: this.runState.assistantUsage.total,
458
- },
459
- cost: { ...this.runState.assistantUsage.cost },
460
- });
461
- if (responseModel &&
462
- responseModel !== formatModelReference(currentRunModel) &&
463
- responseModel !== currentRunModel.id) {
464
- log.logInfo(`[${this.channelId}] Actual model: ${responseModel} (configured: ${formatModelReference(currentRunModel)})`);
525
+ else if (finalOutcomeText && !this.runState.finalResponseDelivered) {
526
+ try {
527
+ await ctx.replaceMessage(finalOutcomeText);
528
+ }
529
+ catch (err) {
530
+ const errMsg = errorMessage(err);
531
+ log.logWarning("Failed to replace message with final text", errMsg);
465
532
  }
466
533
  }
467
- // The turn is over, so the channel is about to look idle to the maintenance gates —
468
- // which is exactly when this state has to be on disk. Everything buffered during the
469
- // turn lands here in one write.
470
- await this.flushMemoryActivity();
471
- // Clear run state
472
- this.runState.ctx = null;
473
- this.runState.logCtx = null;
474
- this.runState.queue = null;
475
- if (implicitTurn) {
476
- this.endTurn();
534
+ await ctx.flush();
535
+ }
536
+ finally {
537
+ await ctx.close();
538
+ }
539
+ // Log usage summary. Gated on tokens as well as cost: a local (or pricing-less) model
540
+ // bills nothing, and skipping it here left both the log and the ledger empty.
541
+ if (this.runState.totalUsage.cost.total > 0 || this.runState.totalUsage.total > 0) {
542
+ const lastAssistantMessage = getLastAssistantUsage(this.session.messages);
543
+ const contextTokens = lastAssistantMessage
544
+ ? lastAssistantMessage.usage.input +
545
+ lastAssistantMessage.usage.output +
546
+ lastAssistantMessage.usage.cacheRead +
547
+ lastAssistantMessage.usage.cacheWrite
548
+ : 0;
549
+ const currentRunModel = this.session.model ?? this.activeModel;
550
+ const contextWindow = currentRunModel.contextWindow || 200000;
551
+ log.logUsageSummary(this.runState.logCtx, this.runState.totalUsage, contextTokens, contextWindow);
552
+ const responseModel = lastAssistantMessage?.responseModel;
553
+ // Ledger turn entry: assistant-only usage (sub-agents recorded separately),
554
+ // keeping Σ(entries) == real spend with no double counting.
555
+ this.ledger.record({
556
+ channelId: this.channelId,
557
+ kind: "turn",
558
+ model: responseModel ?? formatModelReference(currentRunModel),
559
+ usage: {
560
+ input: this.runState.assistantUsage.input,
561
+ output: this.runState.assistantUsage.output,
562
+ cacheRead: this.runState.assistantUsage.cacheRead,
563
+ cacheWrite: this.runState.assistantUsage.cacheWrite,
564
+ total: this.runState.assistantUsage.total,
565
+ },
566
+ cost: { ...this.runState.assistantUsage.cost },
567
+ });
568
+ if (responseModel &&
569
+ responseModel !== formatModelReference(currentRunModel) &&
570
+ responseModel !== currentRunModel.id) {
571
+ log.logInfo(`[${this.channelId}] Actual model: ${responseModel} (configured: ${formatModelReference(currentRunModel)})`);
477
572
  }
478
573
  }
479
- return {
480
- stopReason: this.runState.stopReason,
481
- errorMessage: this.runState.errorMessage,
482
- usage: { ...this.runState.totalUsage, cost: { ...this.runState.totalUsage.cost } },
483
- costKnown: this.runState.usageSources > 0 && this.runState.costKnown,
484
- durationMs: Date.now() - startedAt,
485
- silent: this.runState.finalOutcome.kind === "silent",
486
- };
574
+ // The turn is over, so the channel is about to look idle to the maintenance gates —
575
+ // which is exactly when this state has to be on disk. Everything buffered during the
576
+ // turn lands here in one write.
577
+ await this.flushMemoryActivity();
578
+ // Clear run state
579
+ this.runState.ctx = null;
580
+ this.runState.logCtx = null;
581
+ this.runState.queue = null;
582
+ if (implicitTurn) {
583
+ this.endTurn();
584
+ }
487
585
  }
488
586
  async handleBuiltinCommand(ctx, command) {
489
587
  try {
@@ -544,6 +642,26 @@ export class ChannelRunner {
544
642
  await this.flushMemoryActivity();
545
643
  await this.memoryLifecycle.flushForShutdown();
546
644
  }
645
+ async dispose() {
646
+ await this.flushMemoryForShutdown();
647
+ if (this.isBusy()) {
648
+ // `session.dispose()` aborts in-flight work; a busy runner keeps its session and
649
+ // subscription until whoever holds it calls dispose() again once idle.
650
+ log.logWarning(`[${this.channelId}] dispose() called while busy; session left intact`, "");
651
+ return;
652
+ }
653
+ // Guards a dispose() racing construction: initializeSession assigns `this.session`
654
+ // asynchronously, so a runner disposed the instant after creation may not have one yet.
655
+ await this.sessionReady;
656
+ this.sessionUnsubscribe?.();
657
+ this.sessionUnsubscribe = undefined;
658
+ try {
659
+ this.session.dispose();
660
+ }
661
+ catch (error) {
662
+ log.logWarning(`[${this.channelId}] Session dispose failed`, errorMessage(error));
663
+ }
664
+ }
547
665
  async getMemoryMaintenanceContext() {
548
666
  await this.ensureSessionReady();
549
667
  this.settingsManager.reload();
@@ -601,6 +719,10 @@ export class ChannelRunner {
601
719
  detail: args.trim().toLowerCase() === "detail",
602
720
  });
603
721
  }
722
+ /** `/subagents list`'s role-directory health tail — whatever this runner already discovered. */
723
+ getSubAgentDiscoverySnapshot() {
724
+ return this.subAgentDiscovery;
725
+ }
604
726
  // === Private helpers ===
605
727
  /**
606
728
  * The per-turn channel capsule. It replaces the channel paths that used to sit in
@@ -795,12 +917,18 @@ export class ChannelRunner {
795
917
  agent: this.agent,
796
918
  sessionManager: this.sessionManager,
797
919
  settingsManager: asSdkSettingsManager(this.settingsManager),
798
- cwd: process.cwd(),
920
+ cwd: this.projectScope.projectRoot,
799
921
  modelRuntime: this.modelRuntime,
800
922
  resourceLoader: initialResourceLoader,
801
923
  baseToolsOverride,
802
924
  });
803
925
  this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initialResourceLoader), async ({ sessionManager, sessionStartEvent }) => {
926
+ // `/new`, fork, and switch already wrote the target session's durable header by
927
+ // this point (the SDK does it synchronously before invoking this callback); commit
928
+ // the pointer before we rebuild and rebind to it, so a crash between "SDK created
929
+ // session" and "we finished rebinding" leaves the old ref (and old session)
930
+ // authoritative rather than an orphaned new file (spec 043, D1.3).
931
+ await commitActiveSessionRef(this.channelDir, sessionManager);
804
932
  const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
805
933
  return {
806
934
  session: next.session,
@@ -828,7 +956,12 @@ export class ChannelRunner {
828
956
  this.currentSkills = skills;
829
957
  this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
830
958
  this.rebuildSessionTools();
831
- await this.session.reload();
959
+ try {
960
+ await withTimeout(`[${this.channelId}] session reload`, SESSION_RELOAD_TIMEOUT_MS, () => this.session.reload());
961
+ }
962
+ catch (error) {
963
+ log.logWarning(`[${this.channelId}] Session reload did not settle`, errorMessage(error));
964
+ }
832
965
  }
833
966
  async bindSessionExtensions() {
834
967
  await this.session.bindExtensions({
@@ -879,7 +1012,16 @@ export class ChannelRunner {
879
1012
  }
880
1013
  }
881
1014
  async refreshSubAgentDiscovery() {
882
- await this.modelRegistry.refresh();
1015
+ // Re-resolves models.json *and* every provider's auth, which for an OAuth
1016
+ // provider is a network call. Failing open keeps the last known model
1017
+ // snapshot — stale availability is a far smaller problem than a reload
1018
+ // (and, through it, a `/new` turn) that never returns.
1019
+ try {
1020
+ await withTimeout(`[${this.channelId}] model registry refresh`, MODEL_REGISTRY_REFRESH_TIMEOUT_MS, () => this.modelRegistry.refresh());
1021
+ }
1022
+ catch (error) {
1023
+ log.logWarning(`[${this.channelId}] Model registry refresh did not settle; using the previous model snapshot`, errorMessage(error));
1024
+ }
883
1025
  const discovery = discoverSubAgents(this.workspaceDir, this.modelRegistry.getAvailable());
884
1026
  for (const warning of discovery.warnings) {
885
1027
  log.logWarning(`Sub-agent config warning (${this.channelId})`, warning);
@@ -912,7 +1054,7 @@ export class ChannelRunner {
912
1054
  this.lastWorkspaceResources = resources;
913
1055
  const build = buildPipiclawSystemPrompt({
914
1056
  mode: "normal",
915
- cwd: process.cwd(),
1057
+ cwd: this.projectScope.projectRoot,
916
1058
  workspaceDir: this.workspaceDir,
917
1059
  tools: this.currentTools.map((tool) => ({
918
1060
  name: tool.name,
@@ -924,6 +1066,11 @@ export class ChannelRunner {
924
1066
  subAgents: this.subAgentDiscovery.agents.map((agent) => ({
925
1067
  name: agent.name,
926
1068
  description: agent.description,
1069
+ runtime: agent.runtime,
1070
+ harness: agent.harness,
1071
+ workload: agent.workload ?? (agent.runtime === "external" ? "heavy" : "light"),
1072
+ mutates: agent.mutates,
1073
+ unavailable: agent.unavailable,
927
1074
  })),
928
1075
  skills: this.currentSkills.skills.map((skill) => ({ name: skill.name, description: skill.description })),
929
1076
  });
@@ -941,7 +1088,7 @@ export class ChannelRunner {
941
1088
  }
942
1089
  createResourceLoader() {
943
1090
  return new DefaultResourceLoader({
944
- cwd: process.cwd(),
1091
+ cwd: this.projectScope.projectRoot,
945
1092
  agentDir: this.appHomeDir,
946
1093
  settingsManager: asSdkSettingsManager(this.settingsManager),
947
1094
  extensionFactories: [
@@ -996,7 +1143,7 @@ export class ChannelRunner {
996
1143
  }
997
1144
  createAgentSessionServices(resourceLoader) {
998
1145
  return {
999
- cwd: process.cwd(),
1146
+ cwd: this.projectScope.projectRoot,
1000
1147
  agentDir: this.appHomeDir,
1001
1148
  settingsManager: asSdkSettingsManager(this.settingsManager),
1002
1149
  modelRuntime: this.modelRuntime,
@@ -1048,7 +1195,7 @@ export class ChannelRunner {
1048
1195
  agent,
1049
1196
  sessionManager,
1050
1197
  settingsManager: asSdkSettingsManager(this.settingsManager),
1051
- cwd: process.cwd(),
1198
+ cwd: this.projectScope.projectRoot,
1052
1199
  modelRuntime: this.modelRuntime,
1053
1200
  resourceLoader,
1054
1201
  baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
@@ -1067,6 +1214,7 @@ export class ChannelRunner {
1067
1214
  getAvailableModels: () => this.modelRegistry.getAvailable(),
1068
1215
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
1069
1216
  workspaceDir: this.workspaceDir,
1217
+ projectScope: this.projectScope,
1070
1218
  channelDir: this.channelDir,
1071
1219
  channelId: this.channelId,
1072
1220
  getSubAgentDiscovery: () => this.subAgentDiscovery,
@@ -1,6 +1,12 @@
1
- export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context";
1
+ export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context" | "subagents" | "project";
2
2
  /** The four transport commands handled by `ChannelRunner.handleBuiltinCommand`. */
3
3
  export type RunnerBuiltInCommandName = "help" | "stop" | "steer" | "followup" | "context";
4
+ /**
5
+ * The commands with no mid-turn state to touch: each renders a text report from disk/in-memory
6
+ * state and is dispatched the same way whether a turn is running or the channel is idle. Derived
7
+ * from `BuiltInCommandName` rather than hand-listed, so it can never drift from the source table.
8
+ */
9
+ export type RuntimeCommandName = Exclude<BuiltInCommandName, "help" | "steer" | "followup" | "stop">;
4
10
  export interface BuiltInCommand {
5
11
  name: BuiltInCommandName;
6
12
  args: string;
@@ -81,6 +81,32 @@ export const BUILT_IN_COMMANDS = [
81
81
  // access, so it answers mid-turn like /status and /usage do.
82
82
  availableWhileBusy: true,
83
83
  },
84
+ {
85
+ name: "subagents",
86
+ argumentHint: "<list [running|failed|all]|show <id>|output <id>|cancel <id|all>|roles [name]>",
87
+ description: "查看与控制委派 run(内置与外部)、浏览角色目录;cancel 不经过模型,直接终止",
88
+ examples: [
89
+ "/subagents",
90
+ "/subagents list failed",
91
+ "/subagents show run_a1b2c3",
92
+ "/subagents output run_a1b2c3",
93
+ "/subagents cancel run_a1b2c3",
94
+ "/subagents roles",
95
+ "/subagents roles builder-hard",
96
+ ],
97
+ // A human control path independent of the model (spec 040, D6): /stop no longer kills a
98
+ // dispatched delegation, so cancel must work even when the model/turn is unavailable.
99
+ availableWhileBusy: true,
100
+ },
101
+ {
102
+ name: "project",
103
+ argumentHint: "[set <absolute-path>|reset]",
104
+ description: "查看或切换本频道的项目目录(文件工具/shell 的工作面);set/reset 需频道空闲",
105
+ examples: ["/project", "/project set /home/me/projects/foo", "/project reset"],
106
+ // The read form answers like /status; set/reset validate idleness themselves and reply
107
+ // with a plain error instead of blocking the built-in-command dispatch path.
108
+ availableWhileBusy: true,
109
+ },
84
110
  ];
85
111
  /**
86
112
  * Session commands: handled inside the Pipiclaw session layer (SDK command