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
@@ -2,6 +2,7 @@ import type { CommandModule, JsonSchema, PositionalDefinition } from '../core/co
2
2
  import type { CommandContext } from '../core/context.ts'
3
3
  import { EXIT_INTERNAL, ToolError, UsageError } from '../core/errors.ts'
4
4
  import { callService, expectObject, requiredInputString } from '../core/service.ts'
5
+ import { agentRuntimeCommand } from './runtime.ts'
5
6
 
6
7
  const CONTROL_PANEL = 'control-panel'
7
8
  const OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }
@@ -21,7 +22,7 @@ const PROFILE_FIELDS = ['display_name', 'bio']
21
22
  export function createAgentModule(): CommandModule {
22
23
  return {
23
24
  name: 'agent',
24
- summary: 'List Agents and read or change their profiles',
25
+ summary: 'List Agents, read or change their profiles, and manage the runtimes each one uses',
25
26
  commands: [
26
27
  {
27
28
  verb: 'list',
@@ -144,6 +145,7 @@ export function createAgentModule(): CommandModule {
144
145
  }
145
146
  },
146
147
  },
148
+ agentRuntimeCommand(),
147
149
  ],
148
150
  }
149
151
  }
@@ -883,7 +883,7 @@ async function prepareSource(
883
883
  }
884
884
  }
885
885
 
886
- async function classifySource(
886
+ export async function classifySource(
887
887
  ctx: CommandContext,
888
888
  input: Record<string, unknown>,
889
889
  ): Promise<
@@ -915,6 +915,13 @@ async function classifySource(
915
915
  if (forced) throw new UsageError('INVALID_ARGUMENT', `invalid --from value: ${forced}`)
916
916
 
917
917
  if (/^https?:\/\//i.test(raw)) return { kind: 'url', url: parsePikgUrl(raw) }
918
+ // A DID is never a local file. Probing it as one is not harmless: Windows
919
+ // reads `did:bns:x` as an alternate data stream and stat fails with an
920
+ // invalid-name error instead of NotFound.
921
+ if (isDidSource(raw)) {
922
+ const identifier = normalizeCatalogIdentifier(raw)
923
+ return { kind: 'catalog', display: identifier, serviceSource: { kind: 'identifier', identifier } }
924
+ }
918
925
  const candidatePath = resolveFromCwd(ctx, raw)
919
926
  const stat = await tryLstat(candidatePath)
920
927
  if (stat) {
@@ -1015,7 +1022,7 @@ async function readPikg(
1015
1022
  }
1016
1023
  }
1017
1024
 
1018
- async function downloadPikg(
1025
+ export async function downloadPikg(
1019
1026
  url: URL,
1020
1027
  destination: string,
1021
1028
  downloader: AppModuleDependencies['download'],
@@ -1717,6 +1724,10 @@ function safeUrl(url: URL): string {
1717
1724
  return safe.toString()
1718
1725
  }
1719
1726
 
1727
+ export function isDidSource(value: string): boolean {
1728
+ return value.trim().startsWith('did:')
1729
+ }
1730
+
1720
1731
  function looksLikeLocalPath(value: string): boolean {
1721
1732
  return value.includes('/') || value.includes('\\') || value.startsWith('.') ||
1722
1733
  value.toLowerCase().endsWith('.pikg')
@@ -2,7 +2,8 @@ import type { CommandContext } from '../core/context.ts'
2
2
  import type { CommandModule } from '../core/command.ts'
3
3
  import { EXIT_PERMISSION, EXIT_UNAVAILABLE, ToolError, UsageError } from '../core/errors.ts'
4
4
  import { AIWS_MANIFEST_FILE, AIWS_MANIFEST_VERSION, aiwsContentDigest, controlSkeleton } from 'buckyos/node'
5
- import { createDeterministicTarGz, digestFile, sha256Bytes } from './pikg_archive.ts'
5
+ import { createDeterministicTarGz, digestFile, readTarGz, sha256Bytes } from './pikg_archive.ts'
6
+ import { lintSkillPackage, readSkillDirectory, SKILL_DIRS, skillContentDigest, type SkillPackageFile } from './skill_lint.ts'
6
7
  import {
7
8
  APPDOC_ENTRY,
8
9
  appDocObjectId,
@@ -439,6 +440,10 @@ async function doctorCommand(
439
440
  status: missingSources.length === 0 ? 'ok' : 'missing',
440
441
  missing: missingSources,
441
442
  })
443
+ const skills = pikg.sub_pkgs[PATH_KINDS['agent-skills'].key]
444
+ if (skills?.source.type === 'path' && !missingSources.includes(resolve(metaDir, skills.source.path))) {
445
+ checks.push(await skillLintCheck(app.name, resolve(metaDir, skills.source.path)))
446
+ }
442
447
  if (app.categories[0] === PATH_KINDS['ext-tools'].category) {
443
448
  const catalog = optionalInputString(input, 'catalog')
444
449
  checks.push(...await extToolsChecks(app, pikg, metaDir, catalog ? resolveFromCwd(ctx, catalog) : undefined))
@@ -555,6 +560,9 @@ async function initCommand(
555
560
  if (kind === 'aiws-controls') {
556
561
  await writeAiwsSkeleton(absoluteSource, owner, name, input.composite === true)
557
562
  sourceSummary.skeleton = true
563
+ } else if (kind === 'agent-skills') {
564
+ await writeSkillsSkeleton(absoluteSource, name)
565
+ sourceSummary.skeleton = true
558
566
  } else {
559
567
  await ctx.io.stderr(`warning: source does not exist yet: ${sourceSummary.path}\n`)
560
568
  }
@@ -619,6 +627,67 @@ async function initCommand(
619
627
  }
620
628
  }
621
629
 
630
+ const MAX_SKILL_SOURCE_BYTES = 64 * 1024 * 1024
631
+
632
+ /** `pikg doctor` of an `agent_skills` source (a directory or a `.tar.gz`): the checks the Agent makes when the package is
633
+ * installed. What makes it uninstallable fails the check; the rest are warnings. */
634
+ async function skillLintCheck(packageName: string, source: string): Promise<Record<string, unknown>> {
635
+ const check = { name: 'skill_lint', path: source }
636
+ let files: Map<string, SkillPackageFile>
637
+ let ignored: string[] = []
638
+ try {
639
+ if ((await getHost().stat(source)).isDirectory) {
640
+ ;({ files, ignored } = await readSkillDirectory(source, MAX_SKILL_SOURCE_BYTES))
641
+ } else {
642
+ files = new Map()
643
+ for (const entry of await readTarGz(await getHost().readFile(source), MAX_SKILL_SOURCE_BYTES)) {
644
+ if (SKILL_DIRS.includes(entry.path.split('/')[0])) files.set(entry.path, { bytes: entry.bytes })
645
+ else ignored.push(entry.path)
646
+ }
647
+ }
648
+ } catch (error) {
649
+ return { ...check, status: 'error', detail: error instanceof Error ? error.message : String(error) }
650
+ }
651
+ const { skills, findings } = lintSkillPackage(packageName, files)
652
+ const errors = findings.filter((finding) => finding.level === 'error')
653
+ return {
654
+ ...check,
655
+ status: errors.length ? 'error' : 'ok',
656
+ ...(errors.length ? { detail: errors.map((finding) => finding.note).join('; '), errors } : {}),
657
+ ...(errors.length ? {} : { digest: skillContentDigest(files) }),
658
+ skills: skills.map(({ kind, name, scope, size, commands }) => ({ kind, name, scope, size, commands })),
659
+ warnings: findings.filter((finding) => finding.level !== 'error'),
660
+ ...(ignored.length ? { ignored_files: ignored } : {}),
661
+ }
662
+ }
663
+
664
+ /** A skill package skeleton: one work skill in the directory layout. */
665
+ async function writeSkillsSkeleton(dir: string, name: string): Promise<void> {
666
+ const skill = name.replaceAll('-', '_')
667
+ const manual = join(dir, 'cmd_skills', skill)
668
+ await getHost().mkdir(manual, { recursive: true })
669
+ await getHost().writeTextFile(
670
+ join(manual, 'SKILL.md'),
671
+ [
672
+ '---',
673
+ `name: ${skill}`,
674
+ 'description: One line: what this manual is for, so whoever picks manuals can choose it',
675
+ 'requires: What it needs beyond the commands below, in words',
676
+ 'scope: work',
677
+ '---',
678
+ `# ${skill}`,
679
+ '',
680
+ 'What to do, step by step. Commands this manual runs that are not part of every runtime go into a front matter line',
681
+ '`commands: name, name`; long material goes into `references/` next to this file and is read on demand.',
682
+ '',
683
+ 'A package holds `cmd_skills/<name>/SKILL.md` (work and ui skills), `plan_skills/<name>/SKILL.md` and',
684
+ '`goal_skills/<name>/SKILL.md`, each with an optional `references/`. A skill is text only: it brings no command and no',
685
+ 'install script. Commands come from the standard layer or from extension packages (`buckyos ext-tools`).',
686
+ '',
687
+ ].join('\n'),
688
+ )
689
+ }
690
+
622
691
  /** A control package skeleton: one declarative control (or a composite one) under controls/<name>/ and its manifest
623
692
  * (digest included). */
624
693
  async function writeAiwsSkeleton(dir: string, ownerDid: string, name: string, composite: boolean): Promise<void> {
@@ -0,0 +1,497 @@
1
+ import type { CommandDefinition, CommandModule, JsonSchema, OptionDefinition } from '../core/command.ts'
2
+ import type { CommandContext } from '../core/context.ts'
3
+ import { EXIT_OPERATION, EXIT_PERMISSION, EXIT_UNAVAILABLE, normalizeError, ToolError, UsageError } from '../core/errors.ts'
4
+ import { callService, expectObject, inputString, requiredInputString } from '../core/service.ts'
5
+ import { agentIdFrom } from './skill.ts'
6
+
7
+ const CONTROL_PANEL = 'control-panel'
8
+ const OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }
9
+ const ID: JsonSchema = { type: 'string', minLength: 1 }
10
+ const DEVICE_PREFIX = 'exec-'
11
+ const AGENT_RUNTIME_ACTIONS = ['list', 'enable', 'disable', 'default']
12
+
13
+ const AGENT_OPTION: OptionDefinition = {
14
+ name: 'agent',
15
+ property: 'agent_id',
16
+ description: 'Agent ID as `agent list` prints it',
17
+ type: 'string',
18
+ required: true,
19
+ }
20
+
21
+ type Row = Record<string, string>
22
+ type Json = Record<string, unknown>
23
+
24
+ function objects(value: unknown): Json[] {
25
+ return Array.isArray(value) ? value.filter((item) => item && typeof item === 'object' && !Array.isArray(item)) as Json[] : []
26
+ }
27
+
28
+ function strings(value: unknown): string[] {
29
+ return Array.isArray(value) ? value.map(String) : []
30
+ }
31
+
32
+ function time(value: unknown): string {
33
+ return typeof value === 'number' && value > 0 ? new Date(value).toISOString() : ''
34
+ }
35
+
36
+ function allows(roots: unknown, mode: string, computer: unknown, baseline: unknown): string {
37
+ return [
38
+ strings(roots).join(',') || '-',
39
+ mode,
40
+ ...(computer && computer !== 'none' ? [`computer=${computer}`] : []),
41
+ ...(baseline ? [`baseline=${baseline}`] : []),
42
+ ].join(' ')
43
+ }
44
+
45
+ /** `runtime list` as a table: one row per runtime of the caller's directory (`agent.runtime_catalog`). */
46
+ export function catalogRows(runtimes: Json[]): Row[] {
47
+ return runtimes.map((runtime) => ({
48
+ id: String(runtime.runtime_id ?? ''),
49
+ kind: runtime.kind === 'executor' ? 'device' : String(runtime.kind ?? ''),
50
+ name: String(runtime.name ?? ''),
51
+ state: runtime.closed === true ? 'closed' : 'open',
52
+ online: runtime.online === true ? 'yes' : runtime.online === false ? 'no' : '',
53
+ expires: time(runtime.expires_at_ms),
54
+ allows: allows(runtime.workdir_roots, runtime.read_only === true ? 'ro' : 'rw', runtime.computer, runtime.baseline),
55
+ agents: objects(runtime.assigned_to)
56
+ .map((agent) => `${agent.enabled === true ? '*' : ''}${agent.agent_id}${agent.default === true ? ' (default)' : ''}`)
57
+ .join(', '),
58
+ }))
59
+ }
60
+
61
+ /** `agent runtime list` from the Agent's own records: the current ones (private first), then the retired ones. */
62
+ export function splitAgentRuntimes(records: Json[]): { current: Json[]; history: Json[] } {
63
+ const current = records.filter((record) => record.lifecycle !== 'retired')
64
+ return {
65
+ current: [...current.filter((record) => record.runtime_id === 'private'), ...current.filter((record) => record.runtime_id !== 'private')],
66
+ history: records.filter((record) => record.lifecycle === 'retired'),
67
+ }
68
+ }
69
+
70
+ export function agentRuntimeRows(records: Json[], settings: Json): Row[] {
71
+ const { current, history } = splitAgentRuntimes(records)
72
+ return [...current, ...history].map((record) => {
73
+ const caps = (record.caps ?? {}) as Json
74
+ const grant = (record.grant ?? {}) as Json
75
+ const usage = (record.usage ?? {}) as Json
76
+ const connector = (record.connector ?? {}) as Json
77
+ const retired = record.lifecycle === 'retired'
78
+ return {
79
+ id: String(record.runtime_id ?? ''),
80
+ name: String(record.name ?? ''),
81
+ type: String(connector.type ?? ''),
82
+ state: retired ? 'retired' : record.enabled === false ? 'off' : String(record.availability ?? 'on'),
83
+ default: !retired && (record.default === true || record.runtime_id === settings.default_runtime_id) ? '*' : '',
84
+ os: String(caps.os ?? ''),
85
+ allows: allows(grant.roots, strings(grant.ops).join(',') || '-', grant.computer, caps.baseline),
86
+ expires: time(grant.expires_at_ms),
87
+ sessions: String(usage.sessions_total ?? 0),
88
+ workspaces: String(usage.workspaces ?? 0),
89
+ last_used: time(usage.last_used_at_ms),
90
+ }
91
+ })
92
+ }
93
+
94
+ /** `agent runtime list` when the Agent's service cannot be reached: what the control panel has assigned to it. */
95
+ export function directoryRows(runtimes: Json[], directory: Json): Row[] {
96
+ return runtimes.map((runtime) => ({
97
+ id: String(runtime.runtime_id ?? ''),
98
+ name: String(runtime.name ?? ''),
99
+ type: runtime.kind === 'executor' ? 'device' : String(runtime.kind ?? ''),
100
+ state: runtime.withdrawn === true ? 'withdrawn' : runtime.enabled === true ? (runtime.closed === true ? 'closed' : 'on') : 'off',
101
+ default: runtime.runtime_id === directory.default_runtime_id ? '*' : '',
102
+ os: String(runtime.os ?? ''),
103
+ allows: allows(runtime.workdir_roots, runtime.read_only === true ? 'ro' : 'rw', runtime.computer, runtime.baseline),
104
+ expires: time(runtime.expires_at_ms),
105
+ }))
106
+ }
107
+
108
+ /** What switching a runtime off or removing it touches (`runtimes.impact`), as the lines shown before the question. */
109
+ export function impactText(agentId: string, impact: Json): string {
110
+ const sessions = objects(impact.active_sessions)
111
+ const todos = objects(impact.pending_todos)
112
+ const workspaces = objects(impact.workspaces)
113
+ const lines = [
114
+ `Runtime ${impact.runtime_id} of ${agentId}: ${sessions.length} session(s) in progress, ${todos.length} Todo(s) waiting, ${workspaces.length} workspace(s)` +
115
+ (impact.owner_default === true ? '; it is the default runtime' : ''),
116
+ ]
117
+ for (const session of sessions) {
118
+ lines.push(` session ${session.session_id} [${session.kind}${session.class ? `/${session.class}` : ''}, ${session.run_state}] ${session.title ?? ''}`)
119
+ }
120
+ for (const todo of todos) lines.push(` todo ${todo.session_id}/${todo.todo_id} [${todo.status}] ${todo.title ?? ''}`)
121
+ for (const workspace of workspaces) {
122
+ lines.push(` workspace ${workspace.workspace_id} ${workspace.name ?? ''} ${workspace.directory ?? ''} [${workspace.lifecycle ?? ''}]`)
123
+ }
124
+ if (sessions.length > 0) lines.push(' It cannot be switched off or taken away while these sessions run.')
125
+ return `${lines.join('\n')}\n`
126
+ }
127
+
128
+ /** `exec-<executor_id>` for a device named by its runtime id or its executor id; a node runtime is refused. */
129
+ export function deviceOf(given: string, runtimes: Json[]): { runtime_id: string; executor_id: string; runtime?: Json } {
130
+ const runtime = runtimes.find((item) => item.runtime_id === given || (item.executor_id && item.executor_id === given))
131
+ if (runtime ? runtime.kind !== 'executor' : given === 'host' || given === 'private' || given.startsWith('node-')) {
132
+ throw new UsageError('INVALID_ARGUMENT', `${given} is not a device: only device runtimes (${DEVICE_PREFIX}<executor_id>) are revoked; a node runtime is closed on its node`)
133
+ }
134
+ const executorId = runtime?.executor_id
135
+ ? String(runtime.executor_id)
136
+ : given.startsWith(DEVICE_PREFIX)
137
+ ? given.slice(DEVICE_PREFIX.length)
138
+ : given
139
+ return { runtime_id: runtime ? String(runtime.runtime_id) : `${DEVICE_PREFIX}${executorId}`, executor_id: executorId, ...(runtime ? { runtime } : {}) }
140
+ }
141
+
142
+ function reasonText(error: unknown): string {
143
+ const message = error instanceof Error ? error.message : String(error)
144
+ const brace = message.indexOf('{')
145
+ if (brace < 0) return message
146
+ try {
147
+ const parsed = JSON.parse(message.slice(brace)) as { message?: unknown }
148
+ return typeof parsed.message === 'string' ? parsed.message : message
149
+ } catch {
150
+ return message
151
+ }
152
+ }
153
+
154
+ function serviceReason(error: unknown, prefix: string): string | undefined {
155
+ const message = reasonText(error)
156
+ const at = message.indexOf(`${prefix}:`)
157
+ return at < 0 ? undefined : message.slice(at + prefix.length + 1).trim()
158
+ }
159
+
160
+ function unreachable(error: unknown): boolean {
161
+ const normalized = normalizeError(error)
162
+ return normalized.code === 'SERVICE_UNAVAILABLE' || normalized.code === 'TIMEOUT' ||
163
+ normalized.message.toLowerCase().includes('rpc call error: 404')
164
+ }
165
+
166
+ function message(error: unknown): string {
167
+ return normalizeError(error).message
168
+ }
169
+
170
+ async function confirm(ctx: CommandContext, verb: string, shown: string, question: string, details: Json): Promise<void> {
171
+ if (ctx.confirmed) return
172
+ if (ctx.config.nonInteractive || !ctx.io.inputIsTerminal) {
173
+ throw new ToolError('CONFIRMATION_REQUIRED', `${verb} requires --yes in non-interactive execution`, EXIT_PERMISSION, false, details)
174
+ }
175
+ await ctx.io.stderr(shown)
176
+ const answer = (await ctx.io.prompt(`${question} [y/N] `))?.trim().toLowerCase()
177
+ if (answer !== 'y' && answer !== 'yes') throw new ToolError('CONFIRMATION_DECLINED', `${verb} was declined`, EXIT_PERMISSION)
178
+ }
179
+
180
+ function inProgress(verb: string, shown: string, details: Json): ToolError {
181
+ return new ToolError('SESSIONS_IN_PROGRESS', `${verb}: sessions still run on it; stop them or let them finish first\n${shown}`, EXIT_OPERATION, false, details)
182
+ }
183
+
184
+ async function controlPanel(ctx: CommandContext, method: string, params: Json): Promise<Json> {
185
+ try {
186
+ return expectObject(await callService(ctx, CONTROL_PANEL, method, params), method)
187
+ } catch (error) {
188
+ if (message(error).includes('agent_not_found')) {
189
+ throw new ToolError('RESOURCE_NOT_FOUND', `Agent not found or not yours: ${params.agent_id}`)
190
+ }
191
+ for (const [prefix, code] of [['runtime_not_offered', 'RUNTIME_NOT_OFFERED'], ['invalid_runtimes', 'INVALID_RUNTIMES']]) {
192
+ const reason = serviceReason(error, prefix)
193
+ if (reason !== undefined) throw new ToolError(code, reason, EXIT_OPERATION)
194
+ }
195
+ throw error
196
+ }
197
+ }
198
+
199
+ async function catalog(ctx: CommandContext): Promise<{ response: Json; runtimes: Json[] }> {
200
+ const response = await controlPanel(ctx, 'agent.runtime_catalog', {})
201
+ return { response, runtimes: objects(response.runtimes) }
202
+ }
203
+
204
+ async function impactOf(ctx: CommandContext, agentId: string, runtimeId: string): Promise<Json> {
205
+ return expectObject(await callService(ctx, agentId, 'runtimes.impact', { runtime_id: runtimeId }), 'runtimes.impact')
206
+ }
207
+
208
+ function command(
209
+ definition: Pick<CommandDefinition, 'verb' | 'summary' | 'handler'> & Partial<CommandDefinition> & {
210
+ level: 'read' | 'write' | 'destructive'
211
+ properties: Record<string, JsonSchema>
212
+ required?: string[]
213
+ },
214
+ ): CommandDefinition {
215
+ const { level, properties, required, ...rest } = definition
216
+ return {
217
+ inputSchema: { type: 'object', properties, required: required ?? [], additionalProperties: false },
218
+ outputSchema: OBJECT_OUTPUT,
219
+ resultSchemaVersion: 1,
220
+ access: { mode: 'fixed', level },
221
+ asyncMode: 'sync',
222
+ requiresSession: true,
223
+ ...rest,
224
+ }
225
+ }
226
+
227
+ /** The owner's runtime directory: what runtimes there are, and which Agent each is assigned to. A runtime is a sandbox
228
+ * with its own configuration; assigning it only records that an Agent may use it. */
229
+ export function createRuntimeModule(): CommandModule {
230
+ return {
231
+ name: 'runtime',
232
+ summary: 'List the runtimes of your directory, assign them to Agents, and revoke devices',
233
+ commands: [
234
+ command({
235
+ verb: 'list',
236
+ summary: 'List the runtimes of your directory and the Agents each is assigned to',
237
+ description:
238
+ 'Node runtimes (host, node-*) and devices (exec-<executor_id>). What a runtime allows (directories, ro|rw, computer use, baseline, expiry) is its own configuration. In the agents column `*` marks an Agent that has the runtime switched on and (default) the Agent whose default it is. A device is used by one Agent at a time.',
239
+ level: 'read',
240
+ properties: {},
241
+ examples: ['buckyos runtime list', 'buckyos --output table runtime list'],
242
+ handler: async (ctx) => {
243
+ const { response, runtimes } = await catalog(ctx)
244
+ return { ...response, runtimes: ctx.output.format === 'table' ? catalogRows(runtimes) : runtimes }
245
+ },
246
+ }),
247
+ command({
248
+ verb: 'assign',
249
+ summary: 'Assign a runtime of your directory to an Agent',
250
+ description:
251
+ 'Records that the Agent may use the runtime, switched on unless --disabled. Nothing about what the runtime allows is set per Agent. A device another Agent has switched on is refused (RUNTIME_IN_USE): switch it off there first; this command never does that for you.',
252
+ positionals: [{ name: 'runtime_id', description: 'Runtime id as `runtime list` prints it' }],
253
+ options: [AGENT_OPTION, { name: 'disabled', description: 'Assign it switched off', type: 'boolean' }],
254
+ level: 'write',
255
+ properties: { runtime_id: ID, agent_id: ID, disabled: { type: 'boolean' } },
256
+ required: ['runtime_id', 'agent_id'],
257
+ examples: [
258
+ 'buckyos runtime assign host --agent jarvis.example.zone',
259
+ 'buckyos runtime assign exec-laptop --agent jarvis.example.zone --disabled',
260
+ ],
261
+ handler: async (ctx, input) => await assign(ctx, input),
262
+ }),
263
+ command({
264
+ verb: 'unassign',
265
+ summary: 'Take a runtime away from an Agent',
266
+ description:
267
+ 'Refused while sessions of the Agent run on the runtime (SESSIONS_IN_PROGRESS): stop them or let them finish first. The Agent keeps the record as history; the runtime stays in your directory. When the service of the Agent cannot be reached what runs there is unknown and only --yes removes the assignment, through the control panel.',
268
+ positionals: [{ name: 'runtime_id', description: 'Runtime id' }],
269
+ options: [AGENT_OPTION],
270
+ level: 'destructive',
271
+ properties: { runtime_id: ID, agent_id: ID },
272
+ required: ['runtime_id', 'agent_id'],
273
+ examples: ['buckyos runtime unassign host --agent jarvis.example.zone'],
274
+ handler: async (ctx, input) => await unassign(ctx, input),
275
+ }),
276
+ command({
277
+ verb: 'revoke',
278
+ summary: 'Revoke a device: it stops serving and is taken away from its Agents',
279
+ description:
280
+ 'Devices only (exec-<executor_id>, or the executor id). Refused while sessions of the Agent using it run there (SESSIONS_IN_PROGRESS); otherwise shows the Agents the device is assigned to and asks; --yes skips the question.',
281
+ positionals: [{ name: 'runtime_id', description: 'Device runtime id (exec-<executor_id>) or executor id' }],
282
+ level: 'destructive',
283
+ properties: { runtime_id: ID },
284
+ required: ['runtime_id'],
285
+ examples: ['buckyos runtime revoke exec-laptop', 'buckyos --yes runtime revoke laptop'],
286
+ handler: async (ctx, input) => await revoke(ctx, input),
287
+ }),
288
+ ],
289
+ }
290
+ }
291
+
292
+ /** `agent runtime <list|enable|disable|default> [runtime_id] --agent <agent_id>`: the runtimes one Agent uses. */
293
+ export function agentRuntimeCommand(): CommandDefinition {
294
+ return {
295
+ verb: 'runtime',
296
+ summary: 'The runtimes of one Agent: list them, switch one on or off, choose the default',
297
+ description:
298
+ 'list: the runtimes the Agent has now (its private one first), then the retired ones with their usage; from the control panel when the service of the Agent cannot be reached. enable / disable <runtime_id>: whether the Agent uses a runtime it was assigned; disable is refused while sessions run on it (SESSIONS_IN_PROGRESS). default <runtime_id|private>: the owner default runtime, the machine \"my computer\" means to the Agent (work it starts on its own runs on its private runtime). Runtimes are assigned with `buckyos runtime assign`.',
299
+ positionals: [
300
+ { name: 'action', description: AGENT_RUNTIME_ACTIONS.join(' | ') },
301
+ { name: 'runtime_id', description: 'Runtime id (enable, disable, default); `private` is the own runtime of the Agent', required: false },
302
+ ],
303
+ options: [AGENT_OPTION],
304
+ inputSchema: {
305
+ type: 'object',
306
+ properties: { action: { type: 'string', enum: AGENT_RUNTIME_ACTIONS }, runtime_id: ID, agent_id: ID },
307
+ required: ['action', 'agent_id'],
308
+ additionalProperties: false,
309
+ },
310
+ outputSchema: OBJECT_OUTPUT,
311
+ resultSchemaVersion: 1,
312
+ access: { mode: 'operation', operationIdField: 'action', possibleLevels: ['read', 'write'] },
313
+ asyncMode: 'sync',
314
+ requiresSession: true,
315
+ examples: [
316
+ 'buckyos agent runtime list --agent jarvis.example.zone',
317
+ 'buckyos agent runtime enable host --agent jarvis.example.zone',
318
+ 'buckyos agent runtime disable exec-laptop --agent jarvis.example.zone',
319
+ 'buckyos agent runtime default private --agent jarvis.example.zone',
320
+ ],
321
+ handler: async (ctx, input) => {
322
+ const agentId = agentIdFrom(input)
323
+ const action = requiredInputString(input, 'action')
324
+ const runtimeId = inputString(input, 'runtime_id')
325
+ if (action === 'list') {
326
+ if (runtimeId) throw new UsageError('ARGUMENT_CONFLICT', 'agent runtime list takes no runtime id')
327
+ return await agentRuntimeList(ctx, agentId)
328
+ }
329
+ if (!runtimeId) throw new UsageError('MISSING_ARGUMENT', `agent runtime ${action} needs a runtime id`)
330
+ if (action === 'default') {
331
+ const settings = await settingsSet(ctx, agentId, { runtime_id: runtimeId, default: true })
332
+ return { agent_id: agentId, runtime_id: runtimeId, default: true, settings }
333
+ }
334
+ if (action === 'enable') {
335
+ const settings = await settingsSet(ctx, agentId, { runtime_id: runtimeId, enabled: true })
336
+ return { agent_id: agentId, runtime_id: runtimeId, enabled: true, settings }
337
+ }
338
+ const settings = await settingsSet(ctx, agentId, { runtime_id: runtimeId, enabled: false })
339
+ return { agent_id: agentId, runtime_id: runtimeId, enabled: false, settings }
340
+ },
341
+ }
342
+ }
343
+
344
+ async function settingsSet(ctx: CommandContext, agentId: string, params: Json): Promise<Json> {
345
+ try {
346
+ return expectObject(await callService(ctx, agentId, 'runtimes.settings_set', params), 'runtimes.settings_set')
347
+ } catch (error) {
348
+ throw runtimeError(error, agentId, String(params.runtime_id)) ?? error
349
+ }
350
+ }
351
+
352
+ function runtimeError(error: unknown, agentId: string, runtimeId: string): ToolError | undefined {
353
+ const busy = serviceReason(error, 'sessions_in_progress')
354
+ if (busy !== undefined) {
355
+ return new ToolError('SESSIONS_IN_PROGRESS', `${busy} (buckyos agent runtime list --agent ${agentId})`, EXIT_OPERATION)
356
+ }
357
+ const inUse = serviceReason(error, 'runtime_in_use')
358
+ if (inUse !== undefined) {
359
+ const user = /in use by Agent `([^`]+)`/.exec(inUse)?.[1]
360
+ return new ToolError(
361
+ 'RUNTIME_IN_USE',
362
+ `${inUse}${user ? ` (buckyos agent runtime disable ${runtimeId} --agent ${user})` : ''}`,
363
+ EXIT_OPERATION,
364
+ false,
365
+ user ? { in_use_by: user, disable_command: `buckyos agent runtime disable ${runtimeId} --agent ${user}` } : {},
366
+ )
367
+ }
368
+ return undefined
369
+ }
370
+
371
+ async function agentRuntimeList(ctx: CommandContext, agentId: string): Promise<Json> {
372
+ let records: Json[]
373
+ let settings: Json
374
+ try {
375
+ const listed = await callService<unknown>(ctx, agentId, 'runtimes.list', {})
376
+ if (!Array.isArray(listed)) throw new ToolError('INVALID_SERVICE_RESPONSE', 'runtimes.list must be an array')
377
+ records = objects(listed)
378
+ settings = expectObject(await callService(ctx, agentId, 'runtimes.settings', {}), 'runtimes.settings')
379
+ } catch (error) {
380
+ if (!unreachable(error)) throw error
381
+ const directory = await controlPanel(ctx, 'agent.runtime_directory', { agent_id: agentId })
382
+ const assigned = objects(directory.runtimes).filter((runtime) => runtime.assigned === true)
383
+ const { runtimes: _all, ...rest } = directory
384
+ return {
385
+ agent_id: agentId,
386
+ source: CONTROL_PANEL,
387
+ note: `the service of ${agentId} cannot be reached (${message(error)}): these are its assignments in the control panel; availability, usage and retired runtimes are not known`,
388
+ runtimes: ctx.output.format === 'table' ? directoryRows(assigned, directory) : assigned,
389
+ ...rest,
390
+ }
391
+ }
392
+ const { current, history } = splitAgentRuntimes(records)
393
+ return {
394
+ agent_id: agentId,
395
+ source: 'agent',
396
+ ...(ctx.output.format === 'table' ? { runtimes: agentRuntimeRows(records, settings) } : { runtimes: current, history }),
397
+ default_runtime_id: settings.default_runtime_id ?? null,
398
+ configured_default_runtime_id: settings.configured_default_runtime_id ?? null,
399
+ settings: settings.runtimes ?? {},
400
+ }
401
+ }
402
+
403
+ async function assign(ctx: CommandContext, input: Json): Promise<Json> {
404
+ const agentId = agentIdFrom(input)
405
+ const runtimeId = requiredInputString(input, 'runtime_id')
406
+ const enabled = input.disabled !== true
407
+ try {
408
+ await controlPanel(ctx, 'agent.update', { agent_id: agentId, runtimes: { [runtimeId]: { enabled } } })
409
+ } catch (error) {
410
+ const inUse = serviceReason(error, 'runtime_in_use')
411
+ if (inUse === undefined) throw error
412
+ let user = /in use by Agent `([^`]+)`/.exec(inUse)?.[1]
413
+ let theirs = runtimeId
414
+ try {
415
+ const device = deviceOf(runtimeId, (await catalog(ctx)).runtimes).runtime
416
+ const using = objects(device?.assigned_to).find((agent) => agent.enabled === true && agent.agent_id !== agentId)
417
+ if (using) {
418
+ user = String(using.agent_id)
419
+ theirs = String(using.runtime_id ?? runtimeId)
420
+ }
421
+ } catch {
422
+ // the refusal itself is what matters
423
+ }
424
+ const disable = user ? `buckyos agent runtime disable ${theirs} --agent ${user}` : undefined
425
+ throw new ToolError(
426
+ 'RUNTIME_IN_USE',
427
+ `${inUse}${disable ? `: ${disable}` : ''}`,
428
+ EXIT_OPERATION,
429
+ false,
430
+ user ? { in_use_by: user, disable_command: disable } : {},
431
+ )
432
+ }
433
+ return { agent_id: agentId, runtime_id: runtimeId, assigned: true, enabled }
434
+ }
435
+
436
+ async function unassign(ctx: CommandContext, input: Json): Promise<Json> {
437
+ const agentId = agentIdFrom(input)
438
+ const runtimeId = requiredInputString(input, 'runtime_id')
439
+ let impact: Json
440
+ try {
441
+ impact = await impactOf(ctx, agentId, runtimeId)
442
+ } catch (error) {
443
+ if (!unreachable(error)) throw error
444
+ const why = `the service of ${agentId} cannot be reached (${message(error)}): what it has in progress on ${runtimeId} is unknown`
445
+ if (!ctx.confirmed) {
446
+ throw new ToolError(
447
+ 'AGENT_SERVICE_UNAVAILABLE',
448
+ `${why}. Nothing was changed; --yes removes the assignment through the control panel anyway`,
449
+ EXIT_UNAVAILABLE,
450
+ true,
451
+ )
452
+ }
453
+ await controlPanel(ctx, 'agent.update', { agent_id: agentId, runtimes: { [runtimeId]: null } })
454
+ return { agent_id: agentId, runtime_id: runtimeId, removed: true, via: CONTROL_PANEL, impact: null, warning: why }
455
+ }
456
+ if (impact.blocking === true) throw inProgress('runtime unassign', impactText(agentId, impact), { impact })
457
+ let settings: Json
458
+ try {
459
+ settings = expectObject(await callService(ctx, agentId, 'runtimes.remove', { runtime_id: runtimeId }), 'runtimes.remove')
460
+ } catch (error) {
461
+ throw runtimeError(error, agentId, runtimeId) ?? error
462
+ }
463
+ return { agent_id: agentId, runtime_id: runtimeId, removed: true, via: 'agent', impact, settings }
464
+ }
465
+
466
+ async function revoke(ctx: CommandContext, input: Json): Promise<Json> {
467
+ const given = requiredInputString(input, 'runtime_id')
468
+ const device = deviceOf(given, (await catalog(ctx)).runtimes)
469
+ const assigned = objects(device.runtime?.assigned_to)
470
+ const lines = [
471
+ device.runtime
472
+ ? `Device ${device.runtime_id} (${device.runtime.name ?? device.executor_id}) is assigned to ${assigned.length} Agent(s)`
473
+ : `Device ${device.runtime_id} is not in your runtime directory: nothing is known about its Agents`,
474
+ ...assigned.map((agent) => ` ${agent.enabled === true ? '*' : ' '} ${agent.agent_id}${agent.default === true ? ' (default)' : ''}`),
475
+ ]
476
+ const impacts: Json[] = []
477
+ for (const agent of assigned.filter((item) => item.enabled === true)) {
478
+ const agentId = String(agent.agent_id)
479
+ try {
480
+ const impact = await impactOf(ctx, agentId, String(agent.runtime_id ?? device.runtime_id))
481
+ impacts.push({ agent_id: agentId, impact })
482
+ lines.push(impactText(agentId, impact).trimEnd())
483
+ } catch (error) {
484
+ impacts.push({ agent_id: agentId, impact: null, error: message(error) })
485
+ lines.push(` what ${agentId} has in progress on it is unknown: ${message(error)}`)
486
+ }
487
+ }
488
+ if (impacts.some((item) => (item.impact as Json | null)?.blocking === true)) {
489
+ throw inProgress('runtime revoke', `${lines.join('\n')}\n`, { assigned_to: assigned, impacts })
490
+ }
491
+ await confirm(ctx, 'runtime revoke', `${lines.join('\n')}\n`, `Revoke ${device.runtime_id} and take it away from its Agents?`, {
492
+ assigned_to: assigned,
493
+ impacts,
494
+ })
495
+ const revoked = await controlPanel(ctx, 'executor.device.revoke', { executor_id: device.executor_id })
496
+ return { runtime_id: device.runtime_id, executor_id: device.executor_id, revoked: true, assigned_to: assigned, impacts, ...revoked }
497
+ }