@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/activation.js
CHANGED
|
@@ -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
|
|
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 {
|
|
86
|
-
import {
|
|
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";
|
|
@@ -608,8 +608,14 @@ async function observeCellProgress(id, api, context, budget) {
|
|
|
608
608
|
return work;
|
|
609
609
|
};
|
|
610
610
|
const live = await api.watchDoc(LiveDoc2, api.conversationId, context);
|
|
611
|
-
cell.start((
|
|
612
|
-
|
|
611
|
+
cell.start((call) => own(async () => {
|
|
612
|
+
if (call.kind === "failed")
|
|
613
|
+
throw call.error;
|
|
614
|
+
await publish(call.value);
|
|
615
|
+
}));
|
|
616
|
+
live?.start((call) => own(async () => {
|
|
617
|
+
if (call.kind === "failed")
|
|
618
|
+
throw call.error;
|
|
613
619
|
await api.commit(async (tx) => {
|
|
614
620
|
const record = await tx.task(id);
|
|
615
621
|
if (record === undefined || record.state.status === "terminal")
|
|
@@ -629,43 +635,70 @@ async function observeCellProgress(id, api, context, budget) {
|
|
|
629
635
|
const endings = await Promise.all([cell.stop(), live?.stop()]);
|
|
630
636
|
await Promise.all([...pending]);
|
|
631
637
|
for (const ending of endings)
|
|
632
|
-
if (ending?.
|
|
638
|
+
if (ending?.kind === "listener_error" || ending?.kind === "failed")
|
|
633
639
|
throw ending.error;
|
|
634
640
|
};
|
|
635
641
|
}
|
|
636
642
|
|
|
637
643
|
// packages/execution/src/cell-task.ts
|
|
638
|
-
import { copyJson as copyJson8 } from "@earendil-works/chord";
|
|
639
644
|
import { withAbortSignal } from "@earendil-works/chord/context";
|
|
645
|
+
import { copyJson as copyJson8 } from "@earendil-works/chord/json";
|
|
640
646
|
import {
|
|
641
647
|
defineTask
|
|
642
648
|
} from "@earendil-works/pi-durable";
|
|
643
649
|
|
|
644
650
|
// packages/execution/src/cell-tools.ts
|
|
645
|
-
import { copyJson as copyJson6 } from "@earendil-works/chord";
|
|
646
651
|
import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
|
|
652
|
+
import { copyJson as copyJson6 } from "@earendil-works/chord/json";
|
|
647
653
|
|
|
648
654
|
// packages/execution/src/invocation.ts
|
|
649
|
-
import { copyJson as copyJson5 } from "@earendil-works/chord";
|
|
650
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";
|
|
651
661
|
|
|
652
662
|
// packages/execution/src/native-tools.ts
|
|
653
|
-
import {
|
|
654
|
-
|
|
663
|
+
import {
|
|
664
|
+
withoutAbortSignal
|
|
665
|
+
} from "@earendil-works/chord/context";
|
|
666
|
+
import { copyJson as copyJson4 } from "@earendil-works/chord/json";
|
|
655
667
|
import {
|
|
656
668
|
LiveDoc as LiveDoc3,
|
|
657
669
|
NestedCallDoc as NestedCallDoc2,
|
|
658
|
-
ToolTask as
|
|
670
|
+
ToolTask as ToolTask3
|
|
659
671
|
} from "@earendil-works/pi-durable";
|
|
660
672
|
import { Equal } from "typebox/value";
|
|
661
|
-
|
|
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) {
|
|
662
693
|
let sequence = 0;
|
|
663
694
|
const admissions = [];
|
|
664
|
-
|
|
695
|
+
async function execute(name, args, callContext, options = {}) {
|
|
665
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");
|
|
666
701
|
const key = options.key ?? String(++sequence);
|
|
667
|
-
if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
|
|
668
|
-
throw new Error("Invalid nested call key");
|
|
669
702
|
const call = {
|
|
670
703
|
type: "toolCall",
|
|
671
704
|
id: `${callId}/${key}`,
|
|
@@ -677,11 +710,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
677
710
|
const admission = runtime.commit(async (tx) => {
|
|
678
711
|
const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
|
|
679
712
|
if (slot.taskId !== undefined) {
|
|
680
|
-
const input = (await tx.task(slot.taskId))?.input;
|
|
713
|
+
const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
|
|
681
714
|
if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
|
|
682
715
|
throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
|
|
683
716
|
} else {
|
|
684
|
-
slot.
|
|
717
|
+
slot.kind = "nested";
|
|
718
|
+
slot.taskId = await tx.createTask(ToolTask3, {
|
|
685
719
|
kind: "nested",
|
|
686
720
|
parent: runtime.taskId,
|
|
687
721
|
parentCallId: callId,
|
|
@@ -693,6 +727,9 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
693
727
|
abandonOnRestart: replay !== "safe"
|
|
694
728
|
});
|
|
695
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 };
|
|
696
733
|
live.nestedTools ??= [];
|
|
697
734
|
live.nestedTools.push({
|
|
698
735
|
callId: call.id,
|
|
@@ -724,7 +761,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
724
761
|
const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
|
|
725
762
|
if (slot?.taskId === undefined)
|
|
726
763
|
throw new Error("Nested task creation did not commit");
|
|
727
|
-
const
|
|
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);
|
|
728
771
|
const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
|
|
729
772
|
await runtime.commit(async (tx) => {
|
|
730
773
|
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
@@ -732,7 +775,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
732
775
|
return;
|
|
733
776
|
}, callContext);
|
|
734
777
|
return result === undefined ? {
|
|
735
|
-
taskId
|
|
778
|
+
taskId,
|
|
736
779
|
isError: true,
|
|
737
780
|
diagnostics: [
|
|
738
781
|
{
|
|
@@ -742,9 +785,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
742
785
|
}
|
|
743
786
|
]
|
|
744
787
|
} : copyJson4(result);
|
|
745
|
-
}
|
|
788
|
+
}
|
|
746
789
|
return {
|
|
747
790
|
execute,
|
|
791
|
+
async drain() {
|
|
792
|
+
await Promise.allSettled(admissions);
|
|
793
|
+
},
|
|
748
794
|
async finish() {
|
|
749
795
|
await Promise.allSettled(admissions);
|
|
750
796
|
await cleanupNativeCalls(runtime, withoutAbortSignal(context));
|
|
@@ -752,7 +798,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
752
798
|
};
|
|
753
799
|
}
|
|
754
800
|
async function cleanupNativeCalls(runtime, context) {
|
|
755
|
-
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind ===
|
|
801
|
+
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
|
|
756
802
|
await runtime.commit(async (tx) => {
|
|
757
803
|
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
758
804
|
await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
|
|
@@ -846,18 +892,6 @@ class Progress {
|
|
|
846
892
|
}
|
|
847
893
|
}
|
|
848
894
|
|
|
849
|
-
// packages/execution/src/tool-origin.ts
|
|
850
|
-
import {
|
|
851
|
-
defineDoc as defineDoc2
|
|
852
|
-
} from "@earendil-works/pi-durable";
|
|
853
|
-
var ToolOriginDoc = defineDoc2({
|
|
854
|
-
kind: "howaboua.tool-origin",
|
|
855
|
-
version: 1,
|
|
856
|
-
scope: "task",
|
|
857
|
-
checkpointWhen: () => false,
|
|
858
|
-
initial: () => ({})
|
|
859
|
-
});
|
|
860
|
-
|
|
861
895
|
// packages/execution/src/invocation.ts
|
|
862
896
|
function executionError(code, message) {
|
|
863
897
|
return {
|
|
@@ -869,21 +903,23 @@ function executionError(code, message) {
|
|
|
869
903
|
function errorText(error) {
|
|
870
904
|
return error instanceof Error ? error.message : String(error);
|
|
871
905
|
}
|
|
872
|
-
function createInvocation(runtime, tool, context) {
|
|
906
|
+
function createInvocation(runtime, tool, context, resume) {
|
|
873
907
|
const limits = {
|
|
874
908
|
maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
|
|
875
909
|
maxLines: tool.outputLimits?.maxLines ?? 2000,
|
|
876
910
|
retain: tool.outputLimits?.retain ?? "head"
|
|
877
911
|
};
|
|
878
912
|
const output = new OutputBuffer(limits);
|
|
879
|
-
const diagnostics = [
|
|
880
|
-
|
|
913
|
+
const diagnostics = [
|
|
914
|
+
...resume?.progress?.diagnostics ?? []
|
|
915
|
+
];
|
|
916
|
+
let details = resume?.progress?.details;
|
|
881
917
|
let ended = false;
|
|
882
918
|
const assertLive = () => {
|
|
883
919
|
if (ended)
|
|
884
920
|
throw new Error(`Invocation ${runtime.taskId} has settled`);
|
|
885
921
|
};
|
|
886
|
-
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);
|
|
887
923
|
const snapshot = () => {
|
|
888
924
|
const retained = output.snapshot();
|
|
889
925
|
return {
|
|
@@ -912,6 +948,8 @@ function createInvocation(runtime, tool, context) {
|
|
|
912
948
|
taskId: runtime.taskId,
|
|
913
949
|
conversationId: runtime.conversationId,
|
|
914
950
|
callId: `nested-${runtime.taskId}`,
|
|
951
|
+
wake: resume?.wake,
|
|
952
|
+
checkpoint: resume?.checkpoint,
|
|
915
953
|
registry: runtime.registry,
|
|
916
954
|
agent: runtime.agent,
|
|
917
955
|
env: undefined,
|
|
@@ -932,7 +970,7 @@ function createInvocation(runtime, tool, context) {
|
|
|
932
970
|
const retained = output.snapshot();
|
|
933
971
|
return { text: retained.text, truncated: retained.droppedBytes > 0 };
|
|
934
972
|
},
|
|
935
|
-
executeTool:
|
|
973
|
+
executeTool: native.execute,
|
|
936
974
|
diagnostic: (value) => {
|
|
937
975
|
assertLive();
|
|
938
976
|
diagnostics.push(copyJson5(value, { omitUndefinedProperties: true }));
|
|
@@ -946,24 +984,44 @@ function createInvocation(runtime, tool, context) {
|
|
|
946
984
|
committed.catch(() => {});
|
|
947
985
|
await awaitWithContext(committed, detailContext);
|
|
948
986
|
},
|
|
949
|
-
commit: async (change, commitContext) => {
|
|
987
|
+
commit: async (change, commitContext, options) => {
|
|
950
988
|
assertLive();
|
|
951
989
|
let result;
|
|
952
990
|
await runtime.commit(async (tx) => {
|
|
953
991
|
result = await change(tx);
|
|
954
992
|
return;
|
|
955
|
-
}, commitContext);
|
|
993
|
+
}, commitContext, options);
|
|
956
994
|
return result;
|
|
957
995
|
},
|
|
958
996
|
memo: runtime.memo,
|
|
959
|
-
|
|
997
|
+
readSignal: runtime.readSignal,
|
|
998
|
+
async createTask(task, input, {
|
|
999
|
+
key,
|
|
1000
|
+
...options
|
|
1001
|
+
}, taskContext) {
|
|
960
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");
|
|
961
1007
|
let id;
|
|
962
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
|
+
}
|
|
963
1017
|
id = await tx.createTask(task, input, {
|
|
964
1018
|
...options,
|
|
965
1019
|
...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
|
|
966
1020
|
});
|
|
1021
|
+
if (member !== undefined) {
|
|
1022
|
+
member.kind = "task";
|
|
1023
|
+
member.taskId = id;
|
|
1024
|
+
}
|
|
967
1025
|
const source = await tx.doc(ToolOriginDoc, runtime.taskId);
|
|
968
1026
|
if (source.origin !== undefined)
|
|
969
1027
|
(await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
|
|
@@ -1010,6 +1068,14 @@ function createInvocation(runtime, tool, context) {
|
|
|
1010
1068
|
for (const waiter of await progress.stop())
|
|
1011
1069
|
waiter.reject(error);
|
|
1012
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
|
+
},
|
|
1013
1079
|
limits,
|
|
1014
1080
|
output,
|
|
1015
1081
|
progress
|
|
@@ -1111,7 +1177,74 @@ function combineControls(controls, allowTermination = true) {
|
|
|
1111
1177
|
}
|
|
1112
1178
|
|
|
1113
1179
|
// packages/execution/src/tool-contract.ts
|
|
1114
|
-
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
|
|
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 {}";
|
|
1115
1248
|
function readToolContract(tool) {
|
|
1116
1249
|
const candidate = "executionHints" in tool ? tool.executionHints : undefined;
|
|
1117
1250
|
if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
|
|
@@ -1125,6 +1258,7 @@ function readToolContract(tool) {
|
|
|
1125
1258
|
"yieldTimeMs",
|
|
1126
1259
|
"inputSchema",
|
|
1127
1260
|
"nativeOnly",
|
|
1261
|
+
"nestedHidden",
|
|
1128
1262
|
"discovery"
|
|
1129
1263
|
]);
|
|
1130
1264
|
for (const key of Object.keys(hints))
|
|
@@ -1148,6 +1282,12 @@ function readToolContract(tool) {
|
|
|
1148
1282
|
const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
|
|
1149
1283
|
if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
|
|
1150
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`);
|
|
1151
1291
|
const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
|
|
1152
1292
|
if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
|
|
1153
1293
|
throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
|
|
@@ -1164,6 +1304,8 @@ function readToolContract(tool) {
|
|
|
1164
1304
|
inputSchema,
|
|
1165
1305
|
deferLoading: typeof deferred === "boolean" ? deferred : true,
|
|
1166
1306
|
nativeOnly: nativeOnly === true,
|
|
1307
|
+
nestedHidden: nestedHidden === true,
|
|
1308
|
+
...jsNamespace === undefined ? {} : { jsNamespace },
|
|
1167
1309
|
...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
|
|
1168
1310
|
...outputHint === undefined ? {} : { output: outputHint },
|
|
1169
1311
|
help: [
|
|
@@ -1399,7 +1541,7 @@ function createCellTask(options, nestedTask) {
|
|
|
1399
1541
|
import {
|
|
1400
1542
|
hook,
|
|
1401
1543
|
LiveDoc as LiveDoc4,
|
|
1402
|
-
ToolTask as
|
|
1544
|
+
ToolTask as ToolTask4
|
|
1403
1545
|
} from "@earendil-works/pi-durable";
|
|
1404
1546
|
function forwardingHook() {
|
|
1405
1547
|
let host;
|
|
@@ -1409,7 +1551,7 @@ function forwardingHook() {
|
|
|
1409
1551
|
throw new Error("Create a separate execution component for each Harness");
|
|
1410
1552
|
host = harness;
|
|
1411
1553
|
},
|
|
1412
|
-
hook: hook(
|
|
1554
|
+
hook: hook(ToolTask4, {
|
|
1413
1555
|
async beforeTool(call, api, context) {
|
|
1414
1556
|
const parent = call.parent;
|
|
1415
1557
|
if (parent === undefined || host === undefined)
|
|
@@ -1422,7 +1564,7 @@ function forwardingHook() {
|
|
|
1422
1564
|
if (conversation === undefined)
|
|
1423
1565
|
throw new Error("Forwarded call conversation is unavailable");
|
|
1424
1566
|
await conversation.commit(async (tx) => {
|
|
1425
|
-
if ((await tx.task(api.taskId))?.kind !==
|
|
1567
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
|
|
1426
1568
|
return;
|
|
1427
1569
|
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1428
1570
|
const admission = owner.forwardingCellId === undefined;
|
|
@@ -1449,7 +1591,7 @@ function forwardingHook() {
|
|
|
1449
1591
|
if (conversation === undefined)
|
|
1450
1592
|
throw new Error("Forwarded call conversation is unavailable");
|
|
1451
1593
|
await conversation.commit(async (tx) => {
|
|
1452
|
-
if ((await tx.task(api.taskId))?.kind !==
|
|
1594
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
|
|
1453
1595
|
return;
|
|
1454
1596
|
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1455
1597
|
const cellId = owner.forwardingCellId;
|
|
@@ -1474,17 +1616,18 @@ function forwardingHook() {
|
|
|
1474
1616
|
}
|
|
1475
1617
|
|
|
1476
1618
|
// packages/execution/src/nested.ts
|
|
1619
|
+
import { copyJson as copyJson11 } from "@earendil-works/chord/json";
|
|
1477
1620
|
import {
|
|
1478
1621
|
defineTask as defineTask2
|
|
1479
1622
|
} from "@earendil-works/pi-durable";
|
|
1480
|
-
import {
|
|
1623
|
+
import { compile as compile2 } from "@earendil-works/pi-schema";
|
|
1481
1624
|
|
|
1482
1625
|
// packages/execution/src/nested-call.ts
|
|
1483
1626
|
import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
|
|
1484
1627
|
import {
|
|
1485
|
-
ToolTask as
|
|
1628
|
+
ToolTask as ToolTask5
|
|
1486
1629
|
} from "@earendil-works/pi-durable";
|
|
1487
|
-
import {
|
|
1630
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
1488
1631
|
function nestedCall(runtime, input) {
|
|
1489
1632
|
const args = input.arguments;
|
|
1490
1633
|
return {
|
|
@@ -1505,7 +1648,7 @@ function prepareNestedInput(tool, input) {
|
|
|
1505
1648
|
if (typeof input !== "string")
|
|
1506
1649
|
return input;
|
|
1507
1650
|
const contract = readToolContract(tool);
|
|
1508
|
-
if (Boolean(
|
|
1651
|
+
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)))
|
|
1509
1652
|
return input;
|
|
1510
1653
|
const text = input.trim();
|
|
1511
1654
|
if (contract.discovery === "help" && text === "help")
|
|
@@ -1528,7 +1671,7 @@ function prepareNestedInput(tool, input) {
|
|
|
1528
1671
|
async function eachHook(agent, name, api, invoke) {
|
|
1529
1672
|
for (const extension of agent.extensions)
|
|
1530
1673
|
for (const registration of extension.hooks ?? []) {
|
|
1531
|
-
if (registration.task !==
|
|
1674
|
+
if (registration.task !== ToolTask5.definition.name)
|
|
1532
1675
|
continue;
|
|
1533
1676
|
const handler = registration.handlers[name];
|
|
1534
1677
|
if (handler === undefined)
|
|
@@ -1543,8 +1686,120 @@ async function eachHook(agent, name, api, invoke) {
|
|
|
1543
1686
|
}
|
|
1544
1687
|
}
|
|
1545
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
|
+
|
|
1546
1801
|
// packages/execution/src/nested-result.ts
|
|
1547
|
-
import { copyJson as
|
|
1802
|
+
import { copyJson as copyJson10 } from "@earendil-works/chord/json";
|
|
1548
1803
|
import {
|
|
1549
1804
|
defineEntry,
|
|
1550
1805
|
UsageDoc
|
|
@@ -1592,11 +1847,11 @@ async function settle(runtime, call, result, ending, context) {
|
|
|
1592
1847
|
taskId: runtime.taskId,
|
|
1593
1848
|
callId: call.id,
|
|
1594
1849
|
name: call.name,
|
|
1595
|
-
arguments:
|
|
1850
|
+
arguments: copyJson10(call.arguments),
|
|
1596
1851
|
result: stored,
|
|
1597
1852
|
...current.state.checkpoint.phase === "execute" ? {
|
|
1598
1853
|
intent: {
|
|
1599
|
-
arguments:
|
|
1854
|
+
arguments: copyJson10(current.state.checkpoint.arguments),
|
|
1600
1855
|
replay: current.state.checkpoint.replay
|
|
1601
1856
|
}
|
|
1602
1857
|
} : {}
|
|
@@ -1605,7 +1860,7 @@ async function settle(runtime, call, result, ending, context) {
|
|
|
1605
1860
|
if (result.usage !== undefined) {
|
|
1606
1861
|
const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
|
|
1607
1862
|
const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
|
|
1608
|
-
totals[call.name] =
|
|
1863
|
+
totals[call.name] = copyJson10(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
|
|
1609
1864
|
}
|
|
1610
1865
|
const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
|
|
1611
1866
|
status: ending,
|
|
@@ -1642,7 +1897,11 @@ function sumUsage(previous, added) {
|
|
|
1642
1897
|
function createNestedToolTask(name) {
|
|
1643
1898
|
return defineTask2({
|
|
1644
1899
|
name,
|
|
1645
|
-
version:
|
|
1900
|
+
version: 2,
|
|
1901
|
+
migrate: (input, checkpoint) => ({
|
|
1902
|
+
input,
|
|
1903
|
+
checkpoint
|
|
1904
|
+
}),
|
|
1646
1905
|
initial: () => ({ phase: "call" }),
|
|
1647
1906
|
phases: {
|
|
1648
1907
|
call: async (task, runtime, context) => {
|
|
@@ -1668,22 +1927,25 @@ function createNestedToolTask(name) {
|
|
|
1668
1927
|
return reject(runtime, call, executionError("tool_unavailable", `Tool ${call.name} is not available`), agent, tool, context);
|
|
1669
1928
|
let args;
|
|
1670
1929
|
try {
|
|
1671
|
-
const supplied = task.input.arguments === null && !
|
|
1930
|
+
const supplied = task.input.arguments === null && !compile2(tool.parameters).check(null) && compile2(tool.parameters).check({}) ? undefined : task.input.arguments;
|
|
1672
1931
|
const prepared = tool.prepareArguments === undefined ? prepareNestedInput(tool, supplied) : tool.prepareArguments(prepareNestedInput(tool, supplied));
|
|
1673
|
-
args = checked(tool, call, prepared === undefined &&
|
|
1932
|
+
args = checked(tool, call, prepared === undefined && compile2(tool.parameters).check({}) ? {} : prepared);
|
|
1674
1933
|
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1675
1934
|
call.arguments = args;
|
|
1676
1935
|
} catch (error) {
|
|
1677
1936
|
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1678
1937
|
}
|
|
1679
1938
|
let block;
|
|
1939
|
+
let sleep;
|
|
1680
1940
|
await eachHook(agent, "beforeTool", runtime, async (handler) => {
|
|
1681
|
-
if (block !== undefined)
|
|
1941
|
+
if (block !== undefined || sleep !== undefined)
|
|
1682
1942
|
return;
|
|
1683
1943
|
try {
|
|
1684
1944
|
const decision = await handler({ ...call, arguments: args }, runtime, context);
|
|
1685
1945
|
if (decision?.block !== undefined)
|
|
1686
1946
|
block = decision.block;
|
|
1947
|
+
else if (decision?.sleep !== undefined)
|
|
1948
|
+
sleep = decision.sleep;
|
|
1687
1949
|
else if (decision?.arguments !== undefined)
|
|
1688
1950
|
args = decision.arguments;
|
|
1689
1951
|
} catch (error) {
|
|
@@ -1694,71 +1956,122 @@ function createNestedToolTask(name) {
|
|
|
1694
1956
|
});
|
|
1695
1957
|
if (block !== undefined)
|
|
1696
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
|
+
}
|
|
1697
1965
|
try {
|
|
1698
|
-
args = checked(tool, call, args)
|
|
1966
|
+
args = copyJson11(checked(tool, call, args), {
|
|
1967
|
+
omitUndefinedProperties: true
|
|
1968
|
+
});
|
|
1699
1969
|
} catch (error) {
|
|
1700
1970
|
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1701
1971
|
}
|
|
1702
|
-
await runtime
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
callId: call.id,
|
|
1706
|
-
parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
|
|
1707
|
-
name: call.name,
|
|
1708
|
-
arguments: args,
|
|
1709
|
-
status: "running",
|
|
1710
|
-
result: null,
|
|
1711
|
-
omittedFields: []
|
|
1712
|
-
});
|
|
1713
|
-
return {
|
|
1714
|
-
status: "running",
|
|
1715
|
-
checkpoint: {
|
|
1716
|
-
phase: "execute",
|
|
1717
|
-
arguments: args,
|
|
1718
|
-
replay: tool.replay ?? "unsafe"
|
|
1719
|
-
}
|
|
1720
|
-
};
|
|
1972
|
+
await startAttempt(runtime, call, tool, agent, {
|
|
1973
|
+
arguments: args,
|
|
1974
|
+
replay: tool.replay ?? "unsafe"
|
|
1721
1975
|
}, context);
|
|
1722
|
-
|
|
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);
|
|
1723
1989
|
},
|
|
1724
1990
|
execute: async (task, runtime, context) => {
|
|
1991
|
+
const intent = task.state.checkpoint;
|
|
1725
1992
|
const call = nestedCall(runtime, task.input);
|
|
1726
1993
|
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1727
1994
|
call.arguments = task.state.checkpoint.arguments;
|
|
1728
1995
|
const agent = await runtime.agent(context);
|
|
1729
1996
|
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1730
|
-
if (
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
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);
|
|
1739
2007
|
}
|
|
2008
|
+
if (intent.resume !== undefined)
|
|
2009
|
+
await cancelParkedTool(runtime, tool, intent, context);
|
|
1740
2010
|
await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
|
|
1741
2011
|
}
|
|
1742
2012
|
},
|
|
1743
2013
|
abort: async (task, runtime, context) => {
|
|
1744
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
|
+
}
|
|
1745
2021
|
await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
|
|
1746
2022
|
}
|
|
1747
2023
|
});
|
|
1748
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
|
+
}
|
|
1749
2048
|
async function reject(runtime, call, result, agent, tool, context) {
|
|
1750
2049
|
await eachHook(agent, "afterTool", runtime, async (handler) => {
|
|
1751
2050
|
result = await handler(call, result, runtime, context) ?? result;
|
|
1752
2051
|
});
|
|
1753
2052
|
await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
|
|
1754
2053
|
}
|
|
1755
|
-
async function run(runtime, call, tool,
|
|
2054
|
+
async function run(runtime, call, tool, intent, agent, context, wake) {
|
|
1756
2055
|
let invocation;
|
|
1757
2056
|
let result;
|
|
1758
2057
|
let ending = "completed";
|
|
1759
2058
|
try {
|
|
1760
|
-
|
|
1761
|
-
|
|
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
|
+
}
|
|
1762
2075
|
} catch (error) {
|
|
1763
2076
|
if (runtime.signal.aborted) {
|
|
1764
2077
|
await invocation?.stop(error);
|
|
@@ -1810,7 +2123,7 @@ function finishResult(tool, name, result) {
|
|
|
1810
2123
|
} else if (final.structuredOutput === undefined) {
|
|
1811
2124
|
if (!final.isError)
|
|
1812
2125
|
throw new Error(`Tool ${name} returned no structuredOutput`);
|
|
1813
|
-
} else if (!
|
|
2126
|
+
} else if (!compile2(tool.structuredOutputSchema).check(final.structuredOutput)) {
|
|
1814
2127
|
throw new Error(`Tool ${name} returned structuredOutput that does not match its schema`);
|
|
1815
2128
|
}
|
|
1816
2129
|
} catch (error) {
|
|
@@ -1859,9 +2172,11 @@ function providerProjection(surfaceTools) {
|
|
|
1859
2172
|
const conversation = await host.conversation(api.conversationId, context);
|
|
1860
2173
|
if (conversation === undefined)
|
|
1861
2174
|
throw new Error(`Conversation ${api.conversationId} is unavailable`);
|
|
1862
|
-
for (const tool of (await conversation.agent(context)).tools)
|
|
1863
|
-
|
|
2175
|
+
for (const tool of (await conversation.agent(context)).tools) {
|
|
2176
|
+
const contract = readToolContract(tool);
|
|
2177
|
+
if (contract.nativeOnly || contract.nestedHidden)
|
|
1864
2178
|
visible.add(tool.name);
|
|
2179
|
+
}
|
|
1865
2180
|
}
|
|
1866
2181
|
return { messages: projectToolSchemas(request.messages, visible) };
|
|
1867
2182
|
}
|
|
@@ -1870,7 +2185,7 @@ function providerProjection(surfaceTools) {
|
|
|
1870
2185
|
}
|
|
1871
2186
|
|
|
1872
2187
|
// packages/execution/src/wait-session.ts
|
|
1873
|
-
import { withoutAbortSignal as
|
|
2188
|
+
import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
|
|
1874
2189
|
|
|
1875
2190
|
// packages/execution/src/tool-value.ts
|
|
1876
2191
|
class NestedToolError extends Error {
|
|
@@ -1941,7 +2256,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
|
|
|
1941
2256
|
}, context);
|
|
1942
2257
|
let cancelling;
|
|
1943
2258
|
const abort = () => {
|
|
1944
|
-
cancelling ??= cancelTask(id,
|
|
2259
|
+
cancelling ??= cancelTask(id, withoutAbortSignal4(context));
|
|
1945
2260
|
cancelling.catch(() => {});
|
|
1946
2261
|
};
|
|
1947
2262
|
context.abortSignal?.addEventListener("abort", abort, { once: true });
|
|
@@ -2025,7 +2340,7 @@ function createCellCoordinator(options) {
|
|
|
2025
2340
|
if (driver.closed)
|
|
2026
2341
|
throw new Error("Execution host is closed");
|
|
2027
2342
|
assertSingleExecutionMode(await api.agent(context));
|
|
2028
|
-
const copied =
|
|
2343
|
+
const copied = copyJson12(input);
|
|
2029
2344
|
return api.commit(async (tx) => {
|
|
2030
2345
|
const isolatedLimit = options.isolatedConcurrency ?? 0;
|
|
2031
2346
|
const isolated = isolatedLimit > 0 && input["isolated"] === true;
|
|
@@ -2105,7 +2420,7 @@ function createCellCoordinator(options) {
|
|
|
2105
2420
|
if (yielding.consume()) {
|
|
2106
2421
|
return initial;
|
|
2107
2422
|
}
|
|
2108
|
-
const wait =
|
|
2423
|
+
const wait = withCancel2(context);
|
|
2109
2424
|
const timeout = new Error("Cell observation yielded");
|
|
2110
2425
|
const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
|
|
2111
2426
|
try {
|
|
@@ -3303,7 +3618,7 @@ function notebookExecStartupNotice() {
|
|
|
3303
3618
|
|
|
3304
3619
|
// packages/notebook/src/engine.ts
|
|
3305
3620
|
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
3306
|
-
import { copyJson as
|
|
3621
|
+
import { copyJson as copyJson13 } from "@earendil-works/chord/json";
|
|
3307
3622
|
import {
|
|
3308
3623
|
defineDoc as defineDoc3
|
|
3309
3624
|
} from "@earendil-works/pi-durable";
|
|
@@ -5070,7 +5385,7 @@ class NotebookExecutionRuntime {
|
|
|
5070
5385
|
this.settlement.reportJournalFailure(error, "start", cell);
|
|
5071
5386
|
}
|
|
5072
5387
|
}
|
|
5073
|
-
const metadata = tools.map((tool) => ({
|
|
5388
|
+
const metadata = tools.filter((tool) => !tool.hidden).map((tool) => ({
|
|
5074
5389
|
name: tool.name,
|
|
5075
5390
|
description: tool.help ?? tool.usage + `
|
|
5076
5391
|
` + tool.description
|
|
@@ -5079,7 +5394,7 @@ class NotebookExecutionRuntime {
|
|
|
5079
5394
|
const outputHints = Object.fromEntries(tools.flatMap((tool) => ("textOutput" in tool) && tool.textOutput !== undefined ? [[tool.name, tool.textOutput]] : []));
|
|
5080
5395
|
const wrapped = [
|
|
5081
5396
|
`if (typeof globalThis.__piNotebook?.begin !== "function") throw new Error("Notebook runtime bootstrap unavailable: __piNotebook.begin");`,
|
|
5082
|
-
`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))});`,
|
|
5083
5398
|
code,
|
|
5084
5399
|
`if (typeof globalThis.__piNotebook?.flush !== "function") throw new Error("Notebook runtime bootstrap unavailable: __piNotebook.flush");`,
|
|
5085
5400
|
`await globalThis.__piNotebook.flush(${JSON.stringify(id)});`,
|
|
@@ -9072,8 +9387,10 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
|
|
|
9072
9387
|
};
|
|
9073
9388
|
},
|
|
9074
9389
|
});
|
|
9390
|
+
const __installToolNamespaces = ${installToolNamespacesSource};
|
|
9391
|
+
let __disposeToolNamespaces = __installToolNamespaces(__tools, []);
|
|
9075
9392
|
const __runtime = {
|
|
9076
|
-
async begin(cellId, tools, toolNames, toolOutputHints
|
|
9393
|
+
async begin(cellId, tools, toolNames, toolOutputHints, toolNamespaceDefinitions) {
|
|
9077
9394
|
if (__state.memoryTimer !== undefined) clearInterval(__state.memoryTimer);
|
|
9078
9395
|
__state.cellId = cellId;
|
|
9079
9396
|
__state.toolNames = toolNames;
|
|
@@ -9086,6 +9403,8 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
|
|
|
9086
9403
|
__state.outputTruncated = false;
|
|
9087
9404
|
globalThis.tools = __tools;
|
|
9088
9405
|
globalThis.ALL_TOOLS = tools;
|
|
9406
|
+
__disposeToolNamespaces();
|
|
9407
|
+
__disposeToolNamespaces = __installToolNamespaces(__tools, toolNamespaceDefinitions);
|
|
9089
9408
|
__state.cellGlobals = new Set(Object.getOwnPropertyNames(globalThis));
|
|
9090
9409
|
await __reportMemory(cellId);
|
|
9091
9410
|
__state.memoryTimer = setInterval(() => void __reportMemory(cellId).catch(() => undefined), 1000);
|
|
@@ -9113,6 +9432,7 @@ function notebookBootstrapSource(origin, token, exitToken, cwd) {
|
|
|
9113
9432
|
if (__state.memoryTimer !== undefined) clearInterval(__state.memoryTimer);
|
|
9114
9433
|
__state.memoryTimer = undefined;
|
|
9115
9434
|
__state.cellId = null;
|
|
9435
|
+
__disposeToolNamespaces();
|
|
9116
9436
|
},
|
|
9117
9437
|
projectBindings() {
|
|
9118
9438
|
return [...__state.projectBindings].sort();
|
|
@@ -10507,6 +10827,7 @@ var HOST_BINDINGS = new Set([
|
|
|
10507
10827
|
"notify",
|
|
10508
10828
|
"store",
|
|
10509
10829
|
"text",
|
|
10830
|
+
"toolNamespaces",
|
|
10510
10831
|
"tools",
|
|
10511
10832
|
"yield_control"
|
|
10512
10833
|
]);
|
|
@@ -10933,13 +11254,15 @@ function createNotebookEngine(options) {
|
|
|
10933
11254
|
const contract = readToolContract(registration);
|
|
10934
11255
|
return {
|
|
10935
11256
|
name: registration.name,
|
|
11257
|
+
hidden: contract.nestedHidden || contract.jsNamespace !== undefined,
|
|
11258
|
+
...contract.nestedHidden || contract.jsNamespace === undefined ? {} : { jsNamespace: contract.jsNamespace },
|
|
10936
11259
|
description: contract.description,
|
|
10937
11260
|
usage: contract.usage,
|
|
10938
11261
|
help: contract.help,
|
|
10939
11262
|
...registration.name === "exec_command" || registration.name === "write_stdin" ? { textOutput: "plain-command" } : {},
|
|
10940
11263
|
async invoke(input, _context, signal) {
|
|
10941
11264
|
signal.throwIfAborted();
|
|
10942
|
-
const args =
|
|
11265
|
+
const args = copyJson13(input === undefined ? null : input, {
|
|
10943
11266
|
omitUndefinedProperties: true
|
|
10944
11267
|
});
|
|
10945
11268
|
const invoke = api.tools[registration.name];
|
|
@@ -11092,7 +11415,7 @@ function parseNotebookRequest(input) {
|
|
|
11092
11415
|
}
|
|
11093
11416
|
|
|
11094
11417
|
// packages/notebook/src/tool-observation.ts
|
|
11095
|
-
import { copyJson as
|
|
11418
|
+
import { copyJson as copyJson14 } from "@earendil-works/chord/json";
|
|
11096
11419
|
import {
|
|
11097
11420
|
defineDocFamily as defineDocFamily2
|
|
11098
11421
|
} from "@earendil-works/pi-durable";
|
|
@@ -11147,7 +11470,7 @@ async function observeNotebookCell(observation, maxTokens, api, context) {
|
|
|
11147
11470
|
cell_id: String(observation.cellId),
|
|
11148
11471
|
status: observation.status,
|
|
11149
11472
|
...observation.forwardedToolCalls === undefined ? {} : {
|
|
11150
|
-
forwardedToolCalls:
|
|
11473
|
+
forwardedToolCalls: copyJson14(observation.forwardedToolCalls, {
|
|
11151
11474
|
omitUndefinedProperties: true
|
|
11152
11475
|
})
|
|
11153
11476
|
},
|
|
@@ -11297,15 +11620,15 @@ function createNotebookMode(options) {
|
|
|
11297
11620
|
};
|
|
11298
11621
|
return {
|
|
11299
11622
|
output: [{ type: "text", text: result.message }],
|
|
11300
|
-
details:
|
|
11301
|
-
structuredOutput:
|
|
11623
|
+
details: copyJson15(result.details),
|
|
11624
|
+
structuredOutput: copyJson15(result)
|
|
11302
11625
|
};
|
|
11303
11626
|
}
|
|
11304
11627
|
const result = await engine.control(request, api, context);
|
|
11305
11628
|
return {
|
|
11306
11629
|
output: [{ type: "text", text: result.message }],
|
|
11307
|
-
details:
|
|
11308
|
-
structuredOutput:
|
|
11630
|
+
details: copyJson15(result.details, { omitUndefinedProperties: true }),
|
|
11631
|
+
structuredOutput: copyJson15(result, { omitUndefinedProperties: true })
|
|
11309
11632
|
};
|
|
11310
11633
|
}
|
|
11311
11634
|
});
|
|
@@ -11318,7 +11641,7 @@ function createNotebookMode(options) {
|
|
|
11318
11641
|
...notebook,
|
|
11319
11642
|
executionHints: {
|
|
11320
11643
|
discovery: "help",
|
|
11321
|
-
inputSchema:
|
|
11644
|
+
inputSchema: copyJson15(JSON.parse(JSON.stringify(Type4.Union([NOTEBOOK_PARAMETERS, NOTEBOOK_ACTION_PARAMETERS]))))
|
|
11322
11645
|
}
|
|
11323
11646
|
},
|
|
11324
11647
|
...shell.tools
|
|
@@ -11326,12 +11649,8 @@ function createNotebookMode(options) {
|
|
|
11326
11649
|
sections: [
|
|
11327
11650
|
section("notebook", (input) => {
|
|
11328
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.';
|
|
11329
|
-
const promoted = input.agent.callable.filter((tool) => !["exec", "wait", "notebook"].includes(tool.name)).map(readToolContract).
|
|
11330
|
-
return [
|
|
11331
|
-
base,
|
|
11332
|
-
"For tools listed without a call signature, call with no arguments to get usage without performing an operation. Structured calls use {}.",
|
|
11333
|
-
...promoted
|
|
11334
|
-
].join(`
|
|
11652
|
+
const promoted = input.agent.callable.filter((tool) => !["exec", "wait", "notebook"].includes(tool.name)).map(readToolContract).flatMap(jsToolPrompt);
|
|
11653
|
+
return [base, nestedToolDiscoveryGuidance, ...promoted].join(`
|
|
11335
11654
|
`);
|
|
11336
11655
|
})
|
|
11337
11656
|
]
|