pi-fabric 0.130.2 → 0.131.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 (225) hide show
  1. package/dist/activity/store.d.ts +2 -1
  2. package/dist/activity/store.d.ts.map +1 -1
  3. package/dist/actors/directory.d.ts.map +1 -1
  4. package/dist/actors/global-registry.d.ts.map +1 -1
  5. package/dist/actors/manager.d.ts +4 -3
  6. package/dist/actors/manager.d.ts.map +1 -1
  7. package/dist/actors/mesh-monitor.d.ts +2 -0
  8. package/dist/actors/mesh-monitor.d.ts.map +1 -1
  9. package/dist/actors/name-policy.d.ts +3 -0
  10. package/dist/actors/name-policy.d.ts.map +1 -0
  11. package/dist/actors/registry-store.d.ts +1 -1
  12. package/dist/actors/registry-store.d.ts.map +1 -1
  13. package/dist/agents/agent-files.d.ts +8 -0
  14. package/dist/agents/agent-files.d.ts.map +1 -1
  15. package/dist/agents/agent-files.js +48 -3
  16. package/dist/agents/agent-files.js.map +2 -2
  17. package/dist/agents/child-skills.d.ts +60 -0
  18. package/dist/agents/child-skills.d.ts.map +1 -0
  19. package/dist/agents/child-skills.js +94 -0
  20. package/dist/agents/child-skills.js.map +7 -0
  21. package/dist/agents/clone-first-worktree.d.ts +6 -0
  22. package/dist/agents/clone-first-worktree.d.ts.map +1 -1
  23. package/dist/agents/cow-clone.d.ts.map +1 -1
  24. package/dist/agents/handoff.d.ts +12 -2
  25. package/dist/agents/handoff.d.ts.map +1 -1
  26. package/dist/agents/manager.d.ts +4 -1
  27. package/dist/agents/manager.d.ts.map +1 -1
  28. package/dist/agents/model-pin-guard.d.ts +27 -0
  29. package/dist/agents/model-pin-guard.d.ts.map +1 -0
  30. package/dist/agents/model-pin-guard.js +86 -0
  31. package/dist/agents/model-pin-guard.js.map +7 -0
  32. package/dist/agents/model-pin.d.ts +25 -0
  33. package/dist/agents/model-pin.d.ts.map +1 -0
  34. package/dist/agents/provider-bridge.d.ts +5 -4
  35. package/dist/agents/provider-bridge.d.ts.map +1 -1
  36. package/dist/agents/provider-bridge.js +32 -4
  37. package/dist/agents/provider-bridge.js.map +3 -3
  38. package/dist/agents/request.d.ts.map +1 -1
  39. package/dist/agents/service-schema.d.ts.map +1 -1
  40. package/dist/agents/types.d.ts +25 -0
  41. package/dist/agents/types.d.ts.map +1 -1
  42. package/dist/agents/worktree-manager.d.ts.map +1 -1
  43. package/dist/agents.js +6 -5
  44. package/dist/agents.js.map +2 -2
  45. package/dist/audit/details.d.ts +4 -0
  46. package/dist/audit/details.d.ts.map +1 -1
  47. package/dist/chunks/{chunk-SBAROA4Y.js → chunk-2RWNVCFD.js} +17 -1
  48. package/dist/chunks/{chunk-SBAROA4Y.js.map → chunk-2RWNVCFD.js.map} +2 -2
  49. package/dist/chunks/{chunk-6O6UWMBO.js → chunk-36XQFTEN.js} +2 -2
  50. package/dist/chunks/chunk-3PKZSIRA.js +1312 -0
  51. package/dist/chunks/chunk-3PKZSIRA.js.map +7 -0
  52. package/dist/chunks/{chunk-JJXUOXI5.js → chunk-4KX6BIPL.js} +17 -2
  53. package/dist/chunks/chunk-4KX6BIPL.js.map +7 -0
  54. package/dist/chunks/{chunk-EYHTTMSM.js → chunk-4PBW54I2.js} +5 -5
  55. package/dist/chunks/{chunk-WTIF3MIM.js → chunk-56NMRVTV.js} +8 -8
  56. package/dist/chunks/{chunk-WQFG7ZVC.js → chunk-5BOTHX47.js} +48 -13
  57. package/dist/chunks/chunk-5BOTHX47.js.map +7 -0
  58. package/dist/chunks/chunk-5QJFDKPN.js +179 -0
  59. package/dist/chunks/chunk-5QJFDKPN.js.map +7 -0
  60. package/dist/chunks/chunk-6HO2IUQ5.js +104 -0
  61. package/dist/chunks/chunk-6HO2IUQ5.js.map +7 -0
  62. package/dist/chunks/{chunk-NF6W327N.js → chunk-7CIES6X2.js} +9 -2
  63. package/dist/chunks/chunk-7CIES6X2.js.map +7 -0
  64. package/dist/chunks/{chunk-KDX3762L.js → chunk-DGERP4VL.js} +4 -4
  65. package/dist/chunks/{chunk-K3ZWBUUL.js → chunk-IOGDTIGN.js} +13 -13
  66. package/dist/chunks/chunk-IOGDTIGN.js.map +7 -0
  67. package/dist/chunks/{chunk-UXIBKMUM.js → chunk-KIFOEBYJ.js} +4 -4
  68. package/dist/chunks/{chunk-D5224P2R.js → chunk-LKYLD5SN.js} +7 -7
  69. package/dist/chunks/chunk-NENQZCGW.js +45 -0
  70. package/dist/chunks/chunk-NENQZCGW.js.map +7 -0
  71. package/dist/chunks/{chunk-YTYLKL3Z.js → chunk-OJ4HAALD.js} +8 -8
  72. package/dist/chunks/{chunk-TBB7F7WS.js → chunk-PQVUMJ5J.js} +84 -18
  73. package/dist/chunks/chunk-PQVUMJ5J.js.map +7 -0
  74. package/dist/chunks/chunk-UD7LFV43.js +28 -0
  75. package/dist/chunks/chunk-UD7LFV43.js.map +7 -0
  76. package/dist/chunks/{chunk-CH2QMORW.js → chunk-UFMYN5TA.js} +2 -2
  77. package/dist/chunks/chunk-V4OW2ULC.js +422 -0
  78. package/dist/chunks/chunk-V4OW2ULC.js.map +7 -0
  79. package/dist/chunks/{chunk-6C2DMTQC.js → chunk-VNWQIGQL.js} +552 -145
  80. package/dist/chunks/chunk-VNWQIGQL.js.map +7 -0
  81. package/dist/chunks/{chunk-OA5SJT2T.js → chunk-W3N72XYK.js} +199 -93
  82. package/dist/chunks/chunk-W3N72XYK.js.map +7 -0
  83. package/dist/chunks/{chunk-HAHRJMWY.js → chunk-WWTGWGH7.js} +6 -6
  84. package/dist/chunks/{chunk-F4HL6KJR.js → chunk-X7QETPBC.js} +7 -7
  85. package/dist/chunks/{chunk-SSRSCT2M.js → chunk-XFOSUGLU.js} +4 -4
  86. package/dist/chunks/{chunk-4VGB6HMU.js → chunk-ZFWICFNJ.js} +23 -18
  87. package/dist/chunks/{chunk-4VGB6HMU.js.map → chunk-ZFWICFNJ.js.map} +2 -2
  88. package/dist/commands/fabric-handler.d.ts.map +1 -1
  89. package/dist/commands/fabric-handler.js +43 -7
  90. package/dist/commands/fabric-handler.js.map +2 -2
  91. package/dist/compaction/claim-events.js +2 -2
  92. package/dist/components/configuration.js +3 -3
  93. package/dist/config.d.ts +9 -1
  94. package/dist/config.d.ts.map +1 -1
  95. package/dist/core/action-registry.js +4 -4
  96. package/dist/core/model-aliases.d.ts +22 -0
  97. package/dist/core/model-aliases.d.ts.map +1 -0
  98. package/dist/core/model-resolution.d.ts +41 -20
  99. package/dist/core/model-resolution.d.ts.map +1 -1
  100. package/dist/core/prompt-guidance.js +9 -4
  101. package/dist/core/prompt-guidance.js.map +2 -2
  102. package/dist/core/system-guidance.d.ts.map +1 -1
  103. package/dist/decisions/command.d.ts +2 -1
  104. package/dist/decisions/command.d.ts.map +1 -1
  105. package/dist/decisions/command.js +31 -11
  106. package/dist/decisions/command.js.map +2 -2
  107. package/dist/decisions/events.js +2 -1
  108. package/dist/decisions/events.js.map +1 -1
  109. package/dist/decisions/host.d.ts +8 -0
  110. package/dist/decisions/host.d.ts.map +1 -1
  111. package/dist/decisions/render.d.ts +44 -0
  112. package/dist/decisions/render.d.ts.map +1 -0
  113. package/dist/durable/agent.d.ts +6 -0
  114. package/dist/durable/agent.d.ts.map +1 -1
  115. package/dist/durable/worker-host.d.ts.map +1 -1
  116. package/dist/durable/worker-host.js +7 -1283
  117. package/dist/durable/worker-host.js.map +4 -4
  118. package/dist/durable/worker-options.d.ts +2 -0
  119. package/dist/durable/worker-options.d.ts.map +1 -1
  120. package/dist/durable/worker-role-seed.d.ts +82 -0
  121. package/dist/durable/worker-role-seed.d.ts.map +1 -0
  122. package/dist/durable/worker.js +10 -1
  123. package/dist/durable/worker.js.map +2 -2
  124. package/dist/durable-extension.d.ts +1 -1
  125. package/dist/durable-extension.js +1 -1
  126. package/dist/durable-extension.js.map +1 -1
  127. package/dist/durable-host.d.ts +8 -0
  128. package/dist/durable-host.d.ts.map +1 -0
  129. package/dist/durable-host.js +20 -0
  130. package/dist/durable-host.js.map +7 -0
  131. package/dist/entropy/index.js +1 -1
  132. package/dist/execution-service.d.ts.map +1 -1
  133. package/dist/extension-bootstrap.d.ts.map +1 -1
  134. package/dist/extension-bootstrap.js +16 -16
  135. package/dist/extension.d.ts.map +1 -1
  136. package/dist/fabric-exec-tool.d.ts.map +1 -1
  137. package/dist/fabric-runtime-state.d.ts +2 -0
  138. package/dist/fabric-runtime-state.d.ts.map +1 -1
  139. package/dist/fabric-runtime-state.js +203 -124
  140. package/dist/fabric-runtime-state.js.map +2 -2
  141. package/dist/fabric-state.d.ts +26 -1
  142. package/dist/fabric-state.d.ts.map +1 -1
  143. package/dist/index.js +20 -16
  144. package/dist/index.js.map +1 -1
  145. package/dist/jev/client.js +2 -2
  146. package/dist/jev/observation.js +3 -3
  147. package/dist/jev.js +7 -7
  148. package/dist/protocol.d.ts +84 -0
  149. package/dist/protocol.d.ts.map +1 -1
  150. package/dist/protocol.js +5 -1
  151. package/dist/providers/agents-actions.d.ts.map +1 -1
  152. package/dist/providers/agents-provider.d.ts +3 -0
  153. package/dist/providers/agents-provider.d.ts.map +1 -1
  154. package/dist/providers/jev-provider.js +7 -7
  155. package/dist/residency/host.d.ts.map +1 -1
  156. package/dist/residency/host.js +13 -10
  157. package/dist/residency/pi-entry.js +13 -10
  158. package/dist/residency/pi-entry.js.map +1 -1
  159. package/dist/runtime/core-override-guest-types.js +2 -2
  160. package/dist/runtime/cpython-runtime.js +3 -3
  161. package/dist/runtime/exec-journal.js +3 -3
  162. package/dist/runtime/guest-types.d.ts +1 -1
  163. package/dist/runtime/guest-types.d.ts.map +1 -1
  164. package/dist/runtime/guest-types.js +1 -1
  165. package/dist/runtime/monty-runtime.js +6 -6
  166. package/dist/runtime/node-process-runtime.js +5 -5
  167. package/dist/runtime/quickjs-runtime.js +3 -3
  168. package/dist/runtime/typescript-kernel.js +11 -11
  169. package/dist/storage/retention.d.ts.map +1 -1
  170. package/dist/type-error-guidance.js +1 -1
  171. package/dist/ui/conversation-chrome.js +2 -2
  172. package/dist/ui/conversation.js +10 -10
  173. package/dist/ui/dashboard.d.ts.map +1 -1
  174. package/dist/ui/dashboard.js +14 -12
  175. package/dist/ui/dashboard.js.map +2 -2
  176. package/dist/ui/settings-sections-presentation.d.ts.map +1 -1
  177. package/dist/ui/settings.js +12 -9
  178. package/dist/ui/settings.js.map +2 -2
  179. package/dist/ui/widget.d.ts.map +1 -1
  180. package/dist/verified/generated/actor-name.d.ts +4 -0
  181. package/dist/verified/generated/actor-name.js +17 -0
  182. package/dist/verified/generated/manifest.json +11 -3
  183. package/dist/worker/options.d.ts.map +1 -1
  184. package/dist/worker/options.js +20 -0
  185. package/dist/worker/options.js.map +2 -2
  186. package/dist/worker.js +57 -8
  187. package/dist/worker.js.map +2 -2
  188. package/docs/actor-name-policy-handoff.md +5 -0
  189. package/docs/agents.md +64 -5
  190. package/docs/audit-trace.md +2 -1
  191. package/docs/components.md +1 -1
  192. package/docs/configuration.md +7 -4
  193. package/docs/decisions.md +47 -2
  194. package/docs/durable-pi.md +162 -2
  195. package/docs/interface.md +1 -1
  196. package/docs/providers.md +1 -1
  197. package/docs/verified-kernels.md +1 -0
  198. package/package.json +5 -1
  199. package/proofs/actor-name.ts +27 -0
  200. package/proofs/index.ts +2 -0
  201. package/scripts/verified-kernels.ts +1 -1
  202. package/skillsets/python/fabric-exec/references/agents.md +6 -4
  203. package/skillsets/typescript/fabric-exec/references/agents.md +6 -3
  204. package/dist/chunks/chunk-6C2DMTQC.js.map +0 -7
  205. package/dist/chunks/chunk-JJXUOXI5.js.map +0 -7
  206. package/dist/chunks/chunk-K3ZWBUUL.js.map +0 -7
  207. package/dist/chunks/chunk-KJZAOENY.js +0 -212
  208. package/dist/chunks/chunk-KJZAOENY.js.map +0 -7
  209. package/dist/chunks/chunk-NF6W327N.js.map +0 -7
  210. package/dist/chunks/chunk-OA5SJT2T.js.map +0 -7
  211. package/dist/chunks/chunk-TBB7F7WS.js.map +0 -7
  212. package/dist/chunks/chunk-WQFG7ZVC.js.map +0 -7
  213. package/dist/chunks/chunk-ZLNJDTCN.js +0 -226
  214. package/dist/chunks/chunk-ZLNJDTCN.js.map +0 -7
  215. /package/dist/chunks/{chunk-6O6UWMBO.js.map → chunk-36XQFTEN.js.map} +0 -0
  216. /package/dist/chunks/{chunk-EYHTTMSM.js.map → chunk-4PBW54I2.js.map} +0 -0
  217. /package/dist/chunks/{chunk-WTIF3MIM.js.map → chunk-56NMRVTV.js.map} +0 -0
  218. /package/dist/chunks/{chunk-KDX3762L.js.map → chunk-DGERP4VL.js.map} +0 -0
  219. /package/dist/chunks/{chunk-UXIBKMUM.js.map → chunk-KIFOEBYJ.js.map} +0 -0
  220. /package/dist/chunks/{chunk-D5224P2R.js.map → chunk-LKYLD5SN.js.map} +0 -0
  221. /package/dist/chunks/{chunk-YTYLKL3Z.js.map → chunk-OJ4HAALD.js.map} +0 -0
  222. /package/dist/chunks/{chunk-CH2QMORW.js.map → chunk-UFMYN5TA.js.map} +0 -0
  223. /package/dist/chunks/{chunk-HAHRJMWY.js.map → chunk-WWTGWGH7.js.map} +0 -0
  224. /package/dist/chunks/{chunk-F4HL6KJR.js.map → chunk-X7QETPBC.js.map} +0 -0
  225. /package/dist/chunks/{chunk-SSRSCT2M.js.map → chunk-XFOSUGLU.js.map} +0 -0
@@ -0,0 +1,1312 @@
1
+ import {
2
+ nativeFabricExecExclusions,
3
+ resolveNativeToolSelection
4
+ } from "./chunk-6OGYPHNQ.js";
5
+
6
+ // src/durable/worker-host.ts
7
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
8
+ import { lstat as lstat2, readdir as readdir2, unlink as unlink2 } from "node:fs/promises";
9
+ import path2 from "node:path";
10
+ import { BACKGROUND_CONTEXT as BACKGROUND_CONTEXT2 } from "@earendil-works/chord/context";
11
+ import {
12
+ AgentSessionRuntime,
13
+ createAgentSessionServices,
14
+ createCodemodeExtension,
15
+ createMcpExtension,
16
+ createToolSearchExtension,
17
+ ExtensionRunner,
18
+ getAgentDir as getAgentDir2,
19
+ hasTrustRequiringProjectResources,
20
+ ProjectTrustStore,
21
+ resolveCliModel,
22
+ runRpcMode,
23
+ SessionManager as SessionManager2,
24
+ SettingsManager as SettingsManager2
25
+ } from "@earendil-works/pi-coding-agent";
26
+
27
+ // src/durable/extension-load-error.ts
28
+ var TYPEBOX_ALIAS_FAILURE = /Cannot find module '[^']*[\\/]typebox[\\/][^']*\.[cm]?js[\\/][^']+'/;
29
+ function durableExtensionLoadError(errors) {
30
+ const message = `Durable worker extension loading failed: ${JSON.stringify(errors)}`;
31
+ if (!errors.some((failure) => TYPEBOX_ALIAS_FAILURE.test(failure.error))) return new Error(message);
32
+ return new Error(`${message}
33
+ An extension imported a typebox subpath that the durable worker cannot resolve, because the worker SDK aliases "typebox" to a single file; import from the "typebox" root instead, or use runner "pi".`);
34
+ }
35
+
36
+ // src/durable/session.ts
37
+ import { homedir } from "node:os";
38
+ import { join, resolve } from "node:path";
39
+ import { clampThinkingLevel } from "@earendil-works/pi-ai/compat";
40
+ import {
41
+ AgentSession,
42
+ convertToLlm,
43
+ DefaultResourceLoader,
44
+ getAgentDir,
45
+ ModelRuntime,
46
+ SessionManager,
47
+ SettingsManager
48
+ } from "@earendil-works/pi-coding-agent";
49
+
50
+ // src/durable/agent.ts
51
+ import { createHash, randomUUID } from "node:crypto";
52
+ import { unlink } from "node:fs/promises";
53
+ import path from "node:path";
54
+ import { AsyncLocalStorage } from "node:async_hooks";
55
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
56
+ import { Agent, runToolCall } from "@earendil-works/pi-agent-core";
57
+ import { getCurrentSystemMessage, getCurrentTools, getToolStateChanges, toToolDeclaration, normalizeContext } from "@earendil-works/pi-ai";
58
+ import { Harness, createRegistry, defineDoc, defineTask } from "@earendil-works/pi-durable";
59
+ var EVENT = "fabric.agent.event.v1";
60
+ var HISTORY = "fabric.agent.history.v1";
61
+ var copy = (value) => JSON.parse(JSON.stringify(value));
62
+ var wire = (value) => copy(value);
63
+ var TRANSIENT = "fabricTransient";
64
+ var Ledger = defineDoc({
65
+ kind: "fabric.agent.ledger",
66
+ version: 1,
67
+ scope: "conversation",
68
+ history: "latest",
69
+ fork: "initial",
70
+ initial: () => ({ runId: "", requests: {}, active: 0, steering: [], followup: [] }),
71
+ checkpointWhen: () => true
72
+ });
73
+ var MAX_JOURNAL_RESUMES = 3;
74
+ var fabricJournalPath = (directory, taskId, callId) => path.join(directory, `${createHash("sha256").update(`${taskId}\0${callId}`).digest("hex").slice(0, 32)}.jsonl`);
75
+ async function removeFabricJournal(file) {
76
+ await unlink(file).catch(() => void 0);
77
+ }
78
+ var toolFences = () => {
79
+ const holder = globalThis;
80
+ return holder[Symbol.for("pi-fabric.durable-tool-fence.v1")] ??= new AsyncLocalStorage();
81
+ };
82
+ var DurableAgent = class extends Agent {
83
+ durableOptions;
84
+ observers = /* @__PURE__ */ new Set();
85
+ registry = createRegistry();
86
+ engine;
87
+ root;
88
+ opening;
89
+ releaseStartup;
90
+ startup = new Promise((resolve3) => {
91
+ this.releaseStartup = resolve3;
92
+ });
93
+ /** Reconcile committed history without replaying events, before any recovered task runs. */
94
+ recoverHistory;
95
+ delivery = Promise.resolve();
96
+ admission = Promise.resolve();
97
+ running;
98
+ controller;
99
+ requestId;
100
+ firstRequest = true;
101
+ closing = false;
102
+ closeRequested = false;
103
+ closed;
104
+ active = false;
105
+ partial;
106
+ failure;
107
+ pending = /* @__PURE__ */ new Set();
108
+ emitted = [];
109
+ restored = false;
110
+ resetPending = false;
111
+ queuePreview = [];
112
+ transient = /* @__PURE__ */ new Map();
113
+ transientSequence = 0;
114
+ // Harness keeps its scheduler alive between requests. Never inherit the
115
+ // scheduler's first-request permission/extension scope for later work.
116
+ requestScope = AsyncLocalStorage.snapshot();
117
+ toolTask;
118
+ runTask;
119
+ /** `fabricJournalDirectory` lets an interrupted fabric_exec resume from a crash journal. */
120
+ constructor(options) {
121
+ super(options);
122
+ if (!options.runId) throw new Error("DurableAgent requires a non-empty runId");
123
+ this.durableOptions = options;
124
+ Object.defineProperties(super.state, {
125
+ isStreaming: { get: () => this.active },
126
+ streamingMessage: { get: () => this.partial },
127
+ pendingToolCalls: { get: () => this.pending },
128
+ errorMessage: { get: () => this.failure }
129
+ });
130
+ this.toolTask = this.scopedTask({
131
+ name: "fabric.agent.tool",
132
+ version: 1,
133
+ initial: () => ({ phase: "execute" }),
134
+ phases: { execute: async (task, runtime, ctx) => {
135
+ await this.delivery;
136
+ const { call, message } = task.input;
137
+ const context = await this.executionContext();
138
+ const tool = context.tools?.find((t) => t.name === call.name);
139
+ const prior = await runtime.memo("intent", ctx);
140
+ if (!prior) {
141
+ await runtime.memo("intent", true, ctx);
142
+ await runtime.commit(async (tx) => {
143
+ await this.event(tx, { type: "tool_execution_start", toolCallId: call.id, toolName: call.name, args: call.arguments });
144
+ }, ctx);
145
+ await this.delivery;
146
+ }
147
+ const fabricExec = call.name === "fabric_exec";
148
+ const journalDirectory = fabricExec ? this.durableOptions.fabricJournalDirectory : void 0;
149
+ const journalPath = journalDirectory === void 0 ? void 0 : fabricJournalPath(journalDirectory, String(task.id), call.id);
150
+ const recorded = prior && journalPath ? await runtime.memo("fabric.journal", ctx) : void 0;
151
+ let execute = !prior || task.input.replaySafe === true && tool?.replay === "safe";
152
+ if (!execute && recorded !== void 0) {
153
+ for (let attempt = 1; attempt <= MAX_JOURNAL_RESUMES && !execute; attempt++) {
154
+ if (await runtime.memo(`fabric.resume.${attempt}`, ctx) === void 0) {
155
+ execute = await runtime.memo(`fabric.resume.${attempt}`, true, ctx);
156
+ }
157
+ }
158
+ } else if (!execute && fabricExec && await runtime.memo("fabric.fence", ctx) === true && await runtime.memo("fabric.armed", ctx) === void 0 && await runtime.memo("fabric.rerun", ctx) === void 0) {
159
+ execute = await runtime.memo("fabric.rerun", true, ctx);
160
+ }
161
+ const fence = fabricExec ? {
162
+ toolCallId: call.id,
163
+ accept: async () => {
164
+ if (recorded !== void 0) throw new Error("This Fabric version cannot resume an interrupted fabric_exec from its journal. Nothing was rerun.");
165
+ await runtime.memo("fabric.fence", true, ctx);
166
+ },
167
+ arm: async () => {
168
+ await runtime.memo("fabric.armed", true, ctx);
169
+ },
170
+ ...journalPath ? { journal: {
171
+ path: journalPath,
172
+ ...recorded !== void 0 ? { digest: recorded } : {},
173
+ accept: async (digest) => {
174
+ if (await runtime.memo("fabric.journal", digest, ctx) !== digest) throw new Error("fabric_exec already recorded a different journal");
175
+ }
176
+ } } : {}
177
+ } : void 0;
178
+ const outcome = !execute ? { isError: true, result: { content: [{ type: "text", text: "Tool execution interrupted; unsafe effect was not replayed." }], details: { interrupted: true } } } : await toolFences().run(fence, () => runToolCall(call, {
179
+ tools: context.tools ?? [],
180
+ assistantMessage: message,
181
+ context,
182
+ signal: runtime.signal,
183
+ ...this.beforeToolCall ? { beforeToolCall: this.beforeToolCall } : {},
184
+ ...this.afterToolCall ? { afterToolCall: this.afterToolCall } : {},
185
+ onUpdate: async (result2) => {
186
+ await this.transientEvent((change) => runtime.commit(change, ctx), { type: "tool_execution_update", toolCallId: call.id, toolName: call.name, args: call.arguments, partialResult: result2 });
187
+ }
188
+ }));
189
+ const result = {
190
+ role: "toolResult",
191
+ toolCallId: call.id,
192
+ toolName: call.name,
193
+ content: outcome.result.content ?? [],
194
+ details: outcome.result.details,
195
+ isError: outcome.isError,
196
+ ...outcome.result.usage ? { usage: outcome.result.usage } : {},
197
+ timestamp: Date.now()
198
+ };
199
+ await runtime.commit(async (tx) => {
200
+ await this.event(tx, { type: "tool_execution_end", toolCallId: call.id, toolName: call.name, result: outcome.result, isError: outcome.isError });
201
+ return { status: "terminal", outcome: { status: "completed", result: copy({ ...result, terminate: "terminate" in outcome.result && outcome.result.terminate === true }) } };
202
+ }, ctx);
203
+ if (journalPath) await removeFabricJournal(journalPath);
204
+ } },
205
+ abort: async (task, runtime, ctx) => {
206
+ const { call } = task.input;
207
+ const result = { role: "toolResult", toolCallId: call.id, toolName: call.name, content: [{ type: "text", text: "Tool execution aborted" }], isError: true, timestamp: Date.now() };
208
+ await runtime.commit(async (tx) => {
209
+ await this.event(tx, { type: "tool_execution_end", toolCallId: call.id, toolName: call.name, result, isError: true });
210
+ return { status: "terminal", outcome: { status: "completed", result } };
211
+ }, ctx);
212
+ const journalDirectory = call.name === "fabric_exec" ? this.durableOptions.fabricJournalDirectory : void 0;
213
+ if (journalDirectory !== void 0) await removeFabricJournal(fabricJournalPath(journalDirectory, String(task.id), call.id));
214
+ }
215
+ });
216
+ this.runTask = this.scopedTask({
217
+ name: "fabric.agent.run",
218
+ version: 1,
219
+ initial: () => ({ phase: "prepare" }),
220
+ phases: {
221
+ prepare: async (task, runtime, ctx) => {
222
+ await this.delivery;
223
+ let context = await this.executionContext();
224
+ const saved = await this.engine.snapshot(Ledger, runtime.conversationId, ctx);
225
+ let model = saved?.config?.model ?? this.state.model;
226
+ let thinking = saved?.config?.thinking ?? this.state.thinkingLevel;
227
+ if (task.state.checkpoint.next) {
228
+ const turn = { ...task.state.checkpoint.next, context };
229
+ const update2 = this.prepareNextTurnWithContext ? await this.prepareNextTurnWithContext(turn, runtime.signal) : await this.prepareNextTurn?.(runtime.signal);
230
+ if (update2?.context) context = update2.context;
231
+ model = update2?.model ?? model;
232
+ thinking = update2?.thinkingLevel ?? thinking;
233
+ await runtime.commit(async (tx) => {
234
+ await this.event(tx, { type: "turn_start" });
235
+ }, ctx);
236
+ await this.delivery;
237
+ if (update2?.messages?.length) {
238
+ const additions = update2.messages;
239
+ await runtime.commit(async (tx) => {
240
+ for (const m of additions) await this.message(tx, m);
241
+ }, ctx);
242
+ await this.delivery;
243
+ context = { ...context, messages: [...context.messages, ...additions] };
244
+ }
245
+ }
246
+ await this.admit(runtime.signal);
247
+ await runtime.commit(async (tx) => {
248
+ const ledger = await tx.doc(Ledger, runtime.conversationId);
249
+ const queued = task.state.checkpoint.pending?.map(wire) ?? (task.state.checkpoint.skipSteering ? [] : ledger.steering.splice(0, this.steeringMode === "all" ? ledger.steering.length : 1));
250
+ for (const value of queued) {
251
+ const message = value;
252
+ await this.message(tx, message);
253
+ context.messages.push(message);
254
+ }
255
+ const changes = getToolStateChanges(getCurrentTools(context.messages), (context.tools ?? []).map(toToolDeclaration));
256
+ if (changes.toolsAdded.length || changes.toolsRemoved.length) {
257
+ const message = { role: "system", content: "", timestamp: Date.now(), ...changes };
258
+ await this.message(tx, message);
259
+ context.messages.push(message);
260
+ }
261
+ }, ctx);
262
+ await this.delivery;
263
+ const update = await this.prepareRequest?.({ context, model, thinkingLevel: thinking }, runtime.signal);
264
+ context = update?.context ?? context;
265
+ model = update?.model ?? model;
266
+ thinking = update?.thinkingLevel ?? thinking;
267
+ const transformed = this.transformContext ? await this.transformContext(context.messages, runtime.signal) : context.messages;
268
+ const messages = await this.convertToLlm(transformed);
269
+ await runtime.commit(async (tx) => {
270
+ const ledger = await tx.doc(Ledger, runtime.conversationId);
271
+ ledger.config = { model: wire(model), thinking };
272
+ const registered = new Set(this.state.tools.map((tool) => tool.name));
273
+ if ((context.tools ?? []).some((tool) => !registered.has(tool.name))) throw new Error("Durable request tools must be registered in agent.state.tools");
274
+ ledger.context = { messages: context.messages.map(wire), tools: (context.tools ?? []).map((tool) => tool.name) };
275
+ return { status: "running", checkpoint: { phase: "model", messages: copy(messages), model: copy(model), thinking } };
276
+ }, ctx);
277
+ },
278
+ model: async (task, runtime, ctx) => {
279
+ await this.delivery;
280
+ const cp = task.state.checkpoint;
281
+ const stream = await this.streamFunction(cp.model, normalizeContext({ messages: cp.messages }), {
282
+ signal: runtime.signal,
283
+ ...cp.thinking === "off" ? {} : { reasoning: cp.thinking },
284
+ ...this.sessionId ? { sessionId: this.sessionId } : {},
285
+ ...this.thinkingBudgets ? { thinkingBudgets: this.thinkingBudgets } : {},
286
+ transport: this.transport,
287
+ ...this.maxRetryDelayMs !== void 0 ? { maxRetryDelayMs: this.maxRetryDelayMs } : {},
288
+ ...this.getApiKey ? { apiKey: await this.getApiKey(cp.model.provider) ?? "" } : {},
289
+ ...this.onPayload ? { onPayload: this.onPayload } : {},
290
+ ...this.onResponse ? { onResponse: this.onResponse } : {},
291
+ ...this.onProviderStreamEvent ? { onProviderStreamEvent: this.onProviderStreamEvent } : {}
292
+ });
293
+ let started = false;
294
+ for await (const event of stream) {
295
+ if (event.type === "done" || event.type === "error") continue;
296
+ if (!started) {
297
+ await runtime.commit(async (tx) => {
298
+ await this.event(tx, { type: "message_start", message: event.partial });
299
+ }, ctx);
300
+ await this.delivery;
301
+ }
302
+ started = true;
303
+ if (event.type !== "start") await this.transientEvent((change) => runtime.commit(change, ctx), { type: "message_update", message: event.partial, assistantMessageEvent: event });
304
+ }
305
+ const message = copy({ ...await stream.result(), thinkingLevel: cp.thinking });
306
+ await runtime.commit(async (tx) => {
307
+ if (!started) await this.event(tx, { type: "message_start", message });
308
+ await this.event(tx, { type: "message_end", message });
309
+ const calls = message.stopReason !== "error" && message.stopReason !== "aborted" ? message.content.filter((c) => c.type === "toolCall") : [];
310
+ if (message.stopReason === "length" && calls.length) {
311
+ const results = [];
312
+ for (const call of calls) {
313
+ const result = { content: [{ type: "text", text: "Tool call was truncated by the output token limit; execution refused." }], details: {} };
314
+ await this.event(tx, { type: "tool_execution_start", toolCallId: call.id, toolName: call.name, args: call.arguments });
315
+ await this.event(tx, { type: "tool_execution_end", toolCallId: call.id, toolName: call.name, result, isError: true });
316
+ const toolResult = { role: "toolResult", toolCallId: call.id, toolName: call.name, ...result, isError: true, timestamp: Date.now() };
317
+ results.push(toolResult);
318
+ await this.message(tx, toolResult);
319
+ }
320
+ return { status: "running", checkpoint: { phase: "boundary", message, results } };
321
+ }
322
+ const sequential = this.toolExecution === "sequential" || calls.some((c) => this.state.tools.find((t) => t.name === c.name)?.executionMode === "sequential");
323
+ const children = [];
324
+ for (const call of sequential ? calls.slice(0, 1) : calls) children.push(await tx.createTask(this.toolTask, { message, call, replaySafe: this.state.tools.find((t) => t.name === call.name)?.replay === "safe" }, { ownership: { kind: "task", taskId: task.id } }));
325
+ return children.length ? { status: "waiting", checkpoint: { phase: "tools", message, children }, on: children, policy: "allSettled" } : { status: "running", checkpoint: { phase: "boundary", message, results: [] } };
326
+ }, ctx);
327
+ },
328
+ tools: async (task, runtime, ctx) => {
329
+ await this.delivery;
330
+ const { message, children } = task.state.checkpoint;
331
+ const calls = message.content.filter((c) => c.type === "toolCall");
332
+ if (children.length < calls.length) {
333
+ await runtime.commit(async (tx) => {
334
+ const child = await tx.createTask(this.toolTask, { message, call: calls[children.length], replaySafe: this.state.tools.find((t) => t.name === calls[children.length].name)?.replay === "safe" }, { ownership: { kind: "task", taskId: task.id } });
335
+ return { status: "waiting", checkpoint: { phase: "tools", message, children: [...children, child] }, on: [child], policy: "allSettled" };
336
+ }, ctx);
337
+ return;
338
+ }
339
+ const outcomes = await runtime.outcomes(children, ctx);
340
+ const results = outcomes.map((o, index) => o.status === "completed" ? o.result : {
341
+ role: "toolResult",
342
+ toolCallId: calls[index].id,
343
+ toolName: calls[index].name,
344
+ content: [{ type: "text", text: `Tool task ${o.status}` }],
345
+ isError: true,
346
+ timestamp: Date.now()
347
+ });
348
+ const terminate = results.length > 0 && results.every((r) => r.terminate);
349
+ for (const result of results) delete result.terminate;
350
+ await runtime.commit(async (tx) => {
351
+ for (const result of results) await this.message(tx, result);
352
+ return { status: "running", checkpoint: copy({ phase: "boundary", message, results, terminate }) };
353
+ }, ctx);
354
+ },
355
+ boundary: async (task, runtime, ctx) => {
356
+ await this.delivery;
357
+ const { message, results, terminate } = task.state.checkpoint;
358
+ const decision = await this.finishTurn?.({ message: this.lastAssistant(message), toolResults: this.canonicalToolResults(results), context: await this.executionContext(), newMessages: this.emitted.slice() }, runtime.signal);
359
+ await runtime.commit(async (tx) => {
360
+ await this.event(tx, { type: "turn_end", message, toolResults: results });
361
+ return { status: "running", checkpoint: { phase: "decide", message, results, ...decision ? { action: decision.action } : {}, ...terminate ? { terminate: true } : {} } };
362
+ }, ctx);
363
+ },
364
+ decide: async (task, runtime, ctx) => {
365
+ await this.delivery;
366
+ await this.admit(runtime.signal);
367
+ const cp = task.state.checkpoint;
368
+ await runtime.commit(async (tx) => {
369
+ const ledger = await tx.doc(Ledger, runtime.conversationId);
370
+ const hardEnd = cp.message.stopReason === "error" || cp.message.stopReason === "aborted" || cp.action === "end";
371
+ let queued = [];
372
+ if (!hardEnd) {
373
+ queued = ledger.steering.splice(0, this.steeringMode === "all" ? ledger.steering.length : 1);
374
+ if (!queued.length && (!cp.results.length || cp.terminate) && cp.action !== "continue") queued = ledger.followup.splice(0, this.followUpMode === "all" ? ledger.followup.length : 1);
375
+ }
376
+ if (!hardEnd && (queued.length || cp.results.length && !cp.terminate || cp.action === "continue")) {
377
+ const next = copy({ message: cp.message, toolResults: cp.results, newMessages: this.emitted.slice() });
378
+ return { status: "running", checkpoint: { phase: "prepare", next, ...queued.length ? { pending: copy(queued) } : {}, skipSteering: queued.length > 0 } };
379
+ }
380
+ ledger.active = 0;
381
+ await this.event(tx, { type: "agent_end", messages: this.emitted.slice() });
382
+ return { status: "terminal", outcome: { status: "completed", result: null } };
383
+ }, ctx);
384
+ }
385
+ },
386
+ abort: async (task, runtime, ctx) => {
387
+ await this.delivery;
388
+ const results = [];
389
+ if (task.state.checkpoint.phase === "tools") {
390
+ const { message, children } = task.state.checkpoint;
391
+ const calls = message.content.filter((c) => c.type === "toolCall");
392
+ for (const [index, call] of calls.entries()) {
393
+ const child = children[index] ? await runtime.getTask(children[index], ctx) : void 0;
394
+ const outcome = child?.state.status === "terminal" ? child.state.outcome : void 0;
395
+ const result = outcome?.status === "completed" ? copy(outcome.result) : {
396
+ role: "toolResult",
397
+ toolCallId: call.id,
398
+ toolName: call.name,
399
+ content: [{ type: "text", text: "Tool execution aborted" }],
400
+ isError: true,
401
+ timestamp: Date.now()
402
+ };
403
+ delete result.terminate;
404
+ results.push(result);
405
+ }
406
+ }
407
+ await runtime.commit(async (tx) => {
408
+ const ledger = await tx.doc(Ledger, runtime.conversationId);
409
+ ledger.active = 0;
410
+ for (const result of results) await this.message(tx, result);
411
+ const message = this.failureMessage("Operation aborted", true);
412
+ await this.message(tx, message);
413
+ await this.event(tx, { type: "turn_end", message, toolResults: results });
414
+ await this.event(tx, { type: "agent_end", messages: [...this.emitted, ...results, message] });
415
+ return { status: "terminal", outcome: { status: "aborted" } };
416
+ }, ctx);
417
+ }
418
+ });
419
+ this.registry.install({ name: "fabric-agent", tasks: [this.runTask, this.toolTask] });
420
+ }
421
+ scopedTask(definition) {
422
+ const phases = Object.fromEntries(Object.entries(definition.phases).map(([name, handler]) => [
423
+ name,
424
+ async (...args) => {
425
+ if (!await this.startup) throw new Error("DurableAgent recovery failed");
426
+ return this.requestScope(handler, ...args);
427
+ }
428
+ ]));
429
+ const abort = definition.abort;
430
+ return defineTask({ ...definition, phases, ...abort ? { abort: async (...args) => {
431
+ if (!await this.startup) throw new Error("DurableAgent recovery failed");
432
+ return this.requestScope(abort, ...args);
433
+ } } : {} });
434
+ }
435
+ failureMessage(errorMessage, aborted) {
436
+ return {
437
+ role: "assistant",
438
+ content: [],
439
+ api: this.state.model.api,
440
+ provider: this.state.model.provider,
441
+ model: this.state.model.id,
442
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
443
+ stopReason: aborted ? "aborted" : "error",
444
+ errorMessage,
445
+ timestamp: Date.now()
446
+ };
447
+ }
448
+ context() {
449
+ return { messages: this.state.messages.slice(), tools: this.state.tools.slice() };
450
+ }
451
+ async executionContext() {
452
+ const saved = await this.engine.snapshot(Ledger, this.root.id, BACKGROUND_CONTEXT);
453
+ if (!saved?.context) return this.context();
454
+ return { messages: copy(saved.context.messages), tools: this.state.tools.filter((tool) => saved.context.tools.includes(tool.name)) };
455
+ }
456
+ canonicalToolResults(results) {
457
+ const messages = this.state.messages.slice().reverse();
458
+ return results.map((result) => messages.find((message) => message.role === "toolResult" && message.toolCallId === result.toolCallId) ?? result);
459
+ }
460
+ lastAssistant(fallback) {
461
+ return this.state.messages.slice().reverse().find((m) => m.role === "assistant") ?? fallback;
462
+ }
463
+ async event(tx, event) {
464
+ await tx.appendEntry(this.root.id, { kind: EVENT, data: wire(event) });
465
+ if (event.type === "message_end") {
466
+ const ledger = await tx.doc(Ledger, this.root.id);
467
+ ledger.context?.messages.push(wire(event.message));
468
+ }
469
+ }
470
+ /** Commit an ordered, slim marker for a streaming update; its payload stays in memory until delivery. */
471
+ async transientEvent(commit, event) {
472
+ const sequence = ++this.transientSequence;
473
+ this.transient.set(sequence, copy(event));
474
+ let marker;
475
+ if (event.type === "message_update") {
476
+ const { partial: _partial, ...delta } = event.assistantMessageEvent;
477
+ marker = { type: event.type, assistantMessageEvent: delta };
478
+ } else marker = { type: event.type, toolCallId: event.toolCallId, toolName: event.toolName };
479
+ try {
480
+ await commit(async (tx) => {
481
+ await tx.appendEntry(this.root.id, { kind: EVENT, data: wire({ ...marker, [TRANSIENT]: sequence }) });
482
+ return void 0;
483
+ });
484
+ } catch (error) {
485
+ this.transient.delete(sequence);
486
+ throw error;
487
+ }
488
+ await this.delivery;
489
+ }
490
+ /** Restore a committed streaming marker to the full event; undefined when its payload is not in this process. */
491
+ rehydrate(data) {
492
+ const sequence = data[TRANSIENT];
493
+ if (typeof sequence !== "number") return data;
494
+ const event = this.transient.get(sequence);
495
+ this.transient.delete(sequence);
496
+ return event;
497
+ }
498
+ async message(tx, message) {
499
+ await this.event(tx, { type: "message_start", message });
500
+ await this.event(tx, { type: "message_end", message });
501
+ }
502
+ async expose(event) {
503
+ if (event.type === "turn_end") event = {
504
+ ...event,
505
+ message: event.message.role === "assistant" ? this.lastAssistant(event.message) : event.message,
506
+ toolResults: this.canonicalToolResults(event.toolResults)
507
+ };
508
+ if (event.type === "message_start" && event.message.role === "assistant") this.partial = event.message;
509
+ if (event.type === "message_update") this.partial = event.message;
510
+ if (event.type === "message_end") {
511
+ this.state.messages = [...this.state.messages, event.message];
512
+ this.emitted.push(event.message);
513
+ this.partial = void 0;
514
+ if (event.message.role === "assistant") this.failure = event.message.errorMessage;
515
+ const index = this.queuePreview.findIndex((q) => JSON.stringify(q.message) === JSON.stringify(event.message));
516
+ if (index >= 0) this.queuePreview.splice(index, 1);
517
+ }
518
+ if (event.type === "tool_execution_start") this.pending.add(event.toolCallId);
519
+ if (event.type === "tool_execution_end") this.pending.delete(event.toolCallId);
520
+ for (const observer of this.observers) await observer(event, this.controller?.signal ?? new AbortController().signal);
521
+ }
522
+ async open() {
523
+ if (this.closing) throw new Error("DurableAgent is closed");
524
+ return this.opening ??= (async () => {
525
+ const borrowed = new Proxy(this.durableOptions.storage, { get(target, key) {
526
+ if (key === "close") return async () => {
527
+ };
528
+ const value = Reflect.get(target, key, target);
529
+ return typeof value === "function" ? value.bind(target) : value;
530
+ } });
531
+ const harness = await Harness.open(borrowed, { models: this.durableOptions.models, registry: this.registry }, BACKGROUND_CONTEXT);
532
+ this.engine = harness;
533
+ this.root = await harness.root(BACKGROUND_CONTEXT);
534
+ const ledger = await harness.snapshot(Ledger, this.root.id, BACKGROUND_CONTEXT);
535
+ if (ledger?.runId && ledger.runId !== this.durableOptions.runId) throw new Error("DurableAgent storage belongs to a different runId");
536
+ const history = (await this.root.context(BACKGROUND_CONTEXT)).entries;
537
+ const messages = [];
538
+ for (const entry of history) {
539
+ if (entry.kind === HISTORY) {
540
+ messages.splice(0, messages.length, ...entry.data);
541
+ this.restored = true;
542
+ }
543
+ if (entry.kind === EVENT) {
544
+ const event = entry.data;
545
+ if (event.type === "agent_start") this.emitted = [];
546
+ if (event.type === "message_end") {
547
+ messages.push(event.message);
548
+ this.emitted.push(event.message);
549
+ }
550
+ }
551
+ }
552
+ if (this.restored && !this.resetPending) this.state.messages = messages;
553
+ if (this.restored && !this.resetPending) await this.recoverHistory?.(copy(messages));
554
+ this.queuePreview = [...this.queuePreview, ...(ledger?.steering ?? []).map((message) => ({ mode: "steering", message })), ...(ledger?.followup ?? []).map((message) => ({ mode: "followup", message }))];
555
+ harness.subscribeCommits((publication) => {
556
+ for (const change of publication.changes) {
557
+ if (change.type !== "entry" || change.value.conversationId !== this.root.id || change.value.kind !== EVENT) continue;
558
+ const event = this.rehydrate(copy(change.value.data));
559
+ if (!event) continue;
560
+ this.delivery = this.delivery.then(() => this.requestScope(() => this.expose(event)));
561
+ void this.delivery.catch(() => {
562
+ });
563
+ }
564
+ });
565
+ this.releaseStartup(true);
566
+ })().catch((error) => {
567
+ this.releaseStartup(false);
568
+ throw error;
569
+ });
570
+ }
571
+ /** Resolves only after all controls accepted so far have committed. */
572
+ awaitControls() {
573
+ return this.admission;
574
+ }
575
+ /**
576
+ * A phase's wait for accepted controls. abort() chains the engine abort onto admission, and that abort joins the
577
+ * running invocation, so a phase that kept waiting on admission after its abort signal would wait on itself. The
578
+ * phase's next commit then rejects on the durable abort mark and the abort handler settles the task.
579
+ */
580
+ admit(signal) {
581
+ if (signal.aborted) return Promise.resolve();
582
+ let onAbort;
583
+ const aborted = new Promise((resolve3) => {
584
+ onAbort = resolve3;
585
+ signal.addEventListener("abort", onAbort, { once: true });
586
+ });
587
+ return Promise.race([this.admission, aborted]).finally(() => signal.removeEventListener("abort", onAbort));
588
+ }
589
+ setRequestId(id) {
590
+ if (!id) throw new Error("requestId must not be empty");
591
+ this.requestId = id;
592
+ }
593
+ subscribe(listener) {
594
+ this.observers.add(listener);
595
+ return () => {
596
+ this.observers.delete(listener);
597
+ };
598
+ }
599
+ get signal() {
600
+ return this.controller?.signal;
601
+ }
602
+ waitForIdle() {
603
+ return this.running ?? Promise.resolve();
604
+ }
605
+ abort() {
606
+ this.controller?.abort();
607
+ if (this.root && this.active) {
608
+ const aborting = this.root.abort(BACKGROUND_CONTEXT);
609
+ this.admission = this.admission.then(() => aborting);
610
+ void this.admission.catch(() => {
611
+ });
612
+ }
613
+ }
614
+ prompt(input, images) {
615
+ const messages = typeof input === "string" ? [{ role: "user", content: images?.length ? [{ type: "text", text: input }, ...images] : input, timestamp: Date.now() }] : Array.isArray(input) ? input : [input];
616
+ return this.start(messages);
617
+ }
618
+ continue() {
619
+ return this.start([]);
620
+ }
621
+ start(messages) {
622
+ if (this.active) return Promise.reject(new Error("Agent is already processing a prompt"));
623
+ if (this.closeRequested) return Promise.reject(new Error("DurableAgent is closed"));
624
+ const request = this.requestId ?? (this.firstRequest && messages.length ? this.durableOptions.runId : randomUUID());
625
+ this.requestId = void 0;
626
+ this.firstRequest = false;
627
+ this.requestScope = AsyncLocalStorage.snapshot();
628
+ this.active = true;
629
+ this.failure = void 0;
630
+ this.emitted = [];
631
+ this.controller = new AbortController();
632
+ const run = (async () => {
633
+ await this.open();
634
+ await this.admission;
635
+ let id;
636
+ await this.root.commit(async (tx) => {
637
+ const ledger = await tx.doc(Ledger, this.root.id);
638
+ ledger.runId = this.durableOptions.runId;
639
+ if (Object.hasOwn(ledger.requests, request)) {
640
+ id = ledger.requests[request];
641
+ return;
642
+ }
643
+ if (ledger.active) {
644
+ if (messages.length) throw new Error("Unfinished durable run: resume with continue() or its original requestId");
645
+ id = ledger.active;
646
+ ledger.requests = { ...ledger.requests, [request]: id };
647
+ return;
648
+ }
649
+ if (!messages.length) {
650
+ const last = this.state.messages.at(-1);
651
+ if (!last || this.state.messages.every((m) => m.role === "system")) throw new Error("No messages to continue from");
652
+ if (last.role === "assistant") {
653
+ const queue = ledger.steering.length ? ledger.steering : ledger.followup;
654
+ const mode = ledger.steering.length ? this.steeringMode : this.followUpMode;
655
+ messages = queue.splice(0, mode === "all" ? queue.length : 1);
656
+ if (!messages.length) throw new Error("Cannot continue from message role: assistant");
657
+ }
658
+ }
659
+ delete ledger.context;
660
+ ledger.config = { model: wire(this.state.model), thinking: this.state.thinkingLevel };
661
+ if (!this.restored || this.resetPending || !ledger.active) {
662
+ await tx.appendEntry(this.root.id, { kind: HISTORY, data: wire(this.state.messages) });
663
+ this.restored = true;
664
+ this.resetPending = false;
665
+ }
666
+ this.emitted = [];
667
+ await this.event(tx, { type: "agent_start" });
668
+ await this.event(tx, { type: "turn_start" });
669
+ for (const message of messages) await this.message(tx, message);
670
+ id = await tx.createTask(this.runTask, { request }, { ownership: { kind: "conversation" } });
671
+ ledger.requests = { ...ledger.requests, [request]: id };
672
+ ledger.active = id;
673
+ }, BACKGROUND_CONTEXT);
674
+ await this.delivery;
675
+ if (this.controller.signal.aborted) await this.engine.abortTask(id, BACKGROUND_CONTEXT);
676
+ const settled = await this.engine.waitForTask(id, BACKGROUND_CONTEXT);
677
+ await this.delivery;
678
+ if (settled.state.outcome.status === "failed" || settled.state.outcome.status === "faulted") {
679
+ const message = this.failureMessage(settled.state.outcome.error.message, false);
680
+ await this.root.commit(async (tx) => {
681
+ const ledger = await tx.doc(Ledger, this.root.id);
682
+ if (ledger.active !== id) return;
683
+ ledger.active = 0;
684
+ await this.message(tx, message);
685
+ await this.event(tx, { type: "turn_end", message, toolResults: [] });
686
+ await this.event(tx, { type: "agent_end", messages: [...this.emitted, message] });
687
+ }, BACKGROUND_CONTEXT);
688
+ await this.delivery;
689
+ }
690
+ })().finally(() => {
691
+ this.active = false;
692
+ this.partial = void 0;
693
+ this.pending.clear();
694
+ this.controller = void 0;
695
+ this.running = void 0;
696
+ });
697
+ this.running = run;
698
+ return run;
699
+ }
700
+ enqueue(mode, message) {
701
+ if (this.closeRequested) throw new Error("DurableAgent is closed");
702
+ const request = this.requestId;
703
+ this.requestId = void 0;
704
+ this.queuePreview.push({ mode, message: copy(message) });
705
+ this.admission = this.admission.then(async () => {
706
+ await this.open();
707
+ await this.root.commit(async (tx) => {
708
+ const ledger = await tx.doc(Ledger, this.root.id);
709
+ ledger.runId ||= this.durableOptions.runId;
710
+ ledger.controls ??= {};
711
+ if (request && Object.hasOwn(ledger.controls, request)) {
712
+ const index = this.queuePreview.findIndex((q) => q.mode === mode && JSON.stringify(q.message) === JSON.stringify(message));
713
+ if (index >= 0) this.queuePreview.splice(index, 1);
714
+ return;
715
+ }
716
+ if (request) ledger.controls = { ...ledger.controls, [request]: true };
717
+ ledger[mode].push(wire(message));
718
+ }, BACKGROUND_CONTEXT);
719
+ });
720
+ void this.admission.catch(() => {
721
+ });
722
+ }
723
+ steer(message) {
724
+ this.enqueue("steering", message);
725
+ }
726
+ followUp(message) {
727
+ this.enqueue("followup", message);
728
+ }
729
+ clear(mode) {
730
+ if (this.closeRequested) throw new Error("DurableAgent is closed");
731
+ this.queuePreview = this.queuePreview.filter((q) => mode !== void 0 && q.mode !== mode);
732
+ this.admission = this.admission.then(async () => {
733
+ await this.open();
734
+ await this.root.commit(async (tx) => {
735
+ const d = await tx.doc(Ledger, this.root.id);
736
+ if (!mode || mode === "steering") d.steering = [];
737
+ if (!mode || mode === "followup") d.followup = [];
738
+ }, BACKGROUND_CONTEXT);
739
+ });
740
+ void this.admission.catch(() => {
741
+ });
742
+ }
743
+ clearSteeringQueue() {
744
+ this.clear("steering");
745
+ }
746
+ clearFollowUpQueue() {
747
+ this.clear("followup");
748
+ }
749
+ clearAllQueues() {
750
+ this.clear();
751
+ }
752
+ hasQueuedMessages() {
753
+ return this.queuePreview.length > 0;
754
+ }
755
+ peekQueuedMessages() {
756
+ const steering = this.queuePreview.filter((q) => q.mode === "steering").map((q) => q.message);
757
+ const followup = this.queuePreview.filter((q) => q.mode === "followup").map((q) => q.message);
758
+ return steering.length ? this.steeringMode === "all" ? steering : steering.slice(0, 1) : this.followUpMode === "all" ? followup : followup.slice(0, 1);
759
+ }
760
+ reset() {
761
+ if (this.active) throw new Error("Cannot reset a running DurableAgent");
762
+ const baseline = getCurrentSystemMessage(this.state.messages);
763
+ this.state.messages = baseline ? [baseline] : [];
764
+ this.partial = void 0;
765
+ this.failure = void 0;
766
+ this.pending.clear();
767
+ this.clearAllQueues();
768
+ this.resetPending = true;
769
+ }
770
+ /** Close cancels invocations, NOT durable tasks. A new Harness resumes their checkpoints. */
771
+ close() {
772
+ this.closeRequested = true;
773
+ return this.closed ??= (async () => {
774
+ const drained = await Promise.allSettled([this.opening, this.admission]);
775
+ this.closing = true;
776
+ if (this.engine) await this.engine.close(BACKGROUND_CONTEXT);
777
+ await this.delivery;
778
+ const rejected = drained.find((result) => result.status === "rejected");
779
+ if (rejected?.status === "rejected") throw rejected.reason;
780
+ })();
781
+ }
782
+ };
783
+
784
+ // src/durable/session.ts
785
+ var absolute = (path3) => resolve(path3 === "~" ? homedir() : path3.startsWith("~/") ? join(homedir(), path3.slice(2)) : path3);
786
+ async function createDurableAgentSession(options) {
787
+ if (!options.runId.trim()) throw new Error("A durable session requires a non-empty runId");
788
+ const cwd = absolute(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());
789
+ const agentDir = absolute(options.agentDir ?? getAgentDir());
790
+ const modelRuntime = options.modelRuntime ?? await ModelRuntime.create({
791
+ authPath: join(agentDir, "auth.json"),
792
+ modelsPath: join(agentDir, "models.json")
793
+ });
794
+ const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);
795
+ const sessionManager = options.sessionManager ?? SessionManager.create(
796
+ cwd,
797
+ join(agentDir, "sessions", `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`)
798
+ );
799
+ let resourceLoader = options.resourceLoader;
800
+ if (!resourceLoader) {
801
+ resourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });
802
+ await resourceLoader.reload();
803
+ }
804
+ const existing = sessionManager.buildSessionContext();
805
+ const branch = sessionManager.getBranch();
806
+ const hasHistory = existing.messages.length > 0;
807
+ const hasThinking = branch.some((entry) => entry.type === "thinking_level_change");
808
+ const lastSelection = branch.slice().reverse().find((entry) => entry.type === "model_change");
809
+ const selected = lastSelection?.type === "model_change" ? modelRuntime.getModel(lastSelection.provider, lastSelection.modelId) : void 0;
810
+ const saved = selected?.api === "pi-virtual" ? selected : existing.model ? modelRuntime.getModel(existing.model.provider, existing.model.modelId) : void 0;
811
+ let model = options.model;
812
+ if (!model && hasHistory && (lastSelection || existing.model)) {
813
+ if (!saved || saved.api !== "pi-virtual" && !modelRuntime.hasConfiguredAuth(saved.provider)) {
814
+ throw new Error("Cannot restore durable session model; explicitly select an available model");
815
+ }
816
+ model = saved;
817
+ }
818
+ if (!model) {
819
+ const available = await modelRuntime.getAvailable();
820
+ const provider = settingsManager.getDefaultProvider();
821
+ const modelId = settingsManager.getDefaultModel();
822
+ model = provider || modelId ? available.find((candidate) => (!provider || candidate.provider === provider) && (!modelId || candidate.id === modelId)) : available[0];
823
+ if (!model && (provider || modelId)) throw new Error(`Configured durable model is unavailable: ${provider ?? "*"}/${modelId ?? "*"}`);
824
+ }
825
+ if (!model) throw new Error("No available model for durable session; supply model and modelRuntime");
826
+ const savedThinking = ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(existing.thinkingLevel) ? existing.thinkingLevel : "medium";
827
+ const thinkingLevel = clampThinkingLevel(model, options.thinkingLevel ?? (hasHistory ? hasThinking ? savedThinking : settingsManager.getDefaultThinkingLevel() ?? "medium" : void 0) ?? settingsManager.getModelThinkingLevel(model.provider, model.id) ?? settingsManager.getDefaultThinkingLevel() ?? "medium");
828
+ const extensionRunnerRef = {};
829
+ const agentOptions = {
830
+ initialState: { systemPrompt: "", model, thinkingLevel, tools: [], messages: existing.messages },
831
+ convertToLlm: (messages) => {
832
+ const converted = convertToLlm(messages);
833
+ if (!settingsManager.getBlockImages()) return converted;
834
+ return converted.map((message) => {
835
+ if (message.role !== "user" && message.role !== "toolResult" || !Array.isArray(message.content)) return message;
836
+ return { ...message, content: message.content.map((part) => part.type === "image" ? { type: "text", text: "Image reading is disabled." } : part) };
837
+ });
838
+ },
839
+ transformContext: async (messages) => extensionRunnerRef.current?.emitContext(messages) ?? messages,
840
+ streamFn: (requestModel, context, requestOptions = {}) => {
841
+ const retry = settingsManager.getProviderRetrySettings();
842
+ const idleTimeout = settingsManager.getHttpIdleTimeoutMs();
843
+ const websocketConnectTimeoutMs = requestOptions.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();
844
+ const maxRetries = requestOptions.maxRetries ?? retry.maxRetries;
845
+ return modelRuntime.streamSimple(requestModel, context, {
846
+ ...requestOptions,
847
+ timeoutMs: requestOptions.timeoutMs ?? retry.timeoutMs ?? (idleTimeout === 0 ? 2147483647 : idleTimeout),
848
+ ...websocketConnectTimeoutMs !== void 0 ? { websocketConnectTimeoutMs } : {},
849
+ ...maxRetries !== void 0 ? { maxRetries } : {},
850
+ maxRetryDelayMs: requestOptions.maxRetryDelayMs ?? retry.maxRetryDelayMs,
851
+ transformHeaders: async (headers) => {
852
+ const transformed = headers;
853
+ const runner = extensionRunnerRef.current;
854
+ return runner?.hasHandlers("before_provider_headers") ? runner.emitBeforeProviderHeaders(transformed ?? {}) : transformed ?? {};
855
+ }
856
+ });
857
+ },
858
+ onPayload: async (payload) => {
859
+ const runner = extensionRunnerRef.current;
860
+ return runner?.hasHandlers("before_provider_request") ? runner.emitBeforeProviderRequest(payload) : payload;
861
+ },
862
+ onResponse: async (response) => {
863
+ const runner = extensionRunnerRef.current;
864
+ if (runner?.hasHandlers("after_provider_response")) {
865
+ await runner.emit({ type: "after_provider_response", status: response.status, headers: response.headers });
866
+ }
867
+ },
868
+ onProviderStreamEvent: async (data, requestModel) => {
869
+ const runner = extensionRunnerRef.current;
870
+ if (runner?.hasHandlers("provider_stream_event")) {
871
+ await runner.emit({ type: "provider_stream_event", data, provider: requestModel.provider, api: requestModel.api, model: requestModel.id });
872
+ }
873
+ },
874
+ sessionId: sessionManager.getSessionId(),
875
+ steeringMode: settingsManager.getSteeringMode(),
876
+ followUpMode: settingsManager.getFollowUpMode(),
877
+ transport: settingsManager.getTransport(),
878
+ ...settingsManager.getThinkingBudgets() ? { thinkingBudgets: settingsManager.getThinkingBudgets() } : {},
879
+ ...settingsManager.getProviderRetrySettings().maxRetryDelayMs !== void 0 ? { maxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs } : {}
880
+ };
881
+ const borrowedStorage = new Proxy(options.storage, {
882
+ get(target, property) {
883
+ if (property === "close") return async () => {
884
+ };
885
+ const value = Reflect.get(target, property, target);
886
+ return typeof value === "function" ? value.bind(target) : value;
887
+ }
888
+ });
889
+ const agent = new DurableAgent({
890
+ ...agentOptions,
891
+ models: modelRuntime,
892
+ storage: borrowedStorage,
893
+ runId: options.runId,
894
+ ...options.fabricJournalDirectory ? { fabricJournalDirectory: options.fabricJournalDirectory } : {}
895
+ });
896
+ try {
897
+ if (!hasHistory) sessionManager.appendModelChange(model.provider, model.id);
898
+ if (!hasHistory || !hasThinking) sessionManager.appendThinkingLevelChange(thinkingLevel);
899
+ const excluded = new Set(options.excludeTools);
900
+ const selection = resolveNativeToolSelection(
901
+ options.tools,
902
+ settingsManager.getDefaultTools() ?? ["read", "bash", "edit", "write"],
903
+ options.noTools
904
+ );
905
+ const session = new AgentSession({
906
+ agent,
907
+ cwd,
908
+ sessionManager,
909
+ settingsManager,
910
+ resourceLoader,
911
+ modelRuntime,
912
+ extensionRunnerRef,
913
+ ...options.customTools ? { customTools: options.customTools } : {},
914
+ ...options.scopedModels ? { scopedModels: options.scopedModels } : {},
915
+ ...options.sessionStartEvent ? { sessionStartEvent: options.sessionStartEvent } : {},
916
+ initialActiveToolNames: selection.active.filter((name) => !excluded.has(name)),
917
+ usesDefaultTools: options.tools === void 0 && !options.noTools,
918
+ ...selection.allowed ? { allowedToolNames: selection.allowed } : {},
919
+ ...options.excludeTools ? { excludedToolNames: options.excludeTools } : {}
920
+ });
921
+ agent.recoverHistory = (messages) => {
922
+ const key = (message) => JSON.stringify(message);
923
+ const projected = sessionManager.buildSessionContext().messages;
924
+ const branch2 = sessionManager.getBranch();
925
+ const counts = (values) => {
926
+ const result = /* @__PURE__ */ new Map();
927
+ for (const value of values) result.set(value, (result.get(value) ?? 0) + 1);
928
+ return result;
929
+ };
930
+ const present = counts(projected.map(key));
931
+ for (const [value, count] of counts(branch2.flatMap((entry) => entry.type === "message" ? [key(entry.message)] : []))) {
932
+ present.set(value, Math.max(present.get(value) ?? 0, count));
933
+ }
934
+ const seen = /* @__PURE__ */ new Map();
935
+ let end = 0;
936
+ messages.forEach((message, index) => {
937
+ const value = key(message);
938
+ const count = (seen.get(value) ?? 0) + 1;
939
+ seen.set(value, count);
940
+ if ((present.get(value) ?? 0) >= count) end = index + 1;
941
+ });
942
+ const missing = messages.slice(end);
943
+ const branchIds = new Set(branch2.map((entry) => entry.id));
944
+ const elsewhere = new Set(sessionManager.getEntries().flatMap((entry) => entry.type === "message" && !branchIds.has(entry.id) ? [key(entry.message)] : []));
945
+ if (!missing.some((message) => elsewhere.has(key(message)))) {
946
+ for (const message of missing) {
947
+ if (message.role === "compactionSummary") {
948
+ sessionManager.appendCompaction(message.summary, null, message.tokensBefore);
949
+ } else if (message.role === "branchSummary") {
950
+ sessionManager.branchWithSummary(sessionManager.getLeafId(), message.summary);
951
+ } else {
952
+ sessionManager.appendMessage(message);
953
+ }
954
+ }
955
+ }
956
+ agent.state.messages = sessionManager.buildSessionContext().messages;
957
+ };
958
+ const steer = session.steer.bind(session);
959
+ session.steer = async (...args) => {
960
+ const result = await steer(...args);
961
+ await agent.awaitControls();
962
+ return result;
963
+ };
964
+ const followUp = session.followUp.bind(session);
965
+ session.followUp = async (...args) => {
966
+ const result = await followUp(...args);
967
+ await agent.awaitControls();
968
+ return result;
969
+ };
970
+ let closing;
971
+ return { session, agent, close: () => closing ??= (async () => {
972
+ try {
973
+ await session.abort();
974
+ await session.extensionRunner.emit({ type: "session_shutdown", reason: "quit" });
975
+ } finally {
976
+ try {
977
+ session.dispose();
978
+ } finally {
979
+ await agent.close();
980
+ }
981
+ }
982
+ })() };
983
+ } catch (error) {
984
+ await agent.close();
985
+ throw error;
986
+ }
987
+ }
988
+
989
+ // src/durable/storage.ts
990
+ import { constants } from "node:fs";
991
+ import { chmod, lstat, mkdir, open, readdir, realpath } from "node:fs/promises";
992
+ import { basename, dirname, join as join2, resolve as resolve2 } from "node:path";
993
+ var ownedDirectories = /* @__PURE__ */ new Map();
994
+ async function openDurableWorkerStorage(directory) {
995
+ await mkdir(directory, { recursive: true, mode: 448 });
996
+ const canonical = await realpath(directory);
997
+ if (ownedDirectories.has(canonical)) throw new Error(`Durable worker storage is locked: ${canonical}`);
998
+ const ownership = Symbol(canonical);
999
+ ownedDirectories.set(canonical, ownership);
1000
+ const forget = () => {
1001
+ if (ownedDirectories.get(canonical) === ownership) ownedDirectories.delete(canonical);
1002
+ };
1003
+ try {
1004
+ return await acquire(canonical, forget);
1005
+ } catch (error) {
1006
+ forget();
1007
+ throw error;
1008
+ }
1009
+ }
1010
+ async function acquire(canonical, forget) {
1011
+ await chmod(canonical, 448);
1012
+ const leasePath = join2(canonical, "lease.sqlite");
1013
+ const regular = async (path3, missing = false) => {
1014
+ try {
1015
+ const info = await lstat(path3);
1016
+ if (!info.isFile() || info.nlink !== 1) throw new Error(`Durable file must be a regular, singly-linked file (no symlinks/hardlinks): ${path3}`);
1017
+ } catch (error) {
1018
+ if (!missing || error.code !== "ENOENT") throw error;
1019
+ }
1020
+ };
1021
+ await regular(leasePath, true);
1022
+ try {
1023
+ const leaseFile = await open(leasePath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 384);
1024
+ await leaseFile.close();
1025
+ } catch (error) {
1026
+ if (error.code !== "EEXIST") throw error;
1027
+ }
1028
+ await regular(leasePath);
1029
+ await chmod(leasePath, 384);
1030
+ for (const suffix of ["-journal", "-wal", "-shm"]) await regular(leasePath + suffix, true);
1031
+ const { DatabaseSync } = await import("node:sqlite");
1032
+ const lease = new DatabaseSync(leasePath, { timeout: 0 });
1033
+ let released = false;
1034
+ const release = async () => {
1035
+ if (released) return;
1036
+ lease.close();
1037
+ released = true;
1038
+ forget();
1039
+ };
1040
+ try {
1041
+ lease.exec("PRAGMA busy_timeout = 0; PRAGMA journal_mode = DELETE; BEGIN EXCLUSIVE;");
1042
+ const store = join2(canonical, "store");
1043
+ await mkdir(store, { recursive: true, mode: 448 });
1044
+ if (!(await lstat(store)).isDirectory()) throw new Error("Durable store must be a directory, not a symlink");
1045
+ await chmod(store, 448);
1046
+ for (const name of await readdir(store)) {
1047
+ const path3 = join2(store, name);
1048
+ await regular(path3);
1049
+ await chmod(path3, 384);
1050
+ }
1051
+ const [{ JsonlStorage }, { NodeExecutionEnv }, { FileError }, { BACKGROUND_CONTEXT: BACKGROUND_CONTEXT3 }] = await Promise.all([
1052
+ import("@earendil-works/pi-durable/storage/jsonl"),
1053
+ import("@earendil-works/pi-durable/env/node"),
1054
+ import("@earendil-works/pi-durable/env"),
1055
+ import("@earendil-works/chord/context")
1056
+ ]);
1057
+ const fs = new NodeExecutionEnv({ cwd: canonical });
1058
+ const checked = async (path3) => {
1059
+ if (dirname(resolve2(path3)) !== store || !/^(?:main|(?:doc|task)-(?:0|[1-9]\d*))\.jsonl(?:\.reclaim)?$/.test(basename(path3))) {
1060
+ throw new Error(`Durable path escapes storage: ${path3}`);
1061
+ }
1062
+ if (!(await lstat(store)).isDirectory()) throw new Error("Durable store directory was replaced");
1063
+ await regular(path3, true);
1064
+ };
1065
+ const syncDirectory = async () => {
1066
+ if (process.platform === "win32") return;
1067
+ const dir = await open(store, constants.O_RDONLY | constants.O_NOFOLLOW);
1068
+ try {
1069
+ await dir.sync();
1070
+ } finally {
1071
+ await dir.close();
1072
+ }
1073
+ };
1074
+ for (const method of ["appendFile", "writeFile"]) {
1075
+ fs[method] = async (path3, content, context) => {
1076
+ try {
1077
+ context.abortSignal?.throwIfAborted();
1078
+ await checked(path3);
1079
+ const file = await open(path3, constants.O_CREAT | constants.O_WRONLY | constants.O_NOFOLLOW | (method === "appendFile" ? constants.O_APPEND : 0), 384);
1080
+ try {
1081
+ const info = await file.stat();
1082
+ if (!info.isFile() || info.nlink !== 1) throw new Error("Durable file was replaced");
1083
+ await file.chmod(384);
1084
+ if (method === "writeFile") await file.truncate(0);
1085
+ await file.writeFile(content);
1086
+ await file.sync();
1087
+ } finally {
1088
+ await file.close();
1089
+ }
1090
+ await syncDirectory();
1091
+ return { ok: true, value: void 0 };
1092
+ } catch (error) {
1093
+ return { ok: false, error: new FileError("unknown", String(error), path3, error instanceof Error ? error : void 0) };
1094
+ }
1095
+ };
1096
+ }
1097
+ for (const method of ["openTextLineReader", "flushFile"]) {
1098
+ const original = fs[method].bind(fs);
1099
+ const guarded = async (path3, context) => {
1100
+ await checked(path3);
1101
+ return original(path3, context);
1102
+ };
1103
+ Object.defineProperty(fs, method, { value: guarded });
1104
+ }
1105
+ const truncate = fs.truncateFile.bind(fs);
1106
+ fs.truncateFile = async (path3, size, context) => {
1107
+ await checked(path3);
1108
+ const result = await truncate(path3, size, context);
1109
+ return result.ok ? fs.flushFile(path3, context) : result;
1110
+ };
1111
+ const storage = await JsonlStorage.open(store, fs, BACKGROUND_CONTEXT3, { fsync: true });
1112
+ return { storage, release };
1113
+ } catch (error) {
1114
+ await release();
1115
+ throw new Error(`Cannot acquire durable worker storage at ${canonical}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
1116
+ }
1117
+ }
1118
+
1119
+ // src/durable/worker-host.ts
1120
+ var FABRIC_JOURNAL_RETENTION_MS = 24 * 60 * 60 * 1e3;
1121
+ async function sweepFabricJournals(directory, now = Date.now()) {
1122
+ let names;
1123
+ try {
1124
+ names = await readdir2(directory);
1125
+ } catch (error) {
1126
+ if (error.code === "ENOENT") return;
1127
+ throw error;
1128
+ }
1129
+ for (const name of names) {
1130
+ if (!/^[0-9a-f]{32}\.jsonl$/.test(name)) continue;
1131
+ const file = path2.join(directory, name);
1132
+ const info = await lstat2(file).catch(() => void 0);
1133
+ if (info?.isFile() && now - info.mtimeMs > FABRIC_JOURNAL_RETENTION_MS) await unlink2(file).catch(() => void 0);
1134
+ }
1135
+ }
1136
+ async function resolveDurableProjectTrust(options) {
1137
+ if (!hasTrustRequiringProjectResources(options.cwd)) return true;
1138
+ const store = new ProjectTrustStore(options.agentDir);
1139
+ const context = {
1140
+ cwd: options.cwd,
1141
+ mode: "rpc",
1142
+ hasUI: false,
1143
+ ui: {
1144
+ select: async () => void 0,
1145
+ confirm: async () => false,
1146
+ input: async () => void 0,
1147
+ notify: (message) => process.stderr.write(`${message}
1148
+ `)
1149
+ }
1150
+ };
1151
+ for (const extension of options.extensionsResult.extensions) {
1152
+ for (const handler of extension.handlers.get("project_trust")?.slice() ?? []) {
1153
+ try {
1154
+ const result = await handler({ type: "project_trust", cwd: options.cwd }, context);
1155
+ if (result?.trusted !== "yes" && result?.trusted !== "no") continue;
1156
+ const trusted = result.trusted === "yes";
1157
+ if (result.remember === true) store.set(options.cwd, trusted);
1158
+ return trusted;
1159
+ } catch (error) {
1160
+ process.stderr.write(`Extension ${extension.path} project_trust error: ${String(error)}
1161
+ `);
1162
+ }
1163
+ }
1164
+ }
1165
+ return store.get(options.cwd) ?? options.defaultProjectTrust === "always";
1166
+ }
1167
+ var advertiseHostExtensionRunner = () => {
1168
+ const key = Symbol.for("pi-fabric.host-extension-runners.v1");
1169
+ const holder = globalThis;
1170
+ (holder[key] ??= /* @__PURE__ */ new Set()).add(ExtensionRunner);
1171
+ };
1172
+ var piHttpDispatcher;
1173
+ async function configureDurableHttp(settings) {
1174
+ piHttpDispatcher ??= import(new URL("./core/http-dispatcher.js", import.meta.resolve("@earendil-works/pi-coding-agent")).href);
1175
+ const { applyHttpProxySettings, configureHttpDispatcher } = await piHttpDispatcher;
1176
+ applyHttpProxySettings(settings.getGlobalSettings().httpProxy);
1177
+ configureHttpDispatcher(settings.getHttpIdleTimeoutMs());
1178
+ }
1179
+ async function createDurableWorkerRuntime(options) {
1180
+ advertiseHostExtensionRunner();
1181
+ const cwd = process.cwd();
1182
+ const agentDir = getAgentDir2();
1183
+ const manager = options.sessionFile ? SessionManager2.open(options.sessionFile, void 0, cwd) : SessionManager2.inMemory(cwd);
1184
+ let current;
1185
+ const initialSessionId = manager.getSessionId();
1186
+ let first = true;
1187
+ const closeCurrent = async () => {
1188
+ const previous = current;
1189
+ current = void 0;
1190
+ await previous?.close();
1191
+ };
1192
+ const factory = async (target) => {
1193
+ await closeCurrent();
1194
+ const settings = SettingsManager2.create(target.cwd, target.agentDir, { projectTrusted: false });
1195
+ await configureDurableHttp(settings);
1196
+ const services = await createAgentSessionServices({
1197
+ cwd: target.cwd,
1198
+ agentDir: target.agentDir,
1199
+ settingsManager: settings,
1200
+ modelRuntimeSignal: AbortSignal.timeout(15e3),
1201
+ resourceLoaderReloadOptions: {
1202
+ resolveProjectTrust: ({ extensionsResult }) => resolveDurableProjectTrust({
1203
+ cwd: target.cwd,
1204
+ agentDir: target.agentDir,
1205
+ extensionsResult,
1206
+ defaultProjectTrust: settings.getDefaultProjectTrust()
1207
+ })
1208
+ },
1209
+ resourceLoaderOptions: {
1210
+ additionalExtensionPaths: options.extensions,
1211
+ noExtensions: options.noExtensions,
1212
+ noSkills: options.noSkills,
1213
+ additionalSkillPaths: options.skills,
1214
+ appendSystemPrompt: options.appendSystemPrompt ? [options.appendSystemPrompt] : [],
1215
+ extensionFactories: [
1216
+ { name: "codemode", factory: createCodemodeExtension(), builtin: true, replaceable: true },
1217
+ { name: "tool-search", factory: createToolSearchExtension(), builtin: true, replaceable: true },
1218
+ { name: "mcp", factory: createMcpExtension(), builtin: true, replaceable: true }
1219
+ ]
1220
+ }
1221
+ });
1222
+ const extensionErrors = services.resourceLoader.getExtensions().errors;
1223
+ if (extensionErrors.length) throw durableExtensionLoadError(extensionErrors);
1224
+ for (const diagnostic of services.diagnostics) {
1225
+ process.stderr.write(`${diagnostic.type}: ${diagnostic.message}
1226
+ `);
1227
+ }
1228
+ const selection = resolveCliModel({
1229
+ ...options.model ? { cliModel: options.model } : {},
1230
+ ...options.provider ? { cliProvider: options.provider } : {},
1231
+ ...options.thinking ? { cliThinking: options.thinking } : {},
1232
+ modelRuntime: services.modelRuntime
1233
+ });
1234
+ if (selection.error) throw new Error(selection.error);
1235
+ if (selection.warning) process.stderr.write(`${selection.warning}
1236
+ `);
1237
+ const recoverInitialRequest = first;
1238
+ const sessionId = target.sessionManager.getSessionId();
1239
+ const key = sessionId === initialSessionId ? "initial" : createHash2("sha256").update(sessionId).digest("hex");
1240
+ first = false;
1241
+ const lease = await openDurableWorkerStorage(path2.join(options.directory, key));
1242
+ try {
1243
+ const fabricJournalDirectory = path2.join(options.directory, key, "fabric-journal");
1244
+ await sweepFabricJournals(fabricJournalDirectory);
1245
+ const host = await createDurableAgentSession({
1246
+ fabricJournalDirectory,
1247
+ ...services,
1248
+ sessionManager: target.sessionManager,
1249
+ ...target.sessionStartEvent ? { sessionStartEvent: target.sessionStartEvent } : {},
1250
+ storage: lease.storage,
1251
+ runId: `${options.runId}:${key}`,
1252
+ ...selection.model ? { model: selection.model } : {},
1253
+ ...options.thinking ?? selection.thinkingLevel ? { thinkingLevel: options.thinking ?? selection.thinkingLevel } : {},
1254
+ ...options.tools ? { tools: options.tools } : {},
1255
+ // Apply after wildcard expansion, including /new, /fork and /resume.
1256
+ excludeTools: [...options.excludeTools ?? [], ...nativeFabricExecExclusions(options.tools)],
1257
+ ...options.noTools ? { noTools: options.noTools } : {}
1258
+ });
1259
+ if (!recoverInitialRequest) host.agent.setRequestId(randomUUID2());
1260
+ current = { close: async () => {
1261
+ try {
1262
+ await host.agent.close();
1263
+ } finally {
1264
+ try {
1265
+ await lease.storage.close(BACKGROUND_CONTEXT2);
1266
+ } finally {
1267
+ await lease.release();
1268
+ }
1269
+ }
1270
+ } };
1271
+ return { session: host.session, extensionsResult: services.resourceLoader.getExtensions(), services, diagnostics: services.diagnostics };
1272
+ } catch (error) {
1273
+ try {
1274
+ await lease.storage.close(BACKGROUND_CONTEXT2);
1275
+ } finally {
1276
+ await lease.release();
1277
+ }
1278
+ throw error;
1279
+ }
1280
+ };
1281
+ const initial = await factory({ cwd, agentDir, sessionManager: manager });
1282
+ class DurableRuntime extends AgentSessionRuntime {
1283
+ async dispose() {
1284
+ try {
1285
+ await super.dispose();
1286
+ } finally {
1287
+ await closeCurrent();
1288
+ }
1289
+ }
1290
+ }
1291
+ return new DurableRuntime(initial.session, initial.services, factory, initial.diagnostics);
1292
+ }
1293
+ async function runDurableWorker(options) {
1294
+ const runtime = await createDurableWorkerRuntime(options);
1295
+ try {
1296
+ await runRpcMode(runtime);
1297
+ } finally {
1298
+ await runtime.dispose();
1299
+ }
1300
+ }
1301
+
1302
+ export {
1303
+ DurableAgent,
1304
+ createDurableAgentSession,
1305
+ openDurableWorkerStorage,
1306
+ sweepFabricJournals,
1307
+ resolveDurableProjectTrust,
1308
+ configureDurableHttp,
1309
+ createDurableWorkerRuntime,
1310
+ runDurableWorker
1311
+ };
1312
+ //# sourceMappingURL=chunk-3PKZSIRA.js.map