buckyos 0.7.169 → 0.7.175
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/cli/core/app.ts +2 -0
- package/cli/core/argv.ts +45 -239
- package/cli/core/command.ts +3 -35
- package/cli/dist/cli.mjs +2151 -673
- package/cli/dist/cli.mjs.map +1 -1
- package/cli/modules/agent.ts +3 -1
- package/cli/modules/app.ts +13 -2
- package/cli/modules/pikg.ts +70 -1
- package/cli/modules/runtime.ts +497 -0
- package/cli/modules/skill.ts +583 -161
- package/cli/modules/skill_lint.ts +462 -0
- package/cli/version.ts +1 -1
- package/dist/account-7a7bde6f.mjs +105 -0
- package/dist/account-7a7bde6f.mjs.map +1 -0
- package/dist/account-b12ac6b9.js +2 -0
- package/dist/account-b12ac6b9.js.map +1 -0
- package/dist/aicc-67851c41.mjs +582 -0
- package/dist/aicc-67851c41.mjs.map +1 -0
- package/dist/aicc-ccb36ef7.js +2 -0
- package/dist/aicc-ccb36ef7.js.map +1 -0
- package/dist/app-frame.cjs +1 -1
- package/dist/app-frame.cjs.map +1 -1
- package/dist/app-frame.mjs +1 -0
- package/dist/app-frame.mjs.map +1 -1
- package/dist/browser.cjs +1 -1
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.ts +3 -1
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.mjs +223 -212
- package/dist/browser.mjs.map +1 -1
- package/dist/content.cjs +1 -1
- package/dist/content.cjs.map +1 -1
- package/dist/content.d.ts +2 -1
- package/dist/content.d.ts.map +1 -1
- package/dist/content.mjs +32 -167
- package/dist/content.mjs.map +1 -1
- package/dist/content_mime-dc80d960.js +2 -0
- package/dist/content_mime-dc80d960.js.map +1 -0
- package/dist/content_mime-e42d5f8d.mjs +335 -0
- package/dist/content_mime-e42d5f8d.mjs.map +1 -0
- package/dist/content_mime.d.ts +18 -0
- package/dist/content_mime.d.ts.map +1 -1
- package/dist/did_object_client-6a1b108a.js +2 -0
- package/dist/did_object_client-6a1b108a.js.map +1 -0
- package/dist/did_object_client-7fa36f90.mjs +87 -0
- package/dist/did_object_client-7fa36f90.mjs.map +1 -0
- package/dist/did_object_client.d.ts +39 -0
- package/dist/did_object_client.d.ts.map +1 -0
- package/dist/{executor_client-a32bc377.mjs → executor_client-c620d25c.mjs} +1794 -844
- package/dist/executor_client-c620d25c.mjs.map +1 -0
- package/dist/executor_client-d4439d54.js +13 -0
- package/dist/executor_client-d4439d54.js.map +1 -0
- package/dist/executor_client.d.ts +129 -0
- package/dist/executor_client.d.ts.map +1 -1
- package/dist/file_meta.d.ts +26 -0
- package/dist/file_meta.d.ts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +228 -217
- package/dist/index.mjs.map +1 -1
- package/dist/internal/command_args.d.ts +67 -0
- package/dist/internal/command_args.d.ts.map +1 -0
- package/dist/krpc_client-26c2dc8b.js +2 -0
- package/dist/krpc_client-26c2dc8b.js.map +1 -0
- package/dist/krpc_client-673448e5.mjs +173 -0
- package/dist/krpc_client-673448e5.mjs.map +1 -0
- package/dist/krpc_client.d.ts +5 -1
- package/dist/krpc_client.d.ts.map +1 -1
- package/dist/msg_center_client.d.ts +2 -1
- package/dist/msg_center_client.d.ts.map +1 -1
- package/dist/namelib.d.ts.map +1 -1
- package/dist/ndm_client.d.ts +7 -0
- package/dist/ndm_client.d.ts.map +1 -1
- package/dist/ndn.d.ts +3 -0
- package/dist/ndn.d.ts.map +1 -0
- package/dist/{namelib-b41b10cc.mjs → ndn_types-0fac2499.mjs} +3096 -2816
- package/dist/ndn_types-0fac2499.mjs.map +1 -0
- package/dist/ndn_types-5b138882.js +2 -0
- package/dist/ndn_types-5b138882.js.map +1 -0
- package/dist/ndn_types.d.ts +268 -16
- package/dist/ndn_types.d.ts.map +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/node.mjs +220 -212
- package/dist/node.mjs.map +1 -1
- package/dist/object_url-8fb5a7bf.js +2 -0
- package/dist/object_url-8fb5a7bf.js.map +1 -0
- package/dist/object_url-f72c1704.mjs +412 -0
- package/dist/object_url-f72c1704.mjs.map +1 -0
- package/dist/openai-ae2978de.mjs +163 -0
- package/dist/openai-ae2978de.mjs.map +1 -0
- package/dist/openai-f560d518.js +2 -0
- package/dist/openai-f560d518.js.map +1 -0
- package/dist/provision.cjs +6 -6
- package/dist/provision.cjs.map +1 -1
- package/dist/provision.d.ts +1 -2
- package/dist/provision.d.ts.map +1 -1
- package/dist/provision.mjs +4 -31
- package/dist/provision.mjs.map +1 -1
- package/dist/repo_client.d.ts +2 -1
- package/dist/repo_client.d.ts.map +1 -1
- package/dist/site_manager-11a7a468.mjs +6410 -0
- package/dist/site_manager-11a7a468.mjs.map +1 -0
- package/dist/site_manager-334b1a51.js +2 -0
- package/dist/site_manager-334b1a51.js.map +1 -0
- package/dist/{tus_client-4f7254e9.js → tus_client-809c90ab.js} +2 -2
- package/dist/{tus_client-4f7254e9.js.map → tus_client-809c90ab.js.map} +1 -1
- package/dist/{tus_client-04080b1e.mjs → tus_client-893a3287.mjs} +2 -2
- package/dist/{tus_client-04080b1e.mjs.map → tus_client-893a3287.mjs.map} +1 -1
- package/dist/xllm/core/action_parser.d.ts +15 -0
- package/dist/xllm/core/action_parser.d.ts.map +1 -0
- package/dist/xllm/core/behavior_loop.d.ts +20 -0
- package/dist/xllm/core/behavior_loop.d.ts.map +1 -0
- package/dist/xllm/core/behavior_result.d.ts +11 -0
- package/dist/xllm/core/behavior_result.d.ts.map +1 -0
- package/dist/xllm/core/config.d.ts +62 -0
- package/dist/xllm/core/config.d.ts.map +1 -0
- package/dist/xllm/core/context_window.d.ts +15 -0
- package/dist/xllm/core/context_window.d.ts.map +1 -0
- package/dist/xllm/core/deps.d.ts +97 -0
- package/dist/xllm/core/deps.d.ts.map +1 -0
- package/dist/xllm/core/errors.d.ts +94 -0
- package/dist/xllm/core/errors.d.ts.map +1 -0
- package/dist/xllm/core/interrupt.d.ts +31 -0
- package/dist/xllm/core/interrupt.d.ts.map +1 -0
- package/dist/xllm/core/json.d.ts +11 -0
- package/dist/xllm/core/json.d.ts.map +1 -0
- package/dist/xllm/core/json_check.d.ts +17 -0
- package/dist/xllm/core/json_check.d.ts.map +1 -0
- package/dist/xllm/core/loop.d.ts +135 -0
- package/dist/xllm/core/loop.d.ts.map +1 -0
- package/dist/xllm/core/messages.d.ts +18 -0
- package/dist/xllm/core/messages.d.ts.map +1 -0
- package/dist/xllm/core/observer.d.ts +14 -0
- package/dist/xllm/core/observer.d.ts.map +1 -0
- package/dist/xllm/core/open_runtime.d.ts +22 -0
- package/dist/xllm/core/open_runtime.d.ts.map +1 -0
- package/dist/xllm/core/prepare.d.ts +54 -0
- package/dist/xllm/core/prepare.d.ts.map +1 -0
- package/dist/xllm/core/prompt.d.ts +40 -0
- package/dist/xllm/core/prompt.d.ts.map +1 -0
- package/dist/xllm/core/protocol.d.ts +15 -0
- package/dist/xllm/core/protocol.d.ts.map +1 -0
- package/dist/xllm/core/result.d.ts +12 -0
- package/dist/xllm/core/result.d.ts.map +1 -0
- package/dist/xllm/core/run.d.ts +198 -0
- package/dist/xllm/core/run.d.ts.map +1 -0
- package/dist/xllm/core/rust_text.d.ts +20 -0
- package/dist/xllm/core/rust_text.d.ts.map +1 -0
- package/dist/xllm/core/site_policy.d.ts +5 -0
- package/dist/xllm/core/site_policy.d.ts.map +1 -0
- package/dist/xllm/core/store.d.ts +60 -0
- package/dist/xllm/core/store.d.ts.map +1 -0
- package/dist/xllm/core/suspension.d.ts +13 -0
- package/dist/xllm/core/suspension.d.ts.map +1 -0
- package/dist/xllm/core/tokenizer.d.ts +8 -0
- package/dist/xllm/core/tokenizer.d.ts.map +1 -0
- package/dist/xllm/core/types.d.ts +826 -0
- package/dist/xllm/core/types.d.ts.map +1 -0
- package/dist/xllm/core/xml.d.ts +19 -0
- package/dist/xllm/core/xml.d.ts.map +1 -0
- package/dist/xllm/dev/openai.d.ts +17 -0
- package/dist/xllm/dev/openai.d.ts.map +1 -0
- package/dist/xllm/dev/scripted.d.ts +46 -0
- package/dist/xllm/dev/scripted.d.ts.map +1 -0
- package/dist/xllm/dev.d.ts +5 -0
- package/dist/xllm/dev.d.ts.map +1 -0
- package/dist/xllm/hosts/browser/store.d.ts +41 -0
- package/dist/xllm/hosts/browser/store.d.ts.map +1 -0
- package/dist/xllm/hosts/deno/deno_api.d.ts +103 -0
- package/dist/xllm/hosts/deno/deno_api.d.ts.map +1 -0
- package/dist/xllm/hosts/deno/identity.d.ts +29 -0
- package/dist/xllm/hosts/deno/identity.d.ts.map +1 -0
- package/dist/xllm/hosts/deno/index.d.ts +47 -0
- package/dist/xllm/hosts/deno/index.d.ts.map +1 -0
- package/dist/xllm/hosts/deno/native_runtime.d.ts +93 -0
- package/dist/xllm/hosts/deno/native_runtime.d.ts.map +1 -0
- package/dist/xllm/hosts/deno/native_tools.d.ts +105 -0
- package/dist/xllm/hosts/deno/native_tools.d.ts.map +1 -0
- package/dist/xllm/hosts/deno/provider.d.ts +13 -0
- package/dist/xllm/hosts/deno/provider.d.ts.map +1 -0
- package/dist/xllm/hosts/deno/store.d.ts +60 -0
- package/dist/xllm/hosts/deno/store.d.ts.map +1 -0
- package/dist/xllm/index.d.ts +48 -0
- package/dist/xllm/index.d.ts.map +1 -0
- package/dist/xllm/providers/aicc.d.ts +22 -0
- package/dist/xllm/providers/aicc.d.ts.map +1 -0
- package/dist/xllm/providers/timeout.d.ts +12 -0
- package/dist/xllm/providers/timeout.d.ts.map +1 -0
- package/dist/xllm/runtime/compress.d.ts +149 -0
- package/dist/xllm/runtime/compress.d.ts.map +1 -0
- package/dist/xllm/runtime/did_object_resources.d.ts +21 -0
- package/dist/xllm/runtime/did_object_resources.d.ts.map +1 -0
- package/dist/xllm/runtime/hints.d.ts +23 -0
- package/dist/xllm/runtime/hints.d.ts.map +1 -0
- package/dist/xllm/runtime/site.d.ts +22 -0
- package/dist/xllm/runtime/site.d.ts.map +1 -0
- package/dist/xllm/runtime/site_manager.d.ts +38 -0
- package/dist/xllm/runtime/site_manager.d.ts.map +1 -0
- package/dist/xllm/runtime/site_tools.d.ts +76 -0
- package/dist/xllm/runtime/site_tools.d.ts.map +1 -0
- package/dist/xllm/runtime/step_renderer.d.ts +54 -0
- package/dist/xllm/runtime/step_renderer.d.ts.map +1 -0
- package/dist/xllm/runtime/task_model.d.ts +64 -0
- package/dist/xllm/runtime/task_model.d.ts.map +1 -0
- package/dist/xllm/runtime/tool_result.d.ts +39 -0
- package/dist/xllm/runtime/tool_result.d.ts.map +1 -0
- package/dist/xllm/runtime/types.d.ts +99 -0
- package/dist/xllm/runtime/types.d.ts.map +1 -0
- package/dist/xllm.cjs +2 -0
- package/dist/xllm.cjs.map +1 -0
- package/dist/xllm.mjs +1167 -0
- package/dist/xllm.mjs.map +1 -0
- package/dist/xllm_deno.cjs +2 -0
- package/dist/xllm_deno.cjs.map +1 -0
- package/dist/xllm_deno.mjs +2487 -0
- package/dist/xllm_deno.mjs.map +1 -0
- package/dist/xllm_dev.cjs +2 -0
- package/dist/xllm_dev.cjs.map +1 -0
- package/dist/xllm_dev.mjs +70 -0
- package/dist/xllm_dev.mjs.map +1 -0
- package/package.json +22 -1
- package/src/internal/command_args.ts +268 -0
- package/dist/executor_client-a32bc377.mjs.map +0 -1
- package/dist/executor_client-e026942b.js +0 -13
- package/dist/executor_client-e026942b.js.map +0 -1
- package/dist/namelib-b41b10cc.mjs.map +0 -1
- package/dist/namelib-f8ff0045.js +0 -2
- package/dist/namelib-f8ff0045.js.map +0 -1
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { JsonValue, Observation } from '../core/types';
|
|
2
|
+
export declare const MAX_IN_TOOL_WAIT_MS: number;
|
|
3
|
+
export declare const DEFAULT_TASK_WAIT_MS = 25000;
|
|
4
|
+
export interface TaskResult {
|
|
5
|
+
success: boolean;
|
|
6
|
+
output: string;
|
|
7
|
+
tool_result?: JsonValue;
|
|
8
|
+
}
|
|
9
|
+
export type TaskState = {
|
|
10
|
+
kind: 'running';
|
|
11
|
+
brief: string;
|
|
12
|
+
elapsed_ms: number;
|
|
13
|
+
output_tail?: string;
|
|
14
|
+
cancellable: boolean;
|
|
15
|
+
} | ({
|
|
16
|
+
kind: 'finished';
|
|
17
|
+
} & TaskResult) | {
|
|
18
|
+
kind: 'unknown';
|
|
19
|
+
reason: string;
|
|
20
|
+
};
|
|
21
|
+
export interface TaskBrief {
|
|
22
|
+
task_id: string;
|
|
23
|
+
brief: string;
|
|
24
|
+
status: string;
|
|
25
|
+
elapsed_ms: number;
|
|
26
|
+
last_line?: string;
|
|
27
|
+
cancellable: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** How the model follows a task that is still running. */
|
|
30
|
+
export type TaskFollowup = {
|
|
31
|
+
kind: 'tools';
|
|
32
|
+
} | {
|
|
33
|
+
kind: 'command';
|
|
34
|
+
cli: string;
|
|
35
|
+
} | {
|
|
36
|
+
kind: 'input';
|
|
37
|
+
cli?: string;
|
|
38
|
+
};
|
|
39
|
+
/** The task backend of a run (host-provided; `RunningTaskResolver`). */
|
|
40
|
+
export interface RunningTaskResolver {
|
|
41
|
+
state(taskId: string): Promise<TaskState>;
|
|
42
|
+
/** Wait until the task ends or `untilMs` (epoch ms) passes. */
|
|
43
|
+
wait(taskId: string, untilMs: number | undefined, signal?: AbortSignal): Promise<TaskState>;
|
|
44
|
+
cancel?(taskId: string): Promise<TaskState>;
|
|
45
|
+
/** Tasks of this run; a `running` one at a function-call reply pauses the run (`tasks_running`). */
|
|
46
|
+
active(): Promise<TaskBrief[]>;
|
|
47
|
+
watch?(taskId: string): void;
|
|
48
|
+
followup?(): TaskFollowup;
|
|
49
|
+
}
|
|
50
|
+
export declare function followupHint(f: TaskFollowup, taskId: string, cancellable: boolean): string;
|
|
51
|
+
export declare function followupGeneralHint(f: TaskFollowup): string;
|
|
52
|
+
/**
|
|
53
|
+
* A result as `ToolResultView` serializes it (`into_host`): only the view's
|
|
54
|
+
* fields, `title` / `summary` / `hints` omitted when empty, `detail` when
|
|
55
|
+
* null or `{}`, the protocol version filled in.
|
|
56
|
+
*/
|
|
57
|
+
export declare function resultView(fields: Record<string, JsonValue | undefined>): JsonValue;
|
|
58
|
+
/** The observation of a task's state (`task_state_observation_via`). */
|
|
59
|
+
export declare function taskStateObservation(callId: string, taskId: string, state: TaskState, followup: TaskFollowup): Observation;
|
|
60
|
+
/** When an in-call wait ends: the budget, capped at 30 minutes and the run deadline. */
|
|
61
|
+
export declare function waitUntilMs(nowMs: number, waitMs: number | undefined, deadlineMs: number | undefined): number;
|
|
62
|
+
/** The in-call wait for a pending result: `min(check_after, budget)` (check_after only shortens). */
|
|
63
|
+
export declare function inCallWaitMs(checkAfterSecs: number | undefined, budgetMs: number): number;
|
|
64
|
+
//# sourceMappingURL=task_model.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"task_model.d.ts","sourceRoot":"","sources":["../../../src/xllm/runtime/task_model.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAK3D,eAAO,MAAM,mBAAmB,QAAc,CAAA;AAC9C,eAAO,MAAM,oBAAoB,QAAS,CAAA;AAE1C,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,WAAW,CAAC,EAAE,SAAS,CAAA;CACxB;AAED,MAAM,MAAM,SAAS,GACjB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,OAAO,CAAA;CAAE,GAClG,CAAC;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,GA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MAAM,CAY3D;AAeD;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,GAAG,SAAS,CAAC,GAAG,SAAS,CAqBnF;AAED,wEAAwE;AACxE,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,GAAG,WAAW,CA0B1H;AAED,wFAAwF;AACxF,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAK7G;AAED,qGAAqG;AACrG,wBAAgB,YAAY,CAAC,cAAc,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { JsonValue } from '../core/types';
|
|
2
|
+
export declare const AGENT_TOOL_PROTOCOL_VERSION = "1";
|
|
3
|
+
export type AgentToolStatus = 'success' | 'error' | 'pending';
|
|
4
|
+
export interface ResultHint {
|
|
5
|
+
text: string;
|
|
6
|
+
/** Shown once per run (`hints_once` in run.json). */
|
|
7
|
+
once?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ResultDedup {
|
|
10
|
+
key: string;
|
|
11
|
+
hint: string;
|
|
12
|
+
}
|
|
13
|
+
export interface AgentToolResult {
|
|
14
|
+
agent_tool_protocol: string;
|
|
15
|
+
tool?: string;
|
|
16
|
+
cmd_name?: string;
|
|
17
|
+
status: AgentToolStatus;
|
|
18
|
+
task_id?: string;
|
|
19
|
+
pending_reason?: string;
|
|
20
|
+
/** Seconds after which the caller should look again; a runtime only uses it to shorten its wait. */
|
|
21
|
+
check_after?: number;
|
|
22
|
+
estimated_wait?: string;
|
|
23
|
+
title?: string;
|
|
24
|
+
summary: string;
|
|
25
|
+
detail: JsonValue;
|
|
26
|
+
cmd_args?: string;
|
|
27
|
+
return_code?: number;
|
|
28
|
+
partial_output?: string;
|
|
29
|
+
output?: string;
|
|
30
|
+
hints?: ResultHint[];
|
|
31
|
+
dedup?: ResultDedup;
|
|
32
|
+
}
|
|
33
|
+
/** A return value that is an AgentToolResult envelope (`agent_tool_protocol: "1"`). */
|
|
34
|
+
export declare function asToolResult(value: unknown): AgentToolResult | undefined;
|
|
35
|
+
/** The text the model sees (`AgentToolResult::observation_text`). */
|
|
36
|
+
export declare function observationText(r: AgentToolResult): string;
|
|
37
|
+
/** The envelope as `Observation.host` (`to_host`). */
|
|
38
|
+
export declare function toHost(r: AgentToolResult): JsonValue;
|
|
39
|
+
//# sourceMappingURL=tool_result.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool_result.d.ts","sourceRoot":"","sources":["../../../src/xllm/runtime/tool_result.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAI9C,eAAO,MAAM,2BAA2B,MAAM,CAAA;AAE9C,MAAM,MAAM,eAAe,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAAA;AAE7D,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAA;IACZ,qDAAqD;IACrD,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED,MAAM,WAAW,WAAW;IAC1B,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,MAAM,CAAA;CACb;AAED,MAAM,WAAW,eAAe;IAC9B,mBAAmB,EAAE,MAAM,CAAA;IAC3B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,eAAe,CAAA;IACvB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,oGAAoG;IACpG,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,EAAE,SAAS,CAAA;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,UAAU,EAAE,CAAA;IACpB,KAAK,CAAC,EAAE,WAAW,CAAA;CACpB;AAED,uFAAuF;AACvF,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,eAAe,GAAG,SAAS,CAUxE;AAED,qEAAqE;AACrE,wBAAgB,eAAe,CAAC,CAAC,EAAE,eAAe,GAAG,MAAM,CAW1D;AAED,sDAAsD;AACtD,wBAAgB,MAAM,CAAC,CAAC,EAAE,eAAe,GAAG,SAAS,CAEpD"}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { AiToolCall, EffectiveTools, JsonValue, LoopModel, RuntimeConfig, RuntimeDescriptor, RuntimeInfo, ToolsConfig } from '../core/types';
|
|
2
|
+
import type { ToolManager } from '../core/deps';
|
|
3
|
+
import type { HintLedger } from './hints';
|
|
4
|
+
import type { RunningTaskResolver } from './task_model';
|
|
5
|
+
/** The run a tool set is bound to; `run_dir` only where runs live in a directory. */
|
|
6
|
+
export interface RunBinding {
|
|
7
|
+
run_id: string;
|
|
8
|
+
run_dir?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface RuntimeOpenCtx {
|
|
11
|
+
workdir: string;
|
|
12
|
+
run_id: string;
|
|
13
|
+
loop_model: LoopModel;
|
|
14
|
+
/** Field → where it was decided (`EffectiveTools.sources`). */
|
|
15
|
+
sources: Record<string, string>;
|
|
16
|
+
env: Record<string, string>;
|
|
17
|
+
/** The run's task backend (`XllmDeps.tasks`). */
|
|
18
|
+
tasks?: RunningTaskResolver;
|
|
19
|
+
/** In-call wait budget for tasks (`runtime.task_wait_ms`). */
|
|
20
|
+
task_wait_ms: number;
|
|
21
|
+
}
|
|
22
|
+
/** The tool dispatcher of one run (Rust `XllmToolManager` / `Sandbox`). */
|
|
23
|
+
export interface RunToolManager extends ToolManager {
|
|
24
|
+
/** Bind the tools to the run once its id is known. */
|
|
25
|
+
bindRun(binding: RunBinding): void;
|
|
26
|
+
/**
|
|
27
|
+
* Resume: `callId` may have been started by a previous executor; `reason`
|
|
28
|
+
* is the runtime's account of it. When the waist dispatches it again the
|
|
29
|
+
* manager looks for its result first, runs it again only when the tool is
|
|
30
|
+
* idempotent, and otherwise answers `unresolved` with `reason`.
|
|
31
|
+
*/
|
|
32
|
+
setRecovering(callId: string, reason: string): void;
|
|
33
|
+
/** Paths written by the run's tools (`RunRecord.artifacts`). */
|
|
34
|
+
artifacts(): string[];
|
|
35
|
+
/** Names this manager can dispatch. */
|
|
36
|
+
has(name: string): boolean;
|
|
37
|
+
/** What the model was shown of results' hints (`hints_once` in run.json, `dedup` per history). */
|
|
38
|
+
hintLedger(): HintLedger;
|
|
39
|
+
/** The history was rewritten (compaction): results shown before are shown again. */
|
|
40
|
+
clearDedup(): void;
|
|
41
|
+
/** Tasks of this run; a running one at a function-call reply pauses the run. */
|
|
42
|
+
taskResolver(): RunningTaskResolver | undefined;
|
|
43
|
+
}
|
|
44
|
+
export interface OpenedTools {
|
|
45
|
+
tools: EffectiveTools;
|
|
46
|
+
manager: RunToolManager;
|
|
47
|
+
}
|
|
48
|
+
export interface AgentRuntime {
|
|
49
|
+
/** Identity of the execution target; a resume requires it equal to the saved one. */
|
|
50
|
+
descriptor(): RuntimeDescriptor;
|
|
51
|
+
/** The configuration the runtime was opened with (saved in run.json). */
|
|
52
|
+
config(): RuntimeConfig;
|
|
53
|
+
/** Environment facts for prompts (`{{runtime.*}}`). */
|
|
54
|
+
info(): Promise<RuntimeInfo>;
|
|
55
|
+
/** The tools of one run; `tools` (the configuration) can only select from what the runtime has. */
|
|
56
|
+
open(ctx: RuntimeOpenCtx, tools: ToolsConfig): Promise<OpenedTools>;
|
|
57
|
+
/** The account given to the model for a call that may have run before the previous executor stopped. */
|
|
58
|
+
describeInterrupted(run: RunBinding, call: AiToolCall): Promise<string>;
|
|
59
|
+
/** `{{env.NAME}}`: only what the runtime was given explicitly. */
|
|
60
|
+
env?(name: string): string | undefined;
|
|
61
|
+
}
|
|
62
|
+
/** Text shown for a call (other than `shell`) a previous executor may have started. */
|
|
63
|
+
export declare function unresolvedReason(tool: string): string;
|
|
64
|
+
/** Context of one site tool call. */
|
|
65
|
+
export interface SiteToolCtx {
|
|
66
|
+
run_id: string;
|
|
67
|
+
call_id: string;
|
|
68
|
+
/** Aborts on interrupt (and when the run deadline passed). */
|
|
69
|
+
signal: AbortSignal;
|
|
70
|
+
}
|
|
71
|
+
export interface SiteToolSpec {
|
|
72
|
+
description: string;
|
|
73
|
+
/** JSON Schema of the arguments (an object schema). */
|
|
74
|
+
args_schema: JsonValue;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* A tool the page provides: a plain JS function of the page. Its return value
|
|
78
|
+
* is the result (a string as is, anything else as JSON); a thrown error is a
|
|
79
|
+
* failed call the model sees.
|
|
80
|
+
*/
|
|
81
|
+
export interface SiteTool {
|
|
82
|
+
spec: SiteToolSpec;
|
|
83
|
+
call(args: Record<string, JsonValue>, ctx: SiteToolCtx): unknown;
|
|
84
|
+
/**
|
|
85
|
+
* Running it again with the same arguments has no further effect (or the
|
|
86
|
+
* tool deduplicates by `call_id`): on resume an interrupted call is run
|
|
87
|
+
* again. Otherwise it gets `unresolved` with `describeInterrupted`'s text.
|
|
88
|
+
*/
|
|
89
|
+
idempotent?: boolean | ((args: Record<string, JsonValue>) => boolean);
|
|
90
|
+
/** What became of an interrupted call (read the page's state); default: a generic "effect unknown". */
|
|
91
|
+
describeInterrupted?(args: Record<string, JsonValue>, ctx: SiteToolCtx): string | Promise<string>;
|
|
92
|
+
/**
|
|
93
|
+
* The tool stops its work when `ctx.signal` aborts and then rejects: its
|
|
94
|
+
* effect is known (not done). Without it an interrupted call is abandoned
|
|
95
|
+
* and its effect is unknown.
|
|
96
|
+
*/
|
|
97
|
+
cancellable?: boolean;
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/xllm/runtime/types.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,UAAU,EAAE,cAAc,EAAE,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,iBAAiB,EAAE,WAAW,EAAE,WAAW,EAC7G,MAAM,eAAe,CAAA;AACtB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAC/C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACzC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAA;AAEvD,qFAAqF;AACrF,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAA;IACf,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,SAAS,CAAA;IACrB,+DAA+D;IAC/D,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC3B,iDAAiD;IACjD,KAAK,CAAC,EAAE,mBAAmB,CAAA;IAC3B,8DAA8D;IAC9D,YAAY,EAAE,MAAM,CAAA;CACrB;AAED,2EAA2E;AAC3E,MAAM,WAAW,cAAe,SAAQ,WAAW;IACjD,sDAAsD;IACtD,OAAO,CAAC,OAAO,EAAE,UAAU,GAAG,IAAI,CAAA;IAClC;;;;;OAKG;IACH,aAAa,CAAC,MAAM,EAAE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AA;CACvB;AAED;;;;GAIG;AACH,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,YAAY,CAAA;IAClB,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,GAAG,EAAE,WAAW,GAAG,OAAO,CAAA;IAChE;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,KAAK,OAAO,CAAC,CAAA;IACrE,uGAAuG;IACvG,mBAAmB,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,GAAG,EAAE,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;IACjG;;;;OAIG;IACH,WAAW,CAAC,EAAE,OAAO,CAAA;CACtB"}
|
package/dist/xllm.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./aicc-ccb36ef7.js"),t=require("./site_manager-334b1a51.js"),o=require("./did_object_client-6a1b108a.js");require("./krpc_client-26c2dc8b.js"),require("./object_url-8fb5a7bf.js"),require("./ndn_types-5b138882.js");const r="site",n=/^[A-Za-z0-9_-]{1,64}$/;function s(o,r){return(o??[]).map((o=>{if("named"!==o.kind)throw e.XllmError.capability(`${r}: \`${t.describeToolSource(o)}\` is not available in a site runtime; only the page's tools can be named`);return o.name}))}class i extends Error{constructor(e,t){super(t),this.name="CommandArgsError",this.code=e}}function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function c(e){return e.property??e.name.split("-").join("_")}function l(e){const t=e.slice(2),o=t.indexOf("=");return o<0?{name:t}:{name:t.slice(0,o),inlineValue:t.slice(o+1)}}function u(e,t,o){if(void 0!==o.inlineValue){if(!o.inlineValue)throw new i("MISSING_ARGUMENT",`--${o.name} requires a value`);return{value:o.inlineValue,consumed:1}}const r=e[t+1];if(void 0===r||r.startsWith("--"))throw new i("MISSING_ARGUMENT",`--${o.name} requires a value`);return{value:r,consumed:2}}function p(e,t,o){if("string"===e)return t;const r=Number(t);if(!Number.isFinite(r)||"integer"===e&&!Number.isInteger(r))throw new i("INVALID_ARGUMENT",`--${o} requires a ${e}`);return r}function d(e,t,o,r){const n=t[o];if(!n)throw new i("TOO_MANY_ARGUMENTS",`unexpected positional argument: ${r}`);return e[n.name]=r,o+1}function m(e){const t=[];let o="",r=null,n=!1,s=!1;for(const i of e)n?(o+=i,n=!1,s=!0):"\\"!==i||"single"===r?"single"!==r?"double"!==r?"'"!==i?'"'!==i?/\s/.test(i)?s&&(t.push(o),o="",s=!1):(o+=i,s=!0):(r="double",s=!0):(r="single",s=!0):'"'===i?r=null:o+=i:"'"===i?r=null:o+=i:(n=!0,s=!0);if(n)throw new i("INVALID_COMMAND_LINE","unfinished escape sequence");if(r)throw new i("INVALID_COMMAND_LINE",`unterminated ${r} quote`);return s&&t.push(o),t}function f(e,t,o){var r;if(t.enum&&!t.enum.some((t=>Object.is(t,e))))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be one of ${t.enum.join(", ")}`);if("object"!==t.type)if("array"!==t.type)if("string"!==t.type){if("boolean"===t.type&&"boolean"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a boolean`);if("integer"===t.type&&(!Number.isInteger(e)||"number"!=typeof e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an integer`);if("number"===t.type&&"number"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a number`)}else{if("string"!=typeof e)throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be a string`);if(void 0!==t.minLength&&e.length<t.minLength)throw new i("SCHEMA_VALIDATION_FAILED",`${o} is too short`)}else{if(!Array.isArray(e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an array`);const r=t.items;r&&e.forEach(((e,t)=>f(e,r,`${o}[${t}]`)))}else{if(!e||"object"!=typeof e||Array.isArray(e))throw new i("SCHEMA_VALIDATION_FAILED",`${o} must be an object`);const n=e;for(const e of t.required??[])if(!a(n,e))throw new i("SCHEMA_VALIDATION_FAILED",`${o}.${e} is required`);if(!1===t.additionalProperties)for(const e of Object.keys(n))if(!a(t.properties??{},e))throw new i("SCHEMA_VALIDATION_FAILED",`${o}.${e} is not allowed`);for(const[e,s]of Object.entries(n)){const n=null==(r=t.properties)?void 0:r[e];n&&f(s,n,`${o}.${e}`)}}}const h=["read_only","idempotent_write","write","destructive","admin"],g="xcall <object> <action> [--params <json>] [key=value ...] [--key=value ...]",_=65536,x=/[|;&><`$]/;function y(e){throw new Error(e)}function S(e,t){const o=e.trim();o||y("uri is empty");const r=/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o);let n,s;try{n=r?new URL(o):new URL(o.replace(/^\/+/,""),"site://page/")}catch{y(`invalid uri \`${o}\``)}r?(s=`${n.protocol.slice(0,-1).toLowerCase()}://${n.host.toLowerCase()}`,t.has(s)||y(`uri \`${o}\` is not a resource of this page (absolute URIs are limited to the declared ones)`)):"site:"===n.protocol&&"page"===n.host||y(`uri \`${o}\` is not a resource of this page`);const i=[];for(const c of n.pathname.split("/")){if(""===c)continue;let e;try{e=decodeURIComponent(c)}catch{y(`invalid uri \`${o}\``)}(".."===e||"."===e||e.includes("/")||e.includes("\\"))&&y(`uri \`${o}\` is not a resource of this page`),i.push(e)}const a=(s?`${s}/`:"")+i.join("/")+(n.search||"");return{origin:s,segments:i,query:n.searchParams,text:a}}function T(e,t,o){if(e.origin!==t||e.segments.length!==o.length)return;const r={};for(let n=0;n<o.length;n++){const t=e.segments[n];if(t.startsWith("{")&&t.endsWith("}"))r[t.slice(1,-1)]=o[n];else if(t!==o[n])return}return r}function w(e){if(null==e)return"";if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function b(t){if(e.isObject(t)&&"content"in t&&Object.keys(t).every((e=>"content"===e||"version"===e))){const e=t.version;return{text:w(t.content),version:"string"==typeof e?e:void 0===e?void 0:String(e)}}return{text:w(t)}}function E(e,o){if(t.utf8Length(e)<=o)return{text:e,clipped:!1};let r="",n=0;for(const s of e){const e=t.utf8Length(s);if(n+e>o)break;r+=s,n+=e}return{text:r,clipped:!0}}function O(e,o=1,r){const n=e.split("\n"),s=Math.max(1,Math.floor(o));if(s>n.length&&(1!==s||1!==n.length))return`[offset ${s} is past the end: ${n.length} lines]`;const i=void 0===r?n.length:Math.max(1,Math.floor(r)),a=[];let c=0,l=s-1;for(;l<n.length&&a.length<i;l++){const e=t.utf8Length(n[l])+1;if(a.length>0&&c+e>_)break;a.push(n[l]),c+=e}let u=a.join("\n");return 1===a.length&&t.utf8Length(u)>_&&(u=E(u,_).text+" …"),l<n.length&&(u+=`\n[lines ${s}–${l} of ${n.length}; read on with offset=${l+1}]`),u}function A(e){const t=e.trim();if("true"===t)return!0;if("false"===t)return!1;if("null"===t)return null;if(/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(t))return Number(t);if(t.startsWith("{")||t.startsWith("["))try{return JSON.parse(t)}catch{return t}return t}const R=["config","route-config","session-id","session_id","idempotency-key","idempotency_key","confirm-token","confirm_token","trace-id","trace_id"];function I(t){let o,r,n={};const s={},i=[],a=(e,t)=>{try{return JSON.parse(e)}catch(o){y(`invalid \`${t}\` JSON value \`${e}\`: ${o instanceof Error?o.message:String(o)}\nusage: ${g}`)}},c=e=>y(`unsupported flag \`${e}\` (routing and confirmation are the page's)\nusage: ${g}`);for(let e=0;e<t.length;e++){const l=t[e];if("--params"===l){const o=t[++e];void 0===o&&y(`missing value for --params\nusage: ${g}`),n=a(o,"--params")}else if(l.startsWith("--")){const e=l.indexOf("=");e<0&&c(l);const t=l.slice(2,e),o=l.slice(e+1);"params"===t?n=a(o,"--params"):!t.trim()||t.startsWith("-")||R.includes(t)?c(l):s[t]=A(o)}else if(l.includes("=")){const e=l.indexOf("="),t=l.slice(0,e),i=l.slice(e+1);"object"===t?o=i:"action"===t?r=i:"params"===t?n=a(i,"params"):R.includes(t)?c(l):s[t]=A(i)}else i.push(l)}return o=o??i[0],r=r??i[1],void 0!==i[2]&&(n=a(i[2],"params")),i.length>3&&y(`unexpected positional argument \`${i[3]}\`\nusage: ${g}`),Object.keys(s).length&&(e.isObject(n)||y(`key=value params require object params\nusage: ${g}`),n={...n,...s}),o&&r||y(`xcall needs an object and an action\nusage: ${g}`),e.isObject(n)||y(`params must be a JSON object\nusage: ${g}`),{object:o,action:r,params:n}}function $(e,t){var o;const r=[`${e} — ${t.summary}`];t.description&&r.push("",t.description);const n=(t.positionals??[]).map((e=>!1===e.required?`[${e.name}]`:`<${e.name}>`)).join(" ");r.push("",`usage: ${e}${n?` ${n}`:""}${(t.options??[]).length?" [options]":""}`);for(const s of t.positionals??[])r.push(` ${s.name} ${s.description}`);(t.options??[]).length&&r.push("options:");for(const s of t.options??[])r.push(` --${s.name}${"boolean"===s.type?"":` <${s.type}>`}${s.required?" (required)":""} ${s.description}${s.enum?` (${s.enum.join(" | ")})`:""}`);if(null==(o=t.examples)?void 0:o.length){r.push("examples:");for(const e of t.examples)r.push(` ${e}`)}return r.join("\n")}const N=(e,t)=>({type:"object",properties:e,required:t});const M="https://buckyos.org/traits/index@1";function v(t,o){return e.isObject(t)&&"string"==typeof t[o]?t[o]:""}function L(e){const t=h.indexOf(e);return t<0?h.length:t}function k(t,o,r,n){const s=[`Object: ${t}`,`Object DID: ${o.id}`],i=(o.alsoKnownAs??[]).filter((e=>e!==t));i.length&&s.push(`Also known as: ${i.join(", ")}`);for(const[e,c]of[["Title","title"],["Description","description"]]){const t=v(r,c);t&&s.push(`${e}: ${t}`)}for(const[c,l]of[["Properties","properties"],["Actions","actions"],["Events","events"]]){const t=e.isObject(r)?r[l]:void 0;if(e.isObject(t)&&0!==Object.keys(t).length){s.push(`${c}:`);for(const e of Object.keys(t).sort()){const o=t[e];let r=`- ${e}`;const n=v(o,"description");n&&(r+=`: ${n}`);const i=v(o,"x-buckyos:risk");i&&(r+=` (risk: ${i})`),s.push(r)}}}const a=Object.keys(n);if(a.length){s.push("Summary:");for(const e of a)s.push(`- ${e}:`,JSON.stringify(n[e],null,2))}return s.join("\n")}function j(t){const o=e.isObject(t)?t["x-buckyos:traits"]:void 0;return Array.isArray(o)&&o.includes(M)}const C="xllm-runs",D="records",U="snapshots";function H(e){return new Promise(((t,o)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>o(e.error)}))}function P(e){return new Promise(((t,o)=>{e.oncomplete=()=>t(),e.onerror=()=>o(e.error),e.onabort=()=>o(e.error??new Error("transaction aborted"))}))}exports.AiccLlmClient=e.AiccLlmClient,exports.LLMComputeException=e.LLMComputeException,exports.XllmError=e.XllmError,exports.aiccProviderFailure=e.aiccProviderFailure,exports.anyJsonObjectSchema=e.anyJsonObjectSchema,exports.asComputeError=e.asComputeError,exports.charCount=e.charCount,exports.computeErrorMessage=e.computeErrorMessage,exports.errorSource=e.errorSource,exports.infraRetrySafe=e.infraRetrySafe,exports.llmCorrectable=e.llmCorrectable,exports.providerError=e.providerError,exports.providerErrorFromRpc=e.providerErrorFromRpc,exports.rustTrim=e.rustTrim,exports.rustTrimEnd=e.rustTrimEnd,exports.rustTrimStart=e.rustTrimStart,exports.serdeJson=e.serdeJson,exports.AGENT_TOOL_PROTOCOL_VERSION=t.AGENT_TOOL_PROTOCOL_VERSION,exports.ByteHeuristicTokenizer=t.ByteHeuristicTokenizer,exports.DEFAULT_CONTEXT_YIELD_RATIO=t.DEFAULT_CONTEXT_YIELD_RATIO,exports.DEFAULT_LLM_TIMEOUT_SECS=t.DEFAULT_LLM_TIMEOUT_SECS,exports.DEFAULT_MAX_CONSECUTIVE_ERRORS=t.DEFAULT_MAX_CONSECUTIVE_ERRORS,exports.DEFAULT_MAX_TOOL_ITERATIONS=t.DEFAULT_MAX_TOOL_ITERATIONS,exports.DEFAULT_TASK_WAIT_MS=t.DEFAULT_TASK_WAIT_MS,exports.DEFAULT_TIMEOUT_SECS=t.DEFAULT_TIMEOUT_SECS,exports.HINT_NS_DEDUP=t.HINT_NS_DEDUP,exports.HINT_NS_ONCE=t.HINT_NS_ONCE,exports.HOST_PROMPT_SECTIONS_ALL=t.HOST_PROMPT_SECTIONS_ALL,exports.HOST_PROMPT_SECTIONS_NONE=t.HOST_PROMPT_SECTIONS_NONE,exports.LLMContext=t.LLMContext,exports.LLMContextInterruptHandle=t.LLMContextInterruptHandle,exports.LlmSummarizeCompressor=t.LlmSummarizeCompressor,exports.MAX_IMAGE_ATTACHMENT_BYTES=t.MAX_IMAGE_ATTACHMENT_BYTES,exports.MAX_INJECTIONS_PER_BOUNDARY=t.MAX_INJECTIONS_PER_BOUNDARY,exports.MAX_IN_TOOL_WAIT_MS=t.MAX_IN_TOOL_WAIT_MS,exports.MAX_TEXT_ATTACHMENT_BYTES=t.MAX_TEXT_ATTACHMENT_BYTES,exports.MemoryHintLedger=t.MemoryHintLedger,exports.MemoryRunStore=t.MemoryRunStore,exports.REFUSED_CREDENTIALS=t.REFUSED_CREDENTIALS,exports.REPORT_ARTIFACTS_KEY=t.REPORT_ARTIFACTS_KEY,exports.RUNTIME_PROTOCOL_VERSION=t.RUNTIME_PROTOCOL_VERSION,exports.RUN_RECORD_VERSION=t.RUN_RECORD_VERSION,exports.SNAPSHOT_FORMAT_VERSION=t.SNAPSHOT_FORMAT_VERSION,exports.SUMMARIZE_MODEL_ALIAS=t.SUMMARIZE_MODEL_ALIAS,exports.SiteToolManager=t.SiteToolManager,exports.TemplateEnv=t.TemplateEnv,exports.TimeoutLlmClient=t.TimeoutLlmClient,exports.ToolDispatchException=t.ToolDispatchException,exports.XllmActionParser=t.XllmActionParser,exports.XllmInterrupter=t.XllmInterrupter,exports.XllmRun=t.XllmRun,exports.XllmTask=t.XllmTask,exports.XmlStepRenderer=t.XmlStepRenderer,exports.allowAllPolicy=t.allowAllPolicy,exports.applyHints=t.applyHints,exports.asToolResult=t.asToolResult,exports.assemblePrompt=t.assemblePrompt,exports.buildCmdManualSystemText=t.buildCmdManualSystemText,exports.buildRulesSystemText=t.buildRulesSystemText,exports.buildRuntimeProtocol=t.buildRuntimeProtocol,exports.buildRuntimeProtocolFor=t.buildRuntimeProtocolFor,exports.classifyError=t.classifyError,exports.compactionTargetTokens=t.compactionTargetTokens,exports.compress=t.compress,exports.compressHistory=t.compressHistory,exports.compressOptions=t.compressOptions,exports.computeToolsConfig=t.computeToolsConfig,exports.envelopeObservation=t.envelopeObservation,exports.exportRun=t.exportRun,exports.extractResult=t.extractResult,exports.followupGeneralHint=t.followupGeneralHint,exports.followupHint=t.followupHint,exports.generateRunId=t.generateRunId,exports.importRun=t.importRun,exports.inCallWaitMs=t.inCallWaitMs,exports.inFlightCall=t.inFlightCall,exports.isIdempotent=t.isIdempotent,exports.isSummaryMessage=t.isSummaryMessage,exports.isTerminal=t.isTerminal,exports.materializeHistory=t.materializeHistory,exports.mergeConfigLayers=t.mergeConfigLayers,exports.noopWorklog=t.noopWorklog,exports.observationText=t.observationText,exports.parseLlmContextJson=t.parseLlmContextJson,exports.parseReply=t.parseReply,exports.parseSummaryMessage=t.parseSummaryMessage,exports.renderHintBlock=t.renderHintBlock,exports.renderStepHistory=t.renderStepHistory,exports.renderWithHints=t.renderWithHints,exports.reportArtifacts=t.reportArtifacts,exports.resolveToolSpecs=t.resolveToolSpecs,exports.resultView=t.resultView,exports.rewritableHistory=t.rewritableHistory,exports.runRequest=t.runRequest,exports.splitReportResult=t.splitReportResult,exports.stateFromRequest=t.stateFromRequest,exports.summaryMessage=t.summaryMessage,exports.summaryModel=t.summaryModel,exports.taskStateObservation=t.taskStateObservation,exports.toHost=t.toHost,exports.toolResultViewFromHost=t.toolResultViewFromHost,exports.unresolvedReason=t.unresolvedReason,exports.validateJson=t.validateJson,exports.waitUntilMs=t.waitUntilMs,exports.DIDObjectClient=o.DIDObjectClient,exports.DIDObjectError=o.DIDObjectError,exports.ACTION_RISKS=h,exports.INDEX_TRAIT_URI=M,exports.IndexedDbRunStore=class{constructor(e={}){this.options=e,this.persistent=!0,this.localLocks=new Set}open(){if(!this.db){const t=this.options.idb??globalThis.indexedDB;if(!t)return Promise.reject(e.XllmError.storage("IndexedDB is not available here"));const o=t.open(this.options.dbName??C,1);o.onupgradeneeded=()=>{const e=o.result;e.objectStoreNames.contains(D)||e.createObjectStore(D,{keyPath:"run_id"}),e.objectStoreNames.contains(U)||e.createObjectStore(U)},this.db=H(o)}return this.db}locks(){var e;if(null!==this.options.locks)return this.options.locks??(null==(e=globalThis.navigator)?void 0:e.locks)}runsDir(){}runDir(){}async createRun(){const o=await this.open();for(let e=0;e<8;e++){const e=t.generateRunId();if(!(await H(o.transaction(D).objectStore(D).get(e))))return e}throw e.XllmError.storage("cannot allocate a unique run id")}async writeRecord(e){const t=(await this.open()).transaction(D,"readwrite");t.objectStore(D).put(JSON.parse(JSON.stringify(e))),await P(t)}async readRecord(o){const r=await this.open(),n=await H(r.transaction(D).objectStore(D).get(o));if(!n)throw new e.XllmError({kind:"run_not_found",run_id:o,runs_dir:`indexeddb:${this.options.dbName??C}`});if(n.version!==t.RUN_RECORD_VERSION)throw e.XllmError.notResumable(o,"unsupported run record version");return n}async listRecords(){const e=await this.open();return await H(e.transaction(D).objectStore(D).getAll())}async putSnapshot(e,t){const o=(await this.open()).transaction(U,"readwrite"),r=o.objectStore(U),n=await H(r.getAllKeys(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER]))),s=n.length?Math.max(...n.map((e=>e[1])))+1:1;return r.put(JSON.parse(JSON.stringify(t)),[e,s]),await P(o),s}async getSnapshot(t,o){const r=await this.open(),n=await H(r.transaction(U).objectStore(U).get([t,o]));if(!n)throw new e.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${o} missing`});return n}async listSnapshots(e){const t=await this.open();return(await H(t.transaction(U).objectStore(U).getAllKeys(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])))).map((e=>e[1])).sort(((e,t)=>e-t))}async lockRun(e){const t=`xllm-run:${e}`,o=this.locks();return o?new Promise(((e,r)=>{o.request(t,{ifAvailable:!0},(t=>t?new Promise((t=>e({release:()=>t()}))):(e(null),Promise.resolve()))).catch(r)})):this.localLocks.has(t)?null:(this.localLocks.add(t),{release:()=>{this.localLocks.delete(t)}})}async isRunLive(e){const t=`xllm-run:${e}`,o=this.locks();if(!o)return this.localLocks.has(t);return((await o.query()).held??[]).some((e=>e.name===t))}async removeRun(e){const t=(await this.open()).transaction([D,U],"readwrite");t.objectStore(D).delete(e),t.objectStore(U).delete(IDBKeyRange.bound([e,0],[e,Number.MAX_SAFE_INTEGER])),await P(t)}async importRun(e){const t=(await this.open()).transaction([D,U],"readwrite");t.objectStore(D).put(JSON.parse(JSON.stringify(e.record)));for(const[o,r]of e.snapshots)t.objectStore(U).put(JSON.parse(JSON.stringify(r)),[e.record.run_id,o]);await P(t)}},exports.MAX_RESULT_BYTES=_,exports.SITE_RUNTIME_KIND=r,exports.XCALL_USAGE=g,exports.XLLM_RUNS_DB=C,exports.createSiteRuntime=function(o){var i;const a=null==(i=o.scene)?void 0:i.trim();if(!a)throw e.XllmError.input("createSiteRuntime: `scene` is required");if(!o.origin)throw e.XllmError.input("createSiteRuntime: `origin` is required");const c=new Map;for(const[t,r]of Object.entries(o.tools??{})){if(!n.test(t))throw e.XllmError.tools(`site tool name \`${t}\` must match ${n}`);if(!r||"function"!=typeof r.call||!r.spec)throw e.XllmError.tools(`site tool \`${t}\` needs \`spec\` and \`call\``);c.set(t,r)}const l={...o.env??{}},u={runtime_id:`site:${a}`,kind:r,host:null,target:{origin:o.origin,scene:a},workdir:"/",capabilities:{tools:{},network:!0,os:"browser"}},p={kind:r,env:{}};return void 0!==o.task_wait_ms&&(p.task_wait_ms=o.task_wait_ms),{scene:a,tools:c,descriptor:()=>JSON.parse(JSON.stringify(u)),config:()=>JSON.parse(JSON.stringify(p)),async info(){let e="";try{e=Intl.DateTimeFormat().resolvedOptions().timeZone??""}catch{e=""}return{id:u.runtime_id,kind:r,os:"browser",arch:"",hostname:o.hostname,shell:"",cwd:"/",tools:[],current_time:(new Date).toISOString(),timezone:e,target:u.target,platform:"browser",shell_kind:"",baseline:""}},async open(o,r){const n=r.enabled??!1,i=r.tools2actions??!1;if("function_call"===o.loop_model&&(i||(r.actions??[]).length>0))throw e.XllmError.capability("actions / tools2actions need loop_model behavior");const l=(t,o)=>t.map((t=>{const r=c.get(t);if(!r)throw e.XllmError.capability(`${o}: \`${t}\` is not a tool of scene \`${a}\` (scene tools: ${[...c.keys()].join(", ")||"none"})`);return function(e,t,o){return{name:e,description:t.spec.description,args_schema:t.spec.args_schema,source:o}}(t,r,`name:${t}`)}));let u=[],d=[];const m=r.tools??[],f=r.actions??[];if(n){u=l(void 0===r.tools?[...c.keys()]:s(r.tools,"tools.tools"),"tools.tools"),d=l(s(r.actions,"tools.actions"),"tools.actions"),i&&(d=[...d,...u.filter((e=>!d.some((t=>t.name===e.name))))],u=[])}const h=new Map;for(const e of[...u,...d])h.set(e.name,c.get(e.name));return{tools:{enabled:n,filesystem_policy:r.filesystem_policy??"workspace",tools2actions:i,tool_sources:void 0===r.tools&&n?u.map((e=>({kind:"named",name:e.name}))):m,action_sources:f,native:u,actions:d,bash_tools:[],shell:t.shellSettings(r.shell,t.taskWaitMs(p)),exec_enabled:!1,sources:{...o.sources}},manager:new t.SiteToolManager(h,{tasks:o.tasks,taskWaitMs:o.task_wait_ms})}},async describeInterrupted(e,o){const r=c.get(o.name);if(null==r?void 0:r.describeInterrupted)try{return await r.describeInterrupted(o.args??{},{run_id:e.run_id,call_id:o.call_id,signal:(new AbortController).signal})}catch(n){return`${t.unresolvedReason(o.name)} (describing it failed: ${n instanceof Error?n.message:String(n)})`}return t.unresolvedReason(o.name)},env:e=>l[e]}},exports.didObjectResources=async function(t){const o=L(t.maxRisk??"read_only"),r={};for(const n of t.roots){const s=t.client,i=await s.profile(n),a=j(i),c={},l=e.isObject(i)&&e.isObject(i.actions)?i.actions:{};for(const[t,r]of Object.entries(l)){if(a&&("query"===t||"page"===t))continue;const i=v(r,"x-buckyos:risk");if(L(i)>o)continue;const l=e.isObject(r)?r.input:void 0;c[t]={description:v(r,"description"),risk:i,...null!=l?{input:l}:{},call:(e,o)=>s.invoke(n,t,o)}}const u=[v(i,"title"),v(i,"description")].filter(Boolean).join(" — ")||n;r[n]={description:a?`${u} (a collection: read it with a query, ?cursor=… for the next page)`:u,actions:c,async read(t){if(a&&[...t.query.keys()].length>0){const e=t.query.get("cursor"),o=t.query.get("page_size");if(e)return s.invoke(n,"page",{cursor:e,...o?{page_size:Number(o)}:{}});const r={};for(const[n,s]of t.query)"page_size"!==n&&(r[n]=s);return s.invoke(n,"query",{query:r,...o?{page_size:Number(o)}:{}})}const o=await s.card(n),r=e.isObject(i)&&e.isObject(i.properties)?Object.keys(i.properties).filter((e=>"index_schema"!==e)):[],c=e.isObject(i)&&Array.isArray(i["x-buckyos:summary_props"])?i["x-buckyos:summary_props"].filter((e=>"string"==typeof e)):r,l={};for(const e of c)l[e]=await s.readProperty(n,e);return k(n,{id:String(o.id),alsoKnownAs:o.alsoKnownAs},i,l)}}}return r},exports.normalizeUri=S,exports.pageText=O,exports.renderObjectDocument=k,exports.siteTools=function(e){const o=Object.entries(e.resources??{}).map((([e,t])=>function(e,t){const o=e.indexOf("://");if(o>=0){const r=e.slice(o+3),n=r.indexOf("/"),s=n<0?r:r.slice(0,n),i=n<0?"":r.slice(n+1);return{raw:e,origin:`${e.slice(0,o).toLowerCase()}://${s.toLowerCase()}`,segments:i?i.split("/"):[],decl:t}}const r=e.replace(/^\/+/,"").replace(/\/+$/,"");return{raw:e,segments:r?r.split("/"):[],decl:t}}(e,t))),r=new Set(o.map((e=>e.origin)).filter((e=>void 0!==e))),n=new Map(Object.entries(e.commands??{}));if(n.has("xcall"))throw new Error("siteTools: `xcall` is built in; declare actions on resources instead");const s=(e,t)=>{const n=S(e,r);for(const r of o){const e=T(r,n.origin,n.segments);if(e)return{uri:n.text,pattern:r.raw,params:e,query:n.query,ctx:t,decl:r.decl}}y(`uri \`${e}\` is not a resource of this page; read uri="/" lists them`)},h=async(e,o)=>{var r;const h=(()=>{try{return m(e)}catch(t){y(`${t instanceof Error?t.message:String(t)}; exec runs one command, it is not a shell`)}})(),S="available commands: xcall"+(n.size?`, ${[...n.keys()].join(", ")}`:""),T=e.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g,"");x.test(T)&&y(`exec runs exactly one command and is not a shell: pipes, redirects, \`;\`, \`&\`, backquotes and \`$\` are not supported (quote them to pass them as text). ${S}`);const[b,...O]=h;if(b||y(`empty command; ${S}`),"xcall"===b){if(O.includes("--help")||O.includes("-h"))return`usage: ${g}\nThe actions of each resource are listed by read uri="/".`;const{object:e,action:n,params:i}=I(O),a=s(e,o),c=null==(r=a.decl.actions)?void 0:r[n];if(!c){const e=Object.keys(a.decl.actions??{});y(`resource \`${a.pattern}\` has no action \`${n}\` (actions: ${e.length?e.join(", "):"none"})`)}if(void 0!==c.input){const e=t.validateJson(c.input,i);e&&y(`invalid params for ${n}: ${e}`)}const{decl:l,...u}=a,p=await c.call(u,i);return`[risk: ${c.risk}]\n${E(w(p)||"ok",_).text}`}const A=n.get(b);let R;A||y(`unknown command \`${b}\`; exec runs one command, it is not a shell. ${S}`);try{const e=function(e,t,o){const r={},n=e.positionals??[],s=new Map((e.options??[]).map((e=>[e.name,e])));let m=0,f=!1;for(let h=0;h<t.length;){const e=t[h];if("--help"===e||"-h"===e){f=!0,h+=1;continue}if("--"===e){for(const e of t.slice(h+1))m=d(r,n,m,e);break}if(!e.startsWith("--")){m=d(r,n,m,e),h+=1;continue}const g=l(e),_=null==o?void 0:o(g,t,h);if(void 0!==_){h+=_;continue}const x=s.get(g.name);if(!x)throw new i("UNKNOWN_OPTION",`unknown option: --${g.name}`);const y=c(x);if(a(r,y))throw new i("DUPLICATE_ARGUMENT",`argument provided more than once: ${y}`);if("boolean"===x.type){if(void 0!==g.inlineValue)throw new i("INVALID_ARGUMENT",`--${g.name} does not accept a value`);r[y]=!0,h+=1;continue}const{value:S,consumed:T}=u(t,h,g);r[y]=p(x.type,S,g.name),h+=T}return{input:r,help:f,positionalCount:m}}({positionals:A.positionals,options:A.options},O);if(e.help)return $(b,A);for(let t=e.positionalCount;t<(A.positionals??[]).length;t++)if(!1!==(A.positionals??[])[t].required)throw new i("MISSING_ARGUMENT",`missing positional argument: ${(A.positionals??[])[t].name}`);for(const t of A.options??[]){const o=t.property??t.name.split("-").join("_");if(t.required&&!(o in e.input))throw new i("MISSING_ARGUMENT",`--${t.name} is required`)}R=e.input,A.inputSchema&&f(R,A.inputSchema,"input")}catch(N){throw N instanceof i&&y(`${b}: ${N.message}\n\n${$(b,A)}`),N}return E(w(await A.call(R,o))||"ok",_).text};return{read:{spec:{description:'Read a resource of this page by URI (GET). Start with uri "/": it lists the resources, their actions (with risk) and the commands. A collection\'s read is its list; filter and page with a query (notes?tag=x). Text comes in pages of lines: offset is the first line (1-based), limit the number of lines.',args_schema:N({uri:{type:"string",description:'Resource URI, e.g. "/" or "notes/1"'},offset:{type:"integer",description:"First line, 1-based"},limit:{type:"integer",description:"Number of lines"}},["uri"])},idempotent:!0,async call(e,t){const r=String(e.uri),i="number"==typeof e.offset?e.offset:void 0,a="number"==typeof e.limit?e.limit:void 0;if("/"===r.trim()||""===r.trim())return O((()=>{const e=['Resources (read uri="<resource>"; {name} is one path segment):'];for(const t of o){const o=["read","write","edit"].filter((e=>"edit"===e?!!(t.decl.edit||t.decl.read&&t.decl.write):!!t.decl[e]));e.push(`- ${t.raw} — ${t.decl.description} [${o.join(", ")||"no methods"}]`);for(const[r,n]of Object.entries(t.decl.actions??{}))e.push(` action ${r} (risk: ${n.risk}) — ${n.description}`)}0===o.length&&e.push("(none)"),e.push("",'Commands (exec "<command> --help" for usage):'),e.push(`- xcall — call an action of a resource: ${g}`);for(const[t,o]of n)e.push(`- ${t} — ${o.summary}`);return e.join("\n")})(),i,a);return O((await(async e=>{e.decl.read||y(`resource \`${e.pattern}\` cannot be read`);const{decl:t,...o}=e;return b(await e.decl.read(o))})(s(r,t))).text,i,a)}},write:{spec:{description:'Write a resource\'s content (PUT). mode: "write" (default) replaces it, "new" only creates it and fails if it exists, "append" adds to its end. Use edit to change part of it.',args_schema:N({uri:{type:"string",description:"Resource URI"},content:{type:"string",description:"The content"},mode:{type:"string",enum:["write","new","append"],description:"write | new | append"}},["uri","content"])},async call(e,t){const o=s(String(e.uri),t);o.decl.write||y(`resource \`${o.pattern}\` is read-only`);const{decl:r,...n}=o,i="string"==typeof e.mode?e.mode:"write";return w(await r.write(n,{content:String(e.content),mode:i}))||"written"}},edit:{spec:{description:"Change part of a resource (PATCH): old_string must occur exactly once in its current content and is replaced by new_string.",args_schema:N({uri:{type:"string",description:"Resource URI"},old_string:{type:"string",description:"Text to replace; must occur exactly once"},new_string:{type:"string",description:"Replacement text"}},["uri","old_string","new_string"])},async call(e,t){const o=s(String(e.uri),t),r={old_string:String(e.old_string),new_string:String(e.new_string)},{decl:n,...i}=o;if(n.edit)return w(await n.edit(i,r))||"edited";n.read&&n.write||y(`resource \`${o.pattern}\` cannot be edited`),r.old_string||y("old_string is empty");const a=b(await n.read(i)),c=a.text.split(r.old_string).length-1;0===c&&y("old_string was not found in the current content; read it again"),c>1&&y(`old_string occurs ${c} times; give more context so it occurs exactly once`);const l={content:a.text.replace(r.old_string,(()=>r.new_string)),mode:"write"};return void 0!==a.version&&(l.ifVersion=a.version),w(await n.write(i,l))||"edited"}},exec:{spec:{description:`Run one command (not a shell: no pipes, redirects, ;, &, backquotes or $). Built in: ${g} — calls an action listed by read uri="/". The page's commands are listed there too; "<command> --help" shows a command's usage.`,args_schema:N({command:{type:"string",description:"One command line"}},["command"])},idempotent:e=>function(e,t,o,r){var n,s,i;let a;try{a=m(e)}catch{return!1}const[c,...l]=a;if("xcall"===c)try{const{object:e,action:r}=I(l),i=S(e,o),a=t.find((e=>T(e,i.origin,i.segments))),c=null==(s=null==(n=null==a?void 0:a.decl.actions)?void 0:n[r])?void 0:s.risk;return"read_only"===c||"idempotent_write"===c}catch{return!1}const u=c?r.get(c):void 0;return"read"===(null==(i=null==u?void 0:u.access)?void 0:i.level)}(String(e.command??""),o,r,n),call:(e,t)=>h(String(e.command),t)}}};
|
|
2
|
+
//# sourceMappingURL=xllm.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"xllm.cjs","sources":["../src/xllm/runtime/site.ts","../src/internal/command_args.ts","../src/xllm/runtime/site_tools.ts","../src/xllm/runtime/did_object_resources.ts","../src/xllm/hosts/browser/store.ts"],"sourcesContent":["// `createSiteRuntime`: a page turns the tools of one scene into an\n// AgentRuntime. The SDK ships no tools here; what the scene can do is the\n// page's own JS functions, so xllm never exceeds what the page's JS can do.\n//\n// descriptor: { kind: \"site\", runtime_id: \"site:<scene>\", host: null,\n// target: { origin, scene }, workdir: \"/\", capabilities: { tools: {}, network: true, os: \"browser\" } }\n// Neither the user agent nor the tool list is part of it: a browser update or\n// a new page tool must not make old runs unresumable, while a run of scene A\n// cannot be resumed in scene B (the descriptors differ).\n\nimport type { AiToolCall, EffectiveTools, ResolvedTool, RuntimeConfig, RuntimeDescriptor, RuntimeInfo, ToolSource, ToolsConfig } from '../core/types'\nimport { XllmError } from '../core/errors'\nimport { describeToolSource, shellSettings, taskWaitMs } from '../core/config'\nimport type { AgentRuntime, OpenedTools, RunBinding, RuntimeOpenCtx, SiteTool } from './types'\nimport { unresolvedReason } from './types'\nimport { SiteToolManager } from './site_manager'\n\nexport const SITE_RUNTIME_KIND = 'site'\n\nconst TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/\n\nexport interface SiteRuntimeOptions {\n /** The scene name, e.g. `aiws.wish`: part of the runtime's identity. */\n scene: string\n /** The page's origin (passed in: the runtime never reads `location`). */\n origin: string\n hostname: string\n /** Every tool of this scene. */\n tools: Record<string, SiteTool>\n /** What `{{env.NAME}}` may read. */\n env?: Record<string, string>\n /** `runtime.task_wait_ms` (in-call wait budget for tasks, M2). */\n task_wait_ms?: number\n}\n\nexport interface SiteRuntime extends AgentRuntime {\n readonly scene: string\n /** The scene's tools, by name. */\n readonly tools: ReadonlyMap<string, SiteTool>\n}\n\nfunction resolveTool(name: string, tool: SiteTool, source: string): ResolvedTool {\n return { name, description: tool.spec.description, args_schema: tool.spec.args_schema, source }\n}\n\nfunction namedSources(cfg: ToolSource[] | undefined, field: string): string[] {\n return (cfg ?? []).map(s => {\n if (s.kind !== 'named') {\n throw XllmError.capability(`${field}: \\`${describeToolSource(s)}\\` is not available in a site runtime; only the page's tools can be named`)\n }\n return s.name\n })\n}\n\nexport function createSiteRuntime(options: SiteRuntimeOptions): SiteRuntime {\n const scene = options.scene?.trim()\n if (!scene) throw XllmError.input('createSiteRuntime: `scene` is required')\n if (!options.origin) throw XllmError.input('createSiteRuntime: `origin` is required')\n const tools = new Map<string, SiteTool>()\n for (const [name, tool] of Object.entries(options.tools ?? {})) {\n if (!TOOL_NAME.test(name)) throw XllmError.tools(`site tool name \\`${name}\\` must match ${TOOL_NAME}`)\n if (!tool || typeof tool.call !== 'function' || !tool.spec) throw XllmError.tools(`site tool \\`${name}\\` needs \\`spec\\` and \\`call\\``)\n tools.set(name, tool)\n }\n const env = { ...(options.env ?? {}) }\n const descriptor: RuntimeDescriptor = {\n runtime_id: `site:${scene}`,\n kind: SITE_RUNTIME_KIND,\n host: null,\n target: { origin: options.origin, scene },\n workdir: '/',\n capabilities: { tools: {}, network: true, os: 'browser' },\n }\n const config: RuntimeConfig = { kind: SITE_RUNTIME_KIND, env: {} }\n if (options.task_wait_ms !== undefined) config.task_wait_ms = options.task_wait_ms\n\n const runtime: SiteRuntime = {\n scene,\n tools,\n descriptor: () => JSON.parse(JSON.stringify(descriptor)),\n config: () => JSON.parse(JSON.stringify(config)),\n async info(): Promise<RuntimeInfo> {\n let timezone = ''\n try {\n timezone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? ''\n } catch {\n timezone = ''\n }\n return {\n id: descriptor.runtime_id, kind: SITE_RUNTIME_KIND, os: 'browser', arch: '', hostname: options.hostname, shell: '',\n cwd: '/', tools: [], current_time: new Date().toISOString(), timezone, target: descriptor.target,\n platform: 'browser', shell_kind: '', baseline: '',\n }\n },\n async open(ctx: RuntimeOpenCtx, cfg: ToolsConfig): Promise<OpenedTools> {\n const enabled = cfg.enabled ?? false\n const tools2actions = cfg.tools2actions ?? false\n if (ctx.loop_model === 'function_call' && (tools2actions || (cfg.actions ?? []).length > 0)) {\n throw XllmError.capability('actions / tools2actions need loop_model behavior')\n }\n const pick = (names: string[], field: string): ResolvedTool[] => names.map(name => {\n const tool = tools.get(name)\n if (!tool) {\n throw XllmError.capability(`${field}: \\`${name}\\` is not a tool of scene \\`${scene}\\` (scene tools: ${[...tools.keys()].join(', ') || 'none'})`)\n }\n return resolveTool(name, tool, `name:${name}`)\n })\n let native: ResolvedTool[] = []\n let actions: ResolvedTool[] = []\n const toolSources = cfg.tools ?? []\n const actionSources = cfg.actions ?? []\n if (enabled) {\n const toolNames = cfg.tools === undefined ? [...tools.keys()] : namedSources(cfg.tools, 'tools.tools')\n native = pick(toolNames, 'tools.tools')\n actions = pick(namedSources(cfg.actions, 'tools.actions'), 'tools.actions')\n if (tools2actions) {\n actions = [...actions, ...native.filter(t => !actions.some(a => a.name === t.name))]\n native = []\n }\n }\n const selected = new Map<string, SiteTool>()\n for (const t of [...native, ...actions]) selected.set(t.name, tools.get(t.name) as SiteTool)\n const effective: EffectiveTools = {\n enabled,\n filesystem_policy: cfg.filesystem_policy ?? 'workspace',\n tools2actions,\n tool_sources: cfg.tools === undefined && enabled ? native.map(t => ({ kind: 'named', name: t.name })) : toolSources,\n action_sources: actionSources,\n native,\n actions,\n bash_tools: [],\n shell: shellSettings(cfg.shell, taskWaitMs(config)),\n exec_enabled: false,\n sources: { ...ctx.sources },\n }\n return { tools: effective, manager: new SiteToolManager(selected, { tasks: ctx.tasks, taskWaitMs: ctx.task_wait_ms }) }\n },\n async describeInterrupted(run: RunBinding, call: AiToolCall): Promise<string> {\n const tool = tools.get(call.name)\n if (tool?.describeInterrupted) {\n try {\n return await tool.describeInterrupted(call.args ?? {}, { run_id: run.run_id, call_id: call.call_id, signal: new AbortController().signal })\n } catch (e) {\n return `${unresolvedReason(call.name)} (describing it failed: ${e instanceof Error ? e.message : String(e)})`\n }\n }\n return unresolvedReason(call.name)\n },\n env: (name: string) => env[name],\n }\n return runtime\n}\n","// Command-line parsing shared by the `buckyos` CLI (`cli/core/argv.ts`,\n// `cli/core/command.ts`) and the xllm site tools' `exec`. Self-contained on\n// purpose: the CLI imports it by relative path. Errors carry the CLI's usage\n// codes; the CLI turns them into its `UsageError`.\n\nexport type JsonSchema = {\n type?: 'object' | 'array' | 'string' | 'boolean' | 'integer' | 'number' | 'null'\n title?: string\n description?: string\n properties?: Record<string, JsonSchema>\n required?: string[]\n additionalProperties?: boolean\n items?: JsonSchema\n enum?: unknown[]\n minLength?: number\n minimum?: number\n default?: unknown\n secret?: boolean\n}\n\nexport interface PositionalDefinition {\n name: string\n description: string\n required?: boolean\n}\n\nexport interface OptionDefinition {\n name: string\n property?: string\n description: string\n type: 'string' | 'boolean' | 'integer' | 'number'\n required?: boolean\n secret?: boolean\n enum?: string[]\n}\n\nexport type AccessLevel = 'read' | 'write' | 'destructive' | 'privileged'\n\n/** A usage error with the CLI's code (`UNKNOWN_OPTION`, `SCHEMA_VALIDATION_FAILED`, …). */\nexport class CommandArgsError extends Error {\n readonly code: string\n\n constructor(code: string, message: string) {\n super(message)\n this.name = 'CommandArgsError'\n this.code = code\n }\n}\n\nfunction hasOwn(o: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(o, key)\n}\n\nexport function optionProperty(option: OptionDefinition): string {\n return option.property ?? option.name.split('-').join('_')\n}\n\nexport interface LongOption {\n name: string\n inlineValue?: string\n}\n\nexport function splitLongOption(token: string): LongOption {\n const content = token.slice(2)\n const equalIndex = content.indexOf('=')\n return equalIndex < 0 ? { name: content } : { name: content.slice(0, equalIndex), inlineValue: content.slice(equalIndex + 1) }\n}\n\nexport function readOptionValue(argv: string[], index: number, option: LongOption): { value: string; consumed: number } {\n if (option.inlineValue !== undefined) {\n if (!option.inlineValue) throw new CommandArgsError('MISSING_ARGUMENT', `--${option.name} requires a value`)\n return { value: option.inlineValue, consumed: 1 }\n }\n const value = argv[index + 1]\n if (value === undefined || value.startsWith('--')) throw new CommandArgsError('MISSING_ARGUMENT', `--${option.name} requires a value`)\n return { value, consumed: 2 }\n}\n\nfunction parseOptionValue(type: string, value: string, name: string): unknown {\n if (type === 'string') return value\n const number = Number(value)\n if (!Number.isFinite(number) || (type === 'integer' && !Number.isInteger(number))) {\n throw new CommandArgsError('INVALID_ARGUMENT', `--${name} requires a ${type}`)\n }\n return number\n}\n\nfunction assignPositional(input: Record<string, unknown>, positionals: PositionalDefinition[], index: number, value: string): number {\n const positional = positionals[index]\n if (!positional) throw new CommandArgsError('TOO_MANY_ARGUMENTS', `unexpected positional argument: ${value}`)\n input[positional.name] = value\n return index + 1\n}\n\nexport interface ArgvSpec {\n positionals?: PositionalDefinition[]\n options?: OptionDefinition[]\n}\n\n/**\n * Looks at every long option before the command's own: the CLI handles its\n * interactive session options here. Return how many tokens it consumed, or\n * `undefined` to leave the option to the command.\n */\nexport type LongOptionHook = (option: LongOption, argv: string[], index: number) => number | undefined\n\n/** Positionals, `--opt value` / `--opt=value`, boolean options, `--`; `--help` / `-h` sets `help`. */\nexport function parseArgv(spec: ArgvSpec, argv: string[], beforeOption?: LongOptionHook): {\n input: Record<string, unknown>\n help: boolean\n positionalCount: number\n} {\n const input: Record<string, unknown> = {}\n const positionals = spec.positionals ?? []\n const optionByName = new Map((spec.options ?? []).map(o => [o.name, o]))\n let positionalIndex = 0\n let help = false\n for (let index = 0; index < argv.length;) {\n const token = argv[index]\n if (token === '--help' || token === '-h') {\n help = true\n index += 1\n continue\n }\n if (token === '--') {\n for (const value of argv.slice(index + 1)) positionalIndex = assignPositional(input, positionals, positionalIndex, value)\n break\n }\n if (!token.startsWith('--')) {\n positionalIndex = assignPositional(input, positionals, positionalIndex, token)\n index += 1\n continue\n }\n const parsed = splitLongOption(token)\n const handled = beforeOption?.(parsed, argv, index)\n if (handled !== undefined) {\n index += handled\n continue\n }\n const option = optionByName.get(parsed.name)\n if (!option) throw new CommandArgsError('UNKNOWN_OPTION', `unknown option: --${parsed.name}`)\n const property = optionProperty(option)\n if (hasOwn(input, property)) throw new CommandArgsError('DUPLICATE_ARGUMENT', `argument provided more than once: ${property}`)\n if (option.type === 'boolean') {\n if (parsed.inlineValue !== undefined) throw new CommandArgsError('INVALID_ARGUMENT', `--${parsed.name} does not accept a value`)\n input[property] = true\n index += 1\n continue\n }\n const { value, consumed } = readOptionValue(argv, index, parsed)\n input[property] = parseOptionValue(option.type, value, parsed.name)\n index += consumed\n }\n return { input, help, positionalCount: positionalIndex }\n}\n\n/** Required positionals after `positionalCount` must be in `inputObject`. */\nexport function checkRequiredPositionals(positionals: PositionalDefinition[], positionalCount: number, inputObject: Record<string, unknown> | undefined) {\n for (let index = positionalCount; index < positionals.length; index++) {\n if (positionals[index].required !== false && !hasOwn(inputObject ?? {}, positionals[index].name)) {\n throw new CommandArgsError('MISSING_ARGUMENT', `missing positional argument: ${positionals[index].name}`)\n }\n }\n}\n\nexport function mergeCommandInput(inputObject: Record<string, unknown> | undefined, cliInput: Record<string, unknown>): Record<string, unknown> {\n const result = { ...(inputObject ?? {}) }\n for (const [key, value] of Object.entries(cliInput)) {\n if (hasOwn(result, key)) throw new CommandArgsError('ARGUMENT_CONFLICT', `${key} is present in both --input and argv`)\n result[key] = value\n }\n return result\n}\n\n/** Split a command line into words: single and double quotes, backslash escapes (not inside single quotes). */\nexport function parseShellLine(line: string): string[] {\n const tokens: string[] = []\n let current = ''\n let quote: 'single' | 'double' | null = null\n let escaped = false\n let started = false\n for (const character of line) {\n if (escaped) {\n current += character\n escaped = false\n started = true\n continue\n }\n if (character === '\\\\' && quote !== 'single') {\n escaped = true\n started = true\n continue\n }\n if (quote === 'single') {\n if (character === \"'\") quote = null\n else current += character\n continue\n }\n if (quote === 'double') {\n if (character === '\"') quote = null\n else current += character\n continue\n }\n if (character === \"'\") {\n quote = 'single'\n started = true\n continue\n }\n if (character === '\"') {\n quote = 'double'\n started = true\n continue\n }\n if (/\\s/.test(character)) {\n if (started) {\n tokens.push(current)\n current = ''\n started = false\n }\n continue\n }\n current += character\n started = true\n }\n if (escaped) throw new CommandArgsError('INVALID_COMMAND_LINE', 'unfinished escape sequence')\n if (quote) throw new CommandArgsError('INVALID_COMMAND_LINE', `unterminated ${quote} quote`)\n if (started) tokens.push(current)\n return tokens\n}\n\nexport function validateSchema(value: unknown, schema: JsonSchema, path: string): void {\n if (schema.enum && !schema.enum.some(candidate => Object.is(candidate, value))) {\n throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be one of ${schema.enum.join(', ')}`)\n }\n if (schema.type === 'object') {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be an object`)\n const object = value as Record<string, unknown>\n for (const required of schema.required ?? []) {\n if (!hasOwn(object, required)) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path}.${required} is required`)\n }\n if (schema.additionalProperties === false) {\n for (const key of Object.keys(object)) {\n if (!hasOwn(schema.properties ?? {}, key)) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path}.${key} is not allowed`)\n }\n }\n for (const [key, propertyValue] of Object.entries(object)) {\n const propertySchema = schema.properties?.[key]\n if (propertySchema) validateSchema(propertyValue, propertySchema, `${path}.${key}`)\n }\n return\n }\n if (schema.type === 'array') {\n if (!Array.isArray(value)) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be an array`)\n const items = schema.items\n if (items) value.forEach((item, index) => validateSchema(item, items, `${path}[${index}]`))\n return\n }\n if (schema.type === 'string') {\n if (typeof value !== 'string') throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be a string`)\n if (schema.minLength !== undefined && value.length < schema.minLength) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} is too short`)\n return\n }\n if (schema.type === 'boolean' && typeof value !== 'boolean') throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be a boolean`)\n if (schema.type === 'integer' && (!Number.isInteger(value) || typeof value !== 'number')) {\n throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be an integer`)\n }\n if (schema.type === 'number' && typeof value !== 'number') throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be a number`)\n}\n","// Optional basic tools for a site (TODO §2.1, a trial): what `bash_core`'s four\n// tools are for files, `read` / `write` / `edit` / `exec` are for a page's\n// resources and commands. REST semantics: read = GET (a collection's read is\n// its list, filter with a query), write = PUT, edit = PATCH; everything REST\n// cannot say is a command run by `exec` — `xcall <object> <action>` for the\n// actions declared on resources (DID Object style, with `risk`), and the\n// page's own commands. The four specs are fixed: more resources and commands\n// cost no tokens per round. Every resource, action and command is declared by\n// the page; nothing is forwarded to `fetch` or turned into a raw RPC.\n\nimport type { JsonValue } from '../core/types'\nimport { isObject } from '../core/json'\nimport { validateJson } from '../core/json_check'\nimport { utf8Length } from '../core/tokenizer'\nimport type { SiteTool, SiteToolCtx } from './types'\nimport {\n CommandArgsError, parseArgv, parseShellLine, validateSchema,\n} from '../../internal/command_args'\nimport type { AccessLevel, JsonSchema, OptionDefinition, PositionalDefinition } from '../../internal/command_args'\n\nexport type ActionRisk = 'read_only' | 'idempotent_write' | 'write' | 'destructive' | 'admin'\nexport const ACTION_RISKS: ActionRisk[] = ['read_only', 'idempotent_write', 'write', 'destructive', 'admin']\n\nexport const XCALL_USAGE = 'xcall <object> <action> [--params <json>] [key=value ...] [--key=value ...]'\n/** Result text cap of `read` (one page) and `exec`. */\nexport const MAX_RESULT_BYTES = 64 * 1024\n\n/** What a resource method gets: the URI as normalized, the `{name}` parameters, the query. */\nexport interface ResourceMatch {\n uri: string\n pattern: string\n params: Record<string, string>\n query: URLSearchParams\n ctx: SiteToolCtx\n}\n\n/** A read may return a version: `write` (and the default `edit`) gets it back as `ifVersion`. */\nexport interface Versioned {\n content: unknown\n version?: string\n}\n\nexport interface WriteBody {\n content: string\n mode: 'write' | 'new' | 'append'\n ifVersion?: string\n}\n\nexport interface ActionDecl {\n description: string\n risk: ActionRisk\n /** JSON Schema of the params. */\n input?: JsonValue\n call(m: ResourceMatch, params: Record<string, JsonValue>): unknown\n}\n\nexport interface ResourceDecl {\n description: string\n read?(m: ResourceMatch): unknown\n write?(m: ResourceMatch, body: WriteBody): unknown\n edit?(m: ResourceMatch, body: { old_string: string; new_string: string }): unknown\n actions?: Record<string, ActionDecl>\n}\n\n/** A page command: a subset of the CLI `CommandDefinition`; `call(input)` replaces its handler. */\nexport interface CommandDecl {\n summary: string\n description?: string\n positionals?: PositionalDefinition[]\n options?: OptionDefinition[]\n inputSchema?: JsonSchema\n access?: { mode: 'fixed'; level: AccessLevel }\n examples?: string[]\n call(input: Record<string, unknown>, ctx: SiteToolCtx): unknown\n}\n\nexport interface SiteToolsOptions {\n resources?: Record<string, ResourceDecl>\n commands?: Record<string, CommandDecl>\n}\n\nconst LOCAL_BASE = 'site://page/'\nconst SHELL_CHARS = /[|;&><`$]/\n\ninterface Pattern {\n raw: string\n origin?: string\n segments: string[]\n decl: ResourceDecl\n}\n\nfunction parsePattern(raw: string, decl: ResourceDecl): Pattern {\n const i = raw.indexOf('://')\n if (i >= 0) {\n const rest = raw.slice(i + 3)\n const slash = rest.indexOf('/')\n const host = slash < 0 ? rest : rest.slice(0, slash)\n const path = slash < 0 ? '' : rest.slice(slash + 1)\n return { raw, origin: `${raw.slice(0, i).toLowerCase()}://${host.toLowerCase()}`, segments: path ? path.split('/') : [], decl }\n }\n const path = raw.replace(/^\\/+/, '').replace(/\\/+$/, '')\n return { raw, segments: path ? path.split('/') : [], decl }\n}\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n\n/** Normalize a URI the model gave: relative paths and declared absolute origins only, no `..`, no encoded separators. */\nexport function normalizeUri(uri: string, origins: Set<string>): { origin?: string; segments: string[]; query: URLSearchParams; text: string } {\n const raw = uri.trim()\n if (!raw) fail('uri is empty')\n const absolute = /^[A-Za-z][A-Za-z0-9+.-]*:/.test(raw)\n let url: URL\n try {\n url = absolute ? new URL(raw) : new URL(raw.replace(/^\\/+/, ''), LOCAL_BASE)\n } catch {\n fail(`invalid uri \\`${raw}\\``)\n }\n let origin: string | undefined\n if (absolute) {\n origin = `${url.protocol.slice(0, -1).toLowerCase()}://${url.host.toLowerCase()}`\n if (!origins.has(origin)) fail(`uri \\`${raw}\\` is not a resource of this page (absolute URIs are limited to the declared ones)`)\n } else if (url.protocol !== 'site:' || url.host !== 'page') {\n fail(`uri \\`${raw}\\` is not a resource of this page`)\n }\n const segments: string[] = []\n for (const part of url.pathname.split('/')) {\n if (part === '') continue\n let decoded: string\n try {\n decoded = decodeURIComponent(part)\n } catch {\n fail(`invalid uri \\`${raw}\\``)\n }\n if (decoded === '..' || decoded === '.' || decoded.includes('/') || decoded.includes('\\\\')) fail(`uri \\`${raw}\\` is not a resource of this page`)\n segments.push(decoded)\n }\n const text = (origin ? `${origin}/` : '') + segments.join('/') + (url.search || '')\n return { origin, segments, query: url.searchParams, text }\n}\n\nfunction matchPattern(p: Pattern, origin: string | undefined, segments: string[]): Record<string, string> | undefined {\n if (p.origin !== origin || p.segments.length !== segments.length) return undefined\n const params: Record<string, string> = {}\n for (let i = 0; i < segments.length; i++) {\n const s = p.segments[i]\n if (s.startsWith('{') && s.endsWith('}')) params[s.slice(1, -1)] = segments[i]\n else if (s !== segments[i]) return undefined\n }\n return params\n}\n\nfunction asText(value: unknown): string {\n if (value === undefined || value === null) return ''\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value, null, 2)\n } catch {\n return String(value)\n }\n}\n\nfunction versioned(value: unknown): { text: string; version?: string } {\n if (isObject(value) && 'content' in value && Object.keys(value).every(k => k === 'content' || k === 'version')) {\n const version = value.version\n return { text: asText(value.content), version: typeof version === 'string' ? version : version === undefined ? undefined : String(version) }\n }\n return { text: asText(value) }\n}\n\nfunction clipBytes(text: string, max: number): { text: string; clipped: boolean } {\n if (utf8Length(text) <= max) return { text, clipped: false }\n let out = ''\n let bytes = 0\n for (const ch of text) {\n const n = utf8Length(ch)\n if (bytes + n > max) break\n out += ch\n bytes += n\n }\n return { text: out, clipped: true }\n}\n\n/** One page of a text by lines: `offset` is the 1-based first line. */\nexport function pageText(text: string, offset = 1, limit?: number): string {\n const lines = text.split('\\n')\n const start = Math.max(1, Math.floor(offset))\n if (start > lines.length && !(start === 1 && lines.length === 1)) return `[offset ${start} is past the end: ${lines.length} lines]`\n const wanted = limit === undefined ? lines.length : Math.max(1, Math.floor(limit))\n const out: string[] = []\n let bytes = 0\n let i = start - 1\n for (; i < lines.length && out.length < wanted; i++) {\n const n = utf8Length(lines[i]) + 1\n if (out.length > 0 && bytes + n > MAX_RESULT_BYTES) break\n out.push(lines[i])\n bytes += n\n }\n let body = out.join('\\n')\n if (out.length === 1 && utf8Length(body) > MAX_RESULT_BYTES) body = clipBytes(body, MAX_RESULT_BYTES).text + ' …'\n if (i < lines.length) body += `\\n[lines ${start}–${i} of ${lines.length}; read on with offset=${i + 1}]`\n return body\n}\n\nfunction parseScalar(raw: string): JsonValue {\n const v = raw.trim()\n if (v === 'true') return true\n if (v === 'false') return false\n if (v === 'null') return null\n if (/^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(v)) return Number(v)\n if (v.startsWith('{') || v.startsWith('[')) {\n try {\n return JSON.parse(v)\n } catch {\n return v\n }\n }\n return v\n}\n\nconst UNSUPPORTED_XCALL_KEYS = ['config', 'route-config', 'session-id', 'session_id', 'idempotency-key', 'idempotency_key',\n 'confirm-token', 'confirm_token', 'trace-id', 'trace_id']\n\n/** `xcall` arguments as Rust parses them (`parse_object_x_call_cli_command`), minus routing and confirmation flags. */\nfunction parseXcall(tokens: string[]): { object: string; action: string; params: Record<string, JsonValue> } {\n let object: string | undefined\n let action: string | undefined\n let params: JsonValue = {}\n const pairs: Record<string, JsonValue> = {}\n const positionals: string[] = []\n const json = (raw: string, name: string): JsonValue => {\n try {\n return JSON.parse(raw)\n } catch (e) {\n fail(`invalid \\`${name}\\` JSON value \\`${raw}\\`: ${e instanceof Error ? e.message : String(e)}\\nusage: ${XCALL_USAGE}`)\n }\n }\n const unsupported = (t: string): never => fail(`unsupported flag \\`${t}\\` (routing and confirmation are the page's)\\nusage: ${XCALL_USAGE}`)\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i]\n if (t === '--params') {\n const v = tokens[++i]\n if (v === undefined) fail(`missing value for --params\\nusage: ${XCALL_USAGE}`)\n params = json(v, '--params')\n } else if (t.startsWith('--')) {\n const eq = t.indexOf('=')\n if (eq < 0) unsupported(t)\n const key = t.slice(2, eq)\n const value = t.slice(eq + 1)\n if (key === 'params') params = json(value, '--params')\n else if (!key.trim() || key.startsWith('-') || UNSUPPORTED_XCALL_KEYS.includes(key)) unsupported(t)\n else pairs[key] = parseScalar(value)\n } else if (t.includes('=')) {\n const eq = t.indexOf('=')\n const key = t.slice(0, eq)\n const value = t.slice(eq + 1)\n if (key === 'object') object = value\n else if (key === 'action') action = value\n else if (key === 'params') params = json(value, 'params')\n else if (UNSUPPORTED_XCALL_KEYS.includes(key)) unsupported(t)\n else pairs[key] = parseScalar(value)\n } else {\n positionals.push(t)\n }\n }\n object = object ?? positionals[0]\n action = action ?? positionals[1]\n if (positionals[2] !== undefined) params = json(positionals[2], 'params')\n if (positionals.length > 3) fail(`unexpected positional argument \\`${positionals[3]}\\`\\nusage: ${XCALL_USAGE}`)\n if (Object.keys(pairs).length) {\n if (!isObject(params)) fail(`key=value params require object params\\nusage: ${XCALL_USAGE}`)\n params = { ...params, ...pairs }\n }\n if (!object || !action) fail(`xcall needs an object and an action\\nusage: ${XCALL_USAGE}`)\n if (!isObject(params)) fail(`params must be a JSON object\\nusage: ${XCALL_USAGE}`)\n return { object, action, params }\n}\n\nfunction commandUsage(name: string, c: CommandDecl): string {\n const lines = [`${name} — ${c.summary}`]\n if (c.description) lines.push('', c.description)\n const pos = (c.positionals ?? []).map(p => (p.required === false ? `[${p.name}]` : `<${p.name}>`)).join(' ')\n lines.push('', `usage: ${name}${pos ? ` ${pos}` : ''}${(c.options ?? []).length ? ' [options]' : ''}`)\n for (const p of c.positionals ?? []) lines.push(` ${p.name} ${p.description}`)\n if ((c.options ?? []).length) lines.push('options:')\n for (const o of c.options ?? []) {\n lines.push(` --${o.name}${o.type === 'boolean' ? '' : ` <${o.type}>`}${o.required ? ' (required)' : ''} ${o.description}${o.enum ? ` (${o.enum.join(' | ')})` : ''}`)\n }\n if (c.examples?.length) {\n lines.push('examples:')\n for (const e of c.examples) lines.push(` ${e}`)\n }\n return lines.join('\\n')\n}\n\nconst OBJECT_ARGS = (props: Record<string, JsonValue>, required: string[]): JsonValue => ({ type: 'object', properties: props, required })\n\n/**\n * The four basic tools over the page's resources and commands. Spread them\n * into `createSiteRuntime({ tools })`, alongside named tools if wanted.\n */\nexport function siteTools(options: SiteToolsOptions): Record<string, SiteTool> {\n const patterns = Object.entries(options.resources ?? {}).map(([raw, decl]) => parsePattern(raw, decl))\n const origins = new Set(patterns.map(p => p.origin).filter((o): o is string => o !== undefined))\n const commands = new Map(Object.entries(options.commands ?? {}))\n if (commands.has('xcall')) throw new Error('siteTools: `xcall` is built in; declare actions on resources instead')\n\n const resolve = (uri: string, ctx: SiteToolCtx): ResourceMatch & { decl: ResourceDecl } => {\n const n = normalizeUri(uri, origins)\n for (const p of patterns) {\n const params = matchPattern(p, n.origin, n.segments)\n if (params) return { uri: n.text, pattern: p.raw, params, query: n.query, ctx, decl: p.decl }\n }\n fail(`uri \\`${uri}\\` is not a resource of this page; read uri=\"/\" lists them`)\n }\n\n const discovery = (): string => {\n const lines = ['Resources (read uri=\"<resource>\"; {name} is one path segment):']\n for (const p of patterns) {\n const methods = (['read', 'write', 'edit'] as const).filter(m => m === 'edit' ? !!(p.decl.edit || (p.decl.read && p.decl.write)) : !!p.decl[m])\n lines.push(`- ${p.raw} — ${p.decl.description} [${methods.join(', ') || 'no methods'}]`)\n for (const [name, a] of Object.entries(p.decl.actions ?? {})) lines.push(` action ${name} (risk: ${a.risk}) — ${a.description}`)\n }\n if (patterns.length === 0) lines.push('(none)')\n lines.push('', 'Commands (exec \"<command> --help\" for usage):')\n lines.push(`- xcall — call an action of a resource: ${XCALL_USAGE}`)\n for (const [name, c] of commands) lines.push(`- ${name} — ${c.summary}`)\n return lines.join('\\n')\n }\n\n const exec = async (command: string, ctx: SiteToolCtx): Promise<string> => {\n const words = (() => {\n try {\n return parseShellLine(command)\n } catch (e) {\n fail(`${e instanceof Error ? e.message : String(e)}; exec runs one command, it is not a shell`)\n }\n })()\n const available = `available commands: xcall${commands.size ? `, ${[...commands.keys()].join(', ')}` : ''}`\n const unquoted = command.replace(/'[^']*'|\"(?:[^\"\\\\]|\\\\.)*\"/g, '')\n if (SHELL_CHARS.test(unquoted)) {\n fail(`exec runs exactly one command and is not a shell: pipes, redirects, \\`;\\`, \\`&\\`, backquotes and \\`$\\` are not supported (quote them to pass them as text). ${available}`)\n }\n const [name, ...args] = words\n if (!name) fail(`empty command; ${available}`)\n if (name === 'xcall') {\n if (args.includes('--help') || args.includes('-h')) return `usage: ${XCALL_USAGE}\\nThe actions of each resource are listed by read uri=\"/\".`\n const { object, action, params } = parseXcall(args)\n const m = resolve(object, ctx)\n const decl = m.decl.actions?.[action]\n if (!decl) {\n const known = Object.keys(m.decl.actions ?? {})\n fail(`resource \\`${m.pattern}\\` has no action \\`${action}\\` (actions: ${known.length ? known.join(', ') : 'none'})`)\n }\n if (decl.input !== undefined) {\n const invalid = validateJson(decl.input, params)\n if (invalid) fail(`invalid params for ${action}: ${invalid}`)\n }\n const { decl: _decl, ...match } = m\n void _decl\n const result = await decl.call(match, params)\n return `[risk: ${decl.risk}]\\n${clipBytes(asText(result) || 'ok', MAX_RESULT_BYTES).text}`\n }\n const c = commands.get(name)\n if (!c) fail(`unknown command \\`${name}\\`; exec runs one command, it is not a shell. ${available}`)\n let input: Record<string, unknown>\n try {\n const parsed = parseArgv({ positionals: c.positionals, options: c.options }, args)\n if (parsed.help) return commandUsage(name, c)\n for (let i = parsed.positionalCount; i < (c.positionals ?? []).length; i++) {\n if ((c.positionals ?? [])[i].required !== false) throw new CommandArgsError('MISSING_ARGUMENT', `missing positional argument: ${(c.positionals ?? [])[i].name}`)\n }\n for (const o of c.options ?? []) {\n const prop = o.property ?? o.name.split('-').join('_')\n if (o.required && !(prop in parsed.input)) throw new CommandArgsError('MISSING_ARGUMENT', `--${o.name} is required`)\n }\n input = parsed.input\n if (c.inputSchema) validateSchema(input, c.inputSchema, 'input')\n } catch (e) {\n if (e instanceof CommandArgsError) fail(`${name}: ${e.message}\\n\\n${commandUsage(name, c)}`)\n throw e\n }\n return clipBytes(asText(await c.call(input, ctx)) || 'ok', MAX_RESULT_BYTES).text\n }\n\n const readRaw = async (m: ResourceMatch & { decl: ResourceDecl }) => {\n if (!m.decl.read) fail(`resource \\`${m.pattern}\\` cannot be read`)\n const { decl: _d, ...match } = m\n void _d\n return versioned(await m.decl.read(match))\n }\n\n return {\n read: {\n spec: {\n description: 'Read a resource of this page by URI (GET). Start with uri \"/\": it lists the resources, their actions (with risk) and the commands. A collection\\'s read is its list; filter and page with a query (notes?tag=x). Text comes in pages of lines: offset is the first line (1-based), limit the number of lines.',\n args_schema: OBJECT_ARGS({\n uri: { type: 'string', description: 'Resource URI, e.g. \"/\" or \"notes/1\"' },\n offset: { type: 'integer', description: 'First line, 1-based' },\n limit: { type: 'integer', description: 'Number of lines' },\n }, ['uri']),\n },\n idempotent: true,\n async call(args, ctx) {\n const uri = String(args.uri)\n const offset = typeof args.offset === 'number' ? args.offset : undefined\n const limit = typeof args.limit === 'number' ? args.limit : undefined\n if (uri.trim() === '/' || uri.trim() === '') return pageText(discovery(), offset, limit)\n const r = await readRaw(resolve(uri, ctx))\n return pageText(r.text, offset, limit)\n },\n },\n write: {\n spec: {\n description: 'Write a resource\\'s content (PUT). mode: \"write\" (default) replaces it, \"new\" only creates it and fails if it exists, \"append\" adds to its end. Use edit to change part of it.',\n args_schema: OBJECT_ARGS({\n uri: { type: 'string', description: 'Resource URI' },\n content: { type: 'string', description: 'The content' },\n mode: { type: 'string', enum: ['write', 'new', 'append'], description: 'write | new | append' },\n }, ['uri', 'content']),\n },\n async call(args, ctx) {\n const m = resolve(String(args.uri), ctx)\n if (!m.decl.write) fail(`resource \\`${m.pattern}\\` is read-only`)\n const { decl, ...match } = m\n const mode = (typeof args.mode === 'string' ? args.mode : 'write') as WriteBody['mode']\n return asText(await decl.write!(match, { content: String(args.content), mode })) || 'written'\n },\n },\n edit: {\n spec: {\n description: 'Change part of a resource (PATCH): old_string must occur exactly once in its current content and is replaced by new_string.',\n args_schema: OBJECT_ARGS({\n uri: { type: 'string', description: 'Resource URI' },\n old_string: { type: 'string', description: 'Text to replace; must occur exactly once' },\n new_string: { type: 'string', description: 'Replacement text' },\n }, ['uri', 'old_string', 'new_string']),\n },\n async call(args, ctx) {\n const m = resolve(String(args.uri), ctx)\n const body = { old_string: String(args.old_string), new_string: String(args.new_string) }\n const { decl, ...match } = m\n if (decl.edit) return asText(await decl.edit(match, body)) || 'edited'\n if (!decl.read || !decl.write) fail(`resource \\`${m.pattern}\\` cannot be edited`)\n if (!body.old_string) fail('old_string is empty')\n const current = versioned(await decl.read(match))\n const count = current.text.split(body.old_string).length - 1\n if (count === 0) fail('old_string was not found in the current content; read it again')\n if (count > 1) fail(`old_string occurs ${count} times; give more context so it occurs exactly once`)\n const content = current.text.replace(body.old_string, () => body.new_string)\n const w: WriteBody = { content, mode: 'write' }\n if (current.version !== undefined) w.ifVersion = current.version\n return asText(await decl.write(match, w)) || 'edited'\n },\n },\n exec: {\n spec: {\n description: `Run one command (not a shell: no pipes, redirects, ;, &, backquotes or $). Built in: ${XCALL_USAGE} — calls an action listed by read uri=\"/\". The page's commands are listed there too; \"<command> --help\" shows a command's usage.`,\n args_schema: OBJECT_ARGS({ command: { type: 'string', description: 'One command line' } }, ['command']),\n },\n idempotent: (args: Record<string, JsonValue>) => execIsIdempotent(String(args.command ?? ''), patterns, origins, commands),\n call: (args, ctx) => exec(String(args.command), ctx),\n },\n }\n}\n\n/** Resume rule of `exec`: `xcall` re-runs `read_only` / `idempotent_write` actions, commands re-run at `access: read`. */\nfunction execIsIdempotent(command: string, patterns: Pattern[], origins: Set<string>, commands: Map<string, CommandDecl>): boolean {\n let words: string[]\n try {\n words = parseShellLine(command)\n } catch {\n return false\n }\n const [name, ...args] = words\n if (name === 'xcall') {\n try {\n const { object, action } = parseXcall(args)\n const n = normalizeUri(object, origins)\n const p = patterns.find(q => matchPattern(q, n.origin, n.segments))\n const risk = p?.decl.actions?.[action]?.risk\n return risk === 'read_only' || risk === 'idempotent_write'\n } catch {\n return false\n }\n }\n const c = name ? commands.get(name) : undefined\n return c?.access?.level === 'read'\n}\n\n","// `siteTools` resources from DID Objects a BuckyOS service already serves\n// (`KrpcObjectProvider`): for each root the page lists, its Profile decides\n// what the model can do — properties are read, an IndexTrait collection is\n// read with a query, actions become `xcall` actions with the Profile's\n// `x-buckyos:risk` (above `maxRisk` they are not exposed). What can be reached\n// is decided by the Profile and the roots, never by a URI the model gives.\n\nimport type { JsonValue } from '../core/types'\nimport { isObject } from '../core/json'\nimport type { DIDObjectClient } from '../../did_object_client'\nimport { ACTION_RISKS } from './site_tools'\nimport type { ActionDecl, ActionRisk, ResourceDecl, ResourceMatch } from './site_tools'\n\nexport const INDEX_TRAIT_URI = 'https://buckyos.org/traits/index@1'\n\n/** What `didObjectResources` needs of a DID Object client. */\nexport type DidObjectReader = Pick<DIDObjectClient, 'card' | 'profile' | 'readProperty' | 'invoke'>\n\nexport interface DidObjectResourcesOptions {\n client: DidObjectReader\n /** Object URLs (`obj://…`) the page lets the model reach. */\n roots: string[]\n /** Actions above this risk are not exposed (default `read_only`). */\n maxRisk?: ActionRisk\n}\n\nfunction text(v: JsonValue | undefined, key: string): string {\n return isObject(v) && typeof v[key] === 'string' ? (v[key] as string) : ''\n}\n\nfunction riskRank(r: string): number {\n const i = ACTION_RISKS.indexOf(r as ActionRisk)\n return i < 0 ? ACTION_RISKS.length : i\n}\n\n/** The object document a read shows (as `render_object_document` in agent-did-object-lib). */\nexport function renderObjectDocument(canonical: string, card: { id: string; alsoKnownAs?: string[] }, profile: JsonValue,\n summary: Record<string, JsonValue>): string {\n const lines = [`Object: ${canonical}`, `Object DID: ${card.id}`]\n const aliases = (card.alsoKnownAs ?? []).filter(a => a !== canonical)\n if (aliases.length) lines.push(`Also known as: ${aliases.join(', ')}`)\n for (const [label, key] of [['Title', 'title'], ['Description', 'description']]) {\n const v = text(profile, key)\n if (v) lines.push(`${label}: ${v}`)\n }\n for (const [section, key] of [['Properties', 'properties'], ['Actions', 'actions'], ['Events', 'events']]) {\n const entries = isObject(profile) ? profile[key] : undefined\n if (!isObject(entries) || Object.keys(entries).length === 0) continue\n lines.push(`${section}:`)\n for (const name of Object.keys(entries).sort()) {\n const e = entries[name]\n let line = `- ${name}`\n const d = text(e, 'description')\n if (d) line += `: ${d}`\n const risk = text(e, 'x-buckyos:risk')\n if (risk) line += ` (risk: ${risk})`\n lines.push(line)\n }\n }\n const names = Object.keys(summary)\n if (names.length) {\n lines.push('Summary:')\n for (const name of names) lines.push(`- ${name}:`, JSON.stringify(summary[name], null, 2))\n }\n return lines.join('\\n')\n}\n\nfunction isCollection(profile: JsonValue): boolean {\n const traits = isObject(profile) ? profile['x-buckyos:traits'] : undefined\n return Array.isArray(traits) && traits.includes(INDEX_TRAIT_URI)\n}\n\n/** Resources for `siteTools({ resources })` from the Profiles of `roots`. */\nexport async function didObjectResources(options: DidObjectResourcesOptions): Promise<Record<string, ResourceDecl>> {\n const maxRank = riskRank(options.maxRisk ?? 'read_only')\n const out: Record<string, ResourceDecl> = {}\n for (const root of options.roots) {\n const client = options.client\n const profile = await client.profile(root) as JsonValue\n const collection = isCollection(profile)\n const actions: Record<string, ActionDecl> = {}\n const declared = isObject(profile) && isObject(profile.actions) ? profile.actions : {}\n for (const [name, a] of Object.entries(declared)) {\n if (collection && (name === 'query' || name === 'page')) continue\n const risk = text(a, 'x-buckyos:risk') as ActionRisk\n if (riskRank(risk) > maxRank) continue\n const input = isObject(a) ? a.input : undefined\n actions[name] = {\n description: text(a, 'description'),\n risk,\n ...(input !== undefined && input !== null ? { input } : {}),\n call: (_m: ResourceMatch, params: Record<string, JsonValue>) => client.invoke(root, name, params),\n }\n }\n const description = [text(profile, 'title'), text(profile, 'description')].filter(Boolean).join(' — ') || root\n out[root] = {\n description: collection ? `${description} (a collection: read it with a query, ?cursor=… for the next page)` : description,\n actions,\n async read(m: ResourceMatch) {\n if (collection && [...m.query.keys()].length > 0) {\n const cursor = m.query.get('cursor')\n const pageSize = m.query.get('page_size')\n if (cursor) return client.invoke(root, 'page', { cursor, ...(pageSize ? { page_size: Number(pageSize) } : {}) })\n const query: Record<string, JsonValue> = {}\n for (const [k, v] of m.query) if (k !== 'page_size') query[k] = v\n return client.invoke(root, 'query', { query, ...(pageSize ? { page_size: Number(pageSize) } : {}) })\n }\n const card = await client.card(root)\n const props = isObject(profile) && isObject(profile.properties) ? Object.keys(profile.properties).filter(p => p !== 'index_schema') : []\n const listed = isObject(profile) && Array.isArray(profile['x-buckyos:summary_props'])\n ? (profile['x-buckyos:summary_props'] as JsonValue[]).filter((p): p is string => typeof p === 'string') : props\n const summary: Record<string, JsonValue> = {}\n for (const p of listed) summary[p] = await client.readProperty(root, p) as JsonValue\n return renderObjectDocument(root, { id: String(card.id), alsoKnownAs: card.alsoKnownAs }, profile, summary)\n },\n }\n }\n return out\n}\n","// A run store in the page's IndexedDB (database `xllm-runs`): run.json and\n// numbered snapshots as Rust lays them out, so a run survives a reload of the\n// page and resumes. The run lock is a Web Lock (`navigator.locks`) held while\n// an executor runs; without Web Locks the page is assumed to be the only tab.\n// Data read back is not trusted: `XllmRun.resume` checks it against the\n// page's runtime before anything runs.\n\nimport type { LLMContextSnapshot, RunRecord } from '../../core/types'\nimport { RUN_RECORD_VERSION, generateRunId } from '../../core/store'\nimport type { ExportedRun, RunLock, RunStore } from '../../core/store'\nimport { XllmError } from '../../core/errors'\n\nexport const XLLM_RUNS_DB = 'xllm-runs'\nconst RECORDS = 'records'\nconst SNAPSHOTS = 'snapshots'\n\nfunction req<T>(r: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n r.onsuccess = () => resolve(r.result)\n r.onerror = () => reject(r.error)\n })\n}\n\nfunction done(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve()\n tx.onerror = () => reject(tx.error)\n tx.onabort = () => reject(tx.error ?? new Error('transaction aborted'))\n })\n}\n\ninterface LockLike {\n request(name: string, options: { ifAvailable: boolean }, cb: (lock: unknown) => Promise<void>): Promise<void>\n query(): Promise<{ held?: { name?: string }[] }>\n}\n\nexport class IndexedDbRunStore implements RunStore {\n readonly persistent = true\n private db: Promise<IDBDatabase> | undefined\n private readonly localLocks = new Set<string>()\n\n constructor(private readonly options: { dbName?: string; idb?: IDBFactory; locks?: LockLike | null } = {}) {}\n\n private open(): Promise<IDBDatabase> {\n if (!this.db) {\n const factory = this.options.idb ?? globalThis.indexedDB\n if (!factory) return Promise.reject(XllmError.storage('IndexedDB is not available here'))\n const r = factory.open(this.options.dbName ?? XLLM_RUNS_DB, 1)\n r.onupgradeneeded = () => {\n const db = r.result\n if (!db.objectStoreNames.contains(RECORDS)) db.createObjectStore(RECORDS, { keyPath: 'run_id' })\n if (!db.objectStoreNames.contains(SNAPSHOTS)) db.createObjectStore(SNAPSHOTS)\n }\n this.db = req(r)\n }\n return this.db\n }\n\n private locks(): LockLike | undefined {\n if (this.options.locks === null) return undefined\n return this.options.locks ?? (globalThis.navigator as unknown as { locks?: LockLike } | undefined)?.locks\n }\n\n runsDir(): string | undefined {\n return undefined\n }\n\n runDir(): string | undefined {\n return undefined\n }\n\n async createRun(): Promise<string> {\n const db = await this.open()\n for (let i = 0; i < 8; i++) {\n const id = generateRunId()\n const existing = await req(db.transaction(RECORDS).objectStore(RECORDS).get(id))\n if (!existing) return id\n }\n throw XllmError.storage('cannot allocate a unique run id')\n }\n\n async writeRecord(record: RunRecord): Promise<void> {\n const db = await this.open()\n const tx = db.transaction(RECORDS, 'readwrite')\n tx.objectStore(RECORDS).put(JSON.parse(JSON.stringify(record)))\n await done(tx)\n }\n\n async readRecord(runId: string): Promise<RunRecord> {\n const db = await this.open()\n const rec = await req(db.transaction(RECORDS).objectStore(RECORDS).get(runId)) as RunRecord | undefined\n if (!rec) throw new XllmError({ kind: 'run_not_found', run_id: runId, runs_dir: `indexeddb:${this.options.dbName ?? XLLM_RUNS_DB}` })\n if (rec.version !== RUN_RECORD_VERSION) throw XllmError.notResumable(runId, 'unsupported run record version')\n return rec\n }\n\n async listRecords(): Promise<RunRecord[]> {\n const db = await this.open()\n return await req(db.transaction(RECORDS).objectStore(RECORDS).getAll()) as RunRecord[]\n }\n\n async putSnapshot(runId: string, snapshot: LLMContextSnapshot): Promise<number> {\n const db = await this.open()\n const tx = db.transaction(SNAPSHOTS, 'readwrite')\n const store = tx.objectStore(SNAPSHOTS)\n const keys = await req(store.getAllKeys(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER]))) as [string, number][]\n const next = keys.length ? Math.max(...keys.map(k => k[1])) + 1 : 1\n store.put(JSON.parse(JSON.stringify(snapshot)), [runId, next])\n await done(tx)\n return next\n }\n\n async getSnapshot(runId: string, idx: number): Promise<LLMContextSnapshot> {\n const db = await this.open()\n const s = await req(db.transaction(SNAPSHOTS).objectStore(SNAPSHOTS).get([runId, idx])) as LLMContextSnapshot | undefined\n if (!s) throw new XllmError({ kind: 'corrupted_run', run_id: runId, reason: `snapshot ${idx} missing` })\n return s\n }\n\n async listSnapshots(runId: string): Promise<number[]> {\n const db = await this.open()\n const keys = await req(db.transaction(SNAPSHOTS).objectStore(SNAPSHOTS)\n .getAllKeys(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER]))) as [string, number][]\n return keys.map(k => k[1]).sort((a, b) => a - b)\n }\n\n async lockRun(runId: string): Promise<RunLock | null> {\n const name = `xllm-run:${runId}`\n const locks = this.locks()\n if (!locks) {\n if (this.localLocks.has(name)) return null\n this.localLocks.add(name)\n return { release: () => { this.localLocks.delete(name) } }\n }\n return new Promise<RunLock | null>((resolve, reject) => {\n locks.request(name, { ifAvailable: true }, lock => {\n if (!lock) {\n resolve(null)\n return Promise.resolve()\n }\n return new Promise<void>(release => resolve({ release: () => release() }))\n }).catch(reject)\n })\n }\n\n async isRunLive(runId: string): Promise<boolean> {\n const name = `xllm-run:${runId}`\n const locks = this.locks()\n if (!locks) return this.localLocks.has(name)\n const state = await locks.query()\n return (state.held ?? []).some(l => l.name === name)\n }\n\n async removeRun(runId: string): Promise<void> {\n const db = await this.open()\n const tx = db.transaction([RECORDS, SNAPSHOTS], 'readwrite')\n tx.objectStore(RECORDS).delete(runId)\n tx.objectStore(SNAPSHOTS).delete(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER]))\n await done(tx)\n }\n\n async importRun(run: ExportedRun): Promise<void> {\n const db = await this.open()\n const tx = db.transaction([RECORDS, SNAPSHOTS], 'readwrite')\n tx.objectStore(RECORDS).put(JSON.parse(JSON.stringify(run.record)))\n for (const [idx, s] of run.snapshots) tx.objectStore(SNAPSHOTS).put(JSON.parse(JSON.stringify(s)), [run.record.run_id, idx])\n await done(tx)\n }\n}\n"],"names":["SITE_RUNTIME_KIND","TOOL_NAME","namedSources","cfg","field","map","s","kind","XllmError","capability","describeToolSource","name","CommandArgsError","Error","constructor","code","message","super","this","hasOwn","o","key","Object","prototype","hasOwnProperty","call","optionProperty","option","property","split","join","splitLongOption","token","content","slice","equalIndex","indexOf","inlineValue","readOptionValue","argv","index","value","consumed","startsWith","parseOptionValue","type","number","Number","isFinite","isInteger","assignPositional","input","positionals","positional","parseShellLine","line","tokens","current","quote","escaped","started","character","test","push","validateSchema","schema","path","enum","some","candidate","is","minLength","length","Array","isArray","items","forEach","item","object","required","additionalProperties","keys","properties","propertyValue","entries","propertySchema","_a","ACTION_RISKS","XCALL_USAGE","MAX_RESULT_BYTES","SHELL_CHARS","fail","normalizeUri","uri","origins","raw","trim","absolute","url","origin","URL","replace","protocol","toLowerCase","host","has","segments","part","pathname","decoded","decodeURIComponent","includes","text","search","query","searchParams","matchPattern","p","params","i","endsWith","asText","JSON","stringify","String","versioned","isObject","every","k","version","clipBytes","max","utf8Length","clipped","out","bytes","ch","n","pageText","offset","limit","lines","start","Math","floor","wanted","body","parseScalar","v","parse","UNSUPPORTED_XCALL_KEYS","parseXcall","action","pairs","json","e","unsupported","t","eq","commandUsage","c","summary","description","pos","options","examples","OBJECT_ARGS","props","INDEX_TRAIT_URI","riskRank","r","renderObjectDocument","canonical","card","profile","id","aliases","alsoKnownAs","filter","a","label","section","sort","d","risk","names","isCollection","traits","XLLM_RUNS_DB","RECORDS","SNAPSHOTS","req","Promise","resolve","reject","onsuccess","result","onerror","error","done","tx","oncomplete","onabort","persistent","localLocks","Set","open","db","factory","idb","globalThis","indexedDB","storage","dbName","onupgradeneeded","objectStoreNames","contains","createObjectStore","keyPath","locks","navigator","runsDir","runDir","createRun","generateRunId","transaction","objectStore","get","writeRecord","record","put","readRecord","runId","rec","run_id","runs_dir","RUN_RECORD_VERSION","notResumable","listRecords","getAll","putSnapshot","snapshot","store","getAllKeys","IDBKeyRange","bound","MAX_SAFE_INTEGER","next","getSnapshot","idx","reason","listSnapshots","b","lockRun","request","ifAvailable","lock","release","catch","add","delete","isRunLive","held","l","removeRun","importRun","run","snapshots","scene","tools","Map","tool","spec","set","env","descriptor","runtime_id","target","workdir","capabilities","network","os","config","task_wait_ms","info","timezone","Intl","DateTimeFormat","resolvedOptions","timeZone","arch","hostname","shell","cwd","current_time","Date","toISOString","platform","shell_kind","baseline","ctx","enabled","tools2actions","loop_model","actions","pick","source","args_schema","resolveTool","native","toolSources","actionSources","selected","filesystem_policy","tool_sources","action_sources","bash_tools","shellSettings","taskWaitMs","exec_enabled","sources","manager","SiteToolManager","tasks","describeInterrupted","args","call_id","signal","AbortController","unresolvedReason","async","maxRank","maxRisk","root","roots","client","collection","declared","_m","invoke","Boolean","read","m","cursor","pageSize","page_size","listed","readProperty","patterns","resources","decl","rest","slash","parsePattern","commands","pattern","exec","command","words","available","size","unquoted","known","invalid","validateJson","_decl","match","parsed","beforeOption","optionByName","positionalIndex","help","handled","positionalCount","parseArgv","prop","inputSchema","idempotent","methods","edit","write","discovery","_d","readRaw","mode","old_string","new_string","count","w","ifVersion","find","q","_b","_c","access","level","execIsIdempotent"],"mappings":"uTAiBO,MAAMA,EAAoB,OAE3BC,EAAY,wBA0BlB,SAASC,EAAaC,EAA+BC,GACnD,OAAQD,GAAO,IAAIE,KAASC,IACtB,GAAW,UAAXA,EAAEC,KACEC,MAAAA,EAAAA,UAAUC,WAAW,GAAGL,QAAYM,EAAAA,mBAAmBJ,+EAE/D,OAAOA,EAAEK,IAAA,GAEb,CCbO,MAAMC,UAAyBC,MAGpC,WAAAC,CAAYC,EAAcC,GACxBC,MAAMD,GACNE,KAAKP,KAAO,mBACZO,KAAKH,KAAOA,CACd,EAGF,SAASI,EAAOC,EAAWC,GACzB,OAAOC,OAAOC,UAAUC,eAAeC,KAAKL,EAAGC,EACjD,CAEO,SAASK,EAAeC,GACtB,OAAAA,EAAOC,UAAYD,EAAOhB,KAAKkB,MAAM,KAAKC,KAAK,IACxD,CAOO,SAASC,EAAgBC,GACxB,MAAAC,EAAUD,EAAME,MAAM,GACtBC,EAAaF,EAAQG,QAAQ,KACnC,OAAOD,EAAa,EAAI,CAAExB,KAAMsB,GAAY,CAAEtB,KAAMsB,EAAQC,MAAM,EAAGC,GAAaE,YAAaJ,EAAQC,MAAMC,EAAa,GAC5H,CAEgB,SAAAG,EAAgBC,EAAgBC,EAAeb,GACzD,QAAuB,IAAvBA,EAAOU,YAA2B,CACpC,IAAKV,EA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