@oyasmi/pipiclaw 0.9.0-beta.9 → 0.9.0
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 +7 -0
- package/dist/agent/channel-runner.js +52 -8
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +9 -0
- package/dist/agent/job-manager.d.ts +20 -0
- package/dist/agent/job-manager.js +14 -0
- package/dist/agent/turn-recovery.d.ts +72 -0
- package/dist/agent/turn-recovery.js +193 -0
- package/dist/playbooks/agent-delegation.md +3 -3
- package/dist/playbooks/runtime-orientation.md +5 -0
- package/dist/runtime/active-session-store.d.ts +42 -0
- package/dist/runtime/active-session-store.js +100 -0
- package/dist/runtime/bootstrap.js +48 -3
- package/dist/runtime/dingtalk.js +2 -1
- 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/security/config.js +10 -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/subagents/tool.d.ts +2 -0
- package/dist/subagents/tool.js +8 -2
- package/dist/tools/bash.js +3 -3
- package/dist/tools/edit.js +3 -3
- package/dist/tools/grep.js +3 -3
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +7 -2
- 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/write-content.js +3 -3
- package/dist/tui/app.js +47 -1
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +2 -0
- package/dist/tui/turn-controller.d.ts +1 -0
- package/dist/tui/turn-controller.js +1 -0
- package/package.json +1 -1
|
@@ -17,6 +17,13 @@ export declare class ChannelRunner implements AgentRunner {
|
|
|
17
17
|
private readonly mediaSender?;
|
|
18
18
|
private readonly dispatchVerification?;
|
|
19
19
|
private readonly workspaceDir;
|
|
20
|
+
/**
|
|
21
|
+
* Frozen for the lifetime of this runner generation (spec 043, D4.2): AgentSession, the
|
|
22
|
+
* ResourceLoader, and every tool closure built in this constructor and in `createSessionRuntime`
|
|
23
|
+
* (session-topology rebuilds only rebind the session, never the scope) all read this same value.
|
|
24
|
+
* Changing project is a dispose-and-rebuild of the whole runner, not a field mutation.
|
|
25
|
+
*/
|
|
26
|
+
private readonly projectScope;
|
|
20
27
|
private session;
|
|
21
28
|
private agent;
|
|
22
29
|
private sessionManager;
|
|
@@ -16,7 +16,10 @@ 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";
|
|
22
|
+
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
20
23
|
import { formatConfigDiagnostic } from "../shared/config-diagnostic.js";
|
|
21
24
|
import { formatLocalTime, localStampForFilename } from "../shared/local-time.js";
|
|
22
25
|
import { countPromptUnits } from "../shared/prompt-units.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";
|
|
@@ -107,12 +111,45 @@ export class ChannelRunner {
|
|
|
107
111
|
const executor = createExecutor();
|
|
108
112
|
this.executor = executor;
|
|
109
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;
|
|
110
127
|
// Initial skill summaries
|
|
111
128
|
const initialSkills = loadPipiclawSkills(channelDir);
|
|
112
129
|
this.currentSkills = initialSkills;
|
|
113
|
-
// Create session manager
|
|
114
|
-
|
|
115
|
-
|
|
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
|
+
}
|
|
116
153
|
this.settingsManager = paths.settingsManager;
|
|
117
154
|
this.reportSettingsDiagnostics();
|
|
118
155
|
this.memoryCandidateStore = createMemoryCandidateStore();
|
|
@@ -880,12 +917,18 @@ export class ChannelRunner {
|
|
|
880
917
|
agent: this.agent,
|
|
881
918
|
sessionManager: this.sessionManager,
|
|
882
919
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
883
|
-
cwd:
|
|
920
|
+
cwd: this.projectScope.projectRoot,
|
|
884
921
|
modelRuntime: this.modelRuntime,
|
|
885
922
|
resourceLoader: initialResourceLoader,
|
|
886
923
|
baseToolsOverride,
|
|
887
924
|
});
|
|
888
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);
|
|
889
932
|
const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
|
|
890
933
|
return {
|
|
891
934
|
session: next.session,
|
|
@@ -1011,7 +1054,7 @@ export class ChannelRunner {
|
|
|
1011
1054
|
this.lastWorkspaceResources = resources;
|
|
1012
1055
|
const build = buildPipiclawSystemPrompt({
|
|
1013
1056
|
mode: "normal",
|
|
1014
|
-
cwd:
|
|
1057
|
+
cwd: this.projectScope.projectRoot,
|
|
1015
1058
|
workspaceDir: this.workspaceDir,
|
|
1016
1059
|
tools: this.currentTools.map((tool) => ({
|
|
1017
1060
|
name: tool.name,
|
|
@@ -1045,7 +1088,7 @@ export class ChannelRunner {
|
|
|
1045
1088
|
}
|
|
1046
1089
|
createResourceLoader() {
|
|
1047
1090
|
return new DefaultResourceLoader({
|
|
1048
|
-
cwd:
|
|
1091
|
+
cwd: this.projectScope.projectRoot,
|
|
1049
1092
|
agentDir: this.appHomeDir,
|
|
1050
1093
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
1051
1094
|
extensionFactories: [
|
|
@@ -1100,7 +1143,7 @@ export class ChannelRunner {
|
|
|
1100
1143
|
}
|
|
1101
1144
|
createAgentSessionServices(resourceLoader) {
|
|
1102
1145
|
return {
|
|
1103
|
-
cwd:
|
|
1146
|
+
cwd: this.projectScope.projectRoot,
|
|
1104
1147
|
agentDir: this.appHomeDir,
|
|
1105
1148
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
1106
1149
|
modelRuntime: this.modelRuntime,
|
|
@@ -1152,7 +1195,7 @@ export class ChannelRunner {
|
|
|
1152
1195
|
agent,
|
|
1153
1196
|
sessionManager,
|
|
1154
1197
|
settingsManager: asSdkSettingsManager(this.settingsManager),
|
|
1155
|
-
cwd:
|
|
1198
|
+
cwd: this.projectScope.projectRoot,
|
|
1156
1199
|
modelRuntime: this.modelRuntime,
|
|
1157
1200
|
resourceLoader,
|
|
1158
1201
|
baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
|
|
@@ -1171,6 +1214,7 @@ export class ChannelRunner {
|
|
|
1171
1214
|
getAvailableModels: () => this.modelRegistry.getAvailable(),
|
|
1172
1215
|
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
1173
1216
|
workspaceDir: this.workspaceDir,
|
|
1217
|
+
projectScope: this.projectScope,
|
|
1174
1218
|
channelDir: this.channelDir,
|
|
1175
1219
|
channelId: this.channelId,
|
|
1176
1220
|
getSubAgentDiscovery: () => this.subAgentDiscovery,
|
package/dist/agent/commands.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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
4
|
/**
|
package/dist/agent/commands.js
CHANGED
|
@@ -98,6 +98,15 @@ export const BUILT_IN_COMMANDS = [
|
|
|
98
98
|
// dispatched delegation, so cancel must work even when the model/turn is unavailable.
|
|
99
99
|
availableWhileBusy: true,
|
|
100
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
|
+
},
|
|
101
110
|
];
|
|
102
111
|
/**
|
|
103
112
|
* Session commands: handled inside the Pipiclaw session layer (SDK command
|
|
@@ -35,6 +35,19 @@ export interface JobWakeContract {
|
|
|
35
35
|
/** The task this job is advancing, surfaced in the wake so the model lands in context. */
|
|
36
36
|
taskId?: string;
|
|
37
37
|
}
|
|
38
|
+
interface JobRecord extends JobSnapshot {
|
|
39
|
+
pid: number;
|
|
40
|
+
spillFile: string;
|
|
41
|
+
exitFile: string;
|
|
42
|
+
timeoutSeconds: number;
|
|
43
|
+
contract: JobWakeContract;
|
|
44
|
+
/** When the job reached a terminal status; drives retention of the record and spill file. */
|
|
45
|
+
finishedAt?: number;
|
|
46
|
+
/** Set once the completion wake has been dispatched, so a restart cannot re-announce it. */
|
|
47
|
+
notified?: boolean;
|
|
48
|
+
wakeClaimDispatchId?: string;
|
|
49
|
+
wakeConsumedAt?: number;
|
|
50
|
+
}
|
|
38
51
|
export interface JobStartOptions {
|
|
39
52
|
signal?: AbortSignal;
|
|
40
53
|
notify?: boolean;
|
|
@@ -93,6 +106,7 @@ export declare class ChannelJobManager {
|
|
|
93
106
|
private scheduleGarbageCollection;
|
|
94
107
|
get channel(): string;
|
|
95
108
|
runningCount(): number;
|
|
109
|
+
listRunning(): JobRecord[];
|
|
96
110
|
/** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
|
|
97
111
|
runningTaskIds(): Set<string>;
|
|
98
112
|
/**
|
|
@@ -182,6 +196,12 @@ export declare function configureJobRuntime(config: JobRuntimeConfig): void;
|
|
|
182
196
|
* manager simply has no jobs, and the empty set is the right answer.
|
|
183
197
|
*/
|
|
184
198
|
export declare function channelJobTaskIds(channelId: string): Set<string>;
|
|
199
|
+
/**
|
|
200
|
+
* Human-readable lines naming this channel's currently running background jobs, for the `/project
|
|
201
|
+
* set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no
|
|
202
|
+
* jobs" reasoning, so it needs no `Executor` either.
|
|
203
|
+
*/
|
|
204
|
+
export declare function channelRunningJobLines(channelId: string): string[];
|
|
185
205
|
export declare function getChannelJobManager(channelId: string, executor: Executor): ChannelJobManager;
|
|
186
206
|
/**
|
|
187
207
|
* Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
|
|
@@ -150,6 +150,9 @@ export class ChannelJobManager {
|
|
|
150
150
|
runningCount() {
|
|
151
151
|
return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
|
|
152
152
|
}
|
|
153
|
+
listRunning() {
|
|
154
|
+
return Array.from(this.jobs.values()).filter((job) => job.status === "running");
|
|
155
|
+
}
|
|
153
156
|
/** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
|
|
154
157
|
runningTaskIds() {
|
|
155
158
|
const ids = new Set();
|
|
@@ -554,6 +557,17 @@ export function configureJobRuntime(config) {
|
|
|
554
557
|
export function channelJobTaskIds(channelId) {
|
|
555
558
|
return managers.get(channelId)?.runningTaskIds() ?? new Set();
|
|
556
559
|
}
|
|
560
|
+
/**
|
|
561
|
+
* Human-readable lines naming this channel's currently running background jobs, for the `/project
|
|
562
|
+
* set|reset` blocker check (spec 043, D4.3) — mirrors `channelJobTaskIds`'s "no manager means no
|
|
563
|
+
* jobs" reasoning, so it needs no `Executor` either.
|
|
564
|
+
*/
|
|
565
|
+
export function channelRunningJobLines(channelId) {
|
|
566
|
+
const manager = managers.get(channelId);
|
|
567
|
+
if (!manager)
|
|
568
|
+
return [];
|
|
569
|
+
return manager.listRunning().map((job) => `job \`${job.id}\`: ${job.command.slice(0, 80)}`);
|
|
570
|
+
}
|
|
557
571
|
export function getChannelJobManager(channelId, executor) {
|
|
558
572
|
let manager = managers.get(channelId);
|
|
559
573
|
if (!manager) {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
2
|
+
import { type SessionEntry, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
interface DeclaredToolCall {
|
|
4
|
+
id: string;
|
|
5
|
+
name: string;
|
|
6
|
+
/** Index into the branch's message-entry sequence (source order), used to detect anomalies. */
|
|
7
|
+
entryIndex: number;
|
|
8
|
+
}
|
|
9
|
+
export type RepairPlan = {
|
|
10
|
+
kind: "none";
|
|
11
|
+
} | {
|
|
12
|
+
kind: "append-aborted-assistant";
|
|
13
|
+
} | {
|
|
14
|
+
kind: "append-tool-results";
|
|
15
|
+
calls: DeclaredToolCall[];
|
|
16
|
+
} | {
|
|
17
|
+
kind: "blocked";
|
|
18
|
+
reason: string;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Pure D11 planner: declared − fulfilled → the one repair action to take, or `blocked` when the
|
|
22
|
+
* branch's shape doesn't match a plain crash window (P7: an undecidable shape stops the channel,
|
|
23
|
+
* it never guesses).
|
|
24
|
+
*/
|
|
25
|
+
export declare function planTurnRecovery(branch: SessionEntry[]): RepairPlan;
|
|
26
|
+
/** Fallback identity for the runtime-authored aborted assistant when the branch has no prior
|
|
27
|
+
* assistant message to copy api/provider/model from (e.g. crash before the first response ever
|
|
28
|
+
* landed). Never sent to a provider — this is a resolved message, not a request. */
|
|
29
|
+
export interface FallbackModelIdentity {
|
|
30
|
+
api: AssistantMessage["api"];
|
|
31
|
+
provider: AssistantMessage["provider"];
|
|
32
|
+
model: string;
|
|
33
|
+
}
|
|
34
|
+
export type TurnRecoveryOutcome = {
|
|
35
|
+
kind: "clean";
|
|
36
|
+
} | {
|
|
37
|
+
kind: "repaired";
|
|
38
|
+
appendedToolResults: number;
|
|
39
|
+
appendedAbortedAssistant: boolean;
|
|
40
|
+
} | {
|
|
41
|
+
kind: "blocked";
|
|
42
|
+
reason: string;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Runs the D11 plan against `sessionManager`'s current branch and, if a repair is called for,
|
|
46
|
+
* applies it via `appendMessage()` — the only mutation path (D12): never a direct rewrite of the
|
|
47
|
+
* JSONL file, never a tool call, never a model call, never a second delivery attempt.
|
|
48
|
+
*/
|
|
49
|
+
export declare function recoverInterruptedTurn(sessionManager: SessionManager, fallbackModel: FallbackModelIdentity): TurnRecoveryOutcome;
|
|
50
|
+
export interface WorkspaceRecoveryReport {
|
|
51
|
+
scanned: number;
|
|
52
|
+
repaired: Array<{
|
|
53
|
+
channelDir: string;
|
|
54
|
+
outcome: Extract<TurnRecoveryOutcome, {
|
|
55
|
+
kind: "repaired";
|
|
56
|
+
}>;
|
|
57
|
+
}>;
|
|
58
|
+
blocked: Array<{
|
|
59
|
+
channelDir: string;
|
|
60
|
+
reason: string;
|
|
61
|
+
}>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Daemon-startup half of D10: scans every channel directory under `workspaceDir` and repairs any
|
|
65
|
+
* interrupted turn found, *before* the daemon accepts traffic (point 1). Each channel gets its own
|
|
66
|
+
* fresh `SessionManager` here — safe because, at this point in startup, no `ChannelRunner` for any
|
|
67
|
+
* of these channels has been constructed yet, so nothing else holds a competing in-memory instance
|
|
68
|
+
* over the same file. `ChannelRunner`'s own constructor (D10 point 2) covers everything this scan
|
|
69
|
+
* cannot: a channel created after this scan ran, and re-running the barrier is idempotent either way.
|
|
70
|
+
*/
|
|
71
|
+
export declare function scanWorkspaceForInterruptedTurns(workspaceDir: string, fallbackModel: FallbackModelIdentity): Promise<WorkspaceRecoveryReport>;
|
|
72
|
+
export {};
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { readdir } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { resolveActiveSessionFile } from "../runtime/active-session-store.js";
|
|
5
|
+
/**
|
|
6
|
+
* Repairs a session branch left with a declared-but-unfulfilled tool call by a process that
|
|
7
|
+
* exited between the assistant's tool call and the tool result being recorded (spec 043, D8-D16).
|
|
8
|
+
*
|
|
9
|
+
* The only thing this module does is make the branch structurally legal again (every declared
|
|
10
|
+
* tool call has a result) and honest about what happened (a runtime-authored, clearly-labeled
|
|
11
|
+
* message, never something dressed up as a real model or tool response). It never executes a
|
|
12
|
+
* tool, never calls a model, and never repeats a side effect — see D9/P6 for why that boundary is
|
|
13
|
+
* load-bearing, not just caution.
|
|
14
|
+
*/
|
|
15
|
+
const SYNTHETIC_TOOL_RESULT_HEADER = "Error: Pipiclaw restarted before a durable result was recorded for this tool call.\n" +
|
|
16
|
+
"The operation may or may not have taken effect. Inspect the current target state before retrying; " +
|
|
17
|
+
"do not repeat the operation blindly.";
|
|
18
|
+
const SYNTHETIC_ABORTED_ASSISTANT_TEXT = "Error: Pipiclaw restarted before a response was generated. Re-send the request if it is still needed.";
|
|
19
|
+
function toolGuidance(toolName) {
|
|
20
|
+
if (toolName === "subagent" || toolName === "subagent_manage") {
|
|
21
|
+
return "先用 `subagent_manage op=list` / `show` 查询这次委派是否已经作为一个 durable run 存在。";
|
|
22
|
+
}
|
|
23
|
+
if (toolName === "job" || toolName === "bash") {
|
|
24
|
+
return "若这是一次异步操作(后台 job 或已启动的进程),先用 job `list` / `poll` 查记录,再决定是否需要重跑。";
|
|
25
|
+
}
|
|
26
|
+
if (toolName === "write" || toolName === "edit") {
|
|
27
|
+
return "用 read / grep / git status 检查目标文件的当前内容,再决定是否需要重新执行。";
|
|
28
|
+
}
|
|
29
|
+
if (toolName === "send_media") {
|
|
30
|
+
return "查询目标系统或向用户确认对方是否已经收到,不要自动再发一次。";
|
|
31
|
+
}
|
|
32
|
+
return "检查目标状态后再决定是否需要重试,不要盲目重复这次调用。";
|
|
33
|
+
}
|
|
34
|
+
function messageEntriesOf(branch) {
|
|
35
|
+
return branch.filter((entry) => entry.type === "message");
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Pure D11 planner: declared − fulfilled → the one repair action to take, or `blocked` when the
|
|
39
|
+
* branch's shape doesn't match a plain crash window (P7: an undecidable shape stops the channel,
|
|
40
|
+
* it never guesses).
|
|
41
|
+
*/
|
|
42
|
+
export function planTurnRecovery(branch) {
|
|
43
|
+
const entries = messageEntriesOf(branch);
|
|
44
|
+
if (entries.length === 0) {
|
|
45
|
+
return { kind: "none" };
|
|
46
|
+
}
|
|
47
|
+
const declared = [];
|
|
48
|
+
const fulfilled = new Set();
|
|
49
|
+
for (let i = 0; i < entries.length; i++) {
|
|
50
|
+
const message = entries[i].message;
|
|
51
|
+
if (message.role === "assistant") {
|
|
52
|
+
for (const item of message.content) {
|
|
53
|
+
if (item.type === "toolCall") {
|
|
54
|
+
declared.push({ id: item.id, name: item.name, entryIndex: i });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
else if (message.role === "toolResult") {
|
|
59
|
+
if (fulfilled.has(message.toolCallId)) {
|
|
60
|
+
return { kind: "blocked", reason: `Duplicate tool result recorded for tool call ${message.toolCallId}.` };
|
|
61
|
+
}
|
|
62
|
+
fulfilled.add(message.toolCallId);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const missing = declared.filter((call) => !fulfilled.has(call.id));
|
|
66
|
+
if (missing.length > 0) {
|
|
67
|
+
const firstMissingIndex = missing[0].entryIndex;
|
|
68
|
+
// Sibling calls declared by the *same* assistant message as the first missing one are
|
|
69
|
+
// expected to show up as results in any order (parallel tool calls) — only a message that
|
|
70
|
+
// isn't one of them signals a genuine anomaly, not the ordinary interleaving of results.
|
|
71
|
+
const siblingIds = new Set(declared.filter((call) => call.entryIndex === firstMissingIndex).map((call) => call.id));
|
|
72
|
+
for (let i = firstMissingIndex + 1; i < entries.length; i++) {
|
|
73
|
+
const message = entries[i].message;
|
|
74
|
+
const isExpectedResult = message.role === "toolResult" && siblingIds.has(message.toolCallId);
|
|
75
|
+
if (!isExpectedResult) {
|
|
76
|
+
return {
|
|
77
|
+
kind: "blocked",
|
|
78
|
+
reason: "A message unrelated to the missing tool result(s) appears after them; this is not a plain " +
|
|
79
|
+
"crash window and cannot be safely repaired automatically.",
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { kind: "append-tool-results", calls: missing };
|
|
84
|
+
}
|
|
85
|
+
const last = entries[entries.length - 1].message;
|
|
86
|
+
if (last.role === "user") {
|
|
87
|
+
return { kind: "append-aborted-assistant" };
|
|
88
|
+
}
|
|
89
|
+
return { kind: "none" };
|
|
90
|
+
}
|
|
91
|
+
function mostRecentAssistant(branch) {
|
|
92
|
+
for (let i = branch.length - 1; i >= 0; i--) {
|
|
93
|
+
const entry = branch[i];
|
|
94
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
95
|
+
return entry.message;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
const ZERO_USAGE = {
|
|
101
|
+
input: 0,
|
|
102
|
+
output: 0,
|
|
103
|
+
cacheRead: 0,
|
|
104
|
+
cacheWrite: 0,
|
|
105
|
+
totalTokens: 0,
|
|
106
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Runs the D11 plan against `sessionManager`'s current branch and, if a repair is called for,
|
|
110
|
+
* applies it via `appendMessage()` — the only mutation path (D12): never a direct rewrite of the
|
|
111
|
+
* JSONL file, never a tool call, never a model call, never a second delivery attempt.
|
|
112
|
+
*/
|
|
113
|
+
export function recoverInterruptedTurn(sessionManager, fallbackModel) {
|
|
114
|
+
const branch = sessionManager.getBranch();
|
|
115
|
+
const plan = planTurnRecovery(branch);
|
|
116
|
+
if (plan.kind === "blocked") {
|
|
117
|
+
return plan;
|
|
118
|
+
}
|
|
119
|
+
if (plan.kind === "none") {
|
|
120
|
+
return { kind: "clean" };
|
|
121
|
+
}
|
|
122
|
+
if (plan.kind === "append-tool-results") {
|
|
123
|
+
for (const call of plan.calls) {
|
|
124
|
+
sessionManager.appendMessage({
|
|
125
|
+
role: "toolResult",
|
|
126
|
+
toolCallId: call.id,
|
|
127
|
+
toolName: call.name,
|
|
128
|
+
content: [{ type: "text", text: `${SYNTHETIC_TOOL_RESULT_HEADER}\n\n${toolGuidance(call.name)}` }],
|
|
129
|
+
isError: true,
|
|
130
|
+
timestamp: Date.now(),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return { kind: "repaired", appendedToolResults: plan.calls.length, appendedAbortedAssistant: false };
|
|
134
|
+
}
|
|
135
|
+
// plan.kind === "append-aborted-assistant"
|
|
136
|
+
const recent = mostRecentAssistant(branch);
|
|
137
|
+
const stopReason = "aborted";
|
|
138
|
+
sessionManager.appendMessage({
|
|
139
|
+
role: "assistant",
|
|
140
|
+
content: [{ type: "text", text: SYNTHETIC_ABORTED_ASSISTANT_TEXT }],
|
|
141
|
+
api: recent?.api ?? fallbackModel.api,
|
|
142
|
+
provider: recent?.provider ?? fallbackModel.provider,
|
|
143
|
+
model: recent?.model ?? fallbackModel.model,
|
|
144
|
+
usage: ZERO_USAGE,
|
|
145
|
+
stopReason,
|
|
146
|
+
timestamp: Date.now(),
|
|
147
|
+
});
|
|
148
|
+
return { kind: "repaired", appendedToolResults: 0, appendedAbortedAssistant: true };
|
|
149
|
+
}
|
|
150
|
+
/** A workspace child directory belongs to a channel iff its name starts with one of these
|
|
151
|
+
* prefixes — matches `channel-paths.ts`'s `CHANNEL_ID_PATTERN` without needing to reverse its
|
|
152
|
+
* `/` → `__` escaping, and skips AgentWorkspace resource dirs (skills/, sub-agents/, events/…). */
|
|
153
|
+
const CHANNEL_DIR_PREFIXES = ["dm_", "group_"];
|
|
154
|
+
/**
|
|
155
|
+
* Daemon-startup half of D10: scans every channel directory under `workspaceDir` and repairs any
|
|
156
|
+
* interrupted turn found, *before* the daemon accepts traffic (point 1). Each channel gets its own
|
|
157
|
+
* fresh `SessionManager` here — safe because, at this point in startup, no `ChannelRunner` for any
|
|
158
|
+
* of these channels has been constructed yet, so nothing else holds a competing in-memory instance
|
|
159
|
+
* over the same file. `ChannelRunner`'s own constructor (D10 point 2) covers everything this scan
|
|
160
|
+
* cannot: a channel created after this scan ran, and re-running the barrier is idempotent either way.
|
|
161
|
+
*/
|
|
162
|
+
export async function scanWorkspaceForInterruptedTurns(workspaceDir, fallbackModel) {
|
|
163
|
+
const report = { scanned: 0, repaired: [], blocked: [] };
|
|
164
|
+
let entries;
|
|
165
|
+
try {
|
|
166
|
+
entries = await readdir(workspaceDir, { withFileTypes: true });
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return report;
|
|
170
|
+
}
|
|
171
|
+
for (const entry of entries) {
|
|
172
|
+
if (!entry.isDirectory() || !CHANNEL_DIR_PREFIXES.some((prefix) => entry.name.startsWith(prefix))) {
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const channelDir = join(workspaceDir, entry.name);
|
|
176
|
+
report.scanned++;
|
|
177
|
+
try {
|
|
178
|
+
const activeSessionFile = resolveActiveSessionFile(channelDir);
|
|
179
|
+
const sessionManager = SessionManager.open(join(channelDir, activeSessionFile), channelDir);
|
|
180
|
+
const outcome = recoverInterruptedTurn(sessionManager, fallbackModel);
|
|
181
|
+
if (outcome.kind === "repaired") {
|
|
182
|
+
report.repaired.push({ channelDir, outcome });
|
|
183
|
+
}
|
|
184
|
+
else if (outcome.kind === "blocked") {
|
|
185
|
+
report.blocked.push({ channelDir, reason: outcome.reason });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
report.blocked.push({ channelDir, reason: error instanceof Error ? error.message : String(error) });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return report;
|
|
193
|
+
}
|
|
@@ -36,10 +36,10 @@ order: 36
|
|
|
36
36
|
|
|
37
37
|
## 三、工作目录:每次委派现场决定
|
|
38
38
|
|
|
39
|
-
角色文件里没有默认工作目录,也不会有——同一个角色这次改 A 仓库、下次改 B
|
|
39
|
+
角色文件里没有默认工作目录,也不会有——同一个角色这次改 A 仓库、下次改 B 仓库,一个写死在角色定义里的默认值只会让人跳过该做的判断。省略 `workingDirectory` 时委派落到**当前频道的项目目录**(本回合你自己的工作面),这不是"没有默认值",只是默认值等于你此刻所在的地方;并行写入分片仍然必须各自显式指定,否则两个 run 会悄悄落到同一棵树上。因此:
|
|
40
40
|
|
|
41
|
-
-
|
|
42
|
-
-
|
|
41
|
+
- **并行的写入分片各自显式传 `workingDirectory`(`git worktree add` 后指向不同 checkout)**,不要依赖默认值让它们自动分开——它们不会。
|
|
42
|
+
- 频道配置了项目边界时,`workingDirectory` 必须落在当前项目目录内;传一个目录外的路径会被直接拒绝(`workingDirectory "..." must be inside the project root`),不是先派发再核实。
|
|
43
43
|
- runtime 只在**委派之间**保证排他写锁:`mutates: write` 的 run 会占住目标目录,第二个写入者被拒时错误会点名持有者 runId。锁触发说明分片设计已经出错,它是兜底而不是免于思考的理由。**这把锁只保护声明了 `mutates: write` 的委派**——内置角色的 `mutates` 是按 `tools` 推定(只看 `write`/`edit`,不看 `bash`),外部角色是自述,两者都可能与角色实际行为不符,写清楚 `mutates` 是你的责任,不是 runtime 能替你核实的事。
|
|
44
44
|
- **你自己的 `write` / `edit` / `bash` 不受这把锁保护。** 一个目录上有活跃写委派时,不要同时自己去改它——先等它结束,或者换一棵 worktree。
|
|
45
45
|
- **创建的 worktree 在使用结束后要记得关闭**
|
|
@@ -39,6 +39,11 @@ Workspace 根目录:
|
|
|
39
39
|
- `sub-agents/`:工作区配置的子代理;只加载实际存在的 Markdown 文件。
|
|
40
40
|
- `events/`:全 workspace 的调度事件。
|
|
41
41
|
|
|
42
|
+
项目目录(ProjectRoot):
|
|
43
|
+
|
|
44
|
+
- 与上面的 workspace 根目录是两个不同的东西。`read` / `write` / `edit` / `grep` / `bash` 等通用文件工具和 shell 的 cwd 都以**项目目录**为准,不是 workspace 根目录——workspace 根目录下的文件(`SOUL.md`/`AGENTS.md`/`skills/` 等)要用各自的专用工具(`skill_manage` 等)或只读注入访问,不能假设通用文件工具能直接读写到那里。
|
|
45
|
+
- 频道配置了项目边界(`security.json` 的 `projectAccess`)时,通用文件工具与 sub-agent 默认工作目录都被限制在这个目录内,越界会被直接拒绝;未配置时沿用旧的全局文件权限。人可以用 `/project` 查看或切换当前项目目录,这是运行时命令,不经过模型。
|
|
46
|
+
|
|
42
47
|
当前 channel 目录:
|
|
43
48
|
|
|
44
49
|
- `SESSION.md`:当前工作状态,runtime 维护。
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Points a channel at the one session file it currently considers active. Spec 043, D1.
|
|
3
|
+
*
|
|
4
|
+
* Only the pointer is persisted here — never messages, branches, or project state. A missing ref
|
|
5
|
+
* means "this channel has never run a session-topology operation"; it is interpreted as
|
|
6
|
+
* `context.jsonl` (today's fixed name) rather than written eagerly, so a channel that never calls
|
|
7
|
+
* `/new`/fork/switch never gains an `active-session.json` at all.
|
|
8
|
+
*/
|
|
9
|
+
export interface ActiveSessionRefV1 {
|
|
10
|
+
version: 1;
|
|
11
|
+
/** Basename only — see `isValidSessionRefBasename`. */
|
|
12
|
+
file: string;
|
|
13
|
+
sessionId: string;
|
|
14
|
+
updatedAt: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function getActiveSessionRefPath(channelDir: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* The ref's `file` is opened for append under `channelDir`, and the ref itself lives in a
|
|
19
|
+
* directory a chat participant can otherwise influence the contents of. Reject anything that
|
|
20
|
+
* isn't a plain, single-segment `.jsonl` name so this can never be used to open or create a file
|
|
21
|
+
* outside the channel directory.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isValidSessionRefBasename(file: string): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Resolves which session file a channel should open (runner construction / restart), migrating a
|
|
26
|
+
* channel with no ref to `context.jsonl` and materializing that file. Never writes the ref
|
|
27
|
+
* itself — a missing ref stays missing until a session-topology operation commits one.
|
|
28
|
+
*/
|
|
29
|
+
export declare function resolveActiveSessionFile(channelDir: string): string;
|
|
30
|
+
export interface SessionFileHandle {
|
|
31
|
+
getSessionFile(): string | undefined;
|
|
32
|
+
getSessionId(): string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Commits the active-session ref for a session a topology operation (`/new`, fork, switch) has
|
|
36
|
+
* already created/opened. The SDK writes that session's durable header synchronously before
|
|
37
|
+
* invoking the caller's rebuild callback, so by the time this is called the target file already
|
|
38
|
+
* exists on disk; this only records the pointer. Callers must not rebind their live `AgentSession`
|
|
39
|
+
* until this resolves (spec 043, D1.3) — on throw, nothing is written and the old ref (and thus
|
|
40
|
+
* the old session) remains authoritative.
|
|
41
|
+
*/
|
|
42
|
+
export declare function commitActiveSessionRef(channelDir: string, session: SessionFileHandle): Promise<void>;
|