@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.
@@ -9,7 +9,7 @@ import { Type as Type5 } from "typebox";
9
9
  import { Check as Check3 } from "typebox/value";
10
10
 
11
11
  // packages/js-notebook/src/index.ts
12
- import { copyJson as copyJson13 } from "@earendil-works/chord";
12
+ import { copyJson as copyJson15 } from "@earendil-works/chord/json";
13
13
  import {
14
14
  defineExtension as defineExtension3,
15
15
  defineTool as defineTool3,
@@ -80,8 +80,8 @@ function parseInteger(value, name, minimum = 0, maximum = Number.MAX_SAFE_INTEGE
80
80
  }
81
81
 
82
82
  // packages/execution/src/cells.ts
83
- import { copyJson as copyJson10 } from "@earendil-works/chord";
84
- import { withCancel } from "@earendil-works/chord/context";
83
+ import { withCancel as withCancel2 } from "@earendil-works/chord/context";
84
+ import { copyJson as copyJson12 } from "@earendil-works/chord/json";
85
85
  import {
86
86
  defineExtension
87
87
  } from "@earendil-works/pi-durable";
@@ -92,7 +92,7 @@ import {
92
92
  } from "@earendil-works/pi-durable";
93
93
 
94
94
  // packages/execution/src/forwarding.ts
95
- import { copyJson as copyJson2 } from "@earendil-works/chord";
95
+ import { copyJson as copyJson2 } from "@earendil-works/chord/json";
96
96
  import {
97
97
  LiveDoc,
98
98
  NestedCallDoc,
@@ -102,7 +102,7 @@ import {
102
102
  // packages/execution/src/invocation-state.ts
103
103
  import {
104
104
  copyJson
105
- } from "@earendil-works/chord";
105
+ } from "@earendil-works/chord/json";
106
106
  import {
107
107
  defineDoc
108
108
  } from "@earendil-works/pi-durable";
@@ -579,7 +579,7 @@ async function observeCell(kind, id, api, context, budget) {
579
579
  }
580
580
 
581
581
  // packages/execution/src/cell-progress.ts
582
- import { copyJson as copyJson3 } from "@earendil-works/chord";
582
+ import { copyJson as copyJson3 } from "@earendil-works/chord/json";
583
583
  import {
584
584
  LiveDoc as LiveDoc2
585
585
  } from "@earendil-works/pi-durable";
@@ -639,37 +639,64 @@ async function observeCellProgress(id, api, context, budget) {
639
639
  }
640
640
 
641
641
  // packages/execution/src/cell-task.ts
642
- import { copyJson as copyJson8 } from "@earendil-works/chord";
643
642
  import { withAbortSignal } from "@earendil-works/chord/context";
643
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
644
644
  import {
645
645
  defineTask
646
646
  } from "@earendil-works/pi-durable";
647
647
 
648
648
  // packages/execution/src/cell-tools.ts
649
- import { copyJson as copyJson6 } from "@earendil-works/chord";
650
649
  import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
650
+ import { copyJson as copyJson6 } from "@earendil-works/chord/json";
651
651
 
652
652
  // packages/execution/src/invocation.ts
653
- import { copyJson as copyJson5 } from "@earendil-works/chord";
654
653
  import { awaitWithContext } from "@earendil-works/chord/context";
654
+ import { copyJson as copyJson5 } from "@earendil-works/chord/json";
655
+ import {
656
+ NestedCallDoc as NestedCallDoc3
657
+ } from "@earendil-works/pi-durable";
658
+ import { equal } from "@earendil-works/pi-schema";
655
659
 
656
660
  // packages/execution/src/native-tools.ts
657
- import { copyJson as copyJson4 } from "@earendil-works/chord";
658
- import { withoutAbortSignal } from "@earendil-works/chord/context";
661
+ import {
662
+ withoutAbortSignal
663
+ } from "@earendil-works/chord/context";
664
+ import { copyJson as copyJson4 } from "@earendil-works/chord/json";
659
665
  import {
660
666
  LiveDoc as LiveDoc3,
661
667
  NestedCallDoc as NestedCallDoc2,
662
- ToolTask as ToolTask2
668
+ ToolTask as ToolTask3
663
669
  } from "@earendil-works/pi-durable";
664
670
  import { Equal } from "typebox/value";
665
- function nativeToolCalls(runtime, callId, replay, assertLive, context) {
671
+
672
+ // packages/execution/src/tool-origin.ts
673
+ import {
674
+ defineDoc as defineDoc2,
675
+ ToolTask as ToolTask2
676
+ } from "@earendil-works/pi-durable";
677
+ var ToolOriginDoc = defineDoc2({
678
+ kind: "howaboua.tool-origin",
679
+ version: 1,
680
+ scope: "task",
681
+ checkpointWhen: () => false,
682
+ initial: () => ({})
683
+ });
684
+
685
+ // packages/execution/src/native-tools.ts
686
+ function assertNestedKey(key) {
687
+ if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
688
+ throw new Error("Invalid nested call or task key");
689
+ }
690
+ function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
666
691
  let sequence = 0;
667
692
  const admissions = [];
668
- const execute = async (name, args, callContext, options = {}) => {
693
+ async function execute(name, args, callContext, options = {}) {
669
694
  assertLive();
695
+ if (options.key !== undefined)
696
+ assertNestedKey(options.key);
697
+ else if (resumed)
698
+ throw new Error("Nested calls require an explicit key after waking");
670
699
  const key = options.key ?? String(++sequence);
671
- if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
672
- throw new Error("Invalid nested call key");
673
700
  const call = {
674
701
  type: "toolCall",
675
702
  id: `${callId}/${key}`,
@@ -681,11 +708,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
681
708
  const admission = runtime.commit(async (tx) => {
682
709
  const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
683
710
  if (slot.taskId !== undefined) {
684
- const input = (await tx.task(slot.taskId))?.input;
711
+ const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
685
712
  if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
686
713
  throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
687
714
  } else {
688
- slot.taskId = await tx.createTask(ToolTask2, {
715
+ slot.kind = "nested";
716
+ slot.taskId = await tx.createTask(ToolTask3, {
689
717
  kind: "nested",
690
718
  parent: runtime.taskId,
691
719
  parentCallId: callId,
@@ -697,6 +725,9 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
697
725
  abandonOnRestart: replay !== "safe"
698
726
  });
699
727
  const live = await tx.doc(LiveDoc3, runtime.conversationId);
728
+ const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
729
+ if (origin)
730
+ (await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
700
731
  live.nestedTools ??= [];
701
732
  live.nestedTools.push({
702
733
  callId: call.id,
@@ -728,7 +759,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
728
759
  const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
729
760
  if (slot?.taskId === undefined)
730
761
  throw new Error("Nested task creation did not commit");
731
- const settled = await runtime.waitForTask(slot.taskId, callContext);
762
+ const taskId = slot.taskId;
763
+ const result = (resultContext) => readResult(name, key, taskId, resultContext);
764
+ return options.wait === false ? { taskId, result } : result(callContext);
765
+ }
766
+ async function readResult(name, key, taskId, callContext) {
767
+ assertLive();
768
+ const settled = await runtime.waitForTask(taskId, callContext);
732
769
  const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
733
770
  await runtime.commit(async (tx) => {
734
771
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
@@ -736,7 +773,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
736
773
  return;
737
774
  }, callContext);
738
775
  return result === undefined ? {
739
- taskId: slot.taskId,
776
+ taskId,
740
777
  isError: true,
741
778
  diagnostics: [
742
779
  {
@@ -746,9 +783,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
746
783
  }
747
784
  ]
748
785
  } : copyJson4(result);
749
- };
786
+ }
750
787
  return {
751
788
  execute,
789
+ async drain() {
790
+ await Promise.allSettled(admissions);
791
+ },
752
792
  async finish() {
753
793
  await Promise.allSettled(admissions);
754
794
  await cleanupNativeCalls(runtime, withoutAbortSignal(context));
@@ -756,7 +796,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
756
796
  };
757
797
  }
758
798
  async function cleanupNativeCalls(runtime, context) {
759
- await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
799
+ await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
760
800
  await runtime.commit(async (tx) => {
761
801
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
762
802
  await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
@@ -850,18 +890,6 @@ class Progress {
850
890
  }
851
891
  }
852
892
 
853
- // packages/execution/src/tool-origin.ts
854
- import {
855
- defineDoc as defineDoc2
856
- } from "@earendil-works/pi-durable";
857
- var ToolOriginDoc = defineDoc2({
858
- kind: "howaboua.tool-origin",
859
- version: 1,
860
- scope: "task",
861
- checkpointWhen: () => false,
862
- initial: () => ({})
863
- });
864
-
865
893
  // packages/execution/src/invocation.ts
866
894
  function executionError(code, message) {
867
895
  return {
@@ -873,21 +901,23 @@ function executionError(code, message) {
873
901
  function errorText(error) {
874
902
  return error instanceof Error ? error.message : String(error);
875
903
  }
876
- function createInvocation(runtime, tool, context) {
904
+ function createInvocation(runtime, tool, context, resume) {
877
905
  const limits = {
878
906
  maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
879
907
  maxLines: tool.outputLimits?.maxLines ?? 2000,
880
908
  retain: tool.outputLimits?.retain ?? "head"
881
909
  };
882
910
  const output = new OutputBuffer(limits);
883
- const diagnostics = [];
884
- let details;
911
+ const diagnostics = [
912
+ ...resume?.progress?.diagnostics ?? []
913
+ ];
914
+ let details = resume?.progress?.details;
885
915
  let ended = false;
886
916
  const assertLive = () => {
887
917
  if (ended)
888
918
  throw new Error(`Invocation ${runtime.taskId} has settled`);
889
919
  };
890
- const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
920
+ const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
891
921
  const snapshot = () => {
892
922
  const retained = output.snapshot();
893
923
  return {
@@ -916,6 +946,8 @@ function createInvocation(runtime, tool, context) {
916
946
  taskId: runtime.taskId,
917
947
  conversationId: runtime.conversationId,
918
948
  callId: `nested-${runtime.taskId}`,
949
+ wake: resume?.wake,
950
+ checkpoint: resume?.checkpoint,
919
951
  registry: runtime.registry,
920
952
  agent: runtime.agent,
921
953
  env: undefined,
@@ -936,7 +968,7 @@ function createInvocation(runtime, tool, context) {
936
968
  const retained = output.snapshot();
937
969
  return { text: retained.text, truncated: retained.droppedBytes > 0 };
938
970
  },
939
- executeTool: (...args) => native.execute(...args),
971
+ executeTool: native.execute,
940
972
  diagnostic: (value) => {
941
973
  assertLive();
942
974
  diagnostics.push(copyJson5(value, { omitUndefinedProperties: true }));
@@ -950,24 +982,44 @@ function createInvocation(runtime, tool, context) {
950
982
  committed.catch(() => {});
951
983
  await awaitWithContext(committed, detailContext);
952
984
  },
953
- commit: async (change, commitContext) => {
985
+ commit: async (change, commitContext, options) => {
954
986
  assertLive();
955
987
  let result;
956
988
  await runtime.commit(async (tx) => {
957
989
  result = await change(tx);
958
990
  return;
959
- }, commitContext);
991
+ }, commitContext, options);
960
992
  return result;
961
993
  },
962
994
  memo: runtime.memo,
963
- createTask: async (task, input, options, taskContext) => {
995
+ readSignal: runtime.readSignal,
996
+ async createTask(task, input, {
997
+ key,
998
+ ...options
999
+ }, taskContext) {
964
1000
  assertLive();
1001
+ if (key !== undefined)
1002
+ assertNestedKey(key);
1003
+ else if (resume?.wake !== undefined)
1004
+ throw new Error("Child tasks require an explicit key after waking");
965
1005
  let id;
966
1006
  await runtime.commit(async (tx) => {
1007
+ const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
1008
+ if (member?.taskId !== undefined) {
1009
+ const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
1010
+ if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson5(input, { omitUndefinedProperties: true })))
1011
+ throw new Error(`Key ${key} was already used for another call or task`);
1012
+ id = member.taskId;
1013
+ return;
1014
+ }
967
1015
  id = await tx.createTask(task, input, {
968
1016
  ...options,
969
1017
  ...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
970
1018
  });
1019
+ if (member !== undefined) {
1020
+ member.kind = "task";
1021
+ member.taskId = id;
1022
+ }
971
1023
  const source = await tx.doc(ToolOriginDoc, runtime.taskId);
972
1024
  if (source.origin !== undefined)
973
1025
  (await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
@@ -1014,6 +1066,14 @@ function createInvocation(runtime, tool, context) {
1014
1066
  for (const waiter of await progress.stop())
1015
1067
  waiter.reject(error);
1016
1068
  },
1069
+ async park() {
1070
+ ended = true;
1071
+ await native.drain();
1072
+ output.end();
1073
+ const pending = await progress.stop();
1074
+ const { output: _output, ...kept } = snapshot();
1075
+ return { progress: storeResult(kept), pending };
1076
+ },
1017
1077
  limits,
1018
1078
  output,
1019
1079
  progress
@@ -1115,7 +1175,17 @@ function combineControls(controls, allowTermination = true) {
1115
1175
  }
1116
1176
 
1117
1177
  // packages/execution/src/tool-contract.ts
1118
- import { copyJson as copyJson7 } from "@earendil-works/chord";
1178
+ import { copyJson as copyJson7 } from "@earendil-works/chord/json";
1179
+
1180
+ // packages/execution/src/tool-namespaces.ts
1181
+ import { isJsonValue } from "@earendil-works/chord/json";
1182
+ function validateJsToolNamespace(tool, namespace) {
1183
+ const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
1184
+ 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))))
1185
+ throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
1186
+ }
1187
+
1188
+ // packages/execution/src/tool-contract.ts
1119
1189
  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 {}";
1120
1190
  function readToolContract(tool) {
1121
1191
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
@@ -1130,6 +1200,7 @@ function readToolContract(tool) {
1130
1200
  "yieldTimeMs",
1131
1201
  "inputSchema",
1132
1202
  "nativeOnly",
1203
+ "nestedHidden",
1133
1204
  "discovery"
1134
1205
  ]);
1135
1206
  for (const key of Object.keys(hints))
@@ -1153,6 +1224,12 @@ function readToolContract(tool) {
1153
1224
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1154
1225
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1155
1226
  throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
1227
+ const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
1228
+ const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
1229
+ if (jsNamespace !== undefined)
1230
+ validateJsToolNamespace(tool.name, jsNamespace);
1231
+ if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
1232
+ throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
1156
1233
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1157
1234
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1158
1235
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1169,6 +1246,8 @@ function readToolContract(tool) {
1169
1246
  inputSchema,
1170
1247
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1171
1248
  nativeOnly: nativeOnly === true,
1249
+ nestedHidden: nestedHidden === true,
1250
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1172
1251
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1173
1252
  ...outputHint === undefined ? {} : { output: outputHint },
1174
1253
  help: [
@@ -1404,7 +1483,7 @@ function createCellTask(options, nestedTask) {
1404
1483
  import {
1405
1484
  hook,
1406
1485
  LiveDoc as LiveDoc4,
1407
- ToolTask as ToolTask3
1486
+ ToolTask as ToolTask4
1408
1487
  } from "@earendil-works/pi-durable";
1409
1488
  function forwardingHook() {
1410
1489
  let host;
@@ -1414,7 +1493,7 @@ function forwardingHook() {
1414
1493
  throw new Error("Create a separate execution component for each Harness");
1415
1494
  host = harness;
1416
1495
  },
1417
- hook: hook(ToolTask3, {
1496
+ hook: hook(ToolTask4, {
1418
1497
  async beforeTool(call, api, context) {
1419
1498
  const parent = call.parent;
1420
1499
  if (parent === undefined || host === undefined)
@@ -1427,7 +1506,7 @@ function forwardingHook() {
1427
1506
  if (conversation === undefined)
1428
1507
  throw new Error("Forwarded call conversation is unavailable");
1429
1508
  await conversation.commit(async (tx) => {
1430
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1509
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1431
1510
  return;
1432
1511
  const owner = await tx.doc(InvocationDoc, api.taskId);
1433
1512
  const admission = owner.forwardingCellId === undefined;
@@ -1454,7 +1533,7 @@ function forwardingHook() {
1454
1533
  if (conversation === undefined)
1455
1534
  throw new Error("Forwarded call conversation is unavailable");
1456
1535
  await conversation.commit(async (tx) => {
1457
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1536
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1458
1537
  return;
1459
1538
  const owner = await tx.doc(InvocationDoc, api.taskId);
1460
1539
  const cellId = owner.forwardingCellId;
@@ -1479,6 +1558,7 @@ function forwardingHook() {
1479
1558
  }
1480
1559
 
1481
1560
  // packages/execution/src/nested.ts
1561
+ import { copyJson as copyJson11 } from "@earendil-works/chord/json";
1482
1562
  import {
1483
1563
  defineTask as defineTask2
1484
1564
  } from "@earendil-works/pi-durable";
@@ -1487,7 +1567,7 @@ import { compile as compile2 } from "@earendil-works/pi-schema";
1487
1567
  // packages/execution/src/nested-call.ts
1488
1568
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1489
1569
  import {
1490
- ToolTask as ToolTask4
1570
+ ToolTask as ToolTask5
1491
1571
  } from "@earendil-works/pi-durable";
1492
1572
  import { compile } from "@earendil-works/pi-schema";
1493
1573
  function nestedCall(runtime, input) {
@@ -1533,7 +1613,7 @@ function prepareNestedInput(tool, input) {
1533
1613
  async function eachHook(agent, name, api, invoke) {
1534
1614
  for (const extension of agent.extensions)
1535
1615
  for (const registration of extension.hooks ?? []) {
1536
- if (registration.task !== ToolTask4.definition.name)
1616
+ if (registration.task !== ToolTask5.definition.name)
1537
1617
  continue;
1538
1618
  const handler = registration.handlers[name];
1539
1619
  if (handler === undefined)
@@ -1548,8 +1628,120 @@ async function eachHook(agent, name, api, invoke) {
1548
1628
  }
1549
1629
  }
1550
1630
 
1631
+ // packages/execution/src/nested-park.ts
1632
+ import {
1633
+ withCancel,
1634
+ withoutAbortSignal as withoutAbortSignal3
1635
+ } from "@earendil-works/chord/context";
1636
+ import { copyJson as copyJson9 } from "@earendil-works/chord/json";
1637
+ var resultFields = [
1638
+ "output",
1639
+ "structuredOutput",
1640
+ "isError",
1641
+ "details",
1642
+ "diagnostics",
1643
+ "usage",
1644
+ "control"
1645
+ ];
1646
+ function sleepState(checkpoint, { until, signals }) {
1647
+ return {
1648
+ status: "sleeping",
1649
+ checkpoint,
1650
+ ...until === undefined ? {} : { until },
1651
+ ...signals === undefined ? {} : { signals }
1652
+ };
1653
+ }
1654
+ async function parkGate(runtime, sleep, context) {
1655
+ try {
1656
+ await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
1657
+ } catch (error) {
1658
+ runtime.signal.throwIfAborted();
1659
+ return errorText(error);
1660
+ }
1661
+ }
1662
+ async function parkTool(runtime, invocation, tool, args, park, context) {
1663
+ if (park.kind !== "sleep" && park.kind !== "wait")
1664
+ return "Unknown park kind";
1665
+ const mixed = resultFields.find((field) => (field in park));
1666
+ if (mixed !== undefined)
1667
+ return `A park cannot carry the result field ${mixed}`;
1668
+ const intent = {
1669
+ arguments: args,
1670
+ replay: tool.replay ?? "unsafe",
1671
+ ...park.checkpoint === undefined ? {} : { checkpoint: copyJson9(park.checkpoint) }
1672
+ };
1673
+ const { progress, pending } = await invocation.park();
1674
+ try {
1675
+ await runtime.commit(async (tx) => {
1676
+ if (park.kind === "wait") {
1677
+ for (const id of park.on)
1678
+ if ((await tx.task(id))?.owner !== runtime.taskId)
1679
+ throw new Error(`Task ${id} is not owned by the call`);
1680
+ }
1681
+ const checkpoint = { ...intent, phase: "parked" };
1682
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1683
+ doc.result = progress;
1684
+ doc.droppedBytes = 0;
1685
+ doc.droppedLines = 0;
1686
+ await forwardInvocationResult(tx, runtime.taskId, progress, "running");
1687
+ return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
1688
+ }, context);
1689
+ } catch (error) {
1690
+ for (const waiter of pending)
1691
+ waiter.reject(error);
1692
+ const detached = withoutAbortSignal3(context);
1693
+ const record = await runtime.getTask(runtime.taskId, detached);
1694
+ if (record?.abortRequested) {
1695
+ const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
1696
+ if (watch !== undefined) {
1697
+ const cleanup = withCancel(detached);
1698
+ watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
1699
+ try {
1700
+ await cancelParkedTool(runtime, tool, intent, cleanup.context);
1701
+ } finally {
1702
+ await watch.stop();
1703
+ }
1704
+ }
1705
+ throw error;
1706
+ }
1707
+ runtime.signal.throwIfAborted();
1708
+ return errorText(error);
1709
+ }
1710
+ for (const waiter of pending)
1711
+ waiter.resolve();
1712
+ }
1713
+ async function cancelParkedTool(runtime, tool, intent, context) {
1714
+ if (!tool) {
1715
+ runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
1716
+ return;
1717
+ }
1718
+ if (tool.cancel === undefined)
1719
+ return;
1720
+ const cleanup = createInvocation(runtime, tool, context, {
1721
+ checkpoint: intent.checkpoint,
1722
+ wake: undefined
1723
+ });
1724
+ const refuseWork = () => {
1725
+ throw new Error("A tool cannot start tasks or nested calls during cancellation");
1726
+ };
1727
+ let reason = new Error("Tool cancellation finished");
1728
+ try {
1729
+ const api = await cleanup.executionApi();
1730
+ await tool.cancel(intent.arguments, {
1731
+ ...api,
1732
+ createTask: refuseWork,
1733
+ executeTool: refuseWork
1734
+ }, context);
1735
+ } catch (error) {
1736
+ reason = error;
1737
+ runtime.report(error);
1738
+ } finally {
1739
+ await cleanup.stop(reason);
1740
+ }
1741
+ }
1742
+
1551
1743
  // packages/execution/src/nested-result.ts
1552
- import { copyJson as copyJson9 } from "@earendil-works/chord";
1744
+ import { copyJson as copyJson10 } from "@earendil-works/chord/json";
1553
1745
  import {
1554
1746
  defineEntry,
1555
1747
  UsageDoc
@@ -1597,11 +1789,11 @@ async function settle(runtime, call, result, ending, context) {
1597
1789
  taskId: runtime.taskId,
1598
1790
  callId: call.id,
1599
1791
  name: call.name,
1600
- arguments: copyJson9(call.arguments),
1792
+ arguments: copyJson10(call.arguments),
1601
1793
  result: stored,
1602
1794
  ...current.state.checkpoint.phase === "execute" ? {
1603
1795
  intent: {
1604
- arguments: copyJson9(current.state.checkpoint.arguments),
1796
+ arguments: copyJson10(current.state.checkpoint.arguments),
1605
1797
  replay: current.state.checkpoint.replay
1606
1798
  }
1607
1799
  } : {}
@@ -1610,7 +1802,7 @@ async function settle(runtime, call, result, ending, context) {
1610
1802
  if (result.usage !== undefined) {
1611
1803
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1612
1804
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1613
- totals[call.name] = copyJson9(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1805
+ totals[call.name] = copyJson10(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1614
1806
  }
1615
1807
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1616
1808
  status: ending,
@@ -1647,7 +1839,11 @@ function sumUsage(previous, added) {
1647
1839
  function createNestedToolTask(name) {
1648
1840
  return defineTask2({
1649
1841
  name,
1650
- version: 1,
1842
+ version: 2,
1843
+ migrate: (input, checkpoint) => ({
1844
+ input,
1845
+ checkpoint
1846
+ }),
1651
1847
  initial: () => ({ phase: "call" }),
1652
1848
  phases: {
1653
1849
  call: async (task, runtime, context) => {
@@ -1682,13 +1878,16 @@ function createNestedToolTask(name) {
1682
1878
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1683
1879
  }
1684
1880
  let block;
1881
+ let sleep;
1685
1882
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1686
- if (block !== undefined)
1883
+ if (block !== undefined || sleep !== undefined)
1687
1884
  return;
1688
1885
  try {
1689
1886
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1690
1887
  if (decision?.block !== undefined)
1691
1888
  block = decision.block;
1889
+ else if (decision?.sleep !== undefined)
1890
+ sleep = decision.sleep;
1692
1891
  else if (decision?.arguments !== undefined)
1693
1892
  args = decision.arguments;
1694
1893
  } catch (error) {
@@ -1699,71 +1898,122 @@ function createNestedToolTask(name) {
1699
1898
  });
1700
1899
  if (block !== undefined)
1701
1900
  return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
1901
+ if (sleep !== undefined) {
1902
+ const reason = await parkGate(runtime, sleep, context);
1903
+ if (reason === undefined)
1904
+ return;
1905
+ return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
1906
+ }
1702
1907
  try {
1703
- args = checked(tool, call, args);
1908
+ args = copyJson11(checked(tool, call, args), {
1909
+ omitUndefinedProperties: true
1910
+ });
1704
1911
  } catch (error) {
1705
1912
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1706
1913
  }
1707
- await runtime.commit(async (tx) => {
1708
- await tx.doc(InvocationDoc, runtime.taskId);
1709
- await forwardCall(tx, task.input.cellId, {
1710
- callId: call.id,
1711
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1712
- name: call.name,
1713
- arguments: args,
1714
- status: "running",
1715
- result: null,
1716
- omittedFields: []
1717
- });
1718
- return {
1719
- status: "running",
1720
- checkpoint: {
1721
- phase: "execute",
1722
- arguments: args,
1723
- replay: tool.replay ?? "unsafe"
1724
- }
1725
- };
1914
+ await startAttempt(runtime, call, tool, agent, {
1915
+ arguments: args,
1916
+ replay: tool.replay ?? "unsafe"
1726
1917
  }, context);
1727
- await run(runtime, call, tool, args, agent, context);
1918
+ },
1919
+ parked: async (task, runtime, context) => {
1920
+ const intent = task.state.checkpoint;
1921
+ const call = nestedCall(runtime, task.input);
1922
+ call.arguments = intent.arguments;
1923
+ const agent = await runtime.agent(context);
1924
+ const tool = agent.callable.find((each) => each.name === call.name);
1925
+ if (tool === undefined || readToolContract(tool).nativeOnly)
1926
+ return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
1927
+ await startAttempt(runtime, call, tool, agent, {
1928
+ ...intent,
1929
+ replay: tool.replay ?? "unsafe"
1930
+ }, context, task.state.wake);
1728
1931
  },
1729
1932
  execute: async (task, runtime, context) => {
1933
+ const intent = task.state.checkpoint;
1730
1934
  const call = nestedCall(runtime, task.input);
1731
1935
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1732
1936
  call.arguments = task.state.checkpoint.arguments;
1733
1937
  const agent = await runtime.agent(context);
1734
1938
  const tool = agent.callable.find((each) => each.name === call.name);
1735
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1736
- await runtime.commit(async (tx) => {
1737
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1738
- doc.result = {};
1739
- doc.droppedBytes = 0;
1740
- doc.droppedLines = 0;
1741
- return;
1742
- }, context);
1743
- return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
1939
+ if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1940
+ if (intent.resume === undefined)
1941
+ await runtime.commit(async (tx) => {
1942
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1943
+ doc.result = {};
1944
+ doc.droppedBytes = 0;
1945
+ doc.droppedLines = 0;
1946
+ return;
1947
+ }, context);
1948
+ return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
1744
1949
  }
1950
+ if (intent.resume !== undefined)
1951
+ await cancelParkedTool(runtime, tool, intent, context);
1745
1952
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1746
1953
  }
1747
1954
  },
1748
1955
  abort: async (task, runtime, context) => {
1749
1956
  const call = nestedCall(runtime, task.input);
1957
+ const intent = task.state.checkpoint;
1958
+ if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
1959
+ const agent = await runtime.agent(context);
1960
+ const tool = agent.callable.find((each) => each.name === call.name);
1961
+ await cancelParkedTool(runtime, tool, intent, context);
1962
+ }
1750
1963
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1751
1964
  }
1752
1965
  });
1753
1966
  }
1967
+ async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
1968
+ await runtime.commit(async (tx) => {
1969
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1970
+ await forwardCall(tx, doc.forwardingCellId, {
1971
+ callId: call.id,
1972
+ parentCallId: call.parent?.callId ?? call.id,
1973
+ name: call.name,
1974
+ arguments: intent.arguments,
1975
+ status: "running",
1976
+ result: null,
1977
+ omittedFields: []
1978
+ });
1979
+ return {
1980
+ status: "running",
1981
+ checkpoint: {
1982
+ ...intent,
1983
+ phase: "execute",
1984
+ ...wake === undefined ? {} : { resume: { wake } }
1985
+ }
1986
+ };
1987
+ }, context);
1988
+ await run(runtime, call, tool, intent, agent, context, wake);
1989
+ }
1754
1990
  async function reject(runtime, call, result, agent, tool, context) {
1755
1991
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1756
1992
  result = await handler(call, result, runtime, context) ?? result;
1757
1993
  });
1758
1994
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1759
1995
  }
1760
- async function run(runtime, call, tool, args, agent, context) {
1996
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1761
1997
  let invocation;
1762
1998
  let result;
1763
1999
  let ending = "completed";
1764
2000
  try {
1765
- invocation = createInvocation(runtime, tool, context);
1766
- result = await tool.execute(args, await invocation.executionApi(), context);
2001
+ const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
2002
+ invocation = createInvocation(runtime, tool, context, {
2003
+ wake,
2004
+ checkpoint: intent.checkpoint,
2005
+ ...previous === undefined ? {} : { progress: previous.result }
2006
+ });
2007
+ const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
2008
+ if (returned.kind === undefined)
2009
+ result = returned;
2010
+ else {
2011
+ const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
2012
+ if (reason === undefined)
2013
+ return;
2014
+ result = executionError("invalid_park", reason);
2015
+ ending = "failed";
2016
+ }
1767
2017
  } catch (error) {
1768
2018
  if (runtime.signal.aborted) {
1769
2019
  await invocation?.stop(error);
@@ -1864,9 +2114,11 @@ function providerProjection(surfaceTools) {
1864
2114
  const conversation = await host.conversation(api.conversationId, context);
1865
2115
  if (conversation === undefined)
1866
2116
  throw new Error(`Conversation ${api.conversationId} is unavailable`);
1867
- for (const tool of (await conversation.agent(context)).tools)
1868
- if (readToolContract(tool).nativeOnly)
2117
+ for (const tool of (await conversation.agent(context)).tools) {
2118
+ const contract = readToolContract(tool);
2119
+ if (contract.nativeOnly || contract.nestedHidden)
1869
2120
  visible.add(tool.name);
2121
+ }
1870
2122
  }
1871
2123
  return { messages: projectToolSchemas(request.messages, visible) };
1872
2124
  }
@@ -1875,7 +2127,7 @@ function providerProjection(surfaceTools) {
1875
2127
  }
1876
2128
 
1877
2129
  // packages/execution/src/wait-session.ts
1878
- import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
2130
+ import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
1879
2131
 
1880
2132
  // packages/execution/src/tool-value.ts
1881
2133
  class NestedToolError extends Error {
@@ -1946,7 +2198,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
1946
2198
  }, context);
1947
2199
  let cancelling;
1948
2200
  const abort = () => {
1949
- cancelling ??= cancelTask(id, withoutAbortSignal3(context));
2201
+ cancelling ??= cancelTask(id, withoutAbortSignal4(context));
1950
2202
  cancelling.catch(() => {});
1951
2203
  };
1952
2204
  context.abortSignal?.addEventListener("abort", abort, { once: true });
@@ -2030,7 +2282,7 @@ function createCellCoordinator(options) {
2030
2282
  if (driver.closed)
2031
2283
  throw new Error("Execution host is closed");
2032
2284
  assertSingleExecutionMode(await api.agent(context));
2033
- const copied = copyJson10(input);
2285
+ const copied = copyJson12(input);
2034
2286
  return api.commit(async (tx) => {
2035
2287
  const isolatedLimit = options.isolatedConcurrency ?? 0;
2036
2288
  const isolated = isolatedLimit > 0 && input["isolated"] === true;
@@ -2110,7 +2362,7 @@ function createCellCoordinator(options) {
2110
2362
  if (yielding.consume()) {
2111
2363
  return initial;
2112
2364
  }
2113
- const wait = withCancel(context);
2365
+ const wait = withCancel2(context);
2114
2366
  const timeout = new Error("Cell observation yielded");
2115
2367
  const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
2116
2368
  try {
@@ -3298,7 +3550,7 @@ function createUpdates(write, context) {
3298
3550
  }
3299
3551
 
3300
3552
  // packages/notebook/src/tool-observation.ts
3301
- import { copyJson as copyJson11 } from "@earendil-works/chord";
3553
+ import { copyJson as copyJson13 } from "@earendil-works/chord/json";
3302
3554
  import {
3303
3555
  defineDocFamily as defineDocFamily2
3304
3556
  } from "@earendil-works/pi-durable";
@@ -3353,7 +3605,7 @@ async function observeNotebookCell(observation, maxTokens, api, context) {
3353
3605
  cell_id: String(observation.cellId),
3354
3606
  status: observation.status,
3355
3607
  ...observation.forwardedToolCalls === undefined ? {} : {
3356
- forwardedToolCalls: copyJson11(observation.forwardedToolCalls, {
3608
+ forwardedToolCalls: copyJson13(observation.forwardedToolCalls, {
3357
3609
  omitUndefinedProperties: true
3358
3610
  })
3359
3611
  },
@@ -3374,7 +3626,7 @@ async function observeNotebookCell(observation, maxTokens, api, context) {
3374
3626
 
3375
3627
  // packages/js-notebook/src/engine.ts
3376
3628
  import { randomUUID as randomUUID7 } from "node:crypto";
3377
- import { copyJson as copyJson12 } from "@earendil-works/chord";
3629
+ import { copyJson as copyJson14 } from "@earendil-works/chord/json";
3378
3630
  import {
3379
3631
  defineDoc as defineDoc3
3380
3632
  } from "@earendil-works/pi-durable";
@@ -4200,7 +4452,7 @@ async function runtimePackage(name, version, stateDirectory, signal) {
4200
4452
  }
4201
4453
  async function loadJsRuntime(stateDirectory, signal) {
4202
4454
  signal?.throwIfAborted();
4203
- const installed = await runtimePackage("@earendil-works/pi-codemode", "1.5.0", stateDirectory, signal);
4455
+ const installed = await runtimePackage("@earendil-works/pi-codemode", "1.8.0", stateDirectory, signal);
4204
4456
  const manifest = JSON.parse(await readFile3(installed.manifest, "utf8"));
4205
4457
  if (!manifest || typeof manifest !== "object" || !("main" in manifest) || typeof manifest.main !== "string")
4206
4458
  throw new Error("The JS Notebook runtime package is incomplete; reinstall it, then retry");
@@ -5229,7 +5481,7 @@ class JsNotebookClient {
5229
5481
  const definitions = tools.map((tool) => ({
5230
5482
  name: tool.name,
5231
5483
  exposed: tool.name,
5232
- description: tool.help ?? tool.usage ?? tool.description,
5484
+ ...tool.hidden ? {} : { description: tool.help ?? tool.usage ?? tool.description },
5233
5485
  ..."textOutput" in tool && tool.textOutput ? { output: tool.textOutput } : {}
5234
5486
  }));
5235
5487
  this.project.setTools(definitions);
@@ -5639,13 +5891,14 @@ function createJsNotebookEngine(options) {
5639
5891
  const contract = readToolContract(registration);
5640
5892
  return {
5641
5893
  name: registration.name,
5894
+ hidden: contract.nestedHidden,
5642
5895
  description: contract.description,
5643
5896
  usage: contract.usage,
5644
5897
  help: contract.help,
5645
5898
  ...registration.name === "exec_command" || registration.name === "write_stdin" ? { textOutput: "plain-command" } : {},
5646
5899
  async invoke(input, _context, signal) {
5647
5900
  signal.throwIfAborted();
5648
- const args = copyJson12(input === undefined ? null : input, {
5901
+ const args = copyJson14(input === undefined ? null : input, {
5649
5902
  omitUndefinedProperties: true
5650
5903
  });
5651
5904
  const invoke = api.tools[registration.name];
@@ -5930,15 +6183,15 @@ function createJsNotebookMode(options) {
5930
6183
  };
5931
6184
  return {
5932
6185
  output: [{ type: "text", text: result.message }],
5933
- details: copyJson13(result.details),
5934
- structuredOutput: copyJson13(result)
6186
+ details: copyJson15(result.details),
6187
+ structuredOutput: copyJson15(result)
5935
6188
  };
5936
6189
  }
5937
6190
  const result = await engine.control(request, api, context);
5938
6191
  return {
5939
6192
  output: [{ type: "text", text: result.message }],
5940
- details: copyJson13(result.details, { omitUndefinedProperties: true }),
5941
- structuredOutput: copyJson13(result, { omitUndefinedProperties: true })
6193
+ details: copyJson15(result.details, { omitUndefinedProperties: true }),
6194
+ structuredOutput: copyJson15(result, { omitUndefinedProperties: true })
5942
6195
  };
5943
6196
  }
5944
6197
  });
@@ -5953,7 +6206,7 @@ function createJsNotebookMode(options) {
5953
6206
  sections: [
5954
6207
  section("notebook", (input) => {
5955
6208
  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.';
5956
- 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);
6209
+ 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);
5957
6210
  return [base, nestedToolDiscoveryGuidance, ...promoted].join(`
5958
6211
  `);
5959
6212
  })