@oyasmi/pipiclaw 0.9.0-beta.2 → 0.9.0-beta.4
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.
- package/dist/agent/channel-runner.d.ts +9 -0
- package/dist/agent/channel-runner.js +58 -4
- package/dist/agent/commands.js +11 -3
- package/dist/agent/progress-formatter.js +3 -3
- package/dist/agent/run-queue.d.ts +10 -1
- package/dist/agent/run-queue.js +19 -2
- package/dist/agent/session-resource-gate.d.ts +17 -0
- package/dist/agent/session-resource-gate.js +33 -2
- package/dist/agent/status-render.js +1 -3
- package/dist/agent/types.d.ts +8 -0
- package/dist/runtime/bootstrap.d.ts +14 -0
- package/dist/runtime/bootstrap.js +58 -0
- package/dist/runtime/delivery.js +9 -5
- package/dist/runtime/subagent-commands.d.ts +8 -6
- package/dist/runtime/subagent-commands.js +264 -64
- package/dist/shared/with-timeout.d.ts +14 -0
- package/dist/shared/with-timeout.js +38 -0
- package/dist/subagents/detached-discovery.d.ts +13 -0
- package/dist/subagents/detached-discovery.js +17 -0
- package/dist/subagents/format.d.ts +12 -0
- package/dist/subagents/format.js +24 -0
- package/dist/subagents/runs.d.ts +24 -0
- package/dist/subagents/runs.js +54 -0
- package/dist/subagents/tool.js +4 -2
- package/dist/tools/subagent-manage.js +33 -29
- package/examples/sub-agents/README.md +7 -4
- package/examples/sub-agents/documenter.md +3 -3
- package/examples/sub-agents/git-committer.md +1 -1
- package/examples/sub-agents/verifier.md +1 -1
- package/examples/sub-agents/worker.md +1 -1
- 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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
package/dist/agent/commands.js
CHANGED
|
@@ -83,9 +83,17 @@ export const BUILT_IN_COMMANDS = [
|
|
|
83
83
|
},
|
|
84
84
|
{
|
|
85
85
|
name: "subagents",
|
|
86
|
-
argumentHint: "<list|show <
|
|
87
|
-
description: "查看与控制委派 run
|
|
88
|
-
examples: [
|
|
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,
|
|
@@ -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
|
|
35
|
+
return `▶ ${normalized}`;
|
|
36
36
|
case "thinking":
|
|
37
|
-
return
|
|
37
|
+
return `● ${normalized}`;
|
|
38
38
|
case "error":
|
|
39
|
-
return
|
|
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;
|
package/dist/agent/run-queue.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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}%)`);
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -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,3 +1,4 @@
|
|
|
1
|
+
import { type AgentRunner } from "../agent/index.js";
|
|
1
2
|
import { type JobSnapshot } from "../agent/job-manager.js";
|
|
2
3
|
import { type Executor } from "../executor.js";
|
|
3
4
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
@@ -108,6 +109,17 @@ export interface ClaimedDelegationWake {
|
|
|
108
109
|
* final marker separate lets transports such as TUI mark it consumed only after they have accepted
|
|
109
110
|
* the corresponding turn; a rejected submit remains replayable in the same or next process. */
|
|
110
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>;
|
|
111
123
|
interface RuntimeContextOptions {
|
|
112
124
|
paths: BootstrapPaths;
|
|
113
125
|
dingtalkConfig: DingTalkConfig;
|
|
@@ -135,6 +147,8 @@ interface RuntimeContextOptions {
|
|
|
135
147
|
registerSignalHandlers?: boolean;
|
|
136
148
|
/** Test-only fault seams for the atomic structured-wake task transition. */
|
|
137
149
|
wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
|
|
150
|
+
/** Override the `/stop` watchdog's grace window (tests use a short one). */
|
|
151
|
+
stopForceEndGraceMs?: number;
|
|
138
152
|
}
|
|
139
153
|
export declare function createRuntimeContext(options: RuntimeContextOptions): RuntimeContext & {
|
|
140
154
|
bot: DingTalkBot;
|
|
@@ -18,6 +18,7 @@ import { PipiclawSettingsManager } from "../settings.js";
|
|
|
18
18
|
import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
19
19
|
import { fileStamp } from "../shared/file-stamp.js";
|
|
20
20
|
import { errorMessage } from "../shared/text-utils.js";
|
|
21
|
+
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
21
22
|
import { configureSubAgentRuntime, getSubAgentRunManager, restoreAllSubAgentRuns, } from "../subagents/runs.js";
|
|
22
23
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
23
24
|
import { activateWaitingTaskAndClaimAttempt, finishTaskAttempt, finishWakeTaskActivation, rollbackWakeTaskActivation, } from "../tasks/store.js";
|
|
@@ -465,6 +466,39 @@ export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
|
|
|
465
466
|
rollback: () => rollbackWakeTaskActivation(channelDir, wake.taskId, handoff),
|
|
466
467
|
};
|
|
467
468
|
}
|
|
469
|
+
/**
|
|
470
|
+
* How long `/stop` waits for the turn to actually end before force-releasing it.
|
|
471
|
+
* `requestStop` + `abort` only reach the agent loop; a turn wedged in its
|
|
472
|
+
* epilogue (delivery drain, session-resource reload, memory flush) ignores both
|
|
473
|
+
* and would otherwise keep the channel reporting "已有回合在运行" indefinitely.
|
|
474
|
+
*/
|
|
475
|
+
const STOP_FORCE_END_GRACE_MS = 15_000;
|
|
476
|
+
const STOP_FORCE_END_POLL_MS = 250;
|
|
477
|
+
function sleepUnref(ms) {
|
|
478
|
+
return new Promise((resolve) => {
|
|
479
|
+
const timer = setTimeout(resolve, ms);
|
|
480
|
+
timer.unref?.();
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Watchdog for `/stop`: release the channel if the stopped turn has not ended
|
|
485
|
+
* once the grace window elapses. Returns true when it had to force the release.
|
|
486
|
+
*/
|
|
487
|
+
export async function forceEndStuckTurnAfterStop(input) {
|
|
488
|
+
const graceMs = input.graceMs ?? STOP_FORCE_END_GRACE_MS;
|
|
489
|
+
const pollMs = input.pollMs ?? STOP_FORCE_END_POLL_MS;
|
|
490
|
+
const deadline = Date.now() + graceMs;
|
|
491
|
+
while (input.runner.isBusy() && Date.now() < deadline) {
|
|
492
|
+
await sleepUnref(Math.min(pollMs, Math.max(1, deadline - Date.now())));
|
|
493
|
+
}
|
|
494
|
+
if (!input.runner.forceEndTurn(`/stop did not take effect within ${graceMs}ms`)) {
|
|
495
|
+
return false;
|
|
496
|
+
}
|
|
497
|
+
await input
|
|
498
|
+
.notify?.(`⚠️ 上一个回合的收尾卡住了,已强制结束以释放会话(后台清理仍在继续)。现在可以正常发消息或使用 \`/new\`、\`/model\`。`)
|
|
499
|
+
.catch(() => undefined);
|
|
500
|
+
return true;
|
|
501
|
+
}
|
|
468
502
|
export function createRuntimeContext(options) {
|
|
469
503
|
const startServices = options.startServices ?? true;
|
|
470
504
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
@@ -475,6 +509,8 @@ export function createRuntimeContext(options) {
|
|
|
475
509
|
const cliVersion = readCliVersion();
|
|
476
510
|
const channelRunners = new Map();
|
|
477
511
|
const activeTasks = new Set();
|
|
512
|
+
/** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
|
|
513
|
+
const stopWatchdogs = new Set();
|
|
478
514
|
// `workspace/CHANNELS.md`: names every channel id so the workspace, the logs and the agent
|
|
479
515
|
// stop dealing in `group_cid...`. Writes are debounced internally (see channel-index.ts).
|
|
480
516
|
const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
|
|
@@ -559,6 +595,21 @@ export function createRuntimeContext(options) {
|
|
|
559
595
|
log.logWarning(`[${channelId}] Failed to reset durable-dispatch leases on stop`, errorMessage(err));
|
|
560
596
|
});
|
|
561
597
|
log.logInfo(`[${channelId}] Stop requested`);
|
|
598
|
+
if (!stopWatchdogs.has(channelId)) {
|
|
599
|
+
stopWatchdogs.add(channelId);
|
|
600
|
+
void forceEndStuckTurnAfterStop({
|
|
601
|
+
channelId,
|
|
602
|
+
runner,
|
|
603
|
+
graceMs: options.stopForceEndGraceMs,
|
|
604
|
+
notify: (text) => _bot.sendPlain(channelId, text),
|
|
605
|
+
})
|
|
606
|
+
.catch((err) => {
|
|
607
|
+
log.logWarning(`[${channelId}] Stop watchdog failed`, errorMessage(err));
|
|
608
|
+
})
|
|
609
|
+
.finally(() => {
|
|
610
|
+
stopWatchdogs.delete(channelId);
|
|
611
|
+
});
|
|
612
|
+
}
|
|
562
613
|
}
|
|
563
614
|
return { pausedTaskId };
|
|
564
615
|
},
|
|
@@ -617,6 +668,13 @@ export function createRuntimeContext(options) {
|
|
|
617
668
|
args,
|
|
618
669
|
channelId: event.channelId,
|
|
619
670
|
discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
|
|
671
|
+
// `roles` needs a role directory even for a channel that has never spoken this boot —
|
|
672
|
+
// resolved from disk, without spinning up a full ChannelRunner (spec 041).
|
|
673
|
+
getDetachedDiscovery: () => loadDetachedSubAgentDiscovery({
|
|
674
|
+
workspaceDir: options.paths.workspaceDir,
|
|
675
|
+
authConfigPath: options.paths.authConfigPath,
|
|
676
|
+
modelsConfigPath: options.paths.modelsConfigPath,
|
|
677
|
+
}),
|
|
620
678
|
});
|
|
621
679
|
await bot.sendPlain(event.channelId, response);
|
|
622
680
|
},
|
package/dist/runtime/delivery.js
CHANGED
|
@@ -3,6 +3,10 @@ import { errorMessage } from "../shared/text-utils.js";
|
|
|
3
3
|
const MIN_UPDATE_INTERVAL_MS = 800;
|
|
4
4
|
const ROLLING_WINDOW_SIZE = 3;
|
|
5
5
|
const NO_CONTENT = "";
|
|
6
|
+
// DingTalk's markdown line break: "\n" padded with a space on each side (per DingTalk's
|
|
7
|
+
// own markdown guide). A bare blank line reads as a full paragraph break (too much
|
|
8
|
+
// vertical gap between progress entries); a bare "\n" is swallowed by the renderer.
|
|
9
|
+
const PROGRESS_LINE_BREAK = " \n ";
|
|
6
10
|
// Last-resort ceiling on how long flush() will block a caller. Outbound HTTP now
|
|
7
11
|
// has its own timeout, so the sync loop is already bounded; this only guards against
|
|
8
12
|
// an unforeseen stall so run()'s finally can never hang the channel forever.
|
|
@@ -123,11 +127,11 @@ class ChannelDeliveryController {
|
|
|
123
127
|
if (this.progressStartedAt === 0) {
|
|
124
128
|
this.progressStartedAt = Date.now();
|
|
125
129
|
}
|
|
126
|
-
if (text.startsWith("
|
|
130
|
+
if (text.startsWith("▶ ")) {
|
|
127
131
|
this.toolCallCount++;
|
|
128
132
|
}
|
|
129
133
|
if (this.progressSegments.length > 0) {
|
|
130
|
-
this.progressSegments.push(
|
|
134
|
+
this.progressSegments.push(PROGRESS_LINE_BREAK);
|
|
131
135
|
}
|
|
132
136
|
this.progressSegments.push(text);
|
|
133
137
|
this.progressTextDirty = true;
|
|
@@ -390,7 +394,7 @@ class ChannelDeliveryController {
|
|
|
390
394
|
trimToRecentEntries(maxEntries) {
|
|
391
395
|
let entryCount = 0;
|
|
392
396
|
for (const segment of this.progressSegments) {
|
|
393
|
-
if (segment !==
|
|
397
|
+
if (segment !== PROGRESS_LINE_BREAK) {
|
|
394
398
|
entryCount++;
|
|
395
399
|
}
|
|
396
400
|
}
|
|
@@ -401,11 +405,11 @@ class ChannelDeliveryController {
|
|
|
401
405
|
let removedEntries = 0;
|
|
402
406
|
while (removedEntries < entriesToRemove && this.progressSegments.length > 0) {
|
|
403
407
|
const segment = this.progressSegments.shift();
|
|
404
|
-
if (segment !==
|
|
408
|
+
if (segment !== PROGRESS_LINE_BREAK) {
|
|
405
409
|
removedEntries++;
|
|
406
410
|
}
|
|
407
411
|
}
|
|
408
|
-
while (this.progressSegments[0] ===
|
|
412
|
+
while (this.progressSegments[0] === PROGRESS_LINE_BREAK) {
|
|
409
413
|
this.progressSegments.shift();
|
|
410
414
|
}
|
|
411
415
|
this.progressTextDirty = true;
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
|
|
2
2
|
/**
|
|
3
|
-
* `/subagents` — the human control path that does not depend on the model (spec 040,
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* functions returning markdown, no bot/event coupling.
|
|
3
|
+
* `/subagents` — the human control path that does not depend on the model (spec 040 D6, polished
|
|
4
|
+
* by spec 041). Mirrors `task-commands.ts`'s shape: pure functions returning markdown, no
|
|
5
|
+
* bot/event coupling.
|
|
7
6
|
*/
|
|
8
7
|
export interface HandleSubagentsCommandOptions {
|
|
9
8
|
args: string;
|
|
10
9
|
channelId: string;
|
|
11
|
-
/** Best-effort role-directory snapshot for
|
|
12
|
-
* currently active for this channel (mirrors how `/status` degrades without a live runner). */
|
|
10
|
+
/** Best-effort role-directory snapshot for `roles` / the overview tail; omitted when no runner
|
|
11
|
+
* is currently active for this channel (mirrors how `/status` degrades without a live runner). */
|
|
13
12
|
discovery?: SubAgentDiscoveryResult;
|
|
13
|
+
/** Fallback used only when `discovery` is absent: resolves the role directory from disk without
|
|
14
|
+
* a live `ChannelRunner` (spec 041). Lazy — never called unless a `roles` view is actually rendered. */
|
|
15
|
+
getDetachedDiscovery?: () => Promise<SubAgentDiscoveryResult>;
|
|
14
16
|
}
|
|
15
17
|
export declare function handleSubagentsCommand(options: HandleSubagentsCommandOptions): Promise<string>;
|