{
  "version": 3,
  "sources": ["../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js", "../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js", "../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js", "../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js", "../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js", "../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js", "../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js", "../../core/src/adapter.ts", "../../core/src/registry-api.ts", "../../../node_modules/.pnpm/fflate@0.8.3/node_modules/fflate/esm/index.mjs", "../../protocol/dist/bundle.js", "../../protocol/dist/zip.js", "../../protocol/dist/inline-images.js", "../../protocol/dist/constants.js", "../../protocol/dist/artifact-schema.js", "../../protocol/dist/import-classify.js", "../../protocol/dist/requires.js", "../../protocol/dist/delegation.js", "../../protocol/dist/bundle-signature.js", "../../protocol/dist/key-bind.js", "../../protocol/dist/reserved-handles.js", "../../protocol/dist/slugify.js", "../../protocol/dist/reserved-skill-slugs.js", "../../protocol/dist/triggers.js", "../../protocol/dist/scan-vocabulary.js", "../../protocol/dist/eval.js", "../../protocol/dist/attention-events.js", "../../protocol/dist/device-sync-events.js", "../../protocol/dist/covers.js", "../../protocol/dist/index.js", "../../core/src/bundle/read.ts", "../../protocol/dist/skill-id.js", "../../core/src/util/atomic.ts", "../../core/src/util/pathsafe.ts", "../../core/src/bundle/write.ts", "../../../node_modules/.pnpm/kind-of@6.0.3/node_modules/kind-of/index.js", "../../../node_modules/.pnpm/is-extendable@0.1.1/node_modules/is-extendable/index.js", "../../../node_modules/.pnpm/extend-shallow@2.0.1/node_modules/extend-shallow/index.js", "../../../node_modules/.pnpm/section-matter@1.0.0/node_modules/section-matter/index.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/common.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/exception.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/mark.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/schema.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/str.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/seq.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/map.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/null.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/bool.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/int.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/float.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/schema/json.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/schema/core.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/timestamp.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/merge.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/binary.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/omap.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/pairs.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/set.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/type/js/function.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/schema/default_full.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/loader.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml/dumper.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/lib/js-yaml.js", "../../../node_modules/.pnpm/js-yaml@3.14.2/node_modules/js-yaml/index.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/lib/engines.js", "../../../node_modules/.pnpm/strip-bom-string@1.0.0/node_modules/strip-bom-string/index.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/lib/utils.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/lib/defaults.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/lib/engine.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/lib/stringify.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/lib/excerpt.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/lib/to-file.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/lib/parse.js", "../../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js", "../../core/src/bundle/zip.ts", "../../core/src/bundle/index.ts", "../../core/src/kit/types.ts", "../../core/src/kit/store.ts", "../../core/src/session-token.ts", "../../core/src/device-token.ts", "../../core/src/auth-token.ts", "../../core/src/metrics.ts", "../../core/src/kit/route-history.ts", "../../core/src/commands/route.ts", "../../core/src/registry/identifier.ts", "../../core/src/kit/manifest-match.ts", "../../core/src/kit/sync-scope.ts", "../../core/src/kit/skill-description.ts", "../../core/src/kit/index.ts", "../../core/src/util/unix-perms.ts", "../../core/src/identity/index.ts", "../../core/src/signing/index.ts", "../../core/src/machine-identity.ts", "../../core/src/registry/client.ts", "../../core/src/commands/claim.ts", "../../core/src/commands/login.ts", "../../core/src/signing/envelope.ts", "../../core/src/commands/publish.ts", "../../core/src/signing/pin.ts", "../../core/src/commands/edits-store.ts", "../../core/src/commands/import.ts", "../../core/src/commands/restore.ts", "../../core/src/commands/bundled-route-skill.ts", "../../core/src/kit/dedup-twins.ts", "../../core/src/util/hash.ts", "../../core/src/util/toml-lock.ts", "../../core/src/signing/session-attest.ts", "../../core/src/signing/delegation.ts", "../../core/src/lock.ts", "../../core/src/trust/diff.ts", "../../core/src/trust/approval-lock.ts", "../../core/src/trust/prompt.ts", "../../core/src/trust/quarantine.ts", "../../core/src/trust/policy.ts", "../../core/src/trust/index.ts", "../../core/src/registry/etag-cache.ts", "../../core/src/signing/pin-recovery.ts", "../../core/src/kit/store-integrity.ts", "../../core/src/registry/pull.ts", "../../core/src/registry/revoked-device-keys.ts", "../../core/src/registry/install-metric.ts", "../../core/src/commands/report-device-agents.ts", "../../core/src/kit/materialize-identity.ts", "../../core/src/commands/sync.ts", "../../core/src/commands/edits.ts", "../../core/src/commands/propose.ts", "../../core/src/commands/eval.ts", "../../core/src/github/spec.ts", "../../core/src/github/client.ts", "../../core/src/github/index.ts", "../../core/src/commands/import-github.ts", "../../core/src/commands/discover.ts", "../../core/src/commands/route-hooks/shared.ts", "../../core/src/commands/route-hooks/claude-code.ts", "../../core/src/commands/route-hooks/codex.ts", "../../core/src/commands/route-hooks/cursor.ts", "../../core/src/commands/route-hooks/runtime-specs.ts", "../../core/src/commands/route-hooks/index.ts", "../../core/src/commands/materialize-skills.ts", "../../core/src/commands/kit-add-materialize.ts", "../../core/src/commands/status.ts", "../../core/src/registry/kit-handle.ts", "../../core/src/registry/device-manifest.ts", "../../core/src/registry/index.ts", "../../core/src/commands/add.ts", "../../core/src/pair-code.ts", "../../core/src/registry/account-client.ts", "../../core/src/commands/pending.ts", "../../core/src/commands/approve.ts", "../../core/src/commands/reject.ts", "../../core/src/commands/auth-logout.ts", "../../core/src/commands/auth-disconnect.ts", "../../core/src/commands/auth-status.ts", "../../core/src/commands/doctor.ts", "../../core/src/machine-label.ts", "../../core/src/commands/auth-connect.ts", "../../core/src/commands/auth-connect-pair.ts", "../../core/src/commands/mint-pair-code.ts", "../../core/src/commands/team.ts", "../../core/src/commands/kit.ts", "../../core/src/commands/kit-bootstrap.ts", "../../core/src/commands/upload-skills.ts", "../../core/src/commands/kit-subscribe.ts", "../../core/src/commands/device.ts", "../../core/src/adapters/manifest.ts", "../../core/src/index.ts", "../../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js", "../../mcp/src/protocol.ts", "../../mcp/src/skill-path.ts", "../../mcp/src/store.ts", "../../mcp/src/resources.ts", "../../mcp/src/handler.ts", "../../mcp/src/loopback-token.ts", "../../mcp/src/auth.ts", "../../mcp/src/server.ts", "../../mcp/src/transport/stdio.ts", "../../mcp/src/transport/http.ts", "../../mcp/src/index.ts", "../../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs", "../src/index.ts", "../src/cli-colors.ts", "../src/cli-command-tier.ts", "../src/help/mcp-help.ts", "../src/help/leaf-extended-help.ts", "../src/help/root-surface.ts", "../src/help-format.ts", "../src/connected-sync.ts", "../../../node_modules/.pnpm/@clack+core@1.4.2/node_modules/@clack/core/dist/index.mjs", "../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js", "../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js", "../../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js", "../../../node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js", "../../../node_modules/.pnpm/@clack+prompts@1.6.0/node_modules/@clack/prompts/dist/index.mjs", "../src/cli-context.ts", "../../adapters/claude-code/src/index.ts", "../../adapters/codex/src/index.ts", "../../adapters/openclaw/src/index.ts", "../../adapters/hermes/src/index.ts", "../../adapters/cursor/src/index.ts", "../../adapters/windsurf/src/index.ts", "../../adapters/devin/src/index.ts", "../../adapters/opencode/src/index.ts", "../src/adapter-tiers.ts", "../src/route-hooks-consent.ts", "../src/skill-stats-copy.ts", "../src/bundled-route-path.ts", "../src/bundled-route-content.ts", "../src/pending-review-summary.ts", "../src/sanitize-output.ts", "../src/render-error.ts", "../src/home-menu.ts", "../src/cli-routing.ts", "../src/commands/add-cmd.ts", "../src/auth-required.ts", "../src/exit-codes.ts", "../src/json-output.ts", "../src/cli-add-present.ts", "../src/cli-add-adapters.ts", "../src/cli-add-source.ts", "../src/commands/import-cmd.ts", "../src/apply-to-agents.ts", "../src/commands/upload-present.ts", "../src/commands/auth.ts", "../src/open-browser-url.ts", "../src/commands/avatar.ts", "../src/commands/connect.ts", "../src/commands/doctor.ts", "../src/commands/edits.ts", "../src/commands/export.ts", "../src/commands/list.ts", "../src/kit-list-format.ts", "../src/list-json-format.ts", "../src/commands/mcp.ts", "../src/commands/pending.ts", "../src/commands/route-cmd.ts", "../src/commands/pair.ts", "../src/commands/eval.ts", "../src/commands/kit/index.ts", "../src/commands/login-legacy.ts", "../src/commands/propose.ts", "../src/commands/publish.ts", "../src/cli-deprecation.ts", "../src/commands/team/index.ts", "../src/commands/trust.ts", "../src/commands/register-management-commands.ts", "../src/commands/restore.ts", "../src/commands/status.ts", "../src/commands/sweep.ts", "../src/commands/sync.ts", "../src/sync-kit-plan.ts", "../src/sync-author-key-hint.ts", "../src/commands/runtimes.ts", "../src/commands/search.ts", "../src/commands/usage.ts", "../src/commands/activity.ts", "../src/commands/pin.ts", "../src/commands/update-mode.ts", "../src/commands/upload-cmd.ts", "../src/commands/web-cmd.ts", "../src/commands/register-all.ts", "../src/brand.ts"],
  "sourcesContent": ["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n  /**\n   * Constructs the CommanderError class\n   * @param {number} exitCode suggested exit code which could be used with process.exit\n   * @param {string} code an id string representing the error\n   * @param {string} message human-readable description of the error\n   */\n  constructor(exitCode, code, message) {\n    super(message);\n    // properly capture stack trace in Node.js\n    Error.captureStackTrace(this, this.constructor);\n    this.name = this.constructor.name;\n    this.code = code;\n    this.exitCode = exitCode;\n    this.nestedError = undefined;\n  }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n  /**\n   * Constructs the InvalidArgumentError class\n   * @param {string} [message] explanation of why argument is invalid\n   */\n  constructor(message) {\n    super(1, 'commander.invalidArgument', message);\n    // properly capture stack trace in Node.js\n    Error.captureStackTrace(this, this.constructor);\n    this.name = this.constructor.name;\n  }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n  /**\n   * Initialize a new command argument with the given name and description.\n   * The default is that the argument is required, and you can explicitly\n   * indicate this with <> around the name. Put [] around the name for an optional argument.\n   *\n   * @param {string} name\n   * @param {string} [description]\n   */\n\n  constructor(name, description) {\n    this.description = description || '';\n    this.variadic = false;\n    this.parseArg = undefined;\n    this.defaultValue = undefined;\n    this.defaultValueDescription = undefined;\n    this.argChoices = undefined;\n\n    switch (name[0]) {\n      case '<': // e.g. <required>\n        this.required = true;\n        this._name = name.slice(1, -1);\n        break;\n      case '[': // e.g. [optional]\n        this.required = false;\n        this._name = name.slice(1, -1);\n        break;\n      default:\n        this.required = true;\n        this._name = name;\n        break;\n    }\n\n    if (this._name.length > 3 && this._name.slice(-3) === '...') {\n      this.variadic = true;\n      this._name = this._name.slice(0, -3);\n    }\n  }\n\n  /**\n   * Return argument name.\n   *\n   * @return {string}\n   */\n\n  name() {\n    return this._name;\n  }\n\n  /**\n   * @package\n   */\n\n  _concatValue(value, previous) {\n    if (previous === this.defaultValue || !Array.isArray(previous)) {\n      return [value];\n    }\n\n    return previous.concat(value);\n  }\n\n  /**\n   * Set the default value, and optionally supply the description to be displayed in the help.\n   *\n   * @param {*} value\n   * @param {string} [description]\n   * @return {Argument}\n   */\n\n  default(value, description) {\n    this.defaultValue = value;\n    this.defaultValueDescription = description;\n    return this;\n  }\n\n  /**\n   * Set the custom handler for processing CLI command arguments into argument values.\n   *\n   * @param {Function} [fn]\n   * @return {Argument}\n   */\n\n  argParser(fn) {\n    this.parseArg = fn;\n    return this;\n  }\n\n  /**\n   * Only allow argument value to be one of choices.\n   *\n   * @param {string[]} values\n   * @return {Argument}\n   */\n\n  choices(values) {\n    this.argChoices = values.slice();\n    this.parseArg = (arg, previous) => {\n      if (!this.argChoices.includes(arg)) {\n        throw new InvalidArgumentError(\n          `Allowed choices are ${this.argChoices.join(', ')}.`,\n        );\n      }\n      if (this.variadic) {\n        return this._concatValue(arg, previous);\n      }\n      return arg;\n    };\n    return this;\n  }\n\n  /**\n   * Make argument required.\n   *\n   * @returns {Argument}\n   */\n  argRequired() {\n    this.required = true;\n    return this;\n  }\n\n  /**\n   * Make argument optional.\n   *\n   * @returns {Argument}\n   */\n  argOptional() {\n    this.required = false;\n    return this;\n  }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n  const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n  return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n", "const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n  constructor() {\n    this.helpWidth = undefined;\n    this.sortSubcommands = false;\n    this.sortOptions = false;\n    this.showGlobalOptions = false;\n  }\n\n  /**\n   * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n   *\n   * @param {Command} cmd\n   * @returns {Command[]}\n   */\n\n  visibleCommands(cmd) {\n    const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n    const helpCommand = cmd._getHelpCommand();\n    if (helpCommand && !helpCommand._hidden) {\n      visibleCommands.push(helpCommand);\n    }\n    if (this.sortSubcommands) {\n      visibleCommands.sort((a, b) => {\n        // @ts-ignore: because overloaded return type\n        return a.name().localeCompare(b.name());\n      });\n    }\n    return visibleCommands;\n  }\n\n  /**\n   * Compare options for sort.\n   *\n   * @param {Option} a\n   * @param {Option} b\n   * @returns {number}\n   */\n  compareOptions(a, b) {\n    const getSortKey = (option) => {\n      // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n      return option.short\n        ? option.short.replace(/^-/, '')\n        : option.long.replace(/^--/, '');\n    };\n    return getSortKey(a).localeCompare(getSortKey(b));\n  }\n\n  /**\n   * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n   *\n   * @param {Command} cmd\n   * @returns {Option[]}\n   */\n\n  visibleOptions(cmd) {\n    const visibleOptions = cmd.options.filter((option) => !option.hidden);\n    // Built-in help option.\n    const helpOption = cmd._getHelpOption();\n    if (helpOption && !helpOption.hidden) {\n      // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n      const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n      const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n      if (!removeShort && !removeLong) {\n        visibleOptions.push(helpOption); // no changes needed\n      } else if (helpOption.long && !removeLong) {\n        visibleOptions.push(\n          cmd.createOption(helpOption.long, helpOption.description),\n        );\n      } else if (helpOption.short && !removeShort) {\n        visibleOptions.push(\n          cmd.createOption(helpOption.short, helpOption.description),\n        );\n      }\n    }\n    if (this.sortOptions) {\n      visibleOptions.sort(this.compareOptions);\n    }\n    return visibleOptions;\n  }\n\n  /**\n   * Get an array of the visible global options. (Not including help.)\n   *\n   * @param {Command} cmd\n   * @returns {Option[]}\n   */\n\n  visibleGlobalOptions(cmd) {\n    if (!this.showGlobalOptions) return [];\n\n    const globalOptions = [];\n    for (\n      let ancestorCmd = cmd.parent;\n      ancestorCmd;\n      ancestorCmd = ancestorCmd.parent\n    ) {\n      const visibleOptions = ancestorCmd.options.filter(\n        (option) => !option.hidden,\n      );\n      globalOptions.push(...visibleOptions);\n    }\n    if (this.sortOptions) {\n      globalOptions.sort(this.compareOptions);\n    }\n    return globalOptions;\n  }\n\n  /**\n   * Get an array of the arguments if any have a description.\n   *\n   * @param {Command} cmd\n   * @returns {Argument[]}\n   */\n\n  visibleArguments(cmd) {\n    // Side effect! Apply the legacy descriptions before the arguments are displayed.\n    if (cmd._argsDescription) {\n      cmd.registeredArguments.forEach((argument) => {\n        argument.description =\n          argument.description || cmd._argsDescription[argument.name()] || '';\n      });\n    }\n\n    // If there are any arguments with a description then return all the arguments.\n    if (cmd.registeredArguments.find((argument) => argument.description)) {\n      return cmd.registeredArguments;\n    }\n    return [];\n  }\n\n  /**\n   * Get the command term to show in the list of subcommands.\n   *\n   * @param {Command} cmd\n   * @returns {string}\n   */\n\n  subcommandTerm(cmd) {\n    // Legacy. Ignores custom usage string, and nested commands.\n    const args = cmd.registeredArguments\n      .map((arg) => humanReadableArgName(arg))\n      .join(' ');\n    return (\n      cmd._name +\n      (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n      (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n      (args ? ' ' + args : '')\n    );\n  }\n\n  /**\n   * Get the option term to show in the list of options.\n   *\n   * @param {Option} option\n   * @returns {string}\n   */\n\n  optionTerm(option) {\n    return option.flags;\n  }\n\n  /**\n   * Get the argument term to show in the list of arguments.\n   *\n   * @param {Argument} argument\n   * @returns {string}\n   */\n\n  argumentTerm(argument) {\n    return argument.name();\n  }\n\n  /**\n   * Get the longest command term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  longestSubcommandTermLength(cmd, helper) {\n    return helper.visibleCommands(cmd).reduce((max, command) => {\n      return Math.max(max, helper.subcommandTerm(command).length);\n    }, 0);\n  }\n\n  /**\n   * Get the longest option term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  longestOptionTermLength(cmd, helper) {\n    return helper.visibleOptions(cmd).reduce((max, option) => {\n      return Math.max(max, helper.optionTerm(option).length);\n    }, 0);\n  }\n\n  /**\n   * Get the longest global option term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  longestGlobalOptionTermLength(cmd, helper) {\n    return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n      return Math.max(max, helper.optionTerm(option).length);\n    }, 0);\n  }\n\n  /**\n   * Get the longest argument term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  longestArgumentTermLength(cmd, helper) {\n    return helper.visibleArguments(cmd).reduce((max, argument) => {\n      return Math.max(max, helper.argumentTerm(argument).length);\n    }, 0);\n  }\n\n  /**\n   * Get the command usage to be displayed at the top of the built-in help.\n   *\n   * @param {Command} cmd\n   * @returns {string}\n   */\n\n  commandUsage(cmd) {\n    // Usage\n    let cmdName = cmd._name;\n    if (cmd._aliases[0]) {\n      cmdName = cmdName + '|' + cmd._aliases[0];\n    }\n    let ancestorCmdNames = '';\n    for (\n      let ancestorCmd = cmd.parent;\n      ancestorCmd;\n      ancestorCmd = ancestorCmd.parent\n    ) {\n      ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n    }\n    return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n  }\n\n  /**\n   * Get the description for the command.\n   *\n   * @param {Command} cmd\n   * @returns {string}\n   */\n\n  commandDescription(cmd) {\n    // @ts-ignore: because overloaded return type\n    return cmd.description();\n  }\n\n  /**\n   * Get the subcommand summary to show in the list of subcommands.\n   * (Fallback to description for backwards compatibility.)\n   *\n   * @param {Command} cmd\n   * @returns {string}\n   */\n\n  subcommandDescription(cmd) {\n    // @ts-ignore: because overloaded return type\n    return cmd.summary() || cmd.description();\n  }\n\n  /**\n   * Get the option description to show in the list of options.\n   *\n   * @param {Option} option\n   * @return {string}\n   */\n\n  optionDescription(option) {\n    const extraInfo = [];\n\n    if (option.argChoices) {\n      extraInfo.push(\n        // use stringify to match the display of the default value\n        `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n      );\n    }\n    if (option.defaultValue !== undefined) {\n      // default for boolean and negated more for programmer than end user,\n      // but show true/false for boolean option as may be for hand-rolled env or config processing.\n      const showDefault =\n        option.required ||\n        option.optional ||\n        (option.isBoolean() && typeof option.defaultValue === 'boolean');\n      if (showDefault) {\n        extraInfo.push(\n          `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n        );\n      }\n    }\n    // preset for boolean and negated are more for programmer than end user\n    if (option.presetArg !== undefined && option.optional) {\n      extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n    }\n    if (option.envVar !== undefined) {\n      extraInfo.push(`env: ${option.envVar}`);\n    }\n    if (extraInfo.length > 0) {\n      return `${option.description} (${extraInfo.join(', ')})`;\n    }\n\n    return option.description;\n  }\n\n  /**\n   * Get the argument description to show in the list of arguments.\n   *\n   * @param {Argument} argument\n   * @return {string}\n   */\n\n  argumentDescription(argument) {\n    const extraInfo = [];\n    if (argument.argChoices) {\n      extraInfo.push(\n        // use stringify to match the display of the default value\n        `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n      );\n    }\n    if (argument.defaultValue !== undefined) {\n      extraInfo.push(\n        `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n      );\n    }\n    if (extraInfo.length > 0) {\n      const extraDescripton = `(${extraInfo.join(', ')})`;\n      if (argument.description) {\n        return `${argument.description} ${extraDescripton}`;\n      }\n      return extraDescripton;\n    }\n    return argument.description;\n  }\n\n  /**\n   * Generate the built-in help text.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {string}\n   */\n\n  formatHelp(cmd, helper) {\n    const termWidth = helper.padWidth(cmd, helper);\n    const helpWidth = helper.helpWidth || 80;\n    const itemIndentWidth = 2;\n    const itemSeparatorWidth = 2; // between term and description\n    function formatItem(term, description) {\n      if (description) {\n        const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n        return helper.wrap(\n          fullText,\n          helpWidth - itemIndentWidth,\n          termWidth + itemSeparatorWidth,\n        );\n      }\n      return term;\n    }\n    function formatList(textArray) {\n      return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth));\n    }\n\n    // Usage\n    let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];\n\n    // Description\n    const commandDescription = helper.commandDescription(cmd);\n    if (commandDescription.length > 0) {\n      output = output.concat([\n        helper.wrap(commandDescription, helpWidth, 0),\n        '',\n      ]);\n    }\n\n    // Arguments\n    const argumentList = helper.visibleArguments(cmd).map((argument) => {\n      return formatItem(\n        helper.argumentTerm(argument),\n        helper.argumentDescription(argument),\n      );\n    });\n    if (argumentList.length > 0) {\n      output = output.concat(['Arguments:', formatList(argumentList), '']);\n    }\n\n    // Options\n    const optionList = helper.visibleOptions(cmd).map((option) => {\n      return formatItem(\n        helper.optionTerm(option),\n        helper.optionDescription(option),\n      );\n    });\n    if (optionList.length > 0) {\n      output = output.concat(['Options:', formatList(optionList), '']);\n    }\n\n    if (this.showGlobalOptions) {\n      const globalOptionList = helper\n        .visibleGlobalOptions(cmd)\n        .map((option) => {\n          return formatItem(\n            helper.optionTerm(option),\n            helper.optionDescription(option),\n          );\n        });\n      if (globalOptionList.length > 0) {\n        output = output.concat([\n          'Global Options:',\n          formatList(globalOptionList),\n          '',\n        ]);\n      }\n    }\n\n    // Commands\n    const commandList = helper.visibleCommands(cmd).map((cmd) => {\n      return formatItem(\n        helper.subcommandTerm(cmd),\n        helper.subcommandDescription(cmd),\n      );\n    });\n    if (commandList.length > 0) {\n      output = output.concat(['Commands:', formatList(commandList), '']);\n    }\n\n    return output.join('\\n');\n  }\n\n  /**\n   * Calculate the pad width from the maximum term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  padWidth(cmd, helper) {\n    return Math.max(\n      helper.longestOptionTermLength(cmd, helper),\n      helper.longestGlobalOptionTermLength(cmd, helper),\n      helper.longestSubcommandTermLength(cmd, helper),\n      helper.longestArgumentTermLength(cmd, helper),\n    );\n  }\n\n  /**\n   * Wrap the given string to width characters per line, with lines after the first indented.\n   * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.\n   *\n   * @param {string} str\n   * @param {number} width\n   * @param {number} indent\n   * @param {number} [minColumnWidth=40]\n   * @return {string}\n   *\n   */\n\n  wrap(str, width, indent, minColumnWidth = 40) {\n    // Full \\s characters, minus the linefeeds.\n    const indents =\n      ' \\\\f\\\\t\\\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff';\n    // Detect manually wrapped and indented strings by searching for line break followed by spaces.\n    const manualIndent = new RegExp(`[\\\\n][${indents}]+`);\n    if (str.match(manualIndent)) return str;\n    // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).\n    const columnWidth = width - indent;\n    if (columnWidth < minColumnWidth) return str;\n\n    const leadingStr = str.slice(0, indent);\n    const columnText = str.slice(indent).replace('\\r\\n', '\\n');\n    const indentString = ' '.repeat(indent);\n    const zeroWidthSpace = '\\u200B';\n    const breaks = `\\\\s${zeroWidthSpace}`;\n    // Match line end (so empty lines don't collapse),\n    // or as much text as will fit in column, or excess text up to first break.\n    const regex = new RegExp(\n      `\\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,\n      'g',\n    );\n    const lines = columnText.match(regex) || [];\n    return (\n      leadingStr +\n      lines\n        .map((line, i) => {\n          if (line === '\\n') return ''; // preserve empty lines\n          return (i > 0 ? indentString : '') + line.trimEnd();\n        })\n        .join('\\n')\n    );\n  }\n}\n\nexports.Help = Help;\n", "const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n  /**\n   * Initialize a new `Option` with the given `flags` and `description`.\n   *\n   * @param {string} flags\n   * @param {string} [description]\n   */\n\n  constructor(flags, description) {\n    this.flags = flags;\n    this.description = description || '';\n\n    this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n    this.optional = flags.includes('['); // A value is optional when the option is specified.\n    // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n    this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n    this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n    const optionFlags = splitOptionFlags(flags);\n    this.short = optionFlags.shortFlag;\n    this.long = optionFlags.longFlag;\n    this.negate = false;\n    if (this.long) {\n      this.negate = this.long.startsWith('--no-');\n    }\n    this.defaultValue = undefined;\n    this.defaultValueDescription = undefined;\n    this.presetArg = undefined;\n    this.envVar = undefined;\n    this.parseArg = undefined;\n    this.hidden = false;\n    this.argChoices = undefined;\n    this.conflictsWith = [];\n    this.implied = undefined;\n  }\n\n  /**\n   * Set the default value, and optionally supply the description to be displayed in the help.\n   *\n   * @param {*} value\n   * @param {string} [description]\n   * @return {Option}\n   */\n\n  default(value, description) {\n    this.defaultValue = value;\n    this.defaultValueDescription = description;\n    return this;\n  }\n\n  /**\n   * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n   * The custom processing (parseArg) is called.\n   *\n   * @example\n   * new Option('--color').default('GREYSCALE').preset('RGB');\n   * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n   *\n   * @param {*} arg\n   * @return {Option}\n   */\n\n  preset(arg) {\n    this.presetArg = arg;\n    return this;\n  }\n\n  /**\n   * Add option name(s) that conflict with this option.\n   * An error will be displayed if conflicting options are found during parsing.\n   *\n   * @example\n   * new Option('--rgb').conflicts('cmyk');\n   * new Option('--js').conflicts(['ts', 'jsx']);\n   *\n   * @param {(string | string[])} names\n   * @return {Option}\n   */\n\n  conflicts(names) {\n    this.conflictsWith = this.conflictsWith.concat(names);\n    return this;\n  }\n\n  /**\n   * Specify implied option values for when this option is set and the implied options are not.\n   *\n   * The custom processing (parseArg) is not called on the implied values.\n   *\n   * @example\n   * program\n   *   .addOption(new Option('--log', 'write logging information to file'))\n   *   .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n   *\n   * @param {object} impliedOptionValues\n   * @return {Option}\n   */\n  implies(impliedOptionValues) {\n    let newImplied = impliedOptionValues;\n    if (typeof impliedOptionValues === 'string') {\n      // string is not documented, but easy mistake and we can do what user probably intended.\n      newImplied = { [impliedOptionValues]: true };\n    }\n    this.implied = Object.assign(this.implied || {}, newImplied);\n    return this;\n  }\n\n  /**\n   * Set environment variable to check for option value.\n   *\n   * An environment variable is only used if when processed the current option value is\n   * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n   *\n   * @param {string} name\n   * @return {Option}\n   */\n\n  env(name) {\n    this.envVar = name;\n    return this;\n  }\n\n  /**\n   * Set the custom handler for processing CLI option arguments into option values.\n   *\n   * @param {Function} [fn]\n   * @return {Option}\n   */\n\n  argParser(fn) {\n    this.parseArg = fn;\n    return this;\n  }\n\n  /**\n   * Whether the option is mandatory and must have a value after parsing.\n   *\n   * @param {boolean} [mandatory=true]\n   * @return {Option}\n   */\n\n  makeOptionMandatory(mandatory = true) {\n    this.mandatory = !!mandatory;\n    return this;\n  }\n\n  /**\n   * Hide option in help.\n   *\n   * @param {boolean} [hide=true]\n   * @return {Option}\n   */\n\n  hideHelp(hide = true) {\n    this.hidden = !!hide;\n    return this;\n  }\n\n  /**\n   * @package\n   */\n\n  _concatValue(value, previous) {\n    if (previous === this.defaultValue || !Array.isArray(previous)) {\n      return [value];\n    }\n\n    return previous.concat(value);\n  }\n\n  /**\n   * Only allow option value to be one of choices.\n   *\n   * @param {string[]} values\n   * @return {Option}\n   */\n\n  choices(values) {\n    this.argChoices = values.slice();\n    this.parseArg = (arg, previous) => {\n      if (!this.argChoices.includes(arg)) {\n        throw new InvalidArgumentError(\n          `Allowed choices are ${this.argChoices.join(', ')}.`,\n        );\n      }\n      if (this.variadic) {\n        return this._concatValue(arg, previous);\n      }\n      return arg;\n    };\n    return this;\n  }\n\n  /**\n   * Return option name.\n   *\n   * @return {string}\n   */\n\n  name() {\n    if (this.long) {\n      return this.long.replace(/^--/, '');\n    }\n    return this.short.replace(/^-/, '');\n  }\n\n  /**\n   * Return option name, in a camelcase format that can be used\n   * as a object attribute key.\n   *\n   * @return {string}\n   */\n\n  attributeName() {\n    return camelcase(this.name().replace(/^no-/, ''));\n  }\n\n  /**\n   * Check if `arg` matches the short or long flag.\n   *\n   * @param {string} arg\n   * @return {boolean}\n   * @package\n   */\n\n  is(arg) {\n    return this.short === arg || this.long === arg;\n  }\n\n  /**\n   * Return whether a boolean option.\n   *\n   * Options are one of boolean, negated, required argument, or optional argument.\n   *\n   * @return {boolean}\n   * @package\n   */\n\n  isBoolean() {\n    return !this.required && !this.optional && !this.negate;\n  }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n  /**\n   * @param {Option[]} options\n   */\n  constructor(options) {\n    this.positiveOptions = new Map();\n    this.negativeOptions = new Map();\n    this.dualOptions = new Set();\n    options.forEach((option) => {\n      if (option.negate) {\n        this.negativeOptions.set(option.attributeName(), option);\n      } else {\n        this.positiveOptions.set(option.attributeName(), option);\n      }\n    });\n    this.negativeOptions.forEach((value, key) => {\n      if (this.positiveOptions.has(key)) {\n        this.dualOptions.add(key);\n      }\n    });\n  }\n\n  /**\n   * Did the value come from the option, and not from possible matching dual option?\n   *\n   * @param {*} value\n   * @param {Option} option\n   * @returns {boolean}\n   */\n  valueFromOption(value, option) {\n    const optionKey = option.attributeName();\n    if (!this.dualOptions.has(optionKey)) return true;\n\n    // Use the value to deduce if (probably) came from the option.\n    const preset = this.negativeOptions.get(optionKey).presetArg;\n    const negativeValue = preset !== undefined ? preset : false;\n    return option.negate === (negativeValue === value);\n  }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n  return str.split('-').reduce((str, word) => {\n    return str + word[0].toUpperCase() + word.slice(1);\n  });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n  let shortFlag;\n  let longFlag;\n  // Use original very loose parsing to maintain backwards compatibility for now,\n  // which allowed for example unintended `-sw, --short-word` [sic].\n  const flagParts = flags.split(/[ |,]+/);\n  if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))\n    shortFlag = flagParts.shift();\n  longFlag = flagParts.shift();\n  // Add support for lone short flag without significantly changing parsing!\n  if (!shortFlag && /^-[^-]$/.test(longFlag)) {\n    shortFlag = longFlag;\n    longFlag = undefined;\n  }\n  return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n", "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n  // https://en.wikipedia.org/wiki/Damerau\u2013Levenshtein_distance\n  // Calculating optimal string alignment distance, no substring is edited more than once.\n  // (Simple implementation.)\n\n  // Quick early exit, return worst case.\n  if (Math.abs(a.length - b.length) > maxDistance)\n    return Math.max(a.length, b.length);\n\n  // distance between prefix substrings of a and b\n  const d = [];\n\n  // pure deletions turn a into empty string\n  for (let i = 0; i <= a.length; i++) {\n    d[i] = [i];\n  }\n  // pure insertions turn empty string into b\n  for (let j = 0; j <= b.length; j++) {\n    d[0][j] = j;\n  }\n\n  // fill matrix\n  for (let j = 1; j <= b.length; j++) {\n    for (let i = 1; i <= a.length; i++) {\n      let cost = 1;\n      if (a[i - 1] === b[j - 1]) {\n        cost = 0;\n      } else {\n        cost = 1;\n      }\n      d[i][j] = Math.min(\n        d[i - 1][j] + 1, // deletion\n        d[i][j - 1] + 1, // insertion\n        d[i - 1][j - 1] + cost, // substitution\n      );\n      // transposition\n      if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n        d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n      }\n    }\n  }\n\n  return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n  if (!candidates || candidates.length === 0) return '';\n  // remove possible duplicates\n  candidates = Array.from(new Set(candidates));\n\n  const searchingOptions = word.startsWith('--');\n  if (searchingOptions) {\n    word = word.slice(2);\n    candidates = candidates.map((candidate) => candidate.slice(2));\n  }\n\n  let similar = [];\n  let bestDistance = maxDistance;\n  const minSimilarity = 0.4;\n  candidates.forEach((candidate) => {\n    if (candidate.length <= 1) return; // no one character guesses\n\n    const distance = editDistance(word, candidate);\n    const length = Math.max(word.length, candidate.length);\n    const similarity = (length - distance) / length;\n    if (similarity > minSimilarity) {\n      if (distance < bestDistance) {\n        // better edit distance, throw away previous worse matches\n        bestDistance = distance;\n        similar = [candidate];\n      } else if (distance === bestDistance) {\n        similar.push(candidate);\n      }\n    }\n  });\n\n  similar.sort((a, b) => a.localeCompare(b));\n  if (searchingOptions) {\n    similar = similar.map((candidate) => `--${candidate}`);\n  }\n\n  if (similar.length > 1) {\n    return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n  }\n  if (similar.length === 1) {\n    return `\\n(Did you mean ${similar[0]}?)`;\n  }\n  return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n", "const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n  /**\n   * Initialize a new `Command`.\n   *\n   * @param {string} [name]\n   */\n\n  constructor(name) {\n    super();\n    /** @type {Command[]} */\n    this.commands = [];\n    /** @type {Option[]} */\n    this.options = [];\n    this.parent = null;\n    this._allowUnknownOption = false;\n    this._allowExcessArguments = true;\n    /** @type {Argument[]} */\n    this.registeredArguments = [];\n    this._args = this.registeredArguments; // deprecated old name\n    /** @type {string[]} */\n    this.args = []; // cli args with options removed\n    this.rawArgs = [];\n    this.processedArgs = []; // like .args but after custom processing and collecting variadic\n    this._scriptPath = null;\n    this._name = name || '';\n    this._optionValues = {};\n    this._optionValueSources = {}; // default, env, cli etc\n    this._storeOptionsAsProperties = false;\n    this._actionHandler = null;\n    this._executableHandler = false;\n    this._executableFile = null; // custom name for executable\n    this._executableDir = null; // custom search directory for subcommands\n    this._defaultCommandName = null;\n    this._exitCallback = null;\n    this._aliases = [];\n    this._combineFlagAndOptionalValue = true;\n    this._description = '';\n    this._summary = '';\n    this._argsDescription = undefined; // legacy\n    this._enablePositionalOptions = false;\n    this._passThroughOptions = false;\n    this._lifeCycleHooks = {}; // a hash of arrays\n    /** @type {(boolean | string)} */\n    this._showHelpAfterError = false;\n    this._showSuggestionAfterError = true;\n\n    // see .configureOutput() for docs\n    this._outputConfiguration = {\n      writeOut: (str) => process.stdout.write(str),\n      writeErr: (str) => process.stderr.write(str),\n      getOutHelpWidth: () =>\n        process.stdout.isTTY ? process.stdout.columns : undefined,\n      getErrHelpWidth: () =>\n        process.stderr.isTTY ? process.stderr.columns : undefined,\n      outputError: (str, write) => write(str),\n    };\n\n    this._hidden = false;\n    /** @type {(Option | null | undefined)} */\n    this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n    this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n    /** @type {Command} */\n    this._helpCommand = undefined; // lazy initialised, inherited\n    this._helpConfiguration = {};\n  }\n\n  /**\n   * Copy settings that are useful to have in common across root command and subcommands.\n   *\n   * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n   *\n   * @param {Command} sourceCommand\n   * @return {Command} `this` command for chaining\n   */\n  copyInheritedSettings(sourceCommand) {\n    this._outputConfiguration = sourceCommand._outputConfiguration;\n    this._helpOption = sourceCommand._helpOption;\n    this._helpCommand = sourceCommand._helpCommand;\n    this._helpConfiguration = sourceCommand._helpConfiguration;\n    this._exitCallback = sourceCommand._exitCallback;\n    this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n    this._combineFlagAndOptionalValue =\n      sourceCommand._combineFlagAndOptionalValue;\n    this._allowExcessArguments = sourceCommand._allowExcessArguments;\n    this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n    this._showHelpAfterError = sourceCommand._showHelpAfterError;\n    this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n    return this;\n  }\n\n  /**\n   * @returns {Command[]}\n   * @private\n   */\n\n  _getCommandAndAncestors() {\n    const result = [];\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    for (let command = this; command; command = command.parent) {\n      result.push(command);\n    }\n    return result;\n  }\n\n  /**\n   * Define a command.\n   *\n   * There are two styles of command: pay attention to where to put the description.\n   *\n   * @example\n   * // Command implemented using action handler (description is supplied separately to `.command`)\n   * program\n   *   .command('clone <source> [destination]')\n   *   .description('clone a repository into a newly created directory')\n   *   .action((source, destination) => {\n   *     console.log('clone command called');\n   *   });\n   *\n   * // Command implemented using separate executable file (description is second parameter to `.command`)\n   * program\n   *   .command('start <service>', 'start named service')\n   *   .command('stop [service]', 'stop named service, or all if no name supplied');\n   *\n   * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n   * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n   * @param {object} [execOpts] - configuration options (for executable)\n   * @return {Command} returns new command for action handler, or `this` for executable command\n   */\n\n  command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n    let desc = actionOptsOrExecDesc;\n    let opts = execOpts;\n    if (typeof desc === 'object' && desc !== null) {\n      opts = desc;\n      desc = null;\n    }\n    opts = opts || {};\n    const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n    const cmd = this.createCommand(name);\n    if (desc) {\n      cmd.description(desc);\n      cmd._executableHandler = true;\n    }\n    if (opts.isDefault) this._defaultCommandName = cmd._name;\n    cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n    cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n    if (args) cmd.arguments(args);\n    this._registerCommand(cmd);\n    cmd.parent = this;\n    cmd.copyInheritedSettings(this);\n\n    if (desc) return this;\n    return cmd;\n  }\n\n  /**\n   * Factory routine to create a new unattached command.\n   *\n   * See .command() for creating an attached subcommand, which uses this routine to\n   * create the command. You can override createCommand to customise subcommands.\n   *\n   * @param {string} [name]\n   * @return {Command} new command\n   */\n\n  createCommand(name) {\n    return new Command(name);\n  }\n\n  /**\n   * You can customise the help with a subclass of Help by overriding createHelp,\n   * or by overriding Help properties using configureHelp().\n   *\n   * @return {Help}\n   */\n\n  createHelp() {\n    return Object.assign(new Help(), this.configureHelp());\n  }\n\n  /**\n   * You can customise the help by overriding Help properties using configureHelp(),\n   * or with a subclass of Help by overriding createHelp().\n   *\n   * @param {object} [configuration] - configuration options\n   * @return {(Command | object)} `this` command for chaining, or stored configuration\n   */\n\n  configureHelp(configuration) {\n    if (configuration === undefined) return this._helpConfiguration;\n\n    this._helpConfiguration = configuration;\n    return this;\n  }\n\n  /**\n   * The default output goes to stdout and stderr. You can customise this for special\n   * applications. You can also customise the display of errors by overriding outputError.\n   *\n   * The configuration properties are all functions:\n   *\n   *     // functions to change where being written, stdout and stderr\n   *     writeOut(str)\n   *     writeErr(str)\n   *     // matching functions to specify width for wrapping help\n   *     getOutHelpWidth()\n   *     getErrHelpWidth()\n   *     // functions based on what is being written out\n   *     outputError(str, write) // used for displaying errors, and not used for displaying help\n   *\n   * @param {object} [configuration] - configuration options\n   * @return {(Command | object)} `this` command for chaining, or stored configuration\n   */\n\n  configureOutput(configuration) {\n    if (configuration === undefined) return this._outputConfiguration;\n\n    Object.assign(this._outputConfiguration, configuration);\n    return this;\n  }\n\n  /**\n   * Display the help or a custom message after an error occurs.\n   *\n   * @param {(boolean|string)} [displayHelp]\n   * @return {Command} `this` command for chaining\n   */\n  showHelpAfterError(displayHelp = true) {\n    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n    this._showHelpAfterError = displayHelp;\n    return this;\n  }\n\n  /**\n   * Display suggestion of similar commands for unknown commands, or options for unknown options.\n   *\n   * @param {boolean} [displaySuggestion]\n   * @return {Command} `this` command for chaining\n   */\n  showSuggestionAfterError(displaySuggestion = true) {\n    this._showSuggestionAfterError = !!displaySuggestion;\n    return this;\n  }\n\n  /**\n   * Add a prepared subcommand.\n   *\n   * See .command() for creating an attached subcommand which inherits settings from its parent.\n   *\n   * @param {Command} cmd - new subcommand\n   * @param {object} [opts] - configuration options\n   * @return {Command} `this` command for chaining\n   */\n\n  addCommand(cmd, opts) {\n    if (!cmd._name) {\n      throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n    }\n\n    opts = opts || {};\n    if (opts.isDefault) this._defaultCommandName = cmd._name;\n    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n    this._registerCommand(cmd);\n    cmd.parent = this;\n    cmd._checkForBrokenPassThrough();\n\n    return this;\n  }\n\n  /**\n   * Factory routine to create a new unattached argument.\n   *\n   * See .argument() for creating an attached argument, which uses this routine to\n   * create the argument. You can override createArgument to return a custom argument.\n   *\n   * @param {string} name\n   * @param {string} [description]\n   * @return {Argument} new argument\n   */\n\n  createArgument(name, description) {\n    return new Argument(name, description);\n  }\n\n  /**\n   * Define argument syntax for command.\n   *\n   * The default is that the argument is required, and you can explicitly\n   * indicate this with <> around the name. Put [] around the name for an optional argument.\n   *\n   * @example\n   * program.argument('<input-file>');\n   * program.argument('[output-file]');\n   *\n   * @param {string} name\n   * @param {string} [description]\n   * @param {(Function|*)} [fn] - custom argument processing function\n   * @param {*} [defaultValue]\n   * @return {Command} `this` command for chaining\n   */\n  argument(name, description, fn, defaultValue) {\n    const argument = this.createArgument(name, description);\n    if (typeof fn === 'function') {\n      argument.default(defaultValue).argParser(fn);\n    } else {\n      argument.default(fn);\n    }\n    this.addArgument(argument);\n    return this;\n  }\n\n  /**\n   * Define argument syntax for command, adding multiple at once (without descriptions).\n   *\n   * See also .argument().\n   *\n   * @example\n   * program.arguments('<cmd> [env]');\n   *\n   * @param {string} names\n   * @return {Command} `this` command for chaining\n   */\n\n  arguments(names) {\n    names\n      .trim()\n      .split(/ +/)\n      .forEach((detail) => {\n        this.argument(detail);\n      });\n    return this;\n  }\n\n  /**\n   * Define argument syntax for command, adding a prepared argument.\n   *\n   * @param {Argument} argument\n   * @return {Command} `this` command for chaining\n   */\n  addArgument(argument) {\n    const previousArgument = this.registeredArguments.slice(-1)[0];\n    if (previousArgument && previousArgument.variadic) {\n      throw new Error(\n        `only the last argument can be variadic '${previousArgument.name()}'`,\n      );\n    }\n    if (\n      argument.required &&\n      argument.defaultValue !== undefined &&\n      argument.parseArg === undefined\n    ) {\n      throw new Error(\n        `a default value for a required argument is never used: '${argument.name()}'`,\n      );\n    }\n    this.registeredArguments.push(argument);\n    return this;\n  }\n\n  /**\n   * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n   *\n   * @example\n   *    program.helpCommand('help [cmd]');\n   *    program.helpCommand('help [cmd]', 'show help');\n   *    program.helpCommand(false); // suppress default help command\n   *    program.helpCommand(true); // add help command even if no subcommands\n   *\n   * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n   * @param {string} [description] - custom description\n   * @return {Command} `this` command for chaining\n   */\n\n  helpCommand(enableOrNameAndArgs, description) {\n    if (typeof enableOrNameAndArgs === 'boolean') {\n      this._addImplicitHelpCommand = enableOrNameAndArgs;\n      return this;\n    }\n\n    enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n    const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);\n    const helpDescription = description ?? 'display help for command';\n\n    const helpCommand = this.createCommand(helpName);\n    helpCommand.helpOption(false);\n    if (helpArgs) helpCommand.arguments(helpArgs);\n    if (helpDescription) helpCommand.description(helpDescription);\n\n    this._addImplicitHelpCommand = true;\n    this._helpCommand = helpCommand;\n\n    return this;\n  }\n\n  /**\n   * Add prepared custom help command.\n   *\n   * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n   * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n   * @return {Command} `this` command for chaining\n   */\n  addHelpCommand(helpCommand, deprecatedDescription) {\n    // If not passed an object, call through to helpCommand for backwards compatibility,\n    // as addHelpCommand was originally used like helpCommand is now.\n    if (typeof helpCommand !== 'object') {\n      this.helpCommand(helpCommand, deprecatedDescription);\n      return this;\n    }\n\n    this._addImplicitHelpCommand = true;\n    this._helpCommand = helpCommand;\n    return this;\n  }\n\n  /**\n   * Lazy create help command.\n   *\n   * @return {(Command|null)}\n   * @package\n   */\n  _getHelpCommand() {\n    const hasImplicitHelpCommand =\n      this._addImplicitHelpCommand ??\n      (this.commands.length &&\n        !this._actionHandler &&\n        !this._findCommand('help'));\n\n    if (hasImplicitHelpCommand) {\n      if (this._helpCommand === undefined) {\n        this.helpCommand(undefined, undefined); // use default name and description\n      }\n      return this._helpCommand;\n    }\n    return null;\n  }\n\n  /**\n   * Add hook for life cycle event.\n   *\n   * @param {string} event\n   * @param {Function} listener\n   * @return {Command} `this` command for chaining\n   */\n\n  hook(event, listener) {\n    const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n    if (!allowedValues.includes(event)) {\n      throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n    }\n    if (this._lifeCycleHooks[event]) {\n      this._lifeCycleHooks[event].push(listener);\n    } else {\n      this._lifeCycleHooks[event] = [listener];\n    }\n    return this;\n  }\n\n  /**\n   * Register callback to use as replacement for calling process.exit.\n   *\n   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n   * @return {Command} `this` command for chaining\n   */\n\n  exitOverride(fn) {\n    if (fn) {\n      this._exitCallback = fn;\n    } else {\n      this._exitCallback = (err) => {\n        if (err.code !== 'commander.executeSubCommandAsync') {\n          throw err;\n        } else {\n          // Async callback from spawn events, not useful to throw.\n        }\n      };\n    }\n    return this;\n  }\n\n  /**\n   * Call process.exit, and _exitCallback if defined.\n   *\n   * @param {number} exitCode exit code for using with process.exit\n   * @param {string} code an id string representing the error\n   * @param {string} message human-readable description of the error\n   * @return never\n   * @private\n   */\n\n  _exit(exitCode, code, message) {\n    if (this._exitCallback) {\n      this._exitCallback(new CommanderError(exitCode, code, message));\n      // Expecting this line is not reached.\n    }\n    process.exit(exitCode);\n  }\n\n  /**\n   * Register callback `fn` for the command.\n   *\n   * @example\n   * program\n   *   .command('serve')\n   *   .description('start service')\n   *   .action(function() {\n   *      // do work here\n   *   });\n   *\n   * @param {Function} fn\n   * @return {Command} `this` command for chaining\n   */\n\n  action(fn) {\n    const listener = (args) => {\n      // The .action callback takes an extra parameter which is the command or options.\n      const expectedArgsCount = this.registeredArguments.length;\n      const actionArgs = args.slice(0, expectedArgsCount);\n      if (this._storeOptionsAsProperties) {\n        actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n      } else {\n        actionArgs[expectedArgsCount] = this.opts();\n      }\n      actionArgs.push(this);\n\n      return fn.apply(this, actionArgs);\n    };\n    this._actionHandler = listener;\n    return this;\n  }\n\n  /**\n   * Factory routine to create a new unattached option.\n   *\n   * See .option() for creating an attached option, which uses this routine to\n   * create the option. You can override createOption to return a custom option.\n   *\n   * @param {string} flags\n   * @param {string} [description]\n   * @return {Option} new option\n   */\n\n  createOption(flags, description) {\n    return new Option(flags, description);\n  }\n\n  /**\n   * Wrap parseArgs to catch 'commander.invalidArgument'.\n   *\n   * @param {(Option | Argument)} target\n   * @param {string} value\n   * @param {*} previous\n   * @param {string} invalidArgumentMessage\n   * @private\n   */\n\n  _callParseArg(target, value, previous, invalidArgumentMessage) {\n    try {\n      return target.parseArg(value, previous);\n    } catch (err) {\n      if (err.code === 'commander.invalidArgument') {\n        const message = `${invalidArgumentMessage} ${err.message}`;\n        this.error(message, { exitCode: err.exitCode, code: err.code });\n      }\n      throw err;\n    }\n  }\n\n  /**\n   * Check for option flag conflicts.\n   * Register option if no conflicts found, or throw on conflict.\n   *\n   * @param {Option} option\n   * @private\n   */\n\n  _registerOption(option) {\n    const matchingOption =\n      (option.short && this._findOption(option.short)) ||\n      (option.long && this._findOption(option.long));\n    if (matchingOption) {\n      const matchingFlag =\n        option.long && this._findOption(option.long)\n          ? option.long\n          : option.short;\n      throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n-  already used by option '${matchingOption.flags}'`);\n    }\n\n    this.options.push(option);\n  }\n\n  /**\n   * Check for command name and alias conflicts with existing commands.\n   * Register command if no conflicts found, or throw on conflict.\n   *\n   * @param {Command} command\n   * @private\n   */\n\n  _registerCommand(command) {\n    const knownBy = (cmd) => {\n      return [cmd.name()].concat(cmd.aliases());\n    };\n\n    const alreadyUsed = knownBy(command).find((name) =>\n      this._findCommand(name),\n    );\n    if (alreadyUsed) {\n      const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n      const newCmd = knownBy(command).join('|');\n      throw new Error(\n        `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n      );\n    }\n\n    this.commands.push(command);\n  }\n\n  /**\n   * Add an option.\n   *\n   * @param {Option} option\n   * @return {Command} `this` command for chaining\n   */\n  addOption(option) {\n    this._registerOption(option);\n\n    const oname = option.name();\n    const name = option.attributeName();\n\n    // store default value\n    if (option.negate) {\n      // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n      const positiveLongFlag = option.long.replace(/^--no-/, '--');\n      if (!this._findOption(positiveLongFlag)) {\n        this.setOptionValueWithSource(\n          name,\n          option.defaultValue === undefined ? true : option.defaultValue,\n          'default',\n        );\n      }\n    } else if (option.defaultValue !== undefined) {\n      this.setOptionValueWithSource(name, option.defaultValue, 'default');\n    }\n\n    // handler for cli and env supplied values\n    const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n      // val is null for optional option used without an optional-argument.\n      // val is undefined for boolean and negated option.\n      if (val == null && option.presetArg !== undefined) {\n        val = option.presetArg;\n      }\n\n      // custom processing\n      const oldValue = this.getOptionValue(name);\n      if (val !== null && option.parseArg) {\n        val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n      } else if (val !== null && option.variadic) {\n        val = option._concatValue(val, oldValue);\n      }\n\n      // Fill-in appropriate missing values. Long winded but easy to follow.\n      if (val == null) {\n        if (option.negate) {\n          val = false;\n        } else if (option.isBoolean() || option.optional) {\n          val = true;\n        } else {\n          val = ''; // not normal, parseArg might have failed or be a mock function for testing\n        }\n      }\n      this.setOptionValueWithSource(name, val, valueSource);\n    };\n\n    this.on('option:' + oname, (val) => {\n      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n      handleOptionValue(val, invalidValueMessage, 'cli');\n    });\n\n    if (option.envVar) {\n      this.on('optionEnv:' + oname, (val) => {\n        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n        handleOptionValue(val, invalidValueMessage, 'env');\n      });\n    }\n\n    return this;\n  }\n\n  /**\n   * Internal implementation shared by .option() and .requiredOption()\n   *\n   * @return {Command} `this` command for chaining\n   * @private\n   */\n  _optionEx(config, flags, description, fn, defaultValue) {\n    if (typeof flags === 'object' && flags instanceof Option) {\n      throw new Error(\n        'To add an Option object use addOption() instead of option() or requiredOption()',\n      );\n    }\n    const option = this.createOption(flags, description);\n    option.makeOptionMandatory(!!config.mandatory);\n    if (typeof fn === 'function') {\n      option.default(defaultValue).argParser(fn);\n    } else if (fn instanceof RegExp) {\n      // deprecated\n      const regex = fn;\n      fn = (val, def) => {\n        const m = regex.exec(val);\n        return m ? m[0] : def;\n      };\n      option.default(defaultValue).argParser(fn);\n    } else {\n      option.default(fn);\n    }\n\n    return this.addOption(option);\n  }\n\n  /**\n   * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n   *\n   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n   * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n   *\n   * See the README for more details, and see also addOption() and requiredOption().\n   *\n   * @example\n   * program\n   *     .option('-p, --pepper', 'add pepper')\n   *     .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n   *     .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n   *     .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n   *\n   * @param {string} flags\n   * @param {string} [description]\n   * @param {(Function|*)} [parseArg] - custom option processing function or default value\n   * @param {*} [defaultValue]\n   * @return {Command} `this` command for chaining\n   */\n\n  option(flags, description, parseArg, defaultValue) {\n    return this._optionEx({}, flags, description, parseArg, defaultValue);\n  }\n\n  /**\n   * Add a required option which must have a value after parsing. This usually means\n   * the option must be specified on the command line. (Otherwise the same as .option().)\n   *\n   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n   *\n   * @param {string} flags\n   * @param {string} [description]\n   * @param {(Function|*)} [parseArg] - custom option processing function or default value\n   * @param {*} [defaultValue]\n   * @return {Command} `this` command for chaining\n   */\n\n  requiredOption(flags, description, parseArg, defaultValue) {\n    return this._optionEx(\n      { mandatory: true },\n      flags,\n      description,\n      parseArg,\n      defaultValue,\n    );\n  }\n\n  /**\n   * Alter parsing of short flags with optional values.\n   *\n   * @example\n   * // for `.option('-f,--flag [value]'):\n   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour\n   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n   *\n   * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n   * @return {Command} `this` command for chaining\n   */\n  combineFlagAndOptionalValue(combine = true) {\n    this._combineFlagAndOptionalValue = !!combine;\n    return this;\n  }\n\n  /**\n   * Allow unknown options on the command line.\n   *\n   * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n   * @return {Command} `this` command for chaining\n   */\n  allowUnknownOption(allowUnknown = true) {\n    this._allowUnknownOption = !!allowUnknown;\n    return this;\n  }\n\n  /**\n   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n   *\n   * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n   * @return {Command} `this` command for chaining\n   */\n  allowExcessArguments(allowExcess = true) {\n    this._allowExcessArguments = !!allowExcess;\n    return this;\n  }\n\n  /**\n   * Enable positional options. Positional means global options are specified before subcommands which lets\n   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n   * The default behaviour is non-positional and global options may appear anywhere on the command line.\n   *\n   * @param {boolean} [positional]\n   * @return {Command} `this` command for chaining\n   */\n  enablePositionalOptions(positional = true) {\n    this._enablePositionalOptions = !!positional;\n    return this;\n  }\n\n  /**\n   * Pass through options that come after command-arguments rather than treat them as command-options,\n   * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n   * positional options to have been enabled on the program (parent commands).\n   * The default behaviour is non-positional and options may appear before or after command-arguments.\n   *\n   * @param {boolean} [passThrough] for unknown options.\n   * @return {Command} `this` command for chaining\n   */\n  passThroughOptions(passThrough = true) {\n    this._passThroughOptions = !!passThrough;\n    this._checkForBrokenPassThrough();\n    return this;\n  }\n\n  /**\n   * @private\n   */\n\n  _checkForBrokenPassThrough() {\n    if (\n      this.parent &&\n      this._passThroughOptions &&\n      !this.parent._enablePositionalOptions\n    ) {\n      throw new Error(\n        `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n      );\n    }\n  }\n\n  /**\n   * Whether to store option values as properties on command object,\n   * or store separately (specify false). In both cases the option values can be accessed using .opts().\n   *\n   * @param {boolean} [storeAsProperties=true]\n   * @return {Command} `this` command for chaining\n   */\n\n  storeOptionsAsProperties(storeAsProperties = true) {\n    if (this.options.length) {\n      throw new Error('call .storeOptionsAsProperties() before adding options');\n    }\n    if (Object.keys(this._optionValues).length) {\n      throw new Error(\n        'call .storeOptionsAsProperties() before setting option values',\n      );\n    }\n    this._storeOptionsAsProperties = !!storeAsProperties;\n    return this;\n  }\n\n  /**\n   * Retrieve option value.\n   *\n   * @param {string} key\n   * @return {object} value\n   */\n\n  getOptionValue(key) {\n    if (this._storeOptionsAsProperties) {\n      return this[key];\n    }\n    return this._optionValues[key];\n  }\n\n  /**\n   * Store option value.\n   *\n   * @param {string} key\n   * @param {object} value\n   * @return {Command} `this` command for chaining\n   */\n\n  setOptionValue(key, value) {\n    return this.setOptionValueWithSource(key, value, undefined);\n  }\n\n  /**\n   * Store option value and where the value came from.\n   *\n   * @param {string} key\n   * @param {object} value\n   * @param {string} source - expected values are default/config/env/cli/implied\n   * @return {Command} `this` command for chaining\n   */\n\n  setOptionValueWithSource(key, value, source) {\n    if (this._storeOptionsAsProperties) {\n      this[key] = value;\n    } else {\n      this._optionValues[key] = value;\n    }\n    this._optionValueSources[key] = source;\n    return this;\n  }\n\n  /**\n   * Get source of option value.\n   * Expected values are default | config | env | cli | implied\n   *\n   * @param {string} key\n   * @return {string}\n   */\n\n  getOptionValueSource(key) {\n    return this._optionValueSources[key];\n  }\n\n  /**\n   * Get source of option value. See also .optsWithGlobals().\n   * Expected values are default | config | env | cli | implied\n   *\n   * @param {string} key\n   * @return {string}\n   */\n\n  getOptionValueSourceWithGlobals(key) {\n    // global overwrites local, like optsWithGlobals\n    let source;\n    this._getCommandAndAncestors().forEach((cmd) => {\n      if (cmd.getOptionValueSource(key) !== undefined) {\n        source = cmd.getOptionValueSource(key);\n      }\n    });\n    return source;\n  }\n\n  /**\n   * Get user arguments from implied or explicit arguments.\n   * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n   *\n   * @private\n   */\n\n  _prepareUserArgs(argv, parseOptions) {\n    if (argv !== undefined && !Array.isArray(argv)) {\n      throw new Error('first parameter to parse must be array or undefined');\n    }\n    parseOptions = parseOptions || {};\n\n    // auto-detect argument conventions if nothing supplied\n    if (argv === undefined && parseOptions.from === undefined) {\n      if (process.versions?.electron) {\n        parseOptions.from = 'electron';\n      }\n      // check node specific options for scenarios where user CLI args follow executable without scriptname\n      const execArgv = process.execArgv ?? [];\n      if (\n        execArgv.includes('-e') ||\n        execArgv.includes('--eval') ||\n        execArgv.includes('-p') ||\n        execArgv.includes('--print')\n      ) {\n        parseOptions.from = 'eval'; // internal usage, not documented\n      }\n    }\n\n    // default to using process.argv\n    if (argv === undefined) {\n      argv = process.argv;\n    }\n    this.rawArgs = argv.slice();\n\n    // extract the user args and scriptPath\n    let userArgs;\n    switch (parseOptions.from) {\n      case undefined:\n      case 'node':\n        this._scriptPath = argv[1];\n        userArgs = argv.slice(2);\n        break;\n      case 'electron':\n        // @ts-ignore: because defaultApp is an unknown property\n        if (process.defaultApp) {\n          this._scriptPath = argv[1];\n          userArgs = argv.slice(2);\n        } else {\n          userArgs = argv.slice(1);\n        }\n        break;\n      case 'user':\n        userArgs = argv.slice(0);\n        break;\n      case 'eval':\n        userArgs = argv.slice(1);\n        break;\n      default:\n        throw new Error(\n          `unexpected parse option { from: '${parseOptions.from}' }`,\n        );\n    }\n\n    // Find default name for program from arguments.\n    if (!this._name && this._scriptPath)\n      this.nameFromFilename(this._scriptPath);\n    this._name = this._name || 'program';\n\n    return userArgs;\n  }\n\n  /**\n   * Parse `argv`, setting options and invoking commands when defined.\n   *\n   * Use parseAsync instead of parse if any of your action handlers are async.\n   *\n   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n   *\n   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n   * - `'user'`: just user arguments\n   *\n   * @example\n   * program.parse(); // parse process.argv and auto-detect electron and special node flags\n   * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n   * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n   *\n   * @param {string[]} [argv] - optional, defaults to process.argv\n   * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n   * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n   * @return {Command} `this` command for chaining\n   */\n\n  parse(argv, parseOptions) {\n    const userArgs = this._prepareUserArgs(argv, parseOptions);\n    this._parseCommand([], userArgs);\n\n    return this;\n  }\n\n  /**\n   * Parse `argv`, setting options and invoking commands when defined.\n   *\n   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n   *\n   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n   * - `'user'`: just user arguments\n   *\n   * @example\n   * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n   * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n   * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n   *\n   * @param {string[]} [argv]\n   * @param {object} [parseOptions]\n   * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n   * @return {Promise}\n   */\n\n  async parseAsync(argv, parseOptions) {\n    const userArgs = this._prepareUserArgs(argv, parseOptions);\n    await this._parseCommand([], userArgs);\n\n    return this;\n  }\n\n  /**\n   * Execute a sub-command executable.\n   *\n   * @private\n   */\n\n  _executeSubCommand(subcommand, args) {\n    args = args.slice();\n    let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n    const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n    function findFile(baseDir, baseName) {\n      // Look for specified file\n      const localBin = path.resolve(baseDir, baseName);\n      if (fs.existsSync(localBin)) return localBin;\n\n      // Stop looking if candidate already has an expected extension.\n      if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n      // Try all the extensions.\n      const foundExt = sourceExt.find((ext) =>\n        fs.existsSync(`${localBin}${ext}`),\n      );\n      if (foundExt) return `${localBin}${foundExt}`;\n\n      return undefined;\n    }\n\n    // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n    this._checkForMissingMandatoryOptions();\n    this._checkForConflictingOptions();\n\n    // executableFile and executableDir might be full path, or just a name\n    let executableFile =\n      subcommand._executableFile || `${this._name}-${subcommand._name}`;\n    let executableDir = this._executableDir || '';\n    if (this._scriptPath) {\n      let resolvedScriptPath; // resolve possible symlink for installed npm binary\n      try {\n        resolvedScriptPath = fs.realpathSync(this._scriptPath);\n      } catch (err) {\n        resolvedScriptPath = this._scriptPath;\n      }\n      executableDir = path.resolve(\n        path.dirname(resolvedScriptPath),\n        executableDir,\n      );\n    }\n\n    // Look for a local file in preference to a command in PATH.\n    if (executableDir) {\n      let localFile = findFile(executableDir, executableFile);\n\n      // Legacy search using prefix of script name instead of command name\n      if (!localFile && !subcommand._executableFile && this._scriptPath) {\n        const legacyName = path.basename(\n          this._scriptPath,\n          path.extname(this._scriptPath),\n        );\n        if (legacyName !== this._name) {\n          localFile = findFile(\n            executableDir,\n            `${legacyName}-${subcommand._name}`,\n          );\n        }\n      }\n      executableFile = localFile || executableFile;\n    }\n\n    launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n    let proc;\n    if (process.platform !== 'win32') {\n      if (launchWithNode) {\n        args.unshift(executableFile);\n        // add executable arguments to spawn\n        args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n      } else {\n        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n      }\n    } else {\n      args.unshift(executableFile);\n      // add executable arguments to spawn\n      args = incrementNodeInspectorPort(process.execArgv).concat(args);\n      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n    }\n\n    if (!proc.killed) {\n      // testing mainly to avoid leak warnings during unit tests with mocked spawn\n      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n      signals.forEach((signal) => {\n        process.on(signal, () => {\n          if (proc.killed === false && proc.exitCode === null) {\n            // @ts-ignore because signals not typed to known strings\n            proc.kill(signal);\n          }\n        });\n      });\n    }\n\n    // By default terminate process when spawned process terminates.\n    const exitCallback = this._exitCallback;\n    proc.on('close', (code) => {\n      code = code ?? 1; // code is null if spawned process terminated due to a signal\n      if (!exitCallback) {\n        process.exit(code);\n      } else {\n        exitCallback(\n          new CommanderError(\n            code,\n            'commander.executeSubCommandAsync',\n            '(close)',\n          ),\n        );\n      }\n    });\n    proc.on('error', (err) => {\n      // @ts-ignore: because err.code is an unknown property\n      if (err.code === 'ENOENT') {\n        const executableDirMessage = executableDir\n          ? `searched for local subcommand relative to directory '${executableDir}'`\n          : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n        const executableMissing = `'${executableFile}' does not exist\n - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n        throw new Error(executableMissing);\n        // @ts-ignore: because err.code is an unknown property\n      } else if (err.code === 'EACCES') {\n        throw new Error(`'${executableFile}' not executable`);\n      }\n      if (!exitCallback) {\n        process.exit(1);\n      } else {\n        const wrappedError = new CommanderError(\n          1,\n          'commander.executeSubCommandAsync',\n          '(error)',\n        );\n        wrappedError.nestedError = err;\n        exitCallback(wrappedError);\n      }\n    });\n\n    // Store the reference to the child process\n    this.runningCommand = proc;\n  }\n\n  /**\n   * @private\n   */\n\n  _dispatchSubcommand(commandName, operands, unknown) {\n    const subCommand = this._findCommand(commandName);\n    if (!subCommand) this.help({ error: true });\n\n    let promiseChain;\n    promiseChain = this._chainOrCallSubCommandHook(\n      promiseChain,\n      subCommand,\n      'preSubcommand',\n    );\n    promiseChain = this._chainOrCall(promiseChain, () => {\n      if (subCommand._executableHandler) {\n        this._executeSubCommand(subCommand, operands.concat(unknown));\n      } else {\n        return subCommand._parseCommand(operands, unknown);\n      }\n    });\n    return promiseChain;\n  }\n\n  /**\n   * Invoke help directly if possible, or dispatch if necessary.\n   * e.g. help foo\n   *\n   * @private\n   */\n\n  _dispatchHelpCommand(subcommandName) {\n    if (!subcommandName) {\n      this.help();\n    }\n    const subCommand = this._findCommand(subcommandName);\n    if (subCommand && !subCommand._executableHandler) {\n      subCommand.help();\n    }\n\n    // Fallback to parsing the help flag to invoke the help.\n    return this._dispatchSubcommand(\n      subcommandName,\n      [],\n      [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n    );\n  }\n\n  /**\n   * Check this.args against expected this.registeredArguments.\n   *\n   * @private\n   */\n\n  _checkNumberOfArguments() {\n    // too few\n    this.registeredArguments.forEach((arg, i) => {\n      if (arg.required && this.args[i] == null) {\n        this.missingArgument(arg.name());\n      }\n    });\n    // too many\n    if (\n      this.registeredArguments.length > 0 &&\n      this.registeredArguments[this.registeredArguments.length - 1].variadic\n    ) {\n      return;\n    }\n    if (this.args.length > this.registeredArguments.length) {\n      this._excessArguments(this.args);\n    }\n  }\n\n  /**\n   * Process this.args using this.registeredArguments and save as this.processedArgs!\n   *\n   * @private\n   */\n\n  _processArguments() {\n    const myParseArg = (argument, value, previous) => {\n      // Extra processing for nice error message on parsing failure.\n      let parsedValue = value;\n      if (value !== null && argument.parseArg) {\n        const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n        parsedValue = this._callParseArg(\n          argument,\n          value,\n          previous,\n          invalidValueMessage,\n        );\n      }\n      return parsedValue;\n    };\n\n    this._checkNumberOfArguments();\n\n    const processedArgs = [];\n    this.registeredArguments.forEach((declaredArg, index) => {\n      let value = declaredArg.defaultValue;\n      if (declaredArg.variadic) {\n        // Collect together remaining arguments for passing together as an array.\n        if (index < this.args.length) {\n          value = this.args.slice(index);\n          if (declaredArg.parseArg) {\n            value = value.reduce((processed, v) => {\n              return myParseArg(declaredArg, v, processed);\n            }, declaredArg.defaultValue);\n          }\n        } else if (value === undefined) {\n          value = [];\n        }\n      } else if (index < this.args.length) {\n        value = this.args[index];\n        if (declaredArg.parseArg) {\n          value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n        }\n      }\n      processedArgs[index] = value;\n    });\n    this.processedArgs = processedArgs;\n  }\n\n  /**\n   * Once we have a promise we chain, but call synchronously until then.\n   *\n   * @param {(Promise|undefined)} promise\n   * @param {Function} fn\n   * @return {(Promise|undefined)}\n   * @private\n   */\n\n  _chainOrCall(promise, fn) {\n    // thenable\n    if (promise && promise.then && typeof promise.then === 'function') {\n      // already have a promise, chain callback\n      return promise.then(() => fn());\n    }\n    // callback might return a promise\n    return fn();\n  }\n\n  /**\n   *\n   * @param {(Promise|undefined)} promise\n   * @param {string} event\n   * @return {(Promise|undefined)}\n   * @private\n   */\n\n  _chainOrCallHooks(promise, event) {\n    let result = promise;\n    const hooks = [];\n    this._getCommandAndAncestors()\n      .reverse()\n      .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n      .forEach((hookedCommand) => {\n        hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n          hooks.push({ hookedCommand, callback });\n        });\n      });\n    if (event === 'postAction') {\n      hooks.reverse();\n    }\n\n    hooks.forEach((hookDetail) => {\n      result = this._chainOrCall(result, () => {\n        return hookDetail.callback(hookDetail.hookedCommand, this);\n      });\n    });\n    return result;\n  }\n\n  /**\n   *\n   * @param {(Promise|undefined)} promise\n   * @param {Command} subCommand\n   * @param {string} event\n   * @return {(Promise|undefined)}\n   * @private\n   */\n\n  _chainOrCallSubCommandHook(promise, subCommand, event) {\n    let result = promise;\n    if (this._lifeCycleHooks[event] !== undefined) {\n      this._lifeCycleHooks[event].forEach((hook) => {\n        result = this._chainOrCall(result, () => {\n          return hook(this, subCommand);\n        });\n      });\n    }\n    return result;\n  }\n\n  /**\n   * Process arguments in context of this command.\n   * Returns action result, in case it is a promise.\n   *\n   * @private\n   */\n\n  _parseCommand(operands, unknown) {\n    const parsed = this.parseOptions(unknown);\n    this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n    this._parseOptionsImplied();\n    operands = operands.concat(parsed.operands);\n    unknown = parsed.unknown;\n    this.args = operands.concat(unknown);\n\n    if (operands && this._findCommand(operands[0])) {\n      return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n    }\n    if (\n      this._getHelpCommand() &&\n      operands[0] === this._getHelpCommand().name()\n    ) {\n      return this._dispatchHelpCommand(operands[1]);\n    }\n    if (this._defaultCommandName) {\n      this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n      return this._dispatchSubcommand(\n        this._defaultCommandName,\n        operands,\n        unknown,\n      );\n    }\n    if (\n      this.commands.length &&\n      this.args.length === 0 &&\n      !this._actionHandler &&\n      !this._defaultCommandName\n    ) {\n      // probably missing subcommand and no handler, user needs help (and exit)\n      this.help({ error: true });\n    }\n\n    this._outputHelpIfRequested(parsed.unknown);\n    this._checkForMissingMandatoryOptions();\n    this._checkForConflictingOptions();\n\n    // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n    const checkForUnknownOptions = () => {\n      if (parsed.unknown.length > 0) {\n        this.unknownOption(parsed.unknown[0]);\n      }\n    };\n\n    const commandEvent = `command:${this.name()}`;\n    if (this._actionHandler) {\n      checkForUnknownOptions();\n      this._processArguments();\n\n      let promiseChain;\n      promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n      promiseChain = this._chainOrCall(promiseChain, () =>\n        this._actionHandler(this.processedArgs),\n      );\n      if (this.parent) {\n        promiseChain = this._chainOrCall(promiseChain, () => {\n          this.parent.emit(commandEvent, operands, unknown); // legacy\n        });\n      }\n      promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n      return promiseChain;\n    }\n    if (this.parent && this.parent.listenerCount(commandEvent)) {\n      checkForUnknownOptions();\n      this._processArguments();\n      this.parent.emit(commandEvent, operands, unknown); // legacy\n    } else if (operands.length) {\n      if (this._findCommand('*')) {\n        // legacy default command\n        return this._dispatchSubcommand('*', operands, unknown);\n      }\n      if (this.listenerCount('command:*')) {\n        // skip option check, emit event for possible misspelling suggestion\n        this.emit('command:*', operands, unknown);\n      } else if (this.commands.length) {\n        this.unknownCommand();\n      } else {\n        checkForUnknownOptions();\n        this._processArguments();\n      }\n    } else if (this.commands.length) {\n      checkForUnknownOptions();\n      // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n      this.help({ error: true });\n    } else {\n      checkForUnknownOptions();\n      this._processArguments();\n      // fall through for caller to handle after calling .parse()\n    }\n  }\n\n  /**\n   * Find matching command.\n   *\n   * @private\n   * @return {Command | undefined}\n   */\n  _findCommand(name) {\n    if (!name) return undefined;\n    return this.commands.find(\n      (cmd) => cmd._name === name || cmd._aliases.includes(name),\n    );\n  }\n\n  /**\n   * Return an option matching `arg` if any.\n   *\n   * @param {string} arg\n   * @return {Option}\n   * @package\n   */\n\n  _findOption(arg) {\n    return this.options.find((option) => option.is(arg));\n  }\n\n  /**\n   * Display an error message if a mandatory option does not have a value.\n   * Called after checking for help flags in leaf subcommand.\n   *\n   * @private\n   */\n\n  _checkForMissingMandatoryOptions() {\n    // Walk up hierarchy so can call in subcommand after checking for displaying help.\n    this._getCommandAndAncestors().forEach((cmd) => {\n      cmd.options.forEach((anOption) => {\n        if (\n          anOption.mandatory &&\n          cmd.getOptionValue(anOption.attributeName()) === undefined\n        ) {\n          cmd.missingMandatoryOptionValue(anOption);\n        }\n      });\n    });\n  }\n\n  /**\n   * Display an error message if conflicting options are used together in this.\n   *\n   * @private\n   */\n  _checkForConflictingLocalOptions() {\n    const definedNonDefaultOptions = this.options.filter((option) => {\n      const optionKey = option.attributeName();\n      if (this.getOptionValue(optionKey) === undefined) {\n        return false;\n      }\n      return this.getOptionValueSource(optionKey) !== 'default';\n    });\n\n    const optionsWithConflicting = definedNonDefaultOptions.filter(\n      (option) => option.conflictsWith.length > 0,\n    );\n\n    optionsWithConflicting.forEach((option) => {\n      const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n        option.conflictsWith.includes(defined.attributeName()),\n      );\n      if (conflictingAndDefined) {\n        this._conflictingOption(option, conflictingAndDefined);\n      }\n    });\n  }\n\n  /**\n   * Display an error message if conflicting options are used together.\n   * Called after checking for help flags in leaf subcommand.\n   *\n   * @private\n   */\n  _checkForConflictingOptions() {\n    // Walk up hierarchy so can call in subcommand after checking for displaying help.\n    this._getCommandAndAncestors().forEach((cmd) => {\n      cmd._checkForConflictingLocalOptions();\n    });\n  }\n\n  /**\n   * Parse options from `argv` removing known options,\n   * and return argv split into operands and unknown arguments.\n   *\n   * Examples:\n   *\n   *     argv => operands, unknown\n   *     --known kkk op => [op], []\n   *     op --known kkk => [op], []\n   *     sub --unknown uuu op => [sub], [--unknown uuu op]\n   *     sub -- --unknown uuu op => [sub --unknown uuu op], []\n   *\n   * @param {string[]} argv\n   * @return {{operands: string[], unknown: string[]}}\n   */\n\n  parseOptions(argv) {\n    const operands = []; // operands, not options or values\n    const unknown = []; // first unknown option and remaining unknown args\n    let dest = operands;\n    const args = argv.slice();\n\n    function maybeOption(arg) {\n      return arg.length > 1 && arg[0] === '-';\n    }\n\n    // parse options\n    let activeVariadicOption = null;\n    while (args.length) {\n      const arg = args.shift();\n\n      // literal\n      if (arg === '--') {\n        if (dest === unknown) dest.push(arg);\n        dest.push(...args);\n        break;\n      }\n\n      if (activeVariadicOption && !maybeOption(arg)) {\n        this.emit(`option:${activeVariadicOption.name()}`, arg);\n        continue;\n      }\n      activeVariadicOption = null;\n\n      if (maybeOption(arg)) {\n        const option = this._findOption(arg);\n        // recognised option, call listener to assign value with possible custom processing\n        if (option) {\n          if (option.required) {\n            const value = args.shift();\n            if (value === undefined) this.optionMissingArgument(option);\n            this.emit(`option:${option.name()}`, value);\n          } else if (option.optional) {\n            let value = null;\n            // historical behaviour is optional value is following arg unless an option\n            if (args.length > 0 && !maybeOption(args[0])) {\n              value = args.shift();\n            }\n            this.emit(`option:${option.name()}`, value);\n          } else {\n            // boolean flag\n            this.emit(`option:${option.name()}`);\n          }\n          activeVariadicOption = option.variadic ? option : null;\n          continue;\n        }\n      }\n\n      // Look for combo options following single dash, eat first one if known.\n      if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n        const option = this._findOption(`-${arg[1]}`);\n        if (option) {\n          if (\n            option.required ||\n            (option.optional && this._combineFlagAndOptionalValue)\n          ) {\n            // option with value following in same argument\n            this.emit(`option:${option.name()}`, arg.slice(2));\n          } else {\n            // boolean option, emit and put back remainder of arg for further processing\n            this.emit(`option:${option.name()}`);\n            args.unshift(`-${arg.slice(2)}`);\n          }\n          continue;\n        }\n      }\n\n      // Look for known long flag with value, like --foo=bar\n      if (/^--[^=]+=/.test(arg)) {\n        const index = arg.indexOf('=');\n        const option = this._findOption(arg.slice(0, index));\n        if (option && (option.required || option.optional)) {\n          this.emit(`option:${option.name()}`, arg.slice(index + 1));\n          continue;\n        }\n      }\n\n      // Not a recognised option by this command.\n      // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n      // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n      if (maybeOption(arg)) {\n        dest = unknown;\n      }\n\n      // If using positionalOptions, stop processing our options at subcommand.\n      if (\n        (this._enablePositionalOptions || this._passThroughOptions) &&\n        operands.length === 0 &&\n        unknown.length === 0\n      ) {\n        if (this._findCommand(arg)) {\n          operands.push(arg);\n          if (args.length > 0) unknown.push(...args);\n          break;\n        } else if (\n          this._getHelpCommand() &&\n          arg === this._getHelpCommand().name()\n        ) {\n          operands.push(arg);\n          if (args.length > 0) operands.push(...args);\n          break;\n        } else if (this._defaultCommandName) {\n          unknown.push(arg);\n          if (args.length > 0) unknown.push(...args);\n          break;\n        }\n      }\n\n      // If using passThroughOptions, stop processing options at first command-argument.\n      if (this._passThroughOptions) {\n        dest.push(arg);\n        if (args.length > 0) dest.push(...args);\n        break;\n      }\n\n      // add arg\n      dest.push(arg);\n    }\n\n    return { operands, unknown };\n  }\n\n  /**\n   * Return an object containing local option values as key-value pairs.\n   *\n   * @return {object}\n   */\n  opts() {\n    if (this._storeOptionsAsProperties) {\n      // Preserve original behaviour so backwards compatible when still using properties\n      const result = {};\n      const len = this.options.length;\n\n      for (let i = 0; i < len; i++) {\n        const key = this.options[i].attributeName();\n        result[key] =\n          key === this._versionOptionName ? this._version : this[key];\n      }\n      return result;\n    }\n\n    return this._optionValues;\n  }\n\n  /**\n   * Return an object containing merged local and global option values as key-value pairs.\n   *\n   * @return {object}\n   */\n  optsWithGlobals() {\n    // globals overwrite locals\n    return this._getCommandAndAncestors().reduce(\n      (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n      {},\n    );\n  }\n\n  /**\n   * Display error message and exit (or call exitOverride).\n   *\n   * @param {string} message\n   * @param {object} [errorOptions]\n   * @param {string} [errorOptions.code] - an id string representing the error\n   * @param {number} [errorOptions.exitCode] - used with process.exit\n   */\n  error(message, errorOptions) {\n    // output handling\n    this._outputConfiguration.outputError(\n      `${message}\\n`,\n      this._outputConfiguration.writeErr,\n    );\n    if (typeof this._showHelpAfterError === 'string') {\n      this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n    } else if (this._showHelpAfterError) {\n      this._outputConfiguration.writeErr('\\n');\n      this.outputHelp({ error: true });\n    }\n\n    // exit handling\n    const config = errorOptions || {};\n    const exitCode = config.exitCode || 1;\n    const code = config.code || 'commander.error';\n    this._exit(exitCode, code, message);\n  }\n\n  /**\n   * Apply any option related environment variables, if option does\n   * not have a value from cli or client code.\n   *\n   * @private\n   */\n  _parseOptionsEnv() {\n    this.options.forEach((option) => {\n      if (option.envVar && option.envVar in process.env) {\n        const optionKey = option.attributeName();\n        // Priority check. Do not overwrite cli or options from unknown source (client-code).\n        if (\n          this.getOptionValue(optionKey) === undefined ||\n          ['default', 'config', 'env'].includes(\n            this.getOptionValueSource(optionKey),\n          )\n        ) {\n          if (option.required || option.optional) {\n            // option can take a value\n            // keep very simple, optional always takes value\n            this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n          } else {\n            // boolean\n            // keep very simple, only care that envVar defined and not the value\n            this.emit(`optionEnv:${option.name()}`);\n          }\n        }\n      }\n    });\n  }\n\n  /**\n   * Apply any implied option values, if option is undefined or default value.\n   *\n   * @private\n   */\n  _parseOptionsImplied() {\n    const dualHelper = new DualOptions(this.options);\n    const hasCustomOptionValue = (optionKey) => {\n      return (\n        this.getOptionValue(optionKey) !== undefined &&\n        !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n      );\n    };\n    this.options\n      .filter(\n        (option) =>\n          option.implied !== undefined &&\n          hasCustomOptionValue(option.attributeName()) &&\n          dualHelper.valueFromOption(\n            this.getOptionValue(option.attributeName()),\n            option,\n          ),\n      )\n      .forEach((option) => {\n        Object.keys(option.implied)\n          .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n          .forEach((impliedKey) => {\n            this.setOptionValueWithSource(\n              impliedKey,\n              option.implied[impliedKey],\n              'implied',\n            );\n          });\n      });\n  }\n\n  /**\n   * Argument `name` is missing.\n   *\n   * @param {string} name\n   * @private\n   */\n\n  missingArgument(name) {\n    const message = `error: missing required argument '${name}'`;\n    this.error(message, { code: 'commander.missingArgument' });\n  }\n\n  /**\n   * `Option` is missing an argument.\n   *\n   * @param {Option} option\n   * @private\n   */\n\n  optionMissingArgument(option) {\n    const message = `error: option '${option.flags}' argument missing`;\n    this.error(message, { code: 'commander.optionMissingArgument' });\n  }\n\n  /**\n   * `Option` does not have a value, and is a mandatory option.\n   *\n   * @param {Option} option\n   * @private\n   */\n\n  missingMandatoryOptionValue(option) {\n    const message = `error: required option '${option.flags}' not specified`;\n    this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n  }\n\n  /**\n   * `Option` conflicts with another option.\n   *\n   * @param {Option} option\n   * @param {Option} conflictingOption\n   * @private\n   */\n  _conflictingOption(option, conflictingOption) {\n    // The calling code does not know whether a negated option is the source of the\n    // value, so do some work to take an educated guess.\n    const findBestOptionFromValue = (option) => {\n      const optionKey = option.attributeName();\n      const optionValue = this.getOptionValue(optionKey);\n      const negativeOption = this.options.find(\n        (target) => target.negate && optionKey === target.attributeName(),\n      );\n      const positiveOption = this.options.find(\n        (target) => !target.negate && optionKey === target.attributeName(),\n      );\n      if (\n        negativeOption &&\n        ((negativeOption.presetArg === undefined && optionValue === false) ||\n          (negativeOption.presetArg !== undefined &&\n            optionValue === negativeOption.presetArg))\n      ) {\n        return negativeOption;\n      }\n      return positiveOption || option;\n    };\n\n    const getErrorMessage = (option) => {\n      const bestOption = findBestOptionFromValue(option);\n      const optionKey = bestOption.attributeName();\n      const source = this.getOptionValueSource(optionKey);\n      if (source === 'env') {\n        return `environment variable '${bestOption.envVar}'`;\n      }\n      return `option '${bestOption.flags}'`;\n    };\n\n    const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n    this.error(message, { code: 'commander.conflictingOption' });\n  }\n\n  /**\n   * Unknown option `flag`.\n   *\n   * @param {string} flag\n   * @private\n   */\n\n  unknownOption(flag) {\n    if (this._allowUnknownOption) return;\n    let suggestion = '';\n\n    if (flag.startsWith('--') && this._showSuggestionAfterError) {\n      // Looping to pick up the global options too\n      let candidateFlags = [];\n      // eslint-disable-next-line @typescript-eslint/no-this-alias\n      let command = this;\n      do {\n        const moreFlags = command\n          .createHelp()\n          .visibleOptions(command)\n          .filter((option) => option.long)\n          .map((option) => option.long);\n        candidateFlags = candidateFlags.concat(moreFlags);\n        command = command.parent;\n      } while (command && !command._enablePositionalOptions);\n      suggestion = suggestSimilar(flag, candidateFlags);\n    }\n\n    const message = `error: unknown option '${flag}'${suggestion}`;\n    this.error(message, { code: 'commander.unknownOption' });\n  }\n\n  /**\n   * Excess arguments, more than expected.\n   *\n   * @param {string[]} receivedArgs\n   * @private\n   */\n\n  _excessArguments(receivedArgs) {\n    if (this._allowExcessArguments) return;\n\n    const expected = this.registeredArguments.length;\n    const s = expected === 1 ? '' : 's';\n    const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n    const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n    this.error(message, { code: 'commander.excessArguments' });\n  }\n\n  /**\n   * Unknown command.\n   *\n   * @private\n   */\n\n  unknownCommand() {\n    const unknownName = this.args[0];\n    let suggestion = '';\n\n    if (this._showSuggestionAfterError) {\n      const candidateNames = [];\n      this.createHelp()\n        .visibleCommands(this)\n        .forEach((command) => {\n          candidateNames.push(command.name());\n          // just visible alias\n          if (command.alias()) candidateNames.push(command.alias());\n        });\n      suggestion = suggestSimilar(unknownName, candidateNames);\n    }\n\n    const message = `error: unknown command '${unknownName}'${suggestion}`;\n    this.error(message, { code: 'commander.unknownCommand' });\n  }\n\n  /**\n   * Get or set the program version.\n   *\n   * This method auto-registers the \"-V, --version\" option which will print the version number.\n   *\n   * You can optionally supply the flags and description to override the defaults.\n   *\n   * @param {string} [str]\n   * @param {string} [flags]\n   * @param {string} [description]\n   * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n   */\n\n  version(str, flags, description) {\n    if (str === undefined) return this._version;\n    this._version = str;\n    flags = flags || '-V, --version';\n    description = description || 'output the version number';\n    const versionOption = this.createOption(flags, description);\n    this._versionOptionName = versionOption.attributeName();\n    this._registerOption(versionOption);\n\n    this.on('option:' + versionOption.name(), () => {\n      this._outputConfiguration.writeOut(`${str}\\n`);\n      this._exit(0, 'commander.version', str);\n    });\n    return this;\n  }\n\n  /**\n   * Set the description.\n   *\n   * @param {string} [str]\n   * @param {object} [argsDescription]\n   * @return {(string|Command)}\n   */\n  description(str, argsDescription) {\n    if (str === undefined && argsDescription === undefined)\n      return this._description;\n    this._description = str;\n    if (argsDescription) {\n      this._argsDescription = argsDescription;\n    }\n    return this;\n  }\n\n  /**\n   * Set the summary. Used when listed as subcommand of parent.\n   *\n   * @param {string} [str]\n   * @return {(string|Command)}\n   */\n  summary(str) {\n    if (str === undefined) return this._summary;\n    this._summary = str;\n    return this;\n  }\n\n  /**\n   * Set an alias for the command.\n   *\n   * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n   *\n   * @param {string} [alias]\n   * @return {(string|Command)}\n   */\n\n  alias(alias) {\n    if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n    /** @type {Command} */\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    let command = this;\n    if (\n      this.commands.length !== 0 &&\n      this.commands[this.commands.length - 1]._executableHandler\n    ) {\n      // assume adding alias for last added executable subcommand, rather than this\n      command = this.commands[this.commands.length - 1];\n    }\n\n    if (alias === command._name)\n      throw new Error(\"Command alias can't be the same as its name\");\n    const matchingCommand = this.parent?._findCommand(alias);\n    if (matchingCommand) {\n      // c.f. _registerCommand\n      const existingCmd = [matchingCommand.name()]\n        .concat(matchingCommand.aliases())\n        .join('|');\n      throw new Error(\n        `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n      );\n    }\n\n    command._aliases.push(alias);\n    return this;\n  }\n\n  /**\n   * Set aliases for the command.\n   *\n   * Only the first alias is shown in the auto-generated help.\n   *\n   * @param {string[]} [aliases]\n   * @return {(string[]|Command)}\n   */\n\n  aliases(aliases) {\n    // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n    if (aliases === undefined) return this._aliases;\n\n    aliases.forEach((alias) => this.alias(alias));\n    return this;\n  }\n\n  /**\n   * Set / get the command usage `str`.\n   *\n   * @param {string} [str]\n   * @return {(string|Command)}\n   */\n\n  usage(str) {\n    if (str === undefined) {\n      if (this._usage) return this._usage;\n\n      const args = this.registeredArguments.map((arg) => {\n        return humanReadableArgName(arg);\n      });\n      return []\n        .concat(\n          this.options.length || this._helpOption !== null ? '[options]' : [],\n          this.commands.length ? '[command]' : [],\n          this.registeredArguments.length ? args : [],\n        )\n        .join(' ');\n    }\n\n    this._usage = str;\n    return this;\n  }\n\n  /**\n   * Get or set the name of the command.\n   *\n   * @param {string} [str]\n   * @return {(string|Command)}\n   */\n\n  name(str) {\n    if (str === undefined) return this._name;\n    this._name = str;\n    return this;\n  }\n\n  /**\n   * Set the name of the command from script filename, such as process.argv[1],\n   * or require.main.filename, or __filename.\n   *\n   * (Used internally and public although not documented in README.)\n   *\n   * @example\n   * program.nameFromFilename(require.main.filename);\n   *\n   * @param {string} filename\n   * @return {Command}\n   */\n\n  nameFromFilename(filename) {\n    this._name = path.basename(filename, path.extname(filename));\n\n    return this;\n  }\n\n  /**\n   * Get or set the directory for searching for executable subcommands of this command.\n   *\n   * @example\n   * program.executableDir(__dirname);\n   * // or\n   * program.executableDir('subcommands');\n   *\n   * @param {string} [path]\n   * @return {(string|null|Command)}\n   */\n\n  executableDir(path) {\n    if (path === undefined) return this._executableDir;\n    this._executableDir = path;\n    return this;\n  }\n\n  /**\n   * Return program help documentation.\n   *\n   * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n   * @return {string}\n   */\n\n  helpInformation(contextOptions) {\n    const helper = this.createHelp();\n    if (helper.helpWidth === undefined) {\n      helper.helpWidth =\n        contextOptions && contextOptions.error\n          ? this._outputConfiguration.getErrHelpWidth()\n          : this._outputConfiguration.getOutHelpWidth();\n    }\n    return helper.formatHelp(this, helper);\n  }\n\n  /**\n   * @private\n   */\n\n  _getHelpContext(contextOptions) {\n    contextOptions = contextOptions || {};\n    const context = { error: !!contextOptions.error };\n    let write;\n    if (context.error) {\n      write = (arg) => this._outputConfiguration.writeErr(arg);\n    } else {\n      write = (arg) => this._outputConfiguration.writeOut(arg);\n    }\n    context.write = contextOptions.write || write;\n    context.command = this;\n    return context;\n  }\n\n  /**\n   * Output help information for this command.\n   *\n   * Outputs built-in help, and custom text added using `.addHelpText()`.\n   *\n   * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n   */\n\n  outputHelp(contextOptions) {\n    let deprecatedCallback;\n    if (typeof contextOptions === 'function') {\n      deprecatedCallback = contextOptions;\n      contextOptions = undefined;\n    }\n    const context = this._getHelpContext(contextOptions);\n\n    this._getCommandAndAncestors()\n      .reverse()\n      .forEach((command) => command.emit('beforeAllHelp', context));\n    this.emit('beforeHelp', context);\n\n    let helpInformation = this.helpInformation(context);\n    if (deprecatedCallback) {\n      helpInformation = deprecatedCallback(helpInformation);\n      if (\n        typeof helpInformation !== 'string' &&\n        !Buffer.isBuffer(helpInformation)\n      ) {\n        throw new Error('outputHelp callback must return a string or a Buffer');\n      }\n    }\n    context.write(helpInformation);\n\n    if (this._getHelpOption()?.long) {\n      this.emit(this._getHelpOption().long); // deprecated\n    }\n    this.emit('afterHelp', context);\n    this._getCommandAndAncestors().forEach((command) =>\n      command.emit('afterAllHelp', context),\n    );\n  }\n\n  /**\n   * You can pass in flags and a description to customise the built-in help option.\n   * Pass in false to disable the built-in help option.\n   *\n   * @example\n   * program.helpOption('-?, --help' 'show help'); // customise\n   * program.helpOption(false); // disable\n   *\n   * @param {(string | boolean)} flags\n   * @param {string} [description]\n   * @return {Command} `this` command for chaining\n   */\n\n  helpOption(flags, description) {\n    // Support disabling built-in help option.\n    if (typeof flags === 'boolean') {\n      if (flags) {\n        this._helpOption = this._helpOption ?? undefined; // preserve existing option\n      } else {\n        this._helpOption = null; // disable\n      }\n      return this;\n    }\n\n    // Customise flags and description.\n    flags = flags ?? '-h, --help';\n    description = description ?? 'display help for command';\n    this._helpOption = this.createOption(flags, description);\n\n    return this;\n  }\n\n  /**\n   * Lazy create help option.\n   * Returns null if has been disabled with .helpOption(false).\n   *\n   * @returns {(Option | null)} the help option\n   * @package\n   */\n  _getHelpOption() {\n    // Lazy create help option on demand.\n    if (this._helpOption === undefined) {\n      this.helpOption(undefined, undefined);\n    }\n    return this._helpOption;\n  }\n\n  /**\n   * Supply your own option to use for the built-in help option.\n   * This is an alternative to using helpOption() to customise the flags and description etc.\n   *\n   * @param {Option} option\n   * @return {Command} `this` command for chaining\n   */\n  addHelpOption(option) {\n    this._helpOption = option;\n    return this;\n  }\n\n  /**\n   * Output help information and exit.\n   *\n   * Outputs built-in help, and custom text added using `.addHelpText()`.\n   *\n   * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n   */\n\n  help(contextOptions) {\n    this.outputHelp(contextOptions);\n    let exitCode = process.exitCode || 0;\n    if (\n      exitCode === 0 &&\n      contextOptions &&\n      typeof contextOptions !== 'function' &&\n      contextOptions.error\n    ) {\n      exitCode = 1;\n    }\n    // message: do not have all displayed text available so only passing placeholder.\n    this._exit(exitCode, 'commander.help', '(outputHelp)');\n  }\n\n  /**\n   * Add additional text to be displayed with the built-in help.\n   *\n   * Position is 'before' or 'after' to affect just this command,\n   * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n   *\n   * @param {string} position - before or after built-in help\n   * @param {(string | Function)} text - string to add, or a function returning a string\n   * @return {Command} `this` command for chaining\n   */\n  addHelpText(position, text) {\n    const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n    if (!allowedValues.includes(position)) {\n      throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n    }\n    const helpEvent = `${position}Help`;\n    this.on(helpEvent, (context) => {\n      let helpStr;\n      if (typeof text === 'function') {\n        helpStr = text({ error: context.error, command: context.command });\n      } else {\n        helpStr = text;\n      }\n      // Ignore falsy value when nothing to output.\n      if (helpStr) {\n        context.write(`${helpStr}\\n`);\n      }\n    });\n    return this;\n  }\n\n  /**\n   * Output help information if help flags specified\n   *\n   * @param {Array} args - array of options to search for help flags\n   * @private\n   */\n\n  _outputHelpIfRequested(args) {\n    const helpOption = this._getHelpOption();\n    const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n    if (helpRequested) {\n      this.outputHelp();\n      // (Do not have all displayed text available so only passing placeholder.)\n      this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n    }\n  }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n  // Testing for these options:\n  //  --inspect[=[host:]port]\n  //  --inspect-brk[=[host:]port]\n  //  --inspect-port=[host:]port\n  return args.map((arg) => {\n    if (!arg.startsWith('--inspect')) {\n      return arg;\n    }\n    let debugOption;\n    let debugHost = '127.0.0.1';\n    let debugPort = '9229';\n    let match;\n    if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n      // e.g. --inspect\n      debugOption = match[1];\n    } else if (\n      (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n    ) {\n      debugOption = match[1];\n      if (/^\\d+$/.test(match[3])) {\n        // e.g. --inspect=1234\n        debugPort = match[3];\n      } else {\n        // e.g. --inspect=localhost\n        debugHost = match[3];\n      }\n    } else if (\n      (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n    ) {\n      // e.g. --inspect=localhost:1234\n      debugOption = match[1];\n      debugHost = match[3];\n      debugPort = match[4];\n    }\n\n    if (debugOption && debugPort !== '0') {\n      return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n    }\n    return arg;\n  });\n}\n\nexports.Command = Command;\n", "const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n", "import type { DecodedBundle } from '@skillet/protocol';\n\n/**\n * Where this adapter writes:\n * - \"global\": a single absolute root per host (e.g. `~/.claude/skills`).\n * - \"project\": a path *inside the current project cwd* (e.g. `.windsurf/rules`).\n *\n * Project adapters resolve their absolute root via `projectRoot(cwd)` and\n * are validated against `PROJECT_TARGET_ALLOWLIST` instead of the global\n * `MATERIALIZATION_ROOT_ALLOWLIST`.\n *\n * Omitting `kind` is treated as `\"global\"` for backward compatibility with\n * the v1 SKILL.md-native adapters (Claude Code, Codex, Hermes, OpenClaw,\n * Cursor, Windsurf).\n */\nexport type AdapterKind = 'global' | 'project';\n\nexport interface Adapter {\n  /** Stable runtime key, e.g. \"claude-code\". */\n  name: string;\n  /**\n   * @default \"global\"\n   *\n   * \"global\" \u2014 single host-wide directory listed in\n   * `MATERIALIZATION_ROOT_ALLOWLIST`. Examples: Claude Code, Codex,\n   * Hermes, OpenClaw.\n   *\n   * \"project\" \u2014 per-project directory under the current working tree.\n   * Example: Windsurf (`.windsurf/rules`). Project adapters MUST also\n   * implement `projectRoot(cwd)`.\n   */\n  kind?: AdapterKind;\n  /**\n   * For `kind === \"global\"`: the allowlisted absolute root the runtime\n   * materializes into (e.g. `~/.claude/skills`).\n   *\n   * For `kind === \"project\"`: a stable POSIX-relative path under the\n   * project cwd (e.g. `.windsurf/rules`) \u2014 used as the allowlist key and\n   * for display. The absolute path comes from `projectRoot(cwd)`.\n   */\n  targetDir: string;\n  /** True if this runtime is installed on the host (or, for a project\n   * adapter, discoverable from the host environment). */\n  detect(): Promise<boolean>;\n  /**\n   * Required for `kind === \"project\"`: resolve the absolute root for the\n   * given project working directory.\n   *\n   * Implementations should return `join(cwd, this.targetDir)` (or\n   * equivalent) so the relative POSIX path in `targetDir` stays the\n   * single source of truth.\n   */\n  projectRoot?(cwd: string): string;\n  /**\n   * Optional: when sync cwd is outside a project tree (e.g. `~/.skillet` for\n   * the desktop sidecar), resolve the project cwd to use for materialize.\n   * Return null/undefined to fall back to sync cwd.\n   */\n  resolveMaterializeCwd?(syncCwd: string): Promise<string | null | undefined>;\n  /**\n   * Optional bundle translator. When present, the adapter translates an\n   * incoming SKILL.md bundle into its runtime-native files *before*\n   * anything is written to disk.\n   *\n   * Returns a new `DecodedBundle` whose keys are POSIX-relative paths\n   * under the adapter's per-skill write root. When omitted, the bytes\n   * are written verbatim.\n   *\n   * Hashing, signature verification, and approval all run against the\n   * *original* bundle bytes; `transform` is purely a write-side\n   * representation change.\n   */\n  transform?(\n    slug: string,\n    bundle: DecodedBundle,\n    opts?: MaterializeOptions,\n  ): DecodedBundle | Promise<DecodedBundle>;\n  /**\n   * Write the full bundle tree under the adapter's per-skill root.\n   *\n   * Returns the absolute paths of every file written. The first entry is\n   * the skill's `SKILL.md` (or, for `transform`-using adapters, the\n   * representative native entrypoint) so callers that only need an\n   * entrypoint can `[0]`-index; the rest preserve bundle order (sorted\n   * lexicographically by bundle path).\n   */\n  materialize(slug: string, bundle: DecodedBundle, opts?: MaterializeOptions): Promise<string[]>;\n  /**\n   * Absolute path of the skill's `SKILL.md` (or representative entrypoint\n   * for `transform`-using adapters) for the given slug under this\n   * adapter. Used by sync to read what's currently on disk before\n   * computing the graded diff (\u00A76.2).\n   */\n  targetPath(slug: string, opts?: TargetPathOptions): string;\n  /**\n   * Absolute path of the skill's root directory. The entire bundle (or\n   * its transformed projection) lives underneath this.\n   */\n  targetSkillDir(slug: string, opts?: TargetPathOptions): string;\n  /**\n   * Optional: detect existing skills on disk that the runtime would load\n   * before the Skillet-synced copy under `targetDir`.\n   *\n   * A runtime with multiple skill search paths (e.g. OpenClaw's six-level\n   * precedence) may silently shadow a Skillet sync if a higher-precedence dir\n   * holds a same-slug skill. Adapters that scope shadowing per workspace\n   * use `opts.workspaceDir`; others ignore it.\n   *\n   * Returning an empty array means no shadow was detected. Implementations\n   * MUST NOT throw on I/O errors \u2014 a missing search path is not a shadow.\n   */\n  findShadows?(slug: string, opts?: ShadowFindOptions): Promise<ShadowFinding[]>;\n}\n\nexport interface MaterializeOptions {\n  /** Owner handle (without leading `@`); empty/undefined \u2192 unowned namespace. */\n  owner?: string | null;\n  /** Required for `kind === \"project\"` adapters; ignored by global adapters. */\n  cwd?: string;\n  /** Override the default `<owner>--<slug>` materialized directory name. */\n  dirName?: string;\n  /** Kit entry description when SKILL.md frontmatter is missing or edited away. */\n  description?: string;\n}\n\nexport interface TargetPathOptions {\n  owner?: string | null;\n  /** Required for `kind === \"project\"` adapters; ignored by global adapters. */\n  cwd?: string;\n  /** Override the default `<owner>--<slug>` materialized directory name. */\n  dirName?: string;\n}\n\n/**\n * Apply an adapter's `transform` hook (if any) and return the bundle that\n * should be written to disk. Returns the input bundle unchanged when the\n * adapter does not declare a transform.\n *\n * Adapter implementations should call this from `materialize()` so callers\n * never have to know whether a given adapter rewrites bytes.\n */\nexport async function applyAdapterTransform(\n  adapter: Pick<Adapter, 'transform'>,\n  slug: string,\n  bundle: DecodedBundle,\n  opts?: MaterializeOptions,\n): Promise<DecodedBundle> {\n  if (!adapter.transform) return bundle;\n  return await adapter.transform(slug, bundle, opts);\n}\n\nexport interface ShadowFindOptions {\n  /** Owner handle (without leading `@`); empty/undefined \u2192 unowned namespace. */\n  owner?: string | null;\n  /** Override the default `<owner>--<slug>` materialized directory name. */\n  dirName?: string;\n  /**\n   * Project root the runtime treats as the current workspace. Adapters with\n   * workspace-scoped search paths (e.g. OpenClaw) check inside this dir.\n   * Adapters that only consult HOME-level paths can ignore it.\n   */\n  workspaceDir?: string;\n}\n\nexport interface ShadowFinding {\n  /** Absolute path of the higher-precedence skill that shadows the Skillet copy. */\n  path: string;\n  /**\n   * Short human-readable label for the shadowing location, e.g.\n   * `<workspace>/skills` or `~/.agents/skills`. Used by the CLI to render\n   * a clear warning without leaking absolute home paths into stdout.\n   */\n  location: string;\n}\n\n/**\n * Thrown from `Adapter.materialize` when the adapter is DETECTED but not yet\n * ready to receive skills \u2014 e.g. the harness config root does not exist because\n * the app has never been launched. This is a benign SKIP, not a materialize\n * failure: sync surfaces it as a warning and leaves the skill pending so the\n * next run retries once the agent is set up. Callers that gate exit codes on\n * materialize failures (import's `applyToAgents`, the sync summary) must not\n * treat it as one.\n */\nexport class AdapterSkipError extends Error {\n  readonly adapterSkip = true;\n  constructor(message: string) {\n    super(message);\n    this.name = 'AdapterSkipError';\n  }\n}\n", "/**\n * The registry's canonical API version prefix (PROTOCOL.md \u00A70 mandates\n * `/api/v1/`). Every core/CLI caller builds registry URLs off this constant \u2014\n * `${registryUrl}${REGISTRY_API}/\u2026` \u2014 so a future version bump is a one-line\n * edit rather than a sweep across every command. A guard test (registry-api\n * prefix guard) fails the build if a raw `/api/v1` literal reappears.\n */\nexport const REGISTRY_API = '/api/v1'\n", "import { createRequire } from 'module';\nvar require = createRequire('/');\n// DEFLATE is a complex format; to read this code, you should probably check the RFC first:\n// https://tools.ietf.org/html/rfc1951\n// You may also wish to take a look at the guide I made about this program:\n// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad\n// Some of the following code is similar to that of UZIP.js:\n// https://github.com/photopea/UZIP.js\n// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.\n// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint\n// is better for memory in most engines (I *think*).\nvar _a;\n// Mediocre shim\nvar Worker;\nvar isMarkedAsUntransferable;\nvar workerAdd = \";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global\";\ntry {\n    (_a = require('worker_threads'), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable);\n}\ncatch (e) {\n}\nvar wk = Worker ? function (c, _, msg, transfer, cb) {\n    var done = false;\n    var w = new Worker(c + workerAdd, { eval: true })\n        .on('error', function (e) { return cb(e, null); })\n        .on('message', function (m) { return cb(null, m); })\n        .on('exit', function (c) {\n        if (c && !done)\n            cb(new Error('exited with code ' + c), null);\n    });\n    if (isMarkedAsUntransferable)\n        transfer = transfer.filter(function (t) { return !isMarkedAsUntransferable(t); });\n    w.postMessage(msg, transfer);\n    w.terminate = function () {\n        done = true;\n        return Worker.prototype.terminate.call(w);\n    };\n    return w;\n} : function (_, __, ___, ____, cb) {\n    setImmediate(function () { return cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null); });\n    var NOP = function () { };\n    return {\n        terminate: NOP,\n        postMessage: NOP\n    };\n};\n\n// aliases for shorter compressed code (most minifers don't do this)\nvar u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;\n// fixed length extra bits\nvar fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);\n// fixed distance extra bits\nvar fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);\n// code length index map\nvar clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);\n// get base, reverse index map from extra bits\nvar freb = function (eb, start) {\n    var b = new u16(31);\n    for (var i = 0; i < 31; ++i) {\n        b[i] = start += 1 << eb[i - 1];\n    }\n    // numbers here are at max 18 bits\n    var r = new i32(b[30]);\n    for (var i = 1; i < 30; ++i) {\n        for (var j = b[i]; j < b[i + 1]; ++j) {\n            r[j] = ((j - b[i]) << 5) | i;\n        }\n    }\n    return { b: b, r: r };\n};\nvar _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;\n// we can ignore the fact that the other numbers are wrong; they never happen anyway\nfl[28] = 258, revfl[258] = 28;\nvar _b = freb(fdeb, 0), fd = _b.b, revfd = _b.r;\n// map of value to reverse (assuming 16 bits)\nvar rev = new u16(32768);\nfor (var i = 0; i < 32768; ++i) {\n    // reverse table algorithm from SO\n    var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);\n    x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);\n    x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);\n    rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;\n}\n// create huffman tree from u8 \"map\": index -> code length for code index\n// mb (max bits) must be at most 15\n// TODO: optimize/split up?\nvar hMap = (function (cd, mb, r) {\n    var s = cd.length;\n    // index\n    var i = 0;\n    // u16 \"map\": index -> # of codes with bit length = index\n    var l = new u16(mb);\n    // length of cd must be 288 (total # of codes)\n    for (; i < s; ++i) {\n        if (cd[i])\n            ++l[cd[i] - 1];\n    }\n    // u16 \"map\": index -> minimum code for bit length = index\n    var le = new u16(mb);\n    for (i = 1; i < mb; ++i) {\n        le[i] = (le[i - 1] + l[i - 1]) << 1;\n    }\n    var co;\n    if (r) {\n        // u16 \"map\": index -> number of actual bits, symbol for code\n        co = new u16(1 << mb);\n        // bits to remove for reverser\n        var rvb = 15 - mb;\n        for (i = 0; i < s; ++i) {\n            // ignore 0 lengths\n            if (cd[i]) {\n                // num encoding both symbol and bits read\n                var sv = (i << 4) | cd[i];\n                // free bits\n                var r_1 = mb - cd[i];\n                // start value\n                var v = le[cd[i] - 1]++ << r_1;\n                // m is end value\n                for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {\n                    // every 16 bit value starting with the code yields the same result\n                    co[rev[v] >> rvb] = sv;\n                }\n            }\n        }\n    }\n    else {\n        co = new u16(s);\n        for (i = 0; i < s; ++i) {\n            if (cd[i]) {\n                co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);\n            }\n        }\n    }\n    return co;\n});\n// fixed length tree\nvar flt = new u8(288);\nfor (var i = 0; i < 144; ++i)\n    flt[i] = 8;\nfor (var i = 144; i < 256; ++i)\n    flt[i] = 9;\nfor (var i = 256; i < 280; ++i)\n    flt[i] = 7;\nfor (var i = 280; i < 288; ++i)\n    flt[i] = 8;\n// fixed distance tree\nvar fdt = new u8(32);\nfor (var i = 0; i < 32; ++i)\n    fdt[i] = 5;\n// fixed length map\nvar flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1);\n// fixed distance map\nvar fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);\n// find max of array\nvar max = function (a) {\n    var m = a[0];\n    for (var i = 1; i < a.length; ++i) {\n        if (a[i] > m)\n            m = a[i];\n    }\n    return m;\n};\n// read d, starting at bit p and mask with m\nvar bits = function (d, p, m) {\n    var o = (p / 8) | 0;\n    return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;\n};\n// read d, starting at bit p continuing for at least 16 bits\nvar bits16 = function (d, p) {\n    var o = (p / 8) | 0;\n    return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));\n};\n// get end of byte\nvar shft = function (p) { return ((p + 7) / 8) | 0; };\n// typed array slice - allows garbage collector to free original reference,\n// while being more compatible than .slice\nvar slc = function (v, s, e) {\n    if (s == null || s < 0)\n        s = 0;\n    if (e == null || e > v.length)\n        e = v.length;\n    // can't use .constructor in case user-supplied\n    return new u8(v.subarray(s, e));\n};\n/**\n * Codes for errors generated within this library\n */\nexport var FlateErrorCode = {\n    UnexpectedEOF: 0,\n    InvalidBlockType: 1,\n    InvalidLengthLiteral: 2,\n    InvalidDistance: 3,\n    StreamFinished: 4,\n    NoStreamHandler: 5,\n    InvalidHeader: 6,\n    NoCallback: 7,\n    InvalidUTF8: 8,\n    ExtraFieldTooLong: 9,\n    InvalidDate: 10,\n    FilenameTooLong: 11,\n    StreamFinishing: 12,\n    InvalidZipData: 13,\n    UnknownCompressionMethod: 14\n};\n// error codes\nvar ec = [\n    'unexpected EOF',\n    'invalid block type',\n    'invalid length/literal',\n    'invalid distance',\n    'stream finished',\n    'no stream handler',\n    , // determined by compression function\n    'no callback',\n    'invalid UTF-8 data',\n    'extra field too long',\n    'date not in range 1980-2099',\n    'filename too long',\n    'stream finishing',\n    'invalid zip data'\n    // determined by unknown compression method\n];\n;\nvar err = function (ind, msg, nt) {\n    var e = new Error(msg || ec[ind]);\n    e.code = ind;\n    if (Error.captureStackTrace)\n        Error.captureStackTrace(e, err);\n    if (!nt)\n        throw e;\n    return e;\n};\n// expands raw DEFLATE data\nvar inflt = function (dat, st, buf, dict) {\n    // source length       dict length\n    var sl = dat.length, dl = dict ? dict.length : 0;\n    if (!sl || st.f && !st.l)\n        return buf || new u8(0);\n    var noBuf = !buf;\n    // have to estimate size\n    var resize = noBuf || st.i != 2;\n    // no state\n    var noSt = st.i;\n    // Assumes roughly 33% compression ratio average\n    if (noBuf)\n        buf = new u8(sl * 3);\n    // ensure buffer can fit at least l elements\n    var cbuf = function (l) {\n        var bl = buf.length;\n        // need to increase size to fit\n        if (l > bl) {\n            // Double or set to necessary, whichever is greater\n            var nbuf = new u8(Math.max(bl * 2, l));\n            nbuf.set(buf);\n            buf = nbuf;\n        }\n    };\n    //  last chunk         bitpos           bytes\n    var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;\n    // total bits\n    var tbts = sl * 8;\n    do {\n        if (!lm) {\n            // BFINAL - this is only 1 when last chunk is next\n            final = bits(dat, pos, 1);\n            // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman\n            var type = bits(dat, pos + 1, 3);\n            pos += 3;\n            if (!type) {\n                // go to end of byte boundary\n                var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;\n                if (t > sl) {\n                    if (noSt)\n                        err(0);\n                    break;\n                }\n                // ensure size\n                if (resize)\n                    cbuf(bt + l);\n                // Copy over uncompressed data\n                buf.set(dat.subarray(s, t), bt);\n                // Get new bitpos, update byte count\n                st.b = bt += l, st.p = pos = t * 8, st.f = final;\n                continue;\n            }\n            else if (type == 1)\n                lm = flrm, dm = fdrm, lbt = 9, dbt = 5;\n            else if (type == 2) {\n                //  literal                            lengths\n                var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;\n                var tl = hLit + bits(dat, pos + 5, 31) + 1;\n                pos += 14;\n                // length+distance tree\n                var ldt = new u8(tl);\n                // code length tree\n                var clt = new u8(19);\n                for (var i = 0; i < hcLen; ++i) {\n                    // use index map to get real code\n                    clt[clim[i]] = bits(dat, pos + i * 3, 7);\n                }\n                pos += hcLen * 3;\n                // code lengths bits\n                var clb = max(clt), clbmsk = (1 << clb) - 1;\n                // code lengths map\n                var clm = hMap(clt, clb, 1);\n                for (var i = 0; i < tl;) {\n                    var r = clm[bits(dat, pos, clbmsk)];\n                    // bits read\n                    pos += r & 15;\n                    // symbol\n                    var s = r >> 4;\n                    // code length to copy\n                    if (s < 16) {\n                        ldt[i++] = s;\n                    }\n                    else {\n                        //  copy   count\n                        var c = 0, n = 0;\n                        if (s == 16)\n                            n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];\n                        else if (s == 17)\n                            n = 3 + bits(dat, pos, 7), pos += 3;\n                        else if (s == 18)\n                            n = 11 + bits(dat, pos, 127), pos += 7;\n                        while (n--)\n                            ldt[i++] = c;\n                    }\n                }\n                //    length tree                 distance tree\n                var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);\n                // max length bits\n                lbt = max(lt);\n                // max dist bits\n                dbt = max(dt);\n                lm = hMap(lt, lbt, 1);\n                dm = hMap(dt, dbt, 1);\n            }\n            else\n                err(1);\n            if (pos > tbts) {\n                if (noSt)\n                    err(0);\n                break;\n            }\n        }\n        // Make sure the buffer can hold this + the largest possible addition\n        // Maximum chunk size (practically, theoretically infinite) is 2^17\n        if (resize)\n            cbuf(bt + 131072);\n        var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;\n        var lpos = pos;\n        for (;; lpos = pos) {\n            // bits read, code\n            var c = lm[bits16(dat, pos) & lms], sym = c >> 4;\n            pos += c & 15;\n            if (pos > tbts) {\n                if (noSt)\n                    err(0);\n                break;\n            }\n            if (!c)\n                err(2);\n            if (sym < 256)\n                buf[bt++] = sym;\n            else if (sym == 256) {\n                lpos = pos, lm = null;\n                break;\n            }\n            else {\n                var add = sym - 254;\n                // no extra bits needed if less\n                if (sym > 264) {\n                    // index\n                    var i = sym - 257, b = fleb[i];\n                    add = bits(dat, pos, (1 << b) - 1) + fl[i];\n                    pos += b;\n                }\n                // dist\n                var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;\n                if (!d)\n                    err(3);\n                pos += d & 15;\n                var dt = fd[dsym];\n                if (dsym > 3) {\n                    var b = fdeb[dsym];\n                    dt += bits16(dat, pos) & (1 << b) - 1, pos += b;\n                }\n                if (pos > tbts) {\n                    if (noSt)\n                        err(0);\n                    break;\n                }\n                if (resize)\n                    cbuf(bt + 131072);\n                var end = bt + add;\n                if (bt < dt) {\n                    var shift = dl - dt, dend = Math.min(dt, end);\n                    if (shift + bt < 0)\n                        err(3);\n                    for (; bt < dend; ++bt)\n                        buf[bt] = dict[shift + bt];\n                }\n                for (; bt < end; ++bt)\n                    buf[bt] = buf[bt - dt];\n            }\n        }\n        st.l = lm, st.p = lpos, st.b = bt, st.f = final;\n        if (lm)\n            final = 1, st.m = lbt, st.d = dm, st.n = dbt;\n    } while (!final);\n    // don't reallocate for streams or user buffers\n    return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);\n};\n// starting at p, write the minimum number of bits that can hold v to d\nvar wbits = function (d, p, v) {\n    v <<= p & 7;\n    var o = (p / 8) | 0;\n    d[o] |= v;\n    d[o + 1] |= v >> 8;\n};\n// starting at p, write the minimum number of bits (>8) that can hold v to d\nvar wbits16 = function (d, p, v) {\n    v <<= p & 7;\n    var o = (p / 8) | 0;\n    d[o] |= v;\n    d[o + 1] |= v >> 8;\n    d[o + 2] |= v >> 16;\n};\n// creates code lengths from a frequency table\nvar hTree = function (d, mb) {\n    // Need extra info to make a tree\n    var t = [];\n    for (var i = 0; i < d.length; ++i) {\n        if (d[i])\n            t.push({ s: i, f: d[i] });\n    }\n    var s = t.length;\n    var t2 = t.slice();\n    if (!s)\n        return { t: et, l: 0 };\n    if (s == 1) {\n        var v = new u8(t[0].s + 1);\n        v[t[0].s] = 1;\n        return { t: v, l: 1 };\n    }\n    t.sort(function (a, b) { return a.f - b.f; });\n    // after i2 reaches last ind, will be stopped\n    // freq must be greater than largest possible number of symbols\n    t.push({ s: -1, f: 25001 });\n    var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;\n    t[0] = { s: -1, f: l.f + r.f, l: l, r: r };\n    // efficient algorithm from UZIP.js\n    // i0 is lookbehind, i2 is lookahead - after processing two low-freq\n    // symbols that combined have high freq, will start processing i2 (high-freq,\n    // non-composite) symbols instead\n    // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/\n    while (i1 != s - 1) {\n        l = t[t[i0].f < t[i2].f ? i0++ : i2++];\n        r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];\n        t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r };\n    }\n    var maxSym = t2[0].s;\n    for (var i = 1; i < s; ++i) {\n        if (t2[i].s > maxSym)\n            maxSym = t2[i].s;\n    }\n    // code lengths\n    var tr = new u16(maxSym + 1);\n    // max bits in tree\n    var mbt = ln(t[i1 - 1], tr, 0);\n    if (mbt > mb) {\n        // more algorithms from UZIP.js\n        // TODO: find out how this code works (debt)\n        //  ind    debt\n        var i = 0, dt = 0;\n        //    left            cost\n        var lft = mbt - mb, cst = 1 << lft;\n        t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; });\n        for (; i < s; ++i) {\n            var i2_1 = t2[i].s;\n            if (tr[i2_1] > mb) {\n                dt += cst - (1 << (mbt - tr[i2_1]));\n                tr[i2_1] = mb;\n            }\n            else\n                break;\n        }\n        dt >>= lft;\n        while (dt > 0) {\n            var i2_2 = t2[i].s;\n            if (tr[i2_2] < mb)\n                dt -= 1 << (mb - tr[i2_2]++ - 1);\n            else\n                ++i;\n        }\n        for (; i >= 0 && dt; --i) {\n            var i2_3 = t2[i].s;\n            if (tr[i2_3] == mb) {\n                --tr[i2_3];\n                ++dt;\n            }\n        }\n        mbt = mb;\n    }\n    return { t: new u8(tr), l: mbt };\n};\n// get the max length and assign length codes\nvar ln = function (n, l, d) {\n    return n.s == -1\n        ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1))\n        : (l[n.s] = d);\n};\n// length codes generation\nvar lc = function (c) {\n    var s = c.length;\n    // Note that the semicolon was intentional\n    while (s && !c[--s])\n        ;\n    var cl = new u16(++s);\n    //  ind      num         streak\n    var cli = 0, cln = c[0], cls = 1;\n    var w = function (v) { cl[cli++] = v; };\n    for (var i = 1; i <= s; ++i) {\n        if (c[i] == cln && i != s)\n            ++cls;\n        else {\n            if (!cln && cls > 2) {\n                for (; cls > 138; cls -= 138)\n                    w(32754);\n                if (cls > 2) {\n                    w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305);\n                    cls = 0;\n                }\n            }\n            else if (cls > 3) {\n                w(cln), --cls;\n                for (; cls > 6; cls -= 6)\n                    w(8304);\n                if (cls > 2)\n                    w(((cls - 3) << 5) | 8208), cls = 0;\n            }\n            while (cls--)\n                w(cln);\n            cls = 1;\n            cln = c[i];\n        }\n    }\n    return { c: cl.subarray(0, cli), n: s };\n};\n// calculate the length of output from tree, code lengths\nvar clen = function (cf, cl) {\n    var l = 0;\n    for (var i = 0; i < cl.length; ++i)\n        l += cf[i] * cl[i];\n    return l;\n};\n// writes a fixed block\n// returns the new bit pos\nvar wfblk = function (out, pos, dat) {\n    // no need to write 00 as type: TypedArray defaults to 0\n    var s = dat.length;\n    var o = shft(pos + 2);\n    out[o] = s & 255;\n    out[o + 1] = s >> 8;\n    out[o + 2] = out[o] ^ 255;\n    out[o + 3] = out[o + 1] ^ 255;\n    for (var i = 0; i < s; ++i)\n        out[o + i + 4] = dat[i];\n    return (o + 4 + s) * 8;\n};\n// writes a block\nvar wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {\n    wbits(out, p++, final);\n    ++lf[256];\n    var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l;\n    var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l;\n    var _c = lc(dlt), lclt = _c.c, nlc = _c.n;\n    var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;\n    var lcfreq = new u16(19);\n    for (var i = 0; i < lclt.length; ++i)\n        ++lcfreq[lclt[i] & 31];\n    for (var i = 0; i < lcdt.length; ++i)\n        ++lcfreq[lcdt[i] & 31];\n    var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;\n    var nlcc = 19;\n    for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)\n        ;\n    var flen = (bl + 5) << 3;\n    var ftlen = clen(lf, flt) + clen(df, fdt) + eb;\n    var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];\n    if (bs >= 0 && flen <= ftlen && flen <= dtlen)\n        return wfblk(out, p, dat.subarray(bs, bs + bl));\n    var lm, ll, dm, dl;\n    wbits(out, p, 1 + (dtlen < ftlen)), p += 2;\n    if (dtlen < ftlen) {\n        lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;\n        var llm = hMap(lct, mlcb, 0);\n        wbits(out, p, nlc - 257);\n        wbits(out, p + 5, ndc - 1);\n        wbits(out, p + 10, nlcc - 4);\n        p += 14;\n        for (var i = 0; i < nlcc; ++i)\n            wbits(out, p + 3 * i, lct[clim[i]]);\n        p += 3 * nlcc;\n        var lcts = [lclt, lcdt];\n        for (var it = 0; it < 2; ++it) {\n            var clct = lcts[it];\n            for (var i = 0; i < clct.length; ++i) {\n                var len = clct[i] & 31;\n                wbits(out, p, llm[len]), p += lct[len];\n                if (len > 15)\n                    wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12;\n            }\n        }\n    }\n    else {\n        lm = flm, ll = flt, dm = fdm, dl = fdt;\n    }\n    for (var i = 0; i < li; ++i) {\n        var sym = syms[i];\n        if (sym > 255) {\n            var len = (sym >> 18) & 31;\n            wbits16(out, p, lm[len + 257]), p += ll[len + 257];\n            if (len > 7)\n                wbits(out, p, (sym >> 23) & 31), p += fleb[len];\n            var dst = sym & 31;\n            wbits16(out, p, dm[dst]), p += dl[dst];\n            if (dst > 3)\n                wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst];\n        }\n        else {\n            wbits16(out, p, lm[sym]), p += ll[sym];\n        }\n    }\n    wbits16(out, p, lm[256]);\n    return p + ll[256];\n};\n// deflate options (nice << 13) | chain\nvar deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);\n// empty\nvar et = /*#__PURE__*/ new u8(0);\n// compresses data into a raw DEFLATE buffer\nvar dflt = function (dat, lvl, plvl, pre, post, st) {\n    var s = st.z || dat.length;\n    var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);\n    // writing to this writes to the output buffer\n    var w = o.subarray(pre, o.length - post);\n    var lst = st.l;\n    var pos = (st.r || 0) & 7;\n    if (lvl) {\n        if (pos)\n            w[0] = st.r >> 3;\n        var opt = deo[lvl - 1];\n        var n = opt >> 13, c = opt & 8191;\n        var msk_1 = (1 << plvl) - 1;\n        //    prev 2-byte val map    curr 2-byte val map\n        var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);\n        var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;\n        var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; };\n        // 24576 is an arbitrary number of maximum symbols per block\n        // 424 buffer for last block\n        var syms = new i32(25000);\n        // length/literal freq   distance freq\n        var lf = new u16(288), df = new u16(32);\n        //  l/lcnt  exbits  index          l/lind  waitdx          blkpos\n        var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;\n        for (; i + 2 < s; ++i) {\n            // hash value\n            var hv = hsh(i);\n            // index mod 32768    previous index mod\n            var imod = i & 32767, pimod = head[hv];\n            prev[imod] = pimod;\n            head[hv] = imod;\n            // We always should modify head and prev, but only add symbols if\n            // this data is not yet processed (\"wait\" for wait index)\n            if (wi <= i) {\n                // bytes remaining\n                var rem = s - i;\n                if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {\n                    pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);\n                    li = lc_1 = eb = 0, bs = i;\n                    for (var j = 0; j < 286; ++j)\n                        lf[j] = 0;\n                    for (var j = 0; j < 30; ++j)\n                        df[j] = 0;\n                }\n                //  len    dist   chain\n                var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;\n                if (rem > 2 && hv == hsh(i - dif)) {\n                    var maxn = Math.min(n, rem) - 1;\n                    var maxd = Math.min(32767, i);\n                    // max possible length\n                    // not capped at dif because decompressors implement \"rolling\" index population\n                    var ml = Math.min(258, rem);\n                    while (dif <= maxd && --ch_1 && imod != pimod) {\n                        if (dat[i + l] == dat[i + l - dif]) {\n                            var nl = 0;\n                            for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)\n                                ;\n                            if (nl > l) {\n                                l = nl, d = dif;\n                                // break out early when we reach \"nice\" (we are satisfied enough)\n                                if (nl > maxn)\n                                    break;\n                                // now, find the rarest 2-byte sequence within this\n                                // length of literals and search for that instead.\n                                // Much faster than just using the start\n                                var mmd = Math.min(dif, nl - 2);\n                                var md = 0;\n                                for (var j = 0; j < mmd; ++j) {\n                                    var ti = i - dif + j & 32767;\n                                    var pti = prev[ti];\n                                    var cd = ti - pti & 32767;\n                                    if (cd > md)\n                                        md = cd, pimod = ti;\n                                }\n                            }\n                        }\n                        // check the previous match\n                        imod = pimod, pimod = prev[imod];\n                        dif += imod - pimod & 32767;\n                    }\n                }\n                // d will be nonzero only when a match was found\n                if (d) {\n                    // store both dist and len data in one int32\n                    // Make sure this is recognized as a len/dist with 28th bit (2^28)\n                    syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d];\n                    var lin = revfl[l] & 31, din = revfd[d] & 31;\n                    eb += fleb[lin] + fdeb[din];\n                    ++lf[257 + lin];\n                    ++df[din];\n                    wi = i + l;\n                    ++lc_1;\n                }\n                else {\n                    syms[li++] = dat[i];\n                    ++lf[dat[i]];\n                }\n            }\n        }\n        for (i = Math.max(i, wi); i < s; ++i) {\n            syms[li++] = dat[i];\n            ++lf[dat[i]];\n        }\n        pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);\n        if (!lst) {\n            st.r = (pos & 7) | w[(pos / 8) | 0] << 3;\n            // shft(pos) now 1 less if pos & 7 != 0\n            pos -= 7;\n            st.h = head, st.p = prev, st.i = i, st.w = wi;\n        }\n    }\n    else {\n        for (var i = st.w || 0; i < s + lst; i += 65535) {\n            // end\n            var e = i + 65535;\n            if (e >= s) {\n                // write final block\n                w[(pos / 8) | 0] = lst;\n                e = s;\n            }\n            pos = wfblk(w, pos + 1, dat.subarray(i, e));\n        }\n        st.i = s;\n    }\n    return slc(o, 0, pre + shft(pos) + post);\n};\n// CRC32 table\nvar crct = /*#__PURE__*/ (function () {\n    var t = new Int32Array(256);\n    for (var i = 0; i < 256; ++i) {\n        var c = i, k = 9;\n        while (--k)\n            c = ((c & 1) && -306674912) ^ (c >>> 1);\n        t[i] = c;\n    }\n    return t;\n})();\n// CRC32\nvar crc = function () {\n    var c = -1;\n    return {\n        p: function (d) {\n            // closures have awful performance\n            var cr = c;\n            for (var i = 0; i < d.length; ++i)\n                cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8);\n            c = cr;\n        },\n        d: function () { return ~c; }\n    };\n};\n// Adler32\nvar adler = function () {\n    var a = 1, b = 0;\n    return {\n        p: function (d) {\n            // closures have awful performance\n            var n = a, m = b;\n            var l = d.length | 0;\n            for (var i = 0; i != l;) {\n                var e = Math.min(i + 2655, l);\n                for (; i < e; ++i)\n                    m += n += d[i];\n                n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);\n            }\n            a = n, b = m;\n        },\n        d: function () {\n            a %= 65521, b %= 65521;\n            return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8);\n        }\n    };\n};\n;\n// deflate with opts\nvar dopt = function (dat, opt, pre, post, st) {\n    if (!st) {\n        st = { l: 1 };\n        if (opt.dictionary) {\n            var dict = opt.dictionary.subarray(-32768);\n            var newDat = new u8(dict.length + dat.length);\n            newDat.set(dict);\n            newDat.set(dat, dict.length);\n            dat = newDat;\n            st.w = dict.length;\n        }\n    }\n    return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st);\n};\n// Walmart object spread\nvar mrg = function (a, b) {\n    var o = {};\n    for (var k in a)\n        o[k] = a[k];\n    for (var k in b)\n        o[k] = b[k];\n    return o;\n};\n// worker clone\n// This is possibly the craziest part of the entire codebase, despite how simple it may seem.\n// The only parameter to this function is a closure that returns an array of variables outside of the function scope.\n// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization.\n// We will return an object mapping of true variable name to value (basically, the current scope as a JS object).\n// The reason we can't just use the original variable names is minifiers mangling the toplevel scope.\n// This took me three weeks to figure out how to do.\nvar wcln = function (fn, fnStr, td) {\n    var dt = fn();\n    var st = fn.toString();\n    var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\\s+/g, '').split(',');\n    for (var i = 0; i < dt.length; ++i) {\n        var v = dt[i], k = ks[i];\n        if (typeof v == 'function') {\n            fnStr += ';' + k + '=';\n            var st_1 = v.toString();\n            if (v.prototype) {\n                // for global objects\n                if (st_1.indexOf('[native code]') != -1) {\n                    var spInd = st_1.indexOf(' ', 8) + 1;\n                    fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd));\n                }\n                else {\n                    fnStr += st_1;\n                    for (var t in v.prototype)\n                        fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();\n                }\n            }\n            else\n                fnStr += st_1;\n        }\n        else\n            td[k] = v;\n    }\n    return fnStr;\n};\nvar ch = [];\n// clone bufs\nvar cbfs = function (v) {\n    var tl = [];\n    for (var k in v) {\n        if (v[k].buffer) {\n            tl.push((v[k] = new v[k].constructor(v[k])).buffer);\n        }\n    }\n    return tl;\n};\n// use a worker to execute code\nvar wrkr = function (fns, init, id, cb) {\n    if (!ch[id]) {\n        var fnStr = '', td_1 = {}, m = fns.length - 1;\n        for (var i = 0; i < m; ++i)\n            fnStr = wcln(fns[i], fnStr, td_1);\n        ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 };\n    }\n    var td = mrg({}, ch[id].e);\n    return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb);\n};\n// base async inflate fn\nvar bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; };\nvar bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; };\n// gzip extra\nvar gze = function () { return [gzh, gzhl, wbytes, crc, crct]; };\n// gunzip extra\nvar guze = function () { return [gzs, gzl]; };\n// zlib extra\nvar zle = function () { return [zlh, wbytes, adler]; };\n// unzlib extra\nvar zule = function () { return [zls]; };\n// post buf\nvar pbf = function (msg) { return postMessage(msg, [msg.buffer]); };\n// get opts\nvar gopt = function (o) { return o && {\n    out: o.size && new u8(o.size),\n    dictionary: o.dictionary\n}; };\n// async helper\nvar cbify = function (dat, opts, fns, init, id, cb) {\n    var w = wrkr(fns, init, id, function (err, dat) {\n        w.terminate();\n        cb(err, dat);\n    });\n    w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []);\n    return function () { w.terminate(); };\n};\n// auto stream\nvar astrm = function (strm) {\n    strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); };\n    return function (ev) {\n        if (ev.data[0]) {\n            strm.push(ev.data[0], ev.data[1]);\n            postMessage([ev.data[0].length]);\n        }\n        else\n            strm.flush(ev.data[1]);\n    };\n};\n// async stream attach\nvar astrmify = function (fns, strm, opts, init, id, flush, ext) {\n    var t;\n    var w = wrkr(fns, init, id, function (err, dat) {\n        if (err)\n            w.terminate(), strm.ondata.call(strm, err);\n        else if (!Array.isArray(dat))\n            ext(dat);\n        else if (dat.length == 1) {\n            strm.queuedSize -= dat[0];\n            if (strm.ondrain)\n                strm.ondrain(dat[0]);\n        }\n        else {\n            if (dat[1])\n                w.terminate();\n            strm.ondata.call(strm, err, dat[0], dat[1]);\n        }\n    });\n    w.postMessage(opts);\n    strm.queuedSize = 0;\n    strm.push = function (d, f) {\n        if (!strm.ondata)\n            err(5);\n        if (t)\n            strm.ondata(err(4, 0, 1), null, !!f);\n        strm.queuedSize += d.length;\n        // can fail for cross-realm Uint8Array, but ok - only a small performance penalty\n        w.postMessage([d, t = f], d.buffer instanceof ArrayBuffer ? [d.buffer] : []);\n    };\n    strm.terminate = function () { w.terminate(); };\n    if (flush) {\n        strm.flush = function (sync) { w.postMessage([0, sync]); };\n    }\n};\n// read 2 bytes\nvar b2 = function (d, b) { return d[b] | (d[b + 1] << 8); };\n// read 4 bytes\nvar b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };\n// read 8 bytes\nvar b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); };\n// write bytes\nvar wbytes = function (d, b, v) {\n    for (; v; ++b)\n        d[b] = v, v >>>= 8;\n};\n// gzip header\nvar gzh = function (c, o) {\n    var fn = o.filename;\n    c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix\n    if (o.mtime != 0)\n        wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000));\n    if (fn) {\n        c[3] = 8;\n        for (var i = 0; i <= fn.length; ++i)\n            c[i + 10] = fn.charCodeAt(i);\n    }\n};\n// gzip footer: -8 to -4 = CRC, -4 to -0 is length\n// gzip start\nvar gzs = function (d) {\n    if (d[0] != 31 || d[1] != 139 || d[2] != 8)\n        err(6, 'invalid gzip data');\n    var flg = d[3];\n    var st = 10;\n    if (flg & 4)\n        st += (d[10] | d[11] << 8) + 2;\n    for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])\n        ;\n    return st + (flg & 2);\n};\n// gzip length\nvar gzl = function (d) {\n    var l = d.length;\n    return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;\n};\n// gzip header length\nvar gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); };\n// zlib header\nvar zlh = function (c, o) {\n    var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;\n    c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32);\n    c[1] |= 31 - ((c[0] << 8) | c[1]) % 31;\n    if (o.dictionary) {\n        var h = adler();\n        h.p(o.dictionary);\n        wbytes(c, 2, h.d());\n    }\n};\n// zlib start\nvar zls = function (d, dict) {\n    if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))\n        err(6, 'invalid zlib data');\n    if ((d[1] >> 5 & 1) == +!dict)\n        err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');\n    return (d[1] >> 3 & 4) + 2;\n};\nfunction StrmOpt(opts, cb) {\n    if (typeof opts == 'function')\n        cb = opts, opts = {};\n    this.ondata = cb;\n    return opts;\n}\n/**\n * Streaming DEFLATE compression\n */\nvar Deflate = /*#__PURE__*/ (function () {\n    function Deflate(opts, cb) {\n        if (typeof opts == 'function')\n            cb = opts, opts = {};\n        this.ondata = cb;\n        this.o = opts || {};\n        this.s = { l: 0, i: 32768, w: 32768, z: 32768 };\n        // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev\n        // 98304 = 32768 (lookback) + 65536 (common chunk size)\n        this.b = new u8(98304);\n        if (this.o.dictionary) {\n            var dict = this.o.dictionary.subarray(-32768);\n            this.b.set(dict, 32768 - dict.length);\n            this.s.i = 32768 - dict.length;\n        }\n    }\n    Deflate.prototype.p = function (c, f) {\n        this.ondata(dopt(c, this.o, 0, 0, this.s), f);\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Deflate.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (this.s.l)\n            err(4);\n        var endLen = chunk.length + this.s.z;\n        if (endLen > this.b.length) {\n            if (endLen > 2 * this.b.length - 32768) {\n                var newBuf = new u8(endLen & -32768);\n                newBuf.set(this.b.subarray(0, this.s.z));\n                this.b = newBuf;\n            }\n            var split = this.b.length - this.s.z;\n            this.b.set(chunk.subarray(0, split), this.s.z);\n            this.s.z = this.b.length;\n            this.p(this.b, false);\n            this.b.set(this.b.subarray(-32768));\n            this.b.set(chunk.subarray(split), 32768);\n            this.s.z = chunk.length - split + 32768;\n            this.s.i = 32766, this.s.w = 32768;\n        }\n        else {\n            this.b.set(chunk, this.s.z);\n            this.s.z += chunk.length;\n        }\n        this.s.l = final & 1;\n        if (this.s.z > this.s.w + 8191 || final) {\n            this.p(this.b, final || false);\n            this.s.w = this.s.i, this.s.i -= 2;\n        }\n        if (final) {\n            // cleanup unneeded buffers/state to reduce memory usage\n            this.s = this.o = {};\n            this.b = et;\n        }\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * deflated output for small inputs.\n     * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n     *             extra bytes, but guarantees all pushed data is immediately\n     *             decompressible. A separate DEFLATE stream may be concatenated\n     *             with the current output after a sync flush.\n     */\n    Deflate.prototype.flush = function (sync) {\n        if (!this.ondata)\n            err(5);\n        if (this.s.l)\n            err(4);\n        this.p(this.b, false);\n        this.s.w = this.s.i, this.s.i -= 2;\n        // could technically skip writing the type-0 block for (this.s.r & 7) == 0,\n        // but the deterministic trailer (00 00 FF FF) is useful in some situations\n        if (sync) {\n            var c = new u8(6);\n            c[0] = this.s.r >> 3;\n            // write empty, non-final type-0 block\n            var ep = wfblk(c, this.s.r, et);\n            this.s.r = 0;\n            this.ondata(c.subarray(0, ep >> 3), false);\n        }\n    };\n    return Deflate;\n}());\nexport { Deflate };\n/**\n * Asynchronous streaming DEFLATE compression\n */\nvar AsyncDeflate = /*#__PURE__*/ (function () {\n    function AsyncDeflate(opts, cb) {\n        astrmify([\n            bDflt,\n            function () { return [astrm, Deflate]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Deflate(ev.data);\n            onmessage = astrm(strm);\n        }, 6, 1);\n    }\n    return AsyncDeflate;\n}());\nexport { AsyncDeflate };\nexport function deflate(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n    ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb);\n}\n/**\n * Compresses data with DEFLATE without any wrapper\n * @param data The data to compress\n * @param opts The compression options\n * @returns The deflated version of the data\n */\nexport function deflateSync(data, opts) {\n    return dopt(data, opts || {}, 0, 0);\n}\n/**\n * Streaming DEFLATE decompression\n */\nvar Inflate = /*#__PURE__*/ (function () {\n    function Inflate(opts, cb) {\n        // no StrmOpt here to avoid adding to workerizer\n        if (typeof opts == 'function')\n            cb = opts, opts = {};\n        this.ondata = cb;\n        var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);\n        this.s = { i: 0, b: dict ? dict.length : 0 };\n        this.o = new u8(32768);\n        this.p = new u8(0);\n        if (dict)\n            this.o.set(dict);\n    }\n    Inflate.prototype.e = function (c) {\n        if (!this.ondata)\n            err(5);\n        if (this.d)\n            err(4);\n        if (!this.p.length)\n            this.p = c;\n        else if (c.length) {\n            var n = new u8(this.p.length + c.length);\n            n.set(this.p), n.set(c, this.p.length), this.p = n;\n        }\n    };\n    Inflate.prototype.c = function (final) {\n        this.s.i = +(this.d = final || false);\n        var bts = this.s.b;\n        var dt = inflt(this.p, this.s, this.o);\n        this.ondata(slc(dt, bts, this.s.b), this.d);\n        this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;\n        this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7;\n    };\n    /**\n     * Pushes a chunk to be inflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the final chunk\n     */\n    Inflate.prototype.push = function (chunk, final) {\n        this.e(chunk), this.c(final);\n    };\n    return Inflate;\n}());\nexport { Inflate };\n/**\n * Asynchronous streaming DEFLATE decompression\n */\nvar AsyncInflate = /*#__PURE__*/ (function () {\n    function AsyncInflate(opts, cb) {\n        astrmify([\n            bInflt,\n            function () { return [astrm, Inflate]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Inflate(ev.data);\n            onmessage = astrm(strm);\n        }, 7, 0);\n    }\n    return AsyncInflate;\n}());\nexport { AsyncInflate };\nexport function inflate(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt\n    ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb);\n}\nexport function inflateSync(data, opts) {\n    return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize.\n/**\n * Streaming GZIP compression\n */\nvar Gzip = /*#__PURE__*/ (function () {\n    function Gzip(opts, cb) {\n        this.c = crc();\n        this.l = 0;\n        this.v = 1;\n        Deflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be GZIPped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Gzip.prototype.push = function (chunk, final) {\n        this.c.p(chunk);\n        this.l += chunk.length;\n        Deflate.prototype.push.call(this, chunk, final);\n    };\n    Gzip.prototype.p = function (c, f) {\n        var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s);\n        if (this.v)\n            gzh(raw, this.o), this.v = 0;\n        if (f)\n            wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l);\n        this.ondata(raw, f);\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * GZIPped output for small inputs.\n     * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n     *             extra bytes, but guarantees all pushed data is immediately\n     *             decompressible.\n     */\n    Gzip.prototype.flush = function (sync) {\n        Deflate.prototype.flush.call(this, sync);\n    };\n    return Gzip;\n}());\nexport { Gzip };\n/**\n * Asynchronous streaming GZIP compression\n */\nvar AsyncGzip = /*#__PURE__*/ (function () {\n    function AsyncGzip(opts, cb) {\n        astrmify([\n            bDflt,\n            gze,\n            function () { return [astrm, Deflate, Gzip]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Gzip(ev.data);\n            onmessage = astrm(strm);\n        }, 8, 1);\n    }\n    return AsyncGzip;\n}());\nexport { AsyncGzip };\nexport function gzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n        gze,\n        function () { return [gzipSync]; }\n    ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb);\n}\n/**\n * Compresses data with GZIP\n * @param data The data to compress\n * @param opts The compression options\n * @returns The gzipped version of the data\n */\nexport function gzipSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var c = crc(), l = data.length;\n    c.p(data);\n    var d = dopt(data, opts, gzhl(opts), 8), s = d.length;\n    return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d;\n}\n/**\n * Streaming single or multi-member GZIP decompression\n */\nvar Gunzip = /*#__PURE__*/ (function () {\n    function Gunzip(opts, cb) {\n        this.v = 1;\n        this.r = 0;\n        Inflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be GUNZIPped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Gunzip.prototype.push = function (chunk, final) {\n        Inflate.prototype.e.call(this, chunk);\n        this.r += chunk.length;\n        if (this.v) {\n            var p = this.p.subarray(this.v - 1);\n            var s = p.length > 3 ? gzs(p) : 4;\n            if (s > p.length) {\n                if (!final)\n                    return;\n            }\n            else if (this.v > 1 && this.onmember) {\n                this.onmember(this.r - p.length);\n            }\n            this.p = p.subarray(s), this.v = 0;\n        }\n        // necessary to prevent TS from using the closure value\n        // This allows for workerization to function correctly\n        Inflate.prototype.c.call(this, 0);\n        // process concatenated GZIP\n        if (this.s.f && !this.s.l) {\n            this.v = shft(this.s.p) + 9;\n            this.s = { i: 0 };\n            this.o = new u8(0);\n            this.push(new u8(0), final);\n        }\n        else if (final) {\n            Inflate.prototype.c.call(this, final);\n        }\n    };\n    return Gunzip;\n}());\nexport { Gunzip };\n/**\n * Asynchronous streaming single or multi-member GZIP decompression\n */\nvar AsyncGunzip = /*#__PURE__*/ (function () {\n    function AsyncGunzip(opts, cb) {\n        var _this = this;\n        astrmify([\n            bInflt,\n            guze,\n            function () { return [astrm, Inflate, Gunzip]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Gunzip(ev.data);\n            strm.onmember = function (offset) { return postMessage(offset); };\n            onmessage = astrm(strm);\n        }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); });\n    }\n    return AsyncGunzip;\n}());\nexport { AsyncGunzip };\nexport function gunzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt,\n        guze,\n        function () { return [gunzipSync]; }\n    ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb);\n}\nexport function gunzipSync(data, opts) {\n    var st = gzs(data);\n    if (st + 8 > data.length)\n        err(6, 'invalid gzip data');\n    return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);\n}\n/**\n * Streaming Zlib compression\n */\nvar Zlib = /*#__PURE__*/ (function () {\n    function Zlib(opts, cb) {\n        this.c = adler();\n        this.v = 1;\n        Deflate.call(this, opts, cb);\n    }\n    /**\n     * Pushes a chunk to be zlibbed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Zlib.prototype.push = function (chunk, final) {\n        this.c.p(chunk);\n        Deflate.prototype.push.call(this, chunk, final);\n    };\n    Zlib.prototype.p = function (c, f) {\n        var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s);\n        if (this.v)\n            zlh(raw, this.o), this.v = 0;\n        if (f)\n            wbytes(raw, raw.length - 4, this.c.d());\n        this.ondata(raw, f);\n    };\n    /**\n     * Flushes buffered uncompressed data. Useful to immediately retrieve the\n     * zlibbed output for small inputs.\n     * @param sync Whether to flush to a byte boundary. A sync flush takes 4-5\n     *             extra bytes, but guarantees all pushed data is immediately\n     *             decompressible.\n     */\n    Zlib.prototype.flush = function (sync) {\n        Deflate.prototype.flush.call(this, sync);\n    };\n    return Zlib;\n}());\nexport { Zlib };\n/**\n * Asynchronous streaming Zlib compression\n */\nvar AsyncZlib = /*#__PURE__*/ (function () {\n    function AsyncZlib(opts, cb) {\n        astrmify([\n            bDflt,\n            zle,\n            function () { return [astrm, Deflate, Zlib]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Zlib(ev.data);\n            onmessage = astrm(strm);\n        }, 10, 1);\n    }\n    return AsyncZlib;\n}());\nexport { AsyncZlib };\nexport function zlib(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bDflt,\n        zle,\n        function () { return [zlibSync]; }\n    ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb);\n}\n/**\n * Compress data with Zlib\n * @param data The data to compress\n * @param opts The compression options\n * @returns The zlib-compressed version of the data\n */\nexport function zlibSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var a = adler();\n    a.p(data);\n    var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);\n    return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;\n}\n/**\n * Streaming Zlib decompression\n */\nvar Unzlib = /*#__PURE__*/ (function () {\n    function Unzlib(opts, cb) {\n        Inflate.call(this, opts, cb);\n        this.v = opts && opts.dictionary ? 2 : 1;\n    }\n    /**\n     * Pushes a chunk to be unzlibbed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Unzlib.prototype.push = function (chunk, final) {\n        Inflate.prototype.e.call(this, chunk);\n        if (this.v) {\n            if (this.p.length < 6 && !final)\n                return;\n            this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;\n        }\n        if (final) {\n            if (this.p.length < 4)\n                err(6, 'invalid zlib data');\n            this.p = this.p.subarray(0, -4);\n        }\n        // necessary to prevent TS from using the closure value\n        // This allows for workerization to function correctly\n        Inflate.prototype.c.call(this, final);\n    };\n    return Unzlib;\n}());\nexport { Unzlib };\n/**\n * Asynchronous streaming Zlib decompression\n */\nvar AsyncUnzlib = /*#__PURE__*/ (function () {\n    function AsyncUnzlib(opts, cb) {\n        astrmify([\n            bInflt,\n            zule,\n            function () { return [astrm, Inflate, Unzlib]; }\n        ], this, StrmOpt.call(this, opts, cb), function (ev) {\n            var strm = new Unzlib(ev.data);\n            onmessage = astrm(strm);\n        }, 11, 0);\n    }\n    return AsyncUnzlib;\n}());\nexport { AsyncUnzlib };\nexport function unzlib(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return cbify(data, opts, [\n        bInflt,\n        zule,\n        function () { return [unzlibSync]; }\n    ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb);\n}\nexport function unzlibSync(data, opts) {\n    return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);\n}\n// Default algorithm for compression (used because having a known output size allows faster decompression)\nexport { gzip as compress, AsyncGzip as AsyncCompress };\nexport { gzipSync as compressSync, Gzip as Compress };\n/**\n * Streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar Decompress = /*#__PURE__*/ (function () {\n    function Decompress(opts, cb) {\n        this.o = StrmOpt.call(this, opts, cb) || {};\n        this.G = Gunzip;\n        this.I = Inflate;\n        this.Z = Unzlib;\n    }\n    // init substream\n    // overriden by AsyncDecompress\n    Decompress.prototype.i = function () {\n        var _this = this;\n        this.s.ondata = function (dat, final) {\n            _this.ondata(dat, final);\n        };\n    };\n    /**\n     * Pushes a chunk to be decompressed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Decompress.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (!this.s) {\n            if (this.p && this.p.length) {\n                var n = new u8(this.p.length + chunk.length);\n                n.set(this.p), n.set(chunk, this.p.length);\n            }\n            else\n                this.p = chunk;\n            if (this.p.length > 2) {\n                this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8)\n                    ? new this.G(this.o)\n                    : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31))\n                        ? new this.I(this.o)\n                        : new this.Z(this.o);\n                this.i();\n                this.s.push(this.p, final);\n                this.p = null;\n            }\n        }\n        else\n            this.s.push(chunk, final);\n    };\n    return Decompress;\n}());\nexport { Decompress };\n/**\n * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression\n */\nvar AsyncDecompress = /*#__PURE__*/ (function () {\n    function AsyncDecompress(opts, cb) {\n        Decompress.call(this, opts, cb);\n        this.queuedSize = 0;\n        this.G = AsyncGunzip;\n        this.I = AsyncInflate;\n        this.Z = AsyncUnzlib;\n    }\n    AsyncDecompress.prototype.i = function () {\n        var _this = this;\n        this.s.ondata = function (err, dat, final) {\n            _this.ondata(err, dat, final);\n        };\n        this.s.ondrain = function (size) {\n            _this.queuedSize -= size;\n            if (_this.ondrain)\n                _this.ondrain(size);\n        };\n    };\n    /**\n     * Pushes a chunk to be decompressed\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    AsyncDecompress.prototype.push = function (chunk, final) {\n        this.queuedSize += chunk.length;\n        Decompress.prototype.push.call(this, chunk, final);\n    };\n    return AsyncDecompress;\n}());\nexport { AsyncDecompress };\nexport function decompress(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n        ? gunzip(data, opts, cb)\n        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n            ? inflate(data, opts, cb)\n            : unzlib(data, opts, cb);\n}\n/**\n * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format\n * @param data The data to decompress\n * @param opts The decompression options\n * @returns The decompressed version of the data\n */\nexport function decompressSync(data, opts) {\n    return (data[0] == 31 && data[1] == 139 && data[2] == 8)\n        ? gunzipSync(data, opts)\n        : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31))\n            ? inflateSync(data, opts)\n            : unzlibSync(data, opts);\n}\n// flatten a directory structure\nvar fltn = function (d, p, t, o) {\n    for (var k in d) {\n        var val = d[k], n = p + k, op = o;\n        if (Array.isArray(val))\n            op = mrg(o, val[1]), val = val[0];\n        if (ArrayBuffer.isView(val))\n            t[n] = [val, op];\n        else {\n            t[n += '/'] = [new u8(0), op];\n            fltn(val, n, t, o);\n        }\n    }\n};\n// text encoder\nvar te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder();\n// text decoder\nvar td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();\n// text decoder stream\nvar tds = 0;\ntry {\n    td.decode(et, { stream: true });\n    tds = 1;\n}\ncatch (e) { }\n// decode UTF8\nvar dutf8 = function (d) {\n    for (var r = '', i = 0;;) {\n        var c = d[i++];\n        var eb = (c > 127) + (c > 223) + (c > 239);\n        if (i + eb > d.length)\n            return { s: r, r: slc(d, i - 1) };\n        if (!eb)\n            r += String.fromCharCode(c);\n        else if (eb == 3) {\n            c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536,\n                r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023));\n        }\n        else if (eb & 1)\n            r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63));\n        else\n            r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63));\n    }\n};\n/**\n * Streaming UTF-8 decoding\n */\nvar DecodeUTF8 = /*#__PURE__*/ (function () {\n    /**\n     * Creates a UTF-8 decoding stream\n     * @param cb The callback to call whenever data is decoded\n     */\n    function DecodeUTF8(cb) {\n        this.ondata = cb;\n        if (tds)\n            this.t = new TextDecoder();\n        else\n            this.p = et;\n    }\n    /**\n     * Pushes a chunk to be decoded from UTF-8 binary\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    DecodeUTF8.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        final = !!final;\n        if (this.t) {\n            this.ondata(this.t.decode(chunk, { stream: true }), final);\n            if (final) {\n                if (this.t.decode().length)\n                    err(8);\n                this.t = null;\n            }\n            return;\n        }\n        if (!this.p)\n            err(4);\n        var dat = new u8(this.p.length + chunk.length);\n        dat.set(this.p);\n        dat.set(chunk, this.p.length);\n        var _a = dutf8(dat), s = _a.s, r = _a.r;\n        if (final) {\n            if (r.length)\n                err(8);\n            this.p = null;\n        }\n        else\n            this.p = r;\n        this.ondata(s, final);\n    };\n    return DecodeUTF8;\n}());\nexport { DecodeUTF8 };\n/**\n * Streaming UTF-8 encoding\n */\nvar EncodeUTF8 = /*#__PURE__*/ (function () {\n    /**\n     * Creates a UTF-8 decoding stream\n     * @param cb The callback to call whenever data is encoded\n     */\n    function EncodeUTF8(cb) {\n        this.ondata = cb;\n    }\n    /**\n     * Pushes a chunk to be encoded to UTF-8\n     * @param chunk The string data to push\n     * @param final Whether this is the last chunk\n     */\n    EncodeUTF8.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        if (this.d)\n            err(4);\n        this.ondata(strToU8(chunk), this.d = final || false);\n    };\n    return EncodeUTF8;\n}());\nexport { EncodeUTF8 };\n/**\n * Converts a string into a Uint8Array for use with compression/decompression methods\n * @param str The string to encode\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n *               not need to be true unless decoding a binary string.\n * @returns The string encoded in UTF-8/Latin-1 binary\n */\nexport function strToU8(str, latin1) {\n    if (latin1) {\n        var ar_1 = new u8(str.length);\n        for (var i = 0; i < str.length; ++i)\n            ar_1[i] = str.charCodeAt(i);\n        return ar_1;\n    }\n    if (te)\n        return te.encode(str);\n    var l = str.length;\n    var ar = new u8(str.length + (str.length >> 1));\n    var ai = 0;\n    var w = function (v) { ar[ai++] = v; };\n    for (var i = 0; i < l; ++i) {\n        if (ai + 5 > ar.length) {\n            var n = new u8(ai + 8 + ((l - i) << 1));\n            n.set(ar);\n            ar = n;\n        }\n        var c = str.charCodeAt(i);\n        if (c < 128 || latin1)\n            w(c);\n        else if (c < 2048)\n            w(192 | (c >> 6)), w(128 | (c & 63));\n        else if (c > 55295 && c < 57344)\n            c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023),\n                w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n        else\n            w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63));\n    }\n    return slc(ar, 0, ai);\n}\n/**\n * Converts a Uint8Array to a string\n * @param dat The data to decode to string\n * @param latin1 Whether or not to interpret the data as Latin-1. This should\n *               not need to be true unless encoding to binary string.\n * @returns The original UTF-8/Latin-1 string\n */\nexport function strFromU8(dat, latin1) {\n    if (latin1) {\n        var r = '';\n        for (var i = 0; i < dat.length; i += 16384)\n            r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384));\n        return r;\n    }\n    else if (td) {\n        return td.decode(dat);\n    }\n    else {\n        var _a = dutf8(dat), s = _a.s, r = _a.r;\n        if (r.length)\n            err(8);\n        return s;\n    }\n}\n;\n// deflate bit flag\nvar dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; };\n// skip local zip header\nvar slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); };\n// read zip header\nvar zh = function (d, b, z) {\n    var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;\n    var _a = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a[0], su = _a[1], off = _a[2];\n    return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off];\n};\n// read zip64 header sizes\nvar z64hs = function (d, b, l, z, sc, su, off) {\n    var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;\n    var nf = nsc + nsu + noff;\n    if (z && nf) {\n        for (; b + 4 < e; b += 4 + b2(d, b + 2)) {\n            if (b2(d, b) == 1) {\n                return [\n                    nsc ? b8(d, b + 4 + 8 * nsu) : sc,\n                    nsu ? b8(d, b + 4) : su,\n                    noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,\n                    1\n                ];\n            }\n        }\n        // z == 2 for unknown whether or not zip64\n        if (z < 2)\n            err(13);\n    }\n    return [sc, su, off, 0];\n};\n// extra field length\nvar exfl = function (ex) {\n    var le = 0;\n    if (ex) {\n        for (var k in ex) {\n            var l = ex[k].length;\n            if (l > 65535)\n                err(9);\n            le += l + 4;\n        }\n    }\n    return le;\n};\n// write zip header\nvar wzh = function (d, b, f, fn, u, c, ce, co) {\n    var fl = fn.length, ex = f.extra, col = co && co.length;\n    var exl = exfl(ex);\n    wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4;\n    if (ce != null)\n        d[b++] = 20, d[b++] = f.os;\n    d[b] = 20, b += 2; // spec compliance? what's that?\n    d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8;\n    d[b++] = f.compression & 255, d[b++] = f.compression >> 8;\n    var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;\n    if (y < 0 || y > 119)\n        err(10);\n    wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4;\n    if (c != -1) {\n        wbytes(d, b, f.crc);\n        wbytes(d, b + 4, c < 0 ? -c - 2 : c);\n        wbytes(d, b + 8, f.size);\n    }\n    wbytes(d, b + 12, fl);\n    wbytes(d, b + 14, exl), b += 16;\n    if (ce != null) {\n        wbytes(d, b, col);\n        wbytes(d, b + 6, f.attrs);\n        wbytes(d, b + 10, ce), b += 14;\n    }\n    d.set(fn, b);\n    b += fl;\n    if (exl) {\n        for (var k in ex) {\n            var exf = ex[k], l = exf.length;\n            wbytes(d, b, +k);\n            wbytes(d, b + 2, l);\n            d.set(exf, b + 4), b += 4 + l;\n        }\n    }\n    if (col)\n        d.set(co, b), b += col;\n    return b;\n};\n// write zip footer (end of central directory)\nvar wzf = function (o, b, c, d, e) {\n    wbytes(o, b, 0x6054B50); // skip disk\n    wbytes(o, b + 8, c);\n    wbytes(o, b + 10, c);\n    wbytes(o, b + 12, d);\n    wbytes(o, b + 16, e);\n};\n/**\n * A pass-through stream to keep data uncompressed in a ZIP archive.\n */\nvar ZipPassThrough = /*#__PURE__*/ (function () {\n    /**\n     * Creates a pass-through stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     */\n    function ZipPassThrough(filename) {\n        this.filename = filename;\n        this.c = crc();\n        this.size = 0;\n        this.compression = 0;\n    }\n    /**\n     * Processes a chunk and pushes to the output stream. You can override this\n     * method in a subclass for custom behavior, but by default this passes\n     * the data through. You must call this.ondata(err, chunk, final) at some\n     * point in this method.\n     * @param chunk The chunk to process\n     * @param final Whether this is the last chunk\n     */\n    ZipPassThrough.prototype.process = function (chunk, final) {\n        this.ondata(null, chunk, final);\n    };\n    /**\n     * Pushes a chunk to be added. If you are subclassing this with a custom\n     * compression algorithm, note that you must push data from the source\n     * file only, pre-compression.\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    ZipPassThrough.prototype.push = function (chunk, final) {\n        if (!this.ondata)\n            err(5);\n        this.c.p(chunk);\n        this.size += chunk.length;\n        if (final)\n            this.crc = this.c.d();\n        // we shouldn't really do this cast, but properly handling ArrayBufferLike\n        // makes the API unergonomic with Buffer\n        this.process(chunk, final || false);\n    };\n    return ZipPassThrough;\n}());\nexport { ZipPassThrough };\n// I don't extend because TypeScript extension adds 1kB of runtime bloat\n/**\n * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate\n * for better performance\n */\nvar ZipDeflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     * @param opts The compression options\n     */\n    function ZipDeflate(filename, opts) {\n        var _this = this;\n        if (!opts)\n            opts = {};\n        ZipPassThrough.call(this, filename);\n        this.d = new Deflate(opts, function (dat, final) {\n            _this.ondata(null, dat, final);\n        });\n        this.compression = 8;\n        this.flag = dbf(opts.level);\n    }\n    ZipDeflate.prototype.process = function (chunk, final) {\n        try {\n            this.d.push(chunk, final);\n        }\n        catch (e) {\n            this.ondata(e, null, final);\n        }\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    ZipDeflate.prototype.push = function (chunk, final) {\n        ZipPassThrough.prototype.push.call(this, chunk, final);\n    };\n    return ZipDeflate;\n}());\nexport { ZipDeflate };\n/**\n * Asynchronous streaming DEFLATE compression for ZIP archives\n */\nvar AsyncZipDeflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates an asynchronous DEFLATE stream that can be added to ZIP archives\n     * @param filename The filename to associate with this data stream\n     * @param opts The compression options\n     */\n    function AsyncZipDeflate(filename, opts) {\n        var _this = this;\n        if (!opts)\n            opts = {};\n        ZipPassThrough.call(this, filename);\n        this.d = new AsyncDeflate(opts, function (err, dat, final) {\n            _this.ondata(err, dat, final);\n        });\n        this.compression = 8;\n        this.flag = dbf(opts.level);\n        this.terminate = this.d.terminate;\n    }\n    AsyncZipDeflate.prototype.process = function (chunk, final) {\n        this.d.push(chunk, final);\n    };\n    /**\n     * Pushes a chunk to be deflated\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    AsyncZipDeflate.prototype.push = function (chunk, final) {\n        ZipPassThrough.prototype.push.call(this, chunk, final);\n    };\n    return AsyncZipDeflate;\n}());\nexport { AsyncZipDeflate };\n// TODO: Better tree shaking\n/**\n * A zippable archive to which files can incrementally be added\n */\nvar Zip = /*#__PURE__*/ (function () {\n    /**\n     * Creates an empty ZIP archive to which files can be added\n     * @param cb The callback to call whenever data for the generated ZIP archive\n     *           is available\n     */\n    function Zip(cb) {\n        this.ondata = cb;\n        this.u = [];\n        this.d = 1;\n    }\n    /**\n     * Adds a file to the ZIP archive\n     * @param file The file stream to add\n     */\n    Zip.prototype.add = function (file) {\n        var _this = this;\n        if (!this.ondata)\n            err(5);\n        // finishing or finished\n        if (this.d & 2)\n            this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false);\n        else {\n            var f = strToU8(file.filename), fl_1 = f.length;\n            var com = file.comment, o = com && strToU8(com);\n            var u = fl_1 != file.filename.length || (o && (com.length != o.length));\n            var hl_1 = fl_1 + exfl(file.extra) + 30;\n            if (fl_1 > 65535)\n                this.ondata(err(11, 0, 1), null, false);\n            var header = new u8(hl_1);\n            wzh(header, 0, file, f, u, -1);\n            var chks_1 = [header];\n            var pAll_1 = function () {\n                for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) {\n                    var chk = chks_2[_i];\n                    _this.ondata(null, chk, false);\n                }\n                chks_1 = [];\n            };\n            var tr_1 = this.d;\n            this.d = 0;\n            var ind_1 = this.u.length;\n            var uf_1 = mrg(file, {\n                f: f,\n                u: u,\n                o: o,\n                t: function () {\n                    if (file.terminate)\n                        file.terminate();\n                },\n                r: function () {\n                    pAll_1();\n                    if (tr_1) {\n                        var nxt = _this.u[ind_1 + 1];\n                        if (nxt)\n                            nxt.r();\n                        else\n                            _this.d = 1;\n                    }\n                    tr_1 = 1;\n                }\n            });\n            var cl_1 = 0;\n            file.ondata = function (err, dat, final) {\n                if (err) {\n                    _this.ondata(err, dat, final);\n                    _this.terminate();\n                }\n                else {\n                    cl_1 += dat.length;\n                    chks_1.push(dat);\n                    if (final) {\n                        var dd = new u8(16);\n                        wbytes(dd, 0, 0x8074B50);\n                        wbytes(dd, 4, file.crc);\n                        wbytes(dd, 8, cl_1);\n                        wbytes(dd, 12, file.size);\n                        chks_1.push(dd);\n                        uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size;\n                        if (tr_1)\n                            uf_1.r();\n                        tr_1 = 1;\n                    }\n                    else if (tr_1)\n                        pAll_1();\n                }\n            };\n            this.u.push(uf_1);\n        }\n    };\n    /**\n     * Ends the process of adding files and prepares to emit the final chunks.\n     * This *must* be called after adding all desired files for the resulting\n     * ZIP file to work properly.\n     */\n    Zip.prototype.end = function () {\n        var _this = this;\n        if (this.d & 2) {\n            this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true);\n            return;\n        }\n        if (this.d)\n            this.e();\n        else\n            this.u.push({\n                r: function () {\n                    if (!(_this.d & 1))\n                        return;\n                    _this.u.splice(-1, 1);\n                    _this.e();\n                },\n                t: function () { }\n            });\n        this.d = 3;\n    };\n    Zip.prototype.e = function () {\n        var bt = 0, l = 0, tl = 0;\n        for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n            var f = _a[_i];\n            tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0);\n        }\n        var out = new u8(tl + 22);\n        for (var _b = 0, _c = this.u; _b < _c.length; _b++) {\n            var f = _c[_b];\n            wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o);\n            bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b;\n        }\n        wzf(out, bt, this.u.length, tl, l);\n        this.ondata(null, out, true);\n        this.d = 2;\n    };\n    /**\n     * A method to terminate any internal workers used by the stream. Subsequent\n     * calls to add() will fail.\n     */\n    Zip.prototype.terminate = function () {\n        for (var _i = 0, _a = this.u; _i < _a.length; _i++) {\n            var f = _a[_i];\n            f.t();\n        }\n        this.d = 2;\n    };\n    return Zip;\n}());\nexport { Zip };\nexport function zip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    var r = {};\n    fltn(data, '', r, opts);\n    var k = Object.keys(r);\n    var lft = k.length, o = 0, tot = 0;\n    var slft = lft, files = new Array(lft);\n    var term = [];\n    var tAll = function () {\n        for (var i = 0; i < term.length; ++i)\n            term[i]();\n    };\n    var cbd = function (a, b) {\n        mt(function () { cb(a, b); });\n    };\n    mt(function () { cbd = cb; });\n    var cbf = function () {\n        var out = new u8(tot + 22), oe = o, cdl = tot - o;\n        tot = 0;\n        for (var i = 0; i < slft; ++i) {\n            var f = files[i];\n            try {\n                var l = f.c.length;\n                wzh(out, tot, f, f.f, f.u, l);\n                var badd = 30 + f.f.length + exfl(f.extra);\n                var loc = tot + badd;\n                out.set(f.c, loc);\n                wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l;\n            }\n            catch (e) {\n                return cbd(e, null);\n            }\n        }\n        wzf(out, o, files.length, cdl, oe);\n        cbd(null, out);\n    };\n    if (!lft)\n        cbf();\n    var _loop_1 = function (i) {\n        var fn = k[i];\n        var _a = r[fn], file = _a[0], p = _a[1];\n        var c = crc(), size = file.length;\n        c.p(file);\n        var f = strToU8(fn), s = f.length;\n        var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n        var exl = exfl(p.extra);\n        var compression = p.level == 0 ? 0 : 8;\n        var cbl = function (e, d) {\n            if (e) {\n                tAll();\n                cbd(e, null);\n            }\n            else {\n                var l = d.length;\n                files[i] = mrg(p, {\n                    size: size,\n                    crc: c.d(),\n                    c: d,\n                    f: f,\n                    m: m,\n                    u: s != fn.length || (m && (com.length != ms)),\n                    compression: compression\n                });\n                o += 30 + s + exl + l;\n                tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n                if (!--lft)\n                    cbf();\n            }\n        };\n        if (s > 65535)\n            cbl(err(11, 0, 1), null);\n        if (!compression)\n            cbl(null, file);\n        else if (size < 160000) {\n            try {\n                cbl(null, deflateSync(file, p));\n            }\n            catch (e) {\n                cbl(e, null);\n            }\n        }\n        else\n            term.push(deflate(file, p, cbl));\n    };\n    // Cannot use lft because it can decrease\n    for (var i = 0; i < slft; ++i) {\n        _loop_1(i);\n    }\n    return tAll;\n}\n/**\n * Synchronously creates a ZIP file. Prefer using `zip` for better performance\n * with more than one file.\n * @param data The directory structure for the ZIP archive\n * @param opts The main options, merged with per-file options\n * @returns The generated ZIP archive\n */\nexport function zipSync(data, opts) {\n    if (!opts)\n        opts = {};\n    var r = {};\n    var files = [];\n    fltn(data, '', r, opts);\n    var o = 0;\n    var tot = 0;\n    for (var fn in r) {\n        var _a = r[fn], file = _a[0], p = _a[1];\n        var compression = p.level == 0 ? 0 : 8;\n        var f = strToU8(fn), s = f.length;\n        var com = p.comment, m = com && strToU8(com), ms = m && m.length;\n        var exl = exfl(p.extra);\n        if (s > 65535)\n            err(11);\n        var d = compression ? deflateSync(file, p) : file, l = d.length;\n        var c = crc();\n        c.p(file);\n        files.push(mrg(p, {\n            size: file.length,\n            crc: c.d(),\n            c: d,\n            f: f,\n            m: m,\n            u: s != fn.length || (m && (com.length != ms)),\n            o: o,\n            compression: compression\n        }));\n        o += 30 + s + exl + l;\n        tot += 76 + 2 * (s + exl) + (ms || 0) + l;\n    }\n    var out = new u8(tot + 22), oe = o, cdl = tot - o;\n    for (var i = 0; i < files.length; ++i) {\n        var f = files[i];\n        wzh(out, f.o, f, f.f, f.u, f.c.length);\n        var badd = 30 + f.f.length + exfl(f.extra);\n        out.set(f.c, f.o + badd);\n        wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);\n    }\n    wzf(out, o, files.length, cdl, oe);\n    return out;\n}\n/**\n * Streaming pass-through decompression for ZIP archives\n */\nvar UnzipPassThrough = /*#__PURE__*/ (function () {\n    function UnzipPassThrough() {\n    }\n    UnzipPassThrough.prototype.push = function (chunk, final) {\n        // same as ZipPassThrough: cast to retain Buffer ergonomics\n        this.ondata(null, chunk, final);\n    };\n    UnzipPassThrough.compression = 0;\n    return UnzipPassThrough;\n}());\nexport { UnzipPassThrough };\n/**\n * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for\n * better performance.\n */\nvar UnzipInflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE decompression that can be used in ZIP archives\n     */\n    function UnzipInflate() {\n        var _this = this;\n        this.i = new Inflate(function (dat, final) {\n            _this.ondata(null, dat, final);\n        });\n    }\n    UnzipInflate.prototype.push = function (chunk, final) {\n        try {\n            this.i.push(chunk, final);\n        }\n        catch (e) {\n            this.ondata(e, null, final);\n        }\n    };\n    UnzipInflate.compression = 8;\n    return UnzipInflate;\n}());\nexport { UnzipInflate };\n/**\n * Asynchronous streaming DEFLATE decompression for ZIP archives\n */\nvar AsyncUnzipInflate = /*#__PURE__*/ (function () {\n    /**\n     * Creates a DEFLATE decompression that can be used in ZIP archives\n     */\n    function AsyncUnzipInflate(_, sz) {\n        var _this = this;\n        if (sz < 320000) {\n            this.i = new Inflate(function (dat, final) {\n                _this.ondata(null, dat, final);\n            });\n        }\n        else {\n            this.i = new AsyncInflate(function (err, dat, final) {\n                _this.ondata(err, dat, final);\n            });\n            this.terminate = this.i.terminate;\n        }\n    }\n    AsyncUnzipInflate.prototype.push = function (chunk, final) {\n        if (this.i.terminate)\n            chunk = slc(chunk, 0);\n        this.i.push(chunk, final);\n    };\n    AsyncUnzipInflate.compression = 8;\n    return AsyncUnzipInflate;\n}());\nexport { AsyncUnzipInflate };\n/**\n * A ZIP archive decompression stream that emits files as they are discovered\n */\nvar Unzip = /*#__PURE__*/ (function () {\n    /**\n     * Creates a ZIP decompression stream\n     * @param cb The callback to call whenever a file in the ZIP archive is found\n     */\n    function Unzip(cb) {\n        this.onfile = cb;\n        this.k = [];\n        this.o = {\n            0: UnzipPassThrough\n        };\n        this.p = et;\n    }\n    /**\n     * Pushes a chunk to be unzipped\n     * @param chunk The chunk to push\n     * @param final Whether this is the last chunk\n     */\n    Unzip.prototype.push = function (chunk, final) {\n        var _this = this;\n        if (!this.onfile)\n            err(5);\n        if (!this.p)\n            err(4);\n        if (this.c > 0) {\n            var len = Math.min(this.c, chunk.length);\n            var toAdd = chunk.subarray(0, len);\n            this.c -= len;\n            if (this.d)\n                this.d.push(toAdd, !this.c);\n            else\n                this.k[0].push(toAdd);\n            chunk = chunk.subarray(len);\n            if (chunk.length)\n                return this.push(chunk, final);\n        }\n        else {\n            var f = 0, i = 0, is = void 0, buf = void 0;\n            if (!this.p.length)\n                buf = chunk;\n            else if (!chunk.length)\n                buf = this.p;\n            else {\n                buf = new u8(this.p.length + chunk.length);\n                buf.set(this.p), buf.set(chunk, this.p.length);\n            }\n            var l = buf.length, oc = this.c, add = oc && this.d;\n            var _loop_2 = function () {\n                var sig = b4(buf, i);\n                if (sig == 0x4034B50) {\n                    f = 1, is = i;\n                    this_1.d = null;\n                    this_1.c = 0;\n                    var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28);\n                    if (l > i + 30 + fnl + es) {\n                        var chks_3 = [];\n                        this_1.k.unshift(chks_3);\n                        f = 2;\n                        var lsc = b4(buf, i + 18), lsu = b4(buf, i + 22);\n                        var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u);\n                        var _a = z64hs(buf, i, es, 2, lsc, lsu, 0), sc_1 = _a[0], su_1 = _a[1], z64 = _a[3];\n                        if (dd)\n                            sc_1 = -1 - z64;\n                        i += es;\n                        this_1.c = sc_1;\n                        var d_1;\n                        var file_1 = {\n                            name: fn_1,\n                            compression: cmp_1,\n                            start: function () {\n                                if (!file_1.ondata)\n                                    err(5);\n                                if (!sc_1)\n                                    file_1.ondata(null, et, true);\n                                else {\n                                    var ctr = _this.o[cmp_1];\n                                    if (!ctr)\n                                        file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false);\n                                    d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1);\n                                    d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); };\n                                    for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) {\n                                        var dat = chks_4[_i];\n                                        d_1.push(dat, false);\n                                    }\n                                    if (_this.k[0] == chks_3 && _this.c)\n                                        _this.d = d_1;\n                                    else\n                                        d_1.push(et, true);\n                                }\n                            },\n                            terminate: function () {\n                                if (d_1 && d_1.terminate)\n                                    d_1.terminate();\n                            }\n                        };\n                        if (sc_1 >= 0)\n                            file_1.size = sc_1, file_1.originalSize = su_1;\n                        this_1.onfile(file_1);\n                    }\n                    return \"break\";\n                }\n                else if (oc) {\n                    if (sig == 0x8074B50) {\n                        is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0;\n                        return \"break\";\n                    }\n                    else if (sig == 0x2014B50) {\n                        is = i -= 4, f = 3, this_1.c = 0;\n                        return \"break\";\n                    }\n                }\n            };\n            var this_1 = this;\n            for (; i < l - 4; ++i) {\n                var state_1 = _loop_2();\n                if (state_1 === \"break\")\n                    break;\n            }\n            this.p = et;\n            if (oc < 0) {\n                var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i);\n                if (add)\n                    add.push(dat, !!f);\n                else\n                    this.k[+(f == 2)].push(dat);\n            }\n            if (f & 2)\n                return this.push(buf.subarray(i), final);\n            this.p = buf.subarray(i);\n        }\n        if (final) {\n            if (this.c)\n                err(13);\n            this.p = null;\n        }\n    };\n    /**\n     * Registers a decoder with the stream, allowing for files compressed with\n     * the compression type provided to be expanded correctly\n     * @param decoder The decoder constructor\n     */\n    Unzip.prototype.register = function (decoder) {\n        this.o[decoder.compression] = decoder;\n    };\n    return Unzip;\n}());\nexport { Unzip };\nvar mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); };\nexport function unzip(data, opts, cb) {\n    if (!cb)\n        cb = opts, opts = {};\n    if (typeof cb != 'function')\n        err(7);\n    var term = [];\n    var tAll = function () {\n        for (var i = 0; i < term.length; ++i)\n            term[i]();\n    };\n    var files = {};\n    var cbd = function (a, b) {\n        mt(function () { cb(a, b); });\n    };\n    mt(function () { cbd = cb; });\n    var e = data.length - 22;\n    for (; b4(data, e) != 0x6054B50; --e) {\n        if (!e || data.length - e > 65558) {\n            cbd(err(13, 0, 1), null);\n            return tAll;\n        }\n    }\n    ;\n    var lft = b2(data, e + 8);\n    if (lft) {\n        var c = lft;\n        var o = b4(data, e + 16);\n        var z = b4(data, e - 20) == 0x7064B50;\n        if (z) {\n            var ze = b4(data, e - 12);\n            z = b4(data, ze) == 0x6064B50;\n            if (z) {\n                c = lft = b4(data, ze + 32);\n                o = b4(data, ze + 48);\n            }\n        }\n        var fltr = opts && opts.filter;\n        var _loop_3 = function (i) {\n            var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n            o = no;\n            var cbl = function (e, d) {\n                if (e) {\n                    tAll();\n                    cbd(e, null);\n                }\n                else {\n                    if (d)\n                        files[fn] = d;\n                    if (!--lft)\n                        cbd(null, files);\n                }\n            };\n            if (!fltr || fltr({\n                name: fn,\n                size: sc,\n                originalSize: su,\n                compression: c_1\n            })) {\n                if (!c_1)\n                    cbl(null, slc(data, b, b + sc));\n                else if (c_1 == 8) {\n                    var infl = data.subarray(b, b + sc);\n                    // Synchronously decompress under 512KB, or barely-compressed data\n                    if (su < 524288 || sc > 0.8 * su) {\n                        try {\n                            cbl(null, inflateSync(infl, { out: new u8(su) }));\n                        }\n                        catch (e) {\n                            cbl(e, null);\n                        }\n                    }\n                    else\n                        term.push(inflate(infl, { size: su }, cbl));\n                }\n                else\n                    cbl(err(14, 'unknown compression type ' + c_1, 1), null);\n            }\n            else\n                cbl(null, null);\n        };\n        for (var i = 0; i < c; ++i) {\n            _loop_3(i);\n        }\n    }\n    else\n        cbd(null, {});\n    return tAll;\n}\n/**\n * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better\n * performance with more than one file.\n * @param data The raw compressed ZIP file\n * @param opts The ZIP extraction options\n * @returns The decompressed files\n */\nexport function unzipSync(data, opts) {\n    var files = {};\n    var e = data.length - 22;\n    for (; b4(data, e) != 0x6054B50; --e) {\n        if (!e || data.length - e > 65558)\n            err(13);\n    }\n    ;\n    var c = b2(data, e + 8);\n    if (!c)\n        return {};\n    var o = b4(data, e + 16);\n    var z = b4(data, e - 20) == 0x7064B50;\n    if (z) {\n        var ze = b4(data, e - 12);\n        z = b4(data, ze) == 0x6064B50;\n        if (z) {\n            c = b4(data, ze + 32);\n            o = b4(data, ze + 48);\n        }\n    }\n    var fltr = opts && opts.filter;\n    for (var i = 0; i < c; ++i) {\n        var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off);\n        o = no;\n        if (!fltr || fltr({\n            name: fn,\n            size: sc,\n            originalSize: su,\n            compression: c_2\n        })) {\n            if (!c_2)\n                files[fn] = slc(data, b, b + sc);\n            else if (c_2 == 8)\n                files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });\n            else\n                err(14, 'unknown compression type ' + c_2);\n        }\n    }\n    return files;\n}\n", "// Skill bundle \u2014 wire format (\u00A72.1) + canonical content hash (\u00A72.2).\n//\n// A skill is a folder tree, not a single file. The bundle is a map of\n// POSIX-relative paths to per-file encoded content; `enc: utf8|base64`.\n// Binary is first-class. The canonical hash is over decoded bytes so the\n// transport encoding cannot change the result.\nimport { createHash } from 'node:crypto';\nexport const CONTENT_HASH_PREFIX = 'sha256:';\n// \u00A72.1 size rules.\nexport const MAX_BUNDLE_BYTES = 25 * 1024 * 1024;\nexport const MAX_INSTRUCTION_BYTES = 1 * 1024 * 1024;\n// \u00A72.1: SKILL.md MUST be at the root.\nexport const SKILL_ENTRYPOINT = 'SKILL.md';\n/** Suffix for ephemeral atomic-write backups; never part of skill content. */\nexport const SKILLET_BACKUP_SUFFIX = '.skillet-backup';\nexport function isSkilletBackupPath(path) {\n    return path.endsWith(SKILLET_BACKUP_SUFFIX);\n}\nexport class BundleError extends Error {\n    /** Machine-readable error code per protocol \u00A70. */\n    code;\n    constructor(code, message) {\n        super(message);\n        this.code = code;\n        this.name = 'BundleError';\n    }\n}\n/**\n * Decode a wire-format bundle into a path \u2192 bytes map.\n *\n * - Validates that each entry has a recognized `enc` field.\n * - Does NOT validate paths or sizes (use `validateBundle`).\n */\nexport function decodeBundle(files) {\n    const out = new Map();\n    for (const [path, entry] of Object.entries(files)) {\n        if (entry == null || typeof entry !== 'object') {\n            throw new BundleError('unsafe_path', `Bundle entry for \"${path}\" is not an object`);\n        }\n        if (entry.enc === 'utf8') {\n            out.set(path, Buffer.from(entry.data, 'utf8'));\n        }\n        else if (entry.enc === 'base64') {\n            // strict: reject non-canonical base64 (whitespace, padding errors)\n            const buf = Buffer.from(entry.data, 'base64');\n            // round-trip check \u2014 Node's base64 decoder is lenient; we want strict to\n            // avoid hash mismatches where two different `data` strings decode to the\n            // same bytes (only canonical base64 round-trips).\n            if (buf.toString('base64') !== entry.data) {\n                throw new BundleError('unsafe_path', `Bundle entry for \"${path}\" has non-canonical base64 data`);\n            }\n            out.set(path, buf);\n        }\n        else {\n            throw new BundleError('unsafe_path', `Bundle entry for \"${path}\" has unsupported enc: ${String(entry.enc)}`);\n        }\n    }\n    return out;\n}\n/**\n * Encode a decoded bundle into wire format.\n *\n * Picks `utf8` when the bytes round-trip cleanly through UTF-8 (no replacement\n * characters), otherwise falls back to `base64`. The canonical hash is over\n * the raw bytes either way, so this choice never affects integrity.\n */\nexport function encodeBundle(bundle) {\n    const out = Object.create(null);\n    for (const [path, bytes] of bundle) {\n        const buf = Buffer.from(bytes);\n        const asUtf8 = buf.toString('utf8');\n        const roundTrip = Buffer.from(asUtf8, 'utf8');\n        if (roundTrip.equals(buf)) {\n            out[path] = { enc: 'utf8', data: asUtf8 };\n        }\n        else {\n            out[path] = { enc: 'base64', data: buf.toString('base64') };\n        }\n    }\n    return out;\n}\n/**\n * Canonical content hash per \u00A72.2:\n *\n *   sha256( for each path in lexicographic byte order:\n *             u64be(len(utf8(path))) || utf8(path) ||\n *             u64be(len(content))    || raw_content_bytes )\n *\n * prefixed with `sha256:`. Deterministic across implementations: identical\n * bytes hash identically regardless of how they arrived on the wire.\n *\n * Each field is LENGTH-PREFIXED with a fixed-width 8-byte big-endian count, so\n * no content byte can be mistaken for a delimiter. The previous scheme used an\n * in-band `0x00` separator; because content can itself contain `0x00` (bundles\n * carry binary files), two different file sets could frame to the same byte\n * stream and collide. Length prefixing makes the framing unambiguous.\n */\n/** Drop ephemeral `.skillet-backup` paths before hashing skill bytes. */\nexport function stripSkilletBackupPaths(bundle) {\n    const out = new Map();\n    for (const [path, bytes] of bundle) {\n        if (!isSkilletBackupPath(path))\n            out.set(path, bytes);\n    }\n    return out;\n}\nexport function canonicalContentHash(bundle) {\n    const hash = createHash('sha256');\n    const paths = [...bundle.keys()].sort(comparePathBytes);\n    for (const path of paths) {\n        const pathBytes = Buffer.from(path, 'utf8');\n        const data = bundle.get(path);\n        const content = data == null ? EMPTY_BYTES : Buffer.from(data);\n        hash.update(u64be(pathBytes.length));\n        hash.update(pathBytes);\n        hash.update(u64be(content.length));\n        hash.update(content);\n    }\n    return CONTENT_HASH_PREFIX + hash.digest('hex');\n}\n/**\n * Canonical hash of publishable skill content. Excludes `.skillet-backup` paths\n * so local store reads (which skip those files) align with `entry.hash`.\n */\nexport function skillContentHash(bundle) {\n    return canonicalContentHash(stripSkilletBackupPaths(bundle));\n}\nconst EMPTY_BYTES = Buffer.alloc(0);\n/** Fixed-width 8-byte big-endian length prefix (BigUInt64BE). */\nfunction u64be(n) {\n    const b = Buffer.alloc(8);\n    b.writeBigUInt64BE(BigInt(n));\n    return b;\n}\n/** Lexicographic byte order (NOT JS string comparison, which is by UTF-16 code unit). */\nfunction comparePathBytes(a, b) {\n    const ba = Buffer.from(a, 'utf8');\n    const bb = Buffer.from(b, 'utf8');\n    return Buffer.compare(ba, bb);\n}\n/**\n * Validate bundle paths and sizes per \u00A72.1.\n *\n * Rejects:\n * - missing `SKILL.md` at the bundle root (`unsafe_path` \u2014 bundle invariant).\n * - absolute paths, paths containing `.` or `..` segments, backslashes,\n *   leading slash, trailing slash, empty segments, null bytes, or non-POSIX\n *   separators (`unsafe_path`).\n * - bundle total > 25 MB (`bundle_too_large`).\n * - instruction closure total > 1 MB (`instruction_too_large`).\n *\n * Note: symlinks cannot appear inside a Map<path, bytes> directly \u2014 the\n * filesystem walker (`readBundleFromDir`) rejects them before this point.\n */\nexport function validateBundle(bundle) {\n    if (!bundle.has(SKILL_ENTRYPOINT)) {\n        throw new BundleError('unsafe_path', 'Bundle missing required SKILL.md at root');\n    }\n    let totalBytes = 0;\n    for (const [path, data] of bundle) {\n        assertSafeBundlePath(path);\n        totalBytes += data.byteLength;\n    }\n    if (totalBytes > MAX_BUNDLE_BYTES) {\n        throw new BundleError('bundle_too_large', `Bundle is ${totalBytes} bytes; max is ${MAX_BUNDLE_BYTES}`);\n    }\n    const instructionBytes = instructionClosureBytes(bundle);\n    if (instructionBytes > MAX_INSTRUCTION_BYTES) {\n        throw new BundleError('instruction_too_large', `Instruction closure is ${instructionBytes} bytes; max is ${MAX_INSTRUCTION_BYTES}`);\n    }\n}\n/**\n * Validate a bundle path, returning a human-readable error or `null` when safe.\n * Mirrors `assertSafeBundlePath` for client-side editors.\n */\nexport function bundlePathError(path) {\n    try {\n        assertSafeBundlePath(path);\n        return null;\n    }\n    catch (err) {\n        if (err instanceof BundleError)\n            return err.message;\n        throw err;\n    }\n}\n/**\n * Reject any path the bundle wire format does not accept.\n *\n * The bundle is rooted at the skill directory and uses POSIX separators only.\n * A path failing this rejects the whole publish (\u00A72.1).\n */\nexport function assertSafeBundlePath(path) {\n    if (path.length === 0) {\n        throw new BundleError('unsafe_path', 'Bundle path is empty');\n    }\n    if (path.includes('\\0')) {\n        throw new BundleError('unsafe_path', `Bundle path contains null byte: ${JSON.stringify(path)}`);\n    }\n    if (path.includes('\\\\')) {\n        throw new BundleError('unsafe_path', `Bundle path uses Windows separator (\\\\): ${JSON.stringify(path)}`);\n    }\n    if (path.startsWith('/')) {\n        throw new BundleError('unsafe_path', `Bundle path is absolute: ${JSON.stringify(path)}`);\n    }\n    if (path.endsWith('/')) {\n        throw new BundleError('unsafe_path', `Bundle path ends with separator: ${JSON.stringify(path)}`);\n    }\n    const segments = path.split('/');\n    for (const seg of segments) {\n        if (seg === '' || seg === '.' || seg === '..') {\n            throw new BundleError('unsafe_path', `Bundle path has unsafe segment: ${JSON.stringify(path)}`);\n        }\n    }\n    if (segments.includes('.git')) {\n        throw new BundleError('unsafe_path', `Bundle path includes .git: ${JSON.stringify(path)}`);\n    }\n    const baseName = segments[segments.length - 1];\n    if (baseName.startsWith('.')) {\n        throw new BundleError('unsafe_path', `Bundle path is a dotfile: ${JSON.stringify(path)}`);\n    }\n    if (baseName === '__proto__' || baseName === '.DS_Store') {\n        throw new BundleError('unsafe_path', `Bundle path uses a reserved name: ${JSON.stringify(path)}`);\n    }\n    const blockedConfigNames = new Set([\n        'settings.json',\n        'mcp.json',\n        'claude_desktop_config.json',\n        'hooks.json',\n        '.cursorrules',\n    ]);\n    if (blockedConfigNames.has(baseName)) {\n        throw new BundleError('unsafe_path', `Bundle path is a blocked runtime-control filename: ${JSON.stringify(path)}`);\n    }\n    if (segments.includes('hooks')) {\n        throw new BundleError('unsafe_path', `Bundle path includes a hooks directory: ${JSON.stringify(path)}`);\n    }\n    if (segments[0] === '.claude' || segments[0] === '.cursor') {\n        throw new BundleError('unsafe_path', `Bundle path targets a hidden agent config directory: ${JSON.stringify(path)}`);\n    }\n}\n/**\n * v1 instruction-file classification (legacy interim heuristic).\n *\n * @deprecated Budget enforcement uses {@link computeInstructionClosure}.\n * Kept for callers that still classify paths by directory during the transition.\n */\nexport function isInstructionPath(path) {\n    if (path === SKILL_ENTRYPOINT)\n        return true;\n    if (path.startsWith('agents/') && /\\.(md|markdown|txt)$/i.test(path))\n        return true;\n    return false;\n}\n/** Extract YAML frontmatter from a markdown file body, or null if absent. */\nexport function extractFrontmatterYaml(text) {\n    const match = text.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---/);\n    return match?.[1] ?? null;\n}\n/** Parse a `required_reading:` list from a frontmatter YAML block. */\nexport function parseRequiredReadingFromYaml(yaml) {\n    const items = [];\n    let inBlock = false;\n    for (const line of yaml.split('\\n')) {\n        if (/^required_reading:\\s*$/.test(line)) {\n            inBlock = true;\n            continue;\n        }\n        if (inBlock) {\n            const itemMatch = line.match(/^\\s+-\\s+(?:\"([^\"]*)\"|'([^']*)'|(.+))\\s*$/);\n            if (itemMatch) {\n                const raw = (itemMatch[1] ?? itemMatch[2] ?? itemMatch[3] ?? '').trim();\n                if (raw)\n                    items.push(raw);\n                continue;\n            }\n            if (/^\\S/.test(line)) {\n                inBlock = false;\n            }\n        }\n    }\n    return items;\n}\nfunction decodeBundleText(bundle, path) {\n    const bytes = bundle.get(path);\n    if (!bytes)\n        return '';\n    return Buffer.from(bytes).toString('utf8');\n}\nfunction requiredReadingForPath(bundle, path) {\n    const yaml = extractFrontmatterYaml(decodeBundleText(bundle, path));\n    if (!yaml)\n        return [];\n    return parseRequiredReadingFromYaml(yaml);\n}\nfunction assertSafeGlobPattern(pattern) {\n    const MAX_GLOB_LEN = 128;\n    const MAX_GLOB_STARS = 24;\n    if (pattern.length > MAX_GLOB_LEN) {\n        throw new BundleError('unsafe_path', `required_reading glob exceeds ${MAX_GLOB_LEN} characters`);\n    }\n    if ((pattern.match(/\\*/g) ?? []).length > MAX_GLOB_STARS) {\n        throw new BundleError('unsafe_path', `required_reading glob has too many wildcards`);\n    }\n    if (pattern.length === 0) {\n        throw new BundleError('unsafe_path', 'required_reading glob is empty');\n    }\n    if (pattern.includes('\\0') || pattern.includes('\\\\') || pattern.startsWith('/')) {\n        throw new BundleError('unsafe_path', `required_reading glob is unsafe: ${JSON.stringify(pattern)}`);\n    }\n    for (const seg of pattern.split('/')) {\n        if (seg === '' || seg === '.' || seg === '..') {\n            throw new BundleError('unsafe_path', `required_reading glob has unsafe segment: ${JSON.stringify(pattern)}`);\n        }\n    }\n}\n/** Turn a bundle-relative POSIX glob into a RegExp anchored to the full path. */\nexport function globPatternToRegExp(pattern) {\n    let re = '^';\n    for (let i = 0; i < pattern.length; i += 1) {\n        const ch = pattern[i];\n        if (ch === '*') {\n            if (pattern[i + 1] === '*') {\n                re += '.*';\n                i += 1;\n            }\n            else {\n                re += '[^/]*';\n            }\n        }\n        else if (ch === '?') {\n            re += '[^/]';\n        }\n        else if (/[+^${}()|[\\]\\\\.]/.test(ch)) {\n            re += `\\\\${ch}`;\n        }\n        else {\n            re += ch;\n        }\n    }\n    re += '$';\n    return new RegExp(re);\n}\nfunction resolveGlobAgainstManifest(pattern, manifest) {\n    assertSafeGlobPattern(pattern);\n    const re = globPatternToRegExp(pattern);\n    return [...new Set(manifest.filter((p) => re.test(p)))].sort();\n}\n/**\n * Instruction closure: SKILL.md plus every bundle path\n * reachable via transitive `required_reading` frontmatter.\n */\nexport function computeInstructionClosure(bundle) {\n    if (!bundle.has(SKILL_ENTRYPOINT)) {\n        throw new BundleError('unsafe_path', 'Bundle missing required SKILL.md at root');\n    }\n    const manifest = [...bundle.keys()].sort();\n    const closure = new Set();\n    const work = [SKILL_ENTRYPOINT];\n    while (work.length > 0) {\n        const file = work.pop();\n        if (closure.has(file))\n            continue;\n        if (!bundle.has(file)) {\n            throw new BundleError('unsafe_path', `required_reading references missing bundle path: ${JSON.stringify(file)}`);\n        }\n        assertSafeBundlePath(file);\n        closure.add(file);\n        for (const pattern of requiredReadingForPath(bundle, file)) {\n            const matches = resolveGlobAgainstManifest(pattern, manifest);\n            if (matches.length === 0 && !pattern.includes('*') && !pattern.includes('?')) {\n                throw new BundleError('unsafe_path', `required_reading path not found in bundle: ${JSON.stringify(pattern)}`);\n            }\n            for (const path of matches) {\n                if (!closure.has(path))\n                    work.push(path);\n            }\n        }\n    }\n    return closure;\n}\n/** Sum decoded bytes over the instruction closure. */\nexport function instructionClosureBytes(bundle) {\n    let total = 0;\n    for (const path of computeInstructionClosure(bundle)) {\n        total += bundle.get(path)?.byteLength ?? 0;\n    }\n    return total;\n}\n", "import { zipSync } from 'fflate';\nimport { assertSafeBundlePath, SKILL_ENTRYPOINT } from './bundle.js';\n/**\n * Pack a decoded skill bundle into a `.zip` for export.\n *\n * Lives in the protocol package so both the client (`@skillet/core` \u2192 CLI) and\n * the server (`@skillet/registry` download endpoint) share one packer without\n * the registry depending on client code.\n *\n * Determinism: fflate stamps each entry with the current time by default, which\n * would make output non-reproducible. We pin a fixed mtime and pack entries in\n * sorted path order so the same bundle yields byte-stable output within a\n * runtime (fflate writes the DOS timestamp from local-time fields, so the bytes\n * are not guaranteed identical across timezones \u2014 the registry keys its ETag on\n * the content hash, not on these bytes, so cross-machine drift is harmless).\n *\n * Safety: every bundle path is re-validated with `assertSafeBundlePath` before\n * it becomes a zip entry name \u2014 a zip-slip guard that holds even for an\n * in-memory bundle that never passed the publish validator.\n */\n// DOS/zip timestamps must fall in 1980-2099; fflate reads the Date in local\n// time, so we pick a mid-year, mid-day local constant that stays in range in\n// every timezone. Only its constancy matters for reproducible output.\nconst FIXED_MTIME = new Date(1985, 5, 15, 12, 0, 0);\nconst ZIP_OPTS = { level: 6, mtime: FIXED_MTIME };\nfunction collectInto(files, bundle, prefix) {\n    if (!bundle.has(SKILL_ENTRYPOINT)) {\n        throw new Error(`Cannot export bundle: no ${SKILL_ENTRYPOINT} at the bundle root`);\n    }\n    for (const path of [...bundle.keys()].sort()) {\n        assertSafeBundlePath(path);\n        files[prefix ? `${prefix}/${path}` : path] = bundle.get(path);\n    }\n}\n/**\n * Pack a single skill bundle. With no prefix the `SKILL.md` sits at the zip\n * root \u2014 the shape ChatGPT Skills and Claude Projects expect on upload. Pass a\n * `prefix` (e.g. `owner--slug`) to nest it, which kit export uses to keep\n * multiple skills from colliding in one archive.\n */\nexport function bundleToZip(bundle, opts = {}) {\n    const files = {};\n    collectInto(files, bundle, opts.prefix ?? '');\n    return zipSync(files, ZIP_OPTS);\n}\n/**\n * Pack several skill bundles into one archive, each under its own prefix\n * directory (use `bundleSlugDir` for collision-free `owner--slug` names).\n */\nexport function bundlesToZip(entries) {\n    const files = {};\n    for (const { prefix, bundle } of entries)\n        collectInto(files, bundle, prefix);\n    return zipSync(files, ZIP_OPTS);\n}\n", "/**\n * Inline-image policy for skill bundles \u2014 shared by the registry's raw-file\n * route (server gate) and the web viewer (client mirror), so the two lists\n * can't drift. Browser-safe: no node imports (imported client-side via the\n * `@skillet/protocol/inline-images` subpath).\n *\n * Raster formats only. SVG is deliberately excluded \u2014 it is a script-injection\n * surface (inline <script>, event handlers) and keeps download-only behavior.\n */\n/**\n * Max bytes the registry serves inline per image file. Distinct from the\n * publish-time bundle cap ({@link MAX_BUNDLE_BYTES} in bundle.ts, 25 MiB):\n * this bounds a single <img> fetch, not what a bundle may contain. The web\n * viewer mirrors it client-side and never requests an over-cap file.\n */\nexport const MAX_INLINE_IMAGE_BYTES = 10 * 1024 * 1024;\n/** Allowlisted extension \u2192 exact Content-Type. The registry sets the type from\n *  this map (the web sends `X-Content-Type-Options: nosniff`, so it must be\n *  exact); the key set doubles as the client-side render allowlist. */\nexport const INLINE_IMAGE_CONTENT_TYPES = {\n    png: 'image/png',\n    jpg: 'image/jpeg',\n    jpeg: 'image/jpeg',\n    gif: 'image/gif',\n    webp: 'image/webp',\n};\n/** Lowercased extension of `path` when it is inline-renderable, else null. */\nexport function inlineImageExtension(path) {\n    const dot = path.lastIndexOf('.');\n    if (dot < 0)\n        return null;\n    const ext = path.slice(dot + 1).toLowerCase();\n    return ext in INLINE_IMAGE_CONTENT_TYPES ? ext : null;\n}\n/** True when the bundle path has an allowlisted raster-image extension. */\nexport function isInlineImagePath(path) {\n    return inlineImageExtension(path) !== null;\n}\n", "// Wire-format constants for the Skillet registry protocol.\n//\n// PROTOCOL.md \u00A70: \"Transport: HTTPS, JSON bodies, UTF-8. Versioned under `/api/v1/`.\"\n// PROTOCOL.md \u00A711 (skillet.lock): `registry = \"https://registry.skillet.md\"`.\n//\n// The .dev domain that appeared in an earlier draft is superseded by the\n// normative \u00A711 spelling. Single source of truth for both the lockfile field\n// and the default base URL is `skillet.md`.\nexport const REGISTRY_VERSION_PREFIX = '/api/v1';\nexport const REGISTRY_API_BASE = 'https://registry.skillet.md';\n// Legacy: kept exported so callers that imported v1 directly still compile\n// during the prefix migration. Remove once the registry client is\n// fully on REGISTRY_VERSION_PREFIX.\n/** @deprecated use REGISTRY_VERSION_PREFIX */\nexport const REGISTRY_VERSION = 'v1';\n// PROTOCOL.md \u00A76.1: `sync_interval_seconds` hints background-sync eligibility.\n// Default cadence for caller-agnostic responses is 24h.\nexport const SYNC_INTERVAL_SECONDS_DEFAULT = 86400;\n", "/**\n * Artifact wire-format version \u2014 the shape of manifests, lockfiles, and local\n * kit state. Distinct from `/api/v1` (HTTP surface) and from per-skill\n * `version` integers inside a manifest.\n *\n * Bump only when the serialized contract changes in a breaking way. Clients\n * MUST reject unknown future versions; servers MUST emit the current version\n * on every manifest-shaped response.\n */\nexport const ARTIFACT_SCHEMA_VERSION = 1;\nconst SUPPORTED = new Set([ARTIFACT_SCHEMA_VERSION]);\n/** True when `v` is a schema version this build can read. */\nexport function isSupportedArtifactSchemaVersion(v) {\n    return typeof v === 'number' && SUPPORTED.has(v);\n}\n/**\n * Resolve schema_version from a wire payload. Missing field \u21D2 legacy v1\n * (manifests that predated explicit stamping).\n */\nexport function resolveArtifactSchemaVersion(v, context) {\n    if (v === undefined || v === null)\n        return ARTIFACT_SCHEMA_VERSION;\n    if (!isSupportedArtifactSchemaVersion(v)) {\n        throw new Error(`${context}: unsupported artifact schema_version ${JSON.stringify(v)} (supported: ${ARTIFACT_SCHEMA_VERSION})`);\n    }\n    return v;\n}\n", "// Repo-import classification \u2014 the shared, I/O-free rules that decide how a\n// GitHub repo becomes skills. Both the web importer (packages/web) and the\n// registry sync engine (packages/registry) call these so the two paths agree on\n// what to exclude, what counts as coupled, and how a repo classifies. The fetch\n// mechanics differ per path; the *decisions* live here, once.\n//\n// See docs/plans/repo-import-classification.md.\n/** Build/output, dependency, and tool-mirror dirs we never discover skills in. */\nconst EXCLUDED_DISCOVERY_SEGMENTS = new Set(['node_modules', 'dist', 'build', 'out', 'vendor']);\n/**\n * True for a path we exclude from discovery and from a unified bundle. Any\n * dot-prefixed segment (`.claude`, `.gemini`, `.codex-plugin`, `.github`, \u2026) is\n * a tool-specific generated mirror or VCS/CI dir; the canonical skills live in\n * plain directories. Importing the mirrors would publish duplicates.\n */\nexport function isExcludedDiscoveryPath(path) {\n    return path\n        .split('/')\n        .some((seg) => seg.startsWith('.') || EXCLUDED_DISCOVERY_SEGMENTS.has(seg.toLowerCase()));\n}\n/**\n * A skill is \"coupled\" when its SKILL.md references a path outside its own\n * folder (a `../` segment) \u2014 it depends on a sibling skill or a shared dir, so\n * it only resolves when imported together with the rest of the repo.\n */\nexport function isCoupledSkillMarkdown(markdown) {\n    return /\\.\\.\\//.test(markdown);\n}\n/** A real `skills/x` dir is more canonical than a `plugins/<tool>/skills/x` mirror. */\nexport function isMoreCanonicalSkillDir(a, b) {\n    const aPlugin = a.includes('plugins/');\n    const bPlugin = b.includes('plugins/');\n    if (aPlugin !== bPlugin)\n        return !aPlugin;\n    return a.length < b.length || (a.length === b.length && a < b);\n}\n/**\n * Recommend how to import a discovered repo from its skills' dir + coupled flag.\n *\n * - `single`: one skill \u2014 just publish it.\n * - `unified`: many skills, at least one coupled (references `../`), so they only\n *   work together \u2014 import the whole repo as ONE skill so the shared paths\n *   resolve (no rewriting, no dependency graph).\n * - `kit`: many self-contained skills \u2014 publish each and bundle them in a kit.\n */\nexport function classifyImport(skills) {\n    const n = skills.length;\n    if (n <= 1) {\n        return { mode: 'single', reason: n === 1 ? 'One skill in this repo.' : 'No skills found.' };\n    }\n    const coupled = skills.filter((s) => s.coupled).length;\n    if (coupled > 0) {\n        return {\n            mode: 'unified',\n            reason: `${coupled} of ${n} skills reference shared files (\u2018../\u2019), so they only work together.`,\n        };\n    }\n    return { mode: 'kit', reason: `${n} independent skills.` };\n}\n/**\n * Drop mirror copies: items whose content key (e.g. byte-identical SKILL.md) is\n * the same are the same skill re-emitted for another tool (e.g.\n * `plugins/<tool>/skills/x` mirroring `skills/x`). Keep the canonical one per\n * key; items with a null key (unreadable content) are always kept. Preserves\n * input order minus the dropped duplicates.\n */\nexport function dedupeMirrorsBy(items, dirOf, keyOf) {\n    const byKey = new Map();\n    const kept = [];\n    for (const item of items) {\n        const key = keyOf(item);\n        if (!key) {\n            kept.push(item);\n            continue;\n        }\n        const existing = byKey.get(key);\n        if (!existing) {\n            byKey.set(key, item);\n            kept.push(item);\n        }\n        else if (isMoreCanonicalSkillDir(dirOf(item), dirOf(existing))) {\n            byKey.set(key, item);\n            kept[kept.indexOf(existing)] = item;\n        }\n    }\n    return kept;\n}\n", "// `requires:` manifest schema \u2014 dependency edges + skill\u2192skill deps.\n//\n// This module is the canonical, signed-bundle schema for a skill's declared\n// dependencies. It LOCKS THE FIELD, not the resolver: it parses and validates\n// the `requires:` block of SKILL.md frontmatter. It performs NO I/O and NO\n// fetching \u2014 graph walk, transitive fetch, and trust-gating are the resolver's\n// job and land later.\n//\n// The field lives in SKILL.md frontmatter, so it is inside the canonical\n// content hash (\u00A72.2) and the author signature (\u00A74): dependency edges are\n// tamper-evident and travel with the artifact from version 1.\n/** Per-skill cap on declared dependencies \u2014 bounds resolver fan-out. */\nexport const MAX_REQUIRES_ENTRIES = 64;\n/** Max length of an entry's `reason` note. */\nexport const MAX_REQUIRES_REASON_CHARS = 280;\nconst KIND_KEYS = ['skill', 'agent', 'tool', 'command'];\n/** Canonical published-skill ref: `@author/slug` (lowercase, hyphen/dot-safe). */\nconst SKILL_REF_RE = /^@[a-z0-9][a-z0-9-]*\\/[a-z0-9][a-z0-9._-]*$/;\n/**\n * Version-constraint grammar (skill deps only). Skillet skills are NOT semver:\n * a version is a monotonic integer per skill (\u00A72.3) plus a content hash\n * (\u00A72.2). The vocabulary is defined over THAT model, deliberately not npm\n * semver ranges.\n *\n *   omitted / \"*\" / \"latest\"  \u2192 latest gated version the recipient approved\n *   \"<N>\"                      \u2192 exact version integer\n *   \">=<N>\"                    \u2192 floor: that integer or newer\n *   \"sha256:<hex>\"             \u2192 exact content-hash pin (reproducible)\n */\nconst VERSION_INT_RE = /^\\d+$/;\nconst VERSION_FLOOR_RE = /^>=\\d+$/;\nconst VERSION_HASH_RE = /^sha256:[0-9a-f]{64}$/;\nexport function isValidRequiresVersion(v) {\n    return (v === '*' ||\n        v === 'latest' ||\n        VERSION_INT_RE.test(v) ||\n        VERSION_FLOOR_RE.test(v) ||\n        VERSION_HASH_RE.test(v));\n}\nexport class RequiresError extends Error {\n    code = 'invalid_requires';\n    constructor(message) {\n        super(message);\n        this.name = 'RequiresError';\n    }\n}\n/**\n * Parse + validate the `requires` value pulled from SKILL.md frontmatter.\n *\n * @param raw      The frontmatter `requires` value (any \u2014 it comes from YAML).\n * @param selfRef  The manifest's own `@author/slug`, when known, to reject\n *                 self-dependencies. Omit during import when the ref isn't\n *                 minted yet.\n * @throws RequiresError on any fatal rule (see docs \u00A73.3).\n */\nexport function validateRequires(raw, selfRef) {\n    const warnings = [];\n    if (raw === undefined || raw === null) {\n        return { entries: [], warnings };\n    }\n    if (!Array.isArray(raw)) {\n        throw new RequiresError('`requires` must be an array');\n    }\n    if (raw.length > MAX_REQUIRES_ENTRIES) {\n        throw new RequiresError(`\\`requires\\` has ${raw.length} entries; max is ${MAX_REQUIRES_ENTRIES}`);\n    }\n    const entries = [];\n    raw.forEach((item, i) => {\n        const where = `requires[${i}]`;\n        if (typeof item !== 'object' || item === null || Array.isArray(item)) {\n            throw new RequiresError(`${where} must be a mapping`);\n        }\n        const obj = item;\n        const present = KIND_KEYS.filter((k) => k in obj);\n        if (present.length === 0) {\n            throw new RequiresError(`${where} must declare exactly one of ${KIND_KEYS.join('/')}`);\n        }\n        if (present.length > 1) {\n            throw new RequiresError(`${where} declares multiple kinds (${present.join(', ')}); exactly one allowed`);\n        }\n        const kind = present[0];\n        const target = obj[kind];\n        if (typeof target !== 'string' || target.trim() === '') {\n            throw new RequiresError(`${where}.${kind} must be a non-empty string`);\n        }\n        if ('version' in obj && kind !== 'skill') {\n            throw new RequiresError(`${where}.version is only valid on a \\`skill\\` dependency`);\n        }\n        let version;\n        if (kind === 'skill') {\n            if (!SKILL_REF_RE.test(target)) {\n                throw new RequiresError(`${where}.skill \"${target}\" is not a canonical @author/slug ref`);\n            }\n            if (selfRef && target === selfRef) {\n                throw new RequiresError(`${where}.skill is a self-dependency (${target})`);\n            }\n            if ('version' in obj) {\n                const v = obj['version'];\n                if (typeof v !== 'string' || !isValidRequiresVersion(v)) {\n                    throw new RequiresError(`${where}.version \"${String(v)}\" is not a valid constraint`);\n                }\n                version = v;\n            }\n        }\n        let optional = false;\n        if ('optional' in obj) {\n            if (typeof obj['optional'] !== 'boolean') {\n                throw new RequiresError(`${where}.optional must be a boolean`);\n            }\n            optional = obj['optional'];\n        }\n        let reason;\n        if ('reason' in obj) {\n            const r = obj['reason'];\n            if (typeof r !== 'string') {\n                throw new RequiresError(`${where}.reason must be a string`);\n            }\n            if (r.length > MAX_REQUIRES_REASON_CHARS) {\n                throw new RequiresError(`${where}.reason exceeds ${MAX_REQUIRES_REASON_CHARS} chars`);\n            }\n            reason = r;\n        }\n        // Forward-compat: unknown keys are a warning, not a reject, so the schema\n        // can grow. Echoing them back surfaces typos to the author.\n        const known = new Set([kind, 'version', 'optional', 'reason']);\n        for (const key of Object.keys(obj)) {\n            if (!known.has(key)) {\n                warnings.push(`${where}: unknown key \"${key}\" ignored`);\n            }\n        }\n        entries.push({ kind, target, version, optional, reason });\n    });\n    return { entries, warnings };\n}\n", "// Author-signed device-key delegation (PROTOCOL \u00A74 extension).\n//\n// A delegation certificate is an Ed25519-signed statement, signed by the\n// author's PRIMARY key, that authorizes a device subkey to act (propose /\n// approve) on the author's behalf for a bounded time and scope. The trust chain\n// becomes:\n//\n//   proposal/approval sig \u2190 device subkey \u2190 signed delegation cert \u2190 primary key\n//\n// This module is the SINGLE SOURCE OF TRUTH for the cert/revocation wire shapes,\n// their canonical JSON serialization, and the hashed signing input. Both the\n// registry (verify) and the CLI (mint + sign + client-side verify) import it, so\n// the bytes that get signed and the bytes that get verified can never drift \u2014\n// drift would silently invalidate every delegation (see design \u00A79.6 / \u00A79.7).\n//\n// No new crypto primitive is introduced: the cert is hashed to a\n// `sha256:<hex>` string and signed exactly like a bundle content_hash\n// (signing/envelope.ts), i.e. Ed25519 over `utf8(certHash)`.\nimport { createHash } from 'node:crypto';\n// \u2500\u2500 constants \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nexport const DELEGATION_CERT_VERSION = 1;\nexport const DELEGATION_CERT_TYP = 'skillet-delegation';\nexport const DELEGATION_REVOCATION_TYP = 'skillet-delegation-revocation';\n/** Hard ceiling on a delegation's lifetime (design \u00A72.3 step 5). 365 days. */\nexport const MAX_DELEGATION_TTL_SEC = 365 * 24 * 60 * 60;\n/** CLI-default issuance window (informational; enforced cap is the max). 90 days. */\nexport const DEFAULT_DELEGATION_TTL_SEC = 90 * 24 * 60 * 60;\n/**\n * Scopes a device key may hold when backed by an author-signed delegation cert.\n * `claim` is never delegable. `publish` requires the author to approve the device;\n * browser author_keys without a cert still cannot publish.\n */\nexport const DELEGABLE_SCOPES = ['propose', 'approve', 'publish'];\nconst KEY_ID_RE = /^[0-9a-f]{64}$/;\nconst NONCE_RE = /^[0-9a-f]{32}$/; // 16 random bytes, hex\nconst ED25519_RAW_PUB_BYTES = 32;\n// \u2500\u2500 canonical JSON (RFC 8785 JCS subset) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Deterministic canonical JSON: object keys sorted by UTF-16 code unit, no\n * insignificant whitespace, ECMAScript number formatting, minimal string\n * escaping (V8's JSON.stringify already matches JCS for our ASCII-only inputs).\n *\n * Restricted on purpose to the value types a cert/revocation can hold (string,\n * finite number, boolean, null, array, plain object). Anything else throws \u2014\n * a malformed payload must never be silently coerced into signed bytes.\n */\nexport function canonicalJson(value) {\n    return serialize(value);\n}\nfunction serialize(v) {\n    if (v === null)\n        return 'null';\n    const t = typeof v;\n    if (t === 'string')\n        return JSON.stringify(v);\n    if (t === 'boolean')\n        return v ? 'true' : 'false';\n    if (t === 'number') {\n        if (!Number.isFinite(v)) {\n            throw new Error('canonicalJson: non-finite number is not serializable');\n        }\n        // JCS uses ECMAScript Number\u2192String; for the integer inputs we sign this is exact.\n        return String(v);\n    }\n    if (Array.isArray(v)) {\n        return '[' + v.map((el) => serialize(el)).join(',') + ']';\n    }\n    if (t === 'object') {\n        const obj = v;\n        const keys = Object.keys(obj).sort(); // default sort == UTF-16 code unit order == JCS\n        const parts = [];\n        for (const k of keys) {\n            const val = obj[k];\n            if (val === undefined)\n                continue; // undefined has no JSON form; skip like JSON.stringify\n            parts.push(JSON.stringify(k) + ':' + serialize(val));\n        }\n        return '{' + parts.join(',') + '}';\n    }\n    throw new Error(`canonicalJson: unsupported value type ${t}`);\n}\n/** `sha256:` + hex(sha256(canonicalJson(cert))) \u2014 the string that gets signed. */\nexport function delegationCertHash(cert) {\n    return 'sha256:' + createHash('sha256').update(Buffer.from(canonicalJson(cert), 'utf8')).digest('hex');\n}\n/** Same shape for the revocation statement (distinct `typ` \u21D2 disjoint input). */\nexport function revocationHash(rev) {\n    return 'sha256:' + createHash('sha256').update(Buffer.from(canonicalJson(rev), 'utf8')).digest('hex');\n}\n/**\n * Validates a DelegationCert's structure and policy (NOT its signature):\n * version/typ, id/handle shapes, `device_key_id == hex(device_pub)`,\n * scopes \u2286 DELEGABLE_SCOPES (non-empty), and a positive TTL within the cap.\n *\n * Shared by registration (registry \u00A72.3) and by every verify-time re-check so\n * the same rules apply when minting and when honoring a stored cert.\n */\nexport function validateDelegationCert(cert) {\n    if (!cert || typeof cert !== 'object') {\n        return { code: 'invalid_cert', message: 'cert must be an object' };\n    }\n    const c = cert;\n    if (c.v !== DELEGATION_CERT_VERSION) {\n        return { code: 'invalid_cert', message: `unsupported cert version ${JSON.stringify(c.v)}` };\n    }\n    if (c.typ !== DELEGATION_CERT_TYP) {\n        return { code: 'invalid_cert', message: `cert typ must be ${DELEGATION_CERT_TYP}` };\n    }\n    if (typeof c.author_key_id !== 'string' || !KEY_ID_RE.test(c.author_key_id)) {\n        return { code: 'invalid_cert', message: 'author_key_id must be 64-char lowercase hex' };\n    }\n    if (typeof c.handle !== 'string' || c.handle.length === 0) {\n        return { code: 'invalid_cert', message: 'handle must be a non-empty string' };\n    }\n    if (typeof c.device_key_id !== 'string' || !KEY_ID_RE.test(c.device_key_id)) {\n        return { code: 'invalid_device_key', message: 'device_key_id must be 64-char lowercase hex' };\n    }\n    if (typeof c.device_pub !== 'string' || c.device_pub.length === 0) {\n        return { code: 'invalid_device_key', message: 'device_pub must be a non-empty base64 string' };\n    }\n    // device_key_id MUST equal hex(device_pub) \u2014 binds the indexable id to the\n    // signed key bytes so they can never disagree (design \u00A71.1, T7).\n    let devRaw;\n    try {\n        devRaw = Buffer.from(c.device_pub, 'base64');\n    }\n    catch {\n        return { code: 'invalid_device_key', message: 'device_pub is not valid base64' };\n    }\n    if (devRaw.length !== ED25519_RAW_PUB_BYTES) {\n        return {\n            code: 'invalid_device_key',\n            message: `device_pub must decode to ${ED25519_RAW_PUB_BYTES} bytes, got ${devRaw.length}`,\n        };\n    }\n    if (devRaw.toString('hex') !== c.device_key_id) {\n        return { code: 'invalid_device_key', message: 'device_key_id must equal hex(device_pub)' };\n    }\n    if (typeof c.nonce !== 'string' || !NONCE_RE.test(c.nonce)) {\n        return { code: 'invalid_cert', message: 'nonce must be 32-char lowercase hex (16 bytes)' };\n    }\n    if (!Array.isArray(c.scopes) || c.scopes.length === 0) {\n        return { code: 'invalid_scope', message: 'scopes must be a non-empty array' };\n    }\n    for (const s of c.scopes) {\n        if (typeof s !== 'string' || !DELEGABLE_SCOPES.includes(s)) {\n            return {\n                code: 'invalid_scope',\n                message: `scope ${JSON.stringify(s)} is not delegable; allowed: ${DELEGABLE_SCOPES.join(', ')}`,\n            };\n        }\n    }\n    if (typeof c.issued_at !== 'number' ||\n        !Number.isInteger(c.issued_at) ||\n        typeof c.expires_at !== 'number' ||\n        !Number.isInteger(c.expires_at)) {\n        return { code: 'invalid_expiry', message: 'issued_at and expires_at must be integer unix seconds' };\n    }\n    const ttl = c.expires_at - c.issued_at;\n    if (ttl <= 0) {\n        return { code: 'invalid_expiry', message: 'expires_at must be after issued_at' };\n    }\n    if (ttl > MAX_DELEGATION_TTL_SEC) {\n        return {\n            code: 'invalid_expiry',\n            message: `delegation TTL ${ttl}s exceeds cap ${MAX_DELEGATION_TTL_SEC}s`,\n        };\n    }\n    return { ok: true, cert: c };\n}\n", "/**\n * NF-004 / U4 \u2014 domain-separated bundle signature payload (v2).\n *\n * v1 signs utf8(content_hash) only. v2 signs a canonical struct binding\n * author_key_id + ref + version + content_hash so signatures cannot replay\n * across names or identities.\n */\nimport { canonicalJson } from './delegation.js';\nexport const BUNDLE_SIG_TYP = 'skillet-bundle-v1';\nconst VALID_KEY_ID_RE = /^[0-9a-f]{64}$/;\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\nconst REF_RE = /^@[a-z0-9-]{1,64}\\/[a-z0-9-]{1,64}$/;\nexport function bundleSignatureBytes(payload) {\n    if (payload.typ !== BUNDLE_SIG_TYP) {\n        throw new Error(`bundleSignatureBytes: unsupported typ ${JSON.stringify(payload.typ)}`);\n    }\n    if (!VALID_KEY_ID_RE.test(payload.author_key_id)) {\n        throw new Error(`bundleSignatureBytes: invalid author_key_id ${JSON.stringify(payload.author_key_id)}`);\n    }\n    if (!REF_RE.test(payload.ref)) {\n        throw new Error(`bundleSignatureBytes: ref must match @author/slug, got ${JSON.stringify(payload.ref)}`);\n    }\n    if (!Number.isInteger(payload.version) || payload.version < 1) {\n        throw new Error(`bundleSignatureBytes: version must be a positive integer, got ${payload.version}`);\n    }\n    if (!CONTENT_HASH_RE.test(payload.content_hash)) {\n        throw new Error(`bundleSignatureBytes: content_hash must match /^sha256:[0-9a-f]{64}$/, got ${JSON.stringify(payload.content_hash)}`);\n    }\n    return Buffer.from(canonicalJson(payload), 'utf8');\n}\nexport function isBundleSignatureV2(envelope) {\n    return envelope?.sig_version === 2;\n}\n", "/** Domain-separated PoP message prefix for author browser key bind. */\nexport const KEY_BIND_POP_PREFIX = 'skillet-key-bind:v1:';\nexport function keyBindPopMessage(nonce, keyId) {\n    return `${KEY_BIND_POP_PREFIX}${nonce}:${keyId}`;\n}\nexport function keyBindPopMessageBytes(nonce, keyId) {\n    return Buffer.from(keyBindPopMessage(nonce, keyId), 'utf8');\n}\n", "// Reserved handles \u2014 usernames that cannot be claimed.\n//\n// Single source of truth shared by the registry claim gate (authoritative) and\n// the web client (inline UX). Two reasons a name is reserved:\n//   1. Impersonation / trust \u2014 brand, official, and authority-sounding names a\n//      bad actor could use to phish (\"official\", \"support\", \"skillet-team\").\n//   2. Namespace safety \u2014 words that collide with current or likely future\n//      top-level web routes and system identities, so a handle can never\n//      shadow `/settings`, `/api`, `noreply@\u2026`, etc.\n//\n// Matching is exact and case-insensitive against the normalized handle (handles\n// are already lowercase alphanumeric + hyphen per HANDLE_RE). This mirrors how\n// GitHub/GitLab/etc. reserve names: predictable, no fuzzy matching. Profanity\n// filtering is intentionally NOT in scope here \u2014 that is a separate concern with\n// different tradeoffs (locale, false positives) and can be layered on later.\n//\n// ONE narrow exception to exact-match: brand-prefixed authority\n// compounds. Exact-match only catches bare tokens, so `skillet-support`,\n// `skillet-team`, `skilletsecurity`, etc. all slipped through \u2014\n// a real phishing vector (register `skillet-support`, DM users as staff). We\n// reserve `<brand>` + optional `-` + `<authority term>` for the brand set\n// (`skillet`) crossed with a CURATED authority-term set. This is\n// deliberately a curated list, not a blanket `^skillet-?` reject: a blanket\n// rule would also block legitimate community handles like `skillet-fan`, which\n// must stay claimable. So `skillet-fan` passes; `skillet-support` does not.\n/** Legacy product codename handle \u2014 reserved so it cannot be claimed. */\nexport const RESERVED_LEGACY_CODENAME_HANDLE = 'knox';\n/**\n * Lowercase reserved handles. Grouped only for readability \u2014 membership is a\n * flat set. Keep additions lowercase and hyphen/space free (a handle is a\n * single token under HANDLE_RE).\n */\nexport const RESERVED_HANDLES = new Set([\n    // --- Brand / product ---\n    'skillet',\n    'skillethq',\n    'skilletofficial',\n    RESERVED_LEGACY_CODENAME_HANDLE,\n    'dot',\n    'dotfan',\n    // --- Authority / impersonation ---\n    'official',\n    'verified',\n    'admin',\n    'administrator',\n    'admins',\n    'superuser',\n    'root',\n    'sysadmin',\n    'moderator',\n    'mod',\n    'mods',\n    'staff',\n    'team',\n    'teams',\n    'owner',\n    'support',\n    'helpdesk',\n    'help',\n    'security',\n    'trust',\n    'safety',\n    'abuse',\n    'legal',\n    'billing',\n    'payments',\n    'sales',\n    'press',\n    'marketing',\n    'info',\n    'contact',\n    // --- Mail / system identities ---\n    'noreply',\n    'no-reply',\n    'donotreply',\n    'postmaster',\n    'webmaster',\n    'hostmaster',\n    'mailer-daemon',\n    'daemon',\n    'system',\n    'bot',\n    'robot',\n    // --- Generic user/identity placeholders ---\n    'user',\n    'users',\n    'username',\n    'account',\n    'accounts',\n    'me',\n    'myself',\n    'you',\n    'self',\n    'anonymous',\n    'anon',\n    'guest',\n    'nobody',\n    'everyone',\n    'all',\n    'null',\n    'undefined',\n    'none',\n    'unknown',\n    // --- Web routes / reserved namespace ---\n    'api',\n    'app',\n    'apps',\n    'www',\n    'web',\n    'mail',\n    'email',\n    'cdn',\n    'assets',\n    'static',\n    'media',\n    'images',\n    'img',\n    'files',\n    'download',\n    'downloads',\n    'upload',\n    'uploads',\n    'auth',\n    'oauth',\n    'login',\n    'logout',\n    'signin',\n    'signout',\n    'signup',\n    'register',\n    'verify',\n    'verification',\n    'confirm',\n    'reset',\n    'password',\n    'token',\n    'tokens',\n    'key',\n    'keys',\n    'session',\n    'settings',\n    'setting',\n    'profile',\n    'profiles',\n    'author',\n    'authors',\n    'dashboard',\n    'home',\n    'explore',\n    'search',\n    'discover',\n    'studio',\n    'skill',\n    'skills',\n    'install',\n    'installs',\n    'kit',\n    'kits',\n    'org',\n    'orgs',\n    'organization',\n    'organizations',\n    'enterprise',\n    'team-settings',\n    'docs',\n    'doc',\n    'documentation',\n    'blog',\n    'news',\n    'status',\n    'health',\n    'pricing',\n    'plans',\n    'about',\n    'terms',\n    'tos',\n    'privacy',\n    'policy',\n    'legal-notice',\n    'faq',\n    'contact-us',\n    'careers',\n    'jobs',\n    // --- Environments / infra ---\n    'dev',\n    'test',\n    'testing',\n    'staging',\n    'stage',\n    'prod',\n    'production',\n    'demo',\n    'sandbox',\n    'beta',\n    'alpha',\n    'internal',\n    'localhost',\n    'example',\n]);\n/**\n * Brand prefixes whose authority-compounds are reserved. Bare brand\n * tokens (`skillet`) are already in RESERVED_HANDLES; this set drives\n * the compound rule below.\n */\nexport const BRAND_PREFIXES = ['skillet'];\n/**\n * Authority / staff-impersonation terms that, when suffixed onto a brand prefix\n * (with or without a hyphen), produce a reserved handle. Curated on purpose:\n * each term here reads as official Skillet staff or a trust function, so\n * `skillet-<term>` is a phishing handle, never legitimate community fandom.\n * Community-flavored suffixes (`fan`, `lover`, `ville`, \u2026) are intentionally\n * absent so handles like `skillet-fan` stay claimable.\n */\nexport const BRAND_AUTHORITY_TERMS = new Set([\n    'official',\n    'verified',\n    'admin',\n    'admins',\n    'administrator',\n    'superuser',\n    'root',\n    'sysadmin',\n    'moderator',\n    'mod',\n    'mods',\n    'staff',\n    'team',\n    'teams',\n    'owner',\n    'support',\n    'helpdesk',\n    'help',\n    'security',\n    'trust',\n    'safety',\n    'abuse',\n    'legal',\n    'billing',\n    'payments',\n    'sales',\n    'press',\n    'info',\n    'contact',\n    'bot',\n    'hq',\n]);\n/**\n * True when `h` (already normalized) is a brand prefix followed \u2014 optionally via\n * hyphens \u2014 by a curated authority term. Catches `skillet-support`,\n * `skilletsupport`, `skillet--support`, and `skillet-support-team`.\n * Returns false for `skillet-fan` and bare `skillet`.\n */\nfunction fusedAuthorityTermsCover(rest) {\n    if (rest.length === 0 || BRAND_AUTHORITY_TERMS.has(rest))\n        return false;\n    const terms = [...BRAND_AUTHORITY_TERMS].sort((a, b) => b.length - a.length);\n    function segmentCount(rem) {\n        if (rem.length === 0)\n            return 0;\n        for (const term of terms) {\n            if (!rem.startsWith(term))\n                continue;\n            const next = segmentCount(rem.slice(term.length));\n            if (next >= 0)\n                return 1 + next;\n        }\n        return -1;\n    }\n    return segmentCount(rest) >= 2;\n}\nfunction isReservedBrandCompound(h) {\n    for (const brand of BRAND_PREFIXES) {\n        if (!h.startsWith(brand))\n            continue;\n        let rest = h.slice(brand.length);\n        if (rest.length === 0)\n            continue; // bare brand \u2192 handled by RESERVED_HANDLES\n        // Fused suffix (no hyphens): whole remainder must be an authority term, or a\n        // concatenation of two or more authority terms (e.g. skilletadminsupport).\n        if (!rest.includes('-')) {\n            if (BRAND_AUTHORITY_TERMS.has(rest))\n                return true;\n            if (fusedAuthorityTermsCover(rest))\n                return true;\n            continue;\n        }\n        // Hyphenated suffix: strip repeated leading separators, then flag\n        // when any segment is a curated authority term.\n        rest = rest.replace(/^-+/, '');\n        if (rest.length === 0)\n            continue;\n        for (const segment of rest.split('-')) {\n            if (segment.length > 0 && BRAND_AUTHORITY_TERMS.has(segment))\n                return true;\n        }\n    }\n    return false;\n}\n/** True if `handle` is reserved and may not be claimed. Case-insensitive. */\nexport function isReservedHandle(handle) {\n    const h = handle.trim().toLowerCase();\n    return RESERVED_HANDLES.has(h) || isReservedBrandCompound(h);\n}\n", "// Canonical slug generation \u2014 single source of truth shared by the registry\n// (authoritative), the web client, and the CLI importers. Historically this\n// logic was copy-pasted across ~10 sites, each running\n// `.replace(/[^a-z0-9]+/g, '-')`. That collapses EVERY non-alphanumeric run to a\n// dash, so `writer's room` became `writer-s-room` \u2014 the apostrophe split a word\n// it should have closed. We strip apostrophes (straight and typographic) BEFORE\n// collapsing, so `writer's room` \u2192 `writers-room`.\n//\n// Kept behavior a strict superset of the old kit slugifier: the `fallback` and\n// `maxLength` options reproduce its `|| 'kit'` and 64-char cap so existing call\n// sites adopt this without surprise (apart from the intended apostrophe fix).\n/** Apostrophes elided rather than dashed: straight `'`, typographic `'`, backtick-ish. */\nconst APOSTROPHES = /['\u2019\u2018`\u00B4]/g;\nexport function slugify(input, options = {}) {\n    let slug = input\n        .toLowerCase()\n        .replace(APOSTROPHES, '')\n        .replace(/[^a-z0-9]+/g, '-')\n        .replace(/^-+|-+$/g, '');\n    if (options.maxLength != null && slug.length > options.maxLength) {\n        slug = slug.slice(0, options.maxLength).replace(/-+$/g, '');\n    }\n    return slug || options.fallback || '';\n}\n", "// Reserved skill slugs \u2014 slugs a skill may NOT use because they collide with a\n// static route segment that lives directly under the owner namespace\n// (`/{owner}/...`). Skills render at `/{owner}/{slug}`, a dynamic segment that\n// sits as a sibling of these static segments. Next.js resolves the static\n// segment first, so a skill slugged `kit` would publish successfully yet be\n// permanently unreachable \u2014 the URL would always render the kit page instead.\n// We reject such slugs at publish time so the failure is loud, not silent.\n//\n// HARD COUPLING: this set MUST equal the static child route segments of\n// `packages/web/src/app/(consumer)/[author]/`. Today those are `kit`,\n// `followers`, and `following`. If a new static `[author]/<segment>` route is\n// added, add `<segment>` here too (and cover it in the permalink-routing test).\n//\n// This is distinct from RESERVED_HANDLES, which guards TOP-LEVEL handles\n// (`/{handle}`). This set guards per-owner skill slugs one level down.\n/** Lowercase reserved skill slugs. Membership is exact, case-insensitive. */\nexport const RESERVED_SKILL_SLUGS = new Set([\n    'kit',\n    'followers',\n    'following',\n]);\n/** Protocol grammar for skill slugs (matches core `parseSkillRef`). */\nexport const SKILL_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;\n/** True when `slug` matches the canonical skill slug grammar. */\nexport function isValidSkillSlug(slug) {\n    return SKILL_SLUG_RE.test(slug);\n}\n/** True when `slug` collides with a static owner-namespace route segment. */\nexport function isReservedSkillSlug(slug) {\n    return RESERVED_SKILL_SLUGS.has(slug.trim().toLowerCase());\n}\n", "// `triggers:` manifest schema \u2014 declarative activation cues.\n//\n// Natural-language hints for when a runtime should surface or invoke a skill.\n// Declarative-only \u2014 never an executable hook. Adapters map this field to\n// native trigger surfaces where available; otherwise it folds into the\n// description surface at materialize time.\n/** Per-skill cap on declared triggers \u2014 bounds manifest size. */\nexport const MAX_TRIGGERS = 32;\n/** Max length of a single trigger string. */\nexport const MAX_TRIGGER_CHARS = 280;\nexport class TriggersError extends Error {\n    code = 'invalid_triggers';\n    constructor(message) {\n        super(message);\n        this.name = 'TriggersError';\n    }\n}\n/**\n * Parse + validate the `triggers` value pulled from SKILL.md frontmatter.\n *\n * @throws TriggersError on any fatal rule.\n */\nexport function validateTriggers(raw) {\n    const warnings = [];\n    if (raw === undefined || raw === null) {\n        return { triggers: [], warnings };\n    }\n    if (!Array.isArray(raw)) {\n        throw new TriggersError('`triggers` must be an array of strings');\n    }\n    if (raw.length > MAX_TRIGGERS) {\n        throw new TriggersError(`\\`triggers\\` has ${raw.length} entries; max is ${MAX_TRIGGERS}`);\n    }\n    const triggers = [];\n    const seen = new Set();\n    raw.forEach((item, i) => {\n        const where = `triggers[${i}]`;\n        if (typeof item !== 'string') {\n            throw new TriggersError(`${where} must be a string`);\n        }\n        const value = item.trim();\n        if (value.length === 0) {\n            throw new TriggersError(`${where} must be a non-empty string`);\n        }\n        if (value.length > MAX_TRIGGER_CHARS) {\n            throw new TriggersError(`${where} exceeds ${MAX_TRIGGER_CHARS} chars`);\n        }\n        const key = value.toLowerCase();\n        if (seen.has(key)) {\n            warnings.push(`${where}: duplicate trigger ignored`);\n            return;\n        }\n        seen.add(key);\n        triggers.push(value);\n    });\n    return { triggers, warnings };\n}\n", "// One authoritative scanner vocabulary \u2014 the single source of truth both the\n// web (copy) and the registry (ordering) draw from.\n//\n// Entries are keyed by the ids the detectors ALREADY emit: the seven capability\n// ids (\"what can this skill do?\") and the fourteen threat-category ids (\"is this\n// a threat?\"). This file changes NO detector emission and NO wire format \u2014 the\n// keys ARE the strings emitted today. It only attaches user-facing copy and an\n// optional permission tag to those ids.\n//\n// Two surfaces:\n//   - PERMISSIONS \u2014 one entry per capability id (kind 'permission'). Installer\n//     voice: what the skill CAN do. Ported from the web's CAPABILITY_LABELS /\n//     CAPABILITY_DESCRIBE.\n//   - FLAGS \u2014 one entry per threat-category id (kind 'flag'). label + describe +\n//     fix, plus an optional `permission` tag folding an action finding into the\n//     capability it duplicates (e.g. `destructive` \u2192 `deletes-files`).\n//\n// Copy is plain-English and on-brand: label is a short name, describe is one\n// calm installer-facing sentence, fix is one author-facing sentence. Add an id\n// once here and every trust surface stays in lockstep.\n// ---------------------------------------------------------------------------\n// Permissions \u2014 one per capability id, in canonical chip order.\n// ---------------------------------------------------------------------------\n/**\n * The single canonical chip order, most-impactful-first. This is the canonical\n * home for the order the registry's `CAPABILITY_ORDER` and the web mirror;\n * those import it from here. Keep it the declaration order of the capability\n * union.\n */\nexport const PERMISSION_ORDER = [\n    'runs-shell',\n    'network',\n    'writes-files',\n    'deletes-files',\n    'reads-secrets',\n    'install-hooks',\n    'executes-generated',\n];\n/** Capability vocabulary, keyed by capability id. Ported from the web's\n *  CAPABILITY_LABELS / CAPABILITY_DESCRIBE \u2014 installer voice, no fix. */\nexport const PERMISSIONS = {\n    'runs-shell': {\n        id: 'runs-shell',\n        kind: 'permission',\n        label: 'Run commands',\n        describe: 'Runs shell commands on your machine.',\n    },\n    network: {\n        id: 'network',\n        kind: 'permission',\n        label: 'Use the internet',\n        describe: 'Connects to the internet to fetch data or call other services.',\n    },\n    'writes-files': {\n        id: 'writes-files',\n        kind: 'permission',\n        label: 'Write files',\n        describe: 'Creates or changes files on disk.',\n    },\n    'deletes-files': {\n        id: 'deletes-files',\n        kind: 'permission',\n        label: 'Delete files',\n        describe: 'Removes or overwrites files.',\n    },\n    'reads-secrets': {\n        id: 'reads-secrets',\n        kind: 'permission',\n        label: 'Read env variables',\n        describe: 'Reads environment variables, which may hold tokens or keys.',\n    },\n    'install-hooks': {\n        id: 'install-hooks',\n        kind: 'permission',\n        label: 'Install packages',\n        describe: 'Installs third-party packages, which can run their own setup scripts.',\n    },\n    'executes-generated': {\n        id: 'executes-generated',\n        kind: 'permission',\n        label: 'Run generated code',\n        describe: 'Runs code that it generates at runtime.',\n    },\n};\n// ---------------------------------------------------------------------------\n// Flags \u2014 one per threat-category id.\n//\n// Copy for injection, exfil, destructive, obfuscation, secret,\n// privilege-escalation, and excessive-agency is ported from the web CATALOG\n// (the entry each category resolves to through `findingCategory`). The rest \u2014\n// prompt-leak, supply-chain, output-handling, memory-poisoning, tool-misuse,\n// rogue-agent, and risky-call \u2014 are authored fresh in the same\n// installer voice, because they either fell back to GENERIC or collapsed onto a\n// shared CATALOG entry that did not describe them precisely.\n//\n// `permission` is seeded only from the web's `findingCapability` folds:\n// `risky-call` \u2192 `runs-shell`, `destructive` \u2192 `deletes-files`. No threat\n// category is network-shaped under that logic (exfil is deliberately left\n// standalone), so nothing folds into `network`. Everything else is a\n// standalone warning with no permission tag.\n//\n// `shape` is set on EVERY flag and routes a sub-serious form's presentation:\n// `action` (the skill does something) \u2192 \"What this skill can do\"; `content`\n// (a property of the files) \u2192 the quiet \"also noticed\" note. Action: exfil,\n// destructive, risky-call, supply-chain, tool-misuse, output-handling,\n// privilege-escalation, excessive-agency, rogue-agent. Content: injection,\n// prompt-leak, obfuscation, secret, memory-poisoning.\n// ---------------------------------------------------------------------------\n/** Threat-category vocabulary, keyed by category id. */\nexport const FLAGS = {\n    // --- Ported from the web CATALOG ---\n    injection: {\n        id: 'injection',\n        kind: 'flag',\n        label: 'Prompt injection',\n        describe: 'Text that could try to hijack an agent\u2019s instructions.',\n        fix: 'Reword it so it reads as instructions to the user, not the agent.',\n        shape: 'content',\n    },\n    exfil: {\n        id: 'exfil',\n        kind: 'flag',\n        label: 'Send data out',\n        describe: 'Moves data to an outside destination. Confirm that\u2019s expected.',\n        fix: 'Confirm what leaves and where it goes. Don\u2019t pipe a download straight into a shell.',\n        shape: 'action',\n    },\n    destructive: {\n        id: 'destructive',\n        kind: 'flag',\n        label: 'Delete or overwrite files',\n        describe: 'Removes or overwrites files. Destructive if the path is wrong.',\n        fix: 'Point it at a specific path, never the root.',\n        permission: 'deletes-files',\n        shape: 'action',\n    },\n    obfuscation: {\n        id: 'obfuscation',\n        kind: 'flag',\n        label: 'Hard-to-read code',\n        describe: 'Encoded or scrambled content you can\u2019t read at a glance.',\n        fix: 'Keep it if it\u2019s real data. Otherwise spell it out so it\u2019s readable.',\n        shape: 'content',\n    },\n    secret: {\n        id: 'secret',\n        kind: 'flag',\n        label: 'Possible secret',\n        describe: 'A value that looks like a password or key \u2014 it could be a real credential.',\n        fix: 'Swap it for an environment variable or a placeholder.',\n        shape: 'content',\n    },\n    'privilege-escalation': {\n        id: 'privilege-escalation',\n        kind: 'flag',\n        label: 'Ask for more access',\n        describe: 'Requests elevated permissions. Confirm the skill needs them.',\n        fix: 'Drop the elevated permission if the skill doesn\u2019t need it.',\n        shape: 'action',\n    },\n    'excessive-agency': {\n        id: 'excessive-agency',\n        kind: 'flag',\n        label: 'Act without asking',\n        describe: 'Takes actions on its own, like auto-approving or looping. Fine for trusted automation, worth a glance.',\n        fix: 'Add a confirmation step before it acts on its own.',\n        shape: 'action',\n    },\n    // --- Authored fresh ---\n    'prompt-leak': {\n        id: 'prompt-leak',\n        kind: 'flag',\n        label: 'Reveal the system prompt',\n        describe: 'Tries to reveal an agent\u2019s hidden system instructions.',\n        fix: 'Remove the request for the hidden prompt, or say plainly why the skill needs it.',\n        shape: 'content',\n    },\n    'supply-chain': {\n        id: 'supply-chain',\n        kind: 'flag',\n        label: 'Fetch and run code',\n        describe: 'Downloads code or a package at runtime and runs it, so what executes can change later.',\n        fix: 'Pin the source to a known version and review what it runs before shipping.',\n        shape: 'action',\n    },\n    'output-handling': {\n        id: 'output-handling',\n        kind: 'flag',\n        label: 'Act on model output',\n        describe: 'Feeds the model\u2019s own output into a shell, query, or page without checking it first.',\n        fix: 'Validate or escape model output before you run, query, or render it.',\n        shape: 'action',\n    },\n    'memory-poisoning': {\n        id: 'memory-poisoning',\n        kind: 'flag',\n        label: 'Rewrite agent memory',\n        describe: 'Writes instructions into the agent\u2019s memory that persist across sessions.',\n        fix: 'Drop the persistent write, or confirm the skill genuinely needs durable memory.',\n        shape: 'content',\n    },\n    'tool-misuse': {\n        id: 'tool-misuse',\n        kind: 'flag',\n        label: 'Disable a safety check',\n        describe: 'Turns off a guardrail like auth, TLS verification, or a confirmation prompt.',\n        fix: 'Leave the safety flag on, or explain why this command must skip it.',\n        shape: 'action',\n    },\n    'rogue-agent': {\n        id: 'rogue-agent',\n        kind: 'flag',\n        label: 'Persist or self-modify',\n        describe: 'Sets itself to run later or rewrites its own code to keep running.',\n        fix: 'Remove the persistence hook unless staying resident is the skill\u2019s stated job.',\n        shape: 'action',\n    },\n    'risky-call': {\n        id: 'risky-call',\n        kind: 'flag',\n        label: 'Run a shell command',\n        describe: 'Calls exec, eval, or a subprocess to run a command directly.',\n        fix: 'Build the command from trusted input only, and quote or validate anything dynamic.',\n        permission: 'runs-shell',\n        shape: 'action',\n    },\n};\n/** Every vocabulary entry, keyed by id (permissions and flags merged). */\nexport const SCAN_VOCABULARY = {\n    ...PERMISSIONS,\n    ...FLAGS,\n};\n/** Look up a vocabulary entry by emitted id. Undefined for unknown ids. */\nexport function vocabularyEntry(id) {\n    return SCAN_VOCABULARY[id];\n}\n", "// Basic eval fixture + static runner.\n//\n// v1 runs keyword checks against SKILL.md \u2014 no LLM calls. A bundled\n// `evals/smoke.json` declares prompts and expected instruction coverage;\n// passing means the skill text addresses every case. Full certification is v6.\n/** Canonical minimal eval fixture path inside a skill bundle. */\nexport const EVAL_SMOKE_PATH = 'evals/smoke.json';\nexport const EVAL_FIXTURE_VERSION = 1;\nexport const MAX_EVAL_CASES = 8;\nexport const MAX_EVAL_EXPECT_TERMS = 16;\nexport const MAX_EVAL_TERM_CHARS = 64;\nexport const MAX_EVAL_PROMPT_CHARS = 280;\nexport const MAX_EVAL_ID_CHARS = 64;\nexport class EvalError extends Error {\n    code = 'invalid_eval';\n    constructor(message) {\n        super(message);\n        this.name = 'EvalError';\n    }\n}\nexport function parseEvalFixture(raw) {\n    if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n        throw new EvalError('eval fixture must be an object');\n    }\n    const obj = raw;\n    if (obj.version !== EVAL_FIXTURE_VERSION) {\n        throw new EvalError(`eval fixture version must be ${EVAL_FIXTURE_VERSION}`);\n    }\n    if (!Array.isArray(obj.cases) || obj.cases.length === 0) {\n        throw new EvalError('eval fixture must include at least one case');\n    }\n    if (obj.cases.length > MAX_EVAL_CASES) {\n        throw new EvalError(`eval fixture has ${obj.cases.length} cases; max is ${MAX_EVAL_CASES}`);\n    }\n    const cases = obj.cases.map((item, i) => {\n        const where = `cases[${i}]`;\n        if (typeof item !== 'object' || item === null || Array.isArray(item)) {\n            throw new EvalError(`${where} must be an object`);\n        }\n        const c = item;\n        const id = c.id;\n        if (typeof id !== 'string' || id.trim().length === 0) {\n            throw new EvalError(`${where}.id must be a non-empty string`);\n        }\n        if (id.length > MAX_EVAL_ID_CHARS) {\n            throw new EvalError(`${where}.id exceeds ${MAX_EVAL_ID_CHARS} chars`);\n        }\n        const prompt = c.prompt;\n        if (typeof prompt !== 'string' || prompt.trim().length === 0) {\n            throw new EvalError(`${where}.prompt must be a non-empty string`);\n        }\n        if (prompt.length > MAX_EVAL_PROMPT_CHARS) {\n            throw new EvalError(`${where}.prompt exceeds ${MAX_EVAL_PROMPT_CHARS} chars`);\n        }\n        if (!Array.isArray(c.expect_in_skill) || c.expect_in_skill.length === 0) {\n            throw new EvalError(`${where}.expect_in_skill must be a non-empty string array`);\n        }\n        if (c.expect_in_skill.length > MAX_EVAL_EXPECT_TERMS) {\n            throw new EvalError(`${where}.expect_in_skill exceeds ${MAX_EVAL_EXPECT_TERMS} terms`);\n        }\n        const expect_in_skill = c.expect_in_skill.map((term, j) => {\n            if (typeof term !== 'string' || term.trim().length === 0) {\n                throw new EvalError(`${where}.expect_in_skill[${j}] must be a non-empty string`);\n            }\n            if (term.length > MAX_EVAL_TERM_CHARS) {\n                throw new EvalError(`${where}.expect_in_skill[${j}] exceeds ${MAX_EVAL_TERM_CHARS} chars`);\n            }\n            return term.trim();\n        });\n        return { id: id.trim(), prompt: prompt.trim(), expect_in_skill };\n    });\n    return { version: EVAL_FIXTURE_VERSION, cases };\n}\nexport function readEvalFixtureFromBundle(bundle) {\n    const bytes = bundle.get(EVAL_SMOKE_PATH);\n    if (!bytes)\n        return null;\n    let parsed;\n    try {\n        parsed = JSON.parse(Buffer.from(bytes).toString('utf8'));\n    }\n    catch {\n        throw new EvalError('evals/smoke.json is not valid JSON');\n    }\n    return parseEvalFixture(parsed);\n}\n/**\n * Run the v1 static basic eval against a decoded bundle.\n * No fixture \u2192 status `none`. Fixture present \u2192 `passed` or `failed`.\n */\nexport function runBasicEval(bundle) {\n    const fixture = readEvalFixtureFromBundle(bundle);\n    if (!fixture) {\n        return { status: 'none' };\n    }\n    const skillMd = bundle.get('SKILL.md');\n    if (!skillMd) {\n        return {\n            status: 'failed',\n            fixture,\n            case_results: fixture.cases.map((c) => ({\n                id: c.id,\n                passed: false,\n                missing: c.expect_in_skill,\n            })),\n        };\n    }\n    const haystack = Buffer.from(skillMd).toString('utf8').toLowerCase();\n    const case_results = fixture.cases.map((c) => {\n        const missing = c.expect_in_skill.filter((term) => !haystack.includes(term.toLowerCase()));\n        return { id: c.id, passed: missing.length === 0, ...(missing.length ? { missing } : {}) };\n    });\n    const status = case_results.every((r) => r.passed) ? 'passed' : 'failed';\n    return { status, fixture, case_results };\n}\n", "/** SSE envelopes for web attention streams (registry \u2192 BFF \u2192 browser). */\nfunction isRecord(v) {\n    return typeof v === 'object' && v !== null;\n}\nfunction readSeq(v) {\n    return typeof v === 'number' && Number.isFinite(v) ? v : null;\n}\n/** Parse one SSE `data:` JSON payload; returns null when unknown or malformed. */\nexport function parseAttentionStreamEvent(raw) {\n    let parsed;\n    try {\n        parsed = JSON.parse(raw);\n    }\n    catch {\n        return null;\n    }\n    if (!isRecord(parsed) || typeof parsed.type !== 'string')\n        return null;\n    const seq = readSeq(parsed.seq);\n    if (seq == null)\n        return null;\n    if (parsed.type === 'attention') {\n        const social = parsed.social;\n        const updates = parsed.updates;\n        if (typeof social !== 'number' || typeof updates !== 'number')\n            return null;\n        return { type: 'attention', social, updates, seq };\n    }\n    if (parsed.type === 'social_event') {\n        const kind = parsed.kind;\n        const actor = parsed.actor;\n        const at = parsed.at;\n        if (kind !== 'followed_you' &&\n            kind !== 'subscribed_kit' &&\n            kind !== 'subscribed_author' &&\n            kind !== 'installed_skill') {\n            return null;\n        }\n        if (typeof actor !== 'string' || typeof at !== 'number')\n            return null;\n        return { type: 'social_event', kind, actor, at, seq };\n    }\n    if (parsed.type === 'pending_increased') {\n        return { type: 'pending_increased', seq };\n    }\n    return null;\n}\n", "/** SSE envelopes for device sync streams (registry -> desktop). */\nfunction isRecord(v) {\n    return typeof v === 'object' && v !== null;\n}\nfunction readSeq(v) {\n    return typeof v === 'number' && Number.isFinite(v) ? v : null;\n}\n/** Parse one SSE `data:` JSON payload; returns null when unknown or malformed. */\nexport function parseDeviceSyncStreamEvent(raw) {\n    let parsed;\n    try {\n        parsed = JSON.parse(raw);\n    }\n    catch {\n        return null;\n    }\n    if (!isRecord(parsed) || parsed.type !== 'sync_required')\n        return null;\n    const seq = readSeq(parsed.seq);\n    if (seq == null)\n        return null;\n    return { type: 'sync_required', seq };\n}\n", "/**\n * Deterministic skill/kit cover art \u2014 the single source of truth shared by web\n * and desktop. Framework-agnostic: returns an SVG *string* so each surface can\n * inline it (web via dangerouslySetInnerHTML, desktop via innerHTML). Change the\n * engine here and every surface updates.\n *\n * Ported from the web's GridCover: a single skill is a flat category-tinted\n * ground + one section shape (Code \u25A1 / Grow \u25B3 / Create \u25CB); a kit is four\n * alternating horizontal gradient bands (dominant-category hue) under a grid of\n * per-skill section marks. Category \u2192 color/shape; seed \u2192 placement. (Paper grain\n * is a web-only overlay and is intentionally omitted here \u2014 it needs an image\n * asset and is invisible at list sizes.)\n */\n// key \u2192 { label (drives the alphabetical band sweep), section }. Kept in sync\n// with packages/web/src/lib/categories.ts (which layers browse metadata on top).\nconst CATEGORY_DEFS = [\n    { key: 'frontend', label: 'Frontend', section: 'Code' },\n    { key: 'mobile', label: 'Mobile', section: 'Code' },\n    { key: 'backend', label: 'Backend', section: 'Code' },\n    { key: 'database', label: 'Data', section: 'Code' },\n    { key: 'devops', label: 'DevOps', section: 'Code' },\n    { key: 'security', label: 'Security', section: 'Code' },\n    { key: 'quality', label: 'Code Review', section: 'Code' },\n    { key: 'agents', label: 'AI', section: 'Code' },\n    { key: 'design', label: 'Design', section: 'Create' },\n    { key: 'product', label: 'Strategy', section: 'Grow' },\n    { key: 'research', label: 'Research', section: 'Grow' },\n    { key: 'writing', label: 'Writing', section: 'Create' },\n    { key: 'marketing', label: 'Marketing', section: 'Grow' },\n    { key: 'sales', label: 'Sales', section: 'Grow' },\n    { key: 'finance', label: 'Finance', section: 'Grow' },\n    { key: 'productivity', label: 'Productivity', section: 'Grow' },\n    { key: 'media', label: 'Media', section: 'Create' },\n];\nconst CATEGORY_SECTIONS = ['Code', 'Create', 'Grow'];\n// Each section owns a hue/sat/light band; its categories sweep it alphabetically.\nconst SECTION_BANDS = {\n    Code: { hue: [195, 182], sat: [55, 42], light: [34, 60] },\n    Grow: { hue: [138, 108], sat: [34, 44], light: [32, 54] },\n    Create: { hue: [18, -10], sat: [54, 50], light: [56, 64] },\n};\nconst lerp = (a, b, t) => a + (b - a) * t;\nexport const CATEGORY_SWATCHES = (() => {\n    const out = {};\n    for (const section of CATEGORY_SECTIONS) {\n        const members = CATEGORY_DEFS.filter((c) => c.section === section).sort((a, b) => a.label.localeCompare(b.label));\n        const band = SECTION_BANDS[section];\n        members.forEach((c, i) => {\n            const t = members.length > 1 ? i / (members.length - 1) : 0;\n            out[c.key] = {\n                section,\n                hue: Math.round(((lerp(band.hue[0], band.hue[1], t) % 360) + 360) % 360),\n                sat: Math.round(lerp(band.sat[0], band.sat[1], t)),\n                light: Math.round(lerp(band.light[0], band.light[1], t)),\n            };\n        });\n    }\n    return out;\n})();\nconst KEYS = Object.keys(CATEGORY_SWATCHES);\n// FNV-1a \u2014 matches the web engine so a seed maps to the same fallback category.\nexport function fnv(s) {\n    let h = 2166136261;\n    for (let i = 0; i < s.length; i++)\n        h = ((h ^ s.charCodeAt(i)) * 16777619) >>> 0;\n    return h >>> 0;\n}\n/** The deterministic fallback category for a seed (when real categories are absent).\n *  Callers without category data (e.g. desktop kit covers, which need one per member\n *  to render the multi-band form) can build `members.map(seedCategory)`. */\nexport function seedCategory(seed) {\n    return KEYS[fnv(seed) % KEYS.length];\n}\n/** Valid categories, with a deterministic seed fallback so a cover is never blank. */\nfunction resolveCats(categories, seed) {\n    const valid = categories.filter((c) => !!c && c in CATEGORY_SWATCHES);\n    if (valid.length > 0)\n        return valid;\n    return [KEYS[fnv(seed) % KEYS.length]];\n}\n/** The neutral hue for a genuinely-uncategorized single skill \u2014 a warm gray that\n *  reads as \"no category\" rather than borrowing a real category's tint. Shared so\n *  the hero wash behind the cover can match it. */\nexport const UNCATEGORIZED_HUE = 40;\n/** True for a single skill with no valid category \u2014 the case that renders a\n *  neutral ground-only cover instead of a seed-fabricated category shape. A kit\n *  (more than one member) keeps its decorative seed fallback, so this is false\n *  for multi-member input. */\nexport function isUncategorizedSingle(categories) {\n    if (categories.length > 1)\n        return false;\n    return !categories.some((c) => !!c && c in CATEGORY_SWATCHES);\n}\n/** The inner mark for a skill \u2014 SHAPE encodes the section, COLOR the category. */\nfunction sectionMark(section, mx, my, r, col) {\n    if (section === 'Create')\n        return `<circle cx=\"${mx}\" cy=\"${my}\" r=\"${r}\" fill=\"${col}\"/>`;\n    if (section === 'Grow') {\n        const p = `${mx},${(my - r * 1.08).toFixed(1)} ${(mx + r).toFixed(1)},${(my + r * 0.82).toFixed(1)} ${(mx - r).toFixed(1)},${(my + r * 0.82).toFixed(1)}`;\n        return `<polygon points=\"${p}\" fill=\"${col}\" stroke=\"${col}\" stroke-width=\"${(r * 0.36).toFixed(1)}\" stroke-linejoin=\"round\"/>`;\n    }\n    const s = r * 0.92;\n    return `<rect x=\"${(mx - s).toFixed(1)}\" y=\"${(my - s).toFixed(1)}\" width=\"${(s * 2).toFixed(1)}\" height=\"${(s * 2).toFixed(1)}\" rx=\"${(s * 0.2).toFixed(1)}\" fill=\"${col}\"/>`;\n}\n/** Muted mark for uncategorized singles at list sizes \u2014 not a category shape.\n *  A dashed triangle, not a circle: a dashed circle reads as an unchecked\n *  radio/checkbox next to real controls, while a dashed shape from the cover\n *  vocabulary reads as \"cover not decided yet\". */\nfunction uncategorizedListMark(dark) {\n    const stroke = dark ? `hsl(${UNCATEGORIZED_HUE} 8% 62%)` : `hsl(${UNCATEGORIZED_HUE} 12% 45%)`;\n    return `<path d=\"M60 40 L81.5 77 L38.5 77 Z\" fill=\"none\" stroke=\"${stroke}\" stroke-width=\"3.5\" stroke-dasharray=\"7 5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>`;\n}\n/**\n * The cover SVG for a skill or kit. `categories` is a single [key] for a skill\n * or the members' keys for a kit; pass `[]` to let the seed pick a fallback.\n */\nexport function coverSvg(seed, categories = [], opts = {}) {\n    const dark = opts.dark ?? false;\n    const cats = resolveCats(categories, seed);\n    const uid = fnv(seed);\n    const rnd = (i) => {\n        const x = Math.sin(((uid % 1000) + 1) * (i + 7) * 12.9898) * 43758.5453;\n        return x - Math.floor(x);\n    };\n    const open = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100%\" height=\"100%\" viewBox=\"0 0 120 120\" preserveAspectRatio=\"xMidYMid slice\" aria-hidden=\"true\">`;\n    // A genuinely-uncategorized single skill: neutral warm-gray ground, NO shape.\n    // A section shape would encode a category the skill doesn't have.\n    if (isUncategorizedSingle(categories)) {\n        const ground = dark ? `hsl(${UNCATEGORIZED_HUE} 6% 24%)` : `hsl(${UNCATEGORIZED_HUE} 8% 88%)`;\n        const mark = opts.listMark ? uncategorizedListMark(dark) : '';\n        return `${open}<rect x=\"-1\" y=\"-1\" width=\"122\" height=\"122\" fill=\"${ground}\"/>${mark}</svg>`;\n    }\n    // A single skill: flat tinted ground + one bold section shape.\n    if (cats.length === 1) {\n        const c = CATEGORY_SWATCHES[cats[0]];\n        const ground = dark ? `hsl(${c.hue} 26% 24%)` : `hsl(${c.hue} 30% 88%)`;\n        const mark = opts.groundOnly\n            ? ''\n            : sectionMark(c.section, 60, 60, 30, `hsl(${c.hue} ${c.sat}% ${dark ? 62 : 50}%)`);\n        return `${open}<rect x=\"-1\" y=\"-1\" width=\"122\" height=\"122\" fill=\"${ground}\"/>${mark}</svg>`;\n    }\n    // A kit: four alternating gradient bands in the dominant hue + a grid of marks.\n    const counts = new Map();\n    for (const k of cats)\n        counts.set(k, (counts.get(k) ?? 0) + 1);\n    const buckets = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));\n    const dom = CATEGORY_SWATCHES[buckets[0]?.[0] ?? cats[0]];\n    const hue = Math.round((dom.hue + (rnd(999) - 0.5) * 34 + 720) % 360);\n    const deepC = dark ? `hsl(${hue} 30% 44%)` : `hsl(${hue} 34% 62%)`;\n    const liteC = dark ? `hsl(${hue} 18% 26%)` : `hsl(${hue} 18% 87%)`;\n    const cell = 30;\n    const rowsN = opts.compact ? 3 : 4;\n    const cellH = 120 / rowsN;\n    const id = `gc-${uid.toString(36)}`;\n    // variety-first mark selection (round-robin across categories), up to 12\n    const work = buckets.map(([k, n]) => ({ k, n }));\n    const marks = [];\n    let progressed = true;\n    while (marks.length < 12 && progressed) {\n        progressed = false;\n        for (const b of work) {\n            if (b.n <= 0)\n                continue;\n            marks.push(b.k);\n            b.n--;\n            progressed = true;\n            if (marks.length >= 12)\n                break;\n        }\n    }\n    const defs = Array.from({ length: rowsN }, (_, b) => b)\n        .map((b) => {\n        const flip = b % 2 === 1;\n        const a = flip ? liteC : deepC;\n        const z = flip ? deepC : liteC;\n        return `<linearGradient id=\"${id}-r${b}\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\"><stop offset=\"0%\" stop-color=\"${a}\"/><stop offset=\"100%\" stop-color=\"${z}\"/></linearGradient>`;\n    })\n        .join('');\n    const bands = Array.from({ length: rowsN }, (_, b) => b)\n        .map((b) => `<rect x=\"0\" y=\"${b * cellH}\" width=\"120\" height=\"${cellH + 0.5}\" fill=\"url(#${id}-r${b})\"/>`)\n        .join('');\n    let placements = '';\n    if (!opts.groundOnly) {\n        const used = new Set();\n        const cellOf = (salt) => {\n            for (let t = 0; t < 24; t++) {\n                const c = Math.floor(rnd(salt + t * 2) * 4);\n                const r = Math.floor(rnd(salt + t * 2 + 40) * 3);\n                if (!used.has(`${c},${r}`)) {\n                    used.add(`${c},${r}`);\n                    return [c, r];\n                }\n            }\n            for (let r = 0; r < 3; r++)\n                for (let c = 0; c < 4; c++)\n                    if (!used.has(`${c},${r}`)) {\n                        used.add(`${c},${r}`);\n                        return [c, r];\n                    }\n            return [0, 0];\n        };\n        placements = marks\n            .map((k, i) => {\n            const [c, r] = cellOf(i * 7 + 5);\n            const sc = CATEGORY_SWATCHES[k];\n            const col = `hsl(${sc.hue} ${Math.round(sc.sat * 0.95)}% ${dark ? 64 : 44}%)`;\n            return sectionMark(sc.section, c * cell + cell / 2, r * cellH + cellH / 2, Math.min(cell, cellH) * 0.36, col);\n        })\n            .join('');\n    }\n    return `${open}<defs>${defs}</defs>${bands}${placements}</svg>`;\n}\n", "export { bundleToZip, bundlesToZip } from './zip.js';\nexport { BundleError, CONTENT_HASH_PREFIX, MAX_BUNDLE_BYTES, MAX_INSTRUCTION_BYTES, SKILL_ENTRYPOINT, assertSafeBundlePath, bundlePathError, canonicalContentHash, isSkilletBackupPath, skillContentHash, SKILLET_BACKUP_SUFFIX, stripSkilletBackupPaths, computeInstructionClosure, decodeBundle, encodeBundle, extractFrontmatterYaml, globPatternToRegExp, instructionClosureBytes, isInstructionPath, parseRequiredReadingFromYaml, validateBundle, } from './bundle.js';\nexport { INLINE_IMAGE_CONTENT_TYPES, MAX_INLINE_IMAGE_BYTES, inlineImageExtension, isInlineImagePath, } from './inline-images.js';\nexport { REGISTRY_VERSION, REGISTRY_VERSION_PREFIX, REGISTRY_API_BASE, SYNC_INTERVAL_SECONDS_DEFAULT, } from './constants.js';\nexport { ARTIFACT_SCHEMA_VERSION, isSupportedArtifactSchemaVersion, resolveArtifactSchemaVersion, } from './artifact-schema.js';\nexport { isExcludedDiscoveryPath, isCoupledSkillMarkdown, isMoreCanonicalSkillDir, classifyImport, dedupeMirrorsBy, } from './import-classify.js';\nexport { RequiresError, MAX_REQUIRES_ENTRIES, MAX_REQUIRES_REASON_CHARS, isValidRequiresVersion, validateRequires, } from './requires.js';\nexport { DELEGATION_CERT_VERSION, DELEGATION_CERT_TYP, DELEGATION_REVOCATION_TYP, MAX_DELEGATION_TTL_SEC, DEFAULT_DELEGATION_TTL_SEC, DELEGABLE_SCOPES, canonicalJson, delegationCertHash, revocationHash, validateDelegationCert, } from './delegation.js';\nexport { BUNDLE_SIG_TYP, bundleSignatureBytes, isBundleSignatureV2, } from './bundle-signature.js';\nexport { KEY_BIND_POP_PREFIX, keyBindPopMessage, keyBindPopMessageBytes, } from './key-bind.js';\nexport { RESERVED_HANDLES, isReservedHandle, BRAND_PREFIXES, RESERVED_LEGACY_CODENAME_HANDLE } from './reserved-handles.js';\nexport { slugify } from './slugify.js';\nexport { RESERVED_SKILL_SLUGS, isReservedSkillSlug, isValidSkillSlug, SKILL_SLUG_RE } from './reserved-skill-slugs.js';\nexport { TriggersError, MAX_TRIGGERS, MAX_TRIGGER_CHARS, validateTriggers } from './triggers.js';\nexport { PERMISSIONS, FLAGS, SCAN_VOCABULARY, PERMISSION_ORDER, vocabularyEntry, } from './scan-vocabulary.js';\nexport { EvalError, EVAL_SMOKE_PATH, EVAL_FIXTURE_VERSION, parseEvalFixture, readEvalFixtureFromBundle, runBasicEval, } from './eval.js';\nexport { parseAttentionStreamEvent } from './attention-events.js';\nexport { parseDeviceSyncStreamEvent } from './device-sync-events.js';\nexport * from './covers.js';\n", "import { readdir, readFile, lstat } from 'node:fs/promises';\nimport { join, relative, sep } from 'node:path';\nimport { BundleError, type DecodedBundle, validateBundle } from '@skillet/protocol';\n\n/**\n * Read a skill bundle from a directory on disk into a path\u2192bytes map.\n *\n * - POSIX-relative paths only (we re-join with `/`); preserves the full subtree.\n * - Rejects symlinks anywhere in the tree (`unsafe_path` per \u00A72.1) before any\n *   bytes are read; a symlink in `references/` could otherwise point at\n *   `~/.ssh/id_ed25519` and pull a key into the bundle.\n * - Validates the resulting bundle (`SKILL.md` at root, size caps, safe paths).\n */\nexport async function readBundleFromDir(\n  skillDir: string,\n  opts?: { includeSkilletBackups?: boolean },\n): Promise<DecodedBundle> {\n  const bundle: DecodedBundle = new Map();\n  await walk(skillDir, skillDir, bundle, opts?.includeSkilletBackups === true);\n  validateBundle(bundle);\n  return bundle;\n}\n\nasync function walk(\n  root: string,\n  dir: string,\n  out: DecodedBundle,\n  includeSkilletBackups: boolean,\n): Promise<void> {\n  const entries = await readdir(dir, { withFileTypes: true });\n  for (const entry of entries) {\n    const absPath = join(dir, entry.name);\n    // withFileTypes returns the *type from readdir's dirent*, which on most\n    // platforms is the lstat type \u2014 but we re-lstat to be safe and consistent.\n    const st = await lstat(absPath);\n    if (st.isSymbolicLink()) {\n      throw new BundleError(\n        'unsafe_path',\n        `Symlink in bundle is rejected (\u00A72.1): ${relative(root, absPath)}`,\n      );\n    }\n    if (st.isDirectory()) {\n      await walk(root, absPath, out, includeSkilletBackups);\n      continue;\n    }\n    if (!st.isFile()) {\n      // sockets, fifos, devices \u2014 none of these belong in a skill bundle.\n      throw new BundleError(\n        'unsafe_path',\n        `Non-regular file in bundle is rejected: ${relative(root, absPath)}`,\n      );\n    }\n    if (!includeSkilletBackups && entry.name.endsWith('.skillet-backup')) {\n      continue;\n    }\n    const rel = relative(root, absPath);\n    // Convert host separator to POSIX. On Windows this turns \"agents\\\\r.md\" into\n    // \"agents/r.md\" so the canonical hash (which hashes path bytes) is stable.\n    const posix = sep === '/' ? rel : rel.split(sep).join('/');\n    const bytes = await readFile(absPath);\n    out.set(posix, bytes);\n  }\n}\n", "/**\n * Skill identity \u2014 the single source of truth for the three string forms a\n * skill's identity takes, every conversion between them, and the branded\n * `SkillId` type that guards the registry boundary.\n *\n * A skill has ONE canonical form per MEDIUM, and each form exists because its\n * medium forces it:\n *\n *   \u2022 **wireRef**  `@owner/slug`   \u2014 human / CLI / display, and core's local\n *     kit-state keys. Leading `@`, `/` separator. This is the npm `@scope/pkg`\n *     and GitHub `owner/repo` convention; it's what a person types and reads.\n *\n *   \u2022 **skillId**  `owner:slug`    \u2014 the registry DB primary key (`skills.id`),\n *     every Set/Map key, WHERE param, and all identity comparison. No `@`, `:`\n *     separator, so it stays URL- and path-safe (safe to interpolate into a\n *     route or an id column without escaping).\n *\n *   \u2022 **slugDir**  `owner--slug`   \u2014 the on-disk materialized directory name\n *     (`_local--slug` when unowned). `--` separator because a single directory\n *     name may not contain `/`; the filesystem forbids it.\n *\n * The bug class this module kills is a cross-form comparison that COMPILES \u2014\n * e.g. a wireRef (`@owner/slug`) looked up in a Set keyed on skillId\n * (`owner:slug`), which silently misses instead of erroring. Route every\n * conversion through here and the forms can't drift.\n *\n * BRANDED TYPE \u2014 NEW CONVENTION. `SkillId` is a branded string\n * (`string & { readonly __brand: 'SkillId' }`). The repo has no prior branded\n * types; this module introduces the pattern. A plain `string` is NOT assignable\n * to a `SkillId` \u2014 the ONLY way to mint one is {@link toSkillId} (the sole place\n * the brand cast lives). So a raw wireRef where a `SkillId` is expected is a\n * COMPILE error, not an empty Set at runtime.\n *\n * PURE / ZERO IMPORTS. Like `./covers` and `./untrusted-href`, this module has\n * no runtime imports (no `node:*`) and is exposed only via the\n * `@skillet/protocol/skill-id` SUBPATH \u2014 never the barrel (`./index`), which\n * drags `node:crypto` and blanks a browser page. Browser and webview callers\n * import the subpath and stay off the crypto-laden barrel.\n *\n * Grammar is aligned to what the registry ACTUALLY STORES, not a stricter\n * ideal \u2014 the canonical parser must accept exactly what the system persists or\n * it throws on real DB rows. Handles match the registry's claim-gate\n * `HANDLE_RE` (`packages/registry/src/routes/auth.ts` /\n * `auth/identities.ts`): `/^[a-z0-9][a-z0-9-]{0,38}$/` \u2014 lowercase URL-safe\n * `[a-z0-9-]`, 1-39 chars, no LEADING hyphen but a TRAILING hyphen IS legal\n * (e.g. `alice-` is a claimable handle \u2192 a stored `alice-:tool` skill id).\n * Slugs match the registry's publish-time validator `SKILL_SLUG_RE`\n * (`packages/protocol/src/reserved-skill-slugs.ts`):\n * `/^[a-z0-9][a-z0-9-]{0,62}$/` \u2014 same class, 1-63 chars. Anything outside the\n * allowlist (`.`, `/`, `\\`, `%`, `:`, NUL, whitespace, `..`) is rejected \u2014 the\n * grammar doubles as a path-traversal gate before an identity is ever\n * interpolated into a URL or a directory path.\n *\n * The slugDir DECODER ({@link fromSlugDir}) is deliberately looser than this\n * grammar: it decodes what `core/bundle/write.ts` `bundleSlugDir` WROTE, which\n * emits `owner--slug` / `_local--slug` without grammar-validating the slug. So\n * the decoder accepts any non-empty, non-traversal, `/`- and NUL-free part \u2014\n * you must be able to read back every dir the encoder could have written.\n */\n/**\n * Owner handle: MUST equal the registry's claim-gate `HANDLE_RE`\n * (`packages/registry/src/routes/auth.ts` and `auth/identities.ts`), which is\n * the gate that decides what handle can be claimed and thus what `owner` can\n * appear in a stored `skills.id`. Lowercase alnum + hyphen, 1-39, must START\n * with alnum; a TRAILING hyphen is legal (`alice-`). Being stricter than this\n * would throw on real, claimable identities.\n */\nconst AUTHOR_RE = /^[a-z0-9][a-z0-9-]{0,38}$/;\n/**\n * Slug: MUST equal the registry's publish-time `SKILL_SLUG_RE`\n * (`packages/protocol/src/reserved-skill-slugs.ts`). Lowercase alnum + hyphen,\n * 1-63, must start alnum.\n */\nconst SLUG_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;\n/**\n * A slugDir part (owner or slug) is DECODABLE iff it is something\n * `bundleSlugDir` could have written to disk: non-empty, no path separator, no\n * NUL, and not a `.`/`..` traversal segment. Looser than {@link AUTHOR_RE} /\n * {@link SLUG_RE} on purpose \u2014 the encoder does not grammar-validate the slug,\n * so the decoder must not reject a dir it could have produced. Still a hard\n * traversal/NUL gate before the name is joined into a filesystem path.\n */\nfunction isDecodableSlugPart(part) {\n    return (part.length > 0 &&\n        part !== '.' &&\n        part !== '..' &&\n        !part.includes('/') &&\n        !part.includes('\\\\') &&\n        !part.includes('\\0'));\n}\n/**\n * Thrown by {@link parseRef} (and the converters that build on it) when the\n * input is not a valid identity in any of the three accepted input forms.\n *\n * parseRef THROWS rather than returning null \u2014 matching the stricter existing\n * parser (`core/registry/identifier.ts`, which throws `SkillRefError`) so the\n * delegation in later units is behaviour-preserving. {@link fromSlugDir}, by\n * contrast, returns `null` (matching `parseSkilletSlugDir`) because \"is this a\n * skillet dir?\" is a test, not a parse.\n */\nexport class SkillIdError extends Error {\n    code;\n    constructor(code, message) {\n        super(message);\n        this.code = code;\n        this.name = 'SkillIdError';\n    }\n}\n/**\n * Parse any of the three input forms \u2014 `@owner/slug` (wireRef), `owner/slug`\n * (bare wire), or `owner:slug` (skillId) \u2014 into validated `{ owner, slug }`.\n *\n * Tolerant of the INPUT delimiter (like the registry's `refToAuthorSlug`), but\n * STRICT on the resulting owner/slug grammar (like `identifier.ts`). Strips a\n * single leading `@`, then splits on whichever of `/` or `:` appears first.\n * Throws {@link SkillIdError} on anything malformed: empty owner/slug, an\n * out-of-class character, `..`, or no delimiter at all. The validated parts are\n * safe to interpolate verbatim into a URL or a path.\n */\nexport function parseRef(input) {\n    if (typeof input !== 'string' || input.length === 0) {\n        throw new SkillIdError('invalid_ref', 'Skill ref is empty');\n    }\n    // Reject whitespace / control chars up front for a clear diagnostic.\n    if (/[\\x00-\\x20\\x7f]/.test(input)) {\n        throw new SkillIdError('invalid_ref', `Skill ref ${JSON.stringify(input)} contains whitespace or control characters`);\n    }\n    const body = input.startsWith('@') ? input.slice(1) : input;\n    // Split on the first delimiter, whichever of `/` or `:` comes first.\n    const slashIdx = body.indexOf('/');\n    const colonIdx = body.indexOf(':');\n    let idx;\n    if (slashIdx < 0)\n        idx = colonIdx;\n    else if (colonIdx < 0)\n        idx = slashIdx;\n    else\n        idx = Math.min(slashIdx, colonIdx);\n    if (idx < 0) {\n        throw new SkillIdError('invalid_ref', `Skill ref ${JSON.stringify(input)} must look like \"@owner/slug\", \"owner/slug\", or \"owner:slug\"`);\n    }\n    const owner = body.slice(0, idx);\n    const slug = body.slice(idx + 1);\n    if (!AUTHOR_RE.test(owner)) {\n        throw new SkillIdError('invalid_owner', `Owner ${JSON.stringify(owner)} must be 1-39 lowercase alphanumerics or hyphens, starting with an alphanumeric`);\n    }\n    if (!SLUG_RE.test(slug)) {\n        throw new SkillIdError('invalid_slug', `Slug ${JSON.stringify(slug)} must be 1-63 lowercase alphanumerics or hyphens`);\n    }\n    return { owner, slug };\n}\n/**\n * Canonicalize any input form to a branded `SkillId` (`owner:slug`).\n *\n * This is the ONLY place a plain string becomes a `SkillId` \u2014 the brand cast\n * lives here. Every registry key, Set/Map key, and WHERE param that holds an\n * identity should be produced through this function so a raw wire ref can never\n * reach it uncanonicalized.\n */\nexport function toSkillId(input) {\n    const { owner, slug } = parseRef(input);\n    return `${owner}:${slug}`;\n}\n/**\n * Non-throwing {@link toSkillId} for UNTRUSTED boundaries: returns `null`\n * instead of throwing on a malformed input.\n *\n * Use this to canonicalize external input that reaches a request boundary \u2014 a\n * registry route param, a web `my-kits` id from a URL \u2014 where a throw would\n * become a 500 or crash the render. Trusted/internal callers should use the\n * throwing {@link toSkillId} so a programming error surfaces loudly.\n */\nexport function tryToSkillId(input) {\n    try {\n        return toSkillId(input);\n    }\n    catch {\n        return null;\n    }\n}\n/** Canonicalize any input form to the wireRef (`@owner/slug`) for CLI/display. */\nexport function toWireRef(input) {\n    const { owner, slug } = parseRef(input);\n    return `@${owner}/${slug}`;\n}\n/**\n * Encode an identity to its on-disk slugDir (`owner--slug`).\n *\n * The `@` is stripped (parseRef already dropped it), so the dir is always the\n * clean `owner--slug` form. Unowned skills use `_local--slug`; since none of the\n * input forms can express \"unowned\" (every wireRef/skillId carries an owner),\n * the `_local--` form is produced by {@link toSlugDirParts} / decoded by\n * {@link fromSlugDir} rather than minted from a string here.\n */\nexport function toSlugDir(input) {\n    const { owner, slug } = parseRef(input);\n    return `${owner}--${slug}`;\n}\n/**\n * Encode `{ owner, slug }` to a slugDir, matching `bundleSlugDir`: an unowned\n * skill (null/empty owner) becomes `_local--slug`.\n */\nexport function toSlugDirParts(owner, slug) {\n    if (owner && owner.length > 0) {\n        const clean = owner.startsWith('@') ? owner.slice(1) : owner;\n        if (!AUTHOR_RE.test(clean)) {\n            throw new SkillIdError('invalid_owner', `unsafe owner for slug dir: ${JSON.stringify(owner)}`);\n        }\n        if (!SLUG_RE.test(slug)) {\n            throw new SkillIdError('invalid_slug', `unsafe slug for slug dir: ${JSON.stringify(slug)}`);\n        }\n        return `${clean}--${slug}`;\n    }\n    if (!SLUG_RE.test(slug)) {\n        throw new SkillIdError('invalid_slug', `unsafe slug for slug dir: ${JSON.stringify(slug)}`);\n    }\n    return `_local--${slug}`;\n}\n/**\n * Decode a slugDir back to `{ owner, slug }`, or `null` if `name` is not a\n * Skillet materialized dir. Replicates `core/bundle/write.ts`\n * `parseSkilletSlugDir` exactly:\n *\n *   \u2022 the reserved `skillet` dir \u2192 `{ owner: 'skillet', slug: 'route' }`,\n *   \u2022 `_local--slug`  \u2192 `{ owner: null, slug }` (unowned),\n *   \u2022 `@owner--slug`  \u2192 strips the leading `@`,\n *   \u2022 `owner--slug`   \u2192 `{ owner, slug }`.\n *\n * TOLERANT on decode by design: it decodes what `bundleSlugDir` WROTE, and that\n * encoder emits `owner--slug` / `_local--slug` WITHOUT grammar-validating the\n * slug \u2014 so an unpublished `_local--foo_bar` (underscore) or any looser slug is\n * a real materialized dir on disk. Validating with the strict AUTHOR_RE /\n * SLUG_RE here would return `null` for a dir the system genuinely wrote, making\n * discovery/restore skip it. Instead each part must only be a\n * {@link isDecodableSlugPart}: non-empty, `/`- and NUL-free, and not a `.`/`..`\n * traversal segment \u2014 so a name like `foo--..` still returns `null`. Never\n * compare the result's dir form against an identity \u2014 decode, then compare the\n * `{ owner, slug }`.\n */\nexport function fromSlugDir(name) {\n    if (typeof name !== 'string' || name.length === 0)\n        return null;\n    if (name === 'skillet')\n        return { owner: 'skillet', slug: 'route' };\n    if (name.startsWith('_local--')) {\n        const slug = name.slice('_local--'.length);\n        return isDecodableSlugPart(slug) ? { owner: null, slug } : null;\n    }\n    const sep = name.indexOf('--');\n    if (sep <= 0)\n        return null;\n    let owner = name.slice(0, sep);\n    const slug = name.slice(sep + 2);\n    if (owner.startsWith('@'))\n        owner = owner.slice(1);\n    if (!isDecodableSlugPart(owner) || !isDecodableSlugPart(slug))\n        return null;\n    return { owner, slug };\n}\n", "import { type FileHandle, open, rename, copyFile, mkdir, access, unlink } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\nasync function exists(p: string): Promise<boolean> {\n  try {\n    await access(p);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nasync function fsyncDirectory(dir: string): Promise<void> {\n  if (process.platform === \"win32\") {\n    return;\n  }\n  const dirFd = await open(dir, \"r\");\n  try {\n    await dirFd.sync();\n  } finally {\n    await dirFd.close();\n  }\n}\n\nexport async function atomicWrite(\n  dest: string,\n  content: string | Buffer,\n  opts: { backup?: boolean; mode?: number; fsync?: boolean } = {}\n): Promise<void> {\n  const dir = dirname(dest);\n  await mkdir(dir, { recursive: true });\n\n  if (opts.backup !== false && (await exists(dest))) {\n    const backupPath = `${dest}.skillet-backup`;\n    await copyFile(dest, backupPath);\n  }\n\n  const tmp = join(dir, `.skillet-tmp-${randomBytes(6).toString(\"hex\")}`);\n  let fd: FileHandle | null = null;\n  try {\n    fd = await open(tmp, \"w\", opts.mode);\n    const buf = typeof content === \"string\" ? Buffer.from(content, \"utf8\") : content;\n    await fd.write(buf);\n    // Durability fsync is on by default; opt out (fsync: false) for soft caches\n    // where the atomic rename is wanted but a per-write disk flush is not.\n    if (opts.fsync !== false) await fd.sync();\n    await fd.close();\n    fd = null;\n    await rename(tmp, dest);\n    if (opts.fsync !== false) await fsyncDirectory(dir);\n  } catch (err) {\n    if (fd !== null) {\n      try { await fd.close(); } catch { /* ignore */ }\n      fd = null;\n    }\n    // Static unlink, not a dynamic import(): bundled sidecars can't resolve a\n    // runtime import of a node builtin, so it would throw and leak the temp file.\n    try {\n      await unlink(tmp);\n    } catch {\n      // best effort\n    }\n    throw err;\n  }\n}\n", "import { resolve, relative, normalize, join, sep, dirname } from \"node:path\";\nimport { realpathSync, readFileSync } from \"node:fs\";\nimport { homedir, platform } from \"node:os\";\nimport type { Adapter } from \"../adapter.js\";\n\n// Module-local env-driven roots \u2014 populated at module load by HERMES_ENV_ROOT,\n// never exported. validateMaterializationPath and validateAdapterRoot check\n// this in addition to MATERIALIZATION_ROOT_ALLOWLIST.\nconst _runtimeRoots = new Set<string>();\n\n/**\n * Resolve an env-driven config root to a validated `<dir>/skills` path,\n * or null if the var is unset/empty. Called once at module load.\n *\n * Guards (all required):\n * 1. realpathSync with ENOENT fallback \u2014 defeats symlink attacks.\n * 2. Segment-level \"..\" rejection \u2014 not a substring check.\n * 3. Throws on bad value; never silently falls back to a default \u2014 a\n *    misconfigured root must be loud, not a silent write to a directory\n *    the harness will never read.\n * 4. Suffix \"/skills\" is hardcoded; only the prefix is env-driven.\n */\nfunction resolveEnvSkillsRoot(envVar: string): string | null {\n  const raw = process.env[envVar];\n  if (!raw || raw.length === 0) return null;\n\n  if (raw.includes(\"\\x00\")) {\n    throw new Error(`${envVar} rejected: null byte in value`);\n  }\n\n  // NFC-normalize like Claude Code's own resolver does, so both sides agree\n  // on the same bytes for accented paths. Harmless for Hermes.\n  const normalized = normalize(raw.normalize(\"NFC\"));\n\n  // Segment-level traversal check \u2014 substring \".includes('..')\" is too broad\n  // and rejects legitimate paths like \"/Users/company..name/hermes\".\n  const segments = normalized.split(sep);\n  if (segments.some((s) => s === \"..\")) {\n    throw new Error(`${envVar} rejected: path traversal in value \"${raw}\"`);\n  }\n\n  const resolved = resolve(normalized);\n\n  // realpathSync to catch symlink-to-/etc attacks. ENOENT is safe (fresh\n  // install): if the path doesn't exist there's no symlink to follow.\n  let canonicalized: string;\n  try {\n    canonicalized = realpathSync(resolved);\n  } catch (e: unknown) {\n    if ((e as NodeJS.ErrnoException).code === \"ENOENT\") {\n      canonicalized = resolved;\n    } else {\n      throw e;\n    }\n  }\n\n  return join(canonicalized, \"skills\");\n}\n\n/**\n * Validated env-override for Hermes. Non-null when HERMES_HOME is set and\n * passes all safety checks; null when unset/empty. Computed once at module\n * load \u2014 never re-read from process.env at runtime.\n *\n * When non-null, the resolved path is added to the module-local _runtimeRoots\n * Set so validateMaterializationPath and validateAdapterRoot accept it.\n */\nexport const HERMES_ENV_ROOT: string | null = (() => {\n  const root = resolveEnvSkillsRoot(\"HERMES_HOME\");\n  if (root !== null) _runtimeRoots.add(resolve(root));\n  return root;\n})();\n\n/**\n * Validated env-override for Claude Code. Claude Code 2.1.206's own config\n * resolver is `process.env.CLAUDE_CONFIG_DIR ?? ~/.claude` (binary-verified)\n * and personal skills live under `<root>/skills` \u2014 so when the var is set,\n * `~/.claude/skills` is a directory Claude Code never reads. Unset/empty\n * falls back to the default (matching the binary's `??`); set-but-invalid\n * throws (same contract as HERMES_HOME).\n */\nexport const CLAUDE_ENV_ROOT: string | null = (() => {\n  const root = resolveEnvSkillsRoot(\"CLAUDE_CONFIG_DIR\");\n  if (root !== null) _runtimeRoots.add(resolve(root));\n  return root;\n})();\n\n/**\n * The Hermes home directory absent any profile: HERMES_HOME when set (its\n * validated parent), else the platform default. Hermes's own Windows fallback\n * when LOCALAPPDATA is unset is `~/AppData/Local/hermes` (hermes_constants),\n * NOT the POSIX dot-dir \u2014 matched here so both sides resolve the same tree.\n */\nexport const HERMES_DEFAULT_HOME: string = (() => {\n  if (HERMES_ENV_ROOT !== null) return dirname(HERMES_ENV_ROOT);\n  if (platform() === \"win32\") {\n    const localAppData = safeSystemEnvDir(\"LOCALAPPDATA\");\n    return localAppData\n      ? join(localAppData, \"hermes\")\n      : join(homedir(), \"AppData\", \"Local\", \"hermes\");\n  }\n  return join(homedir(), \".hermes\");\n})();\n\n// Profile names are a single conservative path segment \u2014 anything else\n// (separators, traversal, dotfiles, whitespace) falls back to the default\n// tree rather than widening the write boundary from file content.\nconst HERMES_PROFILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\n\n/**\n * Hermes per-profile skills root, from the sticky `active_profile` file.\n * Hermes keeps a non-default profile's skills at\n * `<home>/profiles/<name>/skills` and scans ONLY the active tree, so a\n * default-tree materialization is invisible to a profile user. Load-once\n * like every other runtime root; a mid-session profile switch takes effect\n * next process (same contract as HERMES_HOME). Null when no profile is\n * active, the name is `default`, or the name fails validation.\n */\nexport const HERMES_PROFILE_ROOT: string | null = (() => {\n  let name: string;\n  try {\n    name = readFileSync(join(HERMES_DEFAULT_HOME, \"active_profile\"), \"utf8\").trim();\n  } catch {\n    return null;\n  }\n  if (!name || name === \"default\" || name.includes(\"\\x00\")) return null;\n  if (name === \".\" || name === \"..\" || !HERMES_PROFILE_RE.test(name)) return null;\n  const root = join(HERMES_DEFAULT_HOME, \"profiles\", name, \"skills\");\n  _runtimeRoots.add(resolve(root));\n  return root;\n})();\n\n/**\n * Sanitize a SYSTEM-set env dir (LOCALAPPDATA/APPDATA) for allowlist use:\n * same guards as resolveEnvSkillsRoot but skip-quietly on a bad value\n * instead of throwing \u2014 these vars are set by the OS, not by the user for\n * Skillet, so a hostile/broken value should drop the entry (materialization\n * then fails the allowlist loudly) rather than brick every CLI run at load.\n */\nfunction safeSystemEnvDir(envVar: string): string | null {\n  const raw = process.env[envVar];\n  if (!raw || raw.length === 0) return null;\n  if (raw.includes(\"\\x00\")) return null;\n  const normalized = normalize(raw);\n  if (normalized.split(sep).some((s) => s === \"..\")) return null;\n  const resolved = resolve(normalized);\n  try {\n    return realpathSync(resolved);\n  } catch (e: unknown) {\n    return (e as NodeJS.ErrnoException).code === \"ENOENT\" ? resolved : null;\n  }\n}\n\n// Compile-time constant \u2014 NOT user-configurable.\n//\n// Codex moved its skills directory from ~/.codex/skills to ~/.agents/skills in\n// June 2026; we materialize only into the supported path. On native Windows,\n// Hermes resolves to %LOCALAPPDATA%\\hermes\\skills and Devin CLI to\n// %APPDATA%\\devin\\skills \u2014 included so the allowlist matches each adapter's\n// runtime-resolved root on that platform. `~/.codeium/windsurf/skills` is\n// Devin Desktop's (n\u00E9 Windsurf) global Agent Skills dir, stable across the\n// June 2026 rebrand per the desktop FAQ.\nfunction buildAllowlist(): readonly string[] {\n  const home = homedir();\n  const entries: string[] = [\n    join(home, \".claude\", \"skills\"),\n    join(home, \".agents\", \"skills\"),\n    join(home, \".openclaw\", \"skills\"),\n    join(home, \".hermes\", \"skills\"),\n    join(home, \".config\", \"devin\", \"skills\"),\n    join(home, \".codeium\", \"windsurf\", \"skills\"),\n  ];\n\n  if (platform() === \"win32\") {\n    const localAppData = safeSystemEnvDir(\"LOCALAPPDATA\");\n    if (localAppData) entries.push(join(localAppData, \"hermes\", \"skills\"));\n    const appData = safeSystemEnvDir(\"APPDATA\");\n    if (appData) entries.push(join(appData, \"devin\", \"skills\"));\n  }\n\n  return Object.freeze(entries);\n}\n\nexport const MATERIALIZATION_ROOT_ALLOWLIST: readonly string[] = buildAllowlist();\n\n/**\n * Per-runtime allowlist for `kind === \"project\"` adapters. Each entry is a\n * POSIX-relative path under the project cwd; an adapter's `targetDir` MUST\n * match exactly. This is the project equivalent of\n * `MATERIALIZATION_ROOT_ALLOWLIST` and prevents a project adapter from\n * declaring `targetDir: \"..\"` or an absolute path.\n *\n * Compile-time constant \u2014 NOT user-configurable.\n */\nexport const PROJECT_TARGET_ALLOWLIST: readonly string[] = Object.freeze([\n  \".cursor/rules\",\n  \".agents/skills\",\n  \".windsurf/rules\",\n]);\n\nexport function assertSafe(root: string, targetPath: string): void {\n  const resolvedRoot = resolve(root);\n  const resolvedTarget = resolve(root, targetPath);\n  const rel = relative(resolvedRoot, resolvedTarget);\n\n  if (rel.startsWith(\"..\") || resolve(targetPath) === targetPath) {\n    throw new Error(`Path escape rejected: \"${targetPath}\" escapes root \"${root}\"`);\n  }\n}\n\nconst SAFE_SLUG_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;\n\nexport function assertSafeSlug(slug: string): void {\n  if (slug.includes(\"\\0\")) {\n    throw new Error(`Null byte rejected in slug: \"${slug}\"`);\n  }\n  if (!SAFE_SLUG_RE.test(slug)) {\n    throw new Error(`Unsafe skill slug rejected: \"${slug}\"`);\n  }\n  const norm = normalize(slug);\n  if (norm === \".\" || norm === \"..\" || norm.includes(\"..\")) {\n    throw new Error(`Unsafe skill slug rejected: \"${slug}\"`);\n  }\n}\n\nexport function validateMaterializationPath(declaredRoot: string, targetPath: string): void {\n  if (declaredRoot.includes(\"\\x00\") || targetPath.includes(\"\\x00\")) {\n    throw new Error(`Path rejected: null byte in path`);\n  }\n\n  if (targetPath.length === 0) {\n    throw new Error(`Path rejected: empty target path`);\n  }\n\n  const resolvedRoot = resolve(declaredRoot);\n  // Env-driven roots (e.g. HERMES_HOME) are stored post-realpathSync. Callers\n  // may pass the pre-canonical (symlink) path, so check both forms.\n  let canonicalRoot: string;\n  try {\n    canonicalRoot = realpathSync(resolvedRoot);\n  } catch {\n    canonicalRoot = resolvedRoot;\n  }\n  const isAllowed =\n    MATERIALIZATION_ROOT_ALLOWLIST.some((allowed) => resolve(allowed) === resolvedRoot) ||\n    _runtimeRoots.has(resolvedRoot) ||\n    _runtimeRoots.has(canonicalRoot);\n  if (!isAllowed) {\n    throw new Error(`Root rejected: \"${declaredRoot}\" is not in the per-runtime allowlist`);\n  }\n\n  const resolvedTarget = resolve(resolvedRoot, targetPath);\n  const rel = relative(resolvedRoot, resolvedTarget);\n  if (rel.startsWith(\"..\")) {\n    throw new Error(`Path escape rejected: \"${targetPath}\" escapes root \"${declaredRoot}\"`);\n  }\n}\n\n/**\n * Path-escape check only \u2014 does NOT enforce the runtime allowlist.\n *\n * Use this from helpers like `writeBundleToDir` where the caller has already\n * validated the root (either via `validateAdapterRoot` at adapter creation,\n * or `validateMaterializationPath` for the slug directory). Re-running the\n * allowlist check from inside core would break adapter tests that materialize\n * into temp dirs.\n */\nexport function assertNoPathEscape(root: string, targetPath: string): void {\n  if (root.includes(\"\\x00\") || targetPath.includes(\"\\x00\")) {\n    throw new Error(`Path rejected: null byte in path`);\n  }\n  if (targetPath.length === 0) {\n    throw new Error(`Path rejected: empty target path`);\n  }\n  const resolvedRoot = resolve(root);\n  const resolvedTarget = resolve(resolvedRoot, targetPath);\n  const rel = relative(resolvedRoot, resolvedTarget);\n  if (rel.startsWith(\"..\") || resolvedTarget === resolvedRoot) {\n    throw new Error(`Path escape rejected: \"${targetPath}\" escapes root \"${root}\"`);\n  }\n}\n\n/**\n * Validate that a project-scoped adapter's declared `targetDir` is in the\n * project-target allowlist AND that `projectRoot(cwd)` stays inside `cwd`.\n *\n * Project adapters are NOT covered by `MATERIALIZATION_ROOT_ALLOWLIST` \u2014\n * their absolute root varies per project \u2014 so they need their own gate.\n */\nexport function validateProjectAdapterRoot(adapter: Adapter, cwd: string): void {\n  if (adapter.kind !== \"project\") {\n    throw new Error(`Adapter \"${adapter.name}\" is not project-scoped`);\n  }\n  if (!cwd || cwd.length === 0) {\n    throw new Error(`Adapter \"${adapter.name}\" requires a non-empty cwd`);\n  }\n  if (cwd.includes(\"\\x00\") || adapter.targetDir.includes(\"\\x00\")) {\n    throw new Error(`Path rejected: null byte in path`);\n  }\n  if (adapter.targetDir.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]/.test(adapter.targetDir)) {\n    throw new Error(\n      `Adapter \"${adapter.name}\" project targetDir \"${adapter.targetDir}\" must be a relative POSIX path`,\n    );\n  }\n  if (!PROJECT_TARGET_ALLOWLIST.includes(adapter.targetDir)) {\n    throw new Error(\n      `Adapter \"${adapter.name}\" project targetDir \"${adapter.targetDir}\" is not in the project-target allowlist`,\n    );\n  }\n  if (!adapter.projectRoot) {\n    throw new Error(\n      `Adapter \"${adapter.name}\" is project-scoped but does not implement projectRoot(cwd)`,\n    );\n  }\n  const resolvedCwd = resolve(cwd);\n  const resolvedRoot = resolve(adapter.projectRoot(cwd));\n  const rel = relative(resolvedCwd, resolvedRoot);\n  if (rel.startsWith(\"..\") || resolvedRoot === resolvedCwd) {\n    throw new Error(\n      `Adapter \"${adapter.name}\" projectRoot(cwd) \"${resolvedRoot}\" escapes cwd \"${resolvedCwd}\"`,\n    );\n  }\n}\n\nexport function validateAdapterRoot(adapter: Adapter, opts: { cwd?: string } = {}): void {\n  if (adapter.kind === \"project\") {\n    if (!opts.cwd) {\n      throw new Error(\n        `Adapter \"${adapter.name}\" is project-scoped; cwd is required for validateAdapterRoot`,\n      );\n    }\n    validateProjectAdapterRoot(adapter, opts.cwd);\n    return;\n  }\n  const resolvedTarget = resolve(adapter.targetDir);\n  let canonicalTarget: string;\n  try {\n    canonicalTarget = realpathSync(resolvedTarget);\n  } catch {\n    canonicalTarget = resolvedTarget;\n  }\n  const isAllowed =\n    MATERIALIZATION_ROOT_ALLOWLIST.some((allowed) => resolve(allowed) === resolvedTarget) ||\n    _runtimeRoots.has(resolvedTarget) ||\n    _runtimeRoots.has(canonicalTarget);\n  if (!isAllowed) {\n    throw new Error(\n      `Adapter \"${adapter.name}\" targetDir \"${adapter.targetDir}\" is not in the per-runtime allowlist`,\n    );\n  }\n}\n\n/**\n * Resolve the absolute write root for an adapter, regardless of kind.\n *\n * - Global adapters return their static `targetDir`.\n * - Project adapters require `opts.cwd` and dispatch to `projectRoot(cwd)`.\n */\nexport function resolveAdapterRoot(\n  adapter: Adapter,\n  opts: { cwd?: string } = {},\n): string {\n  if (adapter.kind === \"project\") {\n    if (!opts.cwd) {\n      throw new Error(\n        `Adapter \"${adapter.name}\" is project-scoped; cwd is required`,\n      );\n    }\n    if (!adapter.projectRoot) {\n      throw new Error(\n        `Adapter \"${adapter.name}\" is project-scoped but does not implement projectRoot(cwd)`,\n      );\n    }\n    return adapter.projectRoot(opts.cwd);\n  }\n  return adapter.targetDir;\n}\n", "import { readFile } from 'node:fs/promises';\nimport { join, sep } from 'node:path';\nimport type { DecodedBundle } from '@skillet/protocol';\nimport { fromSlugDir } from '@skillet/protocol/skill-id';\nimport { atomicWrite } from '../util/atomic.js';\nimport { assertNoPathEscape } from '../util/pathsafe.js';\n\n/**\n * Atomic write that SKIPS the write when the destination is already byte-identical.\n *\n * A full `skillet sync` re-materializes every skill into every detected adapter on\n * every run. Without this guard an unchanged sync rewrites hundreds of files \u2014 each\n * a backup-copy + temp-write + fsync + rename + dir-fsync \u2014 and takes 10s+. A read\n * is far cheaper than that durable write, so comparing first makes an unchanged sync\n * near-instant. Callers still report the path as \"written\" \u2014 the file IS\n * materialized on disk, it just didn't need rewriting.\n */\nasync function writeFileIfChanged(dest: string, buf: Buffer): Promise<void> {\n  try {\n    if ((await readFile(dest)).equals(buf)) return;\n  } catch {\n    // missing / unreadable \u2192 fall through and write it\n  }\n  // backup: false \u2014 this function is never called over a hand-edited dir.\n  // One layer up, sync detects drift against `entry.hash` and marks the\n  // skill `customized_from`; from then on the skill is never materialized\n  // over \u2014 the edit stays live in the folder forever, and this function is\n  // simply skipped for it. There is no heal. A backup is only ever taken at\n  // reconcile time (Take theirs / Restore original), written to\n  // `~/.skillet/edits` before that action replaces the user's version.\n  await atomicWrite(dest, buf, { backup: false });\n}\n\n/**\n * Materialize a bundle into a directory using the layout `<root>/<owner>--<slug>/<bundle paths>`.\n *\n * Each file is written atomically (temp + rename); no backup files are\n * written here. Hand-edits are preserved by never calling this function\n * over them \u2014 sync marks a drifted skill `customized_from` and leaves it\n * live in place; backups happen only at reconcile time (Take theirs /\n * Restore original), not here. Every target path is validated against the per-runtime root\n * allowlist AND a path-escape check \u2014 the bundle path is POSIX-relative but\n * is joined back into the host directory, so a malicious `references/../../`\n * would otherwise reach outside `targetSlugDir`. The protocol validators on\n * publish should catch this earlier; this is defense in depth.\n *\n * @param adapterRoot The allowlisted runtime root (e.g. `~/.claude/skills`).\n * @param slugDir     The owner-prefixed skill dir name (e.g. `@taylor--festival-ops`).\n * @param bundle      The decoded bundle to write.\n * @returns           The list of written absolute paths, in stable lexicographic order.\n */\nexport async function writeBundleToDir(\n  adapterRoot: string,\n  slugDir: string,\n  bundle: DecodedBundle,\n): Promise<string[]> {\n  const written: string[] = [];\n\n  // Hash paths in a stable order so test assertions are predictable.\n  const paths = [...bundle.keys()].sort();\n\n  for (const bundlePath of paths) {\n    // `slugDir/bundlePath` is the path *relative to the adapter root*.\n    // Defense in depth: even though `assertSafeBundlePath` (via the publish\n    // validator) already rejected `..`, re-check that the joined path can't\n    // escape the allowlisted root. Allowlist enforcement is the adapter's\n    // job (`validateMaterializationPath` on the slug dir before calling us).\n    const rel = `${slugDir}/${bundlePath}`;\n    assertNoPathEscape(adapterRoot, rel);\n    // Translate POSIX path to host separators for the actual write.\n    const hostRel = sep === '/' ? rel : rel.split('/').join(sep);\n    const dest = join(adapterRoot, hostRel);\n    const bytes = bundle.get(bundlePath)!;\n    await writeFileIfChanged(dest, Buffer.from(bytes));\n    written.push(dest);\n  }\n\n  return written;\n}\n\n/**\n * Write a flat map of POSIX-relative paths under `root`.\n *\n * Unlike `writeBundleToDir`, no `<owner>--<slug>` directory prefix is\n * implied \u2014 the adapter chooses the layout. Used by project-scoped\n * adapters (Windsurf) whose runtime native format is a flat set of\n * rule files (e.g. `.windsurf/rules/<slug>.md`).\n *\n * Same atomicity + path-escape guarantees as `writeBundleToDir`. Caller is\n * responsible for validating `root` (e.g. via `validateProjectAdapterRoot`\n * for project adapters).\n */\nexport async function writeFilesToRoot(\n  root: string,\n  files: DecodedBundle | Record<string, Uint8Array>,\n): Promise<string[]> {\n  const written: string[] = [];\n  const entries =\n    files instanceof Map\n      ? [...files.entries()]\n      : Object.entries(files);\n  entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\n  for (const [rel, bytes] of entries) {\n    if (!rel || rel.length === 0) {\n      throw new Error(`Path rejected: empty target path`);\n    }\n    if (rel.includes('\\0')) {\n      throw new Error(`Path rejected: null byte in path`);\n    }\n    assertNoPathEscape(root, rel);\n    const hostRel = sep === '/' ? rel : rel.split('/').join(sep);\n    const dest = join(root, hostRel);\n    await writeFileIfChanged(dest, Buffer.from(bytes));\n    written.push(dest);\n  }\n  return written;\n}\n\n/**\n * The owner-prefixed slug directory for a skill, e.g. `@taylor--festival-ops`.\n *\n * \u00A76.4: \"Bundles write as `<adapter-root>/<owner>--<slug>/<bundle paths>`.\n * The `owner--` prefix prevents cross-author collisions.\"\n *\n * Owner is optional during early v1 \u2014 a slug-only skill (no handle yet) is\n * permitted; we still apply a `_local--` prefix so the unowned namespace can\n * never collide with a real handle.\n */\nexport interface MaterializeDirOptions {\n  dirName?: string;\n}\n\n/**\n * Resolve the on-disk skill directory name for adapter materialization.\n * When `dirName` is set (e.g. bundled `@skillet/route` \u2192 `skillet`), we use it\n * verbatim so runtimes that key slash commands off the folder name expose `/skillet`.\n */\nexport function materializeSlugDir(\n  slug: string,\n  owner?: string | null,\n  opts?: MaterializeDirOptions,\n): string {\n  const dirName = opts?.dirName;\n  if (dirName) {\n    if (!/^[a-z0-9-]{1,63}$/.test(dirName)) {\n      throw new Error(`unsafe materialize dirName: ${JSON.stringify(dirName)}`);\n    }\n    return dirName;\n  }\n  return bundleSlugDir(slug, owner);\n}\n\nexport function bundleSlugDir(slug: string, owner?: string | null): string {\n  if (owner && owner.length > 0) {\n    // Defense in depth: this dir name feeds filesystem sinks (materialize and\n    // now the prune's rm/rename). Callers pass regex-gated author handles, but\n    // enforce path-safety at the sink so a future caller can't introduce a\n    // traversal via `owner` (e.g. `..` or a path separator).\n    if (!/^@?[a-z0-9-]{1,40}$/.test(owner)) {\n      throw new Error(`unsafe owner for bundle dir: ${JSON.stringify(owner)}`);\n    }\n    // KEPT LOCAL (not delegated to the shared `toSlugDirParts`): this encoder\n    // PRESERVES a leading `@` in the emitted dir name (`@alice--slug`), while\n    // the shared converter strips it (`alice--slug`). Existing on-disk dirs and\n    // the bundle tests depend on the `@` being preserved, so the shared module\n    // cannot express this without a regression. It also intentionally does not\n    // grammar-validate `slug` here (the looser `[a-z0-9-]` owner gate is the\n    // only sink check). See U2 report.\n    return `${owner}--${slug}`;\n  }\n  return `_local--${slug}`;\n}\n\n/**\n * True when `name` is a Skillet materialized skill directory (\u00A76.4), e.g.\n * `thiago--skillet-sync`, `@thiago--skillet-sync`, or `_local--my-skill`.\n *\n * Delegates the decode to the shared `fromSlugDir` (single source of truth):\n * a name is a Skillet dir iff it decodes to an `{ owner, slug }`.\n */\nexport function isSkilletSlugDirName(name: string): boolean {\n  return fromSlugDir(name) !== null;\n}\n\n/**\n * Parse a Skillet slug dir back into owner (no `@`) + bare slug; null if not\n * Skillet layout. Delegates to the shared `fromSlugDir` \u2014 same `skillet`\u2192route\n * mapping, `_local--` unowned handling, and leading-`@` strip.\n */\nexport function parseSkilletSlugDir(\n  name: string,\n): { owner: string | null; slug: string } | null {\n  return fromSlugDir(name);\n}\n", "var toString = Object.prototype.toString;\n\nmodule.exports = function kindOf(val) {\n  if (val === void 0) return 'undefined';\n  if (val === null) return 'null';\n\n  var type = typeof val;\n  if (type === 'boolean') return 'boolean';\n  if (type === 'string') return 'string';\n  if (type === 'number') return 'number';\n  if (type === 'symbol') return 'symbol';\n  if (type === 'function') {\n    return isGeneratorFn(val) ? 'generatorfunction' : 'function';\n  }\n\n  if (isArray(val)) return 'array';\n  if (isBuffer(val)) return 'buffer';\n  if (isArguments(val)) return 'arguments';\n  if (isDate(val)) return 'date';\n  if (isError(val)) return 'error';\n  if (isRegexp(val)) return 'regexp';\n\n  switch (ctorName(val)) {\n    case 'Symbol': return 'symbol';\n    case 'Promise': return 'promise';\n\n    // Set, Map, WeakSet, WeakMap\n    case 'WeakMap': return 'weakmap';\n    case 'WeakSet': return 'weakset';\n    case 'Map': return 'map';\n    case 'Set': return 'set';\n\n    // 8-bit typed arrays\n    case 'Int8Array': return 'int8array';\n    case 'Uint8Array': return 'uint8array';\n    case 'Uint8ClampedArray': return 'uint8clampedarray';\n\n    // 16-bit typed arrays\n    case 'Int16Array': return 'int16array';\n    case 'Uint16Array': return 'uint16array';\n\n    // 32-bit typed arrays\n    case 'Int32Array': return 'int32array';\n    case 'Uint32Array': return 'uint32array';\n    case 'Float32Array': return 'float32array';\n    case 'Float64Array': return 'float64array';\n  }\n\n  if (isGeneratorObj(val)) {\n    return 'generator';\n  }\n\n  // Non-plain objects\n  type = toString.call(val);\n  switch (type) {\n    case '[object Object]': return 'object';\n    // iterators\n    case '[object Map Iterator]': return 'mapiterator';\n    case '[object Set Iterator]': return 'setiterator';\n    case '[object String Iterator]': return 'stringiterator';\n    case '[object Array Iterator]': return 'arrayiterator';\n  }\n\n  // other\n  return type.slice(8, -1).toLowerCase().replace(/\\s/g, '');\n};\n\nfunction ctorName(val) {\n  return typeof val.constructor === 'function' ? val.constructor.name : null;\n}\n\nfunction isArray(val) {\n  if (Array.isArray) return Array.isArray(val);\n  return val instanceof Array;\n}\n\nfunction isError(val) {\n  return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');\n}\n\nfunction isDate(val) {\n  if (val instanceof Date) return true;\n  return typeof val.toDateString === 'function'\n    && typeof val.getDate === 'function'\n    && typeof val.setDate === 'function';\n}\n\nfunction isRegexp(val) {\n  if (val instanceof RegExp) return true;\n  return typeof val.flags === 'string'\n    && typeof val.ignoreCase === 'boolean'\n    && typeof val.multiline === 'boolean'\n    && typeof val.global === 'boolean';\n}\n\nfunction isGeneratorFn(name, val) {\n  return ctorName(name) === 'GeneratorFunction';\n}\n\nfunction isGeneratorObj(val) {\n  return typeof val.throw === 'function'\n    && typeof val.return === 'function'\n    && typeof val.next === 'function';\n}\n\nfunction isArguments(val) {\n  try {\n    if (typeof val.length === 'number' && typeof val.callee === 'function') {\n      return true;\n    }\n  } catch (err) {\n    if (err.message.indexOf('callee') !== -1) {\n      return true;\n    }\n  }\n  return false;\n}\n\n/**\n * If you need to support Safari 5-7 (8-10 yr-old browser),\n * take a look at https://github.com/feross/is-buffer\n */\n\nfunction isBuffer(val) {\n  if (val.constructor && typeof val.constructor.isBuffer === 'function') {\n    return val.constructor.isBuffer(val);\n  }\n  return false;\n}\n", "/*!\n * is-extendable <https://github.com/jonschlinkert/is-extendable>\n *\n * Copyright (c) 2015, Jon Schlinkert.\n * Licensed under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function isExtendable(val) {\n  return typeof val !== 'undefined' && val !== null\n    && (typeof val === 'object' || typeof val === 'function');\n};\n", "'use strict';\n\nvar isObject = require('is-extendable');\n\nmodule.exports = function extend(o/*, objects*/) {\n  if (!isObject(o)) { o = {}; }\n\n  var len = arguments.length;\n  for (var i = 1; i < len; i++) {\n    var obj = arguments[i];\n\n    if (isObject(obj)) {\n      assign(o, obj);\n    }\n  }\n  return o;\n};\n\nfunction assign(a, b) {\n  for (var key in b) {\n    if (hasOwn(b, key)) {\n      a[key] = b[key];\n    }\n  }\n}\n\n/**\n * Returns true if the given `key` is an own property of `obj`.\n */\n\nfunction hasOwn(obj, key) {\n  return Object.prototype.hasOwnProperty.call(obj, key);\n}\n", "'use strict';\n\nvar typeOf = require('kind-of');\nvar extend = require('extend-shallow');\n\n/**\n * Parse sections in `input` with the given `options`.\n *\n * ```js\n * var sections = require('{%= name %}');\n * var result = sections(input, options);\n * // { content: 'Content before sections', sections: [] }\n * ```\n * @param {String|Buffer|Object} `input` If input is an object, it's `content` property must be a string or buffer.\n * @param {Object} options\n * @return {Object} Returns an object with a `content` string and an array of `sections` objects.\n * @api public\n */\n\nmodule.exports = function(input, options) {\n  if (typeof options === 'function') {\n    options = { parse: options };\n  }\n\n  var file = toObject(input);\n  var defaults = {section_delimiter: '---', parse: identity};\n  var opts = extend({}, defaults, options);\n  var delim = opts.section_delimiter;\n  var lines = file.content.split(/\\r?\\n/);\n  var sections = null;\n  var section = createSection();\n  var content = [];\n  var stack = [];\n\n  function initSections(val) {\n    file.content = val;\n    sections = [];\n    content = [];\n  }\n\n  function closeSection(val) {\n    if (stack.length) {\n      section.key = getKey(stack[0], delim);\n      section.content = val;\n      opts.parse(section, sections);\n      sections.push(section);\n      section = createSection();\n      content = [];\n      stack = [];\n    }\n  }\n\n  for (var i = 0; i < lines.length; i++) {\n    var line = lines[i];\n    var len = stack.length;\n    var ln = line.trim();\n\n    if (isDelimiter(ln, delim)) {\n      if (ln.length === 3 && i !== 0) {\n        if (len === 0 || len === 2) {\n          content.push(line);\n          continue;\n        }\n        stack.push(ln);\n        section.data = content.join('\\n');\n        content = [];\n        continue;\n      }\n\n      if (sections === null) {\n        initSections(content.join('\\n'));\n      }\n\n      if (len === 2) {\n        closeSection(content.join('\\n'));\n      }\n\n      stack.push(ln);\n      continue;\n    }\n\n    content.push(line);\n  }\n\n  if (sections === null) {\n    initSections(content.join('\\n'));\n  } else {\n    closeSection(content.join('\\n'));\n  }\n\n  file.sections = sections;\n  return file;\n};\n\nfunction isDelimiter(line, delim) {\n  if (line.slice(0, delim.length) !== delim) {\n    return false;\n  }\n  if (line.charAt(delim.length + 1) === delim.slice(-1)) {\n    return false;\n  }\n  return true;\n}\n\nfunction toObject(input) {\n  if (typeOf(input) !== 'object') {\n    input = { content: input };\n  }\n\n  if (typeof input.content !== 'string' && !isBuffer(input.content)) {\n    throw new TypeError('expected a buffer or string');\n  }\n\n  input.content = input.content.toString();\n  input.sections = [];\n  return input;\n}\n\nfunction getKey(val, delim) {\n  return val ? val.slice(delim.length).trim() : '';\n}\n\nfunction createSection() {\n  return { key: '', data: '', content: '' };\n}\n\nfunction identity(val) {\n  return val;\n}\n\nfunction isBuffer(val) {\n  if (val && val.constructor && typeof val.constructor.isBuffer === 'function') {\n    return val.constructor.isBuffer(val);\n  }\n  return false;\n}\n", "'use strict';\n\n\nfunction isNothing(subject) {\n  return (typeof subject === 'undefined') || (subject === null);\n}\n\n\nfunction isObject(subject) {\n  return (typeof subject === 'object') && (subject !== null);\n}\n\n\nfunction toArray(sequence) {\n  if (Array.isArray(sequence)) return sequence;\n  else if (isNothing(sequence)) return [];\n\n  return [ sequence ];\n}\n\n\nfunction extend(target, source) {\n  var index, length, key, sourceKeys;\n\n  if (source) {\n    sourceKeys = Object.keys(source);\n\n    for (index = 0, length = sourceKeys.length; index < length; index += 1) {\n      key = sourceKeys[index];\n      target[key] = source[key];\n    }\n  }\n\n  return target;\n}\n\n\nfunction repeat(string, count) {\n  var result = '', cycle;\n\n  for (cycle = 0; cycle < count; cycle += 1) {\n    result += string;\n  }\n\n  return result;\n}\n\n\nfunction isNegativeZero(number) {\n  return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);\n}\n\n\nmodule.exports.isNothing      = isNothing;\nmodule.exports.isObject       = isObject;\nmodule.exports.toArray        = toArray;\nmodule.exports.repeat         = repeat;\nmodule.exports.isNegativeZero = isNegativeZero;\nmodule.exports.extend         = extend;\n", "// YAML error class. http://stackoverflow.com/questions/8458984\n//\n'use strict';\n\nfunction YAMLException(reason, mark) {\n  // Super constructor\n  Error.call(this);\n\n  this.name = 'YAMLException';\n  this.reason = reason;\n  this.mark = mark;\n  this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : '');\n\n  // Include stack trace in error object\n  if (Error.captureStackTrace) {\n    // Chrome and NodeJS\n    Error.captureStackTrace(this, this.constructor);\n  } else {\n    // FF, IE 10+ and Safari 6+. Fallback for others\n    this.stack = (new Error()).stack || '';\n  }\n}\n\n\n// Inherit from Error\nYAMLException.prototype = Object.create(Error.prototype);\nYAMLException.prototype.constructor = YAMLException;\n\n\nYAMLException.prototype.toString = function toString(compact) {\n  var result = this.name + ': ';\n\n  result += this.reason || '(unknown reason)';\n\n  if (!compact && this.mark) {\n    result += ' ' + this.mark.toString();\n  }\n\n  return result;\n};\n\n\nmodule.exports = YAMLException;\n", "'use strict';\n\n\nvar common = require('./common');\n\n\nfunction Mark(name, buffer, position, line, column) {\n  this.name     = name;\n  this.buffer   = buffer;\n  this.position = position;\n  this.line     = line;\n  this.column   = column;\n}\n\n\nMark.prototype.getSnippet = function getSnippet(indent, maxLength) {\n  var head, start, tail, end, snippet;\n\n  if (!this.buffer) return null;\n\n  indent = indent || 4;\n  maxLength = maxLength || 75;\n\n  head = '';\n  start = this.position;\n\n  while (start > 0 && '\\x00\\r\\n\\x85\\u2028\\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) {\n    start -= 1;\n    if (this.position - start > (maxLength / 2 - 1)) {\n      head = ' ... ';\n      start += 5;\n      break;\n    }\n  }\n\n  tail = '';\n  end = this.position;\n\n  while (end < this.buffer.length && '\\x00\\r\\n\\x85\\u2028\\u2029'.indexOf(this.buffer.charAt(end)) === -1) {\n    end += 1;\n    if (end - this.position > (maxLength / 2 - 1)) {\n      tail = ' ... ';\n      end -= 5;\n      break;\n    }\n  }\n\n  snippet = this.buffer.slice(start, end);\n\n  return common.repeat(' ', indent) + head + snippet + tail + '\\n' +\n         common.repeat(' ', indent + this.position - start + head.length) + '^';\n};\n\n\nMark.prototype.toString = function toString(compact) {\n  var snippet, where = '';\n\n  if (this.name) {\n    where += 'in \"' + this.name + '\" ';\n  }\n\n  where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);\n\n  if (!compact) {\n    snippet = this.getSnippet();\n\n    if (snippet) {\n      where += ':\\n' + snippet;\n    }\n  }\n\n  return where;\n};\n\n\nmodule.exports = Mark;\n", "'use strict';\n\nvar YAMLException = require('./exception');\n\nvar TYPE_CONSTRUCTOR_OPTIONS = [\n  'kind',\n  'resolve',\n  'construct',\n  'instanceOf',\n  'predicate',\n  'represent',\n  'defaultStyle',\n  'styleAliases'\n];\n\nvar YAML_NODE_KINDS = [\n  'scalar',\n  'sequence',\n  'mapping'\n];\n\nfunction compileStyleAliases(map) {\n  var result = {};\n\n  if (map !== null) {\n    Object.keys(map).forEach(function (style) {\n      map[style].forEach(function (alias) {\n        result[String(alias)] = style;\n      });\n    });\n  }\n\n  return result;\n}\n\nfunction Type(tag, options) {\n  options = options || {};\n\n  Object.keys(options).forEach(function (name) {\n    if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {\n      throw new YAMLException('Unknown option \"' + name + '\" is met in definition of \"' + tag + '\" YAML type.');\n    }\n  });\n\n  // TODO: Add tag format check.\n  this.tag          = tag;\n  this.kind         = options['kind']         || null;\n  this.resolve      = options['resolve']      || function () { return true; };\n  this.construct    = options['construct']    || function (data) { return data; };\n  this.instanceOf   = options['instanceOf']   || null;\n  this.predicate    = options['predicate']    || null;\n  this.represent    = options['represent']    || null;\n  this.defaultStyle = options['defaultStyle'] || null;\n  this.styleAliases = compileStyleAliases(options['styleAliases'] || null);\n\n  if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {\n    throw new YAMLException('Unknown kind \"' + this.kind + '\" is specified for \"' + tag + '\" YAML type.');\n  }\n}\n\nmodule.exports = Type;\n", "'use strict';\n\n/*eslint-disable max-len*/\n\nvar common        = require('./common');\nvar YAMLException = require('./exception');\nvar Type          = require('./type');\n\n\nfunction compileList(schema, name, result) {\n  var exclude = [];\n\n  schema.include.forEach(function (includedSchema) {\n    result = compileList(includedSchema, name, result);\n  });\n\n  schema[name].forEach(function (currentType) {\n    result.forEach(function (previousType, previousIndex) {\n      if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {\n        exclude.push(previousIndex);\n      }\n    });\n\n    result.push(currentType);\n  });\n\n  return result.filter(function (type, index) {\n    return exclude.indexOf(index) === -1;\n  });\n}\n\n\nfunction compileMap(/* lists... */) {\n  var result = {\n        scalar: {},\n        sequence: {},\n        mapping: {},\n        fallback: {}\n      }, index, length;\n\n  function collectType(type) {\n    result[type.kind][type.tag] = result['fallback'][type.tag] = type;\n  }\n\n  for (index = 0, length = arguments.length; index < length; index += 1) {\n    arguments[index].forEach(collectType);\n  }\n  return result;\n}\n\n\nfunction Schema(definition) {\n  this.include  = definition.include  || [];\n  this.implicit = definition.implicit || [];\n  this.explicit = definition.explicit || [];\n\n  this.implicit.forEach(function (type) {\n    if (type.loadKind && type.loadKind !== 'scalar') {\n      throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');\n    }\n  });\n\n  this.compiledImplicit = compileList(this, 'implicit', []);\n  this.compiledExplicit = compileList(this, 'explicit', []);\n  this.compiledTypeMap  = compileMap(this.compiledImplicit, this.compiledExplicit);\n}\n\n\nSchema.DEFAULT = null;\n\n\nSchema.create = function createSchema() {\n  var schemas, types;\n\n  switch (arguments.length) {\n    case 1:\n      schemas = Schema.DEFAULT;\n      types = arguments[0];\n      break;\n\n    case 2:\n      schemas = arguments[0];\n      types = arguments[1];\n      break;\n\n    default:\n      throw new YAMLException('Wrong number of arguments for Schema.create function');\n  }\n\n  schemas = common.toArray(schemas);\n  types = common.toArray(types);\n\n  if (!schemas.every(function (schema) { return schema instanceof Schema; })) {\n    throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');\n  }\n\n  if (!types.every(function (type) { return type instanceof Type; })) {\n    throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');\n  }\n\n  return new Schema({\n    include: schemas,\n    explicit: types\n  });\n};\n\n\nmodule.exports = Schema;\n", "'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:str', {\n  kind: 'scalar',\n  construct: function (data) { return data !== null ? data : ''; }\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:seq', {\n  kind: 'sequence',\n  construct: function (data) { return data !== null ? data : []; }\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nmodule.exports = new Type('tag:yaml.org,2002:map', {\n  kind: 'mapping',\n  construct: function (data) { return data !== null ? data : {}; }\n});\n", "// Standard YAML's Failsafe schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2802346\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n  explicit: [\n    require('../type/str'),\n    require('../type/seq'),\n    require('../type/map')\n  ]\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlNull(data) {\n  if (data === null) return true;\n\n  var max = data.length;\n\n  return (max === 1 && data === '~') ||\n         (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));\n}\n\nfunction constructYamlNull() {\n  return null;\n}\n\nfunction isNull(object) {\n  return object === null;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:null', {\n  kind: 'scalar',\n  resolve: resolveYamlNull,\n  construct: constructYamlNull,\n  predicate: isNull,\n  represent: {\n    canonical: function () { return '~';    },\n    lowercase: function () { return 'null'; },\n    uppercase: function () { return 'NULL'; },\n    camelcase: function () { return 'Null'; }\n  },\n  defaultStyle: 'lowercase'\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlBoolean(data) {\n  if (data === null) return false;\n\n  var max = data.length;\n\n  return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||\n         (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));\n}\n\nfunction constructYamlBoolean(data) {\n  return data === 'true' ||\n         data === 'True' ||\n         data === 'TRUE';\n}\n\nfunction isBoolean(object) {\n  return Object.prototype.toString.call(object) === '[object Boolean]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:bool', {\n  kind: 'scalar',\n  resolve: resolveYamlBoolean,\n  construct: constructYamlBoolean,\n  predicate: isBoolean,\n  represent: {\n    lowercase: function (object) { return object ? 'true' : 'false'; },\n    uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },\n    camelcase: function (object) { return object ? 'True' : 'False'; }\n  },\n  defaultStyle: 'lowercase'\n});\n", "'use strict';\n\nvar common = require('../common');\nvar Type   = require('../type');\n\nfunction isHexCode(c) {\n  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||\n         ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||\n         ((0x61/* a */ <= c) && (c <= 0x66/* f */));\n}\n\nfunction isOctCode(c) {\n  return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));\n}\n\nfunction isDecCode(c) {\n  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));\n}\n\nfunction resolveYamlInteger(data) {\n  if (data === null) return false;\n\n  var max = data.length,\n      index = 0,\n      hasDigits = false,\n      ch;\n\n  if (!max) return false;\n\n  ch = data[index];\n\n  // sign\n  if (ch === '-' || ch === '+') {\n    ch = data[++index];\n  }\n\n  if (ch === '0') {\n    // 0\n    if (index + 1 === max) return true;\n    ch = data[++index];\n\n    // base 2, base 8, base 16\n\n    if (ch === 'b') {\n      // base 2\n      index++;\n\n      for (; index < max; index++) {\n        ch = data[index];\n        if (ch === '_') continue;\n        if (ch !== '0' && ch !== '1') return false;\n        hasDigits = true;\n      }\n      return hasDigits && ch !== '_';\n    }\n\n\n    if (ch === 'x') {\n      // base 16\n      index++;\n\n      for (; index < max; index++) {\n        ch = data[index];\n        if (ch === '_') continue;\n        if (!isHexCode(data.charCodeAt(index))) return false;\n        hasDigits = true;\n      }\n      return hasDigits && ch !== '_';\n    }\n\n    // base 8\n    for (; index < max; index++) {\n      ch = data[index];\n      if (ch === '_') continue;\n      if (!isOctCode(data.charCodeAt(index))) return false;\n      hasDigits = true;\n    }\n    return hasDigits && ch !== '_';\n  }\n\n  // base 10 (except 0) or base 60\n\n  // value should not start with `_`;\n  if (ch === '_') return false;\n\n  for (; index < max; index++) {\n    ch = data[index];\n    if (ch === '_') continue;\n    if (ch === ':') break;\n    if (!isDecCode(data.charCodeAt(index))) {\n      return false;\n    }\n    hasDigits = true;\n  }\n\n  // Should have digits and should not end with `_`\n  if (!hasDigits || ch === '_') return false;\n\n  // if !base60 - done;\n  if (ch !== ':') return true;\n\n  // base60 almost not used, no needs to optimize\n  return /^(:[0-5]?[0-9])+$/.test(data.slice(index));\n}\n\nfunction constructYamlInteger(data) {\n  var value = data, sign = 1, ch, base, digits = [];\n\n  if (value.indexOf('_') !== -1) {\n    value = value.replace(/_/g, '');\n  }\n\n  ch = value[0];\n\n  if (ch === '-' || ch === '+') {\n    if (ch === '-') sign = -1;\n    value = value.slice(1);\n    ch = value[0];\n  }\n\n  if (value === '0') return 0;\n\n  if (ch === '0') {\n    if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);\n    if (value[1] === 'x') return sign * parseInt(value, 16);\n    return sign * parseInt(value, 8);\n  }\n\n  if (value.indexOf(':') !== -1) {\n    value.split(':').forEach(function (v) {\n      digits.unshift(parseInt(v, 10));\n    });\n\n    value = 0;\n    base = 1;\n\n    digits.forEach(function (d) {\n      value += (d * base);\n      base *= 60;\n    });\n\n    return sign * value;\n\n  }\n\n  return sign * parseInt(value, 10);\n}\n\nfunction isInteger(object) {\n  return (Object.prototype.toString.call(object)) === '[object Number]' &&\n         (object % 1 === 0 && !common.isNegativeZero(object));\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:int', {\n  kind: 'scalar',\n  resolve: resolveYamlInteger,\n  construct: constructYamlInteger,\n  predicate: isInteger,\n  represent: {\n    binary:      function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },\n    octal:       function (obj) { return obj >= 0 ? '0'  + obj.toString(8) : '-0'  + obj.toString(8).slice(1); },\n    decimal:     function (obj) { return obj.toString(10); },\n    /* eslint-disable max-len */\n    hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() :  '-0x' + obj.toString(16).toUpperCase().slice(1); }\n  },\n  defaultStyle: 'decimal',\n  styleAliases: {\n    binary:      [ 2,  'bin' ],\n    octal:       [ 8,  'oct' ],\n    decimal:     [ 10, 'dec' ],\n    hexadecimal: [ 16, 'hex' ]\n  }\n});\n", "'use strict';\n\nvar common = require('../common');\nvar Type   = require('../type');\n\nvar YAML_FLOAT_PATTERN = new RegExp(\n  // 2.5e4, 2.5 and integers\n  '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +\n  // .2e4, .2\n  // special case, seems not from spec\n  '|\\\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +\n  // 20:59\n  '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]*' +\n  // .inf\n  '|[-+]?\\\\.(?:inf|Inf|INF)' +\n  // .nan\n  '|\\\\.(?:nan|NaN|NAN))$');\n\nfunction resolveYamlFloat(data) {\n  if (data === null) return false;\n\n  if (!YAML_FLOAT_PATTERN.test(data) ||\n      // Quick hack to not allow integers end with `_`\n      // Probably should update regexp & check speed\n      data[data.length - 1] === '_') {\n    return false;\n  }\n\n  return true;\n}\n\nfunction constructYamlFloat(data) {\n  var value, sign, base, digits;\n\n  value  = data.replace(/_/g, '').toLowerCase();\n  sign   = value[0] === '-' ? -1 : 1;\n  digits = [];\n\n  if ('+-'.indexOf(value[0]) >= 0) {\n    value = value.slice(1);\n  }\n\n  if (value === '.inf') {\n    return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;\n\n  } else if (value === '.nan') {\n    return NaN;\n\n  } else if (value.indexOf(':') >= 0) {\n    value.split(':').forEach(function (v) {\n      digits.unshift(parseFloat(v, 10));\n    });\n\n    value = 0.0;\n    base = 1;\n\n    digits.forEach(function (d) {\n      value += d * base;\n      base *= 60;\n    });\n\n    return sign * value;\n\n  }\n  return sign * parseFloat(value, 10);\n}\n\n\nvar SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;\n\nfunction representYamlFloat(object, style) {\n  var res;\n\n  if (isNaN(object)) {\n    switch (style) {\n      case 'lowercase': return '.nan';\n      case 'uppercase': return '.NAN';\n      case 'camelcase': return '.NaN';\n    }\n  } else if (Number.POSITIVE_INFINITY === object) {\n    switch (style) {\n      case 'lowercase': return '.inf';\n      case 'uppercase': return '.INF';\n      case 'camelcase': return '.Inf';\n    }\n  } else if (Number.NEGATIVE_INFINITY === object) {\n    switch (style) {\n      case 'lowercase': return '-.inf';\n      case 'uppercase': return '-.INF';\n      case 'camelcase': return '-.Inf';\n    }\n  } else if (common.isNegativeZero(object)) {\n    return '-0.0';\n  }\n\n  res = object.toString(10);\n\n  // JS stringifier can build scientific format without dots: 5e-100,\n  // while YAML requres dot: 5.e-100. Fix it with simple hack\n\n  return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;\n}\n\nfunction isFloat(object) {\n  return (Object.prototype.toString.call(object) === '[object Number]') &&\n         (object % 1 !== 0 || common.isNegativeZero(object));\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:float', {\n  kind: 'scalar',\n  resolve: resolveYamlFloat,\n  construct: constructYamlFloat,\n  predicate: isFloat,\n  represent: representYamlFloat,\n  defaultStyle: 'lowercase'\n});\n", "// Standard YAML's JSON schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2803231\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, this schema is not such strict as defined in the YAML specification.\n// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n  include: [\n    require('./failsafe')\n  ],\n  implicit: [\n    require('../type/null'),\n    require('../type/bool'),\n    require('../type/int'),\n    require('../type/float')\n  ]\n});\n", "// Standard YAML's Core schema.\n// http://www.yaml.org/spec/1.2/spec.html#id2804923\n//\n// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.\n// So, Core schema has no distinctions from JSON schema is JS-YAML.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n  include: [\n    require('./json')\n  ]\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nvar YAML_DATE_REGEXP = new RegExp(\n  '^([0-9][0-9][0-9][0-9])'          + // [1] year\n  '-([0-9][0-9])'                    + // [2] month\n  '-([0-9][0-9])$');                   // [3] day\n\nvar YAML_TIMESTAMP_REGEXP = new RegExp(\n  '^([0-9][0-9][0-9][0-9])'          + // [1] year\n  '-([0-9][0-9]?)'                   + // [2] month\n  '-([0-9][0-9]?)'                   + // [3] day\n  '(?:[Tt]|[ \\\\t]+)'                 + // ...\n  '([0-9][0-9]?)'                    + // [4] hour\n  ':([0-9][0-9])'                    + // [5] minute\n  ':([0-9][0-9])'                    + // [6] second\n  '(?:\\\\.([0-9]*))?'                 + // [7] fraction\n  '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour\n  '(?::([0-9][0-9]))?))?$');           // [11] tz_minute\n\nfunction resolveYamlTimestamp(data) {\n  if (data === null) return false;\n  if (YAML_DATE_REGEXP.exec(data) !== null) return true;\n  if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;\n  return false;\n}\n\nfunction constructYamlTimestamp(data) {\n  var match, year, month, day, hour, minute, second, fraction = 0,\n      delta = null, tz_hour, tz_minute, date;\n\n  match = YAML_DATE_REGEXP.exec(data);\n  if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);\n\n  if (match === null) throw new Error('Date resolve error');\n\n  // match: [1] year [2] month [3] day\n\n  year = +(match[1]);\n  month = +(match[2]) - 1; // JS month starts with 0\n  day = +(match[3]);\n\n  if (!match[4]) { // no hour\n    return new Date(Date.UTC(year, month, day));\n  }\n\n  // match: [4] hour [5] minute [6] second [7] fraction\n\n  hour = +(match[4]);\n  minute = +(match[5]);\n  second = +(match[6]);\n\n  if (match[7]) {\n    fraction = match[7].slice(0, 3);\n    while (fraction.length < 3) { // milli-seconds\n      fraction += '0';\n    }\n    fraction = +fraction;\n  }\n\n  // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute\n\n  if (match[9]) {\n    tz_hour = +(match[10]);\n    tz_minute = +(match[11] || 0);\n    delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds\n    if (match[9] === '-') delta = -delta;\n  }\n\n  date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));\n\n  if (delta) date.setTime(date.getTime() - delta);\n\n  return date;\n}\n\nfunction representYamlTimestamp(object /*, style*/) {\n  return object.toISOString();\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:timestamp', {\n  kind: 'scalar',\n  resolve: resolveYamlTimestamp,\n  construct: constructYamlTimestamp,\n  instanceOf: Date,\n  represent: representYamlTimestamp\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nfunction resolveYamlMerge(data) {\n  return data === '<<' || data === null;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:merge', {\n  kind: 'scalar',\n  resolve: resolveYamlMerge\n});\n", "'use strict';\n\n/*eslint-disable no-bitwise*/\n\nvar NodeBuffer;\n\ntry {\n  // A trick for browserified version, to not include `Buffer` shim\n  var _require = require;\n  NodeBuffer = _require('buffer').Buffer;\n} catch (__) {}\n\nvar Type       = require('../type');\n\n\n// [ 64, 65, 66 ] -> [ padding, CR, LF ]\nvar BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\\n\\r';\n\n\nfunction resolveYamlBinary(data) {\n  if (data === null) return false;\n\n  var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;\n\n  // Convert one by one.\n  for (idx = 0; idx < max; idx++) {\n    code = map.indexOf(data.charAt(idx));\n\n    // Skip CR/LF\n    if (code > 64) continue;\n\n    // Fail on illegal characters\n    if (code < 0) return false;\n\n    bitlen += 6;\n  }\n\n  // If there are any bits left, source was corrupted\n  return (bitlen % 8) === 0;\n}\n\nfunction constructYamlBinary(data) {\n  var idx, tailbits,\n      input = data.replace(/[\\r\\n=]/g, ''), // remove CR/LF & padding to simplify scan\n      max = input.length,\n      map = BASE64_MAP,\n      bits = 0,\n      result = [];\n\n  // Collect by 6*4 bits (3 bytes)\n\n  for (idx = 0; idx < max; idx++) {\n    if ((idx % 4 === 0) && idx) {\n      result.push((bits >> 16) & 0xFF);\n      result.push((bits >> 8) & 0xFF);\n      result.push(bits & 0xFF);\n    }\n\n    bits = (bits << 6) | map.indexOf(input.charAt(idx));\n  }\n\n  // Dump tail\n\n  tailbits = (max % 4) * 6;\n\n  if (tailbits === 0) {\n    result.push((bits >> 16) & 0xFF);\n    result.push((bits >> 8) & 0xFF);\n    result.push(bits & 0xFF);\n  } else if (tailbits === 18) {\n    result.push((bits >> 10) & 0xFF);\n    result.push((bits >> 2) & 0xFF);\n  } else if (tailbits === 12) {\n    result.push((bits >> 4) & 0xFF);\n  }\n\n  // Wrap into Buffer for NodeJS and leave Array for browser\n  if (NodeBuffer) {\n    // Support node 6.+ Buffer API when available\n    return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);\n  }\n\n  return result;\n}\n\nfunction representYamlBinary(object /*, style*/) {\n  var result = '', bits = 0, idx, tail,\n      max = object.length,\n      map = BASE64_MAP;\n\n  // Convert every three bytes to 4 ASCII characters.\n\n  for (idx = 0; idx < max; idx++) {\n    if ((idx % 3 === 0) && idx) {\n      result += map[(bits >> 18) & 0x3F];\n      result += map[(bits >> 12) & 0x3F];\n      result += map[(bits >> 6) & 0x3F];\n      result += map[bits & 0x3F];\n    }\n\n    bits = (bits << 8) + object[idx];\n  }\n\n  // Dump tail\n\n  tail = max % 3;\n\n  if (tail === 0) {\n    result += map[(bits >> 18) & 0x3F];\n    result += map[(bits >> 12) & 0x3F];\n    result += map[(bits >> 6) & 0x3F];\n    result += map[bits & 0x3F];\n  } else if (tail === 2) {\n    result += map[(bits >> 10) & 0x3F];\n    result += map[(bits >> 4) & 0x3F];\n    result += map[(bits << 2) & 0x3F];\n    result += map[64];\n  } else if (tail === 1) {\n    result += map[(bits >> 2) & 0x3F];\n    result += map[(bits << 4) & 0x3F];\n    result += map[64];\n    result += map[64];\n  }\n\n  return result;\n}\n\nfunction isBinary(object) {\n  return NodeBuffer && NodeBuffer.isBuffer(object);\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:binary', {\n  kind: 'scalar',\n  resolve: resolveYamlBinary,\n  construct: constructYamlBinary,\n  predicate: isBinary,\n  represent: representYamlBinary\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\nvar _toString       = Object.prototype.toString;\n\nfunction resolveYamlOmap(data) {\n  if (data === null) return true;\n\n  var objectKeys = [], index, length, pair, pairKey, pairHasKey,\n      object = data;\n\n  for (index = 0, length = object.length; index < length; index += 1) {\n    pair = object[index];\n    pairHasKey = false;\n\n    if (_toString.call(pair) !== '[object Object]') return false;\n\n    for (pairKey in pair) {\n      if (_hasOwnProperty.call(pair, pairKey)) {\n        if (!pairHasKey) pairHasKey = true;\n        else return false;\n      }\n    }\n\n    if (!pairHasKey) return false;\n\n    if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);\n    else return false;\n  }\n\n  return true;\n}\n\nfunction constructYamlOmap(data) {\n  return data !== null ? data : [];\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:omap', {\n  kind: 'sequence',\n  resolve: resolveYamlOmap,\n  construct: constructYamlOmap\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nvar _toString = Object.prototype.toString;\n\nfunction resolveYamlPairs(data) {\n  if (data === null) return true;\n\n  var index, length, pair, keys, result,\n      object = data;\n\n  result = new Array(object.length);\n\n  for (index = 0, length = object.length; index < length; index += 1) {\n    pair = object[index];\n\n    if (_toString.call(pair) !== '[object Object]') return false;\n\n    keys = Object.keys(pair);\n\n    if (keys.length !== 1) return false;\n\n    result[index] = [ keys[0], pair[keys[0]] ];\n  }\n\n  return true;\n}\n\nfunction constructYamlPairs(data) {\n  if (data === null) return [];\n\n  var index, length, pair, keys, result,\n      object = data;\n\n  result = new Array(object.length);\n\n  for (index = 0, length = object.length; index < length; index += 1) {\n    pair = object[index];\n\n    keys = Object.keys(pair);\n\n    result[index] = [ keys[0], pair[keys[0]] ];\n  }\n\n  return result;\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:pairs', {\n  kind: 'sequence',\n  resolve: resolveYamlPairs,\n  construct: constructYamlPairs\n});\n", "'use strict';\n\nvar Type = require('../type');\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction resolveYamlSet(data) {\n  if (data === null) return true;\n\n  var key, object = data;\n\n  for (key in object) {\n    if (_hasOwnProperty.call(object, key)) {\n      if (object[key] !== null) return false;\n    }\n  }\n\n  return true;\n}\n\nfunction constructYamlSet(data) {\n  return data !== null ? data : {};\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:set', {\n  kind: 'mapping',\n  resolve: resolveYamlSet,\n  construct: constructYamlSet\n});\n", "// JS-YAML's default schema for `safeLoad` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on standard YAML's Core schema and includes most of\n// extra types described at YAML tag repository. (http://yaml.org/type/)\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = new Schema({\n  include: [\n    require('./core')\n  ],\n  implicit: [\n    require('../type/timestamp'),\n    require('../type/merge')\n  ],\n  explicit: [\n    require('../type/binary'),\n    require('../type/omap'),\n    require('../type/pairs'),\n    require('../type/set')\n  ]\n});\n", "'use strict';\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptUndefined() {\n  return true;\n}\n\nfunction constructJavascriptUndefined() {\n  /*eslint-disable no-undefined*/\n  return undefined;\n}\n\nfunction representJavascriptUndefined() {\n  return '';\n}\n\nfunction isUndefined(object) {\n  return typeof object === 'undefined';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/undefined', {\n  kind: 'scalar',\n  resolve: resolveJavascriptUndefined,\n  construct: constructJavascriptUndefined,\n  predicate: isUndefined,\n  represent: representJavascriptUndefined\n});\n", "'use strict';\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptRegExp(data) {\n  if (data === null) return false;\n  if (data.length === 0) return false;\n\n  var regexp = data,\n      tail   = /\\/([gim]*)$/.exec(data),\n      modifiers = '';\n\n  // if regexp starts with '/' it can have modifiers and must be properly closed\n  // `/foo/gim` - modifiers tail can be maximum 3 chars\n  if (regexp[0] === '/') {\n    if (tail) modifiers = tail[1];\n\n    if (modifiers.length > 3) return false;\n    // if expression starts with /, is should be properly terminated\n    if (regexp[regexp.length - modifiers.length - 1] !== '/') return false;\n  }\n\n  return true;\n}\n\nfunction constructJavascriptRegExp(data) {\n  var regexp = data,\n      tail   = /\\/([gim]*)$/.exec(data),\n      modifiers = '';\n\n  // `/foo/gim` - tail can be maximum 4 chars\n  if (regexp[0] === '/') {\n    if (tail) modifiers = tail[1];\n    regexp = regexp.slice(1, regexp.length - modifiers.length - 1);\n  }\n\n  return new RegExp(regexp, modifiers);\n}\n\nfunction representJavascriptRegExp(object /*, style*/) {\n  var result = '/' + object.source + '/';\n\n  if (object.global) result += 'g';\n  if (object.multiline) result += 'm';\n  if (object.ignoreCase) result += 'i';\n\n  return result;\n}\n\nfunction isRegExp(object) {\n  return Object.prototype.toString.call(object) === '[object RegExp]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/regexp', {\n  kind: 'scalar',\n  resolve: resolveJavascriptRegExp,\n  construct: constructJavascriptRegExp,\n  predicate: isRegExp,\n  represent: representJavascriptRegExp\n});\n", "'use strict';\n\nvar esprima;\n\n// Browserified version does not have esprima\n//\n// 1. For node.js just require module as deps\n// 2. For browser try to require mudule via external AMD system.\n//    If not found - try to fallback to window.esprima. If not\n//    found too - then fail to parse.\n//\ntry {\n  // workaround to exclude package from browserify list.\n  var _require = require;\n  esprima = _require('esprima');\n} catch (_) {\n  /* eslint-disable no-redeclare */\n  /* global window */\n  if (typeof window !== 'undefined') esprima = window.esprima;\n}\n\nvar Type = require('../../type');\n\nfunction resolveJavascriptFunction(data) {\n  if (data === null) return false;\n\n  try {\n    var source = '(' + data + ')',\n        ast    = esprima.parse(source, { range: true });\n\n    if (ast.type                    !== 'Program'             ||\n        ast.body.length             !== 1                     ||\n        ast.body[0].type            !== 'ExpressionStatement' ||\n        (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&\n          ast.body[0].expression.type !== 'FunctionExpression')) {\n      return false;\n    }\n\n    return true;\n  } catch (err) {\n    return false;\n  }\n}\n\nfunction constructJavascriptFunction(data) {\n  /*jslint evil:true*/\n\n  var source = '(' + data + ')',\n      ast    = esprima.parse(source, { range: true }),\n      params = [],\n      body;\n\n  if (ast.type                    !== 'Program'             ||\n      ast.body.length             !== 1                     ||\n      ast.body[0].type            !== 'ExpressionStatement' ||\n      (ast.body[0].expression.type !== 'ArrowFunctionExpression' &&\n        ast.body[0].expression.type !== 'FunctionExpression')) {\n    throw new Error('Failed to resolve function');\n  }\n\n  ast.body[0].expression.params.forEach(function (param) {\n    params.push(param.name);\n  });\n\n  body = ast.body[0].expression.body.range;\n\n  // Esprima's ranges include the first '{' and the last '}' characters on\n  // function expressions. So cut them out.\n  if (ast.body[0].expression.body.type === 'BlockStatement') {\n    /*eslint-disable no-new-func*/\n    return new Function(params, source.slice(body[0] + 1, body[1] - 1));\n  }\n  // ES6 arrow functions can omit the BlockStatement. In that case, just return\n  // the body.\n  /*eslint-disable no-new-func*/\n  return new Function(params, 'return ' + source.slice(body[0], body[1]));\n}\n\nfunction representJavascriptFunction(object /*, style*/) {\n  return object.toString();\n}\n\nfunction isFunction(object) {\n  return Object.prototype.toString.call(object) === '[object Function]';\n}\n\nmodule.exports = new Type('tag:yaml.org,2002:js/function', {\n  kind: 'scalar',\n  resolve: resolveJavascriptFunction,\n  construct: constructJavascriptFunction,\n  predicate: isFunction,\n  represent: representJavascriptFunction\n});\n", "// JS-YAML's default schema for `load` function.\n// It is not described in the YAML specification.\n//\n// This schema is based on JS-YAML's default safe schema and includes\n// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.\n//\n// Also this schema is used as default base schema at `Schema.create` function.\n\n\n'use strict';\n\n\nvar Schema = require('../schema');\n\n\nmodule.exports = Schema.DEFAULT = new Schema({\n  include: [\n    require('./default_safe')\n  ],\n  explicit: [\n    require('../type/js/undefined'),\n    require('../type/js/regexp'),\n    require('../type/js/function')\n  ]\n});\n", "'use strict';\n\n/*eslint-disable max-len,no-use-before-define*/\n\nvar common              = require('./common');\nvar YAMLException       = require('./exception');\nvar Mark                = require('./mark');\nvar DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');\nvar DEFAULT_FULL_SCHEMA = require('./schema/default_full');\n\n\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\n\nvar CONTEXT_FLOW_IN   = 1;\nvar CONTEXT_FLOW_OUT  = 2;\nvar CONTEXT_BLOCK_IN  = 3;\nvar CONTEXT_BLOCK_OUT = 4;\n\n\nvar CHOMPING_CLIP  = 1;\nvar CHOMPING_STRIP = 2;\nvar CHOMPING_KEEP  = 3;\n\n\nvar PATTERN_NON_PRINTABLE         = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\nvar PATTERN_NON_ASCII_LINE_BREAKS = /[\\x85\\u2028\\u2029]/;\nvar PATTERN_FLOW_INDICATORS       = /[,\\[\\]\\{\\}]/;\nvar PATTERN_TAG_HANDLE            = /^(?:!|!!|![a-z\\-]+!)$/i;\nvar PATTERN_TAG_URI               = /^(?:!|[^,\\[\\]\\{\\}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;\\/\\?:@&=\\+\\$,_\\.!~\\*'\\(\\)\\[\\]])*$/i;\n\n\nfunction _class(obj) { return Object.prototype.toString.call(obj); }\n\nfunction is_EOL(c) {\n  return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);\n}\n\nfunction is_WHITE_SPACE(c) {\n  return (c === 0x09/* Tab */) || (c === 0x20/* Space */);\n}\n\nfunction is_WS_OR_EOL(c) {\n  return (c === 0x09/* Tab */) ||\n         (c === 0x20/* Space */) ||\n         (c === 0x0A/* LF */) ||\n         (c === 0x0D/* CR */);\n}\n\nfunction is_FLOW_INDICATOR(c) {\n  return c === 0x2C/* , */ ||\n         c === 0x5B/* [ */ ||\n         c === 0x5D/* ] */ ||\n         c === 0x7B/* { */ ||\n         c === 0x7D/* } */;\n}\n\nfunction fromHexCode(c) {\n  var lc;\n\n  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n    return c - 0x30;\n  }\n\n  /*eslint-disable no-bitwise*/\n  lc = c | 0x20;\n\n  if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {\n    return lc - 0x61 + 10;\n  }\n\n  return -1;\n}\n\nfunction escapedHexLen(c) {\n  if (c === 0x78/* x */) { return 2; }\n  if (c === 0x75/* u */) { return 4; }\n  if (c === 0x55/* U */) { return 8; }\n  return 0;\n}\n\nfunction fromDecimalCode(c) {\n  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {\n    return c - 0x30;\n  }\n\n  return -1;\n}\n\nfunction simpleEscapeSequence(c) {\n  /* eslint-disable indent */\n  return (c === 0x30/* 0 */) ? '\\x00' :\n        (c === 0x61/* a */) ? '\\x07' :\n        (c === 0x62/* b */) ? '\\x08' :\n        (c === 0x74/* t */) ? '\\x09' :\n        (c === 0x09/* Tab */) ? '\\x09' :\n        (c === 0x6E/* n */) ? '\\x0A' :\n        (c === 0x76/* v */) ? '\\x0B' :\n        (c === 0x66/* f */) ? '\\x0C' :\n        (c === 0x72/* r */) ? '\\x0D' :\n        (c === 0x65/* e */) ? '\\x1B' :\n        (c === 0x20/* Space */) ? ' ' :\n        (c === 0x22/* \" */) ? '\\x22' :\n        (c === 0x2F/* / */) ? '/' :\n        (c === 0x5C/* \\ */) ? '\\x5C' :\n        (c === 0x4E/* N */) ? '\\x85' :\n        (c === 0x5F/* _ */) ? '\\xA0' :\n        (c === 0x4C/* L */) ? '\\u2028' :\n        (c === 0x50/* P */) ? '\\u2029' : '';\n}\n\nfunction charFromCodepoint(c) {\n  if (c <= 0xFFFF) {\n    return String.fromCharCode(c);\n  }\n  // Encode UTF-16 surrogate pair\n  // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF\n  return String.fromCharCode(\n    ((c - 0x010000) >> 10) + 0xD800,\n    ((c - 0x010000) & 0x03FF) + 0xDC00\n  );\n}\n\n// set a property of a literal object, while protecting against prototype pollution,\n// see https://github.com/nodeca/js-yaml/issues/164 for more details\nfunction setProperty(object, key, value) {\n  // used for this specific key only because Object.defineProperty is slow\n  if (key === '__proto__') {\n    Object.defineProperty(object, key, {\n      configurable: true,\n      enumerable: true,\n      writable: true,\n      value: value\n    });\n  } else {\n    object[key] = value;\n  }\n}\n\nvar simpleEscapeCheck = new Array(256); // integer, for fast access\nvar simpleEscapeMap = new Array(256);\nfor (var i = 0; i < 256; i++) {\n  simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;\n  simpleEscapeMap[i] = simpleEscapeSequence(i);\n}\n\n\nfunction State(input, options) {\n  this.input = input;\n\n  this.filename  = options['filename']  || null;\n  this.schema    = options['schema']    || DEFAULT_FULL_SCHEMA;\n  this.onWarning = options['onWarning'] || null;\n  this.legacy    = options['legacy']    || false;\n  this.json      = options['json']      || false;\n  this.listener  = options['listener']  || null;\n\n  this.implicitTypes = this.schema.compiledImplicit;\n  this.typeMap       = this.schema.compiledTypeMap;\n\n  this.length     = input.length;\n  this.position   = 0;\n  this.line       = 0;\n  this.lineStart  = 0;\n  this.lineIndent = 0;\n\n  this.documents = [];\n\n  /*\n  this.version;\n  this.checkLineBreaks;\n  this.tagMap;\n  this.anchorMap;\n  this.tag;\n  this.anchor;\n  this.kind;\n  this.result;*/\n\n}\n\n\nfunction generateError(state, message) {\n  return new YAMLException(\n    message,\n    new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));\n}\n\nfunction throwError(state, message) {\n  throw generateError(state, message);\n}\n\nfunction throwWarning(state, message) {\n  if (state.onWarning) {\n    state.onWarning.call(null, generateError(state, message));\n  }\n}\n\n\nvar directiveHandlers = {\n\n  YAML: function handleYamlDirective(state, name, args) {\n\n    var match, major, minor;\n\n    if (state.version !== null) {\n      throwError(state, 'duplication of %YAML directive');\n    }\n\n    if (args.length !== 1) {\n      throwError(state, 'YAML directive accepts exactly one argument');\n    }\n\n    match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0]);\n\n    if (match === null) {\n      throwError(state, 'ill-formed argument of the YAML directive');\n    }\n\n    major = parseInt(match[1], 10);\n    minor = parseInt(match[2], 10);\n\n    if (major !== 1) {\n      throwError(state, 'unacceptable YAML version of the document');\n    }\n\n    state.version = args[0];\n    state.checkLineBreaks = (minor < 2);\n\n    if (minor !== 1 && minor !== 2) {\n      throwWarning(state, 'unsupported YAML version of the document');\n    }\n  },\n\n  TAG: function handleTagDirective(state, name, args) {\n\n    var handle, prefix;\n\n    if (args.length !== 2) {\n      throwError(state, 'TAG directive accepts exactly two arguments');\n    }\n\n    handle = args[0];\n    prefix = args[1];\n\n    if (!PATTERN_TAG_HANDLE.test(handle)) {\n      throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');\n    }\n\n    if (_hasOwnProperty.call(state.tagMap, handle)) {\n      throwError(state, 'there is a previously declared suffix for \"' + handle + '\" tag handle');\n    }\n\n    if (!PATTERN_TAG_URI.test(prefix)) {\n      throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');\n    }\n\n    state.tagMap[handle] = prefix;\n  }\n};\n\n\nfunction captureSegment(state, start, end, checkJson) {\n  var _position, _length, _character, _result;\n\n  if (start < end) {\n    _result = state.input.slice(start, end);\n\n    if (checkJson) {\n      for (_position = 0, _length = _result.length; _position < _length; _position += 1) {\n        _character = _result.charCodeAt(_position);\n        if (!(_character === 0x09 ||\n              (0x20 <= _character && _character <= 0x10FFFF))) {\n          throwError(state, 'expected valid JSON character');\n        }\n      }\n    } else if (PATTERN_NON_PRINTABLE.test(_result)) {\n      throwError(state, 'the stream contains non-printable characters');\n    }\n\n    state.result += _result;\n  }\n}\n\nfunction mergeMappings(state, destination, source, overridableKeys) {\n  var sourceKeys, key, index, quantity;\n\n  if (!common.isObject(source)) {\n    throwError(state, 'cannot merge mappings; the provided source object is unacceptable');\n  }\n\n  sourceKeys = Object.keys(source);\n\n  for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {\n    key = sourceKeys[index];\n\n    if (!_hasOwnProperty.call(destination, key)) {\n      setProperty(destination, key, source[key]);\n      overridableKeys[key] = true;\n    }\n  }\n}\n\nfunction storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {\n  var index, quantity;\n\n  // The output is a plain object here, so keys can only be strings.\n  // We need to convert keyNode to a string, but doing so can hang the process\n  // (deeply nested arrays that explode exponentially using aliases).\n  if (Array.isArray(keyNode)) {\n    keyNode = Array.prototype.slice.call(keyNode);\n\n    for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {\n      if (Array.isArray(keyNode[index])) {\n        throwError(state, 'nested arrays are not supported inside keys');\n      }\n\n      if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {\n        keyNode[index] = '[object Object]';\n      }\n    }\n  }\n\n  // Avoid code execution in load() via toString property\n  // (still use its own toString for arrays, timestamps,\n  // and whatever user schema extensions happen to have @@toStringTag)\n  if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {\n    keyNode = '[object Object]';\n  }\n\n\n  keyNode = String(keyNode);\n\n  if (_result === null) {\n    _result = {};\n  }\n\n  if (keyTag === 'tag:yaml.org,2002:merge') {\n    if (Array.isArray(valueNode)) {\n      for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {\n        mergeMappings(state, _result, valueNode[index], overridableKeys);\n      }\n    } else {\n      mergeMappings(state, _result, valueNode, overridableKeys);\n    }\n  } else {\n    if (!state.json &&\n        !_hasOwnProperty.call(overridableKeys, keyNode) &&\n        _hasOwnProperty.call(_result, keyNode)) {\n      state.line = startLine || state.line;\n      state.position = startPos || state.position;\n      throwError(state, 'duplicated mapping key');\n    }\n    setProperty(_result, keyNode, valueNode);\n    delete overridableKeys[keyNode];\n  }\n\n  return _result;\n}\n\nfunction readLineBreak(state) {\n  var ch;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (ch === 0x0A/* LF */) {\n    state.position++;\n  } else if (ch === 0x0D/* CR */) {\n    state.position++;\n    if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {\n      state.position++;\n    }\n  } else {\n    throwError(state, 'a line break is expected');\n  }\n\n  state.line += 1;\n  state.lineStart = state.position;\n}\n\nfunction skipSeparationSpace(state, allowComments, checkIndent) {\n  var lineBreaks = 0,\n      ch = state.input.charCodeAt(state.position);\n\n  while (ch !== 0) {\n    while (is_WHITE_SPACE(ch)) {\n      ch = state.input.charCodeAt(++state.position);\n    }\n\n    if (allowComments && ch === 0x23/* # */) {\n      do {\n        ch = state.input.charCodeAt(++state.position);\n      } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);\n    }\n\n    if (is_EOL(ch)) {\n      readLineBreak(state);\n\n      ch = state.input.charCodeAt(state.position);\n      lineBreaks++;\n      state.lineIndent = 0;\n\n      while (ch === 0x20/* Space */) {\n        state.lineIndent++;\n        ch = state.input.charCodeAt(++state.position);\n      }\n    } else {\n      break;\n    }\n  }\n\n  if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {\n    throwWarning(state, 'deficient indentation');\n  }\n\n  return lineBreaks;\n}\n\nfunction testDocumentSeparator(state) {\n  var _position = state.position,\n      ch;\n\n  ch = state.input.charCodeAt(_position);\n\n  // Condition state.position === state.lineStart is tested\n  // in parent on each call, for efficiency. No needs to test here again.\n  if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n      ch === state.input.charCodeAt(_position + 1) &&\n      ch === state.input.charCodeAt(_position + 2)) {\n\n    _position += 3;\n\n    ch = state.input.charCodeAt(_position);\n\n    if (ch === 0 || is_WS_OR_EOL(ch)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nfunction writeFoldedLines(state, count) {\n  if (count === 1) {\n    state.result += ' ';\n  } else if (count > 1) {\n    state.result += common.repeat('\\n', count - 1);\n  }\n}\n\n\nfunction readPlainScalar(state, nodeIndent, withinFlowCollection) {\n  var preceding,\n      following,\n      captureStart,\n      captureEnd,\n      hasPendingContent,\n      _line,\n      _lineStart,\n      _lineIndent,\n      _kind = state.kind,\n      _result = state.result,\n      ch;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (is_WS_OR_EOL(ch)      ||\n      is_FLOW_INDICATOR(ch) ||\n      ch === 0x23/* # */    ||\n      ch === 0x26/* & */    ||\n      ch === 0x2A/* * */    ||\n      ch === 0x21/* ! */    ||\n      ch === 0x7C/* | */    ||\n      ch === 0x3E/* > */    ||\n      ch === 0x27/* ' */    ||\n      ch === 0x22/* \" */    ||\n      ch === 0x25/* % */    ||\n      ch === 0x40/* @ */    ||\n      ch === 0x60/* ` */) {\n    return false;\n  }\n\n  if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n    following = state.input.charCodeAt(state.position + 1);\n\n    if (is_WS_OR_EOL(following) ||\n        withinFlowCollection && is_FLOW_INDICATOR(following)) {\n      return false;\n    }\n  }\n\n  state.kind = 'scalar';\n  state.result = '';\n  captureStart = captureEnd = state.position;\n  hasPendingContent = false;\n\n  while (ch !== 0) {\n    if (ch === 0x3A/* : */) {\n      following = state.input.charCodeAt(state.position + 1);\n\n      if (is_WS_OR_EOL(following) ||\n          withinFlowCollection && is_FLOW_INDICATOR(following)) {\n        break;\n      }\n\n    } else if (ch === 0x23/* # */) {\n      preceding = state.input.charCodeAt(state.position - 1);\n\n      if (is_WS_OR_EOL(preceding)) {\n        break;\n      }\n\n    } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||\n               withinFlowCollection && is_FLOW_INDICATOR(ch)) {\n      break;\n\n    } else if (is_EOL(ch)) {\n      _line = state.line;\n      _lineStart = state.lineStart;\n      _lineIndent = state.lineIndent;\n      skipSeparationSpace(state, false, -1);\n\n      if (state.lineIndent >= nodeIndent) {\n        hasPendingContent = true;\n        ch = state.input.charCodeAt(state.position);\n        continue;\n      } else {\n        state.position = captureEnd;\n        state.line = _line;\n        state.lineStart = _lineStart;\n        state.lineIndent = _lineIndent;\n        break;\n      }\n    }\n\n    if (hasPendingContent) {\n      captureSegment(state, captureStart, captureEnd, false);\n      writeFoldedLines(state, state.line - _line);\n      captureStart = captureEnd = state.position;\n      hasPendingContent = false;\n    }\n\n    if (!is_WHITE_SPACE(ch)) {\n      captureEnd = state.position + 1;\n    }\n\n    ch = state.input.charCodeAt(++state.position);\n  }\n\n  captureSegment(state, captureStart, captureEnd, false);\n\n  if (state.result) {\n    return true;\n  }\n\n  state.kind = _kind;\n  state.result = _result;\n  return false;\n}\n\nfunction readSingleQuotedScalar(state, nodeIndent) {\n  var ch,\n      captureStart, captureEnd;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (ch !== 0x27/* ' */) {\n    return false;\n  }\n\n  state.kind = 'scalar';\n  state.result = '';\n  state.position++;\n  captureStart = captureEnd = state.position;\n\n  while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n    if (ch === 0x27/* ' */) {\n      captureSegment(state, captureStart, state.position, true);\n      ch = state.input.charCodeAt(++state.position);\n\n      if (ch === 0x27/* ' */) {\n        captureStart = state.position;\n        state.position++;\n        captureEnd = state.position;\n      } else {\n        return true;\n      }\n\n    } else if (is_EOL(ch)) {\n      captureSegment(state, captureStart, captureEnd, true);\n      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n      captureStart = captureEnd = state.position;\n\n    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n      throwError(state, 'unexpected end of the document within a single quoted scalar');\n\n    } else {\n      state.position++;\n      captureEnd = state.position;\n    }\n  }\n\n  throwError(state, 'unexpected end of the stream within a single quoted scalar');\n}\n\nfunction readDoubleQuotedScalar(state, nodeIndent) {\n  var captureStart,\n      captureEnd,\n      hexLength,\n      hexResult,\n      tmp,\n      ch;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (ch !== 0x22/* \" */) {\n    return false;\n  }\n\n  state.kind = 'scalar';\n  state.result = '';\n  state.position++;\n  captureStart = captureEnd = state.position;\n\n  while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n    if (ch === 0x22/* \" */) {\n      captureSegment(state, captureStart, state.position, true);\n      state.position++;\n      return true;\n\n    } else if (ch === 0x5C/* \\ */) {\n      captureSegment(state, captureStart, state.position, true);\n      ch = state.input.charCodeAt(++state.position);\n\n      if (is_EOL(ch)) {\n        skipSeparationSpace(state, false, nodeIndent);\n\n        // TODO: rework to inline fn with no type cast?\n      } else if (ch < 256 && simpleEscapeCheck[ch]) {\n        state.result += simpleEscapeMap[ch];\n        state.position++;\n\n      } else if ((tmp = escapedHexLen(ch)) > 0) {\n        hexLength = tmp;\n        hexResult = 0;\n\n        for (; hexLength > 0; hexLength--) {\n          ch = state.input.charCodeAt(++state.position);\n\n          if ((tmp = fromHexCode(ch)) >= 0) {\n            hexResult = (hexResult << 4) + tmp;\n\n          } else {\n            throwError(state, 'expected hexadecimal character');\n          }\n        }\n\n        state.result += charFromCodepoint(hexResult);\n\n        state.position++;\n\n      } else {\n        throwError(state, 'unknown escape sequence');\n      }\n\n      captureStart = captureEnd = state.position;\n\n    } else if (is_EOL(ch)) {\n      captureSegment(state, captureStart, captureEnd, true);\n      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));\n      captureStart = captureEnd = state.position;\n\n    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n      throwError(state, 'unexpected end of the document within a double quoted scalar');\n\n    } else {\n      state.position++;\n      captureEnd = state.position;\n    }\n  }\n\n  throwError(state, 'unexpected end of the stream within a double quoted scalar');\n}\n\nfunction readFlowCollection(state, nodeIndent) {\n  var readNext = true,\n      _line,\n      _tag     = state.tag,\n      _result,\n      _anchor  = state.anchor,\n      following,\n      terminator,\n      isPair,\n      isExplicitPair,\n      isMapping,\n      overridableKeys = {},\n      keyNode,\n      keyTag,\n      valueNode,\n      ch;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (ch === 0x5B/* [ */) {\n    terminator = 0x5D;/* ] */\n    isMapping = false;\n    _result = [];\n  } else if (ch === 0x7B/* { */) {\n    terminator = 0x7D;/* } */\n    isMapping = true;\n    _result = {};\n  } else {\n    return false;\n  }\n\n  if (state.anchor !== null) {\n    state.anchorMap[state.anchor] = _result;\n  }\n\n  ch = state.input.charCodeAt(++state.position);\n\n  while (ch !== 0) {\n    skipSeparationSpace(state, true, nodeIndent);\n\n    ch = state.input.charCodeAt(state.position);\n\n    if (ch === terminator) {\n      state.position++;\n      state.tag = _tag;\n      state.anchor = _anchor;\n      state.kind = isMapping ? 'mapping' : 'sequence';\n      state.result = _result;\n      return true;\n    } else if (!readNext) {\n      throwError(state, 'missed comma between flow collection entries');\n    }\n\n    keyTag = keyNode = valueNode = null;\n    isPair = isExplicitPair = false;\n\n    if (ch === 0x3F/* ? */) {\n      following = state.input.charCodeAt(state.position + 1);\n\n      if (is_WS_OR_EOL(following)) {\n        isPair = isExplicitPair = true;\n        state.position++;\n        skipSeparationSpace(state, true, nodeIndent);\n      }\n    }\n\n    _line = state.line;\n    composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n    keyTag = state.tag;\n    keyNode = state.result;\n    skipSeparationSpace(state, true, nodeIndent);\n\n    ch = state.input.charCodeAt(state.position);\n\n    if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {\n      isPair = true;\n      ch = state.input.charCodeAt(++state.position);\n      skipSeparationSpace(state, true, nodeIndent);\n      composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);\n      valueNode = state.result;\n    }\n\n    if (isMapping) {\n      storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);\n    } else if (isPair) {\n      _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));\n    } else {\n      _result.push(keyNode);\n    }\n\n    skipSeparationSpace(state, true, nodeIndent);\n\n    ch = state.input.charCodeAt(state.position);\n\n    if (ch === 0x2C/* , */) {\n      readNext = true;\n      ch = state.input.charCodeAt(++state.position);\n    } else {\n      readNext = false;\n    }\n  }\n\n  throwError(state, 'unexpected end of the stream within a flow collection');\n}\n\nfunction readBlockScalar(state, nodeIndent) {\n  var captureStart,\n      folding,\n      chomping       = CHOMPING_CLIP,\n      didReadContent = false,\n      detectedIndent = false,\n      textIndent     = nodeIndent,\n      emptyLines     = 0,\n      atMoreIndented = false,\n      tmp,\n      ch;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (ch === 0x7C/* | */) {\n    folding = false;\n  } else if (ch === 0x3E/* > */) {\n    folding = true;\n  } else {\n    return false;\n  }\n\n  state.kind = 'scalar';\n  state.result = '';\n\n  while (ch !== 0) {\n    ch = state.input.charCodeAt(++state.position);\n\n    if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {\n      if (CHOMPING_CLIP === chomping) {\n        chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;\n      } else {\n        throwError(state, 'repeat of a chomping mode identifier');\n      }\n\n    } else if ((tmp = fromDecimalCode(ch)) >= 0) {\n      if (tmp === 0) {\n        throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');\n      } else if (!detectedIndent) {\n        textIndent = nodeIndent + tmp - 1;\n        detectedIndent = true;\n      } else {\n        throwError(state, 'repeat of an indentation width identifier');\n      }\n\n    } else {\n      break;\n    }\n  }\n\n  if (is_WHITE_SPACE(ch)) {\n    do { ch = state.input.charCodeAt(++state.position); }\n    while (is_WHITE_SPACE(ch));\n\n    if (ch === 0x23/* # */) {\n      do { ch = state.input.charCodeAt(++state.position); }\n      while (!is_EOL(ch) && (ch !== 0));\n    }\n  }\n\n  while (ch !== 0) {\n    readLineBreak(state);\n    state.lineIndent = 0;\n\n    ch = state.input.charCodeAt(state.position);\n\n    while ((!detectedIndent || state.lineIndent < textIndent) &&\n           (ch === 0x20/* Space */)) {\n      state.lineIndent++;\n      ch = state.input.charCodeAt(++state.position);\n    }\n\n    if (!detectedIndent && state.lineIndent > textIndent) {\n      textIndent = state.lineIndent;\n    }\n\n    if (is_EOL(ch)) {\n      emptyLines++;\n      continue;\n    }\n\n    // End of the scalar.\n    if (state.lineIndent < textIndent) {\n\n      // Perform the chomping.\n      if (chomping === CHOMPING_KEEP) {\n        state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n      } else if (chomping === CHOMPING_CLIP) {\n        if (didReadContent) { // i.e. only if the scalar is not empty.\n          state.result += '\\n';\n        }\n      }\n\n      // Break this `while` cycle and go to the funciton's epilogue.\n      break;\n    }\n\n    // Folded style: use fancy rules to handle line breaks.\n    if (folding) {\n\n      // Lines starting with white space characters (more-indented lines) are not folded.\n      if (is_WHITE_SPACE(ch)) {\n        atMoreIndented = true;\n        // except for the first content line (cf. Example 8.1)\n        state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n\n      // End of more-indented block.\n      } else if (atMoreIndented) {\n        atMoreIndented = false;\n        state.result += common.repeat('\\n', emptyLines + 1);\n\n      // Just one line break - perceive as the same line.\n      } else if (emptyLines === 0) {\n        if (didReadContent) { // i.e. only if we have already read some scalar content.\n          state.result += ' ';\n        }\n\n      // Several line breaks - perceive as different lines.\n      } else {\n        state.result += common.repeat('\\n', emptyLines);\n      }\n\n    // Literal style: just add exact number of line breaks between content lines.\n    } else {\n      // Keep all line breaks except the header line break.\n      state.result += common.repeat('\\n', didReadContent ? 1 + emptyLines : emptyLines);\n    }\n\n    didReadContent = true;\n    detectedIndent = true;\n    emptyLines = 0;\n    captureStart = state.position;\n\n    while (!is_EOL(ch) && (ch !== 0)) {\n      ch = state.input.charCodeAt(++state.position);\n    }\n\n    captureSegment(state, captureStart, state.position, false);\n  }\n\n  return true;\n}\n\nfunction readBlockSequence(state, nodeIndent) {\n  var _line,\n      _tag      = state.tag,\n      _anchor   = state.anchor,\n      _result   = [],\n      following,\n      detected  = false,\n      ch;\n\n  if (state.anchor !== null) {\n    state.anchorMap[state.anchor] = _result;\n  }\n\n  ch = state.input.charCodeAt(state.position);\n\n  while (ch !== 0) {\n\n    if (ch !== 0x2D/* - */) {\n      break;\n    }\n\n    following = state.input.charCodeAt(state.position + 1);\n\n    if (!is_WS_OR_EOL(following)) {\n      break;\n    }\n\n    detected = true;\n    state.position++;\n\n    if (skipSeparationSpace(state, true, -1)) {\n      if (state.lineIndent <= nodeIndent) {\n        _result.push(null);\n        ch = state.input.charCodeAt(state.position);\n        continue;\n      }\n    }\n\n    _line = state.line;\n    composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);\n    _result.push(state.result);\n    skipSeparationSpace(state, true, -1);\n\n    ch = state.input.charCodeAt(state.position);\n\n    if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {\n      throwError(state, 'bad indentation of a sequence entry');\n    } else if (state.lineIndent < nodeIndent) {\n      break;\n    }\n  }\n\n  if (detected) {\n    state.tag = _tag;\n    state.anchor = _anchor;\n    state.kind = 'sequence';\n    state.result = _result;\n    return true;\n  }\n  return false;\n}\n\nfunction readBlockMapping(state, nodeIndent, flowIndent) {\n  var following,\n      allowCompact,\n      _line,\n      _pos,\n      _tag          = state.tag,\n      _anchor       = state.anchor,\n      _result       = {},\n      overridableKeys = {},\n      keyTag        = null,\n      keyNode       = null,\n      valueNode     = null,\n      atExplicitKey = false,\n      detected      = false,\n      ch;\n\n  if (state.anchor !== null) {\n    state.anchorMap[state.anchor] = _result;\n  }\n\n  ch = state.input.charCodeAt(state.position);\n\n  while (ch !== 0) {\n    following = state.input.charCodeAt(state.position + 1);\n    _line = state.line; // Save the current line.\n    _pos = state.position;\n\n    //\n    // Explicit notation case. There are two separate blocks:\n    // first for the key (denoted by \"?\") and second for the value (denoted by \":\")\n    //\n    if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {\n\n      if (ch === 0x3F/* ? */) {\n        if (atExplicitKey) {\n          storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n          keyTag = keyNode = valueNode = null;\n        }\n\n        detected = true;\n        atExplicitKey = true;\n        allowCompact = true;\n\n      } else if (atExplicitKey) {\n        // i.e. 0x3A/* : */ === character after the explicit key.\n        atExplicitKey = false;\n        allowCompact = true;\n\n      } else {\n        throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');\n      }\n\n      state.position += 1;\n      ch = following;\n\n    //\n    // Implicit notation case. Flow-style node as the key first, then \":\", and the value.\n    //\n    } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n\n      if (state.line === _line) {\n        ch = state.input.charCodeAt(state.position);\n\n        while (is_WHITE_SPACE(ch)) {\n          ch = state.input.charCodeAt(++state.position);\n        }\n\n        if (ch === 0x3A/* : */) {\n          ch = state.input.charCodeAt(++state.position);\n\n          if (!is_WS_OR_EOL(ch)) {\n            throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');\n          }\n\n          if (atExplicitKey) {\n            storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n            keyTag = keyNode = valueNode = null;\n          }\n\n          detected = true;\n          atExplicitKey = false;\n          allowCompact = false;\n          keyTag = state.tag;\n          keyNode = state.result;\n\n        } else if (detected) {\n          throwError(state, 'can not read an implicit mapping pair; a colon is missed');\n\n        } else {\n          state.tag = _tag;\n          state.anchor = _anchor;\n          return true; // Keep the result of `composeNode`.\n        }\n\n      } else if (detected) {\n        throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');\n\n      } else {\n        state.tag = _tag;\n        state.anchor = _anchor;\n        return true; // Keep the result of `composeNode`.\n      }\n\n    } else {\n      break; // Reading is done. Go to the epilogue.\n    }\n\n    //\n    // Common reading code for both explicit and implicit notations.\n    //\n    if (state.line === _line || state.lineIndent > nodeIndent) {\n      if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {\n        if (atExplicitKey) {\n          keyNode = state.result;\n        } else {\n          valueNode = state.result;\n        }\n      }\n\n      if (!atExplicitKey) {\n        storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);\n        keyTag = keyNode = valueNode = null;\n      }\n\n      skipSeparationSpace(state, true, -1);\n      ch = state.input.charCodeAt(state.position);\n    }\n\n    if (state.lineIndent > nodeIndent && (ch !== 0)) {\n      throwError(state, 'bad indentation of a mapping entry');\n    } else if (state.lineIndent < nodeIndent) {\n      break;\n    }\n  }\n\n  //\n  // Epilogue.\n  //\n\n  // Special case: last mapping's node contains only the key in explicit notation.\n  if (atExplicitKey) {\n    storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);\n  }\n\n  // Expose the resulting mapping.\n  if (detected) {\n    state.tag = _tag;\n    state.anchor = _anchor;\n    state.kind = 'mapping';\n    state.result = _result;\n  }\n\n  return detected;\n}\n\nfunction readTagProperty(state) {\n  var _position,\n      isVerbatim = false,\n      isNamed    = false,\n      tagHandle,\n      tagName,\n      ch;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (ch !== 0x21/* ! */) return false;\n\n  if (state.tag !== null) {\n    throwError(state, 'duplication of a tag property');\n  }\n\n  ch = state.input.charCodeAt(++state.position);\n\n  if (ch === 0x3C/* < */) {\n    isVerbatim = true;\n    ch = state.input.charCodeAt(++state.position);\n\n  } else if (ch === 0x21/* ! */) {\n    isNamed = true;\n    tagHandle = '!!';\n    ch = state.input.charCodeAt(++state.position);\n\n  } else {\n    tagHandle = '!';\n  }\n\n  _position = state.position;\n\n  if (isVerbatim) {\n    do { ch = state.input.charCodeAt(++state.position); }\n    while (ch !== 0 && ch !== 0x3E/* > */);\n\n    if (state.position < state.length) {\n      tagName = state.input.slice(_position, state.position);\n      ch = state.input.charCodeAt(++state.position);\n    } else {\n      throwError(state, 'unexpected end of the stream within a verbatim tag');\n    }\n  } else {\n    while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n\n      if (ch === 0x21/* ! */) {\n        if (!isNamed) {\n          tagHandle = state.input.slice(_position - 1, state.position + 1);\n\n          if (!PATTERN_TAG_HANDLE.test(tagHandle)) {\n            throwError(state, 'named tag handle cannot contain such characters');\n          }\n\n          isNamed = true;\n          _position = state.position + 1;\n        } else {\n          throwError(state, 'tag suffix cannot contain exclamation marks');\n        }\n      }\n\n      ch = state.input.charCodeAt(++state.position);\n    }\n\n    tagName = state.input.slice(_position, state.position);\n\n    if (PATTERN_FLOW_INDICATORS.test(tagName)) {\n      throwError(state, 'tag suffix cannot contain flow indicator characters');\n    }\n  }\n\n  if (tagName && !PATTERN_TAG_URI.test(tagName)) {\n    throwError(state, 'tag name cannot contain such characters: ' + tagName);\n  }\n\n  if (isVerbatim) {\n    state.tag = tagName;\n\n  } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {\n    state.tag = state.tagMap[tagHandle] + tagName;\n\n  } else if (tagHandle === '!') {\n    state.tag = '!' + tagName;\n\n  } else if (tagHandle === '!!') {\n    state.tag = 'tag:yaml.org,2002:' + tagName;\n\n  } else {\n    throwError(state, 'undeclared tag handle \"' + tagHandle + '\"');\n  }\n\n  return true;\n}\n\nfunction readAnchorProperty(state) {\n  var _position,\n      ch;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (ch !== 0x26/* & */) return false;\n\n  if (state.anchor !== null) {\n    throwError(state, 'duplication of an anchor property');\n  }\n\n  ch = state.input.charCodeAt(++state.position);\n  _position = state.position;\n\n  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n    ch = state.input.charCodeAt(++state.position);\n  }\n\n  if (state.position === _position) {\n    throwError(state, 'name of an anchor node must contain at least one character');\n  }\n\n  state.anchor = state.input.slice(_position, state.position);\n  return true;\n}\n\nfunction readAlias(state) {\n  var _position, alias,\n      ch;\n\n  ch = state.input.charCodeAt(state.position);\n\n  if (ch !== 0x2A/* * */) return false;\n\n  ch = state.input.charCodeAt(++state.position);\n  _position = state.position;\n\n  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {\n    ch = state.input.charCodeAt(++state.position);\n  }\n\n  if (state.position === _position) {\n    throwError(state, 'name of an alias node must contain at least one character');\n  }\n\n  alias = state.input.slice(_position, state.position);\n\n  if (!_hasOwnProperty.call(state.anchorMap, alias)) {\n    throwError(state, 'unidentified alias \"' + alias + '\"');\n  }\n\n  state.result = state.anchorMap[alias];\n  skipSeparationSpace(state, true, -1);\n  return true;\n}\n\nfunction composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {\n  var allowBlockStyles,\n      allowBlockScalars,\n      allowBlockCollections,\n      indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent\n      atNewLine  = false,\n      hasContent = false,\n      typeIndex,\n      typeQuantity,\n      type,\n      flowIndent,\n      blockIndent;\n\n  if (state.listener !== null) {\n    state.listener('open', state);\n  }\n\n  state.tag    = null;\n  state.anchor = null;\n  state.kind   = null;\n  state.result = null;\n\n  allowBlockStyles = allowBlockScalars = allowBlockCollections =\n    CONTEXT_BLOCK_OUT === nodeContext ||\n    CONTEXT_BLOCK_IN  === nodeContext;\n\n  if (allowToSeek) {\n    if (skipSeparationSpace(state, true, -1)) {\n      atNewLine = true;\n\n      if (state.lineIndent > parentIndent) {\n        indentStatus = 1;\n      } else if (state.lineIndent === parentIndent) {\n        indentStatus = 0;\n      } else if (state.lineIndent < parentIndent) {\n        indentStatus = -1;\n      }\n    }\n  }\n\n  if (indentStatus === 1) {\n    while (readTagProperty(state) || readAnchorProperty(state)) {\n      if (skipSeparationSpace(state, true, -1)) {\n        atNewLine = true;\n        allowBlockCollections = allowBlockStyles;\n\n        if (state.lineIndent > parentIndent) {\n          indentStatus = 1;\n        } else if (state.lineIndent === parentIndent) {\n          indentStatus = 0;\n        } else if (state.lineIndent < parentIndent) {\n          indentStatus = -1;\n        }\n      } else {\n        allowBlockCollections = false;\n      }\n    }\n  }\n\n  if (allowBlockCollections) {\n    allowBlockCollections = atNewLine || allowCompact;\n  }\n\n  if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {\n    if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {\n      flowIndent = parentIndent;\n    } else {\n      flowIndent = parentIndent + 1;\n    }\n\n    blockIndent = state.position - state.lineStart;\n\n    if (indentStatus === 1) {\n      if (allowBlockCollections &&\n          (readBlockSequence(state, blockIndent) ||\n           readBlockMapping(state, blockIndent, flowIndent)) ||\n          readFlowCollection(state, flowIndent)) {\n        hasContent = true;\n      } else {\n        if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||\n            readSingleQuotedScalar(state, flowIndent) ||\n            readDoubleQuotedScalar(state, flowIndent)) {\n          hasContent = true;\n\n        } else if (readAlias(state)) {\n          hasContent = true;\n\n          if (state.tag !== null || state.anchor !== null) {\n            throwError(state, 'alias node should not have any properties');\n          }\n\n        } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {\n          hasContent = true;\n\n          if (state.tag === null) {\n            state.tag = '?';\n          }\n        }\n\n        if (state.anchor !== null) {\n          state.anchorMap[state.anchor] = state.result;\n        }\n      }\n    } else if (indentStatus === 0) {\n      // Special case: block sequences are allowed to have same indentation level as the parent.\n      // http://www.yaml.org/spec/1.2/spec.html#id2799784\n      hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);\n    }\n  }\n\n  if (state.tag !== null && state.tag !== '!') {\n    if (state.tag === '?') {\n      // Implicit resolving is not allowed for non-scalar types, and '?'\n      // non-specific tag is only automatically assigned to plain scalars.\n      //\n      // We only need to check kind conformity in case user explicitly assigns '?'\n      // tag, for example like this: \"!<?> [0]\"\n      //\n      if (state.result !== null && state.kind !== 'scalar') {\n        throwError(state, 'unacceptable node kind for !<?> tag; it should be \"scalar\", not \"' + state.kind + '\"');\n      }\n\n      for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {\n        type = state.implicitTypes[typeIndex];\n\n        if (type.resolve(state.result)) { // `state.result` updated in resolver if matched\n          state.result = type.construct(state.result);\n          state.tag = type.tag;\n          if (state.anchor !== null) {\n            state.anchorMap[state.anchor] = state.result;\n          }\n          break;\n        }\n      }\n    } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {\n      type = state.typeMap[state.kind || 'fallback'][state.tag];\n\n      if (state.result !== null && type.kind !== state.kind) {\n        throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be \"' + type.kind + '\", not \"' + state.kind + '\"');\n      }\n\n      if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched\n        throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');\n      } else {\n        state.result = type.construct(state.result);\n        if (state.anchor !== null) {\n          state.anchorMap[state.anchor] = state.result;\n        }\n      }\n    } else {\n      throwError(state, 'unknown tag !<' + state.tag + '>');\n    }\n  }\n\n  if (state.listener !== null) {\n    state.listener('close', state);\n  }\n  return state.tag !== null ||  state.anchor !== null || hasContent;\n}\n\nfunction readDocument(state) {\n  var documentStart = state.position,\n      _position,\n      directiveName,\n      directiveArgs,\n      hasDirectives = false,\n      ch;\n\n  state.version = null;\n  state.checkLineBreaks = state.legacy;\n  state.tagMap = {};\n  state.anchorMap = {};\n\n  while ((ch = state.input.charCodeAt(state.position)) !== 0) {\n    skipSeparationSpace(state, true, -1);\n\n    ch = state.input.charCodeAt(state.position);\n\n    if (state.lineIndent > 0 || ch !== 0x25/* % */) {\n      break;\n    }\n\n    hasDirectives = true;\n    ch = state.input.charCodeAt(++state.position);\n    _position = state.position;\n\n    while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n      ch = state.input.charCodeAt(++state.position);\n    }\n\n    directiveName = state.input.slice(_position, state.position);\n    directiveArgs = [];\n\n    if (directiveName.length < 1) {\n      throwError(state, 'directive name must not be less than one character in length');\n    }\n\n    while (ch !== 0) {\n      while (is_WHITE_SPACE(ch)) {\n        ch = state.input.charCodeAt(++state.position);\n      }\n\n      if (ch === 0x23/* # */) {\n        do { ch = state.input.charCodeAt(++state.position); }\n        while (ch !== 0 && !is_EOL(ch));\n        break;\n      }\n\n      if (is_EOL(ch)) break;\n\n      _position = state.position;\n\n      while (ch !== 0 && !is_WS_OR_EOL(ch)) {\n        ch = state.input.charCodeAt(++state.position);\n      }\n\n      directiveArgs.push(state.input.slice(_position, state.position));\n    }\n\n    if (ch !== 0) readLineBreak(state);\n\n    if (_hasOwnProperty.call(directiveHandlers, directiveName)) {\n      directiveHandlers[directiveName](state, directiveName, directiveArgs);\n    } else {\n      throwWarning(state, 'unknown document directive \"' + directiveName + '\"');\n    }\n  }\n\n  skipSeparationSpace(state, true, -1);\n\n  if (state.lineIndent === 0 &&\n      state.input.charCodeAt(state.position)     === 0x2D/* - */ &&\n      state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n      state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {\n    state.position += 3;\n    skipSeparationSpace(state, true, -1);\n\n  } else if (hasDirectives) {\n    throwError(state, 'directives end mark is expected');\n  }\n\n  composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);\n  skipSeparationSpace(state, true, -1);\n\n  if (state.checkLineBreaks &&\n      PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {\n    throwWarning(state, 'non-ASCII line breaks are interpreted as content');\n  }\n\n  state.documents.push(state.result);\n\n  if (state.position === state.lineStart && testDocumentSeparator(state)) {\n\n    if (state.input.charCodeAt(state.position) === 0x2E/* . */) {\n      state.position += 3;\n      skipSeparationSpace(state, true, -1);\n    }\n    return;\n  }\n\n  if (state.position < (state.length - 1)) {\n    throwError(state, 'end of the stream or a document separator is expected');\n  } else {\n    return;\n  }\n}\n\n\nfunction loadDocuments(input, options) {\n  input = String(input);\n  options = options || {};\n\n  if (input.length !== 0) {\n\n    // Add tailing `\\n` if not exists\n    if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&\n        input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {\n      input += '\\n';\n    }\n\n    // Strip BOM\n    if (input.charCodeAt(0) === 0xFEFF) {\n      input = input.slice(1);\n    }\n  }\n\n  var state = new State(input, options);\n\n  var nullpos = input.indexOf('\\0');\n\n  if (nullpos !== -1) {\n    state.position = nullpos;\n    throwError(state, 'null byte is not allowed in input');\n  }\n\n  // Use 0 as string terminator. That significantly simplifies bounds check.\n  state.input += '\\0';\n\n  while (state.input.charCodeAt(state.position) === 0x20/* Space */) {\n    state.lineIndent += 1;\n    state.position += 1;\n  }\n\n  while (state.position < (state.length - 1)) {\n    readDocument(state);\n  }\n\n  return state.documents;\n}\n\n\nfunction loadAll(input, iterator, options) {\n  if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {\n    options = iterator;\n    iterator = null;\n  }\n\n  var documents = loadDocuments(input, options);\n\n  if (typeof iterator !== 'function') {\n    return documents;\n  }\n\n  for (var index = 0, length = documents.length; index < length; index += 1) {\n    iterator(documents[index]);\n  }\n}\n\n\nfunction load(input, options) {\n  var documents = loadDocuments(input, options);\n\n  if (documents.length === 0) {\n    /*eslint-disable no-undefined*/\n    return undefined;\n  } else if (documents.length === 1) {\n    return documents[0];\n  }\n  throw new YAMLException('expected a single document in the stream, but found more');\n}\n\n\nfunction safeLoadAll(input, iterator, options) {\n  if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') {\n    options = iterator;\n    iterator = null;\n  }\n\n  return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\n\nfunction safeLoad(input, options) {\n  return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\n\nmodule.exports.loadAll     = loadAll;\nmodule.exports.load        = load;\nmodule.exports.safeLoadAll = safeLoadAll;\nmodule.exports.safeLoad    = safeLoad;\n", "'use strict';\n\n/*eslint-disable no-use-before-define*/\n\nvar common              = require('./common');\nvar YAMLException       = require('./exception');\nvar DEFAULT_FULL_SCHEMA = require('./schema/default_full');\nvar DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');\n\nvar _toString       = Object.prototype.toString;\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar CHAR_TAB                  = 0x09; /* Tab */\nvar CHAR_LINE_FEED            = 0x0A; /* LF */\nvar CHAR_CARRIAGE_RETURN      = 0x0D; /* CR */\nvar CHAR_SPACE                = 0x20; /* Space */\nvar CHAR_EXCLAMATION          = 0x21; /* ! */\nvar CHAR_DOUBLE_QUOTE         = 0x22; /* \" */\nvar CHAR_SHARP                = 0x23; /* # */\nvar CHAR_PERCENT              = 0x25; /* % */\nvar CHAR_AMPERSAND            = 0x26; /* & */\nvar CHAR_SINGLE_QUOTE         = 0x27; /* ' */\nvar CHAR_ASTERISK             = 0x2A; /* * */\nvar CHAR_COMMA                = 0x2C; /* , */\nvar CHAR_MINUS                = 0x2D; /* - */\nvar CHAR_COLON                = 0x3A; /* : */\nvar CHAR_EQUALS               = 0x3D; /* = */\nvar CHAR_GREATER_THAN         = 0x3E; /* > */\nvar CHAR_QUESTION             = 0x3F; /* ? */\nvar CHAR_COMMERCIAL_AT        = 0x40; /* @ */\nvar CHAR_LEFT_SQUARE_BRACKET  = 0x5B; /* [ */\nvar CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */\nvar CHAR_GRAVE_ACCENT         = 0x60; /* ` */\nvar CHAR_LEFT_CURLY_BRACKET   = 0x7B; /* { */\nvar CHAR_VERTICAL_LINE        = 0x7C; /* | */\nvar CHAR_RIGHT_CURLY_BRACKET  = 0x7D; /* } */\n\nvar ESCAPE_SEQUENCES = {};\n\nESCAPE_SEQUENCES[0x00]   = '\\\\0';\nESCAPE_SEQUENCES[0x07]   = '\\\\a';\nESCAPE_SEQUENCES[0x08]   = '\\\\b';\nESCAPE_SEQUENCES[0x09]   = '\\\\t';\nESCAPE_SEQUENCES[0x0A]   = '\\\\n';\nESCAPE_SEQUENCES[0x0B]   = '\\\\v';\nESCAPE_SEQUENCES[0x0C]   = '\\\\f';\nESCAPE_SEQUENCES[0x0D]   = '\\\\r';\nESCAPE_SEQUENCES[0x1B]   = '\\\\e';\nESCAPE_SEQUENCES[0x22]   = '\\\\\"';\nESCAPE_SEQUENCES[0x5C]   = '\\\\\\\\';\nESCAPE_SEQUENCES[0x85]   = '\\\\N';\nESCAPE_SEQUENCES[0xA0]   = '\\\\_';\nESCAPE_SEQUENCES[0x2028] = '\\\\L';\nESCAPE_SEQUENCES[0x2029] = '\\\\P';\n\nvar DEPRECATED_BOOLEANS_SYNTAX = [\n  'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',\n  'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'\n];\n\nfunction compileStyleMap(schema, map) {\n  var result, keys, index, length, tag, style, type;\n\n  if (map === null) return {};\n\n  result = {};\n  keys = Object.keys(map);\n\n  for (index = 0, length = keys.length; index < length; index += 1) {\n    tag = keys[index];\n    style = String(map[tag]);\n\n    if (tag.slice(0, 2) === '!!') {\n      tag = 'tag:yaml.org,2002:' + tag.slice(2);\n    }\n    type = schema.compiledTypeMap['fallback'][tag];\n\n    if (type && _hasOwnProperty.call(type.styleAliases, style)) {\n      style = type.styleAliases[style];\n    }\n\n    result[tag] = style;\n  }\n\n  return result;\n}\n\nfunction encodeHex(character) {\n  var string, handle, length;\n\n  string = character.toString(16).toUpperCase();\n\n  if (character <= 0xFF) {\n    handle = 'x';\n    length = 2;\n  } else if (character <= 0xFFFF) {\n    handle = 'u';\n    length = 4;\n  } else if (character <= 0xFFFFFFFF) {\n    handle = 'U';\n    length = 8;\n  } else {\n    throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');\n  }\n\n  return '\\\\' + handle + common.repeat('0', length - string.length) + string;\n}\n\nfunction State(options) {\n  this.schema        = options['schema'] || DEFAULT_FULL_SCHEMA;\n  this.indent        = Math.max(1, (options['indent'] || 2));\n  this.noArrayIndent = options['noArrayIndent'] || false;\n  this.skipInvalid   = options['skipInvalid'] || false;\n  this.flowLevel     = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);\n  this.styleMap      = compileStyleMap(this.schema, options['styles'] || null);\n  this.sortKeys      = options['sortKeys'] || false;\n  this.lineWidth     = options['lineWidth'] || 80;\n  this.noRefs        = options['noRefs'] || false;\n  this.noCompatMode  = options['noCompatMode'] || false;\n  this.condenseFlow  = options['condenseFlow'] || false;\n\n  this.implicitTypes = this.schema.compiledImplicit;\n  this.explicitTypes = this.schema.compiledExplicit;\n\n  this.tag = null;\n  this.result = '';\n\n  this.duplicates = [];\n  this.usedDuplicates = null;\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString(string, spaces) {\n  var ind = common.repeat(' ', spaces),\n      position = 0,\n      next = -1,\n      result = '',\n      line,\n      length = string.length;\n\n  while (position < length) {\n    next = string.indexOf('\\n', position);\n    if (next === -1) {\n      line = string.slice(position);\n      position = length;\n    } else {\n      line = string.slice(position, next + 1);\n      position = next + 1;\n    }\n\n    if (line.length && line !== '\\n') result += ind;\n\n    result += line;\n  }\n\n  return result;\n}\n\nfunction generateNextLine(state, level) {\n  return '\\n' + common.repeat(' ', state.indent * level);\n}\n\nfunction testImplicitResolving(state, str) {\n  var index, length, type;\n\n  for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {\n    type = state.implicitTypes[index];\n\n    if (type.resolve(str)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace(c) {\n  return c === CHAR_SPACE || c === CHAR_TAB;\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn\u2019t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable(c) {\n  return  (0x00020 <= c && c <= 0x00007E)\n      || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)\n      || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */)\n      ||  (0x10000 <= c && c <= 0x10FFFF);\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char  ::= b-line-feed | b-carriage-return\n// [24] b-line-feed       ::=     #xA    /* LF */\n// [25] b-carriage-return ::=     #xD    /* CR */\n// [3]  c-byte-order-mark ::=     #xFEFF\nfunction isNsChar(c) {\n  return isPrintable(c) && !isWhitespace(c)\n    // byte-order-mark\n    && c !== 0xFEFF\n    // b-char\n    && c !== CHAR_CARRIAGE_RETURN\n    && c !== CHAR_LINE_FEED;\n}\n\n// Simplified test for values allowed after the first character in plain style.\nfunction isPlainSafe(c, prev) {\n  // Uses a subset of nb-char - c-flow-indicator - \":\" - \"#\"\n  // where nb-char ::= c-printable - b-char - c-byte-order-mark.\n  return isPrintable(c) && c !== 0xFEFF\n    // - c-flow-indicator\n    && c !== CHAR_COMMA\n    && c !== CHAR_LEFT_SQUARE_BRACKET\n    && c !== CHAR_RIGHT_SQUARE_BRACKET\n    && c !== CHAR_LEFT_CURLY_BRACKET\n    && c !== CHAR_RIGHT_CURLY_BRACKET\n    // - \":\" - \"#\"\n    // /* An ns-char preceding */ \"#\"\n    && c !== CHAR_COLON\n    && ((c !== CHAR_SHARP) || (prev && isNsChar(prev)));\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst(c) {\n  // Uses a subset of ns-char - c-indicator\n  // where ns-char = nb-char - s-white.\n  return isPrintable(c) && c !== 0xFEFF\n    && !isWhitespace(c) // - s-white\n    // - (c-indicator ::=\n    // \u201C-\u201D | \u201C?\u201D | \u201C:\u201D | \u201C,\u201D | \u201C[\u201D | \u201C]\u201D | \u201C{\u201D | \u201C}\u201D\n    && c !== CHAR_MINUS\n    && c !== CHAR_QUESTION\n    && c !== CHAR_COLON\n    && c !== CHAR_COMMA\n    && c !== CHAR_LEFT_SQUARE_BRACKET\n    && c !== CHAR_RIGHT_SQUARE_BRACKET\n    && c !== CHAR_LEFT_CURLY_BRACKET\n    && c !== CHAR_RIGHT_CURLY_BRACKET\n    // | \u201C#\u201D | \u201C&\u201D | \u201C*\u201D | \u201C!\u201D | \u201C|\u201D | \u201C=\u201D | \u201C>\u201D | \u201C'\u201D | \u201C\"\u201D\n    && c !== CHAR_SHARP\n    && c !== CHAR_AMPERSAND\n    && c !== CHAR_ASTERISK\n    && c !== CHAR_EXCLAMATION\n    && c !== CHAR_VERTICAL_LINE\n    && c !== CHAR_EQUALS\n    && c !== CHAR_GREATER_THAN\n    && c !== CHAR_SINGLE_QUOTE\n    && c !== CHAR_DOUBLE_QUOTE\n    // | \u201C%\u201D | \u201C@\u201D | \u201C`\u201D)\n    && c !== CHAR_PERCENT\n    && c !== CHAR_COMMERCIAL_AT\n    && c !== CHAR_GRAVE_ACCENT;\n}\n\n// Determines whether block indentation indicator is required.\nfunction needIndentIndicator(string) {\n  var leadingSpaceRe = /^\\n* /;\n  return leadingSpaceRe.test(string);\n}\n\nvar STYLE_PLAIN   = 1,\n    STYLE_SINGLE  = 2,\n    STYLE_LITERAL = 3,\n    STYLE_FOLDED  = 4,\n    STYLE_DOUBLE  = 5;\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n//    STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n//    STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n//    STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {\n  var i;\n  var char, prev_char;\n  var hasLineBreak = false;\n  var hasFoldableLine = false; // only checked if shouldTrackWidth\n  var shouldTrackWidth = lineWidth !== -1;\n  var previousLineBreak = -1; // count the first line correctly\n  var plain = isPlainSafeFirst(string.charCodeAt(0))\n          && !isWhitespace(string.charCodeAt(string.length - 1));\n\n  if (singleLineOnly) {\n    // Case: no block styles.\n    // Check for disallowed characters to rule out plain and single.\n    for (i = 0; i < string.length; i++) {\n      char = string.charCodeAt(i);\n      if (!isPrintable(char)) {\n        return STYLE_DOUBLE;\n      }\n      prev_char = i > 0 ? string.charCodeAt(i - 1) : null;\n      plain = plain && isPlainSafe(char, prev_char);\n    }\n  } else {\n    // Case: block styles permitted.\n    for (i = 0; i < string.length; i++) {\n      char = string.charCodeAt(i);\n      if (char === CHAR_LINE_FEED) {\n        hasLineBreak = true;\n        // Check if any line can be folded.\n        if (shouldTrackWidth) {\n          hasFoldableLine = hasFoldableLine ||\n            // Foldable line = too long, and not more-indented.\n            (i - previousLineBreak - 1 > lineWidth &&\n             string[previousLineBreak + 1] !== ' ');\n          previousLineBreak = i;\n        }\n      } else if (!isPrintable(char)) {\n        return STYLE_DOUBLE;\n      }\n      prev_char = i > 0 ? string.charCodeAt(i - 1) : null;\n      plain = plain && isPlainSafe(char, prev_char);\n    }\n    // in case the end is missing a \\n\n    hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n      (i - previousLineBreak - 1 > lineWidth &&\n       string[previousLineBreak + 1] !== ' '));\n  }\n  // Although every style can represent \\n without escaping, prefer block styles\n  // for multiline, since they're more readable and they don't add empty lines.\n  // Also prefer folding a super-long line.\n  if (!hasLineBreak && !hasFoldableLine) {\n    // Strings interpretable as another type have to be quoted;\n    // e.g. the string 'true' vs. the boolean true.\n    return plain && !testAmbiguousType(string)\n      ? STYLE_PLAIN : STYLE_SINGLE;\n  }\n  // Edge case: block indentation indicator can only have one digit.\n  if (indentPerLevel > 9 && needIndentIndicator(string)) {\n    return STYLE_DOUBLE;\n  }\n  // At this point we know block styles are valid.\n  // Prefer literal style unless we want to fold.\n  return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;\n}\n\n// Note: line breaking/folding is implemented for only the folded style.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n//  since the dumper adds its own newline. This always works:\n//    \u2022 No ending newline => unaffected; already using strip \"-\" chomping.\n//    \u2022 Ending newline    => removed then restored.\n//  Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction writeScalar(state, string, level, iskey) {\n  state.dump = (function () {\n    if (string.length === 0) {\n      return \"''\";\n    }\n    if (!state.noCompatMode &&\n        DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {\n      return \"'\" + string + \"'\";\n    }\n\n    var indent = state.indent * Math.max(1, level); // no 0-indent scalars\n    // As indentation gets deeper, let the width decrease monotonically\n    // to the lower bound min(state.lineWidth, 40).\n    // Note that this implies\n    //  state.lineWidth \u2264 40 + state.indent: width is fixed at the lower bound.\n    //  state.lineWidth > 40 + state.indent: width decreases until the lower bound.\n    // This behaves better than a constant minimum width which disallows narrower options,\n    // or an indent threshold which causes the width to suddenly increase.\n    var lineWidth = state.lineWidth === -1\n      ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);\n\n    // Without knowing if keys are implicit/explicit, assume implicit for safety.\n    var singleLineOnly = iskey\n      // No block styles in flow mode.\n      || (state.flowLevel > -1 && level >= state.flowLevel);\n    function testAmbiguity(string) {\n      return testImplicitResolving(state, string);\n    }\n\n    switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {\n      case STYLE_PLAIN:\n        return string;\n      case STYLE_SINGLE:\n        return \"'\" + string.replace(/'/g, \"''\") + \"'\";\n      case STYLE_LITERAL:\n        return '|' + blockHeader(string, state.indent)\n          + dropEndingNewline(indentString(string, indent));\n      case STYLE_FOLDED:\n        return '>' + blockHeader(string, state.indent)\n          + dropEndingNewline(indentString(foldString(string, lineWidth), indent));\n      case STYLE_DOUBLE:\n        return '\"' + escapeString(string, lineWidth) + '\"';\n      default:\n        throw new YAMLException('impossible error: invalid scalar style');\n    }\n  }());\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader(string, indentPerLevel) {\n  var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';\n\n  // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n  var clip =          string[string.length - 1] === '\\n';\n  var keep = clip && (string[string.length - 2] === '\\n' || string === '\\n');\n  var chomp = keep ? '+' : (clip ? '' : '-');\n\n  return indentIndicator + chomp + '\\n';\n}\n\n// (See the note for writeScalar.)\nfunction dropEndingNewline(string) {\n  return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string;\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldString(string, width) {\n  // In folded style, $k$ consecutive newlines output as $k+1$ newlines\u2014\n  // unless they're before or after a more-indented line, or at the very\n  // beginning or end, in which case $k$ maps to $k$.\n  // Therefore, parse each chunk as newline(s) followed by a content line.\n  var lineRe = /(\\n+)([^\\n]*)/g;\n\n  // first line (possibly an empty line)\n  var result = (function () {\n    var nextLF = string.indexOf('\\n');\n    nextLF = nextLF !== -1 ? nextLF : string.length;\n    lineRe.lastIndex = nextLF;\n    return foldLine(string.slice(0, nextLF), width);\n  }());\n  // If we haven't reached the first content line yet, don't add an extra \\n.\n  var prevMoreIndented = string[0] === '\\n' || string[0] === ' ';\n  var moreIndented;\n\n  // rest of the lines\n  var match;\n  while ((match = lineRe.exec(string))) {\n    var prefix = match[1], line = match[2];\n    moreIndented = (line[0] === ' ');\n    result += prefix\n      + (!prevMoreIndented && !moreIndented && line !== ''\n        ? '\\n' : '')\n      + foldLine(line, width);\n    prevMoreIndented = moreIndented;\n  }\n\n  return result;\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine(line, width) {\n  if (line === '' || line[0] === ' ') return line;\n\n  // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n  var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.\n  var match;\n  // start is an inclusive index. end, curr, and next are exclusive.\n  var start = 0, end, curr = 0, next = 0;\n  var result = '';\n\n  // Invariants: 0 <= start <= length-1.\n  //   0 <= curr <= next <= max(0, length-2). curr - start <= width.\n  // Inside the loop:\n  //   A match implies length >= 2, so curr and next are <= length-2.\n  while ((match = breakRe.exec(line))) {\n    next = match.index;\n    // maintain invariant: curr - start <= width\n    if (next - start > width) {\n      end = (curr > start) ? curr : next; // derive end <= length-2\n      result += '\\n' + line.slice(start, end);\n      // skip the space that was output as \\n\n      start = end + 1;                    // derive start <= length-1\n    }\n    curr = next;\n  }\n\n  // By the invariants, start <= length-1, so there is something left over.\n  // It is either the whole string or a part starting from non-whitespace.\n  result += '\\n';\n  // Insert a break if the remainder is too long and there is a break available.\n  if (line.length - start > width && curr > start) {\n    result += line.slice(start, curr) + '\\n' + line.slice(curr + 1);\n  } else {\n    result += line.slice(start);\n  }\n\n  return result.slice(1); // drop extra \\n joiner\n}\n\n// Escapes a double-quoted string.\nfunction escapeString(string) {\n  var result = '';\n  var char, nextChar;\n  var escapeSeq;\n\n  for (var i = 0; i < string.length; i++) {\n    char = string.charCodeAt(i);\n    // Check for surrogate pairs (reference Unicode 3.0 section \"3.7 Surrogates\").\n    if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) {\n      nextChar = string.charCodeAt(i + 1);\n      if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) {\n        // Combine the surrogate pair and store it escaped.\n        result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000);\n        // Advance index one extra since we already used that char here.\n        i++; continue;\n      }\n    }\n    escapeSeq = ESCAPE_SEQUENCES[char];\n    result += !escapeSeq && isPrintable(char)\n      ? string[i]\n      : escapeSeq || encodeHex(char);\n  }\n\n  return result;\n}\n\nfunction writeFlowSequence(state, level, object) {\n  var _result = '',\n      _tag    = state.tag,\n      index,\n      length;\n\n  for (index = 0, length = object.length; index < length; index += 1) {\n    // Write only valid elements.\n    if (writeNode(state, level, object[index], false, false)) {\n      if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : '');\n      _result += state.dump;\n    }\n  }\n\n  state.tag = _tag;\n  state.dump = '[' + _result + ']';\n}\n\nfunction writeBlockSequence(state, level, object, compact) {\n  var _result = '',\n      _tag    = state.tag,\n      index,\n      length;\n\n  for (index = 0, length = object.length; index < length; index += 1) {\n    // Write only valid elements.\n    if (writeNode(state, level + 1, object[index], true, true)) {\n      if (!compact || index !== 0) {\n        _result += generateNextLine(state, level);\n      }\n\n      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n        _result += '-';\n      } else {\n        _result += '- ';\n      }\n\n      _result += state.dump;\n    }\n  }\n\n  state.tag = _tag;\n  state.dump = _result || '[]'; // Empty sequence if no valid values.\n}\n\nfunction writeFlowMapping(state, level, object) {\n  var _result       = '',\n      _tag          = state.tag,\n      objectKeyList = Object.keys(object),\n      index,\n      length,\n      objectKey,\n      objectValue,\n      pairBuffer;\n\n  for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n\n    pairBuffer = '';\n    if (index !== 0) pairBuffer += ', ';\n\n    if (state.condenseFlow) pairBuffer += '\"';\n\n    objectKey = objectKeyList[index];\n    objectValue = object[objectKey];\n\n    if (!writeNode(state, level, objectKey, false, false)) {\n      continue; // Skip this pair because of invalid key;\n    }\n\n    if (state.dump.length > 1024) pairBuffer += '? ';\n\n    pairBuffer += state.dump + (state.condenseFlow ? '\"' : '') + ':' + (state.condenseFlow ? '' : ' ');\n\n    if (!writeNode(state, level, objectValue, false, false)) {\n      continue; // Skip this pair because of invalid value.\n    }\n\n    pairBuffer += state.dump;\n\n    // Both key and value are valid.\n    _result += pairBuffer;\n  }\n\n  state.tag = _tag;\n  state.dump = '{' + _result + '}';\n}\n\nfunction writeBlockMapping(state, level, object, compact) {\n  var _result       = '',\n      _tag          = state.tag,\n      objectKeyList = Object.keys(object),\n      index,\n      length,\n      objectKey,\n      objectValue,\n      explicitPair,\n      pairBuffer;\n\n  // Allow sorting keys so that the output file is deterministic\n  if (state.sortKeys === true) {\n    // Default sorting\n    objectKeyList.sort();\n  } else if (typeof state.sortKeys === 'function') {\n    // Custom sort function\n    objectKeyList.sort(state.sortKeys);\n  } else if (state.sortKeys) {\n    // Something is wrong\n    throw new YAMLException('sortKeys must be a boolean or a function');\n  }\n\n  for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n    pairBuffer = '';\n\n    if (!compact || index !== 0) {\n      pairBuffer += generateNextLine(state, level);\n    }\n\n    objectKey = objectKeyList[index];\n    objectValue = object[objectKey];\n\n    if (!writeNode(state, level + 1, objectKey, true, true, true)) {\n      continue; // Skip this pair because of invalid key.\n    }\n\n    explicitPair = (state.tag !== null && state.tag !== '?') ||\n                   (state.dump && state.dump.length > 1024);\n\n    if (explicitPair) {\n      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n        pairBuffer += '?';\n      } else {\n        pairBuffer += '? ';\n      }\n    }\n\n    pairBuffer += state.dump;\n\n    if (explicitPair) {\n      pairBuffer += generateNextLine(state, level);\n    }\n\n    if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {\n      continue; // Skip this pair because of invalid value.\n    }\n\n    if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {\n      pairBuffer += ':';\n    } else {\n      pairBuffer += ': ';\n    }\n\n    pairBuffer += state.dump;\n\n    // Both key and value are valid.\n    _result += pairBuffer;\n  }\n\n  state.tag = _tag;\n  state.dump = _result || '{}'; // Empty mapping if no valid pairs.\n}\n\nfunction detectType(state, object, explicit) {\n  var _result, typeList, index, length, type, style;\n\n  typeList = explicit ? state.explicitTypes : state.implicitTypes;\n\n  for (index = 0, length = typeList.length; index < length; index += 1) {\n    type = typeList[index];\n\n    if ((type.instanceOf  || type.predicate) &&\n        (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&\n        (!type.predicate  || type.predicate(object))) {\n\n      state.tag = explicit ? type.tag : '?';\n\n      if (type.represent) {\n        style = state.styleMap[type.tag] || type.defaultStyle;\n\n        if (_toString.call(type.represent) === '[object Function]') {\n          _result = type.represent(object, style);\n        } else if (_hasOwnProperty.call(type.represent, style)) {\n          _result = type.represent[style](object, style);\n        } else {\n          throw new YAMLException('!<' + type.tag + '> tag resolver accepts not \"' + style + '\" style');\n        }\n\n        state.dump = _result;\n      }\n\n      return true;\n    }\n  }\n\n  return false;\n}\n\n// Serializes `object` and writes it to global `result`.\n// Returns true on success, or false on invalid object.\n//\nfunction writeNode(state, level, object, block, compact, iskey) {\n  state.tag = null;\n  state.dump = object;\n\n  if (!detectType(state, object, false)) {\n    detectType(state, object, true);\n  }\n\n  var type = _toString.call(state.dump);\n\n  if (block) {\n    block = (state.flowLevel < 0 || state.flowLevel > level);\n  }\n\n  var objectOrArray = type === '[object Object]' || type === '[object Array]',\n      duplicateIndex,\n      duplicate;\n\n  if (objectOrArray) {\n    duplicateIndex = state.duplicates.indexOf(object);\n    duplicate = duplicateIndex !== -1;\n  }\n\n  if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {\n    compact = false;\n  }\n\n  if (duplicate && state.usedDuplicates[duplicateIndex]) {\n    state.dump = '*ref_' + duplicateIndex;\n  } else {\n    if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {\n      state.usedDuplicates[duplicateIndex] = true;\n    }\n    if (type === '[object Object]') {\n      if (block && (Object.keys(state.dump).length !== 0)) {\n        writeBlockMapping(state, level, state.dump, compact);\n        if (duplicate) {\n          state.dump = '&ref_' + duplicateIndex + state.dump;\n        }\n      } else {\n        writeFlowMapping(state, level, state.dump);\n        if (duplicate) {\n          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n        }\n      }\n    } else if (type === '[object Array]') {\n      var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level;\n      if (block && (state.dump.length !== 0)) {\n        writeBlockSequence(state, arrayLevel, state.dump, compact);\n        if (duplicate) {\n          state.dump = '&ref_' + duplicateIndex + state.dump;\n        }\n      } else {\n        writeFlowSequence(state, arrayLevel, state.dump);\n        if (duplicate) {\n          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;\n        }\n      }\n    } else if (type === '[object String]') {\n      if (state.tag !== '?') {\n        writeScalar(state, state.dump, level, iskey);\n      }\n    } else {\n      if (state.skipInvalid) return false;\n      throw new YAMLException('unacceptable kind of an object to dump ' + type);\n    }\n\n    if (state.tag !== null && state.tag !== '?') {\n      state.dump = '!<' + state.tag + '> ' + state.dump;\n    }\n  }\n\n  return true;\n}\n\nfunction getDuplicateReferences(object, state) {\n  var objects = [],\n      duplicatesIndexes = [],\n      index,\n      length;\n\n  inspectNode(object, objects, duplicatesIndexes);\n\n  for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {\n    state.duplicates.push(objects[duplicatesIndexes[index]]);\n  }\n  state.usedDuplicates = new Array(length);\n}\n\nfunction inspectNode(object, objects, duplicatesIndexes) {\n  var objectKeyList,\n      index,\n      length;\n\n  if (object !== null && typeof object === 'object') {\n    index = objects.indexOf(object);\n    if (index !== -1) {\n      if (duplicatesIndexes.indexOf(index) === -1) {\n        duplicatesIndexes.push(index);\n      }\n    } else {\n      objects.push(object);\n\n      if (Array.isArray(object)) {\n        for (index = 0, length = object.length; index < length; index += 1) {\n          inspectNode(object[index], objects, duplicatesIndexes);\n        }\n      } else {\n        objectKeyList = Object.keys(object);\n\n        for (index = 0, length = objectKeyList.length; index < length; index += 1) {\n          inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);\n        }\n      }\n    }\n  }\n}\n\nfunction dump(input, options) {\n  options = options || {};\n\n  var state = new State(options);\n\n  if (!state.noRefs) getDuplicateReferences(input, state);\n\n  if (writeNode(state, 0, input, true, true)) return state.dump + '\\n';\n\n  return '';\n}\n\nfunction safeDump(input, options) {\n  return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));\n}\n\nmodule.exports.dump     = dump;\nmodule.exports.safeDump = safeDump;\n", "'use strict';\n\n\nvar loader = require('./js-yaml/loader');\nvar dumper = require('./js-yaml/dumper');\n\n\nfunction deprecated(name) {\n  return function () {\n    throw new Error('Function ' + name + ' is deprecated and cannot be used.');\n  };\n}\n\n\nmodule.exports.Type                = require('./js-yaml/type');\nmodule.exports.Schema              = require('./js-yaml/schema');\nmodule.exports.FAILSAFE_SCHEMA     = require('./js-yaml/schema/failsafe');\nmodule.exports.JSON_SCHEMA         = require('./js-yaml/schema/json');\nmodule.exports.CORE_SCHEMA         = require('./js-yaml/schema/core');\nmodule.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');\nmodule.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');\nmodule.exports.load                = loader.load;\nmodule.exports.loadAll             = loader.loadAll;\nmodule.exports.safeLoad            = loader.safeLoad;\nmodule.exports.safeLoadAll         = loader.safeLoadAll;\nmodule.exports.dump                = dumper.dump;\nmodule.exports.safeDump            = dumper.safeDump;\nmodule.exports.YAMLException       = require('./js-yaml/exception');\n\n// Deprecated schema names from JS-YAML 2.0.x\nmodule.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');\nmodule.exports.SAFE_SCHEMA    = require('./js-yaml/schema/default_safe');\nmodule.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');\n\n// Deprecated functions from JS-YAML 1.x.x\nmodule.exports.scan           = deprecated('scan');\nmodule.exports.parse          = deprecated('parse');\nmodule.exports.compose        = deprecated('compose');\nmodule.exports.addConstructor = deprecated('addConstructor');\n", "'use strict';\n\n\nvar yaml = require('./lib/js-yaml.js');\n\n\nmodule.exports = yaml;\n", "'use strict';\n\nconst yaml = require('js-yaml');\n\n/**\n * Default engines\n */\n\nconst engines = exports = module.exports;\n\n/**\n * YAML\n */\n\nengines.yaml = {\n  parse: yaml.safeLoad.bind(yaml),\n  stringify: yaml.safeDump.bind(yaml)\n};\n\n/**\n * JSON\n */\n\nengines.json = {\n  parse: JSON.parse.bind(JSON),\n  stringify: function(obj, options) {\n    const opts = Object.assign({replacer: null, space: 2}, options);\n    return JSON.stringify(obj, opts.replacer, opts.space);\n  }\n};\n\n/**\n * JavaScript\n */\n\nengines.javascript = {\n  parse: function parse(str, options, wrap) {\n    /* eslint no-eval: 0 */\n    try {\n      if (wrap !== false) {\n        str = '(function() {\\nreturn ' + str.trim() + ';\\n}());';\n      }\n      return eval(str) || {};\n    } catch (err) {\n      if (wrap !== false && /(unexpected|identifier)/i.test(err.message)) {\n        return parse(str, options, false);\n      }\n      throw new SyntaxError(err);\n    }\n  },\n  stringify: function() {\n    throw new Error('stringifying JavaScript is not supported');\n  }\n};\n", "/*!\n * strip-bom-string <https://github.com/jonschlinkert/strip-bom-string>\n *\n * Copyright (c) 2015, 2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\n'use strict';\n\nmodule.exports = function(str) {\n  if (typeof str === 'string' && str.charAt(0) === '\\ufeff') {\n    return str.slice(1);\n  }\n  return str;\n};\n", "'use strict';\n\nconst stripBom = require('strip-bom-string');\nconst typeOf = require('kind-of');\n\nexports.define = function(obj, key, val) {\n  Reflect.defineProperty(obj, key, {\n    enumerable: false,\n    configurable: true,\n    writable: true,\n    value: val\n  });\n};\n\n/**\n * Returns true if `val` is a buffer\n */\n\nexports.isBuffer = function(val) {\n  return typeOf(val) === 'buffer';\n};\n\n/**\n * Returns true if `val` is an object\n */\n\nexports.isObject = function(val) {\n  return typeOf(val) === 'object';\n};\n\n/**\n * Cast `input` to a buffer\n */\n\nexports.toBuffer = function(input) {\n  return typeof input === 'string' ? Buffer.from(input) : input;\n};\n\n/**\n * Cast `val` to a string.\n */\n\nexports.toString = function(input) {\n  if (exports.isBuffer(input)) return stripBom(String(input));\n  if (typeof input !== 'string') {\n    throw new TypeError('expected input to be a string or buffer');\n  }\n  return stripBom(input);\n};\n\n/**\n * Cast `val` to an array.\n */\n\nexports.arrayify = function(val) {\n  return val ? (Array.isArray(val) ? val : [val]) : [];\n};\n\n/**\n * Returns true if `str` starts with `substr`.\n */\n\nexports.startsWith = function(str, substr, len) {\n  if (typeof len !== 'number') len = substr.length;\n  return str.slice(0, len) === substr;\n};\n", "'use strict';\n\nconst engines = require('./engines');\nconst utils = require('./utils');\n\nmodule.exports = function(options) {\n  const opts = Object.assign({}, options);\n\n  // ensure that delimiters are an array\n  opts.delimiters = utils.arrayify(opts.delims || opts.delimiters || '---');\n  if (opts.delimiters.length === 1) {\n    opts.delimiters.push(opts.delimiters[0]);\n  }\n\n  opts.language = (opts.language || opts.lang || 'yaml').toLowerCase();\n  opts.engines = Object.assign({}, engines, opts.parsers, opts.engines);\n  return opts;\n};\n", "'use strict';\n\nmodule.exports = function(name, options) {\n  let engine = options.engines[name] || options.engines[aliase(name)];\n  if (typeof engine === 'undefined') {\n    throw new Error('gray-matter engine \"' + name + '\" is not registered');\n  }\n  if (typeof engine === 'function') {\n    engine = { parse: engine };\n  }\n  return engine;\n};\n\nfunction aliase(name) {\n  switch (name.toLowerCase()) {\n    case 'js':\n    case 'javascript':\n      return 'javascript';\n    case 'coffee':\n    case 'coffeescript':\n    case 'cson':\n      return 'coffee';\n    case 'yaml':\n    case 'yml':\n      return 'yaml';\n    default: {\n      return name;\n    }\n  }\n}\n", "'use strict';\n\nconst typeOf = require('kind-of');\nconst getEngine = require('./engine');\nconst defaults = require('./defaults');\n\nmodule.exports = function(file, data, options) {\n  if (data == null && options == null) {\n    switch (typeOf(file)) {\n      case 'object':\n        data = file.data;\n        options = {};\n        break;\n      case 'string':\n        return file;\n      default: {\n        throw new TypeError('expected file to be a string or object');\n      }\n    }\n  }\n\n  const str = file.content;\n  const opts = defaults(options);\n  if (data == null) {\n    if (!opts.data) return file;\n    data = opts.data;\n  }\n\n  const language = file.language || opts.language;\n  const engine = getEngine(language, opts);\n  if (typeof engine.stringify !== 'function') {\n    throw new TypeError('expected \"' + language + '.stringify\" to be a function');\n  }\n\n  data = Object.assign({}, file.data, data);\n  const open = opts.delimiters[0];\n  const close = opts.delimiters[1];\n  const matter = engine.stringify(data, options).trim();\n  let buf = '';\n\n  if (matter !== '{}') {\n    buf = newline(open) + newline(matter) + newline(close);\n  }\n\n  if (typeof file.excerpt === 'string' && file.excerpt !== '') {\n    if (str.indexOf(file.excerpt.trim()) === -1) {\n      buf += newline(file.excerpt) + newline(close);\n    }\n  }\n\n  return buf + newline(str);\n};\n\nfunction newline(str) {\n  return str.slice(-1) !== '\\n' ? str + '\\n' : str;\n}\n", "'use strict';\n\nconst defaults = require('./defaults');\n\nmodule.exports = function(file, options) {\n  const opts = defaults(options);\n\n  if (file.data == null) {\n    file.data = {};\n  }\n\n  if (typeof opts.excerpt === 'function') {\n    return opts.excerpt(file, opts);\n  }\n\n  const sep = file.data.excerpt_separator || opts.excerpt_separator;\n  if (sep == null && (opts.excerpt === false || opts.excerpt == null)) {\n    return file;\n  }\n\n  const delimiter = typeof opts.excerpt === 'string'\n    ? opts.excerpt\n    : (sep || opts.delimiters[0]);\n\n  // if enabled, get the excerpt defined after front-matter\n  const idx = file.content.indexOf(delimiter);\n  if (idx !== -1) {\n    file.excerpt = file.content.slice(0, idx);\n  }\n\n  return file;\n};\n", "'use strict';\n\nconst typeOf = require('kind-of');\nconst stringify = require('./stringify');\nconst utils = require('./utils');\n\n/**\n * Normalize the given value to ensure an object is returned\n * with the expected properties.\n */\n\nmodule.exports = function(file) {\n  if (typeOf(file) !== 'object') {\n    file = { content: file };\n  }\n\n  if (typeOf(file.data) !== 'object') {\n    file.data = {};\n  }\n\n  // if file was passed as an object, ensure that\n  // \"file.content\" is set\n  if (file.contents && file.content == null) {\n    file.content = file.contents;\n  }\n\n  // set non-enumerable properties on the file object\n  utils.define(file, 'orig', utils.toBuffer(file.content));\n  utils.define(file, 'language', file.language || '');\n  utils.define(file, 'matter', file.matter || '');\n  utils.define(file, 'stringify', function(data, options) {\n    if (options && options.language) {\n      file.language = options.language;\n    }\n    return stringify(file, data, options);\n  });\n\n  // strip BOM and ensure that \"file.content\" is a string\n  file.content = utils.toString(file.content);\n  file.isEmpty = false;\n  file.excerpt = '';\n  return file;\n};\n", "'use strict';\n\nconst getEngine = require('./engine');\nconst defaults = require('./defaults');\n\nmodule.exports = function(language, str, options) {\n  const opts = defaults(options);\n  const engine = getEngine(language, opts);\n  if (typeof engine.parse !== 'function') {\n    throw new TypeError('expected \"' + language + '.parse\" to be a function');\n  }\n  return engine.parse(str, opts);\n};\n", "'use strict';\n\nconst fs = require('fs');\nconst sections = require('section-matter');\nconst defaults = require('./lib/defaults');\nconst stringify = require('./lib/stringify');\nconst excerpt = require('./lib/excerpt');\nconst engines = require('./lib/engines');\nconst toFile = require('./lib/to-file');\nconst parse = require('./lib/parse');\nconst utils = require('./lib/utils');\n\n/**\n * Takes a string or object with `content` property, extracts\n * and parses front-matter from the string, then returns an object\n * with `data`, `content` and other [useful properties](#returned-object).\n *\n * ```js\n * const matter = require('gray-matter');\n * console.log(matter('---\\ntitle: Home\\n---\\nOther stuff'));\n * //=> { data: { title: 'Home'}, content: 'Other stuff' }\n * ```\n * @param {Object|String} `input` String, or object with `content` string\n * @param {Object} `options`\n * @return {Object}\n * @api public\n */\n\nfunction matter(input, options) {\n  if (input === '') {\n    return { data: {}, content: input, excerpt: '', orig: input };\n  }\n\n  let file = toFile(input);\n  const cached = matter.cache[file.content];\n\n  if (!options) {\n    if (cached) {\n      file = Object.assign({}, cached);\n      file.orig = cached.orig;\n      return file;\n    }\n\n    // only cache if there are no options passed. if we cache when options\n    // are passed, we would need to also cache options values, which would\n    // negate any performance benefits of caching\n    matter.cache[file.content] = file;\n  }\n\n  return parseMatter(file, options);\n}\n\n/**\n * Parse front matter\n */\n\nfunction parseMatter(file, options) {\n  const opts = defaults(options);\n  const open = opts.delimiters[0];\n  const close = '\\n' + opts.delimiters[1];\n  let str = file.content;\n\n  if (opts.language) {\n    file.language = opts.language;\n  }\n\n  // get the length of the opening delimiter\n  const openLen = open.length;\n  if (!utils.startsWith(str, open, openLen)) {\n    excerpt(file, opts);\n    return file;\n  }\n\n  // if the next character after the opening delimiter is\n  // a character from the delimiter, then it's not a front-\n  // matter delimiter\n  if (str.charAt(openLen) === open.slice(-1)) {\n    return file;\n  }\n\n  // strip the opening delimiter\n  str = str.slice(openLen);\n  const len = str.length;\n\n  // use the language defined after first delimiter, if it exists\n  const language = matter.language(str, opts);\n  if (language.name) {\n    file.language = language.name;\n    str = str.slice(language.raw.length);\n  }\n\n  // get the index of the closing delimiter\n  let closeIndex = str.indexOf(close);\n  if (closeIndex === -1) {\n    closeIndex = len;\n  }\n\n  // get the raw front-matter block\n  file.matter = str.slice(0, closeIndex);\n\n  const block = file.matter.replace(/^\\s*#[^\\n]+/gm, '').trim();\n  if (block === '') {\n    file.isEmpty = true;\n    file.empty = file.content;\n    file.data = {};\n  } else {\n\n    // create file.data by parsing the raw file.matter block\n    file.data = parse(file.language, file.matter, opts);\n  }\n\n  // update file.content\n  if (closeIndex === len) {\n    file.content = '';\n  } else {\n    file.content = str.slice(closeIndex + close.length);\n    if (file.content[0] === '\\r') {\n      file.content = file.content.slice(1);\n    }\n    if (file.content[0] === '\\n') {\n      file.content = file.content.slice(1);\n    }\n  }\n\n  excerpt(file, opts);\n\n  if (opts.sections === true || typeof opts.section === 'function') {\n    sections(file, opts.section);\n  }\n  return file;\n}\n\n/**\n * Expose engines\n */\n\nmatter.engines = engines;\n\n/**\n * Stringify an object to YAML or the specified language, and\n * append it to the given string. By default, only YAML and JSON\n * can be stringified. See the [engines](#engines) section to learn\n * how to stringify other languages.\n *\n * ```js\n * console.log(matter.stringify('foo bar baz', {title: 'Home'}));\n * // results in:\n * // ---\n * // title: Home\n * // ---\n * // foo bar baz\n * ```\n * @param {String|Object} `file` The content string to append to stringified front-matter, or a file object with `file.content` string.\n * @param {Object} `data` Front matter to stringify.\n * @param {Object} `options` [Options](#options) to pass to gray-matter and [js-yaml].\n * @return {String} Returns a string created by wrapping stringified yaml with delimiters, and appending that to the given string.\n * @api public\n */\n\nmatter.stringify = function(file, data, options) {\n  if (typeof file === 'string') file = matter(file, options);\n  return stringify(file, data, options);\n};\n\n/**\n * Synchronously read a file from the file system and parse\n * front matter. Returns the same object as the [main function](#matter).\n *\n * ```js\n * const file = matter.read('./content/blog-post.md');\n * ```\n * @param {String} `filepath` file path of the file to read.\n * @param {Object} `options` [Options](#options) to pass to gray-matter.\n * @return {Object} Returns [an object](#returned-object) with `data` and `content`\n * @api public\n */\n\nmatter.read = function(filepath, options) {\n  const str = fs.readFileSync(filepath, 'utf8');\n  const file = matter(str, options);\n  file.path = filepath;\n  return file;\n};\n\n/**\n * Returns true if the given `string` has front matter.\n * @param  {String} `string`\n * @param  {Object} `options`\n * @return {Boolean} True if front matter exists.\n * @api public\n */\n\nmatter.test = function(str, options) {\n  return utils.startsWith(str, defaults(options).delimiters[0]);\n};\n\n/**\n * Detect the language to use, if one is defined after the\n * first front-matter delimiter.\n * @param  {String} `string`\n * @param  {Object} `options`\n * @return {Object} Object with `raw` (actual language string), and `name`, the language with whitespace trimmed\n */\n\nmatter.language = function(str, options) {\n  const opts = defaults(options);\n  const open = opts.delimiters[0];\n\n  if (matter.test(str)) {\n    str = str.slice(open.length);\n  }\n\n  const language = str.slice(0, str.search(/\\r?\\n/));\n  return {\n    raw: language,\n    name: language ? language.trim() : ''\n  };\n};\n\n/**\n * Expose `matter`\n */\n\nmatter.cache = {};\nmatter.clearCache = function() {\n  matter.cache = {};\n};\nmodule.exports = matter;\n", "import matter from 'gray-matter';\nimport { SKILL_ENTRYPOINT, type DecodedBundle } from '@skillet/protocol';\n\n// The packer lives in @skillet/protocol so the server (registry download\n// endpoint) and the client (CLI export) share one implementation without the\n// registry depending on @skillet/core. Re-export it through core's bundle barrel\n// so callers have a single import surface alongside the other bundle helpers.\nexport { bundleToZip, bundlesToZip } from '@skillet/protocol';\n\n/**\n * Return SKILL.md frontmatter keys beyond `name`/`description`.\n *\n * Codex and ChatGPT Skills accept `name` and `description` only (\"Do not\n * include any other fields\"). Export uses this to warn \u2014 never to rewrite \u2014 so\n * the author can decide whether a skill bound for a strict consumer needs\n * trimming. An empty array means the skill is clean. This stays in core (not\n * protocol) because it depends on gray-matter, a client-side concern.\n */\nexport function frontmatterCompatWarnings(bundle: DecodedBundle): string[] {\n  const raw = bundle.get(SKILL_ENTRYPOINT);\n  if (!raw) return [];\n  let data: Record<string, unknown>;\n  try {\n    data = (matter(Buffer.from(raw).toString('utf8')).data ?? {}) as Record<\n      string,\n      unknown\n    >;\n  } catch {\n    return [];\n  }\n  return Object.keys(data).filter((k) => k !== 'name' && k !== 'description');\n}\n", "export {\n  BundleError,\n  CONTENT_HASH_PREFIX,\n  MAX_BUNDLE_BYTES,\n  MAX_INSTRUCTION_BYTES,\n  SKILL_ENTRYPOINT,\n  assertSafeBundlePath,\n  canonicalContentHash,\n  decodeBundle,\n  encodeBundle,\n  isInstructionPath,\n  validateBundle,\n} from '@skillet/protocol';\nexport type {\n  BundleEncoding,\n  BundleFileEntry,\n  BundleFiles,\n  DecodedBundle,\n} from '@skillet/protocol';\n\nexport { readBundleFromDir } from './read.js';\nexport {\n  writeBundleToDir,\n  writeFilesToRoot,\n  bundleSlugDir,\n  materializeSlugDir,\n  isSkilletSlugDirName,\n  parseSkilletSlugDir,\n} from './write.js';\nexport { bundleToZip, bundlesToZip, frontmatterCompatWarnings } from './zip.js';\n", "import type { ScanManifestInfo, SignedDelegation, ArtifactSchemaVersion } from \"@skillet/protocol\";\nimport type { Signature } from \"../signing/envelope.js\";\n\nexport interface SkillEntry {\n  slug: string;\n  /** Author handle without leading `@`. Absent for unowned local imports. */\n  owner?: string | null;\n  name: string;\n  description: string;\n  version: number;\n  /**\n   * Semver display label (\"X.Y.Z\") for `version`, as served by the registry.\n   * Display only \u2014 never used for ordering, pinning, or approval; the integer\n   * `version` stays authoritative. Absent for locally-imported skills and for\n   * entries synced from servers predating the field.\n   */\n  versionLabel?: string;\n  /** Canonical bundle content hash, `sha256:`-prefixed (\u00A72.2). */\n  hash: string;\n  /**\n   * The hash sync LAST SUCCESSFULLY MATERIALIZED to this machine's adapters\n   * (set only after a materialize write lands). This \u2014 not `hash` \u2014 is the drift\n   * baseline: `hash` is advanced by the pull phase before materialize, so if a\n   * pull persists a new version but the subsequent materialize fails/declines\n   * (degrade-never-delete), `hash` records a version that never reached disk.\n   * Comparing on-disk bytes against `hash` would then misread the still-current\n   * author bytes as a hand edit and wrongly customize the skill forever (F1).\n   * `materialized_hash` records what's actually on disk, so a persisted-but-\n   * unmaterialized version RE-MATERIALIZES (converges) instead of customizing.\n   * Absent for entries never materialized on this machine and for legacy state.\n   */\n  materialized_hash?: string;\n  source: \"local\" | \"registry\";\n  /**\n   * Which trust source class this skill belongs to, driving the two\n   * independent global update-trust defaults:\n   *   - \"own-kit\":  came from the user's own kit / a team kit they belong to\n   *                 (the authenticated union manifest).\n   *   - \"external\": added from a stranger (`skillet add @them/skill`).\n   * Absent for locally-imported skills and for legacy entries written before\n   * trust policy; the policy resolver treats absent as \"external\" (the safer,\n   * diff-gated default).\n   */\n  sourceClass?: \"own-kit\" | \"external\";\n  /**\n   * Kit ref this skill was synced under (`@owner/kitname`, the manifest\n   * `source_kit`). Drives the per-kit update-trust override so a subscriber can\n   * auto-trust or gate a whole kit. Absent for locally-imported skills and for\n   * skills not sourced from a kit.\n   */\n  sourceKit?: string | null;\n  /**\n   * Stable id of the kit this skill was synced under (the manifest `kit_id`),\n   * the identity-safe counterpart to the display-only `sourceKit`. Use this for\n   * any kit identity comparison; `sourceKit`'s `@owner/slug-name` is display\n   * only and drifts on rename/slug collision. Absent for locally-imported\n   * skills, own-profile skills, and entries from servers predating the field.\n   */\n  sourceKitId?: string | null;\n  /**\n   * The subscriber's per-kit update-trust preference, set on the web and\n   * delivered via the sync manifest ('auto' | 'gate'). Overrides the global\n   * default but yields to a local per-skill / per-author / per-kit policy. Null\n   * when the subscriber set no web preference.\n   */\n  subscriberTrust?: \"auto\" | \"gate\" | null;\n  /**\n   * The skill's classified category key (e.g. `frontend`, `design`), delivered\n   * via the sync manifest. Public skills only; null/absent when unclassified.\n   * Informational \u2014 drives generated cover art in clients (desktop tray), no\n   * sync/trust logic branches on it.\n   */\n  category?: string | null;\n  registryUrl?: string;\n  /**\n   * Provenance for skills pulled from a remote non-registry source \u2014 currently\n   * `github:<owner>/<repo>@<ref>[#<subdir>]` for `skillet import owner/repo`\n   * Purely informational: these imports are still `source: \"local\"`\n   * (unpublished, self-trusted) and no sync/publish logic branches on it.\n   */\n  origin?: string;\n  /**\n   * Hex-encoded Ed25519 public key ID of the skill author.\n   * Absent for locally-imported skills (always trusted as self-authored).\n   * Set for registry-sourced skills; compared against the user's own key ID\n   * to determine whether auto-trust applies.\n   */\n  authorKeyId?: string;\n  /**\n   * Base64 of the 32 raw Ed25519 public-key bytes for the author. Persisted\n   * alongside `authorKeyId` so verification can run on every sync without a\n   * round-trip to the registry \u2014 and so a poisoned offline run still fails\n   * closed against the locally-pinned key (PROTOCOL \u00A74 + \u00A711).\n   */\n  authorPubBase64?: string;\n  /**\n   * Author signature envelope over `content_hash`. Stored at import time\n   * (registry response) and re-verified before every materialize so a\n   * subsequent registry compromise cannot retroactively swap content.\n   */\n  signature?: Signature;\n  /**\n   * When `signature` was produced by a delegated DEVICE key (its\n   * `key_id` is a device key, not the author's primary), this carries the\n   * inline SignedDelegation so the chain device_sig \u2190 cert \u2190 pinned primary can\n   * be re-verified offline (fresh checkout / CI) without a registry round-trip.\n   * Absent for primary-signed versions and locally-imported skills.\n   */\n  delegation?: SignedDelegation;\n  importedAt: string;\n  updatedAt: string;\n  /**\n   * Last-known server-side scan state. Captured from the\n   * registry manifest entry at sync time so subsequent runs and `skillet status`\n   * can surface quarantined skills without a round-trip. Absent for\n   * locally-imported skills and for `clean` registry versions.\n   */\n  scan?: ScanManifestInfo;\n  /**\n   * When true, the registry-pull phase of sync MUST NOT change this entry's\n   * version/hash \u2014 the user explicitly froze it via `skillet add --pin`. Pulling\n   * is a no-op for pinned entries; the materialize phase still runs against\n   * the pinned bytes already in the local store. Unpinned registry skills\n   * pull in interactive sync only (the headless rule, AC 4).\n   */\n  pinned?: boolean;\n  /**\n   * Set when the user (or their agent) edited this synced skill's materialized\n   * folder (KTD1): the skill is now the user's *customized version*, and this\n   * carries its lineage baseline \u2014 the signed author origin the edit was made\n   * against. While present, sync NEVER materializes over the edit (the edit\n   * stays live in place forever) and the author's updates for it are HELD, not\n   * applied. Cleared by Take theirs / Restore original. Additive \u2014 `readState`\n   * is unvalidated JSON, so older state files simply lack it.\n   */\n  customized_from?: {\n    author: string | null;\n    slug: string;\n    version: number;\n    hash: string;\n  };\n  /**\n   * A held author update for a customized skill (KTD3): the freshly-pulled\n   * upstream `{version, hash}` that differs from `customized_from.hash` and was\n   * NOT materialized over the edit. Surfaced as a quiet, non-blocking signal.\n   * `acknowledged` is set by Keep mine so it stops nudging until a NEWER upstream\n   * hash appears (which replaces this record, clearing the flag). Absent when the\n   * skill is uncustomized or upstream matches the customized baseline.\n   */\n  held_update?: {\n    version: number;\n    hash: string;\n    acknowledged?: boolean;\n    /**\n     * Set when a pull observed this held version is now YANKED on the registry\n     * (F6). A yanked held update stops nudging (never surfaces as `hasUpdate`)\n     * and `takeUpstream` refuses to install it \u2014 the author pulled it. Cleared\n     * only when a NEWER, un-yanked upstream hash replaces this record.\n     */\n    yanked?: boolean;\n  };\n}\n\nexport interface KitState {\n  /** Local kit state container format. */\n  version: 1;\n  /** Wire-format version for synced skill entries. */\n  artifact_schema_version?: ArtifactSchemaVersion;\n  skills: Record<string, SkillEntry>;\n  /**\n   * Whether the LAST post-sync device report carried a non-empty edited set\n   * (KTD2). The registry clears its per-device edit-flags by ABSENCE, so a\n   * device that un-customizes its LAST edited skill in a sync that also\n   * materializes nothing must STILL send the now-empty edited set \u2014 otherwise\n   * the stale `device_skill_edits` row never clears and holds that skill's\n   * updates out of bulk-approve forever. This marker lets the report fire the\n   * clearing case (edited: [] explicitly) on the transition FROM having reported\n   * edits TO none, while a device that never had edits stays silent on idle\n   * syncs. Additive \u2014 older state files simply lack it (treated as false).\n   */\n  edited_reported?: boolean;\n}\n\nexport const REGISTRY_URL_DEFAULT = \"https://registry.skillet.md\";\n", "import { readFile, mkdir, readdir, lstat, rm } from \"node:fs/promises\";\nimport { join, sep } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport type { DecodedBundle } from \"@skillet/protocol\";\nimport { ARTIFACT_SCHEMA_VERSION, validateBundle, isSkilletBackupPath } from \"@skillet/protocol\";\nimport { atomicWrite } from \"../util/atomic.js\";\nimport { assertNoPathEscape } from \"../util/pathsafe.js\";\nimport { readBundleFromDir } from \"../bundle/read.js\";\nimport type { KitState, SkillEntry } from \"./types.js\";\n\nexport const SKILLET_DIR = process.env[\"SKILLET_DIR\"] ?? join(homedir(), \".skillet\");\nconst STATE_FILE = join(SKILLET_DIR, \"state.json\");\n\nexport async function readState(): Promise<KitState> {\n  try {\n    const raw = await readFile(STATE_FILE, \"utf8\");\n    return JSON.parse(raw) as KitState;\n  } catch (err: unknown) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return { version: 1, artifact_schema_version: ARTIFACT_SCHEMA_VERSION, skills: {} };\n    }\n    throw err;\n  }\n}\n\nexport async function writeState(state: KitState): Promise<void> {\n  await mkdir(SKILLET_DIR, { recursive: true });\n  const stamped: KitState = {\n    ...state,\n    artifact_schema_version: state.artifact_schema_version ?? ARTIFACT_SCHEMA_VERSION,\n  };\n  await atomicWrite(STATE_FILE, JSON.stringify(stamped, null, 2) + \"\\n\", { backup: false });\n}\n\nexport async function upsertSkill(entry: SkillEntry): Promise<void> {\n  const state = await readState();\n  state.skills[entry.slug] = entry;\n  await writeState(state);\n}\n\n/**\n * Whether the last post-sync device report carried a non-empty edited set.\n * Read-modify-write against the on-disk state so it never clobbers concurrent\n * per-skill upserts (mirrors {@link upsertSkill}). Drives the \"clear edits by\n * absence\" reconcile: see {@link KitState.edited_reported}.\n */\nexport async function readEditedReported(): Promise<boolean> {\n  const state = await readState();\n  return state.edited_reported === true;\n}\n\nexport async function setEditedReported(reported: boolean): Promise<void> {\n  const state = await readState();\n  if (reported) state.edited_reported = true;\n  else delete state.edited_reported;\n  await writeState(state);\n}\n\nexport function skillContentDir(slug: string): string {\n  // Read-side chokepoint guard mirroring the write side (writeBundleToSkillStore).\n  // Every read of a skill's bytes funnels through here; reject a traversal/absolute\n  // slug (e.g. from a hand-edited state.json or a hostile registry response) before\n  // it can escape the store root.\n  assertNoPathEscape(join(SKILLET_DIR, \"skills\"), slug);\n  return join(SKILLET_DIR, \"skills\", slug);\n}\n\n/**\n * Path to the skill's entrypoint `SKILL.md` in the local store. Bundle is\n * the directory; this is the canonical entry into it.\n */\nexport function skillContentPath(slug: string): string {\n  return join(skillContentDir(slug), \"SKILL.md\");\n}\n\n/**\n * Persist a full bundle tree under the skill store.\n *\n * Removes anything previously in the skill dir so a republish/import that\n * deletes a file actually drops the file from disk (otherwise the next read\n * would still see the stale path and the hash would diverge from publish).\n */\nexport async function writeBundleToSkillStore(\n  slug: string,\n  bundle: DecodedBundle,\n): Promise<void> {\n  // SECURITY: a bundle's keys are attacker-controlled when it comes from the\n  // registry (a hostile/compromised registry, or a session-attested envelope\n  // that skips author crypto). Reject traversal/absolute/oversize entries here,\n  // at the single store-write chokepoint, BEFORE any path is joined or written \u2014\n  // mirroring the materialize-side guard in bundle/write.ts. Without this a key\n  // like `../../../.claude/skills/evil/SKILL.md` would escape the store.\n  validateBundle(bundle);\n\n  // SECURITY: validate the `slug` directory component too \u2014 it's registry/\n  // manifest-derived for the pull callers. Every current caller guards it\n  // upstream, but enforce it here so the chokepoint covers BOTH halves of a\n  // write-what-where (the file path AND the directory prefix). Accepts both\n  // `@author/slug` and bare local slugs; rejects `..`, absolute, and null-byte.\n  assertNoPathEscape(join(SKILLET_DIR, \"skills\"), slug);\n\n  const dir = skillContentDir(slug);\n  await mkdir(dir, { recursive: true });\n  await rmDirContents(dir);\n\n  for (const [bundlePath, bytes] of bundle) {\n    if (isSkilletBackupPath(bundlePath)) continue;\n    const hostRel = sep === \"/\" ? bundlePath : bundlePath.split(\"/\").join(sep);\n    const dest = join(dir, hostRel);\n    await atomicWrite(dest, Buffer.from(bytes), { backup: false });\n  }\n}\n\nexport async function readBundleFromSkillStore(\n  slug: string,\n  opts?: { includeSkilletBackups?: boolean },\n): Promise<DecodedBundle> {\n  return await readBundleFromDir(skillContentDir(slug), opts);\n}\n\nasync function rmDirContents(dir: string): Promise<void> {\n  let entries;\n  try {\n    entries = await readdir(dir);\n  } catch (err: unknown) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return;\n    throw err;\n  }\n  for (const name of entries) {\n    const abs = join(dir, name);\n    const st = await lstat(abs);\n    await rm(abs, { recursive: st.isDirectory(), force: true });\n  }\n}\n", "/**\n * Resolve the registry session bearer from ~/.skillet/session.json or env.\n *\n * We prefer session.json over SKILLET_TOKEN env so a fresh `skillet connect`\n * is not shadowed by a stale exported token from an earlier dev session.\n * Set SKILLET_TOKEN_FORCE=1 to make SKILLET_TOKEN win over session.json (CI).\n */\nimport { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\n\nexport function skilletDir(): string {\n  return process.env['SKILLET_DIR'] ?? join(homedir(), '.skillet');\n}\n\nexport function sessionFilePath(): string {\n  return join(skilletDir(), 'session.json');\n}\n\n/** Persist a registry session token to ~/.skillet/session.json (0600). */\nexport async function saveSessionToken(token: string): Promise<void> {\n  await mkdir(skilletDir(), { recursive: true, mode: 0o700 });\n  await writeFile(\n    sessionFilePath(),\n    JSON.stringify({ session_token: token, saved_at: new Date().toISOString() }, null, 2) + '\\n',\n    { mode: 0o600 },\n  );\n}\n\nexport async function readSessionFileToken(): Promise<string> {\n  try {\n    const raw = await readFile(sessionFilePath(), 'utf8');\n    const parsed = JSON.parse(raw) as { session_token?: string };\n    return typeof parsed.session_token === 'string' ? parsed.session_token : '';\n  } catch {\n    return '';\n  }\n}\n\nexport function envSessionToken(): string {\n  return process.env['SKILLET_TOKEN'] ?? '';\n}\n\n/** When true, `SKILLET_TOKEN` wins over `session.json` for session bearer resolution. */\nexport function envSessionTokenForceActive(): boolean {\n  const raw = process.env['SKILLET_TOKEN_FORCE'];\n  return raw === '1' || raw === 'true' || raw === 'yes';\n}\n\nexport type SessionTokenPrecedence =\n  | 'explicit'\n  | 'env_forced'\n  | 'file'\n  | 'env_fallback'\n  | 'none';\n\n/** Which source would supply the session bearer (device precedence is separate). */\nexport async function sessionTokenPrecedenceMode(\n  explicit?: string,\n): Promise<SessionTokenPrecedence> {\n  if (explicit) return 'explicit';\n  const envToken = envSessionToken();\n  if (envSessionTokenForceActive() && envToken.length > 0) return 'env_forced';\n  const fromFile = await readSessionFileToken();\n  if (fromFile) return 'file';\n  if (envToken.length > 0) return 'env_fallback';\n  return 'none';\n}\n\nexport async function loadSessionToken(explicit?: string): Promise<string> {\n  if (explicit) return explicit;\n  const envToken = envSessionToken();\n  if (envSessionTokenForceActive() && envToken) return envToken;\n  const fromFile = await readSessionFileToken();\n  if (fromFile) return fromFile;\n  return envToken;\n}\n", "/**\n * User-bound registry device bearer (~/.skillet/device.json).\n *\n * Created via POST /api/v1/connect/claim when a machine is pair-claimed.\n * A stored device token takes precedence over session for sync \u2014 see\n * auth-token.ts.\n */\nimport { readFile, writeFile, mkdir, unlink } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { skilletDir } from './session-token.js';\n\nexport interface DeviceTokenFile {\n  device_token: string;\n  device_id?: string;\n  label?: string;\n  /**\n   * Stable client-minted machine identity, presented at pair-claim so the\n   * registry can reclaim this machine's existing device row after the token\n   * is lost or clobbered (e.g. a dev-registry pairing overwrote this file).\n   * Minted once and carried across every save \u2014 losing it only costs dedupe,\n   * never access.\n   */\n  machine_id?: string;\n  saved_at: string;\n}\n\nexport function deviceFilePath(): string {\n  return join(skilletDir(), 'device.json');\n}\n\nexport async function readDeviceFile(): Promise<DeviceTokenFile | null> {\n  try {\n    const raw = await readFile(deviceFilePath(), 'utf8');\n    const parsed = JSON.parse(raw) as DeviceTokenFile;\n    if (typeof parsed.device_token !== 'string') return null;\n    return parsed;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * The file as written, credential or not. Sign-out leaves a machine_id-only\n * stub (no device_token), which the validating reader above reports as \"no\n * device file\" \u2014 machine-id carry-forward must NOT go through that reader or\n * the identity dies on the first save after sign-out.\n */\nasync function readRawDeviceFile(): Promise<Partial<DeviceTokenFile> | null> {\n  try {\n    const raw = await readFile(deviceFilePath(), 'utf8');\n    return JSON.parse(raw) as Partial<DeviceTokenFile>;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Device file for credential use, cleaning up a retired anonymous file on sight.\n *\n * A `label: 'anonymous'` device.json is a leftover from the retired\n * anonymous-bootstrap path \u2014 migration 049 already deleted its registry row, so\n * it is not a credential and its device_id is dead. Detect it, delete it, and\n * report \"no device file\". Concentrating the special case here means read sites\n * don't each need a `label !== 'anonymous'` guard (and don't silently misreport\n * link status or send a dead device id when they forget it).\n */\nexport async function readActiveDeviceFile(): Promise<DeviceTokenFile | null> {\n  const file = await readDeviceFile();\n  if (file?.label === 'anonymous') {\n    await clearDeviceToken();\n    return null;\n  }\n  return file;\n}\n\n/** Stored machine identity, credential or not \u2014 survives the sign-out stub. */\nexport async function readStoredMachineId(): Promise<string | undefined> {\n  const raw = (await readRawDeviceFile())?.machine_id;\n  return typeof raw === 'string' && raw.length > 0 ? raw : undefined;\n}\n\n/** Machine id from device.json when present \u2014 readable even without a valid device token. */\nexport async function readDeviceId(): Promise<string | undefined> {\n  try {\n    const raw = await readFile(deviceFilePath(), 'utf8');\n    const parsed = JSON.parse(raw) as { device_id?: string };\n    return typeof parsed.device_id === 'string' ? parsed.device_id : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nexport async function saveDeviceToken(\n  deviceToken: string,\n  meta: { device_id?: string; label?: string; machine_id?: string } = {},\n): Promise<void> {\n  await mkdir(skilletDir(), { recursive: true, mode: 0o700 });\n  // machine_id must survive saves that don't pass it (auth-connect, any\n  // future writer) \u2014 dropping it silently re-enables duplicate device rows.\n  // Read raw, not via readDeviceFile: the sign-out stub has no token and the\n  // validating reader would drop the id on the first save after sign-out.\n  const machineId = meta.machine_id ?? (await readStoredMachineId());\n  const body: DeviceTokenFile = {\n    device_token: deviceToken,\n    saved_at: new Date().toISOString(),\n    ...(meta.device_id ? { device_id: meta.device_id } : {}),\n    ...(meta.label ? { label: meta.label } : {}),\n    ...(machineId ? { machine_id: machineId } : {}),\n  };\n  await writeFile(deviceFilePath(), JSON.stringify(body, null, 2) + '\\n', { mode: 0o600 });\n}\n\nexport async function clearDeviceToken(): Promise<void> {\n  // Sign-out kills the credential but keeps the machine identity: a stub with\n  // only machine_id stays behind so the next pair reclaims this machine's\n  // existing device row instead of minting a duplicate. Every credential\n  // reader (readDeviceFile here, the desktop's serde parse) already treats a\n  // token-less file as signed-out. Machines with a derivable OS id would\n  // survive a plain unlink too \u2014 the stub is for the fallback population\n  // whose machine_id is a persisted random UUID.\n  const rawMachineId = (await readRawDeviceFile())?.machine_id;\n  if (typeof rawMachineId === 'string' && rawMachineId.length > 0) {\n    const stub = { machine_id: rawMachineId, saved_at: new Date().toISOString() };\n    await writeFile(deviceFilePath(), JSON.stringify(stub, null, 2) + '\\n', { mode: 0o600 });\n    return;\n  }\n  // Use the static top-level unlink, NOT a dynamic import(): bundled sidecars\n  // (the desktop's packaged CLI) can't resolve a runtime import of a node\n  // builtin, so the old `await import('node:fs/promises')` threw and the bare\n  // catch swallowed it \u2014 device.json survived and \"Sign out\" never stuck.\n  try {\n    await unlink(deviceFilePath());\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n  }\n}\n", "/**\n * Resolve which registry bearer to use for sync and other registry reads.\n *\n * Priority: explicit arg \u2192 device.json \u2192 session.json / SKILLET_TOKEN env.\n *\n * A device token is only minted by pair-claiming a machine, so any stored\n * device token marks a linked machine. It wins over session so a web\n * disconnect invalidates sync on that machine.\n *\n * Exception: a device file labeled 'anonymous' is a leftover from the retired\n * anonymous-bootstrap path (its registry row is deleted by migration 049). It\n * is not a credential \u2014 skip it so an upgrading machine falls through to its\n * session (or to the unpaired gate) instead of syncing with a dangling token\n * and landing in the \"disconnected from your account\" lane.\n */\nimport { loadSessionToken } from './session-token.js';\nimport { readActiveDeviceFile, type DeviceTokenFile } from './device-token.js';\n\nexport type RegistryBearerKind = 'session' | 'device' | 'kit' | 'unknown' | 'none';\n\nexport function classifyRegistryBearer(token: string): RegistryBearerKind {\n  if (token.startsWith('skillet_s_')) return 'session';\n  if (token.startsWith('skillet_d_')) return 'device';\n  if (token.startsWith('skillet_k_')) return 'kit';\n  if (token.length > 0) return 'unknown';\n  return 'none';\n}\n\nexport interface RegistryBearer {\n  token: string;\n  kind: RegistryBearerKind;\n}\n\n/** Pair-claimed machine: device token plus session. */\nexport function isLinkedMachineCredentials(\n  deviceFile: DeviceTokenFile | null,\n  sessionToken: string,\n): boolean {\n  return Boolean(deviceFile?.device_id && deviceFile.device_token && sessionToken.length > 0);\n}\n\n/** Load the best available registry bearer for the caller. */\nexport async function loadRegistryBearer(explicit?: string): Promise<RegistryBearer> {\n  if (explicit) {\n    const token = explicit;\n    return { token, kind: classifyRegistryBearer(token) };\n  }\n\n  const deviceFile = await readActiveDeviceFile();\n  if (deviceFile?.device_token) {\n    return { token: deviceFile.device_token, kind: 'device' };\n  }\n\n  const session = await loadSessionToken();\n  if (session) {\n    return { token: session, kind: classifyRegistryBearer(session) };\n  }\n\n  return { token: '', kind: 'none' };\n}\n", "// Activity sink (Phase 0). The actions taken across the CLI (sync, add, publish,\n// login\u2026) post to the registry's activity stream so retention/cohorts/cross-\n// vendor distribution (availability) can be computed later \u2014 history is irrecoverable, so it accrues\n// now. It's the record of your sync, not separate telemetry, and it powers your\n// devices and profile.\n//\n// Privacy: recorded by default for account-bound clients, disclosed on first\n// sync. Opt out with `activity: false` in ~/.skillet/config.json (or\n// SKILLET_ACTIVITY=0); the genuine \"don't record me\" path is anonymous local-\n// first use (no account). The payload is metadata only, and failures are\n// swallowed: activity reporting must never break or slow a command.\nimport { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { skilletDir } from './session-token.js';\nimport { loadRegistryBearer } from './auth-token.js';\nimport { REGISTRY_API } from './registry-api.js';\nimport { REGISTRY_URL_DEFAULT } from './kit/types.js';\n\nexport type Initiator = 'human' | 'daemon' | 'ci';\n\nexport interface SkilletEvent {\n  name: string;\n  initiator: Initiator;\n  ts: string;\n  meta?: Record<string, string | number | boolean>;\n}\n\nlet queue: SkilletEvent[] = [];\nlet scheduled = false;\nlet recordCache: boolean | null = null;\n\n/** Default ON for account-bound clients; opt out via env or config `activity:false`. */\nasync function activityRecording(): Promise<boolean> {\n  const env = process.env['SKILLET_ACTIVITY'];\n  if (env === '0' || env === 'false') return false;\n  if (env === '1' || env === 'true') return true;\n  if (recordCache != null) return recordCache;\n  try {\n    const raw = await readFile(join(skilletDir(), 'config.json'), 'utf8');\n    recordCache = (JSON.parse(raw) as { activity?: boolean }).activity !== false;\n  } catch {\n    recordCache = true; // default ON \u2014 disclosed on first sync; anonymous mode is the opt-out\n  }\n  return recordCache;\n}\n\n/**\n * Record one human/daemon/ci-tagged event. Buffers and best-effort flushes; the\n * north-star (human-only) filtering happens at query time on the `initiator` tag.\n */\nexport function recordEvent(\n  name: string,\n  initiator: Initiator,\n  meta?: Record<string, string | number | boolean>,\n): void {\n  queue.push({ name, initiator, ts: new Date().toISOString(), ...(meta ? { meta } : {}) });\n  if (process.env['SKILLET_ACTIVITY_DEBUG'] === '1') {\n    process.stderr.write(`[skillet:metric] ${JSON.stringify(queue[queue.length - 1])}\\n`);\n  }\n  if (!scheduled) {\n    scheduled = true;\n    setTimeout(() => {\n      scheduled = false;\n      void flushEvents();\n    }, 0);\n  }\n}\n\n/**\n * Flush the buffered events to the registry. Safe to await from the CLI exit path\n * to avoid losing the last batch; otherwise it best-effort flushes on a timer.\n */\nexport async function flushEvents(): Promise<void> {\n  if (queue.length === 0) return;\n  if (!(await activityRecording())) {\n    queue = [];\n    return;\n  }\n  let batch = queue;\n  queue = [];\n  // Route-scoped events (`skill.route*`) require an explicit first-run consent\n  // choice before they upload. Until `routeConsentChosen` is true, drop them from\n  // the batch so the legacy absent-`activity` default-on can never silently opt a\n  // deferred/CI user into route uploads. Non-route events keep prior behavior.\n  if (!(await routeConsentChosen())) {\n    batch = batch.filter((e) => !e.name.startsWith('skill.route'));\n  }\n  if (batch.length === 0) return;\n  try {\n    const { token } = await loadRegistryBearer();\n    if (!token) return; // unattributed events aren't useful \u2014 skip\n    const base = (process.env['SKILLET_REGISTRY_URL'] ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n    await fetch(`${base}${REGISTRY_API}/events`, {\n      method: 'POST',\n      headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },\n      body: JSON.stringify({ events: batch }),\n    });\n  } catch {\n    // fail-silent \u2014 telemetry must never break or slow a command.\n  }\n}\n\n/**\n * Report cross-vendor distribution (availability): which of your skills are\n * present in which runtimes on this machine. Current-state upsert, opt-out aware,\n * metadata only (refs + runtime names). Fail-silent and best-effort like the\n * event sink. Sent on sync alongside the lean `sync` event (which never carries\n * the skill list).\n */\nexport async function reportAvailability(skillRefs: string[], runtimes: string[]): Promise<void> {\n  if (skillRefs.length === 0 || runtimes.length === 0) return;\n  if (!(await activityRecording())) return;\n  try {\n    const { token } = await loadRegistryBearer();\n    if (!token) return;\n    const base = (process.env['SKILLET_REGISTRY_URL'] ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n    await fetch(`${base}${REGISTRY_API}/sync/availability`, {\n      method: 'POST',\n      headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },\n      body: JSON.stringify({ skill_refs: skillRefs, runtimes }),\n    });\n  } catch {\n    // fail-silent \u2014 availability reporting must never break or slow a sync.\n  }\n}\n\n/**\n * Disclose default-on activity recording \u2014 but only where no consent surface\n * will ask. An interactive run asks the real question instead (the CLI's\n * skill-stats consent, right after sync), and once the choice is made there\n * is nothing left to disclose. What remains is the headless default-on case:\n * one line, once, and record that it's been shown.\n */\nexport async function maybeDiscloseActivity(): Promise<void> {\n  if (!(await activityRecording())) return;\n  if (await routeConsentChosen()) return;\n  if (process.stdout.isTTY === true) return;\n  const path = join(skilletDir(), 'config.json');\n  let cfg: Record<string, unknown> = {};\n  try {\n    cfg = JSON.parse(await readFile(path, 'utf8')) as Record<string, unknown>;\n  } catch {\n    /* no config yet */\n  }\n  if (cfg['activityDisclosed'] === true) return;\n  process.stderr.write(\n    'Skillet records sync stats (which skills, which agents) to your account. Set SKILLET_ACTIVITY=0 to keep them local.\\n',\n  );\n  cfg['activityDisclosed'] = true;\n  try {\n    await mkdir(skilletDir(), { recursive: true, mode: 0o700 });\n    await writeFile(path, JSON.stringify(cfg, null, 2));\n  } catch {\n    /* best-effort; if we can't persist the flag we'll just disclose again */\n  }\n}\n\nexport interface ActivityState {\n  /** Whether activity is currently being recorded. */\n  recording: boolean;\n  /** What decides it: an env override, the config file, or the default-on. */\n  source: 'env' | 'config' | 'default';\n  /** Whether the first-sync disclosure has been shown. */\n  disclosed: boolean;\n  /** Whether the one-time /skillet route-consent choice has been made. */\n  routeConsentChosen: boolean;\n}\n\n/** The effective activity state, for `skillet activity status`. */\nexport async function activityState(): Promise<ActivityState> {\n  const env = process.env['SKILLET_ACTIVITY'];\n  const cfg = await readConfig();\n  const disclosed = cfg['activityDisclosed'] === true;\n  const configured = cfg['activity'] as boolean | undefined;\n  const base = { disclosed, routeConsentChosen: cfg['routeConsentChosen'] === true };\n  if (env === '0' || env === 'false') return { recording: false, source: 'env', ...base };\n  if (env === '1' || env === 'true') return { recording: true, source: 'env', ...base };\n  if (configured === false) return { recording: false, source: 'config', ...base };\n  if (configured === true) return { recording: true, source: 'config', ...base };\n  return { recording: true, source: 'default', ...base };\n}\n\n/** Persist the local activity opt-in/out (`skillet activity on|off`). */\nexport async function setActivity(on: boolean): Promise<void> {\n  await mergeConfig({ activity: on });\n  recordCache = on; // refresh the in-process cache\n}\n\n/** Parse config.json into a plain object, or {} when absent/unreadable. */\nasync function readConfig(): Promise<Record<string, unknown>> {\n  try {\n    return JSON.parse(await readFile(join(skilletDir(), 'config.json'), 'utf8')) as Record<\n      string,\n      unknown\n    >;\n  } catch {\n    return {};\n  }\n}\n\n/** Read+merge a patch into config.json (mode 0o700 dir), preserving other keys. */\nasync function mergeConfig(patch: Record<string, unknown>): Promise<void> {\n  const cfg = await readConfig();\n  Object.assign(cfg, patch);\n  await mkdir(skilletDir(), { recursive: true, mode: 0o700 });\n  await writeFile(join(skilletDir(), 'config.json'), JSON.stringify(cfg, null, 2));\n}\n\n/**\n * Whether the one-time `/skillet` route-consent choice has been made. Until it\n * has, route-scoped events do not upload (see flushEvents) \u2014 this is the\n * tri-state gate that keeps a deferred/CI user from being silently opted in by\n * the legacy absent-`activity` default-on. Absent means \"not chosen\".\n */\nexport async function routeConsentChosen(): Promise<boolean> {\n  return (await readConfig())['routeConsentChosen'] === true;\n}\n\n/**\n * Persist the first-run route-consent choice. `record` sets the operational\n * activity flag on; staying local sets it off \u2014 either way the choice is marked\n * made so route events may upload when recording is on.\n */\nexport async function chooseRouteConsent(record: boolean): Promise<void> {\n  await setActivity(record);\n  await mergeConfig({ routeConsentChosen: true });\n}\n\nexport function detectInitiator(): Initiator {\n  if (process.env['CI'] || process.env['SKILLET_TOKEN']) return 'ci';\n  if (process.env['SKILLET_DAEMON'] === '1') return 'daemon';\n  return 'human';\n}\n", "// Local route-history store (content-free, local-only). Every `/skillet` route\n// writes one row here regardless of account state or the upload opt-in, so\n// usage-ranked routing and the `skillet usage` dashboard work offline and for\n// anonymous users while uploading nothing.\n//\n// Privacy invariant: the store holds ONLY skill-scoped, non-content fields.\n// Caller-supplied metadata (runtime) is charset+length sanitized here; the skill\n// ref is a kit-derived canonical ref and the timestamp is generated, so both are\n// trusted by construction rather than sanitized.\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { skilletDir } from \"../session-token.js\";\nimport { atomicWrite } from \"../util/atomic.js\";\n\n/** A skill not routed within this window is a prune candidate. */\nexport const USAGE_DEADWEIGHT_DAYS = 30;\n\nconst ROUTE_HISTORY_VERSION = 1;\n\n/** Max length of any recorded metadata value (runtime, source, surface, \u2026). */\nexport const ROUTE_META_MAX = 64;\n\n/** Per-skill aggregate. */\nexport interface SkillUsage {\n  count: number;\n  firstUsed: string;\n  lastUsed: string;\n  runtimes: Record<string, number>;\n}\n\nexport interface RouteHistory {\n  version: number;\n  skills: Record<string, SkillUsage>;\n}\n\n/** Input to a single local-route write. Only these fields are persisted. */\nexport interface LocalRouteInput {\n  skillRef: string;\n  runtime?: string;\n  /** ISO timestamp; defaults to now. */\n  ts?: string;\n}\n\n/** One derived usage row for the dashboard/ranking. */\nexport interface SkillUsageView {\n  skillRef: string;\n  count: number;\n  firstUsed: string;\n  lastUsed: string;\n  runtimes: Record<string, number>;\n  /** True when lastUsed is older than USAGE_DEADWEIGHT_DAYS. */\n  deadWeight: boolean;\n}\n\nfunction routeHistoryPath(): string {\n  return join(skilletDir(), \"route-history.json\");\n}\n\nfunction emptyHistory(): RouteHistory {\n  return { version: ROUTE_HISTORY_VERSION, skills: {} };\n}\n\n/**\n * THE content firewall for all recorded route metadata. Every metadata value\n * that Skillet stores or uploads (runtime, source, surface) passes through here\n * first, so no free text can ever be smuggled into a route record: the value is\n * lowercased, everything outside `[a-z0-9._-]` becomes `-`, and it is capped at\n * ROUTE_META_MAX chars. A task, prompt, or sentence cannot survive this \u2014 it\n * comes out as a short slug. This is the single function that makes the\n * \"never records your task/prompt/reasoning\" guarantee true; keep it that way.\n */\nexport function sanitizeMetaValue(text: string | undefined): string | undefined {\n  if (!text) return undefined;\n  const trimmed = text.trim().toLowerCase();\n  if (!trimmed) return undefined;\n  const safe = trimmed.replace(/[^a-z0-9._-]/g, \"-\").slice(0, ROUTE_META_MAX);\n  return safe || undefined;\n}\n\n/** True when a skill's last route is older than `days`. */\nfunction isStale(lastUsed: string, days: number): boolean {\n  const age = Date.now() - Date.parse(lastUsed);\n  return Number.isFinite(age) && age > days * 24 * 60 * 60 * 1000;\n}\n\nexport async function readRouteHistory(): Promise<RouteHistory> {\n  try {\n    const parsed = JSON.parse(await readFile(routeHistoryPath(), \"utf8\")) as Partial<RouteHistory>;\n    if (!parsed || typeof parsed !== \"object\" || typeof parsed.skills !== \"object\") {\n      return emptyHistory();\n    }\n    // Read only the fields we use; any extra keys (from a newer writer) are\n    // ignored, so the store is forward-compatible without a migration.\n    return {\n      version: parsed.version ?? ROUTE_HISTORY_VERSION,\n      skills: (parsed.skills as Record<string, SkillUsage>) ?? {},\n    };\n  } catch {\n    // Missing or corrupt file \u2014 never throw; ranking/dashboard degrade gracefully.\n    return emptyHistory();\n  }\n}\n\nasync function writeRouteHistory(history: RouteHistory): Promise<void> {\n  try {\n    // Soft analytics cache: keep the atomic rename (no corrupt partial JSON) but\n    // skip the per-write fsync \u2014 this runs on every route and the data is\n    // best-effort, not a durability-critical record.\n    await atomicWrite(routeHistoryPath(), JSON.stringify(history, null, 2) + \"\\n\", {\n      backup: false,\n      fsync: false,\n    });\n  } catch {\n    // fail-silent \u2014 the local store must never break or slow a route.\n  }\n}\n\n/**\n * Record one route locally. Content-free and fail-silent \u2014 never throws and\n * never blocks the route.\n */\nexport async function recordLocalRoute(input: LocalRouteInput): Promise<void> {\n  const skillRef = input.skillRef?.trim();\n  if (!skillRef) return;\n  const ts = input.ts ?? new Date().toISOString();\n  const runtime = sanitizeMetaValue(input.runtime);\n\n  // The read and write are individually fail-silent, but the mutation between\n  // them must not throw either \u2014 a hand-edited/foreign row could omit `runtimes`.\n  // Coerce the reused entry to a well-formed shape and guard the whole body so a\n  // route is never broken by a malformed store.\n  try {\n    const history = await readRouteHistory();\n    const prior = history.skills[skillRef];\n    const skill: SkillUsage = {\n      count: (prior?.count ?? 0) + 1,\n      firstUsed: prior?.firstUsed ?? ts,\n      lastUsed: ts,\n      runtimes: prior?.runtimes ?? {},\n    };\n    if (runtime) skill.runtimes[runtime] = (skill.runtimes[runtime] ?? 0) + 1;\n    history.skills[skillRef] = skill;\n    await writeRouteHistory(history);\n  } catch {\n    // Never break or slow a route on a bad local store.\n  }\n}\n\n/** Derive a display row for one skill (dead-weight flag). */\nfunction toView(skillRef: string, u: SkillUsage): SkillUsageView {\n  return {\n    skillRef,\n    count: u.count,\n    firstUsed: u.firstUsed,\n    lastUsed: u.lastUsed,\n    runtimes: u.runtimes,\n    deadWeight: isStale(u.lastUsed, USAGE_DEADWEIGHT_DAYS),\n  };\n}\n\n/**\n * Order the given manifest refs by the user's own usage: invocation count desc\n * \u2192 last-used desc \u2192 skillRef asc. Refs absent from history collapse\n * to skillRef-ascending after ranked ones, so a cold/anonymous user gets the\n * same deterministic alphabetical order as before.\n */\nexport function rankSkillRefs(manifestRefs: string[], history: RouteHistory): string[] {\n  return [...manifestRefs].sort((a, b) => {\n    const ua = history.skills[a];\n    const ub = history.skills[b];\n    const ca = ua?.count ?? 0;\n    const cb = ub?.count ?? 0;\n    if (cb !== ca) return cb - ca;\n    const la = ua ? Date.parse(ua.lastUsed) : 0;\n    const lb = ub ? Date.parse(ub.lastUsed) : 0;\n    if ((lb || 0) !== (la || 0)) return (lb || 0) - (la || 0);\n    return a.localeCompare(b);\n  });\n}\n\n/** All usage rows as display views, most-used first (for `skillet usage`). */\nexport function usageViews(history: RouteHistory): SkillUsageView[] {\n  return Object.entries(history.skills)\n    .map(([ref, u]) => toView(ref, u))\n    .sort((a, b) => b.count - a.count || a.skillRef.localeCompare(b.skillRef));\n}\n\n/** Serialize the recorded data for export. */\nexport function exportRecord(history: RouteHistory): { version: number; skills: Record<string, SkillUsage> } {\n  return { version: history.version, skills: history.skills };\n}\n\n/** Delete the local route history (delete path). Fail-silent. */\nexport async function clearRouteHistory(): Promise<void> {\n  await writeRouteHistory(emptyHistory());\n}\n", "import { access } from \"node:fs/promises\";\nimport { readState, skillContentPath } from \"../kit/store.js\";\nimport type { SkillEntry } from \"../kit/types.js\";\nimport { detectInitiator, recordEvent } from \"../metrics.js\";\nimport {\n  recordLocalRoute,\n  readRouteHistory,\n  rankSkillRefs,\n  sanitizeMetaValue,\n} from \"../kit/route-history.js\";\nimport type { KitState } from \"../kit/types.js\";\n\nexport const BUNDLED_ROUTE_SLUG = \"@skillet/route\";\n/** On-disk dir name for `@skillet/route` so Cursor exposes `/skillet`, not `/skillet--route`. */\nexport const BUNDLED_ROUTE_MATERIALIZE_DIR = \"skillet\";\n\nexport interface RouteManifestEntry {\n  slug: string;\n  name: string;\n  description: string;\n  owner: string | null;\n  skillRef: string;\n  path: string;\n}\n\nexport type RouteSkillErrorCode = \"kit_empty\" | \"skill_not_in_kit\";\n\n/**\n * Where a /skillet invocation fired \u2014 the \"invocation surface\" axis of route\n * telemetry. Distinct from `runtime` (which agent, e.g. \"cursor\") and `source`\n * (which recorder, e.g. \"cursor-hook\"). Add new recorders here.\n */\nexport const KNOWN_ROUTE_SURFACES = [\n  'user-prompt-submit', // Claude Code / Codex prompt-submit hook\n  'before-submit-prompt', // Cursor hook\n  'skill-instructions', // the bundled @skillet/route skill following its own instructions\n] as const;\nexport type RouteSurface = (typeof KNOWN_ROUTE_SURFACES)[number];\n\nexport interface RouteInvocationOptions {\n  runtime?: string;\n  source?: string;\n  /** Known values in {@link RouteSurface}; anything else is sanitized to a slug. */\n  surface?: string;\n}\n\nexport class RouteSkillError extends Error {\n  readonly code: RouteSkillErrorCode;\n\n  constructor(code: RouteSkillErrorCode, message: string) {\n    super(message);\n    this.name = \"RouteSkillError\";\n    this.code = code;\n  }\n}\n\nexport function skillRefFromEntry(entry: SkillEntry): string {\n  if (entry.slug.startsWith(\"@\")) return entry.slug;\n  if (entry.owner) return `@${entry.owner}/${entry.slug}`;\n  return entry.slug;\n}\n\nfunction isBundledRouteEntry(entry: SkillEntry): boolean {\n  return entry.slug === BUNDLED_ROUTE_SLUG || skillRefFromEntry(entry) === BUNDLED_ROUTE_SLUG;\n}\n\nexport function findSkillEntryByRef(ref: string, state: KitState): SkillEntry | null {\n  const normalized = ref.trim();\n  if (!normalized) return null;\n  if (state.skills[normalized]) return state.skills[normalized];\n  for (const entry of Object.values(state.skills)) {\n    if (skillRefFromEntry(entry) === normalized) return entry;\n  }\n  return null;\n}\n\nexport async function listRouteManifest(): Promise<RouteManifestEntry[]> {\n  const state = await readState();\n  const skills = Object.values(state.skills).filter((entry) => !isBundledRouteEntry(entry));\n\n  const out: RouteManifestEntry[] = [];\n  for (const entry of skills) {\n    const path = skillContentPath(entry.slug);\n    try {\n      await access(path);\n    } catch {\n      continue;\n    }\n    out.push({\n      slug: entry.slug,\n      name: entry.name,\n      description: entry.description,\n      owner: entry.owner ?? null,\n      skillRef: skillRefFromEntry(entry),\n      path,\n    });\n  }\n\n  // Usage-ranked order: the agent picks from the user's own most-used skills\n  // first \u2014 invocation count, then most-recent, then alphabetical. A cold/\n  // anonymous user with no history collapses to skillRef-ascending, i.e. exactly\n  // today's alphabetical output. Fail-silent: any history read error falls back\n  // to the stable alphabetical order rather than breaking routing.\n  try {\n    const history = await readRouteHistory();\n    // Group by skillRef so two kit entries that resolve to the same ref both\n    // survive (rankSkillRefs works on the unique ref set); single rank sort.\n    const groups = new Map<string, RouteManifestEntry[]>();\n    for (const e of out) {\n      const g = groups.get(e.skillRef);\n      if (g) g.push(e);\n      else groups.set(e.skillRef, [e]);\n    }\n    return rankSkillRefs([...groups.keys()], history).flatMap((ref) => groups.get(ref)!);\n  } catch {\n    return out.sort((a, b) => a.skillRef.localeCompare(b.skillRef));\n  }\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// WHAT LEAVES THE MACHINE for a /skillet route (the complete list \u2014 nothing else)\n//\n// A route emits at most two events, uploaded only when the user has opted into\n// recording (see metrics.ts flushEvents + routeConsentChosen). Their fields:\n//\n//   skill.route.invoke  \u2014 one per /skillet invocation:\n//       command  always \"skillet\"\n//       runtime  which agent (e.g. \"cursor\")            } each passed through\n//       source   which recorder fired it (e.g. \"cursor-hook\") } sanitizeMetaValue,\n//       surface  where it fired (e.g. \"user-prompt-submit\")   } so it can only be\n//                                                               a short a-z0-9._- slug\n//   skill.route         \u2014 one per routed pick:\n//       skill_ref  the kit-canonical skill ref (e.g. \"@thiago/the-lazy-dm\")\n//\n// Plus, on every event (recordEvent): the event name, an ISO timestamp, and an\n// initiator tag (human | daemon | ci). No task, prompt, agent reasoning, or any\n// free-text field is ever attached \u2014 sanitizeMetaValue guarantees it.\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function recordRouteInvocation(\n  opts: RouteInvocationOptions = {},\n): { event: \"skill.route.invoke\"; meta: Record<string, string> } {\n  const meta: Record<string, string> = { command: \"skillet\" };\n  const runtime = sanitizeMetaValue(opts.runtime);\n  const source = sanitizeMetaValue(opts.source);\n  const surface = sanitizeMetaValue(opts.surface);\n  if (runtime) meta.runtime = runtime;\n  if (source) meta.source = source;\n  if (surface) meta.surface = surface;\n\n  recordEvent(\"skill.route.invoke\", detectInitiator(), meta);\n  return { event: \"skill.route.invoke\", meta };\n}\n\nexport interface RecordSkillRouteOptions {\n  runtime?: string;\n}\n\nexport async function recordSkillRoute(\n  skillRef: string,\n  opts: RecordSkillRouteOptions = {},\n): Promise<{ skillRef: string; slug: string }> {\n  const state = await readState();\n  if (Object.keys(state.skills).length === 0) {\n    throw new RouteSkillError(\n      \"kit_empty\",\n      \"No skills in your kit. Run `skillet sync` or `skillet add @author/skill` first.\",\n    );\n  }\n\n  const entry = findSkillEntryByRef(skillRef, state);\n  if (!entry || isBundledRouteEntry(entry)) {\n    throw new RouteSkillError(\n      \"skill_not_in_kit\",\n      `Skill not in kit: ${skillRef.trim()}`,\n    );\n  }\n\n  try {\n    await access(skillContentPath(entry.slug));\n  } catch {\n    throw new RouteSkillError(\n      \"skill_not_in_kit\",\n      `Skill not in kit: ${skillRefFromEntry(entry)}`,\n    );\n  }\n\n  const canonicalRef = skillRefFromEntry(entry);\n\n  // Upload the pick only for registry-sourced skills. A registry skill's ref is\n  // already public; a local/private skill's ref is user-authored and could be\n  // sensitive (e.g. `client-acme-layoffs`), so it must never leave the machine.\n  // The uploaded record is the skill ref only \u2014 never the agent's rationale.\n  // Fail safe to privacy: anything not explicitly `registry` (incl. legacy\n  // entries with no source) is treated as local and not uploaded.\n  if (entry.source === \"registry\") {\n    recordEvent(\"skill.route\", detectInitiator(), { skill_ref: canonicalRef });\n  }\n\n  // Local route-history write: unconditional (every route, local or registry) and\n  // independent of the upload opt-in, so your own `skillet usage` dashboard is\n  // complete while local-skill refs never upload. Fail-silent \u2014 never breaks a route.\n  await recordLocalRoute({ skillRef: canonicalRef, runtime: opts.runtime });\n\n  return { skillRef: canonicalRef, slug: entry.slug };\n}\n", "/**\n * Skill reference parser \u2014 `@author/slug` \u2194 `{ author, slug }`.\n *\n * PROTOCOL \u00A71.1: handles are lowercase URL-safe [a-z0-9-], 1-40 chars; slugs\n * are the same character class but allow longer (path-safe). The grammar here\n * is intentionally narrower than what the registry server accepts on publish\n * \u2014 better to refuse early on the client than to issue an HTTP request that\n * the server will 400 on, and the strict regex doubles as a path-traversal\n * gate before we ever interpolate the ref into a URL.\n *\n * Any character outside the allowlist (including `.`, `/`, `\\`, `%`, NUL,\n * whitespace) is rejected with a typed error so callers can give a useful\n * message and so a hostile manifest can never escape into `joinPath`-style\n * traversal.\n *\n * IMPLEMENTATION: the owner/slug grammar and canonicalization now live in the\n * shared `@skillet/protocol/skill-id` module (single source of truth). This\n * file is a thin wrapper that (1) enforces the STRICT wire input shape \u2014 a `@`\n * prefix and a `/` separator, narrower than the tolerant shared `parseRef`,\n * which also accepts bare `owner/slug` and `owner:slug` \u2014 and (2) keeps the\n * historical `SkillRef` shape + `SkillRefError` code names so callers don't\n * need a sweep. The `SkillIdError` thrown by the shared parser is re-typed to\n * `SkillRefError`.\n */\n\nimport { parseRef, SkillIdError, toWireRef } from '@skillet/protocol/skill-id';\n\nexport interface SkillRef {\n  /** Author handle without the leading `@`. */\n  author: string;\n  /** Skill slug. */\n  slug: string;\n  /** Canonical `@author/slug` form. */\n  canonical: string;\n}\n\nexport class SkillRefError extends Error {\n  readonly code: 'invalid_ref' | 'invalid_author' | 'invalid_slug';\n  constructor(code: SkillRefError['code'], message: string) {\n    super(message);\n    this.code = code;\n    this.name = 'SkillRefError';\n  }\n}\n\n/** Map the shared parser's error code onto this module's historical codes. */\nfunction mapErrorCode(code: SkillIdError['code']): SkillRefError['code'] {\n  return code === 'invalid_owner' ? 'invalid_author' : code;\n}\n\n/**\n * Parses `@author/slug` into its components. Rejects anything that does not\n * exactly match the protocol grammar. Use this BEFORE constructing any URL or\n * path \u2014 the validated `{ author, slug }` are safe to interpolate verbatim.\n */\nexport function parseSkillRef(input: string): SkillRef {\n  if (typeof input !== 'string' || input.length === 0) {\n    throw new SkillRefError('invalid_ref', 'Skill ref is empty');\n  }\n  // Strict wire input shape: the shared `parseRef` is tolerant of a missing\n  // `@` and of the `owner:slug` form, but this parser has always required the\n  // canonical `@author/slug` wire ref. Gate those looser forms out here so the\n  // behaviour matches the historical `REF_RE` (`/^@([a-z0-9-]+)\\/([a-z0-9-]+)$/`).\n  if (!input.startsWith('@') || input.includes(':')) {\n    throw new SkillRefError(\n      'invalid_ref',\n      `Skill ref ${JSON.stringify(input)} must look like \"@author/slug\" (lowercase letters, digits, hyphen)`,\n    );\n  }\n  try {\n    const { owner, slug } = parseRef(input);\n    return { author: owner, slug, canonical: toWireRef(input) };\n  } catch (err) {\n    if (err instanceof SkillIdError) {\n      throw new SkillRefError(mapErrorCode(err.code), err.message);\n    }\n    throw err;\n  }\n}\n\n/** Convenience: format components back to `@author/slug` (no validation). */\nexport function formatSkillRef(author: string, slug: string): string {\n  return `@${author}/${slug}`;\n}\n", "import type { SyncManifestItem } from '@skillet/protocol';\nimport { parseRef } from '@skillet/protocol/skill-id';\nimport { parseSkillRef } from '../registry/identifier.js';\nimport type { KitState, SkillEntry } from './types.js';\n\n/**\n * Registry-served version labels are unsigned, attacker-influenced strings\n * rendered straight into terminals and persisted to local state. The server\n * only ever emits \"X.Y.Z\", so anything else is dropped rather than trusted.\n */\nexport function sanitizeVersionLabel(value: unknown): string | undefined {\n  return typeof value === 'string' && /^\\d+\\.\\d+\\.\\d+$/.test(value) ? value : undefined;\n}\n\n/** Whether a local kit entry refers to the same skill as a manifest row. */\nexport function localMatchesManifest(entry: SkillEntry, item: SyncManifestItem): boolean {\n  if (entry.slug === item.ref) return true;\n  if (entry.hash && item.content_hash && entry.hash === item.content_hash) return true;\n  try {\n    const { author, slug } = parseSkillRef(item.ref);\n    if (entry.slug === slug) return true;\n    // Canonical owner+slug comparison, sourced from the shared tolerant\n    // parser rather than a hand-rolled `/`-only join \u2014 so a local slug\n    // persisted as `@owner/slug`, `owner/slug`, or `owner:slug` all match\n    // the same manifest row instead of silently re-materializing.\n    try {\n      const local = parseRef(entry.slug);\n      if (local.owner === author && local.slug === slug) return true;\n    } catch {\n      // entry.slug isn't a parseable owner+slug ref (e.g. a bare slug) \u2014\n      // already covered by the exact-slug check above.\n    }\n    if (entry.owner === author && entry.name === slug) return true;\n  } catch {\n    // Non-canonical manifest ref \u2014 hash/exact slug only.\n  }\n  return false;\n}\n\n/** All local slugs that refer to the same manifest row (for deduped list UIs). */\nexport function findAllLocalsForManifestItem(\n  state: KitState,\n  item: SyncManifestItem,\n): Array<{ slug: string; entry: SkillEntry }> {\n  const matches: Array<{ slug: string; entry: SkillEntry }> = [];\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (localMatchesManifest(entry, item)) {\n      matches.push({ slug, entry });\n    }\n  }\n  matches.sort((a, b) => {\n    if (a.slug === item.ref) return -1;\n    if (b.slug === item.ref) return 1;\n    return a.slug.localeCompare(b.slug);\n  });\n  return matches;\n}\n\n/** Find the local state row for a manifest item, including import aliases. */\nexport function findLocalForManifestItem(\n  state: KitState,\n  item: SyncManifestItem,\n  skipSlugs: ReadonlySet<string> = new Set(),\n): { slug: string; entry: SkillEntry } | undefined {\n  for (const match of findAllLocalsForManifestItem(state, item)) {\n    if (!skipSlugs.has(match.slug)) return match;\n  }\n  return undefined;\n}\n\n/** Prefer the registry canonical ref when presenting a matched skill. */\nexport function alignEntryToManifest(\n  entry: SkillEntry,\n  item: SyncManifestItem,\n): SkillEntry {\n  const label = sanitizeVersionLabel(item.version_label);\n  return {\n    ...entry,\n    slug: item.ref,\n    owner: entry.owner ?? parseSkillRef(item.ref).author,\n    sourceKit: item.source_kit ?? entry.sourceKit ?? null,\n    sourceClass: entry.sourceClass ?? (item.external_author ? 'external' : 'own-kit'),\n    category: item.category ?? entry.category ?? null,\n    // Carry the display label only when the manifest row describes the same\n    // version the local entry holds \u2014 a slug-only match may be behind it.\n    ...(label && entry.hash === item.content_hash\n      ? { versionLabel: label }\n      : {}),\n  };\n}\n", "import type { SyncManifestItem } from '@skillet/protocol';\nimport type { KitState, SkillEntry } from './types.js';\nimport { BUNDLED_ROUTE_SLUG } from '../commands/route.js';\nimport {\n  alignEntryToManifest,\n  findAllLocalsForManifestItem,\n} from './manifest-match.js';\nimport { parseSkillRef } from '../registry/identifier.js';\n\n/** Skills from a registry kit (`sourceKit` set) are eligible for `skillet sync`. */\nexport function isKitSyncedSkill(entry: SkillEntry): boolean {\n  return typeof entry.sourceKit === 'string' && entry.sourceKit.length > 0;\n}\n\n/**\n * Skillet's own skills, shipped as plumbing rather than user content: the\n * bundled `/skillet` router today, plus any future Skillet-authored companion\n * (help, manage, reconcile). They materialize into every runtime regardless of\n * kit membership and are never counted or listed as the user's skills.\n */\nconst SKILLET_SYSTEM_SKILL_SLUGS = new Set<string>([BUNDLED_ROUTE_SLUG]);\n\nexport function isSkilletSystemSkill(entry: SkillEntry): boolean {\n  return SKILLET_SYSTEM_SKILL_SLUGS.has(entry.slug);\n}\n\nexport function kitSyncedSkillEntries(state: KitState): SkillEntry[] {\n  return Object.values(state.skills).filter(isKitSyncedSkill);\n}\n\nexport interface KitSkillGroup {\n  /** `@owner/kit` when synced from a kit; null for skills not in any kit. */\n  kitRef: string | null;\n  skills: SkillEntry[];\n}\n\nfunction groupSkillsByKitFromState(state: KitState): KitSkillGroup[] {\n  const byKit = new Map<string, SkillEntry[]>();\n  const localOnly: SkillEntry[] = [];\n\n  for (const entry of Object.values(state.skills)) {\n    // The bundled `/skillet` router is Skillet's own plumbing \u2014 never a\n    // user-visible kit skill. Hide it from every list surface.\n    if (isSkilletSystemSkill(entry)) continue;\n    if (isKitSyncedSkill(entry)) {\n      const kit = entry.sourceKit as string;\n      const list = byKit.get(kit) ?? [];\n      list.push(entry);\n      byKit.set(kit, list);\n    } else {\n      localOnly.push(entry);\n    }\n  }\n\n  const groups: KitSkillGroup[] = [];\n  for (const [kitRef, skills] of [...byKit.entries()].sort((a, b) =>\n    a[0].localeCompare(b[0]),\n  )) {\n    skills.sort((a, b) => a.slug.localeCompare(b.slug));\n    groups.push({ kitRef, skills });\n  }\n\n  if (localOnly.length > 0) {\n    localOnly.sort((a, b) => a.slug.localeCompare(b.slug));\n    groups.push({ kitRef: null, skills: localOnly });\n  }\n\n  return groups;\n}\n\nexport interface GroupSkillsByKitOptions {\n  /**\n   * When set (including `[]`), kit membership comes from the registry manifest.\n   * Omit or pass `undefined` only when offline \u2014 local `sourceKit` tags apply.\n   */\n  manifestItems?: SyncManifestItem[] | undefined;\n}\n\n/** Build a display entry from a registry manifest row when nothing is local yet. */\nexport function entryFromManifestItem(item: SyncManifestItem): SkillEntry {\n  let owner: string | null = null;\n  let name = item.ref;\n  try {\n    const parsed = parseSkillRef(item.ref);\n    owner = parsed.author;\n    name = parsed.slug;\n  } catch {\n    // Non-canonical ref \u2014 show as-is.\n  }\n  const now = new Date().toISOString();\n  return {\n    slug: item.ref,\n    owner,\n    name,\n    description: '',\n    version: item.version,\n    hash: item.content_hash,\n    source: 'registry',\n    sourceClass: item.external_author ? 'external' : 'own-kit',\n    sourceKit: item.source_kit,\n    subscriberTrust: item.subscriber_trust ?? null,\n    importedAt: now,\n    updatedAt: now,\n  };\n}\n\n/**\n * Group skills for list UIs. With a sync manifest, kits win over local import\n * aliases (e.g. `skillet-sync` vs `@thiago/skillet-sync`).\n */\nexport function groupSkillsByKit(\n  state: KitState,\n  opts?: GroupSkillsByKitOptions,\n): KitSkillGroup[] {\n  const items = opts?.manifestItems;\n  if (items === undefined) {\n    return groupSkillsByKitFromState(state);\n  }\n\n  const consumed = new Set<string>();\n  const byKit = new Map<string, SkillEntry[]>();\n\n  const kitItems = items.filter(\n    (item) => typeof item.source_kit === 'string' && item.source_kit.length > 0,\n  );\n  kitItems.sort((a, b) => {\n    const kit = (a.source_kit ?? '').localeCompare(b.source_kit ?? '');\n    if (kit !== 0) return kit;\n    return a.ref.localeCompare(b.ref);\n  });\n\n  for (const item of kitItems) {\n    const matches = findAllLocalsForManifestItem(state, item).filter(\n      (m) => !consumed.has(m.slug),\n    );\n    const match = matches[0];\n    for (const alias of matches) {\n      consumed.add(alias.slug);\n    }\n    const display = match\n      ? alignEntryToManifest(match.entry, item)\n      : entryFromManifestItem(item);\n    const kit = item.source_kit as string;\n    const list = byKit.get(kit) ?? [];\n    list.push(display);\n    byKit.set(kit, list);\n  }\n\n  const notInKit: SkillEntry[] = [];\n  for (const entry of Object.values(state.skills)) {\n    if (consumed.has(entry.slug)) continue;\n    // The bundled `/skillet` router is Skillet's own plumbing \u2014 never listed.\n    if (isSkilletSystemSkill(entry)) continue;\n    // Kit-synced locals missing from the device manifest are pending prune \u2014 hide\n    // until `skillet sync` reconciles them off this machine.\n    if (isKitSyncedSkill(entry)) continue;\n    notInKit.push(entry);\n  }\n\n  const groups: KitSkillGroup[] = [];\n  for (const [kitRef, skills] of [...byKit.entries()].sort((a, b) =>\n    a[0].localeCompare(b[0]),\n  )) {\n    skills.sort((a, b) => a.slug.localeCompare(b.slug));\n    groups.push({ kitRef, skills });\n  }\n\n  if (notInKit.length > 0) {\n    notInKit.sort((a, b) => a.slug.localeCompare(b.slug));\n    groups.push({ kitRef: null, skills: notInKit });\n  }\n\n  return groups;\n}\n\n/** KitState slice containing only skills that sync to runtimes. */\nexport function kitSyncedState(state: KitState): KitState {\n  const skills: KitState['skills'] = {};\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (isKitSyncedSkill(entry)) {\n      skills[slug] = entry;\n    }\n  }\n  return { version: state.version, skills };\n}\n", "export type SkillDescriptionSource = 'frontmatter' | 'entry' | 'body' | 'slug';\n\nexport interface SkillDescriptionResolution {\n  description: string;\n  source: SkillDescriptionSource;\n}\n\nexport interface SkillDescriptionResolveInput {\n  frontmatterDescription?: string;\n  optsDescription?: string;\n  body: string;\n  slug: string;\n}\n\nfunction firstBodyLine(body: string): string | null {\n  for (const line of body.split('\\n')) {\n    const trimmed = line.trim();\n    if (!trimmed) continue;\n    const withoutHeading = trimmed.replace(/^#+\\s*/, '').trim();\n    return withoutHeading || trimmed;\n  }\n  return null;\n}\n\n/** Resolve the description Cursor and diagnostics use when SKILL.md omits frontmatter. */\nexport function resolveSkillDescription(\n  input: SkillDescriptionResolveInput,\n): SkillDescriptionResolution {\n  const fromFrontmatter = input.frontmatterDescription?.trim();\n  if (fromFrontmatter) {\n    return { description: fromFrontmatter, source: 'frontmatter' };\n  }\n\n  const fromEntry = input.optsDescription?.trim();\n  if (fromEntry) {\n    return { description: fromEntry, source: 'entry' };\n  }\n\n  const fromBody = firstBodyLine(input.body);\n  if (fromBody) {\n    return { description: fromBody, source: 'body' };\n  }\n\n  const fromSlug = input.slug.trim();\n  if (fromSlug) {\n    return { description: fromSlug, source: 'slug' };\n  }\n\n  return { description: 'skill', source: 'slug' };\n}\n", "export * from \"./types.js\";\nexport * from \"./store.js\";\nexport * from \"./sync-scope.js\";\nexport * from \"./route-history.js\";\nexport * from \"./skill-description.js\";\n", "/** Unix mode bits are meaningful for owner-only secrets; Windows ACLs differ. */\nexport function enforcesUnixFilePermissions(): boolean {\n  return process.platform !== \"win32\";\n}\n", "/**\n * Local identity record: ties a handle on the registry to the Ed25519 key\n * held in the user's signing keystore. Stored at $SKILLET_DIR/identity.json,\n * mode 0600 \u2014 owner-only.\n *\n * No OAuth in v1. The Ed25519 key IS the per-device credential; the registry\n * gates write paths on it. `npx @skilletmd/cli` / sync need no OAuth; login/claim\n * happens at first publish.\n */\nimport { readFile, mkdir, chmod, lstat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { atomicWrite } from \"../util/atomic.js\";\nimport { enforcesUnixFilePermissions } from \"../util/unix-perms.js\";\n\nconst SKILLET_DIR = process.env[\"SKILLET_DIR\"] ?? join(homedir(), \".skillet\");\n\nexport interface Identity {\n  handle: string;\n  keyId: string;\n  registryUrl: string;\n  createdAt: string;\n}\n\nexport function identityPath(): string {\n  return join(SKILLET_DIR, \"identity.json\");\n}\n\nexport async function saveIdentity(id: Identity): Promise<void> {\n  await mkdir(SKILLET_DIR, { recursive: true, mode: 0o700 });\n  const path = identityPath();\n  await atomicWrite(path, JSON.stringify(id, null, 2) + \"\\n\", { backup: false, mode: 0o600 });\n  await chmod(path, 0o600); // defense-in-depth: ensure mode even if umask widened it\n}\n\nexport async function loadIdentity(): Promise<Identity | null> {\n  const path = identityPath();\n  let info;\n  try {\n    info = await lstat(path);\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n    throw err;\n  }\n  if (info.isSymbolicLink()) {\n    throw new Error(\n      `Identity file ${path} is a symlink; refusing to load`\n    );\n  }\n  if ((enforcesUnixFilePermissions() && (info.mode & 0o077) !== 0)) {\n    const perm = (info.mode & 0o777).toString(8).padStart(4, \"0\");\n    throw new Error(\n      `Identity file ${path} has insecure permissions ${perm}; expected 0600`\n    );\n  }\n  const raw = await readFile(path, \"utf8\");\n  return JSON.parse(raw) as Identity;\n}\n", "/**\n * Ed25519 author key management and bundle verification.\n *\n * Security invariants (non-negotiable):\n *   - Private keys are NEVER stored in any registry path or PR-mergeable file.\n *   - Private keys are written to $XDG_CONFIG_HOME/skillet/keys/<keyId>.sk at mode 0600.\n *   - Verification is client-side only, fail-closed: throw before any materialization.\n *   - The Skillet release key public half is hardcoded here; the private half lives on\n *     an air-gapped machine and is never committed to this repository.\n */\nimport {\n  generateKeyPairSync,\n  createPrivateKey,\n  createPublicKey,\n  sign,\n  verify,\n  createHash,\n  type KeyObject,\n} from \"node:crypto\";\nimport {\n  readFile,\n  writeFile,\n  mkdir,\n  rename,\n  chmod,\n  unlink,\n  lstat,\n  readdir,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { enforcesUnixFilePermissions } from \"../util/unix-perms.js\";\n\n// Skillet release public key \u2014 hardcoded for adapter manifest verification.\n// The corresponding private key is held on an air-gapped machine (separate offline\n// key ceremony). Rotation requires a new signed binary release.\n// NEVER commit the private key. To replace: run offline ceremony, paste hex here,\n// ship new binary.\nconst SKILLET_RELEASE_PUBLIC_KEY_HEX =\n  \"8c803b7de8f43c4b9bef171f95767659eebd10846a591e5f1206c571cd880154\";\n\n// keyId must be exactly 64 lowercase hex characters (32-byte Ed25519 public key).\n// Validated before any filepath.join to prevent path traversal via crafted keyIds\n// sourced from untrusted registry manifests.\nconst VALID_KEY_ID_RE = /^[0-9a-f]{64}$/;\n\nconst ED25519_SIG_BYTES = 64;\n\nexport interface AuthorKey {\n  keyId: string; // hex-encoded 32-byte Ed25519 public key\n  publicKey: KeyObject;\n  privateKey?: KeyObject; // undefined in verification-only contexts\n}\n\n/** Returns the hex KeyID for a public KeyObject. */\nfunction publicKeyToKeyId(pub: KeyObject): string {\n  const jwk = pub.export({ format: \"jwk\" }) as { x: string };\n  return Buffer.from(jwk.x, \"base64url\").toString(\"hex\");\n}\n\n/** Generates a fresh Ed25519 key pair. Private key is NOT persisted here \u2014 call saveAuthorKey immediately. */\nexport function generateAuthorKey(): AuthorKey {\n  const { privateKey, publicKey } = generateKeyPairSync(\"ed25519\");\n  return {\n    keyId: publicKeyToKeyId(publicKey),\n    publicKey,\n    privateKey,\n  };\n}\n\nfunction keyDir(configDir: string): string {\n  return join(configDir, \"skillet\", \"keys\");\n}\n\nfunction skPath(configDir: string, keyId: string): string {\n  return join(keyDir(configDir), `${keyId}.sk`);\n}\n\n/**\n * Writes the private key to <configDir>/skillet/keys/<keyId>.sk at mode 0600.\n * Directory is created at mode 0700 if absent. Uses temp+rename for atomicity.\n * configDir MUST be the XDG_CONFIG_HOME path \u2014 never a registry or project directory.\n */\nexport async function saveAuthorKey(\n  key: AuthorKey,\n  configDir: string\n): Promise<void> {\n  if (!key.privateKey) {\n    throw new Error(\"Cannot save author key: private key is undefined\");\n  }\n\n  const dir = keyDir(configDir);\n  await mkdir(dir, { recursive: true, mode: 0o700 });\n\n  const pkcs8Der = key.privateKey.export({\n    type: \"pkcs8\",\n    format: \"der\",\n  }) as Buffer;\n  const encoded = pkcs8Der.toString(\"hex\");\n\n  const path = skPath(configDir, key.keyId);\n  const tmp = `${path}.tmp`;\n\n  try {\n    await writeFile(tmp, encoded, { encoding: \"utf8\", mode: 0o600 });\n    await chmod(tmp, 0o600); // explicit: overrides umask\n    await rename(tmp, path);\n  } catch (err) {\n    try {\n      await unlink(tmp);\n    } catch {\n      // best effort cleanup\n    }\n    throw err;\n  }\n}\n\n/**\n * Loads the first author key found in <configDir>/skillet/keys/.\n * Use loadAuthorKeyById for multi-key setups.\n */\nexport async function loadAuthorKey(configDir: string): Promise<AuthorKey> {\n  const dir = keyDir(configDir);\n  let entries: string[];\n  try {\n    entries = await readdir(dir);\n  } catch {\n    throw new Error(`No author key found in ${dir}`);\n  }\n  for (const entry of entries) {\n    if (entry.endsWith(\".sk\")) {\n      const keyId = entry.slice(0, -3);\n      if (VALID_KEY_ID_RE.test(keyId)) {\n        return loadAuthorKeyById(configDir, keyId);\n      }\n    }\n  }\n  throw new Error(`No author key found in ${dir}`);\n}\n\n/**\n * Loads a specific author key by KeyID (hex-encoded public key).\n * Validates the keyId format before constructing any path.\n */\nexport async function loadAuthorKeyById(\n  configDir: string,\n  keyId: string\n): Promise<AuthorKey> {\n  if (!VALID_KEY_ID_RE.test(keyId)) {\n    throw new Error(\n      `Invalid key ID \"${keyId}\": must be 64 lowercase hex characters`\n    );\n  }\n\n  const path = skPath(configDir, keyId);\n\n  const info = await lstat(path);\n  if (info.isSymbolicLink()) {\n    throw new Error(\n      `Key file ${path} is a symlink; refusing to load`\n    );\n  }\n  if (enforcesUnixFilePermissions() && (info.mode & 0o077) !== 0) {\n    const perm = (info.mode & 0o777).toString(8).padStart(4, \"0\");\n    throw new Error(\n      `Key file ${path} has insecure permissions ${perm}; expected 0600`\n    );\n  }\n\n  const raw = await readFile(path, \"utf8\");\n  const pkcs8Der = Buffer.from(raw.trim(), \"hex\");\n\n  const privateKey = createPrivateKey({\n    key: pkcs8Der,\n    format: \"der\",\n    type: \"pkcs8\",\n  });\n  const publicKey = createPublicKey(privateKey);\n\n  const derivedKeyId = publicKeyToKeyId(publicKey);\n  if (derivedKeyId !== keyId) {\n    throw new Error(\n      `Key file ID mismatch: file says ${keyId}, derived public key is ${derivedKeyId}`\n    );\n  }\n\n  return { keyId, publicKey, privateKey };\n}\n\n/**\n * Signs SHA-256(bundle) with the author's Ed25519 private key.\n * Returns a 64-byte signature.\n * Throws if privateKey is absent (verification-only key).\n */\nexport function signBundle(bundle: Buffer, key: AuthorKey): Buffer {\n  if (!key.privateKey) {\n    throw new Error(\n      \"Cannot sign: private key is undefined (verification-only key)\"\n    );\n  }\n  const digest = createHash(\"sha256\").update(bundle).digest();\n  return sign(null, digest, key.privateKey);\n}\n\n/**\n * Verifies that sig is a valid Ed25519 signature over SHA-256(bundle) by publicKey.\n * Throws a descriptive error for every failure mode.\n *\n * MUST be called before any file is materialized. Callers must treat any thrown\n * error as a hard stop: refuse materialization, exit non-zero, no partial writes.\n */\nexport function verifyBundle(\n  bundle: Buffer,\n  sig: Buffer,\n  publicKey: KeyObject\n): void {\n  if (!sig || sig.length === 0) {\n    throw new Error(\n      \"Signature verification failed: missing or empty signature\"\n    );\n  }\n  if (sig.length !== ED25519_SIG_BYTES) {\n    throw new Error(\n      `Signature verification failed: invalid length ${sig.length} (expected ${ED25519_SIG_BYTES})`\n    );\n  }\n  if (sig.every((b) => b === 0)) {\n    throw new Error(\n      \"Signature verification failed: all-zero signature rejected\"\n    );\n  }\n\n  const digest = createHash(\"sha256\").update(bundle).digest();\n  const valid = verify(null, digest, publicKey, sig);\n  if (!valid) {\n    throw new Error(\n      \"Signature verification failed: signature does not match bundle content\"\n    );\n  }\n}\n\n/**\n * Returns the hardcoded Skillet release public key used to verify adapter manifests.\n * Not user-configurable. Each call returns an independent KeyObject.\n */\nexport function skilletReleasePublicKey(): KeyObject {\n  const raw = Buffer.from(SKILLET_RELEASE_PUBLIC_KEY_HEX, \"hex\");\n  const jwk = { kty: \"OKP\", crv: \"Ed25519\", x: raw.toString(\"base64url\") };\n  return createPublicKey({ key: jwk, format: \"jwk\" });\n}\n", "import { execSync } from 'node:child_process';\nimport { createHmac } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\n\n/**\n * Stable, privacy-preserving machine identity.\n *\n * The OS machine id (IOPlatformUUID / /etc/machine-id / MachineGuid) is keyed\n * through HMAC-SHA256 per machine-id(5): the raw value never leaves the\n * machine, and the digest cannot be correlated with other applications'\n * derivations. The app key is domain separation, not a secret \u2014 but changing\n * it re-mints every machine identity fleet-wide, so it is versioned and fixed.\n *\n * The digest is a same-account dedupe hint for the registry (device-row\n * reclaim), never authentication: cloned VMs and imaged machines can share an\n * OS machine id.\n */\nconst MACHINE_IDENTITY_APP_KEY = 'md.skillet.machine-identity.v1';\n\nfunction readRawMacOs(): string | null {\n  try {\n    const out = execSync('ioreg -rd1 -c IOPlatformExpertDevice', {\n      encoding: 'utf8',\n      timeout: 2000,\n      stdio: ['ignore', 'pipe', 'ignore'],\n    });\n    const match = out.match(/\"IOPlatformUUID\"\\s*=\\s*\"([^\"]+)\"/);\n    return match?.[1] ?? null;\n  } catch {\n    return null;\n  }\n}\n\nfunction readRawLinux(): string | null {\n  for (const path of ['/etc/machine-id', '/var/lib/dbus/machine-id']) {\n    try {\n      const raw = readFileSync(path, 'utf8');\n      if (raw.trim().length > 0) return raw;\n    } catch {\n      // fall through to the next source\n    }\n  }\n  return null;\n}\n\nfunction readRawWindows(): string | null {\n  try {\n    const out = execSync(\n      'reg query \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Cryptography\" /v MachineGuid',\n      { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] },\n    );\n    const match = out.match(/MachineGuid\\s+REG_SZ\\s+(\\S+)/);\n    return match?.[1] ?? null;\n  } catch {\n    return null;\n  }\n}\n\nfunction readRawMachineId(): string | null {\n  switch (process.platform) {\n    case 'darwin':\n      return readRawMacOs();\n    case 'linux':\n      return readRawLinux();\n    case 'win32':\n      return readRawWindows();\n    default:\n      return null;\n  }\n}\n\n/**\n * Derive the app-scoped digest from a raw OS machine id. Pure; exported for\n * tests. Whitespace and case must not change the digest (the same physical id\n * is reported with different casing across OS tools), and a missing or\n * never-initialized id (systemd writes the literal `uninitialized`) yields\n * null rather than a digest of a non-identity.\n */\nexport function deriveMachineId(raw: string | null | undefined): string | null {\n  const normalized = raw?.trim().toLowerCase() ?? '';\n  if (normalized.length === 0 || normalized === 'uninitialized') return null;\n  return createHmac('sha256', normalized).update(MACHINE_IDENTITY_APP_KEY).digest('hex');\n}\n\nlet cached: string | null | undefined;\n\n/**\n * The machine's stable identity digest, or null when the OS id is unavailable\n * (containers without /etc/machine-id, group-policy-blocked reg.exe, unknown\n * platforms). Callers own the fallback \u2014 see auth-connect-pair, which falls\n * back to the persisted device.json id, then a random UUID. Cached per\n * process: the underlying id cannot change while we run.\n */\nexport function stableMachineId(): string | null {\n  if (cached === undefined) cached = deriveMachineId(readRawMachineId());\n  return cached;\n}\n\n/** Test-only: clear the per-process cache. */\nexport function resetMachineIdCacheForTests(): void {\n  cached = undefined;\n}\n", "/**\n * Typed HTTP client for the Skillet registry (PROTOCOL \u00A75/\u00A76.1).\n *\n * Endpoints consumed (under `/api/v1/`, mounted on every Skillet-protocol\n * registry):\n *\n *   GET  /api/v1/skills/:author/:slug/manifest        \u2014 ETag/304, lists versions\n *   GET  /api/v1/skills/:author/:slug/versions/:hash  \u2014 full bundle + signature\n *   GET  /api/v1/sync/manifest?owner=<handle>         \u2014 union sync manifest\n *   GET  /api/v1/sync/content/:content_hash           \u2014 bundle by canonical hash\n *   GET  /api/v1/skills/:owner/:slug/diff?from=&to=   \u2014 server-rendered unified diff\n *   POST /api/v1/profiles                             \u2014 register an author handle\n *   POST /api/v1/skills                               \u2014 publish a signed bundle (\u00A74)\n *   POST /api/v1/skills/:author/:slug/install         \u2014 bump install_count metric\n *\n * Design notes:\n * - Uses globalThis.fetch (Node \u226518). Injectable for tests via `fetchImpl`.\n * - ETag/If-None-Match wired through every cacheable read; the caller threads\n *   the previously-seen tag in and gets a `notModified: true` result back\n *   instead of having to interpret a 304 directly.\n * - All path-interpolated components are validated through `parseSkillRef`\n *   or hash-shape regex before joining \u2014 a hostile registry response cannot\n *   coerce the client into a different URL.\n * - Bundle normalisation: \u00A72.1 lets the server return either `files`\n *   (multi-file canonical) or `content` (legacy single-file). The client\n *   surfaces a `DecodedBundle` either way so callers never branch on age.\n * - Content_hash is the canonical `sha256:<hex>` string everywhere the\n *   protocol uses it (PROTOCOL \u00A72.2); the manifest endpoint's `latest_hash`\n *   ships raw hex for legacy reasons and is canonicalised on read.\n * - Bearer auth is supported via `token` on every method; until the\n *   server enforces it on the sync endpoints, an `?owner=` query stub is\n *   accepted on `getSyncManifest` so existing tests/dev runs work.\n */\n\nimport {\n  CONTENT_HASH_PREFIX,\n  REGISTRY_VERSION_PREFIX,\n  canonicalContentHash,\n  decodeBundle,\n  type AuthorSignature,\n  type BundleFiles,\n  type ContentBundle,\n  type DecodedBundle,\n  type DiffResponse,\n  type SignedDelegation,\n  type SignedRevocation,\n  type SkillManifest,\n  type SyncManifest,\n  resolveArtifactSchemaVersion,\n} from '@skillet/protocol'\nimport { type Signature as Ed25519Envelope } from '../signing/envelope.js'\nimport { REGISTRY_API } from '../registry-api.js'\nimport { stableMachineId } from '../machine-identity.js'\nimport { parseSkillRef } from './identifier.js'\n\nconst HASH_RE = /^[0-9a-f]{64}$/\nconst PREFIXED_HASH_RE = /^sha256:[0-9a-f]{64}$/\n\n/** Per-skill manifest enriched with the server's identity fields. */\nexport interface RegistryManifest extends SkillManifest {\n  /** Hex Ed25519 key id; absent for unclaimed authors. */\n  author_key_id?: string | null\n  /** Base64 of the 32 raw Ed25519 public-key bytes; absent for unclaimed authors. */\n  author_public_key?: string | null\n  /** Per-version signature (and display-only semver label) carried on the manifest. */\n  versions: Array<\n    SkillManifest['versions'][number] & {\n      signature?: AuthorSignature | null\n      version_label?: string\n    }\n  >\n}\n\n/** A scan finding as carried on the publish response / scan_blocked body\n *  Snippets are never sent on the wire; file:line locates it. */\nexport interface ScanWireFinding {\n  category: string\n  confidence: 'low' | 'medium' | 'high'\n  file: string\n  lineStart: number\n  lineEnd: number\n  why: string\n}\n\n/** The shape of a 422 `scan_blocked` body (RegistryError.body when code is\n *  `scan_blocked`). `reason` distinguishes a leaked credential from a confirmed\n *  -dangerous verdict so the CLI can tailor the fix guidance. */\nexport interface ScanBlockedBody {\n  error: 'scan_blocked'\n  reason: 'secret' | 'quarantine'\n  status: 'quarantined'\n  message: string\n  findings: ScanWireFinding[]\n}\n\n/** Cache-aware result wrapper \u2014 distinguishes 304 from 200 without exposing HTTP. */\nexport interface CacheableResult<T> {\n  /** Strong ETag (quoted) as the server returned it. */\n  etag: string | null\n  /** True when the server responded 304. `value` is null in that case. */\n  notModified: boolean\n  value: T | null\n}\n\n/** A version response from `/api/v1/skills/:author/:slug/versions/:hash`. */\nexport interface VersionDetail {\n  hash: string\n  skill_id: string\n  author: string\n  slug: string\n  bundle: DecodedBundle\n  /** Canonical `sha256:<hex>` string the server says is the bundle's hash. */\n  content_hash: string\n  signature: AuthorSignature | null\n  author_key_id: string | null\n  /**\n   * Base64 of the 32 raw Ed25519 public-key bytes (extension to \u00A74).\n   * Null when the publishing author has not yet claimed a key \u2014 in that case\n   * the consumer MUST refuse TOFU pinning rather than fabricate one.\n   */\n  author_public_key: string | null\n  /**\n   * Inline SignedDelegation \u2014 present iff the version was signed by a\n   * delegated DEVICE key. Lets the client verify device_sig \u2190 cert \u2190 primary\n   * key offline. The client re-verifies cert_sig against its TOFU-pinned primary\n   * key, never this registry-served material.\n   */\n  delegation: SignedDelegation | null\n  metadata: Record<string, unknown>\n  published_at: number\n  published_by: string\n  /** Display-only semver label (\"X.Y.Z\"); absent on older servers. */\n  version_label?: string\n}\n\n/** One row of `GET /api/v1/delegations` (the caller's own delegations). */\nexport interface DelegationListItem {\n  device_key_id: string\n  label: string | null\n  scopes: string[]\n  issued_at: number\n  expires_at: number\n  revoked_at: number | null\n  status: 'active' | 'expired' | 'revoked'\n}\n\n/** One row of `GET /api/v1/devices` (session-bound sync agents from connect/pair). */\nexport interface BearerDeviceListItem {\n  device_id: string\n  label: string | null\n  created_at: number\n  agents?: string[]\n  agents_reported_at?: number | null\n  client_kind?: string | null\n}\n\n/** One account-scoped update decision (server source of truth). `version_hash`\n *  is the canonical content hash; the local lock reconciles against it. */\nexport interface AccountDecision {\n  skill_id: string\n  version_hash: string\n  state: 'approved' | 'rejected'\n  source: 'web' | 'desktop' | 'cli' | 'auto'\n  decided_at: number\n}\n\nexport interface AccountDecisions {\n  update_mode: 'auto' | 'manual'\n  decisions: AccountDecision[]\n}\n\n/** Kit payload from GET /kits/by-handle/:owner/:slug. */\nexport interface RegistryKitView {\n  id: string\n  owner: string\n  name: string\n  slug: string\n  description: string | null\n  visibility: string\n  subscribed?: boolean\n  skills: Array<{\n    skill_id: string\n    description?: string | null\n    visibility?: string\n  }>\n}\n\nexport interface RegistryClientOptions {\n  /** Registry base URL, e.g. `https://registry.skillet.md`. No trailing slash. */\n  baseUrl: string\n  /** Optional Bearer token. Omit for public read paths. */\n  token?: string\n  /**\n   * Client version sent as `X-Skillet-Client-Version` on every request so the\n   * registry can evaluate a minimum-supported-version floor. Defaults to\n   * `process.env.SKILLET_CLIENT_VERSION` (the CLI sets this to its build\n   * version), so core never has to import the CLI's version constant.\n   */\n  clientVersion?: string\n  /** Inject an alternate fetch impl for tests. Defaults to globalThis.fetch. */\n  fetchImpl?: typeof fetch\n}\n\nexport class RegistryError extends Error {\n  readonly code: string\n  readonly status?: number\n  readonly body?: unknown\n  constructor(code: string, message: string, status?: number, body?: unknown) {\n    super(message)\n    this.code = code\n    this.status = status\n    this.body = body\n    this.name = 'RegistryError'\n  }\n}\n\nexport class RegistryClient {\n  private readonly baseUrl: string\n  private readonly token?: string\n  private readonly clientVersion?: string\n  private readonly machineId: string | null\n  private readonly clientKind: 'cli' | 'desktop'\n  private readonly fetchImpl: typeof fetch\n\n  constructor(opts: RegistryClientOptions) {\n    if (!opts.baseUrl || typeof opts.baseUrl !== 'string') {\n      throw new Error('RegistryClient: baseUrl is required')\n    }\n    // Normalise \u2014 drop trailing slashes so `${baseUrl}${path}` is unambiguous.\n    this.baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n    this.token = opts.token\n    this.clientVersion = opts.clientVersion ?? process.env['SKILLET_CLIENT_VERSION'] ?? undefined\n    // Identity convergence (R7): every authed request reports the machine and\n    // client kind so the registry backfills device rows without a re-pair.\n    // The desktop tray sets SKILLET_CLIENT_KIND=desktop on its sidecar spawn;\n    // everything else is the CLI.\n    this.machineId = stableMachineId()\n    this.clientKind = process.env['SKILLET_CLIENT_KIND'] === 'desktop' ? 'desktop' : 'cli'\n    const f = opts.fetchImpl ?? globalThis.fetch\n    if (typeof f !== 'function') {\n      throw new Error('RegistryClient: no fetch implementation available')\n    }\n    // Bind so the function keeps its receiver when stored on `this`.\n    this.fetchImpl = f.bind(globalThis)\n  }\n\n  /**\n   * The account this client's bearer resolves to, or null when anonymous,\n   * offline, or the token is dead. Used by the update gate to resolve\n   * \"self\" by account handle \u2014 web-first accounts have no local signing\n   * key, so key identity alone cannot recognize their own skills.\n   */\n  async whoami(): Promise<{ user_id: string | null; handle: string | null } | null> {\n    try {\n      const res = await this.request('GET', '/whoami')\n      if (res.status !== 200) return null\n      const body = (await res.json()) as { user_id?: string | null; handle?: string | null }\n      return { user_id: body.user_id ?? null, handle: body.handle ?? null }\n    } catch {\n      return null\n    }\n  }\n\n  /** Public registry URL \u2014 useful when persisting where a skill came from. */\n  get url(): string {\n    return this.baseUrl\n  }\n\n  /**\n   * GET /api/v1/skills/:author/:slug/manifest with optional `If-None-Match`.\n   * Returns `notModified=true` when the server replies 304.\n   */\n  async getSkillManifest(\n    ref: string,\n    opts: { etag?: string | null } = {},\n  ): Promise<CacheableResult<RegistryManifest>> {\n    const { author, slug } = parseSkillRef(ref)\n    const path = `/skills/${author}/${slug}/manifest`\n    const res = await this.request('GET', path, { ifNoneMatch: opts.etag })\n    if (res.status === 304) {\n      return { etag: res.headers.get('etag'), notModified: true, value: null }\n    }\n    if (res.status !== 200) {\n      await throwForStatus(res, `manifest for ${ref}`)\n    }\n    const body = (await res.json()) as RegistryManifest\n    resolveArtifactSchemaVersion(body.schema_version, `manifest for ${ref}`)\n    return {\n      etag: res.headers.get('etag'),\n      notModified: false,\n      value: body,\n    }\n  }\n\n  /**\n   * GET /api/v1/skills/:author/:slug/versions/:hash.\n   *\n   * Accepts the hash as either `sha256:<hex>` or raw hex. The server stores\n   * canonical hashes in their `sha256:`-prefixed form (PROTOCOL \u00A72.2), so we\n   * always send the prefixed form (URL-encoded). The result's `content_hash`\n   * is always the canonical `sha256:<hex>` form so downstream verifies don't\n   * have to branch on shape.\n   */\n  async getVersion(ref: string, hash: string): Promise<VersionDetail> {\n    const { author, slug } = parseSkillRef(ref)\n    const rawHash = stripHashPrefix(hash)\n    if (!HASH_RE.test(rawHash)) {\n      throw new RegistryError(\n        'invalid_hash',\n        `Hash ${JSON.stringify(hash)} must be 64 lowercase hex chars (optionally prefixed with sha256:)`,\n      )\n    }\n    const prefixed = `${CONTENT_HASH_PREFIX}${rawHash}`\n    const path = `/skills/${author}/${slug}/versions/${encodeURIComponent(prefixed)}`\n    const res = await this.request('GET', path)\n    if (res.status !== 200) {\n      await throwForStatus(res, `version ${rawHash} for ${ref}`)\n    }\n    const body = (await res.json()) as {\n      hash: string\n      skill_id: string\n      author: string\n      slug: string\n      files?: BundleFiles\n      content?: string\n      content_hash?: string\n      signature: AuthorSignature | null\n      author_key_id: string | null\n      author_public_key?: string | null\n      delegation?: SignedDelegation | null\n      metadata?: Record<string, unknown>\n      published_at: number\n      published_by: string\n      schema_version?: number\n    }\n\n    resolveArtifactSchemaVersion(body.schema_version, `version ${rawHash} for ${ref}`)\n\n    const bundle = bundleFromResponse(body.files, body.content)\n    return {\n      hash: body.hash,\n      skill_id: body.skill_id,\n      author: body.author,\n      slug: body.slug,\n      bundle,\n      content_hash:\n        body.content_hash && PREFIXED_HASH_RE.test(body.content_hash)\n          ? body.content_hash\n          : `${CONTENT_HASH_PREFIX}${stripHashPrefix(body.hash)}`,\n      signature: body.signature ?? null,\n      author_key_id: body.author_key_id ?? null,\n      author_public_key: body.author_public_key ?? null,\n      delegation: body.delegation ?? null,\n      metadata: body.metadata ?? {},\n      published_at: body.published_at,\n      published_by: body.published_by,\n    }\n  }\n\n  /**\n   * GET /api/v1/sync/manifest. PROTOCOL \u00A76.1 \u2014 union of caller's default kit\n   * + subscribed kits.\n   *\n   * Auth: `Authorization: Bearer` once the client has a session token. Until\n   * then the server-side stub accepts `?owner=<handle>`; passing `owner` here\n   * appends it to the query string for dev/test compatibility. New code SHOULD\n   * use the bearer-token path.\n   */\n  async getSyncManifest(\n    opts: { etag?: string | null; owner?: string; device?: string } = {},\n  ): Promise<CacheableResult<SyncManifest>> {\n    const params = new URLSearchParams()\n    if (opts.owner) params.set('owner', opts.owner)\n    if (opts.device) params.set('device', opts.device) // per-machine kit routing\n    const qs = params.toString() ? `?${params.toString()}` : ''\n    const res = await this.request('GET', `/sync/manifest${qs}`, {\n      ifNoneMatch: opts.etag,\n    })\n    if (res.status === 304) {\n      return { etag: res.headers.get('etag'), notModified: true, value: null }\n    }\n    if (res.status !== 200) {\n      await throwForStatus(res, 'sync manifest')\n    }\n    const body = (await res.json()) as SyncManifest\n    resolveArtifactSchemaVersion(body.schema_version, 'sync manifest')\n    return { etag: res.headers.get('etag'), notModified: false, value: body }\n  }\n\n  /**\n   * GET /api/v1/sync/content/:content_hash. Returns a decoded bundle alongside\n   * the canonical hash the server stamped on it. Multi-file `files` is\n   * preferred (PROTOCOL \u00A72.1); legacy `content` is honoured as a fallback so\n   * the client keeps working through the bundle-model migration.\n   */\n  async getContentBundle(\n    contentHash: string,\n  ): Promise<{ contentHash: string; bundle: DecodedBundle }> {\n    const raw = stripHashPrefix(contentHash)\n    if (!HASH_RE.test(raw)) {\n      throw new RegistryError(\n        'invalid_hash',\n        `Hash ${JSON.stringify(contentHash)} must be 64 lowercase hex chars (optionally prefixed with sha256:)`,\n      )\n    }\n    // The sync content route strips a `sha256:` prefix client-side, but the\n    // version-detail route does not \u2014 keep both endpoints' URLs consistent\n    // by always sending the prefixed form URL-encoded.\n    const prefixed = `${CONTENT_HASH_PREFIX}${raw}`\n    const res = await this.request('GET', `/sync/content/${encodeURIComponent(prefixed)}`)\n    if (res.status !== 200) {\n      await throwForStatus(res, `content bundle ${raw}`)\n    }\n    const body = (await res.json()) as ContentBundle\n    resolveArtifactSchemaVersion(body.schema_version, 'sync content bundle')\n    const bundle = bundleFromResponse(body.files, body.content)\n    const requestedHash = PREFIXED_HASH_RE.test(contentHash)\n      ? contentHash\n      : `${CONTENT_HASH_PREFIX}${raw}`\n    const recomputed = canonicalContentHash(bundle)\n    if (recomputed !== requestedHash) {\n      throw new RegistryError(\n        'integrity_failed',\n        `Content bundle hash mismatch (requested ${requestedHash}, recomputed ${recomputed})`,\n      )\n    }\n    return {\n      contentHash: requestedHash,\n      bundle,\n    }\n  }\n\n  /**\n   * GET /api/v1/skills/:owner/:slug/diff?from=&to= \u2014 server-rendered unified\n   * diff. Surfaced for completeness (\u00A76.2); the consumer's graded-diff\n   * UI computes the diff locally against materialized state, so this is used\n   * only for cross-checks.\n   */\n  async getDiff(ref: string, from: string, to: string): Promise<DiffResponse> {\n    const { author, slug } = parseSkillRef(ref)\n    const f = stripHashPrefix(from)\n    const t = stripHashPrefix(to)\n    if (!HASH_RE.test(f) || !HASH_RE.test(t)) {\n      throw new RegistryError(\n        'invalid_hash',\n        `Diff hashes must be 64 lowercase hex chars (got from=${from} to=${to})`,\n      )\n    }\n    const qs = `?from=${f}&to=${t}`\n    const res = await this.request('GET', `/skills/${author}/${slug}/diff${qs}`)\n    if (res.status !== 200) {\n      await throwForStatus(res, `diff for ${ref}`)\n    }\n    return (await res.json()) as DiffResponse\n  }\n\n  /**\n   * POST /api/v1/profiles \u2014 register an author handle. Returns the created\n   * profile body on 201. Throws RegistryError('handle_taken', ..., 409) when\n   * the handle is already registered so the caller can detect re-login.\n   */\n  async createProfile(body: {\n    id: string\n    name: string\n    avatar_url?: string\n  }): Promise<Record<string, unknown>> {\n    const res = await this.postRequest('/profiles', body)\n    if (res.status === 409) {\n      let b: unknown\n      try {\n        b = await res.json()\n      } catch {\n        b = null\n      }\n      throw new RegistryError('handle_taken', pickMessage(b) ?? 'Handle already registered', 409, b)\n    }\n    if (res.status !== 201) {\n      await throwForStatus(res, `create profile ${body.id}`)\n    }\n    return (await res.json()) as Record<string, unknown>\n  }\n\n  /** Result of a successful publishSkill call. */\n  // status 200 = content already known (idempotent no-op); 201 = new version\n  async publishSkill(body: {\n    author: string\n    slug: string\n    files: BundleFiles\n    base_hash: string | null\n    signature?: Ed25519Envelope\n    publish_auth?: 'session'\n    visibility?: 'private' | 'public'\n    metadata?: Record<string, unknown>\n  }): Promise<{\n    hash: string\n    skill_id: string\n    version_url: string\n    already_exists: boolean\n    scan?: { status: 'clean' | 'flagged' | 'quarantined'; findings: ScanWireFinding[] }\n  }> {\n    const res = await this.postRequest('/skills', body)\n    if (res.status === 409) {\n      let b: unknown\n      try {\n        b = await res.json()\n      } catch {\n        b = null\n      }\n      throw new RegistryError('conflict', pickMessage(b) ?? 'Local is behind remote', 409, b)\n    }\n    // The publish gate hard-blocks a secret or quarantined verdict with\n    // a 422 carrying the concrete findings. Surface it as a typed error so the\n    // CLI can render the fix guidance instead of a generic HTTP failure.\n    if (res.status === 422) {\n      let b: unknown\n      try {\n        b = await res.json()\n      } catch {\n        b = null\n      }\n      const parsed = b as { error?: string; message?: string } | null\n      if (parsed?.error === 'scan_blocked') {\n        throw new RegistryError(\n          'scan_blocked',\n          parsed.message ?? 'Publish blocked by the scanner.',\n          422,\n          b,\n        )\n      }\n    }\n    if (res.status !== 200 && res.status !== 201) {\n      await throwForStatus(res, `publish ${body.author}/${body.slug}`)\n    }\n    const payload = (await res.json()) as {\n      hash: string\n      skill_id: string\n      version_url: string\n      scan?: { status: 'clean' | 'flagged' | 'quarantined'; findings: ScanWireFinding[] }\n    }\n    return { ...payload, already_exists: res.status === 200 }\n  }\n\n  /**\n   * POST /api/v1/skills/:author/:slug/proposals \u2014 submit a pending proposal.\n   * Server returns 201 with `proposal_url` (not `review_url`).\n   */\n  async proposeSkill(body: {\n    author: string\n    slug: string\n    files: BundleFiles\n    base_hash: string | null\n    signature: Ed25519Envelope\n  }): Promise<{ proposal_id: string; proposal_url: string; state: string; proposed_hash: string }> {\n    const { author, slug, ...rest } = body\n    const path = `/skills/${encodeURIComponent(author)}/${encodeURIComponent(slug)}/proposals`\n    const res = await this.postRequest(path, rest)\n    if (res.status === 409) {\n      let b: unknown\n      try {\n        b = await res.json()\n      } catch {\n        b = null\n      }\n      throw new RegistryError('conflict', pickMessage(b) ?? 'Local is behind remote', 409, b)\n    }\n    // Mirror publishSkill: the proposal secret gate hard-blocks with a 422\n    // carrying concrete findings. Read the body ONCE \u2014 falling through to\n    // throwForStatus after `res.json()` would re-read a consumed stream and lose\n    // the server's real code/message.\n    if (res.status === 422) {\n      let b: unknown\n      try {\n        b = await res.json()\n      } catch {\n        b = null\n      }\n      const parsed = b as\n        | { error?: string; message?: string; finding?: ScanWireFinding; findings?: ScanWireFinding[] }\n        | null\n      if (parsed?.error === 'scan_blocked') {\n        // The proposal-create route emits a singular `finding`; publish/approve\n        // use `findings`. Normalize to an array so one CLI parser handles both.\n        const findings = parsed.findings ?? (parsed.finding ? [parsed.finding] : [])\n        throw new RegistryError(\n          'scan_blocked',\n          parsed.message ?? 'Proposal blocked by the scanner.',\n          422,\n          { ...parsed, findings },\n        )\n      }\n      // Any other 422 \u2014 surface the server's own code/message from the body we\n      // already read (do NOT re-read via throwForStatus).\n      throw new RegistryError(\n        parsed?.error ?? 'unprocessable_entity',\n        parsed?.message ?? `Proposal rejected (HTTP 422)`,\n        422,\n        b,\n      )\n    }\n    if (res.status !== 201) {\n      await throwForStatus(res, `propose ${author}/${slug}`)\n    }\n    const payload = (await res.json()) as {\n      proposal_id: string\n      proposal_url?: string\n      state: string\n      proposed_hash: string\n    }\n    return {\n      proposal_id: payload.proposal_id,\n      proposal_url:\n        payload.proposal_url ?? `${REGISTRY_API}/skills/${author}/${slug}/proposals/${payload.proposal_id}`,\n      state: payload.state,\n      proposed_hash: payload.proposed_hash,\n    }\n  }\n\n  /**\n   * GET /api/v1/skills/:author/:slug/proposals \u2014 list proposals for a skill.\n   */\n  async listProposals(\n    ref: string,\n  ): Promise<\n    Array<{\n      proposal_id: string\n      proposed_hash: string\n      state: string\n      proposer: string\n      proposal_url: string\n      created_at: number\n    }>\n  > {\n    const { author, slug } = parseSkillRef(ref)\n    const path = `/skills/${author}/${slug}/proposals`\n    const res = await this.request('GET', path)\n    if (res.status !== 200) {\n      await throwForStatus(res, `list proposals for ${ref}`)\n    }\n    const body = (await res.json()) as {\n      proposals: Array<{\n        proposal_id: string\n        proposed_hash: string\n        state: string\n        proposer: string\n        proposal_url: string\n        created_at: number\n      }>\n    }\n    return body.proposals\n  }\n\n  /**\n   * GET /api/v1/skills/:author/:slug/proposals/:proposalId \u2014 proposal detail.\n   */\n  async getProposal(\n    ref: string,\n    proposalId: string,\n  ): Promise<{\n    proposal_id: string\n    proposed_hash: string\n    base_hash: string | null\n    state: string\n    proposer: { handle: string; author_key_id: string | null }\n    scan: { status: string }\n    diff: Array<{ path: string; status: string; diff: string | null; binary: boolean }>\n    created_at: number\n    decided_by: string | null\n    decided_at: number | null\n    decision_note: string | null\n  }> {\n    const { author, slug } = parseSkillRef(ref)\n    const path = `/skills/${author}/${slug}/proposals/${encodeURIComponent(proposalId)}`\n    const res = await this.request('GET', path)\n    if (res.status !== 200) {\n      await throwForStatus(res, `get proposal ${proposalId} for ${ref}`)\n    }\n    return (await res.json()) as Awaited<ReturnType<RegistryClient['getProposal']>>\n  }\n\n  /**\n   * POST /api/v1/delegations \u2014 register an author-signed device-key\n   * delegation. Requires the caller's `claim`-scoped session token (the gate is\n   * the same as /claim: a new device key is new authority). `already_exists`\n   * is true on a 200 (idempotent re-POST of the identical cert).\n   */\n  async registerDelegation(body: {\n    cert: SignedDelegation['cert']\n    cert_sig: SignedDelegation['cert_sig']\n    label?: string\n  }): Promise<{\n    device_key_id: string\n    expires_at: number\n    scopes: string[]\n    already_exists: boolean\n  }> {\n    const res = await this.postRequest('/delegations', body)\n    if (res.status === 409) {\n      let b: unknown\n      try {\n        b = await res.json()\n      } catch {\n        b = null\n      }\n      throw new RegistryError(\n        'device_key_in_use',\n        pickMessage(b) ?? 'Device key id already in use',\n        409,\n        b,\n      )\n    }\n    if (res.status !== 200 && res.status !== 201) {\n      await throwForStatus(res, `register delegation ${body.cert.device_key_id}`)\n    }\n    const payload = (await res.json()) as {\n      device_key_id: string\n      expires_at: number\n      scopes: string[]\n    }\n    return { ...payload, already_exists: res.status === 200 }\n  }\n\n  /**\n   * GET /api/v1/delegations \u2014 list the caller's own delegations\n   * (active + expired + revoked). Requires a session token.\n   */\n  async listDelegations(): Promise<DelegationListItem[]> {\n    const res = await this.request('GET', '/delegations')\n    if (res.status !== 200) {\n      await throwForStatus(res, 'list delegations')\n    }\n    const body = (await res.json()) as { delegations?: DelegationListItem[] }\n    return body.delegations ?? []\n  }\n\n  /**\n   * GET /api/v1/authors/:handle/revoked-device-keys \u2014 public revoked device ids\n   * for sync-time delegation refusal.\n   */\n  async listAuthorRevokedDeviceKeys(handle: string): Promise<string[]> {\n    const normalized = handle.replace(/^@/, '').toLowerCase()\n    const res = await this.request('GET', `/authors/${encodeURIComponent(normalized)}/revoked-device-keys`)\n    if (res.status !== 200) {\n      await throwForStatus(res, `list revoked device keys for @${normalized}`)\n    }\n    const body = (await res.json()) as { device_key_ids?: string[] }\n    return body.device_key_ids ?? []\n  }\n\n  /**\n   * GET /api/v1/devices \u2014 list bearer devices bound to the signed-in user\n   * (machines linked via connect/pair or the connect wizard).\n   */\n  async listBearerDevices(): Promise<BearerDeviceListItem[]> {\n    const res = await this.request('GET', '/devices')\n    if (res.status !== 200) {\n      await throwForStatus(res, 'list devices')\n    }\n    const body = (await res.json()) as { devices?: BearerDeviceListItem[] }\n    return body.devices ?? []\n  }\n\n  /**\n   * POST /api/v1/delegations/:device_key_id/revoke \u2014 submit an\n   * author-signed revocation. Idempotent; a 404 means the device key is not the\n   * caller's. Requires a session token.\n   */\n  async revokeDelegation(\n    deviceKeyId: string,\n    body: {\n      revocation: SignedRevocation['revocation']\n      revocation_sig: SignedRevocation['revocation_sig']\n    },\n  ): Promise<{ device_key_id: string; revoked_at: number }> {\n    if (!/^[0-9a-f]{64}$/.test(deviceKeyId)) {\n      throw new RegistryError(\n        'invalid_device_key',\n        `device_key_id ${JSON.stringify(deviceKeyId)} must be 64 lowercase hex chars`,\n      )\n    }\n    const res = await this.postRequest(`/delegations/${deviceKeyId}/revoke`, body)\n    if (res.status !== 200) {\n      await throwForStatus(res, `revoke delegation ${deviceKeyId}`)\n    }\n    return (await res.json()) as { device_key_id: string; revoked_at: number }\n  }\n\n  /**\n   * POST /api/v1/skills/:author/:slug/install \u2014 increment install_count once per\n   * authenticated installer (user session, device, or kit-key). Anonymous calls\n   * still increment on every request (legacy public-skill adds without a token).\n   */\n  async recordInstall(ref: string): Promise<void> {\n    const { author, slug } = parseSkillRef(ref)\n    const path = `/skills/${author}/${slug}/install`\n    const res = await this.postRequest(path, {})\n    if (res.status !== 200) {\n      await throwForStatus(res, `record install for ${ref}`)\n    }\n  }\n\n  /** The account's update mode + recorded decisions \u2014 the device's reconciliation\n   *  feed for the account-scoped approval model. Account-bound token required. */\n  async getMyDecisions(): Promise<AccountDecisions> {\n    const res = await this.request('GET', '/me/decisions')\n    if (res.status !== 200) {\n      await throwForStatus(res, 'account decisions')\n    }\n    return (await res.json()) as AccountDecisions\n  }\n\n  /** Record an approval for a published version, account-scoped. The server\n   *  derives the canonical hash and the source; we only name the version. */\n  async postApproval(skillId: string, versionHash: string): Promise<void> {\n    const res = await this.postRequest('/approvals', {\n      skill_id: skillId,\n      version_hash: versionHash,\n    })\n    if (res.status !== 200) {\n      await throwForStatus(res, `approve ${skillId}@${versionHash}`)\n    }\n  }\n\n  async postRejection(skillId: string, versionHash: string): Promise<void> {\n    const res = await this.postRequest('/rejections', {\n      skill_id: skillId,\n      version_hash: versionHash,\n    })\n    if (res.status !== 200) {\n      await throwForStatus(res, `reject ${skillId}@${versionHash}`)\n    }\n  }\n\n  /** Set the account update mode. Returns the new mode plus how many pending\n   *  updates were applied (non-zero only when flipping to 'auto', which approves\n   *  the pending queue). Account-bound token required. */\n  async setUpdateMode(\n    mode: 'auto' | 'manual',\n  ): Promise<{ mode: 'auto' | 'manual'; applied: number }> {\n    const res = await this.patchRequest('/me/update-mode', { mode })\n    if (res.status !== 200) {\n      await throwForStatus(res, `set update mode to ${mode}`)\n    }\n    return (await res.json()) as { mode: 'auto' | 'manual'; applied: number }\n  }\n\n  /** PATCH /api/v1/devices/:device_id \u2014 rename a device. Session renames any\n   *  owned machine; a device token renames ITSELF (post plan 2026-07-08-002 the\n   *  registry admits the device's own bearer). Returns the stored label\n   *  (trimmed, control-chars stripped, 80-char clamped, empty \u2192 null). */\n  async renameDevice(\n    deviceId: string,\n    label: string,\n  ): Promise<{ device_id: string; label: string | null }> {\n    const res = await this.patchRequest(`/devices/${encodeURIComponent(deviceId)}`, { label })\n    if (res.status !== 200) {\n      await throwForStatus(res, `rename device ${deviceId}`)\n    }\n    return (await res.json()) as { device_id: string; label: string | null }\n  }\n\n  /**\n   * GET /api/v1/kits/by-handle/:owner/:slug \u2014 resolve a public kit permalink.\n   */\n  async getKitByHandle(owner: string, slug: string): Promise<RegistryKitView> {\n    const path = `/kits/by-handle/${encodeURIComponent(owner)}/${encodeURIComponent(slug)}`\n    const res = await this.request('GET', path)\n    if (res.status !== 200) {\n      await throwForStatus(res, `kit @${owner}/${slug}`)\n    }\n    return (await res.json()) as RegistryKitView\n  }\n\n  /**\n   * POST /api/v1/kits/:kitId/subscribe \u2014 follow a kit (session bearer required).\n   */\n  async subscribeKit(kitId: string): Promise<{ subscribed: boolean; kit_id: string }> {\n    const res = await this.postRequest(`/kits/${encodeURIComponent(kitId)}/subscribe`, {})\n    if (res.status === 201) {\n      return (await res.json()) as { subscribed: boolean; kit_id: string }\n    }\n    await throwForStatus(res, `subscribe to kit ${kitId}`)\n    throw new RegistryError('subscribe_failed', 'subscribe failed')\n  }\n\n  /**\n   * PUT /api/v1/devices/:device_id/agents \u2014 report runtimes detected on this machine.\n   */\n  async reportDeviceAgents(deviceId: string, agents: string[]): Promise<void> {\n    const res = await this.putRequest(`/devices/${encodeURIComponent(deviceId)}/agents`, {\n      agents,\n    })\n    if (res.status !== 200) {\n      await throwForStatus(res, `report device agents for ${deviceId}`)\n    }\n  }\n\n  /**\n   * PUT /api/v1/devices/:device_id/materializations \u2014 report per-skill,\n   * per-runtime install outcome after a sync (powers the first-run reveal),\n   * plus the set of skills this device currently keeps a local edit of\n   * (`edited`, ref + baseline only). The registry reconciles the device's edit\n   * flags to exactly that set \u2014 absence clears the flag (KTD2/R3).\n   */\n  async reportDeviceMaterializations(\n    deviceId: string,\n    materializations: Array<{ skill_slug: string; runtime: string; status: string }>,\n    edited: Array<{ ref: string; baselineVersion: string | null; baselineHash: string }> = [],\n  ): Promise<void> {\n    const res = await this.putRequest(\n      `/devices/${encodeURIComponent(deviceId)}/materializations`,\n      { materializations, edited },\n    )\n    if (res.status !== 200) {\n      await throwForStatus(res, `report device materializations for ${deviceId}`)\n    }\n  }\n\n  private async request(\n    method: 'GET',\n    path: string,\n    opts: { ifNoneMatch?: string | null } = {},\n  ): Promise<Response> {\n    const url = `${this.baseUrl}${REGISTRY_VERSION_PREFIX}${path}`\n    const headers: Record<string, string> = { accept: 'application/json' }\n    if (this.token) headers.authorization = `Bearer ${this.token}`\n    if (this.clientVersion) headers['x-skillet-client-version'] = this.clientVersion\n    if (this.machineId) headers['x-skillet-machine-id'] = this.machineId\n    headers['x-skillet-client-kind'] = this.clientKind\n    if (opts.ifNoneMatch) headers['if-none-match'] = opts.ifNoneMatch\n    let res: Response\n    try {\n      res = await this.fetchImpl(url, { method, headers })\n    } catch (err) {\n      throw new RegistryError('network_error', `Registry request failed: ${(err as Error).message}`)\n    }\n    return res\n  }\n\n  /** Shared body-carrying request (POST/PUT/PATCH). The three verbs differ only\n   *  in the method string, so they share one implementation. */\n  private async bodyRequest(\n    method: 'POST' | 'PUT' | 'PATCH',\n    path: string,\n    body: unknown,\n  ): Promise<Response> {\n    const url = `${this.baseUrl}${REGISTRY_VERSION_PREFIX}${path}`\n    const headers: Record<string, string> = {\n      accept: 'application/json',\n      'content-type': 'application/json',\n    }\n    if (this.token) headers.authorization = `Bearer ${this.token}`\n    if (this.clientVersion) headers['x-skillet-client-version'] = this.clientVersion\n    if (this.machineId) headers['x-skillet-machine-id'] = this.machineId\n    headers['x-skillet-client-kind'] = this.clientKind\n    let res: Response\n    try {\n      res = await this.fetchImpl(url, { method, headers, body: JSON.stringify(body) })\n    } catch (err) {\n      throw new RegistryError('network_error', `Registry request failed: ${(err as Error).message}`)\n    }\n    return res\n  }\n\n  private postRequest(path: string, body: unknown): Promise<Response> {\n    return this.bodyRequest('POST', path, body)\n  }\n\n  private putRequest(path: string, body: unknown): Promise<Response> {\n    return this.bodyRequest('PUT', path, body)\n  }\n\n  private patchRequest(path: string, body: unknown): Promise<Response> {\n    return this.bodyRequest('PATCH', path, body)\n  }\n}\n\n/**\n * Strict shape conversion: prefer multi-file `files`, fall back to legacy\n * single-file `content`. A response with neither is malformed.\n */\nfunction bundleFromResponse(\n  files: BundleFiles | undefined,\n  content: string | undefined,\n): DecodedBundle {\n  if (files && Object.keys(files).length > 0) {\n    return decodeBundle(files)\n  }\n  if (typeof content === 'string') {\n    // Legacy single-file: pack it back into the canonical bundle shape so the\n    // hash + downstream materialization paths see one consistent input.\n    return new Map([['SKILL.md', Buffer.from(content, 'utf8')]])\n  }\n  throw new RegistryError('malformed_response', 'Bundle response had neither `files` nor `content`')\n}\n\nfunction stripHashPrefix(s: string): string {\n  return s.startsWith(CONTENT_HASH_PREFIX) ? s.slice(CONTENT_HASH_PREFIX.length) : s\n}\n\nasync function throwForStatus(res: Response, what: string): Promise<never> {\n  let body: unknown\n  try {\n    body = await res.json()\n  } catch {\n    body = await res.text().catch(() => null)\n  }\n  const code = pickCode(body) ?? `http_${res.status}`\n  const message = pickMessage(body) ?? `${what} request failed (HTTP ${res.status})`\n  throw new RegistryError(code, message, res.status, body)\n}\n\nfunction pickCode(body: unknown): string | null {\n  if (body && typeof body === 'object' && 'error' in body) {\n    const e = (body as { error: unknown }).error\n    if (typeof e === 'string') return e\n  }\n  return null\n}\n\nfunction pickMessage(body: unknown): string | null {\n  if (body && typeof body === 'object' && 'message' in body) {\n    const m = (body as { message: unknown }).message\n    if (typeof m === 'string') return m\n  }\n  return null\n}\n", "/**\n * `skillet claim` \u2014 bind the local Ed25519 author key to the session user.\n */\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { loadIdentity, saveIdentity } from '../identity/index.js';\nimport {\n  generateAuthorKey,\n  loadAuthorKey,\n  saveAuthorKey,\n  type AuthorKey,\n} from '../signing/index.js';\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { REGISTRY_API } from '../registry-api.js';\nimport { RegistryError } from '../registry/client.js';\nimport { loadSessionToken, envSessionToken, readSessionFileToken } from '../session-token.js';\n\nexport interface ClaimOptions {\n  registryUrl?: string;\n  token?: string;\n  handle?: string;\n  configDir?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface ClaimResult {\n  handle: string;\n  key_id: string;\n  /**\n   * True when the handle already has a primary key on another machine. The\n   * session remains valid for sync; this machine is not the primary signer.\n   */\n  primaryElsewhere?: boolean;\n}\n\n/** User-facing copy when this machine is linked but not the primary signer. */\nexport function secondaryDeviceMessage(handle: string): string {\n  return (\n    `Account @${handle} is linked on this machine for sync. ` +\n    `Your primary signing key lives on another device \u2014 only one machine holds the primary key. ` +\n    `Use \\`skillet sync\\` here; publish from your primary machine, skillet.md Studio, ` +\n    `or run \\`skillet device approve\\` on the primary to delegate signing to this device.`\n  );\n}\n\nfunction defaultConfigDir(): string {\n  return process.env['XDG_CONFIG_HOME'] ?? join(homedir(), '.config');\n}\n\nasync function loadOrCreateAuthorKey(configDir: string): Promise<AuthorKey> {\n  try {\n    return await loadAuthorKey(configDir);\n  } catch {\n    const key = generateAuthorKey();\n    await saveAuthorKey(key, configDir);\n    return key;\n  }\n}\n\nasync function resolveClaimHandle(\n  token: string,\n  registryUrl: string,\n  identity: Awaited<ReturnType<typeof loadIdentity>>,\n  explicitHandle: string | undefined,\n  fetchImpl: typeof fetch,\n): Promise<string> {\n  const fromOpts = explicitHandle?.trim().toLowerCase();\n  if (fromOpts) return fromOpts;\n  if (identity?.handle) return identity.handle;\n\n  let res: Response;\n  try {\n    res = await fetchImpl(`${registryUrl}${REGISTRY_API}/whoami`, {\n      headers: { authorization: `Bearer ${token}`, accept: 'application/json' },\n    });\n  } catch (err) {\n    throw new RegistryError('network_error', `Request failed: ${(err as Error).message}`);\n  }\n\n  const body = (await res.json().catch(() => null)) as { handle?: string | null } | null;\n  if (!res.ok) {\n    throw new RegistryError(\n      'whoami_failed',\n      'Could not resolve your registry handle. Run `skillet connect <code>` and retry.',\n      res.status,\n      body,\n    );\n  }\n\n  const fromSession = body?.handle?.trim().toLowerCase();\n  if (!fromSession) {\n    throw new RegistryError(\n      'handle_not_claimed',\n      'This account has no handle yet. Run `skillet login --handle <you> --name \"<Name>\"` to register one.',\n    );\n  }\n  return fromSession;\n}\n\nfunction claimErrorMessage(\n  code: string,\n  message: string,\n  payload: unknown,\n  staleEnvHint: string,\n): string {\n  if (code === 'name_taken') {\n    return (\n      `Handle is already claimed by another account. Pick a different handle ` +\n      `(or reset the local registry DB if this is dev dogfood).`\n    );\n  }\n  if (code === 'already_claimed') {\n    const existing =\n      payload && typeof payload === 'object' && 'handle' in payload\n        ? String((payload as Record<string, unknown>).handle)\n        : null;\n    return existing\n      ? `This session is already bound to @${existing}. Use that handle, sign in with a fresh email, or run \\`skillet login --handle ${existing}\\`.${staleEnvHint}`\n      : `${message}${staleEnvHint}`;\n  }\n  if (code === 'key_change_forbidden') {\n    return (\n      `This handle already has a primary signing key on another machine. ` +\n      `Link this device with \\`skillet connect <code>\\` for sync \u2014 ` +\n      `do not run \\`skillet claim\\` again on secondary machines.`\n    );\n  }\n  return message;\n}\n\nexport async function claimHandle(opts: ClaimOptions = {}): Promise<ClaimResult> {\n  const token = await loadSessionToken(opts.token);\n  if (!token) {\n    throw new RegistryError(\n      'not_authenticated',\n      'A session token is required. Run `skillet connect <code>` first.',\n    );\n  }\n\n  const identity = await loadIdentity();\n  const registryUrl = (opts.registryUrl ?? identity?.registryUrl ?? REGISTRY_URL_DEFAULT).replace(\n    /\\/+$/,\n    '',\n  );\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n\n  const handle = await resolveClaimHandle(token, registryUrl, identity, opts.handle, fetchImpl);\n\n  const configDir = opts.configDir ?? defaultConfigDir();\n  const key = await loadOrCreateAuthorKey(configDir);\n  const jwk = key.publicKey.export({ format: 'jwk' }) as { x: string };\n  const publicKey = Buffer.from(jwk.x, 'base64url').toString('base64');\n\n  const url = `${registryUrl}${REGISTRY_API}/claim`;\n\n  let res: Response;\n  try {\n    res = await fetchImpl(url, {\n      method: 'POST',\n      headers: {\n        accept: 'application/json',\n        'content-type': 'application/json',\n        authorization: `Bearer ${token}`,\n      },\n      body: JSON.stringify({\n        handle,\n        public_key: publicKey,\n        key_id: key.keyId,\n      }),\n    });\n  } catch (err) {\n    throw new RegistryError('network_error', `Request failed: ${(err as Error).message}`);\n  }\n\n  const payload = await res.json().catch(() => null);\n  if (!res.ok) {\n    const code =\n      payload && typeof payload === 'object' && 'error' in payload\n        ? String((payload as Record<string, unknown>).error)\n        : `http_${res.status}`;\n    const message =\n      payload && typeof payload === 'object' && 'message' in payload\n        ? String((payload as Record<string, unknown>).message)\n        : `Claim failed (HTTP ${res.status})`;\n    const fileToken = await readSessionFileToken();\n    const staleEnvHint =\n      envSessionToken() && fileToken && envSessionToken() !== fileToken\n        ? ' A stale SKILLET_TOKEN in your shell may be overriding ~/.skillet/session.json \u2014 run `unset SKILLET_TOKEN` and retry.'\n        : '';\n\n    if (code === 'key_change_forbidden') {\n      let whoamiRes: Response;\n      try {\n        whoamiRes = await fetchImpl(`${registryUrl}${REGISTRY_API}/whoami`, {\n          headers: { authorization: `Bearer ${token}`, accept: 'application/json' },\n        });\n      } catch {\n        whoamiRes = new Response(null, { status: 0 });\n      }\n      const whoamiBody = (await whoamiRes.json().catch(() => null)) as {\n        handle?: string | null;\n        author_key_id?: string | null;\n      } | null;\n      const sessionHandle = whoamiBody?.handle?.trim().toLowerCase();\n      const remoteKeyId = whoamiBody?.author_key_id?.trim();\n      if (\n        whoamiRes.ok &&\n        sessionHandle === handle &&\n        remoteKeyId &&\n        remoteKeyId.length > 0\n      ) {\n        return {\n          handle: sessionHandle,\n          key_id: remoteKeyId,\n          primaryElsewhere: true,\n        };\n      }\n    }\n\n    throw new RegistryError(\n      code,\n      claimErrorMessage(code, message, payload, staleEnvHint),\n      res.status,\n      payload,\n    );\n  }\n\n  const result = payload as ClaimResult;\n\n  if (!identity) {\n    await saveIdentity({\n      handle: result.handle,\n      keyId: key.keyId,\n      registryUrl,\n      createdAt: new Date().toISOString(),\n    });\n  }\n\n  return result;\n}\n", "/**\n * `skillet login` \u2014 claim a handle on the registry and bind it to this device's\n * Ed25519 author key.\n *\n * When a registry session exists (`skillet connect`), we bind the handle via\n * `/api/v1/claim` so publish sees the same handle on the session. Without a\n * session, we fall back to the legacy unauthenticated profile registration.\n */\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport {\n  generateAuthorKey,\n  saveAuthorKey,\n  loadAuthorKey,\n  type AuthorKey,\n} from \"../signing/index.js\";\nimport {\n  saveIdentity,\n  loadIdentity,\n  type Identity,\n} from \"../identity/index.js\";\nimport { REGISTRY_URL_DEFAULT } from \"../kit/types.js\";\nimport { RegistryClient, RegistryError } from \"../registry/client.js\";\nimport { recordEvent, detectInitiator } from \"../metrics.js\";\nimport { loadSessionToken } from \"../session-token.js\";\nimport { claimHandle } from \"./claim.js\";\n\nconst HANDLE_RE = /^[a-z0-9][a-z0-9-]{0,38}[a-z0-9]$|^[a-z0-9]$/;\n\nexport interface LoginOptions {\n  handle: string;\n  name: string;\n  avatarUrl?: string;\n  registryUrl?: string;\n  configDir?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface LoginResult {\n  identity: Identity;\n  /** true when the registry created a new profile; false on re-login. */\n  created: boolean;\n}\n\nfunction defaultConfigDir(): string {\n  return process.env[\"XDG_CONFIG_HOME\"] ?? join(homedir(), \".config\");\n}\n\nasync function loadOrCreateKey(configDir: string): Promise<{ key: AuthorKey; created: boolean }> {\n  try {\n    const key = await loadAuthorKey(configDir);\n    return { key, created: false };\n  } catch {\n    const key = generateAuthorKey();\n    await saveAuthorKey(key, configDir);\n    return { key, created: true };\n  }\n}\n\nasync function updateProfileName(\n  registryUrl: string,\n  handle: string,\n  name: string,\n  fetchImpl?: typeof fetch,\n): Promise<void> {\n  const fetchFn = fetchImpl ?? globalThis.fetch;\n  try {\n    await fetchFn(`${registryUrl}/profiles/${encodeURIComponent(handle)}`, {\n      method: \"PATCH\",\n      headers: { \"content-type\": \"application/json\", accept: \"application/json\" },\n      body: JSON.stringify({ name }),\n    });\n  } catch {\n    // Display name is best-effort; claim already created the author row.\n  }\n}\n\nexport async function login(opts: LoginOptions): Promise<LoginResult> {\n  const handle = opts.handle.trim().toLowerCase();\n  if (!HANDLE_RE.test(handle)) {\n    throw new Error(\n      `Invalid handle \"${opts.handle}\": must be 1-40 lowercase alphanumeric characters or hyphens.`\n    );\n  }\n\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/$/, \"\");\n  const configDir = opts.configDir ?? defaultConfigDir();\n  const sessionToken = await loadSessionToken();\n\n  const { key } = await loadOrCreateKey(configDir);\n\n  if (sessionToken) {\n    const claimResult = await claimHandle({\n      handle,\n      registryUrl,\n      token: sessionToken,\n      configDir,\n      fetchImpl: opts.fetchImpl,\n    });\n    if (claimResult.primaryElsewhere) {\n      throw new Error(\n        `Handle @${handle} already has a primary signing key on another machine. ` +\n          `Link this device with \\`skillet connect <code>\\` for sync.`,\n      );\n    }\n    await updateProfileName(registryUrl, handle, opts.name, opts.fetchImpl);\n\n    const identity: Identity = {\n      handle,\n      keyId: key.keyId,\n      registryUrl,\n      createdAt: new Date().toISOString(),\n    };\n    await saveIdentity(identity);\n    recordEvent(\"login\", detectInitiator(), { handle, created: true });\n    return { identity, created: true };\n  }\n\n  const client = new RegistryClient({\n    baseUrl: registryUrl,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n\n  let created = false;\n  try {\n    await client.createProfile({\n      id: handle,\n      name: opts.name,\n      ...(opts.avatarUrl ? { avatar_url: opts.avatarUrl } : {}),\n    });\n    created = true;\n  } catch (err) {\n    if (err instanceof RegistryError && err.status === 409) {\n      const existing = await loadIdentity();\n      if (\n        !existing ||\n        existing.handle !== handle ||\n        existing.registryUrl.replace(/\\/$/, \"\") !== registryUrl\n      ) {\n        throw new Error(\n          `Handle \"${handle}\" is already registered on ${registryUrl}. ` +\n            `Pick a different handle, or run \\`skillet connect <code>\\` first ` +\n            `and retry so the handle binds to your session.`\n        );\n      }\n    } else {\n      throw err;\n    }\n  }\n\n  const identity: Identity = {\n    handle,\n    keyId: key.keyId,\n    registryUrl,\n    createdAt: new Date().toISOString(),\n  };\n  await saveIdentity(identity);\n\n  recordEvent(\"login\", detectInitiator(), { handle, created });\n\n  return { identity, created };\n}\n", "/**\n * Skillet author-signing envelope (PROTOCOL \u00A74).\n *\n * Wire shape \u2014 versionable, embedded in publish bodies, manifests, lockfiles:\n *   { \"alg\": \"ed25519\", \"key_id\": \"<hex>\", \"sig\": \"<base64>\" }\n *\n * Signing input \u2014 what the bytes-on-the-wire actually mean \u2014 is THE bytes of\n * the `content_hash` string (\"sha256:\" + 64 lowercase hex), UTF-8 encoded.\n * That is the contract subtask 1 (canonical hash) plugs into: it\n * controls what value goes into `content_hash`; this envelope says how those\n * bytes are turned into a signature.\n *\n * Why sign the string, not the raw 32-byte digest:\n *   - The string is what every endpoint, response, lockfile, and log shows.\n *     A byte-identical contract end-to-end removes ambiguity about which\n *     value got signed and is what the spec writes verbatim (\u00A74).\n *   - \"key_id\" + \"alg\" leave room for v2 rotation / Sigstore without a\n *     breaking envelope change.\n *\n * Verification is fail-closed. A bad signature aborts that skill and leaves\n * the existing materialized files untouched (\u00A76.4, acceptance criterion 3).\n */\nimport { sign, verify, type KeyObject } from \"node:crypto\";\nimport {\n  BUNDLE_SIG_TYP,\n  bundleSignatureBytes,\n  isBundleSignatureV2,\n  type BundleSignaturePayload,\n} from \"@skillet/protocol\";\n\nexport const SIG_ALG_ED25519 = \"ed25519\" as const;\nexport const SIG_ALG_SESSION = \"session\" as const;\n\nexport type SigAlg = typeof SIG_ALG_ED25519 | typeof SIG_ALG_SESSION;\n\nexport interface Ed25519Signature {\n  alg: typeof SIG_ALG_ED25519;\n  key_id: string;\n  sig: string;\n  /** 2 = binds author/ref/version/content_hash (NF-004). Absent = legacy v1. */\n  sig_version?: 1 | 2;\n}\n\nexport interface EnvelopeBinding {\n  ref: string;\n  version: number;\n  authorKeyId: string;\n}\n\n/** Build v2 binding context from a kit entry or manifest slug. */\nexport function envelopeBindingFromSlug(\n  slug: string,\n  version: number,\n  authorKeyId: string,\n  owner?: string | null,\n  name?: string | null,\n): EnvelopeBinding {\n  if (slug.startsWith(\"@\")) {\n    return { ref: slug, version, authorKeyId };\n  }\n  const author = owner ?? slug.split(\"/\")[0] ?? \"\";\n  const skillName = name ?? slug.split(\"/\").slice(1).join(\"/\") ?? slug;\n  return { ref: `@${author}/${skillName}`, version, authorKeyId };\n}\n\nexport interface SessionAttestedSignature {\n  alg: typeof SIG_ALG_SESSION;\n  key_id: string;\n  sig: string;\n}\n\nexport type Signature = Ed25519Signature | SessionAttestedSignature;\n\nconst VALID_KEY_ID_RE = /^[0-9a-f]{64}$/;\nconst CONTENT_HASH_RE = /^sha256:[0-9a-f]{64}$/;\nconst ED25519_SIG_BYTES = 64;\n\n/**\n * Returns the canonical bytes-to-sign for a content_hash string.\n * MUST be called by both signers and verifiers \u2014 never sign raw digests\n * directly, the string form is what the protocol writes (\u00A74).\n */\nexport function signatureBytes(contentHash: string): Buffer {\n  if (!CONTENT_HASH_RE.test(contentHash)) {\n    throw new Error(\n      `signatureBytes: contentHash must match /^sha256:[0-9a-f]{64}$/, got ${JSON.stringify(contentHash)}`\n    );\n  }\n  return Buffer.from(contentHash, \"utf8\");\n}\n\n/**\n * Produces a wire-shaped signature envelope for the given content hash.\n * `key` MUST carry a private half; throws otherwise.\n */\nexport function signEnvelope(\n  contentHash: string,\n  key: { keyId: string; privateKey?: KeyObject },\n  opts: { binding?: EnvelopeBinding } = {},\n): Ed25519Signature {\n  if (!key.privateKey) {\n    throw new Error(\n      \"signEnvelope: private key is undefined (verification-only key)\"\n    );\n  }\n  if (!VALID_KEY_ID_RE.test(key.keyId)) {\n    throw new Error(\n      `signEnvelope: invalid key_id ${JSON.stringify(key.keyId)} (expected 64-char lowercase hex)`\n    );\n  }\n  const binding = opts.binding;\n  if (binding && binding.authorKeyId !== key.keyId) {\n    throw new Error(\"signEnvelope: binding.authorKeyId must match signing key\");\n  }\n  const message =\n    binding != null\n      ? bundleSignatureBytes({\n          typ: BUNDLE_SIG_TYP,\n          author_key_id: binding.authorKeyId,\n          ref: binding.ref,\n          version: binding.version,\n          content_hash: contentHash,\n        })\n      : signatureBytes(contentHash);\n  const sig = sign(null, message, key.privateKey);\n  return {\n    alg: SIG_ALG_ED25519,\n    key_id: key.keyId,\n    sig: sig.toString(\"base64\"),\n    ...(binding ? { sig_version: 2 as const } : {}),\n  };\n}\n\n/**\n * Verifies an envelope against a public key. Throws (does not return false)\n * for every failure mode so callers cannot accidentally drop the result.\n *\n * Error codes (machine-readable, matching PROTOCOL \u00A70 + acceptance criteria):\n *   - \"signature_invalid\"  \u2014 envelope shape, alg, key_id, or sig bytes are bad\n *   - \"key_id_mismatch\"    \u2014 envelope key_id does not match the pinned key\n *   - \"integrity_failed\"   \u2014 sig does not verify against (contentHash, pubKey)\n */\nexport function verifyEnvelope(\n  contentHash: string,\n  envelope: Ed25519Signature,\n  publicKey: KeyObject,\n  opts: { expectedKeyId?: string; binding?: EnvelopeBinding } = {}\n): void {\n  if (!envelope || envelope.alg !== SIG_ALG_ED25519) {\n    throw new SignatureError(\n      \"signature_invalid\",\n      `unsupported alg ${JSON.stringify(envelope?.alg)}`\n    );\n  }\n  if (!VALID_KEY_ID_RE.test(envelope.key_id)) {\n    throw new SignatureError(\n      \"signature_invalid\",\n      `invalid key_id ${JSON.stringify(envelope.key_id)}`\n    );\n  }\n  if (opts.expectedKeyId && opts.expectedKeyId !== envelope.key_id) {\n    throw new SignatureError(\n      \"key_id_mismatch\",\n      `envelope key_id ${envelope.key_id} does not match pinned ${opts.expectedKeyId}`\n    );\n  }\n  if (!envelope.sig) {\n    throw new SignatureError(\"signature_invalid\", \"missing sig\");\n  }\n\n  let sigBytes: Buffer;\n  try {\n    sigBytes = Buffer.from(envelope.sig, \"base64\");\n  } catch {\n    throw new SignatureError(\"signature_invalid\", \"sig is not valid base64\");\n  }\n  if (sigBytes.length !== ED25519_SIG_BYTES) {\n    throw new SignatureError(\n      \"signature_invalid\",\n      `sig length ${sigBytes.length} (expected ${ED25519_SIG_BYTES})`\n    );\n  }\n  if (sigBytes.every((b) => b === 0)) {\n    throw new SignatureError(\"signature_invalid\", \"all-zero sig rejected\");\n  }\n\n  let message: Buffer;\n  if (isBundleSignatureV2(envelope)) {\n    if (!opts.binding) {\n      throw new SignatureError(\n        \"signature_invalid\",\n        \"v2 envelope requires binding context (ref, version, author_key_id)\"\n      );\n    }\n    const payload: BundleSignaturePayload = {\n      typ: BUNDLE_SIG_TYP,\n      author_key_id: opts.binding.authorKeyId,\n      ref: opts.binding.ref,\n      version: opts.binding.version,\n      content_hash: contentHash,\n    };\n    message = bundleSignatureBytes(payload);\n  } else {\n    message = signatureBytes(contentHash);\n  }\n\n  const ok = verify(null, message, publicKey, sigBytes);\n  if (!ok) {\n    throw new SignatureError(\n      \"integrity_failed\",\n      isBundleSignatureV2(envelope)\n        ? \"signature does not verify against bundle binding\"\n        : \"signature does not verify against content_hash\"\n    );\n  }\n}\n\nexport { isBundleSignatureV2 } from \"@skillet/protocol\";\n\nexport type SignatureErrorCode =\n  | \"signature_invalid\"\n  | \"key_id_mismatch\"\n  | \"integrity_failed\";\n\nexport class SignatureError extends Error {\n  readonly code: SignatureErrorCode;\n  constructor(code: SignatureErrorCode, message: string) {\n    super(`${code}: ${message}`);\n    this.name = \"SignatureError\";\n    this.code = code;\n  }\n}\n", "/**\n * `skillet publish [slug]` \u2014 sign and push kit skill(s) to the registry.\n *\n * Changes:\n *   - `slug` is now optional; when omitted all kit skills are published.\n *   - `visibility` defaults to 'private'; pass 'public' explicitly.\n *   - Identity is minted inline on first publish (no separate `skillet login` step).\n *\n * Flow (per skill):\n *   1. Load (or mint inline) the local identity.\n *   2. Read the skill bundle from the kit store.\n *   3. Run the warn-first privacy scan; HIGH findings hard-block per SPEC Safety \u00A71/\u00A78.\n *   4. Compute the canonical content hash (PROTOCOL \u00A72.2), fetch the current\n *      manifest to learn the remote `latest_hash` (base), and reject\n *      client-side if our hash already matches (mirrors server idempotency).\n *   5. Sign via the \u00A74 envelope (signEnvelope over the canonical hash string).\n *   6. Encode the bundle in wire format (files: BundleFiles) and POST /v1/skills.\n *      409 conflict \u2192 surface \"local is behind remote\" and refuse until the\n *      user re-fetches.\n *   7. Update the kit entry to record the registry source + author key id.\n */\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport matter from \"gray-matter\";\nimport {\n  canonicalContentHash,\n  encodeBundle,\n  validateRequires,\n  validateTriggers,\n  RequiresError,\n  TriggersError,\n  isReservedSkillSlug,\n} from \"@skillet/protocol\";\nimport { loadIdentity, saveIdentity, type Identity } from \"../identity/index.js\";\nimport {\n  generateAuthorKey,\n  saveAuthorKey,\n  loadAuthorKey,\n  loadAuthorKeyById,\n} from \"../signing/index.js\";\nimport { signEnvelope, SIG_ALG_SESSION, type Signature } from \"../signing/envelope.js\";\nimport {\n  readBundleFromSkillStore,\n  readState,\n  upsertSkill,\n} from \"../kit/store.js\";\nimport { RegistryClient, RegistryError, type ScanWireFinding } from \"../registry/client.js\";\nimport { recordEvent, detectInitiator } from \"../metrics.js\";\nimport { REGISTRY_URL_DEFAULT } from \"../kit/types.js\";\nimport { REGISTRY_API } from \"../registry-api.js\";\nimport { loadSessionToken } from \"../session-token.js\";\nimport { claimHandle } from \"./claim.js\";\n\nexport type PublishErrorCode =\n  | \"not_logged_in\"\n  | \"skill_not_found\"\n  | \"not_your_skill\"\n  | \"reserved_slug\"\n  | \"invalid_requires\"\n  | \"invalid_triggers\"\n  | \"scan_blocked\"\n  | \"identical_content\"\n  | \"stale_base\"\n  | \"manifest_fetch_failed\"\n  | \"publish_failed\";\n\nexport class PublishError extends Error {\n  readonly code: PublishErrorCode;\n  readonly detail: unknown;\n\n  constructor(message: string, code: PublishErrorCode, detail?: unknown) {\n    super(message);\n    this.name = \"PublishError\";\n    this.code = code;\n    this.detail = detail;\n  }\n}\n\nexport interface PublishOptions {\n  registryUrl?: string;\n  configDir?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n  /** Plain substrings appended to in-skill `.skilletignore-patterns` for the scan. */\n  ignorePatterns?: string[];\n  /** Visibility to publish with. Defaults to 'private'. */\n  visibility?: 'private' | 'public';\n  /**\n   * Inline identity minting. When no identity exists and these are\n   * provided, mint the identity automatically instead of erroring.\n   */\n  handle?: string;\n  name?: string;\n  /** Publish under verified session (web/desktop); no local Ed25519 signature. */\n  sessionAuth?: boolean;\n}\n\nexport interface PublishResult {\n  hash: string;\n  hashRef: string;\n  versionUrl: string;\n  /** Handle the skill published under (the session account or local identity). */\n  owner: string;\n  /** true when the server returned 200 (content was already known to the registry). */\n  alreadyExists: boolean;\n  /** Server-side scan verdict on the published version \u2014 the SOLE scan authority\n   *  (KTD2). A `flagged` result publishes but is worth explaining; a real secret\n   *  or quarantine aborts the publish upstream (422 `scan_blocked`) and never\n   *  reaches here. Absent on an idempotent no-op. */\n  serverScan?: { status: \"clean\" | \"flagged\" | \"quarantined\"; findings: ScanWireFinding[] };\n  slug: string;\n  /**\n   * Non-fatal `requires:` schema notes (e.g. unknown keys). Surfaced back to\n   * the author rather than swallowed \u2014 see AC #3.\n   */\n  requiresWarnings: string[];\n  triggersWarnings: string[];\n}\n\nfunction defaultConfigDir(): string {\n  return process.env[\"XDG_CONFIG_HOME\"] ?? join(homedir(), \".config\");\n}\n\n/**\n * Mint an identity inline on first publish. Generates a local keypair, registers\n * the author profile, and saves the identity file \u2014 all in one step so the user\n * doesn't need a separate `skillet login` command (SPEC identity-at-publish).\n */\nasync function mintIdentityInline(opts: {\n  handle: string;\n  name: string;\n  registryUrl: string;\n  configDir: string;\n  fetchImpl?: typeof fetch;\n}): Promise<Identity> {\n  const HANDLE_RE = /^[a-z0-9][a-z0-9-]{0,38}[a-z0-9]$|^[a-z0-9]$/;\n  const handle = opts.handle.trim().toLowerCase();\n  if (!HANDLE_RE.test(handle)) {\n    throw new Error(\n      `Invalid handle \"${opts.handle}\": must be 1-40 lowercase alphanumeric or hyphens.`,\n    );\n  }\n\n  const client = new RegistryClient({\n    baseUrl: opts.registryUrl,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n\n  let key;\n  try {\n    key = await loadAuthorKey(opts.configDir);\n  } catch {\n    key = generateAuthorKey();\n    await saveAuthorKey(key, opts.configDir);\n  }\n\n  try {\n    await client.createProfile({ id: handle, name: opts.name });\n  } catch (err) {\n    // 409 = handle already registered; re-login accepted if it matches the local key.\n    if (!(err instanceof RegistryError) || err.status !== 409) {\n      throw err;\n    }\n  }\n\n  const identity: Identity = {\n    handle,\n    keyId: key.keyId,\n    registryUrl: opts.registryUrl,\n    createdAt: new Date().toISOString(),\n  };\n  await saveIdentity(identity);\n\n  const sessionToken = await loadSessionToken();\n  if (sessionToken) {\n    const claimResult = await claimHandle({\n      handle,\n      registryUrl: opts.registryUrl,\n      token: sessionToken,\n      configDir: opts.configDir,\n      fetchImpl: opts.fetchImpl,\n    });\n    if (claimResult.primaryElsewhere) {\n      throw new PublishError(\n        `Primary signing key for @${handle} is on another machine. ` +\n          `Publish from that device, skillet.md Studio, or approve this device from the primary.`,\n        'not_logged_in',\n      );\n    }\n  }\n\n  return identity;\n}\n\nasync function fetchSessionAccount(\n  registryUrl: string,\n  token: string,\n  fetchImpl?: typeof fetch,\n): Promise<{ handle: string; authorKeyId: string | null }> {\n  const res = await (fetchImpl ?? fetch)(`${registryUrl}${REGISTRY_API}/whoami`, {\n    headers: { authorization: `Bearer ${token}`, accept: 'application/json' },\n  });\n  if (!res.ok) {\n    throw new PublishError(\n      'Could not resolve account from session. Sign in again and retry.',\n      'not_logged_in',\n    );\n  }\n  const body = (await res.json()) as { handle?: string | null; author_key_id?: string | null };\n  if (!body.handle) {\n    throw new PublishError(\n      'Session has no claimed handle. Claim a username before publishing.',\n      'not_logged_in',\n    );\n  }\n  return {\n    handle: body.handle,\n    authorKeyId: body.author_key_id ?? null,\n  };\n}\n\nexport async function publish(\n  slug: string,\n  opts: PublishOptions = {}\n): Promise<PublishResult> {\n  return (await publishAll([slug], opts))[0]!;\n}\n\n/**\n * Bulk-publish multiple skills from the kit in one call.\n * Each skill is published independently; failures do not abort the batch.\n */\nexport async function publishAll(\n  slugs: string[],\n  opts: PublishOptions = {},\n): Promise<PublishResult[]> {\n  const configDir = opts.configDir ?? defaultConfigDir();\n  const visibility = opts.visibility ?? 'private';\n  const token = opts.token ?? ((await loadSessionToken()) || undefined);\n\n  let publishHandle: string;\n  let registryUrl: string;\n  let signingKey: Awaited<ReturnType<typeof loadAuthorKeyById>> | null = null;\n  let sessionAuthorKeyId: string | null = null;\n\n  // Load the local signing identity BEFORE deciding the auth mode. The local\n  // Ed25519 key is the user's *explicit* signing identity, so when it exists it\n  // must win \u2014 we never silently downgrade to a session-attested publish just\n  // because a (possibly stale) session token happens to be on disk. Doing the\n  // sessionAuth decision before the identity load was the bug: it forced the\n  // session path on token presence alone and broke local-key (v2) signatures.\n  let identity: Identity | null = await loadIdentity();\n\n  // Session auth is used only when the caller explicitly requests it (web/\n  // desktop have no local key) OR when there is no local identity to sign with\n  // and a session token is available as the fallback. If both a local identity\n  // and a session token exist, the local identity wins.\n  let sessionAuth = opts.sessionAuth === true || (!identity && !!token);\n\n  if (sessionAuth) {\n    if (!token) {\n      throw new PublishError(\n        'Session publish requires sign-in. Run `skillet connect` first.',\n        'not_logged_in',\n      );\n    }\n    registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/$/, '');\n    const account = await fetchSessionAccount(registryUrl, token, opts.fetchImpl);\n    publishHandle = account.handle;\n    sessionAuthorKeyId = account.authorKeyId;\n  } else {\n    // identity was already loaded above; mint inline only when none exists.\n    if (!identity) {\n      if (opts.handle && opts.name) {\n        const inlineRegistryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/$/, '');\n        identity = await mintIdentityInline({\n          handle: opts.handle,\n          name: opts.name,\n          registryUrl: inlineRegistryUrl,\n          configDir,\n          fetchImpl: opts.fetchImpl,\n        });\n      } else {\n        throw new PublishError(\n          'Not logged in. Run `skillet connect <code>` (code from skillet.md Settings), ' +\n            'or pass --handle and --name to this command to claim your identity inline.',\n          'not_logged_in',\n        );\n      }\n    }\n    publishHandle = identity.handle;\n    registryUrl = (opts.registryUrl ?? identity.registryUrl).replace(/\\/$/, '');\n    signingKey = await loadAuthorKeyById(configDir, identity.keyId);\n  }\n\n  const state = await readState();\n\n  const client = new RegistryClient({\n    baseUrl: registryUrl,\n    ...(token ? { token } : {}),\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n\n  const results: PublishResult[] = [];\n\n  for (const slug of slugs) {\n    // A promoted key (@handle/slug) is the caller's own published skill re-keyed\n    // by sync. Registry-facing refs use the bare slug; entries keyed under a\n    // DIFFERENT author are never publishable as your own.\n    let bareSlug = slug;\n    if (slug.startsWith('@')) {\n      const sep = slug.indexOf('/');\n      const keyOwner = sep > 1 ? slug.slice(1, sep) : '';\n      if (sep < 0 || keyOwner !== publishHandle) {\n        throw new PublishError(\n          `Skill \"${slug}\" belongs to @${keyOwner || 'unknown'} \u2014 only your own skills can be published.`,\n          'not_your_skill',\n        );\n      }\n      bareSlug = slug.slice(sep + 1);\n    }\n\n    // Reject reserved slugs before any network/signing work: a skill slugged\n    // kit/followers/following would publish but be unreachable at /{owner}/{slug}.\n    if (isReservedSkillSlug(bareSlug)) {\n      throw new PublishError(\n        `Skill slug \"${bareSlug}\" is reserved and cannot be published. Rename the skill and try again.`,\n        'reserved_slug',\n      );\n    }\n\n    const entry = state.skills[slug];\n    if (!entry) {\n      throw new PublishError(\n        `Skill \"${slug}\" not found in kit. Import it with \\`skillet import <path>\\` first.`,\n        'skill_not_found',\n      );\n    }\n\n    const bundle = await readBundleFromSkillStore(slug);\n\n    // Enforce the `requires:` schema at the publish boundary.\n    // Validate BEFORE signing/minting so a malformed dependency edge can never\n    // reach a signed, content-addressed bundle (the re-mint cost this avoids).\n    // selfRef is this skill's canonical ref so self-dependencies are rejected.\n    const selfRef = `@${publishHandle}/${bareSlug}`;\n    let requiresWarnings: string[];\n    let triggersWarnings: string[];\n    try {\n      const entrypoint = bundle.get(\"SKILL.md\");\n      const fm = entrypoint\n        ? (matter(Buffer.from(entrypoint).toString(\"utf8\")).data as Record<string, unknown>)\n        : {};\n      requiresWarnings = validateRequires(fm[\"requires\"], selfRef).warnings;\n      triggersWarnings = validateTriggers(fm[\"triggers\"]).warnings;\n    } catch (err) {\n      if (err instanceof RequiresError) {\n        throw new PublishError(err.message, \"invalid_requires\");\n      }\n      if (err instanceof TriggersError) {\n        throw new PublishError(err.message, \"invalid_triggers\");\n      }\n      throw err;\n    }\n\n    // No client-side privacy scan (KTD2). The registry publish route is the\n    // single scan authority: its `secretsBlockingScan` + quarantine gate\n    // (routes/skills.ts) aborts a real secret or confirmed-dangerous bundle\n    // with a 422 `scan_blocked` BEFORE any row/blob is stored, and it uses a\n    // benign-corpus so placeholder credentials in example docs pass. Running a\n    // second, cruder regex scan here only diverged the verdict (desktop refused\n    // what the web accepted); removing it makes desktop == web. KTD3: a real\n    // secret's bytes now reach the server before it aborts \u2014 accepted, and\n    // identical to how the web import already behaves.\n\n    const contentHash = canonicalContentHash(bundle);\n\n    let baseHash: string | null = null;\n    try {\n      const manifestResult = await client.getSkillManifest(`@${publishHandle}/${bareSlug}`);\n      if (!manifestResult.notModified && manifestResult.value) {\n        const remoteHash = manifestResult.value.latest_hash ?? null;\n        if (remoteHash) {\n          const normalised = remoteHash.startsWith('sha256:') ? remoteHash : `sha256:${remoteHash}`;\n          if (normalised === contentHash) {\n            // Same bytes \u2014 skip the round-trip only for private republishs.\n            // Public (or visibility flips) still hit the registry so visibility updates.\n            if (visibility === 'private') {\n              results.push({\n                hash: contentHash,\n                hashRef: contentHash,\n                versionUrl: `${REGISTRY_API}/skills/${publishHandle}/${bareSlug}/versions/${contentHash}`,\n                owner: publishHandle,\n                alreadyExists: true,\n                slug,\n                requiresWarnings,\n                triggersWarnings,\n              });\n              continue;\n            }\n            baseHash = normalised;\n          } else {\n            baseHash = normalised;\n          }\n        }\n      }\n    } catch (err) {\n      if (err instanceof RegistryError && err.status === 404) {\n        baseHash = null;\n      } else {\n        throw new PublishError(\n          `Failed to fetch manifest: ${(err as Error).message}`,\n          'manifest_fetch_failed',\n        );\n      }\n    }\n\n    const files = encodeBundle(bundle);\n\n    const sessionSignature = {\n      alg: SIG_ALG_SESSION,\n      key_id: sessionAuthorKeyId ?? '0'.repeat(64),\n      sig: '',\n    };\n\n    let signature: Signature = sessionSignature;\n    let authorKeyId = sessionAuthorKeyId;\n    let authorPubBase64: string | null = null;\n\n    if (!sessionAuth) {\n      if (!signingKey || !identity) {\n        throw new PublishError('Missing local signing key for CLI publish.', 'publish_failed');\n      }\n      signature = signEnvelope(contentHash, signingKey, {\n        binding: {\n          ref: `@${publishHandle}/${bareSlug}`,\n          version: (entry.version ?? 0) + 1,\n          authorKeyId: identity.keyId,\n        },\n      });\n      const jwk = signingKey.publicKey.export({ format: 'jwk' }) as { x: string };\n      authorPubBase64 = Buffer.from(jwk.x, 'base64url').toString('base64');\n      authorKeyId = identity.keyId;\n    }\n\n    let publishResult: Awaited<ReturnType<typeof client.publishSkill>>;\n    try {\n      publishResult = await client.publishSkill({\n        author: publishHandle,\n        slug: bareSlug,\n        files,\n        base_hash: baseHash,\n        ...(sessionAuth\n          ? { publish_auth: 'session' as const }\n          : { signature }),\n        visibility,\n      });\n    } catch (err) {\n      if (err instanceof RegistryError && err.status === 409) {\n        throw new PublishError(\n          err.message || 'Local is behind remote. Fetch the latest version and re-publish.',\n          'stale_base',\n          (err as RegistryError).body,\n        );\n      }\n      // The publish gate hard-blocked a secret or quarantined verdict.\n      // Carry the structured body (reason + findings) so the CLI renders the fix.\n      if (err instanceof RegistryError && err.code === 'scan_blocked') {\n        throw new PublishError(err.message, 'scan_blocked', err.body);\n      }\n      throw new PublishError(\n        `Registry rejected publish: ${(err as Error).message}`,\n        'publish_failed',\n      );\n    }\n\n    if (sessionAuth && authorKeyId && !authorPubBase64) {\n      try {\n        const manifestRes = await client.getSkillManifest(`@${publishHandle}/${bareSlug}`);\n        const manifest = manifestRes.value;\n        if (manifest?.author_public_key) {\n          authorPubBase64 = manifest.author_public_key;\n        }\n        if (manifest?.author_key_id) {\n          authorKeyId = manifest.author_key_id;\n        }\n      } catch {\n        // best-effort: session materialize still works via hash gate when keys absent\n      }\n    }\n\n    await upsertSkill({\n      ...entry,\n      source: 'registry',\n      registryUrl,\n      ...(authorKeyId ? { authorKeyId } : {}),\n      ...(authorPubBase64 ? { authorPubBase64 } : {}),\n      signature,\n      hash: contentHash,\n      updatedAt: new Date().toISOString(),\n    });\n\n    const resultHash = publishResult.hash;\n    const resultHashRef = resultHash.startsWith('sha256:') ? resultHash : `sha256:${resultHash}`;\n\n    recordEvent('publish', detectInitiator(), {\n      slug,\n      hash: resultHashRef,\n      alreadyExists: publishResult.already_exists,\n    });\n\n    results.push({\n      hash: resultHash,\n      hashRef: resultHashRef,\n      versionUrl: publishResult.version_url,\n      owner: publishHandle,\n      alreadyExists: publishResult.already_exists,\n      ...(publishResult.scan ? { serverScan: publishResult.scan } : {}),\n      slug,\n      requiresWarnings,\n      triggersWarnings,\n    });\n  }\n\n  return results;\n}\n", "/**\n * TOFU (trust-on-first-use) store for author public keys (PROTOCOL \u00A74).\n *\n * Layout:\n *   $XDG_CONFIG_HOME/skillet/pinned/<handle>.pub.json\n *     { \"key_id\": \"<64-hex>\", \"alg\": \"ed25519\", \"pub\": \"<base64-raw-32>\",\n *       \"pinned_at\": \"<RFC3339>\", \"first_seen_version\": <number> }\n *\n * Why a per-handle file, not a single db:\n *   - Atomic-write semantics are trivial (one file, one rename).\n *   - A hostile registry can only attack one handle at a time; no monolithic\n *     attack surface and easy human inspection / surgical revert.\n *   - Sync state is decoupled from credentials in ~/.skillet/keys/ (own keys).\n *\n * Verification flow (sync, materialize, CI):\n *   1. Take envelope.key_id off the registry response or lockfile.\n *   2. Look up the pinned key for the handle.\n *   3. If absent \u2192 pin this key (TOFU first-sight), continue.\n *   4. If pinned and key_id matches \u2192 verify and continue.\n *   5. If pinned and key_id differs \u2192 loud `author_key_changed` and refuse\n *      to write. Never silently accept (PROTOCOL \u00A74 hard rule).\n *\n * A lockfile clone closes the TOFU hole: the lockfile already carries the\n * pinned author_key, so a fresh checkout has the pinned identity before the\n * first network call (PROTOCOL \u00A711 + acceptance criterion 5). See `lock.ts`.\n */\n\nimport { mkdir, readFile, readdir, writeFile, rename, unlink, chmod } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { createPublicKey, type KeyObject } from \"node:crypto\";\nimport { SignatureError } from \"./envelope.js\";\n\nconst VALID_KEY_ID_RE = /^[0-9a-f]{64}$/;\n// Handles are URL-safe lowercase per \u00A71.1; we still enforce a strict\n// allowlist before joining to avoid path traversal from a hostile manifest.\nconst VALID_HANDLE_RE = /^[a-z0-9-]{1,64}$/;\n\nexport interface PinnedAuthorKey {\n  /** Lowercase hex Ed25519 key ID \u2014 also the filename stem. */\n  key_id: string;\n  alg: \"ed25519\";\n  /** Base64 of the 32 raw Ed25519 public-key bytes. */\n  pub: string;\n  pinned_at: string;\n  first_seen_version: number;\n}\n\nfunction normalizeHandle(handle: string): string {\n  const h = handle.startsWith(\"@\") ? handle.slice(1) : handle;\n  if (!VALID_HANDLE_RE.test(h)) {\n    throw new Error(`Invalid handle ${JSON.stringify(handle)}`);\n  }\n  return h;\n}\n\nexport function defaultPinDir(): string {\n  const cfg = process.env[\"XDG_CONFIG_HOME\"] ?? join(homedir(), \".config\");\n  return join(cfg, \"skillet\", \"pinned\");\n}\n\nfunction pinPath(dir: string, handle: string): string {\n  return join(dir, `${normalizeHandle(handle)}.pub.json`);\n}\n\n/**\n * Bind a key_id to its public key: key_id MUST equal hex(raw pubkey bytes).\n * Without this a hostile registry can claim any pinned key_id while serving an\n * attacker pub, sign with the attacker priv, and pass both the envelope check\n * and the TOFU string comparison \u2014 the pin would provide zero protection.\n * Comparison need not be constant-time (both values are public). Mirrors the\n * invariant in commands/add.ts so every trust path shares one check.\n */\nexport function assertKeyIdBindsPub(keyId: string, pubBase64: string): void {\n  const derivedKeyId = Buffer.from(pubBase64, \"base64\").toString(\"hex\");\n  if (derivedKeyId !== keyId) {\n    throw new SignatureError(\n      \"signature_invalid\",\n      `author_key_id ${keyId} does not match author_pub (derived key_id ${derivedKeyId})`\n    );\n  }\n}\n\n/** Convert a raw 32-byte Ed25519 pub key (base64) to a Node KeyObject. */\nexport function publicKeyFromBase64(b64: string): KeyObject {\n  const raw = Buffer.from(b64, \"base64\");\n  if (raw.length !== 32) {\n    throw new Error(\n      `Invalid Ed25519 public key: expected 32 raw bytes, got ${raw.length}`\n    );\n  }\n  const jwk = { kty: \"OKP\", crv: \"Ed25519\", x: raw.toString(\"base64url\") };\n  return createPublicKey({ key: jwk, format: \"jwk\" });\n}\n\n/**\n * Reads the pinned key for a handle. Returns null if no pin exists yet.\n * Throws on any other I/O / parse / shape error \u2014 corruption MUST surface,\n * not silently fall through to a re-pin.\n */\nexport async function loadPinnedKey(\n  handle: string,\n  pinDir: string = defaultPinDir()\n): Promise<PinnedAuthorKey | null> {\n  const p = pinPath(pinDir, handle);\n  let raw: string;\n  try {\n    raw = await readFile(p, \"utf8\");\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n    throw err;\n  }\n  const parsed = JSON.parse(raw) as PinnedAuthorKey;\n  if (!parsed || typeof parsed !== \"object\") {\n    throw new Error(`Pinned key file ${p} is malformed`);\n  }\n  if (parsed.alg !== \"ed25519\" || !VALID_KEY_ID_RE.test(parsed.key_id)) {\n    throw new Error(`Pinned key file ${p} has invalid alg/key_id`);\n  }\n  return parsed;\n}\n\n/**\n * Pins a freshly-seen key for a handle. Atomic (temp + rename) and refuses\n * to overwrite an existing pin \u2014 overwrite is a separate, explicit ceremony\n * a human runs after reviewing an `author_key_changed` warning.\n */\nexport async function pinAuthorKey(\n  handle: string,\n  key: { key_id: string; pub: Buffer | string; first_seen_version: number },\n  pinDir: string = defaultPinDir()\n): Promise<PinnedAuthorKey> {\n  if (!VALID_KEY_ID_RE.test(key.key_id)) {\n    throw new Error(`pinAuthorKey: invalid key_id ${JSON.stringify(key.key_id)}`);\n  }\n  const pubB64 = typeof key.pub === \"string\" ? key.pub : key.pub.toString(\"base64\");\n  const raw = Buffer.from(pubB64, \"base64\");\n  if (raw.length !== 32) {\n    throw new Error(\n      `pinAuthorKey: pub must be 32 raw bytes, got ${raw.length}`\n    );\n  }\n  // Never pin a (key_id, pub) the registry didn't actually bind together.\n  assertKeyIdBindsPub(key.key_id, pubB64);\n\n  await mkdir(pinDir, { recursive: true, mode: 0o700 });\n  const dest = pinPath(pinDir, handle);\n  const existing = await loadPinnedKey(handle, pinDir);\n  if (existing) {\n    if (existing.key_id !== key.key_id) {\n      throw new SignatureError(\n        \"key_id_mismatch\",\n        `author_key_changed: handle ${handle} is already pinned to ${existing.key_id}, refusing to silently re-pin to ${key.key_id}`\n      );\n    }\n    return existing; // idempotent re-pin of same key\n  }\n\n  const record: PinnedAuthorKey = {\n    key_id: key.key_id,\n    alg: \"ed25519\",\n    pub: pubB64,\n    pinned_at: new Date().toISOString(),\n    first_seen_version: key.first_seen_version,\n  };\n  const tmp = `${dest}.tmp`;\n  try {\n    await writeFile(tmp, JSON.stringify(record, null, 2) + \"\\n\", {\n      encoding: \"utf8\",\n      mode: 0o600,\n    });\n    await chmod(tmp, 0o600);\n    await rename(tmp, dest);\n  } catch (err) {\n    try { await unlink(tmp); } catch { /* best effort */ }\n    throw err;\n  }\n  return record;\n}\n\n/**\n * Explicit overwrite for the human-approved rotation path: after a loud\n * `author_key_changed` warning, a user opts to re-pin. Kept separate from\n * `pinAuthorKey` so the silent-accept path does not exist.\n */\nexport async function forceRepinAuthorKey(\n  handle: string,\n  key: { key_id: string; pub: Buffer | string; first_seen_version: number },\n  pinDir: string = defaultPinDir()\n): Promise<PinnedAuthorKey> {\n  const dest = pinPath(pinDir, handle);\n  try { await unlink(dest); } catch { /* may not exist */ }\n  return pinAuthorKey(handle, key, pinDir);\n}\n\n/**\n * Resolve the author primary key for signature verification without persisting\n * a TOFU pin. Call {@link commitAuthorKeyPin} only after verification succeeds.\n */\nexport async function authorKeyForVerification(\n  handle: string,\n  served: { key_id: string; pub: string },\n  pinDir: string = defaultPinDir(),\n): Promise<{\n  keyObject: KeyObject;\n  pinnedPrimary: { keyId: string; pub: string };\n  needsPinAfterVerify: boolean;\n}> {\n  assertKeyIdBindsPub(served.key_id, served.pub);\n  const existing = await loadPinnedKey(handle, pinDir);\n  if (existing) {\n    if (existing.key_id !== served.key_id) {\n      throw new SignatureError(\n        \"key_id_mismatch\",\n        `author_key_changed: handle ${handle} pinned to ${existing.key_id}, registry served ${served.key_id}`\n      );\n    }\n    return {\n      keyObject: publicKeyFromBase64(existing.pub),\n      pinnedPrimary: { keyId: existing.key_id, pub: existing.pub },\n      needsPinAfterVerify: false,\n    };\n  }\n  return {\n    keyObject: publicKeyFromBase64(served.pub),\n    pinnedPrimary: { keyId: served.key_id, pub: served.pub },\n    needsPinAfterVerify: true,\n  };\n}\n\n/** Persist a TOFU pin after signature verification succeeded on first sight. */\nexport async function commitAuthorKeyPin(\n  handle: string,\n  served: { key_id: string; pub: string },\n  at_version: number,\n  pinDir: string = defaultPinDir(),\n): Promise<PinnedAuthorKey> {\n  return pinAuthorKey(\n    handle,\n    { key_id: served.key_id, pub: served.pub, first_seen_version: at_version },\n    pinDir,\n  );\n}\n\n/**\n * Resolution helper: given a handle and the registry-served pubkey, returns\n * a verifiable KeyObject. On TOFU first-sight, pins the key and returns it.\n * On match, returns the pinned key. On mismatch, throws SignatureError\n * (`key_id_mismatch`) \u2014 caller MUST treat as a hard stop.\n *\n * `at_version` is recorded for forensics (which version pinned this key).\n */\nexport async function resolveAuthorKey(\n  handle: string,\n  served: { key_id: string; pub: string },\n  at_version: number,\n  pinDir: string = defaultPinDir()\n): Promise<{ keyObject: KeyObject; pinned: PinnedAuthorKey; newlyPinned: boolean }> {\n  // The registry-served (key_id, pub) MUST bind before we trust it on either\n  // the first-sight pin or the repeat-visit compare. Reject a forged pair up\n  // front so a mismatched pub can never reach the string comparison below.\n  assertKeyIdBindsPub(served.key_id, served.pub);\n  const existing = await loadPinnedKey(handle, pinDir);\n  if (existing) {\n    if (existing.key_id !== served.key_id) {\n      throw new SignatureError(\n        \"key_id_mismatch\",\n        `author_key_changed: handle ${handle} pinned to ${existing.key_id}, registry served ${served.key_id}`\n      );\n    }\n    return {\n      keyObject: publicKeyFromBase64(existing.pub),\n      pinned: existing,\n      newlyPinned: false,\n    };\n  }\n  const pinned = await pinAuthorKey(\n    handle,\n    { key_id: served.key_id, pub: served.pub, first_seen_version: at_version },\n    pinDir\n  );\n  return {\n    keyObject: publicKeyFromBase64(pinned.pub),\n    pinned,\n    newlyPinned: true,\n  };\n}\n\n/** For diagnostics/`skillet doctor`: list every handle the user has pinned. */\nexport async function listPinnedHandles(\n  pinDir: string = defaultPinDir()\n): Promise<string[]> {\n  try {\n    const entries = await readdir(pinDir);\n    return entries\n      .filter((e) => e.endsWith(\".pub.json\"))\n      .map((e) => e.slice(0, -\".pub.json\".length))\n      .filter((h) => VALID_HANDLE_RE.test(h));\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n    throw err;\n  }\n}\n\n// Re-export so callers that only deal with TOFU never import envelope.ts.\nexport { SignatureError } from \"./envelope.js\";\n", "// Leaf helpers for the customized-skills machinery \u2014 the pieces that do NOT\n// depend on sync.ts. Extracting them here breaks the two-way ESM cycle between\n// edits.ts (which imports `verifyForMaterialize` from sync.ts) and sync.ts /\n// restore.ts (which need these leaf helpers): during module init the cycle used\n// to reach edits.ts's top-level `export const LEDGER_STAMP` before it was\n// initialized (a TDZ ReferenceError). This module imports NOTHING from sync.ts,\n// so it initializes cleanly and both sides depend on it one-directionally.\n//\n// The `~/.skillet/edits/` dir is a BACKUP STORE: the user's version is snapshot\n// there on first customize and again before any Take theirs / Restore original\n// replaces it, so a replaced edit is always recoverable. It has NO TTL and is\n// deliberately separate from `~/.skillet/trash` (a 30-day sweep target): the\n// edits store is user work a trash-emptying tool must never eat.\nimport { readdir, readFile, writeFile, lstat, mkdir, rename, rm, cp } from 'node:fs/promises'\nimport { join, relative, sep, basename, dirname } from 'node:path'\nimport { canonicalContentHash } from '@skillet/protocol'\nimport { skilletDir } from '../session-token.js'\nimport { atomicWrite } from '../util/atomic.js'\nimport type { Adapter } from '../adapter.js'\n\n// \u2500\u2500 shared run-dir conventions (trash + edits) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** A unique run-dir name, shared by the trash and edits ledgers. */\nexport function ledgerStamp(): string {\n  return `${new Date().toISOString().replace(/[:.]/g, '-')}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/** Matches ledgerStamp() output \u2014 listing/clearing never reaches a foreign dir. */\nexport const LEDGER_STAMP = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}Z-[a-z0-9]{6}$/\n\n/** Write a run's `manifest.json`, creating the run dir. */\nexport async function writeRunManifest(\n  runDir: string,\n  manifest: Record<string, unknown>,\n): Promise<void> {\n  await mkdir(runDir, { recursive: true })\n  await writeFile(join(runDir, 'manifest.json'), JSON.stringify(manifest, null, 2))\n}\n\n/**\n * Move a dir, preferring an atomic rename and falling back to copy+remove\n * across filesystems (EXDEV). Shared by the prune trash pass and restore.\n * Returns true on success.\n *\n * Success means THE BYTES ARE IN THE DESTINATION. When the fallback copy\n * succeeded but removing the source failed, that is still a success \u2014 the\n * leftover source is reported best-effort via `opts.onLeftover`, never by\n * failing the move (a false failure here would make callers treat preserved\n * bytes as lost).\n */\nexport async function moveDir(\n  from: string,\n  to: string,\n  opts: { onLeftover?: (src: string) => void } = {},\n): Promise<boolean> {\n  await mkdir(dirname(to), { recursive: true })\n  try {\n    await rename(from, to)\n    return true\n  } catch {\n    try {\n      await cp(from, to, { recursive: true })\n    } catch {\n      return false\n    }\n    try {\n      await rm(from, { recursive: true, force: true })\n    } catch {\n      opts.onLeftover?.(from)\n    }\n    return true\n  }\n}\n\n// \u2500\u2500 lineage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The signed author origin a customized skill's edit was made against. */\nexport interface SkillLineage {\n  author: string | null\n  slug: string\n  version: number\n  hash: string\n}\n\nexport function editsRoot(): string {\n  return join(skilletDir(), 'edits')\n}\n\n// \u2500\u2500 baseline stash (Restore original) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Content-addressed store of the AUTHOR baseline a customized skill was edited\n * from \u2014 the bytes at `customized_from.hash`. Snapshotted at first-customize\n * (while the skill store still holds those bytes, before any pull overwrites\n * them) so \"Restore original\" can return the version the edit was made FROM\n * even after an author update is pulled \u2014 the case that makes restoreOriginal\n * meaningfully distinct from takeUpstream (F5). Keyed by hash \u2192 self-dedup, no\n * TTL; a trash sweep must never eat it (it lives under `~/.skillet/baselines`).\n */\nexport function baselinesRoot(): string {\n  return join(skilletDir(), 'baselines')\n}\n\nfunction baselineDir(hash: string): string {\n  // `sha256:<hex>` \u2192 a filesystem-safe dir name. Content-addressed: the same\n  // baseline hash always maps to the same dir, so re-stashing is idempotent.\n  return join(baselinesRoot(), hash.replace(/[^a-zA-Z0-9]/g, '_'))\n}\n\n/**\n * Snapshot a baseline bundle under its content hash. Idempotent by hash.\n * Each file is written atomically (temp + rename, F7): a torn write leaves a\n * half-written stash that `readBaselineStash` would otherwise trust \u2014 the atomic\n * write plus the read-side hash validation together reject any partial snapshot.\n */\nexport async function stashBaselineVersion(\n  hash: string,\n  bundle: Map<string, Buffer>,\n): Promise<void> {\n  const dir = baselineDir(hash)\n  await mkdir(dir, { recursive: true })\n  for (const [rel, bytes] of bundle) {\n    const dest = join(dir, ...rel.split('/'))\n    await atomicWrite(dest, bytes, { backup: false })\n  }\n}\n\n/**\n * Read a stashed baseline bundle by hash, or null when none is stored OR the\n * stashed bytes do not hash to `hash` (F7): a torn/partial stash never round-\n * trips through canonicalContentHash, so a caller only ever gets a verified-\n * complete baseline back \u2014 never half of one.\n */\nexport async function readBaselineStash(hash: string): Promise<Map<string, Buffer> | null> {\n  try {\n    const tree = await readTreeIgnoringDotfiles(baselineDir(hash))\n    if (tree.size === 0) return null\n    if (canonicalContentHash(tree) !== hash) return null\n    return tree\n  } catch {\n    return null\n  }\n}\n\n/** Delete a skill's stashed baseline (F8: bound the stash \u2014 drop it once the\n * skill is un-customized or its entry is localized/removed). Best-effort. */\nexport async function clearBaselineStash(hash: string): Promise<void> {\n  try {\n    await rm(baselineDir(hash), { recursive: true, force: true })\n  } catch {\n    // Best-effort disk hygiene \u2014 a failed cleanup never blocks the caller.\n  }\n}\n\n// \u2500\u2500 dotfile-tolerant read \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Read a materialized skill dir, ignoring dot-prefixed names (AE7): a\n * `.DS_Store` must never make the drift read throw \u2014 that would turn detection\n * off. Symlinks and non-regular files are skipped, never followed. The SAME\n * tree feeds detection hashing and backup copying, so the two cannot disagree.\n */\nexport async function readTreeIgnoringDotfiles(dir: string): Promise<Map<string, Buffer>> {\n  const out = new Map<string, Buffer>()\n  await walkIgnoringDotfiles(dir, dir, out)\n  return out\n}\n\nasync function walkIgnoringDotfiles(\n  root: string,\n  dir: string,\n  out: Map<string, Buffer>,\n): Promise<void> {\n  const entries = await readdir(dir, { withFileTypes: true })\n  for (const entry of entries) {\n    if (entry.name.startsWith('.')) continue\n    if (entry.name.endsWith('.skillet-backup')) continue\n    const absPath = join(dir, entry.name)\n    const st = await lstat(absPath)\n    if (st.isSymbolicLink()) continue\n    if (st.isDirectory()) {\n      await walkIgnoringDotfiles(root, absPath, out)\n    } else if (st.isFile()) {\n      const rel = relative(root, absPath)\n      out.set(sep === '/' ? rel : rel.split(sep).join('/'), await readFile(absPath))\n    }\n  }\n}\n\n// \u2500\u2500 drift detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface DriftedCopy {\n  adapter: string\n  dir: string\n}\n\n/** An EXISTING dir whose tree could not be read or hashed \u2014 possibly edited, but unreadable. */\nexport interface UncapturableCopy extends DriftedCopy {\n  /** errno-style code from the failed read/hash, when available. */\n  code: string | null\n}\n\nexport interface DriftDetection {\n  drifted: DriftedCopy[]\n  /**\n   * Existing, non-symlink dirs we could not read or hash. These are NOT clean:\n   * they may hold an edit we cannot prove absent. Callers MUST NOT materialize\n   * over them (never overwrite a possibly-edited dir uncaptured).\n   */\n  uncapturable: UncapturableCopy[]\n}\n\nfunction errnoCode(err: unknown): string | null {\n  const code = (err as NodeJS.ErrnoException | null)?.code\n  return typeof code === 'string' ? code : null\n}\n\n/**\n * Find EVERY global adapter copy of a synced skill whose on-disk bytes drifted\n * from `baselineHash` \u2014 the hash sync last wrote. Project adapters and symlinked\n * dirs are skipped, as is a MISSING dir (nothing on disk). An existing dir we\n * cannot read or hash is returned as `uncapturable` \u2014 never silently clean.\n */\nexport async function detectDriftedGlobalCopies(\n  adapters: Adapter[],\n  adapterSlug: string,\n  owner: string | null,\n  baselineHash: string,\n): Promise<DriftDetection> {\n  const drifted: DriftedCopy[] = []\n  const uncapturable: UncapturableCopy[] = []\n  for (const adapter of adapters) {\n    if (adapter.kind === 'project') continue\n    let dir: string\n    try {\n      dir = adapter.targetSkillDir(adapterSlug, { owner })\n    } catch {\n      continue\n    }\n    let st\n    try {\n      st = await lstat(dir)\n    } catch (err) {\n      const code = errnoCode(err)\n      // Missing target \u2192 nothing on disk. Anything else (EACCES, EIO\u2026) means a\n      // dir may exist that we cannot even inspect \u2014 uncapturable.\n      if (code === 'ENOENT' || code === 'ENOTDIR') continue\n      uncapturable.push({ adapter: adapter.name, dir, code })\n      continue\n    }\n    if (st.isSymbolicLink() || !st.isDirectory()) continue\n    let tree: Map<string, Buffer>\n    try {\n      tree = await readTreeIgnoringDotfiles(dir)\n    } catch (err) {\n      uncapturable.push({ adapter: adapter.name, dir, code: errnoCode(err) })\n      continue\n    }\n    if (tree.size === 0) continue\n    let hash: string\n    try {\n      hash = canonicalContentHash(tree)\n    } catch (err) {\n      uncapturable.push({ adapter: adapter.name, dir, code: errnoCode(err) })\n      continue\n    }\n    if (hash !== baselineHash) drifted.push({ adapter: adapter.name, dir })\n  }\n  return { drifted, uncapturable }\n}\n\n// \u2500\u2500 backup store \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type BackupReason = 'customize' | 'take-upstream' | 'restore-original'\n\nexport interface BackupManifest {\n  backup_id: string\n  reason: BackupReason\n  lineage: SkillLineage\n  adapters: string[]\n  original_paths: string[]\n  tree_hash: string\n  backed_up_at: string\n}\n\nexport interface BackupEntry {\n  id: string\n  dir: string\n  /** Manifest missing or corrupt \u2014 surfaced as an entry, never silently skipped. */\n  unreadable: boolean\n  manifest?: BackupManifest\n}\n\n/**\n * Snapshot a skill's on-disk copies into a new backup entry under\n * `~/.skillet/edits/<stamp>/<adapter>/<dirname>/` with a manifest. No\n * coalescing, no supersede chains \u2014 one snapshot per call, keyed by a fresh\n * stamp. Written on first customize and before Take theirs / Restore original,\n * so the replaced version is always recoverable. Throws only if the write fails.\n */\nexport async function backupSkillVersion(args: {\n  lineage: SkillLineage\n  copies: DriftedCopy[]\n  reason: BackupReason\n}): Promise<{ backupId: string }> {\n  const copies = [...args.copies].sort((a, b) => a.adapter.localeCompare(b.adapter))\n  const backupId = ledgerStamp()\n  const backupDir = join(editsRoot(), backupId)\n  const combined = new Map<string, Buffer>()\n  const adapters: string[] = []\n  const originalPaths: string[] = []\n  for (const copy of copies) {\n    const tree = await readTreeIgnoringDotfiles(copy.dir)\n    const destRoot = join(backupDir, copy.adapter, basename(copy.dir))\n    for (const [rel, bytes] of tree) {\n      const dest = join(destRoot, ...rel.split('/'))\n      // Atomic (temp + rename, F7): a torn backup write must never leave a\n      // half-copy that a later recovery/restore trusts as the user's edit.\n      await atomicWrite(dest, bytes, { backup: false })\n      combined.set(`${copy.adapter}/${basename(copy.dir)}/${rel}`, bytes)\n    }\n    adapters.push(copy.adapter)\n    originalPaths.push(copy.dir)\n  }\n  const manifest: BackupManifest = {\n    backup_id: backupId,\n    reason: args.reason,\n    lineage: args.lineage,\n    adapters,\n    original_paths: originalPaths,\n    tree_hash: canonicalContentHash(combined),\n    backed_up_at: new Date().toISOString(),\n  }\n  await writeRunManifest(backupDir, manifest as unknown as Record<string, unknown>)\n  return { backupId }\n}\n\n/** All backup entries, newest first. Unreadable manifests are surfaced, never skipped. */\nexport async function listBackups(): Promise<BackupEntry[]> {\n  let entries\n  try {\n    entries = await readdir(editsRoot(), { withFileTypes: true })\n  } catch {\n    return []\n  }\n  const out: BackupEntry[] = []\n  for (const e of entries) {\n    if (!e.isDirectory() || !LEDGER_STAMP.test(e.name)) continue\n    const dir = join(editsRoot(), e.name)\n    try {\n      const manifest = JSON.parse(\n        await readFile(join(dir, 'manifest.json'), 'utf8'),\n      ) as BackupManifest\n      out.push({ id: e.name, dir, unreadable: false, manifest })\n    } catch {\n      out.push({ id: e.name, dir, unreadable: true })\n    }\n  }\n  out.sort((a, b) => b.id.localeCompare(a.id)) // stamp is ISO-prefixed \u2192 lexical = chronological\n  return out\n}\n", "import { readFile, mkdir, lstat, mkdtemp, rm, readdir } from \"node:fs/promises\";\nimport { resolve, basename, dirname, join } from \"node:path\";\nimport { tmpdir } from \"node:os\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport matter from \"gray-matter\";\nimport { canonicalContentHash, validateRequires, validateTriggers, slugify as canonicalSlugify, type DecodedBundle } from \"@skillet/protocol\";\nimport { assertSafeSlug } from \"../util/pathsafe.js\";\nimport { readState, writeBundleToSkillStore, upsertSkill, skillContentDir } from \"../kit/store.js\";\nimport { readBundleFromDir } from \"../bundle/read.js\";\nimport { recordEvent, detectInitiator } from \"../metrics.js\";\nimport type { SkillEntry } from \"../kit/types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport class ImportCollisionError extends Error {\n  readonly code = \"slug_collision\" as const;\n\n  constructor(public readonly slug: string) {\n    super(\n      `Skill slug \"${slug}\" already exists in your kit. Re-import with --force to overwrite.`,\n    );\n    this.name = \"ImportCollisionError\";\n  }\n}\n\nexport interface ImportSkillOptions {\n  force?: boolean;\n}\n\nasync function assertImportAllowed(slug: string, force?: boolean): Promise<void> {\n  const state = await readState();\n  if (state.skills[slug] && !force) {\n    throw new ImportCollisionError(slug);\n  }\n}\n\nexport function slugify(name: string): string {\n  return canonicalSlugify(name, { maxLength: 64 });\n}\n\n/**\n * Import a skill from the filesystem.\n *\n * Accepts either:\n *   - a directory containing `SKILL.md` at its root (preferred \u2014 full bundle, \u00A72.1), or\n *   - a path to a `SKILL.md` file (legacy single-file import \u2014 the bundle is the\n *     containing directory).\n *\n * The skill is hashed canonically (\u00A72.2) and stored as the full bundle tree\n * under `~/.skillet/skills/<slug>/`, ready for sync to materialize.\n */\nexport async function importSkill(\n  skillPath: string,\n  opts: ImportSkillOptions = {},\n): Promise<SkillEntry> {\n  const resolvedPath = resolve(skillPath);\n  const skillDir = await resolveSkillDir(resolvedPath);\n\n  const bundle = await readBundleFromDir(skillDir);\n\n  const entrypointBytes = bundle.get(\"SKILL.md\")!;\n  const parsed = matter(Buffer.from(entrypointBytes).toString(\"utf8\"));\n  const fm = parsed.data as Record<string, unknown>;\n  const rawName =\n    typeof fm[\"name\"] === \"string\" ? fm[\"name\"] : basename(skillDir);\n  const description =\n    typeof fm[\"description\"] === \"string\" ? fm[\"description\"] : \"\";\n\n  // Enforce the `requires:` schema at the import boundary. selfRef is\n  // omitted: the skill has no minted @author/slug ref yet, so self-dependency\n  // detection runs later at publish (per the module contract). A malformed\n  // `requires` block throws RequiresError and aborts the import.\n  validateRequires(fm[\"requires\"]);\n  validateTriggers(fm[\"triggers\"]);\n\n  const slug = slugify(rawName);\n  assertSafeSlug(slug);\n  await assertImportAllowed(slug, opts.force);\n\n  const hash = canonicalContentHash(bundle);\n  const now = new Date().toISOString();\n\n  await mkdir(skillContentDir(slug), { recursive: true });\n  await writeBundleToSkillStore(slug, bundle);\n\n  const entry: SkillEntry = {\n    slug,\n    name: rawName,\n    description,\n    version: 1,\n    hash,\n    source: \"local\",\n    importedAt: now,\n    updatedAt: now,\n  };\n\n  await upsertSkill(entry);\n\n  recordEvent(\"skill.import\", detectInitiator(), { slug });\n\n  return entry;\n}\n\nasync function resolveSkillDir(p: string): Promise<string> {\n  const st = await lstat(p);\n  if (st.isDirectory()) {\n    // Confirm SKILL.md is at the root \u2014 readBundleFromDir will assert this too,\n    // but we can give a better error message before the walk.\n    try {\n      await lstat(join(p, \"SKILL.md\"));\n    } catch {\n      throw new Error(`Skill directory \"${p}\" is missing SKILL.md at its root.`);\n    }\n    return p;\n  }\n  if (st.isFile() && basename(p) === \"SKILL.md\") {\n    return dirname(p);\n  }\n  throw new Error(`Cannot import \"${p}\": expected a directory or a path to SKILL.md.`);\n}\n\n// Compatibility export \u2014 older code paths and tests may still call readFile\n// patterns; keep the name available for the (rare) case where a caller wants\n// just the entrypoint text.\nexport async function readSkillEntrypoint(skillDir: string): Promise<string> {\n  return await readFile(join(skillDir, \"SKILL.md\"), \"utf8\");\n}\n\nexport type { DecodedBundle };\n\n// `skillet import <owner>/<repo>` \u2014 clone a GitHub repo and\n// import every skill found in it (directories containing SKILL.md at root).\n// Uses `git clone --depth 1` for speed; temp dir is cleaned up on exit.\n\nconst GITHUB_REPO_RE = /^([a-zA-Z0-9_.-]+)\\/([a-zA-Z0-9_.-]+)$/;\n\nexport function isGithubRepoRef(input: string): boolean {\n  return GITHUB_REPO_RE.test(input);\n}\n\nexport async function importFromGithubRepo(\n  ownerRepo: string,\n  opts: ImportSkillOptions = {},\n): Promise<SkillEntry[]> {\n  const match = GITHUB_REPO_RE.exec(ownerRepo);\n  if (!match) {\n    throw new Error(\n      `Invalid repo reference \"${ownerRepo}\". Expected format: owner/repo`,\n    );\n  }\n  const [, owner, repo] = match;\n  const cloneUrl = `https://github.com/${owner}/${repo}.git`;\n\n  const tmpDir = await mkdtemp(join(tmpdir(), \"skillet-import-\"));\n  try {\n    // Shallow clone \u2014 we only need the latest tree.\n    await execFileAsync(\"git\", [\"clone\", \"--depth\", \"1\", \"--quiet\", cloneUrl, tmpDir]);\n\n    // Find all directories containing a SKILL.md at their root.\n    const skillDirs = await findSkillDirs(tmpDir);\n    if (skillDirs.length === 0) {\n      throw new Error(\n        `No skills found in ${ownerRepo}. A skill directory must contain SKILL.md at its root.`,\n      );\n    }\n\n    const imported: SkillEntry[] = [];\n    for (const dir of skillDirs) {\n      const entry = await importSkill(dir, opts);\n      imported.push(entry);\n    }\n\n    recordEvent(\"skill.import.github\", detectInitiator(), {\n      repo: ownerRepo,\n      count: imported.length,\n    });\n\n    return imported;\n  } finally {\n    await rm(tmpDir, { recursive: true, force: true });\n  }\n}\n\n// Walk `root` depth-first. A directory that has SKILL.md at its root is a\n// skill dir; we don't recurse into it (nested skills are not supported).\nasync function findSkillDirs(root: string): Promise<string[]> {\n  const results: string[] = [];\n  await walkForSkills(root, root, results);\n  return results;\n}\n\nasync function walkForSkills(\n  root: string,\n  dir: string,\n  acc: string[],\n): Promise<void> {\n  let entries: string[];\n  try {\n    entries = await readdir(dir);\n  } catch {\n    return;\n  }\n\n  if (entries.includes(\"SKILL.md\")) {\n    acc.push(dir);\n    return; // don't recurse into a skill dir\n  }\n\n  // Skip common non-skill dirs to keep the walk fast.\n  const skip = new Set([\"node_modules\", \".git\", \".github\", \"dist\", \"build\"]);\n  for (const name of entries) {\n    if (skip.has(name)) continue;\n    const child = join(dir, name);\n    let st;\n    try {\n      st = await lstat(child);\n    } catch {\n      continue;\n    }\n    if (st.isDirectory()) {\n      await walkForSkills(root, child, acc);\n    }\n  }\n}\n", "// `skillet restore` \u2014 bring back skills that a sync prune moved to trash, and\n// age-clear old trash. Operates ONLY off the ledger each prune run writes\n// (`~/.skillet/trash/<stamp>/manifest.json`); it never reconstructs paths\n// heuristically, and it only ever touches dirs matching the prune stamp format.\nimport { readdir, readFile, rm, lstat } from 'node:fs/promises';\nimport { realpathSync } from 'node:fs';\nimport { join, resolve, sep } from 'node:path';\nimport { skilletDir } from '../session-token.js';\nimport { isSkilletSlugDirName } from '../bundle/write.js';\nimport { MATERIALIZATION_ROOT_ALLOWLIST } from '../util/pathsafe.js';\nimport { ledgerStamp, LEDGER_STAMP, writeRunManifest, moveDir } from './edits-store.js';\nimport { importSkill } from './import.js';\n\n/** True iff `child` resolves to `root` or a path beneath it (symlink-safe). */\nfunction withinRoot(child: string, root: string): boolean {\n  let r: string;\n  let c: string;\n  try {\n    r = realpathSync(root);\n    c = realpathSync(child);\n  } catch {\n    r = resolve(root);\n    c = resolve(child);\n  }\n  return c === r || c.startsWith(r + sep);\n}\n\n/**\n * The roots a restore is allowed to write into: the canonical adapter skills\n * roots, plus any in `SKILLET_SKILL_ROOTS` (colon-separated) for advanced setups\n * (a symlinked runtime dir) and sandboxed tests. Read at call time, never frozen.\n */\nfunction restoreRoots(): string[] {\n  const extra = (process.env['SKILLET_SKILL_ROOTS'] ?? '').split(/[:;]/).filter(Boolean);\n  return [...MATERIALIZATION_ROOT_ALLOWLIST, ...extra];\n}\n\n/**\n * Restore destinations are trusted from a user-writable ledger, so they MUST be\n * confined to a real adapter skills root \u2014 otherwise a planted ledger turns\n * `skillet restore` into a write-what-where (move attacker bytes to ~/.ssh, an\n * autostart entry, a shell rc, \u2026). Only paths inside an allowed root, with no\n * traversal/NUL, are eligible.\n */\nfunction isRestorableDest(from: string): boolean {\n  if (typeof from !== 'string' || from.includes('\\0') || from.includes('..')) return false;\n  return restoreRoots().some((root) => withinRoot(from, root));\n}\n\ninterface TrashItem {\n  slug: string;\n  owner: string | null;\n  hash: string;\n  adapter: string;\n  /** Original adapter path the bundle was moved FROM. */\n  from: string;\n  /** Trash path the bundle was moved TO. */\n  to: string;\n}\ninterface TrashLedger {\n  trashedAt: string;\n  /** Which producer wrote this run: 'prune' | 'sweep' | \u2026 (absent pre-kind). */\n  kind?: string;\n  items: TrashItem[];\n}\n\nexport interface TrashRun {\n  /** The trash dir name (the prune run stamp). */\n  id: string;\n  trashedAt: string;\n  /** Distinct skill refs in this run. */\n  skills: string[];\n}\n\nexport interface RestoreResult {\n  runId: string;\n  /** Skill refs whose files were moved back to their adapter dirs. */\n  restored: string[];\n  /** Skill refs re-registered into local kit state. */\n  reimported: string[];\n  /** Items left untouched, with why (destination already exists, etc.). */\n  skipped: Array<{ slug: string; reason: string }>;\n}\n\n// Matches the run stamp `2026-06-20T18-59-08-123Z-abc123` \u2014 never matches a\n// foreign dir, so listing/clearing can't reach outside Skillet's own trash.\nconst TRASH_STAMP = LEDGER_STAMP;\n\nfunction trashRoot(): string {\n  return join(skilletDir(), 'trash');\n}\n\nasync function readLedger(runDir: string): Promise<TrashLedger | null> {\n  try {\n    return JSON.parse(await readFile(join(runDir, 'manifest.json'), 'utf8')) as TrashLedger;\n  } catch {\n    return null;\n  }\n}\n\n/** Existence check that does NOT follow symlinks \u2014 a symlink counts as present\n * (so we never move onto / through it). */\nasync function exists(p: string): Promise<boolean> {\n  try {\n    await lstat(p);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n// Dir moves share moveDir from ./edits-store.js (atomic rename, EXDEV copy+remove\n// fallback) \u2014 one implementation, one set of semantics.\n\n/** List restorable trash runs, newest first. */\nexport async function listTrash(): Promise<TrashRun[]> {\n  let entries;\n  try {\n    entries = await readdir(trashRoot(), { withFileTypes: true });\n  } catch {\n    return [];\n  }\n  const runs: TrashRun[] = [];\n  for (const e of entries) {\n    if (!e.isDirectory() || !TRASH_STAMP.test(e.name)) continue;\n    const ledger = await readLedger(join(trashRoot(), e.name));\n    if (!ledger) continue;\n    runs.push({\n      id: e.name,\n      trashedAt: ledger.trashedAt,\n      skills: [...new Set(ledger.items.map((i) => i.slug))],\n    });\n  }\n  runs.sort((a, b) => b.id.localeCompare(a.id)); // stamp is ISO-prefixed \u2192 lexical = chronological\n  return runs;\n}\n\n/**\n * Restore a trash run (the newest when `runId` is omitted). Moves each ledger\n * item back to its original adapter path and re-registers it as a LOCAL skill\n * (a pruned skill is no longer subscribed). Never clobbers: an item whose\n * destination already exists is skipped. Idempotent \u2014 a second run is a no-op.\n * Returns null when there is nothing to restore.\n */\nexport async function restoreTrash(runId?: string): Promise<RestoreResult | null> {\n  const runs = await listTrash();\n  if (runs.length === 0) return null;\n  const target = runId ? runs.find((r) => r.id === runId) : runs[0];\n  if (!target) return null;\n  const ledger = await readLedger(join(trashRoot(), target.id));\n  if (!ledger) return null;\n\n  const restored = new Set<string>();\n  const skipped: RestoreResult['skipped'] = [];\n  const dirBySlug = new Map<string, string>();\n  const runDir = join(trashRoot(), target.id);\n\n  for (const item of ledger.items) {\n    // The ledger is user-writable: NEVER trust its paths as filesystem sinks.\n    // The destination must be inside a real adapter skills root (blocks the\n    // write-what-where), and the source must stay inside this trash run.\n    if (!isRestorableDest(item.from)) {\n      skipped.push({ slug: item.slug, reason: 'unsafe_destination' });\n      continue;\n    }\n    if (typeof item.to !== 'string' || item.to.includes('\\0') || !withinRoot(item.to, runDir)) {\n      skipped.push({ slug: item.slug, reason: 'unsafe_source' });\n      continue;\n    }\n    if (await exists(item.from)) {\n      skipped.push({ slug: item.slug, reason: 'destination_exists' });\n      continue;\n    }\n    if (!(await exists(item.to))) {\n      skipped.push({ slug: item.slug, reason: 'trash_missing' });\n      continue;\n    }\n    if (await moveDir(item.to, item.from)) {\n      restored.add(item.slug);\n      if (!dirBySlug.has(item.slug)) dirBySlug.set(item.slug, item.from);\n    } else {\n      skipped.push({ slug: item.slug, reason: 'move_failed' });\n    }\n  }\n\n  // Re-register each restored skill as a local skill so it's tracked again and\n  // won't be re-pruned. Files are back even if re-registration fails.\n  const reimported: string[] = [];\n  for (const [slug, dir] of dirBySlug) {\n    try {\n      await importSkill(dir, { force: true });\n      reimported.push(slug);\n    } catch {\n      /* files restored; state re-registration best-effort */\n    }\n  }\n\n  return { runId: target.id, restored: [...restored], reimported, skipped };\n}\n\nexport interface SweepResult {\n  /** Names of the Skillet-managed dirs moved to trash. */\n  trashed: string[];\n  /** Where they went (null when nothing matched). Restorable via `skillet restore`. */\n  trashDir: string | null;\n}\n\n/**\n * Sweep Skillet-managed skill folders (`owner--slug` / `_local--slug`) out of an\n * arbitrary runtime root and into trash \u2014 the safe path to clean up after a\n * deprecated runtime adapter, when an account sync no longer scans that root.\n *\n * NEVER automatic: an explicit `skillet sweep <path>` only. A dir is swept only\n * if it BOTH matches Skillet's naming AND actually contains a `SKILL.md` (a real\n * bundle) \u2014 a name match alone (an unrelated `react--router` clone) is left\n * untouched. Symlinked entries are skipped. Reversible: moved to trash, never a\n * hard delete.\n */\nexport async function sweepOrphans(root: string): Promise<SweepResult> {\n  let entries;\n  try {\n    entries = await readdir(root, { withFileTypes: true });\n  } catch {\n    return { trashed: [], trashDir: null };\n  }\n  const managed: Array<{ name: string }> = [];\n  for (const e of entries) {\n    // Only a real Skillet bundle: managed name, a genuine directory (not a\n    // symlink), with a SKILL.md inside. Name alone is not enough.\n    if (e.isSymbolicLink() || !e.isDirectory() || !isSkilletSlugDirName(e.name)) continue;\n    try {\n      const inner = await readdir(join(root, e.name));\n      if (!inner.includes('SKILL.md')) continue;\n    } catch {\n      continue;\n    }\n    managed.push({ name: e.name });\n  }\n  if (managed.length === 0) return { trashed: [], trashDir: null };\n\n  const trashDir = join(trashRoot(), ledgerStamp());\n  const trashed: string[] = [];\n  const items: Array<Record<string, unknown>> = [];\n  for (const e of managed) {\n    const from = join(root, e.name);\n    const to = join(trashDir, 'sweep', e.name);\n    if (await moveDir(from, to)) {\n      trashed.push(e.name);\n      items.push({ slug: e.name, owner: null, hash: '', adapter: 'sweep', from, to });\n    }\n  }\n  if (items.length > 0) {\n    await writeRunManifest(trashDir, {\n      trashedAt: new Date().toISOString(),\n      kind: 'sweep',\n      items,\n    });\n  }\n  return { trashed, trashDir: trashed.length > 0 ? trashDir : null };\n}\n\n/**\n * Remove trash runs older than `maxAgeDays`. Only touches dirs matching the\n * prune stamp with a parseable, old `trashedAt` \u2014 foreign dirs and recent runs\n * are never removed. Returns the count cleared. Best-effort; never throws.\n */\nexport async function clearOldTrash(maxAgeDays = 30, now = Date.now()): Promise<number> {\n  let entries;\n  try {\n    entries = await readdir(trashRoot(), { withFileTypes: true });\n  } catch {\n    return 0;\n  }\n  const cutoff = now - maxAgeDays * 24 * 60 * 60 * 1000;\n  let cleared = 0;\n  for (const e of entries) {\n    if (!e.isDirectory() || !TRASH_STAMP.test(e.name)) continue;\n    const ledger = await readLedger(join(trashRoot(), e.name));\n    const ts = ledger ? Date.parse(ledger.trashedAt) : NaN;\n    if (Number.isFinite(ts) && ts < cutoff) {\n      try {\n        await rm(join(trashRoot(), e.name), { recursive: true, force: true });\n        cleared++;\n      } catch {\n        /* skip; best-effort */\n      }\n    }\n  }\n  return cleared;\n}\n", "import matter from \"gray-matter\";\nimport { canonicalContentHash, validateBundle, type DecodedBundle } from \"@skillet/protocol\";\nimport { readBundleFromDir } from \"../bundle/read.js\";\nimport {\n  readState,\n  skillContentDir,\n  upsertSkill,\n  writeBundleToSkillStore,\n} from \"../kit/store.js\";\nimport { BUNDLED_ROUTE_SLUG } from \"./route.js\";\nimport type { SkillEntry } from \"../kit/types.js\";\n\nexport type EnsureBundledRouteResult = \"installed\" | \"updated\" | \"unchanged\";\n\nexport { BUNDLED_ROUTE_SLUG };\n\n/** Load the route bundle from disk, falling back to an inlined SKILL.md.\n *\n *  The pkg-compiled desktop sidecar has no `bundled-skills` on disk \u2014 pkg never\n *  snapshots `dist/bundled-skills` \u2014 so the disk read throws there. The CLI\n *  inlines the SKILL.md at bundle time and passes it as the fallback, so the\n *  route skill still materializes for desktop-only users. */\nasync function loadRouteBundle(\n  bundledDir: string,\n  inlineSkillMd: string | undefined,\n): Promise<DecodedBundle> {\n  try {\n    return await readBundleFromDir(bundledDir);\n  } catch (err) {\n    if (!inlineSkillMd) throw err;\n    const bundle: DecodedBundle = new Map();\n    bundle.set(\"SKILL.md\", Buffer.from(inlineSkillMd, \"utf8\"));\n    validateBundle(bundle);\n    return bundle;\n  }\n}\n\nexport async function ensureBundledRouteSkill(\n  bundledDir: string,\n  inlineSkillMd?: string,\n): Promise<EnsureBundledRouteResult> {\n  const bundle = await loadRouteBundle(bundledDir, inlineSkillMd);\n  const hash = canonicalContentHash(bundle);\n  const state = await readState();\n  const existing = state.skills[BUNDLED_ROUTE_SLUG];\n  if (existing?.hash === hash) {\n    try {\n      await readBundleFromDir(skillContentDir(BUNDLED_ROUTE_SLUG));\n      return \"unchanged\";\n    } catch {\n      // Hash matches state but files missing \u2014 reinstall below.\n    }\n  }\n\n  const entrypointBytes = bundle.get(\"SKILL.md\");\n  if (!entrypointBytes) {\n    throw new Error(\"Bundled route skill is missing SKILL.md\");\n  }\n  const parsed = matter(Buffer.from(entrypointBytes).toString(\"utf8\"));\n  const fm = parsed.data as Record<string, unknown>;\n  const name = typeof fm[\"name\"] === \"string\" ? fm[\"name\"] : \"skillet\";\n  const description =\n    typeof fm[\"description\"] === \"string\" ? fm[\"description\"] : \"\";\n\n  await writeBundleToSkillStore(BUNDLED_ROUTE_SLUG, bundle);\n\n  const now = new Date().toISOString();\n  const entry: SkillEntry = {\n    slug: BUNDLED_ROUTE_SLUG,\n    name,\n    description,\n    version: existing?.version ?? 1,\n    hash,\n    source: \"local\",\n    owner: \"skillet\",\n    importedAt: existing?.importedAt ?? now,\n    updatedAt: now,\n  };\n\n  await upsertSkill(entry);\n  return existing ? \"updated\" : \"installed\";\n}\n", "import type { KitState, SkillEntry } from './types.js';\n\n/**\n * Collapse stale \"published twin\" duplicates in the kit state.\n *\n * Publishing a locally-imported skill flips its bare-key entry to\n * `source:'registry'`, and the next union-manifest pull re-keys the same skill\n * under its promoted `@owner/slug` key. That pull's alias-dedup\n * (`promoteAliasToCanonical`) only runs when the manifest returns 200 \u2014 on a\n * stable manifest the request 304s and the sweep never runs, so the bare twin\n * lingers indefinitely. A lingering twin:\n *   - inflates the tray's \"only on this device\" count (it isn't in a sync kit,\n *     so the loose-skill grouping counts it as un-synced), and\n *   - for a `source:'local'` twin, inflates the upload panel's capturable list\n *     (`source==='local' && !owner`), mislabeling an already-published skill as\n *     \"not backed up\".\n *\n * A bare `slug` entry is a stale twin when an OWNED promoted `@owner/slug`\n * entry with the SAME content hash exists. Requirements, each load-bearing:\n *   - hashes must match \u2014 a diverged local edit (a fork off the published\n *     version) is genuine un-backed-up work and must never be discarded;\n *   - the bare entry must be unowned \u2014 an owned bare entry is not a leftover;\n *   - pinned / customized / held-update entries carry user intent and are kept.\n *\n * Pure and I/O-free: it only rewrites `state.skills` and returns the removed\n * keys so the caller can best-effort drop the now-orphaned content dirs.\n */\nexport function collapsePublishedTwins(state: KitState): { removed: string[] } {\n  const removed: string[] = [];\n  const entries = state.skills;\n\n  // Index owned, promoted (`@owner/slug`) entries by their bare slug tail.\n  const promotedByTail = new Map<string, SkillEntry>();\n  for (const [key, entry] of Object.entries(entries)) {\n    if (!key.startsWith('@') || !entry.owner) continue;\n    const slash = key.indexOf('/');\n    const tail = slash >= 0 ? key.slice(slash + 1) : '';\n    if (tail) promotedByTail.set(tail, entry);\n  }\n\n  for (const [key, entry] of Object.entries(entries)) {\n    if (key.startsWith('@')) continue; // only bare keys can be stale twins\n    if (entry.owner) continue; // an owned bare entry is not a publish leftover\n    if (entry.pinned || entry.customized_from || entry.held_update) continue;\n    const twin = promotedByTail.get(key);\n    if (!twin) continue; // no canonical counterpart \u2014 a genuine local-only skill\n    if (!entry.hash || entry.hash !== twin.hash) continue; // diverged edit \u2014 keep\n    delete entries[key];\n    removed.push(key);\n  }\n\n  return { removed };\n}\n", "import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\n\nexport function sha256(content: string | Buffer): string {\n  return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nexport async function hashFile(filePath: string): Promise<string> {\n  const buf = await readFile(filePath);\n  return sha256(buf);\n}\n\nexport function hashRef(hash: string): string {\n  return `sha256:${hash}`;\n}\n", "/**\n * Minimal TOML serializer/parser scoped to the `skillet.lock` schema only\n * (PROTOCOL \u00A711). Deliberately not a general TOML library \u2014 accepts and\n * emits exactly the shapes the lockfile uses:\n *\n *   - top-level scalars: `key = \"string\"` or `key = <integer>`\n *   - array-of-tables headers: `[[skill]]`\n *   - inline tables: `signature = { alg = \"ed25519\", ... }`\n *\n * Why hand-rolled instead of @iarna/toml:\n *   - No new dependency surface for a single tiny, tightly-controlled schema.\n *   - String values are all URL/hex/base64/RFC3339 \u2014 no escape ambiguity.\n *   - Round-trip is property-tested so any drift fails CI before it ships.\n *\n * Strings are emitted as TOML basic-strings; the encoder REFUSES any value\n * containing a control char, backslash, or quote so we never produce\n * ambiguous output. The parser only accepts basic-strings \u2014 `'literal'`,\n * multi-line, and `0x` numerics are not supported and not needed.\n */\n\nexport type TomlScalar = string | number;\nexport type TomlInlineTable = Record<string, TomlScalar>;\nexport type TomlTopValue = TomlScalar | TomlInlineTable;\n\nexport interface TomlArrayOfTablesDoc {\n  /** Top-level scalars in the order they were emitted/encountered. */\n  top: Record<string, TomlTopValue>;\n  /** Repeated [[name]] tables; preserves order. */\n  tables: Record<string, Array<Record<string, TomlTopValue>>>;\n}\n\n// Refuse to emit anything that would need escaping in a TOML basic-string.\n// Lockfile values are URLs, hex, base64, RFC3339 \u2014 never contain control\n// chars, backslashes, or quotes. Refusing is safer than escaping.\nfunction emitString(v: string): string {\n  for (let i = 0; i < v.length; i++) {\n    const code = v.charCodeAt(i);\n    if (code < 0x20 || code === 0x7f) {\n      throw new Error(\n        `toml-lock: refusing to emit string with control char U+${code.toString(16).padStart(4, \"0\")}`\n      );\n    }\n  }\n  if (v.includes(\"\\\\\") || v.includes('\"')) {\n    throw new Error(\n      `toml-lock: refusing to emit string containing backslash or quote: ${JSON.stringify(v)}`\n    );\n  }\n  return `\"${v}\"`;\n}\n\nfunction emitInteger(v: number): string {\n  if (!Number.isInteger(v)) {\n    throw new Error(`toml-lock: only integers supported, got ${v}`);\n  }\n  return String(v);\n}\n\nfunction emitScalar(v: TomlScalar): string {\n  if (typeof v === \"string\") return emitString(v);\n  if (typeof v === \"number\") return emitInteger(v);\n  throw new Error(`toml-lock: unsupported scalar ${typeof v}`);\n}\n\nfunction emitInlineTable(v: TomlInlineTable): string {\n  const parts = Object.entries(v).map(([k, val]) => `${k} = ${emitScalar(val)}`);\n  return `{ ${parts.join(\", \")} }`;\n}\n\nfunction emitTopValue(v: TomlTopValue): string {\n  if (v !== null && typeof v === \"object\") return emitInlineTable(v);\n  return emitScalar(v);\n}\n\nexport function encodeLockToml(doc: TomlArrayOfTablesDoc): string {\n  const lines: string[] = [];\n  for (const [k, v] of Object.entries(doc.top)) {\n    lines.push(`${k} = ${emitTopValue(v)}`);\n  }\n  for (const [name, entries] of Object.entries(doc.tables)) {\n    for (const entry of entries) {\n      lines.push(\"\");\n      lines.push(`[[${name}]]`);\n      for (const [k, v] of Object.entries(entry)) {\n        lines.push(`${k} = ${emitTopValue(v)}`);\n      }\n    }\n  }\n  return lines.join(\"\\n\") + \"\\n\";\n}\n\n// \u2500\u2500 parser \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction stripComment(line: string): string {\n  // Strings cannot contain unescaped `\"` (see encoder), so we can scan once.\n  let inStr = false;\n  for (let i = 0; i < line.length; i++) {\n    const c = line[i];\n    if (c === '\"') inStr = !inStr;\n    else if (c === \"#\" && !inStr) return line.slice(0, i);\n  }\n  return line;\n}\n\nfunction parseString(token: string): string {\n  if (!token.startsWith('\"') || !token.endsWith('\"') || token.length < 2) {\n    throw new Error(`toml-lock parse: expected basic-string, got ${JSON.stringify(token)}`);\n  }\n  const body = token.slice(1, -1);\n  if (body.includes(\"\\\\\")) {\n    throw new Error(`toml-lock parse: escape sequences not supported in ${JSON.stringify(token)}`);\n  }\n  if (body.includes('\"')) {\n    throw new Error(`toml-lock parse: unescaped quote in ${JSON.stringify(token)}`);\n  }\n  return body;\n}\n\nfunction parseInteger(token: string): number {\n  if (!/^-?\\d+$/.test(token)) {\n    throw new Error(`toml-lock parse: expected integer, got ${JSON.stringify(token)}`);\n  }\n  const n = Number(token);\n  if (!Number.isSafeInteger(n)) {\n    throw new Error(`toml-lock parse: integer ${token} out of safe range`);\n  }\n  return n;\n}\n\nfunction parseScalar(token: string): TomlScalar {\n  const t = token.trim();\n  if (t.startsWith('\"')) return parseString(t);\n  return parseInteger(t);\n}\n\nfunction parseInlineTable(token: string): TomlInlineTable {\n  const t = token.trim();\n  if (!t.startsWith(\"{\") || !t.endsWith(\"}\")) {\n    throw new Error(`toml-lock parse: expected inline table, got ${JSON.stringify(token)}`);\n  }\n  const body = t.slice(1, -1).trim();\n  if (body === \"\") return {};\n\n  // Split on commas that aren't inside strings.\n  const pieces: string[] = [];\n  let cur = \"\";\n  let inStr = false;\n  for (let i = 0; i < body.length; i++) {\n    const c = body[i];\n    if (c === '\"') inStr = !inStr;\n    if (c === \",\" && !inStr) {\n      pieces.push(cur);\n      cur = \"\";\n    } else {\n      cur += c;\n    }\n  }\n  if (cur.trim() !== \"\") pieces.push(cur);\n\n  const out: TomlInlineTable = {};\n  for (const p of pieces) {\n    const eq = p.indexOf(\"=\");\n    if (eq < 0) {\n      throw new Error(`toml-lock parse: malformed inline-table entry ${JSON.stringify(p)}`);\n    }\n    const key = p.slice(0, eq).trim();\n    const val = p.slice(eq + 1).trim();\n    out[key] = parseScalar(val);\n  }\n  return out;\n}\n\nfunction parseValue(token: string): TomlTopValue {\n  const t = token.trim();\n  if (t.startsWith(\"{\")) return parseInlineTable(t);\n  return parseScalar(t);\n}\n\nexport function decodeLockToml(input: string): TomlArrayOfTablesDoc {\n  const doc: TomlArrayOfTablesDoc = { top: {}, tables: {} };\n  let current: Record<string, TomlTopValue> | null = null; // null = top-level\n  let currentName: string | null = null;\n\n  const rawLines = input.split(/\\r?\\n/);\n  for (let lineNo = 0; lineNo < rawLines.length; lineNo++) {\n    const raw = rawLines[lineNo];\n    const line = stripComment(raw).trim();\n    if (line === \"\") continue;\n\n    // Array-of-tables header: [[name]]\n    if (line.startsWith(\"[[\") && line.endsWith(\"]]\")) {\n      const name = line.slice(2, -2).trim();\n      if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(name)) {\n        throw new Error(`toml-lock parse line ${lineNo + 1}: invalid table name ${JSON.stringify(name)}`);\n      }\n      currentName = name;\n      current = {};\n      (doc.tables[name] ??= []).push(current);\n      continue;\n    }\n\n    // Plain `[name]` tables intentionally unsupported \u2014 schema doesn't use them.\n    if (line.startsWith(\"[\")) {\n      throw new Error(`toml-lock parse line ${lineNo + 1}: standard tables not supported (${line})`);\n    }\n\n    // key = value\n    const eq = line.indexOf(\"=\");\n    if (eq < 0) {\n      throw new Error(`toml-lock parse line ${lineNo + 1}: expected \"key = value\", got ${JSON.stringify(line)}`);\n    }\n    const key = line.slice(0, eq).trim();\n    const val = line.slice(eq + 1).trim();\n    if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {\n      throw new Error(`toml-lock parse line ${lineNo + 1}: invalid bare key ${JSON.stringify(key)}`);\n    }\n    const parsed = parseValue(val);\n\n    if (current === null) {\n      if (key in doc.top) {\n        throw new Error(`toml-lock parse line ${lineNo + 1}: duplicate top-level key ${key}`);\n      }\n      doc.top[key] = parsed;\n    } else {\n      if (key in current) {\n        throw new Error(\n          `toml-lock parse line ${lineNo + 1}: duplicate key ${key} in [[${currentName}]]`\n        );\n      }\n      current[key] = parsed;\n    }\n  }\n  return doc;\n}\n", "/**\n * Registry versions published under a verified session (web/desktop).\n */\nimport {\n  SIG_ALG_SESSION,\n  SIG_ALG_ED25519,\n  type Ed25519Signature,\n  type SessionAttestedSignature,\n  type Signature,\n} from \"./envelope.js\";\n\nexport { SIG_ALG_SESSION };\n\nexport function isSessionAttestedSignature(\n  envelope: Signature | null | undefined,\n): envelope is SessionAttestedSignature {\n  return envelope?.alg === SIG_ALG_SESSION;\n}\n\nexport function isEd25519Signature(\n  envelope: Signature | null | undefined,\n): envelope is Ed25519Signature {\n  return envelope?.alg === SIG_ALG_ED25519;\n}\n", "/**\n * CLI-side device-key delegation: minting + client-side chain verification.\n *\n * Two responsibilities, both rooted in the author's PRIMARY key:\n *\n *   1. MINT (CLI, `skillet device approve|revoke`): build a DelegationCert /\n *      RevocationStatement and sign it with the primary key loaded from the\n *      keystore. The primary PRIVATE key never leaves this process \u2014 we only\n *      ever pass it to `signEnvelope` (the same audited primitive used for\n *      publish/propose), never serialize it.\n *\n *   2. VERIFY (client, at sync/materialize): given a device-signed version and\n *      its inline SignedDelegation, re-verify the chain\n *\n *        version.signature \u2190 device_pub \u2190 cert \u2190 cert_sig \u2190 PRIMARY key\n *\n *      where the PRIMARY key is the client's TOFU-PINNED key (signing/pin.ts),\n *      **never** the registry-served one (design \u00A79.4). Fail-closed: any missing,\n *      malformed, out-of-chain, revoked, expired, or out-of-scope link throws.\n *\n * This module introduces NO new crypto: certs/revocations are hashed to a\n * `sha256:<hex>` string by @skillet/protocol and signed/verified through the\n * existing envelope path. The wire shapes + canonicalization + hashing are\n * imported from @skillet/protocol so the bytes the CLI signs are byte-identical\n * to the bytes the registry and client verify (design \u00A79.6 / \u00A79.7).\n */\n\nimport { randomBytes, type KeyObject } from \"node:crypto\";\nimport {\n  type DelegationCert,\n  type SignedDelegation,\n  type RevocationStatement,\n  type SignedRevocation,\n  type DelegationScope,\n  DELEGATION_CERT_VERSION,\n  DELEGATION_CERT_TYP,\n  DELEGATION_REVOCATION_TYP,\n  DELEGABLE_SCOPES,\n  DEFAULT_DELEGATION_TTL_SEC,\n  MAX_DELEGATION_TTL_SEC,\n  delegationCertHash,\n  revocationHash,\n  validateDelegationCert,\n} from \"@skillet/protocol\";\nimport {\n  signEnvelope,\n  verifyEnvelope,\n  type Ed25519Signature,\n  type Signature,\n} from \"./envelope.js\";\nimport { publicKeyFromBase64 } from \"./pin.js\";\nimport { type AuthorKey } from \"./index.js\";\n\nconst ED25519_RAW_PUB_BYTES = 32;\nconst KEY_ID_RE = /^[0-9a-f]{64}$/;\n\n/**\n * Fail-closed error for the delegation chain. Carries a machine-readable code so\n * callers (pull, materialize, CLI) can map it the same way they map\n * {@link SignatureError}. A device-signed version that hits ANY of these MUST\n * NOT be materialized (design \u00A79.3).\n */\nexport type DelegationErrorCode =\n  | \"delegation_missing\" // device-keyed version with no inline cert (T9 downgrade)\n  | \"delegation_revoked\" // device key appears in the author's revocation set\n  | \"delegation_expired\" // version published outside the cert's signed validity window\n  | \"delegation_scope_denied\" // cert not authorized for the required action\n  | \"delegation_invalid\"; // cert shape/policy/binding failure\n\nexport class DelegationError extends Error {\n  readonly code: DelegationErrorCode;\n  constructor(code: DelegationErrorCode, message: string) {\n    super(`${code}: ${message}`);\n    this.name = \"DelegationError\";\n    this.code = code;\n  }\n}\n\n// \u2500\u2500 minting (CLI, primary-key-resident) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Validate + normalize a base64 raw-32-byte device pubkey \u2192 its hex key id. */\nexport function deviceKeyIdFromPub(devicePubB64: string): string {\n  const raw = Buffer.from(devicePubB64, \"base64\");\n  // Buffer.from(base64) is lenient (ignores junk); round-trip to reject\n  // anything that does not re-encode to the exact same string.\n  if (raw.toString(\"base64\") !== devicePubB64) {\n    throw new DelegationError(\"delegation_invalid\", \"device_pub is not valid base64\");\n  }\n  if (raw.length !== ED25519_RAW_PUB_BYTES) {\n    throw new DelegationError(\n      \"delegation_invalid\",\n      `device_pub must decode to ${ED25519_RAW_PUB_BYTES} bytes, got ${raw.length}`,\n    );\n  }\n  return raw.toString(\"hex\");\n}\n\nexport interface MintDelegationOptions {\n  /** Primary author key WITH its private half (from the keystore). */\n  primaryKey: AuthorKey;\n  /** The author's registry handle \u2014 bound into the cert (design \u00A71.1, T6). */\n  handle: string;\n  /** Base64 raw 32-byte Ed25519 public key presented by the device/browser. */\n  devicePubB64: string;\n  /** Subset of {propose,approve}. Defaults to BOTH (design \u00A74.1). */\n  scopes?: DelegationScope[];\n  /** Lifetime in seconds. Defaults to 90d; hard-capped at MAX_DELEGATION_TTL_SEC. */\n  ttlSec?: number;\n  /** Optional human label echoed by `skillet device list`. */\n  label?: string;\n  /** Injectable clock (unix seconds) for deterministic tests. */\n  now?: number;\n}\n\n/**\n * Mints + signs a DelegationCert with the primary key. The returned\n * {@link SignedDelegation} is what `skillet device approve` POSTs to\n * `/api/v1/delegations`. `label` is returned alongside (the wire body carries\n * it as a sibling field, not inside the signed cert).\n */\nexport function mintDelegation(opts: MintDelegationOptions): {\n  signed: SignedDelegation;\n  label?: string;\n} {\n  if (!opts.primaryKey.privateKey) {\n    throw new DelegationError(\n      \"delegation_invalid\",\n      \"minting a delegation requires the primary private key (keystore key)\",\n    );\n  }\n  if (!KEY_ID_RE.test(opts.primaryKey.keyId)) {\n    throw new DelegationError(\"delegation_invalid\", \"primary key id is not 64-char hex\");\n  }\n  if (typeof opts.handle !== \"string\" || opts.handle.length === 0) {\n    throw new DelegationError(\"delegation_invalid\", \"handle must be a non-empty string\");\n  }\n\n  const deviceKeyId = deviceKeyIdFromPub(opts.devicePubB64);\n  const scopes = opts.scopes ?? [...DELEGABLE_SCOPES];\n  if (scopes.length === 0) {\n    throw new DelegationError(\"delegation_scope_denied\", \"scopes must be non-empty\");\n  }\n  for (const s of scopes) {\n    if (!(DELEGABLE_SCOPES as readonly string[]).includes(s)) {\n      throw new DelegationError(\n        \"delegation_scope_denied\",\n        `scope ${JSON.stringify(s)} is not delegable; allowed: ${DELEGABLE_SCOPES.join(\", \")}`,\n      );\n    }\n  }\n\n  const issuedAt = opts.now ?? Math.floor(Date.now() / 1000);\n  const requestedTtl = opts.ttlSec ?? DEFAULT_DELEGATION_TTL_SEC;\n  if (!Number.isInteger(requestedTtl) || requestedTtl <= 0) {\n    throw new DelegationError(\"delegation_invalid\", \"ttlSec must be a positive integer\");\n  }\n  const ttl = Math.min(requestedTtl, MAX_DELEGATION_TTL_SEC);\n\n  const cert: DelegationCert = {\n    v: DELEGATION_CERT_VERSION,\n    typ: DELEGATION_CERT_TYP,\n    author_key_id: opts.primaryKey.keyId,\n    handle: opts.handle,\n    device_key_id: deviceKeyId,\n    device_pub: opts.devicePubB64,\n    scopes,\n    issued_at: issuedAt,\n    expires_at: issuedAt + ttl,\n    nonce: randomBytes(16).toString(\"hex\"),\n  };\n\n  // Defense-in-depth: never sign a cert that would not validate on the registry.\n  const shape = validateDelegationCert(cert);\n  if (!(\"ok\" in shape)) {\n    throw new DelegationError(\"delegation_invalid\", `minted cert failed validation: ${shape.message}`);\n  }\n\n  const certHash = delegationCertHash(cert);\n  const cert_sig: Signature = signEnvelope(certHash, opts.primaryKey);\n\n  return {\n    signed: { cert, cert_sig },\n    ...(opts.label ? { label: opts.label } : {}),\n  };\n}\n\nexport interface MintRevocationOptions {\n  primaryKey: AuthorKey;\n  /** Hex id (== hex(device_pub)) of the device key being revoked. */\n  deviceKeyId: string;\n  now?: number;\n}\n\n/**\n * Mints + signs a RevocationStatement with the primary key. This is what\n * `skillet device revoke` POSTs to `/api/v1/delegations/:id/revoke`. Only the\n * primary key can authorize a trust-chain state change (design \u00A73).\n */\nexport function mintRevocation(opts: MintRevocationOptions): SignedRevocation {\n  if (!opts.primaryKey.privateKey) {\n    throw new DelegationError(\n      \"delegation_invalid\",\n      \"minting a revocation requires the primary private key (keystore key)\",\n    );\n  }\n  if (!KEY_ID_RE.test(opts.deviceKeyId)) {\n    throw new DelegationError(\"delegation_invalid\", \"device_key_id must be 64-char lowercase hex\");\n  }\n\n  const revocation: RevocationStatement = {\n    v: DELEGATION_CERT_VERSION,\n    typ: DELEGATION_REVOCATION_TYP,\n    author_key_id: opts.primaryKey.keyId,\n    device_key_id: opts.deviceKeyId,\n    revoked_at: opts.now ?? Math.floor(Date.now() / 1000),\n    nonce: randomBytes(16).toString(\"hex\"),\n  };\n\n  const revHash = revocationHash(revocation);\n  const revocation_sig: Signature = signEnvelope(revHash, opts.primaryKey);\n  return { revocation, revocation_sig };\n}\n\n// \u2500\u2500 client-side chain verification (TOFU-pinned primary is the root) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Verifies a SignedDelegation's cert against the PINNED primary key \u2014 i.e. that\n * the cert was genuinely signed by `pinnedPrimary` and binds to it. Does NOT\n * verify any version/proposal signature; that's the caller's next step.\n *\n * Throws {@link DelegationError}/{@link SignatureError} (fail-closed) on any\n * shape, binding, or signature failure.\n */\nexport function verifyDelegationCert(\n  signed: SignedDelegation,\n  pinnedPrimary: { keyId: string; pub: string },\n): DelegationCert {\n  if (!signed || typeof signed !== \"object\" || !signed.cert || !signed.cert_sig) {\n    throw new DelegationError(\"delegation_invalid\", \"signed delegation missing cert/cert_sig\");\n  }\n  const shape = validateDelegationCert(signed.cert);\n  if (!(\"ok\" in shape)) {\n    throw new DelegationError(\"delegation_invalid\", `delegation cert invalid: ${shape.message}`);\n  }\n  const cert = shape.cert;\n\n  // The cert must bind to, and be signed by, the TOFU-pinned primary key \u2014 not\n  // any key the registry happens to serve (design \u00A79.1/\u00A79.4, T1).\n  if (cert.author_key_id !== pinnedPrimary.keyId) {\n    throw new DelegationError(\n      \"delegation_invalid\",\n      `delegation cert author_key_id ${cert.author_key_id} does not match pinned primary ${pinnedPrimary.keyId}`,\n    );\n  }\n  if (signed.cert_sig.key_id !== pinnedPrimary.keyId) {\n    throw new DelegationError(\n      \"delegation_invalid\",\n      `delegation cert_sig key_id ${signed.cert_sig.key_id} is not the pinned primary key`,\n    );\n  }\n\n  // Recompute the hash from the cert and verify cert_sig against the pinned\n  // primary public key. verifyEnvelope throws on any failure.\n  const certHash = delegationCertHash(cert);\n  const primaryPub: KeyObject = publicKeyFromBase64(pinnedPrimary.pub);\n  verifyEnvelope(certHash, signed.cert_sig, primaryPub, {\n    expectedKeyId: pinnedPrimary.keyId,\n  });\n\n  return cert;\n}\n\nexport interface VerifyDelegatedVersionOptions {\n  /** Canonical `sha256:<hex>` content hash that `versionSignature` covers. */\n  contentHash: string;\n  /** The version's signature envelope (key_id is the DEVICE key id here). */\n  versionSignature: Ed25519Signature;\n  /** The inline SignedDelegation served with the version / pinned in the lockfile. */\n  signedDelegation: SignedDelegation | null | undefined;\n  /** The client's TOFU-pinned primary key for this author (the trust root). */\n  pinnedPrimary: { keyId: string; pub: string };\n  /** The author handle the version belongs to \u2014 must equal cert.handle (T6). */\n  handle: string;\n  /** Action scope to require in the cert. Minted versions are owner-signed \u21D2 'approve'. */\n  requiredScope: DelegationScope;\n  /**\n   * Unix-seconds timestamp the version was published. The cert MUST have been\n   * valid at this instant (design \u00A75: a cert valid when a version was minted\n   * keeps that version valid). Falls back to `now` if omitted (stricter).\n   */\n  publishedAt?: number;\n  /**\n   * Device key ids the author has revoked (pulled on sync). If the version's\n   * device key is in this set, the version is refused (design \u00A73.4 / AC#3).\n   */\n  revokedDeviceKeyIds?: Iterable<string>;\n  now?: number;\n}\n\n/**\n * Full client-side chain verification for a DEVICE-signed version (design \u00A71.3).\n * Call this ONLY when `versionSignature.key_id` is not the primary key id.\n *\n * Order (all fail-closed):\n *   1. inline delegation present                      \u2192 else delegation_missing\n *   2. cert validates + chains to pinned primary      \u2192 verifyDelegationCert\n *   3. version sig key_id == cert.device_key_id       \u2192 binds version\u2194cert\n *   4. cert.handle == handle                          \u2192 T6\n *   5. device key not revoked                          \u2192 delegation_revoked\n *   6. publishedAt within [issued_at, expires_at]      \u2192 delegation_expired\n *   7. requiredScope \u2208 cert.scopes                     \u2192 delegation_scope_denied\n *   8. version sig verifies against cert.device_pub    \u2192 SignatureError\n *\n * On success returns the verified device key id. Throws otherwise \u2014 the caller\n * MUST treat any throw as a hard stop and refuse materialization.\n */\nexport function verifyDelegatedVersionSignature(\n  opts: VerifyDelegatedVersionOptions,\n): { deviceKeyId: string; via: \"delegation\" } {\n  if (!opts.signedDelegation) {\n    throw new DelegationError(\n      \"delegation_missing\",\n      \"version is signed by a device key but carries no delegation cert \u2014 refusing (no downgrade)\",\n    );\n  }\n\n  // 2 \u2014 cert validates and chains to the pinned primary (the trust root).\n  const cert = verifyDelegationCert(opts.signedDelegation, opts.pinnedPrimary);\n\n  // 3 \u2014 the version signature's key_id must be exactly the delegated device key.\n  if (opts.versionSignature.key_id !== cert.device_key_id) {\n    throw new DelegationError(\n      \"delegation_invalid\",\n      `version signed by ${opts.versionSignature.key_id} but delegation is for device ${cert.device_key_id}`,\n    );\n  }\n\n  // 4 \u2014 handle binding.\n  if (cert.handle !== opts.handle) {\n    throw new DelegationError(\n      \"delegation_invalid\",\n      `delegation cert handle ${JSON.stringify(cert.handle)} does not match author ${JSON.stringify(opts.handle)}`,\n    );\n  }\n\n  // 5 \u2014 revocation honoring (negative info pulled on sync).\n  if (opts.revokedDeviceKeyIds) {\n    const revoked =\n      opts.revokedDeviceKeyIds instanceof Set\n        ? opts.revokedDeviceKeyIds\n        : new Set(opts.revokedDeviceKeyIds);\n    if (revoked.has(cert.device_key_id)) {\n      throw new DelegationError(\n        \"delegation_revoked\",\n        `device key ${cert.device_key_id} has been revoked by the author`,\n      );\n    }\n  }\n\n  // 6 \u2014 the cert must have been valid at publish time (design \u00A75).\n  const at = opts.publishedAt ?? opts.now ?? Math.floor(Date.now() / 1000);\n  if (at < cert.issued_at || at > cert.expires_at) {\n    throw new DelegationError(\n      \"delegation_expired\",\n      `version published at ${at} is outside the cert validity window [${cert.issued_at}, ${cert.expires_at}]`,\n    );\n  }\n\n  // 7 \u2014 scope gate.\n  if (!cert.scopes.includes(opts.requiredScope)) {\n    throw new DelegationError(\n      \"delegation_scope_denied\",\n      `device key is not authorized for ${opts.requiredScope} (scopes: ${cert.scopes.join(\", \")})`,\n    );\n  }\n\n  // 8 \u2014 finally, verify the version signature against the device pub taken ONLY\n  // from inside the now-verified cert (never an unsigned column) \u2014 design \u00A79.2.\n  const devicePub = publicKeyFromBase64(cert.device_pub);\n  verifyEnvelope(opts.contentHash, opts.versionSignature, devicePub, {\n    expectedKeyId: cert.device_key_id,\n  });\n\n  return { deviceKeyId: cert.device_key_id, via: \"delegation\" };\n}\n", "/**\n * skillet.lock \u2014 committed, reproducible, CI-verifiable skill manifest.\n *\n * PROTOCOL \u00A711 shape (TOML):\n *\n *   registry      = \"https://registry.skillet.md\"   # REQUIRED \u2014 pins the resolver\n *   generated_at  = \"2026-06-13T17:42:00.000Z\"\n *\n *   [[skill]]\n *   ref          = \"@taylor/festival-ops\"\n *   version      = 7\n *   content_hash = \"sha256:...\"\n *   author_key   = \"<64-hex>\"                    # pins the TOFU hole shut on fresh clones\n *   source       = \"registry\"\n *   registry_url = \"https://...\"                 # optional, when different from top-level\n *   signature    = { alg = \"ed25519\", key_id = \"...\", sig = \"...\" }\n *\n * Why the lockfile shape carries `author_key` AND `signature`:\n *   - `author_key` is what CI verifies a fresh fetch against (closes TOFU\n *     for clones \u2014 see acceptance criterion 5).\n *   - `signature` is the envelope produced at publish time and the proof\n *     CI checks against the pinned `author_key`. Without it, a fresh fetch\n *     could swap in a malicious version that still hashes correctly under\n *     a different \u2014 but registry-served \u2014 author key.\n *\n * Why we switched from JSON to TOML:\n *   - PROTOCOL \u00A711 normative shape.\n *   - Human-diffable; reviewers can audit a skill bump in code review.\n *   - The schema is fixed and tiny, so `util/toml-lock.ts` covers it without\n *     a third-party dep.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { atomicWrite } from \"./util/atomic.js\";\nimport { hashRef, sha256 } from \"./util/hash.js\";\nimport {\n  decodeLockToml,\n  encodeLockToml,\n  type TomlArrayOfTablesDoc,\n  type TomlInlineTable,\n} from \"./util/toml-lock.js\";\nimport { verifyEnvelope, type Signature } from \"./signing/envelope.js\";\nimport { isEd25519Signature, isSessionAttestedSignature } from \"./signing/session-attest.js\";\nimport { publicKeyFromBase64 } from \"./signing/pin.js\";\nimport { verifyDelegationCert } from \"./signing/delegation.js\";\nimport { validateDelegationCert, type SignedDelegation, ARTIFACT_SCHEMA_VERSION, resolveArtifactSchemaVersion } from \"@skillet/protocol\";\nimport type { KitState } from \"./kit/types.js\";\nimport { REGISTRY_URL_DEFAULT } from \"./kit/types.js\";\n\nexport interface LockEntry {\n  ref: string;\n  version: number;\n  /**\n   * Semver display label (\"X.Y.Z\") for `version`. Display only \u2014 CI and sync\n   * verify against `version`/`content_hash`, never this. Absent for local-only\n   * skills and entries written before the registry served labels.\n   */\n  version_label?: string;\n  /** sha256-prefixed canonical content hash (PROTOCOL \u00A72.2) */\n  content_hash: string;\n  /** 64-hex Ed25519 public key ID \u2014 REQUIRED for registry skills, omitted for local-only */\n  author_key?: string;\n  source: \"local\" | \"registry\";\n  registry_url?: string;\n  signature?: Signature;\n  /**\n   * When `signature` was produced by a delegated DEVICE key (its\n   * key_id is not `author_key`), the inline SignedDelegation that chains the\n   * device key to the pinned PRIMARY author key. Lets a fresh clone / CI verify\n   * device_sig \u2190 cert \u2190 pinned primary fully offline. Stored as a JSON string\n   * (`delegation_json`) in the TOML so the nested cert needs no inline-table\n   * gymnastics; the signed bytes are recomputed from the parsed cert.\n   */\n  delegation?: SignedDelegation;\n}\n\nexport interface LockFile {\n  /** Wire-format version for skillet.lock. */\n  schema_version: number;\n  /** REQUIRED \u2014 pins the resolver explicitly so the lockfile is self-contained. */\n  registry: string;\n  generated_at: string;\n  skills: LockEntry[];\n}\n\nconst LOCK_FILENAME = \"skillet.lock\";\n\n// \u2500\u2500 encode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction encodeEntry(entry: LockEntry): Record<string, string | number | TomlInlineTable> {\n  const out: Record<string, string | number | TomlInlineTable> = {\n    ref: entry.ref,\n    version: entry.version,\n    content_hash: entry.content_hash,\n  };\n  if (entry.version_label) out.version_label = entry.version_label;\n  if (entry.author_key) out.author_key = entry.author_key;\n  out.source = entry.source;\n  if (entry.registry_url) out.registry_url = entry.registry_url;\n  if (entry.signature) {\n    out.signature = {\n      alg: entry.signature.alg,\n      key_id: entry.signature.key_id,\n      sig: entry.signature.sig,\n    };\n  }\n  if (entry.delegation) {\n    // base64 of the SignedDelegation JSON. The minimal TOML encoder rejects\n    // basic strings containing quotes/backslashes (which a JSON blob is full\n    // of), so we store the chain as a quote-free base64 field. The signed bytes\n    // are recomputed from the parsed cert at verify time, so the wrapper's\n    // exact byte form is not security-sensitive.\n    out.delegation_b64 = Buffer.from(JSON.stringify(entry.delegation), \"utf8\").toString(\"base64\");\n  }\n  return out;\n}\n\nexport function encodeLockFile(lock: LockFile): string {\n  const doc: TomlArrayOfTablesDoc = {\n    top: {\n      schema_version: lock.schema_version,\n      registry: lock.registry,\n      generated_at: lock.generated_at,\n    },\n    tables: {\n      skill: lock.skills.map(encodeEntry),\n    },\n  };\n  return encodeLockToml(doc);\n}\n\n// \u2500\u2500 write \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Builds a LockFile from current KitState. Each registry-sourced skill MUST\n * supply `content_hash`, `author_key`, and (if present) `signature` for CI\n * verifiability \u2014 local-only skills carry just the hash.\n */\nexport function buildLockFile(\n  state: KitState,\n  opts: {\n    registry?: string;\n    /** Per-slug overrides for signature / author_key as they arrive from\n     *  the registry response or manifest. KitState today doesn't carry\n     *  signatures; this is the seam registry-side work plugs into. */\n    overrides?: Record<\n      string,\n      Partial<Pick<LockEntry, \"content_hash\" | \"author_key\" | \"signature\" | \"registry_url\" | \"delegation\">>\n    >;\n    now?: () => Date;\n  } = {}\n): LockFile {\n  const registry = opts.registry ?? REGISTRY_URL_DEFAULT;\n  const now = opts.now ?? (() => new Date());\n\n  const skills: LockEntry[] = [];\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    const override = opts.overrides?.[slug] ?? {};\n    const baseHash = override.content_hash ?? hashRef(entry.hash);\n    const base: LockEntry = {\n      ref: slug,\n      version: entry.version,\n      content_hash: baseHash,\n      source: entry.source,\n    };\n    if (entry.versionLabel) base.version_label = entry.versionLabel;\n    if (entry.authorKeyId || override.author_key) {\n      base.author_key = override.author_key ?? entry.authorKeyId;\n    }\n    if (entry.registryUrl || override.registry_url) {\n      base.registry_url = override.registry_url ?? entry.registryUrl;\n    }\n    if (override.signature) base.signature = override.signature;\n    // Carry the inline delegation for device-signed versions so a fresh clone\n    // can verify the chain offline (override seam, mirrors `signature`).\n    const delegation = override.delegation ?? entry.delegation;\n    if (delegation) base.delegation = delegation;\n    skills.push(base);\n  }\n\n  return {\n    schema_version: ARTIFACT_SCHEMA_VERSION,\n    registry,\n    generated_at: now().toISOString(),\n    skills,\n  };\n}\n\nexport async function writeLockFile(\n  cwd: string,\n  state: KitState,\n  registryUrl: string = REGISTRY_URL_DEFAULT,\n  overrides?: Record<\n    string,\n    Partial<Pick<LockEntry, \"content_hash\" | \"author_key\" | \"signature\" | \"registry_url\">>\n  >\n): Promise<string> {\n  const lockPath = join(cwd, LOCK_FILENAME);\n  const lock = buildLockFile(state, { registry: registryUrl, overrides });\n  await atomicWrite(lockPath, encodeLockFile(lock), { backup: false });\n  return lockPath;\n}\n\n// \u2500\u2500 decode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction decodeEntry(raw: Record<string, unknown>, idx: number): LockEntry {\n  const need = (k: string): unknown => {\n    if (!(k in raw)) {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} missing required key ${k}`);\n    }\n    return raw[k];\n  };\n  const ref = need(\"ref\");\n  const version = need(\"version\");\n  const content_hash = need(\"content_hash\");\n  const source = need(\"source\");\n\n  if (typeof ref !== \"string\") throw new Error(`skillet.lock: [[skill]] #${idx + 1} ref must be string`);\n  if (typeof version !== \"number\") throw new Error(`skillet.lock: [[skill]] #${idx + 1} version must be integer`);\n  if (typeof content_hash !== \"string\") throw new Error(`skillet.lock: [[skill]] #${idx + 1} content_hash must be string`);\n  if (source !== \"local\" && source !== \"registry\") {\n    throw new Error(`skillet.lock: [[skill]] #${idx + 1} source must be \"local\" or \"registry\", got ${JSON.stringify(source)}`);\n  }\n\n  const entry: LockEntry = { ref, version, content_hash, source };\n\n  if (raw.version_label !== undefined) {\n    if (typeof raw.version_label !== \"string\") {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} version_label must be string`);\n    }\n    entry.version_label = raw.version_label;\n  }\n  if (raw.author_key !== undefined) {\n    if (typeof raw.author_key !== \"string\") {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} author_key must be string`);\n    }\n    entry.author_key = raw.author_key;\n  }\n  if (raw.registry_url !== undefined) {\n    if (typeof raw.registry_url !== \"string\") {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} registry_url must be string`);\n    }\n    entry.registry_url = raw.registry_url;\n  }\n  if (raw.signature !== undefined) {\n    const s = raw.signature as Record<string, unknown>;\n    if (!s || typeof s !== \"object\" || s.alg !== \"ed25519\" || typeof s.key_id !== \"string\" || typeof s.sig !== \"string\") {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} signature has invalid shape`);\n    }\n    entry.signature = { alg: \"ed25519\", key_id: s.key_id, sig: s.sig };\n  }\n  if (raw.delegation_b64 !== undefined) {\n    if (typeof raw.delegation_b64 !== \"string\") {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} delegation_b64 must be a base64 string`);\n    }\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(Buffer.from(raw.delegation_b64, \"base64\").toString(\"utf8\"));\n    } catch {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} delegation_b64 is not valid base64 JSON`);\n    }\n    const d = parsed as Record<string, unknown>;\n    if (!d || typeof d !== \"object\" || !d.cert || !d.cert_sig) {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} delegation_json missing cert/cert_sig`);\n    }\n    const shape = validateDelegationCert(d.cert);\n    if (!(\"ok\" in shape)) {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} delegation cert invalid: ${shape.message}`);\n    }\n    const cs = d.cert_sig as Record<string, unknown>;\n    if (cs.alg !== \"ed25519\" || typeof cs.key_id !== \"string\" || typeof cs.sig !== \"string\") {\n      throw new Error(`skillet.lock: [[skill]] #${idx + 1} delegation cert_sig has invalid shape`);\n    }\n    entry.delegation = {\n      cert: shape.cert,\n      cert_sig: { alg: \"ed25519\", key_id: cs.key_id, sig: cs.sig },\n    };\n  }\n\n  return entry;\n}\n\nexport function decodeLockFile(input: string): LockFile {\n  const doc = decodeLockToml(input);\n  const schema_version = resolveArtifactSchemaVersion(\n    doc.top.schema_version,\n    'skillet.lock',\n  );\n  const registry = doc.top.registry;\n  if (typeof registry !== \"string\" || registry === \"\") {\n    throw new Error(\"skillet.lock: top-level `registry` is required (PROTOCOL \u00A711)\");\n  }\n  const generated_at = doc.top.generated_at;\n  if (typeof generated_at !== \"string\") {\n    throw new Error(\"skillet.lock: top-level `generated_at` must be a string\");\n  }\n  const skillTables = doc.tables.skill ?? [];\n  const skills = skillTables.map((t, i) =>\n    decodeEntry(t as Record<string, unknown>, i)\n  );\n  return { schema_version, registry, generated_at, skills };\n}\n\nexport async function readLockFile(cwd: string): Promise<LockFile> {\n  const lockPath = join(cwd, LOCK_FILENAME);\n  const raw = await readFile(lockPath, \"utf8\");\n  return decodeLockFile(raw);\n}\n\n// \u2500\u2500 verify (CI-side; acceptance criterion 5) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface LockVerificationFinding {\n  ref: string;\n  ok: boolean;\n  reason?: string;\n}\n\n/**\n * Verifies a candidate bundle for a single locked skill.\n *\n * Semantics (CI / `skillet sync` against a lockfile):\n *   - Recompute the canonical content hash from `bundleBytes` and compare to\n *     the lockfile's pinned `content_hash`. Mismatch \u2192 `integrity_failed`.\n *   - Verify the lockfile's `signature` envelope against the pinned\n *     `author_key` (NOT against whatever the registry happens to serve right\n *     now). This is what closes the TOFU hole for fresh clones \u2014 a poisoned\n *     first fetch fails here, not silently pins a new key.\n *\n * `bundleHasher` lets callers plug in the canonical bundle hash without a\n * breaking change. Default is the v0 single-string hash so existing call\n * sites keep working until that subtask lands.\n */\nexport function verifyLockedSkill(\n  entry: LockEntry,\n  bundleBytes: Buffer,\n  opts: { bundleHasher?: (b: Buffer) => string } = {}\n): LockVerificationFinding {\n  if (entry.source === \"local\") {\n    // Local skills are not signed; only the hash anchors integrity.\n    const recomputed = (opts.bundleHasher ?? defaultHasher)(bundleBytes);\n    if (recomputed !== entry.content_hash) {\n      return {\n        ref: entry.ref,\n        ok: false,\n        reason: `integrity_failed: hash ${recomputed} does not match lockfile ${entry.content_hash}`,\n      };\n    }\n    return { ref: entry.ref, ok: true };\n  }\n\n  if (!entry.author_key) {\n    return {\n      ref: entry.ref,\n      ok: false,\n      reason:\n        \"lock_missing_author_key: registry-sourced skill must pin author_key (PROTOCOL \u00A711)\",\n    };\n  }\n  if (!entry.signature) {\n    return {\n      ref: entry.ref,\n      ok: false,\n      reason:\n        \"lock_missing_signature: registry-sourced skill must carry a signature envelope\",\n    };\n  }\n\n  const recomputed = (opts.bundleHasher ?? defaultHasher)(bundleBytes);\n  if (recomputed !== entry.content_hash) {\n    return {\n      ref: entry.ref,\n      ok: false,\n      reason: `integrity_failed: hash ${recomputed} does not match lockfile ${entry.content_hash}`,\n    };\n  }\n\n  // Resolve the pinned key from the lockfile (NOT from the registry). The\n  // lockfile carries the author_key id only; we need the actual pubkey bytes.\n  // Convention: when the registry serves a version it also returns the\n  // base64 pubkey alongside the signature. CI MUST take that pubkey, compute\n  // its key_id, and confirm key_id === entry.author_key BEFORE calling this.\n  // For pure-hash use we still expose a sig-less verification path.\n  return { ref: entry.ref, ok: true, reason: \"verify_pubkey_externally\" };\n}\n\n/**\n * The other half of CI verification: given the pinned author_key id, the\n * server-served public key bytes, and the bundle's locked signature, verify.\n *\n * Split from `verifyLockedSkill` because the public-key bytes live outside\n * the lockfile (the lockfile pins the *identifier*, not the key material \u2014\n * matches PROTOCOL \u00A711). CI fetches the pubkey from the registry's\n * `author_key_id` claim record and confirms `key_id === pinned`.\n */\nexport function verifyLockedSignature(\n  entry: LockEntry,\n  bundleBytes: Buffer,\n  servedPublicKeyB64: string,\n  opts: { bundleHasher?: (b: Buffer) => string } = {}\n): LockVerificationFinding {\n  const baseline = verifyLockedSkill(entry, bundleBytes, opts);\n  if (!baseline.ok || entry.source !== \"registry\") return baseline;\n\n  // Confirm the served pubkey actually corresponds to the pinned key_id.\n  const pubKey = publicKeyFromBase64(servedPublicKeyB64);\n  const jwk = pubKey.export({ format: \"jwk\" }) as { x: string };\n  const derivedKeyId = Buffer.from(jwk.x, \"base64url\").toString(\"hex\");\n  if (derivedKeyId !== entry.author_key) {\n    return {\n      ref: entry.ref,\n      ok: false,\n      reason: `key_id_mismatch: registry pubkey id ${derivedKeyId} does not match lockfile-pinned ${entry.author_key}`,\n    };\n  }\n\n  const sig = entry.signature as Signature;\n  if (isSessionAttestedSignature(sig)) {\n    return {\n      ref: entry.ref,\n      ok: false,\n      reason:\n        'session_attest_unverified: lockfile/CI requires an Ed25519 author signature; session-attested skills need interactive approval',\n    };\n  }\n  if (!isEd25519Signature(sig)) {\n    return {\n      ref: entry.ref,\n      ok: false,\n      reason: `signature_invalid: unsupported lockfile signature alg ${JSON.stringify((entry.signature as Signature).alg)}`,\n    };\n  }\n  try {\n    if (sig.key_id === entry.author_key) {\n      // Direct: the version was signed by the primary key itself.\n      verifyEnvelope(entry.content_hash, sig, pubKey, { expectedKeyId: entry.author_key });\n    } else {\n      // Delegated path: the version was signed by a DEVICE key. Verify\n      // the full chain offline against the pinned PRIMARY (servedPublicKeyB64,\n      // already confirmed to match entry.author_key above). Expiry/revocation\n      // are pin-time/sync-time gates (design \u00A73.5); a version already content-\n      // addressed-pinned in the lockfile is not retroactively unwound here \u2014 we\n      // re-prove only that the chain roots in the pinned primary.\n      if (!entry.delegation) {\n        return {\n          ref: entry.ref,\n          ok: false,\n          reason:\n            \"lock_missing_delegation: device-signed registry skill must carry an inline delegation\",\n        };\n      }\n      const cert = verifyDelegationCert(entry.delegation, {\n        keyId: entry.author_key,\n        pub: servedPublicKeyB64,\n      });\n      if (sig.key_id !== cert.device_key_id) {\n        return {\n          ref: entry.ref,\n          ok: false,\n          reason: `key_id_mismatch: lockfile signature key_id ${sig.key_id} is not the delegated device ${cert.device_key_id}`,\n        };\n      }\n      const refHandle = handleFromRef(entry.ref);\n      if (refHandle && cert.handle !== refHandle) {\n        return {\n          ref: entry.ref,\n          ok: false,\n          reason: `delegation_handle_mismatch: cert handle ${JSON.stringify(cert.handle)} does not match ref ${JSON.stringify(refHandle)}`,\n        };\n      }\n      verifyEnvelope(entry.content_hash, sig, publicKeyFromBase64(cert.device_pub), {\n        expectedKeyId: cert.device_key_id,\n      });\n    }\n  } catch (err) {\n    return {\n      ref: entry.ref,\n      ok: false,\n      reason: (err as Error).message,\n    };\n  }\n\n  return { ref: entry.ref, ok: true };\n}\n\n/** Extracts the author handle from a `@handle/slug` (or `handle/slug`) ref. */\nfunction handleFromRef(ref: string): string | null {\n  const m = ref.match(/^@?([a-z0-9-]+)\\//);\n  return m ? m[1] : null;\n}\n\n/** Default content hasher \u2014 single-buffer sha256. This will be replaced\n *  with the canonical multi-file bundle hash without touching the envelope. */\nfunction defaultHasher(bundle: Buffer): string {\n  return hashRef(sha256(bundle));\n}\n\nexport const LOCK_FILENAME_CONST = LOCK_FILENAME;\n", "/**\n * Graded diff engine for skill content review.\n *\n * Computes unified line-level diffs over materialized content (decoded file buffers,\n * not transport bundles). Color output is opt-in so callers can decide based on TTY.\n *\n * Security invariant: diffs are always computed over the content that will be\n * materialized to disk, never over compressed/encoded transport envelopes.\n */\n\nconst CONTEXT = 3;\n\nconst R = \"\\x1b[31m\";\nconst G = \"\\x1b[32m\";\nconst C = \"\\x1b[36m\";\nconst Z = \"\\x1b[0m\";\n\ntype Op = { t: \"=\" | \"+\" | \"-\"; s: string };\n\nfunction lineDiff(a: string[], b: string[]): Op[] {\n  const m = a.length;\n  const n = b.length;\n\n  // dp[i][j] = LCS length of a[0..i-1] and b[0..j-1]\n  const dp: number[][] = Array.from({ length: m + 1 }, () =>\n    new Array<number>(n + 1).fill(0)\n  );\n  for (let i = 1; i <= m; i++) {\n    for (let j = 1; j <= n; j++) {\n      dp[i][j] =\n        a[i - 1] === b[j - 1]\n          ? dp[i - 1][j - 1] + 1\n          : Math.max(dp[i - 1][j], dp[i][j - 1]);\n    }\n  }\n\n  const ops: Op[] = [];\n  let i = m,\n    j = n;\n  while (i > 0 || j > 0) {\n    if (i > 0 && j > 0 && a[i - 1] === b[j - 1]) {\n      ops.push({ t: \"=\", s: a[i - 1] });\n      i--;\n      j--;\n    } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {\n      ops.push({ t: \"+\", s: b[j - 1] });\n      j--;\n    } else {\n      ops.push({ t: \"-\", s: a[i - 1] });\n      i--;\n    }\n  }\n  return ops.reverse();\n}\n\nfunction hunks(ops: Op[]): Array<[number, number]> {\n  const changed: number[] = [];\n  for (let i = 0; i < ops.length; i++) {\n    if (ops[i].t !== \"=\") changed.push(i);\n  }\n  if (changed.length === 0) return [];\n\n  const result: Array<[number, number]> = [];\n  let lo = Math.max(0, changed[0] - CONTEXT);\n  let hi = Math.min(ops.length - 1, changed[0] + CONTEXT);\n\n  for (let ci = 1; ci < changed.length; ci++) {\n    const nlo = Math.max(0, changed[ci] - CONTEXT);\n    const nhi = Math.min(ops.length - 1, changed[ci] + CONTEXT);\n    if (nlo <= hi + 1) {\n      hi = nhi;\n    } else {\n      result.push([lo, hi]);\n      lo = nlo;\n      hi = nhi;\n    }\n  }\n  result.push([lo, hi]);\n  return result;\n}\n\nfunction renderFileDiff(\n  filename: string,\n  prevBuf: Buffer,\n  nextBuf: Buffer,\n  color: boolean\n): string {\n  const prevText = prevBuf.toString(\"utf8\");\n  const nextText = nextBuf.toString(\"utf8\");\n  if (prevText === nextText) return \"\";\n\n  const ops = lineDiff(prevText.split(\"\\n\"), nextText.split(\"\\n\"));\n  const hs = hunks(ops);\n  if (hs.length === 0) return \"\";\n\n  const hdr1 = color ? `${C}--- a/${filename}${Z}` : `--- a/${filename}`;\n  const hdr2 = color ? `${C}+++ b/${filename}${Z}` : `+++ b/${filename}`;\n  const parts = [hdr1, hdr2];\n\n  for (const [lo, hi] of hs) {\n    // Compute 1-based start lines in each file\n    let aStart = 1,\n      bStart = 1;\n    for (let i = 0; i < lo; i++) {\n      if (ops[i].t === \"=\" || ops[i].t === \"-\") aStart++;\n      if (ops[i].t === \"=\" || ops[i].t === \"+\") bStart++;\n    }\n\n    let aCount = 0,\n      bCount = 0;\n    const hunkLines: string[] = [];\n    for (let i = lo; i <= hi; i++) {\n      const op = ops[i];\n      if (op.t === \"=\") {\n        hunkLines.push(` ${op.s}`);\n        aCount++;\n        bCount++;\n      } else if (op.t === \"-\") {\n        const line = `-${op.s}`;\n        hunkLines.push(color ? `${R}${line}${Z}` : line);\n        aCount++;\n      } else {\n        const line = `+${op.s}`;\n        hunkLines.push(color ? `${G}${line}${Z}` : line);\n        bCount++;\n      }\n    }\n\n    const hhdr = `@@ -${aStart},${aCount} +${bStart},${bCount} @@`;\n    parts.push(color ? `${C}${hhdr}${Z}` : hhdr);\n    parts.push(...hunkLines);\n  }\n\n  return parts.join(\"\\n\");\n}\n\nfunction renderNewFile(filename: string, buf: Buffer, color: boolean): string {\n  const lines = buf.toString(\"utf8\").split(\"\\n\");\n  const hdr1 = color ? `${C}--- /dev/null${Z}` : \"--- /dev/null\";\n  const hdr2 = color ? `${C}+++ b/${filename}${Z}` : `+++ b/${filename}`;\n  const hhdr = `@@ -0,0 +1,${lines.length} @@`;\n  const body = lines.map((l) => (color ? `${G}+${l}${Z}` : `+${l}`));\n  return [hdr1, hdr2, color ? `${C}${hhdr}${Z}` : hhdr, ...body].join(\"\\n\");\n}\n\nfunction renderDeletedFile(filename: string, buf: Buffer, color: boolean): string {\n  const lines = buf.toString(\"utf8\").split(\"\\n\");\n  const hdr1 = color ? `${C}--- a/${filename}${Z}` : `--- a/${filename}`;\n  const hdr2 = color ? `${C}+++ /dev/null${Z}` : \"+++ /dev/null\";\n  const hhdr = `@@ -1,${lines.length} +0,0 @@`;\n  const body = lines.map((l) => (color ? `${R}-${l}${Z}` : `-${l}`));\n  return [hdr1, hdr2, color ? `${C}${hhdr}${Z}` : hhdr, ...body].join(\"\\n\");\n}\n\n/**\n * Computes a unified line-level diff over materialized file content.\n *\n * prev/next are maps of filename \u2192 file buffer (the decoded files that would be\n * written to disk, not transport bundles). Pass color=true when output is a TTY.\n *\n * Returns an empty string when prev and next are identical.\n */\nexport function computeDiff(\n  prev: Record<string, Buffer>,\n  next: Record<string, Buffer>,\n  color = false\n): string {\n  const all = new Set([...Object.keys(prev), ...Object.keys(next)]);\n  const parts: string[] = [];\n\n  for (const filename of [...all].sort()) {\n    const p = prev[filename];\n    const n = next[filename];\n\n    let piece: string;\n    if (!p && n) {\n      piece = renderNewFile(filename, n, color);\n    } else if (p && !n) {\n      piece = renderDeletedFile(filename, p, color);\n    } else if (p && n) {\n      piece = renderFileDiff(filename, p, n, color);\n    } else {\n      continue;\n    }\n\n    if (piece) parts.push(piece);\n  }\n\n  return parts.join(\"\\n\\n\");\n}\n\n/**\n * One reviewable diff for a skill update, however many agents it fans out to.\n *\n * The bundle is the canonical content: after materialization every agent holds\n * byte-identical copies, so diffing each agent's copy repeats the same change\n * once per agent and renders misleading \"new file\" walls for agents that have\n * no copy yet. Diff the incoming bundle once against the most complete on-disk\n * copy instead, and state which agents the write lands in.\n *\n * The prompt-time security invariant holds: the body is still computed over\n * the exact content that will be materialized, and when today's on-disk copies\n * disagree between agents the header says which copy the diff is against.\n */\nexport function renderUpdateReview(opts: {\n  /** Materialized on-disk files, keyed \"agentName/relPath\". */\n  prev: Record<string, Buffer>;\n  /** Incoming bundle content keyed by bundle-relative path. */\n  next: Record<string, Buffer>;\n  /** Agents (adapter names) the update will be written to. */\n  adapterNames: string[];\n  color?: boolean;\n}): string {\n  const byAgent = new Map<string, Record<string, Buffer>>();\n  for (const [key, bytes] of Object.entries(opts.prev)) {\n    const slash = key.indexOf(\"/\");\n    if (slash < 0) continue;\n    const agent = key.slice(0, slash);\n    let files = byAgent.get(agent);\n    if (!files) byAgent.set(agent, (files = {}));\n    files[key.slice(slash + 1)] = bytes;\n  }\n\n  // The most complete copy stands in for \"current\" (ties break by name).\n  const ranked = [...byAgent.entries()].sort(\n    (a, b) =>\n      Object.keys(b[1]).length - Object.keys(a[1]).length ||\n      a[0].localeCompare(b[0]),\n  );\n  const representative = ranked[0];\n  const updating = [...byAgent.keys()].sort();\n  const fresh = opts.adapterNames.filter((n) => !byAgent.has(n)).sort();\n\n  const header: string[] = [];\n  const parts: string[] = [];\n  if (updating.length > 0) parts.push(`Updates ${updating.join(\", \")}`);\n  if (fresh.length > 0) parts.push(`first install for ${fresh.join(\", \")}`);\n  if (parts.length > 0) header.push(parts.join(\" \u00B7 \"));\n\n  const fingerprints = new Set(\n    ranked.map(([, files]) =>\n      Object.keys(files)\n        .sort()\n        .map((rel) => `${rel}\u0000${files[rel].toString(\"base64\")}`)\n        .join(\"\u0001\"),\n    ),\n  );\n  if (fingerprints.size > 1 && representative) {\n    header.push(\n      `Local copies differ between agents; diff shown against ${representative[0]}.`,\n    );\n  }\n\n  // First install: there is no on-disk copy to diff against, and a full\n  // \"new file\" dump of the entire source reviews nothing \u2014 summarize the\n  // shape instead (files + sizes). Updates keep the real diff: the change\n  // IS what's being reviewed there.\n  if (!representative) {\n    const files = Object.keys(opts.next).sort();\n    const lines: string[] = [];\n    const MAX = 8;\n    for (const rel of files.slice(0, MAX)) {\n      const count = opts.next[rel]!.toString(\"utf8\").split(\"\\n\").length;\n      lines.push(`  ${rel} (${count} lines)`);\n    }\n    if (files.length > MAX) {\n      const restLines = files\n        .slice(MAX)\n        .reduce((n, rel) => n + opts.next[rel]!.toString(\"utf8\").split(\"\\n\").length, 0);\n      lines.push(`  \u2026and ${files.length - MAX} more files (${restLines.toLocaleString(\"en-US\")} lines)`);\n    }\n    return [header.join(\"\\n\"), lines.join(\"\\n\")].filter(Boolean).join(\"\\n\\n\");\n  }\n\n  const body = computeDiff(representative[1], opts.next, opts.color ?? false);\n  return [header.join(\"\\n\"), body].filter(Boolean).join(\"\\n\\n\");\n}\n\n/** How many files an install summary names before folding into a count. */\nconst INSTALL_SUMMARY_MAX_FILES = 8;\n\n/** Compact summary for first-time materialization (no full SKILL.md dump).\n *  Large bundles fold: the first few files by name, then one totals line \u2014\n *  a 170-file kit skill must not scroll the prompt it precedes off screen. */\nexport function summarizeInstall(\n  skillRef: string,\n  next: Record<string, Buffer>,\n): string {\n  const seen = new Map<string, number>();\n  for (const key of [...Object.keys(next)].sort()) {\n    const slash = key.indexOf(\"/\");\n    const rel = slash >= 0 ? key.slice(slash + 1) : key;\n    if (rel.endsWith(\".skillet-backup\")) continue;\n    if (seen.has(rel)) continue;\n    seen.set(rel, next[key].toString(\"utf8\").split(\"\\n\").length);\n  }\n  const files = [...seen.entries()];\n  const lines: string[] = [`Install ${skillRef}:`];\n  for (const [rel, lineCount] of files.slice(0, INSTALL_SUMMARY_MAX_FILES)) {\n    lines.push(`  ${rel} (${lineCount} lines)`);\n  }\n  const rest = files.slice(INSTALL_SUMMARY_MAX_FILES);\n  if (rest.length > 0) {\n    const restLines = rest.reduce((n, [, c]) => n + c, 0);\n    lines.push(`  \u2026and ${rest.length} more files (${restLines.toLocaleString(\"en-US\")} lines)`);\n  }\n  return lines.join(\"\\n\");\n}\n", "/**\n * Approval lock: global record of user-approved and user-rejected skill content hashes.\n *\n * Lives at $XDG_DATA_HOME/skillet/skillet.lock (distinct from the per-project\n * skillet.lock which tracks pinned versions). An entry records the content hash\n * and author key ID at approval time; the TOCTOU guard re-verifies the hash\n * immediately before materialization.\n *\n * Security invariants:\n *   - Keyed by <skillId>@<version> so each version has an independent approval/rejection.\n *   - contentHash is sha256-prefixed; matching is exact string equality.\n *   - atomicWrite ensures the lock file is never partially written.\n *   - Any I/O error reading the lock is propagated (not silenced), so a corrupt\n *     lock cannot silently bypass approvals.\n *   - Rejections are version-scoped: rejecting v3 does not suppress the prompt for v4.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { atomicWrite } from \"../util/atomic.js\";\n\nexport interface DiffApproval {\n  /** sha256-prefixed hash of the materialized content at approval time */\n  contentHash: string;\n  /** hex-encoded 64-char Ed25519 public key ID of the update author */\n  authorKeyId: string;\n  /** ISO 8601 approval timestamp */\n  approvedAt: string;\n}\n\nexport interface DiffRejection {\n  /** hex-encoded 64-char Ed25519 public key ID of the update author */\n  authorKeyId: string;\n  /** ISO 8601 rejection timestamp */\n  rejectedAt: string;\n}\n\ninterface ApprovalLockFile {\n  version: 1;\n  approvals: Record<string, DiffApproval>;\n  /** Per-version rejections recorded via non-interactive `skillet reject`. Optional for backward compat. */\n  rejections?: Record<string, DiffRejection>;\n}\n\nfunction entryKey(skillId: string, version: number): string {\n  return `${skillId}@${version}`;\n}\n\n/** Returns the global approval lock path for the current user. */\nexport function defaultApprovalLockPath(): string {\n  const dataHome =\n    process.env[\"XDG_DATA_HOME\"] ?? join(homedir(), \".local\", \"share\");\n  return join(dataHome, \"skillet\", \"skillet.lock\");\n}\n\nasync function readLock(lockPath: string): Promise<ApprovalLockFile> {\n  try {\n    const raw = await readFile(lockPath, \"utf8\");\n    return JSON.parse(raw) as ApprovalLockFile;\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return { version: 1, approvals: {} };\n    }\n    throw err;\n  }\n}\n\n/**\n * Returns true iff the given contentHash matches the previously recorded\n * approval for this skillId@version. Returns false when no approval exists\n * or the hash does not match (triggers re-approval).\n */\nexport async function checkLock(\n  lockPath: string,\n  skillId: string,\n  version: number,\n  contentHash: string\n): Promise<boolean> {\n  const lock = await readLock(lockPath);\n  const entry = lock.approvals[entryKey(skillId, version)];\n  if (!entry) return false;\n  return entry.contentHash === contentHash;\n}\n\n/**\n * Writes an approval record for skillId@version to the lock file.\n * Clears any existing rejection for the same key so that the most-recent\n * decision wins and the two maps cannot hold conflicting states simultaneously.\n * Uses atomicWrite (temp + rename) to prevent partial writes.\n */\nexport async function recordApproval(\n  lockPath: string,\n  skillId: string,\n  version: number,\n  approval: DiffApproval\n): Promise<void> {\n  const lock = await readLock(lockPath);\n  lock.approvals[entryKey(skillId, version)] = approval;\n  delete lock.rejections?.[entryKey(skillId, version)];\n  await atomicWrite(lockPath, JSON.stringify(lock, null, 2) + \"\\n\", {\n    backup: false,\n  });\n}\n\n/**\n * Returns true iff a rejection was explicitly recorded for this skillId@version\n * via `skillet reject`. Returns false when no rejection exists.\n * Version-scoped: a rejection at v3 does not suppress the prompt for v4.\n */\nexport async function checkRejection(\n  lockPath: string,\n  skillId: string,\n  version: number\n): Promise<boolean> {\n  const lock = await readLock(lockPath);\n  return !!(lock.rejections?.[entryKey(skillId, version)]);\n}\n\n/**\n * Writes a rejection record for skillId@version to the lock file.\n * Clears any existing approval for the same key so that the most-recent\n * decision wins and the two maps cannot hold conflicting states simultaneously.\n * Uses atomicWrite (temp + rename) to prevent partial writes.\n */\nexport async function recordRejection(\n  lockPath: string,\n  skillId: string,\n  version: number,\n  rejection: DiffRejection\n): Promise<void> {\n  const lock = await readLock(lockPath);\n  if (!lock.rejections) lock.rejections = {};\n  lock.rejections[entryKey(skillId, version)] = rejection;\n  delete lock.approvals[entryKey(skillId, version)];\n  await atomicWrite(lockPath, JSON.stringify(lock, null, 2) + \"\\n\", {\n    backup: false,\n  });\n}\n\n/**\n * Returns the highest version number for which an approval was recorded for\n * the given skillId, or null if no approval has been recorded yet.\n * Used by `skillet pending --json` to surface the previously approved version.\n */\nexport async function getLastApprovedVersion(\n  lockPath: string,\n  skillId: string\n): Promise<number | null> {\n  const lock = await readLock(lockPath);\n  const prefix = `${skillId}@`;\n  let maxVersion: number | null = null;\n  for (const key of Object.keys(lock.approvals)) {\n    if (key.startsWith(prefix)) {\n      const v = parseInt(key.slice(prefix.length), 10);\n      if (!isNaN(v) && (maxVersion === null || v > maxVersion)) {\n        maxVersion = v;\n      }\n    }\n  }\n  return maxVersion;\n}\n", "/**\n * Interactive approval prompt for graded skill-update diffs.\n *\n * Security invariants:\n *   - Default answer is N (deny). The user must explicitly type \"y\" or \"yes\".\n *   - Non-interactive / non-TTY contexts return false immediately.\n *     Callers must exit non-zero when running in CI and approval is required.\n *   - The diff is always printed before prompting, so the user sees what they\n *     are approving. Callers must not suppress the diff.\n */\n\nimport { createInterface } from \"node:readline\";\nimport type { Writable, Readable } from \"node:stream\";\n\n/**\n * Prints diff to output, then asks the user to approve.\n *\n * Returns true iff the user explicitly answered \"y\" or \"yes\" (case-insensitive).\n * Returns false on EOF, non-TTY output, or any other answer.\n *\n * Pass process.stdout / process.stdin for production; pass mock streams in tests.\n */\nexport type ApprovalPromptKind = \"install\" | \"update\";\n\nexport async function promptApproval(\n  diff: string,\n  output: Writable,\n  input: Readable,\n  kind: ApprovalPromptKind = \"update\",\n): Promise<boolean> {\n  output.write(diff + \"\\n\");\n\n  // Non-TTY: no interactive terminal available \u2014 auto-deny.\n  // Caller is responsible for exiting non-zero.\n  const isTTY = (output as NodeJS.WriteStream).isTTY === true;\n  if (!isTTY) {\n    output.write(\n      \"\\nNon-interactive terminal: approvals must be recorded in the lock file before running in CI.\\n\"\n    );\n    return false;\n  }\n\n  const question =\n    kind === \"install\"\n      ? \"\\nInstall this skill? [y/N] \"\n      : \"\\nApprove this skill update? [y/N] \";\n\n  return new Promise<boolean>((resolve) => {\n    output.write(question);\n\n    const rl = createInterface({ input, output, terminal: false });\n\n    // settled guards against close firing synchronously inside rl.close()\n    // (which would invoke the close handler before the line handler finishes)\n    let settled = false;\n\n    rl.once(\"line\", (line: string) => {\n      settled = true;\n      rl.close();\n      const answer = line.trim().toLowerCase();\n      resolve(answer === \"y\" || answer === \"yes\");\n    });\n\n    rl.once(\"close\", () => {\n      if (!settled) resolve(false); // EOF without a line = deny\n    });\n  });\n}\n", "/**\n * Quarantine-gate prompt. Runs AFTER the standard graded-diff\n * approval, so the user has already seen the byte-level diff. This prompt\n * surfaces the scan findings_summary and demands a literal `understood`\n * acknowledgement before any adapter write.\n *\n * Security invariants:\n *   - Default is deny. Only the literal phrase `understood` (case-insensitive)\n *     approves the materialization.\n *   - Non-TTY contexts auto-deny; only the explicit `allowQuarantined` SyncOptions\n *     flag (or pre-recorded lock entry) lets non-interactive runs proceed.\n *   - The findings_summary is always printed before the prompt \u2014 callers must\n *     not suppress it.\n */\n\nimport { createInterface } from \"node:readline\";\nimport type { Writable, Readable } from \"node:stream\";\nimport type { ScanManifestInfo } from \"@skillet/protocol\";\n\nconst EXTRA_CONSENT_PHRASE = \"understood\";\n\n// Scan findings carry registry-supplied text (file paths, categories, \"why\"\n// strings). Printed raw they could smuggle terminal escape sequences into the\n// consent prompt \u2014 sanitize at the source so every consumer (sync's gate, the\n// menu's scanSummary, `skillet pending`) inherits it. Mirrors the CLI's\n// sanitize-output regexes; \\t and \\n survive.\n// eslint-disable-next-line no-control-regex\nconst ANSI_OSC = /\\x1b\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)/g;\n// eslint-disable-next-line no-control-regex\nconst ANSI_CSI = /\\x1b[@-Z\\\\-_]|\\x1b\\[[0-?]*[ -\\/]*[@-~]/g;\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f]/g;\nfunction sanitize(text: string): string {\n  return text.replace(ANSI_OSC, \"\").replace(ANSI_CSI, \"\").replace(CONTROL, \"\");\n}\n\nexport function renderFindingsSummary(scan: ScanManifestInfo): string {\n  const { status, findings_summary: s } = scan;\n  const header =\n    status === \"quarantined\"\n      ? \"\u26A0  QUARANTINED \u2014 harm scan found high-confidence findings\"\n      : status === \"flagged\"\n        ? \"\u26A0  Flagged \u2014 harm scan surfaced findings worth reviewing\"\n        : \"\u26A0  Scan pending \u2014 server has not finished scanning this version\";\n  const lines: string[] = [header];\n\n  if (status === \"pending\") {\n    lines.push(\"  Try again in a moment, or run `skillet sync` once the scan completes.\");\n    return lines.join(\"\\n\");\n  }\n\n  lines.push(\n    `  Top confidence: ${sanitize(String(s.topConfidence ?? \"n/a\"))} \u00B7 total findings: ${s.total}`,\n  );\n  for (const cat of Object.keys(s.counts) as Array<keyof typeof s.counts>) {\n    const bucket = s.counts[cat] ?? {};\n    const parts = (['high', 'medium', 'low'] as const)\n      .filter((sev) => (bucket[sev] ?? 0) > 0)\n      .map((sev) => `${sev}=${bucket[sev]}`);\n    if (parts.length > 0) lines.push(`  ${sanitize(String(cat))}: ${parts.join(' ')}`);\n  }\n  if (s.highlights.length > 0) {\n    lines.push(\"  Highlights:\");\n    for (const h of s.highlights) {\n      lines.push(\n        `    [${sanitize(String(h.confidence))}] ${sanitize(h.category)} \u00B7 ${sanitize(h.file)} (${sanitize(h.why)})`,\n      );\n    }\n  }\n  return lines.join(\"\\n\");\n}\n\n/**\n * Extra-consent prompt for quarantined versions. Returns true ONLY when the\n * user types the literal phrase `understood`. EOF, non-TTY, and any other\n * input return false.\n */\nexport async function promptQuarantineConsent(\n  scan: ScanManifestInfo,\n  slug: string,\n  output: Writable,\n  input: Readable,\n): Promise<boolean> {\n  output.write(\"\\n\" + renderFindingsSummary(scan) + \"\\n\");\n\n  const isTTY = (output as NodeJS.WriteStream).isTTY === true;\n  if (!isTTY) {\n    output.write(\n      `\\nQuarantined skill \"${slug}\" cannot be applied in a non-interactive run without --allow-quarantined.\\n`,\n    );\n    return false;\n  }\n\n  return new Promise<boolean>((resolve) => {\n    output.write(\n      `\\nThis skill is quarantined. Type \"${EXTRA_CONSENT_PHRASE}\" to apply it anyway: `,\n    );\n    const rl = createInterface({ input, output, terminal: false });\n    let settled = false;\n    rl.once(\"line\", (line: string) => {\n      settled = true;\n      rl.close();\n      resolve(line.trim().toLowerCase() === EXTRA_CONSENT_PHRASE);\n    });\n    rl.once(\"close\", () => {\n      if (!settled) resolve(false);\n    });\n  });\n}\n\n/**\n * Pure helper: should sync invoke the quarantine gate for this entry?\n *\n * Quarantined is the only blocking status \u2014 flagged surfaces in the diff but\n * does not stop materialization. Pending is opt-in safe: we treat it as\n * non-clean for `skillet status` listings but only require extra consent at\n * publish-replay time once the scan resolves.\n */\nexport function requiresQuarantineConsent(\n  scan: ScanManifestInfo | undefined,\n): boolean {\n  return scan?.status === \"quarantined\";\n}\n", "/**\n * Update-trust policy: decide, per incoming update, whether it\n * AUTO-APPLIES (no human diff prompt) or is DIFF-GATED (graded diff + approve).\n *\n * The resolution is a precedence hierarchy \u2014 most specific wins:\n *\n *   1. per-skill    (policy.skills[slug])        \u2014 overrides everything\n *   2. per-author   (policy.authors[authorKeyId]) \u2014 overrides kit + global, for that author\n *   3. per-kit local (policy.kits[sourceKit])     \u2014 a local CLI rule for one kit\n *   4. subscriber trust (input.subscriberTrust)   \u2014 the web-set per-kit preference\n *   5. global by source class                     \u2014 the fallback, TWO independent defaults:\n *        - own-kit  (your team / your own kit)  \u2192 default AUTO-APPLY\n *        - external (strangers)                 \u2192 default DIFF-GATE\n *\n * Per-kit lets a subscriber say \"auto-update this kit, but\n * review that one\" without trusting every author in it individually. It is\n * keyed by the kit ref the skill was synced under (`@owner/kitname`, the\n * manifest `source_kit`). Author/skill overrides are finer-grained and still\n * win, so you can auto-trust a kit yet gate one suspect skill inside it.\n *\n * SECURITY BOUNDARY (AC #5 \u2014 non-negotiable):\n *   This module decides ONLY whether a human reviews the diff. It NEVER governs\n *   whether the content is verified. Auto-apply removes the approval prompt; it\n *   does NOT skip Ed25519 signature verification or the harm scan. Those gates\n *   run unconditionally in the sync materialize path (see commands/sync.ts:\n *   the quarantine gate and verifyForMaterialize both run regardless of the\n *   trust mode resolved here). A trusted, auto-apply skill receiving a\n *   malicious or unsigned update is still hard-blocked. Trust governs review,\n *   not safety.\n *\n * Persistence: a single JSON file at $XDG_CONFIG_HOME/skillet/trust-policy.json,\n * written atomically (temp + rename). Authors are keyed by their Ed25519 key\n * ID (hex), not by handle \u2014 so a key rotation re-falls-through to the default\n * rather than silently inheriting trust granted to the old key.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { atomicWrite } from \"../util/atomic.js\";\n\n/** Whether an update applies without a human prompt (\"auto\") or is gated. */\nexport type TrustMode = \"auto\" | \"gate\";\n\n/**\n * Source class for the two independent global defaults:\n *   - \"own-kit\":  skill came from the user's own kit / a team kit they belong\n *                 to (the authenticated union manifest).\n *   - \"external\": skill was added from a stranger (`skillet add @them/skill`).\n */\nexport type SourceClass = \"own-kit\" | \"external\";\n\nexport interface TrustPolicyFile {\n  version: 1;\n  /** The two independent global defaults, by source class. */\n  globals: Record<SourceClass, TrustMode>;\n  /** Per-author overrides, keyed by Ed25519 key ID (hex). */\n  authors: Record<string, TrustMode>;\n  /** Per-skill overrides, keyed by slug (e.g. \"@taylor/festival-ops\"). */\n  skills: Record<string, TrustMode>;\n  /** Per-kit overrides, keyed by kit ref (e.g. \"@taylor/writers-kit\"). */\n  kits: Record<string, TrustMode>;\n}\n\n/**\n * The shipped defaults \u2014 chosen so the common case needs zero config:\n *   own-kit  \u2192 auto-apply (you trust your own team)\n *   external \u2192 diff-gate  (review before a stranger's update lands)\n */\nexport const DEFAULT_POLICY: TrustPolicyFile = {\n  version: 1,\n  globals: { \"own-kit\": \"auto\", external: \"gate\" },\n  authors: {},\n  skills: {},\n  kits: {},\n};\n\n/** Returns the trust-policy file path for the current user. */\nexport function defaultPolicyPath(): string {\n  const cfg = process.env[\"XDG_CONFIG_HOME\"] ?? join(homedir(), \".config\");\n  return join(cfg, \"skillet\", \"trust-policy.json\");\n}\n\n/** Narrowing guard so a hand-edited/corrupt mode can't slip through. */\nfunction asMode(v: unknown): TrustMode | undefined {\n  return v === \"auto\" || v === \"gate\" ? v : undefined;\n}\n\n/**\n * Reads the policy file, falling back to DEFAULT_POLICY when it does not\n * exist. A present-but-malformed file is repaired field-by-field against the\n * defaults rather than throwing \u2014 a corrupt policy must NEVER fail open into\n * blanket auto-apply, so anything unrecognized resolves to the (safer)\n * default. I/O errors other than ENOENT are propagated.\n */\nexport async function loadPolicy(\n  policyPath: string = defaultPolicyPath()\n): Promise<TrustPolicyFile> {\n  let raw: string;\n  try {\n    raw = await readFile(policyPath, \"utf8\");\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return structuredClone(DEFAULT_POLICY);\n    }\n    throw err;\n  }\n\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(raw);\n  } catch {\n    // A corrupt file must not silently widen trust. Fall back to safe defaults.\n    return structuredClone(DEFAULT_POLICY);\n  }\n\n  const p = (parsed ?? {}) as Partial<TrustPolicyFile>;\n  const globals = (p.globals ?? {}) as Partial<Record<SourceClass, unknown>>;\n  const out: TrustPolicyFile = {\n    version: 1,\n    globals: {\n      \"own-kit\": asMode(globals[\"own-kit\"]) ?? DEFAULT_POLICY.globals[\"own-kit\"],\n      external: asMode(globals.external) ?? DEFAULT_POLICY.globals.external,\n    },\n    authors: {},\n    skills: {},\n    kits: {},\n  };\n  for (const [k, v] of Object.entries(p.authors ?? {})) {\n    const m = asMode(v);\n    if (m) out.authors[k] = m;\n  }\n  for (const [k, v] of Object.entries(p.skills ?? {})) {\n    const m = asMode(v);\n    if (m) out.skills[k] = m;\n  }\n  for (const [k, v] of Object.entries(p.kits ?? {})) {\n    const m = asMode(v);\n    if (m) out.kits[k] = m;\n  }\n  return out;\n}\n\n/** Persists the policy atomically (temp + rename, no backup file). */\nexport async function savePolicy(\n  policy: TrustPolicyFile,\n  policyPath: string = defaultPolicyPath()\n): Promise<void> {\n  await atomicWrite(policyPath, JSON.stringify(policy, null, 2) + \"\\n\", {\n    backup: false,\n  });\n}\n\nexport interface PolicyInput {\n  /** Skill slug, e.g. \"@taylor/festival-ops\". */\n  slug: string;\n  /** Author Ed25519 key ID (hex). Absent for local imports. */\n  authorKeyId?: string | null;\n  /** Where the skill came from. */\n  source: \"local\" | \"registry\";\n  /**\n   * own-kit vs external. Absent for legacy entries written before trust policy;\n   * treated as \"external\" so the safer (gated) default applies on resolution.\n   */\n  sourceClass?: SourceClass | null;\n  /**\n   * Kit ref this skill was synced under (`@owner/kitname`, the manifest\n   * `source_kit`). Drives the local per-kit override. Absent for\n   * locally-imported skills and for skills not sourced from a kit.\n   */\n  sourceKit?: string | null;\n  /**\n   * The subscriber's web-set per-kit trust preference, delivered via the sync\n   * manifest. Overrides the global default but yields to any local per-skill,\n   * per-author, or per-kit override. Null/absent when none was set.\n   */\n  subscriberTrust?: TrustMode | null;\n  /**\n   * NF-006: whether the subscriber has TOFU-pinned this author's primary key.\n   * When explicitly false, resolution gates even under own-kit auto.\n   */\n  authorPinned?: boolean | null;\n}\n\n/**\n * Resolves the effective trust mode for one incoming update via the precedence\n * hierarchy. Pure \u2014 no I/O \u2014 so it is trivially unit-testable for every level.\n *\n * Short-circuits that are always auto (never gated), regardless of policy:\n *   - source === \"local\": the user's own imported file; there is no remote\n *     author to extend trust to.\n *   - authorKeyId === ownKeyId: a self-published update (own signing key).\n *\n * Everything else falls through skill \u2192 author \u2192 kit \u2192 global-by-source-class.\n */\nexport function resolveTrustMode(\n  input: PolicyInput,\n  policy: TrustPolicyFile,\n  ownKeyId?: string | null\n): TrustMode {\n  if (input.source === \"local\") return \"auto\";\n  if (input.authorKeyId && ownKeyId && input.authorKeyId === ownKeyId) {\n    return \"auto\";\n  }\n\n  // NF-006: a registry author the subscriber has not pinned yet always gates.\n  if (input.authorPinned === false) return \"gate\";\n\n  // 1. per-skill \u2014 most specific, wins over everything below.\n  const perSkill = policy.skills[input.slug];\n  if (perSkill) return perSkill;\n\n  // 2. per-author \u2014 overrides kit + global for this author's skills.\n  if (input.authorKeyId) {\n    const perAuthor = policy.authors[input.authorKeyId];\n    if (perAuthor) return perAuthor;\n  }\n\n  // 3. per-kit (local) \u2014 a local CLI override for one subscribed kit, so a\n  //    subscriber can auto-trust a whole kit (or gate one) without touching\n  //    per-author/per-skill rules.\n  if (input.sourceKit) {\n    const perKit = policy.kits[input.sourceKit];\n    if (perKit) return perKit;\n  }\n\n  // 4. subscriber trust \u2014 the web-set per-kit preference (delivered via the\n  //    manifest). It is the same conceptual level as the local per-kit rule, so\n  //    an explicit local override above wins, but this beats the global default.\n  if (input.subscriberTrust) return input.subscriberTrust;\n\n  // 5. global default, by source class. A missing/unknown source class\n  //    resolves to \"external\" \u2014 the safer of the two defaults.\n  const cls: SourceClass = input.sourceClass === \"own-kit\" ? \"own-kit\" : \"external\";\n  return policy.globals[cls];\n}\n\n// \u2500\u2500 setters (substrate for the contextual UX surfaces, AC #6) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// These are the functional primitives the diff-view toggle, skill page, author\n// profile, and the small global-defaults surface call into. They load \u2192 mutate\n// \u2192 save atomically so callers don't have to re-implement read-modify-write.\n\n/** Set one of the two global defaults. */\nexport async function setGlobalDefault(\n  cls: SourceClass,\n  mode: TrustMode,\n  policyPath: string = defaultPolicyPath()\n): Promise<TrustPolicyFile> {\n  const policy = await loadPolicy(policyPath);\n  policy.globals[cls] = mode;\n  await savePolicy(policy, policyPath);\n  return policy;\n}\n\n/** Pin (or clear) trust for a specific author key. mode=null removes the override. */\nexport async function setAuthorPolicy(\n  authorKeyId: string,\n  mode: TrustMode | null,\n  policyPath: string = defaultPolicyPath()\n): Promise<TrustPolicyFile> {\n  const policy = await loadPolicy(policyPath);\n  if (mode === null) delete policy.authors[authorKeyId];\n  else policy.authors[authorKeyId] = mode;\n  await savePolicy(policy, policyPath);\n  return policy;\n}\n\n/** Pin (or clear) trust for a specific skill. mode=null removes the override. */\nexport async function setSkillPolicy(\n  slug: string,\n  mode: TrustMode | null,\n  policyPath: string = defaultPolicyPath()\n): Promise<TrustPolicyFile> {\n  const policy = await loadPolicy(policyPath);\n  if (mode === null) delete policy.skills[slug];\n  else policy.skills[slug] = mode;\n  await savePolicy(policy, policyPath);\n  return policy;\n}\n\n/** Pin (or clear) trust for a specific kit. mode=null removes the override. */\nexport async function setKitPolicy(\n  kitRef: string,\n  mode: TrustMode | null,\n  policyPath: string = defaultPolicyPath()\n): Promise<TrustPolicyFile> {\n  const policy = await loadPolicy(policyPath);\n  if (mode === null) delete policy.kits[kitRef];\n  else policy.kits[kitRef] = mode;\n  await savePolicy(policy, policyPath);\n  return policy;\n}\n", "export { computeDiff, summarizeInstall, renderUpdateReview } from \"./diff.js\";\nexport {\n  checkLock,\n  recordApproval,\n  checkRejection,\n  recordRejection,\n  getLastApprovedVersion,\n  defaultApprovalLockPath,\n} from \"./approval-lock.js\";\nexport type { DiffApproval, DiffRejection } from \"./approval-lock.js\";\nexport { promptApproval, type ApprovalPromptKind } from \"./prompt.js\";\nexport {\n  promptQuarantineConsent,\n  renderFindingsSummary,\n  requiresQuarantineConsent,\n} from \"./quarantine.js\";\nexport {\n  resolveTrustMode,\n  loadPolicy,\n  savePolicy,\n  defaultPolicyPath,\n  setGlobalDefault,\n  setAuthorPolicy,\n  setSkillPolicy,\n  setKitPolicy,\n  DEFAULT_POLICY,\n} from \"./policy.js\";\nexport type {\n  TrustMode,\n  SourceClass,\n  TrustPolicyFile,\n  PolicyInput,\n} from \"./policy.js\";\n", "import { readFile, mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { atomicWrite } from '../util/atomic.js';\n\nexport interface EtagCache {\n  version: 1;\n  /** ref \u2192 quoted ETag the per-skill manifest endpoint last returned. */\n  entries: Record<string, string>;\n  /** Union manifest ETags keyed by registryUrl|deviceId|bearerKind. */\n  union?: Record<string, string>;\n}\n\n/** Stable cache key for GET /sync/manifest (per registry + device scope + bearer class). */\nexport function unionManifestEtagKey(\n  registryUrl: string,\n  deviceId?: string,\n  bearerKind?: string,\n): string {\n  const base = registryUrl.replace(/\\/+$/, '');\n  return `${base}|${deviceId ?? ''}|${bearerKind ?? 'unknown'}`;\n}\n\nexport function bearerKindFromToken(token: string): string {\n  if (token.startsWith('skillet_d_')) return 'device';\n  if (token.startsWith('skillet_k_')) return 'kit';\n  if (token.startsWith('skillet_s_')) return 'session';\n  return 'unknown';\n}\n\nexport function defaultEtagCachePath(): string {\n  const skilletDir = process.env['SKILLET_DIR'] ?? join(homedir(), '.skillet');\n  return join(skilletDir, 'etag-cache.json');\n}\n\nexport async function readEtagCache(path: string): Promise<EtagCache> {\n  try {\n    const raw = await readFile(path, 'utf8');\n    const parsed = JSON.parse(raw) as EtagCache;\n    if (\n      parsed &&\n      typeof parsed === 'object' &&\n      parsed.version === 1 &&\n      typeof parsed.entries === 'object'\n    ) {\n      return {\n        version: 1,\n        entries: parsed.entries,\n        union: parsed.union && typeof parsed.union === 'object' ? parsed.union : {},\n      };\n    }\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {\n      // Corrupt cache is harmless \u2014 we just re-fetch full manifests until the\n      // next successful write replaces it.\n    }\n  }\n  return { version: 1, entries: {}, union: {} };\n}\n\nexport async function writeEtagCache(path: string, cache: EtagCache): Promise<void> {\n  await mkdir(join(path, '..'), { recursive: true });\n  await atomicWrite(path, JSON.stringify(cache, null, 2) + '\\n', { backup: false });\n}\n", "/**\n * TOFU pin recovery when an author's primary signing key changes on the registry.\n *\n * `forceRepinAuthorKey` lives in pin.ts; this module adds comparison, registry\n * fetch, and structured parsing for sync/CLI recovery flows.\n */\n\nimport { parseSkillRef } from '../registry/identifier.js';\nimport { RegistryClient, RegistryError } from '../registry/client.js';\nimport {\n  defaultPinDir,\n  forceRepinAuthorKey,\n  loadPinnedKey,\n  type PinnedAuthorKey,\n} from './pin.js';\n\nconst AUTHOR_KEY_CHANGED_RE =\n  /author_key_changed: handle (\\S+) pinned to ([0-9a-f]{64}), registry served ([0-9a-f]{64})/;\n\nexport interface AuthorKeyMismatchInfo {\n  handle: string;\n  pinnedKeyId: string;\n  servedKeyId: string;\n}\n\nexport interface AuthorPinComparison {\n  handle: string;\n  pinned: PinnedAuthorKey | null;\n  served: { key_id: string; pub: string } | null;\n  mismatch: boolean;\n}\n\n/** Shorten a 64-char hex key id for terminal output. */\nexport function truncateKeyId(keyId: string, prefix = 8): string {\n  if (keyId.length <= prefix * 2) return keyId;\n  return `${keyId.slice(0, prefix)}\u2026`;\n}\n\n/** Parse `author_key_changed` detail from a pull/sync failure reason string. */\nexport function parseAuthorKeyMismatch(reason: string): AuthorKeyMismatchInfo | null {\n  const match = reason.match(AUTHOR_KEY_CHANGED_RE);\n  if (!match) return null;\n  return {\n    handle: match[1]!,\n    pinnedKeyId: match[2]!,\n    servedKeyId: match[3]!,\n  };\n}\n\n/** Compare the local TOFU pin with registry-served author key material. */\nexport async function compareAuthorPin(\n  handle: string,\n  pinDir: string = defaultPinDir(),\n  served?: { key_id: string; pub: string } | null,\n): Promise<AuthorPinComparison> {\n  const normalized = handle.startsWith('@') ? handle.slice(1) : handle;\n  const pinned = await loadPinnedKey(normalized, pinDir);\n  const mismatch =\n    pinned !== null &&\n    served !== null &&\n    served !== undefined &&\n    pinned.key_id !== served.key_id;\n  return {\n    handle: normalized,\n    pinned,\n    served: served ?? null,\n    mismatch,\n  };\n}\n\nfunction assertManifestAuthor(\n  handle: string,\n  ref: string,\n  authorKeyId: string | null | undefined,\n  authorPublicKey: string | null | undefined,\n): { key_id: string; pub: string } {\n  const normalized = handle.startsWith('@') ? handle.slice(1) : handle;\n  const { author } = parseSkillRef(ref);\n  if (author !== normalized) {\n    throw new RegistryError(\n      'author_mismatch',\n      `Skill ${ref} is owned by @${author}, not @${normalized}`,\n    );\n  }\n  if (!authorKeyId || !authorPublicKey) {\n    throw new RegistryError(\n      'author_not_claimed',\n      `@${normalized} has no claimed signing key on the registry`,\n    );\n  }\n  return { key_id: authorKeyId, pub: authorPublicKey };\n}\n\n/**\n * Fetch the registry's current primary author key for a handle.\n * Uses an explicit skill ref when provided; otherwise scans the caller's sync manifest.\n */\nexport async function fetchServedAuthorKey(\n  handle: string,\n  client: RegistryClient,\n  opts: { skillRef?: string } = {},\n): Promise<{ key_id: string; pub: string; skillRef: string }> {\n  const normalized = handle.startsWith('@') ? handle.slice(1) : handle;\n\n  if (opts.skillRef) {\n    const manifest = await client.getSkillManifest(opts.skillRef);\n    if (!manifest.value) {\n      throw new RegistryError('manifest_empty', `No manifest body for ${opts.skillRef}`);\n    }\n    const served = assertManifestAuthor(\n      normalized,\n      opts.skillRef,\n      manifest.value.author_key_id,\n      manifest.value.author_public_key,\n    );\n    return { ...served, skillRef: opts.skillRef };\n  }\n\n  const sync = await client.getSyncManifest();\n  if (!sync.value?.items?.length) {\n    throw new RegistryError(\n      'no_skill_ref',\n      `Cannot resolve @${normalized}'s signing key \u2014 no sync manifest items (pass a skill ref)`,\n    );\n  }\n\n  const item = sync.value.items.find((entry) => {\n    try {\n      return parseSkillRef(entry.ref).author === normalized;\n    } catch {\n      return false;\n    }\n  });\n  if (!item) {\n    throw new RegistryError(\n      'no_skill_ref',\n      `Cannot resolve @${normalized}'s signing key \u2014 no subscribed skill from this author`,\n    );\n  }\n\n  const manifest = await client.getSkillManifest(item.ref);\n  if (!manifest.value) {\n    throw new RegistryError('manifest_empty', `No manifest body for ${item.ref}`);\n  }\n  const served = assertManifestAuthor(\n    normalized,\n    item.ref,\n    manifest.value.author_key_id ?? item.author_key_id,\n    manifest.value.author_public_key,\n  );\n  return { ...served, skillRef: item.ref };\n}\n\n/** Human-approved overwrite of a stale TOFU pin. */\nexport async function acceptAuthorKeyRotation(\n  handle: string,\n  served: { key_id: string; pub: string },\n  pinDir: string = defaultPinDir(),\n  opts: { firstSeenVersion?: number } = {},\n): Promise<PinnedAuthorKey> {\n  return forceRepinAuthorKey(\n    handle,\n    {\n      key_id: served.key_id,\n      pub: served.pub,\n      first_seen_version: opts.firstSeenVersion ?? 0,\n    },\n    pinDir,\n  );\n}\n\n/** Recovery hint lines for terminal sync output. */\nexport function formatAuthorKeyMismatchHint(info: AuthorKeyMismatchInfo): string[] {\n  return [\n    `  author signing key changed for @${info.handle}`,\n    `  pinned: ${truncateKeyId(info.pinnedKeyId)}`,\n    `  registry: ${truncateKeyId(info.servedKeyId)}`,\n    `  Run: skillet pin accept ${info.handle}`,\n  ];\n}\n", "import { access } from 'node:fs/promises';\nimport { canonicalContentHash, skillContentHash } from '@skillet/protocol';\nimport { readBundleFromDir } from '../bundle/read.js';\nimport { skillContentDir } from './store.js';\n\n/**\n * Hash the skill store bundle for `slug`, or null when the store is missing\n * or unreadable as a bundle.\n */\nexport async function readSkillStoreContentHash(slug: string): Promise<string | null> {\n  try {\n    await access(skillContentDir(slug));\n    const bundle = await readBundleFromDir(skillContentDir(slug));\n    return skillContentHash(bundle);\n  } catch (err: unknown) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n    throw err;\n  }\n}\n\n/** True when our skill store directory exists (ENOENT returns false). */\nexport async function skillStoreDirExists(slug: string): Promise<boolean> {\n  try {\n    await access(skillContentDir(slug));\n    return true;\n  } catch (err: unknown) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;\n    throw err;\n  }\n}\n\n/** True when on-disk bundle hash equals the expected canonical `sha256:` hash. */\nexport async function skillStoreMatchesExpectedHash(\n  slug: string,\n  expectedHash: string,\n): Promise<boolean> {\n  const storeHash = await readSkillStoreContentHash(slug);\n  if (!storeHash) return false;\n  if (storeHash === expectedHash) return true;\n  // Legacy polluted publish: entry.hash counted `.skillet-backup` paths.\n  try {\n    const bundle = await readBundleFromDir(skillContentDir(slug), { includeSkilletBackups: true });\n    return canonicalContentHash(bundle) === expectedHash;\n  } catch {\n    return false;\n  }\n}\n\n/** True when store skill bytes match `entryHash`, including legacy polluted hashes. */\nexport function storeBundleMatchesEntryHash(\n  storeBundle: Map<string, Uint8Array>,\n  entryHash: string,\n  storeBundleWithBackups?: Map<string, Uint8Array>,\n): boolean {\n  const skillHash = skillContentHash(storeBundle);\n  if (skillHash === entryHash) return true;\n  if (storeBundleWithBackups) {\n    return canonicalContentHash(storeBundleWithBackups) === entryHash;\n  }\n  return false;\n}\n", "/**\n * Registry-pull phase of `skillet sync` (AC 2 + 4).\n *\n * For every registry-sourced kit entry, hit its manifest with the last-seen\n * ETag. On 304 nothing changes. On a new `latest_hash`, fetch the version,\n * re-verify the signature against the pinned author key (TOFU), and replace\n * the bundle in the local skill store. The kit entry is mutated in place so\n * the subsequent materialize phase sees the new hash and the graded-diff\n * approval gate fires for what we just downloaded.\n *\n * Headless rule: unattended runs SKIP pulling. The user explicitly\n * froze entries with `--pin`; everything else stays at whatever hash was\n * already approved. Interactive runs pull every non-pinned registry entry.\n *\n * ETag persistence: `~/.skillet/etag-cache.json`, keyed by the entry's slug\n * (which IS the canonical `@author/slug` ref). One file, atomic write,\n * cheap to throw away if it ever corrupts \u2014 the worst case is one extra\n * full manifest fetch per skill.\n */\n\nimport matter from 'gray-matter';\nimport { canonicalContentHash, CONTENT_HASH_PREFIX, skillContentHash, type SyncManifestItem } from '@skillet/protocol';\nimport {\n  RegistryClient,\n  RegistryError,\n  type RegistryClientOptions,\n  type RegistryManifest,\n  type VersionDetail,\n} from './client.js';\nimport {\n  signatureBytes,\n  verifyEnvelope,\n  SignatureError,\n  envelopeBindingFromSlug,\n  isBundleSignatureV2,\n  type Signature,\n} from '../signing/envelope.js';\nimport {\n  bearerKindFromToken,\n  defaultEtagCachePath,\n  readEtagCache,\n  unionManifestEtagKey,\n  writeEtagCache,\n} from './etag-cache.js';\nimport { isEd25519Signature, isSessionAttestedSignature } from '../signing/session-attest.js';\nimport {\n  verifyDelegatedVersionSignature,\n  DelegationError,\n} from '../signing/delegation.js';\nimport { assertKeyIdBindsPub, authorKeyForVerification, commitAuthorKeyPin, defaultPinDir } from '../signing/pin.js';\nimport { parseAuthorKeyMismatch } from '../signing/pin-recovery.js';\nimport type { SignedDelegation } from '@skillet/protocol';\nimport { writeBundleToSkillStore, upsertSkill, skillContentDir } from '../kit/store.js';\nimport { skillStoreMatchesExpectedHash, readSkillStoreContentHash } from '../kit/store-integrity.js';\nimport { parseSkillRef } from './identifier.js';\nimport {\n  alignEntryToManifest,\n  findAllLocalsForManifestItem,\n  sanitizeVersionLabel,\n} from '../kit/manifest-match.js';\nimport type { KitState, SkillEntry } from '../kit/types.js';\nimport { rename } from 'node:fs/promises';\n\nexport type PullStatus =\n  | 'updated'      // new hash fetched, bundle rewritten on disk, entry mutated\n  | 'unchanged'    // server returned 304 OR latest_hash already in kit\n  | 'skipped-pinned'      // entry.pinned === true\n  | 'skipped-yanked'      // registry latest is yanked; keep existing bytes\n  | 'skipped-unattended'  // headless rule: not interactive\n  | 'gone'         // registry 404 \u2014 skill deleted upstream; reconcile will prune it\n  | 'failed';      // network / verification error \u2014 entry left untouched\n\nexport interface PullOutcome {\n  slug: string;\n  status: PullStatus;\n  reason?: string;\n  newHash?: string;\n  /**\n   * The canonical (`sha256:`-prefixed) hash of a version the registry now marks\n   * YANKED \u2014 surfaced so a customized skill holding this version as a\n   * `held_update` can be flagged and stop nudging (F6). Set on the `unchanged`\n   * outcome when the held/current version itself is yanked, and on the\n   * `skipped-yanked` outcome for a newer yanked latest. Absent otherwise.\n   */\n  yankedHash?: string;\n  /** Present when verification refused a registry key rotation without re-pin. */\n  authorKeyMismatch?: {\n    handle: string;\n    pinnedKeyId: string;\n    servedKeyId: string;\n  };\n}\n\nexport interface PullOptions {\n  /** When false, pull is skipped for non-pinned entries (the headless rule). */\n  interactive: boolean;\n  /** Pin dir for TOFU verification; defaults to $XDG_CONFIG_HOME/skillet/pinned. */\n  pinDir?: string;\n  /** Override the ETag cache path; defaults to $SKILLET_DIR/etag-cache.json. */\n  etagCachePath?: string;\n  /** Bearer token to pass through to every registry call. */\n  token?: string;\n  /**\n   * Device key ids the relevant authors have revoked, pulled on sync.\n   * A device-signed version whose key is in this set is refused (AC#3). Absent\n   * until a revocation-fetch path is wired (see resolveRevokedDeviceKeyIds).\n   *\n   * NOTE: this is a single set; prefer `getRevokedKeys` for correct PER-REGISTRY\n   * revocation when entries span multiple registries (deepsec MEDIUM). Kept as a\n   * fallback for single-registry callers.\n   */\n  revokedDeviceKeyIds?: Set<string>;\n  /**\n   * Resolve the revoked-device-key set for a SPECIFIC serving registry. When\n   * provided, each entry is checked against the revocation set of the registry\n   * that served it \u2014 not a single default-registry set (deepsec MEDIUM:\n   * delegated-device revocation must be per registry).\n   */\n  getRevokedKeys?: (registryUrl: string) => Promise<Set<string>>;\n  /** Inject an alternate fetch (tests). */\n  fetchImpl?: typeof fetch;\n}\n\n/** Re-export for callers that key union manifest caches. */\nexport { unionManifestEtagKey } from './etag-cache.js';\n\nfunction failedPullOutcome(slug: string, err: unknown): PullOutcome {\n  const reason =\n    err instanceof SignatureError || err instanceof DelegationError\n      ? `${err.code}: ${err.message}`\n      : err instanceof RegistryError\n        ? `${err.code}: ${err.message}`\n        : `pull_failed: ${(err as Error).message}`;\n  const outcome: PullOutcome = { slug, status: 'failed', reason };\n  const mismatch = parseAuthorKeyMismatch(reason);\n  if (mismatch) outcome.authorKeyMismatch = mismatch;\n  return outcome;\n}\n\n/** Options for the union-manifest pull phase. */\nexport interface UnionPullOptions {\n  registryUrl: string;\n  token: string;\n  pinDir?: string;\n  /**\n   * This machine's registry device id. A session token authenticates the user\n   * but not the machine, so we pass it explicitly to get per-device kit routing\n   * (which kits sync here). Omitted \u2192 the full account union.\n   */\n  deviceId?: string;\n  /** Revoked device key ids to refuse on sync (AC#3). See PullOptions. */\n  revokedDeviceKeyIds?: Set<string>;\n  /** Override the ETag cache path; defaults to $SKILLET_DIR/etag-cache.json. */\n  etagCachePath?: string;\n  fetchImpl?: typeof fetch;\n}\n\n/**\n * Fetch the server-side union manifest for the authenticated caller\n * and bring in any skill refs that are new or updated relative to local state.\n * Mutates `state.skills` in place so the downstream materialize loop sees the\n * additions without another pass.\n *\n * Called BEFORE `pullRegistryUpdates` so new refs land in state first; the\n * per-skill pull loop then treats them as already-up-to-date (same hash).\n *\n * Never throws \u2014 per-item failures are returned as `PullOutcome` with\n * status='failed', so one bad skill cannot abort the whole sync.\n */\nasync function promoteAliasToCanonical(\n  state: KitState,\n  item: SyncManifestItem,\n): Promise<SkillEntry> {\n  const matches = findAllLocalsForManifestItem(state, item);\n  const primary = matches[0];\n  if (!primary) {\n    throw new Error(`missing local match for ${item.ref}`);\n  }\n  const aligned = alignEntryToManifest(primary.entry, item);\n\n  for (const { slug } of matches) {\n    if (slug !== item.ref) {\n      delete state.skills[slug];\n    }\n  }\n\n  if (primary.slug !== item.ref) {\n    try {\n      await rename(skillContentDir(primary.slug), skillContentDir(item.ref));\n    } catch {\n      // Content may remain under the alias dir until the next import.\n    }\n  }\n\n  state.skills[item.ref] = aligned;\n  await upsertSkill(aligned);\n  return aligned;\n}\n\nexport interface UnionPullResult {\n  outcomes: PullOutcome[];\n  /**\n   * The set of refs the manifest authoritatively contains \u2014 the keep-set for\n   * pruning. `null` when there is NO authoritative manifest this run (304 not-\n   * modified, 401, or a network error): callers MUST NOT prune on `null`, or a\n   * transient failure would delete the user's skills.\n   */\n  manifestRefs: Set<string> | null;\n  /**\n   * The server's `SyncManifest.account_scope` \u2014 `user` is the only value our\n   * registry emits. `undefined` when not fetched (304/error) or served by an\n   * older server that omits the field. The caller uses this to decide whether\n   * an EMPTY manifest may zero a machine out: only a `user`-scoped empty is an\n   * authoritative \"sync nothing here\".\n   */\n  accountScope?: 'user';\n  /** True when the registry rejected the bearer (401) for a linked device token. */\n  authRejected?: boolean;\n  /** True when GET /sync/manifest returned 304 Not Modified. */\n  unionNotModified?: boolean;\n}\n\nexport async function pullFromUnionManifest(\n  state: KitState,\n  opts: UnionPullOptions,\n): Promise<UnionPullResult> {\n  const client = new RegistryClient({\n    baseUrl: opts.registryUrl,\n    token: opts.token,\n    fetchImpl: opts.fetchImpl,\n  });\n\n  let items: SyncManifestItem[];\n  let accountScope: 'user' | undefined;\n  let unionEtag: string | null = null;\n  const etagPath = opts.etagCachePath ?? defaultEtagCachePath();\n  const cache = await readEtagCache(etagPath);\n  if (!cache.union) cache.union = {};\n  const unionKey = unionManifestEtagKey(\n    opts.registryUrl,\n    opts.deviceId,\n    bearerKindFromToken(opts.token),\n  );\n  const cachedUnionEtag = cache.union[unionKey] ?? null;\n  try {\n    const res = await client.getSyncManifest({\n      device: opts.deviceId,\n      etag: cachedUnionEtag,\n    });\n    // 304 \u2192 identical to last sync (keep-set unchanged); no value \u2192 nothing.\n    // Either way, not an authoritative change to reconcile against.\n    if (res.notModified) {\n      return { outcomes: [], manifestRefs: null, unionNotModified: true };\n    }\n    if (!res.value) return { outcomes: [], manifestRefs: null };\n    unionEtag = res.etag ?? null;\n    items = res.value.items;\n    accountScope = res.value.account_scope;\n  } catch (err) {\n    if (\n      err instanceof RegistryError &&\n      (err.code === 'unauthorized' ||\n        err.status === 401 ||\n        // A device token whose row is unpaired/null-user: the registry fails it\n        // closed with 403 device_not_paired. Same recovery as a 401 \u2014 route it\n        // to the auth-required lane, not a generic throw (which desktop would\n        // misclassify as offline).\n        err.code === 'device_not_paired')\n    ) {\n      const linkedDevice = opts.token.startsWith('skillet_d_');\n      return {\n        outcomes: [],\n        manifestRefs: null,\n        ...(linkedDevice ? { authRejected: true } : {}),\n      };\n    }\n    throw err;\n  }\n\n  const outcomes: PullOutcome[] = [];\n  const pinDir = opts.pinDir ?? defaultPinDir();\n\n  for (const item of items) {\n    const ref = item.ref;\n    // SECURITY (H1): validate the registry-supplied ref BEFORE it reaches any\n    // path operation. The alias-promotion shortcut below calls\n    // promoteAliasToCanonical \u2192 rename(skillContentDir(item.ref)); a hostile\n    // manifest ref like \"../../../tmp/evil\" colliding on a known content_hash\n    // would otherwise move the matched local skill dir out of the store.\n    // parseSkillRef rejects anything outside the @author/slug grammar.\n    try {\n      parseSkillRef(ref);\n    } catch {\n      outcomes.push({ slug: ref, status: 'failed', reason: 'invalid_ref' });\n      continue;\n    }\n    const matches = findAllLocalsForManifestItem(state, item);\n    const existing = matches[0]?.entry;\n    const hasAlias = matches.some((m) => m.slug !== ref);\n\n    if (existing?.pinned) {\n      outcomes.push({ slug: ref, status: 'skipped-pinned' });\n      continue;\n    }\n    if (existing && existing.hash === item.content_hash) {\n      const storeAligned = await skillStoreMatchesExpectedHash(ref, existing.hash);\n      if (storeAligned) {\n        if (hasAlias || !existing.sourceKit) {\n          await promoteAliasToCanonical(state, item);\n        } else {\n          const label = sanitizeVersionLabel(item.version_label);\n          if (label && label !== existing.versionLabel) {\n            existing.versionLabel = label;\n            await upsertSkill(existing);\n          }\n        }\n        outcomes.push({ slug: ref, status: 'unchanged' });\n        continue;\n      }\n      // State matches manifest but local store bytes drifted \u2014 fall through to fetch.\n    } else if (existing) {\n      const storeHash = await readSkillStoreContentHash(ref);\n      if (storeHash && storeHash === existing.hash) {\n        if (\n          await legacyPollutedManifestMatches(client, ref, item.content_hash, storeHash)\n        ) {\n          outcomes.push({ slug: ref, status: 'unchanged' });\n          continue;\n        }\n      }\n      if (storeHash && storeHash === item.content_hash && existing.hash !== item.content_hash) {\n        existing.hash = storeHash;\n        existing.updatedAt = new Date().toISOString();\n        await upsertSkill(existing);\n        outcomes.push({ slug: ref, status: 'unchanged' });\n        continue;\n      }\n    }\n\n    try {\n      const parsed = parseSkillRef(ref);\n      const manifestRes = await client.getSkillManifest(ref);\n      const manifest = manifestRes.value;\n      if (!manifest) {\n        outcomes.push({ slug: ref, status: 'failed', reason: 'manifest_empty' });\n        continue;\n      }\n\n      const placeholder: SkillEntry = existing ?? ({\n        slug: ref,\n        owner: parsed.author,\n        name: parsed.slug,\n        description: '',\n        version: 0,\n        hash: '',\n        source: 'registry',\n        registryUrl: opts.registryUrl,\n        importedAt: new Date().toISOString(),\n        updatedAt: new Date().toISOString(),\n      } as SkillEntry);\n\n      const update = await fetchAndVerify(client, ref, placeholder, manifest, pinDir, opts.revokedDeviceKeyIds);\n      await writeBundleToSkillStore(ref, update.version.bundle);\n\n      const skillMd = update.version.bundle.get('SKILL.md');\n      let name = parsed.slug;\n      let description = '';\n      if (skillMd) {\n        try {\n          const fm = matter(Buffer.from(skillMd).toString('utf8'));\n          const d = fm.data as Record<string, unknown>;\n          if (typeof d.name === 'string' && d.name) name = d.name;\n          if (typeof d.description === 'string') description = d.description;\n        } catch { /* ignore frontmatter parse errors */ }\n      }\n\n      const now = new Date().toISOString();\n      const entry: SkillEntry = {\n        ...placeholder,\n        owner: parsed.author,\n        name,\n        description,\n        version: update.versionInt,\n        // Display-only semver label for the fetched version. The sync item's\n        // label is only trusted when it names the version we actually fetched\n        // (the manifest may have moved past it). `undefined` (older server)\n        // overwrites any stale label carried over from the placeholder and\n        // drops out of the persisted JSON.\n        versionLabel:\n          update.versionLabel ??\n          (item.version === update.versionInt ? sanitizeVersionLabel(item.version_label) : undefined),\n        hash: update.recomputed,\n        source: 'registry',\n        // Union-manifest refs come from the authenticated caller's own\n        // kit / team kits \u2014 classify as own-kit so the own-kit global default\n        // (auto-apply) applies. Preserve an existing class if one was already\n        // set (e.g. a skill first added externally, later shared into a kit\n        // keeps its stricter class unless explicitly re-trusted).\n        sourceClass:\n          existing?.sourceClass ?? (item.external_author ? 'external' : 'own-kit'),\n        // Kit ref this skill was synced under, for the per-kit trust override.\n        sourceKit: item.source_kit ?? existing?.sourceKit ?? null,\n        // Stable kit id (identity-safe; sourceKit is display only).\n        sourceKitId: item.kit_id ?? existing?.sourceKitId ?? null,\n        // Web-set per-kit trust preference delivered via the manifest.\n        subscriberTrust: item.subscriber_trust ?? existing?.subscriberTrust ?? null,\n        // Classified category delivered via the manifest \u2014 drives cover art.\n        category: item.category ?? existing?.category ?? null,\n        registryUrl: opts.registryUrl,\n        authorKeyId: update.authorKeyId,\n        authorPubBase64: update.authorPubBase64,\n        signature: update.envelope,\n        ...(update.delegation ? { delegation: update.delegation } : {}),\n        importedAt: existing?.importedAt ?? now,\n        updatedAt: now,\n      };\n      await upsertSkill(entry);\n      state.skills[ref] = entry;\n      for (const { slug } of matches) {\n        if (slug !== ref) delete state.skills[slug];\n      }\n\n      outcomes.push({ slug: ref, status: 'updated', newHash: update.recomputed });\n    } catch (err) {\n      outcomes.push(failedPullOutcome(ref, err));\n    }\n  }\n\n  // Persist the union etag only after a pull with no hard failures. Caching it\n  // eagerly (pre-verification) turned an all-failed pull into a permanent\n  // silent no-op: every later sync 304'd and reported \"unchanged\" while the\n  // local store never received the manifest's items.\n  if (unionEtag && !outcomes.some((o) => o.status === 'failed')) {\n    cache.union[unionKey] = unionEtag;\n    await writeEtagCache(etagPath, cache);\n  }\n\n  return { outcomes, manifestRefs: new Set(items.map((i) => i.ref)), accountScope };\n}\n\nfunction entryNeedsAuthorMetadataRepair(entry: SkillEntry): boolean {\n  return (\n    entry.source === 'registry' &&\n    entry.signature != null &&\n    isSessionAttestedSignature(entry.signature) &&\n    (!entry.authorKeyId || !entry.authorPubBase64)\n  );\n}\n\nasync function hydrateAuthorMetadataFromManifest(\n  entry: SkillEntry,\n  manifest: RegistryManifest,\n): Promise<boolean> {\n  if (!entryNeedsAuthorMetadataRepair(entry)) return false;\n  const authorKeyId = manifest.author_key_id ?? entry.authorKeyId ?? null;\n  const authorPubBase64 = manifest.author_public_key ?? entry.authorPubBase64 ?? null;\n  if (!authorKeyId || !authorPubBase64) return false;\n  entry.authorKeyId = authorKeyId;\n  entry.authorPubBase64 = authorPubBase64;\n  await upsertSkill(entry);\n  return true;\n}\n\n/**\n * Walks every registry-sourced entry in `state` and (in interactive mode)\n * pulls newer versions into the local skill store. Mutates `state.skills`\n * in place so the caller's subsequent materialize loop sees the updates.\n *\n * Never throws \u2014 a per-entry failure (network, signature, integrity) is\n * captured as a `PullOutcome` with status='failed'. The entry on disk and\n * in memory is left in its prior state so the materialize phase still has\n * a valid bundle to work with.\n */\nexport async function pullRegistryUpdates(\n  state: KitState,\n  opts: PullOptions,\n): Promise<PullOutcome[]> {\n  const outcomes: PullOutcome[] = [];\n  const etagPath = opts.etagCachePath ?? defaultEtagCachePath();\n  const cache = await readEtagCache(etagPath);\n  const pinDir = opts.pinDir ?? defaultPinDir();\n\n  // Cache one client per registryUrl \u2014 fetch() and the Bearer token are the\n  // same across slugs that share a registry, and the constructor's fetchImpl\n  // binding is the expensive bit.\n  const clients = new Map<string, RegistryClient>();\n  const clientFor = (url: string): RegistryClient => {\n    const cached = clients.get(url);\n    if (cached) return cached;\n    const created = new RegistryClient(buildClientOpts(url, opts));\n    clients.set(url, created);\n    return created;\n  };\n\n  let cacheDirty = false;\n\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (entry.source !== 'registry') continue;\n    if (entry.pinned === true) {\n      outcomes.push({ slug, status: 'skipped-pinned' });\n      continue;\n    }\n    if (!opts.interactive) {\n      // PROTOCOL \u00A76 \u2014 unattended sync does NOT pull. Existing materialize\n      // logic still runs against the already-approved bytes on disk.\n      outcomes.push({ slug, status: 'skipped-unattended' });\n      continue;\n    }\n    if (!entry.registryUrl) {\n      outcomes.push({\n        slug,\n        status: 'failed',\n        reason: 'registry_missing: kit entry has no registryUrl \u2014 re-add to repair',\n      });\n      continue;\n    }\n\n    try {\n      const client = clientFor(entry.registryUrl);\n      const cachedEtag = cache.entries[slug] ?? null;\n      const manifestRes = await client.getSkillManifest(slug, { etag: cachedEtag });\n\n      if (manifestRes.etag && manifestRes.etag !== cachedEtag) {\n        cache.entries[slug] = manifestRes.etag;\n        cacheDirty = true;\n      }\n\n      let manifest = manifestRes.value;\n\n      if (manifestRes.notModified) {\n        if (entryNeedsAuthorMetadataRepair(entry)) {\n          try {\n            const fresh = await client.getSkillManifest(slug);\n            if (fresh.value) {\n              manifest = fresh.value;\n              await hydrateAuthorMetadataFromManifest(entry, fresh.value);\n            }\n          } catch {\n            // best-effort repair for stale session-upload metadata\n          }\n        }\n        if (await skillStoreMatchesExpectedHash(slug, entry.hash)) {\n          outcomes.push({ slug, status: 'unchanged' });\n          continue;\n        }\n        // State unchanged on server but local store bytes drifted \u2014 fetch manifest\n        // and repair below.\n        if (!manifest) {\n          const fresh = await client.getSkillManifest(slug);\n          if (fresh.etag && fresh.etag !== cachedEtag) {\n            cache.entries[slug] = fresh.etag;\n            cacheDirty = true;\n          }\n          manifest = fresh.value ?? null;\n        }\n        if (!manifest) {\n          outcomes.push({\n            slug,\n            status: 'failed',\n            reason: 'manifest_empty: registry returned 304 then no body on repair fetch',\n          });\n          continue;\n        }\n      } else if (!manifest) {\n        outcomes.push({\n          slug,\n          status: 'failed',\n          reason: 'manifest_empty: registry returned a 200 without a body',\n        });\n        continue;\n      }\n\n      const expectedHashPrefixed = manifest.latest_hash\n        ? `${CONTENT_HASH_PREFIX}${stripPrefix(manifest.latest_hash)}`\n        : null;\n      if (!expectedHashPrefixed) {\n        outcomes.push({ slug, status: 'unchanged' });\n        continue;\n      }\n      if (expectedHashPrefixed === entry.hash) {\n        const storeAligned = await skillStoreMatchesExpectedHash(slug, entry.hash);\n        if (storeAligned) {\n          const latestVersionMeta = manifest.versions.find((v) => v.hash === manifest.latest_hash);\n          const label = sanitizeVersionLabel(latestVersionMeta?.version_label);\n          if (label && label !== entry.versionLabel) {\n            entry.versionLabel = label;\n            await upsertSkill(entry);\n          }\n          await hydrateAuthorMetadataFromManifest(entry, manifest);\n          outcomes.push({\n            slug,\n            status: 'unchanged',\n            ...(latestVersionMeta?.yanked ? { yankedHash: expectedHashPrefixed } : {}),\n          });\n          continue;\n        }\n        // entry.hash matches manifest but store drifted \u2014 fall through to repair fetch.\n      }\n\n      if (expectedHashPrefixed !== entry.hash) {\n        const storeHash = await readSkillStoreContentHash(slug);\n        if (\n          storeHash &&\n          storeHash === entry.hash &&\n          (await legacyPollutedManifestMatches(client, slug, expectedHashPrefixed, storeHash))\n        ) {\n          const latestVersionMeta = manifest.versions.find((v) => v.hash === manifest.latest_hash);\n          await hydrateAuthorMetadataFromManifest(entry, manifest);\n          outcomes.push({\n            slug,\n            status: 'unchanged',\n            ...(latestVersionMeta?.yanked ? { yankedHash: expectedHashPrefixed } : {}),\n          });\n          continue;\n        }\n      }\n\n      const latestIdx = manifest.versions.findIndex(\n        (v) => v.hash === manifest.latest_hash,\n      );\n      if (latestIdx < 0) {\n        outcomes.push({\n          slug,\n          status: 'failed',\n          reason: `manifest latest_hash ${manifest.latest_hash} not in versions list`,\n        });\n        continue;\n      }\n\n      const latestVersion = manifest.versions[latestIdx];\n      if (latestVersion?.yanked) {\n        outcomes.push({\n          slug,\n          status: 'skipped-yanked',\n          reason: `latest ${manifest.latest_hash} is yanked \u2014 keeping pinned bytes`,\n          yankedHash: expectedHashPrefixed,\n        });\n        continue;\n      }\n\n      // Per-registry revocation: check this entry against the revocation set of\n      // the registry that served it, not a single default-registry set.\n      const revoked = opts.getRevokedKeys\n        ? await opts.getRevokedKeys(entry.registryUrl)\n        : opts.revokedDeviceKeyIds;\n      const update = await fetchAndVerify(client, slug, entry, manifest, pinDir, revoked);\n      if (entry.version != null && entry.version > 0 && update.versionInt < entry.version) {\n        outcomes.push({\n          slug,\n          status: 'failed',\n          reason: `rollback_detected: manifest version ${update.versionInt} is older than local ${entry.version}`,\n        });\n        continue;\n      }\n      // Write bundle to the local skill store, then mutate the kit entry so\n      // the existing materialize loop sees the new hash + signature on this\n      // same sync run.\n      await writeBundleToSkillStore(slug, update.version.bundle);\n      entry.hash = update.recomputed;\n      entry.version = update.versionInt;\n      // Keep the display label in step with the integer: set when the server\n      // provided one, clear a stale one when it did not (older server).\n      if (update.versionLabel) entry.versionLabel = update.versionLabel;\n      else delete entry.versionLabel;\n      entry.signature = update.envelope;\n      entry.authorKeyId = update.authorKeyId;\n      entry.authorPubBase64 = update.authorPubBase64;\n      // Keep `delegation` consistent with `signature`: set it for a device-signed\n      // version, clear any stale one when the signer reverts to the primary key.\n      if (update.delegation) entry.delegation = update.delegation;\n      else delete entry.delegation;\n      entry.updatedAt = new Date().toISOString();\n      // Persist the mutation so a crash mid-sync doesn't leave the on-disk\n      // bundle (v2) and the kit state (v1) out of sync \u2014 the materialize\n      // loop's `if (currentHash !== entry.hash) upsertSkill` would skip the\n      // write since we just made them match in memory.\n      await upsertSkill(entry);\n\n      outcomes.push({ slug, status: 'updated', newHash: update.recomputed });\n    } catch (err) {\n      // A 404 means the skill was deleted from the registry (e.g. unpublished,\n      // or a DB reset). Don't fail the whole sync over a gone skill \u2014 mark it\n      // 'gone' and leave it in state so the reconcile-prune phase (which removes\n      // state entries absent from the union manifest) moves its materialized\n      // copies to trash. Degrade gracefully instead of wedging the tray.\n      if (err instanceof RegistryError && err.status === 404) {\n        outcomes.push({ slug, status: 'gone' });\n      } else {\n        // Never let one bad entry abort the whole sync.\n        outcomes.push(failedPullOutcome(slug, err));\n      }\n    }\n  }\n\n  if (cacheDirty) {\n    try {\n      await writeEtagCache(etagPath, cache);\n    } catch {\n      // Cache persistence failures are non-fatal \u2014 next run just re-fetches.\n    }\n  }\n\n  return outcomes;\n}\n\ninterface FetchAndVerifyResult {\n  version: VersionDetail;\n  recomputed: string;\n  envelope: NonNullable<VersionDetail['signature']>;\n  versionInt: number;\n  /** Display-only semver label served for this version; null on older servers. */\n  versionLabel: string | null;\n  authorKeyId: string;\n  authorPubBase64: string;\n  /** Present iff the version was signed by a delegated device key. */\n  delegation: SignedDelegation | null;\n}\n\nasync function fetchAndVerify(\n  client: RegistryClient,\n  slug: string,\n  entry: SkillEntry,\n  manifest: RegistryManifest,\n  pinDir: string,\n  revokedDeviceKeyIds?: Set<string>,\n): Promise<FetchAndVerifyResult> {\n  if (!manifest.latest_hash) {\n    throw new RegistryError('no_versions', `${slug} has no published versions`);\n  }\n  const latestIdx = manifest.versions.findIndex(\n    (v) => v.hash === manifest.latest_hash,\n  );\n  if (latestIdx < 0) {\n    throw new RegistryError(\n      'malformed_response',\n      `Manifest for ${slug} latest_hash not in versions list`,\n    );\n  }\n  const versionInt = manifest.versions.length - latestIdx;\n  const manifestVersion = manifest.versions[latestIdx];\n\n  const version = await client.getVersion(slug, manifest.latest_hash);\n  const envelope = version.signature ?? manifestVersion.signature ?? null;\n  if (!envelope) {\n    throw new RegistryError(\n      'unsigned_version',\n      `Version ${manifest.latest_hash} for ${slug} has no signature`,\n    );\n  }\n  const authorKeyId =\n    version.author_key_id ?? manifest.author_key_id ?? entry.authorKeyId ?? null;\n  const authorPubBase64 =\n    version.author_public_key ?? manifest.author_public_key ?? entry.authorPubBase64 ?? null;\n  if (!authorKeyId || !authorPubBase64) {\n    throw new RegistryError(\n      'author_not_claimed',\n      `${slug}: cannot verify ${manifest.latest_hash} \u2014 registry returned no author identity`,\n    );\n  }\n\n  const recomputed = skillContentHash(version.bundle);\n  const legacyPollutedHash = canonicalContentHash(version.bundle);\n  const stampedHash =\n    legacyPollutedHash === version.content_hash ? legacyPollutedHash : recomputed;\n  if (recomputed !== version.content_hash && legacyPollutedHash !== version.content_hash) {\n    throw new SignatureError(\n      'signature_invalid',\n      `${slug} bundle hashed to ${recomputed}, server stamped ${version.content_hash}`,\n    );\n  }\n  if (\n    recomputed !== `${CONTENT_HASH_PREFIX}${stripPrefix(manifest.latest_hash)}` &&\n    legacyPollutedHash !== `${CONTENT_HASH_PREFIX}${stripPrefix(manifest.latest_hash)}`\n  ) {\n    throw new SignatureError(\n      'signature_invalid',\n      `${slug} bundle hash ${recomputed} does not match manifest latest_hash ${manifest.latest_hash}`,\n    );\n  }\n\n  const author = handleFromSlug(slug);\n  // Bind the served (key_id, pub) BEFORE pinning: key_id MUST equal hex(pub).\n  // A hostile registry could otherwise pin a victim's key_id against an\n  // attacker-held pub and serve attacker-signed content past the TOFU check.\n  assertKeyIdBindsPub(authorKeyId, authorPubBase64);\n  // TOFU-resolve the author's PRIMARY key. This pins (first-sight) or loads the\n  // primary key the whole trust chain roots in \u2014 for both the direct and the\n  // delegated paths. `pinned` is the locally-pinned material, NOT the\n  // registry-served key (design \u00A79.4): a device cert is verified against this.\n  const { keyObject, pinnedPrimary, needsPinAfterVerify } = await authorKeyForVerification(\n    author,\n    { key_id: authorKeyId, pub: authorPubBase64 },\n    pinDir,\n  );\n\n  let delegation: SignedDelegation | null = null;\n  if (isSessionAttestedSignature(envelope)) {\n    // Registry attested this version at publish time via verified session.\n    // Content-hash checks above are the integrity gate on pull.\n  } else if (envelope.key_id === authorKeyId) {\n    if (!isEd25519Signature(envelope)) {\n      throw new SignatureError(\n        'signature_invalid',\n        `unsupported alg ${JSON.stringify((envelope as Signature).alg)} for direct author signature`,\n      );\n    }\n    verifyEnvelope(stampedHash, envelope, keyObject, {\n      expectedKeyId: authorKeyId,\n      binding: isBundleSignatureV2(envelope)\n        ? envelopeBindingFromSlug(slug, versionInt, authorKeyId)\n        : undefined,\n    });\n  } else {\n    if (!isEd25519Signature(envelope)) {\n      throw new SignatureError(\n        'signature_invalid',\n        `unsupported alg ${JSON.stringify((envelope as Signature).alg)} for delegated signature`,\n      );\n    }\n    // \u2500\u2500 Delegated path: the version is signed by a DEVICE key. Verify\n    // device_sig \u2190 cert \u2190 the PINNED primary, fail-closed, honoring revocations.\n    // Minted versions are owner-signed, so the required action scope is 'approve'.\n    verifyDelegatedVersionSignature({\n      contentHash: stampedHash,\n      versionSignature: envelope,\n      signedDelegation: version.delegation,\n      pinnedPrimary: { keyId: pinnedPrimary.keyId, pub: pinnedPrimary.pub },\n      handle: author,\n      requiredScope: 'approve',\n      publishedAt: version.published_at,\n      revokedDeviceKeyIds: revokedDeviceKeyIds,\n    });\n    delegation = version.delegation;\n  }\n  if (needsPinAfterVerify) {\n    await commitAuthorKeyPin(\n      author,\n      { key_id: authorKeyId, pub: authorPubBase64 },\n      versionInt,\n      pinDir,\n    );\n  }\n  // Touch signatureBytes so the contract that we sign the prefixed-hash\n  // STRING (not raw digest) stays load-bearing inside this module. verifyEnvelope\n  // already encodes via signatureBytes internally; calling it here is purely\n  // defensive against a future refactor that bypasses the wrapper.\n  signatureBytes(stampedHash);\n\n  return {\n    version,\n    recomputed,\n    envelope,\n    versionInt,\n    versionLabel:\n      sanitizeVersionLabel(version.version_label) ??\n      sanitizeVersionLabel(manifestVersion.version_label) ??\n      null,\n    authorKeyId,\n    authorPubBase64,\n    delegation,\n  };\n}\n\nfunction buildClientOpts(baseUrl: string, opts: PullOptions): RegistryClientOptions {\n  return { baseUrl, token: opts.token, fetchImpl: opts.fetchImpl };\n}\n\nfunction stripPrefix(s: string): string {\n  return s.startsWith(CONTENT_HASH_PREFIX) ? s.slice(CONTENT_HASH_PREFIX.length) : s;\n}\n\n/** True when manifest hash includes legacy `.skillet-backup` paths but store bytes match skill content. */\nasync function legacyPollutedManifestMatches(\n  client: RegistryClient,\n  slug: string,\n  manifestHash: string,\n  storeSkillHash: string,\n): Promise<boolean> {\n  try {\n    const version = await client.getVersion(slug, stripPrefix(manifestHash));\n    const full = canonicalContentHash(version.bundle);\n    const stripped = skillContentHash(version.bundle);\n    return full === manifestHash && stripped === storeSkillHash;\n  } catch {\n    return false;\n  }\n}\n\nfunction handleFromSlug(slug: string): string {\n  const m = slug.match(/^@?([a-z0-9-]+)\\//);\n  if (!m) {\n    throw new RegistryError(\n      'invalid_slug',\n      `Cannot derive author handle from slug ${JSON.stringify(slug)}`,\n    );\n  }\n  return m[1];\n}\n", "/**\n * Pull each relevant author's revoked device-key set on sync.\n * Negative info is public \u2014 subscribers need it to refuse freshly delegated versions.\n */\nimport { parseSkillRef } from './identifier.js';\nimport type { KitState } from '../kit/types.js';\nimport { RegistryClient } from './client.js';\n\nfunction authorHandleFromEntry(slug: string, owner: string | null | undefined): string | null {\n  try {\n    const raw = owner ?? parseSkillRef(slug).author;\n    return raw.startsWith('@') ? raw.slice(1) : raw;\n  } catch {\n    return null;\n  }\n}\n\nexport interface RevokedDeviceKeyIdsResult {\n  ids: Set<string>;\n  /** False when we needed revocation data but every per-author fetch failed. */\n  ok: boolean;\n}\n\n/**\n * Best-effort union of revoked device key ids for every registry author in state.\n * Returns ok=false when all fetches failed but handles were present.\n */\nexport async function resolveRevokedDeviceKeyIds(\n  state: KitState,\n  registryUrl: string,\n  opts: { fetchImpl?: typeof fetch } = {},\n): Promise<RevokedDeviceKeyIdsResult> {\n  const handles = new Set<string>();\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (entry.source !== 'registry') continue;\n    const handle = authorHandleFromEntry(slug, entry.owner);\n    if (handle) handles.add(handle);\n  }\n  if (handles.size === 0) return { ids: new Set(), ok: true };\n\n  const client = new RegistryClient({\n    baseUrl: registryUrl,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n  const merged = new Set<string>();\n  let anySucceeded = false;\n  for (const handle of handles) {\n    try {\n      const ids = await client.listAuthorRevokedDeviceKeys(handle);\n      anySucceeded = true;\n      for (const id of ids) merged.add(id);\n    } catch {\n      // Registry unreachable or author unknown \u2014 skip this handle.\n    }\n  }\n  return { ids: merged, ok: anySucceeded };\n}\n", "import { RegistryClient } from './client.js';\n\n/** Best-effort install counter \u2014 never fail the caller path. */\nexport function pingInstallMetric(client: RegistryClient, ref: string): void {\n  void client.recordInstall(ref).catch(() => undefined);\n}\n", "import { RegistryClient } from '../registry/client.js';\nimport { readDeviceFile } from '../device-token.js';\nimport { readEditedReported, setEditedReported } from '../kit/store.js';\nimport type { RegistryBearerKind } from '../auth-token.js';\nimport type { SkillEntry } from '../kit/types.js';\n\nexport interface ReportDeviceAgentsOptions {\n  registryUrl: string;\n  token: string;\n  bearerKind: RegistryBearerKind;\n  agents: string[];\n  fetchImpl?: typeof fetch;\n}\n\n/**\n * After sync, report detected runtimes for this machine's connected device row.\n * Skips kit-keys and machines without a linked device_id (session-only with no pair).\n */\nexport async function reportDeviceAgents(opts: ReportDeviceAgentsOptions): Promise<void> {\n  if (opts.bearerKind === 'kit' || opts.bearerKind === 'none' || !opts.token) return;\n  if (opts.agents.length === 0) return;\n\n  const meta = await readDeviceFile();\n  const deviceId = meta?.device_id;\n  if (!deviceId) return;\n\n  const client = new RegistryClient({\n    baseUrl: opts.registryUrl,\n    token: opts.token,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n  await client.reportDeviceAgents(deviceId, opts.agents);\n}\n\n/** Best-effort \u2014 sync must not fail when the registry is unreachable. */\nexport function pingDeviceAgents(opts: ReportDeviceAgentsOptions): void {\n  void reportDeviceAgents(opts).catch(() => undefined);\n}\n\nexport type MaterializationStatus = 'materialized' | 'skipped-not-detected' | 'failed';\n\nexport interface SkillRuntimeMaterialization {\n  skill_slug: string;\n  runtime: string;\n  status: MaterializationStatus;\n}\n\n/** The subset of a SyncResult needed to derive per-skill/per-runtime status. */\nexport interface MaterializationSource {\n  materialized: Array<{ slug: string; dest: string }>;\n  adapters: Array<{ name: string; status: MaterializationStatus; paths: string[] }>;\n  failed: Array<{ slug: string }>;\n}\n\n/**\n * Map a sync result to a COMPLETE per-skill \u00D7 per-detected-runtime status matrix\n * the web can animate honestly. For every skill touched this sync and every\n * detected runtime (one the agent is installed in), emit the true outcome:\n *   - `materialized` \u2014 the skill's files were written into that runtime;\n *   - `failed` \u2014 the runtime is installed but the write failed (adapter threw,\n *     or the skill failed integrity verification);\n *   - `skipped-not-detected` \u2014 the runtime is installed but this skill wasn't\n *     routed there.\n * Runtimes the agent isn't installed in produce no rows (the web shows only the\n * device's detected runtimes). Completeness matters: a skill that lands nowhere\n * still reports a row per runtime, so the reveal never spins, and a write that\n * failed on an installed runtime is shown as failed, never as \"not installed\".\n */\nexport function deriveMaterializations(src: MaterializationSource): SkillRuntimeMaterialization[] {\n  const destToSlug = new Map(src.materialized.map((m) => [m.dest, m.slug]));\n  const failedSlugs = new Set(src.failed.map((f) => f.slug));\n  // Skills a reveal might be watching: anything written or integrity-failed.\n  const touched = new Set<string>([...src.materialized.map((m) => m.slug), ...failedSlugs]);\n  // Detected runtimes = adapters the agent is installed in (anything not\n  // skipped-not-detected), including ones that failed mid-materialize.\n  const detected = src.adapters.filter((a) => a.status !== 'skipped-not-detected');\n  // For each materialized adapter, the slugs it actually wrote.\n  const writtenByAdapter = new Map<string, Set<string>>();\n  for (const a of src.adapters) {\n    if (a.status !== 'materialized') continue;\n    const written = new Set<string>();\n    for (const p of a.paths) {\n      const slug = destToSlug.get(p);\n      if (slug) written.add(slug);\n    }\n    writtenByAdapter.set(a.name, written);\n  }\n\n  const out: SkillRuntimeMaterialization[] = [];\n  for (const slug of touched) {\n    for (const a of detected) {\n      let status: MaterializationStatus;\n      if (a.status === 'failed') {\n        status = 'failed';\n      } else if (writtenByAdapter.get(a.name)?.has(slug)) {\n        status = 'materialized';\n      } else if (failedSlugs.has(slug)) {\n        status = 'failed';\n      } else {\n        status = 'skipped-not-detected';\n      }\n      out.push({ skill_slug: slug, runtime: a.name, status });\n    }\n  }\n  return out;\n}\n\n/**\n * A skill this device currently keeps a LOCAL edit of (KTD2). Carries only the\n * ref plus its fork lineage baseline \u2014 never filenames, counts, or content (R2).\n */\nexport interface EditedSkill {\n  /** Canonical `@owner/slug` ref (or the bare state key when unowned). */\n  ref: string;\n  /** Baseline version label from the fork lineage; integer version stringified. */\n  baselineVersion: string | null;\n  /** Baseline content hash \u2014 the lineage identity, never the edited content. */\n  baselineHash: string;\n}\n\n/**\n * The set of skills this device currently keeps a local edit of: every state\n * entry with a `customized_from` lineage. Reported alongside the post-sync\n * materialization report; the registry reconciles its edit flags to EXACTLY this\n * set (KTD2). A skill that un-customized this sync (take-theirs / restore cleared\n * `customized_from`) is simply absent, driving the registry's delete-by-absence\n * (R3). Only ref + baseline leave the machine \u2014 never content (R2).\n */\nexport function deriveEditedSkills(skills: Record<string, SkillEntry>): EditedSkill[] {\n  const out: EditedSkill[] = [];\n  for (const [slug, entry] of Object.entries(skills)) {\n    const lineage = entry.customized_from;\n    if (!lineage) continue;\n    const ref = slug.startsWith('@')\n      ? slug\n      : entry.owner\n        ? `@${entry.owner}/${entry.slug}`\n        : slug;\n    out.push({\n      ref,\n      baselineVersion: typeof lineage.version === 'number' ? String(lineage.version) : null,\n      baselineHash: lineage.hash,\n    });\n  }\n  return out;\n}\n\nexport interface ReportDeviceMaterializationsOptions {\n  registryUrl: string;\n  token: string;\n  bearerKind: RegistryBearerKind;\n  materializations: SkillRuntimeMaterialization[];\n  /** Currently-customized skills (KTD2) \u2014 ref + baseline only, reconciled by absence. */\n  edited: EditedSkill[];\n  fetchImpl?: typeof fetch;\n}\n\nexport async function reportDeviceMaterializations(\n  opts: ReportDeviceMaterializationsOptions,\n): Promise<void> {\n  if (opts.bearerKind === 'kit' || opts.bearerKind === 'none' || !opts.token) return;\n\n  // The registry reconciles its per-device edit-flags to EXACTLY the edited set\n  // in each report \u2014 a skill no longer present is deleted by absence (KTD2/R3).\n  // So the empty edited set must still be SENT when a device un-customizes its\n  // LAST edited skill, even in a sync that materializes nothing (a simultaneous\n  // prune, or nothing else changed). Skipping it leaves the stale\n  // `device_skill_edits` row in place, holding that skill's updates out of\n  // bulk-approve indefinitely. We track whether the last report carried edits\n  // (a marker in local state) and force the report on the transition FROM\n  // having-reported-edits TO empty \u2014 sending `edited: []` explicitly so the\n  // registry reconciles-to-empty rather than skipping.\n  const hadReportedEdits = await readEditedReported();\n  const clearingReport = opts.edited.length === 0 && hadReportedEdits;\n  // Fire when there's anything to reconcile: a materialization matrix to record,\n  // a non-empty edited set (it must ride every report where it's non-empty even\n  // if nothing materialized \u2014 a held customized skill materializes nothing), OR\n  // the transition-to-empty clearing case above. A device that never reported\n  // edits and materializes nothing rightly stays silent (no redundant report).\n  if (opts.materializations.length === 0 && opts.edited.length === 0 && !clearingReport) return;\n\n  const meta = await readDeviceFile();\n  const deviceId = meta?.device_id;\n  if (!deviceId) return;\n\n  const client = new RegistryClient({\n    baseUrl: opts.registryUrl,\n    token: opts.token,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n  await client.reportDeviceMaterializations(deviceId, opts.materializations, opts.edited);\n\n  // Persist the marker only AFTER a successful send so a report lost to a network\n  // error retries next sync (the clearing case isn't dropped by an optimistic\n  // flag flip). Set true whenever edits rode this report; clear it once the\n  // now-empty set has actually reached the registry.\n  if (opts.edited.length > 0) {\n    if (!hadReportedEdits) await setEditedReported(true);\n  } else if (hadReportedEdits) {\n    await setEditedReported(false);\n  }\n}\n\n/** Best-effort \u2014 sync must not fail when the registry is unreachable. */\nexport function pingDeviceMaterializations(opts: ReportDeviceMaterializationsOptions): void {\n  void reportDeviceMaterializations(opts).catch(() => undefined);\n}\n", "import type { MaterializeOptions } from \"../adapter.js\";\nimport {\n  BUNDLED_ROUTE_MATERIALIZE_DIR,\n  BUNDLED_ROUTE_SLUG,\n} from \"../commands/route.js\";\n\nexport function bareAdapterSlug(slug: string, owner: string | null): string {\n  if (owner && slug.startsWith(\"@\")) {\n    const idx = slug.indexOf(\"/\");\n    if (idx >= 0) return slug.slice(idx + 1);\n  }\n  return slug;\n}\n\nexport interface SkillMaterializeIdentity {\n  adapterSlug: string;\n  owner: string | null;\n  dirName?: string;\n}\n\nexport function skillMaterializeIdentity(\n  slug: string,\n  owner: string | null,\n): SkillMaterializeIdentity {\n  const adapterSlug = bareAdapterSlug(slug, owner);\n  if (slug === BUNDLED_ROUTE_SLUG) {\n    return {\n      adapterSlug,\n      owner,\n      dirName: BUNDLED_ROUTE_MATERIALIZE_DIR,\n    };\n  }\n  return { adapterSlug, owner };\n}\n\nexport function materializeOptsForIdentity(\n  identity: SkillMaterializeIdentity,\n  cwd?: string,\n  extra?: Pick<MaterializeOptions, \"description\">,\n): MaterializeOptions {\n  return {\n    owner: identity.owner,\n    cwd,\n    ...(identity.dirName ? { dirName: identity.dirName } : {}),\n    ...(extra?.description ? { description: extra.description } : {}),\n  };\n}\n", "import { readFile, readdir, lstat, rm } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join, relative, sep, basename } from 'node:path'\nimport matter from 'gray-matter'\nimport { readBundleFromDir } from '../bundle/read.js'\nimport { skilletDir } from '../session-token.js'\nimport { clearOldTrash } from './restore.js'\nimport {\n  ledgerStamp,\n  writeRunManifest,\n  moveDir,\n  detectDriftedGlobalCopies,\n  backupSkillVersion,\n  stashBaselineVersion,\n  clearBaselineStash,\n} from './edits-store.js'\nimport { ensureBundledRouteSkill } from './bundled-route-skill.js'\nimport { BUNDLED_ROUTE_SLUG } from './route.js'\nimport { canonicalContentHash, type DecodedBundle, skillContentHash, stripSkilletBackupPaths } from '@skillet/protocol'\nimport { parseSkillRef } from '../registry/identifier.js'\nimport { materializeSlugDir } from '../bundle/write.js'\nimport { atomicWrite } from '../util/atomic.js'\nimport { AdapterSkipError, type Adapter } from '../adapter.js'\nimport {\n  readState,\n  writeState,\n  readBundleFromSkillStore,\n  writeBundleToSkillStore,\n  skillContentPath,\n  skillContentDir,\n  upsertSkill,\n} from '../kit/store.js'\nimport { collapsePublishedTwins } from '../kit/dedup-twins.js'\nimport { writeLockFile } from '../lock.js'\nimport {\n  recordEvent,\n  detectInitiator,\n  maybeDiscloseActivity,\n  reportAvailability,\n  activityState,\n} from '../metrics.js'\nimport { loadAuthorKey } from '../signing/index.js'\nimport {\n  verifyEnvelope,\n  SignatureError,\n  envelopeBindingFromSlug,\n  isBundleSignatureV2,\n} from '../signing/envelope.js'\nimport { isSessionAttestedSignature, isEd25519Signature } from '../signing/session-attest.js'\nimport {\n  verifyDelegatedVersionSignature,\n  DelegationError,\n} from '../signing/delegation.js'\nimport { listPinnedHandles, loadPinnedKey, authorKeyForVerification, commitAuthorKeyPin } from '../signing/pin.js'\nimport {\n  summarizeInstall,\n  renderUpdateReview,\n  checkLock,\n  recordApproval,\n  checkRejection,\n  getLastApprovedVersion,\n  defaultApprovalLockPath,\n  promptApproval,\n  promptQuarantineConsent,\n  requiresQuarantineConsent,\n  loadPolicy,\n  resolveTrustMode,\n  type TrustPolicyFile,\n} from '../trust/index.js'\nimport { validateAdapterRoot } from '../util/pathsafe.js'\nimport type { SkillEntry, KitState } from '../kit/types.js'\nimport { pullRegistryUpdates, pullFromUnionManifest, type PullOutcome } from '../registry/pull.js'\nimport { RegistryError } from '../registry/client.js'\nimport { resolveRevokedDeviceKeyIds } from '../registry/revoked-device-keys.js'\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js'\nimport { loadRegistryBearer } from '../auth-token.js'\nimport { readActiveDeviceFile } from '../device-token.js'\nimport { RegistryClient } from '../registry/client.js'\nimport { pingInstallMetric } from '../registry/install-metric.js'\nimport {\n  pingDeviceAgents,\n  pingDeviceMaterializations,\n  deriveMaterializations,\n  deriveEditedSkills,\n} from './report-device-agents.js'\nimport { isKitSyncedSkill, kitSyncedState, isSkilletSystemSkill } from '../kit/sync-scope.js'\nimport {\n  materializeOptsForIdentity,\n  skillMaterializeIdentity,\n} from '../kit/materialize-identity.js'\n\nexport interface SyncOptions {\n  /** XDG_CONFIG_HOME equivalent for loading user's own signing key */\n  configDir?: string\n  /** Override the approval lock path (defaults to $XDG_DATA_HOME/skillet/skillet.lock) */\n  approvalLockPath?: string\n  /**\n   * Override the update-trust policy path (defaults to\n   * $XDG_CONFIG_HOME/skillet/trust-policy.json). Tests inject a temp path.\n   */\n  policyPath?: string\n  /** Override the TOFU pinned-keys directory (defaults to $XDG_CONFIG_HOME/skillet/pinned) */\n  pinDir?: string\n  /** Output stream for diff/prompt (defaults to process.stdout) */\n  output?: NodeJS.WritableStream\n  /** Input stream for approval prompt (defaults to process.stdin) */\n  input?: NodeJS.ReadableStream\n  /**\n   * Pre-approve quarantined-version materialization for non-TTY runs.\n   * Defaults to false; CI without this flag refuses to materialize quarantined\n   * entries, surfacing them in the skip list. TTY runs ignore this flag \u2014\n   * the interactive extra-consent prompt is the only gate.\n   */\n  allowQuarantined?: boolean\n  /**\n   * Per-slug quarantine consent grants: each listed slug materializes as if\n   * `allowQuarantined` were set, WITHOUT widening consent to any other slug in\n   * the same run. Written by review surfaces (the home menu) after the user\n   * explicitly confirmed that skill's harm-scan findings \u2014 a grant is exactly\n   * as wide as what the user saw and accepted.\n   */\n  allowQuarantinedSlugs?: string[]\n  /**\n   * When set, force the registry-pull phase to interactive (pull every\n   * non-pinned entry) or unattended (skip pull entirely, headless rule) mode\n   * regardless of TTY detection. Tests use this; humans rarely need it.\n   */\n  pullMode?: 'interactive' | 'unattended'\n  /** Inject fetch impl for the registry-pull phase (tests). */\n  fetchImpl?: typeof fetch\n  /** Bearer token to pass through to the registry-pull phase. */\n  token?: string\n  /**\n   * Registry base URL for the union-manifest fetch. Defaults to\n   * REGISTRY_URL_DEFAULT. Callers that hold a token SHOULD set this to the\n   * URL the token was issued from so the right server is queried.\n   */\n  registryUrl?: string\n  /**\n   * When true, skip the interactive approval prompt and auto-approve\n   * the graded diff for every incoming skill. Equivalent to setting the\n   * SKILLET_APPROVE_PRE=1 env var. Intended for tests and headless CI that use\n   * kit-key auth (SKILLET_TOKEN=skillet_k_\u2026).\n   */\n  approvePre?: boolean\n  /**\n   * When true, skip the graded-diff approval prompt (e.g. `skillet add -y`).\n   * Records approval in the lock without printing the SKILLET_APPROVE_PRE notice.\n   */\n  autoApprove?: boolean\n  /** Override the etag cache path used by the registry-pull phase. */\n  etagCachePath?: string\n  /**\n   * When true, skip per-skill `Skipped \"\u2026\"` stdout lines during materialize.\n   * Failures still land in `SyncResult.failed`. CLI uses this when rendering a\n   * grouped kit plan instead of inline skip messages.\n   */\n  quietSkipLines?: boolean\n  /**\n   * When set, materialize only these slugs. Used by `skillet add` / `add kit`.\n   * Entries need not be kit-synced (`sourceKit`) when listed here.\n   */\n  slugs?: string[]\n  /**\n   * Skip registry pull phases (union manifest + per-skill pull). `add` uses\n   * this after the skill is already in local kit state.\n   */\n  skipPull?: boolean\n  /**\n   * Adapter names that bypass detect() and always materialize (universal\n   * `.agents/skills` baseline from the CLI).\n   */\n  baselineAdapterNames?: string[]\n  /**\n   * Runtime names for detected agents that READ the universal `.agents/skills`\n   * baseline instead of materializing their own dir (e.g. `opencode`). They are\n   * appended to the availability report because every skill written to the\n   * baseline is also present for them \u2014 without adding a second materialization.\n   * The CLI computes these from its baseline-reader adapters' detect().\n   */\n  readerRuntimes?: string[]\n  /**\n   * Detect registry changes (pull phases only) without materializing adapters.\n   * Sets `changed` on the result; skips prune, lock write, and metrics.\n   */\n  checkOnly?: boolean\n  /**\n   * Directory containing the bundled `@skillet/route` meta-skill. When set, sync\n   * ensures that skill is present in the kit before materializing.\n   */\n  bundledRouteSkillDir?: string\n  /**\n   * The route skill's SKILL.md inlined at bundle time. Used as a fallback when\n   * `bundledRouteSkillDir` isn't on disk \u2014 the packaged desktop sidecar, whose\n   * pkg snapshot never carries `dist/bundled-skills`.\n   */\n  bundledRouteSkillMd?: string\n}\n\nexport type AdapterResultStatus = 'materialized' | 'skipped-not-detected' | 'failed'\n\nexport interface AdapterResult {\n  name: string\n  status: AdapterResultStatus\n  targetDir: string\n  /** Number of skills materialized into this adapter (0 when skipped/failed). */\n  count: number\n  /** Materialized destination paths for this adapter (every written file). */\n  paths: string[]\n  /** Error message when `status === \"failed\"`. */\n  error?: string\n  /**\n   * Non-fatal warnings surfaced by this adapter (e.g. OpenClaw shadow\n   * detection). Empty when the adapter has nothing to flag. Status is not\n   * downgraded \u2014 sync still materializes; the warning is informational.\n   */\n  warnings: string[]\n}\n\nexport interface SyncResult {\n  /**\n   * Flat list of every (adapter \u00D7 skill) write that succeeded.\n   * Kept for backward compatibility with prior callers.\n   */\n  materialized: Array<{ slug: string; dest: string; hash: string }>\n  /** Per-adapter outcome \u2014 one entry per adapter passed in, in input order. */\n  adapters: AdapterResult[]\n  /** Skills that were skipped because integrity verification failed. The\n   *  prior materialized files on disk are untouched for these slugs. */\n  failed: Array<{ slug: string; reason: string }>\n  /**\n   * Updates held for review during an interactive sync: content changed\n   * upstream and needs approval, so the approved on-disk version was left in\n   * place. Interactive sync never interrupts with per-skill diff prompts \u2014\n   * callers render this as a one-line summary pointing at `skillet pending`.\n   */\n  pendingReview: Array<{ slug: string; range: string }>\n  /**\n   * Per-entry outcome of the registry-pull phase that runs BEFORE\n   * the materialize loop. `updated` entries triggered a graded-diff prompt\n   * downstream; `failed` entries did not \u2014 their on-disk bytes were left\n   * untouched, so the materialize phase still proceeds against the prior\n   * approved version.\n   */\n  pull: PullOutcome[]\n  /**\n   * Per-entry outcome of the union-manifest pull phase (runs before\n   * the per-skill pull loop when a token is configured). `updated` means a\n   * new ref from a shared kit was fetched and added to local state.\n   */\n  unionPull: PullOutcome[]\n  /**\n   * Reconcile/prune: kit-derived skills that left your manifest (unsubscribed or\n   * routed off this machine) and were moved to the local trash. Reversible \u2014 the\n   * bundles sit under `trashDir` until you clear it. Only Skillet-written,\n   * unedited copies are moved; a customized skill that leaves the manifest is\n   * kept on disk instead (see `localized`).\n   */\n  pruned: Array<{ slug: string; adapters: string[] }>\n  /**\n   * Customized skills that left your manifest (unsubscribed / kit removed) and\n   * were kept on disk as plain LOCAL skills \u2014 the subscription linkage is\n   * dropped, the edited bytes stay live, and nothing is trashed (KTD7). No fork\n   * ceremony, no held updates.\n   */\n  localized: Array<{ slug: string }>\n  /** Where pruned bundles were moved this run (null when nothing was pruned). */\n  trashDir: string | null\n  /**\n   * Customized skills seen this run (KTD1/KTD3): an edit was found and left live\n   * in place, never materialized over. `hasUpdate` is true when a held author\n   * update is waiting AND unacknowledged \u2014 the quiet signal the CLI/desktop\n   * surface. Replaces the earlier capture/escalation/pause result fields.\n   */\n  customized: Array<{ slug: string; hasUpdate: boolean }>\n  lockPath: string\n  /** Non-fatal routing or account notices surfaced to the CLI summary. */\n  notices: string[]\n  /** Set when `checkOnly` \u2014 whether a full sync would materialize or prune. */\n  changed?: boolean\n}\n\n/**\n * Determines whether a skill update is DIFF-GATED (human must approve) or\n * AUTO-APPLIES, via the trust-policy precedence (skill > author > kit >\n * global-by-source-class). See trust/policy.ts for the resolution rules and\n * the two independent global defaults.\n *\n * This decides ONLY whether a human reviews the diff. It NEVER governs whether\n * the content is verified: even when this returns false (auto-apply), the\n * quarantine (scan) gate and verifyForMaterialize (Ed25519 signature)\n * gate below still run unconditionally. Trust governs review, not safety.\n */\n// Exported as the ONE approval gate: `skillet pending` must agree with sync\n// about what needs review, or held updates become invisible (a stale copy in\n// pending.ts once missed session-attested versions exactly this way).\nexport function requiresApproval(\n  entry: SkillEntry,\n  policy: TrustPolicyFile,\n  ownKeyId: string | null,\n  authorPinned?: boolean,\n  ownHandle?: string | null,\n): boolean {\n  // U5 Option B: session-attested registry versions require review \u2014 except\n  // your OWN skills. Editing your skill on the web IS the consent moment\n  // (add = consent baseline), and the web's pendingTargets deliberately never\n  // queues self-authored rows, so gating here left web edits of your own\n  // skills pending forever with no approval surface. The gate is also not a\n  // real hijacked-session defense: the web session is the account's approval\n  // surface, so a hijacker could approve their own edit anyway. Scan\n  // (quarantine) and signature verification still run unconditionally below.\n  //\n  // \"Self\" resolves by local signing key OR account handle: web-first\n  // accounts publish exclusively through web flows and never mint a local\n  // key, so key identity alone cannot recognize their own skills. The handle\n  // comes from the same trusted source (the registry) as authorKeyId, so it\n  // widens recognition, not the trust boundary.\n  if (entry.signature && isSessionAttestedSignature(entry.signature)) {\n    const keySelf =\n      ownKeyId != null && entry.authorKeyId != null && entry.authorKeyId === ownKeyId\n    const authorHandle = entryAuthorHandle(entry)\n    const handleSelf =\n      ownHandle != null && authorHandle != null && authorHandle === ownHandle\n    if (!keySelf && !handleSelf) return true\n    if (handleSelf && !keySelf) return false\n    // Key-self: fall through to resolveTrustMode, which resolves own-key\n    // content as auto.\n  }\n  const mode = resolveTrustMode(\n    {\n      slug: entry.slug,\n      authorKeyId: entry.authorKeyId ?? null,\n      source: entry.source,\n      sourceClass: entry.sourceClass ?? null,\n      sourceKit: entry.sourceKit ?? null,\n      subscriberTrust: entry.subscriberTrust ?? null,\n      authorPinned,\n    },\n    policy,\n    ownKeyId,\n  )\n  return mode === 'gate'\n}\n\n/** The author handle a state entry belongs to: explicit owner, else the\n *  `@author/slug` prefix. Null for unowned local content. */\nfunction entryAuthorHandle(entry: SkillEntry): string | null {\n  if (entry.owner) return entry.owner\n  if (entry.slug.startsWith('@')) {\n    const sep = entry.slug.indexOf('/')\n    if (sep > 1) return entry.slug.slice(1, sep)\n  }\n  return null\n}\n\nfunction pullOutcomesIndicateWork(outcomes: PullOutcome[]): boolean {\n  // 'gone' means a deleted-upstream skill that reconcile will prune \u2014 real work.\n  return outcomes.some(\n    (o) => o.status === 'updated' || o.status === 'failed' || o.status === 'gone',\n  )\n}\n\nfunction manifestPruneWouldRun(\n  state: KitState,\n  manifestRefs: Set<string> | null,\n  bearerKind: 'session' | 'device' | 'kit' | 'none' | 'unknown',\n  skipPull: boolean,\n): boolean {\n  if (skipPull || !manifestRefs) return false\n  if (bearerKind !== 'session' && bearerKind !== 'device') return false\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (!isKitSyncedSkill(entry)) continue\n    if (entry.source === 'registry' && !manifestRefs.has(slug)) return true\n  }\n  return false\n}\n\nasync function pendingGatedMaterialize(\n  state: KitState,\n  policy: TrustPolicyFile,\n  ownKeyId: string | null,\n  effectivePinDir: string,\n  approvalLockPath: string,\n  approvedHashes: Set<string>,\n  rejectedHashes: Set<string>,\n  ownHandle: string | null = null,\n): Promise<boolean> {\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (!isKitSyncedSkill(entry)) continue\n    if (entry.customized_from) continue // held updates never auto-materialize\n    const authorPinned = await isAuthorPinned(entry, slug, effectivePinDir)\n    if (!requiresApproval(entry, policy, ownKeyId, authorPinned, ownHandle)) continue\n    const bundle = await readBundleFromSkillStore(slug)\n    const currentHash = canonicalContentHash(bundle)\n    if (rejectedHashes.has(currentHash)) continue\n    if (approvedHashes.has(currentHash)) continue\n    const locallyApproved = await checkLock(approvalLockPath, slug, entry.version, currentHash)\n    if (locallyApproved) continue\n    const isRejected = await checkRejection(approvalLockPath, slug, entry.version)\n    if (isRejected) continue\n    return true\n  }\n  return false\n}\n\nexport async function isAuthorPinned(\n  entry: SkillEntry,\n  slug: string,\n  pinDir: string,\n): Promise<boolean | undefined> {\n  if (entry.source !== 'registry') return undefined\n  try {\n    let handle: string\n    if (entry.owner) {\n      handle = entry.owner.startsWith('@') ? entry.owner.slice(1) : entry.owner\n    } else if (slug.includes('/')) {\n      const [authorPart] = slug.startsWith('@') ? slug.slice(1).split('/') : slug.split('/')\n      handle = authorPart ?? ''\n    } else {\n      handle = parseSkillRef(slug.startsWith('@') ? slug : `@${slug}`).author\n    }\n    if (!handle) return false\n    const pinned = await loadPinnedKey(handle, pinDir)\n    return pinned !== null\n  } catch {\n    return false\n  }\n}\n\n/** Project adapters may resolve a different cwd than sync (e.g. desktop ~/.skillet). */\nasync function resolveAdapterMaterializeCwd(\n  adapter: Adapter,\n  syncCwd: string,\n): Promise<string> {\n  if (adapter.resolveMaterializeCwd) {\n    const resolved = await adapter.resolveMaterializeCwd(syncCwd)\n    if (resolved) return resolved\n  }\n  return syncCwd\n}\n\n/**\n * Reads all currently materialized files for each adapter's skill directory.\n *\n * Walks the full bundle tree under adapter.targetSkillDir(slug) so that every\n * bundle file (not just SKILL.md) appears in the graded diff. If the\n * skill directory does not exist yet, the adapter's prev state is empty (first\n * install).\n */\nasync function readCurrentMaterialized(\n  identity: ReturnType<typeof skillMaterializeIdentity>,\n  adapters: Adapter[],\n  cwd: string,\n): Promise<Record<string, Buffer>> {\n  const result: Record<string, Buffer> = {}\n  for (const adapter of adapters) {\n    const adapterCwd = await resolveAdapterMaterializeCwd(adapter, cwd)\n    if (adapter.kind === 'project' && !adapterCwd) continue\n    const skillDir = adapter.targetSkillDir(\n      identity.adapterSlug,\n      materializeOptsForIdentity(identity, adapterCwd),\n    )\n    await walkMaterialized(skillDir, skillDir, adapter.name, result)\n  }\n  return result\n}\n\nasync function walkMaterialized(\n  root: string,\n  dir: string,\n  adapterName: string,\n  out: Record<string, Buffer>,\n): Promise<void> {\n  let entries\n  try {\n    entries = await readdir(dir, { withFileTypes: true })\n  } catch {\n    return\n  }\n  for (const entry of entries) {\n    const absPath = join(dir, entry.name)\n    let st\n    try {\n      st = await lstat(absPath)\n    } catch {\n      continue\n    }\n    if (st.isDirectory()) {\n      await walkMaterialized(root, absPath, adapterName, out)\n    } else if (st.isFile()) {\n      if (entry.name.endsWith('.skillet-backup')) continue\n      const rel = relative(root, absPath)\n      const posix = sep === '/' ? rel : rel.split(sep).join('/')\n      out[`${adapterName}/${posix}`] = await readFile(absPath)\n    }\n  }\n}\n\n/**\n * Per acceptance criterion 3 + PROTOCOL \u00A76.4:\n *\n *   \"Verify the signature and recompute the content hash before writing.\n *    Hash mismatch or bad signature aborts that skill (`integrity_failed`)\n *    and leaves existing files untouched.\"\n *\n * Returns null on success. Returns a reason string on failure \u2014 caller MUST\n * skip materialize for this slug, leaving any prior on-disk copy in place.\n *\n * The TOFU resolution happens here: a registry-sourced skill seen for the\n * first time pins the served pubkey; a subsequent run with a different\n * pubkey throws `key_id_mismatch` (loud, never silent \u2014 PROTOCOL \u00A74).\n *\n * Exported so callers and tests can exercise the integrity gate directly\n * without standing up adapters/state.\n */\nexport async function verifyForMaterialize(\n  entry: SkillEntry,\n  recomputedContentHash: string,\n  pinDir: string,\n  opts: {\n    revokedDeviceKeyIds?: Set<string>;\n    revocationFetchOk?: boolean;\n    /** Legacy polluted publish where entry.hash counted `.skillet-backup` paths. */\n    legacyContentHash?: string;\n  } = {},\n): Promise<string | null> {\n  const hashMatchesEntry = (storeHash: string): boolean =>\n    storeHash === entry.hash ||\n    (opts.legacyContentHash != null && opts.legacyContentHash === entry.hash);\n  // Locally-imported skills are not signed; the recomputed hash is the\n  // only integrity anchor.\n  if (entry.source === 'local') {\n    // entry.hash is already the canonical `sha256:`-prefixed bundle hash\n    // compare verbatim, no hashRef wrapper.\n    if (!hashMatchesEntry(recomputedContentHash)) {\n      return `integrity_failed: local content hash drifted (${recomputedContentHash} vs ${entry.hash})`\n    }\n    return null\n  }\n\n  // Registry-sourced: signature required; session-attested versions use\n  // content-hash match (registry attested at publish), Ed25519/delegated\n  // paths require author key material.\n  if (!entry.signature) {\n    return 'integrity_failed: registry-sourced skill missing signature envelope'\n  }\n\n  if (isSessionAttestedSignature(entry.signature)) {\n    if (!hashMatchesEntry(recomputedContentHash)) {\n      return `integrity_failed: session-attested content hash drifted (${recomputedContentHash} vs ${entry.hash})`\n    }\n    return null\n  }\n\n  if (!entry.authorKeyId || !entry.authorPubBase64) {\n    return 'integrity_failed: registry-sourced skill missing author key material'\n  }\n\n  try {\n    if (!isEd25519Signature(entry.signature)) {\n      return 'integrity_failed: registry-sourced skill has unsupported signature alg'\n    }\n    if (entry.signature.sig_version === 2 && !isBundleSignatureV2(entry.signature)) {\n      return 'integrity_failed: signature claims v2 but envelope is not v2-bound'\n    }\n    const handle = await resolveMaterializeHandle(entry, pinDir)\n    const { keyObject, pinnedPrimary, needsPinAfterVerify } = await authorKeyForVerification(\n      handle,\n      { key_id: entry.authorKeyId, pub: entry.authorPubBase64 },\n      pinDir,\n    )\n    if (entry.signature.key_id === entry.authorKeyId) {\n      const binding = isBundleSignatureV2(entry.signature)\n        ? envelopeBindingFromSlug(\n            entry.slug,\n            entry.version,\n            entry.authorKeyId,\n            entry.owner,\n            entry.name,\n          )\n        : undefined\n      verifyEnvelope(recomputedContentHash, entry.signature, keyObject, {\n        expectedKeyId: entry.authorKeyId,\n        binding,\n      })\n    } else {\n      if (opts.revocationFetchOk === false) {\n        return 'integrity_failed: device-key revocation list unavailable'\n      }\n      verifyDelegatedVersionSignature({\n        contentHash: recomputedContentHash,\n        versionSignature: entry.signature,\n        signedDelegation: entry.delegation,\n        pinnedPrimary: { keyId: pinnedPrimary.keyId, pub: pinnedPrimary.pub },\n        handle,\n        requiredScope: 'approve',\n        revokedDeviceKeyIds: opts.revokedDeviceKeyIds,\n      })\n    }\n    if (needsPinAfterVerify) {\n      await commitAuthorKeyPin(\n        handle,\n        { key_id: entry.authorKeyId, pub: entry.authorPubBase64 },\n        entry.version,\n        pinDir,\n      )\n    }\n  } catch (err) {\n    if (err instanceof SignatureError) {\n      return `${err.code}: ${err.message.replace(/^[a-z_]+: /, '')}`\n    }\n    if (err instanceof DelegationError) {\n      return `${err.code}: ${err.message}`\n    }\n    return `integrity_failed: ${(err as Error).message}`\n  }\n  return null\n}\n\n/** Extract the handle from a slug like `@taylor/festival-ops` \u2192 `taylor`. */\nfunction handleFromSlug(slug: string): string {\n  const m = slug.match(/^@?([a-z0-9-]+)\\//)\n  if (!m) {\n    throw new Error(`Cannot derive handle from slug ${JSON.stringify(slug)}`)\n  }\n  return m[1]\n}\n\nasync function resolveMaterializeHandle(entry: SkillEntry, pinDir: string): Promise<string> {\n  if (entry.owner && entry.owner.length > 0) return entry.owner\n\n  try {\n    return handleFromSlug(entry.slug)\n  } catch {\n    // Legacy pre-canonical entries can store bare slugs. Fall back to the\n    // local TOFU pin store using the entry's author key material.\n  }\n\n  if (!entry.authorKeyId && !entry.authorPubBase64) {\n    throw new Error(`Cannot derive handle from slug ${JSON.stringify(entry.slug)}`)\n  }\n\n  const handles = await listPinnedHandles(pinDir)\n  const matches: string[] = []\n  for (const handle of handles) {\n    const pinned = await loadPinnedKey(handle, pinDir)\n    if (!pinned) continue\n    if (entry.authorKeyId && pinned.key_id === entry.authorKeyId) {\n      matches.push(handle)\n      continue\n    }\n    if (entry.authorPubBase64 && pinned.pub === entry.authorPubBase64) {\n      matches.push(handle)\n    }\n  }\n\n  if (matches.length === 1 && matches[0]) return matches[0]\n  if (matches.length > 1) {\n    throw new Error(\n      `Cannot derive unique handle for legacy slug ${JSON.stringify(entry.slug)}; matched pins: ${matches.join(', ')}`,\n    )\n  }\n  throw new Error(\n    `Cannot derive handle from slug ${JSON.stringify(entry.slug)} and no matching pinned author key`,\n  )\n}\n\n/**\n * Reconcile a customized skill's held-update marker against the freshly-pulled\n * upstream hash (`entry.hash` after the pull phase). Mutates `entry.held_update`\n * and returns whether it changed (so the caller persists only on a change):\n *  - upstream back at the customized baseline \u2192 clear any held update.\n *  - a NEW upstream hash (or first divergence) \u2192 record it (acknowledgement reset\n *    so the quiet signal surfaces again).\n *  - the same hash already held \u2192 no change (Keep mine's ack, if any, survives).\n */\nfunction reconcileHeldUpdate(entry: SkillEntry): boolean {\n  const base = entry.customized_from!.hash\n  const upstream = entry.hash\n  if (upstream === base) {\n    if (entry.held_update) {\n      delete entry.held_update\n      return true\n    }\n    return false\n  }\n  if (!entry.held_update || entry.held_update.hash !== upstream) {\n    entry.held_update = { version: entry.version, hash: upstream }\n    return true\n  }\n  return false\n}\n\n/**\n * A held update surfaces (nudges) when it exists, has not been acknowledged,\n * and is not YANKED. A yanked held version (the author pulled it) must never\n * nudge \u2014 installing it would resurrect a withdrawn version (F6).\n */\nfunction heldUpdateSurfaces(entry: SkillEntry): boolean {\n  return !!entry.held_update && !entry.held_update.acknowledged && !entry.held_update.yanked\n}\n\ninterface PruneResult {\n  pruned: Array<{ slug: string; adapters: string[] }>\n  /** Customized skills that left the manifest and were kept on disk as local skills. */\n  localized: Array<{ slug: string }>\n  trashDir: string | null\n}\n\n/**\n * Reconcile the machine to the manifest: skills that left your kits (you\n * unsubscribed, or routed the kit off this device) are removed from the\n * adapters and moved to `~/.skillet/trash/<run>/` \u2014 reversible, never a hard\n * delete.\n *\n * Deleting files is scary, so the rule is: only remove a skill when we can\n * cleanly account for EVERY adapter copy. Fences:\n *  1. Skillet owns it: only `source:'registry'`, kit-derived (`sourceKit`),\n *     non-pinned, canonical `@owner/slug`-keyed entries are touched. Local,\n *     pinned, directly-added, and alias-keyed entries are invisible to the pruner.\n *  2. You made it yours: a `customized_from` skill that leaves the manifest is\n *     kept on disk as a plain LOCAL skill (subscription linkage dropped, bytes\n *     kept \u2014 KTD7); it is never trashed. Any other readable edit (hash \u2260 what we\n *     wrote) is unverifiable and KEEPS the skill managed rather than deleting it.\n *  3. Authoritative only: the caller passes `manifestRefs` solely on a confirmed\n *     full-union (session/device) 200 \u2014 never on 304/401/error, never kit-key.\n *  4. Global adapters only: project-scoped adapters (Cursor/Windsurf/Devin/\u2026)\n *     are skipped \u2014 their copies live inside the user's project repo, are keyed\n *     per-directory, and an account-wide sync must never reach into a repo to\n *     delete files. Those copies are managed per-project, not here.\n *  5. Account for every (global) copy: a dir we can't read (transformed layout,\n *     permission error, symlink) or a global adapter that won't resolve is\n *     \"unverifiable\" \u2192 KEEP the skill rather than risk orphaning a copy we\n *     couldn't see. Trash happens only when every copy is absent or a clean\n *     verbatim match, and we drop state only once every copy has moved.\n *  6. Empty-manifest guard: an empty manifest zeroes the machine out only for an\n *     account-bound caller (`allowZeroOut`); otherwise it's ignored.\n *\n * Conservative by design: a global transforming adapter would also be KEPT\n * (unverifiable). Complete coverage of non-verbatim layouts needs adapter-aware\n * removal \u2014 a deliberate follow-up.\n */\n/**\n * Whether an EMPTY manifest may zero a machine out. Allowed only for an\n * account-bound caller: the server's `account_scope === 'user'` (so a bound\n * device that routed off every kit can zero out), or \u2014 for an older server that\n * omits the field \u2014 the session-only fallback.\n *\n * The parameter is `string | undefined` on purpose: `account_scope` arrives as\n * unvalidated JSON, so even though our types only admit `'user'`, an OLDER\n * self-hosted registry can still send the retired `'anonymous'` (or anything\n * else) at runtime. Fail safe: an empty manifest with an unrecognized scope\n * must NEVER zero local skills out.\n */\nexport function zeroOutAllowed(\n  accountScope: string | undefined,\n  bearerKind: string,\n): boolean {\n  if (accountScope === 'user') return true\n  if (accountScope !== undefined) return false // unrecognized scope \u2192 fail safe, never zero out\n  return bearerKind === 'session' // old server omitted the field \u2192 fallback\n}\n\n/**\n * Convert an unsubscribed customized (or edited) registry entry into a plain\n * local skill in place: keep the bytes and the entry, drop everything that\n * would make sync re-prune it or track author updates for it (KTD7).\n */\nfunction localizeCustomizedEntry(entry: SkillEntry): void {\n  entry.source = 'local'\n  delete entry.customized_from\n  delete entry.held_update\n  delete entry.sourceKit\n  delete entry.sourceKitId\n  delete entry.subscriberTrust\n  entry.updatedAt = new Date().toISOString()\n}\n\n/** Pull `name`/`description` out of a bundle's SKILL.md frontmatter, if present. */\nfunction nameDescFromBundle(bundle: DecodedBundle): { name?: string; description?: string } {\n  const skillMd = bundle.get('SKILL.md')\n  if (!skillMd) return {}\n  try {\n    const fm = matter(Buffer.from(skillMd).toString('utf8'))\n    const d = fm.data as Record<string, unknown>\n    const out: { name?: string; description?: string } = {}\n    if (typeof d.name === 'string' && d.name) out.name = d.name\n    if (typeof d.description === 'string') out.description = d.description\n    return out\n  } catch {\n    return {}\n  }\n}\n\n/**\n * F4: before flipping a customized/edited unsubscribed skill to LOCAL, import\n * its LIVE on-disk bundle into the skill store and align the entry's\n * hash/name/description to it. Without this the store/record still points at the\n * old AUTHOR bytes, so a later store-based op (materialize, propose, re-sync)\n * resurrects the wrong content. Mutates `entry` in place.\n */\nasync function importLiveTreeToStore(\n  slug: string,\n  bundle: DecodedBundle,\n  entry: SkillEntry,\n): Promise<void> {\n  await writeBundleToSkillStore(slug, bundle)\n  entry.hash = canonicalContentHash(bundle)\n  entry.materialized_hash = entry.hash\n  const nd = nameDescFromBundle(bundle)\n  if (nd.name) entry.name = nd.name\n  if (nd.description !== undefined) entry.description = nd.description\n}\n\nexport async function reconcilePrune(\n  state: KitState,\n  manifestRefs: Set<string>,\n  adapters: Adapter[],\n  opts: {\n    allowZeroOut?: boolean\n    /**\n     * Pre-pull hash/version per slug (RF5): mirrors the drift path's baseline\n     * fallback so a legacy entry (no `materialized_hash`) whose pull advanced\n     * `entry.hash` this run still baselines on what was actually on disk, not the\n     * just-persisted hash \u2014 else the last-materialized author bytes read as an\n     * \"edit\" and a racing unsubscribe localizes a phantom local skill.\n     */\n    prePullSnapshots?: Map<string, { hash: string; version: number }>\n  } = {},\n): Promise<PruneResult> {\n  // Fence 5 \u2014 empty-manifest guard (account-bound zero-out only).\n  if (manifestRefs.size === 0 && !opts.allowZeroOut) {\n    return { pruned: [], localized: [], trashDir: null }\n  }\n\n  const candidates = Object.entries(state.skills).filter(([slug, entry]) => {\n    if (entry.source !== 'registry') return false // never your local skills\n    if (!entry.sourceKit) return false // only kit-derived (skip directly-added)\n    if (entry.pinned) return false // never pinned\n    if (!slug.startsWith('@')) return false // only canonical @owner/slug keys (skip aliases)\n    return !manifestRefs.has(slug) // gone from your manifest \u2192 candidate\n  })\n  if (candidates.length === 0) return { pruned: [], localized: [], trashDir: null }\n\n  // Unique per run so back-to-back syncs can't clobber each other's trash/ledger.\n  const trashDir = join(skilletDir(), 'trash', ledgerStamp())\n  const pruned: PruneResult['pruned'] = []\n  const localized: PruneResult['localized'] = []\n  const ledger: Array<Record<string, unknown>> = []\n\n  for (const [slug, entry] of candidates) {\n    const owner = entry.owner ?? null\n    const identity = skillMaterializeIdentity(slug, owner)\n\n    // Inspect each GLOBAL adapter copy. Classify as absent, a clean verbatim\n    // match (movable), edited, or unverifiable (present but we can't read it).\n    //\n    // Project-scoped adapters are deliberately NOT pruned: their copies live\n    // inside the user's project repo, are keyed per-directory (some even share\n    // one rules dir across skills), and there's no single cwd that identifies\n    // which project a skill was synced into. Skillet must not reach into a repo\n    // to delete files during an account-wide sync \u2014 those copies are managed\n    // per-project. Leaving them is the safe, correct choice.\n    const movable: Array<{ name: string; dir: string }> = []\n    let edited = false\n    let unverifiable = false\n    // The live on-disk bundle to import if this skill localizes (F4). Prefer an\n    // edited copy (the user's actual bytes) over a clean one.\n    let liveBundle: DecodedBundle | null = null\n    // F1-prune: compare against what we LAST MATERIALIZED here, not `entry.hash`.\n    // `entry.hash` is advanced by the pull phase before materialize; a pull that\n    // persisted a new hash whose materialize never landed leaves the OLD author\n    // bytes on disk. Baselining on `entry.hash` would misread those as an edit\n    // and localize a phantom local skill when an unsubscribe races an update.\n    // RF5: fall back to the pre-pull snapshot (mirrors the drift path at the\n    // materialize baseline) so a LEGACY entry with no `materialized_hash` still\n    // baselines on the pre-pull bytes, not the just-advanced `entry.hash`.\n    const pruneBaseline =\n      entry.materialized_hash ?? opts.prePullSnapshots?.get(slug)?.hash ?? entry.hash\n    for (const adapter of adapters) {\n      if (adapter.kind === 'project') continue // never prune project-repo files\n      let dir: string\n      try {\n        dir = adapter.targetSkillDir(\n          identity.adapterSlug,\n          materializeOptsForIdentity(identity),\n        )\n      } catch {\n        unverifiable = true // a global adapter that can't resolve \u2192 don't risk it\n        continue\n      }\n      let st\n      try {\n        st = await lstat(dir)\n      } catch {\n        continue // ENOENT / unreachable \u2192 no copy here\n      }\n      if (st.isSymbolicLink()) {\n        unverifiable = true // never follow/move a symlinked skill dir\n        continue\n      }\n      if (!st.isDirectory()) continue\n      let bundle\n      try {\n        bundle = await readBundleFromDir(dir)\n      } catch {\n        unverifiable = true // exists but unreadable (transformed layout, EACCES)\n        continue\n      }\n      if (!bundle || bundle.size === 0) {\n        unverifiable = true // a dir is there but we can't make sense of it\n        continue\n      }\n      let onDiskHash: string | null = null\n      try {\n        onDiskHash = canonicalContentHash(bundle)\n      } catch {\n        edited = true // unhashable \u2192 treat as edited, never delete\n        continue\n      }\n      if (onDiskHash !== pruneBaseline) {\n        edited = true\n        liveBundle = bundle // the edited tree is the live one to preserve\n      } else {\n        movable.push({ name: adapter.name, dir })\n        if (!liveBundle) liveBundle = bundle\n      }\n    }\n\n    // Fence 2 (KTD7): a customized skill \u2014 or any skill with an edited on-disk\n    // copy \u2014 is yours. Keep the bytes exactly where they are and convert the\n    // entry to a plain LOCAL skill: drop the subscription linkage (sourceKit,\n    // held updates, the customized marker) so it is neither re-pruned nor\n    // update-tracked, but never trash an edit. No fork, no state removal.\n    if (entry.customized_from || edited) {\n      // F4: no readable live tree \u2192 we can't prove what the local bytes are, so\n      // keep the skill MANAGED (unverifiable) rather than mint a phantom local\n      // skill whose store points at stale author bytes.\n      if (!liveBundle) continue\n      // RF8: the entry is leaving the customized world for a plain local skill \u2014\n      // drop its baseline stash so the baselines store doesn't accumulate.\n      if (entry.customized_from) await clearBaselineStash(entry.customized_from.hash)\n      // Import the live edit into the store and align hash/name/description to it\n      // BEFORE flipping to local, so later store-based ops see the edit.\n      await importLiveTreeToStore(slug, liveBundle, entry)\n      localizeCustomizedEntry(entry)\n      localized.push({ slug })\n      continue\n    }\n\n    // Fence 4: a copy we couldn't account for \u2192 keep the skill managed entirely.\n    if (unverifiable) continue\n\n    if (movable.length === 0) {\n      // Cleanly accounted for, nothing on disk \u2192 drop the orphaned state entry.\n      delete state.skills[slug]\n      continue\n    }\n\n    // Move every copy; only drop state once they've ALL moved (no half-removal).\n    // Buffer this skill's moves; commit to the shared ledger only if ALL copies\n    // move. On partial failure, roll the moved copies back so the skill stays\n    // whole and the ledger never references a skill whose state we kept.\n    const perSkill: Array<{ name: string; from: string; to: string }> = []\n    let allMoved = true\n    for (const { name, dir } of movable) {\n      const dest = join(trashDir, name, basename(dir))\n      if (await moveDir(dir, dest)) {\n        perSkill.push({ name, from: dir, to: dest })\n      } else {\n        allMoved = false\n        break\n      }\n    }\n    if (allMoved && perSkill.length > 0) {\n      delete state.skills[slug]\n      for (const m of perSkill) {\n        ledger.push({ slug, owner, hash: entry.hash, adapter: m.name, from: m.from, to: m.to })\n      }\n      pruned.push({ slug, adapters: perSkill.map((m) => m.name) })\n    } else if (!allMoved) {\n      // Partial failure: move the trashed copies back to their source. The skill\n      // is kept whole; the next sync retries the prune cleanly.\n      for (const m of perSkill) await moveDir(m.to, m.from)\n    }\n  }\n\n  if (ledger.length > 0) {\n    await writeRunManifest(trashDir, {\n      trashedAt: new Date().toISOString(),\n      kind: 'prune',\n      items: ledger,\n    })\n  }\n\n  return { pruned, localized, trashDir: pruned.length > 0 ? trashDir : null }\n}\n\n/** Drop pre-0.1.24 `skillet--route` dirs after we materialize the flat `skillet` folder. */\nasync function removeLegacyBundledRouteMaterialization(\n  adapters: Adapter[],\n): Promise<void> {\n  for (const adapter of adapters) {\n    if (adapter.kind === 'project') continue\n    let legacyDir: string\n    try {\n      legacyDir = adapter.targetSkillDir('route', { owner: 'skillet' })\n    } catch {\n      continue\n    }\n    try {\n      await rm(legacyDir, { recursive: true, force: true })\n    } catch {\n      // Best-effort migration; never block sync.\n    }\n  }\n}\n\n// The fenced managed block + rule marker the OLD Windsurf adapter wrote.\nconst WINDSURF_MANAGED_START = '<!-- skillet:start -->'\nconst WINDSURF_MANAGED_END = '<!-- skillet:end -->'\nconst WINDSURF_RULE_MARKER = '<!-- skillet:skill '\n\n/**\n * Clean up artifacts the OLD (project-scoped, rules-flattening) Windsurf\n * adapter left in the sync's cwd, now that windsurf is a global skills-folder\n * materializer. Cwd-local by nature: the old adapter wrote\n * `.windsurf/rules/<owner>--<slug>.md` and a fenced block in `AGENTS.md` under\n * whatever cwd it ran in, and an account-wide sync must not reach into every\n * repo (prune policy). Recognition-gated and never removes user content: a\n * rule file goes only if it still carries our marker header; AGENTS.md loses\n * only the fenced block, never the file, and the file is never created.\n */\nasync function cleanupLegacyWindsurfArtifacts(cwd: string): Promise<void> {\n  const rulesDir = join(cwd, '.windsurf', 'rules')\n  let entries: string[]\n  try {\n    entries = await readdir(rulesDir)\n  } catch {\n    entries = []\n  }\n  for (const name of entries) {\n    if (!name.endsWith('.md')) continue\n    const filePath = join(rulesDir, name)\n    try {\n      const content = await readFile(filePath, 'utf8')\n      if (content.startsWith(WINDSURF_RULE_MARKER)) {\n        await rm(filePath, { force: true })\n      }\n    } catch {\n      // unreadable \u2192 leave it; never guess\n    }\n  }\n\n  const agentsMd = join(cwd, 'AGENTS.md')\n  try {\n    const existing = await readFile(agentsMd, 'utf8')\n    const startIdx = existing.indexOf(WINDSURF_MANAGED_START)\n    const endIdx = existing.indexOf(WINDSURF_MANAGED_END)\n    if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {\n      const before = existing.slice(0, startIdx).trimEnd()\n      const after = existing.slice(endIdx + WINDSURF_MANAGED_END.length).replace(/^\\n+/, '')\n      const next = after ? `${before}\\n\\n${after}\\n` : `${before}\\n`\n      await atomicWrite(agentsMd, next, { backup: true })\n    }\n  } catch {\n    // no AGENTS.md, or unreadable \u2192 nothing to strip\n  }\n}\n\n/**\n * Remove Skillet-managed materializations from Codex's LEGACY `~/.codex/skills`\n * root. Codex moved to `~/.agents/skills` in June 2026 but still reads the old\n * root, so pre-move copies surface as duplicates in skill selectors. A legacy\n * copy is ours-and-unedited when its content matches ANY hash Skillet recorded\n * for the skill \u2014 current store bundle, `materialized_hash`, or `entry.hash`;\n * matching only the current store would strand every legacy copy of a\n * since-updated skill (the common case). No match \u2192 the user edited it; leave\n * it and surface a notice. Removals go through the recoverable trash move.\n *\n * Scope note: this matches only dirs named the way CURRENT Skillet names them\n * (`<owner>--<slug>` via materializeSlugDir). Legacy copies written under a\n * different scheme (e.g. bare slugs) or by a non-Skillet installer are not\n * recognized and are deliberately left untouched \u2014 we never delete a dir we\n * cannot prove is our own.\n */\nasync function cleanupLegacyCodexSkills(\n  state: KitState,\n  notices: string[],\n): Promise<void> {\n  const legacyRoot = join(homedir(), '.codex', 'skills')\n  try {\n    await lstat(legacyRoot)\n  } catch {\n    return\n  }\n  const trashDir = join(skilletDir(), 'trash', ledgerStamp())\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    const identity = skillMaterializeIdentity(slug, entry.owner ?? null)\n    let legacyDir: string\n    try {\n      legacyDir = join(legacyRoot, materializeSlugDir(identity.adapterSlug, identity.owner, {}))\n    } catch {\n      continue\n    }\n    let st\n    try {\n      st = await lstat(legacyDir)\n    } catch {\n      continue\n    }\n    if (st.isSymbolicLink() || !st.isDirectory()) continue\n\n    let onDiskHash: string | null = null\n    try {\n      const bundle = await readBundleFromDir(legacyDir)\n      if (bundle && bundle.size > 0) onDiskHash = canonicalContentHash(bundle)\n    } catch {\n      onDiskHash = null\n    }\n    const known = new Set(\n      [entry.materialized_hash, entry.hash].filter((h): h is string => typeof h === 'string'),\n    )\n    try {\n      const storeBundle = await readBundleFromSkillStore(slug)\n      if (storeBundle && storeBundle.size > 0) known.add(canonicalContentHash(storeBundle))\n    } catch {\n      // store copy unreadable \u2014 rely on recorded hashes\n    }\n\n    if (onDiskHash && known.has(onDiskHash)) {\n      await moveDir(legacyDir, join(trashDir, `codex--${identity.adapterSlug}`))\n    } else {\n      notices.push(\n        `Legacy Codex copy of \"${slug}\" at ${legacyDir} differs from every version Skillet recorded \u2014 left in place; delete it manually if unwanted.`,\n      )\n    }\n  }\n}\n\n/**\n * Runtime names for the availability report: the materializing adapters that\n * were active, plus any detected baseline-READER runtimes (e.g. `opencode`) that\n * read the universal `.agents/skills` dir the baseline just wrote. Every skill\n * materialized to the baseline is present for those readers too, so they earn an\n * availability row without a second materialization. Deduped, order-stable.\n */\nexport function mergeAvailabilityRuntimes(\n  activeNames: string[],\n  readerRuntimes: string[] | undefined,\n): string[] {\n  return [...new Set([...activeNames, ...(readerRuntimes ?? [])])]\n}\n\nexport async function sync(\n  cwd: string,\n  adapters: Adapter[],\n  opts: SyncOptions = {},\n): Promise<SyncResult> {\n  const {\n    configDir = process.env['XDG_CONFIG_HOME'] ?? `${process.env['HOME']}/.config`,\n    approvalLockPath = defaultApprovalLockPath(),\n    pinDir,\n    output = process.stdout as unknown as NodeJS.WritableStream,\n    input = process.stdin as unknown as NodeJS.ReadableStream,\n    allowQuarantined = false,\n    allowQuarantinedSlugs = [],\n    quietSkipLines = false,\n  } = opts\n\n  const state = await readState()\n\n  // Self-heal stale \"published twin\" duplicates every sync (not just on a 200\n  // union pull). Publishing a local skill leaves a bare-key entry behind that\n  // the next manifest pull re-keys to `@owner/slug` \u2014 but that dedup only runs\n  // when the manifest returns 200. On a stable (304) manifest the bare twin\n  // never gets swept, so it lingers and inflates both the tray's \"only on this\n  // device\" count and the upload panel's capturable list. Collapse it here so\n  // the state converges regardless of manifest freshness, then best-effort drop\n  // the now-orphaned bare content dir (the canonical @owner/slug dir is kept).\n  const twins = collapsePublishedTwins(state)\n  if (twins.removed.length > 0) {\n    await writeState(state)\n    for (const key of twins.removed) {\n      try {\n        await rm(skillContentDir(key), { recursive: true, force: true })\n      } catch {\n        // Best-effort: an un-removable orphan dir is harmless \u2014 nothing keys it.\n      }\n    }\n  }\n\n  if (opts.bundledRouteSkillDir) {\n    try {\n      await ensureBundledRouteSkill(opts.bundledRouteSkillDir, opts.bundledRouteSkillMd)\n      // ensureBundledRouteSkill rewrote the store AND persisted state for the\n      // bundled route skill, but `state` above is a pre-ensure in-memory\n      // snapshot. Refresh just that entry so the materialize loop verifies the\n      // freshly-written store against the hash we just recorded. Without this,\n      // the FIRST sync after any router-content change compares new store bytes\n      // against the old snapshot hash, reads it as `integrity_failed: local\n      // content hash drifted`, and skips materializing the update until the\n      // next sync \u2014 so a shipped router change would not reach agents on the\n      // sync that installed it.\n      const refreshed = await readState()\n      const routeEntry = refreshed.skills[BUNDLED_ROUTE_SLUG]\n      if (routeEntry) state.skills[BUNDLED_ROUTE_SLUG] = routeEntry\n      else delete state.skills[BUNDLED_ROUTE_SLUG]\n    } catch {\n      // Best-effort: the bundled meta-skill must not block sync.\n    }\n  }\n  const materialized: SyncResult['materialized'] = []\n  const failed: SyncResult['failed'] = []\n  const pendingReview: SyncResult['pendingReview'] = []\n  const customized: SyncResult['customized'] = []\n\n  // Baseline for drift detection (R1/R2): entry {hash, version} BEFORE any pull\n  // phase bumps them. Drift is measured against what sync last wrote to disk,\n  // so an upstream update arriving this run is not misread as a hand edit \u2014\n  // and a hand edit sitting under an incoming update still is one. Hash and\n  // version are snapshotted TOGETHER: the customized lineage is built from this\n  // snapshot, so an update in the same run can't pair the post-pull version\n  // with the pre-pull hash.\n  const prePullSnapshots = new Map<string, { hash: string; version: number }>()\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    prePullSnapshots.set(slug, { hash: entry.hash, version: entry.version })\n  }\n\n  // Load the update-trust policy and the user's own key ID once.\n  // The policy drives the per-skill auto-apply vs diff-gate decision below;\n  // ownKeyId lets self-published updates auto-apply regardless of policy.\n  const policy = await loadPolicy(opts.policyPath)\n  let ownKeyId: string | null = null\n  try {\n    ownKeyId = (await loadAuthorKey(configDir)).keyId\n  } catch {\n    // No own signing key configured yet \u2014 fine; nothing resolves as self.\n  }\n\n  // Resolve bearer via device.json, then session.json / env.\n  const { token: effectiveToken, kind: bearerKind } = await loadRegistryBearer(opts.token)\n  const effectiveTokenOrUndef = effectiveToken || undefined\n  // This machine's device id \u2014 sent with the union pull so a session-authed CLI\n  // still gets per-device kit routing (the manifest scopes to it server-side).\n  const deviceId = (await readActiveDeviceFile())?.device_id\n  const isKitKey = effectiveTokenOrUndef?.startsWith('skillet_k_') ?? false\n  const approvePre = opts.approvePre === true || process.env['SKILLET_APPROVE_PRE'] === '1'\n  const autoApprove = opts.autoApprove === true\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '')\n  const effectivePinDir = pinDir ?? `${configDir.replace(/\\/$/, '')}/skillet/pinned`\n  const installClient = effectiveTokenOrUndef\n    ? new RegistryClient({\n        baseUrl: registryUrl,\n        token: effectiveTokenOrUndef,\n        ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n      })\n    : null\n  const installPinged = new Set<string>()\n\n  // U7: account-scoped decisions are the source of truth. Pull them once\n  // (best-effort) so they can drive the gate below: the account `update_mode`\n  // sets the external global trust default, server-approved versions short-circuit\n  // the prompt (and mirror into the local lock), and server rejections skip. On\n  // any failure we fall back to the local lock \u2014 sync still runs and the on-device\n  // signature + scan gates are unaffected (trust governs review, not safety).\n  const approvedHashes = new Set<string>()\n  const rejectedHashes = new Set<string>()\n  let accountUpdateMode: 'auto' | 'manual' | null = null\n  // The account handle resolves \"self\" for web-first accounts with no local\n  // signing key (see requiresApproval). Best-effort: offline, gate as before.\n  let ownHandle: string | null = null\n  if (installClient) {\n    try {\n      const acct = await installClient.getMyDecisions()\n      accountUpdateMode = acct.update_mode\n      for (const d of acct.decisions) {\n        if (d.state === 'approved') approvedHashes.add(d.version_hash)\n        else if (d.state === 'rejected') rejectedHashes.add(d.version_hash)\n      }\n    } catch {\n      // Offline or an older registry \u2014 fall back to the local lock.\n    }\n    ownHandle = (await installClient.whoami())?.handle ?? null\n  }\n  // Map the account mode onto the external global default (auto -> auto, manual ->\n  // gate). Per-skill/author/kit overrides and per-kit subscriber_trust still win\n  // above it in resolveTrustMode's precedence (R11). Own content stays auto.\n  if (accountUpdateMode) {\n    policy.globals.external = accountUpdateMode === 'auto' ? 'auto' : 'gate'\n  }\n\n  // Per-registry revocation: a delegated device key revoked on the registry that\n  // serves a skill must block that skill, even if a different (default) registry\n  // hasn't revoked it. Resolve the revocation set PER serving registry, memoized\n  // so each distinct registry is queried once (deepsec MEDIUM). Best-effort:\n  // offline sync proceeds with an empty set.\n  const revokedKeyCache = new Map<string, { ids: Set<string>; ok: boolean }>()\n  const getRevokedKeys = async (\n    url: string | undefined,\n  ): Promise<{ ids: Set<string>; ok: boolean }> => {\n    const key = (url ?? registryUrl).replace(/\\/+$/, '')\n    const cached = revokedKeyCache.get(key)\n    if (cached) return cached\n    let result = { ids: new Set<string>(), ok: true }\n    try {\n      result = await resolveRevokedDeviceKeyIds(state, key, {\n        ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n      })\n    } catch {\n      result = { ids: new Set<string>(), ok: false }\n    }\n    revokedKeyCache.set(key, result)\n    return result\n  }\n  // Home-registry set for the single-registry union-manifest pull below.\n  const homeRevocation = await getRevokedKeys(registryUrl)\n  const revokedDeviceKeyIds = homeRevocation.ids\n\n  // ------------------------------------------------------------------------\n  // Phase 0a: union-manifest pull. When a token is configured, fetch\n  // the server-side union manifest and add any skill refs from shared kits\n  // that aren't in local state yet. Mutates state.skills in place.\n  // This runs BEFORE the per-skill pull loop so new refs are present for the\n  // materialize phase in the same run.\n  // ------------------------------------------------------------------------\n  const unionOutcomes: PullOutcome[] = []\n  // The manifest's keep-set (refs) when the pull was an authoritative 200 \u2014 used\n  // by the prune reconcile below. null on 304/401/error \u2192 never prune this run.\n  let unionManifestRefs: Set<string> | null = null\n  // Server's account-bound signal for the empty-manifest zero-out decision.\n  let unionAccountScope: 'user' | undefined\n  const notices: string[] = []\n  if (effectiveToken && bearerKind === 'session' && !deviceId) {\n    notices.push(\n      'Per-device kit routing skipped \u2014 run `skillet connect` to link this machine.',\n    )\n  }\n  const slugFilter =\n    opts.slugs && opts.slugs.length > 0 ? new Set(opts.slugs) : null\n  if (effectiveToken && !opts.skipPull) {\n    const {\n      outcomes: newRefOutcomes,\n      manifestRefs,\n      accountScope,\n      authRejected,\n    } = await pullFromUnionManifest(state, {\n      registryUrl,\n      token: effectiveToken,\n      pinDir,\n      revokedDeviceKeyIds,\n      ...(deviceId ? { deviceId } : {}),\n      etagCachePath: opts.etagCachePath,\n      fetchImpl: opts.fetchImpl,\n    })\n    if (authRejected) {\n      // Do not edit this message: older bundled desktop sidecars are detected by a\n      // regex over this exact prose (the `machine_disconnected` code is the real\n      // contract; the text is the fallback for sidecars that predate it).\n      throw new RegistryError(\n        'machine_disconnected',\n        'This machine was disconnected from your account. Get a pair code at skillet.md \u2192 Settings \u2192 Devices and run `skillet connect <code>`.',\n        401,\n      )\n    }\n    unionManifestRefs = manifestRefs\n    unionAccountScope = accountScope\n    unionOutcomes.push(...newRefOutcomes)\n    for (const o of newRefOutcomes) {\n      if (o.status === 'failed') {\n        failed.push({ slug: o.slug, reason: o.reason ?? 'union_pull_failed' })\n      }\n    }\n  }\n\n  // ------------------------------------------------------------------------\n  // Phase 0b: pull updates from the registry for every registry-sourced\n  // entry that was already in local state before this run (or just added above\n  // with the same hash). Mutates state.skills in place so the materialize loop\n  // below sees the new bytes + signature + author identity in this same run,\n  // and the graded-diff approval gate fires for whatever just arrived.\n  //\n  // The headless rule maps directly to the pullMode/TTY check:\n  //   - interactive \u2192 pull all non-pinned entries\n  //   - unattended  \u2192 skip pull entirely (pinned bytes already on disk)\n  // Kit-key tokens always run unattended unless pullMode is explicitly set.\n  // ------------------------------------------------------------------------\n  const interactive =\n    opts.pullMode === 'interactive'\n      ? true\n      : opts.pullMode === 'unattended' || isKitKey\n        ? false\n        : opts.checkOnly === true\n          ? true\n          : (output as NodeJS.WriteStream).isTTY === true\n  const pullOutcomes: PullOutcome[] = []\n  if (!opts.skipPull) {\n    pullOutcomes.push(\n      ...(await pullRegistryUpdates(state, {\n        interactive,\n        pinDir,\n        etagCachePath: opts.etagCachePath,\n        token: effectiveToken,\n        // Per-registry revocation (each entry checked against its serving registry).\n        getRevokedKeys: async (url) => (await getRevokedKeys(url)).ids,\n        fetchImpl: opts.fetchImpl,\n      })),\n    )\n    for (const o of pullOutcomes) {\n      if (o.status === 'failed') {\n        // Surface pull failures alongside materialize failures so a CI run\n        // that can't refresh from the registry still exits non-zero. The\n        // pre-existing on-disk bytes are still materialized below \u2014 never\n        // delete an approved version because the network broke.\n        failed.push({ slug: o.slug, reason: o.reason ?? 'pull_failed' })\n      }\n    }\n  }\n\n  // Skills whose bytes changed this run (an UPSTREAM update). Their on-disk copy\n  // legitimately differs from the freshly-bumped entry.hash \u2014 that's not a user\n  // edit, so fork-on-edit must skip them (the graded-diff/materialize path owns\n  // the update). Without this, an update would be misread as an edit and forked.\n  const updatedRefs = new Set<string>()\n  for (const o of unionOutcomes) if (o.status === 'updated') updatedRefs.add(o.slug)\n  for (const o of pullOutcomes) if (o.status === 'updated') updatedRefs.add(o.slug)\n\n  // F6: a pull that reports a version yanked flags any customized skill HOLDING\n  // that version as a held update, so it stops nudging and takeUpstream refuses\n  // it. Runs BEFORE the materialize loop so the customized branch's held-update\n  // reconcile sees the flag (it leaves a same-hash record untouched).\n  if (!opts.checkOnly) {\n    for (const o of [...unionOutcomes, ...pullOutcomes]) {\n      if (!o.yankedHash) continue\n      const e = state.skills[o.slug]\n      if (e?.held_update && e.held_update.hash === o.yankedHash && !e.held_update.yanked) {\n        e.held_update = { ...e.held_update, yanked: true }\n        e.updatedAt = new Date().toISOString()\n        await upsertSkill(e)\n        state.skills[o.slug] = e\n      }\n    }\n  }\n\n  if (opts.checkOnly === true) {\n    const changed =\n      pullOutcomesIndicateWork(unionOutcomes) ||\n      pullOutcomesIndicateWork(pullOutcomes) ||\n      manifestPruneWouldRun(state, unionManifestRefs, bearerKind, !!opts.skipPull) ||\n      (await pendingGatedMaterialize(\n        state,\n        policy,\n        ownKeyId,\n        effectivePinDir,\n        approvalLockPath,\n        approvedHashes,\n        rejectedHashes,\n        ownHandle,\n      ))\n    return {\n      materialized: [],\n      adapters: [],\n      failed,\n      pendingReview,\n      pull: pullOutcomes,\n      unionPull: unionOutcomes,\n      pruned: [],\n      localized: [],\n      trashDir: null,\n      customized: [],\n      lockPath: join(cwd, 'skillet.lock'),\n      notices,\n      changed,\n    }\n  }\n\n  // Security gate runs against every adapter, including ones we will skip:\n  // declared roots must be in the per-runtime allowlist before we even ask\n  // the adapter whether its runtime is present. Project-scoped adapters\n  // (kind=\"project\") are validated against PROJECT_TARGET_ALLOWLIST + the\n  // cwd; global adapters against MATERIALIZATION_ROOT_ALLOWLIST.\n  for (const adapter of adapters) {\n    validateAdapterRoot(adapter, { cwd })\n  }\n\n  // detect() per adapter. Undetected runtimes report skipped-not-detected and\n  // are excluded from materialization. Detected runtimes get an in-progress\n  // entry whose status is upgraded to \"materialized\" or \"failed\" below.\n  // Baseline adapters (universal `.agents/skills`) bypass detect when named in\n  // opts.baselineAdapterNames.\n  const baselineSet = new Set(opts.baselineAdapterNames ?? [])\n  const results: AdapterResult[] = []\n  const active: Adapter[] = []\n  for (const adapter of adapters) {\n    let detected = false\n    const forceBaseline = baselineSet.has(adapter.name)\n    try {\n      detected = forceBaseline ? true : await adapter.detect()\n    } catch (err) {\n      results.push({\n        name: adapter.name,\n        status: 'failed',\n        targetDir: adapter.targetDir,\n        count: 0,\n        paths: [],\n        error: `detect() threw: ${(err as Error).message}`,\n        warnings: [],\n      })\n      continue\n    }\n    if (!detected) {\n      results.push({\n        name: adapter.name,\n        status: 'skipped-not-detected',\n        targetDir: adapter.targetDir,\n        count: 0,\n        paths: [],\n        warnings: [],\n      })\n      continue\n    }\n    results.push({\n      name: adapter.name,\n      status: 'materialized',\n      targetDir: adapter.targetDir,\n      count: 0,\n      paths: [],\n      warnings: [],\n    })\n    active.push(adapter)\n  }\n\n  // Report detected runtimes NOW, not at the end of the run: everything after\n  // this point can throw (approval gate, materialize failures), and a machine\n  // whose sync is blocked still HAS these runtimes \u2014 without the early send,\n  // the web device row read \"No runtimes yet\" for as long as an update sat\n  // unapproved. Fail-silent and unawaited, same as the late reports.\n  pingDeviceAgents({\n    registryUrl,\n    token: effectiveToken,\n    bearerKind,\n    agents: active.map((a) => a.name),\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  })\n\n  const resultByName = new Map(results.map((r) => [r.name, r] as const))\n  const materializeErrors = new Map<string, number>()\n\n  // Reconcile/prune: make this machine match your manifest. Skills you\n  // unsubscribed from or routed off this device left the manifest; move their\n  // Skillet-written, unedited copies to the local trash (reversible). Runs\n  // BEFORE materialize so pruned entries are gone from state and aren't rewritten.\n  // Gated to the full-account union (session/device) \u2014 a kit-key manifest is a\n  // single kit and pruning against it would wrongly remove everything else.\n  // Returns data only (no printing here) so `--json` output stays clean \u2014 the\n  // CLI/desktop format `pruned`/`localized`/`trashDir` for their surface.\n  let pruned: SyncResult['pruned'] = []\n  let localized: SyncResult['localized'] = []\n  let trashDir: string | null = null\n  if (\n    !opts.skipPull &&\n    unionManifestRefs &&\n    (bearerKind === 'session' || bearerKind === 'device')\n  ) {\n    // Zero-out (empty manifest deletes everything) is allowed only for an\n    // account-bound caller. Prefer the server's `account_scope` signal so a\n    // BOUND DEVICE that routed off every kit can zero out too; fall back to the\n    // session-only heuristic when an older server omits the field. Any\n    // unrecognized scope from an older registry never zeroes out.\n    const allowZeroOut = zeroOutAllowed(unionAccountScope, bearerKind)\n    // Snapshot the key set BEFORE prune so we can tell whether reconcilePrune\n    // actually mutated `state` (any removal or fork-swap) and only write when it did.\n    const keysBefore = Object.keys(state.skills).sort().join('\\u0000')\n    // Pass ALL configured global adapters (not just detected ones) so a copy in\n    // any runtime is accounted for. Project-scoped adapters are skipped inside\n    // reconcilePrune \u2014 their per-repo copies are never pruned by an account sync.\n    const rec = await reconcilePrune(state, unionManifestRefs, adapters, {\n      allowZeroOut,\n      prePullSnapshots,\n    })\n    pruned = rec.pruned\n    localized = rec.localized\n    trashDir = rec.trashDir\n    // reconcilePrune mutates `state` in place: it `delete`s pruned/orphaned\n    // entries AND rewrites localized (customized \u2192 local) entries. Those\n    // mutations live ONLY in memory \u2014 `upsertSkill` (below) read-modify-writes\n    // the on-disk state.json one entry at a time, so a stale read would re-add\n    // the just-removed skills (and drop the localization) on the next sync.\n    // Persist the reconciled state now, before the upsert loop re-reads disk, so\n    // the changes stick. We write `state` \u2014 the same object loaded at the top of\n    // sync \u2014 which matches upsertSkill's read-modify-write window, so no new race\n    // is introduced. The key-set guard covers removals; `localized` covers the\n    // in-place rewrites that leave the key set unchanged.\n    if (localized.length > 0 || Object.keys(state.skills).sort().join('\\u0000') !== keysBefore) {\n      await writeState(state)\n    }\n  }\n  // Age out old trash (best-effort; never blocks or breaks sync).\n  void clearOldTrash()\n\n  // One-time migrations off retired layouts (best-effort; never block sync).\n  // Codex legacy `~/.codex/skills` duplicates: global, runs once per sync.\n  await cleanupLegacyCodexSkills(state, notices).catch(() => {})\n  // Old Windsurf project rule files in this cwd, now that windsurf is global.\n  if (active.some((a) => a.name === 'windsurf')) {\n    await cleanupLegacyWindsurfArtifacts(cwd).catch(() => {})\n  }\n\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (slugFilter) {\n      if (!slugFilter.has(slug)) continue\n    } else if (!isKitSyncedSkill(entry) && !isSkilletSystemSkill(entry)) {\n      continue\n    }\n\n    const owner = entry.owner ?? null\n    const identity = skillMaterializeIdentity(slug, owner)\n    const adapterSlug = identity.adapterSlug\n\n    // \u2500\u2500 Customized skills (KTD1/KTD2/KTD3): the edit stays LIVE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n    // A customized skill is never materialized over \u2014 its edit is the live one.\n    // Reconcile the held-update signal against the freshly-pulled upstream hash\n    // (`entry.hash` after the pull phase) and move on; no verify, no gate, no\n    // materialize touches the folder.\n    if (entry.customized_from) {\n      if (reconcileHeldUpdate(entry)) {\n        await upsertSkill(entry)\n        state.skills[slug] = entry\n      }\n      customized.push({ slug, hasUpdate: heldUpdateSurfaces(entry) })\n      continue\n    }\n\n    // Drift baseline (R2 + F1): the hash sync LAST SUCCESSFULLY MATERIALIZED to\n    // this machine. `entry.hash` is advanced by this run's pull BEFORE we\n    // materialize, so a pull that persisted a new version whose materialize then\n    // failed/declined (degrade-never-delete) leaves the OLD author bytes on disk\n    // while state records the new hash. Baselining on `materialized_hash` (what\n    // actually landed) means that lag is seen as \"not yet materialized\" and\n    // RE-MATERIALIZES (converges) below \u2014 never a phantom edit that customizes\n    // the skill forever. Fall back to the pre-pull snapshot (legacy state with no\n    // materialized_hash yet), then the incoming hash for a first-seen entry.\n    const snapshot = prePullSnapshots.get(slug)\n    const driftBaseline = entry.materialized_hash ?? snapshot?.hash ?? entry.hash\n    const detection = await detectDriftedGlobalCopies(adapters, adapterSlug, owner, driftBaseline)\n\n    // RF1 \u2014 a disk difference is a USER EDIT only when the skill is in a STABLE\n    // state: state and disk agree on what should be there\n    // (`materialized_hash === entry.hash`). When author bytes are PENDING \u2014\n    // `materialized_hash` missing (a legacy entry), or `!= entry.hash` (a pull\n    // advanced the hash but the materialize failed / was partial / was declined) \u2014\n    // ANY on-disk difference is our OWN incomplete materialize, NOT a user edit.\n    // In that case we must NOT customize; we fall through and (re-)materialize to\n    // CONVERGE. This is what makes the multi-adapter partial-failure case heal:\n    // next sync sees pending, re-materializes every runtime, and settles \u2014 instead\n    // of freezing the skill customized off a runtime we simply hadn't caught up.\n    const stable = entry.materialized_hash != null && entry.materialized_hash === entry.hash\n\n    // First drift \u2192 mark customized, back up the edit, and LEAVE IT LIVE (R1).\n    // No materialize runs for this skill: the edit is now the user's version.\n    if (stable && detection.drifted.length > 0) {\n      // The lineage is the version the edit was made FROM = the drift baseline.\n      // Pair its version only when the snapshot names that same baseline hash.\n      const baselineVersion =\n        snapshot && snapshot.hash === driftBaseline ? snapshot.version : entry.version\n      const lineage = { author: owner, slug, version: baselineVersion, hash: driftBaseline }\n      // F5: stash the baseline author bytes so Restore original can later return\n      // the version the edit was made FROM, even after an update is pulled. Only\n      // possible while the skill store still holds those exact bytes (no update\n      // overwrote them this run); otherwise restoreOriginal falls back to upstream.\n      try {\n        const storeBundle = await readBundleFromSkillStore(slug)\n        if (canonicalContentHash(storeBundle) === lineage.hash) {\n          await stashBaselineVersion(lineage.hash, storeBundle as unknown as Map<string, Buffer>)\n        }\n      } catch {\n        // Best-effort: a missing/unreadable store just means restore falls back.\n      }\n      try {\n        await backupSkillVersion({ lineage, copies: detection.drifted, reason: 'customize' })\n      } catch {\n        // Best-effort backup (R3): even if the backup write fails, the edit is\n        // left live and the skill is still marked customized \u2014 R1 (never revert)\n        // dominates R3 (back up). The next sync retries the backup on re-detect.\n      }\n      const updated: SkillEntry = {\n        ...entry,\n        customized_from: lineage,\n        updatedAt: new Date().toISOString(),\n      }\n      // An upstream update that already arrived this run is HELD, not applied.\n      if (entry.hash !== lineage.hash) {\n        updated.held_update = { version: entry.version, hash: entry.hash }\n      }\n      await upsertSkill(updated)\n      state.skills[slug] = updated\n      customized.push({ slug, hasUpdate: heldUpdateSurfaces(updated) })\n      continue\n    }\n\n    // An existing dir we cannot read/hash (uncapturable) may hold an edit we\n    // cannot prove absent \u2014 never materialize over it (edit-preservation). Skip\n    // and surface it; no escalation counter (the heal it once guarded is gone).\n    if (detection.uncapturable.length > 0) {\n      const code = detection.uncapturable[detection.uncapturable.length - 1]!.code\n      const reason = `edit_unreadable: an existing on-disk copy of \"${slug}\" could not be read (${code ?? 'unknown'}); left untouched`\n      if (!quietSkipLines) {\n        ;(output as NodeJS.WriteStream).write(`Skipped \"${slug}\" \u2014 ${reason}.\\n`)\n      }\n      failed.push({ slug, reason })\n      continue\n    }\n\n    const bundle: DecodedBundle = await readBundleFromSkillStore(slug)\n    let currentHash = skillContentHash(bundle)\n    let entryForVerify = entry\n    if (currentHash !== entry.hash) {\n      const bundleWithBackups = await readBundleFromSkillStore(slug, {\n        includeSkilletBackups: true,\n      })\n      const legacyHash = canonicalContentHash(bundleWithBackups)\n      if (legacyHash === entry.hash) {\n        await writeBundleToSkillStore(slug, stripSkilletBackupPaths(bundleWithBackups))\n        entryForVerify = {\n          ...entry,\n          hash: currentHash,\n          updatedAt: new Date().toISOString(),\n        }\n        await upsertSkill(entryForVerify)\n        state.skills[slug] = entryForVerify\n      }\n    }\n\n    const authorPinned = await isAuthorPinned(entryForVerify, slug, effectivePinDir)\n    const needsApproval = requiresApproval(entryForVerify, policy, ownKeyId, authorPinned, ownHandle)\n\n    if (needsApproval) {\n      // Account-scoped decisions win on pull (server is source of truth): a\n      // matching account approval short-circuits the prompt and is mirrored into\n      // the local lock; an account rejection skips. The local lock is the\n      // offline fallback.\n      const serverApproved = approvedHashes.has(currentHash)\n      const serverRejected = !serverApproved && rejectedHashes.has(currentHash)\n      const locallyApproved = await checkLock(approvalLockPath, slug, entry.version, currentHash)\n\n      // Mirror a server approval into the local cache so future offline runs are fast.\n      if (serverApproved && !locallyApproved) {\n        await recordApproval(approvalLockPath, slug, entry.version, {\n          contentHash: currentHash,\n          authorKeyId: entry.authorKeyId ?? '',\n          approvedAt: new Date().toISOString(),\n        })\n      }\n\n      const alreadyApproved = serverApproved || locallyApproved\n\n      if (!alreadyApproved) {\n        if (serverRejected) {\n          if (!quietSkipLines) {\n            ;(output as NodeJS.WriteStream).write(\n              `Skipped \"${slug}\" \u2014 v${entry.version} was rejected. Approve it from the web or run \\`skillet approve ${slug} --version ${entry.version}\\`.\\n`,\n            )\n          }\n          continue\n        }\n        // Skip versions explicitly rejected via `skillet reject` \u2014 no diff, no prompt.\n        const isRejected = await checkRejection(approvalLockPath, slug, entry.version)\n        if (isRejected) {\n          if (!quietSkipLines) {\n            ;(output as NodeJS.WriteStream).write(\n              `Skipped \"${slug}\" \u2014 v${entry.version} was rejected. Run \\`skillet approve ${slug} --version ${entry.version}\\` to override.\\n`,\n            )\n          }\n          continue\n        }\n\n        // Build diff against the adapters we'd actually write to (fan-out)\n        // using the full bundle tree (all files, not just SKILL.md).\n        const prev = await readCurrentMaterialized(identity, active, cwd)\n        const next: Record<string, Buffer> = {}\n        for (const adapter of active) {\n          for (const [bundlePath, bytes] of bundle) {\n            next[`${adapter.name}/${bundlePath}`] = Buffer.from(bytes)\n          }\n        }\n\n        const isTTY = (output as NodeJS.WriteStream).isTTY === true\n        const isFirstInstall = Object.keys(prev).length === 0\n        const skillRef = slug.startsWith('@')\n          ? slug\n          : entry.owner\n            ? `@${entry.owner}/${adapterSlug}`\n            : slug\n\n        // Interactive sync holds anything unapproved instead of prompting:\n        // what's on disk stays, and the caller renders result.pendingReview\n        // as a one-line summary. Review + approval live in `skillet pending`\n        // / `skillet approve`. A slug-scoped run (`skillet add`) still\n        // confirms inline \u2014 the user is present and asked for exactly that\n        // skill. Headless runs keep the hard-fail contract below.\n        if (isTTY && !approvePre && !autoApprove && !slugFilter) {\n          let range = 'new'\n          if (!isFirstInstall) {\n            const incoming = `v${entry.versionLabel ?? entry.version}`\n            const last = await getLastApprovedVersion(approvalLockPath, slug)\n            range = last !== null ? `v${last} \u2192 ${incoming}` : incoming\n          }\n          pendingReview.push({ slug, range })\n          continue\n        }\n\n        const nextRel: Record<string, Buffer> = {}\n        for (const [bundlePath, bytes] of bundle) {\n          nextRel[bundlePath] = Buffer.from(bytes)\n        }\n        const diffText = isFirstInstall\n          ? summarizeInstall(skillRef, next)\n          : renderUpdateReview({\n              prev,\n              next: nextRel,\n              adapterNames: active.map((a) => a.name),\n              color: isTTY,\n            }) || `(no materialized version found for \"${slug}\" \u2014 first install from registry)`\n\n        // SKILLET_APPROVE_PRE=1 or opts.approvePre bypasses the\n        // interactive prompt for headless kit-key runs.\n        // opts.autoApprove covers `skillet add -y` and similar user flags.\n        let approved: boolean\n        if (approvePre) {\n          approved = true\n          ;(output as NodeJS.WriteStream).write(\n            `Auto-approved \"${slug}\" via SKILLET_APPROVE_PRE.\\n`,\n          )\n        } else if (autoApprove) {\n          approved = true\n        } else {\n          approved = await promptApproval(\n            diffText,\n            output as import('stream').Writable,\n            input as import('stream').Readable,\n            isFirstInstall ? 'install' : 'update',\n          )\n        }\n\n        if (!approved) {\n          // Non-TTY or kit-key: caller must exit non-zero.\n          const isCI = !!(process.env['CI'] || effectiveToken)\n          if (isCI || !(output as NodeJS.WriteStream).isTTY) {\n            throw new Error(\n              `Skill \"${slug}\" update requires approval. Run interactively to review and approve, or set SKILLET_APPROVE_PRE=1.`,\n            )\n          }\n          // TTY but user said no: skip materialization for this skill.\n          if (!quietSkipLines) {\n            ;(output as NodeJS.WriteStream).write(`Skipped \"${slug}\" \u2014 update not approved.\\n`)\n          }\n          continue\n        }\n\n        // TOCTOU guard: re-read and re-hash before materializing.\n        const verifyBundle = await readBundleFromSkillStore(slug)\n        const verifyHash = skillContentHash(verifyBundle)\n        if (verifyHash !== currentHash) {\n          throw new Error(\n            `TOCTOU: content of \"${slug}\" changed between approval and materialization. Re-run to re-review.`,\n          )\n        }\n\n        // Record approval in the lock.\n        await recordApproval(approvalLockPath, slug, entry.version, {\n          contentHash: currentHash,\n          authorKeyId: entry.authorKeyId ?? '',\n          approvedAt: new Date().toISOString(),\n        })\n      }\n    }\n\n    // KTD7: in account auto-mode, record a source:auto decision for a freshly\n    // auto-applied EXTERNAL update so the recently-applied feed is account-wide.\n    // Write-path only (a POST, never a read); CI/APPROVE_PRE runs record nothing,\n    // and a failed post just drops this run's history (still applies locally).\n    if (\n      accountUpdateMode === 'auto' &&\n      !needsApproval &&\n      updatedRefs.has(slug) &&\n      !approvedHashes.has(currentHash) &&\n      installClient &&\n      !approvePre &&\n      !autoApprove &&\n      entry.owner &&\n      entry.authorKeyId !== ownKeyId\n    ) {\n      try {\n        await installClient.postApproval(`${entry.owner}:${adapterSlug}`, currentHash)\n        approvedHashes.add(currentHash)\n      } catch {\n        // best-effort; unauthenticated/failed post just skips this run's history.\n      }\n    }\n\n    // Quarantine gate \u2014 runs AFTER signature-derived approval but\n    // BEFORE the integrity check + adapter writes. Quarantined versions\n    // require explicit extra consent on top of the standard graded-diff\n    // approval. Non-TTY runs without `allowQuarantined` skip with a reason.\n    if (requiresQuarantineConsent(entry.scan)) {\n      const isTTY = (output as NodeJS.WriteStream).isTTY === true\n      let allow = false\n      if (allowQuarantined || allowQuarantinedSlugs.includes(slug)) {\n        allow = true\n        ;(output as NodeJS.WriteStream).write(\n          allowQuarantined\n            ? `Applying quarantined \"${slug}\" (pre-approved via --allow-quarantined).\\n`\n            : `Applying quarantined \"${slug}\" (consented during review).\\n`,\n        )\n      } else if (isTTY) {\n        allow = await promptQuarantineConsent(\n          entry.scan!,\n          slug,\n          output as import('stream').Writable,\n          input as import('stream').Readable,\n        )\n      }\n      if (!allow) {\n        const reason = `quarantined: harm scan flagged this version (status=${entry.scan?.status}); extra consent required`\n        if (!quietSkipLines) {\n          ;(output as NodeJS.WriteStream).write(`Skipped \"${slug}\" \u2014 ${reason}.\\n`)\n        }\n        failed.push({ slug, reason })\n        continue\n      }\n    }\n\n    // Integrity gate (PROTOCOL \u00A76.4 + acceptance criterion 3) \u2014 runs AFTER\n    // approval but BEFORE any adapter writes. A failure here means the\n    // bytes Skillet is about to materialize cannot be tied to the pinned\n    // author key; we abort this skill and leave prior on-disk files alone.\n    const revocation = await getRevokedKeys(entry.registryUrl)\n    const reason = await verifyForMaterialize(\n      entryForVerify,\n      currentHash,\n      effectivePinDir,\n      // Check this entry against the revocation set of the registry that served\n      // it (per-registry; deepsec MEDIUM), not a single default-registry set.\n      {\n        revokedDeviceKeyIds: revocation.ids,\n        revocationFetchOk: revocation.ok,\n      },\n    )\n    if (reason !== null) {\n      if (!quietSkipLines) {\n        const msg = `Skipped \"${slug}\" \u2014 ${reason}. Existing materialized files left untouched.\\n`\n        ;(output as NodeJS.WriteStream).write(msg)\n      }\n      failed.push({ slug, reason })\n      continue\n    }\n\n    // Degrade-never-delete: a single adapter failure must not abort\n    // the run. Catch per (adapter, skill) and continue siblings; adapter\n    // status is finalized after all skills are processed.\n    //\n    // RF2: track per-adapter success across the GLOBAL adapters so\n    // `materialized_hash` only advances when EVERY global adapter took the bytes.\n    // If ANY global adapter failed (this skill or earlier this run), the on-disk\n    // set is not uniformly the new version, so recording the new hash would let\n    // the next run's RF1 drift baseline treat the lagging runtime as a user edit.\n    // (Project adapters don't participate in global drift, so they don't gate it \u2014\n    // when there are no global adapters `expectedGlobal === 0` and this is vacuous.)\n    let wroteSkill = false\n    let expectedGlobal = 0\n    let succeededGlobal = 0\n    for (const adapter of active) {\n      const isGlobal = adapter.kind !== 'project'\n      if (isGlobal) expectedGlobal += 1\n      const result = resultByName.get(adapter.name)\n      if (!result) continue\n      const adapterCwd = await resolveAdapterMaterializeCwd(adapter, cwd)\n      const entryDescription = entry.description?.trim() ? entry.description : undefined\n      try {\n        // cwd is forwarded so project-scoped adapters (Cursor, Windsurf)\n        // can resolve their root; global adapters ignore it.\n        const writtenPaths = await adapter.materialize(\n          adapterSlug,\n          bundle,\n          materializeOptsForIdentity(identity, adapterCwd, {\n            description: entryDescription,\n          }),\n        )\n        for (const dest of writtenPaths) {\n          materialized.push({ slug, dest, hash: currentHash })\n          result.paths.push(dest)\n          wroteSkill = true\n        }\n        // One increment per skill, not per written file: the sync summary\n        // renders this as \"N skills\" (a multi-file skill is still one skill).\n        // Exclude the bundled `/skillet` router \u2014 it's materialized into every\n        // agent as plumbing but is never a user-visible skill, so the per-agent\n        // tally must match `skillet list` and the \"Synced N kit skill(s)\" line.\n        if (writtenPaths.length > 0 && !isSkilletSystemSkill(entry)) {\n          result.count += 1\n        }\n        if (isGlobal) succeededGlobal += 1\n      } catch (err) {\n        const message = (err as Error).message\n        // A detected-but-not-ready adapter (e.g. installed-but-never-launched:\n        // its config root is absent) throws AdapterSkipError. That is a benign\n        // skip, not a materialize failure: surface it as a warning and leave\n        // the skill pending (succeededGlobal stays short of expectedGlobal, so\n        // the hash isn't advanced and the next run retries). It must NOT enter\n        // `failed`/`materializeErrors`, or import/sync would exit non-zero over\n        // an agent the user simply hasn't opened yet.\n        if (err instanceof AdapterSkipError) {\n          result.warnings.push(`${adapter.name}: ${message}`)\n          continue\n        }\n        failed.push({\n          slug,\n          reason: `materialize_failed: ${adapter.name}: ${message}`,\n        })\n        materializeErrors.set(adapter.name, (materializeErrors.get(adapter.name) ?? 0) + 1)\n        result.error = `materialize(${slug}) failed: ${message}`\n      }\n\n      // Nested-SKILL.md notice: OpenClaw discovers SKILL.md recursively, so a\n      // bundle that ships a SKILL.md below its root registers extra phantom\n      // skills. Faithful materialization is still correct (real bundles nest\n      // legitimately \u2014 the cloudflare mirror ships eleven), so this informs\n      // rather than blocks (Cursor .mdc precedent).\n      if (adapter.name === 'openclaw') {\n        const nested = [...bundle.keys()].filter(\n          (p) => p !== 'SKILL.md' && p.endsWith('/SKILL.md'),\n        )\n        if (nested.length > 0) {\n          notices.push(\n            `\"${slug}\" bundles ${nested.length} nested SKILL.md file(s) (${nested.join(', ')}); OpenClaw discovers each as a separate skill.`,\n          )\n        }\n      }\n\n      // Surface higher-precedence shadows so a Skillet sync that\n      // succeeded on disk but is silently overridden by a workspace skill\n      // doesn't read as \"your skills are everywhere\" when they aren't.\n      // findShadows is opt-in; adapters that don't implement it are skipped.\n      if (adapter.findShadows) {\n        try {\n          const findings = await adapter.findShadows(adapterSlug, {\n            owner: identity.owner,\n            dirName: identity.dirName,\n            workspaceDir: adapterCwd,\n          })\n          for (const f of findings) {\n            result.warnings.push(\n              `\"${slug}\" is shadowed by ${f.location} (${f.path}) \u2014 that copy will load instead of the Skillet-synced version.`,\n            )\n          }\n        } catch {\n          // Shadow detection is informational; never break sync.\n        }\n      }\n    }\n\n    if (wroteSkill && slug === BUNDLED_ROUTE_SLUG) {\n      await removeLegacyBundledRouteMaterialization(active)\n    }\n\n    if (wroteSkill && installClient && entry.source === 'registry' && !installPinged.has(slug)) {\n      installPinged.add(slug)\n      pingInstallMetric(installClient, slug)\n    }\n\n    // F1/RF2: record what actually landed on disk. `materialized_hash` is only\n    // written after a successful materialize (wroteSkill) AND when EVERY global\n    // adapter took the bytes (`allGlobalMaterialized`), so neither a persisted-\n    // but-unmaterialized pull nor a PARTIAL materialize (one runtime wrote vNew,\n    // another still has vOld) poisons the next run's drift baseline. Leaving the\n    // hash un-advanced on a partial keeps the skill in RF1's pending state, so the\n    // next sync re-materializes the lagging runtime and converges. Gating on\n    // `wroteSkill` also stops a store hash from being recorded when nothing wrote.\n    const allGlobalMaterialized = succeededGlobal === expectedGlobal\n    if (\n      wroteSkill &&\n      allGlobalMaterialized &&\n      (currentHash !== entry.hash || entry.materialized_hash !== currentHash)\n    ) {\n      const updated: SkillEntry = {\n        ...entry,\n        hash: currentHash,\n        materialized_hash: currentHash,\n        updatedAt: new Date().toISOString(),\n      }\n      await upsertSkill(updated)\n      state.skills[slug] = updated\n    }\n  }\n\n  for (const adapter of active) {\n    const result = resultByName.get(adapter.name)\n    if (!result) continue\n    const errors = materializeErrors.get(adapter.name) ?? 0\n    if (result.count > 0) {\n      result.status = 'materialized'\n    } else if (errors > 0) {\n      result.status = 'failed'\n    } else {\n      result.status = 'materialized'\n    }\n  }\n\n  // Build per-slug overrides for the lockfile from the in-memory state so\n  // each registry-sourced entry pins its author_key + signature into\n  // skillet.lock for CI verification on a fresh clone (PROTOCOL \u00A711).\n  const overrides: Parameters<typeof writeLockFile>[3] = {}\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (entry.source === 'registry' && entry.authorKeyId && entry.signature) {\n      overrides[slug] = {\n        author_key: entry.authorKeyId,\n        signature: entry.signature,\n      }\n    }\n  }\n  const lockPath = await writeLockFile(cwd, kitSyncedState(state), undefined, overrides)\n\n  // First sync discloses what's recorded (honest default-on), then never again.\n  // Read disclosure state BEFORE disclosing: the per-skill availability send\n  // below is suppressed until the user has actually seen the disclosure, so no\n  // skill list ever leaves the machine ahead of the notice.\n  const alreadyDisclosed = (await activityState()).disclosed\n  if (detectInitiator() === 'human') void maybeDiscloseActivity()\n  recordEvent('sync', detectInitiator(), {\n    count: materialized.length,\n    adapterCount: adapters.length,\n    detectedCount: active.length,\n    failedAdapters: results.filter((r) => r.status === 'failed').length,\n    failedSkills: failed.length,\n  })\n\n  // Cross-vendor distribution (availability): which skills are now present in\n  // which runtimes on this machine. Sent separately from the lean sync event so\n  // the event log never carries a skill list; opt-out-aware and fail-silent.\n  // Held back on the first (pre-disclosure) sync \u2014 disclosure precedes the send.\n  if (alreadyDisclosed) {\n    void reportAvailability(\n      [...new Set(materialized.map((m) => m.slug))],\n      mergeAvailabilityRuntimes(\n        active.map((a) => a.name),\n        opts.readerRuntimes,\n      ),\n    )\n  }\n\n  pingDeviceMaterializations({\n    registryUrl,\n    token: effectiveToken,\n    bearerKind,\n    materializations: deriveMaterializations({ materialized, adapters: results, failed }),\n    // Currently-customized skills ride the same report (KTD2): ref + baseline\n    // only, reconciled to exactly this set on the registry (absence clears).\n    edited: deriveEditedSkills(state.skills),\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  })\n\n  return {\n    materialized,\n    adapters: results,\n    failed,\n    pendingReview,\n    pull: pullOutcomes,\n    unionPull: unionOutcomes,\n    pruned,\n    localized,\n    trashDir,\n    customized,\n    lockPath,\n    notices,\n  }\n}\n\n// Compatibility: skillContentPath is still re-exported for adapters / tests\n// that want the single-file entrypoint on disk.\nexport { skillContentPath }\n", "// Customized skills \u2014 the machinery behind \"editing a synced skill makes it\n// yours.\" When a user (or their agent) edits a materialized skill, sync marks\n// the entry `customized_from` and LEAVES THE EDIT LIVE (never reverted). The\n// author's updates for it are HELD, surfaced quietly, and reconciled on demand:\n//   - takeUpstream(slug)   \u2014 replace the edit with the author's version\n//   - restoreOriginal(slug)\u2014 replace the edit with the current signed version\n//   - keepMine(slug)       \u2014 acknowledge a held update so it stops nudging\n//   - proposeCustomized     \u2014 send the edit upstream (see propose.ts)\n//\n// The leaf helpers this file relies on (the backup store, drift detection, the\n// run-dir conventions) live in ./edits-store.js \u2014 a module that imports NOTHING\n// from ./sync.js. Keeping them there breaks the edits\u2194sync ESM cycle that used\n// to fault on `LEDGER_STAMP` during init. This file keeps only the reconcile\n// actions, which DO need `verifyForMaterialize` from ./sync.js.\nimport { lstat, mkdir, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { canonicalContentHash, type DecodedBundle } from '@skillet/protocol'\nimport { defaultPinDir } from '../signing/pin.js'\nimport {\n  readState,\n  writeState,\n  readBundleFromSkillStore,\n} from '../kit/store.js'\nimport { verifyForMaterialize } from './sync.js'\nimport { recordEvent, detectInitiator } from '../metrics.js'\nimport type { Adapter } from '../adapter.js'\nimport type { SkillEntry } from '../kit/types.js'\nimport {\n  readTreeIgnoringDotfiles,\n  backupSkillVersion,\n  readBaselineStash,\n  clearBaselineStash,\n  type DriftedCopy,\n  type BackupReason,\n  type SkillLineage,\n} from './edits-store.js'\n\n// Backward-compatible re-exports: these leaf helpers moved to ./edits-store.js\n// (breaking the edits\u2194sync import cycle) but stay reachable via this module for\n// existing importers and the curated public surface.\nexport {\n  editsRoot,\n  listBackups,\n  ledgerStamp,\n  writeRunManifest,\n  moveDir,\n  detectDriftedGlobalCopies,\n  LEDGER_STAMP,\n} from './edits-store.js'\nexport type {\n  SkillLineage,\n  DriftedCopy,\n  UncapturableCopy,\n  DriftDetection,\n  BackupReason,\n  BackupManifest,\n  BackupEntry,\n} from './edits-store.js'\n\n/**\n * Strip the `@owner/` canonical prefix before passing to adapter APIs.\n * Adapters receive `(bareSlug, { owner })` separately \u2014 they must not see\n * the `@` or `/` chars that assertSafeSlug rejects. (Mirrors sync.ts.)\n */\nfunction bareAdapterSlug(slug: string, owner: string | null): string {\n  if (owner && slug.startsWith('@')) {\n    const idx = slug.indexOf('/')\n    if (idx >= 0) return slug.slice(idx + 1)\n  }\n  return slug\n}\n\n// \u2500\u2500 lineage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The lineage as a human/registry ref: `@author/slug` for registry origins, the bare slug for local ones. */\nexport function lineageRef(lineage: SkillLineage): string {\n  if (!lineage.author) return lineage.slug\n  return lineage.slug.startsWith('@') ? lineage.slug : `@${lineage.author}/${lineage.slug}`\n}\n\n/**\n * Registry propose target for a lineage, or null when the origin is local-only\n * (nothing upstream to propose to).\n */\nexport function lineageTarget(lineage: SkillLineage): { author: string; slug: string } | null {\n  if (!lineage.author) return null\n  return { author: lineage.author, slug: bareAdapterSlug(lineage.slug, lineage.author) }\n}\n\n/**\n * The first readable global adapter copy of a skill, as a bundle tree. Used to\n * build a propose bundle from the LIVE on-disk edit. Null when no global copy\n * is present/readable.\n */\nexport async function readLiveCustomizedTree(\n  slug: string,\n  owner: string | null,\n  adapters: Adapter[],\n): Promise<Map<string, Buffer> | null> {\n  const adapterSlug = bareAdapterSlug(slug, owner)\n  for (const adapter of adapters) {\n    if (adapter.kind === 'project') continue\n    let dir: string\n    try {\n      dir = adapter.targetSkillDir(adapterSlug, { owner })\n    } catch {\n      continue\n    }\n    try {\n      const tree = await readTreeIgnoringDotfiles(dir)\n      if (tree.size > 0) return tree\n    } catch {\n      continue\n    }\n  }\n  return null\n}\n\n// \u2500\u2500 customized-skill listing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface CustomizedSkill {\n  slug: string\n  entry: SkillEntry\n  /** The lineage baseline the edit was made against. */\n  lineage: SkillLineage\n  /** A held author update is waiting AND has not been acknowledged (Keep mine). */\n  hasUpdate: boolean\n  /** The held update itself, when one exists (regardless of acknowledgement). */\n  held?: { version: number; hash: string }\n}\n\n/** Every customized skill in kit state, flagging which have a held author update. */\nexport async function listCustomized(): Promise<CustomizedSkill[]> {\n  const state = await readState()\n  const out: CustomizedSkill[] = []\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    if (!entry.customized_from) continue\n    const held = entry.held_update\n    out.push({\n      slug,\n      entry,\n      lineage: entry.customized_from,\n      // A yanked held update never nudges \u2014 the author pulled it (F6).\n      hasUpdate: !!held && !held.acknowledged && !held.yanked,\n      ...(held ? { held: { version: held.version, hash: held.hash } } : {}),\n    })\n  }\n  return out\n}\n\n// \u2500\u2500 reconcile actions (take / restore / keep) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type ReconcileErrorCode =\n  | 'not_found'\n  | 'not_customized'\n  | 'integrity_failed'\n  /** The user's edit could not be backed up, so the overwrite was refused (F2). */\n  | 'backup_failed'\n  /** No runtime accepted the author bytes \u2014 the edit is still live (F3). */\n  | 'materialize_failed'\n  /**\n   * Some runtimes took the bytes, some failed \u2014 the succeeded ones were ROLLED\n   * BACK to the edit and the skill stays customized (F3/RF3). No split disk.\n   */\n  | 'partial_failure'\n  /**\n   * A partial materialize failed AND rolling the succeeded runtimes back to the\n   * edit also failed \u2014 the disk may now be split. Loud, unusual, needs a human.\n   */\n  | 'rollback_failed'\n  /**\n   * Restore original was asked for but the exact baseline the edit was made FROM\n   * is no longer obtainable (no stash, store advanced) \u2014 the edit is left in\n   * place rather than silently applying a different (current upstream) version.\n   */\n  | 'baseline_unavailable'\n  /** The target upstream version was yanked by the author (F6). */\n  | 'yanked'\n\nexport class ReconcileError extends Error {\n  readonly code: ReconcileErrorCode\n  constructor(message: string, code: ReconcileErrorCode) {\n    super(message)\n    this.name = 'ReconcileError'\n    this.code = code\n  }\n}\n\nexport interface ReconcileResult {\n  slug: string\n  /** Destination paths the author bytes were materialized into. */\n  materialized: string[]\n  /** Backup entry holding the user's replaced version, or null when nothing was on disk. */\n  backupId: string | null\n  /**\n   * Reserved for a non-fatal note about the reconcile. No longer set for the\n   * baseline-unobtainable case (RF4 now ABORTS there rather than silently\n   * applying a different version), but kept on the surface for forward use.\n   */\n  note?: string\n}\n\nexport interface ReconcileOptions {\n  /** TOFU pinned-keys directory (defaults to $XDG_CONFIG_HOME/skillet/pinned). */\n  pinDir?: string\n}\n\n/** A live global adapter copy captured for backup + rollback: its dir and the\n * exact on-disk edit tree (read once, reused so backup and rollback can't\n * disagree). */\ninterface LiveCopy extends DriftedCopy {\n  tree: Map<string, Buffer>\n}\n\n/**\n * Every readable global adapter copy of a skill currently on disk, each with its\n * edit tree captured. `unreadable` is set when a PRESENT (non-symlink) dir could\n * not be stat'd or read (RF6): distinct from ABSENT. The caller must abort the\n * reconcile on `unreadable` \u2014 materializing over a present-but-unreadable copy\n * would overwrite an edit that was never backed up.\n */\nasync function currentGlobalCopies(\n  adapters: Adapter[],\n  adapterSlug: string,\n  owner: string | null,\n): Promise<{ copies: LiveCopy[]; unreadable: boolean }> {\n  const copies: LiveCopy[] = []\n  let unreadable = false\n  for (const adapter of adapters) {\n    if (adapter.kind === 'project') continue\n    let dir: string\n    try {\n      dir = adapter.targetSkillDir(adapterSlug, { owner })\n    } catch {\n      continue\n    }\n    let st\n    try {\n      st = await lstat(dir)\n    } catch (err) {\n      const code = (err as NodeJS.ErrnoException | null)?.code\n      // Absent \u2192 nothing to back up. Anything else (EACCES, EIO\u2026) \u2192 a dir may be\n      // there that we cannot even inspect: present-but-unreadable, never clean.\n      if (code === 'ENOENT' || code === 'ENOTDIR') continue\n      unreadable = true\n      continue\n    }\n    if (st.isSymbolicLink() || !st.isDirectory()) continue\n    let tree: Map<string, Buffer>\n    try {\n      tree = await readTreeIgnoringDotfiles(dir)\n    } catch {\n      unreadable = true // present but unreadable \u2192 the caller aborts (RF6)\n      continue\n    }\n    if (tree.size > 0) copies.push({ adapter: adapter.name, dir, tree })\n  }\n  return { copies, unreadable }\n}\n\n/**\n * Resolve the AUTHOR baseline a customized skill was edited from \u2014 the bytes at\n * `customized_from.hash` (F5). Prefers the content-addressed baseline stash\n * written at first-customize; falls back to the live store when it still holds\n * those exact bytes (no update pulled). Returns null when the baseline is no\n * longer obtainable \u2014 the caller then falls back to the current upstream.\n */\nasync function resolveBaselineBundle(\n  slug: string,\n  baselineHash: string,\n): Promise<DecodedBundle | null> {\n  const stashed = await readBaselineStash(baselineHash)\n  if (stashed && canonicalContentHash(stashed) === baselineHash) {\n    return stashed as unknown as DecodedBundle\n  }\n  try {\n    const store = await readBundleFromSkillStore(slug)\n    if (canonicalContentHash(store) === baselineHash) return store\n  } catch {\n    // No readable store bytes \u2014 the baseline is unobtainable.\n  }\n  return null\n}\n\n/**\n * Shared core of Take theirs / Restore original: verify the target bytes,\n * back up the user's current on-disk edit, materialize the target over it, and\n * clear `customized_from` / `held_update`.\n *\n * `target` selects which author version is applied:\n *  - 'upstream'  \u2192 the current signed version in the store (full signature gate).\n *  - 'baseline'  \u2192 the version the edit was made FROM (`customized_from.hash`),\n *                  from our trusted local snapshot, integrity-gated by content\n *                  hash; ABORTS (baseline_unavailable) when unobtainable rather\n *                  than substituting a different (current upstream) version (RF4).\n *\n * Verify runs BEFORE the backup and the overwrite (an author version that does\n * not check aborts with the edit left live \u2014 KTD6). The backup runs BEFORE the\n * overwrite and its failure ABORTS (F2 \u2014 never destroy the only copy of the\n * edit). The customized markers are cleared ONLY when EVERY global adapter took\n * the bytes; total/partial materialize failure keeps the skill customized (F3).\n */\nasync function applyAuthorVersion(\n  slug: string,\n  adapters: Adapter[],\n  opts: ReconcileOptions,\n  reason: BackupReason,\n  target: 'upstream' | 'baseline',\n): Promise<ReconcileResult> {\n  const state = await readState()\n  const entry = state.skills[slug]\n  if (!entry) throw new ReconcileError(`No skill \"${slug}\" in kit state.`, 'not_found')\n  if (!entry.customized_from) {\n    throw new ReconcileError(`Skill \"${slug}\" is not customized.`, 'not_customized')\n  }\n  const owner = entry.owner ?? null\n  const pinDir = opts.pinDir ?? defaultPinDir()\n\n  // F6: never install a version the author has YANKED. Take theirs refuses when\n  // the held update it would install is flagged yanked (Restore original is\n  // fine \u2014 restoring the baseline never resurrects the withdrawn version).\n  if (target === 'upstream' && entry.held_update?.yanked && entry.held_update.hash === entry.hash) {\n    throw new ReconcileError(\n      `The upstream version of \"${slug}\" was yanked by the author \u2014 not installing it. Your edit was left in place.`,\n      'yanked',\n    )\n  }\n\n  // Resolve + verify the bytes to materialize (KTD6). Only the user's own edited\n  // bytes ever live unsigned on disk; every author version passes a verify gate.\n  let bundle: DecodedBundle\n  let hash: string\n  if (target === 'baseline') {\n    const baseline = entry.customized_from\n    const resolved = await resolveBaselineBundle(slug, baseline.hash)\n    // RF4: \"Restore original\" means the exact version the edit was made FROM. If\n    // that baseline is unobtainable (no stash, and the store has since advanced\n    // past it), ABORT \u2014 never silently apply the CURRENT upstream in its place\n    // (a different version, and one that would bypass the yanked guard, which is\n    // gated on target === 'upstream'). The edit is left live; Take theirs is the\n    // deliberate way to move to the current version.\n    if (!resolved) {\n      throw new ReconcileError(\n        `Cannot restore the original v${baseline.version} of \"${slug}\" \u2014 the version you edited from is no longer available. Your edit is left in place; use \"Take theirs\" to move to the current version.`,\n        'baseline_unavailable',\n      )\n    }\n    bundle = resolved\n    hash = canonicalContentHash(bundle)\n    // Integrity gate: the local snapshot must hash to the recorded lineage hash\n    // (its author signature was already verified when first materialized). Reuse\n    // verifyForMaterialize via a synthetic local entry so both paths are gated.\n    const verifyEntry: SkillEntry = { ...entry, source: 'local', hash: baseline.hash }\n    const failure = await verifyForMaterialize(verifyEntry, hash, pinDir)\n    if (failure !== null) {\n      throw new ReconcileError(\n        `Cannot restore the original version of \"${slug}\": ${failure}. Your edit was left in place.`,\n        'integrity_failed',\n      )\n    }\n  } else {\n    bundle = await readBundleFromSkillStore(slug)\n    hash = canonicalContentHash(bundle)\n    const failure = await verifyForMaterialize(entry, hash, pinDir)\n    if (failure !== null) {\n      throw new ReconcileError(\n        `Cannot apply the author version of \"${slug}\": ${failure}. Your edit was left in place.`,\n        'integrity_failed',\n      )\n    }\n  }\n\n  // Back up the user's current on-disk edit before anything overwrites it.\n  // F2: when a live copy exists but the backup could not be written, ABORT \u2014\n  // overwriting would destroy the only copy of the user's edit. Proceed without\n  // a backup only when there is genuinely no readable copy on disk.\n  const adapterSlug = bareAdapterSlug(slug, owner)\n  const { copies, unreadable } = await currentGlobalCopies(adapters, adapterSlug, owner)\n  // RF6: a PRESENT-but-unreadable copy holds an edit we cannot capture. Overwriting\n  // it would destroy an un-backed-up edit \u2014 abort, exactly as a failed backup does.\n  if (unreadable) {\n    throw new ReconcileError(\n      `Cannot apply the author version of \"${slug}\": an on-disk copy could not be read to back it up, so it was left in place. Retry once it is readable.`,\n      'backup_failed',\n    )\n  }\n  const copiesByDir = new Map(copies.map((c) => [c.dir, c] as const))\n  let backupId: string | null = null\n  if (copies.length > 0) {\n    try {\n      backupId = (\n        await backupSkillVersion({\n          lineage: { ...entry.customized_from },\n          copies: copies.map((c) => ({ adapter: c.adapter, dir: c.dir })),\n          reason,\n        })\n      ).backupId\n    } catch {\n      // Fall through with backupId still null \u2014 the guard below aborts.\n    }\n    if (backupId === null) {\n      throw new ReconcileError(\n        `Cannot apply the author version of \"${slug}\": backing up your current edit failed, so it was left in place. Retry once the backup location is writable.`,\n        'backup_failed',\n      )\n    }\n  }\n\n  // Materialize the verified bytes over the edit. RF3: take/restore is ALL-OR-\n  // NOTHING. Track per-adapter outcomes; on a PARTIAL failure roll the succeeded\n  // runtimes back to the user's edit (from the captured copy) so the edit stays\n  // live on EVERY runtime and the state is left customized \u2014 never a split disk\n  // (one runtime upstream, one edit). A total failure needs no rollback (nothing\n  // was overwritten). Only when every runtime takes the bytes do we clear state.\n  const materialized: string[] = []\n  const applied: Array<{ dir: string; edit: Map<string, Buffer> | null }> = []\n  let attempted = 0\n  let succeeded = 0\n  for (const adapter of adapters) {\n    if (adapter.kind === 'project') continue\n    attempted += 1\n    let dir: string | null = null\n    try {\n      dir = adapter.targetSkillDir(adapterSlug, { owner })\n    } catch {\n      dir = null\n    }\n    try {\n      const written = await adapter.materialize(adapterSlug, bundle, { owner })\n      materialized.push(...written)\n      succeeded += 1\n      // Remember what to undo if a LATER adapter fails: the captured edit tree\n      // for this dir (restore it), or null when this runtime had no prior copy\n      // (remove what we just wrote \u2014 the edit never lived here).\n      if (dir !== null) applied.push({ dir, edit: copiesByDir.get(dir)?.tree ?? null })\n    } catch {\n      // Degrade-never-delete: keep going; the rollback/throw below handles it.\n    }\n  }\n\n  if (attempted > 0 && succeeded === 0) {\n    throw new ReconcileError(\n      `Could not apply the author version of \"${slug}\": no agent accepted the write, so your edit is still live${backupId ? ` (backed up as ${backupId})` : ''}.`,\n      'materialize_failed',\n    )\n  }\n  if (succeeded < attempted) {\n    // RF3 rollback: restore the edit to every runtime we already wrote author\n    // bytes to, so no runtime is left on the author version. State is untouched\n    // (still customized) below by throwing before the clear.\n    try {\n      await rollbackApplied(applied)\n    } catch (err) {\n      throw new ReconcileError(\n        `Applied the author version of \"${slug}\" to ${succeeded}/${attempted} agents, then failed to roll the rest back; the disk may be split. Restore your edit from the backup${backupId ? ` (${backupId})` : ''}: ${(err as Error).message}`,\n        'rollback_failed',\n      )\n    }\n    throw new ReconcileError(\n      `Could not apply the author version of \"${slug}\" to every agent (${succeeded}/${attempted}); rolled your edit back everywhere, so it stays live and customized. Re-run once all agents are writable${backupId ? ` (your edit is backed up as ${backupId})` : ''}.`,\n      'partial_failure',\n    )\n  }\n\n  // Every adapter took the bytes \u2014 clear the customized state.\n  const now = new Date().toISOString()\n  const baselineHash = entry.customized_from.hash\n  const updated: SkillEntry = { ...entry, hash, materialized_hash: hash, updatedAt: now }\n  delete updated.customized_from\n  delete updated.held_update\n  state.skills[slug] = updated\n  await writeState(state)\n  // RF8: the skill is no longer customized \u2014 drop its baseline stash so the\n  // content-addressed baselines store doesn't accumulate forever.\n  await clearBaselineStash(baselineHash)\n\n  recordEvent(reason === 'take-upstream' ? 'skill.take' : 'skill.restore', detectInitiator(), {\n    slug,\n  })\n  return { slug, materialized, backupId }\n}\n\n/**\n * Undo a partial materialize (RF3): for each runtime we wrote author bytes to,\n * clear the dir and rewrite the user's captured edit tree \u2014 or, when that runtime\n * had no prior copy, remove the freshly written dir. Restores the pre-reconcile\n * disk state so the edit is live everywhere it was. Throws if any step fails\n * (the caller surfaces that as `rollback_failed`).\n */\nasync function rollbackApplied(\n  applied: Array<{ dir: string; edit: Map<string, Buffer> | null }>,\n): Promise<void> {\n  for (const { dir, edit } of applied) {\n    await rm(dir, { recursive: true, force: true })\n    if (!edit) continue // no prior copy \u2192 leaving it removed matches the pre-state\n    for (const [rel, bytes] of edit) {\n      const dest = join(dir, ...rel.split('/'))\n      await mkdir(dirname(dest), { recursive: true })\n      await writeFile(dest, bytes)\n    }\n  }\n}\n\n/**\n * Take theirs: back up the user's version and materialize the current UPSTREAM\n * bytes, clearing the customized state. The upstream bytes are the ones sync\n * already pulled into the skill store (available at reconcile time \u2014 no separate\n * held-bytes stash). Refuses when the upstream version was yanked (F6).\n */\nexport async function takeUpstream(\n  slug: string,\n  adapters: Adapter[],\n  opts: ReconcileOptions = {},\n): Promise<ReconcileResult> {\n  return applyAuthorVersion(slug, adapters, opts, 'take-upstream', 'upstream')\n}\n\n/**\n * Restore original: back up the user's version and materialize the BASELINE the\n * edit was made from (`customized_from`) \u2014 the version the user edited FROM,\n * distinct from the current/held upstream (F5). ABORTS (baseline_unavailable,\n * edit left live) when that baseline is no longer obtainable \u2014 never substitutes\n * the current upstream (RF4).\n */\nexport async function restoreOriginal(\n  slug: string,\n  adapters: Adapter[],\n  opts: ReconcileOptions = {},\n): Promise<ReconcileResult> {\n  return applyAuthorVersion(slug, adapters, opts, 'restore-original', 'baseline')\n}\n\n/**\n * Keep mine: acknowledge a held update so it stops surfacing until a NEWER\n * upstream hash appears (which replaces the record, clearing the flag). A no-op\n * when there is no unacknowledged held update. Returns the entry.\n */\nexport async function keepMine(slug: string): Promise<SkillEntry> {\n  const state = await readState()\n  const entry = state.skills[slug]\n  if (!entry) throw new ReconcileError(`No skill \"${slug}\" in kit state.`, 'not_found')\n  if (entry.held_update && !entry.held_update.acknowledged) {\n    entry.held_update = { ...entry.held_update, acknowledged: true }\n    entry.updatedAt = new Date().toISOString()\n    await writeState(state)\n  }\n  return entry\n}\n", "/**\n * `skillet propose <slug>` \u2014 sign and submit a skill update as a pending proposal.\n *\n * Unlike `skillet publish`, propose does NOT touch the live `latest_hash`. The\n * submitted bundle enters a `pending` state and must be approved by the skill\n * owner before a version is minted (SPEC \u00A79).\n *\n * Flow:\n *   1. Load the local identity (no inline minting \u2014 must be logged in first).\n *   2. Read the skill bundle from the kit store.\n *   3. Run the privacy scan; HIGH findings hard-block (same gate as publish).\n *   4. Compute the canonical content hash and fetch the manifest to learn base_hash.\n *   5. Sign via the \u00A74 envelope (signEnvelope over the canonical hash string).\n *   6. POST /api/v1/skills/:author/:slug/proposals.\n *   7. Record a `propose` metric event.\n *\n * Two entry points share that machinery:\n *   - `propose(slug)` \u2014 the original self-handle path: bundle from the kit\n *     store, target `@<identity.handle>/<slug>`, base from the live manifest.\n *     Byte-compatible for existing callers; `opts.target`/`opts.base` override\n *     the target skill and skip the manifest base fetch.\n *   - `proposeCustomized(slug, adapters)` \u2014 R10: bundle from the LIVE on-disk\n *     edit of a customized skill, target its `customized_from` lineage origin,\n *     base the lineage hash (no auto-rebase). Registry 403/409 come back as\n *     TYPED results (`not_authorized` / `base_stale`), never raw throws \u2014 both\n *     are honest outcomes the CLI/desktop render, and neither un-customizes the\n *     skill (the edit stays live and private).\n */\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport {\n  canonicalContentHash,\n  encodeBundle,\n  type DecodedBundle,\n} from \"@skillet/protocol\";\nimport { loadIdentity, type Identity } from \"../identity/index.js\";\nimport { loadAuthorKeyById } from \"../signing/index.js\";\nimport { signEnvelope } from \"../signing/envelope.js\";\nimport { readBundleFromSkillStore, readState } from \"../kit/store.js\";\nimport { RegistryClient, RegistryError } from \"../registry/client.js\";\nimport { recordEvent, detectInitiator } from \"../metrics.js\";\nimport { REGISTRY_URL_DEFAULT } from \"../kit/types.js\";\nimport type { Adapter } from \"../adapter.js\";\nimport { lineageRef, lineageTarget, readLiveCustomizedTree } from \"./edits.js\";\n\nexport type ProposeErrorCode =\n  | \"not_logged_in\"\n  | \"skill_not_found\"\n  | \"scan_blocked\"\n  | \"stale_base\"\n  | \"not_authorized\"\n  | \"manifest_fetch_failed\"\n  | \"propose_failed\"\n  | \"not_customized\"\n  | \"customized_missing\"\n  | \"local_origin\";\n\nexport class ProposeError extends Error {\n  readonly code: ProposeErrorCode;\n  readonly detail: unknown;\n\n  constructor(message: string, code: ProposeErrorCode, detail?: unknown) {\n    super(message);\n    this.name = \"ProposeError\";\n    this.code = code;\n    this.detail = detail;\n  }\n}\n\n/** Propose against this author/slug instead of the identity's own handle. */\nexport interface ProposeTarget {\n  author: string;\n  slug: string;\n}\n\n/** An explicit base (e.g. a capture's lineage) \u2014 skips the manifest base fetch. */\nexport interface ProposeBase {\n  version: number;\n  hash: string;\n}\n\nexport interface ProposeOptions {\n  registryUrl?: string;\n  configDir?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n  ignorePatterns?: string[];\n  target?: ProposeTarget;\n  base?: ProposeBase;\n}\n\nexport interface ProposeResult {\n  proposalId: string;\n  proposalUrl: string;\n  hash: string;\n  slug: string;\n}\n\nfunction defaultConfigDir(): string {\n  return process.env[\"XDG_CONFIG_HOME\"] ?? join(homedir(), \".config\");\n}\n\nasync function loadIdentityOrThrow(): Promise<Identity> {\n  const identity = await loadIdentity();\n  if (!identity) {\n    throw new ProposeError(\n      \"Not logged in. Run `skillet login --handle <handle> --name \\\"<Name>\\\"` first.\",\n      \"not_logged_in\",\n    );\n  }\n  return identity;\n}\n\nfunction buildClient(identity: Identity, opts: ProposeOptions): RegistryClient {\n  const registryUrl = (opts.registryUrl ?? identity.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/$/, \"\");\n  const token = opts.token ?? process.env[\"SKILLET_TOKEN\"];\n  return new RegistryClient({\n    baseUrl: registryUrl,\n    ...(token ? { token } : {}),\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n}\n\nfunction normalizeHash(hash: string): string {\n  return hash.startsWith(\"sha256:\") ? hash : `sha256:${hash}`;\n}\n\nexport async function propose(\n  slug: string,\n  opts: ProposeOptions = {},\n): Promise<ProposeResult> {\n  const configDir = opts.configDir ?? defaultConfigDir();\n\n  const identity = await loadIdentityOrThrow();\n\n  const state = await readState();\n  const entry = state.skills[slug];\n  if (!entry) {\n    throw new ProposeError(\n      `Skill \"${slug}\" not found in kit. Import it with \\`skillet import <path>\\` first.`,\n      \"skill_not_found\",\n    );\n  }\n\n  const bundle = await readBundleFromSkillStore(slug);\n  // No client-side scan (KTD2): the registry proposal route runs\n  // `secretsBlockingScan` at create AND approve (routes/proposals.ts), so a real\n  // secret is caught server-side. Placeholders pass its benign-corpus.\n\n  const contentHash = canonicalContentHash(bundle);\n  const client = buildClient(identity, opts);\n\n  const targetAuthor = opts.target?.author ?? identity.handle;\n  const targetSlug = opts.target?.slug ?? slug;\n\n  let baseHash: string | null = null;\n  if (opts.base) {\n    // An explicit base (capture lineage) is what the edit was made against \u2014\n    // never silently rebased onto the live manifest (R9: no auto-rebase; the\n    // server's 409 `base_stale` is the honest answer when upstream moved on).\n    baseHash = normalizeHash(opts.base.hash);\n  } else {\n    try {\n      const manifestResult = await client.getSkillManifest(`@${targetAuthor}/${targetSlug}`);\n      if (!manifestResult.notModified && manifestResult.value) {\n        const remoteHash = manifestResult.value.latest_hash ?? null;\n        if (remoteHash) {\n          baseHash = normalizeHash(remoteHash);\n        }\n      }\n    } catch (err) {\n      if (err instanceof RegistryError && err.status === 404) {\n        baseHash = null;\n      } else {\n        throw new ProposeError(\n          `Failed to fetch manifest: ${(err as Error).message}`,\n          \"manifest_fetch_failed\",\n        );\n      }\n    }\n  }\n\n  const key = await loadAuthorKeyById(configDir, identity.keyId);\n  const signature = signEnvelope(contentHash, key);\n  const files = encodeBundle(bundle);\n\n  let proposeResult: { proposal_id: string; proposal_url: string; state: string; proposed_hash: string };\n  try {\n    proposeResult = await client.proposeSkill({\n      author: targetAuthor,\n      slug: targetSlug,\n      files,\n      base_hash: baseHash,\n      signature,\n    });\n  } catch (err) {\n    if (err instanceof RegistryError && err.status === 409) {\n      throw new ProposeError(\n        err.message || \"Local is behind remote. Re-fetch the latest version and re-propose.\",\n        \"stale_base\",\n        (err as RegistryError).body,\n      );\n    }\n    if (err instanceof RegistryError && err.status === 403) {\n      throw new ProposeError(\n        err.message || \"You're not authorized to propose to this skill.\",\n        \"not_authorized\",\n        (err as RegistryError).body,\n      );\n    }\n    // The proposal secret gate refused a real credential \u2014 carry the structured\n    // body (reason + findings) so the CLI lists file:line, like publish does.\n    if (err instanceof RegistryError && err.code === \"scan_blocked\") {\n      throw new ProposeError(err.message, \"scan_blocked\", (err as RegistryError).body);\n    }\n    throw new ProposeError(\n      `Registry rejected proposal: ${(err as Error).message}`,\n      \"propose_failed\",\n    );\n  }\n\n  recordEvent(\"propose\", detectInitiator(), {\n    slug,\n    hash: contentHash,\n    proposalId: proposeResult.proposal_id,\n  });\n\n  return {\n    proposalId: proposeResult.proposal_id,\n    proposalUrl: proposeResult.proposal_url,\n    hash: contentHash,\n    slug,\n  };\n}\n\n// \u2500\u2500 propose-customized (R10) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ProposeCustomizedAccepted {\n  status: \"proposed\";\n  /** The lineage origin the proposal targets, `@author/slug`. */\n  ref: string;\n  proposalId: string;\n  proposalUrl: string;\n  hash: string;\n}\n\n/**\n * The two honest registry refusals, as data instead of throws: the surface\n * renders friendly copy, and the skill stays customized (the edit stays live).\n */\nexport interface ProposeCustomizedRefused {\n  status: \"not_authorized\" | \"base_stale\";\n  ref: string;\n  /** Registry-supplied detail \u2014 surfaces render their own copy on top. */\n  message: string;\n}\n\nexport type ProposeCustomizedResult = ProposeCustomizedAccepted | ProposeCustomizedRefused;\n\n/**\n * Propose a customized skill's edit upstream against its `customized_from`\n * lineage origin. The bundle is built from the LIVE on-disk edit (never the\n * skill store \u2014 the store holds the author's canonical content, not the edit),\n * the base is the lineage hash (no auto-rebase), and the signing + privacy-scan\n * machinery is exactly propose()'s. Proposing does NOT un-customize the skill:\n * the edit stays live and private until the author accepts (or the user takes\n * theirs).\n */\nexport async function proposeCustomized(\n  slug: string,\n  adapters: Adapter[],\n  opts: ProposeOptions = {},\n): Promise<ProposeCustomizedResult> {\n  const configDir = opts.configDir ?? defaultConfigDir();\n\n  const identity = await loadIdentityOrThrow();\n\n  const state = await readState();\n  const entry = state.skills[slug];\n  if (!entry) {\n    throw new ProposeError(`Skill \"${slug}\" not found in kit.`, \"skill_not_found\");\n  }\n  if (!entry.customized_from) {\n    throw new ProposeError(\n      `Skill \"${slug}\" is not customized \u2014 nothing to propose. Edit it first.`,\n      \"not_customized\",\n    );\n  }\n  const lineage = entry.customized_from;\n  const target = lineageTarget(lineage);\n  if (!target) {\n    throw new ProposeError(\n      `Skill \"${slug}\" has a local-only origin \u2014 nothing upstream to propose to.`,\n      \"local_origin\",\n    );\n  }\n  const ref = lineageRef(lineage);\n\n  const tree = await readLiveCustomizedTree(slug, entry.owner ?? null, adapters);\n  if (!tree || !tree.has(\"SKILL.md\")) {\n    throw new ProposeError(\n      `No live edit found on disk for \"${slug}\" \u2014 cannot build a proposal.`,\n      \"customized_missing\",\n    );\n  }\n  const bundle: DecodedBundle = tree;\n  // No client-side scan (KTD2) \u2014 the registry proposal route is the authority.\n\n  const contentHash = canonicalContentHash(bundle);\n  const client = buildClient(identity, opts);\n\n  const key = await loadAuthorKeyById(configDir, identity.keyId);\n  const signature = signEnvelope(contentHash, key);\n  const files = encodeBundle(bundle);\n\n  let proposeResult: { proposal_id: string; proposal_url: string; state: string; proposed_hash: string };\n  try {\n    proposeResult = await client.proposeSkill({\n      author: target.author,\n      slug: target.slug,\n      files,\n      base_hash: normalizeHash(lineage.hash),\n      signature,\n    });\n  } catch (err) {\n    if (err instanceof RegistryError && err.status === 403) {\n      return { status: \"not_authorized\", ref, message: err.message };\n    }\n    if (err instanceof RegistryError && err.status === 409) {\n      return { status: \"base_stale\", ref, message: err.message };\n    }\n    if (err instanceof RegistryError && err.code === \"scan_blocked\") {\n      throw new ProposeError(err.message, \"scan_blocked\", (err as RegistryError).body);\n    }\n    throw new ProposeError(\n      `Registry rejected proposal: ${(err as Error).message}`,\n      \"propose_failed\",\n    );\n  }\n\n  recordEvent(\"propose\", detectInitiator(), {\n    slug: lineage.slug,\n    hash: contentHash,\n    proposalId: proposeResult.proposal_id,\n  });\n\n  return {\n    status: \"proposed\",\n    ref,\n    proposalId: proposeResult.proposal_id,\n    proposalUrl: proposeResult.proposal_url,\n    hash: contentHash,\n  };\n}\n", "/**\n * `skillet eval [slug]` \u2014 run the v1 static basic eval against kit skill(s).\n */\nimport { runBasicEval, EvalError } from '@skillet/protocol';\nimport { readBundleFromSkillStore, readState } from '../kit/store.js';\n\nexport interface EvalSkillResult {\n  slug: string;\n  status: 'passed' | 'failed' | 'none';\n  case_results?: Array<{ id: string; passed: boolean; missing?: string[] }>;\n}\n\nexport async function evalSkills(slugs?: string[]): Promise<EvalSkillResult[]> {\n  const state = await readState();\n  const targets =\n    slugs && slugs.length > 0\n      ? slugs\n      : Object.keys(state.skills);\n\n  if (targets.length === 0) {\n    throw new Error('No skills in kit. Import a skill first.');\n  }\n\n  const results: EvalSkillResult[] = [];\n\n  for (const slug of targets) {\n    if (!state.skills[slug]) {\n      throw new Error(`Skill \"${slug}\" not found in kit.`);\n    }\n    const bundle = await readBundleFromSkillStore(slug);\n    try {\n      const run = runBasicEval(bundle);\n      results.push({\n        slug,\n        status: run.status,\n        ...(run.case_results ? { case_results: run.case_results } : {}),\n      });\n    } catch (err) {\n      if (err instanceof EvalError) {\n        throw new Error(`${slug}: ${err.message}`);\n      }\n      throw err;\n    }\n  }\n\n  return results;\n}\n", "/**\n * GitHub repo-spec parser for `skillet import <owner>/<repo>`.\n *\n * Accepts the friction-free skill.fish-style forms and the URLs people paste\n * out of a browser, normalising them all to `{ owner, repo, ref, subdir }`:\n *\n *   owner/repo\n *   owner/repo@ref                      (branch, tag, or commit sha)\n *   owner/repo/sub/dir                  (import only skills under sub/dir)\n *   owner/repo/sub/dir@ref\n *   github.com/owner/repo\n *   https://github.com/owner/repo\n *   https://github.com/owner/repo.git\n *   https://github.com/owner/repo/tree/<ref>/<subdir...>\n *\n * Like `parseSkillRef`, this runs BEFORE any value is interpolated into a\n * GitHub API URL or a filesystem path, so it doubles as the path-traversal /\n * URL-injection gate: every returned field matches a strict allowlist and is\n * safe to encode and join verbatim. `ref` and `subdir` are still URL-encoded\n * by the client, but rejecting `..` and control chars here keeps a hostile\n * spec from ever reaching the network.\n */\n\n// GitHub owner (user or org): alphanumerics and single hyphens, no leading or\n// trailing hyphen, max 39 chars.\nconst OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;\n// GitHub repo name: alphanumerics, hyphen, underscore, dot (a trailing `.git`\n// is stripped before this check). Max 100 chars.\nconst REPO_RE = /^[A-Za-z0-9._-]{1,100}$/;\n// A git ref \u2014 branch/tag/sha. Conservative: no `..`, no control chars, no\n// leading/trailing slash. Slashes are allowed (e.g. `release/1.x`).\nconst REF_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;\n// Control chars (and space) are never valid anywhere in a spec.\nconst CONTROL_RE = /[\\u0000-\\u0020\\u007f]/;\n\nexport interface GitHubRepoSpec {\n  owner: string;\n  repo: string;\n  /** Branch/tag/sha, or null to use the repo's default branch. */\n  ref: string | null;\n  /** POSIX subdirectory to scope discovery to, or null for the whole repo. */\n  subdir: string | null;\n}\n\nexport class GitHubSpecError extends Error {\n  readonly code: \"invalid_spec\";\n  constructor(message: string) {\n    super(message);\n    this.code = \"invalid_spec\";\n    this.name = \"GitHubSpecError\";\n  }\n}\n\n/**\n * Cheap, allocation-light check used by the CLI to decide whether an `import`\n * argument is a GitHub spec rather than a local path. Deliberately permissive:\n * it only needs to be true for things that have a slash, no whitespace, and no\n * leading `.`/`/`/`~` (which mark a local path). The authoritative validation\n * is `parseGitHubRepoSpec`; the CLI always tries a local `lstat` first, so a\n * false positive here only matters for paths that do not exist on disk.\n */\nexport function looksLikeGitHubSpec(input: string): boolean {\n  if (typeof input !== \"string\" || input.length === 0) return false;\n  if (/\\s/.test(input)) return false;\n  if (input.startsWith(\".\") || input.startsWith(\"/\") || input.startsWith(\"~\")) {\n    return false;\n  }\n  if (/^https?:\\/\\//i.test(input) || input.startsWith(\"github.com/\")) return true;\n  // A bare `a/b` with no scheme: needs at least one slash and a non-empty owner.\n  return /^[^/]+\\/[^/]+/.test(input);\n}\n\nfunction stripGitSuffix(repo: string): string {\n  return repo.endsWith(\".git\") ? repo.slice(0, -4) : repo;\n}\n\nfunction validateSubdir(raw: string): string {\n  const trimmed = raw.replace(/^\\/+|\\/+$/g, \"\");\n  if (trimmed.length === 0) {\n    throw new GitHubSpecError(\"Subdirectory in spec is empty\");\n  }\n  const segments = trimmed.split(\"/\");\n  for (const seg of segments) {\n    if (seg === \"\" || seg === \".\" || seg === \"..\") {\n      throw new GitHubSpecError(\n        `Unsafe subdirectory in spec: ${JSON.stringify(raw)}`,\n      );\n    }\n  }\n  return segments.join(\"/\");\n}\n\nfunction validateRef(raw: string): string {\n  if (!REF_RE.test(raw) || raw.includes(\"..\") || raw.endsWith(\"/\")) {\n    throw new GitHubSpecError(`Unsafe git ref in spec: ${JSON.stringify(raw)}`);\n  }\n  return raw;\n}\n\nfunction finalize(\n  owner: string,\n  repoRaw: string,\n  ref: string | null,\n  subdirRaw: string | null,\n): GitHubRepoSpec {\n  const repo = stripGitSuffix(repoRaw);\n  if (!OWNER_RE.test(owner)) {\n    throw new GitHubSpecError(\n      `Invalid GitHub owner ${JSON.stringify(owner)} (alphanumerics and hyphens, max 39 chars)`,\n    );\n  }\n  if (!REPO_RE.test(repo) || repo === \".\" || repo === \"..\") {\n    throw new GitHubSpecError(`Invalid GitHub repo name ${JSON.stringify(repo)}`);\n  }\n  return {\n    owner,\n    repo,\n    ref: ref ? validateRef(ref) : null,\n    subdir: subdirRaw != null ? validateSubdir(subdirRaw) : null,\n  };\n}\n\n/**\n * Parse any supported GitHub spec form into validated, injection-safe parts.\n * Throws `GitHubSpecError` on anything outside the grammar.\n */\nexport function parseGitHubRepoSpec(input: string): GitHubRepoSpec {\n  if (typeof input !== \"string\" || input.trim().length === 0) {\n    throw new GitHubSpecError(\"GitHub spec is empty\");\n  }\n  if (CONTROL_RE.test(input.trim())) {\n    throw new GitHubSpecError(\n      \"GitHub spec contains whitespace or control characters\",\n    );\n  }\n\n  let rest = input.trim();\n\n  // Strip a leading scheme / host so the rest is `owner/repo[/...]`.\n  rest = rest.replace(/^https?:\\/\\//i, \"\");\n  rest = rest.replace(/^github\\.com\\//i, \"\");\n  // Reject any leftover host (e.g. a GitHub Enterprise URL we don't support).\n  if (rest.includes(\"://\") || rest.includes(\"@github.com\")) {\n    throw new GitHubSpecError(\n      `Unsupported GitHub URL ${JSON.stringify(input)} \u2014 use owner/repo or a github.com URL`,\n    );\n  }\n\n  // A trailing `@ref` applies to the whole spec (owner/repo or owner/repo/sub).\n  let ref: string | null = null;\n  const atIdx = rest.lastIndexOf(\"@\");\n  if (atIdx > 0) {\n    ref = rest.slice(atIdx + 1);\n    rest = rest.slice(0, atIdx);\n    if (ref.length === 0) {\n      throw new GitHubSpecError(\"GitHub spec has empty ref after '@'\");\n    }\n  }\n\n  const parts = rest.split(\"/\").filter((p) => p.length > 0);\n  if (parts.length < 2) {\n    throw new GitHubSpecError(\n      `GitHub spec ${JSON.stringify(input)} must look like \"owner/repo\"`,\n    );\n  }\n\n  const [owner, repo, ...tail] = parts;\n\n  // Browser \"tree\" URLs: owner/repo/tree/<ref>/<subdir...>. The ref segment\n  // here wins over any `@ref` (you cannot have both in a tree URL anyway).\n  if (tail[0] === \"tree\" && tail.length >= 2) {\n    const treeRef = tail[1];\n    const subdir = tail.slice(2).join(\"/\");\n    return finalize(owner, repo, treeRef, subdir.length > 0 ? subdir : null);\n  }\n  // `blob` URLs point at a file; treat its directory as the subdir scope.\n  if (tail[0] === \"blob\" && tail.length >= 3) {\n    const treeRef = tail[1];\n    const filePath = tail.slice(2);\n    filePath.pop(); // drop the filename, keep the directory\n    const subdir = filePath.join(\"/\");\n    return finalize(owner, repo, treeRef, subdir.length > 0 ? subdir : null);\n  }\n\n  const subdir = tail.join(\"/\");\n  return finalize(owner, repo, ref, subdir.length > 0 ? subdir : null);\n}\n", "/**\n * Minimal, dependency-free GitHub source client for `skillet import owner/repo`.\n *\n * v1 is intentionally PUBLIC-ONLY and unauthenticated \u2014 no token is read,\n * stored, or sent. This keeps the import path off the credential-handling\n * surface entirely (the spec defers auth until publish) and means a private or\n * nonexistent repo surfaces the same clean 404 we turn into a friendly error.\n *\n * Two GitHub hosts are used:\n *   - api.github.com    repo metadata + the recursive git tree (2 calls total,\n *                       well inside the 60 req/hr unauthenticated budget).\n *   - raw.githubusercontent.com    file bytes (no API rate limit).\n *\n * fetch is injectable (`fetchImpl`) so the import flow is fully testable with\n * no network \u2014 the same pattern the registry client uses.\n */\n\nconst GITHUB_API = \"https://api.github.com\";\nconst GITHUB_RAW = \"https://raw.githubusercontent.com\";\nconst USER_AGENT = \"skillet-cli\";\n\nconst API_HEADERS: Record<string, string> = {\n  accept: \"application/vnd.github+json\",\n  \"user-agent\": USER_AGENT,\n  \"x-github-api-version\": \"2022-11-28\",\n};\n\nexport type GitHubErrorCode =\n  | \"not_found\"\n  | \"rate_limited\"\n  | \"http_error\"\n  | \"network_error\"\n  | \"fetch_failed\";\n\nexport class GitHubError extends Error {\n  readonly code: GitHubErrorCode;\n  readonly status?: number;\n  constructor(code: GitHubErrorCode, message: string, status?: number) {\n    super(message);\n    this.code = code;\n    if (status != null) this.status = status;\n    this.name = \"GitHubError\";\n  }\n}\n\n/** A single blob (file) entry from the recursive git tree. */\nexport interface TreeBlob {\n  /** POSIX path from the repo root. */\n  path: string;\n  /** Size in bytes as reported by the tree API (0 if unknown). */\n  size: number;\n}\n\nexport interface RepoMeta {\n  defaultBranch: string;\n  private: boolean;\n}\n\nexport interface GitHubSourceOptions {\n  /** Inject an alternate fetch impl for tests. Defaults to globalThis.fetch. */\n  fetchImpl?: typeof fetch;\n}\n\nexport class GitHubSource {\n  private readonly fetchImpl: typeof fetch;\n\n  constructor(opts: GitHubSourceOptions = {}) {\n    const f = opts.fetchImpl ?? globalThis.fetch;\n    if (typeof f !== \"function\") {\n      throw new GitHubError(\n        \"network_error\",\n        \"No fetch implementation available (Node >=18 or inject fetchImpl).\",\n      );\n    }\n    this.fetchImpl = f;\n  }\n\n  private async call(url: string, headers: Record<string, string>): Promise<Response> {\n    try {\n      return await this.fetchImpl(url, { headers });\n    } catch (err) {\n      throw new GitHubError(\n        \"network_error\",\n        `Network error reaching GitHub: ${(err as Error).message}`,\n      );\n    }\n  }\n\n  /** Map a 403 either to a rate-limit error or a generic HTTP error. */\n  private rateLimitOrHttp(res: Response, context: string): GitHubError {\n    const remaining = res.headers.get(\"x-ratelimit-remaining\");\n    if (res.status === 403 && remaining === \"0\") {\n      return new GitHubError(\n        \"rate_limited\",\n        \"GitHub rate limit reached for anonymous requests. Try again later.\",\n        403,\n      );\n    }\n    return new GitHubError(\"http_error\", `${context} (HTTP ${res.status}).`, res.status);\n  }\n\n  /**\n   * Repo metadata. A 404 here is the authoritative \"private or nonexistent\"\n   * signal for unauthenticated callers \u2014 GitHub returns 404 (not 403) for\n   * private repos to avoid leaking their existence.\n   */\n  async getRepoMeta(owner: string, repo: string): Promise<RepoMeta> {\n    const res = await this.call(`${GITHUB_API}/repos/${owner}/${repo}`, API_HEADERS);\n    if (res.status === 404) {\n      throw new GitHubError(\n        \"not_found\",\n        `Repository ${owner}/${repo} not found. It may be private \u2014 only public repos are supported (auth is deferred until publish).`,\n        404,\n      );\n    }\n    if (!res.ok) throw this.rateLimitOrHttp(res, `Could not read ${owner}/${repo}`);\n    const body = (await res.json()) as { default_branch?: string; private?: boolean };\n    return {\n      defaultBranch: body.default_branch ?? \"main\",\n      private: body.private === true,\n    };\n  }\n\n  /**\n   * The full recursive git tree at `ref`. Returns only blobs (files); trees\n   * and submodule `commit` entries are dropped. `truncated` is GitHub's signal\n   * that the repo exceeded its tree-listing cap and the result is partial.\n   */\n  async listTree(\n    owner: string,\n    repo: string,\n    ref: string,\n  ): Promise<{ blobs: TreeBlob[]; truncated: boolean }> {\n    const url = `${GITHUB_API}/repos/${owner}/${repo}/git/trees/${encodeURIComponent(ref)}?recursive=1`;\n    const res = await this.call(url, API_HEADERS);\n    if (res.status === 404) {\n      throw new GitHubError(\n        \"not_found\",\n        `Ref \"${ref}\" not found in ${owner}/${repo}.`,\n        404,\n      );\n    }\n    if (!res.ok) throw this.rateLimitOrHttp(res, `Could not list ${owner}/${repo}@${ref}`);\n    const body = (await res.json()) as {\n      tree?: Array<{ path?: string; type?: string; size?: number }>;\n      truncated?: boolean;\n    };\n    const blobs: TreeBlob[] = [];\n    for (const t of body.tree ?? []) {\n      if (t.type === \"blob\" && typeof t.path === \"string\") {\n        blobs.push({ path: t.path, size: typeof t.size === \"number\" ? t.size : 0 });\n      }\n    }\n    return { blobs, truncated: body.truncated === true };\n  }\n\n  /** Raw bytes of one file at `ref`. Path segments are individually encoded. */\n  async fetchBlob(\n    owner: string,\n    repo: string,\n    ref: string,\n    path: string,\n  ): Promise<Uint8Array> {\n    const encPath = path\n      .split(\"/\")\n      .map((seg) => encodeURIComponent(seg))\n      .join(\"/\");\n    const url = `${GITHUB_RAW}/${owner}/${repo}/${encodeURIComponent(ref)}/${encPath}`;\n    const res = await this.call(url, { \"user-agent\": USER_AGENT });\n    if (!res.ok) {\n      throw new GitHubError(\n        \"fetch_failed\",\n        `Failed to download ${path} from ${owner}/${repo}@${ref} (HTTP ${res.status}).`,\n        res.status,\n      );\n    }\n    return new Uint8Array(await res.arrayBuffer());\n  }\n}\n", "export {\n  parseGitHubRepoSpec,\n  looksLikeGitHubSpec,\n  GitHubSpecError,\n  type GitHubRepoSpec,\n} from \"./spec.js\";\nexport {\n  GitHubSource,\n  GitHubError,\n  type GitHubErrorCode,\n  type GitHubSourceOptions,\n  type RepoMeta,\n  type TreeBlob,\n} from \"./client.js\";\n", "/**\n * `skillet import owner/repo` \u2014 the remote GitHub source.\n *\n * Two phases, split so the CLI can put an interactive picker between them:\n *\n *   1. discoverGitHubSkills() \u2014 fetch the repo's tree, find every SKILL.md\n *      bundle, parse each one's name/description for the picker.\n *   2. importGitHubSkill()    \u2014 download the chosen bundle's files, validate\n *      against the \u00A72.1 caps/path rules, hash, and write it into the local kit.\n *\n * Imports land in the local kit as `source: \"local\"` \u2014 unpublished and\n * self-trusted, i.e. PRIVATE BY DEFAULT. Nothing is pushed to the registry and\n * no signature is minted; publishing stays a separate, explicit `skillet publish`.\n *\n * v1 is public-repo-only and unauthenticated \u2014 see {@link GitHubSource}.\n */\n\nimport { basename } from \"node:path\";\nimport { mkdir } from \"node:fs/promises\";\nimport matter from \"gray-matter\";\nimport {\n  canonicalContentHash,\n  validateBundle,\n  validateRequires,\n  validateTriggers,\n  MAX_BUNDLE_BYTES,\n  slugify as canonicalSlugify,\n  type DecodedBundle,\n} from \"@skillet/protocol\";\nimport { assertSafeSlug } from \"../util/pathsafe.js\";\nimport { ImportCollisionError, type ImportSkillOptions } from \"./import.js\";\nimport { readState, writeBundleToSkillStore, upsertSkill, skillContentDir } from \"../kit/store.js\";\nimport { recordEvent, detectInitiator } from \"../metrics.js\";\nimport type { SkillEntry } from \"../kit/types.js\";\nimport {\n  GitHubSource,\n  type GitHubSourceOptions,\n  type TreeBlob,\n} from \"../github/client.js\";\nimport {\n  parseGitHubRepoSpec,\n  type GitHubRepoSpec,\n} from \"../github/spec.js\";\n\nconst SKILL_ENTRYPOINT = \"SKILL.md\";\n\nfunction slugify(name: string): string {\n  return canonicalSlugify(name, { maxLength: 64 });\n}\n\n/** A SKILL.md bundle discovered in the repo tree, ready to be picked + imported. */\nexport interface DiscoveredGitHubSkill {\n  /** POSIX dir containing the SKILL.md; \"\" for a skill at the repo root. */\n  dir: string;\n  name: string;\n  description: string;\n  /** Kit slug this skill will import as (unique within the discovery set). */\n  slug: string;\n  /** Blobs that belong to this skill (repo-root-relative paths). */\n  files: TreeBlob[];\n  /** Sum of file sizes reported by the tree API. */\n  totalBytes: number;\n}\n\nexport interface GitHubDiscovery {\n  owner: string;\n  repo: string;\n  /** The ref actually used (resolved default branch when none was given). */\n  ref: string;\n  skills: DiscoveredGitHubSkill[];\n  /** True when GitHub truncated the tree listing (very large repo). */\n  truncated: boolean;\n}\n\nexport interface DiscoverOptions extends GitHubSourceOptions {\n  /** Override the spec's ref (and the repo default branch). */\n  ref?: string;\n  /** Inject a pre-built source (tests). Takes precedence over fetchImpl. */\n  source?: GitHubSource;\n}\n\nfunction dirOf(skillMdPath: string): string {\n  if (skillMdPath === SKILL_ENTRYPOINT) return \"\";\n  // \".../SKILL.md\" \u2192 strip the trailing \"/SKILL.md\"\n  return skillMdPath.slice(0, skillMdPath.length - (SKILL_ENTRYPOINT.length + 1));\n}\n\n/** True if `child` is `dir` itself or lives underneath it. \"\" matches all. */\nfunction isUnder(dir: string, child: string): boolean {\n  if (dir === \"\") return true;\n  return child === dir || child.startsWith(dir + \"/\");\n}\n\n/**\n * Assign a blob to the SKILL.md bundle that most closely contains it \u2014 the\n * deepest skill dir that is an ancestor. This is what makes nested skills work:\n * `pack/a/SKILL.md` and `pack/a/refs/x.md` belong to the same skill, but a\n * sibling `pack/b/SKILL.md` carves out its own bundle.\n */\nfunction nearestSkillDir(blobPath: string, skillDirsDeepestFirst: string[]): string | null {\n  for (const dir of skillDirsDeepestFirst) {\n    if (isUnder(dir, blobPath)) return dir;\n  }\n  return null;\n}\n\n/** Ensure every discovered skill maps to a distinct kit slug. */\nfunction disambiguate(slug: string, taken: Set<string>): string {\n  if (!taken.has(slug)) {\n    taken.add(slug);\n    return slug;\n  }\n  let n = 2;\n  while (taken.has(`${slug}-${n}`)) n++;\n  const out = `${slug}-${n}`;\n  taken.add(out);\n  return out;\n}\n\n/**\n * Phase 1: list the repo tree, find every SKILL.md bundle, and parse each one's\n * frontmatter for the picker. Returns an empty `skills` array (not an error)\n * when the repo simply contains no skills.\n */\nexport async function discoverGitHubSkills(\n  specOrString: string | GitHubRepoSpec,\n  opts: DiscoverOptions = {},\n): Promise<GitHubDiscovery> {\n  const spec =\n    typeof specOrString === \"string\"\n      ? parseGitHubRepoSpec(specOrString)\n      : specOrString;\n  const source =\n    opts.source ??\n    new GitHubSource(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {});\n\n  const meta = await source.getRepoMeta(spec.owner, spec.repo);\n  const ref = opts.ref ?? spec.ref ?? meta.defaultBranch;\n\n  const { blobs, truncated } = await source.listTree(spec.owner, spec.repo, ref);\n\n  // All SKILL.md locations, scoped to the requested subdir if any.\n  let skillDirs = blobs\n    .filter((b) => b.path === SKILL_ENTRYPOINT || b.path.endsWith(\"/\" + SKILL_ENTRYPOINT))\n    .map((b) => dirOf(b.path));\n  if (spec.subdir != null) {\n    skillDirs = skillDirs.filter((d) => isUnder(spec.subdir as string, d));\n  }\n  // Deepest first so nearestSkillDir() resolves to the closest ancestor.\n  const dirsDeepestFirst = [...new Set(skillDirs)].sort(\n    (a, b) => b.length - a.length,\n  );\n\n  // Bucket every blob under its nearest skill dir.\n  const buckets = new Map<string, TreeBlob[]>();\n  for (const dir of dirsDeepestFirst) buckets.set(dir, []);\n  for (const blob of blobs) {\n    if (spec.subdir != null && !isUnder(spec.subdir, blob.path)) continue;\n    const owner = nearestSkillDir(blob.path, dirsDeepestFirst);\n    if (owner != null) buckets.get(owner)!.push(blob);\n  }\n\n  // Build a stable, shallowest-first listing with parsed metadata.\n  const orderedDirs = [...buckets.keys()].sort((a, b) => a.length - b.length || a.localeCompare(b));\n  const takenSlugs = new Set<string>();\n  const skills: DiscoveredGitHubSkill[] = [];\n  for (const dir of orderedDirs) {\n    const files = buckets.get(dir)!;\n    const skillMdPath = dir === \"\" ? SKILL_ENTRYPOINT : `${dir}/${SKILL_ENTRYPOINT}`;\n    let name = dir === \"\" ? spec.repo : basename(dir);\n    let description = \"\";\n    try {\n      const bytes = await source.fetchBlob(spec.owner, spec.repo, ref, skillMdPath);\n      const fm = matter(Buffer.from(bytes).toString(\"utf8\")).data as Record<string, unknown>;\n      if (typeof fm[\"name\"] === \"string\" && fm[\"name\"].trim()) name = fm[\"name\"].trim();\n      if (typeof fm[\"description\"] === \"string\") description = fm[\"description\"];\n    } catch {\n      // Couldn't read the entrypoint \u2014 keep the dir-derived name; import will\n      // surface the real error if the user picks this one.\n    }\n    const slug = disambiguate(slugify(name), takenSlugs);\n    skills.push({\n      dir,\n      name,\n      description,\n      slug,\n      files,\n      totalBytes: files.reduce((sum, f) => sum + f.size, 0),\n    });\n  }\n\n  return { owner: spec.owner, repo: spec.repo, ref, skills, truncated };\n}\n\nexport interface ImportGitHubOptions extends GitHubSourceOptions, ImportSkillOptions {\n  source?: GitHubSource;\n}\n\n/**\n * Phase 2: download a discovered skill's files, validate, and write it into the\n * local kit (private by default). Returns the persisted {@link SkillEntry}.\n */\nexport async function importGitHubSkill(\n  discovery: Pick<GitHubDiscovery, \"owner\" | \"repo\" | \"ref\">,\n  skill: DiscoveredGitHubSkill,\n  opts: ImportGitHubOptions = {},\n): Promise<SkillEntry> {\n  const source =\n    opts.source ??\n    new GitHubSource(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {});\n\n  if (skill.totalBytes > MAX_BUNDLE_BYTES) {\n    throw new Error(\n      `Skill \"${skill.name}\" is ${skill.totalBytes} bytes; max bundle size is ${MAX_BUNDLE_BYTES}.`,\n    );\n  }\n\n  // Download each file, re-rooting its path at the skill dir.\n  const bundle: DecodedBundle = new Map();\n  for (const file of skill.files) {\n    const rel = skill.dir === \"\" ? file.path : file.path.slice(skill.dir.length + 1);\n    if (rel.length === 0) continue;\n    const bytes = await source.fetchBlob(discovery.owner, discovery.repo, discovery.ref, file.path);\n    bundle.set(rel, bytes);\n  }\n\n  if (!bundle.has(SKILL_ENTRYPOINT)) {\n    throw new Error(\n      `Skill at \"${skill.dir || \"<root>\"}\" has no ${SKILL_ENTRYPOINT} after fetch \u2014 nothing to import.`,\n    );\n  }\n\n  // \u00A72.1 caps + path safety (mirrors the local-import path).\n  validateBundle(bundle);\n\n  const entrypoint = bundle.get(SKILL_ENTRYPOINT)!;\n  const parsed = matter(Buffer.from(entrypoint).toString(\"utf8\"));\n  const fm = parsed.data as Record<string, unknown>;\n  const rawName =\n    typeof fm[\"name\"] === \"string\" && fm[\"name\"].trim() ? fm[\"name\"].trim() : skill.name;\n  const description =\n    typeof fm[\"description\"] === \"string\" ? fm[\"description\"] : skill.description;\n\n  validateRequires(fm[\"requires\"]);\n  validateTriggers(fm[\"triggers\"]);\n\n  assertSafeSlug(skill.slug);\n  const state = await readState();\n  if (state.skills[skill.slug] && !opts.force) {\n    throw new ImportCollisionError(skill.slug);\n  }\n\n  const hash = canonicalContentHash(bundle);\n  const now = new Date().toISOString();\n  const subpath = skill.dir ? `#${skill.dir}` : \"\";\n  const origin = `github:${discovery.owner}/${discovery.repo}@${discovery.ref}${subpath}`;\n\n  await mkdir(skillContentDir(skill.slug), { recursive: true });\n  await writeBundleToSkillStore(skill.slug, bundle);\n\n  const entry: SkillEntry = {\n    slug: skill.slug,\n    name: rawName,\n    description,\n    version: 1,\n    hash,\n    source: \"local\",\n    origin,\n    importedAt: now,\n    updatedAt: now,\n  };\n\n  await upsertSkill(entry);\n  recordEvent(\"skill.import\", detectInitiator(), { slug: skill.slug, origin: \"github\" });\n\n  return entry;\n}\n", "import { readdir } from \"node:fs/promises\";\nimport { join, basename } from \"node:path\";\nimport matter from \"gray-matter\";\nimport { canonicalContentHash } from \"@skillet/protocol\";\nimport { readBundleFromDir } from \"../bundle/read.js\";\nimport { isSkilletSlugDirName, parseSkilletSlugDir } from \"../bundle/write.js\";\nimport { parseSkillRef } from \"../registry/identifier.js\";\nimport { readState } from \"../kit/store.js\";\nimport { importSkill, slugify } from \"./import.js\";\nimport type { Adapter } from \"../adapter.js\";\nimport type { SkillEntry } from \"../kit/types.js\";\n\n/**\n * Cross-runtime skill discovery (first-run \"wow\").\n *\n * On first run, Skillet scans the runtimes the user already has installed\n * (Claude Code, Codex, \u2026) for skills they already run, and surfaces a single\n * \"we found N skills you already run \u2014 import them?\" moment. Nobody starts\n * empty.\n *\n * This intentionally reuses the existing local-import path:\n *   - `readBundleFromDir` + `canonicalContentHash` do the scan + hashing\n *     (same code the single-path `skillet import <dir>` uses).\n *   - `importSkill` does the actual import (private-by-default `source:\"local\"`).\n * There is no second scanner.\n */\n\n/** Friendly display names for the runtime adapter keys. The `windsurf` KEY is\n *  a frozen wire id; its LABEL is \"Devin Desktop\" after Cognition's June 2026\n *  rebrand of the Windsurf editor. */\nconst RUNTIME_LABELS: Record<string, string> = {\n  \"claude-code\": \"Claude Code\",\n  codex: \"Universal\",\n  \"codex-project\": \"Universal (project)\",\n  openclaw: \"OpenClaw\",\n  hermes: \"Hermes\",\n  cursor: \"Cursor\",\n  windsurf: \"Devin Desktop\",\n  devin: \"Devin\",\n  // opencode reads the universal ~/.agents/skills baseline (like Cursor), so it\n  // is surfaced as a detected runtime for labeling but is not a separate\n  // materializer \u2014 the baseline already writes the skills it reads.\n  opencode: \"opencode\",\n  \"opencode-project\": \"opencode (project)\",\n};\n\nexport function runtimeLabel(name: string): string {\n  return RUNTIME_LABELS[name] ?? name;\n}\n\n/**\n * Render a list of runtime keys as a human phrase, e.g.\n * [\"claude-code\",\"codex\"] \u2192 \"Claude Code + Codex\".\n */\nexport function runtimePhrase(names: string[]): string {\n  return names.map(runtimeLabel).join(\" + \");\n}\n\nexport interface DiscoveredSkill {\n  /** Best-effort slug derived from the bundle's `name` (display + import key). */\n  slug: string;\n  name: string;\n  description: string;\n  /** Canonical bundle content hash, `sha256:`-prefixed (\u00A72.2). */\n  hash: string;\n  /** Runtime adapter names where this exact bundle (by hash) was found. */\n  runtimes: string[];\n  /** A representative on-disk bundle dir to import from. */\n  bundleDir: string;\n  /** True iff a kit entry already has this content hash (already imported). */\n  alreadyInKit: boolean;\n  /**\n   * True when this on-disk bundle is already managed by Skillet \u2014 either\n   * materialized under the `owner--slug` / `_local--slug` layout, or matched\n   * to a registry entry in the kit by owner + slug.\n   */\n  fromSkillet: boolean;\n}\n\nexport interface DiscoveryReport {\n  /** Detected, scannable runtimes that were scanned (by adapter name). */\n  scannedRuntimes: string[];\n  /** Unique skills (deduped by content hash) found across scanned runtimes. */\n  skills: DiscoveredSkill[];\n  /** Subset of `skills` not already in the kit \u2014 the import candidates. */\n  newSkills: DiscoveredSkill[];\n}\n\n// Bound the recursive scan so a deep tree under a runtime's skills dir can\n// never run away. Real layouts are flat (`<root>/<slug>/SKILL.md`) or one level\n// deeper for owned namespaces (`<root>/@owner/<slug>/SKILL.md`).\nconst MAX_SCAN_DEPTH = 3;\n\n/**\n * Collect every directory at or under `root` (to `MAX_SCAN_DEPTH`) that\n * directly contains a `SKILL.md`. Descent stops at a bundle root so the\n * bundle's own subtree (`references/`, etc.) is not mistaken for nested skills.\n *\n * Never throws: a missing or unreadable directory is \"no skills here\", not an\n * error \u2014 discovery is best-effort by design.\n */\nasync function findBundleDirs(\n  root: string,\n  depth: number,\n  out: string[],\n): Promise<void> {\n  let entries;\n  try {\n    entries = await readdir(root, { withFileTypes: true });\n  } catch {\n    return;\n  }\n  if (entries.some((e) => e.isFile() && e.name === \"SKILL.md\")) {\n    out.push(root);\n    return;\n  }\n  if (depth >= MAX_SCAN_DEPTH) return;\n  for (const e of entries) {\n    if (e.isDirectory()) {\n      await findBundleDirs(join(root, e.name), depth + 1, out);\n    }\n  }\n}\n\ninterface ScannedBundle {\n  dir: string;\n  hash: string;\n  name: string;\n  description: string;\n  slug: string;\n}\n\n/**\n * Scan one global runtime's skills directory for existing skill bundles.\n * Project-scoped adapters expose no host-wide dir to scan and are skipped by\n * the caller. Invalid bundles (symlinks, oversize, missing root) are skipped\n * silently \u2014 one bad dir never aborts discovery.\n */\nasync function scanRuntime(adapter: Adapter): Promise<ScannedBundle[]> {\n  const dirs: string[] = [];\n  await findBundleDirs(adapter.targetDir, 0, dirs);\n\n  const found: ScannedBundle[] = [];\n  for (const dir of dirs) {\n    try {\n      const bundle = await readBundleFromDir(dir);\n      const entrypoint = bundle.get(\"SKILL.md\");\n      if (!entrypoint) continue;\n      const hash = canonicalContentHash(bundle);\n      const parsed = matter(Buffer.from(entrypoint).toString(\"utf8\"));\n      const fm = parsed.data as Record<string, unknown>;\n      const name = typeof fm[\"name\"] === \"string\" ? fm[\"name\"] : basename(dir);\n      const description =\n        typeof fm[\"description\"] === \"string\" ? fm[\"description\"] : \"\";\n      found.push({ dir, hash, name, description, slug: slugify(name) });\n    } catch {\n      // unreadable/invalid bundle \u2014 skip, never throw\n    }\n  }\n  return found;\n}\n\nfunction normalizeOwner(owner: string | null | undefined): string | null {\n  if (!owner) return null;\n  const trimmed = owner.trim();\n  if (!trimmed) return null;\n  return trimmed.startsWith(\"@\") ? trimmed.slice(1) : trimmed;\n}\n\nfunction entryOwnerSlug(entry: SkillEntry): { owner: string | null; slug: string } {\n  if (entry.slug.startsWith(\"@\") && entry.slug.includes(\"/\")) {\n    const parsed = parseSkillRef(entry.slug);\n    return { owner: parsed.author, slug: parsed.slug };\n  }\n  return { owner: normalizeOwner(entry.owner), slug: entry.slug };\n}\n\nfunction isFromSkillet(\n  bundleDir: string,\n  hash: string,\n  kitHashes: Set<string>,\n  registryKeys: Set<string>,\n): boolean {\n  if (kitHashes.has(hash)) return true;\n\n  const dirName = basename(bundleDir);\n  if (isSkilletSlugDirName(dirName)) return true;\n\n  const parsed = parseSkilletSlugDir(dirName);\n  if (parsed) {\n    const owner = normalizeOwner(parsed.owner);\n    const key = owner ? `${owner}/${parsed.slug}` : parsed.slug;\n    if (registryKeys.has(key)) return true;\n  }\n\n  return false;\n}\n\n/**\n * Discover skills the user already runs across their installed runtimes.\n *\n * Skills are deduped by canonical content hash, so the same bundle present in\n * both Claude Code and Codex counts once (with both runtimes listed). Skills\n * whose hash already exists in the kit are flagged `alreadyInKit` and excluded\n * from `newSkills`.\n */\nexport async function discoverExistingSkills(\n  adapters: Adapter[],\n): Promise<DiscoveryReport> {\n  const state = await readState();\n  const kitHashes = new Set(Object.values(state.skills).map((s) => s.hash));\n  const registryKeys = new Set<string>();\n  for (const entry of Object.values(state.skills)) {\n    if (entry.source !== \"registry\") continue;\n    const { owner, slug } = entryOwnerSlug(entry);\n    const key = owner ? `${owner}/${slug}` : slug;\n    registryKeys.add(key);\n  }\n\n  const scannedRuntimes: string[] = [];\n  const byHash = new Map<string, DiscoveredSkill>();\n\n  for (const adapter of adapters) {\n    if (adapter.kind === \"project\") continue;\n    let detected = false;\n    try {\n      detected = await adapter.detect();\n    } catch {\n      detected = false;\n    }\n    if (!detected) continue;\n    scannedRuntimes.push(adapter.name);\n\n    for (const f of await scanRuntime(adapter)) {\n      const existing = byHash.get(f.hash);\n      if (existing) {\n        if (!existing.runtimes.includes(adapter.name)) {\n          existing.runtimes.push(adapter.name);\n        }\n        continue;\n      }\n      const alreadyInKit = kitHashes.has(f.hash);\n      const fromSkillet = isFromSkillet(f.dir, f.hash, kitHashes, registryKeys);\n      byHash.set(f.hash, {\n        slug: f.slug,\n        name: f.name,\n        description: f.description,\n        hash: f.hash,\n        runtimes: [adapter.name],\n        bundleDir: f.dir,\n        alreadyInKit,\n        fromSkillet,\n      });\n    }\n  }\n\n  const skills = [...byHash.values()];\n  const newSkills = skills.filter((s) => !s.alreadyInKit && !s.fromSkillet);\n\n  // Note: local discovery (scanning your machine) is intentionally NOT recorded\n  // \u2014 it reads as snooping, and it's passive. Activity captures actions you take\n  // against your account (sync/add/publish), not what's on your disk.\n\n  return { scannedRuntimes, skills, newSkills };\n}\n\nexport interface ImportDiscoveredResult {\n  imported: SkillEntry[];\n  failed: Array<{ name: string; error: string }>;\n}\n\n/**\n * Import a set of discovered skills into the kit by reusing the local-import\n * path (`importSkill`). Each is stored private-by-default (`source:\"local\"`,\n * no owner). One bad bundle does not abort the rest.\n */\nexport async function importDiscoveredSkills(\n  skills: DiscoveredSkill[],\n): Promise<ImportDiscoveredResult> {\n  const imported: SkillEntry[] = [];\n  const failed: Array<{ name: string; error: string }> = [];\n  for (const s of skills) {\n    try {\n      imported.push(await importSkill(s.bundleDir));\n    } catch (err) {\n      failed.push({ name: s.name, error: (err as Error).message });\n    }\n  }\n  return { imported, failed };\n}\n\n/** Union of runtimes across a set of discovered skills (preserves first-seen order). */\nexport function runtimesAcross(skills: DiscoveredSkill[]): string[] {\n  const seen: string[] = [];\n  for (const s of skills) {\n    for (const r of s.runtimes) {\n      if (!seen.includes(r)) seen.push(r);\n    }\n  }\n  return seen;\n}\n", "export const SKILLET_ROUTE_HOOK_MARKER = \"route hook\";\nexport const LEGACY_CURSOR_HOOK_MARKER = \"route cursor-hook\";\n\nexport function shellQuote(value: string): string {\n  return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport function isSkilletRouteHookCommand(command: string): boolean {\n  return (\n    command.includes(SKILLET_ROUTE_HOOK_MARKER) ||\n    command.includes(LEGACY_CURSOR_HOOK_MARKER)\n  );\n}\n\nexport function recorderHookCommand(recorderCommand: string, runtime: string): string {\n  return `${shellQuote(recorderCommand)} route hook --runtime ${runtime}`;\n}\n", "import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { isSkilletRouteHookCommand, recorderHookCommand } from \"./shared.js\";\n\nexport interface ClaudeCodeRouteHookInstallOptions {\n  claudeDir?: string;\n  recorderCommand: string;\n}\n\nexport interface ClaudeCodeRouteHookInstallResult {\n  settingsPath: string;\n  command: string;\n  installed: boolean;\n}\n\ninterface ClaudeCommandHook {\n  type: \"command\";\n  command: string;\n  timeout?: number;\n}\n\ninterface ClaudeHookGroup {\n  matcher?: string;\n  hooks: ClaudeCommandHook[];\n}\n\ninterface ClaudeSettingsFile {\n  hooks?: Record<string, ClaudeHookGroup[]>;\n  [key: string]: unknown;\n}\n\nconst HOOK_EVENT = \"UserPromptSubmit\";\n\nfunction claudeSettingsPath(claudeDir = join(homedir(), \".claude\")): string {\n  return join(claudeDir, \"settings.json\");\n}\n\nasync function readSettings(path: string): Promise<ClaudeSettingsFile> {\n  try {\n    return JSON.parse(await readFile(path, \"utf8\")) as ClaudeSettingsFile;\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return {};\n    }\n    throw err;\n  }\n}\n\nfunction skilletHook(command: string): ClaudeCommandHook {\n  return { type: \"command\", command, timeout: 3 };\n}\n\nexport async function installClaudeCodeRouteHook(\n  opts: ClaudeCodeRouteHookInstallOptions,\n): Promise<ClaudeCodeRouteHookInstallResult> {\n  const claudeDir = opts.claudeDir ?? join(homedir(), \".claude\");\n  const settingsPath = claudeSettingsPath(claudeDir);\n  const command = recorderHookCommand(opts.recorderCommand, \"claude-code\");\n  const settings = await readSettings(settingsPath);\n  const hooks = settings.hooks ?? {};\n  const groups = hooks[HOOK_EVENT] ?? [];\n\n  const cleanedGroups: ClaudeHookGroup[] = groups.map((group) => ({\n    ...group,\n    hooks: (group.hooks ?? []).filter(\n      (entry) => !isSkilletRouteHookCommand(entry.command),\n    ),\n  }));\n\n  const targetGroup =\n    cleanedGroups.find((group) => group.matcher === \"\" || group.matcher === undefined) ??\n    cleanedGroups[0];\n\n  if (targetGroup) {\n    targetGroup.hooks.push(skilletHook(command));\n  } else {\n    cleanedGroups.push({\n      matcher: \"\",\n      hooks: [skilletHook(command)],\n    });\n  }\n\n  settings.hooks = { ...hooks, [HOOK_EVENT]: cleanedGroups };\n\n  await mkdir(claudeDir, { recursive: true, mode: 0o700 });\n  await writeFile(settingsPath, JSON.stringify(settings, null, 2) + \"\\n\", \"utf8\");\n\n  return { settingsPath, command, installed: true };\n}\n", "import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { isSkilletRouteHookCommand, recorderHookCommand } from \"./shared.js\";\n\nexport interface CodexRouteHookInstallOptions {\n  codexDir?: string;\n  recorderCommand: string;\n}\n\nexport interface CodexRouteHookInstallResult {\n  hooksPath: string;\n  configPath: string;\n  command: string;\n  installed: boolean;\n}\n\ninterface CodexCommandHook {\n  type: \"command\";\n  command: string;\n  timeout?: number;\n}\n\ninterface CodexHookGroup {\n  hooks: CodexCommandHook[];\n}\n\ninterface CodexHooksFile {\n  hooks?: Record<string, CodexHookGroup[]>;\n}\n\nconst HOOK_EVENT = \"UserPromptSubmit\";\n\nfunction codexDirPath(codexDir = join(homedir(), \".codex\")): string {\n  return codexDir;\n}\n\nfunction codexHooksPath(codexDir: string): string {\n  return join(codexDir, \"hooks.json\");\n}\n\nfunction codexConfigPath(codexDir: string): string {\n  return join(codexDir, \"config.toml\");\n}\n\nasync function readHooksFile(path: string): Promise<CodexHooksFile> {\n  try {\n    return JSON.parse(await readFile(path, \"utf8\")) as CodexHooksFile;\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return {};\n    }\n    throw err;\n  }\n}\n\nexport function ensureCodexHooksFeatureFlag(raw: string): string {\n  if (/^\\s*codex_hooks\\s*=\\s*true\\s*$/m.test(raw)) {\n    return raw.endsWith(\"\\n\") ? raw : `${raw}\\n`;\n  }\n\n  const featuresMatch = raw.match(/^\\[features\\]\\s*$/im);\n  if (featuresMatch) {\n    const lines = raw.split(\"\\n\");\n    const out: string[] = [];\n    let inserted = false;\n    for (let i = 0; i < lines.length; i++) {\n      out.push(lines[i] ?? \"\");\n      if (/^\\[features\\]\\s*$/i.test(lines[i] ?? \"\")) {\n        const next = lines[i + 1] ?? \"\";\n        if (!/^\\s*codex_hooks\\s*=/.test(next)) {\n          out.push(\"codex_hooks = true\");\n          inserted = true;\n        }\n      }\n    }\n    if (inserted) {\n      return out.join(\"\\n\").endsWith(\"\\n\") ? out.join(\"\\n\") : `${out.join(\"\\n\")}\\n`;\n    }\n  }\n\n  const trimmed = raw.trimEnd();\n  const suffix = trimmed.length > 0 ? \"\\n\\n\" : \"\";\n  return `${trimmed}${suffix}[features]\\ncodex_hooks = true\\n`;\n}\n\nasync function readConfig(path: string): Promise<string> {\n  try {\n    return await readFile(path, \"utf8\");\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return \"\";\n    }\n    throw err;\n  }\n}\n\nfunction skilletHook(command: string): CodexCommandHook {\n  return { type: \"command\", command, timeout: 3 };\n}\n\nexport async function installCodexRouteHook(\n  opts: CodexRouteHookInstallOptions,\n): Promise<CodexRouteHookInstallResult> {\n  const dir = codexDirPath(opts.codexDir);\n  const hooksPath = codexHooksPath(dir);\n  const configPath = codexConfigPath(dir);\n  const command = recorderHookCommand(opts.recorderCommand, \"codex\");\n\n  const configRaw = await readConfig(configPath);\n  const nextConfig = ensureCodexHooksFeatureFlag(configRaw);\n\n  const hooksFile = await readHooksFile(hooksPath);\n  const eventHooks = hooksFile.hooks ?? {};\n  const groups = eventHooks[HOOK_EVENT] ?? [];\n  const cleanedGroups: CodexHookGroup[] = groups.map((group) => ({\n    hooks: (group.hooks ?? []).filter(\n      (entry) => !isSkilletRouteHookCommand(entry.command),\n    ),\n  }));\n\n  if (cleanedGroups.length === 0) {\n    cleanedGroups.push({ hooks: [skilletHook(command)] });\n  } else {\n    cleanedGroups[0]?.hooks.push(skilletHook(command));\n  }\n\n  hooksFile.hooks = { ...eventHooks, [HOOK_EVENT]: cleanedGroups };\n\n  await mkdir(dir, { recursive: true, mode: 0o700 });\n  await writeFile(configPath, nextConfig, \"utf8\");\n  await writeFile(hooksPath, JSON.stringify(hooksFile, null, 2) + \"\\n\", \"utf8\");\n\n  return { hooksPath, configPath, command, installed: true };\n}\n", "import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n  isSkilletRouteHookCommand,\n  recorderHookCommand,\n} from \"./shared.js\";\n\nexport interface CursorRouteHookInstallOptions {\n  cursorDir?: string;\n  recorderCommand: string;\n}\n\nexport interface CursorRouteHookInstallResult {\n  hooksPath: string;\n  command: string;\n  installed: boolean;\n}\n\ninterface HookEntry {\n  command: string;\n  type?: \"command\" | \"prompt\";\n  matcher?: string;\n  timeout?: number;\n  failClosed?: boolean;\n}\n\ninterface CursorHooksFile {\n  version: 1;\n  hooks: Record<string, HookEntry[]>;\n}\n\nconst HOOK_EVENT = \"beforeSubmitPrompt\";\nconst HOOK_MATCHER = \"UserPromptSubmit\";\n\nfunction cursorHooksPath(cursorDir = join(homedir(), \".cursor\")): string {\n  return join(cursorDir, \"hooks.json\");\n}\n\nfunction parseHooksFile(raw: string): CursorHooksFile {\n  const parsed = JSON.parse(raw) as Partial<CursorHooksFile>;\n  return {\n    version: 1,\n    hooks:\n      parsed.hooks && typeof parsed.hooks === \"object\" && !Array.isArray(parsed.hooks)\n        ? parsed.hooks\n        : {},\n  };\n}\n\nasync function readHooksFile(path: string): Promise<CursorHooksFile> {\n  try {\n    return parseHooksFile(await readFile(path, \"utf8\"));\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return { version: 1, hooks: {} };\n    }\n    throw err;\n  }\n}\n\nexport async function installCursorRouteHook(\n  opts: CursorRouteHookInstallOptions,\n): Promise<CursorRouteHookInstallResult> {\n  const cursorDir = opts.cursorDir ?? join(homedir(), \".cursor\");\n  const hooksPath = cursorHooksPath(cursorDir);\n  const command = recorderHookCommand(opts.recorderCommand, \"cursor\");\n  const hooksFile = await readHooksFile(hooksPath);\n  const current = hooksFile.hooks[HOOK_EVENT] ?? [];\n  const nextEntries = current.filter((entry) => !isSkilletRouteHookCommand(entry.command));\n  nextEntries.push({\n    command,\n    matcher: HOOK_MATCHER,\n    timeout: 3,\n    failClosed: false,\n  });\n  hooksFile.hooks[HOOK_EVENT] = nextEntries;\n\n  await mkdir(cursorDir, { recursive: true, mode: 0o700 });\n  await writeFile(hooksPath, JSON.stringify(hooksFile, null, 2) + \"\\n\", \"utf8\");\n\n  return { hooksPath, command, installed: true };\n}\n", "export const HOOK_CAPABLE_RUNTIMES = [\"cursor\", \"claude-code\", \"codex\"] as const;\n\nexport type HookCapableRuntime = (typeof HOOK_CAPABLE_RUNTIMES)[number];\n\nexport function isHookCapableRuntime(name: string): name is HookCapableRuntime {\n  return (HOOK_CAPABLE_RUNTIMES as readonly string[]).includes(name);\n}\n\n/** Map sync adapter names to hook installer runtime keys (deduped). */\nexport function hookRuntimesFromDetected(detected: string[]): HookCapableRuntime[] {\n  const out = new Set<HookCapableRuntime>();\n  for (const name of detected) {\n    if (name === \"cursor\") out.add(\"cursor\");\n    else if (name === \"claude-code\") out.add(\"claude-code\");\n    else if (name === \"codex\" || name === \"codex-project\") out.add(\"codex\");\n  }\n  return [...out];\n}\n", "import { installClaudeCodeRouteHook } from \"./claude-code.js\";\nimport { installCodexRouteHook } from \"./codex.js\";\nimport { installCursorRouteHook } from \"./cursor.js\";\nimport { isHookCapableRuntime } from \"./runtime-specs.js\";\n\nexport {\n  hookRuntimesFromDetected,\n  isHookCapableRuntime,\n  HOOK_CAPABLE_RUNTIMES,\n  type HookCapableRuntime,\n} from \"./runtime-specs.js\";\nexport {\n  installCursorRouteHook,\n  type CursorRouteHookInstallOptions,\n  type CursorRouteHookInstallResult,\n} from \"./cursor.js\";\nexport {\n  installClaudeCodeRouteHook,\n  type ClaudeCodeRouteHookInstallOptions,\n  type ClaudeCodeRouteHookInstallResult,\n} from \"./claude-code.js\";\nexport {\n  installCodexRouteHook,\n  ensureCodexHooksFeatureFlag,\n  type CodexRouteHookInstallOptions,\n  type CodexRouteHookInstallResult,\n} from \"./codex.js\";\nexport {\n  SKILLET_ROUTE_HOOK_MARKER,\n  LEGACY_CURSOR_HOOK_MARKER,\n  isSkilletRouteHookCommand,\n  recorderHookCommand,\n} from \"./shared.js\";\n\nexport interface RouteHookInstallOptions {\n  recorderCommand: string;\n  cursorDir?: string;\n  claudeDir?: string;\n  codexDir?: string;\n}\n\nexport interface RouteHookInstallResult {\n  runtime: string;\n  installed: boolean;\n  configPath?: string;\n  command?: string;\n  error?: string;\n}\n\nexport interface InstallRouteHooksResult {\n  installed: string[];\n  skipped: string[];\n  warnings: string[];\n  results: RouteHookInstallResult[];\n}\n\nexport async function installRouteHook(\n  runtime: string,\n  opts: RouteHookInstallOptions,\n): Promise<RouteHookInstallResult> {\n  if (!isHookCapableRuntime(runtime)) {\n    return { runtime, installed: false, error: `unsupported runtime: ${runtime}` };\n  }\n\n  try {\n    if (runtime === \"cursor\") {\n      const result = await installCursorRouteHook({\n        recorderCommand: opts.recorderCommand,\n        cursorDir: opts.cursorDir,\n      });\n      return {\n        runtime,\n        installed: result.installed,\n        configPath: result.hooksPath,\n        command: result.command,\n      };\n    }\n    if (runtime === \"claude-code\") {\n      const result = await installClaudeCodeRouteHook({\n        recorderCommand: opts.recorderCommand,\n        claudeDir: opts.claudeDir,\n      });\n      return {\n        runtime,\n        installed: result.installed,\n        configPath: result.settingsPath,\n        command: result.command,\n      };\n    }\n    const result = await installCodexRouteHook({\n      recorderCommand: opts.recorderCommand,\n      codexDir: opts.codexDir,\n    });\n    return {\n      runtime,\n      installed: result.installed,\n      configPath: result.hooksPath,\n      command: result.command,\n    };\n  } catch (err) {\n    return {\n      runtime,\n      installed: false,\n      error: (err as Error).message,\n    };\n  }\n}\n\nexport async function installRouteHooksForRuntimes(\n  runtimes: string[],\n  opts: RouteHookInstallOptions,\n): Promise<InstallRouteHooksResult> {\n  const installed: string[] = [];\n  const skipped: string[] = [];\n  const warnings: string[] = [];\n  const results: RouteHookInstallResult[] = [];\n\n  for (const runtime of runtimes) {\n    if (!isHookCapableRuntime(runtime)) {\n      skipped.push(runtime);\n      continue;\n    }\n    const result = await installRouteHook(runtime, opts);\n    results.push(result);\n    if (result.installed) {\n      installed.push(runtime);\n    } else if (result.error) {\n      warnings.push(`${runtime} /skillet hook: ${result.error}`);\n    } else {\n      skipped.push(runtime);\n    }\n  }\n\n  return { installed, skipped, warnings, results };\n}\n", "import type { Adapter } from '../adapter.js';\nimport {\n  sync,\n  type AdapterResult,\n  type SyncOptions,\n} from './sync.js';\n\nexport interface MaterializeSkillsOptions extends SyncOptions {\n  /** Skill slugs to write (e.g. `@author/skill`). Required. */\n  slugs: string[];\n  /**\n   * When true (default), skip registry pull before materialize. Skill `add`\n   * sets this after `add()` / import. Kit `add` sets false so union pull runs.\n   */\n  skipPull?: boolean;\n}\n\nexport interface MaterializeSkillsResult {\n  materialized: Array<{ slug: string; dest: string; hash: string }>;\n  adapters: AdapterResult[];\n  failed: Array<{ slug: string; reason: string }>;\n  lockPath: string;\n}\n\n/**\n * Materialize an explicit slug set into the given adapters without syncing\n * the whole kit. Used by `skillet add` and `skillet add kit`.\n */\nexport async function materializeSkills(\n  cwd: string,\n  adapters: Adapter[],\n  opts: MaterializeSkillsOptions,\n): Promise<MaterializeSkillsResult> {\n  if (opts.slugs.length === 0) {\n    return { materialized: [], adapters: [], failed: [], lockPath: '' };\n  }\n\n  const skipPull = opts.skipPull !== false;\n  const result = await sync(cwd, adapters, {\n    ...opts,\n    slugs: opts.slugs,\n    skipPull,\n    pullMode: skipPull ? 'unattended' : opts.pullMode,\n  });\n\n  return {\n    materialized: result.materialized,\n    adapters: result.adapters,\n    failed: result.failed,\n    lockPath: result.lockPath,\n  };\n}\n", "import { formatSkillRef } from '../registry/identifier.js';\n\n/** Map registry `author:slug` skill_id to canonical `@author/slug`. */\nexport function skillIdToRef(skillId: string): string {\n  const idx = skillId.indexOf(':');\n  if (idx <= 0 || idx >= skillId.length - 1) {\n    throw new Error(`Invalid skill_id ${JSON.stringify(skillId)}`);\n  }\n  const author = skillId.slice(0, idx);\n  const slug = skillId.slice(idx + 1);\n  return formatSkillRef(author, slug);\n}\n\nexport function kitSkillRefsFromIds(\n  skillIds: Array<{ skill_id: string }>,\n): string[] {\n  return skillIds.map((s) => skillIdToRef(s.skill_id));\n}\n", "// `skillet status` \u2014 surfaces the current state of every skill in the local kit,\n// with quarantined and flagged entries called out so a kit member can see\n// what is being held by server-side harm scan (\u00A73.2).\n\nimport { readState } from \"../kit/store.js\";\nimport type { SkillEntry } from \"../kit/types.js\";\n\nexport type StatusBucket = \"quarantined\" | \"flagged\" | \"pending\" | \"clean\";\n\nexport interface StatusEntry {\n  slug: string;\n  bucket: StatusBucket;\n  hash: string;\n  /** Highest-severity finding from the last sync \u2014 null when clean/pending. */\n  topConfidence: \"low\" | \"medium\" | \"high\" | null;\n  /** Total findings from the last sync \u2014 0 for clean/pending. */\n  totalFindings: number;\n}\n\nexport interface StatusReport {\n  total: number;\n  byBucket: Record<StatusBucket, number>;\n  entries: StatusEntry[];\n  /**\n   * Quick-flag for callers: true when at least one skill is quarantined.\n   * `skillet status` exits non-zero in this case so it can be wired into CI.\n   */\n  hasQuarantined: boolean;\n}\n\nfunction bucketFor(entry: SkillEntry): StatusBucket {\n  const status = entry.scan?.status;\n  if (status === \"quarantined\") return \"quarantined\";\n  if (status === \"flagged\") return \"flagged\";\n  if (status === \"pending\") return \"pending\";\n  return \"clean\";\n}\n\nexport async function status(): Promise<StatusReport> {\n  const state = await readState();\n  const entries: StatusEntry[] = [];\n  const byBucket: Record<StatusBucket, number> = {\n    quarantined: 0,\n    flagged: 0,\n    pending: 0,\n    clean: 0,\n  };\n\n  const slugs = Object.keys(state.skills).sort();\n  for (const slug of slugs) {\n    const entry = state.skills[slug]!;\n    const bucket = bucketFor(entry);\n    byBucket[bucket] += 1;\n    entries.push({\n      slug,\n      bucket,\n      hash: entry.hash,\n      topConfidence: entry.scan?.findings_summary.topConfidence ?? null,\n      totalFindings: entry.scan?.findings_summary.total ?? 0,\n    });\n  }\n\n  // Quarantined first, then flagged, then pending, then clean \u2014 operator's\n  // first read should land on the entries that need attention.\n  const order: Record<StatusBucket, number> = {\n    quarantined: 0,\n    flagged: 1,\n    pending: 2,\n    clean: 3,\n  };\n  entries.sort(\n    (a, b) => order[a.bucket] - order[b.bucket] || a.slug.localeCompare(b.slug),\n  );\n\n  return {\n    total: entries.length,\n    byBucket,\n    entries,\n    hasQuarantined: byBucket.quarantined > 0,\n  };\n}\n", "/**\n * Parse a kit permalink handle (`@owner/slug` or `owner/slug`) before it is\n * interpolated into registry URLs.\n */\nconst SEGMENT_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;\nconst CONTROL_RE = /[\\u0000-\\u0020\\u007f]/;\n\nexport class KitHandleError extends Error {\n  readonly code = 'invalid_kit_handle' as const;\n  constructor(message: string) {\n    super(message);\n    this.name = 'KitHandleError';\n  }\n}\n\nexport interface KitHandle {\n  owner: string;\n  slug: string;\n  /** Normalised `@owner/slug` form. */\n  canonical: string;\n}\n\nfunction validateSegment(label: string, value: string): void {\n  if (!value || CONTROL_RE.test(value)) {\n    throw new KitHandleError(`Invalid kit ${label}.`);\n  }\n  if (!SEGMENT_RE.test(value)) {\n    throw new KitHandleError(\n      `Invalid kit ${label}: use lowercase letters, numbers, and hyphens only.`,\n    );\n  }\n}\n\n/** Parse `@owner/kit-slug` or `owner/kit-slug`. */\nexport function parseKitHandle(input: string): KitHandle {\n  const trimmed = input.trim();\n  if (!trimmed) {\n    throw new KitHandleError('Kit handle is required (e.g. @owner/my-kit).');\n  }\n  const raw = trimmed.startsWith('@') ? trimmed.slice(1) : trimmed;\n  const slash = raw.indexOf('/');\n  if (slash <= 0 || slash === raw.length - 1) {\n    throw new KitHandleError('Kit handle must be owner/slug (e.g. @owner/my-kit).');\n  }\n  const owner = raw.slice(0, slash);\n  const slug = raw.slice(slash + 1);\n  if (raw.includes('/', slash + 1)) {\n    throw new KitHandleError('Kit handle must be exactly owner/slug.');\n  }\n  validateSegment('owner', owner);\n  validateSegment('slug', slug);\n  return { owner, slug, canonical: `@${owner}/${slug}` };\n}\n", "import type { SyncManifestItem } from '@skillet/protocol';\nimport { loadRegistryBearer } from '../auth-token.js';\nimport { readDeviceId } from '../device-token.js';\nimport { RegistryClient } from './client.js';\nimport {\n  defaultEtagCachePath,\n  readEtagCache,\n  unionManifestEtagKey,\n  writeEtagCache,\n} from './etag-cache.js';\n\nexport interface DeviceScopedManifestResult {\n  /** Present when the registry returned a manifest; `[]` when the device union is empty. */\n  items: SyncManifestItem[] | undefined;\n  /** True when we got an authoritative 200 from the registry. */\n  fetched: boolean;\n}\n\nexport interface ResolveDeviceScopedManifestOptions {\n  registryUrl: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n  etagCachePath?: string;\n}\n\n/**\n * Fetch the sync manifest this machine should display \u2014 same scoping contract as\n * `skillet sync`. Session tokens pass `?device=` when `device.json` has an id;\n * device tokens rely on server-side `principal.device_id` exclusions.\n */\nexport async function resolveDeviceScopedManifest(\n  opts: ResolveDeviceScopedManifestOptions,\n): Promise<DeviceScopedManifestResult> {\n  const bearer = await loadRegistryBearer(opts.token);\n  if (!bearer.token) {\n    return { items: undefined, fetched: false };\n  }\n\n  const deviceId = await readDeviceId();\n\n  const client = new RegistryClient({\n    baseUrl: opts.registryUrl,\n    token: bearer.token,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n\n  const queryOpts =\n    bearer.kind === 'session' && deviceId ? { device: deviceId } : {};\n\n  const etagPath = opts.etagCachePath ?? defaultEtagCachePath();\n  const cache = await readEtagCache(etagPath);\n  if (!cache.union) cache.union = {};\n  const unionKey = unionManifestEtagKey(\n    opts.registryUrl,\n    bearer.kind === 'session' && deviceId ? deviceId : undefined,\n    bearer.kind,\n  );\n  const cachedUnionEtag = cache.union[unionKey] ?? null;\n\n  try {\n    const res = await client.getSyncManifest({\n      ...queryOpts,\n      etag: cachedUnionEtag,\n    });\n    if (res.notModified || !res.value) {\n      return { items: undefined, fetched: false };\n    }\n    if (res.etag) {\n      cache.union[unionKey] = res.etag;\n      await writeEtagCache(etagPath, cache);\n    }\n    return { items: res.value.items, fetched: true };\n  } catch {\n    return { items: undefined, fetched: false };\n  }\n}\n", "export {\n  formatSkillRef,\n  parseSkillRef,\n  SkillRefError,\n  type SkillRef,\n} from './identifier.js';\nexport {\n  parseKitHandle,\n  KitHandleError,\n  type KitHandle,\n} from './kit-handle.js';\nexport {\n  RegistryClient,\n  RegistryError,\n  type CacheableResult,\n  type RegistryClientOptions,\n  type RegistryManifest,\n  type RegistryKitView,\n  type VersionDetail,\n} from './client.js';\nexport {\n  resolveDeviceScopedManifest,\n  type DeviceScopedManifestResult,\n  type ResolveDeviceScopedManifestOptions,\n} from './device-manifest.js';\n\n// Re-export the Ed25519Envelope alias so downstream can type-check publish bodies.\nexport type { Signature as PublishSignature } from '../signing/envelope.js';\n", "/**\n * `skillet add @author/skill` \u2014 fetch a registry skill into the kit.\n *\n * Flow (PROTOCOL \u00A74 + \u00A76.1):\n *   1. Parse `@author/slug` strictly \u2014 anything that wouldn't pass the\n *      server's grammar is rejected before any HTTP request.\n *   2. GET /api/v1/skills/:author/:slug/manifest \u2192 latest_hash, the matching\n *      version's signature envelope, author_key_id, author_public_key.\n *   3. GET /api/v1/skills/:author/:slug/versions/:hash \u2192 the bundle.\n *   4. Recompute canonicalContentHash(bundle) \u2014 MUST equal the server-stamped\n *      content_hash. A mismatch means the bundle on the wire isn't the bundle\n *      that was signed (acceptance criterion 1, integrity gate).\n *   5. TOFU-resolve the author key via resolveAuthorKey, then verify the\n *      envelope against signatureBytes(content_hash). Fail-closed on\n *      key_id_mismatch, signature_invalid, or a missing pubkey.\n *   6. Write the decoded bundle to the local skill store and persist the kit\n *      entry \u2014 source=registry, private-by-default, with the signature,\n *      pubkey, key_id, version index, and the original registry URL.\n *\n * Re-running `skillet add` on an already-imported ref is idempotent: same\n * content_hash \u2192 no-op; new content_hash \u2192 fetches the newer version, which\n * the materialize-time graded diff will still gate before writing into any\n * runtime directory.\n */\n\nimport matter from 'gray-matter';\nimport {\n  CONTENT_HASH_PREFIX,\n  canonicalContentHash,\n  type DecodedBundle,\n} from '@skillet/protocol';\nimport {\n  RegistryClient,\n  RegistryError,\n  parseSkillRef,\n  type RegistryClientOptions,\n} from '../registry/index.js';\nimport {\n  verifyEnvelope,\n  SignatureError,\n} from '../signing/envelope.js';\nimport { isEd25519Signature, isSessionAttestedSignature } from '../signing/session-attest.js';\nimport { resolveAuthorKey, defaultPinDir } from '../signing/pin.js';\nimport {\n  writeBundleToSkillStore,\n  upsertSkill,\n  readState,\n} from '../kit/store.js';\nimport { recordEvent, detectInitiator } from '../metrics.js';\nimport type { SkillEntry } from '../kit/types.js';\n\nexport interface AddOptions {\n  /** Registry base URL (e.g. `https://registry.skillet.md`). */\n  registryUrl: string;\n  /** Bearer token if available. */\n  token?: string;\n  /** Inject an alternate fetch impl for tests. */\n  fetchImpl?: typeof fetch;\n  /** TOFU pin directory; defaults to `$XDG_CONFIG_HOME/skillet/pinned`. */\n  pinDir?: string;\n  /** When true, mark the entry as locally pinned (registry-pull won't touch it). */\n  pin?: boolean;\n}\n\nexport interface AddResult {\n  entry: SkillEntry;\n  /** True when this was the first sighting of the author's key. */\n  newlyPinned: boolean;\n  /** True when nothing changed (same ref, same hash already in kit). */\n  noop: boolean;\n}\n\n/**\n * Resolve, verify, and persist a registry-served skill into the local kit.\n * Throws RegistryError or SignatureError on every fail-closed path; the CLI\n * surfaces the `.code` on stderr and exits non-zero.\n */\nexport async function add(ref: string, opts: AddOptions): Promise<AddResult> {\n  const parsed = parseSkillRef(ref);\n  // parseSkillRef already enforced /^[a-z0-9-]+$/ on both author and slug \u2014\n  // no `..`, no path separators, no shell metacharacters \u2014 so the canonical\n  // ref is safe to use as the kit key AND as the relative path inside the\n  // local skill store (`~/.skillet/skills/@author/slug/`).\n\n  const client = new RegistryClient(buildClientOptions(opts));\n\n  // ------------------------------------------------------------------------\n  // 1. Manifest \u2192 pick latest_hash + its version envelope + author identity.\n  // ------------------------------------------------------------------------\n  const manifestRes = await client.getSkillManifest(parsed.canonical);\n  const manifest = manifestRes.value;\n  if (!manifest) {\n    // `notModified` is meaningless on a first `add` \u2014 we passed no ETag.\n    throw new RegistryError(\n      'malformed_response',\n      `Manifest for ${parsed.canonical} returned 304 unexpectedly`,\n    );\n  }\n  if (!manifest.latest_hash || manifest.versions.length === 0) {\n    throw new RegistryError(\n      'no_versions',\n      `${parsed.canonical} has no published versions yet`,\n    );\n  }\n  if (!manifest.author_key_id || !manifest.author_public_key) {\n    throw new RegistryError(\n      'author_not_claimed',\n      `Author \"@${parsed.author}\" has not registered a signing key \u2014 refusing to TOFU-pin a missing identity`,\n    );\n  }\n\n  // Versions come back DESC by published_at; index 0 is the newest. Position\n  // counted from the oldest is the monotonic `version` integer the protocol\n  // talks about (PROTOCOL \u00A72.3 placeholder; matches the server's sync route).\n  const latestIdx = manifest.versions.findIndex(\n    (v) => v.hash === manifest.latest_hash,\n  );\n  if (latestIdx < 0) {\n    throw new RegistryError(\n      'malformed_response',\n      `Manifest latest_hash ${manifest.latest_hash} not present in versions list for ${parsed.canonical}`,\n    );\n  }\n  const versionInt = manifest.versions.length - latestIdx;\n  const manifestVersion = manifest.versions[latestIdx];\n  if (manifestVersion.yanked) {\n    throw new RegistryError(\n      'version_yanked',\n      `${parsed.canonical}@${manifest.latest_hash} is yanked \u2014 refusing new install`,\n    );\n  }\n  if (!manifestVersion.signature) {\n    throw new RegistryError(\n      'unsigned_version',\n      `${parsed.canonical}@${manifest.latest_hash} is unsigned \u2014 registry-served versions must carry an Ed25519 envelope (PROTOCOL \u00A74)`,\n    );\n  }\n\n  // ------------------------------------------------------------------------\n  // 2. Skip the round trip if this exact hash is already in the kit.\n  // ------------------------------------------------------------------------\n  const state = await readState();\n  const expectedHashPrefixed = `${CONTENT_HASH_PREFIX}${stripPrefix(manifest.latest_hash)}`;\n  const existing = state.skills[parsed.canonical];\n  if (existing && existing.source === 'registry' && existing.hash === expectedHashPrefixed) {\n    // Honour `--pin` even when re-running on an already-imported ref so the\n    // user can flip the pinned bit without re-downloading.\n    if (opts.pin && !existing.pinned) {\n      const updated: SkillEntry = { ...existing, pinned: true, updatedAt: new Date().toISOString() };\n      await upsertSkill(updated);\n      pingInstallMetric(client, parsed.canonical);\n      return { entry: updated, newlyPinned: false, noop: false };\n    }\n    pingInstallMetric(client, parsed.canonical);\n    return { entry: existing, newlyPinned: false, noop: true };\n  }\n\n  // ------------------------------------------------------------------------\n  // 3. Fetch the actual bundle.\n  // ------------------------------------------------------------------------\n  const version = await client.getVersion(parsed.canonical, manifest.latest_hash);\n\n  // The version endpoint can shadow the manifest signature (e.g. on a rotation\n  // mid-publish). Use whichever is present, preferring the version-detail\n  // one since that's the canonical pairing with the bytes we just received.\n  const envelope = version.signature ?? manifestVersion.signature;\n  if (!envelope) {\n    throw new RegistryError(\n      'unsigned_version',\n      `Version ${manifest.latest_hash} for ${parsed.canonical} has no signature on either manifest or detail endpoint`,\n    );\n  }\n  // Author identity: prefer the version-detail body (locks identity to the\n  // exact published version), fall back to the manifest top-level fields.\n  const authorKeyId = version.author_key_id ?? manifest.author_key_id;\n  const authorPubBase64 = version.author_public_key ?? manifest.author_public_key;\n  if (!authorKeyId || !authorPubBase64) {\n    throw new RegistryError(\n      'author_not_claimed',\n      `Author \"@${parsed.author}\" identity is incomplete \u2014 cannot verify ${manifest.latest_hash}`,\n    );\n  }\n  if (!isSessionAttestedSignature(envelope)) {\n    if (envelope.key_id !== authorKeyId) {\n      // Loud \u2014 a signature signed by a different key than the claimed identity.\n      throw new SignatureError(\n        'key_id_mismatch',\n        `Version ${manifest.latest_hash} signature key_id ${envelope.key_id} disagrees with author_key_id ${authorKeyId}`,\n      );\n    }\n  }\n  // Bind author_key_id to author_pub: key_id MUST equal hex(raw pubkey bytes).\n  // Without this check a MITM can claim any pinned key_id while serving an\n  // attacker pub, sign with the attacker priv, and pass both the envelope check\n  // and the TOFU string comparison \u2014 the pinned key provides zero protection.\n  const derivedKeyId = Buffer.from(authorPubBase64, 'base64').toString('hex');\n  if (derivedKeyId !== authorKeyId) {\n    throw new SignatureError(\n      'signature_invalid',\n      `author_key_id ${authorKeyId} does not match author_pub (derived key_id ${derivedKeyId})`,\n    );\n  }\n\n  // ------------------------------------------------------------------------\n  // 4. Integrity gate: recompute the canonical hash before trusting bytes.\n  // ------------------------------------------------------------------------\n  const recomputed = canonicalContentHash(version.bundle);\n  if (recomputed !== version.content_hash) {\n    throw new SignatureError(\n      'signature_invalid',\n      `Bundle for ${parsed.canonical}@${manifest.latest_hash} hashed to ${recomputed}, server stamped ${version.content_hash}`,\n    );\n  }\n  if (recomputed !== expectedHashPrefixed) {\n    throw new SignatureError(\n      'signature_invalid',\n      `Bundle hash ${recomputed} does not match manifest latest_hash ${expectedHashPrefixed}`,\n    );\n  }\n\n  // ------------------------------------------------------------------------\n  // 5. TOFU + envelope verification.\n  // ------------------------------------------------------------------------\n  const pinDir = opts.pinDir ?? defaultPinDir();\n  let newlyPinned = false;\n  if (isSessionAttestedSignature(envelope)) {\n    // Registry attested via verified session at publish time.\n  } else {\n    if (!isEd25519Signature(envelope)) {\n      throw new SignatureError(\n        'signature_invalid',\n        `unsupported signature alg ${JSON.stringify((envelope as { alg: string }).alg)}`,\n      );\n    }\n    const resolved = await resolveAuthorKey(\n      parsed.author,\n      { key_id: authorKeyId, pub: authorPubBase64 },\n      versionInt,\n      pinDir,\n    );\n    newlyPinned = resolved.newlyPinned;\n    verifyEnvelope(recomputed, envelope, resolved.keyObject, { expectedKeyId: authorKeyId });\n  }\n\n  // ------------------------------------------------------------------------\n  // 6. Persist the bundle + kit entry.\n  // ------------------------------------------------------------------------\n  await writeBundleToSkillStore(parsed.canonical, version.bundle);\n\n  const { name, description } = extractMetadata(version.bundle, parsed.slug);\n  const now = new Date().toISOString();\n  const entry: SkillEntry = {\n    slug: parsed.canonical,\n    owner: parsed.author,\n    name,\n    description,\n    version: versionInt,\n    hash: recomputed,\n    source: 'registry',\n    // An explicit `skillet add @them/skill` pulls a stranger's skill \u2014\n    // classify as external so the external global default (diff-gate) applies.\n    // Preserve an existing class so a re-add doesn't silently downgrade trust.\n    sourceClass: existing?.sourceClass ?? 'external',\n    registryUrl: client.url,\n    authorKeyId,\n    authorPubBase64,\n    signature: envelope,\n    importedAt: existing?.importedAt ?? now,\n    updatedAt: now,\n    ...(opts.pin ? { pinned: true } : {}),\n  };\n  await upsertSkill(entry);\n\n  pingInstallMetric(client, parsed.canonical);\n\n  // Metric: human-initiated `add` event (PROTOCOL \u00A710 \u2014 daemon/CI excluded).\n  recordEvent('skill.add', detectInitiator(), {\n    slug: parsed.canonical,\n    newlyPinned,\n    pinned: entry.pinned === true,\n  });\n\n  return { entry, newlyPinned, noop: false };\n}\n\nimport { pingInstallMetric } from \"../registry/install-metric.js\";\n\nfunction buildClientOptions(opts: AddOptions): RegistryClientOptions {\n  return {\n    baseUrl: opts.registryUrl,\n    token: opts.token,\n    fetchImpl: opts.fetchImpl,\n  };\n}\n\nfunction stripPrefix(s: string): string {\n  return s.startsWith(CONTENT_HASH_PREFIX) ? s.slice(CONTENT_HASH_PREFIX.length) : s;\n}\n\n/**\n * Pull the SKILL.md frontmatter out of the decoded bundle so the kit entry\n * carries the human name/description without reading from disk again. The\n * bundle has already passed validateBundle (SKILL.md present at root), so\n * the get below is safe; fall back to the slug for skills without frontmatter.\n */\nfunction extractMetadata(\n  bundle: DecodedBundle,\n  fallbackName: string,\n): { name: string; description: string } {\n  const entrypoint = bundle.get('SKILL.md');\n  if (!entrypoint) return { name: fallbackName, description: '' };\n  try {\n    const parsed = matter(Buffer.from(entrypoint).toString('utf8'));\n    const fm = parsed.data as Record<string, unknown>;\n    const name = typeof fm.name === 'string' && fm.name.length > 0 ? fm.name : fallbackName;\n    const description = typeof fm.description === 'string' ? fm.description : '';\n    return { name, description };\n  } catch {\n    return { name: fallbackName, description: '' };\n  }\n}\n", "/** Machine pair codes \u2014 same alphabet and shape as registry connect-pair routes. */\n\nexport const PAIR_CODE_LEN = 8;\n\nexport const PAIR_CODE_RE = /^[A-Z2-9]{8}$/;\n\nexport function normalizePairCode(raw: string): string {\n  return raw.trim().toUpperCase().replace(/[\\s_-]+/g, '');\n}\n\nexport function isValidPairCode(raw: string): boolean {\n  return PAIR_CODE_RE.test(normalizePairCode(raw));\n}\n\nfunction looksLikeFormattedCode(raw: string): boolean {\n  const trimmed = raw.trim();\n  if (!trimmed) return false;\n  if (/\\b(NPX|CONNECT|SKILLET)\\b/i.test(trimmed)) return false;\n  const normalized = normalizePairCode(raw);\n  if (normalized.length !== 8 || !PAIR_CODE_RE.test(normalized)) return false;\n  const tokens = trimmed.split(/\\s+/);\n  if (tokens.length >= 3) return false;\n  if (tokens.length === 1) return true;\n  return /^[A-Z2-9]{4}[-\\s][A-Z2-9]{4}$/i.test(trimmed) || tokens.length === 2;\n}\n\n/**\n * Pull an 8-character pair code from raw user input. Accepts a bare code, dashed\n * formatting, or a full `npx \u2026 connect <code>` paste.\n */\nexport function extractPairCode(raw: string): string | null {\n  const normalized = normalizePairCode(raw);\n  if (looksLikeFormattedCode(raw) && PAIR_CODE_RE.test(normalized)) {\n    return normalized;\n  }\n\n  const upper = raw.trim().toUpperCase();\n  const connectMatch = upper.match(/\\bCONNECT\\b\\s*([A-Z2-9]{8})\\b/);\n  if (connectMatch?.[1] && PAIR_CODE_RE.test(connectMatch[1])) {\n    return connectMatch[1];\n  }\n\n  if (!/\\b(NPX|CONNECT|SKILLET)\\b/.test(upper)) {\n    return null;\n  }\n\n  const collapsed = upper.replace(/[^A-Z2-9]/g, '');\n  const matches = collapsed.match(/[A-Z2-9]{8}/g);\n  if (!matches?.length) {\n    return null;\n  }\n  const last = matches[matches.length - 1]!;\n  return PAIR_CODE_RE.test(last) ? last : null;\n}\n", "import { RegistryClient } from './client.js'\nimport { loadRegistryBearer } from '../auth-token.js'\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js'\n\n/**\n * A best-effort authed registry client for account-scoped decision write-through\n *. Returns null when no bearer is configured, so CLI commands stay fully\n * functional offline \u2014 the local lock is recorded regardless and reconciles on\n * the next `skillet sync`.\n */\nexport async function accountClient(registryUrl?: string): Promise<RegistryClient | null> {\n  const { token } = await loadRegistryBearer()\n  if (!token) return null\n  // Honor the registry override like every other authed path \u2014 a local/dev\n  // token sent to prod fails silently and the account read looks empty.\n  const base = registryUrl ?? process.env['SKILLET_REGISTRY_URL'] ?? REGISTRY_URL_DEFAULT\n  return new RegistryClient({\n    baseUrl: base.replace(/\\/+$/, ''),\n    token,\n  })\n}\n\n/** Registry skill id (\"owner:slug\") from a local state key (\"@owner/slug\"). */\nexport function skillIdFromSlug(slug: string, owner: string | null | undefined): string | null {\n  if (!owner) return null\n  const bare = slug.split('/').pop()\n  return bare ? `${owner}:${bare}` : null\n}\n", "import { readFile, readdir, lstat } from 'node:fs/promises'\nimport { join, relative, sep } from 'node:path'\nimport { canonicalContentHash } from '@skillet/protocol'\nimport type { Adapter } from '../adapter.js'\nimport { readState, readBundleFromSkillStore } from '../kit/store.js'\nimport { skillStoreDirExists } from '../kit/store-integrity.js'\nimport { loadAuthorKey } from '../signing/index.js'\nimport {\n  renderUpdateReview,\n  checkLock,\n  requiresQuarantineConsent,\n  renderFindingsSummary,\n  checkRejection,\n  getLastApprovedVersion,\n  defaultApprovalLockPath,\n  loadPolicy,\n} from '../trust/index.js'\nimport { accountClient } from '../registry/account-client.js'\nimport { requiresApproval, isAuthorPinned } from './sync.js'\nimport type { RegistryClient } from '../registry/client.js'\n\nexport interface PendingEntry {\n  slug: string\n  /** Hex-encoded Ed25519 author key ID, or null for locally-imported skills. */\n  authorKeyId: string | null\n  /** Last version approved in the approval lock, or null if never approved. */\n  approvedVersion: number | null\n  /**\n   * Semver display label for `approvedVersion`. The approval lock records\n   * integers only, so this stays undefined until a labeled source exists;\n   * renderers fall back to the integer.\n   */\n  approvedVersionLabel?: string\n  /** Current version in local state (the incoming update awaiting review). */\n  incomingVersion: number\n  /**\n   * Semver display label for `incomingVersion`, persisted on the synced kit\n   * entry by the registry pull. Undefined for entries synced from servers\n   * predating labels; renderers fall back to the integer.\n   */\n  incomingVersionLabel?: string\n  /**\n   * Graded unified diff of the incoming bundle vs the most complete\n   * materialized copy, rendered once with an applies-to header by\n   * renderUpdateReview(). Empty string when no change is detectable\n   * (e.g. no adapters materialized yet and bundle is new).\n   */\n  diff: string\n  /** True when the harm scan quarantined this version \u2014 review surfaces must\n   *  show `scanSummary` before any approve decision (informed consent). */\n  quarantined: boolean\n  /** Rendered harm-scan findings block for quarantined entries (counts +\n   *  highlights, same detail as the sync-time gate), null when clean. */\n  scanSummary: string | null\n}\n\nexport interface PendingResult {\n  pending: PendingEntry[]\n}\n\nexport interface PendingOptions {\n  /** Override the approval lock path (defaults to $XDG_DATA_HOME/skillet/skillet.lock). */\n  approvalLockPath?: string\n  /** Override the trust-policy path. */\n  policyPath?: string\n  /** Override $XDG_CONFIG_HOME for loading the user's own signing key. */\n  configDir?: string\n  /** Project root for project-scoped adapters (Cursor, Windsurf). */\n  cwd?: string\n  /** Injectable account client for tests; defaults to the configured bearer. */\n  client?: RegistryClient | null\n  /** Override the pinned-author-key directory (defaults under configDir). */\n  pinDir?: string\n}\n\nfunction bareAdapterSlug(slug: string, owner: string | null): string {\n  if (owner && slug.startsWith('@')) {\n    const idx = slug.indexOf('/')\n    if (idx >= 0) return slug.slice(idx + 1)\n  }\n  return slug\n}\n\nasync function walkMaterialized(\n  root: string,\n  dir: string,\n  adapterName: string,\n  out: Record<string, Buffer>,\n): Promise<void> {\n  let entries\n  try {\n    entries = await readdir(dir, { withFileTypes: true })\n  } catch {\n    return\n  }\n  for (const entry of entries) {\n    const absPath = join(dir, entry.name)\n    let st\n    try {\n      st = await lstat(absPath)\n    } catch {\n      continue\n    }\n    if (st.isDirectory()) {\n      await walkMaterialized(root, absPath, adapterName, out)\n    } else if (st.isFile()) {\n      const rel = relative(root, absPath)\n      const posix = sep === '/' ? rel : rel.split(sep).join('/')\n      out[`${adapterName}/${posix}`] = await readFile(absPath)\n    }\n  }\n}\n\nasync function readCurrentMaterialized(\n  slug: string,\n  adapters: Adapter[],\n  owner: string | null | undefined,\n  cwd: string,\n): Promise<Record<string, Buffer>> {\n  const result: Record<string, Buffer> = {}\n  for (const adapter of adapters) {\n    if (adapter.kind === 'project' && !cwd) continue\n    const skillDir = adapter.targetSkillDir(slug, { owner: owner ?? null, cwd })\n    await walkMaterialized(skillDir, skillDir, adapter.name, result)\n  }\n  return result\n}\n\n/**\n * Returns all skills that have a pending update requiring human review:\n * diff-gated by trust policy, not yet approved in the approval lock, and not\n * explicitly rejected. Rejected versions are omitted \u2014 they will not re-surface\n * until a newer version arrives.\n *\n * Detects active adapters from the passed list to compute a graded diff of\n * currently materialized files vs the incoming bundle. Undetected adapters\n * contribute nothing to the diff (their on-disk directories are absent).\n */\nexport async function listPending(\n  adapters: Adapter[],\n  opts: PendingOptions = {},\n): Promise<PendingResult> {\n  const {\n    configDir = process.env['XDG_CONFIG_HOME'] ?? `${process.env['HOME']}/.config`,\n    approvalLockPath = defaultApprovalLockPath(),\n    cwd = process.cwd(),\n  } = opts\n\n  const state = await readState()\n  const policy = await loadPolicy(opts.policyPath)\n  let ownKeyId: string | null = null\n  try {\n    ownKeyId = (await loadAuthorKey(configDir)).keyId\n  } catch {\n    // No signing key configured \u2014 nothing resolves as self.\n  }\n\n  // Detect which adapters are active so the diff reflects real on-disk state.\n  const active: Adapter[] = []\n  for (const adapter of adapters) {\n    try {\n      if (await adapter.detect()) active.push(adapter)\n    } catch {\n      // Detection errors are non-fatal for the listing command.\n    }\n  }\n\n  // Merge the account-scoped decisions so an item approved on another surface\n  // (web/desktop) isn't shown as pending here. Best-effort: offline falls back\n  // to the local lock only.\n  const serverApproved = new Set<string>()\n  // Account handle resolves \"self\" for web-first accounts with no local\n  // signing key \u2014 pending must agree with sync's gate (see requiresApproval).\n  let ownHandle: string | null = null\n  try {\n    const client = opts.client ?? (await accountClient())\n    const acct = await client?.getMyDecisions()\n    for (const d of acct?.decisions ?? []) {\n      if (d.state === 'approved') serverApproved.add(d.version_hash)\n    }\n    ownHandle = (await client?.whoami())?.handle ?? null\n  } catch {\n    // offline / no bearer \u2014 local lock is the source.\n  }\n\n  const pending: PendingEntry[] = []\n\n  const pinDir = opts.pinDir ?? `${configDir.replace(/\\/$/, '')}/skillet/pinned`\n  for (const [slug, entry] of Object.entries(state.skills)) {\n    // Same gate as sync, pin-awareness included \u2014 the two surfaces must agree.\n    const authorPinned = await isAuthorPinned(entry, slug, pinDir)\n    if (!requiresApproval(entry, policy, ownKeyId, authorPinned, ownHandle)) continue\n    // We treat missing local store state as a diagnostics omission and avoid\n    // aborting the entire pending listing.\n    if (!(await skillStoreDirExists(slug))) continue\n\n    const bundle = await readBundleFromSkillStore(slug)\n    const currentHash = canonicalContentHash(bundle)\n\n    if (serverApproved.has(currentHash)) continue\n    if (await checkLock(approvalLockPath, slug, entry.version, currentHash)) continue\n    if (await checkRejection(approvalLockPath, slug, entry.version)) continue\n\n    const approvedVersion = await getLastApprovedVersion(approvalLockPath, slug)\n    const owner = entry.owner ?? null\n    const adapterSlug = bareAdapterSlug(slug, owner)\n\n    const prev = await readCurrentMaterialized(adapterSlug, active, owner, cwd)\n    // One diff against the incoming bundle (not one per agent copy) \u2014 see\n    // renderUpdateReview for why the fan-out repeats itself.\n    const next: Record<string, Buffer> = {}\n    for (const [bundlePath, bytes] of bundle) {\n      next[bundlePath] = Buffer.from(bytes)\n    }\n\n    const quarantined = requiresQuarantineConsent(entry.scan)\n    pending.push({\n      slug,\n      authorKeyId: entry.authorKeyId ?? null,\n      approvedVersion,\n      incomingVersion: entry.version,\n      ...(entry.versionLabel ? { incomingVersionLabel: entry.versionLabel } : {}),\n      diff: renderUpdateReview({ prev, next, adapterNames: active.map((a) => a.name) }),\n      quarantined,\n      scanSummary: quarantined && entry.scan ? renderFindingsSummary(entry.scan) : null,\n    })\n  }\n\n  return { pending }\n}\n", "import { canonicalContentHash } from '@skillet/protocol'\nimport { readState, readBundleFromSkillStore } from '../kit/store.js'\nimport { recordApproval, defaultApprovalLockPath } from '../trust/index.js'\nimport { accountClient, skillIdFromSlug } from '../registry/account-client.js'\nimport type { RegistryClient } from '../registry/client.js'\n\nexport interface ApproveOptions {\n  /** Override the approval lock path (defaults to $XDG_DATA_HOME/skillet/skillet.lock). */\n  approvalLockPath?: string\n  /** Injectable account client for tests; defaults to the configured bearer. */\n  client?: RegistryClient | null\n}\n\n/**\n * Non-interactively approves a specific version of a pending skill update,\n * recording it in the approval lock. A subsequent `skillet sync` will materialize\n * the approved version without prompting.\n *\n * Security invariants:\n *   - Only the exact version + content hash is approved; future versions or\n *     tampered content require separate explicit action.\n *   - The Ed25519 signature integrity check runs during the subsequent `skillet sync`\n *     (verifyForMaterialize), not here \u2014 matching the interactive approval flow\n *     where the user approves the diff before sync verifies the signature.\n *   - This does NOT bypass the quarantine gate (harm scan) \u2014 that still runs\n *     during sync for every materialization.\n *   - Approving one skill/version never widens trust for other skills, other\n *     versions, or the author's future updates.\n *\n * @param slug    Skill slug (e.g. \"@taylor/festival-ops\")\n * @param version Exact version number to approve (must match current pending state)\n */\nexport async function approveUpdate(\n  slug: string,\n  version: number,\n  opts: ApproveOptions = {},\n): Promise<void> {\n  const { approvalLockPath = defaultApprovalLockPath() } = opts\n\n  const state = await readState()\n  const entry = state.skills[slug]\n  if (!entry) {\n    throw new Error(`Skill \"${slug}\" not found in kit.`)\n  }\n  if (entry.version !== version) {\n    throw new Error(\n      `Skill \"${slug}\" is at version ${entry.version}, not ${version}. ` +\n        `Run \\`skillet pending --json\\` to see the current pending version.`,\n    )\n  }\n\n  const bundle = await readBundleFromSkillStore(slug)\n  const contentHash = canonicalContentHash(bundle)\n\n  await recordApproval(approvalLockPath, slug, version, {\n    contentHash,\n    authorKeyId: entry.authorKeyId ?? '',\n    approvedAt: new Date().toISOString(),\n  })\n\n  // Write through to the account-scoped record so the decision reaches every\n  // device. Best-effort: the local lock above already succeeded, and sync\n  // reconciles if this misses (offline / no bearer).\n  const skillId = skillIdFromSlug(slug, entry.owner)\n  if (skillId) {\n    try {\n      const client = opts.client ?? (await accountClient())\n      await client?.postApproval(skillId, contentHash)\n    } catch {\n      // best-effort; local approval stands and reconciles on next sync.\n    }\n  }\n}\n", "import { canonicalContentHash } from '@skillet/protocol'\nimport { readState, readBundleFromSkillStore } from '../kit/store.js'\nimport { recordRejection, defaultApprovalLockPath } from '../trust/index.js'\nimport { accountClient, skillIdFromSlug } from '../registry/account-client.js'\nimport type { RegistryClient } from '../registry/client.js'\n\nexport interface RejectOptions {\n  /** Override the approval lock path (defaults to $XDG_DATA_HOME/skillet/skillet.lock). */\n  approvalLockPath?: string\n  /** Injectable account client for tests; defaults to the configured bearer. */\n  client?: RegistryClient | null\n}\n\n/**\n * Non-interactively rejects the current pending version of a skill update,\n * recording it in the approval lock. A subsequent `skillet sync` will skip this\n * version without prompting.\n *\n * Security invariants:\n *   - Version-scoped: rejecting v3 does not suppress the review prompt for v4.\n *   - Rejecting one skill does not affect other skills or the author's trust level.\n *   - The rejected version will not be materialized until a new version arrives\n *     and the user takes an explicit action on it.\n *\n * @param slug Skill slug (e.g. \"@taylor/festival-ops\")\n */\nexport async function rejectUpdate(slug: string, opts: RejectOptions = {}): Promise<void> {\n  const { approvalLockPath = defaultApprovalLockPath() } = opts\n\n  const state = await readState()\n  const entry = state.skills[slug]\n  if (!entry) {\n    throw new Error(`Skill \"${slug}\" not found in kit.`)\n  }\n\n  await recordRejection(approvalLockPath, slug, entry.version, {\n    authorKeyId: entry.authorKeyId ?? '',\n    rejectedAt: new Date().toISOString(),\n  })\n\n  // Write through to the account-scoped record (best-effort; reconciles on sync).\n  const skillId = skillIdFromSlug(slug, entry.owner)\n  if (skillId) {\n    try {\n      const bundle = await readBundleFromSkillStore(slug)\n      const client = opts.client ?? (await accountClient())\n      await client?.postRejection(skillId, canonicalContentHash(bundle))\n    } catch {\n      // best-effort; local rejection stands.\n    }\n  }\n}\n", "/**\n * `skillet auth logout` \u2014 revoke the registry session and clear local credentials.\n */\nimport { unlink } from 'node:fs/promises';\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { REGISTRY_API } from '../registry-api.js';\nimport { RegistryError } from '../registry/client.js';\nimport { loadSessionToken, sessionFilePath } from '../session-token.js';\n\nexport interface AuthLogoutOptions {\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface AuthLogoutResult {\n  /** Registry session revoke succeeded (or no token was present). */\n  serverRevoked: boolean;\n  /** Human-readable registry error when revoke failed but local session was cleared. */\n  serverWarning?: string;\n}\n\nexport async function authLogout(opts: AuthLogoutOptions = {}): Promise<AuthLogoutResult> {\n  const token = await loadSessionToken(opts.token);\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n\n  let serverRevoked = true;\n  let serverWarning: string | undefined;\n\n  if (token) {\n    try {\n      const res = await fetchImpl(`${registryUrl}${REGISTRY_API}/auth/logout`, {\n        method: 'POST',\n        headers: { authorization: `Bearer ${token}` },\n      });\n      if (res.status !== 204 && !res.ok) {\n        serverRevoked = false;\n        serverWarning = `Registry logout failed (HTTP ${res.status})`;\n      }\n    } catch (err) {\n      serverRevoked = false;\n      serverWarning =\n        err instanceof RegistryError\n          ? err.message\n          : `Logout failed: ${(err as Error).message}`;\n    }\n  }\n\n  try {\n    await unlink(sessionFilePath());\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n  }\n\n  return { serverRevoked, ...(serverWarning ? { serverWarning } : {}) };\n}\n", "/**\n * `skillet auth disconnect` \u2014 clear local registry credentials on this machine.\n */\nimport { unlink } from 'node:fs/promises';\nimport { clearDeviceToken, readDeviceFile, readDeviceId } from '../device-token.js';\nimport { identityPath } from '../identity/index.js';\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { REGISTRY_API } from '../registry-api.js';\nimport { loadSessionToken, sessionFilePath } from '../session-token.js';\nimport { authLogout, type AuthLogoutOptions } from './auth-logout.js';\n\nexport type AuthDisconnectOptions = AuthLogoutOptions;\n\nexport interface AuthDisconnectResult {\n  /** This machine's server-side device row was removed, or there was none to\n   *  remove (already gone / never paired). False only when it may still be live\n   *  and we couldn't reach the registry to remove it. */\n  unregistered: boolean;\n  /** Human-readable warning when the machine could not be unregistered. */\n  warning?: string;\n}\n\n/** DELETE can hang forever on a black-hole network; sign-out must not. */\nconst DISCONNECT_TIMEOUT_MS = 8000;\n\nconst DISCONNECT_WARNING =\n  \"Couldn't reach the registry to unregister this machine \u2014 remove it at your account Settings \u2192 Devices.\";\n\n/** Revoke the session when possible, then remove session, device, and identity files locally. */\nexport async function authDisconnectLocal(\n  opts: AuthDisconnectOptions = {},\n): Promise<AuthDisconnectResult> {\n  const unregister = await unregisterDevice(opts);\n\n  // Skip the follow-on session revoke when the device DELETE already succeeded:\n  // a 204 cascades the device-bound session's revocation server-side, so calling\n  // logout afterwards would 401 on the session it just killed and warn falsely.\n  if (!unregister.deleteSucceeded) {\n    try {\n      await authLogout(opts);\n    } catch {\n      // Best-effort registry revoke; we still clear local credentials below.\n    }\n  }\n\n  try {\n    await unlink(sessionFilePath());\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n  }\n\n  await clearDeviceToken();\n\n  try {\n    await unlink(identityPath());\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n  }\n\n  return {\n    unregistered: unregister.unregistered,\n    ...(unregister.warning ? { warning: unregister.warning } : {}),\n  };\n}\n\n/** Remove this machine's device row server-side. Prefers the device token (never\n *  expires) over the session (lapses at the TTL), so a long-lived machine can\n *  still unregister itself; falls back to the session for registries that predate\n *  the device self-unregister lane. */\nasync function unregisterDevice(\n  opts: AuthDisconnectOptions,\n): Promise<{ unregistered: boolean; deleteSucceeded: boolean; warning?: string }> {\n  const device = await readDeviceFile();\n  const deviceId = device?.device_id ?? (await readDeviceId());\n  // Nothing to remove: never paired, or a legacy file with no device_id. Sign-out\n  // is purely local here \u2014 no warning.\n  if (!deviceId) return { unregistered: true, deleteSucceeded: false };\n\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const url = `${registryUrl}${REGISTRY_API}/devices/${encodeURIComponent(deviceId)}`;\n\n  const attempt = async (bearer: string): Promise<number | 'error'> => {\n    const ctrl = new AbortController();\n    const timer = setTimeout(() => ctrl.abort(), DISCONNECT_TIMEOUT_MS);\n    try {\n      const res = await fetchImpl(url, {\n        method: 'DELETE',\n        headers: { authorization: `Bearer ${bearer}` },\n        signal: ctrl.signal,\n      });\n      return res.status;\n    } catch {\n      return 'error';\n    } finally {\n      clearTimeout(timer);\n    }\n  };\n\n  const deviceToken = device?.device_token;\n  const sessionToken = await loadSessionToken(opts.token);\n\n  let status: number | 'error';\n  if (deviceToken) {\n    status = await attempt(deviceToken);\n    // 401 \u2192 a stale device token, or a registry too old to accept device auth on\n    // this route; retry with the session token when we have one.\n    if (status === 401 && sessionToken) status = await attempt(sessionToken);\n  } else if (sessionToken) {\n    status = await attempt(sessionToken);\n  } else {\n    // No credential to authenticate the DELETE; the row may still be live.\n    return { unregistered: false, deleteSucceeded: false, warning: DISCONNECT_WARNING };\n  }\n\n  if (status === 204) return { unregistered: true, deleteSucceeded: true };\n  // 404 (row already gone) or 401 (token already dead) \u2014 nothing left to remove.\n  if (status === 404 || status === 401) return { unregistered: true, deleteSucceeded: false };\n  // Network error, timeout, 5xx, or 403 \u2014 the row may still be live; warn.\n  return { unregistered: false, deleteSucceeded: false, warning: DISCONNECT_WARNING };\n}\n", "/**\n * `skillet auth status` \u2014 show session, device, and signing identity state.\n */\nimport {\n  isLinkedMachineCredentials,\n  loadRegistryBearer,\n  type RegistryBearerKind,\n} from '../auth-token.js';\nimport { readActiveDeviceFile } from '../device-token.js';\nimport { readSessionFileToken } from '../session-token.js';\nimport { loadIdentity } from '../identity/index.js';\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { REGISTRY_API } from '../registry-api.js';\n\nexport interface AuthStatusOptions {\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface AuthStatus {\n  bearer: { kind: RegistryBearerKind; tokenPreview: string | null };\n  identity: {\n    handle: string | null;\n    keyId: string | null;\n    registryUrl: string;\n  } | null;\n  whoami: {\n    handle: string | null;\n    avatar_url: string | null;\n    device_id: string | null;\n    user_id: string | null;\n    author_key_id: string | null;\n    scopes: string[];\n  } | null;\n  /** Pair-claimed machine credentials (session + device), even when whoami is offline. */\n  linked_machine: boolean;\n  /** This machine's device label from device.json (what the web Connections\n   * list calls it) \u2014 so local surfaces can say WHICH device this is. */\n  device_label: string | null;\n  hints: string[];\n}\n\nfunction tokenPreview(token: string): string {\n  if (token.length < 12) return token;\n  return `${token.slice(0, 12)}\u2026`;\n}\n\nexport async function authStatus(opts: AuthStatusOptions = {}): Promise<AuthStatus> {\n  const bearer = await loadRegistryBearer(opts.token);\n  const registryUrl =\n    opts.registryUrl ??\n    process.env['SKILLET_REGISTRY_URL'] ??\n    process.env['SKILLET_REGISTRY'] ??\n    REGISTRY_URL_DEFAULT;\n  const hints: string[] = [];\n\n  let identity: AuthStatus['identity'] = null;\n  try {\n    const id = await loadIdentity();\n    if (id) {\n      identity = {\n        handle: id.handle,\n        keyId: id.keyId,\n        registryUrl: id.registryUrl ?? registryUrl,\n      };\n    }\n  } catch {\n    // no local signing identity\n  }\n\n  let whoami: AuthStatus['whoami'] = null;\n  if (bearer.token) {\n    const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n    try {\n      const res = await fetchImpl(`${registryUrl.replace(/\\/+$/, '')}${REGISTRY_API}/whoami`, {\n        headers: { authorization: `Bearer ${bearer.token}`, accept: 'application/json' },\n      });\n      if (res.ok) {\n        const body = (await res.json()) as {\n          handle?: string | null;\n          avatar_url?: string | null;\n          device_id?: string | null;\n          user_id?: string | null;\n          author_key_id?: string | null;\n          scopes?: string[];\n        };\n        whoami = {\n          handle: body.handle ?? null,\n          avatar_url: body.avatar_url ?? null,\n          device_id: body.device_id ?? null,\n          user_id: body.user_id ?? null,\n          author_key_id: body.author_key_id ?? null,\n          scopes: Array.isArray(body.scopes) ? body.scopes : [],\n        };\n      }\n    } catch {\n      // offline\n    }\n  }\n\n  const deviceFile = await readActiveDeviceFile();\n  const sessionFromFile = await readSessionFileToken();\n  const linked_machine = isLinkedMachineCredentials(deviceFile, sessionFromFile);\n  const device_label = deviceFile?.label ?? null;\n\n  if (bearer.kind === 'none') {\n    hints.push('This machine is not paired \u2014 sign in at skillet.md, then open Settings \u2192 Devices for a pair code.');\n    hints.push('Run `skillet connect <code>` with the pair code to sync kits across machines.');\n    hints.push('Nothing syncs until this machine is paired.');\n  } else if (bearer.kind === 'device' && !whoami?.user_id) {\n    hints.push('Device linked \u2014 account kits sync when online.');\n    if (!whoami) {\n      hints.push('Registry is unreachable; showing last-known linked state.');\n    }\n  } else if (bearer.kind === 'session') {\n    hints.push('Signed in \u2014 list, sync, and session publish work on this device.');\n    const remotePrimary = whoami?.author_key_id ?? null;\n    const localPrimary = identity?.keyId ?? null;\n    if (remotePrimary && localPrimary && localPrimary !== remotePrimary) {\n      hints.push(\n        'Local signing key does not match the registry primary \u2014 this device is session-linked, not primary.',\n      );\n      hints.push(\n        'Device approve/revoke and signature-based publish need the primary machine. Session publish does not.',\n      );\n    } else if (whoami?.handle && remotePrimary && !localPrimary) {\n      hints.push(\n        'No local primary key on this device \u2014 normal for a linked machine. Session publish works while signed in.',\n      );\n    } else if (whoami?.handle && remotePrimary && localPrimary === remotePrimary) {\n      hints.push('This device holds the registry primary signing key.');\n    } else if (!identity?.handle) {\n      hints.push(\n        'A local signing key is only needed for primary-key workflows (device approve, delegated signing).',\n      );\n    }\n  }\n\n  return {\n    bearer: {\n      kind: bearer.kind,\n      tokenPreview: bearer.token ? tokenPreview(bearer.token) : null,\n    },\n    identity,\n    whoami,\n    linked_machine,\n    device_label,\n    hints,\n  };\n}\n", "/**\n * `skillet doctor` \u2014 one-shot diagnostic for auth, sync state, and pending updates.\n */\nimport { join } from 'node:path';\nimport type { Adapter } from '../adapter.js';\nimport { authStatus, type AuthStatus, type AuthStatusOptions } from './auth-status.js';\nimport { listPending } from './pending.js';\nimport { readEditedReported, readState, readBundleFromSkillStore } from '../kit/store.js';\nimport { readSkillStoreContentHash, skillStoreDirExists } from '../kit/store-integrity.js';\nimport { resolveSkillDescription } from '../kit/skill-description.js';\nimport { isKitSyncedSkill } from '../kit/sync-scope.js';\nimport matter from 'gray-matter';\nimport { defaultApprovalLockPath } from '../trust/approval-lock.js';\nimport { listPinnedHandles, defaultPinDir } from '../signing/pin.js';\nimport {\n  deviceFilePath,\n  readActiveDeviceFile,\n} from '../device-token.js';\nimport {\n  envSessionToken,\n  envSessionTokenForceActive,\n  sessionFilePath,\n  sessionTokenPrecedenceMode,\n  skilletDir,\n  type SessionTokenPrecedence,\n} from '../session-token.js';\n\nexport const DOCTOR_REPORT_SCHEMA = 'doctor_report/v1' as const;\n\nexport type { SessionTokenPrecedence };\n\nexport interface DoctorReportPaths {\n  skillet_dir: string;\n  session_file: string;\n  device_file: string;\n  state_file: string;\n  approval_lock: string;\n  pin_dir: string;\n}\n\nexport interface DoctorReportEnv {\n  skillet_daemon: boolean;\n  skillet_registry_url: string | null;\n  skillet_token_set: boolean;\n  skillet_token_force: boolean;\n  skillet_dir_override: boolean;\n  session_token_precedence: SessionTokenPrecedence;\n}\n\nexport interface DoctorReportState {\n  skill_count: number;\n  slugs_sample: string[];\n  edited_reported: boolean;\n}\n\nexport interface DoctorReportPending {\n  count: number;\n  slugs: string[];\n}\n\nexport interface DoctorReportPins {\n  handles: string[];\n}\n\nexport interface DoctorReportDevice {\n  file_present: boolean;\n  device_id: string | null;\n  label: string | null;\n}\n\nexport interface DoctorReportStoreDrift {\n  slug: string;\n  entry_hash: string;\n  store_hash: string | null;\n}\n\nexport interface DoctorReportStoreMissing {\n  slug: string;\n}\n\nexport interface DoctorReportCursorDescription {\n  slug: string;\n  source: 'frontmatter' | 'entry' | 'body' | 'slug';\n  resolved_description: string;\n}\n\nexport interface DoctorReport {\n  schema: typeof DOCTOR_REPORT_SCHEMA;\n  generated_at: string;\n  paths: DoctorReportPaths;\n  env: DoctorReportEnv;\n  auth: AuthStatus;\n  state: DoctorReportState;\n  pending: DoctorReportPending;\n  pins: DoctorReportPins;\n  device: DoctorReportDevice;\n  store_drift: DoctorReportStoreDrift[];\n  store_missing: DoctorReportStoreMissing[];\n  cursor_description_synthesis: DoctorReportCursorDescription[];\n}\n\nexport interface DoctorReportOptions extends AuthStatusOptions {\n  adapters?: Adapter[];\n  cwd?: string;\n  /** Cap slugs listed in state/pending samples for support dumps. */\n  sampleLimit?: number;\n}\n\nfunction envRegistryUrl(): string | null {\n  return process.env['SKILLET_REGISTRY_URL'] ?? process.env['SKILLET_REGISTRY'] ?? null;\n}\n\nfunction sampleSlugs(slugs: string[], limit: number): string[] {\n  return slugs.slice(0, limit).sort((a, b) => a.localeCompare(b));\n}\n\n/** Gather a redacted diagnostic snapshot for support and automation. */\nexport async function collectDoctorReport(\n  opts: DoctorReportOptions = {},\n): Promise<DoctorReport> {\n  const sampleLimit = opts.sampleLimit ?? 12;\n  const adapters = opts.adapters ?? [];\n  const dir = skilletDir();\n\n  const [auth, state, editedReported, pendingResult, pinHandles, deviceFile, precedence] =\n    await Promise.all([\n      authStatus(opts),\n      readState(),\n      readEditedReported(),\n      listPending(adapters, { cwd: opts.cwd }),\n      listPinnedHandles(),\n      readActiveDeviceFile(),\n      sessionTokenPrecedenceMode(opts.token),\n    ]);\n\n  const skillSlugs = Object.keys(state.skills);\n\n  const storeDrift: DoctorReportStoreDrift[] = [];\n  const storeMissing: DoctorReportStoreMissing[] = [];\n  const cursorDescriptionSynthesis: DoctorReportCursorDescription[] = [];\n\n  for (const slug of skillSlugs) {\n    try {\n      if (!(await skillStoreDirExists(slug))) {\n        storeMissing.push({ slug });\n      }\n    } catch {\n      // We treat an inaccessible store directory as a missing-store\n      // diagnostics entry so the report still completes.\n      storeMissing.push({ slug });\n    }\n  }\n\n  for (const slug of skillSlugs) {\n    const entry = state.skills[slug];\n    if (!entry || entry.source !== 'registry' || !entry.hash) continue;\n    const storeHash = await readSkillStoreContentHash(slug);\n    if (storeHash === entry.hash) continue;\n    storeDrift.push({\n      slug,\n      entry_hash: entry.hash,\n      store_hash: storeHash,\n    });\n  }\n\n  for (const slug of skillSlugs) {\n    const entry = state.skills[slug];\n    if (!entry || !isKitSyncedSkill(entry)) continue;\n    try {\n      const bundle = await readBundleFromSkillStore(slug);\n      const skillMd = bundle.get('SKILL.md');\n      if (!skillMd) continue;\n      const parsed = matter(Buffer.from(skillMd).toString('utf8'));\n      const fm = parsed.data as Record<string, unknown>;\n      const frontmatterDescription =\n        typeof fm.description === 'string' ? fm.description : undefined;\n      const resolved = resolveSkillDescription({\n        frontmatterDescription,\n        optsDescription: entry.description,\n        body: parsed.content,\n        slug: entry.name || slug,\n      });\n      if (resolved.source === 'frontmatter') continue;\n      cursorDescriptionSynthesis.push({\n        slug,\n        source: resolved.source,\n        resolved_description: resolved.description,\n      });\n    } catch {\n      // Best-effort diagnostic only.\n    }\n  }\n\n  return {\n    schema: DOCTOR_REPORT_SCHEMA,\n    generated_at: new Date().toISOString(),\n    paths: {\n      skillet_dir: dir,\n      session_file: sessionFilePath(),\n      device_file: deviceFilePath(),\n      state_file: join(dir, 'state.json'),\n      approval_lock: defaultApprovalLockPath(),\n      pin_dir: defaultPinDir(),\n    },\n    env: {\n      skillet_daemon: process.env['SKILLET_DAEMON'] === '1',\n      skillet_registry_url: envRegistryUrl(),\n      skillet_token_set: envSessionToken().length > 0,\n      skillet_token_force: envSessionTokenForceActive(),\n      skillet_dir_override: process.env['SKILLET_DIR'] !== undefined,\n      session_token_precedence: precedence,\n    },\n    auth,\n    state: {\n      skill_count: skillSlugs.length,\n      slugs_sample: sampleSlugs(skillSlugs, sampleLimit),\n      edited_reported: editedReported,\n    },\n    pending: {\n      count: pendingResult.pending.length,\n      slugs: sampleSlugs(\n        pendingResult.pending.map((entry) => entry.slug),\n        sampleLimit,\n      ),\n    },\n    pins: {\n      handles: pinHandles.sort((a, b) => a.localeCompare(b)),\n    },\n    device: {\n      file_present: deviceFile !== null,\n      device_id: deviceFile?.device_id ?? null,\n      label: deviceFile?.label ?? null,\n    },\n    store_drift: storeDrift,\n    store_missing: storeMissing,\n    cursor_description_synthesis: cursorDescriptionSynthesis,\n  };\n}\n", "import { execSync } from 'node:child_process';\nimport { hostname } from 'node:os';\n\nfunction readMacComputerName(): string | null {\n  if (process.platform !== 'darwin') return null;\n  try {\n    const name = execSync('scutil --get ComputerName', {\n      encoding: 'utf8',\n      timeout: 2000,\n      stdio: ['ignore', 'pipe', 'ignore'],\n    }).trim();\n    return name.length > 0 ? name : null;\n  } catch {\n    return null;\n  }\n}\n\n/** Default label for a newly connected sync machine (Settings \u2192 Devices). */\nexport function defaultMachineLabel(): string {\n  const friendly =\n    readMacComputerName() ??\n    process.env['COMPUTERNAME']?.trim() ??\n    process.env['HOSTNAME']?.trim() ??\n    hostname().trim();\n  const label = friendly && friendly !== 'localhost' ? friendly : 'Unnamed machine';\n  return label.slice(0, 80);\n}\n", "/**\n * `skillet auth connect` \u2014 mint a user-bound device token for this machine/agent.\n */\nimport { loadSessionToken } from '../session-token.js';\nimport { saveDeviceToken } from '../device-token.js';\nimport { defaultMachineLabel } from '../machine-label.js';\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { REGISTRY_API } from '../registry-api.js';\n\nexport interface AuthConnectOptions {\n  registryUrl?: string;\n  token?: string;\n  label?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface AuthConnectResult {\n  device_id: string;\n  device_token: string;\n}\n\nexport async function authConnect(opts: AuthConnectOptions = {}): Promise<AuthConnectResult> {\n  const session = await loadSessionToken(opts.token);\n  if (!session || !session.startsWith('skillet_s_')) {\n    throw new Error('A signed-in session is required. Run `skillet connect <code>` first.');\n  }\n\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const label = (opts.label ?? defaultMachineLabel()).slice(0, 80);\n\n  const res = await fetchImpl(`${registryUrl}${REGISTRY_API}/devices/token`, {\n    method: 'POST',\n    headers: {\n      authorization: `Bearer ${session}`,\n      'content-type': 'application/json',\n      accept: 'application/json',\n    },\n    body: JSON.stringify({ label }),\n  });\n\n  const body = (await res.json().catch(() => null)) as {\n    device_id?: string;\n    device_token?: string;\n    message?: string;\n  } | null;\n\n  if (!res.ok || !body?.device_token || !body.device_id) {\n    const msg =\n      body && typeof body === 'object' && 'message' in body\n        ? String(body.message)\n        : `HTTP ${res.status}`;\n    throw new Error(`Could not mint device token: ${msg}`);\n  }\n\n  await saveDeviceToken(body.device_token, { device_id: body.device_id, label });\n\n  return { device_id: body.device_id, device_token: body.device_token };\n}\n", "/**\n * `skillet connect <code>` \u2014 redeem a web pair code for session + device tokens.\n */\nimport { randomUUID } from 'node:crypto';\nimport { extractPairCode } from '../pair-code.js';\nimport { saveSessionToken } from '../session-token.js';\nimport { readDeviceFile, readStoredMachineId, saveDeviceToken } from '../device-token.js';\nimport { defaultMachineLabel } from '../machine-label.js';\nimport { stableMachineId } from '../machine-identity.js';\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { REGISTRY_API } from '../registry-api.js';\n\nexport type ClientPlatform = 'macos' | 'windows';\n\nexport interface AuthConnectPairOptions {\n  code: string;\n  registryUrl?: string;\n  label?: string;\n  /** How this machine is joining: terminal CLI vs desktop menubar app. */\n  clientKind?: 'cli' | 'desktop';\n  fetchImpl?: typeof fetch;\n}\n\n/** Map Node's process.platform to registry client_platform for desktop pairs. */\nexport function clientPlatformFromProcess(\n  platform: string = process.platform,\n): ClientPlatform | undefined {\n  if (platform === 'darwin') return 'macos';\n  if (platform === 'win32') return 'windows';\n  return undefined;\n}\n\nexport interface AuthConnectPairResult {\n  device_id: string;\n  device_token: string;\n  session_token: string;\n  handle: string | null;\n  user_id: string;\n}\n\nexport async function authConnectPair(\n  opts: AuthConnectPairOptions,\n): Promise<AuthConnectPairResult> {\n  const code = extractPairCode(opts.code);\n  if (!code) {\n    throw new Error('Pair code must be 8 characters (letters and numbers).');\n  }\n\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const label = (opts.label ?? defaultMachineLabel()).slice(0, 80);\n  const clientKind = opts.clientKind ?? 'cli';\n  const clientPlatform =\n    clientKind === 'desktop' ? clientPlatformFromProcess() : undefined;\n\n  // Present this machine's existing device identity (a prior pairing) so the\n  // registry rebinds that device instead of minting a duplicate \u2014 re-pairing\n  // the same machine never spawns a second device row.\n  // A token from a different registry simply won't match and is ignored there;\n  // machine_id is the fallback the registry reclaims by when the token is\n  // lost or clobbered (same-account only). Derived from the OS machine\n  // identity so it survives sign-out, wipes, and fresh SKILLET_DIRs; the\n  // stored id covers machines whose OS id is unreadable, and a random UUID is\n  // the last resort (persisted via saveDeviceToken below).\n  const existingDevice = await readDeviceFile().catch(() => null);\n  const storedMachineId = await readStoredMachineId().catch(() => undefined);\n  const machineId = stableMachineId() ?? storedMachineId ?? randomUUID();\n\n  const res = await fetchImpl(`${registryUrl}${REGISTRY_API}/connect/claim`, {\n    method: 'POST',\n    headers: {\n      'content-type': 'application/json',\n      accept: 'application/json',\n    },\n    body: JSON.stringify({\n      code,\n      label,\n      client_kind: clientKind,\n      ...(clientPlatform ? { client_platform: clientPlatform } : {}),\n      ...(existingDevice?.device_token ? { device_token: existingDevice.device_token } : {}),\n      machine_id: machineId,\n    }),\n  });\n\n  const body = (await res.json().catch(() => null)) as {\n    session_token?: string;\n    device_id?: string;\n    device_token?: string;\n    handle?: string | null;\n    user_id?: string;\n    message?: string;\n    error?: string;\n  } | null;\n\n  if (!res.ok || !body?.session_token || !body.device_token || !body.device_id || !body.user_id) {\n    const msg =\n      body && typeof body === 'object' && 'message' in body && body.message\n        ? String(body.message)\n        : body?.error\n          ? String(body.error)\n          : `HTTP ${res.status}`;\n    throw new Error(`Could not connect with pair code: ${msg}`);\n  }\n\n  await saveSessionToken(body.session_token);\n  await saveDeviceToken(body.device_token, {\n    device_id: body.device_id,\n    label,\n    machine_id: machineId,\n  });\n\n  return {\n    session_token: body.session_token,\n    device_id: body.device_id,\n    device_token: body.device_token,\n    handle: body.handle ?? null,\n    user_id: body.user_id,\n  };\n}\n", "/**\n * `skillet pair` \u2014 mint a join code from an already-joined machine.\n *\n * The symmetric counterpart to `skillet connect <code>`: any surface that holds\n * an account-bound token (session or user device token) can mint a short code,\n * which another surface \u2014 web, CLI, or desktop \u2014 redeems to join the same\n * account. This is what makes attach work in any order.\n */\nimport { loadRegistryBearer } from '../auth-token.js';\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { REGISTRY_API } from '../registry-api.js';\n\nexport interface MintPairCodeOptions {\n  registryUrl?: string;\n  /** Explicit bearer; defaults to the best local token (session \u2192 device). */\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface MintPairCodeResult {\n  code: string;\n  expires_at: number;\n  ttl_sec: number;\n}\n\nexport async function mintPairCode(\n  opts: MintPairCodeOptions = {},\n): Promise<MintPairCodeResult> {\n  const bearer = await loadRegistryBearer(opts.token);\n  if (!bearer.token || (bearer.kind !== 'session' && bearer.kind !== 'device')) {\n    throw new Error(\n      'Not signed in on this machine. Run `skillet login` or join with `skillet connect <code>` first.',\n    );\n  }\n\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n\n  const res = await fetchImpl(`${registryUrl}${REGISTRY_API}/connect/codes`, {\n    method: 'POST',\n    headers: { authorization: `Bearer ${bearer.token}`, accept: 'application/json' },\n  });\n\n  const body = (await res.json().catch(() => null)) as\n    | (MintPairCodeResult & { message?: string; error?: string })\n    | null;\n\n  if (!res.ok || !body?.code) {\n    const msg =\n      body && typeof body === 'object' && 'message' in body && body.message\n        ? String(body.message)\n        : body?.error\n          ? String(body.error)\n          : `HTTP ${res.status}`;\n    throw new Error(`Could not mint a pair code: ${msg}`);\n  }\n\n  return { code: body.code, expires_at: body.expires_at, ttl_sec: body.ttl_sec };\n}\n", "// Skillet team create|invite|members\n// Thin wrappers over the /api/v1/orgs registry endpoints.\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { RegistryError } from '../registry/client.js';\nimport { loadSessionToken } from '../session-token.js';\nimport { REGISTRY_API as API } from '../registry-api.js';\n\nasync function sessionToken(explicit?: string): Promise<string> {\n  return loadSessionToken(explicit);\n}\n\nexport interface TeamCreateOptions {\n  slug: string;\n  name: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface TeamCreateResult {\n  org_id: string;\n  slug: string;\n  name: string;\n}\n\nexport interface TeamInviteOptions {\n  orgSlug: string;\n  handle?: string;\n  email?: string;\n  role?: 'admin' | 'member';\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface TeamInviteResult {\n  status: 'added' | 'invited';\n  invite_id?: string;\n  member_id?: string;\n}\n\nexport interface OrgMember {\n  user_id: string;\n  handle: string | null;\n  role: string;\n  invited_at: number;\n  accepted_at: number | null;\n}\n\nexport interface PendingInvite {\n  invite_id: string;\n  handle: string | null;\n  email: string | null;\n  role: string;\n  invited_at: number;\n}\n\nexport interface TeamMembersResult {\n  org: { id: string; slug: string; name: string };\n  members: OrgMember[];\n  pending: PendingInvite[];\n}\n\nexport interface TeamMembersOptions {\n  orgSlug: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nasync function post(\n  url: string,\n  body: unknown,\n  token: string,\n  fetchImpl: typeof fetch,\n): Promise<unknown> {\n  let res: Response;\n  try {\n    res = await fetchImpl(url, {\n      method: 'POST',\n      headers: {\n        'content-type': 'application/json',\n        accept: 'application/json',\n        authorization: `Bearer ${token}`,\n      },\n      body: JSON.stringify(body),\n    });\n  } catch (err) {\n    throw new RegistryError('network_error', `Request failed: ${(err as Error).message}`);\n  }\n  const payload = await res.json().catch(() => null);\n  if (!res.ok) {\n    const code =\n      payload && typeof payload === 'object' && 'error' in payload\n        ? String((payload as Record<string, unknown>).error)\n        : `http_${res.status}`;\n    const message =\n      payload && typeof payload === 'object' && 'message' in payload\n        ? String((payload as Record<string, unknown>).message)\n        : `Request failed (HTTP ${res.status})`;\n    throw new RegistryError(code, message, res.status, payload);\n  }\n  return payload;\n}\n\nasync function get(\n  url: string,\n  token: string,\n  fetchImpl: typeof fetch,\n): Promise<unknown> {\n  let res: Response;\n  try {\n    res = await fetchImpl(url, {\n      headers: {\n        accept: 'application/json',\n        authorization: `Bearer ${token}`,\n      },\n    });\n  } catch (err) {\n    throw new RegistryError('network_error', `Request failed: ${(err as Error).message}`);\n  }\n  const payload = await res.json().catch(() => null);\n  if (!res.ok) {\n    const code =\n      payload && typeof payload === 'object' && 'error' in payload\n        ? String((payload as Record<string, unknown>).error)\n        : `http_${res.status}`;\n    const message =\n      payload && typeof payload === 'object' && 'message' in payload\n        ? String((payload as Record<string, unknown>).message)\n        : `Request failed (HTTP ${res.status})`;\n    throw new RegistryError(code, message, res.status, payload);\n  }\n  return payload;\n}\n\nexport async function createOrg(opts: TeamCreateOptions): Promise<TeamCreateResult> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const token = await sessionToken(opts.token);\n  if (!token) {\n    throw new RegistryError(\n      'not_authenticated',\n      'A session token is required. Run `skillet connect <code>` or set SKILLET_TOKEN.',\n    );\n  }\n  const url = `${registryUrl}${API}/orgs`;\n  return post(url, { slug: opts.slug, name: opts.name }, token, fetchImpl) as Promise<TeamCreateResult>;\n}\n\nexport async function inviteOrgMember(opts: TeamInviteOptions): Promise<TeamInviteResult> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const token = await sessionToken(opts.token);\n  if (!token) {\n    throw new RegistryError(\n      'not_authenticated',\n      'A session token is required. Run `skillet connect <code>` or set SKILLET_TOKEN.',\n    );\n  }\n  const url = `${registryUrl}${API}/orgs/${encodeURIComponent(opts.orgSlug)}/invites`;\n  return post(\n    url,\n    {\n      handle: opts.handle,\n      email: opts.email,\n      role: opts.role ?? 'member',\n    },\n    token,\n    fetchImpl,\n  ) as Promise<TeamInviteResult>;\n}\n\nexport async function listOrgMembers(opts: TeamMembersOptions): Promise<TeamMembersResult> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const token = await sessionToken(opts.token);\n  if (!token) {\n    throw new RegistryError(\n      'not_authenticated',\n      'A session token is required. Run `skillet connect <code>` or set SKILLET_TOKEN.',\n    );\n  }\n  const url = `${registryUrl}${API}/orgs/${encodeURIComponent(opts.orgSlug)}/members`;\n  return get(url, token, fetchImpl) as Promise<TeamMembersResult>;\n}\n", "// Private kit CLI over registry kit + kit-members APIs.\nimport { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { REGISTRY_URL_DEFAULT } from '../kit/types.js';\nimport { loadIdentity } from '../identity/index.js';\nimport { RegistryError } from '../registry/client.js';\nimport { loadSessionToken } from '../session-token.js';\nimport { REGISTRY_API as API } from '../registry-api.js';\n\nfunction skilletDir(): string {\n  return process.env['SKILLET_DIR'] ?? join(homedir(), '.skillet');\n}\n\nfunction kitAliasesPath(): string {\n  return join(skilletDir(), 'kit-aliases.json');\n}\n\nasync function resolveSessionToken(explicit?: string): Promise<string> {\n  return loadSessionToken(explicit);\n}\n\nasync function readAliases(): Promise<Record<string, string>> {\n  try {\n    const raw = await readFile(kitAliasesPath(), 'utf8');\n    return JSON.parse(raw) as Record<string, string>;\n  } catch {\n    return {};\n  }\n}\n\nasync function writeAlias(owner: string, name: string, kitId: string): Promise<void> {\n  const aliases = await readAliases();\n  aliases[`${owner}/${name}`] = kitId;\n  await mkdir(skilletDir(), { recursive: true });\n  await writeFile(kitAliasesPath(), JSON.stringify(aliases, null, 2), 'utf8');\n}\n\nconst UUID_RE =\n  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nasync function resolveKitId(\n  kitRef: string,\n  owner: string,\n): Promise<string> {\n  if (UUID_RE.test(kitRef)) return kitRef;\n  const aliases = await readAliases();\n  const id = aliases[`${owner}/${kitRef}`];\n  if (!id) {\n    throw new RegistryError(\n      'kit_not_found',\n      `Kit \"${kitRef}\" not found for @${owner}. Run \\`skillet kit create ${kitRef}\\` first.`,\n    );\n  }\n  return id;\n}\n\nasync function request(\n  method: string,\n  url: string,\n  token: string,\n  fetchImpl: typeof fetch,\n  body?: unknown,\n): Promise<unknown> {\n  let res: Response;\n  try {\n    res = await fetchImpl(url, {\n      method,\n      headers: {\n        accept: 'application/json',\n        ...(body ? { 'content-type': 'application/json' } : {}),\n        ...(token ? { authorization: `Bearer ${token}` } : {}),\n      },\n      ...(body ? { body: JSON.stringify(body) } : {}),\n    });\n  } catch (err) {\n    throw new RegistryError('network_error', `Request failed: ${(err as Error).message}`);\n  }\n  const payload = await res.json().catch(() => null);\n  if (!res.ok) {\n    const code =\n      payload && typeof payload === 'object' && 'error' in payload\n        ? String((payload as Record<string, unknown>).error)\n        : `http_${res.status}`;\n    let message =\n      payload && typeof payload === 'object' && 'message' in payload\n        ? String((payload as Record<string, unknown>).message)\n        : `Request failed (HTTP ${res.status})`;\n    if (code === 'not_owner') {\n      message =\n        'Only the kit owner can do this. Sign in with the owner account (`skillet connect`) ' +\n        'and run `skillet kit create` under that handle. On one machine, isolate accounts with SKILLET_DIR.';\n    }\n    throw new RegistryError(code, message, res.status, payload);\n  }\n  return payload;\n}\n\nasync function fetchSessionHandle(\n  registryUrl: string,\n  token: string,\n  fetchImpl: typeof fetch,\n): Promise<string | null> {\n  const url = `${registryUrl.replace(/\\/+$/, '')}${API}/whoami`;\n  let res: Response;\n  try {\n    res = await fetchImpl(url, {\n      headers: { accept: 'application/json', authorization: `Bearer ${token}` },\n    });\n  } catch {\n    return null;\n  }\n  if (!res.ok) return null;\n  const body = (await res.json().catch(() => null)) as {\n    token_class?: string;\n    handle?: string | null;\n  } | null;\n  if (body?.token_class === 'session' && body.handle) {\n    return body.handle;\n  }\n  return null;\n}\n\nasync function ownerHandle(opts: {\n  token?: string;\n  registryUrl?: string;\n  fetchImpl?: typeof fetch;\n}): Promise<string> {\n  const token = await resolveSessionToken(opts.token);\n  if (!token) {\n    throw new RegistryError(\n      'not_authenticated',\n      'A session token is required. Run `skillet connect <code>` or set SKILLET_TOKEN.',\n    );\n  }\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const sessionHandle = await fetchSessionHandle(registryUrl, token, fetchImpl);\n  const identity = await loadIdentity();\n  if (sessionHandle) {\n    if (identity?.handle && identity.handle !== sessionHandle) {\n      throw new RegistryError(\n        'handle_mismatch',\n        `Local identity is @${identity.handle} but the signed-in session is @${sessionHandle}. ` +\n          'Kit commands use the signed-in account. Sign out and back in, or use SKILLET_DIR to isolate a second account.',\n      );\n    }\n    return sessionHandle;\n  }\n  if (identity?.handle) {\n    throw new RegistryError(\n      'handle_not_claimed',\n      `Session has no claimed handle. Choose a username at skillet.md or run \\`skillet login --handle <you> --name \"<Name>\"\\`.`,\n    );\n  }\n  throw new RegistryError(\n    'handle_not_claimed',\n    'Claim a handle with `skillet login` before managing kits.',\n  );\n}\n\nexport interface KitCreateOptions {\n  name: string;\n  description?: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface KitCreateResult {\n  id: string;\n  owner: string;\n  name: string;\n}\n\nexport async function createKit(opts: KitCreateOptions): Promise<KitCreateResult> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const owner = await ownerHandle(opts);\n  const url = `${registryUrl}${API}/kits`;\n  const token = await resolveSessionToken(opts.token);\n  const payload = (await request(\n    'POST',\n    url,\n    token,\n    fetchImpl,\n    { owner, name: opts.name, description: opts.description ?? null },\n  )) as { id: string; owner: string; name: string };\n  await writeAlias(owner, opts.name, payload.id);\n  return { id: payload.id, owner: payload.owner, name: payload.name };\n}\n\nexport interface KitAddSkillOptions {\n  kitRef: string;\n  skillRef: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport async function addSkillToKit(opts: KitAddSkillOptions): Promise<void> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const owner = await ownerHandle(opts);\n  const kitId = await resolveKitId(opts.kitRef, owner);\n  const match = opts.skillRef.match(/^@([^/]+)\\/([^/]+)$/);\n  if (!match) {\n    throw new RegistryError('invalid_ref', 'Skill ref must be @author/slug');\n  }\n  const url = `${registryUrl}${API}/kits/${encodeURIComponent(kitId)}/skills`;\n  const token = await resolveSessionToken(opts.token);\n  await request('POST', url, token, fetchImpl, {\n    author: match[1],\n    slug: match[2],\n  });\n}\n\nexport interface KitInviteOptions {\n  kitRef: string;\n  handle?: string;\n  email?: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface KitInviteResult {\n  status: 'added' | 'invited';\n  member_id: string;\n}\n\nexport async function inviteKitMember(opts: KitInviteOptions): Promise<KitInviteResult> {\n  if (!opts.handle && !opts.email) {\n    throw new RegistryError('missing_identifier', 'Provide handle or email');\n  }\n  if (opts.handle && opts.email) {\n    throw new RegistryError('missing_identifier', 'Provide handle or email, not both');\n  }\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const owner = await ownerHandle(opts);\n  const kitId = await resolveKitId(opts.kitRef, owner);\n  const url = `${registryUrl}${API}/kits/${encodeURIComponent(kitId)}/members`;\n  const token = await resolveSessionToken(opts.token);\n  return request('POST', url, token, fetchImpl, {\n    kind: 'human',\n    handle: opts.handle,\n    email: opts.email,\n  }) as Promise<KitInviteResult>;\n}\n\nexport interface KitMembersOptions {\n  kitRef: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface KitMembersResult {\n  /** Kit owner handle (`kits.owner_id`). Present on registry builds with owner in GET /members. */\n  owner?: string;\n  humans: Array<{ user_id: string; handle: string | null; invited_at: number; accepted_at: number | null }>;\n  pending_humans: Array<{ invite_id: string; handle: string | null; email: string | null; invited_at: number }>;\n  agents: Array<{ kit_key_id: string; label: string; created_at: number; revoked_at: number | null }>;\n}\n\nexport async function listKitMembers(opts: KitMembersOptions): Promise<KitMembersResult> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const owner = await ownerHandle(opts);\n  const kitId = await resolveKitId(opts.kitRef, owner);\n  const url = `${registryUrl}${API}/kits/${encodeURIComponent(kitId)}/members`;\n  const token = await resolveSessionToken(opts.token);\n  return request('GET', url, token, fetchImpl) as Promise<KitMembersResult>;\n}\n\nexport interface KitKeyMintOptions {\n  kitRef: string;\n  label: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface KitKeyMintResult {\n  kit_key_id: string;\n  kit_token: string;\n  label: string;\n}\n\nexport async function mintKitKey(opts: KitKeyMintOptions): Promise<KitKeyMintResult> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const owner = await ownerHandle(opts);\n  const kitId = await resolveKitId(opts.kitRef, owner);\n  const url = `${registryUrl}${API}/kits/${encodeURIComponent(kitId)}/members`;\n  const token = await resolveSessionToken(opts.token);\n  return request('POST', url, token, fetchImpl, {\n    kind: 'agent',\n    label: opts.label,\n  }) as Promise<KitKeyMintResult>;\n}\n\nexport interface KitMemberRemoveOptions {\n  kitRef: string;\n  handle: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport async function removeKitMember(opts: KitMemberRemoveOptions): Promise<void> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const owner = await ownerHandle(opts);\n  const kitId = await resolveKitId(opts.kitRef, owner);\n  const members = await listKitMembers(opts);\n  const human = members.humans.find((h) => h.handle === opts.handle);\n  if (!human) {\n    throw new RegistryError('member_not_found', `No member with handle @${opts.handle}`);\n  }\n  const url = `${registryUrl}${API}/kits/${encodeURIComponent(kitId)}/members`;\n  const token = await resolveSessionToken(opts.token);\n  await request('DELETE', url, token, fetchImpl, {\n    member_id: human.user_id,\n  });\n}\n\nexport interface KitKeyRevokeOptions {\n  kitRef: string;\n  kitKeyId: string;\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport async function revokeKitKey(opts: KitKeyRevokeOptions): Promise<void> {\n  const registryUrl = (opts.registryUrl ?? REGISTRY_URL_DEFAULT).replace(/\\/+$/, '');\n  const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n  const owner = await ownerHandle(opts);\n  const kitId = await resolveKitId(opts.kitRef, owner);\n  const url = `${registryUrl}${API}/kits/${encodeURIComponent(kitId)}/members`;\n  const token = await resolveSessionToken(opts.token);\n  await request('DELETE', url, token, fetchImpl, {\n    member_id: opts.kitKeyId,\n  });\n}\n", "/**\n * Publish unpublished local kit skills, create a named registry kit, and link\n * every published skill into it so device sync can route the group as `kit:<id>`.\n */\nimport { readState } from '../kit/store.js';\nimport { loadSessionToken } from '../session-token.js';\nimport { publish, type PublishOptions } from './publish.js';\nimport { createKit, addSkillToKit } from './kit.js';\n\nexport interface BootstrapLocalKitOptions {\n  name: string;\n  visibility?: 'private' | 'public';\n  /** When omitted, every local skill with no owner in the kit store is included. */\n  slugs?: string[];\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n  sessionAuth?: boolean;\n}\n\nexport type BootstrapFailureStage = 'publish' | 'kit_create' | 'kit_add';\n\nexport interface BootstrapLocalKitResult {\n  ok: boolean;\n  kit: { id: string; owner: string; name: string } | null;\n  owner: string;\n  published: Array<{ slug: string; alreadyExists: boolean }>;\n  kitLinked: string[];\n  failed: Array<{ slug: string; stage: BootstrapFailureStage; error: string }>;\n  empty: boolean;\n}\n\nasync function localUnpublishedSlugs(): Promise<string[]> {\n  const state = await readState();\n  return Object.values(state.skills)\n    .filter((s) => s.source === 'local' && !s.owner)\n    .map((s) => s.slug)\n    .sort((a, b) => a.localeCompare(b));\n}\n\nexport async function bootstrapLocalKit(\n  opts: BootstrapLocalKitOptions,\n): Promise<BootstrapLocalKitResult> {\n  const state = await readState();\n  const slugs = (opts.slugs ?? (await localUnpublishedSlugs())).filter((slug) => {\n    const entry = state.skills[slug];\n    return entry?.source === 'local' && !entry.owner;\n  });\n\n  if (slugs.length === 0) {\n    return {\n      ok: false,\n      kit: null,\n      owner: '',\n      published: [],\n      kitLinked: [],\n      failed: [],\n      empty: true,\n    };\n  }\n\n  const token = await loadSessionToken(opts.token);\n  const publishOpts: PublishOptions = {\n    ...(opts.registryUrl ? { registryUrl: opts.registryUrl } : {}),\n    token,\n    visibility: opts.visibility ?? 'private',\n    sessionAuth: opts.sessionAuth ?? true,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  };\n\n  const published: Array<{ slug: string; alreadyExists: boolean }> = [];\n  const failed: BootstrapLocalKitResult['failed'] = [];\n\n  for (const slug of slugs) {\n    try {\n      const result = await publish(slug, publishOpts);\n      published.push({ slug, alreadyExists: result.alreadyExists });\n    } catch (err) {\n      failed.push({ slug, stage: 'publish', error: (err as Error).message });\n    }\n  }\n\n  if (published.length === 0) {\n    return {\n      ok: false,\n      kit: null,\n      owner: '',\n      published,\n      kitLinked: [],\n      failed,\n      empty: false,\n    };\n  }\n\n  let kit: BootstrapLocalKitResult['kit'] = null;\n  let owner = '';\n  try {\n    kit = await createKit({\n      name: opts.name,\n      ...(opts.registryUrl ? { registryUrl: opts.registryUrl } : {}),\n      token,\n      ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n    });\n    owner = kit.owner;\n  } catch (err) {\n    failed.push({ slug: '*', stage: 'kit_create', error: (err as Error).message });\n    return {\n      ok: false,\n      kit: null,\n      owner,\n      published,\n      kitLinked: [],\n      failed,\n      empty: false,\n    };\n  }\n\n  const kitLinked: string[] = [];\n  for (const { slug } of published) {\n    try {\n      await addSkillToKit({\n        kitRef: opts.name,\n        skillRef: `@${owner}/${slug}`,\n        ...(opts.registryUrl ? { registryUrl: opts.registryUrl } : {}),\n        token,\n        ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n      });\n      kitLinked.push(slug);\n    } catch (err) {\n      failed.push({ slug, stage: 'kit_add', error: (err as Error).message });\n    }\n  }\n\n  return {\n    ok: kitLinked.length > 0,\n    kit,\n    owner,\n    published,\n    kitLinked,\n    failed,\n    empty: false,\n  };\n}\n", "/**\n * `skillet upload` \u2014 publish selected local skills to the account.\n *\n * No custom kit is created or linked: published skills reach the user's other\n * machines through the sync manifest's own-authored rows and surface on the\n * author/profile kit (/{handle}/kit). Two selection modes:\n *\n *  - `slugs` omitted \u2192 every local skill with no owner (first backup).\n *  - explicit `slugs` \u2192 resolved against both the bare key and the promoted\n *    `@handle/slug` key, then forwarded to publish even when already published,\n *    so an identical-content re-upload no-ops (private) and a visibility flip\n *    still POSTs. Unknown slugs are dropped (stale-selection safety); publish\n *    itself refuses entries authored by someone else ('not_your_skill').\n */\nimport { readState } from '../kit/store.js';\nimport { publish, PublishError } from './publish.js';\nimport type { ScanWireFinding, ScanBlockedBody } from '../registry/client.js';\n\n/** A privacy/harm finding surfaced to the desktop, flattened from the registry's\n *  scan verdict (KTD2 \u2014 the registry is the single scan authority). */\nexport interface UploadFinding {\n  file: string;\n  line: number;\n  category: string;\n}\n\n/** Flatten the registry's wire findings (which use lineStart/lineEnd) to the\n *  desktop-facing `{ file, line, category }` shape. */\nfunction toUploadFindings(findings: ScanWireFinding[]): UploadFinding[] {\n  return findings.map((f) => ({ file: f.file, line: f.lineStart, category: f.category }));\n}\n\nexport type UploadProgressEvent =\n  | { phase: 'start'; slug: string; index: number; total: number }\n  | { phase: 'done'; slug: string; alreadyExists: boolean; owner: string }\n  | { phase: 'fail'; slug: string; error: string };\n\nexport interface UploadLocalSkillsOptions {\n  visibility?: 'private' | 'public';\n  /** When omitted, every local skill with no owner in the kit store is included. */\n  slugs?: string[];\n  registryUrl?: string;\n  token?: string;\n  fetchImpl?: typeof fetch;\n  sessionAuth?: boolean;\n  onProgress?: (event: UploadProgressEvent) => void;\n}\n\nexport interface UploadLocalSkillsResult {\n  /** At least one skill published. */\n  ok: boolean;\n  /** Handle the skills published under ('' when nothing published). */\n  owner: string;\n  published: Array<{ slug: string; alreadyExists: boolean }>;\n  /**\n   * Failed uploads. `error` is the message string (kept for back-compat);\n   * `findings` carries the registry's structured findings when the failure was a\n   * `scan_blocked` verdict \u2014 a real secret or a confirmed-dangerous bundle the\n   * registry refused (KTD2/KTD5 \u2014 additive, optional).\n   */\n  failed: Array<{ slug: string; error: string; findings?: UploadFinding[] }>;\n  /**\n   * Non-blocking findings from a *successful* upload (R3/KTD5). A skill appears\n   * here when the registry `flagged` (not quarantined) the published version \u2014\n   * it published, but the patterns are worth a look. Omitted entirely when\n   * nothing flagged so an older desktop parser sees no new key (back-compat).\n   */\n  warnings?: Array<{ slug: string; findings: UploadFinding[] }>;\n  /** The resolved selection was empty \u2014 nothing to upload. */\n  empty: boolean;\n}\n\n/** Resolve a requested slug to a kit-state key: exact match, else the promoted\n *  `@handle/<slug>` key sync re-keys own published skills to. */\nfunction resolveStateKey(keys: string[], requested: string): string | null {\n  if (keys.includes(requested)) return requested;\n  if (requested.startsWith('@')) return null;\n  const promoted = keys.filter((k) => k.startsWith('@') && k.endsWith(`/${requested}`));\n  return promoted.length === 1 ? promoted[0]! : null;\n}\n\nexport async function uploadLocalSkills(\n  opts: UploadLocalSkillsOptions = {},\n): Promise<UploadLocalSkillsResult> {\n  const state = await readState();\n  const keys = Object.keys(state.skills);\n\n  let selected: string[];\n  if (opts.slugs === undefined) {\n    // First-backup expansion: local skills that have never been published.\n    selected = Object.entries(state.skills)\n      .filter(([, s]) => s.source === 'local' && !s.owner)\n      .map(([key]) => key)\n      .sort((a, b) => a.localeCompare(b));\n  } else {\n    selected = [\n      ...new Set(\n        opts.slugs\n          .map((s) => resolveStateKey(keys, s.trim()))\n          .filter((k): k is string => k !== null),\n      ),\n    ];\n  }\n\n  if (selected.length === 0) {\n    return { ok: false, owner: '', published: [], failed: [], empty: true };\n  }\n\n  const published: UploadLocalSkillsResult['published'] = [];\n  const failed: UploadLocalSkillsResult['failed'] = [];\n  const warnings: NonNullable<UploadLocalSkillsResult['warnings']> = [];\n  let owner = '';\n\n  for (let index = 0; index < selected.length; index++) {\n    const key = selected[index]!;\n    opts.onProgress?.({ phase: 'start', slug: key, index, total: selected.length });\n    try {\n      const result = await publish(key, {\n        ...(opts.registryUrl ? { registryUrl: opts.registryUrl } : {}),\n        ...(opts.token ? { token: opts.token } : {}),\n        ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n        visibility: opts.visibility ?? 'private',\n        sessionAuth: opts.sessionAuth ?? true,\n      });\n      owner = owner || result.owner;\n      published.push({ slug: key, alreadyExists: result.alreadyExists });\n      // The registry `flagged` (not quarantined) the published version: it\n      // published, but the patterns are worth surfacing (R3). Record them so the\n      // desktop can warn-not-block.\n      if (result.serverScan?.status === 'flagged' && result.serverScan.findings.length > 0) {\n        warnings.push({ slug: key, findings: toUploadFindings(result.serverScan.findings) });\n      }\n      opts.onProgress?.({\n        phase: 'done',\n        slug: key,\n        alreadyExists: result.alreadyExists,\n        owner: result.owner,\n      });\n    } catch (err) {\n      const error = (err as Error).message;\n      // A registry `scan_blocked` refusal (real secret or quarantine) carries the\n      // structured findings on `PublishError.detail` (the 422 body); surface them\n      // alongside the message so the desktop lists what to fix, not just a count.\n      const findings =\n        err instanceof PublishError && err.code === 'scan_blocked'\n          ? toUploadFindings((err.detail as ScanBlockedBody | undefined)?.findings ?? [])\n          : undefined;\n      failed.push({ slug: key, error, ...(findings?.length ? { findings } : {}) });\n      opts.onProgress?.({ phase: 'fail', slug: key, error });\n    }\n  }\n\n  return {\n    ok: published.length > 0,\n    owner,\n    published,\n    failed,\n    ...(warnings.length ? { warnings } : {}),\n    empty: false,\n  };\n}\n", "import { RegistryClient, RegistryError, type RegistryKitView } from '../registry/client.js';\nimport { parseKitHandle } from '../registry/kit-handle.js';\nimport { kitSkillRefsFromIds } from './kit-add-materialize.js';\n\nexport interface SubscribeKitOptions {\n  registryUrl: string;\n  /** Session bearer \u2014 kit subscribe requires a signed-in user. */\n  token: string;\n  fetchImpl?: typeof fetch;\n}\n\nexport interface SubscribeKitResult {\n  kitId: string;\n  kitName: string;\n  owner: string;\n  slug: string;\n  skillCount: number;\n  /** Canonical `@owner/skill` refs in this kit. */\n  skillRefs: string[];\n  alreadySubscribed: boolean;\n}\n\n/**\n * Read-only kit lookup for `add`'s auto-detection. Returns the kit view, or\n * null when no kit lives at this handle (so `add @ref` can fall back to the\n * skill flow). A ref that isn't `@owner/slug` shaped can't name a kit, so it\n * returns null too. Only a 404 is swallowed; other failures propagate.\n */\nexport async function findKitByHandle(\n  ref: string,\n  opts: SubscribeKitOptions,\n): Promise<RegistryKitView | null> {\n  let handle: ReturnType<typeof parseKitHandle>;\n  try {\n    handle = parseKitHandle(ref);\n  } catch {\n    return null;\n  }\n  const client = new RegistryClient({\n    baseUrl: opts.registryUrl,\n    token: opts.token,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n  try {\n    return await client.getKitByHandle(handle.owner, handle.slug);\n  } catch (err) {\n    if (err instanceof RegistryError && err.status === 404) return null;\n    throw err;\n  }\n}\n\n/**\n * Resolve a kit by handle and subscribe the caller's account.\n */\nexport async function subscribeKitByHandle(\n  ref: string,\n  opts: SubscribeKitOptions,\n): Promise<SubscribeKitResult> {\n  const handle = parseKitHandle(ref);\n  const client = new RegistryClient({\n    baseUrl: opts.registryUrl,\n    token: opts.token,\n    fetchImpl: opts.fetchImpl,\n  });\n  const kit = await client.getKitByHandle(handle.owner, handle.slug);\n  const alreadySubscribed = kit.subscribed === true;\n  if (!alreadySubscribed) {\n    await client.subscribeKit(kit.id);\n  }\n  return {\n    kitId: kit.id,\n    kitName: kit.name,\n    owner: kit.owner,\n    slug: kit.slug,\n    skillCount: kit.skills?.length ?? 0,\n    skillRefs: kitSkillRefsFromIds(kit.skills ?? []),\n    alreadySubscribed,\n  };\n}\n", "/**\n * `skillet device \u2026` \u2014 manage author-signed device-key delegations.\n *\n *   approve <device_pub|code>  mint + sign a DelegationCert with the PRIMARY key\n *                              and register it (POST /api/v1/delegations).\n *   list                       GET /api/v1/delegations \u2014 active/expired/revoked.\n *   revoke <device_key_id>     mint + sign a RevocationStatement (primary key)\n *                              and POST it (.../revoke).\n *\n * \"Enroll\" is the end-to-end pairing FLOW, not a CLI write: the device/browser\n * generates its own non-extractable key and presents the public half (design\n * \u00A74.1); the CLI's half of enrollment is `approve`. Per security invariant \u00A79.8\n * this command writes NO new private key to disk \u2014 the only private key it\n * touches is the primary key already in the keystore, used solely to sign.\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { loadIdentity } from \"../identity/index.js\";\nimport { loadAuthorKeyById } from \"../signing/index.js\";\nimport {\n  mintDelegation,\n  mintRevocation,\n  deviceKeyIdFromPub,\n  DelegationError,\n} from \"../signing/delegation.js\";\nimport { RegistryClient, type DelegationListItem, type BearerDeviceListItem } from \"../registry/client.js\";\nimport { loadSessionToken } from \"../session-token.js\";\nimport { loadRegistryBearer } from \"../auth-token.js\";\nimport { readActiveDeviceFile, saveDeviceToken } from \"../device-token.js\";\nimport { REGISTRY_URL_DEFAULT } from \"../kit/types.js\";\nimport type { DelegationScope } from \"@skillet/protocol\";\n\nfunction defaultConfigDir(): string {\n  return process.env[\"XDG_CONFIG_HOME\"] ?? join(homedir(), \".config\");\n}\n\nexport class DeviceCommandError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"DeviceCommandError\";\n  }\n}\n\ninterface BaseDeviceOptions {\n  configDir?: string;\n  registryUrl?: string;\n  /** Explicit session token; falls back to the env / session file. */\n  token?: string;\n  fetchImpl?: typeof fetch;\n}\n\n/** Load a registry session bearer, or throw a user-actionable error. */\nasync function requireSessionToken(\n  opts: BaseDeviceOptions,\n): Promise<{ token: string; registryUrl: string }> {\n  const token = await loadSessionToken(opts.token);\n  if (!token) {\n    throw new DeviceCommandError(\n      \"A session token is required. Run `skillet connect <code>` first.\",\n    );\n  }\n  const identity = await loadIdentity();\n  const registryUrl = (\n    opts.registryUrl ??\n    identity?.registryUrl ??\n    REGISTRY_URL_DEFAULT\n  ).replace(/\\/+$/, \"\");\n  return { token, registryUrl };\n}\n\n/** Primary-key flows need a local signing identity on this machine. */\nasync function requirePrimarySigner(\n  opts: BaseDeviceOptions,\n): Promise<{\n  identity: NonNullable<Awaited<ReturnType<typeof loadIdentity>>>;\n  token: string;\n}> {\n  const identity = await loadIdentity();\n  if (!identity?.keyId) {\n    throw new DeviceCommandError(\n      \"Primary signing key required on this machine. \" +\n        \"Use `skillet device approve` from the device that holds your primary key, \" +\n        \"or publish from skillet.md Studio.\",\n    );\n  }\n  const { token } = await requireSessionToken(opts);\n  return { identity, token };\n}\n\nfunction clientFor(\n  opts: BaseDeviceOptions,\n  identity: { registryUrl?: string },\n  token: string,\n): RegistryClient {\n  return new RegistryClient({\n    baseUrl: opts.registryUrl ?? identity.registryUrl ?? REGISTRY_URL_DEFAULT,\n    token,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n}\n\n/**\n * Accepts either a raw base64 device pubkey or a pairing payload \u2014 a JSON\n * `{ \"device_pub\": \"<base64>\", \"label\"?: \"<str>\" }` string the browser may show\n * as a QR/code (design \u00A74.1 step 2). Returns the normalized pub + optional label.\n */\nexport function parseDevicePairing(input: string): { devicePubB64: string; label?: string } {\n  const trimmed = input.trim();\n  if (trimmed.startsWith(\"{\")) {\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(trimmed);\n    } catch {\n      throw new DeviceCommandError(\"pairing code is not valid JSON\");\n    }\n    const o = parsed as Record<string, unknown>;\n    if (typeof o.device_pub !== \"string\" || o.device_pub.length === 0) {\n      throw new DeviceCommandError(\"pairing code is missing a device_pub field\");\n    }\n    return {\n      devicePubB64: o.device_pub,\n      ...(typeof o.label === \"string\" && o.label.length > 0 ? { label: o.label } : {}),\n    };\n  }\n  return { devicePubB64: trimmed };\n}\n\nexport interface ApproveDeviceOptions extends BaseDeviceOptions {\n  /** Browser-presented device pubkey (base64) or a JSON pairing code. */\n  pairing: string;\n  /** Subset of {propose,approve,publish}. Defaults to all three. */\n  scopes?: DelegationScope[];\n  /** Lifetime in days. Defaults to 90; capped server- and client-side at 365. */\n  ttlDays?: number;\n  /** Override the label parsed from a pairing code. */\n  label?: string;\n  /** Injectable clock (unix seconds) for deterministic tests. */\n  now?: number;\n}\n\nexport interface ApproveDeviceResult {\n  deviceKeyId: string;\n  expiresAt: number;\n  scopes: string[];\n  /** True when the registry returned 200 (idempotent re-POST of the same cert). */\n  alreadyRegistered: boolean;\n}\n\n/**\n * `skillet device approve` \u2014 mint a DelegationCert for the presented device\n * pubkey, sign it with the primary key, and register it. The primary private\n * key is loaded only to sign and never leaves this process.\n */\nexport async function approveDevice(opts: ApproveDeviceOptions): Promise<ApproveDeviceResult> {\n  const { identity, token } = await requirePrimarySigner(opts);\n  const { devicePubB64, label: codeLabel } = parseDevicePairing(opts.pairing);\n  // Validate early so we fail before loading the private key on a bad pub.\n  deviceKeyIdFromPub(devicePubB64);\n\n  const configDir = opts.configDir ?? defaultConfigDir();\n  const primaryKey = await loadAuthorKeyById(configDir, identity.keyId);\n\n  const { signed, label } = mintDelegation({\n    primaryKey,\n    handle: identity.handle,\n    devicePubB64,\n    ...(opts.scopes ? { scopes: opts.scopes } : {}),\n    ...(opts.ttlDays != null ? { ttlSec: Math.round(opts.ttlDays * 86400) } : {}),\n    ...(opts.label ?? codeLabel ? { label: opts.label ?? codeLabel } : {}),\n    ...(opts.now != null ? { now: opts.now } : {}),\n  });\n\n  const client = clientFor(opts, identity, token);\n  const res = await client.registerDelegation({\n    cert: signed.cert,\n    cert_sig: signed.cert_sig,\n    ...(label ? { label } : {}),\n  });\n  return {\n    deviceKeyId: res.device_key_id,\n    expiresAt: res.expires_at,\n    scopes: res.scopes,\n    alreadyRegistered: res.already_exists,\n  };\n}\n\n/** Rows from GET /api/v1/delegations and GET /api/v1/devices (matches web Connected devices). */\nexport interface ConnectedDevicesResult {\n  delegations: DelegationListItem[];\n  sync_devices: BearerDeviceListItem[];\n}\n\n/**\n * `skillet device` / `device list` \u2014 the machines on your account. Bearer is\n * device-token-first (session fallback) via loadRegistryBearer, so the view\n * keeps working after a web session lapses \u2014 the device token is the durable\n * machine credential, same policy as rename/whoami. The registry's GET\n * /devices accepts an account-bound device token (requireUser).\n */\nexport async function listDevices(opts: BaseDeviceOptions): Promise<ConnectedDevicesResult> {\n  const bearer = await loadRegistryBearer(opts.token);\n  if (!bearer.token) {\n    throw new DeviceCommandError(\n      \"This machine isn't connected. Run `skillet connect <code>` first.\",\n    );\n  }\n  const identity = await loadIdentity();\n  const registryUrl = (opts.registryUrl ?? identity?.registryUrl ?? REGISTRY_URL_DEFAULT).replace(\n    /\\/+$/,\n    \"\",\n  );\n  const client = new RegistryClient({\n    baseUrl: registryUrl,\n    token: bearer.token,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n  const sync_devices = await client.listBearerDevices();\n  return { delegations: [], sync_devices };\n}\n\nexport interface RenameDeviceResult {\n  device_id: string;\n  label: string | null;\n}\n\n/**\n * `skillet device rename <label>` \u2014 rename THIS machine's device row.\n *\n * Bearer follows loadRegistryBearer's existing priority (device token first,\n * session fallback): post plan 2026-07-08-002 the registry accepts a device's\n * own token for self-rename, and the device token is the durable credential\n * while sessions lapse. Empty/whitespace labels are rejected BEFORE any\n * network call \u2014 the server would null the label and local surfaces gate on\n * one existing. On success the local device.json label is rewritten too\n * (machine_id preserved by saveDeviceToken), so `auth status` and the tray\n * show the new name immediately.\n */\nexport async function renameDevice(\n  label: string,\n  opts: BaseDeviceOptions = {},\n): Promise<RenameDeviceResult> {\n  const trimmed = label.trim();\n  if (trimmed.length === 0) {\n    throw new DeviceCommandError(\"Label cannot be empty.\");\n  }\n\n  const deviceFile = await readActiveDeviceFile();\n  if (!deviceFile?.device_id || !deviceFile.device_token) {\n    throw new DeviceCommandError(\n      \"This machine is not paired. Run `skillet connect <code>` first.\",\n    );\n  }\n\n  const bearer = await loadRegistryBearer(opts.token);\n  if (bearer.kind === \"none\") {\n    throw new DeviceCommandError(\n      \"No registry credential found. Run `skillet connect <code>` first.\",\n    );\n  }\n\n  const identity = await loadIdentity().catch(() => null);\n  const registryUrl = (\n    opts.registryUrl ??\n    identity?.registryUrl ??\n    REGISTRY_URL_DEFAULT\n  ).replace(/\\/+$/, \"\");\n\n  const client = new RegistryClient({\n    baseUrl: registryUrl,\n    token: bearer.token,\n    ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}),\n  });\n  const result = await client.renameDevice(deviceFile.device_id, trimmed);\n\n  // Keep the local name in lockstep with the registry (R3). saveDeviceToken\n  // carries machine_id forward on its own; label comes from the server's\n  // cleaned value so clamping never diverges.\n  if (result.label) {\n    await saveDeviceToken(deviceFile.device_token, {\n      device_id: deviceFile.device_id,\n      label: result.label,\n      ...(deviceFile.machine_id ? { machine_id: deviceFile.machine_id } : {}),\n    });\n  }\n\n  return result;\n}\n\nexport interface RevokeDeviceOptions extends BaseDeviceOptions {\n  deviceKeyId: string;\n  now?: number;\n}\n\nexport interface RevokeDeviceResult {\n  deviceKeyId: string;\n  revokedAt: number;\n}\n\n/**\n * `skillet device revoke` \u2014 mint + sign a RevocationStatement with the primary\n * key and submit it. After this, the registry rejects new propose/approve from\n * the key, and clients that pull the revocation refuse fresh acceptance.\n */\nexport async function revokeDevice(opts: RevokeDeviceOptions): Promise<RevokeDeviceResult> {\n  const { identity, token } = await requirePrimarySigner(opts);\n  const configDir = opts.configDir ?? defaultConfigDir();\n  const primaryKey = await loadAuthorKeyById(configDir, identity.keyId);\n\n  const signed = mintRevocation({\n    primaryKey,\n    deviceKeyId: opts.deviceKeyId,\n    ...(opts.now != null ? { now: opts.now } : {}),\n  });\n\n  const client = clientFor(opts, identity, token);\n  const res = await client.revokeDelegation(opts.deviceKeyId, {\n    revocation: signed.revocation,\n    revocation_sig: signed.revocation_sig,\n  });\n  return { deviceKeyId: res.device_key_id, revokedAt: res.revoked_at };\n}\n\nexport { DelegationError };\n", "// Client-side verification for the \u00A710 adapter manifest feed.\n//\n// Usage:\n//   const manifest = await fetch('/api/v1/adapters/manifest').then(r => r.json());\n//   const verified = verifyAdapterManifest(manifest);   // throws on any failure\n//   const updated  = mergeAdapterManifest(current, verified); // degrade-never-delete merge\n//\n// Security invariants:\n//   - Signature MUST verify against the hardcoded Skillet release public key.\n//   - content_hash MUST match a fresh derivation from the received adapters.\n//   - Each adapter root is validated against the per-runtime allowlist.\n//   - Path-escape in root is rejected.\n//   - mergeAdapterManifest never deletes an existing adapter; invalid entries degrade.\n\nimport { createHash } from 'node:crypto';\nimport { homedir } from 'node:os';\nimport { resolve, join, normalize, sep } from 'node:path';\nimport { skilletReleasePublicKey } from '../signing/index.js';\nimport { verifyEnvelope, type Signature } from '../signing/envelope.js';\nimport { isEd25519Signature } from '../signing/session-attest.js';\nimport {\n  MATERIALIZATION_ROOT_ALLOWLIST,\n  PROJECT_TARGET_ALLOWLIST,\n} from '../util/pathsafe.js';\n\nexport type AdapterKind = 'global' | 'project';\nexport type AdapterLayout = 'skill-md' | 'mdc' | 'rules-file';\n\nexport interface AdapterEntry {\n  detect: string;\n  key: string;\n  kind: AdapterKind;\n  layout: AdapterLayout;\n  root: string;\n  version: string;\n}\n\nexport interface AdapterManifest {\n  adapters: AdapterEntry[];\n  content_hash: string;\n  signature: Signature | null;\n}\n\nexport interface VerifiedAdapterManifest {\n  adapters: AdapterEntry[];\n  content_hash: string;\n}\n\n// Reject roots with traversal segments or embedded null bytes regardless of kind.\nfunction hasPathEscape(root: string): boolean {\n  if (root.includes('\\x00')) return true;\n  const norm = normalize(root.replace(/\\//g, sep));\n  return norm.split(sep).some((s) => s === '..');\n}\n\n// Expand \"~\" prefix to the actual homedir. Only the leading \"~/\" is expanded;\n// \"~user\" is not supported (and would fail the allowlist check anyway).\nfunction expandTilde(p: string): string {\n  if (p === '~' || p.startsWith('~/')) {\n    return join(homedir(), p.slice(1));\n  }\n  return p;\n}\n\n// Validate a single adapter entry's root against the per-runtime allowlist.\n// Returns null if valid, or a human-readable rejection reason.\nfunction validateRoot(entry: AdapterEntry): string | null {\n  if (hasPathEscape(entry.root)) {\n    return `path-escape rejected in root \"${entry.root}\"`;\n  }\n\n  if (entry.kind === 'project') {\n    if (entry.root.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(entry.root)) {\n      return `project root \"${entry.root}\" must be a relative POSIX path`;\n    }\n    if (!PROJECT_TARGET_ALLOWLIST.includes(entry.root)) {\n      return `project root \"${entry.root}\" is not in the project-target allowlist`;\n    }\n    return null;\n  }\n\n  // Global adapter: expand tilde and compare against MATERIALIZATION_ROOT_ALLOWLIST.\n  const expanded = expandTilde(entry.root);\n  const resolved = resolve(expanded);\n  const allowed = MATERIALIZATION_ROOT_ALLOWLIST.some(\n    (a) => resolve(a) === resolved,\n  );\n  if (!allowed) {\n    return `global root \"${entry.root}\" is not in the per-runtime allowlist`;\n  }\n  return null;\n}\n\n/**\n * Produce the canonical JSON bytes used to compute content_hash.\n * MUST match the server-side implementation in packages/registry/src/routes/adapters.ts.\n * Fields are alphabetical; entries are sorted by key; compact (no whitespace).\n */\nexport function canonicalAdapterJson(adapters: AdapterEntry[]): string {\n  const sorted = [...adapters].sort((a, b) => a.key.localeCompare(b.key));\n  const normalized = sorted.map((e) => ({\n    detect: e.detect,\n    key: e.key,\n    kind: e.kind,\n    layout: e.layout,\n    root: e.root,\n    version: e.version,\n  }));\n  return JSON.stringify(normalized);\n}\n\nexport function deriveAdapterContentHash(adapters: AdapterEntry[]): string {\n  const json = canonicalAdapterJson(adapters);\n  const hex = createHash('sha256').update(json, 'utf8').digest('hex');\n  return `sha256:${hex}`;\n}\n\n/**\n * Verify an adapter manifest received from the registry.\n *\n * Throws a descriptive error for every failure mode:\n *   - Missing or null signature (callers may allow in dev mode with `opts.allowUnsigned`)\n *   - Signature fails Ed25519 verification against the Skillet release public key\n *   - content_hash does not match derivation from the adapters array\n *   - Any adapter entry fails root allowlist validation or path-escape check\n *\n * Returns the verified manifest with only entries that passed allowlist validation.\n * Entries that fail are silently dropped (degrade path); the caller should log them.\n */\n/** Default verify options: unsigned manifests allowed only in non-production dev. */\nexport function adapterManifestVerifyOptions(): { allowUnsigned?: boolean } {\n  if (process.env.SKILLET_ALLOW_UNSIGNED_MANIFEST === '1') {\n    return { allowUnsigned: true };\n  }\n  if (process.env.NODE_ENV === 'production') {\n    return { allowUnsigned: false };\n  }\n  return { allowUnsigned: true };\n}\n\nexport function verifyAdapterManifest(\n  manifest: unknown,\n  opts: { allowUnsigned?: boolean } = adapterManifestVerifyOptions(),\n): VerifiedAdapterManifest {\n  if (!manifest || typeof manifest !== 'object') {\n    throw new Error('adapter manifest: response is not an object');\n  }\n  const m = manifest as Record<string, unknown>;\n\n  if (!Array.isArray(m['adapters'])) {\n    throw new Error('adapter manifest: missing adapters array');\n  }\n  if (typeof m['content_hash'] !== 'string') {\n    throw new Error('adapter manifest: missing content_hash string');\n  }\n\n  const adapters = m['adapters'] as AdapterEntry[];\n  const content_hash = m['content_hash'] as string;\n  const signature = m['signature'] as Signature | null;\n\n  // Signature gate.\n  if (!signature) {\n    if (!opts.allowUnsigned) {\n      throw new Error(\n        'adapter manifest: signature is null; refusing unsigned manifest (pass allowUnsigned for dev mode)',\n      );\n    }\n  } else if (isEd25519Signature(signature)) {\n    const pubKey = skilletReleasePublicKey();\n    verifyEnvelope(content_hash, signature, pubKey);\n  } else {\n    throw new Error(\n      `adapter manifest: unsupported signature alg ${JSON.stringify(signature.alg)}`,\n    );\n  }\n\n  // Integrity: re-derive the hash from the received adapters and compare.\n  const derived = deriveAdapterContentHash(adapters);\n  if (derived !== content_hash) {\n    throw new Error(\n      `adapter manifest: content_hash mismatch (received ${content_hash}, derived ${derived})`,\n    );\n  }\n\n  // Allowlist validation \u2014 degrade-path: drop invalid entries, keep valid ones.\n  const valid: AdapterEntry[] = [];\n  for (const entry of adapters) {\n    const rejection = validateRoot(entry);\n    if (rejection) {\n      // Degrade: skip entry, never throw here. Caller may log this path.\n      continue;\n    }\n    valid.push(entry);\n  }\n\n  return { adapters: valid, content_hash };\n}\n\n/**\n * Merge a verified manifest into the current adapter set.\n *\n * Rules (degrade-never-delete):\n *   - If a key appears in `verified` it replaces the entry in `current`.\n *   - If a key appears only in `current` it is KEPT (never deleted).\n *   - New keys in `verified` not in `current` are added.\n *\n * This is the soak-safe merge: a misbehaving registry that drops adapters\n * does not remove them from the client's active set. A genuine removal\n * requires a version bump and a soak period the CLI orchestrates.\n */\nexport function mergeAdapterManifest(\n  current: AdapterEntry[],\n  verified: VerifiedAdapterManifest,\n): AdapterEntry[] {\n  const map = new Map<string, AdapterEntry>();\n  for (const e of current) map.set(e.key, e);\n  for (const e of verified.adapters) map.set(e.key, e);\n  return [...map.values()];\n}\n", "export * from \"./adapter.js\";\nexport { REGISTRY_API } from \"./registry-api.js\";\nexport * from \"./bundle/index.js\";\nexport * from \"./kit/index.js\";\nexport {\n  saveIdentity,\n  loadIdentity,\n  identityPath,\n  type Identity,\n} from \"./identity/index.js\";\nexport { login, type LoginOptions, type LoginResult } from \"./commands/login.js\";\nexport {\n  publish,\n  publishAll,\n  PublishError,\n  type PublishOptions,\n  type PublishResult,\n  type PublishErrorCode,\n} from \"./commands/publish.js\";\nexport {\n  propose,\n  proposeCustomized,\n  ProposeError,\n  type ProposeOptions,\n  type ProposeResult,\n  type ProposeErrorCode,\n  type ProposeTarget,\n  type ProposeBase,\n  type ProposeCustomizedResult,\n  type ProposeCustomizedAccepted,\n  type ProposeCustomizedRefused,\n} from \"./commands/propose.js\";\nexport {\n  evalSkills,\n  type EvalSkillResult,\n} from \"./commands/eval.js\";\nexport * from \"./lock.js\";\nexport { stableMachineId, deriveMachineId } from \"./machine-identity.js\";\nexport * from \"./metrics.js\";\nexport * from \"./commands/import.js\";\nexport * from \"./github/index.js\";\nexport {\n  discoverGitHubSkills,\n  importGitHubSkill,\n  type DiscoveredGitHubSkill,\n  type GitHubDiscovery,\n  type DiscoverOptions,\n  type ImportGitHubOptions,\n} from \"./commands/import-github.js\";\nexport {\n  discoverExistingSkills,\n  importDiscoveredSkills,\n  runtimeLabel,\n  runtimePhrase,\n  runtimesAcross,\n  type DiscoveredSkill,\n  type DiscoveryReport,\n  type ImportDiscoveredResult,\n} from \"./commands/discover.js\";\nexport * from \"./commands/sync.js\";\n// Curated customized-skills surface: only what the CLI/desktop actually\n// consume. Internals (moveDir, ledgerStamp, backupSkillVersion, drift\n// detection, \u2026) stay module-level exports for core's own commands and tests,\n// but are not part of the package API.\nexport {\n  listCustomized,\n  takeUpstream,\n  restoreOriginal,\n  keepMine,\n  lineageRef,\n  readLiveCustomizedTree,\n  ReconcileError,\n  type CustomizedSkill,\n  type ReconcileResult,\n  type ReconcileOptions,\n  type ReconcileErrorCode,\n} from \"./commands/edits.js\";\n// Moved to the leaf ./commands/edits-store.js (breaks the edits\u2194sync cycle);\n// re-pointed here so the public export names stay identical.\nexport {\n  listBackups,\n  type SkillLineage,\n  type BackupEntry,\n  type BackupManifest,\n  type BackupReason,\n} from \"./commands/edits-store.js\";\nexport {\n  BUNDLED_ROUTE_SLUG,\n  KNOWN_ROUTE_SURFACES,\n  listRouteManifest,\n  recordRouteInvocation,\n  recordSkillRoute,\n  RouteSkillError,\n  skillRefFromEntry,\n  type RouteManifestEntry,\n  type RouteInvocationOptions,\n  type RouteSurface,\n  type RecordSkillRouteOptions,\n  type RouteSkillErrorCode,\n} from \"./commands/route.js\";\nexport {\n  installRouteHook,\n  installRouteHooksForRuntimes,\n  hookRuntimesFromDetected,\n  isHookCapableRuntime,\n  installCursorRouteHook,\n  type RouteHookInstallOptions,\n  type RouteHookInstallResult,\n  type InstallRouteHooksResult,\n  type CursorRouteHookInstallOptions,\n  type CursorRouteHookInstallResult,\n} from \"./commands/route-hooks/index.js\";\nexport {\n  ensureBundledRouteSkill,\n  type EnsureBundledRouteResult,\n} from \"./commands/bundled-route-skill.js\";\nexport {\n  materializeSkills,\n  type MaterializeSkillsOptions,\n  type MaterializeSkillsResult,\n} from \"./commands/materialize-skills.js\";\nexport {\n  skillIdToRef,\n  kitSkillRefsFromIds,\n} from \"./commands/kit-add-materialize.js\";\nexport {\n  listTrash,\n  restoreTrash,\n  clearOldTrash,\n  sweepOrphans,\n  type TrashRun,\n  type RestoreResult,\n  type SweepResult,\n} from \"./commands/restore.js\";\nexport * from \"./commands/status.js\";\nexport { add, type AddOptions, type AddResult } from \"./commands/add.js\";\nexport {\n  extractPairCode,\n  isValidPairCode,\n  normalizePairCode,\n  PAIR_CODE_LEN,\n  PAIR_CODE_RE,\n} from \"./pair-code.js\";\nexport {\n  listPending,\n  type PendingEntry,\n  type PendingResult,\n  type PendingOptions,\n} from \"./commands/pending.js\";\nexport {\n  approveUpdate,\n  type ApproveOptions,\n} from \"./commands/approve.js\";\nexport {\n  rejectUpdate,\n  type RejectOptions,\n} from \"./commands/reject.js\";\nexport {\n  claimHandle,\n  secondaryDeviceMessage,\n  type ClaimOptions,\n  type ClaimResult,\n} from \"./commands/claim.js\";\nexport {\n  authLogout,\n  type AuthLogoutOptions,\n} from \"./commands/auth-logout.js\";\nexport {\n  authDisconnectLocal,\n  type AuthDisconnectOptions,\n} from \"./commands/auth-disconnect.js\";\nexport { loadSessionToken, readSessionFileToken, envSessionToken, envSessionTokenForceActive, sessionTokenPrecedenceMode, saveSessionToken, sessionFilePath, skilletDir } from \"./session-token.js\";\nexport type { SessionTokenPrecedence } from \"./session-token.js\";\nexport {\n  readActiveDeviceFile,\n  saveDeviceToken,\n  clearDeviceToken,\n  deviceFilePath,\n  type DeviceTokenFile,\n} from \"./device-token.js\";\nexport {\n  loadRegistryBearer,\n  classifyRegistryBearer,\n  type RegistryBearer,\n  type RegistryBearerKind,\n} from \"./auth-token.js\";\nexport { authStatus, type AuthStatus, type AuthStatusOptions } from \"./commands/auth-status.js\";\nexport {\n  collectDoctorReport,\n  DOCTOR_REPORT_SCHEMA,\n  type DoctorReport,\n  type DoctorReportOptions,\n} from \"./commands/doctor.js\";\nexport { authConnect, type AuthConnectOptions, type AuthConnectResult } from \"./commands/auth-connect.js\";\nexport {\n  authConnectPair,\n  type AuthConnectPairOptions,\n  type AuthConnectPairResult,\n} from \"./commands/auth-connect-pair.js\";\nexport {\n  mintPairCode,\n  type MintPairCodeOptions,\n  type MintPairCodeResult,\n} from \"./commands/mint-pair-code.js\";\nexport {\n  createOrg,\n  inviteOrgMember,\n  listOrgMembers,\n  type TeamCreateOptions,\n  type TeamCreateResult,\n  type TeamInviteOptions,\n  type TeamInviteResult,\n  type TeamMembersOptions,\n  type TeamMembersResult,\n  type OrgMember,\n  type PendingInvite,\n} from \"./commands/team.js\";\nexport {\n  createKit,\n  addSkillToKit,\n  inviteKitMember,\n  listKitMembers,\n  mintKitKey,\n  removeKitMember,\n  revokeKitKey,\n  type KitCreateOptions,\n  type KitCreateResult,\n  type KitInviteResult,\n  type KitKeyMintResult,\n  type KitMembersResult,\n} from \"./commands/kit.js\";\nexport {\n  bootstrapLocalKit,\n  type BootstrapLocalKitOptions,\n  type BootstrapLocalKitResult,\n  type BootstrapFailureStage,\n} from \"./commands/kit-bootstrap.js\";\nexport {\n  uploadLocalSkills,\n  type UploadLocalSkillsOptions,\n  type UploadLocalSkillsResult,\n  type UploadProgressEvent,\n} from \"./commands/upload-skills.js\";\nexport {\n  subscribeKitByHandle,\n  findKitByHandle,\n  type SubscribeKitOptions,\n  type SubscribeKitResult,\n} from \"./commands/kit-subscribe.js\";\nexport {\n  RegistryClient,\n  RegistryError,\n  parseSkillRef,\n  formatSkillRef,\n  parseKitHandle,\n  KitHandleError,\n  SkillRefError,\n  type SkillRef,\n  type KitHandle,\n  type RegistryClientOptions,\n  type RegistryManifest,\n  type RegistryKitView,\n  type VersionDetail,\n  type CacheableResult,\n  resolveDeviceScopedManifest,\n  type DeviceScopedManifestResult,\n  type ResolveDeviceScopedManifestOptions,\n} from \"./registry/index.js\";\nexport {\n  pullRegistryUpdates,\n  type PullOptions,\n  type PullOutcome,\n  type PullStatus,\n} from \"./registry/pull.js\";\nexport {\n  computeDiff,\n  checkLock,\n  recordApproval,\n  checkRejection,\n  recordRejection,\n  getLastApprovedVersion,\n  defaultApprovalLockPath,\n  promptApproval,\n  promptQuarantineConsent,\n  renderFindingsSummary,\n  requiresQuarantineConsent,\n  resolveTrustMode,\n  loadPolicy,\n  savePolicy,\n  defaultPolicyPath,\n  setGlobalDefault,\n  setAuthorPolicy,\n  setSkillPolicy,\n  setKitPolicy,\n  DEFAULT_POLICY,\n} from \"./trust/index.js\";\nexport type { DiffApproval, DiffRejection } from \"./trust/index.js\";\nexport type {\n  TrustMode,\n  SourceClass,\n  TrustPolicyFile,\n  PolicyInput,\n} from \"./trust/index.js\";\n// Utilities exposed for adapter packages\nexport { sha256, hashRef, hashFile } from \"./util/hash.js\";\nexport {\n  assertSafe,\n  assertSafeSlug,\n  assertNoPathEscape,\n  validateMaterializationPath,\n  validateAdapterRoot,\n  validateProjectAdapterRoot,\n  resolveAdapterRoot,\n  MATERIALIZATION_ROOT_ALLOWLIST,\n  PROJECT_TARGET_ALLOWLIST,\n  HERMES_ENV_ROOT,\n  HERMES_DEFAULT_HOME,\n  HERMES_PROFILE_ROOT,\n  CLAUDE_ENV_ROOT,\n} from \"./util/pathsafe.js\";\nexport { atomicWrite } from \"./util/atomic.js\";\nexport {\n  generateAuthorKey,\n  saveAuthorKey,\n  loadAuthorKey,\n  loadAuthorKeyById,\n  signBundle,\n  verifyBundle,\n  skilletReleasePublicKey,\n} from \"./signing/index.js\";\nexport type { AuthorKey } from \"./signing/index.js\";\nexport {\n  signatureBytes,\n  signEnvelope,\n  verifyEnvelope,\n  SignatureError,\n  SIG_ALG_ED25519,\n} from \"./signing/envelope.js\";\nexport type {\n  Signature,\n  SigAlg,\n  SignatureErrorCode,\n} from \"./signing/envelope.js\";\nexport {\n  defaultPinDir,\n  loadPinnedKey,\n  pinAuthorKey,\n  forceRepinAuthorKey,\n  resolveAuthorKey,\n  listPinnedHandles,\n  publicKeyFromBase64,\n} from \"./signing/pin.js\";\nexport type { PinnedAuthorKey } from \"./signing/pin.js\";\nexport {\n  parseAuthorKeyMismatch,\n  compareAuthorPin,\n  fetchServedAuthorKey,\n  acceptAuthorKeyRotation,\n  formatAuthorKeyMismatchHint,\n  truncateKeyId,\n} from \"./signing/pin-recovery.js\";\nexport type { AuthorKeyMismatchInfo, AuthorPinComparison } from \"./signing/pin-recovery.js\";\nexport {\n  mintDelegation,\n  mintRevocation,\n  deviceKeyIdFromPub,\n  verifyDelegationCert,\n  verifyDelegatedVersionSignature,\n  DelegationError,\n} from \"./signing/delegation.js\";\nexport type {\n  DelegationErrorCode,\n  MintDelegationOptions,\n  MintRevocationOptions,\n  VerifyDelegatedVersionOptions,\n} from \"./signing/delegation.js\";\nexport {\n  approveDevice,\n  listDevices,\n  renameDevice,\n  revokeDevice,\n  parseDevicePairing,\n  DeviceCommandError,\n} from \"./commands/device.js\";\nexport type {\n  ApproveDeviceOptions,\n  ApproveDeviceResult,\n  RevokeDeviceOptions,\n  RevokeDeviceResult,\n  ConnectedDevicesResult,\n} from \"./commands/device.js\";\nexport type { DelegationListItem, BearerDeviceListItem } from \"./registry/client.js\";\nexport {\n  canonicalAdapterJson,\n  deriveAdapterContentHash,\n  verifyAdapterManifest,\n  adapterManifestVerifyOptions,\n  mergeAdapterManifest,\n} from \"./adapters/manifest.js\";\nexport type {\n  AdapterEntry,\n  AdapterManifest,\n  AdapterKind,\n  AdapterLayout,\n  VerifiedAdapterManifest,\n} from \"./adapters/manifest.js\";\n// Explicit named re-exports from ./lock.js so the new symbols\n// (verifyLockedSignature, LockVerificationFinding) are unambiguously surfaced\n// even though line 4's `export * from \"./lock.js\"` already re-exports them.\nexport {\n  encodeLockFile,\n  decodeLockFile,\n  buildLockFile,\n  readLockFile,\n  verifyLockedSkill,\n  verifyLockedSignature,\n} from \"./lock.js\";\nexport type {\n  LockVerificationFinding,\n} from \"./lock.js\";\n", "'use strict';\n\nconst ESC = '\\x1B';\nconst CSI = `${ESC}[`;\nconst beep = '\\u0007';\n\nconst cursor = {\n  to(x, y) {\n    if (!y) return `${CSI}${x + 1}G`;\n    return `${CSI}${y + 1};${x + 1}H`;\n  },\n  move(x, y) {\n    let ret = '';\n\n    if (x < 0) ret += `${CSI}${-x}D`;\n    else if (x > 0) ret += `${CSI}${x}C`;\n\n    if (y < 0) ret += `${CSI}${-y}A`;\n    else if (y > 0) ret += `${CSI}${y}B`;\n\n    return ret;\n  },\n  up: (count = 1) => `${CSI}${count}A`,\n  down: (count = 1) => `${CSI}${count}B`,\n  forward: (count = 1) => `${CSI}${count}C`,\n  backward: (count = 1) => `${CSI}${count}D`,\n  nextLine: (count = 1) => `${CSI}E`.repeat(count),\n  prevLine: (count = 1) => `${CSI}F`.repeat(count),\n  left: `${CSI}G`,\n  hide: `${CSI}?25l`,\n  show: `${CSI}?25h`,\n  save: `${ESC}7`,\n  restore: `${ESC}8`\n}\n\nconst scroll = {\n  up: (count = 1) => `${CSI}S`.repeat(count),\n  down: (count = 1) => `${CSI}T`.repeat(count)\n}\n\nconst erase = {\n  screen: `${CSI}2J`,\n  up: (count = 1) => `${CSI}1J`.repeat(count),\n  down: (count = 1) => `${CSI}J`.repeat(count),\n  line: `${CSI}2K`,\n  lineEnd: `${CSI}K`,\n  lineStart: `${CSI}1K`,\n  lines(count) {\n    let clear = '';\n    for (let i = 0; i < count; i++)\n      clear += this.line + (i < count - 1 ? cursor.up() : '');\n    if (count)\n      clear += cursor.left;\n    return clear;\n  }\n}\n\nmodule.exports = { cursor, scroll, erase, beep };\n", "/**\n * Minimal MCP (Model Context Protocol) JSON-RPC 2.0 wire types.\n * Spec: https://spec.modelcontextprotocol.io/specification/2025-03-26/\n */\n\nexport const JSONRPC_VERSION = \"2.0\" as const;\nexport const MCP_PROTOCOL_VERSION = \"2025-03-26\" as const;\n\n// \u2500\u2500 Incoming messages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface RpcRequest {\n  jsonrpc: \"2.0\";\n  id: string | number;\n  method: string;\n  params?: unknown;\n}\n\n/** Notification: method present, no id. */\nexport interface RpcNotification {\n  jsonrpc: \"2.0\";\n  method: string;\n  params?: unknown;\n}\n\nexport type RpcIncoming = RpcRequest | RpcNotification;\n\nexport function isRequest(msg: RpcIncoming): msg is RpcRequest {\n  return \"id\" in msg;\n}\n\n// \u2500\u2500 Outgoing messages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface RpcSuccess {\n  jsonrpc: \"2.0\";\n  id: string | number;\n  result: unknown;\n}\n\nexport interface RpcErrorResponse {\n  jsonrpc: \"2.0\";\n  id: string | number | null;\n  error: { code: number; message: string; data?: unknown };\n}\n\nexport type RpcResponse = RpcSuccess | RpcErrorResponse;\n\nexport function ok(id: string | number, result: unknown): RpcSuccess {\n  return { jsonrpc: \"2.0\", id, result };\n}\n\nexport function err(\n  id: string | number | null,\n  code: number,\n  message: string,\n  data?: unknown,\n): RpcErrorResponse {\n  const error: { code: number; message: string; data?: unknown } = { code, message };\n  if (data !== undefined) error.data = data;\n  return { jsonrpc: \"2.0\", id, error };\n}\n\n/** Standard JSON-RPC error codes. */\nexport const ERRC = {\n  PARSE_ERROR: -32700,\n  INVALID_REQUEST: -32600,\n  METHOD_NOT_FOUND: -32601,\n  INVALID_PARAMS: -32602,\n  INTERNAL_ERROR: -32603,\n} as const;\n\n// \u2500\u2500 MCP capability shapes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface McpTool {\n  name: string;\n  description: string;\n  inputSchema: {\n    type: \"object\";\n    properties: Record<string, unknown>;\n    required?: string[];\n  };\n}\n\nexport interface McpResource {\n  uri: string;\n  name: string;\n  description?: string;\n  mimeType?: string;\n}\n\nexport interface McpResourceContent {\n  uri: string;\n  mimeType?: string;\n  /** UTF-8 text content. Use `blob` for binary. */\n  text?: string;\n  /** Base64-encoded binary content. */\n  blob?: string;\n}\n\nexport interface ToolResultContent {\n  type: \"text\";\n  text: string;\n}\n", "/**\n * Refuse symlink hops when reading from the canonical skill store.\n */\n\nimport { lstat, realpath } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\nexport class SkillPathError extends Error {\n  constructor(\n    readonly code: \"path_escape\" | \"symlink_refused\",\n    message: string,\n  ) {\n    super(message);\n    this.name = \"SkillPathError\";\n  }\n}\n\n/** Resolve a bundle-relative path under `skillDir`, refusing symlinks and escapes. */\nexport async function resolveSkillFilePath(\n  skillDir: string,\n  bundlePath: string,\n): Promise<string> {\n  const parts = bundlePath.split(\"/\").filter(Boolean);\n  if (parts.length === 0) {\n    throw new SkillPathError(\"path_escape\", \"empty bundle path\");\n  }\n  for (const part of parts) {\n    if (part === \".\" || part === \"..\") {\n      throw new SkillPathError(\"path_escape\", `unsafe path segment: ${part}`);\n    }\n  }\n\n  let current = skillDir;\n  for (const part of parts) {\n    current = join(current, part);\n    const st = await lstat(current);\n    if (st.isSymbolicLink()) {\n      throw new SkillPathError(\"symlink_refused\", `symlink refused: ${part}`);\n    }\n  }\n\n  const rootReal = await realpath(skillDir);\n  const targetReal = await realpath(current);\n  const rel = relative(rootReal, targetReal);\n  if (rel.startsWith(\"..\")) {\n    throw new SkillPathError(\"path_escape\", \"path escapes skill store\");\n  }\n  return current;\n}\n", "/**\n * Read-only view of the Skillet canonical store for the MCP transport.\n *\n * The MCP layer is a pure consumer: it reads from `~/.skillet/skills/{slug}/`\n * (the already-gated, already-verified store) and never re-runs registry\n * pull, signature verification, scan, or the trust gate.\n */\n\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n  readState,\n  skillContentDir,\n  type KitState,\n  type SkillEntry,\n} from \"@skillet/core\";\nimport { resolveSkillFilePath, SkillPathError } from \"./skill-path.js\";\n\nexport { SkillPathError };\n\nexport { type KitState, type SkillEntry };\n\n/** Flat list of bundle file paths (POSIX-relative) for a skill in the store. */\nexport async function listSkillFiles(slug: string): Promise<string[]> {\n  const dir = skillContentDir(slug);\n  const paths: string[] = [];\n  await walkDir(dir, dir, paths);\n  paths.sort();\n  return paths;\n}\n\nasync function walkDir(root: string, current: string, out: string[]): Promise<void> {\n  let entries;\n  try {\n    entries = await readdir(current, { withFileTypes: true });\n  } catch {\n    return;\n  }\n  for (const e of entries) {\n    if (e.isSymbolicLink()) continue;\n    const abs = join(current, e.name);\n    if (e.isDirectory()) {\n      await walkDir(root, abs, out);\n    } else if (e.isFile()) {\n      const rel = abs.slice(root.length + 1).replace(/\\\\/g, \"/\");\n      out.push(rel);\n    }\n  }\n}\n\n/** Read a single file from the skill store. Returns null if not found. */\nexport async function readSkillFile(\n  slug: string,\n  bundlePath: string,\n): Promise<Buffer | null> {\n  const dir = skillContentDir(slug);\n  try {\n    const abs = await resolveSkillFilePath(dir, bundlePath);\n    return await readFile(abs);\n  } catch (e) {\n    if (e instanceof SkillPathError) throw e;\n    if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n    throw e;\n  }\n}\n\nexport { readState };\n\n// \u2500\u2500 Injectable skill source \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Abstraction over where skills come from. The MCP tool/resource layer reads\n * through this interface; local disk (`localSkillSource`) is the default so\n * CLI/stdio behavior is unchanged. Sources are dumb \u2014 auth filtering stays in\n * the caller, and slug/path validation happens before any `readFile` call.\n */\nexport interface SkillSource {\n  /** All skill entries known to this source (pre-auth; caller filters). */\n  listEntries(): Promise<SkillEntry[]>;\n  /** Flat list of bundle file paths (POSIX-relative) for a skill. */\n  listFiles(slug: string): Promise<string[]>;\n  /** Read a single bundle file. Returns null if not found. */\n  readFile(slug: string, path: string): Promise<Uint8Array | string | null>;\n}\n\n/** Default source: the canonical on-disk store (~/.skillet/skills/). */\nexport const localSkillSource: SkillSource = {\n  async listEntries(): Promise<SkillEntry[]> {\n    const state = await readState();\n    return Object.values(state.skills);\n  },\n  listFiles(slug: string): Promise<string[]> {\n    return listSkillFiles(slug);\n  },\n  readFile(slug: string, path: string): Promise<Uint8Array | string | null> {\n    return readSkillFile(slug, path);\n  },\n};\n", "/**\n * Skillet MCP resource model.\n *\n * Resource URI scheme:  skillet://{owner}/{slug}/{path}\n *   owner  \u2014 author handle (without `@`), or `_local` for unowned imports.\n *   slug   \u2014 skill slug (validated by assertSafeSlug).\n *   path   \u2014 POSIX-relative bundle path (e.g. `SKILL.md`, `references/policy.md`).\n *\n * SKILL.md is the headline resource; all other bundle files are siblings.\n * URIs are path-escape safe: `..` and absolute paths are rejected.\n */\n\nimport { Buffer } from \"node:buffer\";\nimport { assertSafeSlug } from \"@skillet/core\";\nimport type { McpResource, McpResourceContent } from \"./protocol.js\";\nimport { localSkillSource, type SkillEntry, type SkillSource } from \"./store.js\";\n\nconst SAFE_SEGMENT_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;\nconst SAFE_PATH_RE = /^[a-zA-Z0-9][a-zA-Z0-9._\\-/]*$/;\n\n/** Canonical owner segment: normalise null/undefined \u2192 `_local`, strip leading `@`. */\nexport function ownerSegment(owner: string | null | undefined): string {\n  if (!owner) return \"_local\";\n  return owner.startsWith(\"@\") ? owner.slice(1) : owner;\n}\n\n/** Build a `skillet://` resource URI for a skill file. */\nexport function buildUri(owner: string | null | undefined, slug: string, path: string): string {\n  return `skillet://${ownerSegment(owner)}/${slug}/${path}`;\n}\n\nexport interface ParsedUri {\n  owner: string;   // owner segment (may be `_local`)\n  slug: string;\n  path: string;   // POSIX-relative bundle path\n}\n\n/**\n * Parse and validate a `skillet://` resource URI.\n * Throws on malformed, path-escape, or unsafe slug/path.\n */\nexport function parseUri(uri: string): ParsedUri {\n  const prefix = \"skillet://\";\n  if (!uri.startsWith(prefix)) {\n    throw new Error(`Invalid Skillet resource URI: expected \"skillet://\" scheme`);\n  }\n  const rest = uri.slice(prefix.length);\n  const firstSlash = rest.indexOf(\"/\");\n  if (firstSlash < 1) throw new Error(`URI missing owner segment: \"${uri}\"`);\n  const owner = rest.slice(0, firstSlash);\n  const afterOwner = rest.slice(firstSlash + 1);\n\n  const secondSlash = afterOwner.indexOf(\"/\");\n  if (secondSlash < 1) throw new Error(`URI missing slug segment: \"${uri}\"`);\n  const slug = afterOwner.slice(0, secondSlash);\n  const path = afterOwner.slice(secondSlash + 1);\n\n  if (!SAFE_SEGMENT_RE.test(owner) && owner !== \"_local\") {\n    throw new Error(`URI owner segment contains unsafe characters: \"${owner}\"`);\n  }\n  assertSafeSlug(slug);\n  validateBundlePath(path);\n\n  return { owner, slug, path };\n}\n\n/** Reject paths with `..`, null bytes, absolute paths, or unsafe chars. */\nfunction validateBundlePath(path: string): void {\n  if (!path || path.length === 0) throw new Error(\"Resource path is empty\");\n  if (path.includes(\"\\x00\")) throw new Error(`Null byte in resource path`);\n  if (path.startsWith(\"/\")) throw new Error(`Absolute resource path rejected: \"${path}\"`);\n  const segments = path.split(\"/\");\n  for (const seg of segments) {\n    if (seg === \".\" || seg === \"..\") {\n      throw new Error(`Path traversal rejected in resource URI: \"${path}\"`);\n    }\n    if (seg.length === 0) throw new Error(`Empty path segment in resource URI: \"${path}\"`);\n  }\n  if (!SAFE_PATH_RE.test(path)) {\n    throw new Error(`Unsafe characters in resource path: \"${path}\"`);\n  }\n}\n\nfunction mimeType(path: string): string {\n  if (path.endsWith(\".md\")) return \"text/markdown\";\n  if (path.endsWith(\".json\")) return \"application/json\";\n  if (path.endsWith(\".yaml\") || path.endsWith(\".yml\")) return \"application/yaml\";\n  if (path.endsWith(\".toml\")) return \"application/toml\";\n  if (path.endsWith(\".txt\")) return \"text/plain\";\n  if (path.endsWith(\".py\")) return \"text/x-python\";\n  if (path.endsWith(\".ts\")) return \"text/typescript\";\n  if (path.endsWith(\".js\")) return \"text/javascript\";\n  return \"application/octet-stream\";\n}\n\n/** UTF-8 text for source data that may be a string or raw bytes. */\nexport function sourceDataToText(data: Uint8Array | string): string {\n  return typeof data === \"string\" ? data : Buffer.from(data).toString(\"utf8\");\n}\n\n/** Base64 for source data that may be a string or raw bytes. */\nfunction sourceDataToBase64(data: Uint8Array | string): string {\n  return typeof data === \"string\"\n    ? Buffer.from(data, \"utf8\").toString(\"base64\")\n    : Buffer.from(data).toString(\"base64\");\n}\n\n/** Build the full resource list for all visible skills. */\nexport async function buildResourceList(\n  skills: SkillEntry[],\n  source: SkillSource = localSkillSource,\n): Promise<McpResource[]> {\n  const out: McpResource[] = [];\n  for (const skill of skills) {\n    const files = await source.listFiles(skill.slug).catch(() => [] as string[]);\n    for (const f of files) {\n      out.push({\n        uri: buildUri(skill.owner, skill.slug, f),\n        name: `${skill.slug}: ${f}`,\n        description: f === \"SKILL.md\" ? skill.description || undefined : undefined,\n        mimeType: mimeType(f),\n      });\n    }\n  }\n  return out;\n}\n\n/** Read a resource by URI. Returns null if the skill or file is not in `visibleSkills`. */\nexport async function readResource(\n  uri: string,\n  skills: SkillEntry[],\n  source: SkillSource = localSkillSource,\n): Promise<McpResourceContent | null> {\n  // parseUri validates slug + path (traversal, null bytes, absolute paths)\n  // BEFORE any source.readFile call \u2014 this applies to injected sources too.\n  let parsed: ParsedUri;\n  try {\n    parsed = parseUri(uri);\n  } catch {\n    return null;\n  }\n\n  const skill = skills.find(\n    (s) => s.slug === parsed.slug && ownerSegment(s.owner) === parsed.owner,\n  );\n  if (!skill) return null;\n\n  const data = await source.readFile(skill.slug, parsed.path);\n  if (data === null) return null;\n\n  const mime = mimeType(parsed.path);\n  const isText = mime.startsWith(\"text/\") || mime === \"application/json\"\n    || mime === \"application/yaml\" || mime === \"application/toml\";\n\n  if (isText) {\n    return { uri, mimeType: mime, text: sourceDataToText(data) };\n  }\n  return { uri, mimeType: mime, blob: sourceDataToBase64(data) };\n}\n", "/**\n * MCP tool and resource request handler.\n *\n * Tools (fixed, declarative \u2014 NOT one tool per skill):\n *   list_skills()           \u2192 kit manifest\n *   get_skill(slug)         \u2192 SKILL.md body + supporting-file resource list\n *   search_skills(query)    \u2192 keyword-matched subset of the manifest (name/description/slug)\n *\n * Resources: one per file in each skill bundle, URI skillet://{owner}/{slug}/{path}.\n *\n * Auth gate is applied by the caller before invoking any handler here.\n */\n\nimport { assertSafeSlug } from \"@skillet/core\";\nimport type {\n  McpResource,\n  McpResourceContent,\n  McpTool,\n  ToolResultContent,\n} from \"./protocol.js\";\nimport { buildResourceList, buildUri, readResource, sourceDataToText } from \"./resources.js\";\nimport { localSkillSource, type SkillEntry, type SkillSource } from \"./store.js\";\n\n/**\n * Slug refs may be owner-qualified (`owner/slug`) when a source disambiguates\n * a cross-owner slug collision (registry mcp/source.ts). Validate each\n * segment under the same rules as a bare slug \u2014 segments can never be `.`,\n * `..`, or empty, so the ref stays traversal-safe for path-based sources too.\n */\nfunction assertSafeSlugRef(ref: string): void {\n  const segments = ref.split(\"/\");\n  if (segments.length > 2) {\n    throw new Error(`Unsafe skill slug rejected: \"${ref}\"`);\n  }\n  for (const segment of segments) assertSafeSlug(segment);\n}\n\n// \u2500\u2500 Tool definitions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const TOOLS: McpTool[] = [\n  {\n    name: \"list_skills\",\n    description:\n      \"List all skills available in this Skillet kit. Returns slug, name, description, version hash, and author for each skill.\",\n    inputSchema: { type: \"object\", properties: {}, required: [] },\n  },\n  {\n    name: \"get_skill\",\n    description:\n      \"Get a skill's full SKILL.md content and the list of its supporting-file resource URIs.\",\n    inputSchema: {\n      type: \"object\",\n      properties: {\n        slug: { type: \"string\", description: \"The skill slug (e.g. festival-ops)\" },\n      },\n      required: [\"slug\"],\n    },\n  },\n  {\n    name: \"search_skills\",\n    description:\n      \"Search skills by keyword. Matches against skill name, description, and slug. Returns the same fields as list_skills.\",\n    inputSchema: {\n      type: \"object\",\n      properties: {\n        query: { type: \"string\", description: \"Search query string\" },\n      },\n      required: [\"query\"],\n    },\n  },\n];\n\n// \u2500\u2500 Tool call implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function callTool(\n  name: string,\n  args: unknown,\n  skills: SkillEntry[],\n  source: SkillSource = localSkillSource,\n): Promise<{ content: ToolResultContent[]; isError?: boolean }> {\n  switch (name) {\n    case \"list_skills\": {\n      const manifest = buildManifest(skills);\n      return {\n        content: [{ type: \"text\", text: JSON.stringify(manifest, null, 2) }],\n      };\n    }\n    case \"get_skill\": {\n      const slug = extractString(args, \"slug\");\n      assertSafeSlugRef(slug);\n      const skill = skills.find((s) => s.slug === slug);\n      if (!skill) {\n        return {\n          content: [{ type: \"text\", text: `Skill not found: ${slug}` }],\n          isError: true,\n        };\n      }\n      const body = await source.readFile(slug, \"SKILL.md\");\n      const files = await listSupportingFiles(skill, source);\n      const result = {\n        slug: skill.slug,\n        name: skill.name,\n        description: skill.description,\n        version_hash: skill.hash,\n        version_label: skill.versionLabel ?? null,\n        author: skill.owner ?? null,\n        skill_md: body === null ? null : sourceDataToText(body),\n        resources: files,\n      };\n      return {\n        content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n      };\n    }\n    case \"search_skills\": {\n      const query = extractString(args, \"query\").toLowerCase();\n      const matched = skills.filter(\n        (s) =>\n          s.name.toLowerCase().includes(query) ||\n          (s.description ?? \"\").toLowerCase().includes(query) ||\n          s.slug.toLowerCase().includes(query),\n      );\n      return {\n        content: [{ type: \"text\", text: JSON.stringify(buildManifest(matched), null, 2) }],\n      };\n    }\n    default:\n      return {\n        content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n        isError: true,\n      };\n  }\n}\n\n// \u2500\u2500 Deep-research alias tools (opt-in; hosted transport only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// ChatGPT deep-research mode calls a fixed `search`/`fetch` tool pair (OpenAI\n// deep-research MCP contract). These aliases expose the same kit data through\n// that contract. They are ONLY advertised/callable when\n// `McpServerOptions.deepResearchAliases` is set \u2014 the local stdio/loopback\n// paths never set it, so the local tool surface stays exactly the three core\n// tools above (R15).\n\nexport const DEEP_RESEARCH_TOOLS: McpTool[] = [\n  {\n    name: \"search\",\n    description:\n      \"Alias of search_skills for OpenAI deep-research clients. Search skills by keyword (name, description, or slug). Returns { results: [{ id, title, url }] }. Pass a result id to fetch to retrieve the full skill document.\",\n    inputSchema: {\n      type: \"object\",\n      properties: {\n        query: { type: \"string\", description: \"Search query string\" },\n      },\n      required: [\"query\"],\n    },\n  },\n  {\n    name: \"fetch\",\n    description:\n      \"Alias of get_skill for OpenAI deep-research clients. Fetch the full document for a skill id returned by search. Returns { id, title, text, url, metadata } where text is the SKILL.md body.\",\n    inputSchema: {\n      type: \"object\",\n      properties: {\n        id: { type: \"string\", description: \"Skill id in owner/slug form (as returned by search)\" },\n      },\n      required: [\"id\"],\n    },\n  },\n];\n\nexport function isDeepResearchTool(name: string): name is \"search\" | \"fetch\" {\n  return name === \"search\" || name === \"fetch\";\n}\n\nexport type DeepResearchOutcome =\n  | { ok: true; content: ToolResultContent[] }\n  | { ok: false; message: string };\n\nexport async function callDeepResearchTool(\n  name: \"search\" | \"fetch\",\n  args: unknown,\n  skills: SkillEntry[],\n  source: SkillSource = localSkillSource,\n): Promise<DeepResearchOutcome> {\n  if (name === \"search\") {\n    const query = extractString(args, \"query\").toLowerCase();\n    // Same matcher as search_skills: name, description, or slug substring.\n    const matched = skills.filter(\n      (s) =>\n        s.name.toLowerCase().includes(query) ||\n        (s.description ?? \"\").toLowerCase().includes(query) ||\n        s.slug.toLowerCase().includes(query),\n    );\n    const results = matched.map((s) => ({\n      id: skillId(s),\n      title: s.name,\n      url: skillPageUrl(s),\n    }));\n    return {\n      ok: true,\n      content: [{ type: \"text\", text: JSON.stringify({ results }, null, 2) }],\n    };\n  }\n\n  const id = extractString(args, \"id\");\n  const skill = skills.find((s) => skillId(s) === id);\n  if (!skill) {\n    return { ok: false, message: `Unknown skill id: ${id}` };\n  }\n  assertSafeSlugRef(skill.slug);\n  const body = await source.readFile(skill.slug, \"SKILL.md\");\n  const doc = {\n    id,\n    title: skill.name,\n    text: body === null ? \"\" : sourceDataToText(body),\n    url: skillPageUrl(skill),\n    metadata: {\n      slug: skill.slug,\n      description: skill.description,\n      version_hash: skill.hash,\n      version_label: skill.versionLabel ?? null,\n      author: skill.owner ?? null,\n    },\n  };\n  return {\n    ok: true,\n    content: [{ type: \"text\", text: JSON.stringify(doc, null, 2) }],\n  };\n}\n\n/** `owner/slug` document id; `_local` owner fallback matches resource URIs. */\nfunction skillId(s: SkillEntry): string {\n  return `${s.owner ?? \"_local\"}/${s.slug}`;\n}\n\n/** Web base for skill page URLs \u2014 same env + default as the CLI's webBaseUrl. */\nfunction webBaseUrl(): string {\n  return (process.env[\"SKILLET_WEB_URL\"] ?? \"https://skillet.md\").replace(/\\/+$/, \"\");\n}\n\nfunction skillPageUrl(s: SkillEntry): string {\n  return `${webBaseUrl()}/${s.owner ?? \"_local\"}/${s.slug}`;\n}\n\n// \u2500\u2500 Resource handlers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport async function listResources(\n  skills: SkillEntry[],\n  source: SkillSource = localSkillSource,\n): Promise<McpResource[]> {\n  return buildResourceList(skills, source);\n}\n\nexport async function handleReadResource(\n  uri: string,\n  skills: SkillEntry[],\n  source: SkillSource = localSkillSource,\n): Promise<McpResourceContent | null> {\n  return readResource(uri, skills, source);\n}\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction buildManifest(\n  skills: SkillEntry[],\n): Array<{\n  slug: string;\n  name: string;\n  description: string;\n  version_hash: string;\n  version_label: string | null;\n  author: string | null;\n}> {\n  return skills.map((s) => ({\n    slug: s.slug,\n    name: s.name,\n    description: s.description,\n    version_hash: s.hash,\n    version_label: s.versionLabel ?? null,\n    author: s.owner ?? null,\n  }));\n}\n\nasync function listSupportingFiles(skill: SkillEntry, source: SkillSource): Promise<string[]> {\n  const files = await source.listFiles(skill.slug).catch(() => [] as string[]);\n  return files.map((f) => buildUri(skill.owner, skill.slug, f));\n}\n\nfunction extractString(args: unknown, key: string): string {\n  if (args === null || typeof args !== \"object\") {\n    throw new Error(`Missing required parameter: ${key}`);\n  }\n  const val = (args as Record<string, unknown>)[key];\n  if (typeof val !== \"string\" || val.length === 0) {\n    throw new Error(`Parameter \"${key}\" must be a non-empty string`);\n  }\n  return val;\n}\n", "/**\n * Per-session loopback bearer for the MCP HTTP transport.\n *\n * Minted on server start and written to ~/.skillet/mcp-loopback-token (mode 0600).\n * Loopback HTTP clients must present this token (prefix `skillet_loop_`) or a\n * registry-validated skillet bearer \u2014 prefix-only skillet_* strings are not\n * accepted.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { SKILLET_DIR } from \"@skillet/core\";\n\nexport const LOOPBACK_TOKEN_PREFIX = \"skillet_loop_\";\nconst TOKEN_FILE = \"mcp-loopback-token\";\n\nexport function loopbackTokenPath(): string {\n  return join(SKILLET_DIR, TOKEN_FILE);\n}\n\n/** True when `token` is our loopback-only bearer shape. */\nexport function isLoopbackSecretToken(token: string): boolean {\n  return token.startsWith(LOOPBACK_TOKEN_PREFIX);\n}\n\n/** Mint (or reuse) the loopback secret for this MCP HTTP session. */\nexport async function ensureLoopbackToken(): Promise<string> {\n  const existing = await readLoopbackToken();\n  if (existing) return existing;\n\n  const token = LOOPBACK_TOKEN_PREFIX + randomBytes(24).toString(\"base64url\");\n  await mkdir(SKILLET_DIR, { recursive: true });\n  await writeFile(loopbackTokenPath(), `${token}\\n`, { mode: 0o600 });\n  return token;\n}\n\nexport async function readLoopbackToken(): Promise<string | null> {\n  try {\n    const raw = await readFile(loopbackTokenPath(), \"utf8\");\n    const token = raw.trim();\n    return isLoopbackSecretToken(token) ? token : null;\n  } catch {\n    return null;\n  }\n}\n", "/**\n * Auth enforcement for the Skillet MCP transport.\n *\n * Reuses the existing token/identity model verbatim (no new credential type):\n *   skillet_k_\u2026 \u2014 kit-key (headless, for automated clients)\n *   skillet_s_\u2026 \u2014 session token\n *   skillet_d_\u2026 \u2014 device token\n *\n * Visibility rule (mirrors the registry pull path, fail-closed):\n *   - Valid token \u2192 all skills in the local store are visible.\n *   - No token / unknown format \u2192 NOTHING visible (empty list).\n *     \"local\" source \u2260 public: locally-imported skills are the user's most\n *     private content and must not be exposed to unauthenticated clients.\n *\n * SECURITY SCOPE (loopback): The `skillet mcp` HTTP server default is\n * loopback-only (127.0.0.1/::1). Loopback HTTP requires a per-session\n * `skillet_loop_*` token or a registry-validated skillet bearer \u2014 prefix-only\n * skillet_* strings are rejected.\n *\n * SECURITY SCOPE (hosted / non-loopback): When the transport is started with\n * an explicit `hosted` option, bearer tokens are validated against the\n * registry token surface (GET /api/v1/sync/manifest) before any skill is\n * served. Results are cached per server instance; registry-unreachable \u2192 fail\n * closed. See `createRegistryValidator`.\n */\n\nimport { RegistryClient } from \"@skillet/core\";\nimport type { SkillEntry } from \"./store.js\";\nimport { isLoopbackSecretToken } from \"./loopback-token.js\";\n\nconst TOKEN_PREFIXES = [\"skillet_k_\", \"skillet_s_\", \"skillet_d_\"] as const;\n\n/** Loopback hostnames/IPs accepted by the HTTP transport. */\nexport const LOOPBACK_HOSTS = new Set([\"127.0.0.1\", \"::1\", \"localhost\"]);\n\n/** Return true when the token format is a recognised Skillet bearer token. */\nexport function isValidToken(token: string | null | undefined): boolean {\n  if (!token) return false;\n  return TOKEN_PREFIXES.some((pfx) => token.startsWith(pfx));\n}\n\n/**\n * Filter the kit's skills for what a client with the given token may see.\n *\n * Valid token \u2192 all skills.\n * No / invalid token \u2192 empty list (fail-closed; no unauthenticated read).\n */\nexport function visibleSkills(\n  skills: SkillEntry[],\n  token: string | null | undefined,\n): SkillEntry[] {\n  if (!isValidToken(token)) return [];\n  return skills;\n}\n\n/**\n * Extract a Bearer token from an HTTP Authorization header value.\n * Returns null if the header is absent or not a Bearer scheme.\n */\nexport function tokenFromHeader(authorization: string | null | undefined): string | null {\n  if (!authorization) return null;\n  const match = /^Bearer\\s+(\\S+)$/i.exec(authorization.trim());\n  return match ? match[1] : null;\n}\n\nexport interface AuthorizeBearerOptions {\n  /** Loopback-only secret minted at HTTP server start. */\n  loopbackSecret?: string | null;\n  registryValidator: RegistryValidator;\n}\n\n/**\n * Authorize a bearer for loopback or hosted HTTP transports.\n * Accepts the loopback secret or a registry-validated skillet token.\n */\nexport async function authorizeBearerToken(\n  token: string | null,\n  opts: AuthorizeBearerOptions,\n): Promise<boolean> {\n  if (!token) return false;\n  if (opts.loopbackSecret && token === opts.loopbackSecret) return true;\n  if (isLoopbackSecretToken(token)) return false;\n  if (!isValidToken(token)) return false;\n  return opts.registryValidator.validate(token);\n}\n\nexport { isLoopbackSecretToken };\n\n/** Opaque handle returned by `createRegistryValidator`. */\nexport interface RegistryValidator {\n  /**\n   * Returns true when the token is valid according to the registry, false\n   * otherwise (invalid token, revoked, or registry unreachable \u2192 fail closed).\n   * Results are cached for the lifetime of this validator instance.\n   */\n  validate(token: string): Promise<boolean>;\n}\n\nexport interface RegistryValidatorOptions {\n  /** Registry base URL used to validate bearer tokens. */\n  registryUrl: string;\n  /** Inject an alternate fetch impl for tests. Defaults to globalThis.fetch. */\n  fetchImpl?: typeof fetch;\n}\n\n/** TTL for a successful (valid) registry validation. Caps the token-revocation window. */\nconst TTL_VALID_MS = 5 * 60 * 1000; // 5 minutes\n\n/**\n * TTL for a failed validation. Lets transient registry outages recover without\n * permanently blocking a legitimate token for the server's lifetime.\n */\nconst TTL_INVALID_MS = 30 * 1000; // 30 seconds\n\ninterface CacheEntry {\n  valid: boolean;\n  expiresAt: number;\n}\n\n/**\n * Create a registry-backed token validator for the hosted MCP path.\n *\n * Calls GET /api/v1/sync/manifest with the bearer token to probe whether the\n * registry accepts it. Results are cached with TTLs: 5 min for valid tokens\n * (caps the revocation window), 30 s for failures (lets transient outages\n * recover). Registry unavailability (network error, 5xx) and any rejection\n * (401, 403) both return false \u2014 fail closed.\n *\n * Future: if the registry adds a dedicated lightweight auth-check endpoint\n * (e.g. GET /api/v1/auth/me), migrate the oracle call here to that endpoint\n * instead of getSyncManifest.\n */\nexport function createRegistryValidator(opts: RegistryValidatorOptions): RegistryValidator {\n  const cache = new Map<string, CacheEntry>();\n\n  return {\n    async validate(token: string): Promise<boolean> {\n      const entry = cache.get(token);\n      if (entry && Date.now() < entry.expiresAt) return entry.valid;\n\n      let valid: boolean;\n      try {\n        const client = new RegistryClient({\n          baseUrl: opts.registryUrl,\n          token,\n          fetchImpl: opts.fetchImpl,\n        });\n        await client.getSyncManifest();\n        valid = true;\n      } catch {\n        // Registry unreachable, 401, 403, or any other error \u2192 fail closed.\n        valid = false;\n      }\n\n      cache.set(token, {\n        valid,\n        expiresAt: Date.now() + (valid ? TTL_VALID_MS : TTL_INVALID_MS),\n      });\n      return valid;\n    },\n  };\n}\n", "/**\n * Skillet MCP server: JSON-RPC 2.0 request dispatcher.\n *\n * Handles:\n *   initialize          \u2192 server capabilities + info\n *   notifications/*     \u2192 no-op (acknowledged)\n *   ping                \u2192 pong\n *   tools/list          \u2192 TOOLS\n *   tools/call          \u2192 callTool()\n *   resources/list      \u2192 listResources()\n *   resources/read      \u2192 handleReadResource()\n */\n\nimport {\n  ERRC,\n  MCP_PROTOCOL_VERSION,\n  err,\n  isRequest,\n  ok,\n  type RpcIncoming,\n  type RpcResponse,\n} from \"./protocol.js\";\nimport {\n  callDeepResearchTool,\n  callTool,\n  DEEP_RESEARCH_TOOLS,\n  handleReadResource,\n  isDeepResearchTool,\n  listResources,\n  TOOLS,\n} from \"./handler.js\";\nimport { visibleSkills } from \"./auth.js\";\nimport { localSkillSource, type SkillEntry, type SkillSource } from \"./store.js\";\n\nconst SERVER_NAME = \"skillet-mcp\";\n/**\n * Fallback when the host doesn't inject its own version (see\n * McpServerOptions.serverVersion). The real number is passed in by whatever\n * ships the server \u2014 the CLI passes CLI_VERSION, the registry its deploy\n * version \u2014 so serverInfo tracks what's actually serving the client.\n */\nconst DEFAULT_SERVER_VERSION = \"0.1.0\";\n\nconst CAPABILITIES = {\n  tools: {},\n  resources: {},\n};\n\n/**\n * Advertised to clients on `initialize`. Read like a system prompt: it primes\n * the model before it calls any tool, so keep it short and action-oriented.\n */\nconst SERVER_INSTRUCTIONS =\n  \"This server exposes a Skillet kit: a curated set of skills (reusable instructions \" +\n  \"and reference files) the user has synced. Call `list_skills` to see what's available, \" +\n  \"`search_skills` to find one by keyword, then `get_skill` to load a skill's full SKILL.md \" +\n  \"and its supporting-file resource URIs before acting on it. Skills are read-only reference \" +\n  \"material \u2014 read a skill in full before following it.\";\n\nexport interface McpServerOptions {\n  /** Bearer token supplied by the connecting client (optional). */\n  token?: string | null;\n  /** HTTP transport already validated the bearer (loopback secret or registry). */\n  httpAuthorized?: boolean;\n  /** Where skills come from. Defaults to the local on-disk store. */\n  source?: SkillSource;\n  /**\n   * Advertise the ChatGPT deep-research `search`/`fetch` alias tools.\n   * Hosted transport only \u2014 never set on the local stdio/loopback paths, so\n   * the local tool surface stays exactly the three core tools (R15).\n   */\n  deepResearchAliases?: boolean;\n  /**\n   * Version string reported in `serverInfo` on `initialize`. The host injects\n   * its own release version (CLI \u2192 CLI_VERSION, registry \u2192 deploy version) so\n   * clients see what's actually serving them. Falls back to a static default.\n   */\n  serverVersion?: string;\n}\n\n/**\n * Handle a single JSON-RPC message and return the response (if any).\n * Returns null for valid notifications (no response needed).\n */\nexport async function handleMessage(\n  msg: RpcIncoming,\n  opts: McpServerOptions = {},\n): Promise<RpcResponse | null> {\n  if (!isRequest(msg)) {\n    // Notification: no response\n    return null;\n  }\n\n  const { id, method, params } = msg;\n  const source = opts.source ?? localSkillSource;\n\n  try {\n    switch (method) {\n      case \"initialize\": {\n        const clientVersion =\n          (params as { protocolVersion?: string } | null)?.protocolVersion ??\n          MCP_PROTOCOL_VERSION;\n        void clientVersion; // accepted regardless of version for compatibility\n        return ok(id, {\n          protocolVersion: MCP_PROTOCOL_VERSION,\n          capabilities: CAPABILITIES,\n          serverInfo: {\n            name: SERVER_NAME,\n            version: opts.serverVersion ?? DEFAULT_SERVER_VERSION,\n          },\n          instructions: SERVER_INSTRUCTIONS,\n        });\n      }\n\n      case \"ping\":\n        return ok(id, {});\n\n      case \"tools/list\":\n        return ok(id, {\n          tools: opts.deepResearchAliases ? [...TOOLS, ...DEEP_RESEARCH_TOOLS] : TOOLS,\n        });\n\n      case \"tools/call\": {\n        const p = params as { name?: string; arguments?: unknown } | null;\n        if (!p?.name) {\n          return err(id, ERRC.INVALID_PARAMS, \"tools/call requires `name`\");\n        }\n        const skills = await loadVisibleSkills(source, opts.token, opts.httpAuthorized);\n        if (opts.deepResearchAliases && isDeepResearchTool(p.name)) {\n          const outcome = await callDeepResearchTool(p.name, p.arguments ?? {}, skills, source);\n          if (!outcome.ok) {\n            return err(id, ERRC.INVALID_PARAMS, outcome.message);\n          }\n          return ok(id, { content: outcome.content });\n        }\n        const result = await callTool(p.name, p.arguments ?? {}, skills, source);\n        return ok(id, result);\n      }\n\n      case \"resources/list\": {\n        const skills = await loadVisibleSkills(source, opts.token, opts.httpAuthorized);\n        const resources = await listResources(skills, source);\n        return ok(id, { resources });\n      }\n\n      case \"resources/read\": {\n        const p = params as { uri?: string } | null;\n        if (!p?.uri) {\n          return err(id, ERRC.INVALID_PARAMS, \"resources/read requires `uri`\");\n        }\n        const skills = await loadVisibleSkills(source, opts.token, opts.httpAuthorized);\n        const content = await handleReadResource(p.uri, skills, source);\n        if (!content) {\n          return err(id, ERRC.INVALID_PARAMS, `Resource not found: ${p.uri}`);\n        }\n        return ok(id, { contents: [content] });\n      }\n\n      default:\n        return err(id, ERRC.METHOD_NOT_FOUND, `Unknown method: ${method}`);\n    }\n  } catch (e) {\n    const message = e instanceof Error ? e.message : \"Internal error\";\n    return err(id, ERRC.INTERNAL_ERROR, message);\n  }\n}\n\nasync function loadVisibleSkills(\n  source: SkillSource,\n  token: string | null | undefined,\n  httpAuthorized?: boolean,\n): Promise<SkillEntry[]> {\n  const all = await source.listEntries();\n  if (httpAuthorized) return all;\n  return visibleSkills(all, token);\n}\n\n/**\n * Parse raw JSON text into an RpcIncoming message.\n * Throws a structured error if parsing fails or the shape is invalid.\n */\nexport function parseMessage(raw: string): RpcIncoming {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(raw);\n  } catch {\n    throw Object.assign(new Error(\"Parse error\"), { jsonrpcCode: ERRC.PARSE_ERROR });\n  }\n  if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n    throw Object.assign(new Error(\"Invalid Request\"), { jsonrpcCode: ERRC.INVALID_REQUEST });\n  }\n  const msg = parsed as Record<string, unknown>;\n  if (msg[\"jsonrpc\"] !== \"2.0\" || typeof msg[\"method\"] !== \"string\") {\n    throw Object.assign(new Error(\"Invalid Request\"), { jsonrpcCode: ERRC.INVALID_REQUEST });\n  }\n  return parsed as RpcIncoming;\n}\n", "/**\n * Skillet MCP stdio transport.\n *\n * Reads newline-delimited JSON-RPC messages from stdin, writes responses to\n * stdout. Errors and diagnostic output go to stderr so stdout remains a clean\n * JSON stream for MCP clients.\n *\n * Each line on stdin is one complete JSON-RPC message. Empty lines are skipped.\n * The transport runs until stdin closes (EOF), then exits cleanly.\n */\n\nimport { createInterface } from \"node:readline\";\nimport { err, ERRC, type RpcResponse } from \"../protocol.js\";\nimport { handleMessage, parseMessage } from \"../server.js\";\n\nexport interface StdioTransportOptions {\n  /** Pre-authenticated bearer token (e.g. passed via --token CLI flag). */\n  token?: string | null;\n  /** Readable stream (defaults to process.stdin). */\n  input?: NodeJS.ReadableStream;\n  /** Writable stream (defaults to process.stdout). */\n  output?: NodeJS.WritableStream;\n  /** Version reported in serverInfo (the host's release version). */\n  serverVersion?: string;\n}\n\n/** Write a single JSON-RPC response to the output stream as a newline-terminated line. */\nfunction writeLine(out: NodeJS.WritableStream, response: RpcResponse): void {\n  out.write(JSON.stringify(response) + \"\\n\");\n}\n\n/** Start the stdio MCP transport and block until stdin closes. */\nexport async function runStdio(opts: StdioTransportOptions = {}): Promise<void> {\n  const input = opts.input ?? process.stdin;\n  const output = opts.output ?? process.stdout;\n  const token = opts.token ?? null;\n  const serverVersion = opts.serverVersion;\n\n  const rl = createInterface({ input, terminal: false });\n\n  await new Promise<void>((resolve) => {\n    rl.on(\"line\", async (line) => {\n      const trimmed = line.trim();\n      if (!trimmed) return;\n\n      let msg;\n      try {\n        msg = parseMessage(trimmed);\n      } catch (e) {\n        const code = (e as { jsonrpcCode?: number }).jsonrpcCode ?? ERRC.PARSE_ERROR;\n        writeLine(output, err(null, code, (e as Error).message));\n        return;\n      }\n\n      const response = await handleMessage(msg, { token, serverVersion }).catch((e: unknown) =>\n        err(\n          \"id\" in msg ? (msg as { id: string | number }).id : null,\n          ERRC.INTERNAL_ERROR,\n          e instanceof Error ? e.message : \"Internal error\",\n        ),\n      );\n\n      if (response !== null) {\n        writeLine(output, response);\n      }\n    });\n\n    rl.on(\"close\", () => resolve());\n    rl.on(\"error\", (e) => {\n      process.stderr.write(`Skillet MCP stdio error: ${e.message}\\n`);\n      resolve();\n    });\n  });\n}\n", "/**\n * Skillet MCP HTTP transport (\"Streamable HTTP\", MCP spec 2025-03-26).\n *\n * Client \u2192 Server:  POST /  with Content-Type: application/json\n *                   Body: single JSON-RPC 2.0 message (request or notification)\n * Server \u2192 Client:  200 application/json for request responses\n *                   202 (no body) for notifications\n *                   4xx for protocol errors\n *\n * Auth:\n *   Loopback mode (default): per-session `skillet_loop_*` token or a\n *   registry-validated skillet bearer. Prefix-only tokens are rejected.\n *\n *   Hosted mode (`opts.hosted` present): bearer token is validated against the\n *   registry token surface before any response is sent. Invalid or missing\n *   tokens \u2192 401. Registry unreachable \u2192 401 (fail closed). Results are\n *   cached per server instance. Only explicitly configured origins are\n *   reflected in CORS; no wildcard.\n *\n * Security scope:\n *   Loopback: only loopback Origins are reflected in CORS. Host header\n *   validated against the loopback allowlist on every request.\n *   Hosted: allowedOrigins is the CORS allowlist (CLIENT origins only). The\n *   Host-header DNS-rebinding guard validates the SERVER's own hostname against\n *   `serverHosts` (plus loopback). These are distinct concepts and must not be\n *   conflated; `serverHosts` falls back to allowedOrigins hostnames for\n *   back-compat when unset.\n */\n\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { err, ERRC, type RpcResponse } from \"../protocol.js\";\nimport { handleMessage, parseMessage } from \"../server.js\";\nimport {\n  tokenFromHeader,\n  isValidToken,\n  LOOPBACK_HOSTS,\n  createRegistryValidator,\n  authorizeBearerToken,\n  type RegistryValidator,\n} from \"../auth.js\";\nimport { ensureLoopbackToken } from \"../loopback-token.js\";\n\nconst DEFAULT_REGISTRY_URL =\n  process.env[\"SKILLET_REGISTRY_URL\"] ??\n  process.env[\"SKILLET_REGISTRY\"] ??\n  \"http://127.0.0.1:3481\";\n\n/** Origins that are safe to reflect for browser-based loopback MCP clients. */\nconst LOOPBACK_ORIGIN_RE = /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d+)?$/;\n\n/**\n * Options required to enable non-loopback (hosted/ChatGPT-style) mode.\n * All fields are mandatory to prevent accidental misconfiguration.\n */\nexport interface HostedTransportOptions {\n  /** Registry base URL used to validate bearer tokens, e.g. `https://registry.skillet.md`. */\n  registryUrl: string;\n  /**\n   * Explicit allowlist of non-loopback origins permitted in CORS. No wildcards.\n   * These are the CLIENT/browser origins that may call this server cross-origin.\n   * Example: `[\"https://chatgpt.com\", \"https://claude.ai\"]`\n   *\n   * NOTE: this is used ONLY for CORS. It must NOT be used to validate the\n   * incoming `Host` header \u2014 see `serverHosts`.\n   */\n  allowedOrigins: readonly string[];\n  /**\n   * Allowlist of THIS server's own public hostname(s), used to validate the\n   * incoming `Host` header (anti-DNS-rebinding guard). Loopback hosts are\n   * always accepted in addition to these. Hostnames only, no scheme or port.\n   * Example: `[\"mcp.skillet.md\"]`\n   *\n   * This is a distinct concept from `allowedOrigins`: the `Host` header is the\n   * server's own public hostname, which is unrelated to which client origins\n   * are permitted via CORS.\n   *\n   * BACK-COMPAT: when omitted, the Host-header allowlist falls back to the\n   * hostnames derived from `allowedOrigins` (the legacy behavior), so existing\n   * callers keep working without change.\n   */\n  serverHosts?: readonly string[];\n  /** Inject an alternate fetch impl for tests. Defaults to globalThis.fetch. */\n  fetchImpl?: typeof fetch;\n}\n\nfunction corsHeaders(\n  origin: string | undefined,\n  allowedHostedOrigins?: readonly string[],\n): Record<string, string> {\n  if (!origin) return {};\n  const isLoopback = LOOPBACK_ORIGIN_RE.test(origin);\n  const isAllowedHosted = !isLoopback && (allowedHostedOrigins?.includes(origin) ?? false);\n  if (isLoopback || isAllowedHosted) {\n    return {\n      \"Access-Control-Allow-Origin\": origin,\n      \"Vary\": \"Origin\",\n      \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n      \"Access-Control-Allow-Headers\": \"Content-Type, Authorization\",\n    };\n  }\n  return {};\n}\n\nexport interface HttpTransportOptions {\n  /** TCP port to listen on. */\n  port: number;\n  /** Hostname / bind address. Defaults to `127.0.0.1`. Non-loopback only allowed with `hosted`. */\n  host?: string;\n  /** Inject an alternate fetch impl for loopback registry validation (tests). */\n  fetchImpl?: typeof fetch;\n  /**\n   * When set, enables non-loopback (hosted/ChatGPT-style) mode.\n   * Bearer tokens are validated against the registry before any skill is served.\n   * Requires sign-off before enabling in production.\n   */\n  hosted?: HostedTransportOptions;\n  /** Version reported in serverInfo (the host's release version). */\n  serverVersion?: string;\n}\n\n/** Max JSON-RPC request body the HTTP transport will buffer (1 MB). */\nexport const MAX_BODY_BYTES = 1024 * 1024;\n\nexport class BodyTooLargeError extends Error {}\n\nexport function readBody(req: IncomingMessage, maxBytes = MAX_BODY_BYTES): Promise<string> {\n  return new Promise((resolve, reject) => {\n    const chunks: Buffer[] = [];\n    let size = 0;\n    req.on(\"data\", (chunk: Buffer) => {\n      size += chunk.length;\n      // Abort mid-stream so a lying/absent content-length can't force an\n      // unbounded buffer (deepsec MEDIUM resource-exhaustion).\n      if (size > maxBytes) {\n        reject(new BodyTooLargeError(\"request body too large\"));\n        req.destroy();\n        return;\n      }\n      chunks.push(chunk);\n    });\n    req.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n    req.on(\"error\", reject);\n  });\n}\n\n/** Extract just the hostname (no port) from an HTTP Host header value. */\nfunction hostFromHeader(hostHeader: string | undefined): string | null {\n  if (!hostHeader) return null;\n  // IPv6: [::1] or [::1]:port\n  const ipv6 = /^\\[([^\\]]+)\\](?::\\d+)?$/.exec(hostHeader);\n  if (ipv6) return ipv6[1];\n  // hostname or IPv4: host or host:port\n  return hostHeader.split(\":\")[0] ?? null;\n}\n\n/** Extract hostnames from a list of full origin strings for Host-header validation. */\nfunction hostsFromOrigins(origins: readonly string[]): Set<string> {\n  const hosts = new Set<string>();\n  for (const o of origins) {\n    try {\n      hosts.add(new URL(o).hostname);\n    } catch {\n      // ignore malformed origin entries\n    }\n  }\n  return hosts;\n}\n\nfunction sendJson(\n  res: ServerResponse,\n  status: number,\n  body: unknown,\n  extraHeaders?: Record<string, string>,\n): void {\n  const payload = JSON.stringify(body);\n  res.writeHead(status, {\n    ...extraHeaders,\n    \"Content-Type\": \"application/json\",\n    \"Content-Length\": Buffer.byteLength(payload),\n  });\n  res.end(payload);\n}\n\nfunction sendError(\n  res: ServerResponse,\n  status: number,\n  response: RpcResponse,\n  extraHeaders?: Record<string, string>,\n): void {\n  sendJson(res, status, response, extraHeaders);\n}\n\ninterface ResolvedLoopbackConfig {\n  loopbackSecret: string;\n  registryValidator: RegistryValidator;\n}\n\ninterface ResolvedHostedConfig {\n  options: HostedTransportOptions;\n  validator: RegistryValidator;\n  allowedHosts: Set<string>;\n}\n\nasync function handleRequest(\n  req: IncomingMessage,\n  res: ServerResponse,\n  hosted: ResolvedHostedConfig | null,\n  loopback: ResolvedLoopbackConfig | null,\n  serverVersion: string | undefined,\n): Promise<void> {\n  // DNS-rebinding guard: validate Host against the loopback allowlist (and\n  // the configured hosted-origin hostnames when in hosted mode).\n  const host = hostFromHeader(req.headers.host);\n  const validHost =\n    host &&\n    (LOOPBACK_HOSTS.has(host) || (hosted?.allowedHosts.has(host) ?? false));\n  if (!validHost) {\n    res.writeHead(421, { \"Content-Type\": \"text/plain\" });\n    res.end(\"Misdirected Request: Host not in allowlist\");\n    return;\n  }\n\n  const origin = req.headers.origin as string | undefined;\n  const cors = corsHeaders(origin, hosted?.options.allowedOrigins);\n\n  // Preflight\n  if (req.method === \"OPTIONS\") {\n    res.writeHead(204, cors);\n    res.end();\n    return;\n  }\n\n  if (req.method !== \"POST\") {\n    res.writeHead(405, { ...cors, Allow: \"POST, OPTIONS\" });\n    res.end();\n    return;\n  }\n\n  // Reject oversized bodies before buffering and before auth, so an\n  // unauthenticated caller can't force a large allocation (deepsec MEDIUM).\n  const declaredLen = Number(req.headers[\"content-length\"] ?? \"\");\n  if (Number.isFinite(declaredLen) && declaredLen > MAX_BODY_BYTES) {\n    res.writeHead(413, { ...cors, \"Content-Type\": \"application/json\" });\n    res.end(JSON.stringify({ error: \"Payload Too Large\" }));\n    return;\n  }\n  let body: string;\n  try {\n    body = await readBody(req);\n  } catch (e) {\n    if (e instanceof BodyTooLargeError) {\n      res.writeHead(413, { ...cors, \"Content-Type\": \"application/json\" });\n      res.end(JSON.stringify({ error: \"Payload Too Large\" }));\n      return;\n    }\n    body = \"\";\n  }\n  const token = tokenFromHeader(req.headers.authorization ?? null);\n\n  if (hosted) {\n    if (!token || !isValidToken(token) || !(await hosted.validator.validate(token))) {\n      res.writeHead(401, {\n        ...cors,\n        \"Content-Type\": \"application/json\",\n        \"WWW-Authenticate\": \"Bearer\",\n      });\n      res.end(JSON.stringify({ error: \"Unauthorized\" }));\n      return;\n    }\n  } else if (loopback) {\n    const ok = await authorizeBearerToken(token, {\n      loopbackSecret: loopback.loopbackSecret,\n      registryValidator: loopback.registryValidator,\n    });\n    if (!ok) {\n      res.writeHead(401, {\n        ...cors,\n        \"Content-Type\": \"application/json\",\n        \"WWW-Authenticate\": \"Bearer\",\n      });\n      res.end(JSON.stringify({ error: \"Unauthorized\" }));\n      return;\n    }\n  }\n\n  let msg;\n  try {\n    msg = parseMessage(body);\n  } catch (e) {\n    const code = (e as { jsonrpcCode?: number }).jsonrpcCode ?? ERRC.PARSE_ERROR;\n    sendError(res, 400, err(null, code, (e as Error).message), cors);\n    return;\n  }\n\n  const response = await handleMessage(msg, {\n    token,\n    httpAuthorized: hosted !== null || loopback !== null,\n    serverVersion,\n  }).catch((e: unknown) =>\n    err(\n      \"id\" in msg ? (msg as { id: string | number }).id : null,\n      ERRC.INTERNAL_ERROR,\n      e instanceof Error ? e.message : \"Internal error\",\n    ),\n  );\n\n  if (response === null) {\n    // Notification acknowledged\n    res.writeHead(202, cors);\n    res.end();\n    return;\n  }\n\n  sendJson(res, 200, response, cors);\n}\n\nexport interface HttpTransportHandle {\n  stop: () => Promise<void>;\n  /** Loopback-only bearer required on every HTTP request (also written to ~/.skillet). */\n  loopbackToken?: string;\n}\n\n/**\n * Start the HTTP MCP transport. Returns a cleanup function that stops the server.\n *\n * By default (no `hosted` option), only loopback bind addresses are accepted\n * (127.0.0.1, ::1, localhost). Passing a non-loopback host without `hosted`\n * is a programming error and throws immediately.\n *\n * When `hosted` is set, non-loopback binds are permitted. Every request must\n * carry a bearer token that validates against the configured registry URL.\n * CORS is restricted to `hosted.allowedOrigins` only \u2014 no wildcard.\n */\nexport function startHttpTransport(opts: HttpTransportOptions): Promise<HttpTransportHandle> {\n  const host = opts.host ?? \"127.0.0.1\";\n\n  if (!opts.hosted && !LOOPBACK_HOSTS.has(host)) {\n    return Promise.reject(\n      new Error(\n        `Skillet MCP HTTP transport is loopback-only (v1). ` +\n        `\"${host}\" is not an allowed bind address. ` +\n        `Use 127.0.0.1, ::1, or localhost, or pass the \\`hosted\\` option to enable non-loopback mode.`,\n      ),\n    );\n  }\n\n  const hostedConfig: ResolvedHostedConfig | null = opts.hosted\n    ? {\n        options: opts.hosted,\n        validator: createRegistryValidator({\n          registryUrl: opts.hosted.registryUrl,\n          fetchImpl: opts.hosted.fetchImpl,\n        }),\n        // Host-header (anti-DNS-rebinding) allowlist = the server's OWN public\n        // hostname(s). When `serverHosts` is set, use it. Otherwise fall back to\n        // hostnames derived from `allowedOrigins` to preserve legacy behavior.\n        allowedHosts: opts.hosted.serverHosts\n          ? new Set(opts.hosted.serverHosts)\n          : hostsFromOrigins(opts.hosted.allowedOrigins),\n      }\n    : null;\n\n  const loopbackPromise = hostedConfig\n    ? Promise.resolve(null as ResolvedLoopbackConfig | null)\n    : ensureLoopbackToken().then((loopbackSecret) => ({\n        loopbackSecret,\n        registryValidator: createRegistryValidator({\n          registryUrl: DEFAULT_REGISTRY_URL,\n          fetchImpl: opts.fetchImpl,\n        }),\n      }));\n\n  return loopbackPromise.then(\n    (loopbackConfig) =>\n      new Promise((resolve, reject) => {\n        const server = createServer((req, res) => {\n          handleRequest(req, res, hostedConfig, loopbackConfig, opts.serverVersion).catch((e: unknown) => {\n            process.stderr.write(\n              `Skillet MCP HTTP error: ${e instanceof Error ? e.message : String(e)}\\n`,\n            );\n            if (!res.headersSent) {\n              sendJson(res, 500, err(null, ERRC.INTERNAL_ERROR, \"Internal server error\"));\n            }\n          });\n        });\n\n        server.on(\"error\", (e) => {\n          process.stderr.write(`Skillet MCP server error: ${e.message}\\n`);\n          reject(e);\n        });\n\n        server.listen(opts.port, host, () => {\n          const loopbackToken = loopbackConfig?.loopbackSecret;\n          // Never print the bearer itself \u2014 it would land in terminal/service\n          // logs as a reusable local credential (deepsec MEDIUM secret-in-log).\n          // It is returned to programmatic callers and saved to the token file.\n          process.stderr.write(\n            `Skillet MCP server listening on http://${host}:${opts.port}` +\n              (opts.hosted ? \" (hosted mode \u2014 registry-validated auth)\" : \"\") +\n              (loopbackToken\n                ? `\\n  Loopback bearer token saved to ~/.skillet/mcp-loopback-token\\n`\n                : \"\") +\n              \"\\n\",\n          );\n          resolve({\n            loopbackToken,\n            stop: () =>\n              new Promise<void>((res, rej) => server.close((e) => (e ? rej(e) : res()))),\n          });\n        });\n      }),\n  );\n}\n", "/**\n * @skillet/mcp \u2014 Skillet MCP server transport.\n *\n * Exposes kit skills to any MCP-capable client (Claude Desktop, ChatGPT,\n * Cursor, etc.) via the Model Context Protocol (MCP, spec 2025-03-26).\n *\n * The server is a read-only consumer of the canonical store (~/.skillet/skills/).\n * It never re-implements registry pull, signature verification, scan, or\n * the trust gate \u2014 it only serves what sync already vetted.\n */\n\nexport { handleMessage, parseMessage, type McpServerOptions } from \"./server.js\";\nexport { runStdio, type StdioTransportOptions } from \"./transport/stdio.js\";\nexport { startHttpTransport, type HttpTransportOptions, type HttpTransportHandle, type HostedTransportOptions } from \"./transport/http.js\";\nexport { isValidToken, tokenFromHeader, visibleSkills, createRegistryValidator, authorizeBearerToken, isLoopbackSecretToken, type RegistryValidator, type RegistryValidatorOptions } from \"./auth.js\";\nexport { ensureLoopbackToken, readLoopbackToken, loopbackTokenPath } from \"./loopback-token.js\";\nexport { buildUri, parseUri, type ParsedUri } from \"./resources.js\";\nexport { TOOLS, DEEP_RESEARCH_TOOLS } from \"./handler.js\";\nexport { localSkillSource, type SkillSource, type SkillEntry } from \"./store.js\";\n", "import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n  program,\n  createCommand,\n  createArgument,\n  createOption,\n  CommanderError,\n  InvalidArgumentError,\n  InvalidOptionArgumentError, // deprecated old name\n  Command,\n  Argument,\n  Option,\n  Help,\n} = commander;\n", "import { Command, CommanderError } from \"commander\";\nimport {\n  readState,\n  loadRegistryBearer,\n  readActiveDeviceFile,\n  discoverExistingSkills,\n  flushEvents,\n} from \"@skillet/core\";\nimport { formatSkilletHelp } from \"./help-format.js\";\nimport { ok, fail, bold, dim, cyan } from \"./cli-colors.js\";\nimport { pairInteractively, runConnectedSync, detectedAgentsPhrase } from \"./connected-sync.js\";\nimport { runHomeMenu } from \"./home-menu.js\";\nimport { launchBanner } from \"./brand.js\";\nimport { printRenderedError } from \"./render-error.js\";\nimport { writeJsonError } from \"./json-output.js\";\nimport { ALL_ADAPTERS, CLI_VERSION, countUserSkills } from \"./cli-context.js\";\nimport { webBaseUrl } from \"./cli-command-tier.js\";\nimport { registerAllCommands } from \"./commands/register-all.js\";\nimport { runDiscovery } from \"./commands/import-cmd.js\";\nimport { shouldRunOnboardingWizard } from \"./cli-routing.js\";\n\nfunction settingsPageUrl(): string {\n  return `${webBaseUrl()}/settings`;\n}\n\n/**\n * First-run wizard: sign in on the web, connect with a pair code, then sync\n * and optionally import skills already on this machine.\n *\n * Pairing is the gate \u2014 sync and discovery run only once this machine is\n * paired to an account. With no pair code the wizard exits cleanly (code 0)\n * with `skillet connect` guidance instead of holding the terminal.\n */\nasync function runOnboardingWizard(): Promise<void> {\n  const bearer = await loadRegistryBearer();\n  // Every bare run opens with the face and an info column, Claude Code style.\n  // Unpaired runs carry the tagline; paired runs say what this machine has.\n  const nameLine = bold(\"Skillet\") + \" \" + dim(`v${CLI_VERSION}`);\n  if (bearer.kind === \"none\") {\n    console.log(\"\\n\" + launchBanner([nameLine, \"your skills, everywhere.\"]));\n    // One step, not two: signing in and grabbing a pair code happen at the\n    // same URL, and the code gets pasted right here.\n    console.log(\"\");\n    console.log(`  Connect this machine to use your skills ${await detectedAgentsPhrase()}.`);\n    console.log(dim(\"  Sign in and get a pair code at \") + cyan(settingsPageUrl()) + \"\\n\");\n\n    if (process.stdout.isTTY !== true) {\n      console.log(`  Then run \\`skillet connect <code>\\``);\n      // Deliberate exit, not an error: nothing syncs or imports unpaired.\n      return;\n    }\n    const result = await pairInteractively();\n    if (!result) {\n      console.log(`\\n  Run \\`skillet connect <code>\\` when you have a pair code from ${settingsPageUrl()}`);\n      return;\n    }\n    const who = result.handle ? `@${result.handle}` : \"your account\";\n    console.log(`\\n${ok(`Connected to ${who}`)}`);\n  } else {\n    // Info column mirrors Claude Code's: version, then what's here (skills\n    // and where they run), then which machine this is. All local reads \u2014\n    // the banner never waits on the network.\n    const state = await readState();\n    const total = countUserSkills(state);\n    const skillsLine =\n      total === 0\n        ? `no skills yet ${await detectedAgentsPhrase()}`\n        : `${total} skill${total === 1 ? \"\" : \"s\"} ${await detectedAgentsPhrase()}`;\n    const label = (await readActiveDeviceFile())?.label;\n    console.log(\n      \"\\n\" + launchBanner([nameLine, skillsLine, ...(label ? [dim(label)] : [])]),\n    );\n    // Interactive bare runs sync \u2014 \"open Skillet\" means your skills are\n    // current, same as launching the desktop app. Headless callers get no\n    // implicit work: a script should say what it means (`skillet sync`).\n    if (process.stdout.isTTY !== true) {\n      console.log(`  Run \\`skillet sync\\` to sync, or \\`skillet status --json\\` for state.`);\n      return;\n    }\n  }\n\n  // The menu right after carries pending review and /skillet teaching with\n  // the data on the options, so the sync path's own hint blocks stay quiet.\n  await runConnectedSync(true, { homeMenuFollows: true });\n\n  const stateAfter = await readState();\n  const kitEmpty = Object.keys(stateAfter.skills).length === 0;\n  if (kitEmpty) {\n    const report = await discoverExistingSkills(ALL_ADAPTERS);\n    if (report.scannedRuntimes.length > 0 && report.newSkills.length > 0) {\n      console.log(\"\\nOptional \u2014 Import skills you already use on this machine\\n\");\n      await runDiscovery({ assumeYes: false });\n    }\n  }\n\n  await runHomeMenu();\n}\n\nconst program = new Command();\n\nprogram\n  .name(\"skillet\")\n  .description(\"Your skills, everywhere.\")\n  .version(CLI_VERSION, \"-v, --version\", \"Show CLI version\");\n\nprogram.configureHelp({\n  formatHelp: formatSkilletHelp,\n  sortSubcommands: false,\n});\n\nregisterAllCommands(program);\n\nprogram.showHelpAfterError();\n\n// Do not use program.action() for the wizard \u2014 Commander runs the default action\n// before unknown-command handling, so typos like `skillet sghagsh` would start onboarding.\n\n// Drain buffered activity before exit. The timer-based flush in metrics can race\n// a fast process exit, so we await an explicit flush after the command resolves,\n// with a `beforeExit` backstop for commands that set process.exitCode and return.\n// (Hard exits via `exitWith` \u2192 `process.exit` can't be awaited; that's the one\n// unavoidable gap, and only failing commands take it.)\nvoid (async () => {\n  process.once(\"beforeExit\", () => {\n    void flushEvents();\n  });\n  try {\n    if (shouldRunOnboardingWizard(process.argv)) {\n      await runOnboardingWizard();\n    } else {\n      await program.parseAsync(process.argv);\n    }\n  } catch (err) {\n    // Last-resort net: a command without its own catch must never dump a\n    // stack trace at a person. One human line (control chars stripped,\n    // hashes shortened), the stack behind SKILLET_DEBUG=1 for us.\n    if (err instanceof CommanderError) throw err; // commander handles its own exits\n    // JSON callers (the tray among them) get a parseable envelope even from\n    // the last-resort net; humans get the rendered line.\n    if (process.argv.includes(\"--json\")) {\n      writeJsonError((err as Error).message || String(err) || \"unknown error\");\n    } else {\n      printRenderedError(err as Error, fail);\n    }\n    if (process.env[\"SKILLET_DEBUG\"] === \"1\" && err instanceof Error && err.stack) {\n      console.error(dim(err.stack));\n    } else {\n      console.error(dim(\"  Set SKILLET_DEBUG=1 for the full details.\"));\n    }\n    process.exitCode = 1;\n  } finally {\n    await flushEvents();\n  }\n})();\n", "// SKILLET_FORCE_COLOR is for transcript capture (the copy-review page), where\n// output is piped but should still show the real look.\nconst useColor = process.stdout.isTTY === true || process.env['SKILLET_FORCE_COLOR'] === '1';\n\nexport function cliColor(code: string, text: string): string {\n  if (!useColor) return text;\n  return `\\u001b[${code}m${text}\\u001b[0m`;\n}\n\nexport const bold = (s: string) => cliColor('1', s);\nexport const dim = (s: string) => cliColor('2', s);\nexport const cyan = (s: string) => cliColor('36', s);\nexport const yellow = (s: string) => cliColor('33', s);\nexport const green = (s: string) => cliColor('32', s);\nexport const red = (s: string) => cliColor('31', s);\n\n// Status lines: color annotates, never decorates. The glyph carries the\n// verdict in color; the message stays plain.\nexport const ok = (msg: string) => `${green('\u2713')} ${msg}`;\nexport const fail = (msg: string) => `${red('\u2717')} ${msg}`;\n\nexport function visibleLength(text: string): number {\n  return text.replace(/\\u001b\\[[0-9;]*m/g, '').length;\n}\n\nexport function padEndVisible(text: string, width: number): string {\n  const pad = Math.max(0, width - visibleLength(text));\n  return text + ' '.repeat(pad);\n}\n", "/**\n * Shared skillet.md origin for user-facing URLs in CLI output.\n *\n * Command tiering (device-agent vs web-managed) is NOT modeled here anymore:\n * the single source is the registration split in commands/register-all.ts \u2014\n * device-tier commands register unconditionally, management verbs behind the\n * legacy flag. A parallel path-classifier used to live here and drifted from\n * that registration (the drift once dropped pending/approve/reject and broke\n * the tray), so it was removed.\n */\nexport function webBaseUrl(): string {\n  return (process.env[\"SKILLET_WEB_URL\"] ?? \"https://skillet.md\").replace(/\\/+$/, \"\");\n}\n", "import { webBaseUrl } from \"../cli-command-tier.js\";\n\n/**\n * Extended help body for `skillet mcp --help` (appended after Usage/Options).\n * Narrative lives here; flags stay in registerMcpCommand.\n */\nexport function mcpExtendedHelp(): string {\n  const web = webBaseUrl();\n  return `\nOverview\n  Expose your local Skillet kit to MCP clients that run on this machine \u2014\n  Claude Desktop, Cursor, Claude Code, or any client that can spawn a local\n  MCP server. The server is a read-only view over ~/.skillet/skills/ \u2014 skills\n  you already synced and approved.\n\nBefore you start\n  Run skillet sync (or sync from the desktop app) so ~/.skillet/skills/ has\n  content.\n\nTransports\n  stdio (default) \u2014 local subprocess clients spawn skillet mcp and talk over\n    stdin/stdout. Use for Claude Desktop, Cursor, and Claude Code.\n  HTTP (--port <n>) \u2014 loopback Streamable HTTP on 127.0.0.1 for local HTTP\n    clients. On start, a loopback bearer is saved to\n    ~/.skillet/mcp-loopback-token (mode 0600).\n\nAuth\n  stdio \u2014 uses this machine's paired device token automatically (device.json,\n    falling back to your session). Pass --token to override with a skillet_s_\n    (session), skillet_d_ (device), or skillet_k_ (kit key) bearer. An\n    unpaired machine with no token serves an empty skill list (fail-closed).\n  HTTP \u2014 every request must present the loopback bearer from\n    ~/.skillet/mcp-loopback-token or a registry-validated skillet bearer as\n    Authorization: Bearer \u2026. Prefix-only tokens are rejected.\n\nTools\n  list_skills()     Kit manifest (slug, name, description, version, author)\n  get_skill(slug)   SKILL.md body plus supporting-file resource URIs\n  search_skills(q)  Keyword search over name and description\n\nResources\n  skillet://{owner}/{slug}/{path}  \u2014 one resource per file in each skill bundle\n  (e.g. skillet://you/my-skill/SKILL.md). Owner _local for unowned imports.\n\nExamples\n\n  Claude Desktop / Cursor (claude_desktop_config.json or ~/.cursor/mcp.json):\n\n    {\n      \"mcpServers\": {\n        \"skillet\": {\n          \"command\": \"skillet\",\n          \"args\": [\"mcp\"]\n        }\n      }\n    }\n\n  HTTP loopback (local HTTP clients on this machine):\n\n    skillet mcp --port 8765\n    # Point the client at http://127.0.0.1:8765 with:\n    # Authorization: Bearer $(cat ~/.skillet/mcp-loopback-token)\n\nWeb agents (ChatGPT, Claude.ai)\n  These run in the cloud and cannot reach a server on your machine. Connect\n  them with your hosted MCP link instead: on ${web}, open Settings \u2192 Account,\n  turn on MCP, and paste the link into the client. (skillet export + bundle\n  upload still works as a static snapshot alternative.)\n\nMore\n  ${web}/docs/mcp\n  ${web}/docs/runtimes/claude-ai\n  ${web}/docs/runtimes/chatgpt\n  Run skillet export for a static .zip when a client cannot use MCP.\n`.trimEnd();\n}\n", "import { mcpExtendedHelp } from \"./mcp-help.js\";\n\n/** Optional extended bodies keyed by leaf command path (e.g. `mcp`). */\nconst LEAF_EXTENDED_HELP: Record<string, () => string> = {\n  mcp: mcpExtendedHelp,\n};\n\nexport function leafExtendedHelp(commandPath: string): string | null {\n  const fn = LEAF_EXTENDED_HELP[commandPath];\n  return fn ? fn() : null;\n}\n", "/** Visibility tier for a CLI command on the default install surface. */\nexport type SurfaceTier = 'root' | 'group' | 'hidden' | 'legacy';\n\nexport interface SurfaceRow {\n  /** Stable command id (e.g. `device rename`, `add kit`). */\n  command: string;\n  usage: string;\n  group: string;\n  tier: SurfaceTier;\n}\n\nexport interface HelpGroup {\n  title: string;\n  rows: Array<{ usage: string; description: string }>;\n}\n\n/**\n * Canonical visibility matrix for default `skillet --help`.\n * Single source for root rows, footer hints, and test assertions.\n */\nexport const ROOT_SURFACE: SurfaceRow[] = [\n  {\n    command: 'connect',\n    usage: 'connect <code>',\n    group: 'Getting started',\n    tier: 'root',\n  },\n  {\n    command: 'web',\n    usage: 'web [path]',\n    group: 'Getting started',\n    tier: 'root',\n  },\n  {\n    command: 'whoami',\n    usage: 'whoami',\n    group: 'This machine',\n    tier: 'root',\n  },\n  {\n    command: 'logout',\n    usage: 'logout',\n    group: 'This machine',\n    tier: 'root',\n  },\n  {\n    command: 'import',\n    usage: 'import [source]',\n    group: 'Skills into your kit',\n    tier: 'group',\n  },\n  {\n    command: 'add',\n    usage: 'add [source]',\n    group: 'Skills into your kit',\n    tier: 'root',\n  },\n  {\n    command: 'add kit',\n    usage: 'add kit <ref>',\n    group: 'Skills into your kit',\n    tier: 'group',\n  },\n  {\n    command: 'search',\n    usage: 'search <keyword...>',\n    group: 'Skills into your kit',\n    tier: 'root',\n  },\n  {\n    command: 'list',\n    usage: 'list',\n    group: 'Skills into your kit',\n    tier: 'root',\n  },\n  {\n    command: 'sync',\n    usage: 'sync',\n    group: 'Sync & share',\n    tier: 'root',\n  },\n  {\n    command: 'scan',\n    usage: 'scan',\n    group: 'Sync & share',\n    tier: 'group',\n  },\n  {\n    command: 'mcp',\n    usage: 'mcp',\n    group: 'Sync & share',\n    tier: 'root',\n  },\n  {\n    command: 'route',\n    usage: 'route',\n    group: 'Sync & share',\n    tier: 'hidden',\n  },\n  {\n    command: 'upload',\n    usage: 'upload',\n    group: 'Sync & share',\n    tier: 'root',\n  },\n  {\n    command: 'export',\n    usage: 'export <ref>',\n    group: 'Sync & share',\n    tier: 'root',\n  },\n  {\n    command: 'usage',\n    usage: 'usage',\n    group: 'This machine',\n    tier: 'root',\n  },\n  {\n    command: 'activity',\n    usage: 'activity',\n    group: 'This machine',\n    tier: 'root',\n  },\n  {\n    command: 'device',\n    usage: 'device',\n    group: 'This machine',\n    tier: 'root',\n  },\n  {\n    command: 'doctor',\n    usage: 'doctor',\n    group: 'This machine',\n    tier: 'root',\n  },\n  { command: 'agents', usage: 'agents', group: '', tier: 'group' },\n  { command: 'runtimes', usage: 'runtimes', group: '', tier: 'group' },\n  { command: 'pending', usage: 'pending', group: '', tier: 'group' },\n  { command: 'approve', usage: 'approve', group: '', tier: 'group' },\n  { command: 'reject', usage: 'reject', group: '', tier: 'group' },\n  { command: 'edits', usage: 'edits', group: '', tier: 'group' },\n  { command: 'restore', usage: 'restore', group: '', tier: 'group' },\n  { command: 'sweep', usage: 'sweep', group: '', tier: 'group' },\n  { command: 'avatar', usage: 'avatar', group: '', tier: 'hidden' },\n  { command: 'auth', usage: 'auth', group: '', tier: 'group' },\n  { command: 'trust', usage: 'trust', group: '', tier: 'hidden' },\n  { command: 'pin', usage: 'pin', group: '', tier: 'hidden' },\n  { command: 'update-mode', usage: 'update-mode', group: '', tier: 'hidden' },\n  { command: 'status', usage: 'status', group: '', tier: 'hidden' },\n  { command: 'publish', usage: 'publish', group: '', tier: 'legacy' },\n];\n\n/** Power-user commands surfaced in the root help footer, not as rows. */\nexport const ROOT_FOOTER_POWER_COMMANDS = [\n  'import',\n  'scan',\n  'pending',\n  'edits',\n  'trust',\n  'pin',\n] as const;\n\nconst GROUP_ORDER = [\n  'Getting started',\n  'Skills into your kit',\n  'Sync & share',\n  'This machine',\n] as const;\n\n/**\n * Curated root help groups \u2014 device golden route only. Descriptions come from\n * the registered commands via `resolve`, so root help and `<cmd> --help` can\n * never drift apart: there is exactly one description per command, the one on\n * `.description()`. A row that fails to resolve is a registration bug \u2014\n * surfaced loudly here (and pinned by help-surface.test.ts) instead of\n * advertising a command that doesn't exist.\n */\nexport function buildRootHelpGroups(resolve: (commandId: string) => string | null): HelpGroup[] {\n  const byGroup = new Map<string, HelpGroup['rows']>();\n  for (const row of ROOT_SURFACE) {\n    if (row.tier !== 'root') continue;\n    const description = resolve(row.command);\n    if (description === null) {\n      throw new Error(`root help advertises \"${row.command}\" but no such command is registered`);\n    }\n    const rows = byGroup.get(row.group) ?? [];\n    rows.push({ usage: row.usage, description });\n    byGroup.set(row.group, rows);\n  }\n  return GROUP_ORDER.filter((title) => byGroup.has(title)).map((title) => ({\n    title,\n    rows: byGroup.get(title)!,\n  }));\n}\n\n/** Resolve a surface command id (\"device rename\", \"add kit\") to its registered\n *  Commander description. Returns null when the command doesn't exist. */\nexport function resolveCommandDescription(\n  root: { commands: ReadonlyArray<{ name(): string; description(): string; commands: ReadonlyArray<unknown> }> },\n  commandId: string,\n): string | null {\n  const parts = commandId.split(' ');\n  let scope: { commands: ReadonlyArray<{ name(): string; description(): string; commands: ReadonlyArray<unknown> }> } = root;\n  let found: { name(): string; description(): string; commands: ReadonlyArray<unknown> } | undefined;\n  for (const part of parts) {\n    found = scope.commands.find((c) => c.name() === part);\n    if (!found) return null;\n    scope = found as typeof scope;\n  }\n  return found ? found.description() : null;\n}\n\nexport function rootHelpRowCount(): number {\n  return ROOT_SURFACE.filter((row) => row.tier === 'root').length;\n}\n\nexport function rootTierCommands(): string[] {\n  return ROOT_SURFACE.filter((row) => row.tier === 'root').map((row) => row.command);\n}\n", "import type { Command, Help } from 'commander';\nimport { bold, cyan, dim, green, padEndVisible, yellow } from './cli-colors.js';\nimport { leafExtendedHelp } from './help/leaf-extended-help.js';\nimport {\n  ROOT_FOOTER_POWER_COMMANDS,\n  buildRootHelpGroups,\n  resolveCommandDescription,\n  type HelpGroup,\n} from './help/root-surface.js';\n\nfunction commandPath(cmd: Command): string {\n  const names: string[] = [];\n  let current: Command | null = cmd;\n  while (current) {\n    const name = current.name();\n    if (name && name !== 'skillet') names.unshift(name);\n    current = current.parent;\n  }\n  return names.join(' ');\n}\n\nfunction renderGroups(groups: HelpGroup[]): string[] {\n  const lines: string[] = [];\n  const usageWidth = Math.min(\n    36,\n    Math.max(20, ...groups.flatMap((g) => g.rows.map((r) => r.usage.length))),\n  );\n\n  for (const group of groups) {\n    lines.push(yellow(group.title));\n    for (const row of group.rows) {\n      const usageCol = padEndVisible(cyan(row.usage), usageWidth);\n      lines.push(`  ${usageCol}  ${dim(row.description)}`);\n    }\n    lines.push('');\n  }\n  return lines;\n}\n\nfunction renderRootHelp(cmd: Command): string {\n  const lines: string[] = [];\n  const version = cmd.version() ?? '';\n  lines.push(bold(`Skillet ${version}`) + dim('   Your skills, everywhere.'));\n  lines.push('');\n  lines.push(bold('Usage'));\n  lines.push(`  ${padEndVisible(cyan('skillet'), 20)}${dim('first run: connect, then sync')}`);\n  lines.push(`  ${padEndVisible(cyan('skillet <command>'), 20)}${dim('run any command below')}`);\n  lines.push('');\n  lines.push(\n    ...renderGroups(buildRootHelpGroups((id) => resolveCommandDescription(cmd, id))),\n  );\n  // Footer: two aligned lines, no backtick-`skillet` repetition, no em-dash.\n  const footLabel = (s: string): string => dim(padEndVisible(s, 16));\n  lines.push(`${footLabel('More commands')}${dim(ROOT_FOOTER_POWER_COMMANDS.join(' \u00B7 '))}`);\n  lines.push(`${footLabel('Details')}${dim('skillet <command> --help')}`);\n  return lines.join('\\n');\n}\n\nfunction renderGroupHelp(cmd: Command, helper: Help): string {\n  const path = commandPath(cmd);\n  const lines: string[] = [];\n  lines.push(bold(path) + (cmd.description() ? dim(`   ${cmd.description()}`) : ''));\n  lines.push('');\n  lines.push(bold('Usage'));\n  lines.push(`  ${cyan(`skillet ${path}`)} <command> [options]`);\n  lines.push('');\n\n  const subcommands = helper.visibleCommands(cmd);\n  if (subcommands.length > 0) {\n    lines.push(yellow('Commands'));\n    const usageWidth = Math.min(\n      32,\n      Math.max(16, ...subcommands.map((c) => helper.subcommandTerm(c).length)),\n    );\n    for (const sub of subcommands) {\n      const term = helper.subcommandTerm(sub);\n      const usageCol = padEndVisible(cyan(term), usageWidth);\n      const desc = sub.description() ?? '';\n      lines.push(`  ${usageCol}  ${dim(desc)}`);\n    }\n    lines.push('');\n  }\n\n  const globalOpts = helper.visibleGlobalOptions(cmd);\n  const opts = helper.visibleOptions(cmd);\n  const allOpts = [...globalOpts, ...opts];\n  if (allOpts.length > 0) {\n    lines.push(yellow('Options'));\n    for (const opt of allOpts) {\n      lines.push(`  ${dim(helper.optionTerm(opt))}`);\n      if (opt.description) lines.push(`    ${dim(opt.description)}`);\n    }\n    lines.push('');\n  }\n\n  lines.push(dim(`Run \\`skillet ${path} <command> --help\\` for command-specific options.`));\n  return lines.join('\\n');\n}\n\nfunction renderLeafHelp(cmd: Command, helper: Help): string {\n  const path = commandPath(cmd);\n  const lines: string[] = [];\n  const title = path.length > 0 ? `skillet ${path}` : 'skillet';\n  lines.push(bold(title) + (cmd.description() ? dim(`   ${cmd.description()}`) : ''));\n  lines.push('');\n  lines.push(bold('Usage'));\n  lines.push(`  ${cyan(helper.commandUsage(cmd))}`);\n  lines.push('');\n\n  const opts = [...helper.visibleGlobalOptions(cmd), ...helper.visibleOptions(cmd)];\n  if (opts.length > 0) {\n    lines.push(yellow('Options'));\n    const termWidth = Math.max(20, ...opts.map((o) => helper.optionTerm(o).length));\n    for (const opt of opts) {\n      const term = padEndVisible(green(helper.optionTerm(opt)), termWidth);\n      lines.push(`  ${term}  ${dim(opt.description ?? '')}`);\n    }\n    lines.push('');\n  }\n\n  const args = cmd.registeredArguments;\n  if (args.length > 0) {\n    lines.push(yellow('Arguments'));\n    for (const arg of args) {\n      lines.push(`  ${cyan(arg.name())}  ${dim(arg.description ?? '')}`);\n    }\n    lines.push('');\n  }\n\n  const extra = leafExtendedHelp(path);\n  if (extra) {\n    lines.push('');\n    lines.push(extra);\n  }\n\n  return lines.join('\\n');\n}\n\n/** Colorful help for skillet and subcommands. */\nexport function formatSkilletHelp(cmd: Command, helper: Help): string {\n  const isRoot = cmd.parent === null;\n  if (isRoot) return renderRootHelp(cmd);\n  if (cmd.commands.length > 0) return renderGroupHelp(cmd, helper);\n  return renderLeafHelp(cmd, helper);\n}\n", "import {\n  sync,\n  readState,\n  authConnectPair,\n  loadRegistryBearer,\n  extractPairCode,\n} from \"@skillet/core\";\nimport * as clack from \"@clack/prompts\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { stat } from \"node:fs/promises\";\nimport { runtimeLabel } from \"@skillet/core\";\nimport { ADDITIONAL_ADAPTERS, BASELINE_GLOBAL_ADAPTERS, countUserSkills } from \"./cli-context.js\";\nimport { resolveSyncAdapters } from \"./adapter-tiers.js\";\nimport { REGISTRY_DEFAULT } from \"./cli-context.js\";\nimport { installRouteHooksWithConsent } from \"./route-hooks-consent.js\";\nimport { webBaseUrl } from \"./cli-command-tier.js\";\nimport { resolveBundledRouteSkillDir } from \"./bundled-route-path.js\";\nimport { inlinedRouteSkillMd } from \"./bundled-route-content.js\";\nimport { ok, fail, dim, bold, cyan } from \"./cli-colors.js\";\nimport { printPendingReviewSummary } from \"./pending-review-summary.js\";\nimport { printRenderedError } from \"./render-error.js\";\n\nfunction settingsPageUrl(): string {\n  return `${webBaseUrl()}/settings`;\n}\n\n/**\n * Name the agents actually on this machine so connect pitches are concrete:\n * \"\u2026use your skills in Claude Code\" beats \"\u2026in every agent\". Local fs checks\n * only; any failure just falls back to the generic phrasing.\n */\nexport async function detectedAgentsPhrase(): Promise<string> {\n  const labels: string[] = [];\n  const seen = new Set<string>();\n  for (const adapter of [...ADDITIONAL_ADAPTERS, ...BASELINE_GLOBAL_ADAPTERS]) {\n    if (seen.has(adapter.name)) continue;\n    seen.add(adapter.name);\n    // The codex adapter also claims the universal ~/.agents dir it owns, which\n    // Skillet creates on every synced machine \u2014 so its detect() can't prove\n    // Codex is installed. Name Codex only on direct evidence, and never say\n    // \"Universal\" to a person.\n    if (adapter.name === \"codex\") {\n      try {\n        await stat(join(homedir(), \".codex\"));\n        labels.push(\"Codex\");\n      } catch {\n        // No ~/.codex \u2014 leave Codex unnamed.\n      }\n      continue;\n    }\n    const label = runtimeLabel(adapter.name);\n    if (label.startsWith(\"Universal\")) continue;\n    try {\n      if (await adapter.detect()) labels.push(label);\n    } catch {\n      // One adapter's failure shouldn't cost the others their mention.\n    }\n  }\n  if (labels.length === 0) return \"on this machine\";\n  if (labels.length === 1) return `in ${labels[0]}`;\n  if (labels.length === 2) return `in ${labels[0]} and ${labels[1]}`;\n  if (labels.length === 3) return `in ${labels[0]}, ${labels[1]}, and ${labels[2]}`;\n  return `in ${labels[0]}, ${labels[1]}, and ${labels.length - 2} more`;\n}\n\n/** Pair-code prompt: greyed placeholder carries the skip affordance, Esc skips. */\nasync function promptPairCode(): Promise<string> {\n  const entry = await clack.text({\n    message: \"Pair code\",\n    placeholder: \"Paste your code \u00B7 Esc to skip\",\n    // Format mistakes never submit \u2014 the prompt stays open with the reason.\n    // Accepts dashed codes and full pasted connect commands (extractPairCode).\n    validate: (value) => {\n      if (!value || !value.trim()) return undefined; // empty submit = skip\n      return extractPairCode(value) ? undefined : \"That doesn't look like a pair code\";\n    },\n  });\n  if (clack.isCancel(entry)) return \"\";\n  const raw = String(entry ?? \"\").trim();\n  return raw ? (extractPairCode(raw) ?? raw) : \"\";\n}\n\n/**\n * Prompt-and-pair loop: a rejected code re-prompts instead of exiting \u2014 the\n * user is already at the prompt, so the prompt is the retry. Esc or an empty\n * submit leaves. Returns the pair result, or null if the user backed out.\n */\nexport async function pairInteractively(\n  opts: { registryUrl?: string; label?: string; clientKind?: \"cli\" | \"desktop\" } = {},\n): Promise<Awaited<ReturnType<typeof authConnectPair>> | null> {\n  for (;;) {\n    const code = await promptPairCode();\n    if (!code) return null;\n    try {\n      return await authConnectPair({ code, registryUrl: REGISTRY_DEFAULT, ...opts });\n    } catch (err) {\n      const reason = (err as Error).message.replace(/^Could not connect with pair code:\\s*/i, \"\");\n      console.error(`\\n${fail(reason)}`);\n      console.log(dim(\"  Codes are single-use. Get a fresh one at \") + cyan(settingsPageUrl()) + \"\\n\");\n    }\n  }\n}\n\n/**\n * Sync this machine and report the outcome. Shared by the bare-command wizard\n * and `skillet connect` (human path) so pairing always ends in a synced\n * machine, matching the desktop's pair-then-sync behavior.\n */\nexport async function runConnectedSync(\n  allowReconnectPrompt = true,\n  // homeMenuFollows: the bare-run menu renders pending review and teaching\n  // itself, with the data on the option \u2014 printing them here too would say\n  // everything twice on one screen.\n  opts: { homeMenuFollows?: boolean } = {},\n): Promise<void> {\n  // Progress only if there's a wait worth explaining: a fast result (or a\n  // fast 401 on a disconnected machine) should print nothing but the outcome.\n  // A managed spinner, not a bare log line \u2014 it stops BEFORE any other output\n  // so it can never interleave with results, hooks, or the consent ask.\n  const spin = clack.spinner();\n  let spinning = false;\n  const progress = setTimeout(() => {\n    if (process.stdout.isTTY === true) {\n      spin.start(\"Syncing\");\n      spinning = true;\n    } else {\n      console.log(\"\\nSyncing\u2026\");\n    }\n  }, 750);\n  const stopProgress = (note?: string) => {\n    clearTimeout(progress);\n    if (spinning) {\n      spin.stop(note ?? \"Synced.\");\n      spinning = false;\n    }\n  };\n\n  try {\n    const bearer = await loadRegistryBearer();\n    const { adapters: syncAdapters, baselineNames } = await resolveSyncAdapters(process.cwd());\n    // Core can write mid-run (skip lines, the TTY quarantine consent prompt).\n    // Any such output must kill the spinner FIRST or the animation draws over\n    // it \u2014 so sync writes through a proxy that stops progress on first use.\n    const syncOutput = new Proxy(process.stdout, {\n      get(target, prop, receiver) {\n        if (prop === \"write\") {\n          return (...args: Parameters<typeof process.stdout.write>) => {\n            stopProgress(\"Syncing paused.\");\n            return target.write(...args);\n          };\n        }\n        return Reflect.get(target, prop, receiver);\n      },\n    }) as NodeJS.WriteStream;\n    const result = await sync(process.cwd(), syncAdapters, {\n      output: syncOutput,\n      token: bearer.token || undefined,\n      baselineAdapterNames: baselineNames,\n      // Core's default is hardcoded prod; without this, the auto-sync after\n      // pairing ignores SKILLET_REGISTRY_URL and 401s dev/local tokens\n      // against production, printing a bogus \"disconnected\" right after a\n      // successful pair.\n      registryUrl: REGISTRY_DEFAULT,\n      bundledRouteSkillDir: resolveBundledRouteSkillDir(),\n      bundledRouteSkillMd: inlinedRouteSkillMd(),\n    });\n    const stateAfter = await readState();\n    const totalSkills = countUserSkills(stateAfter);\n    const detected = result.adapters.filter((a) => a.status !== \"skipped-not-detected\").length;\n\n    // One synced line, ever: when the spinner was shown it resolves INTO the\n    // summary; otherwise the summary prints plainly. Never both.\n    const finish = (line: string) => {\n      if (spinning) {\n        stopProgress(line);\n      } else {\n        stopProgress();\n        console.log(`\\n${ok(line)}`);\n      }\n    };\n\n    if (totalSkills === 0) {\n      finish(\"Sync complete \u2014 your kit is ready.\");\n      console.log(dim(\"  Add skills on \") + cyan(webBaseUrl()));\n      await installRouteHooksWithConsent(result, { teachHint: !opts.homeMenuFollows });\n      return;\n    }\n\n    // One count, plain words: \"18 skills in 4 agents\". The kit-vs-individual\n    // breakdown lives in `skillet list`; here it only invited a \"kit vs kits\"\n    // double meaning, and \"materialized into runtimes\" is internal vocabulary.\n    // Honesty rule, per kind: a held NEW skill is genuinely absent from the\n    // machine, but a held UPDATE means the previous approved version is\n    // still synced \u2014 it must not subtract from the synced count.\n    const newCount = result.pendingReview.filter((p) => p.range === \"new\").length;\n    const updCount = result.pendingReview.length - newCount;\n    const applied = Math.max(0, totalSkills - newCount);\n    const waitingPhrase =\n      newCount > 0 && updCount > 0\n        ? `${newCount} new skill${newCount === 1 ? \"\" : \"s\"} and ${updCount} update${updCount === 1 ? \"\" : \"s\"} need your OK`\n        : newCount > 0\n          ? `${newCount} new skill${newCount === 1 ? \"\" : \"s\"} need${newCount === 1 ? \"s\" : \"\"} your OK`\n          : `${updCount} update${updCount === 1 ? \"\" : \"s\"} need${updCount === 1 ? \"s\" : \"\"} your OK`;\n    finish(\n      newCount === 0 && updCount === 0\n        ? `You're synced \u2014 ${totalSkills} skill${totalSkills === 1 ? \"\" : \"s\"}.`\n        : newCount === 0\n          ? `You're synced \u2014 ${totalSkills} skill${totalSkills === 1 ? \"\" : \"s\"}; ${waitingPhrase}.`\n          : `Synced ${applied} of ${totalSkills} skills; ${waitingPhrase}.`,\n    );\n    if (detected === 0) {\n      console.log(\n        \"  Universal ~/.agents/skills should have received skills. Run `skillet sync` again if it did not arrive.\",\n      );\n    }\n    // The receipt: what arrived THIS run (the CLI's activity view). Silent\n    // consent for your own work must never mean invisible arrival \u2014 these\n    // lines are information, not questions. Held items are excluded; their\n    // menu rows / summary carry them.\n    const held = new Set(result.pendingReview.map((p) => p.slug));\n    const arrived = [\n      ...result.unionPull\n        .filter((o) => o.status === \"updated\" && !held.has(o.slug))\n        .map((o) => ({ slug: o.slug, kind: \"new\" as const })),\n      ...result.pull\n        .filter((o) => o.status === \"updated\" && !held.has(o.slug))\n        .map((o) => ({ slug: o.slug, kind: \"update\" as const })),\n    ];\n    const RECEIPT_MAX = 6;\n    for (const item of arrived.slice(0, RECEIPT_MAX)) {\n      const entry = stateAfter.skills[item.slug];\n      const version = entry ? `v${entry.versionLabel ?? entry.version}` : \"\";\n      console.log(\n        dim(\n          item.kind === \"new\"\n            ? `  + ${item.slug} ${version} (new)`\n            : `  \u2191 ${item.slug} ${version} (updated)`,\n        ),\n      );\n    }\n    if (arrived.length > RECEIPT_MAX) {\n      console.log(dim(`  \u2026and ${arrived.length - RECEIPT_MAX} more`));\n    }\n    if (!opts.homeMenuFollows) printPendingReviewSummary(result.pendingReview);\n    // Hooks + the one-time stats-consent question come LAST: the sync outcome\n    // reads first, and the run ends on the question rather than burying it.\n    // (Pairing's auto-sync shares this moment \u2014 the old \"run skillet sync\"\n    // homework was where onboarding got hooks and consent.)\n    await installRouteHooksWithConsent(result, { teachHint: !opts.homeMenuFollows });\n  } catch (err) {\n    stopProgress(\"Sync stopped.\");\n    // A dead session means this machine needs to re-pair; retrying sync\n    // cannot succeed. Detect by code, with a prose fallback for errors that\n    // lost their type across the CLI boundary.\n    const disconnected =\n      (err as { code?: string }).code === \"machine_disconnected\" ||\n      /disconnected from your account/i.test((err as Error).message);\n    if (disconnected) {\n      console.error(`\\n${fail(\"This machine was disconnected from your account.\")}`);\n      // Interactive terminals reconnect right here: the fix is pasting a code,\n      // not remembering a command. One retry loop only, then hand off.\n      if (allowReconnectPrompt && process.stdout.isTTY === true) {\n        console.log(dim(\"  Get a pair code at \") + cyan(settingsPageUrl()));\n        const result = await pairInteractively();\n        if (result) {\n          const who = result.handle ? `@${result.handle}` : \"your account\";\n          console.log(`\\n${ok(`Connected to ${who}`)}`);\n          return runConnectedSync(false);\n        }\n        console.log(dim(\"\\n  Reconnect anytime: \") + bold(\"skillet connect <code>\"));\n        return;\n      }\n      console.log(dim(\"  Get a pair code at \") + cyan(settingsPageUrl()));\n      console.log(`\\n    ${bold(\"skillet connect <code>\")}`);\n      return;\n    }\n    printRenderedError(\n      err as Error,\n      (what) => `\\n${fail(`Sync didn't finish: ${what}`)}`,\n      (line) => console.log(line.startsWith(\"\\n\") ? line : dim(line)),\n    );\n    // A sync that didn't finish is a failure \u2014 scripts and CI must see it.\n    process.exitCode = 1;\n  }\n}\n", "import { styleText } from 'node:util';\nimport { stdout, stdin } from 'node:process';\nimport * as l from 'node:readline';\nimport l__default from 'node:readline';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport { cursor, erase } from 'sisteransi';\nimport { ReadStream } from 'node:tty';\n\nfunction findCursor(s, o, l) {\n  if (!l.some((r) => !r.disabled))\n    return s;\n  const t = s + o, n = Math.max(l.length - 1, 0), e = t < 0 ? n : t > n ? 0 : t;\n  return l[e].disabled ? findCursor(e, o < 0 ? -1 : 1, l) : e;\n}\nfunction findTextCursor(s, o, l, i) {\n  const t = i.split(`\n`);\n  let n = 0, e = s;\n  for (const r of t) {\n    if (e <= r.length)\n      break;\n    e -= r.length + 1, n++;\n  }\n  for (n = Math.max(0, Math.min(t.length - 1, n + l)), e = Math.min(e, t[n].length) + o; e < 0 && n > 0; )\n    n--, e += t[n].length + 1;\n  for (; e > t[n].length && n < t.length - 1; )\n    e -= t[n].length + 1, n++;\n  e = Math.max(0, Math.min(t[n].length, e));\n  let h = 0;\n  for (let r = 0; r < n; r++)\n    h += t[r].length + 1;\n  return h + e;\n}\n\nconst a$2 = [\"up\", \"down\", \"left\", \"right\", \"space\", \"enter\", \"cancel\"], t = [\n  \"January\",\n  \"February\",\n  \"March\",\n  \"April\",\n  \"May\",\n  \"June\",\n  \"July\",\n  \"August\",\n  \"September\",\n  \"October\",\n  \"November\",\n  \"December\"\n];\nconst settings = {\n  actions: new Set(a$2),\n  aliases: /* @__PURE__ */ new Map([\n    // vim support\n    [\"k\", \"up\"],\n    [\"j\", \"down\"],\n    [\"h\", \"left\"],\n    [\"l\", \"right\"],\n    [\"\u0003\", \"cancel\"],\n    // opinionated defaults!\n    [\"escape\", \"cancel\"]\n  ]),\n  messages: {\n    cancel: \"Canceled\",\n    error: \"Something went wrong\"\n  },\n  withGuide: true,\n  date: {\n    monthNames: [...t],\n    messages: {\n      required: \"Please enter a valid date\",\n      invalidMonth: \"There are only 12 months in a year\",\n      invalidDay: (n, e) => `There are only ${n} days in ${e}`,\n      afterMin: (n) => `Date must be on or after ${n.toISOString().slice(0, 10)}`,\n      beforeMax: (n) => `Date must be on or before ${n.toISOString().slice(0, 10)}`\n    }\n  }\n};\nfunction updateSettings(n) {\n  if (n.aliases !== void 0) {\n    const e = n.aliases;\n    for (const s in e) {\n      if (!Object.hasOwn(e, s)) continue;\n      const i = e[s];\n      settings.actions.has(i) && (settings.aliases.has(s) || settings.aliases.set(s, i));\n    }\n  }\n  if (n.messages !== void 0) {\n    const e = n.messages;\n    e.cancel !== void 0 && (settings.messages.cancel = e.cancel), e.error !== void 0 && (settings.messages.error = e.error);\n  }\n  if (n.withGuide !== void 0 && (settings.withGuide = n.withGuide !== false), n.date !== void 0) {\n    const e = n.date;\n    e.monthNames !== void 0 && (settings.date.monthNames = [...e.monthNames]), e.messages !== void 0 && (e.messages.required !== void 0 && (settings.date.messages.required = e.messages.required), e.messages.invalidMonth !== void 0 && (settings.date.messages.invalidMonth = e.messages.invalidMonth), e.messages.invalidDay !== void 0 && (settings.date.messages.invalidDay = e.messages.invalidDay), e.messages.afterMin !== void 0 && (settings.date.messages.afterMin = e.messages.afterMin), e.messages.beforeMax !== void 0 && (settings.date.messages.beforeMax = e.messages.beforeMax));\n  }\n}\nfunction isActionKey(n, e) {\n  if (typeof n == \"string\")\n    return settings.aliases.get(n) === e;\n  for (const s of n)\n    if (s !== void 0 && isActionKey(s, e))\n      return true;\n  return false;\n}\n\nfunction diffLines(i, s) {\n  if (i === s) return;\n  const e = i.split(`\n`), t = s.split(`\n`), r = Math.max(e.length, t.length), f = [];\n  for (let n = 0; n < r; n++)\n    e[n] !== t[n] && f.push(n);\n  return {\n    lines: f,\n    numLinesBefore: e.length,\n    numLinesAfter: t.length,\n    numLines: r\n  };\n}\n\nconst R = globalThis.process.platform.startsWith(\"win\");\nconst CANCEL_SYMBOL = Symbol(\"clack:cancel\");\nfunction isCancel(e) {\n  return e === CANCEL_SYMBOL;\n}\nfunction setRawMode(e, r) {\n  const o = e;\n  o.isTTY && o.setRawMode(r);\n}\nfunction block({\n  input: e = stdin,\n  output: r = stdout,\n  overwrite: o = true,\n  hideCursor: t = true\n} = {}) {\n  const s = l.createInterface({\n    input: e,\n    output: r,\n    prompt: \"\",\n    tabSize: 1\n  });\n  l.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);\n  const n = (f, { name: a, sequence: p }) => {\n    const c = String(f);\n    if (isActionKey([c, a, p], \"cancel\")) {\n      t && r.write(cursor.show), process.exit(0);\n      return;\n    }\n    if (!o) return;\n    const i = a === \"return\" ? 0 : -1, m = a === \"return\" ? -1 : 0;\n    l.moveCursor(r, i, m, () => {\n      l.clearLine(r, 1, () => {\n        e.once(\"keypress\", n);\n      });\n    });\n  };\n  return t && r.write(cursor.hide), e.once(\"keypress\", n), () => {\n    e.off(\"keypress\", n), t && r.write(cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();\n  };\n}\nconst getColumns = (e) => \"columns\" in e && typeof e.columns == \"number\" ? e.columns : 80, getRows = (e) => \"rows\" in e && typeof e.rows == \"number\" ? e.rows : 20;\nfunction wrapTextWithPrefix(e, r, o, t = o, s = o, n) {\n  const f = getColumns(e ?? stdout);\n  return wrapAnsi(r, f - o.length, {\n    hard: true,\n    trim: false\n  }).split(`\n`).map((c, i, m) => {\n    const d = n ? n(c, i) : c;\n    return i === 0 ? `${t}${d}` : i === m.length - 1 ? `${s}${d}` : `${o}${d}`;\n  }).join(`\n`);\n}\n\nfunction runValidation(e, n) {\n  if (\"~standard\" in e) {\n    const a = e[\"~standard\"].validate(n);\n    if (a instanceof Promise)\n      throw new TypeError(\n        \"Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.\"\n      );\n    return a.issues?.at(0)?.message;\n  }\n  return e(n);\n}\n\nclass V {\n  input;\n  output;\n  _abortSignal;\n  rl;\n  opts;\n  _render;\n  _track = false;\n  _prevFrame = \"\";\n  _subscribers = /* @__PURE__ */ new Map();\n  _cursor = 0;\n  state = \"initial\";\n  error = \"\";\n  value;\n  userInput = \"\";\n  constructor(t, e = true) {\n    const { input: i = stdin, output: n = stdout, render: s, signal: r, ...o } = t;\n    this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = s.bind(this), this._track = e, this._abortSignal = r, this.input = i, this.output = n;\n  }\n  /**\n   * Unsubscribe all listeners\n   */\n  unsubscribe() {\n    this._subscribers.clear();\n  }\n  /**\n   * Set a subscriber with opts\n   * @param event - The event name\n   */\n  setSubscriber(t, e) {\n    const i = this._subscribers.get(t) ?? [];\n    i.push(e), this._subscribers.set(t, i);\n  }\n  /**\n   * Subscribe to an event\n   * @param event - The event name\n   * @param cb - The callback\n   */\n  on(t, e) {\n    this.setSubscriber(t, { cb: e });\n  }\n  /**\n   * Subscribe to an event once\n   * @param event - The event name\n   * @param cb - The callback\n   */\n  once(t, e) {\n    this.setSubscriber(t, { cb: e, once: true });\n  }\n  /**\n   * Emit an event with data\n   * @param event - The event name\n   * @param data - The data to pass to the callback\n   */\n  emit(t, ...e) {\n    const i = this._subscribers.get(t) ?? [], n = [];\n    for (const s of i)\n      s.cb(...e), s.once && n.push(() => i.splice(i.indexOf(s), 1));\n    for (const s of n)\n      s();\n  }\n  prompt() {\n    return new Promise((t) => {\n      if (this._abortSignal) {\n        if (this._abortSignal.aborted)\n          return this.state = \"cancel\", this.close(), t(CANCEL_SYMBOL);\n        this._abortSignal.addEventListener(\n          \"abort\",\n          () => {\n            this.state = \"cancel\", this.close();\n          },\n          { once: true }\n        );\n      }\n      this.rl = l__default.createInterface({\n        input: this.input,\n        tabSize: 2,\n        prompt: \"\",\n        escapeCodeTimeout: 50,\n        terminal: true\n      }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on(\"keypress\", this.onKeypress), setRawMode(this.input, true), this.output.on(\"resize\", this.render), this.render(), this.once(\"submit\", () => {\n        this.output.write(cursor.show), this.output.off(\"resize\", this.render), setRawMode(this.input, false), t(this.value);\n      }), this.once(\"cancel\", () => {\n        this.output.write(cursor.show), this.output.off(\"resize\", this.render), setRawMode(this.input, false), t(CANCEL_SYMBOL);\n      });\n    });\n  }\n  _isActionKey(t, e) {\n    return t === \"\t\";\n  }\n  _shouldSubmit(t, e) {\n    return true;\n  }\n  _setValue(t) {\n    this.value = t, this.emit(\"value\", this.value);\n  }\n  _setUserInput(t, e) {\n    this.userInput = t ?? \"\", this.emit(\"userInput\", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);\n  }\n  _clearUserInput() {\n    this.rl?.write(null, { ctrl: true, name: \"u\" }), this._setUserInput(\"\");\n  }\n  onKeypress(t, e) {\n    if (this._track && e.name !== \"return\" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, { ctrl: true, name: \"h\" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === \"error\" && (this.state = \"active\"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit(\"cursor\", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit(\"cursor\", e.name)), t && (t.toLowerCase() === \"y\" || t.toLowerCase() === \"n\") && this.emit(\"confirm\", t.toLowerCase() === \"y\"), this.emit(\"key\", t, e), e?.name === \"return\" && this._shouldSubmit(t, e)) {\n      if (this.opts.validate) {\n        const i = runValidation(this.opts.validate, this.value);\n        i && (this.error = i instanceof Error ? i.message : i, this.state = \"error\", this.rl?.write(this.userInput));\n      }\n      this.state !== \"error\" && (this.state = \"submit\");\n    }\n    isActionKey([t, e?.name, e?.sequence], \"cancel\") && (this.state = \"cancel\"), (this.state === \"submit\" || this.state === \"cancel\") && this.emit(\"finalize\"), this.render(), (this.state === \"submit\" || this.state === \"cancel\") && this.close();\n  }\n  close() {\n    this.input.unpipe(), this.input.removeListener(\"keypress\", this.onKeypress), this.output.write(`\n`), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();\n  }\n  restoreCursor() {\n    const t = wrapAnsi(this._prevFrame, process.stdout.columns, { hard: true, trim: false }).split(`\n`).length - 1;\n    this.output.write(cursor.move(-999, t * -1));\n  }\n  render() {\n    const t = wrapAnsi(this._render(this) ?? \"\", process.stdout.columns, {\n      hard: true,\n      trim: false\n    });\n    if (t !== this._prevFrame) {\n      if (this.state === \"initial\")\n        this.output.write(cursor.hide);\n      else {\n        const e = diffLines(this._prevFrame, t), i = getRows(this.output);\n        if (this.restoreCursor(), e) {\n          const n = Math.max(0, e.numLinesAfter - i), s = Math.max(0, e.numLinesBefore - i);\n          let r = e.lines.find((o) => o >= n);\n          if (r === void 0) {\n            this._prevFrame = t;\n            return;\n          }\n          if (e.lines.length === 1) {\n            this.output.write(cursor.move(0, r - s)), this.output.write(erase.lines(1));\n            const o = t.split(`\n`);\n            this.output.write(o[r]), this._prevFrame = t, this.output.write(cursor.move(0, o.length - r - 1));\n            return;\n          } else if (e.lines.length > 1) {\n            if (n < s)\n              r = n;\n            else {\n              const h = r - s;\n              h > 0 && this.output.write(cursor.move(0, h));\n            }\n            this.output.write(erase.down());\n            const f = t.split(`\n`).slice(r);\n            this.output.write(f.join(`\n`)), this._prevFrame = t;\n            return;\n          }\n        }\n        this.output.write(erase.down());\n      }\n      this.output.write(t), this.state === \"initial\" && (this.state = \"active\"), this._prevFrame = t;\n    }\n  }\n}\n\nfunction p$1(l, e) {\n  if (l === void 0 || e.length === 0)\n    return 0;\n  const i = e.findIndex((s) => s.value === l);\n  return i !== -1 ? i : 0;\n}\nfunction g(l, e) {\n  return (e.label ?? String(e.value)).toLowerCase().includes(l.toLowerCase());\n}\nfunction m(l, e) {\n  if (e)\n    return l ? e : e[0];\n}\nlet T$1 = class T extends V {\n  filteredOptions;\n  multiple;\n  isNavigating = false;\n  selectedValues = [];\n  focusedValue;\n  #e = 0;\n  #s = \"\";\n  #t;\n  #i;\n  #n;\n  get cursor() {\n    return this.#e;\n  }\n  get userInputWithCursor() {\n    if (!this.userInput)\n      return styleText([\"inverse\", \"hidden\"], \"_\");\n    if (this._cursor >= this.userInput.length)\n      return `${this.userInput}\\u2588`;\n    const e = this.userInput.slice(0, this._cursor), [t, ...i] = this.userInput.slice(this._cursor);\n    return `${e}${styleText(\"inverse\", t)}${i.join(\"\")}`;\n  }\n  get options() {\n    return typeof this.#i == \"function\" ? this.#i() : this.#i;\n  }\n  constructor(e) {\n    super(e), this.#i = e.options, this.#n = e.placeholder;\n    const t = this.options;\n    this.filteredOptions = [...t], this.multiple = e.multiple === true, this.#t = typeof e.options == \"function\" ? e.filter : e.filter ?? g;\n    let i;\n    if (e.initialValue && Array.isArray(e.initialValue) ? this.multiple ? i = e.initialValue : i = e.initialValue.slice(0, 1) : !this.multiple && this.options.length > 0 && (i = [this.options[0].value]), i)\n      for (const s of i) {\n        const n = t.findIndex((o) => o.value === s);\n        n !== -1 && (this.toggleSelected(s), this.#e = n);\n      }\n    this.focusedValue = this.options[this.#e]?.value, this.on(\"key\", (s, n) => this.#l(s, n)), this.on(\"userInput\", (s) => this.#u(s));\n  }\n  _isActionKey(e, t) {\n    return e === \"\t\" || this.multiple && this.isNavigating && t.name === \"space\" && e !== void 0 && e !== \"\";\n  }\n  #l(e, t) {\n    const i = t.name === \"up\", s = t.name === \"down\", n = t.name === \"return\", o = this.userInput === \"\" || this.userInput === \"\t\", u = this.#n, h = this.options, f = u !== void 0 && u !== \"\" && h.some(\n      (r) => !r.disabled && (this.#t ? this.#t(u, r) : true)\n    );\n    if (t.name === \"tab\" && o && f) {\n      this.userInput === \"\t\" && this._clearUserInput(), this._setUserInput(u, true), this.isNavigating = false;\n      return;\n    }\n    i || s ? (this.#e = findCursor(this.#e, i ? -1 : 1, this.filteredOptions), this.focusedValue = this.filteredOptions[this.#e]?.value, this.multiple || (this.selectedValues = [this.focusedValue]), this.isNavigating = true) : n ? this.value = m(this.multiple, this.selectedValues) : this.multiple ? this.focusedValue !== void 0 && (t.name === \"tab\" || this.isNavigating && t.name === \"space\") ? this.toggleSelected(this.focusedValue) : this.isNavigating = false : (this.focusedValue && (this.selectedValues = [this.focusedValue]), this.isNavigating = false);\n  }\n  deselectAll() {\n    this.selectedValues = [];\n  }\n  toggleSelected(e) {\n    this.filteredOptions.length !== 0 && (this.multiple ? this.selectedValues.includes(e) ? this.selectedValues = this.selectedValues.filter((t) => t !== e) : this.selectedValues = [...this.selectedValues, e] : this.selectedValues = [e]);\n  }\n  #u(e) {\n    if (e !== this.#s) {\n      this.#s = e;\n      const t = this.options;\n      e && this.#t ? this.filteredOptions = t.filter((n) => this.#t?.(e, n)) : this.filteredOptions = [...t];\n      const i = p$1(this.focusedValue, this.filteredOptions);\n      this.#e = findCursor(i, 0, this.filteredOptions);\n      const s = this.filteredOptions[this.#e];\n      s && !s.disabled ? this.focusedValue = s.value : this.focusedValue = void 0, this.multiple || (this.focusedValue !== void 0 ? this.toggleSelected(this.focusedValue) : this.deselectAll());\n    }\n  }\n};\n\nclass r extends V {\n  get cursor() {\n    return this.value ? 0 : 1;\n  }\n  get _value() {\n    return this.cursor === 0;\n  }\n  constructor(t) {\n    super(t, false), this.value = !!t.initialValue, this.on(\"userInput\", () => {\n      this.value = this._value;\n    }), this.on(\"confirm\", (i) => {\n      this.output.write(cursor.move(0, -1)), this.value = i, this.state = \"submit\", this.close();\n    }), this.on(\"cursor\", () => {\n      this.value = !this.value;\n    });\n  }\n}\n\nconst _ = {\n  Y: { type: \"year\", len: 4 },\n  M: { type: \"month\", len: 2 },\n  D: { type: \"day\", len: 2 }\n};\nfunction M(r) {\n  return [...r].map((t) => _[t]);\n}\nfunction P(r) {\n  const i = new Intl.DateTimeFormat(r, {\n    year: \"numeric\",\n    month: \"2-digit\",\n    day: \"2-digit\"\n  }).formatToParts(new Date(2e3, 0, 15)), s = [];\n  let n = \"/\";\n  for (const e of i)\n    e.type === \"literal\" ? n = e.value.trim() || e.value : (e.type === \"year\" || e.type === \"month\" || e.type === \"day\") && s.push({ type: e.type, len: e.type === \"year\" ? 4 : 2 });\n  return { segments: s, separator: n };\n}\nfunction p(r) {\n  return Number.parseInt((r || \"0\").replace(/_/g, \"0\"), 10) || 0;\n}\nfunction f(r) {\n  return {\n    year: p(r.year),\n    month: p(r.month),\n    day: p(r.day)\n  };\n}\nfunction c(r, t) {\n  return new Date(r || 2001, t || 1, 0).getDate();\n}\nfunction b(r) {\n  const { year: t, month: i, day: s } = f(r);\n  if (!t || t < 0 || t > 9999 || !i || i < 1 || i > 12 || !s || s < 1) return;\n  const n = new Date(Date.UTC(t, i - 1, s));\n  if (!(n.getUTCFullYear() !== t || n.getUTCMonth() !== i - 1 || n.getUTCDate() !== s))\n    return { year: t, month: i, day: s };\n}\nfunction C(r) {\n  const t = b(r);\n  return t ? new Date(Date.UTC(t.year, t.month - 1, t.day)) : void 0;\n}\nfunction T(r, t, i, s) {\n  const n = i ? {\n    year: i.getUTCFullYear(),\n    month: i.getUTCMonth() + 1,\n    day: i.getUTCDate()\n  } : null, e = s ? {\n    year: s.getUTCFullYear(),\n    month: s.getUTCMonth() + 1,\n    day: s.getUTCDate()\n  } : null;\n  return r === \"year\" ? { min: n?.year ?? 1, max: e?.year ?? 9999 } : r === \"month\" ? {\n    min: n && t.year === n.year ? n.month : 1,\n    max: e && t.year === e.year ? e.month : 12\n  } : {\n    min: n && t.year === n.year && t.month === n.month ? n.day : 1,\n    max: e && t.year === e.year && t.month === e.month ? e.day : c(t.year, t.month)\n  };\n}\nclass U extends V {\n  #i;\n  #o;\n  #t;\n  #h;\n  #u;\n  #e = { segmentIndex: 0, positionInSegment: 0 };\n  #n = true;\n  #s = null;\n  inlineError = \"\";\n  get segmentCursor() {\n    return { ...this.#e };\n  }\n  get segmentValues() {\n    return { ...this.#t };\n  }\n  get segments() {\n    return this.#i;\n  }\n  get separator() {\n    return this.#o;\n  }\n  get formattedValue() {\n    return this.#l(this.#t);\n  }\n  #l(t) {\n    return this.#i.map((i) => t[i.type]).join(this.#o);\n  }\n  #r() {\n    this._setUserInput(this.#l(this.#t)), this._setValue(C(this.#t) ?? void 0);\n  }\n  constructor(t) {\n    const i = t.format ? { segments: M(t.format), separator: t.separator ?? \"/\" } : P(t.locale), s = t.separator ?? i.separator, n = t.format ? M(t.format) : i.segments, e = t.initialValue ?? t.defaultValue, m = e ? {\n      year: String(e.getUTCFullYear()).padStart(4, \"0\"),\n      month: String(e.getUTCMonth() + 1).padStart(2, \"0\"),\n      day: String(e.getUTCDate()).padStart(2, \"0\")\n    } : { year: \"____\", month: \"__\", day: \"__\" }, o = n.map((a) => m[a.type]).join(s);\n    super({ ...t, initialUserInput: o }, false), this.#i = n, this.#o = s, this.#t = m, this.#h = t.minDate, this.#u = t.maxDate, this.#r(), this.on(\"cursor\", (a) => this.#f(a)), this.on(\"key\", (a, u) => this.#y(a, u)), this.on(\"finalize\", () => this.#p(t));\n  }\n  #a() {\n    const t = Math.max(0, Math.min(this.#e.segmentIndex, this.#i.length - 1)), i = this.#i[t];\n    if (i)\n      return this.#e.positionInSegment = Math.max(\n        0,\n        Math.min(this.#e.positionInSegment, i.len - 1)\n      ), { segment: i, index: t };\n  }\n  #m(t) {\n    this.inlineError = \"\", this.#s = null;\n    const i = this.#a();\n    i && (this.#e.segmentIndex = Math.max(\n      0,\n      Math.min(this.#i.length - 1, i.index + t)\n    ), this.#e.positionInSegment = 0, this.#n = true);\n  }\n  #d(t) {\n    const i = this.#a();\n    if (!i) return;\n    const { segment: s } = i, n = this.#t[s.type], e = !n || n.replace(/_/g, \"\") === \"\", m = Number.parseInt((n || \"0\").replace(/_/g, \"0\"), 10) || 0, o = T(\n      s.type,\n      f(this.#t),\n      this.#h,\n      this.#u\n    );\n    let a;\n    e ? a = t === 1 ? o.min : o.max : a = Math.max(Math.min(o.max, m + t), o.min), this.#t = {\n      ...this.#t,\n      [s.type]: a.toString().padStart(s.len, \"0\")\n    }, this.#n = true, this.#s = null, this.#r();\n  }\n  #f(t) {\n    if (t)\n      switch (t) {\n        case \"right\":\n          return this.#m(1);\n        case \"left\":\n          return this.#m(-1);\n        case \"up\":\n          return this.#d(1);\n        case \"down\":\n          return this.#d(-1);\n      }\n  }\n  #y(t, i) {\n    if (i?.name === \"backspace\" || i?.sequence === \"\\x7F\" || i?.sequence === \"\\b\" || t === \"\\x7F\" || t === \"\\b\") {\n      this.inlineError = \"\";\n      const n = this.#a();\n      if (!n) return;\n      if (!this.#t[n.segment.type].replace(/_/g, \"\")) {\n        this.#m(-1);\n        return;\n      }\n      this.#t[n.segment.type] = \"_\".repeat(n.segment.len), this.#n = true, this.#e.positionInSegment = 0, this.#r();\n      return;\n    }\n    if (i?.name === \"tab\") {\n      this.inlineError = \"\";\n      const n = this.#a();\n      if (!n) return;\n      const e = i.shift ? -1 : 1, m = n.index + e;\n      m >= 0 && m < this.#i.length && (this.#e.segmentIndex = m, this.#e.positionInSegment = 0, this.#n = true);\n      return;\n    }\n    if (t && /^[0-9]$/.test(t)) {\n      const n = this.#a();\n      if (!n) return;\n      const { segment: e } = n, m = !this.#t[e.type].replace(/_/g, \"\");\n      if (this.#n && this.#s !== null && !m) {\n        const h = this.#s + t, d = { ...this.#t, [e.type]: h }, g = this.#g(d, e);\n        if (g) {\n          this.inlineError = g, this.#s = null, this.#n = false;\n          return;\n        }\n        this.inlineError = \"\", this.#t[e.type] = h, this.#s = null, this.#n = false, this.#r(), n.index < this.#i.length - 1 && (this.#e.segmentIndex = n.index + 1, this.#e.positionInSegment = 0, this.#n = true);\n        return;\n      }\n      this.#n && !m && (this.#t[e.type] = \"_\".repeat(e.len), this.#e.positionInSegment = 0), this.#n = false, this.#s = null;\n      const o = this.#t[e.type], a = o.indexOf(\"_\"), u = a >= 0 ? a : Math.min(this.#e.positionInSegment, e.len - 1);\n      if (u < 0 || u >= e.len) return;\n      let l = o.slice(0, u) + t + o.slice(u + 1), D = false;\n      if (u === 0 && o === \"__\" && (e.type === \"month\" || e.type === \"day\")) {\n        const h = Number.parseInt(t, 10);\n        l = `0${t}`, D = h <= (e.type === \"month\" ? 1 : 2);\n      }\n      if (e.type === \"year\" && (l = (o.replace(/_/g, \"\") + t).padStart(e.len, \"_\")), !l.includes(\"_\")) {\n        const h = { ...this.#t, [e.type]: l }, d = this.#g(h, e);\n        if (d) {\n          this.inlineError = d;\n          return;\n        }\n      }\n      this.inlineError = \"\", this.#t[e.type] = l;\n      const y = l.includes(\"_\") ? void 0 : b(this.#t);\n      if (y) {\n        const { year: h, month: d } = y, g = c(h, d);\n        this.#t = {\n          year: String(Math.max(0, Math.min(9999, h))).padStart(4, \"0\"),\n          month: String(Math.max(1, Math.min(12, d))).padStart(2, \"0\"),\n          day: String(Math.max(1, Math.min(g, y.day))).padStart(2, \"0\")\n        };\n      }\n      this.#r();\n      const S = l.indexOf(\"_\");\n      D ? (this.#n = true, this.#s = t) : S >= 0 ? this.#e.positionInSegment = S : a >= 0 && n.index < this.#i.length - 1 ? (this.#e.segmentIndex = n.index + 1, this.#e.positionInSegment = 0, this.#n = true) : this.#e.positionInSegment = Math.min(u + 1, e.len - 1);\n    }\n  }\n  #g(t, i) {\n    const { month: s, day: n } = f(t);\n    if (i.type === \"month\" && (s < 0 || s > 12))\n      return settings.date.messages.invalidMonth;\n    if (i.type === \"day\" && (n < 0 || n > 31))\n      return settings.date.messages.invalidDay(31, \"any month\");\n  }\n  #p(t) {\n    const { year: i, month: s, day: n } = f(this.#t);\n    if (i && s && n) {\n      const e = c(i, s);\n      this.#t = {\n        ...this.#t,\n        day: String(Math.min(n, e)).padStart(2, \"0\")\n      };\n    }\n    this.value = C(this.#t) ?? t.defaultValue ?? void 0;\n  }\n}\n\nlet u$1 = class u extends V {\n  options;\n  cursor = 0;\n  #t;\n  getGroupItems(t) {\n    return this.options.filter((r) => r.group === t);\n  }\n  isGroupSelected(t) {\n    const r = this.getGroupItems(t), e = this.value;\n    return e === void 0 ? false : r.every((s) => e.includes(s.value));\n  }\n  toggleValue() {\n    const t = this.options[this.cursor];\n    if (this.value === void 0 && (this.value = []), t.group === true) {\n      const r = t.value, e = this.getGroupItems(r);\n      this.isGroupSelected(r) ? this.value = this.value.filter(\n        (s) => e.findIndex((i) => i.value === s) === -1\n      ) : this.value = [...this.value, ...e.map((s) => s.value)], this.value = Array.from(new Set(this.value));\n    } else {\n      const r = this.value.includes(t.value);\n      this.value = r ? this.value.filter((e) => e !== t.value) : [...this.value, t.value];\n    }\n  }\n  constructor(t) {\n    super(t, false);\n    const { options: r } = t;\n    this.#t = t.selectableGroups !== false, this.options = Object.entries(r).flatMap(([e, s]) => [\n      { value: e, group: true, label: e },\n      ...s.map((i) => ({ ...i, group: e }))\n    ]), this.value = [...t.initialValues ?? []], this.cursor = Math.max(\n      this.options.findIndex(({ value: e }) => e === t.cursorAt),\n      this.#t ? 0 : 1\n    ), this.on(\"cursor\", (e) => {\n      switch (e) {\n        case \"left\":\n        case \"up\": {\n          this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;\n          const s = this.options[this.cursor]?.group === true;\n          !this.#t && s && (this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1);\n          break;\n        }\n        case \"down\":\n        case \"right\": {\n          this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;\n          const s = this.options[this.cursor]?.group === true;\n          !this.#t && s && (this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1);\n          break;\n        }\n        case \"space\":\n          this.toggleValue();\n          break;\n      }\n    });\n  }\n};\n\nconst o$1 = /* @__PURE__ */ new Set([\"up\", \"down\", \"left\", \"right\"]);\nclass h extends V {\n  #t = false;\n  #s;\n  focused = \"editor\";\n  get userInputWithCursor() {\n    if (this.state === \"submit\")\n      return this.userInput;\n    const t = this.userInput;\n    if (this.cursor >= t.length)\n      return `${t}\\u2588`;\n    const s = t.slice(0, this.cursor), r = t[this.cursor], i = t.slice(this.cursor + 1);\n    return r === `\n` ? `${s}\\u2588\n${i}` : `${s}${styleText(\"inverse\", r)}${i}`;\n  }\n  get cursor() {\n    return this._cursor;\n  }\n  #r(t) {\n    if (this.userInput.length === 0) {\n      this._setUserInput(t);\n      return;\n    }\n    this._setUserInput(\n      this.userInput.slice(0, this.cursor) + t + this.userInput.slice(this.cursor)\n    );\n  }\n  #i(t) {\n    const s = this.value ?? \"\";\n    switch (t) {\n      case \"up\":\n        this._cursor = findTextCursor(this._cursor, 0, -1, s);\n        return;\n      case \"down\":\n        this._cursor = findTextCursor(this._cursor, 0, 1, s);\n        return;\n      case \"left\":\n        this._cursor = findTextCursor(this._cursor, -1, 0, s);\n        return;\n      case \"right\":\n        this._cursor = findTextCursor(this._cursor, 1, 0, s);\n        return;\n    }\n  }\n  _shouldSubmit(t, s) {\n    if (this.#s)\n      return this.focused === \"submit\" ? true : (this.#r(`\n`), this._cursor++, false);\n    const r = this.#t;\n    return this.#t = true, r && this.cursor === this.userInput.length ? (this.userInput[this.cursor - 1] === `\n` && (this._setUserInput(\n      this.userInput.slice(0, this.cursor - 1) + this.userInput.slice(this.cursor)\n    ), this._cursor--), true) : (this.#r(`\n`), this._cursor++, false);\n  }\n  constructor(t) {\n    const s = t.initialUserInput ?? t.initialValue;\n    super(\n      {\n        ...t,\n        initialUserInput: s\n      },\n      false\n    ), s !== void 0 && (this._cursor = s.length), this.#s = t.showSubmit ?? false, this.on(\"key\", (r, i) => {\n      if (i?.name && o$1.has(i.name)) {\n        this.#t = false, this.#i(i.name);\n        return;\n      }\n      if (r === \"\t\" && this.#s) {\n        this.focused = this.focused === \"editor\" ? \"submit\" : \"editor\";\n        return;\n      }\n      if (i?.name !== \"return\") {\n        if (this.#t = false, i?.name === \"backspace\" && this.cursor > 0) {\n          this._setUserInput(\n            this.userInput.slice(0, this.cursor - 1) + this.userInput.slice(this.cursor)\n          ), this._cursor--;\n          return;\n        }\n        if (i?.name === \"delete\" && this.cursor < this.userInput.length) {\n          this._setUserInput(\n            this.userInput.slice(0, this.cursor) + this.userInput.slice(this.cursor + 1)\n          );\n          return;\n        }\n        r && (this.#s && this.focused === \"submit\" && (this.focused = \"editor\"), this.#r(r ?? \"\"), this._cursor++);\n      }\n    }), this.on(\"userInput\", (r) => {\n      this._setValue(r);\n    }), this.on(\"finalize\", () => {\n      this.value || (this.value = t.defaultValue), this.value === void 0 && (this.value = \"\");\n    });\n  }\n}\n\nlet a$1 = class a extends V {\n  options;\n  cursor = 0;\n  get _value() {\n    return this.options[this.cursor].value;\n  }\n  get _enabledOptions() {\n    return this.options.filter((e) => e.disabled !== true);\n  }\n  toggleAll() {\n    const e = this._enabledOptions, i = this.value !== void 0 && this.value.length === e.length;\n    this.value = i ? [] : e.map((t) => t.value);\n  }\n  toggleInvert() {\n    const e = this.value;\n    if (!e)\n      return;\n    const i = this._enabledOptions.filter((t) => !e.includes(t.value));\n    this.value = i.map((t) => t.value);\n  }\n  toggleValue() {\n    this.value === void 0 && (this.value = []);\n    const e = this.value.includes(this._value);\n    this.value = e ? this.value.filter((i) => i !== this._value) : [...this.value, this._value];\n  }\n  constructor(e) {\n    super(e, false), this.options = e.options, this.value = [...e.initialValues ?? []];\n    const i = Math.max(\n      this.options.findIndex(({ value: t }) => t === e.cursorAt),\n      0\n    );\n    this.cursor = this.options[i].disabled ? findCursor(i, 1, this.options) : i, this.on(\"key\", (t, l) => {\n      l.name === \"a\" && this.toggleAll(), l.name === \"i\" && this.toggleInvert();\n    }), this.on(\"cursor\", (t) => {\n      switch (t) {\n        case \"left\":\n        case \"up\":\n          this.cursor = findCursor(this.cursor, -1, this.options);\n          break;\n        case \"down\":\n        case \"right\":\n          this.cursor = findCursor(this.cursor, 1, this.options);\n          break;\n        case \"space\":\n          this.toggleValue();\n          break;\n      }\n    });\n  }\n};\n\nclass o extends V {\n  _mask = \"\\u2022\";\n  get cursor() {\n    return this._cursor;\n  }\n  get masked() {\n    return this.userInput.replaceAll(/./g, this._mask);\n  }\n  get userInputWithCursor() {\n    if (this.state === \"submit\" || this.state === \"cancel\")\n      return this.masked;\n    const t = this.userInput;\n    if (this.cursor >= t.length)\n      return `${this.masked}${styleText([\"inverse\", \"hidden\"], \"_\")}`;\n    const s = this.masked, e = s.slice(0, this.cursor), r = s.slice(this.cursor);\n    return `${e}${styleText(\"inverse\", r[0])}${r.slice(1)}`;\n  }\n  clear() {\n    this._clearUserInput();\n  }\n  constructor({ mask: t, ...s }) {\n    super(s), this._mask = t ?? \"\\u2022\", this.on(\"userInput\", (e) => {\n      this._setValue(e);\n    }), this.on(\"finalize\", () => {\n      this.value === void 0 && (this.value = \"\");\n    });\n  }\n}\n\nclass a extends V {\n  options;\n  cursor = 0;\n  get _selectedValue() {\n    return this.options[this.cursor];\n  }\n  changeValue() {\n    this.value = this._selectedValue.value;\n  }\n  constructor(t) {\n    super(t, false), this.options = t.options;\n    const i = this.options.findIndex(({ value: s }) => s === t.initialValue), e = i === -1 ? 0 : i;\n    this.cursor = this.options[e].disabled ? findCursor(e, 1, this.options) : e, this.changeValue(), this.on(\"cursor\", (s) => {\n      switch (s) {\n        case \"left\":\n        case \"up\":\n          this.cursor = findCursor(this.cursor, -1, this.options);\n          break;\n        case \"down\":\n        case \"right\":\n          this.cursor = findCursor(this.cursor, 1, this.options);\n          break;\n      }\n      this.changeValue();\n    });\n  }\n}\n\nclass u extends V {\n  options;\n  cursor = 0;\n  constructor(t) {\n    super(t, false), this.options = t.options;\n    const s = t.caseSensitive === true, i = this.options.map(({ value: [e] }) => s ? e : e?.toLowerCase());\n    this.cursor = Math.max(i.indexOf(t.initialValue), 0), this.on(\"key\", (e) => {\n      if (!e)\n        return;\n      const o = s ? e : e.toLowerCase();\n      if (!i.includes(o))\n        return;\n      const n = this.options.find(({ value: [r] }) => s ? r === o : r?.toLowerCase() === o);\n      n && (this.value = n.value, this.state = \"submit\", this.emit(\"submit\"));\n    });\n  }\n}\n\nclass n extends V {\n  get userInputWithCursor() {\n    if (this.state === \"submit\")\n      return this.userInput;\n    const t = this.userInput;\n    if (this.cursor >= t.length)\n      return `${this.userInput}\\u2588`;\n    const e = t.slice(0, this.cursor), [s, ...r] = t.slice(this.cursor);\n    return `${e}${styleText(\"inverse\", s)}${r.join(\"\")}`;\n  }\n  get cursor() {\n    return this._cursor;\n  }\n  constructor(t) {\n    super({\n      ...t,\n      initialUserInput: t.initialUserInput ?? t.initialValue\n    }), this.on(\"userInput\", (e) => {\n      this._setValue(e);\n    }), this.on(\"finalize\", () => {\n      this.value || (this.value = t.defaultValue), this.value === void 0 && (this.value = \"\");\n    });\n  }\n}\n\nexport { T$1 as AutocompletePrompt, r as ConfirmPrompt, U as DatePrompt, u$1 as GroupMultiSelectPrompt, h as MultiLinePrompt, a$1 as MultiSelectPrompt, o as PasswordPrompt, V as Prompt, u as SelectKeyPrompt, a as SelectPrompt, n as TextPrompt, block, getColumns, getRows, isCancel, runValidation, settings, updateSettings, wrapTextWithPrefix };\n", "/* MAIN */\nconst getCodePointsLength = (() => {\n    const SURROGATE_PAIR_RE = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n    return (input) => {\n        let surrogatePairsNr = 0;\n        SURROGATE_PAIR_RE.lastIndex = 0;\n        while (SURROGATE_PAIR_RE.test(input)) {\n            surrogatePairsNr += 1;\n        }\n        return input.length - surrogatePairsNr;\n    };\n})();\nconst isFullWidth = (x) => {\n    return x === 0x3000 || x >= 0xFF01 && x <= 0xFF60 || x >= 0xFFE0 && x <= 0xFFE6;\n};\nconst isWideNotCJKTNotEmoji = (x) => {\n    return x === 0x231B || x === 0x2329 || x >= 0x2FF0 && x <= 0x2FFF || x >= 0x3001 && x <= 0x303E || x >= 0x3099 && x <= 0x30FF || x >= 0x3105 && x <= 0x312F || x >= 0x3131 && x <= 0x318E || x >= 0x3190 && x <= 0x31E3 || x >= 0x31EF && x <= 0x321E || x >= 0x3220 && x <= 0x3247 || x >= 0x3250 && x <= 0x4DBF || x >= 0xFE10 && x <= 0xFE19 || x >= 0xFE30 && x <= 0xFE52 || x >= 0xFE54 && x <= 0xFE66 || x >= 0xFE68 && x <= 0xFE6B || x >= 0x1F200 && x <= 0x1F202 || x >= 0x1F210 && x <= 0x1F23B || x >= 0x1F240 && x <= 0x1F248 || x >= 0x20000 && x <= 0x2FFFD || x >= 0x30000 && x <= 0x3FFFD;\n};\n/* EXPORT */\nexport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji };\n", "/* IMPORT */\nimport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji } from './utils.js';\n/* HELPERS */\nconst ANSI_RE = /[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\\u001b\\]8;[^;]*;.*?(?:\\u0007|\\u001b\\u005c)/y;\nconst CONTROL_RE = /[\\x00-\\x08\\x0A-\\x1F\\x7F-\\x9F]{1,1000}/y;\nconst CJKT_WIDE_RE = /(?:(?![\\uFF61-\\uFF9F\\uFF00-\\uFFEF])[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\p{Script=Tangut}]){1,1000}/yu;\nconst TAB_RE = /\\t{1,1000}/y;\nconst EMOJI_RE = /[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*/yu;\nconst LATIN_RE = /(?:[\\x20-\\x7E\\xA0-\\xFF](?!\\uFE0F)){1,1000}/y;\nconst MODIFIER_RE = /\\p{M}+/gu;\nconst NO_TRUNCATION = { limit: Infinity, ellipsis: '' };\n/* MAIN */\nconst getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {\n    /* CONSTANTS */\n    const LIMIT = truncationOptions.limit ?? Infinity;\n    const ELLIPSIS = truncationOptions.ellipsis ?? '';\n    const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);\n    const ANSI_WIDTH = 0;\n    const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;\n    const TAB_WIDTH = widthOptions.tabWidth ?? 8;\n    const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;\n    const FULL_WIDTH_WIDTH = 2;\n    const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;\n    const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;\n    const PARSE_BLOCKS = [\n        [LATIN_RE, REGULAR_WIDTH],\n        [ANSI_RE, ANSI_WIDTH],\n        [CONTROL_RE, CONTROL_WIDTH],\n        [TAB_RE, TAB_WIDTH],\n        [EMOJI_RE, EMOJI_WIDTH],\n        [CJKT_WIDE_RE, WIDE_WIDTH],\n    ];\n    /* STATE */\n    let indexPrev = 0;\n    let index = 0;\n    let length = input.length;\n    let lengthExtra = 0;\n    let truncationEnabled = false;\n    let truncationIndex = length;\n    let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);\n    let unmatchedStart = 0;\n    let unmatchedEnd = 0;\n    let width = 0;\n    let widthExtra = 0;\n    /* PARSE LOOP */\n    outer: while (true) {\n        /* UNMATCHED */\n        if ((unmatchedEnd > unmatchedStart) || (index >= length && index > indexPrev)) {\n            const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);\n            lengthExtra = 0;\n            for (const char of unmatched.replaceAll(MODIFIER_RE, '')) {\n                const codePoint = char.codePointAt(0) || 0;\n                if (isFullWidth(codePoint)) {\n                    widthExtra = FULL_WIDTH_WIDTH;\n                }\n                else if (isWideNotCJKTNotEmoji(codePoint)) {\n                    widthExtra = WIDE_WIDTH;\n                }\n                else {\n                    widthExtra = REGULAR_WIDTH;\n                }\n                if ((width + widthExtra) > truncationLimit) {\n                    truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);\n                }\n                if ((width + widthExtra) > LIMIT) {\n                    truncationEnabled = true;\n                    break outer;\n                }\n                lengthExtra += char.length;\n                width += widthExtra;\n            }\n            unmatchedStart = unmatchedEnd = 0;\n        }\n        /* EXITING */\n        if (index >= length) {\n            break outer;\n        }\n        /* PARSE BLOCKS */\n        for (let i = 0, l = PARSE_BLOCKS.length; i < l; i++) {\n            const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];\n            BLOCK_RE.lastIndex = index;\n            if (BLOCK_RE.test(input)) {\n                lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;\n                widthExtra = lengthExtra * BLOCK_WIDTH;\n                if ((width + widthExtra) > truncationLimit) {\n                    truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));\n                }\n                if ((width + widthExtra) > LIMIT) {\n                    truncationEnabled = true;\n                    break outer;\n                }\n                width += widthExtra;\n                unmatchedStart = indexPrev;\n                unmatchedEnd = index;\n                index = indexPrev = BLOCK_RE.lastIndex;\n                continue outer;\n            }\n        }\n        /* UNMATCHED INDEX */\n        index += 1;\n    }\n    /* RETURN */\n    return {\n        width: truncationEnabled ? truncationLimit : width,\n        index: truncationEnabled ? truncationIndex : length,\n        truncated: truncationEnabled,\n        ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH\n    };\n};\n/* EXPORT */\nexport default getStringTruncatedWidth;\n", "/* IMPORT */\nimport fastStringTruncatedWidth from 'fast-string-truncated-width';\n/* HELPERS */\nconst NO_TRUNCATION = {\n    limit: Infinity,\n    ellipsis: '',\n    ellipsisWidth: 0,\n};\n/* MAIN */\nconst fastStringWidth = (input, options = {}) => {\n    return fastStringTruncatedWidth(input, NO_TRUNCATION, options).width;\n};\n/* EXPORT */\nexport default fastStringWidth;\n", "import stringWidth from 'fast-string-width';\nconst ESC = '\\x1B';\nconst CSI = '\\x9B';\nconst END_CODE = 39;\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\nconst GROUP_REGEX = new RegExp(`(?:\\\\${ANSI_CSI}(?<code>\\\\d+)m|\\\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, 'y');\nconst getClosingCode = (openingCode) => {\n    if (openingCode >= 30 && openingCode <= 37)\n        return 39;\n    if (openingCode >= 90 && openingCode <= 97)\n        return 39;\n    if (openingCode >= 40 && openingCode <= 47)\n        return 49;\n    if (openingCode >= 100 && openingCode <= 107)\n        return 49;\n    if (openingCode === 1 || openingCode === 2)\n        return 22;\n    if (openingCode === 3)\n        return 23;\n    if (openingCode === 4)\n        return 24;\n    if (openingCode === 7)\n        return 27;\n    if (openingCode === 8)\n        return 28;\n    if (openingCode === 9)\n        return 29;\n    if (openingCode === 0)\n        return 0;\n    return undefined;\n};\nconst wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;\nconst wrapWord = (rows, word, columns) => {\n    const characters = word[Symbol.iterator]();\n    let isInsideEscape = false;\n    let isInsideLinkEscape = false;\n    let lastRow = rows.at(-1);\n    let visible = lastRow === undefined ? 0 : stringWidth(lastRow);\n    let currentCharacter = characters.next();\n    let nextCharacter = characters.next();\n    let rawCharacterIndex = 0;\n    while (!currentCharacter.done) {\n        const character = currentCharacter.value;\n        const characterLength = stringWidth(character);\n        if (visible + characterLength <= columns) {\n            rows[rows.length - 1] += character;\n        }\n        else {\n            rows.push(character);\n            visible = 0;\n        }\n        if (character === ESC || character === CSI) {\n            isInsideEscape = true;\n            isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);\n        }\n        if (isInsideEscape) {\n            if (isInsideLinkEscape) {\n                if (character === ANSI_ESCAPE_BELL) {\n                    isInsideEscape = false;\n                    isInsideLinkEscape = false;\n                }\n            }\n            else if (character === ANSI_SGR_TERMINATOR) {\n                isInsideEscape = false;\n            }\n        }\n        else {\n            visible += characterLength;\n            if (visible === columns && !nextCharacter.done) {\n                rows.push('');\n                visible = 0;\n            }\n        }\n        currentCharacter = nextCharacter;\n        nextCharacter = characters.next();\n        rawCharacterIndex += character.length;\n    }\n    lastRow = rows.at(-1);\n    if (!visible && lastRow !== undefined && lastRow.length && rows.length > 1) {\n        rows[rows.length - 2] += rows.pop();\n    }\n};\nconst stringVisibleTrimSpacesRight = (string) => {\n    const words = string.split(' ');\n    let last = words.length;\n    while (last) {\n        if (stringWidth(words[last - 1])) {\n            break;\n        }\n        last--;\n    }\n    if (last === words.length) {\n        return string;\n    }\n    return words.slice(0, last).join(' ') + words.slice(last).join('');\n};\nconst exec = (string, columns, options = {}) => {\n    if (options.trim !== false && string.trim() === '') {\n        return '';\n    }\n    let returnValue = '';\n    let escapeCode;\n    let escapeUrl;\n    const words = string.split(' ');\n    let rows = [''];\n    let rowLength = 0;\n    for (let index = 0; index < words.length; index++) {\n        const word = words[index];\n        if (options.trim !== false) {\n            const row = rows.at(-1) ?? '';\n            const trimmed = row.trimStart();\n            if (row.length !== trimmed.length) {\n                rows[rows.length - 1] = trimmed;\n                rowLength = stringWidth(trimmed);\n            }\n        }\n        if (index !== 0) {\n            if (rowLength >= columns &&\n                (options.wordWrap === false || options.trim === false)) {\n                rows.push('');\n                rowLength = 0;\n            }\n            if (rowLength || options.trim === false) {\n                rows[rows.length - 1] += ' ';\n                rowLength++;\n            }\n        }\n        const wordLength = stringWidth(word);\n        if (options.hard && wordLength > columns) {\n            const remainingColumns = columns - rowLength;\n            const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);\n            const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);\n            if (breaksStartingNextLine < breaksStartingThisLine) {\n                rows.push('');\n            }\n            wrapWord(rows, word, columns);\n            rowLength = stringWidth(rows.at(-1) ?? '');\n            continue;\n        }\n        if (rowLength + wordLength > columns && rowLength && wordLength) {\n            if (options.wordWrap === false && rowLength < columns) {\n                wrapWord(rows, word, columns);\n                rowLength = stringWidth(rows.at(-1) ?? '');\n                continue;\n            }\n            rows.push('');\n            rowLength = 0;\n        }\n        if (rowLength + wordLength > columns && options.wordWrap === false) {\n            wrapWord(rows, word, columns);\n            rowLength = stringWidth(rows.at(-1) ?? '');\n            continue;\n        }\n        rows[rows.length - 1] += word;\n        rowLength += wordLength;\n    }\n    if (options.trim !== false) {\n        rows = rows.map((row) => stringVisibleTrimSpacesRight(row));\n    }\n    const preString = rows.join('\\n');\n    let inSurrogate = false;\n    for (let i = 0; i < preString.length; i++) {\n        const character = preString[i];\n        returnValue += character;\n        if (!inSurrogate) {\n            inSurrogate = character >= '\\ud800' && character <= '\\udbff';\n            if (inSurrogate) {\n                continue;\n            }\n        }\n        else {\n            inSurrogate = false;\n        }\n        if (character === ESC || character === CSI) {\n            GROUP_REGEX.lastIndex = i + 1;\n            const groupsResult = GROUP_REGEX.exec(preString);\n            const groups = groupsResult?.groups;\n            if (groups?.code !== undefined) {\n                const code = Number.parseFloat(groups.code);\n                escapeCode = code === END_CODE ? undefined : code;\n            }\n            else if (groups?.uri !== undefined) {\n                escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n            }\n        }\n        if (preString[i + 1] === '\\n') {\n            if (escapeUrl) {\n                returnValue += wrapAnsiHyperlink('');\n            }\n            const closingCode = escapeCode ? getClosingCode(escapeCode) : undefined;\n            if (escapeCode && closingCode) {\n                returnValue += wrapAnsiCode(closingCode);\n            }\n        }\n        else if (character === '\\n') {\n            if (escapeCode && getClosingCode(escapeCode)) {\n                returnValue += wrapAnsiCode(escapeCode);\n            }\n            if (escapeUrl) {\n                returnValue += wrapAnsiHyperlink(escapeUrl);\n            }\n        }\n    }\n    return returnValue;\n};\nconst CRLF_OR_LF = /\\r?\\n/;\nexport function wrapAnsi(string, columns, options) {\n    return String(string)\n        .normalize()\n        .split(CRLF_OR_LF)\n        .map((line) => exec(line, columns, options))\n        .join('\\n');\n}\n", "import { getColumns, getRows, AutocompletePrompt, settings, ConfirmPrompt, wrapTextWithPrefix, DatePrompt, runValidation, isCancel, MultiSelectPrompt, GroupMultiSelectPrompt, MultiLinePrompt, PasswordPrompt, block, SelectPrompt, SelectKeyPrompt, TextPrompt } from '@clack/core';\nexport { isCancel, settings, updateSettings } from '@clack/core';\nimport { styleText, stripVTControlCharacters } from 'node:util';\nimport process$1 from 'node:process';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport l from 'fast-string-width';\nimport { existsSync, lstatSync, readdirSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { cursor, erase } from 'sisteransi';\n\nfunction isUnicodeSupported() {\n\tif (process$1.platform !== 'win32') {\n\t\treturn process$1.env.TERM !== 'linux'; // Linux console (kernel)\n\t}\n\n\treturn Boolean(process$1.env.CI)\n\t\t|| Boolean(process$1.env.WT_SESSION) // Windows Terminal\n\t\t|| Boolean(process$1.env.TERMINUS_SUBLIME) // Terminus (<0.2.27)\n\t\t|| process$1.env.ConEmuTask === '{cmd::Cmder}' // ConEmu and cmder\n\t\t|| process$1.env.TERM_PROGRAM === 'Terminus-Sublime'\n\t\t|| process$1.env.TERM_PROGRAM === 'vscode'\n\t\t|| process$1.env.TERM === 'xterm-256color'\n\t\t|| process$1.env.TERM === 'alacritty'\n\t\t|| process$1.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm';\n}\n\nconst unicode = isUnicodeSupported(), isCI = () => process.env.CI === \"true\", isTTY = (o) => o.isTTY === true, unicodeOr = (o, e) => unicode ? o : e, S_STEP_ACTIVE = unicodeOr(\"\\u25C6\", \"*\"), S_STEP_CANCEL = unicodeOr(\"\\u25A0\", \"x\"), S_STEP_ERROR = unicodeOr(\"\\u25B2\", \"x\"), S_STEP_SUBMIT = unicodeOr(\"\\u25C7\", \"o\"), S_BAR_START = unicodeOr(\"\\u250C\", \"T\"), S_BAR = unicodeOr(\"\\u2502\", \"|\"), S_BAR_END = unicodeOr(\"\\u2514\", \"\\u2014\"), S_BAR_START_RIGHT = unicodeOr(\"\\u2510\", \"T\"), S_BAR_END_RIGHT = unicodeOr(\"\\u2518\", \"\\u2014\"), S_RADIO_ACTIVE = unicodeOr(\"\\u25CF\", \">\"), S_RADIO_INACTIVE = unicodeOr(\"\\u25CB\", \" \"), S_CHECKBOX_ACTIVE = unicodeOr(\"\\u25FB\", \"[\\u2022]\"), S_CHECKBOX_SELECTED = unicodeOr(\"\\u25FC\", \"[+]\"), S_CHECKBOX_INACTIVE = unicodeOr(\"\\u25FB\", \"[ ]\"), S_PASSWORD_MASK = unicodeOr(\"\\u25AA\", \"\\u2022\"), S_BAR_H = unicodeOr(\"\\u2500\", \"-\"), S_CORNER_TOP_RIGHT = unicodeOr(\"\\u256E\", \"+\"), S_CONNECT_LEFT = unicodeOr(\"\\u251C\", \"+\"), S_CORNER_BOTTOM_RIGHT = unicodeOr(\"\\u256F\", \"+\"), S_CORNER_BOTTOM_LEFT = unicodeOr(\"\\u2570\", \"+\"), S_CORNER_TOP_LEFT = unicodeOr(\"\\u256D\", \"+\"), S_INFO = unicodeOr(\"\\u25CF\", \"\\u2022\"), S_SUCCESS = unicodeOr(\"\\u25C6\", \"*\"), S_WARN = unicodeOr(\"\\u25B2\", \"!\"), S_ERROR = unicodeOr(\"\\u25A0\", \"x\"), symbol = (o) => {\n  switch (o) {\n    case \"initial\":\n    case \"active\":\n      return styleText(\"cyan\", S_STEP_ACTIVE);\n    case \"cancel\":\n      return styleText(\"red\", S_STEP_CANCEL);\n    case \"error\":\n      return styleText(\"yellow\", S_STEP_ERROR);\n    case \"submit\":\n      return styleText(\"green\", S_STEP_SUBMIT);\n  }\n}, symbolBar = (o) => {\n  switch (o) {\n    case \"initial\":\n    case \"active\":\n      return styleText(\"cyan\", S_BAR);\n    case \"cancel\":\n      return styleText(\"red\", S_BAR);\n    case \"error\":\n      return styleText(\"yellow\", S_BAR);\n    case \"submit\":\n      return styleText(\"green\", S_BAR);\n  }\n};\nfunction formatInstructionFooter(o, e) {\n  const r = [`${e ? `${styleText(\"cyan\", S_BAR)}  ` : \"\"}${o.join(\" \\u2022 \")}`];\n  return e && r.push(styleText(\"cyan\", S_BAR_END)), r;\n}\n\nconst E$1 = (l, o, g, c, h, O = false) => {\n  let r = o, w = 0;\n  if (O)\n    for (let i = c - 1; i >= g && (r -= l[i].length, w++, !(r <= h)); i--)\n      ;\n  else\n    for (let i = g; i < c && (r -= l[i].length, w++, !(r <= h)); i++)\n      ;\n  return { lineCount: r, removals: w };\n};\nconst limitOptions = ({\n  cursor: l,\n  options: o,\n  style: g,\n  output: c = process.stdout,\n  maxItems: h = Number.POSITIVE_INFINITY,\n  columnPadding: O = 0,\n  rowPadding: r = 4\n}) => {\n  const i = getColumns(c) - O, I = getRows(c), C = styleText(\"dim\", \"...\"), x = Math.max(I - r, 0), m = Math.max(Math.min(h, x), 5);\n  let p = 0;\n  l >= m - 3 && (p = Math.max(\n    Math.min(l - m + 3, o.length - m),\n    0\n  ));\n  let f = m < o.length && p > 0, u = m < o.length && p + m < o.length;\n  const W = Math.min(\n    p + m,\n    o.length\n  ), e = [];\n  let d = 0;\n  f && d++, u && d++;\n  const v = p + (f ? 1 : 0), P = W - (u ? 1 : 0);\n  for (let t = v; t < P; t++) {\n    const n = wrapAnsi(g(o[t], t === l), i, {\n      hard: true,\n      trim: false\n    }).split(`\n`);\n    e.push(n), d += n.length;\n  }\n  if (d > x) {\n    let t = 0, n = 0, s = d;\n    const M = l - v;\n    let a = x;\n    const T = () => E$1(e, s, 0, M, a), L = () => E$1(\n      e,\n      s,\n      M + 1,\n      e.length,\n      a,\n      true\n    );\n    f ? ({ lineCount: s, removals: t } = T(), s > a && (u || (a -= 1), { lineCount: s, removals: n } = L())) : (u || (a -= 1), { lineCount: s, removals: n } = L(), s > a && (a -= 1, { lineCount: s, removals: t } = T())), t > 0 && (f = true, e.splice(0, t)), n > 0 && (u = true, e.splice(e.length - n, n));\n  }\n  const b = [];\n  f && b.push(C);\n  for (const t of e)\n    for (const n of t)\n      b.push(n);\n  return u && b.push(C), b;\n};\n\nfunction P(t) {\n  return t.label ?? String(t.value ?? \"\");\n}\nfunction E(t, c) {\n  if (!t)\n    return true;\n  const n = (c.label ?? String(c.value ?? \"\")).toLowerCase(), i = (c.hint ?? \"\").toLowerCase(), l = String(c.value).toLowerCase(), o = t.toLowerCase();\n  return n.includes(o) || i.includes(o) || l.includes(o);\n}\nfunction N(t, c) {\n  const n = [];\n  for (const i of c)\n    t.includes(i.value) && n.push(i);\n  return n;\n}\nconst autocomplete = (t) => new AutocompletePrompt({\n  options: t.options,\n  initialValue: t.initialValue ? [t.initialValue] : void 0,\n  initialUserInput: t.initialUserInput,\n  placeholder: t.placeholder,\n  filter: t.filter ?? ((n, i) => E(n, i)),\n  signal: t.signal,\n  input: t.input,\n  output: t.output,\n  validate: t.validate,\n  render() {\n    const n = t.withGuide ?? settings.withGuide, i = n ? [`${styleText(\"gray\", S_BAR)}`, `${symbol(this.state)}  ${t.message}`] : [`${symbol(this.state)}  ${t.message}`], l = this.userInput, o = this.options, m = t.placeholder, p = l === \"\" && m !== void 0, $ = (r, s) => {\n      const a = P(r), u = r.hint && r.value === this.focusedValue ? styleText(\"dim\", ` (${r.hint})`) : \"\";\n      switch (s) {\n        case \"active\":\n          return `${styleText(\"green\", S_RADIO_ACTIVE)} ${a}${u}`;\n        case \"inactive\":\n          return `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", a)}`;\n        case \"disabled\":\n          return `${styleText(\"gray\", S_RADIO_INACTIVE)} ${styleText([\"strikethrough\", \"gray\"], a)}`;\n      }\n    };\n    switch (this.state) {\n      case \"submit\": {\n        const r = N(this.selectedValues, o), s = r.length > 0 ? `  ${styleText(\"dim\", r.map(P).join(\", \"))}` : \"\", a = n ? styleText(\"gray\", S_BAR) : \"\";\n        return `${i.join(`\n`)}\n${a}${s}`;\n      }\n      case \"cancel\": {\n        const r = l ? `  ${styleText([\"strikethrough\", \"dim\"], l)}` : \"\", s = n ? styleText(\"gray\", S_BAR) : \"\";\n        return `${i.join(`\n`)}\n${s}${r}`;\n      }\n      default: {\n        const r = this.state === \"error\" ? \"yellow\" : \"cyan\", s = n ? `${styleText(r, S_BAR)}  ` : \"\", a = n ? styleText(r, S_BAR_END) : \"\";\n        let u = \"\";\n        if (this.isNavigating || p) {\n          const d = p ? m : l;\n          u = d !== \"\" ? ` ${styleText(\"dim\", d)}` : \"\";\n        } else\n          u = ` ${this.userInputWithCursor}`;\n        const V = this.filteredOptions.length !== o.length ? styleText(\n          \"dim\",\n          ` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? \"\" : \"es\"})`\n        ) : \"\", y = this.filteredOptions.length === 0 && l ? [`${s}${styleText(\"yellow\", \"No matches found\")}`] : [], b = this.state === \"error\" ? [`${s}${styleText(\"yellow\", this.error)}`] : [];\n        n && i.push(`${s.trimEnd()}`), i.push(\n          `${s}${styleText(\"dim\", \"Search:\")}${u}${V}`,\n          ...y,\n          ...b\n        );\n        const v = [\n          `${styleText(\"dim\", \"\\u2191/\\u2193\")} to select`,\n          `${styleText(\"dim\", \"Enter:\")} confirm`,\n          `${styleText(\"dim\", \"Type:\")} to search`\n        ], g = [`${s}${v.join(\" \\u2022 \")}`, a], O = this.filteredOptions.length === 0 ? [] : limitOptions({\n          cursor: this.cursor,\n          options: this.filteredOptions,\n          columnPadding: n ? 3 : 0,\n          // for `|  ` when guide is shown\n          rowPadding: i.length + g.length,\n          style: (d, f) => $(\n            d,\n            d.disabled ? \"disabled\" : f ? \"active\" : \"inactive\"\n          ),\n          maxItems: t.maxItems,\n          output: t.output\n        });\n        return [\n          ...i,\n          ...O.map((d) => `${s}${d}`),\n          ...g\n        ].join(`\n`);\n      }\n    }\n  }\n}).prompt(), autocompleteMultiselect = (t) => {\n  const c = (i, l, o, m) => {\n    const p = o.includes(i.value), $ = i.label ?? String(i.value ?? \"\"), r = i.hint && m !== void 0 && i.value === m ? styleText(\"dim\", ` (${i.hint})`) : \"\", s = p ? styleText(\"green\", S_CHECKBOX_SELECTED) : styleText(\"dim\", S_CHECKBOX_INACTIVE);\n    return i.disabled ? `${styleText(\"gray\", S_CHECKBOX_INACTIVE)} ${styleText([\"strikethrough\", \"gray\"], $)}` : l ? `${s} ${$}${r}` : `${s} ${styleText(\"dim\", $)}`;\n  }, n = new AutocompletePrompt({\n    options: t.options,\n    multiple: true,\n    placeholder: t.placeholder,\n    filter: t.filter ?? ((i, l) => E(i, l)),\n    validate: () => {\n      if (t.required && n.selectedValues.length === 0)\n        return \"Please select at least one item\";\n    },\n    initialValue: t.initialValues,\n    signal: t.signal,\n    input: t.input,\n    output: t.output,\n    render() {\n      const i = t.withGuide ?? settings.withGuide, l = `${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  ${t.message}\n`, o = this.userInput, m = t.placeholder, p = o === \"\" && m !== void 0, $ = this.isNavigating || p ? styleText(\"dim\", p ? m : o) : this.userInputWithCursor, r = this.options, s = this.filteredOptions.length !== r.length ? styleText(\n        \"dim\",\n        ` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? \"\" : \"es\"})`\n      ) : \"\";\n      switch (this.state) {\n        case \"submit\":\n          return `${l}${i ? `${styleText(\"gray\", S_BAR)}  ` : \"\"}${styleText(\n            \"dim\",\n            `${this.selectedValues.length} items selected`\n          )}`;\n        case \"cancel\":\n          return `${l}${i ? `${styleText(\"gray\", S_BAR)}  ` : \"\"}${styleText(\n            [\"strikethrough\", \"dim\"],\n            o\n          )}`;\n        default: {\n          const a = this.state === \"error\" ? \"yellow\" : \"cyan\", u = i ? `${styleText(a, S_BAR)}  ` : \"\", V = i ? styleText(a, S_BAR_END) : \"\", y = [\n            `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n            `${styleText(\"dim\", this.isNavigating ? \"Space/Tab:\" : \"Tab:\")} select`,\n            `${styleText(\"dim\", \"Enter:\")} confirm`,\n            `${styleText(\"dim\", \"Type:\")} to search`\n          ], b = this.filteredOptions.length === 0 && o ? [`${u}${styleText(\"yellow\", \"No matches found\")}`] : [], v = this.state === \"error\" ? [`${u}${styleText(\"yellow\", this.error)}`] : [], g = [\n            ...`${l}${i ? styleText(a, S_BAR) : \"\"}`.split(`\n`),\n            `${u}${styleText(\"dim\", \"Search:\")} ${$}${s}`,\n            ...b,\n            ...v\n          ], O = [`${u}${y.join(\" \\u2022 \")}`, V], d = limitOptions({\n            cursor: this.cursor,\n            options: this.filteredOptions,\n            style: (f, _) => c(f, _, this.selectedValues, this.focusedValue),\n            maxItems: t.maxItems,\n            output: t.output,\n            rowPadding: g.length + O.length\n          });\n          return [\n            ...g,\n            ...d.map((f) => `${u}${f}`),\n            ...O\n          ].join(`\n`);\n        }\n      }\n    }\n  });\n  return n.prompt();\n};\n\nconst J = [\n  S_CORNER_TOP_LEFT,\n  S_CORNER_TOP_RIGHT,\n  S_CORNER_BOTTOM_LEFT,\n  S_CORNER_BOTTOM_RIGHT\n], K = [S_BAR_START, S_BAR_START_RIGHT, S_BAR_END, S_BAR_END_RIGHT];\nfunction A$1(n, e, t, o) {\n  let i = t, f = t;\n  return o === \"center\" ? i = Math.floor((e - n) / 2) : o === \"right\" && (i = e - n - t), f = e - i - n, [i, f];\n}\nconst Q = (n) => n;\nconst box = (n = \"\", e = \"\", t) => {\n  const o = t?.output ?? process.stdout, i = getColumns(o), R = 1 * 2, u = t?.titlePadding ?? 1, h = t?.contentPadding ?? 2, w = t?.width === void 0 || t.width === \"auto\" ? 1 : Math.min(1, t.width), m = t?.withGuide ?? settings.withGuide ? `${S_BAR} ` : \"\", b = t?.formatBorder ?? Q, a = (t?.rounded ? J : K).map(b), _ = b(S_BAR_H), B = b(S_BAR), p = l(m), x = l(e), O = i - p;\n  let r = Math.floor(i * w) - p;\n  if (t?.width === \"auto\") {\n    const c = n.split(`\n`);\n    let s = x + u * 2;\n    for (const G of c) {\n      const P = l(G) + h * 2;\n      P > s && (s = P);\n    }\n    const g = s + R;\n    g < r && (r = g);\n  }\n  r % 2 !== 0 && (r < O ? r++ : r--);\n  const d = r - R, S = d - u * 2, T = x > S ? `${e.slice(0, S - 3)}...` : e, [y, W] = A$1(\n    l(T),\n    d,\n    u,\n    t?.titleAlign\n  ), L = wrapAnsi(n, d - h * 2, {\n    hard: true,\n    trim: false\n  });\n  o.write(\n    `${m}${a[0]}${_.repeat(y)}${T}${_.repeat(W)}${a[1]}\n`\n  );\n  const E = L.split(`\n`);\n  for (const c of E) {\n    const [s, g] = A$1(\n      l(c),\n      d,\n      h,\n      t?.contentAlign\n    );\n    o.write(\n      `${m}${B}${\" \".repeat(s)}${c}${\" \".repeat(g)}${B}\n`\n    );\n  }\n  o.write(`${m}${a[2]}${_.repeat(d)}${a[3]}\n`);\n};\n\nconst confirm = (i) => {\n  const a = i.active ?? \"Yes\", s = i.inactive ?? \"No\";\n  return new ConfirmPrompt({\n    active: a,\n    inactive: s,\n    signal: i.signal,\n    input: i.input,\n    output: i.output,\n    initialValue: i.initialValue ?? true,\n    render() {\n      const e = i.withGuide ?? settings.withGuide, u = `${symbol(this.state)}  `, l = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", f = wrapTextWithPrefix(\n        i.output,\n        i.message,\n        l,\n        u\n      ), o = `${e ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${f}\n`, c = this.value ? a : s;\n      switch (this.state) {\n        case \"submit\": {\n          const r = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\";\n          return `${o}${r}${styleText(\"dim\", c)}`;\n        }\n        case \"cancel\": {\n          const r = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\";\n          return `${o}${r}${styleText([\"strikethrough\", \"dim\"], c)}${e ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n        }\n        default: {\n          const r = e ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", g = e ? styleText(\"cyan\", S_BAR_END) : \"\";\n          return `${o}${r}${this.value ? `${styleText(\"green\", S_RADIO_ACTIVE)} ${a}` : `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", a)}`}${i.vertical ? e ? `\n${styleText(\"cyan\", S_BAR)}  ` : `\n` : ` ${styleText(\"dim\", \"/\")} `}${this.value ? `${styleText(\"dim\", S_RADIO_INACTIVE)} ${styleText(\"dim\", s)}` : `${styleText(\"green\", S_RADIO_ACTIVE)} ${s}`}\n${g}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst date = (e) => {\n  const r = e.validate;\n  return new DatePrompt({\n    ...e,\n    validate(t) {\n      if (t === void 0)\n        return e.defaultValue !== void 0 ? void 0 : r ? runValidation(r, t) : settings.date.messages.required;\n      const o = (i) => i.toISOString().slice(0, 10);\n      if (e.minDate && o(t) < o(e.minDate))\n        return settings.date.messages.afterMin(e.minDate);\n      if (e.maxDate && o(t) > o(e.maxDate))\n        return settings.date.messages.beforeMax(e.maxDate);\n      if (r) return runValidation(r, t);\n    },\n    render() {\n      const t = (e?.withGuide ?? settings.withGuide) !== false, i = `${`${t ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  `}${e.message}\n`, l = this.state !== \"initial\" ? this.state : \"active\", d = b(this, l), c = this.value instanceof Date ? this.formattedValue : \"\";\n      switch (this.state) {\n        case \"error\": {\n          const a = this.error ? `  ${styleText(\"yellow\", this.error)}` : \"\", s = t ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", f = t ? styleText(\"yellow\", S_BAR_END) : \"\";\n          return `${i.trim()}\n${s}${d}\n${f}${a}\n`;\n        }\n        case \"submit\": {\n          const a = c ? `  ${styleText(\"dim\", c)}` : \"\", s = t ? styleText(\"gray\", S_BAR) : \"\";\n          return `${i}${s}${a}`;\n        }\n        case \"cancel\": {\n          const a = c ? `  ${styleText([\"strikethrough\", \"dim\"], c)}` : \"\", s = t ? styleText(\"gray\", S_BAR) : \"\";\n          return `${i}${s}${a}${c.trim() ? `\n${s}` : \"\"}`;\n        }\n        default: {\n          const a = t ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", s = t ? styleText(\"cyan\", S_BAR_END) : \"\", f = t ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", g = this.inlineError ? `\n${f}${styleText(\"yellow\", this.inlineError)}` : \"\";\n          return `${i}${a}${d}${g}\n${s}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\nfunction b(e, r) {\n  const t = e.segmentValues, o = e.segmentCursor;\n  if (r === \"submit\" || r === \"cancel\")\n    return e.formattedValue;\n  const i = styleText(\"gray\", e.separator);\n  return e.segments.map((l, d) => {\n    const c = d === o.segmentIndex && ![\"submit\", \"cancel\"].includes(r), a = p[l.type];\n    return x(t[l.type], { isActive: c, label: a });\n  }).join(i);\n}\nfunction x(e, r) {\n  const t = !e || e.replace(/_/g, \"\") === \"\";\n  return r.isActive ? styleText(\"inverse\", t ? r.label : e.replace(/_/g, \" \")) : t ? styleText(\"dim\", r.label) : e.replace(/_/g, styleText(\"dim\", \" \"));\n}\nconst p = {\n  year: \"yyyy\",\n  month: \"mm\",\n  day: \"dd\"\n};\n\nconst group = async (o, r) => {\n  const t = {}, p = Object.keys(o);\n  for (const e of p) {\n    const i = o[e], n = await i({ results: t })?.catch((a) => {\n      throw a;\n    });\n    if (typeof r?.onCancel == \"function\" && isCancel(n)) {\n      t[e] = \"canceled\", r.onCancel({ results: t });\n      continue;\n    }\n    t[e] = n;\n  }\n  return t;\n};\n\nconst MULTISELECT_INSTRUCTIONS = [\n  `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n  `${styleText(\"dim\", \"Space:\")} select`,\n  `${styleText(\"dim\", \"Enter:\")} confirm`\n];\nconst m = (n, o) => n.split(`\n`).map((d) => o(d)).join(`\n`);\nconst multiselect = (n) => {\n  const o = (t, a) => {\n    const r = t.label ?? String(t.value);\n    return a === \"disabled\" ? `${styleText(\"gray\", S_CHECKBOX_INACTIVE)} ${m(r, (l) => styleText([\"strikethrough\", \"gray\"], l))}${t.hint ? ` ${styleText(\"dim\", `(${t.hint ?? \"disabled\"})`)}` : \"\"}` : a === \"active\" ? `${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} ${r}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"selected\" ? `${styleText(\"green\", S_CHECKBOX_SELECTED)} ${m(r, (l) => styleText(\"dim\", l))}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"cancelled\" ? `${m(r, (l) => styleText([\"strikethrough\", \"dim\"], l))}` : a === \"active-selected\" ? `${styleText(\"green\", S_CHECKBOX_SELECTED)} ${r}${t.hint ? ` ${styleText(\"dim\", `(${t.hint})`)}` : \"\"}` : a === \"submitted\" ? `${m(r, (l) => styleText(\"dim\", l))}` : `${styleText(\"dim\", S_CHECKBOX_INACTIVE)} ${m(r, (l) => styleText(\"dim\", l))}`;\n  }, d = n.required ?? true;\n  return new MultiSelectPrompt({\n    options: n.options,\n    signal: n.signal,\n    input: n.input,\n    output: n.output,\n    initialValues: n.initialValues,\n    required: d,\n    cursorAt: n.cursorAt,\n    validate(t) {\n      if (d && (t === void 0 || t.length === 0))\n        return `Please select at least one option.\n${styleText(\n          \"reset\",\n          styleText(\n            \"dim\",\n            `Press ${styleText([\"gray\", \"bgWhite\", \"inverse\"], \" space \")} to select, ${styleText(\n              \"gray\",\n              styleText(\"bgWhite\", styleText(\"inverse\", \" enter \"))\n            )} to submit`\n          )\n        )}`;\n    },\n    render() {\n      const t = n.withGuide ?? settings.withGuide, a = wrapTextWithPrefix(\n        n.output,\n        n.message,\n        t ? `${symbolBar(this.state)}  ` : \"\",\n        `${symbol(this.state)}  `\n      ), r = `${t ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${a}\n`, l = this.value ?? [], p = (i, u) => {\n        if (i.disabled)\n          return o(i, \"disabled\");\n        const s = l.includes(i.value);\n        return u && s ? o(i, \"active-selected\") : s ? o(i, \"selected\") : o(i, u ? \"active\" : \"inactive\");\n      };\n      switch (this.state) {\n        case \"submit\": {\n          const i = this.options.filter(({ value: s }) => l.includes(s)).map((s) => o(s, \"submitted\")).join(styleText(\"dim\", \", \")) || styleText(\"dim\", \"none\"), u = wrapTextWithPrefix(\n            n.output,\n            i,\n            t ? `${styleText(\"gray\", S_BAR)}  ` : \"\"\n          );\n          return `${r}${u}`;\n        }\n        case \"cancel\": {\n          const i = this.options.filter(({ value: s }) => l.includes(s)).map((s) => o(s, \"cancelled\")).join(styleText(\"dim\", \", \"));\n          if (i.trim() === \"\")\n            return `${r}${styleText(\"gray\", S_BAR)}`;\n          const u = wrapTextWithPrefix(\n            n.output,\n            i,\n            t ? `${styleText(\"gray\", S_BAR)}  ` : \"\"\n          );\n          return `${r}${u}${t ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n        }\n        case \"error\": {\n          const i = t ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", u = this.error.split(`\n`).map(\n            ($, x) => x === 0 ? `${t ? `${styleText(\"yellow\", S_BAR_END)}  ` : \"\"}${styleText(\"yellow\", $)}` : `   ${$}`\n          ).join(`\n`), s = r.split(`\n`).length, g = u.split(`\n`).length + 1;\n          return `${r}${i}${limitOptions({\n            output: n.output,\n            options: this.options,\n            cursor: this.cursor,\n            maxItems: n.maxItems,\n            columnPadding: i.length,\n            rowPadding: s + g,\n            style: p\n          }).join(`\n${i}`)}\n${u}\n`;\n        }\n        default: {\n          const i = t ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", u = r.split(`\n`).length, s = formatInstructionFooter(MULTISELECT_INSTRUCTIONS, t), g = s.join(`\n`), $ = s.length + 1;\n          return `${r}${i}${limitOptions({\n            output: n.output,\n            options: this.options,\n            cursor: this.cursor,\n            maxItems: n.maxItems,\n            columnPadding: i.length,\n            rowPadding: u + $,\n            style: p\n          }).join(`\n${i}`)}\n${g}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst groupMultiselect = (o) => {\n  const { selectableGroups: f = true, groupSpacing: b = 0 } = o, m = (n, l, g = []) => {\n    const a = n.label ?? String(n.value), t = typeof n.group == \"string\", u = t && (g[g.indexOf(n) + 1] ?? { group: true }), s = t && u && u.group === true;\n    let r = \"\", c = \"\";\n    t && (f ? (r = s ? `${S_BAR_END} ` : `${S_BAR} `, c = s ? \"  \" : `${S_BAR} `) : r = \"  \");\n    let i = \"\";\n    if (b > 0 && !t && (i = `\n`.repeat(b)), l === \"active\")\n      return wrapTextWithPrefix(\n        o.output,\n        `${a}${n.hint ? ` ${styleText(\"dim\", `(${n.hint})`)}` : \"\"}`,\n        `${i}${styleText(\"dim\", r)} `,\n        `${i}${styleText(\"dim\", r)}${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} `,\n        `${i}${styleText(\"dim\", c)} `\n      );\n    if (l === \"group-active\")\n      return wrapTextWithPrefix(\n        o.output,\n        a,\n        `${i}${r} `,\n        `${i}${r}${styleText(\"cyan\", S_CHECKBOX_ACTIVE)} `,\n        `${i}${c} `,\n        (d) => styleText(\"dim\", d)\n      );\n    if (l === \"group-active-selected\")\n      return wrapTextWithPrefix(\n        o.output,\n        a,\n        `${i}${r} `,\n        `${i}${r}${styleText(\"green\", S_CHECKBOX_SELECTED)} `,\n        `${i}${c} `,\n        (d) => styleText(\"dim\", d)\n      );\n    if (l === \"selected\") {\n      const d = t || f ? styleText(\"green\", S_CHECKBOX_SELECTED) : \"\";\n      return wrapTextWithPrefix(\n        o.output,\n        `${a}${n.hint ? ` (${n.hint})` : \"\"}`,\n        `${i}${styleText(\"dim\", r)} `,\n        `${i}${styleText(\"dim\", r)}${d} `,\n        `${i}${styleText(\"dim\", c)} `,\n        (S) => styleText(\"dim\", S)\n      );\n    }\n    if (l === \"cancelled\")\n      return `${styleText([\"strikethrough\", \"dim\"], a)}`;\n    if (l === \"active-selected\")\n      return wrapTextWithPrefix(\n        o.output,\n        `${a}${n.hint ? ` ${styleText(\"dim\", `(${n.hint})`)}` : \"\"}`,\n        `${i}${styleText(\"dim\", r)} `,\n        `${i}${styleText(\"dim\", r)}${styleText(\"green\", S_CHECKBOX_SELECTED)} `,\n        `${i}${styleText(\"dim\", c)} `\n      );\n    if (l === \"submitted\")\n      return `${styleText(\"dim\", a)}`;\n    const h = t || f ? styleText(\"dim\", S_CHECKBOX_INACTIVE) : \"\";\n    return wrapTextWithPrefix(\n      o.output,\n      a,\n      `${i}${styleText(\"dim\", r)} `,\n      `${i}${styleText(\"dim\", r)}${h} `,\n      `${i}${styleText(\"dim\", c)} `,\n      (d) => styleText(\"dim\", d)\n    );\n  }, x = o.required ?? true;\n  return new GroupMultiSelectPrompt({\n    options: o.options,\n    signal: o.signal,\n    input: o.input,\n    output: o.output,\n    initialValues: o.initialValues,\n    required: x,\n    cursorAt: o.cursorAt,\n    selectableGroups: f,\n    validate(n) {\n      if (x && (n === void 0 || n.length === 0))\n        return `Please select at least one option.\n${styleText(\n          \"reset\",\n          styleText(\n            \"dim\",\n            `Press ${styleText([\"gray\", \"bgWhite\", \"inverse\"], \" space \")} to select, ${styleText(\n              \"gray\",\n              styleText([\"bgWhite\", \"inverse\"], \" enter \")\n            )} to submit`\n          )\n        )}`;\n    },\n    render() {\n      const n = o.withGuide ?? settings.withGuide, l = `${n ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  ${o.message}\n`, g = this.value ?? [], a = (t, u) => {\n        const s = this.options, r = g.includes(t.value) || t.group === true && this.isGroupSelected(`${t.value}`);\n        return !u && typeof t.group == \"string\" && this.options[this.cursor].value === t.group ? m(t, r ? \"group-active-selected\" : \"group-active\", s) : u && r ? m(t, \"active-selected\", s) : r ? m(t, \"selected\", s) : m(t, u ? \"active\" : \"inactive\", s);\n      };\n      switch (this.state) {\n        case \"submit\": {\n          const t = this.options.filter(({ value: s }) => g.includes(s)).map((s) => m(s, \"submitted\")), u = t.length === 0 ? \"\" : `  ${t.join(styleText(\"dim\", \", \"))}`;\n          return `${l}${n ? styleText(\"gray\", S_BAR) : \"\"}${u}`;\n        }\n        case \"cancel\": {\n          const t = this.options.filter(({ value: u }) => g.includes(u)).map((u) => m(u, \"cancelled\")).join(styleText(\"dim\", \", \"));\n          return `${l}${n ? `${styleText(\"gray\", S_BAR)}  ` : \"\"}${t.trim() ? `${t}${n ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}` : \"\"}`;\n        }\n        case \"error\": {\n          const t = n ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", u = this.error.split(`\n`).map(\n            (i, h) => h === 0 ? `${n ? `${styleText(\"yellow\", S_BAR_END)}  ` : \"\"}${styleText(\"yellow\", i)}` : `   ${i}`\n          ).join(`\n`), s = l.split(`\n`).length, r = u.split(`\n`).length + 1, c = limitOptions({\n            output: o.output,\n            options: this.options,\n            cursor: this.cursor,\n            maxItems: o.maxItems,\n            columnPadding: t.length,\n            rowPadding: s + r,\n            style: a\n          }).join(`\n${t}`);\n          return `${l}${t}${c}\n${u}\n`;\n        }\n        default: {\n          const t = n ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", u = l.split(`\n`).length, s = formatInstructionFooter(MULTISELECT_INSTRUCTIONS, n), r = s.join(`\n`), c = s.length + 1, i = limitOptions({\n            output: o.output,\n            options: this.options,\n            cursor: this.cursor,\n            maxItems: o.maxItems,\n            columnPadding: t.length,\n            rowPadding: u + c,\n            style: a\n          }).join(`\n${t}`);\n          return `${l}${t}${i}\n${r}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst log = {\n  message: (s = [], {\n    symbol: e = styleText(\"gray\", S_BAR),\n    secondarySymbol: r = styleText(\"gray\", S_BAR),\n    output: m = process.stdout,\n    spacing: l = 1,\n    withGuide: c\n  } = {}) => {\n    const t = [], o = c ?? settings.withGuide, f = o ? r : \"\", O = o ? `${e}  ` : \"\", u = o ? `${r}  ` : \"\";\n    for (let i = 0; i < l; i++)\n      t.push(f);\n    const g = Array.isArray(s) ? s : s.split(`\n`);\n    if (g.length > 0) {\n      const [i, ...y] = g;\n      i.length > 0 ? t.push(`${O}${i}`) : t.push(o ? e : \"\");\n      for (const p of y)\n        p.length > 0 ? t.push(`${u}${p}`) : t.push(o ? r : \"\");\n    }\n    m.write(`${t.join(`\n`)}\n`);\n  },\n  info: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"blue\", S_INFO) });\n  },\n  success: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"green\", S_SUCCESS) });\n  },\n  step: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"green\", S_STEP_SUBMIT) });\n  },\n  warn: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"yellow\", S_WARN) });\n  },\n  /** alias for `log.warn()`. */\n  warning: (s, e) => {\n    log.warn(s, e);\n  },\n  error: (s, e) => {\n    log.message(s, { ...e, symbol: styleText(\"red\", S_ERROR) });\n  }\n};\n\nconst cancel = (o = \"\", t) => {\n  const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR_END)}  ` : \"\";\n  i.write(`${e}${styleText(\"red\", o)}\n\n`);\n}, intro = (o = \"\", t) => {\n  const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR_START)}  ` : \"\";\n  i.write(`${e}${o}\n`);\n}, outro = (o = \"\", t) => {\n  const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText(\"gray\", S_BAR)}\n${styleText(\"gray\", S_BAR_END)}  ` : \"\";\n  i.write(`${e}${o}\n\n`);\n};\n\nconst multiline = (e) => new MultiLinePrompt({\n  validate: e.validate,\n  placeholder: e.placeholder,\n  defaultValue: e.defaultValue,\n  initialValue: e.initialValue,\n  showSubmit: e.showSubmit,\n  output: e.output,\n  signal: e.signal,\n  input: e.input,\n  render() {\n    const i = e?.withGuide ?? settings.withGuide, o = `${`${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  `}${e.message}\n`, h = e.placeholder ? styleText(\"inverse\", e.placeholder[0]) + styleText(\"dim\", e.placeholder.slice(1)) : styleText([\"inverse\", \"hidden\"], \"_\"), a = this.userInput ? this.userInputWithCursor : h, s = this.value ?? \"\", c = e.showSubmit ? `\n  ${styleText(this.focused === \"submit\" ? \"cyan\" : \"dim\", \"[ submit ]\")}` : \"\";\n    switch (this.state) {\n      case \"error\": {\n        const n = `${styleText(\"yellow\", S_BAR)}  `, r = i ? wrapTextWithPrefix(e.output, a, n, void 0) : a, u = styleText(\"yellow\", S_BAR_END);\n        return `${o}${r}\n${u}  ${styleText(\"yellow\", this.error)}${c}\n`;\n      }\n      case \"submit\": {\n        const n = `${styleText(\"gray\", S_BAR)}  `, r = i ? wrapTextWithPrefix(\n          e.output,\n          s,\n          n,\n          void 0,\n          void 0,\n          (u) => styleText(\"dim\", u)\n        ) : s ? styleText(\"dim\", s) : \"\";\n        return `${o}${r}`;\n      }\n      case \"cancel\": {\n        const n = `${styleText(\"gray\", S_BAR)}  `, r = i ? wrapTextWithPrefix(\n          e.output,\n          s,\n          n,\n          void 0,\n          void 0,\n          (u) => styleText([\"strikethrough\", \"dim\"], u)\n        ) : s ? styleText([\"strikethrough\", \"dim\"], s) : \"\";\n        return `${o}${r}`;\n      }\n      default: {\n        const n = i ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", r = i ? styleText(\"cyan\", S_BAR_END) : \"\", u = i ? wrapTextWithPrefix(e.output, a, n) : a;\n        return `${o}${u}\n${r}${c}\n`;\n      }\n    }\n  }\n}).prompt();\n\nconst W$1 = (o) => o, C = (o, e, s) => {\n  const a = {\n    hard: true,\n    trim: false\n  }, i = wrapAnsi(o, e, a).split(`\n`), c = i.reduce((n, t) => Math.max(l(t), n), 0), u = i.map(s).reduce((n, t) => Math.max(l(t), n), 0), g = e - (u - c);\n  return wrapAnsi(o, g, a);\n};\nconst note = (o = \"\", e = \"\", s) => {\n  const a = s?.output ?? process$1.stdout, i = s?.withGuide ?? settings.withGuide, c = s?.format ?? W$1, g = [\"\", ...C(o, getColumns(a) - 6, c).split(`\n`).map(c), \"\"], n = l(e), t = Math.max(\n    g.reduce((m, F) => {\n      const O = l(F);\n      return O > m ? O : m;\n    }, 0),\n    n\n  ) + 2, h = g.map(\n    (m) => `${styleText(\"gray\", S_BAR)}  ${m}${\" \".repeat(t - l(m))}${styleText(\"gray\", S_BAR)}`\n  ).join(`\n`), T = i ? `${styleText(\"gray\", S_BAR)}\n` : \"\", l$1 = i ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;\n  a.write(\n    `${T}${styleText(\"green\", S_STEP_SUBMIT)}  ${styleText(\"reset\", e)} ${styleText(\n      \"gray\",\n      S_BAR_H.repeat(Math.max(t - n - 1, 1)) + S_CORNER_TOP_RIGHT\n    )}\n${h}\n${styleText(\"gray\", l$1 + S_BAR_H.repeat(t + 2) + S_CORNER_BOTTOM_RIGHT)}\n`\n  );\n};\n\nconst password = (r) => new PasswordPrompt({\n  validate: r.validate,\n  mask: r.mask ?? S_PASSWORD_MASK,\n  signal: r.signal,\n  input: r.input,\n  output: r.output,\n  render() {\n    const e = r.withGuide ?? settings.withGuide, o = `${e ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  ${r.message}\n`, c = this.userInputWithCursor, i = this.masked;\n    switch (this.state) {\n      case \"error\": {\n        const s = e ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", n = e ? `${styleText(\"yellow\", S_BAR_END)}  ` : \"\", l = i ?? \"\";\n        return r.clearOnError && this.clear(), `${o.trim()}\n${s}${l}\n${n}${styleText(\"yellow\", this.error)}\n`;\n      }\n      case \"submit\": {\n        const s = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", n = i ? styleText(\"dim\", i) : \"\";\n        return `${o}${s}${n}`;\n      }\n      case \"cancel\": {\n        const s = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", n = i ? styleText([\"strikethrough\", \"dim\"], i) : \"\";\n        return `${o}${s}${n}${i && e ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n      }\n      default: {\n        const s = e ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", n = e ? styleText(\"cyan\", S_BAR_END) : \"\";\n        return `${o}${s}${c}\n${n}\n`;\n      }\n    }\n  }\n}).prompt();\n\nconst path = (e) => {\n  const a = e.validate;\n  return autocomplete({\n    ...e,\n    initialUserInput: e.initialValue ?? e.root ?? process.cwd(),\n    maxItems: 5,\n    validate(t) {\n      if (!Array.isArray(t)) {\n        if (!t)\n          return \"Please select a path\";\n        if (a)\n          return runValidation(a, t);\n      }\n    },\n    options() {\n      const t = this.userInput;\n      if (t === \"\")\n        return [];\n      try {\n        let i;\n        existsSync(t) ? lstatSync(t).isDirectory() && (!e.directory || t.endsWith(\"/\")) ? i = t : i = dirname(t) : i = dirname(t);\n        const c = t.length > 1 && t.endsWith(\"/\") ? t.slice(0, -1) : t;\n        return readdirSync(i).map((r) => {\n          const n = join(i, r), m = lstatSync(n);\n          return {\n            name: r,\n            path: n,\n            isDirectory: m.isDirectory()\n          };\n        }).filter(\n          ({ path: r, isDirectory: n }) => r.startsWith(c) && (n || !e.directory)\n        ).map((r) => ({\n          value: r.path\n        }));\n      } catch {\n        return [];\n      }\n    }\n  });\n};\n\nconst W = (l) => styleText(\"magenta\", l);\nconst spinner = ({\n  indicator: l = \"dots\",\n  onCancel: h,\n  output: n = process.stdout,\n  cancelMessage: G,\n  errorMessage: O,\n  frames: E = unicode ? [\"\\u25D2\", \"\\u25D0\", \"\\u25D3\", \"\\u25D1\"] : [\"\\u2022\", \"o\", \"O\", \"0\"],\n  delay: F = unicode ? 80 : 120,\n  signal: m,\n  ...I\n} = {}) => {\n  const u = isCI();\n  let M, T, d = false, S = false, s = \"\", p, w = performance.now();\n  const x = getColumns(n), k = I?.styleFrame ?? W, g = (e) => {\n    const r = e > 1 ? O ?? settings.messages.error : G ?? settings.messages.cancel;\n    S = e === 1, d && (a(r, e), S && typeof h == \"function\" && h());\n  }, f = () => g(2), i = () => g(1), A = () => {\n    process.on(\"uncaughtExceptionMonitor\", f), process.on(\"unhandledRejection\", f), process.on(\"SIGINT\", i), process.on(\"SIGTERM\", i), process.on(\"exit\", g), m && m.addEventListener(\"abort\", i);\n  }, H = () => {\n    process.removeListener(\"uncaughtExceptionMonitor\", f), process.removeListener(\"unhandledRejection\", f), process.removeListener(\"SIGINT\", i), process.removeListener(\"SIGTERM\", i), process.removeListener(\"exit\", g), m && m.removeEventListener(\"abort\", i);\n  }, y = () => {\n    if (p === void 0) return;\n    u && n.write(`\n`);\n    const r = wrapAnsi(p, x, {\n      hard: true,\n      trim: false\n    }).split(`\n`);\n    r.length > 1 && n.write(cursor.up(r.length - 1)), n.write(cursor.to(0)), n.write(erase.down());\n  }, C = (e) => e.replace(/\\.+$/, \"\"), _ = (e) => {\n    const r = (performance.now() - e) / 1e3, t = Math.floor(r / 60), o = Math.floor(r % 60);\n    return t > 0 ? `[${t}m ${o}s]` : `[${o}s]`;\n  }, N = I.withGuide ?? settings.withGuide, P = (e = \"\") => {\n    d = true, M = block({ output: n }), s = C(e), w = performance.now(), N && n.write(`${styleText(\"gray\", S_BAR)}\n`);\n    let r = 0, t = 0;\n    A(), T = setInterval(() => {\n      if (u && s === p)\n        return;\n      y(), p = s;\n      const o = k(E[r]);\n      let v;\n      if (u)\n        v = `${o}  ${s}...`;\n      else if (l === \"timer\")\n        v = `${o}  ${s} ${_(w)}`;\n      else {\n        const B = \".\".repeat(Math.floor(t)).slice(0, 3);\n        v = `${o}  ${s}${B}`;\n      }\n      const j = wrapAnsi(v, x, {\n        hard: true,\n        trim: false\n      });\n      n.write(j), r = r + 1 < E.length ? r + 1 : 0, t = t < 4 ? t + 0.125 : 0;\n    }, F);\n  }, a = (e = \"\", r = 0, t = false) => {\n    if (!d) return;\n    d = false, clearInterval(T), y();\n    const o = r === 0 ? styleText(\"green\", S_STEP_SUBMIT) : r === 1 ? styleText(\"red\", S_STEP_CANCEL) : styleText(\"red\", S_STEP_ERROR);\n    s = e ?? s, t || (l === \"timer\" ? n.write(`${o}  ${s} ${_(w)}\n`) : n.write(`${o}  ${s}\n`)), H(), M();\n  };\n  return {\n    start: P,\n    stop: (e = \"\") => a(e, 0),\n    message: (e = \"\") => {\n      s = C(e ?? s);\n    },\n    cancel: (e = \"\") => a(e, 1),\n    error: (e = \"\") => a(e, 2),\n    clear: () => a(\"\", 0, true),\n    get isCancelled() {\n      return S;\n    }\n  };\n};\n\nconst u = {\n  light: unicodeOr(\"\\u2500\", \"-\"),\n  heavy: unicodeOr(\"\\u2501\", \"=\"),\n  block: unicodeOr(\"\\u2588\", \"#\")\n};\nfunction progress({\n  style: o = \"heavy\",\n  max: d = 100,\n  size: v = 40,\n  ...x\n} = {}) {\n  const r = spinner(x);\n  let a = 0, n = \"\";\n  const c = Math.max(1, d), l = Math.max(1, v), S = (t) => {\n    switch (t) {\n      case \"initial\":\n      case \"active\":\n        return (e) => styleText(\"magenta\", e);\n      case \"error\":\n      case \"cancel\":\n        return (e) => styleText(\"red\", e);\n      case \"submit\":\n        return (e) => styleText(\"green\", e);\n      default:\n        return (e) => styleText(\"magenta\", e);\n    }\n  }, p = (t, e) => {\n    const m = Math.floor(a / c * l);\n    return `${S(t)(u[o].repeat(m))}${styleText(\"dim\", u[o].repeat(l - m))} ${e}`;\n  }, h = (t = \"\") => {\n    n = t, r.start(p(\"initial\", t));\n  }, g = (t = 1, e) => {\n    a = Math.min(c, t + a), r.message(p(\"active\", e ?? n)), n = e ?? n;\n  };\n  return {\n    start: h,\n    stop: r.stop,\n    cancel: r.cancel,\n    error: r.error,\n    clear: r.clear,\n    advance: g,\n    isCancelled: r.isCancelled,\n    message: (t) => g(0, t)\n  };\n}\n\nconst SELECT_INSTRUCTIONS = [\n  `${styleText(\"dim\", \"\\u2191/\\u2193\")} to navigate`,\n  `${styleText(\"dim\", \"Enter:\")} confirm`\n];\nconst c = (t, a) => t.includes(`\n`) ? t.split(`\n`).map((i) => a(i)).join(`\n`) : a(t);\nconst select = (t) => {\n  const a = (i, m) => {\n    const s = i.label ?? String(i.value);\n    switch (m) {\n      case \"disabled\":\n        return `${styleText(\"gray\", S_RADIO_INACTIVE)} ${c(s, (n) => styleText(\"gray\", n))}${i.hint ? ` ${styleText(\"dim\", `(${i.hint ?? \"disabled\"})`)}` : \"\"}`;\n      case \"selected\":\n        return `${c(s, (n) => styleText(\"dim\", n))}`;\n      case \"active\":\n        return `${styleText(\"green\", S_RADIO_ACTIVE)} ${s}${i.hint ? ` ${styleText(\"dim\", `(${i.hint})`)}` : \"\"}`;\n      case \"cancelled\":\n        return `${c(s, (n) => styleText([\"strikethrough\", \"dim\"], n))}`;\n      default:\n        return `${styleText(\"dim\", S_RADIO_INACTIVE)} ${c(s, (n) => styleText(\"dim\", n))}`;\n    }\n  };\n  return new SelectPrompt({\n    options: t.options,\n    signal: t.signal,\n    input: t.input,\n    output: t.output,\n    initialValue: t.initialValue,\n    render() {\n      const i = t.withGuide ?? settings.withGuide, m = `${symbol(this.state)}  `, s = `${symbolBar(this.state)}  `, n = wrapTextWithPrefix(\n        t.output,\n        t.message,\n        s,\n        m\n      ), u = `${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${n}\n`;\n      switch (this.state) {\n        case \"submit\": {\n          const r = i ? `${styleText(\"gray\", S_BAR)}  ` : \"\", o = wrapTextWithPrefix(\n            t.output,\n            a(this.options[this.cursor], \"selected\"),\n            r\n          );\n          return `${u}${o}`;\n        }\n        case \"cancel\": {\n          const r = i ? `${styleText(\"gray\", S_BAR)}  ` : \"\", o = wrapTextWithPrefix(\n            t.output,\n            a(this.options[this.cursor], \"cancelled\"),\n            r\n          );\n          return `${u}${o}${i ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n        }\n        default: {\n          const r = i ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", o = u.split(`\n`).length, $ = formatInstructionFooter(SELECT_INSTRUCTIONS, i), h = $.join(`\n`), b = $.length + 1;\n          return `${u}${r}${limitOptions({\n            output: t.output,\n            cursor: this.cursor,\n            options: this.options,\n            maxItems: t.maxItems,\n            columnPadding: r.length,\n            rowPadding: o + b,\n            style: (p, x) => a(p, p.disabled ? \"disabled\" : x ? \"active\" : \"inactive\")\n          }).join(`\n${r}`)}\n${h}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst selectKey = (t) => {\n  const l = (e, a = \"inactive\") => {\n    const n = e.label ?? String(e.value);\n    return a === \"selected\" ? `${styleText(\"dim\", n)}` : a === \"cancelled\" ? `${styleText([\"strikethrough\", \"dim\"], n)}` : a === \"active\" ? `${styleText([\"bgCyan\", \"gray\"], ` ${e.value} `)} ${n}${e.hint ? ` ${styleText(\"dim\", `(${e.hint})`)}` : \"\"}` : `${styleText([\"gray\", \"bgWhite\", \"inverse\"], ` ${e.value} `)} ${n}${e.hint ? ` ${styleText(\"dim\", `(${e.hint})`)}` : \"\"}`;\n  };\n  return new SelectKeyPrompt({\n    options: t.options,\n    signal: t.signal,\n    input: t.input,\n    output: t.output,\n    initialValue: t.initialValue,\n    caseSensitive: t.caseSensitive,\n    render() {\n      const e = t.withGuide ?? settings.withGuide, a = `${e ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  ${t.message}\n`;\n      switch (this.state) {\n        case \"submit\": {\n          const n = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", s = this.options.find((u) => u.value === this.value) ?? t.options[0], c = wrapTextWithPrefix(\n            t.output,\n            l(s, \"selected\"),\n            n\n          );\n          return `${a}${c}`;\n        }\n        case \"cancel\": {\n          const n = e ? `${styleText(\"gray\", S_BAR)}  ` : \"\", s = wrapTextWithPrefix(\n            t.output,\n            l(this.options[0], \"cancelled\"),\n            n\n          );\n          return `${a}${s}${e ? `\n${styleText(\"gray\", S_BAR)}` : \"\"}`;\n        }\n        default: {\n          const n = e ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", s = e ? styleText(\"cyan\", S_BAR_END) : \"\", c = this.options.map(\n            (u, $) => wrapTextWithPrefix(\n              t.output,\n              l(u, $ === this.cursor ? \"active\" : \"inactive\"),\n              n\n            )\n          ).join(`\n`);\n          return `${a}${c}\n${s}\n`;\n        }\n      }\n    }\n  }).prompt();\n};\n\nconst i = `${styleText(\"gray\", S_BAR)}  `;\nconst stream = {\n  message: async (e, { symbol: l = styleText(\"gray\", S_BAR) } = {}) => {\n    process.stdout.write(`${styleText(\"gray\", S_BAR)}\n${l}  `);\n    let s = 3;\n    for await (let r of e) {\n      r = r.replace(/\\n/g, `\n${i}`), r.includes(`\n`) && (s = 3 + stripVTControlCharacters(r.slice(r.lastIndexOf(`\n`))).length);\n      const o = stripVTControlCharacters(r).length;\n      s + o < process.stdout.columns ? (s += o, process.stdout.write(r)) : (process.stdout.write(`\n${i}${r.trimStart()}`), s = 3 + stripVTControlCharacters(r.trimStart()).length);\n    }\n    process.stdout.write(`\n`);\n  },\n  info: (e) => stream.message(e, { symbol: styleText(\"blue\", S_INFO) }),\n  success: (e) => stream.message(e, { symbol: styleText(\"green\", S_SUCCESS) }),\n  step: (e) => stream.message(e, { symbol: styleText(\"green\", S_STEP_SUBMIT) }),\n  warn: (e) => stream.message(e, { symbol: styleText(\"yellow\", S_WARN) }),\n  /** alias for `log.warn()`. */\n  warning: (e) => stream.warn(e),\n  error: (e) => stream.message(e, { symbol: styleText(\"red\", S_ERROR) })\n};\n\nconst tasks = async (o, e) => {\n  for (const t of o) {\n    if (t.enabled === false) continue;\n    const s = spinner(e);\n    s.start(t.title);\n    const n = await t.task(s.message);\n    s.stop(n || t.title);\n  }\n};\n\nconst A = (l) => l.replace(/\\x1b\\[(?:\\d+;)*\\d*[ABCDEFGHfJKSTsu]|\\x1b\\[(s|u)/g, \"\");\nconst taskLog = (l) => {\n  const r = l.output ?? process.stdout, O = getColumns(r), i = styleText(\"gray\", S_BAR), p = l.spacing ?? 1, k = 3, m = l.retainLog === true, d = !isCI() && isTTY(r);\n  r.write(`${i}\n`), r.write(`${styleText(\"green\", S_STEP_SUBMIT)}  ${l.title}\n`);\n  for (let e = 0; e < p; e++)\n    r.write(`${i}\n`);\n  const n = [\n    {\n      value: \"\",\n      full: \"\"\n    }\n  ];\n  let v = false;\n  const f = (e) => {\n    if (n.length === 0)\n      return;\n    let s = 0;\n    e && (s += p + 2);\n    for (const t of n) {\n      const { value: o, result: a } = t;\n      let g = a?.message ?? o;\n      if (g.length === 0)\n        continue;\n      a === void 0 && t.header !== void 0 && t.header !== \"\" && (g += `\n${t.header}`);\n      const x = g.split(`\n`).reduce((b, w) => w === \"\" ? b + 1 : b + Math.ceil((w.length + k) / O), 0);\n      s += x;\n    }\n    s > 0 && (s += 1, r.write(erase.lines(s)));\n  }, h = (e, s, t) => {\n    const o = t ? `${e.full}\n${e.value}` : e.value;\n    e.header !== void 0 && e.header !== \"\" && log.message(\n      e.header.split(`\n`).map((a) => styleText(\"bold\", a)),\n      {\n        output: r,\n        secondarySymbol: i,\n        symbol: i,\n        spacing: 0\n      }\n    ), log.message(\n      o.split(`\n`).map((a) => styleText(\"dim\", a)),\n      {\n        output: r,\n        secondarySymbol: i,\n        symbol: i,\n        spacing: s ?? p\n      }\n    );\n  }, T = () => {\n    for (const e of n) {\n      const { header: s, value: t, full: o } = e;\n      (s === void 0 || s.length === 0) && t.length === 0 || h(e, void 0, m === true && o.length > 0);\n    }\n  }, L = (e, s, t) => {\n    if (f(false), (t?.raw !== true || !v) && e.value !== \"\" && (e.value += `\n`), e.value += A(s), v = t?.raw === true, l.limit !== void 0) {\n      const o = e.value.split(`\n`), a = o.length - l.limit;\n      if (a > 0) {\n        const g = o.splice(0, a);\n        m && (e.full += (e.full === \"\" ? \"\" : `\n`) + g.join(`\n`));\n      }\n      e.value = o.join(`\n`);\n    }\n    d && y();\n  }, y = () => {\n    for (const e of n)\n      e.result ? e.result.status === \"error\" ? log.error(e.result.message, { output: r, secondarySymbol: i, spacing: 0 }) : log.success(e.result.message, { output: r, secondarySymbol: i, spacing: 0 }) : e.value !== \"\" && h(e, 0);\n  }, B = (e, s) => {\n    f(false), e.result = s, d && y();\n  };\n  return {\n    message(e, s) {\n      L(n[0], e, s);\n    },\n    group(e) {\n      const s = {\n        header: e,\n        value: \"\",\n        full: \"\"\n      };\n      return n.push(s), {\n        message(t, o) {\n          L(s, t, o);\n        },\n        error(t) {\n          B(s, {\n            status: \"error\",\n            message: t\n          });\n        },\n        success(t) {\n          B(s, {\n            status: \"success\",\n            message: t\n          });\n        }\n      };\n    },\n    error(e, s) {\n      f(true), log.error(e, { output: r, secondarySymbol: i, spacing: 1 }), s?.showLog !== false && T(), n.splice(1, n.length - 1), n[0].value = \"\", n[0].full = \"\";\n    },\n    success(e, s) {\n      f(true), log.success(e, { output: r, secondarySymbol: i, spacing: 1 }), s?.showLog === true && T(), n.splice(1, n.length - 1), n[0].value = \"\", n[0].full = \"\";\n    }\n  };\n};\n\nconst text = (t) => new TextPrompt({\n  validate: t.validate,\n  placeholder: t.placeholder,\n  defaultValue: t.defaultValue,\n  initialValue: t.initialValue,\n  output: t.output,\n  signal: t.signal,\n  input: t.input,\n  render() {\n    const i = t?.withGuide ?? settings.withGuide, s = `${`${i ? `${styleText(\"gray\", S_BAR)}\n` : \"\"}${symbol(this.state)}  `}${t.message}\n`, c = t.placeholder ? styleText(\"inverse\", t.placeholder[0]) + styleText(\"dim\", t.placeholder.slice(1)) : styleText([\"inverse\", \"hidden\"], \"_\"), o = this.userInput ? this.userInputWithCursor : c, a = this.value ?? \"\";\n    switch (this.state) {\n      case \"error\": {\n        const n = this.error ? `  ${styleText(\"yellow\", this.error)}` : \"\", r = i ? `${styleText(\"yellow\", S_BAR)}  ` : \"\", d = i ? styleText(\"yellow\", S_BAR_END) : \"\";\n        return `${s.trim()}\n${r}${o}\n${d}${n}\n`;\n      }\n      case \"submit\": {\n        const n = a ? `  ${styleText(\"dim\", a)}` : \"\", r = i ? styleText(\"gray\", S_BAR) : \"\";\n        return `${s}${r}${n}`;\n      }\n      case \"cancel\": {\n        const n = a ? `  ${styleText([\"strikethrough\", \"dim\"], a)}` : \"\", r = i ? styleText(\"gray\", S_BAR) : \"\";\n        return `${s}${r}${n}${a.trim() ? `\n${r}` : \"\"}`;\n      }\n      default: {\n        const n = i ? `${styleText(\"cyan\", S_BAR)}  ` : \"\", r = i ? styleText(\"cyan\", S_BAR_END) : \"\";\n        return `${s}${n}${o}\n${r}\n`;\n      }\n    }\n  }\n}).prompt();\n\nexport { MULTISELECT_INSTRUCTIONS, SELECT_INSTRUCTIONS, S_BAR, S_BAR_END, S_BAR_END_RIGHT, S_BAR_H, S_BAR_START, S_BAR_START_RIGHT, S_CHECKBOX_ACTIVE, S_CHECKBOX_INACTIVE, S_CHECKBOX_SELECTED, S_CONNECT_LEFT, S_CORNER_BOTTOM_LEFT, S_CORNER_BOTTOM_RIGHT, S_CORNER_TOP_LEFT, S_CORNER_TOP_RIGHT, S_ERROR, S_INFO, S_PASSWORD_MASK, S_RADIO_ACTIVE, S_RADIO_INACTIVE, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, S_SUCCESS, S_WARN, autocomplete, autocompleteMultiselect, box, cancel, confirm, date, formatInstructionFooter, group, groupMultiselect, intro, isCI, isTTY, limitOptions, log, multiline, multiselect, note, outro, password, path, progress, select, selectKey, spinner, stream, symbol, symbolBar, taskLog, tasks, text, unicode, unicodeOr };\n", "import { existsSync, readFileSync } from \"node:fs\";\nimport { lstat } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { Adapter, AdapterResult } from \"@skillet/core\";\nimport { loadIdentity, runtimeLabel } from \"@skillet/core\";\nimport { claudeCodeAdapter } from \"@skillet/adapters-claude-code\";\nimport { codexAdapter, codexProjectAdapter } from \"@skillet/adapters-codex\";\nimport { openclawAdapter } from \"@skillet/adapters-openclaw\";\nimport { hermesAdapter } from \"@skillet/adapters-hermes\";\nimport { cursorAdapter } from \"@skillet/adapters-cursor\";\nimport { windsurfAdapter } from \"@skillet/adapters-windsurf\";\nimport { devinAdapter } from \"@skillet/adapters-devin\";\nimport { opencodeAdapter } from \"@skillet/adapters-opencode\";\nimport { BUNDLED_ROUTE_SLUG } from \"@skillet/core\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\ndeclare const __SKILLET_CLI_VERSION__: string | undefined;\n\n/** Version from package.json in dev; injected at esbuild bundle time for pkg sidecars. */\nexport const CLI_VERSION =\n  typeof __SKILLET_CLI_VERSION__ !== \"undefined\"\n    ? __SKILLET_CLI_VERSION__\n    : (JSON.parse(\n        readFileSync(join(__dirname, \"..\", \"package.json\"), \"utf8\"),\n      ) as { version: string }).version;\n\n// Expose the client version to @skillet/core's RegistryClient (which sends it as\n// X-Skillet-Client-Version for the min-supported-version gate) without core\n// importing the CLI. Same process, so the env var reaches core's client.\nif (!process.env[\"SKILLET_CLIENT_VERSION\"]) {\n  process.env[\"SKILLET_CLIENT_VERSION\"] = CLI_VERSION;\n}\n\n/** Global universal baseline \u2014 always materializes to `~/.agents/skills`. */\nexport const BASELINE_GLOBAL_ADAPTERS: Adapter[] = [codexAdapter];\n\n/** Re-export for tier resolution (repo `.agents/skills` when in a project). */\nexport { codexProjectAdapter };\n\n/** Opt-in runtimes beyond the universal `.agents/skills` baseline. */\nexport const ADDITIONAL_ADAPTERS: Adapter[] = [\n  claudeCodeAdapter,\n  openclawAdapter,\n  hermesAdapter,\n  cursorAdapter,\n  windsurfAdapter,\n  devinAdapter,\n];\n\n/** Full runtime adapter set \u2014 order matches core/sync iteration and human output. */\nexport const ALL_ADAPTERS: Adapter[] = [\n  ...BASELINE_GLOBAL_ADAPTERS,\n  ...ADDITIONAL_ADAPTERS,\n];\n\n/**\n * Agents that READ the universal `~/.agents/skills` baseline rather than\n * materializing into their own directory. opencode reads that path (same as the\n * Codex baseline), so it must NOT join the materializing set \u2014 that would\n * double-write and double-count one materialization. Instead it is surfaced\n * here for detection/labeling in `skillet runtimes` (and the desktop tray\n * facepile) so users see opencode as a runtime whose skills live in the shared\n * baseline dir. Detection is opencode-specific (`~/.config/opencode`).\n */\nexport const BASELINE_READER_ADAPTERS: Adapter[] = [opencodeAdapter];\n\nexport function statusGlyph(status: AdapterResult[\"status\"]): string {\n  switch (status) {\n    case \"materialized\":\n      return \"\u2713\";\n    case \"skipped-not-detected\":\n      return \"\u00B7\";\n    case \"failed\":\n      return \"\u2717\";\n  }\n}\n\n/**\n * Human display name for an adapter, from the same single source of truth as\n * `skillet runtimes` \u2014 so `windsurf` reads \"Devin Desktop\" (Cognition's June\n * 2026 rebrand of the Windsurf editor) and never gets mistaken for the separate\n * `devin` (Devin CLI/Local) row. Mirrors the runtimes codex special-case: the\n * universal `~/.agents/skills` baseline is only labeled \"Codex\" on direct\n * evidence (`~/.codex`), else the honest \"Universal\".\n */\nexport function adapterDisplayLabel(name: string): string {\n  if (name === \"codex\" && existsSync(join(homedir(), \".codex\"))) return \"Codex\";\n  return runtimeLabel(name);\n}\n\nexport function renderAdapterLine(r: AdapterResult): string {\n  const glyph = statusGlyph(r.status);\n  const label = adapterDisplayLabel(r.name);\n  if (r.status === \"materialized\") {\n    return `  ${glyph} ${label}: ${r.count} skill${r.count === 1 ? \"\" : \"s\"} \u2192 ${r.targetDir}`;\n  }\n  if (r.status === \"skipped-not-detected\") {\n    return `  ${glyph} ${label}: not detected`;\n  }\n  return `  ${glyph} ${label}: failed \u2014 ${r.error ?? \"unknown error\"}`;\n}\n\n/** commander `collect` accumulator for repeatable options. */\nexport function collect(value: string, previous: string[]): string[] {\n  return previous.concat([value]);\n}\n\nexport async function pathExists(p: string): Promise<boolean> {\n  try {\n    await lstat(p);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/** Skills a person manages: everything in state except Skillet's own bundled\n *  /skillet router, which is plumbing and never counts as \"your skills\". */\nexport function countUserSkills(state: { skills: Record<string, unknown> }): number {\n  return Object.keys(state.skills).filter((slug) => slug !== BUNDLED_ROUTE_SLUG).length;\n}\n\nexport const REGISTRY_DEFAULT =\n  process.env[\"SKILLET_REGISTRY_URL\"] ??\n  process.env[\"SKILLET_REGISTRY\"] ??\n  \"https://registry.skillet.md\";\n\n/** Resolve the registry base URL for a registry-scoped command: explicit\n *  override, then stored identity, then env, then the default \u2014 trailing slash\n *  stripped. Centralizes the coalesce so commands don't each re-implement it. */\nexport async function resolveRegistryUrl(opts: { registry?: string } = {}): Promise<string> {\n  const identity = await loadIdentity();\n  return (\n    opts.registry ??\n    identity?.registryUrl ??\n    process.env[\"SKILLET_REGISTRY_URL\"] ??\n    REGISTRY_DEFAULT\n  ).replace(/\\/$/, \"\");\n}\n\n/** Registry URL for kit/team commands. */\nexport const REGISTRY_DEFAULT_TEAM =\n  process.env[\"SKILLET_REGISTRY_URL\"] ??\n  process.env[\"SKILLET_REGISTRY\"] ??\n  \"https://registry.skillet.md\";\n", "import { join, sep, dirname } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { access } from \"node:fs/promises\";\nimport type { Adapter, MaterializeOptions, TargetPathOptions } from \"@skillet/core\";\nimport type { DecodedBundle } from \"@skillet/core\";\nimport {\n  assertSafeSlug,\n  materializeSlugDir,\n  validateMaterializationPath,\n  writeBundleToDir,\n  CLAUDE_ENV_ROOT,\n} from \"@skillet/core\";\n\nexport type { Adapter };\n\n// Claude Code's own resolver is `CLAUDE_CONFIG_DIR ?? ~/.claude` with skills\n// under `<root>/skills` (verified against the 2.1.206 binary). When the env\n// var is set, `~/.claude/skills` is a directory Claude Code never reads \u2014\n// detection and materialization must both follow the resolved root.\nconst CLAUDE_SKILLS_DIR = CLAUDE_ENV_ROOT ?? join(homedir(), \".claude\", \"skills\");\n\nexport async function detect(): Promise<boolean> {\n  try {\n    await access(dirname(CLAUDE_SKILLS_DIR));\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function materialize(\n  slug: string,\n  bundle: DecodedBundle,\n  opts: MaterializeOptions = {},\n): Promise<string[]> {\n  assertSafeSlug(slug);\n  const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n  validateMaterializationPath(CLAUDE_SKILLS_DIR, slugDir);\n  return writeBundleToDir(CLAUDE_SKILLS_DIR, slugDir, bundle);\n}\n\nexport function targetPath(\n  slug: string,\n  opts: TargetPathOptions = {},\n): string {\n  assertSafeSlug(slug);\n  const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n  const rel = `${slugDir}/SKILL.md`;\n  const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n  return join(CLAUDE_SKILLS_DIR, hostRel);\n}\n\nexport function targetSkillDir(\n  slug: string,\n  opts: TargetPathOptions = {},\n): string {\n  assertSafeSlug(slug);\n  return join(CLAUDE_SKILLS_DIR, materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n}\n\nexport const claudeCodeAdapter: Adapter = {\n  name: \"claude-code\",\n  targetDir: CLAUDE_SKILLS_DIR,\n  detect,\n  materialize,\n  targetPath,\n  targetSkillDir,\n};\n\nexport default claudeCodeAdapter;\n", "import { join, sep, resolve, dirname } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { access } from \"node:fs/promises\";\nimport type { Adapter, MaterializeOptions, TargetPathOptions } from \"@skillet/core\";\nimport type { DecodedBundle } from \"@skillet/core\";\nimport {\n  assertSafeSlug,\n  materializeSlugDir,\n  validateMaterializationPath,\n  validateProjectAdapterRoot,\n  writeBundleToDir,\n} from \"@skillet/core\";\n\nexport type { Adapter };\n\n// Codex global skills live at ~/.agents/skills (repo scope shipped in\n// rust-v0.94.0, 2026-02-02; personal ~/.agents/skills in rust-v0.95.0,\n// 2026-02-04). The previous path (~/.codex/skills) is a deprecated back-compat\n// location Codex STILL READS \u2014 so pre-move copies surface as duplicates in\n// skill selectors, cleaned up by sync's cleanupLegacyCodexSkills. We detect\n// either directory so Skillet claims hosts with the old dir installed, but we\n// only materialize into the supported path.\nconst DEFAULT_TARGET_DIR = join(homedir(), \".agents\", \"skills\");\nconst LEGACY_DETECT_DIR = join(homedir(), \".codex\");\nconst PRIMARY_DETECT_DIR = join(homedir(), \".agents\");\n\n// Relative POSIX path under the project root; must match PROJECT_TARGET_ALLOWLIST.\nconst PROJECT_TARGET_DIR = \".agents/skills\";\n\n/**\n * Walk up from startDir looking for the nearest ancestor directory that marks\n * a project root. Returns the absolute path of the first match, or null if the\n * filesystem root is reached without a match.\n *\n * Markers are `.git` (Codex's own project-root default) and `.agents` (whose\n * presence proves a prior project materialization). `package.json` was dropped\n * (2026-07): it made a bare Node package with no git dir route project-scoped,\n * diverging from Codex, which keys project scope on the repo root.\n *\n * Codex resolution precedence when the same skill name appears in multiple\n * scopes: project (repo `.agents/skills`) > user (`~/.agents/skills`) > admin.\n * Skillet writes to the repo path when a project root is detected via this\n * walk-up; otherwise it writes to the user path.\n */\nexport async function findProjectRoot(startDir: string): Promise<string | null> {\n  let current = resolve(startDir);\n  while (true) {\n    for (const marker of [\".git\", \".agents\"]) {\n      try {\n        await access(join(current, marker));\n        return current;\n      } catch {\n        // marker not present in this directory; continue\n      }\n    }\n    const parent = dirname(current);\n    if (parent === current) return null; // reached filesystem root\n    current = parent;\n  }\n}\n\nexport function createAdapter(baseDir = DEFAULT_TARGET_DIR): Adapter {\n  return {\n    name: \"codex\",\n    targetDir: baseDir,\n\n    async detect(): Promise<boolean> {\n      for (const dir of [PRIMARY_DETECT_DIR, LEGACY_DETECT_DIR]) {\n        try {\n          await access(dir);\n          return true;\n        } catch {\n          // try next\n        }\n      }\n      return false;\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      validateMaterializationPath(baseDir, slugDir);\n      return writeBundleToDir(baseDir, slugDir, bundle);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      const rel = `${slugDir}/SKILL.md`;\n      const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n      return join(baseDir, hostRel);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      return join(baseDir, materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n    },\n  };\n}\n\nexport function createProjectAdapter(): Adapter {\n  const adapter: Adapter = {\n    name: \"codex-project\",\n    kind: \"project\",\n    targetDir: PROJECT_TARGET_DIR,\n\n    async detect(): Promise<boolean> {\n      const root = await findProjectRoot(process.cwd());\n      return root !== null;\n    },\n\n    projectRoot(cwd: string): string {\n      // Given the project root directory, return the absolute write root.\n      // Used by validateProjectAdapterRoot for structural safety checks.\n      return join(cwd, \".agents\", \"skills\");\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      const startDir = opts.cwd ?? process.cwd();\n      assertSafeSlug(slug);\n      const projRoot = await findProjectRoot(startDir);\n      if (!projRoot) {\n        throw new Error(\n          `No project root found from \"${startDir}\" \u2014 expected .agents/, .git/, or package.json in an ancestor directory`,\n        );\n      }\n      validateProjectAdapterRoot(adapter, projRoot);\n      const absRoot = join(projRoot, \".agents\", \"skills\");\n      // Guard: if the walk-up resolved to homedir (e.g. ~/.agents/ exists),\n      // absRoot would silently equal the global adapter's target. Decline so\n      // the caller falls through to the global codexAdapter instead.\n      if (resolve(absRoot) === resolve(join(homedir(), \".agents\", \"skills\"))) {\n        throw new Error(\n          `No project-specific root found from \"${startDir}\" \u2014 walk-up resolved to the global Codex path. Use codexAdapter (global) instead.`,\n        );\n      }\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      return writeBundleToDir(absRoot, slugDir, bundle);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      const cwd = opts.cwd ?? process.cwd();\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      const rel = `${slugDir}/SKILL.md`;\n      const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n      return join(cwd, \".agents\", \"skills\", hostRel);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      const cwd = opts.cwd ?? process.cwd();\n      assertSafeSlug(slug);\n      return join(cwd, \".agents\", \"skills\", materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n    },\n  };\n  return adapter;\n}\n\nexport const codexAdapter: Adapter = createAdapter();\nexport const codexProjectAdapter: Adapter = createProjectAdapter();\nexport default codexAdapter;\n", "import { join, sep } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { access, readFile, readdir, lstat } from \"node:fs/promises\";\nimport type {\n  Adapter,\n  MaterializeOptions,\n  ShadowFinding,\n  ShadowFindOptions,\n  TargetPathOptions,\n} from \"@skillet/core\";\nimport type { DecodedBundle } from \"@skillet/core\";\nimport {\n  assertSafeSlug,\n  materializeSlugDir,\n  validateMaterializationPath,\n  writeBundleToDir,\n} from \"@skillet/core\";\n\nexport type { Adapter };\n\nconst DEFAULT_TARGET_DIR = join(homedir(), \".openclaw\", \"skills\");\n\n// OpenClaw discovers a skill wherever a SKILL.md appears (up to six levels\n// deep) and identifies it by frontmatter `name`, falling back to the dir name\n// \u2014 the folder path is organizational only. Support dirs it never treats as\n// skill roots (mirrors OpenClaw's own excluded set).\nconst SHADOW_WALK_DEPTH = 6;\nconst SUPPORT_DIRS = new Set([\"references\", \"templates\", \"assets\", \"scripts\", \"node_modules\"]);\n\n/** Frontmatter `name:` from SKILL.md text, or null. */\nfunction frontmatterName(text: string): string | null {\n  const fm = text.match(/^---\\n([\\s\\S]*?)\\n---/);\n  if (!fm) return null;\n  const m = fm[1]!.match(/^name:\\s*(.+)$/m);\n  return m ? m[1]!.trim().replace(/^[\"']|[\"']$/g, \"\") : null;\n}\n\n/**\n * Walk `root` up to `SHADOW_WALK_DEPTH` levels for SKILL.md files, yielding\n * `{ path, name }` per skill (name = frontmatter name, else containing dir\n * name). lstat-based: never follows symlinks out of the root; skips support\n * dirs. Never throws \u2014 a missing/unreadable path yields nothing.\n */\nasync function collectSkills(\n  root: string,\n  depth: number,\n): Promise<Array<{ path: string; name: string }>> {\n  if (depth < 0) return [];\n  let entries: import(\"node:fs\").Dirent[];\n  try {\n    entries = await readdir(root, { withFileTypes: true });\n  } catch {\n    return [];\n  }\n  const out: Array<{ path: string; name: string }> = [];\n  for (const e of entries) {\n    if (e.isSymbolicLink()) continue; // never follow symlinks off-root\n    if (e.name === \"SKILL.md\" && e.isFile()) {\n      const filePath = join(root, e.name);\n      try {\n        const text = await readFile(filePath, \"utf8\");\n        out.push({ path: filePath, name: frontmatterName(text) ?? basenameOf(root) });\n      } catch {\n        // unreadable \u2192 skip\n      }\n    } else if (e.isDirectory() && !SUPPORT_DIRS.has(e.name)) {\n      out.push(...(await collectSkills(join(root, e.name), depth - 1)));\n    }\n  }\n  return out;\n}\n\nfunction basenameOf(p: string): string {\n  const parts = p.split(sep);\n  return parts[parts.length - 1] ?? p;\n}\n\n// OpenClaw resolves skills across six precedence levels (docs.openclaw.ai\n// /tools/skills-config). Skillet materializes into ~/.openclaw/skills \u2014 level\n// #4. These three higher-precedence locations silently override it when\n// they hold a same-slug SKILL.md, so we surface them as shadows on sync.\nfunction shadowSearchPaths(\n  workspaceDir: string | undefined,\n): Array<{ root: string; location: string }> {\n  const paths: Array<{ root: string; location: string }> = [];\n  if (workspaceDir) {\n    paths.push({\n      root: join(workspaceDir, \"skills\"),\n      location: \"<workspace>/skills\",\n    });\n    paths.push({\n      root: join(workspaceDir, \".agents\", \"skills\"),\n      location: \"<workspace>/.agents/skills\",\n    });\n  }\n  paths.push({\n    root: join(homedir(), \".agents\", \"skills\"),\n    location: \"~/.agents/skills\",\n  });\n  return paths;\n}\n\nexport function createAdapter(baseDir = DEFAULT_TARGET_DIR): Adapter {\n  return {\n    name: \"openclaw\",\n    targetDir: baseDir,\n\n    async detect(): Promise<boolean> {\n      try {\n        await access(join(homedir(), \".openclaw\"));\n        return true;\n      } catch {\n        return false;\n      }\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      validateMaterializationPath(baseDir, slugDir);\n      return writeBundleToDir(baseDir, slugDir, bundle);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      const rel = `${slugDir}/SKILL.md`;\n      const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n      return join(baseDir, hostRel);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      return join(baseDir, materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n    },\n\n    async findShadows(\n      slug: string,\n      opts: ShadowFindOptions = {},\n    ): Promise<ShadowFinding[]> {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n\n      // OpenClaw keys skill identity on the frontmatter `name`, not the folder\n      // name \u2014 so a higher-precedence skill under ANY folder shadows ours when\n      // its name matches. Resolve our own effective name from the SKILL.md we\n      // just materialized (frontmatter name, else our dir name), then scan the\n      // higher-precedence roots by name. Falls back to the dir name if our copy\n      // is unreadable.\n      let ourName = slugDir;\n      try {\n        const ours = await readFile(join(baseDir, slugDir, \"SKILL.md\"), \"utf8\");\n        ourName = frontmatterName(ours) ?? slugDir;\n      } catch {\n        // use dir name\n      }\n\n      const findings: ShadowFinding[] = [];\n      for (const { root, location } of shadowSearchPaths(opts.workspaceDir)) {\n        try {\n          await lstat(root);\n        } catch {\n          continue; // missing higher-precedence root is the common case\n        }\n        for (const found of await collectSkills(root, SHADOW_WALK_DEPTH)) {\n          if (found.name === ourName) findings.push({ path: found.path, location });\n        }\n      }\n      return findings;\n    },\n  };\n}\n\nexport const openclawAdapter: Adapter = createAdapter();\nexport default openclawAdapter;\n", "import { join, sep } from \"node:path\";\nimport { access } from \"node:fs/promises\";\nimport type { Adapter, MaterializeOptions, TargetPathOptions } from \"@skillet/core\";\nimport type { DecodedBundle } from \"@skillet/core\";\nimport {\n  assertSafeSlug,\n  materializeSlugDir,\n  HERMES_DEFAULT_HOME,\n  HERMES_PROFILE_ROOT,\n  validateMaterializationPath,\n  writeBundleToDir,\n} from \"@skillet/core\";\n\nexport type { Adapter };\n\nfunction resolveDefaultTargetDir(): string {\n  // Precedence: active profile tree (Hermes scans ONLY the active profile's\n  // skills; the sticky ~/.hermes/active_profile file names it), else the\n  // home tree. HERMES_HOME composes upstream: both HERMES_PROFILE_ROOT and\n  // HERMES_DEFAULT_HOME already honor it (resolved once in pathsafe).\n  if (HERMES_PROFILE_ROOT !== null) return HERMES_PROFILE_ROOT;\n  return join(HERMES_DEFAULT_HOME, \"skills\");\n}\n\nfunction resolveDetectDir(): string {\n  // detect() checks the hermes home itself \u2014 profile presence changes where\n  // skills go, not whether Hermes is installed.\n  return HERMES_DEFAULT_HOME;\n}\n\nconst DEFAULT_TARGET_DIR = resolveDefaultTargetDir();\n\nexport function createAdapter(baseDir = DEFAULT_TARGET_DIR): Adapter {\n  return {\n    name: \"hermes\",\n    targetDir: baseDir,\n\n    async detect(): Promise<boolean> {\n      try {\n        await access(resolveDetectDir());\n        return true;\n      } catch {\n        return false;\n      }\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      validateMaterializationPath(baseDir, slugDir);\n      return writeBundleToDir(baseDir, slugDir, bundle);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      const rel = `${slugDir}/SKILL.md`;\n      const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n      return join(baseDir, hostRel);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      return join(baseDir, materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n    },\n  };\n}\n\nexport const hermesAdapter: Adapter = createAdapter();\nexport default hermesAdapter;\n", "import { join, dirname, resolve } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { access } from \"node:fs/promises\";\nimport type { Adapter, MaterializeOptions, TargetPathOptions } from \"@skillet/core\";\nimport type { DecodedBundle } from \"@skillet/core\";\nimport {\n  assertSafeSlug,\n  applyAdapterTransform,\n  materializeSlugDir,\n  resolveSkillDescription,\n  validateProjectAdapterRoot,\n  writeFilesToRoot,\n} from \"@skillet/core\";\n\nexport type { Adapter };\n\n/** Relative POSIX path under the project root where Cursor loads rules. */\nexport const TARGET_DIR = \".cursor/rules\";\n\n/**\n * Walk up from `startDir` to the nearest ancestor containing `.cursor/`,\n * `.git/`, or `package.json`. Falls back to `startDir` itself.\n */\nexport function findProjectRoot(startDir: string): string {\n  let dir = startDir;\n    while (true) {\n      if (\n        existsSync(join(dir, \".cursor\", \"rules\")) ||\n        existsSync(join(dir, \".git\")) ||\n        existsSync(join(dir, \"package.json\"))\n      ) {\n        return dir;\n      }\n    const parent = dirname(dir);\n    if (parent === dir) break; // reached filesystem root\n    dir = parent;\n  }\n  return startDir;\n}\n\n/** Canonical path for directory comparisons (macOS /var vs /private/var after chdir). */\nfunction canonicalDir(dir: string): string {\n  try {\n    return realpathSync(dir);\n  } catch {\n    return resolve(dir);\n  }\n}\n\nasync function hasCursorRules(dir: string): Promise<boolean> {\n  try {\n    await access(join(dir, \".cursor\", \"rules\"));\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nasync function walkUpForCursorRules(startDir: string): Promise<string | null> {\n  let dir = startDir;\n  while (true) {\n    if (await hasCursorRules(dir)) return dir;\n    const parent = dirname(dir);\n    if (parent === dir) break;\n    dir = parent;\n  }\n  return null;\n}\n\n/**\n * Resolve a project directory that contains `.cursor/rules` by walking UP from\n * the real cwd. Deliberately does NOT scan the user's dev folders (~/Documents,\n * ~/code, \u2026): that crawl injected `.cursor/rules` into every project AND tripped\n * a macOS TCC \"access your Documents folder\" prompt. Cursor reads skills from the\n * global `~/.agents/skills` Skillet already writes (cursor.com/docs/skills), so\n * `.cursor/rules` materialize only happens when the CLI is run from a project.\n */\nexport async function resolveCursorRulesProject(\n  startDir: string,\n): Promise<string | null> {\n  const fromWalk = await walkUpForCursorRules(startDir);\n  return fromWalk ? canonicalDir(fromWalk) : null;\n}\n\n/**\n * Parse YAML frontmatter from SKILL.md content.\n * Returns the frontmatter key\u2192value map and the body (content after the closing ---).\n */\nfunction parseSkillMdFrontmatter(content: string): {\n  frontmatter: Record<string, string>;\n  body: string;\n} {\n  if (!content.startsWith(\"---\\n\")) {\n    return { frontmatter: {}, body: content };\n  }\n  const end = content.indexOf(\"\\n---\\n\", 4);\n  if (end === -1) {\n    return { frontmatter: {}, body: content };\n  }\n  const fmText = content.slice(4, end);\n  const body = content.slice(end + 5);\n  const frontmatter: Record<string, string> = {};\n  const lines = fmText.split(\"\\n\");\n  for (let i = 0; i < lines.length; i++) {\n    const line = lines[i];\n    // Only top-level (unindented) lines start a key. Indented lines belong to a\n    // preceding multi-line value or nested mapping and are consumed below \u2014\n    // without this, a multi-line `description:` (value on the next indented\n    // lines) parsed as empty and the adapter wrongly rejected the whole skill.\n    if (/^\\s/.test(line)) continue;\n    const colon = line.indexOf(\":\");\n    if (colon === -1) continue;\n    const key = line.slice(0, colon).trim();\n    let val = line.slice(colon + 1).trim();\n    const blockScalar = /^[|>][+-]?$/.test(val); // `|`, `>`, `|-`, `>-`\n    if (val === \"\" || blockScalar) {\n      // Gather the following indented lines. Literal (`|`) keeps newlines; plain\n      // (empty) and folded (`>`) join with spaces, matching YAML folding.\n      const literal = val.startsWith(\"|\");\n      const collected: string[] = [];\n      while (i + 1 < lines.length && /^\\s+\\S/.test(lines[i + 1])) {\n        collected.push(lines[i + 1].replace(/^\\s+/, \"\"));\n        i++;\n      }\n      val = collected.join(literal ? \"\\n\" : \" \").trim();\n    } else if (\n      (val.startsWith('\"') && val.endsWith('\"')) ||\n      (val.startsWith(\"'\") && val.endsWith(\"'\"))\n    ) {\n      val = val.slice(1, -1);\n    }\n    frontmatter[key] = val;\n  }\n  return { frontmatter, body };\n}\n\nexport function createAdapter(): Adapter {\n  const adapter: Adapter = {\n    name: \"cursor\",\n    kind: \"project\",\n    targetDir: TARGET_DIR,\n\n    projectRoot(cwd: string): string {\n      return join(cwd, \".cursor\", \"rules\");\n    },\n\n    async detect(): Promise<boolean> {\n      // Cursor is INSTALLED \u2014 not \"a .cursor folder exists somewhere\" (which\n      // Skillet's own materialize creates, a self-perpetuating false positive).\n      // Check the app bundle / user data only a real Cursor install produces.\n      for (const p of [\n        \"/Applications/Cursor.app\",\n        join(homedir(), \"Library\", \"Application Support\", \"Cursor\"),\n        join(homedir(), \".config\", \"Cursor\"),\n        join(homedir(), \".cursor\"),\n      ]) {\n        try {\n          await access(p);\n          return true;\n        } catch {\n          // not this one\n        }\n      }\n      return false;\n    },\n\n    async resolveMaterializeCwd(syncCwd: string): Promise<string | null> {\n      return resolveCursorRulesProject(syncCwd);\n    },\n\n    transform(slug: string, bundle: DecodedBundle, opts: MaterializeOptions = {}): DecodedBundle {\n      assertSafeSlug(slug);\n      const prefix = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n\n      const skillMdBytes = bundle.get(\"SKILL.md\");\n      if (!skillMdBytes) {\n        throw new Error(\n          `Cursor adapter: bundle for \"${slug}\" is missing SKILL.md`,\n        );\n      }\n\n      const skillMdContent = Buffer.from(skillMdBytes).toString(\"utf8\");\n      const { frontmatter, body } = parseSkillMdFrontmatter(skillMdContent);\n\n      const { description: desc } = resolveSkillDescription({\n        frontmatterDescription: frontmatter[\"description\"],\n        optsDescription: opts.description,\n        body,\n        slug,\n      });\n\n      // Escape YAML metacharacters via a block scalar (NF-008).\n      const descYaml =\n        desc.includes(\"\\n\") || desc.includes('\"') || desc.includes(\":\") || desc.includes(\"#\")\n          ? `|\\n${desc\n              .split(\"\\n\")\n              .map((line) => `  ${line}`)\n              .join(\"\\n\")}`\n          : `\"${desc.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n      const mdc = `---\\ndescription: ${descYaml}\\nglobs: [\"**/*\"]\\nalwaysApply: false\\n---\\n${body}`;\n\n      const out: DecodedBundle = new Map();\n      out.set(`${prefix}.mdc`, Buffer.from(mdc, \"utf8\"));\n\n      // Nested .mdc files materialize as-is. Cursor discovers rules\n      // recursively under .cursor/rules (documented since 2.2, verified\n      // against the 3.8.11 bundle's `**/.cursor/rules/**/*.mdc` glob), so a\n      // bundled .mdc becomes a live rule with its AUTHOR'S frontmatter \u2014\n      // which is the point of shipping one (e.g. cloudflare/skills'\n      // rules/workers.mdc, an auto-attach rule for JS/TS files). Pre-2.2\n      // Cursor ignores nested .mdc entirely: inert, never harmful. Content\n      // safety stays with the scan/trust gates \u2014 the skill's own generated\n      // rule above already injects its whole body, so a nested rule grants\n      // nothing new.\n      for (const [path, bytes] of bundle) {\n        if (path === \"SKILL.md\") continue;\n        out.set(`${prefix}/${path}`, bytes);\n      }\n\n      return out;\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      if (!opts.cwd) {\n        throw new Error(`Cursor adapter: cwd is required for project-scoped materialize`);\n      }\n      assertSafeSlug(slug);\n      validateProjectAdapterRoot(adapter, opts.cwd);\n      const root = adapter.projectRoot!(opts.cwd);\n      const translated = await applyAdapterTransform(adapter, slug, bundle, opts);\n      return writeFilesToRoot(root, translated);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      if (!opts.cwd) {\n        throw new Error(`Cursor adapter: cwd is required for project-scoped targetPath`);\n      }\n      assertSafeSlug(slug);\n      const prefix = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      return join(adapter.projectRoot!(opts.cwd), `${prefix}.mdc`);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      if (!opts.cwd) {\n        throw new Error(`Cursor adapter: cwd is required for project-scoped targetSkillDir`);\n      }\n      assertSafeSlug(slug);\n      const prefix = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      return join(adapter.projectRoot!(opts.cwd), prefix);\n    },\n  };\n\n  return adapter;\n}\n\nexport const cursorAdapter: Adapter = createAdapter();\nexport default cursorAdapter;\n", "import { join, sep } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { access } from \"node:fs/promises\";\nimport type { Adapter, MaterializeOptions, TargetPathOptions } from \"@skillet/core\";\nimport type { DecodedBundle } from \"@skillet/core\";\nimport {\n  AdapterSkipError,\n  assertSafeSlug,\n  materializeSlugDir,\n  validateMaterializationPath,\n  writeBundleToDir,\n} from \"@skillet/core\";\n\nexport type { Adapter };\n\n// Devin Desktop (n\u00E9 Windsurf, rebranded 2026-06-02) reads native Agent Skills:\n// SKILL.md folders under ~/.codeium/windsurf/skills/ (global) \u2014 the same\n// layout as Claude Code/Codex/Devin, spec at agentskills.io\n// (docs.devin.ai/desktop/cascade/skills). This replaced the old rules-file\n// flattening, which was format-hobbled three ways: activation frontmatter\n// stripped, a 12k-char workspace-rule cap, and supporting files dropped.\n// ~/.codeium/windsurf is stable across the rebrand (FAQ; verified on a fresh\n// Devin.app 3.4.27 install \u2014 the root exists, skills/ is created on first\n// write). The adapter id stays \"windsurf\": it is a wire contract with the\n// tray; only display labels say \"Devin Desktop\".\nconst WINDSURF_SKILLS_DIR = join(homedir(), \".codeium\", \"windsurf\", \"skills\");\nconst WINDSURF_ROOT = join(homedir(), \".codeium\", \"windsurf\");\n\nexport function createAdapter(baseDir?: string): Adapter {\n  const targetDir = baseDir ?? WINDSURF_SKILLS_DIR;\n\n  return {\n    name: \"windsurf\",\n    targetDir,\n\n    async detect(): Promise<boolean> {\n      // Windsurf rebranded to Devin Desktop on 2026-06-02 (v3.0.12): the app\n      // is now Devin.app and new data lands in Application Support/Devin,\n      // while ~/.codeium/windsurf stays the config/skills home across the\n      // rebrand (FAQ: \"these paths remain the same\"; verified on a fresh\n      // 3.4.27 install). The rebrand ADDS markers, never removes them \u2014 an\n      // un-updated legacy Windsurf install must keep detecting. Note\n      // /Applications/Devin.app is the EDITOR: the devin adapter must never\n      // claim it (Devin CLI detection is ~/.config/devin + PATH).\n      for (const p of [\n        join(homedir(), \".codeium\", \"windsurf\"),\n        \"/Applications/Windsurf.app\",\n        join(homedir(), \"Library\", \"Application Support\", \"Windsurf\"),\n        \"/Applications/Devin.app\",\n        join(homedir(), \"Library\", \"Application Support\", \"Devin\"),\n      ]) {\n        try {\n          await access(p);\n          return true;\n        } catch {\n          // not this one\n        }\n      }\n      return false;\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      assertSafeSlug(slug);\n      // Never invent the harness's config root: if ~/.codeium/windsurf is\n      // absent, writing into a manufactured tree would report success while\n      // Devin Desktop reads nothing \u2014 a silent no-op wearing a green check.\n      // The skills/ SUBDIR is created on write (fresh installs lack it until\n      // something writes skills; observed 2026-07-10), but the root must\n      // already exist. Callers surface the thrown error as a skip notice.\n      if (targetDir === WINDSURF_SKILLS_DIR) {\n        try {\n          await access(WINDSURF_ROOT);\n        } catch {\n          // Detected but not launched yet: a benign skip, not a failure.\n          throw new AdapterSkipError(\n            \"Devin Desktop config root (~/.codeium/windsurf) not found \u2014 skipping; launch the app once and sync again\",\n          );\n        }\n      }\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      validateMaterializationPath(targetDir, slugDir);\n      return writeBundleToDir(targetDir, slugDir, bundle);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      const rel = `${slugDir}/SKILL.md`;\n      const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n      return join(targetDir, hostRel);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      return join(targetDir, materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n    },\n  };\n}\n\nexport const windsurfAdapter: Adapter = createAdapter();\nexport default windsurfAdapter;\n", "import { join, sep, delimiter, dirname } from \"node:path\";\nimport { homedir, platform } from \"node:os\";\nimport { access } from \"node:fs/promises\";\nimport type { Adapter, MaterializeOptions, TargetPathOptions } from \"@skillet/core\";\nimport type { DecodedBundle } from \"@skillet/core\";\nimport {\n  assertSafeSlug,\n  materializeSlugDir,\n  validateMaterializationPath,\n  writeBundleToDir,\n} from \"@skillet/core\";\n\nexport type { Adapter };\n\n// Devin CLI/Local reads user-global skills from `~/.config/devin/skills/`\n// (POSIX) / `%APPDATA%\\devin\\skills` (Windows) \u2014 the same SKILL.md-per-folder\n// layout as Claude Code and Codex (docs.devin.ai/cli/extensibility/skills/\n// overview). Rules, separately, come from `.claude/` + `AGENTS.md`; those are\n// not skills. So Devin is a GLOBAL adapter, not the project-scoped\n// `.devin/rules` writer it used to be (which Devin never read).\nfunction resolveTargetDir(): string {\n  if (platform() === \"win32\") {\n    const appData = process.env[\"APPDATA\"];\n    return appData && appData.length > 0\n      ? join(appData, \"devin\", \"skills\")\n      : join(homedir(), \"AppData\", \"Roaming\", \"devin\", \"skills\");\n  }\n  return join(homedir(), \".config\", \"devin\", \"skills\");\n}\nconst DEFAULT_TARGET_DIR = resolveTargetDir();\n\n/**\n * Best-effort existence scan for a `devin` binary across PATH entries \u2014 a\n * pure filesystem check, NEVER spawning the binary: detect() runs unattended\n * from the tray, so executing whatever PATH resolves would turn routine\n * detection into arbitrary code execution.\n */\nasync function devinOnPath(): Promise<boolean> {\n  const pathVar = process.env[\"PATH\"];\n  if (!pathVar) return false;\n  const names = platform() === \"win32\" ? [\"devin.exe\", \"devin.cmd\", \"devin.bat\"] : [\"devin\"];\n  for (const dir of pathVar.split(delimiter)) {\n    if (!dir) continue;\n    for (const name of names) {\n      try {\n        await access(join(dir, name));\n        return true;\n      } catch {\n        // keep scanning\n      }\n    }\n  }\n  return false;\n}\n\nexport function createAdapter(baseDir?: string): Adapter {\n  const targetDir = baseDir ?? DEFAULT_TARGET_DIR;\n\n  return {\n    name: \"devin\",\n    targetDir,\n\n    async detect(): Promise<boolean> {\n      // Devin CLI's install footprint: ~/.config/devin (created at install/\n      // first-config) or a `devin` binary on PATH. Deliberately NOT\n      // /Applications/Devin.app \u2014 since the 2026-06 rebrand that is Devin\n      // Desktop, the former Windsurf editor, which the windsurf adapter owns.\n      // Devin Desktop also creates ~/.config/devin (observed on a fresh\n      // 3.4.27 install: cli/ + config.json), and that is a TRUE positive:\n      // Desktop ships Devin Local, which shares the CLI's skills discovery \u2014\n      // such machines legitimately run both surfaces.\n      try {\n        await access(dirname(targetDir));\n        return true;\n      } catch {\n        // fall through to the PATH scan\n      }\n      return devinOnPath();\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      validateMaterializationPath(targetDir, slugDir);\n      return writeBundleToDir(targetDir, slugDir, bundle);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      const rel = `${slugDir}/SKILL.md`;\n      const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n      return join(targetDir, hostRel);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      return join(targetDir, materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n    },\n  };\n}\n\nexport const devinAdapter: Adapter = createAdapter();\nexport default devinAdapter;\n", "import { join, sep, resolve, dirname } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { access } from \"node:fs/promises\";\nimport type { Adapter, MaterializeOptions, TargetPathOptions } from \"@skillet/core\";\nimport type { DecodedBundle } from \"@skillet/core\";\nimport {\n  assertSafeSlug,\n  materializeSlugDir,\n  validateMaterializationPath,\n  validateProjectAdapterRoot,\n  writeBundleToDir,\n} from \"@skillet/core\";\n\nexport type { Adapter };\n\n// opencode reads Agent Skills from several roots (opencode.ai/docs/skills):\n// its native `~/.config/opencode/skills` + project `.opencode/skills`, the\n// Claude-compatible `~/.claude/skills`, AND the agent-compatible\n// `~/.agents/skills` (global) / `.agents/skills` (project). Skillet materializes\n// into the agent-compatible `.agents/skills` path \u2014 the SAME path Codex uses \u2014\n// so a single materialization serves both runtimes (see the shared-path shadow\n// handling in @skillet/core). We detect an opencode install by its own config\n// dir (`~/.config/opencode`) rather than `.agents/`, which any agent tool may\n// create, so detection stays specific to opencode.\nconst DEFAULT_TARGET_DIR = join(homedir(), \".agents\", \"skills\");\nconst PRIMARY_DETECT_DIR = join(homedir(), \".config\", \"opencode\");\n\n// Relative POSIX path under the project root; must match PROJECT_TARGET_ALLOWLIST.\nconst PROJECT_TARGET_DIR = \".agents/skills\";\n\n/**\n * Walk up from startDir looking for the nearest ancestor directory that marks\n * a project root. Returns the absolute path of the first match, or null if the\n * filesystem root is reached without a match.\n *\n * Markers are `.git` (the repo root opencode resolves project scope against),\n * `.opencode` (an opencode project config dir), and `.agents` (whose presence\n * proves a prior project materialization). opencode walks up to the git worktree\n * to resolve project-local skills, so keying on the repo root matches it.\n *\n * opencode resolution when the same skill name appears in multiple scopes:\n * project (repo `.agents/skills`) is loaded alongside user (`~/.agents/skills`).\n * Skillet writes to the repo path when a project root is detected via this\n * walk-up; otherwise it writes to the user path.\n */\nexport async function findProjectRoot(startDir: string): Promise<string | null> {\n  let current = resolve(startDir);\n  while (true) {\n    for (const marker of [\".git\", \".opencode\", \".agents\"]) {\n      try {\n        await access(join(current, marker));\n        return current;\n      } catch {\n        // marker not present in this directory; continue\n      }\n    }\n    const parent = dirname(current);\n    if (parent === current) return null; // reached filesystem root\n    current = parent;\n  }\n}\n\nexport function createAdapter(baseDir = DEFAULT_TARGET_DIR): Adapter {\n  return {\n    name: \"opencode\",\n    targetDir: baseDir,\n\n    async detect(): Promise<boolean> {\n      try {\n        await access(PRIMARY_DETECT_DIR);\n        return true;\n      } catch {\n        return false;\n      }\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      validateMaterializationPath(baseDir, slugDir);\n      return writeBundleToDir(baseDir, slugDir, bundle);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      const rel = `${slugDir}/SKILL.md`;\n      const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n      return join(baseDir, hostRel);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      assertSafeSlug(slug);\n      return join(baseDir, materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n    },\n  };\n}\n\nexport function createProjectAdapter(): Adapter {\n  const adapter: Adapter = {\n    name: \"opencode-project\",\n    kind: \"project\",\n    targetDir: PROJECT_TARGET_DIR,\n\n    async detect(): Promise<boolean> {\n      const root = await findProjectRoot(process.cwd());\n      return root !== null;\n    },\n\n    projectRoot(cwd: string): string {\n      // Given the project root directory, return the absolute write root.\n      // Used by validateProjectAdapterRoot for structural safety checks.\n      return join(cwd, \".agents\", \"skills\");\n    },\n\n    async materialize(\n      slug: string,\n      bundle: DecodedBundle,\n      opts: MaterializeOptions = {},\n    ): Promise<string[]> {\n      const startDir = opts.cwd ?? process.cwd();\n      assertSafeSlug(slug);\n      const projRoot = await findProjectRoot(startDir);\n      if (!projRoot) {\n        throw new Error(\n          `No project root found from \"${startDir}\" \u2014 expected .git/, .opencode/, or .agents/ in an ancestor directory`,\n        );\n      }\n      validateProjectAdapterRoot(adapter, projRoot);\n      const absRoot = join(projRoot, \".agents\", \"skills\");\n      // Guard: if the walk-up resolved to homedir (e.g. ~/.agents/ exists),\n      // absRoot would silently equal the global adapter's target. Decline so\n      // the caller falls through to the global opencodeAdapter instead.\n      if (resolve(absRoot) === resolve(join(homedir(), \".agents\", \"skills\"))) {\n        throw new Error(\n          `No project-specific root found from \"${startDir}\" \u2014 walk-up resolved to the global agent-skills path. Use opencodeAdapter (global) instead.`,\n        );\n      }\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      return writeBundleToDir(absRoot, slugDir, bundle);\n    },\n\n    targetPath(slug: string, opts: TargetPathOptions = {}): string {\n      const cwd = opts.cwd ?? process.cwd();\n      assertSafeSlug(slug);\n      const slugDir = materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName });\n      const rel = `${slugDir}/SKILL.md`;\n      const hostRel = sep === \"/\" ? rel : rel.split(\"/\").join(sep);\n      return join(cwd, \".agents\", \"skills\", hostRel);\n    },\n\n    targetSkillDir(slug: string, opts: TargetPathOptions = {}): string {\n      const cwd = opts.cwd ?? process.cwd();\n      assertSafeSlug(slug);\n      return join(cwd, \".agents\", \"skills\", materializeSlugDir(slug, opts.owner ?? null, { dirName: opts.dirName }));\n    },\n  };\n  return adapter;\n}\n\nexport const opencodeAdapter: Adapter = createAdapter();\nexport const opencodeProjectAdapter: Adapter = createProjectAdapter();\nexport default opencodeAdapter;\n", "import { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport type { Adapter } from '@skillet/core';\nimport { findProjectRoot } from '@skillet/adapters-codex';\nimport {\n  ADDITIONAL_ADAPTERS,\n  BASELINE_GLOBAL_ADAPTERS,\n  codexProjectAdapter,\n} from './cli-context.js';\n\n/** Names that always materialize (universal `.agents/skills`). */\nexport const BASELINE_ADAPTER_NAMES = ['codex', 'codex-project'] as const;\n\nexport type BaselineAdapterName = (typeof BASELINE_ADAPTER_NAMES)[number];\n\nexport function isBaselineAdapterName(name: string): name is BaselineAdapterName {\n  return (BASELINE_ADAPTER_NAMES as readonly string[]).includes(name);\n}\n\n/**\n * Universal baseline: global `~/.agents/skills` plus repo `.agents/skills`\n * when cwd resolves a real project root (not the homedir-global collision).\n */\nexport async function baselineAdaptersForCwd(cwd: string): Promise<Adapter[]> {\n  const baseline: Adapter[] = [...BASELINE_GLOBAL_ADAPTERS];\n  const projectRoot = await findProjectRoot(cwd);\n  if (!projectRoot) {\n    return baseline;\n  }\n\n  const absRoot = join(projectRoot, '.agents', 'skills');\n  const globalRoot = join(homedir(), '.agents', 'skills');\n  if (resolve(absRoot) === resolve(globalRoot)) {\n    return baseline;\n  }\n\n  baseline.push(codexProjectAdapter);\n  return baseline;\n}\n\nexport function baselineNamesForAdapters(adapters: Adapter[]): string[] {\n  return adapters\n    .map((a) => a.name)\n    .filter((name) => isBaselineAdapterName(name));\n}\n\nexport interface ResolvedAdapters {\n  adapters: Adapter[];\n  baselineNames: string[];\n}\n\nexport async function resolveMaterializeAdapters(\n  cwd: string,\n  pickedAdditional: Adapter[],\n): Promise<ResolvedAdapters> {\n  const baseline = await baselineAdaptersForCwd(cwd);\n  const baselineNames = baselineNamesForAdapters(baseline);\n  const baselineSet = new Set(baselineNames);\n  const additional = pickedAdditional.filter((a) => !baselineSet.has(a.name));\n  return {\n    adapters: [...baseline, ...additional],\n    baselineNames,\n  };\n}\n\nexport async function resolveSyncAdapters(cwd: string): Promise<ResolvedAdapters> {\n  const baseline = await baselineAdaptersForCwd(cwd);\n  const baselineNames = baselineNamesForAdapters(baseline);\n  const detectedAdditional: Adapter[] = [];\n\n  for (const adapter of ADDITIONAL_ADAPTERS) {\n    try {\n      if (await adapter.detect()) {\n        detectedAdditional.push(adapter);\n      }\n    } catch {\n      // Non-fatal \u2014 skip adapters that fail detect.\n    }\n  }\n\n  return {\n    adapters: [...baseline, ...detectedAdditional],\n    baselineNames,\n  };\n}\n\n/** Names of the adapters whose detect() answers yes \u2014 concurrent, failures\n *  skipped. The one canonical \"which agents are here\" loop; every surface\n *  that needs the list calls this instead of re-rolling it. */\nexport async function detectAdapterNames(adapters: readonly Adapter[]): Promise<string[]> {\n  const detected = await Promise.all(\n    adapters.map((adapter) =>\n      adapter\n        .detect()\n        .then((hit) => (hit ? adapter.name : null))\n        .catch(() => null),\n    ),\n  );\n  return detected.filter((name): name is string => name !== null);\n}\n\n/** Additional adapter names currently detected (for `-a` error messages). */\nexport async function detectAdditionalAdapterNames(): Promise<string[]> {\n  return detectAdapterNames(ADDITIONAL_ADAPTERS);\n}\n", "import {\n  installRouteHooksForRuntimes,\n  hookRuntimesFromDetected,\n  routeConsentChosen,\n  chooseRouteConsent,\n  readRouteHistory,\n  type SyncResult,\n} from \"@skillet/core\";\nimport * as clack from \"@clack/prompts\";\nimport { STATS_SYNC_ON_MSG, STATS_LOCAL_MSG } from \"./skill-stats-copy.js\";\nimport { webBaseUrl } from \"./cli-command-tier.js\";\nimport { dim, cyan, yellow } from \"./cli-colors.js\";\n\n/**\n * Post-sync /skillet hook install + first-run route-consent choice, shared by\n * `skillet sync` and the auto-sync after pairing (wizard / `skillet connect`).\n * Before connect auto-synced, the \"run skillet sync\" homework was accidentally\n * where onboarders got hooks and the consent question \u2014 this keeps that moment\n * on every path that syncs interactively.\n *\n * Consent gate: only interactive (TTY, not --json), only after a hook actually\n * installed, only if never chosen. In --json/CI we defer \u2014 leaving the choice\n * unmade keeps route events local until the next interactive surface, never\n * silently opting in.\n *\n * The prose promises here are privacy commitments (what telemetry collects and\n * where it stays) \u2014 reword only with product sign-off, and keep `skillet\n * activity` copy in lockstep.\n */\nexport async function installRouteHooksWithConsent(\n  result: Pick<SyncResult, \"adapters\">,\n  opts: { json?: boolean; teachHint?: boolean } = {},\n): Promise<void> {\n  const asJson = opts.json === true;\n  try {\n    // Dev runs from source (tsx) put the raw .ts entry in argv[1]; a hook\n    // pointing there fails \"Permission denied\" on every agent prompt once\n    // this process is gone. Fall back to the installed binary name \u2014 a dev\n    // hook must be asked for explicitly via SKILLET_CLI.\n    const argvCommand = process.argv[1] ?? \"skillet\";\n    const recorderCommand =\n      process.env[\"SKILLET_CLI\"] ??\n      (/\\.(mts|cts|ts|tsx)$/.test(argvCommand) ? \"skillet\" : argvCommand);\n    const detected = result.adapters\n      .filter((a) => a.status !== \"skipped-not-detected\")\n      .map((a) => a.name);\n    const hookRuntimes = hookRuntimesFromDetected(detected);\n    const hookInstall = await installRouteHooksForRuntimes(hookRuntimes, {\n      recorderCommand,\n    });\n    if (!asJson) {\n      for (const warning of hookInstall.warnings) {\n        console.log(`${yellow(\"\u26A0\")}  ${warning}`);\n      }\n    }\n    if (\n      !asJson &&\n      process.stdout.isTTY === true &&\n      hookInstall.installed.length > 0 &&\n      !(await routeConsentChosen())\n    ) {\n      // The ask waits for real stats: someone who has never run /skillet has\n      // nothing to sync, so the first-run moment teaches the verb instead.\n      // Once local uses exist, the question arrives with its own evidence.\n      const history = await readRouteHistory();\n      const uses = Object.values(history.skills).reduce((n, s) => n + s.count, 0);\n      if (uses === 0) {\n        // teachHint false = a surface that teaches on its own follows (the\n        // bare-run home menu), so saying it here too would double up.\n        if (opts.teachHint !== false) {\n          console.log(\"\");\n          console.log(\n            `Try ${cyan(\"/skillet <task>\")} in any agent. It picks the right skill from your kit.`,\n          );\n          console.log(dim(\"Stats stay on this machine. See them with \") + cyan(\"skillet usage\"));\n        }\n        return;\n      }\n      // Mirrors the web Settings \"Skill stats\" panel. Honesty contract: the\n      // local tally is unconditional (route.ts writes route-history on every\n      // route to power `skillet usage`), so the question is ONLY about what is\n      // actually a choice \u2014 syncing those stats to the account. Never phrase\n      // this as \"count y/N\"; declining does not stop local counting.\n      console.log(\"\");\n      clack.log.message(\n        [\n          `You've used /skillet ${uses === 1 ? \"once\" : `${uses} times`} on this machine. Skillet keeps those`,\n          \"stats local: which skill it picks and which agent ran it. Nothing you\",\n          \"type or the agent writes is ever saved.\",\n          dim(\"Details: \") + cyan(`${webBaseUrl()}/docs/privacy`),\n        ].join(\"\\n\"),\n      );\n      const record = await clack.confirm({\n        message: \"Sync skill stats to your account?\",\n        initialValue: false,\n      });\n      // Esc defers: the choice stays unmade and the next interactive sync\n      // asks again \u2014 never a silent, permanent opt-out.\n      if (clack.isCancel(record)) return;\n      await chooseRouteConsent(record);\n      console.log(record ? STATS_SYNC_ON_MSG : STATS_LOCAL_MSG);\n    }\n  } catch (err) {\n    if (!asJson) {\n      console.log(`${yellow(\"\u26A0\")}  /skillet usage hooks were not installed: ${(err as Error).message}`);\n    }\n  }\n}\n", "/**\n * Skill-stats confirmation copy, shared by the first-run consent ask\n * (route-hooks-consent.ts) and `skillet activity choose` so the two surfaces\n * cannot drift. Honesty contract: the local tally is unconditional; these\n * strings only ever describe the SYNC choice.\n */\nexport const STATS_SYNC_ON_MSG = \"Syncing skill stats. Change anytime with `skillet activity off`\";\nexport const STATS_LOCAL_MSG = \"Skill stats stay on this machine.\";\n", "import { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** Absolute path to the bundled `@skillet/route` skill directory shipped with the CLI. */\nexport function resolveBundledRouteSkillDir(): string {\n  const here = dirname(fileURLToPath(import.meta.url));\n  const besideEntry = join(here, \"bundled-skills\", \"skillet-route\");\n  if (existsSync(besideEntry)) return besideEntry;\n  return join(here, \"..\", \"bundled-skills\", \"skillet-route\");\n}\n", "// The route skill's SKILL.md, inlined at bundle time (esbuild `define` in\n// scripts/bundle-cli.mjs) so it survives inside the pkg-compiled desktop\n// sidecar \u2014 pkg never snapshots `dist/bundled-skills`, so the on-disk copy is\n// unreachable there. In dev (tsx runs src directly, no define) the symbol is\n// undefined and the caller reads the SKILL.md from disk, which exists in the\n// source tree.\ndeclare const __SKILLET_ROUTE_SKILL_MD__: string;\n\nexport function inlinedRouteSkillMd(): string | undefined {\n  return typeof __SKILLET_ROUTE_SKILL_MD__ !== \"undefined\"\n    ? __SKILLET_ROUTE_SKILL_MD__\n    : undefined;\n}\n", "import { bold, dim, cyan } from \"./cli-colors.js\";\n\n/**\n * One-line summary of the skills sync held for review (new arrivals and\n * updates alike) \u2014 the interactive-sync replacement for the old per-skill\n * diff prompts. Silent when nothing is waiting.\n */\nexport function printPendingReviewSummary(\n  pending: Array<{ slug: string; range: string }>,\n): void {\n  if (pending.length === 0) return;\n  // Same split as the home menu: updates and new arrivals are different\n  // decisions, so each kind gets its own line.\n  const updates = pending.filter((p) => p.range !== \"new\");\n  const arrivals = pending.filter((p) => p.range === \"new\");\n  console.log(\"\");\n  if (arrivals.length > 0) {\n    const items = arrivals.map((p) => p.slug).join(\", \");\n    console.log(`${arrivals.length} new skill${arrivals.length === 1 ? \"\" : \"s\"} to add: ${items}`);\n  }\n  if (updates.length > 0) {\n    const items = updates.map((p) => `${p.slug} ${dim(`(${p.range})`)}`).join(\", \");\n    console.log(`${updates.length} skill update${updates.length === 1 ? \"\" : \"s\"} to review: ${items}`);\n  }\n  console.log(dim(\"  Review with \") + cyan(bold(\"skillet pending\")));\n}\n", "/**\n * Strip terminal control/escape sequences from untrusted text before printing.\n *\n * Registry-supplied proposal diffs (file paths + diff content) are\n * attacker-controlled; printed raw they can carry ANSI/OSC escape sequences\n * that rewrite the screen, spoof prompts, or alter the clipboard/title (deepsec\n * MEDIUM terminal-injection). Tabs and the visible text are preserved; ESC\n * sequences and other C0/C1 control characters are removed.\n */\n// eslint-disable-next-line no-control-regex\nconst ANSI_OSC = /\\x1b\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)/g; // OSC: ESC ] ... BEL|ST\n// eslint-disable-next-line no-control-regex\nconst ANSI_CSI = /\\x1b[@-Z\\\\-_]|\\x1b\\[[0-?]*[ -/]*[@-~]/g; // CSI + 2-char escapes\n// eslint-disable-next-line no-control-regex\nconst CONTROL = /[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f]/g; // C0/C1 except \\t (0x09) and \\n (0x0a)\n\nexport function stripControlChars(text: string): string {\n  return text.replace(ANSI_OSC, \"\").replace(ANSI_CSI, \"\").replace(CONTROL, \"\");\n}\n\n/**\n * Render a registry scan finding (a `scan_blocked` refusal) for the terminal\n * WITHOUT the matched value. A secret's bytes ARE the secret, so they must never\n * be printed (deepsec MEDIUM secret-in-log) \u2014 show only the location + category.\n * Shared by the `publish`, `propose`, and `edits propose` commands, which all\n * surface the same registry `scan_blocked` body.\n */\nexport function formatScanFinding(f: { file: string; lineStart: number; category: string }): string {\n  return `  ${f.file}:${f.lineStart} [${f.category}] (matched value redacted)`;\n}\n", "import { stripControlChars } from \"./sanitize-output.js\";\nimport { webBaseUrl } from \"./cli-command-tier.js\";\n\nexport interface RenderedError {\n  /** What happened, in words a person can act on. */\n  line: string;\n  /** The one next action, when a real one exists. */\n  next?: string;\n}\n\n/** Truncate raw content hashes so they stop dominating error lines. */\nfunction shortenHashes(text: string): string {\n  return text.replace(/sha256:([0-9a-f]{8})[0-9a-f]{56}/gi, \"sha256:$1\u2026\");\n}\n\nconst KNOWN: Array<{ match: RegExp; render: (raw: string) => RenderedError }> = [\n  {\n    match: /^signature_invalid|signature key_id|does not match author_pub|hashed to sha256/i,\n    render: () => ({\n      line: \"This skill's content doesn't match its author's signature, so Skillet refused it to protect you.\",\n      next: \"If this keeps happening, remove and re-add the skill, or check with its author.\",\n    }),\n  },\n  {\n    match: /^rollback_detected/i,\n    render: () => ({\n      line: \"The registry offered an OLDER version than the one you already have, which can hide a fix. Skillet kept your newer copy.\",\n      next: \"If the author intentionally rolled back, remove and re-add the skill to accept it.\",\n    }),\n  },\n  {\n    match: /^manifest_empty/i,\n    render: () => ({\n      line: \"The registry answered but sent no skill data.\",\n      next: \"Usually temporary. Run `skillet sync` again in a moment.\",\n    }),\n  },\n  {\n    match: /^registry_missing/i,\n    render: () => ({\n      line: \"This skill has lost its registry link, so updates can't be pulled.\",\n      next: \"Re-add it to repair: `skillet add <ref>`.\",\n    }),\n  },\n  {\n    match: /is yanked/i,\n    render: () => ({\n      line: \"The author pulled this version, so Skillet won't install it.\",\n      next: \"A newer version will install normally when it's published.\",\n    }),\n  },\n  {\n    match: /is unsigned|has not registered a signing key/i,\n    render: () => ({\n      line: \"This skill isn't signed by its author yet, so Skillet can't verify who wrote it.\",\n      next: \"Ask the author to publish a signed version.\",\n    }),\n  },\n  {\n    match: /http_401|http_403|HTTP 401|HTTP 403|unauthorized/i,\n    render: () => ({\n      line: \"The registry didn't accept this machine's credentials.\",\n      next: \"Reconnect with a fresh code: `skillet connect <code>` (get one at \" + `${webBaseUrl()}/settings).`,\n    }),\n  },\n  {\n    match: /http_5\\d\\d|HTTP 5\\d\\d/i,\n    render: () => ({\n      line: \"The registry had a problem on its end.\",\n      next: \"Try again in a minute; if it persists, check \" + `${webBaseUrl()} for status.`,\n    }),\n  },\n  {\n    match: /http_404|HTTP 404/i,\n    render: () => ({\n      line: \"The registry doesn't have what this command asked for. It may have been removed or renamed.\",\n    }),\n  },\n  {\n    match: /fetch failed|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network/i,\n    render: () => ({\n      line: \"The registry couldn't be reached. Check your connection.\",\n      next: \"Everything already synced keeps working offline; run `skillet sync` when you're back.\",\n    }),\n  },\n];\n\n/**\n * One human rendering for every error the CLI shows (KTD3). Known internal\n * codes become a plain sentence plus the one next action; unknown text is\n * cleaned (control characters stripped \u2014 registry-supplied text is a trust\n * boundary \u2014 and hashes shortened) rather than dumped raw. Core keeps\n * throwing coded errors; only the presentation lives here.\n */\nexport function renderError(reasonOrError: string | Error): RenderedError {\n  const raw =\n    typeof reasonOrError === \"string\"\n      ? reasonOrError\n      : (reasonOrError?.message ?? String(reasonOrError));\n  const safe = stripControlChars(raw);\n  for (const { match, render } of KNOWN) {\n    if (match.test(safe)) {\n      const rendered = render(safe);\n      return { line: stripControlChars(rendered.line), ...(rendered.next ? { next: stripControlChars(rendered.next) } : {}) };\n    }\n  }\n  // Unknown: clean, shorten, and strip a leading KNOWN internal code prefix\n  // (never an arbitrary `word:` prefix \u2014 that would eat slugs and filenames).\n  const cleaned = shortenHashes(safe).replace(\n    /^(pull_failed|integrity_failed|union_pull_failed|materialize_failed|edit_unreadable|quarantined|http_\\d+):\\s+/,\n    \"\",\n  );\n  return { line: cleaned || \"Something went wrong, and the error carried no details.\" };\n}\n\n/** Convenience: the rendered error as one or two printable lines. */\nexport function renderErrorLines(reasonOrError: string | Error): string[] {\n  const { line, next } = renderError(reasonOrError);\n  return next ? [line, `  ${next}`] : [line];\n}\n\n/**\n * Print a rendered error: the first line through `decorate` (fail(), a\n * prefix template, \u2026), follow-up action lines plain. One printer instead of\n * the destructure-and-loop repeated at every call site.\n */\nexport function printRenderedError(\n  reasonOrError: string | Error,\n  decorate: (line: string) => string = (l) => l,\n  print: (line: string) => void = console.error,\n): void {\n  const [what, ...next] = renderErrorLines(reasonOrError);\n  print(decorate(what));\n  for (const n of next) print(n);\n}\n", "import * as clack from \"@clack/prompts\";\nimport { Command } from \"commander\";\nimport {\n  readState,\n  readRouteHistory,\n  listPending,\n  approveUpdate,\n  rejectUpdate,\n  requiresQuarantineConsent,\n  groupSkillsByKit,\n  type PendingEntry,\n} from \"@skillet/core\";\nimport { ALL_ADAPTERS, CLI_VERSION, countUserSkills } from \"./cli-context.js\";\nimport { registerAllCommands } from \"./commands/register-all.js\";\nimport { formatSkilletHelp } from \"./help-format.js\";\nimport { applyToAgents } from \"./apply-to-agents.js\";\nimport { renderKitList } from \"./kit-list-format.js\";\nimport { formatPendingRange } from \"./commands/pending.js\";\nimport { stripControlChars } from \"./sanitize-output.js\";\nimport { webBaseUrl } from \"./cli-command-tier.js\";\nimport { ok, fail, bold, dim, cyan } from \"./cli-colors.js\";\nimport { printRenderedError } from \"./render-error.js\";\n\n/**\n * The bare-run home: after sync reports, one navigable menu instead of a wall\n * of hints. Options are earned, not fixed \u2014 review only appears when something\n * waits, and the /skillet teach block leads until the first real use. Esc or\n * \"Done\" leaves quietly; every other action returns here.\n */\nexport async function runHomeMenu(): Promise<void> {\n  if (process.stdout.isTTY !== true) return;\n\n  for (;;) {\n    const state = await readState();\n    const total = countUserSkills(state);\n    const history = await readRouteHistory();\n    const used = Object.values(history.skills).some((s) => s.count > 0);\n    let pending: PendingEntry[] = [];\n    try {\n      pending = (await listPending(ALL_ADAPTERS)).pending;\n    } catch {\n      // Pending listing is a menu nicety, never a blocker.\n    }\n\n    const options: { value: string; label: string; hint?: string }[] = [];\n    // Updates and new arrivals are different decisions \u2014 \"accept this change\n    // to something I run\" vs \"let this onto my machine at all\" \u2014 so they get\n    // separate rows. Version moves stay inside the review flow, where each\n    // skill's header carries its range.\n    const updates = pending.filter((p) => p.approvedVersion !== null);\n    const arrivals = pending.filter((p) => p.approvedVersion === null);\n    const hintFor = (list: PendingEntry[]) => {\n      const shown = list.slice(0, 3).map((p) => p.slug).join(\", \");\n      return list.length > 3 ? `${shown} +${list.length - 3} more` : shown;\n    };\n    // Menu rows are ACTIONS, not status lines: with a handful of items each\n    // gets a verb-led row naming the actual skill (the Apple move \u2014 name the\n    // thing when you can). Past that, collapse to one count row per kind.\n    const REVIEW_INLINE_MAX = 4;\n    // New skills outrank updates: letting something onto the machine is the\n    // bigger decision, so it always sits first.\n    if (pending.length > 0 && pending.length <= REVIEW_INLINE_MAX) {\n      for (const p of arrivals) {\n        options.push({\n          value: `review-one:${p.slug}`,\n          // Outcome, not mechanism: choosing this ADDS the skill (after a\n          // look at what it is). \"Review\" stays for updates, where reviewing\n          // the change IS the action.\n          label: `Add new skill: ${p.slug}`,\n          hint: `v${p.incomingVersionLabel ?? p.incomingVersion}`,\n        });\n      }\n      for (const p of updates) {\n        options.push({\n          value: `review-one:${p.slug}`,\n          label: `Review update: ${p.slug}`,\n          hint: formatPendingRange(p),\n        });\n      }\n    } else {\n      if (arrivals.length > 0) {\n        options.push({\n          value: \"review-new\",\n          label: `Add ${arrivals.length} new skills`,\n          hint: hintFor(arrivals),\n        });\n      }\n      if (updates.length > 0) {\n        options.push({\n          value: \"review-updates\",\n          label: `Review ${updates.length} skill updates`,\n          hint: hintFor(updates),\n        });\n      }\n    }\n    if (!used) {\n      // Honest label: the CLI can't run /skillet itself (it lives inside the\n      // agents), so this shows how \u2014 it never claims to execute anything.\n      options.push({ value: \"learn\", label: \"How to run your first skill\", hint: \"/skillet\" });\n    }\n    options.push({ value: \"skills\", label: `Your skills (${total})` });\n    if (used) {\n      options.push({ value: \"learn\", label: \"How /skillet works\" });\n    }\n    options.push({ value: \"help\", label: \"Help\", hint: \"all commands\" });\n    options.push({ value: \"exit\", label: \"Done\" });\n\n    console.log(\"\");\n    const choice = await clack.select({\n      message: \"What next?\",\n      options,\n      initialValue: options[0]!.value,\n    });\n    if (clack.isCancel(choice) || choice === \"exit\") return;\n    if (typeof choice === \"string\" && choice.startsWith(\"review-one:\")) {\n      const slug = choice.slice(\"review-one:\".length);\n      const entry = pending.find((p) => p.slug === slug);\n      if (entry) await reviewPending([entry]);\n    }\n    if (choice === \"review-updates\") await reviewPending(updates);\n    if (choice === \"review-new\") await reviewPending(arrivals);\n    if (choice === \"skills\") showSkills(state, arrivals);\n    if (choice === \"learn\") showLearn();\n    if (choice === \"help\") showHelp();\n  }\n}\n\n/** Render the same root `skillet --help` surface from inside the home menu. */\nfunction showHelp(): void {\n  const program = new Command(\"skillet\").version(CLI_VERSION);\n  program.configureHelp({ formatHelp: formatSkilletHelp, sortSubcommands: false });\n  registerAllCommands(program);\n  console.log(\"\");\n  console.log(program.helpInformation());\n}\n\nfunction showSkills(\n  state: Awaited<ReturnType<typeof readState>>,\n  awaitingArrivals: PendingEntry[] = [],\n): void {\n  // Same grouped view as `skillet list`: kits are how skills arrive, so the\n  // kit is the section header, not a suffix repeated on every row. Local\n  // grouping only \u2014 a menu action shouldn't wait on the network.\n  const groups = groupSkillsByKit(state);\n  console.log(\"\");\n  console.log(\n    renderKitList(groups, { awaitingConsent: new Set(awaitingArrivals.map((p) => p.slug)) }),\n  );\n  console.log(dim(\"\\n  Add more at \") + cyan(`${webBaseUrl()}/browse`));\n}\n\nfunction showLearn(): void {\n  console.log(\"\");\n  console.log(`  In any agent (Claude Code, Cursor, Codex), type ${bold(\"/skillet\")} and the task:`);\n  console.log(\"\");\n  console.log(cyan(\"  /skillet review this PR like grace would\"));\n  console.log(\"\");\n  console.log(\"  Skillet picks the right skill from your kit and your agent runs it.\");\n  console.log(dim(\"  Uses stay on this machine. See them with \") + cyan(\"skillet usage\"));\n}\n\n/**\n * Per-skill review loop: the diff (already deduped to one copy with an\n * applies-to header), then approve / later / reject. Approvals materialize\n * immediately with a scoped sync \u2014 no \"now run skillet sync\" homework.\n *\n * Quarantined entries are the safety-critical path: the harm-scan findings\n * render BEFORE the decision, the select never defaults to Approve, and\n * approving asks one more default-No confirm that becomes the quarantine\n * consent. That consent is granted per slug (allowQuarantinedSlugs), never\n * batch-wide \u2014 a grant is exactly as wide as what this user saw and accepted.\n */\nasync function reviewPending(pending: PendingEntry[]): Promise<void> {\n  const approved: string[] = [];\n  const quarantineConsented: string[] = [];\n  for (const entry of pending) {\n    console.log(\"\");\n    console.log(`${bold(entry.slug)} ${dim(`(${formatPendingRange(entry)})`)}`);\n    if (entry.quarantined && entry.scanSummary) {\n      console.log(stripControlChars(entry.scanSummary));\n      console.log(\"\");\n    }\n    if (entry.diff) console.log(stripControlChars(entry.diff));\n    const isNew = entry.approvedVersion === null;\n    const action = await clack.select({\n      message: entry.quarantined\n        ? `${entry.slug} is quarantined. ${isNew ? \"Add\" : \"Apply\"} anyway?`\n        : isNew\n          ? `Add ${entry.slug}?`\n          : `Apply this update to ${entry.slug}?`,\n      options: [\n        {\n          value: \"approve\",\n          label: entry.quarantined\n            ? `${isNew ? \"Add\" : \"Approve\"} quarantined skill`\n            : isNew\n              ? \"Add it\"\n              : \"Approve\",\n          hint: isNew ? \"installs now\" : \"applies now\",\n        },\n        { value: \"later\", label: \"Decide later\" },\n        { value: \"reject\", label: \"Reject this version\", hint: \"a newer version asks again\" },\n      ],\n      // Never preselect Approve on a quarantined entry: Enter-Enter must not\n      // be able to materialize harm-scan-flagged content.\n      initialValue: entry.quarantined ? \"later\" : \"approve\",\n    });\n    if (clack.isCancel(action)) break;\n    if (action === \"approve\") {\n      // Re-read the entry: the menu's pending snapshot can be stale (a\n      // background tray sync may have flipped the scan verdict since). The\n      // consent decision must be made against what will actually be written.\n      const stateNow = await readState();\n      const entryNow = stateNow.skills[entry.slug];\n      const quarantinedNow = entry.quarantined || requiresQuarantineConsent(entryNow?.scan);\n      if (quarantinedNow && !entry.quarantined) {\n        console.log(dim(`  ${entry.slug} was quarantined by a newer scan. Review it again next pass.`));\n        continue;\n      }\n      if (entry.quarantined) {\n        const consent = await clack.confirm({\n          message: `Apply the quarantined ${entry.slug} despite the findings above?`,\n          initialValue: false,\n        });\n        // Esc or No: fail closed \u2014 no approval, nothing written.\n        if (clack.isCancel(consent) || consent !== true) {\n          console.log(dim(\"  Left for later. Nothing applied.\"));\n          continue;\n        }\n        quarantineConsented.push(entry.slug);\n      }\n      await approveUpdate(entry.slug, entry.incomingVersion, {});\n      approved.push(entry.slug);\n    } else if (action === \"reject\") {\n      await rejectUpdate(entry.slug);\n      console.log(dim(`  Rejected v${entry.incomingVersionLabel ?? entry.incomingVersion}.`));\n    }\n  }\n  if (approved.length === 0) return;\n\n  try {\n    const result = await applyToAgents(approved, { allowQuarantinedSlugs: quarantineConsented });\n    // Say what actually happened, not what was approved: a quarantine skip\n    // (scan flipped mid-review) must not be counted as applied.\n    const skipped = result.failed.filter((f) => f.reason.startsWith(\"quarantined\"));\n    const appliedCount = approved.length - skipped.length;\n    if (appliedCount > 0) {\n      console.log(ok(`Applied ${appliedCount} update${appliedCount === 1 ? \"\" : \"s\"}.`));\n    }\n    for (const f of skipped) {\n      console.log(dim(`  ${f.slug} was quarantined by a newer scan and was not applied.`));\n    }\n  } catch (err) {\n    printRenderedError(err as Error, (what) => fail(`Applying failed: ${what}`));\n    console.log(dim(\"  The approvals were recorded; run `skillet sync` to finish applying.\"));\n  }\n}\n", "/** True when argv has no subcommand or flags \u2014 only then do we run the onboarding wizard. */\nexport function shouldRunOnboardingWizard(argv: string[] = process.argv): boolean {\n  return argv.slice(2).length === 0;\n}\n\n/** Opt-in registry management verbs for CI, desktop, and dogfood scripts. */\nexport function legacyManagementEnabled(): boolean {\n  return process.env[\"SKILLET_LEGACY_CLI\"] === \"1\";\n}\n", "import type { Command } from 'commander';\nimport * as clack from '@clack/prompts';\nimport {\n  add,\n  importGitHubSkill,\n  importSkill,\n  loadRegistryBearer,\n  loadSessionToken,\n  materializeSkills,\n  subscribeKitByHandle,\n  findKitByHandle,\n  type DiscoveredGitHubSkill,\n} from '@skillet/core';\nimport {\n  collect,\n  REGISTRY_DEFAULT,\n  renderAdapterLine,\n} from '../cli-context.js';\nimport { webBaseUrl } from '../cli-command-tier.js';\nimport { authRequiredMessage, requirePaired } from '../auth-required.js';\nimport { ExitCode, exitWith } from '../exit-codes.js';\nimport { writeJsonError, writeJsonOk } from '../json-output.js';\nimport {\n  configureAddPresent,\n  printAddBanner,\n  printAddError,\n  printAddHint,\n  printStepInfo,\n  printStepSelect,\n  printStepSuccess,\n} from '../cli-add-present.js';\nimport {\n  detectInstalledAdapters,\n  formatAdapterList,\n  pickAdapters,\n  warnNoAdditionalRuntimes,\n  type DetectedAdapter,\n} from '../cli-add-adapters.js';\nimport { resolveMaterializeAdapters } from '../adapter-tiers.js';\nimport {\n  discoverGithubForAdd,\n  resolveAddSource,\n} from '../cli-add-source.js';\nimport { selectSkills } from './import-cmd.js';\n\nexport interface AddFlowOptions {\n  registry: string;\n  ref?: string;\n  skill: string[];\n  list?: boolean;\n  yes?: boolean;\n  global?: boolean;\n  adapter: string[];\n  json?: boolean;\n  token?: string;\n  pin?: boolean;\n  cwd?: string;\n}\n\nexport interface AddFlowResult {\n  kind: 'skill' | 'kit';\n  source: string;\n  skill?: string;\n  skills?: string[];\n  kit?: string;\n  adapters: string[];\n  synced: boolean;\n  materialized: number;\n}\n\n/**\n * Kit subscribe needs a *session* token specifically (a device-paired machine\n * without a web session still can't subscribe). The generic unpaired case is\n * handled earlier by the command-entry pairing gate (requirePaired).\n */\nfunction kitAuthMessage(): string {\n  const web = webBaseUrl();\n  return `Kit install requires a signed-in session. Sign in at ${web}, then run \\`skillet connect <code>\\` from ${web}/settings.`;\n}\n\nasync function runPostInstallMaterialize(\n  cwd: string,\n  slugs: string[],\n  adapters: DetectedAdapter[],\n  opts: {\n    token?: string;\n    registryUrl: string;\n    asJson: boolean;\n    autoApprove: boolean;\n    skipPull: boolean;\n  },\n): Promise<{ synced: boolean; materialized: number; adapterNames: string[] }> {\n  const { adapters: adapterList, baselineNames } = await resolveMaterializeAdapters(\n    cwd,\n    adapters.map((a) => a.adapter),\n  );\n  const result = await materializeSkills(cwd, adapterList, {\n    slugs,\n    token: opts.token,\n    registryUrl: opts.registryUrl,\n    quietSkipLines: opts.asJson,\n    autoApprove: opts.autoApprove,\n    skipPull: opts.skipPull,\n    pullMode: opts.skipPull ? 'unattended' : undefined,\n    baselineAdapterNames: baselineNames,\n  });\n  const materialized = result.adapters.filter((a) => a.status === 'materialized').length;\n  if (!opts.asJson) {\n    console.log('');\n    for (const r of result.adapters) {\n      if (r.status !== 'skipped-not-detected') {\n        console.log(renderAdapterLine(r));\n      }\n    }\n  }\n  return {\n    synced: true,\n    materialized,\n    adapterNames: adapterList.map((a) => a.name),\n  };\n}\n\nasync function pickGithubSkillInteractive(\n  skills: DiscoveredGitHubSkill[],\n): Promise<DiscoveredGitHubSkill | null> {\n  if (skills.length === 1) return skills[0] ?? null;\n  const selected = await clack.select({\n    message: 'Which skill do you want to install?',\n    options: skills.map((s) => ({\n      value: s.slug,\n      label: s.slug,\n      hint: s.description ?? undefined,\n    })),\n  });\n  if (clack.isCancel(selected)) return null;\n  const slug = selected as string;\n  return skills.find((s) => s.slug === slug) ?? null;\n}\n\nexport async function runSkillAddFlow(\n  sourceInput: string | undefined,\n  opts: AddFlowOptions,\n): Promise<AddFlowResult> {\n  const asJson = opts.json === true;\n  const interactive = !asJson && process.stdin.isTTY === true && process.stdout.isTTY === true;\n  configureAddPresent({ json: asJson });\n\n  if (!asJson) {\n    printAddBanner();\n  }\n\n  const resolved = await resolveAddSource(sourceInput);\n  if (resolved.kind === 'missing') {\n    throw new Error(\n      sourceInput\n        ? `Unrecognized source \"${sourceInput}\". Use a GitHub repo (owner/repo), @author/skill, or a local path.`\n        : 'Source is required. Example: skillet add vercel-labs/skills --skill find-skills',\n    );\n  }\n\n  if (!asJson) {\n    printStepInfo(`Source: ${resolved.display}`);\n  }\n\n  let installedSlug: string;\n  let installedName: string;\n\n  if (resolved.kind === 'registry_skill' && resolved.registryRef) {\n    const bearer = await loadRegistryBearer(opts.token);\n    if (!bearer.token) {\n      // Defensive: the command-entry pairing gate already exited unpaired runs.\n      throw new Error(authRequiredMessage());\n    }\n    if (!asJson) {\n      printStepSelect(`Selected: ${resolved.registryRef}`, resolved.registryRef);\n    }\n    const result = await add(resolved.registryRef, {\n      registryUrl: opts.registry,\n      token: bearer.token,\n      pin: opts.pin === true,\n    });\n    installedSlug = result.entry.slug;\n    installedName = result.entry.slug;\n    if (!asJson && !result.noop) {\n      printStepSuccess(`Added ${installedSlug} from registry`);\n    }\n  } else if (resolved.kind === 'github') {\n    const discovery = await discoverGithubForAdd(resolved, { ref: opts.ref });\n    if (discovery.skills.length === 0) {\n      throw new Error(`No skills found in ${discovery.owner}/${discovery.repo}.`);\n    }\n    if (!asJson) {\n      const label = discovery.skills.length === 1 ? 'skill' : 'skills';\n      printStepInfo(`Found ${discovery.skills.length} ${label}`);\n    }\n    if (opts.list === true) {\n      if (asJson) {\n        return {\n          kind: 'skill',\n          source: resolved.display,\n          skills: discovery.skills.map((s) => s.slug),\n          adapters: [],\n          synced: false,\n          materialized: 0,\n        };\n      }\n      for (const s of discovery.skills) {\n        console.log(`  ${s.slug}${s.description ? ` \u2014 ${s.description}` : ''}`);\n      }\n      return {\n        kind: 'skill',\n        source: resolved.display,\n        skills: discovery.skills.map((s) => s.slug),\n        adapters: [],\n        synced: false,\n        materialized: 0,\n      };\n    }\n\n    let chosen: DiscoveredGitHubSkill[];\n    if (opts.skill.length > 0 || opts.yes === true || !interactive) {\n      chosen = await selectSkills(discovery, { skill: opts.skill, all: opts.yes === true });\n    } else {\n      const one = await pickGithubSkillInteractive(discovery.skills);\n      chosen = one ? [one] : [];\n    }\n    if (chosen.length === 0) {\n      throw new Error('No skill selected.');\n    }\n    if (chosen.length > 1 && !asJson) {\n      printStepSelect(`Selected ${chosen.length} skills: ${chosen.map((s) => s.slug).join(', ')}`);\n    } else if (!asJson) {\n      printStepSelect(`Selected: ${chosen[0]!.slug}`, chosen[0]!.slug);\n    }\n\n    if (chosen.length > 1) {\n      throw new Error(\n        'Single-install supports one skill at a time. Pick one with --skill or run again.',\n      );\n    }\n    const skill = chosen[0]!;\n    const entry = await importGitHubSkill(discovery, skill);\n    installedSlug = entry.slug;\n    installedName = entry.name;\n    if (!asJson) {\n      printStepSuccess(`Imported \"${installedName}\" as ${installedSlug}`);\n    }\n  } else if (resolved.kind === 'local_path' && resolved.localPath) {\n    const entry = await importSkill(resolved.localPath);\n    installedSlug = entry.slug;\n    installedName = entry.name;\n    if (!asJson) {\n      printStepSelect(`Selected: ${installedSlug}`, installedSlug);\n      printStepSuccess(`Imported \"${installedName}\" as ${installedSlug}`);\n    }\n  } else {\n    throw new Error('Unsupported source type.');\n  }\n\n  const cwd = opts.cwd ?? process.cwd();\n  const detected = await detectInstalledAdapters();\n  const picked = await pickAdapters(detected, {\n    yes: opts.yes,\n    adapterFlags: opts.adapter,\n    interactive,\n    global: opts.global,\n    cwd,\n  });\n\n  if (detected.length === 0 && !asJson) {\n    warnNoAdditionalRuntimes();\n  }\n\n  const bearer = await loadRegistryBearer(opts.token);\n  const syncResult = await runPostInstallMaterialize(cwd, [installedSlug], picked, {\n    token: bearer.token || undefined,\n    registryUrl: opts.registry,\n    asJson,\n    autoApprove: opts.yes === true,\n    skipPull: true,\n  });\n\n  if (!asJson) {\n    printStepSuccess(\n      `Installed ${installedSlug} \u2192 synced to ${syncResult.materialized} agent(s) (${formatAdapterList(picked)})`,\n    );\n    if (resolved.kind !== 'registry_skill') {\n      printAddHint('On this machine only for now. Put it on your other machines with `skillet upload`');\n    }\n  }\n\n  return {\n    kind: 'skill',\n    source: resolved.display,\n    skill: installedSlug,\n    adapters: syncResult.adapterNames,\n    synced: syncResult.synced,\n    materialized: syncResult.materialized,\n  };\n}\n\n/**\n * Does this `add` source resolve to a kit? Only `@owner/slug` refs can, and\n * only when we hold a session bearer (kit reads/subscribes are session-scoped).\n * A read-only probe: null/404 \u2192 not a kit \u2192 the skill flow handles it.\n */\nasync function sourceIsKit(source: string | undefined, opts: AddFlowOptions): Promise<boolean> {\n  const ref = source?.trim();\n  if (!ref || !ref.startsWith('@')) return false;\n  const session = await loadSessionToken(opts.token);\n  if (!session || !session.startsWith('skillet_s_')) return false;\n  const kit = await findKitByHandle(ref, {\n    registryUrl: opts.registry,\n    token: session,\n  });\n  return kit !== null;\n}\n\nexport async function runKitAddFlow(ref: string, opts: AddFlowOptions): Promise<AddFlowResult> {\n  const asJson = opts.json === true;\n  const interactive = !asJson && process.stdin.isTTY === true && process.stdout.isTTY === true;\n  configureAddPresent({ json: asJson });\n\n  if (!asJson) {\n    printAddBanner();\n  }\n\n  const session = await loadSessionToken(opts.token);\n  if (!session || !session.startsWith('skillet_s_')) {\n    throw new Error(kitAuthMessage());\n  }\n\n  if (!asJson) {\n    printStepInfo(`Kit: ${ref.startsWith('@') ? ref : `@${ref}`}`);\n  }\n\n  const sub = await subscribeKitByHandle(ref, {\n    registryUrl: opts.registry,\n    token: session,\n  });\n\n  if (!asJson) {\n    printStepInfo(`Found kit \"${sub.kitName}\" with ${sub.skillCount} skill(s)`);\n    if (sub.alreadySubscribed) {\n      printStepSelect(`Already subscribed to ${sub.kitName}`);\n    } else {\n      printStepSuccess(`Subscribed to ${sub.kitName}`);\n    }\n  }\n\n  const cwd = opts.cwd ?? process.cwd();\n  const detected = await detectInstalledAdapters();\n  const picked = await pickAdapters(detected, {\n    yes: opts.yes,\n    adapterFlags: opts.adapter,\n    interactive,\n    global: opts.global,\n    cwd,\n  });\n\n  if (detected.length === 0 && !asJson) {\n    warnNoAdditionalRuntimes();\n  }\n\n  const syncResult = await runPostInstallMaterialize(cwd, sub.skillRefs, picked, {\n    token: session,\n    registryUrl: opts.registry,\n    asJson,\n    autoApprove: opts.yes === true,\n    skipPull: false,\n  });\n\n  const kitRef = `@${sub.owner}/${sub.slug}`;\n  if (!asJson) {\n    printStepSuccess(\n      `Kit ${kitRef} \u2192 synced to ${syncResult.materialized} agent(s) (${formatAdapterList(picked)})`,\n    );\n  }\n\n  return {\n    kind: 'kit',\n    source: kitRef,\n    kit: kitRef,\n    adapters: syncResult.adapterNames,\n    synced: syncResult.synced,\n    materialized: syncResult.materialized,\n  };\n}\n\nfunction sharedAddOptions(cmd: Command): void {\n  cmd\n    .option('--registry <url>', 'Registry base URL', REGISTRY_DEFAULT)\n    .option('--ref <ref>', 'GitHub branch, tag, or commit')\n    .option(\n      '--skill <name>',\n      'Install only the named skill(s) from a repo; repeatable',\n      collect,\n      [] as string[],\n    )\n    .option('--list', 'List discoverable skills without installing')\n    .option('-y, --yes', 'Skip prompts; use defaults')\n    .option('-g, --global', 'Install only to Universal ~/.agents/skills (skip other agents)')\n    .option('-a, --adapter <name>', 'Target agent(s) by name; repeatable', collect, [] as string[])\n    .option('--json', 'Machine-readable output')\n    .option('--token <token>', 'Bearer token override')\n    .option('--pin', 'Pin registry skill to current version')\n    .option('--cwd <dir>', 'Working directory for skillet.lock', process.cwd());\n}\n\nexport function registerAddCommand(program: Command): void {\n  const addCmd = program\n    .command('add [source]')\n    .description('Add a skill or kit from the library, GitHub, or a path');\n\n  sharedAddOptions(addCmd);\n\n  addCmd.action(async (source: string | undefined, opts: AddFlowOptions) => {\n    // Pairing gate for EVERY source branch (GitHub, local path, registry) \u2014\n    // unpaired machines never fetch, prompt, or write the kit. The gate\n    // precedes source resolution, so no GitHub/registry request is attempted.\n    // In --json mode the auth_required envelope goes to stdout (sidecar contract).\n    await requirePaired(opts.token, { json: opts.json === true });\n    try {\n      // A bare `@owner/slug` can name a kit or a skill. Probe the kit namespace\n      // first (read-only, session bearer); on a hit, subscribe it as a kit,\n      // otherwise install it as a skill. GitHub URLs and local paths are never\n      // kits, so only `@`-refs are probed \u2014 one verb, `add`, covers both.\n      if (await sourceIsKit(source, opts)) {\n        const result = await runKitAddFlow(source!.trim(), opts);\n        if (opts.json === true) {\n          writeJsonOk(result);\n        }\n        return;\n      }\n      const result = await runSkillAddFlow(source, opts);\n      if (opts.json === true) {\n        writeJsonOk(result);\n      }\n    } catch (err) {\n      const message = (err as Error).message;\n      if (opts.json === true) {\n        writeJsonError(message);\n      } else {\n        printAddError(message);\n        exitWith(ExitCode.ERROR);\n      }\n    }\n  });\n\n  // `add kit <ref>` stays as an explicit escape hatch (and the scripting/tray\n  // contract), but it is off the root help surface: bare `add` auto-detects.\n  const kitCmd = addCmd\n    .command('kit <ref>')\n    .description('Subscribe to a kit and sync its skills');\n\n  sharedAddOptions(kitCmd);\n\n  kitCmd.action(async (ref: string, opts: AddFlowOptions) => {\n    // Same pairing gate as `add` \u2014 kit subscribe is a kit-write path too.\n    await requirePaired(opts.token, { json: opts.json === true });\n    try {\n      const result = await runKitAddFlow(ref, opts);\n      if (opts.json === true) {\n        writeJsonOk(result);\n      }\n    } catch (err) {\n      const message = (err as Error).message;\n      if (opts.json === true) {\n        writeJsonError(message);\n      } else {\n        printAddError(message);\n        exitWith(ExitCode.ERROR);\n      }\n    }\n  });\n}\n", "/**\n * Shared \"this machine is not paired\" failure \u2014 the single source for the\n * auth-required copy, the `--json` envelope, and the exit code.\n *\n * Every command that requires pairing (sync, import, add, discovery) imports\n * from here. Reusing the copy must be an import, not a convention \u2014 do not\n * restate this guidance at call sites.\n */\nimport { loadRegistryBearer, type RegistryBearer } from \"@skillet/core\";\nimport { webBaseUrl } from \"./cli-command-tier.js\";\nimport { ExitCode, exitWith } from \"./exit-codes.js\";\nimport { fail, dim, bold, cyan } from \"./cli-colors.js\";\n\n/** Machine-readable error tag for `--json` consumers (desktop sidecar contract). */\nexport const AUTH_REQUIRED = \"auth_required\";\n\n/** Stable exit code for the unpaired failure (CLI reference on skillet.md). */\nexport const AUTH_REQUIRED_EXIT = ExitCode.AUTH;\n\n/** Human guidance: sign in on the web, get a pair code, run `skillet connect`. */\nexport function authRequiredMessage(): string {\n  const web = webBaseUrl();\n  return `This machine is not paired to an account. Sign in on ${web}, get a pair code at ${web}/settings, then run \\`skillet connect <code>\\`.`;\n}\n\nexport interface AuthRequiredJson {\n  ok: false;\n  error: typeof AUTH_REQUIRED;\n  code: typeof AUTH_REQUIRED;\n  message: string;\n}\n\n/** `--json` envelope for unpaired commands. */\nexport function authRequiredJson(): AuthRequiredJson {\n  return {\n    ok: false,\n    error: AUTH_REQUIRED,\n    code: AUTH_REQUIRED,\n    message: authRequiredMessage(),\n  };\n}\n\n/**\n * Print the auth-required failure and exit non-zero.\n *\n * In `--json` mode the envelope MUST go to stdout: the desktop parses stdout\n * and classifies non-JSON output as an approval block and stderr-only failure\n * as offline (packages/desktop/src/main.ts getSurfacesUncached), so a bare\n * text error here would misroute every background tick.\n */\nexport function failAuthRequired(opts: { json?: boolean } = {}): never {\n  if (opts.json === true) {\n    process.stdout.write(JSON.stringify(authRequiredJson(), null, 2) + \"\\n\");\n  } else {\n    // Same facts as authRequiredMessage(), shaped for a person: problem first,\n    // URL and command each ending their own line. The first sentence must keep\n    // \"is not paired to an account\" \u2014 desktop tray-logic classifies by that\n    // prose as a fallback when the code field is absent.\n    const web = webBaseUrl();\n    console.error(fail(\"This machine is not paired to an account.\"));\n    console.error(dim(\"  Sign in and get a pair code at \") + cyan(`${web}/settings`));\n    console.error(dim(\"  Then run \") + bold(\"skillet connect <code>\"));\n  }\n  exitWith(AUTH_REQUIRED_EXIT);\n}\n\n/**\n * Gate a command on pairing, returning the resolved bearer. An unpaired machine\n * (bearer kind 'none') triggers failAuthRequired, which exits non-zero with the\n * correct stdout/stderr envelope \u2014 so every gated command shares one check and\n * none can get that contract wrong. Callers past this point have a usable bearer.\n */\nexport async function requirePaired(\n  token?: string,\n  opts: { json?: boolean } = {},\n): Promise<RegistryBearer> {\n  const bearer = await loadRegistryBearer(token);\n  if (bearer.kind === \"none\") failAuthRequired({ json: opts.json === true });\n  return bearer;\n}\n", "/**\n * Stable CLI exit codes for CI and scripting.\n * Documented in packages/web/content/docs/cli.md \u2014 do not renumber without a major bump.\n */\nexport const ExitCode = {\n  /** Command completed successfully. */\n  OK: 0,\n  /** General failure (sync adapter fail, quarantined status, etc.). */\n  ERROR: 1,\n  /** Invalid usage / missing required args. */\n  USAGE: 2,\n  /** Auth required or auth rejected. */\n  AUTH: 3,\n  /** Conflict / stale base / registry 409. */\n  CONFLICT: 4,\n} as const;\n\nexport type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode];\n\nexport function exitWith(code: ExitCodeValue): never {\n  process.exit(code);\n}\n", "import { ExitCode, exitWith, type ExitCodeValue } from \"./exit-codes.js\";\n\n/** Machine-readable CLI envelope for `--json` responses. */\nexport interface JsonEnvelope<T = unknown> {\n  ok: boolean;\n  data?: T;\n  error?: string;\n  code?: string;\n}\n\nexport function writeJson<T>(payload: JsonEnvelope<T>, exitCode?: ExitCodeValue): void {\n  process.stdout.write(JSON.stringify(payload, null, 2) + \"\\n\");\n  if (exitCode !== undefined && exitCode !== ExitCode.OK) {\n    exitWith(exitCode);\n  }\n}\n\nexport function writeJsonOk<T>(data: T, exitCode: ExitCodeValue = ExitCode.OK): void {\n  writeJson({ ok: true, data }, exitCode);\n}\n\nexport function writeJsonError(\n  message: string,\n  opts: { code?: string; exitCode?: ExitCodeValue } = {},\n): never {\n  const exitCode = opts.exitCode ?? ExitCode.ERROR;\n  process.stdout.write(\n    JSON.stringify(\n      { ok: false, error: message, ...(opts.code ? { code: opts.code } : {}) },\n      null,\n      2,\n    ) + \"\\n\",\n  );\n  exitWith(exitCode);\n}\n\n/** Legacy `{ ok, ...fields }` blobs still emitted by some commands \u2014 wrap for consistency. */\nexport function legacyOrEnvelope<T extends Record<string, unknown>>(\n  legacy: T,\n  asJson: boolean,\n): void {\n  if (!asJson) return;\n  process.stdout.write(JSON.stringify(legacy, null, 2) + \"\\n\");\n}\n", "import { cyan, dim, green } from './cli-colors.js';\nimport { printRenderedError } from './render-error.js';\n\nexport interface AddPresentOptions {\n  color?: boolean;\n  json?: boolean;\n}\n\nlet colorEnabled = process.stdout.isTTY === true;\n\nexport function configureAddPresent(opts: AddPresentOptions): void {\n  if (opts.json === true) {\n    colorEnabled = false;\n    return;\n  }\n  if (opts.color === false) {\n    colorEnabled = false;\n  }\n}\n\nfunction paint(code: string, text: string): string {\n  if (!colorEnabled) return text;\n  return `\\u001b[${code}m${text}\\u001b[0m`;\n}\n\nconst stepPrefix = () => paint('2', '\u2502');\n\nexport function printAddBanner(): void {\n  // skills.sh-style add stays quiet at the top \u2014 steps carry the story.\n}\n\nexport function printStepInfo(message: string): void {\n  console.log(`${stepPrefix()} ${paint('36', '\u25C7')} ${message}`);\n}\n\nexport function printStepSelect(message: string, highlight?: string): void {\n  const body = highlight ? message.replace(highlight, cyan(highlight)) : message;\n  console.log(`${stepPrefix()} ${paint('34', '\u25C6')} ${body}`);\n}\n\nexport function printStepSuccess(message: string): void {\n  console.log(`${stepPrefix()} ${green('\u25C6')} ${message}`);\n}\n\nexport function printAddHint(message: string): void {\n  console.log(dim(message));\n}\n\nexport function printAddError(message: string): void {\n  // House convention: the glyph carries the verdict in color, message plain.\n  // The renderer maps internal codes to a sentence + next action and strips\n  // control characters from registry-supplied text.\n  printRenderedError(message, (what) => `${paint('31', '\u2717')} ${what}`);\n}\n", "import type { Adapter } from '@skillet/core';\nimport { runtimeLabel } from '@skillet/core';\nimport * as clack from '@clack/prompts';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { ADDITIONAL_ADAPTERS } from './cli-context.js';\nimport { baselineAdaptersForCwd, isBaselineAdapterName } from './adapter-tiers.js';\nimport { dim } from './cli-colors.js';\n\nexport interface DetectedAdapter {\n  adapter: Adapter;\n  name: string;\n  label: string;\n  pathHint: string;\n}\n\nfunction adapterPathHint(adapter: Adapter): string {\n  return adapter.targetDir;\n}\n\nexport async function detectInstalledAdapters(): Promise<DetectedAdapter[]> {\n  const detected: DetectedAdapter[] = [];\n  for (const adapter of ADDITIONAL_ADAPTERS) {\n    try {\n      if (await adapter.detect()) {\n        detected.push({\n          adapter,\n          name: adapter.name,\n          label: runtimeLabel(adapter.name),\n          pathHint: adapterPathHint(adapter),\n        });\n      }\n    } catch {\n      // Non-fatal \u2014 skip adapters that fail detect.\n    }\n  }\n  return detected;\n}\n\nexport interface PickAdaptersOptions {\n  yes?: boolean;\n  adapterFlags?: string[];\n  interactive?: boolean;\n  /** Install only to universal baseline; skip additional runtimes. */\n  global?: boolean;\n  cwd?: string;\n}\n\nfunction pickByFlags(\n  detected: DetectedAdapter[],\n  wanted: Set<string>,\n): DetectedAdapter[] {\n  const additionalWanted = [...wanted].filter((w) => !isBaselineAdapterName(w));\n  const wantedSet = new Set(additionalWanted);\n  const picked = detected.filter((d) => wantedSet.has(d.name));\n  const missing = additionalWanted.filter((w) => !picked.some((p) => p.name === w));\n  if (missing.length > 0) {\n    throw new Error(\n      `Unknown or undetected agent(s): ${missing.join(', ')}. Detected additional: ${detected.map((d) => d.name).join(', ') || '(none)'}. Universal ~/.agents/skills is always included.`,\n    );\n  }\n  return picked;\n}\n\nasync function printUniversalBaseline(cwd: string): Promise<boolean> {\n  const homeAgents = join(homedir(), '.agents', 'skills');\n  console.log(dim(`Universal (${homeAgents}) \u2014 always included`));\n  const baseline = await baselineAdaptersForCwd(cwd);\n  const hasProject = baseline.some((a) => a.name === 'codex-project');\n  if (hasProject) {\n    console.log(dim('Universal (./.agents/skills) \u2014 always included for this project'));\n  }\n  return hasProject;\n}\n\nasync function pickAdditionalInteractive(\n  detected: DetectedAdapter[],\n  cwd: string,\n): Promise<DetectedAdapter[]> {\n  await printUniversalBaseline(cwd);\n\n  if (detected.length === 0) {\n    return [];\n  }\n\n  const additionalPick = await clack.multiselect({\n    message: 'Also install to which agents?',\n    options: detected.map((d) => ({\n      value: d.name,\n      label: d.label,\n      hint: d.pathHint,\n    })),\n    required: false,\n  });\n  if (clack.isCancel(additionalPick)) {\n    throw new Error('Install cancelled.');\n  }\n\n  const names = new Set(additionalPick as string[]);\n  return detected.filter((d) => names.has(d.name));\n}\n\nexport async function pickAdapters(\n  detected: DetectedAdapter[],\n  opts: PickAdaptersOptions,\n): Promise<DetectedAdapter[]> {\n  const cwd = opts.cwd ?? process.cwd();\n\n  if (opts.adapterFlags && opts.adapterFlags.length > 0) {\n    const wanted = new Set(opts.adapterFlags.map((a) => a.toLowerCase()));\n    return pickByFlags(detected, wanted);\n  }\n\n  if (opts.global === true || opts.yes === true || opts.interactive === false) {\n    return [];\n  }\n\n  if (detected.length === 0) {\n    await printUniversalBaseline(cwd);\n    return [];\n  }\n\n  if (detected.length === 1) {\n    await printUniversalBaseline(cwd);\n    const only = detected[0]!;\n    const pickOne = await clack.confirm({\n      message: `Also install to ${only.label}?`,\n      initialValue: false,\n    });\n    if (clack.isCancel(pickOne)) {\n      throw new Error('Install cancelled.');\n    }\n    return pickOne ? [only] : [];\n  }\n\n  return pickAdditionalInteractive(detected, cwd);\n}\n\nexport function formatAdapterList(adapters: DetectedAdapter[]): string {\n  if (adapters.length === 0) return 'Universal only';\n  return `Universal + ${adapters.map((a) => a.label).join(', ')}`;\n}\n\nexport function warnNoAdditionalRuntimes(): void {\n  console.log(\n    dim(\n      'No other agents detected. Installed to Universal ~/.agents/skills only; run `skillet sync` after installing another agent.',\n    ),\n  );\n}\n\n/** @internal test helper */\nexport function partitionAdapters(detected: DetectedAdapter[]): {\n  additional: DetectedAdapter[];\n} {\n  return { additional: detected };\n}\n", "import { access } from 'node:fs/promises';\nimport {\n  discoverGitHubSkills,\n  looksLikeGitHubSpec,\n  parseSkillRef,\n  SkillRefError,\n  type GitHubDiscovery,\n} from '@skillet/core';\n\nexport type AddSourceKind = 'github' | 'registry_skill' | 'local_path' | 'missing';\n\nexport interface ResolvedAddSource {\n  kind: AddSourceKind;\n  /** Original user input. */\n  raw: string;\n  /** Display label for stepped output. */\n  display: string;\n  githubRef?: string;\n  registryRef?: string;\n  localPath?: string;\n}\n\nexport function isRegistrySkillRef(source: string): boolean {\n  if (!source.startsWith('@')) return false;\n  try {\n    parseSkillRef(source);\n    return true;\n  } catch (err) {\n    if (err instanceof SkillRefError) return false;\n    throw err;\n  }\n}\n\nexport function normalizeRegistryRef(source: string): string {\n  const ref = source.startsWith('@') ? source : `@${source}`;\n  return parseSkillRef(ref).canonical;\n}\n\nexport async function resolveAddSource(source: string | undefined): Promise<ResolvedAddSource> {\n  const raw = (source ?? '').trim();\n  if (!raw) {\n    return { kind: 'missing', raw: '', display: '' };\n  }\n\n  if (raw.startsWith('@')) {\n    const registryRef = normalizeRegistryRef(raw);\n    return { kind: 'registry_skill', raw, display: registryRef, registryRef };\n  }\n\n  if (looksLikeGitHubSpec(raw)) {\n    return {\n      kind: 'github',\n      raw,\n      display: raw.includes('github.com') ? raw : `https://github.com/${raw.replace(/^\\/+/, '')}`,\n      githubRef: raw,\n    };\n  }\n\n  try {\n    await access(raw);\n    return { kind: 'local_path', raw, display: raw, localPath: raw };\n  } catch {\n    // Not a readable local path \u2014 may still be a bundle path the importer resolves.\n  }\n\n  if (raw.startsWith('.') || raw.startsWith('/') || raw.startsWith('~')) {\n    return { kind: 'local_path', raw, display: raw, localPath: raw };\n  }\n\n  return { kind: 'missing', raw, display: raw };\n}\n\nexport async function discoverGithubForAdd(\n  source: ResolvedAddSource,\n  opts: { ref?: string },\n): Promise<GitHubDiscovery> {\n  if (source.kind !== 'github' || !source.githubRef) {\n    throw new Error('Not a GitHub source');\n  }\n  return discoverGitHubSkills(source.githubRef, opts.ref ? { ref: opts.ref } : {});\n}\n", "import * as clack from \"@clack/prompts\";\nimport {\n  importSkill,\n  discoverGitHubSkills,\n  importGitHubSkill,\n  looksLikeGitHubSpec,\n  discoverExistingSkills,\n  importDiscoveredSkills,\n  uploadLocalSkills,\n  runtimePhrase,\n  runtimesAcross,\n  type DiscoveredGitHubSkill,\n  type GitHubDiscovery,\n  type DiscoveredSkill,\n  type UploadProgressEvent,\n} from \"@skillet/core\";\nimport { ok, fail, green, red, dim, bold } from \"../cli-colors.js\";\nimport type { Command } from \"commander\";\nimport { requirePaired } from \"../auth-required.js\";\nimport { ALL_ADAPTERS, collect, pathExists, REGISTRY_DEFAULT } from \"../cli-context.js\";\nimport { applyToAgents } from \"../apply-to-agents.js\";\nimport { configureAddPresent, printAddError, printStepInfo } from \"../cli-add-present.js\";\nimport { renderUploadProgress, summarizeUploadResult } from \"./upload-present.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { printRenderedError } from \"../render-error.js\";\nimport { stripControlChars } from \"../sanitize-output.js\";\n\n/** Options shared by every import branch that decide whether we also publish. */\ninterface UploadIntent {\n  /** `--local`: import into the kit only, never publish to the account. */\n  local?: boolean;\n}\n\n/**\n * Pick which discovered GitHub skills to import. `--all` and `--skill` bypass\n * the prompt entirely; a single discovered skill auto-selects. Only the\n * genuinely-ambiguous interactive case opens a readline picker, and a non-TTY\n * run with no selector is a clean error rather than a hang.\n */\nexport async function selectSkills(\n  discovery: GitHubDiscovery,\n  opts: { skill: string[]; all?: boolean; yes?: boolean },\n): Promise<DiscoveredGitHubSkill[]> {\n  const { skills } = discovery;\n  // -y promises \"no prompting\" everywhere, same as add: take everything.\n  if (opts.all || opts.yes) return skills;\n\n  if (opts.skill.length > 0) {\n    const wanted = new Set(opts.skill.map((s) => s.toLowerCase()));\n    const picked = skills.filter(\n      (s) =>\n        wanted.has(s.slug.toLowerCase()) || wanted.has(s.name.toLowerCase()),\n    );\n    const matchedKeys = new Set(\n      picked.flatMap((s) => [s.slug.toLowerCase(), s.name.toLowerCase()]),\n    );\n    const missing = [...wanted].filter((w) => !matchedKeys.has(w));\n    if (missing.length > 0) {\n      throw new Error(\n        `No skill named ${missing.map((m) => `\"${m}\"`).join(\", \")} in ${discovery.owner}/${discovery.repo}. Available: ${skills.map((s) => s.slug).join(\", \") || \"(none)\"}`,\n      );\n    }\n    return picked;\n  }\n\n  if (skills.length === 1) return skills;\n\n  if (!process.stdin.isTTY) {\n    throw new Error(\n      `${skills.length} skills found in ${discovery.owner}/${discovery.repo}. Re-run with --all or --skill <name> (non-interactive). Available: ${skills.map((s) => s.slug).join(\", \")}`,\n    );\n  }\n\n  const picked = await clack.multiselect({\n    message: `Found ${skills.length} skills in ${discovery.owner}/${discovery.repo}@${discovery.ref}. Which to import?`,\n    options: skills.map((s) => ({\n      value: s.slug,\n      // Repo-supplied text is a trust boundary: strip terminal escapes.\n      label: stripControlChars(s.slug),\n      hint: s.description || s.dir ? stripControlChars(s.description ?? s.dir ?? \"\") : undefined,\n    })),\n    required: false,\n  });\n  // Esc or empty: cancel quietly \u2014 a mistyped pick can never abort the run.\n  if (clack.isCancel(picked) || !Array.isArray(picked) || picked.length === 0) return [];\n  const wanted = new Set(picked as string[]);\n  return skills.filter((s) => wanted.has(s.slug));\n}\n\nexport async function runGitHubImport(\n  source: string,\n  opts: { ref?: string; skill: string[]; all?: boolean; yes?: boolean; force?: boolean; local?: boolean },\n): Promise<void> {\n  const discovery = await discoverGitHubSkills(\n    source,\n    opts.ref ? { ref: opts.ref } : {},\n  );\n\n  if (discovery.truncated) {\n    console.log(\n      \"\u26A0  GitHub truncated the file listing for this repo \u2014 some skills may be missing.\",\n    );\n  }\n\n  if (discovery.skills.length === 0) {\n    console.log(\n      `No SKILL.md bundles found in ${discovery.owner}/${discovery.repo}@${discovery.ref}.`,\n    );\n    return;\n  }\n\n  const chosen = await selectSkills(discovery, opts);\n  if (chosen.length === 0) {\n    console.log(\"Nothing selected \u2014 no skills imported.\");\n    return;\n  }\n\n  let failures = 0;\n  const imported: string[] = [];\n  for (const skill of chosen) {\n    try {\n      const entry = await importGitHubSkill(discovery, skill, { force: opts.force === true });\n      imported.push(entry.slug);\n      console.log(ok(stripControlChars(`Imported \"${entry.name}\" as ${entry.slug} (private to your kit)`)));\n      console.log(`  hash: ${entry.hash}`);\n    } catch (err) {\n      failures++;\n      console.error(fail(`${skill.slug}: ${(err as Error).message}`));\n    }\n  }\n  console.log(\n    `\\nImported ${chosen.length - failures}/${chosen.length} skill(s) from ${discovery.owner}/${discovery.repo}.`,\n  );\n  await applyImported(imported);\n  await uploadImported(imported, { local: opts.local === true });\n  if (failures > 0) exitWith(ExitCode.ERROR);\n}\n\n/**\n * Ask a yes/no question on the terminal. Default is No; Esc cancels (also\n * No \u2014 callers treat this as \"don't act\", never as a recorded opt-out).\n * Non-TTY returns false, preserving the headless deny-by-default contract.\n */\nexport async function confirm(question: string): Promise<boolean> {\n  if (process.stdout.isTTY !== true) return false;\n  const answer = await clack.confirm({ message: question, initialValue: false });\n  return !clack.isCancel(answer) && answer === true;\n}\n\n/**\n * A scannable list of what we'd import: grouped by where each skill runs, names\n * only. The full descriptions (often a paragraph each) are noise at the\n * import-decision moment \u2014 the user is choosing whether to bring skills they\n * already run into their kit, not reading the catalog. Names wrap into short\n * lines so a big list stays compact instead of scrolling off-screen.\n */\nfunction renderDiscoveredGroups(skills: DiscoveredSkill[]): string {\n  // Group by the combined runtime phrase (e.g. \"Universal\", \"Claude Code\",\n  // \"Universal + Claude Code\"), preserving first-seen order.\n  const groups = new Map<string, string[]>();\n  for (const s of skills) {\n    const where = runtimePhrase(s.runtimes);\n    const names = groups.get(where) ?? [];\n    names.push(s.name);\n    groups.set(where, names);\n  }\n\n  const WIDTH = 64;\n  const lines: string[] = [];\n  for (const [where, names] of groups) {\n    if (lines.length > 0) lines.push(\"\");\n    lines.push(`  ${bold(where)}`);\n    let row = \"\";\n    for (const name of names) {\n      const next = row ? `${row}  ${name}` : name;\n      if (row && next.length > WIDTH) {\n        lines.push(`    ${row}`);\n        row = name;\n      } else {\n        row = next;\n      }\n    }\n    if (row) lines.push(`    ${row}`);\n  }\n  return lines.join(\"\\n\");\n}\n\n/**\n * Scan installed runtimes for skills the user already runs and offer to import.\n * Reuses the local-import path; interactive imports also back up to the account\n * as private (skip with `--local`).\n */\nexport async function runDiscovery(opts: { assumeYes: boolean; local?: boolean }): Promise<void> {\n  const report = await discoverExistingSkills(ALL_ADAPTERS);\n\n  if (report.scannedRuntimes.length === 0) {\n    console.log(\n      \"No supported agents detected yet. Install Claude Code or Codex, or import a skill directly with `skillet import <path>`.\",\n    );\n    return;\n  }\n\n  const scannedPhrase = runtimePhrase(report.scannedRuntimes);\n  const skippedSkillet = report.skills.filter((s) => s.fromSkillet && !s.alreadyInKit).length;\n\n  if (report.newSkills.length === 0) {\n    if (report.skills.length > 0) {\n      if (skippedSkillet > 0 && report.skills.every((s) => s.fromSkillet || s.alreadyInKit)) {\n        const parts: string[] = [];\n        const inKit = report.skills.filter((s) => s.alreadyInKit).length;\n        if (inKit > 0) parts.push(`${inKit} already in your kit`);\n        if (skippedSkillet > 0) parts.push(`${skippedSkillet} already synced from Skillet`);\n        console.log(ok(`You're all set \u2014 ${parts.join(\", \")} across ${scannedPhrase}.`));\n      } else {\n        console.log(\n          ok(`You're all set \u2014 all ${report.skills.length} skill(s) across ${scannedPhrase} are already in your kit.`),\n        );\n      }\n    } else {\n      console.log(\n        `No existing skills found in ${scannedPhrase}. Import one with \\`skillet import <path>\\` whenever you're ready.`,\n      );\n    }\n    return;\n  }\n\n  const where = runtimePhrase(runtimesAcross(report.newSkills));\n  const n = report.newSkills.length;\n  if (skippedSkillet > 0) {\n    console.log(\n      `  (${skippedSkillet} skill${skippedSkillet === 1 ? \"\" : \"s\"} already synced from Skillet \u2014 skipping)`,\n    );\n  }\n  console.log(\n    `\\nWe found ${n} skill${n === 1 ? \"\" : \"s\"} you already run across ${where}.\\n`,\n  );\n  console.log(renderDiscoveredGroups(report.newSkills));\n\n  // Pick which to import. Headless (`-y` or non-TTY \u2014 how the desktop's\n  // background scan runs) takes all with no prompt and stays local, since\n  // uploadImported no-ops off a TTY. Interactive opens a checkbox list with\n  // everything pre-checked: \"import all\" is one Enter, narrowing is a few\n  // spacebars.\n  let selected: DiscoveredSkill[];\n  if (opts.assumeYes) {\n    selected = report.newSkills;\n  } else if (process.stdin.isTTY !== true) {\n    console.log(\n      \"\\nNon-interactive terminal \u2014 skipping import. Re-run with `skillet import --yes` to import all, or `skillet import <path>` for one.\",\n    );\n    return;\n  } else {\n    console.log(\n      opts.local === true\n        ? \"\\nSelected skills go into your kit only.\"\n        : \"\\nSelected skills go into your kit and are backed up to your account, private.\",\n    );\n    const picked = await clack.multiselect({\n      message: \"Which skills should we import?\",\n      options: report.newSkills.map((s, i) => ({\n        value: String(i),\n        label: stripControlChars(s.name),\n        hint: stripControlChars(runtimePhrase(s.runtimes)),\n      })),\n      initialValues: report.newSkills.map((_, i) => String(i)),\n      required: false,\n    });\n    if (clack.isCancel(picked) || !Array.isArray(picked) || picked.length === 0) {\n      console.log(\"\\nNothing selected \u2014 no skills imported.\");\n      return;\n    }\n    const wanted = new Set(picked as string[]);\n    selected = report.newSkills.filter((_, i) => wanted.has(String(i)));\n  }\n\n  const result = await importDiscoveredSkills(selected);\n  console.log(\"\");\n  for (const e of result.imported) {\n    console.log(`  ${green(\"\u2713\")} Imported \"${e.name}\" as ${e.slug}`);\n  }\n  for (const f of result.failed) {\n    console.log(`  ${red(\"\u2717\")} ${f.name}: ${f.error}`);\n  }\n  console.log(`\\nImported ${result.imported.length} skill(s) into your kit.`);\n  const importedSlugs = result.imported.map((e) => e.slug);\n  await applyImported(importedSlugs);\n  await uploadImported(importedSlugs, { local: opts.local === true });\n  if (result.failed.length > 0) exitWith(ExitCode.ERROR);\n}\n\n/**\n * Imports finish their own job (no \"now run skillet sync\" homework): put the\n * just-imported skills into the agents on this machine with a scoped apply.\n * Quiet on skips; quarantined entries keep their gate (non-TTY: skip+reason).\n */\nasync function applyImported(slugs: string[]): Promise<void> {\n  if (slugs.length === 0) return;\n  try {\n    const result = await applyToAgents(slugs, { skipPull: true });\n    const agents = result.adapters.filter((a) => a.status === \"materialized\").length;\n    console.log(dim(`  In your agents now (${agents} on this machine).`));\n  } catch (err) {\n    // The import itself succeeded \u2014 never let this read as \"Import failed\".\n    printRenderedError(err as Error, (what) =>\n      fail(`Imported, but couldn't put it into your agents: ${what}`),\n    );\n    console.error(dim(\"  Run `skillet sync` to retry.\"));\n    exitWith(ExitCode.ERROR);\n  }\n}\n\n/**\n * Publish the just-imported skills to the user's account as private, so they\n * sync to their other machines. Runs only in an interactive terminal: a\n * headless `import -y` (how the desktop's background scan invokes import) stays\n * local \u2014 the desktop publishes through its own \"back up\" action. `--local`\n * opts out entirely. Non-fatal: the import already landed in the kit, so a\n * publish failure is a warning with a retry hint, never \"Import failed\".\n */\nasync function uploadImported(slugs: string[], opts: UploadIntent): Promise<void> {\n  if (opts.local === true) return;\n  if (process.stdout.isTTY !== true) return;\n  if (slugs.length === 0) return;\n\n  configureAddPresent({ json: false, color: true });\n  try {\n    const result = await uploadLocalSkills({\n      slugs,\n      visibility: \"private\",\n      registryUrl: REGISTRY_DEFAULT,\n      sessionAuth: true,\n      onProgress: (event: UploadProgressEvent) => {\n        if (event.phase === \"start\" && event.index === 0) {\n          printStepInfo(\n            `Publishing ${event.total} skill${event.total === 1 ? \"\" : \"s\"} to your account (private)`,\n          );\n        }\n        renderUploadProgress(event);\n      },\n    });\n    if (result.empty) return;\n    if (result.ok) {\n      console.log(summarizeUploadResult(result, \"private\"));\n    } else {\n      printAddError(\"Some skills didn't publish. Retry with `skillet upload --all`.\");\n    }\n  } catch (err) {\n    printAddError(\n      `Imported to your kit, but publishing to your account failed: ${(err as Error).message}`,\n    );\n    console.error(\n      dim(\"  They're private on this machine. Retry with `skillet upload --all`.\"),\n    );\n  }\n}\n\nexport function registerImportCommand(program: Command): void {\n  program\n    .command(\"import [source]\")\n    .description(\"Bring skills you already have (in your agents or a folder) into your kit\")\n    .option(\"-y, --yes\", \"Import every discovered skill without prompting\")\n    .option(\"--ref <ref>\", \"GitHub branch, tag, or commit to import from\")\n    .option(\n      \"--skill <name>\",\n      \"Import only the named skill(s) from a repo; repeatable. Skips the picker.\",\n      collect,\n      [] as string[],\n    )\n    .option(\"--all\", \"Import every skill found in the repo; skips the picker\")\n    .option(\"--force\", \"Overwrite an existing kit skill when the slug collides\")\n    .option(\"--local\", \"Import into your kit only; don't back up to your account\")\n    .action(\n      async (\n        source: string | undefined,\n        opts: {\n          yes?: boolean;\n          ref?: string;\n          skill: string[];\n          all?: boolean;\n          force?: boolean;\n          local?: boolean;\n        },\n      ) => {\n        // Pairing gate for every import branch (local path, GitHub, runtime\n        // discovery): an unpaired machine never scans, prompts, or writes to\n        // the kit. Core's importSkill/discoverExistingSkills stay auth-free\n        // (KTD3); the gate lives here at the command layer. `import` has no\n        // --json mode, so the desktop's `import -y` gets stderr + exit 3.\n        await requirePaired();\n\n        if (!source) {\n          await runDiscovery({ assumeYes: opts.yes === true, local: opts.local === true });\n          return;\n        }\n        try {\n          if (await pathExists(source)) {\n            const entry = await importSkill(source, { force: opts.force === true });\n            console.log(ok(`Imported \"${entry.name}\" as ${entry.slug}`));\n            console.log(`  hash: ${entry.hash}`);\n            await applyImported([entry.slug]);\n            await uploadImported([entry.slug], { local: opts.local === true });\n            return;\n          }\n          if (looksLikeGitHubSpec(source)) {\n            await runGitHubImport(source, opts);\n            return;\n          }\n          await importSkill(source, { force: opts.force === true });\n        } catch (err) {\n          console.error(fail(`Import failed: ${(err as Error).message}`));\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n}\n", "import {\n  materializeSkills,\n  loadRegistryBearer,\n  type MaterializeSkillsResult,\n} from \"@skillet/core\";\nimport { resolveSyncAdapters } from \"./adapter-tiers.js\";\nimport { REGISTRY_DEFAULT } from \"./cli-context.js\";\n\n/**\n * Scoped \"put these skills into the agents on this machine\" \u2014 the shared tail\n * of every surface that finishes its own job (home-menu review, `approve`,\n * `import`). Bearer + adapter resolution + quiet scoped materialize; callers\n * keep their own success copy and pass only what differs.\n */\nexport async function applyToAgents(\n  slugs: string[],\n  extra: { allowQuarantinedSlugs?: string[]; skipPull?: boolean } = {},\n): Promise<MaterializeSkillsResult> {\n  const bearer = await loadRegistryBearer();\n  const { adapters, baselineNames } = await resolveSyncAdapters(process.cwd());\n  const result = await materializeSkills(process.cwd(), adapters, {\n    slugs,\n    token: bearer.token || undefined,\n    registryUrl: REGISTRY_DEFAULT,\n    baselineAdapterNames: baselineNames,\n    quietSkipLines: true,\n    ...extra,\n  });\n  // Core reports per-skill failures as data, not throws. A caller about to\n  // print \"applied\" must not do so over an integrity or write failure \u2014\n  // surface those here, centrally. Quarantine skips stay non-throwing: they\n  // are an expected gate outcome with their own messaging.\n  const blocking = result.failed.filter((f) => !f.reason.startsWith(\"quarantined\"));\n  if (blocking.length > 0) {\n    const first = blocking[0]!;\n    throw new Error(\n      blocking.length === 1\n        ? `Could not apply \"${first.slug}\": ${first.reason}`\n        : `Could not apply ${blocking.length} skills (first: \"${first.slug}\": ${first.reason})`,\n    );\n  }\n  return result;\n}\n", "import type {\n  UploadLocalSkillsResult,\n  UploadProgressEvent,\n} from \"@skillet/core\";\nimport {\n  printAddError,\n  printStepInfo,\n  printStepSuccess,\n} from \"../cli-add-present.js\";\n\n// Shared upload presentation, used by both `skillet upload` and the publish\n// step folded into `skillet import`. Lives here (not in upload-cmd) so import\n// can reuse it without an import cycle \u2014 upload-cmd imports `confirm` from\n// import-cmd.\n\n/** Bare slug for display \u2014 strip a single promoted `@owner/slug` prefix. */\nexport function displaySlug(stateKey: string): string {\n  const m = /^@([^/]+)\\/(.+)$/.exec(stateKey);\n  return m ? m[2]! : stateKey;\n}\n\nexport function registryRef(owner: string, stateKey: string): string {\n  return `@${owner}/${displaySlug(stateKey)}`;\n}\n\nexport function renderUploadProgress(event: UploadProgressEvent): void {\n  const label = displaySlug(event.slug);\n  if (event.phase === \"start\") {\n    printStepInfo(`Uploading ${label}\u2026`);\n    return;\n  }\n  if (event.phase === \"fail\") {\n    printAddError(`${label}: ${event.error}`);\n    return;\n  }\n  if (event.alreadyExists) {\n    printStepInfo(`${label} unchanged on profile`);\n    return;\n  }\n  printStepSuccess(`${label} \u2192 ${registryRef(event.owner, event.slug)}`);\n}\n\nexport function summarizeUploadResult(\n  result: UploadLocalSkillsResult,\n  visibility: \"private\" | \"public\",\n): string {\n  const vis = visibility === \"public\" ? \"public\" : \"private\";\n  const publishedNew = result.published.filter((p) => !p.alreadyExists).length;\n  const unchanged = result.published.filter((p) => p.alreadyExists).length;\n  const failed = result.failed.length;\n  const parts: string[] = [];\n  if (publishedNew > 0) {\n    parts.push(`${publishedNew} published`);\n  }\n  if (unchanged > 0) {\n    parts.push(`${unchanged} unchanged`);\n  }\n  if (failed > 0) {\n    parts.push(`${failed} failed`);\n  }\n  const detail = parts.length > 0 ? parts.join(\", \") : \"0 skills\";\n  return `\u2713 ${detail} on @${result.owner} (${vis})`;\n}\n", "import type { Command } from \"commander\";\nimport {\n  authLogout,\n  authDisconnectLocal,\n  authStatus,\n  authConnect,\n  approveDevice,\n  listDevices,\n  renameDevice,\n  revokeDevice,\n  readActiveDeviceFile,\n} from \"@skillet/core\";\nimport { REGISTRY_DEFAULT, resolveRegistryUrl } from \"../cli-context.js\";\nimport { webBaseUrl } from \"../cli-command-tier.js\";\n\n/**\n * Safe machine-readable shape for `auth connect --json` \u2014 only non-secret\n * metadata. Bearer tokens (device_token, session_token) are deliberately\n * omitted; they would land in CI logs / shell history (deepsec MEDIUM\n * secret-in-log) and are already persisted to ~/.skillet.\n */\nexport function safeAuthConnectJson(result: { device_id: string }): string {\n  return JSON.stringify({ ok: true, device_id: result.device_id }, null, 2);\n}\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { ok, fail, dim, bold, cyan } from \"../cli-colors.js\";\nimport { writeJsonError } from \"../json-output.js\";\nimport { resolveWebUrl } from \"../open-browser-url.js\";\nimport { printRenderedError } from \"../render-error.js\";\n\nconst LOGOUT_DESCRIPTION = \"Sign out of this machine\";\nconst DISCONNECT_DESCRIPTION =\n  \"Sign out and erase this machine's local credentials\";\n\n/** Shared action for `skillet logout` and `skillet auth logout`. */\nasync function runLogoutAction(opts: { registry: string }, label: string): Promise<void> {\n  try {\n    const result = await authLogout({ registryUrl: opts.registry });\n    delete process.env[\"SKILLET_TOKEN\"];\n    if (!result.serverRevoked && result.serverWarning) {\n      console.warn(`\u26A0 ${result.serverWarning} \u2014 local session cleared anyway.`);\n    }\n    console.log(ok(\"Signed out. Session cleared.\"));\n  } catch (err) {\n    console.error(fail(`${label} failed: ${(err as Error).message}`));\n    exitWith(ExitCode.ERROR);\n  }\n}\n\n/** Shared action for `skillet disconnect` and `skillet auth disconnect`. */\nasync function runDisconnectAction(opts: { registry: string }, label: string): Promise<void> {\n  try {\n    const result = await authDisconnectLocal({ registryUrl: opts.registry });\n    delete process.env[\"SKILLET_TOKEN\"];\n    if (!result.unregistered && result.warning) {\n      console.warn(`\u26A0 ${result.warning}`);\n    }\n    console.log(ok(\"Disconnected. Local credentials cleared.\"));\n  } catch (err) {\n    console.error(fail(`${label} failed: ${(err as Error).message}`));\n    exitWith(ExitCode.ERROR);\n  }\n}\n\n/**\n * Top-level sign-out. `skillet logout` ends the session on this machine;\n * `skillet logout --forget` also erases this machine's local credentials (the\n * heavier reset that used to be `disconnect`). Both `disconnect` aliases stay\n * registered but hidden \u2014 the desktop tray invokes `auth disconnect`, and\n * scripts may still call the top-level `disconnect`.\n */\nexport function registerSessionAliasCommands(program: Command): void {\n  program\n    .command(\"logout\")\n    .description(LOGOUT_DESCRIPTION)\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .option(\"--forget\", \"Also erase this machine's local credentials\")\n    .action((opts: { registry: string; forget?: boolean }) =>\n      opts.forget\n        ? runDisconnectAction(opts, \"logout --forget\")\n        : runLogoutAction(opts, \"logout\"),\n    );\n\n  program\n    .command(\"disconnect\", { hidden: true })\n    .description(DISCONNECT_DESCRIPTION)\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .action((opts: { registry: string }) => runDisconnectAction(opts, \"disconnect\"));\n}\n\nexport function registerAuthCommands(program: Command): void {\n  const auth = program.command(\"auth\").description(\"Sign in and manage registry session\");\n\n  // `auth login` (email magic-link CLI login) retired with the magic-link pipe.\n  // Pair this machine with `skillet connect <code>` (a code from web Settings).\n\n  auth\n    .command(\"logout\")\n    .description(LOGOUT_DESCRIPTION)\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .action((opts: { registry: string }) => runLogoutAction(opts, \"auth logout\"));\n\n  // Hidden from `auth --help`: humans use `logout --forget`. Still registered\n  // and callable \u2014 the desktop tray invokes `auth disconnect`.\n  auth\n    .command(\"disconnect\", { hidden: true })\n    .description(DISCONNECT_DESCRIPTION)\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .action((opts: { registry: string }) => runDisconnectAction(opts, \"auth disconnect\"));\n\n  // Hidden from `auth --help`: humans use `doctor`. Still registered and\n  // callable with an unchanged `--json` envelope \u2014 the desktop tray invokes\n  // `auth status --json`.\n  auth\n    .command(\"status\", { hidden: true })\n    .description(\"Show session, device token, and signing identity state\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .option(\"--token <token>\", \"Bearer token override\")\n    .option(\"--json\", \"Emit machine-readable status\")\n    .action(async (opts: { registry: string; token?: string; json?: boolean }) => {\n      try {\n        const status = await authStatus({\n          registryUrl: opts.registry,\n          ...(opts.token ? { token: opts.token } : {}),\n        });\n        if (opts.json) {\n          process.stdout.write(JSON.stringify({ ok: true, ...status }, null, 2) + \"\\n\");\n          return;\n        }\n        const who = status.whoami;\n        const remotePrimary = who?.author_key_id ?? null;\n        const localKey = status.identity?.keyId ?? null;\n        console.log(`Bearer: ${status.bearer.kind}${status.bearer.tokenPreview ? ` (${status.bearer.tokenPreview})` : \"\"}`);\n        if (who?.handle) console.log(`  registry handle: @${who.handle}`);\n        if (who?.user_id) console.log(`  user: ${who.user_id.slice(0, 8)}\u2026`);\n        if (who?.device_id) console.log(`  device: ${who.device_id.slice(0, 12)}\u2026`);\n        if (remotePrimary) {\n          console.log(`  registry primary key: ${remotePrimary.slice(0, 16)}\u2026`);\n        }\n        if (localKey) {\n          if (remotePrimary && localKey !== remotePrimary) {\n            console.log(`  local signing key: ${localKey.slice(0, 16)}\u2026 (not registry primary)`);\n          } else {\n            console.log(`  local signing key: ${localKey.slice(0, 16)}\u2026 (registry primary)`);\n          }\n        } else {\n          console.log(\"  local signing key: none\");\n        }\n        if (status.hints.length > 0) {\n          console.log(\"\");\n          for (const h of status.hints) console.log(`  \u2192 ${h}`);\n        }\n      } catch (err) {\n        printRenderedError(err as Error, (what) => fail(`Couldn't read auth status. ${what}`));\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  // `skillet whoami` \u2014 registry session + local signing identity for the native app gate.\n  program\n    .command(\"whoami\")\n    .description(\"Who this machine is signed in as\")\n    .option(\"--json\", \"Emit machine-readable identity JSON\")\n    .action(async (opts: { json?: boolean }) => {\n      try {\n        const status = await authStatus();\n        const identity = status.identity\n          ? {\n              handle: status.identity.handle,\n              keyId: status.identity.keyId,\n              registryUrl: status.identity.registryUrl,\n            }\n          : null;\n\n        if (opts.json) {\n          process.stdout.write(\n            JSON.stringify({\n              identity,\n              registry: status.whoami,\n              bearer: status.bearer.kind,\n            }) + \"\\n\",\n          );\n          return;\n        }\n\n        if (identity?.handle && identity.keyId) {\n          const remotePrimary = status.whoami?.author_key_id ?? null;\n          console.log(`@${identity.handle} on ${identity.registryUrl}`);\n          if (remotePrimary && identity.keyId !== remotePrimary) {\n            console.log(`  local key: ${identity.keyId.slice(0, 16)}\u2026 (not registry primary)`);\n            if (remotePrimary) {\n              console.log(`  registry primary: ${remotePrimary.slice(0, 16)}\u2026`);\n            }\n          } else {\n            console.log(`  key: ${identity.keyId.slice(0, 16)}\u2026 (registry primary)`);\n          }\n          if (status.whoami?.user_id) {\n            console.log(`  registry session: active`);\n          }\n          return;\n        }\n\n        if (status.whoami?.handle) {\n          console.log(`@${status.whoami.handle} (signed in)`);\n          if (status.whoami.user_id) {\n            console.log(`  user: ${status.whoami.user_id.slice(0, 8)}\u2026`);\n          }\n          const remotePrimary = status.whoami.author_key_id;\n          if (remotePrimary && identity?.keyId !== remotePrimary) {\n            console.log(`  signing key: primary is on another machine (session publish works here)`);\n          } else {\n            console.log(`  signing key: no local primary on this device (session publish works here)`);\n          }\n          return;\n        }\n\n        if (status.bearer.kind !== \"none\") {\n          console.log(`Signed in (${status.bearer.kind})`);\n          console.log(`  Run \\`skillet auth status\\` for details.`);\n          return;\n        }\n\n        console.log(\"Not signed in.\");\n        console.log(dim(\"  Sign in and get a pair code at \") + cyan(resolveWebUrl(\"/settings\")));\n        console.log(dim(\"  Then run \") + bold(\"skillet connect <code>\"));\n      } catch (err) {\n        if (opts.json) {\n          process.stdout.write(\n            JSON.stringify({ identity: null, error: (err as Error).message }) + \"\\n\",\n          );\n          exitWith(ExitCode.ERROR);\n        }\n        printRenderedError(err as Error, fail);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  // `skillet device \u2026`: manage author-signed device-key\n  // delegations. A device/browser generates its own key and presents the public\n  // half; the primary key (in this keystore) signs a delegation cert authorizing\n  // it to propose/approve on the author's behalf.\n  // Bare `skillet device` is the whole \"This machine\" view: every machine on\n  // the account, which one this is, and the rename hint \u2014 so a person never\n  // has to remember `device list` vs `device show` vs `device rename`. This is\n  // a human overview only (no flags): declaring options on the parent would\n  // shadow the subcommands' own `--json`, which the tray parses. Scripts use\n  // `device list --json`; the subcommands stay for the tray (`device rename`).\n  const device = program\n    .command(\"device\")\n    .description(\"Your machines: which one this is, plus how to rename it\")\n    .action(async () => {\n      try {\n        const [result, active] = await Promise.all([listDevices({}), readActiveDeviceFile()]);\n        const currentId = active?.device_id ?? null;\n        const { sync_devices } = result;\n        if (sync_devices.length === 0) {\n          console.log(\"No machines connected yet.\");\n          console.log(\n            dim(\"  Pair one: \") + bold(\"skillet connect <code>\") + dim(\" (code from \") + cyan(`${webBaseUrl()}/settings`) + dim(\")\"),\n          );\n          return;\n        }\n        console.log(`Machines on your account (${sync_devices.length})`);\n        for (const d of sync_devices) {\n          const isCurrent = currentId !== null && d.device_id === currentId;\n          const marker = isCurrent ? cyan(\"\u25CF\") : dim(\"\u25CB\");\n          const name = d.label ? d.label : dim(\"(unnamed)\");\n          const here = isCurrent ? cyan(\"  \u2190 this machine\") : \"\";\n          const added = new Date(d.created_at * 1000).toISOString().slice(0, 10);\n          console.log(`  ${marker} ${name}${here}`);\n          console.log(dim(`      ${d.device_id.slice(0, 16)}\u2026  added ${added}`));\n        }\n        console.log(\"\");\n        console.log(dim(\"  Rename this machine: \") + bold(\"skillet device rename <label>\"));\n        console.log(dim(\"  Manage on the web:   \") + cyan(`${webBaseUrl()}/settings`));\n      } catch (err) {\n        printRenderedError(err as Error, (what) => fail(`Couldn't list your machines. ${what}`));\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  device\n    .command(\"list\")\n    .description(\"List the machines on your account\")\n    .option(\"--registry <url>\", \"Registry base URL\")\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .option(\"--json\", \"Emit machine-readable JSON\")\n    .action(async (opts: { registry?: string; token?: string; json?: boolean }) => {\n      try {\n        const result = await listDevices({\n          ...(opts.registry ? { registryUrl: opts.registry } : {}),\n          ...(opts.token ? { token: opts.token } : {}),\n        });\n        if (opts.json) {\n          process.stdout.write(JSON.stringify({ ok: true, sync_devices: result.sync_devices }) + \"\\n\");\n          return;\n        }\n        const { sync_devices } = result;\n        if (sync_devices.length === 0) {\n          console.log(\n            \"No connected devices. Pair a machine with `skillet connect <code>` or open Settings on skillet.md.\",\n          );\n          return;\n        }\n        for (const d of sync_devices) {\n          const added = new Date(d.created_at * 1000).toISOString().slice(0, 10);\n          const label = d.label ? ` \"${d.label}\"` : \"\";\n          console.log(`  ${d.device_id.slice(0, 16)}\u2026${label}  added ${added}`);\n        }\n      } catch (err) {\n        printRenderedError(err as Error, (what) => fail(`Couldn't list devices. ${what}`));\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  device\n    .command(\"rename <label>\")\n    .description(\"Rename this machine\")\n    .option(\"--registry <url>\", \"Registry base URL\")\n    .option(\"--token <token>\", \"Registry token (defaults to this machine's credentials)\")\n    .option(\"--json\", \"Emit machine-readable JSON\")\n    .action(async (label: string, opts: { registry?: string; token?: string; json?: boolean }) => {\n      try {\n        const result = await renameDevice(label, {\n          // Env-aware coalesce (explicit flag \u2192 identity \u2192 SKILLET_REGISTRY_URL\n          // \u2192 default) \u2014 the tray sidecar reaches local/dev registries via env.\n          registryUrl: await resolveRegistryUrl({ ...(opts.registry ? { registry: opts.registry } : {}) }),\n          ...(opts.token ? { token: opts.token } : {}),\n        });\n        if (opts.json) {\n          // Ad-hoc { ok: true, ...fields } shape \u2014 the desktop tray parses it.\n          process.stdout.write(\n            JSON.stringify({ ok: true, device_id: result.device_id, label: result.label }) + \"\\n\",\n          );\n          return;\n        }\n        console.log(ok(`Renamed this machine to \"${result.label}\"`));\n      } catch (err) {\n        const message = (err as Error).message;\n        if (opts.json) {\n          writeJsonError(message);\n          return;\n        }\n        printRenderedError(err as Error, (what) => fail(`Couldn't rename this machine. ${what}`));\n        exitWith(\n          /not paired|credential|session token|401|403|unauthorized/i.test(message)\n            ? ExitCode.AUTH\n            : ExitCode.ERROR,\n        );\n      }\n    });\n}\n\n/** Legacy device/session linking \u2014 SKILLET_LEGACY_CLI=1 only. */\nexport function registerLegacyAuthCommands(program: Command): void {\n  const auth = program.commands.find((c) => c.name() === \"auth\");\n  const device = program.commands.find((c) => c.name() === \"device\");\n  if (!auth || !device) {\n    throw new Error(\"registerAuthCommands must run before registerLegacyAuthCommands\");\n  }\n\n  auth\n    .command(\"connect\")\n    .description(\n      \"Attach machine via signed-in session (prefer `skillet connect <code>` from skillet.md)\",\n    )\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .option(\"--token <token>\", \"Session token (defaults to ~/.skillet/session.json)\")\n    .option(\"--label <label>\", \"Label for this agent in settings\")\n    .option(\"--json\", \"Emit machine-readable result\")\n    .action(async (opts: { registry: string; token?: string; label?: string; json?: boolean }) => {\n      try {\n        const result = await authConnect({\n          registryUrl: opts.registry,\n          ...(opts.token ? { token: opts.token } : {}),\n          ...(opts.label ? { label: opts.label } : {}),\n        });\n        if (opts.json) {\n          process.stdout.write(safeAuthConnectJson(result) + \"\\n\");\n          return;\n        }\n        console.log(ok(`Connected this machine to your account`));\n        console.log(`  device: ${result.device_id}`);\n        console.log(`  token saved to ~/.skillet/device.json`);\n        console.log(`  Pull kits with \\`skillet sync\\``);\n      } catch (err) {\n        printRenderedError(err as Error, (what) => fail(`Couldn't connect this machine. ${what}`));\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  device\n    .command(\"approve <device_pub_or_code>\")\n    .description(\"Approve a device key: mint + sign a delegation cert with your primary key\")\n    .option(\"--scopes <list>\", \"Comma-separated scopes (propose,approve,publish)\", \"propose,approve,publish\")\n    .option(\"--ttl-days <n>\", \"Delegation lifetime in days (default 90, max 365)\")\n    .option(\"--label <label>\", \"Human label for the device (e.g. \\\"Sarah's MacBook\\\")\")\n    .option(\"--registry <url>\", \"Registry base URL\")\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .option(\"--json\", \"Emit machine-readable JSON\")\n    .action(\n      async (\n        pairing: string,\n        opts: {\n          scopes: string;\n          ttlDays?: string;\n          label?: string;\n          registry?: string;\n          token?: string;\n          json?: boolean;\n        },\n      ) => {\n        try {\n          const scopes = opts.scopes\n            .split(\",\")\n            .map((s) => s.trim())\n            .filter(Boolean);\n          for (const s of scopes) {\n            if (s !== \"propose\" && s !== \"approve\" && s !== \"publish\") {\n              throw new Error(`invalid scope ${JSON.stringify(s)} \u2014 only propose,approve,publish are delegable`);\n            }\n          }\n          const ttlDays = opts.ttlDays != null ? Number(opts.ttlDays) : undefined;\n          if (ttlDays != null && (!Number.isFinite(ttlDays) || ttlDays <= 0)) {\n            throw new Error(\"--ttl-days must be a positive number\");\n          }\n          const res = await approveDevice({\n            pairing,\n            scopes: scopes as (\"propose\" | \"approve\" | \"publish\")[],\n            ...(ttlDays != null ? { ttlDays } : {}),\n            ...(opts.label ? { label: opts.label } : {}),\n            ...(opts.registry ? { registryUrl: opts.registry } : {}),\n            ...(opts.token ? { token: opts.token } : {}),\n          });\n          if (opts.json) {\n            process.stdout.write(JSON.stringify({ ok: true, ...res }) + \"\\n\");\n            return;\n          }\n          const when = new Date(res.expiresAt * 1000).toISOString().slice(0, 10);\n          console.log(\n            ok(`${res.alreadyRegistered ? \"Already approved\" : \"Approved\"} device ${res.deviceKeyId.slice(0, 16)}\u2026`),\n          );\n          console.log(`  scopes: ${res.scopes.join(\", \")}  \u00B7  expires: ${when}`);\n        } catch (err) {\n          printRenderedError(err as Error, (what) => fail(`Couldn't approve device. ${what}`));\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n\n  device\n    .command(\"revoke <device_key_id>\")\n    .description(\"Revoke a device key (mint + sign a revocation with your primary key)\")\n    .option(\"--registry <url>\", \"Registry base URL\")\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .option(\"--json\", \"Emit machine-readable JSON\")\n    .action(\n      async (\n        deviceKeyId: string,\n        opts: { registry?: string; token?: string; json?: boolean },\n      ) => {\n        try {\n          const res = await revokeDevice({\n            deviceKeyId,\n            ...(opts.registry ? { registryUrl: opts.registry } : {}),\n            ...(opts.token ? { token: opts.token } : {}),\n          });\n          if (opts.json) {\n            process.stdout.write(JSON.stringify({ ok: true, ...res }) + \"\\n\");\n            return;\n          }\n          const when = new Date(res.revokedAt * 1000).toISOString();\n          console.log(ok(`Revoked device ${res.deviceKeyId.slice(0, 16)}\u2026 at ${when}`));\n        } catch (err) {\n          printRenderedError(err as Error, (what) => fail(`Couldn't revoke device. ${what}`));\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n}\n", "import { spawn } from \"node:child_process\";\nimport { webBaseUrl } from \"./cli-command-tier.js\";\n\n/** Build a skillet.md URL from an optional site-relative path. */\nexport function resolveWebUrl(path?: string): string {\n  const base = webBaseUrl();\n  if (path === undefined || path.length === 0) return base;\n  // Accept a bare path (`settings`) as shorthand for the rooted form\n  // (`/settings`); normalize the leading slash rather than rejecting it. Still\n  // reject `//\u2026`, which the browser reads as a protocol-relative URL to another\n  // origin \u2014 a bare-path input can never be that once we've prepended the slash.\n  const rooted = path.startsWith(\"/\") ? path : `/${path}`;\n  if (rooted.startsWith(\"//\")) {\n    throw new Error(\"Path must be site-relative (e.g. /settings)\");\n  }\n  return `${base}${rooted}`;\n}\n\n/** Reject URLs that could break out of a Windows `cmd /C start` invocation. */\nexport function assertSafeBrowserUrl(url: string): void {\n  if (!url.startsWith(\"http://\") && !url.startsWith(\"https://\")) {\n    throw new Error(\"Browser URL must be http or https\");\n  }\n  if (/[\"&\\r\\n]/.test(url)) {\n    throw new Error(\"Browser URL contains unsafe characters\");\n  }\n}\n\n/** Open a URL in the system default browser. Returns false when no opener is available. */\nexport function openBrowserUrl(url: string): Promise<boolean> {\n  assertSafeBrowserUrl(url);\n\n  const platform = process.platform;\n  const [cmd, args] =\n    platform === \"darwin\"\n      ? ([\"open\", [url]] as const)\n      : platform === \"win32\"\n        ? ([\"cmd\", [\"/C\", \"start\", \"\", url]] as const)\n        : ([\"xdg-open\", [url]] as const);\n\n  return new Promise((resolve) => {\n    const child = spawn(cmd, [...args], { stdio: \"ignore\", detached: true });\n    child.on(\"error\", () => resolve(false));\n    child.on(\"spawn\", () => {\n      child.unref();\n      resolve(true);\n    });\n  });\n}\n", "import type { Command } from \"commander\";\nimport { authStatus } from \"@skillet/core\";\nimport { REGISTRY_DEFAULT } from \"../cli-context.js\";\n\n/** Stable per-person hue (0\u2013359), matching the web's avatar tint (FNV-1a). */\nfunction handleHue(handle: string): number {\n  let h = 2166136261;\n  for (let i = 0; i < handle.length; i++) h = ((h ^ handle.charCodeAt(i)) * 16777619) >>> 0;\n  return h % 360;\n}\n\n/**\n * `skillet avatar` \u2014 print the signed-in user's avatar as a `data:` URI.\n *\n * The desktop app renders it in-process: its CSP is `img-src 'self' asset:\n * data:`, so a remote R2 avatar URL is blocked, but a data URI is safe. Fetching\n * + encoding happens here (Node) rather than loosening the desktop CSP. Emits\n * `{\"data_uri\": \"data:image/\u2026;base64,\u2026\" | null}` \u2014 null when signed out, the\n * user has no custom avatar, or the fetch fails (client falls back to a monogram).\n */\nexport function registerAvatarCommand(program: Command): void {\n  // Hidden from help: internal plumbing the desktop tray calls to render the\n  // signed-in user's avatar. Still registered and callable (`skillet avatar`).\n  program\n    .command(\"avatar\", { hidden: true })\n    .description(\"Print the signed-in user's avatar image (internal)\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .option(\"--token <token>\", \"Bearer token override\")\n    .action(async (opts: { registry: string; token?: string }) => {\n      const status = await authStatus({\n        registryUrl: opts.registry,\n        ...(opts.token ? { token: opts.token } : {}),\n      });\n      const raw = status.whoami?.avatar_url ?? null;\n      // A custom avatar is an absolute (R2) URL; a default illustrated face is a\n      // web-relative path (`/avatars/default/\u2026`) \u2014 resolve it against the web app.\n      const webBase = (process.env.SKILLET_WEB_URL || \"https://skillet.md\").replace(/\\/+$/, \"\");\n      const url = raw ? (/^https?:\\/\\//.test(raw) ? raw : `${webBase}${raw.startsWith(\"/\") ? \"\" : \"/\"}${raw}`) : null;\n      let dataUri: string | null = null;\n      if (url) {\n        try {\n          const res = await fetch(url);\n          if (res.ok) {\n            const contentType = res.headers.get(\"content-type\") || \"image/webp\";\n            const b64 = Buffer.from(await res.arrayBuffer()).toString(\"base64\");\n            dataUri = `data:${contentType};base64,${b64}`;\n          }\n        } catch {\n          // offline / unreachable \u2014 leave null, the client shows a monogram\n        }\n      }\n      // Default illustrated faces are transparent black line-art on a per-person\n      // pastel tint (mirrors the web's avatarTintGradient). The hue is encoded in\n      // the URL (`?h=220`); fall back to a stable hash of the handle. Custom\n      // photos fill the circle, so no tint.\n      let tint: string | null = null;\n      if (raw && raw.includes(\"/avatars/default/\")) {\n        const m = /[?&]h=(\\d+)/.exec(raw);\n        const hue = m ? Number(m[1]) % 360 : handleHue(status.whoami?.handle ?? \"\");\n        tint = `radial-gradient(120% 120% at 30% 26%, hsl(${hue} 64% 94%), hsl(${hue} 52% 83%))`;\n      }\n      process.stdout.write(JSON.stringify({ data_uri: dataUri, tint }) + \"\\n\");\n    });\n}\n", "import type { Command } from \"commander\";\nimport { authConnectPair } from \"@skillet/core\";\nimport { REGISTRY_DEFAULT } from \"../cli-context.js\";\nimport { webBaseUrl } from \"../cli-command-tier.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { writeJsonError } from \"../json-output.js\";\nimport { ok, fail, dim, cyan } from \"../cli-colors.js\";\nimport { printRenderedError } from \"../render-error.js\";\nimport { runConnectedSync, detectedAgentsPhrase, pairInteractively } from \"../connected-sync.js\";\n\nexport function registerConnectCommand(program: Command): void {\n  program\n    .command(\"connect [code]\")\n    .description(\"Link this machine with a pair code from skillet.md Settings\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .option(\"--label <label>\", \"Label for this machine in settings\")\n    .option(\"--client <kind>\", \"Client surface: cli or desktop\", \"cli\")\n    .option(\"--json\", \"Emit machine-readable result\")\n    .action(async (codeArg: string | undefined, opts: { registry: string; label?: string; client: string; json?: boolean }) => {\n      const clientKind = opts.client === 'desktop' ? 'desktop' : 'cli';\n      const pairOpts = {\n        registryUrl: opts.registry,\n        ...(opts.label ? { label: opts.label } : {}),\n        clientKind,\n      } as const;\n      const interactive = !opts.json && process.stdout.isTTY === true;\n      const code = codeArg?.trim() ?? \"\";\n\n      const printSuccessAndSync = async (result: Awaited<ReturnType<typeof authConnectPair>>) => {\n        const who = result.handle ? `@${result.handle}` : \"your account\";\n        console.log(ok(`Connected this machine to ${who}`));\n        console.log(dim(`  device: ${result.device_id}`));\n        console.log(dim(`  Manage pairing at `) + cyan(`${webBaseUrl()}/settings`));\n        // Pairing ends in a synced machine, same as the desktop: no homework.\n        await runConnectedSync(false);\n      };\n\n      // Prompt-and-retry loop for humans: bad codes re-prompt, Esc leaves quietly.\n      const promptLoop = async () => {\n        const result = await pairInteractively(pairOpts);\n        if (!result) {\n          exitWith(ExitCode.ERROR);\n          return;\n        }\n        console.log(\"\");\n        await printSuccessAndSync(result);\n      };\n\n      // No code on an interactive terminal: ask for it here instead of making\n      // the user retype the command after fetching one.\n      if (!code && interactive) {\n        console.log(`  Connect this machine to your account to use your skills ${await detectedAgentsPhrase()}.`);\n        console.log(dim(\"  Get a pair code at \") + cyan(`${webBaseUrl()}/settings`));\n        await promptLoop();\n        return;\n      }\n      if (!code) {\n        if (opts.json) {\n          writeJsonError(\"missing pair code\");\n        } else {\n          console.error(fail(\"No pair code provided.\"));\n          console.error(dim(\"  Run `skillet connect <code>` with a code from \") + cyan(`${webBaseUrl()}/settings`));\n        }\n        exitWith(ExitCode.ERROR);\n        return;\n      }\n      try {\n        const result = await authConnectPair({ code, ...pairOpts });\n        if (opts.json) {\n          process.stdout.write(JSON.stringify({ ok: true, ...result }, null, 2) + \"\\n\");\n          return;\n        }\n        await printSuccessAndSync(result);\n      } catch (err) {\n        const message = (err as Error).message;\n        if (opts.json) {\n          // Keep the raw message on the JSON surface: the desktop tray parses it.\n          writeJsonError(message);\n        }\n        const reason = message.replace(/^Could not connect with pair code:\\s*/i, \"\");\n        printRenderedError(reason, (what) => fail(`Could not connect: ${what}`));\n        if (interactive) {\n          // The typed code failed but a human is right here \u2014 offer the\n          // prompt instead of making them rebuild the command line.\n          console.log(dim(\"  Get a fresh code at \") + cyan(`${webBaseUrl()}/settings`));\n          await promptLoop();\n          return;\n        }\n        console.error(dim(\"  Try again with a fresh code from \") + cyan(`${webBaseUrl()}/settings`));\n        exitWith(ExitCode.ERROR);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport { collectDoctorReport } from \"@skillet/core\";\nimport { ALL_ADAPTERS } from \"../cli-context.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { fail } from \"../cli-colors.js\";\n\nfunction formatDoctorHuman(report: Awaited<ReturnType<typeof collectDoctorReport>>): string {\n  const lines: string[] = [];\n  lines.push(`Skillet doctor (${report.schema})`);\n  lines.push(`Generated: ${report.generated_at}`);\n  lines.push(\"\");\n\n  lines.push(\"Auth / enrollment\");\n  lines.push(`  bearer: ${report.auth.bearer.kind}`);\n  if (report.auth.bearer.tokenPreview) {\n    lines.push(`  token: ${report.auth.bearer.tokenPreview}`);\n  }\n  lines.push(`  linked machine: ${report.auth.linked_machine ? \"yes\" : \"no\"}`);\n  if (report.auth.whoami?.handle) {\n    lines.push(`  whoami: @${report.auth.whoami.handle}`);\n  } else if (report.auth.whoami === null && report.auth.bearer.kind !== \"none\") {\n    lines.push(\"  whoami: unreachable (offline or registry error)\");\n  }\n  if (report.device.device_id) {\n    lines.push(`  device id: ${report.device.device_id}`);\n  }\n  if (report.device.label) {\n    lines.push(`  device label: ${report.device.label}`);\n  }\n  // Signing identity \u2014 the state `auth status` used to show. Surfacing it here\n  // is what makes hiding that command lossless: is there a local signing key,\n  // and does it match the account's registry primary?\n  const who = report.auth.whoami;\n  if (who?.user_id) {\n    lines.push(`  user: ${who.user_id.slice(0, 8)}\u2026`);\n  }\n  const remotePrimary = who?.author_key_id ?? null;\n  const localKey = report.auth.identity?.keyId ?? null;\n  if (remotePrimary) {\n    lines.push(`  registry primary key: ${remotePrimary.slice(0, 16)}\u2026`);\n  }\n  lines.push(\n    localKey\n      ? `  local signing key: ${localKey.slice(0, 16)}\u2026 ${\n          remotePrimary && localKey !== remotePrimary ? \"(not registry primary)\" : \"(registry primary)\"\n        }`\n      : \"  local signing key: none\",\n  );\n  lines.push(\"\");\n\n  lines.push(\"Local state\");\n  lines.push(`  skills: ${report.state.skill_count}`);\n  if (report.state.slugs_sample.length > 0) {\n    lines.push(`  sample: ${report.state.slugs_sample.join(\", \")}`);\n  }\n  lines.push(`  edited reported: ${report.state.edited_reported ? \"yes\" : \"no\"}`);\n  lines.push(`  pending updates: ${report.pending.count}`);\n  if (report.pending.slugs.length > 0) {\n    lines.push(`  pending slugs: ${report.pending.slugs.join(\", \")}`);\n  }\n  lines.push(`  pinned authors: ${report.pins.handles.length}`);\n  if (report.pins.handles.length > 0) {\n    lines.push(`  pin handles: ${report.pins.handles.join(\", \")}`);\n  }\n  lines.push(\"\");\n\n  lines.push(\"Environment\");\n  lines.push(`  session precedence: ${report.env.session_token_precedence}`);\n  lines.push(`  SKILLET_TOKEN set: ${report.env.skillet_token_set ? \"yes\" : \"no\"}`);\n  lines.push(`  SKILLET_TOKEN_FORCE: ${report.env.skillet_token_force ? \"yes\" : \"no\"}`);\n  lines.push(`  SKILLET_DAEMON: ${report.env.skillet_daemon ? \"yes\" : \"no\"}`);\n  if (report.env.skillet_registry_url) {\n    lines.push(`  SKILLET_REGISTRY_URL: ${report.env.skillet_registry_url}`);\n  }\n  lines.push(`  SKILLET_DIR override: ${report.env.skillet_dir_override ? \"yes\" : \"no\"}`);\n  lines.push(\"\");\n\n  lines.push(\"Paths\");\n  lines.push(`  skillet dir: ${report.paths.skillet_dir}`);\n  lines.push(`  state: ${report.paths.state_file}`);\n  lines.push(`  session: ${report.paths.session_file}`);\n  lines.push(`  device: ${report.paths.device_file}`);\n  lines.push(`  approval lock: ${report.paths.approval_lock}`);\n  lines.push(`  pin dir: ${report.paths.pin_dir}`);\n  lines.push(\"\");\n\n  if (report.auth.hints.length > 0) {\n    lines.push(\"Hints\");\n    for (const hint of report.auth.hints) {\n      lines.push(`  \u2022 ${hint}`);\n    }\n  }\n\n  return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport function registerDoctorCommand(program: Command): void {\n  program\n    .command(\"doctor\")\n    .description(\"Auth, sync state, pending updates, and paths\")\n    .option(\"--json\", \"Emit machine-readable doctor report\")\n    .action(async (opts: { json?: boolean }) => {\n      try {\n        const report = await collectDoctorReport({ adapters: ALL_ADAPTERS });\n        if (opts.json === true) {\n          process.stdout.write(JSON.stringify(report, null, 2) + \"\\n\");\n          return;\n        }\n        process.stdout.write(formatDoctorHuman(report));\n      } catch (err) {\n        console.error(fail(`Doctor failed: ${(err as Error).message}`));\n        exitWith(ExitCode.ERROR);\n      }\n    });\n}\n", "/**\n * `skillet edits` \u2014 the ungated surface for customized skills (R5, R6, R8, R9,\n * R10). When you (or your agent) edit a synced skill, it becomes YOUR version:\n * the edit stays live, the author's updates are held, and you reconcile on\n * demand. ALWAYS registered, like `restore` \u2014 a customized skill must never\n * need SKILLET_LEGACY_CLI to be listed, diffed, or reconciled.\n *\n *   list           \u2014 your customized skills, flagging which have a held update\n *   diff <skill>   \u2014 your live version vs the current upstream\n *   take <skill>   \u2014 replace your edit with the author's version (backs yours up)\n *   restore <skill>\u2014 replace your edit with the current signed original\n *   keep <skill>   \u2014 acknowledge a held update so it stops nudging\n *   propose <skill>\u2014 send your edit upstream to the author\n *\n * Registry refusals on propose are honest outcomes, not dead-ends: 403 and 409\n * print friendly copy pointing at `skillet edits keep`, and NEITHER un-customizes\n * the skill \u2014 the edit stays live and private.\n */\nimport type { Command } from \"commander\";\nimport {\n  listCustomized,\n  takeUpstream,\n  restoreOriginal,\n  keepMine,\n  proposeCustomized,\n  lineageRef,\n  readBundleFromSkillStore,\n  readLiveCustomizedTree,\n  ReconcileError,\n  ProposeError,\n  type CustomizedSkill,\n  type ProposeCustomizedResult,\n} from \"@skillet/core\";\nimport { toWireRef } from \"@skillet/protocol/skill-id\";\nimport { ExitCode, exitWith, type ExitCodeValue } from \"../exit-codes.js\";\nimport { resolveSyncAdapters } from \"../adapter-tiers.js\";\nimport { stripControlChars, formatScanFinding } from \"../sanitize-output.js\";\n\n// \u2500\u2500 ref resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Canonicalize a ref to its wireRef (`@owner/slug`) for comparison, tolerating\n * all three input forms (`@a/b`, `a/b`, `a:b`) via the shared skill-id module \u2014\n * so a user typing any of them resolves the same local entry (R2 crossing\n * consistency). Unparseable input (a local-only lineage's bare slug, or a\n * malformed arg) falls back to the raw string, preserving the old exact-match\n * behaviour and letting a bad ref simply fail to match rather than throw.\n */\nfunction canonicalRef(ref: string): string {\n  try {\n    return toWireRef(ref);\n  } catch {\n    return ref;\n  }\n}\n\n/**\n * Pure ref \u2192 customized-skill match. Customized skills key on their original\n * `@author/slug` ref, so a match on the state key OR on `lineageRef(lineage)`\n * both resolve. Both sides are run through {@link canonicalRef} so the local\n * store's canonical key matches whichever of `@a/b` / `a/b` / `a:b` the user\n * typed. Exported for unit testing without a live edits store.\n */\nexport function findCustomizedByRef(\n  all: CustomizedSkill[],\n  ref: string,\n): CustomizedSkill | null {\n  const target = canonicalRef(ref);\n  return (\n    all.find(\n      (c) =>\n        canonicalRef(c.slug) === target ||\n        canonicalRef(lineageRef(c.lineage)) === target,\n    ) ?? null\n  );\n}\n\n/**\n * Resolve a `<skill>` arg to its customized-skill entry against the live edits\n * store, tolerant of the input ref form.\n */\nasync function resolveCustomized(ref: string): Promise<CustomizedSkill | null> {\n  return findCustomizedByRef(await listCustomized(), ref);\n}\n\n// \u2500\u2500 diff rendering \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type FileStatus = \"added\" | \"removed\" | \"changed\" | \"unchanged\";\n\nexport interface FileDiff {\n  path: string;\n  status: FileStatus;\n}\n\n/** A structured hunk line for the --json diff (consumed by the desktop viewer). */\nexport type DiffHunkLine = { kind: \"add\" | \"del\" | \"ctx\"; text: string };\n\nexport interface FileDiffJson extends FileDiff {\n  /** True when the file is binary/non-text \u2014 content can't be shown as lines. */\n  binary?: boolean;\n  /** Line-level hunk for a changed text file (yours vs upstream). */\n  hunks?: DiffHunkLine[];\n}\n\n/**\n * Structured line diff (same trim logic as lineDiff, emitted as {kind,text}\n * objects) so the desktop viewer can render real changed lines, not just which\n * file changed. old = upstream (theirs), new = live (yours): a removed line is\n * theirs, an added line is yours.\n */\nexport function diffHunks(oldStr: string, newStr: string): DiffHunkLine[] {\n  const a = oldStr.split(\"\\n\");\n  const b = newStr.split(\"\\n\");\n  let start = 0;\n  while (start < a.length && start < b.length && a[start] === b[start]) start++;\n  let endA = a.length;\n  let endB = b.length;\n  while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {\n    endA--;\n    endB--;\n  }\n  const out: DiffHunkLine[] = [];\n  for (let i = Math.max(0, start - 2); i < start; i++) out.push({ kind: \"ctx\", text: a[i]! });\n  for (let i = start; i < endA; i++) out.push({ kind: \"del\", text: a[i]! });\n  for (let i = start; i < endB; i++) out.push({ kind: \"add\", text: b[i]! });\n  for (let i = endB; i < Math.min(b.length, endB + 2); i++) out.push({ kind: \"ctx\", text: b[i]! });\n  return out;\n}\n\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) return false;\n  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n  return true;\n}\n\n/** Per-file status of the live edit vs the upstream bundle. */\nexport function diffTrees(\n  live: Map<string, Uint8Array>,\n  upstream: Map<string, Uint8Array>,\n): FileDiff[] {\n  const paths = new Set([...live.keys(), ...upstream.keys()]);\n  const out: FileDiff[] = [];\n  for (const path of [...paths].sort()) {\n    const l = live.get(path);\n    const u = upstream.get(path);\n    let status: FileStatus;\n    if (l && !u) status = \"added\";\n    else if (!l && u) status = \"removed\";\n    else if (l && u && bytesEqual(l, u)) status = \"unchanged\";\n    else status = \"changed\";\n    out.push({ path, status });\n  }\n  return out;\n}\n\nexport function isText(buf: Uint8Array): boolean {\n  return !buf.includes(0);\n}\n\n/**\n * A compact line diff: common prefix/suffix trimmed, the divergent middle shown\n * as removed-then-added with two lines of surrounding context. Not a minimal\n * Myers diff \u2014 clear and dependency-free, which is all a reconcile view needs.\n */\nexport function lineDiff(oldStr: string, newStr: string): string[] {\n  // Same trim logic as diffHunks, rendered as prefixed strings for the terminal.\n  return diffHunks(oldStr, newStr).map((h) =>\n    h.kind === \"del\" ? `  -${h.text}` : h.kind === \"add\" ? `  +${h.text}` : `   ${h.text}`,\n  );\n}\n\n// \u2500\u2500 list \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface CustomizedRow {\n  /** State key (the lineage ref the skill is customized from). */\n  slug: string;\n  /** `@author/slug` lineage ref. */\n  ref: string;\n  /** Always true \u2014 every row in this list is a customized skill (R9 honesty). */\n  customized: true;\n  /** A held author update is waiting AND has not been acknowledged. */\n  hasUpdate: boolean;\n  /** The baseline version the edit was made against. */\n  version: number;\n  /** The held update itself, when one exists. */\n  held?: { version: number; hash: string };\n}\n\nfunction toRow(c: CustomizedSkill): CustomizedRow {\n  return {\n    slug: c.slug,\n    ref: lineageRef(c.lineage),\n    customized: true,\n    hasUpdate: c.hasUpdate,\n    version: c.lineage.version,\n    ...(c.held ? { held: c.held } : {}),\n  };\n}\n\n// \u2500\u2500 outcome mapping (propose) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** What a propose outcome writes and how it exits \u2014 pure, so it's unit-testable. */\nexport interface ProposeOutcomeOutput {\n  stdout: string[];\n  stderr: string[];\n  exitCode: ExitCodeValue;\n}\n\n/**\n * Outcome \u2192 output mapping for `edits propose`. Each of the three outcomes is\n * EXCLUSIVE \u2014 exactly one message set, one exit code \u2014 via an exhaustive switch\n * on `status` so `not_authorized` can never fall through into `base_stale` (the\n * old inline branches let it, and only process.exit saved them). With `json`,\n * all three are outcome-as-data: one JSON object on stdout, exit 0, so machine\n * callers (the desktop) parse status instead of regexing stderr prose.\n */\nexport function renderProposeOutcome(\n  result: ProposeCustomizedResult,\n  ref: string,\n  json: boolean,\n): ProposeOutcomeOutput {\n  switch (result.status) {\n    case \"proposed\":\n      if (json) {\n        return {\n          stdout: [\n            JSON.stringify({ status: \"proposed\", proposal_id: result.proposalId }),\n          ],\n          stderr: [],\n          exitCode: ExitCode.OK,\n        };\n      }\n      return {\n        stdout: [\n          `\u2713 Proposal submitted for ${stripControlChars(result.ref)}`,\n          `  proposal: ${result.proposalId}`,\n          `  hash:     ${result.hash}`,\n          `  url:      ${result.proposalUrl}`,\n        ],\n        stderr: [],\n        exitCode: ExitCode.OK,\n      };\n    // 403/409 are honest refusals, not errors \u2014 and NEVER un-customize the\n    // skill: your edit stays live and the keep hint still has something to act on.\n    case \"not_authorized\":\n      if (json) {\n        return { stdout: [JSON.stringify({ status: \"not_authorized\" })], stderr: [], exitCode: ExitCode.OK };\n      }\n      return {\n        stdout: [],\n        stderr: [\n          `\u2717 You're not on this skill's team \u2014 keep your version with \\`skillet edits keep ${ref}\\``,\n        ],\n        exitCode: ExitCode.AUTH,\n      };\n    case \"base_stale\":\n      if (json) {\n        return { stdout: [JSON.stringify({ status: \"base_stale\" })], stderr: [], exitCode: ExitCode.OK };\n      }\n      return {\n        stdout: [],\n        stderr: [\n          `\u2717 This skill has moved on upstream since your edit \u2014 keep yours with \\`skillet edits keep ${ref}\\``,\n        ],\n        exitCode: ExitCode.CONFLICT,\n      };\n  }\n}\n\n// \u2500\u2500 command registration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function runEditsList(opts: { json?: boolean }): Promise<void> {\n  const skills = await listCustomized();\n  if (opts.json === true) {\n    process.stdout.write(\n      JSON.stringify({ ok: true, customized: skills.map(toRow) }, null, 2) + \"\\n\",\n    );\n    return;\n  }\n  if (skills.length === 0) {\n    console.log(\"No customized skills. Every synced skill matches its author's version.\");\n    return;\n  }\n  console.log(\n    \"Your customized skills (`skillet edits diff|take|restore|keep|propose <skill>`):\\n\",\n  );\n  for (const c of skills) {\n    const ref = stripControlChars(lineageRef(c.lineage));\n    const state = c.hasUpdate ? \"update available\" : \"up to date\";\n    console.log(`  ${ref}  \u00B7 customized \u00B7 ${state}`);\n  }\n}\n\nexport function registerEditsCommand(program: Command): void {\n  const edits = program\n    .command(\"edits\")\n    .description(\"Skills you customized: your live edits, with author updates held\");\n\n  // Bare `skillet edits` lists \u2014 same contract as `skillet pending`: the noun\n  // alone shows you the things, subcommands act on them.\n  edits.action(async () => {\n    await runEditsList({});\n  });\n\n  edits\n    .command(\"list\")\n    .description(\"List your customized skills and which have a held update\")\n    .option(\"--json\", \"Emit machine-readable output\")\n    .action(async (opts: { json?: boolean }) => {\n      await runEditsList(opts);\n    });\n\n  edits\n    .command(\"diff <skill>\")\n    .description(\"Show your version against the author's current one\")\n    .option(\"--json\", \"Emit machine-readable output\")\n    .action(async (skill: string, opts: { json?: boolean }) => {\n      const asJson = opts.json === true;\n      const customized = await resolveCustomized(skill);\n      if (!customized) {\n        const msg = `No customized skill \"${skill}\". Run \\`skillet edits list\\`.`;\n        if (asJson) {\n          process.stdout.write(JSON.stringify({ ok: false, error: msg }, null, 2) + \"\\n\");\n        } else {\n          console.error(`\u2717 ${msg}`);\n        }\n        exitWith(ExitCode.ERROR);\n        return;\n      }\n\n      const owner = customized.entry.owner ?? null;\n      const { adapters } = await resolveSyncAdapters(process.cwd());\n      const live =\n        (await readLiveCustomizedTree(customized.slug, owner, adapters)) ??\n        new Map<string, Uint8Array>();\n      let upstream: Map<string, Uint8Array>;\n      try {\n        upstream = await readBundleFromSkillStore(customized.slug);\n      } catch {\n        upstream = new Map<string, Uint8Array>();\n      }\n      const files = diffTrees(live, upstream);\n\n      if (asJson) {\n        // Enrich each changed file with line-level hunks (or a binary flag) so\n        // the desktop viewer shows the actual changed lines, not just filenames.\n        const filesJson: FileDiffJson[] = files.map((f) => {\n          if (f.status !== \"changed\") return f;\n          const l = live.get(f.path);\n          const u = upstream.get(f.path);\n          if (!l || !u) return f;\n          if (!isText(l) || !isText(u)) return { ...f, binary: true };\n          const dec = new TextDecoder();\n          return { ...f, hunks: diffHunks(dec.decode(u), dec.decode(l)) };\n        });\n        process.stdout.write(\n          JSON.stringify(\n            {\n              ok: true,\n              skill: lineageRef(customized.lineage),\n              customized: true,\n              hasUpdate: customized.hasUpdate,\n              ...(customized.held ? { held: customized.held } : {}),\n              files: filesJson,\n            },\n            null,\n            2,\n          ) + \"\\n\",\n        );\n        return;\n      }\n\n      const ref = stripControlChars(lineageRef(customized.lineage));\n      console.log(`Diff: your \"${ref}\" vs the author's current version (yours is -, theirs is +):\\n`);\n      const changed = files.filter((f) => f.status !== \"unchanged\");\n      if (changed.length === 0) {\n        console.log(\"  (identical \u2014 your version matches the upstream bytes)\");\n        return;\n      }\n      for (const f of changed) {\n        console.log(`  ${f.status.padEnd(9)} ${stripControlChars(f.path)}`);\n        const l = live.get(f.path);\n        const u = upstream.get(f.path);\n        if (f.status === \"changed\" && l && u && isText(l) && isText(u)) {\n          const upstreamText = Buffer.from(u).toString(\"utf8\");\n          const liveText = Buffer.from(l).toString(\"utf8\");\n          for (const line of lineDiff(upstreamText, liveText)) {\n            console.log(`  ${line}`);\n          }\n        }\n      }\n    });\n\n  edits\n    .command(\"take <skill>\")\n    .description(\"Replace your edit with the author's version (backs yours up first)\")\n    .action(async (skill: string) => {\n      try {\n        const customized = await resolveCustomized(skill);\n        if (!customized) {\n          console.error(`\u2717 No customized skill \"${skill}\". Run \\`skillet edits list\\`.`);\n          exitWith(ExitCode.ERROR);\n          return;\n        }\n        const { adapters } = await resolveSyncAdapters(process.cwd());\n        const result = await takeUpstream(customized.slug, adapters);\n        console.log(`\u2713 Took the author's version of \"${stripControlChars(lineageRef(customized.lineage))}\"`);\n        if (result.materialized.length > 0) {\n          console.log(`  applied ${result.materialized.length} file(s) to your agents`);\n        }\n        if (result.backupId) {\n          console.log(`  your version was backed up (${result.backupId}) \u2014 recoverable`);\n        }\n      } catch (err) {\n        console.error(`\u2717 ${(err as Error).message}`);\n        exitWith(err instanceof ReconcileError && err.code === \"integrity_failed\" ? ExitCode.CONFLICT : ExitCode.ERROR);\n      }\n    });\n\n  edits\n    .command(\"restore <skill>\")\n    .description(\"Replace your edit with the author's original (backs yours up first)\")\n    .action(async (skill: string) => {\n      try {\n        const customized = await resolveCustomized(skill);\n        if (!customized) {\n          console.error(`\u2717 No customized skill \"${skill}\". Run \\`skillet edits list\\`.`);\n          exitWith(ExitCode.ERROR);\n          return;\n        }\n        const { adapters } = await resolveSyncAdapters(process.cwd());\n        const result = await restoreOriginal(customized.slug, adapters);\n        console.log(`\u2713 Restored the original version of \"${stripControlChars(lineageRef(customized.lineage))}\"`);\n        if (result.materialized.length > 0) {\n          console.log(`  applied ${result.materialized.length} file(s) to your agents`);\n        }\n        if (result.backupId) {\n          console.log(`  your version was backed up (${result.backupId}) \u2014 recoverable`);\n        }\n      } catch (err) {\n        console.error(`\u2717 ${(err as Error).message}`);\n        exitWith(err instanceof ReconcileError && err.code === \"integrity_failed\" ? ExitCode.CONFLICT : ExitCode.ERROR);\n      }\n    });\n\n  edits\n    .command(\"keep <skill>\")\n    .description(\"Acknowledge a held update so it stops nudging until the next one\")\n    .action(async (skill: string) => {\n      try {\n        const customized = await resolveCustomized(skill);\n        if (!customized) {\n          console.error(`\u2717 No customized skill \"${skill}\". Run \\`skillet edits list\\`.`);\n          exitWith(ExitCode.ERROR);\n          return;\n        }\n        await keepMine(customized.slug);\n        console.log(\n          `\u2713 Keeping your version of \"${stripControlChars(lineageRef(customized.lineage))}\" \u2014 it won't nag again until the author ships a newer update.`,\n        );\n      } catch (err) {\n        console.error(`\u2717 ${(err as Error).message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  edits\n    .command(\"propose <skill>\")\n    .description(\"Propose your edit upstream to the skill's author\")\n    .option(\"--registry <url>\", \"Registry base URL (overrides identity default)\")\n    .option(\"--token <token>\", \"Bearer token (overrides SKILLET_TOKEN env var)\")\n    .option(\"--json\", \"Emit machine-readable output (proposed/not_authorized/base_stale exit 0)\")\n    .action(async (skill: string, opts: { registry?: string; token?: string; json?: boolean }) => {\n      const asJson = opts.json === true;\n      const customized = await resolveCustomized(skill);\n      if (!customized) {\n        const msg = `No customized skill \"${skill}\". Run \\`skillet edits list\\`.`;\n        if (asJson) {\n          process.stdout.write(JSON.stringify({ status: \"error\", message: msg }) + \"\\n\");\n        }\n        console.error(`\u2717 ${msg}`);\n        exitWith(ExitCode.ERROR);\n        return;\n      }\n      const ref = lineageRef(customized.lineage);\n      try {\n        const { adapters } = await resolveSyncAdapters(process.cwd());\n        const result = await proposeCustomized(customized.slug, adapters, {\n          ...(opts.registry ? { registryUrl: opts.registry } : {}),\n          ...(opts.token ? { token: opts.token } : {}),\n        });\n        const out = renderProposeOutcome(result, ref, asJson);\n        for (const line of out.stdout) console.log(line);\n        for (const line of out.stderr) console.error(line);\n        if (out.exitCode !== ExitCode.OK) exitWith(out.exitCode);\n        return;\n      } catch (err) {\n        // Real failures (network, not customized, unknown skill) stay\n        // nonzero-exit with stderr prose; --json additionally puts the outcome\n        // on stdout as data.\n        if (asJson) {\n          process.stdout.write(\n            JSON.stringify({ status: \"error\", message: (err as Error).message }) + \"\\n\",\n          );\n        }\n        if (err instanceof ProposeError) {\n          console.error(`\u2717 ${err.message}`);\n          if (err.code === \"scan_blocked\") {\n            const body = err.detail as\n              | { findings?: Array<{ file: string; lineStart: number; category: string }> }\n              | undefined;\n            for (const f of body?.findings ?? []) {\n              console.error(formatScanFinding(f));\n            }\n            console.error(\"  Remove the credential (use an env var or placeholder) and re-propose.\");\n          }\n          exitWith(ExitCode.ERROR);\n        }\n        console.error(`\u2717 Propose failed: ${(err as Error).message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport { writeFileSync, unlinkSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport {\n  readState,\n  readBundleFromSkillStore,\n  bundleToZip,\n  bundlesToZip,\n  bundleSlugDir,\n  frontmatterCompatWarnings,\n} from \"@skillet/core\";\n\ntype State = Awaited<ReturnType<typeof readState>>;\ntype SkillEntry = State[\"skills\"][string];\n\n/** Accept `@owner/slug`, `owner/slug`, or a bare `slug`; the local store is keyed by slug. */\nfunction resolveSlug(ref: string): string {\n  let s = ref.trim();\n  if (s.startsWith(\"@\")) s = s.slice(1);\n  if (s.includes(\"/\")) s = s.split(\"/\").pop() ?? s;\n  return s;\n}\n\nconst stripAt = (s: string): string => (s.startsWith(\"@\") ? s.slice(1) : s);\n\n/** Bare kit name (last path segment, no `@`) \u2014 used for filenames. */\nfunction kitNameOf(sourceKit: string | null | undefined): string | null {\n  if (!sourceKit) return null;\n  const bare = stripAt(sourceKit);\n  return bare.includes(\"/\") ? (bare.split(\"/\").pop() ?? bare) : bare;\n}\n\n/**\n * Match a skill's `sourceKit` (`@owner/kitname`) against the user's `--kit`\n * input. An owner-qualified input (`@owner/kit` or `owner/kit`) matches exactly;\n * a bare name matches the kit name only. `sourceKit` is display-only and can\n * collide across owners (see SkillEntry), so a bare name may match two kits from\n * different owners \u2014 qualify with the owner to disambiguate.\n */\nfunction kitMatches(sourceKit: string | null | undefined, input: string): boolean {\n  if (!sourceKit) return false;\n  const sk = stripAt(sourceKit);\n  const want = stripAt(input.trim());\n  if (want.includes(\"/\")) return sk === want;\n  const bare = sk.includes(\"/\") ? (sk.split(\"/\").pop() ?? sk) : sk;\n  return bare === want;\n}\n\nfunction warnFrontmatter(entry: SkillEntry, extras: string[]): void {\n  if (extras.length === 0) return;\n  process.stderr.write(\n    `warning: ${entry.slug} has SKILL.md frontmatter beyond name/description (${extras.join(\n      \", \",\n    )}). Codex and ChatGPT Skills ignore extra fields \u2014 trim them for a clean import.\\n`,\n  );\n}\n\n/**\n * A safe `.zip` base name. Slugs/kit names are `[a-z0-9-]` at the registry, but\n * the export sink trusts local state \u2014 sanitize here too so a poisoned\n * `state.json` (or a hostile registry response) can't turn `<base>.zip` into a\n * path traversal when joined onto cwd.\n */\nfunction safeFileBase(name: string): string {\n  return name.replace(/[^a-z0-9-]/gi, \"\") || \"skill\";\n}\n\nfunction emit(zip: Uint8Array, fileName: string, toStdout: boolean): void {\n  const buf = Buffer.from(zip);\n  if (toStdout) {\n    try {\n      process.stdout.write(buf);\n    } catch (err) {\n      // EPIPE when the consumer (e.g. `head`) closed the pipe early.\n      process.stderr.write(`Failed to write to stdout: ${(err as Error).message}\\n`);\n      process.exitCode = 1;\n    }\n    return;\n  }\n  const dest = resolve(process.cwd(), fileName);\n  try {\n    writeFileSync(dest, buf);\n  } catch (err) {\n    // Don't leave a truncated zip behind on ENOSPC/EACCES.\n    try {\n      unlinkSync(dest);\n    } catch {\n      /* best effort */\n    }\n    process.stderr.write(`Failed to write ${dest}: ${(err as Error).message}\\n`);\n    process.exitCode = 1;\n    return;\n  }\n  process.stderr.write(`Wrote ${dest} (${zip.byteLength} bytes)\\n`);\n}\n\nexport function registerExportCommand(program: Command): void {\n  program\n    .command(\"export [ref]\")\n    .description(\n      \"Export a skill or kit as a .zip for anywhere Skillet cannot sync\",\n    )\n    .option(\"--kit <name>\", \"Export every skill in a kit as one archive\")\n    .option(\"--stdout\", \"Write the zip to stdout instead of a file\")\n    .action(\n      async (\n        ref: string | undefined,\n        opts: { kit?: string; stdout?: boolean },\n      ) => {\n        const state = await readState();\n        const toStdout = opts.stdout === true;\n\n        if (opts.kit) {\n          const inKit = Object.values(state.skills).filter((e) =>\n            kitMatches(e.sourceKit, opts.kit!),\n          );\n          if (inKit.length === 0) {\n            process.stderr.write(\n              `No kit \"${opts.kit}\" found in your installed skills. Run \\`skillet list\\` to see your kits.\\n`,\n            );\n            process.exitCode = 1;\n            return;\n          }\n          // Filename from the bare kit name of the first match (sanitized),\n          // since the user's input may be owner-qualified (`@owner/kit`).\n          const fileBase = safeFileBase(kitNameOf(inKit[0]?.sourceKit) ?? resolveSlug(opts.kit));\n          const entries: Array<{ prefix: string; bundle: Awaited<ReturnType<typeof readBundleFromSkillStore>> }> = [];\n          for (const entry of inKit) {\n            if (entry.scan?.status === \"quarantined\") {\n              process.stderr.write(\n                `Skipping ${entry.slug}: quarantined by harm scan \u2014 not exported.\\n`,\n              );\n              continue;\n            }\n            let bundle: Awaited<ReturnType<typeof readBundleFromSkillStore>>;\n            try {\n              bundle = await readBundleFromSkillStore(entry.slug);\n            } catch (err) {\n              // Store drift (bytes pruned out-of-band, corrupt SKILL.md) \u2014 skip\n              // the broken skill, flag failure, keep exporting the rest.\n              process.stderr.write(`Skipping ${entry.slug}: ${(err as Error).message}\\n`);\n              process.exitCode = 1;\n              continue;\n            }\n            warnFrontmatter(entry, frontmatterCompatWarnings(bundle));\n            entries.push({\n              prefix: bundleSlugDir(entry.slug, entry.owner ?? null),\n              bundle,\n            });\n          }\n          if (entries.length === 0) {\n            process.stderr.write(\n              `Nothing to export in kit \"${opts.kit}\" \u2014 every skill was quarantined or unreadable.\\n`,\n            );\n            process.exitCode = 1;\n            return;\n          }\n          emit(bundlesToZip(entries), `${fileBase}.zip`, toStdout);\n          return;\n        }\n\n        if (!ref) {\n          process.stderr.write(\n            \"Usage: skillet export <@owner/slug> [--stdout]  |  skillet export --kit <name>\\n\",\n          );\n          process.exitCode = 1;\n          return;\n        }\n\n        const slug = resolveSlug(ref);\n        const entry = state.skills[slug];\n        if (!entry) {\n          process.stderr.write(\n            `No skill \"${ref}\" in your kit. Run \\`skillet list\\` to see installed skills.\\n`,\n          );\n          process.exitCode = 1;\n          return;\n        }\n        if (entry.scan?.status === \"quarantined\") {\n          process.stderr.write(\n            `Refusing to export ${entry.slug}: quarantined by harm scan. Resolve it first or re-sync a clean version.\\n`,\n          );\n          process.exitCode = 1;\n          return;\n        }\n\n        let bundle: Awaited<ReturnType<typeof readBundleFromSkillStore>>;\n        try {\n          bundle = await readBundleFromSkillStore(entry.slug);\n        } catch (err) {\n          // Store drift (bytes pruned, corrupt SKILL.md) \u2014 fail cleanly rather\n          // than crashing with an unhandled rejection + stack trace.\n          process.stderr.write(`Cannot export ${entry.slug}: ${(err as Error).message}\\n`);\n          process.exitCode = 1;\n          return;\n        }\n        warnFrontmatter(entry, frontmatterCompatWarnings(bundle));\n        emit(bundleToZip(bundle), `${safeFileBase(entry.slug)}.zip`, toStdout);\n      },\n    );\n}\n", "import type { Command } from \"commander\";\nimport { readFileSync } from \"node:fs\";\nimport {\n  readState,\n  skillContentPath,\n  groupSkillsByKit,\n  resolveDeviceScopedManifest,\n} from \"@skillet/core\";\nimport { renderKitList } from \"../kit-list-format.js\";\nimport { toListJsonSkill } from \"../list-json-format.js\";\nimport { REGISTRY_DEFAULT } from \"../cli-context.js\";\nimport { webBaseUrl } from \"../cli-command-tier.js\";\nimport { dim, bold, cyan } from \"../cli-colors.js\";\n\nexport function registerListCommand(program: Command): void {\n  program\n    .command(\"list\")\n    .description(\"List skills grouped by kit\")\n    .option(\n      \"--json\",\n      \"Emit the kit as JSON, including each skill's SKILL.md body (the desktop app's read contract)\",\n    )\n    .action(async (opts: { json?: boolean }) => {\n      const state = await readState();\n      const skills = Object.values(state.skills);\n\n      const manifest = await resolveDeviceScopedManifest({\n        registryUrl: REGISTRY_DEFAULT,\n      });\n      const listOpts =\n        manifest.fetched && manifest.items !== undefined\n          ? { manifestItems: manifest.items }\n          : undefined;\n\n      const groups = groupSkillsByKit(state, listOpts);\n      const listedSkills = groups.flatMap((g) => g.skills);\n\n      if (opts.json === true) {\n        const out = listedSkills.map((s) => {\n          let body = \"\";\n          try {\n            body = readFileSync(skillContentPath(s.slug), \"utf8\");\n          } catch {\n            body = \"\";\n          }\n          const local = skills.some((localSkill) => localSkill.slug === s.slug);\n          return toListJsonSkill(s, { local, body });\n        });\n        process.stdout.write(\n          JSON.stringify(\n            {\n              skills: out,\n              groups: groups.map((g) => ({\n                kitRef: g.kitRef,\n                synced: g.kitRef !== null,\n                skills: g.skills.map((s) => s.slug),\n              })),\n            },\n            null,\n            2,\n          ) + \"\\n\",\n        );\n        return;\n      }\n\n      if (listedSkills.length === 0) {\n        if (manifest.fetched) {\n          console.log(\"No skills in your kits yet.\");\n          console.log(dim(\"  Add skills at \") + cyan(webBaseUrl()));\n          console.log(dim(\"  Or import local skills with `skillet import <path>`\"));\n        } else {\n          console.log(\"Your kit is empty.\");\n          console.log(dim(\"  Sign in and get a pair code at \") + cyan(`${webBaseUrl()}/settings`));\n          console.log(dim(\"  Then run \") + bold(\"skillet connect <code>\"));\n          console.log(dim(\"  Or import local skills with `skillet import <path>`\"));\n        }\n        return;\n      }\n\n      const notLocal = listedSkills.some(\n        (s) => !skills.some((localSkill) => localSkill.slug === s.slug),\n      );\n      console.log(renderKitList(groups, notLocal ? { registryOnly: true } : undefined));\n    });\n}\n", "import type { KitSkillGroup, SkillEntry } from '@skillet/core';\nimport { BUNDLED_ROUTE_SLUG } from '@skillet/core';\nimport { bold, cyan, dim, padEndVisible, yellow } from './cli-colors.js';\nimport { renderError } from './render-error.js';\n\nfunction formatSkillRow(\n  skill: SkillEntry,\n  slugWidth: number,\n  skipReason?: string,\n  kitAuthor?: string | null,\n): string {\n  // Slug and version only: descriptions and hashes are detail surfaces\n  // (--json, the web, doctor), and a scannable list beats a complete one.\n  // Inside a kit, a slug's author prefix DIMS when it matches the kit's\n  // author (context already says it) and stays bright when it differs \u2014\n  // the prefix becomes a trust signal that pops exactly when it matters.\n  const sameAuthorPrefix = kitAuthor ? `@${kitAuthor}/` : null;\n  const slugCol =\n    sameAuthorPrefix && skill.slug.startsWith(sameAuthorPrefix)\n      ? padEndVisible(\n          dim(sameAuthorPrefix) + cyan(skill.slug.slice(sameAuthorPrefix.length)),\n          slugWidth,\n        )\n      : padEndVisible(cyan(skill.slug), slugWidth);\n  const ver = dim(`v${skill.versionLabel ?? skill.version}`);\n  const skip = skipReason ? `  ${dim(`skipped: ${renderError(skipReason).line}`)}` : '';\n  return `  ${slugCol}  ${ver}${skip}`;\n}\n\nconst DEFAULT_SYNC_HEADER = 'Kits on this device';\n\n/** Grouped kit/skill plan for `skillet sync` and `--dry-run` (kit groups only). */\nexport function renderSyncKitPlan(\n  groups: KitSkillGroup[],\n  opts?: {\n    skipReasons?: Map<string, string>;\n    header?: string;\n    offline?: boolean;\n  },\n): string {\n  const kitGroups = groups.filter((g): g is KitSkillGroup & { kitRef: string } => g.kitRef !== null);\n  if (kitGroups.length === 0) {\n    return dim('No kit skills on this device.');\n  }\n\n  const lines: string[] = [];\n  const header = opts?.header ?? DEFAULT_SYNC_HEADER;\n  lines.push(bold(header));\n  if (opts?.offline) {\n    lines.push(dim('  (offline \u2014 grouped from local state)'));\n  }\n  lines.push('');\n\n  const slugWidth = Math.min(\n    48,\n    Math.max(12, ...kitGroups.flatMap((g) => g.skills.map((s) => s.slug.length))),\n  );\n\n  for (const group of kitGroups) {\n    lines.push(\n      bold(group.kitRef) +\n        dim(`  (${group.skills.length} skill${group.skills.length === 1 ? '' : 's'})`),\n    );\n    for (const skill of group.skills) {\n      const reason = opts?.skipReasons?.get(skill.slug);\n      lines.push(formatSkillRow(skill, slugWidth, reason));\n    }\n    lines.push('');\n  }\n\n  if (lines[lines.length - 1] === '') {\n    lines.pop();\n  }\n\n  return lines.join('\\n');\n}\n\nexport function renderKitList(\n  rawGroups: KitSkillGroup[],\n  opts?: { registryOnly?: boolean; awaitingConsent?: ReadonlySet<string> },\n): string {\n  // The bundled /skillet router is Skillet's own plumbing \u2014 it appears in\n  // machine surfaces (--json is the desktop's read contract) but never in a\n  // human list of \"your skills\".\n  const groups = rawGroups\n    .map((g) => ({ ...g, skills: g.skills.filter((s) => s.slug !== BUNDLED_ROUTE_SLUG) }))\n    .filter((g) => g.skills.length > 0);\n  const lines: string[] = [];\n  const total = groups.reduce((n, g) => n + g.skills.length, 0);\n  const synced = groups\n    .filter((g) => g.kitRef !== null)\n    .reduce((n, g) => n + g.skills.length, 0);\n  const localOnly = total - synced;\n\n  // The breakdown only appears when there IS a breakdown: with everything\n  // kit-synced, \"17 skills \u2014 17 synced from kits\" says one number twice.\n  lines.push(\n    localOnly > 0\n      ? bold(`${total} skill${total === 1 ? '' : 's'}`) + dim(`, ${localOnly} not in a kit`)\n      : bold(`${total} skill${total === 1 ? '' : 's'}`),\n  );\n  lines.push('');\n\n  const slugWidth = Math.min(\n    48,\n    Math.max(\n      12,\n      ...groups.flatMap((g) => g.skills.map((s) => s.slug.length)),\n    ),\n  );\n\n  for (const group of groups) {\n    const header =\n      group.kitRef !== null\n        ? bold(group.kitRef) + dim(`  (${group.skills.length} skill${group.skills.length === 1 ? '' : 's'})`)\n        : yellow('Not in a kit') + dim('  (local imports, not synced to agents)');\n    lines.push(header);\n\n    const kitAuthor =\n      group.kitRef !== null ? (group.kitRef.replace(/^@/, '').split('/')[0] ?? null) : null;\n    for (const skill of group.skills) {\n      const row = formatSkillRow(skill, slugWidth, undefined, kitAuthor);\n      lines.push(\n        opts?.awaitingConsent?.has(skill.slug) ? `${row}  ${dim('waiting for your OK')}` : row,\n      );\n    }\n    lines.push('');\n  }\n\n  if (groups.length > 0 && groups[groups.length - 1].skills.length >= 0) {\n    lines.pop(); // trailing blank\n  }\n\n  if (opts?.registryOnly) {\n    lines.push(\n      dim('Registry view. Run `skillet sync` to pull skills onto this machine.'),\n    );\n  } else if (localOnly > 0 && synced === 0) {\n    lines.push(\n      dim('No kit skills yet \u2014 sign in and run `skillet sync`, or add skills to a kit on the web.'),\n    );\n  }\n\n  return lines.join('\\n');\n}\n", "import type { SkillEntry } from \"@skillet/core\";\nimport { skillContentPath } from \"@skillet/core\";\n\nexport interface ListJsonSkill {\n  slug: string;\n  name: string;\n  description: string;\n  owner: string | null;\n  version: number;\n  versionLabel: string | null;\n  source: SkillEntry[\"source\"];\n  sourceClass: SkillEntry[\"sourceClass\"] | null;\n  sourceKit: string | null;\n  category: string | null;\n  synced: boolean;\n  pinned: boolean;\n  local: boolean;\n  /** Absolute path to this skill's SKILL.md on disk \u2014 the desktop shows it\n   *  (shortened) and opens it so you can read a skill before uploading. */\n  path: string;\n  body: string;\n}\n\n/** Per-skill mapping for `skillet list --json` (the desktop app's read contract). */\nexport function toListJsonSkill(\n  s: SkillEntry,\n  opts: { local: boolean; body: string },\n): ListJsonSkill {\n  return {\n    slug: s.slug,\n    name: s.name,\n    description: s.description,\n    owner: s.owner ?? null,\n    version: s.version,\n    versionLabel: s.versionLabel ?? null,\n    source: s.source,\n    sourceClass: s.sourceClass ?? null,\n    sourceKit: s.sourceKit ?? null,\n    category: s.category ?? null,\n    synced: typeof s.sourceKit === \"string\" && s.sourceKit.length > 0,\n    pinned: s.pinned === true,\n    local: opts.local,\n    path: skillContentPath(s.slug),\n    body: opts.body,\n  };\n}\n", "import type { Command } from \"commander\";\nimport { loadRegistryBearer } from \"@skillet/core\";\nimport { CLI_VERSION } from \"../cli-context.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\n\nexport function registerMcpCommand(program: Command): void {\n  program\n    .command(\"mcp\")\n    .description(\"Serve your kit to MCP agents (Claude Desktop, Cursor, Claude Code)\")\n    .option(\"--port <number>\", \"Start HTTP transport on this port instead of stdio\")\n    .option(\n      \"--token <token>\",\n      \"Bearer token for stdio mode (defaults to this machine's paired device token)\",\n    )\n    .action(async (opts: { port?: string; token?: string }) => {\n      const { runStdio } = await import(\"@skillet/mcp\");\n      const { startHttpTransport } = await import(\"@skillet/mcp\");\n\n      if (opts.port !== undefined) {\n        const port = Number.parseInt(opts.port, 10);\n        if (!Number.isFinite(port) || port < 1 || port > 65535) {\n          console.error(`\u2717 Invalid port: ${opts.port}`);\n          exitWith(ExitCode.ERROR);\n        }\n        const stop = await startHttpTransport({ port, serverVersion: CLI_VERSION }).catch((e: Error) => {\n          console.error(`\u2717 MCP HTTP server failed to start: ${e.message}`);\n          exitWith(ExitCode.ERROR);\n        });\n        if (stop.loopbackToken) {\n          console.error(\n            `MCP loopback bearer (Authorization: Bearer \u2026): saved to ~/.skillet/mcp-loopback-token`,\n          );\n        }\n        await new Promise<void>((resolve) => {\n          process.on(\"SIGINT\", () => stop.stop().finally(resolve));\n          process.on(\"SIGTERM\", () => stop.stop().finally(resolve));\n        });\n      } else {\n        // A human running this in a terminal sees a silent hang: stdio mode\n        // waits for JSON-RPC on stdin and keeps stdout a clean JSON stream, so\n        // there is nothing to print. Clients spawn us with piped stdin (no\n        // TTY), so this hint only reaches a person and never pollutes stdout.\n        if (process.stdin.isTTY) {\n          process.stderr.write(\n            \"This is the LOCAL MCP server. It runs on this machine and is now\\n\" +\n              \"waiting for a client to connect over stdin. Nothing else prints here:\\n\" +\n              \"stdout is reserved for the JSON stream.\\n\\n\" +\n              \"For a client on this machine (Claude Desktop, Cursor, Claude Code),\\n\" +\n              \"add this to its MCP config, then let the client launch skillet:\\n\" +\n              '  { \"mcpServers\": { \"skillet\": { \"command\": \"skillet\", \"args\": [\"mcp\"] } } }\\n\\n' +\n              \"For a web agent (ChatGPT, Claude.ai) that can't reach your machine,\\n\" +\n              \"use your hosted MCP link instead. Turn it on and copy it with:\\n\" +\n              \"  skillet web settings\\n\\n\" +\n              \"Full setup: skillet mcp --help. Press Ctrl+C to stop.\\n\\n\",\n          );\n        }\n        // stdio serves a local same-user client (the process could read\n        // ~/.skillet/skills directly), so default to the machine's own\n        // credentials: --token \u2192 device.json \u2192 session. Unpaired stays\n        // fail-closed (empty list).\n        const bearer = await loadRegistryBearer(opts.token);\n        await runStdio({ token: bearer.token || null, serverVersion: CLI_VERSION });\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport {\n  listPending,\n  approveUpdate,\n  rejectUpdate,\n  readState,\n  requiresQuarantineConsent,\n  renderFindingsSummary,\n} from \"@skillet/core\";\nimport type { PendingEntry } from \"@skillet/core\";\nimport { ALL_ADAPTERS } from \"../cli-context.js\";\nimport { applyToAgents } from \"../apply-to-agents.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { ok, fail, dim } from \"../cli-colors.js\";\nimport { printRenderedError } from \"../render-error.js\";\nimport { stripControlChars } from \"../sanitize-output.js\";\n\n/** `v1 \u2192 v2.1.0`-style range; each side prefers its semver label, falling back to the integer. */\nexport function formatPendingRange(\n  entry: Pick<\n    PendingEntry,\n    \"approvedVersion\" | \"approvedVersionLabel\" | \"incomingVersion\" | \"incomingVersionLabel\"\n  >,\n): string {\n  const incoming = `v${entry.incomingVersionLabel ?? entry.incomingVersion}`;\n  return entry.approvedVersion !== null\n    ? `v${entry.approvedVersionLabel ?? entry.approvedVersion} \u2192 ${incoming}`\n    : `new (${incoming})`;\n}\n\nexport function registerPendingCommands(program: Command): void {\n  program\n    .command(\"pending\")\n    .description(\n      \"Skills waiting for your review, with their diffs\",\n    )\n    .option(\"--json\", \"Emit a machine-readable pending list\")\n    .action(async (opts: { json?: boolean }) => {\n      try {\n        const result = await listPending(ALL_ADAPTERS);\n        if (opts.json === true) {\n          process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n          return;\n        }\n        if (result.pending.length === 0) {\n          console.log(\"No pending updates \u2014 all skills are approved or auto-applied.\");\n          return;\n        }\n        console.log(`${result.pending.length} skill(s) pending review:\\n`);\n        for (const entry of result.pending) {\n          const from = formatPendingRange(entry);\n          const author = entry.authorKeyId\n            ? `  author: ${entry.authorKeyId.slice(0, 16)}\u2026`\n            : \"\";\n          console.log(`  \u2022 ${entry.slug} (${from})${author}`);\n          if (entry.quarantined && entry.scanSummary) {\n            console.log(stripControlChars(entry.scanSummary));\n          }\n          if (entry.diff) {\n            console.log(stripControlChars(entry.diff));\n          } else {\n            console.log(\"  (no diff available; no agents detected)\");\n          }\n          console.log(\n            `  Approve: skillet approve ${entry.slug} --version ${entry.incomingVersion}`,\n          );\n          console.log(`  Reject:  skillet reject ${entry.slug}\\n`);\n        }\n      } catch (err) {\n        console.error(`\u2717 pending failed: ${(err as Error).message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  program\n    .command(\"approve <slug>\")\n    .description(\"Approve a skill's waiting update and apply it\")\n    .option(\n      \"--version <number>\",\n      \"Exact version to approve (defaults to the current waiting version)\",\n    )\n    .action(async (slug: string, opts: { version?: string }) => {\n      let version: number;\n      if (opts.version !== undefined) {\n        version = parseInt(opts.version, 10);\n        if (isNaN(version) || version < 1) {\n          console.error(fail(`--version must be a positive integer, got \"${opts.version}\"`));\n          exitWith(ExitCode.USAGE);\n          return;\n        }\n      } else {\n        // No flag: approve what's actually waiting \u2014 the CLI already knows.\n        const state = await readState();\n        const entry = state.skills[slug];\n        if (!entry) {\n          console.error(fail(`\"${slug}\" isn't in your kit.`));\n          exitWith(ExitCode.ERROR);\n          return;\n        }\n        version = entry.version;\n      }\n      // Quarantine check comes BEFORE the approval is recorded: a recorded\n      // approval satisfies the pending gate, which would make the entry\n      // vanish from `skillet pending` and the home menu \u2014 stranding a\n      // quarantined skill as approved-but-unapplied with no review surface\n      // left to consent on. Refuse first, record nothing.\n      const stateNow = await readState();\n      const entryNow = stateNow.skills[slug];\n      if (entryNow && requiresQuarantineConsent(entryNow.scan)) {\n        if (entryNow.scan) console.log(stripControlChars(renderFindingsSummary(entryNow.scan)));\n        console.error(\n          fail(\n            `\"${slug}\" is quarantined and was not approved or applied. Review it with \\`skillet\\` (home menu) or \\`skillet pending\\`.`,\n          ),\n        );\n        exitWith(ExitCode.ERROR);\n        return;\n      }\n      try {\n        await approveUpdate(slug, version, {});\n      } catch (err) {\n        console.error(fail(`approve failed: ${(err as Error).message}`));\n        exitWith(ExitCode.ERROR);\n        return;\n      }\n      try {\n        await applyToAgents([slug]);\n      } catch (err) {\n        // The approval IS recorded \u2014 say so, or the user can't explain why\n        // the entry vanished from pending while nothing changed on disk.\n        console.log(ok(`Approved \"${slug}\" v${version}.`));\n        printRenderedError(err as Error, (what) => fail(`Applying failed: ${what}`));\n        console.error(dim(\"  The approval is recorded; run `skillet sync` to finish applying.\"));\n        exitWith(ExitCode.ERROR);\n        return;\n      }\n      console.log(ok(`Approved and applied \"${slug}\" v${version}.`));\n    });\n\n  program\n    .command(\"reject <slug>\")\n    .description(\n      \"Reject a skill's waiting update; a newer version asks again\",\n    )\n    .action(async (slug: string) => {\n      try {\n        await rejectUpdate(slug);\n        console.log(\n          `\u2713 Rejected pending update for \"${slug}\". A new version will prompt again when it arrives.`,\n        );\n      } catch (err) {\n        console.error(`\u2717 reject failed: ${(err as Error).message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport { stdin } from \"node:process\";\nimport {\n  flushEvents,\n  listRouteManifest,\n  recordRouteInvocation,\n  recordSkillRoute,\n  RouteSkillError,\n  type RouteSurface,\n} from \"@skillet/core\";\nimport { bold, cyan, dim, green } from \"../cli-colors.js\";\nimport { webBaseUrl } from \"../cli-command-tier.js\";\nimport { ExitCode } from \"../exit-codes.js\";\n\nconst PHASE_SEARCHING = \"Searching\";\nconst PHASE_PICKED = \"Picked\";\nconst PHASE_USING = \"Using\";\n\nasync function readStdin(): Promise<string> {\n  return new Promise((resolve) => {\n    let body = \"\";\n    stdin.setEncoding(\"utf8\");\n    stdin.on(\"data\", (chunk: string) => {\n      body += chunk;\n    });\n    stdin.on(\"end\", () => resolve(body));\n    stdin.on(\"error\", () => resolve(\"\"));\n  });\n}\n\nfunction objectValues(value: unknown): unknown[] {\n  if (!value || typeof value !== \"object\") return [];\n  return Object.values(value as Record<string, unknown>);\n}\n\nfunction collectStrings(value: unknown, out: string[] = []): string[] {\n  if (typeof value === \"string\") {\n    out.push(value);\n    return out;\n  }\n  if (Array.isArray(value)) {\n    for (const item of value) collectStrings(item, out);\n    return out;\n  }\n  for (const item of objectValues(value)) collectStrings(item, out);\n  return out;\n}\n\nfunction hookPayloadInvokesSkillet(raw: string): boolean {\n  if (!raw.trim()) return false;\n  try {\n    const parsed = JSON.parse(raw) as unknown;\n    return collectStrings(parsed).some((text) => text.trimStart().startsWith(\"/skillet\"));\n  } catch {\n    return false;\n  }\n}\n\nfunction printPhases(skillRef: string, opts: { json?: boolean }): void {\n  const phases = [PHASE_SEARCHING, PHASE_PICKED, PHASE_USING];\n  if (opts.json) {\n    process.stdout.write(\n      JSON.stringify({ ok: true, skillRef, phases }) + \"\\n\",\n    );\n    return;\n  }\n  if (process.stdout.isTTY) {\n    console.log(dim(`  ${PHASE_SEARCHING}\u2026 kit skills`));\n    console.log(cyan(`  ${PHASE_PICKED}  ${skillRef}`));\n    console.log(green(`  ${PHASE_USING}  ${skillRef}`));\n    return;\n  }\n  console.log(`${PHASE_SEARCHING}`);\n  console.log(`${PHASE_PICKED} ${skillRef}`);\n  console.log(`${PHASE_USING} ${skillRef}`);\n}\n\nfunction emptyKitMessage(): string {\n  return (\n    `No skills in your kit. Run \\`skillet sync\\`, \\`skillet add @author/skill\\`, ` +\n    `or add skills on ${webBaseUrl()}.`\n  );\n}\n\nexport function registerRouteCommand(program: Command): void {\n  const route = program\n    .command(\"route\")\n    .description(\"The /skillet router: picks the right skill for a task\");\n\n  route\n    .command(\"manifest\")\n    .description(\"List kit skills for agent routing (metadata only, no SKILL.md bodies)\")\n    .option(\"--json\", \"Emit machine-readable manifest\")\n    .action(async (opts: { json?: boolean }) => {\n      const skills = await listRouteManifest();\n      if (skills.length === 0) {\n        if (opts.json) {\n          process.stdout.write(JSON.stringify({ skills: [], error: \"kit_empty\" }) + \"\\n\");\n        } else {\n          console.error(emptyKitMessage());\n        }\n        process.exitCode = ExitCode.ERROR;\n        return;\n      }\n\n      if (opts.json) {\n        process.stdout.write(JSON.stringify({ skills }) + \"\\n\");\n        return;\n      }\n\n      const refWidth = Math.max(\n        8,\n        ...skills.map((s) => s.skillRef.length),\n      );\n      console.log(bold(`${\"REF\".padEnd(refWidth)}  NAME`));\n      for (const s of skills) {\n        console.log(`${s.skillRef.padEnd(refWidth)}  ${s.name}`);\n      }\n    });\n\n  route\n    .command(\"begin\")\n    .description(\"Record a /skillet invocation (metadata only)\")\n    .option(\"--runtime <runtime>\", \"Agent name, e.g. cursor\")\n    .option(\"--source <source>\", \"Recorder source, e.g. cursor-hook\")\n    .option(\"--surface <surface>\", \"Invocation surface, e.g. user-prompt-submit\")\n    .option(\"--json\", \"Emit machine-readable result\")\n    .action(\n      async (opts: {\n        runtime?: string;\n        source?: string;\n        surface?: string;\n        json?: boolean;\n      }) => {\n        const result = recordRouteInvocation({\n          runtime: opts.runtime,\n          source: opts.source,\n          surface: opts.surface,\n        });\n        await flushEvents();\n        if (opts.json) {\n          process.stdout.write(JSON.stringify({ ok: true, ...result }) + \"\\n\");\n        }\n      },\n    );\n\n  route\n    .command(\"hook\")\n    .description(\"Agent hook entrypoint for /skillet\")\n    .option(\"--runtime <runtime>\", \"Agent name, e.g. cursor, claude-code, codex\")\n    .action(async (opts: { runtime?: string }) => {\n      const raw = await readStdin();\n      if (!hookPayloadInvokesSkillet(raw)) return;\n      const runtime = opts.runtime?.trim() || \"unknown\";\n      recordRouteInvocation({\n        runtime,\n        source: `${runtime}-hook`,\n        surface: \"user-prompt-submit\" satisfies RouteSurface,\n      });\n      await flushEvents();\n    });\n\n  route\n    .command(\"record <skill-ref>\")\n    .description(\"Record a routed skill pick\")\n    .option(\"--runtime <runtime>\", \"Agent name, e.g. cursor, claude-code, codex\")\n    .option(\"--json\", \"Emit machine-readable result\")\n    .action(\n      async (skillRef: string, opts: { runtime?: string; json?: boolean }) => {\n        try {\n          const result = await recordSkillRoute(skillRef, { runtime: opts.runtime });\n          printPhases(result.skillRef, { json: opts.json });\n        } catch (err) {\n          if (err instanceof RouteSkillError) {\n            if (!opts.json) console.error(err.message);\n            else {\n              process.stdout.write(\n                JSON.stringify({ ok: false, error: err.code, message: err.message }) + \"\\n\",\n              );\n            }\n            process.exitCode = ExitCode.ERROR;\n            return;\n          }\n          throw err;\n        }\n      },\n    );\n}\n", "import type { Command } from \"commander\";\nimport { mintPairCode } from \"@skillet/core\";\nimport { REGISTRY_DEFAULT } from \"../cli-context.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\n\nexport function registerPairCommand(program: Command): void {\n  program\n    .command(\"pair\")\n    .description(\"Mint a join code to attach another device, browser, or app to this account\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .option(\"--json\", \"Emit machine-readable result\")\n    .action(async (opts: { registry: string; json?: boolean }) => {\n      try {\n        const result = await mintPairCode({ registryUrl: opts.registry });\n        if (opts.json) {\n          process.stdout.write(JSON.stringify({ ok: true, ...result }, null, 2) + \"\\n\");\n          return;\n        }\n        const mins = Math.round(result.ttl_sec / 60);\n        console.log(`Join code: ${result.code}`);\n        console.log(`  Expires in ${mins} min.`);\n        console.log(`  On the other device, run: skillet connect ${result.code}`);\n        console.log(`  Or paste it into skillet.md \u2192 Settings \u2192 Devices, or the desktop app.`);\n      } catch (err) {\n        console.error(`\u2717 pair failed: ${(err as Error).message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport { evalSkills } from \"@skillet/core\";\nimport { ExitCode } from \"../exit-codes.js\";\n\nexport function registerEvalCommand(program: Command): void {\n  program\n    .command(\"eval [slug]\")\n    .description(\"Run the static basic eval (evals/smoke.json) against kit skill(s)\")\n    .option(\"--json\", \"Emit machine-readable results\")\n    .action(async (slug: string | undefined, opts: { json?: boolean }) => {\n      const slugs = slug ? [slug] : undefined;\n      const results = await evalSkills(slugs);\n      if (opts.json) {\n        process.stdout.write(JSON.stringify({ ok: true, results }) + \"\\n\");\n        return;\n      }\n      for (const r of results) {\n        const label = r.status === \"passed\" ? \"PASS\" : r.status === \"failed\" ? \"FAIL\" : \"SKIP\";\n        console.log(`${label}  ${r.slug}  (${r.status})`);\n        if (r.case_results) {\n          for (const c of r.case_results) {\n            const mark = c.passed ? \"  \u2713\" : \"  \u2717\";\n            console.log(`${mark} ${c.id}${c.missing ? ` \u2014 missing: ${c.missing.join(\", \")}` : \"\"}`);\n          }\n        }\n      }\n      const failed = results.some((r) => r.status === \"failed\");\n      if (failed) process.exitCode = ExitCode.ERROR;\n    });\n}\n", "import type { Command } from \"commander\";\nimport {\n  createKit,\n  addSkillToKit,\n  inviteKitMember,\n  listKitMembers,\n  mintKitKey,\n  removeKitMember,\n  revokeKitKey,\n  bootstrapLocalKit,\n} from \"@skillet/core\";\nimport { REGISTRY_DEFAULT_TEAM } from \"../../cli-context.js\";\nimport { ExitCode, exitWith } from \"../../exit-codes.js\";\n\nexport function registerKitCommands(program: Command): void {\n  const kit = program\n    .command(\"kit\")\n    .description(\"Manage private skill kits (share skills with teammates)\");\n\n  kit\n    .command(\"create <name>\")\n    .description(\"Create a private kit\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(async (name: string, opts: { registry: string; token?: string }) => {\n      try {\n        const result = await createKit({\n          name,\n          registryUrl: opts.registry,\n          token: opts.token,\n        });\n        console.log(`\u2713 Kit \"${result.name}\" created for @${result.owner}`);\n        console.log(`  id: ${result.id}`);\n      } catch (err) {\n        const e = err as Error & { code?: string };\n        console.error(`\u2717 kit create failed: ${e.message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  kit\n    .command(\"bootstrap <name>\")\n    .description(\n      \"Publish local skills, create a named kit, and add them so every signed-in device can sync the set\",\n    )\n    .option(\"--json\", \"Emit a machine-readable report (for the desktop app)\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(async (name: string, opts: { json?: boolean; registry: string; token?: string }) => {\n      try {\n        const result = await bootstrapLocalKit({\n          name,\n          registryUrl: opts.registry,\n          token: opts.token,\n          sessionAuth: true,\n        });\n        if (opts.json) {\n          process.stdout.write(JSON.stringify(result) + \"\\n\");\n          if (!result.ok && !result.empty) exitWith(ExitCode.ERROR);\n          return;\n        }\n        if (result.empty) {\n          console.log(\"No local skills to back up. Run `skillet import` to add skills from your runtimes first.\");\n          return;\n        }\n        if (!result.ok) {\n          console.error(\"\u2717 kit bootstrap did not complete.\");\n          for (const f of result.failed) {\n            console.error(`  ${f.slug} (${f.stage}): ${f.error}`);\n          }\n          exitWith(ExitCode.ERROR);\n        }\n        console.log(\n          `\u2713 Backed up ${result.kitLinked.length} skill(s) to kit \"${result.kit?.name}\" (@${result.owner})`,\n        );\n        if (result.failed.length > 0) {\n          console.log(`  ${result.failed.length} skill(s) had errors \u2014 see above.`);\n        }\n        console.log(\"  Run `skillet sync` on your other devices to pull them in.\");\n      } catch (err) {\n        const e = err as Error;\n        if (opts.json) {\n          process.stdout.write(JSON.stringify({ ok: false, error: e.message }) + \"\\n\");\n        } else {\n          console.error(`\u2717 kit bootstrap failed: ${e.message}`);\n        }\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  kit\n    .command(\"add <kit> <ref>\")\n    .description(\"Link a published skill into a kit (@author/slug into kit name or UUID)\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(\n      async (kitRef: string, ref: string, opts: { registry: string; token?: string }) => {\n        try {\n          await addSkillToKit({\n            kitRef,\n            skillRef: ref,\n            registryUrl: opts.registry,\n            token: opts.token,\n          });\n          console.log(`\u2713 Added ${ref} to kit ${kitRef}`);\n        } catch (err) {\n          const e = err as Error & { code?: string };\n          console.error(`\u2717 kit add failed: ${e.message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n\n  kit\n    .command(\"invite <kit> <handle>\")\n    .description(\"Invite a teammate to a private kit by handle\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(\n      async (kitRef: string, handle: string, opts: { registry: string; token?: string }) => {\n        try {\n          const result = await inviteKitMember({\n            kitRef,\n            handle,\n            registryUrl: opts.registry,\n            token: opts.token,\n          });\n          if (result.status === \"added\") {\n            console.log(`\u2713 @${handle} added to kit ${kitRef}`);\n          } else {\n            console.log(`\u2713 @${handle} invited to kit ${kitRef} (pending until they claim handle)`);\n          }\n        } catch (err) {\n          const e = err as Error & { code?: string };\n          console.error(`\u2717 kit invite failed: ${e.message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n\n  kit\n    .command(\"members <kit>\")\n    .description(\"List humans, pending invites, and kit-keys for a kit\")\n    .option(\"--json\", \"Emit machine-readable output\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(async (kitRef: string, opts: { json?: boolean; registry: string; token?: string }) => {\n      try {\n        const result = await listKitMembers({\n          kitRef,\n          registryUrl: opts.registry,\n          token: opts.token,\n        });\n        if (opts.json) {\n          process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n          return;\n        }\n        const ownerPrefix = result.owner ? `owner @${result.owner}, ` : \"\";\n        console.log(\n          `Kit ${kitRef} \u2014 ${ownerPrefix}${result.humans.length} invited member(s), ${result.pending_humans.length} pending, ${result.agents.length} key(s)`,\n        );\n        if (result.owner) {\n          console.log(`  owner   @${result.owner}`);\n        }\n        for (const h of result.humans) {\n          console.log(`  member  @${h.handle ?? h.user_id}`);\n        }\n        for (const p of result.pending_humans) {\n          console.log(`  pending ${p.handle ? `@${p.handle}` : p.email ?? p.invite_id}`);\n        }\n        for (const a of result.agents) {\n          const revoked = a.revoked_at ? \" (revoked)\" : \"\";\n          console.log(`  key     ${a.kit_key_id}  ${a.label}${revoked}`);\n        }\n      } catch (err) {\n        const e = err as Error & { code?: string };\n        console.error(`\u2717 kit members failed: ${e.message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  const kitKey = kit.command(\"key\").description(\"Manage headless kit-keys\");\n\n  kitKey\n    .command(\"mint <kit>\")\n    .description(\"Mint a scoped kit-key for CI/agents\")\n    .requiredOption(\"--label <label>\", \"Label for this key, e.g. ci-runner\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(async (kitRef: string, opts: { label: string; registry: string; token?: string }) => {\n      try {\n        const result = await mintKitKey({\n          kitRef,\n          label: opts.label,\n          registryUrl: opts.registry,\n          token: opts.token,\n        });\n        console.log(`\u2713 Kit-key minted for ${kitRef} (${result.label})`);\n        console.log(`  kit_key_id: ${result.kit_key_id}`);\n        console.log(`  token: ${result.kit_token}`);\n        console.log(\"  Store this token now \u2014 it is shown exactly once.\");\n      } catch (err) {\n        const e = err as Error & { code?: string };\n        console.error(`\u2717 kit key mint failed: ${e.message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  kitKey\n    .command(\"revoke <kit> <kit-key-id>\")\n    .description(\"Revoke a kit-key\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(\n      async (kitRef: string, kitKeyId: string, opts: { registry: string; token?: string }) => {\n        try {\n          await revokeKitKey({\n            kitRef,\n            kitKeyId,\n            registryUrl: opts.registry,\n            token: opts.token,\n          });\n          console.log(`\u2713 Revoked kit-key ${kitKeyId} on kit ${kitRef}`);\n        } catch (err) {\n          const e = err as Error & { code?: string };\n          console.error(`\u2717 kit key revoke failed: ${e.message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n\n  const kitMember = kit.command(\"member\").description(\"Manage kit membership\");\n\n  kitMember\n    .command(\"remove <kit> <handle>\")\n    .description(\"Remove a human member from a kit\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(\n      async (kitRef: string, handle: string, opts: { registry: string; token?: string }) => {\n        try {\n          await removeKitMember({\n            kitRef,\n            handle,\n            registryUrl: opts.registry,\n            token: opts.token,\n          });\n          console.log(`\u2713 Removed @${handle} from kit ${kitRef}`);\n        } catch (err) {\n          const e = err as Error & { code?: string };\n          console.error(`\u2717 kit member remove failed: ${e.message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n}\n", "import type { Command } from \"commander\";\nimport { login, claimHandle, secondaryDeviceMessage } from \"@skillet/core\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\n\nexport function registerLoginLegacyCommands(program: Command): void {\n  program\n    .command(\"login\")\n    .description(\n      \"Claim a handle and create local Ed25519 author key (native app flow; use `skillet connect` to pair this machine)\",\n    )\n    .requiredOption(\"--handle <handle>\", \"Your registry handle, e.g. taylor\")\n    .requiredOption(\"--name <name>\", \"Display name for your profile\")\n    .option(\"--avatar <url>\", \"Avatar URL\")\n    .option(\n      \"--registry <url>\",\n      \"Registry base URL (defaults to SKILLET_REGISTRY_URL env var or the built-in default)\",\n      process.env[\"SKILLET_REGISTRY_URL\"],\n    )\n    .option(\"--json\", \"Emit machine-readable identity JSON (for the native app)\")\n    .action(\n      async (opts: {\n        handle: string;\n        name: string;\n        avatar?: string;\n        registry?: string;\n        json?: boolean;\n      }) => {\n        try {\n          const result = await login({\n            handle: opts.handle,\n            name: opts.name,\n            ...(opts.avatar ? { avatarUrl: opts.avatar } : {}),\n            ...(opts.registry ? { registryUrl: opts.registry } : {}),\n          });\n          const { identity, created } = result;\n          if (opts.json) {\n            process.stdout.write(JSON.stringify({ ok: true, created, identity }) + \"\\n\");\n            return;\n          }\n          console.log(\n            created\n              ? `\u2713 Registered @${identity.handle} on ${identity.registryUrl}`\n              : `\u2713 Re-attached @${identity.handle} on ${identity.registryUrl}`,\n          );\n          console.log(`  key: ${identity.keyId.slice(0, 16)}\u2026`);\n          if (created) {\n            // Recoverability nudge: a handle-claimed account has no email, so\n            // losing this machine loses the account. Point to the non-forking\n            // path (pair the browser, then add an email in Settings).\n            console.log(\n              `\\n  Tip: add an email so you can recover this account and sign in on the web.\\n` +\n                `  Run \\`skillet pair\\`, connect your browser at the link it prints, then add an email in Settings \u2192 Account.`,\n            );\n          }\n        } catch (err) {\n          if (opts.json) {\n            process.stdout.write(\n              JSON.stringify({ ok: false, error: (err as Error).message }) + \"\\n\",\n            );\n            exitWith(ExitCode.ERROR);\n          }\n          console.error(`\u2717 Login failed: ${(err as Error).message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n\n  program\n    .command(\"claim\")\n    .description(\n      \"Bind this machine as the primary signing key (first device only; use connect on additional machines)\",\n    )\n    .option(\n      \"--registry <url>\",\n      \"Registry base URL (defaults to SKILLET_REGISTRY_URL or identity registry)\",\n      process.env[\"SKILLET_REGISTRY_URL\"],\n    )\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(async (opts: { registry?: string; token?: string }) => {\n      try {\n        const result = await claimHandle({\n          ...(opts.registry ? { registryUrl: opts.registry } : {}),\n          ...(opts.token ? { token: opts.token } : {}),\n        });\n        if (result.primaryElsewhere) {\n          console.log(`\u2713 ${secondaryDeviceMessage(result.handle)}`);\n          return;\n        }\n        console.log(`\u2713 Claimed @${result.handle} with key ${result.key_id.slice(0, 16)}\u2026`);\n      } catch (err) {\n        console.error(`\u2717 Claim failed: ${(err as Error).message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport { propose, ProposeError, RegistryClient } from \"@skillet/core\";\nimport { resolveRegistryUrl } from \"../cli-context.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { stripControlChars, formatScanFinding } from \"../sanitize-output.js\";\n\nasync function registryClient(opts: { registry?: string; token?: string }): Promise<RegistryClient> {\n  const registryUrl = await resolveRegistryUrl(opts);\n  const token = opts.token ?? process.env[\"SKILLET_TOKEN\"];\n  return new RegistryClient({\n    baseUrl: registryUrl,\n    ...(token ? { token } : {}),\n  });\n}\n\nexport function registerProposeCommands(program: Command): void {\n  program\n    .command(\"propose <slug>\")\n    .description(\n      \"Sign and submit a pending proposal for a skill. Does not publish live until the owner approves.\",\n    )\n    .option(\"--registry <url>\", \"Registry base URL (overrides identity default)\")\n    .option(\"--token <token>\", \"Bearer token (overrides SKILLET_TOKEN env var)\")\n    .action(async (slug: string, opts: { registry?: string; token?: string }) => {\n      try {\n        const result = await propose(slug, {\n          ...(opts.registry ? { registryUrl: opts.registry } : {}),\n          ...(opts.token ? { token: opts.token } : {}),\n        });\n        console.log(`\u2713 Proposal submitted for ${slug}`);\n        console.log(`  proposal: ${result.proposalId}`);\n        console.log(`  hash:     ${result.hash}`);\n        console.log(`  url:      ${result.proposalUrl}`);\n      } catch (err) {\n        if (err instanceof ProposeError) {\n          console.error(`\u2717 ${err.message}`);\n          if (err.code === \"stale_base\") {\n            console.error(\"  Run `skillet sync` (or fetch the latest manifest) and re-propose.\");\n          } else if (err.code === \"scan_blocked\") {\n            // The registry proposal gate refused a secret \u2014 list each file:line\n            // so the author knows what to remove (same shape as publish).\n            const body = err.detail as\n              | { findings?: Array<{ file: string; lineStart: number; category: string }> }\n              | undefined;\n            for (const f of body?.findings ?? []) {\n              console.error(formatScanFinding(f));\n            }\n            console.error(\"  Remove the credential (use an env var or placeholder) and re-propose.\");\n          }\n          exitWith(ExitCode.ERROR);\n        }\n        console.error(`\u2717 Propose failed: ${(err as Error).message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  const proposals = program\n    .command(\"proposals\")\n    .description(\"Inspect proposals for a skill (@author/slug)\");\n\n  proposals\n    .command(\"list <ref>\")\n    .description(\"List proposals for a skill (@author/slug)\")\n    .option(\"--registry <url>\", \"Registry base URL\")\n    .option(\"--token <token>\", \"Bearer token (overrides SKILLET_TOKEN env var)\")\n    .option(\"--json\", \"Emit raw JSON\")\n    .action(\n      async (ref: string, opts: { registry?: string; token?: string; json?: boolean }) => {\n        const client = await registryClient(opts);\n        try {\n          const list = await client.listProposals(ref);\n          if (opts.json) {\n            console.log(JSON.stringify(list, null, 2));\n            return;\n          }\n          if (list.length === 0) {\n            console.log(`No proposals for ${ref}.`);\n            return;\n          }\n          for (const p of list) {\n            const date = new Date(p.created_at * 1000).toISOString().slice(0, 10);\n            console.log(\n              `  ${p.proposal_id.slice(0, 8)}\u2026  [${p.state}]  ${p.proposer}  ${date}`,\n            );\n            console.log(`    hash: ${p.proposed_hash}`);\n          }\n        } catch (err) {\n          console.error(`\u2717 ${(err as Error).message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n\n  proposals\n    .command(\"show <ref> <proposalId>\")\n    .description(\"Show proposal detail with graded diff (@author/slug proposalId)\")\n    .option(\"--registry <url>\", \"Registry base URL\")\n    .option(\"--token <token>\", \"Bearer token (overrides SKILLET_TOKEN env var)\")\n    .option(\"--json\", \"Emit raw JSON\")\n    .action(\n      async (\n        ref: string,\n        proposalId: string,\n        opts: { registry?: string; token?: string; json?: boolean },\n      ) => {\n        const client = await registryClient(opts);\n        try {\n          const detail = await client.getProposal(ref, proposalId);\n          if (opts.json) {\n            console.log(JSON.stringify(detail, null, 2));\n            return;\n          }\n          console.log(`Proposal ${detail.proposal_id} [${detail.state}]`);\n          console.log(`  skill:    ${ref}`);\n          console.log(`  proposer: ${detail.proposer.handle}`);\n          console.log(`  hash:     ${detail.proposed_hash}`);\n          console.log(`  scan:     ${detail.scan.status}`);\n          if (detail.diff.length > 0) {\n            console.log(\"\\nDiff:\");\n            for (const f of detail.diff) {\n              if (f.status === \"unchanged\") continue;\n              // Path + diff content are attacker-controlled (registry-supplied);\n              // strip terminal control sequences before printing (deepsec MEDIUM\n              // terminal-injection).\n              console.log(\n                `  ${f.status.toUpperCase()}  ${stripControlChars(f.path)}${f.binary ? \" (binary)\" : \"\"}`,\n              );\n              if (f.diff) {\n                for (const line of f.diff.split(\"\\n\").slice(0, 20)) {\n                  console.log(`    ${stripControlChars(line)}`);\n                }\n              }\n            }\n          }\n        } catch (err) {\n          console.error(`\u2717 ${(err as Error).message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n}\n", "import type { Command } from \"commander\";\nimport { readState, publishAll, loadIdentity, loadRegistryBearer, PublishError } from \"@skillet/core\";\nimport * as clack from \"@clack/prompts\";\nimport { printDeprecationHint } from \"../cli-deprecation.js\";\nimport { fail } from \"../cli-colors.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { formatScanFinding } from \"../sanitize-output.js\";\n\nexport function registerPublishCommand(program: Command): void {\n  program\n    .command(\"publish [slug]\")\n    .description(\n      \"Legacy: sign and push skill(s) to the registry (prefer `upload` on this device)\",\n    )\n    .option(\n      \"--registry <url>\",\n      \"Registry base URL (defaults to the one captured at login)\",\n      process.env[\"SKILLET_REGISTRY_URL\"],\n    )\n    .option(\"--token <token>\", \"Bearer token for the registry (defaults to $SKILLET_TOKEN)\")\n    .option(\"--public\", \"Publish publicly (requires confirmation; default is private)\")\n    .option(\"--yes\", \"Skip the public-publish confirmation (required for --public without a terminal)\")\n    .option(\"--handle <handle>\", \"Claim this handle at first publish (inline login)\")\n    .option(\"--name <name>\", \"Display name for inline handle claim\")\n    .option(\"--session\", \"Publish via verified session (web/desktop); no local Ed25519 signature\")\n    .option(\"--json\", \"Emit a machine-readable publish report (for the native app)\")\n    .action(\n      async (\n        slug: string | undefined,\n        opts: {\n          registry?: string;\n          token?: string;\n          public?: boolean;\n          yes?: boolean;\n          handle?: string;\n          name?: string;\n          json?: boolean;\n          session?: boolean;\n        },\n      ) => {\n        printDeprecationHint(\n          \"To share local skills from this machine, use `skillet upload`\",\n        );\n        const asJson = opts.json === true;\n        const isPublic = opts.public === true;\n        const visibility = isPublic ? \"public\" : \"private\";\n\n        let slugsToPublish: string[];\n        if (slug) {\n          slugsToPublish = [slug];\n        } else {\n          const state = await readState();\n          slugsToPublish = Object.keys(state.skills);\n          if (slugsToPublish.length === 0) {\n            if (asJson) {\n              process.stdout.write(\n                JSON.stringify({ ok: true, visibility, results: [], empty: true }) + \"\\n\",\n              );\n              return;\n            }\n            console.log(\"Kit is empty. Use `skillet import <path>` to add a skill first.\");\n            return;\n          }\n          if (!asJson) {\n            console.log(\n              `Found ${slugsToPublish.length} skill(s) in kit: ${slugsToPublish.join(\", \")}`,\n            );\n          }\n        }\n\n        // Public visibility always needs explicit consent: the clack confirm\n        // on a terminal, or the --yes flag anywhere. Headless --public without\n        // --yes refuses \u2014 it must never publish publicly in silence.\n        if (isPublic && opts.yes !== true) {\n          // Prompting needs BOTH streams: clack renders on stdout and reads\n          // stdin. Either one piped means no real consent is possible \u2014 the\n          // explicit flag is the only path (fail closed).\n          if (process.stdout.isTTY !== true || process.stdin.isTTY !== true) {\n            if (asJson) {\n              process.stdout.write(\n                JSON.stringify({\n                  ok: false,\n                  code: \"confirmation_required\",\n                  error: \"publishing publicly needs --yes when not run interactively\",\n                }) + \"\\n\",\n              );\n            } else {\n              console.error(fail(\"Publishing publicly needs --yes when not run interactively.\"));\n            }\n            exitWith(ExitCode.USAGE);\n            return;\n          }\n          const answer = await clack.confirm({\n            message: `Publish ${slugsToPublish.length} skill${slugsToPublish.length === 1 ? \"\" : \"s\"} publicly? Anyone will be able to see them.`,\n            initialValue: false,\n          });\n          // Esc or No: fail closed, nothing published.\n          if (clack.isCancel(answer) || answer !== true) {\n            console.log(\"Cancelled. Nothing published.\");\n            return;\n          }\n        }\n\n        const identity = await loadIdentity();\n        const bearer = await loadRegistryBearer(opts.token);\n        const useSessionPublish = opts.session === true || (!!bearer.token && !identity);\n\n        let resolvedHandle = opts.handle;\n        let resolvedName = opts.name;\n        if (\n          !identity &&\n          !useSessionPublish &&\n          !resolvedHandle &&\n          process.stdout.isTTY === true &&\n          process.stdin.isTTY === true\n        ) {\n          console.log(\"\\nFirst publish. Claim your identity.\\n\");\n          const handleAnswer = await clack.text({\n            message: \"Handle\",\n            placeholder: \"e.g. taylor\",\n            validate: (v) => (v && v.trim().length > 0 ? undefined : \"A handle is required\"),\n          });\n          if (clack.isCancel(handleAnswer)) {\n            console.log(\"Cancelled. Nothing published.\");\n            return;\n          }\n          resolvedHandle = String(handleAnswer).trim().toLowerCase();\n          const nameAnswer = await clack.text({\n            message: \"Display name\",\n            placeholder: \"e.g. Taylor Santos\",\n          });\n          if (clack.isCancel(nameAnswer)) {\n            console.log(\"Cancelled. Nothing published.\");\n            return;\n          }\n          resolvedName = String(nameAnswer ?? \"\").trim();\n        }\n\n        try {\n          const results = await publishAll(slugsToPublish, {\n            ...(opts.registry ? { registryUrl: opts.registry } : {}),\n            ...(opts.token ? { token: opts.token } : {}),\n            visibility,\n            ...(resolvedHandle ? { handle: resolvedHandle } : {}),\n            ...(resolvedName ? { name: resolvedName } : {}),\n            ...(useSessionPublish ? { sessionAuth: true } : {}),\n          });\n\n          const resolvedIdentity = await loadIdentity();\n          const handle = resolvedIdentity?.handle ?? resolvedHandle ?? \"unknown\";\n\n          if (asJson) {\n            process.stdout.write(\n              JSON.stringify({\n                ok: true,\n                visibility,\n                handle,\n                results: results.map((r) => ({\n                  slug: r.slug,\n                  alreadyExists: r.alreadyExists,\n                  hashRef: r.hashRef,\n                  versionUrl: r.versionUrl,\n                  requiresWarnings: r.requiresWarnings,\n                })),\n              }) + \"\\n\",\n            );\n            return;\n          }\n\n          for (const result of results) {\n            for (const w of result.requiresWarnings) {\n              console.log(`\u26A0  ${result.slug}: requires: ${w}`);\n            }\n            console.log(\n              result.alreadyExists\n                ? `= ${handle}/${result.slug} already at ${result.hashRef.slice(0, 19)}\u2026 (no-op)`\n                : `\u2713 Published ${handle}/${result.slug} [${visibility}] ${result.hashRef.slice(0, 19)}\u2026`,\n            );\n            if (!result.alreadyExists) {\n              console.log(`  ${result.versionUrl}`);\n            }\n            // A flagged version publishes, but installers see the\n            // findings. Nudge the author to explain them on the web (notes can't\n            // be entered from the CLI).\n            if (result.serverScan?.status === \"flagged\") {\n              const n = result.serverScan.findings.length;\n              console.log(\n                `  \u2691 ${n} pattern${n === 1 ? \"\" : \"s\"} flagged \u2014 add an explanation at /${handle}/${result.slug} so installers know why.`,\n              );\n            }\n          }\n        } catch (err) {\n          if (asJson) {\n            const code = err instanceof PublishError ? err.code : \"publish_failed\";\n            const detail = err instanceof PublishError ? err.detail : undefined;\n            process.stdout.write(\n              JSON.stringify({\n                ok: false,\n                code,\n                error: (err as Error).message,\n                ...(detail !== undefined ? { detail } : {}),\n              }) + \"\\n\",\n            );\n            exitWith(ExitCode.ERROR);\n          }\n          if (err instanceof PublishError) {\n            console.error(`\u2717 ${err.message}`);\n            if (err.code === \"stale_base\") {\n              console.error(\"  Run `skillet sync` to pick up the latest version, then publish again.\");\n              exitWith(ExitCode.CONFLICT);\n            } else if (err.code === \"scan_blocked\") {\n              // The registry refused a secret or quarantined verdict.\n              const body = err.detail as\n                | {\n                    reason?: \"secret\" | \"quarantine\";\n                    findings?: Array<{ file: string; lineStart: number; category: string }>;\n                  }\n                | undefined;\n              for (const f of body?.findings ?? []) {\n                console.error(formatScanFinding(f));\n              }\n              console.error(\n                body?.reason === \"secret\"\n                  ? \"  Remove the credential (use an env var or placeholder) and republish.\"\n                  : \"  Fix the flagged patterns and republish.\",\n              );\n            }\n            exitWith(ExitCode.ERROR);\n          }\n          console.error(`\u2717 Publish failed: ${(err as Error).message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n}\n", "import { dim } from \"./cli-colors.js\";\n\n/** Print a one-line stderr hint when a deprecated alias is invoked (TTY or not). */\nexport function printDeprecationHint(message: string): void {\n  console.error(dim(message));\n}\n", "import type { Command } from \"commander\";\nimport { createOrg, inviteOrgMember, listOrgMembers } from \"@skillet/core\";\nimport { REGISTRY_DEFAULT_TEAM } from \"../../cli-context.js\";\nimport { ExitCode, exitWith } from \"../../exit-codes.js\";\n\nexport function registerTeamCommands(program: Command): void {\n  const team = program\n    .command(\"team\")\n    .description(\"Manage teams (organizations) on the registry\");\n\n  team\n    .command(\"create\")\n    .description(\"Create a new team on the registry\")\n    .requiredOption(\"--slug <slug>\", \"URL-safe team identifier, e.g. acme\")\n    .requiredOption(\"--name <name>\", \"Human-readable team name\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to ~/.skillet/session.json)\")\n    .action(async (opts: { slug: string; name: string; registry: string; token?: string }) => {\n      try {\n        const result = await createOrg({\n          slug: opts.slug,\n          name: opts.name,\n          registryUrl: opts.registry,\n          token: opts.token,\n        });\n        console.log(`\u2713 Team \"${result.name}\" created (slug: ${result.slug})`);\n        console.log(`  id: ${result.org_id}`);\n      } catch (err) {\n        const e = err as Error & { code?: string };\n        console.error(`\u2717 team create failed: ${e.message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n\n  team\n    .command(\"invite <slug>\")\n    .description(\"Invite a member to a team by handle or email\")\n    .option(\"--handle <handle>\", \"Skillet handle of the user to invite\")\n    .option(\"--email <email>\", \"Email address of the user to invite\")\n    .option(\"--role <role>\", \"Role to assign: member (default) or admin\", \"member\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to ~/.skillet/session.json)\")\n    .action(\n      async (\n        slug: string,\n        opts: { handle?: string; email?: string; role: string; registry: string; token?: string },\n      ) => {\n        if (!opts.handle && !opts.email) {\n          console.error(\"\u2717 Provide --handle or --email\");\n          exitWith(ExitCode.USAGE);\n        }\n        if (opts.handle && opts.email) {\n          console.error(\"\u2717 Provide --handle or --email, not both\");\n          exitWith(ExitCode.USAGE);\n        }\n        if (opts.role !== \"member\" && opts.role !== \"admin\") {\n          console.error(`\u2717 Invalid role \"${opts.role}\". Use \"member\" or \"admin\".`);\n          exitWith(ExitCode.USAGE);\n        }\n        try {\n          const result = await inviteOrgMember({\n            orgSlug: slug,\n            handle: opts.handle,\n            email: opts.email,\n            role: opts.role as \"member\" | \"admin\",\n            registryUrl: opts.registry,\n            token: opts.token,\n          });\n          if (result.status === \"added\") {\n            console.log(`\u2713 Added ${opts.handle ?? opts.email} to ${slug}`);\n          } else {\n            console.log(`\u2713 Invited ${opts.handle ?? opts.email} to ${slug} (pending acceptance)`);\n          }\n        } catch (err) {\n          const e = err as Error & { code?: string };\n          console.error(`\u2717 team invite failed: ${e.message}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n\n  team\n    .command(\"members <slug>\")\n    .description(\"List members of a team\")\n    .option(\"--json\", \"Emit machine-readable member list\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT_TEAM)\n    .option(\"--token <token>\", \"Session token (defaults to ~/.skillet/session.json)\")\n    .action(async (slug: string, opts: { json?: boolean; registry: string; token?: string }) => {\n      try {\n        const result = await listOrgMembers({\n          orgSlug: slug,\n          registryUrl: opts.registry,\n          token: opts.token,\n        });\n        if (opts.json) {\n          process.stdout.write(JSON.stringify(result, null, 2) + \"\\n\");\n          return;\n        }\n        console.log(`Team: ${result.org.name} (${result.org.slug})`);\n        if (result.members.length === 0 && result.pending.length === 0) {\n          console.log(\"  (no members)\");\n          return;\n        }\n        if (result.members.length > 0) {\n          console.log(`\\n${result.members.length} member(s):`);\n          for (const m of result.members) {\n            console.log(`  ${m.role.padEnd(6)}  @${m.handle ?? m.user_id}`);\n          }\n        }\n        if (result.pending.length > 0) {\n          console.log(`\\n${result.pending.length} pending invite(s):`);\n          for (const p of result.pending) {\n            const who = p.handle ? `@${p.handle}` : p.email ?? \"(unknown)\";\n            console.log(`  ${p.role.padEnd(6)}  ${who}`);\n          }\n        }\n      } catch (err) {\n        const e = err as Error & { code?: string };\n        console.error(`\u2717 team members failed: ${e.message}`);\n        exitWith(ExitCode.ERROR);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport {\n  loadPolicy,\n  setGlobalDefault,\n  setAuthorPolicy,\n  setSkillPolicy,\n  setKitPolicy,\n  type TrustMode,\n  type SourceClass,\n} from \"@skillet/core\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\n\nfunction parseMode(v: string): TrustMode {\n  if (v === \"auto\" || v === \"gate\") return v;\n  console.error(`\u2717 Invalid mode \"${v}\". Use \"auto\" or \"gate\".`);\n  exitWith(ExitCode.USAGE);\n}\n\nexport function registerTrustCommands(program: Command): void {\n  const trust = program\n    .command(\"trust\", { hidden: true })\n    .description(\"Control whether synced updates auto-apply or wait for a diff\");\n\n  trust\n    .command(\"show\")\n    .description(\"Show the current update-trust policy (globals, authors, kits, skills)\")\n    .option(\"--json\", \"Emit the raw policy JSON\")\n    .action(async (opts: { json?: boolean }) => {\n      const policy = await loadPolicy();\n      if (opts.json) {\n        console.log(JSON.stringify(policy, null, 2));\n        return;\n      }\n      console.log(\"Update-trust policy\");\n      console.log(`  global  own-kit (your team):  ${policy.globals[\"own-kit\"]}`);\n      console.log(`  global  external (strangers): ${policy.globals.external}`);\n      const authors = Object.entries(policy.authors);\n      const kits = Object.entries(policy.kits);\n      const skills = Object.entries(policy.skills);\n      if (authors.length) {\n        console.log(\"  per-author:\");\n        for (const [k, m] of authors) console.log(`    ${k.slice(0, 16)}\u2026 \u2192 ${m}`);\n      }\n      if (kits.length) {\n        console.log(\"  per-kit:\");\n        for (const [k, m] of kits) console.log(`    ${k} \u2192 ${m}`);\n      }\n      if (skills.length) {\n        console.log(\"  per-skill:\");\n        for (const [s, m] of skills) console.log(`    ${s} \u2192 ${m}`);\n      }\n      if (!authors.length && !kits.length && !skills.length) {\n        console.log(\"  (no per-author, per-kit, or per-skill overrides \u2014 defaults apply)\");\n      }\n    });\n\n}\n\n/** Legacy trust mutations \u2014 SKILLET_LEGACY_CLI=1 only. */\nexport function registerLegacyTrustCommands(program: Command): void {\n  const trust = program.commands.find((c) => c.name() === \"trust\");\n  if (!trust) {\n    throw new Error(\"registerTrustCommands must run before registerLegacyTrustCommands\");\n  }\n\n  trust\n    .command(\"default <class> <mode>\")\n    .description('Set a global default. <class>: own-kit | external. <mode>: auto | gate')\n    .action(async (cls: string, mode: string) => {\n      if (cls !== \"own-kit\" && cls !== \"external\") {\n        console.error(`\u2717 Invalid class \"${cls}\". Use \"own-kit\" or \"external\".`);\n        exitWith(ExitCode.USAGE);\n      }\n      await setGlobalDefault(cls as SourceClass, parseMode(mode));\n      console.log(`\u2713 Global default for ${cls} set to ${mode}.`);\n    });\n\n  trust\n    .command(\"author <keyId> <mode>\")\n    .description('Trust an author by key ID. <mode>: auto | gate | clear (remove override)')\n    .action(async (keyId: string, mode: string) => {\n      if (mode === \"clear\") {\n        await setAuthorPolicy(keyId, null);\n        console.log(`\u2713 Cleared per-author override for ${keyId.slice(0, 16)}\u2026.`);\n        return;\n      }\n      await setAuthorPolicy(keyId, parseMode(mode));\n      console.log(`\u2713 Author ${keyId.slice(0, 16)}\u2026 set to ${mode}.`);\n    });\n\n  trust\n    .command(\"skill <slug> <mode>\")\n    .description('Override trust for one skill. <mode>: auto | gate | clear (remove override)')\n    .action(async (slug: string, mode: string) => {\n      if (mode === \"clear\") {\n        await setSkillPolicy(slug, null);\n        console.log(`\u2713 Cleared per-skill override for ${slug}.`);\n        return;\n      }\n      await setSkillPolicy(slug, parseMode(mode));\n      console.log(`\u2713 Skill ${slug} set to ${mode}.`);\n    });\n\n  trust\n    .command(\"kit <kitRef> <mode>\")\n    .description(\n      \"Auto-apply or gate updates from one subscribed kit. <kitRef>: @owner/kit. <mode>: auto | gate | clear (remove override)\",\n    )\n    .action(async (kitRef: string, mode: string) => {\n      if (mode === \"clear\") {\n        await setKitPolicy(kitRef, null);\n        console.log(`\u2713 Cleared per-kit override for ${kitRef}.`);\n        return;\n      }\n      await setKitPolicy(kitRef, parseMode(mode));\n      console.log(`\u2713 Kit ${kitRef} set to ${mode}.`);\n    });\n}\n", "import type { Command } from \"commander\";\nimport { registerLegacyAuthCommands } from \"./auth.js\";\nimport { registerPairCommand } from \"./pair.js\";\nimport { registerEvalCommand } from \"./eval.js\";\nimport { registerKitCommands } from \"./kit/index.js\";\nimport { registerLoginLegacyCommands } from \"./login-legacy.js\";\nimport { registerProposeCommands } from \"./propose.js\";\nimport { registerPublishCommand } from \"./publish.js\";\nimport { registerTeamCommands } from \"./team/index.js\";\nimport { registerLegacyTrustCommands } from \"./trust.js\";\n\n/** Registry management verbs \u2014 opt in with SKILLET_LEGACY_CLI=1. */\nexport function registerManagementCommands(program: Command): void {\n  registerPairCommand(program);\n  registerLoginLegacyCommands(program);\n  registerEvalCommand(program);\n  registerPublishCommand(program);\n  registerProposeCommands(program);\n  registerKitCommands(program);\n  registerTeamCommands(program);\n  registerLegacyAuthCommands(program);\n  registerLegacyTrustCommands(program);\n}\n", "import type { Command } from \"commander\";\nimport { listTrash, restoreTrash } from \"@skillet/core\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\n\nfunction relTime(iso: string): string {\n  const then = Date.parse(iso);\n  if (!Number.isFinite(then)) return iso;\n  const mins = Math.round((Date.now() - then) / 60000);\n  if (mins < 1) return \"just now\";\n  if (mins < 60) return `${mins}m ago`;\n  const hrs = Math.round(mins / 60);\n  if (hrs < 24) return `${hrs}h ago`;\n  return `${Math.round(hrs / 24)}d ago`;\n}\n\nexport function registerRestoreCommand(program: Command): void {\n  program\n    .command(\"restore [run]\")\n    .description(\n      \"Restore skills a sync prune moved to trash. No args lists runs; pass a run id or `latest`.\",\n    )\n    .option(\"--json\", \"Emit machine-readable output\")\n    .action(async (run: string | undefined, opts: { json?: boolean }) => {\n      const asJson = opts.json === true;\n\n      // No arg \u2192 list restorable runs.\n      if (!run) {\n        const runs = await listTrash();\n        if (asJson) {\n          process.stdout.write(JSON.stringify({ ok: true, runs }, null, 2) + \"\\n\");\n          return;\n        }\n        if (runs.length === 0) {\n          console.log(\"Nothing in trash to restore.\");\n          return;\n        }\n        console.log(\"Trashed by sync prune (restore with `skillet restore <id>` or `latest`):\\n\");\n        for (const r of runs) {\n          console.log(\n            `  ${r.id}  \u00B7 ${relTime(r.trashedAt)} \u00B7 ${r.skills.length} skill${r.skills.length === 1 ? \"\" : \"s\"}`,\n          );\n          console.log(`    ${r.skills.join(\", \")}`);\n        }\n        return;\n      }\n\n      const runId = run === \"latest\" ? undefined : run;\n      const result = await restoreTrash(runId);\n\n      if (asJson) {\n        process.stdout.write(JSON.stringify({ ok: result != null, result }, null, 2) + \"\\n\");\n        if (result == null) exitWith(ExitCode.ERROR);\n        return;\n      }\n\n      if (result == null) {\n        console.log(run === \"latest\" ? \"Nothing in trash to restore.\" : `No trash run \"${run}\".`);\n        exitWith(ExitCode.ERROR);\n        return;\n      }\n\n      if (result.restored.length > 0) {\n        console.log(\n          `Restored ${result.restored.length} skill${result.restored.length === 1 ? \"\" : \"s\"}: ${result.restored.join(\", \")}`,\n        );\n      } else {\n        console.log(\"Nothing restored \u2014 every item was already in place or missing.\");\n      }\n      for (const s of result.skipped) {\n        console.log(`  skipped ${s.slug} (${s.reason})`);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport {\n  status as statusCommand,\n  readState,\n  listPending,\n  activityState,\n  authStatus,\n  type StatusEntry,\n} from \"@skillet/core\";\nimport { ALL_ADAPTERS, countUserSkills } from \"../cli-context.js\";\nimport { detectAdapterNames } from \"../adapter-tiers.js\";\nimport { webBaseUrl } from \"../cli-command-tier.js\";\nimport { dim, cyan, green, yellow, bold, ok } from \"../cli-colors.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\n\nasync function runScanReport(opts: { json?: boolean }): Promise<void> {\n  const report = await statusCommand();\n  if (opts.json === true) {\n    process.stdout.write(JSON.stringify(report, null, 2) + \"\\n\");\n    if (report.hasQuarantined) {\n      exitWith(ExitCode.ERROR);\n    }\n    return;\n  }\n  if (report.total === 0) {\n    console.log(\"Kit is empty.\");\n    console.log(dim(\"  Add skills at \") + cyan(webBaseUrl()));\n    console.log(dim(\"  Or import local skills with `skillet import <path>`\"));\n    return;\n  }\n  const summary = [\n    `quarantined=${report.byBucket.quarantined}`,\n    `flagged=${report.byBucket.flagged}`,\n    `pending=${report.byBucket.pending}`,\n    `clean=${report.byBucket.clean}`,\n  ].join(\" \u00B7 \");\n  console.log(`${report.total} skill(s) \u2014 ${summary}\\n`);\n\n  const glyph = (e: StatusEntry): string => {\n    if (e.bucket === \"quarantined\") return \"\u26D4\";\n    if (e.bucket === \"flagged\") return yellow(\"\u26A0 \");\n    if (e.bucket === \"pending\") return dim(\"\u2026\");\n    return green(\"\u2713\");\n  };\n\n  for (const entry of report.entries) {\n    const tail =\n      entry.bucket === \"clean\"\n        ? \"\"\n        : entry.bucket === \"pending\"\n          ? \"  (scan in progress)\"\n          : `  (${entry.totalFindings} finding${entry.totalFindings === 1 ? \"\" : \"s\"}, top=${entry.topConfidence})`;\n    console.log(`  ${glyph(entry)} ${entry.slug}${tail}`);\n  }\n\n  if (report.hasQuarantined) {\n    console.log(\n      \"\\nQuarantined entries require `--allow-quarantined` (CI) or interactive consent before they apply.\",\n    );\n    exitWith(ExitCode.ERROR);\n  }\n}\n\n/** One screen: who, how many skills, how many agents, what's waiting. */\nasync function runOverview(): Promise<void> {\n  // All five reads are independent \u2014 one round of concurrency instead of a\n  // serial chain (listPending includes a network read; detect() hits disk).\n  const [state, auth, waiting, agents, stats] = await Promise.all([\n    readState(),\n    authStatus().catch(() => null),\n    listPending(ALL_ADAPTERS).then(\n      (r) => r.pending.length,\n      () => 0, // pending count is a nicety here, never a blocker\n    ),\n    detectAdapterNames(ALL_ADAPTERS),\n    activityState().catch(() => null),\n  ]);\n  const skills = countUserSkills(state);\n\n  const handle = auth?.whoami?.handle ?? auth?.identity?.handle ?? null;\n  console.log(\"\");\n  if (handle) {\n    console.log(`  ${ok(`Connected as @${handle}`)}`);\n  } else {\n    console.log(`  Not connected. ${dim(\"Pair with\")} ${cyan(bold(\"skillet connect <code>\"))}`);\n  }\n  console.log(`  ${bold(String(skills))} skill${skills === 1 ? \"\" : \"s\"} in your kit \u00B7 ${agents.length} agent${agents.length === 1 ? \"\" : \"s\"} on this machine`);\n  if (waiting > 0) {\n    console.log(`  ${waiting} skill${waiting === 1 ? \"\" : \"s\"} waiting for review ${dim(\"\u00B7 skillet pending\")}`);\n  }\n  if (stats) {\n    // Unpaired machines cannot sync stats regardless of the flag \u2014 say what\n    // is actually happening, not what the setting would do with an account.\n    const syncing = stats.recording && handle !== null;\n    console.log(`  Skill stats: ${syncing ? \"syncing to your account\" : \"on this machine only\"}`);\n  }\n  console.log(\"\");\n}\n\nfunction attachScanOptions(cmd: Command): void {\n  cmd.option(\"--json\", \"Emit a machine-readable scan report\");\n}\n\nexport function registerStatusCommand(program: Command): void {\n  const scanCmd = program\n    .command(\"scan\")\n    .description(\"Check your kit for unsafe skills\");\n\n  attachScanOptions(scanCmd);\n  scanCmd.action(async (opts: { json?: boolean }) => {\n    await runScanReport(opts);\n  });\n\n  // `status` is two commands in one, split by surface:\n  //   - `--json` keeps the harm-scan report shape AND its non-zero exit on\n  //     quarantined entries \u2014 the desktop tray parses exactly this\n  //     (src-tauri lib.rs scan_status), so the shape is a compat contract.\n  //   - the human path is the at-a-glance overview a person means by \"status\".\n  // Hidden from help: `doctor` is the human diagnostic. Still registered and\n  // callable so scripts and fall-through paths keep working.\n  const statusCmd = program\n    .command(\"status\", { hidden: true })\n    .description(\"Your connection, kit, agents, and anything waiting\");\n\n  attachScanOptions(statusCmd);\n  statusCmd.action(async (opts: { json?: boolean }) => {\n    if (opts.json === true) {\n      await runScanReport(opts);\n      return;\n    }\n    await runOverview();\n  });\n}\n", "import type { Command } from \"commander\";\nimport { resolve } from \"node:path\";\nimport { sweepOrphans } from \"@skillet/core\";\n\nexport function registerSweepCommand(program: Command): void {\n  program\n    .command(\"sweep <path>\")\n    .description(\"Move a removed agent's skill folders to the trash (restorable)\")\n    .option(\"--json\", \"Emit machine-readable output\")\n    .action(async (path: string, opts: { json?: boolean }) => {\n      const res = await sweepOrphans(resolve(path));\n      if (opts.json === true) {\n        process.stdout.write(JSON.stringify({ ok: true, ...res }, null, 2) + \"\\n\");\n        return;\n      }\n      if (res.trashed.length === 0) {\n        console.log(`No Skillet-managed folders found under ${path}.`);\n        return;\n      }\n      console.log(\n        `Moved ${res.trashed.length} Skillet folder(s) to trash: ${res.trashed.join(\", \")}`,\n      );\n      console.log(`  \u2192 ${res.trashDir} (restore with \\`skillet restore\\`)`);\n    });\n}\n", "import type { Command } from 'commander'\nimport { join } from 'node:path'\nimport {\n  readState,\n  sync,\n  kitSyncedSkillEntries,\n  isSkilletSystemSkill,\n  resolveDeviceScopedManifest,\n  RegistryError,\n  acceptAuthorKeyRotation,\n  fetchServedAuthorKey,\n  RegistryClient,\n} from '@skillet/core'\nimport { installRouteHooksWithConsent } from '../route-hooks-consent.js'\nimport { ExitCode, exitWith } from '../exit-codes.js'\nimport { requirePaired } from '../auth-required.js'\nimport { writeJsonError } from '../json-output.js'\nimport type { SyncDryRunPlan } from '../dry-run.js'\nimport { renderAdapterLine, REGISTRY_DEFAULT, BASELINE_READER_ADAPTERS } from '../cli-context.js'\nimport { resolveSyncAdapters } from '../adapter-tiers.js'\nimport { resolveBundledRouteSkillDir } from '../bundled-route-path.js'\nimport { inlinedRouteSkillMd } from '../bundled-route-content.js'\nimport { webBaseUrl } from '../cli-command-tier.js'\nimport { ok, fail, dim, yellow } from '../cli-colors.js'\nimport { renderSyncKitPlan } from '../kit-list-format.js'\nimport { printRenderedError } from '../render-error.js'\nimport { printPendingReviewSummary } from '../pending-review-summary.js'\nimport {\n  buildSyncKitsJson,\n  kitGroupsForDevice,\n  skipReasonsFromSyncResult,\n  type SyncKitGroupJson,\n} from '../sync-kit-plan.js'\nimport {\n  authorKeyMismatchHandles,\n  renderFailedPullLine,\n} from '../sync-author-key-hint.js'\nimport { confirm } from './import-cmd.js'\n\nasync function buildSyncDryRunPlan(cwd: string): Promise<SyncDryRunPlan> {\n  const state = await readState()\n  const manifest = await resolveDeviceScopedManifest({ registryUrl: REGISTRY_DEFAULT })\n  const listOpts = manifest.fetched && manifest.items !== undefined\n    ? manifest.items\n    : undefined\n  const groups = kitGroupsForDevice(state, listOpts)\n  const kits = buildSyncKitsJson(groups, new Map(), 'planned')\n  const synced = kitSyncedSkillEntries(state)\n  const { adapters, baselineNames } = await resolveSyncAdapters(cwd)\n  const baselineSet = new Set(baselineNames)\n  const baselineAdapters = baselineNames\n  const detectedAdditionalAdapters: string[] = []\n  for (const adapter of adapters) {\n    if (!baselineSet.has(adapter.name)) {\n      detectedAdditionalAdapters.push(adapter.name)\n    }\n  }\n  return {\n    dryRun: true,\n    cwd,\n    skillCount: synced.length,\n    syncedSkillSlugs: synced.map((s) => s.slug),\n    kits,\n    baselineAdapters,\n    detectedAdditionalAdapters,\n    detectedAdapters: adapters.map((a) => a.name),\n    lockPath: join(cwd, 'skillet.lock'),\n  }\n}\n\nasync function loadDeviceKitGroups(state: Awaited<ReturnType<typeof readState>>) {\n  const manifest = await resolveDeviceScopedManifest({ registryUrl: REGISTRY_DEFAULT })\n  const items = manifest.fetched && manifest.items !== undefined ? manifest.items : undefined\n  return {\n    groups: kitGroupsForDevice(state, items),\n    offline: !manifest.fetched,\n  }\n}\n\nexport function registerSyncCommand(program: Command): void {\n  program\n    .command('sync')\n    .description('Put your kit into every agent on this machine')\n    .option('--cwd <dir>', 'Working directory for skillet.lock', process.cwd())\n    .option('--json', 'Emit a machine-readable result report')\n    .option(\n      '--dry-run',\n      'Preview sync targets and detected agents without writing anything',\n    )\n    .option(\n      '--allow-quarantined',\n      'Pre-approve quarantined versions in runs without a terminal',\n    )\n    .option('--check', 'Detect registry changes without writing to agents')\n    .option('--token <token>', 'Bearer token (session, device, or env override)')\n    .action(\n      async (opts: {\n        cwd: string\n        json?: boolean\n        dryRun?: boolean\n        allowQuarantined?: boolean\n        check?: boolean\n        token?: string\n      }) => {\n        const asJson = opts.json === true\n\n        if (opts.dryRun) {\n          const plan = await buildSyncDryRunPlan(opts.cwd)\n          if (asJson) {\n            process.stdout.write(JSON.stringify({ ok: true, data: plan }, null, 2) + '\\n')\n          } else {\n            console.log('Dry run \u2014 no files written.\\n')\n            const state = await readState()\n            const { groups, offline } = await loadDeviceKitGroups(state)\n            console.log(\n              renderSyncKitPlan(groups, {\n                header: 'Kits on this device (dry run)',\n                offline,\n              }),\n            )\n            console.log(\n              `\\n  universal (always): ${plan.baselineAdapters.join(', ') || '(none)'}`,\n            )\n            console.log(\n              `  additional (detected): ${plan.detectedAdditionalAdapters.length > 0 ? plan.detectedAdditionalAdapters.join(', ') : '(none)'}`,\n            )\n            console.log(`  lock would write: ${plan.lockPath}`)\n          }\n          return\n        }\n\n        try {\n          // Pairing is required \u2014 unpaired sync does no local materialization.\n          // requirePaired writes the auth_required JSON envelope to STDOUT in\n          // --json mode (sync --json, sync --check --json): the desktop parses\n          // stdout and classifies non-JSON as an approval block and stderr-only\n          // failure as offline, so this must stay machine-readable.\n          const bearer = await requirePaired(opts.token, { json: asJson })\n\n          const { adapters: syncAdapters, baselineNames } = await resolveSyncAdapters(opts.cwd)\n\n          // Detected baseline-reader runtimes (opencode) \u2014 they read the shared\n          // `.agents/skills` baseline, so sync attributes availability to them\n          // without materializing a second copy.\n          const readerRuntimes = (\n            await Promise.all(\n              BASELINE_READER_ADAPTERS.map(async (a) =>\n                (await a.detect().catch(() => false)) ? a.name : null,\n              ),\n            )\n          ).filter((n): n is string => n !== null)\n\n          const syncOpts = {\n            allowQuarantined: opts.allowQuarantined === true,\n            token: bearer.token || undefined,\n            quietSkipLines: !asJson,\n            baselineAdapterNames: baselineNames,\n            readerRuntimes,\n            checkOnly: opts.check === true,\n            registryUrl: REGISTRY_DEFAULT,\n            bundledRouteSkillDir: resolveBundledRouteSkillDir(),\n            bundledRouteSkillMd: inlinedRouteSkillMd(),\n          }\n\n          let result = await sync(opts.cwd, syncAdapters, syncOpts)\n\n          if (\n            !asJson &&\n            opts.check !== true &&\n            process.stdout.isTTY === true &&\n            bearer.token\n          ) {\n            const mismatchHandles = authorKeyMismatchHandles([\n              ...result.unionPull,\n              ...result.pull,\n            ])\n            let repinned = false\n            const client = new RegistryClient({\n              baseUrl: REGISTRY_DEFAULT,\n              token: bearer.token,\n            })\n            for (const handle of mismatchHandles) {\n              const accepted = await confirm(\n                `Author signing key changed for @${handle}. Accept the registry key and retry sync?`,\n              )\n              if (!accepted) continue\n              try {\n                const served = await fetchServedAuthorKey(handle, client)\n                await acceptAuthorKeyRotation(handle, {\n                  key_id: served.key_id,\n                  pub: served.pub,\n                })\n                repinned = true\n              } catch (err) {\n                console.error(fail(`Could not re-pin @${handle}: ${(err as Error).message}`))\n              }\n            }\n            if (repinned) {\n              result = await sync(opts.cwd, syncAdapters, syncOpts)\n            }\n          }\n\n          if (opts.check === true) {\n            const unionFailed = result.unionPull.filter((o) => o.status === 'failed')\n            const pullFailed = result.pull.filter((o) => o.status === 'failed')\n            const checkOk = unionFailed.length === 0 && pullFailed.length === 0\n            if (asJson) {\n              process.stdout.write(\n                JSON.stringify(\n                  {\n                    ok: checkOk,\n                    changed: result.changed === true,\n                    unionPull: result.unionPull,\n                    pull: result.pull,\n                    failed: result.failed,\n                  },\n                  null,\n                  2,\n                ) + '\\n',\n              )\n            } else if (result.changed) {\n              console.log('Changes detected. Apply them with `skillet sync`')\n            } else {\n              console.log(ok('Up to date.'))\n            }\n            if (!checkOk) exitWith(ExitCode.ERROR)\n            return\n          }\n\n          const stateAfter = await readState()\n          // Exclude the bundled `/skillet` router \u2014 it's Skillet's own plumbing,\n          // never a user-visible skill (same as `skillet list`).\n          const allSkills = Object.values(stateAfter.skills).filter(\n            (e) => !isSkilletSystemSkill(e),\n          ).length\n          const unionPulled = result.unionPull.filter((o) => o.status === 'updated').length\n          const unionFailed = result.unionPull.filter((o) => o.status === 'failed')\n\n          // Account truly has no kit skills \u2014 not \"pull failed for skills list already showed\".\n          // (Past the pairing gate a bearer token is always present.)\n          if (allSkills === 0 && result.unionPull.length === 0) {\n            if (asJson) {\n              process.stdout.write(\n                JSON.stringify(\n                  {\n                    ok: true,\n                    kitEmpty: true,\n                    accountLinked: true,\n                    adapters: result.adapters,\n                    lockPath: result.lockPath,\n                    unionPull: result.unionPull,\n                  },\n                  null,\n                  2,\n                ) + '\\n',\n              )\n            } else {\n              console.log(\n                'No skills in your account kits yet. Publish on skillet.md, or import local skills with `skillet import <path>`',\n              )\n            }\n            return\n          }\n\n          const syncedSkills = kitSyncedSkillEntries(stateAfter).length\n          const localOnly = allSkills - syncedSkills\n          const kitRefs = new Set(\n            kitSyncedSkillEntries(stateAfter)\n              .map((s) => s.sourceKit)\n              .filter((k): k is string => typeof k === 'string' && k.length > 0),\n          )\n\n          const { groups: kitGroups, offline: kitGroupsOffline } = await loadDeviceKitGroups(\n            stateAfter,\n          )\n          const skipReasons = skipReasonsFromSyncResult(result)\n          const kitsJson: SyncKitGroupJson[] = buildSyncKitsJson(kitGroups, skipReasons, 'synced')\n\n          if (asJson) {\n            // Hooks still install on the JSON surface (the desktop tray syncs\n            // this way); the consent question itself is TTY-only and deferred.\n            await installRouteHooksWithConsent(result, { json: true })\n            const failed = result.adapters.filter((a) => a.status === 'failed')\n            process.stdout.write(\n              JSON.stringify(\n                {\n                  ok: failed.length === 0 && unionFailed.length === 0,\n                  lockPath: result.lockPath,\n                  skillCount: syncedSkills,\n                  libraryCount: allSkills,\n                  localOnlyCount: localOnly,\n                  kitCount: kitRefs.size,\n                  kits: kitsJson,\n                  unionPull: result.unionPull,\n                  adapters: result.adapters,\n                  materialized: result.materialized,\n                  pruned: result.pruned,\n                  trashDir: result.trashDir,\n                  customized: result.customized,\n                  localized: result.localized,\n                  pendingReview: result.pendingReview,\n                },\n                null,\n                2,\n              ) + '\\n',\n            )\n            if (failed.length > 0 || unionFailed.length > 0) {\n              exitWith(ExitCode.ERROR)\n            }\n            return\n          }\n\n          if (result.unionPull.length > 0) {\n            const parts: string[] = []\n            if (unionPulled > 0) parts.push(`${unionPulled} new/updated from registry`)\n            const skipped = result.unionPull.filter((o) => o.status === 'unchanged').length\n            if (skipped > 0) parts.push(`${skipped} unchanged`)\n            if (unionFailed.length > 0) parts.push(`${unionFailed.length} failed`)\n            console.log(\n              `Registry kits: ${parts.join(', ')}${kitRefs.size > 0 ? ` \u00B7 ${kitRefs.size} kit(s)` : ''}\\n`,\n            )\n            for (const o of unionFailed) {\n              for (const line of renderFailedPullLine(o)) {\n                console.log(line)\n              }\n            }\n          }\n\n          const kitPlan = renderSyncKitPlan(kitGroups, {\n            skipReasons,\n            offline: kitGroupsOffline,\n          })\n          if (kitPlan.length > 0) {\n            console.log(`${kitPlan}\\n`)\n          }\n\n          for (const notice of result.notices) {\n            console.log(`\u26A0  ${notice}`)\n          }\n          printPendingReviewSummary(result.pendingReview)\n          // Customized skills with a held author update \u2014 a quiet, non-blocking\n          // signal (R5), one line each, pointing at the reconcile surface. No\n          // deadline, nothing reverted; `skillet edits` drives take/keep/diff.\n          for (const c of result.customized) {\n            if (!c.hasUpdate) continue\n            console.log(\n              `Your version of \"${c.slug}\" has an author update waiting. Reconcile with \\`skillet edits\\``,\n            )\n          }\n          // A customized skill that left the manifest (unsubscribed / kit\n          // removed) is kept as a plain local skill, not trashed (KTD7) \u2014 say\n          // so quietly, same one-line style as the held-update notice above.\n          for (const l of result.localized) {\n            console.log(`Kept \"${l.slug}\" as your own local skill (unsubscribed).`)\n          }\n          if (result.pruned.length > 0 && result.trashDir) {\n            const names = result.pruned.map((p) => p.slug).join(', ')\n            console.log(`Removed ${result.pruned.length} skill(s) no longer in your kits: ${names}`)\n            console.log(\n              `  \u2192 moved to ${result.trashDir} (restore by moving the folders back, or delete to reclaim space)\\n`,\n            )\n          }\n\n          console.log('Agents:')\n          for (const r of result.adapters) {\n            console.log(renderAdapterLine(r))\n            for (const w of r.warnings) {\n              console.log(`    ${yellow('\u26A0')}  ${w}`)\n            }\n          }\n\n          const detectedCount = result.adapters.filter(\n            (a) => a.status !== 'skipped-not-detected',\n          ).length\n          const failedCount = result.adapters.filter((a) => a.status === 'failed').length\n\n          console.log(dim(`\\nLock written: ${result.lockPath}`))\n          const syncLine =\n            `Synced ${syncedSkills} kit skill(s) into ${detectedCount}/${result.adapters.length} agent(s)` +\n            (kitRefs.size > 0 ? ` \u00B7 ${kitRefs.size} kit(s)` : '')\n          console.log(\n            failedCount > 0\n              ? fail(`${syncLine}. ${failedCount} agent(s) failed (see above)`)\n              : ok(syncLine),\n          )\n          if (localOnly > 0) {\n            console.log(\n              `\\n${localOnly} local skill(s) in your library were not synced (kit-exclusive).`,\n            )\n          }\n\n          // U8: updates summary \u2014 how many incoming versions were applied this run.\n          const appliedUpdates = [...result.pull, ...result.unionPull].filter(\n            (o) => o.status === 'updated',\n          ).length\n          if (appliedUpdates > 0) {\n            console.log(`Updates: ${appliedUpdates} applied this sync.`)\n          }\n\n          // Capture hint: local skills not yet on your profile. A one-liner, not a\n          // prompt \u2014 points at the existing explicit, private-by-default publish.\n          if (bearer.kind === 'session') {\n            const capturable = Object.values(stateAfter.skills).filter(\n              (s) => s.source === 'local' && !s.owner,\n            ).length\n            if (capturable > 0) {\n              console.log(\n                `\\n${capturable} local skill(s) aren't on your profile yet. Publish them (private by default) at ${webBaseUrl()}/skills/new`,\n              )\n            }\n          }\n\n          if (detectedCount === 0) {\n            console.log(`\\n${yellow('\u26A0')}  No agents received skills. Check errors above.`)\n          }\n\n          // Hooks + the one-time stats-consent question come LAST (shared with\n          // the pairing auto-sync): the sync outcome reads first and the run\n          // ends on the question instead of burying it mid-output.\n          await installRouteHooksWithConsent(result, { json: asJson })\n\n          if (failedCount > 0 || unionFailed.length > 0) {\n            exitWith(ExitCode.ERROR)\n          }\n        } catch (err) {\n          if (asJson) {\n            // Narrow to RegistryError so incidental `.code` fields (e.g. a raw\n            // fs ENOENT) never leak into the structured envelope contract.\n            const code = err instanceof RegistryError ? err.code : undefined\n            writeJsonError((err as Error).message, code ? { code } : {})\n          } else {\n            printRenderedError(err as Error, (what) => fail(`Sync failed: ${what}`))\n            exitWith(ExitCode.ERROR)\n          }\n        }\n      },\n    )\n}\n", "import type {\n  GroupSkillsByKitOptions,\n  KitSkillGroup,\n  KitState,\n  SyncResult,\n} from '@skillet/core';\nimport { groupSkillsByKit } from '@skillet/core';\n\nexport type SyncKitSkillStatus = 'synced' | 'skipped' | 'planned';\n\nexport interface SyncKitSkillJson {\n  slug: string;\n  status: SyncKitSkillStatus;\n  reason?: string;\n}\n\nexport interface SyncKitGroupJson {\n  kitRef: string;\n  skills: SyncKitSkillJson[];\n}\n\n/** Kit groups for this device (manifest-scoped when items are provided). */\nexport function kitGroupsForDevice(\n  state: KitState,\n  manifestItems: GroupSkillsByKitOptions['manifestItems'],\n): KitSkillGroup[] {\n  const grouped = groupSkillsByKit(\n    state,\n    manifestItems !== undefined ? { manifestItems } : undefined,\n  );\n  return grouped.filter((g): g is KitSkillGroup & { kitRef: string } => g.kitRef !== null);\n}\n\nexport function skipReasonsFromSyncResult(\n  result: Pick<SyncResult, 'failed' | 'unionPull'>,\n): Map<string, string> {\n  const map = new Map<string, string>();\n  for (const f of result.failed) {\n    map.set(f.slug, f.reason);\n  }\n  for (const o of result.unionPull) {\n    if (o.status === 'failed') {\n      map.set(o.slug, o.reason ?? 'union_pull_failed');\n    }\n  }\n  return map;\n}\n\nexport function buildSyncKitsJson(\n  groups: KitSkillGroup[],\n  skipReasons: Map<string, string>,\n  mode: 'synced' | 'planned',\n): SyncKitGroupJson[] {\n  return groups\n    .filter((g): g is KitSkillGroup & { kitRef: string } => g.kitRef !== null)\n    .map((g) => ({\n      kitRef: g.kitRef,\n      skills: g.skills.map((skill) => {\n        const reason = skipReasons.get(skill.slug);\n        if (reason) {\n          return { slug: skill.slug, status: 'skipped' as const, reason };\n        }\n        return {\n          slug: skill.slug,\n          status: mode === 'planned' ? ('planned' as const) : ('synced' as const),\n        };\n      }),\n    }));\n}\n", "import type { PullOutcome } from '@skillet/core';\nimport { formatAuthorKeyMismatchHint, parseAuthorKeyMismatch } from '@skillet/core';\nimport { renderErrorLines } from './render-error.js';\n\n/** Render a failed pull line plus optional author-key recovery hints. */\nexport function renderFailedPullLine(outcome: PullOutcome): string[] {\n  const [what, ...next] = renderErrorLines(outcome.reason ?? 'pull_failed');\n  const lines = [`  \u2717 ${outcome.slug}: ${what}`, ...next.map((n) => `  ${n}`)];\n  const mismatch = outcome.authorKeyMismatch ?? parseAuthorKeyMismatch(outcome.reason ?? '');\n  if (mismatch) {\n    lines.push(...formatAuthorKeyMismatchHint(mismatch));\n  }\n  return lines;\n}\n\n/** Unique author handles that failed sync due to key rotation. */\nexport function authorKeyMismatchHandles(outcomes: PullOutcome[]): string[] {\n  const handles = new Set<string>();\n  for (const outcome of outcomes) {\n    const mismatch = outcome.authorKeyMismatch ?? parseAuthorKeyMismatch(outcome.reason ?? '');\n    if (mismatch) handles.add(mismatch.handle);\n  }\n  return [...handles];\n}\n", "import type { Command } from 'commander'\nimport { homedir } from 'node:os'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { runtimeLabel } from '@skillet/core'\nimport {\n  ADDITIONAL_ADAPTERS,\n  BASELINE_GLOBAL_ADAPTERS,\n  BASELINE_READER_ADAPTERS,\n} from '../cli-context.js'\n\n// Agents that read the global ~/.agents/skills baseline rather than their own dir\n// (Cursor's per-project .cursor/rules adapter is legacy; it loads the global\n// baseline too). Point the tray's folder link at where skills actually live.\nconst GLOBAL_AGENTS_SKILLS = new Set(['cursor'])\n\n/**\n * `skillet runtimes --json` \u2014 list the agent runtimes detected on THIS machine and\n * where their skills materialize. Pure LOCAL detection (each adapter's `detect()`),\n * no registry call, no sync \u2014 so it succeeds even when the machine is offline,\n * disconnected, or the sync is failing on a bad skill.\n *\n * Covers BOTH the baseline global adapters (Codex \u2192 ~/.agents/skills) and the\n * additional detected runtimes (Claude Code, Cursor, \u2026). The desktop tray reads\n * this for the \"your agents\" facepile + folder list, decoupled from `sync` so a\n * registry hiccup can never blank out which agents you have.\n */\nexport function registerRuntimesCommand(program: Command): void {\n  // `agents` is the user-facing name; `runtimes` stays as a hidden alias with\n  // byte-identical output because the desktop tray shells out to\n  // `skillet runtimes --json` (src-tauri lib.rs) \u2014 the JSON keys, including\n  // the `runtimes` array name, are a compat contract, not vocabulary.\n  const action = async (opts: { json?: boolean }) => {\n      const agentsSkills = join(homedir(), '.agents', 'skills')\n      const seen = new Set<string>()\n      const runtimes: Array<{ name: string; label: string; targetDir: string }> = []\n      // Baseline first (Codex owns the universal dir), then additional runtimes.\n      for (const adapter of [...BASELINE_GLOBAL_ADAPTERS, ...ADDITIONAL_ADAPTERS]) {\n        if (seen.has(adapter.name)) continue\n        try {\n          if (await adapter.detect()) {\n            seen.add(adapter.name)\n            // The codex adapter also claims the universal ~/.agents dir it\n            // owns, so its detect() can't prove Codex itself is installed.\n            // Label it Codex only on direct evidence (~/.codex), else keep\n            // the honest \"Universal\". Every surface downstream (tray facepile,\n            // onboarding chips) inherits this rule.\n            const label =\n              adapter.name === 'codex' && existsSync(join(homedir(), '.codex'))\n                ? 'Codex'\n                : runtimeLabel(adapter.name)\n            runtimes.push({\n              name: adapter.name,\n              label,\n              targetDir: GLOBAL_AGENTS_SKILLS.has(adapter.name)\n                ? agentsSkills\n                : adapter.targetDir,\n            })\n          }\n        } catch {\n          // Non-fatal \u2014 skip adapters whose detect() throws.\n        }\n      }\n      // Baseline-reader agents (opencode) read the universal ~/.agents/skills\n      // dir instead of materializing their own \u2014 surface them as detected\n      // runtimes pointing at that shared dir, without adding them to the\n      // materializing set. Their detect() is agent-specific (~/.config/opencode).\n      for (const adapter of BASELINE_READER_ADAPTERS) {\n        if (seen.has(adapter.name)) continue\n        try {\n          if (await adapter.detect()) {\n            seen.add(adapter.name)\n            runtimes.push({\n              name: adapter.name,\n              label: runtimeLabel(adapter.name),\n              targetDir: agentsSkills,\n            })\n          }\n        } catch {\n          // Non-fatal \u2014 skip adapters whose detect() throws.\n        }\n      }\n      if (opts.json === true) {\n        process.stdout.write(JSON.stringify({ ok: true, runtimes }, null, 2) + '\\n')\n        return\n      }\n      if (runtimes.length === 0) {\n        console.log('No agents detected on this machine.')\n        return\n      }\n      for (const r of runtimes) {\n        console.log(`${r.label}  ${r.targetDir}`)\n      }\n  }\n\n  program\n    .command('agents')\n    .description('List the agents on this machine and where their skills live')\n    .option('--json', 'Emit a machine-readable list of detected agents')\n    .action(action)\n\n  program\n    .command('runtimes', { hidden: true })\n    .description('Hidden alias of `agents` (desktop tray compat)')\n    .option('--json', 'Emit a machine-readable list of detected agents')\n    .action(action)\n}\n", "import type { Command } from \"commander\";\nimport { REGISTRY_API, listRouteManifest } from \"@skillet/core\";\nimport { CLI_VERSION, resolveRegistryUrl } from \"../cli-context.js\";\nimport { webBaseUrl } from \"../cli-command-tier.js\";\nimport { stripControlChars } from \"../sanitize-output.js\";\nimport { writeJsonOk, writeJsonError } from \"../json-output.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { bold, cyan, dim } from \"../cli-colors.js\";\n\n/**\n * `skillet search <keyword...>` \u2014 public, anonymous registry search.\n *\n * The router's registry fall-through (@skillet/route) calls this on a whiff to\n * turn \"no local skill fits\" into named, installable suggestions. It is also a\n * standalone command: a person can search the library from the terminal.\n *\n * Transport is a plain `fetch`, NOT the RegistryClient \u2014 the client attaches\n * `x-skillet-machine-id` to every request, and search keywords must stay\n * unlinked from device identity. The registry endpoint is public and needs no\n * auth. The only headers sent are the client version and, for router-driven\n * calls, a fixed content-free source marker.\n */\n\n/** Hard caps. One positional = one literal query = one request. */\nexport const MAX_QUERIES = 3;\nexport const MAX_KEYWORD_LEN = 64;\n\n/** One merged, ranked suggestion the router can render without a second call. */\nexport interface SearchResult {\n  /** Exact `@author/slug` \u2014 usable verbatim as the `skillet add` argument. */\n  ref: string;\n  description: string | null;\n  install_count: number;\n  /** Highest per-query tier score this ref earned (within-query tiebreak only). */\n  score: number;\n  category: string | null;\n  /** Absolute skill URL, so a suggestion is clickable. */\n  url: string;\n  /** True when the ref is already in the local kit \u2014 the router filters these. */\n  installed: boolean;\n}\n\nexport interface SearchOutcome {\n  results: SearchResult[];\n  /** Queries that rejected or returned non-2xx. */\n  failedQueries: number;\n  /** The exact queries actually sent (post-sanitization, empties dropped). */\n  sentQueries: string[];\n}\n\ninterface RegistrySkillRow {\n  author?: unknown;\n  slug?: unknown;\n  description?: unknown;\n  install_count?: unknown;\n  score?: unknown;\n  category?: unknown;\n}\n\ninterface SearchDeps {\n  fetchImpl: typeof fetch;\n  registryUrl: string;\n  webUrl: string;\n  /** Local-kit refs, lowercased, for a case-insensitive installed check. */\n  installedRefs: Set<string>;\n  /** Fixed marker slug (e.g. `route-skill`); sent on the first request only. */\n  source?: string;\n  /** Per-request `limit` forwarded to the registry (registry clamps 1..25). */\n  limit?: number;\n}\n\n/**\n * Sanitize one keyword before it leaves the machine. Strips terminal control\n * chars, collapses whitespace, trims, and caps length \u2014 a mechanical backstop\n * independent of whatever composed the keyword (the router's distillation step\n * is prompt-level; this is not). Returns null when nothing survives.\n */\nexport function sanitizeKeyword(raw: string): string | null {\n  const cleaned = stripControlChars(raw).replace(/\\s+/g, \" \").trim().slice(0, MAX_KEYWORD_LEN);\n  return cleaned === \"\" ? null : cleaned;\n}\n\n/**\n * Sanitize each keyword, lowercase to the registry's own match form, drop\n * empties, and dedup (the registry lowercases `q`, so \"Blog\" and \"blog\" are the\n * same query \u2014 sending both fires a redundant request and double-counts the ref\n * in match-breadth ranking). The lowercased form is the canonical set of queries\n * a search sends.\n */\nexport function prepareQueries(raw: string[]): string[] {\n  const seen = new Set<string>();\n  const out: string[] = [];\n  for (const r of raw) {\n    const kw = sanitizeKeyword(r);\n    if (kw === null) continue;\n    const canonical = kw.toLowerCase();\n    if (seen.has(canonical)) continue;\n    seen.add(canonical);\n    out.push(canonical);\n  }\n  return out;\n}\n\ninterface Accum {\n  ref: string;\n  description: string | null;\n  install_count: number;\n  score: number;\n  category: string | null;\n  url: string;\n  matchCount: number;\n}\n\ninterface QueryResult {\n  failed: boolean;\n  rows: RegistrySkillRow[];\n}\n\nasync function fetchQuery(q: string, withSource: boolean, deps: SearchDeps): Promise<QueryResult> {\n  const params = new URLSearchParams({ q, types: \"skills\" });\n  if (deps.limit !== undefined) params.set(\"limit\", String(deps.limit));\n  const url = `${deps.registryUrl}${REGISTRY_API}/search?${params.toString()}`;\n  const headers: Record<string, string> = { \"x-skillet-client-version\": CLI_VERSION };\n  if (withSource && deps.source !== undefined) headers[\"x-skillet-search-source\"] = deps.source;\n\n  try {\n    const res = await deps.fetchImpl(url, { headers });\n    // A 429 (rate limit) or 5xx body has no `groups` key; reading it as zero\n    // results would masquerade as \"library has nothing\". Treat non-2xx as a\n    // failed query, distinct from an honest empty result.\n    if (!res.ok) return { failed: true, rows: [] };\n    const body = (await res.json()) as { groups?: { skills?: unknown } };\n    const rows = Array.isArray(body?.groups?.skills)\n      ? (body.groups!.skills as RegistrySkillRow[])\n      : [];\n    return { failed: false, rows };\n  } catch {\n    return { failed: true, rows: [] };\n  }\n}\n\n/**\n * Run each keyword as its own request (in parallel) and merge client-side. The\n * registry matches a query as ONE literal substring with no tokenization, so\n * distinct keywords are fanned out here; a single multi-word phrase is the\n * router's to avoid composing.\n *\n * Ranking: match breadth first (how many of the issued queries returned a ref),\n * then the registry's own relevance tier `score`, then `install_count`. Score\n * beats installs because within a query it encodes exact-name > slug >\n * description \u2014 the single-keyword case (the router's common path) would\n * otherwise let a popular tangential description-match bury an exact-name hit.\n *\n * The source marker rides only the FIRST request, so the registry counts one\n * event per search invocation (a demand signal), not one per fanned-out keyword.\n */\nexport async function runSearch(keywords: string[], deps: SearchDeps): Promise<SearchOutcome> {\n  const sentQueries = prepareQueries(keywords);\n\n  const perQuery = await Promise.all(\n    sentQueries.map((q, i) => fetchQuery(q, i === 0, deps)),\n  );\n\n  const byRef = new Map<string, Accum>();\n  let failedQueries = 0;\n\n  for (const result of perQuery) {\n    if (result.failed) {\n      failedQueries += 1;\n      continue;\n    }\n    for (const row of result.rows) {\n      const author = typeof row.author === \"string\" ? row.author : null;\n      const slug = typeof row.slug === \"string\" ? row.slug : null;\n      if (author === null || slug === null) continue;\n      // Author/slug are untrusted third-party content (R11), same as description\n      // and category \u2014 strip terminal escapes before they reach the ref/url that\n      // print to the terminal and become the copy-pasted `skillet add` argument.\n      const safeAuthor = stripControlChars(author);\n      const safeSlug = stripControlChars(slug);\n      const ref = `@${safeAuthor}/${safeSlug}`;\n      const score = typeof row.score === \"number\" ? row.score : 0;\n      const existing = byRef.get(ref);\n      if (existing) {\n        existing.matchCount += 1;\n        if (score > existing.score) existing.score = score;\n      } else {\n        byRef.set(ref, {\n          ref,\n          description:\n            typeof row.description === \"string\" ? stripControlChars(row.description) : null,\n          install_count: typeof row.install_count === \"number\" ? row.install_count : 0,\n          score,\n          category: typeof row.category === \"string\" ? stripControlChars(row.category) : null,\n          url: `${deps.webUrl}/${safeAuthor}/${safeSlug}`,\n          matchCount: 1,\n        });\n      }\n    }\n  }\n\n  const results: SearchResult[] = [...byRef.values()]\n    .sort(\n      (a, b) =>\n        b.matchCount - a.matchCount ||\n        b.score - a.score ||\n        b.install_count - a.install_count ||\n        a.ref.localeCompare(b.ref),\n    )\n    .map((a) => ({\n      ref: a.ref,\n      description: a.description,\n      install_count: a.install_count,\n      score: a.score,\n      category: a.category,\n      url: a.url,\n      // Case-insensitive: the local kit ref and the registry handle can differ\n      // in case; an exact-string miss would re-suggest an installed skill.\n      installed: deps.installedRefs.has(a.ref.toLowerCase()),\n    }));\n\n  return { results, failedQueries, sentQueries };\n}\n\nfunction renderHuman(outcome: SearchOutcome): void {\n  if (outcome.sentQueries.length === 0) {\n    console.log(\"No searchable keywords.\");\n    return;\n  }\n  if (outcome.results.length === 0) {\n    console.log(\"Nothing in the library matches.\");\n    if (outcome.failedQueries > 0) {\n      console.log(dim(`(${outcome.failedQueries} of ${outcome.sentQueries.length} queries failed)`));\n    }\n    return;\n  }\n  for (const r of outcome.results) {\n    const tag = r.installed ? dim(\" (in your kit)\") : \"\";\n    console.log(`${bold(r.ref)}${tag}`);\n    if (r.description) console.log(`  ${r.description}`);\n    console.log(dim(`  ${r.install_count} installs  ${cyan(r.url)}`));\n  }\n  if (outcome.failedQueries > 0) {\n    console.log(dim(`\\n${outcome.failedQueries} of ${outcome.sentQueries.length} queries failed.`));\n  }\n}\n\nexport function registerSearchCommand(program: Command): void {\n  program\n    .command(\"search\")\n    .argument(\"<keyword...>\", \"One or more capability keywords (each is one library search)\")\n    .description(\"Search the public skill library\")\n    .option(\"--json\", \"Emit machine-readable results\")\n    .option(\"--source <slug>\", \"Fixed source marker for router-driven calls\")\n    .option(\"--limit <n>\", \"Results per query (registry-clamped 1..25)\")\n    .action(\n      async (\n        keywords: string[],\n        opts: { json?: boolean; source?: string; limit?: string },\n      ) => {\n        const asJson = opts.json === true;\n        // Cap on the real query count (post-sanitize, post-dedup), so a trailing\n        // blank or a repeated keyword doesn't trip the limit on a valid search.\n        const queries = prepareQueries(keywords);\n        if (queries.length > MAX_QUERIES) {\n          if (asJson) {\n            writeJsonError(`At most ${MAX_QUERIES} keywords per search.`, {\n              code: \"too_many_queries\",\n              exitCode: ExitCode.USAGE,\n            });\n          }\n          console.error(`At most ${MAX_QUERIES} keywords per search.`);\n          exitWith(ExitCode.USAGE);\n        }\n\n        const limit = opts.limit !== undefined ? Number.parseInt(opts.limit, 10) : undefined;\n        const [registryUrl, manifest] = await Promise.all([\n          resolveRegistryUrl(),\n          listRouteManifest().catch(() => []),\n        ]);\n        // Lowercased for a case-insensitive installed check (see runSearch).\n        const installedRefs = new Set(manifest.map((e) => e.skillRef.toLowerCase()));\n\n        const outcome = await runSearch(keywords, {\n          fetchImpl: fetch,\n          registryUrl,\n          webUrl: webBaseUrl(),\n          installedRefs,\n          source: opts.source,\n          limit: Number.isFinite(limit) ? (limit as number) : undefined,\n        });\n\n        // Every query failed \u2192 this is an error, not an honest empty result.\n        if (outcome.sentQueries.length > 0 && outcome.failedQueries === outcome.sentQueries.length) {\n          if (asJson) {\n            writeJsonError(\"Every search query failed.\", {\n              code: \"search_failed\",\n              exitCode: ExitCode.ERROR,\n            });\n          }\n          console.error(\"Every search query failed; the registry may be unreachable.\");\n          exitWith(ExitCode.ERROR);\n        }\n\n        if (asJson) {\n          writeJsonOk({\n            results: outcome.results,\n            failedQueries: outcome.failedQueries,\n            queries: outcome.sentQueries,\n          });\n          return;\n        }\n        renderHuman(outcome);\n      },\n    );\n}\n", "import type { Command } from \"commander\";\nimport { readRouteHistory, usageViews, USAGE_DEADWEIGHT_DAYS } from \"@skillet/core\";\nimport { bold, dim } from \"../cli-colors.js\";\n\n/** Short relative last-used label (\"today\", \"3d ago\", \"5w ago\"). */\nfunction lastUsedLabel(iso: string): string {\n  const ms = Date.now() - Date.parse(iso);\n  if (!Number.isFinite(ms) || ms < 0) return \"\u2014\";\n  const days = Math.floor(ms / (24 * 60 * 60 * 1000));\n  if (days <= 0) return \"today\";\n  if (days === 1) return \"1d ago\";\n  if (days < 14) return `${days}d ago`;\n  if (days < 60) return `${Math.floor(days / 7)}w ago`;\n  return `${Math.floor(days / 30)}mo ago`;\n}\n\n/**\n * `skillet usage [--json]` \u2014 your routed skills from the LOCAL route history:\n * invocation count, last-used, the runtimes each fired on, and dead-weight prune\n * flags. Pure local read (no registry), so it works offline and for\n * anonymous users. The desktop/web surfaces consume the same `--json` shape.\n */\nexport function registerUsageCommand(program: Command): void {\n  program\n    .command(\"usage\")\n    .description(\"Skill stats on this machine (local only)\")\n    .option(\"--json\", \"Emit a machine-readable usage list\")\n    .action(async (opts: { json?: boolean }) => {\n      const history = await readRouteHistory();\n      const views = usageViews(history);\n\n      if (opts.json === true) {\n        process.stdout.write(JSON.stringify({ ok: true, skills: views }, null, 2) + \"\\n\");\n        return;\n      }\n\n      if (views.length === 0) {\n        console.log(\n          \"No /skillet routes recorded yet.\\n\" +\n            \"Use `/skillet <task>` in your agent, or run `skillet sync` to add skills.\",\n        );\n        return;\n      }\n\n      const refWidth = Math.max(6, ...views.map((v) => v.skillRef.length));\n      console.log(bold(`${\"SKILL\".padEnd(refWidth)}  USES  LAST       AGENTS`));\n      for (const v of views) {\n        const runtimes = Object.keys(v.runtimes).join(\", \") || \"\u2014\";\n        const flag = v.deadWeight ? dim(\"  (prune?)\") : \"\";\n        console.log(\n          `${v.skillRef.padEnd(refWidth)}  ${String(v.count).padStart(4)}  ${lastUsedLabel(\n            v.lastUsed,\n          ).padEnd(9)}  ${runtimes}${flag}`,\n        );\n      }\n\n      const dead = views.filter((v) => v.deadWeight).length;\n      if (dead > 0) {\n        console.log(\n          dim(`\\n${dead} skill(s) not routed in ${USAGE_DEADWEIGHT_DAYS}+ days \u2014 prune candidates.`),\n        );\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport {\n  setActivity,\n  activityState,\n  chooseRouteConsent,\n  loadRegistryBearer,\n  readRouteHistory,\n  exportRecord,\n  clearRouteHistory,\n  REGISTRY_API,\n} from \"@skillet/core\";\nimport { REGISTRY_DEFAULT } from \"../cli-context.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { fail } from \"../cli-colors.js\";\nimport { STATS_SYNC_ON_MSG, STATS_LOCAL_MSG } from \"../skill-stats-copy.js\";\n\n/** Push the private-mode flag to the registry. Best-effort \u2014 local config is the\n * source of truth for the client; the server flag just stops a stale client. */\nasync function syncServerFlag(privateMode: boolean): Promise<\"ok\" | \"no-token\" | \"failed\"> {\n  const bearer = await loadRegistryBearer();\n  if (!bearer.token) return \"no-token\";\n  try {\n    const base = (process.env[\"SKILLET_REGISTRY_URL\"] ?? REGISTRY_DEFAULT).replace(/\\/+$/, \"\");\n    const res = await fetch(`${base}${REGISTRY_API}/me/activity`, {\n      method: \"PUT\",\n      headers: { \"content-type\": \"application/json\", authorization: `Bearer ${bearer.token}` },\n      body: JSON.stringify({ private: privateMode }),\n    });\n    return res.ok ? \"ok\" : \"failed\";\n  } catch {\n    return \"failed\";\n  }\n}\n\nfunction serverNote(result: \"ok\" | \"no-token\" | \"failed\"): string {\n  if (result === \"failed\") return \" (set locally; couldn't reach the server to sync it)\";\n  return \"\";\n}\n\n/** Delete the caller's recorded activity (events + availability) on the server. */\nasync function clearServer(): Promise<{ events: number; availability: number } | \"no-token\" | \"failed\"> {\n  const bearer = await loadRegistryBearer();\n  if (!bearer.token) return \"no-token\";\n  try {\n    const base = (process.env[\"SKILLET_REGISTRY_URL\"] ?? REGISTRY_DEFAULT).replace(/\\/+$/, \"\");\n    const headers = { authorization: `Bearer ${bearer.token}` };\n    const [ev, re] = await Promise.all([\n      fetch(`${base}${REGISTRY_API}/me/events`, { method: \"DELETE\", headers }),\n      fetch(`${base}${REGISTRY_API}/me/availability`, { method: \"DELETE\", headers }),\n    ]);\n    if (!ev.ok || !re.ok) return \"failed\";\n    const events = ((await ev.json()) as { deleted?: number }).deleted ?? 0;\n    const availability = ((await re.json()) as { deleted?: number }).deleted ?? 0;\n    return { events, availability };\n  } catch {\n    return \"failed\";\n  }\n}\n\n/** The `activity status` view. Shared by the `status` subcommand and by bare\n *  `skillet activity`, which defaults to it \u2014 the noun alone shows the state,\n *  subcommands change it. */\nasync function runActivityStatus(opts: { json?: boolean }): Promise<void> {\n  const s = await activityState();\n  if (opts.json === true) {\n    process.stdout.write(JSON.stringify({ ok: true, ...s }, null, 2) + \"\\n\");\n    return;\n  }\n  console.log(`Activity recording: ${s.recording ? \"ON\" : \"OFF\"} (${s.source})`);\n  if (s.source === \"env\") {\n    console.log(\"  Set by the SKILLET_ACTIVITY env var (overrides config).\");\n  }\n  if (s.recording) {\n    console.log(\n      \"  Records sync stats (which skills, which agents) to power your devices,\\n\" +\n        \"  profile, and the public availability graph. `skillet activity off` to opt out.\",\n    );\n  } else {\n    console.log(\"  Not recording. `skillet activity on` to re-enable.\");\n  }\n  if (!s.routeConsentChosen) {\n    // The consent question only appears once there's real usage to sync:\n    // `skillet sync` asks \"you've used /skillet N times \u2014 sync those stats?\",\n    // so with zero routes it teaches the verb instead of asking. Say which\n    // one you're in so `status` doesn't promise a question that won't come.\n    const history = await readRouteHistory();\n    const uses = Object.values(history.skills).reduce((n, r) => n + r.count, 0);\n    console.log(\n      uses === 0\n        ? \"  /skillet route recording: choice not made yet \u2014 route events stay local.\\n\" +\n            \"  Use `/skillet <task>` at least once, then an interactive `skillet sync`\\n\" +\n            \"  will ask whether to sync those stats to your account.\"\n        : \"  /skillet route recording: choice not made yet \u2014 route events stay local\\n\" +\n            \"  until you choose on your next interactive `skillet sync`.\",\n    );\n  }\n}\n\nexport function registerActivityCommand(program: Command): void {\n  const activity = program\n    .command(\"activity\")\n    .description(\"What Skillet records: view, export, delete, or change it\");\n\n  // Bare `skillet activity` shows the status \u2014 same shape as `edits`/`pending`.\n  activity.action(async () => {\n    await runActivityStatus({});\n  });\n\n  activity\n    .command(\"status\")\n    .description(\"Show whether activity is recorded and what decides it\")\n    .option(\"--json\", \"Emit machine-readable state\")\n    .action(async (opts: { json?: boolean }) => {\n      await runActivityStatus(opts);\n    });\n\n  activity\n    .command(\"on\")\n    .description(\"Turn activity recording on\")\n    .action(async () => {\n      await setActivity(true);\n      const server = await syncServerFlag(false);\n      console.log(`Activity recording on.${serverNote(server)}`);\n    });\n\n  activity\n    .command(\"off\")\n    .description(\"Turn activity recording off (opt out)\")\n    .action(async () => {\n      await setActivity(false);\n      const server = await syncServerFlag(true);\n      console.log(`Activity recording off.${serverNote(server)}`);\n      console.log(\"Past activity is retained. `skillet activity clear` to delete it.\");\n    });\n\n  activity\n    .command(\"choose <where>\")\n    .description(\"Answer the skill-stats question: `sync` stats to your account, or keep them `local`\")\n    .option(\"--json\", \"Emit machine-readable result\")\n    .action(async (where: string, opts: { json?: boolean }) => {\n      // The one verb that marks the consent question ANSWERED (routeConsentChosen),\n      // unlike `on`/`off` which only flip the flag. The desktop tray's one-time\n      // ask card calls this with --json; the CLI first-run ask uses the same\n      // chooseRouteConsent underneath.\n      if (where !== \"sync\" && where !== \"local\") {\n        const msg = \"choose takes `sync` or `local`\";\n        if (opts.json === true) {\n          process.stdout.write(JSON.stringify({ ok: false, error: msg }) + \"\\n\");\n        } else {\n          console.error(fail(msg));\n        }\n        exitWith(ExitCode.USAGE);\n        return;\n      }\n      const record = where === \"sync\";\n      await chooseRouteConsent(record);\n      // Server flag parity with `on`/`off` (best-effort; local config is truth).\n      const server = await syncServerFlag(!record);\n      if (opts.json === true) {\n        const s = await activityState();\n        process.stdout.write(\n          JSON.stringify(\n            { ok: true, recording: s.recording, routeConsentChosen: s.routeConsentChosen },\n            null,\n            2,\n          ) + \"\\n\",\n        );\n        return;\n      }\n      console.log(`${record ? STATS_SYNC_ON_MSG : STATS_LOCAL_MSG}${serverNote(server)}`);\n    });\n\n  activity\n    .command(\"clear\")\n    .description(\"Delete your recorded activity: local history and server events\")\n    .action(async () => {\n      // Local first: this always succeeds and covers anonymous users, who have\n      // no server records to clear.\n      await clearRouteHistory();\n      console.log(\"Cleared local /skillet route history.\");\n\n      const res = await clearServer();\n      if (res === \"no-token\") {\n        console.log(\"Not signed in \u2014 nothing on the server to clear.\");\n        return;\n      }\n      if (res === \"failed\") {\n        console.log(\"Couldn't reach the server to clear your server-side activity. Try again.\");\n        return;\n      }\n      console.log(`Cleared ${res.events} server event(s) and ${res.availability} availability row(s).`);\n    });\n\n  activity\n    .command(\"export\")\n    .description(\"Export everything recorded about you (local route history + server activity)\")\n    .action(async () => {\n      // The full local store (skill refs, counts, timestamps, runtimes \u2014 all\n      // content-free) plus your server-side activity, so you can inspect exactly\n      // what Skillet holds about you.\n      const local = exportRecord(await readRouteHistory());\n      const server = await fetchServerActivity();\n      process.stdout.write(JSON.stringify({ ok: true, local, server }, null, 2) + \"\\n\");\n    });\n}\n\n/** Best-effort read of the caller's server-recorded activity for export. */\nasync function fetchServerActivity(): Promise<\n  { events: unknown; availability: unknown } | \"no-token\" | \"failed\"\n> {\n  const bearer = await loadRegistryBearer();\n  if (!bearer.token) return \"no-token\";\n  try {\n    const base = (process.env[\"SKILLET_REGISTRY_URL\"] ?? REGISTRY_DEFAULT).replace(/\\/+$/, \"\");\n    const headers = { authorization: `Bearer ${bearer.token}` };\n    const [ev, re] = await Promise.all([\n      fetch(`${base}${REGISTRY_API}/me/events`, { headers }),\n      fetch(`${base}${REGISTRY_API}/me/availability`, { headers }),\n    ]);\n    if (!ev.ok || !re.ok) return \"failed\";\n    return { events: await ev.json(), availability: await re.json() };\n  } catch {\n    return \"failed\";\n  }\n}\n", "import type { Command } from 'commander';\nimport * as clack from '@clack/prompts';\nimport {\n  RegistryClient,\n  acceptAuthorKeyRotation,\n  compareAuthorPin,\n  fetchServedAuthorKey,\n  listPinnedHandles,\n  loadPinnedKey,\n  loadRegistryBearer,\n  truncateKeyId,\n} from '@skillet/core';\nimport { ExitCode, exitWith } from '../exit-codes.js';\nimport { REGISTRY_DEFAULT } from '../cli-context.js';\n\nfunction normalizeHandleArg(raw: string): string {\n  const handle = raw.startsWith('@') ? raw.slice(1) : raw;\n  if (!/^[a-z0-9-]{1,64}$/.test(handle)) {\n    console.error(`\u2717 Invalid handle ${JSON.stringify(raw)}`);\n    exitWith(ExitCode.USAGE);\n  }\n  return handle;\n}\n\nfunction registryClient(token?: string): RegistryClient {\n  return new RegistryClient({\n    baseUrl: REGISTRY_DEFAULT,\n    token,\n  });\n}\n\nexport function registerPinCommands(program: Command): void {\n  const pin = program\n    .command('pin', { hidden: true })\n    .description('Author signing keys this machine trusts (pinned on first sync)');\n\n  pin\n    .command('list')\n    .description('List handles with locally pinned author signing keys')\n    .option('--json', 'Emit JSON')\n    .action(async (opts: { json?: boolean }) => {\n      const handles = await listPinnedHandles();\n      if (opts.json) {\n        process.stdout.write(JSON.stringify({ handles }, null, 2) + '\\n');\n        return;\n      }\n      if (handles.length === 0) {\n        console.log('No pinned author keys on this device.');\n        return;\n      }\n      console.log('Pinned author keys:');\n      for (const handle of handles.sort()) {\n        console.log(`  @${handle}`);\n      }\n    });\n\n  pin\n    .command('show <handle>')\n    .description('Compare the local pin with the registry-served author key')\n    .option('--json', 'Emit JSON')\n    .option('--token <token>', 'Bearer token override')\n    .action(async (handleArg: string, opts: { json?: boolean; token?: string }) => {\n      const handle = normalizeHandleArg(handleArg);\n      const bearer = await loadRegistryBearer(opts.token);\n      const client = registryClient(bearer.token || undefined);\n      let served: { key_id: string; pub: string } | null = null;\n      try {\n        const fetched = await fetchServedAuthorKey(handle, client);\n        served = { key_id: fetched.key_id, pub: fetched.pub };\n      } catch (err) {\n        if (!opts.json) {\n          console.error(`\u2717 Could not fetch registry key for @${handle}: ${(err as Error).message}`);\n        }\n        if (opts.json) {\n          process.stdout.write(\n            JSON.stringify(\n              {\n                handle,\n                pinned: await loadPinnedKey(handle),\n                served: null,\n                mismatch: false,\n                fetchError: (err as Error).message,\n              },\n              null,\n              2,\n            ) + '\\n',\n          );\n        }\n        exitWith(ExitCode.ERROR);\n      }\n\n      const comparison = await compareAuthorPin(handle, undefined, served);\n      if (opts.json) {\n        process.stdout.write(\n          JSON.stringify(\n            {\n              handle: comparison.handle,\n              pinned_key_id: comparison.pinned?.key_id ?? null,\n              registry_key_id: comparison.served?.key_id ?? null,\n              mismatch: comparison.mismatch,\n            },\n            null,\n            2,\n          ) + '\\n',\n        );\n        return;\n      }\n\n      console.log(`Author pin for @${handle}`);\n      if (comparison.pinned) {\n        console.log(`  pinned:   ${comparison.pinned.key_id} (since ${comparison.pinned.pinned_at})`);\n      } else {\n        console.log('  pinned:   (none; the first sync pins the author key)');\n      }\n      if (comparison.served) {\n        console.log(`  registry: ${comparison.served.key_id}`);\n      }\n      if (comparison.mismatch) {\n        console.log('\\n  mismatch \u2014 run `skillet pin accept ' + handle + '` to re-pin.');\n      } else if (comparison.pinned && comparison.served) {\n        console.log('\\n  keys match.');\n      }\n    });\n\n  pin\n    .command('accept <handle>')\n    .description('Accept the registry author key and replace a stale pin')\n    .option('--yes', 'Skip confirmation prompt')\n    .option('--token <token>', 'Bearer token override')\n    .action(async (handleArg: string, opts: { yes?: boolean; token?: string }) => {\n      const handle = normalizeHandleArg(handleArg);\n      const bearer = await loadRegistryBearer(opts.token);\n      const client = registryClient(bearer.token || undefined);\n\n      let served: { key_id: string; pub: string };\n      try {\n        const fetched = await fetchServedAuthorKey(handle, client);\n        served = { key_id: fetched.key_id, pub: fetched.pub };\n      } catch (err) {\n        console.error(`\u2717 Could not fetch registry key for @${handle}: ${(err as Error).message}`);\n        exitWith(ExitCode.ERROR);\n      }\n\n      const comparison = await compareAuthorPin(handle, undefined, served);\n      if (!comparison.pinned) {\n        await acceptAuthorKeyRotation(handle, served);\n        console.log(`\u2713 Pinned @${handle} to ${truncateKeyId(served.key_id)}.`);\n        return;\n      }\n      if (!comparison.mismatch) {\n        console.log(`\u2713 @${handle} is already pinned to the registry key (${truncateKeyId(served.key_id)}).`);\n        return;\n      }\n\n      const pinnedShort = truncateKeyId(comparison.pinned.key_id);\n      const servedShort = truncateKeyId(served.key_id);\n      let accepted = opts.yes === true;\n      if (!accepted) {\n        if (process.stdout.isTTY !== true) {\n          console.error(\n            `\u2717 Author key changed for @${handle} (${pinnedShort} \u2192 ${servedShort}). Re-run with --yes in non-interactive mode.`,\n          );\n          exitWith(ExitCode.ERROR);\n        }\n        const answer = await clack.confirm({\n          message:\n            `Accept new signing key for @${handle}?\\n  pinned: ${pinnedShort}\\n  registry: ${servedShort}`,\n        });\n        if (clack.isCancel(answer) || answer !== true) {\n          console.log('Pin unchanged.');\n          return;\n        }\n        accepted = true;\n      }\n\n      if (accepted) {\n        await acceptAuthorKeyRotation(handle, served);\n        console.log(`\u2713 Re-pinned @${handle} to ${servedShort}. Run \\`skillet sync\\` to pull affected skills.`);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport { RegistryClient, loadSessionToken } from \"@skillet/core\";\nimport { resolveRegistryUrl } from \"../cli-context.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\n\n/** Build an account-scoped RegistryClient from the stored session (or overrides).\n *  update-mode is account-scoped, so a session bearer is required. */\nasync function accountClient(opts: { registry?: string; token?: string }): Promise<RegistryClient> {\n  const registryUrl = await resolveRegistryUrl(opts);\n  const token = await loadSessionToken(opts.token);\n  if (!token) {\n    console.error(\"\u2717 Not signed in. Pair this machine with `skillet connect <code>`.\");\n    exitWith(ExitCode.AUTH);\n  }\n  return new RegistryClient({ baseUrl: registryUrl, token });\n}\n\nconst label = (mode: \"auto\" | \"manual\"): string =>\n  mode === \"auto\" ? \"ON (auto)\" : \"OFF (manual)\";\n\nexport function registerUpdateModeCommand(program: Command): void {\n  program\n    .command(\"update-mode [mode]\", { hidden: true })\n    .description(\n      \"Show or set whether subscribed skills auto-update. <mode>: auto | manual. No arg prints the current mode.\",\n    )\n    .option(\"--registry <url>\", \"Registry base URL (overrides identity default)\")\n    .option(\"--token <token>\", \"Session bearer token (overrides the stored session)\")\n    .option(\"--json\", \"Emit raw JSON\")\n    .action(\n      async (\n        mode: string | undefined,\n        opts: { registry?: string; token?: string; json?: boolean },\n      ) => {\n        try {\n          const client = await accountClient(opts);\n\n          if (mode === undefined) {\n            const { update_mode } = await client.getMyDecisions();\n            if (opts.json) {\n              console.log(JSON.stringify({ mode: update_mode }));\n              return;\n            }\n            console.log(`Auto-update is ${label(update_mode)}.`);\n            return;\n          }\n\n          if (mode !== \"auto\" && mode !== \"manual\") {\n            console.error(`\u2717 Invalid mode \"${mode}\". Use \"auto\" or \"manual\".`);\n            exitWith(ExitCode.USAGE);\n          }\n\n          const result = await client.setUpdateMode(mode);\n          if (opts.json) {\n            console.log(JSON.stringify(result));\n            return;\n          }\n          console.log(`\u2713 Auto-update set to ${label(result.mode)}.`);\n          if (result.mode === \"auto\" && result.applied > 0) {\n            console.log(`  Applied ${result.applied} pending update${result.applied === 1 ? \"\" : \"s\"}.`);\n          }\n        } catch (err) {\n          console.error(`\u2717 ${err instanceof Error ? err.message : String(err)}`);\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n}\n", "import type { Command } from \"commander\";\nimport {\n  readState,\n  uploadLocalSkills,\n  type UploadProgressEvent,\n} from \"@skillet/core\";\nimport { requirePaired } from \"../auth-required.js\";\nimport { confirm } from \"./import-cmd.js\";\nimport {\n  configureAddPresent,\n  printAddHint,\n  printStepInfo,\n} from \"../cli-add-present.js\";\nimport { collect, REGISTRY_DEFAULT } from \"../cli-context.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\nimport { fail } from \"../cli-colors.js\";\nimport {\n  displaySlug,\n  renderUploadProgress,\n  summarizeUploadResult,\n} from \"./upload-present.js\";\n\nexport { displaySlug, renderUploadProgress, summarizeUploadResult };\n\n/** Count local, un-owned skills \u2014 the set a no-`--skill` batch would publish. */\nasync function countCapturable(): Promise<number> {\n  const state = await readState();\n  return Object.values(state.skills).filter((s) => s.source === \"local\" && !s.owner)\n    .length;\n}\n\n/** Upload local skills to the account's profile kit (desktop + device golden route). */\nexport function registerUploadCommand(program: Command): void {\n  program\n    .command(\"upload [name]\")\n    .description(\"Upload local skills, private, to your account\")\n    .option(\"--skill <slug>\", \"Upload only the named skill(s); repeatable\", collect, [] as string[])\n    .option(\"--all\", \"Upload every un-published local skill (required for a no --skill batch)\")\n    .option(\"--public\", \"Publish publicly (default is private)\")\n    .option(\"--json\", \"Emit a machine-readable report (for the desktop app)\")\n    .option(\"--registry <url>\", \"Registry base URL\", REGISTRY_DEFAULT)\n    .option(\"--token <token>\", \"Session token (defaults to $SKILLET_TOKEN)\")\n    .action(\n      async (\n        name: string | undefined,\n        opts: {\n          skill: string[];\n          all?: boolean;\n          public?: boolean;\n          json?: boolean;\n          registry: string;\n          token?: string;\n        },\n      ) => {\n        const asJson = opts.json === true;\n\n        // The positional was removed (skills go to the profile kit, not a named\n        // kit). It used to be accepted-and-ignored, which silently turned\n        // `upload marketing-skills` (intent: one skill) into a no-`--skill`\n        // batch that published EVERY local skill. Hard-fail instead so the old\n        // syntax can never trigger a mass upload.\n        if (name !== undefined) {\n          const msg =\n            `upload no longer takes a positional name. Use \\`--skill ${name}\\` to upload one skill, or \\`--all\\` to upload every local skill.`;\n          if (asJson) {\n            process.stdout.write(JSON.stringify({ ok: false, error: msg, code: \"positional_removed\" }) + \"\\n\");\n          } else {\n            console.error(fail(msg));\n          }\n          exitWith(ExitCode.ERROR);\n        }\n\n        // Pairing gate \u2014 upload publishes local skills to the account, so an\n        // unpaired machine fails with the shared auth-required message. In\n        // --json mode (how the desktop invokes it) the envelope goes to stdout.\n        await requirePaired(opts.token, { json: asJson });\n\n        // No `--skill` means \"publish every local skill.\" That is a bulk,\n        // hard-to-undo action, so it must be explicit: `--all` (scripts/desktop\n        // \u2014 desktop always passes `--skill`, so it never reaches here) or an\n        // interactive y/N confirm. Refusing the silent default is what closes\n        // the accidental mass-upload path.\n        if (opts.skill.length === 0 && opts.all !== true) {\n          const count = await countCapturable();\n          if (count === 0) {\n            const msg = \"Nothing to upload. Run `skillet import` to pull skills from this machine first.\";\n            if (asJson) {\n              process.stdout.write(JSON.stringify({ ok: false, empty: true, error: msg }) + \"\\n\");\n            } else {\n              console.log(msg);\n            }\n            return;\n          }\n          const vis = opts.public === true ? \"publicly\" : \"privately (private)\";\n          const proceed =\n            process.stdin.isTTY === true &&\n            (await confirm(\n              `This will upload all ${count} local skill(s) ${vis} to your profile. Continue?`,\n            ));\n          if (!proceed) {\n            const msg =\n              `Refusing to upload all ${count} local skill(s) without confirmation. Pass \\`--all\\` or select skills with \\`--skill <slug>\\`.`;\n            if (asJson) {\n              process.stdout.write(JSON.stringify({ ok: false, error: msg, code: \"confirmation_required\" }) + \"\\n\");\n            } else {\n              console.error(fail(msg));\n            }\n            // USAGE, matching publish's confirmation_required and the\n            // documented exit-code table (missing flags, not a failure).\n            exitWith(ExitCode.USAGE);\n          }\n        }\n\n        const visibility = opts.public === true ? \"public\" : \"private\";\n        if (!asJson) {\n          configureAddPresent({ json: false, color: process.stdout.isTTY === true });\n        }\n\n        try {\n          const result = await uploadLocalSkills({\n            ...(opts.skill.length > 0 ? { slugs: opts.skill } : {}),\n            visibility,\n            registryUrl: opts.registry,\n            token: opts.token,\n            sessionAuth: true,\n            ...(!asJson\n              ? {\n                  onProgress: (event: UploadProgressEvent) => {\n                    if (event.phase === \"start\" && event.index === 0) {\n                      printStepInfo(\n                        `${event.total} local skill${event.total === 1 ? \"\" : \"s\"} (${visibility})`,\n                      );\n                    }\n                    renderUploadProgress(event);\n                  },\n                }\n              : {}),\n          });\n          if (asJson) {\n            process.stdout.write(JSON.stringify(result) + \"\\n\");\n            if (!result.ok && !result.empty) exitWith(ExitCode.ERROR);\n            return;\n          }\n          if (result.empty) {\n            console.log(\n              \"Nothing to upload. Run `skillet import` to pull skills from this machine first.\",\n            );\n            return;\n          }\n          if (!result.ok) {\n            console.error(fail(\"Upload did not complete.\"));\n            if (result.published.length === 0) {\n              for (const f of result.failed) {\n                console.error(`  ${displaySlug(f.slug)}: ${f.error}`);\n              }\n            }\n            exitWith(ExitCode.ERROR);\n          }\n          console.log(summarizeUploadResult(result, visibility));\n          printAddHint(\"Other devices pull them in on the next sync.\");\n        } catch (err) {\n          const message = (err as Error).message;\n          if (asJson) {\n            process.stdout.write(JSON.stringify({ ok: false, error: message }) + \"\\n\");\n          } else {\n            console.error(fail(`Upload failed: ${message}`));\n          }\n          exitWith(ExitCode.ERROR);\n        }\n      },\n    );\n}\n", "import type { Command } from \"commander\";\nimport { openBrowserUrl, resolveWebUrl } from \"../open-browser-url.js\";\nimport { ExitCode, exitWith } from \"../exit-codes.js\";\n\nexport function registerWebCommand(program: Command): void {\n  program\n    .command(\"web [path]\")\n    .description(\"Open skillet.md in your browser (e.g. /settings)\")\n    .action(async (path: string | undefined) => {\n      try {\n        const url = resolveWebUrl(path);\n        const opened = await openBrowserUrl(url);\n        if (opened) {\n          console.log(`Opened ${url}`);\n          return;\n        }\n        console.log(url);\n      } catch (err) {\n        console.error(`\u2717 ${(err as Error).message}`);\n        exitWith(ExitCode.USAGE);\n      }\n    });\n}\n", "import type { Command } from \"commander\";\nimport { legacyManagementEnabled } from \"../cli-routing.js\";\nimport { registerAddCommand } from \"./add-cmd.js\";\nimport { registerAuthCommands, registerSessionAliasCommands } from \"./auth.js\";\nimport { registerAvatarCommand } from \"./avatar.js\";\nimport { registerConnectCommand } from \"./connect.js\";\nimport { registerDoctorCommand } from \"./doctor.js\";\nimport { registerEditsCommand } from \"./edits.js\";\nimport { registerExportCommand } from \"./export.js\";\nimport { registerImportCommand } from \"./import-cmd.js\";\nimport { registerListCommand } from \"./list.js\";\nimport { registerMcpCommand } from \"./mcp.js\";\nimport { registerPendingCommands } from \"./pending.js\";\nimport { registerRouteCommand } from \"./route-cmd.js\";\nimport { registerManagementCommands } from \"./register-management-commands.js\";\nimport { registerRestoreCommand } from \"./restore.js\";\nimport { registerStatusCommand } from \"./status.js\";\nimport { registerSweepCommand } from \"./sweep.js\";\nimport { registerSyncCommand } from \"./sync.js\";\nimport { registerRuntimesCommand } from \"./runtimes.js\";\nimport { registerSearchCommand } from \"./search.js\";\nimport { registerUsageCommand } from \"./usage.js\";\nimport { registerActivityCommand } from \"./activity.js\";\nimport { registerTrustCommands } from \"./trust.js\";\nimport { registerPinCommands } from \"./pin.js\";\nimport { registerUpdateModeCommand } from \"./update-mode.js\";\nimport { registerUploadCommand } from \"./upload-cmd.js\";\nimport { registerWebCommand } from \"./web-cmd.js\";\n\n/**\n * Canonical CLI verb taxonomy (pre-launch naming contract):\n * - import \u2014 ingest local/runtime/GitHub skills into the kit\n * - add \u2014 install or subscribe so skills materialize on this machine\n * - upload \u2014 share local kit skills to the account profile (device tier)\n * - scan \u2014 harm-scan safety state for kit skills\n * Legacy aliases (status, publish, \u2026) remain callable with deprecation hints.\n */\n\nexport interface RegisterCommandsOptions {\n  /** Register hidden management verbs (default: SKILLET_LEGACY_CLI=1). */\n  legacyManagement?: boolean;\n}\n\nexport function registerAllCommands(program: Command, options?: RegisterCommandsOptions): void {\n  registerSyncCommand(program);\n  // Pure-local agent detection for the desktop tray \u2014 no registry, so it survives\n  // a failing sync (deleted skill, DB reset, offline). Device-tier: always on.\n  registerRuntimesCommand(program);\n  // Local-only usage dashboard: reads the route-history store, no\n  // registry \u2014 works offline and for anonymous users, like `runtimes`.\n  registerUsageCommand(program);\n  // Data rights + consent surface: view/export/delete recorded data and\n  // toggle the two consent tiers. Always registered \u2014 a user's ability to see and\n  // delete what's recorded about them must never depend on SKILLET_LEGACY_CLI\n  // (same footing as `edits`/`restore`/`pending`).\n  registerActivityCommand(program);\n  registerRestoreCommand(program);\n  // ALWAYS registered (R10): a captured edit must never need SKILLET_LEGACY_CLI\n  // to be reviewed, kept, proposed, or discarded \u2014 same footing as `restore`.\n  registerEditsCommand(program);\n  registerSweepCommand(program);\n  registerListCommand(program);\n  // Public, anonymous registry search \u2014 read-only, no pairing. The @skillet/route\n  // fall-through shells out to this on a whiff; also usable standalone. Device-tier:\n  // always registered so the bundled router can rely on it being present.\n  registerSearchCommand(program);\n  registerStatusCommand(program);\n  registerDoctorCommand(program);\n  registerAuthCommands(program);\n  // Top-level `logout` / `disconnect` aliases for the `auth` verbs \u2014 sign-out is\n  // a first-reach command, so it earns a root verb instead of only `auth logout`.\n  registerSessionAliasCommands(program);\n  registerAvatarCommand(program);\n  registerConnectCommand(program);\n  registerWebCommand(program);\n  registerAddCommand(program);\n  registerImportCommand(program);\n  registerExportCommand(program);\n  registerUploadCommand(program);\n  registerTrustCommands(program);\n  registerPinCommands(program);\n  registerUpdateModeCommand(program);\n  registerMcpCommand(program);\n  registerRouteCommand(program);\n  // Update approval is a DEVICE concern, not a management verb: it gates this\n  // machine's sync, and the desktop tray drives it (`pending`/`approve`/`reject`\n  // --json). Hiding it behind SKILLET_LEGACY_CLI broke the tray's badge and the\n  // web-approval \u2192 lock-file reconcile, leaving sync approval-blocked forever.\n  registerPendingCommands(program);\n\n  const legacy = options?.legacyManagement ?? legacyManagementEnabled();\n  if (legacy) {\n    registerManagementCommands(program);\n  }\n}\n", "import { dim, padEndVisible, visibleLength } from \"./cli-colors.js\";\n\n/**\n * The Skillet face, quadrant-block-rendered from the desktop app icon\n * (src-tauri/icons/128x128.png): a solid tile with the wink chevron, donut\n * eye, and smile knocked out, so grouty terminal line spacing can't shatter\n * it into floating pieces. Every bare run opens with it, Claude Code style \u2014\n * face on the left, info column beside it. No color \u2014 the shape is the brand.\n */\nexport const SKILLET_FACE = [\n  \"\u2597\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2596\",\n  \"\u2588\u2588\u2584\u2580\u2588\u2588\u2580\u2580\u2588\u2588\",\n  \"\u2588\u2588\u2588\u2580\u2584\u2588 \u2598\u2588\u2588\",\n  \"\u2588\u2588\u2584\u259B\u259C\u2588\u2580\u2588\u2588\u2588\",\n  \"\u259D\u2588\u2588\u2588\u2584\u2584\u259F\u2588\u2588\u2598\",\n];\n\n/** Column where the info lines start, past the widest face row. */\nconst INFO_COLUMN = 14;\n\n/** Face row the first info line sits beside (centers 3 lines on 5 rows). */\nconst INFO_START_ROW = 1;\n\n/**\n * Launch banner: the face with up to three info lines beside it \u2014 name and\n * version first, then whatever the run knows (skill count, agents, machine).\n * The face renders dim: full-brightness block mass overpowers the text, and\n * dim tracks the user's theme where a hardcoded gray would not.\n */\nexport function launchBanner(\n  infoLines: string[],\n  width = process.stdout.columns ?? 80,\n): string {\n  const lines = SKILLET_FACE.map((row) => dim(row));\n  const longest = Math.max(0, ...infoLines.map(visibleLength));\n  // Never let the terminal wrap mid-face \u2014 a sheared row of blocks reads as\n  // garbage. When the side-by-side layout doesn't fit, stack instead.\n  if (width < INFO_COLUMN + longest) {\n    return [...lines, \"\", ...infoLines].join(\"\\n\");\n  }\n  infoLines.slice(0, lines.length - INFO_START_ROW).forEach((info, i) => {\n    const row = INFO_START_ROW + i;\n    lines[row] = padEndVisible(lines[row]!, INFO_COLUMN) + info;\n  });\n  return lines.join(\"\\n\");\n}\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,kFAAAA,UAAA;AAGA,QAAMC,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAO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,YAAMA,SAAQ,WAAW,QAAQ,IAAI;AAAA,IACvC;AAAA,EACF,SAASC,MAAK;AAIZ,QAAIA,gBAAe,eAAgB,OAAMA;AAGzC,QAAI,QAAQ,KAAK,SAAS,QAAQ,GAAG;AACnC,qBAAgBA,KAAc,WAAW,OAAOA,IAAG,KAAK,eAAe;AAAA,IACzE,OAAO;AACL,yBAAmBA,MAAc,IAAI;AAAA,IACvC;AACA,QAAI,QAAQ,IAAI,eAAe,MAAM,OAAOA,gBAAe,SAASA,KAAI,OAAO;AAC7E,cAAQ,MAAM,IAAIA,KAAI,KAAK,CAAC;AAAA,IAC9B,OAAO;AACL,cAAQ,MAAM,IAAI,6CAA6C,CAAC;AAAA,IAClE;AACA,YAAQ,WAAW;AAAA,EACrB,UAAE;AACA,UAAM,YAAY;AAAA,EACpB;AACF,GAAG;",
  "names": ["exports", "CommanderError", "InvalidArgumentError", "exports", "InvalidArgumentError", "Argument", "exports", "Help", "cmd", "a", "str", "i", "exports", "InvalidArgumentError", "Option", "options", "str", "exports", "a", "i", "exports", "process", "Argument", "CommanderError", "Help", "Option", "Command", "str", "err", "m", "i", "option", "path", "text", "exports", "Argument", "Command", "CommanderError", "InvalidArgumentError", "Help", "Option", "str", "i", "l", "n", "c", "r", "o", "_a", "m", "require", "t", "t2", "a", "i2", "_b", "post", "u", "fl", "n", "a", "text", "yaml", "i", "i", "r", "t", "rev", "c", "import_node_crypto", "options", "i", "i", "c", "status", "r", "a", "t", "c", "i", "slug", "sep", "fd", "err", "import_promises", "import_node_path", "import_node_crypto", "targetPath", "import_node_path", "a", "import_promises", "import_node_path", "exports", "module", "err", "exports", "module", "exports", "module", "o", "i", "a", "exports", "module", "options", "i", "ln", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "options", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "c", "sign", "exports", "module", "sign", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "err", "exports", "module", "exports", "module", "c", "lc", "i", "options", "exports", "module", "options", "str", "c", "i", "string", "block", "exports", "module", "require_js_yaml", "exports", "module", "yaml", "options", "err", "exports", "module", "str", "exports", "str", "exports", "module", "engines", "options", "exports", "module", "options", "exports", "module", "options", "str", "open", "matter", "exports", "module", "options", "sep", "delimiter", "exports", "module", "options", "exports", "module", "str", "options", "exports", "module", "engines", "parse", "matter", "options", "cached", "open", "str", "block", "matter", "init_zip", "init_bundle", "init_zip", "err", "import_promises", "import_node_path", "import_node_os", "import_promises", "import_node_path", "import_node_os", "err", "import_promises", "import_node_path", "sessionToken", "import_promises", "import_node_path", "text", "u", "a", "import_promises", "import_node_path", "a", "canonicalRef", "import_promises", "err", "a", "label", "a", "m", "SKILLET_DIR", "err", "import_promises", "import_node_path", "import_node_os", "err", "VALID_KEY_ID_RE", "import_node_crypto", "import_promises", "import_node_path", "import_node_crypto", "import_node_fs", "m", "status", "t", "skillId", "label", "err", "err", "import_node_path", "import_node_os", "defaultConfigDir", "sessionToken", "identity", "err", "import_node_path", "import_node_os", "CONTENT_HASH_RE", "VALID_KEY_ID_RE", "ok", "import_node_crypto", "defaultConfigDir", "HANDLE_RE", "err", "sessionToken", "sep", "matter", "import_node_path", "import_node_os", "import_gray_matter", "h", "err", "VALID_KEY_ID_RE", "import_promises", "import_node_os", "import_node_path", "import_node_crypto", "err", "a", "import_promises", "import_node_path", "slugify", "matter", "import_promises", "import_node_path", "import_node_child_process", "import_gray_matter", "r", "c", "exists", "i", "a", "import_promises", "import_node_fs", "import_node_path", "err", "matter", "import_gray_matter", "i", "ED25519_RAW_PUB_BYTES", "KEY_ID_RE", "import_node_crypto", "init_delegation", "import_node_path", "init_delegation", "a", "m", "n", "i", "j", "l", "c", "skillId", "err", "import_promises", "import_node_path", "import_node_os", "resolve", "text", "status", "h", "resolve", "import_node_readline", "err", "m", "import_promises", "import_node_path", "import_node_os", "skilletDir", "err", "import_promises", "import_node_os", "import_node_path", "manifest", "served", "sync", "err", "import_promises", "err", "m", "label", "matter", "o", "i", "clientFor", "cached", "import_gray_matter", "import_promises", "init_delegation", "m", "a", "status", "sep", "o", "err", "handleFromSlug", "m", "matter", "h", "cached", "a", "r", "reason", "isCI", "verifyBundle", "import_promises", "import_node_os", "import_node_path", "import_gray_matter", "init_delegation", "bareAdapterSlug", "err", "c", "import_promises", "import_node_path", "defaultConfigDir", "err", "import_node_path", "import_node_os", "err", "init_eval", "REF_RE", "subdir", "init_client", "status", "err", "t", "init_client", "slugify", "SKILL_ENTRYPOINT", "n", "a", "matter", "import_node_path", "import_promises", "import_gray_matter", "init_client", "matter", "slugify", "err", "r", "import_promises", "import_node_path", "import_gray_matter", "err", "settings", "import_promises", "import_node_os", "import_node_path", "err", "i", "readConfig", "skilletHook", "HOOK_EVENT", "import_promises", "import_node_os", "import_node_path", "readHooksFile", "err", "HOOK_EVENT", "import_promises", "import_node_os", "import_node_path", "result", "err", "skillId", "status", "a", "label", "CONTROL_RE", "stripPrefix", "matter", "import_gray_matter", "bareAdapterSlug", "walkMaterialized", "readCurrentMaterialized", "a", "import_promises", "import_node_path", "skillId", "skillId", "err", "import_promises", "err", "sessionToken", "status", "import_promises", "a", "matter", "import_node_path", "import_gray_matter", "label", "import_node_child_process", "import_node_os", "label", "platform", "label", "import_node_crypto", "err", "skilletDir", "err", "h", "import_promises", "import_node_path", "import_node_os", "init_kit", "a", "err", "init_kit", "a", "err", "err", "defaultConfigDir", "o", "label", "import_node_os", "import_node_path", "init_delegation", "init_dist", "init_bundle", "init_eval", "init_kit", "init_delegation", "exports", "module", "ESC", "CSI", "cursor", "erase", "i", "ok", "err", "import_promises", "import_node_path", "import_promises", "import_node_path", "init_store", "init_dist", "isText", "init_dist", "init_store", "webBaseUrl", "init_dist", "init_store", "import_node_crypto", "import_promises", "import_node_path", "init_dist", "init_dist", "ok", "err", "init_store", "resolve", "err", "import_node_readline", "resolve", "o", "status", "ok", "err", "dist_exports", "init_dist", "init_store", "commander", "init_dist", "text", "commandPath", "resolve", "c", "r", "c", "o", "init_dist", "import_node_util", "import_node_readline", "CONTROL_RE", "i", "l", "NO_TRUNCATION", "options", "dist_default", "ANSI_CSI", "ANSI_OSC", "dist_default", "options", "i", "o", "l", "r", "t", "n", "n", "n", "i", "t", "r", "R", "o", "a", "c", "m", "l__default", "h", "t", "i", "i", "t", "l", "a", "t", "i", "t", "r", "import_node_util", "import_node_process", "import_sisteransi", "process$1", "o", "r", "l", "c", "h", "i", "C", "m", "u", "W", "t", "n", "a", "i", "a", "u", "l", "o", "c", "r", "n", "o", "t", "a", "r", "l", "i", "u", "r", "m", "l", "c", "t", "o", "u", "i", "l", "h", "n", "G", "m", "u", "r", "a", "i", "C", "t", "o", "t", "a", "i", "m", "n", "u", "r", "o", "h", "t", "i", "c", "o", "a", "n", "r", "import_node_os", "import_node_path", "import_promises", "init_dist", "import_node_fs", "import_promises", "import_node_os", "import_node_path", "init_dist", "import_node_path", "import_node_os", "import_promises", "init_dist", "import_node_path", "import_node_os", "import_promises", "init_dist", "import_node_path", "import_node_os", "import_promises", "init_dist", "DEFAULT_TARGET_DIR", "text", "m", "createAdapter", "import_node_path", "import_promises", "init_dist", "DEFAULT_TARGET_DIR", "createAdapter", "import_node_path", "import_node_os", "import_node_fs", "import_promises", "init_dist", "i", "createAdapter", "import_node_path", "import_node_os", "import_promises", "init_dist", "createAdapter", "import_node_path", "import_node_os", "import_promises", "init_dist", "DEFAULT_TARGET_DIR", "createAdapter", "import_node_path", "import_node_os", "import_promises", "init_dist", "DEFAULT_TARGET_DIR", "PRIMARY_DETECT_DIR", "PROJECT_TARGET_DIR", "findProjectRoot", "createAdapter", "createProjectAdapter", "init_dist", "readFileSync", "status", "r", "label", "import_node_os", "import_node_path", "a", "init_dist", "a", "n", "err", "import_node_fs", "import_node_path", "import_node_url", "ANSI_OSC", "ANSI_CSI", "CONTROL", "text", "text", "l", "n", "label", "err", "a", "o", "init_dist", "init_dist", "init_dist", "text", "init_dist", "import_node_os", "import_node_path", "a", "import_promises", "init_dist", "registryRef", "init_dist", "init_dist", "m", "label", "wanted", "picked", "m", "err", "confirm", "n", "i", "a", "program", "a", "r", "bearer", "label", "program", "result", "err", "init_dist", "import_node_child_process", "platform", "resolve", "label", "err", "program", "status", "h", "c", "init_dist", "h", "i", "program", "status", "m", "init_dist", "program", "err", "init_dist", "program", "err", "init_dist", "c", "a", "i", "l", "u", "status", "lineDiff", "h", "program", "err", "import_node_fs", "import_node_path", "init_dist", "err", "program", "entry", "bundle", "import_node_fs", "init_dist", "init_dist", "n", "init_dist", "program", "init_dist", "program", "runStdio", "startHttpTransport", "resolve", "init_dist", "program", "err", "import_node_process", "init_dist", "resolve", "text", "program", "err", "init_dist", "program", "err", "init_dist", "program", "r", "label", "c", "init_dist", "program", "err", "h", "a", "init_dist", "program", "err", "init_dist", "program", "err", "init_dist", "program", "r", "n", "err", "init_dist", "program", "err", "m", "init_dist", "program", "m", "c", "program", "init_dist", "program", "r", "init_dist", "r", "program", "import_node_path", "init_dist", "program", "import_node_path", "init_dist", "init_dist", "o", "init_dist", "n", "a", "program", "n", "confirm", "err", "unionFailed", "o", "c", "l", "r", "import_node_os", "import_node_fs", "import_node_path", "init_dist", "program", "label", "r", "init_dist", "r", "i", "a", "program", "init_dist", "program", "init_dist", "n", "r", "program", "init_dist", "registryClient", "program", "err", "init_dist", "accountClient", "program", "err", "init_dist", "program", "confirm", "err", "program", "err", "program", "options", "options", "program", "err", "i", "settingsPageUrl", "label", "program", "err"]
}
