@howaboua/pi-durable-code 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 +427 -110
- package/dist/code/src/engine.d.ts +1 -1
- package/dist/code/src/history.d.ts +4 -4
- package/dist/code/src/index.d.ts +1 -0
- package/dist/code/src/runtime-contract.d.ts +3 -0
- package/dist/code/src/runtime-tools.d.ts +1 -1
- 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 +427 -110
- package/package.json +10 -9
package/dist/index.js
CHANGED
|
@@ -67,8 +67,8 @@ function parseInteger(value, name, minimum = 0, maximum = Number.MAX_SAFE_INTEGE
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
// packages/execution/src/cells.ts
|
|
70
|
-
import {
|
|
71
|
-
import {
|
|
70
|
+
import { withCancel as withCancel2 } from "@earendil-works/chord/context";
|
|
71
|
+
import { copyJson as copyJson12 } from "@earendil-works/chord/json";
|
|
72
72
|
import {
|
|
73
73
|
defineExtension
|
|
74
74
|
} from "@earendil-works/pi-durable";
|
|
@@ -79,7 +79,7 @@ import {
|
|
|
79
79
|
} from "@earendil-works/pi-durable";
|
|
80
80
|
|
|
81
81
|
// packages/execution/src/forwarding.ts
|
|
82
|
-
import { copyJson as copyJson2 } from "@earendil-works/chord";
|
|
82
|
+
import { copyJson as copyJson2 } from "@earendil-works/chord/json";
|
|
83
83
|
import {
|
|
84
84
|
LiveDoc,
|
|
85
85
|
NestedCallDoc,
|
|
@@ -89,7 +89,7 @@ import {
|
|
|
89
89
|
// packages/execution/src/invocation-state.ts
|
|
90
90
|
import {
|
|
91
91
|
copyJson
|
|
92
|
-
} from "@earendil-works/chord";
|
|
92
|
+
} from "@earendil-works/chord/json";
|
|
93
93
|
import {
|
|
94
94
|
defineDoc
|
|
95
95
|
} from "@earendil-works/pi-durable";
|
|
@@ -566,7 +566,7 @@ async function observeCell(kind, id, api, context, budget) {
|
|
|
566
566
|
}
|
|
567
567
|
|
|
568
568
|
// packages/execution/src/cell-progress.ts
|
|
569
|
-
import { copyJson as copyJson3 } from "@earendil-works/chord";
|
|
569
|
+
import { copyJson as copyJson3 } from "@earendil-works/chord/json";
|
|
570
570
|
import {
|
|
571
571
|
LiveDoc as LiveDoc2
|
|
572
572
|
} from "@earendil-works/pi-durable";
|
|
@@ -593,8 +593,14 @@ async function observeCellProgress(id, api, context, budget) {
|
|
|
593
593
|
return work;
|
|
594
594
|
};
|
|
595
595
|
const live = await api.watchDoc(LiveDoc2, api.conversationId, context);
|
|
596
|
-
cell.start((
|
|
597
|
-
|
|
596
|
+
cell.start((call) => own(async () => {
|
|
597
|
+
if (call.kind === "failed")
|
|
598
|
+
throw call.error;
|
|
599
|
+
await publish(call.value);
|
|
600
|
+
}));
|
|
601
|
+
live?.start((call) => own(async () => {
|
|
602
|
+
if (call.kind === "failed")
|
|
603
|
+
throw call.error;
|
|
598
604
|
await api.commit(async (tx) => {
|
|
599
605
|
const record = await tx.task(id);
|
|
600
606
|
if (record === undefined || record.state.status === "terminal")
|
|
@@ -614,43 +620,70 @@ async function observeCellProgress(id, api, context, budget) {
|
|
|
614
620
|
const endings = await Promise.all([cell.stop(), live?.stop()]);
|
|
615
621
|
await Promise.all([...pending]);
|
|
616
622
|
for (const ending of endings)
|
|
617
|
-
if (ending?.
|
|
623
|
+
if (ending?.kind === "listener_error" || ending?.kind === "failed")
|
|
618
624
|
throw ending.error;
|
|
619
625
|
};
|
|
620
626
|
}
|
|
621
627
|
|
|
622
628
|
// packages/execution/src/cell-task.ts
|
|
623
|
-
import { copyJson as copyJson8 } from "@earendil-works/chord";
|
|
624
629
|
import { withAbortSignal } from "@earendil-works/chord/context";
|
|
630
|
+
import { copyJson as copyJson8 } from "@earendil-works/chord/json";
|
|
625
631
|
import {
|
|
626
632
|
defineTask
|
|
627
633
|
} from "@earendil-works/pi-durable";
|
|
628
634
|
|
|
629
635
|
// packages/execution/src/cell-tools.ts
|
|
630
|
-
import { copyJson as copyJson6 } from "@earendil-works/chord";
|
|
631
636
|
import { withoutAbortSignal as withoutAbortSignal2 } from "@earendil-works/chord/context";
|
|
637
|
+
import { copyJson as copyJson6 } from "@earendil-works/chord/json";
|
|
632
638
|
|
|
633
639
|
// packages/execution/src/invocation.ts
|
|
634
|
-
import { copyJson as copyJson5 } from "@earendil-works/chord";
|
|
635
640
|
import { awaitWithContext } from "@earendil-works/chord/context";
|
|
641
|
+
import { copyJson as copyJson5 } from "@earendil-works/chord/json";
|
|
642
|
+
import {
|
|
643
|
+
NestedCallDoc as NestedCallDoc3
|
|
644
|
+
} from "@earendil-works/pi-durable";
|
|
645
|
+
import { equal } from "@earendil-works/pi-schema";
|
|
636
646
|
|
|
637
647
|
// packages/execution/src/native-tools.ts
|
|
638
|
-
import {
|
|
639
|
-
|
|
648
|
+
import {
|
|
649
|
+
withoutAbortSignal
|
|
650
|
+
} from "@earendil-works/chord/context";
|
|
651
|
+
import { copyJson as copyJson4 } from "@earendil-works/chord/json";
|
|
640
652
|
import {
|
|
641
653
|
LiveDoc as LiveDoc3,
|
|
642
654
|
NestedCallDoc as NestedCallDoc2,
|
|
643
|
-
ToolTask as
|
|
655
|
+
ToolTask as ToolTask3
|
|
644
656
|
} from "@earendil-works/pi-durable";
|
|
645
657
|
import { Equal } from "typebox/value";
|
|
646
|
-
|
|
658
|
+
|
|
659
|
+
// packages/execution/src/tool-origin.ts
|
|
660
|
+
import {
|
|
661
|
+
defineDoc as defineDoc2,
|
|
662
|
+
ToolTask as ToolTask2
|
|
663
|
+
} from "@earendil-works/pi-durable";
|
|
664
|
+
var ToolOriginDoc = defineDoc2({
|
|
665
|
+
kind: "howaboua.tool-origin",
|
|
666
|
+
version: 1,
|
|
667
|
+
scope: "task",
|
|
668
|
+
checkpointWhen: () => false,
|
|
669
|
+
initial: () => ({})
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
// packages/execution/src/native-tools.ts
|
|
673
|
+
function assertNestedKey(key) {
|
|
674
|
+
if (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key))
|
|
675
|
+
throw new Error("Invalid nested call or task key");
|
|
676
|
+
}
|
|
677
|
+
function nativeToolCalls(runtime, callId, replay, resumed, assertLive, context) {
|
|
647
678
|
let sequence = 0;
|
|
648
679
|
const admissions = [];
|
|
649
|
-
|
|
680
|
+
async function execute(name, args, callContext, options = {}) {
|
|
650
681
|
assertLive();
|
|
682
|
+
if (options.key !== undefined)
|
|
683
|
+
assertNestedKey(options.key);
|
|
684
|
+
else if (resumed)
|
|
685
|
+
throw new Error("Nested calls require an explicit key after waking");
|
|
651
686
|
const key = options.key ?? String(++sequence);
|
|
652
|
-
if (options.key !== undefined && (!key || key.includes("/") || key === "__proto__" || /^[1-9][0-9]*$/.test(key)))
|
|
653
|
-
throw new Error("Invalid nested call key");
|
|
654
687
|
const call = {
|
|
655
688
|
type: "toolCall",
|
|
656
689
|
id: `${callId}/${key}`,
|
|
@@ -662,11 +695,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
662
695
|
const admission = runtime.commit(async (tx) => {
|
|
663
696
|
const slot = await tx.doc(NestedCallDoc2, runtime.taskId, key, null);
|
|
664
697
|
if (slot.taskId !== undefined) {
|
|
665
|
-
const input = (await tx.task(slot.taskId))?.input;
|
|
698
|
+
const input = slot.kind === "task" ? undefined : (await tx.task(slot.taskId))?.input;
|
|
666
699
|
if (input?.kind !== "nested" || input.call.name !== name || !Equal(input.call.arguments, call.arguments))
|
|
667
700
|
throw new Error(`Nested call ${call.id} was already made with another tool or other arguments`);
|
|
668
701
|
} else {
|
|
669
|
-
slot.
|
|
702
|
+
slot.kind = "nested";
|
|
703
|
+
slot.taskId = await tx.createTask(ToolTask3, {
|
|
670
704
|
kind: "nested",
|
|
671
705
|
parent: runtime.taskId,
|
|
672
706
|
parentCallId: callId,
|
|
@@ -678,6 +712,9 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
678
712
|
abandonOnRestart: replay !== "safe"
|
|
679
713
|
});
|
|
680
714
|
const live = await tx.doc(LiveDoc3, runtime.conversationId);
|
|
715
|
+
const origin = (await tx.doc(ToolOriginDoc, runtime.taskId)).origin;
|
|
716
|
+
if (origin)
|
|
717
|
+
(await tx.doc(ToolOriginDoc, slot.taskId)).origin = { ...origin };
|
|
681
718
|
live.nestedTools ??= [];
|
|
682
719
|
live.nestedTools.push({
|
|
683
720
|
callId: call.id,
|
|
@@ -709,7 +746,13 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
709
746
|
const slot = await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext);
|
|
710
747
|
if (slot?.taskId === undefined)
|
|
711
748
|
throw new Error("Nested task creation did not commit");
|
|
712
|
-
const
|
|
749
|
+
const taskId = slot.taskId;
|
|
750
|
+
const result = (resultContext) => readResult(name, key, taskId, resultContext);
|
|
751
|
+
return options.wait === false ? { taskId, result } : result(callContext);
|
|
752
|
+
}
|
|
753
|
+
async function readResult(name, key, taskId, callContext) {
|
|
754
|
+
assertLive();
|
|
755
|
+
const settled = await runtime.waitForTask(taskId, callContext);
|
|
713
756
|
const result = (await runtime.snapshot(NestedCallDoc2, runtime.taskId, key, callContext))?.result;
|
|
714
757
|
await runtime.commit(async (tx) => {
|
|
715
758
|
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
@@ -717,7 +760,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
717
760
|
return;
|
|
718
761
|
}, callContext);
|
|
719
762
|
return result === undefined ? {
|
|
720
|
-
taskId
|
|
763
|
+
taskId,
|
|
721
764
|
isError: true,
|
|
722
765
|
diagnostics: [
|
|
723
766
|
{
|
|
@@ -727,9 +770,12 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
727
770
|
}
|
|
728
771
|
]
|
|
729
772
|
} : copyJson4(result);
|
|
730
|
-
}
|
|
773
|
+
}
|
|
731
774
|
return {
|
|
732
775
|
execute,
|
|
776
|
+
async drain() {
|
|
777
|
+
await Promise.allSettled(admissions);
|
|
778
|
+
},
|
|
733
779
|
async finish() {
|
|
734
780
|
await Promise.allSettled(admissions);
|
|
735
781
|
await cleanupNativeCalls(runtime, withoutAbortSignal(context));
|
|
@@ -737,7 +783,7 @@ function nativeToolCalls(runtime, callId, replay, assertLive, context) {
|
|
|
737
783
|
};
|
|
738
784
|
}
|
|
739
785
|
async function cleanupNativeCalls(runtime, context) {
|
|
740
|
-
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind ===
|
|
786
|
+
await Promise.all((await runtime.ownedTasks(context)).filter((child) => child.kind === ToolTask3.definition.name).map((child) => runtime.abortOwned(child.id, context)));
|
|
741
787
|
await runtime.commit(async (tx) => {
|
|
742
788
|
const owner = await tx.doc(InvocationDoc, runtime.taskId);
|
|
743
789
|
await captureNativeCalls(tx, runtime.conversationId, runtime.taskId, owner.forwardingCellId);
|
|
@@ -831,18 +877,6 @@ class Progress {
|
|
|
831
877
|
}
|
|
832
878
|
}
|
|
833
879
|
|
|
834
|
-
// packages/execution/src/tool-origin.ts
|
|
835
|
-
import {
|
|
836
|
-
defineDoc as defineDoc2
|
|
837
|
-
} from "@earendil-works/pi-durable";
|
|
838
|
-
var ToolOriginDoc = defineDoc2({
|
|
839
|
-
kind: "howaboua.tool-origin",
|
|
840
|
-
version: 1,
|
|
841
|
-
scope: "task",
|
|
842
|
-
checkpointWhen: () => false,
|
|
843
|
-
initial: () => ({})
|
|
844
|
-
});
|
|
845
|
-
|
|
846
880
|
// packages/execution/src/invocation.ts
|
|
847
881
|
function executionError(code, message) {
|
|
848
882
|
return {
|
|
@@ -854,21 +888,23 @@ function executionError(code, message) {
|
|
|
854
888
|
function errorText(error) {
|
|
855
889
|
return error instanceof Error ? error.message : String(error);
|
|
856
890
|
}
|
|
857
|
-
function createInvocation(runtime, tool, context) {
|
|
891
|
+
function createInvocation(runtime, tool, context, resume) {
|
|
858
892
|
const limits = {
|
|
859
893
|
maxBytes: tool.outputLimits?.maxBytes ?? 50 * 1024,
|
|
860
894
|
maxLines: tool.outputLimits?.maxLines ?? 2000,
|
|
861
895
|
retain: tool.outputLimits?.retain ?? "head"
|
|
862
896
|
};
|
|
863
897
|
const output = new OutputBuffer(limits);
|
|
864
|
-
const diagnostics = [
|
|
865
|
-
|
|
898
|
+
const diagnostics = [
|
|
899
|
+
...resume?.progress?.diagnostics ?? []
|
|
900
|
+
];
|
|
901
|
+
let details = resume?.progress?.details;
|
|
866
902
|
let ended = false;
|
|
867
903
|
const assertLive = () => {
|
|
868
904
|
if (ended)
|
|
869
905
|
throw new Error(`Invocation ${runtime.taskId} has settled`);
|
|
870
906
|
};
|
|
871
|
-
const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, assertLive, context);
|
|
907
|
+
const native = nativeToolCalls(runtime, `nested-${runtime.taskId}`, tool.replay, resume?.wake !== undefined, assertLive, context);
|
|
872
908
|
const snapshot = () => {
|
|
873
909
|
const retained = output.snapshot();
|
|
874
910
|
return {
|
|
@@ -897,6 +933,8 @@ function createInvocation(runtime, tool, context) {
|
|
|
897
933
|
taskId: runtime.taskId,
|
|
898
934
|
conversationId: runtime.conversationId,
|
|
899
935
|
callId: `nested-${runtime.taskId}`,
|
|
936
|
+
wake: resume?.wake,
|
|
937
|
+
checkpoint: resume?.checkpoint,
|
|
900
938
|
registry: runtime.registry,
|
|
901
939
|
agent: runtime.agent,
|
|
902
940
|
env: undefined,
|
|
@@ -917,7 +955,7 @@ function createInvocation(runtime, tool, context) {
|
|
|
917
955
|
const retained = output.snapshot();
|
|
918
956
|
return { text: retained.text, truncated: retained.droppedBytes > 0 };
|
|
919
957
|
},
|
|
920
|
-
executeTool:
|
|
958
|
+
executeTool: native.execute,
|
|
921
959
|
diagnostic: (value) => {
|
|
922
960
|
assertLive();
|
|
923
961
|
diagnostics.push(copyJson5(value, { omitUndefinedProperties: true }));
|
|
@@ -931,24 +969,44 @@ function createInvocation(runtime, tool, context) {
|
|
|
931
969
|
committed.catch(() => {});
|
|
932
970
|
await awaitWithContext(committed, detailContext);
|
|
933
971
|
},
|
|
934
|
-
commit: async (change, commitContext) => {
|
|
972
|
+
commit: async (change, commitContext, options) => {
|
|
935
973
|
assertLive();
|
|
936
974
|
let result;
|
|
937
975
|
await runtime.commit(async (tx) => {
|
|
938
976
|
result = await change(tx);
|
|
939
977
|
return;
|
|
940
|
-
}, commitContext);
|
|
978
|
+
}, commitContext, options);
|
|
941
979
|
return result;
|
|
942
980
|
},
|
|
943
981
|
memo: runtime.memo,
|
|
944
|
-
|
|
982
|
+
readSignal: runtime.readSignal,
|
|
983
|
+
async createTask(task, input, {
|
|
984
|
+
key,
|
|
985
|
+
...options
|
|
986
|
+
}, taskContext) {
|
|
945
987
|
assertLive();
|
|
988
|
+
if (key !== undefined)
|
|
989
|
+
assertNestedKey(key);
|
|
990
|
+
else if (resume?.wake !== undefined)
|
|
991
|
+
throw new Error("Child tasks require an explicit key after waking");
|
|
946
992
|
let id;
|
|
947
993
|
await runtime.commit(async (tx) => {
|
|
994
|
+
const member = key === undefined ? undefined : await tx.doc(NestedCallDoc3, runtime.taskId, key, null);
|
|
995
|
+
if (member?.taskId !== undefined) {
|
|
996
|
+
const existing = member.kind === "task" ? await tx.task(member.taskId) : undefined;
|
|
997
|
+
if (existing?.kind !== task.definition.name || !equal(existing.input, copyJson5(input, { omitUndefinedProperties: true })))
|
|
998
|
+
throw new Error(`Key ${key} was already used for another call or task`);
|
|
999
|
+
id = member.taskId;
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
948
1002
|
id = await tx.createTask(task, input, {
|
|
949
1003
|
...options,
|
|
950
1004
|
...options.abandonOnRestart === undefined && tool.replay !== "safe" && options.ownership.kind === "task" && options.ownership.taskId === runtime.taskId ? { abandonOnRestart: true } : {}
|
|
951
1005
|
});
|
|
1006
|
+
if (member !== undefined) {
|
|
1007
|
+
member.kind = "task";
|
|
1008
|
+
member.taskId = id;
|
|
1009
|
+
}
|
|
952
1010
|
const source = await tx.doc(ToolOriginDoc, runtime.taskId);
|
|
953
1011
|
if (source.origin !== undefined)
|
|
954
1012
|
(await tx.doc(ToolOriginDoc, id)).origin = { ...source.origin };
|
|
@@ -995,6 +1053,14 @@ function createInvocation(runtime, tool, context) {
|
|
|
995
1053
|
for (const waiter of await progress.stop())
|
|
996
1054
|
waiter.reject(error);
|
|
997
1055
|
},
|
|
1056
|
+
async park() {
|
|
1057
|
+
ended = true;
|
|
1058
|
+
await native.drain();
|
|
1059
|
+
output.end();
|
|
1060
|
+
const pending = await progress.stop();
|
|
1061
|
+
const { output: _output, ...kept } = snapshot();
|
|
1062
|
+
return { progress: storeResult(kept), pending };
|
|
1063
|
+
},
|
|
998
1064
|
limits,
|
|
999
1065
|
output,
|
|
1000
1066
|
progress
|
|
@@ -1096,7 +1162,74 @@ function combineControls(controls, allowTermination = true) {
|
|
|
1096
1162
|
}
|
|
1097
1163
|
|
|
1098
1164
|
// packages/execution/src/tool-contract.ts
|
|
1099
|
-
import { copyJson as copyJson7 } from "@earendil-works/chord";
|
|
1165
|
+
import { copyJson as copyJson7 } from "@earendil-works/chord/json";
|
|
1166
|
+
|
|
1167
|
+
// packages/execution/src/tool-namespaces.ts
|
|
1168
|
+
import { isJsonValue } from "@earendil-works/chord/json";
|
|
1169
|
+
function validateJsToolNamespace(tool, namespace) {
|
|
1170
|
+
const key = (value) => typeof value === "string" && /^[a-zA-Z_$][\w$]*$/.test(value);
|
|
1171
|
+
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))))
|
|
1172
|
+
throw new Error(`Tool ${tool} has invalid jsNamespace metadata`);
|
|
1173
|
+
}
|
|
1174
|
+
function jsToolPrompt(contract) {
|
|
1175
|
+
if (contract.nativeOnly || contract.nestedHidden)
|
|
1176
|
+
return [];
|
|
1177
|
+
if (contract.jsNamespace)
|
|
1178
|
+
return [contract.jsNamespace.prompt];
|
|
1179
|
+
return contract.deferLoading ? [] : [contract.prompt];
|
|
1180
|
+
}
|
|
1181
|
+
function namespaceDefinitions(tools) {
|
|
1182
|
+
return tools.flatMap(({ name, jsNamespace }) => jsNamespace ? [{ tool: name, name: jsNamespace.name, methods: jsNamespace.methods }] : []);
|
|
1183
|
+
}
|
|
1184
|
+
var installToolNamespacesSource = `(tools, definitions) => {
|
|
1185
|
+
const namespaces = Object.create(null);
|
|
1186
|
+
const binders = Object.create(null);
|
|
1187
|
+
let active = true;
|
|
1188
|
+
const add = (target, key, value) => {
|
|
1189
|
+
if (Object.hasOwn(target, key)) throw new Error("Duplicate tool namespace member: " + key);
|
|
1190
|
+
target[key] = value;
|
|
1191
|
+
};
|
|
1192
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1193
|
+
for (const { tool, name, methods } of definitions) {
|
|
1194
|
+
const namespace = namespaces[name] ??= Object.create(null);
|
|
1195
|
+
const bound = binders[name] ??= Object.create(null);
|
|
1196
|
+
for (const { name: method, bind, defaults } of methods) {
|
|
1197
|
+
const invoke = (args, ref) => {
|
|
1198
|
+
if (!active)
|
|
1199
|
+
throw new Error("Tool namespace binding expired; bind the server reference again in this cell");
|
|
1200
|
+
if (args !== undefined && !object(args))
|
|
1201
|
+
throw new TypeError("Tool namespace arguments must be an object");
|
|
1202
|
+
return tools[tool]({ ...args, ...defaults, ...(bind === undefined ? {} : { [bind]: ref }) });
|
|
1203
|
+
};
|
|
1204
|
+
if (bind === undefined) {
|
|
1205
|
+
add(namespace, method, (args) => invoke(args));
|
|
1206
|
+
continue;
|
|
1207
|
+
}
|
|
1208
|
+
if (!Object.hasOwn(bound, bind)) {
|
|
1209
|
+
const members = bound[bind] = Object.create(null);
|
|
1210
|
+
add(namespace, bind, (ref) => {
|
|
1211
|
+
if (!object(ref)) throw new TypeError("Supply a discovered namespace reference");
|
|
1212
|
+
const reference = { ...ref };
|
|
1213
|
+
const result = Object.create(null);
|
|
1214
|
+
for (const [key, call] of Object.entries(members))
|
|
1215
|
+
result[key] = (args) => call(args, reference);
|
|
1216
|
+
return Object.freeze(result);
|
|
1217
|
+
});
|
|
1218
|
+
}
|
|
1219
|
+
add(bound[bind], method, invoke);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
for (const namespace of Object.values(namespaces)) Object.freeze(namespace);
|
|
1223
|
+
globalThis.toolNamespaces = Object.freeze(namespaces);
|
|
1224
|
+
return () => {
|
|
1225
|
+
active = false;
|
|
1226
|
+
if (globalThis.toolNamespaces === namespaces)
|
|
1227
|
+
globalThis.toolNamespaces = Object.freeze(Object.create(null));
|
|
1228
|
+
};
|
|
1229
|
+
}`;
|
|
1230
|
+
|
|
1231
|
+
// packages/execution/src/tool-contract.ts
|
|
1232
|
+
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 {}";
|
|
1100
1233
|
function readToolContract(tool) {
|
|
1101
1234
|
const candidate = "executionHints" in tool ? tool.executionHints : undefined;
|
|
1102
1235
|
if (candidate !== undefined && (candidate === null || typeof candidate !== "object" || Array.isArray(candidate))) {
|
|
@@ -1110,6 +1243,7 @@ function readToolContract(tool) {
|
|
|
1110
1243
|
"yieldTimeMs",
|
|
1111
1244
|
"inputSchema",
|
|
1112
1245
|
"nativeOnly",
|
|
1246
|
+
"nestedHidden",
|
|
1113
1247
|
"discovery"
|
|
1114
1248
|
]);
|
|
1115
1249
|
for (const key of Object.keys(hints))
|
|
@@ -1133,6 +1267,12 @@ function readToolContract(tool) {
|
|
|
1133
1267
|
const nativeOnly = "nativeOnly" in hints ? hints.nativeOnly : undefined;
|
|
1134
1268
|
if (nativeOnly !== undefined && typeof nativeOnly !== "boolean")
|
|
1135
1269
|
throw new Error(`Tool ${tool.name} executionHints.nativeOnly must be a boolean`);
|
|
1270
|
+
const nestedHidden = "nestedHidden" in hints ? hints.nestedHidden : undefined;
|
|
1271
|
+
const jsNamespace = "jsNamespace" in tool ? tool.jsNamespace : undefined;
|
|
1272
|
+
if (jsNamespace !== undefined)
|
|
1273
|
+
validateJsToolNamespace(tool.name, jsNamespace);
|
|
1274
|
+
if (nestedHidden !== undefined && typeof nestedHidden !== "boolean")
|
|
1275
|
+
throw new Error(`Tool ${tool.name} executionHints.nestedHidden must be a boolean`);
|
|
1136
1276
|
const yieldTimeMs = "yieldTimeMs" in hints ? hints.yieldTimeMs : undefined;
|
|
1137
1277
|
if (yieldTimeMs !== undefined && (typeof yieldTimeMs !== "number" || !Number.isSafeInteger(yieldTimeMs) || yieldTimeMs < 0))
|
|
1138
1278
|
throw new Error(`Tool ${tool.name} executionHints.yieldTimeMs must be a non-negative safe integer`);
|
|
@@ -1149,6 +1289,8 @@ function readToolContract(tool) {
|
|
|
1149
1289
|
inputSchema,
|
|
1150
1290
|
deferLoading: typeof deferred === "boolean" ? deferred : true,
|
|
1151
1291
|
nativeOnly: nativeOnly === true,
|
|
1292
|
+
nestedHidden: nestedHidden === true,
|
|
1293
|
+
...jsNamespace === undefined ? {} : { jsNamespace },
|
|
1152
1294
|
...typeof yieldTimeMs === "number" ? { yieldTimeMs } : {},
|
|
1153
1295
|
...outputHint === undefined ? {} : { output: outputHint },
|
|
1154
1296
|
help: [
|
|
@@ -1384,7 +1526,7 @@ function createCellTask(options, nestedTask) {
|
|
|
1384
1526
|
import {
|
|
1385
1527
|
hook,
|
|
1386
1528
|
LiveDoc as LiveDoc4,
|
|
1387
|
-
ToolTask as
|
|
1529
|
+
ToolTask as ToolTask4
|
|
1388
1530
|
} from "@earendil-works/pi-durable";
|
|
1389
1531
|
function forwardingHook() {
|
|
1390
1532
|
let host;
|
|
@@ -1394,7 +1536,7 @@ function forwardingHook() {
|
|
|
1394
1536
|
throw new Error("Create a separate execution component for each Harness");
|
|
1395
1537
|
host = harness;
|
|
1396
1538
|
},
|
|
1397
|
-
hook: hook(
|
|
1539
|
+
hook: hook(ToolTask4, {
|
|
1398
1540
|
async beforeTool(call, api, context) {
|
|
1399
1541
|
const parent = call.parent;
|
|
1400
1542
|
if (parent === undefined || host === undefined)
|
|
@@ -1407,7 +1549,7 @@ function forwardingHook() {
|
|
|
1407
1549
|
if (conversation === undefined)
|
|
1408
1550
|
throw new Error("Forwarded call conversation is unavailable");
|
|
1409
1551
|
await conversation.commit(async (tx) => {
|
|
1410
|
-
if ((await tx.task(api.taskId))?.kind !==
|
|
1552
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
|
|
1411
1553
|
return;
|
|
1412
1554
|
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1413
1555
|
const admission = owner.forwardingCellId === undefined;
|
|
@@ -1434,7 +1576,7 @@ function forwardingHook() {
|
|
|
1434
1576
|
if (conversation === undefined)
|
|
1435
1577
|
throw new Error("Forwarded call conversation is unavailable");
|
|
1436
1578
|
await conversation.commit(async (tx) => {
|
|
1437
|
-
if ((await tx.task(api.taskId))?.kind !==
|
|
1579
|
+
if ((await tx.task(api.taskId))?.kind !== ToolTask4.definition.name)
|
|
1438
1580
|
return;
|
|
1439
1581
|
const owner = await tx.doc(InvocationDoc, api.taskId);
|
|
1440
1582
|
const cellId = owner.forwardingCellId;
|
|
@@ -1459,17 +1601,18 @@ function forwardingHook() {
|
|
|
1459
1601
|
}
|
|
1460
1602
|
|
|
1461
1603
|
// packages/execution/src/nested.ts
|
|
1604
|
+
import { copyJson as copyJson11 } from "@earendil-works/chord/json";
|
|
1462
1605
|
import {
|
|
1463
1606
|
defineTask as defineTask2
|
|
1464
1607
|
} from "@earendil-works/pi-durable";
|
|
1465
|
-
import {
|
|
1608
|
+
import { compile as compile2 } from "@earendil-works/pi-schema";
|
|
1466
1609
|
|
|
1467
1610
|
// packages/execution/src/nested-call.ts
|
|
1468
1611
|
import { validateToolArguments } from "@earendil-works/pi-ai/utils/validation";
|
|
1469
1612
|
import {
|
|
1470
|
-
ToolTask as
|
|
1613
|
+
ToolTask as ToolTask5
|
|
1471
1614
|
} from "@earendil-works/pi-durable";
|
|
1472
|
-
import {
|
|
1615
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
1473
1616
|
function nestedCall(runtime, input) {
|
|
1474
1617
|
const args = input.arguments;
|
|
1475
1618
|
return {
|
|
@@ -1490,7 +1633,7 @@ function prepareNestedInput(tool, input) {
|
|
|
1490
1633
|
if (typeof input !== "string")
|
|
1491
1634
|
return input;
|
|
1492
1635
|
const contract = readToolContract(tool);
|
|
1493
|
-
if (Boolean(
|
|
1636
|
+
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)))
|
|
1494
1637
|
return input;
|
|
1495
1638
|
const text = input.trim();
|
|
1496
1639
|
if (contract.discovery === "help" && text === "help")
|
|
@@ -1513,7 +1656,7 @@ function prepareNestedInput(tool, input) {
|
|
|
1513
1656
|
async function eachHook(agent, name, api, invoke) {
|
|
1514
1657
|
for (const extension of agent.extensions)
|
|
1515
1658
|
for (const registration of extension.hooks ?? []) {
|
|
1516
|
-
if (registration.task !==
|
|
1659
|
+
if (registration.task !== ToolTask5.definition.name)
|
|
1517
1660
|
continue;
|
|
1518
1661
|
const handler = registration.handlers[name];
|
|
1519
1662
|
if (handler === undefined)
|
|
@@ -1528,8 +1671,120 @@ async function eachHook(agent, name, api, invoke) {
|
|
|
1528
1671
|
}
|
|
1529
1672
|
}
|
|
1530
1673
|
|
|
1674
|
+
// packages/execution/src/nested-park.ts
|
|
1675
|
+
import {
|
|
1676
|
+
withCancel,
|
|
1677
|
+
withoutAbortSignal as withoutAbortSignal3
|
|
1678
|
+
} from "@earendil-works/chord/context";
|
|
1679
|
+
import { copyJson as copyJson9 } from "@earendil-works/chord/json";
|
|
1680
|
+
var resultFields = [
|
|
1681
|
+
"output",
|
|
1682
|
+
"structuredOutput",
|
|
1683
|
+
"isError",
|
|
1684
|
+
"details",
|
|
1685
|
+
"diagnostics",
|
|
1686
|
+
"usage",
|
|
1687
|
+
"control"
|
|
1688
|
+
];
|
|
1689
|
+
function sleepState(checkpoint, { until, signals }) {
|
|
1690
|
+
return {
|
|
1691
|
+
status: "sleeping",
|
|
1692
|
+
checkpoint,
|
|
1693
|
+
...until === undefined ? {} : { until },
|
|
1694
|
+
...signals === undefined ? {} : { signals }
|
|
1695
|
+
};
|
|
1696
|
+
}
|
|
1697
|
+
async function parkGate(runtime, sleep, context) {
|
|
1698
|
+
try {
|
|
1699
|
+
await runtime.commit(() => sleepState({ phase: "call" }, sleep), context);
|
|
1700
|
+
} catch (error) {
|
|
1701
|
+
runtime.signal.throwIfAborted();
|
|
1702
|
+
return errorText(error);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
async function parkTool(runtime, invocation, tool, args, park, context) {
|
|
1706
|
+
if (park.kind !== "sleep" && park.kind !== "wait")
|
|
1707
|
+
return "Unknown park kind";
|
|
1708
|
+
const mixed = resultFields.find((field) => (field in park));
|
|
1709
|
+
if (mixed !== undefined)
|
|
1710
|
+
return `A park cannot carry the result field ${mixed}`;
|
|
1711
|
+
const intent = {
|
|
1712
|
+
arguments: args,
|
|
1713
|
+
replay: tool.replay ?? "unsafe",
|
|
1714
|
+
...park.checkpoint === undefined ? {} : { checkpoint: copyJson9(park.checkpoint) }
|
|
1715
|
+
};
|
|
1716
|
+
const { progress, pending } = await invocation.park();
|
|
1717
|
+
try {
|
|
1718
|
+
await runtime.commit(async (tx) => {
|
|
1719
|
+
if (park.kind === "wait") {
|
|
1720
|
+
for (const id of park.on)
|
|
1721
|
+
if ((await tx.task(id))?.owner !== runtime.taskId)
|
|
1722
|
+
throw new Error(`Task ${id} is not owned by the call`);
|
|
1723
|
+
}
|
|
1724
|
+
const checkpoint = { ...intent, phase: "parked" };
|
|
1725
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1726
|
+
doc.result = progress;
|
|
1727
|
+
doc.droppedBytes = 0;
|
|
1728
|
+
doc.droppedLines = 0;
|
|
1729
|
+
await forwardInvocationResult(tx, runtime.taskId, progress, "running");
|
|
1730
|
+
return park.kind === "sleep" ? sleepState(checkpoint, park) : { status: "waiting", checkpoint, on: park.on, policy: park.policy };
|
|
1731
|
+
}, context);
|
|
1732
|
+
} catch (error) {
|
|
1733
|
+
for (const waiter of pending)
|
|
1734
|
+
waiter.reject(error);
|
|
1735
|
+
const detached = withoutAbortSignal3(context);
|
|
1736
|
+
const record = await runtime.getTask(runtime.taskId, detached);
|
|
1737
|
+
if (record?.abortRequested) {
|
|
1738
|
+
const watch = await runtime.watchDoc(InvocationDoc, runtime.taskId, detached);
|
|
1739
|
+
if (watch !== undefined) {
|
|
1740
|
+
const cleanup = withCancel(detached);
|
|
1741
|
+
watch.closed.then((end) => cleanup.cancel(end.kind === "failed" ? end.error : undefined));
|
|
1742
|
+
try {
|
|
1743
|
+
await cancelParkedTool(runtime, tool, intent, cleanup.context);
|
|
1744
|
+
} finally {
|
|
1745
|
+
await watch.stop();
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
throw error;
|
|
1749
|
+
}
|
|
1750
|
+
runtime.signal.throwIfAborted();
|
|
1751
|
+
return errorText(error);
|
|
1752
|
+
}
|
|
1753
|
+
for (const waiter of pending)
|
|
1754
|
+
waiter.resolve();
|
|
1755
|
+
}
|
|
1756
|
+
async function cancelParkedTool(runtime, tool, intent, context) {
|
|
1757
|
+
if (!tool) {
|
|
1758
|
+
runtime.report(new Error("The parked tool is no longer registered; cleanup could not run"));
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
if (tool.cancel === undefined)
|
|
1762
|
+
return;
|
|
1763
|
+
const cleanup = createInvocation(runtime, tool, context, {
|
|
1764
|
+
checkpoint: intent.checkpoint,
|
|
1765
|
+
wake: undefined
|
|
1766
|
+
});
|
|
1767
|
+
const refuseWork = () => {
|
|
1768
|
+
throw new Error("A tool cannot start tasks or nested calls during cancellation");
|
|
1769
|
+
};
|
|
1770
|
+
let reason = new Error("Tool cancellation finished");
|
|
1771
|
+
try {
|
|
1772
|
+
const api = await cleanup.executionApi();
|
|
1773
|
+
await tool.cancel(intent.arguments, {
|
|
1774
|
+
...api,
|
|
1775
|
+
createTask: refuseWork,
|
|
1776
|
+
executeTool: refuseWork
|
|
1777
|
+
}, context);
|
|
1778
|
+
} catch (error) {
|
|
1779
|
+
reason = error;
|
|
1780
|
+
runtime.report(error);
|
|
1781
|
+
} finally {
|
|
1782
|
+
await cleanup.stop(reason);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
|
|
1531
1786
|
// packages/execution/src/nested-result.ts
|
|
1532
|
-
import { copyJson as
|
|
1787
|
+
import { copyJson as copyJson10 } from "@earendil-works/chord/json";
|
|
1533
1788
|
import {
|
|
1534
1789
|
defineEntry,
|
|
1535
1790
|
UsageDoc
|
|
@@ -1577,11 +1832,11 @@ async function settle(runtime, call, result, ending, context) {
|
|
|
1577
1832
|
taskId: runtime.taskId,
|
|
1578
1833
|
callId: call.id,
|
|
1579
1834
|
name: call.name,
|
|
1580
|
-
arguments:
|
|
1835
|
+
arguments: copyJson10(call.arguments),
|
|
1581
1836
|
result: stored,
|
|
1582
1837
|
...current.state.checkpoint.phase === "execute" ? {
|
|
1583
1838
|
intent: {
|
|
1584
|
-
arguments:
|
|
1839
|
+
arguments: copyJson10(current.state.checkpoint.arguments),
|
|
1585
1840
|
replay: current.state.checkpoint.replay
|
|
1586
1841
|
}
|
|
1587
1842
|
} : {}
|
|
@@ -1590,7 +1845,7 @@ async function settle(runtime, call, result, ending, context) {
|
|
|
1590
1845
|
if (result.usage !== undefined) {
|
|
1591
1846
|
const totals = (await tx.doc(UsageDoc, runtime.conversationId)).tools;
|
|
1592
1847
|
const previous = Object.hasOwn(totals, call.name) ? totals[call.name] : undefined;
|
|
1593
|
-
totals[call.name] =
|
|
1848
|
+
totals[call.name] = copyJson10(previous === undefined ? result.usage : sumUsage(previous, result.usage), { omitUndefinedProperties: true });
|
|
1594
1849
|
}
|
|
1595
1850
|
const outcome = ending === "completed" ? { status: ending, result: stored } : ending === "aborted" ? { status: ending, result: stored } : {
|
|
1596
1851
|
status: ending,
|
|
@@ -1627,7 +1882,11 @@ function sumUsage(previous, added) {
|
|
|
1627
1882
|
function createNestedToolTask(name) {
|
|
1628
1883
|
return defineTask2({
|
|
1629
1884
|
name,
|
|
1630
|
-
version:
|
|
1885
|
+
version: 2,
|
|
1886
|
+
migrate: (input, checkpoint) => ({
|
|
1887
|
+
input,
|
|
1888
|
+
checkpoint
|
|
1889
|
+
}),
|
|
1631
1890
|
initial: () => ({ phase: "call" }),
|
|
1632
1891
|
phases: {
|
|
1633
1892
|
call: async (task, runtime, context) => {
|
|
@@ -1653,22 +1912,25 @@ function createNestedToolTask(name) {
|
|
|
1653
1912
|
return reject(runtime, call, executionError("tool_unavailable", `Tool ${call.name} is not available`), agent, tool, context);
|
|
1654
1913
|
let args;
|
|
1655
1914
|
try {
|
|
1656
|
-
const supplied = task.input.arguments === null && !
|
|
1915
|
+
const supplied = task.input.arguments === null && !compile2(tool.parameters).check(null) && compile2(tool.parameters).check({}) ? undefined : task.input.arguments;
|
|
1657
1916
|
const prepared = tool.prepareArguments === undefined ? prepareNestedInput(tool, supplied) : tool.prepareArguments(prepareNestedInput(tool, supplied));
|
|
1658
|
-
args = checked(tool, call, prepared === undefined &&
|
|
1917
|
+
args = checked(tool, call, prepared === undefined && compile2(tool.parameters).check({}) ? {} : prepared);
|
|
1659
1918
|
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1660
1919
|
call.arguments = args;
|
|
1661
1920
|
} catch (error) {
|
|
1662
1921
|
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1663
1922
|
}
|
|
1664
1923
|
let block;
|
|
1924
|
+
let sleep;
|
|
1665
1925
|
await eachHook(agent, "beforeTool", runtime, async (handler) => {
|
|
1666
|
-
if (block !== undefined)
|
|
1926
|
+
if (block !== undefined || sleep !== undefined)
|
|
1667
1927
|
return;
|
|
1668
1928
|
try {
|
|
1669
1929
|
const decision = await handler({ ...call, arguments: args }, runtime, context);
|
|
1670
1930
|
if (decision?.block !== undefined)
|
|
1671
1931
|
block = decision.block;
|
|
1932
|
+
else if (decision?.sleep !== undefined)
|
|
1933
|
+
sleep = decision.sleep;
|
|
1672
1934
|
else if (decision?.arguments !== undefined)
|
|
1673
1935
|
args = decision.arguments;
|
|
1674
1936
|
} catch (error) {
|
|
@@ -1679,71 +1941,122 @@ function createNestedToolTask(name) {
|
|
|
1679
1941
|
});
|
|
1680
1942
|
if (block !== undefined)
|
|
1681
1943
|
return reject(runtime, call, executionError("blocked", `Tool call blocked: ${block}`), agent, tool, context);
|
|
1944
|
+
if (sleep !== undefined) {
|
|
1945
|
+
const reason = await parkGate(runtime, sleep, context);
|
|
1946
|
+
if (reason === undefined)
|
|
1947
|
+
return;
|
|
1948
|
+
return reject(runtime, call, executionError("invalid_park", reason), agent, tool, context);
|
|
1949
|
+
}
|
|
1682
1950
|
try {
|
|
1683
|
-
args = checked(tool, call, args)
|
|
1951
|
+
args = copyJson11(checked(tool, call, args), {
|
|
1952
|
+
omitUndefinedProperties: true
|
|
1953
|
+
});
|
|
1684
1954
|
} catch (error) {
|
|
1685
1955
|
return reject(runtime, call, executionError("invalid_arguments", errorText(error)), agent, tool, context);
|
|
1686
1956
|
}
|
|
1687
|
-
await runtime
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
callId: call.id,
|
|
1691
|
-
parentCallId: call.parent?.callId ?? `nested-${runtime.taskId}`,
|
|
1692
|
-
name: call.name,
|
|
1693
|
-
arguments: args,
|
|
1694
|
-
status: "running",
|
|
1695
|
-
result: null,
|
|
1696
|
-
omittedFields: []
|
|
1697
|
-
});
|
|
1698
|
-
return {
|
|
1699
|
-
status: "running",
|
|
1700
|
-
checkpoint: {
|
|
1701
|
-
phase: "execute",
|
|
1702
|
-
arguments: args,
|
|
1703
|
-
replay: tool.replay ?? "unsafe"
|
|
1704
|
-
}
|
|
1705
|
-
};
|
|
1957
|
+
await startAttempt(runtime, call, tool, agent, {
|
|
1958
|
+
arguments: args,
|
|
1959
|
+
replay: tool.replay ?? "unsafe"
|
|
1706
1960
|
}, context);
|
|
1707
|
-
|
|
1961
|
+
},
|
|
1962
|
+
parked: async (task, runtime, context) => {
|
|
1963
|
+
const intent = task.state.checkpoint;
|
|
1964
|
+
const call = nestedCall(runtime, task.input);
|
|
1965
|
+
call.arguments = intent.arguments;
|
|
1966
|
+
const agent = await runtime.agent(context);
|
|
1967
|
+
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1968
|
+
if (tool === undefined || readToolContract(tool).nativeOnly)
|
|
1969
|
+
return interrupted(runtime, call, "interrupted", `Parked tool ${call.name} is no longer available and could not be resumed`, context);
|
|
1970
|
+
await startAttempt(runtime, call, tool, agent, {
|
|
1971
|
+
...intent,
|
|
1972
|
+
replay: tool.replay ?? "unsafe"
|
|
1973
|
+
}, context, task.state.wake);
|
|
1708
1974
|
},
|
|
1709
1975
|
execute: async (task, runtime, context) => {
|
|
1976
|
+
const intent = task.state.checkpoint;
|
|
1710
1977
|
const call = nestedCall(runtime, task.input);
|
|
1711
1978
|
if (task.input.arguments === null || typeof task.input.arguments !== "object" || Array.isArray(task.input.arguments))
|
|
1712
1979
|
call.arguments = task.state.checkpoint.arguments;
|
|
1713
1980
|
const agent = await runtime.agent(context);
|
|
1714
1981
|
const tool = agent.callable.find((each) => each.name === call.name);
|
|
1715
|
-
if (
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1982
|
+
if (intent.replay === "safe" && tool?.replay === "safe" && !readToolContract(tool).nativeOnly) {
|
|
1983
|
+
if (intent.resume === undefined)
|
|
1984
|
+
await runtime.commit(async (tx) => {
|
|
1985
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
1986
|
+
doc.result = {};
|
|
1987
|
+
doc.droppedBytes = 0;
|
|
1988
|
+
doc.droppedLines = 0;
|
|
1989
|
+
return;
|
|
1990
|
+
}, context);
|
|
1991
|
+
return run(runtime, call, tool, intent, agent, context, intent.resume?.wake);
|
|
1724
1992
|
}
|
|
1993
|
+
if (intent.resume !== undefined)
|
|
1994
|
+
await cancelParkedTool(runtime, tool, intent, context);
|
|
1725
1995
|
await interrupted(runtime, call, "interrupted", `Tool ${call.name} was interrupted and may have partially run`, context);
|
|
1726
1996
|
}
|
|
1727
1997
|
},
|
|
1728
1998
|
abort: async (task, runtime, context) => {
|
|
1729
1999
|
const call = nestedCall(runtime, task.input);
|
|
2000
|
+
const intent = task.state.checkpoint;
|
|
2001
|
+
if (intent.phase === "parked" || intent.phase === "execute" && intent.resume !== undefined) {
|
|
2002
|
+
const agent = await runtime.agent(context);
|
|
2003
|
+
const tool = agent.callable.find((each) => each.name === call.name);
|
|
2004
|
+
await cancelParkedTool(runtime, tool, intent, context);
|
|
2005
|
+
}
|
|
1730
2006
|
await interrupted(runtime, call, "aborted", `Tool ${call.name} was aborted${task.state.checkpoint.phase === "execute" ? " and may have partially run" : ""}`, context);
|
|
1731
2007
|
}
|
|
1732
2008
|
});
|
|
1733
2009
|
}
|
|
2010
|
+
async function startAttempt(runtime, call, tool, agent, intent, context, wake) {
|
|
2011
|
+
await runtime.commit(async (tx) => {
|
|
2012
|
+
const doc = await tx.doc(InvocationDoc, runtime.taskId);
|
|
2013
|
+
await forwardCall(tx, doc.forwardingCellId, {
|
|
2014
|
+
callId: call.id,
|
|
2015
|
+
parentCallId: call.parent?.callId ?? call.id,
|
|
2016
|
+
name: call.name,
|
|
2017
|
+
arguments: intent.arguments,
|
|
2018
|
+
status: "running",
|
|
2019
|
+
result: null,
|
|
2020
|
+
omittedFields: []
|
|
2021
|
+
});
|
|
2022
|
+
return {
|
|
2023
|
+
status: "running",
|
|
2024
|
+
checkpoint: {
|
|
2025
|
+
...intent,
|
|
2026
|
+
phase: "execute",
|
|
2027
|
+
...wake === undefined ? {} : { resume: { wake } }
|
|
2028
|
+
}
|
|
2029
|
+
};
|
|
2030
|
+
}, context);
|
|
2031
|
+
await run(runtime, call, tool, intent, agent, context, wake);
|
|
2032
|
+
}
|
|
1734
2033
|
async function reject(runtime, call, result, agent, tool, context) {
|
|
1735
2034
|
await eachHook(agent, "afterTool", runtime, async (handler) => {
|
|
1736
2035
|
result = await handler(call, result, runtime, context) ?? result;
|
|
1737
2036
|
});
|
|
1738
2037
|
await settle(runtime, call, finishResult(tool, call.name, result), "completed", context);
|
|
1739
2038
|
}
|
|
1740
|
-
async function run(runtime, call, tool,
|
|
2039
|
+
async function run(runtime, call, tool, intent, agent, context, wake) {
|
|
1741
2040
|
let invocation;
|
|
1742
2041
|
let result;
|
|
1743
2042
|
let ending = "completed";
|
|
1744
2043
|
try {
|
|
1745
|
-
|
|
1746
|
-
|
|
2044
|
+
const previous = wake === undefined ? undefined : await runtime.snapshot(InvocationDoc, runtime.taskId, context);
|
|
2045
|
+
invocation = createInvocation(runtime, tool, context, {
|
|
2046
|
+
wake,
|
|
2047
|
+
checkpoint: intent.checkpoint,
|
|
2048
|
+
...previous === undefined ? {} : { progress: previous.result }
|
|
2049
|
+
});
|
|
2050
|
+
const returned = await tool.execute(intent.arguments, await invocation.executionApi(), context);
|
|
2051
|
+
if (returned.kind === undefined)
|
|
2052
|
+
result = returned;
|
|
2053
|
+
else {
|
|
2054
|
+
const reason = await parkTool(runtime, invocation, tool, intent.arguments, returned, context);
|
|
2055
|
+
if (reason === undefined)
|
|
2056
|
+
return;
|
|
2057
|
+
result = executionError("invalid_park", reason);
|
|
2058
|
+
ending = "failed";
|
|
2059
|
+
}
|
|
1747
2060
|
} catch (error) {
|
|
1748
2061
|
if (runtime.signal.aborted) {
|
|
1749
2062
|
await invocation?.stop(error);
|
|
@@ -1795,7 +2108,7 @@ function finishResult(tool, name, result) {
|
|
|
1795
2108
|
} else if (final.structuredOutput === undefined) {
|
|
1796
2109
|
if (!final.isError)
|
|
1797
2110
|
throw new Error(`Tool ${name} returned no structuredOutput`);
|
|
1798
|
-
} else if (!
|
|
2111
|
+
} else if (!compile2(tool.structuredOutputSchema).check(final.structuredOutput)) {
|
|
1799
2112
|
throw new Error(`Tool ${name} returned structuredOutput that does not match its schema`);
|
|
1800
2113
|
}
|
|
1801
2114
|
} catch (error) {
|
|
@@ -1844,9 +2157,11 @@ function providerProjection(surfaceTools) {
|
|
|
1844
2157
|
const conversation = await host.conversation(api.conversationId, context);
|
|
1845
2158
|
if (conversation === undefined)
|
|
1846
2159
|
throw new Error(`Conversation ${api.conversationId} is unavailable`);
|
|
1847
|
-
for (const tool of (await conversation.agent(context)).tools)
|
|
1848
|
-
|
|
2160
|
+
for (const tool of (await conversation.agent(context)).tools) {
|
|
2161
|
+
const contract = readToolContract(tool);
|
|
2162
|
+
if (contract.nativeOnly || contract.nestedHidden)
|
|
1849
2163
|
visible.add(tool.name);
|
|
2164
|
+
}
|
|
1850
2165
|
}
|
|
1851
2166
|
return { messages: projectToolSchemas(request.messages, visible) };
|
|
1852
2167
|
}
|
|
@@ -1855,7 +2170,7 @@ function providerProjection(surfaceTools) {
|
|
|
1855
2170
|
}
|
|
1856
2171
|
|
|
1857
2172
|
// packages/execution/src/wait-session.ts
|
|
1858
|
-
import { withoutAbortSignal as
|
|
2173
|
+
import { withoutAbortSignal as withoutAbortSignal4 } from "@earendil-works/chord/context";
|
|
1859
2174
|
|
|
1860
2175
|
// packages/execution/src/tool-value.ts
|
|
1861
2176
|
class NestedToolError extends Error {
|
|
@@ -1926,7 +2241,7 @@ async function recoverWaitSession(cellId, yieldTimeMs, maxTokens, api, context,
|
|
|
1926
2241
|
}, context);
|
|
1927
2242
|
let cancelling;
|
|
1928
2243
|
const abort = () => {
|
|
1929
|
-
cancelling ??= cancelTask(id,
|
|
2244
|
+
cancelling ??= cancelTask(id, withoutAbortSignal4(context));
|
|
1930
2245
|
cancelling.catch(() => {});
|
|
1931
2246
|
};
|
|
1932
2247
|
context.abortSignal?.addEventListener("abort", abort, { once: true });
|
|
@@ -2010,7 +2325,7 @@ function createCellCoordinator(options) {
|
|
|
2010
2325
|
if (driver.closed)
|
|
2011
2326
|
throw new Error("Execution host is closed");
|
|
2012
2327
|
assertSingleExecutionMode(await api.agent(context));
|
|
2013
|
-
const copied =
|
|
2328
|
+
const copied = copyJson12(input);
|
|
2014
2329
|
return api.commit(async (tx) => {
|
|
2015
2330
|
const isolatedLimit = options.isolatedConcurrency ?? 0;
|
|
2016
2331
|
const isolated = isolatedLimit > 0 && input["isolated"] === true;
|
|
@@ -2090,7 +2405,7 @@ function createCellCoordinator(options) {
|
|
|
2090
2405
|
if (yielding.consume()) {
|
|
2091
2406
|
return initial;
|
|
2092
2407
|
}
|
|
2093
|
-
const wait =
|
|
2408
|
+
const wait = withCancel2(context);
|
|
2094
2409
|
const timeout = new Error("Cell observation yielded");
|
|
2095
2410
|
const timer = setTimeout(() => wait.cancel(timeout), Math.min(yieldTimeMs, 2147483647));
|
|
2096
2411
|
try {
|
|
@@ -3278,7 +3593,7 @@ function createUpdates(write, context) {
|
|
|
3278
3593
|
}
|
|
3279
3594
|
|
|
3280
3595
|
// packages/code/src/cell-output.ts
|
|
3281
|
-
import { copyJson as
|
|
3596
|
+
import { copyJson as copyJson13 } from "@earendil-works/chord/json";
|
|
3282
3597
|
|
|
3283
3598
|
// packages/code/src/result.ts
|
|
3284
3599
|
function runtimeResult(response, maxTokens = 1e4) {
|
|
@@ -3526,7 +3841,7 @@ ${TRUNCATED_OUTPUT_NOTICE}`
|
|
|
3526
3841
|
...details !== null && typeof details === "object" && !Array.isArray(details) ? details : {},
|
|
3527
3842
|
cellId: observation.cellId,
|
|
3528
3843
|
...observation.forwardedToolCalls === undefined ? {} : {
|
|
3529
|
-
forwardedToolCalls:
|
|
3844
|
+
forwardedToolCalls: copyJson13(observation.forwardedToolCalls, {
|
|
3530
3845
|
omitUndefinedProperties: true
|
|
3531
3846
|
})
|
|
3532
3847
|
},
|
|
@@ -4427,19 +4742,21 @@ function toolBootstrap(tools, yieldMarker) {
|
|
|
4427
4742
|
tool.name,
|
|
4428
4743
|
`durable_tool_${index}`
|
|
4429
4744
|
]);
|
|
4430
|
-
const discovery = tools.map((tool) => ({
|
|
4745
|
+
const discovery = tools.filter((tool) => !tool.hidden).map((tool) => ({
|
|
4431
4746
|
name: tool.name,
|
|
4432
4747
|
description: tool.description
|
|
4433
4748
|
}));
|
|
4434
|
-
return `(()=>{const native=globalThis.tools;const registry=Object.create(null);for(const [name,wire] of ${JSON.stringify(entries)})registry[name]=native[wire];globalThis.tools=registry;globalThis.ALL_TOOLS=${JSON.stringify(discovery)};const emit=globalThis.notify;const yieldCell=globalThis.yield_control;globalThis.yield_control=()=>{emit(${JSON.stringify(yieldMarker)});return yieldCell();};})();`;
|
|
4749
|
+
return `(()=>{const native=globalThis.tools;const registry=Object.create(null);for(const [name,wire] of ${JSON.stringify(entries)})registry[name]=native[wire];globalThis.tools=registry;globalThis.ALL_TOOLS=${JSON.stringify(discovery)};(${installToolNamespacesSource})(registry,${JSON.stringify(namespaceDefinitions(tools))});const emit=globalThis.notify;const yieldCell=globalThis.yield_control;globalThis.yield_control=()=>{emit(${JSON.stringify(yieldMarker)});return yieldCell();};})();`;
|
|
4435
4750
|
}
|
|
4436
4751
|
|
|
4437
4752
|
// packages/code/src/runtime-tools.ts
|
|
4438
|
-
import { copyJson as
|
|
4753
|
+
import { copyJson as copyJson14 } from "@earendil-works/chord/json";
|
|
4439
4754
|
function runtimeTools(api, contracts, observation, context) {
|
|
4440
4755
|
const publish = () => api.publish(observation.result(), context);
|
|
4441
4756
|
const tools = api.registrations.map((registration, index) => ({
|
|
4442
4757
|
name: registration.name,
|
|
4758
|
+
hidden: contracts[index]?.nestedHidden === true || contracts[index]?.jsNamespace !== undefined,
|
|
4759
|
+
...contracts[index]?.nestedHidden || contracts[index]?.jsNamespace === undefined ? {} : { jsNamespace: contracts[index].jsNamespace },
|
|
4443
4760
|
description: contracts[index]?.help ?? registration.description,
|
|
4444
4761
|
inputSchema: contracts[index]?.inputSchema ?? registration.parameters,
|
|
4445
4762
|
invoke: async (input, signal, callId) => {
|
|
@@ -4447,7 +4764,7 @@ function runtimeTools(api, contracts, observation, context) {
|
|
|
4447
4764
|
const invoke = api.tools[registration.name];
|
|
4448
4765
|
if (!invoke)
|
|
4449
4766
|
throw new Error(`Tool ${registration.name} is unavailable`);
|
|
4450
|
-
const argumentsValue =
|
|
4767
|
+
const argumentsValue = copyJson14(input === undefined ? null : input);
|
|
4451
4768
|
const trace = observation.trace(callId, registration.name, argumentsValue);
|
|
4452
4769
|
await publish();
|
|
4453
4770
|
try {
|
|
@@ -5028,10 +5345,10 @@ function createCodeMode(options) {
|
|
|
5028
5345
|
tools: [exec, wait, ...shell.tools],
|
|
5029
5346
|
sections: [
|
|
5030
5347
|
section("code", (input) => {
|
|
5031
|
-
const usage = input.agent.callable.filter((tool) => tool.name !== "exec" && tool.name !== "wait").map(readToolContract).
|
|
5348
|
+
const usage = input.agent.callable.filter((tool) => tool.name !== "exec" && tool.name !== "wait").map(readToolContract).flatMap(jsToolPrompt).join(`
|
|
5032
5349
|
`);
|
|
5033
5350
|
return [
|
|
5034
|
-
|
|
5351
|
+
nestedToolDiscoveryGuidance,
|
|
5035
5352
|
'exec accepts JavaScript source with optional // @exec: {"yield_time_ms":30000,"max_output_tokens":10000}. Await work and emit with text(value), image(value), generatedImage(value), notify(value). tools contains ordinary registered tools. ALL_TOOLS lists callable contracts. store(key,value)/load(key) retain serializable values between cells. Cells have no filesystem, network or Node globals. Shell tools follow the conversation environment. Use wait for exec cells and tools.write_stdin for shell sessions.',
|
|
5036
5353
|
usage
|
|
5037
5354
|
].filter(Boolean).join(`
|