{"version":3,"file":"cli.mjs","sources":["../core/errors.ts","../../src/internal/command_args.ts","../core/argv.ts","../runtime/host.ts","../core/config.ts","../core/runtime.ts","../core/development_mode.ts","../core/identity.ts","../core/auth.ts","../core/output.ts","../core/registry.ts","../core/history.ts","../core/repl.ts","../modules/auth.ts","../modules/core.ts","../core/service.ts","../modules/system.ts","../modules/system_config.ts","../modules/pikg_archive.ts","../modules/pikg_protocol.ts","../modules/skill_lint.ts","../version.ts","../modules/pikg.ts","../core/task.ts","../modules/app.ts","../core/download.ts","../modules/diagnostic.ts","../modules/log.ts","../modules/task.ts","../modules/provision.ts","../modules/skill.ts","../modules/runtime.ts","../modules/agent.ts","../modules/ai.ts","../modules/share.ts","../modules/bucket.ts","../modules/obj.ts","../modules/executor.ts","../modules/ext_tools.ts","../modules/aiws_place.ts","../modules/aiws.ts","../core/app.ts","../main.ts","../runtime/fs_retry.ts","../runtime/path_policy.ts","../runtime/host_node.ts","../runtime/node_entry.ts"],"sourcesContent":["export const EXIT_SUCCESS = 0\nexport const EXIT_USAGE = 2\nexport const EXIT_AUTH = 3\nexport const EXIT_PERMISSION = 4\nexport const EXIT_UNAVAILABLE = 5\nexport const EXIT_OPERATION = 6\nexport const EXIT_PARTIAL = 7\nexport const EXIT_TIMEOUT = 8\nexport const EXIT_INTERNAL = 9\n\nexport class ToolError extends Error {\n  readonly code: string\n  readonly exitCode: number\n  readonly retryable: boolean\n  readonly details: Record<string, unknown>\n\n  constructor(\n    code: string,\n    message: string,\n    exitCode = EXIT_OPERATION,\n    retryable = false,\n    details: Record<string, unknown> = {},\n  ) {\n    super(message)\n    this.name = 'ToolError'\n    this.code = code\n    this.exitCode = exitCode\n    this.retryable = retryable\n    this.details = details\n  }\n}\n\nexport class UsageError extends ToolError {\n  constructor(code: string, message: string, details: Record<string, unknown> = {}) {\n    super(code, message, EXIT_USAGE, false, details)\n  }\n}\n\nconst JWT_PATTERN = /\\beyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\b/g\nconst URL_CREDENTIAL_PATTERN = /(\\w+:\\/\\/)[^\\s/@:]+:[^\\s/@]+@/g\nconst DATABASE_URI_PATTERN =\n  /\\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\\+srv)?|redis|rediss|sqlite):\\/\\/[^\\s,;]+/gi\n\nexport function sanitizeMessage(message: string): string {\n  return message\n    .replaceAll(JWT_PATTERN, '[REDACTED_TOKEN]')\n    .replaceAll(URL_CREDENTIAL_PATTERN, '$1[REDACTED]@')\n    .replaceAll(DATABASE_URI_PATTERN, '[REDACTED_DATABASE_URI]')\n    .replace(\n      /(session[_-]?token|refresh[_-]?token|access[_-]?token|private[_-]?key|password|passwd|api[_-]?key|client[_-]?secret|secret)\\s*[=:]\\s*[^\\s,;]+/gi,\n      '$1=[REDACTED]',\n    )\n}\n\nexport function normalizeError(error: unknown): ToolError {\n  if (error instanceof ToolError) {\n    return new ToolError(\n      error.code,\n      sanitizeMessage(error.message),\n      error.exitCode,\n      error.retryable,\n      error.details,\n    )\n  }\n\n  const raw = error instanceof Error ? error.message : String(error)\n  const message = sanitizeMessage(raw)\n  const lower = message.toLowerCase()\n\n  if (lower.includes('abort') || lower.includes('cancel')) {\n    return new ToolError('CANCELED', 'operation canceled', EXIT_TIMEOUT)\n  }\n  if (lower.includes('timeout') || lower.includes('timed out')) {\n    return new ToolError('TIMEOUT', 'operation timed out', EXIT_TIMEOUT, true)\n  }\n  if (\n    lower.includes('permission denied') || lower.includes('no permission') ||\n    lower.includes('rpc call error: 403')\n  ) {\n    return new ToolError('PERMISSION_DENIED', message, EXIT_PERMISSION)\n  }\n  if (\n    lower.includes('rpc call error: 401') || lower.includes('unauthorized') ||\n    lower.includes('token expired') || lower.includes('session expired') ||\n    lower.includes('invalid token')\n  ) {\n    return new ToolError(\n      lower.includes('expired') ? 'SESSION_EXPIRED' : 'INVALID_SESSION',\n      lower.includes('expired') ? 'the session token has expired' : message,\n      EXIT_AUTH,\n    )\n  }\n  if (\n    lower.includes('fetch failed') || lower.includes('connection refused') ||\n    lower.includes('rpc call error: 502') || lower.includes('rpc call error: 503') ||\n    lower.includes('rpc call error: 504')\n  ) {\n    return new ToolError('SERVICE_UNAVAILABLE', message, EXIT_UNAVAILABLE, true)\n  }\n  if (lower.includes('not found') || lower.includes('key not exist')) {\n    return new ToolError('RESOURCE_NOT_FOUND', message, EXIT_OPERATION)\n  }\n  if (lower.includes('rpc call error:')) {\n    return new ToolError('OPERATION_FAILED', message, EXIT_OPERATION)\n  }\n  return new ToolError('INTERNAL_ERROR', message || 'internal error', EXIT_INTERNAL)\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","import type { JsonSchema, RegisteredCommand } from './command.ts'\nimport { UsageError } from './errors.ts'\nimport {\n  checkRequiredPositionals,\n  CommandArgsError,\n  type LongOption,\n  mergeCommandInput,\n  parseArgv,\n  parseShellLine as parseShellLineCore,\n  readOptionValue as readOptionValueCore,\n  splitLongOption,\n  validateSchema as validateSchemaCore,\n} from '../../src/internal/command_args.ts'\n\nexport const OUTPUT_FORMATS = ['json', 'jsonl', 'table', 'text', 'raw'] as const\nexport type OutputFormat = typeof OUTPUT_FORMATS[number]\n\nexport interface GlobalOptions {\n  configDir?: string\n  allowRead?: string[]\n  profile?: string\n  zone?: string\n  endpoint?: string\n  identity?: string\n  sessionToken?: string\n  sessionTokenFile?: string\n  cli?: boolean\n  output?: OutputFormat\n  input?: string\n  timeout?: string\n  traceId?: string\n  idempotencyKey?: string\n  wait?: boolean\n  nonInteractive?: boolean\n  yes?: boolean\n  noColor?: boolean\n  verbose?: boolean\n  help?: boolean\n  version?: boolean\n}\n\nexport interface Invocation {\n  global: GlobalOptions\n  module?: string\n  verb?: string\n  actionArgv: string[]\n}\n\nexport interface ParsedCommandArgs {\n  input: Record<string, unknown>\n  scoped: GlobalOptions\n  help: boolean\n}\n\nconst STRING_GLOBALS = new Map<string, keyof GlobalOptions>([\n  ['config-dir', 'configDir'],\n  ['profile', 'profile'],\n  ['zone', 'zone'],\n  ['endpoint', 'endpoint'],\n  ['identity', 'identity'],\n  ['session-token', 'sessionToken'],\n  ['session-token-file', 'sessionTokenFile'],\n  ['output', 'output'],\n  ['input', 'input'],\n  ['timeout', 'timeout'],\n  ['trace-id', 'traceId'],\n  ['idempotency-key', 'idempotencyKey'],\n])\n\nconst REPEATABLE_STRING_GLOBALS = new Map<string, keyof GlobalOptions>([\n  ['allow-read', 'allowRead'],\n])\n\nconst BOOLEAN_GLOBALS = new Map<string, keyof GlobalOptions>([\n  ['cli', 'cli'],\n  ['wait', 'wait'],\n  ['non-interactive', 'nonInteractive'],\n  ['yes', 'yes'],\n  ['no-color', 'noColor'],\n  ['verbose', 'verbose'],\n  ['help', 'help'],\n  ['version', 'version'],\n])\n\nconst REPL_SCOPED_STRING_GLOBALS = new Set([\n  'input',\n  'timeout',\n  'trace-id',\n  'idempotency-key',\n  'output',\n])\nconst REPL_SCOPED_BOOLEAN_GLOBALS = new Set(['wait', 'yes'])\n\nexport function parseInvocation(argv: string[]): Invocation {\n  const global: GlobalOptions = {}\n  let index = 0\n  while (index < argv.length) {\n    const token = argv[index]\n    if (token === '-h') {\n      setGlobal(global, 'help', true)\n      index += 1\n      continue\n    }\n    if (token === '--') {\n      index += 1\n      break\n    }\n    if (!token.startsWith('--')) break\n    const parsed = splitLongOption(token)\n    const booleanProperty = BOOLEAN_GLOBALS.get(parsed.name)\n    if (booleanProperty) {\n      if (parsed.inlineValue !== undefined) {\n        throw new UsageError('INVALID_ARGUMENT', `--${parsed.name} does not accept a value`)\n      }\n      setGlobal(global, booleanProperty, true)\n      index += 1\n      continue\n    }\n    const stringProperty = STRING_GLOBALS.get(parsed.name)\n    const repeatableStringProperty = REPEATABLE_STRING_GLOBALS.get(parsed.name)\n    if (!stringProperty && !repeatableStringProperty) {\n      throw new UsageError('UNKNOWN_OPTION', `unknown global option: --${parsed.name}`)\n    }\n    const { value, consumed } = readOptionValue(argv, index, parsed)\n    if (repeatableStringProperty === 'allowRead') {\n      global.allowRead = [...(global.allowRead ?? []), value]\n    } else {\n      setGlobal(global, stringProperty!, normalizeGlobalValue(parsed.name, value))\n    }\n    index += consumed\n  }\n\n  const module = argv[index]\n  const verb = argv[index + 1]\n  const actionArgv = module ? argv.slice(index + (verb ? 2 : 1)) : []\n  if (module?.startsWith('-')) {\n    throw new UsageError(\n      'INVALID_ARGUMENT',\n      `global options must appear before the module: ${module}`,\n    )\n  }\n  return { global, module, verb, actionArgv }\n}\n\nexport function parseCommandArgs(\n  command: RegisteredCommand,\n  argv: string[],\n  inputObject: Record<string, unknown> | undefined,\n  allowReplScopedGlobals = false,\n  deferValidation = false,\n): ParsedCommandArgs {\n  const scoped: GlobalOptions = {}\n  if (command.module === 'obj' && command.verb === 'call') {\n    if (inputObject) throw new UsageError('INVALID_ARGUMENT', 'pass xcall arguments directly')\n    return { input: { argv }, scoped, help: false }\n  }\n  const replScoped = (parsed: LongOption, args: string[], index: number): number | undefined => {\n    if (!allowReplScopedGlobals) return undefined\n    if (REPL_SCOPED_BOOLEAN_GLOBALS.has(parsed.name)) {\n      if (parsed.inlineValue !== undefined) {\n        throw new UsageError('INVALID_ARGUMENT', `--${parsed.name} does not accept a value`)\n      }\n      setGlobal(scoped, BOOLEAN_GLOBALS.get(parsed.name)!, true)\n      return 1\n    }\n    if (REPL_SCOPED_STRING_GLOBALS.has(parsed.name)) {\n      const property = STRING_GLOBALS.get(parsed.name)!\n      const { value, consumed } = readOptionValue(args, index, parsed)\n      setGlobal(scoped, property, normalizeGlobalValue(parsed.name, value))\n      return consumed\n    }\n    if (\n      STRING_GLOBALS.has(parsed.name) || REPEATABLE_STRING_GLOBALS.has(parsed.name) ||\n      BOOLEAN_GLOBALS.has(parsed.name)\n    ) {\n      throw new UsageError(\n        'SESSION_OPTION_FROZEN',\n        `--${parsed.name} is frozen for the interactive session`,\n      )\n    }\n    return undefined\n  }\n  return usage(() => {\n    const parsed = parseArgv(command, argv, replScoped)\n    if (!deferValidation) {\n      checkRequiredPositionals(command.positionals ?? [], parsed.positionalCount, inputObject)\n    }\n    const input = mergeCommandInput(inputObject, parsed.input)\n    if (!deferValidation) validateSchemaCore(input, command.inputSchema, 'input')\n    return { input, scoped, help: parsed.help }\n  })\n}\n\nexport function parseDuration(value: string): number {\n  const match = /^(\\d+)(ms|s|m|h)$/.exec(value.trim())\n  if (!match) {\n    throw new UsageError('INVALID_DURATION', `invalid duration: ${value}`)\n  }\n  const amount = Number(match[1])\n  const scale = match[2] === 'ms'\n    ? 1\n    : match[2] === 's'\n    ? 1_000\n    : match[2] === 'm'\n    ? 60_000\n    : 3_600_000\n  const result = amount * scale\n  if (!Number.isSafeInteger(result) || result <= 0) {\n    throw new UsageError('INVALID_DURATION', `invalid duration: ${value}`)\n  }\n  return result\n}\n\nexport function parseShellLine(line: string): string[] {\n  return usage(() => parseShellLineCore(line))\n}\n\nexport function validateSchema(value: unknown, schema: JsonSchema, path: string): void {\n  usage(() => validateSchemaCore(value, schema, path))\n}\n\n/** Usage errors of the shared parser become the CLI's `UsageError` (same code and message). */\nfunction usage<T>(f: () => T): T {\n  try {\n    return f()\n  } catch (error) {\n    if (error instanceof CommandArgsError) throw new UsageError(error.code, error.message)\n    throw error\n  }\n}\n\nfunction readOptionValue(\n  argv: string[],\n  index: number,\n  option: LongOption,\n): { value: string; consumed: number } {\n  return usage(() => readOptionValueCore(argv, index, option))\n}\n\n\n\n\n\n\nfunction normalizeGlobalValue(name: string, value: string): string | OutputFormat {\n  if (name === 'output') {\n    if (!OUTPUT_FORMATS.includes(value as OutputFormat)) {\n      throw new UsageError('INVALID_OUTPUT_FORMAT', `invalid output format: ${value}`)\n    }\n    return value as OutputFormat\n  }\n  return value\n}\n\nfunction setGlobal<K extends keyof GlobalOptions>(\n  target: GlobalOptions,\n  property: K,\n  value: GlobalOptions[K],\n): void {\n  if (target[property] !== undefined) {\n    throw new UsageError('DUPLICATE_ARGUMENT', `option provided more than once: ${property}`)\n  }\n  target[property] = value\n}\n","export type HostKind = 'node' | 'deno'\nexport type DistributionKind = 'developer' | 'system'\nexport type HostErrorCode =\n  | 'NotFound'\n  | 'PermissionDenied'\n  | 'AlreadyExists'\n  | 'InvalidInput'\n  | 'Unknown'\n\nexport class HostError extends Error {\n  readonly code: HostErrorCode\n  readonly path?: string\n\n  constructor(code: HostErrorCode, message: string, path?: string, cause?: unknown) {\n    super(message, { cause })\n    this.name = 'HostError'\n    this.code = code\n    this.path = path\n  }\n}\n\nexport function isHostError(error: unknown, code: HostErrorCode): error is HostError {\n  return error instanceof HostError && error.code === code\n}\n\nexport interface HostFileInfo {\n  isFile: boolean\n  isDirectory: boolean\n  isSymlink: boolean\n  size: number\n  mode: number | null\n  mtime: Date | null\n  dev: number | null\n  ino: number | null\n}\n\nexport interface HostDirEntry {\n  name: string\n  isFile: boolean\n  isDirectory: boolean\n  isSymlink: boolean\n}\n\nexport interface HostFile {\n  read(buffer: Uint8Array): Promise<number | null>\n  write(buffer: Uint8Array): Promise<number>\n  seek(offset: number): Promise<number>\n  stat(): Promise<HostFileInfo>\n  sync(): Promise<void>\n  close(): Promise<void>\n}\n\nexport interface HostHash {\n  update(bytes: Uint8Array): void\n  digestHex(): string\n}\n\nexport interface HostCommandOutput {\n  success: boolean\n  code: number\n  stdout: Uint8Array\n  stderr: Uint8Array\n}\n\n/** A child process the tool talks to line by line (a wish macro's stdio bridge). */\nexport interface HostChild {\n  /** Lines the child writes to stdout, without the newline. */\n  lines(): AsyncIterable<string>\n  writeLine(line: string): Promise<void>\n  closeInput(): Promise<void>\n  /** Everything the child wrote to stderr, once it exits. */\n  readonly stderr: Promise<string>\n  readonly status: Promise<number>\n  kill(): void\n}\n\nexport interface HostPath {\n  readonly sep: string\n  basename(path: string): string\n  dirname(path: string): string\n  isAbsolute(path: string): boolean\n  join(...parts: string[]): string\n  relative(from: string, to: string): string\n  resolve(...parts: string[]): string\n  parse(path: string): { root: string; dir: string; base: string; ext: string; name: string }\n}\n\nexport interface DistributionPolicy {\n  readonly name: 'developer-default' | 'system-default'\n  readonly distribution: DistributionKind\n  readonly packageRoot: string\n  readonly readPaths: readonly string[]\n  readonly writePaths: readonly string[]\n  readonly environment: readonly string[]\n  readonly subprocesses: readonly string[]\n  readonly network: boolean\n  readonly buckyosRoot?: string\n}\n\nexport interface ToolHost {\n  readonly kind: HostKind\n  readonly runtimeName: string\n  readonly runtimeVersion: string\n  readonly platform: string\n  readonly arch: string\n  readonly pid: number\n  readonly executable: string\n  readonly runtimeExecutable: string\n  readonly policy: DistributionPolicy\n  readonly path: HostPath\n\n  cwd(): string\n  homeDir(): string\n  env(name: string): string | undefined\n  exit(code: number): never\n  setExitCode(code: number): void\n\n  readTextFile(path: string): Promise<string>\n  readFile(path: string): Promise<Uint8Array>\n  writeTextFile(\n    path: string,\n    value: string,\n    options?: { createNew?: boolean; mode?: number },\n  ): Promise<void>\n  writeFile(\n    path: string,\n    value: Uint8Array,\n    options?: { createNew?: boolean; mode?: number },\n  ): Promise<void>\n  readDir(path: string): Promise<HostDirEntry[]>\n  stat(path: string): Promise<HostFileInfo>\n  lstat(path: string): Promise<HostFileInfo>\n  realPath(path: string): Promise<string>\n  makeTempDir(options?: { dir?: string; prefix?: string }): Promise<string>\n  makeTempFile(options?: { dir?: string; prefix?: string }): Promise<string>\n  rename(from: string, to: string): Promise<void>\n  remove(path: string, options?: { recursive?: boolean }): Promise<void>\n  mkdir(path: string, options?: { recursive?: boolean; mode?: number }): Promise<void>\n  chmod(path: string, mode: number): Promise<void>\n  symlink(target: string, path: string): Promise<void>\n  copyFile(from: string, to: string): Promise<void>\n  open(\n    path: string,\n    options: { read?: boolean; write?: boolean; createNew?: boolean; mode?: number },\n  ): Promise<HostFile>\n\n  // Policy check without a filesystem side effect: rejects paths outside the\n  // distribution policy (or escaping it through symlinks) with PermissionDenied.\n  assertAccess(path: string, operation: 'read' | 'write'): Promise<void>\n\n  createHash(algorithm: 'sha256'): HostHash\n  gzipFile(source: string, destination: string): Promise<void>\n  run(command: string, args: string[]): Promise<HostCommandOutput>\n  runGzip(command: string, args: string[], destination: string): Promise<HostCommandOutput>\n  /** Start `command` in `cwd` with exactly `env` (nothing inherited), stdin and stdout piped line by line. */\n  spawn(command: string, args: string[], options: { cwd: string; env: Record<string, string> }): HostChild\n\n  stdout(value: string | Uint8Array): Promise<void>\n  stderr(value: string | Uint8Array): Promise<void>\n  readStdin(): Promise<string>\n  readLine(prompt: string): Promise<string | null>\n  readSecret(prompt: string): Promise<string>\n  inputIsTerminal(): boolean\n  createLineReader(options: {\n    history: string[]\n    historySize: number\n    completer(line: string): [string[], string]\n    onSigint(): void\n  }): HostLineReader\n}\n\nexport interface HostLineReader extends AsyncIterable<string> {\n  write(value: string): void\n  setPrompt(value: string): void\n  prompt(): void\n  close(): void\n}\n\nlet activeHost: ToolHost | undefined\n\nexport function installHost(host: ToolHost): void {\n  if (activeHost && activeHost !== host) throw new Error('CLI host is already installed')\n  activeHost = host\n}\n\nexport function getHost(): ToolHost {\n  if (!activeHost) throw new Error('CLI host was not injected by a launcher')\n  return activeHost\n}\n\nexport function resetHostForTest(): void {\n  activeHost = undefined\n}\n\nexport const TOOL_ENVIRONMENT_NAMES = [\n  'HOME',\n  'USERPROFILE',\n  'APPDATA',\n  'BUCKYOS_TOOL_CONFIG_DIR',\n  'BUCKYOS_TOOL_PROFILE',\n  'BUCKYOS_TOOL_ZONE',\n  'BUCKYOS_TOOL_ENDPOINT',\n  'BUCKYOS_TOOL_IDENTITY',\n  'BUCKYOS_TOOL_OUTPUT',\n  'BUCKYOS_APPCLIENT_SESSION_TOKEN',\n  'BUCKYOS_ROOT',\n  'SOURCE_DATE_EPOCH',\n] as const\n\ninterface PolicyOptions {\n  /** The runtime running the tool (Deno): `aiws run-exec` / `run-program` run a wish macro with it. */\n  runtimeExecutable?: string\n  distribution: DistributionKind\n  argv: string[]\n  cwd: string\n  packageRoot: string\n  homeDir: string\n  environment: Record<string, string | undefined>\n  path: HostPath\n  buckyosRoot?: string\n}\n\nexport function buildDistributionPolicy(options: PolicyOptions): DistributionPolicy {\n  const { argv, cwd, packageRoot, homeDir, environment, path } = options\n  const buckyosRoot = path.resolve(\n    options.buckyosRoot ?? environment.BUCKYOS_ROOT ?? defaultBuckyosRoot(options),\n  )\n  const configRoot = path.resolve(\n    environment.BUCKYOS_TOOL_CONFIG_DIR ?? path.join(homeDir, '.buckyos_tool'),\n  )\n  const readPaths = new Set([\n    path.resolve(packageRoot),\n    path.resolve(cwd),\n    configRoot,\n    path.resolve(path.join(homeDir, '.buckyos')),\n    path.resolve(path.join(homeDir, '.buckycli')),\n  ])\n  const writePaths = new Set([path.resolve(cwd), configRoot])\n  if (options.distribution === 'system') readPaths.add(buckyosRoot)\n\n  const parsed = collectArgumentPaths(argv)\n  if (\n    options.distribution === 'system' && parsed.module === 'app' &&\n    ['fetch', 'install'].includes(parsed.verb ?? '')\n  ) {\n    writePaths.add(path.join(buckyosRoot, 'cache', 'control_panel', 'pikg_staging', 'incoming'))\n  }\n  for (const candidate of parsed.read) readPaths.add(resolveInputPath(candidate, cwd, path))\n  for (const candidate of parsed.readParents) {\n    readPaths.add(path.dirname(resolveInputPath(candidate, cwd, path)))\n  }\n  for (const candidate of parsed.write) writePaths.add(resolveInputPath(candidate, cwd, path))\n  for (const candidate of parsed.writeParents) {\n    writePaths.add(path.dirname(resolveInputPath(candidate, cwd, path)))\n  }\n  const subprocesses = parsed.module === 'pikg' && ['init', 'build'].includes(parsed.verb ?? '')\n    ? ['docker']\n    : parsed.module === 'aiws' && ['run-exec', 'run-program'].includes(parsed.verb ?? '') && options.runtimeExecutable\n    ? [options.runtimeExecutable]\n    : options.distribution === 'system' && parsed.module === 'obj' && parsed.verb === 'call'\n    ? [path.join(buckyosRoot, 'bin', 'opendan', path.sep === '\\\\' ? 'agent_tool.exe' : 'agent_tool')]\n    : []\n  const network = parsed.module !== undefined &&\n    !['pikg', 'command', 'completion', 'config', 'provision'].includes(parsed.module)\n  const allowedEnvironment = options.distribution === 'developer'\n    ? TOOL_ENVIRONMENT_NAMES.filter((name) => name !== 'BUCKYOS_ROOT')\n    : TOOL_ENVIRONMENT_NAMES\n\n  return Object.freeze({\n    name: options.distribution === 'system' ? 'system-default' : 'developer-default',\n    distribution: options.distribution,\n    packageRoot: path.resolve(packageRoot),\n    readPaths: Object.freeze([...readPaths]),\n    writePaths: Object.freeze([...writePaths]),\n    environment: Object.freeze(allowedEnvironment),\n    subprocesses: Object.freeze(subprocesses),\n    network,\n    ...(options.distribution === 'system' ? { buckyosRoot } : {}),\n  })\n}\n\nfunction defaultBuckyosRoot(options: PolicyOptions): string {\n  if (options.path.sep === '\\\\') {\n    return options.environment.APPDATA\n      ? options.path.join(options.environment.APPDATA, 'buckyos')\n      : options.path.join(options.homeDir, 'AppData', 'Roaming', 'buckyos')\n  }\n  return '/opt/buckyos'\n}\n\nfunction resolveInputPath(value: string, cwd: string, path: HostPath): string {\n  return path.isAbsolute(value) ? path.resolve(value) : path.resolve(cwd, value)\n}\n\nfunction collectArgumentPaths(argv: string[]): {\n  read: string[]\n  readParents: string[]\n  write: string[]\n  writeParents: string[]\n  module?: string\n  verb?: string\n} {\n  const read: string[] = []\n  const readParents: string[] = []\n  const write: string[] = []\n  const writeParents: string[] = []\n  let module: string | undefined\n  let verb: string | undefined\n  let positional = 0\n  const valueOptions = new Set([\n    'profile',\n    'zone',\n    'endpoint',\n    'identity',\n    'session-token',\n    'output',\n    'timeout',\n    'trace-id',\n    'idempotency-key',\n    'from',\n    'app-class',\n    'owner',\n    'policy',\n    'data',\n    'strategy',\n    'kind',\n    'source',\n    'version',\n    'name',\n  ])\n  const booleanOptions = new Set([\n    'replace',\n    'cli',\n    'wait',\n    'non-interactive',\n    'yes',\n    'no-color',\n    'verbose',\n    'help',\n    'version',\n  ])\n  for (let index = 0; index < argv.length; index++) {\n    const token = argv[index]\n    if (!module && !token.startsWith('-')) {\n      module = token\n      continue\n    }\n    if (module && !verb && !token.startsWith('-')) {\n      verb = token\n      continue\n    }\n    if (token.startsWith('--')) {\n      const equal = token.indexOf('=')\n      const name = token.slice(2, equal < 0 ? undefined : equal)\n      if (booleanOptions.has(name)) continue\n      const inline = equal < 0 ? undefined : token.slice(equal + 1)\n      const value = inline ?? argv[index + 1]\n      if (inline === undefined && value !== undefined && !value.startsWith('--')) index++\n      if (value === undefined) continue\n      if (name === 'config-dir') {\n        read.push(value)\n        write.push(value)\n      } else if (name === 'allow-read') {\n        read.push(value)\n      } else if (['input', 'session-token-file', 'pikg'].includes(name)) {\n        if (value !== '-') read.push(value)\n      } else if (name === 'catalog' && module === 'pikg') {\n        read.push(value)\n      } else if (name === 'source' && module === 'pikg') {\n        read.push(value)\n      } else if (name === 'plan') {\n        read.push(value)\n        if (module === 'app' && verb === 'fetch') write.push(value)\n      } else if (name === 'path') write.push(value)\n      else if (name === 'app-doc' && module === 'app' && verb === 'publish') read.push(value)\n      else if (name === 'file' && module === 'system-config' && verb === 'set-file') {\n        read.push(value)\n      } else if (name === 'root' && module === 'provision') {\n        // status/check read the target root; activate also writes it.\n        read.push(value)\n        if (verb === 'activate') write.push(value)\n      } else if (name === 'owner-key-backup' && module === 'provision') {\n        // check inspects the backup location; activate creates the file there.\n        readParents.push(value)\n        if (verb === 'activate') writeParents.push(value)\n      } else if (!valueOptions.has(name)) continue\n      continue\n    }\n    if (module === 'app' && ['fetch', 'install'].includes(verb ?? '') && positional++ === 0) {\n      if (!/^https?:\\/\\//i.test(token)) read.push(token)\n    } else if (module === 'skill' && verb === 'install' && positional++ === 0) {\n      read.push(token)\n    } else if (module === 'pikg' && positional++ === 0) {\n      read.push(token)\n      if (verb === 'init' || verb === 'pack') write.push(token)\n      else if (verb === 'build' || verb === 'clean') writeParents.push(token)\n    }\n  }\n  return { read, readParents, write, writeParents, module, verb }\n}\n\nexport function policyView(host: ToolHost): Record<string, unknown> {\n  return {\n    executable: host.executable,\n    runtime_executable: host.runtimeExecutable,\n    distribution: host.policy.distribution,\n    policy: host.policy.name,\n    host: host.kind,\n    runtime: host.runtimeName,\n    runtime_version: host.runtimeVersion,\n    platform: host.platform,\n    arch: host.arch,\n    package_root: host.policy.packageRoot,\n    read_paths: [...host.policy.readPaths],\n    write_paths: [...host.policy.writePaths],\n    environment: [...host.policy.environment],\n    subprocesses: [...host.policy.subprocesses],\n    network: host.policy.network,\n  }\n}\n\nexport async function readDistributionManifest(\n  host: ToolHost = getHost(),\n): Promise<Record<string, unknown> | null> {\n  const path = host.path.join(host.policy.packageRoot, 'distribution.json')\n  try {\n    const value = JSON.parse(await host.readTextFile(path)) as unknown\n    return value && typeof value === 'object' && !Array.isArray(value)\n      ? value as Record<string, unknown>\n      : null\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) return null\n    throw error\n  }\n}\n\nexport function distributionManifestView(\n  manifest: Record<string, unknown> | null,\n): Record<string, unknown> | null {\n  if (!manifest) return null\n  const { npm_files: files, ...summary } = manifest\n  return {\n    ...summary,\n    npm_file_count: Array.isArray(files) ? files.length : null,\n  }\n}\n","import type { GlobalOptions, OutputFormat } from './argv.ts'\nimport { parseDuration } from './argv.ts'\nimport { ToolError, UsageError } from './errors.ts'\nimport { getHost, isHostError } from '../runtime/host.ts'\n\nconst dirname = (path: string) => getHost().path.dirname(path)\nconst isAbsolute = (path: string) => getHost().path.isAbsolute(path)\nconst join = (...parts: string[]) => getHost().path.join(...parts)\nconst resolve = (...parts: string[]) => getHost().path.resolve(...parts)\n\nexport interface ToolConfig {\n  schema_version: 1\n  default_profile?: string\n  output?: OutputFormat\n}\n\nexport interface ProfileConfig {\n  schema_version: 1\n  zone?: string\n  endpoint?: string\n  identity?: string\n  default_protocol?: 'http://' | 'https://'\n  output?: OutputFormat\n}\n\nexport interface ImplicitDeviceIdentity {\n  did: string\n  name: string\n  zoneDid: string\n  buckyosRoot: string\n  nodeIdentityPath: string\n  publicRoot: string\n  securityRoot: string\n}\n\nexport interface ResolvedConfig {\n  configDir: string\n  profileName?: string\n  zone?: string\n  endpoint?: string\n  identity?: string\n  identityRoot?: string\n  securityRoot?: string\n  sessionToken?: string\n  sessionTokenFile?: string\n  output: OutputFormat\n  defaultProtocol: 'http://' | 'https://'\n  timeoutMs: number\n  traceId?: string\n  idempotencyKey?: string\n  wait: boolean\n  nonInteractive: boolean\n  yes: boolean\n  noColor: boolean\n  verbose: boolean\n  implicitDeviceIdentity?: ImplicitDeviceIdentity\n  sources: Record<string, string>\n}\n\nexport type Environment = Record<string, string | undefined>\n\nexport const ENVIRONMENT_NAMES = [\n  'HOME',\n  'USERPROFILE',\n  'APPDATA',\n  'BUCKYOS_TOOL_CONFIG_DIR',\n  'BUCKYOS_TOOL_PROFILE',\n  'BUCKYOS_TOOL_ZONE',\n  'BUCKYOS_TOOL_ENDPOINT',\n  'BUCKYOS_TOOL_IDENTITY',\n  'BUCKYOS_TOOL_OUTPUT',\n  'BUCKYOS_APPCLIENT_SESSION_TOKEN',\n  'BUCKYOS_ROOT',\n] as const\n\nconst PROFILE_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport class ConfigStore {\n  readonly root: string\n\n  constructor(root: string) {\n    this.root = resolve(root)\n  }\n\n  async readConfig(): Promise<ToolConfig> {\n    return await this.#readJson<ToolConfig>(join(this.root, 'config.json'), {\n      schema_version: 1,\n    })\n  }\n\n  async readProfile(name: string): Promise<ProfileConfig | undefined> {\n    validateProfileName(name)\n    return await this.#readJson<ProfileConfig>(this.profilePath(name), undefined)\n  }\n\n  async listProfiles(): Promise<string[]> {\n    const directory = join(this.root, 'profiles')\n    try {\n      const names: string[] = []\n      for (const entry of await getHost().readDir(directory)) {\n        if (entry.isFile && entry.name.endsWith('.json')) {\n          const name = entry.name.slice(0, -5)\n          if (PROFILE_NAME.test(name)) names.push(name)\n        }\n      }\n      return names.sort()\n    } catch (error) {\n      if (isHostError(error, 'NotFound')) return []\n      throw error\n    }\n  }\n\n  async writeConfig(config: ToolConfig): Promise<void> {\n    validateToolConfig(config, 'config.json')\n    await this.#atomicWrite(join(this.root, 'config.json'), config)\n  }\n\n  async writeProfile(name: string, profile: ProfileConfig): Promise<void> {\n    validateProfileName(name)\n    validateProfileConfig(profile, `profiles/${name}.json`)\n    await this.#atomicWrite(this.profilePath(name), profile)\n  }\n\n  profilePath(name: string): string {\n    validateProfileName(name)\n    return join(this.root, 'profiles', `${name}.json`)\n  }\n\n  historyPath(): string {\n    return join(this.root, 'state', 'repl_history')\n  }\n\n  async #readJson<T>(path: string, missing: T | undefined): Promise<T> {\n    try {\n      const parsed = JSON.parse(await getHost().readTextFile(path)) as unknown\n      if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n        throw new UsageError('INVALID_CONFIG', `${path} must contain a JSON object`)\n      }\n      if ((parsed as Record<string, unknown>).schema_version !== 1) {\n        throw new UsageError(\n          'UNSUPPORTED_CONFIG_VERSION',\n          `${path} has an unsupported schema_version`,\n        )\n      }\n      if (path.endsWith('config.json') && !path.includes('/profiles/')) {\n        validateToolConfig(parsed as ToolConfig, path)\n      } else {\n        validateProfileConfig(parsed as ProfileConfig, path)\n      }\n      return parsed as T\n    } catch (error) {\n      if (isHostError(error, 'NotFound') && missing !== undefined) return missing\n      if (error instanceof SyntaxError) {\n        throw new UsageError('INVALID_CONFIG', `${path} is not valid JSON`)\n      }\n      throw error\n    }\n  }\n\n  async #atomicWrite(path: string, value: unknown): Promise<void> {\n    const host = getHost()\n    await host.mkdir(dirname(path), { recursive: true, mode: 0o700 })\n    const temporary = `${path}.tmp-${host.pid}-${crypto.randomUUID()}`\n    const body = `${JSON.stringify(value, null, 2)}\\n`\n    try {\n      await host.writeTextFile(temporary, body, { mode: 0o600, createNew: true })\n      await host.rename(temporary, path)\n      if (host.platform !== 'windows') await host.chmod(path, 0o600)\n    } catch (error) {\n      try {\n        await host.remove(temporary)\n      } catch (cleanupError) {\n        void cleanupError\n      }\n      throw error\n    }\n  }\n}\n\nexport async function resolveConfig(\n  explicit: GlobalOptions,\n  environment: Environment = readEnvironment(),\n  options: { interactive?: boolean; cwd?: string; homeDir?: string } = {},\n): Promise<{ resolved: ResolvedConfig; store: ConfigStore }> {\n  const cwd = options.cwd ?? getHost().cwd()\n  const homeDir = options.homeDir ?? environment.HOME ?? environment.USERPROFILE ??\n    getHost().homeDir()\n  const configDir = resolveConfigRoot(explicit, environment, cwd, homeDir)\n  const store = new ConfigStore(configDir)\n  const config = await store.readConfig()\n  const profileName = explicit.profile ?? environment.BUCKYOS_TOOL_PROFILE ?? config.default_profile\n  const profile = profileName ? await store.readProfile(profileName) : undefined\n  if (profileName && !profile) {\n    throw new UsageError('PROFILE_NOT_FOUND', `profile not found: ${profileName}`)\n  }\n\n  const sources: Record<string, string> = {\n    config_dir: sourceOf(\n      explicit.configDir,\n      environment.BUCKYOS_TOOL_CONFIG_DIR,\n      undefined,\n      'default',\n    ),\n  }\n  const zone = select(\n    'zone',\n    explicit.zone,\n    environment.BUCKYOS_TOOL_ZONE,\n    profile?.zone,\n    undefined,\n    sources,\n  )\n  const endpoint = select(\n    'endpoint',\n    explicit.endpoint,\n    environment.BUCKYOS_TOOL_ENDPOINT,\n    profile?.endpoint,\n    undefined,\n    sources,\n  )\n  const identity = select(\n    'identity',\n    explicit.identity,\n    environment.BUCKYOS_TOOL_IDENTITY,\n    profile?.identity,\n    undefined,\n    sources,\n  )\n  let output: OutputFormat\n  if (options.interactive && explicit.output === undefined) {\n    output = 'table'\n    sources.output = 'interactive-default'\n  } else {\n    output = select(\n      'output',\n      explicit.output,\n      asOutput(environment.BUCKYOS_TOOL_OUTPUT),\n      profile?.output,\n      config.output ?? 'json',\n      sources,\n    )!\n  }\n  const defaultProtocol = profile?.default_protocol ?? inferProtocol(endpoint) ?? 'https://'\n  const timeoutMs = explicit.timeout ? parseDuration(explicit.timeout) : DEFAULT_TIMEOUT_MS\n\n  if (endpoint) validateEndpoint(endpoint)\n  const sessionToken = explicit.sessionToken ?? environment.BUCKYOS_APPCLIENT_SESSION_TOKEN\n  if (sessionToken) sources.session_token = explicit.sessionToken ? 'argument' : 'environment'\n  if (profileName) {\n    sources.profile = explicit.profile\n      ? 'argument'\n      : environment.BUCKYOS_TOOL_PROFILE\n      ? 'environment'\n      : 'config'\n  }\n\n  return {\n    store,\n    resolved: {\n      configDir,\n      profileName,\n      zone,\n      endpoint,\n      identity,\n      sessionToken,\n      sessionTokenFile: explicit.sessionTokenFile,\n      output,\n      defaultProtocol,\n      timeoutMs,\n      traceId: explicit.traceId,\n      idempotencyKey: explicit.idempotencyKey,\n      wait: explicit.wait ?? false,\n      nonInteractive: explicit.nonInteractive ?? false,\n      yes: explicit.yes ?? false,\n      noColor: explicit.noColor ?? false,\n      verbose: explicit.verbose ?? false,\n      sources,\n    },\n  }\n}\n\nexport function resolveConfigRoot(\n  explicit: GlobalOptions,\n  environment: Environment,\n  cwd = getHost().cwd(),\n  homeDir = environment.HOME ?? environment.USERPROFILE ?? getHost().homeDir(),\n): string {\n  const value = explicit.configDir ?? environment.BUCKYOS_TOOL_CONFIG_DIR ??\n    join(homeDir, '.buckyos_tool')\n  return isAbsolute(value) ? value : resolve(cwd, value)\n}\n\nexport function localResolvedConfig(\n  explicit: GlobalOptions,\n  environment: Environment = readEnvironment(),\n  options: { cwd?: string; homeDir?: string; interactive?: boolean } = {},\n): { resolved: ResolvedConfig; store: ConfigStore } {\n  const cwd = options.cwd ?? getHost().cwd()\n  const homeDir = options.homeDir ?? environment.HOME ?? environment.USERPROFILE ??\n    getHost().homeDir()\n  const configDir = resolveConfigRoot(explicit, environment, cwd, homeDir)\n  const output = options.interactive && explicit.output === undefined\n    ? 'table'\n    : explicit.output ?? asOutput(environment.BUCKYOS_TOOL_OUTPUT) ?? 'json'\n  return {\n    store: new ConfigStore(configDir),\n    resolved: {\n      configDir,\n      profileName: explicit.profile ?? environment.BUCKYOS_TOOL_PROFILE,\n      zone: explicit.zone ?? environment.BUCKYOS_TOOL_ZONE,\n      endpoint: explicit.endpoint ?? environment.BUCKYOS_TOOL_ENDPOINT,\n      identity: explicit.identity ?? environment.BUCKYOS_TOOL_IDENTITY,\n      sessionToken: explicit.sessionToken ?? environment.BUCKYOS_APPCLIENT_SESSION_TOKEN,\n      sessionTokenFile: explicit.sessionTokenFile,\n      output,\n      defaultProtocol: inferProtocol(explicit.endpoint ?? environment.BUCKYOS_TOOL_ENDPOINT) ??\n        'https://',\n      timeoutMs: explicit.timeout ? parseDuration(explicit.timeout) : DEFAULT_TIMEOUT_MS,\n      traceId: explicit.traceId,\n      idempotencyKey: explicit.idempotencyKey,\n      wait: explicit.wait ?? false,\n      nonInteractive: explicit.nonInteractive ?? false,\n      yes: explicit.yes ?? false,\n      noColor: explicit.noColor ?? false,\n      verbose: explicit.verbose ?? false,\n      sources: {\n        config_dir: sourceOf(\n          explicit.configDir,\n          environment.BUCKYOS_TOOL_CONFIG_DIR,\n          undefined,\n          'default',\n        ),\n        output: explicit.output\n          ? 'argument'\n          : environment.BUCKYOS_TOOL_OUTPUT\n          ? 'environment'\n          : 'default',\n      },\n    },\n  }\n}\n\nexport function readEnvironment(): Environment {\n  const allowed = getHost().policy.environment\n  return Object.fromEntries(\n    ENVIRONMENT_NAMES.map((\n      name,\n    ) => [name, allowed.includes(name) ? getHost().env(name) : undefined]),\n  )\n}\n\nexport function effectiveConfigView(config: ResolvedConfig): Record<string, unknown> {\n  return {\n    schema_version: 1,\n    config_dir: config.configDir,\n    profile: config.profileName ?? null,\n    zone: config.zone ?? null,\n    endpoint: redactUrl(config.endpoint),\n    identity: config.identity ?? null,\n    identity_root: config.identityRoot ?? null,\n    security_root: config.securityRoot ? '[CONFIGURED]' : null,\n    output: config.output,\n    default_protocol: config.defaultProtocol,\n    timeout_ms: config.timeoutMs,\n    session_token: config.sessionToken || config.sessionTokenFile\n      ? {\n        present: true,\n        source: config.sources.session_token ?? (config.sessionTokenFile ? 'file' : 'unknown'),\n        summary: '[REDACTED]',\n      }\n      : { present: false },\n    sources: config.sources,\n  }\n}\n\nexport function validateProfileName(name: string): void {\n  if (!PROFILE_NAME.test(name)) {\n    throw new UsageError('INVALID_PROFILE_NAME', `invalid profile name: ${name}`)\n  }\n}\n\nfunction validateToolConfig(config: ToolConfig, source: string): void {\n  if (config.schema_version !== 1) {\n    throw new UsageError(\n      'UNSUPPORTED_CONFIG_VERSION',\n      `${source} has an unsupported schema_version`,\n    )\n  }\n  if (config.default_profile !== undefined) validateProfileName(config.default_profile)\n  if (config.output !== undefined) asOutput(config.output, source)\n  rejectUnknownKeys(config as unknown as Record<string, unknown>, [\n    'schema_version',\n    'default_profile',\n    'output',\n  ], source)\n}\n\nfunction validateProfileConfig(profile: ProfileConfig, source: string): void {\n  if (profile.schema_version !== 1) {\n    throw new UsageError(\n      'UNSUPPORTED_CONFIG_VERSION',\n      `${source} has an unsupported schema_version`,\n    )\n  }\n  if (profile.output !== undefined) asOutput(profile.output, source)\n  if (\n    profile.default_protocol !== undefined &&\n    !['http://', 'https://'].includes(profile.default_protocol)\n  ) {\n    throw new UsageError('INVALID_CONFIG', `${source}.default_protocol must be http:// or https://`)\n  }\n  if (profile.endpoint) validateEndpoint(profile.endpoint)\n  rejectUnknownKeys(\n    profile as unknown as Record<string, unknown>,\n    ['schema_version', 'zone', 'endpoint', 'identity', 'default_protocol', 'output'],\n    source,\n  )\n}\n\nfunction rejectUnknownKeys(\n  value: Record<string, unknown>,\n  allowed: string[],\n  source: string,\n): void {\n  const allowedSet = new Set(allowed)\n  const unknown = Object.keys(value).filter((key) => !allowedSet.has(key))\n  if (unknown.length > 0) {\n    throw new UsageError(\n      'INVALID_CONFIG',\n      `${source} contains unsupported fields: ${unknown.join(', ')}`,\n    )\n  }\n}\n\nfunction asOutput(\n  value: string | undefined,\n  source = 'BUCKYOS_TOOL_OUTPUT',\n): OutputFormat | undefined {\n  if (value === undefined) return undefined\n  if (!['json', 'jsonl', 'table', 'text', 'raw'].includes(value)) {\n    throw new UsageError('INVALID_OUTPUT_FORMAT', `${source} has invalid output format: ${value}`)\n  }\n  return value as OutputFormat\n}\n\nfunction select<T>(\n  name: string,\n  explicit: T | undefined,\n  environment: T | undefined,\n  profile: T | undefined,\n  fallback: T | undefined,\n  sources: Record<string, string>,\n): T | undefined {\n  if (explicit !== undefined) {\n    sources[name] = 'argument'\n    return explicit\n  }\n  if (environment !== undefined) {\n    sources[name] = 'environment'\n    return environment\n  }\n  if (profile !== undefined) {\n    sources[name] = 'profile'\n    return profile\n  }\n  if (fallback !== undefined) sources[name] = 'default'\n  return fallback\n}\n\nfunction sourceOf(\n  explicit: unknown,\n  environment: unknown,\n  profile: unknown,\n  fallback: string,\n): string {\n  return explicit !== undefined\n    ? 'argument'\n    : environment !== undefined\n    ? 'environment'\n    : profile !== undefined\n    ? 'profile'\n    : fallback\n}\n\nfunction validateEndpoint(value: string): void {\n  let url: URL\n  try {\n    url = new URL(value)\n  } catch {\n    throw new UsageError('INVALID_ENDPOINT', `invalid endpoint URL: ${value}`)\n  }\n  if (!['http:', 'https:'].includes(url.protocol)) {\n    throw new UsageError('INVALID_ENDPOINT', 'endpoint must use http or https')\n  }\n}\n\nfunction inferProtocol(endpoint: string | undefined): 'http://' | 'https://' | undefined {\n  if (!endpoint) return undefined\n  return endpoint.startsWith('http://')\n    ? 'http://'\n    : endpoint.startsWith('https://')\n    ? 'https://'\n    : undefined\n}\n\nfunction redactUrl(value: string | undefined): string | null {\n  if (!value) return null\n  try {\n    const url = new URL(value)\n    if (url.username || url.password) {\n      url.username = '[REDACTED]'\n      url.password = '[REDACTED]'\n    }\n    return url.toString()\n  } catch {\n    return '[INVALID_URL]'\n  }\n}\n\nexport function configValueError(message: string): ToolError {\n  return new ToolError('INVALID_CONFIG_VALUE', message, 2)\n}\n","import { buckyos, BuckyOSSDK, namelib, RuntimeType } from 'buckyos/node'\nimport type { SessionController } from './auth.ts'\nimport type { ResolvedConfig } from './config.ts'\nimport type { ResolvedConnection } from './context.ts'\nimport { ToolError, UsageError } from './errors.ts'\n\nexport interface RuntimeAdapter {\n  initialize(config: ResolvedConfig, session: SessionController): Promise<ResolvedConnection>\n}\n\nexport interface RpcCallOptions {\n  traceId: string\n  timeoutMs: number\n  signal?: AbortSignal\n}\n\nexport interface ServiceClientRegistry {\n  call<T>(\n    service: string,\n    method: string,\n    params: Record<string, unknown>,\n    options: RpcCallOptions,\n  ): Promise<T>\n  createEventReader?(pattern: string, signal?: AbortSignal): Promise<EventReader>\n}\n\nexport interface EventReader {\n  pullEvent(timeoutMs?: number): Promise<unknown | null>\n  close(): Promise<void>\n}\n\ninterface RpcClient {\n  call<T>(\n    method: string,\n    params: Record<string, unknown>,\n    options: { traceId: string },\n  ): Promise<T>\n}\n\ntype RpcClientConstructor = new (\n  url: string,\n  token?: string | null,\n  sequence?: number | null,\n  options?: { sessionTokenProvider?: () => Promise<string | null> },\n) => RpcClient\n\nexport class BuckyOSRuntimeAdapter implements RuntimeAdapter {\n  #sdk = new BuckyOSSDK('node')\n\n  async initialize(\n    config: ResolvedConfig,\n    session: SessionController,\n  ): Promise<ResolvedConnection> {\n    const authenticated = session.current()\n    const zoneHost = resolveZoneHost(config)\n    const initialize = this.#sdk.initBuckyOS as unknown as (\n      appId: string,\n      config: Record<string, unknown>,\n    ) => Promise<void>\n    await initialize.call(this.#sdk, authenticated.principal.appId, {\n      appId: authenticated.principal.appId,\n      ownerUserId: authenticated.principal.id,\n      runtimeType: RuntimeType.AppClient,\n      zoneHost,\n      defaultProtocol: config.defaultProtocol,\n      sessionToken: authenticated.token,\n      privateKeySearchPaths: [],\n      autoRenew: false,\n      verifyHubServiceUrl: resolveServiceUrl(config, 'verify-hub'),\n    })\n    return {\n      zone: config.zone ?? zoneHost,\n      endpoint: config.endpoint ?? `${config.defaultProtocol}${zoneHost}`,\n      defaultProtocol: config.defaultProtocol,\n    }\n  }\n}\n\nexport class BuckyOSServiceClientRegistry implements ServiceClientRegistry {\n  readonly #config: ResolvedConfig\n  readonly #session: SessionController\n  readonly #clients = new Map<string, RpcClient>()\n\n  constructor(config: ResolvedConfig, session: SessionController) {\n    this.#config = config\n    this.#session = session\n  }\n\n  async call<T>(\n    service: string,\n    method: string,\n    params: Record<string, unknown>,\n    options: RpcCallOptions,\n  ): Promise<T> {\n    let client = this.#clients.get(service)\n    if (!client) {\n      const RpcClient = buckyos.kRPCClient as unknown as RpcClientConstructor\n      client = new RpcClient(resolveServiceUrl(this.#config, service), null, null, {\n        sessionTokenProvider: async () => (await this.#session.ensureValid()).token,\n      })\n      this.#clients.set(service, client)\n    }\n    const request = client.call(method, params, { traceId: options.traceId }) as Promise<T>\n    return await withDeadline(request, options.timeoutMs, options.signal)\n  }\n\n  async createEventReader(pattern: string, signal?: AbortSignal): Promise<EventReader> {\n    return await buckyos.createEventReader(pattern, { keepaliveMs: 5_000, signal })\n  }\n}\n\nexport class InteractiveSession {\n  readonly authentication: SessionController\n  readonly clients: ServiceClientRegistry\n  readonly connection: ResolvedConnection\n  readonly startedAt: number\n\n  private constructor(\n    authentication: SessionController,\n    clients: ServiceClientRegistry,\n    connection: ResolvedConnection,\n  ) {\n    this.authentication = authentication\n    this.clients = clients\n    this.connection = connection\n    this.startedAt = Date.now()\n  }\n\n  static async create(\n    config: ResolvedConfig,\n    authentication: SessionController,\n    runtime: RuntimeAdapter = new BuckyOSRuntimeAdapter(),\n    clients?: ServiceClientRegistry,\n  ): Promise<InteractiveSession> {\n    await authentication.connect()\n    const connection = await runtime.initialize(config, authentication)\n    return new InteractiveSession(\n      authentication,\n      clients ?? new BuckyOSServiceClientRegistry(config, authentication),\n      connection,\n    )\n  }\n\n  async reconnect(): Promise<void> {\n    await this.authentication.reconnect()\n  }\n}\n\nexport function resolveServiceUrl(config: ResolvedConfig, service: string): string {\n  if (config.endpoint) {\n    const endpoint = new URL(config.endpoint)\n    const marker = endpoint.pathname.indexOf('/kapi/')\n    if (marker >= 0) endpoint.pathname = `${endpoint.pathname.slice(0, marker)}/kapi/${service}`\n    else if (endpoint.pathname.endsWith('/kapi')) {\n      endpoint.pathname = `${endpoint.pathname}/${service}`\n    } else endpoint.pathname = `${endpoint.pathname.replace(/\\/$/, '')}/kapi/${service}`\n    endpoint.search = ''\n    endpoint.hash = ''\n    return endpoint.toString().replace(/\\/$/, '')\n  }\n  const host = resolveZoneHost(config)\n  return `${config.defaultProtocol}${host}/kapi/${service}`\n}\n\nexport function resolveZoneHost(config: ResolvedConfig): string {\n  if (config.zone) {\n    try {\n      return namelib.DID.fromStr(config.zone).toRawHostName()\n    } catch {\n      throw new UsageError('INVALID_ZONE', `invalid zone host or DID: ${config.zone}`)\n    }\n  }\n  if (config.endpoint) return new URL(config.endpoint).host\n  throw new UsageError('CONNECTION_REQUIRED', 'an endpoint or zone is required for online commands')\n}\n\nexport async function withDeadline<T>(\n  promise: Promise<T>,\n  timeoutMs: number,\n  signal?: AbortSignal,\n): Promise<T> {\n  if (signal?.aborted) throw new ToolError('CANCELED', 'operation canceled', 8)\n  let timer: ReturnType<typeof setTimeout> | undefined\n  let abortHandler: (() => void) | undefined\n  const guards: Promise<never>[] = [\n    new Promise((_, reject) => {\n      timer = setTimeout(\n        () => reject(new ToolError('TIMEOUT', 'operation timed out', 8, true)),\n        timeoutMs,\n      )\n    }),\n  ]\n  if (signal) {\n    guards.push(\n      new Promise((_, reject) => {\n        abortHandler = () => reject(new ToolError('CANCELED', 'operation canceled', 8))\n        signal.addEventListener('abort', abortHandler, { once: true })\n      }),\n    )\n  }\n  try {\n    return await Promise.race([promise, ...guards])\n  } finally {\n    if (timer !== undefined) clearTimeout(timer)\n    if (signal && abortHandler) signal.removeEventListener('abort', abortHandler)\n  }\n}\n","import { buckyos } from 'buckyos/node'\nimport type { ResolvedConfig } from './config.ts'\nimport { resolveServiceUrl } from './runtime.ts'\n\nexport const BUCKYOS_DEV_CONFIG_KEY = 'system/buckyos_dev_config'\nexport const BUCKYOS_DEV_CONFIG_SCHEMA_VERSION = 1\n\nexport interface BuckyOSDevConfig {\n  schema_version: 1\n  enabled: boolean\n  enabled_at: number | null\n  enabled_by: string | null\n}\n\nexport type DevelopmentModeDecision =\n  | { state: 'enabled'; config: BuckyOSDevConfig }\n  | { state: 'disabled'; config: BuckyOSDevConfig }\n  | { state: 'unavailable'; reason: string }\n\nexport type DevelopmentModeReader = (\n  config: ResolvedConfig,\n) => Promise<DevelopmentModeDecision>\n\ninterface PublicRpcClient {\n  call<T>(method: string, params: Record<string, unknown>): Promise<T>\n}\n\n/**\n * Read the target Zone's public developer-mode setting.\n *\n * This deliberately uses control-panel's unauthenticated `system.dev_mode.get`\n * endpoint: developer mode must be known before a local identity is touched or\n * exchanged at verify-hub. Every error is converted to `unavailable`, which is\n * a fail-closed result for the identity resolver.\n */\nexport async function readTargetDevelopmentMode(\n  config: ResolvedConfig,\n): Promise<DevelopmentModeDecision> {\n  try {\n    const url = resolveServiceUrl(config, 'control-panel')\n    const client = new buckyos.kRPCClient(url) as unknown as PublicRpcClient\n    const value = await withTimeout(\n      client.call<unknown>('system.dev_mode.get', {}),\n      config.timeoutMs,\n    )\n    const parsed = parseBuckyOSDevConfig(value)\n    return parsed.enabled\n      ? { state: 'enabled', config: parsed }\n      : { state: 'disabled', config: parsed }\n  } catch (error) {\n    return {\n      state: 'unavailable',\n      reason: error instanceof Error ? error.message : String(error),\n    }\n  }\n}\n\nexport function parseBuckyOSDevConfig(value: unknown): BuckyOSDevConfig {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) {\n    throw new Error('BuckyOSDevConfig must be an object')\n  }\n  const config = value as Record<string, unknown>\n  const keys = Object.keys(config).sort()\n  const expectedKeys = ['enabled', 'enabled_at', 'enabled_by', 'schema_version']\n  if (JSON.stringify(keys) !== JSON.stringify(expectedKeys)) {\n    throw new Error('BuckyOSDevConfig contains missing or unsupported fields')\n  }\n  if (config.schema_version !== BUCKYOS_DEV_CONFIG_SCHEMA_VERSION) {\n    throw new Error(`unsupported BuckyOSDevConfig schema_version ${String(config.schema_version)}`)\n  }\n  if (typeof config.enabled !== 'boolean') {\n    throw new Error('BuckyOSDevConfig enabled must be a boolean')\n  }\n  const enabledAt = config.enabled_at\n  const enabledBy = config.enabled_by\n  const hasAuditFields = Number.isSafeInteger(enabledAt) && (enabledAt as number) > 0 &&\n    typeof enabledBy === 'string' && enabledBy.trim().length > 0\n  const hasNoAuditFields = enabledAt === null && enabledBy === null\n  if (!hasAuditFields && !hasNoAuditFields) {\n    throw new Error('BuckyOSDevConfig enabled_at and enabled_by must be valid and present together')\n  }\n  if (config.enabled && !hasAuditFields) {\n    throw new Error('enabled BuckyOSDevConfig requires enable audit fields')\n  }\n  return {\n    schema_version: 1,\n    enabled: config.enabled,\n    enabled_at: enabledAt as number | null,\n    enabled_by: enabledBy as string | null,\n  }\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n  let timer: ReturnType<typeof setTimeout> | undefined\n  const timeout = new Promise<never>((_, reject) => {\n    timer = setTimeout(() => reject(new Error('developer-mode lookup timed out')), timeoutMs)\n  })\n  try {\n    return await Promise.race([promise, timeout])\n  } finally {\n    if (timer !== undefined) clearTimeout(timer)\n  }\n}\n","import { namelib } from 'buckyos/node'\nimport { type Environment, readEnvironment, type ResolvedConfig } from './config.ts'\nimport { EXIT_AUTH, EXIT_PERMISSION, ToolError, UsageError } from './errors.ts'\nimport { getHost, isHostError } from '../runtime/host.ts'\n\nconst join = (...parts: string[]) => getHost().path.join(...parts)\n\nconst LOCAL_NODE_GATEWAY_ENDPOINT = 'http://127.0.0.1:3180'\n\nexport interface IdentityMaterial {\n  did: string\n  subject: string\n  issuer: string\n  principalKind: 'user' | 'device'\n  publicRoot: string\n  securityRoot: string\n  documentPath: string\n  privateKeyPath: string\n  privateKeyPem: string\n  source: IdentityRootPair['source']\n}\n\nexport interface IdentityRootPair {\n  publicRoot: string\n  securityRoot: string\n  source: 'buckyos-home' | 'buckycli-home' | 'current-device'\n}\n\nexport interface IdentityRootOptions {\n  includeOperations?: boolean\n  includeDeveloper?: boolean\n}\n\nexport const IDENTITY_CANDIDATE_LIMIT = 8\nexport const IDENTITY_REJECTION_CODES = Object.freeze([\n  'IDENTITY_KIND_NOT_ACCEPTED',\n  'AUTHENTICATION_REJECTED',\n])\n\nexport interface IdentityCandidate {\n  material: IdentityMaterial\n  source: IdentityRootPair['source']\n  directory: string\n}\n\nexport interface IdentityCandidateScan {\n  order: readonly IdentityRootPair['source'][]\n  limit: number\n  candidates: IdentityCandidate[]\n  skipped: Array<{\n    source: IdentityRootPair['source']\n    identity?: string\n    path: string\n    reason: string\n  }>\n}\n\nexport async function applyImplicitDeviceIdentity(\n  config: ResolvedConfig,\n  environment: Environment = readEnvironment(),\n): Promise<ResolvedConfig> {\n  if (\n    config.sessionToken || config.sessionTokenFile || config.identity || config.zone ||\n    config.endpoint\n  ) {\n    return config\n  }\n  const device = await readCurrentDeviceIdentity(environment)\n  if (!device) return config\n  return {\n    ...config,\n    identity: device.did,\n    zone: device.zoneDid,\n    endpoint: LOCAL_NODE_GATEWAY_ENDPOINT,\n    identityRoot: device.publicRoot,\n    securityRoot: device.securityRoot,\n    defaultProtocol: 'http://',\n    implicitDeviceIdentity: device,\n    sources: {\n      ...config.sources,\n      identity: 'current-device',\n      zone: 'current-device',\n      endpoint: 'local-node-gateway',\n      identity_root: 'current-device',\n      security_root: 'current-device',\n    },\n  }\n}\n\nexport async function readCurrentDeviceIdentity(\n  environment: Environment = readEnvironment(),\n): Promise<NonNullable<ResolvedConfig['implicitDeviceIdentity']> | undefined> {\n  if (\n    getHost().policy.distribution === 'developer' && environment.BUCKYOS_ROOT === undefined\n  ) return undefined\n  const buckyosRoot = environment.BUCKYOS_ROOT ?? defaultBuckyOSRoot(environment)\n  const nodeIdentityPath = join(buckyosRoot, 'etc', 'node_identity.json')\n  let value: unknown\n  try {\n    value = JSON.parse(await getHost().readTextFile(nodeIdentityPath))\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) return undefined\n    if (isHostError(error, 'PermissionDenied')) {\n      throw new ToolError(\n        'DEVICE_IDENTITY_READ_FAILED',\n        `permission denied reading current device identity: ${nodeIdentityPath}`,\n        EXIT_PERMISSION,\n      )\n    }\n    throw new ToolError(\n      'DEVICE_IDENTITY_READ_FAILED',\n      `failed to read current device identity: ${nodeIdentityPath}`,\n      EXIT_AUTH,\n    )\n  }\n  if (!value || typeof value !== 'object' || Array.isArray(value)) {\n    throw invalidDeviceIdentity(nodeIdentityPath)\n  }\n  const document = value as Record<string, unknown>\n  const did = nonEmptyString(document.device_did)\n  const name = nonEmptyString(document.device_name)\n  const zoneDid = nonEmptyString(document.zone_did)\n  if (document.schema !== 'buckyos.node_identity.v2' || !did || !name || !zoneDid) {\n    throw invalidDeviceIdentity(nodeIdentityPath)\n  }\n  try {\n    namelib.DID.fromStr(did)\n    namelib.DID.fromStr(zoneDid)\n  } catch {\n    throw invalidDeviceIdentity(nodeIdentityPath)\n  }\n  return {\n    did,\n    name,\n    zoneDid,\n    buckyosRoot,\n    nodeIdentityPath,\n    publicRoot: join(buckyosRoot, 'local', 'identity'),\n    securityRoot: join(buckyosRoot, 'security'),\n  }\n}\n\nexport function identityRootPairs(\n  config: ResolvedConfig,\n  environment: Environment = readEnvironment(),\n  options: IdentityRootOptions = {},\n): IdentityRootPair[] {\n  const device = config.implicitDeviceIdentity\n  if (device) {\n    return [{\n      publicRoot: device.publicRoot,\n      securityRoot: device.securityRoot,\n      source: 'current-device',\n    }]\n  }\n\n  const home = environment.HOME ?? environment.USERPROFILE ?? getHost().homeDir()\n  const pairs: IdentityRootPair[] = []\n  if (options.includeOperations ?? true) {\n    pairs.push({\n      publicRoot: join(home, '.buckyos', 'local', 'identity'),\n      securityRoot: join(home, '.buckyos', 'security'),\n      source: 'buckyos-home',\n    })\n  }\n  if (options.includeDeveloper ?? false) {\n    pairs.push({\n      publicRoot: join(home, '.buckycli', 'local', 'identity'),\n      securityRoot: join(home, '.buckycli', 'security'),\n      source: 'buckycli-home',\n    })\n  }\n  return deduplicatePairs(pairs)\n}\n\nexport async function resolveIdentityMaterial(\n  selectedIdentity: string,\n  config: ResolvedConfig,\n  environment: Environment = readEnvironment(),\n  options: IdentityRootOptions = {},\n): Promise<IdentityMaterial> {\n  const selected = selectedIdentity.trim()\n  if (!selected) throw new UsageError('IDENTITY_REQUIRED', 'identity is empty')\n\n  for (const roots of identityRootPairs(config, environment, options)) {\n    for (const directory of await candidateDirectories(roots.publicRoot, selected)) {\n      const material = await loadIdentityMaterial(roots, directory, selected)\n      if (material) return material\n    }\n  }\n\n  throw new ToolError(\n    'IDENTITY_NOT_FOUND',\n    `no usable authentication material found for identity ${selected}`,\n    EXIT_AUTH,\n  )\n}\n\nexport async function scanIdentityCandidates(\n  config: ResolvedConfig,\n  environment: Environment = readEnvironment(),\n  options: IdentityRootOptions = {},\n): Promise<IdentityCandidateScan> {\n  const candidates: IdentityCandidate[] = []\n  const skipped: IdentityCandidateScan['skipped'] = []\n  const seen = new Set<string>()\n  const roots = identityRootPairs(config, environment, options)\n  for (const pair of roots) {\n    let directories: string[]\n    try {\n      directories = await candidateDirectories(pair.publicRoot, '')\n    } catch (error) {\n      if (isHostError(error, 'PermissionDenied')) {\n        skipped.push({ source: pair.source, path: pair.publicRoot, reason: 'policy-denied' })\n        continue\n      }\n      throw error\n    }\n    for (const directory of directories) {\n      if (candidates.length >= IDENTITY_CANDIDATE_LIMIT) break\n      const documentPath = join(pair.publicRoot, directory, 'did.json')\n      try {\n        const material = await loadIdentityMaterial(pair, directory)\n        if (!material) {\n          skipped.push({ source: pair.source, path: documentPath, reason: 'not-usable' })\n          continue\n        }\n        if (seen.has(material.did)) {\n          skipped.push({\n            source: pair.source,\n            identity: material.did,\n            path: documentPath,\n            reason: 'duplicate',\n          })\n          continue\n        }\n        seen.add(material.did)\n        candidates.push({ material, source: pair.source, directory })\n      } catch (error) {\n        if (isHostError(error, 'PermissionDenied')) {\n          skipped.push({ source: pair.source, path: documentPath, reason: 'policy-denied' })\n          continue\n        }\n        if (error instanceof ToolError && error.code === 'IDENTITY_KEYREF_UNSUPPORTED') {\n          skipped.push({\n            source: pair.source,\n            identity: typeof error.details.identity === 'string'\n              ? error.details.identity\n              : undefined,\n            path: documentPath,\n            reason: 'key-reference-unsupported',\n          })\n          continue\n        }\n        throw error\n      }\n    }\n    if (candidates.length >= IDENTITY_CANDIDATE_LIMIT) break\n  }\n  return {\n    order: Object.freeze(roots.map((pair) => pair.source)),\n    limit: IDENTITY_CANDIDATE_LIMIT,\n    candidates,\n    skipped,\n  }\n}\n\nexport async function identityCandidateView(\n  config: ResolvedConfig,\n  environment: Environment = readEnvironment(),\n  developerModeEnabled = false,\n): Promise<Record<string, unknown>> {\n  if (config.identity) {\n    try {\n      const material = await resolveIdentityMaterial(config.identity, config, environment, {\n        includeDeveloper: developerModeEnabled,\n      })\n      return {\n        mode: 'explicit',\n        order: [material.did],\n        limit: 1,\n        candidates: [{\n          identity: material.did,\n          source: config.sources.identity ?? 'explicit',\n          document_path: material.documentPath,\n        }],\n        skipped: [],\n      }\n    } catch (error) {\n      return {\n        mode: 'explicit',\n        order: [config.identity],\n        limit: 1,\n        candidates: [],\n        skipped: [{\n          identity: config.identity,\n          reason: error instanceof ToolError ? error.code : 'unavailable',\n        }],\n      }\n    }\n  }\n  const scan = await scanIdentityCandidates(config, environment, {\n    includeDeveloper: developerModeEnabled,\n  })\n  return {\n    mode: 'search',\n    order: scan.order,\n    limit: scan.limit,\n    candidates: scan.candidates.map((candidate) => ({\n      identity: candidate.material.did,\n      source: candidate.source,\n      document_path: candidate.material.documentPath,\n    })),\n    skipped: scan.skipped,\n  }\n}\n\nasync function loadIdentityMaterial(\n  roots: IdentityRootPair,\n  directory: string,\n  selected?: string,\n): Promise<IdentityMaterial | undefined> {\n  const documentPath = join(roots.publicRoot, directory, 'did.json')\n  const document = await readIdentityDocument(documentPath)\n  if (!document || selected && !identityMatches(document, selected)) return undefined\n  const did = typeof document.id === 'string' ? document.id : ''\n  const subject = typeof document.name === 'string' && document.name.trim()\n    ? document.name.trim()\n    : did\n  if (!did || !subject) return undefined\n\n  const privateKeyPath = join(roots.securityRoot, directory, 'authentication.private.pem')\n  try {\n    const privateKeyPem = (await getHost().readTextFile(privateKeyPath)).trim()\n    if (!privateKeyPem) return undefined\n    return {\n      did,\n      subject,\n      issuer: subject,\n      principalKind: typeof document.device_type === 'string' ? 'device' : 'user',\n      publicRoot: roots.publicRoot,\n      securityRoot: roots.securityRoot,\n      documentPath,\n      privateKeyPath,\n      privateKeyPem,\n      source: roots.source,\n    }\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n  }\n\n  const keyrefPath = join(roots.securityRoot, directory, 'authentication.keyref.json')\n  try {\n    await getHost().stat(keyrefPath)\n    throw new ToolError(\n      'IDENTITY_KEYREF_UNSUPPORTED',\n      'the selected identity uses a key reference unsupported by this runtime',\n      EXIT_AUTH,\n      false,\n      { identity: did, keyref_path: keyrefPath },\n    )\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n  }\n  return undefined\n}\n\nasync function candidateDirectories(publicRoot: string, identity: string): Promise<string[]> {\n  if (identity.startsWith('did:')) {\n    try {\n      return [namelib.DID.fromStr(identity).toFilename()]\n    } catch {\n      throw new UsageError('INVALID_IDENTITY', `invalid DID: ${identity}`)\n    }\n  }\n  const directories: string[] = []\n  try {\n    for (const entry of await getHost().readDir(publicRoot)) {\n      if (entry.isDirectory) directories.push(entry.name)\n    }\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) return []\n    throw error\n  }\n  return directories.sort()\n}\n\nasync function readIdentityDocument(path: string): Promise<Record<string, unknown> | null> {\n  try {\n    const value = JSON.parse(await getHost().readTextFile(path)) as unknown\n    return value && typeof value === 'object' && !Array.isArray(value)\n      ? value as Record<string, unknown>\n      : null\n  } catch (error) {\n    if (isHostError(error, 'NotFound') || error instanceof SyntaxError) return null\n    throw error\n  }\n}\n\nfunction identityMatches(document: Record<string, unknown>, selected: string): boolean {\n  if (typeof document.id === 'string' && document.id === selected) return true\n  return typeof document.name === 'string' && document.name === selected\n}\n\nexport function defaultBuckyOSRoot(environment: Environment = readEnvironment()): string {\n  if (getHost().platform === 'windows') {\n    const appData = environment.APPDATA\n    return appData ? join(appData, 'buckyos') : 'C:\\\\BuckyOS'\n  }\n  return '/opt/buckyos'\n}\n\nfunction invalidDeviceIdentity(path: string): ToolError {\n  return new ToolError(\n    'INVALID_DEVICE_IDENTITY',\n    `current device identity is invalid: ${path}`,\n    EXIT_AUTH,\n  )\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\nfunction deduplicatePairs(pairs: IdentityRootPair[]): IdentityRootPair[] {\n  const seen = new Set<string>()\n  return pairs.filter((pair) => {\n    const key = `${pair.publicRoot}\\0${pair.securityRoot}`\n    if (seen.has(key)) return false\n    seen.add(key)\n    return true\n  })\n}\n","import {\n  buckyos,\n  createAppInstanceId,\n  parseSessionTokenClaims,\n  VerifyHubClient,\n} from 'buckyos/node'\nimport { type Environment, readEnvironment, type ResolvedConfig } from './config.ts'\nimport {\n  type DevelopmentModeDecision,\n  type DevelopmentModeReader,\n  readTargetDevelopmentMode,\n} from './development_mode.ts'\nimport { EXIT_AUTH, sanitizeMessage, ToolError } from './errors.ts'\nimport {\n  IDENTITY_CANDIDATE_LIMIT,\n  IDENTITY_REJECTION_CODES,\n  type IdentityCandidate,\n  type IdentityMaterial,\n  resolveIdentityMaterial,\n  scanIdentityCandidates,\n} from './identity.ts'\nimport { resolveServiceUrl } from './runtime.ts'\nimport { getHost } from '../runtime/host.ts'\n\ntype AuthTarget =\n  | { kind: 'app'; app_instance_id: string }\n  | { kind: 'system'; service_id: string }\n\nexport type AuthenticationKind =\n  | 'session-token'\n  | 'session-token-file'\n  | 'environment'\n  | 'identity'\n  | 'password'\n  | 'mock'\n\nexport interface ResolvedPrincipal {\n  id: string\n  appId: string\n  appInstanceId?: string\n  authentication: AuthenticationKind\n  tokenExpiresAt?: string\n}\n\nexport interface AuthenticatedSession {\n  token: string\n  principal: ResolvedPrincipal\n  claims: Record<string, unknown>\n  renewable: boolean\n}\n\nexport interface AuthenticationTransport {\n  loginByJwt(url: string, jwt: string, target: AuthTarget, timeoutMs: number): Promise<string>\n  loginByPassword(\n    url: string,\n    username: string,\n    password: string,\n    target: AuthTarget,\n    timeoutMs: number,\n  ): Promise<string>\n}\n\nexport interface AuthenticationDependencies {\n  transport?: AuthenticationTransport\n  readPassword?: (prompt: string) => Promise<string>\n  readUsername?: (prompt: string) => Promise<string>\n  readDevelopmentMode?: DevelopmentModeReader\n  now?: () => number\n}\n\nexport interface SessionController {\n  readonly config: ResolvedConfig\n  connect(): Promise<AuthenticatedSession>\n  ensureValid(): Promise<AuthenticatedSession>\n  reconnect(): Promise<AuthenticatedSession>\n  current(): AuthenticatedSession\n  status(): Record<string, unknown>\n}\n\nconst LOGIN_APP_ID = 'buckycli'\nconst LOGIN_TOKEN_TTL_SECONDS = 10 * 60\n\nexport class AuthenticationSession implements SessionController {\n  readonly config: ResolvedConfig\n  readonly #environment: Environment\n  readonly #transport: AuthenticationTransport\n  readonly #readPassword: (prompt: string) => Promise<string>\n  readonly #readUsername: (prompt: string) => Promise<string>\n  readonly #readDevelopmentMode: DevelopmentModeReader\n  readonly #now: () => number\n  #session?: AuthenticatedSession\n  #acceptedIdentity?: IdentityMaterial\n  #developmentMode?: DevelopmentModeDecision\n  #identityAttempts: Array<{ identity: string; code: string; message: string }> = []\n\n  constructor(\n    config: ResolvedConfig,\n    environment: Environment = readEnvironment(),\n    dependencies: AuthenticationDependencies = {},\n  ) {\n    this.config = config\n    this.#environment = environment\n    this.#transport = dependencies.transport ?? new SdkAuthenticationTransport()\n    this.#readPassword = dependencies.readPassword ?? readSecret\n    this.#readUsername = dependencies.readUsername ?? readVisible\n    this.#readDevelopmentMode = dependencies.readDevelopmentMode ?? readTargetDevelopmentMode\n    this.#now = dependencies.now ?? Date.now\n  }\n\n  async connect(): Promise<AuthenticatedSession> {\n    if (this.#session) return this.#session\n    this.#session = await this.#authenticate(false)\n    return this.#session\n  }\n\n  async ensureValid(): Promise<AuthenticatedSession> {\n    const session = await this.connect()\n    const exp = numberClaim(session.claims.exp)\n    const nowSeconds = Math.floor(this.#now() / 1_000)\n    if (exp === undefined || exp > nowSeconds + 15) return session\n    if (!session.renewable) {\n      throw new ToolError(\n        'SESSION_EXPIRED',\n        'the externally supplied session token has expired',\n        EXIT_AUTH,\n      )\n    }\n    this.#session = await this.#authenticate(true)\n    return this.#session\n  }\n\n  async reconnect(): Promise<AuthenticatedSession> {\n    this.#session = await this.#authenticate(true)\n    return this.#session\n  }\n\n  current(): AuthenticatedSession {\n    if (!this.#session) {\n      throw new ToolError('AUTH_REQUIRED', 'session is not initialized', EXIT_AUTH)\n    }\n    return this.#session\n  }\n\n  status(): Record<string, unknown> {\n    const session = this.current()\n    const expiresAt = session.principal.tokenExpiresAt\n    const exp = numberClaim(session.claims.exp)\n    const remainingSeconds = exp === undefined\n      ? null\n      : Math.max(0, exp - Math.floor(this.#now() / 1_000))\n    return {\n      authenticated: true,\n      principal: session.principal.id,\n      appid: session.principal.appId,\n      app_instance_id: session.principal.appInstanceId ?? null,\n      authentication: session.principal.authentication,\n      renewable: session.renewable,\n      expires_at: expiresAt ?? null,\n      remaining_seconds: remainingSeconds,\n      developer_mode: this.#developmentMode?.state ?? null,\n      identity_attempts: this.#identityAttempts,\n    }\n  }\n\n  async #authenticate(reconnect: boolean): Promise<AuthenticatedSession> {\n    if (this.config.sessionToken) {\n      const source = this.config.sources.session_token === 'environment'\n        ? 'environment'\n        : 'session-token'\n      return externalSession(this.config.sessionToken, source, this.#now())\n    }\n\n    if (this.config.sessionTokenFile) {\n      let token: string\n      try {\n        token = (await getHost().readTextFile(this.config.sessionTokenFile)).trim()\n      } catch (error) {\n        throw new ToolError(\n          'SESSION_TOKEN_FILE_ERROR',\n          `failed to read session token file: ${\n            error instanceof Error ? error.message : String(error)\n          }`,\n          EXIT_AUTH,\n        )\n      }\n      if (!token) {\n        throw new ToolError('INVALID_SESSION_TOKEN', 'session token file is empty', EXIT_AUTH)\n      }\n      return externalSession(token, 'session-token-file', this.#now())\n    }\n\n    const injected = this.#environment.BUCKYOS_APPCLIENT_SESSION_TOKEN?.trim()\n    if (injected) return externalSession(injected, 'environment', this.#now())\n\n    if (this.#acceptedIdentity) {\n      if (this.#acceptedIdentity.source === 'buckycli-home') {\n        await this.#requireDeveloperIdentityAccess()\n      }\n      return await this.#loginWithIdentity(this.#acceptedIdentity)\n    }\n\n    if (this.config.identity) {\n      const material = await this.#resolveExplicitIdentity(this.config.identity)\n      const session = await this.#loginWithIdentity(material)\n      this.#acceptedIdentity = material\n      return session\n    }\n\n    this.#identityAttempts = []\n    const operations = await scanIdentityCandidates(this.config, this.#environment)\n    const operationsSession = await this.#tryIdentityCandidates(operations.candidates)\n    if (operationsSession) return operationsSession\n\n    const developmentMode = await this.#checkDevelopmentMode()\n    if (\n      developmentMode.state === 'enabled' &&\n      operations.candidates.length < IDENTITY_CANDIDATE_LIMIT\n    ) {\n      const operationsDids = new Set(\n        operations.candidates.map((candidate) => candidate.material.did),\n      )\n      const developer = await scanIdentityCandidates(this.config, this.#environment, {\n        includeOperations: false,\n        includeDeveloper: true,\n      })\n      const remaining = IDENTITY_CANDIDATE_LIMIT - operations.candidates.length\n      const candidates = developer.candidates.filter((candidate) =>\n        !operationsDids.has(candidate.material.did)\n      ).slice(0, remaining)\n      const developerSession = await this.#tryIdentityCandidates(candidates)\n      if (developerSession) return developerSession\n    }\n    if (this.#identityAttempts.length > 0) {\n      throw new ToolError(\n        'IDENTITY_CANDIDATES_REJECTED',\n        `all ${this.#identityAttempts.length} identity candidates were rejected`,\n        EXIT_AUTH,\n        false,\n        { attempts: this.#identityAttempts },\n      )\n    }\n\n    if (this.config.nonInteractive) {\n      throw new ToolError(\n        'AUTH_REQUIRED',\n        'no session token or usable identity is available in non-interactive mode',\n        EXIT_AUTH,\n      )\n    }\n    const username = this.config.identity?.startsWith('did:')\n      ? await this.#readUsername('Username: ')\n      : this.config.identity ?? await this.#readUsername('Username: ')\n    if (!username.trim()) throw new ToolError('AUTH_REQUIRED', 'username is required', EXIT_AUTH)\n    const password = await this.#readPassword(reconnect ? 'Password (reconnect): ' : 'Password: ')\n    const token = await this.#transport.loginByPassword(\n      resolveServiceUrl(this.config, 'verify-hub'),\n      username.trim(),\n      password,\n      appAuthTarget(username.trim()),\n      this.config.timeoutMs,\n    )\n    return authenticatedSession(token, 'password', true, this.#now())\n  }\n\n  async #resolveExplicitIdentity(selectedIdentity: string): Promise<IdentityMaterial> {\n    if (this.config.implicitDeviceIdentity) {\n      return await resolveIdentityMaterial(selectedIdentity, this.config, this.#environment)\n    }\n\n    try {\n      return await resolveIdentityMaterial(selectedIdentity, this.config, this.#environment)\n    } catch (error) {\n      if (!(error instanceof ToolError) || error.code !== 'IDENTITY_NOT_FOUND') throw error\n    }\n\n    await this.#requireDeveloperIdentityAccess()\n    return await resolveIdentityMaterial(selectedIdentity, this.config, this.#environment, {\n      includeOperations: false,\n      includeDeveloper: true,\n    })\n  }\n\n  async #tryIdentityCandidates(\n    candidates: readonly IdentityCandidate[],\n  ): Promise<AuthenticatedSession | undefined> {\n    for (const candidate of candidates) {\n      try {\n        const session = await this.#loginWithIdentity(candidate.material)\n        this.#acceptedIdentity = candidate.material\n        return session\n      } catch (error) {\n        if (!isIdentityRejection(error)) throw error\n        this.#identityAttempts.push({\n          identity: candidate.material.did,\n          code: error.code,\n          message: sanitizeMessage(error.message),\n        })\n      }\n    }\n    return undefined\n  }\n\n  async #loginWithIdentity(material: IdentityMaterial): Promise<AuthenticatedSession> {\n    const loginJwt = await createLoginJwt(\n      material.subject,\n      material.issuer,\n      material.privateKeyPem,\n      this.#now(),\n    )\n    const token = await this.#transport.loginByJwt(\n      resolveServiceUrl(this.config, 'verify-hub'),\n      loginJwt,\n      identityAuthTarget(material.principalKind, material.subject),\n      this.config.timeoutMs,\n    )\n    return authenticatedSession(token, 'identity', true, this.#now())\n  }\n\n  async #checkDevelopmentMode(): Promise<DevelopmentModeDecision> {\n    this.#developmentMode = await this.#readDevelopmentMode(this.config)\n    return this.#developmentMode\n  }\n\n  async #requireDeveloperIdentityAccess(): Promise<void> {\n    const decision = await this.#checkDevelopmentMode()\n    if (decision.state === 'enabled') return\n    this.#acceptedIdentity = undefined\n    if (decision.state === 'disabled') {\n      throw new ToolError(\n        'DEVELOPER_IDENTITY_DISABLED',\n        'the target Zone has developer mode disabled; local developer identities are unavailable',\n        EXIT_AUTH,\n      )\n    }\n    throw new ToolError(\n      'DEVELOPER_MODE_UNAVAILABLE',\n      'the target Zone developer-mode configuration could not be verified',\n      EXIT_AUTH,\n      true,\n      { reason: sanitizeMessage(decision.reason) },\n    )\n  }\n}\n\nfunction isIdentityRejection(error: unknown): error is ToolError {\n  return error instanceof ToolError && IDENTITY_REJECTION_CODES.includes(error.code)\n}\n\nexport class SdkAuthenticationTransport implements AuthenticationTransport {\n  async loginByJwt(\n    url: string,\n    jwt: string,\n    target: AuthTarget,\n    timeoutMs: number,\n  ): Promise<string> {\n    const client = new buckyos.kRPCClient(url)\n    const response = await withLocalTimeout(\n      new VerifyHubClient(client).loginByJwt({ jwt, target }),\n      timeoutMs,\n    )\n    if (!response.session_token) throw new Error('verify-hub returned no session token')\n    return response.session_token\n  }\n\n  async loginByPassword(\n    url: string,\n    username: string,\n    password: string,\n    target: AuthTarget,\n    timeoutMs: number,\n  ): Promise<string> {\n    const client = new buckyos.kRPCClient(url)\n    const verifyHub = new VerifyHubClient(client)\n    const nonce = Date.now()\n    verifyHub.setSeq(nonce)\n    const response = await withLocalTimeout(\n      verifyHub.loginByPassword({\n        username,\n        password: (buckyos.hashPassword as unknown as (\n          username: string,\n          password: string,\n          nonce?: number | null,\n        ) => string)(username, password, nonce),\n        target,\n        login_nonce: nonce,\n      }),\n      timeoutMs,\n    )\n    if (!response.session_token) throw new Error('verify-hub returned no session token')\n    return response.session_token\n  }\n}\n\nfunction identityAuthTarget(\n  principalKind: 'user' | 'device',\n  subject: string,\n): AuthTarget {\n  return principalKind === 'device'\n    ? { kind: 'system', service_id: LOGIN_APP_ID }\n    : appAuthTarget(subject)\n}\n\nfunction appAuthTarget(ownerUserId: string): AuthTarget {\n  return {\n    kind: 'app',\n    app_instance_id: createAppInstanceId(LOGIN_APP_ID, ownerUserId),\n  }\n}\n\nexport function authenticatedSession(\n  token: string,\n  authentication: AuthenticationKind,\n  renewable: boolean,\n  nowMs = Date.now(),\n): AuthenticatedSession {\n  const claims = parseClaims(token)\n  const exp = numberClaim(claims.exp)\n  const nowSeconds = Math.floor(nowMs / 1_000)\n  if (exp !== undefined && exp <= nowSeconds) {\n    throw new ToolError('SESSION_EXPIRED', 'the session token has expired', EXIT_AUTH)\n  }\n  const id = stringClaim(claims.sub) ?? stringClaim(claims.userid)\n  const appId = stringClaim(claims.appid) ?? stringClaim(claims.aud)\n  if (!id || !appId) {\n    throw new ToolError(\n      'INVALID_SESSION_TOKEN',\n      'session token is missing principal or appid claims',\n      EXIT_AUTH,\n    )\n  }\n  const appInstanceId = stringClaim(claims.app_instance_id) ??\n    stringClaim((claims.extra as Record<string, unknown> | undefined)?.app_instance_id)\n  return {\n    token,\n    claims,\n    renewable,\n    principal: {\n      id,\n      appId,\n      appInstanceId,\n      authentication,\n      tokenExpiresAt: exp === undefined ? undefined : new Date(exp * 1_000).toISOString(),\n    },\n  }\n}\n\nfunction externalSession(\n  token: string,\n  authentication: Extract<\n    AuthenticationKind,\n    'session-token' | 'session-token-file' | 'environment'\n  >,\n  nowMs: number,\n): AuthenticatedSession {\n  return authenticatedSession(token, authentication, false, nowMs)\n}\n\nfunction parseClaims(token: string): Record<string, unknown> {\n  const claims = parseSessionTokenClaims(token)\n  if (!claims) {\n    throw new ToolError('INVALID_SESSION_TOKEN', 'session token is not a valid JWT', EXIT_AUTH)\n  }\n  return claims as Record<string, unknown>\n}\n\nasync function createLoginJwt(\n  subject: string,\n  issuer: string,\n  privateKeyPem: string,\n  nowMs: number,\n): Promise<string> {\n  const now = Math.floor(nowMs / 1_000)\n  const header = { alg: 'EdDSA', kid: issuer, typ: 'JWT' }\n  const payload = {\n    token_type: 'Normal',\n    appid: LOGIN_APP_ID,\n    jti: crypto.randomUUID(),\n    session: now,\n    sub: subject,\n    userid: subject,\n    iss: issuer,\n    exp: now + LOGIN_TOKEN_TTL_SECONDS,\n    sudo: false,\n    extra: {},\n  }\n  const signingInput = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`\n  const keyBytes = pemBytes(privateKeyPem)\n  let key: CryptoKey\n  try {\n    key = await crypto.subtle.importKey(\n      'pkcs8',\n      keyBytes.slice().buffer as ArrayBuffer,\n      { name: 'Ed25519' },\n      false,\n      ['sign'],\n    )\n  } catch {\n    throw new ToolError(\n      'INVALID_PRIVATE_KEY',\n      'identity authentication key is not a valid Ed25519 PKCS8 key',\n      EXIT_AUTH,\n    )\n  }\n  const signature = await crypto.subtle.sign('Ed25519', key, new TextEncoder().encode(signingInput))\n  return `${signingInput}.${base64Url(new Uint8Array(signature))}`\n}\n\nfunction pemBytes(pem: string): Uint8Array {\n  const encoded = pem.replace(/-----[^-]+-----/g, '').replaceAll(/\\s/g, '')\n  const binary = atob(encoded)\n  return Uint8Array.from(binary, (character) => character.charCodeAt(0))\n}\n\nfunction base64Url(value: string | Uint8Array): string {\n  const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : value\n  let binary = ''\n  for (const byte of bytes) binary += String.fromCharCode(byte)\n  return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')\n}\n\nfunction stringClaim(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\nfunction numberClaim(value: unknown): number | undefined {\n  return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nasync function withLocalTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n  let timer: ReturnType<typeof setTimeout> | undefined\n  const timeout = new Promise<never>((_, reject) => {\n    timer = setTimeout(\n      () => reject(new ToolError('TIMEOUT', 'authentication timed out', 8, true)),\n      timeoutMs,\n    )\n  })\n  try {\n    return await Promise.race([promise, timeout])\n  } finally {\n    if (timer !== undefined) clearTimeout(timer)\n  }\n}\n\nasync function readVisible(prompt: string): Promise<string> {\n  return (await getHost().readLine(prompt))?.trim() ?? ''\n}\n\nasync function readSecret(prompt: string): Promise<string> {\n  if (!getHost().inputIsTerminal()) {\n    throw new ToolError(\n      'INTERACTIVE_AUTH_UNAVAILABLE',\n      'password input requires a terminal',\n      EXIT_AUTH,\n    )\n  }\n  try {\n    return await getHost().readSecret(prompt)\n  } catch (error) {\n    throw new ToolError(\n      'INTERACTIVE_AUTH_UNAVAILABLE',\n      error instanceof Error ? error.message : String(error),\n      EXIT_AUTH,\n    )\n  }\n}\n","import type { OutputFormat } from './argv.ts'\nimport type { ToolError } from './errors.ts'\n\nexport interface EnvelopeMeta {\n  command: string\n  trace_id: string\n  duration_ms: number\n}\n\nexport interface SuccessEnvelope {\n  schema_version: 1\n  ok: true\n  data: unknown\n  meta: EnvelopeMeta\n}\n\nexport interface ErrorEnvelope {\n  schema_version: 1\n  ok: false\n  error: {\n    code: string\n    message: string\n    retryable: boolean\n    details: Record<string, unknown>\n  }\n  meta: Omit<EnvelopeMeta, 'duration_ms'> & { duration_ms?: number }\n}\n\nexport function successEnvelope(data: unknown, meta: EnvelopeMeta): SuccessEnvelope {\n  return { schema_version: 1, ok: true, data, meta }\n}\n\nexport function errorEnvelope(\n  error: ToolError,\n  meta: Omit<EnvelopeMeta, 'duration_ms'> & { duration_ms?: number },\n): ErrorEnvelope {\n  return {\n    schema_version: 1,\n    ok: false,\n    error: {\n      code: error.code,\n      message: error.message,\n      retryable: error.retryable,\n      details: error.details,\n    },\n    meta,\n  }\n}\n\nexport function renderSuccess(envelope: SuccessEnvelope, format: OutputFormat): string {\n  if (format === 'json' || format === 'jsonl') return JSON.stringify(envelope)\n  if (format === 'raw') {\n    if (typeof envelope.data !== 'string') throw new Error('raw output requires a string result')\n    return envelope.data\n  }\n  if (format === 'text') return renderText(envelope.data)\n  return renderTable(envelope.data)\n}\n\nexport function renderError(envelope: ErrorEnvelope, format: OutputFormat): string {\n  if (format === 'json' || format === 'jsonl' || format === 'raw') return JSON.stringify(envelope)\n  const retryable = envelope.error.retryable ? ' (retryable)' : ''\n  return `${envelope.error.code}${retryable}: ${envelope.error.message}`\n}\n\nfunction renderText(data: unknown): string {\n  if (typeof data === 'string') return data\n  if (data && typeof data === 'object' && !Array.isArray(data)) {\n    const object = data as Record<string, unknown>\n    if (typeof object.script === 'string') return object.script\n    if (typeof object.text === 'string') return object.text\n  }\n  return JSON.stringify(data, null, 2)\n}\n\nfunction renderTable(data: unknown): string {\n  if (Array.isArray(data)) return renderRows(data)\n  if (data && typeof data === 'object') {\n    const object = data as Record<string, unknown>\n    const arrayEntry = Object.entries(object).find(([, value]) => Array.isArray(value))\n    if (arrayEntry) return renderRows(arrayEntry[1] as unknown[])\n    const rows = Object.entries(object).map(([key, value]) => ({ key, value: displayValue(value) }))\n    return renderRows(rows)\n  }\n  return String(data ?? '')\n}\n\nfunction renderRows(rows: unknown[]): string {\n  if (rows.length === 0) return '(empty)'\n  const objects = rows.map((row) =>\n    row && typeof row === 'object' && !Array.isArray(row)\n      ? row as Record<string, unknown>\n      : { value: row }\n  )\n  const columns = [...new Set(objects.flatMap((row) => Object.keys(row)))]\n  const rendered = objects.map((row) => columns.map((column) => displayValue(row[column])))\n  const widths = columns.map((column, index) =>\n    Math.max(column.length, ...rendered.map((row) => row[index].length))\n  )\n  const header = columns.map((column, index) => column.padEnd(widths[index])).join('  ')\n  const separator = widths.map((width) => '-'.repeat(width)).join('  ')\n  const body = rendered.map((row) =>\n    row.map((value, index) => value.padEnd(widths[index])).join('  ')\n  )\n  return [header, separator, ...body].join('\\n')\n}\n\nfunction displayValue(value: unknown): string {\n  if (value === null || value === undefined) return ''\n  if (typeof value === 'string') return value\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n  return JSON.stringify(value)\n}\n","import type { CommandDefinition, CommandModule, JsonSchema, RegisteredCommand } from './command.ts'\nimport { optionProperty } from './command.ts'\nimport { UsageError } from './errors.ts'\n\nconst KEBAB_CASE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\n\nconst GLOBAL_OPTIONS = [\n  { name: 'config-dir', property: 'configDir', type: 'string', scope: 'process' },\n  {\n    name: 'allow-read',\n    property: 'allowRead',\n    type: 'string',\n    scope: 'process',\n    repeatable: true,\n  },\n  { name: 'profile', property: 'profile', type: 'string', scope: 'session' },\n  { name: 'zone', property: 'zone', type: 'string', scope: 'session' },\n  { name: 'endpoint', property: 'endpoint', type: 'string', scope: 'session' },\n  { name: 'identity', property: 'identity', type: 'string', scope: 'session' },\n  {\n    name: 'session-token',\n    property: 'sessionToken',\n    type: 'string',\n    scope: 'session',\n    secret: true,\n  },\n  {\n    name: 'session-token-file',\n    property: 'sessionTokenFile',\n    type: 'string',\n    scope: 'session',\n    secret: true,\n  },\n  { name: 'cli', property: 'cli', type: 'boolean', scope: 'process' },\n  {\n    name: 'output',\n    property: 'output',\n    type: 'string',\n    scope: 'command',\n    enum: ['json', 'jsonl', 'table', 'text', 'raw'],\n  },\n  { name: 'input', property: 'input', type: 'string', scope: 'command' },\n  { name: 'timeout', property: 'timeout', type: 'duration', scope: 'command' },\n  { name: 'trace-id', property: 'traceId', type: 'string', scope: 'command' },\n  {\n    name: 'idempotency-key',\n    property: 'idempotencyKey',\n    type: 'string',\n    scope: 'command',\n  },\n  { name: 'wait', property: 'wait', type: 'boolean', scope: 'command' },\n  {\n    name: 'non-interactive',\n    property: 'nonInteractive',\n    type: 'boolean',\n    scope: 'process',\n  },\n  { name: 'yes', property: 'yes', type: 'boolean', scope: 'command' },\n  { name: 'no-color', property: 'noColor', type: 'boolean', scope: 'process' },\n  { name: 'verbose', property: 'verbose', type: 'boolean', scope: 'process' },\n  { name: 'help', property: 'help', type: 'boolean', scope: 'process' },\n  { name: 'version', property: 'version', type: 'boolean', scope: 'process' },\n]\n\nconst REPL_COMMAND_OPTION_NAMES = new Set([\n  'output',\n  'input',\n  'timeout',\n  'trace-id',\n  'idempotency-key',\n  'wait',\n  'yes',\n])\n\nexport class CommandRegistry {\n  #modules = new Map<string, CommandModule>()\n  #commands = new Map<string, RegisteredCommand>()\n\n  register(module: CommandModule): void {\n    if (!KEBAB_CASE.test(module.name)) {\n      throw new Error(`invalid module name: ${module.name}`)\n    }\n    if (this.#modules.has(module.name)) {\n      throw new Error(`duplicate module: ${module.name}`)\n    }\n    for (const definition of module.commands) {\n      this.#validateDefinition(module.name, definition)\n      const key = `${module.name}.${definition.verb}`\n      if (this.#commands.has(key)) throw new Error(`duplicate command: ${key}`)\n      this.#commands.set(key, {\n        ...definition,\n        module: module.name,\n        moduleSummary: module.summary,\n      })\n    }\n    this.#modules.set(module.name, module)\n  }\n\n  get(module: string, verb: string): RegisteredCommand {\n    const command = this.#commands.get(`${module}.${verb}`)\n    if (!command) {\n      if (!this.#modules.has(module)) {\n        throw new UsageError('UNKNOWN_MODULE', `unknown module: ${module}`)\n      }\n      throw new UsageError('UNKNOWN_COMMAND', `unknown command: ${module} ${verb}`)\n    }\n    return command\n  }\n\n  modules(): CommandModule[] {\n    return [...this.#modules.values()].sort((a, b) => a.name.localeCompare(b.name))\n  }\n\n  commands(): RegisteredCommand[] {\n    return [...this.#commands.values()].sort((a, b) =>\n      `${a.module}.${a.verb}`.localeCompare(`${b.module}.${b.verb}`)\n    )\n  }\n\n  describe(module: string, verb: string): Record<string, unknown> {\n    const command = this.get(module, verb)\n    return {\n      schema_version: 1,\n      module: command.module,\n      verb: command.verb,\n      summary: command.summary,\n      description: command.description ?? command.summary,\n      syntax: this.syntax(command),\n      global_options: GLOBAL_OPTIONS,\n      repl_command_options: GLOBAL_OPTIONS.filter((option) =>\n        REPL_COMMAND_OPTION_NAMES.has(option.name)\n      ),\n      positionals: command.positionals ?? [],\n      options: (command.options ?? []).map((option) => ({\n        ...option,\n        property: optionProperty(option),\n      })),\n      input_schema: command.inputSchema,\n      output_schema: command.outputSchema,\n      result_schema_version: command.resultSchemaVersion,\n      access: command.access,\n      async_mode: command.asyncMode,\n      requires_session: command.requiresSession,\n      execution: command.execution ?? (command.requiresSession ? 'service' : 'local'),\n      network_access: command.networkAccess ?? command.requiresSession,\n      examples: command.examples ?? [],\n    }\n  }\n\n  syntax(command: RegisteredCommand): string {\n    const positionals = (command.positionals ?? []).map((position) =>\n      position.required === false ? `[${position.name}]` : `<${position.name}>`\n    )\n    const options = (command.options ?? []).map((option) =>\n      option.type === 'boolean'\n        ? `[--${option.name}]`\n        : `[--${option.name} <${option.property ?? option.name}>]`\n    )\n    return ['buckyos', command.module, command.verb, ...positionals, ...options].join(' ')\n  }\n\n  completionCandidates(tokens: string[]): string[] {\n    if (tokens.length <= 1) return this.modules().map((module) => module.name)\n    const module = this.#modules.get(tokens[0])\n    if (!module) return this.modules().map((candidate) => candidate.name)\n    if (tokens.length === 2 && !tokens[1].startsWith('--')) {\n      return module.commands.map((command) => command.verb).sort()\n    }\n    const verb = tokens[1]\n    const command = this.#commands.get(`${module.name}.${verb}`)\n    if (!command) return module.commands.map((candidate) => candidate.verb).sort()\n    return [\n      ...(command.options ?? []).map((option) => `--${option.name}`),\n      '--input',\n      '--timeout',\n      '--trace-id',\n      '--idempotency-key',\n      '--output',\n      '--wait',\n      '--yes',\n      '--help',\n    ].sort()\n  }\n\n  #validateDefinition(module: string, definition: CommandDefinition): void {\n    if (!KEBAB_CASE.test(definition.verb)) {\n      throw new Error(`invalid verb name: ${module} ${definition.verb}`)\n    }\n    const positionals = definition.positionals ?? []\n    const positionalNames = new Set<string>()\n    for (const positional of positionals) {\n      if (positionalNames.has(positional.name)) {\n        throw new Error(`duplicate positional ${positional.name} in ${module}.${definition.verb}`)\n      }\n      positionalNames.add(positional.name)\n    }\n    const optionNames = new Set<string>()\n    for (const option of definition.options ?? []) {\n      if (!KEBAB_CASE.test(option.name) || optionNames.has(option.name)) {\n        throw new Error(\n          `invalid or duplicate option --${option.name} in ${module}.${definition.verb}`,\n        )\n      }\n      optionNames.add(option.name)\n    }\n    this.#assertObjectSchema(definition.inputSchema, `${module}.${definition.verb} input`)\n    this.#assertObjectSchema(definition.outputSchema, `${module}.${definition.verb} output`)\n  }\n\n  #assertObjectSchema(schema: JsonSchema, label: string): void {\n    if (schema.type !== 'object') throw new Error(`${label} schema must be an object`)\n  }\n}\n","import type { RegisteredCommand } from './command.ts'\nimport { getHost, isHostError } from '../runtime/host.ts'\nimport { optionProperty } from './command.ts'\nimport { parseShellLine } from './argv.ts'\n\nconst SECRET_WORDS =\n  /(?:session[-_]?token|refresh[-_]?token|password|private[-_]?key|sudo[-_]?token)/i\n\nexport class ReplHistory {\n  readonly path: string\n  readonly limit: number\n  #entries: string[] = []\n\n  constructor(path: string, limit = 500) {\n    this.path = path\n    this.limit = limit\n  }\n\n  async load(): Promise<string[]> {\n    try {\n      this.#entries = (await getHost().readTextFile(this.path))\n        .split(/\\r?\\n/)\n        .map((line) => line.trim())\n        .filter(Boolean)\n        .slice(-this.limit)\n    } catch (error) {\n      if (!isHostError(error, 'NotFound')) throw error\n      this.#entries = []\n    }\n    return [...this.#entries]\n  }\n\n  entries(): string[] {\n    return [...this.#entries]\n  }\n\n  async add(line: string, command?: RegisteredCommand): Promise<void> {\n    if (!shouldPersistHistory(line, command)) return\n    if (this.#entries.at(-1) !== line) this.#entries.push(line)\n    this.#entries = this.#entries.slice(-this.limit)\n    const host = getHost()\n    await host.mkdir(host.path.dirname(this.path), { recursive: true, mode: 0o700 })\n    await host.writeTextFile(this.path, `${this.#entries.join('\\n')}\\n`, { mode: 0o600 })\n    if (host.platform !== 'windows') await host.chmod(this.path, 0o600)\n  }\n}\n\nexport function shouldPersistHistory(line: string, command?: RegisteredCommand): boolean {\n  if (SECRET_WORDS.test(line)) return false\n  if (!command) return true\n  if (Object.values(command.inputSchema.properties ?? {}).some((schema) => schema.secret)) {\n    return false\n  }\n  let tokens: string[]\n  try {\n    tokens = parseShellLine(line)\n  } catch {\n    return false\n  }\n  const secretOptions = new Set(\n    (command.options ?? []).filter((option) => option.secret).flatMap((option) => [\n      `--${option.name}`,\n      optionProperty(option),\n    ]),\n  )\n  return !tokens.some((token) => secretOptions.has(token.split('=', 1)[0]))\n}\n","import type { CommandRegistry } from './registry.ts'\nimport type { ConfigStore, ResolvedConfig } from './config.ts'\nimport { effectiveConfigView } from './config.ts'\nimport { parseShellLine } from './argv.ts'\nimport { normalizeError } from './errors.ts'\nimport { ReplHistory } from './history.ts'\nimport type { InteractiveSession } from './runtime.ts'\nimport { getHost, type HostLineReader } from '../runtime/host.ts'\n\nexport interface ReplOptions {\n  registry: CommandRegistry\n  config: ResolvedConfig\n  configStore: ConfigStore\n  session: InteractiveSession\n  execute(tokens: string[], signal: AbortSignal): Promise<void>\n}\n\nexport async function runRepl(options: ReplOptions): Promise<void> {\n  const history = new ReplHistory(options.configStore.historyPath())\n  const savedHistory = await history.load()\n  const completer = (line: string): [string[], string] => {\n    const fragment = line.match(/[^\\s]*$/)?.[0] ?? ''\n    const prefix = line.slice(0, line.length - fragment.length)\n    let tokens: string[]\n    try {\n      tokens = parseShellLine(prefix)\n    } catch {\n      tokens = prefix.trim().split(/\\s+/).filter(Boolean)\n    }\n    tokens.push(fragment)\n    const candidates = options.registry.completionCandidates(tokens)\n    return [candidates.filter((candidate) => candidate.startsWith(fragment)), fragment]\n  }\n  let running: AbortController | undefined\n  const readline: HostLineReader = getHost().createLineReader({\n    history: [...savedHistory].reverse(),\n    historySize: history.limit,\n    completer,\n    onSigint: () => {\n      if (running) running.abort()\n      else {\n        readline.write('^C\\n')\n        readline.prompt()\n      }\n    },\n  })\n  const prompt = replPrompt(options.config)\n  readline.write('BuckyOS interactive session. Use :help for commands and :exit to quit.\\n')\n  readline.setPrompt(prompt)\n  readline.prompt()\n\n  try {\n    for await (const rawLine of readline) {\n      const line = rawLine.trim()\n      if (!line) {\n        readline.prompt()\n        continue\n      }\n      if (line.startsWith(':')) {\n        const shouldExit = await handleBuiltin(line, options, history)\n        if (shouldExit) break\n        readline.prompt()\n        continue\n      }\n\n      let tokens: string[]\n      try {\n        tokens = parseShellLine(line)\n      } catch (error) {\n        const normalized = normalizeError(error)\n        readline.write(`${normalized.code}: ${normalized.message}\\n`)\n        readline.prompt()\n        continue\n      }\n      let command\n      try {\n        if (tokens.length >= 2) command = options.registry.get(tokens[0], tokens[1])\n      } catch {\n        command = undefined\n      }\n      await history.add(line, command)\n      running = new AbortController()\n      try {\n        await options.execute(tokens, running.signal)\n      } catch (error) {\n        const normalized = normalizeError(error)\n        readline.write(`${normalized.code}: ${normalized.message}\\n`)\n      } finally {\n        running = undefined\n      }\n      readline.prompt()\n    }\n  } finally {\n    readline.close()\n  }\n}\n\nasync function handleBuiltin(\n  line: string,\n  options: ReplOptions,\n  history: ReplHistory,\n): Promise<boolean> {\n  const command = line.split(/\\s+/, 1)[0]\n  switch (command) {\n    case ':exit':\n    case ':quit':\n      return true\n    case ':help':\n      await getHost().stderr(\n        [\n          'Enter: <module> <verb> [primary-selector] [action-options]',\n          'Built-ins: :help :context :session :history :reconnect :exit :quit',\n          `Modules: ${options.registry.modules().map((module) => module.name).join(', ')}`,\n          '',\n        ].join('\\n'),\n      )\n      break\n    case ':context':\n      await getHost().stderr(`${JSON.stringify(effectiveConfigView(options.config), null, 2)}\\n`)\n      break\n    case ':session':\n      await getHost().stderr(\n        `${JSON.stringify(options.session.authentication.status(), null, 2)}\\n`,\n      )\n      break\n    case ':history':\n      await getHost().stderr(\n        `${history.entries().map((entry, index) => `${index + 1}  ${entry}`).join('\\n')}\\n`,\n      )\n      break\n    case ':reconnect':\n      try {\n        await options.session.reconnect()\n        await getHost().stderr('session reconnected\\n')\n      } catch (error) {\n        const normalized = normalizeError(error)\n        await getHost().stderr(`${normalized.code}: ${normalized.message}\\n`)\n      }\n      break\n    default:\n      await getHost().stderr(`unknown REPL command: ${command}\\n`)\n  }\n  return false\n}\n\nfunction replPrompt(config: ResolvedConfig): string {\n  const profile = config.profileName ?? 'default'\n  const zone = config.zone ?? (config.endpoint ? new URL(config.endpoint).host : 'unresolved')\n  const identity = config.identity ?? 'external-session'\n  return `buckyos[${profile}|${zone}|${identity}]> `\n}\n","import type { CommandModule } from '../core/command.ts'\nimport { ToolError } from '../core/errors.ts'\n\nconst EMPTY_INPUT = { type: 'object' as const, properties: {}, additionalProperties: false }\nconst OBJECT_OUTPUT = { type: 'object' as const, additionalProperties: true }\n\nexport function createAuthModule(): CommandModule {\n  return {\n    name: 'auth',\n    summary: 'Inspect the current authenticated session',\n    commands: [\n      {\n        verb: 'whoami',\n        summary: 'Show the effective principal and application identity',\n        inputSchema: EMPTY_INPUT,\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: ['buckyos --profile production auth whoami'],\n        handler: (ctx) =>\n          Promise.resolve({\n            principal: ctx.principal.id,\n            appid: ctx.principal.appId,\n            app_instance_id: ctx.principal.appInstanceId ?? null,\n            authentication: ctx.principal.authentication,\n            zone: ctx.connection.zone,\n          }),\n      },\n      {\n        verb: 'session-status',\n        summary: 'Show the in-memory session state without exposing credentials',\n        inputSchema: EMPTY_INPUT,\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: ['buckyos --profile production auth session-status'],\n        handler: (ctx) => {\n          if (!ctx.session) {\n            throw new ToolError('INTERNAL_ERROR', 'authenticated session is unavailable', 9)\n          }\n          return Promise.resolve(ctx.session.status())\n        },\n      },\n    ],\n  }\n}\n","import type { CommandModule } from '../core/command.ts'\nimport type { CommandRegistry } from '../core/registry.ts'\nimport {\n  configValueError,\n  effectiveConfigView,\n  type ProfileConfig,\n  type ToolConfig,\n  validateProfileName,\n} from '../core/config.ts'\nimport { UsageError } from '../core/errors.ts'\n\nconst EMPTY_INPUT = {\n  type: 'object' as const,\n  properties: {},\n  additionalProperties: false,\n}\nconst OBJECT_OUTPUT = { type: 'object' as const, additionalProperties: true }\n\nexport function createCoreModules(registry: CommandRegistry): CommandModule[] {\n  return [createCommandModule(registry), createConfigModule(), createCompletionModule(registry)]\n}\n\nfunction createCommandModule(registry: CommandRegistry): CommandModule {\n  return {\n    name: 'command',\n    summary: 'Discover the machine-readable command registry',\n    commands: [\n      {\n        verb: 'list',\n        summary: 'List registered modules and commands',\n        inputSchema: EMPTY_INPUT,\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        examples: ['buckyos command list'],\n        handler: () =>\n          Promise.resolve({\n            modules: registry.modules().map((module) => ({\n              name: module.name,\n              summary: module.summary,\n              commands: module.commands.map((command) => ({\n                verb: command.verb,\n                summary: command.summary,\n              })),\n            })),\n          }),\n      },\n      {\n        verb: 'describe',\n        summary: 'Describe one command and its complete schemas',\n        positionals: [\n          { name: 'target_module', description: 'Module name' },\n          { name: 'target_verb', description: 'Verb name' },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: {\n            target_module: { type: 'string', minLength: 1 },\n            target_verb: { type: 'string', minLength: 1 },\n          },\n          required: ['target_module', 'target_verb'],\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        examples: ['buckyos command describe system status'],\n        handler: (_ctx, input) =>\n          Promise.resolve(\n            registry.describe(String(input.target_module), String(input.target_verb)),\n          ),\n      },\n    ],\n  }\n}\n\nfunction createConfigModule(): CommandModule {\n  return {\n    name: 'config',\n    summary: 'Manage local non-secret tool configuration',\n    commands: [\n      {\n        verb: 'list',\n        summary: 'List the global configuration and available profiles',\n        inputSchema: EMPTY_INPUT,\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        examples: ['buckyos config list'],\n        handler: async (ctx) => ({\n          config: await ctx.configStore.readConfig(),\n          profiles: await ctx.configStore.listProfiles(),\n        }),\n      },\n      {\n        verb: 'get',\n        summary: 'Read a global or profile configuration value',\n        positionals: [{ name: 'key', description: 'Configuration key', required: false }],\n        options: [\n          {\n            name: 'profile-name',\n            property: 'profile_name',\n            description: 'Read a profile',\n            type: 'string',\n          },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: {\n            key: { type: 'string', minLength: 1 },\n            profile_name: { type: 'string', minLength: 1 },\n          },\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        examples: [\n          'buckyos config get output',\n          'buckyos config get zone --profile-name production',\n        ],\n        handler: async (ctx, input) => {\n          const profileName = optionalString(input.profile_name)\n          const value = profileName\n            ? await ctx.configStore.readProfile(profileName)\n            : await ctx.configStore.readConfig()\n          if (!value) throw new UsageError('PROFILE_NOT_FOUND', `profile not found: ${profileName}`)\n          const key = optionalString(input.key)\n          if (!key) return { value }\n          if (!Object.hasOwn(value, key)) {\n            throw new UsageError('CONFIG_KEY_NOT_FOUND', `configuration key not found: ${key}`)\n          }\n          return { key, value: (value as unknown as Record<string, unknown>)[key] }\n        },\n      },\n      {\n        verb: 'set',\n        summary: 'Atomically set a global or profile configuration value',\n        positionals: [{ name: 'key', description: 'Configuration key' }],\n        options: [\n          { name: 'value', description: 'Configuration value', type: 'string', required: true },\n          {\n            name: 'profile-name',\n            property: 'profile_name',\n            description: 'Write a profile',\n            type: 'string',\n          },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: {\n            key: { type: 'string', minLength: 1 },\n            value: { type: 'string' },\n            profile_name: { type: 'string', minLength: 1 },\n          },\n          required: ['key', 'value'],\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'write' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        examples: [\n          'buckyos config set output --value json',\n          'buckyos config set zone --value corp.example.com --profile-name production',\n        ],\n        handler: async (ctx, input) => {\n          const key = String(input.key)\n          const rawValue = String(input.value)\n          const profileName = optionalString(input.profile_name)\n          if (profileName) {\n            validateProfileName(profileName)\n            const profile = await ctx.configStore.readProfile(profileName) ?? { schema_version: 1 }\n            setProfileValue(profile, key, rawValue)\n            await ctx.configStore.writeProfile(profileName, profile)\n            return {\n              profile: profileName,\n              key,\n              value: (profile as unknown as Record<string, unknown>)[key],\n            }\n          }\n          const config = await ctx.configStore.readConfig()\n          setGlobalValue(config, key, rawValue)\n          await ctx.configStore.writeConfig(config)\n          return { profile: null, key, value: (config as unknown as Record<string, unknown>)[key] }\n        },\n      },\n      {\n        verb: 'use',\n        summary: 'Select the default profile',\n        positionals: [{ name: 'profile_name', description: 'Profile name' }],\n        inputSchema: {\n          type: 'object',\n          properties: { profile_name: { type: 'string', minLength: 1 } },\n          required: ['profile_name'],\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'write' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        examples: ['buckyos config use production'],\n        handler: async (ctx, input) => {\n          const profileName = String(input.profile_name)\n          if (!await ctx.configStore.readProfile(profileName)) {\n            throw new UsageError('PROFILE_NOT_FOUND', `profile not found: ${profileName}`)\n          }\n          const config = await ctx.configStore.readConfig()\n          config.default_profile = profileName\n          await ctx.configStore.writeConfig(config)\n          return { default_profile: profileName }\n        },\n      },\n      {\n        verb: 'check',\n        summary: 'Validate configuration and show a redacted effective view',\n        options: [\n          {\n            name: 'effective',\n            description: 'Include the effective merged configuration',\n            type: 'boolean',\n          },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: { effective: { type: 'boolean' } },\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        examples: ['buckyos --profile production config check --effective'],\n        handler: async (ctx, input) => ({\n          valid: true,\n          profile_count: (await ctx.configStore.listProfiles()).length,\n          ...(input.effective ? { effective: effectiveConfigView(ctx.config) } : {}),\n        }),\n      },\n    ],\n  }\n}\n\nfunction createCompletionModule(registry: CommandRegistry): CommandModule {\n  return {\n    name: 'completion',\n    summary: 'Generate shell completion scripts from the command registry',\n    commands: [\n      {\n        verb: 'generate',\n        summary: 'Generate completion for bash, zsh, or fish',\n        options: [\n          {\n            name: 'shell',\n            description: 'Target shell',\n            type: 'string',\n            required: true,\n            enum: ['bash', 'zsh', 'fish'],\n          },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: { shell: { type: 'string', enum: ['bash', 'zsh', 'fish'] } },\n          required: ['shell'],\n          additionalProperties: false,\n        },\n        outputSchema: {\n          type: 'object',\n          properties: { shell: { type: 'string' }, script: { type: 'string' } },\n          required: ['shell', 'script'],\n          additionalProperties: false,\n        },\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        examples: ['buckyos --output text completion generate --shell bash'],\n        handler: (_ctx, input) => {\n          const shell = String(input.shell)\n          return Promise.resolve({ shell, script: completionScript(registry, shell) })\n        },\n      },\n    ],\n  }\n}\n\nfunction setGlobalValue(config: ToolConfig, key: string, value: string): void {\n  if (key === 'default_profile') {\n    validateProfileName(value)\n    config.default_profile = value\n  } else if (key === 'output') {\n    config.output = outputValue(value)\n  } else {\n    throw configValueError(`unsupported global configuration key: ${key}`)\n  }\n}\n\nfunction setProfileValue(profile: ProfileConfig, key: string, value: string): void {\n  if (key === 'zone' || key === 'endpoint' || key === 'identity') profile[key] = value\n  else if (key === 'default_protocol') {\n    if (value !== 'http://' && value !== 'https://') {\n      throw configValueError('default_protocol must be http:// or https://')\n    }\n    profile.default_protocol = value\n  } else if (key === 'output') profile.output = outputValue(value)\n  else throw configValueError(`unsupported profile configuration key: ${key}`)\n}\n\nfunction outputValue(value: string): 'json' | 'jsonl' | 'table' | 'text' | 'raw' {\n  if (!['json', 'jsonl', 'table', 'text', 'raw'].includes(value)) {\n    throw configValueError(`invalid output format: ${value}`)\n  }\n  return value as 'json' | 'jsonl' | 'table' | 'text' | 'raw'\n}\n\nfunction optionalString(value: unknown): string | undefined {\n  return typeof value === 'string' && value ? value : undefined\n}\n\nfunction completionScript(registry: CommandRegistry, shell: string): string {\n  const modules = registry.modules().map((module) => module.name).join(' ')\n  const commands = registry.commands().map((command) => `${command.module}:${command.verb}`).join(\n    ' ',\n  )\n  if (shell === 'fish') {\n    return `complete -c buckyos -f\\ncomplete -c buckyos -n '__fish_use_subcommand' -a '${modules}'\\n# ${commands}\\n`\n  }\n  if (shell === 'zsh') {\n    return `#compdef buckyos\\n_arguments '1:module:(${modules})' '*::argument:->args'\\n# ${commands}\\n`\n  }\n  return `_buckyos_complete() {\\n  if [ \"${'${COMP_CWORD}'}\" -eq 1 ]; then\\n    COMPREPLY=( $(compgen -W '${modules}' -- \"${'${COMP_WORDS[COMP_CWORD]}'}\") )\\n  fi\\n}\\ncomplete -F _buckyos_complete buckyos\\n# ${commands}\\n`\n}\n","import type { CommandContext } from './context.ts'\nimport { EXIT_INTERNAL, ToolError, UsageError } from './errors.ts'\n\nexport function rpcOptions(ctx: CommandContext): {\n  traceId: string\n  timeoutMs: number\n  signal: AbortSignal\n} {\n  return {\n    traceId: ctx.traceId,\n    timeoutMs: Math.max(1, (ctx.deadline ?? Date.now()) - Date.now()),\n    signal: ctx.signal,\n  }\n}\n\nexport async function callService<T = unknown>(\n  ctx: CommandContext,\n  service: string,\n  method: string,\n  params: Record<string, unknown>,\n): Promise<T> {\n  try {\n    return await ctx.clients.call<T>(service, method, params, rpcOptions(ctx))\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error)\n    const stable = message.match(/\\b((?:TASK|AUDIT|DIAGNOSTIC|LOG)_[A-Z0-9_]+):/)\n    if (stable) throw new ToolError(stable[1], message)\n    throw error\n  }\n}\n\nexport function expectObject(value: unknown, label: string): Record<string, unknown> {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `${label} must be an object`, EXIT_INTERNAL)\n  }\n  return value as Record<string, unknown>\n}\n\nexport function expectString(value: unknown, label: string): string {\n  if (typeof value !== 'string' || !value.trim()) {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `${label} must be a string`, EXIT_INTERNAL)\n  }\n  return value\n}\n\nexport function inputString(input: Record<string, unknown>, key: string): string | undefined {\n  const value = input[key]\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\nexport function requiredInputString(input: Record<string, unknown>, key: string): string {\n  const value = inputString(input, key)\n  if (!value) throw new UsageError('INVALID_ARGUMENT', `${key} is required`)\n  return value\n}\n\nexport function parseTimestamp(value: unknown, key: string): number | undefined {\n  if (value === undefined) return undefined\n  if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value\n  if (typeof value !== 'string' || !value.trim()) {\n    throw new UsageError('INVALID_ARGUMENT', `${key} must be RFC 3339 or Unix milliseconds`)\n  }\n  if (/^\\d+$/.test(value)) {\n    const milliseconds = Number(value)\n    if (Number.isSafeInteger(milliseconds)) return milliseconds\n  }\n  const milliseconds = Date.parse(value)\n  if (!Number.isFinite(milliseconds)) {\n    throw new UsageError('INVALID_ARGUMENT', `${key} must be RFC 3339 or Unix milliseconds`)\n  }\n  return milliseconds\n}\n\nexport function splitServices(value: unknown): string[] {\n  const items = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : []\n  return [...new Set(items.map((item) => String(item).trim()).filter(Boolean))]\n}\n","import type { CommandModule, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { callService, expectObject } from '../core/service.ts'\n\nconst CONTROL_PANEL = 'control-panel'\nconst EMPTY_INPUT: JsonSchema = { type: 'object', properties: {}, additionalProperties: false }\nconst BUCKYOS_INFO: JsonSchema = {\n  type: 'object',\n  properties: {\n    version: { type: 'string' },\n    build_version: { type: 'string' },\n    release_channel: { type: 'string' },\n    target: { type: 'string' },\n  },\n  additionalProperties: true,\n}\n\nexport function createSystemModule(): CommandModule {\n  return {\n    name: 'system',\n    summary: 'Inspect BuckyOS Zone health and version state',\n    commands: [\n      {\n        verb: 'status',\n        summary: 'Get host resource state, configured service keys, and the BuckyOS version',\n        description:\n          'state and warnings come from CPU/memory/disk/swap of the Control Panel host; services lists the keys under services/ with status unknown (not a per-service health check); buckyos is the system.buckyos_info.get record.',\n        inputSchema: EMPTY_INPUT,\n        outputSchema: {\n          type: 'object',\n          properties: { buckyos: BUCKYOS_INFO },\n          required: ['buckyos'],\n          additionalProperties: true,\n        },\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: ['buckyos --profile production system status'],\n        handler: async (ctx) => {\n          const [status, buckyos] = await Promise.all([\n            callService(ctx, CONTROL_PANEL, 'system.status', {}),\n            buckyosInfo(ctx),\n          ])\n          return { ...expectObject(status, 'system.status'), buckyos }\n        },\n      },\n      {\n        verb: 'info',\n        summary: 'Get the installed BuckyOS version, build version, and release channel',\n        description:\n          'build_version is build<YYMMDD>.<branch>.<commit12>[.dirty]; any authenticated identity may read it.',\n        inputSchema: EMPTY_INPUT,\n        outputSchema: BUCKYOS_INFO,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: ['buckyos system info'],\n        handler: async (ctx) => await buckyosInfo(ctx),\n      },\n    ],\n  }\n}\n\nasync function buckyosInfo(ctx: CommandContext): Promise<Record<string, unknown>> {\n  return expectObject(\n    await callService(ctx, CONTROL_PANEL, 'system.buckyos_info.get', {}),\n    'system.buckyos_info.get',\n  )\n}\n","import type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { EXIT_INTERNAL, ToolError, UsageError } from '../core/errors.ts'\nimport { getHost } from '../runtime/host.ts'\n\nconst SERVICE_NAME = 'system_config'\nconst OBJECT_OUTPUT = { type: 'object' as const, additionalProperties: false }\nconst KEY_INPUT: JsonSchema = {\n  type: 'object',\n  properties: { key: { type: 'string', minLength: 1 } },\n  required: ['key'],\n  additionalProperties: false,\n}\n\nexport function createSystemConfigModule(): CommandModule {\n  return {\n    name: 'system-config',\n    summary: 'Read and modify the Zone system-config key-value store',\n    commands: [\n      {\n        verb: 'get',\n        summary: 'Get one system-config value',\n        positionals: [{ name: 'key', description: 'System-config key' }],\n        inputSchema: KEY_INPUT,\n        outputSchema: {\n          ...OBJECT_OUTPUT,\n          properties: {\n            key: { type: 'string' },\n            value: { type: 'string' },\n            version: { type: 'integer' },\n            text: { type: 'string' },\n          },\n          required: ['key', 'value', 'version', 'text'],\n        },\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: [\n          'buckyos --profile production system-config get boot/config',\n          'buckyos --output text system-config get services/example/config',\n        ],\n        handler: async (ctx, input) => {\n          const key = String(input.key)\n          const result = await callSystemConfig<unknown>(ctx, 'sys_config_get', { key })\n          if (result === null) {\n            throw new ToolError(\n              'RESOURCE_NOT_FOUND',\n              `system-config key not found: ${key}`,\n            )\n          }\n          if (!isConfigValue(result)) invalidResponse('sys_config_get')\n          return { key, value: result.value, version: result.version, text: result.value }\n        },\n      },\n      {\n        verb: 'list',\n        summary: 'List direct child keys under a system-config key',\n        positionals: [\n          { name: 'key', description: 'Parent key; omit to list the root', required: false },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: { key: { type: 'string' } },\n          additionalProperties: false,\n        },\n        outputSchema: {\n          ...OBJECT_OUTPUT,\n          properties: {\n            key: { type: 'string' },\n            items: { type: 'array', items: { type: 'string' } },\n          },\n          required: ['key', 'items'],\n        },\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: [\n          'buckyos system-config list',\n          'buckyos system-config list services',\n        ],\n        handler: async (ctx, input) => {\n          const key = typeof input.key === 'string' ? input.key : ''\n          const result = await callSystemConfig<unknown>(ctx, 'sys_config_list', { key })\n          if (!Array.isArray(result) || !result.every((item) => typeof item === 'string')) {\n            invalidResponse('sys_config_list')\n          }\n          return { key, items: result as string[] }\n        },\n      },\n      setCommand(),\n      setFileCommand(),\n      mutationCommand({\n        verb: 'append',\n        summary: 'Append text to an existing system-config value',\n        method: 'sys_config_append',\n        valueProperty: 'append_value',\n        resultProperty: 'appended',\n      }),\n    ],\n  }\n}\n\nfunction setCommand(): CommandDefinition {\n  return {\n    verb: 'set',\n    summary: 'Set one system-config value',\n    positionals: [{ name: 'key', description: 'System-config key' }],\n    options: [\n      { name: 'value', description: 'Value to store', type: 'string', required: true },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        key: { type: 'string', minLength: 1 },\n        value: { type: 'string', minLength: 1 },\n      },\n      required: ['key', 'value'],\n      additionalProperties: false,\n    },\n    outputSchema: {\n      ...OBJECT_OUTPUT,\n      properties: { key: { type: 'string' }, updated: { type: 'boolean' } },\n      required: ['key', 'updated'],\n    },\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos system-config set services/example/config --value enabled'],\n    handler: async (ctx, input) => {\n      const key = String(input.key)\n      await callSystemConfig(ctx, 'sys_config_set', { key, value: String(input.value) })\n      return { key, updated: true }\n    },\n  }\n}\n\nfunction setFileCommand(): CommandDefinition {\n  return {\n    verb: 'set-file',\n    summary: 'Set one system-config value from a file',\n    positionals: [{ name: 'key', description: 'System-config key' }],\n    options: [\n      {\n        name: 'file',\n        description: 'File whose content will be stored',\n        type: 'string',\n        required: true,\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        key: { type: 'string', minLength: 1 },\n        file: { type: 'string', minLength: 1 },\n      },\n      required: ['key', 'file'],\n      additionalProperties: false,\n    },\n    outputSchema: {\n      ...OBJECT_OUTPUT,\n      properties: { key: { type: 'string' }, updated: { type: 'boolean' } },\n      required: ['key', 'updated'],\n    },\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos system-config set-file services/example/config --file ./config.json'],\n    handler: async (ctx, input) => {\n      const key = String(input.key)\n      const value = await readValueFile(String(input.file))\n      if (!value) throw new UsageError('INVALID_ARGUMENT', 'system-config value must not be empty')\n      await callSystemConfig(ctx, 'sys_config_set', { key, value })\n      return { key, updated: true }\n    },\n  }\n}\n\nfunction mutationCommand(options: {\n  verb: string\n  summary: string\n  method: string\n  valueProperty: string\n  resultProperty: string\n}): CommandDefinition {\n  return {\n    verb: options.verb,\n    summary: options.summary,\n    positionals: [{ name: 'key', description: 'System-config key' }],\n    options: [\n      { name: 'value', description: 'Value to append', type: 'string', required: true },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        key: { type: 'string', minLength: 1 },\n        value: { type: 'string', minLength: 1 },\n      },\n      required: ['key', 'value'],\n      additionalProperties: false,\n    },\n    outputSchema: {\n      ...OBJECT_OUTPUT,\n      properties: {\n        key: { type: 'string' },\n        [options.resultProperty]: { type: 'boolean' },\n      },\n      required: ['key', options.resultProperty],\n    },\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: [`buckyos system-config ${options.verb} system/rbac/policy --value 'p,...'`],\n    handler: async (ctx, input) => {\n      const key = String(input.key)\n      await callSystemConfig(ctx, options.method, {\n        key,\n        [options.valueProperty]: String(input.value),\n      })\n      return { key, [options.resultProperty]: true }\n    },\n  }\n}\n\nasync function callSystemConfig<T = unknown>(\n  ctx: CommandContext,\n  method: string,\n  params: Record<string, unknown>,\n): Promise<T> {\n  return await ctx.clients.call<T>(SERVICE_NAME, method, params, {\n    traceId: ctx.traceId,\n    timeoutMs: Math.max(1, (ctx.deadline ?? Date.now()) - Date.now()),\n    signal: ctx.signal,\n  })\n}\n\nasync function readValueFile(path: string): Promise<string> {\n  try {\n    return await getHost().readTextFile(path)\n  } catch (error) {\n    throw new UsageError(\n      'INPUT_READ_FAILED',\n      `failed to read value file: ${error instanceof Error ? error.message : String(error)}`,\n    )\n  }\n}\n\nfunction isConfigValue(value: unknown): value is { value: string; version: number } {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n  const object = value as Record<string, unknown>\n  return typeof object.value === 'string' && Number.isSafeInteger(object.version) &&\n    Number(object.version) >= 0\n}\n\nfunction invalidResponse(method: string): never {\n  throw new ToolError(\n    'INVALID_SERVICE_RESPONSE',\n    `system-config returned an invalid response for ${method}`,\n    EXIT_INTERNAL,\n  )\n}\n","import { ToolError, UsageError } from '../core/errors.ts'\nimport {\n  getHost,\n  type HostDirEntry,\n  type HostFile,\n  type HostFileInfo,\n  isHostError,\n} from '../runtime/host.ts'\n\nconst dirname = (path: string) => getHost().path.dirname(path)\nconst relative = (from: string, to: string) => getHost().path.relative(from, to)\nconst resolve = (...parts: string[]) => getHost().path.resolve(...parts)\n\nconst BLOCK_SIZE = 512\nconst ZIP_LOCAL_SIGNATURE = 0x04034b50\nconst ZIP_CENTRAL_SIGNATURE = 0x02014b50\nconst ZIP_EOCD_SIGNATURE = 0x06054b50\nconst ZIP64_EOCD_SIGNATURE = 0x06064b50\nconst ZIP64_LOCATOR_SIGNATURE = 0x07064b50\nconst MAX_CENTRAL_DIRECTORY = 64 * 1024 * 1024\nexport const MAX_PIKG_ENTRIES = 4096\n\nconst CRC_TABLE = new Uint32Array(256)\nfor (let index = 0; index < CRC_TABLE.length; index++) {\n  let value = index\n  for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ (value & 1 ? 0xedb88320 : 0)\n  CRC_TABLE[index] = value >>> 0\n}\n\nexport interface FileDigest {\n  size: number\n  sha256: string\n  crc32: number\n}\n\nexport interface ZipEntry {\n  name: string\n  compressedSize: number\n  size: number\n  crc32: number\n  compression: number\n  flags: number\n  localOffset: number\n  dataOffset: number\n  externalAttributes: number\n  isDirectory: boolean\n}\n\nexport interface OpenZip {\n  path: string\n  size: number\n  entries: ZipEntry[]\n  byName: Map<string, ZipEntry>\n}\n\ninterface TarSource {\n  archivePath: string\n  physicalPath: string\n  kind: 'file' | 'directory'\n  size: number\n  executable: boolean\n  identity: string\n  contentDigest?: string\n}\n\ninterface ZipWriteSource {\n  name: string\n  bytes?: Uint8Array\n  path?: string\n}\n\nexport async function digestFile(path: string): Promise<FileDigest> {\n  const file = await getHost().open(path, { read: true })\n  const sha = getHost().createHash('sha256')\n  let crc = 0xffffffff\n  let size = 0\n  try {\n    const buffer = new Uint8Array(256 * 1024)\n    while (true) {\n      const read = await file.read(buffer)\n      if (read === null) break\n      const chunk = buffer.subarray(0, read)\n      sha.update(chunk)\n      crc = updateCrc32(crc, chunk)\n      size += read\n      if (!Number.isSafeInteger(size)) throw new UsageError('FILE_TOO_LARGE', 'file is too large')\n    }\n  } finally {\n    await file.close()\n  }\n  return { size, sha256: sha.digestHex(), crc32: (crc ^ 0xffffffff) >>> 0 }\n}\n\nexport function sha256Bytes(bytes: Uint8Array): string {\n  const sha = getHost().createHash('sha256')\n  sha.update(bytes)\n  return sha.digestHex()\n}\n\nexport async function createDeterministicTarGz(\n  sourceDir: string,\n  destination: string,\n): Promise<void> {\n  const root = await getHost().realPath(sourceDir)\n  const before = await collectTarSources(root)\n  const tarPath = `${destination}.tar-${crypto.randomUUID()}`\n  const tar = await getHost().open(tarPath, { createNew: true, write: true, mode: 0o600 })\n  try {\n    for (const source of before) {\n      const header = tarHeader(source)\n      await writeAll(tar, header)\n      if (source.kind === 'file') {\n        await copyFileToWriter(source.physicalPath, tar)\n        const padding = (BLOCK_SIZE - source.size % BLOCK_SIZE) % BLOCK_SIZE\n        if (padding) await writeAll(tar, new Uint8Array(padding))\n      }\n    }\n    await writeAll(tar, new Uint8Array(BLOCK_SIZE * 2))\n    await tar.sync()\n  } finally {\n    await tar.close()\n  }\n\n  try {\n    const after = await collectTarSources(root)\n    if (JSON.stringify(before.map(sourceIdentity)) !== JSON.stringify(after.map(sourceIdentity))) {\n      throw new ToolError('SOURCE_CHANGED', 'subpackage source changed while it was archived')\n    }\n    await gzipFile(tarPath, destination)\n  } finally {\n    await removeIfExists(tarPath)\n  }\n}\n\nexport async function gzipFile(source: string, destination: string): Promise<void> {\n  await getHost().gzipFile(source, destination)\n}\n\nexport interface TarFileEntry {\n  path: string\n  executable: boolean\n  bytes: Uint8Array\n}\n\nexport async function readTarGz(bytes: Uint8Array, limit: number): Promise<TarFileEntry[]> {\n  const tar = await gunzipBytes(bytes, limit)\n  const files: TarFileEntry[] = []\n  const seen = new Set<string>()\n  let offset = 0\n  while (\n    offset + BLOCK_SIZE <= tar.length && tar.subarray(offset, offset + BLOCK_SIZE).some(Boolean)\n  ) {\n    const header = parseTarHeader(tar.subarray(offset, offset + BLOCK_SIZE))\n    const start = offset + BLOCK_SIZE\n    if (start + header.size > tar.length) {\n      throw invalidZip('payload', `tar entry is truncated: ${header.path}`)\n    }\n    offset = start + Math.ceil(header.size / BLOCK_SIZE) * BLOCK_SIZE\n    if (header.kind !== 'file') continue\n    if (seen.has(header.path)) throw invalidZip('payload', `duplicate tar entry: ${header.path}`)\n    seen.add(header.path)\n    files.push({ path: header.path, executable: header.executable, bytes: tar.slice(start, start + header.size) })\n  }\n  return files\n}\n\ninterface TarHeader {\n  path: string\n  kind: 'file' | 'directory' | 'root'\n  size: number\n  executable: boolean\n}\n\nfunction parseTarHeader(block: Uint8Array): TarHeader {\n  const decoder = new TextDecoder('utf-8', { fatal: true })\n  const text = (offset: number, length: number) =>\n    decoder.decode(block.subarray(offset, offset + length)).replace(/\\0.*$/s, '')\n  let raw: string\n  let size: number\n  let mode: number\n  try {\n    const prefix = text(257, 6) === 'ustar' ? text(345, 155) : ''\n    raw = prefix ? `${prefix}/${text(0, 100)}` : text(0, 100)\n    size = Number.parseInt(text(124, 12).trim() || '0', 8)\n    mode = Number.parseInt(text(100, 8).trim() || '0', 8)\n  } catch {\n    throw invalidZip('payload', 'tar header is not valid UTF-8')\n  }\n  if (!Number.isSafeInteger(size) || size < 0) {\n    throw invalidZip('payload', `tar entry is truncated: ${raw}`)\n  }\n  const type = String.fromCharCode(block[156] || 0x30)\n  const path = raw.replace(/^(?:\\.\\/)+/, '').replace(/\\/$/, '')\n  if (type === '5' && (path === '' || path === '.')) {\n    return { path, kind: 'root', size, executable: false }\n  }\n  if (\n    !path || path.startsWith('/') || /^[A-Za-z]:/.test(path) || path.includes('\\\\') ||\n    path.split('/').some((segment) => !segment || segment === '.' || segment === '..')\n  ) {\n    throw invalidZip('payload', `unsafe tar entry path: ${JSON.stringify(raw)}`)\n  }\n  if (type !== '5' && type !== '0') {\n    throw invalidZip('payload', `tar entry is not a regular file or directory: ${path}`)\n  }\n  return { path, kind: type === '5' ? 'directory' : 'file', size, executable: (mode & 0o111) !== 0 }\n}\n\nexport interface TarListing {\n  files: Map<string, { size: number; executable: boolean }>\n  directories: Set<string>\n  /** The contents of the files `capture` asked for. */\n  captured: Map<string, Uint8Array>\n}\n\n/** List a tar.gz too large to hold: a package's payload is gigabytes, and only its few small files need reading. */\nexport async function listTarGzStream(\n  gzip: ReadableStream<Uint8Array>,\n  limit: number,\n  capture: (path: string, size: number) => boolean,\n): Promise<TarListing> {\n  const listing: TarListing = { files: new Map(), directories: new Set(), captured: new Map() }\n  const header = new Uint8Array(BLOCK_SIZE)\n  let headerFill = 0\n  let skip = 0\n  let body: { path: string; bytes: Uint8Array; fill: number } | undefined\n  let ended = false\n  let total = 0\n  try {\n    const stream = gzip.pipeThrough(\n      new DecompressionStream('gzip') as unknown as ReadableWritablePair<Uint8Array, Uint8Array>,\n    )\n    for await (const chunk of stream) {\n      total += chunk.length\n      if (total > limit) throw invalidZip('limits', 'payload expands beyond the size limit')\n      let offset = 0\n      while (offset < chunk.length && !ended) {\n        if (skip > 0) {\n          const take = Math.min(skip, chunk.length - offset)\n          if (body && body.fill < body.bytes.length) {\n            const part = Math.min(take, body.bytes.length - body.fill)\n            body.bytes.set(chunk.subarray(offset, offset + part), body.fill)\n            body.fill += part\n            if (body.fill === body.bytes.length) {\n              listing.captured.set(body.path, body.bytes)\n              body = undefined\n            }\n          }\n          skip -= take\n          offset += take\n          continue\n        }\n        const take = Math.min(BLOCK_SIZE - headerFill, chunk.length - offset)\n        header.set(chunk.subarray(offset, offset + take), headerFill)\n        headerFill += take\n        offset += take\n        if (headerFill < BLOCK_SIZE) break\n        headerFill = 0\n        if (!header.some(Boolean)) {\n          ended = true\n          break\n        }\n        const entry = parseTarHeader(header)\n        skip = Math.ceil(entry.size / BLOCK_SIZE) * BLOCK_SIZE\n        if (entry.kind === 'directory') listing.directories.add(entry.path)\n        if (entry.kind !== 'file') continue\n        if (listing.files.has(entry.path)) {\n          throw invalidZip('payload', `duplicate tar entry: ${entry.path}`)\n        }\n        listing.files.set(entry.path, { size: entry.size, executable: entry.executable })\n        if (capture(entry.path, entry.size)) {\n          if (entry.size === 0) listing.captured.set(entry.path, new Uint8Array())\n          else body = { path: entry.path, bytes: new Uint8Array(entry.size), fill: 0 }\n        }\n      }\n    }\n  } catch (error) {\n    if (error instanceof ToolError) throw error\n    throw invalidZip('compression', 'payload is not a valid gzip stream')\n  }\n  if (skip > 0 || headerFill > 0 || body) throw invalidZip('payload', 'tar stream is truncated')\n  return listing\n}\n\nexport function fileReadableStream(path: string): ReadableStream<Uint8Array> {\n  let file: HostFile | undefined\n  return new ReadableStream<Uint8Array>({\n    async pull(controller) {\n      file ??= await getHost().open(path, { read: true })\n      const buffer = new Uint8Array(256 * 1024)\n      const read = await file.read(buffer)\n      if (read === null) {\n        await file.close()\n        controller.close()\n        return\n      }\n      controller.enqueue(buffer.subarray(0, read))\n    },\n    async cancel() {\n      await file?.close()\n    },\n  })\n}\n\nasync function gunzipBytes(bytes: Uint8Array, limit: number): Promise<Uint8Array> {\n  const stream = new ReadableStream<Uint8Array>({\n    start(controller) {\n      controller.enqueue(bytes)\n      controller.close()\n    },\n  }).pipeThrough(\n    new DecompressionStream('gzip') as unknown as ReadableWritablePair<Uint8Array, Uint8Array>,\n  )\n  const chunks: Uint8Array[] = []\n  let size = 0\n  try {\n    for await (const chunk of stream) {\n      size += chunk.length\n      if (size > limit) throw invalidZip('limits', 'payload expands beyond the size limit')\n      chunks.push(chunk)\n    }\n  } catch (error) {\n    if (error instanceof ToolError) throw error\n    throw invalidZip('compression', 'payload is not a valid gzip stream')\n  }\n  const result = new Uint8Array(size)\n  let position = 0\n  for (const chunk of chunks) {\n    result.set(chunk, position)\n    position += chunk.length\n  }\n  return result\n}\n\nexport async function writeStoredZip(\n  destination: string,\n  sources: ZipWriteSource[],\n): Promise<void> {\n  if (sources.length > MAX_PIKG_ENTRIES) {\n    throw new UsageError('TOO_MANY_ENTRIES', 'PIKG contains too many entries')\n  }\n  const names = new Set<string>()\n  const prepared = [] as Array<\n    ZipWriteSource & { nameBytes: Uint8Array; digest: FileDigest; offset: number; zip64: boolean }\n  >\n  for (const source of sources) {\n    validateZipEntryName(source.name)\n    if (names.has(source.name)) throw invalidZip('structure', `duplicate entry: ${source.name}`)\n    names.add(source.name)\n    if ((source.bytes === undefined) === (source.path === undefined)) {\n      throw new Error(`zip source ${source.name} must provide exactly one body`)\n    }\n    const digest = source.bytes\n      ? {\n        size: source.bytes.byteLength,\n        sha256: sha256Bytes(source.bytes),\n        crc32: crc32(source.bytes),\n      }\n      : await digestFile(source.path!)\n    prepared.push({\n      ...source,\n      nameBytes: new TextEncoder().encode(source.name),\n      digest,\n      offset: 0,\n      zip64: digest.size > 0xffffffff,\n    })\n  }\n\n  await getHost().mkdir(dirname(destination), { recursive: true })\n  const output = await getHost().open(destination, { createNew: true, write: true, mode: 0o600 })\n  let offset = 0\n  const centralRecords: Uint8Array[] = []\n  try {\n    for (const source of prepared) {\n      source.offset = offset\n      source.zip64 ||= offset > 0xffffffff\n      const localExtra = source.zip64 ? zip64Extra([source.digest.size, source.digest.size]) : EMPTY\n      const local = new Uint8Array(30 + source.nameBytes.length + localExtra.length)\n      const view = new DataView(local.buffer)\n      view.setUint32(0, ZIP_LOCAL_SIGNATURE, true)\n      view.setUint16(4, source.zip64 ? 45 : 20, true)\n      view.setUint16(6, 0x0800, true)\n      view.setUint16(8, 0, true)\n      view.setUint32(14, source.digest.crc32, true)\n      view.setUint32(18, source.zip64 ? 0xffffffff : source.digest.size, true)\n      view.setUint32(22, source.zip64 ? 0xffffffff : source.digest.size, true)\n      view.setUint16(26, source.nameBytes.length, true)\n      view.setUint16(28, localExtra.length, true)\n      local.set(source.nameBytes, 30)\n      local.set(localExtra, 30 + source.nameBytes.length)\n      await writeAll(output, local)\n      offset += local.length\n      if (source.bytes) {\n        await writeAll(output, source.bytes)\n      } else {\n        await copyFileToWriter(source.path!, output)\n      }\n      offset += source.digest.size\n\n      const centralExtra = source.zip64\n        ? zip64Extra([source.digest.size, source.digest.size, source.offset])\n        : EMPTY\n      const central = new Uint8Array(46 + source.nameBytes.length + centralExtra.length)\n      const centralView = new DataView(central.buffer)\n      centralView.setUint32(0, ZIP_CENTRAL_SIGNATURE, true)\n      centralView.setUint16(4, (3 << 8) | 45, true)\n      centralView.setUint16(6, source.zip64 ? 45 : 20, true)\n      centralView.setUint16(8, 0x0800, true)\n      centralView.setUint16(10, 0, true)\n      centralView.setUint32(16, source.digest.crc32, true)\n      centralView.setUint32(20, source.zip64 ? 0xffffffff : source.digest.size, true)\n      centralView.setUint32(24, source.zip64 ? 0xffffffff : source.digest.size, true)\n      centralView.setUint16(28, source.nameBytes.length, true)\n      centralView.setUint16(30, centralExtra.length, true)\n      centralView.setUint32(38, 0o100644 << 16, true)\n      centralView.setUint32(42, source.zip64 ? 0xffffffff : source.offset, true)\n      central.set(source.nameBytes, 46)\n      central.set(centralExtra, 46 + source.nameBytes.length)\n      centralRecords.push(central)\n    }\n\n    const centralOffset = offset\n    for (const record of centralRecords) {\n      await writeAll(output, record)\n      offset += record.length\n    }\n    const centralSize = offset - centralOffset\n    const needsZip64 = prepared.some((source) => source.zip64) || centralOffset > 0xffffffff ||\n      centralSize > 0xffffffff\n    if (needsZip64) {\n      const zip64Offset = offset\n      const eocd64 = new Uint8Array(56)\n      const view64 = new DataView(eocd64.buffer)\n      view64.setUint32(0, ZIP64_EOCD_SIGNATURE, true)\n      setUint64(view64, 4, 44)\n      view64.setUint16(12, (3 << 8) | 45, true)\n      view64.setUint16(14, 45, true)\n      setUint64(view64, 24, prepared.length)\n      setUint64(view64, 32, prepared.length)\n      setUint64(view64, 40, centralSize)\n      setUint64(view64, 48, centralOffset)\n      await writeAll(output, eocd64)\n      offset += eocd64.length\n      const locator = new Uint8Array(20)\n      const locatorView = new DataView(locator.buffer)\n      locatorView.setUint32(0, ZIP64_LOCATOR_SIGNATURE, true)\n      setUint64(locatorView, 8, zip64Offset)\n      locatorView.setUint32(16, 1, true)\n      await writeAll(output, locator)\n      offset += locator.length\n    }\n    const eocd = new Uint8Array(22)\n    const view = new DataView(eocd.buffer)\n    view.setUint32(0, ZIP_EOCD_SIGNATURE, true)\n    view.setUint16(8, needsZip64 ? 0xffff : prepared.length, true)\n    view.setUint16(10, needsZip64 ? 0xffff : prepared.length, true)\n    view.setUint32(12, needsZip64 ? 0xffffffff : centralSize, true)\n    view.setUint32(16, needsZip64 ? 0xffffffff : centralOffset, true)\n    await writeAll(output, eocd)\n    await output.sync()\n  } finally {\n    await output.close()\n  }\n}\n\nexport async function openZip(path: string): Promise<OpenZip> {\n  const stat = await getHost().stat(path)\n  if (!stat.isFile || stat.size < 22) throw invalidZip('container', 'PIKG is not a ZIP file')\n  const file = await getHost().open(path, { read: true })\n  try {\n    const magic = await readAt(file, 0, 4)\n    if (\n      new DataView(magic.buffer, magic.byteOffset, magic.byteLength).getUint32(0, true) !==\n        ZIP_LOCAL_SIGNATURE\n    ) {\n      throw invalidZip('container', 'PIKG magic mismatch')\n    }\n    const tailLength = Math.min(stat.size, 22 + 65535)\n    const tail = await readAt(file, stat.size - tailLength, tailLength)\n    const eocdPosition = findLastSignature(tail, ZIP_EOCD_SIGNATURE)\n    if (eocdPosition < 0 || eocdPosition + 22 > tail.length) {\n      throw invalidZip('container', 'ZIP end-of-central-directory record is missing')\n    }\n    const eocd = new DataView(\n      tail.buffer,\n      tail.byteOffset + eocdPosition,\n      tail.length - eocdPosition,\n    )\n    const commentLength = eocd.getUint16(20, true)\n    if (eocdPosition + 22 + commentLength !== tail.length) {\n      throw invalidZip('container', 'ZIP has trailing data or a truncated comment')\n    }\n    if (eocd.getUint16(4, true) !== 0 || eocd.getUint16(6, true) !== 0) {\n      throw invalidZip('container', 'multi-disk ZIP files are not supported')\n    }\n    let count = eocd.getUint16(10, true)\n    if (eocd.getUint16(8, true) !== count) {\n      throw invalidZip('container', 'ZIP entry counts disagree')\n    }\n    let centralSize = eocd.getUint32(12, true)\n    let centralOffset = eocd.getUint32(16, true)\n    if (count === 0xffff || centralSize === 0xffffffff || centralOffset === 0xffffffff) {\n      const eocdAbsolute = stat.size - tailLength + eocdPosition\n      if (eocdAbsolute < 20) throw invalidZip('container', 'ZIP64 locator is missing')\n      const locatorBytes = await readAt(file, eocdAbsolute - 20, 20)\n      const locator = new DataView(locatorBytes.buffer, locatorBytes.byteOffset, 20)\n      if (locator.getUint32(0, true) !== ZIP64_LOCATOR_SIGNATURE) {\n        throw invalidZip('container', 'ZIP64 locator signature mismatch')\n      }\n      if (locator.getUint32(4, true) !== 0 || locator.getUint32(16, true) !== 1) {\n        throw invalidZip('container', 'multi-disk ZIP64 files are not supported')\n      }\n      const recordOffset = uint64(locator, 8)\n      const recordBytes = await readAt(file, recordOffset, 56)\n      const record = new DataView(recordBytes.buffer, recordBytes.byteOffset, 56)\n      if (record.getUint32(0, true) !== ZIP64_EOCD_SIGNATURE) {\n        throw invalidZip('container', 'ZIP64 end record signature mismatch')\n      }\n      if (record.getUint32(16, true) !== 0 || record.getUint32(20, true) !== 0) {\n        throw invalidZip('container', 'multi-disk ZIP64 files are not supported')\n      }\n      if (uint64(record, 24) !== uint64(record, 32)) {\n        throw invalidZip('container', 'ZIP64 entry counts disagree')\n      }\n      count = uint64(record, 32)\n      centralSize = uint64(record, 40)\n      centralOffset = uint64(record, 48)\n    }\n    if (count > MAX_PIKG_ENTRIES) throw invalidZip('structure', 'PIKG has too many entries')\n    if (centralSize > MAX_CENTRAL_DIRECTORY) {\n      throw invalidZip('structure', 'PIKG central directory exceeds the size limit')\n    }\n    if (centralOffset + centralSize > stat.size) {\n      throw invalidZip('container', 'ZIP central directory is out of bounds')\n    }\n    const central = await readAt(file, centralOffset, centralSize)\n    const decoder = new TextDecoder('utf-8', { fatal: true })\n    const entries: ZipEntry[] = []\n    const byName = new Map<string, ZipEntry>()\n    const fileNames = new Set<string>()\n    const directories = new Set<string>()\n    let position = 0\n    for (let index = 0; index < count; index++) {\n      if (position + 46 > central.length || u32(central, position) !== ZIP_CENTRAL_SIGNATURE) {\n        throw invalidZip('structure', `central directory entry #${index} is truncated`)\n      }\n      const flags = u16(central, position + 8)\n      const compression = u16(central, position + 10)\n      const crc = u32(central, position + 16)\n      let compressedSize = u32(central, position + 20)\n      let size = u32(central, position + 24)\n      const nameLength = u16(central, position + 28)\n      const extraLength = u16(central, position + 30)\n      const commentLength = u16(central, position + 32)\n      const externalAttributes = u32(central, position + 38)\n      let localOffset = u32(central, position + 42)\n      const end = position + 46 + nameLength + extraLength + commentLength\n      if (end > central.length) throw invalidZip('structure', 'central directory is truncated')\n      let name: string\n      try {\n        name = decoder.decode(central.subarray(position + 46, position + 46 + nameLength))\n      } catch {\n        throw invalidZip('structure', `entry #${index} name is not UTF-8`)\n      }\n      validateZipEntryName(name)\n      if (byName.has(name)) throw invalidZip('structure', `duplicate entry: ${name}`)\n      if (flags & 0x0001) throw invalidZip('structure', `encrypted entry is not allowed: ${name}`)\n      if (![0, 8].includes(compression)) {\n        throw invalidZip('structure', `unsupported compression method for ${name}`)\n      }\n      const extra = central.subarray(\n        position + 46 + nameLength,\n        position + 46 + nameLength + extraLength,\n      )\n      if (size === 0xffffffff || compressedSize === 0xffffffff || localOffset === 0xffffffff) {\n        const values = parseZip64Extra(extra)\n        let valueIndex = 0\n        if (size === 0xffffffff) size = requiredZip64(values, valueIndex++, name)\n        if (compressedSize === 0xffffffff) {\n          compressedSize = requiredZip64(values, valueIndex++, name)\n        }\n        if (localOffset === 0xffffffff) localOffset = requiredZip64(values, valueIndex++, name)\n      }\n      const mode = (externalAttributes >>> 16) & 0xffff\n      if ((mode & 0xf000) === 0xa000) {\n        throw invalidZip('structure', `symlink entry is not allowed: ${name}`)\n      }\n      const isDirectory = name.endsWith('/')\n      const normalized = name.replace(/\\/$/, '')\n      if (isDirectory) directories.add(normalized)\n      else fileNames.add(name)\n      const entry: ZipEntry = {\n        name,\n        compressedSize,\n        size,\n        crc32: crc,\n        compression,\n        flags,\n        localOffset,\n        dataOffset: 0,\n        externalAttributes,\n        isDirectory,\n      }\n      entries.push(entry)\n      byName.set(name, entry)\n      position = end\n    }\n    if (position !== central.length) {\n      throw invalidZip('structure', 'central directory size mismatch')\n    }\n    for (const fileName of fileNames) {\n      const parts = fileName.split('/')\n      let prefix = ''\n      for (const part of parts.slice(0, -1)) {\n        prefix = prefix ? `${prefix}/${part}` : part\n        directories.add(prefix)\n      }\n    }\n    const conflict = [...fileNames].find((name) => directories.has(name))\n    if (conflict) throw invalidZip('structure', `path is both file and directory: ${conflict}`)\n\n    const intervals: Array<[number, number, string]> = []\n    for (const entry of entries) {\n      const local = await readAt(file, entry.localOffset, 30)\n      if (u32(local, 0) !== ZIP_LOCAL_SIGNATURE) {\n        throw invalidZip('structure', `local header is missing for ${entry.name}`)\n      }\n      const localFlags = u16(local, 6)\n      const localCompression = u16(local, 8)\n      const localNameLength = u16(local, 26)\n      const localExtraLength = u16(local, 28)\n      if (localFlags !== entry.flags || localCompression !== entry.compression) {\n        throw invalidZip('structure', `local header disagrees for ${entry.name}`)\n      }\n      const localName = await readAt(file, entry.localOffset + 30, localNameLength)\n      let decodedLocalName: string\n      try {\n        decodedLocalName = decoder.decode(localName)\n      } catch {\n        throw invalidZip('structure', `local entry name is not UTF-8: ${entry.name}`)\n      }\n      if (decodedLocalName !== entry.name) {\n        throw invalidZip('structure', `local entry name disagrees for ${entry.name}`)\n      }\n      entry.dataOffset = entry.localOffset + 30 + localNameLength + localExtraLength\n      const end = entry.dataOffset + entry.compressedSize\n      if (end > centralOffset) {\n        throw invalidZip('structure', `entry data is out of bounds: ${entry.name}`)\n      }\n      intervals.push([entry.localOffset, end, entry.name])\n    }\n    intervals.sort((left, right) => left[0] - right[0])\n    for (let index = 1; index < intervals.length; index++) {\n      if (intervals[index][0] < intervals[index - 1][1]) {\n        throw invalidZip('structure', `overlapping ZIP entries: ${intervals[index][2]}`)\n      }\n    }\n    return { path: resolve(path), size: stat.size, entries, byName }\n  } finally {\n    await file.close()\n  }\n}\n\nexport async function readZipEntry(\n  archive: OpenZip,\n  entry: ZipEntry,\n  limit: number,\n): Promise<Uint8Array> {\n  if (entry.size > limit) throw invalidZip('limits', `entry exceeds size limit: ${entry.name}`)\n  const chunks: Uint8Array[] = []\n  let size = 0\n  const verification = createEntryVerification(entry)\n  try {\n    for await (const chunk of zipEntryStream(archive.path, entry)) {\n      size += chunk.byteLength\n      if (size > limit || size > entry.size) {\n        throw invalidZip('limits', `entry expands beyond its declared size: ${entry.name}`)\n      }\n      verification.update(chunk)\n      chunks.push(chunk.slice())\n    }\n  } catch (error) {\n    if (error instanceof ToolError) throw error\n    throw invalidZip('compression', `failed to read entry ${entry.name}`)\n  }\n  verification.finish(size)\n  const result = new Uint8Array(size)\n  let offset = 0\n  for (const chunk of chunks) {\n    result.set(chunk, offset)\n    offset += chunk.length\n  }\n  return result\n}\n\nexport async function verifyZipEntry(\n  archive: OpenZip,\n  entry: ZipEntry,\n  expectedSha256?: string,\n): Promise<FileDigest> {\n  const verification = createEntryVerification(entry)\n  try {\n    for await (const chunk of zipEntryStream(archive.path, entry)) verification.update(chunk)\n  } catch (error) {\n    if (error instanceof ToolError) throw error\n    throw invalidZip('compression', `failed to read entry ${entry.name}`)\n  }\n  const result = verification.finish()\n  if (expectedSha256 && result.sha256 !== expectedSha256.toLowerCase()) {\n    throw invalidZip('content', `content digest mismatch: ${entry.name}`, entry.name)\n  }\n  return result\n}\n\nfunction createEntryVerification(entry: ZipEntry): {\n  update(chunk: Uint8Array): void\n  finish(actualSize?: number): FileDigest\n} {\n  const sha = getHost().createHash('sha256')\n  let crc = 0xffffffff\n  let size = 0\n  return {\n    update(chunk) {\n      size += chunk.length\n      if (size > entry.size) {\n        throw invalidZip('limits', `entry is larger than declared: ${entry.name}`)\n      }\n      sha.update(chunk)\n      crc = updateCrc32(crc, chunk)\n    },\n    finish(actualSize = size) {\n      if (actualSize !== entry.size || size !== entry.size) {\n        throw invalidZip('content', `entry size mismatch: ${entry.name}`, entry.name)\n      }\n      const actualCrc = (crc ^ 0xffffffff) >>> 0\n      if (actualCrc !== entry.crc32) {\n        throw invalidZip('content', `entry CRC mismatch: ${entry.name}`, entry.name)\n      }\n      return { size, sha256: sha.digestHex(), crc32: actualCrc }\n    },\n  }\n}\n\nexport function zipEntryStream(path: string, entry: ZipEntry): ReadableStream<Uint8Array> {\n  let file: HostFile | undefined\n  let remaining = entry.compressedSize\n  const compressed = new ReadableStream<Uint8Array>({\n    async start() {\n      file = await getHost().open(path, { read: true })\n      await file.seek(entry.dataOffset)\n    },\n    async pull(controller) {\n      if (!file || remaining === 0) {\n        void file?.close()\n        controller.close()\n        return\n      }\n      const buffer = new Uint8Array(Math.min(256 * 1024, remaining))\n      const read = await file.read(buffer)\n      if (read === null) {\n        void file.close()\n        controller.error(invalidZip('container', `truncated entry: ${entry.name}`))\n        return\n      }\n      remaining -= read\n      controller.enqueue(buffer.subarray(0, read))\n    },\n    cancel() {\n      void file?.close()\n    },\n  })\n  if (entry.compression === 0) return compressed\n  return compressed.pipeThrough(\n    new DecompressionStream('deflate-raw') as unknown as ReadableWritablePair<\n      Uint8Array,\n      Uint8Array\n    >,\n  )\n}\n\nasync function collectTarSources(root: string): Promise<TarSource[]> {\n  const output: TarSource[] = []\n  const activeDirectories = new Set<string>()\n  async function walk(physicalDirectory: string, archivePrefix: string): Promise<void> {\n    const realDirectory = await getHost().realPath(physicalDirectory)\n    assertWithin(root, realDirectory, archivePrefix || '.')\n    if (activeDirectories.has(realDirectory)) {\n      throw new UsageError('INVALID_SOURCE', `symlink cycle in source: ${archivePrefix}`)\n    }\n    activeDirectories.add(realDirectory)\n    try {\n      const children = [] as HostDirEntry[]\n      for (const child of await getHost().readDir(realDirectory)) children.push(child)\n      children.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)\n      for (const child of children) {\n        if (child.name.includes('\\0') || child.name.includes('/') || child.name.includes('\\\\')) {\n          throw new UsageError('INVALID_SOURCE', 'source contains an unsafe file name')\n        }\n        const archivePath = archivePrefix ? `${archivePrefix}/${child.name}` : child.name\n        const unresolved = resolve(realDirectory, child.name)\n        const info = await getHost().lstat(unresolved)\n        const physical = info.isSymlink ? await getHost().realPath(unresolved) : unresolved\n        assertWithin(root, physical, archivePath)\n        const target = info.isSymlink ? await getHost().stat(physical) : info\n        if (target.isDirectory) {\n          output.push({\n            archivePath: `${archivePath}/`,\n            physicalPath: physical,\n            kind: 'directory',\n            size: 0,\n            executable: true,\n            identity: fileIdentity(info, physical, target),\n          })\n          await walk(physical, archivePath)\n        } else if (target.isFile) {\n          output.push({\n            archivePath,\n            physicalPath: physical,\n            kind: 'file',\n            size: target.size,\n            executable: ((target.mode ?? 0) & 0o111) !== 0,\n            identity: fileIdentity(info, physical, target),\n            contentDigest: (await digestFile(physical)).sha256,\n          })\n        } else {\n          throw new UsageError('INVALID_SOURCE', `unsupported special file: ${archivePath}`)\n        }\n      }\n    } finally {\n      activeDirectories.delete(realDirectory)\n    }\n  }\n  await walk(root, '')\n  return output\n}\n\nfunction fileIdentity(link: HostFileInfo, realPath: string, target: HostFileInfo): string {\n  return JSON.stringify({\n    realPath,\n    linkMtime: link.mtime?.getTime() ?? null,\n    mtime: target.mtime?.getTime() ?? null,\n    size: target.size,\n    dev: target.dev,\n    ino: target.ino,\n    mode: target.mode,\n  })\n}\n\nfunction sourceIdentity(source: TarSource): unknown {\n  return [\n    source.archivePath,\n    source.kind,\n    source.size,\n    source.executable,\n    source.identity,\n    source.contentDigest ?? null,\n  ]\n}\n\nfunction assertWithin(root: string, candidate: string, label: string): void {\n  const path = relative(root, candidate)\n  if (\n    path === '..' || path.startsWith(`..${getHost().path.sep}`) ||\n    resolve(candidate) === resolve(root) && label !== '.'\n  ) {\n    throw new UsageError('INVALID_SOURCE', `symlink escapes source root: ${label}`)\n  }\n}\n\nfunction tarHeader(source: TarSource): Uint8Array {\n  const header = new Uint8Array(BLOCK_SIZE)\n  const { name, prefix } = splitUstarPath(source.archivePath)\n  writeString(header, 0, 100, name)\n  writeOctal(\n    header,\n    100,\n    8,\n    source.kind === 'directory' ? 0o755 : source.executable ? 0o755 : 0o644,\n  )\n  writeOctal(header, 108, 8, 0)\n  writeOctal(header, 116, 8, 0)\n  writeOctal(header, 124, 12, source.size)\n  writeOctal(header, 136, 12, 0)\n  header.fill(0x20, 148, 156)\n  header[156] = source.kind === 'directory' ? 0x35 : 0x30\n  writeString(header, 257, 6, 'ustar\\0')\n  writeString(header, 263, 2, '00')\n  writeString(header, 345, 155, prefix)\n  let checksum = 0\n  for (const byte of header) checksum += byte\n  writeChecksum(header, checksum)\n  return header\n}\n\nfunction splitUstarPath(path: string): { name: string; prefix: string } {\n  const encoder = new TextEncoder()\n  if (encoder.encode(path).length <= 100) return { name: path, prefix: '' }\n  const directory = path.endsWith('/')\n  const core = directory ? path.slice(0, -1) : path\n  const parts = core.split('/')\n  for (let index = parts.length - 1; index > 0; index--) {\n    const prefix = parts.slice(0, index).join('/')\n    const name = `${parts.slice(index).join('/')}${directory ? '/' : ''}`\n    if (encoder.encode(prefix).length <= 155 && encoder.encode(name).length <= 100) {\n      return { name, prefix }\n    }\n  }\n  throw new UsageError('INVALID_SOURCE', `source path is too long for a portable tar: ${path}`)\n}\n\nfunction writeString(target: Uint8Array, offset: number, length: number, value: string): void {\n  const bytes = new TextEncoder().encode(value)\n  if (bytes.length > length) throw new UsageError('INVALID_SOURCE', 'tar field is too long')\n  target.set(bytes, offset)\n}\n\nfunction writeOctal(target: Uint8Array, offset: number, length: number, value: number): void {\n  const text = value.toString(8).padStart(length - 1, '0')\n  if (text.length >= length) throw new UsageError('FILE_TOO_LARGE', 'tar field overflows')\n  writeString(target, offset, length, `${text}\\0`)\n}\n\nfunction writeChecksum(target: Uint8Array, value: number): void {\n  const text = value.toString(8).padStart(6, '0')\n  writeString(target, 148, 8, `${text}\\0 `)\n}\n\nfunction validateZipEntryName(name: string): void {\n  if (!name || name.includes('\\0') || name.includes('\\\\') || name.startsWith('/')) {\n    throw invalidZip('structure', `unsafe entry name: ${JSON.stringify(name)}`)\n  }\n  if (/^[A-Za-z]:/.test(name)) throw invalidZip('structure', `absolute entry name: ${name}`)\n  const directory = name.endsWith('/')\n  const segments = name.split('/')\n  for (let index = 0; index < segments.length; index++) {\n    const segment = segments[index]\n    if (\n      segment === '.' || segment === '..' ||\n      (!segment && !(directory && index === segments.length - 1))\n    ) {\n      throw invalidZip('structure', `unsafe entry name: ${name}`)\n    }\n  }\n}\n\nfunction invalidZip(stage: string, message: string, entry?: string): ToolError {\n  return new ToolError('INVALID_PACKAGE', message, 6, false, {\n    stage,\n    ...(entry ? { entry } : {}),\n  })\n}\n\nfunction crc32(bytes: Uint8Array): number {\n  return (updateCrc32(0xffffffff, bytes) ^ 0xffffffff) >>> 0\n}\n\nfunction updateCrc32(crc: number, bytes: Uint8Array): number {\n  let value = crc\n  for (const byte of bytes) value = CRC_TABLE[(value ^ byte) & 0xff] ^ (value >>> 8)\n  return value >>> 0\n}\n\nasync function writeAll(file: HostFile, bytes: Uint8Array): Promise<void> {\n  let offset = 0\n  while (offset < bytes.length) offset += await file.write(bytes.subarray(offset))\n}\n\nasync function copyFileToWriter(path: string, output: HostFile): Promise<void> {\n  const input = await getHost().open(path, { read: true })\n  try {\n    const buffer = new Uint8Array(256 * 1024)\n    while (true) {\n      const read = await input.read(buffer)\n      if (read === null) break\n      await writeAll(output, buffer.subarray(0, read))\n    }\n  } finally {\n    await input.close()\n  }\n}\n\nasync function readAt(file: HostFile, offset: number, length: number): Promise<Uint8Array> {\n  if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0) {\n    throw invalidZip('container', 'ZIP offset is invalid')\n  }\n  await file.seek(offset)\n  const output = new Uint8Array(length)\n  let position = 0\n  while (position < length) {\n    const read = await file.read(output.subarray(position))\n    if (read === null) throw invalidZip('container', 'ZIP file is truncated')\n    position += read\n  }\n  return output\n}\n\nfunction findLastSignature(bytes: Uint8Array, signature: number): number {\n  for (let index = bytes.length - 4; index >= 0; index--) {\n    if (u32(bytes, index) === signature) return index\n  }\n  return -1\n}\n\nfunction parseZip64Extra(extra: Uint8Array): number[] {\n  let position = 0\n  while (position + 4 <= extra.length) {\n    const id = u16(extra, position)\n    const length = u16(extra, position + 2)\n    const end = position + 4 + length\n    if (end > extra.length) throw invalidZip('structure', 'ZIP extra field is truncated')\n    if (id === 0x0001) {\n      if (length % 8 !== 0) throw invalidZip('structure', 'ZIP64 extra field is malformed')\n      const view = new DataView(extra.buffer, extra.byteOffset + position + 4, length)\n      const values: number[] = []\n      for (let offset = 0; offset < length; offset += 8) values.push(uint64(view, offset))\n      return values\n    }\n    position = end\n  }\n  throw invalidZip('structure', 'ZIP64 extra field is missing')\n}\n\nfunction requiredZip64(values: number[], index: number, name: string): number {\n  const value = values[index]\n  if (value === undefined) throw invalidZip('structure', `ZIP64 values are missing for ${name}`)\n  return value\n}\n\nfunction zip64Extra(values: number[]): Uint8Array {\n  const output = new Uint8Array(4 + values.length * 8)\n  const view = new DataView(output.buffer)\n  view.setUint16(0, 0x0001, true)\n  view.setUint16(2, values.length * 8, true)\n  values.forEach((value, index) => setUint64(view, 4 + index * 8, value))\n  return output\n}\n\nfunction setUint64(view: DataView, offset: number, value: number): void {\n  if (!Number.isSafeInteger(value) || value < 0) throw new Error('uint64 value is unsafe')\n  view.setBigUint64(offset, BigInt(value), true)\n}\n\nfunction uint64(view: DataView, offset: number): number {\n  const value = view.getBigUint64(offset, true)\n  if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n    throw invalidZip('limits', 'ZIP64 value is too large')\n  }\n  return Number(value)\n}\n\nfunction u16(bytes: Uint8Array, offset: number): number {\n  return new DataView(bytes.buffer, bytes.byteOffset + offset, 2).getUint16(0, true)\n}\n\nfunction u32(bytes: Uint8Array, offset: number): number {\n  return new DataView(bytes.buffer, bytes.byteOffset + offset, 4).getUint32(0, true)\n}\n\nasync function removeIfExists(path: string): Promise<void> {\n  try {\n    await getHost().remove(path)\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n  }\n}\n\nconst EMPTY = new Uint8Array()\n","import { ndn, verifyBundle } from 'buckyos/node'\nimport { ToolError, UsageError } from '../core/errors.ts'\nimport { getHost } from '../runtime/host.ts'\nimport {\n  digestFile,\n  type FileDigest,\n  fileReadableStream,\n  listTarGzStream,\n  openZip,\n  readTarGz,\n  readZipEntry,\n  sha256Bytes,\n  verifyZipEntry,\n  writeStoredZip,\n  zipEntryStream,\n} from './pikg_archive.ts'\n\nconst basename = (path: string) => getHost().path.basename(path)\nconst join = (...parts: string[]) => getHost().path.join(...parts)\nconst resolve = (...parts: string[]) => getHost().path.resolve(...parts)\n\nexport const PACKAGE_META_SCHEMA = 'buckyos.pikg.package-meta.v1'\nexport const DIST_MANIFEST_NAME = '.buckyos-pikg-dist.json'\nexport const APPDOC_ENTRY = 'APPDOC.json'\nexport const APPDOC_JWT_ENTRY = 'APPDOC.jwt'\nexport const PACKAGE_META_ENTRY = 'PACKAGE_META.json'\nexport const MAX_APPDOC_BYTES = 1024 * 1024\nexport const MAX_METADATA_ENTRY_BYTES = 8 * 1024 * 1024\nexport const MAX_METADATA_TOTAL_BYTES = 64 * 1024 * 1024\n\nconst SAFE_SUBPACKAGE = /^[A-Za-z0-9._-]+$/\nconst SAFE_BNS_LABEL = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/\nconst SHA256_DIGEST = /^sha256:([0-9a-fA-F]{64})$/\nconst OBJECT_ID = /^(appdoc|pkg):[0-9a-f]{64}$/\n\nexport interface ContentIndexEntry {\n  sub_pkg_name: string\n  path: string\n  format: 'tar.gz'\n  size: number\n  digest: string\n}\n\nexport interface PackageMetaFile {\n  '@schema': typeof PACKAGE_META_SCHEMA\n  app_doc_id: string\n  package_objects: Record<string, Record<string, unknown>>\n  content_index: Record<string, ContentIndexEntry>\n}\n\nexport interface ValidatedSubpackage {\n  key: string\n  selector: Record<string, string> | null\n  required: boolean\n  pkg_id: string\n  pkg_objid: string\n  payload_path: string\n  payload_size: number\n  payload_digest: string\n  docker_image_name?: string\n  docker_image_digest?: string\n}\n\nexport interface ValidatedPikg {\n  appDoc: Record<string, unknown>\n  appDocObjectId: string\n  packageMeta: PackageMetaFile\n  subpackages: ValidatedSubpackage[]\n  hasJsonAppDoc: boolean\n  hasSignedAppDoc: boolean\n  canonicalMatch: boolean\n}\n\nexport interface PikgInspectionResult {\n  schema_version: 1\n  /** An `aiws` package: its bundle checked like the AI Workspace library does. */\n  aiws?: Record<string, unknown>\n  /** An `ext_tools` package: what its `ext-manifest.json` says, checked against every payload. */\n  ext_tools?: Record<string, unknown>\n  protocol: string\n  pikg_path: string\n  size: number\n  pikg_digest: string\n  valid: true\n  app: {\n    did: string\n    app_id: string\n    name?: string\n    app_type: string\n    version: string\n    owner: string\n    app_doc_object_id: string\n  }\n  app_doc_form: 'unsigned' | 'signed' | 'both'\n  canonical_match: boolean\n  subpackages: Array<Record<string, unknown>>\n  offline_content_validation: 'passed'\n  signature_validation: 'not-present' | 'not-resolvable-offline'\n  publication_validation: 'not-checked'\n}\n\nexport function validateSubpackageName(name: string): void {\n  if (!SAFE_SUBPACKAGE.test(name) || name === '.' || name === '..') {\n    throw new UsageError('INVALID_SUBPACKAGE_NAME', `invalid subpackage name: ${name}`)\n  }\n}\n\nexport function normalizeArch(value: string): string {\n  switch (value.trim().toLowerCase()) {\n    case 'amd64':\n    case 'x86_64':\n    case 'x64':\n      return 'x86_64'\n    case 'arm64':\n    case 'aarch64':\n      return 'aarch64'\n    default:\n      return value.trim().toLowerCase()\n  }\n}\n\nexport function normalizeOs(value: string): string {\n  switch (value.trim().toLowerCase()) {\n    case 'darwin':\n    case 'apple':\n    case 'macos':\n    case 'osx':\n      return 'macos'\n    case 'win':\n    case 'win32':\n    case 'windows':\n      return 'windows'\n    default:\n      return value.trim().toLowerCase()\n  }\n}\n\nexport function derivedSelector(key: string): Record<string, string> | undefined {\n  const selectors: Record<string, Record<string, string>> = {\n    amd64_docker_image: { os: 'linux', arch: 'x86_64' },\n    aarch64_docker_image: { os: 'linux', arch: 'aarch64' },\n    amd64_linux_app: { os: 'linux', arch: 'x86_64' },\n    aarch64_linux_app: { os: 'linux', arch: 'aarch64' },\n    amd64_win_app: { os: 'windows', arch: 'x86_64' },\n    aarch64_win_app: { os: 'windows', arch: 'aarch64' },\n    amd64_apple_app: { os: 'macos', arch: 'x86_64' },\n    aarch64_apple_app: { os: 'macos', arch: 'aarch64' },\n    web: {},\n    agent: {},\n    agent_skills: {},\n    aiws: {},\n    script: {},\n  }\n  return selectors[key] ?? extToolsPlatformOfKey(key)?.selector\n}\n\nexport function canonicalSelector(\n  value: unknown,\n  label: string,\n): Record<string, string> | undefined {\n  if (value === undefined) return undefined\n  const selector = expectObject(value, label)\n  rejectUnknown(selector, ['os', 'arch', 'min_kernel_version'], label)\n  const output: Record<string, string> = {}\n  for (const key of ['os', 'arch', 'min_kernel_version']) {\n    if (selector[key] !== undefined) {\n      output[key] = expectNonEmptyString(selector[key], `${label}.${key}`)\n    }\n  }\n  if (output.os) output.os = normalizeOs(output.os)\n  if (output.arch) output.arch = normalizeArch(output.arch)\n  return output\n}\n\nexport function assertSelectorCompatible(\n  key: string,\n  selector: Record<string, string> | undefined,\n  label: string,\n): void {\n  const derived = derivedSelector(key)\n  if (!derived || !selector) return\n  for (const field of ['os', 'arch']) {\n    if (derived[field] !== undefined && selector[field] !== derived[field]) {\n      throw new UsageError(\n        'SELECTOR_CONFLICT',\n        `${label}.${field} conflicts with the selector derived from ${key}`,\n      )\n    }\n  }\n}\n\nexport function deriveAppNamespace(\n  appDid: string,\n): string {\n  return appIdFromDid(appDid)\n}\n\nexport function appIdFromDid(appDid: string): string {\n  const app = parseDid(appDid, 'did')\n  if (\n    app.id.includes('#') || app.id.includes('/') || app.id.includes('%') || app.id.includes(':')\n  ) {\n    throw new UsageError(\n      'INVALID_APP_ID',\n      'App DID must use hostname form without path, fragment, port, or encoding',\n    )\n  }\n  const labels = app.id.split('.')\n  if (labels.some((label) => !SAFE_BNS_LABEL.test(label))) {\n    throw new UsageError('INVALID_APP_ID', 'App DID must contain canonical lowercase DNS labels')\n  }\n  if (app.method === 'web') {\n    if (labels.length >= 3 && labels.at(-1) === 'did') {\n      throw new UsageError(\n        'INVALID_APP_ID',\n        'did:web hostname conflicts with the reserved non-Web .did form',\n      )\n    }\n    return app.id\n  }\n  return `${app.id}.${app.method}.did`\n}\n\nexport function createPackageMeta(\n  packageName: string,\n  version: string,\n  author: string,\n  owner: string,\n  payload: FileDigest,\n  timestamp: number,\n): { value: Record<string, unknown>; objectId: string } {\n  const content = ndn.ChunkId.fromMix256Result(\n    payload.size,\n    ndn.hexToBytes(payload.sha256),\n  ).toString()\n  const value: Record<string, unknown> = {\n    name: packageName,\n    author,\n    owner,\n    create_time: timestamp,\n    last_update_time: timestamp,\n    size: payload.size,\n    content,\n    version,\n  }\n  const objectId = ndn.buildNamedObjectByJson(ndn.OBJ_TYPE_PKG, value)[0].toString()\n  return { value, objectId }\n}\n\nexport function validatePermissions(value: unknown, label: string): unknown[] {\n  if (!Array.isArray(value)) throw invalid('schema', `${label} must be an array`)\n  return value.map((raw, index) => {\n    const item = expectObject(raw, `${label}[${index}]`)\n    assertKnownFields(item, ['scope_path', 'required', 'actions', 'exp'], `${label}[${index}]`)\n    expectNonEmptyString(item.scope_path, `${label}[${index}].scope_path`)\n    if (typeof item.required !== 'boolean') {\n      throw invalid('schema', `${label}[${index}].required must be boolean`)\n    }\n    if (\n      item.actions !== undefined &&\n      (!Array.isArray(item.actions) || item.actions.some((action) => typeof action !== 'string'))\n    ) {\n      throw invalid('schema', `${label}[${index}].actions must be a string array`)\n    }\n    if (\n      item.exp !== null && item.exp !== undefined &&\n      (typeof item.exp !== 'number' || !Number.isInteger(item.exp) || item.exp < 0 ||\n        item.exp > 0xffffffff)\n    ) {\n      throw invalid('schema', `${label}[${index}].exp must be null or a uint32`)\n    }\n    return raw\n  })\n}\n\nconst BUCKET_POLICIES = ['documents', 'app_data', 'collected', 'ambient', 'temp', 'cache']\n\n/** `buckets` / `storage_quota_mib` (BuckyOS 应用对象桶设计 §4.3, §4.5.3, D17). */\nfunction validateBuckets(config: Record<string, unknown>, label: string): void {\n  if (config.storage_quota_mib !== undefined) {\n    expectUint(config.storage_quota_mib, `${label}.storage_quota_mib`, Number.MAX_SAFE_INTEGER)\n  }\n  let needsAppPool = false\n  for (const [name, raw] of Object.entries(expectObject(config.buckets ?? {}, `${label}.buckets`))) {\n    const at = `${label}.buckets.${name}`\n    if (!/^[A-Za-z0-9._-]{1,128}$/.test(name) || name === '.' || name === '..') {\n      throw invalid('schema', `${at} is not a valid bucket name`)\n    }\n    const bucket = expectObject(raw, at)\n    assertKnownFields(\n      bucket,\n      ['kind', 'data_policy', 'scope', 'versioning', 'quota_mib', 'max_objects', 'default_ttl_days', 'lifecycle'],\n      at,\n    )\n    if (!['data', 'object'].includes(String(bucket.kind))) throw invalid('schema', `${at}.kind is data or object`)\n    const policy = String(bucket.data_policy)\n    if (!BUCKET_POLICIES.includes(policy)) throw invalid('schema', `${at}.data_policy is invalid`)\n    if (bucket.scope !== undefined && !['user', 'zone'].includes(String(bucket.scope))) {\n      throw invalid('schema', `${at}.scope is user or zone`)\n    }\n    // The AppDoc carries the declaration without defaults, as BuckyOS serializes it.\n    if (bucket.scope === 'user') delete bucket.scope\n    optionalBoolean(bucket.versioning, `${at}.versioning`)\n    const userOwned = policy === 'documents' || policy === 'collected'\n    if (bucket.quota_mib !== undefined) {\n      expectUint(bucket.quota_mib, `${at}.quota_mib`, Number.MAX_SAFE_INTEGER)\n      if (userOwned) throw invalid('schema', `${at}: a ${policy} bucket uses the user's quota`)\n    }\n    if (bucket.max_objects !== undefined) expectUint(bucket.max_objects, `${at}.max_objects`, Number.MAX_SAFE_INTEGER)\n    if (bucket.versioning === true && !['documents', 'app_data', 'collected'].includes(policy)) {\n      throw invalid('schema', `${at}: a ${policy} bucket cannot be versioned`)\n    }\n    if (bucket.default_ttl_days !== undefined) {\n      expectUint(bucket.default_ttl_days, `${at}.default_ttl_days`, 0xffffffff)\n      if (!['ambient', 'temp', 'cache'].includes(policy)) {\n        throw invalid('schema', `${at}: a ${policy} bucket cannot declare default_ttl_days`)\n      }\n    }\n    if (policy === 'temp') {\n      const days = bucket.default_ttl_days\n      if (typeof days !== 'number' || days < 1 || days > 30) {\n        throw invalid('schema', `${at}: a temp bucket declares default_ttl_days 1..30`)\n      }\n    }\n    if (bucket.lifecycle !== undefined) {\n      const lifecycle = bucket.lifecycle\n      if (!Array.isArray(lifecycle)) throw invalid('schema', `${at}.lifecycle must be an array`)\n      if (lifecycle.length === 0) delete bucket.lifecycle\n      for (const [index, rule] of lifecycle.entries()) {\n        const kind = String(expectObject(rule, `${at}.lifecycle[${index}]`).rule)\n        if (!['expire', 'noncurrent_expire', 'expired_delete_marker'].includes(kind)) {\n          throw invalid('schema', `${at}.lifecycle[${index}].rule is invalid`)\n        }\n        if (policy === 'temp' || (userOwned && kind !== 'noncurrent_expire')) {\n          throw invalid('schema', `${at}: a ${policy} bucket does not accept the ${kind} rule`)\n        }\n      }\n    }\n    needsAppPool ||= policy === 'app_data' || policy === 'temp'\n  }\n  if (needsAppPool && config.storage_quota_mib === undefined) {\n    throw invalid('schema', `${label}.storage_quota_mib is required when app_data or temp buckets are declared`)\n  }\n}\n\nexport function validateServiceConfigTips(\n  value: unknown,\n  label: string,\n): Record<string, unknown> {\n  const config = expectObject(value, label)\n  for (\n    const field of [\n      'service_endpoints',\n      'data_mount_points',\n      'local_cache_mount_points',\n      'external_mount_points',\n      'rdb_instances',\n      'bash_envs',\n      'runtime_caps',\n    ]\n  ) {\n    if (config[field] !== undefined) expectObject(config[field], `${label}.${field}`)\n  }\n  for (\n    const [name, raw] of Object.entries(\n      expectObject(config.service_endpoints ?? {}, `${label}.service_endpoints`),\n    )\n  ) {\n    const endpoint = expectObject(raw, `${label}.service_endpoints.${name}`)\n    assertKnownFields(\n      endpoint,\n      ['protocol', 'inner_port', 'required', 'description', 'expose'],\n      `${label}.service_endpoints.${name}`,\n    )\n    if (!['http', 'https', 'tcp', 'udp'].includes(String(endpoint.protocol))) {\n      throw invalid('schema', `${label}.service_endpoints.${name}.protocol is invalid`)\n    }\n    expectUint(endpoint.inner_port, `${label}.service_endpoints.${name}.inner_port`, 0xffff)\n    optionalBoolean(endpoint.required, `${label}.service_endpoints.${name}.required`)\n    validateStringMap(\n      endpoint.description ?? {},\n      `${label}.service_endpoints.${name}.description`,\n    )\n    if (endpoint.expose !== undefined && endpoint.expose !== null) {\n      const expose = expectObject(endpoint.expose, `${label}.service_endpoints.${name}.expose`)\n      assertKnownFields(\n        expose,\n        ['route', 'scope', 'allow_guest'],\n        `${label}.service_endpoints.${name}.expose`,\n      )\n      const route = expectObject(expose.route, `${label}.service_endpoints.${name}.expose.route`)\n      if (route.type === 'web') {\n        assertKnownFields(route, ['type'], `${label}.service_endpoints.${name}.expose.route`)\n      } else if (route.type === 'port') {\n        assertKnownFields(\n          route,\n          ['type', 'preferred_port'],\n          `${label}.service_endpoints.${name}.expose.route`,\n        )\n        if (route.preferred_port !== undefined) {\n          expectUint(\n            route.preferred_port,\n            `${label}.service_endpoints.${name}.expose.route.preferred_port`,\n            0xffff,\n          )\n        }\n      } else {\n        throw invalid('schema', `${label}.service_endpoints.${name}.expose.route.type is invalid`)\n      }\n      optionalString(expose.scope, `${label}.service_endpoints.${name}.expose.scope`)\n      optionalBoolean(\n        expose.allow_guest,\n        `${label}.service_endpoints.${name}.expose.allow_guest`,\n      )\n    }\n  }\n  for (\n    const field of [\n      'data_mount_points',\n      'local_cache_mount_points',\n      'external_mount_points',\n    ]\n  ) {\n    for (\n      const [name, raw] of Object.entries(expectObject(config[field] ?? {}, `${label}.${field}`))\n    ) {\n      if (raw === null) continue\n      const mount = expectObject(raw, `${label}.${field}.${name}`)\n      assertKnownFields(\n        mount,\n        ['mount_point_name', 'access', 'reason'],\n        `${label}.${field}.${name}`,\n      )\n      expectNonEmptyString(mount.mount_point_name, `${label}.${field}.${name}.mount_point_name`)\n      expectNonEmptyString(mount.access, `${label}.${field}.${name}.access`)\n      validateStringMap(mount.reason, `${label}.${field}.${name}.reason`)\n    }\n  }\n  for (\n    const [name, raw] of Object.entries(\n      expectObject(config.rdb_instances ?? {}, `${label}.rdb_instances`),\n    )\n  ) {\n    const database = expectObject(raw, `${label}.rdb_instances.${name}`)\n    assertKnownFields(\n      database,\n      ['backend', 'version', 'schema', 'connection'],\n      `${label}.rdb_instances.${name}`,\n    )\n    if (!['sqlite', 'postgres'].includes(String(database.backend))) {\n      throw invalid('schema', `${label}.rdb_instances.${name}.backend is invalid`)\n    }\n    if (database.version !== undefined) {\n      expectUint(\n        database.version,\n        `${label}.rdb_instances.${name}.version`,\n        Number.MAX_SAFE_INTEGER,\n      )\n    }\n    const schemas = validateStringMap(\n      database.schema ?? {},\n      `${label}.rdb_instances.${name}.schema`,\n    )\n    for (const backend of Object.keys(schemas)) {\n      if (!['sqlite', 'postgres'].includes(backend)) {\n        throw invalid('schema', `${label}.rdb_instances.${name}.schema.${backend} is invalid`)\n      }\n    }\n    optionalString(database.connection, `${label}.rdb_instances.${name}.connection`)\n  }\n  validateBuckets(config, label)\n  if (config.instance_volume !== undefined) {\n    const volume = expectObject(config.instance_volume, `${label}.instance_volume`)\n    assertKnownFields(\n      volume,\n      ['mode', 'quota_mib', 'ephemeral_contents'],\n      `${label}.instance_volume`,\n    )\n    if (\n      volume.mode !== undefined &&\n      !['required', 'optional', 'disabled'].includes(String(volume.mode))\n    ) {\n      throw invalid('schema', `${label}.instance_volume.mode is invalid`)\n    }\n    if (volume.quota_mib !== undefined) {\n      expectUint(volume.quota_mib, `${label}.instance_volume.quota_mib`, Number.MAX_SAFE_INTEGER)\n    }\n    if (\n      volume.ephemeral_contents !== undefined &&\n      (!Array.isArray(volume.ephemeral_contents) ||\n        volume.ephemeral_contents.some((item) => typeof item !== 'string'))\n    ) {\n      throw invalid('schema', `${label}.instance_volume.ephemeral_contents must be a string array`)\n    }\n  }\n  for (\n    const [name, raw] of Object.entries(expectObject(config.bash_envs ?? {}, `${label}.bash_envs`))\n  ) {\n    const environment = expectObject(raw, `${label}.bash_envs.${name}`)\n    assertKnownFields(environment, ['required', 'description'], `${label}.bash_envs.${name}`)\n    if (typeof environment.required !== 'boolean') {\n      throw invalid('schema', `${label}.bash_envs.${name}.required must be boolean`)\n    }\n    validateStringMap(environment.description ?? {}, `${label}.bash_envs.${name}.description`)\n  }\n  validateStringMap(config.runtime_caps ?? {}, `${label}.runtime_caps`)\n  optionalString(config.container_param, `${label}.container_param`)\n  optionalString(config.start_param, `${label}.start_param`)\n  return config\n}\n\nexport function appDocObjectId(value: Record<string, unknown>): string {\n  return ndn.buildNamedObjectByJson('appdoc', value)[0].toString()\n}\n\n/** The sub-package of an `aiws` package: the AIWS bundle (aiws-manifest.json plus controls/<dir>/<file> and, from\n * manifest_version 3, Workspace templates under templates/<id>/). */\nexport const AIWS_SUB_PACKAGE = 'aiws'\nconst MAX_AIWS_PAYLOAD_BYTES = 256 * 1024 * 1024\n\n/** Check the bundle inside an `aiws` payload the way the AI Workspace library does (digests, component.json, the\n * templates' shape, snapshot, digest and required controls, no file outside a control, a template or the manifest). */\nexport async function verifyAiwsPayload(tarGz: Uint8Array): Promise<Record<string, unknown>> {\n  const files = new Map<string, Uint8Array>()\n  for (const entry of await readTarGz(tarGz, MAX_AIWS_PAYLOAD_BYTES)) files.set(entry.path, entry.bytes)\n  let checked\n  try {\n    checked = await verifyBundle(files)\n  } catch (error) {\n    throw invalid('aiws', `aiws bundle: ${error instanceof Error ? error.message : String(error)}`)\n  }\n  const errors = checked.diagnostics.filter((d: { severity: string }) => d.severity === 'error')\n  if (errors.length > 0) {\n    throw invalid('aiws', `aiws bundle: ${errors.map((d: { file: string; message: string }) => `${d.file}: ${d.message}`).join('; ')}`)\n  }\n  return {\n    manifest_version: checked.manifest.manifest_version,\n    controls: checked.manifest.controls.map((c: Record<string, unknown>) => ({ ident: c.ident, kind: c.kind, version: c.version, digest: c.digest })),\n    templates: checked.manifest.workspace_templates.map((t: Record<string, unknown>) => ({ id: t.id, title: t.title, digest: t.digest, requires: t.requires })),\n  }\n}\n\n/** Extension tool packages (`app_type = ext_tools`): tools every Agent of a machine shares, one payload per platform. */\nexport const EXT_TOOLS_APP_TYPE = 'ext_tools'\nexport const EXT_TOOLS_MANIFEST_FILE = 'ext-manifest.json'\nexport const EXT_TOOLS_MANIFEST_SCHEMA = 'buckyos.ext_tools/1'\nconst MAX_EXT_TOOLS_PAYLOAD_BYTES = 64 * 1024 * 1024 * 1024\n/** The standard layer's commands (Rust: `EXT_TOOLS_RESERVED_COMMANDS`, `baseline::STANDARD_TOOLS`): `tools/bin` comes first\n * on the PATH, so a package providing one would shadow an Agent's identity and control commands. */\nexport const EXT_TOOLS_RESERVED_COMMANDS = [\n  'agent-session', 'agent_tool', 'ai_provider', 'ai_provider_test', 'ai_quota', 'aicc-tool', 'ask_user', 'buckyos',\n  'caption_image', 'detect_image', 'edit_image', 'edit_video', 'enhance_audio', 'extend_video', 'gen_image', 'gen_music',\n  'gen_video', 'import_office', 'import_table', 'inpaint_image', 'llm_understand_media', 'materialize_resource',\n  'ocr_image', 'reflow', 'remove_bg', 'resume_aicc_task', 'segment_image', 'speech_to_text', 'text_to_speech', 'upscale_image',\n  'upscale_video', 'xagent',\n]\nconst MAX_EXT_TOOLS_LAUNCHER_BYTES = 1024 * 1024\nconst EXT_TOOLS_ID = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/\nconst EXT_TOOLS_COMMAND = /^[A-Za-z0-9_+-][A-Za-z0-9._+-]*$/\nconst EXT_TOOLS_WINDOWS_SUFFIXES = ['', '.exe', '.cmd', '.bat', '.ps1']\n// A launcher resolves its tree from its own location: these never exist where a package lands.\nconst BUILD_MACHINE_PATH = /(?:^|[\\s\"'=:(])(\\/home\\/|\\/Users\\/|\\/root\\/|\\/tmp\\/|\\/var\\/folders\\/|\\/opt\\/buckyos\\/|[A-Za-z]:\\\\\\\\?Users\\\\)/\n\nexport interface ExtToolsPlatform {\n  name: string\n  key: string\n  selector: Record<string, string>\n}\n\nexport const EXT_TOOLS_PLATFORMS: ExtToolsPlatform[] = [\n  { name: 'linux-x86_64', key: 'ext_tools_linux_x86_64', selector: { os: 'linux', arch: 'x86_64' } },\n  { name: 'linux-aarch64', key: 'ext_tools_linux_aarch64', selector: { os: 'linux', arch: 'aarch64' } },\n  { name: 'darwin-arm64', key: 'ext_tools_darwin_arm64', selector: { os: 'macos', arch: 'aarch64' } },\n  { name: 'darwin-x86_64', key: 'ext_tools_darwin_x86_64', selector: { os: 'macos', arch: 'x86_64' } },\n  { name: 'windows-x86_64', key: 'ext_tools_windows_x86_64', selector: { os: 'windows', arch: 'x86_64' } },\n]\n\nexport function extToolsPlatformOfKey(key: string): ExtToolsPlatform | undefined {\n  return EXT_TOOLS_PLATFORMS.find((platform) => platform.key === key)\n}\n\n/** Where one platform gets an online item: the upstream's own archive, and what to do with it once unpacked. */\nexport interface ExtToolsOnlineSource {\n  url: string\n  sha256: string\n  size_bytes: number\n  format: string\n  into?: string\n  rename?: Array<[string, string]>\n  overlay?: string\n}\n\n/** Something a package only declares: a node downloads it from the upstream to `tools/online/<id>/` once the package is\n * installed. A platform without an entry has no such item. */\nexport interface ExtToolsOnlineItem {\n  id: string\n  version: string\n  desc?: string\n  license?: string\n  auto?: boolean\n  platforms: Record<string, ExtToolsOnlineSource>\n}\n\nexport interface ExtToolsManifest {\n  schema: string\n  id: string\n  version: string\n  requires: Array<{ id: string; version: string }>\n  conflicts: string[]\n  provides: Array<{ command: string; version_probe: string; smoke?: string; needs?: string[] }>\n  platforms: string[]\n  size_bytes?: Record<string, number>\n  license?: string\n  desc?: string\n  online?: ExtToolsOnlineItem[]\n}\n\nconst EXT_TOOLS_VERSION = /^[A-Za-z0-9._+-]+$/\nexport const EXT_TOOLS_ONLINE_FORMATS = ['zip', 'tar.gz']\n\nfunction unknownKeys(value: Record<string, unknown>, allowed: string[]): string[] {\n  return Object.keys(value).filter((key) => !allowed.includes(key))\n}\n\nfunction isHttpsUrl(value: unknown): boolean {\n  if (typeof value !== 'string') return false\n  try {\n    const url = new URL(value)\n    return url.protocol === 'https:' && url.hostname !== ''\n  } catch {\n    return false\n  }\n}\n\n/** What is wrong with one platform's source of online item `item` (Rust: `ExtToolsOnlineSource::problem`). */\nfunction extToolsOnlineSourceErrors(item: string, raw: unknown): string[] {\n  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return ['must be an object']\n  const source = raw as Record<string, unknown>\n  const errors = unknownKeys(source, ['url', 'sha256', 'size_bytes', 'format', 'into', 'rename', 'overlay']).map((key) => `${key} is not a field`)\n  if (!isHttpsUrl(source.url)) errors.push(`url ${JSON.stringify(source.url)} must be an https address`)\n  if (typeof source.sha256 !== 'string' || !/^[0-9a-fA-F]{64}$/.test(source.sha256)) errors.push('sha256 must be 64 hex digits')\n  if (!Number.isSafeInteger(source.size_bytes) || (source.size_bytes as number) <= 0) errors.push('size_bytes must be the size of the archive')\n  if (typeof source.format !== 'string' || !EXT_TOOLS_ONLINE_FORMATS.includes(source.format)) errors.push(`format ${JSON.stringify(source.format)} must be zip or tar.gz`)\n  if (source.into !== undefined && (typeof source.into !== 'string' || !isSafeRelativePath(source.into))) errors.push('into must be a relative path inside the item')\n  const pairs = source.rename === undefined ? [] : source.rename\n  const renamed = Array.isArray(pairs) && pairs.every((pair) =>\n    Array.isArray(pair) && pair.length === 2 && pair.every((path) => typeof path === 'string' && isSafeRelativePath(path)) && pair[0] !== pair[1]\n  )\n  if (!renamed) errors.push('rename must be [from, to] pairs of relative paths inside the item')\n  const root = `online/${item}`\n  const overlay = source.overlay\n  if (overlay !== undefined && !(typeof overlay === 'string' && isSafeRelativePath(overlay) && (overlay === root || overlay.startsWith(`${root}/`)))) {\n    errors.push(`overlay must be ${root} or a directory below it`)\n  }\n  return errors\n}\n\n/** The `online` list of a manifest (Rust: `ExtToolsManifest::validate`), and the ids it declares. */\nfunction extToolsOnlineErrors(manifest: Record<string, unknown>): { errors: string[]; items: Set<string> } {\n  const errors: string[] = []\n  const items = new Set<string>()\n  if (manifest.online === undefined) return { errors, items }\n  if (!Array.isArray(manifest.online)) return { errors: ['online must be a list of items'], items }\n  const platforms = Array.isArray(manifest.platforms) ? manifest.platforms : []\n  for (const raw of manifest.online) {\n    const item = (raw ?? {}) as Record<string, unknown>\n    const id = item.id\n    if (typeof id !== 'string' || !EXT_TOOLS_ID.test(id)) {\n      errors.push(`online: id ${JSON.stringify(id)} must be lowercase letters, digits and -`)\n      continue\n    }\n    if (items.has(id)) errors.push(`online: ${id} is listed twice`)\n    items.add(id)\n    for (const key of unknownKeys(item, ['id', 'version', 'desc', 'license', 'auto', 'platforms'])) errors.push(`online ${id}: ${key} is not a field`)\n    if (typeof item.version !== 'string' || !EXT_TOOLS_VERSION.test(item.version)) errors.push(`online ${id}: version must be letters, digits and ._+-`)\n    for (const text of ['desc', 'license']) if (item[text] !== undefined && typeof item[text] !== 'string') errors.push(`online ${id}: ${text} must be a string`)\n    if (item.auto !== undefined && typeof item.auto !== 'boolean') errors.push(`online ${id}: auto must be true or false`)\n    const sources = item.platforms\n    if (!sources || typeof sources !== 'object' || Array.isArray(sources) || Object.keys(sources).length === 0) {\n      errors.push(`online ${id}: platforms must not be empty`)\n      continue\n    }\n    for (const [platform, source] of Object.entries(sources)) {\n      if (!platforms.includes(platform)) errors.push(`online ${id}: ${platform} is not a platform of the package`)\n      for (const problem of extToolsOnlineSourceErrors(id, source)) errors.push(`online ${id} on ${platform}: ${problem}`)\n    }\n  }\n  return { errors, items }\n}\n\n/** The manifest's own rules (`buckyos.ext_tools/1`, doc/pikg/format.md §5), each problem one line. */\nexport function extToolsManifestErrors(value: unknown): string[] {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) return ['must be a JSON object']\n  const manifest = value as Record<string, unknown>\n  const errors: string[] = []\n  const allowed = ['schema', 'id', 'version', 'requires', 'conflicts', 'provides', 'platforms', 'size_bytes', 'license', 'desc', 'online']\n  for (const key of Object.keys(manifest)) if (!allowed.includes(key)) errors.push(`${key} is not a field of the manifest`)\n  if (manifest.schema !== EXT_TOOLS_MANIFEST_SCHEMA) errors.push(`schema must be ${EXT_TOOLS_MANIFEST_SCHEMA}`)\n  if (typeof manifest.id !== 'string' || !EXT_TOOLS_ID.test(manifest.id)) errors.push('id must be lowercase letters, digits and -')\n  if (typeof manifest.version !== 'string' || !EXT_TOOLS_VERSION.test(manifest.version)) errors.push('version must be letters, digits and ._+-')\n  if (!Array.isArray(manifest.provides)) errors.push('provides must be a list')\n  else if (manifest.provides.length === 0 && !(Array.isArray(manifest.online) && manifest.online.length > 0)) {\n    errors.push('a package provides commands or declares online items')\n  }\n  const online = extToolsOnlineErrors(manifest)\n  errors.push(...online.errors)\n  const commands = new Set<string>()\n  for (const raw of Array.isArray(manifest.provides) ? manifest.provides : []) {\n    const entry = (raw ?? {}) as Record<string, unknown>\n    const command = entry.command\n    if (typeof command !== 'string' || !EXT_TOOLS_COMMAND.test(command)) {\n      errors.push(`provides: ${JSON.stringify(command)} is not a command name`)\n      continue\n    }\n    if (commands.has(command)) errors.push(`provides: command ${command} is listed twice`)\n    if (EXT_TOOLS_RESERVED_COMMANDS.includes(command)) errors.push(`provides: ${command} is a standard command and cannot be provided by a package`)\n    commands.add(command)\n    for (const key of unknownKeys(entry, ['command', 'version_probe', 'smoke', 'needs'])) errors.push(`provides: ${key} is not a field of ${command}`)\n    if (typeof entry.version_probe !== 'string' || !entry.version_probe.trim()) errors.push(`provides: ${command} has no version_probe`)\n    const smoke = entry.smoke\n    if (smoke !== undefined && (typeof smoke !== 'string' || !isSafeRelativePath(smoke))) {\n      errors.push(`provides: the smoke of ${command} must be a relative path inside the payload`)\n    }\n    const needs = entry.needs === undefined ? [] : entry.needs\n    if (!Array.isArray(needs) || !needs.every((need) => typeof need === 'string')) {\n      errors.push(`provides: the needs of ${command} must list online items by id`)\n      continue\n    }\n    for (const need of needs as string[]) if (!online.items.has(need)) errors.push(`provides: ${command} needs ${need}, which is not an online item of the package`)\n    if (new Set(needs).size !== needs.length) errors.push(`provides: ${command} needs an online item twice`)\n  }\n  if (!Array.isArray(manifest.platforms) || manifest.platforms.length === 0) errors.push('platforms must not be empty')\n  for (const platform of Array.isArray(manifest.platforms) ? manifest.platforms : []) {\n    if (!EXT_TOOLS_PLATFORMS.some((known) => known.name === platform)) errors.push(`unknown platform ${JSON.stringify(platform)}`)\n  }\n  for (const raw of Array.isArray(manifest.requires) ? manifest.requires : manifest.requires === undefined ? [] : [null]) {\n    const required = (raw ?? {}) as Record<string, unknown>\n    if (typeof required.id !== 'string' || !EXT_TOOLS_ID.test(required.id) || required.id === manifest.id || typeof required.version !== 'string') {\n      errors.push(`requires: ${JSON.stringify(raw)} is not another package's {id, version}`)\n    }\n  }\n  if (manifest.conflicts !== undefined && !(Array.isArray(manifest.conflicts) && manifest.conflicts.every((id) => typeof id === 'string' && id !== manifest.id))) {\n    errors.push('conflicts must list other packages by id')\n  }\n  return errors\n}\n\nfunction isSafeRelativePath(path: string): boolean {\n  return !path.includes('\\\\') && !path.startsWith('/') && path.split('/').every((part) => part && part !== '.' && part !== '..')\n}\n\nexport function parseExtToolsManifest(bytes: Uint8Array): ExtToolsManifest {\n  let value: unknown\n  try {\n    value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n  } catch (error) {\n    throw invalid('ext_tools', `${EXT_TOOLS_MANIFEST_FILE} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`)\n  }\n  const errors = extToolsManifestErrors(value)\n  if (errors.length > 0) throw invalid('ext_tools', `${EXT_TOOLS_MANIFEST_FILE}: ${errors.join('; ')}`)\n  const manifest = value as ExtToolsManifest\n  manifest.requires ??= []\n  manifest.conflicts ??= []\n  return manifest\n}\n\n/** A payload's tree, from a directory or from its tar: the regular files, as `pikg build` would archive them. */\nexport interface ExtToolsPayloadTree {\n  files: Map<string, { executable: boolean }>\n  directories: Set<string>\n  /** The contents of the small files under `bin/`. */\n  launchers: Map<string, Uint8Array>\n}\n\n/** What is wrong with a payload of `platform`: its layout, a launcher for every command it provides and for nothing\n * else, the smoke scripts, and launchers that only name paths of the machine that built them. */\nexport function extToolsPayloadErrors(manifest: ExtToolsManifest, platform: string, tree: ExtToolsPayloadTree, buildPaths: string[] = []): string[] {\n  const errors: string[] = []\n  const windows = platform.startsWith('windows-')\n  const suffixes = windows ? EXT_TOOLS_WINDOWS_SUFFIXES : ['']\n  const online = manifest.online ?? []\n  for (const path of [...tree.files.keys(), ...tree.directories]) {\n    const [top, second] = path.split('/')\n    const isTop = !path.includes('/')\n    const known = top === EXT_TOOLS_MANIFEST_FILE && isTop || top === 'bin' || top === 'smoke' || top === 'store' || top === 'online'\n    if (!known) errors.push(`${path}: a package only holds ${EXT_TOOLS_MANIFEST_FILE}, bin/, smoke/, store/${manifest.id}/ and online/<item>/`)\n    if (top === 'store' && second !== undefined && second !== manifest.id) errors.push(`${path}: a package only writes store/${manifest.id}/`)\n    if (top === 'online' && second !== undefined && !online.some((item) => item.id === second)) errors.push(`${path}: not an online item of the package`)\n  }\n  for (const item of online) {\n    const overlay = item.platforms[platform]?.overlay\n    const present = overlay !== undefined && (tree.directories.has(overlay) || [...tree.files.keys()].some((path) => path.startsWith(`${overlay}/`)))\n    if (overlay !== undefined && !present) errors.push(`${overlay}: the overlay of online item ${item.id} is missing`)\n  }\n  const declared = new Set(manifest.provides.map((provided) => provided.command))\n  for (const provided of manifest.provides) {\n    const launcher = suffixes.map((suffix) => tree.files.get(`bin/${provided.command}${suffix}`)).find(Boolean)\n    if (!launcher) errors.push(`bin/${provided.command}: the launcher of a provided command is missing`)\n    else if (!windows && !launcher.executable) errors.push(`bin/${provided.command}: the launcher is not executable`)\n    const smoke = provided.smoke && windows ? provided.smoke.replace(/\\.[^./]+$/, '.ps1') : provided.smoke\n    if (smoke && !tree.files.has(smoke)) errors.push(`${smoke}: the smoke script of ${provided.command} is missing`)\n  }\n  for (const path of tree.files.keys()) {\n    if (!path.startsWith('bin/')) continue\n    const name = path.slice('bin/'.length)\n    const command = suffixes.map((suffix) => suffix && name.endsWith(suffix) ? name.slice(0, -suffix.length) : name).find((candidate) => declared.has(candidate))\n    if (!command) errors.push(`${path}: not in provides, so nothing knows this package provides it`)\n  }\n  const decoder = new TextDecoder()\n  for (const [path, bytes] of tree.launchers) {\n    const text = decoder.decode(bytes)\n    const named = buildPaths.find((dir) => text.includes(dir))\n    if (named) errors.push(`${path}: names ${named} on the machine that built it`)\n    else if (BUILD_MACHINE_PATH.test(text)) errors.push(`${path}: names an absolute path of the machine that built it (${BUILD_MACHINE_PATH.exec(text)?.[1]})`)\n  }\n  return errors\n}\n\nfunction assertExtToolsOf(appDoc: Record<string, unknown>, manifest: ExtToolsManifest, platform: string, platforms: string[]): void {\n  if (manifest.id !== appDoc.name) throw invalid('ext_tools', `${EXT_TOOLS_MANIFEST_FILE} id ${manifest.id} is not the App name ${appDoc.name}`)\n  if (manifest.version !== appDoc.version) throw invalid('ext_tools', `${EXT_TOOLS_MANIFEST_FILE} version ${manifest.version} is not the App version ${appDoc.version}`)\n  if (!manifest.platforms.includes(platform)) throw invalid('ext_tools', `${EXT_TOOLS_MANIFEST_FILE} does not list the payload's platform ${platform}`)\n  const missing = manifest.platforms.filter((name) => !platforms.includes(name))\n  if (missing.length > 0) throw invalid('ext_tools', `${EXT_TOOLS_MANIFEST_FILE} lists platforms without a payload: ${missing.join(', ')}`)\n}\n\n/** Check one payload of an `ext_tools` package (a tar.gz stream, never held whole) and return its manifest. */\nasync function verifyExtToolsPayload(\n  gzip: ReadableStream<Uint8Array>,\n  key: string,\n  appDoc: Record<string, unknown>,\n): Promise<ExtToolsManifest> {\n  const platform = extToolsPlatformOfKey(key)\n  if (!platform) throw invalid('appdoc', `an ext_tools package has no sub package ${key}`)\n  const listing = await listTarGzStream(\n    gzip,\n    MAX_EXT_TOOLS_PAYLOAD_BYTES,\n    (path, size) => path === EXT_TOOLS_MANIFEST_FILE || (path.startsWith('bin/') && size <= MAX_EXT_TOOLS_LAUNCHER_BYTES),\n  )\n  const raw = listing.captured.get(EXT_TOOLS_MANIFEST_FILE)\n  if (!raw) throw invalid('ext_tools', `${key}: ${EXT_TOOLS_MANIFEST_FILE} is not at the root of the payload`)\n  const manifest = parseExtToolsManifest(raw)\n  assertExtToolsOf(appDoc, manifest, platform.name, Object.keys(expectObject(appDoc.pkg_list, 'APPDOC.pkg_list')).flatMap((k) => extToolsPlatformOfKey(k)?.name ?? []))\n  const launchers = new Map([...listing.captured].filter(([path]) => path.startsWith('bin/')))\n  const errors = extToolsPayloadErrors(manifest, platform.name, { files: listing.files, directories: listing.directories, launchers })\n  if (errors.length > 0) throw invalid('ext_tools', `${key}: ${errors.join('; ')}`)\n  return manifest\n}\n\nexport async function validateSnapshot(\n  distDir: string,\n  appDoc: Record<string, unknown>,\n  packageMeta: PackageMetaFile,\n): Promise<ValidatedPikg> {\n  const payloads = new Map<string, FileDigest>()\n  for (const entryValue of Object.values(packageMeta.content_index)) {\n    const entry = validateContentIndexEntry(entryValue, 'content_index')\n    const path = join(distDir, entry.path)\n    const digest = await digestFile(path)\n    payloads.set(entry.path, digest)\n  }\n  const validated = validateObjectGraph(appDoc, packageMeta, payloads, true, false, true)\n  if (appDoc.app_type === 'aiws') {\n    for (const sub of validated.subpackages) await verifyAiwsPayload(await getHost().readFile(join(distDir, sub.payload_path)))\n  }\n  if (appDoc.app_type === EXT_TOOLS_APP_TYPE) {\n    for (const sub of validated.subpackages) await verifyExtToolsPayload(fileReadableStream(join(distDir, sub.payload_path)), sub.key, appDoc)\n  }\n  return validated\n}\n\nexport async function packSnapshot(\n  distDir: string,\n  destination: string,\n  appDoc: Record<string, unknown>,\n  packageMeta: PackageMetaFile,\n): Promise<void> {\n  const validated = await validateSnapshot(distDir, appDoc, packageMeta)\n  const encoder = new TextEncoder()\n  await writeStoredZip(destination, [\n    { name: APPDOC_ENTRY, bytes: encoder.encode(`${JSON.stringify(appDoc, null, 2)}\\n`) },\n    {\n      name: PACKAGE_META_ENTRY,\n      bytes: encoder.encode(`${JSON.stringify(packageMeta, null, 2)}\\n`),\n    },\n    ...validated.subpackages.map((subpackage) => ({\n      name: subpackage.payload_path,\n      path: join(distDir, subpackage.payload_path),\n    })),\n  ])\n}\n\nexport async function inspectPikg(path: string): Promise<PikgInspectionResult> {\n  const archive = await openZip(path)\n  let metadataTotal = 0\n  for (const entry of archive.entries) {\n    if (\n      entry.name === APPDOC_ENTRY || entry.name === APPDOC_JWT_ENTRY ||\n      entry.name === PACKAGE_META_ENTRY ||\n      entry.name.startsWith('objects/') && entry.name.endsWith('.json')\n    ) {\n      const limit = entry.name === APPDOC_ENTRY || entry.name === APPDOC_JWT_ENTRY\n        ? MAX_APPDOC_BYTES\n        : MAX_METADATA_ENTRY_BYTES\n      if (entry.size > limit) throw invalid('limits', `metadata entry exceeds limit: ${entry.name}`)\n      metadataTotal += entry.size\n    }\n  }\n  if (metadataTotal > MAX_METADATA_TOTAL_BYTES) {\n    throw invalid('limits', 'PIKG metadata exceeds the total size limit')\n  }\n  if (archive.byName.has('APPDOC.wt')) {\n    throw invalid('appdoc', 'legacy APPDOC.wt is not supported')\n  }\n  const jsonEntry = archive.byName.get(APPDOC_ENTRY)\n  const jwtEntry = archive.byName.get(APPDOC_JWT_ENTRY)\n  if (!jsonEntry && !jwtEntry) throw invalid('appdoc', 'PIKG has no App Document')\n\n  const jsonDoc = jsonEntry\n    ? parseJsonObject(\n      await readZipEntry(archive, jsonEntry, MAX_APPDOC_BYTES),\n      APPDOC_ENTRY,\n    )\n    : undefined\n  const jwt = jwtEntry\n    ? new TextDecoder('utf-8', { fatal: true }).decode(\n      await readZipEntry(archive, jwtEntry, MAX_APPDOC_BYTES),\n    ).trim()\n    : undefined\n  const jwtDoc = jwt ? decodeJwtClaims(jwt) : undefined\n  if (jsonDoc && jwtDoc && appDocObjectId(jsonDoc) !== appDocObjectId(jwtDoc)) {\n    throw invalid('appdoc', 'APPDOC.json and APPDOC.jwt have different canonical documents')\n  }\n  const appDoc = jwtDoc ?? jsonDoc!\n  const metaEntry = archive.byName.get(PACKAGE_META_ENTRY)\n  if (!metaEntry) throw invalid('package-meta', 'PACKAGE_META.json is required')\n  const packageMeta = parsePackageMeta(\n    parseJsonObject(\n      await readZipEntry(archive, metaEntry, MAX_METADATA_ENTRY_BYTES),\n      PACKAGE_META_ENTRY,\n    ),\n  )\n  for (\n    const entry of archive.entries.filter((candidate) => candidate.name.startsWith('objects/'))\n  ) {\n    const match = /^objects\\/([^/]+)\\.json$/.exec(entry.name)\n    if (!match) {\n      throw invalid(\n        'object-graph',\n        `invalid object entry path: ${entry.name}`,\n        entry.name,\n      )\n    }\n    let objectId: InstanceType<typeof ndn.ObjId>\n    try {\n      objectId = ndn.ObjId.fromString(match[1])\n    } catch {\n      throw invalid('object-graph', `invalid object entry ID: ${entry.name}`, entry.name)\n    }\n    const value = parseJsonValue(\n      await readZipEntry(archive, entry, MAX_METADATA_ENTRY_BYTES),\n      entry.name,\n    )\n    const computed = ndn.buildNamedObjectByJson(objectId.objType, value)[0]\n    if (!computed.equals(objectId)) {\n      throw invalid('object-graph', `object entry ID mismatch: ${entry.name}`, entry.name)\n    }\n  }\n  const payloads = new Map<string, FileDigest>()\n  for (const value of Object.values(packageMeta.content_index)) {\n    const content = validateContentIndexEntry(value, 'content_index')\n    const entry = archive.byName.get(content.path)\n    if (!entry) throw invalid('content-index', `content entry is missing: ${content.path}`)\n    if (entry.size !== content.size) {\n      throw invalid('content-index', `content entry size mismatch: ${content.path}`, content.path)\n    }\n    const expected = parseSha256(content.digest, `content_index.${content.digest}`)\n    payloads.set(content.path, await verifyZipEntry(archive, entry, expected))\n  }\n  const validated = validateObjectGraph(\n    appDoc,\n    packageMeta,\n    payloads,\n    Boolean(jsonEntry),\n    Boolean(jwtEntry),\n    !jsonDoc || !jwtDoc || appDocObjectId(jsonDoc) === appDocObjectId(jwtDoc),\n  )\n  let aiws: Record<string, unknown> | undefined\n  if (appDoc.app_type === 'aiws') {\n    const sub = validated.subpackages[0]\n    aiws = await verifyAiwsPayload(await readZipEntry(archive, archive.byName.get(sub.payload_path)!, MAX_AIWS_PAYLOAD_BYTES))\n  }\n  let extTools: Record<string, unknown> | undefined\n  if (appDoc.app_type === EXT_TOOLS_APP_TYPE) {\n    for (const sub of validated.subpackages) {\n      const manifest = await verifyExtToolsPayload(zipEntryStream(archive.path, archive.byName.get(sub.payload_path)!), sub.key, appDoc)\n      extTools ??= { ...manifest }\n    }\n  }\n  const pikgDigest = await digestFile(path)\n  return {\n    schema_version: 1,\n    ...(aiws ? { aiws } : {}),\n    ...(extTools ? { ext_tools: extTools } : {}),\n    protocol: PACKAGE_META_SCHEMA,\n    pikg_path: resolve(path),\n    size: pikgDigest.size,\n    pikg_digest: `sha256:${pikgDigest.sha256}`,\n    valid: true,\n    app: {\n      did: String(appDoc.did),\n      app_id: appIdFromDid(String(appDoc.did)),\n      ...(typeof appDoc.name === 'string' ? { name: appDoc.name } : {}),\n      app_type: String(appDoc.app_type),\n      version: String(appDoc.version),\n      owner: String(appDoc.owner),\n      app_doc_object_id: validated.appDocObjectId,\n    },\n    app_doc_form: jsonEntry && jwtEntry ? 'both' : jwtEntry ? 'signed' : 'unsigned',\n    canonical_match: validated.canonicalMatch,\n    subpackages: validated.subpackages.map((subpackage) => ({\n      key: subpackage.key,\n      selector: subpackage.selector,\n      required: subpackage.required,\n      pkg_id: subpackage.pkg_id,\n      pkg_objid: subpackage.pkg_objid,\n      payload: {\n        path: subpackage.payload_path,\n        size: subpackage.payload_size,\n        digest: subpackage.payload_digest,\n      },\n      ...(subpackage.docker_image_name ? { docker_image_name: subpackage.docker_image_name } : {}),\n      ...(subpackage.docker_image_digest\n        ? { docker_image_digest: subpackage.docker_image_digest }\n        : {}),\n    })),\n    offline_content_validation: 'passed',\n    signature_validation: jwtEntry ? 'not-resolvable-offline' : 'not-present',\n    publication_validation: 'not-checked',\n  }\n}\n\nexport function parsePackageMeta(value: Record<string, unknown>): PackageMetaFile {\n  try {\n    rejectUnknown(\n      value,\n      ['@schema', 'app_doc_id', 'package_objects', 'content_index'],\n      PACKAGE_META_ENTRY,\n    )\n  } catch (error) {\n    if (error instanceof UsageError) throw invalid('package-meta', error.message)\n    throw error\n  }\n  if (value['@schema'] !== PACKAGE_META_SCHEMA) {\n    throw invalid('package-meta', `unsupported PACKAGE_META.json schema: ${value['@schema']}`)\n  }\n  const appDocId = expectNonEmptyString(value.app_doc_id, 'PACKAGE_META.json.app_doc_id')\n  if (!OBJECT_ID.test(appDocId) || !appDocId.startsWith('appdoc:')) {\n    throw invalid('package-meta', 'PACKAGE_META.json.app_doc_id is invalid')\n  }\n  const packageObjects = expectObject(value.package_objects, 'PACKAGE_META.json.package_objects')\n  const contentIndex = expectObject(value.content_index, 'PACKAGE_META.json.content_index')\n  return {\n    '@schema': PACKAGE_META_SCHEMA,\n    app_doc_id: appDocId,\n    package_objects: packageObjects as Record<string, Record<string, unknown>>,\n    content_index: contentIndex as Record<string, ContentIndexEntry>,\n  }\n}\n\nfunction validateObjectGraph(\n  appDoc: Record<string, unknown>,\n  packageMeta: PackageMetaFile,\n  payloads: Map<string, FileDigest>,\n  hasJson: boolean,\n  hasSigned: boolean,\n  canonicalMatch: boolean,\n): ValidatedPikg {\n  validateAppDocShape(appDoc)\n  const appId = appDocObjectId(appDoc)\n  if (packageMeta.app_doc_id !== appId) {\n    throw invalid('object-graph', 'PACKAGE_META.json app_doc_id does not match APPDOC')\n  }\n  const appVersion = String(appDoc.version)\n  const namespace = deriveNamespaceForPackage(appDoc)\n  const pkgList = appDoc.pkg_list as Record<string, unknown>\n  const referenced = new Set<string>()\n  const subpackages: ValidatedSubpackage[] = []\n  const contentBySubpackage = new Map<string, ContentIndexEntry>()\n  for (const [digest, raw] of Object.entries(packageMeta.content_index)) {\n    const entry = validateContentIndexEntry(raw, `content_index.${digest}`)\n    if (entry.digest !== digest) throw invalid('content-index', `digest key mismatch: ${digest}`)\n    const expectedHex = parseSha256(digest, `content_index.${digest}`)\n    const payload = payloads.get(entry.path)\n    if (!payload) throw invalid('content-index', `payload is missing: ${entry.path}`, entry.path)\n    if (payload.size !== entry.size || payload.sha256 !== expectedHex) {\n      throw invalid('content', `payload does not match content index: ${entry.path}`, entry.path)\n    }\n    if (contentBySubpackage.has(entry.sub_pkg_name)) {\n      throw invalid('content-index', `subpackage has more than one payload: ${entry.sub_pkg_name}`)\n    }\n    contentBySubpackage.set(entry.sub_pkg_name, entry)\n  }\n\n  const dependencyNames = new Set<string>()\n  for (\n    const [key, rawDesc] of Object.entries(pkgList).sort(([left], [right]) =>\n      left.localeCompare(right)\n    )\n  ) {\n    validateSubpackageNameForPackage(key)\n    const desc = expectObject(rawDesc, `APPDOC.pkg_list.${key}`)\n    rejectUnknown(\n      desc,\n      [\n        'pkg_id',\n        'pkg_objid',\n        'docker_image_name',\n        'docker_image_digest',\n        'source_url',\n        'selector',\n        'required',\n      ],\n      `APPDOC.pkg_list.${key}`,\n    )\n    if (desc.source_url !== undefined) {\n      throw invalid('self-contained', `source_url is not allowed for bundled App: ${key}`)\n    }\n    const pkgId = expectNonEmptyString(desc.pkg_id, `APPDOC.pkg_list.${key}.pkg_id`)\n    const parsedId = parsePackageId(pkgId, key)\n    if (parsedId.version !== appVersion) {\n      throw invalid('namespace', `subpackage ${key} must use App version ${appVersion}`)\n    }\n    const uniqueName = packageUniqueName(parsedId.name, key)\n    const namespacePrefix = uniqueName.endsWith(`.${namespace}`)\n      ? uniqueName.slice(0, -namespace.length - 1)\n      : undefined\n    if (\n      uniqueName !== namespace &&\n      (!namespacePrefix || namespacePrefix.includes('.') ||\n        !/^[a-z0-9][a-z0-9_-]*$/.test(namespacePrefix))\n    ) {\n      throw invalid('namespace', `subpackage ${key} is outside App package namespace`)\n    }\n    const pkgObjid = expectNonEmptyString(desc.pkg_objid, `APPDOC.pkg_list.${key}.pkg_objid`)\n    if (!OBJECT_ID.test(pkgObjid) || !pkgObjid.startsWith('pkg:')) {\n      throw invalid('object-graph', `subpackage ${key} has an invalid pkg_objid`)\n    }\n    const packageObject = packageMeta.package_objects[pkgObjid]\n    if (!packageObject) throw invalid('object-graph', `PackageMeta is missing for ${key}`)\n    const computed = ndn.buildNamedObjectByJson(ndn.OBJ_TYPE_PKG, packageObject)[0].toString()\n    if (computed !== pkgObjid) {\n      throw invalid('object-graph', `PackageMeta Object ID mismatch: ${key}`)\n    }\n    const metaName = expectNonEmptyString(packageObject.name, `PackageMeta(${key}).name`)\n    const metaVersion = expectNonEmptyString(packageObject.version, `PackageMeta(${key}).version`)\n    if (metaName !== parsedId.name || metaVersion !== parsedId.version) {\n      throw invalid('namespace', `PackageMeta identity does not match pkg_id: ${key}`)\n    }\n    if (packageObject.owner !== appDoc.owner || packageObject.author !== appDoc.author) {\n      throw invalid('namespace', `PackageMeta owner/author does not match AppDoc: ${key}`)\n    }\n    const metaDeps = packageObject.deps\n    if (\n      metaDeps !== undefined &&\n      Object.keys(expectObject(metaDeps, `PackageMeta(${key}).deps`)).length\n    ) {\n      throw invalid(\n        'self-contained',\n        `third-party PackageMeta dependencies are not allowed: ${key}`,\n      )\n    }\n    const entry = contentBySubpackage.get(key)\n    if (!entry) throw invalid('content-index', `content index is missing for ${key}`)\n    if (entry.path !== `${key}.tar.gz` || entry.format !== 'tar.gz') {\n      throw invalid('content-index', `subpackage ${key} has a noncanonical payload path`)\n    }\n    const metaSize = expectSafeInteger(packageObject.size, `PackageMeta(${key}).size`)\n    if (metaSize !== entry.size) throw invalid('content', `PackageMeta size mismatch: ${key}`)\n    validateChunkContent(\n      expectNonEmptyString(packageObject.content, `PackageMeta(${key}).content`),\n      entry.size,\n      parseSha256(entry.digest, `content_index.${entry.digest}`),\n      key,\n    )\n    const selector = canonicalSelectorForPackage(desc.selector, `APPDOC.pkg_list.${key}.selector`)\n    assertSelectorForPackage(key, selector)\n    if (desc.required !== undefined && typeof desc.required !== 'boolean') {\n      throw invalid('appdoc', `required must be boolean: ${key}`)\n    }\n    const dockerImageName = optionalNonEmptyString(\n      desc.docker_image_name,\n      `APPDOC.pkg_list.${key}.docker_image_name`,\n    )\n    const dockerImageDigest = optionalNonEmptyString(\n      desc.docker_image_digest,\n      `APPDOC.pkg_list.${key}.docker_image_digest`,\n    )\n    if (dockerImageDigest && !SHA256_DIGEST.test(dockerImageDigest)) {\n      throw invalid('appdoc', `invalid Docker image digest: ${key}`)\n    }\n    referenced.add(pkgObjid)\n    dependencyNames.add(metaName)\n    subpackages.push({\n      key,\n      selector: selector ?? derivedSelector(key) ?? null,\n      required: desc.required === undefined ? true : desc.required,\n      pkg_id: pkgId,\n      pkg_objid: pkgObjid,\n      payload_path: entry.path,\n      payload_size: entry.size,\n      payload_digest: entry.digest,\n      ...(dockerImageName ? { docker_image_name: dockerImageName } : {}),\n      ...(dockerImageDigest ? { docker_image_digest: dockerImageDigest } : {}),\n    })\n  }\n  if (subpackages.length === 0) throw invalid('appdoc', 'AppDoc.pkg_list must not be empty')\n  for (const key of Object.keys(packageMeta.package_objects)) {\n    if (!referenced.has(key)) {\n      throw invalid('object-graph', `unreferenced PackageMeta object: ${key}`)\n    }\n  }\n  if (contentBySubpackage.size !== subpackages.length) {\n    throw invalid('content-index', 'content index and pkg_list have different subpackages')\n  }\n  if (dependencyNames.size !== subpackages.length) {\n    throw invalid('self-contained', 'AppDoc package identities are not unique')\n  }\n  return {\n    appDoc,\n    appDocObjectId: appId,\n    packageMeta,\n    subpackages,\n    hasJsonAppDoc: hasJson,\n    hasSignedAppDoc: hasSigned,\n    canonicalMatch,\n  }\n}\n\nexport function validateAppPresentation(value: unknown, label: string): Record<string, unknown> {\n  const presentation = expectObject(value, label)\n  rejectUnknown(presentation, ['title', 'summary', 'description', 'icons', 'links', 'license'], label)\n  for (const field of ['title', 'summary', 'description', 'icons', 'links']) {\n    const values = expectObject(presentation[field], `${label}.${field}`)\n    for (const [key, item] of Object.entries(values)) {\n      if (typeof item !== 'string') {\n        throw invalid('appdoc', `${label}.${field}.${key} must be a string`)\n      }\n      if (field === 'icons') {\n        try {\n          ndn.ObjId.fromString(item)\n        } catch {\n          throw invalid('appdoc', `${label}.${field}.${key} must be an ObjectId`)\n        }\n      }\n    }\n  }\n  if (typeof presentation.license !== 'string') {\n    throw invalid('appdoc', `${label}.license must be a string`)\n  }\n  return presentation\n}\n\nexport function validateAppDocShape(appDoc: Record<string, unknown>): void {\n  if (appDoc.presentation !== undefined && appDoc.presentation !== null) {\n    validateAppPresentation(appDoc.presentation, 'APPDOC.presentation')\n  }\n  rejectUnknown(\n    appDoc,\n    [\n      'schema_version',\n      'doc_type',\n      'did',\n      'name',\n      'copyright',\n      'tags',\n      'categories',\n      'base_on',\n      'directory',\n      'references',\n      'version',\n      'version_tag',\n      'app_type',\n      'owner',\n      'controller',\n      'author',\n      'create_time',\n      'last_update_time',\n      'exp',\n      'pkg_list',\n      'show_name',\n      'presentation',\n      'sdk_version',\n      'req_capbilities',\n      'permissions',\n      'content_handlers',\n      'selector_type',\n      'service_config_tips',\n    ],\n    'APPDOC',\n  )\n  if (appDoc.schema_version !== 1) {\n    throw invalid('appdoc', 'APPDOC.schema_version must be 1')\n  }\n  for (\n    const field of [\n      'did',\n      'version',\n      'app_type',\n      'owner',\n      'controller',\n      'author',\n      'show_name',\n      'selector_type',\n    ]\n  ) {\n    expectNonEmptyString(appDoc[field], `APPDOC.${field}`)\n  }\n  if (appDoc.doc_type !== 'app') throw invalid('appdoc', 'APPDOC.doc_type must be app')\n  if (!['service', 'dapp', 'web', 'agent', 'agent_skills', 'aiws', EXT_TOOLS_APP_TYPE].includes(String(appDoc.app_type))) {\n    throw invalid('appdoc', 'APPDOC.app_type is invalid')\n  }\n  if (appDoc.name !== undefined) expectNonEmptyString(appDoc.name, 'APPDOC.name')\n  optionalString(appDoc.copyright, 'APPDOC.copyright')\n  for (const field of ['tags', 'categories']) {\n    const values = appDoc[field]\n    if (\n      values !== undefined &&\n      (!Array.isArray(values) || values.length === 0 ||\n        values.some((value) => typeof value !== 'string'))\n    ) {\n      throw invalid('appdoc', `APPDOC.${field} must be a non-empty string array when present`)\n    }\n  }\n  if (appDoc.base_on !== undefined) {\n    const baseOn = expectNonEmptyString(appDoc.base_on, 'APPDOC.base_on')\n    try {\n      ndn.ObjId.fromString(baseOn)\n    } catch {\n      throw invalid('appdoc', 'APPDOC.base_on must be an ObjectId')\n    }\n  }\n  for (const field of ['directory', 'references']) {\n    if (appDoc[field] === undefined) continue\n    const entries = expectObject(appDoc[field], `APPDOC.${field}`)\n    if (Object.keys(entries).length === 0) {\n      throw invalid('appdoc', `APPDOC.${field} must not be empty when present`)\n    }\n    for (const [key, value] of Object.entries(entries)) {\n      expectObject(value, `APPDOC.${field}.${key}`)\n    }\n  }\n  expectSafeInteger(appDoc.create_time, 'APPDOC.create_time')\n  expectSafeInteger(appDoc.last_update_time, 'APPDOC.last_update_time')\n  if (expectSafeInteger(appDoc.exp, 'APPDOC.exp') === 0) {\n    throw invalid('appdoc', 'APPDOC.exp must be greater than zero')\n  }\n  appIdFromDid(String(appDoc.did))\n  parseDid(String(appDoc.owner), 'owner')\n  parseDid(String(appDoc.controller), 'controller')\n  parseDid(String(appDoc.author), 'author')\n  if (appDoc.permissions !== undefined && !Array.isArray(appDoc.permissions)) {\n    throw invalid('appdoc', 'APPDOC.permissions must be an array')\n  }\n  validatePermissions(appDoc.permissions ?? [], 'APPDOC.permissions')\n  if (appDoc.content_handlers !== undefined && !Array.isArray(appDoc.content_handlers)) {\n    throw invalid('appdoc', 'APPDOC.content_handlers must be an array')\n  }\n  validateServiceConfigTips(appDoc.service_config_tips, 'APPDOC.service_config_tips')\n  const pkgList = expectObject(appDoc.pkg_list, 'APPDOC.pkg_list')\n  if (Object.keys(pkgList).length === 0) {\n    throw invalid('appdoc', 'APPDOC.pkg_list must not be empty')\n  }\n  if (appDoc.app_type === 'agent_skills') {\n    expectNonEmptyString(appDoc.name, 'APPDOC.name')\n    if (Object.keys(pkgList).join() !== 'agent_skills') {\n      throw invalid('appdoc', 'an agent_skills App must contain only the agent_skills sub package')\n    }\n  }\n  // AI Workspace controls (buckyos aiworkspace README “Extension controls”): one bundle, nothing to run\n  if (appDoc.app_type === 'aiws' && Object.keys(pkgList).join() !== AIWS_SUB_PACKAGE) {\n    throw invalid('appdoc', 'an aiws package must contain only the aiws sub package')\n  }\n  // Extension tools: one payload per platform, nothing to run\n  if (appDoc.app_type === EXT_TOOLS_APP_TYPE) {\n    expectNonEmptyString(appDoc.name, 'APPDOC.name')\n    const unknown = Object.keys(pkgList).find((key) => !extToolsPlatformOfKey(key))\n    if (unknown) throw invalid('appdoc', `an ext_tools package must contain only ext_tools_<os>_<arch> sub packages, not ${unknown}`)\n  } else {\n    const stray = Object.keys(pkgList).find((key) => extToolsPlatformOfKey(key))\n    if (stray) throw invalid('appdoc', `${stray} belongs to an ext_tools package`)\n  }\n  deriveNamespaceForPackage(appDoc)\n}\n\nfunction deriveNamespaceForPackage(appDoc: Record<string, unknown>): string {\n  try {\n    return deriveAppNamespace(String(appDoc.did))\n  } catch (error) {\n    if (error instanceof UsageError) throw invalid('namespace', error.message)\n    throw error\n  }\n}\n\nfunction validateContentIndexEntry(value: unknown, label: string): ContentIndexEntry {\n  const entry = expectObject(value, label)\n  rejectUnknown(entry, ['sub_pkg_name', 'path', 'format', 'size', 'digest'], label)\n  const subpackage = expectNonEmptyString(entry.sub_pkg_name, `${label}.sub_pkg_name`)\n  validateSubpackageNameForPackage(subpackage)\n  const path = expectNonEmptyString(entry.path, `${label}.path`)\n  if (path !== `${subpackage}.tar.gz`) {\n    throw invalid('content-index', `invalid payload path: ${path}`)\n  }\n  if (entry.format !== 'tar.gz') throw invalid('content-index', `invalid payload format: ${path}`)\n  const size = expectSafeInteger(entry.size, `${label}.size`)\n  const digest = expectNonEmptyString(entry.digest, `${label}.digest`)\n  parseSha256(digest, `${label}.digest`)\n  return { sub_pkg_name: subpackage, path, format: 'tar.gz', size, digest }\n}\n\nfunction validateChunkContent(content: string, size: number, sha256: string, key: string): void {\n  let chunk: InstanceType<typeof ndn.ChunkId>\n  try {\n    chunk = ndn.ChunkId.fromString(content)\n  } catch {\n    throw invalid('content', `PackageMeta content is not a ChunkId: ${key}`)\n  }\n  if (!['sha256', 'mix256'].includes(chunk.chunkType)) {\n    throw invalid('content', `unsupported PackageMeta ChunkId type: ${key}`)\n  }\n  const hash = ndn.hexToBytes(sha256)\n  const expected = chunk.chunkType === 'mix256'\n    ? ndn.ChunkId.fromMix256Result(size, hash)\n    : ndn.ChunkId.fromSha256Result(hash)\n  if (chunk.toString() !== expected.toString()) {\n    throw invalid('content', `PackageMeta ChunkId digest mismatch: ${key}`)\n  }\n}\n\nfunction parsePackageId(value: string, key: string): { name: string; version: string } {\n  const parts = value.split('#')\n  if (parts.length !== 2 || !parts[0] || !parts[1] || parts[1].startsWith('$')) {\n    throw invalid('namespace', `subpackage ${key} must use an exact-version pkg_id`)\n  }\n  return { name: parts[0], version: parts[1] }\n}\n\nfunction packageUniqueName(packageName: string, key: string): string {\n  const parts = packageName.split('.')\n  const environments = new Set([\n    'all',\n    'nightly-linux-amd64',\n    'nightly-linux-aarch64',\n    'nightly-windows-amd64',\n    'nightly-windows-aarch64',\n    'nightly-apple-amd64',\n    'nightly-apple-aarch64',\n  ])\n  const unique = parts.length > 1 && environments.has(parts[0])\n    ? parts.slice(1).join('.')\n    : parts.join('.')\n  if (!unique || unique.split('.').some((label) => !/^[a-z0-9][a-z0-9_-]*$/.test(label))) {\n    throw invalid('namespace', `subpackage ${key} has an invalid package name`)\n  }\n  return unique\n}\n\nfunction decodeJwtClaims(jwt: string): Record<string, unknown> {\n  const segments = jwt.split('.')\n  if (segments.length !== 3 || !segments[1]) throw invalid('appdoc', 'APPDOC.jwt is malformed')\n  try {\n    const normalized = segments[1].replaceAll('-', '+').replaceAll('_', '/')\n    const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')\n    const binary = atob(padded)\n    const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0))\n    return parseJsonObject(bytes, APPDOC_JWT_ENTRY)\n  } catch (error) {\n    if (error instanceof ToolError) throw error\n    throw invalid('appdoc', 'APPDOC.jwt claims are not valid JSON')\n  }\n}\n\nfunction parseJsonObject(bytes: Uint8Array, label: string): Record<string, unknown> {\n  return expectObject(parseJsonValue(bytes, label), label)\n}\n\nfunction parseJsonValue(bytes: Uint8Array, label: string): unknown {\n  try {\n    return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n  } catch (error) {\n    if (error instanceof ToolError) throw error\n    throw invalid('metadata', `${label} is not valid JSON`)\n  }\n}\n\nfunction parseDid(value: string, label: string): { method: string; id: string } {\n  const match = /^did:([a-z0-9]+):(.+)$/.exec(value)\n  if (!match) throw new UsageError('INVALID_DID', `${label} must be a DID`)\n  return { method: match[1], id: match[2] }\n}\n\nfunction parseSha256(value: string, label: string): string {\n  const match = SHA256_DIGEST.exec(value)\n  if (!match) throw invalid('digest', `${label} must be sha256:<64 lowercase hex>`)\n  return match[1].toLowerCase()\n}\n\nfunction canonicalSelectorForPackage(\n  value: unknown,\n  label: string,\n): Record<string, string> | undefined {\n  try {\n    return canonicalSelector(value, label)\n  } catch (error) {\n    if (error instanceof UsageError) throw invalid('appdoc', error.message)\n    throw error\n  }\n}\n\nfunction assertSelectorForPackage(key: string, selector: Record<string, string> | undefined): void {\n  try {\n    assertSelectorCompatible(key, selector, `APPDOC.pkg_list.${key}.selector`)\n  } catch (error) {\n    if (error instanceof UsageError) throw invalid('appdoc', error.message)\n    throw error\n  }\n}\n\nfunction validateSubpackageNameForPackage(name: string): void {\n  try {\n    validateSubpackageName(name)\n  } catch (error) {\n    if (error instanceof UsageError) throw invalid('appdoc', error.message)\n    throw error\n  }\n}\n\nexport function expectObject(value: unknown, label: string): Record<string, unknown> {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) {\n    throw invalid('schema', `${label} must be an object`)\n  }\n  return value as Record<string, unknown>\n}\n\nexport function expectNonEmptyString(value: unknown, label: string): string {\n  if (typeof value !== 'string' || !value.trim()) {\n    throw invalid('schema', `${label} must be a string`)\n  }\n  return value\n}\n\nfunction optionalNonEmptyString(value: unknown, label: string): string | undefined {\n  return value === undefined ? undefined : expectNonEmptyString(value, label)\n}\n\nfunction expectSafeInteger(value: unknown, label: string): number {\n  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n    throw invalid('schema', `${label} must be a non-negative safe integer`)\n  }\n  return value\n}\n\nfunction expectUint(value: unknown, label: string, maximum: number): number {\n  const result = expectSafeInteger(value, label)\n  if (result > maximum) throw invalid('schema', `${label} is too large`)\n  return result\n}\n\nfunction optionalBoolean(value: unknown, label: string): void {\n  if (value !== undefined && typeof value !== 'boolean') {\n    throw invalid('schema', `${label} must be boolean`)\n  }\n}\n\nfunction optionalString(value: unknown, label: string): void {\n  if (value !== undefined && typeof value !== 'string') {\n    throw invalid('schema', `${label} must be a string`)\n  }\n}\n\nfunction validateStringMap(value: unknown, label: string): Record<string, unknown> {\n  const result = expectObject(value, label)\n  if (Object.values(result).some((item) => typeof item !== 'string')) {\n    throw invalid('schema', `${label} values must be strings`)\n  }\n  return result\n}\n\nfunction assertKnownFields(\n  value: Record<string, unknown>,\n  allowed: string[],\n  label: string,\n): void {\n  const accepted = new Set(allowed)\n  const unknown = Object.keys(value).find((key) => !accepted.has(key))\n  if (unknown) throw invalid('schema', `${label}.${unknown} is not allowed`)\n}\n\nexport function rejectUnknown(\n  value: Record<string, unknown>,\n  allowed: string[],\n  label: string,\n): void {\n  const accepted = new Set(allowed)\n  const unknown = Object.keys(value).filter((key) => !accepted.has(key))\n  if (unknown.length) {\n    throw new UsageError('SCHEMA_VALIDATION_FAILED', `${label}.${unknown[0]} is not allowed`)\n  }\n}\n\nfunction invalid(stage: string, message: string, entry?: string): ToolError {\n  return new ToolError('INVALID_PACKAGE', message, 6, false, {\n    stage,\n    ...(entry ? { entry: basename(entry) } : {}),\n  })\n}\n\nexport function stableJsonDigest(value: unknown): string {\n  return sha256Bytes(new TextEncoder().encode(ndn.toCanonicalJsonString(value)))\n}\n\nexport function validateContentHandlers(value: unknown, permissions: unknown[]): unknown[] {\n  if (!Array.isArray(value)) throw invalid('appdoc', 'content_handlers must be an array')\n  const ids = new Set<string>()\n  for (const raw of value) {\n    const h = expectObject(raw, 'content handler')\n    const id = expectNonEmptyString(h.handler_id, 'handler_id')\n    if (!/^[a-zA-Z0-9_-]+$/.test(id) || ids.has(id)) throw invalid('appdoc', 'invalid or duplicate handler_id')\n    ids.add(id)\n    if (!Number.isSafeInteger(h.version) || Number(h.version) < 1) throw invalid('appdoc', 'invalid handler version')\n    if (!Array.isArray(h.selectors) || !h.selectors.length) throw invalid('appdoc', 'missing selectors')\n    for (const rawSelector of h.selectors) {\n      const s = expectObject(rawSelector, 'selector')\n      if (!['mime', 'objType', 'schema', 'ext'].some(k => k in s)) throw invalid('appdoc', 'empty selector')\n      for (const key of ['mime', 'objType', 'schema']) {\n        const v = s[key]\n        if (v !== undefined && !(typeof v === 'string' && v.length) && !(Array.isArray(v) && v.length && v.every(i => typeof i === 'string' && i.length))) throw invalid('appdoc', 'invalid selector field')\n      }\n      if (s.maxSize !== undefined && (!Number.isSafeInteger(s.maxSize) || Number(s.maxSize) < 0)) throw invalid('appdoc', 'invalid maxSize')\n    }\n    const intents = expectObject(h.intents, 'intents')\n    if (Object.keys(intents).length !== 1 || !intents.open) throw invalid('appdoc', 'only open intent is supported')\n    const open = expectObject(intents.open, 'open')\n    const entry = expectObject(open.entry, 'entry')\n    const path = expectNonEmptyString(entry.path, 'entry.path')\n    let decoded: string\n    try { decoded = decodeURIComponent(path) } catch { throw invalid('appdoc', 'invalid entry path') }\n    if (entry.type !== 'web' || !decoded.startsWith('/') || decoded.startsWith('//') || decoded.includes('..') || decoded.includes('\\\\') || decoded.includes('://') || decoded.includes('#') || /[\\r\\n]/.test(decoded)) throw invalid('appdoc', 'unsafe Web entry')\n    if (open.priority !== undefined && (!Number.isSafeInteger(open.priority) || Number(open.priority) < 0 || Number(open.priority) > 80)) throw invalid('appdoc', 'priority must be 0..80')\n    if (open.window !== undefined && open.window !== 'new' && open.window !== 'reuse') throw invalid('appdoc', 'invalid window policy')\n    if (open.multiSource !== undefined && typeof open.multiSource !== 'boolean') throw invalid('appdoc', 'invalid multiSource')\n    if (open.modes !== undefined && (!Array.isArray(open.modes) || !open.modes.length || open.modes.some(m => m !== 'view' && m !== 'edit'))) throw invalid('appdoc', 'invalid modes')\n    if (h.permissions !== undefined && (!Array.isArray(h.permissions) || h.permissions.some(scope => !permissions.some(p => p && typeof p === 'object' && (p as Record<string, unknown>).scope_path === scope)))) throw invalid('appdoc', 'handler permissions exceed App permissions')\n  }\n  return value\n}\n","// The checks of a skill package before it reaches an Agent: a port of `package_skills`, `commands_in_manual` and the\n// content rules of `plan()` in buckyos `src/frame/lib_opendan/src/skills.rs`, with the front matter rules of\n// `protocol/behavior.rs`. The Agent runs the Rust ones again at install; keep the two in step.\nimport { getHost } from '../runtime/host.ts'\nimport { sha256Bytes } from './pikg_archive.ts'\nimport { EXT_TOOLS_RESERVED_COMMANDS } from './pikg_protocol.ts'\n\nexport const SKILL_KINDS = ['work', 'plan', 'goal'] as const\nexport type SkillKind = (typeof SKILL_KINDS)[number]\nexport const SKILL_KIND_DIRS: Record<SkillKind, string> = {\n  work: 'cmd_skills',\n  plan: 'plan_skills',\n  goal: 'goal_skills',\n}\nexport const TOOLS_DIR = 'tools'\nexport const SKILL_DIRS = [...SKILL_KINDS.map((kind) => SKILL_KIND_DIRS[kind]), TOOLS_DIR]\nexport const SKILL_MANUAL = 'SKILL.md'\nexport const SKILL_REFERENCES = 'references'\nexport const SKILL_REVISIONS = 'revisions'\nexport const SKILL_PLATFORMS = ['linux', 'macos', 'windows']\nexport const UI_MANUAL_WARN_BYTES = 16 * 1024\nexport const PLAN_MANUAL_WARN_BYTES = 3 * 1024\nconst MAX_NAME_LEN = 200\n\n/** Commands of the standard layer (Rust: `STANDARD_TOOLS` in buckyos `src/frame/lib_opendan/src/baseline.rs`): a manual\n * does not declare them. */\nexport const STANDARD_COMMANDS: readonly string[] = EXT_TOOLS_RESERVED_COMMANDS\n\nexport interface SkillFinding {\n  code: string\n  /** `error` (not installable) | `high` | `medium` | `low`. */\n  level: string\n  where: string\n  note: string\n}\n\nexport interface SkillPackageFile {\n  bytes: Uint8Array\n}\n\nexport type SkillScope = 'work' | 'ui' | 'ui,work'\n\nexport interface LintedSkill {\n  kind: SkillKind\n  name: string\n  scope: SkillScope\n  description: string\n  requires: string\n  baseline: 'standard' | 'extended'\n  platforms: string[]\n  commands: string[]\n  size: number\n  references: string[]\n}\n\nexport interface SkillLintResult {\n  skills: LintedSkill[]\n  findings: SkillFinding[]\n}\n\n// Words at a command position that are the shell's own or part of every runtime.\nconst SHELL_WORDS = new Set([\n  'if', 'then', 'else', 'elif', 'fi', 'for', 'while', 'until', 'do', 'done', 'case', 'esac', 'in', 'function', 'select', 'time',\n  'cd', 'echo', 'printf', 'export', 'set', 'unset', 'read', 'exit', 'return', 'source', 'eval', 'exec', 'test', 'true', 'false', 'local',\n  'declare', 'trap', 'wait', 'shift', 'alias', 'type', 'command', 'pwd', 'kill', 'umask', 'ulimit', 'break', 'continue', 'let', 'readonly',\n  'ls', 'cat', 'cp', 'mv', 'rm', 'mkdir', 'rmdir', 'touch', 'ln', 'chmod', 'chown', 'head', 'tail', 'grep', 'sed', 'awk', 'sort', 'uniq',\n  'wc', 'cut', 'tr', 'tee', 'find', 'xargs', 'basename', 'dirname', 'date', 'sleep', 'env', 'which', 'diff', 'du', 'df', 'stat', 'mktemp',\n  'sh', 'bash', 'id', 'whoami', 'uname', 'realpath', 'readlink', 'seq', 'yes', 'nohup', 'timeout', 'tar', 'gzip', 'gunzip', 'sha256sum',\n  'base64', 'cmp', 'file', 'ps', 'less', 'more', 'printenv', 'hostname', 'expr', 'od', 'paste', 'comm', 'nl', 'tac', 'rev', 'fold', 'column',\n  'read', 'shell',\n])\nconst SHELL_LANGS = new Set(['', 'sh', 'bash', 'shell', 'zsh', 'console'])\nconst ASSIGNMENT_KEY = /^[A-Za-z0-9_]+$/\nconst PLAIN_WORD = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/\n\nfunction asciiLower(text: string): string {\n  return text.replace(/[A-Z]/g, (c) => c.toLowerCase())\n}\n\n/** The commands the shell code blocks of a manual run: the first word of each command, the shell's own words and\n * placeholders left out. A heuristic for telling the owner what a manual relies on, never a gate. */\nexport function commandsInManual(text: string): Set<string> {\n  const out = new Set<string>()\n  let inBlock = false\n  let shell = false\n  let heredoc: string | undefined\n  let continued = false\n  for (const raw of text.split('\\n')) {\n    let line = raw.trim()\n    if (line.startsWith('```')) {\n      inBlock = !inBlock\n      shell = inBlock && SHELL_LANGS.has(asciiLower(line.slice(3).trim()))\n      heredoc = undefined\n      continued = false\n      continue\n    }\n    if (!inBlock || !shell) continue\n    if (heredoc !== undefined) {\n      if (line === heredoc) heredoc = undefined\n      continue\n    }\n    const wasContinued = continued\n    continued = line.endsWith('\\\\')\n    const at = line.indexOf('<<')\n    if (at >= 0) {\n      const tag = line.slice(at + 2).replace(/^-+/, '').trim().split(/\\s/)[0].replace(/^['\"]+|['\"]+$/g, '')\n      if (tag && /^[A-Za-z0-9_]+$/.test(tag)) heredoc = tag\n    }\n    if (wasContinued || !line || line.startsWith('#')) continue\n    if (line.startsWith('$ ')) line = line.slice(2)\n    let quote: string | undefined\n    const segments = ['']\n    const chars = Array.from(line)\n    for (let i = 0; i < chars.length; i += 1) {\n      const c = chars[i]\n      if (quote !== undefined) {\n        if (c === quote) quote = undefined\n      } else if (c === \"'\" || c === '\"') {\n        quote = c\n      } else if (c === '#' && (i === 0 || /\\s/.test(chars[i - 1]))) {\n        break\n      } else if (\n        // `a|b|c` without spaces is a list of alternatives in a usage line, not a pipe (as in skills.rs).\n        (c === '|' && (chars[i + 1] === undefined || /\\s/.test(chars[i + 1]) || chars[i + 1] === '|' || (i > 0 && /\\s/.test(chars[i - 1])))) ||\n        c === ';' || (c === '&' && chars[i + 1] === '&')\n      ) {\n        if (chars[i + 1] === c) i += 1\n        segments.push('')\n        continue\n      } else if (c === '$' && chars[i + 1] === '(') {\n        segments.push('')\n        i += 1\n        continue\n      }\n      segments[segments.length - 1] += c\n    }\n    for (const segment of segments) {\n      const first = segment.split(/\\s+/).filter(Boolean).find((w) => {\n        const eq = w.indexOf('=')\n        if (eq >= 0 && ASSIGNMENT_KEY.test(w.slice(0, eq))) return false\n        return w !== 'sudo' && w !== '(' && w !== '{' && w !== '!'\n      })\n      if (first === undefined) continue\n      const word = first.replace(/^\\(+/, '')\n      if (PLAIN_WORD.test(word) && /[a-z]/.test(word) && !SHELL_WORDS.has(word)) out.add(word)\n    }\n  }\n  return out\n}\n\n/** A manual split into its front matter (`---` lines around `key: value` lines) and its body; without front matter it\n * is all body. */\nexport function splitFrontMatter(text: string): { fields: Map<string, string>; body: string } {\n  const trimmed = text.replace(/^﻿+/, '')\n  const rest = trimmed.startsWith('---\\n')\n    ? trimmed.slice(4)\n    : trimmed.startsWith('---\\r\\n')\n    ? trimmed.slice(5)\n    : undefined\n  if (rest === undefined) return { fields: new Map(), body: text.trim() }\n  const fields = new Map<string, string>()\n  let offset = 0\n  while (offset < rest.length) {\n    const end = rest.indexOf('\\n', offset)\n    const next = end < 0 ? rest.length : end + 1\n    const line = rest.slice(offset, next).trim()\n    offset = next\n    if (line === '---') return { fields, body: rest.slice(offset).trim() }\n    const colon = line.indexOf(':')\n    if (colon < 0) continue\n    let value = line.slice(colon + 1).trim()\n    for (const q of ['\"', \"'\"]) {\n      if (value.length >= 2 && value.startsWith(q) && value.endsWith(q)) {\n        value = value.slice(1, -1)\n        break\n      }\n    }\n    fields.set(line.slice(0, colon).trim(), value)\n  }\n  // No closing line: not front matter.\n  return { fields: new Map(), body: text.trim() }\n}\n\nfunction skillRequirements(fields: Map<string, string>): { baseline: 'standard' | 'extended'; platforms: string[] } {\n  const raw = (fields.get('baseline') ?? '').trim()\n  if (raw !== '' && raw !== 'standard' && raw !== 'extended') {\n    throw new Error(`baseline \\`${raw}\\` is not standard | extended`)\n  }\n  const platforms: string[] = []\n  for (const part of (fields.get('platforms') ?? '').split(',')) {\n    const p = part.trim()\n    if (!p) continue\n    if (!SKILL_PLATFORMS.includes(p)) throw new Error(`platform \\`${p}\\` is not one of ${SKILL_PLATFORMS.join(', ')}`)\n    if (!platforms.includes(p)) platforms.push(p)\n  }\n  return { baseline: raw === 'extended' ? 'extended' : 'standard', platforms }\n}\n\nfunction skillScope(fields: Map<string, string>): SkillScope {\n  let ui = false\n  let work = false\n  for (const part of (fields.get('scope') ?? '').split(',')) {\n    const word = part.trim()\n    if (word === 'ui') ui = true\n    else if (word === 'work') work = true\n    else if (word) throw new Error(`scope \\`${word}\\` is not ui | work`)\n  }\n  return ui ? (work ? 'ui,work' : 'ui') : 'work'\n}\n\nfunction skillCommandsOf(fields: Map<string, string>): string[] {\n  const commands = (fields.get('commands') ?? '').split(',').map((c) => c.trim())\n    .filter((c) => c && !c.startsWith('.') && /^[A-Za-z0-9._+-]+$/.test(c))\n  return commands.filter((c, index) => index === 0 || commands[index - 1] !== c)\n}\n\nfunction textOf(bytes: Uint8Array): string | undefined {\n  try {\n    return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)\n  } catch {\n    return undefined\n  }\n}\n\nfunction byteLength(text: string): number {\n  return new TextEncoder().encode(text).length\n}\n\n/** Where a package file lands, and the skill it belongs to. */\nfunction place(path: string): { kind: SkillKind; name: string } {\n  const bad = (hint = ''): never => {\n    throw new Error(\n      `\\`${path}\\` is not a skill file: a skill package holds <cmd_skills|plan_skills|goal_skills>/<name>/${SKILL_MANUAL} and their ${SKILL_REFERENCES}/…${hint}`,\n    )\n  }\n  const parts = path.split('/')\n  if (parts.some((p) => p === '' || p === '.' || p === '..')) bad()\n  if (parts[0] === TOOLS_DIR) {\n    throw new Error(\n      `\\`${path}\\`: a skill is text only and brings no command or install script; publish the commands as an extension package and name them in the manual's \\`commands\\``,\n    )\n  }\n  const kind = SKILL_KINDS.find((k) => SKILL_KIND_DIRS[k] === parts[0])\n  if (!kind || parts.length < 2) return bad()\n  if (parts.length === 2) {\n    return bad(parts[1].endsWith('.md') ? ` (a flat ${parts[0]}/<name>.md is no skill: move it to ${parts[0]}/${parts[1].slice(0, -3)}/${SKILL_MANUAL})` : '')\n  }\n  const manual = parts.length === 3 && parts[2] === SKILL_MANUAL\n  const reference = parts.length >= 4 && parts[2] === SKILL_REFERENCES\n  if (!manual && !reference) bad()\n  const name = parts[1]\n  if (name.length > MAX_NAME_LEN || name.startsWith('.') || !/^[A-Za-z0-9_.-]+$/.test(name)) bad()\n  return { kind, name }\n}\n\nfunction packageSkills(packageName: string, files: Map<string, SkillPackageFile>, findings: SkillFinding[]): LintedSkill[] {\n  const paths = [...files.keys()].sort()\n  const grouped = new Map<string, { kind: SkillKind; name: string; paths: string[] }>()\n  for (const path of paths) {\n    const { kind, name } = place(path)\n    const key = `${SKILL_KINDS.indexOf(kind)}:${name}`\n    if (!grouped.has(key)) grouped.set(key, { kind, name, paths: [] })\n    grouped.get(key)!.paths.push(path)\n  }\n  const binary = paths.find((path) => textOf(files.get(path)!.bytes) === undefined)\n  if (binary) throw new Error(`${binary} is not UTF-8 text: a skill is text only`)\n  if (grouped.size === 0) {\n    throw new Error(`package ${packageName} holds no skill (<cmd_skills|plan_skills|goal_skills>/<name>/${SKILL_MANUAL})`)\n  }\n  const out: LintedSkill[] = []\n  const groups = [...grouped.values()].sort((a, b) =>\n    SKILL_KINDS.indexOf(a.kind) - SKILL_KINDS.indexOf(b.kind) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)\n  )\n  for (const { kind, name, paths: own } of groups) {\n    const dir = SKILL_KIND_DIRS[kind]\n    const manual = `${dir}/${name}/${SKILL_MANUAL}`\n    const file = files.get(manual)\n    if (!file) throw new Error(`${dir}/${name}/ has no ${SKILL_MANUAL}`)\n    const text = textOf(file.bytes)\n    if (text === undefined) throw new Error(`${manual} is not UTF-8 text`)\n    const { fields, body } = splitFrontMatter(text)\n    let requirements: ReturnType<typeof skillRequirements>\n    let scope: SkillScope\n    try {\n      requirements = skillRequirements(fields)\n      scope = skillScope(fields)\n      if (kind !== 'work') {\n        for (const key of ['scope', 'commands']) {\n          if ((fields.get(key) ?? '').trim()) {\n            throw new Error(`a ${kind} skill declares no \\`${key}\\`: it names no commands and is read, not frozen`)\n          }\n        }\n      }\n    } catch (error) {\n      throw new Error(`${manual}: ${(error as Error).message}`)\n    }\n    if (fields.has('name') && fields.get('name') !== name) {\n      throw new Error(`${manual}: front matter name \\`${fields.get('name')}\\` differs from its directory`)\n    }\n    const refPrefix = `${dir}/${name}/${SKILL_REFERENCES}/`\n    const skill: LintedSkill = {\n      kind,\n      name,\n      scope: kind === 'work' ? scope : 'work',\n      description: fields.get('description') ?? '',\n      requires: fields.get('requires') ?? '',\n      baseline: requirements.baseline,\n      platforms: requirements.platforms,\n      commands: skillCommandsOf(fields),\n      size: byteLength(body),\n      references: own.filter((p) => p.startsWith(refPrefix)).map((p) => p.slice(refPrefix.length)),\n    }\n    const add = (code: string, level: string, note: string) => findings.push({ code, level, where: manual, note })\n    if (!skill.description.trim()) add('no_description', 'medium', 'no `description`: whoever chooses manuals only sees the name')\n    const texts = [body]\n    for (const path of own) {\n      if (!path.includes(`/${SKILL_REFERENCES}/`) || !path.endsWith('.md')) continue\n      const reference = textOf(files.get(path)!.bytes)\n      if (reference !== undefined) texts.push(reference)\n    }\n    const used = [...new Set(texts.flatMap((t) => [...commandsInManual(t)]))].sort()\n    if (kind === 'work') {\n      if (skill.scope !== 'work' && skill.size > UI_MANUAL_WARN_BYTES) {\n        add('ui_manual_large', 'low', `${skill.size} bytes: every conversation that takes it carries them (advised: at most ${UI_MANUAL_WARN_BYTES})`)\n      }\n      const undeclared = used.filter((c) => !skill.commands.includes(c) && !STANDARD_COMMANDS.includes(c))\n      if (undeclared.length) add('undeclared_commands', 'low', `the manual runs ${undeclared.join(', ')} without naming them in \\`commands\\``)\n      const lower = texts.map((t) => t.toLowerCase())\n      const unused = skill.commands.filter((c) => !lower.some((t) => t.includes(c.toLowerCase())))\n      if (unused.length) add('unused_commands', 'low', `\\`commands\\` names ${unused.join(', ')} but the manual never mentions them`)\n    } else if (kind === 'plan') {\n      if (skill.size > PLAN_MANUAL_WARN_BYTES) {\n        add('plan_manual_large', 'low', `${skill.size} bytes (advised: at most ${PLAN_MANUAL_WARN_BYTES}): a plan reads it whole`)\n      }\n      const hard = texts.some((t) =>\n        t.includes('create-worksession') || t.includes('--cmd-skill') ||\n        t.split('\\n').some((l) => l.includes('--skill ') && !l.includes('--skill <'))\n      )\n      if (hard || used.length) {\n        add(\n          'plan_depends_on_commands',\n          'medium',\n          'a plan skill says how to split, order and check work, not which commands or manuals to use: move commands into a work skill and write \"give this step a manual for X\"',\n        )\n      }\n    }\n    out.push(skill)\n  }\n  return out\n}\n\nconst PACKAGE_MANAGERS = [\n  'apt-get ', 'apt install', 'brew install', 'npm install -g', 'npm i -g', 'pip install', 'pip3 install', 'winget install',\n  'choco install', 'dnf install', 'yum install', 'apk add',\n]\nconst SECRET_WORDS = ['TOKEN', 'SECRET', 'PASSWORD', 'API_KEY', 'APIKEY', 'PRIVATE_KEY']\n\n/** What `skills.install_plan` tells the owner about the content of a package (Rust: `plan()`), as far as it can be told\n * without the Agent: nothing about what it replaces. */\nfunction riskFindings(skills: LintedSkill[], files: Map<string, SkillPackageFile>, findings: SkillFinding[]): void {\n  const paths = [...files.keys()].sort()\n  for (const skill of skills) {\n    const dir = SKILL_KIND_DIRS[skill.kind]\n    const key = `${skill.kind}:${skill.name}`\n    if (skill.scope !== 'work') {\n      findings.push({ code: 'ui_scope', level: 'medium', where: key, note: 'its scope includes `ui`: once the owner adds it to the UI set it goes into the prompt of every conversation' })\n    }\n    for (const path of paths) {\n      if (!path.startsWith(`${dir}/${skill.name}/`)) continue\n      const text = textOf(files.get(path)!.bytes)\n      if (text === undefined) continue\n      const lower = asciiLower(text)\n      const piped = lower.split('\\n').some((l) =>\n        (l.includes('curl ') || l.includes('wget ')) && (l.includes('| sh') || l.includes('|sh') || l.includes('| bash') || l.includes('|bash'))\n      )\n      if (piped) {\n        findings.push({ code: 'network_script', level: 'high', where: path, note: 'tells the agent to download a script and run it (`curl … | sh`)' })\n      }\n      const managers = PACKAGE_MANAGERS.filter((m) => lower.includes(m))\n      if (managers.length) {\n        findings.push({ code: 'package_manager', level: 'medium', where: path, note: `uses a package manager (${managers.join(', ').replaceAll('  ', ' ')})` })\n      }\n      if (lower.split('\\n').some((l) => l.split(/\\s+/).includes('sudo'))) {\n        findings.push({ code: 'privilege', level: 'high', where: path, note: 'asks for root (`sudo`)' })\n      }\n      const secrets = [...new Set(\n        text.split(/[^A-Za-z0-9_]/).filter((w) => w.length > 5 && /^[A-Z0-9_]+$/.test(w) && SECRET_WORDS.some((s) => w.includes(s))),\n      )].sort()\n      if (secrets.length) {\n        findings.push({ code: 'secrets', level: 'medium', where: path, note: `reads secrets from the environment (${secrets.join(', ')})` })\n      }\n    }\n  }\n}\n\n/** The content digest of a package (Rust: `content_digest`): `sha256:<hex>` over the lines `<path>|<sha256 of the file>`\n * in path order. The Agent reports the same value as `digest` of the install plan and of the installed package. */\nexport function skillContentDigest(files: Map<string, SkillPackageFile>): string {\n  const lines = [...files.keys()].sort().map((path) => `${path}|${sha256Bytes(files.get(path)!.bytes)}\\n`)\n  return `sha256:${sha256Bytes(new TextEncoder().encode(lines.join('')))}`\n}\n\n/** Check a skill package without an Agent (`pikg doctor`, a directory given to `skill install`). A package that cannot\n * be installed gets one `invalid_package` finding of level `error`, first; the rest is advice. */\nexport function lintSkillPackage(packageName: string, files: Map<string, SkillPackageFile>): SkillLintResult {\n  const findings: SkillFinding[] = []\n  try {\n    const skills = packageSkills(packageName, files, findings)\n    riskFindings(skills, files, findings)\n    return { skills, findings }\n  } catch (error) {\n    findings.unshift({ code: 'invalid_package', level: 'error', where: packageName, note: (error as Error).message })\n    return { skills: [], findings }\n  }\n}\n\n/** A directory laid out like the `agent_skills` sub package, read as `pikg build` archives it: the skill directories\n * only (`revisions/` of a manual left out; a `tools/` is read so that the package is refused for it), links followed\n * while they stay inside. */\nexport async function readSkillDirectory(\n  root: string,\n  limit: number,\n): Promise<{ files: Map<string, SkillPackageFile>; ignored: string[] }> {\n  const host = getHost()\n  const realRoot = await host.realPath(root)\n  const files = new Map<string, SkillPackageFile>()\n  const ignored: string[] = []\n  let total = 0\n  const walk = async (directory: string, prefix: string): Promise<void> => {\n    const children = (await host.readDir(directory)).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n    for (const child of children) {\n      const rel = prefix ? `${prefix}/${child.name}` : child.name\n      const parts = rel.split('/')\n      if (parts.length > 32) throw new Error(`${rel}: nested too deep`)\n      if (!prefix && !SKILL_DIRS.includes(child.name)) {\n        ignored.push(rel)\n        continue\n      }\n      if (parts[0] !== TOOLS_DIR && parts.length === 3 && parts[2] === SKILL_REVISIONS) continue\n      let path = host.path.join(directory, child.name)\n      if ((await host.lstat(path)).isSymlink) {\n        path = await host.realPath(path)\n        const inside = host.path.relative(realRoot, path)\n        if (inside === '..' || inside.startsWith(`..${host.path.sep}`) || host.path.isAbsolute(inside)) {\n          throw new Error(`${rel}: a link out of the skill directory`)\n        }\n      }\n      const info = await host.stat(path)\n      if (info.isDirectory) {\n        await walk(path, rel)\n      } else if (info.isFile) {\n        total += info.size\n        if (total > limit) throw new Error(`the skill directory holds more than ${limit} bytes`)\n        files.set(rel, { bytes: await host.readFile(path) })\n      } else {\n        throw new Error(`${rel}: not a regular file`)\n      }\n    }\n  }\n  await walk(realRoot, '')\n  return { files, ignored }\n}\n","// Generated by scripts/generate-cli-version.mjs. Do not edit.\nexport const PACKAGE_VERSION = '0.7.200'\nexport const TOOL_VERSION = PACKAGE_VERSION\nexport const SDK_VERSION = PACKAGE_VERSION\nexport const PROTOCOL_VERSION = '1'\n","import type { CommandContext } from '../core/context.ts'\nimport type { CommandModule } from '../core/command.ts'\nimport { EXIT_PERMISSION, EXIT_UNAVAILABLE, ToolError, UsageError } from '../core/errors.ts'\nimport {\n  AIWS_MANIFEST_FILE,\n  AIWS_MANIFEST_VERSION,\n  aiwsContentDigest,\n  controlSkeleton,\n} from 'buckyos/node'\nimport { createDeterministicTarGz, digestFile, readTarGz, sha256Bytes } from './pikg_archive.ts'\nimport {\n  lintSkillPackage,\n  readSkillDirectory,\n  SKILL_DIRS,\n  skillContentDigest,\n  type SkillPackageFile,\n} from './skill_lint.ts'\nimport {\n  APPDOC_ENTRY,\n  appDocObjectId,\n  assertSelectorCompatible,\n  canonicalSelector,\n  createPackageMeta,\n  deriveAppNamespace,\n  derivedSelector,\n  DIST_MANIFEST_NAME,\n  expectNonEmptyString,\n  expectObject,\n  EXT_TOOLS_MANIFEST_FILE,\n  EXT_TOOLS_MANIFEST_SCHEMA,\n  EXT_TOOLS_PLATFORMS,\n  type ExtToolsManifest,\n  extToolsManifestErrors,\n  extToolsPayloadErrors,\n  type ExtToolsPayloadTree,\n  extToolsPlatformOfKey,\n  inspectPikg,\n  normalizeArch,\n  PACKAGE_META_ENTRY,\n  PACKAGE_META_SCHEMA,\n  type PackageMetaFile,\n  packSnapshot,\n  parsePackageMeta,\n  rejectUnknown,\n  stableJsonDigest,\n  validateAppPresentation,\n  validateContentHandlers,\n  validatePermissions,\n  validateServiceConfigTips,\n  validateSnapshot,\n  validateSubpackageName,\n} from './pikg_protocol.ts'\nimport {\n  distributionManifestView,\n  getHost,\n  type HostFileInfo,\n  isHostError,\n  policyView,\n  readDistributionManifest,\n} from '../runtime/host.ts'\nimport { PROTOCOL_VERSION, SDK_VERSION, TOOL_VERSION } from '../version.ts'\nimport { identityCandidateView } from '../core/identity.ts'\n\nconst basename = (path: string) => getHost().path.basename(path)\nconst dirname = (path: string) => getHost().path.dirname(path)\nconst isAbsolute = (path: string) => getHost().path.isAbsolute(path)\nconst join = (...parts: string[]) => getHost().path.join(...parts)\nconst relative = (from: string, to: string) => getHost().path.relative(from, to)\nconst resolve = (...parts: string[]) => getHost().path.resolve(...parts)\n\nconst APP_DOCUMENT_LIFETIME_SECONDS = 5 * 365 * 24 * 60 * 60\nconst SAFE_PIKG_FILE = /^[A-Za-z0-9._-]+\\.pikg$/\nconst APP_NAME = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/\nconst VERSION = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/\nconst SHA256_ID = /^sha256:[0-9a-f]{64}$/\nconst OBJECT_ID = /^(?:appdoc|pkg):[0-9a-f]{64}$/\nconst SAFE_GENERATED_FILE = /^[A-Za-z0-9._-]+$/\nconst OBJECT_OUTPUT = { type: 'object' as const, additionalProperties: true }\nconst APP_KINDS = ['static-web', 'script', 'docker', 'agent-skills', 'aiws-controls', 'ext-tools']\nconst PATH_KINDS: Record<string, { key: string; category: string; selectorType: string }> = {\n  'static-web': { key: 'web', category: 'web', selectorType: 'static' },\n  script: { key: 'script', category: 'dapp', selectorType: 'single' },\n  'agent-skills': { key: 'agent_skills', category: 'agent_skills', selectorType: 'single' },\n  // AI Workspace controls: one bundle (aiws-manifest.json + controls/<dir>/), installed into the AI Workspace library\n  'aiws-controls': { key: 'aiws', category: 'aiws', selectorType: 'single' },\n  // Extension tools: ext-manifest.json + payload/<platform>/, one sub package per platform, enabled for the Zone\n  'ext-tools': { key: 'ext_tools', category: 'ext_tools', selectorType: 'single' },\n}\nconst EXT_TOOLS_LAUNCHER_LIMIT = 1024 * 1024\n\nexport interface DockerImageInfo {\n  id: string\n  architecture: string\n  canonicalName: string\n}\n\nexport interface DockerClient {\n  inspect(reference: string): Promise<DockerImageInfo>\n  save(imageId: string, destinationTarGz: string): Promise<void>\n}\n\nexport interface PikgModuleDependencies {\n  docker?: DockerClient\n  now?: () => number\n}\n\ninterface AppMeta {\n  schema_version: 1\n  did: string\n  name: string\n  version: string\n  owner: string\n  author: string\n  show_name: string\n  presentation?: Record<string, unknown>\n  categories: string[]\n  permissions: unknown[]\n  content_handlers?: unknown[]\n  selector_type: string\n  service_config_tips: Record<string, unknown>\n}\n\ninterface PathSource {\n  type: 'path'\n  path: string\n}\n\ninterface DockerSource {\n  type: 'docker-image'\n  image: string\n}\n\ninterface SubpackageInput {\n  selector?: Record<string, string>\n  required: boolean\n  source: PathSource | DockerSource\n}\n\ninterface PikgMeta {\n  schema_version: 1\n  output_dir: string\n  pikg_file: string\n  sub_pkgs: Record<string, SubpackageInput>\n}\n\ninterface GeneratedFileRecord {\n  size: number\n  digest: string\n}\n\ninterface DistManifest {\n  schema_version: 1\n  tool_version: string\n  meta_root_id: string\n  source_fingerprint: string\n  app_doc_object_id: string\n  pikg_file: string\n  generated_files: Record<string, GeneratedFileRecord>\n  subpackages: Record<\n    string,\n    { source_kind: string; size: number; digest: string; pkg_objid: string }\n  >\n}\n\ninterface PreparedSubpackage {\n  key: string\n  input: SubpackageInput\n  payloadPath: string\n  digest: GeneratedFileRecord\n  docker?: DockerImageInfo\n}\n\nfunction packageEnvironmentQualifier(\n  key: string,\n  selector: Record<string, string> | undefined,\n): string {\n  const effective = selector ?? derivedSelector(key)\n  const os = effective?.os\n  const arch = effective?.arch\n  if (!os || !arch) return 'all'\n  const environmentOs = os === 'macos' ? 'apple' : os\n  const environmentArch = arch === 'x86_64' ? 'amd64' : arch\n  const qualifier = `nightly-${environmentOs}-${environmentArch}`\n  return new Set([\n      'nightly-linux-amd64',\n      'nightly-linux-aarch64',\n      'nightly-windows-amd64',\n      'nightly-windows-aarch64',\n      'nightly-apple-amd64',\n      'nightly-apple-aarch64',\n    ]).has(qualifier)\n    ? qualifier\n    : 'all'\n}\n\nexport function createPikgModule(dependencies: PikgModuleDependencies = {}): CommandModule {\n  const docker = dependencies.docker ?? new LocalDockerClient()\n  const now = dependencies.now ?? reproducibleBuildTimestamp\n  return {\n    name: 'pikg',\n    summary: 'Build and verify local PIKG release candidates',\n    commands: [\n      {\n        verb: 'doctor',\n        summary: 'Inspect the local SDK, Tool, host policy, metadata, and target profile',\n        positionals: [\n          { name: 'meta_dir', description: 'dapp_meta directory', required: false },\n        ],\n        options: [\n          {\n            name: 'catalog',\n            description:\n              'ext-tools: a directory of other packages (<id>/ext-manifest.json) to check requires and same-named commands against',\n            type: 'string',\n          },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: {\n            meta_dir: { type: 'string', minLength: 1 },\n            catalog: { type: 'string', minLength: 1 },\n          },\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        execution: 'local',\n        networkAccess: false,\n        examples: [\n          'buckyos pikg doctor',\n          'buckyos pikg doctor ./dapp_meta',\n          'buckyos pikg doctor ./dapp_meta --catalog ../publish/exttool',\n        ],\n        handler: async (ctx, input) => await doctorCommand(ctx, input),\n      },\n      {\n        verb: 'init',\n        summary: 'Create local PIKG development metadata',\n        description: 'Creates only dapp_meta/app.json and dapp_meta/pikg.json.',\n        positionals: [\n          { name: 'project_dir', description: 'Existing App project directory', required: false },\n        ],\n        options: [\n          { name: 'name', description: 'App name', type: 'string' },\n          { name: 'owner', description: 'Owner DID', type: 'string' },\n          {\n            name: 'kind',\n            description: 'Initial App kind',\n            type: 'string',\n            enum: APP_KINDS,\n          },\n          {\n            name: 'source',\n            description: 'Build output path or local Docker image',\n            type: 'string',\n          },\n          { name: 'version', description: 'Initial App version', type: 'string' },\n          { name: 'app-did', property: 'app_did', description: 'Explicit App DID', type: 'string' },\n          {\n            name: 'composite',\n            description:\n              'aiws-controls: start the package with a composite control (a panel of Blocks) instead of a declarative one',\n            type: 'boolean',\n          },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: {\n            project_dir: { type: 'string', minLength: 1 },\n            name: { type: 'string', minLength: 1 },\n            owner: { type: 'string', minLength: 1 },\n            kind: { type: 'string', enum: APP_KINDS },\n            source: { type: 'string', minLength: 1 },\n            version: { type: 'string', minLength: 1 },\n            app_did: { type: 'string', minLength: 1 },\n            composite: { type: 'boolean' },\n          },\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'write' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        execution: 'local',\n        networkAccess: false,\n        examples: [\n          'buckyos pikg init .',\n          'buckyos --non-interactive pikg init . --owner did:bns:root --kind static-web --source ./web/dist',\n          'buckyos --non-interactive pikg init . --owner did:bns:root --kind agent-skills --source ./skills',\n          'buckyos --non-interactive pikg init . --owner did:bns:alice --kind aiws-controls --source ./aiws',\n          'buckyos --non-interactive pikg init . --owner did:bns:alice --kind aiws-controls --source ./aiws --composite',\n          'buckyos --non-interactive pikg init . --name ext-media --owner did:bns:root --kind ext-tools --source ./ext-media',\n        ],\n        handler: async (ctx, input) => await initCommand(ctx, input, docker),\n      },\n      {\n        verb: 'build',\n        summary: 'Build a managed dapp_dist snapshot',\n        positionals: [\n          { name: 'meta_dir', description: 'dapp_meta directory', required: false },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: { meta_dir: { type: 'string', minLength: 1 } },\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'write' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        execution: 'local',\n        networkAccess: false,\n        examples: ['buckyos pikg build ./dapp_meta'],\n        handler: async (ctx, input) => await buildCommand(ctx, input, docker, now),\n      },\n      {\n        verb: 'pack',\n        summary: 'Pack and verify a complete PIKG',\n        positionals: [\n          { name: 'dist_dir', description: 'Managed dapp_dist directory', required: false },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: { dist_dir: { type: 'string', minLength: 1 } },\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'write' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        execution: 'local',\n        networkAccess: false,\n        examples: ['buckyos pikg pack ./dapp_dist'],\n        handler: async (ctx, input) => await packCommand(ctx, input),\n      },\n      {\n        verb: 'info',\n        summary: 'Strictly verify and inspect a local PIKG',\n        positionals: [{ name: 'pikg_path', description: 'Local .pikg file' }],\n        inputSchema: {\n          type: 'object',\n          properties: { pikg_path: { type: 'string', minLength: 1 } },\n          required: ['pikg_path'],\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        execution: 'local',\n        networkAccess: false,\n        examples: ['buckyos pikg info ./dapp_dist/demo-0.1.0.pikg'],\n        handler: async (ctx, input) =>\n          await inspectPikg(resolveFromCwd(ctx, expectInputString(input, 'pikg_path'))),\n      },\n      {\n        verb: 'clean',\n        summary: 'Safely delete a managed dapp_dist',\n        positionals: [\n          { name: 'meta_dir', description: 'dapp_meta directory', required: false },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: { meta_dir: { type: 'string', minLength: 1 } },\n          additionalProperties: false,\n        },\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'destructive' },\n        asyncMode: 'sync',\n        requiresSession: false,\n        execution: 'local',\n        networkAccess: false,\n        examples: ['buckyos --non-interactive --yes pikg clean ./dapp_meta'],\n        handler: async (ctx, input) => await cleanCommand(ctx, input),\n      },\n    ],\n  }\n}\n\nfunction reproducibleBuildTimestamp(): number {\n  const configured = getHost().env('SOURCE_DATE_EPOCH')\n  if (configured === undefined) return Math.floor(Date.now() / 1000)\n  if (!/^\\d+$/.test(configured)) {\n    throw new UsageError(\n      'INVALID_SOURCE_DATE_EPOCH',\n      'SOURCE_DATE_EPOCH must be a non-negative integer number of seconds',\n    )\n  }\n  const seconds = Number(configured)\n  if (!Number.isSafeInteger(seconds)) {\n    throw new UsageError(\n      'INVALID_SOURCE_DATE_EPOCH',\n      'SOURCE_DATE_EPOCH is outside the supported integer range',\n    )\n  }\n  return seconds\n}\n\nasync function doctorCommand(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n  const metaInput = optionalInputString(input, 'meta_dir') ?? './dapp_meta'\n  const metaDir = resolveFromCwd(ctx, metaInput)\n  const checks: Array<Record<string, unknown>> = []\n  let appMeta: Record<string, unknown> | undefined\n  let pikgMeta: Record<string, unknown> | undefined\n  for (\n    const [name, path] of [\n      ['app_metadata', join(metaDir, 'app.json')],\n      ['pikg_metadata', join(metaDir, 'pikg.json')],\n    ] as const\n  ) {\n    try {\n      const value = await readJson(path, name)\n      if (name === 'app_metadata') appMeta = value\n      else pikgMeta = value\n      checks.push({ name, status: 'ok', path })\n    } catch (error) {\n      checks.push({\n        name,\n        status: isHostError(error, 'NotFound') ? 'missing' : 'error',\n        path,\n        detail: error instanceof Error ? error.message : String(error),\n      })\n    }\n  }\n  if (appMeta && pikgMeta) {\n    try {\n      const app = parseAppMeta(appMeta)\n      const pikg = parsePikgMeta(pikgMeta, app)\n      const missingSources: string[] = []\n      for (const subpackage of Object.values(pikg.sub_pkgs)) {\n        if (subpackage.source.type !== 'path') continue\n        const source = resolve(metaDir, subpackage.source.path)\n        try {\n          await getHost().lstat(source)\n        } catch (error) {\n          if (isHostError(error, 'NotFound')) missingSources.push(source)\n          else throw error\n        }\n      }\n      checks.push({\n        name: 'build_outputs',\n        status: missingSources.length === 0 ? 'ok' : 'missing',\n        missing: missingSources,\n      })\n      const skills = pikg.sub_pkgs[PATH_KINDS['agent-skills'].key]\n      if (\n        skills?.source.type === 'path' &&\n        !missingSources.includes(resolve(metaDir, skills.source.path))\n      ) {\n        checks.push(await skillLintCheck(app.name, resolve(metaDir, skills.source.path)))\n      }\n      if (app.categories[0] === PATH_KINDS['ext-tools'].category) {\n        const catalog = optionalInputString(input, 'catalog')\n        checks.push(\n          ...await extToolsChecks(\n            app,\n            pikg,\n            metaDir,\n            catalog ? resolveFromCwd(ctx, catalog) : undefined,\n          ),\n        )\n      }\n    } catch (error) {\n      checks.push({\n        name: 'metadata_schema',\n        status: 'error',\n        detail: error instanceof Error ? error.message : String(error),\n      })\n    }\n  }\n  const globalConfig = await ctx.configStore.readConfig()\n  const profileName = ctx.config.profileName ?? globalConfig.default_profile\n  const profile = profileName ? await ctx.configStore.readProfile(profileName) : undefined\n  const host = getHost()\n  return {\n    healthy: checks.every((check) => check.status === 'ok' || check.status === 'skipped'),\n    tool_version: TOOL_VERSION,\n    sdk_version: SDK_VERSION,\n    protocol_version: PROTOCOL_VERSION,\n    ...policyView(host),\n    distribution_manifest: distributionManifestView(await readDistributionManifest(host)),\n    target: {\n      profile: profileName ?? null,\n      zone: ctx.config.zone ?? profile?.zone ?? null,\n      endpoint: ctx.config.endpoint ?? profile?.endpoint ?? null,\n      compatibility: 'not-checked',\n    },\n    identity_candidates: await identityCandidateView(ctx.config),\n    checks,\n  }\n}\n\nasync function initCommand(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  docker: DockerClient,\n): Promise<Record<string, unknown>> {\n  const projectInput = optionalInputString(input, 'project_dir') ?? '.'\n  const projectDir = await realDirectory(resolveFromCwd(ctx, projectInput), 'project directory')\n  let name = optionalInputString(input, 'name') ?? normalizeAppName(basename(projectDir))\n  const canPrompt = !ctx.config.nonInteractive && !ctx.interactive && ctx.io.inputIsTerminal\n  if (!name) name = await requiredPrompt(ctx, canPrompt, 'App name: ', 'name')\n  let owner = optionalInputString(input, 'owner')\n  if (!owner) owner = await requiredPrompt(ctx, canPrompt, 'Owner DID: ', 'owner')\n  let kind = optionalInputString(input, 'kind')\n  if (!kind) {\n    kind = await requiredPrompt(\n      ctx,\n      canPrompt,\n      `App kind (${APP_KINDS.join('/')}): `,\n      'kind',\n    )\n  }\n  if (!APP_KINDS.includes(kind)) {\n    throw new UsageError('INVALID_APP_KIND', `invalid App kind: ${kind}`)\n  }\n  let source = optionalInputString(input, 'source')\n  if (!source) source = await requiredPrompt(ctx, canPrompt, 'Source: ', 'source')\n  const version = optionalInputString(input, 'version') ?? '0.1.0'\n  validateAppName(name)\n  validateVersion(version)\n  const derivedDid = deriveAppDid(name, owner)\n  const appDid = optionalInputString(input, 'app_did') ?? derivedDid\n  deriveAppNamespace(appDid)\n\n  let subpackageKey: string\n  let sourceValue: Record<string, string>\n  let selector: Record<string, string> | undefined\n  let sourceSummary: Record<string, unknown>\n  if (kind === 'ext-tools') {\n    const platform = hostExtToolsPlatform()\n    const absoluteSource = resolve(projectDir, source)\n    subpackageKey = platform.key\n    selector = platform.selector\n    sourceValue = {\n      type: 'path',\n      path: toPortablePath(\n        relative(join(projectDir, 'dapp_meta'), join(absoluteSource, 'payload', platform.name)),\n      ),\n    }\n    sourceSummary = {\n      type: 'path',\n      path: displaySource(projectDir, absoluteSource),\n      platform: platform.name,\n    }\n    try {\n      await getHost().lstat(join(absoluteSource, EXT_TOOLS_MANIFEST_FILE))\n    } catch (error) {\n      if (!isHostError(error, 'NotFound')) throw error\n      await writeExtToolsSkeleton(absoluteSource, name, version, platform.name)\n      sourceSummary.skeleton = true\n    }\n  } else if (kind === 'docker') {\n    const image = await docker.inspect(source)\n    const arch = normalizeArch(image.architecture)\n    subpackageKey = arch === 'x86_64'\n      ? 'amd64_docker_image'\n      : arch === 'aarch64'\n      ? 'aarch64_docker_image'\n      : (() => {\n        throw new UsageError('UNSUPPORTED_ARCHITECTURE', `unsupported Docker architecture: ${arch}`)\n      })()\n    selector = { os: 'linux', arch }\n    sourceValue = { type: 'docker-image', image: source }\n    sourceSummary = { type: 'docker-image', image: image.canonicalName, image_id: image.id }\n  } else {\n    subpackageKey = PATH_KINDS[kind].key\n    const absoluteSource = resolve(projectDir, source)\n    const persistedSource = isAbsolute(source)\n      ? resolve(source)\n      : toPortablePath(relative(join(projectDir, 'dapp_meta'), absoluteSource))\n    sourceValue = { type: 'path', path: persistedSource }\n    sourceSummary = { type: 'path', path: displaySource(projectDir, absoluteSource) }\n    try {\n      await getHost().lstat(absoluteSource)\n    } catch (error) {\n      if (!isHostError(error, 'NotFound')) throw error\n      if (kind === 'aiws-controls') {\n        await writeAiwsSkeleton(absoluteSource, owner, name, input.composite === true)\n        sourceSummary.skeleton = true\n      } else if (kind === 'agent-skills') {\n        await writeSkillsSkeleton(absoluteSource, name)\n        sourceSummary.skeleton = true\n      } else {\n        await ctx.io.stderr(`warning: source does not exist yet: ${sourceSummary.path}\\n`)\n      }\n    }\n  }\n\n  const appMeta: AppMeta = {\n    schema_version: 1,\n    did: appDid,\n    name,\n    version,\n    owner,\n    author: owner,\n    show_name: name,\n    categories: [PATH_KINDS[kind]?.category ?? 'dapp'],\n    permissions: [],\n    selector_type: PATH_KINDS[kind]?.selectorType ?? 'single',\n    service_config_tips: {},\n  }\n  const pikgMeta = {\n    schema_version: 1,\n    output_dir: '../dapp_dist',\n    pikg_file: `${name}-${version}.pikg`,\n    sub_pkgs: {\n      [subpackageKey]: {\n        ...(selector ? { selector } : {}),\n        required: true,\n        source: sourceValue,\n      },\n    },\n  }\n  parseAppMeta({ ...appMeta })\n  parsePikgMeta(pikgMeta)\n  const metaDir = join(projectDir, 'dapp_meta')\n  await initializeMetaDirectory(projectDir, metaDir, appMeta, pikgMeta)\n  return {\n    project_dir: projectDir,\n    meta_dir: metaDir,\n    generated_files: [join(metaDir, 'app.json'), join(metaDir, 'pikg.json')],\n    app: {\n      did: appDid,\n      name,\n      version,\n      owner,\n      author: owner,\n      show_name: name,\n      categories: appMeta.categories,\n      permissions: [],\n      selector_type: appMeta.selector_type,\n      service_config_tips: {},\n    },\n    subpackage: {\n      key: subpackageKey,\n      kind,\n      source: sourceSummary,\n      required: true,\n      ...(selector ? { selector } : {}),\n    },\n    output_dir: join(projectDir, 'dapp_dist'),\n    pikg_file: pikgMeta.pikg_file,\n    next_command: `buckyos pikg build ${metaDir}`,\n  }\n}\n\nconst MAX_SKILL_SOURCE_BYTES = 64 * 1024 * 1024\n\n/** `pikg doctor` of an `agent_skills` source (a directory or a `.tar.gz`): the checks the Agent makes when the package is\n * installed. What makes it uninstallable fails the check; the rest are warnings. */\nasync function skillLintCheck(\n  packageName: string,\n  source: string,\n): Promise<Record<string, unknown>> {\n  const check = { name: 'skill_lint', path: source }\n  let files: Map<string, SkillPackageFile>\n  let ignored: string[] = []\n  try {\n    if ((await getHost().stat(source)).isDirectory) {\n      ;({ files, ignored } = await readSkillDirectory(source, MAX_SKILL_SOURCE_BYTES))\n    } else {\n      files = new Map()\n      for (\n        const entry of await readTarGz(await getHost().readFile(source), MAX_SKILL_SOURCE_BYTES)\n      ) {\n        if (SKILL_DIRS.includes(entry.path.split('/')[0])) {\n          files.set(entry.path, { bytes: entry.bytes })\n        } else ignored.push(entry.path)\n      }\n    }\n  } catch (error) {\n    return {\n      ...check,\n      status: 'error',\n      detail: error instanceof Error ? error.message : String(error),\n    }\n  }\n  const { skills, findings } = lintSkillPackage(packageName, files)\n  const errors = findings.filter((finding) => finding.level === 'error')\n  return {\n    ...check,\n    status: errors.length ? 'error' : 'ok',\n    ...(errors.length ? { detail: errors.map((finding) => finding.note).join('; '), errors } : {}),\n    ...(errors.length ? {} : { digest: skillContentDigest(files) }),\n    skills: skills.map(({ kind, name, scope, size, commands }) => ({\n      kind,\n      name,\n      scope,\n      size,\n      commands,\n    })),\n    warnings: findings.filter((finding) => finding.level !== 'error'),\n    ...(ignored.length ? { ignored_files: ignored } : {}),\n  }\n}\n\n/** A skill package skeleton: one work skill in the directory layout. */\nasync function writeSkillsSkeleton(dir: string, name: string): Promise<void> {\n  const skill = name.replaceAll('-', '_')\n  const manual = join(dir, 'cmd_skills', skill)\n  await getHost().mkdir(manual, { recursive: true })\n  await getHost().writeTextFile(\n    join(manual, 'SKILL.md'),\n    [\n      '---',\n      `name: ${skill}`,\n      'description: One line: what this manual is for, so whoever picks manuals can choose it',\n      'requires: What it needs beyond the commands below, in words',\n      'scope: work',\n      '---',\n      `# ${skill}`,\n      '',\n      'What to do, step by step. Commands this manual runs that are not part of every runtime go into a front matter line',\n      '`commands: name, name`; long material goes into `references/` next to this file and is read on demand.',\n      '',\n      'A package holds `cmd_skills/<name>/SKILL.md` (work and ui skills), `plan_skills/<name>/SKILL.md` and',\n      '`goal_skills/<name>/SKILL.md`, each with an optional `references/`. A skill is text only: it brings no command and no',\n      'install script. Commands come from the standard layer or from extension packages (`buckyos ext-tools`).',\n      '',\n    ].join('\\n'),\n  )\n}\n\n/** A control package skeleton: one declarative control (or a composite one) under controls/<name>/ and its manifest\n * (digest included). */\nasync function writeAiwsSkeleton(\n  dir: string,\n  ownerDid: string,\n  name: string,\n  composite: boolean,\n): Promise<void> {\n  const kind = composite ? 'composite' : 'declarative'\n  const files = controlSkeleton({ authorDid: ownerDid, name, title: name, kind })\n  const encoder = new TextEncoder()\n  const host = getHost()\n  await host.mkdir(join(dir, 'controls', name), { recursive: true })\n  for (const [file, text] of Object.entries(files)) {\n    await host.writeTextFile(join(dir, 'controls', name, file), text)\n  }\n  const digest = await aiwsContentDigest(\n    Object.entries(files).map(([file, text]) =>\n      [file, encoder.encode(text)] as [string, Uint8Array]\n    ),\n  )\n  const manifest = {\n    manifest_version: AIWS_MANIFEST_VERSION,\n    purpose: 'aiws',\n    host_api: composite ? {} : { declarative: 1 },\n    controls: [{\n      ident: `${ownerDid}#${name}`,\n      name,\n      kind,\n      version: 1,\n      digest,\n      dir: `controls/${name}/`,\n      title: name,\n    }],\n    workspace_templates: [],\n  }\n  await host.writeTextFile(join(dir, AIWS_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`)\n}\n\nfunction hostExtToolsPlatform(): (typeof EXT_TOOLS_PLATFORMS)[number] {\n  const host = getHost()\n  const os = host.platform === 'darwin'\n    ? 'macos'\n    : host.platform === 'win32'\n    ? 'windows'\n    : host.platform\n  const arch = normalizeArch(host.arch)\n  const platform = EXT_TOOLS_PLATFORMS.find((known) =>\n    known.selector.os === os && known.selector.arch === arch\n  )\n  if (!platform) {\n    throw new UsageError(\n      'UNSUPPORTED_PLATFORM',\n      `extension packages have no payload for ${os}/${arch}`,\n    )\n  }\n  return platform\n}\n\n/** An extension package skeleton for this machine's platform: `ext-manifest.json` and one command that runs and has a\n * smoke script, so the package builds from the first minute. Other platforms are added beside it. */\nasync function writeExtToolsSkeleton(\n  dir: string,\n  id: string,\n  version: string,\n  platform: string,\n): Promise<void> {\n  const host = getHost()\n  const manifest = {\n    schema: EXT_TOOLS_MANIFEST_SCHEMA,\n    id,\n    version,\n    requires: [],\n    conflicts: [],\n    provides: [{ command: id, version_probe: `${id} --version`, smoke: `smoke/${id}.sh` }],\n    platforms: [platform],\n    license: '',\n    desc: '',\n  }\n  const text = `${JSON.stringify(manifest, null, 2)}\\n`\n  const payload = join(dir, 'payload', platform)\n  for (const sub of ['bin', 'smoke', join('store', id)]) {\n    await host.mkdir(join(payload, sub), { recursive: true })\n  }\n  await host.writeTextFile(join(dir, EXT_TOOLS_MANIFEST_FILE), text)\n  await host.writeTextFile(join(payload, EXT_TOOLS_MANIFEST_FILE), text)\n  const windows = platform.startsWith('windows-')\n  await host.writeTextFile(\n    join(payload, 'bin', windows ? `${id}.cmd` : id),\n    windows ? `@echo off\\r\\necho ${id} ${version}\\r\\n` : `#!/bin/sh\\necho \"${id} ${version}\"\\n`,\n    { mode: 0o755 },\n  )\n  await host.writeTextFile(\n    join(payload, 'smoke', windows ? `${id}.ps1` : `${id}.sh`),\n    windows\n      ? `$ErrorActionPreference = 'Continue'\\n& ${id} --version | Out-Null\\nif ($LASTEXITCODE -ne 0) { exit 1 }\\n`\n      : `#!/bin/sh\\nset -eu\\n${id} --version >/dev/null\\n`,\n    { mode: 0o755 },\n  )\n}\n\nasync function readExtToolsManifestFile(\n  path: string,\n): Promise<{ text: string; manifest?: ExtToolsManifest; errors: string[] }> {\n  let text: string\n  try {\n    text = await getHost().readTextFile(path)\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) return { text: '', errors: ['not found'] }\n    throw error\n  }\n  let value: unknown\n  try {\n    value = JSON.parse(text)\n  } catch {\n    return { text, errors: ['not valid JSON'] }\n  }\n  const errors = extToolsManifestErrors(value)\n  if (errors.length > 0) return { text, errors }\n  const manifest = value as ExtToolsManifest\n  manifest.requires ??= []\n  manifest.conflicts ??= []\n  return { text, manifest, errors }\n}\n\n/** A payload directory as `pikg build` would archive it: symlinks read through, and refused when they leave the tree. */\nasync function readExtToolsPayloadTree(\n  root: string,\n): Promise<{ tree: ExtToolsPayloadTree; errors: string[] }> {\n  const host = getHost()\n  const tree: ExtToolsPayloadTree = {\n    files: new Map(),\n    directories: new Set(),\n    launchers: new Map(),\n  }\n  const errors: string[] = []\n  const realRoot = await host.realPath(root)\n  const walk = async (directory: string, prefix: string): Promise<void> => {\n    const children = await host.readDir(directory)\n    for (const child of children) {\n      const archivePath = prefix ? `${prefix}/${child.name}` : child.name\n      const path = join(directory, child.name)\n      const link = await host.lstat(path)\n      let physical = path\n      if (link.isSymlink) {\n        try {\n          physical = await host.realPath(path)\n        } catch (error) {\n          errors.push(\n            `${archivePath}: ${\n              isHostError(error, 'NotFound') ? 'a dangling symlink' : 'a symlink out of the payload'\n            }`,\n          )\n          continue\n        }\n        const inside = relative(realRoot, physical)\n        if (inside === '..' || inside.startsWith(`..${host.path.sep}`) || isAbsolute(inside)) {\n          errors.push(`${archivePath}: a symlink out of the payload`)\n          continue\n        }\n      }\n      const info = link.isSymlink ? await host.stat(physical) : link\n      if (info.isDirectory) {\n        tree.directories.add(archivePath)\n        await walk(physical, archivePath)\n      } else if (info.isFile) {\n        tree.files.set(archivePath, { executable: ((info.mode ?? 0) & 0o111) !== 0 })\n        if (archivePath.startsWith('bin/') && info.size <= EXT_TOOLS_LAUNCHER_LIMIT) {\n          tree.launchers.set(archivePath, await host.readFile(physical))\n        }\n      } else {\n        errors.push(`${archivePath}: not a regular file`)\n      }\n    }\n  }\n  await walk(realRoot, '')\n  return { tree, errors }\n}\n\n/** `pikg doctor` of an extension package: the manifest against the App, every platform's payload, and, given a catalog\n * of the other packages, `requires` and same-named commands. */\nasync function extToolsChecks(\n  app: AppMeta,\n  pikg: PikgMeta,\n  metaDir: string,\n  catalogDir: string | undefined,\n): Promise<Array<Record<string, unknown>>> {\n  const checks: Array<Record<string, unknown>> = []\n  const platforms = new Map<string, string>()\n  const stray: string[] = []\n  for (const [key, subpackage] of Object.entries(pikg.sub_pkgs)) {\n    const platform = extToolsPlatformOfKey(key)\n    if (!platform || subpackage.source.type !== 'path') {\n      stray.push(key)\n      continue\n    }\n    platforms.set(platform.name, resolve(metaDir, subpackage.source.path))\n  }\n  const sources = [...platforms.values()]\n  // <source>/payload/<platform>: the package's manifest is two levels up\n  const source = sources.length > 0 ? dirname(dirname(sources[0])) : dirname(metaDir)\n  const master = await readExtToolsManifestFile(join(source, EXT_TOOLS_MANIFEST_FILE))\n  const manifestErrors = [...master.errors]\n  if (stray.length > 0) {\n    manifestErrors.push(\n      `sub packages must be ext_tools_<os>_<arch> from a directory: ${stray.join(', ')}`,\n    )\n  }\n  const manifest = master.manifest\n  if (manifest) {\n    if (manifest.id !== app.name) {\n      manifestErrors.push(`id ${manifest.id} is not the App name ${app.name}`)\n    }\n    if (manifest.version !== app.version) {\n      manifestErrors.push(`version ${manifest.version} is not the App version ${app.version}`)\n    }\n    const without = manifest.platforms.filter((name) => !platforms.has(name))\n    if (without.length > 0) {\n      manifestErrors.push(`platforms without a sub package: ${without.join(', ')}`)\n    }\n    const unlisted = [...platforms.keys()].filter((name) => !manifest.platforms.includes(name))\n    if (unlisted.length > 0) {\n      manifestErrors.push(`sub packages of platforms it does not list: ${unlisted.join(', ')}`)\n    }\n  }\n  checks.push({\n    name: 'ext_tools_manifest',\n    status: manifestErrors.length === 0 ? 'ok' : 'error',\n    path: join(source, EXT_TOOLS_MANIFEST_FILE),\n    ...(manifestErrors.length > 0 ? { errors: manifestErrors } : {}),\n  })\n  if (!manifest) return checks\n  for (const [platform, dir] of platforms) {\n    const errors: string[] = []\n    try {\n      const { tree, errors: walkErrors } = await readExtToolsPayloadTree(dir)\n      errors.push(...walkErrors)\n      const copy = await readExtToolsManifestFile(join(dir, EXT_TOOLS_MANIFEST_FILE))\n      if (copy.errors.length > 0) {\n        errors.push(`${EXT_TOOLS_MANIFEST_FILE}: ${copy.errors.join('; ')}`)\n      } else if (copy.text !== master.text) {\n        errors.push(`${EXT_TOOLS_MANIFEST_FILE}: differs from the package's manifest`)\n      }\n      errors.push(...extToolsPayloadErrors(manifest, platform, tree, [source, metaDir]))\n    } catch (error) {\n      if (!isHostError(error, 'NotFound')) throw error\n      errors.push(`${dir}: not found`)\n    }\n    checks.push({\n      name: 'ext_tools_payload',\n      platform,\n      status: errors.length === 0 ? 'ok' : 'error',\n      path: dir,\n      ...(errors.length > 0 ? { errors } : {}),\n    })\n  }\n  if (!catalogDir) {\n    checks.push({\n      name: 'ext_tools_catalog',\n      status: 'skipped',\n      detail: 'no --catalog: requires and commands other packages also provide are not checked',\n    })\n    return checks\n  }\n  const others = new Map<string, ExtToolsManifest>()\n  const catalogErrors: string[] = []\n  for (const entry of await getHost().readDir(catalogDir)) {\n    if (entry.isFile) continue\n    const candidate = await readExtToolsManifestFile(\n      join(catalogDir, entry.name, EXT_TOOLS_MANIFEST_FILE),\n    )\n    if (candidate.errors.includes('not found')) continue\n    if (!candidate.manifest) catalogErrors.push(`${entry.name}: ${candidate.errors.join('; ')}`)\n    else if (candidate.manifest.id !== manifest.id) {\n      others.set(candidate.manifest.id, candidate.manifest)\n    }\n  }\n  for (const required of manifest.requires) {\n    if (!others.has(required.id)) catalogErrors.push(`requires ${required.id}: not in the catalog`)\n  }\n  const commands = new Set(manifest.provides.map((provided) => provided.command))\n  for (const other of others.values()) {\n    if (manifest.conflicts.includes(other.id) || other.conflicts.includes(manifest.id)) continue\n    const shared = other.provides.map((provided) => provided.command).filter((command) =>\n      commands.has(command)\n    )\n    if (shared.length > 0) {\n      catalogErrors.push(\n        `${other.id} also provides ${\n          shared.join(', ')\n        }: one of the two must list the other in conflicts`,\n      )\n    }\n  }\n  checks.push({\n    name: 'ext_tools_catalog',\n    status: catalogErrors.length === 0 ? 'ok' : 'error',\n    path: catalogDir,\n    packages: [...others.keys()],\n    ...(catalogErrors.length > 0 ? { errors: catalogErrors } : {}),\n  })\n  return checks\n}\n\nasync function buildCommand(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  docker: DockerClient,\n  now: () => number,\n): Promise<Record<string, unknown>> {\n  const metaInput = optionalInputString(input, 'meta_dir') ?? './dapp_meta'\n  const metaDir = await realDirectory(resolveFromCwd(ctx, metaInput), 'dapp_meta')\n  const appMeta = parseAppMeta(await readJson(join(metaDir, 'app.json'), 'app.json'))\n  const pikgMeta = parsePikgMeta(await readJson(join(metaDir, 'pikg.json'), 'pikg.json'), appMeta)\n  const configuredDist = resolve(metaDir, pikgMeta.output_dir)\n  await rejectLeafSymlink(configuredDist, 'UNSAFE_OUTPUT_DIR')\n  const distDir = await canonicalTarget(configuredDist)\n  const projectDir = dirname(metaDir)\n  const sourcePaths: string[] = []\n  for (const subpackage of Object.values(pikgMeta.sub_pkgs)) {\n    if (subpackage.source.type === 'path') {\n      sourcePaths.push(await getHost().realPath(resolve(metaDir, subpackage.source.path)))\n    }\n  }\n  assertBuildPaths(metaDir, distDir, sourcePaths)\n  await validateReplaceableDist(distDir, metaRootId(metaDir))\n  await getHost().mkdir(dirname(distDir), { recursive: true })\n  const temporary = await getHost().makeTempDir({\n    dir: dirname(distDir),\n    prefix: '.buckyos-pikg-build-',\n  })\n  try {\n    const prepared: PreparedSubpackage[] = []\n    for (\n      const [key, subpackage] of Object.entries(pikgMeta.sub_pkgs).sort(([a], [b]) =>\n        a.localeCompare(b)\n      )\n    ) {\n      const payloadPath = join(temporary, `${key}.tar.gz`)\n      let dockerInfo: DockerImageInfo | undefined\n      if (subpackage.source.type === 'path') {\n        const sourcePath = await getHost().realPath(resolve(metaDir, subpackage.source.path))\n        const info = await getHost().stat(sourcePath)\n        if (info.isDirectory) {\n          await createDeterministicTarGz(sourcePath, payloadPath)\n        } else if (info.isFile && sourcePath.toLowerCase().endsWith('.tar.gz')) {\n          const before = await digestFile(sourcePath)\n          const beforeStat = statIdentity(await getHost().stat(sourcePath))\n          await getHost().copyFile(sourcePath, payloadPath)\n          const after = await digestFile(sourcePath)\n          const afterStat = statIdentity(await getHost().stat(sourcePath))\n          const copied = await digestFile(payloadPath)\n          if (\n            beforeStat !== afterStat || before.size !== after.size ||\n            before.sha256 !== after.sha256 || copied.size !== before.size ||\n            copied.sha256 !== before.sha256\n          ) {\n            throw new ToolError('SOURCE_CHANGED', `source changed while copied: ${key}`)\n          }\n        } else {\n          throw new UsageError(\n            'INVALID_SOURCE',\n            `${key} source must be a directory or .tar.gz file`,\n          )\n        }\n      } else {\n        dockerInfo = await docker.inspect(subpackage.source.image)\n        if (!SHA256_ID.test(dockerInfo.id)) {\n          throw new ToolError(\n            'DOCKER_IDENTITY_INVALID',\n            `Docker image ${key} has no immutable image ID`,\n          )\n        }\n        await docker.save(dockerInfo.id, payloadPath)\n        const after = await docker.inspect(dockerInfo.id)\n        if (after.id !== dockerInfo.id) {\n          throw new ToolError(\n            'SOURCE_CHANGED',\n            `Docker image identity changed while exporting: ${key}`,\n          )\n        }\n      }\n      const digest = await digestFile(payloadPath)\n      prepared.push({\n        key,\n        input: subpackage,\n        payloadPath,\n        digest: { size: digest.size, digest: `sha256:${digest.sha256}` },\n        ...(dockerInfo ? { docker: dockerInfo } : {}),\n      })\n    }\n\n    const timestamp = now()\n    if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error('invalid clock value')\n    const namespace = deriveAppNamespace(appMeta.did)\n    const packageObjects: Record<string, Record<string, unknown>> = {}\n    const contentIndex: PackageMetaFile['content_index'] = {}\n    const pkgList: Record<string, Record<string, unknown>> = {}\n    const generatedSubpackages: DistManifest['subpackages'] = {}\n    const packageNames = new Set<string>()\n    for (const item of prepared) {\n      const packageName = `${packageEnvironmentQualifier(item.key, item.input.selector)}.${\n        packageSuffix(item.key)\n      }.${namespace}`\n      if (packageNames.has(packageName)) {\n        throw new UsageError('PACKAGE_NAME_COLLISION', `subpackage names collide at ${packageName}`)\n      }\n      packageNames.add(packageName)\n      const payloadHash = item.digest.digest.slice('sha256:'.length)\n      const packageMeta = createPackageMeta(\n        packageName,\n        appMeta.version,\n        appMeta.author,\n        appMeta.owner,\n        { size: item.digest.size, sha256: payloadHash, crc32: 0 },\n        timestamp,\n      )\n      packageObjects[packageMeta.objectId] = packageMeta.value\n      if (contentIndex[item.digest.digest]) {\n        throw new UsageError(\n          'DUPLICATE_PAYLOAD_DIGEST',\n          `subpackages cannot share the same payload digest: ${item.key}`,\n        )\n      }\n      contentIndex[item.digest.digest] = {\n        sub_pkg_name: item.key,\n        path: `${item.key}.tar.gz`,\n        format: 'tar.gz',\n        size: item.digest.size,\n        digest: item.digest.digest,\n      }\n      const selector = item.input.selector\n      pkgList[item.key] = {\n        pkg_id: `${packageName}#${appMeta.version}`,\n        pkg_objid: packageMeta.objectId,\n        ...(item.docker\n          ? {\n            docker_image_name: item.docker.canonicalName,\n            docker_image_digest: item.docker.id,\n          }\n          : {}),\n        ...(selector ? { selector } : {}),\n        required: item.input.required,\n      }\n      generatedSubpackages[item.key] = {\n        source_kind: item.input.source.type,\n        size: item.digest.size,\n        digest: item.digest.digest,\n        pkg_objid: packageMeta.objectId,\n      }\n    }\n    const appDoc: Record<string, unknown> = {\n      schema_version: 1,\n      doc_type: 'app',\n      did: appMeta.did,\n      name: appMeta.name,\n      version: appMeta.version,\n      app_type: appMeta.categories[0],\n      author: appMeta.author,\n      owner: appMeta.owner,\n      controller: appMeta.owner,\n      create_time: timestamp,\n      last_update_time: timestamp,\n      exp: timestamp + APP_DOCUMENT_LIFETIME_SECONDS,\n      categories: appMeta.categories,\n      pkg_list: pkgList,\n      show_name: appMeta.show_name,\n      ...(appMeta.presentation ? { presentation: appMeta.presentation } : {}),\n      ...(appMeta.permissions.length ? { permissions: appMeta.permissions } : {}),\n      ...(appMeta.content_handlers?.length ? { content_handlers: appMeta.content_handlers } : {}),\n      selector_type: appMeta.selector_type,\n      service_config_tips: appMeta.service_config_tips,\n    }\n    const appObjectId = appDocObjectId(appDoc)\n    const packageMeta: PackageMetaFile = {\n      '@schema': PACKAGE_META_SCHEMA,\n      app_doc_id: appObjectId,\n      package_objects: packageObjects,\n      content_index: contentIndex,\n    }\n    await writeJson(join(temporary, APPDOC_ENTRY), appDoc)\n    await writeJson(join(temporary, PACKAGE_META_ENTRY), packageMeta)\n    const validated = await validateSnapshot(temporary, appDoc, packageMeta)\n    const generatedFiles: DistManifest['generated_files'] = {}\n    for (\n      const name of [\n        APPDOC_ENTRY,\n        PACKAGE_META_ENTRY,\n        ...prepared.map((item) => `${item.key}.tar.gz`),\n      ]\n    ) {\n      const digest = await digestFile(join(temporary, name))\n      generatedFiles[name] = { size: digest.size, digest: `sha256:${digest.sha256}` }\n    }\n    const manifest: DistManifest = {\n      schema_version: 1,\n      tool_version: TOOL_VERSION,\n      meta_root_id: metaRootId(metaDir),\n      source_fingerprint: `sha256:${\n        stableJsonDigest({\n          app: appMeta,\n          pikg: pikgMeta,\n          payloads: generatedSubpackages,\n        })\n      }`,\n      app_doc_object_id: appObjectId,\n      pikg_file: pikgMeta.pikg_file,\n      generated_files: generatedFiles,\n      subpackages: generatedSubpackages,\n    }\n    await writeJson(join(temporary, DIST_MANIFEST_NAME), manifest)\n    await replaceDirectory(temporary, distDir)\n    return {\n      meta_dir: metaDir,\n      dist_dir: distDir,\n      app_did: appMeta.did,\n      app_doc_object_id: appObjectId,\n      subpackage_count: validated.subpackages.length,\n      subpackages: validated.subpackages.map((item) => ({\n        key: item.key,\n        source_kind: pikgMeta.sub_pkgs[item.key].source.type,\n        size: item.payload_size,\n        digest: item.payload_digest,\n        pkg_objid: item.pkg_objid,\n      })),\n      ready_for_pack: true,\n      next_command: `buckyos pikg pack ${distDir}`,\n      project_dir: projectDir,\n    }\n  } catch (error) {\n    await removeTreeIfExists(temporary)\n    throw error\n  }\n}\n\nasync function packCommand(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n  const distInput = optionalInputString(input, 'dist_dir') ?? './dapp_dist'\n  const distDir = await safeExistingDirectory(resolveFromCwd(ctx, distInput), 'dapp_dist')\n  const manifest = await validateManagedDist(distDir, undefined, true)\n  const appDoc = await readJson(join(distDir, APPDOC_ENTRY), APPDOC_ENTRY)\n  const packageMeta = parsePackageMeta(\n    await readJson(join(distDir, PACKAGE_META_ENTRY), PACKAGE_META_ENTRY),\n  )\n  const validated = await validateSnapshot(distDir, appDoc, packageMeta)\n  if (validated.appDocObjectId !== manifest.app_doc_object_id) {\n    throw new ToolError(\n      'INVALID_PACKAGE',\n      'snapshot AppDoc Object ID differs from ownership manifest',\n    )\n  }\n  const temporary = join(distDir, `.${manifest.pikg_file}.tmp-${crypto.randomUUID()}`)\n  const finalPath = join(distDir, manifest.pikg_file)\n  try {\n    await packSnapshot(distDir, temporary, appDoc, packageMeta)\n    const inspection = await inspectPikg(temporary)\n    if (inspection.app.app_doc_object_id !== manifest.app_doc_object_id) {\n      throw new ToolError(\n        'INVALID_PACKAGE',\n        'PIKG self-check returned a different AppDoc Object ID',\n      )\n    }\n    await replaceFile(temporary, finalPath)\n    const digest = await digestFile(finalPath)\n    return {\n      dist_dir: distDir,\n      pikg_path: finalPath,\n      size: digest.size,\n      pikg_digest: `sha256:${digest.sha256}`,\n      app_doc_object_id: inspection.app.app_doc_object_id,\n      validation: 'passed',\n    }\n  } catch (error) {\n    await removeFileIfExists(temporary)\n    throw error\n  }\n}\n\nasync function cleanCommand(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n  const metaInput = optionalInputString(input, 'meta_dir') ?? './dapp_meta'\n  const metaDir = await realDirectory(resolveFromCwd(ctx, metaInput), 'dapp_meta')\n  const appMeta = parseAppMeta(await readJson(join(metaDir, 'app.json'), 'app.json'))\n  const pikgMeta = parsePikgMeta(\n    await readJson(join(metaDir, 'pikg.json'), 'pikg.json'),\n    appMeta,\n  )\n  const configuredDist = resolve(metaDir, pikgMeta.output_dir)\n  assertSafeCleanTarget(ctx, metaDir, configuredDist, [])\n  await rejectLeafSymlink(configuredDist, 'UNSAFE_CLEAN_TARGET')\n  const distDir = await canonicalTarget(configuredDist)\n  try {\n    await getHost().lstat(distDir)\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) {\n      return { meta_dir: metaDir, dist_dir: distDir, removed: false }\n    }\n    throw error\n  }\n  const sourcePaths: string[] = []\n  for (const subpackage of Object.values(pikgMeta.sub_pkgs)) {\n    if (subpackage.source.type === 'path') {\n      try {\n        sourcePaths.push(await getHost().realPath(resolve(metaDir, subpackage.source.path)))\n      } catch (error) {\n        if (!isHostError(error, 'NotFound')) throw error\n      }\n    }\n  }\n  assertSafeCleanTarget(ctx, metaDir, distDir, sourcePaths)\n  await validateManagedDist(distDir, metaRootId(metaDir), true, 'UNSAFE_CLEAN_TARGET')\n  if (!ctx.confirmed) {\n    if (ctx.config.nonInteractive || ctx.interactive || !ctx.io.inputIsTerminal) {\n      throw new ToolError(\n        'CONFIRMATION_REQUIRED',\n        'pikg clean requires --yes in non-interactive mode',\n        EXIT_PERMISSION,\n      )\n    }\n    const answer = await ctx.io.prompt(`Delete managed PIKG output ${distDir}? [y/N] `)\n    if (!answer || !['y', 'yes'].includes(answer.trim().toLowerCase())) {\n      throw new ToolError('CONFIRMATION_DECLINED', 'PIKG clean was declined', EXIT_PERMISSION)\n    }\n  }\n  await getHost().remove(distDir, { recursive: true })\n  return { meta_dir: metaDir, dist_dir: distDir, removed: true }\n}\n\nfunction parseAppMeta(value: Record<string, unknown>): AppMeta {\n  rejectUnknown(\n    value,\n    [\n      'schema_version',\n      'did',\n      'name',\n      'version',\n      'owner',\n      'author',\n      'show_name',\n      'presentation',\n      'categories',\n      'permissions',\n      'content_handlers',\n      'selector_type',\n      'service_config_tips',\n    ],\n    'app.json',\n  )\n  if (value.schema_version !== 1) {\n    throw new UsageError('UNSUPPORTED_SCHEMA_VERSION', 'app.json.schema_version must be 1')\n  }\n  const name = developmentString(value.name, 'app.json.name')\n  validateAppName(name)\n  const version = developmentString(value.version, 'app.json.version')\n  validateVersion(version)\n  const did = developmentString(value.did, 'app.json.did')\n  const owner = developmentString(value.owner, 'app.json.owner')\n  deriveAppNamespace(did)\n  const categories = value.categories\n  if (\n    !Array.isArray(categories) || !categories.length ||\n    categories.some((item) => typeof item !== 'string')\n  ) {\n    throw new UsageError(\n      'SCHEMA_VALIDATION_FAILED',\n      'app.json.categories must be a non-empty string array',\n    )\n  }\n  const permissions = developmentValidation(\n    () => validatePermissions(value.permissions ?? [], 'app.json.permissions'),\n  )\n  const serviceConfig = developmentValidation(() =>\n    validateServiceConfigTips(\n      value.service_config_tips ?? {},\n      'app.json.service_config_tips',\n    )\n  )\n  return {\n    schema_version: 1,\n    did,\n    name,\n    version,\n    owner,\n    author: developmentString(value.author, 'app.json.author'),\n    show_name: developmentString(value.show_name, 'app.json.show_name'),\n    ...(value.presentation === undefined ? {} : {\n      presentation: developmentValidation(() =>\n        validateAppPresentation(value.presentation, 'app.json.presentation')\n      ),\n    }),\n    categories: categories as string[],\n    permissions,\n    ...(value.content_handlers === undefined ? {} : {\n      content_handlers: developmentValidation(() =>\n        validateContentHandlers(value.content_handlers, permissions)\n      ),\n    }),\n    selector_type: developmentString(value.selector_type, 'app.json.selector_type'),\n    service_config_tips: serviceConfig,\n  }\n}\n\nfunction parsePikgMeta(value: Record<string, unknown>, app?: AppMeta): PikgMeta {\n  rejectUnknown(value, ['schema_version', 'output_dir', 'pikg_file', 'sub_pkgs'], 'pikg.json')\n  if (value.schema_version !== 1) {\n    throw new UsageError('UNSUPPORTED_SCHEMA_VERSION', 'pikg.json.schema_version must be 1')\n  }\n  const outputDir = value.output_dir === undefined\n    ? '../dapp_dist'\n    : developmentString(value.output_dir, 'pikg.json.output_dir')\n  const defaultPikgFile = app ? `${app.name}-${app.version}.pikg` : undefined\n  const pikgFile = value.pikg_file === undefined\n    ? defaultPikgFile ?? (() => {\n      throw new UsageError('SCHEMA_VALIDATION_FAILED', 'pikg.json.pikg_file is required')\n    })()\n    : developmentString(value.pikg_file, 'pikg.json.pikg_file')\n  if (\n    !SAFE_PIKG_FILE.test(pikgFile) || pikgFile.includes('..') || basename(pikgFile) !== pikgFile\n  ) {\n    throw new UsageError('INVALID_PIKG_FILE', 'pikg_file must be a safe .pikg file name')\n  }\n  const rawSubpackages = developmentObject(value.sub_pkgs, 'pikg.json.sub_pkgs')\n  if (!Object.keys(rawSubpackages).length) {\n    throw new UsageError('SCHEMA_VALIDATION_FAILED', 'pikg.json.sub_pkgs must not be empty')\n  }\n  const subpackages: Record<string, SubpackageInput> = {}\n  for (const [key, raw] of Object.entries(rawSubpackages)) {\n    validateSubpackageName(key)\n    const subpackage = developmentObject(raw, `pikg.json.sub_pkgs.${key}`)\n    rejectUnknown(subpackage, ['selector', 'required', 'source'], `pikg.json.sub_pkgs.${key}`)\n    const selector = developmentValidation(() =>\n      canonicalSelector(subpackage.selector, `pikg.json.sub_pkgs.${key}.selector`)\n    )\n    assertSelectorCompatible(key, selector, `pikg.json.sub_pkgs.${key}.selector`)\n    if (subpackage.required !== undefined && typeof subpackage.required !== 'boolean') {\n      throw new UsageError('SCHEMA_VALIDATION_FAILED', `${key}.required must be boolean`)\n    }\n    const source = developmentObject(subpackage.source, `pikg.json.sub_pkgs.${key}.source`)\n    if (source.type === 'path') {\n      rejectUnknown(source, ['type', 'path'], `pikg.json.sub_pkgs.${key}.source`)\n      subpackages[key] = {\n        ...(selector ? { selector } : {}),\n        required: subpackage.required === undefined ? true : subpackage.required,\n        source: { type: 'path', path: developmentString(source.path, `${key}.source.path`) },\n      }\n    } else if (source.type === 'docker-image') {\n      rejectUnknown(source, ['type', 'image'], `pikg.json.sub_pkgs.${key}.source`)\n      subpackages[key] = {\n        ...(selector ? { selector } : {}),\n        required: subpackage.required === undefined ? true : subpackage.required,\n        source: {\n          type: 'docker-image',\n          image: developmentString(source.image, `${key}.source.image`),\n        },\n      }\n    } else {\n      throw new UsageError('INVALID_SOURCE', `${key}.source.type must be path or docker-image`)\n    }\n  }\n  return {\n    schema_version: 1,\n    output_dir: outputDir,\n    pikg_file: pikgFile,\n    sub_pkgs: subpackages,\n  }\n}\n\nasync function initializeMetaDirectory(\n  projectDir: string,\n  metaDir: string,\n  appMeta: AppMeta,\n  pikgMeta: Record<string, unknown>,\n): Promise<void> {\n  let existedEmpty = false\n  try {\n    const stat = await getHost().lstat(metaDir)\n    if (!stat.isDirectory || stat.isSymlink) {\n      throw new UsageError(\n        'ALREADY_EXISTS',\n        'dapp_meta already exists and is not an empty directory',\n      )\n    }\n    for (const _entry of await getHost().readDir(metaDir)) {\n      throw new UsageError('ALREADY_EXISTS', 'dapp_meta already contains files')\n    }\n    existedEmpty = true\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n  }\n  const temporary = await getHost().makeTempDir({ dir: projectDir, prefix: '.buckyos-pikg-init-' })\n  try {\n    await writeJson(join(temporary, 'app.json'), appMeta)\n    await writeJson(join(temporary, 'pikg.json'), pikgMeta)\n    parseAppMeta(await readJson(join(temporary, 'app.json'), 'app.json'))\n    parsePikgMeta(await readJson(join(temporary, 'pikg.json'), 'pikg.json'), appMeta)\n    if (existedEmpty) await getHost().remove(metaDir)\n    try {\n      await getHost().rename(temporary, metaDir)\n    } catch (error) {\n      if (existedEmpty) await getHost().mkdir(metaDir)\n      throw error\n    }\n  } catch (error) {\n    await removeTreeIfExists(temporary)\n    throw error\n  }\n}\n\nasync function validateReplaceableDist(distDir: string, expectedMetaRootId: string): Promise<void> {\n  try {\n    await getHost().lstat(distDir)\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) return\n    throw error\n  }\n  await validateManagedDist(distDir, expectedMetaRootId, true)\n}\n\nasync function validateManagedDist(\n  distDir: string,\n  expectedMetaRootId?: string,\n  verifyFiles = true,\n  unsafeCode = 'UNSAFE_DIST_TARGET',\n): Promise<DistManifest> {\n  try {\n    const info = await getHost().lstat(distDir)\n    if (!info.isDirectory || info.isSymlink) throw new Error('target is not a real directory')\n    const manifest = parseDistManifest(\n      await readJson(join(distDir, DIST_MANIFEST_NAME), DIST_MANIFEST_NAME),\n    )\n    if (expectedMetaRootId && manifest.meta_root_id !== expectedMetaRootId) {\n      throw new Error('ownership manifest belongs to another dapp_meta')\n    }\n    const allowed = new Set([\n      DIST_MANIFEST_NAME,\n      manifest.pikg_file,\n      ...Object.keys(manifest.generated_files),\n    ])\n    for (const entry of await getHost().readDir(distDir)) {\n      if (!entry.isFile || entry.isSymlink || !allowed.has(entry.name)) {\n        throw new Error(`unmanaged entry exists: ${entry.name}`)\n      }\n    }\n    for (const name of Object.keys(manifest.generated_files)) {\n      const info = await getHost().lstat(join(distDir, name))\n      if (!info.isFile || info.isSymlink) throw new Error(`generated file is unsafe: ${name}`)\n      if (verifyFiles) {\n        const expected = manifest.generated_files[name]\n        const actual = await digestFile(join(distDir, name))\n        if (actual.size !== expected.size || `sha256:${actual.sha256}` !== expected.digest) {\n          throw new Error(`generated file was modified: ${name}`)\n        }\n      }\n    }\n    return manifest\n  } catch (error) {\n    if (error instanceof ToolError && error.code === unsafeCode) throw error\n    throw new ToolError(\n      unsafeCode,\n      `managed dist validation failed: ${error instanceof Error ? error.message : String(error)}`,\n      6,\n    )\n  }\n}\n\nfunction parseDistManifest(value: Record<string, unknown>): DistManifest {\n  rejectUnknown(\n    value,\n    [\n      'schema_version',\n      'tool_version',\n      'meta_root_id',\n      'source_fingerprint',\n      'app_doc_object_id',\n      'pikg_file',\n      'generated_files',\n      'subpackages',\n    ],\n    DIST_MANIFEST_NAME,\n  )\n  if (value.schema_version !== 1) throw new Error('unsupported ownership manifest version')\n  const pikgFile = String(value.pikg_file ?? '')\n  if (\n    !SAFE_PIKG_FILE.test(pikgFile) || pikgFile.includes('..') || basename(pikgFile) !== pikgFile\n  ) {\n    throw new Error('ownership manifest has an unsafe pikg_file')\n  }\n  const generatedRaw = expectObject(value.generated_files, `${DIST_MANIFEST_NAME}.generated_files`)\n  const generated: Record<string, GeneratedFileRecord> = {}\n  for (const [name, raw] of Object.entries(generatedRaw)) {\n    if (\n      !SAFE_GENERATED_FILE.test(name) || name === '.' || name === '..' || name.includes('\\\\') ||\n      basename(name) !== name || name === DIST_MANIFEST_NAME || name === pikgFile\n    ) {\n      throw new Error(`ownership manifest has an unsafe generated file: ${name}`)\n    }\n    const record = expectObject(raw, `generated_files.${name}`)\n    rejectUnknown(record, ['size', 'digest'], `generated_files.${name}`)\n    if (typeof record.size !== 'number' || !Number.isSafeInteger(record.size) || record.size < 0) {\n      throw new Error(`generated_files.${name}.size is invalid`)\n    }\n    if (typeof record.digest !== 'string' || !SHA256_ID.test(record.digest)) {\n      throw new Error(`generated_files.${name}.digest is invalid`)\n    }\n    generated[name] = { size: record.size, digest: record.digest }\n  }\n  if (!generated[APPDOC_ENTRY] || !generated[PACKAGE_META_ENTRY]) {\n    throw new Error('ownership manifest is missing required metadata files')\n  }\n  return {\n    schema_version: 1,\n    tool_version: String(value.tool_version ?? ''),\n    meta_root_id: validateDigestString(value.meta_root_id, 'meta_root_id'),\n    source_fingerprint: validateDigestString(value.source_fingerprint, 'source_fingerprint'),\n    app_doc_object_id: validateObjectId(value.app_doc_object_id, 'app_doc_object_id'),\n    pikg_file: pikgFile,\n    generated_files: generated,\n    subpackages: expectObject(value.subpackages, 'subpackages') as DistManifest['subpackages'],\n  }\n}\n\nfunction assertBuildPaths(metaDir: string, distDir: string, sourcePaths: string[]): void {\n  if (pathsOverlap(metaDir, distDir)) {\n    throw new UsageError('UNSAFE_OUTPUT_DIR', 'output_dir overlaps dapp_meta')\n  }\n  for (const source of sourcePaths) {\n    if (pathsOverlap(source, distDir)) {\n      throw new UsageError('UNSAFE_OUTPUT_DIR', 'output_dir overlaps a subpackage source')\n    }\n  }\n}\n\nfunction assertSafeCleanTarget(\n  ctx: CommandContext,\n  metaDir: string,\n  distDir: string,\n  sourcePaths: string[],\n): void {\n  const projectDir = dirname(metaDir)\n  const exactProtected = [resolve(ctx.cwd), projectDir]\n  const home = getHost().env('HOME') ?? getHost().env('USERPROFILE')\n  if (home) exactProtected.push(resolve(home))\n  if (\n    dirname(distDir) === distDir ||\n    exactProtected.some((path) => resolve(path) === resolve(distDir)) ||\n    pathsOverlap(metaDir, distDir) || sourcePaths.some((path) => pathsOverlap(path, distDir))\n  ) {\n    throw new ToolError('UNSAFE_CLEAN_TARGET', 'refusing to clean an unsafe output directory')\n  }\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n  try {\n    await getHost().lstat(path)\n    return true\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) return false\n    throw error\n  }\n}\n\nasync function replaceDirectory(temporary: string, destination: string): Promise<void> {\n  if (!(await pathExists(destination))) {\n    try {\n      await getHost().rename(temporary, destination)\n      return\n    } catch (error) {\n      // Windows reports EPERM, not EEXIST, when the destination directory is\n      // already there. Fall through and replace it when that is the case.\n      if (\n        getHost().platform !== 'windows' || !isHostError(error, 'PermissionDenied') ||\n        !(await pathExists(destination))\n      ) {\n        throw error\n      }\n    }\n  }\n  const backup = `${destination}.previous-${crypto.randomUUID()}`\n  await getHost().rename(destination, backup)\n  try {\n    await getHost().rename(temporary, destination)\n  } catch (error) {\n    await getHost().rename(backup, destination)\n    throw error\n  }\n  await getHost().remove(backup, { recursive: true })\n}\n\nasync function replaceFile(temporary: string, destination: string): Promise<void> {\n  let exists = false\n  try {\n    await getHost().lstat(destination)\n    exists = true\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n  }\n  if (!exists) {\n    await getHost().rename(temporary, destination)\n    return\n  }\n  const backup = `${destination}.previous-${crypto.randomUUID()}`\n  await getHost().rename(destination, backup)\n  try {\n    await getHost().rename(temporary, destination)\n  } catch (error) {\n    await getHost().rename(backup, destination)\n    throw error\n  }\n  await removeFileIfExists(backup)\n}\n\nclass LocalDockerClient implements DockerClient {\n  async inspect(reference: string): Promise<DockerImageInfo> {\n    let result\n    try {\n      result = await getHost().run('docker', ['image', 'inspect', reference])\n    } catch (error) {\n      throw new ToolError(\n        'DOCKER_UNAVAILABLE',\n        `Docker inspect is unavailable: ${error instanceof Error ? error.message : String(error)}`,\n        EXIT_UNAVAILABLE,\n        true,\n      )\n    }\n    if (!result.success) {\n      throw new ToolError(\n        'DOCKER_IMAGE_NOT_FOUND',\n        `local Docker image is unavailable: ${safeDockerError(result.stderr)}`,\n        EXIT_UNAVAILABLE,\n      )\n    }\n    let values: unknown\n    try {\n      values = JSON.parse(new TextDecoder().decode(result.stdout))\n    } catch {\n      throw new ToolError('DOCKER_INSPECT_INVALID', 'Docker inspect returned invalid JSON')\n    }\n    if (!Array.isArray(values) || values.length !== 1) {\n      throw new ToolError('DOCKER_INSPECT_INVALID', 'Docker inspect returned an unexpected result')\n    }\n    const value = developmentObject(values[0], 'Docker inspect')\n    const id = developmentString(value.Id, 'Docker image ID').toLowerCase()\n    if (!SHA256_ID.test(id)) {\n      throw new ToolError('DOCKER_IDENTITY_INVALID', 'Docker image ID is not immutable sha256')\n    }\n    const architecture = developmentString(value.Architecture, 'Docker architecture')\n    const tags = Array.isArray(value.RepoTags)\n      ? value.RepoTags.filter((tag): tag is string =>\n        typeof tag === 'string' && tag !== '<none>:<none>'\n      )\n      : []\n    return {\n      id,\n      architecture,\n      canonicalName: tags.includes(reference) ? reference : tags[0] ?? reference,\n    }\n  }\n\n  async save(imageId: string, destinationTarGz: string): Promise<void> {\n    try {\n      const result = await getHost().runGzip(\n        'docker',\n        ['image', 'save', imageId],\n        destinationTarGz,\n      )\n      if (!result.success) {\n        await removeFileIfExists(destinationTarGz)\n        throw new ToolError(\n          'DOCKER_EXPORT_FAILED',\n          `Docker image save failed: ${safeDockerError(result.stderr)}`,\n          EXIT_UNAVAILABLE,\n        )\n      }\n    } catch (error) {\n      if (error instanceof ToolError) throw error\n      throw new ToolError(\n        'DOCKER_UNAVAILABLE',\n        `Docker save is unavailable: ${error instanceof Error ? error.message : String(error)}`,\n        EXIT_UNAVAILABLE,\n        true,\n      )\n    }\n  }\n}\n\nfunction resolveFromCwd(ctx: CommandContext, value: string): string {\n  return isAbsolute(value) ? resolve(value) : resolve(ctx.cwd, value)\n}\n\nasync function realDirectory(path: string, label: string): Promise<string> {\n  const real = await getHost().realPath(path)\n  const stat = await getHost().stat(real)\n  if (!stat.isDirectory) throw new UsageError('INVALID_PATH', `${label} must be a directory`)\n  return real\n}\n\nasync function safeExistingDirectory(path: string, label: string): Promise<string> {\n  const info = await getHost().lstat(path)\n  if (!info.isDirectory || info.isSymlink) {\n    throw new UsageError('INVALID_PATH', `${label} must be a real directory`)\n  }\n  return await getHost().realPath(path)\n}\n\nasync function canonicalTarget(path: string): Promise<string> {\n  const absolute = resolve(path)\n  try {\n    return await getHost().realPath(absolute)\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n    const parent = dirname(absolute)\n    if (parent === absolute) return absolute\n    return join(await canonicalTarget(parent), basename(absolute))\n  }\n}\n\nasync function rejectLeafSymlink(path: string, code: string): Promise<void> {\n  try {\n    if ((await getHost().lstat(path)).isSymlink) {\n      throw new ToolError(code, 'configured output_dir must not be a symlink')\n    }\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) return\n    throw error\n  }\n}\n\nfunction pathsOverlap(left: string, right: string): boolean {\n  const leftToRight = relative(resolve(left), resolve(right))\n  const rightToLeft = relative(resolve(right), resolve(left))\n  const separator = getHost().path.sep\n  return leftToRight === '' || !leftToRight.startsWith(`..${separator}`) && leftToRight !== '..' ||\n    !rightToLeft.startsWith(`..${separator}`) && rightToLeft !== '..'\n}\n\nfunction metaRootId(metaDir: string): string {\n  return `sha256:${sha256Bytes(new TextEncoder().encode(resolve(metaDir)))}`\n}\n\nfunction packageSuffix(key: string): string {\n  const suffix = key.toLowerCase().replaceAll(/[^a-z0-9_-]+/g, '-').replaceAll(/^-+|-+$/g, '')\n  if (!suffix) {\n    throw new UsageError('INVALID_SUBPACKAGE_NAME', `cannot derive package name from ${key}`)\n  }\n  return suffix\n}\n\nfunction normalizeAppName(value: string): string {\n  return value.toLowerCase().replaceAll(/[^a-z0-9]+/g, '-').replaceAll(/^-+|-+$/g, '')\n}\n\nfunction validateAppName(value: string): void {\n  if (!APP_NAME.test(value)) throw new UsageError('INVALID_APP_NAME', `invalid App name: ${value}`)\n}\n\nfunction validateVersion(value: string): void {\n  if (!VERSION.test(value)) throw new UsageError('INVALID_VERSION', `invalid App version: ${value}`)\n}\n\nfunction deriveAppDid(name: string, owner: string): string {\n  const match = /^did:bns:([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)$/.exec(owner)\n  if (!match) {\n    throw new UsageError(\n      'INVALID_OWNER_DID',\n      'Owner DID must be a standard single-label did:bns DID for an ordinary App',\n    )\n  }\n  return `did:bns:${name}.${match[1]}`\n}\n\nasync function requiredPrompt(\n  ctx: CommandContext,\n  canPrompt: boolean,\n  message: string,\n  field: string,\n): Promise<string> {\n  if (!canPrompt) {\n    throw new UsageError('MISSING_REQUIRED_INPUT', `${field} is required`)\n  }\n  const answer = await ctx.io.prompt(message)\n  if (!answer?.trim()) throw new UsageError('MISSING_REQUIRED_INPUT', `${field} is required`)\n  return answer.trim()\n}\n\nfunction optionalInputString(input: Record<string, unknown>, key: string): string | undefined {\n  return input[key] === undefined ? undefined : expectInputString(input, key)\n}\n\nfunction expectInputString(input: Record<string, unknown>, key: string): string {\n  const value = input[key]\n  if (typeof value !== 'string' || !value) {\n    throw new UsageError('MISSING_REQUIRED_INPUT', `${key} is required`)\n  }\n  return value\n}\n\nfunction developmentString(value: unknown, label: string): string {\n  try {\n    return expectNonEmptyString(value, label)\n  } catch (error) {\n    if (error instanceof ToolError) throw new UsageError('SCHEMA_VALIDATION_FAILED', error.message)\n    throw error\n  }\n}\n\nfunction developmentObject(value: unknown, label: string): Record<string, unknown> {\n  try {\n    return expectObject(value, label)\n  } catch (error) {\n    if (error instanceof ToolError) throw new UsageError('SCHEMA_VALIDATION_FAILED', error.message)\n    throw error\n  }\n}\n\nfunction developmentValidation<T>(validate: () => T): T {\n  try {\n    return validate()\n  } catch (error) {\n    if (error instanceof ToolError) throw new UsageError('SCHEMA_VALIDATION_FAILED', error.message)\n    throw error\n  }\n}\n\nasync function readJson(path: string, label: string): Promise<Record<string, unknown>> {\n  try {\n    const parsed = JSON.parse(await getHost().readTextFile(path))\n    return developmentObject(parsed, label)\n  } catch (error) {\n    if (error instanceof SyntaxError) {\n      throw new UsageError('INVALID_JSON', `${label} is not valid JSON`)\n    }\n    throw error\n  }\n}\n\nasync function writeJson(path: string, value: unknown): Promise<void> {\n  await getHost().writeTextFile(path, `${JSON.stringify(value, null, 2)}\\n`, {\n    createNew: true,\n    mode: 0o600,\n  })\n}\n\nfunction validateDigestString(value: unknown, label: string): string {\n  if (typeof value !== 'string' || !SHA256_ID.test(value)) throw new Error(`${label} is invalid`)\n  return value\n}\n\nfunction validateObjectId(value: unknown, label: string): string {\n  if (typeof value !== 'string' || !OBJECT_ID.test(value)) throw new Error(`${label} is invalid`)\n  return value\n}\n\nfunction statIdentity(value: HostFileInfo): string {\n  return JSON.stringify({\n    size: value.size,\n    mtime: value.mtime?.getTime() ?? null,\n    dev: value.dev,\n    ino: value.ino,\n    mode: value.mode,\n  })\n}\n\nfunction displaySource(projectDir: string, source: string): string {\n  const display = relative(projectDir, source)\n  return display && !display.startsWith(`..${getHost().path.sep}`) && display !== '..'\n    ? toPortablePath(display)\n    : '[external path]'\n}\n\nfunction toPortablePath(path: string): string {\n  return path.split(getHost().path.sep).join('/') || '.'\n}\n\nfunction safeDockerError(bytes: Uint8Array): string {\n  const text = new TextDecoder().decode(bytes).trim().replaceAll(/[\\r\\n]+/g, ' ')\n  return text.slice(0, 500) || 'unknown Docker error'\n}\n\nasync function removeTreeIfExists(path: string): Promise<void> {\n  try {\n    await getHost().remove(path, { recursive: true })\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n  }\n}\n\nasync function removeFileIfExists(path: string): Promise<void> {\n  try {\n    await getHost().remove(path)\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n  }\n}\n","import { taskMgrTaskEventPath } from 'buckyos/node'\nimport type { CommandContext } from './context.ts'\nimport { EXIT_OPERATION, EXIT_TIMEOUT, ToolError } from './errors.ts'\n\nconst TASK_MANAGER_SERVICE = 'task-manager'\nconst DEFAULT_POLL_INTERVAL_MS = 500\n\nexport interface TaskObservation {\n  revision?: number\n  phase: string\n  outcome?: string\n  message?: string\n  error?: {\n    code?: string\n    message?: string\n    retryable?: boolean\n    details?: Record<string, unknown>\n  }\n  data: Record<string, unknown>\n  progress?: unknown\n}\n\nexport interface TaskWaitOptions {\n  observe?: (ctx: CommandContext, taskId: string) => Promise<TaskObservation>\n  pollIntervalMs?: number\n  sleep?: (milliseconds: number, signal: AbortSignal) => Promise<void>\n  failOnTaskFailure?: boolean\n  onObservation?: (observation: TaskObservation) => Promise<void>\n}\n\nexport async function waitForTask(\n  ctx: CommandContext,\n  taskId: string,\n  options: TaskWaitOptions = {},\n): Promise<Record<string, unknown>> {\n  const observe = options.observe ?? observeTask\n  const sleep = options.sleep ?? abortableSleep\n  const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS\n  const failOnTaskFailure = options.failOnTaskFailure ?? true\n  let lastProgress = ''\n  let lastRevision: number | undefined\n  let reader: Awaited<ReturnType<NonNullable<typeof ctx.clients.createEventReader>>> | undefined\n\n  try {\n    const remaining = Math.max(1, (ctx.deadline ?? Date.now()) - Date.now())\n    const eventSignal = AbortSignal.any([ctx.signal, AbortSignal.timeout(remaining)])\n    reader = await ctx.clients.createEventReader?.(taskMgrTaskEventPath(taskId), eventSignal)\n  } catch {\n    reader = undefined\n  }\n\n  try {\n    while (true) {\n      const observation = await observe(ctx, taskId)\n      const progress = JSON.stringify({\n        task_id: taskId,\n        revision: observation.revision,\n        phase: observation.phase,\n        outcome: observation.outcome,\n        progress: observation.progress,\n        message: observation.message,\n      })\n      const changed = observation.revision === undefined\n        ? progress !== lastProgress\n        : observation.revision !== lastRevision\n      if (changed) {\n        if (options.onObservation) await options.onObservation(observation)\n        else await ctx.io.stderr(`${progress}\\n`)\n        lastProgress = progress\n        lastRevision = observation.revision\n      }\n\n      if (observation.phase === 'Terminal') {\n        if (failOnTaskFailure && observation.outcome !== 'Succeeded') {\n          const error = observation.error\n          throw new ToolError(\n            normalizeTaskErrorCode(error?.code, observation.outcome),\n            error?.message ?? `task ${taskId} ended with ${observation.outcome ?? 'no outcome'}`,\n            observation.outcome === 'Canceled' ? EXIT_TIMEOUT : EXIT_OPERATION,\n            error?.retryable ?? false,\n            { task_id: taskId },\n          )\n        }\n        return observation.data\n      }\n\n      const remaining = (ctx.deadline ?? Date.now()) - Date.now()\n      if (remaining <= 0) {\n        throw new ToolError(\n          'TIMEOUT',\n          `timed out waiting for task ${taskId}`,\n          EXIT_TIMEOUT,\n          true,\n          { task_id: taskId },\n        )\n      }\n      const interval = Math.min(pollIntervalMs, remaining)\n      if (reader) await reader.pullEvent(interval)\n      else await sleep(interval, ctx.signal)\n    }\n  } finally {\n    await reader?.close().catch(() => undefined)\n  }\n}\n\nasync function observeTask(ctx: CommandContext, taskId: string): Promise<TaskObservation> {\n  const response = await ctx.clients.call<unknown>(\n    TASK_MANAGER_SERVICE,\n    'get_task',\n    { task_id: taskId },\n    rpcOptions(ctx),\n  )\n  const envelope = expectObject(response, 'TaskManager get_task response')\n  const task = expectObject(envelope.task ?? envelope, 'TaskManager task')\n  const phase = expectString(task.phase, 'task.phase')\n  const outcome = optionalString(task.outcome)\n  const taskError = isObject(task.error) ? task.error : undefined\n  return {\n    revision: typeof task.revision === 'number' ? task.revision : undefined,\n    phase,\n    outcome,\n    message: optionalString(task.message),\n    error: taskError\n      ? {\n        code: optionalString(taskError.code),\n        message: optionalString(taskError.message),\n        retryable: typeof taskError.retryable === 'boolean' ? taskError.retryable : undefined,\n        details: isObject(taskError.detail) ? taskError.detail : undefined,\n      }\n      : undefined,\n    progress: task.progress,\n    data: task,\n  }\n}\n\nfunction rpcOptions(ctx: CommandContext): {\n  traceId: string\n  timeoutMs: number\n  signal: AbortSignal\n} {\n  return {\n    traceId: ctx.traceId,\n    timeoutMs: Math.max(1, (ctx.deadline ?? Date.now()) - Date.now()),\n    signal: ctx.signal,\n  }\n}\n\nfunction normalizeTaskErrorCode(code: string | undefined, outcome: string | undefined): string {\n  if (code) return code.trim().replaceAll(/[^A-Za-z0-9]+/g, '_').toUpperCase()\n  return outcome === 'Canceled' ? 'CANCELED' : 'TASK_FAILED'\n}\n\nfunction optionalString(value: unknown): string | undefined {\n  return typeof value === 'string' ? value : undefined\n}\n\nfunction expectString(value: unknown, label: string): string {\n  if (typeof value !== 'string' || !value) {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `${label} must be a string`, 9)\n  }\n  return value\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction expectObject(value: unknown, label: string): Record<string, unknown> {\n  if (!isObject(value)) {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `${label} must be an object`, 9)\n  }\n  return value\n}\n\nfunction abortableSleep(milliseconds: number, signal: AbortSignal): Promise<void> {\n  if (signal.aborted) {\n    return Promise.reject(new ToolError('CANCELED', 'operation canceled', EXIT_TIMEOUT))\n  }\n  return new Promise((resolve, reject) => {\n    const timer = setTimeout(() => {\n      signal.removeEventListener('abort', onAbort)\n      resolve()\n    }, milliseconds)\n    const onAbort = () => {\n      clearTimeout(timer)\n      reject(new ToolError('CANCELED', 'operation canceled', EXIT_TIMEOUT))\n    }\n    signal.addEventListener('abort', onAbort, { once: true })\n  })\n}\n","import { namelib, ndm_proxy, ndn } from 'buckyos/node'\nimport type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport {\n  EXIT_AUTH,\n  EXIT_INTERNAL,\n  EXIT_OPERATION,\n  EXIT_PERMISSION,\n  EXIT_TIMEOUT,\n  EXIT_UNAVAILABLE,\n  ToolError,\n  UsageError,\n} from '../core/errors.ts'\nimport { type TaskObservation, waitForTask } from '../core/task.ts'\nimport { getHost, type HostFile, type HostFileInfo, isHostError } from '../runtime/host.ts'\n\nconst isAbsolute = (path: string) => getHost().path.isAbsolute(path)\nconst resolve = (...parts: string[]) => getHost().path.resolve(...parts)\n\nconst CONTROL_PANEL_SERVICE = 'control-panel'\nconst PLAN_SCHEMA_VERSION = 4\nconst STAGING_RELEASE_TIMEOUT_MS = 5_000\nconst ZIP_LOCAL_MAGIC = [0x50, 0x4b, 0x03, 0x04] as const\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst INSTALL_POLICIES = [\n  'strict-public',\n  'normal',\n  'trusted-share',\n  'local-developer',\n  'system-internal',\n] as const\n\ntype PikgPurpose = 'inspect' | 'install'\ntype SourceKind = 'catalog' | 'pikg' | 'url'\n\nexport interface PikgSnapshot {\n  kind: 'pikg' | 'url'\n  display: string\n  path: string\n  localFileId?: string\n  digest: string\n  size: number\n}\n\nexport interface PikgStagingMetadata {\n  schema_version: number\n  handle: string\n  pikg_digest: string\n  size: number\n  purpose: PikgPurpose\n  expires_at?: number\n}\n\nexport interface AppModuleDependencies {\n  download?: (url: URL, signal: AbortSignal) => Promise<Uint8Array>\n  stagePikg?: (\n    ctx: CommandContext,\n    snapshot: PikgSnapshot,\n    purpose: PikgPurpose,\n  ) => Promise<PikgStagingMetadata>\n  sleep?: (milliseconds: number, signal: AbortSignal) => Promise<void>\n}\n\ninterface CatalogSource {\n  kind: 'catalog'\n  display: string\n  serviceSource: { kind: 'identifier'; identifier: string }\n}\n\ninterface StagedSource {\n  kind: 'pikg' | 'url'\n  display: string\n  snapshot: PikgSnapshot\n  staging: PikgStagingMetadata\n  serviceSource: { kind: 'local_pikg'; staging_handle: string }\n}\n\ntype PreparedSource = CatalogSource | StagedSource\n\ninterface InstallInspection {\n  schema_version: number\n  plan: Record<string, unknown>\n  resolution_status: Record<string, unknown>\n  status: Record<string, unknown>\n}\n\nexport function createAppModule(dependencies: AppModuleDependencies = {}): CommandModule {\n  const commands = [\n    fetchCommand(dependencies),\n    listCommand(),\n    getCommand(),\n    installCommand(dependencies),\n    upgradeCommand(dependencies),\n    uninstallCommand(dependencies),\n    cancelCommand(),\n    lifecycleCommand('start', 'Start an installed App'),\n    lifecycleCommand('stop', 'Stop an installed App'),\n    restartCommand(),\n    statusCommand(),\n    publishCommand(),\n  ]\n  return {\n    name: 'app',\n    summary: 'Inspect, install, upgrade, and control Apps',\n    commands: commands.map((command) => {\n      const handler = command.handler\n      return {\n        ...command,\n        handler: async (ctx, input) => sanitizeAppOutput(await handler(ctx, input)),\n      }\n    }),\n  }\n}\n\nfunction cancelCommand(): CommandDefinition {\n  return {\n    verb: 'cancel',\n    summary: 'Cancel an installation or upgrade task and release its App mutation',\n    positionals: [{ name: 'task_id', description: 'Installation Task ID', required: true }],\n    options: [{\n      name: 'force',\n      description: 'Defer staging cleanup after cancellation',\n      type: 'boolean',\n    }],\n    inputSchema: {\n      type: 'object',\n      properties: { task_id: { type: 'string', minLength: 1 }, force: { type: 'boolean' } },\n      required: ['task_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos app cancel t-0123456789abcdef0123456789abcdef --force'],\n    handler: async (ctx, input) =>\n      await callControl(ctx, 'apps.install.cancel', {\n        task_id: expectString(input, 'task_id'),\n        force: input.force === true,\n      }),\n  }\n}\n\nfunction fetchCommand(dependencies: AppModuleDependencies): CommandDefinition {\n  return {\n    verb: 'fetch',\n    summary: 'Inspect an App source and optionally write a fresh-install plan',\n    positionals: [\n      {\n        name: 'source',\n        description: 'Catalog name/DID, local PIKG path, or HTTP(S) URL',\n        required: false,\n      },\n    ],\n    options: sourceOptions([\n      { name: 'plan', description: 'Write the v4 InstallPlan to this JSON file', type: 'string' },\n      ownerOption(),\n      policyOption(),\n    ]),\n    inputSchema: sourceInputSchema({\n      plan: { type: 'string', minLength: 1 },\n      owner_user_id: { type: 'string', minLength: 1 },\n      policy: { type: 'string', enum: [...INSTALL_POLICIES] },\n      target: { type: 'object', additionalProperties: true },\n      install_params: { type: 'object', additionalProperties: true },\n    }),\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: [\n      'buckyos app fetch did:bns:app1.alice',\n      'buckyos app fetch ./demo-0.1.0.pikg --plan ./demo.install-plan.json',\n    ],\n    handler: async (ctx, input) => await fetchApp(ctx, input, dependencies),\n  }\n}\n\nfunction listCommand(): CommandDefinition {\n  return {\n    verb: 'list',\n    summary: 'List visible installed Apps',\n    inputSchema: emptyInputSchema(),\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos app list'],\n    handler: async (ctx) => await callControl(ctx, 'apps.list', {}),\n  }\n}\n\nfunction getCommand(): CommandDefinition {\n  return selectorCommand({\n    verb: 'get',\n    summary: 'Get installation and runtime details for one App',\n    access: 'read',\n    asyncMode: 'sync',\n    handler: async (ctx, input) => {\n      const selector = normalizeAppSelector(expectString(input, 'app_name'))\n      const [details, status] = await Promise.all([\n        callControl(ctx, 'apps.details', { selector }),\n        callControl(ctx, 'apps.status', { selector }),\n      ])\n      return { details, status }\n    },\n  })\n}\n\nfunction installCommand(dependencies: AppModuleDependencies): CommandDefinition {\n  return {\n    verb: 'install',\n    summary: 'Install from a v4 plan or upgrade an existing App from a source',\n    positionals: [\n      {\n        name: 'source',\n        description: 'Catalog name/DID, local PIKG path, or HTTP(S) URL',\n        required: false,\n      },\n    ],\n    options: sourceOptions([\n      { name: 'plan', description: 'Fresh-install v4 InstallPlan JSON file', type: 'string' },\n      {\n        name: 'dry-run',\n        property: 'dry_run',\n        description: 'Preflight and print without submitting',\n        type: 'boolean',\n      },\n      {\n        name: 'no-wait',\n        property: 'no_wait',\n        description: 'Return immediately after task creation',\n        type: 'boolean',\n      },\n      policyOption(),\n    ]),\n    inputSchema: sourceInputSchema({\n      plan: { type: 'string', minLength: 1 },\n      dry_run: { type: 'boolean' },\n      no_wait: { type: 'boolean' },\n      policy: { type: 'string', enum: [...INSTALL_POLICIES] },\n    }),\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'either',\n    requiresSession: true,\n    examples: [\n      'buckyos app install did:bns:app1.alice --plan ./app1.install-plan.json',\n      'buckyos --yes app install https://example.com/app1-1.2.0.pikg',\n    ],\n    handler: async (ctx, input) => await installApp(ctx, input, dependencies),\n  }\n}\n\nfunction upgradeCommand(dependencies: AppModuleDependencies): CommandDefinition {\n  return {\n    verb: 'upgrade',\n    summary: 'Check and apply Catalog upgrades',\n    positionals: [\n      { name: 'app_name', description: 'Installed App name or DID; omit for all', required: false },\n    ],\n    options: [\n      {\n        name: 'dry-run',\n        property: 'dry_run',\n        description: 'Only show the upgrade preflight',\n        type: 'boolean',\n      },\n      {\n        name: 'no-wait',\n        property: 'no_wait',\n        description: 'Return immediately after task creation',\n        type: 'boolean',\n      },\n      policyOption(),\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        app_name: { type: 'string', minLength: 1 },\n        dry_run: { type: 'boolean' },\n        no_wait: { type: 'boolean' },\n        policy: { type: 'string', enum: [...INSTALL_POLICIES] },\n      },\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'either',\n    requiresSession: true,\n    examples: ['buckyos app upgrade', 'buckyos --yes app upgrade did:bns:app1.alice'],\n    handler: async (ctx, input) => await upgradeApps(ctx, input, dependencies),\n  }\n}\n\nfunction uninstallCommand(dependencies: AppModuleDependencies): CommandDefinition {\n  return {\n    ...selectorCommand({\n      verb: 'uninstall',\n      summary: 'Uninstall an App and explicitly retain or delete its managed data',\n      access: 'destructive',\n      asyncMode: 'task',\n      handler: async (ctx, input) => await uninstallApp(ctx, input, dependencies),\n    }),\n    options: [\n      {\n        name: 'data',\n        description: 'Managed data disposition',\n        type: 'string',\n        required: true,\n        enum: ['retain', 'delete'],\n      },\n      {\n        name: 'dry-run',\n        property: 'dry_run',\n        description: 'Only show the uninstall preflight',\n        type: 'boolean',\n      },\n      {\n        name: 'no-wait',\n        property: 'no_wait',\n        description: 'Return immediately after task creation',\n        type: 'boolean',\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        app_name: { type: 'string', minLength: 1 },\n        data: { type: 'string', enum: ['retain', 'delete'] },\n        dry_run: { type: 'boolean' },\n        no_wait: { type: 'boolean' },\n      },\n      required: ['app_name', 'data'],\n      additionalProperties: false,\n    },\n    examples: ['buckyos app uninstall app1 --data retain'],\n  }\n}\n\nfunction lifecycleCommand(verb: 'start' | 'stop', summary: string): CommandDefinition {\n  return {\n    ...selectorCommand({\n      verb,\n      summary,\n      access: 'write',\n      asyncMode: verb === 'start' ? 'task' : 'either',\n      handler: async (ctx, input) => await mutateLifecycle(ctx, input, verb),\n    }),\n    options: [\n      {\n        name: 'no-wait',\n        property: 'no_wait',\n        description: 'Return immediately after task creation',\n        type: 'boolean',\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        app_name: { type: 'string', minLength: 1 },\n        no_wait: { type: 'boolean' },\n      },\n      required: ['app_name'],\n      additionalProperties: false,\n    },\n  }\n}\n\nfunction restartCommand(): CommandDefinition {\n  return {\n    ...selectorCommand({\n      verb: 'restart',\n      summary: 'Recreate the runtime instances for an installed App',\n      access: 'write',\n      asyncMode: 'task',\n      handler: async (ctx, input) => await mutateLifecycle(ctx, input, 'restart'),\n    }),\n    options: [\n      {\n        name: 'strategy',\n        description: 'Restart strategy; rolling is currently unsupported',\n        type: 'string',\n        enum: ['recreate', 'rolling'],\n      },\n      {\n        name: 'no-wait',\n        property: 'no_wait',\n        description: 'Return immediately after task creation',\n        type: 'boolean',\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        app_name: { type: 'string', minLength: 1 },\n        strategy: { type: 'string', enum: ['recreate', 'rolling'] },\n        no_wait: { type: 'boolean' },\n      },\n      required: ['app_name'],\n      additionalProperties: false,\n    },\n    examples: ['buckyos app restart app1'],\n  }\n}\n\nfunction statusCommand(): CommandDefinition {\n  return {\n    verb: 'status',\n    summary: 'Show desired, task, scheduled, runtime, version, and readiness state',\n    positionals: [\n      { name: 'app_name', description: 'Installed App name or DID; omit for all', required: false },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: { app_name: { type: 'string', minLength: 1 } },\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos app status', 'buckyos app status did:bns:app1.alice'],\n    handler: async (ctx, input) => {\n      if (typeof input.app_name === 'string') {\n        const selector = normalizeAppSelector(input.app_name)\n        const [status, details] = await Promise.all([\n          callControl(ctx, 'apps.status', { selector }),\n          callControl(ctx, 'apps.details', { selector }),\n        ])\n        const detailObject = expectObject(details, 'apps.details response')\n        const summary = expectObject(detailObject.summary, 'apps.details summary')\n        return {\n          ...expectObject(status, 'apps.status response'),\n          web_hosts: Array.isArray(summary.web_hosts) ? summary.web_hosts : [],\n        }\n      }\n      const listed = expectObject(await callControl(ctx, 'apps.list', {}), 'apps.list response')\n      const apps = Array.isArray(listed.apps) ? listed.apps : []\n      const items = await Promise.all(apps.map(async (item) => {\n        const app = expectObject(item, 'apps.list item')\n        const selector = expectString(app, 'app_instance_id')\n        return {\n          ...expectObject(\n            await callControl(ctx, 'apps.status', { selector }),\n            'apps.status response',\n          ),\n          web_hosts: Array.isArray(app.web_hosts) ? app.web_hosts : [],\n        }\n      }))\n      return { total: items.length, items }\n    },\n  }\n}\n\nfunction publishCommand(): CommandDefinition {\n  return {\n    verb: 'publish',\n    summary: 'Package a directory on the control-panel node into the Zone Repo as an App candidate',\n    description:\n      'Calls control-panel app.publish: packages <local_dir> (a path on the control-panel node; nothing is uploaded) with the AppDoc template, stores PackageMeta and the AppDoc in the Zone Repo/NamedStore, and stages a self-checked PIKG there. The AppDoc is not Owner-signed and no BNS/App DID record is updated, so this is not an authoritative App release.',\n    positionals: [\n      { name: 'local_dir', description: 'Absolute source directory on the control-panel node' },\n    ],\n    options: [\n      {\n        name: 'app-doc',\n        property: 'app_doc',\n        description: 'AppDoc template JSON file (pkg_list entries without pkg_objid)',\n        type: 'string',\n        required: true,\n      },\n      {\n        name: 'app-type',\n        property: 'app_type',\n        description: 'App type; defaults to the template app_type',\n        type: 'string',\n        enum: ['dapp', 'web', 'agent', 'ext_tools'],\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        local_dir: { type: 'string', minLength: 1 },\n        app_doc: { type: 'string', minLength: 1 },\n        app_type: { type: 'string', enum: ['dapp', 'web', 'agent', 'ext_tools'] },\n      },\n      required: ['local_dir', 'app_doc'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: [\n      'buckyos app publish /srv/build/demo-web --app-doc ./demo-web.appdoc.json',\n      'buckyos app publish /srv/build/demo-agent --app-doc ./demo-agent.appdoc.json --app-type agent',\n      'buckyos app publish /srv/build/ext-media --app-doc ./dapp_dist/APPDOC.json',\n    ],\n    handler: async (ctx, input) => {\n      const localDir = expectString(input, 'local_dir')\n      if (!isAbsolute(localDir)) {\n        throw new UsageError(\n          'INVALID_ARGUMENT',\n          'local_dir must be an absolute path on the control-panel node',\n        )\n      }\n      let appDoc: unknown\n      try {\n        appDoc = JSON.parse(\n          await getHost().readTextFile(resolveFromCwd(ctx, expectString(input, 'app_doc'))),\n        )\n      } catch (error) {\n        throw new UsageError(\n          'INVALID_APP_DOC',\n          `failed to read AppDoc template: ${errorMessage(error)}`,\n        )\n      }\n      if (!isObject(appDoc)) {\n        throw new UsageError('INVALID_APP_DOC', 'AppDoc template must be a JSON object')\n      }\n      const result = expectObject(\n        await callControl(ctx, 'app.publish', {\n          local_dir: localDir,\n          app_doc: appDoc,\n          ...(typeof input.app_type === 'string' ? { app_type: input.app_type } : {}),\n        }),\n        'app.publish response',\n      )\n      const { ok: _ok, ...published } = result\n      return {\n        ...published,\n        publish_status: expectString(result, 'publish_status'),\n        app_doc_signature: 'not-signed',\n        app_did_publication: 'not-published',\n      }\n    },\n  }\n}\n\nasync function fetchApp(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  dependencies: AppModuleDependencies,\n): Promise<Record<string, unknown>> {\n  const source = await prepareSource(ctx, input, 'inspect', dependencies)\n  try {\n    let inspection = await inspectSource(ctx, source, input)\n    const planPathInput = optionalString(input.plan)\n    let planPath: string | undefined\n    if (planPathInput) {\n      inspection = await finalizePlanChoices(ctx, source, input, inspection)\n      const plan = inspection.plan\n      assertPortablePlan(plan)\n      planPath = resolveFromCwd(ctx, planPathInput)\n      await writePlanFile(ctx, planPath, plan)\n    }\n    return {\n      source: sourceSummary(source),\n      app: inspection.plan.app,\n      source_identity: inspection.plan.source_identity,\n      resolution: inspection.resolution_status,\n      status: inspection.status,\n      plan_path: planPath ?? null,\n      plan_fingerprint: planPath ? inspection.plan.plan_fingerprint : null,\n    }\n  } finally {\n    await releaseStaging(ctx, source)\n  }\n}\n\nasync function installApp(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  dependencies: AppModuleDependencies,\n): Promise<Record<string, unknown>> {\n  rejectDryRunNoWait(input)\n  const submittedPlan = optionalString(input.plan)\n    ? await readPlanFile(resolveFromCwd(ctx, String(input.plan)))\n    : undefined\n  const source = await prepareSource(ctx, input, 'install', dependencies)\n  let keepStaging = false\n  try {\n    let inspection = submittedPlan\n      ? await recomputePlan(ctx, source, input, submittedPlan)\n      : await inspectSource(ctx, source, input)\n    verifyPikgBinding(source, submittedPlan ?? inspection.plan)\n    if ((inspection.plan.app_doc as Record<string, unknown> | undefined)?.app_type === 'ext_tools') {\n      throw new ToolError(\n        'EXT_TOOLS_NOT_AN_APP',\n        'an extension tool package is not installed as an App: publish it to the Repo with `buckyos app publish`, then enable it for the Zone on the management page',\n      )\n    }\n    const app = expectObject(inspection.plan.app, 'inspection.plan.app')\n    const appDid = expectString(app, 'did')\n    const plannedOwner = submittedPlan ? expectString(submittedPlan, 'owner_user_id') : undefined\n    const installed = await findInstalled(ctx, appDid, plannedOwner)\n\n    if (submittedPlan && installed) {\n      throw new ToolError(\n        'PLAN_NOT_APPLICABLE',\n        'a fresh-install plan cannot be applied over an installed App',\n      )\n    }\n    if (!submittedPlan && !installed) {\n      throw new ToolError(\n        'PLAN_REQUIRED',\n        `App is not installed; run app fetch ${source.display} --plan <path> first`,\n      )\n    }\n\n    if (submittedPlan) {\n      assertPlanMatchesInspection(submittedPlan, inspection)\n    } else {\n      const scope = installedScope(installed!)\n      inspection = await inspectSource(ctx, source, input, { ...scope, action: 'upgrade' })\n      verifyPikgBinding(source, inspection.plan)\n    }\n\n    if (input.dry_run === true) {\n      return {\n        action: 'dry_run',\n        source: sourceSummary(source),\n        plan: inspection.plan,\n        status: inspection.status,\n      }\n    }\n\n    if (planUse(inspection.plan) === 'SATISFIED') {\n      return satisfiedResult(inspection)\n    }\n    await confirmChange(ctx, 'install', confirmationSummary(inspection))\n    const params = {\n      ...sourceRpcParams(source),\n      ...planScopeAndOptions(inspection.plan),\n      options: installOptions(input),\n      plan: submittedPlan ?? inspection.plan,\n      approved_plan_fingerprint: expectString(inspection.plan, 'plan_fingerprint'),\n      idempotency_key: idempotencyKey(ctx),\n    }\n    const submitted = expectObject(\n      await callControl(ctx, 'apps.submit', params),\n      'apps.submit response',\n    )\n    if (submitted.action === 'satisfied' || submitted.task_id === null) {\n      return submitted\n    }\n    const taskId = expectString(submitted, 'task_id')\n    keepStaging = true\n    if (input.no_wait === true) return submitted\n    try {\n      const status = await waitForTask(ctx, taskId, {\n        observe: observeInstallTask,\n        sleep: dependencies.sleep,\n      })\n      return { ...submitted, status }\n    } finally {\n      keepStaging = false\n    }\n  } finally {\n    if (!keepStaging) await releaseStaging(ctx, source)\n  }\n}\n\nasync function upgradeApps(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  dependencies: AppModuleDependencies,\n): Promise<Record<string, unknown>> {\n  rejectDryRunNoWait(input)\n  const selector = typeof input.app_name === 'string'\n    ? normalizeAppSelector(input.app_name)\n    : undefined\n  const check = expectObject(\n    await callControl(ctx, 'apps.upgrade.check', selector ? { selector } : {}),\n    'apps.upgrade.check response',\n  )\n  const items = Array.isArray(check.items) ? check.items : []\n  const actionable = items.filter((value) => {\n    const item = isObject(value) ? value : {}\n    return item.state === 'UPDATE_AVAILABLE' || item.state === 'PERMISSION_RECONFIRM_REQUIRED'\n  })\n\n  if (input.dry_run === true) return { action: 'dry_run', check }\n  if (actionable.length === 0) return { action: 'satisfied', total: items.length, items }\n\n  await confirmChange(ctx, 'upgrade', {\n    total: items.length,\n    update_count: actionable.length,\n    items,\n  })\n\n  let submitted: Record<string, unknown>\n  let installTask = false\n  if (selector) {\n    const item = expectObject(actionable[0], 'upgrade item')\n    const appDid = expectString(item, 'app_did')\n    const details = await findInstalled(ctx, appDid)\n    if (!details) throw new ToolError('RESOURCE_NOT_FOUND', `App is not installed: ${appDid}`)\n    const source: CatalogSource = {\n      kind: 'catalog',\n      display: appDid,\n      serviceSource: { kind: 'identifier', identifier: appDid },\n    }\n    const inspection = await inspectSource(ctx, source, input, {\n      ...installedScope(details),\n      action: 'upgrade',\n    })\n    submitted = expectObject(\n      await callControl(ctx, 'apps.submit', {\n        ...sourceRpcParams(source),\n        ...planScopeAndOptions(inspection.plan),\n        options: installOptions(input),\n        plan: inspection.plan,\n        approved_plan_fingerprint: expectString(inspection.plan, 'plan_fingerprint'),\n        idempotency_key: idempotencyKey(ctx),\n      }),\n      'apps.submit response',\n    )\n    installTask = submitted.task_id !== null\n  } else {\n    submitted = expectObject(\n      await callControl(ctx, 'apps.upgrade', { idempotency_key: idempotencyKey(ctx) }),\n      'apps.upgrade response',\n    )\n  }\n  if (submitted.task_id === null || submitted.action === 'satisfied') return submitted\n  const taskId = expectString(submitted, 'task_id')\n  if (input.no_wait === true) return submitted\n  const status = await waitForTask(ctx, taskId, {\n    observe: installTask ? observeInstallTask : undefined,\n    sleep: dependencies.sleep,\n  })\n  return { ...submitted, status }\n}\n\nasync function uninstallApp(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  dependencies: AppModuleDependencies,\n): Promise<Record<string, unknown>> {\n  rejectDryRunNoWait(input)\n  const selector = normalizeAppSelector(expectString(input, 'app_name'))\n  const status = await callControl(ctx, 'apps.status', { selector })\n  const preflight = { action: 'uninstall', data_disposition: input.data, status }\n  if (input.dry_run === true) return { action: 'dry_run', preflight }\n  await confirmChange(ctx, 'uninstall', preflight)\n  const submitted = expectObject(\n    await callControl(ctx, 'apps.uninstall', {\n      selector,\n      data_disposition: input.data,\n      idempotency_key: idempotencyKey(ctx),\n    }),\n    'apps.uninstall response',\n  )\n  const taskId = expectString(submitted, 'task_id')\n  if (input.no_wait === true) return submitted\n  const task = await waitForTask(ctx, taskId, { sleep: dependencies.sleep })\n  return { ...submitted, status: task }\n}\n\nasync function mutateLifecycle(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  verb: 'start' | 'stop' | 'restart',\n): Promise<Record<string, unknown>> {\n  if (input.strategy === 'rolling') {\n    throw new ToolError(\n      'UNSUPPORTED_STRATEGY',\n      'rolling restart is not supported by the current deployment strategy',\n    )\n  }\n  const selector = normalizeAppSelector(expectString(input, 'app_name'))\n  const submitted = expectObject(\n    await callControl(ctx, `apps.${verb}`, {\n      selector,\n      idempotency_key: idempotencyKey(ctx),\n      ...(verb === 'restart' ? { restart_strategy: input.strategy ?? 'recreate' } : {}),\n    }),\n    `apps.${verb} response`,\n  )\n  const taskId = expectString(submitted, 'task_id')\n  if (input.no_wait === true) return submitted\n  const task = await waitForTask(ctx, taskId)\n  return { ...submitted, status: task }\n}\n\n/** A local `.pikg` staged for an inspection or import that is not an App install. */\nexport async function stageLocalPikg(ctx: CommandContext, path: string): Promise<PikgStagingMetadata> {\n  const prepared = await prepareSource(ctx, { pikg: path }, 'inspect', {})\n  if (prepared.kind === 'catalog') throw new UsageError('INVALID_PIKG_SOURCE', 'not a local PIKG')\n  return prepared.staging\n}\n\nasync function prepareSource(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  purpose: PikgPurpose,\n  dependencies: AppModuleDependencies,\n): Promise<PreparedSource> {\n  const classified = await classifySource(ctx, input)\n  if (classified.kind === 'catalog') return classified\n\n  const host = getHost()\n  const localDirectory = localPikgDirectory(ctx)\n  let directory: string\n  let localFileId: string | undefined\n  if (localDirectory) {\n    try {\n      await host.mkdir(localDirectory, { recursive: true, mode: 0o700 })\n      directory = localDirectory\n      localFileId = crypto.randomUUID().replaceAll('-', '')\n    } catch (error) {\n      if (!isHostError(error, 'PermissionDenied') && !isHostError(error, 'NotFound')) throw error\n    }\n  }\n  if (!localFileId) {\n    await host.mkdir(ctx.configStore.root, { recursive: true, mode: 0o700 })\n    directory = await host.makeTempDir({ dir: ctx.configStore.root, prefix: '.pikg-' })\n  }\n  let path = host.path.join(directory!, `${localFileId ?? 'source'}.pikg`)\n  const snapshotAt = (destination: string) =>\n    classified.kind === 'url'\n      ? downloadPikg(classified.url, destination, dependencies.download, ctx.signal)\n      : readPikg(classified.path, destination, ctx.signal)\n  try {\n    let snapshot: PikgSnapshot\n    try {\n      snapshot = await snapshotAt(path)\n    } catch (error) {\n      if (!localFileId || !isHostError(error, 'PermissionDenied')) throw error\n      await host.remove(path).catch(() => {})\n      localFileId = undefined\n      await host.mkdir(ctx.configStore.root, { recursive: true, mode: 0o700 })\n      directory = await host.makeTempDir({ dir: ctx.configStore.root, prefix: '.pikg-' })\n      path = host.path.join(directory, 'source.pikg')\n      snapshot = await snapshotAt(path)\n    }\n    snapshot.localFileId = localFileId\n    const stage = dependencies.stagePikg ?? stagePikg\n    const metadata = await stage(ctx, snapshot, purpose)\n    if (metadata.schema_version !== PLAN_SCHEMA_VERSION) {\n      throw new ToolError('UNSUPPORTED_SCHEMA_VERSION', 'staging returned a non-v4 schema')\n    }\n    if (metadata.pikg_digest !== snapshot.digest || metadata.size !== snapshot.size) {\n      throw new ToolError(\n        'PIKG_DIGEST_MISMATCH',\n        'the staged PIKG does not match the client byte snapshot',\n        EXIT_OPERATION,\n        false,\n        {\n          expected_digest: snapshot.digest,\n          staged_digest: metadata.pikg_digest,\n          expected_size: snapshot.size,\n          staged_size: metadata.size,\n        },\n      )\n    }\n    if (metadata.purpose !== purpose) {\n      throw new ToolError(\n        'INVALID_SERVICE_RESPONSE',\n        'staging purpose does not match the request',\n        9,\n      )\n    }\n    return {\n      kind: snapshot.kind,\n      display: snapshot.display,\n      snapshot,\n      staging: metadata,\n      serviceSource: { kind: 'local_pikg', staging_handle: metadata.handle },\n    }\n  } finally {\n    await host.remove(localFileId ? path : directory!, { recursive: !localFileId })\n      .catch(() => {})\n  }\n}\n\nexport async function classifySource(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n): Promise<\n  | CatalogSource\n  | { kind: 'pikg'; path: string }\n  | { kind: 'url'; url: URL }\n> {\n  const positional = optionalString(input.source)\n  const pikg = optionalString(input.pikg)\n  if (positional && pikg) {\n    throw new UsageError('ARGUMENT_CONFLICT', '<source> and --pikg are mutually exclusive')\n  }\n  const raw = pikg ?? positional\n  if (!raw) throw new UsageError('MISSING_ARGUMENT', 'source or --pikg is required')\n  const forced = pikg ? 'pikg' : optionalString(input.from)\n  if (pikg && forced && forced !== 'pikg') {\n    throw new UsageError('ARGUMENT_CONFLICT', '--pikg conflicts with --from')\n  }\n\n  if (forced === 'url') return { kind: 'url', url: parsePikgUrl(raw) }\n  if (forced === 'pikg') return { kind: 'pikg', path: resolveFromCwd(ctx, raw) }\n  if (forced === 'catalog') {\n    return {\n      kind: 'catalog',\n      display: normalizeCatalogIdentifier(raw),\n      serviceSource: { kind: 'identifier', identifier: normalizeCatalogIdentifier(raw) },\n    }\n  }\n  if (forced) throw new UsageError('INVALID_ARGUMENT', `invalid --from value: ${forced}`)\n\n  if (/^https?:\\/\\//i.test(raw)) return { kind: 'url', url: parsePikgUrl(raw) }\n  // A DID is never a local file. Probing it as one is not harmless: Windows\n  // reads `did:bns:x` as an alternate data stream and stat fails with an\n  // invalid-name error instead of NotFound.\n  if (isDidSource(raw)) {\n    const identifier = normalizeCatalogIdentifier(raw)\n    return { kind: 'catalog', display: identifier, serviceSource: { kind: 'identifier', identifier } }\n  }\n  const candidatePath = resolveFromCwd(ctx, raw)\n  const stat = await tryLstat(candidatePath)\n  if (stat) {\n    if (!stat.isFile) {\n      throw new UsageError('INVALID_PIKG_SOURCE', `PIKG source is not a regular file: ${raw}`)\n    }\n    return { kind: 'pikg', path: candidatePath }\n  }\n  if (looksLikeLocalPath(raw)) {\n    throw new UsageError('PIKG_NOT_FOUND', `PIKG source does not exist: ${raw}`)\n  }\n  const identifier = normalizeCatalogIdentifier(raw)\n  return {\n    kind: 'catalog',\n    display: identifier,\n    serviceSource: { kind: 'identifier', identifier },\n  }\n}\n\nfunction localPikgDirectory(ctx: CommandContext): string | undefined {\n  const root = getHost().policy.buckyosRoot\n  const hostname = new URL(ctx.connection.endpoint).hostname\n  if (!root || !['localhost', '127.0.0.1', '[::1]'].includes(hostname)) return undefined\n  return getHost().path.join(root, 'cache', 'control_panel', 'pikg_staging', 'incoming')\n}\n\nasync function* fileChunks(file: HostFile, size: number): AsyncGenerator<Uint8Array> {\n  const buffer = new Uint8Array(size)\n  while (true) {\n    let used = 0\n    while (used < buffer.length) {\n      const read = await file.read(buffer.subarray(used))\n      if (read === null) break\n      if (read === 0) throw new UsageError('PIKG_READ_FAILED', 'PIKG read made no progress')\n      used += read\n    }\n    if (used === 0) break\n    yield buffer.subarray(0, used)\n  }\n}\n\nasync function writePikgSnapshot(\n  path: string,\n  chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>,\n  signal: AbortSignal,\n): Promise<{ path: string; digest: string; size: number }> {\n  const output = await getHost().open(path, { write: true, createNew: true, mode: 0o600 })\n  const hash = getHost().createHash('sha256')\n  const magic = new Uint8Array(ZIP_LOCAL_MAGIC.length)\n  let size = 0\n  try {\n    for await (const chunk of chunks) {\n      signal.throwIfAborted()\n      if (size < magic.length) magic.set(chunk.subarray(0, magic.length - size), size)\n      hash.update(chunk)\n      size += chunk.length\n      if (!Number.isSafeInteger(size)) throw new UsageError('PIKG_TOO_LARGE', 'PIKG is too large')\n      let offset = 0\n      while (offset < chunk.length) {\n        const written = await output.write(chunk.subarray(offset))\n        if (written === 0) throw new UsageError('PIKG_WRITE_FAILED', 'PIKG write made no progress')\n        offset += written\n      }\n    }\n    validatePikgSnapshot(magic.subarray(0, Math.min(size, magic.length)))\n    await output.sync()\n    return { path, size, digest: hash.digestHex() }\n  } finally {\n    await output.close()\n  }\n}\n\nasync function readPikg(\n  source: string,\n  destination: string,\n  signal: AbortSignal,\n): Promise<PikgSnapshot> {\n  let file: HostFile\n  try {\n    file = await getHost().open(source, { read: true })\n  } catch (error) {\n    throw new UsageError('PIKG_READ_FAILED', `failed to open PIKG: ${errorMessage(error)}`)\n  }\n  try {\n    const before = await file.stat()\n    if (!before.isFile) throw new UsageError('INVALID_PIKG_SOURCE', 'PIKG source is not a file')\n    const snapshot = await writePikgSnapshot(destination, fileChunks(file, 256 * 1024), signal)\n    const after = await file.stat()\n    if (\n      snapshot.size !== before.size || before.size !== after.size ||\n      before.mtime?.getTime() !== after.mtime?.getTime()\n    ) {\n      throw new UsageError('PIKG_READ_FAILED', 'PIKG changed while being read')\n    }\n    return { kind: 'pikg', display: source, ...snapshot }\n  } finally {\n    await file.close()\n  }\n}\n\nexport async function downloadPikg(\n  url: URL,\n  destination: string,\n  downloader: AppModuleDependencies['download'],\n  signal: AbortSignal,\n): Promise<PikgSnapshot> {\n  let chunks: Uint8Array[] | ReadableStream<Uint8Array> | undefined\n  try {\n    chunks = downloader ? [await downloader(url, signal)] : await defaultDownload(url, signal)\n    const snapshot = await writePikgSnapshot(destination, chunks, signal)\n    return { kind: 'url', display: safeUrl(url), ...snapshot }\n  } catch (error) {\n    if (error instanceof ToolError || isHostError(error, 'PermissionDenied')) throw error\n    signal.throwIfAborted()\n    throw new ToolError(\n      'PIKG_DOWNLOAD_FAILED',\n      `failed to download PIKG: ${errorMessage(error)}`,\n      5,\n      true,\n    )\n  } finally {\n    if (chunks instanceof ReadableStream && !chunks.locked) await chunks.cancel().catch(() => {})\n  }\n}\n\nasync function defaultDownload(url: URL, signal: AbortSignal): Promise<ReadableStream<Uint8Array>> {\n  const response = await fetch(url, { method: 'GET', redirect: 'follow', signal })\n  if (!response.ok || !response.body) {\n    await response.body?.cancel()\n    throw new ToolError(\n      'PIKG_DOWNLOAD_FAILED',\n      `PIKG download returned HTTP ${response.status}`,\n      5,\n      response.status >= 500,\n    )\n  }\n  return response.body\n}\n\nasync function stagePikg(\n  ctx: CommandContext,\n  snapshot: PikgSnapshot,\n  purpose: PikgPurpose,\n): Promise<PikgStagingMetadata> {\n  const identity = { pikg_digest: snapshot.digest, size: snapshot.size, purpose }\n  if (snapshot.localFileId) {\n    try {\n      const value = expectObject(\n        await callControl(ctx, 'apps.staging.finalize', {\n          ...identity,\n          local_file_id: snapshot.localFileId,\n        }),\n        'apps.staging.finalize response',\n      )\n      return parseStagingMetadata(value)\n    } catch (error) {\n      if (!errorMessage(error).includes('LOCAL_PIKG_UNAVAILABLE')) throw error\n    }\n  }\n  const session = ctx.session\n  if (!session) throw new ToolError('AUTH_REQUIRED', 'authenticated session is required', 3)\n  const token = (await session.ensureValid()).token\n  const proxy = ndm_proxy.createNdmProxyClient({\n    endpoint: gatewayOrigin(ctx.connection.endpoint),\n    sessionToken: token,\n    fetcher: (request: RequestInfo | URL, init?: RequestInit) =>\n      fetch(normalizeNdmRequestUrl(request), { ...init, signal: ctx.signal }),\n  })\n  let fileObjectId: string\n  try {\n    const file = await getHost().open(snapshot.path, { read: true })\n    const chunks = new ndn.SimpleChunkList()\n    const hash = getHost().createHash('sha256')\n    try {\n      for await (const bytes of fileChunks(file, 32 * 1024 * 1024)) {\n        ctx.signal.throwIfAborted()\n        hash.update(bytes)\n        const chunk = ndn.ChunkId.fromMix256Result(bytes.length, ndn.sha256Bytes(bytes))\n        await proxy.putChunk(chunk.toString(), bytes)\n        chunks.appendChunk(chunk)\n      }\n    } finally {\n      await file.close()\n    }\n    if (chunks.total_size !== snapshot.size || hash.digestHex() !== snapshot.digest) {\n      throw new ToolError('PIKG_DIGEST_MISMATCH', 'PIKG snapshot changed during upload')\n    }\n    let content = chunks.body[0].toString()\n    if (chunks.body.length > 1) {\n      const [id, body] = chunks.genObjId()\n      await proxy.putObject({ obj_id: id.toString(), obj_data: body })\n      content = id.toString()\n    }\n    const fileObject = new ndn.FileObject(`${snapshot.digest}.pikg`, snapshot.size, content)\n    const [id, body] = fileObject.genObjId()\n    await proxy.putObject({ obj_id: id.toString(), obj_data: body })\n    fileObjectId = id.toString()\n  } catch (error) {\n    if (error instanceof ToolError) throw error\n    ctx.signal.throwIfAborted()\n    throw new ToolError(\n      'PIKG_UPLOAD_FAILED',\n      `failed to upload PIKG: ${errorMessage(error)}`,\n      5,\n      true,\n    )\n  }\n  const value = expectObject(\n    await callControl(ctx, 'apps.staging.finalize', {\n      ...identity,\n      source_obj_id: fileObjectId,\n    }),\n    'apps.staging.finalize response',\n  )\n  return parseStagingMetadata(value)\n}\n\nfunction parseStagingMetadata(value: Record<string, unknown>): PikgStagingMetadata {\n  return {\n    schema_version: expectNumber(value, 'schema_version'),\n    handle: expectString(value, 'handle'),\n    pikg_digest: expectString(value, 'pikg_digest'),\n    size: expectNumber(value, 'size'),\n    purpose: expectString(value, 'purpose') as PikgPurpose,\n    expires_at: optionalNumber(value.expires_at),\n  }\n}\n\nfunction normalizeNdmRequestUrl(request: RequestInfo | URL): RequestInfo | URL {\n  if (typeof request === 'string') {\n    return request.replaceAll('%3A', ':').replaceAll('%3a', ':')\n  }\n  if (request instanceof URL) {\n    return new URL(request.toString().replaceAll('%3A', ':').replaceAll('%3a', ':'))\n  }\n  return request\n}\n\nasync function inspectSource(\n  ctx: CommandContext,\n  source: PreparedSource,\n  input: Record<string, unknown>,\n  overrides: Record<string, unknown> = {},\n): Promise<InstallInspection> {\n  const result = await callControl(ctx, 'apps.inspect', {\n    ...sourceRpcParams(source),\n    ...scopeAndChoiceParams(input),\n    ...overrides,\n    options: installOptions(input),\n  })\n  return expectInspection(result)\n}\n\nasync function recomputePlan(\n  ctx: CommandContext,\n  source: PreparedSource,\n  input: Record<string, unknown>,\n  plan: Record<string, unknown>,\n  overrides: Record<string, unknown> = {},\n): Promise<InstallInspection> {\n  return expectInspection(\n    await callControl(ctx, 'apps.plan.recompute', {\n      ...sourceRpcParams(source),\n      ...planScopeAndOptions(plan),\n      ...overrides,\n      plan,\n      options: installOptions(input),\n    }),\n  )\n}\n\nasync function finalizePlanChoices(\n  ctx: CommandContext,\n  source: PreparedSource,\n  input: Record<string, unknown>,\n  initial: InstallInspection,\n): Promise<InstallInspection> {\n  let inspection = initial\n  const configReady = readinessValue(inspection, 'config') === 'READY'\n  if (ctx.config.nonInteractive) {\n    if (!configReady && input.target === undefined && input.install_params === undefined) {\n      throw new ToolError(\n        'PLAN_INPUT_REQUIRED',\n        'Installer defaults do not form a complete install plan; provide target/install_params with --input',\n      )\n    }\n    return inspection\n  }\n\n  await ctx.io.stderr(`${JSON.stringify(confirmationSummary(inspection), null, 2)}\\n`)\n  if (!ctx.io.inputIsTerminal || ctx.confirmed) return inspection\n  const answer = (await ctx.io.prompt('Accept default install plan? [Y/e/n] '))?.trim()\n    .toLowerCase()\n  if (answer === 'n' || answer === 'no') {\n    throw new ToolError(\n      'CONFIRMATION_DECLINED',\n      'install plan creation was declined',\n      EXIT_PERMISSION,\n    )\n  }\n  if (answer === 'e' || answer === 'edit') {\n    const raw = await ctx.io.prompt('Plan choices JSON ({\"target\":...,\"install_params\":...}): ')\n    const choices = parsePlanChoices(raw)\n    inspection = await recomputePlan(ctx, source, input, initial.plan, choices)\n  }\n  if (readinessValue(inspection, 'config') !== 'READY') {\n    throw new ToolError(\n      'PLAN_INPUT_REQUIRED',\n      'the selected plan still has unresolved configuration requirements',\n    )\n  }\n  return inspection\n}\n\nasync function findInstalled(\n  ctx: CommandContext,\n  appDid: string,\n  ownerUserId?: string,\n): Promise<Record<string, unknown> | undefined> {\n  try {\n    return expectObject(\n      await callControl(ctx, 'apps.details', {\n        selector: appDid,\n        ...(ownerUserId ? { owner_user_id: ownerUserId } : {}),\n      }),\n      'apps.details response',\n    )\n  } catch (error) {\n    if (error instanceof ToolError && error.code === 'RESOURCE_NOT_FOUND') return undefined\n    throw error\n  }\n}\n\nasync function observeInstallTask(\n  ctx: CommandContext,\n  taskId: string,\n): Promise<TaskObservation> {\n  const status = expectObject(\n    await callControl(ctx, 'apps.install.status', { task_id: taskId }),\n    'apps.install.status response',\n  )\n  const error = isObject(status.error) ? status.error : undefined\n  const sanitizedDetails = error && isObject(error.details)\n    ? sanitizeAppOutput(error.details)\n    : undefined\n  return {\n    phase: expectString(status, 'task_phase'),\n    outcome: optionalString(status.task_outcome),\n    message: installProgressMessage(status),\n    error: error\n      ? {\n        code: optionalString(error.code),\n        message: optionalString(error.message),\n        retryable: typeof error.retryable === 'boolean' ? error.retryable : undefined,\n        details: isObject(sanitizedDetails) ? sanitizedDetails : undefined,\n      }\n      : undefined,\n    data: status,\n  }\n}\n\nasync function confirmChange(\n  ctx: CommandContext,\n  action: string,\n  summary: Record<string, unknown>,\n): Promise<void> {\n  await ctx.io.stderr(`${JSON.stringify({ action, preflight: summary }, null, 2)}\\n`)\n  if (ctx.confirmed) return\n  if (ctx.config.nonInteractive || !ctx.io.inputIsTerminal) {\n    throw new ToolError(\n      'CONFIRMATION_REQUIRED',\n      `${action} requires --yes in non-interactive execution`,\n      EXIT_PERMISSION,\n    )\n  }\n  const answer = (await ctx.io.prompt(`Proceed with app ${action}? [y/N] `))?.trim().toLowerCase()\n  if (answer !== 'y' && answer !== 'yes') {\n    throw new ToolError('CONFIRMATION_DECLINED', `${action} was declined`, EXIT_PERMISSION)\n  }\n}\n\nasync function callControl<T = unknown>(\n  ctx: CommandContext,\n  method: string,\n  params: Record<string, unknown>,\n): Promise<T> {\n  try {\n    return await ctx.clients.call<T>(CONTROL_PANEL_SERVICE, method, params, rpcOptions(ctx))\n  } catch (error) {\n    throw normalizeAppServiceError(error)\n  }\n}\n\nfunction normalizeAppServiceError(error: unknown): ToolError {\n  if (error instanceof ToolError) return error\n  const message = errorMessage(error)\n  const structured = parseEmbeddedJson(message)\n  if (structured && typeof structured.code === 'string') {\n    const rawDetails = isObject(structured.details) ? structured.details : structured\n    const details = sanitizeAppOutput(rawDetails)\n    return new ToolError(\n      structured.code,\n      typeof structured.message === 'string' ? structured.message : message,\n      structured.code === 'AMBIGUOUS_APP_TARGET' ? EXIT_OPERATION : EXIT_OPERATION,\n      structured.retryable === true,\n      isObject(details) ? details : {},\n    )\n  }\n  const lower = message.toLowerCase()\n  if (\n    lower.includes('invalid token') || lower.includes('unauthorized') ||\n    lower.includes('rpc call error: 401') || lower.includes('session expired') ||\n    lower.includes('token expired')\n  ) {\n    return new ToolError(\n      lower.includes('expired') ? 'SESSION_EXPIRED' : 'INVALID_SESSION',\n      lower.includes('expired') ? 'the session token has expired' : message,\n      EXIT_AUTH,\n    )\n  }\n  if (lower.includes('abort') || lower.includes('cancel')) {\n    return new ToolError('CANCELED', 'operation canceled', EXIT_TIMEOUT)\n  }\n  if (lower.includes('timeout') || lower.includes('timed out')) {\n    return new ToolError('TIMEOUT', 'operation timed out', EXIT_TIMEOUT, true)\n  }\n  if (\n    lower.includes('fetch failed') || lower.includes('connection refused') ||\n    lower.includes('rpc call error: 502') || lower.includes('rpc call error: 503') ||\n    lower.includes('rpc call error: 504')\n  ) {\n    return new ToolError('SERVICE_UNAVAILABLE', message, EXIT_UNAVAILABLE, true)\n  }\n  if (message.includes('APP_NOT_INSTALLED') || /not found/i.test(message)) {\n    return new ToolError('RESOURCE_NOT_FOUND', message)\n  }\n  if (/permission|forbidden/i.test(message)) {\n    return new ToolError('PERMISSION_DENIED', message, EXIT_PERMISSION)\n  }\n  if (/rolling restart is not supported/i.test(message)) {\n    return new ToolError('UNSUPPORTED_STRATEGY', message)\n  }\n  return new ToolError('OPERATION_FAILED', message, EXIT_OPERATION)\n}\n\nfunction sourceRpcParams(source: PreparedSource): Record<string, unknown> {\n  return { source: source.serviceSource }\n}\n\nfunction scopeAndChoiceParams(input: Record<string, unknown>): Record<string, unknown> {\n  return {\n    ...(typeof input.owner_user_id === 'string' ? { owner_user_id: input.owner_user_id } : {}),\n    ...(isObject(input.target) ? { target: input.target } : {}),\n    ...(isObject(input.install_params) ? { install_params: input.install_params } : {}),\n  }\n}\n\nfunction planScopeAndOptions(plan: Record<string, unknown>): Record<string, unknown> {\n  return {\n    owner_user_id: expectString(plan, 'owner_user_id'),\n    target: expectObject(plan.target, 'plan.target'),\n    install_params: expectObject(plan.install_params, 'plan.install_params'),\n  }\n}\n\nfunction installedScope(details: Record<string, unknown>): Record<string, unknown> {\n  return {\n    owner_user_id: expectString(details, 'owner_user_id'),\n  }\n}\n\nfunction installOptions(input: Record<string, unknown>): Record<string, unknown> {\n  const policy = optionalString(input.policy) ?? 'normal'\n  return { policy: policy.replaceAll('-', '_').toUpperCase() }\n}\n\nfunction sourceSummary(source: PreparedSource): Record<string, unknown> {\n  if (source.kind === 'catalog') return { kind: source.kind, identifier: source.display }\n  return {\n    kind: source.kind,\n    source: source.display,\n    pikg_digest: source.snapshot.digest,\n    size: source.snapshot.size,\n  }\n}\n\nfunction confirmationSummary(inspection: InstallInspection): Record<string, unknown> {\n  const plan = inspection.plan\n  return {\n    plan_fingerprint: plan.plan_fingerprint,\n    plan_use: plan.plan_use,\n    app: plan.app,\n    app_instance_id: plan.app_instance_id,\n    owner_user_id: plan.owner_user_id,\n    target: plan.target,\n    selected_packages: plan.selected_packages,\n    install_params: plan.install_params,\n    readiness: inspection.status.readiness,\n    warnings: inspection.status.warnings ?? [],\n  }\n}\n\nfunction satisfiedResult(inspection: InstallInspection): Record<string, unknown> {\n  return {\n    action: 'satisfied',\n    task_id: null,\n    app_instance_id: inspection.plan.app_instance_id,\n    app_doc_object_id: expectObject(inspection.plan.app, 'plan.app').object_id,\n  }\n}\n\nfunction assertPlanMatchesInspection(\n  plan: Record<string, unknown>,\n  inspection: InstallInspection,\n): void {\n  const fingerprint = expectString(plan, 'plan_fingerprint')\n  if (fingerprint !== inspection.plan.plan_fingerprint) {\n    throw new ToolError(\n      'PLAN_STALE',\n      'the plan no longer matches the authoritative source, scope, target, or configuration',\n      EXIT_OPERATION,\n      false,\n      {\n        plan_fingerprint: fingerprint,\n        current_fingerprint: inspection.plan.plan_fingerprint,\n      },\n    )\n  }\n}\n\nfunction verifyPikgBinding(\n  source: PreparedSource,\n  plan: Record<string, unknown>,\n): void {\n  if (source.kind === 'catalog') return\n  const identity = expectObject(plan.source_identity, 'plan.source_identity')\n  const digest = expectString(identity, 'pikg_digest')\n  if (digest !== source.snapshot.digest) {\n    throw new ToolError(\n      'PLAN_STALE',\n      'the PIKG byte snapshot does not match the plan source digest',\n      EXIT_OPERATION,\n      false,\n      { plan_digest: digest, source_digest: source.snapshot.digest },\n    )\n  }\n}\n\nfunction assertPortablePlan(plan: Record<string, unknown>): void {\n  if (plan.schema_version !== PLAN_SCHEMA_VERSION) {\n    throw new ToolError(\n      'UNSUPPORTED_SCHEMA_VERSION',\n      `InstallPlan schema must be v${PLAN_SCHEMA_VERSION}`,\n    )\n  }\n  expectString(plan, 'plan_fingerprint')\n  expectString(plan, 'task_id')\n  const allowed = new Set([\n    'schema_version',\n    'plan_use',\n    'task_id',\n    'app_instance_id',\n    'owner_user_id',\n    'source_identity',\n    'app',\n    'app_doc',\n    'resolution',\n    'target',\n    'selected_packages',\n    'required_contents',\n    'install_params',\n    'service_spec_config',\n    'plan_fingerprint',\n    'created_at',\n  ])\n  for (const key of Object.keys(plan)) {\n    if (!allowed.has(key)) {\n      throw new ToolError('PLAN_STALE', `InstallPlan contains an unknown field: ${key}`)\n    }\n  }\n  assertNoPlanSecrets(plan, 'plan')\n}\n\nfunction assertNoPlanSecrets(value: unknown, path: string): void {\n  if (Array.isArray(value)) {\n    value.forEach((item, index) => assertNoPlanSecrets(item, `${path}[${index}]`))\n    return\n  }\n  if (!isObject(value)) return\n  for (const [key, child] of Object.entries(value)) {\n    const normalized = key.toLowerCase()\n    const disallowed = normalized === 'staging_handle' || normalized === 'staging_path' ||\n      normalized === 'session_token' || normalized === 'refresh_token' ||\n      normalized === 'private_key' || normalized === 'password' ||\n      normalized.endsWith('_token') || normalized.endsWith('_password') ||\n      normalized.endsWith('_private_key') ||\n      (normalized.endsWith('secret') && normalized !== 'secret_ref')\n    if (disallowed) {\n      throw new ToolError('INVALID_PLAN_SECRET', `${path}.${key} is forbidden in InstallPlan`)\n    }\n    if (\n      typeof child === 'string' &&\n      (/^[a-z][a-z0-9+.-]*:\\/\\/[^\\s/@:]+:[^\\s/@]+@/i.test(child) ||\n        /^(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis):\\/\\//i.test(child))\n    ) {\n      throw new ToolError(\n        'INVALID_PLAN_SECRET',\n        `${path}.${key} contains a connection string; use SecretRef`,\n      )\n    }\n    assertNoPlanSecrets(child, `${path}.${key}`)\n  }\n}\n\nasync function readPlanFile(path: string): Promise<Record<string, unknown>> {\n  let raw: string\n  try {\n    raw = await getHost().readTextFile(path)\n  } catch (error) {\n    throw new UsageError('PLAN_READ_FAILED', `failed to read InstallPlan: ${errorMessage(error)}`)\n  }\n  let value: unknown\n  try {\n    value = JSON.parse(raw)\n  } catch {\n    throw new UsageError('INVALID_PLAN_JSON', 'InstallPlan is not valid JSON')\n  }\n  const plan = expectObject(value, 'InstallPlan')\n  assertPortablePlan(plan)\n  return plan\n}\n\nasync function writePlanFile(\n  ctx: CommandContext,\n  path: string,\n  plan: Record<string, unknown>,\n): Promise<void> {\n  const exists = await tryLstat(path)\n  if (exists) {\n    if (!exists.isFile) {\n      throw new UsageError('INVALID_PLAN_PATH', 'InstallPlan destination is not a regular file')\n    }\n    if (!ctx.confirmed) {\n      if (ctx.config.nonInteractive || !ctx.io.inputIsTerminal) {\n        throw new ToolError(\n          'CONFIRMATION_REQUIRED',\n          `InstallPlan already exists: ${path}; use --yes to overwrite it`,\n          EXIT_PERMISSION,\n        )\n      }\n      const answer = (await ctx.io.prompt(`Overwrite existing InstallPlan ${path}? [y/N] `))\n        ?.trim().toLowerCase()\n      if (answer !== 'y' && answer !== 'yes') {\n        throw new ToolError(\n          'CONFIRMATION_DECLINED',\n          'InstallPlan overwrite was declined',\n          EXIT_PERMISSION,\n        )\n      }\n    }\n  }\n  const content = `${JSON.stringify(plan, null, 2)}\\n`\n  try {\n    await getHost().writeTextFile(\n      path,\n      content,\n      exists ? { mode: 0o600 } : { createNew: true, mode: 0o600 },\n    )\n    if (getHost().platform !== 'windows') await getHost().chmod(path, 0o600)\n  } catch (error) {\n    throw new UsageError('PLAN_WRITE_FAILED', `failed to write InstallPlan: ${errorMessage(error)}`)\n  }\n}\n\nasync function releaseStaging(ctx: CommandContext, source: PreparedSource): Promise<void> {\n  if (source.kind === 'catalog') return\n  try {\n    await ctx.clients.call(\n      CONTROL_PANEL_SERVICE,\n      'apps.staging.release',\n      { staging_handle: source.staging.handle },\n      {\n        traceId: ctx.traceId,\n        timeoutMs: STAGING_RELEASE_TIMEOUT_MS,\n        signal: new AbortController().signal,\n      },\n    )\n  } catch (error) {\n    await ctx.io.stderr(`warning: failed to release PIKG staging lease: ${errorMessage(error)}\\n`)\n  }\n}\n\nfunction expectInspection(value: unknown): InstallInspection {\n  const object = expectObject(value, 'apps.inspect response')\n  const schemaVersion = expectNumber(object, 'schema_version')\n  if (schemaVersion !== PLAN_SCHEMA_VERSION) {\n    throw new ToolError(\n      'UNSUPPORTED_SCHEMA_VERSION',\n      `Installer returned schema v${schemaVersion}; v${PLAN_SCHEMA_VERSION} is required`,\n    )\n  }\n  const inspection: InstallInspection = {\n    schema_version: schemaVersion,\n    plan: expectObject(object.plan, 'inspection.plan'),\n    resolution_status: expectObject(object.resolution_status, 'inspection.resolution_status'),\n    status: expectObject(object.status, 'inspection.status'),\n  }\n  assertPortablePlan(inspection.plan)\n  if (inspection.status.plan_fingerprint !== inspection.plan.plan_fingerprint) {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', 'inspection fingerprint fields disagree', 9)\n  }\n  return inspection\n}\n\nfunction parsePlanChoices(raw: string | null | undefined): Record<string, unknown> {\n  if (!raw) throw new ToolError('PLAN_INPUT_REQUIRED', 'plan choices JSON is required')\n  let value: unknown\n  try {\n    value = JSON.parse(raw)\n  } catch {\n    throw new UsageError('INVALID_INPUT_JSON', 'plan choices are not valid JSON')\n  }\n  const choices = expectObject(value, 'plan choices')\n  for (const key of Object.keys(choices)) {\n    if (key !== 'target' && key !== 'install_params') {\n      throw new UsageError('INVALID_ARGUMENT', `unknown plan choice: ${key}`)\n    }\n  }\n  return choices\n}\n\nfunction normalizeCatalogIdentifier(value: string): string {\n  const raw = value.trim()\n  if (\n    !raw || /^https?:\\/\\//i.test(raw) || raw.includes('/') || raw.includes('\\\\') || /\\s/.test(raw)\n  ) {\n    throw new UsageError('INVALID_APP_NAME', `invalid Catalog App identifier: ${value}`)\n  }\n  if (raw.startsWith('did:')) {\n    return parseAppDid(raw)\n  }\n  return raw.includes('.') ? raw.toLowerCase() : parseAppDid(`did:bns:${raw}`)\n}\n\nfunction normalizeAppSelector(value: string): string {\n  return normalizeCatalogIdentifier(value)\n}\n\nfunction parseAppDid(raw: string): string {\n  let did: InstanceType<typeof namelib.DID>\n  try {\n    did = namelib.DID.fromStr(raw)\n  } catch (error) {\n    throw new UsageError('INVALID_APP_DID', `invalid App DID: ${errorMessage(error)}`)\n  }\n  if (did.method === 'key' || did.method === 'dev') {\n    throw new UsageError('INVALID_APP_DID', 'key-class DIDs cannot identify an App')\n  }\n  return did.toString()\n}\n\nfunction parsePikgUrl(value: string): URL {\n  let url: URL\n  try {\n    url = new URL(value)\n  } catch {\n    throw new UsageError('INVALID_PIKG_URL', `invalid PIKG URL: ${value}`)\n  }\n  if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n    throw new UsageError('INVALID_PIKG_URL', 'PIKG URL must use HTTP or HTTPS')\n  }\n  if (url.username || url.password) {\n    throw new UsageError('INVALID_PIKG_URL', 'PIKG URL must not contain credentials')\n  }\n  return url\n}\n\nfunction validatePikgSnapshot(bytes: Uint8Array): void {\n  if (bytes.length < ZIP_LOCAL_MAGIC.length) {\n    throw new UsageError('INVALID_PIKG', 'PIKG is too small to be a ZIP container')\n  }\n  if (!ZIP_LOCAL_MAGIC.every((byte, index) => bytes[index] === byte)) {\n    throw new UsageError('INVALID_PIKG', 'PIKG magic mismatch: expected a ZIP container')\n  }\n}\n\nfunction gatewayOrigin(endpoint: string): string {\n  const url = new URL(endpoint)\n  const marker = url.pathname.indexOf('/kapi')\n  url.pathname = marker >= 0 ? url.pathname.slice(0, marker) || '/' : '/'\n  url.search = ''\n  url.hash = ''\n  return url.toString().replace(/\\/$/, '')\n}\n\nfunction safeUrl(url: URL): string {\n  const safe = new URL(url)\n  safe.search = ''\n  safe.hash = ''\n  return safe.toString()\n}\n\nexport function isDidSource(value: string): boolean {\n  return value.trim().startsWith('did:')\n}\n\nfunction looksLikeLocalPath(value: string): boolean {\n  return value.includes('/') || value.includes('\\\\') || value.startsWith('.') ||\n    value.toLowerCase().endsWith('.pikg')\n}\n\nasync function tryLstat(path: string): Promise<HostFileInfo | undefined> {\n  try {\n    return await getHost().lstat(path)\n  } catch (error) {\n    if (isHostError(error, 'NotFound')) return undefined\n    throw new UsageError('FILE_ACCESS_FAILED', `failed to inspect ${path}: ${errorMessage(error)}`)\n  }\n}\n\nfunction resolveFromCwd(ctx: CommandContext, path: string): string {\n  return isAbsolute(path) ? resolve(path) : resolve(ctx.cwd, path)\n}\n\nfunction parseEmbeddedJson(message: string): Record<string, unknown> | undefined {\n  for (let index = message.indexOf('{'); index >= 0; index = message.indexOf('{', index + 1)) {\n    try {\n      const value = JSON.parse(message.slice(index))\n      if (isObject(value)) return value\n    } catch {\n      // Try the next opening brace; kRPC prefixes structured service errors.\n    }\n  }\n  return undefined\n}\n\nfunction readinessValue(inspection: InstallInspection, field: string): string | undefined {\n  const readiness = isObject(inspection.status.readiness) ? inspection.status.readiness : undefined\n  return readiness ? optionalString(readiness[field]) : undefined\n}\n\nfunction planUse(plan: Record<string, unknown>): string | undefined {\n  return optionalString(plan.plan_use)\n}\n\nfunction installProgressMessage(status: Record<string, unknown>): string | undefined {\n  const stage = optionalString(status.stage)\n  const progress = isObject(status.progress) ? status.progress : undefined\n  const percent = progress && typeof progress.percent === 'number'\n    ? `${progress.percent}%`\n    : undefined\n  return [stage, percent].filter(Boolean).join(' ') || undefined\n}\n\nfunction idempotencyKey(ctx: CommandContext): string {\n  return ctx.idempotencyKey ?? crypto.randomUUID()\n}\n\nfunction rejectDryRunNoWait(input: Record<string, unknown>): void {\n  if (input.dry_run === true && input.no_wait === true) {\n    throw new UsageError('ARGUMENT_CONFLICT', '--dry-run and --no-wait are mutually exclusive')\n  }\n}\n\nfunction selectorCommand(options: {\n  verb: string\n  summary: string\n  access: 'read' | 'write' | 'destructive'\n  asyncMode: 'sync' | 'task' | 'either'\n  handler: CommandDefinition['handler']\n}): CommandDefinition {\n  return {\n    verb: options.verb,\n    summary: options.summary,\n    positionals: [{ name: 'app_name', description: 'Installed App name or DID' }],\n    inputSchema: {\n      type: 'object',\n      properties: { app_name: { type: 'string', minLength: 1 } },\n      required: ['app_name'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: options.access },\n    asyncMode: options.asyncMode,\n    requiresSession: true,\n    examples: [`buckyos app ${options.verb} app1`],\n    handler: options.handler,\n  }\n}\n\nfunction sourceOptions(\n  extra: NonNullable<CommandDefinition['options']>,\n): NonNullable<CommandDefinition['options']> {\n  return [\n    {\n      name: 'from',\n      description: 'Force source type',\n      type: 'string',\n      enum: ['catalog', 'pikg', 'url'],\n    },\n    { name: 'pikg', description: 'Explicit local PIKG path', type: 'string' },\n    ...extra,\n  ]\n}\n\nfunction sourceInputSchema(extra: Record<string, JsonSchema>): JsonSchema {\n  return {\n    type: 'object',\n    properties: {\n      source: { type: 'string', minLength: 1 },\n      from: { type: 'string', enum: ['catalog', 'pikg', 'url'] },\n      pikg: { type: 'string', minLength: 1 },\n      ...extra,\n    },\n    additionalProperties: false,\n  }\n}\n\nfunction emptyInputSchema(): JsonSchema {\n  return { type: 'object', properties: {}, additionalProperties: false }\n}\n\nfunction ownerOption(): NonNullable<CommandDefinition['options']>[number] {\n  return {\n    name: 'owner',\n    property: 'owner_user_id',\n    description: 'Installation owner user',\n    type: 'string',\n  }\n}\n\nfunction policyOption(): NonNullable<CommandDefinition['options']>[number] {\n  return {\n    name: 'policy',\n    description: 'Installer trust policy',\n    type: 'string',\n    enum: [...INSTALL_POLICIES],\n  }\n}\n\nfunction rpcOptions(ctx: CommandContext): {\n  traceId: string\n  timeoutMs: number\n  signal: AbortSignal\n} {\n  return {\n    traceId: ctx.traceId,\n    timeoutMs: Math.max(1, (ctx.deadline ?? Date.now()) - Date.now()),\n    signal: ctx.signal,\n  }\n}\n\nfunction expectObject(value: unknown, label: string): Record<string, unknown> {\n  if (!isObject(value)) {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `${label} must be an object`, EXIT_INTERNAL)\n  }\n  return value\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction expectString(object: Record<string, unknown>, property: string): string\nfunction expectString(value: unknown, property: string): string\nfunction expectString(value: unknown, property: string): string {\n  const candidate = isObject(value) ? value[property] : value\n  if (typeof candidate !== 'string' || !candidate.trim()) {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `${property} must be a non-empty string`, 9)\n  }\n  return candidate\n}\n\nfunction expectNumber(object: Record<string, unknown>, property: string): number {\n  const value = object[property]\n  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `${property} must be a non-negative integer`, 9)\n  }\n  return value\n}\n\nfunction optionalString(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim() ? value : undefined\n}\n\nfunction optionalNumber(value: unknown): number | undefined {\n  return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction errorMessage(error: unknown): string {\n  return error instanceof Error ? error.message : String(error)\n}\n\nfunction sanitizeAppOutput(value: unknown): unknown {\n  if (Array.isArray(value)) return value.map(sanitizeAppOutput)\n  if (!isObject(value)) return value\n  const result: Record<string, unknown> = {}\n  const forbidden = new Set([\n    'spec_path',\n    'staging_handle',\n    'staging_path',\n    'source_url',\n    'session_token',\n    'refresh_token',\n    'private_key',\n    'password',\n    'connection_string',\n    'database_url',\n  ])\n  for (const [key, child] of Object.entries(value)) {\n    if (!forbidden.has(key.toLowerCase())) result[key] = sanitizeAppOutput(child)\n  }\n  return result\n}\n","import type { CommandContext } from './context.ts'\nimport { resolveServiceUrl } from './runtime.ts'\nimport { ToolError, UsageError } from './errors.ts'\nimport { getHost, isHostError } from '../runtime/host.ts'\n\nexport interface ArtifactDownload {\n  path: string\n  size: number\n  sha256: string\n}\n\nexport type ArtifactFetcher = (\n  url: URL,\n  ctx: CommandContext,\n) => Promise<Uint8Array>\n\nexport async function downloadArtifact(\n  ctx: CommandContext,\n  service: string,\n  rawUrl: string,\n  rawPath: string,\n  fetcher: ArtifactFetcher = defaultArtifactFetcher,\n): Promise<ArtifactDownload> {\n  const path = getHost().path.isAbsolute(rawPath)\n    ? rawPath\n    : getHost().path.resolve(ctx.cwd, rawPath)\n  const base = new URL(resolveServiceUrl(ctx.config, service))\n  const url = new URL(rawUrl, `${base.protocol}//${base.host}`)\n  if (url.origin !== base.origin || url.username || url.password) {\n    throw new ToolError('INVALID_DOWNLOAD_URL', 'artifact URL must use the configured Zone origin')\n  }\n  const bytes = await fetcher(url, ctx)\n  try {\n    const file = await getHost().open(path, { createNew: true, write: true })\n    try {\n      let offset = 0\n      while (offset < bytes.length) offset += await file.write(bytes.subarray(offset))\n      await file.sync()\n    } finally {\n      await file.close()\n    }\n  } catch (error) {\n    if (isHostError(error, 'AlreadyExists')) {\n      throw new UsageError('OUTPUT_EXISTS', `output path already exists: ${path}`)\n    }\n    try {\n      await getHost().remove(path)\n    } catch {\n      // Preserve the original write error if best-effort cleanup also fails.\n    }\n    throw error\n  }\n  const digest = await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes).buffer)\n  return { path, size: bytes.byteLength, sha256: toHex(new Uint8Array(digest)) }\n}\n\nasync function defaultArtifactFetcher(url: URL, ctx: CommandContext): Promise<Uint8Array> {\n  const token = ctx.session ? (await ctx.session.ensureValid()).token : undefined\n  const response = await fetch(url, {\n    headers: token ? { authorization: `Bearer ${token}` } : undefined,\n    signal: ctx.signal,\n  })\n  if (!response.ok) {\n    throw new ToolError(\n      'DOWNLOAD_FAILED',\n      `artifact download failed with HTTP ${response.status}`,\n    )\n  }\n  return new Uint8Array(await response.arrayBuffer())\n}\n\nfunction toHex(bytes: Uint8Array): string {\n  return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n","import type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport type { ArtifactFetcher } from '../core/download.ts'\nimport { downloadArtifact } from '../core/download.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { ToolError, UsageError } from '../core/errors.ts'\nimport {\n  callService,\n  expectObject,\n  expectString,\n  inputString,\n  requiredInputString,\n  splitServices,\n} from '../core/service.ts'\nimport { waitForTask } from '../core/task.ts'\nimport { getHost } from '../runtime/host.ts'\n\nconst CONTROL_PANEL = 'control-panel'\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\n\nexport interface DiagnosticModuleDependencies {\n  download?: ArtifactFetcher\n}\n\nexport function createDiagnosticModule(\n  dependencies: DiagnosticModuleDependencies = {},\n): CommandModule {\n  return {\n    name: 'diagnostic',\n    summary: 'Collect and export privileged redacted diagnostic bundles',\n    commands: [collectCommand(), exportCommand(dependencies)],\n  }\n}\n\nfunction collectCommand(): CommandDefinition {\n  return {\n    verb: 'collect',\n    summary: 'Create a redacted diagnostic bundle Task',\n    options: [\n      {\n        name: 'services',\n        description: 'Comma-separated service IDs',\n        type: 'string',\n        required: true,\n      },\n      { name: 'since', description: 'RFC 3339 lower time boundary', type: 'string' },\n      { name: 'until', description: 'RFC 3339 upper time boundary', type: 'string' },\n      {\n        name: 'no-wait',\n        property: 'no_wait',\n        description: 'Return after Task creation',\n        type: 'boolean',\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        services: {},\n        since: { type: 'string', minLength: 1 },\n        until: { type: 'string', minLength: 1 },\n        no_wait: { type: 'boolean' },\n      },\n      required: ['services'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'privileged' },\n    asyncMode: 'task',\n    requiresSession: true,\n    examples: [\n      'buckyos --idempotency-key diag-42 diagnostic collect --services scheduler,node_daemon --since 2026-08-25T00:00:00Z',\n    ],\n    handler: async (ctx, input) => {\n      const services = splitServices(input.services)\n      if (services.length === 0) {\n        throw new UsageError('INVALID_ARGUMENT', 'at least one diagnostic service is required')\n      }\n      const response = expectObject(\n        await callService(\n          ctx,\n          CONTROL_PANEL,\n          'diagnostic.collect',\n          compact({\n            services,\n            since: inputString(input, 'since'),\n            until: inputString(input, 'until'),\n            idempotency_key: ctx.idempotencyKey ?? `diagnostic-${crypto.randomUUID()}`,\n          }),\n        ),\n        'Control Panel diagnostic.collect response',\n      )\n      const taskId = expectString(response.task_id, 'diagnostic.collect.task_id')\n      if (input.no_wait === true) return { task_id: taskId }\n      return await waitForTask(ctx, taskId)\n    },\n  }\n}\n\nfunction exportCommand(dependencies: DiagnosticModuleDependencies): CommandDefinition {\n  return {\n    verb: 'export',\n    summary: 'Export one diagnostic bundle to a new file',\n    positionals: [{ name: 'bundle_id', description: 'Opaque bundle ID', required: true }],\n    options: [{\n      name: 'path',\n      description: 'New destination file',\n      type: 'string',\n      required: true,\n    }],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        bundle_id: { type: 'string', minLength: 1 },\n        path: { type: 'string', minLength: 1 },\n      },\n      required: ['bundle_id', 'path'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'privileged' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos diagnostic export diag-opaque --path ./diagnostic.zip'],\n    handler: async (ctx, input) => await exportDiagnostic(ctx, input, dependencies),\n  }\n}\n\nasync function exportDiagnostic(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  dependencies: DiagnosticModuleDependencies,\n): Promise<Record<string, unknown>> {\n  const response = expectObject(\n    await callService(ctx, CONTROL_PANEL, 'diagnostic.export', {\n      bundle_id: requiredInputString(input, 'bundle_id'),\n    }),\n    'Control Panel diagnostic.export response',\n  )\n  const downloaded = await downloadArtifact(\n    ctx,\n    CONTROL_PANEL,\n    expectString(response.url, 'diagnostic.export.url'),\n    requiredInputString(input, 'path'),\n    dependencies.download,\n  )\n  const expected = typeof response.artifact_sha256 === 'string'\n    ? response.artifact_sha256\n    : undefined\n  if (expected && downloaded.sha256 !== expected) {\n    try {\n      await getHost().remove(downloaded.path)\n    } catch {\n      // Report the integrity failure even if best-effort cleanup is denied.\n    }\n    throw new ToolError('ARTIFACT_HASH_MISMATCH', 'diagnostic archive SHA-256 mismatch')\n  }\n  return {\n    ...downloaded,\n    bundle_id: response.bundle_id ?? input.bundle_id,\n    content_sha256: response.sha256 ?? null,\n    expires_at: response.expires_at ?? null,\n  }\n}\n\nfunction compact(value: Record<string, unknown>): Record<string, unknown> {\n  return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined))\n}\n","import type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport { type ArtifactFetcher, downloadArtifact } from '../core/download.ts'\nimport { EXIT_TIMEOUT, ToolError, UsageError } from '../core/errors.ts'\nimport {\n  callService,\n  expectObject,\n  expectString,\n  inputString,\n  requiredInputString,\n  splitServices,\n} from '../core/service.ts'\n\nconst CONTROL_PANEL = 'control-panel'\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\n// Stored entry levels (control-panel sys_log_mgr normalize_log_level); WARN is stored as warning.\nconst LOG_LEVELS = ['error', 'warning', 'info', 'debug', 'trace']\n\nexport interface LogModuleDependencies {\n  sleep?: (milliseconds: number, signal: AbortSignal) => Promise<void>\n  download?: ArtifactFetcher\n}\n\nexport function createLogModule(dependencies: LogModuleDependencies = {}): CommandModule {\n  return {\n    name: 'log',\n    summary: 'List services, query, follow, and export redacted system logs',\n    commands: [\n      servicesCommand(),\n      queryCommand(),\n      tailCommand(dependencies),\n      exportCommand(dependencies),\n    ],\n  }\n}\n\nfunction servicesCommand(): CommandDefinition {\n  return {\n    verb: 'services',\n    summary: 'List the service IDs that have system logs',\n    inputSchema: { type: 'object', properties: {}, additionalProperties: false },\n    outputSchema: {\n      type: 'object',\n      properties: { services: { type: 'array', items: OBJECT_OUTPUT } },\n      required: ['services'],\n      additionalProperties: false,\n    },\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos log services'],\n    handler: async (ctx) => {\n      const response = expectObject(\n        await callService(ctx, CONTROL_PANEL, 'system.logs.list', {}),\n        'Control Panel log service list',\n      )\n      if (!Array.isArray(response.services)) invalidResponse('log service list')\n      return { services: response.services }\n    },\n  }\n}\n\nfunction queryCommand(): CommandDefinition {\n  return {\n    verb: 'query',\n    summary: 'Query structured redacted log entries',\n    options: [\n      ...filterOptions(false),\n      {\n        name: 'direction',\n        description: 'Page direction',\n        type: 'string',\n        enum: ['forward', 'backward'],\n      },\n      { name: 'cursor', description: 'Opaque page cursor', type: 'string' },\n      { name: 'limit', description: 'Page size, at most 500', type: 'integer' },\n    ],\n    inputSchema: filterSchema({\n      direction: { type: 'string', enum: ['forward', 'backward'] },\n      cursor: { type: 'string', minLength: 1 },\n      limit: { type: 'integer', minimum: 1 },\n    }),\n    outputSchema: pageSchema(),\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos log query --service scheduler --level error --limit 100'],\n    handler: async (ctx, input) => {\n      const params = normalizeFilter(input, true)\n      const response = expectObject(\n        await callService(ctx, CONTROL_PANEL, 'system.logs.query', params),\n        'Control Panel log query response',\n      )\n      if (!Array.isArray(response.entries)) invalidResponse('log query entries')\n      return { items: response.entries, next_cursor: response.nextCursor ?? null }\n    },\n  }\n}\n\nfunction tailCommand(dependencies: LogModuleDependencies): CommandDefinition {\n  const sleep = dependencies.sleep ?? abortableSleep\n  return {\n    verb: 'tail',\n    summary: 'Continuously stream structured redacted log entries',\n    options: [\n      ...filterOptions(false),\n      {\n        name: 'from',\n        description: 'Initial read position',\n        type: 'string',\n        enum: ['start', 'end'],\n      },\n    ],\n    inputSchema: filterSchema({ from: { type: 'string', enum: ['start', 'end'] } }),\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'stream',\n    requiresSession: true,\n    examples: ['buckyos --timeout 10m log tail --service scheduler --from end'],\n    handler: async (ctx, input) => {\n      const params = normalizeFilter(input, false)\n      if (params.services.length !== 1) {\n        throw new UsageError('INVALID_ARGUMENT', 'log tail requires exactly one service')\n      }\n      let cursor: string | undefined\n      while (true) {\n        const remaining = (ctx.deadline ?? Date.now()) - Date.now()\n        if (remaining <= 0) throw timeoutError()\n        const response = expectObject(\n          await callService(ctx, CONTROL_PANEL, 'system.logs.tail', {\n            ...params,\n            cursor,\n            from: inputString(input, 'from') ?? 'end',\n            limit: 500,\n          }),\n          'Control Panel log tail response',\n        )\n        if (!Array.isArray(response.entries)) invalidResponse('log tail entries')\n        for (const entry of response.entries) {\n          await ctx.io.stdout(`${\n            JSON.stringify({\n              schema_version: 1,\n              type: 'log-entry',\n              entry,\n            })\n          }\\n`)\n        }\n        cursor = expectString(response.nextCursor, 'log tail nextCursor')\n        await sleep(\n          Math.min(500, Math.max(1, (ctx.deadline ?? Date.now()) - Date.now())),\n          ctx.signal,\n        )\n      }\n    },\n  }\n}\n\nfunction exportCommand(dependencies: LogModuleDependencies): CommandDefinition {\n  return {\n    verb: 'export',\n    summary: 'Export a bounded redacted log archive to a new file',\n    options: [\n      ...filterOptions(true),\n      { name: 'path', description: 'New destination file', type: 'string', required: true },\n    ],\n    inputSchema: {\n      ...filterSchema({ path: { type: 'string', minLength: 1 } }),\n      required: ['path'],\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: [\n      'buckyos log export --services scheduler,node_daemon --since 2026-08-25T00:00:00Z --path ./logs.zip',\n    ],\n    handler: async (ctx, input) => {\n      const params = normalizeFilter(input, false)\n      if (params.services.length === 0) {\n        throw new UsageError('INVALID_ARGUMENT', 'log export requires at least one service')\n      }\n      if (!params.since && !params.until) {\n        throw new UsageError(\n          'INVALID_ARGUMENT',\n          'log export requires a since or until time boundary',\n        )\n      }\n      const response = expectObject(\n        await callService(ctx, CONTROL_PANEL, 'system.logs.download', {\n          ...params,\n          mode: 'filtered',\n        }),\n        'Control Panel log export response',\n      )\n      const downloaded = await downloadArtifact(\n        ctx,\n        CONTROL_PANEL,\n        expectString(response.url, 'log export url'),\n        requiredInputString(input, 'path'),\n        dependencies.download,\n      )\n      return downloaded\n    },\n  }\n}\n\nfunction filterOptions(plural: boolean) {\n  return [\n    {\n      name: plural ? 'services' : 'service',\n      property: plural ? 'services' : 'service',\n      description: plural\n        ? 'Comma-separated service IDs (buckyos log services)'\n        : 'Service ID (buckyos log services)',\n      type: 'string' as const,\n      required: true,\n    },\n    {\n      name: 'file',\n      description: 'Exact filename in the service log directory',\n      type: 'string' as const,\n    },\n    {\n      name: 'level',\n      description: `Log level: ${LOG_LEVELS.join(', ')} (warn = warning)`,\n      type: 'string' as const,\n    },\n    { name: 'keyword', description: 'Case-insensitive content filter', type: 'string' as const },\n    { name: 'since', description: 'RFC 3339 lower time boundary', type: 'string' as const },\n    { name: 'until', description: 'RFC 3339 upper time boundary', type: 'string' as const },\n  ]\n}\n\nfunction filterSchema(extra: Record<string, JsonSchema>): JsonSchema {\n  return {\n    type: 'object',\n    properties: {\n      service: { type: 'string', minLength: 1 },\n      services: {},\n      file: { type: 'string', minLength: 1 },\n      level: { type: 'string', minLength: 1 },\n      keyword: { type: 'string', minLength: 1 },\n      since: { type: 'string', minLength: 1 },\n      until: { type: 'string', minLength: 1 },\n      ...extra,\n    },\n    additionalProperties: false,\n  }\n}\n\nfunction normalizeFilter(\n  input: Record<string, unknown>,\n  withPage: boolean,\n): Record<string, unknown> & { services: string[] } {\n  const services = splitServices(input.services ?? input.service)\n  if (services.length === 0) throw new UsageError('INVALID_ARGUMENT', 'service is required')\n  const limit = input.limit === undefined ? undefined : Number(input.limit)\n  if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)) {\n    throw new UsageError('INVALID_ARGUMENT', 'limit must be an integer between 1 and 500')\n  }\n  return compact({\n    services,\n    file: inputString(input, 'file'),\n    level: normalizeLevel(inputString(input, 'level')),\n    keyword: inputString(input, 'keyword'),\n    since: normalizeLogTime(input, 'since'),\n    until: normalizeLogTime(input, 'until'),\n    direction: withPage ? inputString(input, 'direction') ?? 'forward' : undefined,\n    cursor: withPage ? inputString(input, 'cursor') : undefined,\n    limit: withPage ? limit : undefined,\n  }) as Record<string, unknown> & { services: string[] }\n}\n\nfunction normalizeLevel(value: string | undefined): string | undefined {\n  if (!value) return undefined\n  const level = value.toLowerCase() === 'warn' ? 'warning' : value.toLowerCase()\n  if (!LOG_LEVELS.includes(level)) {\n    throw new UsageError(\n      'INVALID_ARGUMENT',\n      `level must be one of ${LOG_LEVELS.join(', ')} (warn = warning)`,\n    )\n  }\n  return level\n}\n\nfunction normalizeLogTime(input: Record<string, unknown>, key: string): string | undefined {\n  const value = inputString(input, key)\n  if (!value) return undefined\n  if (!Number.isFinite(Date.parse(value))) {\n    throw new UsageError('INVALID_ARGUMENT', `${key} must be RFC 3339`)\n  }\n  return value\n}\n\nfunction pageSchema(): JsonSchema {\n  return {\n    type: 'object',\n    properties: { items: { type: 'array', items: {} }, next_cursor: {} },\n    required: ['items', 'next_cursor'],\n    additionalProperties: false,\n  }\n}\n\nfunction compact(value: Record<string, unknown>): Record<string, unknown> {\n  return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined))\n}\n\nfunction invalidResponse(label: string): never {\n  throw new ToolError('INVALID_SERVICE_RESPONSE', `${label} is invalid`)\n}\n\nfunction timeoutError(): ToolError {\n  return new ToolError('TIMEOUT', 'timed out following logs', EXIT_TIMEOUT, true)\n}\n\nfunction abortableSleep(milliseconds: number, signal: AbortSignal): Promise<void> {\n  if (signal.aborted) return Promise.reject(new ToolError('CANCELED', 'operation canceled'))\n  return new Promise((resolve, reject) => {\n    const onAbort = () => {\n      clearTimeout(timer)\n      reject(new ToolError('CANCELED', 'operation canceled'))\n    }\n    const timer = setTimeout(() => {\n      signal.removeEventListener('abort', onAbort)\n      resolve()\n    }, milliseconds)\n    signal.addEventListener('abort', onAbort, { once: true })\n  })\n}\n","import type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport { EXIT_INTERNAL, ToolError, UsageError } from '../core/errors.ts'\nimport {\n  callService,\n  expectObject,\n  expectString,\n  inputString,\n  parseTimestamp,\n  requiredInputString,\n} from '../core/service.ts'\nimport { waitForTask } from '../core/task.ts'\n\nconst TASK_MANAGER = 'task-manager'\nconst CONTROL_PANEL = 'control-panel'\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\n\nexport function createTaskModule(): CommandModule {\n  return {\n    name: 'task',\n    summary: 'Inspect, wait for, cancel, and retry durable Tasks',\n    commands: [listCommand(), getCommand(), waitCommand(), cancelCommand(), retryCommand()],\n  }\n}\n\nfunction listCommand(): CommandDefinition {\n  return {\n    verb: 'list',\n    summary: 'List visible Tasks',\n    options: [\n      { name: 'owner', description: 'Creator user ID', type: 'string' },\n      { name: 'type', description: 'Task schema ID', type: 'string' },\n      { name: 'state', description: 'Task phase', type: 'string' },\n      { name: 'since', description: 'Created at or after this time', type: 'string' },\n      { name: 'until', description: 'Created at or before this time', type: 'string' },\n      { name: 'cursor', description: 'Opaque page cursor', type: 'string' },\n      { name: 'limit', description: 'Page size, at most 500', type: 'integer' },\n      {\n        name: 'include-archived',\n        property: 'include_archived',\n        description: 'Include archived Tasks',\n        type: 'boolean',\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        owner: { type: 'string', minLength: 1 },\n        type: { type: 'string', minLength: 1 },\n        state: { type: 'string', minLength: 1 },\n        since: {},\n        until: {},\n        cursor: { type: 'string', minLength: 1 },\n        limit: { type: 'integer', minimum: 1 },\n        include_archived: { type: 'boolean' },\n      },\n      additionalProperties: false,\n    },\n    outputSchema: pageSchema(),\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos task list --state running --limit 50'],\n    handler: async (ctx, input) => {\n      const limit = normalizeLimit(input.limit)\n      const response = expectObject(\n        await callService(\n          ctx,\n          TASK_MANAGER,\n          'list_tasks',\n          compact({\n            creator_user_id: inputString(input, 'owner'),\n            schema_id: inputString(input, 'type'),\n            phase: input.state === undefined ? undefined : normalizePhase(String(input.state)),\n            created_after: parseTimestamp(input.since, 'since'),\n            created_before: parseTimestamp(input.until, 'until'),\n            cursor: inputString(input, 'cursor'),\n            limit,\n            include_archived: input.include_archived === true,\n          }),\n        ),\n        'TaskManager list_tasks response',\n      )\n      const items = response.tasks\n      if (!Array.isArray(items)) invalidResponse('list_tasks.tasks')\n      return { items, next_cursor: response.next_cursor ?? null }\n    },\n  }\n}\n\nfunction getCommand(): CommandDefinition {\n  return {\n    verb: 'get',\n    summary: 'Get one Task snapshot and its direct children',\n    positionals: [{ name: 'task_id', description: 'Opaque Task ID', required: true }],\n    options: [\n      {\n        name: 'children-cursor',\n        property: 'children_cursor',\n        description: 'Child page cursor',\n        type: 'string',\n      },\n      {\n        name: 'children-limit',\n        property: 'children_limit',\n        description: 'Child page size',\n        type: 'integer',\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        task_id: { type: 'string', minLength: 1 },\n        children_cursor: { type: 'string', minLength: 1 },\n        children_limit: { type: 'integer', minimum: 1 },\n      },\n      required: ['task_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos task get t-0123456789abcdef0123456789abcdef'],\n    handler: async (ctx, input) => {\n      const taskId = requiredInputString(input, 'task_id')\n      const [taskResponse, childrenResponse] = await Promise.all([\n        callService(ctx, TASK_MANAGER, 'get_task', { task_id: taskId }),\n        callService(\n          ctx,\n          TASK_MANAGER,\n          'get_subtasks',\n          compact({\n            task_id: taskId,\n            cursor: inputString(input, 'children_cursor'),\n            limit: normalizeLimit(input.children_limit),\n          }),\n        ),\n      ])\n      const taskEnvelope = expectObject(taskResponse, 'TaskManager get_task response')\n      const childrenEnvelope = expectObject(childrenResponse, 'TaskManager get_subtasks response')\n      if (!Array.isArray(childrenEnvelope.tasks)) invalidResponse('get_subtasks.tasks')\n      return {\n        task: expectObject(taskEnvelope.task ?? taskEnvelope, 'TaskManager task'),\n        children: {\n          items: childrenEnvelope.tasks,\n          next_cursor: childrenEnvelope.next_cursor ?? null,\n        },\n      }\n    },\n  }\n}\n\nfunction waitCommand(): CommandDefinition {\n  return {\n    verb: 'wait',\n    summary: 'Stream changes until a Task becomes terminal',\n    positionals: [{ name: 'task_id', description: 'Opaque Task ID', required: true }],\n    inputSchema: taskIdSchema(),\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'stream',\n    requiresSession: true,\n    examples: ['buckyos --timeout 10m task wait t-0123456789abcdef0123456789abcdef'],\n    handler: async (ctx, input) => {\n      const taskId = requiredInputString(input, 'task_id')\n      return await waitForTask(ctx, taskId, {\n        failOnTaskFailure: false,\n        onObservation: async (observation) => {\n          await ctx.io.stdout(`${\n            JSON.stringify({\n              schema_version: 1,\n              type: 'task-progress',\n              task_id: taskId,\n              revision: observation.revision ?? null,\n              phase: observation.phase,\n              outcome: observation.outcome ?? null,\n              progress: observation.progress ?? null,\n              message: observation.message ?? null,\n            })\n          }\\n`)\n        },\n      })\n    },\n  }\n}\n\nfunction cancelCommand(): CommandDefinition {\n  return {\n    verb: 'cancel',\n    summary: 'Request Task cancellation',\n    positionals: [{ name: 'task_id', description: 'Opaque Task ID', required: true }],\n    options: [\n      { name: 'recursive', description: 'Request cancellation for descendants', type: 'boolean' },\n      {\n        name: 'expected-revision',\n        property: 'expected_revision',\n        description: 'Optimistic revision fence',\n        type: 'integer',\n      },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        task_id: { type: 'string', minLength: 1 },\n        recursive: { type: 'boolean' },\n        expected_revision: { type: 'integer', minimum: 0 },\n      },\n      required: ['task_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos task cancel t-0123456789abcdef0123456789abcdef --recursive'],\n    handler: async (ctx, input) => {\n      const taskId = requiredInputString(input, 'task_id')\n      return await callService(\n        ctx,\n        TASK_MANAGER,\n        'request_control',\n        compact({\n          task_id: taskId,\n          action: 'Cancel',\n          request_id: ctx.idempotencyKey ?? `ctl-${crypto.randomUUID().replaceAll('-', '')}`,\n          recursive: input.recursive === true,\n          expected_revision: input.expected_revision,\n        }),\n      )\n    },\n  }\n}\n\nfunction retryCommand(): CommandDefinition {\n  return {\n    verb: 'retry',\n    summary: 'Create a new Task through the owning domain retry handler',\n    positionals: [{ name: 'task_id', description: 'Failed terminal Task ID', required: true }],\n    options: [{\n      name: 'no-wait',\n      property: 'no_wait',\n      description: 'Return after creation',\n      type: 'boolean',\n    }],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        task_id: { type: 'string', minLength: 1 },\n        no_wait: { type: 'boolean' },\n      },\n      required: ['task_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'either',\n    requiresSession: true,\n    examples: ['buckyos --idempotency-key retry-42 task retry t-0123456789abcdef0123456789abcdef'],\n    handler: async (ctx, input) => {\n      const taskId = requiredInputString(input, 'task_id')\n      const oldEnvelope = expectObject(\n        await callService(ctx, TASK_MANAGER, 'get_task', { task_id: taskId }),\n        'TaskManager get_task response',\n      )\n      const oldTask = expectObject(oldEnvelope.task ?? oldEnvelope, 'TaskManager task')\n      if (oldTask.phase !== 'Terminal' || oldTask.outcome !== 'Failed') {\n        throw new UsageError('TASK_NOT_RETRYABLE', 'only a terminal failed Task can be retried')\n      }\n      const response = expectObject(\n        await callService(ctx, CONTROL_PANEL, 'task.retry', {\n          task_id: taskId,\n          idempotency_key: ctx.idempotencyKey ?? `retry-${crypto.randomUUID()}`,\n        }),\n        'Control Panel task.retry response',\n      )\n      const retryTaskId = expectString(response.task_id, 'task.retry.task_id')\n      if (retryTaskId === taskId || response.retry_of !== taskId) {\n        invalidResponse('task.retry identity')\n      }\n      if (input.no_wait === true) return response\n      return await waitForTask(ctx, retryTaskId)\n    },\n  }\n}\n\nfunction taskIdSchema(): JsonSchema {\n  return {\n    type: 'object',\n    properties: { task_id: { type: 'string', minLength: 1 } },\n    required: ['task_id'],\n    additionalProperties: false,\n  }\n}\n\nfunction pageSchema(): JsonSchema {\n  return {\n    type: 'object',\n    properties: {\n      items: { type: 'array', items: {} },\n      next_cursor: {},\n    },\n    required: ['items', 'next_cursor'],\n    additionalProperties: false,\n  }\n}\n\nfunction normalizePhase(value: string): string {\n  const normalized = value.trim().toLowerCase()\n  const phase = ['promised', 'accepted', 'running', 'waiting', 'paused', 'terminal']\n    .find((candidate) => candidate === normalized)\n  if (!phase) throw new UsageError('INVALID_ARGUMENT', `unknown Task phase: ${value}`)\n  return phase[0].toUpperCase() + phase.slice(1)\n}\n\nfunction normalizeLimit(value: unknown): number | undefined {\n  if (value === undefined) return undefined\n  if (!Number.isSafeInteger(value) || Number(value) < 1 || Number(value) > 500) {\n    throw new UsageError('INVALID_ARGUMENT', 'limit must be an integer between 1 and 500')\n  }\n  return Number(value)\n}\n\nfunction compact(value: Record<string, unknown>): Record<string, unknown> {\n  return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined))\n}\n\nfunction invalidResponse(label: string): never {\n  throw new ToolError('INVALID_SERVICE_RESPONSE', `${label} is invalid`, EXIT_INTERNAL)\n}\n","import type {\n  CommandDefinition,\n  CommandModule,\n  JsonSchema,\n  OptionDefinition,\n} from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport {\n  EXIT_OPERATION,\n  EXIT_PARTIAL,\n  EXIT_PERMISSION,\n  EXIT_USAGE,\n  ToolError,\n  UsageError,\n} from '../core/errors.ts'\nimport { getHost, isHostError } from '../runtime/host.ts'\nimport { TOOL_VERSION } from '../version.ts'\nimport * as provisionSdk from 'buckyos/provision'\n\n// provision: first activation of an installed, not yet activated BuckyOS root on\n// this machine (single OOD, did:web, no SN/BNS). Every command is local: no\n// Zone session, no verify-hub, no TaskManager, no network. The activation\n// implementation lives in the SDK (buckyos/provision); this module is the thin\n// argv/confirmation/secret/output layer described in doc/modules/provision.md.\n\n// The built SDK entry is untyped for `deno check` (as buckyos/node is for the\n// core); these interfaces mirror the API documented in src/provision_activate.ts.\nexport type ActivationState = 'not_installed' | 'unactivated' | 'partial' | 'configured' | 'invalid'\n\nexport interface ActivationProblem {\n  code: string\n  message: string\n}\n\nexport interface ActivationFileEntry {\n  path: string\n  role: string\n  required: boolean\n  secret: boolean\n}\n\nexport interface ObservedActivationFile extends ActivationFileEntry {\n  present: boolean\n}\n\nexport interface CommittedActivationFile extends ActivationFileEntry {\n  sha256: string | null\n}\n\nexport interface ActivationDnsRecord {\n  type: 'A' | 'AAAA'\n  name: string\n  value: string\n}\n\nexport interface ActivationLockInfo {\n  path: string\n  schemaVersion: number | null\n  traceId: string | null\n  startedAt: number | null\n  domain: string | null\n  stage: string | null\n  committedFiles: string[]\n  ownerKeyBackupPath: string | null\n  corrupt: boolean\n}\n\nexport interface ActivationStatus {\n  rootDir: string\n  state: ActivationState\n  startupRequired: boolean\n  observedAt: number\n  zoneDid: string | null\n  ownerDid: string | null\n  deviceDid: string | null\n  deviceName: string | null\n  accessHostname: string | null\n  files: ObservedActivationFile[]\n  problems: ActivationProblem[]\n  warnings: string[]\n  lock: ActivationLockInfo | null\n}\n\nexport interface OfflineActivationCheckOptions {\n  rootDir: string\n  domain: string\n  ownerName: string\n  ownerKeyBackupPath: string\n  rtcpPort?: number\n  guestAccess?: boolean\n  publicIp?: string\n}\n\nexport interface OfflineActivationOptions extends OfflineActivationCheckOptions {\n  adminPassword: string\n  traceId?: string\n}\n\nexport interface OfflineActivationPrecheck {\n  ready: boolean\n  rootDir: string\n  state: ActivationState\n  domain: string\n  ownerName: string\n  ownerDid: string\n  zoneDid: string\n  deviceDid: string\n  deviceName: string\n  accessHostname: string\n  rtcpPort: number\n  guestAccess: boolean\n  publicIp: string | null\n  dnsRecords: ActivationDnsRecord[]\n  ownerKeyBackup: { path: string; directoryExists: boolean; exists: boolean }\n  plannedFiles: ActivationFileEntry[]\n  problems: ActivationProblem[]\n  status: ActivationStatus\n}\n\nexport interface OfflineActivationResult {\n  rootDir: string\n  state: 'configured'\n  startupRequired: true\n  domain: string\n  ownerName: string\n  ownerDid: string\n  zoneDid: string\n  deviceDid: string\n  deviceName: string\n  accessHostname: string\n  rtcpPort: number\n  guestAccess: boolean\n  publicIp: string | null\n  documentIat: number\n  documentExp: number\n  ownerKeyBackup: { path: string; saved: true }\n  dnsRecords: ActivationDnsRecord[]\n  committedFiles: CommittedActivationFile[]\n  warnings: string[]\n}\n\ninterface ProvisionSdk {\n  inspectActivationRoot(rootDir: string): Promise<ActivationStatus>\n  checkOfflineActivation(options: OfflineActivationCheckOptions): Promise<OfflineActivationPrecheck>\n  activateOfflineZone(options: OfflineActivationOptions): Promise<OfflineActivationResult>\n}\n\nconst sdk = provisionSdk as unknown as ProvisionSdk\n\nexport interface ProvisionModuleDependencies {\n  inspect?: ProvisionSdk['inspectActivationRoot']\n  check?: ProvisionSdk['checkOfflineActivation']\n  activate?: ProvisionSdk['activateOfflineZone']\n}\n\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\n\nconst ROOT_OPTION: OptionDefinition = {\n  name: 'root',\n  description:\n    'Installed BuckyOS root on this machine (BUCKYOS_ROOT); read by status/check, written by activate',\n  type: 'string',\n  required: true,\n}\n\nconst TARGET_OPTIONS: OptionDefinition[] = [\n  ROOT_OPTION,\n  {\n    name: 'domain',\n    description: 'Fixed public host name; Owner DID and Zone DID become did:web:<domain>',\n    type: 'string',\n    required: true,\n  },\n  {\n    name: 'owner-name',\n    property: 'owner_name',\n    description: 'Local administrator / OwnerDocument name (lowercase DNS label)',\n    type: 'string',\n    required: true,\n  },\n  {\n    name: 'owner-key-backup',\n    property: 'owner_key_backup',\n    description:\n      'New file for the Owner private-key recovery copy; its directory must exist and the file must not',\n    type: 'string',\n    required: true,\n  },\n  {\n    name: 'public-ip',\n    property: 'public_ip',\n    description: 'Fixed public IP used only for the A/AAAA record instructions',\n    type: 'string',\n  },\n  {\n    name: 'rtcp-port',\n    property: 'rtcp_port',\n    description: 'RTCP port, default 2980',\n    type: 'integer',\n  },\n  {\n    name: 'guest-access',\n    property: 'guest_access',\n    description: 'Enable guest access in the first-boot configuration',\n    type: 'boolean',\n  },\n]\n\nconst TARGET_INPUT_PROPERTIES: Record<string, JsonSchema> = {\n  root: { type: 'string', minLength: 1 },\n  domain: { type: 'string', minLength: 1 },\n  owner_name: { type: 'string', minLength: 1 },\n  owner_key_backup: { type: 'string', minLength: 1 },\n  public_ip: { type: 'string' },\n  rtcp_port: { type: 'integer', minimum: 1 },\n  guest_access: { type: 'boolean' },\n}\n\nconst TARGET_REQUIRED = ['root', 'domain', 'owner_name', 'owner_key_backup']\n\nconst POLICY_NOTE =\n  'Paths are read from argv by the launcher to grant the minimal filesystem permissions; ' +\n  'root and owner_key_backup given only inside --input are limited to the policy roots (cwd, ' +\n  'and the paired BUCKYOS_ROOT of the system distribution).'\n\nexport function createProvisionModule(\n  dependencies: ProvisionModuleDependencies = {},\n): CommandModule {\n  const deps: ResolvedDependencies = {\n    inspect: dependencies.inspect ?? sdk.inspectActivationRoot,\n    check: dependencies.check ?? sdk.checkOfflineActivation,\n    activate: dependencies.activate ?? sdk.activateOfflineZone,\n  }\n  return {\n    name: 'provision',\n    summary: 'Activate an installed BuckyOS root on this machine (first Zone, Owner, and OOD)',\n    commands: [statusCommand(deps), checkCommand(deps), activateCommand(deps)],\n  }\n}\n\ntype ResolvedDependencies = Required<ProvisionModuleDependencies>\n\nfunction statusCommand(deps: ResolvedDependencies): CommandDefinition {\n  return {\n    verb: 'status',\n    summary: 'Inspect the local activation material of an installed BuckyOS root',\n    description:\n      'Read-only. Reports not_installed, unactivated, partial, configured, or invalid from the ' +\n      'files under the root; configured only means the first-boot material is complete and internally ' +\n      'consistent (startup_required=true). Service health, DNS, TLS, and public DID discovery are not checked. ' +\n      POLICY_NOTE,\n    options: [ROOT_OPTION],\n    inputSchema: {\n      type: 'object',\n      properties: { root: { type: 'string', minLength: 1 } },\n      required: ['root'],\n      additionalProperties: false,\n    },\n    outputSchema: {\n      ...OBJECT_OUTPUT,\n      properties: {\n        root: { type: 'string' },\n        state: {\n          type: 'string',\n          enum: ['not_installed', 'unactivated', 'partial', 'configured', 'invalid'],\n        },\n        startup_required: { type: 'boolean' },\n      },\n      required: ['root', 'state', 'startup_required'],\n    },\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: false,\n    execution: 'local',\n    networkAccess: false,\n    examples: ['buckyos provision status --root /opt/buckyos'],\n    handler: async (ctx, input) => {\n      const root = resolvePath(ctx, requiredString(input, 'root'))\n      await assertHostAccess(root, 'read')\n      return statusView(await runSdk(() => deps.inspect(root)))\n    },\n  }\n}\n\nfunction checkCommand(deps: ResolvedDependencies): CommandDefinition {\n  return {\n    verb: 'check',\n    summary: 'Validate activation parameters and the target root without writing anything',\n    description:\n      'Read-only precheck shared with activate: parameters, target state, and the owner key ' +\n      'backup location. No keys are generated, no backup is written, and no operation is produced; ' +\n      'activate re-validates the target itself. Fails with the first problem code when the target is not ready. ' +\n      POLICY_NOTE,\n    options: TARGET_OPTIONS,\n    inputSchema: {\n      type: 'object',\n      properties: TARGET_INPUT_PROPERTIES,\n      required: TARGET_REQUIRED,\n      additionalProperties: false,\n    },\n    outputSchema: {\n      ...OBJECT_OUTPUT,\n      properties: {\n        ready: { type: 'boolean' },\n        root: { type: 'string' },\n        state: { type: 'string' },\n      },\n      required: ['ready', 'root', 'state'],\n    },\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: false,\n    execution: 'local',\n    networkAccess: false,\n    examples: [\n      'buckyos provision check --root /opt/buckyos --domain corp.example.com --owner-name admin --owner-key-backup /secure-backup/corp-owner.pem',\n    ],\n    handler: async (ctx, input) => {\n      const options = activationOptions(ctx, input)\n      await assertHostAccess(options.rootDir, 'read')\n      await assertHostAccess(getHost().path.dirname(options.ownerKeyBackupPath), 'read')\n      const precheck = await runSdk(() => deps.check(options))\n      if (!precheck.ready) throw precheckError(precheck)\n      return precheckView(precheck)\n    },\n  }\n}\n\nfunction activateCommand(deps: ResolvedDependencies): CommandDefinition {\n  return {\n    verb: 'activate',\n    summary:\n      'Activate the root: create the first Zone, Owner, and OOD identity and the first-boot configuration',\n    description:\n      'Privileged local write. Generates random Ed25519 Owner/device keys and current-time documents, ' +\n      'saves the Owner private-key backup, then commits the identity, Zone, and start_config files; ' +\n      'etc/node_identity.json is written last because node-daemon treats it as the activation switch. ' +\n      'The administrator password is read from the secret admin_password field of --input JSON or from a ' +\n      'hidden terminal prompt; there is no --admin-password option. Non-interactive runs require --yes. ' +\n      'Repeated, partial, and invalid targets are rejected; there is no --force. After success restart ' +\n      'BuckyOS through the installer or node control entry; this command never reports the Zone as online. ' +\n      POLICY_NOTE,\n    options: TARGET_OPTIONS,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        ...TARGET_INPUT_PROPERTIES,\n        admin_password: {\n          type: 'string',\n          secret: true,\n          description: 'Administrator password (secret; --input JSON or hidden prompt only)',\n        },\n      },\n      required: TARGET_REQUIRED,\n      additionalProperties: false,\n    },\n    outputSchema: {\n      ...OBJECT_OUTPUT,\n      properties: {\n        root: { type: 'string' },\n        state: { type: 'string', enum: ['configured'] },\n        startup_required: { type: 'boolean' },\n      },\n      required: ['root', 'state', 'startup_required'],\n    },\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'privileged' },\n    asyncMode: 'sync',\n    requiresSession: false,\n    execution: 'local',\n    networkAccess: false,\n    examples: [\n      'buckyos provision activate --root /opt/buckyos --domain corp.example.com --owner-name admin --owner-key-backup /secure-backup/corp-owner.pem',\n      'buckyos --non-interactive --yes --input activation.json provision activate --root /opt/buckyos --owner-key-backup /secure-backup/corp-owner.pem',\n    ],\n    handler: async (ctx, input) => {\n      const options = activationOptions(ctx, input)\n      const backupDirectory = getHost().path.dirname(options.ownerKeyBackupPath)\n      await assertHostAccess(options.rootDir, 'read')\n      await assertHostAccess(options.rootDir, 'write')\n      await assertHostAccess(backupDirectory, 'read')\n      await assertHostAccess(backupDirectory, 'write')\n      const precheck = await runSdk(() => deps.check(options))\n      if (!precheck.ready) throw precheckError(precheck)\n      const adminPassword = await obtainAdminPassword(ctx, input)\n      await confirmActivation(ctx, precheck)\n      const result = await runSdk(() =>\n        deps.activate({ ...options, adminPassword, traceId: ctx.traceId })\n      )\n      return resultView(ctx, input, result)\n    },\n  }\n}\n\n// ---------------------------------------------------------------------------\n// input handling\n// ---------------------------------------------------------------------------\n\nfunction activationOptions(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n): OfflineActivationCheckOptions {\n  return {\n    rootDir: resolvePath(ctx, requiredString(input, 'root')),\n    domain: requiredString(input, 'domain'),\n    ownerName: requiredString(input, 'owner_name'),\n    ownerKeyBackupPath: resolvePath(ctx, requiredString(input, 'owner_key_backup')),\n    publicIp: optionalString(input, 'public_ip'),\n    rtcpPort: typeof input.rtcp_port === 'number' ? input.rtcp_port : undefined,\n    guestAccess: input.guest_access === true,\n  }\n}\n\nfunction requiredString(input: Record<string, unknown>, key: string): string {\n  const value = optionalString(input, key)\n  if (!value) throw new UsageError('INVALID_ARGUMENT', `${key} is required`)\n  return value\n}\n\nfunction optionalString(input: Record<string, unknown>, key: string): string | undefined {\n  const value = input[key]\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\nfunction resolvePath(ctx: CommandContext, value: string): string {\n  const path = getHost().path\n  return path.isAbsolute(value) ? path.resolve(value) : path.resolve(ctx.cwd, value)\n}\n\nasync function assertHostAccess(path: string, operation: 'read' | 'write'): Promise<void> {\n  try {\n    await getHost().assertAccess(path, operation)\n  } catch (error) {\n    if (isHostError(error, 'PermissionDenied')) {\n      throw new ToolError(\n        'HOST_ACCESS_DENIED',\n        `${error.message}; pass the path on the command line (--root / --owner-key-backup) so the launcher can grant it`,\n        EXIT_PERMISSION,\n        false,\n        { path, operation },\n      )\n    }\n    throw error\n  }\n}\n\nasync function obtainAdminPassword(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n): Promise<string> {\n  if (typeof input.admin_password === 'string') return input.admin_password\n  if (ctx.config.nonInteractive) {\n    throw new UsageError(\n      'SECRET_REQUIRED',\n      'admin_password must be provided through --input JSON in non-interactive mode',\n    )\n  }\n  if (!ctx.io.inputIsTerminal) {\n    throw new UsageError(\n      'SECRET_INPUT_UNAVAILABLE',\n      'the administrator password requires an interactive terminal or --input JSON',\n    )\n  }\n  const host = getHost()\n  let password: string\n  let confirmation: string\n  try {\n    password = await host.readSecret('Administrator password: ')\n    confirmation = await host.readSecret('Confirm administrator password: ')\n  } catch (error) {\n    if (isHostError(error, 'PermissionDenied')) {\n      throw new UsageError('SECRET_INPUT_UNAVAILABLE', error.message)\n    }\n    throw error\n  }\n  if (password !== confirmation) {\n    throw new UsageError('PASSWORD_MISMATCH', 'the administrator passwords do not match')\n  }\n  return password\n}\n\nasync function confirmActivation(\n  ctx: CommandContext,\n  precheck: OfflineActivationPrecheck,\n): Promise<void> {\n  if (ctx.confirmed) return\n  if (ctx.config.nonInteractive) {\n    throw new ToolError(\n      'CONFIRMATION_REQUIRED',\n      'provision activate requires --yes in non-interactive mode',\n      EXIT_PERMISSION,\n    )\n  }\n  if (!ctx.io.inputIsTerminal) {\n    throw new ToolError(\n      'CONFIRMATION_REQUIRED',\n      'provision activate requires an interactive terminal or --yes',\n      EXIT_PERMISSION,\n    )\n  }\n  await ctx.io.stderr(\n    [\n      'Activation summary',\n      `  BUCKYOS_ROOT : ${precheck.rootDir}`,\n      `  Owner/Zone   : ${precheck.zoneDid}`,\n      `  Device       : ${precheck.deviceDid}`,\n      `  Admin        : ${precheck.ownerName}`,\n      `  Network      : ${'wan'} (no SN, no BNS)`,\n      `  RTCP port    : ${precheck.rtcpPort}`,\n      `  Guest access : ${precheck.guestAccess}`,\n      `  Owner backup : ${precheck.ownerKeyBackup.path}`,\n      '',\n    ].join('\\n'),\n  )\n  const answer = (await ctx.io.prompt('Write this activation to disk? [y/N] '))?.trim()\n    .toLowerCase()\n  if (answer !== 'y' && answer !== 'yes') {\n    throw new ToolError('CONFIRMATION_DECLINED', 'activation was declined', EXIT_PERMISSION)\n  }\n}\n\n// ---------------------------------------------------------------------------\n// SDK error mapping\n// ---------------------------------------------------------------------------\n\ninterface SdkError extends Error {\n  code: string\n  details: Record<string, unknown>\n}\n\nfunction isSdkError(error: unknown): error is SdkError {\n  return error instanceof Error && error.name === 'ActivationError' &&\n    typeof (error as { code?: unknown }).code === 'string'\n}\n\nasync function runSdk<T>(run: () => Promise<T>): Promise<T> {\n  try {\n    return await run()\n  } catch (error) {\n    if (isSdkError(error)) {\n      const exitCode = error.code === 'INVALID_ARGUMENT'\n        ? EXIT_USAGE\n        : error.code === 'ACTIVATION_COMMIT_FAILED'\n        ? EXIT_PARTIAL\n        : EXIT_OPERATION\n      throw new ToolError(error.code, error.message, exitCode, false, error.details ?? {})\n    }\n    throw error\n  }\n}\n\nfunction precheckError(precheck: OfflineActivationPrecheck): ToolError {\n  const [first] = precheck.problems\n  const single = precheck.problems.length === 1\n  return new ToolError(\n    single ? first.code : 'ACTIVATION_PRECHECK_FAILED',\n    single\n      ? first.message\n      : `activation precheck failed: ${precheck.problems.map((p) => p.message).join('; ')}`,\n    EXIT_OPERATION,\n    false,\n    precheckView(precheck),\n  )\n}\n\n// ---------------------------------------------------------------------------\n// output views (snake_case, never secrets)\n// ---------------------------------------------------------------------------\n\nfunction statusView(status: ActivationStatus): Record<string, unknown> {\n  return {\n    root: status.rootDir,\n    state: status.state,\n    startup_required: status.startupRequired,\n    observed_at: status.observedAt,\n    zone_did: status.zoneDid,\n    owner_did: status.ownerDid,\n    device_did: status.deviceDid,\n    device_name: status.deviceName,\n    access_hostname: status.accessHostname,\n    files: status.files.map((file) => ({\n      path: file.path,\n      role: file.role,\n      required: file.required,\n      secret: file.secret,\n      present: file.present,\n    })),\n    problems: status.problems,\n    warnings: status.warnings,\n    lock: status.lock\n      ? {\n        path: status.lock.path,\n        stage: status.lock.stage,\n        trace_id: status.lock.traceId,\n        started_at: status.lock.startedAt,\n        domain: status.lock.domain,\n        committed_files: status.lock.committedFiles,\n        owner_key_backup: status.lock.ownerKeyBackupPath,\n        corrupt: status.lock.corrupt,\n      }\n      : null,\n  }\n}\n\nfunction precheckView(precheck: OfflineActivationPrecheck): Record<string, unknown> {\n  return {\n    ready: precheck.ready,\n    root: precheck.rootDir,\n    state: precheck.state,\n    domain: precheck.domain,\n    owner_name: precheck.ownerName,\n    owner_did: precheck.ownerDid,\n    zone_did: precheck.zoneDid,\n    device_did: precheck.deviceDid,\n    device_name: precheck.deviceName,\n    access_hostname: precheck.accessHostname,\n    rtcp_port: precheck.rtcpPort,\n    guest_access: precheck.guestAccess,\n    public_ip: precheck.publicIp,\n    dns_records: precheck.dnsRecords,\n    owner_key_backup: {\n      path: precheck.ownerKeyBackup.path,\n      directory_exists: precheck.ownerKeyBackup.directoryExists,\n      exists: precheck.ownerKeyBackup.exists,\n    },\n    planned_files: precheck.plannedFiles,\n    problems: precheck.problems,\n    target: statusView(precheck.status),\n  }\n}\n\nfunction resultView(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  result: OfflineActivationResult,\n): Record<string, unknown> {\n  const dnsNotes = [\n    ...result.dnsRecords.map((record) => `${record.type} ${record.name} ${record.value}`),\n    ...(result.publicIp ? [] : [`A/AAAA ${result.domain} <this node's fixed public IP>`]),\n    `The address record is also saved in etc/zone_dns_records.json under ${result.rootDir}.`,\n    `Local boot uses etc/${result.domain}.zone.json; no DNS BOOT/PKX/DEV records are required.`,\n    'TLS/ACME is not provided by SN in this mode; configure it on the public gateway.',\n  ]\n  return {\n    root: result.rootDir,\n    state: result.state,\n    startup_required: result.startupRequired,\n    domain: result.domain,\n    owner_name: result.ownerName,\n    owner_did: result.ownerDid,\n    zone_did: result.zoneDid,\n    device_did: result.deviceDid,\n    device_name: result.deviceName,\n    access_hostname: result.accessHostname,\n    rtcp_port: result.rtcpPort,\n    guest_access: result.guestAccess,\n    public_ip: result.publicIp,\n    document_iat: result.documentIat,\n    document_exp: result.documentExp,\n    owner_key_backup: result.ownerKeyBackup,\n    dns_records: result.dnsRecords,\n    dns_notes: dnsNotes,\n    committed_files: result.committedFiles,\n    warnings: result.warnings,\n    next_steps: [\n      'Restart BuckyOS through the installer or the node control entry to leave activation mode and boot the new Zone.',\n      'Check the running Zone afterwards with system status; activation does not verify service health, DNS, or TLS.',\n      `Keep the Owner private-key backup ${result.ownerKeyBackup.path} offline; it is the only recovery copy.`,\n    ],\n    audit: {\n      module: ctx.command.module,\n      verb: ctx.command.verb,\n      trace_id: ctx.traceId,\n      tool_version: TOOL_VERSION,\n      input_fingerprint: inputFingerprint(input),\n    },\n  }\n}\n\nfunction inputFingerprint(input: Record<string, unknown>): string {\n  const material: Record<string, unknown> = {}\n  for (const key of Object.keys(TARGET_INPUT_PROPERTIES).sort()) {\n    if (input[key] !== undefined) material[key] = input[key]\n  }\n  const hash = getHost().createHash('sha256')\n  hash.update(new TextEncoder().encode(JSON.stringify(material)))\n  return hash.digestHex()\n}\n","import type { CommandDefinition, CommandModule, JsonSchema, OptionDefinition } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { EXIT_INTERNAL, EXIT_PERMISSION, EXIT_UNAVAILABLE, ToolError, UsageError } from '../core/errors.ts'\nimport { callService, inputString, requiredInputString } from '../core/service.ts'\nimport { getHost, isHostError } from '../runtime/host.ts'\nimport { type AppModuleDependencies, classifySource, downloadPikg, isDidSource } from './app.ts'\nimport { openZip, readTarGz, readZipEntry, sha256Bytes } from './pikg_archive.ts'\nimport { inspectPikg } from './pikg_protocol.ts'\nimport { lintSkillPackage, readSkillDirectory, SKILL_DIRS, SKILL_KINDS, type SkillPackageFile } from './skill_lint.ts'\n\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst SKILLS_SUB_PKG = 'agent_skills'\nconst SKILL_SCOPES = ['ui', 'work']\nconst IMPORT_SCOPES = ['work', 'ui', 'plan']\nconst SOURCE_KINDS = ['pikg', 'dir', 'url', 'did']\nconst MAX_SKILL_PAYLOAD_BYTES = 64 * 1024 * 1024\nconst MAX_IMPORT_TEXT_BYTES = 512 * 1024\nconst AGENT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\nexport interface SkillModuleDependencies {\n  /** Downloads a skill PIKG (`skill install <url>`). */\n  download?: AppModuleDependencies['download']\n  /** Fetches the text `skill import <url>` hands to the Agent. */\n  fetchText?: (url: URL, signal: AbortSignal) => Promise<string>\n  readStdin?: () => Promise<string>\n}\n\nconst AGENT_OPTION: OptionDefinition = {\n  name: 'agent',\n  property: 'agent_id',\n  description: 'Agent ID; the Agent serves kRPC at /kapi/<agent_id>',\n  type: 'string',\n  required: true,\n}\n\nconst KIND_OPTION: OptionDefinition = {\n  name: 'kind',\n  description: 'Skill kind',\n  type: 'string',\n  enum: [...SKILL_KINDS],\n}\n\nconst RUNTIME_OPTION: OptionDefinition = {\n  name: 'runtime',\n  property: 'runtime_id',\n  description: 'Runtime id (default: the private runtime)',\n  type: 'string',\n}\n\nconst AGENT_PROPERTY: JsonSchema = { type: 'string', minLength: 1 }\nconst NAME_PROPERTY: JsonSchema = { type: 'string', minLength: 1 }\nconst KIND_PROPERTY: JsonSchema = { type: 'string', enum: [...SKILL_KINDS] }\n\nfunction command(\n  definition: Pick<CommandDefinition, 'verb' | 'summary' | 'handler'> & Partial<CommandDefinition> & {\n    level: 'read' | 'write' | 'destructive'\n    properties: Record<string, JsonSchema>\n    required?: string[]\n  },\n): CommandDefinition {\n  const { level, properties, required, ...rest } = definition\n  return {\n    options: [AGENT_OPTION],\n    inputSchema: {\n      type: 'object',\n      properties: { agent_id: AGENT_PROPERTY, ...properties },\n      required: ['agent_id', ...(required ?? [])],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level },\n    asyncMode: 'sync',\n    requiresSession: true,\n    ...rest,\n  }\n}\n\nexport function createSkillModule(dependencies: SkillModuleDependencies = {}): CommandModule {\n  return {\n    name: 'skill',\n    summary: 'List, install, enable, and remove the work/plan/goal skills of an Agent',\n    commands: [\n      command({\n        verb: 'list',\n        summary: 'List the skills of an Agent',\n        description:\n          'Skills that no new session takes (disabled by the owner) are left out unless --all, which also lists the drafts waiting for the owner. --scope selects work skills by scope. --stats adds how often each manual was frozen, and the count of work created without any manual.',\n        options: [\n          AGENT_OPTION,\n          KIND_OPTION,\n          { name: 'scope', description: 'Work skills whose scope includes this', type: 'string', enum: SKILL_SCOPES },\n          { name: 'all', description: 'Include skills that are not enabled, and drafts', type: 'boolean' },\n          { name: 'stats', description: 'Include usage', type: 'boolean' },\n        ],\n        level: 'read',\n        properties: {\n          kind: KIND_PROPERTY,\n          scope: { type: 'string', enum: SKILL_SCOPES },\n          all: { type: 'boolean' },\n          stats: { type: 'boolean' },\n        },\n        examples: [\n          'buckyos skill list --agent jarvis.example.zone',\n          'buckyos skill list --agent jarvis.example.zone --kind work --scope ui',\n          'buckyos skill list --agent jarvis.example.zone --all --stats',\n        ],\n        handler: async (ctx, input) => await listCommand(ctx, input),\n      }),\n      command({\n        verb: 'status',\n        summary:\n          'Whether each work skill works on a runtime of the Agent: baseline and platform, the commands it relies on, and the extension package that would bring what is missing',\n        options: [AGENT_OPTION, RUNTIME_OPTION],\n        level: 'read',\n        properties: { runtime_id: { type: 'string', minLength: 1 } },\n        examples: ['buckyos skill status --agent jarvis.example.zone --runtime host'],\n        handler: async (ctx, input) =>\n          await callService<Record<string, unknown>>(ctx, agentIdFrom(input), 'skills.status', {\n            runtime_id: input.runtime_id ?? null,\n          }),\n      }),\n      command({\n        verb: 'install',\n        summary: 'Install skills into an Agent: plan, confirm, install',\n        description:\n          'The source is a skill PIKG (local file or HTTP(S) URL; verified offline, app_type agent_skills), a directory laid out like its agent_skills sub package (cmd_skills/, plan_skills/, goal_skills/; the package is named after the directory), or --draft <slug> for a draft in the AgentRoot. A skill is text only: a package with tools/ (commands, install scripts) or a file that is not UTF-8 text is refused; commands come from the standard layer or from extension packages (buckyos ext-tools) and a manual only names them in `commands`. The Agent plans the installation first (nothing is written): the plan and its risk findings are shown and must be confirmed; --yes accepts every risk level. Installing is checking and copying: nothing runs. Only the owner installs. Sessions created before keep their frozen manuals.',\n        positionals: [{ name: 'source', description: 'Skill .pikg file, skill directory, or HTTP(S) URL', required: false }],\n        options: [\n          AGENT_OPTION,\n          { name: 'from', description: 'Force source type', type: 'string', enum: SOURCE_KINDS },\n          { name: 'draft', description: 'Install this draft of the AgentRoot (skills_drafts/<slug>) instead of a source', type: 'string' },\n          { ...RUNTIME_OPTION, description: 'Runtime the commands the manuals name are checked against in the plan (default: the private runtime)' },\n          { name: 'replace', description: 'Replace skills of the same names from another package', type: 'boolean' },\n        ],\n        level: 'write',\n        properties: {\n          source: { type: 'string', minLength: 1 },\n          from: { type: 'string', enum: SOURCE_KINDS },\n          draft: { type: 'string', minLength: 1 },\n          runtime_id: { type: 'string', minLength: 1 },\n          replace: { type: 'boolean' },\n        },\n        examples: [\n          'buckyos skill install ./dapp_dist/hello-skills-0.1.0.pikg --agent jarvis.example.zone',\n          'buckyos --yes skill install ./skills --agent jarvis.example.zone --replace',\n          'buckyos skill install https://example.com/hello-skills-0.1.0.pikg --agent jarvis.example.zone',\n          'buckyos skill install --draft notes-to-slides --agent jarvis.example.zone',\n        ],\n        handler: async (ctx, input) => await installCommand(ctx, input, dependencies),\n      }),\n      command({\n        verb: 'remove',\n        summary: 'Remove an installed skill from an Agent',\n        description: 'Only installed and imported skills can be removed. Without --kind the kind is looked up by name.',\n        positionals: [{ name: 'name', description: 'Skill name' }],\n        options: [AGENT_OPTION, KIND_OPTION],\n        level: 'destructive',\n        properties: { name: NAME_PROPERTY, kind: KIND_PROPERTY },\n        required: ['name'],\n        examples: ['buckyos --yes skill remove hello --agent jarvis.example.zone --kind work'],\n        handler: async (ctx, input) => {\n          const agentId = agentIdFrom(input)\n          const name = requiredInputString(input, 'name')\n          const kind = await kindOf(ctx, agentId, name, input)\n          await confirm(ctx, 'skill remove', `Remove ${kind} skill ${name} from ${agentId}?`)\n          const removed = await callService<unknown>(ctx, agentId, 'skills.remove', { kind, name })\n          return { agent_id: agentId, removed: expectObject(removed, 'skills.remove') }\n        },\n      }),\n      command({\n        verb: 'disable',\n        summary: 'Disable a skill of an Agent: no new session takes it',\n        description:\n          'Any skill can be disabled, package ones included. Running sessions keep what they froze. Without --kind the kind is looked up by name.',\n        positionals: [{ name: 'name', description: 'Skill name' }],\n        options: [AGENT_OPTION, KIND_OPTION, { name: 'reason', description: 'Why, for the record', type: 'string' }],\n        level: 'write',\n        properties: { name: NAME_PROPERTY, kind: KIND_PROPERTY, reason: { type: 'string' } },\n        required: ['name'],\n        examples: ['buckyos skill disable aigc_video --agent jarvis.example.zone --reason \"no provider\"'],\n        handler: async (ctx, input) => await setEnabled(ctx, input, false),\n      }),\n      command({\n        verb: 'enable',\n        summary: 'Enable a disabled skill of an Agent',\n        positionals: [{ name: 'name', description: 'Skill name' }],\n        options: [AGENT_OPTION, KIND_OPTION],\n        level: 'write',\n        properties: { name: NAME_PROPERTY, kind: KIND_PROPERTY },\n        required: ['name'],\n        examples: ['buckyos skill enable aigc_video --agent jarvis.example.zone'],\n        handler: async (ctx, input) => await setEnabled(ctx, input, true),\n      }),\n      command({\n        verb: 'ui-list',\n        summary: 'The work skills every new conversation (UI session) of the Agent takes',\n        level: 'read',\n        properties: {},\n        examples: ['buckyos skill ui-list --agent jarvis.example.zone'],\n        handler: async (ctx, input) => {\n          const agentId = agentIdFrom(input)\n          return { agent_id: agentId, ...await uiGet(ctx, agentId) }\n        },\n      }),\n      command({\n        verb: 'ui-add',\n        summary: 'Add a skill whose scope includes ui to the conversations of the Agent',\n        description:\n          'Takes effect in conversations created afterwards. The result gives total_bytes: every conversation carries that much manual text.',\n        positionals: [{ name: 'name', description: 'Skill name' }],\n        level: 'write',\n        properties: { name: NAME_PROPERTY },\n        required: ['name'],\n        examples: ['buckyos skill ui-add share --agent jarvis.example.zone'],\n        handler: async (ctx, input) => await uiChange(ctx, input, true),\n      }),\n      command({\n        verb: 'ui-remove',\n        summary: 'Take a skill out of the conversations of the Agent',\n        positionals: [{ name: 'name', description: 'Skill name' }],\n        level: 'write',\n        properties: { name: NAME_PROPERTY },\n        required: ['name'],\n        examples: ['buckyos skill ui-remove share --agent jarvis.example.zone'],\n        handler: async (ctx, input) => await uiChange(ctx, input, false),\n      }),\n      command({\n        verb: 'import',\n        summary: 'Hand a text to the Agent to turn into a skill draft',\n        description:\n          'Reads the text from a file, an HTTP(S) URL, or stdin (-). The Agent starts a work session that writes a draft under skills_drafts/; nothing is installed. The owner reads the draft (skill drafts, skill draft-show) and installs it with skill install --draft <slug>.',\n        positionals: [{ name: 'source', description: 'Text file, HTTP(S) URL, or - for stdin' }],\n        options: [\n          AGENT_OPTION,\n          { name: 'name', description: 'Slug of the draft', type: 'string' },\n          { name: 'scope', description: 'What to make of it', type: 'string', enum: IMPORT_SCOPES },\n          { ...RUNTIME_OPTION, description: 'Runtime the commands the text names are checked on (default: the private runtime)' },\n        ],\n        level: 'write',\n        properties: {\n          source: { type: 'string', minLength: 1 },\n          name: { type: 'string', minLength: 1 },\n          scope: { type: 'string', enum: IMPORT_SCOPES },\n          runtime_id: { type: 'string', minLength: 1 },\n        },\n        required: ['source'],\n        examples: [\n          'buckyos skill import ./notes/release-checklist.md --agent jarvis.example.zone --name release_checklist',\n          'cat howto.md | buckyos skill import - --agent jarvis.example.zone --scope plan',\n        ],\n        handler: async (ctx, input) => await importCommand(ctx, input, dependencies),\n      }),\n      command({\n        verb: 'drafts',\n        summary: 'List the skill drafts of an Agent that wait for the owner',\n        level: 'read',\n        properties: {},\n        examples: ['buckyos skill drafts --agent jarvis.example.zone'],\n        handler: async (ctx, input) => {\n          const agentId = agentIdFrom(input)\n          const drafts = await listDrafts(ctx, agentId)\n          return { agent_id: agentId, total: drafts.length, drafts }\n        },\n      }),\n      command({\n        verb: 'draft-show',\n        summary: 'Show a skill draft, or one of its files',\n        positionals: [{ name: 'slug', description: 'Draft slug' }],\n        options: [AGENT_OPTION, { name: 'file', description: 'Draft-relative path of a file to print', type: 'string' }],\n        level: 'read',\n        properties: { slug: NAME_PROPERTY, file: { type: 'string', minLength: 1 } },\n        required: ['slug'],\n        examples: [\n          'buckyos skill draft-show release_checklist --agent jarvis.example.zone',\n          'buckyos skill draft-show release_checklist --file cmd_skills/release_checklist/SKILL.md --agent jarvis.example.zone',\n        ],\n        handler: async (ctx, input) => {\n          const agentId = agentIdFrom(input)\n          const slug = requiredInputString(input, 'slug')\n          const file = inputString(input, 'file')\n          if (file) {\n            const shown = expectObject(await callService<unknown>(ctx, agentId, 'skills.draft_file', { slug, file }), 'skills.draft_file')\n            return { agent_id: agentId, slug, file, text: shown.text }\n          }\n          const draft = (await listDrafts(ctx, agentId)).find((item) => item.slug === slug)\n          if (!draft) throw new ToolError('RESOURCE_NOT_FOUND', `Agent ${agentId} has no skill draft ${slug}`)\n          return { agent_id: agentId, ...draft, install_command: `buckyos skill install --draft ${slug} --agent ${agentId}` }\n        },\n      }),\n      command({\n        verb: 'draft-discard',\n        summary: 'Delete a skill draft',\n        positionals: [{ name: 'slug', description: 'Draft slug' }],\n        level: 'destructive',\n        properties: { slug: NAME_PROPERTY },\n        required: ['slug'],\n        examples: ['buckyos --yes skill draft-discard release_checklist --agent jarvis.example.zone'],\n        handler: async (ctx, input) => {\n          const agentId = agentIdFrom(input)\n          const slug = requiredInputString(input, 'slug')\n          await confirm(ctx, 'skill draft-discard', `Discard skill draft ${slug} of ${agentId}?`)\n          await callService<unknown>(ctx, agentId, 'skills.draft_discard', { slug })\n          return { agent_id: agentId, discarded: slug }\n        },\n      }),\n    ],\n  }\n}\n\nasync function listCommand(ctx: CommandContext, input: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const agentId = agentIdFrom(input)\n  const scope = inputString(input, 'scope')\n  let kind = inputString(input, 'kind')\n  if (scope) {\n    if (kind && kind !== 'work') throw new UsageError('ARGUMENT_CONFLICT', `--scope selects work skills; a ${kind} skill has no scope`)\n    kind = 'work'\n  }\n  const listed = (await listSkills(ctx, agentId, kind)).filter((skill) => {\n    if (!scope) return true\n    const own = typeof skill.scope === 'string' ? skill.scope.split(',').map((word) => word.trim()) : ['work']\n    return own.includes(scope)\n  })\n  const shown = input.all === true ? listed : listed.filter((skill) => skill.enabled !== false)\n  const stats = input.stats === true\n  const skills = stats ? shown : shown.map(({ usage: _usage, ...skill }) => skill)\n  const result: Record<string, unknown> = {\n    agent_id: agentId,\n    ...(kind ? { kind } : {}),\n    ...(scope ? { scope } : {}),\n    total: skills.length,\n    not_enabled: listed.length - listed.filter((skill) => skill.enabled !== false).length,\n    skills,\n  }\n  if (stats) {\n    const state = expectObject(await callService<unknown>(ctx, agentId, 'skills.state', {}), 'skills.state')\n    const usage = state.usage && typeof state.usage === 'object' ? state.usage as Record<string, unknown> : {}\n    result.usage_none = usage.none ?? { frozen: 0, last_ms: 0 }\n  }\n  if (input.all === true) result.drafts = await listDrafts(ctx, agentId)\n  return result\n}\n\nasync function setEnabled(ctx: CommandContext, input: Record<string, unknown>, enabled: boolean): Promise<Record<string, unknown>> {\n  const agentId = agentIdFrom(input)\n  const name = requiredInputString(input, 'name')\n  const kind = await kindOf(ctx, agentId, name, input)\n  const reason = inputString(input, 'reason')\n  const skill = await callService<unknown>(ctx, agentId, 'skills.set_enabled', {\n    kind,\n    name,\n    enabled,\n    ...(reason ? { reason } : {}),\n  })\n  return { agent_id: agentId, skill: expectObject(skill, 'skills.set_enabled') }\n}\n\nasync function uiGet(ctx: CommandContext, agentId: string): Promise<Record<string, unknown> & { names: string[] }> {\n  const ui = expectObject(await callService<unknown>(ctx, agentId, 'skills.ui_get', {}), 'skills.ui_get')\n  if (!Array.isArray(ui.names)) invalidResponse('skills.ui_get')\n  return { ...ui, names: (ui.names as unknown[]).map(String) }\n}\n\nasync function uiChange(ctx: CommandContext, input: Record<string, unknown>, add: boolean): Promise<Record<string, unknown>> {\n  const agentId = agentIdFrom(input)\n  const name = requiredInputString(input, 'name')\n  const current = await uiGet(ctx, agentId)\n  const has = current.names.includes(name)\n  if (!add && !has) {\n    throw new ToolError('RESOURCE_NOT_FOUND', `${name} is not among the UI skills of ${agentId} (${current.names.join(', ') || 'none'})`)\n  }\n  if (add && has) return { agent_id: agentId, changed: false, ...current }\n  const names = add ? [...current.names, name] : current.names.filter((item) => item !== name)\n  const ui = expectObject(await callService<unknown>(ctx, agentId, 'skills.ui_set', { names }), 'skills.ui_set')\n  return { agent_id: agentId, changed: true, ...ui }\n}\n\ninterface SkillSource {\n  summary: Record<string, unknown>\n  params: Record<string, unknown>\n  extra: Record<string, unknown>\n}\n\nasync function installCommand(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  dependencies: SkillModuleDependencies,\n): Promise<Record<string, unknown>> {\n  const agentId = agentIdFrom(input)\n  const source = await skillSource(ctx, input, dependencies)\n  const runtimeId = inputString(input, 'runtime_id')\n  const runtime = runtimeId ? { runtime_id: runtimeId } : {}\n  const plan = expectObject(\n    await callService<unknown>(ctx, agentId, 'skills.install_plan', { ...source.params, ...runtime }),\n    'skills.install_plan',\n  )\n  const planDigest = plan.plan_digest\n  if (typeof planDigest !== 'string' || !planDigest) invalidResponse('skills.install_plan')\n  if (!ctx.confirmed) {\n    if (ctx.config.nonInteractive || !ctx.io.inputIsTerminal) {\n      throw new ToolError(\n        'CONFIRMATION_REQUIRED',\n        `skill install requires --yes in non-interactive execution (risk: ${riskLevel(plan)})`,\n        EXIT_PERMISSION,\n        false,\n        { plan },\n      )\n    }\n    await ctx.io.stderr(planText(plan))\n    await confirm(ctx, 'skill install', `Install into ${agentId} (risk: ${riskLevel(plan)})?`)\n  }\n  const report = expectObject(\n    await callService<unknown>(ctx, agentId, 'skills.install', {\n      ...source.params,\n      plan_digest: planDigest,\n      replace: input.replace === true,\n    }),\n    'skills.install',\n  )\n  return { agent_id: agentId, source: source.summary, ...source.extra, plan, ...report }\n}\n\nfunction riskLevel(plan: Record<string, unknown>): string {\n  const risk = plan.risk && typeof plan.risk === 'object' ? plan.risk as Record<string, unknown> : {}\n  return typeof risk.level === 'string' ? risk.level : 'unknown'\n}\n\nfunction planText(plan: Record<string, unknown>): string {\n  const lines = [`Install plan: ${plan.package}${plan.version ? ` ${plan.version}` : ''} (${plan.digest})`]\n  for (const item of Array.isArray(plan.skills) ? plan.skills : []) {\n    const skill = item as Record<string, unknown>\n    const scope = typeof skill.scope === 'string' ? ` [${skill.scope}]` : ''\n    const replaces = skill.replaces ? `; replaces the ${skill.replaces} skill` : ''\n    const commands = Array.isArray(skill.commands) && skill.commands.length ? `; commands: ${skill.commands.join(', ')}` : ''\n    lines.push(`  ${skill.kind} ${skill.name}${scope}: ${skill.description ?? ''}${commands}${replaces}`)\n  }\n  if (plan.checked_runtime_id) lines.push(`Commands checked on runtime: ${plan.checked_runtime_id}`)\n  for (const item of Array.isArray(plan.command_status) ? plan.command_status : []) {\n    const entry = item as Record<string, unknown>\n    const status = entry.status && typeof entry.status === 'object' ? entry.status as Record<string, unknown> : {}\n    if (status.state !== 'partial') continue\n    const states = status.commands && typeof status.commands === 'object' ? status.commands as Record<string, { present?: boolean }> : {}\n    const missing = Object.keys(states).filter((name) => states[name]?.present === false)\n    const packages = (Array.isArray(status.recommended_packages) ? status.recommended_packages : [])\n      .map((pkg) => String((pkg as Record<string, unknown>).id))\n    const none = Array.isArray(status.no_package) ? status.no_package.map(String) : []\n    lines.push(\n      `  ${entry.name}: missing ${missing.join(', ')}` +\n        (packages.length ? `; extension packages that bring them: ${packages.join(', ')} (buckyos ext-tools enable)` : '') +\n        (none.length ? `; no package provides ${none.join(', ')}` : ''),\n    )\n  }\n  const risk = plan.risk && typeof plan.risk === 'object' ? plan.risk as Record<string, unknown> : {}\n  lines.push(`Risk: ${riskLevel(plan)}`)\n  for (const item of Array.isArray(risk.findings) ? risk.findings : []) {\n    const finding = item as Record<string, unknown>\n    lines.push(`  [${finding.level}] ${finding.code} ${finding.where}: ${finding.note}`)\n  }\n  return `${lines.join('\\n')}\\n`\n}\n\nasync function skillSource(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  dependencies: SkillModuleDependencies,\n): Promise<SkillSource> {\n  const host = getHost()\n  const draft = inputString(input, 'draft')\n  const raw = inputString(input, 'source')\n  const forced = inputString(input, 'from')\n  if (draft) {\n    if (raw || forced) throw new UsageError('ARGUMENT_CONFLICT', '--draft takes no <source> and no --from: the Agent reads the draft itself')\n    return { summary: { kind: 'draft', draft }, params: { draft }, extra: {} }\n  }\n  if (!raw) throw new UsageError('MISSING_ARGUMENT', 'a <source> or --draft <slug> is required')\n  const local = host.path.isAbsolute(raw) ? host.path.resolve(raw) : host.path.resolve(ctx.cwd, raw)\n  let directory = forced === 'dir'\n  if (!forced && !/^https?:\\/\\//i.test(raw) && !isDidSource(raw)) {\n    try {\n      directory = (await host.stat(local)).isDirectory\n    } catch (error) {\n      if (!isHostError(error, 'NotFound')) throw error\n    }\n  }\n  if (directory) return await directorySource(local)\n\n  const classified = await classifySource(ctx, { source: raw, ...(forced ? { from: forced === 'did' ? 'catalog' : forced } : {}) })\n  if (classified.kind === 'catalog') {\n    throw new ToolError(\n      'SKILL_SOURCE_UNSUPPORTED',\n      `${classified.display} names a Catalog App, and the Catalog cannot hand a skill PIKG to this tool yet: install from the .pikg file or its URL`,\n      EXIT_UNAVAILABLE,\n    )\n  }\n  if (classified.kind === 'pikg') return await pikgSource(classified.path, { kind: 'pikg', path: classified.path })\n  await host.mkdir(ctx.configStore.root, { recursive: true, mode: 0o700 })\n  const temporary = await host.makeTempDir({ dir: ctx.configStore.root, prefix: '.skill-pikg-' })\n  try {\n    const snapshot = await downloadPikg(classified.url, host.path.join(temporary, 'source.pikg'), dependencies.download, ctx.signal)\n    return await pikgSource(snapshot.path, { kind: 'url', url: snapshot.display })\n  } finally {\n    await host.remove(temporary, { recursive: true }).catch(() => {})\n  }\n}\n\nasync function pikgSource(path: string, summary: Record<string, unknown>): Promise<SkillSource> {\n  const inspection = await inspectPikg(path)\n  if (inspection.app.app_type !== SKILLS_SUB_PKG) {\n    throw new UsageError(\n      'NOT_A_SKILL_PACKAGE',\n      `PIKG app_type is ${inspection.app.app_type}; a skill package has app_type ${SKILLS_SUB_PKG} (buckyos pikg init --kind agent-skills)`,\n    )\n  }\n  const payload = inspection.subpackages.find((item) => item.key === SKILLS_SUB_PKG)\n    ?.payload as { path: string; digest: string }\n  const archive = await openZip(path)\n  const bytes = await readZipEntry(archive, archive.byName.get(payload.path)!, MAX_SKILL_PAYLOAD_BYTES)\n  if (`sha256:${sha256Bytes(bytes)}` !== payload.digest) {\n    throw new ToolError('INVALID_PACKAGE', 'PIKG changed after it was verified')\n  }\n  const files = new Map<string, SkillPackageFile>()\n  const ignored: string[] = []\n  for (const entry of await readTarGz(bytes, MAX_SKILL_PAYLOAD_BYTES)) {\n    if (SKILL_DIRS.includes(entry.path.split('/')[0])) files.set(entry.path, { bytes: entry.bytes })\n    else ignored.push(entry.path)\n  }\n  return {\n    summary,\n    params: {\n      package: {\n        package: inspection.app.name,\n        version: inspection.app.version,\n        pikg_digest: inspection.pikg_digest,\n        files: packageFiles(files),\n      },\n    },\n    extra: { pikg_digest: inspection.pikg_digest, ...(ignored.length ? { ignored_files: ignored } : {}) },\n  }\n}\n\nasync function directorySource(path: string): Promise<SkillSource> {\n  const host = getHost()\n  let root: string\n  let read: Awaited<ReturnType<typeof readSkillDirectory>>\n  try {\n    root = await host.realPath(path)\n    if (!(await host.stat(root)).isDirectory) throw new Error('not a directory')\n    read = await readSkillDirectory(root, MAX_SKILL_PAYLOAD_BYTES)\n  } catch (error) {\n    throw new UsageError('INVALID_SKILL_SOURCE', `${path}: ${error instanceof Error ? error.message : String(error)}`)\n  }\n  const name = host.path.basename(root)\n  const invalid = lintSkillPackage(name, read.files).findings.find((finding) => finding.level === 'error')\n  if (invalid) throw new UsageError('INVALID_SKILL_PACKAGE', invalid.note)\n  return {\n    summary: { kind: 'dir', path: root },\n    params: { package: { package: name, version: '', files: packageFiles(read.files) } },\n    extra: read.ignored.length ? { ignored_files: read.ignored } : {},\n  }\n}\n\nfunction packageFiles(files: Map<string, SkillPackageFile>): Record<string, { content: string }> {\n  const out: Record<string, { content: string }> = {}\n  for (const path of [...files.keys()].sort()) out[path] = { content: base64(files.get(path)!.bytes) }\n  return out\n}\n\nasync function importCommand(\n  ctx: CommandContext,\n  input: Record<string, unknown>,\n  dependencies: SkillModuleDependencies,\n): Promise<Record<string, unknown>> {\n  const host = getHost()\n  const agentId = agentIdFrom(input)\n  const raw = requiredInputString(input, 'source')\n  let text: string\n  let source: string\n  if (raw === '-') {\n    text = await (dependencies.readStdin ?? (() => host.readStdin()))()\n    source = 'stdin'\n  } else if (/^https?:\\/\\//i.test(raw)) {\n    let url: URL\n    try {\n      url = new URL(raw)\n    } catch {\n      throw new UsageError('INVALID_ARGUMENT', `invalid URL: ${raw}`)\n    }\n    if (url.username || url.password) throw new UsageError('INVALID_ARGUMENT', 'the URL must not contain credentials')\n    try {\n      text = await (dependencies.fetchText ?? fetchText)(url, ctx.signal)\n    } catch (error) {\n      if (error instanceof ToolError) throw error\n      ctx.signal.throwIfAborted()\n      throw new ToolError('SKILL_IMPORT_FETCH_FAILED', `failed to fetch ${url.origin}${url.pathname}: ${error instanceof Error ? error.message : String(error)}`, EXIT_UNAVAILABLE, true)\n    }\n    source = `${url.origin}${url.pathname}`\n  } else {\n    const path = host.path.isAbsolute(raw) ? host.path.resolve(raw) : host.path.resolve(ctx.cwd, raw)\n    try {\n      text = new TextDecoder('utf-8', { fatal: true }).decode(await host.readFile(path))\n    } catch (error) {\n      throw new UsageError('FILE_ACCESS_FAILED', `failed to read ${raw} as UTF-8 text: ${error instanceof Error ? error.message : String(error)}`)\n    }\n    source = host.path.basename(path)\n  }\n  if (!text.trim()) throw new UsageError('INVALID_ARGUMENT', 'the text to import is empty')\n  if (new TextEncoder().encode(text).length > MAX_IMPORT_TEXT_BYTES) {\n    throw new UsageError('INVALID_ARGUMENT', `the text to import is larger than ${MAX_IMPORT_TEXT_BYTES} bytes`)\n  }\n  const name = inputString(input, 'name')\n  const scope = inputString(input, 'scope')\n  const runtimeId = inputString(input, 'runtime_id')\n  const started = expectObject(\n    await callService<unknown>(ctx, agentId, 'skills.import', {\n      text,\n      ...(name ? { name } : {}),\n      ...(scope ? { scope } : {}),\n      source,\n      ...(runtimeId ? { runtime_id: runtimeId } : {}),\n    }),\n    'skills.import',\n  )\n  return {\n    agent_id: agentId,\n    source,\n    ...started,\n    installed: false,\n    note:\n      'The Agent writes a draft in that work session; nothing is installed. When it reports, the draft is listed by the drafts command; read it, then install it.',\n    drafts_command: `buckyos skill drafts --agent ${agentId}`,\n    install_command: `buckyos skill install --draft ${name ?? '<slug>'} --agent ${agentId}`,\n  }\n}\n\nasync function fetchText(url: URL, signal: AbortSignal): Promise<string> {\n  const response = await fetch(url, { method: 'GET', redirect: 'follow', signal })\n  if (!response.ok) {\n    await response.body?.cancel()\n    throw new ToolError('SKILL_IMPORT_FETCH_FAILED', `the URL returned HTTP ${response.status}`, EXIT_UNAVAILABLE, response.status >= 500)\n  }\n  return await response.text()\n}\n\nasync function confirm(ctx: CommandContext, verb: string, question: string): Promise<void> {\n  if (ctx.confirmed) return\n  if (ctx.config.nonInteractive || !ctx.io.inputIsTerminal) {\n    throw new ToolError('CONFIRMATION_REQUIRED', `${verb} requires --yes in non-interactive execution`, EXIT_PERMISSION)\n  }\n  const answer = (await ctx.io.prompt(`${question} [y/N] `))?.trim().toLowerCase()\n  if (answer !== 'y' && answer !== 'yes') {\n    throw new ToolError('CONFIRMATION_DECLINED', `${verb} was declined`, EXIT_PERMISSION)\n  }\n}\n\nasync function kindOf(ctx: CommandContext, agentId: string, name: string, input: Record<string, unknown>): Promise<string> {\n  const given = inputString(input, 'kind')\n  if (given) return given\n  const kinds = (await listSkills(ctx, agentId)).filter((skill) => skill.name === name).map((skill) => String(skill.kind))\n  if (kinds.length === 0) throw new ToolError('RESOURCE_NOT_FOUND', `Agent ${agentId} has no skill named ${name}`)\n  if (kinds.length > 1) throw new UsageError('AMBIGUOUS_SKILL', `${name} is a ${kinds.join(' and a ')} skill; use --kind`)\n  return kinds[0]\n}\n\nasync function listSkills(ctx: CommandContext, agentId: string, kind?: string): Promise<Record<string, unknown>[]> {\n  const skills = await callService<unknown>(ctx, agentId, 'skills.list', kind ? { kind } : {})\n  if (!Array.isArray(skills)) invalidResponse('skills.list')\n  return (skills as unknown[]).map((skill) => expectObject(skill, 'skills.list'))\n}\n\nasync function listDrafts(ctx: CommandContext, agentId: string): Promise<Record<string, unknown>[]> {\n  const drafts = await callService<unknown>(ctx, agentId, 'skills.drafts', {})\n  if (!Array.isArray(drafts)) invalidResponse('skills.drafts')\n  return (drafts as unknown[]).map((draft) => expectObject(draft, 'skills.drafts'))\n}\n\nexport function agentIdFrom(input: Record<string, unknown>): string {\n  const agentId = requiredInputString(input, 'agent_id')\n  if (!AGENT_ID.test(agentId)) {\n    throw new UsageError('INVALID_AGENT_ID', `invalid Agent ID: ${agentId}`)\n  }\n  return agentId\n}\n\nfunction expectObject(value: unknown, method: string): Record<string, unknown> {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) invalidResponse(method)\n  return value as Record<string, unknown>\n}\n\nfunction invalidResponse(method: string): never {\n  throw new ToolError(\n    'INVALID_SERVICE_RESPONSE',\n    `Agent returned an invalid response for ${method}`,\n    EXIT_INTERNAL,\n  )\n}\n\nfunction base64(bytes: Uint8Array): string {\n  let binary = ''\n  for (let index = 0; index < bytes.length; index += 0x8000) {\n    binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000))\n  }\n  return btoa(binary)\n}\n","import type { CommandDefinition, CommandModule, JsonSchema, OptionDefinition } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { EXIT_OPERATION, EXIT_PERMISSION, EXIT_UNAVAILABLE, normalizeError, ToolError, UsageError } from '../core/errors.ts'\nimport { callService, expectObject, inputString, requiredInputString } from '../core/service.ts'\nimport { agentIdFrom } from './skill.ts'\n\nconst CONTROL_PANEL = 'control-panel'\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst ID: JsonSchema = { type: 'string', minLength: 1 }\nconst DEVICE_PREFIX = 'exec-'\nconst AGENT_RUNTIME_ACTIONS = ['list', 'enable', 'disable', 'default']\n\nconst AGENT_OPTION: OptionDefinition = {\n  name: 'agent',\n  property: 'agent_id',\n  description: 'Agent ID as `agent list` prints it',\n  type: 'string',\n  required: true,\n}\n\ntype Row = Record<string, string>\ntype Json = Record<string, unknown>\n\nfunction objects(value: unknown): Json[] {\n  return Array.isArray(value) ? value.filter((item) => item && typeof item === 'object' && !Array.isArray(item)) as Json[] : []\n}\n\nfunction strings(value: unknown): string[] {\n  return Array.isArray(value) ? value.map(String) : []\n}\n\nfunction time(value: unknown): string {\n  return typeof value === 'number' && value > 0 ? new Date(value).toISOString() : ''\n}\n\nfunction allows(roots: unknown, mode: string, computer: unknown, baseline: unknown): string {\n  return [\n    strings(roots).join(',') || '-',\n    mode,\n    ...(computer && computer !== 'none' ? [`computer=${computer}`] : []),\n    ...(baseline ? [`baseline=${baseline}`] : []),\n  ].join(' ')\n}\n\n/** `runtime list` as a table: one row per runtime of the caller's directory (`agent.runtime_catalog`). */\nexport function catalogRows(runtimes: Json[]): Row[] {\n  return runtimes.map((runtime) => ({\n    id: String(runtime.runtime_id ?? ''),\n    kind: runtime.kind === 'executor' ? 'device' : String(runtime.kind ?? ''),\n    name: String(runtime.name ?? ''),\n    state: runtime.closed === true ? 'closed' : 'open',\n    online: runtime.online === true ? 'yes' : runtime.online === false ? 'no' : '',\n    expires: time(runtime.expires_at_ms),\n    allows: allows(runtime.workdir_roots, runtime.read_only === true ? 'ro' : 'rw', runtime.computer, runtime.baseline),\n    agents: objects(runtime.assigned_to)\n      .map((agent) => `${agent.enabled === true ? '*' : ''}${agent.agent_id}${agent.default === true ? ' (default)' : ''}`)\n      .join(', '),\n  }))\n}\n\n/** `agent runtime list` from the Agent's own records: the current ones (private first), then the retired ones. */\nexport function splitAgentRuntimes(records: Json[]): { current: Json[]; history: Json[] } {\n  const current = records.filter((record) => record.lifecycle !== 'retired')\n  return {\n    current: [...current.filter((record) => record.runtime_id === 'private'), ...current.filter((record) => record.runtime_id !== 'private')],\n    history: records.filter((record) => record.lifecycle === 'retired'),\n  }\n}\n\nexport function agentRuntimeRows(records: Json[], settings: Json): Row[] {\n  const { current, history } = splitAgentRuntimes(records)\n  return [...current, ...history].map((record) => {\n    const caps = (record.caps ?? {}) as Json\n    const grant = (record.grant ?? {}) as Json\n    const usage = (record.usage ?? {}) as Json\n    const connector = (record.connector ?? {}) as Json\n    const retired = record.lifecycle === 'retired'\n    return {\n      id: String(record.runtime_id ?? ''),\n      name: String(record.name ?? ''),\n      type: String(connector.type ?? ''),\n      state: retired ? 'retired' : record.enabled === false ? 'off' : String(record.availability ?? 'on'),\n      default: !retired && (record.default === true || record.runtime_id === settings.default_runtime_id) ? '*' : '',\n      os: String(caps.os ?? ''),\n      allows: allows(grant.roots, strings(grant.ops).join(',') || '-', grant.computer, caps.baseline),\n      expires: time(grant.expires_at_ms),\n      sessions: String(usage.sessions_total ?? 0),\n      workspaces: String(usage.workspaces ?? 0),\n      last_used: time(usage.last_used_at_ms),\n    }\n  })\n}\n\n/** `agent runtime list` when the Agent's service cannot be reached: what the control panel has assigned to it. */\nexport function directoryRows(runtimes: Json[], directory: Json): Row[] {\n  return runtimes.map((runtime) => ({\n    id: String(runtime.runtime_id ?? ''),\n    name: String(runtime.name ?? ''),\n    type: runtime.kind === 'executor' ? 'device' : String(runtime.kind ?? ''),\n    state: runtime.withdrawn === true ? 'withdrawn' : runtime.enabled === true ? (runtime.closed === true ? 'closed' : 'on') : 'off',\n    default: runtime.runtime_id === directory.default_runtime_id ? '*' : '',\n    os: String(runtime.os ?? ''),\n    allows: allows(runtime.workdir_roots, runtime.read_only === true ? 'ro' : 'rw', runtime.computer, runtime.baseline),\n    expires: time(runtime.expires_at_ms),\n  }))\n}\n\n/** What switching a runtime off or removing it touches (`runtimes.impact`), as the lines shown before the question. */\nexport function impactText(agentId: string, impact: Json): string {\n  const sessions = objects(impact.active_sessions)\n  const todos = objects(impact.pending_todos)\n  const workspaces = objects(impact.workspaces)\n  const lines = [\n    `Runtime ${impact.runtime_id} of ${agentId}: ${sessions.length} session(s) in progress, ${todos.length} Todo(s) waiting, ${workspaces.length} workspace(s)` +\n    (impact.owner_default === true ? '; it is the default runtime' : ''),\n  ]\n  for (const session of sessions) {\n    lines.push(`  session ${session.session_id} [${session.kind}${session.class ? `/${session.class}` : ''}, ${session.run_state}] ${session.title ?? ''}`)\n  }\n  for (const todo of todos) lines.push(`  todo ${todo.session_id}/${todo.todo_id} [${todo.status}] ${todo.title ?? ''}`)\n  for (const workspace of workspaces) {\n    lines.push(`  workspace ${workspace.workspace_id} ${workspace.name ?? ''} ${workspace.directory ?? ''} [${workspace.lifecycle ?? ''}]`)\n  }\n  if (sessions.length > 0) lines.push('  It cannot be switched off or taken away while these sessions run.')\n  return `${lines.join('\\n')}\\n`\n}\n\n/** `exec-<executor_id>` for a device named by its runtime id or its executor id; a node runtime is refused. */\nexport function deviceOf(given: string, runtimes: Json[]): { runtime_id: string; executor_id: string; runtime?: Json } {\n  const runtime = runtimes.find((item) => item.runtime_id === given || (item.executor_id && item.executor_id === given))\n  if (runtime ? runtime.kind !== 'executor' : given === 'host' || given === 'private' || given.startsWith('node-')) {\n    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`)\n  }\n  const executorId = runtime?.executor_id\n    ? String(runtime.executor_id)\n    : given.startsWith(DEVICE_PREFIX)\n    ? given.slice(DEVICE_PREFIX.length)\n    : given\n  return { runtime_id: runtime ? String(runtime.runtime_id) : `${DEVICE_PREFIX}${executorId}`, executor_id: executorId, ...(runtime ? { runtime } : {}) }\n}\n\nfunction reasonText(error: unknown): string {\n  const message = error instanceof Error ? error.message : String(error)\n  const brace = message.indexOf('{')\n  if (brace < 0) return message\n  try {\n    const parsed = JSON.parse(message.slice(brace)) as { message?: unknown }\n    return typeof parsed.message === 'string' ? parsed.message : message\n  } catch {\n    return message\n  }\n}\n\nfunction serviceReason(error: unknown, prefix: string): string | undefined {\n  const message = reasonText(error)\n  const at = message.indexOf(`${prefix}:`)\n  return at < 0 ? undefined : message.slice(at + prefix.length + 1).trim()\n}\n\nfunction unreachable(error: unknown): boolean {\n  const normalized = normalizeError(error)\n  return normalized.code === 'SERVICE_UNAVAILABLE' || normalized.code === 'TIMEOUT' ||\n    normalized.message.toLowerCase().includes('rpc call error: 404')\n}\n\nfunction message(error: unknown): string {\n  return normalizeError(error).message\n}\n\nasync function confirm(ctx: CommandContext, verb: string, shown: string, question: string, details: Json): Promise<void> {\n  if (ctx.confirmed) return\n  if (ctx.config.nonInteractive || !ctx.io.inputIsTerminal) {\n    throw new ToolError('CONFIRMATION_REQUIRED', `${verb} requires --yes in non-interactive execution`, EXIT_PERMISSION, false, details)\n  }\n  await ctx.io.stderr(shown)\n  const answer = (await ctx.io.prompt(`${question} [y/N] `))?.trim().toLowerCase()\n  if (answer !== 'y' && answer !== 'yes') throw new ToolError('CONFIRMATION_DECLINED', `${verb} was declined`, EXIT_PERMISSION)\n}\n\nfunction inProgress(verb: string, shown: string, details: Json): ToolError {\n  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)\n}\n\nasync function controlPanel(ctx: CommandContext, method: string, params: Json): Promise<Json> {\n  try {\n    return expectObject(await callService(ctx, CONTROL_PANEL, method, params), method)\n  } catch (error) {\n    if (message(error).includes('agent_not_found')) {\n      throw new ToolError('RESOURCE_NOT_FOUND', `Agent not found or not yours: ${params.agent_id}`)\n    }\n    for (const [prefix, code] of [['runtime_not_offered', 'RUNTIME_NOT_OFFERED'], ['invalid_runtimes', 'INVALID_RUNTIMES']]) {\n      const reason = serviceReason(error, prefix)\n      if (reason !== undefined) throw new ToolError(code, reason, EXIT_OPERATION)\n    }\n    throw error\n  }\n}\n\nasync function catalog(ctx: CommandContext): Promise<{ response: Json; runtimes: Json[] }> {\n  const response = await controlPanel(ctx, 'agent.runtime_catalog', {})\n  return { response, runtimes: objects(response.runtimes) }\n}\n\nasync function impactOf(ctx: CommandContext, agentId: string, runtimeId: string): Promise<Json> {\n  return expectObject(await callService(ctx, agentId, 'runtimes.impact', { runtime_id: runtimeId }), 'runtimes.impact')\n}\n\nfunction command(\n  definition: Pick<CommandDefinition, 'verb' | 'summary' | 'handler'> & Partial<CommandDefinition> & {\n    level: 'read' | 'write' | 'destructive'\n    properties: Record<string, JsonSchema>\n    required?: string[]\n  },\n): CommandDefinition {\n  const { level, properties, required, ...rest } = definition\n  return {\n    inputSchema: { type: 'object', properties, required: required ?? [], additionalProperties: false },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level },\n    asyncMode: 'sync',\n    requiresSession: true,\n    ...rest,\n  }\n}\n\n/** The owner's runtime directory: what runtimes there are, and which Agent each is assigned to. A runtime is a sandbox\n * with its own configuration; assigning it only records that an Agent may use it. */\nexport function createRuntimeModule(): CommandModule {\n  return {\n    name: 'runtime',\n    summary: 'List the runtimes of your directory, assign them to Agents, and revoke devices',\n    commands: [\n      command({\n        verb: 'list',\n        summary: 'List the runtimes of your directory and the Agents each is assigned to',\n        description:\n          '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.',\n        level: 'read',\n        properties: {},\n        examples: ['buckyos runtime list', 'buckyos --output table runtime list'],\n        handler: async (ctx) => {\n          const { response, runtimes } = await catalog(ctx)\n          return { ...response, runtimes: ctx.output.format === 'table' ? catalogRows(runtimes) : runtimes }\n        },\n      }),\n      command({\n        verb: 'assign',\n        summary: 'Assign a runtime of your directory to an Agent',\n        description:\n          '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.',\n        positionals: [{ name: 'runtime_id', description: 'Runtime id as `runtime list` prints it' }],\n        options: [AGENT_OPTION, { name: 'disabled', description: 'Assign it switched off', type: 'boolean' }],\n        level: 'write',\n        properties: { runtime_id: ID, agent_id: ID, disabled: { type: 'boolean' } },\n        required: ['runtime_id', 'agent_id'],\n        examples: [\n          'buckyos runtime assign host --agent jarvis.example.zone',\n          'buckyos runtime assign exec-laptop --agent jarvis.example.zone --disabled',\n        ],\n        handler: async (ctx, input) => await assign(ctx, input),\n      }),\n      command({\n        verb: 'unassign',\n        summary: 'Take a runtime away from an Agent',\n        description:\n          '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.',\n        positionals: [{ name: 'runtime_id', description: 'Runtime id' }],\n        options: [AGENT_OPTION],\n        level: 'destructive',\n        properties: { runtime_id: ID, agent_id: ID },\n        required: ['runtime_id', 'agent_id'],\n        examples: ['buckyos runtime unassign host --agent jarvis.example.zone'],\n        handler: async (ctx, input) => await unassign(ctx, input),\n      }),\n      command({\n        verb: 'revoke',\n        summary: 'Revoke a device: it stops serving and is taken away from its Agents',\n        description:\n          '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.',\n        positionals: [{ name: 'runtime_id', description: 'Device runtime id (exec-<executor_id>) or executor id' }],\n        level: 'destructive',\n        properties: { runtime_id: ID },\n        required: ['runtime_id'],\n        examples: ['buckyos runtime revoke exec-laptop', 'buckyos --yes runtime revoke laptop'],\n        handler: async (ctx, input) => await revoke(ctx, input),\n      }),\n    ],\n  }\n}\n\n/** `agent runtime <list|enable|disable|default> [runtime_id] --agent <agent_id>`: the runtimes one Agent uses. */\nexport function agentRuntimeCommand(): CommandDefinition {\n  return {\n    verb: 'runtime',\n    summary: 'The runtimes of one Agent: list them, switch one on or off, choose the default',\n    description:\n      '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`.',\n    positionals: [\n      { name: 'action', description: AGENT_RUNTIME_ACTIONS.join(' | ') },\n      { name: 'runtime_id', description: 'Runtime id (enable, disable, default); `private` is the own runtime of the Agent', required: false },\n    ],\n    options: [AGENT_OPTION],\n    inputSchema: {\n      type: 'object',\n      properties: { action: { type: 'string', enum: AGENT_RUNTIME_ACTIONS }, runtime_id: ID, agent_id: ID },\n      required: ['action', 'agent_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'operation', operationIdField: 'action', possibleLevels: ['read', 'write'] },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: [\n      'buckyos agent runtime list --agent jarvis.example.zone',\n      'buckyos agent runtime enable host --agent jarvis.example.zone',\n      'buckyos agent runtime disable exec-laptop --agent jarvis.example.zone',\n      'buckyos agent runtime default private --agent jarvis.example.zone',\n    ],\n    handler: async (ctx, input) => {\n      const agentId = agentIdFrom(input)\n      const action = requiredInputString(input, 'action')\n      const runtimeId = inputString(input, 'runtime_id')\n      if (action === 'list') {\n        if (runtimeId) throw new UsageError('ARGUMENT_CONFLICT', 'agent runtime list takes no runtime id')\n        return await agentRuntimeList(ctx, agentId)\n      }\n      if (!runtimeId) throw new UsageError('MISSING_ARGUMENT', `agent runtime ${action} needs a runtime id`)\n      if (action === 'default') {\n        const settings = await settingsSet(ctx, agentId, { runtime_id: runtimeId, default: true })\n        return { agent_id: agentId, runtime_id: runtimeId, default: true, settings }\n      }\n      if (action === 'enable') {\n        const settings = await settingsSet(ctx, agentId, { runtime_id: runtimeId, enabled: true })\n        return { agent_id: agentId, runtime_id: runtimeId, enabled: true, settings }\n      }\n      const settings = await settingsSet(ctx, agentId, { runtime_id: runtimeId, enabled: false })\n      return { agent_id: agentId, runtime_id: runtimeId, enabled: false, settings }\n    },\n  }\n}\n\nasync function settingsSet(ctx: CommandContext, agentId: string, params: Json): Promise<Json> {\n  try {\n    return expectObject(await callService(ctx, agentId, 'runtimes.settings_set', params), 'runtimes.settings_set')\n  } catch (error) {\n    throw runtimeError(error, agentId, String(params.runtime_id)) ?? error\n  }\n}\n\nfunction runtimeError(error: unknown, agentId: string, runtimeId: string): ToolError | undefined {\n  const busy = serviceReason(error, 'sessions_in_progress')\n  if (busy !== undefined) {\n    return new ToolError('SESSIONS_IN_PROGRESS', `${busy} (buckyos agent runtime list --agent ${agentId})`, EXIT_OPERATION)\n  }\n  const inUse = serviceReason(error, 'runtime_in_use')\n  if (inUse !== undefined) {\n    const user = /in use by Agent `([^`]+)`/.exec(inUse)?.[1]\n    return new ToolError(\n      'RUNTIME_IN_USE',\n      `${inUse}${user ? ` (buckyos agent runtime disable ${runtimeId} --agent ${user})` : ''}`,\n      EXIT_OPERATION,\n      false,\n      user ? { in_use_by: user, disable_command: `buckyos agent runtime disable ${runtimeId} --agent ${user}` } : {},\n    )\n  }\n  return undefined\n}\n\nasync function agentRuntimeList(ctx: CommandContext, agentId: string): Promise<Json> {\n  let records: Json[]\n  let settings: Json\n  try {\n    const listed = await callService<unknown>(ctx, agentId, 'runtimes.list', {})\n    if (!Array.isArray(listed)) throw new ToolError('INVALID_SERVICE_RESPONSE', 'runtimes.list must be an array')\n    records = objects(listed)\n    settings = expectObject(await callService(ctx, agentId, 'runtimes.settings', {}), 'runtimes.settings')\n  } catch (error) {\n    if (!unreachable(error)) throw error\n    const directory = await controlPanel(ctx, 'agent.runtime_directory', { agent_id: agentId })\n    const assigned = objects(directory.runtimes).filter((runtime) => runtime.assigned === true)\n    const { runtimes: _all, ...rest } = directory\n    return {\n      agent_id: agentId,\n      source: CONTROL_PANEL,\n      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`,\n      runtimes: ctx.output.format === 'table' ? directoryRows(assigned, directory) : assigned,\n      ...rest,\n    }\n  }\n  const { current, history } = splitAgentRuntimes(records)\n  return {\n    agent_id: agentId,\n    source: 'agent',\n    ...(ctx.output.format === 'table' ? { runtimes: agentRuntimeRows(records, settings) } : { runtimes: current, history }),\n    default_runtime_id: settings.default_runtime_id ?? null,\n    configured_default_runtime_id: settings.configured_default_runtime_id ?? null,\n    settings: settings.runtimes ?? {},\n  }\n}\n\nasync function assign(ctx: CommandContext, input: Json): Promise<Json> {\n  const agentId = agentIdFrom(input)\n  const runtimeId = requiredInputString(input, 'runtime_id')\n  const enabled = input.disabled !== true\n  try {\n    await controlPanel(ctx, 'agent.update', { agent_id: agentId, runtimes: { [runtimeId]: { enabled } } })\n  } catch (error) {\n    const inUse = serviceReason(error, 'runtime_in_use')\n    if (inUse === undefined) throw error\n    let user = /in use by Agent `([^`]+)`/.exec(inUse)?.[1]\n    let theirs = runtimeId\n    try {\n      const device = deviceOf(runtimeId, (await catalog(ctx)).runtimes).runtime\n      const using = objects(device?.assigned_to).find((agent) => agent.enabled === true && agent.agent_id !== agentId)\n      if (using) {\n        user = String(using.agent_id)\n        theirs = String(using.runtime_id ?? runtimeId)\n      }\n    } catch {\n      // the refusal itself is what matters\n    }\n    const disable = user ? `buckyos agent runtime disable ${theirs} --agent ${user}` : undefined\n    throw new ToolError(\n      'RUNTIME_IN_USE',\n      `${inUse}${disable ? `: ${disable}` : ''}`,\n      EXIT_OPERATION,\n      false,\n      user ? { in_use_by: user, disable_command: disable } : {},\n    )\n  }\n  return { agent_id: agentId, runtime_id: runtimeId, assigned: true, enabled }\n}\n\nasync function unassign(ctx: CommandContext, input: Json): Promise<Json> {\n  const agentId = agentIdFrom(input)\n  const runtimeId = requiredInputString(input, 'runtime_id')\n  let impact: Json\n  try {\n    impact = await impactOf(ctx, agentId, runtimeId)\n  } catch (error) {\n    if (!unreachable(error)) throw error\n    const why = `the service of ${agentId} cannot be reached (${message(error)}): what it has in progress on ${runtimeId} is unknown`\n    if (!ctx.confirmed) {\n      throw new ToolError(\n        'AGENT_SERVICE_UNAVAILABLE',\n        `${why}. Nothing was changed; --yes removes the assignment through the control panel anyway`,\n        EXIT_UNAVAILABLE,\n        true,\n      )\n    }\n    await controlPanel(ctx, 'agent.update', { agent_id: agentId, runtimes: { [runtimeId]: null } })\n    return { agent_id: agentId, runtime_id: runtimeId, removed: true, via: CONTROL_PANEL, impact: null, warning: why }\n  }\n  if (impact.blocking === true) throw inProgress('runtime unassign', impactText(agentId, impact), { impact })\n  let settings: Json\n  try {\n    settings = expectObject(await callService(ctx, agentId, 'runtimes.remove', { runtime_id: runtimeId }), 'runtimes.remove')\n  } catch (error) {\n    throw runtimeError(error, agentId, runtimeId) ?? error\n  }\n  return { agent_id: agentId, runtime_id: runtimeId, removed: true, via: 'agent', impact, settings }\n}\n\nasync function revoke(ctx: CommandContext, input: Json): Promise<Json> {\n  const given = requiredInputString(input, 'runtime_id')\n  const device = deviceOf(given, (await catalog(ctx)).runtimes)\n  const assigned = objects(device.runtime?.assigned_to)\n  const lines = [\n    device.runtime\n      ? `Device ${device.runtime_id} (${device.runtime.name ?? device.executor_id}) is assigned to ${assigned.length} Agent(s)`\n      : `Device ${device.runtime_id} is not in your runtime directory: nothing is known about its Agents`,\n    ...assigned.map((agent) => `  ${agent.enabled === true ? '*' : ' '} ${agent.agent_id}${agent.default === true ? ' (default)' : ''}`),\n  ]\n  const impacts: Json[] = []\n  for (const agent of assigned.filter((item) => item.enabled === true)) {\n    const agentId = String(agent.agent_id)\n    try {\n      const impact = await impactOf(ctx, agentId, String(agent.runtime_id ?? device.runtime_id))\n      impacts.push({ agent_id: agentId, impact })\n      lines.push(impactText(agentId, impact).trimEnd())\n    } catch (error) {\n      impacts.push({ agent_id: agentId, impact: null, error: message(error) })\n      lines.push(`  what ${agentId} has in progress on it is unknown: ${message(error)}`)\n    }\n  }\n  if (impacts.some((item) => (item.impact as Json | null)?.blocking === true)) {\n    throw inProgress('runtime revoke', `${lines.join('\\n')}\\n`, { assigned_to: assigned, impacts })\n  }\n  await confirm(ctx, 'runtime revoke', `${lines.join('\\n')}\\n`, `Revoke ${device.runtime_id} and take it away from its Agents?`, {\n    assigned_to: assigned,\n    impacts,\n  })\n  const revoked = await controlPanel(ctx, 'executor.device.revoke', { executor_id: device.executor_id })\n  return { runtime_id: device.runtime_id, executor_id: device.executor_id, revoked: true, assigned_to: assigned, impacts, ...revoked }\n}\n","import type { CommandModule, JsonSchema, PositionalDefinition } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { EXIT_INTERNAL, ToolError, UsageError } from '../core/errors.ts'\nimport { callService, expectObject, requiredInputString } from '../core/service.ts'\nimport { agentRuntimeCommand } from './runtime.ts'\n\nconst CONTROL_PANEL = 'control-panel'\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst AGENT_POSITIONAL: PositionalDefinition = {\n  name: 'agent_id',\n  description: 'Agent ID as `agent list` prints it (raw host name, e.g. jarvis.example.zone)',\n}\nconst AGENT_INPUT: JsonSchema = {\n  type: 'object',\n  properties: { agent_id: { type: 'string', minLength: 1 } },\n  required: ['agent_id'],\n  additionalProperties: false,\n}\nconst PROFILE_FIELDS = ['display_name', 'bio']\n\n// Control Panel answers for Agents the caller owns; admins (and the device identity) see all.\nexport function createAgentModule(): CommandModule {\n  return {\n    name: 'agent',\n    summary: 'List Agents, read or change their profiles, and manage the runtimes each one uses',\n    commands: [\n      {\n        verb: 'list',\n        summary: 'List the Agents visible to the caller',\n        description: 'Owners see their own Agents; admins see every Agent in the Zone.',\n        inputSchema: { type: 'object', properties: {}, additionalProperties: false },\n        outputSchema: {\n          type: 'object',\n          properties: { agents: { type: 'array', items: OBJECT_OUTPUT } },\n          required: ['agents'],\n          additionalProperties: false,\n        },\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: ['buckyos agent list'],\n        handler: async (ctx) => {\n          const response = await callAgent(ctx, 'agent.list', {})\n          if (!Array.isArray(response.agents)) {\n            throw new ToolError(\n              'INVALID_SERVICE_RESPONSE',\n              'agent.list agents must be an array',\n              EXIT_INTERNAL,\n            )\n          }\n          return { agents: response.agents }\n        },\n      },\n      {\n        verb: 'get',\n        summary: 'Get one Agent: profile, settings, install state, template, and runtime',\n        positionals: [AGENT_POSITIONAL],\n        inputSchema: AGENT_INPUT,\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: ['buckyos agent get jarvis.example.zone'],\n        handler: async (ctx, input) =>\n          await callAgent(ctx, 'agent.get', { agent_id: requiredInputString(input, 'agent_id') }),\n      },\n      {\n        verb: 'profile-get',\n        summary: 'Get the public profile (display name, bio, avatar) of an Agent',\n        positionals: [AGENT_POSITIONAL],\n        inputSchema: AGENT_INPUT,\n        outputSchema: OBJECT_OUTPUT,\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'read' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: ['buckyos agent profile-get jarvis.example.zone'],\n        handler: async (ctx, input) => {\n          const agentId = requiredInputString(input, 'agent_id')\n          return {\n            agent_id: agentId,\n            ...await callAgent(ctx, 'agent.profile.get', { agent_id: agentId }),\n          }\n        },\n      },\n      {\n        verb: 'profile-set',\n        summary: 'Change the display name or bio of an Agent',\n        description:\n          'Only the given fields change; an empty value clears the field. Returns the profile before and after the change, and Message Center reloads the new name.',\n        positionals: [AGENT_POSITIONAL],\n        options: [\n          {\n            name: 'display-name',\n            description: 'New display name; empty clears it',\n            type: 'string',\n          },\n          { name: 'bio', description: 'New bio; empty clears it', type: 'string' },\n        ],\n        inputSchema: {\n          type: 'object',\n          properties: {\n            agent_id: { type: 'string', minLength: 1 },\n            display_name: { type: 'string' },\n            bio: { type: 'string' },\n          },\n          required: ['agent_id'],\n          additionalProperties: false,\n        },\n        outputSchema: {\n          type: 'object',\n          properties: {\n            agent_id: { type: 'string' },\n            before: OBJECT_OUTPUT,\n            profile: OBJECT_OUTPUT,\n          },\n          required: ['agent_id', 'before', 'profile'],\n          additionalProperties: false,\n        },\n        resultSchemaVersion: 1,\n        access: { mode: 'fixed', level: 'write' },\n        asyncMode: 'sync',\n        requiresSession: true,\n        examples: [\n          \"buckyos agent profile-set jarvis.example.zone --display-name 'Jarvis'\",\n          \"buckyos agent profile-set jarvis.example.zone --bio ''\",\n        ],\n        handler: async (ctx, input) => {\n          const agentId = requiredInputString(input, 'agent_id')\n          const changes = Object.fromEntries(\n            PROFILE_FIELDS.filter((field) => typeof input[field] === 'string')\n              .map((field) => [field, input[field]]),\n          )\n          if (Object.keys(changes).length === 0) {\n            throw new UsageError('INVALID_ARGUMENT', 'give --display-name or --bio')\n          }\n          const before = await callAgent(ctx, 'agent.profile.get', { agent_id: agentId })\n          const after = await callAgent(ctx, 'agent.profile.set', { agent_id: agentId, ...changes })\n          return {\n            agent_id: agentId,\n            before: expectObject(before.profile, 'agent.profile.get profile'),\n            profile: expectObject(after.profile, 'agent.profile.set profile'),\n          }\n        },\n      },\n      agentRuntimeCommand(),\n    ],\n  }\n}\n\nasync function callAgent(\n  ctx: CommandContext,\n  method: string,\n  params: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n  try {\n    return expectObject(await callService(ctx, CONTROL_PANEL, method, params), method)\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error)\n    if (message.includes('agent_not_found')) {\n      throw new ToolError('RESOURCE_NOT_FOUND', `Agent not found or not yours: ${params.agent_id}`)\n    }\n    throw error\n  }\n}\n","import type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport { UsageError } from '../core/errors.ts'\nimport {\n  callService,\n  expectObject,\n  inputString,\n  parseTimestamp,\n  splitServices,\n} from '../core/service.ts'\n\nconst AICC = 'aicc'\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst EMPTY_INPUT: JsonSchema = { type: 'object', properties: {}, additionalProperties: false }\nconst RANGES = ['last1d', 'last7d', 'last30d']\nconst GROUPS = [\n  'provider_instance_name',\n  'provider_model',\n  'request_model',\n  'method',\n  'capability',\n  'caller_app_id',\n  'user_id',\n  'tenant_id',\n]\n\n// Read views of the AICC service (/kapi/aicc); provider and routing changes stay in Control Panel.\nexport function createAiModule(): CommandModule {\n  return {\n    name: 'ai',\n    summary: 'Read AI provider, routing, usage and token quota state of the AICC service',\n    commands: [\n      readCommand({\n        verb: 'providers',\n        summary: 'List configured AI provider instances with auth, health, and model inventory',\n        method: 'provider.list',\n        description:\n          'Credentials are reported only as configured/kind; secrets are never returned.',\n      }),\n      readCommand({\n        verb: 'routing',\n        summary: 'Get the AICC routing overlay and its settings revision',\n        method: 'routing.get',\n        description: 'An empty routing object means the default routing of the model catalog.',\n      }),\n      usageCommand(),\n      quotaCommand(),\n    ],\n  }\n}\n\nfunction quotaCommand(): CommandDefinition {\n  return {\n    verb: 'quota',\n    summary: \"Show the token quota rules that limit the caller's AI calls and what is left\",\n    description:\n      'Admin rules on the caller and the caller\\'s Apps, shared App rules, and the caller\\'s own App limits, each with its current window or total account. A refused call returns quota_exhausted / quota_budget_exceeded with the blocking rules.',\n    options: [\n      { name: 'app', description: 'Only the rules that apply to calls of this App (an AppId or AgentId)', type: 'string' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: { app: { type: 'string', minLength: 1 } },\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos ai quota', 'buckyos ai quota --app aiworkspace'],\n    handler: async (ctx, input) =>\n      expectObject(\n        await callService(ctx, AICC, 'quota.query', inputString(input, 'app') ? { app_id: inputString(input, 'app') } : {}),\n        'quota.query',\n      ),\n  }\n}\n\nfunction readCommand(options: {\n  verb: string\n  summary: string\n  method: string\n  description: string\n}): CommandDefinition {\n  return {\n    verb: options.verb,\n    summary: options.summary,\n    description: options.description,\n    inputSchema: EMPTY_INPUT,\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: [`buckyos ai ${options.verb}`],\n    handler: async (ctx) =>\n      expectObject(await callService(ctx, AICC, options.method, {}), options.method),\n  }\n}\n\nfunction usageCommand(): CommandDefinition {\n  return {\n    verb: 'usage',\n    summary: \"Aggregate the caller's AI usage: requests, tokens, and cost\",\n    description:\n      \"Scoped to the caller's own user (a device identity sees only its own calls, not the Zone total). Without --since the range defaults to last7d; --until defaults to now.\",\n    options: [\n      {\n        name: 'range',\n        description: 'last1d, last7d (default), or last30d',\n        type: 'string',\n        enum: RANGES,\n      },\n      { name: 'since', description: 'RFC 3339 or Unix ms lower bound', type: 'string' },\n      { name: 'until', description: 'RFC 3339 or Unix ms upper bound', type: 'string' },\n      {\n        name: 'group-by',\n        description: `Comma-separated: ${GROUPS.join(', ')}`,\n        type: 'string',\n      },\n      {\n        name: 'bucket',\n        description: 'Time buckets: hour or day',\n        type: 'string',\n        enum: ['hour', 'day'],\n      },\n      { name: 'events', description: 'Also return the individual usage events', type: 'boolean' },\n      { name: 'limit', description: 'Event page size', type: 'integer' },\n      { name: 'cursor', description: 'Opaque event page cursor', type: 'string' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        range: { type: 'string', enum: RANGES },\n        since: { type: 'string', minLength: 1 },\n        until: { type: 'string', minLength: 1 },\n        group_by: { type: 'string', minLength: 1 },\n        bucket: { type: 'string', enum: ['hour', 'day'] },\n        events: { type: 'boolean' },\n        limit: { type: 'integer', minimum: 1 },\n        cursor: { type: 'string', minLength: 1 },\n      },\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: [\n      'buckyos ai usage --range last1d --group-by provider_instance_name,provider_model',\n      'buckyos ai usage --since 2026-10-01T00:00:00Z --bucket day',\n    ],\n    handler: async (ctx, input) => {\n      const groupBy = splitServices(input.group_by)\n      const unknown = groupBy.filter((group) => !GROUPS.includes(group))\n      if (unknown.length > 0) {\n        throw new UsageError(\n          'INVALID_ARGUMENT',\n          `unknown group-by ${unknown.join(', ')}; use ${GROUPS.join(', ')}`,\n        )\n      }\n      return expectObject(\n        await callService(ctx, AICC, 'usage.query', {\n          time_range: timeRange(input),\n          ...(groupBy.length > 0 ? { group_by: groupBy } : {}),\n          ...(input.bucket ? { time_bucket: input.bucket } : {}),\n          output_mode: input.events === true ? 'summary_and_events' : 'summary',\n          ...(input.limit !== undefined ? { limit: input.limit } : {}),\n          ...(inputString(input, 'cursor') ? { cursor: inputString(input, 'cursor') } : {}),\n        }),\n        'usage.query',\n      )\n    },\n  }\n}\n\nfunction timeRange(input: Record<string, unknown>): Record<string, unknown> {\n  const since = parseTimestamp(input.since, 'since')\n  const until = parseTimestamp(input.until, 'until')\n  if (since === undefined) {\n    if (until !== undefined) throw new UsageError('INVALID_ARGUMENT', '--until requires --since')\n    return { kind: inputString(input, 'range') ?? 'last7d' }\n  }\n  if (input.range !== undefined) {\n    throw new UsageError('ARGUMENT_CONFLICT', '--range cannot be combined with --since')\n  }\n  return { kind: 'explicit', start_time_ms: since, end_time_ms: until ?? Date.now() }\n}\n","import type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { EXIT_INTERNAL, ToolError, UsageError } from '../core/errors.ts'\nimport { expectObject, inputString, parseTimestamp, requiredInputString } from '../core/service.ts'\n\n// Share links of the Zone file service (nfs-server `share.*` over NFSP,\n// buckyos notepads/share-content-mgr-tech-design-todo.md §3.6).\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst DAY_MS = 86_400_000\nconst EXPIRES_HELP = '1d, 7d (default), 30d, none, or an RFC 3339 time'\n\nexport function createShareModule(): CommandModule {\n  return {\n    name: 'share',\n    summary: 'Share files and folders as links, and manage what you have shared',\n    commands: [\n      createCommand(),\n      listCommand(),\n      getCommand(),\n      updateCommand(),\n      stopCommand(),\n      statsCommand(),\n    ],\n  }\n}\n\ninterface NfspSession {\n  call(method: string, args: Record<string, unknown>, write?: boolean): Promise<Record<string, unknown>>\n}\n\nasync function openNfsp(ctx: CommandContext): Promise<NfspSession> {\n  const session = ctx.session\n  if (!session) throw new ToolError('AUTH_REQUIRED', 'authenticated session is required', 3)\n  const token = (await session.ensureValid()).token\n  const base = gatewayOrigin(ctx.connection.endpoint)\n  let seq = 0\n  const post = async (method: string, body: Record<string, unknown>) => {\n    const response = await fetch(`${base}/nfs/v1/${method}`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },\n      body: JSON.stringify(body),\n      signal: ctx.signal,\n    })\n    let parsed: { ok?: boolean; result?: unknown; error?: Record<string, unknown> }\n    try {\n      parsed = await response.json()\n    } catch {\n      throw new ToolError('INVALID_SERVICE_RESPONSE', `file service answered HTTP ${response.status}`, EXIT_INTERNAL)\n    }\n    if (parsed.ok !== true) {\n      const error = parsed.error ?? {}\n      const reason = typeof error.reason === 'string' ? error.reason.toUpperCase() : String(error.code ?? 'INTERNAL')\n      throw new ToolError(`SHARE_${reason}`, String(error.message ?? 'share request failed'))\n    }\n    return expectObject(parsed.result, `${method} result`)\n  }\n  const hello = await post('hello', { args: { versions: ['nfsp/0'] } })\n  const sessionId = String(hello.session ?? '')\n  if (!Array.isArray(hello.features) || !hello.features.includes('share')) {\n    throw new ToolError('SHARE_UNSUPPORTED', 'the file service of this Zone does not support sharing')\n  }\n  return {\n    call: (method, args, write = false) =>\n      post(method, { session: sessionId, args: { ...args, source_hint: 'cli' }, ...(write ? { seq: ++seq } : {}) }),\n  }\n}\n\n/** The Zone gateway origin of a service endpoint (`…/kapi/<service>`): where `/nfs/v1` and other routes live. */\nexport function gatewayOrigin(endpoint: string): string {\n  const url = new URL(endpoint)\n  const marker = url.pathname.indexOf('/kapi')\n  url.pathname = marker >= 0 ? url.pathname.slice(0, marker) || '/' : '/'\n  url.search = ''\n  url.hash = ''\n  return url.toString().replace(/\\/$/, '')\n}\n\n/** `--expires` → unix seconds, `null` for no expiry, `undefined` for the server default (7 days). */\nexport function parseExpires(value: unknown): number | null | undefined {\n  if (value === undefined) return undefined\n  const text = String(value).trim().toLowerCase()\n  if (text === 'none' || text === 'never') return null\n  const days = text.match(/^(\\d+)d$/)\n  if (days) return Math.floor((Date.now() + Number(days[1]) * DAY_MS) / 1000)\n  const at = parseTimestamp(value, 'expires')\n  if (at === undefined) return undefined\n  if (at <= Date.now()) throw new UsageError('INVALID_ARGUMENT', 'expires must be in the future')\n  return Math.floor(at / 1000)\n}\n\nfunction sourceLocator(path: string): Record<string, unknown> {\n  if (path.startsWith('cyfs://')) return { uri: path }\n  return { path: path.startsWith('/') ? path : `/${path}` }\n}\n\nfunction summary(share: Record<string, unknown>): Record<string, unknown> {\n  const keep = ['share_id', 'kind', 'title', 'status', 'access', 'expires_at', 'url', 'target_app', 'delivery_state', 'source_path', 'revision', 'created_at', 'stats']\n  return Object.fromEntries(keep.filter((key) => share[key] !== undefined).map((key) => [key, share[key]]))\n}\n\nfunction createCommand(): CommandDefinition {\n  return {\n    verb: 'create',\n    summary: 'Share a file or folder as a link (a snapshot of its current content)',\n    positionals: [{ name: 'path', description: 'File or folder, e.g. /home/alice/report.pdf or cyfs:///home/alice/report.pdf', required: true }],\n    options: [\n      { name: 'expires', description: `Link expiry: ${EXPIRES_HELP}`, type: 'string' },\n      { name: 'password', description: 'Require this password to open the link', type: 'string' },\n      { name: 'title', description: 'Title shown to visitors', type: 'string' },\n      { name: 'no-download', property: 'no_download', description: 'Preview only, no download button', type: 'boolean' },\n      { name: 'wait', description: 'Wait for a large snapshot to finish', type: 'boolean' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        path: { type: 'string', minLength: 1 },\n        expires: { type: 'string', minLength: 1 },\n        password: { type: 'string', minLength: 1 },\n        title: { type: 'string', minLength: 1 },\n        no_download: { type: 'boolean' },\n        wait: { type: 'boolean' },\n      },\n      required: ['path'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'either',\n    requiresSession: true,\n    examples: [\n      'buckyos share create /home/alice/report.pdf',\n      'buckyos share create /home/alice/photos --expires 30d --password s3cret',\n    ],\n    handler: async (ctx, input) => {\n      const nfsp = await openNfsp(ctx)\n      const expires = parseExpires(input.expires)\n      const password = inputString(input, 'password')\n      const policy: Record<string, unknown> = {\n        access: password ? 'password' : 'holder',\n        allow_download: input.no_download !== true,\n        ...(password ? { password } : {}),\n        ...(expires !== undefined ? { expires_at: expires } : {}),\n      }\n      let op = await nfsp.call('share.create', {\n        source: sourceLocator(requiredInputString(input, 'path')),\n        policy,\n        title: inputString(input, 'title'),\n        idempotency_key: ctx.idempotencyKey ?? crypto.randomUUID(),\n      }, true)\n      while (input.wait === true && (op.state === 'running' || op.state === 'preparing')) {\n        await new Promise((resolve) => setTimeout(resolve, 1000))\n        ctx.signal.throwIfAborted()\n        op = await nfsp.call('share.operation', { operation_id: op.operation_id })\n      }\n      if (op.state === 'failed' || op.state === 'canceled') {\n        const error = (op.error ?? {}) as Record<string, unknown>\n        throw new ToolError(`SHARE_${String(error.reason ?? op.state).toUpperCase()}`, String(error.message ?? `share ${op.state}`))\n      }\n      return {\n        operation_id: op.operation_id,\n        state: op.state,\n        share_id: op.share_id ?? null,\n        url: op.url ?? null,\n        source_changed: op.source_changed ?? false,\n        ...(op.share ? { share: summary(op.share as Record<string, unknown>) } : {}),\n      }\n    },\n  }\n}\n\nfunction listCommand(): CommandDefinition {\n  return {\n    verb: 'list',\n    summary: 'List your shares',\n    options: [\n      { name: 'kind', description: 'link or app_delivery', type: 'string', enum: ['link', 'app_delivery'] },\n      { name: 'status', description: 'active, stopped, expired, ...', type: 'string' },\n      { name: 'q', description: 'Search title and path', type: 'string' },\n      { name: 'include-hidden', property: 'include_hidden', description: 'Include hidden shares', type: 'boolean' },\n      { name: 'cursor', description: 'Page cursor', type: 'string' },\n      { name: 'limit', description: 'Page size, at most 200', type: 'integer' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        kind: { type: 'string', enum: ['link', 'app_delivery'] },\n        status: { type: 'string', minLength: 1 },\n        q: { type: 'string', minLength: 1 },\n        include_hidden: { type: 'boolean' },\n        cursor: { type: 'string', minLength: 1 },\n        limit: { type: 'integer', minimum: 1 },\n      },\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos share list --kind link --status active'],\n    handler: async (ctx, input) => {\n      const nfsp = await openNfsp(ctx)\n      const page = await nfsp.call('share.list', {\n        kind: input.kind,\n        status: input.status,\n        q: input.q,\n        include_hidden: input.include_hidden === true,\n        cursor: input.cursor,\n        limit: input.limit,\n      })\n      const items = Array.isArray(page.items) ? page.items as Record<string, unknown>[] : []\n      return { items: items.map(summary), next_cursor: page.next_cursor ?? null }\n    },\n  }\n}\n\nfunction getCommand(): CommandDefinition {\n  return {\n    verb: 'get',\n    summary: 'Show one share: link, policy, snapshot, delivery, statistics and history',\n    positionals: [{ name: 'share_id', description: 'Share ID (sh_…)', required: true }],\n    inputSchema: {\n      type: 'object',\n      properties: { share_id: { type: 'string', minLength: 1 } },\n      required: ['share_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos share get sh_0123456789abcdef'],\n    handler: async (ctx, input) => {\n      const nfsp = await openNfsp(ctx)\n      return await nfsp.call('share.get', { share_id: requiredInputString(input, 'share_id') })\n    },\n  }\n}\n\nfunction updateCommand(): CommandDefinition {\n  return {\n    verb: 'update',\n    summary: 'Change a link\\'s expiry, password, title or download setting',\n    positionals: [{ name: 'share_id', description: 'Share ID (sh_…)', required: true }],\n    options: [\n      { name: 'expires', description: `New expiry: ${EXPIRES_HELP}`, type: 'string' },\n      { name: 'password', description: 'Set or change the password', type: 'string' },\n      { name: 'no-password', property: 'no_password', description: 'Remove the password', type: 'boolean' },\n      { name: 'title', description: 'New title', type: 'string' },\n      { name: 'download', description: 'Allow (true) or forbid (false) downloading', type: 'boolean' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        share_id: { type: 'string', minLength: 1 },\n        expires: { type: 'string', minLength: 1 },\n        password: { type: 'string', minLength: 1 },\n        no_password: { type: 'boolean' },\n        title: { type: 'string', minLength: 1 },\n        download: { type: 'boolean' },\n      },\n      required: ['share_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos share update sh_0123456789abcdef --expires none', 'buckyos share update sh_0123456789abcdef --password n3w'],\n    handler: async (ctx, input) => {\n      if (input.password !== undefined && input.no_password === true) {\n        throw new UsageError('INVALID_ARGUMENT', 'use either --password or --no-password')\n      }\n      const changes: Record<string, unknown> = {}\n      const expires = parseExpires(input.expires)\n      if (expires !== undefined) changes.expires_at = expires\n      if (input.password !== undefined) changes.password = String(input.password)\n      if (input.no_password === true) changes.password = null\n      if (input.title !== undefined) changes.title = String(input.title)\n      if (input.download !== undefined) changes.allow_download = input.download === true\n      if (!Object.keys(changes).length) throw new UsageError('INVALID_ARGUMENT', 'nothing to change')\n      const nfsp = await openNfsp(ctx)\n      const shareId = requiredInputString(input, 'share_id')\n      const current = await nfsp.call('share.get', { share_id: shareId })\n      const result = await nfsp.call('share.update', { share_id: shareId, revision: current.revision, changes }, true)\n      return { revision: result.revision, share: summary(expectObject(result.share, 'share.update share')) }\n    },\n  }\n}\n\nfunction stopCommand(): CommandDefinition {\n  return {\n    verb: 'stop',\n    summary: 'Stop a share: the link stops working and the kept snapshot is released',\n    positionals: [{ name: 'share_id', description: 'Share ID (sh_…)', required: true }],\n    options: [{ name: 'reason', description: 'Recorded in the share history', type: 'string' }],\n    inputSchema: {\n      type: 'object',\n      properties: { share_id: { type: 'string', minLength: 1 }, reason: { type: 'string', minLength: 1 } },\n      required: ['share_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'destructive' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos share stop sh_0123456789abcdef --reason \"sent by mistake\"'],\n    handler: async (ctx, input) => {\n      const nfsp = await openNfsp(ctx)\n      const shareId = requiredInputString(input, 'share_id')\n      const current = await nfsp.call('share.get', { share_id: shareId })\n      return await nfsp.call('share.stop', { share_id: shareId, revision: current.revision, reason: inputString(input, 'reason') }, true)\n    },\n  }\n}\n\nfunction statsCommand(): CommandDefinition {\n  return {\n    verb: 'stats',\n    summary: 'Views, downloads, traffic and visitors of one share or all of yours',\n    options: [\n      { name: 'share-id', property: 'share_id', description: 'One share instead of all', type: 'string' },\n      { name: 'days', description: 'How many days back (default 30)', type: 'integer' },\n      { name: 'granularity', description: 'day or hour', type: 'string', enum: ['day', 'hour'] },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        share_id: { type: 'string', minLength: 1 },\n        days: { type: 'integer', minimum: 1 },\n        granularity: { type: 'string', enum: ['day', 'hour'] },\n      },\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos share stats --days 7', 'buckyos share stats --share-id sh_0123456789abcdef --granularity hour --days 2'],\n    handler: async (ctx, input) => {\n      const nfsp = await openNfsp(ctx)\n      const to = Math.floor(Date.now() / 1000) + 1\n      const days = typeof input.days === 'number' ? input.days : 30\n      return await nfsp.call('share.stats', {\n        share_id: inputString(input, 'share_id'),\n        from: to - days * 86_400,\n        to,\n        granularity: input.granularity ?? 'day',\n      })\n    },\n  }\n}\n","import type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { EXIT_INTERNAL, ToolError, UsageError } from '../core/errors.ts'\nimport { callService, inputString, parseTimestamp, requiredInputString } from '../core/service.ts'\nimport { getHost } from '../runtime/host.ts'\n\n// Application object buckets (BuckyOS doc/arch/应用对象桶 Bucket 设计.md §12.4):\n// kRPC `bucket.*` on nfs-server plus the `/bucket/v1/<bucket_id>/<key>` data plane.\n// A target is `obj://bucket/<scope>/<appid>/<owner>/<name>[/<key>]` or the same without the scheme.\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst SERVICE = 'nfs-server'\nconst MAX_PUT_BYTES = 32 * 1024 * 1024\nconst DAY_MS = 86_400_000\n/** `BucketError::code()` of bucket_store; service errors read `<code>: <message>`. */\nconst BUCKET_ERROR_CODES = [\n  'bucket_not_found', 'no_such_key', 'invalid_key', 'invalid_argument', 'precondition_failed', 'permission_denied',\n  'quota_exceeded', 'object_too_large', 'content_not_available', 'content_evicted', 'origin_unavailable', 'kind_mismatch',\n  'policy_violation', 'origin_required', 'not_held', 'token_invalid', 'conflict', 'store_error', 'db_error', 'internal_error',\n]\n\nexport function createBucketModule(): CommandModule {\n  return {\n    name: 'bucket',\n    summary: 'Read and write application object buckets (key -> object, retained by the Zone)',\n    commands: [lsCommand(), statCommand(), putCommand(), getCommand(), rmCommand(), linkCommand(), s3KeysCommand(), s3KeyCreateCommand(), s3KeyRevokeCommand()],\n  }\n}\n\nexport interface BucketTarget {\n  bucketId: string\n  key: string\n}\n\n/** Splits `obj://bucket/<scope>/<appid>/<owner>/<name>/<key...>` (scheme optional). */\nexport function parseBucketTarget(value: string, keyRequired: boolean): BucketTarget {\n  const path = value.startsWith('obj://bucket/') ? value.slice('obj://bucket/'.length) : value\n  const parts = path.split('/')\n  if (parts.length < 4 || !['user', 'zone'].includes(parts[0]) || parts.slice(0, 4).some((p) => !p)) {\n    throw new UsageError('INVALID_ARGUMENT', `'${value}' is not obj://bucket/<scope>/<appid>/<owner>/<name>[/<key>]`)\n  }\n  const key = parts.slice(4).join('/')\n  if (keyRequired && !key) throw new UsageError('INVALID_ARGUMENT', `'${value}' names no key`)\n  return { bucketId: parts.slice(0, 4).join('/'), key }\n}\n\nasync function call<T = Record<string, unknown>>(ctx: CommandContext, method: string, params: Record<string, unknown>): Promise<T> {\n  try {\n    return await callService<T>(ctx, SERVICE, method, params)\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error)\n    const code = BUCKET_ERROR_CODES.find((c) => message.includes(`${c}: `))\n    if (code) throw new ToolError(`BUCKET_${code.toUpperCase()}`, message)\n    throw error\n  }\n}\n\nfunction gatewayOrigin(endpoint: string): string {\n  const url = new URL(endpoint)\n  const marker = url.pathname.indexOf('/kapi')\n  url.pathname = marker >= 0 ? url.pathname.slice(0, marker) || '/' : '/'\n  url.search = ''\n  url.hash = ''\n  return url.toString().replace(/\\/$/, '')\n}\n\nfunction objectUrl(ctx: CommandContext, target: BucketTarget, query: Record<string, string> = {}): string {\n  const qs = new URLSearchParams(query).toString()\n  const key = target.key.split('/').map(encodeURIComponent).join('/')\n  return `${gatewayOrigin(ctx.connection.endpoint)}/bucket/v1/${target.bucketId}/${key}${qs ? `?${qs}` : ''}`\n}\n\nasync function bearer(ctx: CommandContext): Promise<Record<string, string>> {\n  if (!ctx.session) throw new ToolError('AUTH_REQUIRED', 'authenticated session is required', 3)\n  return { Authorization: `Bearer ${(await ctx.session.ensureValid()).token}` }\n}\n\nasync function failure(response: Response): Promise<never> {\n  let body: Record<string, unknown> = {}\n  try {\n    body = await response.json()\n  } catch {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `bucket data plane answered HTTP ${response.status}`, EXIT_INTERNAL)\n  }\n  throw new ToolError(`BUCKET_${String(body.error ?? response.status).toUpperCase()}`, String(body.message ?? `HTTP ${response.status}`))\n}\n\nconst TARGET = { name: 'target', description: 'obj://bucket/<scope>/<appid>/<owner>/<name>[/<key>]', required: true }\n\nfunction lsCommand(): CommandDefinition {\n  return {\n    verb: 'ls',\n    summary: 'List your buckets, or the keys of one bucket',\n    positionals: [{ ...TARGET, required: false }],\n    options: [\n      { name: 'delimiter', description: 'Fold keys at this delimiter (e.g. /)', type: 'string' },\n      { name: 'start-after', property: 'start_after', description: 'Continue after this key', type: 'string' },\n      { name: 'limit', description: 'Page size, at most 1000', type: 'integer' },\n      { name: 'appid', description: 'Only buckets of this app (no target)', type: 'string' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        target: { type: 'string', minLength: 1 },\n        delimiter: { type: 'string', minLength: 1 },\n        start_after: { type: 'string', minLength: 1 },\n        limit: { type: 'integer', minimum: 1 },\n        appid: { type: 'string', minLength: 1 },\n      },\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos bucket ls', 'buckyos bucket ls obj://bucket/user/photos/alice/library/2026/ --delimiter /'],\n    handler: async (ctx, input) => {\n      const raw = inputString(input, 'target')\n      if (!raw) return { buckets: await call(ctx, 'bucket.list', { appid: inputString(input, 'appid') }) }\n      const target = parseBucketTarget(raw, false)\n      return await call(ctx, 'bucket.list_objects', {\n        bucket_id: target.bucketId,\n        prefix: target.key,\n        delimiter: inputString(input, 'delimiter'),\n        start_after: inputString(input, 'start_after'),\n        limit: input.limit,\n      })\n    },\n  }\n}\n\nfunction statCommand(): CommandDefinition {\n  return {\n    verb: 'stat',\n    summary: 'Show a bucket (usage, quota) or a key (binding and where its content is)',\n    positionals: [TARGET],\n    options: [{ name: 'version', description: 'A specific version of the key', type: 'integer' }],\n    inputSchema: {\n      type: 'object',\n      properties: { target: { type: 'string', minLength: 1 }, version: { type: 'integer', minimum: 1 } },\n      required: ['target'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos bucket stat obj://bucket/user/photos/alice/library', 'buckyos bucket stat obj://bucket/user/photos/alice/library/a.jpg'],\n    handler: async (ctx, input) => {\n      const target = parseBucketTarget(requiredInputString(input, 'target'), false)\n      if (!target.key) {\n        const [bucket, quota] = await Promise.all([\n          call(ctx, 'bucket.stat', { bucket_id: target.bucketId }),\n          call(ctx, 'bucket.get_quota', { bucket_id: target.bucketId }),\n        ])\n        return { bucket, quota }\n      }\n      return await call(ctx, 'bucket.head', { bucket_id: target.bucketId, key: target.key, version: input.version })\n    },\n  }\n}\n\nfunction putCommand(): CommandDefinition {\n  return {\n    verb: 'put',\n    summary: 'Store a local file (up to 32 MiB) under a key; success means the Zone retains it',\n    positionals: [TARGET, { name: 'file', description: 'Local file to upload', required: true }],\n    options: [\n      { name: 'content-type', property: 'content_type', description: 'Content-Type of the object', type: 'string' },\n      { name: 'if-absent', property: 'if_absent', description: 'Fail if the key already exists', type: 'boolean' },\n      { name: 'expires', description: 'Unbind after: 1d, 7d, or an RFC 3339 time (temp/cache/app_data buckets)', type: 'string' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        target: { type: 'string', minLength: 1 },\n        file: { type: 'string', minLength: 1 },\n        content_type: { type: 'string', minLength: 1 },\n        if_absent: { type: 'boolean' },\n        expires: { type: 'string', minLength: 1 },\n      },\n      required: ['target', 'file'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    networkAccess: true,\n    examples: ['buckyos bucket put obj://bucket/user/photos/alice/library/2026/a.jpg ./a.jpg --content-type image/jpeg'],\n    handler: async (ctx, input) => {\n      const target = parseBucketTarget(requiredInputString(input, 'target'), true)\n      const bytes = await getHost().readFile(requiredInputString(input, 'file'))\n      if (bytes.byteLength > MAX_PUT_BYTES) {\n        throw new UsageError('FILE_TOO_LARGE', 'files over 32 MiB go through the SDK upload (ndm.startUpload with bind)')\n      }\n      const headers: Record<string, string> = { ...(await bearer(ctx)) }\n      const contentType = inputString(input, 'content_type')\n      if (contentType) headers['Content-Type'] = contentType\n      if (input.if_absent === true) headers['If-None-Match'] = '*'\n      const expires = inputString(input, 'expires')\n      if (expires) {\n        const days = expires.match(/^(\\d+)d$/)\n        const at = days ? Date.now() + Number(days[1]) * DAY_MS : parseTimestamp(expires, 'expires')\n        if (at !== undefined) headers['x-bucky-expires-at'] = String(at)\n      }\n      const response = await fetch(objectUrl(ctx, target), { method: 'PUT', headers, body: new Blob([bytes as Uint8Array<ArrayBuffer>]), signal: ctx.signal })\n      if (!response.ok) await failure(response)\n      return await response.json()\n    },\n  }\n}\n\nfunction getCommand(): CommandDefinition {\n  return {\n    verb: 'get',\n    summary: 'Download a key to a local file',\n    positionals: [TARGET, { name: 'output', description: 'Local file to write', required: true }],\n    options: [{ name: 'version', description: 'A specific version of the key', type: 'integer' }],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        target: { type: 'string', minLength: 1 },\n        output: { type: 'string', minLength: 1 },\n        version: { type: 'integer', minimum: 1 },\n      },\n      required: ['target', 'output'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    networkAccess: true,\n    examples: ['buckyos bucket get obj://bucket/user/photos/alice/library/2026/a.jpg ./a.jpg'],\n    handler: async (ctx, input) => {\n      const target = parseBucketTarget(requiredInputString(input, 'target'), true)\n      const query: Record<string, string> = input.version !== undefined ? { version: String(input.version) } : {}\n      const response = await fetch(objectUrl(ctx, target, query), { headers: await bearer(ctx), signal: ctx.signal })\n      if (!response.ok) await failure(response)\n      const bytes = new Uint8Array(await response.arrayBuffer())\n      const output = requiredInputString(input, 'output')\n      await getHost().writeFile(output, bytes)\n      return {\n        output,\n        size: bytes.byteLength,\n        obj_id: response.headers.get('x-bucky-obj-id'),\n        version: Number(response.headers.get('x-bucky-version')),\n        content_type: response.headers.get('content-type'),\n      }\n    },\n  }\n}\n\nfunction rmCommand(): CommandDefinition {\n  return {\n    verb: 'rm',\n    summary: 'Unbind a key (the bucket stops retaining its content)',\n    positionals: [TARGET],\n    options: [{ name: 'version', description: 'Remove only this version', type: 'integer' }],\n    inputSchema: {\n      type: 'object',\n      properties: { target: { type: 'string', minLength: 1 }, version: { type: 'integer', minimum: 1 } },\n      required: ['target'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos bucket rm obj://bucket/user/photos/alice/library/2026/a.jpg'],\n    handler: async (ctx, input) => {\n      const target = parseBucketTarget(requiredInputString(input, 'target'), true)\n      return await call(ctx, 'bucket.delete', { bucket_id: target.bucketId, key: target.key, version: input.version })\n    },\n  }\n}\n\nfunction linkCommand(): CommandDefinition {\n  return {\n    verb: 'link',\n    summary: 'Create a revocable read link to one key (up to 7 days, no Zone account needed)',\n    positionals: [TARGET],\n    options: [\n      { name: 'expires', description: '1d (default) to 7d, or an RFC 3339 time', type: 'string' },\n      { name: 'max-uses', property: 'max_uses', description: 'Stop after this many reads', type: 'integer' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: {\n        target: { type: 'string', minLength: 1 },\n        expires: { type: 'string', minLength: 1 },\n        max_uses: { type: 'integer', minimum: 1 },\n      },\n      required: ['target'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos bucket link obj://bucket/user/photos/alice/library/2026/a.jpg --expires 3d'],\n    handler: async (ctx, input) => {\n      const target = parseBucketTarget(requiredInputString(input, 'target'), true)\n      const text = inputString(input, 'expires') ?? '1d'\n      const days = text.match(/^(\\d+)d$/)\n      const expiresAt = days ? Date.now() + Number(days[1]) * DAY_MS : parseTimestamp(text, 'expires')\n      if (expiresAt === undefined) throw new UsageError('INVALID_ARGUMENT', 'expires is required')\n      const issued = await call(ctx, 'bucket.create_access_token', {\n        bucket_id: target.bucketId,\n        key: target.key,\n        actions: ['read'],\n        expires_at: expiresAt,\n        max_uses: input.max_uses,\n      })\n      return { ...issued, url: `${gatewayOrigin(ctx.connection.endpoint)}${String(issued.path)}` }\n    },\n  }\n}\n\nfunction s3KeysCommand(): CommandDefinition {\n  return {\n    verb: 's3-keys',\n    summary: 'List your S3 access keys (secrets are shown only when created)',\n    inputSchema: { type: 'object', properties: {}, additionalProperties: false },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos bucket s3-keys'],\n    handler: async (ctx) => ({ keys: await call(ctx, 'bucket.list_s3_keys', {}) }),\n  }\n}\n\nfunction s3KeyCreateCommand(): CommandDefinition {\n  return {\n    verb: 's3-key-create',\n    summary: 'Issue an S3 access key for one of your apps (endpoint https://<zone>/s3 or https://s3.<zone>)',\n    options: [\n      { name: 'app', description: 'App id whose buckets the key reaches', type: 'string' },\n      { name: 'prefix', description: 'Only keys under this prefix', type: 'string' },\n      { name: 'expires', description: 'Expiry: 30d, or an RFC 3339 time (default: none)', type: 'string' },\n    ],\n    inputSchema: {\n      type: 'object',\n      properties: { app: { type: 'string', minLength: 1 }, prefix: { type: 'string', minLength: 1 }, expires: { type: 'string', minLength: 1 } },\n      required: ['app'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos bucket s3-key-create --app photos.app.bns.did --expires 30d'],\n    handler: async (ctx, input) => {\n      const text = inputString(input, 'expires')\n      const days = text?.match(/^(\\d+)d$/)\n      const expiresAt = !text ? undefined : days ? Date.now() + Number(days[1]) * DAY_MS : parseTimestamp(text, 'expires')\n      const prefix = inputString(input, 'prefix')\n      const key = await call(ctx, 'bucket.create_s3_key', {\n        appid: requiredInputString(input, 'app'),\n        scope: prefix ? { prefix } : undefined,\n        expires_at: expiresAt,\n      })\n      return { ...key, endpoint: `${gatewayOrigin(ctx.connection.endpoint)}/s3`, region: 'us-east-1', path_style: true }\n    },\n  }\n}\n\nfunction s3KeyRevokeCommand(): CommandDefinition {\n  return {\n    verb: 's3-key-revoke',\n    summary: 'Revoke an S3 access key (its presigned URLs stop working too)',\n    positionals: [{ name: 'access_key_id', description: 'Access key id (BK…)', required: true }],\n    inputSchema: {\n      type: 'object',\n      properties: { access_key_id: { type: 'string', minLength: 1 } },\n      required: ['access_key_id'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos bucket s3-key-revoke BKABCDEFGHIJKLMNOPQR'],\n    handler: async (ctx, input) => await call(ctx, 'bucket.revoke_s3_key', { access_key_id: requiredInputString(input, 'access_key_id') }),\n  }\n}\n","import { objectUrl } from 'buckyos/node'\nimport type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { EXIT_INTERNAL, ToolError, UsageError } from '../core/errors.ts'\nimport { getHost } from '../runtime/host.ts'\nimport { callService, expectObject, requiredInputString } from '../core/service.ts'\n\n// System URLs (buckyos doc/key url.md part one): `resolve` normalizes a reference and\n// says where it lives, `read` follows a DID Object Card to its Profile and summary\n// properties. Resolving a url never implies the caller may read it.\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\ninterface ObjectCard extends Record<string, unknown> {\n  service?: Array<Record<string, unknown>>\n}\n\ninterface ObjectProfile extends Record<string, unknown> {\n  properties?: Record<string, unknown>\n  actions?: Record<string, Record<string, unknown>>\n  events?: Record<string, Record<string, unknown>>\n  'x-buckyos:summary_props'?: string[]\n}\n\ntype ParsedUrl = ReturnType<typeof objectUrl.parseObjectUrl>\nconst URL_ARG = { name: 'url', description: 'obj:// cyfs:// file:// https:// url, or //<service>/... /abs/path shorthand', required: true }\n\nexport function createObjModule(): CommandModule {\n  return {\n    name: 'obj',\n    summary: 'Resolve system URLs and read DID Objects (obj://, cyfs://, file://, https://)',\n    commands: [resolveCommand(), readCommand(), aliasCommand(), callCommand()],\n  }\n}\n\nfunction gatewayOrigin(endpoint: string): string {\n  const url = new URL(endpoint)\n  const marker = url.pathname.indexOf('/kapi')\n  url.pathname = marker >= 0 ? url.pathname.slice(0, marker) || '/' : '/'\n  url.search = ''\n  url.hash = ''\n  return url.toString().replace(/\\/$/, '')\n}\n\nfunction parse(raw: string): ParsedUrl {\n  try {\n    return objectUrl.parseObjectUrl(objectUrl.expandInputShorthand(raw))\n  } catch (error) {\n    throw new UsageError('INVALID_ARGUMENT', error instanceof Error ? error.message : String(error))\n  }\n}\n\n/** The HTTP endpoint of a DID Object, when it has one: Provider routes for obj:// (and cyfs:///, its DFS object), https as is. */\nfunction endpointOf(ctx: CommandContext, url: ParsedUrl): string | null {\n  // Without a session the connection is a placeholder: give the gateway-relative path.\n  const origin = /^https?:\\/\\//.test(ctx.connection.endpoint) ? gatewayOrigin(ctx.connection.endpoint) : ''\n\n  return objectUrl.objectEndpoint(url, origin, ctx.connection.zone)\n}\n\nfunction describe(ctx: CommandContext, url: ParsedUrl): Record<string, unknown> {\n  const out: Record<string, unknown> = {\n    canonical: objectUrl.formatObjectUrl(url),\n    kind: url.kind === 'obj' ? `obj_${url.host!.kind}` : url.kind,\n    rbac_resource_key: objectUrl.rbacResourceKey(url, ctx.connection.zone),\n    endpoint: endpointOf(ctx, url),\n  }\n  if (url.kind === 'obj') {\n    out.host = url.host!.name\n    out.event_pattern = objectUrl.objectEventPattern(url)\n  }\n  if (url.kind === 'file') out.device = url.deviceId ?? '(empty host: the source runtime, else the Zone default device)'\n  if (url.kind === 'cyfs_object') out.obj_id = url.objId!.toString()\n  return out\n}\n\nfunction resolveCommand(): CommandDefinition {\n  return {\n    verb: 'resolve',\n    summary: 'Normalize a URL and show its identity, RBAC key, events and endpoint (no access check)',\n    positionals: [URL_ARG],\n    inputSchema: { type: 'object', properties: { url: { type: 'string', minLength: 1 } }, required: ['url'], additionalProperties: false },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: false,\n    examples: ['buckyos obj resolve obj://msg-center/owners/did:bns:alice/sessions', 'buckyos obj resolve //config/boot/config', 'buckyos obj resolve cyfs:///home/alice/a.md'],\n    handler: (ctx, input) => Promise.resolve(describe(ctx, parse(requiredInputString(input, 'url')))),\n  }\n}\n\nasync function getJson(ctx: CommandContext, url: string): Promise<unknown> {\n  const headers: Record<string, string> = { accept: 'application/json' }\n  if (ctx.session && new URL(url).origin === new URL(ctx.connection.endpoint).origin) headers.authorization = `Bearer ${(await ctx.session.ensureValid()).token}`\n  const response = await fetch(url, { headers, signal: ctx.signal })\n  const text = await response.text()\n  if (!response.ok) {\n    const code = response.status === 403 || response.status === 401 ? 'PERMISSION_DENIED' : response.status === 404 ? 'NOT_FOUND' : 'OBJECT_READ_FAILED'\n    throw new ToolError(code, `${url}: HTTP ${response.status} ${text.slice(0, 300)}`)\n  }\n  try {\n    return JSON.parse(text)\n  } catch {\n    throw new ToolError('INVALID_SERVICE_RESPONSE', `${url} did not answer JSON`, EXIT_INTERNAL)\n  }\n}\n\nfunction readCommand(): CommandDefinition {\n  return {\n    verb: 'read',\n    summary: 'Read a DID Object: its Card, Profile (properties, actions, events) and summary properties',\n    positionals: [URL_ARG],\n    options: [{ name: 'property', description: 'Read these properties instead of the summary ones (comma separated)', type: 'string' }],\n    inputSchema: {\n      type: 'object',\n      properties: { url: { type: 'string', minLength: 1 }, property: { type: 'string', minLength: 1 } },\n      required: ['url'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT,\n    resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync',\n    requiresSession: true,\n    examples: ['buckyos obj read obj://aiworkspace/ws_1/entities/e_1', 'buckyos obj read obj://xiaobai.test.buckyos.io/sessions/s-1 --property report'],\n    handler: async (ctx, input) => {\n      const url = parse(requiredInputString(input, 'url'))\n      const endpoint = endpointOf(ctx, url)\n      if (!endpoint) throw new ToolError('UNSUPPORTED_OBJECT', `${objectUrl.formatObjectUrl(url)} has no DID Object endpoint; read it as a file or content object`)\n      const card = (await getJson(ctx, endpoint)) as ObjectCard\n      const service = (card.service ?? []).find((s: Record<string, unknown>) => s.type === 'DIDObjectService')\n      if (!service) throw new ToolError('INVALID_SERVICE_RESPONSE', `${endpoint} answered no DID Object Card`, EXIT_INTERNAL)\n      const serviceEndpoint = String(service.serviceEndpoint).replace(/\\/$/, '')\n      const profileUrl = new URL(String(service.profile), `${serviceEndpoint}/`).toString()\n      const profile = (await getJson(ctx, profileUrl)) as ObjectProfile\n      const wanted = typeof input.property === 'string' ? input.property.split(',').map((p) => p.trim()).filter(Boolean) : (profile['x-buckyos:summary_props'] ?? [])\n      const properties: Record<string, unknown> = {}\n      for (const name of wanted) {\n        if (!profile.properties?.[name]) throw new UsageError('INVALID_ARGUMENT', `property ${name} is not declared by the object`)\n        properties[name] = await getJson(ctx, `${serviceEndpoint}/props/${encodeURIComponent(name)}`)\n      }\n      return {\n        ...describe(ctx, url),\n        object_did: card.id,\n        also_known_as: card.alsoKnownAs ?? [],\n        title: profile.title,\n        description: profile.description,\n        kind: service.kind ?? profile['x-buckyos:kind'],\n        traits: profile['x-buckyos:traits'] ?? [],\n        declared: {\n          properties: Object.keys(profile.properties ?? {}),\n          actions: Object.fromEntries(Object.entries(profile.actions ?? {}).map(([name, a]) => [name, { risk: a['x-buckyos:risk'], rbac: a['x-buckyos:rbac'] }])),\n          events: Object.fromEntries(Object.entries(profile.events ?? {}).map(([name, e]) => [name, e['x-buckyos:kevent']])),\n        },\n        properties,\n      }\n    },\n  }\n}\n\nfunction aliasCommand(): CommandDefinition {\n  const names = ['list', 'set', 'rm']\n  return {\n    verb: 'alias', summary: 'List, override or reset object aliases in your current Zone',\n    positionals: [{ name: 'action', description: 'list | set | rm', required: true }, { name: 'name', description: 'Complete alias name (set, rm)', required: false }],\n    options: [\n      { name: 'kind', description: 'local | link | disabled', type: 'string', enum: ['local', 'link', 'disabled'] },\n      { name: 'object', description: 'Installed object ID for a local binding', type: 'string' },\n      { name: 'url', description: 'Fixed Object URL for a link', type: 'string' },\n      { name: 'if-revision', property: 'if_revision', description: 'Expected override revision (0 if never configured)', type: 'integer' },\n    ],\n    inputSchema: { type: 'object', properties: {\n      action: { type: 'string', enum: names }, name: { type: 'string' }, kind: { type: 'string' },\n      object: { type: 'string' }, url: { type: 'string' }, if_revision: { type: 'integer', minimum: 0 },\n    }, required: ['action'], additionalProperties: false },\n    outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: { mode: 'operation', operationIdField: 'action', possibleLevels: ['read', 'write'] },\n    asyncMode: 'sync', requiresSession: true,\n    examples: ['buckyos obj alias list', 'buckyos obj alias set owner.cal --kind link --url obj://cal/calendars/alice --if-revision 0', 'buckyos obj alias rm owner.cal --if-revision 1'],\n    handler: async (ctx, input) => {\n      const { action, ...params } = input\n      if (!names.includes(String(action))) throw new UsageError('INVALID_ARGUMENT', 'expected list, set or rm')\n      if (action === 'list' && Object.keys(params).length) throw new UsageError('INVALID_ARGUMENT', 'list takes no arguments')\n      if (action !== 'list' && (!params.name || !Number.isSafeInteger(params.if_revision))) throw new UsageError('INVALID_ARGUMENT', 'name and --if-revision are required')\n      if (action === 'set' && !params.kind) throw new UsageError('INVALID_ARGUMENT', 'set requires --kind')\n      const result = expectObject(await callService(ctx, 'control-panel', 'owner.alias.' + action, params), 'owner.alias.' + action)\n      if (result.ok === false) {\n        const e = expectObject(result.error, 'alias error')\n        throw new ToolError(String(e.code), String(e.message), undefined, false, { detail: e.detail })\n      }\n      return result\n    },\n  }\n}\n\nfunction callCommand(): CommandDefinition {\n  return {\n    verb: 'call', summary: 'Invoke xcall with your current Zone session',\n    description: 'Pass the object, action and xcall arguments verbatim. The installed agent_tool handles profiles, permissions, output and exit status.',\n    examples: ['buckyos obj call owner who', 'buckyos obj call owner.todo add title=Review'],\n    inputSchema: { type: 'object', properties: { argv: { type: 'array', items: { type: 'string' } } }, required: ['argv'] },\n    outputSchema: { type: 'object', properties: { exit_code: { type: 'integer' } }, required: ['exit_code'] }, resultSchemaVersion: 1, access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync', requiresSession: true,\n    handler: async (ctx, input) => {\n      const host = getHost()\n      const root = host.policy.buckyosRoot\n      if (!root || host.policy.distribution !== 'system') throw new ToolError('EXTENSION_UNAVAILABLE', 'xcall requires the BuckyOS system installation')\n      if (!ctx.session) throw new ToolError('AUTH_REQUIRED', 'xcall requires a signed-in Zone session')\n      const { token } = await ctx.session.ensureValid()\n      const exe = host.path.join(root, 'bin', 'opendan', host.platform === 'win32' || host.platform === 'windows' ? 'agent_tool.exe' : 'agent_tool')\n      const env = { BUCKYOS_ROOT: root, BUCKYOS_TOOL_ENDPOINT: ctx.connection.endpoint, BUCKYOS_APPCLIENT_SESSION_TOKEN: token }\n      const child = host.spawn(exe, ['xcall', ...(input.argv as string[])], { cwd: ctx.cwd, env })\n      const cancel = () => child.kill()\n      ctx.signal.addEventListener('abort', cancel, { once: true })\n      try {\n        await child.closeInput()\n        for await (const line of child.lines()) await ctx.io.stdout(line + '\\n')\n        const stderr = await child.stderr\n        if (stderr) await ctx.io.stderr(stderr)\n        return { exit_code: await child.status }\n      } finally {\n        ctx.signal.removeEventListener('abort', cancel)\n      }\n    },\n  }\n}\n","import { ExecutorCommandStream } from 'buckyos/node'\nimport type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { ToolError } from '../core/errors.ts'\nimport { getHost } from '../runtime/host.ts'\n\nconst text = { type: 'string' as const, minLength: 1 }\ntype ExecutorRoute = Parameters<typeof ExecutorCommandStream.connect>[0]\ntype ExecutorOperationLocator = Parameters<InstanceType<typeof ExecutorCommandStream>['query']>[0]\nconst object = { type: 'object' as const, additionalProperties: true }\nconst targetProperties = {\n  executor_id: text, generation: { type: 'integer' as const, minimum: 1 },\n  profile_id: text, store_id: text, locator: text,\n}\n\nfunction call<T>(ctx: CommandContext, method: string, params: Record<string, unknown>): Promise<T> {\n  return ctx.clients.call('control-panel', method, params, {\n    traceId: ctx.traceId, signal: ctx.signal, timeoutMs: Math.max(1, (ctx.deadline ?? Date.now() + 30000) - Date.now()),\n  })\n}\n\nfunction management(verb: string, method: string, properties: Record<string, JsonSchema>, required: string[], write = false): CommandDefinition {\n  return {\n    verb, summary: `Executor ${verb}`, inputSchema: { ...object, properties, required, additionalProperties: false },\n    outputSchema: object, resultSchemaVersion: 1, access: { mode: 'fixed', level: write ? 'write' : 'read' },\n    asyncMode: 'sync', requiresSession: true,\n    options: Object.entries(properties).filter(([, schema]) => schema.type !== 'object').map(([name, schema]) => ({\n      name: name.replaceAll('_', '-'), property: name, description: name, type: schema.type === 'integer' ? 'integer' as const : 'string' as const,\n      required: required.includes(name),\n    })),\n    handler: (ctx, input) => call(ctx, method, input),\n  }\n}\n\nexport function createExecutorModule(): CommandModule {\n  return {\n    name: 'executor', summary: 'Manage lightweight devices and explicitly target online command/file executors',\n    commands: [\n      management('create', 'executor.device.create', { name: text, profiles: object, limits: object, expires_at_ms: { type: 'integer' } }, ['name', 'profiles'], true),\n      management('list', 'executor.device.list', {}, []),\n      management('issue', 'executor.device.issue', { executor_id: text, expires_at_ms: { type: 'integer' } }, ['executor_id'], true),\n      management('revoke', 'executor.device.revoke', { executor_id: text }, ['executor_id'], true),\n      management('delete', 'executor.device.delete', { executor_id: text }, ['executor_id'], true),\n      management('online', 'executor.online.list', {}, []),\n      operation('exec', { cmd: text, cwd: text, env: object, execution_timeout_ms: { type: 'integer', minimum: 1 } }, ['cmd', 'cwd']),\n      operation('read', { path: text }, ['path']),\n      operation('write', { path: text, content: { type: 'string' }, mode: { type: 'string', enum: ['replace', 'append', 'create_new'] } }, ['path', 'content']),\n      operation('edit', { path: text, old_string: text, new_string: { type: 'string' } }, ['path', 'old_string', 'new_string']),\n      operation('query', { channel: { type: 'string', enum: ['stdout', 'stderr', 'content'] }, offset: { type: 'integer', minimum: 0 }, wait_ms: { type: 'integer', minimum: 0 } }, []),\n      operation('cancel', {}, []),\n    ],\n  }\n}\n\nfunction operation(verb: string, extra: Record<string, JsonSchema>, required: string[]): CommandDefinition {\n  const recovery = verb === 'query' || verb === 'cancel'\n  const properties: Record<string, JsonSchema> = { ...targetProperties, ...extra }\n  return {\n    verb, summary: `${verb} on an explicit executor; persist --locator before dispatch and query it after disconnection`,\n    inputSchema: { ...object, properties, required: [...Object.keys(targetProperties), ...required], additionalProperties: false },\n    outputSchema: object, resultSchemaVersion: 1,\n    access: { mode: 'fixed', level: ['read', 'query'].includes(verb) ? 'read' : 'write' },\n    asyncMode: 'sync', requiresSession: true,\n    options: Object.entries(properties).filter(([, schema]) => schema.type !== 'object').map(([name, schema]) => ({\n      name: name.replaceAll('_', '-'), property: name, description: name,\n      type: schema.type === 'integer' ? 'integer' as const : 'string' as const,\n      required: Object.keys(targetProperties).includes(name) || required.includes(name),\n    })),\n    handler: async (ctx, input) => {\n      const target = { executor_id: String(input.executor_id), generation: Number(input.generation), profile_id: String(input.profile_id), store_id: String(input.store_id) }\n      const path = String(input.locator)\n      const host = getHost()\n      let locator: ExecutorOperationLocator\n      if (recovery) locator = JSON.parse(await host.readTextFile(path))\n      else {\n        locator = { ...target, op_id: crypto.randomUUID(), run_id: ctx.traceId, call_id: ctx.idempotencyKey ?? crypto.randomUUID() }\n        await host.writeTextFile(path, JSON.stringify(locator) + '\\n', { createNew: true, mode: 0o600 })\n      }\n      if (!ctx.session) throw new ToolError('AUTH_REQUIRED', 'An authenticated App session is required')\n      const { token } = await ctx.session.ensureValid()\n      const route = await call<ExecutorRoute>(ctx, 'executor.stream.open', { executor_id: target.executor_id, generation: target.generation, profile_id: target.profile_id })\n      const stream = await ExecutorCommandStream.connect(route, target, token, 'buckyos-cli', locator.run_id)\n      if (!stream) throw new ToolError('INVALID_SERVICE_RESPONSE', 'Executor stream did not initialize')\n      const abort = () => stream.close()\n      ctx.signal.addEventListener('abort', abort, { once: true })\n      try {\n        let reply\n        if (verb === 'exec') reply = await stream.exec(locator, String(input.cmd), String(input.cwd), (input.env ?? {}) as Record<string, string>, Number(input.execution_timeout_ms ?? 60000))\n        else if (verb === 'read') reply = await stream.read(locator, String(input.path))\n        else if (verb === 'write') reply = await stream.write(locator, String(input.path), new TextEncoder().encode(String(input.content)), (input.mode ?? 'replace') as 'replace' | 'append' | 'create_new')\n        else if (verb === 'edit') reply = await stream.edit(locator, String(input.path), [{ old_string: String(input.old_string), new_string: String(input.new_string) }])\n        else if (verb === 'cancel') reply = await stream.cancel(locator)\n        else reply = await stream.query(locator, input.channel as 'stdout' | 'stderr' | 'content' | undefined, Number(input.offset ?? 0), Number(input.wait_ms ?? 0))\n        return { locator, reply }\n      } finally { ctx.signal.removeEventListener('abort', abort); stream.close() }\n    },\n  }\n}\n","import type { CommandDefinition, CommandModule, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { UsageError } from '../core/errors.ts'\nimport { stageLocalPikg } from './app.ts'\n\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst ID = { type: 'string' as const, minLength: 1 }\n\nfunction call<T = Record<string, unknown>>(ctx: CommandContext, method: string, params: Record<string, unknown>): Promise<T> {\n  return ctx.clients.call('control-panel', method, params, {\n    traceId: ctx.traceId, signal: ctx.signal, timeoutMs: Math.max(1, (ctx.deadline ?? Date.now() + 60000) - Date.now()),\n  })\n}\n\nfunction requestOf(input: Record<string, unknown>, enabled: boolean): Record<string, unknown> {\n  const id = typeof input.id === 'string' ? input.id : ''\n  if (!id) throw new UsageError('MISSING_ARGUMENT', 'a package id is required')\n  return { id, enabled, ...(typeof input.version === 'string' ? { version: input.version } : {}) }\n}\n\nfunction read(verb: string, summary: string, method: string): CommandDefinition {\n  return {\n    verb, summary,\n    inputSchema: { type: 'object', properties: {}, additionalProperties: false },\n    outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: { mode: 'fixed', level: 'read' },\n    asyncMode: 'sync', requiresSession: true,\n    handler: (ctx) => call(ctx, method, {}),\n  }\n}\n\nfunction desired(verb: string, summary: string, enabled: boolean): CommandDefinition {\n  const properties: Record<string, JsonSchema> = { id: ID, ...(enabled ? { version: { type: 'string', minLength: 1 } } : {}), dry_run: { type: 'boolean' } }\n  return {\n    verb, summary,\n    positionals: [{ name: 'id', description: 'Package id, e.g. ext-core' }],\n    options: [\n      ...(enabled ? [{ name: 'version', description: 'A published version; the newest without it', type: 'string' as const }] : []),\n      { name: 'dry-run', property: 'dry_run', description: 'Only show what would change', type: 'boolean' as const },\n    ],\n    inputSchema: { type: 'object', properties, required: ['id'], additionalProperties: false },\n    outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync', requiresSession: true,\n    handler: (ctx, input) => call(ctx, input.dry_run === true ? 'ext_tools.plan' : 'ext_tools.set_desired', requestOf(input, enabled)),\n  }\n}\n\n/** An online item is what a package only declares: each node downloads it from its upstream once, when the package is\n * installed. A download that failed stays failed until it is asked for again, which is what this does. */\nfunction download(): CommandDefinition {\n  return {\n    verb: 'download',\n    summary: 'Ask the nodes to download an online item of a package again: after a failure, or to replace what is there',\n    positionals: [\n      { name: 'id', description: 'Package id, e.g. ext-core' },\n      { name: 'item', description: 'Online item id, e.g. chromium (see `online` in ext-tools status)' },\n    ],\n    options: [{ name: 'node', description: 'Only this node; without it every node that has the item', type: 'string' as const }],\n    inputSchema: {\n      type: 'object',\n      properties: { id: ID, item: ID, node: { type: 'string', minLength: 1 } },\n      required: ['id', 'item'],\n      additionalProperties: false,\n    },\n    outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: { mode: 'fixed', level: 'write' },\n    asyncMode: 'sync', requiresSession: true,\n    handler: (ctx, input) => {\n      for (const name of ['id', 'item']) {\n        if (typeof input[name] !== 'string' || !input[name]) throw new UsageError('MISSING_ARGUMENT', `a package id and an online item id are required`)\n      }\n      return call(ctx, 'ext_tools.download', { id: input.id, item: input.item, ...(typeof input.node === 'string' ? { node: input.node } : {}) })\n    },\n  }\n}\n\n/** The Zone's extension packages. The administrator says what the Zone should have; each node's reconciler gets there. */\nexport function createExtToolsModule(): CommandModule {\n  return {\n    name: 'ext-tools',\n    summary: 'Manage the extension tool packages every Agent of the Zone shares',\n    commands: [\n      read('list', 'The packages published in the Repo, and what each provides', 'ext_tools.catalog'),\n      read('status', 'Package by node: what is asked for, where each node got to, and the online items it downloaded or still waits for', 'ext_tools.status'),\n      desired('enable', 'Enable or upgrade a package, with the packages it requires', true),\n      desired('disable', 'Disable a package; refused while an enabled package requires it', false),\n      download(),\n      {\n        verb: 'import',\n        summary: 'Put an already built .pikg (an official release asset) into the Repo unchanged',\n        positionals: [{ name: 'pikg', description: 'Local .pikg file' }],\n        inputSchema: { type: 'object', properties: { pikg: { type: 'string', minLength: 1 } }, required: ['pikg'], additionalProperties: false },\n        outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: { mode: 'fixed', level: 'write' },\n        asyncMode: 'sync', requiresSession: true,\n        handler: async (ctx, input) => {\n          const staging = await stageLocalPikg(ctx, String(input.pikg))\n          return await call(ctx, 'ext_tools.import', { handle: staging.handle })\n        },\n      },\n    ],\n  }\n}\n","import {\n  AIWS_PROTOCOL_VERSION,\n  BindFailure,\n  bindingsPayload,\n  createOps,\n  noUiDialogs,\n  orderKeyBetween,\n  resolveBindings,\n} from 'buckyos/node'\nimport type { CommandDefinition, JsonSchema } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { ToolError, UsageError } from '../core/errors.ts'\nimport { callService, expectObject, inputString, requiredInputString } from '../core/service.ts'\n\n// Placing a control on a canvas as an Agent (buckyos notepads/aiworkspace-control-on-bind-todo.md §2.8, Q6): the same\n// on_bind / on_init_control a person's insertion runs (buckyos-websdk aiws_bind.ts), without dialogs (`no_ui`). What the\n// Agent gives (--bind) is taken; what the default rule settles without a choice (none → created, one → bound) is done;\n// where a person would have to choose, the command fails naming the binding to give. One Commit. An HTML control that\n// decides its bindings in its own script (on_bind \"script\", TODO §2.9) is not run here: what the Agent gives is its ctx,\n// taken as it is (owner 11-12).\n\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst SERVICE = 'aiworkspace'\nconst NOT_DATA = new Set([\n  'buckyos.cell',\n  'buckyos.container',\n  'buckyos.block-def',\n  'buckyos.viewport',\n  'buckyos.show-path',\n])\nconst BUILTIN_SIZE: Record<string, { w: number; h: number }> = {\n  todo: { w: 420, h: 520 },\n  calendar: { w: 860, h: 620 },\n}\n\ntype Envelope = Record<string, unknown> & {\n  entity_id: string\n  type_id: string\n  parent_id?: string | null\n  order_key?: string | null\n  deleted?: boolean\n  /** a path node: an entity the caller cannot read, listed above one it can (no name, no content) */\n  path_only?: boolean\n}\n// the shapes of buckyos-websdk aiws_bind.ts (the CLI reads the SDK's built JavaScript)\ntype BindingDecl = {\n  accepts?: string[]\n  required?: boolean\n  many?: boolean\n  schema_id?: string\n  title?: string\n}\ntype DataInfo = {\n  entity_id: string\n  type_id: string\n  schema_id: string | null\n  title: string | null\n}\ntype DataQuery = { accepts?: string[]; schema_id?: string; ids?: string[] }\ntype GivenCtx = {\n  node: string\n  given: Record<string, string | string[]>\n  decls: Record<string, BindingDecl>\n}\n\n/** An HTML control's on_bind for an Agent: its script runs in a person's browser only, so the bindings given are taken as\n * they are; a required one not given fails naming it. */\nfunction givenOnly(title: string) {\n  return (ctx: GivenCtx) => {\n    const missing = Object.entries(ctx.decls).filter(([name, d]) =>\n      d.required && ctx.given[name] === undefined\n    )\n      .map(([name]) => name)\n    if (missing.length > 0) {\n      throw new BindFailure(\n        `${title} decides its data in its own script, which runs in a person's browser only: give ${\n          missing.join(', ')\n        } with --bind`,\n        'NEEDS_UI',\n        ctx.node,\n        missing[0],\n      )\n    }\n    return Promise.resolve({ bindings: ctx.given, create: [] })\n  }\n}\ntype Outcome =\n  | {\n    ok: true\n    results: Map<string, { bindings: Record<string, string | string[]> }>\n    then: { node: string; action: string }[]\n  }\n  | { ok: false; error: { code: string; message: string; binding?: string } }\n\nasync function call(\n  ctx: CommandContext,\n  method: string,\n  params: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n  const result = expectObject(await callService<unknown>(ctx, SERVICE, method, params), method)\n  if (result.ok === false) {\n    const error = expectObject(result.error, `${method}.error`)\n    const code = typeof error.code === 'string' ? error.code : 'AIWS_ERROR'\n    throw new ToolError(code, `${code}: ${String(error.detail ?? code)}`, undefined, false, {\n      ...(error.sub_code ? { sub_code: error.sub_code } : {}),\n      ...(error.data !== undefined ? { data: error.data } : {}),\n    })\n  }\n  return result\n}\n\n/** `name=id[,id];name2=id` → given bindings. */\nfunction parseBind(text: string | undefined): Record<string, string | string[]> {\n  const out: Record<string, string | string[]> = {}\n  for (const part of (text ?? '').split(';').map((s) => s.trim()).filter(Boolean)) {\n    const at = part.indexOf('=')\n    if (at <= 0) throw new UsageError('AIWS_USAGE', `--bind ${part}: name=id[,id]`)\n    const ids = part.slice(at + 1).split(',').map((s) => s.trim()).filter(Boolean)\n    out[part.slice(0, at).trim()] = ids.length === 1 ? ids[0] : ids\n  }\n  return out\n}\n\nfunction freeName(taken: Set<string>, base: string): string {\n  let name = base\n  for (let n = 2; taken.has(name); n++) name = `${base} (${n})`\n  taken.add(name)\n  return name\n}\n\nexport const placeCommand: CommandDefinition = {\n  verb: 'place',\n  summary:\n    'Place a control on a canvas the way a person inserts it: its on_bind settles its data (none → created, one → bound); give a binding where it would ask',\n  description:\n    'CONTROL is `todo`, `calendar` or a definition of the workspace (its entity id, or its identity <author_did>#<name>). Bindings you give (--bind \"photos=d1;votes=t1,t2\", a list for a `many` binding) are taken; the rest follow the control\\'s on_bind with no dialogs: a choice a person would make fails with NEEDS_UI naming the binding to give. Data it creates (a standard table, a composite\\'s declared table or folder) goes into the canvas\\'s content folder, owned by the control. A composite\\'s on_init_control actions (e.g. preparing a ballot) are listed in `then`: run them yourself (the Desktop runs them for a person). An HTML control whose own script decides its data (on_bind \"script\", see its AGENT.md) is not run here: give its bindings with --bind; a required one missing fails with NEEDS_UI.',\n  positionals: [{\n    name: 'control',\n    description: 'todo | calendar | a definition id | <author_did>#<name>',\n    required: true,\n  }],\n  options: [\n    {\n      name: 'workspace',\n      property: 'workspace_id',\n      description: 'Workspace id (ws_…)',\n      type: 'string',\n      required: true,\n    },\n    {\n      name: 'surface',\n      property: 'surface',\n      description: 'Canvas (Surface) id',\n      type: 'string',\n      required: true,\n    },\n    {\n      name: 'bind',\n      property: 'bind',\n      description: 'Bindings you give: \"name=id[,id];name=id\"',\n      type: 'string',\n    },\n    { name: 'title', property: 'title', description: 'Title of the control', type: 'string' },\n    {\n      name: 'at',\n      property: 'at',\n      description: 'Position x,y on a free canvas (default: right of what is on it)',\n      type: 'string',\n    },\n    {\n      name: 'config',\n      property: 'config',\n      description: 'Instance properties, a JSON object',\n      type: 'string',\n    },\n  ],\n  inputSchema: {\n    type: 'object',\n    properties: {\n      control: { type: 'string', minLength: 1 },\n      workspace_id: { type: 'string', minLength: 1 },\n      surface: { type: 'string', minLength: 1 },\n      bind: { type: 'string' },\n      title: { type: 'string' },\n      at: { type: 'string' },\n      config: { type: 'string' },\n    },\n    required: ['control', 'workspace_id', 'surface'],\n    additionalProperties: false,\n  },\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: [\n    'buckyos aiws place todo --workspace ws_… --surface sf_…',\n    'buckyos aiws place calendar --workspace ws_… --surface sf_… --bind \"events=t_cal\"',\n    'buckyos aiws place did:bns:buckyos#photo-vote --workspace ws_… --surface sf_… --bind \"photos=d_trip\"',\n  ],\n  handler: async (ctx, input) => {\n    const ws = requiredInputString(input, 'workspace_id')\n    const surfaceId = requiredInputString(input, 'surface')\n    const control = requiredInputString(input, 'control')\n    const info = await call(ctx, 'ws.get_info', { workspace_id: ws })\n    const entities = (await call(ctx, 'doc.outline', { workspace_id: ws })).entities as Envelope[]\n    const byId = new Map(entities.map((e) => [e.entity_id, e]))\n    const surface = byId.get(surfaceId)\n    if (!surface || surface.kind !== 'surface' || surface.path_only) {\n      throw new UsageError('AIWS_USAGE', `${surfaceId} is not a canvas of this workspace`)\n    }\n    const folderId = String(surface.content_folder_id ?? '')\n    const config = inputString(input, 'config')\n      ? JSON.parse(inputString(input, 'config')!) as Record<string, unknown>\n      : undefined\n    // by default right of what is already on the canvas, so the controls an Agent places do not cover each other\n    const right = entities.filter((e) => e.parent_id === surfaceId && !e.deleted).reduce(\n      (max, e) => {\n        const p = e.placement as { x?: unknown; w?: unknown } | undefined\n        return typeof p?.x === 'number'\n          ? Math.max(max, p.x + (typeof p.w === 'number' ? p.w : 320))\n          : max\n      },\n      0,\n    )\n    const at = inputString(input, 'at')\n      ? inputString(input, 'at')!.split(',').map(Number)\n      : [right > 0 ? right + 40 : 40, 40]\n\n    // the control: a built-in data control's contract, or a definition of the workspace\n    let decls: Record<string, BindingDecl>\n    let node: { onBind?: unknown; onInit?: unknown } = {}\n    let op: Record<string, unknown>\n    let title = inputString(input, 'title') ?? undefined\n    const id = `c${Math.random().toString(36).slice(2, 14)}`\n    if (control === 'todo' || control === 'calendar') {\n      const contract = expectObject(\n        (await call(ctx, 'control.describe', { kind: control })).control,\n        'control',\n      ).contract as Record<string, unknown>\n      decls = (contract.bindings ?? {}) as Record<string, BindingDecl>\n      title ??= String(contract.title ?? control)\n      const size = BUILTIN_SIZE[control]\n      op = {\n        op: 'entity.create',\n        entity_id: id,\n        type_id: 'buckyos.container',\n        parent_id: surfaceId,\n        placement: { x: at[0] || 40, y: at[1] || 40, ...size },\n        payload: { kind: control, layout: { mode: 'data' }, title },\n      }\n    } else {\n      const def = entities.find((e) =>\n        e.type_id === 'buckyos.block-def' && !e.deleted &&\n        (e.entity_id === control || e.ident === control)\n      )\n      if (!def) {\n        throw new UsageError(\n          'AIWS_USAGE',\n          `no control ${control} in this workspace (build or import it first)`,\n        )\n      }\n      const payload =\n        ((await call(ctx, 'doc.read', { workspace_id: ws, entity_id: def.entity_id })).content as {\n          payload: Record<string, unknown>\n        }).payload\n      decls = (payload.bindings ?? {}) as Record<string, BindingDecl>\n      title ??= String(payload.title ?? def.entity_id)\n      // a composite's declared steps; an HTML control's script is not run (its init check is the default one)\n      node = payload.on_bind === 'script'\n        ? { onBind: givenOnly(title) }\n        : payload.kind === 'composite'\n        ? { onBind: payload.on_bind, onInit: payload.on_init_control }\n        : {}\n      const size = (payload.default_size as { w: number; h: number } | undefined) ??\n        { w: 320, h: 240 }\n      op = payload.kind === 'composite'\n        ? {\n          op: 'entity.create',\n          entity_id: id,\n          type_id: 'buckyos.container',\n          parent_id: surfaceId,\n          placement: { x: at[0] || 40, y: at[1] || 40, w: 'auto', h: 'auto' },\n          payload: {\n            kind: 'composite',\n            def_ref: { entity_id: def.entity_id },\n            ...(config ? { config } : {}),\n          },\n        }\n        : {\n          op: 'entity.create',\n          entity_id: id,\n          type_id: 'buckyos.cell',\n          parent_id: surfaceId,\n          placement: { x: at[0] || 40, y: at[1] || 40, ...size },\n          payload: {\n            view: { type: String(payload.kind) },\n            def_ref: { entity_id: def.entity_id },\n            ...(config ? { config } : {}),\n          },\n        }\n    }\n\n    const data: DataInfo[] = entities.filter((e) => !e.deleted && !NOT_DATA.has(e.type_id))\n      .map((e) => ({\n        entity_id: e.entity_id,\n        type_id: e.type_id,\n        schema_id: (e.schema_id as string | null) ?? null,\n        title: (e.title as string | null) ?? (e.name as string | null) ?? null,\n      }))\n    const outcome = await resolveBindings(\n      {\n        id,\n        title: title!,\n        decls,\n        given: parseBind(inputString(input, 'bind') ?? undefined),\n        children: [],\n        ...node,\n      } as never,\n      {\n        reason: 'insert',\n        no_ui: true,\n        dialogs: noUiDialogs(),\n        find: (q: DataQuery) =>\n          data.filter((d) =>\n            (!q.accepts?.length || q.accepts.includes(d.type_id)) &&\n            (!q.schema_id || d.schema_id === q.schema_id) && (!q.ids || q.ids.includes(d.entity_id))\n          ),\n      },\n    ) as Outcome\n    if (!outcome.ok) {\n      throw new ToolError(\n        outcome.error.code,\n        `${outcome.error.code}: ${outcome.error.message}`,\n        undefined,\n        false,\n        { ...(outcome.error.binding ? { binding: outcome.error.binding } : {}) },\n      )\n    }\n\n    const children = entities.filter((e) => e.parent_id === folderId && !e.deleted)\n    const taken = new Set(children.map((e) => String(e.name ?? '')).filter(Boolean))\n    let last = children.map((e) => e.order_key ?? '').filter(Boolean).sort().at(-1) ?? null\n    const made = createOps(outcome.results, {\n      folderId,\n      newId: () => `d${Math.random().toString(36).slice(2, 14)}`,\n      orderKey: () => {\n        last = orderKeyBetween(last, null)\n        return last\n      },\n      freeName: (name: string) => freeName(taken, name),\n      locale: /^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale) ? 'zh' : 'en',\n    })\n    const bindings = bindingsPayload(outcome.results.get(id)!.bindings, decls, made.ids)\n    const lastOnCanvas =\n      entities.filter((e) => e.parent_id === surfaceId && !e.deleted).map((e) => e.order_key ?? '')\n        .filter(Boolean).sort().at(-1) ?? null\n    op.order_key = orderKeyBetween(lastOnCanvas, null)\n    if (Object.keys(bindings).length > 0) {\n      ;(op.payload as Record<string, unknown>).bindings = bindings\n    }\n    const commit = await call(ctx, 'doc.commit', {\n      protocol_version: AIWS_PROTOCOL_VERSION,\n      workspace_id: ws,\n      epoch: info.epoch,\n      idempotency_key: `place-${id}`,\n      origin: 'agent',\n      message: `place ${title}`,\n      operations: [...made.ops, op],\n    })\n    if (commit.status !== 'accepted') {\n      throw new ToolError(\n        'AIWS_COMMIT_REFUSED',\n        `the placement was not accepted: ${JSON.stringify(commit).slice(0, 500)}`,\n      )\n    }\n    return {\n      entity_id: id,\n      bindings,\n      created: Object.values(made.ids),\n      then: outcome.then.map((t) => t.action),\n      commit_seq: commit.seq ?? null,\n    }\n  },\n}\n","import {\n  AIWS_MANIFEST_FILE,\n  AIWS_MANIFEST_VERSION,\n  AiwsFailure,\n  AiwsSourceError,\n  aiwsTarget,\n  buildControl,\n  commitOps,\n  exportBundle,\n  fieldAdd,\n  isSourcePath,\n  move,\n  NfspClient,\n  optionAdd,\n  packBuildFiles,\n  pullControl,\n  rename,\n  setProps,\n  tableDelete,\n  tableInsert,\n  tableSet,\n  templateDir,\n  textAppend,\n  textDeleteBlocks,\n  textReplaceBlock,\n  watchControl,\n} from 'buckyos/node'\nimport { AiccLlmClient, LLMComputeException, providerErrorFromRpc } from 'buckyos/xllm'\nimport type { CommandDefinition, CommandModule, JsonSchema, OptionDefinition, PositionalDefinition } from '../core/command.ts'\nimport type { CommandContext } from '../core/context.ts'\nimport { EXIT_AUTH, ToolError, UsageError } from '../core/errors.ts'\nimport { callService, expectObject, inputString, requiredInputString, rpcOptions } from '../core/service.ts'\nimport { getHost } from '../runtime/host.ts'\nimport { createPikgModule } from './pikg.ts'\nimport { placeCommand } from './aiws_place.ts'\nimport { gatewayOrigin } from './share.ts'\n\n// AI Workspace (`/kapi/aiworkspace`): finding, reading, querying and writing a workspace (ls, find, grep, stat, cat,\n// resolve, sql; table, text, mv, rename, set-prop: buckyos notepads/aiws-core-api-design.md §9), and the executor\n// protocol of a wish run (内核架构改进 M3): claim → heartbeat → report. Source of truth for the methods:\n// buckyos/src/frame/aiworkspace/README.md (Protocol).\nconst SERVICE = 'aiworkspace'\nconst OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }\nconst WORKSPACE_OPTION: OptionDefinition = { name: 'workspace', property: 'workspace_id', description: 'Workspace id (ws_…)', type: 'string', required: true }\nconst RUN_OPTION: OptionDefinition = { name: 'run', property: 'run_id', description: 'Run id (run_…)', type: 'string', required: true }\nconst ATTEMPT_OPTION: OptionDefinition = { name: 'attempt', property: 'attempt', description: 'The attempt number `run-claim` answered', type: 'integer', required: true }\n\nfunction workspaceInput(extra: Record<string, JsonSchema>, required: string[] = []): JsonSchema {\n  return { type: 'object', properties: { workspace_id: { type: 'string', minLength: 1 }, ...extra }, required: ['workspace_id', ...required], additionalProperties: false }\n}\n\nasync function aiws(ctx: CommandContext, method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const result = expectObject(await callService<unknown>(ctx, SERVICE, method, params), method)\n  if (result.ok === false) {\n    const error = expectObject(result.error, `${method}.error`)\n    const code = typeof error.code === 'string' ? error.code : 'AIWS_ERROR'\n    const detail = typeof error.detail === 'string' ? error.detail : code\n    // the structured part (a build's diagnostics, a conflict's revisions) travels in the error's details\n    const details: Record<string, unknown> = {}\n    if (typeof error.sub_code === 'string') details.sub_code = error.sub_code\n    if (error.data !== undefined) details.data = error.data\n    throw new ToolError(code, `${code}${typeof error.sub_code === 'string' ? `/${error.sub_code}` : ''}: ${detail}`, undefined, false, details)\n  }\n  return result\n}\n\nasync function jsonInput(input: Record<string, unknown>, textKey: string, fileKey: string, label: string): Promise<unknown> {\n  const text = inputString(input, textKey)\n  const file = inputString(input, fileKey)\n  if (text && file) throw new UsageError('AIWS_USAGE', `${textKey} and ${fileKey} are exclusive`)\n  if (file) return JSON.parse(await getHost().readTextFile(file)) as unknown\n  if (text) return JSON.parse(text) as unknown\n  throw new UsageError('AIWS_USAGE', `${label}: pass --${textKey.replace(/_/g, '-')} or --${fileKey.replace(/_/g, '-')}`)\n}\n\n// ---- finding and reading. An entity argument is a path (`/data/销售`, `~<entity_id>/…`) or an entity id.\n\nconst PATH_HELP = 'Path (/data/销售, ~<entity_id>/…) or entity id'\nconst TYPE_OPTIONS: OptionDefinition[] = [\n  { name: 'type', property: 'type', description: 'Only these types, comma-separated: table, richtext, record, annotation, block, container (container:<kind>), asset, dir, wish, def, …', type: 'string' },\n  { name: 'not-type', property: 'not_type', description: 'Leave these types out, comma-separated', type: 'string' },\n]\nconst CURSOR_OPTION: OptionDefinition = { name: 'cursor', property: 'cursor', description: 'Continue from the next_cursor of a previous page', type: 'string' }\nconst READ_ACCESS = { mode: 'fixed', level: 'read' } as const\nconst WRITE_ACCESS = { mode: 'fixed', level: 'write' } as const\n\n/** The keys of `input` that are given, renamed by `names` ({ input key: param }). */\nfunction given(input: Record<string, unknown>, names: Record<string, string>): Record<string, unknown> {\n  const out: Record<string, unknown> = {}\n  for (const [key, param] of Object.entries(names)) {\n    const v = input[key]\n    if (typeof v === 'string' ? v.trim() !== '' : v !== undefined && v !== false) out[param] = typeof v === 'string' ? v.trim() : v\n  }\n  return out\n}\n\nfunction jsonArg(text: string, label: string): unknown {\n  try {\n    return JSON.parse(text) as unknown\n  } catch (error) {\n    throw new UsageError('AIWS_USAGE', `${label}: ${error instanceof Error ? error.message : String(error)}`)\n  }\n}\n\nconst readCommand: CommandDefinition = {\n  verb: 'read',\n  summary: 'Read one entity of a workspace: envelope and native content',\n  positionals: [{ name: 'entity_id', description: PATH_HELP, required: true } satisfies PositionalDefinition],\n  options: [WORKSPACE_OPTION, { name: 'selector', property: 'selector', description: 'Selector JSON, e.g. {\"kind\":\"table_record\",\"record_id\":\"r1\"}', type: 'string' }],\n  inputSchema: workspaceInput({ entity_id: { type: 'string', minLength: 1 }, selector: { type: 'string' } }, ['entity_id']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws read orders --workspace ws_abc', 'buckyos aiws read /data/订单 --workspace ws_abc --selector \\'{\"kind\":\"table_record\",\"record_id\":\"r1\"}\\''],\n  handler: (ctx, input) => {\n    const selector = inputString(input, 'selector')\n    return aiws(ctx, 'doc.read', { workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'entity_id')), ...(selector ? { selector: jsonArg(selector, '--selector') } : {}) })\n  },\n}\n\nconst lsCommand: CommandDefinition = {\n  verb: 'ls',\n  summary: 'The direct children of a path (default /), in tree order: name, path, type, title, children, body state',\n  positionals: [{ name: 'path', description: `${PATH_HELP} (default /)`, required: false }],\n  options: [WORKSPACE_OPTION, ...TYPE_OPTIONS, { name: 'schema', property: 'schema', description: 'Only entities of this schema id, e.g. buckyos.todo@1', type: 'string' }, { name: 'limit', property: 'limit', description: 'Items per page (≤ 1000, default 100)', type: 'integer' }, CURSOR_OPTION],\n  inputSchema: workspaceInput({ path: { type: 'string' }, type: { type: 'string' }, not_type: { type: 'string' }, schema: { type: 'string' }, limit: { type: 'integer', minimum: 1 }, cursor: { type: 'string' } }),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws ls --workspace ws_abc', 'buckyos aiws ls /data --workspace ws_abc --type table'],\n  handler: (ctx, input) => aiws(ctx, 'doc.list', { workspace_id: requiredInputString(input, 'workspace_id'), ...given(input, { path: 'at', type: 'type', not_type: 'not_type', schema: 'schema', limit: 'limit', cursor: 'cursor' }) }),\n}\n\nconst findCommand: CommandDefinition = {\n  verb: 'find',\n  summary: 'Entities whose name or title holds a literal (case-insensitive), by type and schema, walking down from a path',\n  description: 'A pre-order walk of at most 20 000 entities per call: when `complete` is false, continue with --cursor. Without text it finds by --type / --schema only.',\n  positionals: [{ name: 'text', description: 'Literal looked for in names and titles', required: false }],\n  options: [WORKSPACE_OPTION, { name: 'at', property: 'at', description: `Where to start: ${PATH_HELP} (default /)`, type: 'string' }, { name: 'depth', property: 'depth', description: 'Levels below --at (≤ 16)', type: 'integer' }, ...TYPE_OPTIONS, { name: 'schema', property: 'schema', description: 'Only entities of this schema id', type: 'string' }, { name: 'limit', property: 'limit', description: 'Items per page (≤ 200, default 50)', type: 'integer' }, CURSOR_OPTION],\n  inputSchema: workspaceInput({ text: { type: 'string' }, at: { type: 'string' }, depth: { type: 'integer', minimum: 1 }, type: { type: 'string' }, not_type: { type: 'string' }, schema: { type: 'string' }, limit: { type: 'integer', minimum: 1 }, cursor: { type: 'string' } }),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws find 销售 --workspace ws_abc', 'buckyos aiws find --workspace ws_abc --type table --at /data'],\n  handler: (ctx, input) => aiws(ctx, 'doc.find', { workspace_id: requiredInputString(input, 'workspace_id'), ...given(input, { text: 'name', at: 'at', depth: 'depth', type: 'type', not_type: 'not_type', schema: 'schema', limit: 'limit', cursor: 'cursor' }) }),\n}\n\nconst grepCommand: CommandDefinition = {\n  verb: 'grep',\n  summary: 'A literal (1–256 characters) in names, titles and bodies (the plain-text rendering of each entity): hits with a snippet and the selector of the part',\n  description: 'Literal match, case-insensitive unless --case; no regex. An empty result means “none” only when coverage.complete is true; otherwise continue with --cursor. Annotations, viewports, paths, tasks, responses and results are searched only when named in --type.',\n  positionals: [{ name: 'text', description: 'Literal to look for', required: true }],\n  options: [WORKSPACE_OPTION, { name: 'at', property: 'at', description: `Where to search: ${PATH_HELP} (default /)`, type: 'string' }, { name: 'depth', property: 'depth', description: 'Levels below --at', type: 'integer' }, { name: 'case', property: 'case', description: 'Compare case-sensitively', type: 'boolean' }, ...TYPE_OPTIONS, { name: 'limit', property: 'limit', description: 'Hits per page (≤ 100, default 20)', type: 'integer' }, CURSOR_OPTION],\n  inputSchema: workspaceInput({ text: { type: 'string', minLength: 1 }, at: { type: 'string' }, depth: { type: 'integer', minimum: 1 }, case: { type: 'boolean' }, type: { type: 'string' }, not_type: { type: 'string' }, limit: { type: 'integer', minimum: 1 }, cursor: { type: 'string' } }, ['text']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws grep 华东 --workspace ws_abc', 'buckyos aiws grep \"Q4 plan\" --workspace ws_abc --at /docs --type richtext'],\n  handler: (ctx, input) => aiws(ctx, 'doc.query', { workspace_id: requiredInputString(input, 'workspace_id'), text: requiredInputString(input, 'text'), ...given(input, { at: 'at', depth: 'depth', case: 'case', type: 'type', not_type: 'not_type', limit: 'limit', cursor: 'cursor' }) }),\n}\n\n// ---- permissions (buckyos notepads/aiws-permission-system-prd.md §4; README “Permissions”): entries `subject × resource\n// → allow, deny` addressed by path, logical groups, anonymous access, inner-path publications, the operation record.\nconst SUBJECT_HELP = 'A principal (user id, DID), @<group>, @all, @guest or @creator'\nconst caps = (text: string | undefined): string[] => (text ? ids(text) : [])\n\nconst aclCommand: CommandDefinition = {\n  verb: 'acl',\n  summary: 'Read permissions: `ls` (every entry, or your own), `show <path>` (who holds what on it and from where), `who [subject]` (a subject\\'s entries; a principal\\'s groups), `explain <path> [--principal]` (why each capability is allowed or refused), `groups`, `entries` (share links), `audit` (the operation record)',\n  description: 'Entries are decided by the nearest layer (the entity, its ancestors, then /) that mentions a capability, then by the most specific tier (a single caller, then groups and @creator, then @guest and @all); a deny wins within a tier. Anyone may ask about themselves (who, explain); the rest needs manage.',\n  positionals: [\n    { name: 'action', description: 'ls | show | who | explain | groups | entries | audit', required: true },\n    { name: 'target', description: `show / explain: ${PATH_HELP} (default /); who: ${SUBJECT_HELP}`, required: false },\n  ],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'principal', property: 'principal', description: 'explain: whose permissions (default: yours; another\\'s needs manage)', type: 'string' },\n    { name: 'expand', property: 'expand', description: 'show: list the members of each group', type: 'boolean' },\n    { name: 'after', property: 'after', description: 'audit: records after this sequence number', type: 'integer' },\n    { name: 'limit', property: 'limit', description: 'audit: at most this many records (≤ 1000)', type: 'integer' },\n  ],\n  inputSchema: workspaceInput({\n    action: { type: 'string', enum: ['ls', 'show', 'who', 'explain', 'groups', 'entries', 'audit'] }, target: { type: 'string' }, principal: { type: 'string' },\n    expand: { type: 'boolean' }, after: { type: 'integer' }, limit: { type: 'integer', minimum: 1 },\n  }, ['action']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: [\n    'buckyos aiws acl show /data/成绩 --workspace ws_abc',\n    'buckyos aiws acl explain /data/成绩 --principal bob --workspace ws_abc',\n    'buckyos aiws acl who @teachers --workspace ws_abc',\n    'buckyos aiws acl groups --workspace ws_abc',\n  ],\n  handler: (ctx, input) => {\n    const workspace_id = requiredInputString(input, 'workspace_id')\n    const target = inputString(input, 'target')\n    switch (requiredInputString(input, 'action')) {\n      case 'ls': return aiws(ctx, 'acl.query', { workspace_id, by: 'all' })\n      case 'show': return aiws(ctx, 'acl.query', { workspace_id, by: 'entity', resource: target ?? '/', ...given(input, { expand: 'expand' }) })\n      case 'who': return aiws(ctx, 'acl.query', { workspace_id, by: 'subject', ...(target ? { subject: target } : {}) })\n      case 'explain': return aiws(ctx, 'acl.query', { workspace_id, by: 'explain', resource: target ?? '/', ...given(input, { principal: 'principal' }) })\n      case 'groups': return aiws(ctx, 'acl.groups', { workspace_id })\n      case 'entries': return aiws(ctx, 'ws.list_entries', { workspace_id })\n      case 'audit': return aiws(ctx, 'acl.audit', { workspace_id, ...given(input, { after: 'after', limit: 'limit' }) })\n      default: throw new UsageError('AIWS_USAGE', 'acl: ls, show, who, explain, groups, entries or audit')\n    }\n  },\n}\n\nconst aclEditCommand: CommandDefinition = {\n  verb: 'acl-edit',\n  summary: 'Change permissions: `set <subject> <path> --allow … --deny …` (replaces that entry; both empty removes it), `rm <subject> <path>`, `group-add <id> [--title]`, `group-rm <id>`, `member-add <group> <members>`, `member-rm <group> <members>`, `anonymous on|off`, `bind <wish> <group|none> [--mode]`, `entry-add <group> --methods …`, `entry-close <entry_id> [--remove-members]`, `publish <path> [--name]`, `unpublish <path>`',\n  description: 'Needs manage (giving or taking manage, or changing the members of a group holding it, is the owner\\'s). Members: a principal, group:<system group>, contact:<your did>#<tag>, * (every unrestricted account of the Zone); a group is never a member of a group. @all and @guest never get manage or run; @guest exists only while anonymous access is on. A share entry leads into a group holding neither manage nor run.',\n  positionals: [\n    { name: 'action', description: 'set | rm | group-add | group-rm | member-add | member-rm | anonymous | bind | entry-add | entry-close | publish | unpublish', required: true },\n    { name: 'target', description: `set / rm: ${SUBJECT_HELP}; group-*, member-*, entry-add: group id; anonymous: on | off; bind, publish, unpublish: ${PATH_HELP}; entry-close: entry id`, required: false },\n    { name: 'arg', description: `set / rm: ${PATH_HELP} (default /); member-*: members, comma-separated; bind: group id or none`, required: false },\n  ],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'allow', property: 'allow', description: 'set: capabilities, comma-separated (read, append, update, delete, structure, comment, export, manage, run)', type: 'string' },\n    { name: 'deny', property: 'deny', description: 'set: capabilities refused, comma-separated', type: 'string' },\n    { name: 'title', property: 'title', description: 'group-add: the group\\'s title', type: 'string' },\n    { name: 'description', property: 'description', description: 'group-add: what the group is for', type: 'string' },\n    { name: 'mode', property: 'mode', description: 'bind: union (default) or intersection with the triggerer\\'s permissions', type: 'string', enum: ['union', 'intersection'] },\n    { name: 'methods', property: 'methods', description: 'entry-add: ways in, comma-separated: guest, password, self_register, did_login', type: 'string' },\n    { name: 'expires-at', property: 'expires_at', description: 'entry-add: unix seconds', type: 'integer' },\n    { name: 'max-joins', property: 'max_joins', description: 'entry-add: how many may join at most', type: 'integer' },\n    { name: 'remove-members', property: 'remove_members', description: 'entry-close: those who joined through it leave the group too', type: 'boolean' },\n    { name: 'name', property: 'name', description: 'publish: the last segment of the link', type: 'string' },\n  ],\n  inputSchema: workspaceInput({\n    action: { type: 'string', enum: ['set', 'rm', 'group-add', 'group-rm', 'member-add', 'member-rm', 'anonymous', 'bind', 'entry-add', 'entry-close', 'publish', 'unpublish'] },\n    target: { type: 'string' }, arg: { type: 'string' }, allow: { type: 'string' }, deny: { type: 'string' }, title: { type: 'string' }, description: { type: 'string' },\n    mode: { type: 'string', enum: ['union', 'intersection'] }, methods: { type: 'string' }, expires_at: { type: 'integer' }, max_joins: { type: 'integer', minimum: 1 },\n    remove_members: { type: 'boolean' }, name: { type: 'string' },\n  }, ['action']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: WRITE_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: [\n    'buckyos aiws acl-edit group-add teachers --title 老师 --workspace ws_abc',\n    'buckyos aiws acl-edit member-add teachers group:staff,bob --workspace ws_abc',\n    'buckyos aiws acl-edit set @teachers /data/成绩 --allow read,update --workspace ws_abc',\n    'buckyos aiws acl-edit set @all /data/工资 --deny read --workspace ws_abc',\n    'buckyos aiws acl-edit anonymous on --workspace ws_abc',\n    'buckyos aiws acl-edit entry-add visitors --methods guest,password --workspace ws_abc',\n  ],\n  handler: async (ctx, input) => {\n    const workspace_id = requiredInputString(input, 'workspace_id')\n    const target = () => requiredInputString(input, 'target')\n    const arg = inputString(input, 'arg')\n    const entityId = async (path: string) => String((await aiws(ctx, 'doc.resolve', { workspace_id, ...( path.startsWith('/') || path.startsWith('~') ? { path } : { reference: { entity_id: path, mode: 'live' } }) })).entity_id)\n    switch (requiredInputString(input, 'action')) {\n      case 'set': return aiws(ctx, 'acl.set', { workspace_id, changes: [{ subject: target(), resource: arg ?? '/', allow: caps(inputString(input, 'allow')), deny: caps(inputString(input, 'deny')) }] })\n      case 'rm': return aiws(ctx, 'acl.set', { workspace_id, changes: [{ subject: target(), resource: arg ?? '/' }] })\n      case 'group-add': return aiws(ctx, 'acl.set_group', { workspace_id, group_id: target(), ...given(input, { title: 'title', description: 'description' }) })\n      case 'group-rm': return aiws(ctx, 'acl.delete_group', { workspace_id, group_id: target() })\n      case 'member-add': return aiws(ctx, 'acl.members', { workspace_id, group_id: target(), add: ids(arg ?? '') })\n      case 'member-rm': return aiws(ctx, 'acl.members', { workspace_id, group_id: target(), remove: ids(arg ?? '') })\n      case 'anonymous': {\n        const on = target()\n        if (on !== 'on' && on !== 'off') throw new UsageError('AIWS_USAGE', 'anonymous on | off')\n        return aiws(ctx, 'acl.set_anonymous', { workspace_id, enabled: on === 'on' })\n      }\n      case 'bind': return aiws(ctx, 'acl.bind_macro', { workspace_id, wish: target(), group_id: !arg || arg === 'none' ? null : arg, ...given(input, { mode: 'mode' }) })\n      case 'entry-add': {\n        const methods = Object.fromEntries(ids(requiredInputString(input, 'methods')).map((m) => [m, true]))\n        return aiws(ctx, 'ws.create_entry', { workspace_id, group_id: target(), methods, ...given(input, { expires_at: 'expires_at', max_joins: 'max_joins' }) })\n      }\n      case 'entry-close': return aiws(ctx, 'ws.close_entry', { workspace_id, entry_id: target(), ...given(input, { remove_members: 'remove_members' }) })\n      case 'publish': return aiws(ctx, 'ws.publish', { workspace_id, entity_id: await entityId(target()), ...given(input, { name: 'name' }) })\n      case 'unpublish': return aiws(ctx, 'ws.unpublish', { workspace_id, entity_id: await entityId(target()) })\n      default: throw new UsageError('AIWS_USAGE', 'acl-edit: set, rm, group-add, group-rm, member-add, member-rm, anonymous, bind, entry-add, entry-close, publish or unpublish')\n    }\n  },\n}\n\nconst statCommand: CommandDefinition = {\n  verb: 'stat',\n  summary: 'What an entity is: path, name, title, type, schema, parent, versions, body state and size, children, your capabilities and the Commit operations its type takes',\n  positionals: [{ name: 'path', description: PATH_HELP, required: true }],\n  options: [WORKSPACE_OPTION],\n  inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 } }, ['path']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws stat /data/销售 --workspace ws_abc'],\n  handler: (ctx, input) => aiws(ctx, 'doc.read', { workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'path')), as: 'meta' }),\n}\n\n/** Pages of a body followed at most this far (32 KiB each by default). */\nconst CAT_MAX_PAGES = 512\n\nconst catCommand: CommandDefinition = {\n  verb: 'cat',\n  summary: 'The plain-text body of an entity (rich text as Markdown, a table as CSV, …), whole: the pages are followed unless --max-bytes or --cursor asks for one page',\n  description: 'With --output text only the text is printed. A table body is CSV of display values (select labels, reference paths); one part (a record, a block) is read with --selector.',\n  positionals: [{ name: 'path', description: PATH_HELP, required: true }],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'selector', property: 'selector', description: 'Only this part, selector JSON, e.g. {\"kind\":\"richtext_block\",\"block_id\":\"b3\"}', type: 'string' },\n    { name: 'max-bytes', property: 'max_bytes', description: 'One page of at most this many bytes (64…262144)', type: 'integer' },\n    CURSOR_OPTION,\n  ],\n  inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, selector: { type: 'string' }, max_bytes: { type: 'integer', minimum: 64 }, cursor: { type: 'string' } }, ['path']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws cat /docs/周报 --workspace ws_abc --output text', 'buckyos aiws cat /data/销售 --workspace ws_abc --max-bytes 4096'],\n  handler: async (ctx, input) => {\n    const selector = inputString(input, 'selector')\n    const request = {\n      workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'path')), as: 'body',\n      ...(selector ? { selector: jsonArg(selector, '--selector') } : {}), ...given(input, { max_bytes: 'max_bytes' }),\n    }\n    let page = await aiws(ctx, 'doc.read', { ...request, ...given(input, { cursor: 'cursor' }) })\n    if (input.max_bytes !== undefined || inputString(input, 'cursor')) return page\n    let text = String(page.text ?? '')\n    for (let n = 1; page.complete === false && typeof page.next_cursor === 'string' && n < CAT_MAX_PAGES; n++) {\n      page = await aiws(ctx, 'doc.read', { ...request, cursor: page.next_cursor })\n      text += String(page.text ?? '')\n    }\n    const { parts: _parts, ...last } = page\n    return { ...last, text }\n  },\n}\n\nconst resolveCommand: CommandDefinition = {\n  verb: 'resolve',\n  summary: 'A path (or entity id) as a reference: entity id, canonical reference, path and name',\n  positionals: [{ name: 'path', description: PATH_HELP, required: true }],\n  options: [WORKSPACE_OPTION],\n  inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 } }, ['path']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws resolve /data/销售 --workspace ws_abc'],\n  handler: (ctx, input) => {\n    const target = aiwsTarget(requiredInputString(input, 'path'))\n    return aiws(ctx, 'doc.resolve', { workspace_id: requiredInputString(input, 'workspace_id'), ...('path' in target ? target : { reference: { entity_id: target.entity_id, mode: 'live' } }) })\n  },\n}\n\n/** `--table a=/data/销售,b=orders`: aliases of the tables a query reads (a path may hold commas; a pair starts at\n * `<alias>=`). */\nfunction tableAliases(text: string): Record<string, string> {\n  const out: Record<string, string> = {}\n  for (const pair of text.split(/,(?=\\s*[A-Za-z_][A-Za-z0-9_]*=)/)) {\n    const m = /^\\s*([A-Za-z_][A-Za-z0-9_]*)=(.+?)\\s*$/.exec(pair)\n    if (!m) throw new UsageError('AIWS_USAGE', `--table ${pair}: <alias>=<path or entity id>`)\n    out[m[1]] = m[2]\n  }\n  return out\n}\n\nconst sqlCommand: CommandDefinition = {\n  verb: 'sql',\n  summary: 'One SQL SELECT over the tables of a workspace: a table is named by its path in double quotes (FROM \"/data/销售\"), \"~<entity_id>\", or an alias of --table',\n  description: 'Columns: _id (record id), _rev, _body (path of the record body), _record (the record as doc.read gives it, JSON), and per field \"<name>\" (display value: select label, multi-select JSON array of labels, reference path, decimal / currency amount as a number, boolean 1/0) and \"<name>#raw\" (stored value: option ids, exact decimal, reference / currency JSON); currency also \"<name>#currency\". SELECT only (WITH, subqueries and window functions included); at most --max-rows rows (truncated tells), 4 MiB and 2 s. URL tables have no local rows (NOT_MATERIALIZED).',\n  positionals: [{ name: 'sql', description: 'The SELECT statement', required: true }],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'table', property: 'table', description: 'Aliases: alias=<path or entity id>[,alias=…]; only these tables are visible then', type: 'string' },\n    { name: 'params', property: 'params', description: 'Positional parameters (?) as a JSON array', type: 'string' },\n    { name: 'max-rows', property: 'max_rows', description: 'Rows at most (≤ 5000, default 1000)', type: 'integer' },\n  ],\n  inputSchema: workspaceInput({ sql: { type: 'string', minLength: 1 }, table: { type: 'string' }, params: { type: 'string' }, max_rows: { type: 'integer', minimum: 1 } }, ['sql']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: READ_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: [\n    'buckyos aiws sql \\'SELECT \"客户\", SUM(\"金额\") AS total FROM \"/data/销售\" GROUP BY \"客户\" ORDER BY total DESC LIMIT 10\\' --workspace ws_abc',\n    'buckyos aiws sql \\'SELECT \"_id\", \"客户\", \"金额\" FROM t WHERE \"状态\" = ? LIMIT 20\\' --table t=/data/销售 --params \\'[\"已完成\"]\\' --workspace ws_abc',\n  ],\n  handler: (ctx, input) => {\n    const table = inputString(input, 'table')\n    const params = inputString(input, 'params')\n    const values = params ? jsonArg(params, '--params') : undefined\n    if (values !== undefined && !Array.isArray(values)) throw new UsageError('AIWS_USAGE', '--params is a JSON array')\n    return aiws(ctx, 'doc.query', {\n      workspace_id: requiredInputString(input, 'workspace_id'), sql: requiredInputString(input, 'sql'),\n      ...(table ? { tables: tableAliases(table) } : {}), ...(values ? { params: values } : {}), ...given(input, { max_rows: 'max_rows' }),\n    })\n  },\n}\n\n// ---- writing: the operations of buckyos-websdk src/aiws_write.ts, committed as one Commit each (an idempotency key, and\n// on an unknown result doc.get_submission, then the same key again). Field names, option labels and `expect` come from\n// what is read just before.\n\ntype TableRead = Parameters<typeof tableInsert>[0]\ntype RichTextRead = Parameters<typeof textReplaceBlock>[0]\ntype EntityRead = Parameters<typeof rename>[0]\n\n/** The service as the SDK's write helpers take it: a business failure is an `AiwsFailure`, never an unknown result. */\nfunction writeTransport(ctx: CommandContext) {\n  return {\n    call: async <T,>(method: string, params: Record<string, unknown>): Promise<T> => {\n      const result = expectObject(await callService<unknown>(ctx, SERVICE, method, params), method)\n      if (result.ok === false) {\n        const error = expectObject(result.error, `${method}.error`)\n        throw new AiwsFailure({ code: String(error.code ?? 'AIWS_ERROR'), retryable: Boolean(error.retryable), detail: String(error.detail ?? error.code ?? ''), sub_code: typeof error.sub_code === 'string' ? error.sub_code : undefined, data: error.data })\n      }\n      return result as T\n    },\n  }\n}\n\n/** A refusal (of the service, or of a helper: an unknown field, a block not read) as the CLI's error, its code first. */\nasync function writing<T>(work: () => Promise<T>): Promise<T> {\n  try {\n    return await work()\n  } catch (error) {\n    if (error instanceof AiwsFailure) throw new ToolError(error.code, error.message, undefined, false, { ...(error.subCode ? { sub_code: error.subCode } : {}), ...(error.data !== undefined ? { data: error.data } : {}) })\n    throw error\n  }\n}\n\nasync function commit(ctx: CommandContext, ws: string, ops: Record<string, unknown>[], message: string): Promise<Record<string, unknown>> {\n  const result = await commitOps(writeTransport(ctx), ws, ops as never, { message, ...(ctx.idempotencyKey ? { idempotencyKey: ctx.idempotencyKey } : {}) })\n  return { ok: true, status: result.status, commit_id: result.commit_id, seq: result.seq }\n}\n\n/** The envelope of an entity (ids and revs) without its content. */\nfunction envelopeOf(ctx: CommandContext, ws: string, target: string): Promise<Record<string, unknown>> {\n  return aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target), selector: { kind: 'doc_key', key: 'title' } })\n}\n\nconst ids = (text: string) => text.split(',').map((s) => s.trim()).filter(Boolean)\n\nasync function markdownInput(input: Record<string, unknown>): Promise<string> {\n  const text = typeof input.text === 'string' ? input.text : undefined\n  const file = inputString(input, 'file')\n  if ((text !== undefined) === (file !== undefined)) throw new UsageError('AIWS_USAGE', 'pass --file <md> or --text <markdown>')\n  return file ? await getHost().readTextFile(file) : text!\n}\n\nconst tableCommand: CommandDefinition = {\n  verb: 'table',\n  summary: 'Write a table: `add <table> --values` (records), `set <table> <record_id> --values` (cells), `rm <table> <record_id>[,…]`, `field-add <table> --name --type`, `option-add <table> <field> <label>`',\n  description: '--values is JSON keyed by field name with display values (a select takes its label, a multi-select labels, a reference an entity id; null clears a cell on set); add takes an object or an array of them, \"_id\" naming a record id. Each change is expected at the version just read: a concurrent change of the same cell is a REVISION_CONFLICT (read again). field-add --type: text, number, decimal, boolean, date, datetime, select, multi_select, object_ref, currency, json; --options gives a select its labels; --default is what new records get when they do not give the field (a display value, like --values: a select takes its label; not on object_ref).',\n  positionals: [\n    { name: 'action', description: 'add | set | rm | field-add | option-add', required: true },\n    { name: 'table', description: `The table: ${PATH_HELP}`, required: true },\n    { name: 'target', description: 'set: record id; rm: record ids, comma-separated; option-add: field name', required: false },\n    { name: 'label', description: 'option-add: the new option label', required: false },\n  ],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'values', property: 'values', description: 'add / set: JSON keyed by field name', type: 'string' },\n    { name: 'name', property: 'name', description: 'field-add: the field name', type: 'string' },\n    { name: 'type', property: 'type', description: 'field-add: the field type', type: 'string', enum: ['text', 'number', 'decimal', 'boolean', 'date', 'datetime', 'select', 'multi_select', 'object_ref', 'currency', 'json'] },\n    { name: 'options', property: 'options', description: 'field-add: option labels of a select, a JSON array or comma-separated', type: 'string' },\n    { name: 'default', property: 'default', description: 'field-add: the value new records get when they do not give the field (display form)', type: 'string' },\n  ],\n  inputSchema: workspaceInput({\n    action: { type: 'string', enum: ['add', 'set', 'rm', 'field-add', 'option-add'] }, table: { type: 'string', minLength: 1 }, target: { type: 'string' }, label: { type: 'string' },\n    values: { type: 'string' }, name: { type: 'string' }, type: { type: 'string' }, options: { type: 'string' }, default: { type: 'string' },\n  }, ['action', 'table']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: WRITE_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: [\n    'buckyos aiws table add /data/销售 --values \\'{\"客户\":\"ACME\",\"金额\":\"1200.50\",\"状态\":\"进行中\"}\\' --workspace ws_abc',\n    'buckyos aiws table set /data/销售 r123 --values \\'{\"状态\":\"已完成\"}\\' --workspace ws_abc',\n    'buckyos aiws table rm /data/销售 r123,r124 --workspace ws_abc',\n    'buckyos aiws table field-add /data/销售 --name 负责人 --type text --workspace ws_abc',\n    'buckyos aiws table field-add /data/销售 --name 阶段 --type select --options 线索,成交 --default 线索 --workspace ws_abc',\n    'buckyos aiws table option-add /data/销售 状态 已取消 --workspace ws_abc',\n  ],\n  handler: (ctx, input) => writing(async () => {\n    const ws = requiredInputString(input, 'workspace_id')\n    const action = requiredInputString(input, 'action')\n    const tablePath = requiredInputString(input, 'table')\n    const values = () => {\n      const v = jsonArg(requiredInputString(input, 'values'), '--values')\n      if (!v || typeof v !== 'object') throw new UsageError('AIWS_USAGE', '--values is a JSON object keyed by field name')\n      return v as Record<string, unknown> | Record<string, unknown>[]\n    }\n    if (action === 'rm') {\n      const records = ids(requiredInputString(input, 'target'))\n      const reads = await Promise.all(records.map((record_id) => aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(tablePath), selector: { kind: 'table_record', record_id } })))\n      const table = String(reads[0].entity_id)\n      return { ...await commit(ctx, ws, tableDelete(table, records, reads as never), `delete ${records.length} record(s)`), table, removed: records }\n    }\n    const table = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(tablePath) }) as unknown as TableRead\n    switch (action) {\n      case 'add': {\n        const rows = values()\n        const ops = tableInsert(table, Array.isArray(rows) ? rows : [rows])\n        const record_ids = ((ops[0]?.records ?? []) as { record_id: string }[]).map((r) => r.record_id)\n        return { ...await commit(ctx, ws, ops, `add ${record_ids.length} record(s)`), table: table.entity_id, record_ids }\n      }\n      case 'set': {\n        const record_id = requiredInputString(input, 'target')\n        const v = values()\n        if (Array.isArray(v)) throw new UsageError('AIWS_USAGE', 'set takes one --values object')\n        const read = await aiws(ctx, 'doc.read', { workspace_id: ws, entity_id: table.entity_id, selector: { kind: 'table_record', record_id } })\n        const ops = tableSet(table, record_id, v, read as never)\n        if (ops.length === 0) return { ok: true, status: 'unchanged', table: table.entity_id, record_id }\n        return { ...await commit(ctx, ws, ops, `update record ${record_id}`), table: table.entity_id, record_id }\n      }\n      case 'field-add': {\n        const options = inputString(input, 'options')\n        const labels = options === undefined ? undefined : options.startsWith('[') ? jsonArg(options, '--options') as string[] : ids(options)\n        const fallback = inputString(input, 'default')\n        const op = fieldAdd(table, { name: requiredInputString(input, 'name'), type: requiredInputString(input, 'type'), ...(labels ? { options: labels } : {}), ...(fallback !== undefined ? { default: fallback } : {}) })\n        const field = op.field as { field_id: string; options?: unknown[] }\n        return { ...await commit(ctx, ws, [op], `add field ${requiredInputString(input, 'name')}`), table: table.entity_id, field_id: field.field_id, ...(field.options ? { options: field.options } : {}) }\n      }\n      case 'option-add': {\n        const op = optionAdd(table, requiredInputString(input, 'target'), requiredInputString(input, 'label'))\n        return { ...await commit(ctx, ws, [op], `add option ${requiredInputString(input, 'label')}`), table: table.entity_id, field_id: op.field_id, option: op.option }\n      }\n      default:\n        throw new UsageError('AIWS_USAGE', `table: add, set, rm, field-add or option-add, not ${action}`)\n    }\n  }),\n}\n\nconst textCommand: CommandDefinition = {\n  verb: 'text',\n  summary: 'Write a rich text by blocks from Markdown: `append <doc> --file <md>`, `replace <doc> <block_id> --file <md>`, `rm <doc> <block_id>[,…]`',\n  description: 'Markdown: headings, paragraphs, bullet / ordered / task lists, fenced code, quotes, rules, pipe tables, inline code, strong, emphasis, strike and links ([label](entity:<id>) links an entity). Block ids are in the rich text as `doc.read` answers it (content.blocks) and in the selectors of `grep` hits; a replaced or removed block is expected at the version just read (REVISION_CONFLICT when it changed meanwhile). replace keeps the block id for the first block of the Markdown and inserts the rest after it.',\n  positionals: [\n    { name: 'action', description: 'append | replace | rm', required: true },\n    { name: 'doc', description: `The rich text: ${PATH_HELP}`, required: true },\n    { name: 'block', description: 'replace: block id; rm: block ids, comma-separated', required: false },\n  ],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'file', property: 'file', description: 'append / replace: a local Markdown file', type: 'string' },\n    { name: 'text', property: 'text', description: 'append / replace: the Markdown itself', type: 'string' },\n  ],\n  inputSchema: workspaceInput({ action: { type: 'string', enum: ['append', 'replace', 'rm'] }, doc: { type: 'string', minLength: 1 }, block: { type: 'string' }, file: { type: 'string' }, text: { type: 'string' } }, ['action', 'doc']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: WRITE_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: [\n    'buckyos aiws text append /docs/周报 --file notes.md --workspace ws_abc',\n    'buckyos aiws text replace /docs/周报 b12 --text \"## 下周计划\" --workspace ws_abc',\n    'buckyos aiws text rm /docs/周报 b12,b13 --workspace ws_abc',\n  ],\n  handler: (ctx, input) => writing(async () => {\n    const ws = requiredInputString(input, 'workspace_id')\n    const action = requiredInputString(input, 'action')\n    const target = requiredInputString(input, 'doc')\n    if (action === 'append') {\n      const markdown = await markdownInput(input)\n      const doc = String((await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target), as: 'meta' })).entity_id)\n      const ops = textAppend(doc, markdown)\n      const blocks = (ops[0].blocks as { attrs: { block_id: string } }[]).map((b) => b.attrs.block_id)\n      return { ...await commit(ctx, ws, ops, 'append text'), doc, blocks }\n    }\n    if (action !== 'replace' && action !== 'rm') throw new UsageError('AIWS_USAGE', `text: append, replace or rm, not ${action}`)\n    const markdown = action === 'replace' ? await markdownInput(input) : ''\n    const doc = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target) }) as unknown as RichTextRead\n    if (action === 'rm') {\n      const blocks = ids(requiredInputString(input, 'block'))\n      return { ...await commit(ctx, ws, textDeleteBlocks(doc, blocks), `delete ${blocks.length} block(s)`), doc: doc.entity_id, removed: blocks }\n    }\n    const block = requiredInputString(input, 'block')\n    const ops = textReplaceBlock(doc, block, markdown)\n    const added = ops.length > 1 ? ((ops[1] as Record<string, unknown>).blocks as { attrs: { block_id: string } }[]).map((b) => b.attrs.block_id) : []\n    return { ...await commit(ctx, ws, ops, `replace block ${block}`), doc: doc.entity_id, blocks: [block, ...added] }\n  }),\n}\n\nconst mvCommand: CommandDefinition = {\n  verb: 'mv',\n  summary: 'Move an entity under another parent, after its last child (a following name moves aside if taken there)',\n  positionals: [{ name: 'path', description: PATH_HELP, required: true }, { name: 'parent', description: `The new parent: ${PATH_HELP}`, required: true }],\n  options: [WORKSPACE_OPTION],\n  inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, parent: { type: 'string', minLength: 1 } }, ['path', 'parent']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: WRITE_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws mv /data/草稿 /archive --workspace ws_abc'],\n  handler: (ctx, input) => writing(async () => {\n    const ws = requiredInputString(input, 'workspace_id')\n    const entity = await envelopeOf(ctx, ws, requiredInputString(input, 'path'))\n    const parent = String((await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(requiredInputString(input, 'parent')), as: 'meta' })).entity_id)\n    // the new place: after the last child the caller sees there\n    let last: string | undefined\n    let cursor: string | undefined\n    for (let page = 0; page < 100; page++) {\n      const listed = await aiws(ctx, 'doc.list', { workspace_id: ws, at: parent, limit: 1000, ...(cursor ? { cursor } : {}) })\n      const items = (Array.isArray(listed.items) ? listed.items : []) as { entity_id: string }[]\n      last = items.map((i) => i.entity_id).filter((id) => id !== entity.entity_id).at(-1) ?? last\n      if (typeof listed.next_cursor !== 'string' || items.length === 0) break\n      cursor = listed.next_cursor\n    }\n    const after = last ? (await envelopeOf(ctx, ws, last)).order_key : undefined\n    const op = move(entity as unknown as EntityRead, parent, typeof after === 'string' ? after : null)\n    return { ...await commit(ctx, ws, [op], `move ${entity.entity_id}`), entity_id: entity.entity_id, parent }\n  }),\n}\n\nconst renameCommand: CommandDefinition = {\n  verb: 'rename',\n  summary: 'Give an entity a name of its own (its path segment), or --auto to let it follow its title again',\n  positionals: [{ name: 'path', description: PATH_HELP, required: true }, { name: 'name', description: 'The new name (1–128 characters, no /, not starting with ~)', required: false }],\n  options: [WORKSPACE_OPTION, { name: 'auto', property: 'auto', description: 'Name it after its title again (or a counter)', type: 'boolean' }],\n  inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, name: { type: 'string' }, auto: { type: 'boolean' } }, ['path']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: WRITE_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws rename /data/销售 销售-2026 --workspace ws_abc', 'buckyos aiws rename ~sales --auto --workspace ws_abc'],\n  handler: (ctx, input) => writing(async () => {\n    const ws = requiredInputString(input, 'workspace_id')\n    const name = inputString(input, 'name')\n    if ((name === undefined) === (input.auto !== true)) throw new UsageError('AIWS_USAGE', 'rename: pass a new name or --auto')\n    const entity = await envelopeOf(ctx, ws, requiredInputString(input, 'path'))\n    return { ...await commit(ctx, ws, [rename(entity as unknown as EntityRead, name ?? null)], `rename ${entity.entity_id}`), entity_id: entity.entity_id, ...(name ? { name } : {}) }\n  }),\n}\n\nconst setPropCommand: CommandDefinition = {\n  verb: 'set-prop',\n  summary: 'Set properties of a Block or a container: `config`, `bindings` or `on`, as JSON { <name>: value | null } (null removes one), each expected at the version just read',\n  positionals: [\n    { name: 'path', description: `The Block or container: ${PATH_HELP}`, required: true },\n    { name: 'key', description: 'config | bindings | on', required: true },\n    { name: 'props', description: 'JSON object { <name>: value | null }', required: true },\n  ],\n  options: [WORKSPACE_OPTION],\n  inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, key: { type: 'string', enum: ['config', 'bindings', 'on'] }, props: { type: 'string', minLength: 1 } }, ['path', 'key', 'props']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: WRITE_ACCESS,\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws set-prop /surfaces/看板/kpi config \\'{\"label\":\"本月销售\"}\\' --workspace ws_abc'],\n  handler: (ctx, input) => writing(async () => {\n    const ws = requiredInputString(input, 'workspace_id')\n    const key = requiredInputString(input, 'key')\n    if (key !== 'config' && key !== 'bindings' && key !== 'on') throw new UsageError('AIWS_USAGE', 'set-prop: the key is config, bindings or on')\n    const props = jsonArg(requiredInputString(input, 'props'), 'props')\n    if (!props || typeof props !== 'object' || Array.isArray(props)) throw new UsageError('AIWS_USAGE', 'props is a JSON object { <name>: value | null }')\n    const entity = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(requiredInputString(input, 'path')) })\n    return { ...await commit(ctx, ws, [setProps(entity as unknown as EntityRead, key, props as Record<string, unknown>)], `set ${key} of ${entity.entity_id}`), entity_id: entity.entity_id }\n  }),\n}\n\nconst infoCommand: CommandDefinition = {\n  verb: 'info',\n  summary: 'Workspace info: versions, capabilities of the caller, usage, where wish runs execute by default',\n  options: [WORKSPACE_OPTION],\n  inputSchema: workspaceInput({}),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'read' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws info --workspace ws_abc'],\n  handler: (ctx, input) => aiws(ctx, 'ws.get_info', { workspace_id: requiredInputString(input, 'workspace_id') }),\n}\n\nconst runGetCommand: CommandDefinition = {\n  verb: 'run-get',\n  summary: 'A wish run: state, progress, execution context, the brief an executor starts from, what it wrote (applied) and the record it added to the wish\\'s history (record)',\n  options: [WORKSPACE_OPTION, RUN_OPTION],\n  inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 } }, ['run_id']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'read' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-get --workspace ws_abc --run run_xyz'],\n  handler: (ctx, input) => aiws(ctx, 'proc.get', { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id') }),\n}\n\nconst runClaimCommand: CommandDefinition = {\n  verb: 'run-claim',\n  summary: 'Take a run as its executor: starts an attempt, answers the attempt number, a run token and the lease',\n  options: [WORKSPACE_OPTION, RUN_OPTION, { name: 'claim-token', property: 'claim_token', description: 'The claim token the run was dispatched with (ct_…)', type: 'string', required: true, secret: true }],\n  inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, claim_token: { type: 'string', minLength: 1 } }, ['run_id', 'claim_token']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-claim --workspace ws_abc --run run_xyz --claim-token ct_…'],\n  handler: (ctx, input) => aiws(ctx, 'proc.claim', {\n    workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), claim_token: requiredInputString(input, 'claim_token'),\n    executor: { kind: 'agent', principal: ctx.principal.id },\n  }),\n}\n\nconst runHeartbeatCommand: CommandDefinition = {\n  verb: 'run-heartbeat',\n  summary: 'Keep the lease of a claimed run alive (every minute while working); optionally report progress',\n  options: [WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION, { name: 'phase', property: 'phase', description: 'A short progress phase, e.g. \"reading inputs\"', type: 'string' }],\n  inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, phase: { type: 'string' } }, ['run_id', 'attempt']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-heartbeat --workspace ws_abc --run run_xyz --attempt 1 --phase \"reading inputs\"'],\n  handler: (ctx, input) => {\n    const phase = inputString(input, 'phase')\n    return aiws(ctx, 'proc.heartbeat', { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt, ...(phase ? { progress: { phase } } : {}) })\n  },\n}\n\nconst runFilesCommand: CommandDefinition = {\n  verb: 'run-files',\n  summary: 'Write the stage of a claimed run into a directory: the snapshot (context/), request.json, the Renderer catalog, the program host (lib/, with the stage budget and manifest in lib/stage.json) and, when there is one, program/main.js',\n  description: 'Run the macro there with `run-exec` (or `run-program`, which also hands it in): it reads program/main.js and writes output/.aiws/results.json, exactly as every executor runs it.',\n  options: [WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION, { name: 'dir', property: 'dir', description: 'Directory to write into (created)', type: 'string', required: true }],\n  inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, dir: { type: 'string', minLength: 1 } }, ['run_id', 'attempt', 'dir']),\n  outputSchema: { type: 'object', properties: { dir: { type: 'string' }, files: { type: 'array', items: { type: 'string' } } }, required: ['dir', 'files'], additionalProperties: true },\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'read' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-files --workspace ws_abc --run run_xyz --attempt 1 --dir work'],\n  handler: async (ctx, input) => {\n    const result = await aiws(ctx, 'proc.files', { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt })\n    const dir = requiredInputString(input, 'dir')\n    const host = getHost()\n    const written: string[] = []\n    for (const [path, file] of Object.entries(expectObject(result.files, 'proc.files.files'))) {\n      const f = expectObject(file, path)\n      if (typeof f.text !== 'string' && typeof f.base64 !== 'string') continue\n      const target = `${dir}/${path}`\n      await host.mkdir(target.slice(0, target.lastIndexOf('/')), { recursive: true })\n      if (typeof f.text === 'string') await host.writeTextFile(target, f.text)\n      else await host.writeFile(target, Uint8Array.from(atob(f.base64 as string), (c) => c.charCodeAt(0)))\n      written.push(path)\n    }\n    await host.mkdir(`${dir}/output`, { recursive: true })\n    await host.mkdir(`${dir}/program`, { recursive: true })\n    await host.mkdir(`${dir}/lib`, { recursive: true })\n    await host.writeTextFile(`${dir}/lib/stage.json`, JSON.stringify(result.stage ?? {}))\n    return { dir, files: written }\n  },\n}\n\nconst runToolCommand: CommandDefinition = {\n  verb: 'run-tool',\n  summary: 'Call one stage tool of a claimed run (ws_profile, ws_read, ws_query, submit_analysis, check_results, finish, …): the service answers as it answers the model',\n  options: [WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION, { name: 'name', property: 'name', description: 'Tool name (the claim answered the list, with their argument schemas)', type: 'string', required: true }, { name: 'args', property: 'args', description: 'Arguments JSON', type: 'string' }, { name: 'args-file', property: 'args_file', description: 'Path of a JSON file holding the arguments', type: 'string' }],\n  inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, name: { type: 'string', minLength: 1 }, args: { type: 'string' }, args_file: { type: 'string' } }, ['run_id', 'attempt', 'name']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-tool --workspace ws_abc --run run_xyz --attempt 1 --name ws_profile --args \\'{\"target\":\"@B1\"}\\'', 'buckyos aiws run-tool --workspace ws_abc --run run_xyz --attempt 1 --name finish --args \\'{\"summary\":\"done\"}\\''],\n  handler: async (ctx, input) => {\n    const args = inputString(input, 'args') || inputString(input, 'args_file') ? await jsonInput(input, 'args', 'args_file', 'arguments') : {}\n    return aiws(ctx, 'proc.tool', { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt, name: requiredInputString(input, 'name'), args })\n  },\n}\n\n// ---- running a wish macro the way every executor runs it (AI Native phase 1, section 2.6): a Deno child that reads only\n// the stage directory, writes only its output/, reaches only the Zone's host, with an empty environment and no token; its\n// bridge calls (`aiws.sql`, `aiws.ai.complete`, `aiws.llm.map`, `aiws.zone.fetch`) come back over stdio and are answered\n// here with the stage's lib/host.js: SQL by the service, AI with this session's own AICC, Zone resources with this session.\n\nconst BRIDGE_PREFIX = '\\x1eaiws '\nconst REFUSALS: Record<string, string> = {\n  quota_exhausted: 'AI_QUOTA_EXHAUSTED', quota_budget_exceeded: 'AI_QUOTA_BUDGET_EXCEEDED', resource_not_permitted: 'AI_RESOURCE_NOT_PERMITTED',\n  attribution_unavailable: 'AI_ATTRIBUTION_UNAVAILABLE', credentials: 'AI_UNAVAILABLE',\n}\n\ninterface MacroRun { source: string; results: unknown; log: string; code: number }\n\n/** An AICC refusal as the run's sub-code (AI_QUOTA_EXHAUSTED…), anything else as it came. */\nfunction refusalOf(error: unknown): unknown {\n  if (error instanceof LLMComputeException && error.error.kind === 'provider' && typeof error.error.failure === 'object' && 'refused' in error.error.failure) {\n    const e = new Error(error.message) as Error & { code?: string }\n    e.code = REFUSALS[error.error.failure.refused.code] ?? 'AI_QUOTA_EXHAUSTED'\n    return e\n  }\n  return error\n}\n\n/** One AICC call of a macro's generated picture or clip, with this session; a refusal carries the run's sub-code. */\nfunction sessionAicc(ctx: CommandContext) {\n  return async (method: string, params: Record<string, unknown>) => {\n    try {\n      return await ctx.clients.call('aicc', method, params, rpcOptions(ctx))\n    } catch (error) {\n      throw refusalOf(providerErrorFromRpc(`aicc ${method} failed`, error))\n    }\n  }\n}\n\n/** One inference with this session's AICC; a refusal carries the run's sub-code. */\nfunction sessionInfer(ctx: CommandContext) {\n  const call = async (method: string, params: unknown) => {\n    try {\n      return await ctx.clients.call('aicc', method, params as Record<string, unknown>, rpcOptions(ctx))\n    } catch (error) {\n      throw providerErrorFromRpc(`aicc ${method} failed`, error)\n    }\n  }\n  const client = new AiccLlmClient({ chatCompletionsCreate: (r: unknown) => call('chat.completions.create', r), helperLlmChat: (r: unknown) => call('helper.llm_chat', r) } as never)\n  return async (req: { model: string; messages: { role: 'system' | 'user' | 'assistant'; text: string }[]; schema: unknown; max_tokens: number }) => {\n    try {\n      const r: { message: { content: { type: string; text?: string }[] }; usage?: { input_tokens?: number; output_tokens?: number }; extra?: unknown } = await client.infer({\n        messages: req.messages.map((m) => ({ role: m.role, content: [{ type: 'text' as const, text: m.text }] })), model_alias: req.model, fallbacks: [], temperature: 0,\n        max_completion_tokens: req.max_tokens, force_json: req.schema !== null, ...(req.schema !== null ? { json_schema: req.schema as never } : {}),\n        disable_capabilities: [], tool_specs: [], allow_tool_calls: false, signal: ctx.signal,\n      })\n      // AICC names the model its route ended at (`extra.model`): the run's record shows it\n      const model = (r.extra as { model?: unknown } | undefined)?.model\n      return {\n        text: r.message.content.map((c) => (c.type === 'text' ? c.text ?? '' : '')).join(''), tokens: r.usage?.output_tokens, input_tokens: r.usage?.input_tokens,\n        ...(typeof model === 'string' && model ? { model } : {}),\n      }\n    } catch (error) {\n      throw refusalOf(error)\n    }\n  }\n}\n\nasync function execMacro(ctx: CommandContext, input: Record<string, unknown>): Promise<MacroRun> {\n  const host = getHost()\n  // Subprocess cwd resolves directory aliases (e.g. /var -> /private/var on macOS).\n  // Use the same canonical path for the macro's read/write permission scopes.\n  const dir = await host.realPath(host.path.resolve(ctx.cwd, requiredInputString(input, 'dir')))\n  const ids = { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt }\n  const source = await host.readTextFile(`${dir}/program/main.js`)\n  let stage: { budget?: Record<string, unknown>; manifest?: unknown } = {}\n  try { stage = JSON.parse(await host.readTextFile(`${dir}/lib/stage.json`)) } catch { stage = {} }\n  const budget = stage.budget ?? {}\n  const manifest = stage.manifest && typeof stage.manifest === 'object' ? stage.manifest as { resources?: { timeout_secs?: number } } : null\n  const { createBridgeHost } = await import(new URL(`file://${dir}/lib/host.js`).href) as { createBridgeHost: (o: Record<string, unknown>) => { handle(op: string, req: unknown): Promise<unknown> } }\n  const origin = gatewayOrigin(ctx.connection.endpoint)\n  const zoneHost = new URL(origin).hostname\n  const bridge = createBridgeHost({\n    tool: async (name: string, args: unknown) => {\n      try {\n        return await aiws(ctx, 'proc.tool', { ...ids, name, args })\n      } catch (error) {\n        return { status: 'error', text: error instanceof Error ? error.message : String(error) }\n      }\n    },\n    infer: sessionInfer(ctx),\n    zoneFetch: async (url: string, init: { method: string; headers: Record<string, string>; body: string | null }) => {\n      const res = await fetch(url, { method: init.method, headers: { ...init.headers, Authorization: `Bearer ${await sessionToken(ctx)}` }, body: init.body ?? undefined, signal: ctx.signal })\n      const bytes = new Uint8Array(await res.arrayBuffer())\n      const headers: Record<string, string> = {}\n      res.headers.forEach((v, k) => { headers[k] = v })\n      try { return { status: res.status, headers, text: new TextDecoder('utf-8', { fatal: true }).decode(bytes) } } catch { return { status: res.status, headers, base64: btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join('')) } }\n    },\n    aicc: sessionAicc(ctx),\n    task: (id: string) => ctx.clients.call('task-manager', 'get_task', { task_id: id }, rpcOptions(ctx)),\n    importAsset: (objId: string) => aiws(ctx, 'asset.import_object', { workspace_id: ids.workspace_id, obj_id: objId }),\n    zoneHosts: [zoneHost], zoneOrigin: origin, budget, manifest,\n  })\n  await host.remove(`${dir}/output/.aiws/results.json`).catch(() => undefined)\n  await host.mkdir(`${dir}/output`, { recursive: true })\n  // under Deno the tool's own runtime runs the macro; the Node distribution uses the Deno on PATH\n  const child = host.spawn(host.kind === 'deno' ? host.runtimeExecutable : 'deno', [\n    'run', '--no-prompt', '--quiet', '--no-remote', `--allow-read=${dir}`, `--allow-write=${dir}/output`, `--allow-net=${zoneHost}`, 'lib/run.js', '--bridge',\n  ], { cwd: dir, env: { NO_COLOR: '1', DENO_NO_UPDATE_CHECK: '1', DENO_DIR: `${dir}/.deno` } })\n  const cap = Number(budget.program_timeout_secs) || 120\n  const limit = Math.min(cap, Number(manifest?.resources?.timeout_secs) || cap)\n  let timedOut = false\n  // the time the macro itself took: waits for generated pictures and clips have their own limit\n  const started = Date.now()\n  let media = 0\n  let mediaSince = 0\n  let mediaMs = 0\n  const timer = setInterval(() => {\n    if (Date.now() - started - mediaMs - (media ? Date.now() - mediaSince : 0) > limit * 1000) { timedOut = true; child.kill() }\n  }, 1000)\n  const out: string[] = []\n  const pending = new Set<Promise<void>>()\n  try {\n    for await (const line of child.lines()) {\n      if (!line.startsWith(BRIDGE_PREFIX)) { out.push(line); continue }\n      const msg = JSON.parse(line.slice(BRIDGE_PREFIX.length)) as { id: number; op: string; req: unknown }\n      // answered as they come: a macro that generates several pictures at once waits for the slowest, not the sum\n      const waiting = msg.op === 'ai.image' || msg.op === 'ai.video'\n      if (waiting && media++ === 0) mediaSince = Date.now()\n      const answer: Promise<void> = bridge.handle(msg.op, msg.req)\n        .then((body) => child.writeLine(JSON.stringify({ id: msg.id, body })))\n        .finally(() => { if (waiting && --media === 0) mediaMs += Date.now() - mediaSince; pending.delete(answer) })\n      pending.add(answer)\n    }\n    await Promise.allSettled([...pending])\n  } finally {\n    clearInterval(timer)\n    await child.closeInput()\n  }\n  const code = await child.status\n  const log = [...out, await child.stderr, ...(timedOut ? [`The macro timed out (${limit} s)`] : [])].filter(Boolean).join('\\n')\n  let results: unknown = null\n  try { results = JSON.parse(await host.readTextFile(`${dir}/output/.aiws/results.json`)) } catch { results = null }\n  if (timedOut) results = { error: `The macro timed out (${limit} s)` }\n  return { source, results, log, code }\n}\n\nconst RUN_EXEC_OPTIONS: OptionDefinition[] = [\n  WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION,\n  { name: 'dir', property: 'dir', description: 'The stage directory written by run-files (program/main.js, lib/, output/), under the current directory', type: 'string', required: true },\n]\nconst RUN_EXEC_INPUT = workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, dir: { type: 'string', minLength: 1 } }, ['run_id', 'attempt', 'dir'])\n\nconst runExecCommand: CommandDefinition = {\n  verb: 'run-exec',\n  summary: 'Run program/main.js of a stage directory as every executor runs a wish macro: reads only the directory, writes only output/, reaches only the Zone, its AI calls with your session; prints its outcome',\n  description: 'The macro gets no token and no environment. Use it to debug a macro; `run-program` runs it the same way and hands it in. API: the wish macro guide (src/frame/aiworkspace/aiws/README.md in buckyos).',\n  options: RUN_EXEC_OPTIONS,\n  inputSchema: RUN_EXEC_INPUT,\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-exec --workspace ws_abc --run run_xyz --attempt 1 --dir work'],\n  handler: async (ctx, input) => {\n    const run = await execMacro(ctx, input)\n    const r = (run.results ?? {}) as Record<string, unknown>\n    return { exit_code: run.code, error: r.error ?? null, error_code: r.error_code ?? null, ai: r.ai ?? null, declare: r.declare ?? null, log: run.log }\n  },\n}\n\nconst runProgramCommand: CommandDefinition = {\n  verb: 'run-program',\n  summary: 'Run the macro of a stage directory (as run-exec) and hand the run in: the source, its results, the files under output/ and its log; the service judges it against the contract',\n  description: 'While coding, the answer is what the model would read (previews, checks, manifest, problems); running a stored macro, a failure ends the run. Then `run-report --finished`.',\n  options: RUN_EXEC_OPTIONS,\n  inputSchema: RUN_EXEC_INPUT,\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-program --workspace ws_abc --run run_xyz --attempt 1 --dir work'],\n  handler: async (ctx, input) => {\n    const host = getHost()\n    const dir = host.path.resolve(ctx.cwd, requiredInputString(input, 'dir'))\n    const run = await execMacro(ctx, input)\n    const files: Record<string, unknown> = {}\n    const walk = async (rel: string) => {\n      for (const entry of await host.readDir(`${dir}/output${rel ? `/${rel}` : ''}`)) {\n        const name = rel ? `${rel}/${entry.name}` : entry.name\n        if (name === '.aiws' || name.startsWith('.aiws/')) continue\n        if (entry.isDirectory) await walk(name)\n        else {\n          const bytes = await host.readFile(`${dir}/output/${name}`)\n          let text: string | null = null\n          try { text = bytes.includes(0) ? null : new TextDecoder('utf-8', { fatal: true }).decode(bytes) } catch { text = null }\n          files[`output/${name}`] = text ?? { base64: btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join('')) }\n        }\n      }\n    }\n    await walk('')\n    return aiws(ctx, 'proc.program', { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt, source: run.source, results: run.results, log: run.log, files })\n  },\n}\n\nconst runStartCommand: CommandDefinition = {\n  verb: 'run-start',\n  summary: 'Start a wish run that you execute yourself (an analysis you work out in a conversation, coding, running): answers the run and its claim token; your AI resources pay',\n  description: 'Then `run-claim` with that token and work it like any run. An analysis is handed in with `run-tool --name submit_analysis` then `run-report --finished`, or `run-report --analysis-file`. Needs update on the wish.',\n  options: [WORKSPACE_OPTION, { name: 'wish', property: 'wish_id', description: 'The wish (its entity id)', type: 'string', required: true },\n    { name: 'stage', property: 'stage', description: 'analyze | code | run (default analyze)', type: 'string' }],\n  inputSchema: workspaceInput({ wish_id: { type: 'string', minLength: 1 }, stage: { type: 'string', enum: ['analyze', 'code', 'run'] } }, ['wish_id']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-start --workspace ws_abc --wish wish_q3 --stage analyze'],\n  handler: (ctx, input) => aiws(ctx, 'proc.start', {\n    workspace_id: requiredInputString(input, 'workspace_id'), program: 'wish.xllm@1', idempotency_key: ctx.idempotencyKey ?? `cli-${ctx.traceId}`,\n    params: { wish_id: requiredInputString(input, 'wish_id'), stage: inputString(input, 'stage') || 'analyze', execution: { mode: 'local' } },\n  }),\n}\n\nconst runReportCommand: CommandDefinition = {\n  verb: 'run-report',\n  summary: 'End a claimed run: --finished after the stage is done (submit_analysis or finish accepted, or the stored macro handed in), an analysis made elsewhere, or a failure — with what your model loop used',\n  description: 'The service then checks the stage and writes it at once: an analysis its task contract, coding only the macro, a run its results; each stage adds a record to the wish\\'s history, a failure too (and writes nothing else). Results always come from the macro (run-program). --model, --input-tokens, --output-tokens and --calls go into that record as they are: what the model turns of this stage used (leave them out when you called no model, as when you only ran the stored macro). A superseded attempt or a cancelled run gets RUN_REVOKED.',\n  options: [\n    WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION,\n    { name: 'finished', property: 'finished', description: 'The stage is done: the service writes what it produced', type: 'boolean' },\n    { name: 'analysis', property: 'analysis', description: 'Analysis JSON (analyze runs, wish.analysis.v3)', type: 'string' },\n    { name: 'analysis-file', property: 'analysis_file', description: 'Path of a JSON file holding the analysis', type: 'string' },\n    { name: 'summary', property: 'summary', description: 'One paragraph on what was done', type: 'string' },\n    { name: 'warning', property: 'warnings', description: 'A warning for the user (repeatable)', type: 'string' },\n    { name: 'error', property: 'error', description: 'Report a failure instead: its reason', type: 'string' },\n    { name: 'model', property: 'model', description: 'The model that answered your last model turn (the stage\\'s model when you cannot tell)', type: 'string' },\n    { name: 'input-tokens', property: 'input_tokens', description: 'Input tokens of all your model turns in this stage', type: 'integer' },\n    { name: 'output-tokens', property: 'output_tokens', description: 'Output tokens of all your model turns in this stage', type: 'integer' },\n    { name: 'calls', property: 'calls', description: 'How many model turns this stage took', type: 'integer' },\n  ],\n  inputSchema: workspaceInput({\n    run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, finished: { type: 'boolean' }, analysis: { type: 'string' }, analysis_file: { type: 'string' }, summary: { type: 'string' }, warnings: { type: 'string' }, error: { type: 'string' },\n    model: { type: 'string', minLength: 1 }, input_tokens: { type: 'integer', minimum: 0 }, output_tokens: { type: 'integer', minimum: 0 }, calls: { type: 'integer', minimum: 0 },\n  }, ['run_id', 'attempt']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: [\n    'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --finished',\n    'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --finished --model gpt-6-astra --input-tokens 12340 --output-tokens 1205 --calls 7',\n    'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --analysis-file out/analysis.json',\n    'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --error \"the input table is empty\"',\n  ],\n  handler: async (ctx, input) => {\n    const params: Record<string, unknown> = { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt }\n    const error = inputString(input, 'error')\n    if (error) {\n      params.error = { code: 'EXECUTOR_FAILED', detail: error }\n    } else if (input.finished === true) {\n      params.finished = true\n    } else {\n      params.analysis = await jsonInput(input, 'analysis', 'analysis_file', 'an analysis')\n    }\n    const summary = inputString(input, 'summary')\n    if (summary) params.summary = summary\n    const warning = inputString(input, 'warnings')\n    if (warning) params.warnings = [warning]\n    const usage: Record<string, unknown> = {}\n    const model = inputString(input, 'model')\n    if (model) usage.model = model\n    for (const key of ['input_tokens', 'output_tokens', 'calls']) if (typeof input[key] === 'number') usage[key] = input[key]\n    if (Object.keys(usage).length) params.usage = usage\n    return aiws(ctx, 'proc.report', params)\n  },\n}\n\nconst runRollbackCommand: CommandDefinition = {\n  verb: 'run-rollback',\n  summary: 'Roll a wish run back: what it wrote (its analysis, its macro or its results) returns to the stage\\'s previous version; only the run whose record is current for its stage',\n  description: 'Results the run updated return to what they were before it (a person\\'s edits it overwrote included), results it created go with their Blocks; a macro or an analysis returns to the one of the previous record. When what the run wrote was changed since, nothing is written: the answer is `status: needs_confirm` with what would be lost (`lost`, `hidden_lost`); run it again with --confirm to go ahead. Otherwise one Commit: `commit` and the `rollback` record added to the history. Another record than the current one: INVALID_OPERATION / NOT_CURRENT_RECORD. Needs update on the wish.',\n  options: [WORKSPACE_OPTION, RUN_OPTION, { name: 'confirm', property: 'confirm', description: 'Go ahead although the later changes listed by a first try are lost', type: 'boolean' }],\n  inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, confirm: { type: 'boolean' } }, ['run_id']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws run-rollback --workspace ws_abc --run run_xyz', 'buckyos aiws run-rollback --workspace ws_abc --run run_xyz --confirm'],\n  handler: (ctx, input) => aiws(ctx, 'proc.rollback', {\n    workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), ...(input.confirm === true ? { confirm: true } : {}),\n  }),\n}\n\n// Block-controls (a mind map…): the catalogue each control describes itself in, and its exchange formats\n// (脑图方案 §8.1). The service dispatches by control kind: `control.*` in buckyos/src/frame/aiworkspace/README.md.\nconst controlsCommand: CommandDefinition = {\n  verb: 'controls',\n  summary: 'Block-controls a canvas offers: `list` (kind, what it is, when to use it), `describe <kind>` (the full self-description to follow)',\n  positionals: [{ name: 'action', description: 'list | describe', required: true }, { name: 'kind', description: 'Control kind for describe, e.g. mindmap', required: false }],\n  options: [],\n  inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['list', 'describe'] }, kind: { type: 'string' } }, required: ['action'], additionalProperties: false },\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'read' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws controls list', 'buckyos aiws controls describe mindmap'],\n  handler: (ctx, input) => {\n    const action = requiredInputString(input, 'action')\n    if (action === 'list') return aiws(ctx, 'control.list', {})\n    if (action !== 'describe') throw new UsageError('AIWS_USAGE', 'controls: list or describe <kind>')\n    return aiws(ctx, 'control.describe', { kind: requiredInputString(input, 'kind') })\n  },\n}\n\n/** `markdown` / `opml` from an explicit option or the file name. */\nfunction exchangeFormat(explicit: string | undefined, file: string): string {\n  if (explicit) return explicit\n  return /\\.(opml|xml)$/i.test(file) ? 'opml' : 'markdown'\n}\n\nconst importCommand: CommandDefinition = {\n  verb: 'import',\n  summary: 'Create a Block-control from an exchange file: a mind map from a Markdown outline (nested list) or OPML',\n  positionals: [{ name: 'file', description: 'Local file (.md / .opml)', required: true }],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'parent', property: 'parent_id', description: 'Surface (or group) id to put the control on', type: 'string', required: true },\n    { name: 'kind', property: 'kind', description: 'Control kind (default mindmap)', type: 'string' },\n    { name: 'format', property: 'format', description: 'markdown | opml (default: by the file extension)', type: 'string', enum: ['markdown', 'opml'] },\n    { name: 'at', property: 'at', description: 'x,y on a free canvas: where the first root goes', type: 'string' },\n    { name: 'title', property: 'title', description: 'Title of the control (default: the single root, or the OPML title)', type: 'string' },\n  ],\n  inputSchema: workspaceInput({ file: { type: 'string', minLength: 1 }, parent_id: { type: 'string', minLength: 1 }, kind: { type: 'string' }, format: { type: 'string' }, at: { type: 'string' }, title: { type: 'string' } }, ['file', 'parent_id']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws import plan.md --workspace ws_abc --parent sf_main --at 100,80', 'buckyos aiws import ideas.opml --workspace ws_abc --parent sf_main'],\n  handler: async (ctx, input) => {\n    const file = requiredInputString(input, 'file')\n    const params: Record<string, unknown> = {\n      workspace_id: requiredInputString(input, 'workspace_id'), parent_id: requiredInputString(input, 'parent_id'),\n      kind: inputString(input, 'kind') ?? 'mindmap', format: exchangeFormat(inputString(input, 'format'), file), text: await getHost().readTextFile(file),\n    }\n    const at = inputString(input, 'at')\n    if (at) {\n      const [x, y] = at.split(',').map(Number)\n      if (!Number.isFinite(x) || !Number.isFinite(y)) throw new UsageError('AIWS_USAGE', '--at is x,y')\n      params.at = { x, y }\n    }\n    const title = inputString(input, 'title')\n    if (title) params.title = title\n    return aiws(ctx, 'control.import', params)\n  },\n}\n\nconst exportCommand: CommandDefinition = {\n  verb: 'export',\n  summary: 'A Block-control in an exchange format: a mind map as a Markdown outline or OPML',\n  positionals: [{ name: 'entity_id', description: 'The control (container) id', required: true }],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'format', property: 'format', description: 'markdown (default) | opml', type: 'string', enum: ['markdown', 'opml'] },\n    { name: 'out', property: 'out', description: 'Write the text to this file instead of answering it', type: 'string' },\n  ],\n  inputSchema: workspaceInput({ entity_id: { type: 'string', minLength: 1 }, format: { type: 'string' }, out: { type: 'string' } }, ['entity_id']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'read' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws export mm_plan --workspace ws_abc', 'buckyos aiws export mm_plan --workspace ws_abc --format opml --out plan.opml'],\n  handler: async (ctx, input) => {\n    const result = await aiws(ctx, 'control.export', { workspace_id: requiredInputString(input, 'workspace_id'), entity_id: requiredInputString(input, 'entity_id'), format: inputString(input, 'format') ?? 'markdown' })\n    const out = inputString(input, 'out')\n    if (!out) return result\n    await getHost().writeTextFile(out, String(result.text ?? ''))\n    return { ok: true, format: result.format, kind: result.kind, path: out }\n  },\n}\n\n// ---- extension controls (buckyos aiworkspace README “Extension controls”): source in the Zone's home folders,\n// built into a Workspace, exported as a bundle / `aiws` PIKG, installed into the caller's library, imported elsewhere.\n// The drivers are buckyos-websdk src/aiws_ext.ts, shared with the Desktop.\n\nasync function sessionToken(ctx: CommandContext): Promise<string> {\n  const session = ctx.session\n  if (!session) throw new ToolError('AUTH_REQUIRED', 'authenticated session is required', EXIT_AUTH)\n  return (await session.ensureValid()).token\n}\n\n/** The Zone file service (NFSP) with the caller's session: where control sources live. */\nasync function openHome(ctx: CommandContext): Promise<NfspClient> {\n  const session = ctx.session\n  if (!session) throw new ToolError('AUTH_REQUIRED', 'authenticated session is required', EXIT_AUTH)\n  const nfsp = new NfspClient({ baseUrl: gatewayOrigin(ctx.connection.endpoint), sessionToken: async () => (await session.ensureValid()).token })\n  await nfsp.hello(['cli'])\n  return nfsp\n}\n\n/** The two calls the shared drivers make (`AiwsExtRpc` of buckyos-websdk src/aiws_ext.ts). */\nfunction extRpc(ctx: CommandContext) {\n  return {\n    extBuild: (workspace_id: string, params: Record<string, unknown>) => aiws(ctx, 'ext.build', { workspace_id, ...params }) as never,\n    extExport: (workspace_id: string, entity_ids: string[], purpose: string = 'package') => aiws(ctx, 'ext.export', { workspace_id, entity_ids, purpose }) as never,\n  }\n}\n\n/** Bytes of a Workspace object (`GET /kapi/aiworkspace/asset/<ws>/<obj_id>`, authorized through what references it). */\nfunction assetFetcher(ctx: CommandContext): (workspaceId: string, objId: string) => Promise<Uint8Array> {\n  return async (workspaceId, objId) => {\n    const response = await fetch(`${gatewayOrigin(ctx.connection.endpoint)}/kapi/aiworkspace/asset/${encodeURIComponent(workspaceId)}/${encodeURIComponent(objId)}`, {\n      headers: { Authorization: `Bearer ${await sessionToken(ctx)}` },\n      signal: ctx.signal,\n    })\n    if (!response.ok) throw new ToolError('AIWS_ASSET_UNAVAILABLE', `asset ${objId}: HTTP ${response.status}`)\n    return new Uint8Array(await response.arrayBuffer())\n  }\n}\n\n/** Source problems (not refusals of the service) as a build failure with diagnostics. */\nasync function sourceErrors<T>(run: () => Promise<T>): Promise<T> {\n  try {\n    return await run()\n  } catch (error) {\n    if (error instanceof AiwsSourceError) throw new ToolError('BUILD_FAILED', `BUILD_FAILED: ${error.message}`, undefined, false, { data: { diagnostics: error.diagnostics } })\n    throw error\n  }\n}\n\nfunction list(input: Record<string, unknown>, key: string): string[] {\n  return requiredInputString(input, key).split(',').map((s) => s.trim()).filter(Boolean)\n}\n\nconst IDENT = /^did:[a-z0-9]+:[^/#\\s]+#[a-z0-9][a-z0-9._-]{0,63}$/\n\n/** A `--migration` file: `{ \"<author_did>#<name>\": Migration }` (aiworkspace schemas/migration.schema.json: `config` /\n * `bindings` `{ rename, drop, fill }`, `slots` `{ rename, move }`, `events` `{ rename, drop }`), passed as it is. */\nasync function migrationFile(ctx: CommandContext, path: string): Promise<Record<string, unknown>> {\n  const host = getHost()\n  let value: unknown\n  try {\n    value = JSON.parse(await host.readTextFile(host.path.resolve(ctx.cwd, path)))\n  } catch (error) {\n    throw new UsageError('AIWS_USAGE', `--migration ${path}: ${error instanceof Error ? error.message : String(error)}`)\n  }\n  const shape = `--migration ${path}: { \"<author_did>#<name>\": { config?, bindings?, slots?, events? } }`\n  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new UsageError('AIWS_USAGE', shape)\n  for (const [ident, m] of Object.entries(value)) {\n    if (!IDENT.test(ident) || !m || typeof m !== 'object' || Array.isArray(m) || Object.keys(m).some((k) => !['config', 'bindings', 'slots', 'events'].includes(k))) {\n      throw new UsageError('AIWS_USAGE', `${shape} (at ${ident})`)\n    }\n  }\n  return value as Record<string, unknown>\n}\n\n// ---- local source folders: a developer's or an Agent's own disk (files go inline; past 4 MiB per build the largest\n// are uploaded and sent by reference, Q22)\n\nconst LOCAL_STATE = '.aiws-build.json'\n\nasync function isLocalDir(path: string): Promise<boolean> {\n  try { return (await getHost().stat(path)).isDirectory } catch { return false }\n}\n\n/** The files of a local source folder, sub-folders included (names are relative paths; dot entries are skipped). */\nasync function localFiles(dir: string): Promise<{ name: string; bytes: Uint8Array }[]> {\n  const host = getHost()\n  const files: { name: string; bytes: Uint8Array }[] = []\n  const problems: { file: string; severity: 'error'; message: string }[] = []\n  const walk = async (folder: string, prefix: string, depth: number): Promise<void> => {\n    for (const entry of await host.readDir(folder)) {\n      if (entry.name.startsWith('.')) continue\n      const name = `${prefix}${entry.name}`\n      if (entry.isDirectory) {\n        if (depth >= 8) problems.push({ file: name, severity: 'error', message: 'sub-folders nest at most 8 levels' })\n        else await walk(host.path.join(folder, entry.name), `${name}/`, depth + 1)\n      } else if (entry.isFile) files.push({ name, bytes: await host.readFile(host.path.join(folder, entry.name)) })\n      else problems.push({ file: name, severity: 'error', message: 'only files and folders belong to a control source' })\n    }\n  }\n  await walk(dir, '', 0)\n  if (files.length === 0) problems.push({ file: '', severity: 'error', message: `${dir} holds no files` })\n  if (problems.length > 0) throw new ToolError('BUILD_FAILED', `BUILD_FAILED: ${problems.map((p) => `${p.file}: ${p.message}`).join('; ')}`, undefined, false, { data: { diagnostics: problems } })\n  return files.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n}\n\n/** Put a source file too big to go inline into the caller's own `exports` bucket: the FileObject the build names (the\n * service reads it through the NDM gateway with the caller's token). */\nfunction sourceUploader(ctx: CommandContext): (name: string, bytes: Uint8Array) => Promise<string> {\n  return async (name, bytes) => {\n    const bucket = `user/aiworkspace/${ctx.principal.id}/exports`\n    const key = `aiws-src/${Date.now()}-${name.replaceAll('/', '_')}`\n    const url = `${gatewayOrigin(ctx.connection.endpoint)}/bucket/v1/${bucket}/${key.split('/').map(encodeURIComponent).join('/')}`\n    const response = await fetch(url, { method: 'PUT', headers: { Authorization: `Bearer ${await sessionToken(ctx)}` }, body: new Blob([bytes as Uint8Array<ArrayBuffer>]), signal: ctx.signal })\n    if (!response.ok) throw new ToolError('AIWS_UPLOAD_FAILED', `upload of ${name}: HTTP ${response.status} ${await response.text().catch(() => '')}`)\n    const put = await response.json() as { obj_id?: string }\n    if (!put.obj_id) throw new ToolError('AIWS_UPLOAD_FAILED', `upload of ${name}: the bucket answered no obj_id`)\n    return put.obj_id\n  }\n}\n\nasync function localState(dir: string): Promise<Record<string, unknown> | null> {\n  try { return JSON.parse(await getHost().readTextFile(getHost().path.join(dir, LOCAL_STATE))) as Record<string, unknown> } catch { return null }\n}\n\n/** Build a local folder into a Workspace; the base it was built on is kept in its `.aiws-build.json`. */\nasync function buildLocal(ctx: CommandContext, ws: string, dir: string, opts: { folderId?: string; force?: boolean; dryRun?: boolean; migration?: Record<string, unknown> }): Promise<Record<string, unknown>> {\n  const state = await localState(dir)\n  const result = await aiws(ctx, 'ext.build', {\n    workspace_id: ws, files: await sourceErrors(async () => packBuildFiles(await localFiles(dir), sourceUploader(ctx))),\n    ...(opts.folderId ? { folder_id: opts.folderId } : {}),\n    ...(state && state.workspace_id === ws ? { expect: { def_rev: state.def_rev, dir_rev: state.dir_rev } } : {}),\n    ...(opts.force ? { force: true } : {}), ...(opts.dryRun ? { dry_run: true } : {}), ...(opts.migration ? { migration: opts.migration } : {}),\n  })\n  if (!opts.dryRun && typeof result.def_entity_id === 'string' && typeof result.def_rev === 'number') {\n    await getHost().writeTextFile(getHost().path.join(dir, LOCAL_STATE), `${JSON.stringify({ workspace_id: ws, def_entity_id: result.def_entity_id, def_rev: result.def_rev, dir_rev: result.dir_rev ?? 0, ident: result.ident, at: new Date().toISOString() }, null, 2)}\\n`)\n  }\n  return result\n}\n\nconst buildCommand: CommandDefinition = {\n  verb: 'build',\n  summary: 'Build a control from its source folder (local, or in the Zone; component.json + files) into a Workspace; instances update, a failure commits nothing',\n  description: 'The folder is a local folder (when it exists here; its files are sent inline, and past 4 MiB per build the largest are uploaded to your exports bucket and sent by reference) or a Zone path (e.g. /home/alice/AI Workspace/Demo/controls/kpi-card; --zone-path forces it); sub-folders are part of the source (file names are relative paths). The base of the last build or pull is kept in its .aiws-build.json; building over a newer Workspace version is refused (pull first, or --force). --watch rebuilds on every change until interrupted. A build that narrows what instances rely on (a binding renamed, a slot moved, an event dropped) takes --migration, a JSON file { \"<author_did>#<name>\": Migration } (as ext-upgrade).',\n  positionals: [{ name: 'dir', description: 'Local folder, or Zone path of the control source folder', required: true }],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'folder', property: 'folder_id', description: 'Data folder for the definition (default: data/extensions)', type: 'string' },\n    { name: 'watch', property: 'watch', description: 'Rebuild whenever the folder changes', type: 'boolean' },\n    { name: 'dry-run', property: 'dry_run', description: 'Check only: diagnostics, nothing committed', type: 'boolean' },\n    { name: 'force', property: 'force', description: 'Build over whatever the Workspace holds now', type: 'boolean' },\n    { name: 'zone-path', property: 'zone_path', description: 'Treat the folder as a Zone path even if a local folder has that name', type: 'boolean' },\n    { name: 'migration', property: 'migration', description: 'JSON file { \"<author_did>#<name>\": Migration } rewriting the instances of a build that narrows the contract', type: 'string' },\n  ],\n  inputSchema: workspaceInput({ dir: { type: 'string', minLength: 1 }, folder_id: { type: 'string' }, watch: { type: 'boolean' }, dry_run: { type: 'boolean' }, force: { type: 'boolean' }, zone_path: { type: 'boolean' }, migration: { type: 'string' } }, ['dir']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws build \"/home/alice/AI Workspace/Demo/controls/kpi-card\" --workspace ws_abc', 'buckyos aiws build \"/home/alice/AI Workspace/Demo/controls/kpi-card\" --workspace ws_abc --watch'],\n  handler: async (ctx, input) => {\n    const ws = requiredInputString(input, 'workspace_id')\n    const dir = requiredInputString(input, 'dir')\n    const migration = inputString(input, 'migration')\n    const opts = { folderId: inputString(input, 'folder_id'), force: input.force === true, dryRun: input.dry_run === true, upload: sourceUploader(ctx), ...(migration ? { migration: await migrationFile(ctx, migration) } : {}) }\n    if (input.zone_path !== true && await isLocalDir(getHost().path.resolve(ctx.cwd, dir))) {\n      const local = getHost().path.resolve(ctx.cwd, dir)\n      if (input.watch === true) throw new UsageError('AIWS_USAGE', '--watch follows a Zone folder; rebuild a local folder yourself')\n      return buildLocal(ctx, ws, local, opts)\n    }\n    const nfsp = await openHome(ctx)\n    if (input.watch !== true) return sourceErrors(() => buildControl(extRpc(ctx), nfsp, ws, dir, opts))\n    let builds = 0\n    let failures = 0\n    await watchControl(nfsp, dir, async () => {\n      try {\n        const r = await sourceErrors(() => buildControl(extRpc(ctx), nfsp, ws, dir, opts))\n        builds++\n        await ctx.io.stderr(`built ${r.ident} v${r.version ?? '?'} (${r.unchanged ? 'unchanged' : r.status})\\n`)\n      } catch (error) {\n        failures++\n        const diagnostics = error instanceof ToolError ? (error.details.data as { diagnostics?: unknown[] } | undefined)?.diagnostics : undefined\n        await ctx.io.stderr(`build failed: ${error instanceof Error ? error.message : String(error)}\\n${diagnostics ? `${JSON.stringify(diagnostics, null, 2)}\\n` : ''}`)\n      }\n    }, { signal: ctx.signal })\n    return { ok: true, watched: dir, builds, failures }\n  },\n}\n\nconst pullCommand: CommandDefinition = {\n  verb: 'pull',\n  summary: 'Write a control definition’s Workspace snapshot into a folder — a Zone path (default) or a local one (--local) — as the base of the next build',\n  positionals: [{ name: 'def', description: 'Definition (buckyos.block-def) id', required: true }],\n  options: [WORKSPACE_OPTION, { name: 'out', property: 'out', description: 'Folder to write (created)', type: 'string', required: true }, { name: 'local', property: 'local', description: 'Write into a local folder instead of the Zone', type: 'boolean' }],\n  inputSchema: workspaceInput({ def: { type: 'string', minLength: 1 }, out: { type: 'string', minLength: 1 }, local: { type: 'boolean' } }, ['def', 'out']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws pull def_abc --workspace ws_abc --out \"/home/alice/AI Workspace/Demo/controls/kpi-card\"'],\n  handler: async (ctx, input) => {\n    if (input.local === true) {\n      const ws = requiredInputString(input, 'workspace_id')\n      const host = getHost()\n      const out = host.path.resolve(ctx.cwd, requiredInputString(input, 'out'))\n      const r = await aiws(ctx, 'ext.export', { workspace_id: ws, entity_ids: [requiredInputString(input, 'def')], purpose: 'pull' })\n      const control = expectObject((r.controls as unknown[])[0], 'ext.export.controls[0]')\n      await host.mkdir(out, { recursive: true })\n      const fetchAsset = assetFetcher(ctx)\n      const files: string[] = []\n      for (const f of control.files as { name: string; obj_id?: string; text?: string }[]) {\n        const target = host.path.join(out, ...f.name.split('/'))\n        await host.mkdir(host.path.dirname(target), { recursive: true })\n        if (f.text !== undefined) await host.writeTextFile(target, f.text)\n        else await host.writeFile(target, await fetchAsset(ws, String(f.obj_id)))\n        files.push(f.name)\n      }\n      await host.writeTextFile(host.path.join(out, LOCAL_STATE), `${JSON.stringify({ workspace_id: ws, def_entity_id: control.entity_id, def_rev: control.def_rev, dir_rev: control.dir_rev, ident: control.ident, at: new Date().toISOString() }, null, 2)}\\n`)\n      return { ok: true, out, files }\n    }\n    const nfsp = await openHome(ctx)\n    const r = await pullControl(extRpc(ctx), nfsp, requiredInputString(input, 'workspace_id'), requiredInputString(input, 'def'), requiredInputString(input, 'out'), assetFetcher(ctx))\n    return { ok: true, out: requiredInputString(input, 'out'), ...r }\n  },\n}\n\n/** Run a verb of the pikg module (init / build / pack) with this command's context. */\nasync function pikgVerb(ctx: CommandContext, verb: string, input: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const command = createPikgModule().commands.find((c) => c.verb === verb)\n  if (!command) throw new ToolError('INTERNAL', `pikg ${verb} is missing`)\n  return expectObject(await command.handler(ctx, input), `pikg ${verb}`)\n}\n\n/** Bind a local `.pikg` into the caller's own `user/aiworkspace/<user>/exports` bucket (the data plane PUT, ≤ 32 MiB):\n * what `ext.install { pikg: { bucket_id, key } }` takes (and consumes once installed). */\nasync function uploadPackage(ctx: CommandContext, path: string): Promise<{ bucket_id: string; key: string }> {\n  const bucket_id = `user/aiworkspace/${ctx.principal.id}/exports`\n  const key = `aiws/${Date.now()}-${getHost().path.basename(path)}`\n  const bytes = await getHost().readFile(path)\n  if (bytes.byteLength > 32 * 1024 * 1024) throw new UsageError('FILE_TOO_LARGE', 'a control package installed from the CLI is limited to 32 MiB')\n  const url = `${gatewayOrigin(ctx.connection.endpoint)}/bucket/v1/${bucket_id}/${key.split('/').map(encodeURIComponent).join('/')}`\n  const response = await fetch(url, { method: 'PUT', headers: { Authorization: `Bearer ${await sessionToken(ctx)}` }, body: new Blob([bytes as Uint8Array<ArrayBuffer>]), signal: ctx.signal })\n  if (!response.ok) throw new ToolError('AIWS_UPLOAD_FAILED', `upload of ${path}: HTTP ${response.status} ${await response.text().catch(() => '')}`)\n  return { bucket_id, key }\n}\n\nconst PACKAGE_INPUT: Record<string, JsonSchema> = { name: { type: 'string' }, version: { type: 'string' }, owner: { type: 'string' }, pikg: { type: 'boolean' }, install: { type: 'boolean' } }\n\nfunction packageOptions(nameDefault: string): OptionDefinition[] {\n  return [\n    { name: 'name', property: 'name', description: `Package name (default: ${nameDefault})`, type: 'string' },\n    { name: 'version', property: 'version', description: 'Package version (default 0.1.0)', type: 'string' },\n    { name: 'owner', property: 'owner', description: 'Owner DID of the package (default did:bns:<you>)', type: 'string' },\n    { name: 'pikg', property: 'pikg', description: 'Also pack the bundle as an aiws PIKG', type: 'boolean' },\n    { name: 'install', property: 'install', description: 'Pack, then install into your AI Workspace library (dev mode)', type: 'boolean' },\n  ]\n}\n\nconst fromBase64 = (text: string) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0))\n\n/** Write a bundle (manifest, `controls/<dir>/`, `templates/<id>/`) as `<out>/aiws/`. */\nasync function writeBundle(out: string, files: Map<string, Uint8Array>): Promise<string> {\n  const host = getHost()\n  const root = host.path.join(out, 'aiws')\n  // a previous export's controls must not linger in the bundle\n  await host.remove(root, { recursive: true }).catch(() => undefined)\n  for (const [path, bytes] of files) {\n    const target = host.path.join(root, path)\n    await host.mkdir(host.path.dirname(target), { recursive: true })\n    await host.writeFile(target, bytes)\n  }\n  return root\n}\n\n/** `--pikg` / `--install` of a bundle written into `<out>/aiws/`: pikg init (once) / build / pack in `<out>` (kind\n * aiws-controls); `--install` binds the `.pikg` into your aiworkspace exports bucket and calls `ext.install`. */\nasync function packBundle(ctx: CommandContext, input: Record<string, unknown>, out: string, defaultName: string, result: Record<string, unknown>): Promise<Record<string, unknown>> {\n  if (input.pikg !== true && input.install !== true) return result\n  const host = getHost()\n  const name = inputString(input, 'name') ?? defaultName\n  const owner = inputString(input, 'owner') ?? `did:bns:${ctx.principal.id}`\n  const version = inputString(input, 'version') ?? '0.1.0'\n  const appJson = host.path.join(out, 'dapp_meta', 'app.json')\n  const existing = await host.readTextFile(appJson).then((t) => JSON.parse(t) as Record<string, unknown>).catch(() => null)\n  if (!existing) {\n    await pikgVerb(ctx, 'init', { project_dir: out, name, owner, kind: 'aiws-controls', source: './aiws', version })\n  } else if (inputString(input, 'version') && existing.version !== version) {\n    // a re-export at a new version: the same project, the new version (a library refuses other content at an old one)\n    await host.writeTextFile(appJson, `${JSON.stringify({ ...existing, version }, null, 2)}\\n`)\n    const pikgJson = host.path.join(out, 'dapp_meta', 'pikg.json')\n    const meta = JSON.parse(await host.readTextFile(pikgJson)) as Record<string, unknown>\n    await host.writeTextFile(pikgJson, `${JSON.stringify({ ...meta, pikg_file: `${existing.name}-${version}.pikg` }, null, 2)}\\n`)\n  }\n  await pikgVerb(ctx, 'build', { meta_dir: host.path.join(out, 'dapp_meta') })\n  const packed = await pikgVerb(ctx, 'pack', { dist_dir: host.path.join(out, 'dapp_dist') })\n  const pikgPath = String(packed.pikg_path)\n  result.pikg = pikgPath\n  if (input.install !== true) return result\n  result.install = await aiws(ctx, 'ext.install', { pikg: await uploadPackage(ctx, pikgPath), mode: 'dev' })\n  return result\n}\n\nconst controlSummary = (controls: Record<string, unknown>[]) => controls.map((c) => ({ ident: c.ident, kind: c.kind, version: c.version, digest: c.digest }))\n\nconst extExportCommand: CommandDefinition = {\n  verb: 'ext-export',\n  summary: 'Export Workspace controls as a bundle in a local folder; optionally pack it as an aiws PIKG and install it into your library',\n  description: 'Writes <out>/aiws/ (aiws-manifest.json + controls/<dir>/). --pikg (or --install) also runs pikg init/build/pack in <out> (kind aiws-controls); --install binds the .pikg into your aiworkspace exports bucket and calls ext.install.',\n  positionals: [{ name: 'defs', description: 'Definition (or instance) ids, comma-separated', required: true }],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'out', property: 'out', description: 'Local folder to write into (created)', type: 'string', required: true },\n    ...packageOptions('the first control’s'),\n  ],\n  inputSchema: workspaceInput({ defs: { type: 'string', minLength: 1 }, out: { type: 'string', minLength: 1 }, ...PACKAGE_INPUT }, ['defs', 'out']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws ext-export def_abc,def_xyz --workspace ws_abc --out ./kpi-pack --install'],\n  handler: async (ctx, input) => {\n    const out = getHost().path.resolve(ctx.cwd, requiredInputString(input, 'out'))\n    const bundle = await exportBundle(extRpc(ctx), requiredInputString(input, 'workspace_id'), list(input, 'defs'), assetFetcher(ctx))\n    const result: Record<string, unknown> = { ok: true, bundle: await writeBundle(out, bundle.files), controls: controlSummary(bundle.manifest.controls) }\n    return packBundle(ctx, input, out, bundle.manifest.controls[0]?.name.replace(/[._]/g, '-') ?? 'controls', result)\n  },\n}\n\nconst extUpgradeCommand: CommandDefinition = {\n  verb: 'ext-upgrade',\n  summary: 'Upgrade controls a Workspace imported from your library to the version your library holds now (one Commit; instances keep their overrides and content)',\n  description: 'Each definition is rebuilt from its package in your library (--pkg, or the package it was imported from), with what it builds on from the same package, dependencies first. A definition built locally since its import is refused (EXT_LOCAL_CHANGES; the error data lists the changed files) unless --force. A version that narrows what instances rely on needs --migration, a JSON file { \"<author_did>#<name>\": Migration } keyed by identity (config / bindings { rename, drop, fill }, slots { rename, move }, events { rename, drop }); --dry-run answers what it would write on each instance. Across Zones: `aiws library bundle <pkg_id> --out <file>` in the Zone of the library, then `aiws ext-import --bundle <file> --upgrade` in the Zone of the Workspace.',\n  positionals: [{ name: 'defs', description: 'Definition (buckyos.block-def) ids, comma-separated', required: true }],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'pkg', property: 'pkg_id', description: 'Library package to upgrade from (default: the one each definition was imported from)', type: 'string' },\n    { name: 'migration', property: 'migration', description: 'JSON file { \"<author_did>#<name>\": Migration } rewriting the instances of a narrowing version', type: 'string' },\n    { name: 'dry-run', property: 'dry_run', description: 'Check only: the plan per instance, nothing committed', type: 'boolean' },\n    { name: 'force', property: 'force', description: 'Upgrade over local changes (they are replaced)', type: 'boolean' },\n  ],\n  inputSchema: workspaceInput({ defs: { type: 'string', minLength: 1 }, pkg_id: { type: 'string' }, migration: { type: 'string' }, dry_run: { type: 'boolean' }, force: { type: 'boolean' } }, ['defs']),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws ext-upgrade def_abc --workspace ws_abc --dry-run', 'buckyos aiws ext-upgrade def_abc,def_xyz --workspace ws_abc --migration ./migration.json'],\n  handler: async (ctx, input) => {\n    const pkg = inputString(input, 'pkg_id')\n    const migration = inputString(input, 'migration')\n    return aiws(ctx, 'ext.upgrade', {\n      workspace_id: requiredInputString(input, 'workspace_id'),\n      items: list(input, 'defs').map((def_entity_id) => ({ def_entity_id, ...(pkg ? { pkg_id: pkg } : {}) })),\n      ...(migration ? { migration: await migrationFile(ctx, migration) } : {}),\n      ...(input.force === true ? { force: true } : {}), ...(input.dry_run === true ? { dry_run: true } : {}),\n      ...(ctx.idempotencyKey ? { idempotency_key: ctx.idempotencyKey } : {}),\n    })\n  },\n}\n\nconst libraryCommand: CommandDefinition = {\n  verb: 'library',\n  summary: 'Your AI Workspace control library: `list` (each control with the identities it depends on, `deps`, and the package’s templates), `install <file.pikg>` (an aiws package, dev mode), `remove <pkg_id>`, `bundle <pkg_id> --out <file.json>` (the controls with their bytes, for `ext-import --bundle` in another Zone)',\n  positionals: [{ name: 'action', description: 'list | install | remove | bundle', required: true }, { name: 'target', description: 'install: local .pikg path; remove, bundle: package id', required: false }],\n  options: [\n    { name: 'out', property: 'out', description: 'bundle: the JSON file to write', type: 'string' },\n    { name: 'idents', property: 'idents', description: 'bundle: only these controls (and what they build on), comma-separated identities', type: 'string' },\n  ],\n  inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['list', 'install', 'remove', 'bundle'] }, target: { type: 'string' }, out: { type: 'string' }, idents: { type: 'string' } }, required: ['action'], additionalProperties: false },\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws library list', 'buckyos aiws library install ./kpi-pack-0.1.0.pikg', 'buckyos aiws library remove kpi-pack.alice.bns.did', 'buckyos aiws library bundle kpi-pack.alice.bns.did --out ./kpi-pack.bundle.json'],\n  handler: async (ctx, input) => {\n    const action = requiredInputString(input, 'action')\n    if (action === 'list') return aiws(ctx, 'ext.list_library', {})\n    if (action === 'remove') return aiws(ctx, 'ext.uninstall', { pkg_id: requiredInputString(input, 'target') })\n    if (action === 'bundle') {\n      const host = getHost()\n      const out = host.path.resolve(ctx.cwd, requiredInputString(input, 'out'))\n      const idents = inputString(input, 'idents')\n      const r = await aiws(ctx, 'ext.library_bundle', { pkg_id: requiredInputString(input, 'target'), ...(idents ? { idents: list(input, 'idents') } : {}) })\n      const controls = (Array.isArray(r.controls) ? r.controls : []) as Record<string, unknown>[]\n      await host.writeTextFile(out, `${JSON.stringify({ pkg_id: r.pkg_id, controls }, null, 2)}\\n`)\n      return { ok: true, out, pkg_id: r.pkg_id, controls: controls.map((c) => ({ ident: c.ident, version: c.version, digest: c.digest, deps: c.deps })) }\n    }\n    if (action !== 'install') throw new UsageError('AIWS_USAGE', 'library: list, install <file.pikg>, remove <pkg_id> or bundle <pkg_id> --out <file.json>')\n    const path = getHost().path.resolve(ctx.cwd, requiredInputString(input, 'target'))\n    return aiws(ctx, 'ext.install', { pikg: await uploadPackage(ctx, path), mode: 'dev' })\n  },\n}\n\ninterface BundleControl { ident: string; deps?: string[]; provenance?: Record<string, unknown>; files: { name: string; base64: string }[] }\n\n/** Build the controls of a library bundle (`library bundle` in the Zone of the library) into a Workspace of this Zone:\n * their bytes with their `provenance`, what they build on first (README “Import” across Zones). `upgrade` replaces what\n * the Workspace holds of these identities (`migration` per identity, Q30); without it a dependency the Workspace already\n * holds from another source is met by that definition, as `ext.import` does. */\nasync function relayBundle(ctx: CommandContext, ws: string, controls: BundleControl[], opts: { folderId?: string; upgrade: boolean; migration?: Record<string, unknown> }): Promise<Record<string, unknown>[]> {\n  const pending = [...controls]\n  const needed = new Set(controls.flatMap((c) => c.deps ?? []))\n  const out: Record<string, unknown>[] = []\n  while (pending.length > 0) {\n    const left = new Set(pending.map((c) => c.ident))\n    const c = pending.splice(Math.max(0, pending.findIndex((p) => (p.deps ?? []).every((d) => !left.has(d) || d === p.ident))), 1)[0]\n    try {\n      const r = await aiws(ctx, 'ext.build', {\n        workspace_id: ws, files: await sourceErrors(() => packBuildFiles(c.files.map((f) => ({ name: f.name, bytes: fromBase64(f.base64) })), sourceUploader(ctx))), provenance: c.provenance,\n        ...(opts.folderId ? { folder_id: opts.folderId } : {}),\n        ...(opts.upgrade ? { upgrade: true } : {}),\n        ...(opts.migration?.[c.ident] ? { migration: { [c.ident]: opts.migration[c.ident] } } : {}),\n      })\n      out.push({ ident: c.ident, def_entity_id: r.def_entity_id, action: r.action ?? r.status, version: r.version })\n    } catch (error) {\n      if (opts.upgrade || !needed.has(c.ident) || !(error instanceof ToolError) || error.details.sub_code !== 'EXT_IDENT_EXISTS') throw error\n      out.push({ ident: c.ident, def_entity_id: (error.details.data as { def_entity_id?: unknown } | undefined)?.def_entity_id, action: 'satisfied' })\n    }\n  }\n  return out\n}\n\nconst extImportCommand: CommandDefinition = {\n  verb: 'ext-import',\n  summary: 'Bring controls of your library into a Workspace (one Commit): <pkg_id>#<ident>, comma-separated; what they build on (deps) comes along, dependencies first, and an identity the Workspace already has satisfies it. --bundle builds a library bundle of another Zone instead',\n  description: 'Across Zones: `aiws library bundle <pkg_id> --out <file>` in the Zone of the library, then `aiws ext-import --bundle <file> --workspace <ws>` in the Zone of the Workspace: each control is built with its package provenance, dependencies first; a dependency the Workspace already holds is met by that definition. --upgrade (with --bundle) upgrades the identities the Workspace holds from another version, --migration naming a JSON file { \"<author_did>#<name>\": Migration } for a version that narrows what instances rely on. Upgrades from your library in the same Zone are `aiws ext-upgrade`.',\n  positionals: [{ name: 'items', description: '<pkg_id>#<author_did>#<name>[,…] (ext.list_library names them); not with --bundle', required: false }],\n  options: [\n    WORKSPACE_OPTION,\n    { name: 'folder', property: 'folder_id', description: 'Data folder for the definitions (default: data/extensions)', type: 'string' },\n    { name: 'bundle', property: 'bundle', description: 'A library bundle file (`aiws library bundle`, any Zone) to build instead of items', type: 'string' },\n    { name: 'upgrade', property: 'upgrade', description: 'With --bundle: upgrade identities the Workspace holds from another version', type: 'boolean' },\n    { name: 'migration', property: 'migration', description: 'With --upgrade: JSON file { \"<author_did>#<name>\": Migration }', type: 'string' },\n  ],\n  inputSchema: workspaceInput({ items: { type: 'string', minLength: 1 }, folder_id: { type: 'string' }, bundle: { type: 'string' }, upgrade: { type: 'boolean' }, migration: { type: 'string' } }),\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: ['buckyos aiws ext-import kpi-pack.alice.bns.did#did:bns:alice#kpi-card --workspace ws_abc', 'buckyos aiws ext-import --bundle ./kpi-pack.bundle.json --workspace ws_abc --upgrade'],\n  handler: async (ctx, input) => {\n    const ws = requiredInputString(input, 'workspace_id')\n    const folder = inputString(input, 'folder_id')\n    const bundle = inputString(input, 'bundle')\n    const migration = inputString(input, 'migration')\n    if (migration && input.upgrade !== true) throw new UsageError('AIWS_USAGE', '--migration goes with --upgrade')\n    if (!bundle) {\n      if (input.upgrade === true) throw new UsageError('AIWS_USAGE', '--upgrade goes with --bundle (a library bundle of another Zone); upgrade what came from your own library with `aiws ext-upgrade`')\n      const items = list(input, 'items').map((item) => {\n        const cut = item.indexOf('#')\n        if (cut <= 0) throw new UsageError('AIWS_USAGE', `${item}: <pkg_id>#<ident>`)\n        return { pkg_id: item.slice(0, cut), ident: item.slice(cut + 1) }\n      })\n      return aiws(ctx, 'ext.import', { workspace_id: ws, items, ...(folder ? { folder_id: folder } : {}) })\n    }\n    if (inputString(input, 'items')) throw new UsageError('AIWS_USAGE', 'pass items or --bundle, not both')\n    const host = getHost()\n    const file = JSON.parse(await host.readTextFile(host.path.resolve(ctx.cwd, bundle))) as { controls?: unknown }\n    if (!Array.isArray(file.controls) || file.controls.some((c) => !c || typeof c.ident !== 'string' || !Array.isArray(c.files))) {\n      throw new UsageError('AIWS_USAGE', `--bundle ${bundle}: not a library bundle ({ pkg_id, controls: [{ ident, provenance, files }] }, from \\`aiws library bundle\\`)`)\n    }\n    const controls = await relayBundle(ctx, ws, file.controls as BundleControl[], { folderId: folder, upgrade: input.upgrade === true, ...(migration ? { migration: await migrationFile(ctx, migration) } : {}) })\n    return { ok: true, controls }\n  },\n}\n\n/** `template create --param k=v[,k=v…]`, typed by the template's `params` (string | number | boolean). */\nfunction createParams(text: string, declared: Record<string, { type?: string }>): Record<string, string | number | boolean> {\n  const out: Record<string, string | number | boolean> = {}\n  for (const pair of text.split(',').map((s) => s.trim()).filter(Boolean)) {\n    const cut = pair.indexOf('=')\n    const name = cut > 0 ? pair.slice(0, cut) : ''\n    if (!Object.hasOwn(declared, name)) throw new UsageError('AIWS_USAGE', `--param ${pair}: the template's params are ${Object.keys(declared).join(', ') || '(none)'}`)\n    out[name] = typedValue(declared[name].type, pair.slice(cut + 1), `--param ${pair}`)\n  }\n  return out\n}\n\n/** `template export --param name:type[:default][,…]`: the params a new Workspace is created with. */\nfunction exportParams(text: string): Record<string, { type: string; default?: string | number | boolean }> {\n  const out: Record<string, { type: string; default?: string | number | boolean }> = {}\n  for (const item of text.split(',').map((s) => s.trim()).filter(Boolean)) {\n    const [name, type, ...rest] = item.split(':')\n    if (!name || !['string', 'number', 'boolean'].includes(type)) throw new UsageError('AIWS_USAGE', `--param ${item}: <name>:<string | number | boolean>[:<default>]`)\n    out[name] = { type, ...(rest.length > 0 ? { default: typedValue(type, rest.join(':'), `--param ${item}`) } : {}) }\n  }\n  return out\n}\n\nfunction typedValue(type: string | undefined, raw: string, label: string): string | number | boolean {\n  if (type === 'number') {\n    const n = Number(raw)\n    if (!raw.trim() || !Number.isFinite(n)) throw new UsageError('AIWS_USAGE', `${label}: a number`)\n    return n\n  }\n  if (type === 'boolean') {\n    if (raw !== 'true' && raw !== 'false') throw new UsageError('AIWS_USAGE', `${label}: true or false`)\n    return raw === 'true'\n  }\n  return raw\n}\n\n/** `template export`: the template snapshot (`ext.export_template`) and the controls it needs (`ext.export`, package)\n * as one bundle in `<out>/aiws/`, then packed / installed as `ext-export` does. */\nasync function exportTemplate(ctx: CommandContext, input: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const ws = requiredInputString(input, 'workspace_id')\n  const id = requiredInputString(input, 'id')\n  if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(id)) throw new UsageError('AIWS_USAGE', `--id ${id}: [a-z0-9][a-z0-9-]{0,63}`)\n  const description = inputString(input, 'description')\n  const param = inputString(input, 'param')\n  const template = {\n    id, title: requiredInputString(input, 'title'), ...(description ? { description } : {}), ...(param ? { params: exportParams(param) } : {}),\n    ...(inputString(input, 'reset') ? { reset: { tables: list(input, 'reset') } } : {}),\n  }\n  const out = getHost().path.resolve(ctx.cwd, requiredInputString(input, 'out'))\n  const r = await aiws(ctx, 'ext.export_template', { workspace_id: ws, surfaces: list(input, 'surfaces'), ...(inputString(input, 'data') ? { data: list(input, 'data') } : {}), template })\n  const item = expectObject(r.template, 'ext.export_template.template')\n  const defs = (Array.isArray(r.controls) ? r.controls : []).map((c) => typeof c === 'string' ? c : String(expectObject(c, 'ext.export_template.controls[]').entity_id))\n  const files = new Map<string, Uint8Array>()\n  let manifest: Record<string, unknown> = { manifest_version: AIWS_MANIFEST_VERSION, purpose: 'aiws', host_api: {}, controls: [] }\n  if (defs.length > 0) {\n    const bundle = await exportBundle(extRpc(ctx), ws, defs, assetFetcher(ctx))\n    for (const [path, bytes] of bundle.files) files.set(path, bytes)\n    manifest = bundle.manifest\n  }\n  const dir = templateDir(id)\n  for (const f of (Array.isArray(r.files) ? r.files : []) as { path: string; base64: string }[]) {\n    const path = f.path.startsWith(dir) ? f.path : `${dir}${f.path}`\n    if (!isSourcePath(path)) throw new ToolError('INVALID_SERVICE_RESPONSE', `ext.export_template: ${f.path} is not a file of the template`)\n    files.set(path, fromBase64(f.base64))\n  }\n  manifest = { ...manifest, manifest_version: AIWS_MANIFEST_VERSION, workspace_templates: [item] }\n  files.set(AIWS_MANIFEST_FILE, new TextEncoder().encode(`${JSON.stringify(manifest, null, 2)}\\n`))\n  const result: Record<string, unknown> = {\n    ok: true, bundle: await writeBundle(out, files), template: { id: item.id, title: item.title, digest: item.digest, requires: item.requires },\n    controls: controlSummary(manifest.controls as Record<string, unknown>[]),\n  }\n  return packBundle(ctx, input, out, id, result)\n}\n\nconst templateCommand: CommandDefinition = {\n  verb: 'template',\n  summary: 'Workspace templates (snapshots carried in control packages): `list` (the templates of your library), `create <pkg_id>#<template_id>` (a new Workspace from one: answers its workspace_id), `export` (Surfaces of a Workspace as a template bundle; --pikg / --install pack it with the controls it needs and install it)',\n  description: 'create: --title names the new Workspace; --param k=v[,k=v…] sets the template’s params (typed as the template declares them; `template list` shows them). Installing a template never creates a Workspace; each create makes an independent one. export: --workspace, --surfaces s1,s2, --id and --title are required; --data e1,e2 carries data entities along, --param name:type[:default][,…] (type string | number | boolean) declares what a creator fills into {{params.<name>}}, --reset t1,t2 names tables a new Workspace starts without rows. It writes <out>/aiws/ (aiws-manifest.json at manifest_version 3 with the template in workspace_templates, controls/<dir>/ of the controls it needs, templates/<id>/), then packs and installs it as `ext-export` does.',\n  positionals: [{ name: 'action', description: 'list | create | export', required: true }, { name: 'target', description: 'create: <pkg_id>#<template_id>', required: false }],\n  options: [\n    { name: 'workspace', property: 'workspace_id', description: 'export: Workspace id (ws_…)', type: 'string' },\n    { name: 'surfaces', property: 'surfaces', description: 'export: Surface ids, comma-separated', type: 'string' },\n    { name: 'id', property: 'id', description: 'export: template id ([a-z0-9][a-z0-9-]{0,63})', type: 'string' },\n    { name: 'title', property: 'title', description: 'create: title of the new Workspace; export: title of the template', type: 'string' },\n    { name: 'description', property: 'description', description: 'export: what the template is for', type: 'string' },\n    { name: 'data', property: 'data', description: 'export: data entity ids to carry along, comma-separated', type: 'string' },\n    { name: 'param', property: 'param', description: 'create: k=v[,k=v…]; export: name:type[:default][,…]', type: 'string' },\n    { name: 'reset', property: 'reset', description: 'export: tables a new Workspace starts without rows, comma-separated', type: 'string' },\n    { name: 'out', property: 'out', description: 'export: local folder to write into (created)', type: 'string' },\n    ...packageOptions('the template id'),\n  ],\n  inputSchema: {\n    type: 'object',\n    properties: {\n      action: { type: 'string', enum: ['list', 'create', 'export'] }, target: { type: 'string' }, workspace_id: { type: 'string' }, surfaces: { type: 'string' }, id: { type: 'string' },\n      title: { type: 'string' }, description: { type: 'string' }, data: { type: 'string' }, param: { type: 'string' }, reset: { type: 'string' }, out: { type: 'string' }, ...PACKAGE_INPUT,\n    },\n    required: ['action'],\n    additionalProperties: false,\n  },\n  outputSchema: OBJECT_OUTPUT,\n  resultSchemaVersion: 1,\n  access: { mode: 'fixed', level: 'write' },\n  asyncMode: 'sync',\n  requiresSession: true,\n  examples: [\n    'buckyos aiws template list',\n    'buckyos aiws template create team-pack.alice.bns.did#team-board --title \"Ops board\" --param team_name=Ops',\n    'buckyos aiws template export --workspace ws_abc --surfaces sf_board --id team-board --title \"Team task board\" --param team_name:string:Team --reset tasks --out ./team-pack --install',\n  ],\n  handler: async (ctx, input) => {\n    const action = requiredInputString(input, 'action')\n    if (action === 'list') {\n      const library = await aiws(ctx, 'ext.list_library', {})\n      const packages = (Array.isArray(library.packages) ? library.packages : []) as { pkg_id: string; version?: string; templates?: Record<string, unknown>[] }[]\n      return { ok: true, templates: packages.flatMap((p) => (p.templates ?? []).map((t) => ({ ref: `${p.pkg_id}#${t.id}`, pkg_id: p.pkg_id, version: p.version, ...t }))) }\n    }\n    if (action === 'export') return exportTemplate(ctx, input)\n    if (action !== 'create') throw new UsageError('AIWS_USAGE', 'template: list, create <pkg_id>#<template_id> or export --workspace <ws> --surfaces <ids> --id <id> --title <title> --out <dir>')\n    const target = requiredInputString(input, 'target')\n    const cut = target.indexOf('#')\n    if (cut <= 0 || cut === target.length - 1) throw new UsageError('AIWS_USAGE', `${target}: <pkg_id>#<template_id>`)\n    const [pkg_id, template_id] = [target.slice(0, cut), target.slice(cut + 1)]\n    const param = inputString(input, 'param')\n    let params: Record<string, string | number | boolean> | undefined\n    if (param) {\n      const library = await aiws(ctx, 'ext.list_library', {})\n      const packages = (Array.isArray(library.packages) ? library.packages : []) as { pkg_id: string; templates?: { id: string; params?: Record<string, { type?: string }> }[] }[]\n      const found = packages.find((p) => p.pkg_id === pkg_id)?.templates?.find((t) => t.id === template_id)\n      if (!found) throw new UsageError('AIWS_USAGE', `${target} is not a template of your library (aiws template list)`)\n      params = createParams(param, found.params ?? {})\n    }\n    const title = inputString(input, 'title')\n    return aiws(ctx, 'ext.create_from_template', { pkg_id, template_id, ...(title ? { title } : {}), ...(params ? { params } : {}) })\n  },\n}\n\nconst selectNameCommand: CommandDefinition = {\n  verb: 'select-name', summary: 'Choose the workspace that keeps a conflicting personal name',\n  positionals: [{ name: 'name', description: 'Conflicting workspace name', required: true }],\n  options: [WORKSPACE_OPTION], inputSchema: workspaceInput({ name: { type: 'string', minLength: 1 } }, ['name']),\n  outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: WRITE_ACCESS, asyncMode: 'sync', requiresSession: true,\n  examples: ['buckyos aiws select-name schedule --workspace ws_2611a123'],\n  handler: (ctx, input) => aiws(ctx, 'ws.select_name', input),\n}\n\nexport function createAiwsModule(): CommandModule {\n  return {\n    name: 'aiws',\n    summary: 'AI Workspace: find and read a workspace by path (ls, find, grep, stat, cat, resolve, read), its permissions (acl, acl-edit), query its tables in SQL (sql), write tables, rich text and common properties (table, text, mv, rename, set-prop), resolve conflicting workspace names (select-name), Block-controls (catalogue, import, export), extension controls (build, pull, export, library, import, upgrade), Workspace templates (list, create, export), and execute wish runs as their executor (claim, heartbeat, report) or roll one back',\n    commands: [infoCommand, selectNameCommand, lsCommand, findCommand, grepCommand, statCommand, aclCommand, aclEditCommand, catCommand, resolveCommand, readCommand, sqlCommand, tableCommand, textCommand, mvCommand, renameCommand, setPropCommand, placeCommand, controlsCommand, importCommand, exportCommand, buildCommand, pullCommand, extExportCommand, libraryCommand, extImportCommand, extUpgradeCommand, templateCommand, runGetCommand, runClaimCommand, runHeartbeatCommand, runFilesCommand, runToolCommand, runExecCommand, runProgramCommand, runReportCommand, runRollbackCommand, runStartCommand],\n  }\n}\n","import type { GlobalOptions } from './argv.ts'\nimport { parseCommandArgs, parseDuration, parseInvocation, validateSchema } from './argv.ts'\nimport { AuthenticationSession, type SessionController } from './auth.ts'\nimport type { RegisteredCommand } from './command.ts'\nimport {\n  type ConfigStore,\n  type Environment,\n  type ImplicitDeviceIdentity,\n  localResolvedConfig,\n  readEnvironment,\n  resolveConfig,\n  type ResolvedConfig,\n} from './config.ts'\nimport type { CommandContext } from './context.ts'\nimport { EXIT_PERMISSION, EXIT_SUCCESS, normalizeError, ToolError, UsageError } from './errors.ts'\nimport { applyImplicitDeviceIdentity, identityCandidateView } from './identity.ts'\nimport { errorEnvelope, renderError, renderSuccess, successEnvelope } from './output.ts'\nimport { CommandRegistry } from './registry.ts'\nimport { runRepl } from './repl.ts'\nimport {\n  BuckyOSRuntimeAdapter,\n  BuckyOSServiceClientRegistry,\n  InteractiveSession,\n  type RuntimeAdapter,\n  type ServiceClientRegistry,\n} from './runtime.ts'\nimport { createAuthModule } from '../modules/auth.ts'\nimport { createCoreModules } from '../modules/core.ts'\nimport { createSystemModule } from '../modules/system.ts'\nimport { createSystemConfigModule } from '../modules/system_config.ts'\nimport { createPikgModule, type PikgModuleDependencies } from '../modules/pikg.ts'\nimport { type AppModuleDependencies, createAppModule } from '../modules/app.ts'\nimport { createDiagnosticModule, type DiagnosticModuleDependencies } from '../modules/diagnostic.ts'\nimport { createLogModule, type LogModuleDependencies } from '../modules/log.ts'\nimport { createTaskModule } from '../modules/task.ts'\nimport { createProvisionModule, type ProvisionModuleDependencies } from '../modules/provision.ts'\nimport { createSkillModule } from '../modules/skill.ts'\nimport { createAgentModule } from '../modules/agent.ts'\nimport { createAiModule } from '../modules/ai.ts'\nimport { createShareModule } from '../modules/share.ts'\nimport { createBucketModule } from '../modules/bucket.ts'\nimport { createObjModule } from '../modules/obj.ts'\nimport { createExecutorModule } from '../modules/executor.ts'\nimport { createExtToolsModule } from '../modules/ext_tools.ts'\nimport { createRuntimeModule } from '../modules/runtime.ts'\nimport { createAiwsModule } from '../modules/aiws.ts'\nimport {\n  distributionManifestView,\n  getHost,\n  policyView,\n  readDistributionManifest,\n} from '../runtime/host.ts'\nimport { PROTOCOL_VERSION, SDK_VERSION, TOOL_VERSION } from '../version.ts'\n\nexport const VERSION = TOOL_VERSION\n\nexport interface ToolStdio {\n  stdout(value: string): Promise<void>\n  stderr(value: string): Promise<void>\n  readStdin(): Promise<string>\n  prompt?(message: string): Promise<string | null>\n  inputIsTerminal?(): boolean\n}\n\nexport interface ApplicationDependencies {\n  environment?: Environment\n  cwd?: string\n  homeDir?: string\n  stdio?: ToolStdio\n  createAuthentication?: (config: ResolvedConfig) => SessionController\n  runtime?: RuntimeAdapter\n  createClients?: (\n    config: ResolvedConfig,\n    authentication: SessionController,\n  ) => ServiceClientRegistry\n  confirmDeviceIdentity?: (identity: ImplicitDeviceIdentity) => Promise<boolean>\n  repl?: typeof runRepl\n  pikg?: PikgModuleDependencies\n  app?: AppModuleDependencies\n  log?: LogModuleDependencies\n  diagnostic?: DiagnosticModuleDependencies\n  provision?: ProvisionModuleDependencies\n}\n\nexport class BuckyOSToolApplication {\n  readonly registry: CommandRegistry\n  readonly #environment: Environment\n  readonly #cwd: string\n  readonly #homeDir?: string\n  readonly #stdio: ToolStdio\n  readonly #createAuthentication: (config: ResolvedConfig) => SessionController\n  readonly #runtime: RuntimeAdapter\n  readonly #createClients: (\n    config: ResolvedConfig,\n    authentication: SessionController,\n  ) => ServiceClientRegistry\n  readonly #confirmDeviceIdentity: (identity: ImplicitDeviceIdentity) => Promise<boolean>\n  readonly #repl: typeof runRepl\n\n  constructor(dependencies: ApplicationDependencies = {}) {\n    this.registry = createRegistry(\n      dependencies.pikg,\n      dependencies.app,\n      dependencies.log,\n      dependencies.diagnostic,\n      dependencies.provision,\n    )\n    this.#environment = dependencies.environment ?? readEnvironment()\n    this.#cwd = dependencies.cwd ?? getHost().cwd()\n    this.#homeDir = dependencies.homeDir\n    this.#stdio = dependencies.stdio ?? defaultStdio()\n    this.#createAuthentication = dependencies.createAuthentication ??\n      ((config) => new AuthenticationSession(config, this.#environment))\n    this.#runtime = dependencies.runtime ?? new BuckyOSRuntimeAdapter()\n    this.#createClients = dependencies.createClients ??\n      ((config, authentication) => new BuckyOSServiceClientRegistry(config, authentication))\n    this.#confirmDeviceIdentity = dependencies.confirmDeviceIdentity ?? confirmDeviceIdentity\n    this.#repl = dependencies.repl ?? runRepl\n  }\n\n  async run(argv: string[]): Promise<number> {\n    let fallbackTraceId: string = crypto.randomUUID()\n    try {\n      const invocation = parseInvocation(argv)\n      fallbackTraceId = invocation.global.traceId ?? fallbackTraceId\n      if (invocation.global.version) {\n        if (invocation.module) {\n          throw new UsageError('ARGUMENT_CONFLICT', '--version cannot be combined with a command')\n        }\n        if (invocation.global.verbose) {\n          const distributionManifest = await readDistributionManifest()\n          let identityCandidates: Record<string, unknown>\n          try {\n            const setup = await resolveConfig(invocation.global, this.#environment, {\n              cwd: this.#cwd,\n              homeDir: this.#homeDir,\n            })\n            setup.resolved = await applyImplicitDeviceIdentity(\n              setup.resolved,\n              this.#environment,\n            )\n            identityCandidates = await identityCandidateView(\n              setup.resolved,\n              this.#environment,\n            )\n          } catch (error) {\n            const normalized = normalizeError(error)\n            identityCandidates = { mode: 'unavailable', error: normalized.code }\n          }\n          await this.#stdio.stdout(`${\n            JSON.stringify(\n              {\n                buckyos: distributionManifest?.buckyos_version ?? null,\n                buckyos_build_id: distributionManifest?.build_id ?? null,\n                tool_version: TOOL_VERSION,\n                sdk_version: SDK_VERSION,\n                protocol_version: PROTOCOL_VERSION,\n                target_zone: invocation.global.zone ?? getHost().env('BUCKYOS_TOOL_ZONE') ?? null,\n                compatibility: 'not-checked',\n                ...policyView(getHost()),\n                identity_candidates: identityCandidates,\n                distribution_manifest: distributionManifestView(distributionManifest),\n              },\n              null,\n              2,\n            )\n          }\\n`)\n        } else {\n          await this.#stdio.stdout(`buckyos ${VERSION}\\n`)\n        }\n        return EXIT_SUCCESS\n      }\n      if (invocation.global.cli) {\n        return await this.#runInteractive(invocation.global, invocation.module, invocation.verb)\n      }\n      if (!invocation.module) {\n        if (invocation.global.help) {\n          await this.#stdio.stdout(`${topLevelHelp(this.registry)}\\n`)\n          return EXIT_SUCCESS\n        }\n        throw new UsageError('COMMAND_REQUIRED', 'a module and verb are required')\n      }\n      if (!invocation.verb || invocation.verb === '--help' || invocation.verb === '-h') {\n        await this.#stdio.stdout(`${moduleHelp(this.registry, invocation.module)}\\n`)\n        return EXIT_SUCCESS\n      }\n\n      const command = this.registry.get(invocation.module, invocation.verb)\n      if (\n        invocation.global.help || invocation.actionArgv.includes('--help') ||\n        invocation.actionArgv.includes('-h')\n      ) {\n        await this.#stdio.stdout(`${commandHelp(this.registry, command)}\\n`)\n        return EXIT_SUCCESS\n      }\n      if (command.execution === 'local') assertNoSessionOptions(invocation.global, command)\n      const setup = await this.#resolveForCommand(command, invocation.global)\n      const inputObject = invocation.global.input\n        ? await this.#readInputObject(invocation.global.input)\n        : undefined\n      const parsed = parseCommandArgs(command, invocation.actionArgv, inputObject)\n      if (setup.resolved.output === 'raw' && !command.supportsRawOutput) {\n        throw new UsageError(\n          'RAW_OUTPUT_UNSUPPORTED',\n          `${command.module} ${command.verb} does not support raw output`,\n        )\n      }\n      const session = command.requiresSession\n        ? await this.#createSession(setup.resolved)\n        : undefined\n      return await this.#executeAndEmit(\n        command,\n        parsed.input,\n        setup.resolved,\n        setup.store,\n        session,\n        false,\n        new AbortController().signal,\n      )\n    } catch (error) {\n      const normalized = normalizeError(error)\n      const envelope = errorEnvelope(normalized, { command: 'core', trace_id: fallbackTraceId })\n      await this.#stdio.stdout(`${renderError(envelope, 'json')}\\n`)\n      return normalized.exitCode\n    }\n  }\n\n  async #runInteractive(global: GlobalOptions, module?: string, verb?: string): Promise<number> {\n    if (module || verb) {\n      throw new UsageError('ARGUMENT_CONFLICT', '--cli cannot be combined with a module or verb')\n    }\n    if (global.nonInteractive) {\n      throw new UsageError('ARGUMENT_CONFLICT', '--cli conflicts with --non-interactive')\n    }\n    for (\n      const [name, value] of [\n        ['input', global.input],\n        ['timeout', global.timeout],\n        ['trace-id', global.traceId],\n        ['idempotency-key', global.idempotencyKey],\n        ['wait', global.wait],\n        ['yes', global.yes],\n      ] as const\n    ) {\n      if (value !== undefined) {\n        throw new UsageError(\n          'ARGUMENT_CONFLICT',\n          `--${name} is command-scoped and cannot be set when entering --cli`,\n        )\n      }\n    }\n    const setup = await resolveConfig(global, this.#environment, {\n      interactive: true,\n      cwd: this.#cwd,\n      homeDir: this.#homeDir,\n    })\n    setup.resolved = await applyImplicitDeviceIdentity(setup.resolved, this.#environment)\n    const session = await this.#createSession(setup.resolved)\n    await this.#repl({\n      registry: this.registry,\n      config: setup.resolved,\n      configStore: setup.store,\n      session,\n      execute: async (tokens, signal) =>\n        await this.#executeInteractiveLine(tokens, signal, setup.resolved, setup.store, session),\n    })\n    return EXIT_SUCCESS\n  }\n\n  async #executeInteractiveLine(\n    tokens: string[],\n    signal: AbortSignal,\n    frozen: ResolvedConfig,\n    store: ConfigStore,\n    session: InteractiveSession,\n  ): Promise<void> {\n    if (tokens.length < 2) throw new UsageError('COMMAND_REQUIRED', 'enter <module> <verb>')\n    const command = this.registry.get(tokens[0], tokens[1])\n    const actionArgv = tokens.slice(2)\n    if (actionArgv.includes('--help') || actionArgv.includes('-h')) {\n      await this.#stdio.stdout(`${commandHelp(this.registry, command)}\\n`)\n      return\n    }\n    const preliminary = parseCommandArgs(command, actionArgv, undefined, true, true)\n    if (preliminary.scoped.input === '-') {\n      throw new UsageError('STDIN_UNAVAILABLE', '--input - is not available inside --cli')\n    }\n    const inputObject = preliminary.scoped.input\n      ? await this.#readInputObject(preliminary.scoped.input)\n      : undefined\n    const parsed = parseCommandArgs(command, actionArgv, inputObject, true)\n    const config: ResolvedConfig = {\n      ...frozen,\n      output: parsed.scoped.output ?? frozen.output,\n      timeoutMs: parsed.scoped.timeout ? parseDuration(parsed.scoped.timeout) : frozen.timeoutMs,\n      traceId: parsed.scoped.traceId,\n      idempotencyKey: parsed.scoped.idempotencyKey,\n      wait: parsed.scoped.wait ?? false,\n      yes: parsed.scoped.yes ?? false,\n    }\n    if (config.output === 'raw' && !command.supportsRawOutput) {\n      throw new UsageError(\n        'RAW_OUTPUT_UNSUPPORTED',\n        `${command.module} ${command.verb} does not support raw output`,\n      )\n    }\n    await this.#executeAndEmit(command, parsed.input, config, store, session, true, signal)\n  }\n\n  async #executeAndEmit(\n    command: RegisteredCommand,\n    input: Record<string, unknown>,\n    config: ResolvedConfig,\n    store: ConfigStore,\n    session: InteractiveSession | undefined,\n    interactive: boolean,\n    signal: AbortSignal,\n  ): Promise<number> {\n    const traceId = config.traceId ?? crypto.randomUUID()\n    const startedAt = Date.now()\n    try {\n      if (command.requiresSession && !session) {\n        throw new ToolError('AUTH_REQUIRED', 'authenticated session is required', 3)\n      }\n      if (command.requiresSession) await session!.authentication.ensureValid()\n      const principal = session?.authentication.current().principal ?? {\n        id: 'local',\n        appId: 'buckyos-tool',\n        authentication: 'mock' as const,\n      }\n      const context: CommandContext = {\n        command: { module: command.module, verb: command.verb },\n        definition: command,\n        connection: session?.connection ?? {\n          zone: config.zone ?? 'local',\n          endpoint: config.endpoint ?? 'local://',\n          defaultProtocol: config.defaultProtocol,\n        },\n        principal,\n        clients: session?.clients ?? unavailableClients,\n        output: { format: config.output },\n        traceId,\n        idempotencyKey: config.idempotencyKey,\n        deadline: Date.now() + config.timeoutMs,\n        signal,\n        cwd: this.#cwd,\n        io: {\n          stdout: (value) => this.#stdio.stdout(value),\n          stderr: (value) => this.#stdio.stderr(value),\n          prompt: (message) => this.#stdio.prompt?.(message) ?? Promise.resolve(null),\n          inputIsTerminal: this.#stdio.inputIsTerminal?.() ?? false,\n        },\n        interactive,\n        confirmed: config.yes,\n        config,\n        configStore: store,\n        session: session?.authentication,\n      }\n      const data = await command.handler(context, input)\n      try {\n        validateSchema(data, command.outputSchema, 'output')\n      } catch (error) {\n        throw new ToolError(\n          'INVALID_HANDLER_OUTPUT',\n          error instanceof Error ? error.message : String(error),\n          9,\n        )\n      }\n      if (command.module === 'obj' && command.verb === 'call') return (data as { exit_code: number }).exit_code\n      const envelope = successEnvelope(data, {\n        command: `${command.module}.${command.verb}`,\n        trace_id: traceId,\n        duration_ms: Date.now() - startedAt,\n      })\n      await this.#stdio.stdout(\n        `${renderSuccess(envelope, config.output)}${config.output === 'raw' ? '' : '\\n'}`,\n      )\n      return EXIT_SUCCESS\n    } catch (error) {\n      const normalized = normalizeError(error)\n      const envelope = errorEnvelope(normalized, {\n        command: `${command.module}.${command.verb}`,\n        trace_id: traceId,\n        duration_ms: Date.now() - startedAt,\n      })\n      await this.#stdio.stdout(`${renderError(envelope, config.output)}\\n`)\n      if (config.verbose) await this.#stdio.stderr(`diagnostic: ${normalized.code}\\n`)\n      return normalized.exitCode\n    }\n  }\n\n  async #resolveForCommand(\n    command: RegisteredCommand,\n    global: GlobalOptions,\n  ): Promise<{ resolved: ResolvedConfig; store: ConfigStore }> {\n    if (command.requiresSession || (command.module === 'config' && command.verb === 'check')) {\n      const setup = await resolveConfig(global, this.#environment, {\n        cwd: this.#cwd,\n        homeDir: this.#homeDir,\n      })\n      if (command.requiresSession) {\n        setup.resolved = await applyImplicitDeviceIdentity(setup.resolved, this.#environment)\n      }\n      return setup\n    }\n    return localResolvedConfig(global, this.#environment, {\n      cwd: this.#cwd,\n      homeDir: this.#homeDir,\n    })\n  }\n\n  async #createSession(config: ResolvedConfig): Promise<InteractiveSession> {\n    await this.#approveImplicitDeviceIdentity(config)\n    const authentication = this.#createAuthentication(config)\n    return await InteractiveSession.create(\n      config,\n      authentication,\n      this.#runtime,\n      this.#createClients(config, authentication),\n    )\n  }\n\n  async #approveImplicitDeviceIdentity(config: ResolvedConfig): Promise<void> {\n    const identity = config.implicitDeviceIdentity\n    if (!identity || config.yes) return\n    if (config.nonInteractive) {\n      throw new ToolError(\n        'CONFIRMATION_REQUIRED',\n        'using the current device identity requires --yes in non-interactive mode',\n        EXIT_PERMISSION,\n        false,\n        { identity: identity.did },\n      )\n    }\n    if (!await this.#confirmDeviceIdentity(identity)) {\n      throw new ToolError(\n        'CONFIRMATION_DECLINED',\n        'current device identity confirmation was declined',\n        EXIT_PERMISSION,\n        false,\n        { identity: identity.did },\n      )\n    }\n  }\n\n  async #readInputObject(path: string): Promise<Record<string, unknown>> {\n    let raw: string\n    try {\n      raw = path === '-' ? await this.#stdio.readStdin() : await getHost().readTextFile(path)\n    } catch (error) {\n      throw new UsageError(\n        'INPUT_READ_FAILED',\n        `failed to read input: ${error instanceof Error ? error.message : String(error)}`,\n      )\n    }\n    let parsed: unknown\n    try {\n      parsed = JSON.parse(raw)\n    } catch {\n      throw new UsageError('INVALID_INPUT_JSON', 'input is not valid JSON')\n    }\n    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n      throw new UsageError('INVALID_INPUT_JSON', 'input JSON must be an object')\n    }\n    return parsed as Record<string, unknown>\n  }\n}\n\nexport function createRegistry(\n  pikgDependencies?: PikgModuleDependencies,\n  appDependencies?: AppModuleDependencies,\n  logDependencies?: LogModuleDependencies,\n  diagnosticDependencies?: DiagnosticModuleDependencies,\n  provisionDependencies?: ProvisionModuleDependencies,\n): CommandRegistry {\n  const registry = new CommandRegistry()\n  for (const module of createCoreModules(registry)) registry.register(module)\n  registry.register(createAuthModule())\n  registry.register(createPikgModule(pikgDependencies))\n  registry.register(createSystemModule())\n  registry.register(createSystemConfigModule())\n  registry.register(createAppModule(appDependencies))\n  registry.register(createTaskModule())\n  registry.register(createLogModule(logDependencies))\n  registry.register(createDiagnosticModule(diagnosticDependencies))\n  registry.register(createProvisionModule(provisionDependencies))\n  registry.register(createSkillModule())\n  registry.register(createAgentModule())\n  registry.register(createAiModule())\n  registry.register(createShareModule())\n  registry.register(createBucketModule())\n  registry.register(createObjModule())\n  registry.register(createExecutorModule())\n  registry.register(createExtToolsModule())\n  registry.register(createRuntimeModule())\n  registry.register(createAiwsModule())\n  return registry\n}\n\n// Commands that declare execution=local run without a Zone, profile, identity,\n// or network; online-only session options must not silently retarget them.\nfunction assertNoSessionOptions(global: GlobalOptions, command: RegisteredCommand): void {\n  for (\n    const [name, value] of [\n      ['profile', global.profile],\n      ['zone', global.zone],\n      ['endpoint', global.endpoint],\n      ['identity', global.identity],\n      ['session-token', global.sessionToken],\n      ['session-token-file', global.sessionTokenFile],\n    ] as const\n  ) {\n    if (value !== undefined) {\n      throw new UsageError(\n        'ARGUMENT_CONFLICT',\n        `--${name} cannot be combined with the local command ${command.module} ${command.verb}`,\n      )\n    }\n  }\n}\n\nconst unavailableClients: ServiceClientRegistry = {\n  call: () => Promise.reject(new ToolError('INTERNAL_ERROR', 'service clients are unavailable', 9)),\n}\n\nfunction topLevelHelp(registry: CommandRegistry): string {\n  return [\n    `BuckyOS Tool ${VERSION}`,\n    '',\n    'Usage:',\n    '  buckyos [global-options] <module> <verb> [primary-selector] [action-options]',\n    '  buckyos [session-options] --cli',\n    '',\n    'Modules:',\n    ...registry.modules().map((module) => `  ${module.name.padEnd(12)} ${module.summary}`),\n    '',\n    'Global options:',\n    '  --config-dir <path>  --profile <name>  --zone <host-or-did>',\n    '  --allow-read <path>  Add a readable filesystem root (repeatable)',\n    '  --endpoint <url>      --identity <did-or-name>',\n    '  --session-token <token> | --session-token-file <path>',\n    '    Prefer --session-token-file for automation; argv tokens may appear in process listings.',\n    '  --output <json|jsonl|table|text|raw>  --input <path|->',\n    '  --timeout <duration>  --trace-id <id>  --non-interactive  --yes',\n    '  --cli  --help  --version',\n    '',\n    'Use `buckyos command describe <module> <verb>` for machine-readable schemas.',\n  ].join('\\n')\n}\n\nfunction moduleHelp(registry: CommandRegistry, moduleName: string): string {\n  const module = registry.modules().find((candidate) => candidate.name === moduleName)\n  if (!module) throw new UsageError('UNKNOWN_MODULE', `unknown module: ${moduleName}`)\n  return [\n    `${module.name}: ${module.summary}`,\n    '',\n    'Commands:',\n    ...module.commands.map((command) => `  ${command.verb.padEnd(18)} ${command.summary}`),\n  ].join('\\n')\n}\n\nfunction commandHelp(registry: CommandRegistry, command: RegisteredCommand): string {\n  return [\n    command.summary,\n    '',\n    `Usage: ${registry.syntax(command)}`,\n    ...(command.description ? ['', command.description] : []),\n    ...((command.positionals?.length ?? 0) > 0\n      ? [\n        '',\n        'Arguments:',\n        ...command.positionals!.map((position) =>\n          `  ${position.name.padEnd(20)} ${position.description}`\n        ),\n      ]\n      : []),\n    ...((command.options?.length ?? 0) > 0\n      ? [\n        '',\n        'Options:',\n        ...command.options!.map((option) => `  --${option.name.padEnd(18)} ${option.description}`),\n      ]\n      : []),\n    ...((command.examples?.length ?? 0) > 0\n      ? ['', 'Examples:', ...command.examples!.map((example) => `  ${example}`)]\n      : []),\n  ].join('\\n')\n}\n\nfunction defaultStdio(): ToolStdio {\n  return {\n    stdout: async (value) => await getHost().stdout(value),\n    stderr: async (value) => await getHost().stderr(value),\n    readStdin: async () => await getHost().readStdin(),\n    prompt: async (message) => await getHost().readLine(message),\n    inputIsTerminal: () => getHost().inputIsTerminal(),\n  }\n}\n\nasync function confirmDeviceIdentity(identity: ImplicitDeviceIdentity): Promise<boolean> {\n  if (!getHost().inputIsTerminal()) {\n    throw new ToolError(\n      'CONFIRMATION_REQUIRED',\n      'using the current device identity requires an interactive terminal or --yes',\n      EXIT_PERMISSION,\n      false,\n      { identity: identity.did },\n    )\n  }\n  const prompt = `Use current device identity ${identity.name} (${identity.did})? ` +\n    'This identity may have broad privileges. Continue? [y/N] '\n  const answer = (await getHost().readLine(prompt))?.trim() ?? ''\n  return answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes'\n}\n","import { BuckyOSToolApplication } from './core/app.ts'\nimport type { ToolHost } from './runtime/host.ts'\nimport { installHost } from './runtime/host.ts'\n\nexport async function runCli(host: ToolHost, argv: string[]): Promise<number> {\n  installHost(host)\n  return await new BuckyOSToolApplication().run(argv)\n}\n","// Windows MoveFileEx returns EPERM or EBUSY while a scanner still has a new\n// file open, and also when a directory rename lands on an existing directory.\n// A short retry covers the transient lock. The caller decides when to stop.\nexport async function retryWindowsLock<T>(\n  windows: boolean,\n  operation: () => Promise<T>,\n  retryable: (error: unknown) => boolean,\n  wait: (attempt: number) => number = defaultWait,\n): Promise<T> {\n  let attempt = 0\n  while (true) {\n    try {\n      return await operation()\n    } catch (error) {\n      const delay = windows && retryable(error) ? wait(attempt) : 0\n      if (delay <= 0) throw error\n      attempt++\n      await new Promise((resolve) => setTimeout(resolve, delay))\n    }\n  }\n}\n\nfunction defaultWait(attempt: number): number {\n  const waits = [50, 100, 150, 250, 400, 600, 800]\n  return waits[attempt] ?? 0\n}\n","import { type DistributionPolicy, HostError, type HostPath, isHostError } from './host.ts'\n\nexport async function assertPathAccess(\n  policy: DistributionPolicy,\n  path: HostPath,\n  realPath: (value: string) => Promise<string>,\n  candidate: string,\n  operation: 'read' | 'write',\n  resolveLinks = true,\n): Promise<void> {\n  const roots = operation === 'read' ? policy.readPaths : policy.writePaths\n  const absolute = path.resolve(candidate)\n  const physicalRoots: string[] = []\n  for (const root of roots) {\n    try {\n      physicalRoots.push(await realPath(path.resolve(root)))\n    } catch (error) {\n      if (!isHostError(error, 'NotFound') && !isHostError(error, 'PermissionDenied')) throw error\n    }\n  }\n  if (!insideAny(absolute, roots, path) && !insideAny(absolute, physicalRoots, path)) {\n    throw new HostError(\n      'PermissionDenied',\n      `${operation} access is outside ${policy.name}: ${absolute}`,\n      absolute,\n    )\n  }\n  if (!resolveLinks) return\n  try {\n    const physical = await realPath(absolute)\n    if (!insideAny(physical, physicalRoots, path)) {\n      throw new HostError(\n        'PermissionDenied',\n        `${operation} access escapes ${policy.name}: ${absolute}`,\n        absolute,\n      )\n    }\n  } catch (error) {\n    if (!isHostError(error, 'NotFound')) throw error\n  }\n}\n\nfunction insideAny(candidate: string, roots: readonly string[], path: HostPath): boolean {\n  return roots.some((root) => {\n    const relative = path.relative(path.resolve(root), candidate)\n    return relative === '' || relative !== '..' && !relative.startsWith(`..${path.sep}`) &&\n        !path.isAbsolute(relative)\n  })\n}\n","import { createHash as nodeCreateHash } from 'node:crypto'\nimport {\n  chmod,\n  copyFile,\n  lstat,\n  mkdir,\n  mkdtemp,\n  open,\n  readdir,\n  readFile,\n  realpath,\n  rename,\n  rm,\n  stat,\n  symlink,\n  writeFile,\n} from 'node:fs/promises'\nimport { createReadStream, createWriteStream, existsSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport * as nodePath from 'node:path'\nimport { spawn } from 'node:child_process'\nimport process from 'node:process'\nimport { createInterface } from 'node:readline/promises'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport { constants as zlibConstants, createGzip } from 'node:zlib'\nimport { retryWindowsLock } from './fs_retry.ts'\nimport { assertPathAccess } from './path_policy.ts'\nimport {\n  type DistributionPolicy,\n  HostError,\n  type HostChild,\n  type HostFile,\n  type HostFileInfo,\n  type HostLineReader,\n  type ToolHost,\n} from './host.ts'\n\nexport class NodeHost implements ToolHost {\n  readonly kind = 'node' as const\n  readonly runtimeName = 'node'\n  readonly runtimeVersion = process.versions.node\n  readonly platform = normalizePlatform(process.platform)\n  readonly arch = normalizeArch(process.arch)\n  readonly pid = process.pid\n  readonly executable = process.argv[1] ? nodePath.resolve(process.argv[1]) : process.execPath\n  readonly runtimeExecutable = process.execPath\n  readonly path = nodePath\n  readonly policy: DistributionPolicy\n\n  constructor(policy: DistributionPolicy) {\n    this.policy = policy\n  }\n\n  cwd(): string {\n    return process.cwd()\n  }\n\n  homeDir(): string {\n    return process.env.HOME ?? process.env.USERPROFILE ?? process.cwd()\n  }\n\n  env(name: string): string | undefined {\n    if (!this.policy.environment.includes(name)) {\n      throw new HostError('PermissionDenied', `environment access is not allowed: ${name}`)\n    }\n    return process.env[name]\n  }\n\n  exit(code: number): never {\n    process.exit(code)\n  }\n\n  setExitCode(code: number): void {\n    process.exitCode = code\n  }\n\n  async readTextFile(path: string): Promise<string> {\n    await this.assertPath(path, 'read')\n    try {\n      return await readFile(path, 'utf8')\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async readFile(path: string): Promise<Uint8Array> {\n    await this.assertPath(path, 'read')\n    try {\n      return new Uint8Array(await readFile(path))\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async writeTextFile(\n    path: string,\n    value: string,\n    options: { createNew?: boolean; mode?: number } = {},\n  ): Promise<void> {\n    await this.assertPath(path, 'write')\n    try {\n      await writeFile(path, value, {\n        flag: options.createNew ? 'wx' : 'w',\n        mode: options.mode,\n      })\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async writeFile(\n    path: string,\n    value: Uint8Array,\n    options: { createNew?: boolean; mode?: number } = {},\n  ): Promise<void> {\n    await this.assertPath(path, 'write')\n    try {\n      await writeFile(path, value, {\n        flag: options.createNew ? 'wx' : 'w',\n        mode: options.mode,\n      })\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async readDir(path: string) {\n    await this.assertPath(path, 'read')\n    try {\n      return (await readdir(path, { withFileTypes: true })).map((entry) => ({\n        name: entry.name,\n        isFile: entry.isFile(),\n        isDirectory: entry.isDirectory(),\n        isSymlink: entry.isSymbolicLink(),\n      }))\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async stat(path: string): Promise<HostFileInfo> {\n    await this.assertPath(path, 'read')\n    try {\n      return fileInfo(await stat(path))\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async lstat(path: string): Promise<HostFileInfo> {\n    await this.assertPath(path, 'read', false)\n    try {\n      return fileInfo(await lstat(path))\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async realPath(path: string): Promise<string> {\n    await this.assertPath(path, 'read')\n    try {\n      return await realpath(path)\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async makeTempDir(options: { dir?: string; prefix?: string } = {}): Promise<string> {\n    const directory = options.dir ?? tmpdir()\n    await this.assertPath(directory, 'write')\n    try {\n      return await mkdtemp(nodePath.join(directory, options.prefix ?? 'buckyos-'))\n    } catch (error) {\n      throw translateNodeError(error, directory)\n    }\n  }\n\n  async makeTempFile(options: { dir?: string; prefix?: string } = {}): Promise<string> {\n    const directory = await this.makeTempDir({ dir: options.dir, prefix: options.prefix })\n    const path = nodePath.join(directory, 'file')\n    await this.writeFile(path, new Uint8Array(), { createNew: true, mode: 0o600 })\n    return path\n  }\n\n  async rename(from: string, to: string): Promise<void> {\n    await this.assertPath(from, 'write')\n    await this.assertPath(to, 'write')\n    try {\n      await retryWindowsLock(\n        this.platform === 'windows',\n        () => rename(from, to),\n        nodeSharingViolation,\n      )\n    } catch (error) {\n      throw translateNodeError(error, `${from} -> ${to}`)\n    }\n  }\n\n  async remove(path: string, options: { recursive?: boolean } = {}): Promise<void> {\n    await this.assertPath(path, 'write', false)\n    try {\n      await retryWindowsLock(\n        this.platform === 'windows',\n        () => rm(path, { recursive: options.recursive ?? false }),\n        nodeSharingViolation,\n      )\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async mkdir(path: string, options: { recursive?: boolean; mode?: number } = {}): Promise<void> {\n    await this.assertPath(path, 'write', false)\n    try {\n      await mkdir(path, { recursive: options.recursive, mode: options.mode })\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async chmod(path: string, mode: number): Promise<void> {\n    await this.assertPath(path, 'write')\n    try {\n      await chmod(path, mode)\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async symlink(target: string, path: string): Promise<void> {\n    await this.assertPath(target, 'read')\n    await this.assertPath(path, 'write', false)\n    try {\n      await symlink(target, path)\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async copyFile(from: string, to: string): Promise<void> {\n    await this.assertPath(from, 'read')\n    await this.assertPath(to, 'write', false)\n    try {\n      await copyFile(from, to)\n    } catch (error) {\n      throw translateNodeError(error, `${from} -> ${to}`)\n    }\n  }\n\n  async open(\n    path: string,\n    options: { read?: boolean; write?: boolean; createNew?: boolean; mode?: number },\n  ): Promise<HostFile> {\n    await this.assertPath(path, options.write ? 'write' : 'read', !options.createNew)\n    const flags = options.read && options.write\n      ? 'r+'\n      : options.write\n      ? options.createNew ? 'wx' : 'w'\n      : 'r'\n    try {\n      return new NodeHostFile(await open(path, flags, options.mode))\n    } catch (error) {\n      throw translateNodeError(error, path)\n    }\n  }\n\n  async assertAccess(path: string, operation: 'read' | 'write'): Promise<void> {\n    await this.assertPath(path, operation)\n  }\n\n  createHash(_algorithm: 'sha256') {\n    const hash = nodeCreateHash('sha256')\n    return {\n      update(bytes: Uint8Array) {\n        hash.update(bytes)\n      },\n      digestHex() {\n        return hash.digest('hex')\n      },\n    }\n  }\n\n  async gzipFile(source: string, destination: string): Promise<void> {\n    await this.assertPath(source, 'read')\n    await this.assertPath(destination, 'write', false)\n    try {\n      await pipeline(\n        Readable.from(fixedChunks(createReadStream(source))),\n        createGzip({ level: 6, strategy: zlibConstants.Z_RLE }),\n        createWriteStream(destination, { flags: 'wx', mode: 0o600 }),\n      )\n    } catch (error) {\n      throw translateNodeError(error, destination)\n    }\n  }\n\n  async run(command: string, args: string[]) {\n    this.assertCommand(command)\n    return await capture(command, args)\n  }\n\n  spawn(command: string, args: string[], options: { cwd: string; env: Record<string, string> }): HostChild {\n    this.assertCommand(command)\n    // the child's environment is exactly `env`: the command is found on this process's PATH first\n    const resolved = command.includes(nodePath.sep) ? command\n      : (process.env.PATH ?? '').split(nodePath.delimiter).map((dir) => nodePath.join(dir, command)).find((p) => existsSync(p)) ?? command\n    const child = spawn(resolved, args, { cwd: options.cwd, env: options.env, stdio: ['pipe', 'pipe', 'pipe'], shell: false })\n    const errChunks: Uint8Array[] = []\n    child.stderr.on('data', (chunk) => errChunks.push(new Uint8Array(chunk)))\n    const status = childStatus(child)\n    return {\n      async *lines() {\n        let buf = ''\n        for await (const chunk of child.stdout) {\n          buf += new TextDecoder().decode(chunk as Uint8Array, { stream: true })\n          let i\n          while ((i = buf.indexOf('\\n')) >= 0) {\n            yield buf.slice(0, i)\n            buf = buf.slice(i + 1)\n          }\n        }\n        if (buf) yield buf\n      },\n      writeLine: (line: string) => new Promise<void>((resolve) => { child.stdin.write(line + '\\n', () => resolve()) }),\n      closeInput: () => new Promise<void>((resolve) => { child.stdin.end(() => resolve()) }),\n      stderr: status.then(() => new TextDecoder().decode(concat(errChunks))),\n      status,\n      kill: () => { child.kill('SIGKILL') },\n    }\n  }\n\n  async runGzip(command: string, args: string[], destination: string) {\n    this.assertCommand(command)\n    await this.assertPath(destination, 'write', false)\n    const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], shell: false })\n    const stderr: Uint8Array[] = []\n    child.stderr.on('data', (chunk) => stderr.push(new Uint8Array(chunk)))\n    try {\n      await pipeline(\n        Readable.from(fixedChunks(child.stdout)),\n        createGzip({ level: 6, strategy: zlibConstants.Z_RLE }),\n        createWriteStream(destination, { flags: 'wx', mode: 0o600 }),\n      )\n      const code = await childStatus(child)\n      return { success: code === 0, code, stdout: new Uint8Array(), stderr: concat(stderr) }\n    } catch (error) {\n      child.kill()\n      throw translateNodeError(error, destination)\n    }\n  }\n\n  async stdout(value: string | Uint8Array): Promise<void> {\n    await writeStream(process.stdout, value)\n  }\n\n  async stderr(value: string | Uint8Array): Promise<void> {\n    await writeStream(process.stderr, value)\n  }\n\n  async readStdin(): Promise<string> {\n    const chunks: Uint8Array[] = []\n    for await (const chunk of process.stdin) chunks.push(new Uint8Array(chunk))\n    return new TextDecoder().decode(concat(chunks))\n  }\n\n  async readLine(prompt: string): Promise<string | null> {\n    const reader = createInterface({ input: process.stdin, output: process.stderr })\n    try {\n      return await reader.question(prompt)\n    } catch {\n      return null\n    } finally {\n      reader.close()\n    }\n  }\n\n  async readSecret(prompt: string): Promise<string> {\n    if (!this.inputIsTerminal() || typeof process.stdin.setRawMode !== 'function') {\n      throw new HostError('PermissionDenied', 'secret input requires a terminal')\n    }\n    await this.stderr(prompt)\n    process.stdin.setRawMode(true)\n    process.stdin.resume()\n    const bytes: number[] = []\n    try {\n      while (true) {\n        const chunk = await readInputChunk()\n        if (chunk === null) break\n        const byte = chunk[0]\n        if (byte === 10 || byte === 13) break\n        if (byte === 3) throw new HostError('PermissionDenied', 'secret input canceled')\n        if (byte === 8 || byte === 127) bytes.pop()\n        else bytes.push(byte)\n      }\n    } finally {\n      process.stdin.setRawMode(false)\n      process.stdin.pause()\n      await this.stderr('\\n')\n    }\n    return new TextDecoder().decode(Uint8Array.from(bytes))\n  }\n\n  inputIsTerminal(): boolean {\n    return Boolean(process.stdin.isTTY)\n  }\n\n  createLineReader(options: {\n    history: string[]\n    historySize: number\n    completer(line: string): [string[], string]\n    onSigint(): void\n  }): HostLineReader {\n    const reader = createInterface({\n      input: process.stdin,\n      output: process.stderr,\n      terminal: true,\n      history: options.history,\n      historySize: options.historySize,\n      completer: options.completer,\n    })\n    reader.on('SIGINT', options.onSigint)\n    return {\n      [Symbol.asyncIterator]: () => reader[Symbol.asyncIterator](),\n      write: (value) => process.stderr.write(value),\n      setPrompt: (value) => reader.setPrompt(value),\n      prompt: () => reader.prompt(),\n      close: () => reader.close(),\n    }\n  }\n\n  private assertCommand(command: string): void {\n    if (!this.policy.subprocesses.includes(command)) {\n      throw new HostError('PermissionDenied', `subprocess is not allowed: ${command}`)\n    }\n  }\n\n  private async assertPath(\n    candidate: string,\n    operation: 'read' | 'write',\n    resolveLinks = true,\n  ): Promise<void> {\n    await assertPathAccess(\n      this.policy,\n      nodePath,\n      async (path) => {\n        try {\n          return await realpath(path)\n        } catch (error) {\n          throw translateNodeError(error, path)\n        }\n      },\n      candidate,\n      operation,\n      resolveLinks,\n    )\n  }\n}\n\nasync function* fixedChunks(\n  source: AsyncIterable<Uint8Array>,\n): AsyncGenerator<Uint8Array> {\n  const size = 64 * 1024\n  let pending = new Uint8Array(size)\n  let used = 0\n  for await (const chunk of source) {\n    let offset = 0\n    while (offset < chunk.byteLength) {\n      const copied = Math.min(size - used, chunk.byteLength - offset)\n      pending.set(chunk.subarray(offset, offset + copied), used)\n      used += copied\n      offset += copied\n      if (used === size) {\n        yield pending\n        pending = new Uint8Array(size)\n        used = 0\n      }\n    }\n  }\n  if (used > 0) yield pending.slice(0, used)\n}\n\nclass NodeHostFile implements HostFile {\n  readonly handle\n  #position = 0\n\n  constructor(handle: Awaited<ReturnType<typeof open>>) {\n    this.handle = handle\n  }\n\n  async read(buffer: Uint8Array): Promise<number | null> {\n    const result = await this.handle.read(buffer, 0, buffer.length, this.#position)\n    if (result.bytesRead === 0) return null\n    this.#position += result.bytesRead\n    return result.bytesRead\n  }\n\n  async write(buffer: Uint8Array): Promise<number> {\n    const result = await this.handle.write(buffer, 0, buffer.length, this.#position)\n    this.#position += result.bytesWritten\n    return result.bytesWritten\n  }\n\n  seek(offset: number): Promise<number> {\n    this.#position = offset\n    return Promise.resolve(offset)\n  }\n\n  async stat(): Promise<HostFileInfo> {\n    return fileInfo(await this.handle.stat())\n  }\n\n  async sync(): Promise<void> {\n    await this.handle.sync()\n  }\n\n  close(): Promise<void> {\n    return this.handle.close()\n  }\n}\n\nfunction fileInfo(value: {\n  isFile(): boolean\n  isDirectory(): boolean\n  isSymbolicLink(): boolean\n  size: number\n  mode: number\n  mtime: Date\n  dev: number\n  ino: number\n}): HostFileInfo {\n  return {\n    isFile: value.isFile(),\n    isDirectory: value.isDirectory(),\n    isSymlink: value.isSymbolicLink(),\n    size: value.size,\n    mode: value.mode ?? null,\n    mtime: value.mtime ?? null,\n    dev: value.dev ?? null,\n    ino: value.ino ?? null,\n  }\n}\n\nasync function capture(command: string, args: string[]) {\n  return await new Promise<{\n    success: boolean\n    code: number\n    stdout: Uint8Array\n    stderr: Uint8Array\n  }>((resolve, reject) => {\n    const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], shell: false })\n    const stdout: Uint8Array[] = []\n    const stderr: Uint8Array[] = []\n    child.stdout.on('data', (chunk) => stdout.push(new Uint8Array(chunk)))\n    child.stderr.on('data', (chunk) => stderr.push(new Uint8Array(chunk)))\n    child.once('error', reject)\n    child.once('close', (code) =>\n      resolve({\n        success: code === 0,\n        code: code ?? 1,\n        stdout: concat(stdout),\n        stderr: concat(stderr),\n      }))\n  })\n}\n\nasync function childStatus(child: ReturnType<typeof spawn>): Promise<number> {\n  if (child.exitCode !== null) return child.exitCode\n  return await new Promise((resolve, reject) => {\n    child.once('error', reject)\n    child.once('close', (code) => resolve(code ?? 1))\n  })\n}\n\nfunction concat(chunks: Uint8Array[]): Uint8Array {\n  const output = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0))\n  let offset = 0\n  for (const chunk of chunks) {\n    output.set(chunk, offset)\n    offset += chunk.length\n  }\n  return output\n}\n\nasync function writeStream(\n  stream: NodeJS.WritableStream,\n  value: string | Uint8Array,\n): Promise<void> {\n  await new Promise<void>((resolve, reject) => {\n    stream.write(value, (error?: Error | null) => error ? reject(error) : resolve())\n  })\n}\n\nasync function readInputChunk(): Promise<Uint8Array | null> {\n  return await new Promise((resolve, reject) => {\n    const onData = (chunk: Uint8Array) => done(new Uint8Array(chunk))\n    const onEnd = () => done(null)\n    const onError = (error: Error) => {\n      cleanup()\n      reject(error)\n    }\n    const cleanup = () => {\n      process.stdin.off('data', onData)\n      process.stdin.off('end', onEnd)\n      process.stdin.off('error', onError)\n    }\n    const done = (value: Uint8Array | null) => {\n      cleanup()\n      resolve(value)\n    }\n    process.stdin.once('data', onData)\n    process.stdin.once('end', onEnd)\n    process.stdin.once('error', onError)\n  })\n}\n\nfunction nodeSharingViolation(error: unknown): boolean {\n  const code = (error as { code?: string }).code\n  return code === 'EPERM' || code === 'EACCES' || code === 'EBUSY'\n}\n\nfunction translateNodeError(error: unknown, path?: string): HostError {\n  if (error instanceof HostError) return error\n  const code = (error as { code?: string }).code\n  const kind = code === 'ENOENT'\n    ? 'NotFound'\n    : code === 'EACCES' || code === 'EPERM'\n    ? 'PermissionDenied'\n    : code === 'EEXIST'\n    ? 'AlreadyExists'\n    : code === 'EINVAL'\n    ? 'InvalidInput'\n    : 'Unknown'\n  return new HostError(kind, error instanceof Error ? error.message : String(error), path, error)\n}\n\nfunction normalizePlatform(value: string): string {\n  return value === 'win32' ? 'windows' : value === 'darwin' ? 'macos' : value\n}\n\nfunction normalizeArch(value: string): string {\n  return value === 'x64' ? 'x86_64' : value === 'arm64' ? 'aarch64' : value\n}\n","import process from 'node:process'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, resolve } from 'node:path'\nimport { runCli } from '../main.ts'\nimport { buildDistributionPolicy, installHost, TOOL_ENVIRONMENT_NAMES } from './host.ts'\nimport { NodeHost } from './host_node.ts'\n\nconst packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../..')\nconst environment = Object.fromEntries(\n  TOOL_ENVIRONMENT_NAMES.map((name) => [name, process.env[name]]),\n)\nconst policy = buildDistributionPolicy({\n  runtimeExecutable: 'deno',\n  distribution: 'developer',\n  argv: process.argv.slice(2),\n  cwd: process.cwd(),\n  packageRoot,\n  homeDir: process.env.HOME ?? process.env.USERPROFILE ?? process.cwd(),\n  environment,\n  path: await import('node:path'),\n})\nconst host = new NodeHost(policy)\ninstallHost(host)\nhost.setExitCode(await runCli(host, process.argv.slice(2)))\n"],"names":["message","readOptionValue","value","parseShellLine","validateSchema","object","command","validateSchemaCore","parseShellLineCore","readOptionValueCore","host","packageRoot","environment","read","summary","dirname","isAbsolute","join","resolve","sessionToken","token","objects","module","SECRET_WORDS","EMPTY_INPUT","OBJECT_OUTPUT","optionalString","rpcOptions","expectObject","expectString","milliseconds","CONTROL_PANEL","buckyos","invalidResponse","relative","text","capture","take","view","stat","commentLength","realDirectory","basename","OBJECT_ID","normalizeArch","policy","aiws","ids","open","VERSION","buildCommand","resolveFromCwd","catalog","sourceSummary","packageMeta","info","abortableSleep","isObject","listCommand","getCommand","installCommand","cancelCommand","statusCommand","identifier","gatewayOrigin","id","body","exportCommand","compact","pageSchema","operation","AGENT_OPTION","confirm","importCommand","usage","invalid","given","ID","caps","settings","readCommand","DAY_MS","SERVICE","lsCommand","statCommand","call","resolveCommand","objectUrl","commit","table","markdown","doc","ops","r","c","setup","rename","nodeCreateHash","zlibConstants"],"mappings":";;;;;;;;;;;;;;;;AAAO,MAAM,eAAe;AACrB,MAAM,aAAa;AACnB,MAAM,YAAY;AAClB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AAEtB,MAAM,kBAAkB,MAAM;AAAA,EAMnC,YACE,MACAA,UACA,WAAW,gBACX,YAAY,OACZ,UAAmC,IACnC;AACA,UAAMA,QAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,YAAY;AACjB,SAAK,UAAU;AAAA,EACjB;AACF;AAEO,MAAM,mBAAmB,UAAU;AAAA,EACxC,YAAY,MAAcA,UAAiB,UAAmC,CAAA,GAAI;AAChF,UAAM,MAAMA,UAAS,YAAY,OAAO,OAAO;AAAA,EACjD;AACF;AAEA,MAAM,cAAc;AACpB,MAAM,yBAAyB;AAC/B,MAAM,uBACJ;AAEK,SAAS,gBAAgBA,UAAyB;AACvD,SAAOA,SACJ,WAAW,aAAa,kBAAkB,EAC1C,WAAW,wBAAwB,eAAe,EAClD,WAAW,sBAAsB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