@oyasmi/pipiclaw 0.9.0-beta.1 → 0.9.0-beta.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 (54) hide show
  1. package/dist/agent/channel-runner.d.ts +9 -0
  2. package/dist/agent/channel-runner.js +58 -4
  3. package/dist/agent/commands.js +11 -3
  4. package/dist/agent/job-manager.d.ts +6 -0
  5. package/dist/agent/job-manager.js +55 -1
  6. package/dist/agent/progress-formatter.js +3 -3
  7. package/dist/agent/run-queue.d.ts +10 -1
  8. package/dist/agent/run-queue.js +19 -2
  9. package/dist/agent/session-resource-gate.d.ts +17 -0
  10. package/dist/agent/session-resource-gate.js +33 -2
  11. package/dist/agent/status-render.js +1 -3
  12. package/dist/agent/types.d.ts +8 -0
  13. package/dist/runtime/bootstrap.d.ts +52 -0
  14. package/dist/runtime/bootstrap.js +192 -25
  15. package/dist/runtime/delivery.js +5 -5
  16. package/dist/runtime/dingtalk.d.ts +8 -0
  17. package/dist/runtime/durable-dispatch.d.ts +4 -0
  18. package/dist/runtime/durable-dispatch.js +16 -0
  19. package/dist/runtime/subagent-commands.d.ts +8 -6
  20. package/dist/runtime/subagent-commands.js +264 -64
  21. package/dist/security/logger.js +7 -0
  22. package/dist/shared/host-process.d.ts +7 -1
  23. package/dist/shared/host-process.js +7 -3
  24. package/dist/shared/jsonl-appender.d.ts +2 -0
  25. package/dist/shared/jsonl-appender.js +25 -13
  26. package/dist/shared/with-timeout.d.ts +14 -0
  27. package/dist/shared/with-timeout.js +38 -0
  28. package/dist/subagents/detached-discovery.d.ts +13 -0
  29. package/dist/subagents/detached-discovery.js +17 -0
  30. package/dist/subagents/external/run.d.ts +10 -0
  31. package/dist/subagents/external/run.js +47 -1
  32. package/dist/subagents/format.d.ts +12 -0
  33. package/dist/subagents/format.js +24 -0
  34. package/dist/subagents/runs.d.ts +38 -0
  35. package/dist/subagents/runs.js +171 -24
  36. package/dist/subagents/tool.d.ts +18 -0
  37. package/dist/subagents/tool.js +147 -89
  38. package/dist/tasks/control.d.ts +12 -0
  39. package/dist/tasks/control.js +20 -0
  40. package/dist/tasks/store.d.ts +21 -0
  41. package/dist/tasks/store.js +80 -0
  42. package/dist/tools/index.js +2 -0
  43. package/dist/tools/subagent-manage.d.ts +5 -0
  44. package/dist/tools/subagent-manage.js +68 -51
  45. package/dist/usage/ledger.d.ts +7 -0
  46. package/dist/usage/ledger.js +15 -2
  47. package/dist/usage/render.js +22 -0
  48. package/examples/sub-agents/README.md +12 -7
  49. package/examples/sub-agents/documenter.md +3 -3
  50. package/examples/sub-agents/git-committer.md +1 -1
  51. package/examples/sub-agents/reviewer.md +12 -6
  52. package/examples/sub-agents/verifier.md +5 -2
  53. package/examples/sub-agents/worker.md +1 -1
  54. package/package.json +1 -1
@@ -47,13 +47,22 @@ export declare class ChannelRunner implements AgentRunner {
47
47
  private tasksEnabled;
48
48
  /** Single owner of turn state; see TurnPhase in types.ts. */
49
49
  private turn;
50
+ /**
51
+ * Turns released by `forceEndTurn` whose owner has not called `endTurn` yet.
52
+ * That late release must be swallowed, or it would clear the busy state of
53
+ * whichever turn started in the meantime.
54
+ */
55
+ private abandonedTurns;
50
56
  /** When the primary model last failed and we switched to the backup. null = on primary. */
51
57
  private primaryFailedAt;
52
58
  private runState;
53
59
  constructor(channelId: string, channelDir: string, paths: RunnerFactoryPaths);
54
60
  beginTurn(taskText: string): void;
55
61
  endTurn(): void;
62
+ forceEndTurn(reason: string): boolean;
56
63
  isBusy(): boolean;
64
+ /** Advance a turn's phase, unless that turn has since been released. */
65
+ private setPhase;
57
66
  requestStop(): void;
58
67
  getTurnStatus(): TurnStatus;
59
68
  run(ctx: ChannelContext, store: ChannelStore): Promise<{
@@ -23,6 +23,7 @@ import { formatLocalTime, localStampForFilename } from "../shared/local-time.js"
23
23
  import { countPromptUnits } from "../shared/prompt-units.js";
24
24
  import { errorMessage } from "../shared/text-utils.js";
25
25
  import { isRecord } from "../shared/type-guards.js";
26
+ import { withTimeout } from "../shared/with-timeout.js";
26
27
  import { discoverSubAgents } from "../subagents/discovery.js";
27
28
  import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
28
29
  import { createPipiclawTools } from "../tools/index.js";
@@ -65,6 +66,15 @@ function asSdkSettingsManager(manager) {
65
66
  });
66
67
  }
67
68
  const DEFAULT_MAIN_THINKING_LEVEL = "medium";
69
+ /**
70
+ * Ceilings for the two awaited steps of a session-resource reload. Both reach
71
+ * the network (model/auth re-resolution; the SDK session's own reload) and
72
+ * neither carries a timeout of its own, so a stalled provider used to freeze a
73
+ * reload — and, before the gate detached it, the turn that triggered it. On
74
+ * timeout the reload keeps the resources it already had and logs.
75
+ */
76
+ const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
77
+ const SESSION_RELOAD_TIMEOUT_MS = 30_000;
68
78
  export class ChannelRunner {
69
79
  constructor(channelId, channelDir, paths) {
70
80
  this.ledger = getUsageLedger();
@@ -77,6 +87,12 @@ export class ChannelRunner {
77
87
  phase: "idle",
78
88
  stopRequested: false,
79
89
  };
90
+ /**
91
+ * Turns released by `forceEndTurn` whose owner has not called `endTurn` yet.
92
+ * That late release must be swallowed, or it would clear the busy state of
93
+ * whichever turn started in the meantime.
94
+ */
95
+ this.abandonedTurns = 0;
80
96
  /** When the primary model last failed and we switched to the backup. null = on primary. */
81
97
  this.primaryFailedAt = null;
82
98
  // --- Per run ---
@@ -145,11 +161,32 @@ export class ChannelRunner {
145
161
  this.turn = { phase: "dispatching", stopRequested: false, taskText };
146
162
  }
147
163
  endTurn() {
164
+ // A turn that `forceEndTurn` already released no longer owns this state.
165
+ if (this.abandonedTurns > 0) {
166
+ this.abandonedTurns--;
167
+ return;
168
+ }
148
169
  this.turn = { phase: "idle", stopRequested: false };
149
170
  }
171
+ forceEndTurn(reason) {
172
+ if (this.turn.phase === "idle") {
173
+ return false;
174
+ }
175
+ 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`);
176
+ this.abandonedTurns++;
177
+ this.turn = { phase: "idle", stopRequested: false };
178
+ return true;
179
+ }
150
180
  isBusy() {
151
181
  return this.turn.phase !== "idle";
152
182
  }
183
+ /** Advance a turn's phase, unless that turn has since been released. */
184
+ setPhase(turn, phase) {
185
+ if (this.turn !== turn) {
186
+ return;
187
+ }
188
+ this.turn.phase = phase;
189
+ }
153
190
  requestStop() {
154
191
  if (this.turn.phase !== "idle") {
155
192
  this.turn.stopRequested = true;
@@ -167,7 +204,10 @@ export class ChannelRunner {
167
204
  if (implicitTurn) {
168
205
  this.beginTurn(ctx.message.text);
169
206
  }
170
- this.turn.phase = "preparing";
207
+ // Every later phase write goes through this reference: once `forceEndTurn`
208
+ // has released this turn, `this.turn` may already belong to the next one.
209
+ const ownTurn = this.turn;
210
+ this.setPhase(ownTurn, "preparing");
171
211
  const runQueue = createRunQueue();
172
212
  this.runState.queue = runQueue.queue;
173
213
  let promptSubmitted = false;
@@ -339,7 +379,7 @@ export class ChannelRunner {
339
379
  });
340
380
  }
341
381
  finally {
342
- this.turn.phase = "finishing";
382
+ this.setPhase(ownTurn, "finishing");
343
383
  // Debug dump (PIPICLAW_DEBUG=1). Written after the run so `systemPrompt` is the
344
384
  // string the provider actually received — base sections, pi's tail, and the boundary
345
385
  // footer the prompt extension appends at before_agent_start.
@@ -832,7 +872,12 @@ export class ChannelRunner {
832
872
  this.currentSkills = skills;
833
873
  this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
834
874
  this.rebuildSessionTools();
835
- await this.session.reload();
875
+ try {
876
+ await withTimeout(`[${this.channelId}] session reload`, SESSION_RELOAD_TIMEOUT_MS, () => this.session.reload());
877
+ }
878
+ catch (error) {
879
+ log.logWarning(`[${this.channelId}] Session reload did not settle`, errorMessage(error));
880
+ }
836
881
  }
837
882
  async bindSessionExtensions() {
838
883
  await this.session.bindExtensions({
@@ -883,7 +928,16 @@ export class ChannelRunner {
883
928
  }
884
929
  }
885
930
  async refreshSubAgentDiscovery() {
886
- await this.modelRegistry.refresh();
931
+ // Re-resolves models.json *and* every provider's auth, which for an OAuth
932
+ // provider is a network call. Failing open keeps the last known model
933
+ // snapshot — stale availability is a far smaller problem than a reload
934
+ // (and, through it, a `/new` turn) that never returns.
935
+ try {
936
+ await withTimeout(`[${this.channelId}] model registry refresh`, MODEL_REGISTRY_REFRESH_TIMEOUT_MS, () => this.modelRegistry.refresh());
937
+ }
938
+ catch (error) {
939
+ log.logWarning(`[${this.channelId}] Model registry refresh did not settle; using the previous model snapshot`, errorMessage(error));
940
+ }
887
941
  const discovery = discoverSubAgents(this.workspaceDir, this.modelRegistry.getAvailable());
888
942
  for (const warning of discovery.warnings) {
889
943
  log.logWarning(`Sub-agent config warning (${this.channelId})`, warning);
@@ -83,9 +83,17 @@ export const BUILT_IN_COMMANDS = [
83
83
  },
84
84
  {
85
85
  name: "subagents",
86
- argumentHint: "<list|show <runId>|cancel <runId>>",
87
- description: "查看与控制委派 run(内置与外部);cancel 不经过模型,直接终止",
88
- examples: ["/subagents list", "/subagents show a1b2c3d4", "/subagents cancel a1b2c3d4"],
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
+ ],
89
97
  // A human control path independent of the model (spec 040, D6): /stop no longer kills a
90
98
  // dispatched delegation, so cancel must work even when the model/turn is unavailable.
91
99
  availableWhileBusy: true,
@@ -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 {
@@ -66,6 +69,7 @@ export declare class ChannelJobManager {
66
69
  private readonly channelId;
67
70
  private readonly executor;
68
71
  private readonly jobs;
72
+ private readonly wakeQueue;
69
73
  private sweepTimer?;
70
74
  private garbageCollectionTimer?;
71
75
  private sweeping;
@@ -133,6 +137,8 @@ export declare class ChannelJobManager {
133
137
  private announce;
134
138
  private kill;
135
139
  list(signal?: AbortSignal): Promise<JobSnapshot[]>;
140
+ beginWakeConsumption(id: string, taskId: string, dispatchId: string): Promise<boolean>;
141
+ finishWakeConsumption(id: string, dispatchId: string): Promise<void>;
136
142
  cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
137
143
  id: string;
138
144
  status: JobStatus | "not_found";
@@ -4,6 +4,7 @@ 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";
@@ -67,6 +68,7 @@ function toSnapshot(record) {
67
68
  startedAt: record.startedAt,
68
69
  durationMs: record.status === "running" ? Date.now() - record.startedAt : record.durationMs,
69
70
  exitCode: record.exitCode,
71
+ taskId: record.contract.taskId,
70
72
  };
71
73
  }
72
74
  export class ChannelJobManager {
@@ -74,6 +76,7 @@ export class ChannelJobManager {
74
76
  this.channelId = channelId;
75
77
  this.executor = executor;
76
78
  this.jobs = new Map();
79
+ this.wakeQueue = createSerialQueue();
77
80
  this.sweeping = false;
78
81
  // A bare number keeps the original `sweepIntervalMs` positional form working for tests.
79
82
  this.options = typeof options === "number" ? { sweepIntervalMs: options } : options;
@@ -83,7 +86,7 @@ export class ChannelJobManager {
83
86
  return this.options.stateDir ? join(this.options.stateDir, `${id}.json`) : undefined;
84
87
  }
85
88
  /** Mirror a record to disk. Persistence is best-effort: it must never fail a job operation. */
86
- async persist(record) {
89
+ async persist(record, required = false) {
87
90
  const path = this.recordPath(record.id);
88
91
  if (!path)
89
92
  return;
@@ -93,6 +96,8 @@ export class ChannelJobManager {
93
96
  await chmod(path, 0o600).catch(() => undefined);
94
97
  }
95
98
  catch (error) {
99
+ if (required)
100
+ throw error;
96
101
  log.logWarning(`Failed to persist background job ${record.id}`, errorMessage(error));
97
102
  }
98
103
  }
@@ -353,6 +358,16 @@ export class ChannelJobManager {
353
358
  conversationId: "",
354
359
  conversationType: this.channelId.startsWith("group_") ? "2" : "1",
355
360
  dispatchId: `job:${this.channelId}:${record.id}:done`,
361
+ ...(record.contract.taskId
362
+ ? {
363
+ internalWake: {
364
+ kind: "job",
365
+ resourceId: record.id,
366
+ taskId: record.contract.taskId,
367
+ dispatchId: `job:${this.channelId}:${record.id}:done`,
368
+ },
369
+ }
370
+ : {}),
356
371
  };
357
372
  try {
358
373
  await this.options.dispatch(event);
@@ -375,6 +390,45 @@ export class ChannelJobManager {
375
390
  }
376
391
  return Array.from(this.jobs.values()).map(toSnapshot);
377
392
  }
393
+ async beginWakeConsumption(id, taskId, dispatchId) {
394
+ return this.wakeQueue.run(id, async () => {
395
+ const record = this.jobs.get(id);
396
+ const expected = `job:${this.channelId}:${id}:done`;
397
+ if (!record ||
398
+ record.status === "running" ||
399
+ record.contract.taskId !== taskId ||
400
+ dispatchId !== expected ||
401
+ record.wakeConsumedAt ||
402
+ (record.wakeClaimDispatchId && record.wakeClaimDispatchId !== dispatchId)) {
403
+ return false;
404
+ }
405
+ const previousClaim = record.wakeClaimDispatchId;
406
+ record.wakeClaimDispatchId = dispatchId;
407
+ try {
408
+ await this.persist(record, true);
409
+ }
410
+ catch (error) {
411
+ record.wakeClaimDispatchId = previousClaim;
412
+ throw error;
413
+ }
414
+ return true;
415
+ });
416
+ }
417
+ async finishWakeConsumption(id, dispatchId) {
418
+ await this.wakeQueue.run(id, async () => {
419
+ const record = this.jobs.get(id);
420
+ if (!record || record.wakeClaimDispatchId !== dispatchId || record.wakeConsumedAt)
421
+ return;
422
+ record.wakeConsumedAt = Date.now();
423
+ try {
424
+ await this.persist(record, true);
425
+ }
426
+ catch (error) {
427
+ record.wakeConsumedAt = undefined;
428
+ throw error;
429
+ }
430
+ });
431
+ }
378
432
  async cancel(ids, signal) {
379
433
  const results = [];
380
434
  for (const id of ids) {
@@ -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
  }
@@ -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,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;
@@ -39,15 +39,13 @@ export function renderStatus(options) {
39
39
  try {
40
40
  const snapshot = runner.getStatusSnapshot();
41
41
  lines.push(`- Model: ${snapshot.model}`);
42
+ lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
42
43
  if (snapshot.fallback) {
43
44
  const until = new Date(snapshot.fallback.cooldownUntilMs);
44
45
  const hh = String(until.getHours()).padStart(2, "0");
45
46
  const mm = String(until.getMinutes()).padStart(2, "0");
46
47
  lines.push(`- Fallback: active(primary ${snapshot.fallback.primary} 冷却至 ${hh}:${mm})`);
47
48
  }
48
- if (snapshot.thinkingLevel && snapshot.thinkingLevel !== "off") {
49
- lines.push(`- Thinking: ${snapshot.thinkingLevel}`);
50
- }
51
49
  if (snapshot.contextTokens !== undefined && snapshot.contextWindow > 0) {
52
50
  const percent = ((snapshot.contextTokens / snapshot.contextWindow) * 100).toFixed(1);
53
51
  lines.push(`- Context: ${formatTokenCount(snapshot.contextTokens)} / ${formatTokenCount(snapshot.contextWindow)} (${percent}%)`);
@@ -64,6 +64,14 @@ export interface AgentRunner {
64
64
  beginTurn(taskText: string): void;
65
65
  /** Release the turn (idempotent). Transports call this after all per-message work. */
66
66
  endTurn(): void;
67
+ /**
68
+ * Release a turn whose owner is wedged (a stalled epilogue: delivery drain,
69
+ * resource reload, memory flush) so the channel stops reporting busy. The
70
+ * wedged turn keeps running to completion; its later `endTurn` is ignored.
71
+ * Returns false when the runner was already idle. `/stop`'s last resort — a
72
+ * normal stop goes through `requestStop` + `abort`.
73
+ */
74
+ forceEndTurn(reason: string): boolean;
67
75
  /** True from beginTurn until endTurn. */
68
76
  isBusy(): boolean;
69
77
  /** Mark the current turn as user-stopped (no-op when idle). */
@@ -1,5 +1,9 @@
1
+ import { type AgentRunner } from "../agent/index.js";
2
+ import { type JobSnapshot } from "../agent/job-manager.js";
1
3
  import { type Executor } from "../executor.js";
2
4
  import { PipiclawSettingsManager } from "../settings.js";
5
+ import { type RunRecord } from "../subagents/runs.js";
6
+ import { type WakeTaskTransitionHooks } from "../tasks/store.js";
3
7
  import { DingTalkBot, type DingTalkConfig, type DingTalkEvent, type DingTalkHandler } from "./dingtalk.js";
4
8
  import { ChannelStore } from "./store.js";
5
9
  export interface BootstrapPaths {
@@ -72,6 +76,50 @@ export declare function bootstrapAppHome(paths?: BootstrapPaths, io?: BootstrapI
72
76
  export declare function printBootstrapSummary(result: BootstrapResult, io?: BootstrapIO, paths?: BootstrapPaths): void;
73
77
  export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
74
78
  export declare function parseArgs(argv: string[], paths?: BootstrapPaths, io?: BootstrapIO): void;
79
+ /**
80
+ * Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
81
+ * on this channel, has actually finished (a still-`running` job cannot have produced this wake —
82
+ * accepting it anyway would let a message merely mentioning a live job's id activate a task
83
+ * early), and really is the one whose own contract names `taskId` (spec 040, T9). The text itself
84
+ * is never sufficient — it can be typed by any user, or echoed back by an external agent's own
85
+ * untrusted stdout.
86
+ */
87
+ export declare function isVerifiedJobWake(jobs: JobSnapshot[], jobId: string, taskId: string): boolean;
88
+ /**
89
+ * Same check as `isVerifiedJobWake`, for a `[SUBAGENT:<runId>] ... belongs to task <taskId>.`
90
+ * delegation wake. `settledAt` (rather than `status !== "running"`) is the terminal marker here
91
+ * because it is the one field `SubAgentRunManager.settle()` sets unconditionally and first, before
92
+ * usage/archive/wake side effects — the same idempotency guard the manager itself relies on.
93
+ */
94
+ export declare function isVerifiedDelegationWake(record: RunRecord | undefined, taskId: string): boolean;
95
+ /** Plain wake text is untrusted. Only an event carrying the producer-created structured envelope
96
+ * and its exact durable dispatch id may enter task activation; normal DingTalk inbound events do
97
+ * not populate `internalWake`, so copying a real wake's text is insufficient. */
98
+ export declare function isTrustedInternalWake(event: DingTalkEvent, kind: "job" | "subagent", resourceId: string, taskId: string): event is DingTalkEvent & {
99
+ dispatchId: string;
100
+ };
101
+ export interface ClaimedDelegationWake {
102
+ taskId: string;
103
+ generation?: number;
104
+ activated: boolean;
105
+ finish(): Promise<void>;
106
+ rollback(): Promise<void>;
107
+ }
108
+ /** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
109
+ * final marker separate lets transports such as TUI mark it consumed only after they have accepted
110
+ * the corresponding turn; a rejected submit remains replayable in the same or next process. */
111
+ export declare function claimVerifiedDelegationWake(event: DingTalkEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
112
+ /**
113
+ * Watchdog for `/stop`: release the channel if the stopped turn has not ended
114
+ * once the grace window elapses. Returns true when it had to force the release.
115
+ */
116
+ export declare function forceEndStuckTurnAfterStop(input: {
117
+ channelId: string;
118
+ runner: AgentRunner;
119
+ graceMs?: number;
120
+ pollMs?: number;
121
+ notify?: (text: string) => Promise<unknown>;
122
+ }): Promise<boolean>;
75
123
  interface RuntimeContextOptions {
76
124
  paths: BootstrapPaths;
77
125
  dingtalkConfig: DingTalkConfig;
@@ -97,6 +145,10 @@ interface RuntimeContextOptions {
97
145
  onTaskDriverDispatch?: (event: DingTalkEvent, accepted: boolean) => void;
98
146
  startServices?: boolean;
99
147
  registerSignalHandlers?: boolean;
148
+ /** Test-only fault seams for the atomic structured-wake task transition. */
149
+ wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
150
+ /** Override the `/stop` watchdog's grace window (tests use a short one). */
151
+ stopForceEndGraceMs?: number;
100
152
  }
101
153
  export declare function createRuntimeContext(options: RuntimeContextOptions): RuntimeContext & {
102
154
  bot: DingTalkBot;