@howaboua/pi-durable-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.
@@ -10,7 +10,7 @@ import { Type as Type5 } from "typebox";
10
10
  import { Check as Check3 } from "typebox/value";
11
11
 
12
12
  // packages/notebook/src/index.ts
13
- import { copyJson as copyJson13 } from "@earendil-works/chord";
13
+ import { copyJson as copyJson15 } from "@earendil-works/chord/json";
14
14
  import {
15
15
  defineExtension as defineExtension3,
16
16
  defineTool as defineTool3,
@@ -82,8 +82,8 @@ function parseInteger(value, name, minimum = 0, maximum = Number.MAX_SAFE_INTEGE
82
82
  }
83
83
 
84
84
  // packages/execution/src/cells.ts
85
- import { copyJson as copyJson10 } from "@earendil-works/chord";
86
- import { withCancel } from "@earendil-works/chord/context";
85
+ import { withCancel as withCancel2 } from "@earendil-works/chord/context";
86
+ import { copyJson as copyJson12 } from "@earendil-works/chord/json";
87
87
  import {
88
88
  defineExtension
89
89
  } from "@earendil-works/pi-durable";
@@ -94,7 +94,7 @@ import {
94
94
  } from "@earendil-works/pi-durable";
95
95
 
96
96
  // packages/execution/src/forwarding.ts
97
- import { copyJson as copyJson2 } from "@earendil-works/chord";
97
+ import { copyJson as copyJson2 } from "@earendil-works/chord/json";
98
98
  import {
99
99
  LiveDoc,
100
100
  NestedCallDoc,
@@ -104,7 +104,7 @@ import {
104
104
  // packages/execution/src/invocation-state.ts
105
105
  import {
106
106
  copyJson
107
- } from "@earendil-works/chord";
107
+ } from "@earendil-works/chord/json";
108
108
  import {
109
109
  defineDoc
110
110
  } from "@earendil-works/pi-durable";
@@ -581,7 +581,7 @@ async function observeCell(kind, id, api, context, budget) {
581
581
  }
582
582
 
583
583
  // packages/execution/src/cell-progress.ts
584
- import { copyJson as copyJson3 } from "@earendil-works/chord";
584
+ import { copyJson as copyJson3 } from "@earendil-works/chord/json";
585
585
  import {
586
586
  LiveDoc as LiveDoc2
587
587
  } from "@earendil-works/pi-durable";
@@ -641,37 +641,64 @@ async function observeCellProgress(id, api, context, budget) {
641
641
  }
642
642
 
643
643
  // packages/execution/src/cell-task.ts
644
- import { copyJson as copyJson8 } from "@earendil-works/chord";
645
644
  import { withAbortSignal } from "@earendil-works/chord/context";
645
+ import { copyJson as copyJson8 } from "@earendil-works/chord/json";
646
646
  import {
647
647
  defineTask
648
648
  } from "@earendil-works/pi-durable";
649
649
 
650
650
  // packages/execution/src/cell-tools.ts
651
- import { copyJson as copyJson6 } from "@earendil-works/chord";
652
651
  import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
652
+ import { copyJson as copyJson6 } from "@earendil-works/chord/json";
653
653
 
654
654
  // packages/execution/src/invocation.ts
655
- import { copyJson as copyJson5 } from "@earendil-works/chord";
656
655
  import { awaitWithContext } from "@earendil-works/chord/context";
656
+ import { copyJson as copyJson5 } from "@earendil-works/chord/json";
657
+ import {
658
+ NestedCallDoc as NestedCallDoc3
659
+ } from "@earendil-works/pi-durable";
660
+ import { equal } from "@earendil-works/pi-schema";
657
661
 
658
662
  // packages/execution/src/native-tools.ts
659
- import { copyJson as copyJson4 } from "@earendil-works/chord";
660
- import { withoutAbortSignal } from "@earendil-works/chord/context";
663
+ import {
664
+ withoutAbortSignal
665
+ } from "@earendil-works/chord/context";
666
+ import { copyJson as copyJson4 } from "@earendil-works/chord/json";
661
667
  import {
662
668
  LiveDoc as LiveDoc3,
663
669
  NestedCallDoc as NestedCallDoc2,
664
- ToolTask as ToolTask2
670
+ ToolTask as ToolTask3
665
671
  } from "@earendil-works/pi-durable";
666
672
  import { Equal } from "typebox/value";
667
- function nativeToolCalls(runtime, callId, replay, assertLive, context) {
673
+
674
+ // packages/execution/src/tool-origin.ts
675
+ import {
676
+ defineDoc as defineDoc2,
677
+ ToolTask as ToolTask2
678
+ } from "@earendil-works/pi-durable";
679
+ var ToolOriginDoc = defineDoc2({
680
+ kind: "howaboua.tool-origin",
681
+ version: 1,
682
+ scope: "task",
683
+ checkpointWhen: () => false,
684
+ initial: () => ({})
685
+ });
686
+
687
+ // packages/execution/src/native-tools.ts
688
+ function assertNestedKey(key) {
689
+ if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
690
+ throw new Error("Invalid nested call or task key");
691
+ }
692
+ function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
668
693
  let sequence = 0;
669
694
  const admissions = [];
670
- const execute = async (name, args, callContext, options = {}) => {
695
+ async function execute(name, args, callContext, options = {}) {
671
696
  assertLive();
697
+ if (options.key !== undefined)
698
+ assertNestedKey(options.key);
699
+ else if (resumed)
700
+ throw new Error("Nested calls require an explicit key after waking");
672
701
  const key = options.key ?? String(++sequence);
673
- if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
674
- throw new Error("Invalid nested call key");
675
702
  const call = {
676
703
  type: "toolCall",
677
704
  id: `${callId}/${key}`,
@@ -683,11 +710,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
683
710
  const admission = runtime.commit(async (tx) => {
684
711
  const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
685
712
  if (slot.taskId !== undefined) {
686
- const input = (await tx.task(slot.taskId))?.input;
713
+ const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
687
714
  if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
688
715
  throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
689
716
  } else {
690
- slot.taskId = await tx.createTask(ToolTask2, {
717
+ slot.kind = "nested";
718
+ slot.taskId = await tx.createTask(ToolTask3, {
691
719
  kind: "nested",
692
720
  parent: runtime.taskId,
693
721
  parentCallId: callId,
@@ -699,6 +727,9 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
699
727
  abandonOnRestart: replay !== "safe"
700
728
  });
701
729
  const live = await tx.doc(LiveDoc3, runtime.conversationId);
730
+ const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
731
+ if (origin)
732
+ (await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
702
733
  live.nestedTools ??= [];
703
734
  live.nestedTools.push({
704
735
  callId: call.id,
@@ -730,7 +761,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
730
761
  const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
731
762
  if (slot?.taskId === undefined)
732
763
  throw new Error("Nested task creation did not commit");
733
- const settled = await runtime.waitForTask(slot.taskId, callContext);
764
+ const taskId = slot.taskId;
765
+ const result = (resultContext) => readResult(name, key, taskId, resultContext);
766
+ return options.wait === false ? { taskId, result } : result(callContext);
767
+ }
768
+ async function readResult(name, key, taskId, callContext) {
769
+ assertLive();
770
+ const settled = await runtime.waitForTask(taskId, callContext);
734
771
  const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
735
772
  await runtime.commit(async (tx) => {
736
773
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
@@ -738,7 +775,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
738
775
  return;
739
776
  }, callContext);
740
777
  return result === undefined ? {
741
- taskId: slot.taskId,
778
+ taskId,
742
779
  isError: true,
743
780
  diagnostics: [
744
781
  {
@@ -748,9 +785,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
748
785
  }
749
786
  ]
750
787
  } : copyJson4(result);
751
- };
788
+ }
752
789
  return {
753
790
  execute,
791
+ async drain() {
792
+ await Promise.allSettled(admissions);
793
+ },
754
794
  async finish() {
755
795
  await Promise.allSettled(admissions);
756
796
  await cleanupNativeCalls(runtime, withoutAbortSignal(context));
@@ -758,7 +798,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
758
798
  };
759
799
  }
760
800
  async function cleanupNativeCalls(runtime, context) {
761
- await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask2.definition.name).map((child) => runtime.abortOwned(child.id, context)));
801
+ await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
762
802
  await runtime.commit(async (tx) => {
763
803
  const owner = await tx.doc(InvocationDoc, runtime.taskId);
764
804
  await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
@@ -852,18 +892,6 @@ class Progress {
852
892
  }
853
893
  }
854
894
 
855
- // packages/execution/src/tool-origin.ts
856
- import {
857
- defineDoc as defineDoc2
858
- } from "@earendil-works/pi-durable";
859
- var ToolOriginDoc = defineDoc2({
860
- kind: "howaboua.tool-origin",
861
- version: 1,
862
- scope: "task",
863
- checkpointWhen: () => false,
864
- initial: () => ({})
865
- });
866
-
867
895
  // packages/execution/src/invocation.ts
868
896
  function executionError(code, message) {
869
897
  return {
@@ -875,21 +903,23 @@ function executionError(code, message) {
875
903
  function errorText(error) {
876
904
  return error instanceof Error ? error.message : String(error);
877
905
  }
878
- function createInvocation(runtime, tool, context) {
906
+ function createInvocation(runtime, tool, context, resume) {
879
907
  const limits = {
880
908
  maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
881
909
  maxLines: tool.outputLimits?.maxLines ?? 2000,
882
910
  retain: tool.outputLimits?.retain ?? "head"
883
911
  };
884
912
  const output = new OutputBuffer(limits);
885
- const diagnostics = [];
886
- let details;
913
+ const diagnostics = [
914
+ ...resume?.progress?.diagnostics ?? []
915
+ ];
916
+ let details = resume?.progress?.details;
887
917
  let ended = false;
888
918
  const assertLive = () => {
889
919
  if (ended)
890
920
  throw new Error(`Invocation ${runtime.taskId} has settled`);
891
921
  };
892
- const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
922
+ const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
893
923
  const snapshot = () => {
894
924
  const retained = output.snapshot();
895
925
  return {
@@ -918,6 +948,8 @@ function createInvocation(runtime, tool, context) {
918
948
  taskId: runtime.taskId,
919
949
  conversationId: runtime.conversationId,
920
950
  callId: `nested-${runtime.taskId}`,
951
+ wake: resume?.wake,
952
+ checkpoint: resume?.checkpoint,
921
953
  registry: runtime.registry,
922
954
  agent: runtime.agent,
923
955
  env: undefined,
@@ -938,7 +970,7 @@ function createInvocation(runtime, tool, context) {
938
970
  const retained = output.snapshot();
939
971
  return { text: retained.text, truncated: retained.droppedBytes > 0 };
940
972
  },
941
- executeTool: (...args) => native.execute(...args),
973
+ executeTool: native.execute,
942
974
  diagnostic: (value) => {
943
975
  assertLive();
944
976
  diagnostics.push(copyJson5(value, { omitUndefinedProperties: true }));
@@ -952,24 +984,44 @@ function createInvocation(runtime, tool, context) {
952
984
  committed.catch(() => {});
953
985
  await awaitWithContext(committed, detailContext);
954
986
  },
955
- commit: async (change, commitContext) => {
987
+ commit: async (change, commitContext, options) => {
956
988
  assertLive();
957
989
  let result;
958
990
  await runtime.commit(async (tx) => {
959
991
  result = await change(tx);
960
992
  return;
961
- }, commitContext);
993
+ }, commitContext, options);
962
994
  return result;
963
995
  },
964
996
  memo: runtime.memo,
965
- createTask: async (task, input, options, taskContext) => {
997
+ readSignal: runtime.readSignal,
998
+ async createTask(task, input, {
999
+ key,
1000
+ ...options
1001
+ }, taskContext) {
966
1002
  assertLive();
1003
+ if (key !== undefined)
1004
+ assertNestedKey(key);
1005
+ else if (resume?.wake !== undefined)
1006
+ throw new Error("Child tasks require an explicit key after waking");
967
1007
  let id;
968
1008
  await runtime.commit(async (tx) => {
1009
+ const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
1010
+ if (member?.taskId !== undefined) {
1011
+ const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
1012
+ if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson5(input, { omitUndefinedProperties: true })))
1013
+ throw new Error(`Key ${key} was already used for another call or task`);
1014
+ id = member.taskId;
1015
+ return;
1016
+ }
969
1017
  id = await tx.createTask(task, input, {
970
1018
  ...options,
971
1019
  ...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
972
1020
  });
1021
+ if (member !== undefined) {
1022
+ member.kind = "task";
1023
+ member.taskId = id;
1024
+ }
973
1025
  const source = await tx.doc(ToolOriginDoc, runtime.taskId);
974
1026
  if (source.origin !== undefined)
975
1027
  (await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
@@ -1016,6 +1068,14 @@ function createInvocation(runtime, tool, context) {
1016
1068
  for (const waiter of await progress.stop())
1017
1069
  waiter.reject(error);
1018
1070
  },
1071
+ async park() {
1072
+ ended = true;
1073
+ await native.drain();
1074
+ output.end();
1075
+ const pending = await progress.stop();
1076
+ const { output: _output, ...kept } = snapshot();
1077
+ return { progress: storeResult(kept), pending };
1078
+ },
1019
1079
  limits,
1020
1080
  output,
1021
1081
  progress
@@ -1117,7 +1177,73 @@ function combineControls(controls, allowTermination = true) {
1117
1177
  }
1118
1178
 
1119
1179
  // packages/execution/src/tool-contract.ts
1120
- import { copyJson as copyJson7 } from "@earendil-works/chord";
1180
+ import { copyJson as copyJson7 } from "@earendil-works/chord/json";
1181
+
1182
+ // packages/execution/src/tool-namespaces.ts
1183
+ import { isJsonValue } from "@earendil-works/chord/json";
1184
+ function validateJsToolNamespace(tool, namespace) {
1185
+ const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
1186
+ 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))))
1187
+ throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
1188
+ }
1189
+ function jsToolPrompt(contract) {
1190
+ if (contract.nativeOnly || contract.nestedHidden)
1191
+ return [];
1192
+ if (contract.jsNamespace)
1193
+ return [contract.jsNamespace.prompt];
1194
+ return contract.deferLoading ? [] : [contract.prompt];
1195
+ }
1196
+ function namespaceDefinitions(tools) {
1197
+ return tools.flatMap(({ name, jsNamespace }) => jsNamespace ? [{ tool: name, name: jsNamespace.name, methods: jsNamespace.methods }] : []);
1198
+ }
1199
+ var installToolNamespacesSource = `(tools, definitions) => {
1200
+ const namespaces = Object.create(null);
1201
+ const binders = Object.create(null);
1202
+ let active = true;
1203
+ const add = (target, key, value) => {
1204
+ if (Object.hasOwn(target, key)) throw new Error("Duplicate tool namespace member: " + key);
1205
+ target[key] = value;
1206
+ };
1207
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
1208
+ for (const { tool, name, methods } of definitions) {
1209
+ const namespace = namespaces[name] ??= Object.create(null);
1210
+ const bound = binders[name] ??= Object.create(null);
1211
+ for (const { name: method, bind, defaults } of methods) {
1212
+ const invoke = (args, ref) => {
1213
+ if (!active)
1214
+ throw new Error("Tool namespace binding expired; bind the server reference again in this cell");
1215
+ if (args !== undefined && !object(args))
1216
+ throw new TypeError("Tool namespace arguments must be an object");
1217
+ return tools[tool]({ ...args, ...defaults, ...(bind === undefined ? {} : { [bind]: ref }) });
1218
+ };
1219
+ if (bind === undefined) {
1220
+ add(namespace, method, (args) => invoke(args));
1221
+ continue;
1222
+ }
1223
+ if (!Object.hasOwn(bound, bind)) {
1224
+ const members = bound[bind] = Object.create(null);
1225
+ add(namespace, bind, (ref) => {
1226
+ if (!object(ref)) throw new TypeError("Supply a discovered namespace reference");
1227
+ const reference = { ...ref };
1228
+ const result = Object.create(null);
1229
+ for (const [key, call] of Object.entries(members))
1230
+ result[key] = (args) => call(args, reference);
1231
+ return Object.freeze(result);
1232
+ });
1233
+ }
1234
+ add(bound[bind], method, invoke);
1235
+ }
1236
+ }
1237
+ for (const namespace of Object.values(namespaces)) Object.freeze(namespace);
1238
+ globalThis.toolNamespaces = Object.freeze(namespaces);
1239
+ return () => {
1240
+ active = false;
1241
+ if (globalThis.toolNamespaces === namespaces)
1242
+ globalThis.toolNamespaces = Object.freeze(Object.create(null));
1243
+ };
1244
+ }`;
1245
+
1246
+ // packages/execution/src/tool-contract.ts
1121
1247
  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 {}";
1122
1248
  function readToolContract(tool) {
1123
1249
  const candidate = "executionHints" in tool ? tool.executionHints : undefined;
@@ -1132,6 +1258,7 @@ function readToolContract(tool) {
1132
1258
  "yieldTimeMs",
1133
1259
  "inputSchema",
1134
1260
  "nativeOnly",
1261
+ "nestedHidden",
1135
1262
  "discovery"
1136
1263
  ]);
1137
1264
  for (const key of Object.keys(hints))
@@ -1155,6 +1282,12 @@ function readToolContract(tool) {
1155
1282
  const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
1156
1283
  if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
1157
1284
  throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
1285
+ const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
1286
+ const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
1287
+ if (jsNamespace !== undefined)
1288
+ validateJsToolNamespace(tool.name, jsNamespace);
1289
+ if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
1290
+ throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
1158
1291
  const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
1159
1292
  if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
1160
1293
  throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
@@ -1171,6 +1304,8 @@ function readToolContract(tool) {
1171
1304
  inputSchema,
1172
1305
  deferLoading: typeof deferred === "boolean" ? deferred : true,
1173
1306
  nativeOnly: nativeOnly === true,
1307
+ nestedHidden: nestedHidden === true,
1308
+ ...jsNamespace === undefined ? {} : { jsNamespace },
1174
1309
  ...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
1175
1310
  ...outputHint === undefined ? {} : { output: outputHint },
1176
1311
  help: [
@@ -1406,7 +1541,7 @@ function createCellTask(options, nestedTask) {
1406
1541
  import {
1407
1542
  hook,
1408
1543
  LiveDoc as LiveDoc4,
1409
- ToolTask as ToolTask3
1544
+ ToolTask as ToolTask4
1410
1545
  } from "@earendil-works/pi-durable";
1411
1546
  function forwardingHook() {
1412
1547
  let host;
@@ -1416,7 +1551,7 @@ function forwardingHook() {
1416
1551
  throw new Error("Create a separate execution component for each Harness");
1417
1552
  host = harness;
1418
1553
  },
1419
- hook: hook(ToolTask3, {
1554
+ hook: hook(ToolTask4, {
1420
1555
  async beforeTool(call, api, context) {
1421
1556
  const parent = call.parent;
1422
1557
  if (parent === undefined || host === undefined)
@@ -1429,7 +1564,7 @@ function forwardingHook() {
1429
1564
  if (conversation === undefined)
1430
1565
  throw new Error("Forwarded call conversation is unavailable");
1431
1566
  await conversation.commit(async (tx) => {
1432
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1567
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1433
1568
  return;
1434
1569
  const owner = await tx.doc(InvocationDoc, api.taskId);
1435
1570
  const admission = owner.forwardingCellId === undefined;
@@ -1456,7 +1591,7 @@ function forwardingHook() {
1456
1591
  if (conversation === undefined)
1457
1592
  throw new Error("Forwarded call conversation is unavailable");
1458
1593
  await conversation.commit(async (tx) => {
1459
- if ((await tx.task(api.taskId))?.kind !== ToolTask3.definition.name)
1594
+ if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
1460
1595
  return;
1461
1596
  const owner = await tx.doc(InvocationDoc, api.taskId);
1462
1597
  const cellId = owner.forwardingCellId;
@@ -1481,6 +1616,7 @@ function forwardingHook() {
1481
1616
  }
1482
1617
 
1483
1618
  // packages/execution/src/nested.ts
1619
+ import { copyJson as copyJson11 } from "@earendil-works/chord/json";
1484
1620
  import {
1485
1621
  defineTask as defineTask2
1486
1622
  } from "@earendil-works/pi-durable";
@@ -1489,7 +1625,7 @@ import { compile as compile2 } from "@earendil-works/pi-schema";
1489
1625
  // packages/execution/src/nested-call.ts
1490
1626
  import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
1491
1627
  import {
1492
- ToolTask as ToolTask4
1628
+ ToolTask as ToolTask5
1493
1629
  } from "@earendil-works/pi-durable";
1494
1630
  import { compile } from "@earendil-works/pi-schema";
1495
1631
  function nestedCall(runtime, input) {
@@ -1535,7 +1671,7 @@ function prepareNestedInput(tool, input) {
1535
1671
  async function eachHook(agent, name, api, invoke) {
1536
1672
  for (const extension of agent.extensions)
1537
1673
  for (const registration of extension.hooks ?? []) {
1538
- if (registration.task !== ToolTask4.definition.name)
1674
+ if (registration.task !== ToolTask5.definition.name)
1539
1675
  continue;
1540
1676
  const handler = registration.handlers[name];
1541
1677
  if (handler === undefined)
@@ -1550,8 +1686,120 @@ async function eachHook(agent, name, api, invoke) {
1550
1686
  }
1551
1687
  }
1552
1688
 
1689
+ // packages/execution/src/nested-park.ts
1690
+ import {
1691
+ withCancel,
1692
+ withoutAbortSignal as withoutAbortSignal3
1693
+ } from "@earendil-works/chord/context";
1694
+ import { copyJson as copyJson9 } from "@earendil-works/chord/json";
1695
+ var resultFields = [
1696
+ "output",
1697
+ "structuredOutput",
1698
+ "isError",
1699
+ "details",
1700
+ "diagnostics",
1701
+ "usage",
1702
+ "control"
1703
+ ];
1704
+ function sleepState(checkpoint, { until, signals }) {
1705
+ return {
1706
+ status: "sleeping",
1707
+ checkpoint,
1708
+ ...until === undefined ? {} : { until },
1709
+ ...signals === undefined ? {} : { signals }
1710
+ };
1711
+ }
1712
+ async function parkGate(runtime, sleep, context) {
1713
+ try {
1714
+ await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
1715
+ } catch (error) {
1716
+ runtime.signal.throwIfAborted();
1717
+ return errorText(error);
1718
+ }
1719
+ }
1720
+ async function parkTool(runtime, invocation, tool, args, park, context) {
1721
+ if (park.kind !== "sleep" && park.kind !== "wait")
1722
+ return "Unknown park kind";
1723
+ const mixed = resultFields.find((field) => (field in park));
1724
+ if (mixed !== undefined)
1725
+ return `A park cannot carry the result field ${mixed}`;
1726
+ const intent = {
1727
+ arguments: args,
1728
+ replay: tool.replay ?? "unsafe",
1729
+ ...park.checkpoint === undefined ? {} : { checkpoint: copyJson9(park.checkpoint) }
1730
+ };
1731
+ const { progress, pending } = await invocation.park();
1732
+ try {
1733
+ await runtime.commit(async (tx) => {
1734
+ if (park.kind === "wait") {
1735
+ for (const id of park.on)
1736
+ if ((await tx.task(id))?.owner !== runtime.taskId)
1737
+ throw new Error(`Task ${id} is not owned by the call`);
1738
+ }
1739
+ const checkpoint = { ...intent, phase: "parked" };
1740
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
1741
+ doc.result = progress;
1742
+ doc.droppedBytes = 0;
1743
+ doc.droppedLines = 0;
1744
+ await forwardInvocationResult(tx, runtime.taskId, progress, "running");
1745
+ return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
1746
+ }, context);
1747
+ } catch (error) {
1748
+ for (const waiter of pending)
1749
+ waiter.reject(error);
1750
+ const detached = withoutAbortSignal3(context);
1751
+ const record = await runtime.getTask(runtime.taskId, detached);
1752
+ if (record?.abortRequested) {
1753
+ const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
1754
+ if (watch !== undefined) {
1755
+ const cleanup = withCancel(detached);
1756
+ watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
1757
+ try {
1758
+ await cancelParkedTool(runtime, tool, intent, cleanup.context);
1759
+ } finally {
1760
+ await watch.stop();
1761
+ }
1762
+ }
1763
+ throw error;
1764
+ }
1765
+ runtime.signal.throwIfAborted();
1766
+ return errorText(error);
1767
+ }
1768
+ for (const waiter of pending)
1769
+ waiter.resolve();
1770
+ }
1771
+ async function cancelParkedTool(runtime, tool, intent, context) {
1772
+ if (!tool) {
1773
+ runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
1774
+ return;
1775
+ }
1776
+ if (tool.cancel === undefined)
1777
+ return;
1778
+ const cleanup = createInvocation(runtime, tool, context, {
1779
+ checkpoint: intent.checkpoint,
1780
+ wake: undefined
1781
+ });
1782
+ const refuseWork = () => {
1783
+ throw new Error("A tool cannot start tasks or nested calls during cancellation");
1784
+ };
1785
+ let reason = new Error("Tool cancellation finished");
1786
+ try {
1787
+ const api = await cleanup.executionApi();
1788
+ await tool.cancel(intent.arguments, {
1789
+ ...api,
1790
+ createTask: refuseWork,
1791
+ executeTool: refuseWork
1792
+ }, context);
1793
+ } catch (error) {
1794
+ reason = error;
1795
+ runtime.report(error);
1796
+ } finally {
1797
+ await cleanup.stop(reason);
1798
+ }
1799
+ }
1800
+
1553
1801
  // packages/execution/src/nested-result.ts
1554
- import { copyJson as copyJson9 } from "@earendil-works/chord";
1802
+ import { copyJson as copyJson10 } from "@earendil-works/chord/json";
1555
1803
  import {
1556
1804
  defineEntry,
1557
1805
  UsageDoc
@@ -1599,11 +1847,11 @@ async function settle(runtime, call, result, ending, context) {
1599
1847
  taskId: runtime.taskId,
1600
1848
  callId: call.id,
1601
1849
  name: call.name,
1602
- arguments: copyJson9(call.arguments),
1850
+ arguments: copyJson10(call.arguments),
1603
1851
  result: stored,
1604
1852
  ...current.state.checkpoint.phase === "execute" ? {
1605
1853
  intent: {
1606
- arguments: copyJson9(current.state.checkpoint.arguments),
1854
+ arguments: copyJson10(current.state.checkpoint.arguments),
1607
1855
  replay: current.state.checkpoint.replay
1608
1856
  }
1609
1857
  } : {}
@@ -1612,7 +1860,7 @@ async function settle(runtime, call, result, ending, context) {
1612
1860
  if (result.usage !== undefined) {
1613
1861
  const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
1614
1862
  const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
1615
- totals[call.name] = copyJson9(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1863
+ totals[call.name] = copyJson10(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
1616
1864
  }
1617
1865
  const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
1618
1866
  status: ending,
@@ -1649,7 +1897,11 @@ function sumUsage(previous, added) {
1649
1897
  function createNestedToolTask(name) {
1650
1898
  return defineTask2({
1651
1899
  name,
1652
- version: 1,
1900
+ version: 2,
1901
+ migrate: (input, checkpoint) => ({
1902
+ input,
1903
+ checkpoint
1904
+ }),
1653
1905
  initial: () => ({ phase: "call" }),
1654
1906
  phases: {
1655
1907
  call: async (task, runtime, context) => {
@@ -1684,13 +1936,16 @@ function createNestedToolTask(name) {
1684
1936
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1685
1937
  }
1686
1938
  let block;
1939
+ let sleep;
1687
1940
  await eachHook(agent, "beforeTool", runtime, async (handler) => {
1688
- if (block !== undefined)
1941
+ if (block !== undefined || sleep !== undefined)
1689
1942
  return;
1690
1943
  try {
1691
1944
  const decision = await handler({ ...call, arguments: args }, runtime, context);
1692
1945
  if (decision?.block !== undefined)
1693
1946
  block = decision.block;
1947
+ else if (decision?.sleep !== undefined)
1948
+ sleep = decision.sleep;
1694
1949
  else if (decision?.arguments !== undefined)
1695
1950
  args = decision.arguments;
1696
1951
  } catch (error) {
@@ -1701,71 +1956,122 @@ function createNestedToolTask(name) {
1701
1956
  });
1702
1957
  if (block !== undefined)
1703
1958
  return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
1959
+ if (sleep !== undefined) {
1960
+ const reason = await parkGate(runtime, sleep, context);
1961
+ if (reason === undefined)
1962
+ return;
1963
+ return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
1964
+ }
1704
1965
  try {
1705
- args = checked(tool, call, args);
1966
+ args = copyJson11(checked(tool, call, args), {
1967
+ omitUndefinedProperties: true
1968
+ });
1706
1969
  } catch (error) {
1707
1970
  return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
1708
1971
  }
1709
- await runtime.commit(async (tx) => {
1710
- await tx.doc(InvocationDoc, runtime.taskId);
1711
- await forwardCall(tx, task.input.cellId, {
1712
- callId: call.id,
1713
- parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
1714
- name: call.name,
1715
- arguments: args,
1716
- status: "running",
1717
- result: null,
1718
- omittedFields: []
1719
- });
1720
- return {
1721
- status: "running",
1722
- checkpoint: {
1723
- phase: "execute",
1724
- arguments: args,
1725
- replay: tool.replay ?? "unsafe"
1726
- }
1727
- };
1972
+ await startAttempt(runtime, call, tool, agent, {
1973
+ arguments: args,
1974
+ replay: tool.replay ?? "unsafe"
1728
1975
  }, context);
1729
- await run(runtime, call, tool, args, agent, context);
1976
+ },
1977
+ parked: async (task, runtime, context) => {
1978
+ const intent = task.state.checkpoint;
1979
+ const call = nestedCall(runtime, task.input);
1980
+ call.arguments = intent.arguments;
1981
+ const agent = await runtime.agent(context);
1982
+ const tool = agent.callable.find((each) => each.name === call.name);
1983
+ if (tool === undefined || readToolContract(tool).nativeOnly)
1984
+ return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
1985
+ await startAttempt(runtime, call, tool, agent, {
1986
+ ...intent,
1987
+ replay: tool.replay ?? "unsafe"
1988
+ }, context, task.state.wake);
1730
1989
  },
1731
1990
  execute: async (task, runtime, context) => {
1991
+ const intent = task.state.checkpoint;
1732
1992
  const call = nestedCall(runtime, task.input);
1733
1993
  if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
1734
1994
  call.arguments = task.state.checkpoint.arguments;
1735
1995
  const agent = await runtime.agent(context);
1736
1996
  const tool = agent.callable.find((each) => each.name === call.name);
1737
- if (task.state.checkpoint.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1738
- await runtime.commit(async (tx) => {
1739
- const doc = await tx.doc(InvocationDoc, runtime.taskId);
1740
- doc.result = {};
1741
- doc.droppedBytes = 0;
1742
- doc.droppedLines = 0;
1743
- return;
1744
- }, context);
1745
- return run(runtime, call, tool, task.state.checkpoint.arguments, agent, context);
1997
+ if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
1998
+ if (intent.resume === undefined)
1999
+ await runtime.commit(async (tx) => {
2000
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
2001
+ doc.result = {};
2002
+ doc.droppedBytes = 0;
2003
+ doc.droppedLines = 0;
2004
+ return;
2005
+ }, context);
2006
+ return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
1746
2007
  }
2008
+ if (intent.resume !== undefined)
2009
+ await cancelParkedTool(runtime, tool, intent, context);
1747
2010
  await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
1748
2011
  }
1749
2012
  },
1750
2013
  abort: async (task, runtime, context) => {
1751
2014
  const call = nestedCall(runtime, task.input);
2015
+ const intent = task.state.checkpoint;
2016
+ if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
2017
+ const agent = await runtime.agent(context);
2018
+ const tool = agent.callable.find((each) => each.name === call.name);
2019
+ await cancelParkedTool(runtime, tool, intent, context);
2020
+ }
1752
2021
  await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
1753
2022
  }
1754
2023
  });
1755
2024
  }
2025
+ async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
2026
+ await runtime.commit(async (tx) => {
2027
+ const doc = await tx.doc(InvocationDoc, runtime.taskId);
2028
+ await forwardCall(tx, doc.forwardingCellId, {
2029
+ callId: call.id,
2030
+ parentCallId: call.parent?.callId ?? call.id,
2031
+ name: call.name,
2032
+ arguments: intent.arguments,
2033
+ status: "running",
2034
+ result: null,
2035
+ omittedFields: []
2036
+ });
2037
+ return {
2038
+ status: "running",
2039
+ checkpoint: {
2040
+ ...intent,
2041
+ phase: "execute",
2042
+ ...wake === undefined ? {} : { resume: { wake } }
2043
+ }
2044
+ };
2045
+ }, context);
2046
+ await run(runtime, call, tool, intent, agent, context, wake);
2047
+ }
1756
2048
  async function reject(runtime, call, result, agent, tool, context) {
1757
2049
  await eachHook(agent, "afterTool", runtime, async (handler) => {
1758
2050
  result = await handler(call, result, runtime, context) ?? result;
1759
2051
  });
1760
2052
  await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
1761
2053
  }
1762
- async function run(runtime, call, tool, args, agent, context) {
2054
+ async function run(runtime, call, tool, intent, agent, context, wake) {
1763
2055
  let invocation;
1764
2056
  let result;
1765
2057
  let ending = "completed";
1766
2058
  try {
1767
- invocation = createInvocation(runtime, tool, context);
1768
- result = await tool.execute(args, await invocation.executionApi(), context);
2059
+ const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
2060
+ invocation = createInvocation(runtime, tool, context, {
2061
+ wake,
2062
+ checkpoint: intent.checkpoint,
2063
+ ...previous === undefined ? {} : { progress: previous.result }
2064
+ });
2065
+ const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
2066
+ if (returned.kind === undefined)
2067
+ result = returned;
2068
+ else {
2069
+ const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
2070
+ if (reason === undefined)
2071
+ return;
2072
+ result = executionError("invalid_park", reason);
2073
+ ending = "failed";
2074
+ }
1769
2075
  } catch (error) {
1770
2076
  if (runtime.signal.aborted) {
1771
2077
  await invocation?.stop(error);
@@ -1866,9 +2172,11 @@ function providerProjection(surfaceTools) {
1866
2172
  const conversation = await host.conversation(api.conversationId, context);
1867
2173
  if (conversation === undefined)
1868
2174
  throw new Error(`Conversation ${api.conversationId} is unavailable`);
1869
- for (const tool of (await conversation.agent(context)).tools)
1870
- if (readToolContract(tool).nativeOnly)
2175
+ for (const tool of (await conversation.agent(context)).tools) {
2176
+ const contract = readToolContract(tool);
2177
+ if (contract.nativeOnly || contract.nestedHidden)
1871
2178
  visible.add(tool.name);
2179
+ }
1872
2180
  }
1873
2181
  return { messages: projectToolSchemas(request.messages, visible) };
1874
2182
  }
@@ -1877,7 +2185,7 @@ function providerProjection(surfaceTools) {
1877
2185
  }
1878
2186
 
1879
2187
  // packages/execution/src/wait-session.ts
1880
- import { withoutAbortSignal as withoutAbortSignal3 } from "@earendil-works/chord/context";
2188
+ import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
1881
2189
 
1882
2190
  // packages/execution/src/tool-value.ts
1883
2191
  class NestedToolError extends Error {
@@ -1948,7 +2256,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
1948
2256
  }, context);
1949
2257
  let cancelling;
1950
2258
  const abort = () => {
1951
- cancelling ??= cancelTask(id, withoutAbortSignal3(context));
2259
+ cancelling ??= cancelTask(id, withoutAbortSignal4(context));
1952
2260
  cancelling.catch(() => {});
1953
2261
  };
1954
2262
  context.abortSignal?.addEventListener("abort", abort, { once: true });
@@ -2032,7 +2340,7 @@ function createCellCoordinator(options) {
2032
2340
  if (driver.closed)
2033
2341
  throw new Error("Execution host is closed");
2034
2342
  assertSingleExecutionMode(await api.agent(context));
2035
- const copied = copyJson10(input);
2343
+ const copied = copyJson12(input);
2036
2344
  return api.commit(async (tx) => {
2037
2345
  const isolatedLimit = options.isolatedConcurrency ?? 0;
2038
2346
  const isolated = isolatedLimit > 0 && input["isolated"] === true;
@@ -2112,7 +2420,7 @@ function createCellCoordinator(options) {
2112
2420
  if (yielding.consume()) {
2113
2421
  return initial;
2114
2422
  }
2115
- const wait = withCancel(context);
2423
+ const wait = withCancel2(context);
2116
2424
  const timeout = new Error("Cell observation yielded");
2117
2425
  const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
2118
2426
  try {
@@ -3310,7 +3618,7 @@ function notebookExecStartupNotice() {
3310
3618
 
3311
3619
  // packages/notebook/src/engine.ts
3312
3620
  import { randomUUID as randomUUID16 } from "node:crypto";
3313
- import { copyJson as copyJson11 } from "@earendil-works/chord";
3621
+ import { copyJson as copyJson13 } from "@earendil-works/chord/json";
3314
3622
  import {
3315
3623
  defineDoc as defineDoc3
3316
3624
  } from "@earendil-works/pi-durable";
@@ -5077,7 +5385,7 @@ class NotebookExecutionRuntime {
5077
5385
  this.settlement.reportJournalFailure(error, "start", cell);
5078
5386
  }
5079
5387
  }
5080
- const metadata = tools.map((tool) => ({
5388
+ const metadata = tools.filter((tool) => !tool.hidden).map((tool) => ({
5081
5389
  name: tool.name,
5082
5390
  description: tool.help ?? tool.usage + `
5083
5391
  ` + tool.description
@@ -5086,7 +5394,7 @@ class NotebookExecutionRuntime {
5086
5394
  const outputHints = Object.fromEntries(tools.flatMap((tool) => ("textOutput" in tool) && tool.textOutput !== undefined ? [[tool.name, tool.textOutput]] : []));
5087
5395
  const wrapped = [
5088
5396
  `if (typeof globalThis.__piNotebook?.begin !== "function") throw new Error("Notebook runtime bootstrap unavailable: __piNotebook.begin");`,
5089
- `await globalThis.__piNotebook.begin(${JSON.stringify(id)}, ${JSON.stringify(metadata)}, JSON.parse(${JSON.stringify(JSON.stringify(toolNames))}), JSON.parse(${JSON.stringify(JSON.stringify(outputHints))}));`,
5397
+ `await globalThis.__piNotebook.begin(${JSON.stringify(id)}, ${JSON.stringify(metadata)}, JSON.parse(${JSON.stringify(JSON.stringify(toolNames))}), JSON.parse(${JSON.stringify(JSON.stringify(outputHints))}), ${JSON.stringify(namespaceDefinitions(tools))});`,
5090
5398
  code,
5091
5399
  `if (typeof globalThis.__piNotebook?.flush !== "function") throw new Error("Notebook runtime bootstrap unavailable: __piNotebook.flush");`,
5092
5400
  `await globalThis.__piNotebook.flush(${JSON.stringify(id)});`,
@@ -9079,8 +9387,10 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
9079
9387
  };
9080
9388
  },
9081
9389
  });
9390
+ const __installToolNamespaces = ${installToolNamespacesSource};
9391
+ let __disposeToolNamespaces = __installToolNamespaces(__tools, []);
9082
9392
  const __runtime = {
9083
- async begin(cellId, tools, toolNames, toolOutputHints = {}) {
9393
+ async begin(cellId, tools, toolNames, toolOutputHints, toolNamespaceDefinitions) {
9084
9394
  if (__state.memoryTimer !== undefined) clearInterval(__state.memoryTimer);
9085
9395
  __state.cellId = cellId;
9086
9396
  __state.toolNames = toolNames;
@@ -9093,6 +9403,8 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
9093
9403
  __state.outputTruncated = false;
9094
9404
  globalThis.tools = __tools;
9095
9405
  globalThis.ALL_TOOLS = tools;
9406
+ __disposeToolNamespaces();
9407
+ __disposeToolNamespaces = __installToolNamespaces(__tools, toolNamespaceDefinitions);
9096
9408
  __state.cellGlobals = new Set(Object.getOwnPropertyNames(globalThis));
9097
9409
  await __reportMemory(cellId);
9098
9410
  __state.memoryTimer = setInterval(() => void __reportMemory(cellId).catch(() => undefined), 1000);
@@ -9120,6 +9432,7 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
9120
9432
  if (__state.memoryTimer !== undefined) clearInterval(__state.memoryTimer);
9121
9433
  __state.memoryTimer = undefined;
9122
9434
  __state.cellId = null;
9435
+ __disposeToolNamespaces();
9123
9436
  },
9124
9437
  projectBindings() {
9125
9438
  return [...__state.projectBindings].sort();
@@ -10514,6 +10827,7 @@ var HOST_BINDINGS = new Set([
10514
10827
  "notify",
10515
10828
  "store",
10516
10829
  "text",
10830
+ "toolNamespaces",
10517
10831
  "tools",
10518
10832
  "yield_control"
10519
10833
  ]);
@@ -10940,13 +11254,15 @@ function createNotebookEngine(options) {
10940
11254
  const contract = readToolContract(registration);
10941
11255
  return {
10942
11256
  name: registration.name,
11257
+ hidden: contract.nestedHidden || contract.jsNamespace !== undefined,
11258
+ ...contract.nestedHidden || contract.jsNamespace === undefined ? {} : { jsNamespace: contract.jsNamespace },
10943
11259
  description: contract.description,
10944
11260
  usage: contract.usage,
10945
11261
  help: contract.help,
10946
11262
  ...registration.name === "exec_command" || registration.name === "write_stdin" ? { textOutput: "plain-command" } : {},
10947
11263
  async invoke(input, _context, signal) {
10948
11264
  signal.throwIfAborted();
10949
- const args = copyJson11(input === undefined ? null : input, {
11265
+ const args = copyJson13(input === undefined ? null : input, {
10950
11266
  omitUndefinedProperties: true
10951
11267
  });
10952
11268
  const invoke = api.tools[registration.name];
@@ -11099,7 +11415,7 @@ function parseNotebookRequest(input) {
11099
11415
  }
11100
11416
 
11101
11417
  // packages/notebook/src/tool-observation.ts
11102
- import { copyJson as copyJson12 } from "@earendil-works/chord";
11418
+ import { copyJson as copyJson14 } from "@earendil-works/chord/json";
11103
11419
  import {
11104
11420
  defineDocFamily as defineDocFamily2
11105
11421
  } from "@earendil-works/pi-durable";
@@ -11154,7 +11470,7 @@ async function observeNotebookCell(observation, maxTokens, api, context) {
11154
11470
  cell_id: String(observation.cellId),
11155
11471
  status: observation.status,
11156
11472
  ...observation.forwardedToolCalls === undefined ? {} : {
11157
- forwardedToolCalls: copyJson12(observation.forwardedToolCalls, {
11473
+ forwardedToolCalls: copyJson14(observation.forwardedToolCalls, {
11158
11474
  omitUndefinedProperties: true
11159
11475
  })
11160
11476
  },
@@ -11304,15 +11620,15 @@ function createNotebookMode(options) {
11304
11620
  };
11305
11621
  return {
11306
11622
  output: [{ type: "text", text: result.message }],
11307
- details: copyJson13(result.details),
11308
- structuredOutput: copyJson13(result)
11623
+ details: copyJson15(result.details),
11624
+ structuredOutput: copyJson15(result)
11309
11625
  };
11310
11626
  }
11311
11627
  const result = await engine.control(request, api, context);
11312
11628
  return {
11313
11629
  output: [{ type: "text", text: result.message }],
11314
- details: copyJson13(result.details, { omitUndefinedProperties: true }),
11315
- structuredOutput: copyJson13(result, { omitUndefinedProperties: true })
11630
+ details: copyJson15(result.details, { omitUndefinedProperties: true }),
11631
+ structuredOutput: copyJson15(result, { omitUndefinedProperties: true })
11316
11632
  };
11317
11633
  }
11318
11634
  });
@@ -11325,7 +11641,7 @@ function createNotebookMode(options) {
11325
11641
  ...notebook,
11326
11642
  executionHints: {
11327
11643
  discovery: "help",
11328
- inputSchema: copyJson13(JSON.parse(JSON.stringify(Type4.Union([NOTEBOOK_PARAMETERS, NOTEBOOK_ACTION_PARAMETERS]))))
11644
+ inputSchema: copyJson15(JSON.parse(JSON.stringify(Type4.Union([NOTEBOOK_PARAMETERS, NOTEBOOK_ACTION_PARAMETERS]))))
11329
11645
  }
11330
11646
  },
11331
11647
  ...shell.tools
@@ -11333,7 +11649,7 @@ function createNotebookMode(options) {
11333
11649
  sections: [
11334
11650
  section("notebook", (input) => {
11335
11651
  const base = 'exec: TypeScript, top-level await and globals persist. Run normal exec cells sequentially. A leading // @exec: {"isolated":true} runs a separate kernel from committed state, up to four at once; completion saves a candidate without changing live bindings. Use wait to continue or terminate. Bare values are discarded. Use text(value), image(value), generatedImage(value), notify(value), store(key,value), load(key), exit() and yield_control(). ALL_TOOLS lists selected tool contracts. Reuse matching retained globals. Keep one-offs block-local. Retain only what you plan to reuse, and clean up when the task ends. Keep retained helpers self-contained; recreate imports, closures and live handles after restart. Keep canonical project artifacts in files and carry shell state through files or arguments. Ask before adding npm imports inside this Deno notebook, then use exact-version npm: specifiers. This rule does not govern repository dependencies. Inside exec tools.notebook supports status without query, list and diagnostics. Run other notebook actions after exec returns.';
11336
- 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);
11652
+ const promoted = input.agent.callable.filter((tool) => !["exec", "wait", "notebook"].includes(tool.name)).map(readToolContract).flatMap(jsToolPrompt);
11337
11653
  return [base, nestedToolDiscoveryGuidance, ...promoted].join(`
11338
11654
  `);
11339
11655
  })