buckyos 0.7.170 → 0.7.177

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.
Files changed (220) hide show
  1. package/cli/core/app.ts +2 -0
  2. package/cli/core/argv.ts +45 -239
  3. package/cli/core/command.ts +3 -35
  4. package/cli/dist/cli.mjs +2151 -673
  5. package/cli/dist/cli.mjs.map +1 -1
  6. package/cli/modules/agent.ts +3 -1
  7. package/cli/modules/app.ts +13 -2
  8. package/cli/modules/pikg.ts +70 -1
  9. package/cli/modules/runtime.ts +497 -0
  10. package/cli/modules/skill.ts +583 -161
  11. package/cli/modules/skill_lint.ts +462 -0
  12. package/cli/version.ts +1 -1
  13. package/dist/account-7a7bde6f.mjs +105 -0
  14. package/dist/account-7a7bde6f.mjs.map +1 -0
  15. package/dist/account-b12ac6b9.js +2 -0
  16. package/dist/account-b12ac6b9.js.map +1 -0
  17. package/dist/aicc-67851c41.mjs +582 -0
  18. package/dist/aicc-67851c41.mjs.map +1 -0
  19. package/dist/aicc-ccb36ef7.js +2 -0
  20. package/dist/aicc-ccb36ef7.js.map +1 -0
  21. package/dist/aiworkspace_client.d.ts +36 -2
  22. package/dist/aiworkspace_client.d.ts.map +1 -1
  23. package/dist/app-frame.cjs +1 -1
  24. package/dist/app-frame.cjs.map +1 -1
  25. package/dist/app-frame.d.ts +56 -1
  26. package/dist/app-frame.d.ts.map +1 -1
  27. package/dist/app-frame.mjs +285 -4
  28. package/dist/app-frame.mjs.map +1 -1
  29. package/dist/browser.cjs +1 -1
  30. package/dist/browser.cjs.map +1 -1
  31. package/dist/browser.d.ts +4 -0
  32. package/dist/browser.d.ts.map +1 -1
  33. package/dist/browser.mjs +218 -194
  34. package/dist/browser.mjs.map +1 -1
  35. package/dist/content.cjs +1 -1
  36. package/dist/content.cjs.map +1 -1
  37. package/dist/content.d.ts +77 -0
  38. package/dist/content.d.ts.map +1 -1
  39. package/dist/content.mjs +65 -0
  40. package/dist/content.mjs.map +1 -1
  41. package/dist/content_objid-1aff74b6.js +2 -0
  42. package/dist/content_objid-1aff74b6.js.map +1 -0
  43. package/dist/content_objid-9232bcaf.mjs +29 -0
  44. package/dist/content_objid-9232bcaf.mjs.map +1 -0
  45. package/dist/content_objid.d.ts +15 -0
  46. package/dist/content_objid.d.ts.map +1 -0
  47. package/dist/did_object_client-6a1b108a.js +2 -0
  48. package/dist/did_object_client-6a1b108a.js.map +1 -0
  49. package/dist/did_object_client-7fa36f90.mjs +87 -0
  50. package/dist/did_object_client-7fa36f90.mjs.map +1 -0
  51. package/dist/did_object_client.d.ts +39 -0
  52. package/dist/did_object_client.d.ts.map +1 -0
  53. package/dist/executor_client-7ce0ddc7.js +13 -0
  54. package/dist/executor_client-7ce0ddc7.js.map +1 -0
  55. package/dist/{executor_client-5f4d0468.mjs → executor_client-bfc8a1e1.mjs} +308 -752
  56. package/dist/executor_client-bfc8a1e1.mjs.map +1 -0
  57. package/dist/executor_client.d.ts +129 -0
  58. package/dist/executor_client.d.ts.map +1 -1
  59. package/dist/index.cjs +1 -1
  60. package/dist/index.cjs.map +1 -1
  61. package/dist/index.d.ts +3 -0
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.mjs +218 -199
  64. package/dist/index.mjs.map +1 -1
  65. package/dist/internal/command_args.d.ts +67 -0
  66. package/dist/internal/command_args.d.ts.map +1 -0
  67. package/dist/krpc_client-26c2dc8b.js +2 -0
  68. package/dist/krpc_client-26c2dc8b.js.map +1 -0
  69. package/dist/krpc_client-673448e5.mjs +173 -0
  70. package/dist/krpc_client-673448e5.mjs.map +1 -0
  71. package/dist/krpc_client.d.ts +5 -1
  72. package/dist/krpc_client.d.ts.map +1 -1
  73. package/dist/{ndn_types-ab30fac0.mjs → ndn_types-0fac2499.mjs} +115 -215
  74. package/dist/ndn_types-0fac2499.mjs.map +1 -0
  75. package/dist/ndn_types-5b138882.js +2 -0
  76. package/dist/ndn_types-5b138882.js.map +1 -0
  77. package/dist/node.cjs +1 -1
  78. package/dist/node.cjs.map +1 -1
  79. package/dist/node.mjs +201 -194
  80. package/dist/node.mjs.map +1 -1
  81. package/dist/object_url-8fb5a7bf.js +2 -0
  82. package/dist/object_url-8fb5a7bf.js.map +1 -0
  83. package/dist/object_url-f72c1704.mjs +412 -0
  84. package/dist/object_url-f72c1704.mjs.map +1 -0
  85. package/dist/openai-ae2978de.mjs +163 -0
  86. package/dist/openai-ae2978de.mjs.map +1 -0
  87. package/dist/openai-f560d518.js +2 -0
  88. package/dist/openai-f560d518.js.map +1 -0
  89. package/dist/provision.cjs +6 -6
  90. package/dist/provision.cjs.map +1 -1
  91. package/dist/provision.mjs +4 -3
  92. package/dist/provision.mjs.map +1 -1
  93. package/dist/site_manager-11a7a468.mjs +6410 -0
  94. package/dist/site_manager-11a7a468.mjs.map +1 -0
  95. package/dist/site_manager-334b1a51.js +2 -0
  96. package/dist/site_manager-334b1a51.js.map +1 -0
  97. package/dist/{tus_client-b231b248.js → tus_client-809c90ab.js} +2 -2
  98. package/dist/{tus_client-b231b248.js.map → tus_client-809c90ab.js.map} +1 -1
  99. package/dist/{tus_client-d1ffe2d6.mjs → tus_client-893a3287.mjs} +2 -2
  100. package/dist/{tus_client-d1ffe2d6.mjs.map → tus_client-893a3287.mjs.map} +1 -1
  101. package/dist/xllm/core/action_parser.d.ts +15 -0
  102. package/dist/xllm/core/action_parser.d.ts.map +1 -0
  103. package/dist/xllm/core/behavior_loop.d.ts +20 -0
  104. package/dist/xllm/core/behavior_loop.d.ts.map +1 -0
  105. package/dist/xllm/core/behavior_result.d.ts +11 -0
  106. package/dist/xllm/core/behavior_result.d.ts.map +1 -0
  107. package/dist/xllm/core/config.d.ts +62 -0
  108. package/dist/xllm/core/config.d.ts.map +1 -0
  109. package/dist/xllm/core/context_window.d.ts +15 -0
  110. package/dist/xllm/core/context_window.d.ts.map +1 -0
  111. package/dist/xllm/core/deps.d.ts +97 -0
  112. package/dist/xllm/core/deps.d.ts.map +1 -0
  113. package/dist/xllm/core/errors.d.ts +94 -0
  114. package/dist/xllm/core/errors.d.ts.map +1 -0
  115. package/dist/xllm/core/interrupt.d.ts +31 -0
  116. package/dist/xllm/core/interrupt.d.ts.map +1 -0
  117. package/dist/xllm/core/json.d.ts +11 -0
  118. package/dist/xllm/core/json.d.ts.map +1 -0
  119. package/dist/xllm/core/json_check.d.ts +17 -0
  120. package/dist/xllm/core/json_check.d.ts.map +1 -0
  121. package/dist/xllm/core/loop.d.ts +135 -0
  122. package/dist/xllm/core/loop.d.ts.map +1 -0
  123. package/dist/xllm/core/messages.d.ts +18 -0
  124. package/dist/xllm/core/messages.d.ts.map +1 -0
  125. package/dist/xllm/core/observer.d.ts +14 -0
  126. package/dist/xllm/core/observer.d.ts.map +1 -0
  127. package/dist/xllm/core/open_runtime.d.ts +22 -0
  128. package/dist/xllm/core/open_runtime.d.ts.map +1 -0
  129. package/dist/xllm/core/prepare.d.ts +54 -0
  130. package/dist/xllm/core/prepare.d.ts.map +1 -0
  131. package/dist/xllm/core/prompt.d.ts +40 -0
  132. package/dist/xllm/core/prompt.d.ts.map +1 -0
  133. package/dist/xllm/core/protocol.d.ts +15 -0
  134. package/dist/xllm/core/protocol.d.ts.map +1 -0
  135. package/dist/xllm/core/result.d.ts +12 -0
  136. package/dist/xllm/core/result.d.ts.map +1 -0
  137. package/dist/xllm/core/run.d.ts +198 -0
  138. package/dist/xllm/core/run.d.ts.map +1 -0
  139. package/dist/xllm/core/rust_text.d.ts +20 -0
  140. package/dist/xllm/core/rust_text.d.ts.map +1 -0
  141. package/dist/xllm/core/site_policy.d.ts +5 -0
  142. package/dist/xllm/core/site_policy.d.ts.map +1 -0
  143. package/dist/xllm/core/store.d.ts +60 -0
  144. package/dist/xllm/core/store.d.ts.map +1 -0
  145. package/dist/xllm/core/suspension.d.ts +13 -0
  146. package/dist/xllm/core/suspension.d.ts.map +1 -0
  147. package/dist/xllm/core/tokenizer.d.ts +8 -0
  148. package/dist/xllm/core/tokenizer.d.ts.map +1 -0
  149. package/dist/xllm/core/types.d.ts +826 -0
  150. package/dist/xllm/core/types.d.ts.map +1 -0
  151. package/dist/xllm/core/xml.d.ts +19 -0
  152. package/dist/xllm/core/xml.d.ts.map +1 -0
  153. package/dist/xllm/dev/openai.d.ts +17 -0
  154. package/dist/xllm/dev/openai.d.ts.map +1 -0
  155. package/dist/xllm/dev/scripted.d.ts +46 -0
  156. package/dist/xllm/dev/scripted.d.ts.map +1 -0
  157. package/dist/xllm/dev.d.ts +5 -0
  158. package/dist/xllm/dev.d.ts.map +1 -0
  159. package/dist/xllm/hosts/browser/store.d.ts +41 -0
  160. package/dist/xllm/hosts/browser/store.d.ts.map +1 -0
  161. package/dist/xllm/hosts/deno/deno_api.d.ts +103 -0
  162. package/dist/xllm/hosts/deno/deno_api.d.ts.map +1 -0
  163. package/dist/xllm/hosts/deno/identity.d.ts +29 -0
  164. package/dist/xllm/hosts/deno/identity.d.ts.map +1 -0
  165. package/dist/xllm/hosts/deno/index.d.ts +47 -0
  166. package/dist/xllm/hosts/deno/index.d.ts.map +1 -0
  167. package/dist/xllm/hosts/deno/native_runtime.d.ts +93 -0
  168. package/dist/xllm/hosts/deno/native_runtime.d.ts.map +1 -0
  169. package/dist/xllm/hosts/deno/native_tools.d.ts +105 -0
  170. package/dist/xllm/hosts/deno/native_tools.d.ts.map +1 -0
  171. package/dist/xllm/hosts/deno/provider.d.ts +13 -0
  172. package/dist/xllm/hosts/deno/provider.d.ts.map +1 -0
  173. package/dist/xllm/hosts/deno/store.d.ts +60 -0
  174. package/dist/xllm/hosts/deno/store.d.ts.map +1 -0
  175. package/dist/xllm/index.d.ts +48 -0
  176. package/dist/xllm/index.d.ts.map +1 -0
  177. package/dist/xllm/providers/aicc.d.ts +22 -0
  178. package/dist/xllm/providers/aicc.d.ts.map +1 -0
  179. package/dist/xllm/providers/timeout.d.ts +12 -0
  180. package/dist/xllm/providers/timeout.d.ts.map +1 -0
  181. package/dist/xllm/runtime/compress.d.ts +149 -0
  182. package/dist/xllm/runtime/compress.d.ts.map +1 -0
  183. package/dist/xllm/runtime/did_object_resources.d.ts +21 -0
  184. package/dist/xllm/runtime/did_object_resources.d.ts.map +1 -0
  185. package/dist/xllm/runtime/hints.d.ts +23 -0
  186. package/dist/xllm/runtime/hints.d.ts.map +1 -0
  187. package/dist/xllm/runtime/site.d.ts +22 -0
  188. package/dist/xllm/runtime/site.d.ts.map +1 -0
  189. package/dist/xllm/runtime/site_manager.d.ts +38 -0
  190. package/dist/xllm/runtime/site_manager.d.ts.map +1 -0
  191. package/dist/xllm/runtime/site_tools.d.ts +76 -0
  192. package/dist/xllm/runtime/site_tools.d.ts.map +1 -0
  193. package/dist/xllm/runtime/step_renderer.d.ts +54 -0
  194. package/dist/xllm/runtime/step_renderer.d.ts.map +1 -0
  195. package/dist/xllm/runtime/task_model.d.ts +64 -0
  196. package/dist/xllm/runtime/task_model.d.ts.map +1 -0
  197. package/dist/xllm/runtime/tool_result.d.ts +39 -0
  198. package/dist/xllm/runtime/tool_result.d.ts.map +1 -0
  199. package/dist/xllm/runtime/types.d.ts +99 -0
  200. package/dist/xllm/runtime/types.d.ts.map +1 -0
  201. package/dist/xllm.cjs +2 -0
  202. package/dist/xllm.cjs.map +1 -0
  203. package/dist/xllm.mjs +1167 -0
  204. package/dist/xllm.mjs.map +1 -0
  205. package/dist/xllm_deno.cjs +2 -0
  206. package/dist/xllm_deno.cjs.map +1 -0
  207. package/dist/xllm_deno.mjs +2487 -0
  208. package/dist/xllm_deno.mjs.map +1 -0
  209. package/dist/xllm_dev.cjs +2 -0
  210. package/dist/xllm_dev.cjs.map +1 -0
  211. package/dist/xllm_dev.mjs +70 -0
  212. package/dist/xllm_dev.mjs.map +1 -0
  213. package/package.json +22 -1
  214. package/src/internal/command_args.ts +268 -0
  215. package/dist/executor_client-1ee523cf.js +0 -13
  216. package/dist/executor_client-1ee523cf.js.map +0 -1
  217. package/dist/executor_client-5f4d0468.mjs.map +0 -1
  218. package/dist/ndn_types-8c2696d5.js +0 -2
  219. package/dist/ndn_types-8c2696d5.js.map +0 -1
  220. package/dist/ndn_types-ab30fac0.mjs.map +0 -1
package/dist/xllm.mjs ADDED
@@ -0,0 +1,1167 @@
1
+ import { X as XllmError, i as isObject } from "./aicc-67851c41.mjs";
2
+ import { A, L, h, j, a, d, c, e, b, l, p, k, r, f, g, s } from "./aicc-67851c41.mjs";
3
+ import { s as shellSettings, t as taskWaitMs, S as SiteToolManager, u as unresolvedReason, d as describeToolSource, a as utf8Length, v as validateJson, g as generateRunId, R as RUN_RECORD_VERSION } from "./site_manager-11a7a468.mjs";
4
+ import { a8, B, D, h as h2, i, j as j2, k as k2, l as l2, ao, ap, V, W, L as L2, e as e2, ae, a4, M, m, a5, aq, G, Y, K, z, b as b2, af, x, aA, T, X, Z, _, $, ac, f as f2, ar, a9, y, A as A2, C, E, F, a0, ag, ah, ai, aj, o, a6, H, J, au, av, I, aw, a1, a7, ak, a2, P, q, n, aa, w, p as p2, al, as, Q, at, N, r as r2, ax, U, a3, O, c as c2, am, an, ay, ab, ad, az } from "./site_manager-11a7a468.mjs";
5
+ import { D as D2, a as a10 } from "./did_object_client-7fa36f90.mjs";
6
+ import "./krpc_client-673448e5.mjs";
7
+ import "./object_url-f72c1704.mjs";
8
+ import "./ndn_types-0fac2499.mjs";
9
+ const SITE_RUNTIME_KIND = "site";
10
+ const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
11
+ function resolveTool(name, tool, source) {
12
+ return { name, description: tool.spec.description, args_schema: tool.spec.args_schema, source };
13
+ }
14
+ function namedSources(cfg, field) {
15
+ return (cfg ?? []).map((s2) => {
16
+ if (s2.kind !== "named") {
17
+ throw XllmError.capability(`${field}: \`${describeToolSource(s2)}\` is not available in a site runtime; only the page's tools can be named`);
18
+ }
19
+ return s2.name;
20
+ });
21
+ }
22
+ function createSiteRuntime(options) {
23
+ var _a;
24
+ const scene = (_a = options.scene) == null ? void 0 : _a.trim();
25
+ if (!scene)
26
+ throw XllmError.input("createSiteRuntime: `scene` is required");
27
+ if (!options.origin)
28
+ throw XllmError.input("createSiteRuntime: `origin` is required");
29
+ const tools = /* @__PURE__ */ new Map();
30
+ for (const [name, tool] of Object.entries(options.tools ?? {})) {
31
+ if (!TOOL_NAME.test(name))
32
+ throw XllmError.tools(`site tool name \`${name}\` must match ${TOOL_NAME}`);
33
+ if (!tool || typeof tool.call !== "function" || !tool.spec)
34
+ throw XllmError.tools(`site tool \`${name}\` needs \`spec\` and \`call\``);
35
+ tools.set(name, tool);
36
+ }
37
+ const env = { ...options.env ?? {} };
38
+ const descriptor = {
39
+ runtime_id: `site:${scene}`,
40
+ kind: SITE_RUNTIME_KIND,
41
+ host: null,
42
+ target: { origin: options.origin, scene },
43
+ workdir: "/",
44
+ capabilities: { tools: {}, network: true, os: "browser" }
45
+ };
46
+ const config = { kind: SITE_RUNTIME_KIND, env: {} };
47
+ if (options.task_wait_ms !== void 0)
48
+ config.task_wait_ms = options.task_wait_ms;
49
+ const runtime = {
50
+ scene,
51
+ tools,
52
+ descriptor: () => JSON.parse(JSON.stringify(descriptor)),
53
+ config: () => JSON.parse(JSON.stringify(config)),
54
+ async info() {
55
+ let timezone = "";
56
+ try {
57
+ timezone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? "";
58
+ } catch {
59
+ timezone = "";
60
+ }
61
+ return {
62
+ id: descriptor.runtime_id,
63
+ kind: SITE_RUNTIME_KIND,
64
+ os: "browser",
65
+ arch: "",
66
+ hostname: options.hostname,
67
+ shell: "",
68
+ cwd: "/",
69
+ tools: [],
70
+ current_time: (/* @__PURE__ */ new Date()).toISOString(),
71
+ timezone,
72
+ target: descriptor.target,
73
+ platform: "browser",
74
+ shell_kind: "",
75
+ baseline: ""
76
+ };
77
+ },
78
+ async open(ctx, cfg) {
79
+ const enabled = cfg.enabled ?? false;
80
+ const tools2actions = cfg.tools2actions ?? false;
81
+ if (ctx.loop_model === "function_call" && (tools2actions || (cfg.actions ?? []).length > 0)) {
82
+ throw XllmError.capability("actions / tools2actions need loop_model behavior");
83
+ }
84
+ const pick = (names, field) => names.map((name) => {
85
+ const tool = tools.get(name);
86
+ if (!tool) {
87
+ throw XllmError.capability(`${field}: \`${name}\` is not a tool of scene \`${scene}\` (scene tools: ${[...tools.keys()].join(", ") || "none"})`);
88
+ }
89
+ return resolveTool(name, tool, `name:${name}`);
90
+ });
91
+ let native = [];
92
+ let actions = [];
93
+ const toolSources = cfg.tools ?? [];
94
+ const actionSources = cfg.actions ?? [];
95
+ if (enabled) {
96
+ const toolNames = cfg.tools === void 0 ? [...tools.keys()] : namedSources(cfg.tools, "tools.tools");
97
+ native = pick(toolNames, "tools.tools");
98
+ actions = pick(namedSources(cfg.actions, "tools.actions"), "tools.actions");
99
+ if (tools2actions) {
100
+ actions = [...actions, ...native.filter((t) => !actions.some((a11) => a11.name === t.name))];
101
+ native = [];
102
+ }
103
+ }
104
+ const selected = /* @__PURE__ */ new Map();
105
+ for (const t of [...native, ...actions])
106
+ selected.set(t.name, tools.get(t.name));
107
+ const effective = {
108
+ enabled,
109
+ filesystem_policy: cfg.filesystem_policy ?? "workspace",
110
+ tools2actions,
111
+ tool_sources: cfg.tools === void 0 && enabled ? native.map((t) => ({ kind: "named", name: t.name })) : toolSources,
112
+ action_sources: actionSources,
113
+ native,
114
+ actions,
115
+ bash_tools: [],
116
+ shell: shellSettings(cfg.shell, taskWaitMs(config)),
117
+ exec_enabled: false,
118
+ sources: { ...ctx.sources }
119
+ };
120
+ return { tools: effective, manager: new SiteToolManager(selected, { tasks: ctx.tasks, taskWaitMs: ctx.task_wait_ms }) };
121
+ },
122
+ async describeInterrupted(run, call) {
123
+ const tool = tools.get(call.name);
124
+ if (tool == null ? void 0 : tool.describeInterrupted) {
125
+ try {
126
+ return await tool.describeInterrupted(call.args ?? {}, { run_id: run.run_id, call_id: call.call_id, signal: new AbortController().signal });
127
+ } catch (e3) {
128
+ return `${unresolvedReason(call.name)} (describing it failed: ${e3 instanceof Error ? e3.message : String(e3)})`;
129
+ }
130
+ }
131
+ return unresolvedReason(call.name);
132
+ },
133
+ env: (name) => env[name]
134
+ };
135
+ return runtime;
136
+ }
137
+ class CommandArgsError extends Error {
138
+ constructor(code, message) {
139
+ super(message);
140
+ this.name = "CommandArgsError";
141
+ this.code = code;
142
+ }
143
+ }
144
+ function hasOwn(o2, key) {
145
+ return Object.prototype.hasOwnProperty.call(o2, key);
146
+ }
147
+ function optionProperty(option) {
148
+ return option.property ?? option.name.split("-").join("_");
149
+ }
150
+ function splitLongOption(token) {
151
+ const content = token.slice(2);
152
+ const equalIndex = content.indexOf("=");
153
+ return equalIndex < 0 ? { name: content } : { name: content.slice(0, equalIndex), inlineValue: content.slice(equalIndex + 1) };
154
+ }
155
+ function readOptionValue(argv, index, option) {
156
+ if (option.inlineValue !== void 0) {
157
+ if (!option.inlineValue)
158
+ throw new CommandArgsError("MISSING_ARGUMENT", `--${option.name} requires a value`);
159
+ return { value: option.inlineValue, consumed: 1 };
160
+ }
161
+ const value = argv[index + 1];
162
+ if (value === void 0 || value.startsWith("--"))
163
+ throw new CommandArgsError("MISSING_ARGUMENT", `--${option.name} requires a value`);
164
+ return { value, consumed: 2 };
165
+ }
166
+ function parseOptionValue(type, value, name) {
167
+ if (type === "string")
168
+ return value;
169
+ const number = Number(value);
170
+ if (!Number.isFinite(number) || type === "integer" && !Number.isInteger(number)) {
171
+ throw new CommandArgsError("INVALID_ARGUMENT", `--${name} requires a ${type}`);
172
+ }
173
+ return number;
174
+ }
175
+ function assignPositional(input, positionals, index, value) {
176
+ const positional = positionals[index];
177
+ if (!positional)
178
+ throw new CommandArgsError("TOO_MANY_ARGUMENTS", `unexpected positional argument: ${value}`);
179
+ input[positional.name] = value;
180
+ return index + 1;
181
+ }
182
+ function parseArgv(spec, argv, beforeOption) {
183
+ const input = {};
184
+ const positionals = spec.positionals ?? [];
185
+ const optionByName = new Map((spec.options ?? []).map((o2) => [o2.name, o2]));
186
+ let positionalIndex = 0;
187
+ let help = false;
188
+ for (let index = 0; index < argv.length; ) {
189
+ const token = argv[index];
190
+ if (token === "--help" || token === "-h") {
191
+ help = true;
192
+ index += 1;
193
+ continue;
194
+ }
195
+ if (token === "--") {
196
+ for (const value2 of argv.slice(index + 1))
197
+ positionalIndex = assignPositional(input, positionals, positionalIndex, value2);
198
+ break;
199
+ }
200
+ if (!token.startsWith("--")) {
201
+ positionalIndex = assignPositional(input, positionals, positionalIndex, token);
202
+ index += 1;
203
+ continue;
204
+ }
205
+ const parsed = splitLongOption(token);
206
+ const handled = beforeOption == null ? void 0 : beforeOption(parsed, argv, index);
207
+ if (handled !== void 0) {
208
+ index += handled;
209
+ continue;
210
+ }
211
+ const option = optionByName.get(parsed.name);
212
+ if (!option)
213
+ throw new CommandArgsError("UNKNOWN_OPTION", `unknown option: --${parsed.name}`);
214
+ const property = optionProperty(option);
215
+ if (hasOwn(input, property))
216
+ throw new CommandArgsError("DUPLICATE_ARGUMENT", `argument provided more than once: ${property}`);
217
+ if (option.type === "boolean") {
218
+ if (parsed.inlineValue !== void 0)
219
+ throw new CommandArgsError("INVALID_ARGUMENT", `--${parsed.name} does not accept a value`);
220
+ input[property] = true;
221
+ index += 1;
222
+ continue;
223
+ }
224
+ const { value, consumed } = readOptionValue(argv, index, parsed);
225
+ input[property] = parseOptionValue(option.type, value, parsed.name);
226
+ index += consumed;
227
+ }
228
+ return { input, help, positionalCount: positionalIndex };
229
+ }
230
+ function parseShellLine(line) {
231
+ const tokens = [];
232
+ let current = "";
233
+ let quote = null;
234
+ let escaped = false;
235
+ let started = false;
236
+ for (const character of line) {
237
+ if (escaped) {
238
+ current += character;
239
+ escaped = false;
240
+ started = true;
241
+ continue;
242
+ }
243
+ if (character === "\\" && quote !== "single") {
244
+ escaped = true;
245
+ started = true;
246
+ continue;
247
+ }
248
+ if (quote === "single") {
249
+ if (character === "'")
250
+ quote = null;
251
+ else
252
+ current += character;
253
+ continue;
254
+ }
255
+ if (quote === "double") {
256
+ if (character === '"')
257
+ quote = null;
258
+ else
259
+ current += character;
260
+ continue;
261
+ }
262
+ if (character === "'") {
263
+ quote = "single";
264
+ started = true;
265
+ continue;
266
+ }
267
+ if (character === '"') {
268
+ quote = "double";
269
+ started = true;
270
+ continue;
271
+ }
272
+ if (/\s/.test(character)) {
273
+ if (started) {
274
+ tokens.push(current);
275
+ current = "";
276
+ started = false;
277
+ }
278
+ continue;
279
+ }
280
+ current += character;
281
+ started = true;
282
+ }
283
+ if (escaped)
284
+ throw new CommandArgsError("INVALID_COMMAND_LINE", "unfinished escape sequence");
285
+ if (quote)
286
+ throw new CommandArgsError("INVALID_COMMAND_LINE", `unterminated ${quote} quote`);
287
+ if (started)
288
+ tokens.push(current);
289
+ return tokens;
290
+ }
291
+ function validateSchema(value, schema, path) {
292
+ var _a;
293
+ if (schema.enum && !schema.enum.some((candidate) => Object.is(candidate, value))) {
294
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path} must be one of ${schema.enum.join(", ")}`);
295
+ }
296
+ if (schema.type === "object") {
297
+ if (!value || typeof value !== "object" || Array.isArray(value))
298
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path} must be an object`);
299
+ const object = value;
300
+ for (const required of schema.required ?? []) {
301
+ if (!hasOwn(object, required))
302
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path}.${required} is required`);
303
+ }
304
+ if (schema.additionalProperties === false) {
305
+ for (const key of Object.keys(object)) {
306
+ if (!hasOwn(schema.properties ?? {}, key))
307
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path}.${key} is not allowed`);
308
+ }
309
+ }
310
+ for (const [key, propertyValue] of Object.entries(object)) {
311
+ const propertySchema = (_a = schema.properties) == null ? void 0 : _a[key];
312
+ if (propertySchema)
313
+ validateSchema(propertyValue, propertySchema, `${path}.${key}`);
314
+ }
315
+ return;
316
+ }
317
+ if (schema.type === "array") {
318
+ if (!Array.isArray(value))
319
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path} must be an array`);
320
+ const items = schema.items;
321
+ if (items)
322
+ value.forEach((item, index) => validateSchema(item, items, `${path}[${index}]`));
323
+ return;
324
+ }
325
+ if (schema.type === "string") {
326
+ if (typeof value !== "string")
327
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path} must be a string`);
328
+ if (schema.minLength !== void 0 && value.length < schema.minLength)
329
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path} is too short`);
330
+ return;
331
+ }
332
+ if (schema.type === "boolean" && typeof value !== "boolean")
333
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path} must be a boolean`);
334
+ if (schema.type === "integer" && (!Number.isInteger(value) || typeof value !== "number")) {
335
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path} must be an integer`);
336
+ }
337
+ if (schema.type === "number" && typeof value !== "number")
338
+ throw new CommandArgsError("SCHEMA_VALIDATION_FAILED", `${path} must be a number`);
339
+ }
340
+ const ACTION_RISKS = ["read_only", "idempotent_write", "write", "destructive", "admin"];
341
+ const XCALL_USAGE = "xcall <object> <action> [--params <json>] [key=value ...] [--key=value ...]";
342
+ const MAX_RESULT_BYTES = 64 * 1024;
343
+ const LOCAL_BASE = "site://page/";
344
+ const SHELL_CHARS = /[|;&><`$]/;
345
+ function parsePattern(raw, decl) {
346
+ const i2 = raw.indexOf("://");
347
+ if (i2 >= 0) {
348
+ const rest = raw.slice(i2 + 3);
349
+ const slash = rest.indexOf("/");
350
+ const host = slash < 0 ? rest : rest.slice(0, slash);
351
+ const path2 = slash < 0 ? "" : rest.slice(slash + 1);
352
+ return { raw, origin: `${raw.slice(0, i2).toLowerCase()}://${host.toLowerCase()}`, segments: path2 ? path2.split("/") : [], decl };
353
+ }
354
+ const path = raw.replace(/^\/+/, "").replace(/\/+$/, "");
355
+ return { raw, segments: path ? path.split("/") : [], decl };
356
+ }
357
+ function fail(message) {
358
+ throw new Error(message);
359
+ }
360
+ function normalizeUri(uri, origins) {
361
+ const raw = uri.trim();
362
+ if (!raw)
363
+ fail("uri is empty");
364
+ const absolute = /^[A-Za-z][A-Za-z0-9+.-]*:/.test(raw);
365
+ let url;
366
+ try {
367
+ url = absolute ? new URL(raw) : new URL(raw.replace(/^\/+/, ""), LOCAL_BASE);
368
+ } catch {
369
+ fail(`invalid uri \`${raw}\``);
370
+ }
371
+ let origin;
372
+ if (absolute) {
373
+ origin = `${url.protocol.slice(0, -1).toLowerCase()}://${url.host.toLowerCase()}`;
374
+ if (!origins.has(origin))
375
+ fail(`uri \`${raw}\` is not a resource of this page (absolute URIs are limited to the declared ones)`);
376
+ } else if (url.protocol !== "site:" || url.host !== "page") {
377
+ fail(`uri \`${raw}\` is not a resource of this page`);
378
+ }
379
+ const segments = [];
380
+ for (const part of url.pathname.split("/")) {
381
+ if (part === "")
382
+ continue;
383
+ let decoded;
384
+ try {
385
+ decoded = decodeURIComponent(part);
386
+ } catch {
387
+ fail(`invalid uri \`${raw}\``);
388
+ }
389
+ if (decoded === ".." || decoded === "." || decoded.includes("/") || decoded.includes("\\"))
390
+ fail(`uri \`${raw}\` is not a resource of this page`);
391
+ segments.push(decoded);
392
+ }
393
+ const text2 = (origin ? `${origin}/` : "") + segments.join("/") + (url.search || "");
394
+ return { origin, segments, query: url.searchParams, text: text2 };
395
+ }
396
+ function matchPattern(p3, origin, segments) {
397
+ if (p3.origin !== origin || p3.segments.length !== segments.length)
398
+ return void 0;
399
+ const params = {};
400
+ for (let i2 = 0; i2 < segments.length; i2++) {
401
+ const s2 = p3.segments[i2];
402
+ if (s2.startsWith("{") && s2.endsWith("}"))
403
+ params[s2.slice(1, -1)] = segments[i2];
404
+ else if (s2 !== segments[i2])
405
+ return void 0;
406
+ }
407
+ return params;
408
+ }
409
+ function asText(value) {
410
+ if (value === void 0 || value === null)
411
+ return "";
412
+ if (typeof value === "string")
413
+ return value;
414
+ try {
415
+ return JSON.stringify(value, null, 2);
416
+ } catch {
417
+ return String(value);
418
+ }
419
+ }
420
+ function versioned(value) {
421
+ if (isObject(value) && "content" in value && Object.keys(value).every((k3) => k3 === "content" || k3 === "version")) {
422
+ const version = value.version;
423
+ return { text: asText(value.content), version: typeof version === "string" ? version : version === void 0 ? void 0 : String(version) };
424
+ }
425
+ return { text: asText(value) };
426
+ }
427
+ function clipBytes(text2, max) {
428
+ if (utf8Length(text2) <= max)
429
+ return { text: text2, clipped: false };
430
+ let out = "";
431
+ let bytes = 0;
432
+ for (const ch of text2) {
433
+ const n2 = utf8Length(ch);
434
+ if (bytes + n2 > max)
435
+ break;
436
+ out += ch;
437
+ bytes += n2;
438
+ }
439
+ return { text: out, clipped: true };
440
+ }
441
+ function pageText(text2, offset = 1, limit) {
442
+ const lines = text2.split("\n");
443
+ const start = Math.max(1, Math.floor(offset));
444
+ if (start > lines.length && !(start === 1 && lines.length === 1))
445
+ return `[offset ${start} is past the end: ${lines.length} lines]`;
446
+ const wanted = limit === void 0 ? lines.length : Math.max(1, Math.floor(limit));
447
+ const out = [];
448
+ let bytes = 0;
449
+ let i2 = start - 1;
450
+ for (; i2 < lines.length && out.length < wanted; i2++) {
451
+ const n2 = utf8Length(lines[i2]) + 1;
452
+ if (out.length > 0 && bytes + n2 > MAX_RESULT_BYTES)
453
+ break;
454
+ out.push(lines[i2]);
455
+ bytes += n2;
456
+ }
457
+ let body = out.join("\n");
458
+ if (out.length === 1 && utf8Length(body) > MAX_RESULT_BYTES)
459
+ body = clipBytes(body, MAX_RESULT_BYTES).text + " …";
460
+ if (i2 < lines.length)
461
+ body += `
462
+ [lines ${start}–${i2} of ${lines.length}; read on with offset=${i2 + 1}]`;
463
+ return body;
464
+ }
465
+ function parseScalar(raw) {
466
+ const v = raw.trim();
467
+ if (v === "true")
468
+ return true;
469
+ if (v === "false")
470
+ return false;
471
+ if (v === "null")
472
+ return null;
473
+ if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(v))
474
+ return Number(v);
475
+ if (v.startsWith("{") || v.startsWith("[")) {
476
+ try {
477
+ return JSON.parse(v);
478
+ } catch {
479
+ return v;
480
+ }
481
+ }
482
+ return v;
483
+ }
484
+ const UNSUPPORTED_XCALL_KEYS = [
485
+ "config",
486
+ "route-config",
487
+ "session-id",
488
+ "session_id",
489
+ "idempotency-key",
490
+ "idempotency_key",
491
+ "confirm-token",
492
+ "confirm_token",
493
+ "trace-id",
494
+ "trace_id"
495
+ ];
496
+ function parseXcall(tokens) {
497
+ let object;
498
+ let action;
499
+ let params = {};
500
+ const pairs = {};
501
+ const positionals = [];
502
+ const json = (raw, name) => {
503
+ try {
504
+ return JSON.parse(raw);
505
+ } catch (e3) {
506
+ fail(`invalid \`${name}\` JSON value \`${raw}\`: ${e3 instanceof Error ? e3.message : String(e3)}
507
+ usage: ${XCALL_USAGE}`);
508
+ }
509
+ };
510
+ const unsupported = (t) => fail(`unsupported flag \`${t}\` (routing and confirmation are the page's)
511
+ usage: ${XCALL_USAGE}`);
512
+ for (let i2 = 0; i2 < tokens.length; i2++) {
513
+ const t = tokens[i2];
514
+ if (t === "--params") {
515
+ const v = tokens[++i2];
516
+ if (v === void 0)
517
+ fail(`missing value for --params
518
+ usage: ${XCALL_USAGE}`);
519
+ params = json(v, "--params");
520
+ } else if (t.startsWith("--")) {
521
+ const eq = t.indexOf("=");
522
+ if (eq < 0)
523
+ unsupported(t);
524
+ const key = t.slice(2, eq);
525
+ const value = t.slice(eq + 1);
526
+ if (key === "params")
527
+ params = json(value, "--params");
528
+ else if (!key.trim() || key.startsWith("-") || UNSUPPORTED_XCALL_KEYS.includes(key))
529
+ unsupported(t);
530
+ else
531
+ pairs[key] = parseScalar(value);
532
+ } else if (t.includes("=")) {
533
+ const eq = t.indexOf("=");
534
+ const key = t.slice(0, eq);
535
+ const value = t.slice(eq + 1);
536
+ if (key === "object")
537
+ object = value;
538
+ else if (key === "action")
539
+ action = value;
540
+ else if (key === "params")
541
+ params = json(value, "params");
542
+ else if (UNSUPPORTED_XCALL_KEYS.includes(key))
543
+ unsupported(t);
544
+ else
545
+ pairs[key] = parseScalar(value);
546
+ } else {
547
+ positionals.push(t);
548
+ }
549
+ }
550
+ object = object ?? positionals[0];
551
+ action = action ?? positionals[1];
552
+ if (positionals[2] !== void 0)
553
+ params = json(positionals[2], "params");
554
+ if (positionals.length > 3)
555
+ fail(`unexpected positional argument \`${positionals[3]}\`
556
+ usage: ${XCALL_USAGE}`);
557
+ if (Object.keys(pairs).length) {
558
+ if (!isObject(params))
559
+ fail(`key=value params require object params
560
+ usage: ${XCALL_USAGE}`);
561
+ params = { ...params, ...pairs };
562
+ }
563
+ if (!object || !action)
564
+ fail(`xcall needs an object and an action
565
+ usage: ${XCALL_USAGE}`);
566
+ if (!isObject(params))
567
+ fail(`params must be a JSON object
568
+ usage: ${XCALL_USAGE}`);
569
+ return { object, action, params };
570
+ }
571
+ function commandUsage(name, c3) {
572
+ var _a;
573
+ const lines = [`${name} — ${c3.summary}`];
574
+ if (c3.description)
575
+ lines.push("", c3.description);
576
+ const pos = (c3.positionals ?? []).map((p3) => p3.required === false ? `[${p3.name}]` : `<${p3.name}>`).join(" ");
577
+ lines.push("", `usage: ${name}${pos ? ` ${pos}` : ""}${(c3.options ?? []).length ? " [options]" : ""}`);
578
+ for (const p3 of c3.positionals ?? [])
579
+ lines.push(` ${p3.name} ${p3.description}`);
580
+ if ((c3.options ?? []).length)
581
+ lines.push("options:");
582
+ for (const o2 of c3.options ?? []) {
583
+ lines.push(` --${o2.name}${o2.type === "boolean" ? "" : ` <${o2.type}>`}${o2.required ? " (required)" : ""} ${o2.description}${o2.enum ? ` (${o2.enum.join(" | ")})` : ""}`);
584
+ }
585
+ if ((_a = c3.examples) == null ? void 0 : _a.length) {
586
+ lines.push("examples:");
587
+ for (const e3 of c3.examples)
588
+ lines.push(` ${e3}`);
589
+ }
590
+ return lines.join("\n");
591
+ }
592
+ const OBJECT_ARGS = (props, required) => ({ type: "object", properties: props, required });
593
+ function siteTools(options) {
594
+ const patterns = Object.entries(options.resources ?? {}).map(([raw, decl]) => parsePattern(raw, decl));
595
+ const origins = new Set(patterns.map((p3) => p3.origin).filter((o2) => o2 !== void 0));
596
+ const commands = new Map(Object.entries(options.commands ?? {}));
597
+ if (commands.has("xcall"))
598
+ throw new Error("siteTools: `xcall` is built in; declare actions on resources instead");
599
+ const resolve = (uri, ctx) => {
600
+ const n2 = normalizeUri(uri, origins);
601
+ for (const p3 of patterns) {
602
+ const params = matchPattern(p3, n2.origin, n2.segments);
603
+ if (params)
604
+ return { uri: n2.text, pattern: p3.raw, params, query: n2.query, ctx, decl: p3.decl };
605
+ }
606
+ fail(`uri \`${uri}\` is not a resource of this page; read uri="/" lists them`);
607
+ };
608
+ const discovery = () => {
609
+ const lines = ['Resources (read uri="<resource>"; {name} is one path segment):'];
610
+ for (const p3 of patterns) {
611
+ const methods = ["read", "write", "edit"].filter((m2) => m2 === "edit" ? !!(p3.decl.edit || p3.decl.read && p3.decl.write) : !!p3.decl[m2]);
612
+ lines.push(`- ${p3.raw} — ${p3.decl.description} [${methods.join(", ") || "no methods"}]`);
613
+ for (const [name, a11] of Object.entries(p3.decl.actions ?? {}))
614
+ lines.push(` action ${name} (risk: ${a11.risk}) — ${a11.description}`);
615
+ }
616
+ if (patterns.length === 0)
617
+ lines.push("(none)");
618
+ lines.push("", 'Commands (exec "<command> --help" for usage):');
619
+ lines.push(`- xcall — call an action of a resource: ${XCALL_USAGE}`);
620
+ for (const [name, c3] of commands)
621
+ lines.push(`- ${name} — ${c3.summary}`);
622
+ return lines.join("\n");
623
+ };
624
+ const exec = async (command, ctx) => {
625
+ var _a;
626
+ const words = (() => {
627
+ try {
628
+ return parseShellLine(command);
629
+ } catch (e3) {
630
+ fail(`${e3 instanceof Error ? e3.message : String(e3)}; exec runs one command, it is not a shell`);
631
+ }
632
+ })();
633
+ const available = `available commands: xcall${commands.size ? `, ${[...commands.keys()].join(", ")}` : ""}`;
634
+ const unquoted = command.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "");
635
+ if (SHELL_CHARS.test(unquoted)) {
636
+ 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}`);
637
+ }
638
+ const [name, ...args] = words;
639
+ if (!name)
640
+ fail(`empty command; ${available}`);
641
+ if (name === "xcall") {
642
+ if (args.includes("--help") || args.includes("-h"))
643
+ return `usage: ${XCALL_USAGE}
644
+ The actions of each resource are listed by read uri="/".`;
645
+ const { object, action, params } = parseXcall(args);
646
+ const m2 = resolve(object, ctx);
647
+ const decl = (_a = m2.decl.actions) == null ? void 0 : _a[action];
648
+ if (!decl) {
649
+ const known = Object.keys(m2.decl.actions ?? {});
650
+ fail(`resource \`${m2.pattern}\` has no action \`${action}\` (actions: ${known.length ? known.join(", ") : "none"})`);
651
+ }
652
+ if (decl.input !== void 0) {
653
+ const invalid = validateJson(decl.input, params);
654
+ if (invalid)
655
+ fail(`invalid params for ${action}: ${invalid}`);
656
+ }
657
+ const { decl: _decl, ...match } = m2;
658
+ const result = await decl.call(match, params);
659
+ return `[risk: ${decl.risk}]
660
+ ${clipBytes(asText(result) || "ok", MAX_RESULT_BYTES).text}`;
661
+ }
662
+ const c3 = commands.get(name);
663
+ if (!c3)
664
+ fail(`unknown command \`${name}\`; exec runs one command, it is not a shell. ${available}`);
665
+ let input;
666
+ try {
667
+ const parsed = parseArgv({ positionals: c3.positionals, options: c3.options }, args);
668
+ if (parsed.help)
669
+ return commandUsage(name, c3);
670
+ for (let i2 = parsed.positionalCount; i2 < (c3.positionals ?? []).length; i2++) {
671
+ if ((c3.positionals ?? [])[i2].required !== false)
672
+ throw new CommandArgsError("MISSING_ARGUMENT", `missing positional argument: ${(c3.positionals ?? [])[i2].name}`);
673
+ }
674
+ for (const o2 of c3.options ?? []) {
675
+ const prop = o2.property ?? o2.name.split("-").join("_");
676
+ if (o2.required && !(prop in parsed.input))
677
+ throw new CommandArgsError("MISSING_ARGUMENT", `--${o2.name} is required`);
678
+ }
679
+ input = parsed.input;
680
+ if (c3.inputSchema)
681
+ validateSchema(input, c3.inputSchema, "input");
682
+ } catch (e3) {
683
+ if (e3 instanceof CommandArgsError)
684
+ fail(`${name}: ${e3.message}
685
+
686
+ ${commandUsage(name, c3)}`);
687
+ throw e3;
688
+ }
689
+ return clipBytes(asText(await c3.call(input, ctx)) || "ok", MAX_RESULT_BYTES).text;
690
+ };
691
+ const readRaw = async (m2) => {
692
+ if (!m2.decl.read)
693
+ fail(`resource \`${m2.pattern}\` cannot be read`);
694
+ const { decl: _d, ...match } = m2;
695
+ return versioned(await m2.decl.read(match));
696
+ };
697
+ return {
698
+ read: {
699
+ spec: {
700
+ 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.`,
701
+ args_schema: OBJECT_ARGS({
702
+ uri: { type: "string", description: 'Resource URI, e.g. "/" or "notes/1"' },
703
+ offset: { type: "integer", description: "First line, 1-based" },
704
+ limit: { type: "integer", description: "Number of lines" }
705
+ }, ["uri"])
706
+ },
707
+ idempotent: true,
708
+ async call(args, ctx) {
709
+ const uri = String(args.uri);
710
+ const offset = typeof args.offset === "number" ? args.offset : void 0;
711
+ const limit = typeof args.limit === "number" ? args.limit : void 0;
712
+ if (uri.trim() === "/" || uri.trim() === "")
713
+ return pageText(discovery(), offset, limit);
714
+ const r3 = await readRaw(resolve(uri, ctx));
715
+ return pageText(r3.text, offset, limit);
716
+ }
717
+ },
718
+ write: {
719
+ spec: {
720
+ 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.`,
721
+ args_schema: OBJECT_ARGS({
722
+ uri: { type: "string", description: "Resource URI" },
723
+ content: { type: "string", description: "The content" },
724
+ mode: { type: "string", enum: ["write", "new", "append"], description: "write | new | append" }
725
+ }, ["uri", "content"])
726
+ },
727
+ async call(args, ctx) {
728
+ const m2 = resolve(String(args.uri), ctx);
729
+ if (!m2.decl.write)
730
+ fail(`resource \`${m2.pattern}\` is read-only`);
731
+ const { decl, ...match } = m2;
732
+ const mode = typeof args.mode === "string" ? args.mode : "write";
733
+ return asText(await decl.write(match, { content: String(args.content), mode })) || "written";
734
+ }
735
+ },
736
+ edit: {
737
+ spec: {
738
+ description: "Change part of a resource (PATCH): old_string must occur exactly once in its current content and is replaced by new_string.",
739
+ args_schema: OBJECT_ARGS({
740
+ uri: { type: "string", description: "Resource URI" },
741
+ old_string: { type: "string", description: "Text to replace; must occur exactly once" },
742
+ new_string: { type: "string", description: "Replacement text" }
743
+ }, ["uri", "old_string", "new_string"])
744
+ },
745
+ async call(args, ctx) {
746
+ const m2 = resolve(String(args.uri), ctx);
747
+ const body = { old_string: String(args.old_string), new_string: String(args.new_string) };
748
+ const { decl, ...match } = m2;
749
+ if (decl.edit)
750
+ return asText(await decl.edit(match, body)) || "edited";
751
+ if (!decl.read || !decl.write)
752
+ fail(`resource \`${m2.pattern}\` cannot be edited`);
753
+ if (!body.old_string)
754
+ fail("old_string is empty");
755
+ const current = versioned(await decl.read(match));
756
+ const count = current.text.split(body.old_string).length - 1;
757
+ if (count === 0)
758
+ fail("old_string was not found in the current content; read it again");
759
+ if (count > 1)
760
+ fail(`old_string occurs ${count} times; give more context so it occurs exactly once`);
761
+ const content = current.text.replace(body.old_string, () => body.new_string);
762
+ const w2 = { content, mode: "write" };
763
+ if (current.version !== void 0)
764
+ w2.ifVersion = current.version;
765
+ return asText(await decl.write(match, w2)) || "edited";
766
+ }
767
+ },
768
+ exec: {
769
+ spec: {
770
+ 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.`,
771
+ args_schema: OBJECT_ARGS({ command: { type: "string", description: "One command line" } }, ["command"])
772
+ },
773
+ idempotent: (args) => execIsIdempotent(String(args.command ?? ""), patterns, origins, commands),
774
+ call: (args, ctx) => exec(String(args.command), ctx)
775
+ }
776
+ };
777
+ }
778
+ function execIsIdempotent(command, patterns, origins, commands) {
779
+ var _a, _b, _c;
780
+ let words;
781
+ try {
782
+ words = parseShellLine(command);
783
+ } catch {
784
+ return false;
785
+ }
786
+ const [name, ...args] = words;
787
+ if (name === "xcall") {
788
+ try {
789
+ const { object, action } = parseXcall(args);
790
+ const n2 = normalizeUri(object, origins);
791
+ const p3 = patterns.find((q2) => matchPattern(q2, n2.origin, n2.segments));
792
+ const risk = (_b = (_a = p3 == null ? void 0 : p3.decl.actions) == null ? void 0 : _a[action]) == null ? void 0 : _b.risk;
793
+ return risk === "read_only" || risk === "idempotent_write";
794
+ } catch {
795
+ return false;
796
+ }
797
+ }
798
+ const c3 = name ? commands.get(name) : void 0;
799
+ return ((_c = c3 == null ? void 0 : c3.access) == null ? void 0 : _c.level) === "read";
800
+ }
801
+ const INDEX_TRAIT_URI = "https://buckyos.org/traits/index@1";
802
+ function text(v, key) {
803
+ return isObject(v) && typeof v[key] === "string" ? v[key] : "";
804
+ }
805
+ function riskRank(r3) {
806
+ const i2 = ACTION_RISKS.indexOf(r3);
807
+ return i2 < 0 ? ACTION_RISKS.length : i2;
808
+ }
809
+ function renderObjectDocument(canonical, card, profile, summary) {
810
+ const lines = [`Object: ${canonical}`, `Object DID: ${card.id}`];
811
+ const aliases = (card.alsoKnownAs ?? []).filter((a11) => a11 !== canonical);
812
+ if (aliases.length)
813
+ lines.push(`Also known as: ${aliases.join(", ")}`);
814
+ for (const [label, key] of [["Title", "title"], ["Description", "description"]]) {
815
+ const v = text(profile, key);
816
+ if (v)
817
+ lines.push(`${label}: ${v}`);
818
+ }
819
+ for (const [section, key] of [["Properties", "properties"], ["Actions", "actions"], ["Events", "events"]]) {
820
+ const entries = isObject(profile) ? profile[key] : void 0;
821
+ if (!isObject(entries) || Object.keys(entries).length === 0)
822
+ continue;
823
+ lines.push(`${section}:`);
824
+ for (const name of Object.keys(entries).sort()) {
825
+ const e3 = entries[name];
826
+ let line = `- ${name}`;
827
+ const d2 = text(e3, "description");
828
+ if (d2)
829
+ line += `: ${d2}`;
830
+ const risk = text(e3, "x-buckyos:risk");
831
+ if (risk)
832
+ line += ` (risk: ${risk})`;
833
+ lines.push(line);
834
+ }
835
+ }
836
+ const names = Object.keys(summary);
837
+ if (names.length) {
838
+ lines.push("Summary:");
839
+ for (const name of names)
840
+ lines.push(`- ${name}:`, JSON.stringify(summary[name], null, 2));
841
+ }
842
+ return lines.join("\n");
843
+ }
844
+ function isCollection(profile) {
845
+ const traits = isObject(profile) ? profile["x-buckyos:traits"] : void 0;
846
+ return Array.isArray(traits) && traits.includes(INDEX_TRAIT_URI);
847
+ }
848
+ async function didObjectResources(options) {
849
+ const maxRank = riskRank(options.maxRisk ?? "read_only");
850
+ const out = {};
851
+ for (const root of options.roots) {
852
+ const client = options.client;
853
+ const profile = await client.profile(root);
854
+ const collection = isCollection(profile);
855
+ const actions = {};
856
+ const declared = isObject(profile) && isObject(profile.actions) ? profile.actions : {};
857
+ for (const [name, a11] of Object.entries(declared)) {
858
+ if (collection && (name === "query" || name === "page"))
859
+ continue;
860
+ const risk = text(a11, "x-buckyos:risk");
861
+ if (riskRank(risk) > maxRank)
862
+ continue;
863
+ const input = isObject(a11) ? a11.input : void 0;
864
+ actions[name] = {
865
+ description: text(a11, "description"),
866
+ risk,
867
+ ...input !== void 0 && input !== null ? { input } : {},
868
+ call: (_m, params) => client.invoke(root, name, params)
869
+ };
870
+ }
871
+ const description = [text(profile, "title"), text(profile, "description")].filter(Boolean).join(" — ") || root;
872
+ out[root] = {
873
+ description: collection ? `${description} (a collection: read it with a query, ?cursor=… for the next page)` : description,
874
+ actions,
875
+ async read(m2) {
876
+ if (collection && [...m2.query.keys()].length > 0) {
877
+ const cursor = m2.query.get("cursor");
878
+ const pageSize = m2.query.get("page_size");
879
+ if (cursor)
880
+ return client.invoke(root, "page", { cursor, ...pageSize ? { page_size: Number(pageSize) } : {} });
881
+ const query = {};
882
+ for (const [k3, v] of m2.query)
883
+ if (k3 !== "page_size")
884
+ query[k3] = v;
885
+ return client.invoke(root, "query", { query, ...pageSize ? { page_size: Number(pageSize) } : {} });
886
+ }
887
+ const card = await client.card(root);
888
+ const props = isObject(profile) && isObject(profile.properties) ? Object.keys(profile.properties).filter((p3) => p3 !== "index_schema") : [];
889
+ const listed = isObject(profile) && Array.isArray(profile["x-buckyos:summary_props"]) ? profile["x-buckyos:summary_props"].filter((p3) => typeof p3 === "string") : props;
890
+ const summary = {};
891
+ for (const p3 of listed)
892
+ summary[p3] = await client.readProperty(root, p3);
893
+ return renderObjectDocument(root, { id: String(card.id), alsoKnownAs: card.alsoKnownAs }, profile, summary);
894
+ }
895
+ };
896
+ }
897
+ return out;
898
+ }
899
+ const XLLM_RUNS_DB = "xllm-runs";
900
+ const RECORDS = "records";
901
+ const SNAPSHOTS = "snapshots";
902
+ function req(r3) {
903
+ return new Promise((resolve, reject) => {
904
+ r3.onsuccess = () => resolve(r3.result);
905
+ r3.onerror = () => reject(r3.error);
906
+ });
907
+ }
908
+ function done(tx) {
909
+ return new Promise((resolve, reject) => {
910
+ tx.oncomplete = () => resolve();
911
+ tx.onerror = () => reject(tx.error);
912
+ tx.onabort = () => reject(tx.error ?? new Error("transaction aborted"));
913
+ });
914
+ }
915
+ class IndexedDbRunStore {
916
+ constructor(options = {}) {
917
+ this.options = options;
918
+ this.persistent = true;
919
+ this.localLocks = /* @__PURE__ */ new Set();
920
+ }
921
+ open() {
922
+ if (!this.db) {
923
+ const factory = this.options.idb ?? globalThis.indexedDB;
924
+ if (!factory)
925
+ return Promise.reject(XllmError.storage("IndexedDB is not available here"));
926
+ const r3 = factory.open(this.options.dbName ?? XLLM_RUNS_DB, 1);
927
+ r3.onupgradeneeded = () => {
928
+ const db = r3.result;
929
+ if (!db.objectStoreNames.contains(RECORDS))
930
+ db.createObjectStore(RECORDS, { keyPath: "run_id" });
931
+ if (!db.objectStoreNames.contains(SNAPSHOTS))
932
+ db.createObjectStore(SNAPSHOTS);
933
+ };
934
+ this.db = req(r3);
935
+ }
936
+ return this.db;
937
+ }
938
+ locks() {
939
+ var _a;
940
+ if (this.options.locks === null)
941
+ return void 0;
942
+ return this.options.locks ?? ((_a = globalThis.navigator) == null ? void 0 : _a.locks);
943
+ }
944
+ runsDir() {
945
+ return void 0;
946
+ }
947
+ runDir() {
948
+ return void 0;
949
+ }
950
+ async createRun() {
951
+ const db = await this.open();
952
+ for (let i2 = 0; i2 < 8; i2++) {
953
+ const id = generateRunId();
954
+ const existing = await req(db.transaction(RECORDS).objectStore(RECORDS).get(id));
955
+ if (!existing)
956
+ return id;
957
+ }
958
+ throw XllmError.storage("cannot allocate a unique run id");
959
+ }
960
+ async writeRecord(record) {
961
+ const db = await this.open();
962
+ const tx = db.transaction(RECORDS, "readwrite");
963
+ tx.objectStore(RECORDS).put(JSON.parse(JSON.stringify(record)));
964
+ await done(tx);
965
+ }
966
+ async readRecord(runId) {
967
+ const db = await this.open();
968
+ const rec = await req(db.transaction(RECORDS).objectStore(RECORDS).get(runId));
969
+ if (!rec)
970
+ throw new XllmError({ kind: "run_not_found", run_id: runId, runs_dir: `indexeddb:${this.options.dbName ?? XLLM_RUNS_DB}` });
971
+ if (rec.version !== RUN_RECORD_VERSION)
972
+ throw XllmError.notResumable(runId, "unsupported run record version");
973
+ return rec;
974
+ }
975
+ async listRecords() {
976
+ const db = await this.open();
977
+ return await req(db.transaction(RECORDS).objectStore(RECORDS).getAll());
978
+ }
979
+ async putSnapshot(runId, snapshot) {
980
+ const db = await this.open();
981
+ const tx = db.transaction(SNAPSHOTS, "readwrite");
982
+ const store = tx.objectStore(SNAPSHOTS);
983
+ const keys = await req(store.getAllKeys(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER])));
984
+ const next = keys.length ? Math.max(...keys.map((k3) => k3[1])) + 1 : 1;
985
+ store.put(JSON.parse(JSON.stringify(snapshot)), [runId, next]);
986
+ await done(tx);
987
+ return next;
988
+ }
989
+ async getSnapshot(runId, idx) {
990
+ const db = await this.open();
991
+ const s2 = await req(db.transaction(SNAPSHOTS).objectStore(SNAPSHOTS).get([runId, idx]));
992
+ if (!s2)
993
+ throw new XllmError({ kind: "corrupted_run", run_id: runId, reason: `snapshot ${idx} missing` });
994
+ return s2;
995
+ }
996
+ async listSnapshots(runId) {
997
+ const db = await this.open();
998
+ const keys = await req(db.transaction(SNAPSHOTS).objectStore(SNAPSHOTS).getAllKeys(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER])));
999
+ return keys.map((k3) => k3[1]).sort((a11, b3) => a11 - b3);
1000
+ }
1001
+ async lockRun(runId) {
1002
+ const name = `xllm-run:${runId}`;
1003
+ const locks = this.locks();
1004
+ if (!locks) {
1005
+ if (this.localLocks.has(name))
1006
+ return null;
1007
+ this.localLocks.add(name);
1008
+ return { release: () => {
1009
+ this.localLocks.delete(name);
1010
+ } };
1011
+ }
1012
+ return new Promise((resolve, reject) => {
1013
+ locks.request(name, { ifAvailable: true }, (lock) => {
1014
+ if (!lock) {
1015
+ resolve(null);
1016
+ return Promise.resolve();
1017
+ }
1018
+ return new Promise((release) => resolve({ release: () => release() }));
1019
+ }).catch(reject);
1020
+ });
1021
+ }
1022
+ async isRunLive(runId) {
1023
+ const name = `xllm-run:${runId}`;
1024
+ const locks = this.locks();
1025
+ if (!locks)
1026
+ return this.localLocks.has(name);
1027
+ const state = await locks.query();
1028
+ return (state.held ?? []).some((l3) => l3.name === name);
1029
+ }
1030
+ async removeRun(runId) {
1031
+ const db = await this.open();
1032
+ const tx = db.transaction([RECORDS, SNAPSHOTS], "readwrite");
1033
+ tx.objectStore(RECORDS).delete(runId);
1034
+ tx.objectStore(SNAPSHOTS).delete(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER]));
1035
+ await done(tx);
1036
+ }
1037
+ async importRun(run) {
1038
+ const db = await this.open();
1039
+ const tx = db.transaction([RECORDS, SNAPSHOTS], "readwrite");
1040
+ tx.objectStore(RECORDS).put(JSON.parse(JSON.stringify(run.record)));
1041
+ for (const [idx, s2] of run.snapshots)
1042
+ tx.objectStore(SNAPSHOTS).put(JSON.parse(JSON.stringify(s2)), [run.record.run_id, idx]);
1043
+ await done(tx);
1044
+ }
1045
+ }
1046
+ export {
1047
+ ACTION_RISKS,
1048
+ a8 as AGENT_TOOL_PROTOCOL_VERSION,
1049
+ A as AiccLlmClient,
1050
+ B as ByteHeuristicTokenizer,
1051
+ D as DEFAULT_CONTEXT_YIELD_RATIO,
1052
+ h2 as DEFAULT_LLM_TIMEOUT_SECS,
1053
+ i as DEFAULT_MAX_CONSECUTIVE_ERRORS,
1054
+ j2 as DEFAULT_MAX_TOOL_ITERATIONS,
1055
+ k2 as DEFAULT_TASK_WAIT_MS,
1056
+ l2 as DEFAULT_TIMEOUT_SECS,
1057
+ D2 as DIDObjectClient,
1058
+ a10 as DIDObjectError,
1059
+ ao as HINT_NS_DEDUP,
1060
+ ap as HINT_NS_ONCE,
1061
+ V as HOST_PROMPT_SECTIONS_ALL,
1062
+ W as HOST_PROMPT_SECTIONS_NONE,
1063
+ INDEX_TRAIT_URI,
1064
+ IndexedDbRunStore,
1065
+ L as LLMComputeException,
1066
+ L2 as LLMContext,
1067
+ e2 as LLMContextInterruptHandle,
1068
+ ae as LlmSummarizeCompressor,
1069
+ a4 as MAX_IMAGE_ATTACHMENT_BYTES,
1070
+ M as MAX_INJECTIONS_PER_BOUNDARY,
1071
+ m as MAX_IN_TOOL_WAIT_MS,
1072
+ MAX_RESULT_BYTES,
1073
+ a5 as MAX_TEXT_ATTACHMENT_BYTES,
1074
+ aq as MemoryHintLedger,
1075
+ G as MemoryRunStore,
1076
+ Y as REFUSED_CREDENTIALS,
1077
+ K as REPORT_ARTIFACTS_KEY,
1078
+ z as RUNTIME_PROTOCOL_VERSION,
1079
+ RUN_RECORD_VERSION,
1080
+ SITE_RUNTIME_KIND,
1081
+ b2 as SNAPSHOT_FORMAT_VERSION,
1082
+ af as SUMMARIZE_MODEL_ALIAS,
1083
+ SiteToolManager,
1084
+ x as TemplateEnv,
1085
+ aA as TimeoutLlmClient,
1086
+ T as ToolDispatchException,
1087
+ XCALL_USAGE,
1088
+ XLLM_RUNS_DB,
1089
+ X as XllmActionParser,
1090
+ XllmError,
1091
+ Z as XllmInterrupter,
1092
+ _ as XllmRun,
1093
+ $ as XllmTask,
1094
+ ac as XmlStepRenderer,
1095
+ h as aiccProviderFailure,
1096
+ f2 as allowAllPolicy,
1097
+ j as anyJsonObjectSchema,
1098
+ ar as applyHints,
1099
+ a as asComputeError,
1100
+ a9 as asToolResult,
1101
+ y as assemblePrompt,
1102
+ A2 as buildCmdManualSystemText,
1103
+ C as buildRulesSystemText,
1104
+ E as buildRuntimeProtocol,
1105
+ F as buildRuntimeProtocolFor,
1106
+ d as charCount,
1107
+ a0 as classifyError,
1108
+ ag as compactionTargetTokens,
1109
+ ah as compress,
1110
+ ai as compressHistory,
1111
+ aj as compressOptions,
1112
+ c as computeErrorMessage,
1113
+ o as computeToolsConfig,
1114
+ createSiteRuntime,
1115
+ didObjectResources,
1116
+ a6 as envelopeObservation,
1117
+ e as errorSource,
1118
+ H as exportRun,
1119
+ J as extractResult,
1120
+ au as followupGeneralHint,
1121
+ av as followupHint,
1122
+ generateRunId,
1123
+ I as importRun,
1124
+ aw as inCallWaitMs,
1125
+ a1 as inFlightCall,
1126
+ b as infraRetrySafe,
1127
+ a7 as isIdempotent,
1128
+ ak as isSummaryMessage,
1129
+ a2 as isTerminal,
1130
+ l as llmCorrectable,
1131
+ P as materializeHistory,
1132
+ q as mergeConfigLayers,
1133
+ n as noopWorklog,
1134
+ normalizeUri,
1135
+ aa as observationText,
1136
+ pageText,
1137
+ w as parseLlmContextJson,
1138
+ p2 as parseReply,
1139
+ al as parseSummaryMessage,
1140
+ p as providerError,
1141
+ k as providerErrorFromRpc,
1142
+ as as renderHintBlock,
1143
+ renderObjectDocument,
1144
+ Q as renderStepHistory,
1145
+ at as renderWithHints,
1146
+ N as reportArtifacts,
1147
+ r2 as resolveToolSpecs,
1148
+ ax as resultView,
1149
+ U as rewritableHistory,
1150
+ a3 as runRequest,
1151
+ r as rustTrim,
1152
+ f as rustTrimEnd,
1153
+ g as rustTrimStart,
1154
+ s as serdeJson,
1155
+ siteTools,
1156
+ O as splitReportResult,
1157
+ c2 as stateFromRequest,
1158
+ am as summaryMessage,
1159
+ an as summaryModel,
1160
+ ay as taskStateObservation,
1161
+ ab as toHost,
1162
+ ad as toolResultViewFromHost,
1163
+ unresolvedReason,
1164
+ validateJson,
1165
+ az as waitUntilMs
1166
+ };
1167
+ //# sourceMappingURL=xllm.mjs.map