@oyasmi/pipiclaw 0.9.0-beta.8 → 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.
Files changed (80) hide show
  1. package/dist/agent/channel-runner.d.ts +8 -0
  2. package/dist/agent/channel-runner.js +73 -10
  3. package/dist/agent/commands.d.ts +1 -1
  4. package/dist/agent/commands.js +9 -0
  5. package/dist/agent/index.d.ts +1 -1
  6. package/dist/agent/index.js +1 -1
  7. package/dist/agent/job-manager.d.ts +23 -3
  8. package/dist/agent/job-manager.js +14 -1
  9. package/dist/agent/runner-factory.d.ts +16 -4
  10. package/dist/agent/runner-factory.js +9 -23
  11. package/dist/agent/turn-recovery.d.ts +72 -0
  12. package/dist/agent/turn-recovery.js +193 -0
  13. package/dist/agent/types.d.ts +9 -1
  14. package/dist/agent/types.js +3 -16
  15. package/dist/playbooks/agent-delegation.md +3 -3
  16. package/dist/playbooks/runtime-orientation.md +5 -0
  17. package/dist/runtime/active-session-store.d.ts +42 -0
  18. package/dist/runtime/active-session-store.js +100 -0
  19. package/dist/runtime/bootstrap.d.ts +10 -2
  20. package/dist/runtime/bootstrap.js +122 -53
  21. package/dist/runtime/channel-event.d.ts +41 -0
  22. package/dist/runtime/channel-event.js +1 -0
  23. package/dist/runtime/delivery.d.ts +3 -2
  24. package/dist/runtime/dingtalk.d.ts +9 -31
  25. package/dist/runtime/dingtalk.js +2 -1
  26. package/dist/runtime/durable-dispatch.d.ts +3 -2
  27. package/dist/runtime/events.d.ts +3 -2
  28. package/dist/runtime/events.js +2 -3
  29. package/dist/runtime/project-commands.d.ts +16 -0
  30. package/dist/runtime/project-commands.js +112 -0
  31. package/dist/runtime/project-scope-store.d.ts +31 -0
  32. package/dist/runtime/project-scope-store.js +102 -0
  33. package/dist/runtime/task-commands.js +2 -2
  34. package/dist/runtime/task-driver.d.ts +7 -7
  35. package/dist/runtime/task-driver.js +1 -4
  36. package/dist/runtime/task-migration.js +1 -1
  37. package/dist/runtime/task-wake.d.ts +4 -4
  38. package/dist/security/config.js +10 -0
  39. package/dist/security/path-guard.js +34 -9
  40. package/dist/security/project-scope.d.ts +45 -0
  41. package/dist/security/project-scope.js +107 -0
  42. package/dist/security/types.d.ts +20 -2
  43. package/dist/settings.d.ts +0 -106
  44. package/dist/settings.js +0 -224
  45. package/dist/shared/types.d.ts +1 -0
  46. package/dist/shared/types.js +10 -1
  47. package/dist/subagents/external/run.js +2 -8
  48. package/dist/subagents/runs.d.ts +3 -3
  49. package/dist/subagents/runs.js +2 -12
  50. package/dist/subagents/tool.d.ts +13 -4
  51. package/dist/subagents/tool.js +9 -15
  52. package/dist/tasks/ledger.js +1 -1
  53. package/dist/{shared → tasks}/task-schedule.js +1 -1
  54. package/dist/tools/bash.js +4 -4
  55. package/dist/tools/edit.js +3 -3
  56. package/dist/tools/event-manage.js +1 -4
  57. package/dist/tools/grep.js +5 -6
  58. package/dist/tools/index.d.ts +3 -0
  59. package/dist/tools/index.js +7 -2
  60. package/dist/tools/job.js +5 -5
  61. package/dist/tools/memory-manage.js +3 -6
  62. package/dist/tools/read.js +3 -3
  63. package/dist/tools/registry.js +1 -1
  64. package/dist/tools/send-media.js +2 -2
  65. package/dist/tools/session-search.js +0 -1
  66. package/dist/tools/skill-manage.js +3 -3
  67. package/dist/tools/subagent-manage.js +3 -3
  68. package/dist/tools/task-manage/shared.js +2 -2
  69. package/dist/tools/task-manage.js +1 -4
  70. package/dist/tools/web-fetch.js +0 -1
  71. package/dist/tools/write-content.js +3 -3
  72. package/dist/tui/app.js +50 -4
  73. package/dist/tui/commands.d.ts +1 -0
  74. package/dist/tui/commands.js +2 -0
  75. package/dist/tui/turn-controller.d.ts +1 -0
  76. package/dist/tui/turn-controller.js +1 -0
  77. package/package.json +1 -1
  78. /package/dist/{shared → tasks}/task-events.d.ts +0 -0
  79. /package/dist/{shared → tasks}/task-events.js +0 -0
  80. /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
@@ -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;
@@ -92,6 +99,7 @@ export declare class ChannelRunner implements AgentRunner {
92
99
  isKnownSlashCommand(text: string): boolean;
93
100
  queueSteer(text: string, userName?: string): Promise<void>;
94
101
  flushMemoryForShutdown(): Promise<void>;
102
+ dispose(): Promise<void>;
95
103
  getMemoryMaintenanceContext(): Promise<MemoryMaintenanceRuntimeContext>;
96
104
  getStatusSnapshot(): RunnerStatusSnapshot;
97
105
  abort(): Promise<void>;
@@ -16,8 +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";
20
- import { PipiclawSettingsManager } from "../settings.js";
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";
@@ -40,6 +42,7 @@ import { loadWorkspacePromptResources } from "./prompt/resources.js";
40
42
  import { createRunQueue } from "./run-queue.js";
41
43
  import { handleSessionEvent } from "./session-events.js";
42
44
  import { SessionResourceGate } from "./session-resource-gate.js";
45
+ import { recoverInterruptedTurn } from "./turn-recovery.js";
43
46
  import { getLastAssistantUsage } from "./type-guards.js";
44
47
  import { createEmptyRunState, MAX_USER_MESSAGE_CHARS, } from "./types.js";
45
48
  import { loadPipiclawSkills, resolvePipiclawSkills } from "./workspace-resources.js";
@@ -108,13 +111,46 @@ export class ChannelRunner {
108
111
  const executor = createExecutor();
109
112
  this.executor = executor;
110
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;
111
127
  // Initial skill summaries
112
128
  const initialSkills = loadPipiclawSkills(channelDir);
113
129
  this.currentSkills = initialSkills;
114
- // Create session manager
115
- const contextFile = join(channelDir, "context.jsonl");
116
- this.sessionManager = SessionManager.open(contextFile, channelDir);
117
- this.settingsManager = new PipiclawSettingsManager(this.appHomeDir);
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;
118
154
  this.reportSettingsDiagnostics();
119
155
  this.memoryCandidateStore = createMemoryCandidateStore();
120
156
  this.memoryActivityRecorder = createMemoryActivityRecorder({
@@ -606,6 +642,26 @@ export class ChannelRunner {
606
642
  await this.flushMemoryActivity();
607
643
  await this.memoryLifecycle.flushForShutdown();
608
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
+ }
609
665
  async getMemoryMaintenanceContext() {
610
666
  await this.ensureSessionReady();
611
667
  this.settingsManager.reload();
@@ -861,12 +917,18 @@ export class ChannelRunner {
861
917
  agent: this.agent,
862
918
  sessionManager: this.sessionManager,
863
919
  settingsManager: asSdkSettingsManager(this.settingsManager),
864
- cwd: process.cwd(),
920
+ cwd: this.projectScope.projectRoot,
865
921
  modelRuntime: this.modelRuntime,
866
922
  resourceLoader: initialResourceLoader,
867
923
  baseToolsOverride,
868
924
  });
869
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);
870
932
  const next = this.createSessionRuntime(sessionManager, sessionStartEvent);
871
933
  return {
872
934
  session: next.session,
@@ -992,7 +1054,7 @@ export class ChannelRunner {
992
1054
  this.lastWorkspaceResources = resources;
993
1055
  const build = buildPipiclawSystemPrompt({
994
1056
  mode: "normal",
995
- cwd: process.cwd(),
1057
+ cwd: this.projectScope.projectRoot,
996
1058
  workspaceDir: this.workspaceDir,
997
1059
  tools: this.currentTools.map((tool) => ({
998
1060
  name: tool.name,
@@ -1026,7 +1088,7 @@ export class ChannelRunner {
1026
1088
  }
1027
1089
  createResourceLoader() {
1028
1090
  return new DefaultResourceLoader({
1029
- cwd: process.cwd(),
1091
+ cwd: this.projectScope.projectRoot,
1030
1092
  agentDir: this.appHomeDir,
1031
1093
  settingsManager: asSdkSettingsManager(this.settingsManager),
1032
1094
  extensionFactories: [
@@ -1081,7 +1143,7 @@ export class ChannelRunner {
1081
1143
  }
1082
1144
  createAgentSessionServices(resourceLoader) {
1083
1145
  return {
1084
- cwd: process.cwd(),
1146
+ cwd: this.projectScope.projectRoot,
1085
1147
  agentDir: this.appHomeDir,
1086
1148
  settingsManager: asSdkSettingsManager(this.settingsManager),
1087
1149
  modelRuntime: this.modelRuntime,
@@ -1133,7 +1195,7 @@ export class ChannelRunner {
1133
1195
  agent,
1134
1196
  sessionManager,
1135
1197
  settingsManager: asSdkSettingsManager(this.settingsManager),
1136
- cwd: process.cwd(),
1198
+ cwd: this.projectScope.projectRoot,
1137
1199
  modelRuntime: this.modelRuntime,
1138
1200
  resourceLoader,
1139
1201
  baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
@@ -1152,6 +1214,7 @@ export class ChannelRunner {
1152
1214
  getAvailableModels: () => this.modelRegistry.getAvailable(),
1153
1215
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
1154
1216
  workspaceDir: this.workspaceDir,
1217
+ projectScope: this.projectScope,
1155
1218
  channelDir: this.channelDir,
1156
1219
  channelId: this.channelId,
1157
1220
  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
@@ -1,2 +1,2 @@
1
- export { getOrCreateRunner } from "./runner-factory.js";
1
+ export { createRunner } from "./runner-factory.js";
2
2
  export type { AgentRunner } from "./types.js";
@@ -1 +1 @@
1
- export { getOrCreateRunner } from "./runner-factory.js";
1
+ export { createRunner } from "./runner-factory.js";
@@ -1,5 +1,5 @@
1
1
  import type { Executor } from "../executor.js";
2
- import type { DingTalkEvent } from "../runtime/dingtalk.js";
2
+ import type { ChannelEvent } from "../runtime/channel-event.js";
3
3
  /**
4
4
  * Per-channel manager for background bash jobs. A long command that ran synchronously would hold
5
5
  * the channel's run queue for its whole duration, blocking `/steer`, `/followup`, and every other
@@ -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;
@@ -44,7 +57,7 @@ export interface JobManagerOptions {
44
57
  /** Directory for this channel's persisted job records. Omit to run without persistence. */
45
58
  stateDir?: string;
46
59
  /** Delivers the completion wake. Omit to disable waking (sub-agent and test paths). */
47
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
60
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
48
61
  sweepIntervalMs?: number;
49
62
  }
50
63
  /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
@@ -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
  /**
@@ -166,7 +180,7 @@ export declare class ChannelJobManager {
166
180
  interface JobRuntimeConfig {
167
181
  /** Root of the per-channel record directories (`<jobsStateDir>/<channelId>/`). */
168
182
  jobsStateDir?: string;
169
- dispatch?: (event: DingTalkEvent) => boolean | Promise<boolean>;
183
+ dispatch?: (event: ChannelEvent) => boolean | Promise<boolean>;
170
184
  }
171
185
  /**
172
186
  * Give background jobs their persistence root and their way to wake a channel. Called once from
@@ -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();
@@ -356,7 +359,6 @@ export class ChannelJobManager {
356
359
  `Full output: ${record.spillFile}\n` +
357
360
  "Continue whatever was waiting on this job. If it needs no follow-up, respond with exactly [SILENT].",
358
361
  ts: String(Date.now()),
359
- conversationId: "",
360
362
  conversationType: this.channelId.startsWith("group_") ? "2" : "1",
361
363
  dispatchId: `job:${this.channelId}:${record.id}:done`,
362
364
  ...(record.contract.taskId
@@ -555,6 +557,17 @@ export function configureJobRuntime(config) {
555
557
  export function channelJobTaskIds(channelId) {
556
558
  return managers.get(channelId)?.runningTaskIds() ?? new Set();
557
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
+ }
558
571
  export function getChannelJobManager(channelId, executor) {
559
572
  let manager = managers.get(channelId);
560
573
  if (!manager) {
@@ -1,19 +1,31 @@
1
1
  import type { MediaSender } from "../runtime/channel-context.js";
2
+ import type { PipiclawSettingsManager } from "../settings.js";
2
3
  import type { AgentRunner } from "./types.js";
3
4
  export interface RunnerFactoryPaths {
4
5
  appHomeDir: string;
5
6
  authConfigPath: string;
6
7
  modelsConfigPath: string;
8
+ /**
9
+ * The single app-level settings manager (from `prepareAppServices`), shared across every
10
+ * channel's runner rather than each constructing its own. Keeps `drainErrors()`/diagnostics
11
+ * ordering and `reload()`'s file-stamp guard meaningful instead of racing N independent copies.
12
+ */
13
+ settingsManager: PipiclawSettingsManager;
7
14
  /** Optional, side-effect-free observer used by the behavior-eval harness. */
8
15
  onSessionEvent?: (event: unknown, channelId: string) => void;
9
16
  /**
10
17
  * Transport that can deliver file attachments (the DingTalk bot, or the terminal).
11
- * Present enables the `send_media` tool; absent, the tool is not built. Not part
12
- * of the runner cache key — it is a stable per-process transport handle.
18
+ * Present enables the `send_media` tool; absent, the tool is not built.
13
19
  */
14
20
  mediaSender?: MediaSender;
15
21
  /** Runtime callback that durably enqueues an independent task verifier. */
16
22
  dispatchVerification?: (taskId: string) => Promise<boolean>;
17
23
  }
18
- export declare function getOrCreateRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
19
- export declare function resetRunner(channelId: string, paths?: RunnerFactoryPaths, channelDir?: string): void;
24
+ /**
25
+ * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
26
+ * (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
27
+ * its own lifecycle (the daemon's runtime channel map with LRU eviction; the TUI's single local
28
+ * `const`, one channel per process) — a second cache here just duplicated that ownership and
29
+ * could hold a stale entry the real owner had already disposed.
30
+ */
31
+ export declare function createRunner(channelId: string, channelDir: string, paths: RunnerFactoryPaths): AgentRunner;
@@ -1,25 +1,11 @@
1
1
  import { ChannelRunner } from "./channel-runner.js";
2
- const channelRunners = new Map();
3
- function runnerKey(paths, channelId, channelDir) {
4
- return `${paths.appHomeDir}\0${channelDir}\0${channelId}`;
5
- }
6
- export function getOrCreateRunner(channelId, channelDir, paths) {
7
- const key = runnerKey(paths, channelId, channelDir);
8
- const existing = channelRunners.get(key);
9
- if (existing)
10
- return existing;
11
- const runner = new ChannelRunner(channelId, channelDir, paths);
12
- channelRunners.set(key, runner);
13
- return runner;
14
- }
15
- export function resetRunner(channelId, paths, channelDir) {
16
- if (paths && channelDir) {
17
- channelRunners.delete(runnerKey(paths, channelId, channelDir));
18
- return;
19
- }
20
- for (const key of channelRunners.keys()) {
21
- if (key.endsWith(`\0${channelId}`)) {
22
- channelRunners.delete(key);
23
- }
24
- }
2
+ /**
3
+ * Stateless: always constructs a fresh runner. The daemon (`runtime/bootstrap.ts`) and the TUI
4
+ * (`tui/app.ts`) are the only two callers, and each already owns exactly one cache appropriate to
5
+ * its own lifecycle (the daemon's runtime channel map with LRU eviction; the TUI's single local
6
+ * `const`, one channel per process) — a second cache here just duplicated that ownership and
7
+ * could hold a stale entry the real owner had already disposed.
8
+ */
9
+ export function createRunner(channelId, channelDir, paths) {
10
+ return new ChannelRunner(channelId, channelDir, paths);
25
11
  }
@@ -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
+ }