agents 0.32.0 → 0.34.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 (187) hide show
  1. package/README.md +1 -1
  2. package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +1 -1
  5. package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
  6. package/dist/agent-tools.d.ts +1 -1
  7. package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
  8. package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
  9. package/dist/browser/ai.js +2 -3
  10. package/dist/browser/ai.js.map +1 -1
  11. package/dist/browser/index.d.ts +33 -21
  12. package/dist/browser/index.js +937 -4
  13. package/dist/browser/index.js.map +1 -0
  14. package/dist/browser/tools/ai-sdk.d.ts +4 -4
  15. package/dist/browser/tools/ai-sdk.js +9 -3
  16. package/dist/browser/tools/ai-sdk.js.map +1 -1
  17. package/dist/browser/tools/pi.d.ts +11 -8
  18. package/dist/browser/tools/pi.js +58 -11
  19. package/dist/browser/tools/pi.js.map +1 -1
  20. package/dist/browser/tools/tanstack-ai.d.ts +4 -4
  21. package/dist/browser/tools/tanstack-ai.js +3 -3
  22. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  23. package/dist/{browser-D9RNpJuT.d.ts → browser-C9T74n4c.d.ts} +302 -95
  24. package/dist/browser-tool-DOqT1oSD.js +360 -0
  25. package/dist/browser-tool-DOqT1oSD.js.map +1 -0
  26. package/dist/{browser-tool-BhjCcNVE.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
  27. package/dist/capability-DBAKc6UZ.js.map +1 -1
  28. package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
  29. package/dist/chat/index.d.ts +37 -6
  30. package/dist/chat/index.js +39 -3
  31. package/dist/chat/index.js.map +1 -1
  32. package/dist/chat/react.js +1 -0
  33. package/dist/chat/react.js.map +1 -1
  34. package/dist/chat-sdk/index.d.ts +3 -3
  35. package/dist/chat-sdk/index.js +1 -1
  36. package/dist/cli.js +62 -60
  37. package/dist/client-CkT8voRY.js +3740 -0
  38. package/dist/client-CkT8voRY.js.map +1 -0
  39. package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
  40. package/dist/client.d.ts +1 -1
  41. package/dist/{connector-CM-uuxKM.js → connector-Bphz6wIw.js} +414 -3
  42. package/dist/connector-Bphz6wIw.js.map +1 -0
  43. package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
  44. package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
  45. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  46. package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
  47. package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
  48. package/dist/experimental/channels/index.d.ts +2 -2
  49. package/dist/experimental/channels/web/index.d.ts +2 -2
  50. package/dist/experimental/channels/web/index.js +1 -1
  51. package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
  52. package/dist/harness/ai-sdk/index.d.ts +2 -2
  53. package/dist/harness/container/index.d.ts +2 -2
  54. package/dist/harness/container/index.js +1 -1
  55. package/dist/harness/container/index.js.map +1 -1
  56. package/dist/harness/opencode/index.d.ts +1 -1
  57. package/dist/harness/pi/index.d.ts +200 -37
  58. package/dist/harness/pi/index.js +202 -100
  59. package/dist/harness/pi/index.js.map +1 -1
  60. package/dist/harness/think/index.d.ts +2 -2
  61. package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
  62. package/dist/images-D4gtE06D.js.map +1 -0
  63. package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
  64. package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
  65. package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
  66. package/dist/index.d.ts +21 -21
  67. package/dist/index.js +2 -2
  68. package/dist/{input-schema-BQykTEp_.js → input-schema-D6GilRXI.js} +3 -3
  69. package/dist/input-schema-D6GilRXI.js.map +1 -0
  70. package/dist/{input-schema-B0Etuo-o.js → input-schema-y8W5bOdM.js} +3 -3
  71. package/dist/input-schema-y8W5bOdM.js.map +1 -0
  72. package/dist/internal_context.d.ts +1 -1
  73. package/dist/lifecycle/index.d.ts +3 -3
  74. package/dist/lifecycle/index.js +1 -1
  75. package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
  76. package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
  77. package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
  78. package/dist/mcp/client/do-oauth-client-provider.js +45 -2
  79. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
  80. package/dist/mcp/client/index.d.ts +42 -36
  81. package/dist/mcp/client/index.js +2 -2
  82. package/dist/mcp/index.d.ts +16 -16
  83. package/dist/mcp/index.js +2 -2
  84. package/dist/models/ai-sdk/index.d.ts +9 -5
  85. package/dist/models/ai-sdk/index.js +1 -1
  86. package/dist/models/opencode/index.d.ts +3 -3
  87. package/dist/models/opencode/index.js +2 -2
  88. package/dist/models/opencode/index.js.map +1 -1
  89. package/dist/models/pi-ai/index.d.ts +4 -4
  90. package/dist/models/pi-ai/index.js +64 -170
  91. package/dist/models/pi-ai/index.js.map +1 -1
  92. package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
  93. package/dist/queue/index.d.ts +1 -1
  94. package/dist/queue/index.js +1 -1
  95. package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
  96. package/dist/queue-B_wl6K0Z.js.map +1 -0
  97. package/dist/react.d.ts +2 -2
  98. package/dist/routing/index.d.ts +2 -2
  99. package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
  100. package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
  101. package/dist/scheduler-DGNEmxQR.js.map +1 -0
  102. package/dist/schedules/index.d.ts +1 -1
  103. package/dist/schedules/index.js +1 -1
  104. package/dist/serializable.d.ts +1 -1
  105. package/dist/{session-7CDgVE0z.js → session-CRY0bGiI.js} +423 -411
  106. package/dist/session-CRY0bGiI.js.map +1 -0
  107. package/dist/sessions/index.d.ts +1 -1
  108. package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
  109. package/dist/settings-D2F_qONv.js.map +1 -0
  110. package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
  111. package/dist/src-BO1FdLK1.js.map +1 -0
  112. package/dist/state/index.d.ts +1 -1
  113. package/dist/streams/index.d.ts +1 -1
  114. package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
  115. package/dist/sub-routing.d.ts +12 -12
  116. package/dist/tasks/index.d.ts +1 -1
  117. package/dist/tasks/index.js +1 -1
  118. package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
  119. package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
  120. package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
  121. package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
  122. package/dist/tool-CmAGY6Fo.js.map +1 -0
  123. package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
  124. package/dist/tool-Kxcj8_22.js.map +1 -0
  125. package/dist/{tool-helpers-BI7ifO2S.js → tool-helpers-F3_Wy2YX.js} +2 -2
  126. package/dist/{tool-helpers-BI7ifO2S.js.map → tool-helpers-F3_Wy2YX.js.map} +1 -1
  127. package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
  128. package/dist/voice/index.d.ts +2 -2
  129. package/dist/web/fetch/index.js +1 -1
  130. package/dist/web/fetch/tools/ai-sdk.js +2 -2
  131. package/dist/web/fetch/tools/pi.d.ts +9 -7
  132. package/dist/web/fetch/tools/pi.js +31 -7
  133. package/dist/web/fetch/tools/pi.js.map +1 -1
  134. package/dist/web/fetch/tools/tanstack-ai.js +2 -2
  135. package/dist/web/search/index.js +1 -1
  136. package/dist/web/search/tools/ai-sdk.js +2 -2
  137. package/dist/web/search/tools/pi.d.ts +9 -4
  138. package/dist/web/search/tools/pi.js +27 -11
  139. package/dist/web/search/tools/pi.js.map +1 -1
  140. package/dist/web/search/tools/tanstack-ai.js +2 -2
  141. package/dist/websockets/index.d.ts +2 -2
  142. package/dist/websockets/index.js +1 -1
  143. package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
  144. package/dist/websockets-W4uhRg4-.js.map +1 -0
  145. package/dist/workflow-types.d.ts +1 -1
  146. package/dist/workflows.d.ts +1 -1
  147. package/docs/agent-class.md +30 -4
  148. package/docs/browse-the-web.md +50 -3
  149. package/docs/chat-agents.md +13 -10
  150. package/docs/client-tools-continuation.md +1 -1
  151. package/docs/codemode.md +1 -1
  152. package/docs/configuration.md +6 -3
  153. package/docs/cross-domain-authentication.md +1 -1
  154. package/docs/fetch-the-web.md +20 -0
  155. package/docs/harnesses/pi.md +242 -33
  156. package/docs/harnesses/think.md +1 -1
  157. package/docs/http-websockets.md +40 -32
  158. package/docs/human-in-the-loop.md +2 -2
  159. package/docs/lifecycle.md +56 -0
  160. package/docs/mcp-client.md +104 -7
  161. package/docs/models-pi-ai.md +24 -10
  162. package/docs/models.md +42 -17
  163. package/docs/resumable-streaming.md +1 -1
  164. package/docs/retries.md +3 -6
  165. package/docs/search-the-web.md +10 -0
  166. package/docs/voice.md +1 -1
  167. package/package.json +16 -9
  168. package/dist/ai-sdk-Kon40i0q.js.map +0 -1
  169. package/dist/browser-1eUbPvC2.js +0 -931
  170. package/dist/browser-1eUbPvC2.js.map +0 -1
  171. package/dist/browser-tool-DRan7Lk6.js +0 -497
  172. package/dist/browser-tool-DRan7Lk6.js.map +0 -1
  173. package/dist/client-DMWujQJ1.js +0 -2325
  174. package/dist/client-DMWujQJ1.js.map +0 -1
  175. package/dist/connector-CM-uuxKM.js.map +0 -1
  176. package/dist/images-CfuRCjwq.js.map +0 -1
  177. package/dist/input-schema-B0Etuo-o.js.map +0 -1
  178. package/dist/input-schema-BQykTEp_.js.map +0 -1
  179. package/dist/lifecycle-v1rKHV2C.js.map +0 -1
  180. package/dist/queue-CcIjVYTE.js.map +0 -1
  181. package/dist/scheduler-FIHv2-kJ.js.map +0 -1
  182. package/dist/session-7CDgVE0z.js.map +0 -1
  183. package/dist/settings-Dk2il2Hf.js.map +0 -1
  184. package/dist/src-DoGNJ4Ud.js.map +0 -1
  185. package/dist/tool-CxKsvxjm.js.map +0 -1
  186. package/dist/tool-DkT_DJBm.js.map +0 -1
  187. package/dist/websockets-C6SJtWCJ.js.map +0 -1
@@ -1,9 +1,9 @@
1
- import { u as MAX_WEB_SEARCH_QUERY_LENGTH } from "./tool-DkT_DJBm.js";
1
+ import { u as MAX_WEB_SEARCH_QUERY_LENGTH } from "./tool-CmAGY6Fo.js";
2
2
  import { z } from "zod";
3
3
  //#region src/web/search/tools/input-schema.ts
4
4
  /**
5
5
  * The zod input schema shared by the AI SDK and TanStack AI adapters. Kept
6
- * out of the core so the pi adapter, which uses TypeBox, does not need zod.
6
+ * out of the core so the pi adapter, which uses pi-schema, does not need zod.
7
7
  * Internal — not an entry point.
8
8
  */
9
9
  /**
@@ -20,4 +20,4 @@ function webSearchInputSchema(maxLimit) {
20
20
  //#endregion
21
21
  export { webSearchInputSchema as t };
22
22
 
23
- //# sourceMappingURL=input-schema-B0Etuo-o.js.map
23
+ //# sourceMappingURL=input-schema-y8W5bOdM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"input-schema-y8W5bOdM.js","names":[],"sources":["../src/web/search/tools/input-schema.ts"],"sourcesContent":["/**\n * The zod input schema shared by the AI SDK and TanStack AI adapters. Kept\n * out of the core so the pi adapter, which uses pi-schema, does not need zod.\n * Internal — not an entry point.\n */\nimport { z } from \"zod\";\nimport {\n MAX_WEB_SEARCH_QUERY_LENGTH,\n type WebSearchToolInput\n} from \"../contract\";\n\n/**\n * The model's input schema. The description tells the model the host's\n * `limit`; a larger value is not rejected (which would cost a validation\n * round trip) but capped by the core.\n */\nexport function webSearchInputSchema(maxLimit: number) {\n return z.object({\n query: z\n .string()\n .min(1)\n .max(MAX_WEB_SEARCH_QUERY_LENGTH)\n .describe(\"What to search for.\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(`How many results to return (at most ${maxLimit}).`)\n }) satisfies z.ZodType<WebSearchToolInput>;\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAgB,qBAAqB,UAAkB;CACrD,OAAO,EAAE,OAAO;EACd,OAAO,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,IAAI,2BAA2B,CAAC,CAChC,SAAS,qBAAqB;EACjC,OAAO,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,SAAS,uCAAuC,SAAS,GAAG;CACjE,CAAC;AACH"}
@@ -2,7 +2,7 @@ import {
2
2
  i as __DO_NOT_USE_WILL_BREAK__agentContext,
3
3
  n as CurrentAgentContext,
4
4
  t as AgentContextStore
5
- } from "./current-agent-CKgT5d1O.js";
5
+ } from "./current-agent-DShbQHDO.js";
6
6
  import { t as AgentEmail } from "./internal_context-BlxFEWfn.js";
7
7
  export {
8
8
  type AgentContextStore,
@@ -24,16 +24,16 @@ import {
24
24
  w as ConnectionState,
25
25
  x as Connection,
26
26
  y as LifecycleJobPushOptions
27
- } from "../capability-runner-BiVUtjqC.js";
27
+ } from "../capability-runner-uFOdSANC.js";
28
28
  import {
29
29
  n as LifecycleOptions,
30
30
  t as Lifecycle
31
- } from "../durable-object-lifecycle-DOI_bzCH.js";
31
+ } from "../durable-object-lifecycle-CRCA6O0W.js";
32
32
  import {
33
33
  a as getCurrentAgent,
34
34
  n as CurrentAgentContext,
35
35
  r as LifecycleObject
36
- } from "../current-agent-CKgT5d1O.js";
36
+ } from "../current-agent-DShbQHDO.js";
37
37
  export {
38
38
  type CapabilityRequestContext,
39
39
  type CapabilityStartContext,
@@ -1,4 +1,4 @@
1
1
  import { n as getCurrentAgent } from "../current-agent-DhoDkSnH.js";
2
2
  import { t as LifecycleCapability } from "../capability-DBAKc6UZ.js";
3
- import { t as Lifecycle } from "../lifecycle-v1rKHV2C.js";
3
+ import { t as Lifecycle } from "../lifecycle-CB5Dmtrt.js";
4
4
  export { Lifecycle, LifecycleCapability, getCurrentAgent };
@@ -215,6 +215,7 @@ function isHungRow(row, nowMs) {
215
215
  }
216
216
  var _storage = /* @__PURE__ */ new WeakMap();
217
217
  var _tableEnsured = /* @__PURE__ */ new WeakMap();
218
+ var _inFlight = /* @__PURE__ */ new WeakMap();
218
219
  var _JobQueue_brand = /* @__PURE__ */ new WeakSet();
219
220
  /**
220
221
  * @internal SQL-backed job queue. Lifecycle owns the single instance; the
@@ -225,8 +226,43 @@ var JobQueue = class {
225
226
  _classPrivateMethodInitSpec(this, _JobQueue_brand);
226
227
  _classPrivateFieldInitSpec(this, _storage, void 0);
227
228
  _classPrivateFieldInitSpec(this, _tableEnsured, false);
229
+ _classPrivateFieldInitSpec(this, _inFlight, /* @__PURE__ */ new Map());
228
230
  _classPrivateFieldSet2(_storage, this, storage);
229
231
  }
232
+ /**
233
+ * Claim a due job for one dispatch: mark it running and record its
234
+ * revision. A takeover of a hung job first invalidates the dispatches
235
+ * still holding it. Release the claim when the dispatch ends.
236
+ */
237
+ claim(id, nowMs, takeover = false) {
238
+ let entry = _classPrivateFieldGet2(_inFlight, this).get(id);
239
+ if (!entry) {
240
+ entry = {
241
+ revision: 0,
242
+ dispatches: 0
243
+ };
244
+ _classPrivateFieldGet2(_inFlight, this).set(id, entry);
245
+ } else if (takeover) entry.revision += 1;
246
+ entry.dispatches += 1;
247
+ this.markRunning(id, nowMs);
248
+ return {
249
+ id,
250
+ entry,
251
+ revision: entry.revision
252
+ };
253
+ }
254
+ /** End one dispatch's claim. */
255
+ release(claim) {
256
+ claim.entry.dispatches -= 1;
257
+ if (claim.entry.dispatches === 0 && _classPrivateFieldGet2(_inFlight, this).get(claim.id) === claim.entry) _classPrivateFieldGet2(_inFlight, this).delete(claim.id);
258
+ }
259
+ /**
260
+ * Whether the job still exists as the dispatch claimed it: no cancel,
261
+ * push, reschedule, breaker retime or hung takeover touched it since.
262
+ */
263
+ isCurrent(claim) {
264
+ return _classPrivateFieldGet2(_inFlight, this).get(claim.id) === claim.entry && claim.entry.revision === claim.revision && _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "SELECT id FROM cf_agents_jobs WHERE id = ?", claim.id).length > 0;
265
+ }
230
266
  push(capability, options) {
231
267
  if (!Number.isFinite(options.time) || options.time < 0) throw new Error(`Invalid job time: ${String(options.time)}`);
232
268
  if (typeof options.fn !== "string" || options.fn.trim() === "") throw new Error("Jobs require a non-empty fn");
@@ -249,6 +285,7 @@ var JobQueue = class {
249
285
  execution_started_at = NULL
250
286
  WHERE cf_agents_jobs.capability = excluded.capability`, id, capability, options.fn, Math.floor(options.time), options.payload === void 0 ? null : JSON.stringify(options.payload), options.retry ? JSON.stringify(options.retry) : null, options.singleflight ? 1 : 0, options.hungTimeoutSeconds ?? null, options.exclusive ? 1 : 0, options.recoveryLoop ? 1 : 0);
251
287
  const job = this.get(capability, id);
288
+ if (job) _assertClassBrand(_JobQueue_brand, this, _revise).call(this, id);
252
289
  if (!job) {
253
290
  const owner = _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "SELECT capability FROM cf_agents_jobs WHERE id = ?", id)[0]?.capability;
254
291
  throw new Error(owner !== void 0 ? `Job id ${JSON.stringify(id)} already belongs to ${JSON.stringify(owner)}; job ids are scoped to their owner` : `Failed to persist job ${id}`);
@@ -257,12 +294,14 @@ var JobQueue = class {
257
294
  }
258
295
  cancel(capability, id) {
259
296
  if (_assertClassBrand(_JobQueue_brand, this, _sql).call(this, "SELECT id FROM cf_agents_jobs WHERE id = ? AND capability = ?", id, capability).length === 0) return false;
297
+ _assertClassBrand(_JobQueue_brand, this, _revise).call(this, id);
260
298
  _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "DELETE FROM cf_agents_jobs WHERE id = ? AND capability = ?", id, capability);
261
299
  return true;
262
300
  }
263
301
  reschedule(capability, id, time) {
264
302
  if (!Number.isFinite(time) || time < 0) throw new Error(`Invalid job time: ${String(time)}`);
265
303
  if (_assertClassBrand(_JobQueue_brand, this, _sql).call(this, "SELECT id FROM cf_agents_jobs WHERE id = ? AND capability = ?", id, capability).length === 0) return false;
304
+ _assertClassBrand(_JobQueue_brand, this, _revise).call(this, id);
266
305
  _assertClassBrand(_JobQueue_brand, this, _sql).call(this, `UPDATE cf_agents_jobs
267
306
  SET time = ?, running = 0, execution_started_at = NULL
268
307
  WHERE id = ? AND capability = ?`, Math.floor(time), id, capability);
@@ -294,15 +333,16 @@ var JobQueue = class {
294
333
  WHERE id = ?`, id);
295
334
  }
296
335
  delete(id) {
336
+ _assertClassBrand(_JobQueue_brand, this, _revise).call(this, id);
297
337
  _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "DELETE FROM cf_agents_jobs WHERE id = ?", id);
298
338
  }
299
339
  /**
300
- * Unguarded retime for the alarm memory-limit breaker's backoff: the
301
- * platform-failure path clears the dispatch marker before the breaker
302
- * runs, so the guarded {@link applyOutcome} would no-op — and the
303
- * breaker's backoff must land regardless, it is protecting the object.
340
+ * Unguarded retime for the alarm memory-limit breaker's backoff, which
341
+ * must land regardless of any dispatch: it is protecting the object. It
342
+ * bumps the revision, so no dispatch's drive result overrides it.
304
343
  */
305
344
  retime(id, time) {
345
+ _assertClassBrand(_JobQueue_brand, this, _revise).call(this, id);
306
346
  _assertClassBrand(_JobQueue_brand, this, _sql).call(this, `UPDATE cf_agents_jobs
307
347
  SET time = ?, running = 0, execution_started_at = NULL
308
348
  WHERE id = ?`, Math.floor(time), id);
@@ -311,9 +351,10 @@ var JobQueue = class {
311
351
  * Back off every pending recovery-loop job that would fire before the
312
352
  * breaker's backoff time (#1825), so a doomed loop's sibling rows cannot
313
353
  * re-trigger it on the next wake. Unguarded like {@link retime}: the
314
- * breaker's backoff must land regardless of dispatch markers.
354
+ * breaker's backoff must land regardless of any dispatch.
315
355
  */
316
356
  delayRecoveryLoopJobs(time) {
357
+ for (const { id } of _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "SELECT id FROM cf_agents_jobs WHERE recovery_loop = 1 AND time <= ?", Math.floor(time))) _assertClassBrand(_JobQueue_brand, this, _revise).call(this, id);
317
358
  _assertClassBrand(_JobQueue_brand, this, _sql).call(this, `UPDATE cf_agents_jobs
318
359
  SET time = ?, running = 0, execution_started_at = NULL
319
360
  WHERE recovery_loop = 1 AND time <= ?`, Math.floor(time), Math.floor(time));
@@ -331,18 +372,22 @@ var JobQueue = class {
331
372
  * budget (#1825). Unrelated jobs are untouched.
332
373
  */
333
374
  purgeRecoveryLoopJobs() {
375
+ for (const { id } of _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "SELECT id FROM cf_agents_jobs WHERE recovery_loop = 1")) _assertClassBrand(_JobQueue_brand, this, _revise).call(this, id);
334
376
  _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "DELETE FROM cf_agents_jobs WHERE recovery_loop = 1");
335
377
  }
336
378
  /**
337
- * Apply one drive result, guarded on the dispatch marker: every driven
338
- * job carries `running = 1` for the duration of its dispatch, and a
339
- * same-id `push()` or `reschedule()` made meanwhile clears it. A cleared
340
- * marker means newer durable intent exists, so the outcome quietly
341
- * defers to it instead of deleting or retiming the fresher job.
379
+ * Apply one drive result, guarded on the revision the dispatch claimed
380
+ * the job at. A cancel, same-id push or reschedule made meanwhile bumped
381
+ * it: newer durable intent exists, so the outcome quietly defers to it
382
+ * instead of deleting or retiming the fresher job. Another dispatch of
383
+ * the same unchanged job (overlapping alarms) does not bump it, so either
384
+ * dispatch's result applies.
342
385
  */
343
- applyOutcome(id, outcome) {
386
+ applyOutcome(claim, outcome) {
387
+ if (!this.isCurrent(claim)) return;
388
+ const { id } = claim;
344
389
  if (outcome === void 0) {
345
- _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "DELETE FROM cf_agents_jobs WHERE id = ? AND running = 1", id);
390
+ _assertClassBrand(_JobQueue_brand, this, _sql).call(this, "DELETE FROM cf_agents_jobs WHERE id = ?", id);
346
391
  return;
347
392
  }
348
393
  if (outcome === "yield") {
@@ -352,7 +397,7 @@ var JobQueue = class {
352
397
  if (typeof outcome === "object" && Number.isFinite(outcome.rescheduleAt) && outcome.rescheduleAt >= 0) {
353
398
  _assertClassBrand(_JobQueue_brand, this, _sql).call(this, `UPDATE cf_agents_jobs
354
399
  SET time = ?, running = 0, execution_started_at = NULL
355
- WHERE id = ? AND running = 1`, Math.floor(outcome.rescheduleAt), id);
400
+ WHERE id = ?`, Math.floor(outcome.rescheduleAt), id);
356
401
  return;
357
402
  }
358
403
  throw new Error(`Invalid job outcome for ${id}`);
@@ -413,6 +458,10 @@ function _ensureTable() {
413
458
  ) WITHOUT ROWID`);
414
459
  _classPrivateFieldSet2(_tableEnsured, this, true);
415
460
  }
461
+ function _revise(id) {
462
+ const entry = _classPrivateFieldGet2(_inFlight, this).get(id);
463
+ if (entry) entry.revision += 1;
464
+ }
416
465
  //#endregion
417
466
  //#region src/lifecycle/job-driver.ts
418
467
  /**
@@ -443,6 +492,8 @@ const JOB_BACKLOG_WARNING_THRESHOLD = 10;
443
492
  * isolate death mid-drive still wakes this object to resume its queue.
444
493
  */
445
494
  const DEADMAN_ALARM_DELAY_MS = 3e4;
495
+ /** A retry found its job cancelled or replaced, so it did not run. */
496
+ const SUPERSEDED = Symbol("superseded");
446
497
  /**
447
498
  * Carries the row a platform failure escaped from out to `runAlarm`'s catch,
448
499
  * across the rethrow from `#driveJob`. Attribution must not live in a shared
@@ -596,20 +647,27 @@ async function _driveDueJobs() {
596
647
  if (_classPrivateFieldGet2(_options, this).disabled()) return;
597
648
  const row = _classPrivateFieldGet2(_options, this).queue.dueRow(stale.id, nowMs);
598
649
  if (!row) continue;
650
+ let takeover = false;
599
651
  if (row.singleflight === 1 && row.running === 1) {
600
652
  if (!isHungRow(row, nowMs)) {
601
653
  console.warn(`Skipping job ${row.id}: previous execution still running`);
602
654
  continue;
603
655
  }
604
656
  console.warn(`Forcing reset of hung job ${row.id} (started ${Math.round((nowMs - (row.execution_started_at ?? 0)) / 1e3)}s ago)`);
657
+ takeover = true;
658
+ }
659
+ const claim = _classPrivateFieldGet2(_options, this).queue.claim(row.id, nowMs, takeover);
660
+ try {
661
+ await _assertClassBrand(_JobDriver_brand, this, _driveJob).call(this, row, claim);
662
+ } finally {
663
+ _classPrivateFieldGet2(_options, this).queue.release(claim);
605
664
  }
606
- _classPrivateFieldGet2(_options, this).queue.markRunning(row.id, nowMs);
607
- await _assertClassBrand(_JobDriver_brand, this, _driveJob).call(this, row);
608
665
  }
609
666
  }
610
667
  /** Dispatch one due row to its owner with retry and failure policy. */
611
- async function _driveJob(row) {
668
+ async function _driveJob(row, claim) {
612
669
  const { queue, resolveDispatch, disabled } = _classPrivateFieldGet2(_options, this);
670
+ const owned = () => queue.isCurrent(claim);
613
671
  const job = jobFromRow(row);
614
672
  const dispatch = await resolveDispatch(row.capability);
615
673
  if (!dispatch) {
@@ -632,10 +690,13 @@ async function _driveJob(row) {
632
690
  }, hungTimeoutMs(row));
633
691
  let outcome;
634
692
  try {
635
- outcome = await _classPrivateFieldGet2(_alarmScope, this).run({ executing: row }, () => tryN(maxAttempts, (attempt) => dispatch.onJob({
636
- job,
637
- attempt
638
- }), {
693
+ outcome = await _classPrivateFieldGet2(_alarmScope, this).run({ executing: row }, () => tryN(maxAttempts, async (attempt) => {
694
+ if (attempt > 1 && !owned()) return SUPERSEDED;
695
+ return dispatch.onJob({
696
+ job,
697
+ attempt
698
+ });
699
+ }, {
639
700
  baseDelayMs: job.retry?.baseDelayMs ?? DEFAULT_JOB_RETRY.baseDelayMs,
640
701
  maxDelayMs: job.retry?.maxDelayMs ?? DEFAULT_JOB_RETRY.maxDelayMs,
641
702
  shouldRetry: (error) => !isDurableObjectCodeUpdateReset(error) && !isDurableObjectMemoryLimitReset(error)
@@ -644,7 +705,7 @@ async function _driveJob(row) {
644
705
  if (disabled()) return;
645
706
  if (isPlatformFailure(error)) {
646
707
  try {
647
- queue.clearRunning(row.id);
708
+ if (owned()) queue.clearRunning(row.id);
648
709
  } catch {}
649
710
  console.warn(`Deferring job ${row.id} to a fresh invocation after a platform failure; the job is preserved.`);
650
711
  throw new AttributedPlatformFailure(row, error);
@@ -661,7 +722,8 @@ async function _driveJob(row) {
661
722
  clearTimeout(slowWatchdog);
662
723
  }
663
724
  if (disabled()) return;
664
- queue.applyOutcome(row.id, outcome ?? void 0);
725
+ if (outcome === SUPERSEDED) return;
726
+ queue.applyOutcome(claim, outcome ?? void 0);
665
727
  }
666
728
  function _warnBacklog(due) {
667
729
  const counts = /* @__PURE__ */ new Map();
@@ -834,6 +896,21 @@ function decodeProps(header) {
834
896
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
835
897
  return JSON.parse(new TextDecoder().decode(bytes));
836
898
  }
899
+ /**
900
+ * The response to a failed `fetch` when the host's `onFetchError` gives none.
901
+ * It never carries the error: its message and stack can reveal internals to
902
+ * callers that are not authenticated.
903
+ */
904
+ function defaultFetchErrorResponse(request) {
905
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return new Response("Internal Server Error", { status: 500 });
906
+ const pair = new WebSocketPair();
907
+ pair[1].accept();
908
+ pair[1].close(1011, "Uncaught exception during session setup");
909
+ return new Response(null, {
910
+ status: 101,
911
+ webSocket: pair[0]
912
+ });
913
+ }
837
914
  const lifecycleEventSinks = /* @__PURE__ */ new WeakMap();
838
915
  const lifecycleRouteTransports = /* @__PURE__ */ new WeakMap();
839
916
  const lifecycleHostInvokers = /* @__PURE__ */ new WeakMap();
@@ -1054,18 +1131,8 @@ var Lifecycle = class Lifecycle {
1054
1131
  return new Response("WebSocket upgrades are not enabled on this Durable Object. Install a capability that claims them (e.g. WebSockets).", { status: 404 });
1055
1132
  }
1056
1133
  } catch (err) {
1057
- console.error(`Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} fetch:`, err);
1058
- if (!(err instanceof Error)) throw err;
1059
- if (request.headers.get("Upgrade") === "websocket") {
1060
- const pair = new WebSocketPair();
1061
- pair[1].accept();
1062
- pair[1].send(JSON.stringify({ error: err.stack }));
1063
- pair[1].close(1011, "Uncaught exception during session setup");
1064
- return new Response(null, {
1065
- status: 101,
1066
- webSocket: pair[0]
1067
- });
1068
- } else return new Response(err.stack, { status: 500 });
1134
+ console.error(_assertClassBrand(_Lifecycle_brand, this, _errorLogPrefix).call(this, "fetch"), err);
1135
+ return _assertClassBrand(_Lifecycle_brand, this, _respondToFetchError).call(this, request, err);
1069
1136
  }
1070
1137
  }
1071
1138
  /** @internal Dispatch a hibernating WebSocket message. */
@@ -1074,7 +1141,7 @@ var Lifecycle = class Lifecycle {
1074
1141
  await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
1075
1142
  await runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).webSocketMessage(ws, message));
1076
1143
  } catch (e) {
1077
- console.error(`Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} webSocketMessage:`, e);
1144
+ console.error(_assertClassBrand(_Lifecycle_brand, this, _errorLogPrefix).call(this, "webSocketMessage"), e);
1078
1145
  }
1079
1146
  }
1080
1147
  /** @internal Dispatch a hibernating WebSocket close. */
@@ -1083,7 +1150,7 @@ var Lifecycle = class Lifecycle {
1083
1150
  await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
1084
1151
  await runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).webSocketClose(ws, code, reason, wasClean));
1085
1152
  } catch (e) {
1086
- console.error(`Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} webSocketClose:`, e);
1153
+ console.error(_assertClassBrand(_Lifecycle_brand, this, _errorLogPrefix).call(this, "webSocketClose"), e);
1087
1154
  }
1088
1155
  }
1089
1156
  /** @internal Dispatch a hibernating WebSocket error. */
@@ -1093,7 +1160,7 @@ var Lifecycle = class Lifecycle {
1093
1160
  await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
1094
1161
  await runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).webSocketError(ws, error));
1095
1162
  } catch (e) {
1096
- console.error(`Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} webSocketError:`, e);
1163
+ console.error(_assertClassBrand(_Lifecycle_brand, this, _errorLogPrefix).call(this, "webSocketError"), e);
1097
1164
  }
1098
1165
  }
1099
1166
  /**
@@ -1298,6 +1365,27 @@ function _reportEventSinkFailure(event, error) {
1298
1365
  function _deliverPendingEvents() {
1299
1366
  for (const event of _classPrivateFieldGet2(_pendingEvents, this).splice(0)) _assertClassBrand(_Lifecycle_brand, this, _publishCapabilityEvent).call(this, event);
1300
1367
  }
1368
+ /** The prefix for an error logged from one of this object's handlers. */
1369
+ function _errorLogPrefix(handler) {
1370
+ return `Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} ${handler}:`;
1371
+ }
1372
+ /**
1373
+ * Answer a failed `fetch`: the host's `onFetchError` response if it gives
1374
+ * one, otherwise a default that never carries the error.
1375
+ */
1376
+ async function _respondToFetchError(request, error) {
1377
+ if (_classPrivateFieldGet2(_host, this).onFetchError) try {
1378
+ const response = await runInLifecycleHostContext({
1379
+ host: _classPrivateFieldGet2(_host, this),
1380
+ request
1381
+ }, () => _classPrivateFieldGet2(_host, this).onFetchError(request, error));
1382
+ if (response instanceof Response) return response;
1383
+ } catch (hookError) {
1384
+ console.error(_assertClassBrand(_Lifecycle_brand, this, _errorLogPrefix).call(this, "onFetchError"), hookError);
1385
+ }
1386
+ if (!(error instanceof Error)) throw error;
1387
+ return defaultFetchErrorResponse(request);
1388
+ }
1301
1389
  function _ensureInitialized() {
1302
1390
  if (_classPrivateFieldGet2(_status, this) === "started") return Promise.resolve();
1303
1391
  if (_classPrivateFieldGet2(_startup, this) === void 0) {
@@ -1386,4 +1474,4 @@ async function _resolveJobDispatch(owner) {
1386
1474
  //#endregion
1387
1475
  export { abortWithoutAlarmRetry as a, setLifecycleRouteTransport as i, setLifecycleEventSink as n, setLifecycleHostInvoker as r, Lifecycle as t };
1388
1476
 
1389
- //# sourceMappingURL=lifecycle-v1rKHV2C.js.map
1477
+ //# sourceMappingURL=lifecycle-CB5Dmtrt.js.map