@howaboua/pi-durable-notebook 0.10.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/activation.js +440 -121
- package/dist/execution/src/cell-contract.d.ts +2 -1
- package/dist/execution/src/cell-observation.d.ts +1 -1
- package/dist/execution/src/cell-progress.d.ts +1 -1
- package/dist/execution/src/cell-tools.d.ts +2 -1
- package/dist/execution/src/cells.d.ts +1 -1
- package/dist/execution/src/custom-commands.d.ts +3 -2
- package/dist/execution/src/history.d.ts +1 -1
- package/dist/execution/src/invocation-state.d.ts +1 -1
- package/dist/execution/src/invocation.d.ts +79 -2
- package/dist/execution/src/native-tools.d.ts +18 -7
- package/dist/execution/src/nested-call.d.ts +11 -3
- package/dist/execution/src/nested-park.d.ts +9 -0
- package/dist/execution/src/nested-result.d.ts +1 -1
- package/dist/execution/src/tool-contract.d.ts +10 -3
- package/dist/execution/src/tool-namespaces.d.ts +31 -0
- package/dist/execution/src/tool-origin.d.ts +9 -1
- package/dist/execution/src/wait-session.d.ts +1 -1
- package/dist/history.js +18 -11
- package/dist/index.js +440 -121
- package/dist/notebook/src/engine.d.ts +1 -1
- package/dist/notebook/src/history.d.ts +4 -4
- package/dist/notebook/src/index.d.ts +7 -4
- package/dist/notebook/src/runtime-contract.d.ts +3 -0
- package/dist/notebook/src/tool-observation.d.ts +5 -4
- package/package.json +10 -9
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// packages/notebook/src/index.ts
|
|
2
|
-
import { copyJson as
|
|
2
|
+
import { copyJson as copyJson15 } from "@earendil-works/chord/json";
|
|
3
3
|
import {
|
|
4
4
|
defineExtension as defineExtension3,
|
|
5
5
|
defineTool as defineTool3,
|
|
@@ -71,8 +71,8 @@ function parseInteger(value, name, minimum = 0, maximum = Number.MAX_SAFE_INTEGE
|
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
// packages/execution/src/cells.ts
|
|
74
|
-
import {
|
|
75
|
-
import {
|
|
74
|
+
import { withCancel as withCancel2 } from "@earendil-works/chord/context";
|
|
75
|
+
import { copyJson as copyJson12 } from "@earendil-works/chord/json";
|
|
76
76
|
import {
|
|
77
77
|
defineExtension
|
|
78
78
|
} from "@earendil-works/pi-durable";
|
|
@@ -83,7 +83,7 @@ import {
|
|
|
83
83
|
} from "@earendil-works/pi-durable";
|
|
84
84
|
|
|
85
85
|
// packages/execution/src/forwarding.ts
|
|
86
|
-
import { copyJson as copyJson2 } from "@earendil-works/chord";
|
|
86
|
+
import { copyJson as copyJson2 } from "@earendil-works/chord/json";
|
|
87
87
|
import {
|
|
88
88
|
LiveDoc,
|
|
89
89
|
NestedCallDoc,
|
|
@@ -93,7 +93,7 @@ import {
|
|
|
93
93
|
// packages/execution/src/invocation-state.ts
|
|
94
94
|
import {
|
|
95
95
|
copyJson
|
|
96
|
-
} from "@earendil-works/chord";
|
|
96
|
+
} from "@earendil-works/chord/json";
|
|
97
97
|
import {
|
|
98
98
|
defineDoc
|
|
99
99
|
} from "@earendil-works/pi-durable";
|
|
@@ -570,7 +570,7 @@ async function observeCell(kind, id, api, context, budget) {
|
|
|
570
570
|
}
|
|
571
571
|
|
|
572
572
|
// packages/execution/src/cell-progress.ts
|
|
573
|
-
import { copyJson as copyJson3 } from "@earendil-works/chord";
|
|
573
|
+
import { copyJson as copyJson3 } from "@earendil-works/chord/json";
|
|
574
574
|
import {
|
|
575
575
|
LiveDoc as LiveDoc2
|
|
576
576
|
} from "@earendil-works/pi-durable";
|
|
@@ -597,8 +597,14 @@ async function observeCellProgress(id, api, context, budget) {
|
|
|
597
597
|
return work;
|
|
598
598
|
};
|
|
599
599
|
const live = await api.watchDoc(LiveDoc2, api.conversationId, context);
|
|
600
|
-
cell.start((
|
|
601
|
-
|
|
600
|
+
cell.start((call) => own(async () => {
|
|
601
|
+
if (call.kind === "failed")
|
|
602
|
+
throw call.error;
|
|
603
|
+
await publish(call.value);
|
|
604
|
+
}));
|
|
605
|
+
live?.start((call) => own(async () => {
|
|
606
|
+
if (call.kind === "failed")
|
|
607
|
+
throw call.error;
|
|
602
608
|
await api.commit(async (tx) => {
|
|
603
609
|
const record = await tx.task(id);
|
|
604
610
|
if (record === undefined || record.state.status === "terminal")
|
|
@@ -618,43 +624,70 @@ async function observeCellProgress(id, api, context, budget) {
|
|
|
618
624
|
const endings = await Promise.all([cell.stop(), live?.stop()]);
|
|
619
625
|
await Promise.all([...pending]);
|
|
620
626
|
for (const ending of endings)
|
|
621
|
-
if (ending?.
|
|
627
|
+
if (ending?.kind === "listener_error" || ending?.kind === "failed")
|
|
622
628
|
throw ending.error;
|
|
623
629
|
};
|
|
624
630
|
}
|
|
625
631
|
|
|
626
632
|
// packages/execution/src/cell-task.ts
|
|
627
|
-
import { copyJson as copyJson8 } from "@earendil-works/chord";
|
|
628
633
|
import { withAbortSignal } from "@earendil-works/chord/context";
|
|
634
|
+
import { copyJson as copyJson8 } from "@earendil-works/chord/json";
|
|
629
635
|
import {
|
|
630
636
|
defineTask
|
|
631
637
|
} from "@earendil-works/pi-durable";
|
|
632
638
|
|
|
633
639
|
// packages/execution/src/cell-tools.ts
|
|
634
|
-
import { copyJson as copyJson6 } from "@earendil-works/chord";
|
|
635
640
|
import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
|
|
641
|
+
import { copyJson as copyJson6 } from "@earendil-works/chord/json";
|
|
636
642
|
|
|
637
643
|
// packages/execution/src/invocation.ts
|
|
638
|
-
import { copyJson as copyJson5 } from "@earendil-works/chord";
|
|
639
644
|
import { awaitWithContext } from "@earendil-works/chord/context";
|
|
645
|
+
import { copyJson as copyJson5 } from "@earendil-works/chord/json";
|
|
646
|
+
import {
|
|
647
|
+
NestedCallDoc as NestedCallDoc3
|
|
648
|
+
} from "@earendil-works/pi-durable";
|
|
649
|
+
import { equal } from "@earendil-works/pi-schema";
|
|
640
650
|
|
|
641
651
|
// packages/execution/src/native-tools.ts
|
|
642
|
-
import {
|
|
643
|
-
|
|
652
|
+
import {
|
|
653
|
+
withoutAbortSignal
|
|
654
|
+
} from "@earendil-works/chord/context";
|
|
655
|
+
import { copyJson as copyJson4 } from "@earendil-works/chord/json";
|
|
644
656
|
import {
|
|
645
657
|
LiveDoc as LiveDoc3,
|
|
646
658
|
NestedCallDoc as NestedCallDoc2,
|
|
647
|
-
ToolTask as
|
|
659
|
+
ToolTask as ToolTask3
|
|
648
660
|
} from "@earendil-works/pi-durable";
|
|
649
661
|
import { Equal } from "typebox/value";
|
|
650
|
-
|
|
662
|
+
|
|
663
|
+
// packages/execution/src/tool-origin.ts
|
|
664
|
+
import {
|
|
665
|
+
defineDoc as defineDoc2,
|
|
666
|
+
ToolTask as ToolTask2
|
|
667
|
+
} from "@earendil-works/pi-durable";
|
|
668
|
+
var ToolOriginDoc = defineDoc2({
|
|
669
|
+
kind: "howaboua.tool-origin",
|
|
670
|
+
version: 1,
|
|
671
|
+
scope: "task",
|
|
672
|
+
checkpointWhen: () => false,
|
|
673
|
+
initial: () => ({})
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
// packages/execution/src/native-tools.ts
|
|
677
|
+
function assertNestedKey(key) {
|
|
678
|
+
if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
|
|
679
|
+
throw new Error("Invalid nested call or task key");
|
|
680
|
+
}
|
|
681
|
+
function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
|
|
651
682
|
let sequence = 0;
|
|
652
683
|
const admissions = [];
|
|
653
|
-
|
|
684
|
+
async function execute(name, args, callContext, options = {}) {
|
|
654
685
|
assertLive();
|
|
686
|
+
if (options.key !== undefined)
|
|
687
|
+
assertNestedKey(options.key);
|
|
688
|
+
else if (resumed)
|
|
689
|
+
throw new Error("Nested calls require an explicit key after waking");
|
|
655
690
|
const key = options.key ?? String(++sequence);
|
|
656
|
-
if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
|
|
657
|
-
throw new Error("Invalid nested call key");
|
|
658
691
|
const call = {
|
|
659
692
|
type: "toolCall",
|
|
660
693
|
id: `${callId}/${key}`,
|
|
@@ -666,11 +699,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
666
699
|
const admission = runtime.commit(async (tx) => {
|
|
667
700
|
const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
|
|
668
701
|
if (slot.taskId !== undefined) {
|
|
669
|
-
const input = (await tx.task(slot.taskId))?.input;
|
|
702
|
+
const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
|
|
670
703
|
if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
|
|
671
704
|
throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
|
|
672
705
|
} else {
|
|
673
|
-
slot.
|
|
706
|
+
slot.kind = "nested";
|
|
707
|
+
slot.taskId = await tx.createTask(ToolTask3, {
|
|
674
708
|
kind: "nested",
|
|
675
709
|
parent: runtime.taskId,
|
|
676
710
|
parentCallId: callId,
|
|
@@ -682,6 +716,9 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
682
716
|
abandonOnRestart: replay !== "safe"
|
|
683
717
|
});
|
|
684
718
|
const live = await tx.doc(LiveDoc3, runtime.conversationId);
|
|
719
|
+
const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
|
|
720
|
+
if (origin)
|
|
721
|
+
(await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
|
|
685
722
|
live.nestedTools ??= [];
|
|
686
723
|
live.nestedTools.push({
|
|
687
724
|
callId: call.id,
|
|
@@ -713,7 +750,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
713
750
|
const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
|
|
714
751
|
if (slot?.taskId === undefined)
|
|
715
752
|
throw new Error("Nested task creation did not commit");
|
|
716
|
-
const
|
|
753
|
+
const taskId = slot.taskId;
|
|
754
|
+
const result = (resultContext) => readResult(name, key, taskId, resultContext);
|
|
755
|
+
return options.wait === false ? { taskId, result } : result(callContext);
|
|
756
|
+
}
|
|
757
|
+
async function readResult(name, key, taskId, callContext) {
|
|
758
|
+
assertLive();
|
|
759
|
+
const settled = await runtime.waitForTask(taskId, callContext);
|
|
717
760
|
const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
|
|
718
761
|
await runtime.commit(async (tx) => {
|
|
719
762
|
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
@@ -721,7 +764,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
721
764
|
return;
|
|
722
765
|
}, callContext);
|
|
723
766
|
return result === undefined ? {
|
|
724
|
-
taskId
|
|
767
|
+
taskId,
|
|
725
768
|
isError: true,
|
|
726
769
|
diagnostics: [
|
|
727
770
|
{
|
|
@@ -731,9 +774,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
731
774
|
}
|
|
732
775
|
]
|
|
733
776
|
} : copyJson4(result);
|
|
734
|
-
}
|
|
777
|
+
}
|
|
735
778
|
return {
|
|
736
779
|
execute,
|
|
780
|
+
async drain() {
|
|
781
|
+
await Promise.allSettled(admissions);
|
|
782
|
+
},
|
|
737
783
|
async finish() {
|
|
738
784
|
await Promise.allSettled(admissions);
|
|
739
785
|
await cleanupNativeCalls(runtime, withoutAbortSignal(context));
|
|
@@ -741,7 +787,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
741
787
|
};
|
|
742
788
|
}
|
|
743
789
|
async function cleanupNativeCalls(runtime, context) {
|
|
744
|
-
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind ===
|
|
790
|
+
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
|
|
745
791
|
await runtime.commit(async (tx) => {
|
|
746
792
|
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
747
793
|
await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
|
|
@@ -835,18 +881,6 @@ class Progress {
|
|
|
835
881
|
}
|
|
836
882
|
}
|
|
837
883
|
|
|
838
|
-
// packages/execution/src/tool-origin.ts
|
|
839
|
-
import {
|
|
840
|
-
defineDoc as defineDoc2
|
|
841
|
-
} from "@earendil-works/pi-durable";
|
|
842
|
-
var ToolOriginDoc = defineDoc2({
|
|
843
|
-
kind: "howaboua.tool-origin",
|
|
844
|
-
version: 1,
|
|
845
|
-
scope: "task",
|
|
846
|
-
checkpointWhen: () => false,
|
|
847
|
-
initial: () => ({})
|
|
848
|
-
});
|
|
849
|
-
|
|
850
884
|
// packages/execution/src/invocation.ts
|
|
851
885
|
function executionError(code, message) {
|
|
852
886
|
return {
|
|
@@ -858,21 +892,23 @@ function executionError(code, message) {
|
|
|
858
892
|
function errorText(error) {
|
|
859
893
|
return error instanceof Error ? error.message : String(error);
|
|
860
894
|
}
|
|
861
|
-
function createInvocation(runtime, tool, context) {
|
|
895
|
+
function createInvocation(runtime, tool, context, resume) {
|
|
862
896
|
const limits = {
|
|
863
897
|
maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
|
|
864
898
|
maxLines: tool.outputLimits?.maxLines ?? 2000,
|
|
865
899
|
retain: tool.outputLimits?.retain ?? "head"
|
|
866
900
|
};
|
|
867
901
|
const output = new OutputBuffer(limits);
|
|
868
|
-
const diagnostics = [
|
|
869
|
-
|
|
902
|
+
const diagnostics = [
|
|
903
|
+
...resume?.progress?.diagnostics ?? []
|
|
904
|
+
];
|
|
905
|
+
let details = resume?.progress?.details;
|
|
870
906
|
let ended = false;
|
|
871
907
|
const assertLive = () => {
|
|
872
908
|
if (ended)
|
|
873
909
|
throw new Error(`Invocation ${runtime.taskId} has settled`);
|
|
874
910
|
};
|
|
875
|
-
const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
|
|
911
|
+
const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
|
|
876
912
|
const snapshot = () => {
|
|
877
913
|
const retained = output.snapshot();
|
|
878
914
|
return {
|
|
@@ -901,6 +937,8 @@ function createInvocation(runtime, tool, context) {
|
|
|
901
937
|
taskId: runtime.taskId,
|
|
902
938
|
conversationId: runtime.conversationId,
|
|
903
939
|
callId: `nested-${runtime.taskId}`,
|
|
940
|
+
wake: resume?.wake,
|
|
941
|
+
checkpoint: resume?.checkpoint,
|
|
904
942
|
registry: runtime.registry,
|
|
905
943
|
agent: runtime.agent,
|
|
906
944
|
env: undefined,
|
|
@@ -921,7 +959,7 @@ function createInvocation(runtime, tool, context) {
|
|
|
921
959
|
const retained = output.snapshot();
|
|
922
960
|
return { text: retained.text, truncated: retained.droppedBytes > 0 };
|
|
923
961
|
},
|
|
924
|
-
executeTool:
|
|
962
|
+
executeTool: native.execute,
|
|
925
963
|
diagnostic: (value) => {
|
|
926
964
|
assertLive();
|
|
927
965
|
diagnostics.push(copyJson5(value, { omitUndefinedProperties: true }));
|
|
@@ -935,24 +973,44 @@ function createInvocation(runtime, tool, context) {
|
|
|
935
973
|
committed.catch(() => {});
|
|
936
974
|
await awaitWithContext(committed, detailContext);
|
|
937
975
|
},
|
|
938
|
-
commit: async (change, commitContext) => {
|
|
976
|
+
commit: async (change, commitContext, options) => {
|
|
939
977
|
assertLive();
|
|
940
978
|
let result;
|
|
941
979
|
await runtime.commit(async (tx) => {
|
|
942
980
|
result = await change(tx);
|
|
943
981
|
return;
|
|
944
|
-
}, commitContext);
|
|
982
|
+
}, commitContext, options);
|
|
945
983
|
return result;
|
|
946
984
|
},
|
|
947
985
|
memo: runtime.memo,
|
|
948
|
-
|
|
986
|
+
readSignal: runtime.readSignal,
|
|
987
|
+
async createTask(task, input, {
|
|
988
|
+
key,
|
|
989
|
+
...options
|
|
990
|
+
}, taskContext) {
|
|
949
991
|
assertLive();
|
|
992
|
+
if (key !== undefined)
|
|
993
|
+
assertNestedKey(key);
|
|
994
|
+
else if (resume?.wake !== undefined)
|
|
995
|
+
throw new Error("Child tasks require an explicit key after waking");
|
|
950
996
|
let id;
|
|
951
997
|
await runtime.commit(async (tx) => {
|
|
998
|
+
const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
|
|
999
|
+
if (member?.taskId !== undefined) {
|
|
1000
|
+
const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
|
|
1001
|
+
if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson5(input, { omitUndefinedProperties: true })))
|
|
1002
|
+
throw new Error(`Key ${key} was already used for another call or task`);
|
|
1003
|
+
id = member.taskId;
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
952
1006
|
id = await tx.createTask(task, input, {
|
|
953
1007
|
...options,
|
|
954
1008
|
...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
|
|
955
1009
|
});
|
|
1010
|
+
if (member !== undefined) {
|
|
1011
|
+
member.kind = "task";
|
|
1012
|
+
member.taskId = id;
|
|
1013
|
+
}
|
|
956
1014
|
const source = await tx.doc(ToolOriginDoc, runtime.taskId);
|
|
957
1015
|
if (source.origin !== undefined)
|
|
958
1016
|
(await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
|
|
@@ -999,6 +1057,14 @@ function createInvocation(runtime, tool, context) {
|
|
|
999
1057
|
for (const waiter of await progress.stop())
|
|
1000
1058
|
waiter.reject(error);
|
|
1001
1059
|
},
|
|
1060
|
+
async park() {
|
|
1061
|
+
ended = true;
|
|
1062
|
+
await native.drain();
|
|
1063
|
+
output.end();
|
|
1064
|
+
const pending = await progress.stop();
|
|
1065
|
+
const { output: _output, ...kept } = snapshot();
|
|
1066
|
+
return { progress: storeResult(kept), pending };
|
|
1067
|
+
},
|
|
1002
1068
|
limits,
|
|
1003
1069
|
output,
|
|
1004
1070
|
progress
|
|
@@ -1100,7 +1166,74 @@ function combineControls(controls, allowTermination = true) {
|
|
|
1100
1166
|
}
|
|
1101
1167
|
|
|
1102
1168
|
// packages/execution/src/tool-contract.ts
|
|
1103
|
-
import { copyJson as copyJson7 } from "@earendil-works/chord";
|
|
1169
|
+
import { copyJson as copyJson7 } from "@earendil-works/chord/json";
|
|
1170
|
+
|
|
1171
|
+
// packages/execution/src/tool-namespaces.ts
|
|
1172
|
+
import { isJsonValue } from "@earendil-works/chord/json";
|
|
1173
|
+
function validateJsToolNamespace(tool, namespace) {
|
|
1174
|
+
const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
|
|
1175
|
+
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))))
|
|
1176
|
+
throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
|
|
1177
|
+
}
|
|
1178
|
+
function jsToolPrompt(contract) {
|
|
1179
|
+
if (contract.nativeOnly || contract.nestedHidden)
|
|
1180
|
+
return [];
|
|
1181
|
+
if (contract.jsNamespace)
|
|
1182
|
+
return [contract.jsNamespace.prompt];
|
|
1183
|
+
return contract.deferLoading ? [] : [contract.prompt];
|
|
1184
|
+
}
|
|
1185
|
+
function namespaceDefinitions(tools) {
|
|
1186
|
+
return tools.flatMap(({ name, jsNamespace }) => jsNamespace ? [{ tool: name, name: jsNamespace.name, methods: jsNamespace.methods }] : []);
|
|
1187
|
+
}
|
|
1188
|
+
var installToolNamespacesSource = `(tools, definitions) => {
|
|
1189
|
+
const namespaces = Object.create(null);
|
|
1190
|
+
const binders = Object.create(null);
|
|
1191
|
+
let active = true;
|
|
1192
|
+
const add = (target, key, value) => {
|
|
1193
|
+
if (Object.hasOwn(target, key)) throw new Error("Duplicate tool namespace member: " + key);
|
|
1194
|
+
target[key] = value;
|
|
1195
|
+
};
|
|
1196
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1197
|
+
for (const { tool, name, methods } of definitions) {
|
|
1198
|
+
const namespace = namespaces[name] ??= Object.create(null);
|
|
1199
|
+
const bound = binders[name] ??= Object.create(null);
|
|
1200
|
+
for (const { name: method, bind, defaults } of methods) {
|
|
1201
|
+
const invoke = (args, ref) => {
|
|
1202
|
+
if (!active)
|
|
1203
|
+
throw new Error("Tool namespace binding expired; bind the server reference again in this cell");
|
|
1204
|
+
if (args !== undefined && !object(args))
|
|
1205
|
+
throw new TypeError("Tool namespace arguments must be an object");
|
|
1206
|
+
return tools[tool]({ ...args, ...defaults, ...(bind === undefined ? {} : { [bind]: ref }) });
|
|
1207
|
+
};
|
|
1208
|
+
if (bind === undefined) {
|
|
1209
|
+
add(namespace, method, (args) => invoke(args));
|
|
1210
|
+
continue;
|
|
1211
|
+
}
|
|
1212
|
+
if (!Object.hasOwn(bound, bind)) {
|
|
1213
|
+
const members = bound[bind] = Object.create(null);
|
|
1214
|
+
add(namespace, bind, (ref) => {
|
|
1215
|
+
if (!object(ref)) throw new TypeError("Supply a discovered namespace reference");
|
|
1216
|
+
const reference = { ...ref };
|
|
1217
|
+
const result = Object.create(null);
|
|
1218
|
+
for (const [key, call] of Object.entries(members))
|
|
1219
|
+
result[key] = (args) => call(args, reference);
|
|
1220
|
+
return Object.freeze(result);
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1223
|
+
add(bound[bind], method, invoke);
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
for (const namespace of Object.values(namespaces)) Object.freeze(namespace);
|
|
1227
|
+
globalThis.toolNamespaces = Object.freeze(namespaces);
|
|
1228
|
+
return () => {
|
|
1229
|
+
active = false;
|
|
1230
|
+
if (globalThis.toolNamespaces === namespaces)
|
|
1231
|
+
globalThis.toolNamespaces = Object.freeze(Object.create(null));
|
|
1232
|
+
};
|
|
1233
|
+
}`;
|
|
1234
|
+
|
|
1235
|
+
// packages/execution/src/tool-contract.ts
|
|
1236
|
+
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 {}";
|
|
1104
1237
|
function readToolContract(tool) {
|
|
1105
1238
|
const candidate = "executionHints" in tool ? tool.executionHints : undefined;
|
|
1106
1239
|
if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
|
|
@@ -1114,6 +1247,7 @@ function readToolContract(tool) {
|
|
|
1114
1247
|
"yieldTimeMs",
|
|
1115
1248
|
"inputSchema",
|
|
1116
1249
|
"nativeOnly",
|
|
1250
|
+
"nestedHidden",
|
|
1117
1251
|
"discovery"
|
|
1118
1252
|
]);
|
|
1119
1253
|
for (const key of Object.keys(hints))
|
|
@@ -1137,6 +1271,12 @@ function readToolContract(tool) {
|
|
|
1137
1271
|
const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
|
|
1138
1272
|
if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
|
|
1139
1273
|
throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
|
|
1274
|
+
const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
|
|
1275
|
+
const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
|
|
1276
|
+
if (jsNamespace !== undefined)
|
|
1277
|
+
validateJsToolNamespace(tool.name, jsNamespace);
|
|
1278
|
+
if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
|
|
1279
|
+
throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
|
|
1140
1280
|
const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
|
|
1141
1281
|
if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
|
|
1142
1282
|
throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
|
|
@@ -1153,6 +1293,8 @@ function readToolContract(tool) {
|
|
|
1153
1293
|
inputSchema,
|
|
1154
1294
|
deferLoading: typeof deferred === "boolean" ? deferred : true,
|
|
1155
1295
|
nativeOnly: nativeOnly === true,
|
|
1296
|
+
nestedHidden: nestedHidden === true,
|
|
1297
|
+
...jsNamespace === undefined ? {} : { jsNamespace },
|
|
1156
1298
|
...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
|
|
1157
1299
|
...outputHint === undefined ? {} : { output: outputHint },
|
|
1158
1300
|
help: [
|
|
@@ -1388,7 +1530,7 @@ function createCellTask(options, nestedTask) {
|
|
|
1388
1530
|
import {
|
|
1389
1531
|
hook,
|
|
1390
1532
|
LiveDoc as LiveDoc4,
|
|
1391
|
-
ToolTask as
|
|
1533
|
+
ToolTask as ToolTask4
|
|
1392
1534
|
} from "@earendil-works/pi-durable";
|
|
1393
1535
|
function forwardingHook() {
|
|
1394
1536
|
let host;
|
|
@@ -1398,7 +1540,7 @@ function forwardingHook() {
|
|
|
1398
1540
|
throw new Error("Create a separate execution component for each Harness");
|
|
1399
1541
|
host = harness;
|
|
1400
1542
|
},
|
|
1401
|
-
hook: hook(
|
|
1543
|
+
hook: hook(ToolTask4, {
|
|
1402
1544
|
async beforeTool(call, api, context) {
|
|
1403
1545
|
const parent = call.parent;
|
|
1404
1546
|
if (parent === undefined || host === undefined)
|
|
@@ -1411,7 +1553,7 @@ function forwardingHook() {
|
|
|
1411
1553
|
if (conversation === undefined)
|
|
1412
1554
|
throw new Error("Forwarded call conversation is unavailable");
|
|
1413
1555
|
await conversation.commit(async (tx) => {
|
|
1414
|
-
if ((await tx.task(api.taskId))?.kind !==
|
|
1556
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
|
|
1415
1557
|
return;
|
|
1416
1558
|
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1417
1559
|
const admission = owner.forwardingCellId === undefined;
|
|
@@ -1438,7 +1580,7 @@ function forwardingHook() {
|
|
|
1438
1580
|
if (conversation === undefined)
|
|
1439
1581
|
throw new Error("Forwarded call conversation is unavailable");
|
|
1440
1582
|
await conversation.commit(async (tx) => {
|
|
1441
|
-
if ((await tx.task(api.taskId))?.kind !==
|
|
1583
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
|
|
1442
1584
|
return;
|
|
1443
1585
|
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1444
1586
|
const cellId = owner.forwardingCellId;
|
|
@@ -1463,17 +1605,18 @@ function forwardingHook() {
|
|
|
1463
1605
|
}
|
|
1464
1606
|
|
|
1465
1607
|
// packages/execution/src/nested.ts
|
|
1608
|
+
import { copyJson as copyJson11 } from "@earendil-works/chord/json";
|
|
1466
1609
|
import {
|
|
1467
1610
|
defineTask as defineTask2
|
|
1468
1611
|
} from "@earendil-works/pi-durable";
|
|
1469
|
-
import {
|
|
1612
|
+
import { compile as compile2 } from "@earendil-works/pi-schema";
|
|
1470
1613
|
|
|
1471
1614
|
// packages/execution/src/nested-call.ts
|
|
1472
1615
|
import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
|
|
1473
1616
|
import {
|
|
1474
|
-
ToolTask as
|
|
1617
|
+
ToolTask as ToolTask5
|
|
1475
1618
|
} from "@earendil-works/pi-durable";
|
|
1476
|
-
import {
|
|
1619
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
1477
1620
|
function nestedCall(runtime, input) {
|
|
1478
1621
|
const args = input.arguments;
|
|
1479
1622
|
return {
|
|
@@ -1494,7 +1637,7 @@ function prepareNestedInput(tool, input) {
|
|
|
1494
1637
|
if (typeof input !== "string")
|
|
1495
1638
|
return input;
|
|
1496
1639
|
const contract = readToolContract(tool);
|
|
1497
|
-
if (Boolean(
|
|
1640
|
+
if (Boolean(compile(tool.parameters).check(input)) || (typeof contract.inputSchema === "boolean" || typeof contract.inputSchema === "object" && contract.inputSchema !== null && !Array.isArray(contract.inputSchema)) && Boolean(compile(contract.inputSchema).check(input)))
|
|
1498
1641
|
return input;
|
|
1499
1642
|
const text = input.trim();
|
|
1500
1643
|
if (contract.discovery === "help" && text === "help")
|
|
@@ -1517,7 +1660,7 @@ function prepareNestedInput(tool, input) {
|
|
|
1517
1660
|
async function eachHook(agent, name, api, invoke) {
|
|
1518
1661
|
for (const extension of agent.extensions)
|
|
1519
1662
|
for (const registration of extension.hooks ?? []) {
|
|
1520
|
-
if (registration.task !==
|
|
1663
|
+
if (registration.task !== ToolTask5.definition.name)
|
|
1521
1664
|
continue;
|
|
1522
1665
|
const handler = registration.handlers[name];
|
|
1523
1666
|
if (handler === undefined)
|
|
@@ -1532,8 +1675,120 @@ async function eachHook(agent, name, api, invoke) {
|
|
|
1532
1675
|
}
|
|
1533
1676
|
}
|
|
1534
1677
|
|
|
1678
|
+
// packages/execution/src/nested-park.ts
|
|
1679
|
+
import {
|
|
1680
|
+
withCancel,
|
|
1681
|
+
withoutAbortSignal as withoutAbortSignal3
|
|
1682
|
+
} from "@earendil-works/chord/context";
|
|
1683
|
+
import { copyJson as copyJson9 } from "@earendil-works/chord/json";
|
|
1684
|
+
var resultFields = [
|
|
1685
|
+
"output",
|
|
1686
|
+
"structuredOutput",
|
|
1687
|
+
"isError",
|
|
1688
|
+
"details",
|
|
1689
|
+
"diagnostics",
|
|
1690
|
+
"usage",
|
|
1691
|
+
"control"
|
|
1692
|
+
];
|
|
1693
|
+
function sleepState(checkpoint, { until, signals }) {
|
|
1694
|
+
return {
|
|
1695
|
+
status: "sleeping",
|
|
1696
|
+
checkpoint,
|
|
1697
|
+
...until === undefined ? {} : { until },
|
|
1698
|
+
...signals === undefined ? {} : { signals }
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
async function parkGate(runtime, sleep, context) {
|
|
1702
|
+
try {
|
|
1703
|
+
await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
|
|
1704
|
+
} catch (error) {
|
|
1705
|
+
runtime.signal.throwIfAborted();
|
|
1706
|
+
return errorText(error);
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
async function parkTool(runtime, invocation, tool, args, park, context) {
|
|
1710
|
+
if (park.kind !== "sleep" && park.kind !== "wait")
|
|
1711
|
+
return "Unknown park kind";
|
|
1712
|
+
const mixed = resultFields.find((field) => (field in park));
|
|
1713
|
+
if (mixed !== undefined)
|
|
1714
|
+
return `A park cannot carry the result field ${mixed}`;
|
|
1715
|
+
const intent = {
|
|
1716
|
+
arguments: args,
|
|
1717
|
+
replay: tool.replay ?? "unsafe",
|
|
1718
|
+
...park.checkpoint === undefined ? {} : { checkpoint: copyJson9(park.checkpoint) }
|
|
1719
|
+
};
|
|
1720
|
+
const { progress, pending } = await invocation.park();
|
|
1721
|
+
try {
|
|
1722
|
+
await runtime.commit(async (tx) => {
|
|
1723
|
+
if (park.kind === "wait") {
|
|
1724
|
+
for (const id of park.on)
|
|
1725
|
+
if ((await tx.task(id))?.owner !== runtime.taskId)
|
|
1726
|
+
throw new Error(`Task ${id} is not owned by the call`);
|
|
1727
|
+
}
|
|
1728
|
+
const checkpoint = { ...intent, phase: "parked" };
|
|
1729
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1730
|
+
doc.result = progress;
|
|
1731
|
+
doc.droppedBytes = 0;
|
|
1732
|
+
doc.droppedLines = 0;
|
|
1733
|
+
await forwardInvocationResult(tx, runtime.taskId, progress, "running");
|
|
1734
|
+
return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
|
|
1735
|
+
}, context);
|
|
1736
|
+
} catch (error) {
|
|
1737
|
+
for (const waiter of pending)
|
|
1738
|
+
waiter.reject(error);
|
|
1739
|
+
const detached = withoutAbortSignal3(context);
|
|
1740
|
+
const record = await runtime.getTask(runtime.taskId, detached);
|
|
1741
|
+
if (record?.abortRequested) {
|
|
1742
|
+
const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
|
|
1743
|
+
if (watch !== undefined) {
|
|
1744
|
+
const cleanup = withCancel(detached);
|
|
1745
|
+
watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
|
|
1746
|
+
try {
|
|
1747
|
+
await cancelParkedTool(runtime, tool, intent, cleanup.context);
|
|
1748
|
+
} finally {
|
|
1749
|
+
await watch.stop();
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
throw error;
|
|
1753
|
+
}
|
|
1754
|
+
runtime.signal.throwIfAborted();
|
|
1755
|
+
return errorText(error);
|
|
1756
|
+
}
|
|
1757
|
+
for (const waiter of pending)
|
|
1758
|
+
waiter.resolve();
|
|
1759
|
+
}
|
|
1760
|
+
async function cancelParkedTool(runtime, tool, intent, context) {
|
|
1761
|
+
if (!tool) {
|
|
1762
|
+
runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
if (tool.cancel === undefined)
|
|
1766
|
+
return;
|
|
1767
|
+
const cleanup = createInvocation(runtime, tool, context, {
|
|
1768
|
+
checkpoint: intent.checkpoint,
|
|
1769
|
+
wake: undefined
|
|
1770
|
+
});
|
|
1771
|
+
const refuseWork = () => {
|
|
1772
|
+
throw new Error("A tool cannot start tasks or nested calls during cancellation");
|
|
1773
|
+
};
|
|
1774
|
+
let reason = new Error("Tool cancellation finished");
|
|
1775
|
+
try {
|
|
1776
|
+
const api = await cleanup.executionApi();
|
|
1777
|
+
await tool.cancel(intent.arguments, {
|
|
1778
|
+
...api,
|
|
1779
|
+
createTask: refuseWork,
|
|
1780
|
+
executeTool: refuseWork
|
|
1781
|
+
}, context);
|
|
1782
|
+
} catch (error) {
|
|
1783
|
+
reason = error;
|
|
1784
|
+
runtime.report(error);
|
|
1785
|
+
} finally {
|
|
1786
|
+
await cleanup.stop(reason);
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1535
1790
|
// packages/execution/src/nested-result.ts
|
|
1536
|
-
import { copyJson as
|
|
1791
|
+
import { copyJson as copyJson10 } from "@earendil-works/chord/json";
|
|
1537
1792
|
import {
|
|
1538
1793
|
defineEntry,
|
|
1539
1794
|
UsageDoc
|
|
@@ -1581,11 +1836,11 @@ async function settle(runtime, call, result, ending, context) {
|
|
|
1581
1836
|
taskId: runtime.taskId,
|
|
1582
1837
|
callId: call.id,
|
|
1583
1838
|
name: call.name,
|
|
1584
|
-
arguments:
|
|
1839
|
+
arguments: copyJson10(call.arguments),
|
|
1585
1840
|
result: stored,
|
|
1586
1841
|
...current.state.checkpoint.phase === "execute" ? {
|
|
1587
1842
|
intent: {
|
|
1588
|
-
arguments:
|
|
1843
|
+
arguments: copyJson10(current.state.checkpoint.arguments),
|
|
1589
1844
|
replay: current.state.checkpoint.replay
|
|
1590
1845
|
}
|
|
1591
1846
|
} : {}
|
|
@@ -1594,7 +1849,7 @@ async function settle(runtime, call, result, ending, context) {
|
|
|
1594
1849
|
if (result.usage !== undefined) {
|
|
1595
1850
|
const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
|
|
1596
1851
|
const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
|
|
1597
|
-
totals[call.name] =
|
|
1852
|
+
totals[call.name] = copyJson10(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
|
|
1598
1853
|
}
|
|
1599
1854
|
const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
|
|
1600
1855
|
status: ending,
|
|
@@ -1631,7 +1886,11 @@ function sumUsage(previous, added) {
|
|
|
1631
1886
|
function createNestedToolTask(name) {
|
|
1632
1887
|
return defineTask2({
|
|
1633
1888
|
name,
|
|
1634
|
-
version:
|
|
1889
|
+
version: 2,
|
|
1890
|
+
migrate: (input, checkpoint) => ({
|
|
1891
|
+
input,
|
|
1892
|
+
checkpoint
|
|
1893
|
+
}),
|
|
1635
1894
|
initial: () => ({ phase: "call" }),
|
|
1636
1895
|
phases: {
|
|
1637
1896
|
call: async (task, runtime, context) => {
|
|
@@ -1657,22 +1916,25 @@ function createNestedToolTask(name) {
|
|
|
1657
1916
|
return reject(runtime, call, executionError("tool_unavailable", `Tool ${call.name} is not available`), agent, tool, context);
|
|
1658
1917
|
let args;
|
|
1659
1918
|
try {
|
|
1660
|
-
const supplied = task.input.arguments === null && !
|
|
1919
|
+
const supplied = task.input.arguments === null && !compile2(tool.parameters).check(null) && compile2(tool.parameters).check({}) ? undefined : task.input.arguments;
|
|
1661
1920
|
const prepared = tool.prepareArguments === undefined ? prepareNestedInput(tool, supplied) : tool.prepareArguments(prepareNestedInput(tool, supplied));
|
|
1662
|
-
args = checked(tool, call, prepared === undefined &&
|
|
1921
|
+
args = checked(tool, call, prepared === undefined && compile2(tool.parameters).check({}) ? {} : prepared);
|
|
1663
1922
|
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1664
1923
|
call.arguments = args;
|
|
1665
1924
|
} catch (error) {
|
|
1666
1925
|
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1667
1926
|
}
|
|
1668
1927
|
let block;
|
|
1928
|
+
let sleep;
|
|
1669
1929
|
await eachHook(agent, "beforeTool", runtime, async (handler) => {
|
|
1670
|
-
if (block !== undefined)
|
|
1930
|
+
if (block !== undefined || sleep !== undefined)
|
|
1671
1931
|
return;
|
|
1672
1932
|
try {
|
|
1673
1933
|
const decision = await handler({ ...call, arguments: args }, runtime, context);
|
|
1674
1934
|
if (decision?.block !== undefined)
|
|
1675
1935
|
block = decision.block;
|
|
1936
|
+
else if (decision?.sleep !== undefined)
|
|
1937
|
+
sleep = decision.sleep;
|
|
1676
1938
|
else if (decision?.arguments !== undefined)
|
|
1677
1939
|
args = decision.arguments;
|
|
1678
1940
|
} catch (error) {
|
|
@@ -1683,71 +1945,122 @@ function createNestedToolTask(name) {
|
|
|
1683
1945
|
});
|
|
1684
1946
|
if (block !== undefined)
|
|
1685
1947
|
return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
|
|
1948
|
+
if (sleep !== undefined) {
|
|
1949
|
+
const reason = await parkGate(runtime, sleep, context);
|
|
1950
|
+
if (reason === undefined)
|
|
1951
|
+
return;
|
|
1952
|
+
return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
|
|
1953
|
+
}
|
|
1686
1954
|
try {
|
|
1687
|
-
args = checked(tool, call, args)
|
|
1955
|
+
args = copyJson11(checked(tool, call, args), {
|
|
1956
|
+
omitUndefinedProperties: true
|
|
1957
|
+
});
|
|
1688
1958
|
} catch (error) {
|
|
1689
1959
|
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1690
1960
|
}
|
|
1691
|
-
await runtime
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
callId: call.id,
|
|
1695
|
-
parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
|
|
1696
|
-
name: call.name,
|
|
1697
|
-
arguments: args,
|
|
1698
|
-
status: "running",
|
|
1699
|
-
result: null,
|
|
1700
|
-
omittedFields: []
|
|
1701
|
-
});
|
|
1702
|
-
return {
|
|
1703
|
-
status: "running",
|
|
1704
|
-
checkpoint: {
|
|
1705
|
-
phase: "execute",
|
|
1706
|
-
arguments: args,
|
|
1707
|
-
replay: tool.replay ?? "unsafe"
|
|
1708
|
-
}
|
|
1709
|
-
};
|
|
1961
|
+
await startAttempt(runtime, call, tool, agent, {
|
|
1962
|
+
arguments: args,
|
|
1963
|
+
replay: tool.replay ?? "unsafe"
|
|
1710
1964
|
}, context);
|
|
1711
|
-
|
|
1965
|
+
},
|
|
1966
|
+
parked: async (task, runtime, context) => {
|
|
1967
|
+
const intent = task.state.checkpoint;
|
|
1968
|
+
const call = nestedCall(runtime, task.input);
|
|
1969
|
+
call.arguments = intent.arguments;
|
|
1970
|
+
const agent = await runtime.agent(context);
|
|
1971
|
+
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1972
|
+
if (tool === undefined || readToolContract(tool).nativeOnly)
|
|
1973
|
+
return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
|
|
1974
|
+
await startAttempt(runtime, call, tool, agent, {
|
|
1975
|
+
...intent,
|
|
1976
|
+
replay: tool.replay ?? "unsafe"
|
|
1977
|
+
}, context, task.state.wake);
|
|
1712
1978
|
},
|
|
1713
1979
|
execute: async (task, runtime, context) => {
|
|
1980
|
+
const intent = task.state.checkpoint;
|
|
1714
1981
|
const call = nestedCall(runtime, task.input);
|
|
1715
1982
|
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1716
1983
|
call.arguments = task.state.checkpoint.arguments;
|
|
1717
1984
|
const agent = await runtime.agent(context);
|
|
1718
1985
|
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1719
|
-
if (
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1986
|
+
if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
|
|
1987
|
+
if (intent.resume === undefined)
|
|
1988
|
+
await runtime.commit(async (tx) => {
|
|
1989
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1990
|
+
doc.result = {};
|
|
1991
|
+
doc.droppedBytes = 0;
|
|
1992
|
+
doc.droppedLines = 0;
|
|
1993
|
+
return;
|
|
1994
|
+
}, context);
|
|
1995
|
+
return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
|
|
1728
1996
|
}
|
|
1997
|
+
if (intent.resume !== undefined)
|
|
1998
|
+
await cancelParkedTool(runtime, tool, intent, context);
|
|
1729
1999
|
await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
|
|
1730
2000
|
}
|
|
1731
2001
|
},
|
|
1732
2002
|
abort: async (task, runtime, context) => {
|
|
1733
2003
|
const call = nestedCall(runtime, task.input);
|
|
2004
|
+
const intent = task.state.checkpoint;
|
|
2005
|
+
if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
|
|
2006
|
+
const agent = await runtime.agent(context);
|
|
2007
|
+
const tool = agent.callable.find((each) => each.name === call.name);
|
|
2008
|
+
await cancelParkedTool(runtime, tool, intent, context);
|
|
2009
|
+
}
|
|
1734
2010
|
await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
|
|
1735
2011
|
}
|
|
1736
2012
|
});
|
|
1737
2013
|
}
|
|
2014
|
+
async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
|
|
2015
|
+
await runtime.commit(async (tx) => {
|
|
2016
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
2017
|
+
await forwardCall(tx, doc.forwardingCellId, {
|
|
2018
|
+
callId: call.id,
|
|
2019
|
+
parentCallId: call.parent?.callId ?? call.id,
|
|
2020
|
+
name: call.name,
|
|
2021
|
+
arguments: intent.arguments,
|
|
2022
|
+
status: "running",
|
|
2023
|
+
result: null,
|
|
2024
|
+
omittedFields: []
|
|
2025
|
+
});
|
|
2026
|
+
return {
|
|
2027
|
+
status: "running",
|
|
2028
|
+
checkpoint: {
|
|
2029
|
+
...intent,
|
|
2030
|
+
phase: "execute",
|
|
2031
|
+
...wake === undefined ? {} : { resume: { wake } }
|
|
2032
|
+
}
|
|
2033
|
+
};
|
|
2034
|
+
}, context);
|
|
2035
|
+
await run(runtime, call, tool, intent, agent, context, wake);
|
|
2036
|
+
}
|
|
1738
2037
|
async function reject(runtime, call, result, agent, tool, context) {
|
|
1739
2038
|
await eachHook(agent, "afterTool", runtime, async (handler) => {
|
|
1740
2039
|
result = await handler(call, result, runtime, context) ?? result;
|
|
1741
2040
|
});
|
|
1742
2041
|
await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
|
|
1743
2042
|
}
|
|
1744
|
-
async function run(runtime, call, tool,
|
|
2043
|
+
async function run(runtime, call, tool, intent, agent, context, wake) {
|
|
1745
2044
|
let invocation;
|
|
1746
2045
|
let result;
|
|
1747
2046
|
let ending = "completed";
|
|
1748
2047
|
try {
|
|
1749
|
-
|
|
1750
|
-
|
|
2048
|
+
const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
|
|
2049
|
+
invocation = createInvocation(runtime, tool, context, {
|
|
2050
|
+
wake,
|
|
2051
|
+
checkpoint: intent.checkpoint,
|
|
2052
|
+
...previous === undefined ? {} : { progress: previous.result }
|
|
2053
|
+
});
|
|
2054
|
+
const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
|
|
2055
|
+
if (returned.kind === undefined)
|
|
2056
|
+
result = returned;
|
|
2057
|
+
else {
|
|
2058
|
+
const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
|
|
2059
|
+
if (reason === undefined)
|
|
2060
|
+
return;
|
|
2061
|
+
result = executionError("invalid_park", reason);
|
|
2062
|
+
ending = "failed";
|
|
2063
|
+
}
|
|
1751
2064
|
} catch (error) {
|
|
1752
2065
|
if (runtime.signal.aborted) {
|
|
1753
2066
|
await invocation?.stop(error);
|
|
@@ -1799,7 +2112,7 @@ function finishResult(tool, name, result) {
|
|
|
1799
2112
|
} else if (final.structuredOutput === undefined) {
|
|
1800
2113
|
if (!final.isError)
|
|
1801
2114
|
throw new Error(`Tool ${name} returned no structuredOutput`);
|
|
1802
|
-
} else if (!
|
|
2115
|
+
} else if (!compile2(tool.structuredOutputSchema).check(final.structuredOutput)) {
|
|
1803
2116
|
throw new Error(`Tool ${name} returned structuredOutput that does not match its schema`);
|
|
1804
2117
|
}
|
|
1805
2118
|
} catch (error) {
|
|
@@ -1848,9 +2161,11 @@ function providerProjection(surfaceTools) {
|
|
|
1848
2161
|
const conversation = await host.conversation(api.conversationId, context);
|
|
1849
2162
|
if (conversation === undefined)
|
|
1850
2163
|
throw new Error(`Conversation ${api.conversationId} is unavailable`);
|
|
1851
|
-
for (const tool of (await conversation.agent(context)).tools)
|
|
1852
|
-
|
|
2164
|
+
for (const tool of (await conversation.agent(context)).tools) {
|
|
2165
|
+
const contract = readToolContract(tool);
|
|
2166
|
+
if (contract.nativeOnly || contract.nestedHidden)
|
|
1853
2167
|
visible.add(tool.name);
|
|
2168
|
+
}
|
|
1854
2169
|
}
|
|
1855
2170
|
return { messages: projectToolSchemas(request.messages, visible) };
|
|
1856
2171
|
}
|
|
@@ -1859,7 +2174,7 @@ function providerProjection(surfaceTools) {
|
|
|
1859
2174
|
}
|
|
1860
2175
|
|
|
1861
2176
|
// packages/execution/src/wait-session.ts
|
|
1862
|
-
import { withoutAbortSignal as
|
|
2177
|
+
import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
|
|
1863
2178
|
|
|
1864
2179
|
// packages/execution/src/tool-value.ts
|
|
1865
2180
|
class NestedToolError extends Error {
|
|
@@ -1930,7 +2245,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
|
|
|
1930
2245
|
}, context);
|
|
1931
2246
|
let cancelling;
|
|
1932
2247
|
const abort = () => {
|
|
1933
|
-
cancelling ??= cancelTask(id,
|
|
2248
|
+
cancelling ??= cancelTask(id, withoutAbortSignal4(context));
|
|
1934
2249
|
cancelling.catch(() => {});
|
|
1935
2250
|
};
|
|
1936
2251
|
context.abortSignal?.addEventListener("abort", abort, { once: true });
|
|
@@ -2014,7 +2329,7 @@ function createCellCoordinator(options) {
|
|
|
2014
2329
|
if (driver.closed)
|
|
2015
2330
|
throw new Error("Execution host is closed");
|
|
2016
2331
|
assertSingleExecutionMode(await api.agent(context));
|
|
2017
|
-
const copied =
|
|
2332
|
+
const copied = copyJson12(input);
|
|
2018
2333
|
return api.commit(async (tx) => {
|
|
2019
2334
|
const isolatedLimit = options.isolatedConcurrency ?? 0;
|
|
2020
2335
|
const isolated = isolatedLimit > 0 && input["isolated"] === true;
|
|
@@ -2094,7 +2409,7 @@ function createCellCoordinator(options) {
|
|
|
2094
2409
|
if (yielding.consume()) {
|
|
2095
2410
|
return initial;
|
|
2096
2411
|
}
|
|
2097
|
-
const wait =
|
|
2412
|
+
const wait = withCancel2(context);
|
|
2098
2413
|
const timeout = new Error("Cell observation yielded");
|
|
2099
2414
|
const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
|
|
2100
2415
|
try {
|
|
@@ -3292,7 +3607,7 @@ function notebookExecStartupNotice() {
|
|
|
3292
3607
|
|
|
3293
3608
|
// packages/notebook/src/engine.ts
|
|
3294
3609
|
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
3295
|
-
import { copyJson as
|
|
3610
|
+
import { copyJson as copyJson13 } from "@earendil-works/chord/json";
|
|
3296
3611
|
import {
|
|
3297
3612
|
defineDoc as defineDoc3
|
|
3298
3613
|
} from "@earendil-works/pi-durable";
|
|
@@ -5059,7 +5374,7 @@ class NotebookExecutionRuntime {
|
|
|
5059
5374
|
this.settlement.reportJournalFailure(error, "start", cell);
|
|
5060
5375
|
}
|
|
5061
5376
|
}
|
|
5062
|
-
const metadata = tools.map((tool) => ({
|
|
5377
|
+
const metadata = tools.filter((tool) => !tool.hidden).map((tool) => ({
|
|
5063
5378
|
name: tool.name,
|
|
5064
5379
|
description: tool.help ?? tool.usage + `
|
|
5065
5380
|
` + tool.description
|
|
@@ -5068,7 +5383,7 @@ class NotebookExecutionRuntime {
|
|
|
5068
5383
|
const outputHints = Object.fromEntries(tools.flatMap((tool) => ("textOutput" in tool) && tool.textOutput !== undefined ? [[tool.name, tool.textOutput]] : []));
|
|
5069
5384
|
const wrapped = [
|
|
5070
5385
|
`if (typeof globalThis.__piNotebook?.begin !== "function") throw new Error("Notebook runtime bootstrap unavailable: __piNotebook.begin");`,
|
|
5071
|
-
`await globalThis.__piNotebook.begin(${JSON.stringify(id)}, ${JSON.stringify(metadata)}, JSON.parse(${JSON.stringify(JSON.stringify(toolNames))}), JSON.parse(${JSON.stringify(JSON.stringify(outputHints))}));`,
|
|
5386
|
+
`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))});`,
|
|
5072
5387
|
code,
|
|
5073
5388
|
`if (typeof globalThis.__piNotebook?.flush !== "function") throw new Error("Notebook runtime bootstrap unavailable: __piNotebook.flush");`,
|
|
5074
5389
|
`await globalThis.__piNotebook.flush(${JSON.stringify(id)});`,
|
|
@@ -9061,8 +9376,10 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
|
|
|
9061
9376
|
};
|
|
9062
9377
|
},
|
|
9063
9378
|
});
|
|
9379
|
+
const __installToolNamespaces = ${installToolNamespacesSource};
|
|
9380
|
+
let __disposeToolNamespaces = __installToolNamespaces(__tools, []);
|
|
9064
9381
|
const __runtime = {
|
|
9065
|
-
async begin(cellId, tools, toolNames, toolOutputHints
|
|
9382
|
+
async begin(cellId, tools, toolNames, toolOutputHints, toolNamespaceDefinitions) {
|
|
9066
9383
|
if (__state.memoryTimer !== undefined) clearInterval(__state.memoryTimer);
|
|
9067
9384
|
__state.cellId = cellId;
|
|
9068
9385
|
__state.toolNames = toolNames;
|
|
@@ -9075,6 +9392,8 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
|
|
|
9075
9392
|
__state.outputTruncated = false;
|
|
9076
9393
|
globalThis.tools = __tools;
|
|
9077
9394
|
globalThis.ALL_TOOLS = tools;
|
|
9395
|
+
__disposeToolNamespaces();
|
|
9396
|
+
__disposeToolNamespaces = __installToolNamespaces(__tools, toolNamespaceDefinitions);
|
|
9078
9397
|
__state.cellGlobals = new Set(Object.getOwnPropertyNames(globalThis));
|
|
9079
9398
|
await __reportMemory(cellId);
|
|
9080
9399
|
__state.memoryTimer = setInterval(() => void __reportMemory(cellId).catch(() => undefined), 1000);
|
|
@@ -9102,6 +9421,7 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
|
|
|
9102
9421
|
if (__state.memoryTimer !== undefined) clearInterval(__state.memoryTimer);
|
|
9103
9422
|
__state.memoryTimer = undefined;
|
|
9104
9423
|
__state.cellId = null;
|
|
9424
|
+
__disposeToolNamespaces();
|
|
9105
9425
|
},
|
|
9106
9426
|
projectBindings() {
|
|
9107
9427
|
return [...__state.projectBindings].sort();
|
|
@@ -10496,6 +10816,7 @@ var HOST_BINDINGS = new Set([
|
|
|
10496
10816
|
"notify",
|
|
10497
10817
|
"store",
|
|
10498
10818
|
"text",
|
|
10819
|
+
"toolNamespaces",
|
|
10499
10820
|
"tools",
|
|
10500
10821
|
"yield_control"
|
|
10501
10822
|
]);
|
|
@@ -10922,13 +11243,15 @@ function createNotebookEngine(options) {
|
|
|
10922
11243
|
const contract = readToolContract(registration);
|
|
10923
11244
|
return {
|
|
10924
11245
|
name: registration.name,
|
|
11246
|
+
hidden: contract.nestedHidden || contract.jsNamespace !== undefined,
|
|
11247
|
+
...contract.nestedHidden || contract.jsNamespace === undefined ? {} : { jsNamespace: contract.jsNamespace },
|
|
10925
11248
|
description: contract.description,
|
|
10926
11249
|
usage: contract.usage,
|
|
10927
11250
|
help: contract.help,
|
|
10928
11251
|
...registration.name === "exec_command" || registration.name === "write_stdin" ? { textOutput: "plain-command" } : {},
|
|
10929
11252
|
async invoke(input, _context, signal) {
|
|
10930
11253
|
signal.throwIfAborted();
|
|
10931
|
-
const args =
|
|
11254
|
+
const args = copyJson13(input === undefined ? null : input, {
|
|
10932
11255
|
omitUndefinedProperties: true
|
|
10933
11256
|
});
|
|
10934
11257
|
const invoke = api.tools[registration.name];
|
|
@@ -11081,7 +11404,7 @@ function parseNotebookRequest(input) {
|
|
|
11081
11404
|
}
|
|
11082
11405
|
|
|
11083
11406
|
// packages/notebook/src/tool-observation.ts
|
|
11084
|
-
import { copyJson as
|
|
11407
|
+
import { copyJson as copyJson14 } from "@earendil-works/chord/json";
|
|
11085
11408
|
import {
|
|
11086
11409
|
defineDocFamily as defineDocFamily2
|
|
11087
11410
|
} from "@earendil-works/pi-durable";
|
|
@@ -11136,7 +11459,7 @@ async function observeNotebookCell(observation, maxTokens, api, context) {
|
|
|
11136
11459
|
cell_id: String(observation.cellId),
|
|
11137
11460
|
status: observation.status,
|
|
11138
11461
|
...observation.forwardedToolCalls === undefined ? {} : {
|
|
11139
|
-
forwardedToolCalls:
|
|
11462
|
+
forwardedToolCalls: copyJson14(observation.forwardedToolCalls, {
|
|
11140
11463
|
omitUndefinedProperties: true
|
|
11141
11464
|
})
|
|
11142
11465
|
},
|
|
@@ -11650,15 +11973,15 @@ function createNotebookMode(options) {
|
|
|
11650
11973
|
};
|
|
11651
11974
|
return {
|
|
11652
11975
|
output: [{ type: "text", text: result.message }],
|
|
11653
|
-
details:
|
|
11654
|
-
structuredOutput:
|
|
11976
|
+
details: copyJson15(result.details),
|
|
11977
|
+
structuredOutput: copyJson15(result)
|
|
11655
11978
|
};
|
|
11656
11979
|
}
|
|
11657
11980
|
const result = await engine.control(request, api, context);
|
|
11658
11981
|
return {
|
|
11659
11982
|
output: [{ type: "text", text: result.message }],
|
|
11660
|
-
details:
|
|
11661
|
-
structuredOutput:
|
|
11983
|
+
details: copyJson15(result.details, { omitUndefinedProperties: true }),
|
|
11984
|
+
structuredOutput: copyJson15(result, { omitUndefinedProperties: true })
|
|
11662
11985
|
};
|
|
11663
11986
|
}
|
|
11664
11987
|
});
|
|
@@ -11671,7 +11994,7 @@ function createNotebookMode(options) {
|
|
|
11671
11994
|
...notebook,
|
|
11672
11995
|
executionHints: {
|
|
11673
11996
|
discovery: "help",
|
|
11674
|
-
inputSchema:
|
|
11997
|
+
inputSchema: copyJson15(JSON.parse(JSON.stringify(Type4.Union([NOTEBOOK_PARAMETERS, NOTEBOOK_ACTION_PARAMETERS]))))
|
|
11675
11998
|
}
|
|
11676
11999
|
},
|
|
11677
12000
|
...shell.tools
|
|
@@ -11679,12 +12002,8 @@ function createNotebookMode(options) {
|
|
|
11679
12002
|
sections: [
|
|
11680
12003
|
section("notebook", (input) => {
|
|
11681
12004
|
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.';
|
|
11682
|
-
const promoted = input.agent.callable.filter((tool) => !["exec", "wait", "notebook"].includes(tool.name)).map(readToolContract).
|
|
11683
|
-
return [
|
|
11684
|
-
base,
|
|
11685
|
-
"For tools listed without a call signature, call with no arguments to get usage without performing an operation. Structured calls use {}.",
|
|
11686
|
-
...promoted
|
|
11687
|
-
].join(`
|
|
12005
|
+
const promoted = input.agent.callable.filter((tool) => !["exec", "wait", "notebook"].includes(tool.name)).map(readToolContract).flatMap(jsToolPrompt);
|
|
12006
|
+
return [base, nestedToolDiscoveryGuidance, ...promoted].join(`
|
|
11688
12007
|
`);
|
|
11689
12008
|
})
|
|
11690
12009
|
]
|