@howaboua/pi-durable-js-notebook 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
@@ -1,5 +1,5 @@
1
1
  // packages/js-notebook/src/index.ts
2
- import { copyJson as copyJson13 } from "@earendil-works/chord";
2
+ import { copyJson as copyJson15 } from "@earendil-works/chord/json";
3
3
  import {
4
4
  defineExtension as defineExtension3,
5
5
  defineTool as defineTool3,
@@ -70,8 +70,8 @@ function parseInteger(value, name, minimum = 0, maximum = Number.MAX_SAFE_INTEGE
70
70
  }
71
71
 
72
72
  // packages/execution/src/cells.ts
73
- import { copyJson as copyJson10 } from "@earendil-works/chord";
74
- import { withCancel } from "@earendil-works/chord/context";
73
+ import { withCancel as withCancel2 } from "@earendil-works/chord/context";
74
+ import { copyJson as copyJson12 } from "@earendil-works/chord/json";
75
75
  import {
76
76
  defineExtension
77
77
  } from "@earendil-works/pi-durable";
@@ -82,7 +82,7 @@ import {
82
82
  } from "@earendil-works/pi-durable";
83
83
 
84
84
  // packages/execution/src/forwarding.ts
85
- import { copyJson as copyJson2 } from "@earendil-works/chord";
85
+ import { copyJson as copyJson2 } from "@earendil-works/chord/json";
86
86
  import {
87
87
  LiveDoc,
88
88
  NestedCallDoc,
@@ -92,7 +92,7 @@ import {
92
92
  // packages/execution/src/invocation-state.ts
93
93
  import {
94
94
  copyJson
95
- } from "@earendil-works/chord";
95
+ } from "@earendil-works/chord/json";
96
96
  import {
97
97
  defineDoc
98
98
  } from "@earendil-works/pi-durable";
@@ -569,7 +569,7 @@ async function observeCell(kind, id, api, context, budget) {
569
569
  }
570
570
 
571
571
  // packages/execution/src/cell-progress.ts
572
- import { copyJson as copyJson3 } from "@earendil-works/chord";
572
+ import { copyJson as copyJson3 } from "@earendil-works/chord/json";
573
573
  import {
574
574
  LiveDoc as LiveDoc2
575
575
  } from "@earendil-works/pi-durable";
@@ -629,37 +629,64 @@ async function observeCellProgress(id, api, context, budget) {
629
629
  }
630
630
 
631
631
  // packages/execution/src/cell-task.ts
632
- import { copyJson as copyJson8 } from "@earendil-works/chord";
633
632
  import { withAbortSignal } from "@earendil-works/chord/context";
633
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
634
634
  import {
635
635
  defineTask
636
636
  } from "@earendil-works/pi-durable";
637
637
 
638
638
  // packages/execution/src/cell-tools.ts
639
- import { copyJson as copyJson6 } from "@earendil-works/chord";
640
639
  import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
640
+ import { copyJson as copyJson6 } from "@earendil-works/chord/json";
641
641
 
642
642
  // packages/execution/src/invocation.ts
643
- import { copyJson as copyJson5 } from "@earendil-works/chord";
644
643
  import { awaitWithContext } from "@earendil-works/chord/context";
644
+ import { copyJson as copyJson5 } from "@earendil-works/chord/json";
645
+ import {
646
+ NestedCallDoc as NestedCallDoc3
647
+ } from "@earendil-works/pi-durable";
648
+ import { equal } from "@earendil-works/pi-schema";
645
649
 
646
650
  // packages/execution/src/native-tools.ts
647
- import { copyJson as copyJson4 } from "@earendil-works/chord";
648
- import { withoutAbortSignal } from "@earendil-works/chord/context";
651
+ import {
652
+ withoutAbortSignal
653
+ } from "@earendil-works/chord/context";
654
+ import { copyJson as copyJson4 } from "@earendil-works/chord/json";
649
655
  import {
650
656
  LiveDoc as LiveDoc3,
651
657
  NestedCallDoc as NestedCallDoc2,
652
- ToolTask as ToolTask2
658
+ ToolTask as ToolTask3
653
659
  } from "@earendil-works/pi-durable";
654
660
  import { Equal } from "typebox/value";
655
- function nativeToolCalls(runtime, callId, replay, assertLive, context) {
661
+
662
+ // packages/execution/src/tool-origin.ts
663
+ import {
664
+ defineDoc as defineDoc2,
665
+ ToolTask as ToolTask2
666
+ } from "@earendil-works/pi-durable";
667
+ var ToolOriginDoc = defineDoc2({
668
+ kind: "howaboua.tool-origin",
669
+ version: 1,
670
+ scope: "task",
671
+ checkpointWhen: () => false,
672
+ initial: () => ({})
673
+ });
674
+
675
+ // packages/execution/src/native-tools.ts
676
+ function assertNestedKey(key) {
677
+ if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
678
+ throw new Error("Invalid nested call or task key");
679
+ }
680
+ function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
656
681
  let sequence = 0;
657
682
  const admissions = [];
658
- const execute = async (name, args, callContext, options = {}) => {
683
+ async function execute(name, args, callContext, options = {}) {
659
684
  assertLive();
685
+ if (options.key !== undefined)
686
+ assertNestedKey(options.key);
687
+ else if (resumed)
688
+ throw new Error("Nested calls require an explicit key after waking");
660
689
  const key = options.key ?? String(++sequence);
661
- if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
662
- throw new Error("Invalid nested call key");
663
690
  const call = {
664
691
  type: "toolCall",
665
692
  id: `${callId}/${key}`,
@@ -671,11 +698,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
671
698
  const admission = runtime.commit(async (tx) => {
672
699
  const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
673
700
  if (slot.taskId !== undefined) {
674
- const input = (await tx.task(slot.taskId))?.input;
701
+ const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
675
702
  if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
676
703
  throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
677
704
  } else {
678
- slot.taskId = await tx.createTask(ToolTask2, {
705
+ slot.kind = "nested";
706
+ slot.taskId = await tx.createTask(ToolTask3, {
679
707
  kind: "nested",
680
708
  parent: runtime.taskId,
681
709
  parentCallId: callId,
@@ -687,6 +715,9 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
687
715
  abandonOnRestart: replay !== "safe"
688
716
  });
689
717
  const live = await tx.doc(LiveDoc3, runtime.conversationId);
718
+ const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
719
+ if (origin)
720
+ (await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
690
721
  live.nestedTools ??= [];
691
722
  live.nestedTools.push({
692
723
  callId: call.id,
@@ -718,7 +749,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
718
749
  const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
719
750
  if (slot?.taskId === undefined)
720
751
  throw new Error("Nested task creation did not commit");
721
- const settled = await runtime.waitForTask(slot.taskId, callContext);
752
+ const taskId = slot.taskId;
753
+ const result = (resultContext) => readResult(name, key, taskId, resultContext);
754
+ return options.wait === false ? { taskId, result } : result(callContext);
755
+ }
756
+ async function readResult(name, key, taskId, callContext) {
757
+ assertLive();
758
+ const settled = await runtime.waitForTask(taskId, callContext);
722
759
  const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
723
760
  await runtime.commit(async (tx) => {
724
761
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
@@ -726,7 +763,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
726
763
  return;
727
764
  }, callContext);
728
765
  return result === undefined ? {
729
- taskId: slot.taskId,
766
+ taskId,
730
767
  isError: true,
731
768
  diagnostics: [
732
769
  {
@@ -736,9 +773,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
736
773
  }
737
774
  ]
738
775
  } : copyJson4(result);
739
- };
776
+ }
740
777
  return {
741
778
  execute,
779
+ async drain() {
780
+ await Promise.allSettled(admissions);
781
+ },
742
782
  async finish() {
743
783
  await Promise.allSettled(admissions);
744
784
  await cleanupNativeCalls(runtime, withoutAbortSignal(context));
@@ -746,7 +786,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
746
786
  };
747
787
  }
748
788
  async function cleanupNativeCalls(runtime, context) {
749
- await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
789
+ await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
750
790
  await runtime.commit(async (tx) => {
751
791
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
752
792
  await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
@@ -840,18 +880,6 @@ class Progress {
840
880
  }
841
881
  }
842
882
 
843
- // packages/execution/src/tool-origin.ts
844
- import {
845
- defineDoc as defineDoc2
846
- } from "@earendil-works/pi-durable";
847
- var ToolOriginDoc = defineDoc2({
848
- kind: "howaboua.tool-origin",
849
- version: 1,
850
- scope: "task",
851
- checkpointWhen: () => false,
852
- initial: () => ({})
853
- });
854
-
855
883
  // packages/execution/src/invocation.ts
856
884
  function executionError(code, message) {
857
885
  return {
@@ -863,21 +891,23 @@ function executionError(code, message) {
863
891
  function errorText(error) {
864
892
  return error instanceof Error ? error.message : String(error);
865
893
  }
866
- function createInvocation(runtime, tool, context) {
894
+ function createInvocation(runtime, tool, context, resume) {
867
895
  const limits = {
868
896
  maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
869
897
  maxLines: tool.outputLimits?.maxLines ?? 2000,
870
898
  retain: tool.outputLimits?.retain ?? "head"
871
899
  };
872
900
  const output = new OutputBuffer(limits);
873
- const diagnostics = [];
874
- let details;
901
+ const diagnostics = [
902
+ ...resume?.progress?.diagnostics ?? []
903
+ ];
904
+ let details = resume?.progress?.details;
875
905
  let ended = false;
876
906
  const assertLive = () => {
877
907
  if (ended)
878
908
  throw new Error(`Invocation ${runtime.taskId} has settled`);
879
909
  };
880
- const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
910
+ const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
881
911
  const snapshot = () => {
882
912
  const retained = output.snapshot();
883
913
  return {
@@ -906,6 +936,8 @@ function createInvocation(runtime, tool, context) {
906
936
  taskId: runtime.taskId,
907
937
  conversationId: runtime.conversationId,
908
938
  callId: `nested-${runtime.taskId}`,
939
+ wake: resume?.wake,
940
+ checkpoint: resume?.checkpoint,
909
941
  registry: runtime.registry,
910
942
  agent: runtime.agent,
911
943
  env: undefined,
@@ -926,7 +958,7 @@ function createInvocation(runtime, tool, context) {
926
958
  const retained = output.snapshot();
927
959
  return { text: retained.text, truncated: retained.droppedBytes > 0 };
928
960
  },
929
- executeTool: (...args) => native.execute(...args),
961
+ executeTool: native.execute,
930
962
  diagnostic: (value) => {
931
963
  assertLive();
932
964
  diagnostics.push(copyJson5(value, { omitUndefinedProperties: true }));
@@ -940,24 +972,44 @@ function createInvocation(runtime, tool, context) {
940
972
  committed.catch(() => {});
941
973
  await awaitWithContext(committed, detailContext);
942
974
  },
943
- commit: async (change, commitContext) => {
975
+ commit: async (change, commitContext, options) => {
944
976
  assertLive();
945
977
  let result;
946
978
  await runtime.commit(async (tx) => {
947
979
  result = await change(tx);
948
980
  return;
949
- }, commitContext);
981
+ }, commitContext, options);
950
982
  return result;
951
983
  },
952
984
  memo: runtime.memo,
953
- createTask: async (task, input, options, taskContext) => {
985
+ readSignal: runtime.readSignal,
986
+ async createTask(task, input, {
987
+ key,
988
+ ...options
989
+ }, taskContext) {
954
990
  assertLive();
991
+ if (key !== undefined)
992
+ assertNestedKey(key);
993
+ else if (resume?.wake !== undefined)
994
+ throw new Error("Child tasks require an explicit key after waking");
955
995
  let id;
956
996
  await runtime.commit(async (tx) => {
997
+ const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
998
+ if (member?.taskId !== undefined) {
999
+ const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
1000
+ if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson5(input, { omitUndefinedProperties: true })))
1001
+ throw new Error(`Key ${key} was already used for another call or task`);
1002
+ id = member.taskId;
1003
+ return;
1004
+ }
957
1005
  id = await tx.createTask(task, input, {
958
1006
  ...options,
959
1007
  ...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
960
1008
  });
1009
+ if (member !== undefined) {
1010
+ member.kind = "task";
1011
+ member.taskId = id;
1012
+ }
961
1013
  const source = await tx.doc(ToolOriginDoc, runtime.taskId);
962
1014
  if (source.origin !== undefined)
963
1015
  (await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
@@ -1004,6 +1056,14 @@ function createInvocation(runtime, tool, context) {
1004
1056
  for (const waiter of await progress.stop())
1005
1057
  waiter.reject(error);
1006
1058
  },
1059
+ async park() {
1060
+ ended = true;
1061
+ await native.drain();
1062
+ output.end();
1063
+ const pending = await progress.stop();
1064
+ const { output: _output, ...kept } = snapshot();
1065
+ return { progress: storeResult(kept), pending };
1066
+ },
1007
1067
  limits,
1008
1068
  output,
1009
1069
  progress
@@ -1105,7 +1165,17 @@ function combineControls(controls, allowTermination = true) {
1105
1165
  }
1106
1166
 
1107
1167
  // packages/execution/src/tool-contract.ts
1108
- import { copyJson as copyJson7 } from "@earendil-works/chord";
1168
+ import { copyJson as copyJson7 } from "@earendil-works/chord/json";
1169
+
1170
+ // packages/execution/src/tool-namespaces.ts
1171
+ import { isJsonValue } from "@earendil-works/chord/json";
1172
+ function validateJsToolNamespace(tool, namespace) {
1173
+ const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
1174
+ 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))))
1175
+ throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
1176
+ }
1177
+
1178
+ // packages/execution/src/tool-contract.ts
1109
1179
  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 {}";
1110
1180
  function readToolContract(tool) {
1111
1181
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
@@ -1120,6 +1190,7 @@ function readToolContract(tool) {
1120
1190
  "yieldTimeMs",
1121
1191
  "inputSchema",
1122
1192
  "nativeOnly",
1193
+ "nestedHidden",
1123
1194
  "discovery"
1124
1195
  ]);
1125
1196
  for (const key of Object.keys(hints))
@@ -1143,6 +1214,12 @@ function readToolContract(tool) {
1143
1214
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1144
1215
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1145
1216
  throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
1217
+ const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
1218
+ const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
1219
+ if (jsNamespace !== undefined)
1220
+ validateJsToolNamespace(tool.name, jsNamespace);
1221
+ if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
1222
+ throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
1146
1223
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1147
1224
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1148
1225
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1159,6 +1236,8 @@ function readToolContract(tool) {
1159
1236
  inputSchema,
1160
1237
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1161
1238
  nativeOnly: nativeOnly === true,
1239
+ nestedHidden: nestedHidden === true,
1240
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1162
1241
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1163
1242
  ...outputHint === undefined ? {} : { output: outputHint },
1164
1243
  help: [
@@ -1394,7 +1473,7 @@ function createCellTask(options, nestedTask) {
1394
1473
  import {
1395
1474
  hook,
1396
1475
  LiveDoc as LiveDoc4,
1397
- ToolTask as ToolTask3
1476
+ ToolTask as ToolTask4
1398
1477
  } from "@earendil-works/pi-durable";
1399
1478
  function forwardingHook() {
1400
1479
  let host;
@@ -1404,7 +1483,7 @@ function forwardingHook() {
1404
1483
  throw new Error("Create a separate execution component for each Harness");
1405
1484
  host = harness;
1406
1485
  },
1407
- hook: hook(ToolTask3, {
1486
+ hook: hook(ToolTask4, {
1408
1487
  async beforeTool(call, api, context) {
1409
1488
  const parent = call.parent;
1410
1489
  if (parent === undefined || host === undefined)
@@ -1417,7 +1496,7 @@ function forwardingHook() {
1417
1496
  if (conversation === undefined)
1418
1497
  throw new Error("Forwarded call conversation is unavailable");
1419
1498
  await conversation.commit(async (tx) => {
1420
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1499
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1421
1500
  return;
1422
1501
  const owner = await tx.doc(InvocationDoc, api.taskId);
1423
1502
  const admission = owner.forwardingCellId === undefined;
@@ -1444,7 +1523,7 @@ function forwardingHook() {
1444
1523
  if (conversation === undefined)
1445
1524
  throw new Error("Forwarded call conversation is unavailable");
1446
1525
  await conversation.commit(async (tx) => {
1447
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1526
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1448
1527
  return;
1449
1528
  const owner = await tx.doc(InvocationDoc, api.taskId);
1450
1529
  const cellId = owner.forwardingCellId;
@@ -1469,6 +1548,7 @@ function forwardingHook() {
1469
1548
  }
1470
1549
 
1471
1550
  // packages/execution/src/nested.ts
1551
+ import { copyJson as copyJson11 } from "@earendil-works/chord/json";
1472
1552
  import {
1473
1553
  defineTask as defineTask2
1474
1554
  } from "@earendil-works/pi-durable";
@@ -1477,7 +1557,7 @@ import { compile as compile2 } from "@earendil-works/pi-schema";
1477
1557
  // packages/execution/src/nested-call.ts
1478
1558
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1479
1559
  import {
1480
- ToolTask as ToolTask4
1560
+ ToolTask as ToolTask5
1481
1561
  } from "@earendil-works/pi-durable";
1482
1562
  import { compile } from "@earendil-works/pi-schema";
1483
1563
  function nestedCall(runtime, input) {
@@ -1523,7 +1603,7 @@ function prepareNestedInput(tool, input) {
1523
1603
  async function eachHook(agent, name, api, invoke) {
1524
1604
  for (const extension of agent.extensions)
1525
1605
  for (const registration of extension.hooks ?? []) {
1526
- if (registration.task !== ToolTask4.definition.name)
1606
+ if (registration.task !== ToolTask5.definition.name)
1527
1607
  continue;
1528
1608
  const handler = registration.handlers[name];
1529
1609
  if (handler === undefined)
@@ -1538,8 +1618,120 @@ async function eachHook(agent, name, api, invoke) {
1538
1618
  }
1539
1619
  }
1540
1620
 
1621
+ // packages/execution/src/nested-park.ts
1622
+ import {
1623
+ withCancel,
1624
+ withoutAbortSignal as withoutAbortSignal3
1625
+ } from "@earendil-works/chord/context";
1626
+ import { copyJson as copyJson9 } from "@earendil-works/chord/json";
1627
+ var resultFields = [
1628
+ "output",
1629
+ "structuredOutput",
1630
+ "isError",
1631
+ "details",
1632
+ "diagnostics",
1633
+ "usage",
1634
+ "control"
1635
+ ];
1636
+ function sleepState(checkpoint, { until, signals }) {
1637
+ return {
1638
+ status: "sleeping",
1639
+ checkpoint,
1640
+ ...until === undefined ? {} : { until },
1641
+ ...signals === undefined ? {} : { signals }
1642
+ };
1643
+ }
1644
+ async function parkGate(runtime, sleep, context) {
1645
+ try {
1646
+ await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
1647
+ } catch (error) {
1648
+ runtime.signal.throwIfAborted();
1649
+ return errorText(error);
1650
+ }
1651
+ }
1652
+ async function parkTool(runtime, invocation, tool, args, park, context) {
1653
+ if (park.kind !== "sleep" && park.kind !== "wait")
1654
+ return "Unknown park kind";
1655
+ const mixed = resultFields.find((field) => (field in park));
1656
+ if (mixed !== undefined)
1657
+ return `A park cannot carry the result field ${mixed}`;
1658
+ const intent = {
1659
+ arguments: args,
1660
+ replay: tool.replay ?? "unsafe",
1661
+ ...park.checkpoint === undefined ? {} : { checkpoint: copyJson9(park.checkpoint) }
1662
+ };
1663
+ const { progress, pending } = await invocation.park();
1664
+ try {
1665
+ await runtime.commit(async (tx) => {
1666
+ if (park.kind === "wait") {
1667
+ for (const id of park.on)
1668
+ if ((await tx.task(id))?.owner !== runtime.taskId)
1669
+ throw new Error(`Task ${id} is not owned by the call`);
1670
+ }
1671
+ const checkpoint = { ...intent, phase: "parked" };
1672
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1673
+ doc.result = progress;
1674
+ doc.droppedBytes = 0;
1675
+ doc.droppedLines = 0;
1676
+ await forwardInvocationResult(tx, runtime.taskId, progress, "running");
1677
+ return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
1678
+ }, context);
1679
+ } catch (error) {
1680
+ for (const waiter of pending)
1681
+ waiter.reject(error);
1682
+ const detached = withoutAbortSignal3(context);
1683
+ const record = await runtime.getTask(runtime.taskId, detached);
1684
+ if (record?.abortRequested) {
1685
+ const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
1686
+ if (watch !== undefined) {
1687
+ const cleanup = withCancel(detached);
1688
+ watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
1689
+ try {
1690
+ await cancelParkedTool(runtime, tool, intent, cleanup.context);
1691
+ } finally {
1692
+ await watch.stop();
1693
+ }
1694
+ }
1695
+ throw error;
1696
+ }
1697
+ runtime.signal.throwIfAborted();
1698
+ return errorText(error);
1699
+ }
1700
+ for (const waiter of pending)
1701
+ waiter.resolve();
1702
+ }
1703
+ async function cancelParkedTool(runtime, tool, intent, context) {
1704
+ if (!tool) {
1705
+ runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
1706
+ return;
1707
+ }
1708
+ if (tool.cancel === undefined)
1709
+ return;
1710
+ const cleanup = createInvocation(runtime, tool, context, {
1711
+ checkpoint: intent.checkpoint,
1712
+ wake: undefined
1713
+ });
1714
+ const refuseWork = () => {
1715
+ throw new Error("A tool cannot start tasks or nested calls during cancellation");
1716
+ };
1717
+ let reason = new Error("Tool cancellation finished");
1718
+ try {
1719
+ const api = await cleanup.executionApi();
1720
+ await tool.cancel(intent.arguments, {
1721
+ ...api,
1722
+ createTask: refuseWork,
1723
+ executeTool: refuseWork
1724
+ }, context);
1725
+ } catch (error) {
1726
+ reason = error;
1727
+ runtime.report(error);
1728
+ } finally {
1729
+ await cleanup.stop(reason);
1730
+ }
1731
+ }
1732
+
1541
1733
  // packages/execution/src/nested-result.ts
1542
- import { copyJson as copyJson9 } from "@earendil-works/chord";
1734
+ import { copyJson as copyJson10 } from "@earendil-works/chord/json";
1543
1735
  import {
1544
1736
  defineEntry,
1545
1737
  UsageDoc
@@ -1587,11 +1779,11 @@ async function settle(runtime, call, result, ending, context) {
1587
1779
  taskId: runtime.taskId,
1588
1780
  callId: call.id,
1589
1781
  name: call.name,
1590
- arguments: copyJson9(call.arguments),
1782
+ arguments: copyJson10(call.arguments),
1591
1783
  result: stored,
1592
1784
  ...current.state.checkpoint.phase === "execute" ? {
1593
1785
  intent: {
1594
- arguments: copyJson9(current.state.checkpoint.arguments),
1786
+ arguments: copyJson10(current.state.checkpoint.arguments),
1595
1787
  replay: current.state.checkpoint.replay
1596
1788
  }
1597
1789
  } : {}
@@ -1600,7 +1792,7 @@ async function settle(runtime, call, result, ending, context) {
1600
1792
  if (result.usage !== undefined) {
1601
1793
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1602
1794
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1603
- totals[call.name] = copyJson9(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1795
+ totals[call.name] = copyJson10(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1604
1796
  }
1605
1797
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1606
1798
  status: ending,
@@ -1637,7 +1829,11 @@ function sumUsage(previous, added) {
1637
1829
  function createNestedToolTask(name) {
1638
1830
  return defineTask2({
1639
1831
  name,
1640
- version: 1,
1832
+ version: 2,
1833
+ migrate: (input, checkpoint) => ({
1834
+ input,
1835
+ checkpoint
1836
+ }),
1641
1837
  initial: () => ({ phase: "call" }),
1642
1838
  phases: {
1643
1839
  call: async (task, runtime, context) => {
@@ -1672,13 +1868,16 @@ function createNestedToolTask(name) {
1672
1868
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1673
1869
  }
1674
1870
  let block;
1871
+ let sleep;
1675
1872
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1676
- if (block !== undefined)
1873
+ if (block !== undefined || sleep !== undefined)
1677
1874
  return;
1678
1875
  try {
1679
1876
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1680
1877
  if (decision?.block !== undefined)
1681
1878
  block = decision.block;
1879
+ else if (decision?.sleep !== undefined)
1880
+ sleep = decision.sleep;
1682
1881
  else if (decision?.arguments !== undefined)
1683
1882
  args = decision.arguments;
1684
1883
  } catch (error) {
@@ -1689,71 +1888,122 @@ function createNestedToolTask(name) {
1689
1888
  });
1690
1889
  if (block !== undefined)
1691
1890
  return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
1891
+ if (sleep !== undefined) {
1892
+ const reason = await parkGate(runtime, sleep, context);
1893
+ if (reason === undefined)
1894
+ return;
1895
+ return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
1896
+ }
1692
1897
  try {
1693
- args = checked(tool, call, args);
1898
+ args = copyJson11(checked(tool, call, args), {
1899
+ omitUndefinedProperties: true
1900
+ });
1694
1901
  } catch (error) {
1695
1902
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1696
1903
  }
1697
- await runtime.commit(async (tx) => {
1698
- await tx.doc(InvocationDoc, runtime.taskId);
1699
- await forwardCall(tx, task.input.cellId, {
1700
- callId: call.id,
1701
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1702
- name: call.name,
1703
- arguments: args,
1704
- status: "running",
1705
- result: null,
1706
- omittedFields: []
1707
- });
1708
- return {
1709
- status: "running",
1710
- checkpoint: {
1711
- phase: "execute",
1712
- arguments: args,
1713
- replay: tool.replay ?? "unsafe"
1714
- }
1715
- };
1904
+ await startAttempt(runtime, call, tool, agent, {
1905
+ arguments: args,
1906
+ replay: tool.replay ?? "unsafe"
1716
1907
  }, context);
1717
- await run(runtime, call, tool, args, agent, context);
1908
+ },
1909
+ parked: async (task, runtime, context) => {
1910
+ const intent = task.state.checkpoint;
1911
+ const call = nestedCall(runtime, task.input);
1912
+ call.arguments = intent.arguments;
1913
+ const agent = await runtime.agent(context);
1914
+ const tool = agent.callable.find((each) => each.name === call.name);
1915
+ if (tool === undefined || readToolContract(tool).nativeOnly)
1916
+ return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
1917
+ await startAttempt(runtime, call, tool, agent, {
1918
+ ...intent,
1919
+ replay: tool.replay ?? "unsafe"
1920
+ }, context, task.state.wake);
1718
1921
  },
1719
1922
  execute: async (task, runtime, context) => {
1923
+ const intent = task.state.checkpoint;
1720
1924
  const call = nestedCall(runtime, task.input);
1721
1925
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1722
1926
  call.arguments = task.state.checkpoint.arguments;
1723
1927
  const agent = await runtime.agent(context);
1724
1928
  const tool = agent.callable.find((each) => each.name === call.name);
1725
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1726
- await runtime.commit(async (tx) => {
1727
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1728
- doc.result = {};
1729
- doc.droppedBytes = 0;
1730
- doc.droppedLines = 0;
1731
- return;
1732
- }, context);
1733
- return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
1929
+ if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1930
+ if (intent.resume === undefined)
1931
+ await runtime.commit(async (tx) => {
1932
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1933
+ doc.result = {};
1934
+ doc.droppedBytes = 0;
1935
+ doc.droppedLines = 0;
1936
+ return;
1937
+ }, context);
1938
+ return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
1734
1939
  }
1940
+ if (intent.resume !== undefined)
1941
+ await cancelParkedTool(runtime, tool, intent, context);
1735
1942
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1736
1943
  }
1737
1944
  },
1738
1945
  abort: async (task, runtime, context) => {
1739
1946
  const call = nestedCall(runtime, task.input);
1947
+ const intent = task.state.checkpoint;
1948
+ if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
1949
+ const agent = await runtime.agent(context);
1950
+ const tool = agent.callable.find((each) => each.name === call.name);
1951
+ await cancelParkedTool(runtime, tool, intent, context);
1952
+ }
1740
1953
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1741
1954
  }
1742
1955
  });
1743
1956
  }
1957
+ async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
1958
+ await runtime.commit(async (tx) => {
1959
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1960
+ await forwardCall(tx, doc.forwardingCellId, {
1961
+ callId: call.id,
1962
+ parentCallId: call.parent?.callId ?? call.id,
1963
+ name: call.name,
1964
+ arguments: intent.arguments,
1965
+ status: "running",
1966
+ result: null,
1967
+ omittedFields: []
1968
+ });
1969
+ return {
1970
+ status: "running",
1971
+ checkpoint: {
1972
+ ...intent,
1973
+ phase: "execute",
1974
+ ...wake === undefined ? {} : { resume: { wake } }
1975
+ }
1976
+ };
1977
+ }, context);
1978
+ await run(runtime, call, tool, intent, agent, context, wake);
1979
+ }
1744
1980
  async function reject(runtime, call, result, agent, tool, context) {
1745
1981
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1746
1982
  result = await handler(call, result, runtime, context) ?? result;
1747
1983
  });
1748
1984
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1749
1985
  }
1750
- async function run(runtime, call, tool, args, agent, context) {
1986
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1751
1987
  let invocation;
1752
1988
  let result;
1753
1989
  let ending = "completed";
1754
1990
  try {
1755
- invocation = createInvocation(runtime, tool, context);
1756
- result = await tool.execute(args, await invocation.executionApi(), context);
1991
+ const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
1992
+ invocation = createInvocation(runtime, tool, context, {
1993
+ wake,
1994
+ checkpoint: intent.checkpoint,
1995
+ ...previous === undefined ? {} : { progress: previous.result }
1996
+ });
1997
+ const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
1998
+ if (returned.kind === undefined)
1999
+ result = returned;
2000
+ else {
2001
+ const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
2002
+ if (reason === undefined)
2003
+ return;
2004
+ result = executionError("invalid_park", reason);
2005
+ ending = "failed";
2006
+ }
1757
2007
  } catch (error) {
1758
2008
  if (runtime.signal.aborted) {
1759
2009
  await invocation?.stop(error);
@@ -1854,9 +2104,11 @@ function providerProjection(surfaceTools) {
1854
2104
  const conversation = await host.conversation(api.conversationId, context);
1855
2105
  if (conversation === undefined)
1856
2106
  throw new Error(`Conversation ${api.conversationId} is unavailable`);
1857
- for (const tool of (await conversation.agent(context)).tools)
1858
- if (readToolContract(tool).nativeOnly)
2107
+ for (const tool of (await conversation.agent(context)).tools) {
2108
+ const contract = readToolContract(tool);
2109
+ if (contract.nativeOnly || contract.nestedHidden)
1859
2110
  visible.add(tool.name);
2111
+ }
1860
2112
  }
1861
2113
  return { messages: projectToolSchemas(request.messages, visible) };
1862
2114
  }
@@ -1865,7 +2117,7 @@ function providerProjection(surfaceTools) {
1865
2117
  }
1866
2118
 
1867
2119
  // packages/execution/src/wait-session.ts
1868
- import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
2120
+ import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
1869
2121
 
1870
2122
  // packages/execution/src/tool-value.ts
1871
2123
  class NestedToolError extends Error {
@@ -1936,7 +2188,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
1936
2188
  }, context);
1937
2189
  let cancelling;
1938
2190
  const abort = () => {
1939
- cancelling ??= cancelTask(id, withoutAbortSignal3(context));
2191
+ cancelling ??= cancelTask(id, withoutAbortSignal4(context));
1940
2192
  cancelling.catch(() => {});
1941
2193
  };
1942
2194
  context.abortSignal?.addEventListener("abort", abort, { once: true });
@@ -2020,7 +2272,7 @@ function createCellCoordinator(options) {
2020
2272
  if (driver.closed)
2021
2273
  throw new Error("Execution host is closed");
2022
2274
  assertSingleExecutionMode(await api.agent(context));
2023
- const copied = copyJson10(input);
2275
+ const copied = copyJson12(input);
2024
2276
  return api.commit(async (tx) => {
2025
2277
  const isolatedLimit = options.isolatedConcurrency ?? 0;
2026
2278
  const isolated = isolatedLimit > 0 && input["isolated"] === true;
@@ -2100,7 +2352,7 @@ function createCellCoordinator(options) {
2100
2352
  if (yielding.consume()) {
2101
2353
  return initial;
2102
2354
  }
2103
- const wait = withCancel(context);
2355
+ const wait = withCancel2(context);
2104
2356
  const timeout = new Error("Cell observation yielded");
2105
2357
  const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
2106
2358
  try {
@@ -3288,7 +3540,7 @@ function createUpdates(write, context) {
3288
3540
  }
3289
3541
 
3290
3542
  // packages/notebook/src/tool-observation.ts
3291
- import { copyJson as copyJson11 } from "@earendil-works/chord";
3543
+ import { copyJson as copyJson13 } from "@earendil-works/chord/json";
3292
3544
  import {
3293
3545
  defineDocFamily as defineDocFamily2
3294
3546
  } from "@earendil-works/pi-durable";
@@ -3343,7 +3595,7 @@ async function observeNotebookCell(observation, maxTokens, api, context) {
3343
3595
  cell_id: String(observation.cellId),
3344
3596
  status: observation.status,
3345
3597
  ...observation.forwardedToolCalls === undefined ? {} : {
3346
- forwardedToolCalls: copyJson11(observation.forwardedToolCalls, {
3598
+ forwardedToolCalls: copyJson13(observation.forwardedToolCalls, {
3347
3599
  omitUndefinedProperties: true
3348
3600
  })
3349
3601
  },
@@ -3364,7 +3616,7 @@ async function observeNotebookCell(observation, maxTokens, api, context) {
3364
3616
 
3365
3617
  // packages/js-notebook/src/engine.ts
3366
3618
  import { randomUUID as randomUUID7 } from "node:crypto";
3367
- import { copyJson as copyJson12 } from "@earendil-works/chord";
3619
+ import { copyJson as copyJson14 } from "@earendil-works/chord/json";
3368
3620
  import {
3369
3621
  defineDoc as defineDoc3
3370
3622
  } from "@earendil-works/pi-durable";
@@ -4190,7 +4442,7 @@ async function runtimePackage(name, version, stateDirectory, signal) {
4190
4442
  }
4191
4443
  async function loadJsRuntime(stateDirectory, signal) {
4192
4444
  signal?.throwIfAborted();
4193
- const installed = await runtimePackage("@earendil-works/pi-codemode", "1.5.0", stateDirectory, signal);
4445
+ const installed = await runtimePackage("@earendil-works/pi-codemode", "1.8.0", stateDirectory, signal);
4194
4446
  const manifest = JSON.parse(await readFile3(installed.manifest, "utf8"));
4195
4447
  if (!manifest || typeof manifest !== "object" || !("main" in manifest) || typeof manifest.main !== "string")
4196
4448
  throw new Error("The JS Notebook runtime package is incomplete; reinstall it, then retry");
@@ -5219,7 +5471,7 @@ class JsNotebookClient {
5219
5471
  const definitions = tools.map((tool) => ({
5220
5472
  name: tool.name,
5221
5473
  exposed: tool.name,
5222
- description: tool.help ?? tool.usage ?? tool.description,
5474
+ ...tool.hidden ? {} : { description: tool.help ?? tool.usage ?? tool.description },
5223
5475
  ..."textOutput" in tool && tool.textOutput ? { output: tool.textOutput } : {}
5224
5476
  }));
5225
5477
  this.project.setTools(definitions);
@@ -5629,13 +5881,14 @@ function createJsNotebookEngine(options) {
5629
5881
  const contract = readToolContract(registration);
5630
5882
  return {
5631
5883
  name: registration.name,
5884
+ hidden: contract.nestedHidden,
5632
5885
  description: contract.description,
5633
5886
  usage: contract.usage,
5634
5887
  help: contract.help,
5635
5888
  ...registration.name === "exec_command" || registration.name === "write_stdin" ? { textOutput: "plain-command" } : {},
5636
5889
  async invoke(input, _context, signal) {
5637
5890
  signal.throwIfAborted();
5638
- const args = copyJson12(input === undefined ? null : input, {
5891
+ const args = copyJson14(input === undefined ? null : input, {
5639
5892
  omitUndefinedProperties: true
5640
5893
  });
5641
5894
  const invoke = api.tools[registration.name];
@@ -6284,15 +6537,15 @@ function createJsNotebookMode(options) {
6284
6537
  };
6285
6538
  return {
6286
6539
  output: [{ type: "text", text: result.message }],
6287
- details: copyJson13(result.details),
6288
- structuredOutput: copyJson13(result)
6540
+ details: copyJson15(result.details),
6541
+ structuredOutput: copyJson15(result)
6289
6542
  };
6290
6543
  }
6291
6544
  const result = await engine.control(request, api, context);
6292
6545
  return {
6293
6546
  output: [{ type: "text", text: result.message }],
6294
- details: copyJson13(result.details, { omitUndefinedProperties: true }),
6295
- structuredOutput: copyJson13(result, { omitUndefinedProperties: true })
6547
+ details: copyJson15(result.details, { omitUndefinedProperties: true }),
6548
+ structuredOutput: copyJson15(result, { omitUndefinedProperties: true })
6296
6549
  };
6297
6550
  }
6298
6551
  });
@@ -6307,7 +6560,7 @@ function createJsNotebookMode(options) {
6307
6560
  sections: [
6308
6561
  section("notebook", (input) => {
6309
6562
  const base = 'exec: JavaScript with top-level await in a persistent QuickJS VM. Closures, classes and cyclic data survive checkpoints without replay. Bare values are discarded. Use text(value), image(value), notify(value), store(key,value), load(key), exit() and yield_control(). ALL_TOOLS lists selected registrations. Normal cells share project state. A leading // @exec: {"isolated":true} forks the last committed state and saves a candidate without adopting it. Whole-notebook profile loads replace live state. External effects are never rolled back. Node APIs and imports are unavailable inside the VM.';
6310
- const promoted = input.agent.callable.filter((tool) => !["exec", "wait", "notebook"].includes(tool.name)).map(readToolContract).filter((contract) => !contract.nativeOnly && !contract.deferLoading).map((contract) => contract.prompt);
6563
+ const promoted = input.agent.callable.filter((tool) => !["exec", "wait", "notebook"].includes(tool.name)).map(readToolContract).filter((contract) => !contract.nativeOnly && !contract.nestedHidden && !contract.deferLoading).map((contract) => contract.prompt);
6311
6564
  return [base, nestedToolDiscoveryGuidance, ...promoted].join(`
6312
6565
  `);
6313
6566
  })