@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.
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";
@@ -983,8 +1043,14 @@ async function observeCellProgress(id, api, context, budget) {
983
1043
  return work;
984
1044
  };
985
1045
  const live = await api.watchDoc(LiveDoc3, api.conversationId, context);
986
- cell.start((value) => own(() => publish(value)));
987
- live?.start(() => own(async () => {
1046
+ cell.start((call) => own(async () => {
1047
+ if (call.kind === "failed")
1048
+ throw call.error;
1049
+ await publish(call.value);
1050
+ }));
1051
+ live?.start((call) => own(async () => {
1052
+ if (call.kind === "failed")
1053
+ throw call.error;
988
1054
  await api.commit(async (tx) => {
989
1055
  const record = await tx.task(id);
990
1056
  if (record === undefined || record.state.status === "terminal")
@@ -1004,14 +1070,14 @@ async function observeCellProgress(id, api, context, budget) {
1004
1070
  const endings = await Promise.all([cell.stop(), live?.stop()]);
1005
1071
  await Promise.all([...pending]);
1006
1072
  for (const ending of endings)
1007
- if (ending?.reason === "listener_error")
1073
+ if (ending?.kind === "listener_error" || ending?.kind === "failed")
1008
1074
  throw ending.error;
1009
1075
  };
1010
1076
  }
1011
1077
 
1012
1078
  // packages/execution/src/cell-task.ts
1013
- import { copyJson as copyJson8 } from "@earendil-works/chord";
1014
1079
  import { withAbortSignal } from "@earendil-works/chord/context";
1080
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
1015
1081
  import {
1016
1082
  defineTask
1017
1083
  } from "@earendil-works/pi-durable";
@@ -1033,7 +1099,18 @@ function combineControls(controls, allowTermination = true) {
1033
1099
  }
1034
1100
 
1035
1101
  // packages/execution/src/tool-contract.ts
1036
- 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
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 {}";
1037
1114
  function readToolContract(tool) {
1038
1115
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
1039
1116
  if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
@@ -1047,6 +1124,7 @@ function readToolContract(tool) {
1047
1124
  "yieldTimeMs",
1048
1125
  "inputSchema",
1049
1126
  "nativeOnly",
1127
+ "nestedHidden",
1050
1128
  "discovery"
1051
1129
  ]);
1052
1130
  for (const key of Object.keys(hints))
@@ -1070,6 +1148,12 @@ function readToolContract(tool) {
1070
1148
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1071
1149
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1072
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`);
1073
1157
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1074
1158
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1075
1159
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1086,6 +1170,8 @@ function readToolContract(tool) {
1086
1170
  inputSchema,
1087
1171
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1088
1172
  nativeOnly: nativeOnly === true,
1173
+ nestedHidden: nestedHidden === true,
1174
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1089
1175
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1090
1176
  ...outputHint === undefined ? {} : { output: outputHint },
1091
1177
  help: [
@@ -1321,7 +1407,7 @@ function createCellTask(options, nestedTask) {
1321
1407
  import {
1322
1408
  hook,
1323
1409
  LiveDoc as LiveDoc4,
1324
- ToolTask as ToolTask3
1410
+ ToolTask as ToolTask4
1325
1411
  } from "@earendil-works/pi-durable";
1326
1412
  function forwardingHook() {
1327
1413
  let host;
@@ -1331,7 +1417,7 @@ function forwardingHook() {
1331
1417
  throw new Error("Create a separate execution component for each Harness");
1332
1418
  host = harness;
1333
1419
  },
1334
- hook: hook(ToolTask3, {
1420
+ hook: hook(ToolTask4, {
1335
1421
  async beforeTool(call, api, context) {
1336
1422
  const parent = call.parent;
1337
1423
  if (parent === undefined || host === undefined)
@@ -1344,7 +1430,7 @@ function forwardingHook() {
1344
1430
  if (conversation === undefined)
1345
1431
  throw new Error("Forwarded call conversation is unavailable");
1346
1432
  await conversation.commit(async (tx) => {
1347
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1433
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1348
1434
  return;
1349
1435
  const owner = await tx.doc(InvocationDoc, api.taskId);
1350
1436
  const admission = owner.forwardingCellId === undefined;
@@ -1371,7 +1457,7 @@ function forwardingHook() {
1371
1457
  if (conversation === undefined)
1372
1458
  throw new Error("Forwarded call conversation is unavailable");
1373
1459
  await conversation.commit(async (tx) => {
1374
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1460
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1375
1461
  return;
1376
1462
  const owner = await tx.doc(InvocationDoc, api.taskId);
1377
1463
  const cellId = owner.forwardingCellId;
@@ -1396,17 +1482,18 @@ function forwardingHook() {
1396
1482
  }
1397
1483
 
1398
1484
  // packages/execution/src/nested.ts
1485
+ import { copyJson as copyJson11 } from "@earendil-works/chord/json";
1399
1486
  import {
1400
1487
  defineTask as defineTask2
1401
1488
  } from "@earendil-works/pi-durable";
1402
- import { Compile as Compile2 } from "typebox/compile";
1489
+ import { compile as compile2 } from "@earendil-works/pi-schema";
1403
1490
 
1404
1491
  // packages/execution/src/nested-call.ts
1405
1492
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1406
1493
  import {
1407
- ToolTask as ToolTask4
1494
+ ToolTask as ToolTask5
1408
1495
  } from "@earendil-works/pi-durable";
1409
- import { Compile } from "typebox/compile";
1496
+ import { compile } from "@earendil-works/pi-schema";
1410
1497
  function nestedCall(runtime, input) {
1411
1498
  const args = input.arguments;
1412
1499
  return {
@@ -1427,7 +1514,7 @@ function prepareNestedInput(tool, input) {
1427
1514
  if (typeof input !== "string")
1428
1515
  return input;
1429
1516
  const contract = readToolContract(tool);
1430
- if (Boolean(Compile(tool.parameters).Check(input)) || Boolean(Compile(contract.inputSchema).Check(input)))
1517
+ 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)))
1431
1518
  return input;
1432
1519
  const text = input.trim();
1433
1520
  if (contract.discovery === "help" && text === "help")
@@ -1450,7 +1537,7 @@ function prepareNestedInput(tool, input) {
1450
1537
  async function eachHook(agent, name, api, invoke) {
1451
1538
  for (const extension of agent.extensions)
1452
1539
  for (const registration of extension.hooks ?? []) {
1453
- if (registration.task !== ToolTask4.definition.name)
1540
+ if (registration.task !== ToolTask5.definition.name)
1454
1541
  continue;
1455
1542
  const handler = registration.handlers[name];
1456
1543
  if (handler === undefined)
@@ -1465,8 +1552,120 @@ async function eachHook(agent, name, api, invoke) {
1465
1552
  }
1466
1553
  }
1467
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
+
1468
1667
  // packages/execution/src/nested-result.ts
1469
- import { copyJson as copyJson9 } from "@earendil-works/chord";
1668
+ import { copyJson as copyJson10 } from "@earendil-works/chord/json";
1470
1669
  import {
1471
1670
  defineEntry,
1472
1671
  UsageDoc
@@ -1514,11 +1713,11 @@ async function settle(runtime, call, result, ending, context) {
1514
1713
  taskId: runtime.taskId,
1515
1714
  callId: call.id,
1516
1715
  name: call.name,
1517
- arguments: copyJson9(call.arguments),
1716
+ arguments: copyJson10(call.arguments),
1518
1717
  result: stored,
1519
1718
  ...current.state.checkpoint.phase === "execute" ? {
1520
1719
  intent: {
1521
- arguments: copyJson9(current.state.checkpoint.arguments),
1720
+ arguments: copyJson10(current.state.checkpoint.arguments),
1522
1721
  replay: current.state.checkpoint.replay
1523
1722
  }
1524
1723
  } : {}
@@ -1527,7 +1726,7 @@ async function settle(runtime, call, result, ending, context) {
1527
1726
  if (result.usage !== undefined) {
1528
1727
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1529
1728
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1530
- 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 });
1531
1730
  }
1532
1731
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1533
1732
  status: ending,
@@ -1564,7 +1763,11 @@ function sumUsage(previous, added) {
1564
1763
  function createNestedToolTask(name) {
1565
1764
  return defineTask2({
1566
1765
  name,
1567
- version: 1,
1766
+ version: 2,
1767
+ migrate: (input, checkpoint) => ({
1768
+ input,
1769
+ checkpoint
1770
+ }),
1568
1771
  initial: () => ({ phase: "call" }),
1569
1772
  phases: {
1570
1773
  call: async (task, runtime, context) => {
@@ -1590,22 +1793,25 @@ function createNestedToolTask(name) {
1590
1793
  return reject(runtime, call, executionError("tool_unavailable", `Tool ${call.name} is not available`), agent, tool, context);
1591
1794
  let args;
1592
1795
  try {
1593
- const supplied = task.input.arguments === null && !Compile2(tool.parameters).Check(null) && Compile2(tool.parameters).Check({}) ? undefined : task.input.arguments;
1796
+ const supplied = task.input.arguments === null && !compile2(tool.parameters).check(null) && compile2(tool.parameters).check({}) ? undefined : task.input.arguments;
1594
1797
  const prepared = tool.prepareArguments === undefined ? prepareNestedInput(tool, supplied) : tool.prepareArguments(prepareNestedInput(tool, supplied));
1595
- args = checked(tool, call, prepared === undefined && Compile2(tool.parameters).Check({}) ? {} : prepared);
1798
+ args = checked(tool, call, prepared === undefined && compile2(tool.parameters).check({}) ? {} : prepared);
1596
1799
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1597
1800
  call.arguments = args;
1598
1801
  } catch (error) {
1599
1802
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1600
1803
  }
1601
1804
  let block;
1805
+ let sleep;
1602
1806
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1603
- if (block !== undefined)
1807
+ if (block !== undefined || sleep !== undefined)
1604
1808
  return;
1605
1809
  try {
1606
1810
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1607
1811
  if (decision?.block !== undefined)
1608
1812
  block = decision.block;
1813
+ else if (decision?.sleep !== undefined)
1814
+ sleep = decision.sleep;
1609
1815
  else if (decision?.arguments !== undefined)
1610
1816
  args = decision.arguments;
1611
1817
  } catch (error) {
@@ -1616,71 +1822,122 @@ function createNestedToolTask(name) {
1616
1822
  });
1617
1823
  if (block !== undefined)
1618
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
+ }
1619
1831
  try {
1620
- args = checked(tool, call, args);
1832
+ args = copyJson11(checked(tool, call, args), {
1833
+ omitUndefinedProperties: true
1834
+ });
1621
1835
  } catch (error) {
1622
1836
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1623
1837
  }
1624
- await runtime.commit(async (tx) => {
1625
- await tx.doc(InvocationDoc, runtime.taskId);
1626
- await forwardCall(tx, task.input.cellId, {
1627
- callId: call.id,
1628
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1629
- name: call.name,
1630
- arguments: args,
1631
- status: "running",
1632
- result: null,
1633
- omittedFields: []
1634
- });
1635
- return {
1636
- status: "running",
1637
- checkpoint: {
1638
- phase: "execute",
1639
- arguments: args,
1640
- replay: tool.replay ?? "unsafe"
1641
- }
1642
- };
1838
+ await startAttempt(runtime, call, tool, agent, {
1839
+ arguments: args,
1840
+ replay: tool.replay ?? "unsafe"
1643
1841
  }, context);
1644
- 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);
1645
1855
  },
1646
1856
  execute: async (task, runtime, context) => {
1857
+ const intent = task.state.checkpoint;
1647
1858
  const call = nestedCall(runtime, task.input);
1648
1859
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1649
1860
  call.arguments = task.state.checkpoint.arguments;
1650
1861
  const agent = await runtime.agent(context);
1651
1862
  const tool = agent.callable.find((each) => each.name === call.name);
1652
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1653
- await runtime.commit(async (tx) => {
1654
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1655
- doc.result = {};
1656
- doc.droppedBytes = 0;
1657
- doc.droppedLines = 0;
1658
- return;
1659
- }, context);
1660
- 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);
1661
1873
  }
1874
+ if (intent.resume !== undefined)
1875
+ await cancelParkedTool(runtime, tool, intent, context);
1662
1876
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1663
1877
  }
1664
1878
  },
1665
1879
  abort: async (task, runtime, context) => {
1666
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
+ }
1667
1887
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1668
1888
  }
1669
1889
  });
1670
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
+ }
1671
1914
  async function reject(runtime, call, result, agent, tool, context) {
1672
1915
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1673
1916
  result = await handler(call, result, runtime, context) ?? result;
1674
1917
  });
1675
1918
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1676
1919
  }
1677
- async function run(runtime, call, tool, args, agent, context) {
1920
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1678
1921
  let invocation;
1679
1922
  let result;
1680
1923
  let ending = "completed";
1681
1924
  try {
1682
- invocation = createInvocation(runtime, tool, context);
1683
- 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
+ }
1684
1941
  } catch (error) {
1685
1942
  if (runtime.signal.aborted) {
1686
1943
  await invocation?.stop(error);
@@ -1732,7 +1989,7 @@ function finishResult(tool, name, result) {
1732
1989
  } else if (final.structuredOutput === undefined) {
1733
1990
  if (!final.isError)
1734
1991
  throw new Error(`Tool ${name} returned no structuredOutput`);
1735
- } else if (!Compile2(tool.structuredOutputSchema).Check(final.structuredOutput)) {
1992
+ } else if (!compile2(tool.structuredOutputSchema).check(final.structuredOutput)) {
1736
1993
  throw new Error(`Tool ${name} returned structuredOutput that does not match its schema`);
1737
1994
  }
1738
1995
  } catch (error) {
@@ -1781,9 +2038,11 @@ function providerProjection(surfaceTools) {
1781
2038
  const conversation = await host.conversation(api.conversationId, context);
1782
2039
  if (conversation === undefined)
1783
2040
  throw new Error(`Conversation ${api.conversationId} is unavailable`);
1784
- for (const tool of (await conversation.agent(context)).tools)
1785
- 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)
1786
2044
  visible.add(tool.name);
2045
+ }
1787
2046
  }
1788
2047
  return { messages: projectToolSchemas(request.messages, visible) };
1789
2048
  }
@@ -1792,7 +2051,7 @@ function providerProjection(surfaceTools) {
1792
2051
  }
1793
2052
 
1794
2053
  // packages/execution/src/wait-session.ts
1795
- import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
2054
+ import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
1796
2055
 
1797
2056
  // packages/execution/src/tool-value.ts
1798
2057
  class NestedToolError extends Error {
@@ -1863,7 +2122,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
1863
2122
  }, context);
1864
2123
  let cancelling;
1865
2124
  const abort = () => {
1866
- cancelling ??= cancelTask(id, withoutAbortSignal3(context));
2125
+ cancelling ??= cancelTask(id, withoutAbortSignal4(context));
1867
2126
  cancelling.catch(() => {});
1868
2127
  };
1869
2128
  context.abortSignal?.addEventListener("abort", abort, { once: true });
@@ -1947,7 +2206,7 @@ function createCellCoordinator(options) {
1947
2206
  if (driver.closed)
1948
2207
  throw new Error("Execution host is closed");
1949
2208
  assertSingleExecutionMode(await api.agent(context));
1950
- const copied = copyJson10(input);
2209
+ const copied = copyJson12(input);
1951
2210
  return api.commit(async (tx) => {
1952
2211
  const isolatedLimit = options.isolatedConcurrency ?? 0;
1953
2212
  const isolated = isolatedLimit > 0 && input["isolated"] === true;
@@ -2027,7 +2286,7 @@ function createCellCoordinator(options) {
2027
2286
  if (yielding.consume()) {
2028
2287
  return initial;
2029
2288
  }
2030
- const wait = withCancel(context);
2289
+ const wait = withCancel2(context);
2031
2290
  const timeout = new Error("Cell observation yielded");
2032
2291
  const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
2033
2292
  try {
@@ -2260,7 +2519,7 @@ function moduleCode(request, limits, invoke) {
2260
2519
  }
2261
2520
 
2262
2521
  // packages/worker-code/src/output.ts
2263
- import { copyJson as copyJson11 } from "@earendil-works/chord";
2522
+ import { copyJson as copyJson13 } from "@earendil-works/chord/json";
2264
2523
  function guestContent(kind, value) {
2265
2524
  if (kind === "text")
2266
2525
  return {
@@ -2312,7 +2571,7 @@ function observeWorkerCell(observation, maxTokens, delivered) {
2312
2571
  ...fields,
2313
2572
  cellId: observation.cellId,
2314
2573
  ...observation.forwardedToolCalls === undefined ? {} : {
2315
- forwardedToolCalls: copyJson11(observation.forwardedToolCalls, {
2574
+ forwardedToolCalls: copyJson13(observation.forwardedToolCalls, {
2316
2575
  omitUndefinedProperties: true
2317
2576
  })
2318
2577
  },
@@ -2554,7 +2813,7 @@ class WorkerRuntime {
2554
2813
  };
2555
2814
  const result = await this.evaluate(input["code"], modules, api.signal, {
2556
2815
  tools: api.tools,
2557
- inventory: api.registrations.map(readToolContract).map((tool) => ({
2816
+ inventory: api.registrations.map(readToolContract).filter((tool) => !tool.nestedHidden).map((tool) => ({
2558
2817
  name: tool.name,
2559
2818
  description: tool.description,
2560
2819
  parameters: tool.inputSchema,
@@ -2715,8 +2974,9 @@ function createWorkerCode(options) {
2715
2974
  tools: [exec, wait],
2716
2975
  sections: [
2717
2976
  section("worker-code", (input) => [
2977
+ nestedToolDiscoveryGuidance,
2718
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.",
2719
- ...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)
2720
2980
  ].join(`
2721
2981
  `))
2722
2982
  ]