@howaboua/pi-durable-worker-code 0.11.0 → 0.13.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.
@@ -15,11 +15,11 @@ import {
15
15
  import { Type as Type2 } from "typebox";
16
16
 
17
17
  // packages/execution/src/cell-tools.ts
18
- import { copyJson as copyJson5 } from "@earendil-works/chord";
19
18
  import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
19
+ import { copyJson as copyJson5 } from "@earendil-works/chord/json";
20
20
 
21
21
  // packages/execution/src/forwarding.ts
22
- import { copyJson as copyJson2 } from "@earendil-works/chord";
22
+ import { copyJson as copyJson2 } from "@earendil-works/chord/json";
23
23
  import {
24
24
  LiveDoc,
25
25
  NestedCallDoc,
@@ -29,7 +29,7 @@ import {
29
29
  // packages/execution/src/invocation-state.ts
30
30
  import {
31
31
  copyJson
32
- } from "@earendil-works/chord";
32
+ } from "@earendil-works/chord/json";
33
33
  import {
34
34
  defineDoc
35
35
  } from "@earendil-works/pi-durable";
@@ -471,26 +471,53 @@ async function captureNativeCalls(tx, conversationId, owner, cellId) {
471
471
  }
472
472
 
473
473
  // packages/execution/src/invocation.ts
474
- import { copyJson as copyJson4 } from "@earendil-works/chord";
475
474
  import { awaitWithContext } from "@earendil-works/chord/context";
475
+ import { copyJson as copyJson4 } from "@earendil-works/chord/json";
476
+ import {
477
+ NestedCallDoc as NestedCallDoc3
478
+ } from "@earendil-works/pi-durable";
479
+ import { equal } from "@earendil-works/pi-schema";
476
480
 
477
481
  // packages/execution/src/native-tools.ts
478
- import { copyJson as copyJson3 } from "@earendil-works/chord";
479
- import { withoutAbortSignal } from "@earendil-works/chord/context";
482
+ import {
483
+ withoutAbortSignal
484
+ } from "@earendil-works/chord/context";
485
+ import { copyJson as copyJson3 } from "@earendil-works/chord/json";
480
486
  import {
481
487
  LiveDoc as LiveDoc2,
482
488
  NestedCallDoc as NestedCallDoc2,
483
- ToolTask as ToolTask2
489
+ ToolTask as ToolTask3
484
490
  } from "@earendil-works/pi-durable";
485
491
  import { Equal } from "typebox/value";
486
- function nativeToolCalls(runtime, callId, replay, assertLive, context) {
492
+
493
+ // packages/execution/src/tool-origin.ts
494
+ import {
495
+ defineDoc as defineDoc2,
496
+ ToolTask as ToolTask2
497
+ } from "@earendil-works/pi-durable";
498
+ var ToolOriginDoc = defineDoc2({
499
+ kind: "howaboua.tool-origin",
500
+ version: 1,
501
+ scope: "task",
502
+ checkpointWhen: () => false,
503
+ initial: () => ({})
504
+ });
505
+
506
+ // packages/execution/src/native-tools.ts
507
+ function assertNestedKey(key) {
508
+ if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
509
+ throw new Error("Invalid nested call or task key");
510
+ }
511
+ function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
487
512
  let sequence = 0;
488
513
  const admissions = [];
489
- const execute = async (name, args, callContext, options = {}) => {
514
+ async function execute(name, args, callContext, options = {}) {
490
515
  assertLive();
516
+ if (options.key !== undefined)
517
+ assertNestedKey(options.key);
518
+ else if (resumed)
519
+ throw new Error("Nested calls require an explicit key after waking");
491
520
  const key = options.key ?? String(++sequence);
492
- if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
493
- throw new Error("Invalid nested call key");
494
521
  const call = {
495
522
  type: "toolCall",
496
523
  id: `${callId}/${key}`,
@@ -502,11 +529,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
502
529
  const admission = runtime.commit(async (tx) => {
503
530
  const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
504
531
  if (slot.taskId !== undefined) {
505
- const input = (await tx.task(slot.taskId))?.input;
532
+ const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
506
533
  if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
507
534
  throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
508
535
  } else {
509
- slot.taskId = await tx.createTask(ToolTask2, {
536
+ slot.kind = "nested";
537
+ slot.taskId = await tx.createTask(ToolTask3, {
510
538
  kind: "nested",
511
539
  parent: runtime.taskId,
512
540
  parentCallId: callId,
@@ -518,6 +546,9 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
518
546
  abandonOnRestart: replay !== "safe"
519
547
  });
520
548
  const live = await tx.doc(LiveDoc2, runtime.conversationId);
549
+ const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
550
+ if (origin)
551
+ (await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
521
552
  live.nestedTools ??= [];
522
553
  live.nestedTools.push({
523
554
  callId: call.id,
@@ -549,7 +580,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
549
580
  const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
550
581
  if (slot?.taskId === undefined)
551
582
  throw new Error("Nested task creation did not commit");
552
- const settled = await runtime.waitForTask(slot.taskId, callContext);
583
+ const taskId = slot.taskId;
584
+ const result = (resultContext) => readResult(name, key, taskId, resultContext);
585
+ return options.wait === false ? { taskId, result } : result(callContext);
586
+ }
587
+ async function readResult(name, key, taskId, callContext) {
588
+ assertLive();
589
+ const settled = await runtime.waitForTask(taskId, callContext);
553
590
  const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
554
591
  await runtime.commit(async (tx) => {
555
592
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
@@ -557,7 +594,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
557
594
  return;
558
595
  }, callContext);
559
596
  return result === undefined ? {
560
- taskId: slot.taskId,
597
+ taskId,
561
598
  isError: true,
562
599
  diagnostics: [
563
600
  {
@@ -567,9 +604,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
567
604
  }
568
605
  ]
569
606
  } : copyJson3(result);
570
- };
607
+ }
571
608
  return {
572
609
  execute,
610
+ async drain() {
611
+ await Promise.allSettled(admissions);
612
+ },
573
613
  async finish() {
574
614
  await Promise.allSettled(admissions);
575
615
  await cleanupNativeCalls(runtime, withoutAbortSignal(context));
@@ -577,7 +617,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
577
617
  };
578
618
  }
579
619
  async function cleanupNativeCalls(runtime, context) {
580
- await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
620
+ await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
581
621
  await runtime.commit(async (tx) => {
582
622
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
583
623
  await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
@@ -671,18 +711,6 @@ class Progress {
671
711
  }
672
712
  }
673
713
 
674
- // packages/execution/src/tool-origin.ts
675
- import {
676
- defineDoc as defineDoc2
677
- } from "@earendil-works/pi-durable";
678
- var ToolOriginDoc = defineDoc2({
679
- kind: "howaboua.tool-origin",
680
- version: 1,
681
- scope: "task",
682
- checkpointWhen: () => false,
683
- initial: () => ({})
684
- });
685
-
686
714
  // packages/execution/src/invocation.ts
687
715
  function executionError(code, message) {
688
716
  return {
@@ -694,21 +722,23 @@ function executionError(code, message) {
694
722
  function errorText(error) {
695
723
  return error instanceof Error ? error.message : String(error);
696
724
  }
697
- function createInvocation(runtime, tool, context) {
725
+ function createInvocation(runtime, tool, context, resume) {
698
726
  const limits = {
699
727
  maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
700
728
  maxLines: tool.outputLimits?.maxLines ?? 2000,
701
729
  retain: tool.outputLimits?.retain ?? "head"
702
730
  };
703
731
  const output = new OutputBuffer(limits);
704
- const diagnostics = [];
705
- let details;
732
+ const diagnostics = [
733
+ ...resume?.progress?.diagnostics ?? []
734
+ ];
735
+ let details = resume?.progress?.details;
706
736
  let ended = false;
707
737
  const assertLive = () => {
708
738
  if (ended)
709
739
  throw new Error(`Invocation ${runtime.taskId} has settled`);
710
740
  };
711
- const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
741
+ const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
712
742
  const snapshot = () => {
713
743
  const retained = output.snapshot();
714
744
  return {
@@ -737,6 +767,8 @@ function createInvocation(runtime, tool, context) {
737
767
  taskId: runtime.taskId,
738
768
  conversationId: runtime.conversationId,
739
769
  callId: `nested-${runtime.taskId}`,
770
+ wake: resume?.wake,
771
+ checkpoint: resume?.checkpoint,
740
772
  registry: runtime.registry,
741
773
  agent: runtime.agent,
742
774
  env: undefined,
@@ -757,7 +789,7 @@ function createInvocation(runtime, tool, context) {
757
789
  const retained = output.snapshot();
758
790
  return { text: retained.text, truncated: retained.droppedBytes > 0 };
759
791
  },
760
- executeTool: (...args) => native.execute(...args),
792
+ executeTool: native.execute,
761
793
  diagnostic: (value) => {
762
794
  assertLive();
763
795
  diagnostics.push(copyJson4(value, { omitUndefinedProperties: true }));
@@ -771,24 +803,44 @@ function createInvocation(runtime, tool, context) {
771
803
  committed.catch(() => {});
772
804
  await awaitWithContext(committed, detailContext);
773
805
  },
774
- commit: async (change, commitContext) => {
806
+ commit: async (change, commitContext, options) => {
775
807
  assertLive();
776
808
  let result;
777
809
  await runtime.commit(async (tx) => {
778
810
  result = await change(tx);
779
811
  return;
780
- }, commitContext);
812
+ }, commitContext, options);
781
813
  return result;
782
814
  },
783
815
  memo: runtime.memo,
784
- createTask: async (task, input, options, taskContext) => {
816
+ readSignal: runtime.readSignal,
817
+ async createTask(task, input, {
818
+ key,
819
+ ...options
820
+ }, taskContext) {
785
821
  assertLive();
822
+ if (key !== undefined)
823
+ assertNestedKey(key);
824
+ else if (resume?.wake !== undefined)
825
+ throw new Error("Child tasks require an explicit key after waking");
786
826
  let id;
787
827
  await runtime.commit(async (tx) => {
828
+ const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
829
+ if (member?.taskId !== undefined) {
830
+ const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
831
+ if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson4(input, { omitUndefinedProperties: true })))
832
+ throw new Error(`Key ${key} was already used for another call or task`);
833
+ id = member.taskId;
834
+ return;
835
+ }
788
836
  id = await tx.createTask(task, input, {
789
837
  ...options,
790
838
  ...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
791
839
  });
840
+ if (member !== undefined) {
841
+ member.kind = "task";
842
+ member.taskId = id;
843
+ }
792
844
  const source = await tx.doc(ToolOriginDoc, runtime.taskId);
793
845
  if (source.origin !== undefined)
794
846
  (await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
@@ -835,6 +887,14 @@ function createInvocation(runtime, tool, context) {
835
887
  for (const waiter of await progress.stop())
836
888
  waiter.reject(error);
837
889
  },
890
+ async park() {
891
+ ended = true;
892
+ await native.drain();
893
+ output.end();
894
+ const pending = await progress.stop();
895
+ const { output: _output, ...kept } = snapshot();
896
+ return { progress: storeResult(kept), pending };
897
+ },
838
898
  limits,
839
899
  output,
840
900
  progress
@@ -920,8 +980,8 @@ function cellTools(runtime, toolApi, registrations, nestedTask, controls, cancel
920
980
  }
921
981
 
922
982
  // packages/execution/src/cells.ts
923
- import { copyJson as copyJson10 } from "@earendil-works/chord";
924
- import { withCancel } from "@earendil-works/chord/context";
983
+ import { withCancel as withCancel2 } from "@earendil-works/chord/context";
984
+ import { copyJson as copyJson12 } from "@earendil-works/chord/json";
925
985
  import {
926
986
  defineExtension
927
987
  } from "@earendil-works/pi-durable";
@@ -965,7 +1025,7 @@ async function observeCell(kind, id, api, context, budget) {
965
1025
  }
966
1026
 
967
1027
  // packages/execution/src/cell-progress.ts
968
- import { copyJson as copyJson6 } from "@earendil-works/chord";
1028
+ import { copyJson as copyJson6 } from "@earendil-works/chord/json";
969
1029
  import {
970
1030
  LiveDoc as LiveDoc3
971
1031
  } from "@earendil-works/pi-durable";
@@ -1025,8 +1085,8 @@ async function observeCellProgress(id, api, context, budget) {
1025
1085
  }
1026
1086
 
1027
1087
  // packages/execution/src/cell-task.ts
1028
- import { copyJson as copyJson8 } from "@earendil-works/chord";
1029
1088
  import { withAbortSignal } from "@earendil-works/chord/context";
1089
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
1030
1090
  import {
1031
1091
  defineTask
1032
1092
  } from "@earendil-works/pi-durable";
@@ -1048,7 +1108,17 @@ function combineControls(controls, allowTermination = true) {
1048
1108
  }
1049
1109
 
1050
1110
  // packages/execution/src/tool-contract.ts
1051
- import { copyJson as copyJson7 } from "@earendil-works/chord";
1111
+ import { copyJson as copyJson7 } from "@earendil-works/chord/json";
1112
+
1113
+ // packages/execution/src/tool-namespaces.ts
1114
+ import { isJsonValue } from "@earendil-works/chord/json";
1115
+ function validateJsToolNamespace(tool, namespace) {
1116
+ const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
1117
+ if (!namespace || !key(namespace.name) || typeof namespace.prompt !== "string" || !namespace.prompt.trim() || !Array.isArray(namespace.methods) || !namespace.methods.length || namespace.methods.some((method) => !method || !key(method.name) || method.bind !== undefined && !key(method.bind) || method.defaults !== undefined && (!method.defaults || typeof method.defaults !== "object" || Array.isArray(method.defaults) || !isJsonValue(method.defaults))))
1118
+ throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
1119
+ }
1120
+
1121
+ // packages/execution/src/tool-contract.ts
1052
1122
  var nestedToolDiscoveryGuidance = "Tools without a shown call signature: help is required only while their current arguments are unknown. Call with no arguments and read the result before composing an operation. Reuse known arguments without repeating help. Structured discovery uses {}";
1053
1123
  function readToolContract(tool) {
1054
1124
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
@@ -1063,6 +1133,7 @@ function readToolContract(tool) {
1063
1133
  "yieldTimeMs",
1064
1134
  "inputSchema",
1065
1135
  "nativeOnly",
1136
+ "nestedHidden",
1066
1137
  "discovery"
1067
1138
  ]);
1068
1139
  for (const key of Object.keys(hints))
@@ -1086,6 +1157,12 @@ function readToolContract(tool) {
1086
1157
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1087
1158
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1088
1159
  throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
1160
+ const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
1161
+ const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
1162
+ if (jsNamespace !== undefined)
1163
+ validateJsToolNamespace(tool.name, jsNamespace);
1164
+ if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
1165
+ throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
1089
1166
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1090
1167
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1091
1168
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1102,6 +1179,8 @@ function readToolContract(tool) {
1102
1179
  inputSchema,
1103
1180
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1104
1181
  nativeOnly: nativeOnly === true,
1182
+ nestedHidden: nestedHidden === true,
1183
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1105
1184
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1106
1185
  ...outputHint === undefined ? {} : { output: outputHint },
1107
1186
  help: [
@@ -1337,7 +1416,7 @@ function createCellTask(options, nestedTask) {
1337
1416
  import {
1338
1417
  hook,
1339
1418
  LiveDoc as LiveDoc4,
1340
- ToolTask as ToolTask3
1419
+ ToolTask as ToolTask4
1341
1420
  } from "@earendil-works/pi-durable";
1342
1421
  function forwardingHook() {
1343
1422
  let host;
@@ -1347,7 +1426,7 @@ function forwardingHook() {
1347
1426
  throw new Error("Create a separate execution component for each Harness");
1348
1427
  host = harness;
1349
1428
  },
1350
- hook: hook(ToolTask3, {
1429
+ hook: hook(ToolTask4, {
1351
1430
  async beforeTool(call, api, context) {
1352
1431
  const parent = call.parent;
1353
1432
  if (parent === undefined || host === undefined)
@@ -1360,7 +1439,7 @@ function forwardingHook() {
1360
1439
  if (conversation === undefined)
1361
1440
  throw new Error("Forwarded call conversation is unavailable");
1362
1441
  await conversation.commit(async (tx) => {
1363
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1442
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1364
1443
  return;
1365
1444
  const owner = await tx.doc(InvocationDoc, api.taskId);
1366
1445
  const admission = owner.forwardingCellId === undefined;
@@ -1387,7 +1466,7 @@ function forwardingHook() {
1387
1466
  if (conversation === undefined)
1388
1467
  throw new Error("Forwarded call conversation is unavailable");
1389
1468
  await conversation.commit(async (tx) => {
1390
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1469
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1391
1470
  return;
1392
1471
  const owner = await tx.doc(InvocationDoc, api.taskId);
1393
1472
  const cellId = owner.forwardingCellId;
@@ -1412,6 +1491,7 @@ function forwardingHook() {
1412
1491
  }
1413
1492
 
1414
1493
  // packages/execution/src/nested.ts
1494
+ import { copyJson as copyJson11 } from "@earendil-works/chord/json";
1415
1495
  import {
1416
1496
  defineTask as defineTask2
1417
1497
  } from "@earendil-works/pi-durable";
@@ -1420,7 +1500,7 @@ import { compile as compile2 } from "@earendil-works/pi-schema";
1420
1500
  // packages/execution/src/nested-call.ts
1421
1501
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1422
1502
  import {
1423
- ToolTask as ToolTask4
1503
+ ToolTask as ToolTask5
1424
1504
  } from "@earendil-works/pi-durable";
1425
1505
  import { compile } from "@earendil-works/pi-schema";
1426
1506
  function nestedCall(runtime, input) {
@@ -1466,7 +1546,7 @@ function prepareNestedInput(tool, input) {
1466
1546
  async function eachHook(agent, name, api, invoke) {
1467
1547
  for (const extension of agent.extensions)
1468
1548
  for (const registration of extension.hooks ?? []) {
1469
- if (registration.task !== ToolTask4.definition.name)
1549
+ if (registration.task !== ToolTask5.definition.name)
1470
1550
  continue;
1471
1551
  const handler = registration.handlers[name];
1472
1552
  if (handler === undefined)
@@ -1481,8 +1561,120 @@ async function eachHook(agent, name, api, invoke) {
1481
1561
  }
1482
1562
  }
1483
1563
 
1564
+ // packages/execution/src/nested-park.ts
1565
+ import {
1566
+ withCancel,
1567
+ withoutAbortSignal as withoutAbortSignal3
1568
+ } from "@earendil-works/chord/context";
1569
+ import { copyJson as copyJson9 } from "@earendil-works/chord/json";
1570
+ var resultFields = [
1571
+ "output",
1572
+ "structuredOutput",
1573
+ "isError",
1574
+ "details",
1575
+ "diagnostics",
1576
+ "usage",
1577
+ "control"
1578
+ ];
1579
+ function sleepState(checkpoint, { until, signals }) {
1580
+ return {
1581
+ status: "sleeping",
1582
+ checkpoint,
1583
+ ...until === undefined ? {} : { until },
1584
+ ...signals === undefined ? {} : { signals }
1585
+ };
1586
+ }
1587
+ async function parkGate(runtime, sleep, context) {
1588
+ try {
1589
+ await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
1590
+ } catch (error) {
1591
+ runtime.signal.throwIfAborted();
1592
+ return errorText(error);
1593
+ }
1594
+ }
1595
+ async function parkTool(runtime, invocation, tool, args, park, context) {
1596
+ if (park.kind !== "sleep" && park.kind !== "wait")
1597
+ return "Unknown park kind";
1598
+ const mixed = resultFields.find((field) => (field in park));
1599
+ if (mixed !== undefined)
1600
+ return `A park cannot carry the result field ${mixed}`;
1601
+ const intent = {
1602
+ arguments: args,
1603
+ replay: tool.replay ?? "unsafe",
1604
+ ...park.checkpoint === undefined ? {} : { checkpoint: copyJson9(park.checkpoint) }
1605
+ };
1606
+ const { progress, pending } = await invocation.park();
1607
+ try {
1608
+ await runtime.commit(async (tx) => {
1609
+ if (park.kind === "wait") {
1610
+ for (const id of park.on)
1611
+ if ((await tx.task(id))?.owner !== runtime.taskId)
1612
+ throw new Error(`Task ${id} is not owned by the call`);
1613
+ }
1614
+ const checkpoint = { ...intent, phase: "parked" };
1615
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1616
+ doc.result = progress;
1617
+ doc.droppedBytes = 0;
1618
+ doc.droppedLines = 0;
1619
+ await forwardInvocationResult(tx, runtime.taskId, progress, "running");
1620
+ return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
1621
+ }, context);
1622
+ } catch (error) {
1623
+ for (const waiter of pending)
1624
+ waiter.reject(error);
1625
+ const detached = withoutAbortSignal3(context);
1626
+ const record = await runtime.getTask(runtime.taskId, detached);
1627
+ if (record?.abortRequested) {
1628
+ const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
1629
+ if (watch !== undefined) {
1630
+ const cleanup = withCancel(detached);
1631
+ watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
1632
+ try {
1633
+ await cancelParkedTool(runtime, tool, intent, cleanup.context);
1634
+ } finally {
1635
+ await watch.stop();
1636
+ }
1637
+ }
1638
+ throw error;
1639
+ }
1640
+ runtime.signal.throwIfAborted();
1641
+ return errorText(error);
1642
+ }
1643
+ for (const waiter of pending)
1644
+ waiter.resolve();
1645
+ }
1646
+ async function cancelParkedTool(runtime, tool, intent, context) {
1647
+ if (!tool) {
1648
+ runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
1649
+ return;
1650
+ }
1651
+ if (tool.cancel === undefined)
1652
+ return;
1653
+ const cleanup = createInvocation(runtime, tool, context, {
1654
+ checkpoint: intent.checkpoint,
1655
+ wake: undefined
1656
+ });
1657
+ const refuseWork = () => {
1658
+ throw new Error("A tool cannot start tasks or nested calls during cancellation");
1659
+ };
1660
+ let reason = new Error("Tool cancellation finished");
1661
+ try {
1662
+ const api = await cleanup.executionApi();
1663
+ await tool.cancel(intent.arguments, {
1664
+ ...api,
1665
+ createTask: refuseWork,
1666
+ executeTool: refuseWork
1667
+ }, context);
1668
+ } catch (error) {
1669
+ reason = error;
1670
+ runtime.report(error);
1671
+ } finally {
1672
+ await cleanup.stop(reason);
1673
+ }
1674
+ }
1675
+
1484
1676
  // packages/execution/src/nested-result.ts
1485
- import { copyJson as copyJson9 } from "@earendil-works/chord";
1677
+ import { copyJson as copyJson10 } from "@earendil-works/chord/json";
1486
1678
  import {
1487
1679
  defineEntry,
1488
1680
  UsageDoc
@@ -1530,11 +1722,11 @@ async function settle(runtime, call, result, ending, context) {
1530
1722
  taskId: runtime.taskId,
1531
1723
  callId: call.id,
1532
1724
  name: call.name,
1533
- arguments: copyJson9(call.arguments),
1725
+ arguments: copyJson10(call.arguments),
1534
1726
  result: stored,
1535
1727
  ...current.state.checkpoint.phase === "execute" ? {
1536
1728
  intent: {
1537
- arguments: copyJson9(current.state.checkpoint.arguments),
1729
+ arguments: copyJson10(current.state.checkpoint.arguments),
1538
1730
  replay: current.state.checkpoint.replay
1539
1731
  }
1540
1732
  } : {}
@@ -1543,7 +1735,7 @@ async function settle(runtime, call, result, ending, context) {
1543
1735
  if (result.usage !== undefined) {
1544
1736
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1545
1737
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1546
- totals[call.name] = copyJson9(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1738
+ totals[call.name] = copyJson10(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1547
1739
  }
1548
1740
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1549
1741
  status: ending,
@@ -1580,7 +1772,11 @@ function sumUsage(previous, added) {
1580
1772
  function createNestedToolTask(name) {
1581
1773
  return defineTask2({
1582
1774
  name,
1583
- version: 1,
1775
+ version: 2,
1776
+ migrate: (input, checkpoint) => ({
1777
+ input,
1778
+ checkpoint
1779
+ }),
1584
1780
  initial: () => ({ phase: "call" }),
1585
1781
  phases: {
1586
1782
  call: async (task, runtime, context) => {
@@ -1615,13 +1811,16 @@ function createNestedToolTask(name) {
1615
1811
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1616
1812
  }
1617
1813
  let block;
1814
+ let sleep;
1618
1815
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1619
- if (block !== undefined)
1816
+ if (block !== undefined || sleep !== undefined)
1620
1817
  return;
1621
1818
  try {
1622
1819
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1623
1820
  if (decision?.block !== undefined)
1624
1821
  block = decision.block;
1822
+ else if (decision?.sleep !== undefined)
1823
+ sleep = decision.sleep;
1625
1824
  else if (decision?.arguments !== undefined)
1626
1825
  args = decision.arguments;
1627
1826
  } catch (error) {
@@ -1632,71 +1831,122 @@ function createNestedToolTask(name) {
1632
1831
  });
1633
1832
  if (block !== undefined)
1634
1833
  return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
1834
+ if (sleep !== undefined) {
1835
+ const reason = await parkGate(runtime, sleep, context);
1836
+ if (reason === undefined)
1837
+ return;
1838
+ return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
1839
+ }
1635
1840
  try {
1636
- args = checked(tool, call, args);
1841
+ args = copyJson11(checked(tool, call, args), {
1842
+ omitUndefinedProperties: true
1843
+ });
1637
1844
  } catch (error) {
1638
1845
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1639
1846
  }
1640
- await runtime.commit(async (tx) => {
1641
- await tx.doc(InvocationDoc, runtime.taskId);
1642
- await forwardCall(tx, task.input.cellId, {
1643
- callId: call.id,
1644
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1645
- name: call.name,
1646
- arguments: args,
1647
- status: "running",
1648
- result: null,
1649
- omittedFields: []
1650
- });
1651
- return {
1652
- status: "running",
1653
- checkpoint: {
1654
- phase: "execute",
1655
- arguments: args,
1656
- replay: tool.replay ?? "unsafe"
1657
- }
1658
- };
1847
+ await startAttempt(runtime, call, tool, agent, {
1848
+ arguments: args,
1849
+ replay: tool.replay ?? "unsafe"
1659
1850
  }, context);
1660
- await run(runtime, call, tool, args, agent, context);
1851
+ },
1852
+ parked: async (task, runtime, context) => {
1853
+ const intent = task.state.checkpoint;
1854
+ const call = nestedCall(runtime, task.input);
1855
+ call.arguments = intent.arguments;
1856
+ const agent = await runtime.agent(context);
1857
+ const tool = agent.callable.find((each) => each.name === call.name);
1858
+ if (tool === undefined || readToolContract(tool).nativeOnly)
1859
+ return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
1860
+ await startAttempt(runtime, call, tool, agent, {
1861
+ ...intent,
1862
+ replay: tool.replay ?? "unsafe"
1863
+ }, context, task.state.wake);
1661
1864
  },
1662
1865
  execute: async (task, runtime, context) => {
1866
+ const intent = task.state.checkpoint;
1663
1867
  const call = nestedCall(runtime, task.input);
1664
1868
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1665
1869
  call.arguments = task.state.checkpoint.arguments;
1666
1870
  const agent = await runtime.agent(context);
1667
1871
  const tool = agent.callable.find((each) => each.name === call.name);
1668
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1669
- await runtime.commit(async (tx) => {
1670
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1671
- doc.result = {};
1672
- doc.droppedBytes = 0;
1673
- doc.droppedLines = 0;
1674
- return;
1675
- }, context);
1676
- return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
1872
+ if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1873
+ if (intent.resume === undefined)
1874
+ await runtime.commit(async (tx) => {
1875
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1876
+ doc.result = {};
1877
+ doc.droppedBytes = 0;
1878
+ doc.droppedLines = 0;
1879
+ return;
1880
+ }, context);
1881
+ return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
1677
1882
  }
1883
+ if (intent.resume !== undefined)
1884
+ await cancelParkedTool(runtime, tool, intent, context);
1678
1885
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1679
1886
  }
1680
1887
  },
1681
1888
  abort: async (task, runtime, context) => {
1682
1889
  const call = nestedCall(runtime, task.input);
1890
+ const intent = task.state.checkpoint;
1891
+ if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
1892
+ const agent = await runtime.agent(context);
1893
+ const tool = agent.callable.find((each) => each.name === call.name);
1894
+ await cancelParkedTool(runtime, tool, intent, context);
1895
+ }
1683
1896
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1684
1897
  }
1685
1898
  });
1686
1899
  }
1900
+ async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
1901
+ await runtime.commit(async (tx) => {
1902
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1903
+ await forwardCall(tx, doc.forwardingCellId, {
1904
+ callId: call.id,
1905
+ parentCallId: call.parent?.callId ?? call.id,
1906
+ name: call.name,
1907
+ arguments: intent.arguments,
1908
+ status: "running",
1909
+ result: null,
1910
+ omittedFields: []
1911
+ });
1912
+ return {
1913
+ status: "running",
1914
+ checkpoint: {
1915
+ ...intent,
1916
+ phase: "execute",
1917
+ ...wake === undefined ? {} : { resume: { wake } }
1918
+ }
1919
+ };
1920
+ }, context);
1921
+ await run(runtime, call, tool, intent, agent, context, wake);
1922
+ }
1687
1923
  async function reject(runtime, call, result, agent, tool, context) {
1688
1924
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1689
1925
  result = await handler(call, result, runtime, context) ?? result;
1690
1926
  });
1691
1927
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1692
1928
  }
1693
- async function run(runtime, call, tool, args, agent, context) {
1929
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1694
1930
  let invocation;
1695
1931
  let result;
1696
1932
  let ending = "completed";
1697
1933
  try {
1698
- invocation = createInvocation(runtime, tool, context);
1699
- result = await tool.execute(args, await invocation.executionApi(), context);
1934
+ const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
1935
+ invocation = createInvocation(runtime, tool, context, {
1936
+ wake,
1937
+ checkpoint: intent.checkpoint,
1938
+ ...previous === undefined ? {} : { progress: previous.result }
1939
+ });
1940
+ const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
1941
+ if (returned.kind === undefined)
1942
+ result = returned;
1943
+ else {
1944
+ const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
1945
+ if (reason === undefined)
1946
+ return;
1947
+ result = executionError("invalid_park", reason);
1948
+ ending = "failed";
1949
+ }
1700
1950
  } catch (error) {
1701
1951
  if (runtime.signal.aborted) {
1702
1952
  await invocation?.stop(error);
@@ -1797,9 +2047,11 @@ function providerProjection(surfaceTools) {
1797
2047
  const conversation = await host.conversation(api.conversationId, context);
1798
2048
  if (conversation === undefined)
1799
2049
  throw new Error(`Conversation ${api.conversationId} is unavailable`);
1800
- for (const tool of (await conversation.agent(context)).tools)
1801
- if (readToolContract(tool).nativeOnly)
2050
+ for (const tool of (await conversation.agent(context)).tools) {
2051
+ const contract = readToolContract(tool);
2052
+ if (contract.nativeOnly || contract.nestedHidden)
1802
2053
  visible.add(tool.name);
2054
+ }
1803
2055
  }
1804
2056
  return { messages: projectToolSchemas(request.messages, visible) };
1805
2057
  }
@@ -1808,7 +2060,7 @@ function providerProjection(surfaceTools) {
1808
2060
  }
1809
2061
 
1810
2062
  // packages/execution/src/wait-session.ts
1811
- import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
2063
+ import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
1812
2064
 
1813
2065
  // packages/execution/src/tool-value.ts
1814
2066
  class NestedToolError extends Error {
@@ -1879,7 +2131,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
1879
2131
  }, context);
1880
2132
  let cancelling;
1881
2133
  const abort = () => {
1882
- cancelling ??= cancelTask(id, withoutAbortSignal3(context));
2134
+ cancelling ??= cancelTask(id, withoutAbortSignal4(context));
1883
2135
  cancelling.catch(() => {});
1884
2136
  };
1885
2137
  context.abortSignal?.addEventListener("abort", abort, { once: true });
@@ -1963,7 +2215,7 @@ function createCellCoordinator(options) {
1963
2215
  if (driver.closed)
1964
2216
  throw new Error("Execution host is closed");
1965
2217
  assertSingleExecutionMode(await api.agent(context));
1966
- const copied = copyJson10(input);
2218
+ const copied = copyJson12(input);
1967
2219
  return api.commit(async (tx) => {
1968
2220
  const isolatedLimit = options.isolatedConcurrency ?? 0;
1969
2221
  const isolated = isolatedLimit > 0 && input["isolated"] === true;
@@ -2043,7 +2295,7 @@ function createCellCoordinator(options) {
2043
2295
  if (yielding.consume()) {
2044
2296
  return initial;
2045
2297
  }
2046
- const wait = withCancel(context);
2298
+ const wait = withCancel2(context);
2047
2299
  const timeout = new Error("Cell observation yielded");
2048
2300
  const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
2049
2301
  try {
@@ -2276,7 +2528,7 @@ function moduleCode(request, limits, invoke) {
2276
2528
  }
2277
2529
 
2278
2530
  // packages/worker-code/src/output.ts
2279
- import { copyJson as copyJson11 } from "@earendil-works/chord";
2531
+ import { copyJson as copyJson13 } from "@earendil-works/chord/json";
2280
2532
  function guestContent(kind, value) {
2281
2533
  if (kind === "text")
2282
2534
  return {
@@ -2328,7 +2580,7 @@ function observeWorkerCell(observation, maxTokens, delivered) {
2328
2580
  ...fields,
2329
2581
  cellId: observation.cellId,
2330
2582
  ...observation.forwardedToolCalls === undefined ? {} : {
2331
- forwardedToolCalls: copyJson11(observation.forwardedToolCalls, {
2583
+ forwardedToolCalls: copyJson13(observation.forwardedToolCalls, {
2332
2584
  omitUndefinedProperties: true
2333
2585
  })
2334
2586
  },
@@ -2570,7 +2822,7 @@ class WorkerRuntime {
2570
2822
  };
2571
2823
  const result = await this.evaluate(input["code"], modules, api.signal, {
2572
2824
  tools: api.tools,
2573
- inventory: api.registrations.map(readToolContract).map((tool) => ({
2825
+ inventory: api.registrations.map(readToolContract).filter((tool) => !tool.nestedHidden).map((tool) => ({
2574
2826
  name: tool.name,
2575
2827
  description: tool.description,
2576
2828
  parameters: tool.inputSchema,
@@ -2734,7 +2986,7 @@ function createWorkerCode(options) {
2734
2986
  section("worker-code", (input) => [
2735
2987
  nestedToolDiscoveryGuidance,
2736
2988
  "exec runs fresh bounded JavaScript. Await tools[name](args) and emit with text(value) or image({data,mimeType}). ALL_TOOLS lists callable contracts with original names. await yield_control() wakes the observer. Use wait for running cells. Guest globals and imports do not persist. No shell, ambient network or native globals.",
2737
- ...input.agent.callable.filter((tool) => tool.name !== "exec" && tool.name !== "wait").map(readToolContract).filter((contract) => !contract.nativeOnly && !contract.deferLoading).map((contract) => contract.usage)
2989
+ ...input.agent.callable.filter((tool) => tool.name !== "exec" && tool.name !== "wait").map(readToolContract).filter((contract) => !contract.nativeOnly && !contract.nestedHidden && !contract.deferLoading).map((contract) => contract.usage)
2738
2990
  ].join(`
2739
2991
  `))
2740
2992
  ]