@oyasmi/pipiclaw 0.9.0-beta.9 → 0.9.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/agent/channel-runner.d.ts +12 -0
  2. package/dist/agent/channel-runner.js +88 -8
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +12 -1
  5. package/dist/agent/job-manager.d.ts +20 -0
  6. package/dist/agent/job-manager.js +14 -0
  7. package/dist/agent/turn-recovery.d.ts +72 -0
  8. package/dist/agent/turn-recovery.js +193 -0
  9. package/dist/agent/types.d.ts +6 -0
  10. package/dist/memory/lifecycle.d.ts +15 -0
  11. package/dist/memory/lifecycle.js +60 -0
  12. package/dist/playbooks/agent-delegation.md +3 -3
  13. package/dist/playbooks/runtime-orientation.md +5 -0
  14. package/dist/runtime/active-session-store.d.ts +54 -0
  15. package/dist/runtime/active-session-store.js +126 -0
  16. package/dist/runtime/bootstrap.js +122 -3
  17. package/dist/runtime/delivery.js +1 -1
  18. package/dist/runtime/dingtalk.d.ts +7 -0
  19. package/dist/runtime/dingtalk.js +24 -4
  20. package/dist/runtime/project-commands.d.ts +16 -0
  21. package/dist/runtime/project-commands.js +112 -0
  22. package/dist/runtime/project-scope-store.d.ts +31 -0
  23. package/dist/runtime/project-scope-store.js +102 -0
  24. package/dist/security/config.js +10 -0
  25. package/dist/security/path-guard.js +34 -9
  26. package/dist/security/project-scope.d.ts +45 -0
  27. package/dist/security/project-scope.js +107 -0
  28. package/dist/security/types.d.ts +20 -2
  29. package/dist/subagents/tool.d.ts +2 -0
  30. package/dist/subagents/tool.js +8 -2
  31. package/dist/tools/bash.js +3 -3
  32. package/dist/tools/edit.js +3 -3
  33. package/dist/tools/grep.js +3 -3
  34. package/dist/tools/index.d.ts +3 -0
  35. package/dist/tools/index.js +7 -2
  36. package/dist/tools/read.js +3 -3
  37. package/dist/tools/registry.js +1 -1
  38. package/dist/tools/send-media.js +2 -2
  39. package/dist/tools/write-content.js +3 -3
  40. package/dist/tui/app.js +47 -1
  41. package/dist/tui/commands.d.ts +1 -0
  42. package/dist/tui/commands.js +2 -0
  43. package/dist/tui/turn-controller.d.ts +1 -0
  44. package/dist/tui/turn-controller.js +1 -0
  45. 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;
@@ -53,6 +60,8 @@ export declare class ChannelRunner implements AgentRunner {
53
60
  * whichever turn started in the meantime.
54
61
  */
55
62
  private abandonedTurns;
63
+ /** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
64
+ private retired;
56
65
  /** When the primary model last failed and we switched to the backup. null = on primary. */
57
66
  private primaryFailedAt;
58
67
  private runState;
@@ -96,6 +105,9 @@ export declare class ChannelRunner implements AgentRunner {
96
105
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
97
106
  getStatusSnapshot(): RunnerStatusSnapshot;
98
107
  abort(): Promise<void>;
108
+ isCompacting(): boolean;
109
+ interruptCompaction(): boolean;
110
+ retireForNewSession(): void;
99
111
  /**
100
112
  * `/context` — read-only prompt accounting, no LLM cost. Reports the section
101
113
  * breakdown of the system prompt, the tool schemas (billed on top of it, and
@@ -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";
@@ -92,6 +96,8 @@ export class ChannelRunner {
92
96
  * whichever turn started in the meantime.
93
97
  */
94
98
  this.abandonedTurns = 0;
99
+ /** Set once transport-level `/new` replaces this generation. A retired runner is never reused. */
100
+ this.retired = false;
95
101
  /** When the primary model last failed and we switched to the backup. null = on primary. */
96
102
  this.primaryFailedAt = null;
97
103
  // --- Per run ---
@@ -107,12 +113,45 @@ export class ChannelRunner {
107
113
  const executor = createExecutor();
108
114
  this.executor = executor;
109
115
  this.workspaceDir = resolve(dirname(channelDir));
116
+ // Resolve and freeze this generation's ProjectScope (spec 043, D2/D3/D4.2). A channel with
117
+ // no persisted selection gets the app default, materialized as its first selection right
118
+ // here. A selection that no longer resolves safely (deleted directory, re-pointed symlink,
119
+ // or a since-tightened allowlist) fails the whole runner closed rather than silently
120
+ // falling back to a different root (P7) — the fix is `/project set`/`reset` from a plain
121
+ // runtime command path, not a degraded-but-running channel; see project-scope-store.ts.
122
+ const securityConfigForScope = loadSecurityConfigWithDiagnostics(this.appHomeDir);
123
+ const projectAccessResolution = resolveProjectAccessPolicy(securityConfigForScope.config, process.cwd());
124
+ const scopeOutcome = resolveProjectScope(channelDir, projectAccessResolution);
125
+ if (scopeOutcome.kind === "blocked") {
126
+ throw new Error(`[${channelId}] Cannot start channel: ${scopeOutcome.reason}`);
127
+ }
128
+ this.projectScope = scopeOutcome.scope;
110
129
  // Initial skill summaries
111
130
  const initialSkills = loadPipiclawSkills(channelDir);
112
131
  this.currentSkills = initialSkills;
113
- // Create session manager
114
- const contextFile = join(channelDir, "context.jsonl");
115
- this.sessionManager = SessionManager.open(contextFile, channelDir);
132
+ // Create session manager, opening whichever session this channel's active-session ref
133
+ // (or the context.jsonl default, for a channel that has never run a topology op) names
134
+ // (spec 043, D1).
135
+ const activeSessionFile = resolveActiveSessionFile(channelDir);
136
+ this.sessionManager = SessionManager.open(join(channelDir, activeSessionFile), channelDir);
137
+ // Per-runner recovery barrier (spec 043, D10 point 2): repairs must run against this exact
138
+ // SessionManager instance, before anything else touches it — a second `open()` of the same
139
+ // file would mutate a branch this instance never sees, silently desyncing the two. The
140
+ // daemon's own startup scan (bootstrap.ts) covers channels with no live runner yet; this
141
+ // covers lazy channels, the TUI, and a channel whose file was fixed by hand after the scan
142
+ // already ran and reported it blocked.
143
+ const recoveryOutcome = recoverInterruptedTurn(this.sessionManager, {
144
+ api: defaultModel.api,
145
+ provider: defaultModel.provider,
146
+ model: defaultModel.id,
147
+ });
148
+ if (recoveryOutcome.kind === "blocked") {
149
+ throw new Error(`[${channelId}] Cannot start channel: session left in an unrecoverable state after a restart (${recoveryOutcome.reason}). ` +
150
+ `Back up ${join(channelDir, activeSessionFile)} on the host, move it aside, then use /new to start a fresh session.`);
151
+ }
152
+ if (recoveryOutcome.kind === "repaired") {
153
+ log.logWarning(`[${channelId}] Repaired an interrupted turn on restart`, `toolResults=${recoveryOutcome.appendedToolResults} abortedAssistant=${recoveryOutcome.appendedAbortedAssistant}`);
154
+ }
116
155
  this.settingsManager = paths.settingsManager;
117
156
  this.reportSettingsDiagnostics();
118
157
  this.memoryCandidateStore = createMemoryCandidateStore();
@@ -663,6 +702,40 @@ export class ChannelRunner {
663
702
  async abort() {
664
703
  await this.session.abort();
665
704
  }
705
+ isCompacting() {
706
+ return this.session?.isCompacting ?? false;
707
+ }
708
+ interruptCompaction() {
709
+ if (!this.session?.isCompacting)
710
+ return false;
711
+ this.session.abortCompaction();
712
+ return true;
713
+ }
714
+ retireForNewSession() {
715
+ if (this.retired)
716
+ return;
717
+ this.retired = true;
718
+ if (this.session) {
719
+ this.memoryLifecycle.noteNewSessionBoundary();
720
+ }
721
+ // close() marks the delivery context closed synchronously before awaiting its drain,
722
+ // so late events from the old provider cannot overwrite the new session's response.
723
+ void this.runState.ctx?.close().catch(() => undefined);
724
+ this.forceEndTurn("superseded by /new");
725
+ const retireLiveSession = () => {
726
+ this.sessionUnsubscribe?.();
727
+ this.sessionUnsubscribe = undefined;
728
+ this.session.dispose();
729
+ };
730
+ if (this.session) {
731
+ retireLiveSession();
732
+ }
733
+ else {
734
+ // A second message can issue `/new` while this generation is still initializing.
735
+ // Let construction settle in the background, then immediately tear it down.
736
+ void this.sessionReady.then(retireLiveSession, () => undefined);
737
+ }
738
+ }
666
739
  /**
667
740
  * `/context` — read-only prompt accounting, no LLM cost. Reports the section
668
741
  * breakdown of the system prompt, the tool schemas (billed on top of it, and
@@ -880,12 +953,18 @@ export class ChannelRunner {
880
953
  agent: this.agent,
881
954
  sessionManager: this.sessionManager,
882
955
  settingsManager: asSdkSettingsManager(this.settingsManager),
883
- cwd: process.cwd(),
956
+ cwd: this.projectScope.projectRoot,
884
957
  modelRuntime: this.modelRuntime,
885
958
  resourceLoader: initialResourceLoader,
886
959
  baseToolsOverride,
887
960
  });
888
961
  this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initialResourceLoader), async ({ sessionManager, sessionStartEvent }) => {
962
+ // `/new`, fork, and switch already wrote the target session's durable header by
963
+ // this point (the SDK does it synchronously before invoking this callback); commit
964
+ // the pointer before we rebuild and rebind to it, so a crash between "SDK created
965
+ // session" and "we finished rebinding" leaves the old ref (and old session)
966
+ // authoritative rather than an orphaned new file (spec 043, D1.3).
967
+ await commitActiveSessionRef(this.channelDir, sessionManager);
889
968
  const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
890
969
  return {
891
970
  session: next.session,
@@ -1011,7 +1090,7 @@ export class ChannelRunner {
1011
1090
  this.lastWorkspaceResources = resources;
1012
1091
  const build = buildPipiclawSystemPrompt({
1013
1092
  mode: "normal",
1014
- cwd: process.cwd(),
1093
+ cwd: this.projectScope.projectRoot,
1015
1094
  workspaceDir: this.workspaceDir,
1016
1095
  tools: this.currentTools.map((tool) => ({
1017
1096
  name: tool.name,
@@ -1045,7 +1124,7 @@ export class ChannelRunner {
1045
1124
  }
1046
1125
  createResourceLoader() {
1047
1126
  return new DefaultResourceLoader({
1048
- cwd: process.cwd(),
1127
+ cwd: this.projectScope.projectRoot,
1049
1128
  agentDir: this.appHomeDir,
1050
1129
  settingsManager: asSdkSettingsManager(this.settingsManager),
1051
1130
  extensionFactories: [
@@ -1100,7 +1179,7 @@ export class ChannelRunner {
1100
1179
  }
1101
1180
  createAgentSessionServices(resourceLoader) {
1102
1181
  return {
1103
- cwd: process.cwd(),
1182
+ cwd: this.projectScope.projectRoot,
1104
1183
  agentDir: this.appHomeDir,
1105
1184
  settingsManager: asSdkSettingsManager(this.settingsManager),
1106
1185
  modelRuntime: this.modelRuntime,
@@ -1152,7 +1231,7 @@ export class ChannelRunner {
1152
1231
  agent,
1153
1232
  sessionManager,
1154
1233
  settingsManager: asSdkSettingsManager(this.settingsManager),
1155
- cwd: process.cwd(),
1234
+ cwd: this.projectScope.projectRoot,
1156
1235
  modelRuntime: this.modelRuntime,
1157
1236
  resourceLoader,
1158
1237
  baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
@@ -1171,6 +1250,7 @@ export class ChannelRunner {
1171
1250
  getAvailableModels: () => this.modelRegistry.getAvailable(),
1172
1251
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
1173
1252
  workspaceDir: this.workspaceDir,
1253
+ projectScope: this.projectScope,
1174
1254
  channelDir: this.channelDir,
1175
1255
  channelId: this.channelId,
1176
1256
  getSubAgentDiscovery: () => this.subAgentDiscovery,
@@ -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
  /**
@@ -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
@@ -132,6 +141,7 @@ export const SESSION_COMMANDS = [
132
141
  name: "new",
133
142
  description: "开启新会话",
134
143
  examples: ["/new"],
144
+ availableWhileBusy: true,
135
145
  },
136
146
  {
137
147
  name: "compact",
@@ -160,7 +170,8 @@ export function isRunnerBuiltInCommand(command) {
160
170
  }
161
171
  /** Comma-separated list of commands usable while a task is streaming (names only). */
162
172
  export function formatBusyCommandList() {
163
- return BUILT_IN_COMMANDS.filter((command) => command.availableWhileBusy)
173
+ return [...BUILT_IN_COMMANDS, ...SESSION_COMMANDS]
174
+ .filter((command) => command.availableWhileBusy)
164
175
  .map((command) => `\`/${command.name}\``)
165
176
  .join(", ");
166
177
  }
@@ -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
+ }
@@ -56,6 +56,12 @@ export interface AgentRunner {
56
56
  * already discovered, without forcing a rescan. */
57
57
  getSubAgentDiscoverySnapshot(): SubAgentDiscoveryResult;
58
58
  abort(): Promise<void>;
59
+ /** True when the SDK is currently summarizing context. */
60
+ isCompacting?(): boolean;
61
+ /** Cancel context summarization synchronously; returns whether one was active. */
62
+ interruptCompaction?(): boolean;
63
+ /** Permanently retire this runner generation after an out-of-band `/new`. */
64
+ retireForNewSession?(): void;
59
65
  /**
60
66
  * Synchronously reserve the turn for a message. Transports MUST call this in
61
67
  * the same tick they dequeue the message, before any await, so a concurrent
@@ -5,6 +5,19 @@ import type { PipiclawSessionMemorySettings } from "../settings.js";
5
5
  import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
6
6
  import { type MemoryActivityEvent } from "./maintenance-state.js";
7
7
  export type ConsolidationReason = "compaction" | "new-session" | "idle" | "shutdown";
8
+ /**
9
+ * Bound one standalone summarization request. Provider limits can be lower than a model's
10
+ * advertised context window; sending the whole pre-compaction transcript is therefore not safe.
11
+ * The head preserves the original goal and the larger tail preserves current work. Durable
12
+ * memory is refreshed before this runs, so the omitted middle is still available outside the
13
+ * provider request.
14
+ */
15
+ export declare function boundCompactionMessages(messages: AgentMessage[], contextWindow: number, reserveTokens: number): {
16
+ messages: AgentMessage[];
17
+ truncated: boolean;
18
+ originalChars: number;
19
+ boundedChars: number;
20
+ };
8
21
  export interface MemoryLifecycleOptions {
9
22
  channelId: string;
10
23
  channelDir: string;
@@ -46,6 +59,8 @@ export declare class MemoryLifecycle {
46
59
  private handleSessionBeforeCompact;
47
60
  private handleSessionCompact;
48
61
  private handleSessionBeforeSwitch;
62
+ /** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
63
+ noteNewSessionBoundary(): void;
49
64
  /** Await any in-flight detached new-session consolidation (shutdown/tests). */
50
65
  whenNewSessionConsolidationSettled(): Promise<void>;
51
66
  private handleSessionStart;