@oyasmi/pipiclaw 0.9.0-beta.1 → 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.
- package/README.md +146 -177
- package/dist/agent/channel-runner.d.ts +25 -0
- package/dist/agent/channel-runner.js +284 -145
- package/dist/agent/commands.d.ts +7 -1
- package/dist/agent/commands.js +20 -3
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/agent/job-manager.d.ts +29 -3
- package/dist/agent/job-manager.js +65 -2
- 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/runner-factory.d.ts +16 -4
- package/dist/agent/runner-factory.js +9 -23
- 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/turn-recovery.d.ts +72 -0
- package/dist/agent/turn-recovery.js +193 -0
- package/dist/agent/types.d.ts +17 -1
- package/dist/agent/types.js +3 -16
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/main.js +2 -1
- package/dist/memory/extraction.js +0 -1
- package/dist/memory/maintenance-gates.d.ts +1 -1
- package/dist/memory/maintenance-jobs.js +2 -3
- package/dist/memory/metadata.d.ts +0 -15
- package/dist/memory/metadata.js +0 -7
- package/dist/memory/probation.d.ts +1 -5
- package/dist/memory/probation.js +2 -6
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/scheduler.d.ts +1 -0
- package/dist/memory/scheduler.js +64 -6
- package/dist/models/auth-cli.d.ts +1 -1
- package/dist/models/auth-cli.js +3 -2
- package/dist/paths.d.ts +0 -6
- package/dist/paths.js +0 -6
- package/dist/playbooks/agent-delegation.md +14 -13
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/catalog.d.ts +2 -2
- package/dist/playbooks/catalog.js +20 -9
- package/dist/playbooks/event-scheduling.md +1 -1
- package/dist/playbooks/memory-and-learning.md +1 -1
- package/dist/playbooks/outbound-media.md +5 -5
- package/dist/playbooks/runtime-orientation.md +6 -1
- package/dist/playbooks/task-driving.md +1 -1
- package/dist/playbooks/task-planning.md +1 -1
- package/dist/runtime/active-session-store.d.ts +42 -0
- package/dist/runtime/active-session-store.js +100 -0
- package/dist/runtime/app-home.d.ts +32 -0
- package/dist/runtime/app-home.js +319 -0
- package/dist/runtime/bootstrap.d.ts +30 -36
- package/dist/runtime/bootstrap.js +344 -502
- package/dist/runtime/channel-event.d.ts +41 -0
- package/dist/runtime/channel-event.js +1 -0
- package/dist/runtime/delivery.d.ts +3 -2
- package/dist/runtime/delivery.js +11 -6
- package/dist/runtime/dingtalk.d.ts +16 -29
- package/dist/runtime/dingtalk.js +5 -12
- package/dist/runtime/durable-dispatch.d.ts +8 -2
- package/dist/runtime/durable-dispatch.js +52 -25
- package/dist/runtime/events.d.ts +3 -2
- package/dist/runtime/events.js +2 -3
- package/dist/runtime/project-commands.d.ts +16 -0
- package/dist/runtime/project-commands.js +112 -0
- package/dist/runtime/project-scope-store.d.ts +31 -0
- package/dist/runtime/project-scope-store.js +102 -0
- package/dist/runtime/subagent-commands.d.ts +8 -6
- package/dist/runtime/subagent-commands.js +302 -64
- package/dist/runtime/task-commands.js +2 -2
- package/dist/runtime/task-driver.d.ts +7 -7
- package/dist/runtime/task-driver.js +1 -4
- package/dist/runtime/task-migration.js +1 -1
- package/dist/runtime/task-wake.d.ts +54 -0
- package/dist/runtime/task-wake.js +99 -0
- package/dist/security/config.js +10 -0
- package/dist/security/logger.js +7 -0
- package/dist/security/path-guard.js +34 -9
- package/dist/security/project-scope.d.ts +45 -0
- package/dist/security/project-scope.js +107 -0
- package/dist/security/types.d.ts +20 -2
- package/dist/settings.d.ts +0 -106
- package/dist/settings.js +0 -224
- package/dist/shared/host-process.d.ts +30 -8
- package/dist/shared/host-process.js +78 -6
- package/dist/shared/jsonl-appender.d.ts +2 -0
- package/dist/shared/jsonl-appender.js +25 -13
- package/dist/shared/types.d.ts +1 -0
- package/dist/shared/types.js +10 -1
- package/dist/shared/wake-claim.d.ts +23 -0
- package/dist/shared/wake-claim.js +26 -0
- 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/discovery.d.ts +33 -1
- package/dist/subagents/discovery.js +139 -25
- package/dist/subagents/external/claude-code.js +13 -7
- package/dist/subagents/external/codex-cli.js +4 -4
- package/dist/subagents/external/exec.js +8 -2
- package/dist/subagents/external/harness.d.ts +22 -3
- package/dist/subagents/external/harness.js +40 -7
- package/dist/subagents/external/run.d.ts +38 -3
- package/dist/subagents/external/run.js +169 -103
- package/dist/subagents/external/settlement.d.ts +50 -0
- package/dist/subagents/external/settlement.js +123 -0
- package/dist/subagents/format.d.ts +16 -0
- package/dist/subagents/format.js +31 -0
- package/dist/subagents/runs.d.ts +139 -13
- package/dist/subagents/runs.js +481 -94
- package/dist/subagents/tool.d.ts +60 -6
- package/dist/subagents/tool.js +274 -159
- package/dist/subagents/verification-outcome.d.ts +26 -0
- package/dist/subagents/verification-outcome.js +16 -0
- package/dist/subagents/workspace-lease.d.ts +10 -1
- package/dist/subagents/workspace-lease.js +15 -2
- package/dist/tasks/control.d.ts +12 -0
- package/dist/tasks/control.js +20 -0
- package/dist/tasks/ledger.js +1 -1
- package/dist/tasks/store.d.ts +21 -0
- package/dist/tasks/store.js +80 -0
- package/dist/{shared → tasks}/task-schedule.js +1 -1
- package/dist/tools/bash.js +4 -4
- package/dist/tools/edit.js +3 -3
- package/dist/tools/event-manage.js +1 -4
- package/dist/tools/grep.js +5 -6
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +15 -2
- package/dist/tools/job.js +5 -5
- package/dist/tools/memory-manage.js +3 -7
- package/dist/tools/read.js +3 -3
- package/dist/tools/registry.js +1 -1
- package/dist/tools/send-media.js +2 -2
- package/dist/tools/session-search.js +0 -1
- package/dist/tools/skill-manage.js +3 -3
- package/dist/tools/subagent-manage.d.ts +22 -3
- package/dist/tools/subagent-manage.js +156 -52
- package/dist/tools/task-manage/shared.js +2 -2
- package/dist/tools/task-manage.js +1 -4
- package/dist/tools/web-fetch.js +0 -1
- package/dist/tools/write-content.js +3 -3
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.js +53 -6
- package/dist/tui/cli.d.ts +1 -1
- package/dist/tui/cli.js +1 -1
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +2 -0
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/dist/tui/turn-controller.d.ts +1 -0
- package/dist/tui/turn-controller.js +1 -0
- package/dist/usage/ledger.d.ts +7 -0
- package/dist/usage/ledger.js +15 -2
- package/dist/usage/render.js +22 -0
- package/examples/sub-agents/README.md +27 -13
- package/examples/sub-agents/builder-hard.md +9 -8
- package/examples/sub-agents/builder.md +12 -11
- package/examples/sub-agents/documenter.md +10 -13
- package/examples/sub-agents/explorer.md +16 -13
- package/examples/sub-agents/git-committer.md +33 -40
- package/examples/sub-agents/log-sifter.md +19 -16
- package/examples/sub-agents/planner.md +17 -17
- package/examples/sub-agents/reviewer.md +11 -15
- package/examples/sub-agents/scout.md +5 -6
- package/examples/sub-agents/verifier.md +8 -11
- package/examples/sub-agents/worker.md +6 -7
- package/package.json +1 -1
- /package/dist/{shared → tasks}/task-events.d.ts +0 -0
- /package/dist/{shared → tasks}/task-events.js +0 -0
- /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 {
|
|
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
|
-
|
|
100
|
-
|
|
101
|
-
|
|
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
|
-
|
|
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.
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
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
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
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
|
-
|
|
394
|
-
|
|
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
|
-
|
|
399
|
-
|
|
400
|
-
|
|
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
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
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
|
-
|
|
419
|
-
|
|
420
|
-
|
|
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
|
-
|
|
430
|
-
|
|
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
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
await
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
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
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
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();
|
|
@@ -799,12 +917,18 @@ export class ChannelRunner {
|
|
|
799
917
|
agent: this.agent,
|
|
800
918
|
sessionManager: this.sessionManager,
|
|
801
919
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
802
|
-
cwd:
|
|
920
|
+
cwd: this.projectScope.projectRoot,
|
|
803
921
|
modelRuntime: this.modelRuntime,
|
|
804
922
|
resourceLoader: initialResourceLoader,
|
|
805
923
|
baseToolsOverride,
|
|
806
924
|
});
|
|
807
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);
|
|
808
932
|
const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
|
|
809
933
|
return {
|
|
810
934
|
session: next.session,
|
|
@@ -832,7 +956,12 @@ export class ChannelRunner {
|
|
|
832
956
|
this.currentSkills = skills;
|
|
833
957
|
this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
|
|
834
958
|
this.rebuildSessionTools();
|
|
835
|
-
|
|
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
|
+
}
|
|
836
965
|
}
|
|
837
966
|
async bindSessionExtensions() {
|
|
838
967
|
await this.session.bindExtensions({
|
|
@@ -883,7 +1012,16 @@ export class ChannelRunner {
|
|
|
883
1012
|
}
|
|
884
1013
|
}
|
|
885
1014
|
async refreshSubAgentDiscovery() {
|
|
886
|
-
|
|
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
|
+
}
|
|
887
1025
|
const discovery = discoverSubAgents(this.workspaceDir, this.modelRegistry.getAvailable());
|
|
888
1026
|
for (const warning of discovery.warnings) {
|
|
889
1027
|
log.logWarning(`Sub-agent config warning (${this.channelId})`, warning);
|
|
@@ -916,7 +1054,7 @@ export class ChannelRunner {
|
|
|
916
1054
|
this.lastWorkspaceResources = resources;
|
|
917
1055
|
const build = buildPipiclawSystemPrompt({
|
|
918
1056
|
mode: "normal",
|
|
919
|
-
cwd:
|
|
1057
|
+
cwd: this.projectScope.projectRoot,
|
|
920
1058
|
workspaceDir: this.workspaceDir,
|
|
921
1059
|
tools: this.currentTools.map((tool) => ({
|
|
922
1060
|
name: tool.name,
|
|
@@ -950,7 +1088,7 @@ export class ChannelRunner {
|
|
|
950
1088
|
}
|
|
951
1089
|
createResourceLoader() {
|
|
952
1090
|
return new DefaultResourceLoader({
|
|
953
|
-
cwd:
|
|
1091
|
+
cwd: this.projectScope.projectRoot,
|
|
954
1092
|
agentDir: this.appHomeDir,
|
|
955
1093
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
956
1094
|
extensionFactories: [
|
|
@@ -1005,7 +1143,7 @@ export class ChannelRunner {
|
|
|
1005
1143
|
}
|
|
1006
1144
|
createAgentSessionServices(resourceLoader) {
|
|
1007
1145
|
return {
|
|
1008
|
-
cwd:
|
|
1146
|
+
cwd: this.projectScope.projectRoot,
|
|
1009
1147
|
agentDir: this.appHomeDir,
|
|
1010
1148
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
1011
1149
|
modelRuntime: this.modelRuntime,
|
|
@@ -1057,7 +1195,7 @@ export class ChannelRunner {
|
|
|
1057
1195
|
agent,
|
|
1058
1196
|
sessionManager,
|
|
1059
1197
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
1060
|
-
cwd:
|
|
1198
|
+
cwd: this.projectScope.projectRoot,
|
|
1061
1199
|
modelRuntime: this.modelRuntime,
|
|
1062
1200
|
resourceLoader,
|
|
1063
1201
|
baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
|
|
@@ -1076,6 +1214,7 @@ export class ChannelRunner {
|
|
|
1076
1214
|
getAvailableModels: () => this.modelRegistry.getAvailable(),
|
|
1077
1215
|
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
1078
1216
|
workspaceDir: this.workspaceDir,
|
|
1217
|
+
projectScope: this.projectScope,
|
|
1079
1218
|
channelDir: this.channelDir,
|
|
1080
1219
|
channelId: this.channelId,
|
|
1081
1220
|
getSubAgentDiscovery: () => this.subAgentDiscovery,
|
package/dist/agent/commands.d.ts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
export type BuiltInCommandName = "help" | "steer" | "followup" | "stop" | "events" | "tasks" | "status" | "usage" | "context" | "subagents";
|
|
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;
|
package/dist/agent/commands.js
CHANGED
|
@@ -83,13 +83,30 @@ 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,
|
|
92
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
|
+
},
|
|
93
110
|
];
|
|
94
111
|
/**
|
|
95
112
|
* Session commands: handled inside the Pipiclaw session layer (SDK command
|
package/dist/agent/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { createRunner } from "./runner-factory.js";
|
|
2
2
|
export type { AgentRunner } from "./types.js";
|
package/dist/agent/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { createRunner } from "./runner-factory.js";
|