pi-dent-agent 0.2.3 → 0.2.4
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/index.ts +5 -1
- package/lib/config.ts +59 -0
- package/lib/engine.ts +4 -1
- package/lib/script-render.ts +1 -1
- package/lib/script-runner.ts +70 -4
- package/lib/script-tool-calls.ts +116 -0
- package/lib/script-tool-log.ts +143 -0
- package/lib/script-tool-types.ts +258 -0
- package/lib/script-tool.ts +103 -9
- package/lib/script-worker.ts +92 -1
- package/lib/search-tool.ts +1 -1
- package/lib/tools.ts +13 -5
- package/node_modules/express-rate-limit/dist/index.cjs +6 -4
- package/node_modules/express-rate-limit/dist/index.mjs +6 -4
- package/node_modules/express-rate-limit/package.json +1 -1
- package/node_modules/jose/dist/webapi/jwks/remote.js +2 -2
- package/node_modules/jose/dist/webapi/jwt/encrypt.js +5 -8
- package/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +1 -1
- package/node_modules/jose/dist/webapi/lib/jwe_encrypt.js +2 -2
- package/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +1 -1
- package/node_modules/jose/dist/webapi/lib/key.js +2 -0
- package/node_modules/jose/package.json +1 -1
- package/node_modules/object-inspect/CHANGELOG.md +31 -0
- package/node_modules/object-inspect/index.js +326 -24
- package/node_modules/object-inspect/package.json +22 -13
- package/node_modules/object-inspect/readme.markdown +4 -1
- package/node_modules/object-inspect/stringWidth.js +68 -0
- package/node_modules/object-inspect/stringWidthRanges.js +38 -0
- package/package.json +1 -1
- package/node_modules/object-inspect/.eslintrc +0 -53
- package/node_modules/object-inspect/.nycrc +0 -13
- package/node_modules/object-inspect/example/all.js +0 -23
- package/node_modules/object-inspect/example/circular.js +0 -6
- package/node_modules/object-inspect/example/fn.js +0 -5
- package/node_modules/object-inspect/example/inspect.js +0 -10
- package/node_modules/object-inspect/test/bigint.js +0 -58
- package/node_modules/object-inspect/test/browser/dom.js +0 -15
- package/node_modules/object-inspect/test/circular.js +0 -16
- package/node_modules/object-inspect/test/deep.js +0 -12
- package/node_modules/object-inspect/test/element.js +0 -53
- package/node_modules/object-inspect/test/err.js +0 -48
- package/node_modules/object-inspect/test/fakes.js +0 -29
- package/node_modules/object-inspect/test/fn.js +0 -76
- package/node_modules/object-inspect/test/global.js +0 -17
- package/node_modules/object-inspect/test/has.js +0 -15
- package/node_modules/object-inspect/test/holes.js +0 -15
- package/node_modules/object-inspect/test/indent-option.js +0 -271
- package/node_modules/object-inspect/test/inspect.js +0 -139
- package/node_modules/object-inspect/test/lowbyte.js +0 -12
- package/node_modules/object-inspect/test/number.js +0 -58
- package/node_modules/object-inspect/test/quoteStyle.js +0 -26
- package/node_modules/object-inspect/test/toStringTag.js +0 -40
- package/node_modules/object-inspect/test/undef.js +0 -12
- package/node_modules/object-inspect/test/values.js +0 -261
- package/node_modules/object-inspect/test-core-js.js +0 -26
package/index.ts
CHANGED
|
@@ -35,6 +35,7 @@ import {
|
|
|
35
35
|
makeTaskTool,
|
|
36
36
|
} from "./lib/tools.ts";
|
|
37
37
|
import { makeScriptTool } from "./lib/script-tool.ts";
|
|
38
|
+
import { DEFAULT_TOOLS_ALLOW } from "./lib/script-tool-types.ts";
|
|
38
39
|
import { makeBashTool, readBashSettings } from "./lib/bash-tool.ts";
|
|
39
40
|
import { makeSearchTool, searchRuntime } from "./lib/search-tool.ts";
|
|
40
41
|
import { makeMarkdownTool, markdownRuntime } from "pi-dent-markdown";
|
|
@@ -52,7 +53,7 @@ import {
|
|
|
52
53
|
makeAskUserQuestionTool,
|
|
53
54
|
} from "./lib/ask-user-question-tool.ts";
|
|
54
55
|
import { readFileSync } from "node:fs";
|
|
55
|
-
import { parseFooter, parseTaskBrowser } from "./lib/config.ts";
|
|
56
|
+
import { parseFooter, parseScript, parseTaskBrowser } from "./lib/config.ts";
|
|
56
57
|
import { createFooterComponent } from "./lib/footer.ts";
|
|
57
58
|
import { TaskBrowserOverlay } from "./lib/task-browser.ts";
|
|
58
59
|
import { startTaskWidget, type TaskPaint, type TaskWidgetHandle } from "./lib/task-widget.ts";
|
|
@@ -724,6 +725,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
724
725
|
|
|
725
726
|
// Task browser (task-browser.md): the shortcut opens the overlay; the overlay closes itself on it.
|
|
726
727
|
const taskBrowserShortcut = parseTaskBrowser(boot.config).shortcut;
|
|
728
|
+
const scriptToolsAllow = parseScript(boot.config).toolsAllow ?? DEFAULT_TOOLS_ALLOW;
|
|
727
729
|
const toggleTaskBrowser = async (ctx: ExtensionContext): Promise<void> => {
|
|
728
730
|
if (closeTaskBrowser) {
|
|
729
731
|
closeTaskBrowser();
|
|
@@ -834,6 +836,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
834
836
|
hostProvider: () => currentHost,
|
|
835
837
|
cohortFor: (toolCallId) => cohorts.cohortFor(toolCallId),
|
|
836
838
|
agentDir: agentDirForHost,
|
|
839
|
+
// script-tool.md Section 8; its diagnostics are boot diagnostics.
|
|
840
|
+
toolsAllow: () => scriptToolsAllow,
|
|
837
841
|
}),
|
|
838
842
|
);
|
|
839
843
|
pi.registerTool(
|
package/lib/config.ts
CHANGED
|
@@ -26,6 +26,7 @@ export const SUPPORTED_ROOT_KEYS = [
|
|
|
26
26
|
"taskBrowser",
|
|
27
27
|
"footer",
|
|
28
28
|
"recapModel",
|
|
29
|
+
"script",
|
|
29
30
|
// Owned by pi-dent-terms (config-file.md, Section 2): pi-dent never validates it.
|
|
30
31
|
"terms",
|
|
31
32
|
] as const;
|
|
@@ -585,6 +586,64 @@ export function parseTaskBrowser(config: BootConfig): {
|
|
|
585
586
|
return out;
|
|
586
587
|
}
|
|
587
588
|
|
|
589
|
+
/**
|
|
590
|
+
* The `script` configuration (script-tool.md Section 8) with its diagnostics: the allow lists,
|
|
591
|
+
* `undefined` where the key is absent or ignored.
|
|
592
|
+
*/
|
|
593
|
+
export function parseScript(config: BootConfig): {
|
|
594
|
+
networkAllow: string[] | undefined;
|
|
595
|
+
toolsAllow: string[] | undefined;
|
|
596
|
+
diagnostics: string[];
|
|
597
|
+
} {
|
|
598
|
+
const out: {
|
|
599
|
+
networkAllow: string[] | undefined;
|
|
600
|
+
toolsAllow: string[] | undefined;
|
|
601
|
+
diagnostics: string[];
|
|
602
|
+
} = { networkAllow: undefined, toolsAllow: undefined, diagnostics: [] };
|
|
603
|
+
const at = (path: string[]): string => attributePath(config.layers, config.projectRoot, path);
|
|
604
|
+
/** The object at `path` when it is one; a diagnostic when it is present and is not. */
|
|
605
|
+
const object = (
|
|
606
|
+
value: unknown,
|
|
607
|
+
path: string[],
|
|
608
|
+
known: readonly string[],
|
|
609
|
+
): Record<string, unknown> | undefined => {
|
|
610
|
+
if (value === undefined) return undefined;
|
|
611
|
+
const name = path.join(".");
|
|
612
|
+
if (!isPlainObject(value)) {
|
|
613
|
+
out.diagnostics.push(`config: ${at(path)}: ${name} must be an object; ignored`);
|
|
614
|
+
return undefined;
|
|
615
|
+
}
|
|
616
|
+
const unknownKeys = Object.keys(value).filter((key) => !known.includes(key));
|
|
617
|
+
if (unknownKeys.length > 0) {
|
|
618
|
+
out.diagnostics.push(
|
|
619
|
+
`config: ${unknownKeysMessage(name, unknownKeys, (key) => at([...path, key]))}`,
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
return value;
|
|
623
|
+
};
|
|
624
|
+
const allow = (
|
|
625
|
+
parent: Record<string, unknown> | undefined,
|
|
626
|
+
path: string[],
|
|
627
|
+
): string[] | undefined => {
|
|
628
|
+
if (parent === undefined || !Object.hasOwn(parent, "allow")) return;
|
|
629
|
+
const value = parent.allow;
|
|
630
|
+
if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
|
|
631
|
+
return value.filter((entry): entry is string => typeof entry === "string");
|
|
632
|
+
}
|
|
633
|
+
const full = [...path, "allow"];
|
|
634
|
+
out.diagnostics.push(
|
|
635
|
+
`config: ${at(full)}: ${full.join(".")} must be an array of strings; ignored`,
|
|
636
|
+
);
|
|
637
|
+
};
|
|
638
|
+
const script = object(config.merged.script, ["script"], ["network", "tools"]);
|
|
639
|
+
if (script === undefined) return out;
|
|
640
|
+
const network = object(script.network, ["script", "network"], ["allow"]);
|
|
641
|
+
out.networkAllow = allow(network, ["script", "network"]);
|
|
642
|
+
const tools = object(script.tools, ["script", "tools"], ["allow"]);
|
|
643
|
+
out.toolsAllow = allow(tools, ["script", "tools"]);
|
|
644
|
+
return out;
|
|
645
|
+
}
|
|
646
|
+
|
|
588
647
|
/** The footer configuration (footer.md Section 1.1) with its diagnostics. */
|
|
589
648
|
export function parseFooter(config: BootConfig): { enabled: boolean; diagnostics: string[] } {
|
|
590
649
|
const raw = config.merged.footer;
|
package/lib/engine.ts
CHANGED
|
@@ -44,7 +44,7 @@ import {
|
|
|
44
44
|
} from "./catalogs.ts";
|
|
45
45
|
import { resolveCwdParam } from "./cwd-param.ts";
|
|
46
46
|
import { type PluginEntry, appendPluginContext, discoverPlugins } from "./plugins.ts";
|
|
47
|
-
import { type BootConfig, parseTaskBrowser, readConfig } from "./config.ts";
|
|
47
|
+
import { type BootConfig, parseScript, parseTaskBrowser, readConfig } from "./config.ts";
|
|
48
48
|
import type { CompactionSettings, HostSession } from "./host.ts";
|
|
49
49
|
import type { BillingService } from "./billing.ts";
|
|
50
50
|
import {
|
|
@@ -734,6 +734,9 @@ export function readBootSnapshot(cwd = process.cwd()): BootSnapshot {
|
|
|
734
734
|
for (const message of parseTaskBrowser(config).diagnostics) {
|
|
735
735
|
diagnostics.push({ level: "warning", message });
|
|
736
736
|
}
|
|
737
|
+
for (const message of parseScript(config).diagnostics) {
|
|
738
|
+
diagnostics.push({ level: "warning", message });
|
|
739
|
+
}
|
|
737
740
|
for (const message of parsedModelGuidance(config).diagnostics) {
|
|
738
741
|
diagnostics.push({ level: "warning", message });
|
|
739
742
|
}
|
package/lib/script-render.ts
CHANGED
|
@@ -36,7 +36,7 @@ function isPlainObject(value: object): boolean {
|
|
|
36
36
|
return proto === Object.prototype || proto === null;
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
function isJsonCompatible(value: unknown, ancestors: Set<object> = new Set()): boolean {
|
|
39
|
+
export function isJsonCompatible(value: unknown, ancestors: Set<object> = new Set()): boolean {
|
|
40
40
|
if (value === null) return true;
|
|
41
41
|
if (typeof value === "boolean") return true;
|
|
42
42
|
if (typeof value === "number") return Number.isFinite(value);
|
package/lib/script-runner.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { Worker } from "node:worker_threads";
|
|
2
2
|
import type { ReturnValueRender } from "./script-render.ts";
|
|
3
|
+
import type { ToolCallReply } from "./script-tool-calls.ts";
|
|
4
|
+
import { toolDeclarations } from "./script-tool-types.ts";
|
|
3
5
|
import { applySessionTmp } from "./session-tmp.ts";
|
|
4
6
|
import { killTreeWindows, prefixBytes, signalGroup } from "./tool-common.ts";
|
|
5
|
-
import { errorCode } from "./util.ts";
|
|
7
|
+
import { errorCode, errorMessage } from "./util.ts";
|
|
6
8
|
import { typeStrippingOptions } from "./worker-options.ts";
|
|
7
9
|
|
|
8
10
|
/**
|
|
@@ -88,6 +90,18 @@ export interface ScriptRunRequest {
|
|
|
88
90
|
* kept (no `env` option).
|
|
89
91
|
*/
|
|
90
92
|
extraEnv?: Record<string, string>;
|
|
93
|
+
/** The tool functions (Section 10); absent binds none. */
|
|
94
|
+
tools?: ScriptRunTools;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The tool functions of a run (Section 10.3). */
|
|
98
|
+
export interface ScriptRunTools {
|
|
99
|
+
/** Bound tool names, in declaration order. */
|
|
100
|
+
names: string[];
|
|
101
|
+
/** The tool declarations (Section 10.2), returned by `dent.toolTypes()`. */
|
|
102
|
+
declarations: string;
|
|
103
|
+
/** Runs one nested call; the signal aborts at settlement. */
|
|
104
|
+
call: (name: string, args: unknown, signal: AbortSignal) => Promise<ToolCallReply>;
|
|
91
105
|
}
|
|
92
106
|
|
|
93
107
|
export interface ScriptRunResult {
|
|
@@ -110,6 +124,13 @@ export interface ScriptRunResult {
|
|
|
110
124
|
export interface ScriptRunHandle {
|
|
111
125
|
promise: Promise<ScriptRunResult>;
|
|
112
126
|
cancel: (reason: "killed" | "aborted") => void;
|
|
127
|
+
/** When the run started (Section 6), in ms since the epoch; absent when none started. */
|
|
128
|
+
startedAt: () => number | undefined;
|
|
129
|
+
/**
|
|
130
|
+
* Append one line of the host's own to the run's stderr, until the result is built
|
|
131
|
+
* (the tool log's write failure, Section 10.4). Returns `false` when it is too late.
|
|
132
|
+
*/
|
|
133
|
+
stderrLine: (line: string) => boolean;
|
|
113
134
|
}
|
|
114
135
|
|
|
115
136
|
/** Signal one spawned child by its process ID (Windows: its tree with taskkill /T /F). */
|
|
@@ -140,9 +161,12 @@ function groupIsEmpty(pid: number): boolean {
|
|
|
140
161
|
|
|
141
162
|
export function runScript(req: ScriptRunRequest): ScriptRunHandle {
|
|
142
163
|
let cancel: (reason: "killed" | "aborted") => void = () => {};
|
|
164
|
+
/** The run's start; absent until the run is created. */
|
|
165
|
+
let started: number | undefined;
|
|
166
|
+
let stderrLine: (line: string) => boolean = () => false;
|
|
143
167
|
const promise = new Promise<ScriptRunResult>((resolve) => {
|
|
144
|
-
/**
|
|
145
|
-
let
|
|
168
|
+
/** Whether the result was built: nothing reaches the capture after it. */
|
|
169
|
+
let finished = false;
|
|
146
170
|
/** When the run settled: its end (Section 5), before the termination drain. */
|
|
147
171
|
let ended: number | undefined;
|
|
148
172
|
const capture: StreamCapture = {
|
|
@@ -160,8 +184,11 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
|
|
|
160
184
|
const groupPids = new Set<number>();
|
|
161
185
|
let worker: Worker | undefined;
|
|
162
186
|
let timer: NodeJS.Timeout | undefined;
|
|
187
|
+
/** Signals of the nested calls still running (Section 10.3). */
|
|
188
|
+
const nestedCalls = new Set<AbortController>();
|
|
163
189
|
|
|
164
190
|
const finish = (partial: Partial<ScriptRunResult>) => {
|
|
191
|
+
finished = true;
|
|
165
192
|
void worker?.terminate();
|
|
166
193
|
resolve({
|
|
167
194
|
stdout: capture.text.stdout,
|
|
@@ -230,6 +257,9 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
|
|
|
230
257
|
ended = Date.now();
|
|
231
258
|
if (timer) clearTimeout(timer);
|
|
232
259
|
req.signal?.removeEventListener("abort", onAbort);
|
|
260
|
+
// Section 10.3: nested calls still running are aborted, not awaited, and their outcomes dropped.
|
|
261
|
+
for (const controller of nestedCalls) controller.abort();
|
|
262
|
+
nestedCalls.clear();
|
|
233
263
|
settleTree(partial);
|
|
234
264
|
};
|
|
235
265
|
|
|
@@ -243,6 +273,13 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
|
|
|
243
273
|
}
|
|
244
274
|
|
|
245
275
|
cancel = (reason) => settle({ exitReason: reason });
|
|
276
|
+
stderrLine = (line) => {
|
|
277
|
+
if (finished) return false;
|
|
278
|
+
const text = capture.text.stderr;
|
|
279
|
+
const lead = text !== "" && !text.endsWith("\n") ? "\n" : "";
|
|
280
|
+
appendStream(capture, "stderr", `${lead}${line}\n`, req.onOutput);
|
|
281
|
+
return true;
|
|
282
|
+
};
|
|
246
283
|
|
|
247
284
|
// The worker's process.env: the host's, the caller's extra env merged over it, then the
|
|
248
285
|
// session tmp folder (bash-tool.md, Section 3).
|
|
@@ -257,6 +294,8 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
|
|
|
257
294
|
cwd: req.cwd,
|
|
258
295
|
input: req.input,
|
|
259
296
|
aliases: req.aliases,
|
|
297
|
+
toolNames: req.tools?.names ?? [],
|
|
298
|
+
toolTypes: req.tools?.declarations ?? toolDeclarations({ bound: [], unbound: [] }),
|
|
260
299
|
},
|
|
261
300
|
env: workerEnv,
|
|
262
301
|
});
|
|
@@ -293,6 +332,9 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
|
|
|
293
332
|
// is free to be reused: it is no longer part of the tree (Section 6).
|
|
294
333
|
if (groupPids.has(msg.pid) && groupIsEmpty(msg.pid)) groupPids.delete(msg.pid);
|
|
295
334
|
break;
|
|
335
|
+
case "tool-call":
|
|
336
|
+
if (!settled) startNestedCall(msg.id, String(msg.name), msg.args);
|
|
337
|
+
break;
|
|
296
338
|
case "exit-called":
|
|
297
339
|
settle({ exitReason: "exit-called", exitCode: msg.code ?? 0 });
|
|
298
340
|
break;
|
|
@@ -320,6 +362,30 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
|
|
|
320
362
|
}
|
|
321
363
|
});
|
|
322
364
|
|
|
365
|
+
/** Section 10.3, step 2 onward: run the nested call and post its reply unless the run settled. */
|
|
366
|
+
function startNestedCall(id: unknown, name: string, args: unknown): void {
|
|
367
|
+
const controller = new AbortController();
|
|
368
|
+
nestedCalls.add(controller);
|
|
369
|
+
const call = req.tools?.call;
|
|
370
|
+
const pending: Promise<ToolCallReply> =
|
|
371
|
+
call === undefined || !req.tools?.names.includes(name)
|
|
372
|
+
? Promise.resolve({
|
|
373
|
+
ok: false,
|
|
374
|
+
error: { name: "Error", message: `tool ${name} is not bound` },
|
|
375
|
+
})
|
|
376
|
+
: call(name, args, controller.signal);
|
|
377
|
+
void pending
|
|
378
|
+
.catch((error: unknown): ToolCallReply => ({
|
|
379
|
+
ok: false,
|
|
380
|
+
error: { name: "Error", message: errorMessage(error) },
|
|
381
|
+
}))
|
|
382
|
+
.then((reply) => {
|
|
383
|
+
nestedCalls.delete(controller);
|
|
384
|
+
if (settled) return;
|
|
385
|
+
worker?.postMessage({ type: "tool-result", id, reply });
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
323
389
|
worker.on("error", (err: unknown) => {
|
|
324
390
|
// A worker that throws a non-Error value passes it through raw; normalise
|
|
325
391
|
// before reading name/message/stack (Section 3: strings).
|
|
@@ -348,5 +414,5 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
|
|
|
348
414
|
}
|
|
349
415
|
});
|
|
350
416
|
});
|
|
351
|
-
return { promise, cancel };
|
|
417
|
+
return { promise, cancel, startedAt: () => started, stderrLine: (line) => stderrLine(line) };
|
|
352
418
|
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import Schema from "typebox/schema";
|
|
2
|
+
import type { CallableTool } from "./script-tool-types.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A nested call of a tool function, host side (specs/script-tool.md Section 10.3, steps 2 to 4).
|
|
6
|
+
* Step 1 runs in the script worker.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** A `ToolContent` part (Section 10.2). */
|
|
10
|
+
export type ToolCallContent =
|
|
11
|
+
| { type: "text"; text: string }
|
|
12
|
+
| { type: "image"; data: string; mimeType: string }
|
|
13
|
+
| { type: "other"; kind: string };
|
|
14
|
+
|
|
15
|
+
/** The resolved value of a tool function, before the worker freezes it (Section 10.3). */
|
|
16
|
+
export interface ToolCallValue {
|
|
17
|
+
text: string;
|
|
18
|
+
content: ToolCallContent[];
|
|
19
|
+
details: unknown;
|
|
20
|
+
structured: unknown;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type ToolCallReply =
|
|
24
|
+
| { ok: true; value: ToolCallValue }
|
|
25
|
+
| { ok: false; error: { name: string; message: string } };
|
|
26
|
+
|
|
27
|
+
/** The host's outcome of a nested call, as `ctx.executeTool` resolves it. */
|
|
28
|
+
export interface NestedCallOutcome {
|
|
29
|
+
result: { content: readonly unknown[]; details?: unknown; structuredContent?: unknown };
|
|
30
|
+
isError: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type ExecuteTool = (
|
|
34
|
+
name: string,
|
|
35
|
+
args: unknown,
|
|
36
|
+
options: { signal: AbortSignal },
|
|
37
|
+
) => Promise<NestedCallOutcome>;
|
|
38
|
+
|
|
39
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
40
|
+
return typeof value === "object" && value !== null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A content part as a `ToolContent` (Section 10.3): text, image, or `other` naming its type. */
|
|
44
|
+
function contentPart(part: unknown): ToolCallContent {
|
|
45
|
+
if (!isRecord(part)) return { type: "other", kind: "" };
|
|
46
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
47
|
+
return { type: "text", text: part.text };
|
|
48
|
+
}
|
|
49
|
+
if (part.type === "image" && typeof part.data === "string" && typeof part.mimeType === "string") {
|
|
50
|
+
return { type: "image", data: part.data, mimeType: part.mimeType };
|
|
51
|
+
}
|
|
52
|
+
return { type: "other", kind: typeof part.type === "string" ? part.type : "" };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** `details` through a JSON round trip; `undefined` when it does not survive one (Section 10.3). */
|
|
56
|
+
function jsonDetails(details: unknown): unknown {
|
|
57
|
+
if (details === undefined) return undefined;
|
|
58
|
+
let json: string | undefined;
|
|
59
|
+
try {
|
|
60
|
+
json = JSON.stringify(details);
|
|
61
|
+
} catch {
|
|
62
|
+
// Section 10.3: details that JSON.stringify rejects become undefined.
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
return json === undefined ? undefined : JSON.parse(json);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Whether `value` validates against a JSON Schema; a schema the validator rejects matches nothing. */
|
|
69
|
+
function validates(schema: unknown, value: unknown): boolean {
|
|
70
|
+
if (typeof schema !== "boolean" && (typeof schema !== "object" || schema === null)) return false;
|
|
71
|
+
try {
|
|
72
|
+
return Schema.Check(schema, value);
|
|
73
|
+
} catch {
|
|
74
|
+
// The mismatch rejection reports it to the script (Section 10.3, step 3).
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Run one nested call and settle it per Section 10.3, steps 2 to 4. */
|
|
80
|
+
export async function callBoundTool(
|
|
81
|
+
tool: CallableTool,
|
|
82
|
+
args: unknown,
|
|
83
|
+
executeTool: ExecuteTool,
|
|
84
|
+
signal: AbortSignal,
|
|
85
|
+
): Promise<ToolCallReply> {
|
|
86
|
+
const outcome = await executeTool(tool.name, args, { signal });
|
|
87
|
+
const content = outcome.result.content.map(contentPart);
|
|
88
|
+
const text = content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
|
|
89
|
+
if (outcome.isError) {
|
|
90
|
+
return {
|
|
91
|
+
ok: false,
|
|
92
|
+
error: { name: "ToolError", message: text === "" ? `tool ${tool.name} failed` : text },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const structured = outcome.result.structuredContent;
|
|
96
|
+
if (tool.outputSchema !== undefined) {
|
|
97
|
+
if (structured === undefined || !validates(tool.outputSchema, structured)) {
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
error: {
|
|
101
|
+
name: "Error",
|
|
102
|
+
message: `tool ${tool.name} returned structured content that does not match its output schema`,
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
ok: true,
|
|
109
|
+
value: {
|
|
110
|
+
text,
|
|
111
|
+
content,
|
|
112
|
+
details: jsonDetails(outcome.result.details),
|
|
113
|
+
structured: tool.outputSchema === undefined ? undefined : structured,
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { errorMessage, safeName } from "./util.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The tool log of a `Script` run (specs/script-tool.md Section 10.4): a session file in the
|
|
7
|
+
* invoking session's agent directory recording the run's source and every nested call, so that
|
|
8
|
+
* `Search` reads it as a member of the session tree. Lines are appended synchronously, in event
|
|
9
|
+
* order; a write failure is reported once on the run's stderr and ends the log.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The tool log of `taskId` in `agentDir`: `<agentDir>/script-<safeTaskId>.jsonl`. */
|
|
13
|
+
export function toolLogPathFor(agentDir: string, taskId: string): string {
|
|
14
|
+
return join(agentDir, `script-${safeName(taskId)}.jsonl`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The outcome of a nested call as the host returned it. */
|
|
18
|
+
export interface LoggedOutcome {
|
|
19
|
+
content: unknown;
|
|
20
|
+
details?: unknown;
|
|
21
|
+
isError: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ToolLogOptions {
|
|
25
|
+
agentDir: string;
|
|
26
|
+
taskId: string;
|
|
27
|
+
/** The run's resolved `cwd`. */
|
|
28
|
+
cwd: string;
|
|
29
|
+
/** The row's `code`. */
|
|
30
|
+
source: string;
|
|
31
|
+
/** The run's start, in ms since the epoch. */
|
|
32
|
+
runStart: () => number;
|
|
33
|
+
/** Append one line to the run's stderr. */
|
|
34
|
+
reportFailure: (line: string) => void;
|
|
35
|
+
now?: () => number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const ABORTED_CONTENT = [{ type: "text", text: "aborted: the script run settled" }];
|
|
39
|
+
|
|
40
|
+
export class ScriptToolLog {
|
|
41
|
+
readonly path: string;
|
|
42
|
+
/** Nested calls started, whether or not the log could be written. */
|
|
43
|
+
calls = 0;
|
|
44
|
+
private readonly options: ToolLogOptions;
|
|
45
|
+
private state: "none" | "open" | "failed" = "none";
|
|
46
|
+
private created = false;
|
|
47
|
+
private entries = 0;
|
|
48
|
+
private lastId: string | null = null;
|
|
49
|
+
/** Calls started and not yet logged as settled: call ID to tool name. */
|
|
50
|
+
private readonly open = new Map<string, string>();
|
|
51
|
+
|
|
52
|
+
constructor(options: ToolLogOptions) {
|
|
53
|
+
this.options = options;
|
|
54
|
+
this.path = toolLogPathFor(options.agentDir, options.taskId);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The path for `details.toolLogPath`: present exactly when the log was created. */
|
|
58
|
+
get createdPath(): string | undefined {
|
|
59
|
+
return this.created ? this.path : undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Record the start of a nested call, creating the log at the first; returns its call ID. */
|
|
63
|
+
start(name: string, args: unknown): string {
|
|
64
|
+
this.calls++;
|
|
65
|
+
const callId = `call-${this.calls}`;
|
|
66
|
+
this.open.set(callId, name);
|
|
67
|
+
if (this.state === "none") this.create();
|
|
68
|
+
this.append({
|
|
69
|
+
role: "assistant",
|
|
70
|
+
content: [{ type: "toolCall", id: callId, name, arguments: args }],
|
|
71
|
+
});
|
|
72
|
+
return callId;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Record a nested call's settlement; a call already logged as settled is left alone. */
|
|
76
|
+
settle(callId: string, outcome: LoggedOutcome): void {
|
|
77
|
+
const name = this.open.get(callId);
|
|
78
|
+
if (name === undefined) return;
|
|
79
|
+
this.open.delete(callId);
|
|
80
|
+
this.append({
|
|
81
|
+
role: "toolResult",
|
|
82
|
+
toolCallId: callId,
|
|
83
|
+
toolName: name,
|
|
84
|
+
content: outcome.content,
|
|
85
|
+
details: outcome.details,
|
|
86
|
+
isError: outcome.isError,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Record a call still running when the run settles as aborted at this moment. */
|
|
91
|
+
abort(callId: string): void {
|
|
92
|
+
this.settle(callId, { content: ABORTED_CONTENT, isError: true });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
private timestamp(): string {
|
|
96
|
+
return new Date(this.options.now?.() ?? Date.now()).toISOString();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private create(): void {
|
|
100
|
+
const { agentDir, taskId, cwd, source, runStart } = this.options;
|
|
101
|
+
const header = {
|
|
102
|
+
type: "session",
|
|
103
|
+
id: taskId,
|
|
104
|
+
timestamp: new Date(runStart()).toISOString(),
|
|
105
|
+
cwd,
|
|
106
|
+
};
|
|
107
|
+
try {
|
|
108
|
+
mkdirSync(agentDir, { recursive: true });
|
|
109
|
+
writeFileSync(this.path, `${JSON.stringify(header)}\n`);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
this.fail(error);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
this.created = true;
|
|
115
|
+
this.state = "open";
|
|
116
|
+
this.append({ role: "user", content: source });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private append(message: Record<string, unknown>): void {
|
|
120
|
+
if (this.state !== "open") return;
|
|
121
|
+
const id = `entry-${this.entries + 1}`;
|
|
122
|
+
const entry = {
|
|
123
|
+
type: "message",
|
|
124
|
+
id,
|
|
125
|
+
parentId: this.lastId,
|
|
126
|
+
timestamp: this.timestamp(),
|
|
127
|
+
message,
|
|
128
|
+
};
|
|
129
|
+
try {
|
|
130
|
+
appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
this.fail(error);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
this.entries++;
|
|
136
|
+
this.lastId = id;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private fail(error: unknown): void {
|
|
140
|
+
this.state = "failed";
|
|
141
|
+
this.options.reportFailure(`pi-dent: tool log write failed: ${errorMessage(error)}`);
|
|
142
|
+
}
|
|
143
|
+
}
|