@howaboua/pi-durable-worker-code 0.10.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";
@@ -992,8 +1052,14 @@ async function observeCellProgress(id, api, context, budget) {
992
1052
  return work;
993
1053
  };
994
1054
  const live = await api.watchDoc(LiveDoc3, api.conversationId, context);
995
- cell.start((value) => own(() => publish(value)));
996
- live?.start(() => own(async () => {
1055
+ cell.start((call) => own(async () => {
1056
+ if (call.kind === "failed")
1057
+ throw call.error;
1058
+ await publish(call.value);
1059
+ }));
1060
+ live?.start((call) => own(async () => {
1061
+ if (call.kind === "failed")
1062
+ throw call.error;
997
1063
  await api.commit(async (tx) => {
998
1064
  const record = await tx.task(id);
999
1065
  if (record === undefined || record.state.status === "terminal")
@@ -1013,14 +1079,14 @@ async function observeCellProgress(id, api, context, budget) {
1013
1079
  const endings = await Promise.all([cell.stop(), live?.stop()]);
1014
1080
  await Promise.all([...pending]);
1015
1081
  for (const ending of endings)
1016
- if (ending?.reason === "listener_error")
1082
+ if (ending?.kind === "listener_error" || ending?.kind === "failed")
1017
1083
  throw ending.error;
1018
1084
  };
1019
1085
  }
1020
1086
 
1021
1087
  // packages/execution/src/cell-task.ts
1022
- import { copyJson as copyJson8 } from "@earendil-works/chord";
1023
1088
  import { withAbortSignal } from "@earendil-works/chord/context";
1089
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
1024
1090
  import {
1025
1091
  defineTask
1026
1092
  } from "@earendil-works/pi-durable";
@@ -1042,7 +1108,18 @@ function combineControls(controls, allowTermination = true) {
1042
1108
  }
1043
1109
 
1044
1110
  // packages/execution/src/tool-contract.ts
1045
- 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
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 {}";
1046
1123
  function readToolContract(tool) {
1047
1124
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
1048
1125
  if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
@@ -1056,6 +1133,7 @@ function readToolContract(tool) {
1056
1133
  "yieldTimeMs",
1057
1134
  "inputSchema",
1058
1135
  "nativeOnly",
1136
+ "nestedHidden",
1059
1137
  "discovery"
1060
1138
  ]);
1061
1139
  for (const key of Object.keys(hints))
@@ -1079,6 +1157,12 @@ function readToolContract(tool) {
1079
1157
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1080
1158
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1081
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`);
1082
1166
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1083
1167
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1084
1168
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1095,6 +1179,8 @@ function readToolContract(tool) {
1095
1179
  inputSchema,
1096
1180
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1097
1181
  nativeOnly: nativeOnly === true,
1182
+ nestedHidden: nestedHidden === true,
1183
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1098
1184
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1099
1185
  ...outputHint === undefined ? {} : { output: outputHint },
1100
1186
  help: [
@@ -1330,7 +1416,7 @@ function createCellTask(options, nestedTask) {
1330
1416
  import {
1331
1417
  hook,
1332
1418
  LiveDoc as LiveDoc4,
1333
- ToolTask as ToolTask3
1419
+ ToolTask as ToolTask4
1334
1420
  } from "@earendil-works/pi-durable";
1335
1421
  function forwardingHook() {
1336
1422
  let host;
@@ -1340,7 +1426,7 @@ function forwardingHook() {
1340
1426
  throw new Error("Create a separate execution component for each Harness");
1341
1427
  host = harness;
1342
1428
  },
1343
- hook: hook(ToolTask3, {
1429
+ hook: hook(ToolTask4, {
1344
1430
  async beforeTool(call, api, context) {
1345
1431
  const parent = call.parent;
1346
1432
  if (parent === undefined || host === undefined)
@@ -1353,7 +1439,7 @@ function forwardingHook() {
1353
1439
  if (conversation === undefined)
1354
1440
  throw new Error("Forwarded call conversation is unavailable");
1355
1441
  await conversation.commit(async (tx) => {
1356
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1442
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1357
1443
  return;
1358
1444
  const owner = await tx.doc(InvocationDoc, api.taskId);
1359
1445
  const admission = owner.forwardingCellId === undefined;
@@ -1380,7 +1466,7 @@ function forwardingHook() {
1380
1466
  if (conversation === undefined)
1381
1467
  throw new Error("Forwarded call conversation is unavailable");
1382
1468
  await conversation.commit(async (tx) => {
1383
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1469
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1384
1470
  return;
1385
1471
  const owner = await tx.doc(InvocationDoc, api.taskId);
1386
1472
  const cellId = owner.forwardingCellId;
@@ -1405,17 +1491,18 @@ function forwardingHook() {
1405
1491
  }
1406
1492
 
1407
1493
  // packages/execution/src/nested.ts
1494
+ import { copyJson as copyJson11 } from "@earendil-works/chord/json";
1408
1495
  import {
1409
1496
  defineTask as defineTask2
1410
1497
  } from "@earendil-works/pi-durable";
1411
- import { Compile as Compile2 } from "typebox/compile";
1498
+ import { compile as compile2 } from "@earendil-works/pi-schema";
1412
1499
 
1413
1500
  // packages/execution/src/nested-call.ts
1414
1501
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1415
1502
  import {
1416
- ToolTask as ToolTask4
1503
+ ToolTask as ToolTask5
1417
1504
  } from "@earendil-works/pi-durable";
1418
- import { Compile } from "typebox/compile";
1505
+ import { compile } from "@earendil-works/pi-schema";
1419
1506
  function nestedCall(runtime, input) {
1420
1507
  const args = input.arguments;
1421
1508
  return {
@@ -1436,7 +1523,7 @@ function prepareNestedInput(tool, input) {
1436
1523
  if (typeof input !== "string")
1437
1524
  return input;
1438
1525
  const contract = readToolContract(tool);
1439
- if (Boolean(Compile(tool.parameters).Check(input)) || Boolean(Compile(contract.inputSchema).Check(input)))
1526
+ if (Boolean(compile(tool.parameters).check(input)) || (typeof contract.inputSchema === "boolean" || typeof contract.inputSchema === "object" && contract.inputSchema !== null && !Array.isArray(contract.inputSchema)) && Boolean(compile(contract.inputSchema).check(input)))
1440
1527
  return input;
1441
1528
  const text = input.trim();
1442
1529
  if (contract.discovery === "help" && text === "help")
@@ -1459,7 +1546,7 @@ function prepareNestedInput(tool, input) {
1459
1546
  async function eachHook(agent, name, api, invoke) {
1460
1547
  for (const extension of agent.extensions)
1461
1548
  for (const registration of extension.hooks ?? []) {
1462
- if (registration.task !== ToolTask4.definition.name)
1549
+ if (registration.task !== ToolTask5.definition.name)
1463
1550
  continue;
1464
1551
  const handler = registration.handlers[name];
1465
1552
  if (handler === undefined)
@@ -1474,8 +1561,120 @@ async function eachHook(agent, name, api, invoke) {
1474
1561
  }
1475
1562
  }
1476
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
+
1477
1676
  // packages/execution/src/nested-result.ts
1478
- import { copyJson as copyJson9 } from "@earendil-works/chord";
1677
+ import { copyJson as copyJson10 } from "@earendil-works/chord/json";
1479
1678
  import {
1480
1679
  defineEntry,
1481
1680
  UsageDoc
@@ -1523,11 +1722,11 @@ async function settle(runtime, call, result, ending, context) {
1523
1722
  taskId: runtime.taskId,
1524
1723
  callId: call.id,
1525
1724
  name: call.name,
1526
- arguments: copyJson9(call.arguments),
1725
+ arguments: copyJson10(call.arguments),
1527
1726
  result: stored,
1528
1727
  ...current.state.checkpoint.phase === "execute" ? {
1529
1728
  intent: {
1530
- arguments: copyJson9(current.state.checkpoint.arguments),
1729
+ arguments: copyJson10(current.state.checkpoint.arguments),
1531
1730
  replay: current.state.checkpoint.replay
1532
1731
  }
1533
1732
  } : {}
@@ -1536,7 +1735,7 @@ async function settle(runtime, call, result, ending, context) {
1536
1735
  if (result.usage !== undefined) {
1537
1736
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1538
1737
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1539
- 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 });
1540
1739
  }
1541
1740
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1542
1741
  status: ending,
@@ -1573,7 +1772,11 @@ function sumUsage(previous, added) {
1573
1772
  function createNestedToolTask(name) {
1574
1773
  return defineTask2({
1575
1774
  name,
1576
- version: 1,
1775
+ version: 2,
1776
+ migrate: (input, checkpoint) => ({
1777
+ input,
1778
+ checkpoint
1779
+ }),
1577
1780
  initial: () => ({ phase: "call" }),
1578
1781
  phases: {
1579
1782
  call: async (task, runtime, context) => {
@@ -1599,22 +1802,25 @@ function createNestedToolTask(name) {
1599
1802
  return reject(runtime, call, executionError("tool_unavailable", `Tool ${call.name} is not available`), agent, tool, context);
1600
1803
  let args;
1601
1804
  try {
1602
- const supplied = task.input.arguments === null && !Compile2(tool.parameters).Check(null) && Compile2(tool.parameters).Check({}) ? undefined : task.input.arguments;
1805
+ const supplied = task.input.arguments === null && !compile2(tool.parameters).check(null) && compile2(tool.parameters).check({}) ? undefined : task.input.arguments;
1603
1806
  const prepared = tool.prepareArguments === undefined ? prepareNestedInput(tool, supplied) : tool.prepareArguments(prepareNestedInput(tool, supplied));
1604
- args = checked(tool, call, prepared === undefined && Compile2(tool.parameters).Check({}) ? {} : prepared);
1807
+ args = checked(tool, call, prepared === undefined && compile2(tool.parameters).check({}) ? {} : prepared);
1605
1808
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1606
1809
  call.arguments = args;
1607
1810
  } catch (error) {
1608
1811
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1609
1812
  }
1610
1813
  let block;
1814
+ let sleep;
1611
1815
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1612
- if (block !== undefined)
1816
+ if (block !== undefined || sleep !== undefined)
1613
1817
  return;
1614
1818
  try {
1615
1819
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1616
1820
  if (decision?.block !== undefined)
1617
1821
  block = decision.block;
1822
+ else if (decision?.sleep !== undefined)
1823
+ sleep = decision.sleep;
1618
1824
  else if (decision?.arguments !== undefined)
1619
1825
  args = decision.arguments;
1620
1826
  } catch (error) {
@@ -1625,71 +1831,122 @@ function createNestedToolTask(name) {
1625
1831
  });
1626
1832
  if (block !== undefined)
1627
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
+ }
1628
1840
  try {
1629
- args = checked(tool, call, args);
1841
+ args = copyJson11(checked(tool, call, args), {
1842
+ omitUndefinedProperties: true
1843
+ });
1630
1844
  } catch (error) {
1631
1845
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1632
1846
  }
1633
- await runtime.commit(async (tx) => {
1634
- await tx.doc(InvocationDoc, runtime.taskId);
1635
- await forwardCall(tx, task.input.cellId, {
1636
- callId: call.id,
1637
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1638
- name: call.name,
1639
- arguments: args,
1640
- status: "running",
1641
- result: null,
1642
- omittedFields: []
1643
- });
1644
- return {
1645
- status: "running",
1646
- checkpoint: {
1647
- phase: "execute",
1648
- arguments: args,
1649
- replay: tool.replay ?? "unsafe"
1650
- }
1651
- };
1847
+ await startAttempt(runtime, call, tool, agent, {
1848
+ arguments: args,
1849
+ replay: tool.replay ?? "unsafe"
1652
1850
  }, context);
1653
- 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);
1654
1864
  },
1655
1865
  execute: async (task, runtime, context) => {
1866
+ const intent = task.state.checkpoint;
1656
1867
  const call = nestedCall(runtime, task.input);
1657
1868
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1658
1869
  call.arguments = task.state.checkpoint.arguments;
1659
1870
  const agent = await runtime.agent(context);
1660
1871
  const tool = agent.callable.find((each) => each.name === call.name);
1661
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1662
- await runtime.commit(async (tx) => {
1663
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1664
- doc.result = {};
1665
- doc.droppedBytes = 0;
1666
- doc.droppedLines = 0;
1667
- return;
1668
- }, context);
1669
- 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);
1670
1882
  }
1883
+ if (intent.resume !== undefined)
1884
+ await cancelParkedTool(runtime, tool, intent, context);
1671
1885
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1672
1886
  }
1673
1887
  },
1674
1888
  abort: async (task, runtime, context) => {
1675
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
+ }
1676
1896
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1677
1897
  }
1678
1898
  });
1679
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
+ }
1680
1923
  async function reject(runtime, call, result, agent, tool, context) {
1681
1924
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1682
1925
  result = await handler(call, result, runtime, context) ?? result;
1683
1926
  });
1684
1927
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1685
1928
  }
1686
- async function run(runtime, call, tool, args, agent, context) {
1929
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1687
1930
  let invocation;
1688
1931
  let result;
1689
1932
  let ending = "completed";
1690
1933
  try {
1691
- invocation = createInvocation(runtime, tool, context);
1692
- 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
+ }
1693
1950
  } catch (error) {
1694
1951
  if (runtime.signal.aborted) {
1695
1952
  await invocation?.stop(error);
@@ -1741,7 +1998,7 @@ function finishResult(tool, name, result) {
1741
1998
  } else if (final.structuredOutput === undefined) {
1742
1999
  if (!final.isError)
1743
2000
  throw new Error(`Tool ${name} returned no structuredOutput`);
1744
- } else if (!Compile2(tool.structuredOutputSchema).Check(final.structuredOutput)) {
2001
+ } else if (!compile2(tool.structuredOutputSchema).check(final.structuredOutput)) {
1745
2002
  throw new Error(`Tool ${name} returned structuredOutput that does not match its schema`);
1746
2003
  }
1747
2004
  } catch (error) {
@@ -1790,9 +2047,11 @@ function providerProjection(surfaceTools) {
1790
2047
  const conversation = await host.conversation(api.conversationId, context);
1791
2048
  if (conversation === undefined)
1792
2049
  throw new Error(`Conversation ${api.conversationId} is unavailable`);
1793
- for (const tool of (await conversation.agent(context)).tools)
1794
- 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)
1795
2053
  visible.add(tool.name);
2054
+ }
1796
2055
  }
1797
2056
  return { messages: projectToolSchemas(request.messages, visible) };
1798
2057
  }
@@ -1801,7 +2060,7 @@ function providerProjection(surfaceTools) {
1801
2060
  }
1802
2061
 
1803
2062
  // packages/execution/src/wait-session.ts
1804
- import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
2063
+ import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
1805
2064
 
1806
2065
  // packages/execution/src/tool-value.ts
1807
2066
  class NestedToolError extends Error {
@@ -1872,7 +2131,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
1872
2131
  }, context);
1873
2132
  let cancelling;
1874
2133
  const abort = () => {
1875
- cancelling ??= cancelTask(id, withoutAbortSignal3(context));
2134
+ cancelling ??= cancelTask(id, withoutAbortSignal4(context));
1876
2135
  cancelling.catch(() => {});
1877
2136
  };
1878
2137
  context.abortSignal?.addEventListener("abort", abort, { once: true });
@@ -1956,7 +2215,7 @@ function createCellCoordinator(options) {
1956
2215
  if (driver.closed)
1957
2216
  throw new Error("Execution host is closed");
1958
2217
  assertSingleExecutionMode(await api.agent(context));
1959
- const copied = copyJson10(input);
2218
+ const copied = copyJson12(input);
1960
2219
  return api.commit(async (tx) => {
1961
2220
  const isolatedLimit = options.isolatedConcurrency ?? 0;
1962
2221
  const isolated = isolatedLimit > 0 && input["isolated"] === true;
@@ -2036,7 +2295,7 @@ function createCellCoordinator(options) {
2036
2295
  if (yielding.consume()) {
2037
2296
  return initial;
2038
2297
  }
2039
- const wait = withCancel(context);
2298
+ const wait = withCancel2(context);
2040
2299
  const timeout = new Error("Cell observation yielded");
2041
2300
  const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
2042
2301
  try {
@@ -2269,7 +2528,7 @@ function moduleCode(request, limits, invoke) {
2269
2528
  }
2270
2529
 
2271
2530
  // packages/worker-code/src/output.ts
2272
- import { copyJson as copyJson11 } from "@earendil-works/chord";
2531
+ import { copyJson as copyJson13 } from "@earendil-works/chord/json";
2273
2532
  function guestContent(kind, value) {
2274
2533
  if (kind === "text")
2275
2534
  return {
@@ -2321,7 +2580,7 @@ function observeWorkerCell(observation, maxTokens, delivered) {
2321
2580
  ...fields,
2322
2581
  cellId: observation.cellId,
2323
2582
  ...observation.forwardedToolCalls === undefined ? {} : {
2324
- forwardedToolCalls: copyJson11(observation.forwardedToolCalls, {
2583
+ forwardedToolCalls: copyJson13(observation.forwardedToolCalls, {
2325
2584
  omitUndefinedProperties: true
2326
2585
  })
2327
2586
  },
@@ -2563,7 +2822,7 @@ class WorkerRuntime {
2563
2822
  };
2564
2823
  const result = await this.evaluate(input["code"], modules, api.signal, {
2565
2824
  tools: api.tools,
2566
- inventory: api.registrations.map(readToolContract).map((tool) => ({
2825
+ inventory: api.registrations.map(readToolContract).filter((tool) => !tool.nestedHidden).map((tool) => ({
2567
2826
  name: tool.name,
2568
2827
  description: tool.description,
2569
2828
  parameters: tool.inputSchema,
@@ -2725,8 +2984,9 @@ function createWorkerCode(options) {
2725
2984
  tools: [exec, wait],
2726
2985
  sections: [
2727
2986
  section("worker-code", (input) => [
2987
+ nestedToolDiscoveryGuidance,
2728
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.",
2729
- ...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)
2730
2990
  ].join(`
2731
2991
  `))
2732
2992
  ]