buckyos 0.7.170 → 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.
Files changed (200) 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/browser.cjs +1 -1
  22. package/dist/browser.cjs.map +1 -1
  23. package/dist/browser.d.ts +2 -0
  24. package/dist/browser.d.ts.map +1 -1
  25. package/dist/browser.mjs +204 -194
  26. package/dist/browser.mjs.map +1 -1
  27. package/dist/did_object_client-6a1b108a.js +2 -0
  28. package/dist/did_object_client-6a1b108a.js.map +1 -0
  29. package/dist/did_object_client-7fa36f90.mjs +87 -0
  30. package/dist/did_object_client-7fa36f90.mjs.map +1 -0
  31. package/dist/did_object_client.d.ts +39 -0
  32. package/dist/did_object_client.d.ts.map +1 -0
  33. package/dist/{executor_client-5f4d0468.mjs → executor_client-c620d25c.mjs} +233 -748
  34. package/dist/executor_client-c620d25c.mjs.map +1 -0
  35. package/dist/executor_client-d4439d54.js +13 -0
  36. package/dist/executor_client-d4439d54.js.map +1 -0
  37. package/dist/executor_client.d.ts +129 -0
  38. package/dist/executor_client.d.ts.map +1 -1
  39. package/dist/index.cjs +1 -1
  40. package/dist/index.cjs.map +1 -1
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.mjs +209 -199
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/internal/command_args.d.ts +67 -0
  46. package/dist/internal/command_args.d.ts.map +1 -0
  47. package/dist/krpc_client-26c2dc8b.js +2 -0
  48. package/dist/krpc_client-26c2dc8b.js.map +1 -0
  49. package/dist/krpc_client-673448e5.mjs +173 -0
  50. package/dist/krpc_client-673448e5.mjs.map +1 -0
  51. package/dist/krpc_client.d.ts +5 -1
  52. package/dist/krpc_client.d.ts.map +1 -1
  53. package/dist/{ndn_types-ab30fac0.mjs → ndn_types-0fac2499.mjs} +115 -215
  54. package/dist/ndn_types-0fac2499.mjs.map +1 -0
  55. package/dist/ndn_types-5b138882.js +2 -0
  56. package/dist/ndn_types-5b138882.js.map +1 -0
  57. package/dist/node.cjs +1 -1
  58. package/dist/node.cjs.map +1 -1
  59. package/dist/node.mjs +201 -194
  60. package/dist/node.mjs.map +1 -1
  61. package/dist/object_url-8fb5a7bf.js +2 -0
  62. package/dist/object_url-8fb5a7bf.js.map +1 -0
  63. package/dist/object_url-f72c1704.mjs +412 -0
  64. package/dist/object_url-f72c1704.mjs.map +1 -0
  65. package/dist/openai-ae2978de.mjs +163 -0
  66. package/dist/openai-ae2978de.mjs.map +1 -0
  67. package/dist/openai-f560d518.js +2 -0
  68. package/dist/openai-f560d518.js.map +1 -0
  69. package/dist/provision.cjs +6 -6
  70. package/dist/provision.cjs.map +1 -1
  71. package/dist/provision.mjs +4 -3
  72. package/dist/provision.mjs.map +1 -1
  73. package/dist/site_manager-11a7a468.mjs +6410 -0
  74. package/dist/site_manager-11a7a468.mjs.map +1 -0
  75. package/dist/site_manager-334b1a51.js +2 -0
  76. package/dist/site_manager-334b1a51.js.map +1 -0
  77. package/dist/{tus_client-b231b248.js → tus_client-809c90ab.js} +2 -2
  78. package/dist/{tus_client-b231b248.js.map → tus_client-809c90ab.js.map} +1 -1
  79. package/dist/{tus_client-d1ffe2d6.mjs → tus_client-893a3287.mjs} +2 -2
  80. package/dist/{tus_client-d1ffe2d6.mjs.map → tus_client-893a3287.mjs.map} +1 -1
  81. package/dist/xllm/core/action_parser.d.ts +15 -0
  82. package/dist/xllm/core/action_parser.d.ts.map +1 -0
  83. package/dist/xllm/core/behavior_loop.d.ts +20 -0
  84. package/dist/xllm/core/behavior_loop.d.ts.map +1 -0
  85. package/dist/xllm/core/behavior_result.d.ts +11 -0
  86. package/dist/xllm/core/behavior_result.d.ts.map +1 -0
  87. package/dist/xllm/core/config.d.ts +62 -0
  88. package/dist/xllm/core/config.d.ts.map +1 -0
  89. package/dist/xllm/core/context_window.d.ts +15 -0
  90. package/dist/xllm/core/context_window.d.ts.map +1 -0
  91. package/dist/xllm/core/deps.d.ts +97 -0
  92. package/dist/xllm/core/deps.d.ts.map +1 -0
  93. package/dist/xllm/core/errors.d.ts +94 -0
  94. package/dist/xllm/core/errors.d.ts.map +1 -0
  95. package/dist/xllm/core/interrupt.d.ts +31 -0
  96. package/dist/xllm/core/interrupt.d.ts.map +1 -0
  97. package/dist/xllm/core/json.d.ts +11 -0
  98. package/dist/xllm/core/json.d.ts.map +1 -0
  99. package/dist/xllm/core/json_check.d.ts +17 -0
  100. package/dist/xllm/core/json_check.d.ts.map +1 -0
  101. package/dist/xllm/core/loop.d.ts +135 -0
  102. package/dist/xllm/core/loop.d.ts.map +1 -0
  103. package/dist/xllm/core/messages.d.ts +18 -0
  104. package/dist/xllm/core/messages.d.ts.map +1 -0
  105. package/dist/xllm/core/observer.d.ts +14 -0
  106. package/dist/xllm/core/observer.d.ts.map +1 -0
  107. package/dist/xllm/core/open_runtime.d.ts +22 -0
  108. package/dist/xllm/core/open_runtime.d.ts.map +1 -0
  109. package/dist/xllm/core/prepare.d.ts +54 -0
  110. package/dist/xllm/core/prepare.d.ts.map +1 -0
  111. package/dist/xllm/core/prompt.d.ts +40 -0
  112. package/dist/xllm/core/prompt.d.ts.map +1 -0
  113. package/dist/xllm/core/protocol.d.ts +15 -0
  114. package/dist/xllm/core/protocol.d.ts.map +1 -0
  115. package/dist/xllm/core/result.d.ts +12 -0
  116. package/dist/xllm/core/result.d.ts.map +1 -0
  117. package/dist/xllm/core/run.d.ts +198 -0
  118. package/dist/xllm/core/run.d.ts.map +1 -0
  119. package/dist/xllm/core/rust_text.d.ts +20 -0
  120. package/dist/xllm/core/rust_text.d.ts.map +1 -0
  121. package/dist/xllm/core/site_policy.d.ts +5 -0
  122. package/dist/xllm/core/site_policy.d.ts.map +1 -0
  123. package/dist/xllm/core/store.d.ts +60 -0
  124. package/dist/xllm/core/store.d.ts.map +1 -0
  125. package/dist/xllm/core/suspension.d.ts +13 -0
  126. package/dist/xllm/core/suspension.d.ts.map +1 -0
  127. package/dist/xllm/core/tokenizer.d.ts +8 -0
  128. package/dist/xllm/core/tokenizer.d.ts.map +1 -0
  129. package/dist/xllm/core/types.d.ts +826 -0
  130. package/dist/xllm/core/types.d.ts.map +1 -0
  131. package/dist/xllm/core/xml.d.ts +19 -0
  132. package/dist/xllm/core/xml.d.ts.map +1 -0
  133. package/dist/xllm/dev/openai.d.ts +17 -0
  134. package/dist/xllm/dev/openai.d.ts.map +1 -0
  135. package/dist/xllm/dev/scripted.d.ts +46 -0
  136. package/dist/xllm/dev/scripted.d.ts.map +1 -0
  137. package/dist/xllm/dev.d.ts +5 -0
  138. package/dist/xllm/dev.d.ts.map +1 -0
  139. package/dist/xllm/hosts/browser/store.d.ts +41 -0
  140. package/dist/xllm/hosts/browser/store.d.ts.map +1 -0
  141. package/dist/xllm/hosts/deno/deno_api.d.ts +103 -0
  142. package/dist/xllm/hosts/deno/deno_api.d.ts.map +1 -0
  143. package/dist/xllm/hosts/deno/identity.d.ts +29 -0
  144. package/dist/xllm/hosts/deno/identity.d.ts.map +1 -0
  145. package/dist/xllm/hosts/deno/index.d.ts +47 -0
  146. package/dist/xllm/hosts/deno/index.d.ts.map +1 -0
  147. package/dist/xllm/hosts/deno/native_runtime.d.ts +93 -0
  148. package/dist/xllm/hosts/deno/native_runtime.d.ts.map +1 -0
  149. package/dist/xllm/hosts/deno/native_tools.d.ts +105 -0
  150. package/dist/xllm/hosts/deno/native_tools.d.ts.map +1 -0
  151. package/dist/xllm/hosts/deno/provider.d.ts +13 -0
  152. package/dist/xllm/hosts/deno/provider.d.ts.map +1 -0
  153. package/dist/xllm/hosts/deno/store.d.ts +60 -0
  154. package/dist/xllm/hosts/deno/store.d.ts.map +1 -0
  155. package/dist/xllm/index.d.ts +48 -0
  156. package/dist/xllm/index.d.ts.map +1 -0
  157. package/dist/xllm/providers/aicc.d.ts +22 -0
  158. package/dist/xllm/providers/aicc.d.ts.map +1 -0
  159. package/dist/xllm/providers/timeout.d.ts +12 -0
  160. package/dist/xllm/providers/timeout.d.ts.map +1 -0
  161. package/dist/xllm/runtime/compress.d.ts +149 -0
  162. package/dist/xllm/runtime/compress.d.ts.map +1 -0
  163. package/dist/xllm/runtime/did_object_resources.d.ts +21 -0
  164. package/dist/xllm/runtime/did_object_resources.d.ts.map +1 -0
  165. package/dist/xllm/runtime/hints.d.ts +23 -0
  166. package/dist/xllm/runtime/hints.d.ts.map +1 -0
  167. package/dist/xllm/runtime/site.d.ts +22 -0
  168. package/dist/xllm/runtime/site.d.ts.map +1 -0
  169. package/dist/xllm/runtime/site_manager.d.ts +38 -0
  170. package/dist/xllm/runtime/site_manager.d.ts.map +1 -0
  171. package/dist/xllm/runtime/site_tools.d.ts +76 -0
  172. package/dist/xllm/runtime/site_tools.d.ts.map +1 -0
  173. package/dist/xllm/runtime/step_renderer.d.ts +54 -0
  174. package/dist/xllm/runtime/step_renderer.d.ts.map +1 -0
  175. package/dist/xllm/runtime/task_model.d.ts +64 -0
  176. package/dist/xllm/runtime/task_model.d.ts.map +1 -0
  177. package/dist/xllm/runtime/tool_result.d.ts +39 -0
  178. package/dist/xllm/runtime/tool_result.d.ts.map +1 -0
  179. package/dist/xllm/runtime/types.d.ts +99 -0
  180. package/dist/xllm/runtime/types.d.ts.map +1 -0
  181. package/dist/xllm.cjs +2 -0
  182. package/dist/xllm.cjs.map +1 -0
  183. package/dist/xllm.mjs +1167 -0
  184. package/dist/xllm.mjs.map +1 -0
  185. package/dist/xllm_deno.cjs +2 -0
  186. package/dist/xllm_deno.cjs.map +1 -0
  187. package/dist/xllm_deno.mjs +2487 -0
  188. package/dist/xllm_deno.mjs.map +1 -0
  189. package/dist/xllm_dev.cjs +2 -0
  190. package/dist/xllm_dev.cjs.map +1 -0
  191. package/dist/xllm_dev.mjs +70 -0
  192. package/dist/xllm_dev.mjs.map +1 -0
  193. package/package.json +22 -1
  194. package/src/internal/command_args.ts +268 -0
  195. package/dist/executor_client-1ee523cf.js +0 -13
  196. package/dist/executor_client-1ee523cf.js.map +0 -1
  197. package/dist/executor_client-5f4d0468.mjs.map +0 -1
  198. package/dist/ndn_types-8c2696d5.js +0 -2
  199. package/dist/ndn_types-8c2696d5.js.map +0 -1
  200. package/dist/ndn_types-ab30fac0.mjs.map +0 -1
@@ -0,0 +1,2487 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+ import { n as canonicalJson, i as isObject, X as XllmError, m as cloneJson, p as providerError, A as AiccLlmClient } from "./aicc-67851c41.mjs";
8
+ import { aB as normalizePath, aq as MemoryHintLedger, ao as HINT_NS_DEDUP, T as ToolDispatchException, ab as toHost, ay as taskStateObservation, a6 as envelopeObservation, ar as applyHints, aC as PLANNED_RUNTIME_KINDS, s as shellSettings, aD as BUILTIN_TOOL_GROUP_BASH, u as unresolvedReason, d as describeToolSource, aE as BUILTIN_TOOL_GROUP_BASH_CORE, aF as resolveConfigPath, g as generateRunId, R as RUN_RECORD_VERSION, Y as REFUSED_CREDENTIALS, q as mergeConfigLayers, w as parseLlmContextJson, G as MemoryRunStore, $ as XllmTask, a2 as isTerminal, _ as XllmRun } from "./site_manager-11a7a468.mjs";
9
+ import { O as OpenAiLlmClient } from "./openai-ae2978de.mjs";
10
+ import "./krpc_client-673448e5.mjs";
11
+ function deno() {
12
+ const d = globalThis.Deno;
13
+ if (!d)
14
+ throw new Error("the xllm Deno host needs the Deno runtime");
15
+ return d;
16
+ }
17
+ function isNotFound(e) {
18
+ return e instanceof deno().errors.NotFound;
19
+ }
20
+ function isAlreadyExists(e) {
21
+ return e instanceof deno().errors.AlreadyExists;
22
+ }
23
+ function errorText(e) {
24
+ return e instanceof Error ? e.message : String(e);
25
+ }
26
+ function homeDir() {
27
+ const env = deno().env;
28
+ return env.get("HOME") ?? env.get("USERPROFILE");
29
+ }
30
+ function joinPath(...parts) {
31
+ let out = "";
32
+ for (const p of parts) {
33
+ if (!p)
34
+ continue;
35
+ if (p.startsWith("/") || !out)
36
+ out = p;
37
+ else
38
+ out = out.endsWith("/") ? out + p : `${out}/${p}`;
39
+ }
40
+ return out;
41
+ }
42
+ function parentDir(p) {
43
+ const t = p.replace(/\/+$/, "");
44
+ const i = t.lastIndexOf("/");
45
+ return i < 0 ? "." : i === 0 ? "/" : t.slice(0, i);
46
+ }
47
+ async function isDir(p) {
48
+ try {
49
+ return (await deno().stat(p)).isDirectory;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+ async function writeFileSynced(path, bytes) {
55
+ const f = await deno().open(path, { write: true, create: true, truncate: true });
56
+ try {
57
+ let off = 0;
58
+ while (off < bytes.length)
59
+ off += await f.write(bytes.subarray(off));
60
+ await f.sync();
61
+ } finally {
62
+ f.close();
63
+ }
64
+ }
65
+ async function syncDir(dir) {
66
+ if (deno().build.os === "windows")
67
+ return;
68
+ const f = await deno().open(dir, { read: true });
69
+ try {
70
+ await f.sync();
71
+ } finally {
72
+ f.close();
73
+ }
74
+ }
75
+ const fromNumH = (n) => n / 2 ** 32 | 0;
76
+ const fromNumL = (n) => n >>> 0;
77
+ function isBytes(a) {
78
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
79
+ }
80
+ const atitle = (title) => title ? `"${title}" ` : "";
81
+ function anumber(n, title = "") {
82
+ if (typeof n !== "number")
83
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
84
+ if (!Number.isSafeInteger(n) || n < 0)
85
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
86
+ return n;
87
+ }
88
+ function abytes(value, length, title = "") {
89
+ if (isBytes(value) && (length === void 0 || value.length === length))
90
+ return value;
91
+ if (length !== void 0)
92
+ anumber(length, "length");
93
+ const bytes = isBytes(value);
94
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
95
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
96
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
97
+ if (!bytes)
98
+ throw new TypeError(message);
99
+ throw new RangeError(message);
100
+ }
101
+ function copyBytes(bytes) {
102
+ return Uint8Array.from(abytes(bytes));
103
+ }
104
+ const aobject = (value, label) => {
105
+ if (value === null || typeof value !== "object" || Array.isArray(value))
106
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
107
+ };
108
+ const aopts = (value, label) => {
109
+ aobject(value, label);
110
+ const proto = Object.getPrototypeOf(value);
111
+ if (proto !== Object.prototype && proto !== null)
112
+ throw new TypeError(`"${label}" expected plain object`);
113
+ if (Object.hasOwn(value, "__proto__"))
114
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
115
+ };
116
+ function aexists(instance, checkFinished = true) {
117
+ if (instance.destroyed)
118
+ throw new Error("hash was destroyed");
119
+ if (checkFinished && instance.finished)
120
+ throw new Error("digest() was already called");
121
+ }
122
+ function aoutput(out, instance) {
123
+ abytes(out, void 0, "output");
124
+ const min = instance.outputLen;
125
+ if (!(out.length >= min)) {
126
+ throw new RangeError('"output" expected length >= ' + min);
127
+ }
128
+ }
129
+ function u8(arr) {
130
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
131
+ }
132
+ function u32(arr) {
133
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
134
+ }
135
+ function clean(...arrays) {
136
+ for (let i = 0; i < arrays.length; i++) {
137
+ arrays[i].fill(0);
138
+ }
139
+ }
140
+ function rotr(word, shift) {
141
+ return word << 32 - shift | word >>> shift;
142
+ }
143
+ const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
144
+ function byteSwap(word) {
145
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
146
+ }
147
+ const swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0;
148
+ function byteSwap32(arr) {
149
+ for (let i = 0; i < arr.length; i++) {
150
+ arr[i] = byteSwap(arr[i]);
151
+ }
152
+ return arr;
153
+ }
154
+ const swap32IfBE = isLE ? (u) => u : byteSwap32;
155
+ const hasHexBuiltin = /* @__PURE__ */ (() => (
156
+ // @ts-ignore
157
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
158
+ ))();
159
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
160
+ function bytesToHex(bytes) {
161
+ abytes(bytes);
162
+ if (hasHexBuiltin)
163
+ return bytes.toHex();
164
+ let hex = "";
165
+ for (let i = 0; i < bytes.length; i++) {
166
+ hex += hexes[bytes[i]];
167
+ }
168
+ return hex;
169
+ }
170
+ function checkOpts(defaults, opts, title = "opts") {
171
+ aopts(defaults, "defaults");
172
+ if (opts !== void 0)
173
+ aopts(opts, title);
174
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
175
+ return merged;
176
+ }
177
+ function createHasher(hashCons, info = {}) {
178
+ if (typeof hashCons !== "function")
179
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
180
+ info = checkOpts({}, info, "info");
181
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
182
+ const tmp = hashCons(void 0);
183
+ hashC.outputLen = tmp.outputLen;
184
+ hashC.blockLen = tmp.blockLen;
185
+ hashC.canXOF = tmp.canXOF;
186
+ hashC.create = (opts) => hashCons(opts);
187
+ Object.assign(hashC, info);
188
+ return Object.freeze(hashC);
189
+ }
190
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
191
+ 1779033703,
192
+ 3144134277,
193
+ 1013904242,
194
+ 2773480762,
195
+ 1359893119,
196
+ 2600822924,
197
+ 528734635,
198
+ 1541459225
199
+ ]);
200
+ function G1s(a, b, c, d, x) {
201
+ a = a + b + x | 0;
202
+ d = rotr(d ^ a, 16);
203
+ c = c + d | 0;
204
+ b = rotr(b ^ c, 12);
205
+ return { a, b, c, d };
206
+ }
207
+ function G2s(a, b, c, d, x) {
208
+ a = a + b + x | 0;
209
+ d = rotr(d ^ a, 8);
210
+ c = c + d | 0;
211
+ b = rotr(b ^ c, 7);
212
+ return { a, b, c, d };
213
+ }
214
+ class _BLAKE2 {
215
+ constructor(blockLen, outputLen) {
216
+ __publicField(this, "buffer");
217
+ __publicField(this, "buffer32");
218
+ __publicField(this, "finished", false);
219
+ __publicField(this, "destroyed", false);
220
+ __publicField(this, "length", 0);
221
+ __publicField(this, "pos", 0);
222
+ __publicField(this, "blockLen");
223
+ __publicField(this, "outputLen");
224
+ __publicField(this, "canXOF", false);
225
+ anumber(blockLen);
226
+ anumber(outputLen);
227
+ this.blockLen = blockLen;
228
+ this.outputLen = outputLen;
229
+ this.buffer = new Uint8Array(blockLen);
230
+ this.buffer32 = u32(this.buffer);
231
+ }
232
+ update(data) {
233
+ aexists(this);
234
+ abytes(data);
235
+ const { blockLen, buffer, buffer32 } = this;
236
+ const len = data.length;
237
+ const offset = data.byteOffset;
238
+ const buf = data.buffer;
239
+ for (let pos = 0; pos < len; ) {
240
+ if (this.pos === blockLen) {
241
+ swap32IfBE(buffer32);
242
+ this.compress(buffer32, 0, false);
243
+ swap32IfBE(buffer32);
244
+ this.pos = 0;
245
+ }
246
+ const take = Math.min(blockLen - this.pos, len - pos);
247
+ const dataOffset = offset + pos;
248
+ if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
249
+ const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
250
+ swap32IfBE(data32);
251
+ for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
252
+ this.length += blockLen;
253
+ this.compress(data32, pos32, false);
254
+ }
255
+ swap32IfBE(data32);
256
+ continue;
257
+ }
258
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
259
+ this.pos += take;
260
+ this.length += take;
261
+ pos += take;
262
+ }
263
+ return this;
264
+ }
265
+ digestInto(out) {
266
+ aexists(this);
267
+ aoutput(out, this);
268
+ if (out.byteOffset & 3)
269
+ throw new RangeError('"output" expected 4-byte aligned byteOffset, got ' + out.byteOffset);
270
+ const { pos, buffer32 } = this;
271
+ this.finished = true;
272
+ this.buffer.fill(0, pos);
273
+ swap32IfBE(buffer32);
274
+ this.compress(buffer32, 0, true);
275
+ swap32IfBE(buffer32);
276
+ const state = this.get();
277
+ const out32 = out === this.buffer ? buffer32 : u32(out);
278
+ const full = Math.floor(this.outputLen / 4);
279
+ for (let i = 0; i < full; i++)
280
+ out32[i] = swap8IfBE(state[i]);
281
+ const tail = this.outputLen % 4;
282
+ if (!tail)
283
+ return;
284
+ const off = full * 4;
285
+ const word = state[full];
286
+ for (let i = 0; i < tail; i++)
287
+ out[off + i] = word >>> 8 * i;
288
+ }
289
+ digest() {
290
+ const { buffer, outputLen } = this;
291
+ this.digestInto(buffer);
292
+ const res = buffer.slice(0, outputLen);
293
+ this.destroy();
294
+ return res;
295
+ }
296
+ _cloneInto(to) {
297
+ const { buffer, length, finished, destroyed, outputLen, pos } = this;
298
+ to || (to = new this.constructor({ dkLen: outputLen }));
299
+ to.set(...this.get());
300
+ to.buffer.set(buffer);
301
+ to.destroyed = destroyed;
302
+ to.finished = finished;
303
+ to.length = length;
304
+ to.pos = pos;
305
+ to.outputLen = outputLen;
306
+ return to;
307
+ }
308
+ clone() {
309
+ return this._cloneInto();
310
+ }
311
+ }
312
+ function _compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
313
+ let j = 0;
314
+ for (let i = 0; i < rounds; i++) {
315
+ ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
316
+ ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
317
+ ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
318
+ ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));
319
+ ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));
320
+ ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));
321
+ ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));
322
+ ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));
323
+ ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));
324
+ ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));
325
+ ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));
326
+ ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));
327
+ ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));
328
+ ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));
329
+ ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));
330
+ ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));
331
+ }
332
+ return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
333
+ }
334
+ const B3_Flags = {
335
+ CHUNK_START: 1,
336
+ CHUNK_END: 2,
337
+ PARENT: 4,
338
+ ROOT: 8,
339
+ KEYED_HASH: 16,
340
+ DERIVE_KEY_CONTEXT: 32,
341
+ DERIVE_KEY_MATERIAL: 64
342
+ };
343
+ const B3_IV = /* @__PURE__ */ SHA256_IV.slice();
344
+ const B3_SIGMA = /* @__PURE__ */ (() => {
345
+ const Id = Array.from({ length: 16 }, (_, i) => i);
346
+ const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
347
+ const res = [];
348
+ for (let i = 0, v = Id; i < 7; i++, v = permute(v))
349
+ res.push(...v);
350
+ return Uint8Array.from(res);
351
+ })();
352
+ class _BLAKE3 extends _BLAKE2 {
353
+ constructor(opts = {}, flags = 0) {
354
+ opts = checkOpts({}, opts);
355
+ super(64, opts.dkLen === void 0 ? 32 : opts.dkLen);
356
+ __publicField(this, "canXOF", true);
357
+ __publicField(this, "chunkPos", 0);
358
+ // Position of current block in chunk
359
+ // How many chunks we already have; exact while this stays within
360
+ // JS's safe-integer range.
361
+ __publicField(this, "chunksDone", 0);
362
+ __publicField(this, "flags", 0 | 0);
363
+ __publicField(this, "IV");
364
+ __publicField(this, "state");
365
+ __publicField(this, "stack", []);
366
+ // Output
367
+ __publicField(this, "posOut", 0);
368
+ __publicField(this, "bufferOut32", new Uint32Array(16));
369
+ __publicField(this, "bufferOut");
370
+ // Index of output chunk; exact while this stays within JS's
371
+ // safe-integer range.
372
+ __publicField(this, "chunkOut", 0);
373
+ __publicField(this, "enableXOF", true);
374
+ const { key, context } = opts;
375
+ const hasContext = context !== void 0;
376
+ if (key !== void 0) {
377
+ if (hasContext)
378
+ throw new Error('cannot use both "key" and "context"');
379
+ abytes(key, 32, "key");
380
+ const k = copyBytes(key);
381
+ this.IV = u32(k);
382
+ swap32IfBE(this.IV);
383
+ this.flags = flags | B3_Flags.KEYED_HASH;
384
+ } else if (hasContext) {
385
+ abytes(context, void 0, "context");
386
+ const ctx = context;
387
+ const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT).update(ctx).digest();
388
+ this.IV = u32(contextKey);
389
+ swap32IfBE(this.IV);
390
+ this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;
391
+ } else {
392
+ this.IV = B3_IV;
393
+ this.flags = flags;
394
+ }
395
+ this.state = this.IV.slice();
396
+ this.bufferOut = u8(this.bufferOut32);
397
+ }
398
+ // _BLAKE2's scalar-state hooks are unused here: BLAKE3 keeps its tree/XOF state in arrays and
399
+ // copies it directly in _cloneInto().
400
+ get() {
401
+ return [];
402
+ }
403
+ set() {
404
+ }
405
+ // Truncated chunk/parent compression: seed v8..v15 as IV[0..3], t0, t1,
406
+ // block length, and flags, then keep only the first 8 output words.
407
+ b2Compress(counter, flags, buf, bufPos = 0) {
408
+ const { state: s, pos } = this;
409
+ const t0 = fromNumL(counter);
410
+ const t1 = fromNumH(counter);
411
+ const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], t0, t1, pos, flags);
412
+ s[0] = v0 ^ v8;
413
+ s[1] = v1 ^ v9;
414
+ s[2] = v2 ^ v10;
415
+ s[3] = v3 ^ v11;
416
+ s[4] = v4 ^ v12;
417
+ s[5] = v5 ^ v13;
418
+ s[6] = v6 ^ v14;
419
+ s[7] = v7 ^ v15;
420
+ }
421
+ compress(buf, bufPos = 0, isLast = false) {
422
+ let flags = this.flags;
423
+ if (!this.chunkPos)
424
+ flags |= B3_Flags.CHUNK_START;
425
+ if (this.chunkPos === 15 || isLast)
426
+ flags |= B3_Flags.CHUNK_END;
427
+ if (!isLast)
428
+ this.pos = this.blockLen;
429
+ this.b2Compress(this.chunksDone, flags, buf, bufPos);
430
+ this.chunkPos += 1;
431
+ if (this.chunkPos === 16 || isLast) {
432
+ let chunk = this.state;
433
+ this.state = this.IV.slice();
434
+ for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks = Math.floor(chunks / 2)) {
435
+ if (!(last = this.stack.pop()))
436
+ break;
437
+ this.buffer32.set(last, 0);
438
+ this.buffer32.set(chunk, 8);
439
+ this.pos = this.blockLen;
440
+ this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);
441
+ chunk = this.state;
442
+ this.state = this.IV.slice();
443
+ }
444
+ this.chunksDone++;
445
+ this.chunkPos = 0;
446
+ this.stack.push(chunk);
447
+ }
448
+ this.pos = 0;
449
+ }
450
+ // Overriding hides _BLAKE2's flat implementation, which would otherwise be inherited
451
+ // and silently miss the tree state (CV stack, chunk counters; get()/set() are stubs here).
452
+ _cloneInto(to) {
453
+ const staleOutput = !!to && to.finished && !to.destroyed;
454
+ to = super._cloneInto(to);
455
+ const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
456
+ to.state.set(state);
457
+ to.stack = stack.map((i) => Uint32Array.from(i));
458
+ if (IV === B3_IV) {
459
+ if (to.IV !== B3_IV)
460
+ clean(to.IV);
461
+ to.IV = B3_IV;
462
+ } else if (to.IV === B3_IV) {
463
+ to.IV = IV.slice();
464
+ } else {
465
+ to.IV.set(IV);
466
+ }
467
+ to.flags = flags;
468
+ to.chunkPos = chunkPos;
469
+ to.chunksDone = chunksDone;
470
+ to.posOut = posOut;
471
+ to.chunkOut = chunkOut;
472
+ to.enableXOF = this.enableXOF;
473
+ if (this.finished) {
474
+ to.bufferOut32.set(this.bufferOut32);
475
+ } else if (staleOutput) {
476
+ clean(to.bufferOut32);
477
+ }
478
+ return to;
479
+ }
480
+ destroy() {
481
+ this.destroyed = true;
482
+ clean(this.state, this.buffer32, this.bufferOut32);
483
+ if (this.IV !== B3_IV)
484
+ clean(this.IV);
485
+ clean(...this.stack);
486
+ }
487
+ // Root/XOF compression: rerun the same ROOT inputs with incrementing output
488
+ // counter `t` and materialize all 16 output words.
489
+ // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
490
+ b2CompressOut() {
491
+ const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;
492
+ const outCounter = this.chunkOut++;
493
+ const t0 = fromNumL(outCounter);
494
+ const t1 = fromNumH(outCounter);
495
+ swap32IfBE(buffer32);
496
+ const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = _compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], t0, t1, pos, flags);
497
+ out32[0] = v0 ^ v8;
498
+ out32[1] = v1 ^ v9;
499
+ out32[2] = v2 ^ v10;
500
+ out32[3] = v3 ^ v11;
501
+ out32[4] = v4 ^ v12;
502
+ out32[5] = v5 ^ v13;
503
+ out32[6] = v6 ^ v14;
504
+ out32[7] = v7 ^ v15;
505
+ out32[8] = s[0] ^ v8;
506
+ out32[9] = s[1] ^ v9;
507
+ out32[10] = s[2] ^ v10;
508
+ out32[11] = s[3] ^ v11;
509
+ out32[12] = s[4] ^ v12;
510
+ out32[13] = s[5] ^ v13;
511
+ out32[14] = s[6] ^ v14;
512
+ out32[15] = s[7] ^ v15;
513
+ swap32IfBE(buffer32);
514
+ swap32IfBE(out32);
515
+ this.posOut = 0;
516
+ }
517
+ finish() {
518
+ if (this.finished)
519
+ return;
520
+ this.finished = true;
521
+ this.buffer.fill(0, this.pos);
522
+ let flags = this.flags | B3_Flags.ROOT;
523
+ if (this.stack.length) {
524
+ flags |= B3_Flags.PARENT;
525
+ swap32IfBE(this.buffer32);
526
+ this.compress(this.buffer32, 0, true);
527
+ swap32IfBE(this.buffer32);
528
+ this.chunksDone = 0;
529
+ this.pos = this.blockLen;
530
+ } else {
531
+ flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;
532
+ }
533
+ this.flags = flags;
534
+ this.b2CompressOut();
535
+ }
536
+ writeInto(out) {
537
+ aexists(this, false);
538
+ abytes(out);
539
+ this.finish();
540
+ const { blockLen, bufferOut } = this;
541
+ for (let pos = 0, len = out.length; pos < len; ) {
542
+ if (this.posOut >= blockLen)
543
+ this.b2CompressOut();
544
+ const take = Math.min(blockLen - this.posOut, len - pos);
545
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
546
+ this.posOut += take;
547
+ pos += take;
548
+ }
549
+ return out;
550
+ }
551
+ xofInto(out) {
552
+ if (!this.enableXOF)
553
+ throw new Error("no XOF after digest()");
554
+ return this.writeInto(out);
555
+ }
556
+ xof(bytes) {
557
+ anumber(bytes);
558
+ return this.xofInto(new Uint8Array(bytes));
559
+ }
560
+ digestInto(out) {
561
+ aoutput(out, this);
562
+ if (this.finished)
563
+ throw new Error("digest() was already called");
564
+ this.enableXOF = false;
565
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
566
+ this.destroy();
567
+ }
568
+ digest() {
569
+ const out = new Uint8Array(this.outputLen);
570
+ this.digestInto(out);
571
+ return out;
572
+ }
573
+ }
574
+ const blake3 = /* @__PURE__ */ createHasher((opts = {}) => new _BLAKE3(opts));
575
+ const HOST_ID_ENV = "AGENT_TOOL_HOST_ID";
576
+ function blake3Hex(text) {
577
+ return bytesToHex(blake3(new TextEncoder().encode(text)));
578
+ }
579
+ async function readText$1(path) {
580
+ try {
581
+ return await deno().readTextFile(path);
582
+ } catch {
583
+ return null;
584
+ }
585
+ }
586
+ function nativeHostIdFrom(i) {
587
+ var _a;
588
+ const id = (_a = i.agent_tool_host_id) == null ? void 0 : _a.trim();
589
+ if (id)
590
+ return `host:${id}:`;
591
+ const host = i.etc_hostname ?? i.hostname_env ?? "unknown";
592
+ return `host:${host.trim()}:${(i.machine_id ?? "").trim()}`;
593
+ }
594
+ async function nativeHostId() {
595
+ const env = deno().env.get(HOST_ID_ENV) ?? null;
596
+ if (env == null ? void 0 : env.trim())
597
+ return nativeHostIdFrom({ agent_tool_host_id: env, etc_hostname: null, hostname_env: null, machine_id: null });
598
+ return nativeHostIdFrom({
599
+ agent_tool_host_id: env,
600
+ etc_hostname: await readText$1("/etc/hostname"),
601
+ hostname_env: deno().env.get("HOSTNAME") ?? null,
602
+ machine_id: await readText$1("/etc/machine-id")
603
+ });
604
+ }
605
+ function nativeTarget(hostId, uid) {
606
+ return { host: hostId, uid };
607
+ }
608
+ function targetText(target) {
609
+ return canonicalJson(target);
610
+ }
611
+ function deriveRuntimeId(configuredId, kind, target) {
612
+ return configuredId ?? runtimeIdOf(kind, target);
613
+ }
614
+ function runtimeIdOf(kind, target) {
615
+ return `${kind}:${blake3Hex(targetText(target)).slice(0, 24)}`;
616
+ }
617
+ function workdirLockPath(lockDir, workdir) {
618
+ return joinPath(lockDir, `${blake3Hex(workdir).slice(0, 24)}.lock`);
619
+ }
620
+ const TOOL_READ_FILE = "read_file";
621
+ const TOOL_WRITE_FILE = "write_file";
622
+ const TOOL_EDIT_FILE = "edit_file";
623
+ const TOOL_SHELL = "shell";
624
+ const BASH_GROUP_TOOLS = [TOOL_READ_FILE, TOOL_WRITE_FILE, TOOL_EDIT_FILE, TOOL_SHELL];
625
+ const EXEC_MAX_OUTPUT_BYTES = 64 * 1024;
626
+ const OUTPUT_TAIL_BYTES = 2048;
627
+ const TIMEOUT_EXIT_CODE = 124;
628
+ const ENV_CALL_ID = "XLLM_CALL_ID";
629
+ const ENV_RUN_ID = "XLLM_RUN_ID";
630
+ const LOCAL_ENGINE = "native";
631
+ const READ_FILE_PREVIEW_MAX_LINES = 200;
632
+ const CMD_PARAM_PREVIEW_KEEP_CHARS = 32;
633
+ const HISTORY_COMPACT_CMD_MAX_CHARS = 96;
634
+ class NativeToolError extends Error {
635
+ constructor(kind, detail, effectUnknown = false) {
636
+ super(kind === "invalid_args" ? `invalid args: ${detail}` : kind === "exec_failed" ? `execution failed: ${detail}` : kind === "timeout" ? "timeout" : kind === "transport" ? `runtime transport: ${detail}` : `cancelled: ${detail}`);
637
+ this.kind = kind;
638
+ this.detail = detail;
639
+ this.effectUnknown = effectUnknown;
640
+ this.name = "NativeToolError";
641
+ }
642
+ }
643
+ const invalidArgs = (m) => new NativeToolError("invalid_args", m);
644
+ const execFailed = (m) => new NativeToolError("exec_failed", m);
645
+ function tokenizeBashCommandLine(line) {
646
+ const tokens = [];
647
+ let cur = "";
648
+ let single = false;
649
+ let double = false;
650
+ const chars = [...line];
651
+ for (let i = 0; i < chars.length; i++) {
652
+ const ch = chars[i];
653
+ if (ch === "'" && !double)
654
+ single = !single;
655
+ else if (ch === '"' && !single)
656
+ double = !double;
657
+ else if (ch === "\\" && !single) {
658
+ if (i + 1 < chars.length)
659
+ cur += chars[++i];
660
+ } else if (/\s/.test(ch) && !single && !double) {
661
+ if (cur) {
662
+ tokens.push(cur);
663
+ cur = "";
664
+ }
665
+ } else
666
+ cur += ch;
667
+ }
668
+ if (single || double)
669
+ return void 0;
670
+ if (cur)
671
+ tokens.push(cur);
672
+ return tokens;
673
+ }
674
+ function truncateText(text, max) {
675
+ const chars = [...text];
676
+ return chars.length <= max ? text : `${chars.slice(0, max).join("")}...[TRUNCATED]`;
677
+ }
678
+ function defaultTitle(r) {
679
+ var _a;
680
+ const line = r.cmd_name !== void 0 ? ((_a = r.cmd_args) == null ? void 0 : _a.trim()) ? `${r.cmd_name} ${r.cmd_args.trim()}` : r.cmd_name : void 0;
681
+ const cmd = (line !== void 0 ? truncateText(line.trim(), HISTORY_COMPACT_CMD_MAX_CHARS) : "") || "action";
682
+ const status = r.status === "pending" ? r.pending_reason !== void 0 ? `pending (${r.pending_reason})` : "pending" : r.status;
683
+ return `${cmd} => ${status}`;
684
+ }
685
+ function builtinResult(tool, detail, cmdLine, summary) {
686
+ const r = { agent_tool_protocol: "1", tool, status: "success", summary, detail };
687
+ const tokens = tokenizeBashCommandLine(cmdLine);
688
+ const parts = tokens && tokens.length ? tokens : cmdLine.split(/\s+/).filter(Boolean);
689
+ if (parts.length) {
690
+ r.cmd_name = parts[0];
691
+ if (parts.length > 1)
692
+ r.cmd_args = parts.slice(1).join(" ");
693
+ }
694
+ r.title = defaultTitle(r);
695
+ return r;
696
+ }
697
+ function withOutput(r, output) {
698
+ if (output.trim())
699
+ r.output = output;
700
+ else
701
+ delete r.output;
702
+ return r;
703
+ }
704
+ function pathStartsWith(p, root) {
705
+ if (root === "/")
706
+ return p.startsWith("/");
707
+ return p === root || p.startsWith(`${root}/`);
708
+ }
709
+ function checkAllowed(path, roots) {
710
+ if (roots.length === 0 || roots.some((r) => pathStartsWith(path, r)))
711
+ return;
712
+ throw invalidArgs(`path not allowed by policy: ${path}`);
713
+ }
714
+ async function canonicalMissing(path) {
715
+ let ancestor = path.replace(/\/+$/, "") || "/";
716
+ const missing = [];
717
+ for (; ; ) {
718
+ try {
719
+ const real = await deno().realPath(ancestor);
720
+ return normalizePath(joinPath(real, ...missing.slice().reverse()));
721
+ } catch (e) {
722
+ if (!isNotFound(e))
723
+ throw execFailed(errorText(e));
724
+ try {
725
+ await deno().lstat(ancestor);
726
+ throw invalidArgs(`dangling symlink: ${ancestor}`);
727
+ } catch (le) {
728
+ if (le instanceof NativeToolError)
729
+ throw le;
730
+ }
731
+ const name = ancestor.slice(ancestor.lastIndexOf("/") + 1);
732
+ if (!name || name === "..")
733
+ throw invalidArgs(`cannot resolve ${path}`);
734
+ if (name !== ".")
735
+ missing.push(name);
736
+ const parent = parentDir(ancestor);
737
+ if (parent === ancestor || ancestor === "/")
738
+ throw invalidArgs("path has no existing ancestor");
739
+ ancestor = parent;
740
+ }
741
+ }
742
+ }
743
+ async function resolvePath(root, raw, allowed) {
744
+ if (!raw.trim())
745
+ throw invalidArgs("path cannot be empty");
746
+ const candidate = raw.startsWith("/") ? raw : joinPath(root, raw);
747
+ checkAllowed(normalizePath(candidate), allowed);
748
+ const real = await canonicalMissing(candidate);
749
+ const roots = await Promise.all(allowed.map(canonicalMissing));
750
+ checkAllowed(real, roots);
751
+ return real;
752
+ }
753
+ function encodeObjSegment(seg) {
754
+ let out = "";
755
+ for (const b of new TextEncoder().encode(seg)) {
756
+ const c = String.fromCharCode(b);
757
+ out += /[A-Za-z0-9\-._~!$&'()*+,;=:@]/.test(c) ? c : `%${b.toString(16).toUpperCase().padStart(2, "0")}`;
758
+ }
759
+ return out;
760
+ }
761
+ function cyfsUrl(dfsRoot, abs) {
762
+ if (!dfsRoot)
763
+ return void 0;
764
+ const root = normalizePath(dfsRoot);
765
+ if (!pathStartsWith(abs, root))
766
+ return void 0;
767
+ const rel = abs.slice(root.length).split("/").filter((s) => s && s !== ".");
768
+ return `cyfs://${["", ...rel].map(encodeObjSegment).join("/") || "/"}`;
769
+ }
770
+ function serdeKind(v) {
771
+ if (v === null)
772
+ return "null";
773
+ if (typeof v === "boolean")
774
+ return `boolean \`${v}\``;
775
+ if (typeof v === "number")
776
+ return Number.isInteger(v) ? `integer \`${v}\`` : `floating point \`${v}\``;
777
+ if (typeof v === "string")
778
+ return `string ${JSON.stringify(v)}`;
779
+ if (Array.isArray(v))
780
+ return "sequence";
781
+ return "map";
782
+ }
783
+ function argError(tool, reason) {
784
+ return invalidArgs(`invalid args for \`${tool}\`: ${reason}`);
785
+ }
786
+ function reqString(tool, args, key) {
787
+ const v = args[key];
788
+ if (v === void 0)
789
+ throw argError(tool, `missing field \`${key}\``);
790
+ if (typeof v !== "string")
791
+ throw argError(tool, `invalid type: ${serdeKind(v)}, expected a string`);
792
+ return v;
793
+ }
794
+ function optString(tool, args, key) {
795
+ const v = args[key];
796
+ if (v === void 0 || v === null)
797
+ return void 0;
798
+ if (typeof v !== "string")
799
+ throw argError(tool, `invalid type: ${serdeKind(v)}, expected a string`);
800
+ return v;
801
+ }
802
+ const utf8 = new TextEncoder();
803
+ function byteLength(s) {
804
+ return utf8.encode(s).length;
805
+ }
806
+ function decodeLossy(bytes) {
807
+ return new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes);
808
+ }
809
+ function splitLinesPreserveEnding(content) {
810
+ if (!content)
811
+ return [];
812
+ return content.match(/[^\n]*\n|[^\n]+$/g) ?? [];
813
+ }
814
+ function strLines(s) {
815
+ if (!s)
816
+ return [];
817
+ const parts = s.split("\n");
818
+ if (parts[parts.length - 1] === "")
819
+ parts.pop();
820
+ return parts.map((l) => l.endsWith("\r") ? l.slice(0, -1) : l);
821
+ }
822
+ function trimEndLineBreaks(s) {
823
+ return s.replace(/[\r\n]+$/, "");
824
+ }
825
+ function compactCmdParamPreview(raw) {
826
+ const escaped = raw.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n");
827
+ const totalLines = raw ? Math.max(strLines(raw).length, 1) : 0;
828
+ const chars = [...escaped];
829
+ if (chars.length <= CMD_PARAM_PREVIEW_KEEP_CHARS * 2)
830
+ return escaped;
831
+ return `${chars.slice(0, CMD_PARAM_PREVIEW_KEEP_CHARS).join("")}...(total ${totalLines} lines)...${chars.slice(-CMD_PARAM_PREVIEW_KEEP_CHARS).join("")}`;
832
+ }
833
+ function buildSimpleDiff(path, before, after) {
834
+ const a = strLines(before);
835
+ const b = strLines(after);
836
+ const body = [];
837
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
838
+ const o = a[i];
839
+ const n = b[i];
840
+ if (o !== void 0 && n !== void 0) {
841
+ if (o === n)
842
+ body.push(` ${o}`);
843
+ else
844
+ body.push(`-${o}`, `+${n}`);
845
+ } else if (o !== void 0)
846
+ body.push(`-${o}`);
847
+ else if (n !== void 0)
848
+ body.push(`+${n}`);
849
+ }
850
+ return [`--- a/${path}`, `+++ b/${path}`, `@@ -1,${a.length} +1,${b.length} @@`, ...body].join("\n");
851
+ }
852
+ function parseMarkerToken(raw, rangeText) {
853
+ const t = raw.trim();
854
+ if (t === "$")
855
+ return "end";
856
+ if (t.startsWith("+") || !/^-?\d+$/.test(t))
857
+ throw invalidArgs(`invalid range text \`${rangeText}\``);
858
+ const v = Number(t);
859
+ if (v === 0)
860
+ throw invalidArgs("range must be 1-based, zero is invalid");
861
+ return v;
862
+ }
863
+ function parseCountText(raw, rangeText) {
864
+ const t = raw.trim();
865
+ if (!t.startsWith("+"))
866
+ throw invalidArgs(`invalid range text \`${rangeText}\``);
867
+ const c = t.slice(1).trim();
868
+ if (!/^\d+$/.test(c))
869
+ throw invalidArgs(`invalid range text \`${rangeText}\``);
870
+ const n = Number(c);
871
+ if (n === 0)
872
+ throw invalidArgs("range count must be positive integer");
873
+ return n;
874
+ }
875
+ function parseMarkerJson(v, name) {
876
+ if (typeof v === "string")
877
+ return parseMarkerToken(v, name);
878
+ if (typeof v === "number" && Number.isInteger(v)) {
879
+ if (v === 0)
880
+ throw invalidArgs(`${name} must be non-zero integer`);
881
+ return v;
882
+ }
883
+ throw invalidArgs(`${name} must be integer or \`$\``);
884
+ }
885
+ function parseCountJson(v, name) {
886
+ if (typeof v !== "number" || !Number.isInteger(v) || v <= 0)
887
+ throw invalidArgs(`${name} must be positive integer`);
888
+ return v;
889
+ }
890
+ function parseRangeText(raw) {
891
+ const text = raw.trim();
892
+ if (!text || text === "-")
893
+ return void 0;
894
+ if (text.includes(",") || text.includes(":")) {
895
+ if (text.includes(",") && text.includes(":"))
896
+ throw invalidArgs(`invalid range text \`${raw}\``);
897
+ const parts = text.split(text.includes(",") ? "," : ":");
898
+ if (parts.length !== 2)
899
+ throw invalidArgs(`invalid range text \`${raw}\``);
900
+ const start = parts[0].trim() ? parseMarkerToken(parts[0].trim(), raw) : void 0;
901
+ const endText = parts[1].trim();
902
+ if (endText.startsWith("+")) {
903
+ if (start === void 0)
904
+ throw invalidArgs(`range \`${raw}\` with \`+count\` requires start`);
905
+ return { start, count: parseCountText(endText, raw), defaultEnd: "same_as_start" };
906
+ }
907
+ return { start, end: endText ? parseMarkerToken(endText, raw) : void 0, defaultEnd: "end" };
908
+ }
909
+ const dash = text.indexOf("-");
910
+ if (dash >= 0) {
911
+ const left = text.slice(0, dash).trim();
912
+ const right = text.slice(dash + 1).trim();
913
+ if (left && right && /^\d+$/.test(left) && /^\d+$/.test(right)) {
914
+ return { start: parseMarkerToken(left, raw), end: parseMarkerToken(right, raw), defaultEnd: "same_as_start" };
915
+ }
916
+ }
917
+ return { start: parseMarkerToken(text, raw), defaultEnd: "same_as_start" };
918
+ }
919
+ function parseRangeSpec(raw) {
920
+ if (raw === void 0 || raw === null)
921
+ return void 0;
922
+ if (isObject(raw)) {
923
+ const start = raw.start !== void 0 ? parseMarkerJson(raw.start, "range.start") : void 0;
924
+ const end = raw.end !== void 0 ? parseMarkerJson(raw.end, "range.end") : void 0;
925
+ const count = raw.count !== void 0 ? parseCountJson(raw.count, "range.count") : void 0;
926
+ if (count !== void 0 && end !== void 0)
927
+ throw invalidArgs("range cannot set both `end` and `count`");
928
+ if (count !== void 0 && start === void 0)
929
+ throw invalidArgs("range.count requires range.start");
930
+ if (start === void 0 && end === void 0 && count === void 0) {
931
+ throw invalidArgs("range object must contain at least one of start/end/count");
932
+ }
933
+ return { start, end, count, defaultEnd: "tail_if_start_negative" };
934
+ }
935
+ if (Array.isArray(raw)) {
936
+ if (raw.length === 0 || raw.length > 2)
937
+ throw invalidArgs("range array must be [start] or [start,end]");
938
+ return {
939
+ start: parseMarkerJson(raw[0], "range[0]"),
940
+ end: raw.length === 2 ? parseMarkerJson(raw[1], "range[1]") : void 0,
941
+ defaultEnd: "same_as_start"
942
+ };
943
+ }
944
+ if (typeof raw === "number" && Number.isInteger(raw))
945
+ return { start: parseMarkerJson(raw, "range"), defaultEnd: "same_as_start" };
946
+ if (typeof raw === "string")
947
+ return parseRangeText(raw);
948
+ throw invalidArgs("range must be string/number/array/object");
949
+ }
950
+ function resolveMarker(m, total) {
951
+ if (m === "end")
952
+ return total;
953
+ return m > 0 ? m : total + m + 1;
954
+ }
955
+ function resolveRange(spec, total) {
956
+ const startMarker = spec.start ?? 1;
957
+ const startRaw = resolveMarker(startMarker, total);
958
+ let endRaw;
959
+ if (spec.count !== void 0)
960
+ endRaw = startRaw + spec.count - 1;
961
+ else if (spec.end !== void 0)
962
+ endRaw = resolveMarker(spec.end, total);
963
+ else if (spec.defaultEnd === "same_as_start")
964
+ endRaw = startRaw;
965
+ else if (spec.defaultEnd === "end")
966
+ endRaw = total;
967
+ else
968
+ endRaw = typeof startMarker === "number" && startMarker < 0 ? total : startRaw;
969
+ return [Math.min(Math.max(startRaw, 1), total + 1), Math.min(Math.max(endRaw, 0), total)];
970
+ }
971
+ function readCmdLine(path, firstChunk, range) {
972
+ let cmd = `${TOOL_READ_FILE} ${path}`;
973
+ if (firstChunk !== void 0)
974
+ cmd += ` first_chunk="${compactCmdParamPreview(firstChunk)}"`;
975
+ if (range !== void 0 && range !== null) {
976
+ const text = typeof range === "string" ? range : canonicalJson(range);
977
+ if (text.trim())
978
+ cmd += ` range=${text}`;
979
+ }
980
+ return cmd;
981
+ }
982
+ const READ_FILE_SPEC = {
983
+ name: TOOL_READ_FILE,
984
+ description: `Read a text file. range selects 1-based lines ("120-200", "120:$", "120:+20", "-50:$" for the last 50); first_chunk starts the read at the first occurrence of that text. Paths are relative to the working directory; paths outside it only where the run's filesystem policy allows.`,
985
+ args_schema: {
986
+ properties: {
987
+ first_chunk: { description: "Start the read at the first occurrence of this text (range then counts from there).", type: "string" },
988
+ path: { description: "File to read, relative to the working directory.", type: "string" },
989
+ range: { description: '1-based line range: "120-200", "120:$" (to the end), "120:+20" (20 lines from 120); negative numbers count from the end ("-50:$").' }
990
+ },
991
+ required: ["path"],
992
+ type: "object"
993
+ }
994
+ };
995
+ const WRITE_FILE_SPEC = {
996
+ name: TOOL_WRITE_FILE,
997
+ description: `Write a text file: mode "write" (default) creates or overwrites it, "append" adds to its end, "new" creates it and fails if it exists. Parent directories are created. Paths are relative to the working directory; paths outside it only where the run's filesystem policy allows.`,
998
+ args_schema: {
999
+ properties: {
1000
+ content: { description: "The text to write.", type: "string" },
1001
+ mode: { description: "`write` (default): create or overwrite; `append`: add to the end; `new`: create, fail if the file exists.", type: "string" },
1002
+ path: { description: "File to write, relative to the working directory.", type: "string" }
1003
+ },
1004
+ required: ["content", "path"],
1005
+ type: "object"
1006
+ }
1007
+ };
1008
+ const EDIT_FILE_SPEC = {
1009
+ name: TOOL_EDIT_FILE,
1010
+ description: "Replace the one exact occurrence of old_string with new_string in a text file. Fails when old_string is absent or occurs more than once: include enough surrounding text to make it unique. Paths are relative to the working directory; paths outside it only where the run's filesystem policy allows.",
1011
+ args_schema: {
1012
+ properties: {
1013
+ new_string: { description: "The replacement text.", type: "string" },
1014
+ old_string: { description: "The exact text to replace; it must occur exactly once.", type: "string" },
1015
+ path: { description: "File to edit, relative to the working directory.", type: "string" }
1016
+ },
1017
+ required: ["new_string", "old_string", "path"],
1018
+ type: "object"
1019
+ }
1020
+ };
1021
+ async function readText(path) {
1022
+ try {
1023
+ return decodeLossy(await deno().readFile(path));
1024
+ } catch (e) {
1025
+ throw execFailed(`read file failed: ${errorText(e)}`);
1026
+ }
1027
+ }
1028
+ async function writeText(path, text) {
1029
+ try {
1030
+ await deno().mkdir(parentDir(path), { recursive: true });
1031
+ } catch (e) {
1032
+ throw execFailed(errorText(e));
1033
+ }
1034
+ try {
1035
+ await deno().writeFile(path, utf8.encode(text));
1036
+ } catch (e) {
1037
+ throw execFailed(`write file failed: ${errorText(e)}`);
1038
+ }
1039
+ }
1040
+ async function exists(path) {
1041
+ try {
1042
+ await deno().stat(path);
1043
+ return true;
1044
+ } catch (e) {
1045
+ if (isNotFound(e))
1046
+ return false;
1047
+ throw execFailed(errorText(e));
1048
+ }
1049
+ }
1050
+ function readFileTool(cfg) {
1051
+ return {
1052
+ spec: READ_FILE_SPEC,
1053
+ idempotent: true,
1054
+ cancellable: false,
1055
+ async call(args) {
1056
+ const rawPath = reqString(TOOL_READ_FILE, args, "path");
1057
+ const firstChunk = optString(TOOL_READ_FILE, args, "first_chunk");
1058
+ const range = args.range === null ? void 0 : args.range;
1059
+ const filePath = rawPath.trim();
1060
+ if (!filePath)
1061
+ throw invalidArgs("missing required arg `path`");
1062
+ const abs = await resolvePath(cfg.root, filePath, cfg.allowedRead);
1063
+ const full = await readText(abs);
1064
+ let chunk;
1065
+ let matched = true;
1066
+ let chunkStart = 1;
1067
+ if (firstChunk !== void 0) {
1068
+ const pos = full.indexOf(firstChunk);
1069
+ if (pos >= 0) {
1070
+ chunk = full.slice(pos);
1071
+ chunkStart = (full.slice(0, pos).match(/\n/g) ?? []).length + 1;
1072
+ } else {
1073
+ chunk = "";
1074
+ matched = false;
1075
+ }
1076
+ } else
1077
+ chunk = full;
1078
+ const lines = splitLinesPreserveEnding(chunk);
1079
+ const total = lines.length;
1080
+ const spec = parseRangeSpec(range);
1081
+ let start;
1082
+ let end;
1083
+ let label = "";
1084
+ if (spec) {
1085
+ [start, end] = resolveRange(spec, total);
1086
+ label = `${start}-${end}`;
1087
+ } else if (total === 0) {
1088
+ start = 1;
1089
+ end = 0;
1090
+ } else {
1091
+ start = 1;
1092
+ end = total;
1093
+ }
1094
+ const si = Math.min(Math.max(start - 1, 0), total);
1095
+ const ei = Math.min(end, total);
1096
+ const selected = si < ei ? lines.slice(si, ei) : [];
1097
+ const content = selected.join("");
1098
+ const count = selected.length;
1099
+ const startLine = count === 0 ? null : chunkStart + si;
1100
+ const endLine = startLine === null ? null : startLine + Math.max(count - 1, 0);
1101
+ let preview = "";
1102
+ if (startLine !== null) {
1103
+ preview = selected.slice(0, READ_FILE_PREVIEW_MAX_LINES).map((l, i) => `${startLine + i}: ${trimEndLineBreaks(l)}`).join("\n");
1104
+ if (selected.length > READ_FILE_PREVIEW_MAX_LINES)
1105
+ preview += `${preview ? "\n" : ""}... truncated to ${READ_FILE_PREVIEW_MAX_LINES} lines`;
1106
+ }
1107
+ const bytes = byteLength(content);
1108
+ const cmdLine = readCmdLine(filePath, firstChunk, range);
1109
+ let summary;
1110
+ if (matched) {
1111
+ const linesText = startLine !== null && endLine !== null ? startLine === endLine ? `1 line at ${startLine}` : `${count} lines at ${startLine}-${endLine}` : "0 lines";
1112
+ const base = `succeeded, read ${bytes} bytes across ${linesText}`;
1113
+ summary = preview ? `${base}
1114
+ \`\`\`content
1115
+ ${preview}
1116
+ \`\`\`` : base;
1117
+ } else {
1118
+ summary = "succeeded, first_chunk was not found, read 0 bytes across 0 lines";
1119
+ }
1120
+ const detail = {};
1121
+ const url = cyfsUrl(cfg.dfsRoot, abs);
1122
+ if (url !== void 0)
1123
+ detail.cyfs_url = url;
1124
+ Object.assign(detail, {
1125
+ content,
1126
+ matched,
1127
+ line_range: label,
1128
+ bytes,
1129
+ line_count: count,
1130
+ start_line: startLine,
1131
+ end_line: endLine,
1132
+ preview_truncated: count > READ_FILE_PREVIEW_MAX_LINES
1133
+ });
1134
+ const result = builtinResult(TOOL_READ_FILE, detail, cmdLine, summary);
1135
+ result.title = `${cmdLine} => ${matched ? "success" : "anchor not found"}`;
1136
+ return withReadDedup(result, filePath, canonicalJson(Object.fromEntries(Object.entries(args).filter(([k]) => k !== "path"))));
1137
+ }
1138
+ };
1139
+ }
1140
+ function withReadDedup(result, what, window) {
1141
+ var _a;
1142
+ if (result.status !== "success")
1143
+ return result;
1144
+ const text = ((_a = result.output) == null ? void 0 : _a.trim()) ? result.output : result.summary.trim() ? result.summary : canonicalJson(result.detail);
1145
+ result.dedup = {
1146
+ key: `read:${what}#${window}:${blake3Hex(text).slice(0, 16)}`,
1147
+ hint: `\`${what}\` is unchanged since you read it earlier in this run; use that content.`
1148
+ };
1149
+ return result;
1150
+ }
1151
+ function normalizeWriteMode(raw) {
1152
+ const m = (raw ?? "write").trim().toLowerCase();
1153
+ if (m === "new" || m === "create")
1154
+ return "new";
1155
+ if (m === "append")
1156
+ return "append";
1157
+ if (m === "" || m === "write" || m === "overwrite")
1158
+ return "write";
1159
+ throw invalidArgs(`invalid write mode \`${m}\`, expected new/append/write`);
1160
+ }
1161
+ function writeFileTool(cfg) {
1162
+ return {
1163
+ spec: WRITE_FILE_SPEC,
1164
+ idempotent: false,
1165
+ cancellable: false,
1166
+ async call(args) {
1167
+ const rawPath = reqString(TOOL_WRITE_FILE, args, "path");
1168
+ const content = reqString(TOOL_WRITE_FILE, args, "content");
1169
+ const rawMode = optString(TOOL_WRITE_FILE, args, "mode");
1170
+ let cmdMode;
1171
+ try {
1172
+ cmdMode = normalizeWriteMode(rawMode);
1173
+ } catch {
1174
+ cmdMode = "write";
1175
+ }
1176
+ const cmdLine = `${TOOL_WRITE_FILE} ${rawPath} mode=${cmdMode}`;
1177
+ const filePath = rawPath.trim();
1178
+ if (!filePath)
1179
+ throw invalidArgs("missing required arg `path`");
1180
+ const mode = normalizeWriteMode(rawMode);
1181
+ const abs = await resolvePath(cfg.root, filePath, cfg.allowedWrite);
1182
+ const present = await exists(abs);
1183
+ if (mode === "new" && present)
1184
+ throw invalidArgs(`write mode \`new\` requires target file not exist: ${filePath}`);
1185
+ const original = present ? await readText(abs) : "";
1186
+ const operation = mode === "append" ? "append" : mode === "new" ? "new" : present ? "write" : "create";
1187
+ const updated = mode === "append" ? `${original}${content}` : content;
1188
+ await writeText(abs, updated);
1189
+ const lineCount = splitLinesPreserveEnding(content).length;
1190
+ const detail = {};
1191
+ const url = cyfsUrl(cfg.dfsRoot, abs);
1192
+ if (url !== void 0)
1193
+ detail.cyfs_url = url;
1194
+ const bytesAfter = byteLength(updated);
1195
+ Object.assign(detail, { created: !present, changed: original !== updated, bytes_written: bytesAfter, line_count: lineCount });
1196
+ const verb = operation === "append" ? "appended" : operation === "new" || operation === "create" ? "created" : "wrote";
1197
+ const summary = `${verb} ${filePath}, wrote ${byteLength(content)} bytes across ${lineCount === 1 ? "1 line" : `${lineCount} lines`}`;
1198
+ const result = builtinResult(TOOL_WRITE_FILE, detail, cmdLine, summary);
1199
+ const label = operation === "append" ? "append" : operation === "new" || operation === "create" ? "new" : "write";
1200
+ result.title = `${TOOL_WRITE_FILE} ${filePath} mode=${label} => success (${bytesAfter} bytes)`;
1201
+ return result;
1202
+ }
1203
+ };
1204
+ }
1205
+ function editFileTool(cfg) {
1206
+ return {
1207
+ spec: EDIT_FILE_SPEC,
1208
+ idempotent: false,
1209
+ cancellable: false,
1210
+ async call(args) {
1211
+ const rawPath = reqString(TOOL_EDIT_FILE, args, "path");
1212
+ const oldString = reqString(TOOL_EDIT_FILE, args, "old_string");
1213
+ const newString = reqString(TOOL_EDIT_FILE, args, "new_string");
1214
+ const cmdLine = `${TOOL_EDIT_FILE} ${rawPath} old_string="${compactCmdParamPreview(oldString)}"`;
1215
+ const filePath = rawPath.trim();
1216
+ if (!filePath)
1217
+ throw invalidArgs("missing required arg `path`");
1218
+ if (!oldString)
1219
+ throw invalidArgs("missing required arg `old_string`");
1220
+ if (oldString === newString)
1221
+ throw invalidArgs("`new_string` must be different from `old_string`");
1222
+ const abs = await resolvePath(cfg.root, filePath, cfg.allowedWrite);
1223
+ const original = await readText(abs);
1224
+ const matches = [];
1225
+ for (let at = original.indexOf(oldString); at >= 0; at = original.indexOf(oldString, at + oldString.length))
1226
+ matches.push(at);
1227
+ if (matches.length === 0)
1228
+ throw invalidArgs("`old_string` was not found in the file");
1229
+ if (matches.length > 1)
1230
+ throw invalidArgs(`\`old_string\` must match exactly once, found ${matches.length} matches`);
1231
+ const pos = matches[0];
1232
+ const updated = original.slice(0, pos) + newString + original.slice(pos + oldString.length);
1233
+ const changed = original !== updated;
1234
+ if (changed)
1235
+ await writeText(abs, updated);
1236
+ const diff = buildSimpleDiff(filePath, original, updated);
1237
+ const line = (original.slice(0, pos).match(/\n/g) ?? []).length + 1;
1238
+ const detail = {};
1239
+ const url = cyfsUrl(cfg.dfsRoot, abs);
1240
+ if (url !== void 0)
1241
+ detail.cyfs_url = url;
1242
+ Object.assign(detail, { matched: true, changed, mode: "replace", line, diff, diff_truncated: false });
1243
+ const summary = changed ? diff.trim() ? `edited ${filePath} with replace at line ${line}
1244
+ \`\`\`diff
1245
+ ${diff}
1246
+ \`\`\`` : `edited ${filePath} with replace at line ${line}` : `edit ${filePath} made no change`;
1247
+ const result = builtinResult(TOOL_EDIT_FILE, detail, cmdLine, summary);
1248
+ result.title = `${TOOL_EDIT_FILE} ${filePath} => ${changed ? `success (line ${line})` : "no change"}`;
1249
+ return result;
1250
+ }
1251
+ };
1252
+ }
1253
+ const NATIVE_WRAPPER = `if [ "$#" -ge 2 ]; then export PATH="$2"; fi
1254
+ printf '%s\\n' "$0" > "$1/command"
1255
+ "$BASH" -c "$0" </dev/null >"$1/stdout" 2>"$1/stderr"
1256
+ __llm_ec=$?
1257
+ printf '%s\\n' "$__llm_ec" > "$1/exit.tmp" && command -p mv -f "$1/exit.tmp" "$1/exit"
1258
+ exit $__llm_ec`;
1259
+ const SYSTEM_PATH_ENTRIES = ["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"];
1260
+ function sanitizeCallId(callId) {
1261
+ const s = [...callId].map((c) => /[A-Za-z0-9\-_.]/.test(c) ? c : "_").join("");
1262
+ return !s || s.startsWith(".") ? `c_${s}` : s;
1263
+ }
1264
+ function execDirFor(runDir, callId) {
1265
+ if (!runDir || !callId)
1266
+ return void 0;
1267
+ return joinPath(runDir, "exec", sanitizeCallId(callId));
1268
+ }
1269
+ function fmtElapsed(ms) {
1270
+ const s = Math.floor(ms / 1e3);
1271
+ if (s < 60)
1272
+ return `${s}s`;
1273
+ if (s < 3600)
1274
+ return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
1275
+ return `${Math.floor(s / 3600)}h${String(Math.floor(s % 3600 / 60)).padStart(2, "0")}m`;
1276
+ }
1277
+ function boundedText(bytes, max) {
1278
+ const headCap = Math.floor(max / 4);
1279
+ const tailCap = max - headCap;
1280
+ const head = bytes.subarray(0, Math.min(headCap, bytes.length));
1281
+ const rest = bytes.subarray(head.length);
1282
+ const tail = rest.subarray(Math.max(0, rest.length - tailCap));
1283
+ const truncated = bytes.length > head.length + tail.length;
1284
+ if (!truncated)
1285
+ return [decodeLossy(head) + decodeLossy(tail), false];
1286
+ return [`${decodeLossy(head)}
1287
+ …[${bytes.length - head.length - tail.length} bytes omitted]…
1288
+ ${decodeLossy(tail)}`, true];
1289
+ }
1290
+ async function readBytes(path) {
1291
+ try {
1292
+ return await deno().readFile(path);
1293
+ } catch {
1294
+ return void 0;
1295
+ }
1296
+ }
1297
+ async function readFileBounded(path, max) {
1298
+ const bytes = await readBytes(path);
1299
+ return bytes ? boundedText(bytes, Math.max(max, 16)) : ["", false];
1300
+ }
1301
+ async function readFileTail(path, max) {
1302
+ const bytes = await readBytes(path);
1303
+ return bytes ? decodeLossy(bytes.subarray(Math.max(0, bytes.length - max))) : "";
1304
+ }
1305
+ async function readExitFile(dir) {
1306
+ try {
1307
+ const t = (await deno().readTextFile(joinPath(dir, "exit"))).trim();
1308
+ return /^[+-]?\d+$/.test(t) ? Number(t) : void 0;
1309
+ } catch {
1310
+ return void 0;
1311
+ }
1312
+ }
1313
+ async function outputFromExecDir(dir, exitCode, timedOut, elapsedMs, max, cwd) {
1314
+ const [stdout, outTrunc] = await readFileBounded(joinPath(dir, "stdout"), max);
1315
+ const [stderr, errTrunc] = await readFileBounded(joinPath(dir, "stderr"), max);
1316
+ let output = stdout;
1317
+ if (stderr) {
1318
+ if (output && !output.endsWith("\n"))
1319
+ output += "\n";
1320
+ output += stderr;
1321
+ }
1322
+ return { exit_code: exitCode, stdout, stderr, output, output_truncated: outTrunc || errTrunc, timed_out: timedOut, duration_ms: Math.floor(elapsedMs), cwd };
1323
+ }
1324
+ const SIGNALS = {
1325
+ SIGHUP: 1,
1326
+ SIGINT: 2,
1327
+ SIGQUIT: 3,
1328
+ SIGILL: 4,
1329
+ SIGTRAP: 5,
1330
+ SIGABRT: 6,
1331
+ SIGBUS: 7,
1332
+ SIGFPE: 8,
1333
+ SIGKILL: 9,
1334
+ SIGUSR1: 10,
1335
+ SIGSEGV: 11,
1336
+ SIGUSR2: 12,
1337
+ SIGPIPE: 13,
1338
+ SIGALRM: 14,
1339
+ SIGTERM: 15
1340
+ };
1341
+ function exitCodeOf(status) {
1342
+ if (status.signal)
1343
+ return 128 + (SIGNALS[status.signal] ?? 0);
1344
+ return status.code;
1345
+ }
1346
+ function commandHasShellOperator(command) {
1347
+ let single = false;
1348
+ let double = false;
1349
+ let escaped = false;
1350
+ for (const ch of command) {
1351
+ if (escaped) {
1352
+ escaped = false;
1353
+ continue;
1354
+ }
1355
+ if (ch === "\\" && !single)
1356
+ escaped = true;
1357
+ else if (ch === "'" && !double)
1358
+ single = !single;
1359
+ else if (ch === '"' && !single)
1360
+ double = !double;
1361
+ else if ("|;&><\n\r".includes(ch) && !single && !double)
1362
+ return true;
1363
+ }
1364
+ return false;
1365
+ }
1366
+ const RESULT_STRING_FIELDS = ["tool", "cmd_name", "task_id", "pending_reason", "estimated_wait", "title", "summary", "cmd_args", "partial_output", "output"];
1367
+ function forwardInnerResult(command, out) {
1368
+ var _a;
1369
+ if (commandHasShellOperator(command) || !((_a = tokenizeBashCommandLine(command)) == null ? void 0 : _a.length))
1370
+ return void 0;
1371
+ const stdout = out.stdout.trim();
1372
+ if (!stdout)
1373
+ return void 0;
1374
+ let v;
1375
+ try {
1376
+ v = JSON.parse(stdout);
1377
+ } catch {
1378
+ return void 0;
1379
+ }
1380
+ if (!isObject(v) || v.agent_tool_protocol !== "1")
1381
+ return void 0;
1382
+ const status = v.status ?? "success";
1383
+ if (status !== "success" && status !== "error" && status !== "pending")
1384
+ return void 0;
1385
+ for (const k of RESULT_STRING_FIELDS)
1386
+ if (v[k] !== void 0 && v[k] !== null && typeof v[k] !== "string")
1387
+ return void 0;
1388
+ if (status === "pending" && typeof v.task_id !== "string")
1389
+ return void 0;
1390
+ const r = { ...v, status, summary: typeof v.summary === "string" ? v.summary : "", detail: v.detail === void 0 ? {} : v.detail };
1391
+ if (r.return_code === void 0 && out.exit_code !== 0)
1392
+ r.return_code = out.exit_code;
1393
+ return r;
1394
+ }
1395
+ function shellSpec(cfg) {
1396
+ const max = cfg.maxTimeoutMs;
1397
+ const description = `Run a command in this run's runtime (native) with bash syntax. It starts in the working directory unless cwd is given; it is not sandboxed and runs with the current user's permissions. The command is a child process of this executor: an interrupt or a timeout ends its process group; processes it leaves behind after returning are not managed. Waits for the command to finish. Default timeout ${Math.floor(cfg.timeoutMs / 1e3)}s${max === 0 ? ", no upper limit" : `, max ${Math.floor(max / 1e3)}s`}; on timeout the command is stopped and the output so far is returned. Start a long-lived service with nohup / setsid and return at once; on Unix, processes started with \`&\` / nohup in the foreground command's process group also end when that command is interrupted or times out. Long output keeps its beginning and end.`;
1398
+ const timeout = {
1399
+ description: `Timeout in milliseconds (default ${cfg.timeoutMs}${max === 0 ? "" : `, max ${max}`}). Set it explicitly for long builds, tests or media commands.`,
1400
+ minimum: 1,
1401
+ type: "integer"
1402
+ };
1403
+ if (max !== 0)
1404
+ timeout.maximum = max;
1405
+ return {
1406
+ name: TOOL_SHELL,
1407
+ description,
1408
+ args_schema: {
1409
+ properties: {
1410
+ command: { description: "bash command to execute", type: "string" },
1411
+ cwd: {
1412
+ description: cfg.restrictCwd ? "Working directory, relative to or within the configured workspace. Defaults to the workspace." : "Working directory, absolute or relative to the default working directory. Defaults to that directory; outside paths are allowed subject to OS permissions.",
1413
+ type: "string"
1414
+ },
1415
+ timeout_ms: timeout
1416
+ },
1417
+ required: ["command"],
1418
+ type: "object"
1419
+ }
1420
+ };
1421
+ }
1422
+ function parseMs(raw, name) {
1423
+ if (raw === void 0 || raw === null)
1424
+ return void 0;
1425
+ if (typeof raw === "number" && Number.isInteger(raw) && raw >= 0)
1426
+ return raw;
1427
+ if (typeof raw === "string" && /^\d+$/.test(raw.trim()))
1428
+ return Number(raw.trim());
1429
+ throw invalidArgs(`\`${name}\` must be a non-negative integer`);
1430
+ }
1431
+ function parseEnv(raw) {
1432
+ if (raw === void 0 || raw === null)
1433
+ return [];
1434
+ if (!isObject(raw))
1435
+ throw invalidArgs("`env` must be an object of string=>string");
1436
+ const out = [];
1437
+ for (const [k, v] of Object.entries(raw)) {
1438
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k))
1439
+ throw invalidArgs(`invalid env key \`${k}\` (must match [A-Za-z_][A-Za-z0-9_]*)`);
1440
+ if (typeof v === "string")
1441
+ out.push([k, v]);
1442
+ else if (typeof v === "number" || typeof v === "boolean")
1443
+ out.push([k, String(v)]);
1444
+ else if (v === null)
1445
+ out.push([k, ""]);
1446
+ else
1447
+ throw invalidArgs(`env value for \`${k}\` must be string/number/bool, got ${canonicalJson(v)}`);
1448
+ }
1449
+ return out;
1450
+ }
1451
+ function appendPathEntry(entry, base) {
1452
+ if (!base)
1453
+ return entry;
1454
+ return base.split(":").includes(entry) ? base : `${base}:${entry}`;
1455
+ }
1456
+ let localSeq = 0;
1457
+ function sleepOrStop(ms) {
1458
+ let timer;
1459
+ const done = new Promise((resolve) => {
1460
+ timer = setTimeout(() => resolve("timeout"), Math.min(ms, 2 ** 31 - 1));
1461
+ });
1462
+ return { done, stop: () => clearTimeout(timer) };
1463
+ }
1464
+ function causeText(cause) {
1465
+ return cause === "finishing" ? "the run is finishing" : cause === "deadline" ? "the run's total time limit was reached" : "the run was interrupted";
1466
+ }
1467
+ function shellTool(cfg) {
1468
+ const resolveTimeout = (raw) => {
1469
+ const c = raw ?? cfg.timeoutMs;
1470
+ return cfg.maxTimeoutMs === 0 ? c : Math.min(Math.max(c, 1), cfg.maxTimeoutMs);
1471
+ };
1472
+ return {
1473
+ spec: shellSpec(cfg),
1474
+ idempotent: false,
1475
+ cancellable: true,
1476
+ async call(args, ctx) {
1477
+ const command = typeof args.command === "string" ? args.command.trim() : "";
1478
+ if (!command)
1479
+ throw invalidArgs("`command` is required and must be non-empty");
1480
+ const rawCwd = typeof args.cwd === "string" ? args.cwd : void 0;
1481
+ const root = normalizePath(cfg.workspace);
1482
+ const cwd = await resolvePath(root, rawCwd ?? ".", cfg.restrictCwd ? [root] : []);
1483
+ if (!await isDir(cwd))
1484
+ throw invalidArgs(`cwd does not exist: ${cwd}`);
1485
+ const userEnv = parseEnv(args.env);
1486
+ const timeoutRaw = parseMs(args.timeout_ms, "timeout_ms");
1487
+ if (timeoutRaw === 0 && cfg.maxTimeoutMs !== 0)
1488
+ throw invalidArgs("`timeout_ms` must be a positive integer");
1489
+ const timeoutMs = resolveTimeout(timeoutRaw);
1490
+ parseMs(args.wait_ms, "wait_ms");
1491
+ const reqEnv = new Map(userEnv);
1492
+ let path = (reqEnv.get("PATH") ?? deno().env.get("PATH") ?? "").trim();
1493
+ for (const e of SYSTEM_PATH_ENTRIES)
1494
+ path = appendPathEntry(e, path);
1495
+ reqEnv.set("PATH", path);
1496
+ if (ctx.call_id)
1497
+ reqEnv.set(ENV_CALL_ID, ctx.call_id);
1498
+ if (ctx.run_id)
1499
+ reqEnv.set(ENV_RUN_ID, ctx.run_id);
1500
+ const env = { ...cfg.env, ...Object.fromEntries(reqEnv) };
1501
+ env.PATH = [...new Set(path.split(":").filter(Boolean))].join(":");
1502
+ const bound = execDirFor(ctx.run_dir, ctx.call_id);
1503
+ const temp = bound === void 0;
1504
+ const dir = bound ?? joinPath(deno().env.get("TMPDIR") || "/tmp", `llm-shell-${deno().pid}-${++localSeq}`);
1505
+ try {
1506
+ await deno().mkdir(dir, { recursive: true, mode: 448 });
1507
+ } catch (e) {
1508
+ throw execFailed(`execution directory: ${errorText(e)}`);
1509
+ }
1510
+ for (const stale of ["exit", "exit.tmp"])
1511
+ await deno().remove(joinPath(dir, stale)).catch(() => void 0);
1512
+ let child;
1513
+ const started = performance.now();
1514
+ try {
1515
+ child = new (deno()).Command("/bin/bash", {
1516
+ args: ["-c", NATIVE_WRAPPER, command, dir],
1517
+ cwd,
1518
+ env,
1519
+ stdin: "null",
1520
+ stdout: "null",
1521
+ stderr: "null"
1522
+ }).spawn();
1523
+ } catch (e) {
1524
+ throw execFailed(`spawn shell failed: ${errorText(e)}`);
1525
+ }
1526
+ const cleanup = async () => {
1527
+ if (temp)
1528
+ await deno().remove(dir, { recursive: true }).catch(() => void 0);
1529
+ };
1530
+ const kill = async () => {
1531
+ try {
1532
+ child.kill("SIGKILL");
1533
+ } catch {
1534
+ }
1535
+ const t = sleepOrStop(5e3);
1536
+ await Promise.race([child.status, t.done]);
1537
+ t.stop();
1538
+ const out2 = await outputFromExecDir(dir, TIMEOUT_EXIT_CODE, true, performance.now() - started, EXEC_MAX_OUTPUT_BYTES, cwd);
1539
+ await cleanup();
1540
+ return out2;
1541
+ };
1542
+ const timer = sleepOrStop(timeoutMs === 0 ? 365 * 24 * 3600 * 1e3 : timeoutMs);
1543
+ const first = await Promise.race([
1544
+ child.status.then((s) => ({ exited: s })),
1545
+ timer.done.then(() => ({ timeout: true })),
1546
+ ctx.call.cancelled().then((cause) => ({ cancel: cause }))
1547
+ ]);
1548
+ timer.stop();
1549
+ let out;
1550
+ if ("exited" in first) {
1551
+ out = await outputFromExecDir(dir, exitCodeOf(first.exited), false, performance.now() - started, EXEC_MAX_OUTPUT_BYTES, cwd);
1552
+ await cleanup();
1553
+ } else if ("timeout" in first) {
1554
+ out = await kill();
1555
+ } else {
1556
+ const tail = (await readFileTail(joinPath(dir, "stdout"), OUTPUT_TAIL_BYTES)).trimEnd();
1557
+ const stopped = await kill();
1558
+ throw new NativeToolError(
1559
+ "cancelled",
1560
+ `shell (native): \`${command}\` was stopped after ${stopped.duration_ms}ms because ${causeText(first.cancel)}. It may have had partial side effects; check before repeating it.${tail.trim() ? `
1561
+ --- output so far (tail) ---
1562
+ ${tail}` : ""}`
1563
+ );
1564
+ }
1565
+ return shellFinishedResult(command, out, timeoutMs, cfg.maxTimeoutMs);
1566
+ }
1567
+ };
1568
+ }
1569
+ function shellFinishedResult(command, out, timeoutMs, maxTimeoutMs) {
1570
+ if (!out.timed_out) {
1571
+ const inner = forwardInnerResult(command, out);
1572
+ if (inner)
1573
+ return inner;
1574
+ }
1575
+ const summary = out.timed_out ? `timed out after ${out.duration_ms}ms (timeout_ms=${timeoutMs}); the command was stopped. Retry with a larger timeout_ms${maxTimeoutMs === 0 ? "" : ` (max ${maxTimeoutMs})`}, or start a long-lived service with nohup / setsid and return at once.` : `exit=${out.exit_code} in ${out.duration_ms}ms`;
1576
+ const detail = {
1577
+ command,
1578
+ cwd: out.cwd,
1579
+ exit_code: out.exit_code,
1580
+ stdout: out.stdout,
1581
+ stderr: out.stderr,
1582
+ output: out.output,
1583
+ output_truncated: out.output_truncated,
1584
+ timed_out: out.timed_out,
1585
+ duration_ms: out.duration_ms,
1586
+ engine: LOCAL_ENGINE,
1587
+ runtime: "native"
1588
+ };
1589
+ const r = builtinResult(TOOL_SHELL, detail, `${TOOL_SHELL} ${command}`, summary);
1590
+ r.status = out.exit_code === 0 && !out.timed_out ? "success" : "error";
1591
+ r.return_code = out.exit_code;
1592
+ r.title = defaultTitle(r);
1593
+ return withOutput(r, out.output);
1594
+ }
1595
+ const NATIVE_KIND = "native";
1596
+ const LOCAL_PROBE = `set -e
1597
+ command -v bash >/dev/null
1598
+ machine_id="$(cat /etc/machine-id 2>/dev/null || true)"
1599
+ [ -n "$machine_id" ] || machine_id="$(hostname)"
1600
+ printf '%s\\0' "$machine_id" "$(hostname)" "$(id -u)" "$(uname -s | tr '[:upper:]' '[:lower:]')" "$(uname -m)" "$(command -v bash)" "$(pwd -P)" "\${PATH}" "$(date +%Y-%m-%dT%H:%M:%S%z)" "$(date +%Z%z)"
1601
+ for tool in bash realpath base64; do if command -v "$tool" >/dev/null; then printf '%s\\0' "$tool"; fi; done
1602
+ `;
1603
+ function parseProbe(bytes) {
1604
+ let text = new TextDecoder().decode(bytes);
1605
+ if (text.endsWith("\0"))
1606
+ text = text.slice(0, -1);
1607
+ const p = text.split("\0");
1608
+ if (p.length < 10 || p.slice(0, 10).some((f) => f === ""))
1609
+ throw XllmError.capability("execution environment probe returned incomplete data");
1610
+ return {
1611
+ machine: p[0],
1612
+ hostname: p[1],
1613
+ uid: p[2],
1614
+ os: p[3],
1615
+ arch: p[4],
1616
+ shell: p[5],
1617
+ cwd: p[6],
1618
+ path: p[7],
1619
+ current_time: p[8],
1620
+ timezone: p[9],
1621
+ tools: p.slice(10, 42)
1622
+ };
1623
+ }
1624
+ async function localProbe(cwd, env) {
1625
+ if (deno().build.os === "windows")
1626
+ throw XllmError.capability("the Deno host's native runtime needs bash (Linux / macOS); Windows PowerShell runtimes are Rust-only");
1627
+ let out;
1628
+ try {
1629
+ out = await new (deno()).Command("/bin/bash", {
1630
+ args: ["-c", LOCAL_PROBE],
1631
+ cwd,
1632
+ env,
1633
+ stdin: "null",
1634
+ stdout: "piped",
1635
+ stderr: "piped",
1636
+ signal: AbortSignal.timeout(1e4)
1637
+ }).output();
1638
+ } catch (e) {
1639
+ throw XllmError.capability(errorText(e));
1640
+ }
1641
+ if (!out.success)
1642
+ throw XllmError.capability(`native capability probe failed: ${new TextDecoder().decode(out.stderr)}`);
1643
+ return parseProbe(out.stdout);
1644
+ }
1645
+ function configError(reason) {
1646
+ return XllmError.config(".llm_context", "runtime", reason);
1647
+ }
1648
+ function validateConfig(c) {
1649
+ const kind = c.kind ?? NATIVE_KIND;
1650
+ if (PLANNED_RUNTIME_KINDS.includes(kind))
1651
+ throw XllmError.capability(`runtime \`${kind}\` is planned but not implemented`);
1652
+ if (kind === "site")
1653
+ throw XllmError.capability("runtime `site` is built by a website (createSiteRuntime); the Deno host runs `native`");
1654
+ if (kind === "remote_ssh" || kind === "remote_node")
1655
+ throw XllmError.capability(`runtime \`${kind}\` is not available on the Deno host (only \`native\`)`);
1656
+ if (kind !== NATIVE_KIND)
1657
+ throw configError(`unknown runtime kind \`${kind}\``);
1658
+ if (c.remote_ssh && c.kind !== void 0)
1659
+ throw configError("remote_ssh connection block requires kind: remote_ssh");
1660
+ if (c.remote_node && c.kind !== void 0)
1661
+ throw configError("remote_node connection block requires kind: remote_node");
1662
+ if (c.remote_ssh || c.remote_node)
1663
+ throw configError("connection block does not match runtime kind");
1664
+ validateEnv(c.env ?? {});
1665
+ if (c.id !== void 0 && !c.id.trim())
1666
+ throw configError("id cannot be empty");
1667
+ if (c.task_wait_ms === 0)
1668
+ throw configError("task_wait_ms must be positive");
1669
+ }
1670
+ function validateEnv(env) {
1671
+ for (const [k, v] of Object.entries(env)) {
1672
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || v.includes("\0"))
1673
+ throw configError(`invalid env key or value \`${k}\``);
1674
+ }
1675
+ }
1676
+ function infoOf(probe, id, target, baseline) {
1677
+ const os = probe.os.toLowerCase();
1678
+ const shellName = probe.shell.split(/[/\\]/).pop() ?? "";
1679
+ return {
1680
+ id,
1681
+ kind: NATIVE_KIND,
1682
+ os: probe.os,
1683
+ arch: probe.arch,
1684
+ hostname: probe.hostname,
1685
+ shell: probe.shell,
1686
+ cwd: probe.cwd,
1687
+ tools: probe.tools,
1688
+ current_time: probe.current_time,
1689
+ timezone: probe.timezone,
1690
+ target,
1691
+ platform: os === "darwin" || os === "macos" ? "macos" : os,
1692
+ shell_kind: shellName.replace(/\.exe$/, "").replace(/\.EXE$/, "").toLowerCase(),
1693
+ baseline: baseline ?? ""
1694
+ };
1695
+ }
1696
+ const INTENT_ARG = "intent";
1697
+ const INTENT_OPTIONAL_DESCRIPTION = "Optional: why you make this call now and what you expect it to give you, in one short sentence. Shown as the progress of your work.";
1698
+ function withOptionalIntent(spec) {
1699
+ const s = cloneJson(spec);
1700
+ let schema = s.args_schema;
1701
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema))
1702
+ schema = s.args_schema = { type: "object" };
1703
+ if (typeof schema.properties !== "object" || schema.properties === null || Array.isArray(schema.properties))
1704
+ schema.properties = {};
1705
+ schema.properties[INTENT_ARG] = { type: "string", description: INTENT_OPTIONAL_DESCRIPTION };
1706
+ if (Array.isArray(schema.required))
1707
+ schema.required = schema.required.filter((r) => r !== INTENT_ARG);
1708
+ return s;
1709
+ }
1710
+ function causeName(cause) {
1711
+ return cause === "deadline" ? "Deadline" : cause === "finishing" ? "Finishing" : "Interrupted";
1712
+ }
1713
+ class NativeToolManager {
1714
+ constructor(tools, workdir, advertised) {
1715
+ this.tools = tools;
1716
+ this.workdir = workdir;
1717
+ this.advertised = advertised;
1718
+ this.binding = { run_id: "" };
1719
+ this.ledger = new MemoryHintLedger();
1720
+ this.written = [];
1721
+ }
1722
+ bindRun(binding) {
1723
+ this.binding = { ...binding };
1724
+ }
1725
+ setRecovering(callId, reason) {
1726
+ this.recovering = { callId, reason };
1727
+ }
1728
+ artifacts() {
1729
+ return [...this.written];
1730
+ }
1731
+ has(name) {
1732
+ return this.tools.has(name);
1733
+ }
1734
+ hintLedger() {
1735
+ return this.ledger;
1736
+ }
1737
+ clearDedup() {
1738
+ this.ledger.clear(HINT_NS_DEDUP);
1739
+ }
1740
+ taskResolver() {
1741
+ return void 0;
1742
+ }
1743
+ listToolSpecs() {
1744
+ const specs = this.advertised ? [...this.advertised.values()] : [...this.tools.values()].map((t) => t.spec);
1745
+ return specs.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map((s) => BASH_GROUP_TOOLS.includes(s.name) ? withOptionalIntent(s) : cloneJson(s));
1746
+ }
1747
+ names() {
1748
+ return [...this.tools.keys()].sort().join(", ");
1749
+ }
1750
+ async callTool(call, ctx) {
1751
+ var _a, _b;
1752
+ const callId = call.call_id;
1753
+ const tool = this.tools.get(call.name);
1754
+ if (!tool)
1755
+ return { kind: "error", call_id: callId, message: `tool \`${call.name}\` is not available in this run (available: ${this.names()})` };
1756
+ const args = { ...call.args ?? {} };
1757
+ if (BASH_GROUP_TOOLS.includes(call.name))
1758
+ delete args[INTENT_ARG];
1759
+ if (((_a = this.recovering) == null ? void 0 : _a.callId) === callId) {
1760
+ const reason = this.recovering.reason;
1761
+ this.recovering = void 0;
1762
+ if (!tool.idempotent)
1763
+ return { kind: "unresolved", call_id: callId, reason, effect_unknown: true };
1764
+ }
1765
+ const running = tool.call(args, { call_id: callId, run_id: this.binding.run_id, run_dir: this.binding.run_dir, call: ctx }).then((ok) => ({ ok }), (err) => ({ err }));
1766
+ let settled;
1767
+ if (tool.cancellable) {
1768
+ settled = await running;
1769
+ } else {
1770
+ const first = await Promise.race([running, ctx.cancelledHard().then((cause) => ({ cancelled: cause }))]);
1771
+ if ("cancelled" in first) {
1772
+ return {
1773
+ kind: "cancelled",
1774
+ call_id: callId,
1775
+ reason: `tool \`${call.name}\` was abandoned while running (${causeName(first.cancelled)}); it cannot be cancelled, so its effect is unknown`,
1776
+ effect_unknown: true
1777
+ };
1778
+ }
1779
+ settled = first;
1780
+ }
1781
+ if ("err" in settled) {
1782
+ const e = settled.err;
1783
+ if (e instanceof NativeToolError) {
1784
+ if (e.kind === "transport")
1785
+ throw new ToolDispatchException(e.detail, e.effectUnknown);
1786
+ if (e.kind === "cancelled")
1787
+ return { kind: "cancelled", call_id: callId, reason: e.detail, effect_unknown: e.effectUnknown };
1788
+ return { kind: "error", call_id: callId, message: e.message };
1789
+ }
1790
+ return { kind: "error", call_id: callId, message: `execution failed: ${errorText(e)}` };
1791
+ }
1792
+ const result = settled.ok;
1793
+ if (result.status === "success" && (call.name === TOOL_WRITE_FILE || call.name === TOOL_EDIT_FILE)) {
1794
+ const p = args.path;
1795
+ if (typeof p === "string") {
1796
+ const abs = p.startsWith("/") ? p : normalizePath(joinPath(this.workdir, p));
1797
+ if (!this.written.includes(abs))
1798
+ this.written.push(abs);
1799
+ }
1800
+ }
1801
+ if (result.status === "pending") {
1802
+ const taskId = (_b = result.task_id) == null ? void 0 : _b.trim();
1803
+ if (!taskId)
1804
+ return { kind: "error", call_id: callId, message: `tool \`${call.name}\` returned a pending result without a task_id`, host: toHost(result) };
1805
+ return taskStateObservation(callId, taskId, { kind: "unknown", reason: "this runtime has no task backend" }, { kind: "tools" });
1806
+ }
1807
+ return envelopeObservation(callId, result, applyHints(result, this.ledger));
1808
+ }
1809
+ }
1810
+ function nativeDescriptor(runtimeId, target, probe) {
1811
+ return {
1812
+ runtime_id: runtimeId,
1813
+ kind: NATIVE_KIND,
1814
+ host: target.host,
1815
+ target,
1816
+ workdir: probe.cwd,
1817
+ capabilities: { tools: Object.fromEntries(probe.tools.map((t) => [t, "available"])), network: true, os: probe.os }
1818
+ };
1819
+ }
1820
+ function shellNeedsTasks(shell) {
1821
+ return shell.wait_ms < shell.timeout_ms;
1822
+ }
1823
+ async function createNativeRuntime(options = {}) {
1824
+ const configured = cloneJson(options.config ?? { env: {} });
1825
+ configured.env = configured.env ?? {};
1826
+ validateConfig(configured);
1827
+ const rawCwd = configured.workdir ?? options.workdir ?? deno().cwd();
1828
+ let cwd;
1829
+ try {
1830
+ cwd = await deno().realPath(rawCwd);
1831
+ } catch (e) {
1832
+ throw XllmError.capability(`runtime cwd ${rawCwd}: ${errorText(e)}`);
1833
+ }
1834
+ if (!await isDir(cwd))
1835
+ throw XllmError.capability("runtime workdir must be a directory");
1836
+ const probe = await localProbe(cwd, configured.env);
1837
+ const target = nativeTarget(await nativeHostId(), probe.uid);
1838
+ const id = deriveRuntimeId(configured.id, NATIVE_KIND, target);
1839
+ const info = infoOf(probe, id, target, configured.baseline);
1840
+ const config = { ...configured, kind: NATIVE_KIND, id, workdir: info.cwd };
1841
+ const descriptor = nativeDescriptor(id, target, probe);
1842
+ const dfsRoot = joinPath(deno().env.get("BUCKYOS_ROOT") || "/opt/buckyos", "data");
1843
+ const expand = (sources, field, shell, fsPolicy, env, tools) => {
1844
+ const out = [];
1845
+ for (const src of sources) {
1846
+ const desc = describeToolSource(src);
1847
+ if (src.kind === "mcp")
1848
+ throw XllmError.capability(`${field}: \`${desc}\`: MCP tools are not available on the Deno host`);
1849
+ if (src.kind === "named")
1850
+ throw XllmError.capability(`${field}: \`${desc}\`: named host tools are not available on the Deno host (only the \`bash\` group)`);
1851
+ if (src.groupname === BUILTIN_TOOL_GROUP_BASH_CORE || src.groupname === "executor") {
1852
+ throw XllmError.capability(`${field}: \`${desc}\` needs a host task CLI / executor that the Deno host does not provide (use \`bash\`)`);
1853
+ }
1854
+ if (src.groupname !== BUILTIN_TOOL_GROUP_BASH) {
1855
+ throw XllmError.tools(`unknown builtin tool group \`${src.groupname}\` (available: ${BUILTIN_TOOL_GROUP_BASH}, ${BUILTIN_TOOL_GROUP_BASH_CORE}, executor)`);
1856
+ }
1857
+ if (shellNeedsTasks(shell)) {
1858
+ throw XllmError.capability(`${field}: \`shell\` would hand commands still running after runtime.task_wait_ms (${shell.wait_ms} ms) to a task backend, which the Deno host does not have; set runtime.task_wait_ms to at least tools.shell.timeout_ms (${shell.timeout_ms} ms) so \`shell\` waits for its command`);
1859
+ }
1860
+ const restrict = fsPolicy === "workspace";
1861
+ const fileCfg = {
1862
+ root: info.cwd,
1863
+ allowedRead: restrict ? [info.cwd] : [],
1864
+ allowedWrite: restrict ? [info.cwd] : [],
1865
+ dfsRoot
1866
+ };
1867
+ const group = [
1868
+ readFileTool(fileCfg),
1869
+ writeFileTool(fileCfg),
1870
+ editFileTool(fileCfg),
1871
+ shellTool({ workspace: info.cwd, restrictCwd: restrict, timeoutMs: shell.timeout_ms, maxTimeoutMs: shell.max_timeout_ms, env })
1872
+ ];
1873
+ for (const t of group) {
1874
+ if (tools.has(t.spec.name)) {
1875
+ throw XllmError.tools(`tool name \`${t.spec.name}\` from ${desc} conflicts with an already expanded tool of the same name`);
1876
+ }
1877
+ tools.set(t.spec.name, t);
1878
+ out.push({ name: t.spec.name, description: t.spec.description, args_schema: cloneJson(t.spec.args_schema), source: desc });
1879
+ }
1880
+ }
1881
+ return out;
1882
+ };
1883
+ let openedNames;
1884
+ const runtime = {
1885
+ kind: NATIVE_KIND,
1886
+ probe,
1887
+ descriptor: () => cloneJson(descriptor),
1888
+ config: () => cloneJson(config),
1889
+ // After `open`, the info of the opened tool set (Rust prompts read the manager's: probed
1890
+ // commands and the run's tool names, sorted, at most 32).
1891
+ async info() {
1892
+ const now = await localProbe(info.cwd, config.env);
1893
+ const tools = openedNames ? [.../* @__PURE__ */ new Set([...info.tools, ...openedNames])].sort().slice(0, 32) : info.tools;
1894
+ return { ...cloneJson(info), tools, current_time: now.current_time, timezone: now.timezone };
1895
+ },
1896
+ // deno-lint-ignore require-await
1897
+ async open(ctx, requested) {
1898
+ validateEnv(ctx.env);
1899
+ const env = { ...config.env, ...ctx.env };
1900
+ env.PATH = env.PATH ?? probe.path;
1901
+ const take = options.takeover && options.takeover.run_id === ctx.run_id ? options.takeover.tools : void 0;
1902
+ const cfg = take ? {
1903
+ enabled: take.enabled,
1904
+ filesystem_policy: take.filesystem_policy,
1905
+ tools2actions: take.tools2actions,
1906
+ tools: take.tool_sources,
1907
+ actions: take.action_sources,
1908
+ bash_tools: take.bash_tools,
1909
+ shell: { timeout_ms: take.shell.timeout_ms, max_timeout_ms: take.shell.max_timeout_ms }
1910
+ } : requested;
1911
+ const enabled = cfg.enabled ?? false;
1912
+ const fsPolicy = cfg.filesystem_policy ?? "workspace";
1913
+ const tools2actions = cfg.tools2actions ?? false;
1914
+ const shell = shellSettings(cfg.shell, ctx.task_wait_ms);
1915
+ const loop = ctx.loop_model;
1916
+ const eff = {
1917
+ enabled,
1918
+ filesystem_policy: fsPolicy,
1919
+ tools2actions,
1920
+ tool_sources: cloneJson(cfg.tools ?? []),
1921
+ action_sources: cloneJson(cfg.actions ?? []),
1922
+ native: [],
1923
+ actions: [],
1924
+ bash_tools: cloneJson(cfg.bash_tools ?? []),
1925
+ shell,
1926
+ exec_enabled: false,
1927
+ sources: { ...ctx.sources }
1928
+ };
1929
+ if (loop === "function_call") {
1930
+ if (tools2actions) {
1931
+ throw XllmError.capability("`tools2actions: true` requires `loop_model: behavior`; function_call cannot convert tools into actions");
1932
+ }
1933
+ if ((cfg.actions ?? []).length > 0) {
1934
+ throw XllmError.capability("`actions` are configured but `loop_model` is function_call; use `loop_model: behavior` or remove `actions`");
1935
+ }
1936
+ }
1937
+ const tools = /* @__PURE__ */ new Map();
1938
+ if (enabled) {
1939
+ const toolSources = cfg.tools ?? [{ kind: "group", groupname: BUILTIN_TOOL_GROUP_BASH }];
1940
+ eff.tool_sources = cloneJson(toolSources);
1941
+ const native = expand(toolSources, "tools.tools", shell, fsPolicy, env, tools);
1942
+ const explicit = expand(eff.action_sources, "tools.actions", shell, fsPolicy, env, tools);
1943
+ if (loop === "behavior" && tools2actions) {
1944
+ eff.actions = [...native, ...explicit];
1945
+ } else {
1946
+ eff.native = native;
1947
+ eff.actions = explicit;
1948
+ }
1949
+ eff.exec_enabled = tools.has(TOOL_SHELL) && [...eff.native, ...eff.actions].some((t) => t.name === TOOL_SHELL);
1950
+ }
1951
+ let advertised;
1952
+ if (take) {
1953
+ advertised = /* @__PURE__ */ new Map();
1954
+ for (const t of [...take.native, ...take.actions]) {
1955
+ if (tools.has(t.name))
1956
+ advertised.set(t.name, { name: t.name, description: t.description, args_schema: cloneJson(t.args_schema) });
1957
+ }
1958
+ }
1959
+ openedNames = [...eff.native, ...eff.actions].map((t) => t.name);
1960
+ return { tools: eff, manager: new NativeToolManager(tools, info.cwd, advertised) };
1961
+ },
1962
+ async describeInterrupted(run, call) {
1963
+ if (call.name !== TOOL_SHELL)
1964
+ return unresolvedReason(call.name);
1965
+ const dir = execDirFor(run.run_dir, call.call_id);
1966
+ if (dir === void 0)
1967
+ return interruptedShellText(call, void 0, "(no execution directory)");
1968
+ return interruptedShellText(call, await readExecDir(dir), dir);
1969
+ }
1970
+ };
1971
+ return runtime;
1972
+ }
1973
+ async function readExecDir(dir) {
1974
+ let started;
1975
+ try {
1976
+ const m = (await deno().stat(joinPath(dir, "command"))).mtime;
1977
+ if (m)
1978
+ started = Math.floor(m.getTime());
1979
+ } catch {
1980
+ started = void 0;
1981
+ }
1982
+ return {
1983
+ exit_code: await readExitFile(dir),
1984
+ stdout_tail: await readFileTail(joinPath(dir, "stdout"), OUTPUT_TAIL_BYTES),
1985
+ stderr_tail: await readFileTail(joinPath(dir, "stderr"), OUTPUT_TAIL_BYTES),
1986
+ exists: await isDir(dir),
1987
+ started_at_ms: started
1988
+ };
1989
+ }
1990
+ function shellCommandOf(call) {
1991
+ var _a;
1992
+ const c = (_a = call.args) == null ? void 0 : _a.command;
1993
+ if (typeof c !== "string")
1994
+ return "";
1995
+ const one = c.split(/\s+/).filter(Boolean).join(" ");
1996
+ const chars = [...one];
1997
+ return chars.length > 160 ? `${chars.slice(0, 160).join("")}…` : one;
1998
+ }
1999
+ function tails(f) {
2000
+ let s = "";
2001
+ if (f.stdout_tail.trim())
2002
+ s += `
2003
+ --- stdout (tail) ---
2004
+ ${f.stdout_tail.trimEnd()}`;
2005
+ if (f.stderr_tail.trim())
2006
+ s += `
2007
+ --- stderr (tail) ---
2008
+ ${f.stderr_tail.trimEnd()}`;
2009
+ return s;
2010
+ }
2011
+ function interruptedShellText(call, facts, location) {
2012
+ const command = shellCommandOf(call);
2013
+ const started = (facts == null ? void 0 : facts.started_at_ms) !== void 0 ? `started ${fmtElapsed(Math.max(0, Date.now() - facts.started_at_ms))} ago (at ${facts.started_at_ms} ms since epoch)` : "start time unknown";
2014
+ if ((facts == null ? void 0 : facts.exit_code) !== void 0) {
2015
+ return `shell (native): the previous executor exited while \`${command}\` was running (${started}). The command has since ended with exit code ${facts.exit_code} (read from ${location}); its result was never returned, so review it before deciding whether to repeat anything.${tails(facts)}`;
2016
+ }
2017
+ return `shell (native): the previous executor exited while \`${command}\` was running (${started}). The command may have partly executed; it usually ended together with the executor, but not necessarily (e.g. after kill -9 it may still be running). Background processes it started are unaffected. Check the actual state before repeating it.${facts ? tails(facts) : ""}`;
2018
+ }
2019
+ const DEFAULT_RUNS_DIR = "~/.xllm/runs";
2020
+ const DEFAULT_LOCK_DIR = "~/.xllm/locks";
2021
+ function resolveHostPath(raw, baseDir) {
2022
+ return resolveConfigPath(raw, baseDir, homeDir());
2023
+ }
2024
+ function runsDirOf(setting, origin) {
2025
+ if ((setting == null ? void 0 : setting.kind) === "disabled")
2026
+ return void 0;
2027
+ const raw = (setting == null ? void 0 : setting.kind) === "path" ? setting.path : DEFAULT_RUNS_DIR;
2028
+ return resolveHostPath(raw, parentDir(origin.startsWith("/") ? origin : joinPath(deno().cwd(), origin)));
2029
+ }
2030
+ class FileLock {
2031
+ constructor(file, path) {
2032
+ this.file = file;
2033
+ this.path = path;
2034
+ this.released = false;
2035
+ }
2036
+ /** Non-blocking (`FileLock::try_acquire`): `null` when another open file holds it. */
2037
+ static async tryAcquire(path) {
2038
+ try {
2039
+ await deno().mkdir(parentDir(path), { recursive: true });
2040
+ } catch (e) {
2041
+ throw XllmError.storage(`cannot create lock directory ${parentDir(path)}: ${errorText(e)}`);
2042
+ }
2043
+ let file;
2044
+ try {
2045
+ file = await deno().open(path, { read: true, write: true, create: true });
2046
+ } catch (e) {
2047
+ throw XllmError.storage(`cannot open lock ${path}: ${errorText(e)}`);
2048
+ }
2049
+ if (!await file.tryLock(true)) {
2050
+ file.close();
2051
+ return null;
2052
+ }
2053
+ try {
2054
+ await deno().writeTextFile(path, `${deno().pid}
2055
+ `);
2056
+ } catch {
2057
+ }
2058
+ return new FileLock(file, path);
2059
+ }
2060
+ async release() {
2061
+ if (this.released)
2062
+ return;
2063
+ this.released = true;
2064
+ try {
2065
+ await this.file.unlock();
2066
+ } finally {
2067
+ this.file.close();
2068
+ }
2069
+ }
2070
+ }
2071
+ async function isLocked(path) {
2072
+ let file;
2073
+ try {
2074
+ file = await deno().open(path, { read: true, write: true, create: true });
2075
+ } catch {
2076
+ return false;
2077
+ }
2078
+ try {
2079
+ if (await file.tryLock(true)) {
2080
+ await file.unlock();
2081
+ return false;
2082
+ }
2083
+ return true;
2084
+ } finally {
2085
+ file.close();
2086
+ }
2087
+ }
2088
+ let tmpCounter = 0;
2089
+ function pad4(n) {
2090
+ return String(n).padStart(4, "0");
2091
+ }
2092
+ class FileRunStore {
2093
+ /** `runsDir`: absolute, or relative to the current directory; `~` is the home directory. */
2094
+ constructor(runsDir) {
2095
+ this.persistent = true;
2096
+ this.dir = resolveHostPath(runsDir, deno().cwd());
2097
+ }
2098
+ runsDir() {
2099
+ return this.dir;
2100
+ }
2101
+ runDir(runId) {
2102
+ return joinPath(this.dir, runId);
2103
+ }
2104
+ /** The runs directory can be created and written (`ensure_writable`). */
2105
+ async ensureWritable() {
2106
+ try {
2107
+ await deno().mkdir(this.dir, { recursive: true });
2108
+ } catch (e) {
2109
+ throw XllmError.storage(`runs directory ${this.dir} cannot be created: ${errorText(e)}`);
2110
+ }
2111
+ const probe = joinPath(this.dir, `.probe-${deno().pid}`);
2112
+ try {
2113
+ await deno().writeFile(probe, new Uint8Array());
2114
+ } catch (e) {
2115
+ throw XllmError.storage(`runs directory ${this.dir} is not writable: ${errorText(e)}`);
2116
+ }
2117
+ await deno().remove(probe).catch(() => void 0);
2118
+ }
2119
+ async createRun() {
2120
+ await this.ensureWritable();
2121
+ for (let i = 0; i < 8; i++) {
2122
+ const runId = generateRunId();
2123
+ const dir = this.runDir(runId);
2124
+ try {
2125
+ await deno().mkdir(dir);
2126
+ } catch (e) {
2127
+ if (isAlreadyExists(e))
2128
+ continue;
2129
+ throw XllmError.storage(`cannot create run directory ${dir}: ${errorText(e)}`);
2130
+ }
2131
+ await deno().mkdir(joinPath(dir, "snapshots"), { recursive: true });
2132
+ return runId;
2133
+ }
2134
+ throw XllmError.storage("cannot allocate a unique run id");
2135
+ }
2136
+ async writeRecord(record) {
2137
+ const dir = this.runDir(record.run_id);
2138
+ const path = joinPath(dir, "run.json");
2139
+ const tmp = joinPath(dir, `run.json.tmp-${deno().pid}-${tmpCounter++}`);
2140
+ try {
2141
+ await deno().mkdir(dir, { recursive: true });
2142
+ await writeFileSynced(tmp, new TextEncoder().encode(JSON.stringify(record, null, 2)));
2143
+ } catch (e) {
2144
+ throw XllmError.storage(`write ${tmp}: ${errorText(e)}`);
2145
+ }
2146
+ try {
2147
+ await deno().rename(tmp, path);
2148
+ } catch (e) {
2149
+ throw XllmError.storage(`commit ${path}: ${errorText(e)}`);
2150
+ }
2151
+ try {
2152
+ await syncDir(dir);
2153
+ } catch (e) {
2154
+ throw XllmError.storage(`sync ${dir}: ${errorText(e)}`);
2155
+ }
2156
+ }
2157
+ /** Rejects with `run_not_found`, `not_resumable` (another record version, like Rust) or `corrupted_run`. */
2158
+ async readRecord(runId) {
2159
+ const path = joinPath(this.runDir(runId), "run.json");
2160
+ let text;
2161
+ try {
2162
+ text = await deno().readTextFile(path);
2163
+ } catch (e) {
2164
+ if (isNotFound(e))
2165
+ throw new XllmError({ kind: "run_not_found", run_id: runId, runs_dir: this.dir });
2166
+ throw XllmError.storage(`read ${path}: ${errorText(e)}`);
2167
+ }
2168
+ let value;
2169
+ try {
2170
+ value = JSON.parse(text);
2171
+ } catch (e) {
2172
+ throw new XllmError({ kind: "corrupted_run", run_id: runId, reason: errorText(e) });
2173
+ }
2174
+ const v = value;
2175
+ if ((v == null ? void 0 : v.version) !== RUN_RECORD_VERSION)
2176
+ throw XllmError.notResumable(runId, "unsupported run record version");
2177
+ if (typeof v.run_id !== "string" || typeof v.status !== "string" || typeof v.config !== "object" || typeof v.prompt !== "object") {
2178
+ throw new XllmError({ kind: "corrupted_run", run_id: runId, reason: "run.json unreadable: missing run_id / status / config / prompt" });
2179
+ }
2180
+ return value;
2181
+ }
2182
+ async listRecords() {
2183
+ const out = [];
2184
+ let entries;
2185
+ try {
2186
+ entries = deno().readDir(this.dir);
2187
+ for await (const entry of entries) {
2188
+ if (!entry.isDirectory)
2189
+ continue;
2190
+ try {
2191
+ const rec = JSON.parse(await deno().readTextFile(joinPath(this.dir, entry.name, "run.json")));
2192
+ if (rec && typeof rec.run_id === "string")
2193
+ out.push(rec);
2194
+ } catch {
2195
+ }
2196
+ }
2197
+ } catch (e) {
2198
+ if (isNotFound(e))
2199
+ return out;
2200
+ throw XllmError.storage(`read runs directory ${this.dir}: ${errorText(e)}`);
2201
+ }
2202
+ return out;
2203
+ }
2204
+ async putSnapshot(runId, snapshot) {
2205
+ const dir = joinPath(this.runDir(runId), "snapshots");
2206
+ try {
2207
+ await deno().mkdir(dir, { recursive: true });
2208
+ const idxs = await this.listSnapshots(runId);
2209
+ const next = idxs.length ? idxs[idxs.length - 1] + 1 : 1;
2210
+ const path = joinPath(dir, `${pad4(next)}.json`);
2211
+ const tmp = joinPath(dir, `${pad4(next)}.json.tmp`);
2212
+ await writeFileSynced(tmp, new TextEncoder().encode(JSON.stringify(snapshot)));
2213
+ await deno().rename(tmp, path);
2214
+ await syncDir(dir);
2215
+ return next;
2216
+ } catch (e) {
2217
+ if (e instanceof XllmError)
2218
+ throw e;
2219
+ throw XllmError.storage(`write snapshot of ${runId}: ${errorText(e)}`);
2220
+ }
2221
+ }
2222
+ async getSnapshot(runId, idx) {
2223
+ const path = joinPath(this.runDir(runId), "snapshots", `${pad4(idx)}.json`);
2224
+ let text;
2225
+ try {
2226
+ text = await deno().readTextFile(path);
2227
+ } catch (e) {
2228
+ throw new XllmError({ kind: "corrupted_run", run_id: runId, reason: `snapshot ${idx} missing at ${path}: ${errorText(e)}` });
2229
+ }
2230
+ try {
2231
+ return JSON.parse(text);
2232
+ } catch (e) {
2233
+ throw new XllmError({ kind: "corrupted_run", run_id: runId, reason: `snapshot ${idx} unreadable: ${errorText(e)}` });
2234
+ }
2235
+ }
2236
+ async listSnapshots(runId) {
2237
+ const dir = joinPath(this.runDir(runId), "snapshots");
2238
+ const idxs = [];
2239
+ try {
2240
+ for await (const entry of deno().readDir(dir)) {
2241
+ const m = /^(\d+)\.json$/.exec(entry.name);
2242
+ if (m)
2243
+ idxs.push(Number(m[1]));
2244
+ }
2245
+ } catch (e) {
2246
+ if (isNotFound(e))
2247
+ return [];
2248
+ throw e;
2249
+ }
2250
+ return idxs.sort((a, b) => a - b);
2251
+ }
2252
+ /** The run's execution lock (`<run>/.lock`), `null` when another process (or open file) holds it. */
2253
+ lockRun(runId) {
2254
+ return FileLock.tryAcquire(joinPath(this.runDir(runId), ".lock"));
2255
+ }
2256
+ /** Some process holds the run's `.lock` (`is_run_live`). */
2257
+ async isRunLive(runId) {
2258
+ if (!await isDir(this.runDir(runId)))
2259
+ return false;
2260
+ return isLocked(joinPath(this.runDir(runId), ".lock"));
2261
+ }
2262
+ /** Delete the run directory; the caller holds its lock and has nothing unreconciled in flight. */
2263
+ async removeRun(runId) {
2264
+ const dir = this.runDir(runId);
2265
+ try {
2266
+ await deno().remove(dir, { recursive: true });
2267
+ } catch (e) {
2268
+ if (!isNotFound(e))
2269
+ throw XllmError.storage(`remove ${dir}: ${errorText(e)}`);
2270
+ }
2271
+ await syncDir(this.dir).catch(() => void 0);
2272
+ }
2273
+ /** Write a run exported from another store: same id, same snapshot indices. */
2274
+ async importRun(run) {
2275
+ const id = run.record.run_id;
2276
+ if (await this.isRunLive(id))
2277
+ throw new XllmError({ kind: "run_busy", run_id: id });
2278
+ const dir = this.runDir(id);
2279
+ await deno().mkdir(joinPath(dir, "snapshots"), { recursive: true });
2280
+ for (const [idx, snapshot] of run.snapshots) {
2281
+ const path = joinPath(dir, "snapshots", `${pad4(idx)}.json`);
2282
+ const tmp = `${path}.tmp`;
2283
+ await writeFileSynced(tmp, new TextEncoder().encode(JSON.stringify(snapshot)));
2284
+ await deno().rename(tmp, path);
2285
+ }
2286
+ await syncDir(joinPath(dir, "snapshots"));
2287
+ await this.writeRecord(run.record);
2288
+ }
2289
+ }
2290
+ function workdirLocker(lockDir = DEFAULT_LOCK_DIR) {
2291
+ const dir = resolveHostPath(lockDir, deno().cwd());
2292
+ return async (workdir, runId) => {
2293
+ const lock = await FileLock.tryAcquire(workdirLockPath(dir, workdir));
2294
+ if (lock)
2295
+ await deno().writeTextFile(lock.path, `${runId}
2296
+ `).catch(() => void 0);
2297
+ return lock;
2298
+ };
2299
+ }
2300
+ function workdirExists(workdir) {
2301
+ return isDir(workdir);
2302
+ }
2303
+ const SESSION_TOKEN_ENV = "BUCKYOS_APPCLIENT_SESSION_TOKEN";
2304
+ async function resolveSecret(ref) {
2305
+ if (ref.kind === "env") {
2306
+ const v = deno().env.get(ref.name);
2307
+ if (v === void 0)
2308
+ throw XllmError.capability(`environment variable \`${ref.name}\` is not set`);
2309
+ return v;
2310
+ }
2311
+ let raw;
2312
+ try {
2313
+ raw = await deno().readTextFile(ref.path);
2314
+ } catch (e) {
2315
+ throw XllmError.capability(`cannot re-read credential source ${ref.path}:${ref.field}: ${errorText(e)}`);
2316
+ }
2317
+ let doc;
2318
+ try {
2319
+ doc = JSON.parse(raw);
2320
+ } catch (e) {
2321
+ throw XllmError.capability(`cannot parse credential source ${ref.path} (the Deno host reads JSON configuration): ${errorText(e)}`);
2322
+ }
2323
+ let cur = doc;
2324
+ for (const seg of ref.field.split(".")) {
2325
+ if (!isObject(cur) || !(seg in cur))
2326
+ throw XllmError.capability(`credential field \`${ref.field}\` no longer exists in ${ref.path}`);
2327
+ cur = cur[seg];
2328
+ }
2329
+ if (typeof cur !== "string" || !cur.trim())
2330
+ throw XllmError.capability(`credential field \`${ref.field}\` in ${ref.path} is empty or not a string`);
2331
+ return cur;
2332
+ }
2333
+ function credentialsRefusedClient(message) {
2334
+ return {
2335
+ // deno-lint-ignore require-await
2336
+ async infer() {
2337
+ throw providerError({ refused: { code: REFUSED_CREDENTIALS } }, message);
2338
+ }
2339
+ };
2340
+ }
2341
+ async function loadNodeSdk() {
2342
+ const url = new URL("./node.mjs", self.location).href;
2343
+ return await import(
2344
+ /* @vite-ignore */
2345
+ url
2346
+ );
2347
+ }
2348
+ async function createLlmClient(provider) {
2349
+ var _a, _b, _c;
2350
+ if ((provider.kind ?? "buckyos") === "openai") {
2351
+ const key = provider.api_key ? await resolveSecret(provider.api_key) : deno().env.get("OPENAI_API_KEY");
2352
+ if (!(key == null ? void 0 : key.trim())) {
2353
+ throw XllmError.capability("openai provider: no API key; set `provider.api_key`, `provider.api_key_env` or the OPENAI_API_KEY environment variable");
2354
+ }
2355
+ return new OpenAiLlmClient({ baseUrl: provider.base_url, apiKey: key, headers: provider.headers });
2356
+ }
2357
+ if (provider.on_behalf_of !== void 0 && provider.on_behalf_of !== null) {
2358
+ throw XllmError.capability("buckyos provider: `on_behalf_of` (a system service paying for a user) is not available on the Deno host");
2359
+ }
2360
+ const token = provider.session_token ? await resolveSecret(provider.session_token) : (_a = deno().env.get(SESSION_TOKEN_ENV)) == null ? void 0 : _a.trim();
2361
+ if (!token) {
2362
+ return credentialsRefusedClient(`buckyos provider: no BuckyOS session on this host (set ${SESSION_TOKEN_ENV}), sign in and resume`);
2363
+ }
2364
+ const appId = ((_b = deno().env.get("BUCKYOS_APP_ID")) == null ? void 0 : _b.trim()) || "buckycli";
2365
+ const sdk = new (await loadNodeSdk()).BuckyOSSDK("node");
2366
+ try {
2367
+ await sdk.initBuckyOS(appId, {
2368
+ zoneHost: ((_c = deno().env.get("BUCKYOS_ZONE_HOST")) == null ? void 0 : _c.trim()) ?? "",
2369
+ appId,
2370
+ defaultProtocol: "https://",
2371
+ runtimeType: "AppClient",
2372
+ sessionToken: token,
2373
+ privateKeySearchPaths: [],
2374
+ autoRenew: false
2375
+ });
2376
+ } catch (e) {
2377
+ throw XllmError.capability(`buckyos provider: cannot initialize the BuckyOS runtime (check zone/session setup): ${errorText(e)}`);
2378
+ }
2379
+ return new AiccLlmClient(sdk.getAiccClient());
2380
+ }
2381
+ function nativeDeps(runtime, store, llm, options = {}) {
2382
+ const deps = {
2383
+ llm,
2384
+ runtime,
2385
+ store,
2386
+ pid: deno().pid,
2387
+ lockWorkdir: workdirLocker(options.lockDir),
2388
+ workdirExists
2389
+ };
2390
+ if (options.observer)
2391
+ deps.observer = options.observer;
2392
+ if (options.tokenizer)
2393
+ deps.tokenizer = options.tokenizer;
2394
+ return deps;
2395
+ }
2396
+ const pendingLlm = {
2397
+ infer() {
2398
+ throw XllmError.other("the model client is created after the task is prepared");
2399
+ }
2400
+ };
2401
+ async function prepareNativeTask(llmContext, origin, input, overrides, options = {}) {
2402
+ const merged = mergeConfigLayers([{ path: origin, file: parseLlmContextJson(origin, llmContext ?? null) }]);
2403
+ const runtime = await createNativeRuntime({ config: merged.runtime, workdir: options.workdir });
2404
+ let store = options.store;
2405
+ if (!store) {
2406
+ const dir = runsDirOf(merged.runs_dir, origin);
2407
+ store = dir === void 0 ? new MemoryRunStore() : new FileRunStore(dir);
2408
+ }
2409
+ const draft = nativeDeps(runtime, store, options.llm ?? pendingLlm, options);
2410
+ const task = await XllmTask.prepare(llmContext, origin, input, overrides, draft);
2411
+ return { task, deps: { ...draft, llm: options.llm ?? await createLlmClient(task.config.provider) } };
2412
+ }
2413
+ function unavailableRuntime(error) {
2414
+ const err = error instanceof XllmError ? error : XllmError.capability(error instanceof Error ? error.message : String(error));
2415
+ const fail = () => {
2416
+ throw err;
2417
+ };
2418
+ const rejected = () => Promise.reject(err);
2419
+ return { descriptor: fail, config: fail, info: rejected, open: rejected, describeInterrupted: rejected };
2420
+ }
2421
+ async function resumeNativeRun(store, runId, limits = {}, options = {}) {
2422
+ const record = await store.readRecord(runId);
2423
+ let runtime;
2424
+ let llm = options.llm;
2425
+ if (isTerminal(record.status)) {
2426
+ runtime = unavailableRuntime(XllmError.other("a terminal run is not executed"));
2427
+ } else {
2428
+ try {
2429
+ runtime = await createNativeRuntime({
2430
+ config: record.config.runtime,
2431
+ workdir: record.workdir,
2432
+ takeover: { run_id: record.run_id, tools: record.config.tools }
2433
+ });
2434
+ } catch (e) {
2435
+ runtime = unavailableRuntime(e);
2436
+ }
2437
+ llm = llm ?? await createLlmClient(record.config.provider);
2438
+ }
2439
+ return XllmRun.resume(store, runId, limits, nativeDeps(runtime, store, llm ?? pendingLlm, options));
2440
+ }
2441
+ export {
2442
+ BASH_GROUP_TOOLS,
2443
+ DEFAULT_LOCK_DIR,
2444
+ DEFAULT_RUNS_DIR,
2445
+ EDIT_FILE_SPEC,
2446
+ EXEC_MAX_OUTPUT_BYTES,
2447
+ FileLock,
2448
+ FileRunStore,
2449
+ HOST_ID_ENV,
2450
+ LOCAL_PROBE,
2451
+ NATIVE_KIND,
2452
+ NATIVE_WRAPPER,
2453
+ NativeToolManager,
2454
+ READ_FILE_SPEC,
2455
+ SESSION_TOKEN_ENV,
2456
+ WRITE_FILE_SPEC,
2457
+ blake3Hex,
2458
+ createLlmClient,
2459
+ createNativeRuntime,
2460
+ credentialsRefusedClient,
2461
+ deriveRuntimeId,
2462
+ execDirFor,
2463
+ fmtElapsed,
2464
+ interruptedShellText,
2465
+ isLocked,
2466
+ localProbe,
2467
+ nativeDeps,
2468
+ nativeDescriptor,
2469
+ nativeHostId,
2470
+ nativeHostIdFrom,
2471
+ nativeTarget,
2472
+ parseProbe,
2473
+ prepareNativeTask,
2474
+ readExecDir,
2475
+ resolveHostPath,
2476
+ resolveSecret,
2477
+ resumeNativeRun,
2478
+ runsDirOf,
2479
+ runtimeIdOf,
2480
+ sanitizeCallId,
2481
+ shellSpec,
2482
+ targetText,
2483
+ workdirExists,
2484
+ workdirLockPath,
2485
+ workdirLocker
2486
+ };
2487
+ //# sourceMappingURL=xllm_deno.mjs.map