@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.
package/dist/index.js CHANGED
@@ -6,11 +6,11 @@ import {
6
6
  import { Type as Type2 } from "typebox";
7
7
 
8
8
  // packages/execution/src/cell-tools.ts
9
- import { copyJson as copyJson5 } from "@earendil-works/chord";
10
9
  import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
10
+ import { copyJson as copyJson5 } from "@earendil-works/chord/json";
11
11
 
12
12
  // packages/execution/src/forwarding.ts
13
- import { copyJson as copyJson2 } from "@earendil-works/chord";
13
+ import { copyJson as copyJson2 } from "@earendil-works/chord/json";
14
14
  import {
15
15
  LiveDoc,
16
16
  NestedCallDoc,
@@ -20,7 +20,7 @@ import {
20
20
  // packages/execution/src/invocation-state.ts
21
21
  import {
22
22
  copyJson
23
- } from "@earendil-works/chord";
23
+ } from "@earendil-works/chord/json";
24
24
  import {
25
25
  defineDoc
26
26
  } from "@earendil-works/pi-durable";
@@ -462,26 +462,53 @@ async function captureNativeCalls(tx, conversationId, owner, cellId) {
462
462
  }
463
463
 
464
464
  // packages/execution/src/invocation.ts
465
- import { copyJson as copyJson4 } from "@earendil-works/chord";
466
465
  import { awaitWithContext } from "@earendil-works/chord/context";
466
+ import { copyJson as copyJson4 } from "@earendil-works/chord/json";
467
+ import {
468
+ NestedCallDoc as NestedCallDoc3
469
+ } from "@earendil-works/pi-durable";
470
+ import { equal } from "@earendil-works/pi-schema";
467
471
 
468
472
  // packages/execution/src/native-tools.ts
469
- import { copyJson as copyJson3 } from "@earendil-works/chord";
470
- import { withoutAbortSignal } from "@earendil-works/chord/context";
473
+ import {
474
+ withoutAbortSignal
475
+ } from "@earendil-works/chord/context";
476
+ import { copyJson as copyJson3 } from "@earendil-works/chord/json";
471
477
  import {
472
478
  LiveDoc as LiveDoc2,
473
479
  NestedCallDoc as NestedCallDoc2,
474
- ToolTask as ToolTask2
480
+ ToolTask as ToolTask3
475
481
  } from "@earendil-works/pi-durable";
476
482
  import { Equal } from "typebox/value";
477
- function nativeToolCalls(runtime, callId, replay, assertLive, context) {
483
+
484
+ // packages/execution/src/tool-origin.ts
485
+ import {
486
+ defineDoc as defineDoc2,
487
+ ToolTask as ToolTask2
488
+ } from "@earendil-works/pi-durable";
489
+ var ToolOriginDoc = defineDoc2({
490
+ kind: "howaboua.tool-origin",
491
+ version: 1,
492
+ scope: "task",
493
+ checkpointWhen: () => false,
494
+ initial: () => ({})
495
+ });
496
+
497
+ // packages/execution/src/native-tools.ts
498
+ function assertNestedKey(key) {
499
+ if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
500
+ throw new Error("Invalid nested call or task key");
501
+ }
502
+ function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
478
503
  let sequence = 0;
479
504
  const admissions = [];
480
- const execute = async (name, args, callContext, options = {}) => {
505
+ async function execute(name, args, callContext, options = {}) {
481
506
  assertLive();
507
+ if (options.key !== undefined)
508
+ assertNestedKey(options.key);
509
+ else if (resumed)
510
+ throw new Error("Nested calls require an explicit key after waking");
482
511
  const key = options.key ?? String(++sequence);
483
- if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
484
- throw new Error("Invalid nested call key");
485
512
  const call = {
486
513
  type: "toolCall",
487
514
  id: `${callId}/${key}`,
@@ -493,11 +520,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
493
520
  const admission = runtime.commit(async (tx) => {
494
521
  const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
495
522
  if (slot.taskId !== undefined) {
496
- const input = (await tx.task(slot.taskId))?.input;
523
+ const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
497
524
  if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
498
525
  throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
499
526
  } else {
500
- slot.taskId = await tx.createTask(ToolTask2, {
527
+ slot.kind = "nested";
528
+ slot.taskId = await tx.createTask(ToolTask3, {
501
529
  kind: "nested",
502
530
  parent: runtime.taskId,
503
531
  parentCallId: callId,
@@ -509,6 +537,9 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
509
537
  abandonOnRestart: replay !== "safe"
510
538
  });
511
539
  const live = await tx.doc(LiveDoc2, runtime.conversationId);
540
+ const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
541
+ if (origin)
542
+ (await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
512
543
  live.nestedTools ??= [];
513
544
  live.nestedTools.push({
514
545
  callId: call.id,
@@ -540,7 +571,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
540
571
  const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
541
572
  if (slot?.taskId === undefined)
542
573
  throw new Error("Nested task creation did not commit");
543
- const settled = await runtime.waitForTask(slot.taskId, callContext);
574
+ const taskId = slot.taskId;
575
+ const result = (resultContext) => readResult(name, key, taskId, resultContext);
576
+ return options.wait === false ? { taskId, result } : result(callContext);
577
+ }
578
+ async function readResult(name, key, taskId, callContext) {
579
+ assertLive();
580
+ const settled = await runtime.waitForTask(taskId, callContext);
544
581
  const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
545
582
  await runtime.commit(async (tx) => {
546
583
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
@@ -548,7 +585,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
548
585
  return;
549
586
  }, callContext);
550
587
  return result === undefined ? {
551
- taskId: slot.taskId,
588
+ taskId,
552
589
  isError: true,
553
590
  diagnostics: [
554
591
  {
@@ -558,9 +595,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
558
595
  }
559
596
  ]
560
597
  } : copyJson3(result);
561
- };
598
+ }
562
599
  return {
563
600
  execute,
601
+ async drain() {
602
+ await Promise.allSettled(admissions);
603
+ },
564
604
  async finish() {
565
605
  await Promise.allSettled(admissions);
566
606
  await cleanupNativeCalls(runtime, withoutAbortSignal(context));
@@ -568,7 +608,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
568
608
  };
569
609
  }
570
610
  async function cleanupNativeCalls(runtime, context) {
571
- await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
611
+ await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
572
612
  await runtime.commit(async (tx) => {
573
613
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
574
614
  await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
@@ -662,18 +702,6 @@ class Progress {
662
702
  }
663
703
  }
664
704
 
665
- // packages/execution/src/tool-origin.ts
666
- import {
667
- defineDoc as defineDoc2
668
- } from "@earendil-works/pi-durable";
669
- var ToolOriginDoc = defineDoc2({
670
- kind: "howaboua.tool-origin",
671
- version: 1,
672
- scope: "task",
673
- checkpointWhen: () => false,
674
- initial: () => ({})
675
- });
676
-
677
705
  // packages/execution/src/invocation.ts
678
706
  function executionError(code, message) {
679
707
  return {
@@ -685,21 +713,23 @@ function executionError(code, message) {
685
713
  function errorText(error) {
686
714
  return error instanceof Error ? error.message : String(error);
687
715
  }
688
- function createInvocation(runtime, tool, context) {
716
+ function createInvocation(runtime, tool, context, resume) {
689
717
  const limits = {
690
718
  maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
691
719
  maxLines: tool.outputLimits?.maxLines ?? 2000,
692
720
  retain: tool.outputLimits?.retain ?? "head"
693
721
  };
694
722
  const output = new OutputBuffer(limits);
695
- const diagnostics = [];
696
- let details;
723
+ const diagnostics = [
724
+ ...resume?.progress?.diagnostics ?? []
725
+ ];
726
+ let details = resume?.progress?.details;
697
727
  let ended = false;
698
728
  const assertLive = () => {
699
729
  if (ended)
700
730
  throw new Error(`Invocation ${runtime.taskId} has settled`);
701
731
  };
702
- const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
732
+ const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
703
733
  const snapshot = () => {
704
734
  const retained = output.snapshot();
705
735
  return {
@@ -728,6 +758,8 @@ function createInvocation(runtime, tool, context) {
728
758
  taskId: runtime.taskId,
729
759
  conversationId: runtime.conversationId,
730
760
  callId: `nested-${runtime.taskId}`,
761
+ wake: resume?.wake,
762
+ checkpoint: resume?.checkpoint,
731
763
  registry: runtime.registry,
732
764
  agent: runtime.agent,
733
765
  env: undefined,
@@ -748,7 +780,7 @@ function createInvocation(runtime, tool, context) {
748
780
  const retained = output.snapshot();
749
781
  return { text: retained.text, truncated: retained.droppedBytes > 0 };
750
782
  },
751
- executeTool: (...args) => native.execute(...args),
783
+ executeTool: native.execute,
752
784
  diagnostic: (value) => {
753
785
  assertLive();
754
786
  diagnostics.push(copyJson4(value, { omitUndefinedProperties: true }));
@@ -762,24 +794,44 @@ function createInvocation(runtime, tool, context) {
762
794
  committed.catch(() => {});
763
795
  await awaitWithContext(committed, detailContext);
764
796
  },
765
- commit: async (change, commitContext) => {
797
+ commit: async (change, commitContext, options) => {
766
798
  assertLive();
767
799
  let result;
768
800
  await runtime.commit(async (tx) => {
769
801
  result = await change(tx);
770
802
  return;
771
- }, commitContext);
803
+ }, commitContext, options);
772
804
  return result;
773
805
  },
774
806
  memo: runtime.memo,
775
- createTask: async (task, input, options, taskContext) => {
807
+ readSignal: runtime.readSignal,
808
+ async createTask(task, input, {
809
+ key,
810
+ ...options
811
+ }, taskContext) {
776
812
  assertLive();
813
+ if (key !== undefined)
814
+ assertNestedKey(key);
815
+ else if (resume?.wake !== undefined)
816
+ throw new Error("Child tasks require an explicit key after waking");
777
817
  let id;
778
818
  await runtime.commit(async (tx) => {
819
+ const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
820
+ if (member?.taskId !== undefined) {
821
+ const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
822
+ if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson4(input, { omitUndefinedProperties: true })))
823
+ throw new Error(`Key ${key} was already used for another call or task`);
824
+ id = member.taskId;
825
+ return;
826
+ }
779
827
  id = await tx.createTask(task, input, {
780
828
  ...options,
781
829
  ...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
782
830
  });
831
+ if (member !== undefined) {
832
+ member.kind = "task";
833
+ member.taskId = id;
834
+ }
783
835
  const source = await tx.doc(ToolOriginDoc, runtime.taskId);
784
836
  if (source.origin !== undefined)
785
837
  (await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
@@ -826,6 +878,14 @@ function createInvocation(runtime, tool, context) {
826
878
  for (const waiter of await progress.stop())
827
879
  waiter.reject(error);
828
880
  },
881
+ async park() {
882
+ ended = true;
883
+ await native.drain();
884
+ output.end();
885
+ const pending = await progress.stop();
886
+ const { output: _output, ...kept } = snapshot();
887
+ return { progress: storeResult(kept), pending };
888
+ },
829
889
  limits,
830
890
  output,
831
891
  progress
@@ -911,8 +971,8 @@ function cellTools(runtime, toolApi, registrations, nestedTask, controls, cancel
911
971
  }
912
972
 
913
973
  // packages/execution/src/cells.ts
914
- import { copyJson as copyJson10 } from "@earendil-works/chord";
915
- import { withCancel } from "@earendil-works/chord/context";
974
+ import { withCancel as withCancel2 } from "@earendil-works/chord/context";
975
+ import { copyJson as copyJson12 } from "@earendil-works/chord/json";
916
976
  import {
917
977
  defineExtension
918
978
  } from "@earendil-works/pi-durable";
@@ -956,7 +1016,7 @@ async function observeCell(kind, id, api, context, budget) {
956
1016
  }
957
1017
 
958
1018
  // packages/execution/src/cell-progress.ts
959
- import { copyJson as copyJson6 } from "@earendil-works/chord";
1019
+ import { copyJson as copyJson6 } from "@earendil-works/chord/json";
960
1020
  import {
961
1021
  LiveDoc as LiveDoc3
962
1022
  } from "@earendil-works/pi-durable";
@@ -1016,8 +1076,8 @@ async function observeCellProgress(id, api, context, budget) {
1016
1076
  }
1017
1077
 
1018
1078
  // packages/execution/src/cell-task.ts
1019
- import { copyJson as copyJson8 } from "@earendil-works/chord";
1020
1079
  import { withAbortSignal } from "@earendil-works/chord/context";
1080
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
1021
1081
  import {
1022
1082
  defineTask
1023
1083
  } from "@earendil-works/pi-durable";
@@ -1039,7 +1099,17 @@ function combineControls(controls, allowTermination = true) {
1039
1099
  }
1040
1100
 
1041
1101
  // packages/execution/src/tool-contract.ts
1042
- import { copyJson as copyJson7 } from "@earendil-works/chord";
1102
+ import { copyJson as copyJson7 } from "@earendil-works/chord/json";
1103
+
1104
+ // packages/execution/src/tool-namespaces.ts
1105
+ import { isJsonValue } from "@earendil-works/chord/json";
1106
+ function validateJsToolNamespace(tool, namespace) {
1107
+ const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
1108
+ 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))))
1109
+ throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
1110
+ }
1111
+
1112
+ // packages/execution/src/tool-contract.ts
1043
1113
  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 {}";
1044
1114
  function readToolContract(tool) {
1045
1115
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
@@ -1054,6 +1124,7 @@ function readToolContract(tool) {
1054
1124
  "yieldTimeMs",
1055
1125
  "inputSchema",
1056
1126
  "nativeOnly",
1127
+ "nestedHidden",
1057
1128
  "discovery"
1058
1129
  ]);
1059
1130
  for (const key of Object.keys(hints))
@@ -1077,6 +1148,12 @@ function readToolContract(tool) {
1077
1148
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1078
1149
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1079
1150
  throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
1151
+ const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
1152
+ const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
1153
+ if (jsNamespace !== undefined)
1154
+ validateJsToolNamespace(tool.name, jsNamespace);
1155
+ if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
1156
+ throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
1080
1157
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1081
1158
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1082
1159
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1093,6 +1170,8 @@ function readToolContract(tool) {
1093
1170
  inputSchema,
1094
1171
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1095
1172
  nativeOnly: nativeOnly === true,
1173
+ nestedHidden: nestedHidden === true,
1174
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1096
1175
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1097
1176
  ...outputHint === undefined ? {} : { output: outputHint },
1098
1177
  help: [
@@ -1328,7 +1407,7 @@ function createCellTask(options, nestedTask) {
1328
1407
  import {
1329
1408
  hook,
1330
1409
  LiveDoc as LiveDoc4,
1331
- ToolTask as ToolTask3
1410
+ ToolTask as ToolTask4
1332
1411
  } from "@earendil-works/pi-durable";
1333
1412
  function forwardingHook() {
1334
1413
  let host;
@@ -1338,7 +1417,7 @@ function forwardingHook() {
1338
1417
  throw new Error("Create a separate execution component for each Harness");
1339
1418
  host = harness;
1340
1419
  },
1341
- hook: hook(ToolTask3, {
1420
+ hook: hook(ToolTask4, {
1342
1421
  async beforeTool(call, api, context) {
1343
1422
  const parent = call.parent;
1344
1423
  if (parent === undefined || host === undefined)
@@ -1351,7 +1430,7 @@ function forwardingHook() {
1351
1430
  if (conversation === undefined)
1352
1431
  throw new Error("Forwarded call conversation is unavailable");
1353
1432
  await conversation.commit(async (tx) => {
1354
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1433
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1355
1434
  return;
1356
1435
  const owner = await tx.doc(InvocationDoc, api.taskId);
1357
1436
  const admission = owner.forwardingCellId === undefined;
@@ -1378,7 +1457,7 @@ function forwardingHook() {
1378
1457
  if (conversation === undefined)
1379
1458
  throw new Error("Forwarded call conversation is unavailable");
1380
1459
  await conversation.commit(async (tx) => {
1381
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1460
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1382
1461
  return;
1383
1462
  const owner = await tx.doc(InvocationDoc, api.taskId);
1384
1463
  const cellId = owner.forwardingCellId;
@@ -1403,6 +1482,7 @@ function forwardingHook() {
1403
1482
  }
1404
1483
 
1405
1484
  // packages/execution/src/nested.ts
1485
+ import { copyJson as copyJson11 } from "@earendil-works/chord/json";
1406
1486
  import {
1407
1487
  defineTask as defineTask2
1408
1488
  } from "@earendil-works/pi-durable";
@@ -1411,7 +1491,7 @@ import { compile as compile2 } from "@earendil-works/pi-schema";
1411
1491
  // packages/execution/src/nested-call.ts
1412
1492
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1413
1493
  import {
1414
- ToolTask as ToolTask4
1494
+ ToolTask as ToolTask5
1415
1495
  } from "@earendil-works/pi-durable";
1416
1496
  import { compile } from "@earendil-works/pi-schema";
1417
1497
  function nestedCall(runtime, input) {
@@ -1457,7 +1537,7 @@ function prepareNestedInput(tool, input) {
1457
1537
  async function eachHook(agent, name, api, invoke) {
1458
1538
  for (const extension of agent.extensions)
1459
1539
  for (const registration of extension.hooks ?? []) {
1460
- if (registration.task !== ToolTask4.definition.name)
1540
+ if (registration.task !== ToolTask5.definition.name)
1461
1541
  continue;
1462
1542
  const handler = registration.handlers[name];
1463
1543
  if (handler === undefined)
@@ -1472,8 +1552,120 @@ async function eachHook(agent, name, api, invoke) {
1472
1552
  }
1473
1553
  }
1474
1554
 
1555
+ // packages/execution/src/nested-park.ts
1556
+ import {
1557
+ withCancel,
1558
+ withoutAbortSignal as withoutAbortSignal3
1559
+ } from "@earendil-works/chord/context";
1560
+ import { copyJson as copyJson9 } from "@earendil-works/chord/json";
1561
+ var resultFields = [
1562
+ "output",
1563
+ "structuredOutput",
1564
+ "isError",
1565
+ "details",
1566
+ "diagnostics",
1567
+ "usage",
1568
+ "control"
1569
+ ];
1570
+ function sleepState(checkpoint, { until, signals }) {
1571
+ return {
1572
+ status: "sleeping",
1573
+ checkpoint,
1574
+ ...until === undefined ? {} : { until },
1575
+ ...signals === undefined ? {} : { signals }
1576
+ };
1577
+ }
1578
+ async function parkGate(runtime, sleep, context) {
1579
+ try {
1580
+ await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
1581
+ } catch (error) {
1582
+ runtime.signal.throwIfAborted();
1583
+ return errorText(error);
1584
+ }
1585
+ }
1586
+ async function parkTool(runtime, invocation, tool, args, park, context) {
1587
+ if (park.kind !== "sleep" && park.kind !== "wait")
1588
+ return "Unknown park kind";
1589
+ const mixed = resultFields.find((field) => (field in park));
1590
+ if (mixed !== undefined)
1591
+ return `A park cannot carry the result field ${mixed}`;
1592
+ const intent = {
1593
+ arguments: args,
1594
+ replay: tool.replay ?? "unsafe",
1595
+ ...park.checkpoint === undefined ? {} : { checkpoint: copyJson9(park.checkpoint) }
1596
+ };
1597
+ const { progress, pending } = await invocation.park();
1598
+ try {
1599
+ await runtime.commit(async (tx) => {
1600
+ if (park.kind === "wait") {
1601
+ for (const id of park.on)
1602
+ if ((await tx.task(id))?.owner !== runtime.taskId)
1603
+ throw new Error(`Task ${id} is not owned by the call`);
1604
+ }
1605
+ const checkpoint = { ...intent, phase: "parked" };
1606
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1607
+ doc.result = progress;
1608
+ doc.droppedBytes = 0;
1609
+ doc.droppedLines = 0;
1610
+ await forwardInvocationResult(tx, runtime.taskId, progress, "running");
1611
+ return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
1612
+ }, context);
1613
+ } catch (error) {
1614
+ for (const waiter of pending)
1615
+ waiter.reject(error);
1616
+ const detached = withoutAbortSignal3(context);
1617
+ const record = await runtime.getTask(runtime.taskId, detached);
1618
+ if (record?.abortRequested) {
1619
+ const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
1620
+ if (watch !== undefined) {
1621
+ const cleanup = withCancel(detached);
1622
+ watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
1623
+ try {
1624
+ await cancelParkedTool(runtime, tool, intent, cleanup.context);
1625
+ } finally {
1626
+ await watch.stop();
1627
+ }
1628
+ }
1629
+ throw error;
1630
+ }
1631
+ runtime.signal.throwIfAborted();
1632
+ return errorText(error);
1633
+ }
1634
+ for (const waiter of pending)
1635
+ waiter.resolve();
1636
+ }
1637
+ async function cancelParkedTool(runtime, tool, intent, context) {
1638
+ if (!tool) {
1639
+ runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
1640
+ return;
1641
+ }
1642
+ if (tool.cancel === undefined)
1643
+ return;
1644
+ const cleanup = createInvocation(runtime, tool, context, {
1645
+ checkpoint: intent.checkpoint,
1646
+ wake: undefined
1647
+ });
1648
+ const refuseWork = () => {
1649
+ throw new Error("A tool cannot start tasks or nested calls during cancellation");
1650
+ };
1651
+ let reason = new Error("Tool cancellation finished");
1652
+ try {
1653
+ const api = await cleanup.executionApi();
1654
+ await tool.cancel(intent.arguments, {
1655
+ ...api,
1656
+ createTask: refuseWork,
1657
+ executeTool: refuseWork
1658
+ }, context);
1659
+ } catch (error) {
1660
+ reason = error;
1661
+ runtime.report(error);
1662
+ } finally {
1663
+ await cleanup.stop(reason);
1664
+ }
1665
+ }
1666
+
1475
1667
  // packages/execution/src/nested-result.ts
1476
- import { copyJson as copyJson9 } from "@earendil-works/chord";
1668
+ import { copyJson as copyJson10 } from "@earendil-works/chord/json";
1477
1669
  import {
1478
1670
  defineEntry,
1479
1671
  UsageDoc
@@ -1521,11 +1713,11 @@ async function settle(runtime, call, result, ending, context) {
1521
1713
  taskId: runtime.taskId,
1522
1714
  callId: call.id,
1523
1715
  name: call.name,
1524
- arguments: copyJson9(call.arguments),
1716
+ arguments: copyJson10(call.arguments),
1525
1717
  result: stored,
1526
1718
  ...current.state.checkpoint.phase === "execute" ? {
1527
1719
  intent: {
1528
- arguments: copyJson9(current.state.checkpoint.arguments),
1720
+ arguments: copyJson10(current.state.checkpoint.arguments),
1529
1721
  replay: current.state.checkpoint.replay
1530
1722
  }
1531
1723
  } : {}
@@ -1534,7 +1726,7 @@ async function settle(runtime, call, result, ending, context) {
1534
1726
  if (result.usage !== undefined) {
1535
1727
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1536
1728
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1537
- totals[call.name] = copyJson9(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1729
+ totals[call.name] = copyJson10(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1538
1730
  }
1539
1731
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1540
1732
  status: ending,
@@ -1571,7 +1763,11 @@ function sumUsage(previous, added) {
1571
1763
  function createNestedToolTask(name) {
1572
1764
  return defineTask2({
1573
1765
  name,
1574
- version: 1,
1766
+ version: 2,
1767
+ migrate: (input, checkpoint) => ({
1768
+ input,
1769
+ checkpoint
1770
+ }),
1575
1771
  initial: () => ({ phase: "call" }),
1576
1772
  phases: {
1577
1773
  call: async (task, runtime, context) => {
@@ -1606,13 +1802,16 @@ function createNestedToolTask(name) {
1606
1802
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1607
1803
  }
1608
1804
  let block;
1805
+ let sleep;
1609
1806
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1610
- if (block !== undefined)
1807
+ if (block !== undefined || sleep !== undefined)
1611
1808
  return;
1612
1809
  try {
1613
1810
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1614
1811
  if (decision?.block !== undefined)
1615
1812
  block = decision.block;
1813
+ else if (decision?.sleep !== undefined)
1814
+ sleep = decision.sleep;
1616
1815
  else if (decision?.arguments !== undefined)
1617
1816
  args = decision.arguments;
1618
1817
  } catch (error) {
@@ -1623,71 +1822,122 @@ function createNestedToolTask(name) {
1623
1822
  });
1624
1823
  if (block !== undefined)
1625
1824
  return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
1825
+ if (sleep !== undefined) {
1826
+ const reason = await parkGate(runtime, sleep, context);
1827
+ if (reason === undefined)
1828
+ return;
1829
+ return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
1830
+ }
1626
1831
  try {
1627
- args = checked(tool, call, args);
1832
+ args = copyJson11(checked(tool, call, args), {
1833
+ omitUndefinedProperties: true
1834
+ });
1628
1835
  } catch (error) {
1629
1836
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1630
1837
  }
1631
- await runtime.commit(async (tx) => {
1632
- await tx.doc(InvocationDoc, runtime.taskId);
1633
- await forwardCall(tx, task.input.cellId, {
1634
- callId: call.id,
1635
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1636
- name: call.name,
1637
- arguments: args,
1638
- status: "running",
1639
- result: null,
1640
- omittedFields: []
1641
- });
1642
- return {
1643
- status: "running",
1644
- checkpoint: {
1645
- phase: "execute",
1646
- arguments: args,
1647
- replay: tool.replay ?? "unsafe"
1648
- }
1649
- };
1838
+ await startAttempt(runtime, call, tool, agent, {
1839
+ arguments: args,
1840
+ replay: tool.replay ?? "unsafe"
1650
1841
  }, context);
1651
- await run(runtime, call, tool, args, agent, context);
1842
+ },
1843
+ parked: async (task, runtime, context) => {
1844
+ const intent = task.state.checkpoint;
1845
+ const call = nestedCall(runtime, task.input);
1846
+ call.arguments = intent.arguments;
1847
+ const agent = await runtime.agent(context);
1848
+ const tool = agent.callable.find((each) => each.name === call.name);
1849
+ if (tool === undefined || readToolContract(tool).nativeOnly)
1850
+ return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
1851
+ await startAttempt(runtime, call, tool, agent, {
1852
+ ...intent,
1853
+ replay: tool.replay ?? "unsafe"
1854
+ }, context, task.state.wake);
1652
1855
  },
1653
1856
  execute: async (task, runtime, context) => {
1857
+ const intent = task.state.checkpoint;
1654
1858
  const call = nestedCall(runtime, task.input);
1655
1859
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1656
1860
  call.arguments = task.state.checkpoint.arguments;
1657
1861
  const agent = await runtime.agent(context);
1658
1862
  const tool = agent.callable.find((each) => each.name === call.name);
1659
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1660
- await runtime.commit(async (tx) => {
1661
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1662
- doc.result = {};
1663
- doc.droppedBytes = 0;
1664
- doc.droppedLines = 0;
1665
- return;
1666
- }, context);
1667
- return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
1863
+ if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1864
+ if (intent.resume === undefined)
1865
+ await runtime.commit(async (tx) => {
1866
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1867
+ doc.result = {};
1868
+ doc.droppedBytes = 0;
1869
+ doc.droppedLines = 0;
1870
+ return;
1871
+ }, context);
1872
+ return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
1668
1873
  }
1874
+ if (intent.resume !== undefined)
1875
+ await cancelParkedTool(runtime, tool, intent, context);
1669
1876
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1670
1877
  }
1671
1878
  },
1672
1879
  abort: async (task, runtime, context) => {
1673
1880
  const call = nestedCall(runtime, task.input);
1881
+ const intent = task.state.checkpoint;
1882
+ if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
1883
+ const agent = await runtime.agent(context);
1884
+ const tool = agent.callable.find((each) => each.name === call.name);
1885
+ await cancelParkedTool(runtime, tool, intent, context);
1886
+ }
1674
1887
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1675
1888
  }
1676
1889
  });
1677
1890
  }
1891
+ async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
1892
+ await runtime.commit(async (tx) => {
1893
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1894
+ await forwardCall(tx, doc.forwardingCellId, {
1895
+ callId: call.id,
1896
+ parentCallId: call.parent?.callId ?? call.id,
1897
+ name: call.name,
1898
+ arguments: intent.arguments,
1899
+ status: "running",
1900
+ result: null,
1901
+ omittedFields: []
1902
+ });
1903
+ return {
1904
+ status: "running",
1905
+ checkpoint: {
1906
+ ...intent,
1907
+ phase: "execute",
1908
+ ...wake === undefined ? {} : { resume: { wake } }
1909
+ }
1910
+ };
1911
+ }, context);
1912
+ await run(runtime, call, tool, intent, agent, context, wake);
1913
+ }
1678
1914
  async function reject(runtime, call, result, agent, tool, context) {
1679
1915
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1680
1916
  result = await handler(call, result, runtime, context) ?? result;
1681
1917
  });
1682
1918
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1683
1919
  }
1684
- async function run(runtime, call, tool, args, agent, context) {
1920
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1685
1921
  let invocation;
1686
1922
  let result;
1687
1923
  let ending = "completed";
1688
1924
  try {
1689
- invocation = createInvocation(runtime, tool, context);
1690
- result = await tool.execute(args, await invocation.executionApi(), context);
1925
+ const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
1926
+ invocation = createInvocation(runtime, tool, context, {
1927
+ wake,
1928
+ checkpoint: intent.checkpoint,
1929
+ ...previous === undefined ? {} : { progress: previous.result }
1930
+ });
1931
+ const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
1932
+ if (returned.kind === undefined)
1933
+ result = returned;
1934
+ else {
1935
+ const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
1936
+ if (reason === undefined)
1937
+ return;
1938
+ result = executionError("invalid_park", reason);
1939
+ ending = "failed";
1940
+ }
1691
1941
  } catch (error) {
1692
1942
  if (runtime.signal.aborted) {
1693
1943
  await invocation?.stop(error);
@@ -1788,9 +2038,11 @@ function providerProjection(surfaceTools) {
1788
2038
  const conversation = await host.conversation(api.conversationId, context);
1789
2039
  if (conversation === undefined)
1790
2040
  throw new Error(`Conversation ${api.conversationId} is unavailable`);
1791
- for (const tool of (await conversation.agent(context)).tools)
1792
- if (readToolContract(tool).nativeOnly)
2041
+ for (const tool of (await conversation.agent(context)).tools) {
2042
+ const contract = readToolContract(tool);
2043
+ if (contract.nativeOnly || contract.nestedHidden)
1793
2044
  visible.add(tool.name);
2045
+ }
1794
2046
  }
1795
2047
  return { messages: projectToolSchemas(request.messages, visible) };
1796
2048
  }
@@ -1799,7 +2051,7 @@ function providerProjection(surfaceTools) {
1799
2051
  }
1800
2052
 
1801
2053
  // packages/execution/src/wait-session.ts
1802
- import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
2054
+ import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
1803
2055
 
1804
2056
  // packages/execution/src/tool-value.ts
1805
2057
  class NestedToolError extends Error {
@@ -1870,7 +2122,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
1870
2122
  }, context);
1871
2123
  let cancelling;
1872
2124
  const abort = () => {
1873
- cancelling ??= cancelTask(id, withoutAbortSignal3(context));
2125
+ cancelling ??= cancelTask(id, withoutAbortSignal4(context));
1874
2126
  cancelling.catch(() => {});
1875
2127
  };
1876
2128
  context.abortSignal?.addEventListener("abort", abort, { once: true });
@@ -1954,7 +2206,7 @@ function createCellCoordinator(options) {
1954
2206
  if (driver.closed)
1955
2207
  throw new Error("Execution host is closed");
1956
2208
  assertSingleExecutionMode(await api.agent(context));
1957
- const copied = copyJson10(input);
2209
+ const copied = copyJson12(input);
1958
2210
  return api.commit(async (tx) => {
1959
2211
  const isolatedLimit = options.isolatedConcurrency ?? 0;
1960
2212
  const isolated = isolatedLimit > 0 && input["isolated"] === true;
@@ -2034,7 +2286,7 @@ function createCellCoordinator(options) {
2034
2286
  if (yielding.consume()) {
2035
2287
  return initial;
2036
2288
  }
2037
- const wait = withCancel(context);
2289
+ const wait = withCancel2(context);
2038
2290
  const timeout = new Error("Cell observation yielded");
2039
2291
  const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
2040
2292
  try {
@@ -2267,7 +2519,7 @@ function moduleCode(request, limits, invoke) {
2267
2519
  }
2268
2520
 
2269
2521
  // packages/worker-code/src/output.ts
2270
- import { copyJson as copyJson11 } from "@earendil-works/chord";
2522
+ import { copyJson as copyJson13 } from "@earendil-works/chord/json";
2271
2523
  function guestContent(kind, value) {
2272
2524
  if (kind === "text")
2273
2525
  return {
@@ -2319,7 +2571,7 @@ function observeWorkerCell(observation, maxTokens, delivered) {
2319
2571
  ...fields,
2320
2572
  cellId: observation.cellId,
2321
2573
  ...observation.forwardedToolCalls === undefined ? {} : {
2322
- forwardedToolCalls: copyJson11(observation.forwardedToolCalls, {
2574
+ forwardedToolCalls: copyJson13(observation.forwardedToolCalls, {
2323
2575
  omitUndefinedProperties: true
2324
2576
  })
2325
2577
  },
@@ -2561,7 +2813,7 @@ class WorkerRuntime {
2561
2813
  };
2562
2814
  const result = await this.evaluate(input["code"], modules, api.signal, {
2563
2815
  tools: api.tools,
2564
- inventory: api.registrations.map(readToolContract).map((tool) => ({
2816
+ inventory: api.registrations.map(readToolContract).filter((tool) => !tool.nestedHidden).map((tool) => ({
2565
2817
  name: tool.name,
2566
2818
  description: tool.description,
2567
2819
  parameters: tool.inputSchema,
@@ -2724,7 +2976,7 @@ function createWorkerCode(options) {
2724
2976
  section("worker-code", (input) => [
2725
2977
  nestedToolDiscoveryGuidance,
2726
2978
  "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.",
2727
- ...input.agent.callable.filter((tool) => tool.name !== "exec" && tool.name !== "wait").map(readToolContract).filter((contract) => !contract.nativeOnly && !contract.deferLoading).map((contract) => contract.usage)
2979
+ ...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)
2728
2980
  ].join(`
2729
2981
  `))
2730
2982
  ]