buckyos 0.7.170 → 0.7.177

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/cli/core/app.ts +2 -0
  2. package/cli/core/argv.ts +45 -239
  3. package/cli/core/command.ts +3 -35
  4. package/cli/dist/cli.mjs +2151 -673
  5. package/cli/dist/cli.mjs.map +1 -1
  6. package/cli/modules/agent.ts +3 -1
  7. package/cli/modules/app.ts +13 -2
  8. package/cli/modules/pikg.ts +70 -1
  9. package/cli/modules/runtime.ts +497 -0
  10. package/cli/modules/skill.ts +583 -161
  11. package/cli/modules/skill_lint.ts +462 -0
  12. package/cli/version.ts +1 -1
  13. package/dist/account-7a7bde6f.mjs +105 -0
  14. package/dist/account-7a7bde6f.mjs.map +1 -0
  15. package/dist/account-b12ac6b9.js +2 -0
  16. package/dist/account-b12ac6b9.js.map +1 -0
  17. package/dist/aicc-67851c41.mjs +582 -0
  18. package/dist/aicc-67851c41.mjs.map +1 -0
  19. package/dist/aicc-ccb36ef7.js +2 -0
  20. package/dist/aicc-ccb36ef7.js.map +1 -0
  21. package/dist/aiworkspace_client.d.ts +36 -2
  22. package/dist/aiworkspace_client.d.ts.map +1 -1
  23. package/dist/app-frame.cjs +1 -1
  24. package/dist/app-frame.cjs.map +1 -1
  25. package/dist/app-frame.d.ts +56 -1
  26. package/dist/app-frame.d.ts.map +1 -1
  27. package/dist/app-frame.mjs +285 -4
  28. package/dist/app-frame.mjs.map +1 -1
  29. package/dist/browser.cjs +1 -1
  30. package/dist/browser.cjs.map +1 -1
  31. package/dist/browser.d.ts +4 -0
  32. package/dist/browser.d.ts.map +1 -1
  33. package/dist/browser.mjs +218 -194
  34. package/dist/browser.mjs.map +1 -1
  35. package/dist/content.cjs +1 -1
  36. package/dist/content.cjs.map +1 -1
  37. package/dist/content.d.ts +77 -0
  38. package/dist/content.d.ts.map +1 -1
  39. package/dist/content.mjs +65 -0
  40. package/dist/content.mjs.map +1 -1
  41. package/dist/content_objid-1aff74b6.js +2 -0
  42. package/dist/content_objid-1aff74b6.js.map +1 -0
  43. package/dist/content_objid-9232bcaf.mjs +29 -0
  44. package/dist/content_objid-9232bcaf.mjs.map +1 -0
  45. package/dist/content_objid.d.ts +15 -0
  46. package/dist/content_objid.d.ts.map +1 -0
  47. package/dist/did_object_client-6a1b108a.js +2 -0
  48. package/dist/did_object_client-6a1b108a.js.map +1 -0
  49. package/dist/did_object_client-7fa36f90.mjs +87 -0
  50. package/dist/did_object_client-7fa36f90.mjs.map +1 -0
  51. package/dist/did_object_client.d.ts +39 -0
  52. package/dist/did_object_client.d.ts.map +1 -0
  53. package/dist/executor_client-7ce0ddc7.js +13 -0
  54. package/dist/executor_client-7ce0ddc7.js.map +1 -0
  55. package/dist/{executor_client-5f4d0468.mjs → executor_client-bfc8a1e1.mjs} +308 -752
  56. package/dist/executor_client-bfc8a1e1.mjs.map +1 -0
  57. package/dist/executor_client.d.ts +129 -0
  58. package/dist/executor_client.d.ts.map +1 -1
  59. package/dist/index.cjs +1 -1
  60. package/dist/index.cjs.map +1 -1
  61. package/dist/index.d.ts +3 -0
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.mjs +218 -199
  64. package/dist/index.mjs.map +1 -1
  65. package/dist/internal/command_args.d.ts +67 -0
  66. package/dist/internal/command_args.d.ts.map +1 -0
  67. package/dist/krpc_client-26c2dc8b.js +2 -0
  68. package/dist/krpc_client-26c2dc8b.js.map +1 -0
  69. package/dist/krpc_client-673448e5.mjs +173 -0
  70. package/dist/krpc_client-673448e5.mjs.map +1 -0
  71. package/dist/krpc_client.d.ts +5 -1
  72. package/dist/krpc_client.d.ts.map +1 -1
  73. package/dist/{ndn_types-ab30fac0.mjs → ndn_types-0fac2499.mjs} +115 -215
  74. package/dist/ndn_types-0fac2499.mjs.map +1 -0
  75. package/dist/ndn_types-5b138882.js +2 -0
  76. package/dist/ndn_types-5b138882.js.map +1 -0
  77. package/dist/node.cjs +1 -1
  78. package/dist/node.cjs.map +1 -1
  79. package/dist/node.mjs +201 -194
  80. package/dist/node.mjs.map +1 -1
  81. package/dist/object_url-8fb5a7bf.js +2 -0
  82. package/dist/object_url-8fb5a7bf.js.map +1 -0
  83. package/dist/object_url-f72c1704.mjs +412 -0
  84. package/dist/object_url-f72c1704.mjs.map +1 -0
  85. package/dist/openai-ae2978de.mjs +163 -0
  86. package/dist/openai-ae2978de.mjs.map +1 -0
  87. package/dist/openai-f560d518.js +2 -0
  88. package/dist/openai-f560d518.js.map +1 -0
  89. package/dist/provision.cjs +6 -6
  90. package/dist/provision.cjs.map +1 -1
  91. package/dist/provision.mjs +4 -3
  92. package/dist/provision.mjs.map +1 -1
  93. package/dist/site_manager-11a7a468.mjs +6410 -0
  94. package/dist/site_manager-11a7a468.mjs.map +1 -0
  95. package/dist/site_manager-334b1a51.js +2 -0
  96. package/dist/site_manager-334b1a51.js.map +1 -0
  97. package/dist/{tus_client-b231b248.js → tus_client-809c90ab.js} +2 -2
  98. package/dist/{tus_client-b231b248.js.map → tus_client-809c90ab.js.map} +1 -1
  99. package/dist/{tus_client-d1ffe2d6.mjs → tus_client-893a3287.mjs} +2 -2
  100. package/dist/{tus_client-d1ffe2d6.mjs.map → tus_client-893a3287.mjs.map} +1 -1
  101. package/dist/xllm/core/action_parser.d.ts +15 -0
  102. package/dist/xllm/core/action_parser.d.ts.map +1 -0
  103. package/dist/xllm/core/behavior_loop.d.ts +20 -0
  104. package/dist/xllm/core/behavior_loop.d.ts.map +1 -0
  105. package/dist/xllm/core/behavior_result.d.ts +11 -0
  106. package/dist/xllm/core/behavior_result.d.ts.map +1 -0
  107. package/dist/xllm/core/config.d.ts +62 -0
  108. package/dist/xllm/core/config.d.ts.map +1 -0
  109. package/dist/xllm/core/context_window.d.ts +15 -0
  110. package/dist/xllm/core/context_window.d.ts.map +1 -0
  111. package/dist/xllm/core/deps.d.ts +97 -0
  112. package/dist/xllm/core/deps.d.ts.map +1 -0
  113. package/dist/xllm/core/errors.d.ts +94 -0
  114. package/dist/xllm/core/errors.d.ts.map +1 -0
  115. package/dist/xllm/core/interrupt.d.ts +31 -0
  116. package/dist/xllm/core/interrupt.d.ts.map +1 -0
  117. package/dist/xllm/core/json.d.ts +11 -0
  118. package/dist/xllm/core/json.d.ts.map +1 -0
  119. package/dist/xllm/core/json_check.d.ts +17 -0
  120. package/dist/xllm/core/json_check.d.ts.map +1 -0
  121. package/dist/xllm/core/loop.d.ts +135 -0
  122. package/dist/xllm/core/loop.d.ts.map +1 -0
  123. package/dist/xllm/core/messages.d.ts +18 -0
  124. package/dist/xllm/core/messages.d.ts.map +1 -0
  125. package/dist/xllm/core/observer.d.ts +14 -0
  126. package/dist/xllm/core/observer.d.ts.map +1 -0
  127. package/dist/xllm/core/open_runtime.d.ts +22 -0
  128. package/dist/xllm/core/open_runtime.d.ts.map +1 -0
  129. package/dist/xllm/core/prepare.d.ts +54 -0
  130. package/dist/xllm/core/prepare.d.ts.map +1 -0
  131. package/dist/xllm/core/prompt.d.ts +40 -0
  132. package/dist/xllm/core/prompt.d.ts.map +1 -0
  133. package/dist/xllm/core/protocol.d.ts +15 -0
  134. package/dist/xllm/core/protocol.d.ts.map +1 -0
  135. package/dist/xllm/core/result.d.ts +12 -0
  136. package/dist/xllm/core/result.d.ts.map +1 -0
  137. package/dist/xllm/core/run.d.ts +198 -0
  138. package/dist/xllm/core/run.d.ts.map +1 -0
  139. package/dist/xllm/core/rust_text.d.ts +20 -0
  140. package/dist/xllm/core/rust_text.d.ts.map +1 -0
  141. package/dist/xllm/core/site_policy.d.ts +5 -0
  142. package/dist/xllm/core/site_policy.d.ts.map +1 -0
  143. package/dist/xllm/core/store.d.ts +60 -0
  144. package/dist/xllm/core/store.d.ts.map +1 -0
  145. package/dist/xllm/core/suspension.d.ts +13 -0
  146. package/dist/xllm/core/suspension.d.ts.map +1 -0
  147. package/dist/xllm/core/tokenizer.d.ts +8 -0
  148. package/dist/xllm/core/tokenizer.d.ts.map +1 -0
  149. package/dist/xllm/core/types.d.ts +826 -0
  150. package/dist/xllm/core/types.d.ts.map +1 -0
  151. package/dist/xllm/core/xml.d.ts +19 -0
  152. package/dist/xllm/core/xml.d.ts.map +1 -0
  153. package/dist/xllm/dev/openai.d.ts +17 -0
  154. package/dist/xllm/dev/openai.d.ts.map +1 -0
  155. package/dist/xllm/dev/scripted.d.ts +46 -0
  156. package/dist/xllm/dev/scripted.d.ts.map +1 -0
  157. package/dist/xllm/dev.d.ts +5 -0
  158. package/dist/xllm/dev.d.ts.map +1 -0
  159. package/dist/xllm/hosts/browser/store.d.ts +41 -0
  160. package/dist/xllm/hosts/browser/store.d.ts.map +1 -0
  161. package/dist/xllm/hosts/deno/deno_api.d.ts +103 -0
  162. package/dist/xllm/hosts/deno/deno_api.d.ts.map +1 -0
  163. package/dist/xllm/hosts/deno/identity.d.ts +29 -0
  164. package/dist/xllm/hosts/deno/identity.d.ts.map +1 -0
  165. package/dist/xllm/hosts/deno/index.d.ts +47 -0
  166. package/dist/xllm/hosts/deno/index.d.ts.map +1 -0
  167. package/dist/xllm/hosts/deno/native_runtime.d.ts +93 -0
  168. package/dist/xllm/hosts/deno/native_runtime.d.ts.map +1 -0
  169. package/dist/xllm/hosts/deno/native_tools.d.ts +105 -0
  170. package/dist/xllm/hosts/deno/native_tools.d.ts.map +1 -0
  171. package/dist/xllm/hosts/deno/provider.d.ts +13 -0
  172. package/dist/xllm/hosts/deno/provider.d.ts.map +1 -0
  173. package/dist/xllm/hosts/deno/store.d.ts +60 -0
  174. package/dist/xllm/hosts/deno/store.d.ts.map +1 -0
  175. package/dist/xllm/index.d.ts +48 -0
  176. package/dist/xllm/index.d.ts.map +1 -0
  177. package/dist/xllm/providers/aicc.d.ts +22 -0
  178. package/dist/xllm/providers/aicc.d.ts.map +1 -0
  179. package/dist/xllm/providers/timeout.d.ts +12 -0
  180. package/dist/xllm/providers/timeout.d.ts.map +1 -0
  181. package/dist/xllm/runtime/compress.d.ts +149 -0
  182. package/dist/xllm/runtime/compress.d.ts.map +1 -0
  183. package/dist/xllm/runtime/did_object_resources.d.ts +21 -0
  184. package/dist/xllm/runtime/did_object_resources.d.ts.map +1 -0
  185. package/dist/xllm/runtime/hints.d.ts +23 -0
  186. package/dist/xllm/runtime/hints.d.ts.map +1 -0
  187. package/dist/xllm/runtime/site.d.ts +22 -0
  188. package/dist/xllm/runtime/site.d.ts.map +1 -0
  189. package/dist/xllm/runtime/site_manager.d.ts +38 -0
  190. package/dist/xllm/runtime/site_manager.d.ts.map +1 -0
  191. package/dist/xllm/runtime/site_tools.d.ts +76 -0
  192. package/dist/xllm/runtime/site_tools.d.ts.map +1 -0
  193. package/dist/xllm/runtime/step_renderer.d.ts +54 -0
  194. package/dist/xllm/runtime/step_renderer.d.ts.map +1 -0
  195. package/dist/xllm/runtime/task_model.d.ts +64 -0
  196. package/dist/xllm/runtime/task_model.d.ts.map +1 -0
  197. package/dist/xllm/runtime/tool_result.d.ts +39 -0
  198. package/dist/xllm/runtime/tool_result.d.ts.map +1 -0
  199. package/dist/xllm/runtime/types.d.ts +99 -0
  200. package/dist/xllm/runtime/types.d.ts.map +1 -0
  201. package/dist/xllm.cjs +2 -0
  202. package/dist/xllm.cjs.map +1 -0
  203. package/dist/xllm.mjs +1167 -0
  204. package/dist/xllm.mjs.map +1 -0
  205. package/dist/xllm_deno.cjs +2 -0
  206. package/dist/xllm_deno.cjs.map +1 -0
  207. package/dist/xllm_deno.mjs +2487 -0
  208. package/dist/xllm_deno.mjs.map +1 -0
  209. package/dist/xllm_dev.cjs +2 -0
  210. package/dist/xllm_dev.cjs.map +1 -0
  211. package/dist/xllm_dev.mjs +70 -0
  212. package/dist/xllm_dev.mjs.map +1 -0
  213. package/package.json +22 -1
  214. package/src/internal/command_args.ts +268 -0
  215. package/dist/executor_client-1ee523cf.js +0 -13
  216. package/dist/executor_client-1ee523cf.js.map +0 -1
  217. package/dist/executor_client-5f4d0468.mjs.map +0 -1
  218. package/dist/ndn_types-8c2696d5.js +0 -2
  219. package/dist/ndn_types-8c2696d5.js.map +0 -1
  220. package/dist/ndn_types-ab30fac0.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"xllm.mjs","sources":["../src/xllm/runtime/site.ts","../src/internal/command_args.ts","../src/xllm/runtime/site_tools.ts","../src/xllm/runtime/did_object_resources.ts","../src/xllm/hosts/browser/store.ts"],"sourcesContent":["// `createSiteRuntime`: a page turns the tools of one scene into an\n// AgentRuntime. The SDK ships no tools here; what the scene can do is the\n// page's own JS functions, so xllm never exceeds what the page's JS can do.\n//\n// descriptor: { kind: \"site\", runtime_id: \"site:<scene>\", host: null,\n// target: { origin, scene }, workdir: \"/\", capabilities: { tools: {}, network: true, os: \"browser\" } }\n// Neither the user agent nor the tool list is part of it: a browser update or\n// a new page tool must not make old runs unresumable, while a run of scene A\n// cannot be resumed in scene B (the descriptors differ).\n\nimport type { AiToolCall, EffectiveTools, ResolvedTool, RuntimeConfig, RuntimeDescriptor, RuntimeInfo, ToolSource, ToolsConfig } from '../core/types'\nimport { XllmError } from '../core/errors'\nimport { describeToolSource, shellSettings, taskWaitMs } from '../core/config'\nimport type { AgentRuntime, OpenedTools, RunBinding, RuntimeOpenCtx, SiteTool } from './types'\nimport { unresolvedReason } from './types'\nimport { SiteToolManager } from './site_manager'\n\nexport const SITE_RUNTIME_KIND = 'site'\n\nconst TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/\n\nexport interface SiteRuntimeOptions {\n /** The scene name, e.g. `aiws.wish`: part of the runtime's identity. */\n scene: string\n /** The page's origin (passed in: the runtime never reads `location`). */\n origin: string\n hostname: string\n /** Every tool of this scene. */\n tools: Record<string, SiteTool>\n /** What `{{env.NAME}}` may read. */\n env?: Record<string, string>\n /** `runtime.task_wait_ms` (in-call wait budget for tasks, M2). */\n task_wait_ms?: number\n}\n\nexport interface SiteRuntime extends AgentRuntime {\n readonly scene: string\n /** The scene's tools, by name. */\n readonly tools: ReadonlyMap<string, SiteTool>\n}\n\nfunction resolveTool(name: string, tool: SiteTool, source: string): ResolvedTool {\n return { name, description: tool.spec.description, args_schema: tool.spec.args_schema, source }\n}\n\nfunction namedSources(cfg: ToolSource[] | undefined, field: string): string[] {\n return (cfg ?? []).map(s => {\n if (s.kind !== 'named') {\n throw XllmError.capability(`${field}: \\`${describeToolSource(s)}\\` is not available in a site runtime; only the page's tools can be named`)\n }\n return s.name\n })\n}\n\nexport function createSiteRuntime(options: SiteRuntimeOptions): SiteRuntime {\n const scene = options.scene?.trim()\n if (!scene) throw XllmError.input('createSiteRuntime: `scene` is required')\n if (!options.origin) throw XllmError.input('createSiteRuntime: `origin` is required')\n const tools = new Map<string, SiteTool>()\n for (const [name, tool] of Object.entries(options.tools ?? {})) {\n if (!TOOL_NAME.test(name)) throw XllmError.tools(`site tool name \\`${name}\\` must match ${TOOL_NAME}`)\n if (!tool || typeof tool.call !== 'function' || !tool.spec) throw XllmError.tools(`site tool \\`${name}\\` needs \\`spec\\` and \\`call\\``)\n tools.set(name, tool)\n }\n const env = { ...(options.env ?? {}) }\n const descriptor: RuntimeDescriptor = {\n runtime_id: `site:${scene}`,\n kind: SITE_RUNTIME_KIND,\n host: null,\n target: { origin: options.origin, scene },\n workdir: '/',\n capabilities: { tools: {}, network: true, os: 'browser' },\n }\n const config: RuntimeConfig = { kind: SITE_RUNTIME_KIND, env: {} }\n if (options.task_wait_ms !== undefined) config.task_wait_ms = options.task_wait_ms\n\n const runtime: SiteRuntime = {\n scene,\n tools,\n descriptor: () => JSON.parse(JSON.stringify(descriptor)),\n config: () => JSON.parse(JSON.stringify(config)),\n async info(): Promise<RuntimeInfo> {\n let timezone = ''\n try {\n timezone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? ''\n } catch {\n timezone = ''\n }\n return {\n id: descriptor.runtime_id, kind: SITE_RUNTIME_KIND, os: 'browser', arch: '', hostname: options.hostname, shell: '',\n cwd: '/', tools: [], current_time: new Date().toISOString(), timezone, target: descriptor.target,\n platform: 'browser', shell_kind: '', baseline: '',\n }\n },\n async open(ctx: RuntimeOpenCtx, cfg: ToolsConfig): Promise<OpenedTools> {\n const enabled = cfg.enabled ?? false\n const tools2actions = cfg.tools2actions ?? false\n if (ctx.loop_model === 'function_call' && (tools2actions || (cfg.actions ?? []).length > 0)) {\n throw XllmError.capability('actions / tools2actions need loop_model behavior')\n }\n const pick = (names: string[], field: string): ResolvedTool[] => names.map(name => {\n const tool = tools.get(name)\n if (!tool) {\n throw XllmError.capability(`${field}: \\`${name}\\` is not a tool of scene \\`${scene}\\` (scene tools: ${[...tools.keys()].join(', ') || 'none'})`)\n }\n return resolveTool(name, tool, `name:${name}`)\n })\n let native: ResolvedTool[] = []\n let actions: ResolvedTool[] = []\n const toolSources = cfg.tools ?? []\n const actionSources = cfg.actions ?? []\n if (enabled) {\n const toolNames = cfg.tools === undefined ? [...tools.keys()] : namedSources(cfg.tools, 'tools.tools')\n native = pick(toolNames, 'tools.tools')\n actions = pick(namedSources(cfg.actions, 'tools.actions'), 'tools.actions')\n if (tools2actions) {\n actions = [...actions, ...native.filter(t => !actions.some(a => a.name === t.name))]\n native = []\n }\n }\n const selected = new Map<string, SiteTool>()\n for (const t of [...native, ...actions]) selected.set(t.name, tools.get(t.name) as SiteTool)\n const effective: EffectiveTools = {\n enabled,\n filesystem_policy: cfg.filesystem_policy ?? 'workspace',\n tools2actions,\n tool_sources: cfg.tools === undefined && enabled ? native.map(t => ({ kind: 'named', name: t.name })) : toolSources,\n action_sources: actionSources,\n native,\n actions,\n bash_tools: [],\n shell: shellSettings(cfg.shell, taskWaitMs(config)),\n exec_enabled: false,\n sources: { ...ctx.sources },\n }\n return { tools: effective, manager: new SiteToolManager(selected, { tasks: ctx.tasks, taskWaitMs: ctx.task_wait_ms }) }\n },\n async describeInterrupted(run: RunBinding, call: AiToolCall): Promise<string> {\n const tool = tools.get(call.name)\n if (tool?.describeInterrupted) {\n try {\n return await tool.describeInterrupted(call.args ?? {}, { run_id: run.run_id, call_id: call.call_id, signal: new AbortController().signal })\n } catch (e) {\n return `${unresolvedReason(call.name)} (describing it failed: ${e instanceof Error ? e.message : String(e)})`\n }\n }\n return unresolvedReason(call.name)\n },\n env: (name: string) => env[name],\n }\n return runtime\n}\n","// Command-line parsing shared by the `buckyos` CLI (`cli/core/argv.ts`,\n// `cli/core/command.ts`) and the xllm site tools' `exec`. Self-contained on\n// purpose: the CLI imports it by relative path. Errors carry the CLI's usage\n// codes; the CLI turns them into its `UsageError`.\n\nexport type JsonSchema = {\n type?: 'object' | 'array' | 'string' | 'boolean' | 'integer' | 'number' | 'null'\n title?: string\n description?: string\n properties?: Record<string, JsonSchema>\n required?: string[]\n additionalProperties?: boolean\n items?: JsonSchema\n enum?: unknown[]\n minLength?: number\n minimum?: number\n default?: unknown\n secret?: boolean\n}\n\nexport interface PositionalDefinition {\n name: string\n description: string\n required?: boolean\n}\n\nexport interface OptionDefinition {\n name: string\n property?: string\n description: string\n type: 'string' | 'boolean' | 'integer' | 'number'\n required?: boolean\n secret?: boolean\n enum?: string[]\n}\n\nexport type AccessLevel = 'read' | 'write' | 'destructive' | 'privileged'\n\n/** A usage error with the CLI's code (`UNKNOWN_OPTION`, `SCHEMA_VALIDATION_FAILED`, …). */\nexport class CommandArgsError extends Error {\n readonly code: string\n\n constructor(code: string, message: string) {\n super(message)\n this.name = 'CommandArgsError'\n this.code = code\n }\n}\n\nfunction hasOwn(o: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(o, key)\n}\n\nexport function optionProperty(option: OptionDefinition): string {\n return option.property ?? option.name.split('-').join('_')\n}\n\nexport interface LongOption {\n name: string\n inlineValue?: string\n}\n\nexport function splitLongOption(token: string): LongOption {\n const content = token.slice(2)\n const equalIndex = content.indexOf('=')\n return equalIndex < 0 ? { name: content } : { name: content.slice(0, equalIndex), inlineValue: content.slice(equalIndex + 1) }\n}\n\nexport function readOptionValue(argv: string[], index: number, option: LongOption): { value: string; consumed: number } {\n if (option.inlineValue !== undefined) {\n if (!option.inlineValue) throw new CommandArgsError('MISSING_ARGUMENT', `--${option.name} requires a value`)\n return { value: option.inlineValue, consumed: 1 }\n }\n const value = argv[index + 1]\n if (value === undefined || value.startsWith('--')) throw new CommandArgsError('MISSING_ARGUMENT', `--${option.name} requires a value`)\n return { value, consumed: 2 }\n}\n\nfunction parseOptionValue(type: string, value: string, name: string): unknown {\n if (type === 'string') return value\n const number = Number(value)\n if (!Number.isFinite(number) || (type === 'integer' && !Number.isInteger(number))) {\n throw new CommandArgsError('INVALID_ARGUMENT', `--${name} requires a ${type}`)\n }\n return number\n}\n\nfunction assignPositional(input: Record<string, unknown>, positionals: PositionalDefinition[], index: number, value: string): number {\n const positional = positionals[index]\n if (!positional) throw new CommandArgsError('TOO_MANY_ARGUMENTS', `unexpected positional argument: ${value}`)\n input[positional.name] = value\n return index + 1\n}\n\nexport interface ArgvSpec {\n positionals?: PositionalDefinition[]\n options?: OptionDefinition[]\n}\n\n/**\n * Looks at every long option before the command's own: the CLI handles its\n * interactive session options here. Return how many tokens it consumed, or\n * `undefined` to leave the option to the command.\n */\nexport type LongOptionHook = (option: LongOption, argv: string[], index: number) => number | undefined\n\n/** Positionals, `--opt value` / `--opt=value`, boolean options, `--`; `--help` / `-h` sets `help`. */\nexport function parseArgv(spec: ArgvSpec, argv: string[], beforeOption?: LongOptionHook): {\n input: Record<string, unknown>\n help: boolean\n positionalCount: number\n} {\n const input: Record<string, unknown> = {}\n const positionals = spec.positionals ?? []\n const optionByName = new Map((spec.options ?? []).map(o => [o.name, o]))\n let positionalIndex = 0\n let help = false\n for (let index = 0; index < argv.length;) {\n const token = argv[index]\n if (token === '--help' || token === '-h') {\n help = true\n index += 1\n continue\n }\n if (token === '--') {\n for (const value of argv.slice(index + 1)) positionalIndex = assignPositional(input, positionals, positionalIndex, value)\n break\n }\n if (!token.startsWith('--')) {\n positionalIndex = assignPositional(input, positionals, positionalIndex, token)\n index += 1\n continue\n }\n const parsed = splitLongOption(token)\n const handled = beforeOption?.(parsed, argv, index)\n if (handled !== undefined) {\n index += handled\n continue\n }\n const option = optionByName.get(parsed.name)\n if (!option) throw new CommandArgsError('UNKNOWN_OPTION', `unknown option: --${parsed.name}`)\n const property = optionProperty(option)\n if (hasOwn(input, property)) throw new CommandArgsError('DUPLICATE_ARGUMENT', `argument provided more than once: ${property}`)\n if (option.type === 'boolean') {\n if (parsed.inlineValue !== undefined) throw new CommandArgsError('INVALID_ARGUMENT', `--${parsed.name} does not accept a value`)\n input[property] = true\n index += 1\n continue\n }\n const { value, consumed } = readOptionValue(argv, index, parsed)\n input[property] = parseOptionValue(option.type, value, parsed.name)\n index += consumed\n }\n return { input, help, positionalCount: positionalIndex }\n}\n\n/** Required positionals after `positionalCount` must be in `inputObject`. */\nexport function checkRequiredPositionals(positionals: PositionalDefinition[], positionalCount: number, inputObject: Record<string, unknown> | undefined) {\n for (let index = positionalCount; index < positionals.length; index++) {\n if (positionals[index].required !== false && !hasOwn(inputObject ?? {}, positionals[index].name)) {\n throw new CommandArgsError('MISSING_ARGUMENT', `missing positional argument: ${positionals[index].name}`)\n }\n }\n}\n\nexport function mergeCommandInput(inputObject: Record<string, unknown> | undefined, cliInput: Record<string, unknown>): Record<string, unknown> {\n const result = { ...(inputObject ?? {}) }\n for (const [key, value] of Object.entries(cliInput)) {\n if (hasOwn(result, key)) throw new CommandArgsError('ARGUMENT_CONFLICT', `${key} is present in both --input and argv`)\n result[key] = value\n }\n return result\n}\n\n/** Split a command line into words: single and double quotes, backslash escapes (not inside single quotes). */\nexport function parseShellLine(line: string): string[] {\n const tokens: string[] = []\n let current = ''\n let quote: 'single' | 'double' | null = null\n let escaped = false\n let started = false\n for (const character of line) {\n if (escaped) {\n current += character\n escaped = false\n started = true\n continue\n }\n if (character === '\\\\' && quote !== 'single') {\n escaped = true\n started = true\n continue\n }\n if (quote === 'single') {\n if (character === \"'\") quote = null\n else current += character\n continue\n }\n if (quote === 'double') {\n if (character === '\"') quote = null\n else current += character\n continue\n }\n if (character === \"'\") {\n quote = 'single'\n started = true\n continue\n }\n if (character === '\"') {\n quote = 'double'\n started = true\n continue\n }\n if (/\\s/.test(character)) {\n if (started) {\n tokens.push(current)\n current = ''\n started = false\n }\n continue\n }\n current += character\n started = true\n }\n if (escaped) throw new CommandArgsError('INVALID_COMMAND_LINE', 'unfinished escape sequence')\n if (quote) throw new CommandArgsError('INVALID_COMMAND_LINE', `unterminated ${quote} quote`)\n if (started) tokens.push(current)\n return tokens\n}\n\nexport function validateSchema(value: unknown, schema: JsonSchema, path: string): void {\n if (schema.enum && !schema.enum.some(candidate => Object.is(candidate, value))) {\n throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be one of ${schema.enum.join(', ')}`)\n }\n if (schema.type === 'object') {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be an object`)\n const object = value as Record<string, unknown>\n for (const required of schema.required ?? []) {\n if (!hasOwn(object, required)) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path}.${required} is required`)\n }\n if (schema.additionalProperties === false) {\n for (const key of Object.keys(object)) {\n if (!hasOwn(schema.properties ?? {}, key)) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path}.${key} is not allowed`)\n }\n }\n for (const [key, propertyValue] of Object.entries(object)) {\n const propertySchema = schema.properties?.[key]\n if (propertySchema) validateSchema(propertyValue, propertySchema, `${path}.${key}`)\n }\n return\n }\n if (schema.type === 'array') {\n if (!Array.isArray(value)) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be an array`)\n const items = schema.items\n if (items) value.forEach((item, index) => validateSchema(item, items, `${path}[${index}]`))\n return\n }\n if (schema.type === 'string') {\n if (typeof value !== 'string') throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be a string`)\n if (schema.minLength !== undefined && value.length < schema.minLength) throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} is too short`)\n return\n }\n if (schema.type === 'boolean' && typeof value !== 'boolean') throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be a boolean`)\n if (schema.type === 'integer' && (!Number.isInteger(value) || typeof value !== 'number')) {\n throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be an integer`)\n }\n if (schema.type === 'number' && typeof value !== 'number') throw new CommandArgsError('SCHEMA_VALIDATION_FAILED', `${path} must be a number`)\n}\n","// Optional basic tools for a site (TODO §2.1, a trial): what `bash_core`'s four\n// tools are for files, `read` / `write` / `edit` / `exec` are for a page's\n// resources and commands. REST semantics: read = GET (a collection's read is\n// its list, filter with a query), write = PUT, edit = PATCH; everything REST\n// cannot say is a command run by `exec` — `xcall <object> <action>` for the\n// actions declared on resources (DID Object style, with `risk`), and the\n// page's own commands. The four specs are fixed: more resources and commands\n// cost no tokens per round. Every resource, action and command is declared by\n// the page; nothing is forwarded to `fetch` or turned into a raw RPC.\n\nimport type { JsonValue } from '../core/types'\nimport { isObject } from '../core/json'\nimport { validateJson } from '../core/json_check'\nimport { utf8Length } from '../core/tokenizer'\nimport type { SiteTool, SiteToolCtx } from './types'\nimport {\n CommandArgsError, parseArgv, parseShellLine, validateSchema,\n} from '../../internal/command_args'\nimport type { AccessLevel, JsonSchema, OptionDefinition, PositionalDefinition } from '../../internal/command_args'\n\nexport type ActionRisk = 'read_only' | 'idempotent_write' | 'write' | 'destructive' | 'admin'\nexport const ACTION_RISKS: ActionRisk[] = ['read_only', 'idempotent_write', 'write', 'destructive', 'admin']\n\nexport const XCALL_USAGE = 'xcall <object> <action> [--params <json>] [key=value ...] [--key=value ...]'\n/** Result text cap of `read` (one page) and `exec`. */\nexport const MAX_RESULT_BYTES = 64 * 1024\n\n/** What a resource method gets: the URI as normalized, the `{name}` parameters, the query. */\nexport interface ResourceMatch {\n uri: string\n pattern: string\n params: Record<string, string>\n query: URLSearchParams\n ctx: SiteToolCtx\n}\n\n/** A read may return a version: `write` (and the default `edit`) gets it back as `ifVersion`. */\nexport interface Versioned {\n content: unknown\n version?: string\n}\n\nexport interface WriteBody {\n content: string\n mode: 'write' | 'new' | 'append'\n ifVersion?: string\n}\n\nexport interface ActionDecl {\n description: string\n risk: ActionRisk\n /** JSON Schema of the params. */\n input?: JsonValue\n call(m: ResourceMatch, params: Record<string, JsonValue>): unknown\n}\n\nexport interface ResourceDecl {\n description: string\n read?(m: ResourceMatch): unknown\n write?(m: ResourceMatch, body: WriteBody): unknown\n edit?(m: ResourceMatch, body: { old_string: string; new_string: string }): unknown\n actions?: Record<string, ActionDecl>\n}\n\n/** A page command: a subset of the CLI `CommandDefinition`; `call(input)` replaces its handler. */\nexport interface CommandDecl {\n summary: string\n description?: string\n positionals?: PositionalDefinition[]\n options?: OptionDefinition[]\n inputSchema?: JsonSchema\n access?: { mode: 'fixed'; level: AccessLevel }\n examples?: string[]\n call(input: Record<string, unknown>, ctx: SiteToolCtx): unknown\n}\n\nexport interface SiteToolsOptions {\n resources?: Record<string, ResourceDecl>\n commands?: Record<string, CommandDecl>\n}\n\nconst LOCAL_BASE = 'site://page/'\nconst SHELL_CHARS = /[|;&><`$]/\n\ninterface Pattern {\n raw: string\n origin?: string\n segments: string[]\n decl: ResourceDecl\n}\n\nfunction parsePattern(raw: string, decl: ResourceDecl): Pattern {\n const i = raw.indexOf('://')\n if (i >= 0) {\n const rest = raw.slice(i + 3)\n const slash = rest.indexOf('/')\n const host = slash < 0 ? rest : rest.slice(0, slash)\n const path = slash < 0 ? '' : rest.slice(slash + 1)\n return { raw, origin: `${raw.slice(0, i).toLowerCase()}://${host.toLowerCase()}`, segments: path ? path.split('/') : [], decl }\n }\n const path = raw.replace(/^\\/+/, '').replace(/\\/+$/, '')\n return { raw, segments: path ? path.split('/') : [], decl }\n}\n\nfunction fail(message: string): never {\n throw new Error(message)\n}\n\n/** Normalize a URI the model gave: relative paths and declared absolute origins only, no `..`, no encoded separators. */\nexport function normalizeUri(uri: string, origins: Set<string>): { origin?: string; segments: string[]; query: URLSearchParams; text: string } {\n const raw = uri.trim()\n if (!raw) fail('uri is empty')\n const absolute = /^[A-Za-z][A-Za-z0-9+.-]*:/.test(raw)\n let url: URL\n try {\n url = absolute ? new URL(raw) : new URL(raw.replace(/^\\/+/, ''), LOCAL_BASE)\n } catch {\n fail(`invalid uri \\`${raw}\\``)\n }\n let origin: string | undefined\n if (absolute) {\n origin = `${url.protocol.slice(0, -1).toLowerCase()}://${url.host.toLowerCase()}`\n if (!origins.has(origin)) fail(`uri \\`${raw}\\` is not a resource of this page (absolute URIs are limited to the declared ones)`)\n } else if (url.protocol !== 'site:' || url.host !== 'page') {\n fail(`uri \\`${raw}\\` is not a resource of this page`)\n }\n const segments: string[] = []\n for (const part of url.pathname.split('/')) {\n if (part === '') continue\n let decoded: string\n try {\n decoded = decodeURIComponent(part)\n } catch {\n fail(`invalid uri \\`${raw}\\``)\n }\n if (decoded === '..' || decoded === '.' || decoded.includes('/') || decoded.includes('\\\\')) fail(`uri \\`${raw}\\` is not a resource of this page`)\n segments.push(decoded)\n }\n const text = (origin ? `${origin}/` : '') + segments.join('/') + (url.search || '')\n return { origin, segments, query: url.searchParams, text }\n}\n\nfunction matchPattern(p: Pattern, origin: string | undefined, segments: string[]): Record<string, string> | undefined {\n if (p.origin !== origin || p.segments.length !== segments.length) return undefined\n const params: Record<string, string> = {}\n for (let i = 0; i < segments.length; i++) {\n const s = p.segments[i]\n if (s.startsWith('{') && s.endsWith('}')) params[s.slice(1, -1)] = segments[i]\n else if (s !== segments[i]) return undefined\n }\n return params\n}\n\nfunction asText(value: unknown): string {\n if (value === undefined || value === null) return ''\n if (typeof value === 'string') return value\n try {\n return JSON.stringify(value, null, 2)\n } catch {\n return String(value)\n }\n}\n\nfunction versioned(value: unknown): { text: string; version?: string } {\n if (isObject(value) && 'content' in value && Object.keys(value).every(k => k === 'content' || k === 'version')) {\n const version = value.version\n return { text: asText(value.content), version: typeof version === 'string' ? version : version === undefined ? undefined : String(version) }\n }\n return { text: asText(value) }\n}\n\nfunction clipBytes(text: string, max: number): { text: string; clipped: boolean } {\n if (utf8Length(text) <= max) return { text, clipped: false }\n let out = ''\n let bytes = 0\n for (const ch of text) {\n const n = utf8Length(ch)\n if (bytes + n > max) break\n out += ch\n bytes += n\n }\n return { text: out, clipped: true }\n}\n\n/** One page of a text by lines: `offset` is the 1-based first line. */\nexport function pageText(text: string, offset = 1, limit?: number): string {\n const lines = text.split('\\n')\n const start = Math.max(1, Math.floor(offset))\n if (start > lines.length && !(start === 1 && lines.length === 1)) return `[offset ${start} is past the end: ${lines.length} lines]`\n const wanted = limit === undefined ? lines.length : Math.max(1, Math.floor(limit))\n const out: string[] = []\n let bytes = 0\n let i = start - 1\n for (; i < lines.length && out.length < wanted; i++) {\n const n = utf8Length(lines[i]) + 1\n if (out.length > 0 && bytes + n > MAX_RESULT_BYTES) break\n out.push(lines[i])\n bytes += n\n }\n let body = out.join('\\n')\n if (out.length === 1 && utf8Length(body) > MAX_RESULT_BYTES) body = clipBytes(body, MAX_RESULT_BYTES).text + ' …'\n if (i < lines.length) body += `\\n[lines ${start}–${i} of ${lines.length}; read on with offset=${i + 1}]`\n return body\n}\n\nfunction parseScalar(raw: string): JsonValue {\n const v = raw.trim()\n if (v === 'true') return true\n if (v === 'false') return false\n if (v === 'null') return null\n if (/^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(v)) return Number(v)\n if (v.startsWith('{') || v.startsWith('[')) {\n try {\n return JSON.parse(v)\n } catch {\n return v\n }\n }\n return v\n}\n\nconst UNSUPPORTED_XCALL_KEYS = ['config', 'route-config', 'session-id', 'session_id', 'idempotency-key', 'idempotency_key',\n 'confirm-token', 'confirm_token', 'trace-id', 'trace_id']\n\n/** `xcall` arguments as Rust parses them (`parse_object_x_call_cli_command`), minus routing and confirmation flags. */\nfunction parseXcall(tokens: string[]): { object: string; action: string; params: Record<string, JsonValue> } {\n let object: string | undefined\n let action: string | undefined\n let params: JsonValue = {}\n const pairs: Record<string, JsonValue> = {}\n const positionals: string[] = []\n const json = (raw: string, name: string): JsonValue => {\n try {\n return JSON.parse(raw)\n } catch (e) {\n fail(`invalid \\`${name}\\` JSON value \\`${raw}\\`: ${e instanceof Error ? e.message : String(e)}\\nusage: ${XCALL_USAGE}`)\n }\n }\n const unsupported = (t: string): never => fail(`unsupported flag \\`${t}\\` (routing and confirmation are the page's)\\nusage: ${XCALL_USAGE}`)\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i]\n if (t === '--params') {\n const v = tokens[++i]\n if (v === undefined) fail(`missing value for --params\\nusage: ${XCALL_USAGE}`)\n params = json(v, '--params')\n } else if (t.startsWith('--')) {\n const eq = t.indexOf('=')\n if (eq < 0) unsupported(t)\n const key = t.slice(2, eq)\n const value = t.slice(eq + 1)\n if (key === 'params') params = json(value, '--params')\n else if (!key.trim() || key.startsWith('-') || UNSUPPORTED_XCALL_KEYS.includes(key)) unsupported(t)\n else pairs[key] = parseScalar(value)\n } else if (t.includes('=')) {\n const eq = t.indexOf('=')\n const key = t.slice(0, eq)\n const value = t.slice(eq + 1)\n if (key === 'object') object = value\n else if (key === 'action') action = value\n else if (key === 'params') params = json(value, 'params')\n else if (UNSUPPORTED_XCALL_KEYS.includes(key)) unsupported(t)\n else pairs[key] = parseScalar(value)\n } else {\n positionals.push(t)\n }\n }\n object = object ?? positionals[0]\n action = action ?? positionals[1]\n if (positionals[2] !== undefined) params = json(positionals[2], 'params')\n if (positionals.length > 3) fail(`unexpected positional argument \\`${positionals[3]}\\`\\nusage: ${XCALL_USAGE}`)\n if (Object.keys(pairs).length) {\n if (!isObject(params)) fail(`key=value params require object params\\nusage: ${XCALL_USAGE}`)\n params = { ...params, ...pairs }\n }\n if (!object || !action) fail(`xcall needs an object and an action\\nusage: ${XCALL_USAGE}`)\n if (!isObject(params)) fail(`params must be a JSON object\\nusage: ${XCALL_USAGE}`)\n return { object, action, params }\n}\n\nfunction commandUsage(name: string, c: CommandDecl): string {\n const lines = [`${name} — ${c.summary}`]\n if (c.description) lines.push('', c.description)\n const pos = (c.positionals ?? []).map(p => (p.required === false ? `[${p.name}]` : `<${p.name}>`)).join(' ')\n lines.push('', `usage: ${name}${pos ? ` ${pos}` : ''}${(c.options ?? []).length ? ' [options]' : ''}`)\n for (const p of c.positionals ?? []) lines.push(` ${p.name} ${p.description}`)\n if ((c.options ?? []).length) lines.push('options:')\n for (const o of c.options ?? []) {\n lines.push(` --${o.name}${o.type === 'boolean' ? '' : ` <${o.type}>`}${o.required ? ' (required)' : ''} ${o.description}${o.enum ? ` (${o.enum.join(' | ')})` : ''}`)\n }\n if (c.examples?.length) {\n lines.push('examples:')\n for (const e of c.examples) lines.push(` ${e}`)\n }\n return lines.join('\\n')\n}\n\nconst OBJECT_ARGS = (props: Record<string, JsonValue>, required: string[]): JsonValue => ({ type: 'object', properties: props, required })\n\n/**\n * The four basic tools over the page's resources and commands. Spread them\n * into `createSiteRuntime({ tools })`, alongside named tools if wanted.\n */\nexport function siteTools(options: SiteToolsOptions): Record<string, SiteTool> {\n const patterns = Object.entries(options.resources ?? {}).map(([raw, decl]) => parsePattern(raw, decl))\n const origins = new Set(patterns.map(p => p.origin).filter((o): o is string => o !== undefined))\n const commands = new Map(Object.entries(options.commands ?? {}))\n if (commands.has('xcall')) throw new Error('siteTools: `xcall` is built in; declare actions on resources instead')\n\n const resolve = (uri: string, ctx: SiteToolCtx): ResourceMatch & { decl: ResourceDecl } => {\n const n = normalizeUri(uri, origins)\n for (const p of patterns) {\n const params = matchPattern(p, n.origin, n.segments)\n if (params) return { uri: n.text, pattern: p.raw, params, query: n.query, ctx, decl: p.decl }\n }\n fail(`uri \\`${uri}\\` is not a resource of this page; read uri=\"/\" lists them`)\n }\n\n const discovery = (): string => {\n const lines = ['Resources (read uri=\"<resource>\"; {name} is one path segment):']\n for (const p of patterns) {\n const methods = (['read', 'write', 'edit'] as const).filter(m => m === 'edit' ? !!(p.decl.edit || (p.decl.read && p.decl.write)) : !!p.decl[m])\n lines.push(`- ${p.raw} — ${p.decl.description} [${methods.join(', ') || 'no methods'}]`)\n for (const [name, a] of Object.entries(p.decl.actions ?? {})) lines.push(` action ${name} (risk: ${a.risk}) — ${a.description}`)\n }\n if (patterns.length === 0) lines.push('(none)')\n lines.push('', 'Commands (exec \"<command> --help\" for usage):')\n lines.push(`- xcall — call an action of a resource: ${XCALL_USAGE}`)\n for (const [name, c] of commands) lines.push(`- ${name} — ${c.summary}`)\n return lines.join('\\n')\n }\n\n const exec = async (command: string, ctx: SiteToolCtx): Promise<string> => {\n const words = (() => {\n try {\n return parseShellLine(command)\n } catch (e) {\n fail(`${e instanceof Error ? e.message : String(e)}; exec runs one command, it is not a shell`)\n }\n })()\n const available = `available commands: xcall${commands.size ? `, ${[...commands.keys()].join(', ')}` : ''}`\n const unquoted = command.replace(/'[^']*'|\"(?:[^\"\\\\]|\\\\.)*\"/g, '')\n if (SHELL_CHARS.test(unquoted)) {\n fail(`exec runs exactly one command and is not a shell: pipes, redirects, \\`;\\`, \\`&\\`, backquotes and \\`$\\` are not supported (quote them to pass them as text). ${available}`)\n }\n const [name, ...args] = words\n if (!name) fail(`empty command; ${available}`)\n if (name === 'xcall') {\n if (args.includes('--help') || args.includes('-h')) return `usage: ${XCALL_USAGE}\\nThe actions of each resource are listed by read uri=\"/\".`\n const { object, action, params } = parseXcall(args)\n const m = resolve(object, ctx)\n const decl = m.decl.actions?.[action]\n if (!decl) {\n const known = Object.keys(m.decl.actions ?? {})\n fail(`resource \\`${m.pattern}\\` has no action \\`${action}\\` (actions: ${known.length ? known.join(', ') : 'none'})`)\n }\n if (decl.input !== undefined) {\n const invalid = validateJson(decl.input, params)\n if (invalid) fail(`invalid params for ${action}: ${invalid}`)\n }\n const { decl: _decl, ...match } = m\n void _decl\n const result = await decl.call(match, params)\n return `[risk: ${decl.risk}]\\n${clipBytes(asText(result) || 'ok', MAX_RESULT_BYTES).text}`\n }\n const c = commands.get(name)\n if (!c) fail(`unknown command \\`${name}\\`; exec runs one command, it is not a shell. ${available}`)\n let input: Record<string, unknown>\n try {\n const parsed = parseArgv({ positionals: c.positionals, options: c.options }, args)\n if (parsed.help) return commandUsage(name, c)\n for (let i = parsed.positionalCount; i < (c.positionals ?? []).length; i++) {\n if ((c.positionals ?? [])[i].required !== false) throw new CommandArgsError('MISSING_ARGUMENT', `missing positional argument: ${(c.positionals ?? [])[i].name}`)\n }\n for (const o of c.options ?? []) {\n const prop = o.property ?? o.name.split('-').join('_')\n if (o.required && !(prop in parsed.input)) throw new CommandArgsError('MISSING_ARGUMENT', `--${o.name} is required`)\n }\n input = parsed.input\n if (c.inputSchema) validateSchema(input, c.inputSchema, 'input')\n } catch (e) {\n if (e instanceof CommandArgsError) fail(`${name}: ${e.message}\\n\\n${commandUsage(name, c)}`)\n throw e\n }\n return clipBytes(asText(await c.call(input, ctx)) || 'ok', MAX_RESULT_BYTES).text\n }\n\n const readRaw = async (m: ResourceMatch & { decl: ResourceDecl }) => {\n if (!m.decl.read) fail(`resource \\`${m.pattern}\\` cannot be read`)\n const { decl: _d, ...match } = m\n void _d\n return versioned(await m.decl.read(match))\n }\n\n return {\n read: {\n spec: {\n description: 'Read a resource of this page by URI (GET). Start with uri \"/\": it lists the resources, their actions (with risk) and the commands. A collection\\'s read is its list; filter and page with a query (notes?tag=x). Text comes in pages of lines: offset is the first line (1-based), limit the number of lines.',\n args_schema: OBJECT_ARGS({\n uri: { type: 'string', description: 'Resource URI, e.g. \"/\" or \"notes/1\"' },\n offset: { type: 'integer', description: 'First line, 1-based' },\n limit: { type: 'integer', description: 'Number of lines' },\n }, ['uri']),\n },\n idempotent: true,\n async call(args, ctx) {\n const uri = String(args.uri)\n const offset = typeof args.offset === 'number' ? args.offset : undefined\n const limit = typeof args.limit === 'number' ? args.limit : undefined\n if (uri.trim() === '/' || uri.trim() === '') return pageText(discovery(), offset, limit)\n const r = await readRaw(resolve(uri, ctx))\n return pageText(r.text, offset, limit)\n },\n },\n write: {\n spec: {\n description: 'Write a resource\\'s content (PUT). mode: \"write\" (default) replaces it, \"new\" only creates it and fails if it exists, \"append\" adds to its end. Use edit to change part of it.',\n args_schema: OBJECT_ARGS({\n uri: { type: 'string', description: 'Resource URI' },\n content: { type: 'string', description: 'The content' },\n mode: { type: 'string', enum: ['write', 'new', 'append'], description: 'write | new | append' },\n }, ['uri', 'content']),\n },\n async call(args, ctx) {\n const m = resolve(String(args.uri), ctx)\n if (!m.decl.write) fail(`resource \\`${m.pattern}\\` is read-only`)\n const { decl, ...match } = m\n const mode = (typeof args.mode === 'string' ? args.mode : 'write') as WriteBody['mode']\n return asText(await decl.write!(match, { content: String(args.content), mode })) || 'written'\n },\n },\n edit: {\n spec: {\n description: 'Change part of a resource (PATCH): old_string must occur exactly once in its current content and is replaced by new_string.',\n args_schema: OBJECT_ARGS({\n uri: { type: 'string', description: 'Resource URI' },\n old_string: { type: 'string', description: 'Text to replace; must occur exactly once' },\n new_string: { type: 'string', description: 'Replacement text' },\n }, ['uri', 'old_string', 'new_string']),\n },\n async call(args, ctx) {\n const m = resolve(String(args.uri), ctx)\n const body = { old_string: String(args.old_string), new_string: String(args.new_string) }\n const { decl, ...match } = m\n if (decl.edit) return asText(await decl.edit(match, body)) || 'edited'\n if (!decl.read || !decl.write) fail(`resource \\`${m.pattern}\\` cannot be edited`)\n if (!body.old_string) fail('old_string is empty')\n const current = versioned(await decl.read(match))\n const count = current.text.split(body.old_string).length - 1\n if (count === 0) fail('old_string was not found in the current content; read it again')\n if (count > 1) fail(`old_string occurs ${count} times; give more context so it occurs exactly once`)\n const content = current.text.replace(body.old_string, () => body.new_string)\n const w: WriteBody = { content, mode: 'write' }\n if (current.version !== undefined) w.ifVersion = current.version\n return asText(await decl.write(match, w)) || 'edited'\n },\n },\n exec: {\n spec: {\n description: `Run one command (not a shell: no pipes, redirects, ;, &, backquotes or $). Built in: ${XCALL_USAGE} — calls an action listed by read uri=\"/\". The page's commands are listed there too; \"<command> --help\" shows a command's usage.`,\n args_schema: OBJECT_ARGS({ command: { type: 'string', description: 'One command line' } }, ['command']),\n },\n idempotent: (args: Record<string, JsonValue>) => execIsIdempotent(String(args.command ?? ''), patterns, origins, commands),\n call: (args, ctx) => exec(String(args.command), ctx),\n },\n }\n}\n\n/** Resume rule of `exec`: `xcall` re-runs `read_only` / `idempotent_write` actions, commands re-run at `access: read`. */\nfunction execIsIdempotent(command: string, patterns: Pattern[], origins: Set<string>, commands: Map<string, CommandDecl>): boolean {\n let words: string[]\n try {\n words = parseShellLine(command)\n } catch {\n return false\n }\n const [name, ...args] = words\n if (name === 'xcall') {\n try {\n const { object, action } = parseXcall(args)\n const n = normalizeUri(object, origins)\n const p = patterns.find(q => matchPattern(q, n.origin, n.segments))\n const risk = p?.decl.actions?.[action]?.risk\n return risk === 'read_only' || risk === 'idempotent_write'\n } catch {\n return false\n }\n }\n const c = name ? commands.get(name) : undefined\n return c?.access?.level === 'read'\n}\n\n","// `siteTools` resources from DID Objects a BuckyOS service already serves\n// (`KrpcObjectProvider`): for each root the page lists, its Profile decides\n// what the model can do — properties are read, an IndexTrait collection is\n// read with a query, actions become `xcall` actions with the Profile's\n// `x-buckyos:risk` (above `maxRisk` they are not exposed). What can be reached\n// is decided by the Profile and the roots, never by a URI the model gives.\n\nimport type { JsonValue } from '../core/types'\nimport { isObject } from '../core/json'\nimport type { DIDObjectClient } from '../../did_object_client'\nimport { ACTION_RISKS } from './site_tools'\nimport type { ActionDecl, ActionRisk, ResourceDecl, ResourceMatch } from './site_tools'\n\nexport const INDEX_TRAIT_URI = 'https://buckyos.org/traits/index@1'\n\n/** What `didObjectResources` needs of a DID Object client. */\nexport type DidObjectReader = Pick<DIDObjectClient, 'card' | 'profile' | 'readProperty' | 'invoke'>\n\nexport interface DidObjectResourcesOptions {\n client: DidObjectReader\n /** Object URLs (`obj://…`) the page lets the model reach. */\n roots: string[]\n /** Actions above this risk are not exposed (default `read_only`). */\n maxRisk?: ActionRisk\n}\n\nfunction text(v: JsonValue | undefined, key: string): string {\n return isObject(v) && typeof v[key] === 'string' ? (v[key] as string) : ''\n}\n\nfunction riskRank(r: string): number {\n const i = ACTION_RISKS.indexOf(r as ActionRisk)\n return i < 0 ? ACTION_RISKS.length : i\n}\n\n/** The object document a read shows (as `render_object_document` in agent-did-object-lib). */\nexport function renderObjectDocument(canonical: string, card: { id: string; alsoKnownAs?: string[] }, profile: JsonValue,\n summary: Record<string, JsonValue>): string {\n const lines = [`Object: ${canonical}`, `Object DID: ${card.id}`]\n const aliases = (card.alsoKnownAs ?? []).filter(a => a !== canonical)\n if (aliases.length) lines.push(`Also known as: ${aliases.join(', ')}`)\n for (const [label, key] of [['Title', 'title'], ['Description', 'description']]) {\n const v = text(profile, key)\n if (v) lines.push(`${label}: ${v}`)\n }\n for (const [section, key] of [['Properties', 'properties'], ['Actions', 'actions'], ['Events', 'events']]) {\n const entries = isObject(profile) ? profile[key] : undefined\n if (!isObject(entries) || Object.keys(entries).length === 0) continue\n lines.push(`${section}:`)\n for (const name of Object.keys(entries).sort()) {\n const e = entries[name]\n let line = `- ${name}`\n const d = text(e, 'description')\n if (d) line += `: ${d}`\n const risk = text(e, 'x-buckyos:risk')\n if (risk) line += ` (risk: ${risk})`\n lines.push(line)\n }\n }\n const names = Object.keys(summary)\n if (names.length) {\n lines.push('Summary:')\n for (const name of names) lines.push(`- ${name}:`, JSON.stringify(summary[name], null, 2))\n }\n return lines.join('\\n')\n}\n\nfunction isCollection(profile: JsonValue): boolean {\n const traits = isObject(profile) ? profile['x-buckyos:traits'] : undefined\n return Array.isArray(traits) && traits.includes(INDEX_TRAIT_URI)\n}\n\n/** Resources for `siteTools({ resources })` from the Profiles of `roots`. */\nexport async function didObjectResources(options: DidObjectResourcesOptions): Promise<Record<string, ResourceDecl>> {\n const maxRank = riskRank(options.maxRisk ?? 'read_only')\n const out: Record<string, ResourceDecl> = {}\n for (const root of options.roots) {\n const client = options.client\n const profile = await client.profile(root) as JsonValue\n const collection = isCollection(profile)\n const actions: Record<string, ActionDecl> = {}\n const declared = isObject(profile) && isObject(profile.actions) ? profile.actions : {}\n for (const [name, a] of Object.entries(declared)) {\n if (collection && (name === 'query' || name === 'page')) continue\n const risk = text(a, 'x-buckyos:risk') as ActionRisk\n if (riskRank(risk) > maxRank) continue\n const input = isObject(a) ? a.input : undefined\n actions[name] = {\n description: text(a, 'description'),\n risk,\n ...(input !== undefined && input !== null ? { input } : {}),\n call: (_m: ResourceMatch, params: Record<string, JsonValue>) => client.invoke(root, name, params),\n }\n }\n const description = [text(profile, 'title'), text(profile, 'description')].filter(Boolean).join(' — ') || root\n out[root] = {\n description: collection ? `${description} (a collection: read it with a query, ?cursor=… for the next page)` : description,\n actions,\n async read(m: ResourceMatch) {\n if (collection && [...m.query.keys()].length > 0) {\n const cursor = m.query.get('cursor')\n const pageSize = m.query.get('page_size')\n if (cursor) return client.invoke(root, 'page', { cursor, ...(pageSize ? { page_size: Number(pageSize) } : {}) })\n const query: Record<string, JsonValue> = {}\n for (const [k, v] of m.query) if (k !== 'page_size') query[k] = v\n return client.invoke(root, 'query', { query, ...(pageSize ? { page_size: Number(pageSize) } : {}) })\n }\n const card = await client.card(root)\n const props = isObject(profile) && isObject(profile.properties) ? Object.keys(profile.properties).filter(p => p !== 'index_schema') : []\n const listed = isObject(profile) && Array.isArray(profile['x-buckyos:summary_props'])\n ? (profile['x-buckyos:summary_props'] as JsonValue[]).filter((p): p is string => typeof p === 'string') : props\n const summary: Record<string, JsonValue> = {}\n for (const p of listed) summary[p] = await client.readProperty(root, p) as JsonValue\n return renderObjectDocument(root, { id: String(card.id), alsoKnownAs: card.alsoKnownAs }, profile, summary)\n },\n }\n }\n return out\n}\n","// A run store in the page's IndexedDB (database `xllm-runs`): run.json and\n// numbered snapshots as Rust lays them out, so a run survives a reload of the\n// page and resumes. The run lock is a Web Lock (`navigator.locks`) held while\n// an executor runs; without Web Locks the page is assumed to be the only tab.\n// Data read back is not trusted: `XllmRun.resume` checks it against the\n// page's runtime before anything runs.\n\nimport type { LLMContextSnapshot, RunRecord } from '../../core/types'\nimport { RUN_RECORD_VERSION, generateRunId } from '../../core/store'\nimport type { ExportedRun, RunLock, RunStore } from '../../core/store'\nimport { XllmError } from '../../core/errors'\n\nexport const XLLM_RUNS_DB = 'xllm-runs'\nconst RECORDS = 'records'\nconst SNAPSHOTS = 'snapshots'\n\nfunction req<T>(r: IDBRequest<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n r.onsuccess = () => resolve(r.result)\n r.onerror = () => reject(r.error)\n })\n}\n\nfunction done(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve()\n tx.onerror = () => reject(tx.error)\n tx.onabort = () => reject(tx.error ?? new Error('transaction aborted'))\n })\n}\n\ninterface LockLike {\n request(name: string, options: { ifAvailable: boolean }, cb: (lock: unknown) => Promise<void>): Promise<void>\n query(): Promise<{ held?: { name?: string }[] }>\n}\n\nexport class IndexedDbRunStore implements RunStore {\n readonly persistent = true\n private db: Promise<IDBDatabase> | undefined\n private readonly localLocks = new Set<string>()\n\n constructor(private readonly options: { dbName?: string; idb?: IDBFactory; locks?: LockLike | null } = {}) {}\n\n private open(): Promise<IDBDatabase> {\n if (!this.db) {\n const factory = this.options.idb ?? globalThis.indexedDB\n if (!factory) return Promise.reject(XllmError.storage('IndexedDB is not available here'))\n const r = factory.open(this.options.dbName ?? XLLM_RUNS_DB, 1)\n r.onupgradeneeded = () => {\n const db = r.result\n if (!db.objectStoreNames.contains(RECORDS)) db.createObjectStore(RECORDS, { keyPath: 'run_id' })\n if (!db.objectStoreNames.contains(SNAPSHOTS)) db.createObjectStore(SNAPSHOTS)\n }\n this.db = req(r)\n }\n return this.db\n }\n\n private locks(): LockLike | undefined {\n if (this.options.locks === null) return undefined\n return this.options.locks ?? (globalThis.navigator as unknown as { locks?: LockLike } | undefined)?.locks\n }\n\n runsDir(): string | undefined {\n return undefined\n }\n\n runDir(): string | undefined {\n return undefined\n }\n\n async createRun(): Promise<string> {\n const db = await this.open()\n for (let i = 0; i < 8; i++) {\n const id = generateRunId()\n const existing = await req(db.transaction(RECORDS).objectStore(RECORDS).get(id))\n if (!existing) return id\n }\n throw XllmError.storage('cannot allocate a unique run id')\n }\n\n async writeRecord(record: RunRecord): Promise<void> {\n const db = await this.open()\n const tx = db.transaction(RECORDS, 'readwrite')\n tx.objectStore(RECORDS).put(JSON.parse(JSON.stringify(record)))\n await done(tx)\n }\n\n async readRecord(runId: string): Promise<RunRecord> {\n const db = await this.open()\n const rec = await req(db.transaction(RECORDS).objectStore(RECORDS).get(runId)) as RunRecord | undefined\n if (!rec) throw new XllmError({ kind: 'run_not_found', run_id: runId, runs_dir: `indexeddb:${this.options.dbName ?? XLLM_RUNS_DB}` })\n if (rec.version !== RUN_RECORD_VERSION) throw XllmError.notResumable(runId, 'unsupported run record version')\n return rec\n }\n\n async listRecords(): Promise<RunRecord[]> {\n const db = await this.open()\n return await req(db.transaction(RECORDS).objectStore(RECORDS).getAll()) as RunRecord[]\n }\n\n async putSnapshot(runId: string, snapshot: LLMContextSnapshot): Promise<number> {\n const db = await this.open()\n const tx = db.transaction(SNAPSHOTS, 'readwrite')\n const store = tx.objectStore(SNAPSHOTS)\n const keys = await req(store.getAllKeys(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER]))) as [string, number][]\n const next = keys.length ? Math.max(...keys.map(k => k[1])) + 1 : 1\n store.put(JSON.parse(JSON.stringify(snapshot)), [runId, next])\n await done(tx)\n return next\n }\n\n async getSnapshot(runId: string, idx: number): Promise<LLMContextSnapshot> {\n const db = await this.open()\n const s = await req(db.transaction(SNAPSHOTS).objectStore(SNAPSHOTS).get([runId, idx])) as LLMContextSnapshot | undefined\n if (!s) throw new XllmError({ kind: 'corrupted_run', run_id: runId, reason: `snapshot ${idx} missing` })\n return s\n }\n\n async listSnapshots(runId: string): Promise<number[]> {\n const db = await this.open()\n const keys = await req(db.transaction(SNAPSHOTS).objectStore(SNAPSHOTS)\n .getAllKeys(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER]))) as [string, number][]\n return keys.map(k => k[1]).sort((a, b) => a - b)\n }\n\n async lockRun(runId: string): Promise<RunLock | null> {\n const name = `xllm-run:${runId}`\n const locks = this.locks()\n if (!locks) {\n if (this.localLocks.has(name)) return null\n this.localLocks.add(name)\n return { release: () => { this.localLocks.delete(name) } }\n }\n return new Promise<RunLock | null>((resolve, reject) => {\n locks.request(name, { ifAvailable: true }, lock => {\n if (!lock) {\n resolve(null)\n return Promise.resolve()\n }\n return new Promise<void>(release => resolve({ release: () => release() }))\n }).catch(reject)\n })\n }\n\n async isRunLive(runId: string): Promise<boolean> {\n const name = `xllm-run:${runId}`\n const locks = this.locks()\n if (!locks) return this.localLocks.has(name)\n const state = await locks.query()\n return (state.held ?? []).some(l => l.name === name)\n }\n\n async removeRun(runId: string): Promise<void> {\n const db = await this.open()\n const tx = db.transaction([RECORDS, SNAPSHOTS], 'readwrite')\n tx.objectStore(RECORDS).delete(runId)\n tx.objectStore(SNAPSHOTS).delete(IDBKeyRange.bound([runId, 0], [runId, Number.MAX_SAFE_INTEGER]))\n await done(tx)\n }\n\n async importRun(run: ExportedRun): Promise<void> {\n const db = await this.open()\n const tx = db.transaction([RECORDS, SNAPSHOTS], 'readwrite')\n tx.objectStore(RECORDS).put(JSON.parse(JSON.stringify(run.record)))\n for (const [idx, s] of run.snapshots) tx.objectStore(SNAPSHOTS).put(JSON.parse(JSON.stringify(s)), [run.record.run_id, idx])\n await done(tx)\n }\n}\n"],"names":["s","a","e","o","value","i","path","text","p","k","n","c","m","r","w","q","d","b","l"],"mappings":";;;;;;;;AAiBO,MAAM,oBAAoB;AAEjC,MAAM,YAAY;AAsBlB,SAAS,YAAY,MAAc,MAAgB,QAA8B;AACxE,SAAA,EAAE,MAAM,aAAa,KAAK,KAAK,aAAa,aAAa,KAAK,KAAK,aAAa,OAAO;AAChG;AAEA,SAAS,aAAa,KAA+B,OAAyB;AAC5E,UAAQ,OAAO,CAAA,GAAI,IAAI,CAAKA,OAAA;AACtB,QAAAA,GAAE,SAAS,SAAS;AAChB,YAAA,UAAU,WAAW,GAAG,KAAK,OAAO,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AAM,UAAU,OAA8B;AACtC,UAAA,KAAK,MAAM,KAAK;AACtB,UAAM,KAAK,GAAG,YAAY,CAAC,SAAS,SAAS,GAAG,WAAW;AAC3D,OAAG,YAAY,OAAO,EAAE,OAAO,KAAK;AACpC,OAAG,YAAY,SAAS,EAAE,OAAO,YAAY,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,OAAO,gBAAgB,CAAC,CAAC;AAChG,UAAM,KAAK,EAAE;AAAA,EACf;AAAA,EAEA,MAAM,UAAU,KAAiC;AACzC,UAAA,KAAK,MAAM,KAAK;AACtB,UAAM,KAAK,GAAG,YAAY,CAAC,SAAS,SAAS,GAAG,WAAW;AACxD,OAAA,YAAY,OAAO,EAAE,IAAI,KAAK,MAAM,KAAK,UAAU,IAAI,MAAM,CAAC,CAAC;AAClE,eAAW,CAAC,KAAKlB,EAAC,KAAK,IAAI;AAAW,SAAG,YAAY,SAAS,EAAE,IAAI,KAAK,MAAM,KAAK,UAAUA,EAAC,CAAC,GAAG,CAAC,IAAI,OAAO,QAAQ,GAAG,CAAC;AAC3H,UAAM,KAAK,EAAE;AAAA,EACf;AACF;"}
@@ -0,0 +1,2 @@
1
+ "use strict";var t=Object.defineProperty,e=(e,n,r)=>(((e,n,r)=>{n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r})(e,"symbol"!=typeof n?n+"":n,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./aicc-ccb36ef7.js"),r=require("./site_manager-334b1a51.js"),i=require("./openai-f560d518.js");function o(){const t=globalThis.Deno;if(!t)throw new Error("the xllm Deno host needs the Deno runtime");return t}function s(t){return t instanceof o().errors.NotFound}function a(t){return t instanceof o().errors.AlreadyExists}function c(t){return t instanceof Error?t.message:String(t)}function l(...t){let e="";for(const n of t)n&&(e=n.startsWith("/")||!e?n:e.endsWith("/")?e+n:`${e}/${n}`);return e}function u(t){const e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n<0?".":0===n?"/":e.slice(0,n)}async function d(t){try{return(await o().stat(t)).isDirectory}catch{return!1}}async function h(t,e){const n=await o().open(t,{write:!0,create:!0,truncate:!0});try{let t=0;for(;t<e.length;)t+=await n.write(e.subarray(t));await n.sync()}finally{n.close()}}async function f(t){if("windows"===o().build.os)return;const e=await o().open(t,{read:!0});try{await e.sync()}finally{e.close()}}require("./krpc_client-26c2dc8b.js");const m=t=>t/2**32|0,p=t=>t>>>0;function w(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name&&"BYTES_PER_ELEMENT"in t&&1===t.BYTES_PER_ELEMENT}const g=t=>t?`"${t}" `:"";function y(t,e=""){if("number"!=typeof t)throw new TypeError(g(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(g(e)+"expected integer >= 0, got "+t);return t}function _(t,e,n=""){if(w(t)&&(void 0===e||t.length===e))return t;void 0!==e&&y(e,"length");const r=w(t),i=void 0!==e?` of length ${e}`:"",o=r?`length=${t.length}`:"type="+typeof t,s=g(n)+"expected Uint8Array"+i+", got "+o;if(!r)throw new TypeError(s);throw new RangeError(s)}const v=(t,e)=>{((t,e)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new TypeError(("object"===e?"":`"${e}" `)+"expected object, got type="+typeof t)})(t,e);const n=Object.getPrototypeOf(t);if(n!==Object.prototype&&null!==n)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function b(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function $(t,e){_(t,void 0,"output");const n=e.outputLen;if(!(t.length>=n))throw new RangeError('"output" expected length >= '+n)}function k(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function x(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function E(t,e){return t<<32-e|t>>>e}const O=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function I(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const S=O?t=>t:t=>I(t)>>>0;const T=O?t=>t:function(t){for(let e=0;e<t.length;e++)t[e]=I(t[e]);return t},A=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),L=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function P(t,e,n="opts"){v(t,"defaults"),void 0!==e&&v(e,n);return Object.assign(Object.create(null),t,e)}function R(t,e={}){if("function"!=typeof t)throw new TypeError('"hashCons" expected function, got type='+typeof t);e=P({},e,"info");const n=(e,n)=>t(n).update(e).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=e=>t(e),Object.assign(n,e),Object.freeze(n)}const D=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function j(t,e,n,r,i){return r=E(r^(t=t+e+i|0),16),{a:t,b:e=E(e^(n=n+r|0),12),c:n,d:r}}function X(t,e,n,r,i){return r=E(r^(t=t+e+i|0),8),{a:t,b:e=E(e^(n=n+r|0),7),c:n,d:r}}class M{constructor(t,n){e(this,"buffer"),e(this,"buffer32"),e(this,"finished",!1),e(this,"destroyed",!1),e(this,"length",0),e(this,"pos",0),e(this,"blockLen"),e(this,"outputLen"),e(this,"canXOF",!1),y(t),y(n),this.blockLen=t,this.outputLen=n,this.buffer=new Uint8Array(t),this.buffer32=k(this.buffer)}update(t){b(this),_(t);const{blockLen:e,buffer:n,buffer32:r}=this,i=t.length,o=t.byteOffset,s=t.buffer;for(let a=0;a<i;){this.pos===e&&(T(r),this.compress(r,0,!1),T(r),this.pos=0);const c=Math.min(e-this.pos,i-a),l=o+a;if(c!==e||l%4||!(a+c<i))n.set(0===a&&c===i?t:t.subarray(a,a+c),this.pos),this.pos+=c,this.length+=c,a+=c;else{const t=new Uint32Array(s,l,Math.floor((i-a)/4));T(t);for(let n=0;a+e<i;n+=r.length,a+=e)this.length+=e,this.compress(t,n,!1);T(t)}}return this}digestInto(t){if(b(this),$(t,this),3&t.byteOffset)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+t.byteOffset);const{pos:e,buffer32:n}=this;this.finished=!0,this.buffer.fill(0,e),T(n),this.compress(n,0,!0),T(n);const r=this.get(),i=t===this.buffer?n:k(t),o=Math.floor(this.outputLen/4);for(let l=0;l<o;l++)i[l]=S(r[l]);const s=this.outputLen%4;if(!s)return;const a=4*o,c=r[o];for(let l=0;l<s;l++)t[a+l]=c>>>8*l}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){const{buffer:e,length:n,finished:r,destroyed:i,outputLen:o,pos:s}=this;return t||(t=new this.constructor({dkLen:o})),t.set(...this.get()),t.buffer.set(e),t.destroyed=i,t.finished=r,t.length=n,t.pos=s,t.outputLen=o,t}clone(){return this._cloneInto()}}function N(t,e,n,r,i,o,s,a,c,l,u,d,h,f,m,p,w,g,y,_){let v=0;for(let b=0;b<r;b++)({a:i,b:c,c:h,d:w}=j(i,c,h,w,n[e+t[v++]])),({a:i,b:c,c:h,d:w}=X(i,c,h,w,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=j(o,l,f,g,n[e+t[v++]])),({a:o,b:l,c:f,d:g}=X(o,l,f,g,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=j(s,u,m,y,n[e+t[v++]])),({a:s,b:u,c:m,d:y}=X(s,u,m,y,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=j(a,d,p,_,n[e+t[v++]])),({a:a,b:d,c:p,d:_}=X(a,d,p,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=j(i,l,m,_,n[e+t[v++]])),({a:i,b:l,c:m,d:_}=X(i,l,m,_,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=j(o,u,p,w,n[e+t[v++]])),({a:o,b:u,c:p,d:w}=X(o,u,p,w,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=j(s,d,h,g,n[e+t[v++]])),({a:s,b:d,c:h,d:g}=X(s,d,h,g,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=j(a,c,f,y,n[e+t[v++]])),({a:a,b:c,c:f,d:y}=X(a,c,f,y,n[e+t[v++]]));return{v0:i,v1:o,v2:s,v3:a,v4:c,v5:l,v6:u,v7:d,v8:h,v9:f,v10:m,v11:p,v12:w,v13:g,v14:y,v15:_}}const U=1,C=2,F=4,H=8,B=16,z=32,q=64,J=D.slice(),W=(()=>{const t=Array.from({length:16},((t,e)=>e)),e=t=>[2,6,3,10,7,0,4,13,1,11,12,5,9,14,15,8].map((e=>t[e])),n=[];for(let r=0,i=t;r<7;r++,i=e(i))n.push(...i);return Uint8Array.from(n)})();class V extends M{constructor(t={},n=0){super(64,void 0===(t=P({},t)).dkLen?32:t.dkLen),e(this,"canXOF",!0),e(this,"chunkPos",0),e(this,"chunksDone",0),e(this,"flags",0),e(this,"IV"),e(this,"state"),e(this,"stack",[]),e(this,"posOut",0),e(this,"bufferOut32",new Uint32Array(16)),e(this,"bufferOut"),e(this,"chunkOut",0),e(this,"enableXOF",!0);const{key:r,context:i}=t,o=void 0!==i;if(void 0!==r){if(o)throw new Error('cannot use both "key" and "context"');_(r,32,"key");const t=(s=r,Uint8Array.from(_(s)));this.IV=k(t),T(this.IV),this.flags=n|B}else if(o){_(i,void 0,"context");const t=i,e=new V({dkLen:32},z).update(t).digest();this.IV=k(e),T(this.IV),this.flags=n|q}else this.IV=J,this.flags=n;var s,a;this.state=this.IV.slice(),this.bufferOut=(a=this.bufferOut32,new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}get(){return[]}set(){}b2Compress(t,e,n,r=0){const{state:i,pos:o}=this,s=p(t),a=m(t),{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(W,r,n,7,i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],J[0],J[1],J[2],J[3],s,a,o,e);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E}compress(t,e=0,n=!1){let r=this.flags;if(this.chunkPos||(r|=U),(15===this.chunkPos||n)&&(r|=C),n||(this.pos=this.blockLen),this.b2Compress(this.chunksDone,r,t,e),this.chunkPos+=1,16===this.chunkPos||n){let t=this.state;this.state=this.IV.slice();for(let e,r=this.chunksDone+1;(n||!(1&r))&&(e=this.stack.pop());r=Math.floor(r/2))this.buffer32.set(e,0),this.buffer32.set(t,8),this.pos=this.blockLen,this.b2Compress(0,this.flags|F,this.buffer32,0),t=this.state,this.state=this.IV.slice();this.chunksDone++,this.chunkPos=0,this.stack.push(t)}this.pos=0}_cloneInto(t){const e=!!t&&t.finished&&!t.destroyed;t=super._cloneInto(t);const{IV:n,flags:r,state:i,chunkPos:o,posOut:s,chunkOut:a,stack:c,chunksDone:l}=this;return t.state.set(i),t.stack=c.map((t=>Uint32Array.from(t))),n===J?(t.IV!==J&&x(t.IV),t.IV=J):t.IV===J?t.IV=n.slice():t.IV.set(n),t.flags=r,t.chunkPos=o,t.chunksDone=l,t.posOut=s,t.chunkOut=a,t.enableXOF=this.enableXOF,this.finished?t.bufferOut32.set(this.bufferOut32):e&&x(t.bufferOut32),t}destroy(){this.destroyed=!0,x(this.state,this.buffer32,this.bufferOut32),this.IV!==J&&x(this.IV),x(...this.stack)}b2CompressOut(){const{state:t,pos:e,flags:n,buffer32:r,bufferOut32:i}=this,o=this.chunkOut++,s=p(o),a=m(o);T(r);const{v0:c,v1:l,v2:u,v3:d,v4:h,v5:f,v6:w,v7:g,v8:y,v9:_,v10:v,v11:b,v12:$,v13:k,v14:x,v15:E}=N(W,0,r,7,t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],J[0],J[1],J[2],J[3],s,a,e,n);i[0]=c^y,i[1]=l^_,i[2]=u^v,i[3]=d^b,i[4]=h^$,i[5]=f^k,i[6]=w^x,i[7]=g^E,i[8]=t[0]^y,i[9]=t[1]^_,i[10]=t[2]^v,i[11]=t[3]^b,i[12]=t[4]^$,i[13]=t[5]^k,i[14]=t[6]^x,i[15]=t[7]^E,T(r),T(i),this.posOut=0}finish(){if(this.finished)return;this.finished=!0,this.buffer.fill(0,this.pos);let t=this.flags|H;this.stack.length?(t|=F,T(this.buffer32),this.compress(this.buffer32,0,!0),T(this.buffer32),this.chunksDone=0,this.pos=this.blockLen):t|=(this.chunkPos?0:U)|C,this.flags=t,this.b2CompressOut()}writeInto(t){b(this,!1),_(t),this.finish();const{blockLen:e,bufferOut:n}=this;for(let r=0,i=t.length;r<i;){this.posOut>=e&&this.b2CompressOut();const o=Math.min(e-this.posOut,i-r);t.set(n.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("no XOF after digest()");return this.writeInto(t)}xof(t){return y(t),this.xofInto(new Uint8Array(t))}digestInto(t){if($(t,this),this.finished)throw new Error("digest() was already called");this.enableXOF=!1,this.writeInto(t.length===this.outputLen?t:t.subarray(0,this.outputLen)),this.destroy()}digest(){const t=new Uint8Array(this.outputLen);return this.digestInto(t),t}}const G=R(((t={})=>new V(t))),K="AGENT_TOOL_HOST_ID";function Y(t){return function(t){if(_(t),A)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=L[t[n]];return e}(G((new TextEncoder).encode(t)))}async function Z(t){try{return await o().readTextFile(t)}catch{return null}}function Q(t){var e;const n=null==(e=t.agent_tool_host_id)?void 0:e.trim();if(n)return`host:${n}:`;return`host:${(t.etc_hostname??t.hostname_env??"unknown").trim()}:${(t.machine_id??"").trim()}`}async function tt(){const t=o().env.get(K)??null;return(null==t?void 0:t.trim())?Q({agent_tool_host_id:t,etc_hostname:null,hostname_env:null,machine_id:null}):Q({agent_tool_host_id:t,etc_hostname:await Z("/etc/hostname"),hostname_env:o().env.get("HOSTNAME")??null,machine_id:await Z("/etc/machine-id")})}function et(t,e){return{host:t,uid:e}}function nt(t){return n.canonicalJson(t)}function rt(t,e,n){return t??it(e,n)}function it(t,e){return`${t}:${Y(nt(e)).slice(0,24)}`}function ot(t,e){return l(t,`${Y(e).slice(0,24)}.lock`)}const st="read_file",at="write_file",ct="edit_file",lt="shell",ut=[st,at,ct,lt],dt=65536,ht=2048,ft="native",mt=200;class pt extends Error{constructor(t,e,n=!1){super("invalid_args"===t?`invalid args: ${e}`:"exec_failed"===t?`execution failed: ${e}`:"timeout"===t?"timeout":"transport"===t?`runtime transport: ${e}`:`cancelled: ${e}`),this.kind=t,this.detail=e,this.effectUnknown=n,this.name="NativeToolError"}}const wt=t=>new pt("invalid_args",t),gt=t=>new pt("exec_failed",t);function yt(t){const e=[];let n="",r=!1,i=!1;const o=[...t];for(let s=0;s<o.length;s++){const t=o[s];"'"!==t||i?'"'!==t||r?"\\"!==t||r?!/\s/.test(t)||r||i?n+=t:n&&(e.push(n),n=""):s+1<o.length&&(n+=o[++s]):i=!i:r=!r}if(!r&&!i)return n&&e.push(n),e}function _t(t){var e;const n=void 0!==t.cmd_name?(null==(e=t.cmd_args)?void 0:e.trim())?`${t.cmd_name} ${t.cmd_args.trim()}`:t.cmd_name:void 0;return`${(void 0!==n?function(t,e){const n=[...t];return n.length<=e?t:`${n.slice(0,e).join("")}...[TRUNCATED]`}(n.trim(),96):"")||"action"} => ${"pending"===t.status?void 0!==t.pending_reason?`pending (${t.pending_reason})`:"pending":t.status}`}function vt(t,e,n,r){const i={agent_tool_protocol:"1",tool:t,status:"success",summary:r,detail:e},o=yt(n),s=o&&o.length?o:n.split(/\s+/).filter(Boolean);return s.length&&(i.cmd_name=s[0],s.length>1&&(i.cmd_args=s.slice(1).join(" "))),i.title=_t(i),i}function bt(t,e){return"/"===e?t.startsWith("/"):t===e||t.startsWith(`${e}/`)}function $t(t,e){if(0!==e.length&&!e.some((e=>bt(t,e))))throw wt(`path not allowed by policy: ${t}`)}async function kt(t){let e=t.replace(/\/+$/,"")||"/";const n=[];for(;;)try{const t=await o().realPath(e);return r.normalizePath(l(t,...n.slice().reverse()))}catch(i){if(!s(i))throw gt(c(i));try{throw await o().lstat(e),wt(`dangling symlink: ${e}`)}catch(a){if(a instanceof pt)throw a}const r=e.slice(e.lastIndexOf("/")+1);if(!r||".."===r)throw wt(`cannot resolve ${t}`);"."!==r&&n.push(r);const l=u(e);if(l===e||"/"===e)throw wt("path has no existing ancestor");e=l}}async function xt(t,e,n){if(!e.trim())throw wt("path cannot be empty");const i=e.startsWith("/")?e:l(t,e);$t(r.normalizePath(i),n);const o=await kt(i);return $t(o,await Promise.all(n.map(kt))),o}function Et(t){let e="";for(const n of(new TextEncoder).encode(t)){const t=String.fromCharCode(n);e+=/[A-Za-z0-9\-._~!$&'()*+,;=:@]/.test(t)?t:`%${n.toString(16).toUpperCase().padStart(2,"0")}`}return e}function Ot(t,e){if(!t)return;const n=r.normalizePath(t);if(!bt(e,n))return;return`cyfs://${["",...e.slice(n.length).split("/").filter((t=>t&&"."!==t))].map(Et).join("/")||"/"}`}function It(t){return null===t?"null":"boolean"==typeof t?`boolean \`${t}\``:"number"==typeof t?Number.isInteger(t)?`integer \`${t}\``:`floating point \`${t}\``:"string"==typeof t?`string ${JSON.stringify(t)}`:Array.isArray(t)?"sequence":"map"}function St(t,e){return wt(`invalid args for \`${t}\`: ${e}`)}function Tt(t,e,n){const r=e[n];if(void 0===r)throw St(t,`missing field \`${n}\``);if("string"!=typeof r)throw St(t,`invalid type: ${It(r)}, expected a string`);return r}function At(t,e,n){const r=e[n];if(null!=r){if("string"!=typeof r)throw St(t,`invalid type: ${It(r)}, expected a string`);return r}}const Lt=new TextEncoder;function Pt(t){return Lt.encode(t).length}function Rt(t){return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(t)}function Dt(t){return t?t.match(/[^\n]*\n|[^\n]+$/g)??[]:[]}function jt(t){if(!t)return[];const e=t.split("\n");return""===e[e.length-1]&&e.pop(),e.map((t=>t.endsWith("\r")?t.slice(0,-1):t))}function Xt(t){const e=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n"),n=t?Math.max(jt(t).length,1):0,r=[...e];return r.length<=64?e:`${r.slice(0,32).join("")}...(total ${n} lines)...${r.slice(-32).join("")}`}function Mt(t,e){const n=t.trim();if("$"===n)return"end";if(n.startsWith("+")||!/^-?\d+$/.test(n))throw wt(`invalid range text \`${e}\``);const r=Number(n);if(0===r)throw wt("range must be 1-based, zero is invalid");return r}function Nt(t,e){const n=t.trim();if(!n.startsWith("+"))throw wt(`invalid range text \`${e}\``);const r=n.slice(1).trim();if(!/^\d+$/.test(r))throw wt(`invalid range text \`${e}\``);const i=Number(r);if(0===i)throw wt("range count must be positive integer");return i}function Ut(t,e){if("string"==typeof t)return Mt(t,e);if("number"==typeof t&&Number.isInteger(t)){if(0===t)throw wt(`${e} must be non-zero integer`);return t}throw wt(`${e} must be integer or \`$\``)}function Ct(t){if(null!=t){if(n.isObject(t)){const e=void 0!==t.start?Ut(t.start,"range.start"):void 0,n=void 0!==t.end?Ut(t.end,"range.end"):void 0,r=void 0!==t.count?function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<=0)throw wt(`${e} must be positive integer`);return t}(t.count,"range.count"):void 0;if(void 0!==r&&void 0!==n)throw wt("range cannot set both `end` and `count`");if(void 0!==r&&void 0===e)throw wt("range.count requires range.start");if(void 0===e&&void 0===n&&void 0===r)throw wt("range object must contain at least one of start/end/count");return{start:e,end:n,count:r,defaultEnd:"tail_if_start_negative"}}if(Array.isArray(t)){if(0===t.length||t.length>2)throw wt("range array must be [start] or [start,end]");return{start:Ut(t[0],"range[0]"),end:2===t.length?Ut(t[1],"range[1]"):void 0,defaultEnd:"same_as_start"}}if("number"==typeof t&&Number.isInteger(t))return{start:Ut(t,"range"),defaultEnd:"same_as_start"};if("string"==typeof t)return function(t){const e=t.trim();if(!e||"-"===e)return;if(e.includes(",")||e.includes(":")){if(e.includes(",")&&e.includes(":"))throw wt(`invalid range text \`${t}\``);const n=e.split(e.includes(",")?",":":");if(2!==n.length)throw wt(`invalid range text \`${t}\``);const r=n[0].trim()?Mt(n[0].trim(),t):void 0,i=n[1].trim();if(i.startsWith("+")){if(void 0===r)throw wt(`range \`${t}\` with \`+count\` requires start`);return{start:r,count:Nt(i,t),defaultEnd:"same_as_start"}}return{start:r,end:i?Mt(i,t):void 0,defaultEnd:"end"}}const n=e.indexOf("-");if(n>=0){const r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(r&&i&&/^\d+$/.test(r)&&/^\d+$/.test(i))return{start:Mt(r,t),end:Mt(i,t),defaultEnd:"same_as_start"}}return{start:Mt(e,t),defaultEnd:"same_as_start"}}(t);throw wt("range must be string/number/array/object")}}function Ft(t,e){return"end"===t?e:t>0?t:e+t+1}const Ht={name:st,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.',args_schema:{properties:{first_chunk:{description:"Start the read at the first occurrence of this text (range then counts from there).",type:"string"},path:{description:"File to read, relative to the working directory.",type:"string"},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:$").'}},required:["path"],type:"object"}},Bt={name:at,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.',args_schema:{properties:{content:{description:"The text to write.",type:"string"},mode:{description:"`write` (default): create or overwrite; `append`: add to the end; `new`: create, fail if the file exists.",type:"string"},path:{description:"File to write, relative to the working directory.",type:"string"}},required:["content","path"],type:"object"}},zt={name:ct,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.",args_schema:{properties:{new_string:{description:"The replacement text.",type:"string"},old_string:{description:"The exact text to replace; it must occur exactly once.",type:"string"},path:{description:"File to edit, relative to the working directory.",type:"string"}},required:["new_string","old_string","path"],type:"object"}};async function qt(t){try{return Rt(await o().readFile(t))}catch(e){throw gt(`read file failed: ${c(e)}`)}}async function Jt(t,e){try{await o().mkdir(u(t),{recursive:!0})}catch(n){throw gt(c(n))}try{await o().writeFile(t,Lt.encode(e))}catch(n){throw gt(`write file failed: ${c(n)}`)}}function Wt(t){return{spec:Ht,idempotent:!0,cancellable:!1,async call(e){const r=Tt(st,e,"path"),i=At(st,e,"first_chunk"),o=null===e.range?void 0:e.range,s=r.trim();if(!s)throw wt("missing required arg `path`");const a=await xt(t.root,s,t.allowedRead),c=await qt(a);let l,u=!0,d=1;if(void 0!==i){const t=c.indexOf(i);t>=0?(l=c.slice(t),d=(c.slice(0,t).match(/\n/g)??[]).length+1):(l="",u=!1)}else l=c;const h=Dt(l),f=h.length,m=Ct(o);let p,w,g="";m?([p,w]=function(t,e){const n=t.start??1,r=Ft(n,e);let i;return i=void 0!==t.count?r+t.count-1:void 0!==t.end?Ft(t.end,e):"same_as_start"===t.defaultEnd?r:"end"===t.defaultEnd||"number"==typeof n&&n<0?e:r,[Math.min(Math.max(r,1),e+1),Math.min(Math.max(i,0),e)]}(m,f),g=`${p}-${w}`):0===f?(p=1,w=0):(p=1,w=f);const y=Math.min(Math.max(p-1,0),f),_=Math.min(w,f),v=y<_?h.slice(y,_):[],b=v.join(""),$=v.length,k=0===$?null:d+y,x=null===k?null:k+Math.max($-1,0);let E="";null!==k&&(E=v.slice(0,mt).map(((t,e)=>{return`${k+e}: ${n=t,n.replace(/[\r\n]+$/,"")}`;var n})).join("\n"),v.length>mt&&(E+=(E?"\n":"")+"... truncated to 200 lines"));const O=Pt(b),I=function(t,e,r){let i=`${st} ${t}`;if(void 0!==e&&(i+=` first_chunk="${Xt(e)}"`),null!=r){const t="string"==typeof r?r:n.canonicalJson(r);t.trim()&&(i+=` range=${t}`)}return i}(s,i,o);let S;if(u){const t=`succeeded, read ${O} bytes across ${null!==k&&null!==x?k===x?`1 line at ${k}`:`${$} lines at ${k}-${x}`:"0 lines"}`;S=E?`${t}\n\`\`\`content\n${E}\n\`\`\``:t}else S="succeeded, first_chunk was not found, read 0 bytes across 0 lines";const T={},A=Ot(t.dfsRoot,a);void 0!==A&&(T.cyfs_url=A),Object.assign(T,{content:b,matched:u,line_range:g,bytes:O,line_count:$,start_line:k,end_line:x,preview_truncated:$>mt});const L=vt(st,T,I,S);return L.title=`${I} => ${u?"success":"anchor not found"}`,function(t,e,r){var i;if("success"!==t.status)return t;const o=(null==(i=t.output)?void 0:i.trim())?t.output:t.summary.trim()?t.summary:n.canonicalJson(t.detail);return t.dedup={key:`read:${e}#${r}:${Y(o).slice(0,16)}`,hint:`\`${e}\` is unchanged since you read it earlier in this run; use that content.`},t}(L,s,n.canonicalJson(Object.fromEntries(Object.entries(e).filter((([t])=>"path"!==t)))))}}}function Vt(t){const e=(t??"write").trim().toLowerCase();if("new"===e||"create"===e)return"new";if("append"===e)return"append";if(""===e||"write"===e||"overwrite"===e)return"write";throw wt(`invalid write mode \`${e}\`, expected new/append/write`)}function Gt(t){return{spec:Bt,idempotent:!1,cancellable:!1,async call(e){const n=Tt(at,e,"path"),r=Tt(at,e,"content"),i=At(at,e,"mode");let a;try{a=Vt(i)}catch{a="write"}const l=`${at} ${n} mode=${a}`,u=n.trim();if(!u)throw wt("missing required arg `path`");const d=Vt(i),h=await xt(t.root,u,t.allowedWrite),f=await async function(t){try{return await o().stat(t),!0}catch(e){if(s(e))return!1;throw gt(c(e))}}(h);if("new"===d&&f)throw wt(`write mode \`new\` requires target file not exist: ${u}`);const m=f?await qt(h):"",p="append"===d?"append":"new"===d?"new":f?"write":"create",w="append"===d?`${m}${r}`:r;await Jt(h,w);const g=Dt(r).length,y={},_=Ot(t.dfsRoot,h);void 0!==_&&(y.cyfs_url=_);const v=Pt(w);Object.assign(y,{created:!f,changed:m!==w,bytes_written:v,line_count:g});const b=`${"append"===p?"appended":"new"===p||"create"===p?"created":"wrote"} ${u}, wrote ${Pt(r)} bytes across ${1===g?"1 line":`${g} lines`}`,$=vt(at,y,l,b),k="append"===p?"append":"new"===p||"create"===p?"new":"write";return $.title=`${at} ${u} mode=${k} => success (${v} bytes)`,$}}}function Kt(t){return{spec:zt,idempotent:!1,cancellable:!1,async call(e){const n=Tt(ct,e,"path"),r=Tt(ct,e,"old_string"),i=Tt(ct,e,"new_string"),o=`${ct} ${n} old_string="${Xt(r)}"`,s=n.trim();if(!s)throw wt("missing required arg `path`");if(!r)throw wt("missing required arg `old_string`");if(r===i)throw wt("`new_string` must be different from `old_string`");const a=await xt(t.root,s,t.allowedWrite),c=await qt(a),l=[];for(let t=c.indexOf(r);t>=0;t=c.indexOf(r,t+r.length))l.push(t);if(0===l.length)throw wt("`old_string` was not found in the file");if(l.length>1)throw wt(`\`old_string\` must match exactly once, found ${l.length} matches`);const u=l[0],d=c.slice(0,u)+i+c.slice(u+r.length),h=c!==d;h&&await Jt(a,d);const f=function(t,e,n){const r=jt(e),i=jt(n),o=[];for(let s=0;s<Math.max(r.length,i.length);s++){const t=r[s],e=i[s];void 0!==t&&void 0!==e?t===e?o.push(` ${t}`):o.push(`-${t}`,`+${e}`):void 0!==t?o.push(`-${t}`):void 0!==e&&o.push(`+${e}`)}return[`--- a/${t}`,`+++ b/${t}`,`@@ -1,${r.length} +1,${i.length} @@`,...o].join("\n")}(s,c,d),m=(c.slice(0,u).match(/\n/g)??[]).length+1,p={},w=Ot(t.dfsRoot,a);void 0!==w&&(p.cyfs_url=w),Object.assign(p,{matched:!0,changed:h,mode:"replace",line:m,diff:f,diff_truncated:!1});const g=h?f.trim()?`edited ${s} with replace at line ${m}\n\`\`\`diff\n${f}\n\`\`\``:`edited ${s} with replace at line ${m}`:`edit ${s} made no change`,y=vt(ct,p,o,g);return y.title=`${ct} ${s} => ${h?`success (line ${m})`:"no change"}`,y}}}const Yt='if [ "$#" -ge 2 ]; then export PATH="$2"; fi\nprintf \'%s\\n\' "$0" > "$1/command"\n"$BASH" -c "$0" </dev/null >"$1/stdout" 2>"$1/stderr"\n__llm_ec=$?\nprintf \'%s\\n\' "$__llm_ec" > "$1/exit.tmp" && command -p mv -f "$1/exit.tmp" "$1/exit"\nexit $__llm_ec',Zt=["/usr/local/sbin","/usr/local/bin","/usr/sbin","/usr/bin","/sbin","/bin"];function Qt(t){const e=[...t].map((t=>/[A-Za-z0-9\-_.]/.test(t)?t:"_")).join("");return!e||e.startsWith(".")?`c_${e}`:e}function te(t,e){if(t&&e)return l(t,"exec",Qt(e))}function ee(t){const e=Math.floor(t/1e3);return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${String(e%60).padStart(2,"0")}s`:`${Math.floor(e/3600)}h${String(Math.floor(e%3600/60)).padStart(2,"0")}m`}async function ne(t){try{return await o().readFile(t)}catch{return}}async function re(t,e){const n=await ne(t);return n?function(t,e){const n=Math.floor(e/4),r=e-n,i=t.subarray(0,Math.min(n,t.length)),o=t.subarray(i.length),s=o.subarray(Math.max(0,o.length-r));return t.length>i.length+s.length?[`${Rt(i)}\n…[${t.length-i.length-s.length} bytes omitted]…\n${Rt(s)}`,!0]:[Rt(i)+Rt(s),!1]}(n,Math.max(e,16)):["",!1]}async function ie(t,e){const n=await ne(t);return n?Rt(n.subarray(Math.max(0,n.length-e))):""}async function oe(t){try{const e=(await o().readTextFile(l(t,"exit"))).trim();return/^[+-]?\d+$/.test(e)?Number(e):void 0}catch{return}}async function se(t,e,n,r,i,o){const[s,a]=await re(l(t,"stdout"),i),[c,u]=await re(l(t,"stderr"),i);let d=s;return c&&(d&&!d.endsWith("\n")&&(d+="\n"),d+=c),{exit_code:e,stdout:s,stderr:c,output:d,output_truncated:a||u,timed_out:n,duration_ms:Math.floor(r),cwd:o}}const ae={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15};const ce=["tool","cmd_name","task_id","pending_reason","estimated_wait","title","summary","cmd_args","partial_output","output"];function le(t){const e=t.maxTimeoutMs,n=`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(t.timeoutMs/1e3)}s${0===e?", no upper limit":`, max ${Math.floor(e/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.`,r={description:`Timeout in milliseconds (default ${t.timeoutMs}${0===e?"":`, max ${e}`}). Set it explicitly for long builds, tests or media commands.`,minimum:1,type:"integer"};return 0!==e&&(r.maximum=e),{name:lt,description:n,args_schema:{properties:{command:{description:"bash command to execute",type:"string"},cwd:{description:t.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.",type:"string"},timeout_ms:r},required:["command"],type:"object"}}}function ue(t,e){if(null!=t){if("number"==typeof t&&Number.isInteger(t)&&t>=0)return t;if("string"==typeof t&&/^\d+$/.test(t.trim()))return Number(t.trim());throw wt(`\`${e}\` must be a non-negative integer`)}}let de=0;function he(t){let e;return{done:new Promise((n=>{e=setTimeout((()=>n("timeout")),Math.min(t,2**31-1))})),stop:()=>clearTimeout(e)}}function fe(t){return{spec:le(t),idempotent:!1,cancellable:!0,async call(e,i){const s="string"==typeof e.command?e.command.trim():"";if(!s)throw wt("`command` is required and must be non-empty");const a="string"==typeof e.cwd?e.cwd:void 0,u=r.normalizePath(t.workspace),h=await xt(u,a??".",t.restrictCwd?[u]:[]);if(!(await d(h)))throw wt(`cwd does not exist: ${h}`);const f=function(t){if(null==t)return[];if(!n.isObject(t))throw wt("`env` must be an object of string=>string");const e=[];for(const[r,i]of Object.entries(t)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw wt(`invalid env key \`${r}\` (must match [A-Za-z_][A-Za-z0-9_]*)`);if("string"==typeof i)e.push([r,i]);else if("number"==typeof i||"boolean"==typeof i)e.push([r,String(i)]);else{if(null!==i)throw wt(`env value for \`${r}\` must be string/number/bool, got ${n.canonicalJson(i)}`);e.push([r,""])}}return e}(e.env),m=ue(e.timeout_ms,"timeout_ms");if(0===m&&0!==t.maxTimeoutMs)throw wt("`timeout_ms` must be a positive integer");const p=(e=>{const n=e??t.timeoutMs;return 0===t.maxTimeoutMs?n:Math.min(Math.max(n,1),t.maxTimeoutMs)})(m);ue(e.wait_ms,"wait_ms");const w=new Map(f);let g=(w.get("PATH")??o().env.get("PATH")??"").trim();for(const t of Zt)y=t,g=(_=g)?_.split(":").includes(y)?_:`${_}:${y}`:y;var y,_;w.set("PATH",g),i.call_id&&w.set("XLLM_CALL_ID",i.call_id),i.run_id&&w.set("XLLM_RUN_ID",i.run_id);const v={...t.env,...Object.fromEntries(w)};v.PATH=[...new Set(g.split(":").filter(Boolean))].join(":");const b=te(i.run_dir,i.call_id),$=void 0===b,k=b??l(o().env.get("TMPDIR")||"/tmp",`llm-shell-${o().pid}-${++de}`);try{await o().mkdir(k,{recursive:!0,mode:448})}catch(R){throw gt(`execution directory: ${c(R)}`)}for(const t of["exit","exit.tmp"])await o().remove(l(k,t)).catch((()=>{}));let x;const E=performance.now();try{x=new(o().Command)("/bin/bash",{args:["-c",Yt,s,k],cwd:h,env:v,stdin:"null",stdout:"null",stderr:"null"}).spawn()}catch(R){throw gt(`spawn shell failed: ${c(R)}`)}const O=async()=>{$&&await o().remove(k,{recursive:!0}).catch((()=>{}))},I=async()=>{try{x.kill("SIGKILL")}catch{}const t=he(5e3);await Promise.race([x.status,t.done]),t.stop();const e=await se(k,124,!0,performance.now()-E,dt,h);return await O(),e},S=he(0===p?31536e6:p),T=await Promise.race([x.status.then((t=>({exited:t}))),S.done.then((()=>({timeout:!0}))),i.call.cancelled().then((t=>({cancel:t})))]);let A;if(S.stop(),"exited"in T)A=await se(k,(P=T.exited,P.signal?128+(ae[P.signal]??0):P.code),!1,performance.now()-E,dt,h),await O();else{if(!("timeout"in T)){const t=(await ie(l(k,"stdout"),ht)).trimEnd(),e=await I();throw new pt("cancelled",`shell (native): \`${s}\` was stopped after ${e.duration_ms}ms because ${L=T.cancel,"finishing"===L?"the run is finishing":"deadline"===L?"the run's total time limit was reached":"the run was interrupted"}. It may have had partial side effects; check before repeating it.${t.trim()?`\n--- output so far (tail) ---\n${t}`:""}`)}A=await I()}var L,P;return function(t,e,r,i){if(!e.timed_out){const r=function(t,e){var r;if(function(t){let e=!1,n=!1,r=!1;for(const i of t)if(r)r=!1;else if("\\"!==i||e)if("'"!==i||n)if('"'!==i||e){if("|;&><\n\r".includes(i)&&!e&&!n)return!0}else n=!n;else e=!e;else r=!0;return!1}(t)||!(null==(r=yt(t))?void 0:r.length))return;const i=e.stdout.trim();if(!i)return;let o;try{o=JSON.parse(i)}catch{return}if(!n.isObject(o)||"1"!==o.agent_tool_protocol)return;const s=o.status??"success";if("success"!==s&&"error"!==s&&"pending"!==s)return;for(const n of ce)if(void 0!==o[n]&&null!==o[n]&&"string"!=typeof o[n])return;if("pending"===s&&"string"!=typeof o.task_id)return;const a={...o,status:s,summary:"string"==typeof o.summary?o.summary:"",detail:void 0===o.detail?{}:o.detail};return void 0===a.return_code&&0!==e.exit_code&&(a.return_code=e.exit_code),a}(t,e);if(r)return r}const o=e.timed_out?`timed out after ${e.duration_ms}ms (timeout_ms=${r}); the command was stopped. Retry with a larger timeout_ms${0===i?"":` (max ${i})`}, or start a long-lived service with nohup / setsid and return at once.`:`exit=${e.exit_code} in ${e.duration_ms}ms`,s={command:t,cwd:e.cwd,exit_code:e.exit_code,stdout:e.stdout,stderr:e.stderr,output:e.output,output_truncated:e.output_truncated,timed_out:e.timed_out,duration_ms:e.duration_ms,engine:ft,runtime:"native"},a=vt(lt,s,`${lt} ${t}`,o);return a.status=0!==e.exit_code||e.timed_out?"error":"success",a.return_code=e.exit_code,a.title=_t(a),function(t,e){return e.trim()?t.output=e:delete t.output,t}(a,e.output)}(s,A,p,t.maxTimeoutMs)}}}const me="native",pe='set -e\ncommand -v bash >/dev/null\nmachine_id="$(cat /etc/machine-id 2>/dev/null || true)"\n[ -n "$machine_id" ] || machine_id="$(hostname)"\nprintf \'%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)"\nfor tool in bash realpath base64; do if command -v "$tool" >/dev/null; then printf \'%s\\0\' "$tool"; fi; done\n';function we(t){let e=(new TextDecoder).decode(t);e.endsWith("\0")&&(e=e.slice(0,-1));const r=e.split("\0");if(r.length<10||r.slice(0,10).some((t=>""===t)))throw n.XllmError.capability("execution environment probe returned incomplete data");return{machine:r[0],hostname:r[1],uid:r[2],os:r[3],arch:r[4],shell:r[5],cwd:r[6],path:r[7],current_time:r[8],timezone:r[9],tools:r.slice(10,42)}}async function ge(t,e){if("windows"===o().build.os)throw n.XllmError.capability("the Deno host's native runtime needs bash (Linux / macOS); Windows PowerShell runtimes are Rust-only");let r;try{r=await new(o().Command)("/bin/bash",{args:["-c",pe],cwd:t,env:e,stdin:"null",stdout:"piped",stderr:"piped",signal:AbortSignal.timeout(1e4)}).output()}catch(i){throw n.XllmError.capability(c(i))}if(!r.success)throw n.XllmError.capability(`native capability probe failed: ${(new TextDecoder).decode(r.stderr)}`);return we(r.stdout)}function ye(t){return n.XllmError.config(".llm_context","runtime",t)}function _e(t){for(const[e,n]of Object.entries(t))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)||n.includes("\0"))throw ye(`invalid env key or value \`${e}\``)}const ve="intent";class be{constructor(t,e,n){this.tools=t,this.workdir=e,this.advertised=n,this.binding={run_id:""},this.ledger=new r.MemoryHintLedger,this.written=[]}bindRun(t){this.binding={...t}}setRecovering(t,e){this.recovering={callId:t,reason:e}}artifacts(){return[...this.written]}has(t){return this.tools.has(t)}hintLedger(){return this.ledger}clearDedup(){this.ledger.clear(r.HINT_NS_DEDUP)}taskResolver(){}listToolSpecs(){return(this.advertised?[...this.advertised.values()]:[...this.tools.values()].map((t=>t.spec))).sort(((t,e)=>t.name<e.name?-1:t.name>e.name?1:0)).map((t=>ut.includes(t.name)?function(t){const e=n.cloneJson(t);let r=e.args_schema;return("object"!=typeof r||null===r||Array.isArray(r))&&(r=e.args_schema={type:"object"}),("object"!=typeof r.properties||null===r.properties||Array.isArray(r.properties))&&(r.properties={}),r.properties[ve]={type:"string",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."},Array.isArray(r.required)&&(r.required=r.required.filter((t=>t!==ve))),e}(t):n.cloneJson(t)))}names(){return[...this.tools.keys()].sort().join(", ")}async callTool(t,e){var n,i;const o=t.call_id,s=this.tools.get(t.name);if(!s)return{kind:"error",call_id:o,message:`tool \`${t.name}\` is not available in this run (available: ${this.names()})`};const a={...t.args??{}};if(ut.includes(t.name)&&delete a[ve],(null==(n=this.recovering)?void 0:n.callId)===o){const t=this.recovering.reason;if(this.recovering=void 0,!s.idempotent)return{kind:"unresolved",call_id:o,reason:t,effect_unknown:!0}}const u=s.call(a,{call_id:o,run_id:this.binding.run_id,run_dir:this.binding.run_dir,call:e}).then((t=>({ok:t})),(t=>({err:t})));let d;if(s.cancellable)d=await u;else{const n=await Promise.race([u,e.cancelledHard().then((t=>({cancelled:t})))]);if("cancelled"in n)return{kind:"cancelled",call_id:o,reason:`tool \`${t.name}\` was abandoned while running (${h=n.cancelled,"deadline"===h?"Deadline":"finishing"===h?"Finishing":"Interrupted"}); it cannot be cancelled, so its effect is unknown`,effect_unknown:!0};d=n}var h;if("err"in d){const t=d.err;if(t instanceof pt){if("transport"===t.kind)throw new r.ToolDispatchException(t.detail,t.effectUnknown);return"cancelled"===t.kind?{kind:"cancelled",call_id:o,reason:t.detail,effect_unknown:t.effectUnknown}:{kind:"error",call_id:o,message:t.message}}return{kind:"error",call_id:o,message:`execution failed: ${c(t)}`}}const f=d.ok;if("success"===f.status&&(t.name===at||t.name===ct)){const t=a.path;if("string"==typeof t){const e=t.startsWith("/")?t:r.normalizePath(l(this.workdir,t));this.written.includes(e)||this.written.push(e)}}if("pending"===f.status){const e=null==(i=f.task_id)?void 0:i.trim();return e?r.taskStateObservation(o,e,{kind:"unknown",reason:"this runtime has no task backend"},{kind:"tools"}):{kind:"error",call_id:o,message:`tool \`${t.name}\` returned a pending result without a task_id`,host:r.toHost(f)}}return r.envelopeObservation(o,f,r.applyHints(f,this.ledger))}}function $e(t,e,n){return{runtime_id:t,kind:me,host:e.host,target:e,workdir:n.cwd,capabilities:{tools:Object.fromEntries(n.tools.map((t=>[t,"available"]))),network:!0,os:n.os}}}function ke(t){return t.wait_ms<t.timeout_ms}async function xe(t={}){const e=n.cloneJson(t.config??{env:{}});e.env=e.env??{},function(t){const e=t.kind??me;if(r.PLANNED_RUNTIME_KINDS.includes(e))throw n.XllmError.capability(`runtime \`${e}\` is planned but not implemented`);if("site"===e)throw n.XllmError.capability("runtime `site` is built by a website (createSiteRuntime); the Deno host runs `native`");if("remote_ssh"===e||"remote_node"===e)throw n.XllmError.capability(`runtime \`${e}\` is not available on the Deno host (only \`native\`)`);if(e!==me)throw ye(`unknown runtime kind \`${e}\``);if(t.remote_ssh&&void 0!==t.kind)throw ye("remote_ssh connection block requires kind: remote_ssh");if(t.remote_node&&void 0!==t.kind)throw ye("remote_node connection block requires kind: remote_node");if(t.remote_ssh||t.remote_node)throw ye("connection block does not match runtime kind");if(_e(t.env??{}),void 0!==t.id&&!t.id.trim())throw ye("id cannot be empty");if(0===t.task_wait_ms)throw ye("task_wait_ms must be positive")}(e);const i=e.workdir??t.workdir??o().cwd();let s;try{s=await o().realPath(i)}catch(_){throw n.XllmError.capability(`runtime cwd ${i}: ${c(_)}`)}if(!(await d(s)))throw n.XllmError.capability("runtime workdir must be a directory");const a=await ge(s,e.env),u=et(await tt(),a.uid),h=rt(e.id,me,u),f=function(t,e,n,r){const i=t.os.toLowerCase(),o=t.shell.split(/[/\\]/).pop()??"";return{id:e,kind:me,os:t.os,arch:t.arch,hostname:t.hostname,shell:t.shell,cwd:t.cwd,tools:t.tools,current_time:t.current_time,timezone:t.timezone,target:n,platform:"darwin"===i||"macos"===i?"macos":i,shell_kind:o.replace(/\.exe$/,"").replace(/\.EXE$/,"").toLowerCase(),baseline:r??""}}(a,h,u,e.baseline),m={...e,kind:me,id:h,workdir:f.cwd},p=$e(h,u,a),w=l(o().env.get("BUCKYOS_ROOT")||"/opt/buckyos","data"),g=(t,e,i,o,s,a)=>{const c=[];for(const l of t){const t=r.describeToolSource(l);if("mcp"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: MCP tools are not available on the Deno host`);if("named"===l.kind)throw n.XllmError.capability(`${e}: \`${t}\`: named host tools are not available on the Deno host (only the \`bash\` group)`);if(l.groupname===r.BUILTIN_TOOL_GROUP_BASH_CORE||"executor"===l.groupname)throw n.XllmError.capability(`${e}: \`${t}\` needs a host task CLI / executor that the Deno host does not provide (use \`bash\`)`);if(l.groupname!==r.BUILTIN_TOOL_GROUP_BASH)throw n.XllmError.tools(`unknown builtin tool group \`${l.groupname}\` (available: ${r.BUILTIN_TOOL_GROUP_BASH}, ${r.BUILTIN_TOOL_GROUP_BASH_CORE}, executor)`);if(ke(i))throw n.XllmError.capability(`${e}: \`shell\` would hand commands still running after runtime.task_wait_ms (${i.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 (${i.timeout_ms} ms) so \`shell\` waits for its command`);const u="workspace"===o,d={root:f.cwd,allowedRead:u?[f.cwd]:[],allowedWrite:u?[f.cwd]:[],dfsRoot:w},h=[Wt(d),Gt(d),Kt(d),fe({workspace:f.cwd,restrictCwd:u,timeoutMs:i.timeout_ms,maxTimeoutMs:i.max_timeout_ms,env:s})];for(const e of h){if(a.has(e.spec.name))throw n.XllmError.tools(`tool name \`${e.spec.name}\` from ${t} conflicts with an already expanded tool of the same name`);a.set(e.spec.name,e),c.push({name:e.spec.name,description:e.spec.description,args_schema:n.cloneJson(e.spec.args_schema),source:t})}}return c};let y;return{kind:me,probe:a,descriptor:()=>n.cloneJson(p),config:()=>n.cloneJson(m),async info(){const t=await ge(f.cwd,m.env),e=y?[...new Set([...f.tools,...y])].sort().slice(0,32):f.tools;return{...n.cloneJson(f),tools:e,current_time:t.current_time,timezone:t.timezone}},async open(e,i){_e(e.env);const o={...m.env,...e.env};o.PATH=o.PATH??a.path;const s=t.takeover&&t.takeover.run_id===e.run_id?t.takeover.tools:void 0,c=s?{enabled:s.enabled,filesystem_policy:s.filesystem_policy,tools2actions:s.tools2actions,tools:s.tool_sources,actions:s.action_sources,bash_tools:s.bash_tools,shell:{timeout_ms:s.shell.timeout_ms,max_timeout_ms:s.shell.max_timeout_ms}}:i,l=c.enabled??!1,u=c.filesystem_policy??"workspace",d=c.tools2actions??!1,h=r.shellSettings(c.shell,e.task_wait_ms),p=e.loop_model,w={enabled:l,filesystem_policy:u,tools2actions:d,tool_sources:n.cloneJson(c.tools??[]),action_sources:n.cloneJson(c.actions??[]),native:[],actions:[],bash_tools:n.cloneJson(c.bash_tools??[]),shell:h,exec_enabled:!1,sources:{...e.sources}};if("function_call"===p){if(d)throw n.XllmError.capability("`tools2actions: true` requires `loop_model: behavior`; function_call cannot convert tools into actions");if((c.actions??[]).length>0)throw n.XllmError.capability("`actions` are configured but `loop_model` is function_call; use `loop_model: behavior` or remove `actions`")}const _=new Map;if(l){const t=c.tools??[{kind:"group",groupname:r.BUILTIN_TOOL_GROUP_BASH}];w.tool_sources=n.cloneJson(t);const e=g(t,"tools.tools",h,u,o,_),i=g(w.action_sources,"tools.actions",h,u,o,_);"behavior"===p&&d?w.actions=[...e,...i]:(w.native=e,w.actions=i),w.exec_enabled=_.has(lt)&&[...w.native,...w.actions].some((t=>t.name===lt))}let v;if(s){v=new Map;for(const t of[...s.native,...s.actions])_.has(t.name)&&v.set(t.name,{name:t.name,description:t.description,args_schema:n.cloneJson(t.args_schema)})}return y=[...w.native,...w.actions].map((t=>t.name)),{tools:w,manager:new be(_,f.cwd,v)}},async describeInterrupted(t,e){if(e.name!==lt)return r.unresolvedReason(e.name);const n=te(t.run_dir,e.call_id);return void 0===n?Ie(e,void 0,"(no execution directory)"):Ie(e,await Ee(n),n)}}}async function Ee(t){let e;try{const n=(await o().stat(l(t,"command"))).mtime;n&&(e=Math.floor(n.getTime()))}catch{e=void 0}return{exit_code:await oe(t),stdout_tail:await ie(l(t,"stdout"),ht),stderr_tail:await ie(l(t,"stderr"),ht),exists:await d(t),started_at_ms:e}}function Oe(t){let e="";return t.stdout_tail.trim()&&(e+=`\n--- stdout (tail) ---\n${t.stdout_tail.trimEnd()}`),t.stderr_tail.trim()&&(e+=`\n--- stderr (tail) ---\n${t.stderr_tail.trimEnd()}`),e}function Ie(t,e,n){const r=function(t){var e;const n=null==(e=t.args)?void 0:e.command;if("string"!=typeof n)return"";const r=n.split(/\s+/).filter(Boolean).join(" "),i=[...r];return i.length>160?`${i.slice(0,160).join("")}…`:r}(t),i=void 0!==(null==e?void 0:e.started_at_ms)?`started ${ee(Math.max(0,Date.now()-e.started_at_ms))} ago (at ${e.started_at_ms} ms since epoch)`:"start time unknown";return void 0!==(null==e?void 0:e.exit_code)?`shell (native): the previous executor exited while \`${r}\` was running (${i}). The command has since ended with exit code ${e.exit_code} (read from ${n}); its result was never returned, so review it before deciding whether to repeat anything.${Oe(e)}`:`shell (native): the previous executor exited while \`${r}\` was running (${i}). 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.${e?Oe(e):""}`}const Se="~/.xllm/runs",Te="~/.xllm/locks";function Ae(t,e){return r.resolveConfigPath(t,e,function(){const t=o().env;return t.get("HOME")??t.get("USERPROFILE")}())}function Le(t,e){if("disabled"===(null==t?void 0:t.kind))return;return Ae("path"===(null==t?void 0:t.kind)?t.path:Se,u(e.startsWith("/")?e:l(o().cwd(),e)))}class Pe{constructor(t,e){this.file=t,this.path=e,this.released=!1}static async tryAcquire(t){try{await o().mkdir(u(t),{recursive:!0})}catch(r){throw n.XllmError.storage(`cannot create lock directory ${u(t)}: ${c(r)}`)}let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch(r){throw n.XllmError.storage(`cannot open lock ${t}: ${c(r)}`)}if(!(await e.tryLock(!0)))return e.close(),null;try{await o().writeTextFile(t,`${o().pid}\n`)}catch{}return new Pe(e,t)}async release(){if(!this.released){this.released=!0;try{await this.file.unlock()}finally{this.file.close()}}}}async function Re(t){let e;try{e=await o().open(t,{read:!0,write:!0,create:!0})}catch{return!1}try{return!(await e.tryLock(!0))||(await e.unlock(),!1)}finally{e.close()}}let De=0;function je(t){return String(t).padStart(4,"0")}class Xe{constructor(t){this.persistent=!0,this.dir=Ae(t,o().cwd())}runsDir(){return this.dir}runDir(t){return l(this.dir,t)}async ensureWritable(){try{await o().mkdir(this.dir,{recursive:!0})}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} cannot be created: ${c(e)}`)}const t=l(this.dir,`.probe-${o().pid}`);try{await o().writeFile(t,new Uint8Array)}catch(e){throw n.XllmError.storage(`runs directory ${this.dir} is not writable: ${c(e)}`)}await o().remove(t).catch((()=>{}))}async createRun(){await this.ensureWritable();for(let e=0;e<8;e++){const e=r.generateRunId(),i=this.runDir(e);try{await o().mkdir(i)}catch(t){if(a(t))continue;throw n.XllmError.storage(`cannot create run directory ${i}: ${c(t)}`)}return await o().mkdir(l(i,"snapshots"),{recursive:!0}),e}throw n.XllmError.storage("cannot allocate a unique run id")}async writeRecord(t){const e=this.runDir(t.run_id),r=l(e,"run.json"),i=l(e,`run.json.tmp-${o().pid}-${De++}`);try{await o().mkdir(e,{recursive:!0}),await h(i,(new TextEncoder).encode(JSON.stringify(t,null,2)))}catch(s){throw n.XllmError.storage(`write ${i}: ${c(s)}`)}try{await o().rename(i,r)}catch(s){throw n.XllmError.storage(`commit ${r}: ${c(s)}`)}try{await f(e)}catch(s){throw n.XllmError.storage(`sync ${e}: ${c(s)}`)}}async readRecord(t){const e=l(this.runDir(t),"run.json");let i,a;try{i=await o().readTextFile(e)}catch(d){if(s(d))throw new n.XllmError({kind:"run_not_found",run_id:t,runs_dir:this.dir});throw n.XllmError.storage(`read ${e}: ${c(d)}`)}try{a=JSON.parse(i)}catch(d){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:c(d)})}const u=a;if((null==u?void 0:u.version)!==r.RUN_RECORD_VERSION)throw n.XllmError.notResumable(t,"unsupported run record version");if("string"!=typeof u.run_id||"string"!=typeof u.status||"object"!=typeof u.config||"object"!=typeof u.prompt)throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:"run.json unreadable: missing run_id / status / config / prompt"});return a}async listRecords(){const t=[];let e;try{e=o().readDir(this.dir);for await(const n of e)if(n.isDirectory)try{const e=JSON.parse(await o().readTextFile(l(this.dir,n.name,"run.json")));e&&"string"==typeof e.run_id&&t.push(e)}catch{}}catch(r){if(s(r))return t;throw n.XllmError.storage(`read runs directory ${this.dir}: ${c(r)}`)}return t}async putSnapshot(t,e){const r=l(this.runDir(t),"snapshots");try{await o().mkdir(r,{recursive:!0});const n=await this.listSnapshots(t),i=n.length?n[n.length-1]+1:1,s=l(r,`${je(i)}.json`),a=l(r,`${je(i)}.json.tmp`);return await h(a,(new TextEncoder).encode(JSON.stringify(e))),await o().rename(a,s),await f(r),i}catch(i){if(i instanceof n.XllmError)throw i;throw n.XllmError.storage(`write snapshot of ${t}: ${c(i)}`)}}async getSnapshot(t,e){const r=l(this.runDir(t),"snapshots",`${je(e)}.json`);let i;try{i=await o().readTextFile(r)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} missing at ${r}: ${c(s)}`})}try{return JSON.parse(i)}catch(s){throw new n.XllmError({kind:"corrupted_run",run_id:t,reason:`snapshot ${e} unreadable: ${c(s)}`})}}async listSnapshots(t){const e=l(this.runDir(t),"snapshots"),n=[];try{for await(const t of o().readDir(e)){const e=/^(\d+)\.json$/.exec(t.name);e&&n.push(Number(e[1]))}}catch(r){if(s(r))return[];throw r}return n.sort(((t,e)=>t-e))}lockRun(t){return Pe.tryAcquire(l(this.runDir(t),".lock"))}async isRunLive(t){return!!(await d(this.runDir(t)))&&Re(l(this.runDir(t),".lock"))}async removeRun(t){const e=this.runDir(t);try{await o().remove(e,{recursive:!0})}catch(r){if(!s(r))throw n.XllmError.storage(`remove ${e}: ${c(r)}`)}await f(this.dir).catch((()=>{}))}async importRun(t){const e=t.record.run_id;if(await this.isRunLive(e))throw new n.XllmError({kind:"run_busy",run_id:e});const r=this.runDir(e);await o().mkdir(l(r,"snapshots"),{recursive:!0});for(const[n,i]of t.snapshots){const t=l(r,"snapshots",`${je(n)}.json`),e=`${t}.tmp`;await h(e,(new TextEncoder).encode(JSON.stringify(i))),await o().rename(e,t)}await f(l(r,"snapshots")),await this.writeRecord(t.record)}}function Me(t=Te){const e=Ae(t,o().cwd());return async(t,n)=>{const r=await Pe.tryAcquire(ot(e,t));return r&&await o().writeTextFile(r.path,`${n}\n`).catch((()=>{})),r}}function Ne(t){return d(t)}const Ue="BUCKYOS_APPCLIENT_SESSION_TOKEN";async function Ce(t){if("env"===t.kind){const e=o().env.get(t.name);if(void 0===e)throw n.XllmError.capability(`environment variable \`${t.name}\` is not set`);return e}let e,r;try{e=await o().readTextFile(t.path)}catch(s){throw n.XllmError.capability(`cannot re-read credential source ${t.path}:${t.field}: ${c(s)}`)}try{r=JSON.parse(e)}catch(s){throw n.XllmError.capability(`cannot parse credential source ${t.path} (the Deno host reads JSON configuration): ${c(s)}`)}let i=r;for(const o of t.field.split(".")){if(!n.isObject(i)||!(o in i))throw n.XllmError.capability(`credential field \`${t.field}\` no longer exists in ${t.path}`);i=i[o]}if("string"!=typeof i||!i.trim())throw n.XllmError.capability(`credential field \`${t.field}\` in ${t.path} is empty or not a string`);return i}function Fe(t){return{async infer(){throw n.providerError({refused:{code:r.REFUSED_CREDENTIALS}},t)}}}async function He(t){var e,r,s;if("openai"===(t.kind??"buckyos")){const e=t.api_key?await Ce(t.api_key):o().env.get("OPENAI_API_KEY");if(!(null==e?void 0:e.trim()))throw n.XllmError.capability("openai provider: no API key; set `provider.api_key`, `provider.api_key_env` or the OPENAI_API_KEY environment variable");return new i.OpenAiLlmClient({baseUrl:t.base_url,apiKey:e,headers:t.headers})}if(void 0!==t.on_behalf_of&&null!==t.on_behalf_of)throw n.XllmError.capability("buckyos provider: `on_behalf_of` (a system service paying for a user) is not available on the Deno host");const a=t.session_token?await Ce(t.session_token):null==(e=o().env.get(Ue))?void 0:e.trim();if(!a)return Fe(`buckyos provider: no BuckyOS session on this host (set ${Ue}), sign in and resume`);const l=(null==(r=o().env.get("BUCKYOS_APP_ID"))?void 0:r.trim())||"buckycli",u=new((await async function(){const t=new URL("./node.mjs",self.location).href;return await import(t)}()).BuckyOSSDK)("node");try{await u.initBuckyOS(l,{zoneHost:(null==(s=o().env.get("BUCKYOS_ZONE_HOST"))?void 0:s.trim())??"",appId:l,defaultProtocol:"https://",runtimeType:"AppClient",sessionToken:a,privateKeySearchPaths:[],autoRenew:!1})}catch(d){throw n.XllmError.capability(`buckyos provider: cannot initialize the BuckyOS runtime (check zone/session setup): ${c(d)}`)}return new n.AiccLlmClient(u.getAiccClient())}function Be(t,e,n,r={}){const i={llm:n,runtime:t,store:e,pid:o().pid,lockWorkdir:Me(r.lockDir),workdirExists:Ne};return r.observer&&(i.observer=r.observer),r.tokenizer&&(i.tokenizer=r.tokenizer),i}const ze={infer(){throw n.XllmError.other("the model client is created after the task is prepared")}};function qe(t){const e=t instanceof n.XllmError?t:n.XllmError.capability(t instanceof Error?t.message:String(t)),r=()=>{throw e},i=()=>Promise.reject(e);return{descriptor:r,config:r,info:i,open:i,describeInterrupted:i}}exports.BASH_GROUP_TOOLS=ut,exports.DEFAULT_LOCK_DIR=Te,exports.DEFAULT_RUNS_DIR=Se,exports.EDIT_FILE_SPEC=zt,exports.EXEC_MAX_OUTPUT_BYTES=dt,exports.FileLock=Pe,exports.FileRunStore=Xe,exports.HOST_ID_ENV=K,exports.LOCAL_PROBE=pe,exports.NATIVE_KIND=me,exports.NATIVE_WRAPPER=Yt,exports.NativeToolManager=be,exports.READ_FILE_SPEC=Ht,exports.SESSION_TOKEN_ENV=Ue,exports.WRITE_FILE_SPEC=Bt,exports.blake3Hex=Y,exports.createLlmClient=He,exports.createNativeRuntime=xe,exports.credentialsRefusedClient=Fe,exports.deriveRuntimeId=rt,exports.execDirFor=te,exports.fmtElapsed=ee,exports.interruptedShellText=Ie,exports.isLocked=Re,exports.localProbe=ge,exports.nativeDeps=Be,exports.nativeDescriptor=$e,exports.nativeHostId=tt,exports.nativeHostIdFrom=Q,exports.nativeTarget=et,exports.parseProbe=we,exports.prepareNativeTask=async function(t,e,n,i,o={}){const s=r.mergeConfigLayers([{path:e,file:r.parseLlmContextJson(e,t??null)}]),a=await xe({config:s.runtime,workdir:o.workdir});let c=o.store;if(!c){const t=Le(s.runs_dir,e);c=void 0===t?new r.MemoryRunStore:new Xe(t)}const l=Be(a,c,o.llm??ze,o),u=await r.XllmTask.prepare(t,e,n,i,l);return{task:u,deps:{...l,llm:o.llm??await He(u.config.provider)}}},exports.readExecDir=Ee,exports.resolveHostPath=Ae,exports.resolveSecret=Ce,exports.resumeNativeRun=async function(t,e,i={},o={}){const s=await t.readRecord(e);let a,c=o.llm;if(r.isTerminal(s.status))a=qe(n.XllmError.other("a terminal run is not executed"));else{try{a=await xe({config:s.config.runtime,workdir:s.workdir,takeover:{run_id:s.run_id,tools:s.config.tools}})}catch(l){a=qe(l)}c=c??await He(s.config.provider)}return r.XllmRun.resume(t,e,i,Be(a,t,c??ze,o))},exports.runsDirOf=Le,exports.runtimeIdOf=it,exports.sanitizeCallId=Qt,exports.shellSpec=le,exports.targetText=nt,exports.workdirExists=Ne,exports.workdirLockPath=ot,exports.workdirLocker=Me;
2
+ //# sourceMappingURL=xllm_deno.cjs.map