@hugomrdias/fil 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +136 -2
- package/bin/fil.js +7 -0
- package/dist/chunks/_esm-BBXTTBLC.js +9 -0
- package/dist/chunks/_esm-BBXTTBLC.js.map +7 -0
- package/dist/chunks/ccip-TGFMQFIR.js +3 -0
- package/dist/chunks/ccip-TGFMQFIR.js.map +7 -0
- package/dist/chunks/chunk-2KPBBDBJ.js +3 -0
- package/dist/chunks/chunk-2KPBBDBJ.js.map +7 -0
- package/dist/chunks/chunk-35V77X3C.js +12 -0
- package/dist/chunks/chunk-35V77X3C.js.map +7 -0
- package/dist/chunks/chunk-46FBFEBX.js +3 -0
- package/dist/chunks/chunk-46FBFEBX.js.map +7 -0
- package/dist/chunks/chunk-4BBXH7CB.js +6 -0
- package/dist/chunks/chunk-4BBXH7CB.js.map +7 -0
- package/dist/chunks/chunk-4DUACCJB.js +186 -0
- package/dist/chunks/chunk-4DUACCJB.js.map +7 -0
- package/dist/chunks/chunk-5EYSPKTK.js +3 -0
- package/dist/chunks/chunk-5EYSPKTK.js.map +7 -0
- package/dist/chunks/chunk-7MEK5RQ7.js +11 -0
- package/dist/chunks/chunk-7MEK5RQ7.js.map +7 -0
- package/dist/chunks/chunk-7WN6TT5U.js +4 -0
- package/dist/chunks/chunk-7WN6TT5U.js.map +7 -0
- package/dist/chunks/chunk-CU3SGKNA.js +3 -0
- package/dist/chunks/chunk-CU3SGKNA.js.map +7 -0
- package/dist/chunks/chunk-EDF5XCIN.js +4 -0
- package/dist/chunks/chunk-EDF5XCIN.js.map +7 -0
- package/dist/chunks/chunk-GVAFHRPJ.js +124 -0
- package/dist/chunks/chunk-GVAFHRPJ.js.map +7 -0
- package/dist/chunks/chunk-IJ2NNDTJ.js +3 -0
- package/dist/chunks/chunk-IJ2NNDTJ.js.map +7 -0
- package/dist/chunks/chunk-ISML2NA2.js +3 -0
- package/dist/chunks/chunk-ISML2NA2.js.map +7 -0
- package/dist/chunks/chunk-KAQPCD23.js +4 -0
- package/dist/chunks/chunk-KAQPCD23.js.map +7 -0
- package/dist/chunks/chunk-LOTWVNDB.js +3 -0
- package/dist/chunks/chunk-LOTWVNDB.js.map +7 -0
- package/dist/chunks/chunk-NPYAGWD6.js +4 -0
- package/dist/chunks/chunk-NPYAGWD6.js.map +7 -0
- package/dist/chunks/chunk-QYPR6473.js +3 -0
- package/dist/chunks/chunk-QYPR6473.js.map +7 -0
- package/dist/chunks/chunk-RK6JJQZL.js +41 -0
- package/dist/chunks/chunk-RK6JJQZL.js.map +7 -0
- package/dist/chunks/chunk-UJQDDRQD.js +59 -0
- package/dist/chunks/chunk-UJQDDRQD.js.map +7 -0
- package/dist/chunks/chunk-UVXTIEPU.js +4 -0
- package/dist/chunks/chunk-UVXTIEPU.js.map +7 -0
- package/dist/chunks/chunk-VTR7BON5.js +4 -0
- package/dist/chunks/chunk-VTR7BON5.js.map +7 -0
- package/dist/chunks/chunk-XQRC2SUG.js +4 -0
- package/dist/chunks/chunk-XQRC2SUG.js.map +7 -0
- package/dist/chunks/chunk-YIAP3JO3.js +3 -0
- package/dist/chunks/chunk-YIAP3JO3.js.map +7 -0
- package/dist/chunks/chunk-ZD6MKB4J.js +5 -0
- package/dist/chunks/chunk-ZD6MKB4J.js.map +7 -0
- package/dist/chunks/delete-XVYLEMHB.js +3 -0
- package/dist/chunks/delete-XVYLEMHB.js.map +7 -0
- package/dist/chunks/doctor-2W65SQJS.js +3 -0
- package/dist/chunks/doctor-2W65SQJS.js.map +7 -0
- package/dist/chunks/get-ZP66WVWT.js +3 -0
- package/dist/chunks/get-ZP66WVWT.js.map +7 -0
- package/dist/chunks/inspect-HV2SQPTB.js +3 -0
- package/dist/chunks/inspect-HV2SQPTB.js.map +7 -0
- package/dist/chunks/inspect-PQCV7LQT.js +3 -0
- package/dist/chunks/inspect-PQCV7LQT.js.map +7 -0
- package/dist/chunks/login-GQ4PM7SA.js +4 -0
- package/dist/chunks/login-GQ4PM7SA.js.map +7 -0
- package/dist/chunks/logout-7N23QWWM.js +3 -0
- package/dist/chunks/logout-7N23QWWM.js.map +7 -0
- package/dist/chunks/ls-7XYH5VPL.js +3 -0
- package/dist/chunks/ls-7XYH5VPL.js.map +7 -0
- package/dist/chunks/ls-ARM57VNR.js +3 -0
- package/dist/chunks/ls-ARM57VNR.js.map +7 -0
- package/dist/chunks/map-error-7POTPJ7R.js +3 -0
- package/dist/chunks/map-error-7POTPJ7R.js.map +7 -0
- package/dist/chunks/put-EHRNCZHT.js +3 -0
- package/dist/chunks/put-EHRNCZHT.js.map +7 -0
- package/dist/chunks/resume-RLZB7L3C.js +3 -0
- package/dist/chunks/resume-RLZB7L3C.js.map +7 -0
- package/dist/chunks/secp256k1-2OHXXNYZ.js +3 -0
- package/dist/chunks/secp256k1-2OHXXNYZ.js.map +7 -0
- package/dist/chunks/skills.run-IDY347MW.js +5 -0
- package/dist/chunks/skills.run-IDY347MW.js.map +7 -0
- package/dist/chunks/status-D4CXVYRA.js +3 -0
- package/dist/chunks/status-D4CXVYRA.js.map +7 -0
- package/dist/main.js +3 -0
- package/dist/main.js.map +7 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +52 -3
- package/skills/fil/SKILL.md +28 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../clipact/src/agent.ts", "../../../clipact/src/route.ts", "../../../clipact/src/spec.ts", "../../../clipact/src/completion.ts", "../../../clipact/src/help.ts", "../../../clipact/src/discovery.ts", "../../../clipact/src/input.ts", "../../../clipact/src/io.ts", "../../../clipact/src/mode.ts", "../../../clipact/src/session.ts", "../../../clipact/src/cli.ts"],
|
|
4
|
+
"sourcesContent": ["/** Environment variables read by the framework. */\nexport type Env = Record<string, string | undefined>\n\n/** Vendor variables that identify a coding agent, checked after `AI_AGENT` and `AGENT`. */\nconst VENDOR_VARIABLES: [variable: string, agent: string][] = [\n ['CLAUDECODE', 'claude-code'],\n ['CLAUDE_CODE_CHILD_SESSION', 'claude-code'],\n ['CODEX_THREAD_ID', 'codex'],\n ['CODEX_CI', 'codex'],\n ['GEMINI_CLI', 'gemini-cli'],\n ['CURSOR_AGENT', 'cursor'],\n ['OPENCODE', 'opencode'],\n ['AUGMENT_AGENT', 'augment'],\n ['COPILOT_AGENT_SESSION_ID', 'copilot'],\n ['AMP_CURRENT_THREAD_ID', 'amp'],\n ['QWEN_CODE_SESSION_ID', 'qwen-code'],\n]\n\n/** Returns `true` for a set variable that is not an explicit off value. */\nexport function isSet(value: string | undefined): value is string {\n return (\n value !== undefined && value !== '' && value !== '0' && value !== 'false'\n )\n}\n\n/**\n * Detects a coding agent from the environment and returns its name.\n *\n * Detection is heuristic and only changes presentation defaults.\n *\n * @see https://github.com/hugomrdias/fil/blob/main/docs/agent-cli/guidelines.md#agent-detection-and-help\n */\nexport function detectAgent(env: Env): string | false {\n for (const variable of ['AI_AGENT', 'AGENT']) {\n const value = env[variable]\n if (isSet(value)) {\n return value === '1' || value === 'true' ? 'unknown' : value\n }\n }\n for (const [variable, agent] of VENDOR_VARIABLES) {\n if (isSet(env[variable])) {\n return agent\n }\n }\n return false\n}\n\n/** Parses common boolean spellings: `true`, `false`, `1`, and `0`. */\nexport function parseBoolean(raw: string): boolean | undefined {\n if (raw === 'true' || raw === '1') {\n return true\n }\n if (raw === 'false' || raw === '0') {\n return false\n }\n return undefined\n}\n", "import type { AnyCommand, CliOptions, CommandNode, Group } from './define.ts'\nimport { CliError, DefinitionError, type Next } from './errors.ts'\n\n/** A flag owned by the framework rather than a command's input. */\nexport interface FrameworkFlag {\n /** Name without dashes. */\n name: string\n description: string\n /** Placeholder and choices when the flag takes a value. */\n value?: { label: string; choices?: readonly string[] }\n /** Single-letter alias, such as `h` for `-h`. */\n short?: string\n /** Also accepted as `--no-<name>`. */\n negatable?: boolean\n /** Accepted anywhere, including by built-in commands. */\n global?: boolean\n /** Accepted only by commands that support it. */\n when?: (command: AnyCommand) => boolean\n}\n\n/**\n * Every framework flag, command flags first. Parsing, routing, help, and\n * completion all derive from this list.\n */\nexport const FRAMEWORK_FLAGS: readonly FrameworkFlag[] = [\n {\n name: 'yes',\n description: 'Confirm without a prompt',\n when: (command) => Boolean(command.confirm),\n },\n {\n name: 'dry-run',\n description: 'Report what would happen without side effects',\n when: (command) => command.dryRun === true,\n },\n {\n name: 'input',\n description: 'Read input fields from a JSON object',\n value: { label: '<file|->' },\n },\n {\n name: 'json',\n description: 'Write one JSON result to stdout',\n global: true,\n },\n {\n name: 'format',\n description: 'Choose the output format',\n value: { label: '<human|json>', choices: ['human', 'json'] },\n global: true,\n },\n {\n name: 'agent',\n description: 'Override agent detection',\n negatable: true,\n global: true,\n },\n {\n name: 'debug',\n description: 'Show input sources and stack traces on stderr',\n global: true,\n },\n { name: 'help', description: 'Show help', short: 'h', global: true },\n { name: 'version', description: 'Show the version', global: true },\n]\n\n/** Returns the raw tokens of a flag, such as `-h` and `--help`. */\nexport function flagTokens(flag: FrameworkFlag): string[] {\n return [\n ...(flag.short ? [`-${flag.short}`] : []),\n `--${flag.name}`,\n ...(flag.negatable ? [`--no-${flag.name}`] : []),\n ]\n}\n\n/**\n * Classifies a raw argument as a framework flag that takes its value from\n * the next argument (`value`), one complete in itself (`switch`), or neither.\n */\nexport function frameworkToken(arg: string): 'value' | 'switch' | undefined {\n for (const flag of FRAMEWORK_FLAGS) {\n if (flag.value) {\n if (arg === `--${flag.name}`) {\n return 'value'\n }\n if (arg.startsWith(`--${flag.name}=`)) {\n return 'switch'\n }\n } else if (flagTokens(flag).includes(arg)) {\n return 'switch'\n }\n }\n return undefined\n}\n\n/** Framework flags that decide the mode and fast paths, scanned before parsing. */\nexport interface GlobalFlags {\n json: boolean\n format: string | undefined\n agent: boolean | undefined\n debug: boolean\n help: boolean\n version: boolean\n}\n\n/** A positional word before any non-framework option. */\ninterface Word {\n index: number\n value: string\n}\n\n/** The result of routing argv through the command tree. */\nexport type Route =\n | { kind: 'node'; node: CommandNode; path: string[]; rest: string[] }\n | {\n kind: 'unknown'\n group: Group\n path: string[]\n word: string\n suggestion: string | undefined\n }\n\n/** Collects framework flags from anywhere before `--`. */\nexport function scanGlobalFlags(args: string[]): GlobalFlags {\n const flags: GlobalFlags = {\n json: false,\n format: undefined,\n agent: undefined,\n debug: false,\n help: false,\n version: false,\n }\n for (let index = 0; index < args.length; index++) {\n const arg = args[index] as string\n if (arg === '--') {\n break\n }\n if (arg === '--json') {\n flags.json = true\n } else if (arg === '--agent') {\n flags.agent = true\n } else if (arg === '--no-agent') {\n flags.agent = false\n } else if (arg === '--debug') {\n flags.debug = true\n } else if (arg === '--help' || arg === '-h') {\n flags.help = true\n } else if (arg === '--version') {\n flags.version = true\n } else if (arg === '--format') {\n flags.format = args[index + 1] ?? ''\n index++\n } else if (arg.startsWith('--format=')) {\n flags.format = arg.slice('--format='.length)\n }\n }\n return flags\n}\n\n/** Returns the leading positional words, skipping framework flags. */\nfunction leadingWords(args: string[]): Word[] {\n const words: Word[] = []\n for (let index = 0; index < args.length; index++) {\n const arg = args[index] as string\n if (arg === '--') {\n break\n }\n if (arg.startsWith('-') && arg !== '-') {\n const token = frameworkToken(arg)\n if (!token) {\n break\n }\n if (token === 'value') {\n index++\n }\n continue\n }\n words.push({ index, value: arg })\n }\n return words\n}\n\n/** Finds a node by its canonical path below `root`. */\nexport function findNode(root: Group, path: string[]): CommandNode | undefined {\n let node: CommandNode = root\n for (const name of path) {\n if (node.kind !== 'group') {\n return undefined\n }\n const child: CommandNode | undefined = node.commands.find(\n (candidate) => candidate.name === name\n )\n if (!child) {\n return undefined\n }\n node = child\n }\n return node\n}\n\n/**\n * Routes leading positional words through groups until a command is\n * reached, resolving aliases.\n */\nexport function route(\n root: Group,\n args: string[],\n aliases: Record<string, string> = {}\n): Route {\n const words = leadingWords(args)\n let node: CommandNode = root\n const path: string[] = []\n const consumed: number[] = []\n let position = 0\n\n const sortedAliases = Object.entries(aliases).sort(\n ([a], [b]) => b.split(' ').length - a.split(' ').length\n )\n for (const [alias, target] of sortedAliases) {\n const aliasWords = alias.split(' ')\n if (aliasWords.every((word, index) => words[index]?.value === word)) {\n const targetPath = target.split(' ')\n const resolved = findNode(root, targetPath)\n if (!resolved) {\n throw new DefinitionError(alias, `alias target \"${target}\" not found`)\n }\n node = resolved\n path.push(...targetPath)\n consumed.push(...words.slice(0, aliasWords.length).map((w) => w.index))\n position = aliasWords.length\n break\n }\n }\n\n while (node.kind === 'group' && position < words.length) {\n const word = words[position] as Word\n const group: Group = node\n const child = group.commands.find(\n (candidate) => candidate.name === word.value\n )\n if (!child) {\n return {\n kind: 'unknown',\n group,\n path,\n word: word.value,\n suggestion: closest(\n word.value,\n group.commands.map((candidate) => candidate.name)\n ),\n }\n }\n node = child\n path.push(child.name)\n consumed.push(word.index)\n position++\n }\n return { kind: 'node', node, path, rest: without(args, consumed) }\n}\n\n/** Builds the error for an unknown command word. */\nexport function unknownCommand(\n cli: CliOptions,\n routed: Extract<Route, { kind: 'unknown' }>\n): CliError {\n const attempted = [cli.name, ...routed.path, routed.word].join(' ')\n const next: Next[] = []\n if (routed.suggestion) {\n next.push({\n by: 'agent',\n command: [cli.name, ...routed.path, routed.suggestion, '--help'].join(\n ' '\n ),\n description: `Show help for \"${routed.suggestion}\"`,\n })\n }\n next.push({\n by: 'agent',\n command: `${cli.name} schema --list`,\n description: 'List all commands',\n })\n return new CliError({\n code: 'invalid_input',\n message: `Unknown command \"${attempted}\".${routed.suggestion ? ` Did you mean \"${routed.suggestion}\"?` : ''}`,\n retryable: false,\n next,\n })\n}\n\n/** Returns `args` without the given indexes. */\nfunction without(args: string[], indexes: number[]): string[] {\n return args.filter((_, index) => !indexes.includes(index))\n}\n\n/** Returns the candidate within a small edit distance of `input`, if any. */\nexport function closest(\n input: string,\n candidates: string[]\n): string | undefined {\n let best: string | undefined\n let bestDistance = Math.max(2, Math.floor(input.length / 3)) + 1\n for (const candidate of candidates) {\n const distance = editDistance(input, candidate)\n if (distance < bestDistance) {\n best = candidate\n bestDistance = distance\n }\n }\n return best\n}\n\n/** Levenshtein distance between two strings. */\nfunction editDistance(a: string, b: string): number {\n let previous = Array.from({ length: b.length + 1 }, (_, index) => index)\n for (let i = 1; i <= a.length; i++) {\n const current = [i]\n for (let j = 1; j <= b.length; j++) {\n current[j] = Math.min(\n (previous[j] as number) + 1,\n (current[j - 1] as number) + 1,\n (previous[j - 1] as number) + (a[i - 1] === b[j - 1] ? 0 : 1)\n )\n }\n previous = current\n }\n return previous[b.length] as number\n}\n", "import type { AnyCommand, Schema } from './define.ts'\nimport { BUILTIN_ERROR_CODES, DefinitionError } from './errors.ts'\nimport { fromJsonSchema } from './json-schema.ts'\nimport { FRAMEWORK_FLAGS } from './route.ts'\n\n/** A JSON Schema object as produced by Standard JSON Schema converters. */\nexport type JsonSchema = Record<string, unknown>\n\n/** The JSON type a field's command-line value is converted to. */\nexport type FieldKind =\n | 'string'\n | 'number'\n | 'integer'\n | 'boolean'\n | 'array'\n | 'object'\n | 'unknown'\n\n/** Everything the runtime needs to know about one input field. */\nexport interface FieldSpec {\n name: string\n /** Flag name without dashes, such as `private-key` for `privateKey`. */\n flag: string\n kind: FieldKind\n /** Kind of array items. */\n itemKind: FieldKind\n required: boolean\n description: string | undefined\n default: unknown\n enum: unknown[] | undefined\n positional: boolean\n /** The last positional, collecting remaining arguments. */\n variadic: boolean\n env: string | undefined\n secret: boolean\n}\n\n/** A command's resolved fields and JSON Schemas. */\nexport interface CommandSpec {\n path: string\n command: AnyCommand\n input: Schema\n inputJsonSchema: JsonSchema\n /** Converted on first use; only `schema` and agent help read it. */\n readonly outputJsonSchema: JsonSchema | undefined\n fields: FieldSpec[]\n positionals: FieldSpec[]\n byName: Map<string, FieldSpec>\n byFlag: Map<string, FieldSpec>\n /** Declared error codes followed by the built-in ones. */\n errors: string[]\n}\n\n/** The JSON Schema dialect `schema` publishes. */\nexport const JSON_SCHEMA_TARGET = { target: 'draft-2020-12' } as const\n\n/** Standard schema for commands without `input`: an empty object. */\nexport const EMPTY_INPUT: Schema = fromJsonSchema({\n type: 'object',\n properties: {},\n additionalProperties: false,\n})\n\n/**\n * Converts a camelCase field name to a flag name: `privateKey` to\n * `private-key`, and acronyms as one word, `rpcURL` to `rpc-url`.\n */\nexport function toFlag(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')\n .toLowerCase()\n}\n\nconst cache = new WeakMap<AnyCommand, CommandSpec>()\n\n/**\n * Resolves a command's fields from its input JSON Schema and checks the\n * definition. Runs only for the command being executed or described, so\n * startup never converts every schema.\n */\nexport function resolveSpec(command: AnyCommand, path: string): CommandSpec {\n const cached = cache.get(command)\n if (cached) {\n return cached\n }\n const input: Schema = command.input ?? EMPTY_INPUT\n const inputJsonSchema =\n input['~standard'].jsonSchema.input(JSON_SCHEMA_TARGET)\n if (inputJsonSchema.type !== 'object') {\n throw new DefinitionError(path, 'input must be an object schema')\n }\n const properties = (inputJsonSchema.properties ?? {}) as Record<\n string,\n JsonSchema\n >\n const required = new Set((inputJsonSchema.required ?? []) as string[])\n const positionalNames: string[] = command.positionals ?? []\n const secrets = new Set<string>(command.secrets ?? [])\n const env: Record<string, string | undefined> = command.env ?? {}\n\n for (const name of [...positionalNames, ...secrets, ...Object.keys(env)]) {\n if (!(name in properties)) {\n throw new DefinitionError(path, `\"${name}\" is not an input field`)\n }\n }\n\n const fields: FieldSpec[] = Object.entries(properties).map(\n ([name, schema]) => {\n const resolved = deref(schema, inputJsonSchema)\n const kind = kindOf(resolved, inputJsonSchema)\n const items =\n kind === 'array'\n ? deref((resolved.items ?? {}) as JsonSchema, inputJsonSchema)\n : undefined\n const index = positionalNames.indexOf(name)\n return {\n name,\n flag: toFlag(name),\n kind,\n itemKind: items ? kindOf(items, inputJsonSchema) : 'unknown',\n required: required.has(name),\n description:\n (resolved.description as string | undefined) ??\n (schema.description as string | undefined),\n default: schema.default ?? resolved.default,\n enum: (resolved.enum ?? items?.enum) as unknown[] | undefined,\n positional: index !== -1,\n variadic:\n index !== -1 &&\n index === positionalNames.length - 1 &&\n kind === 'array',\n env: env[name],\n secret: secrets.has(name),\n }\n }\n )\n\n const byName = new Map(fields.map((field) => [field.name, field]))\n const positionals = positionalNames.map(\n (name) => byName.get(name) as FieldSpec\n )\n let seenOptional = false\n for (const [index, field] of positionals.entries()) {\n if (field.kind === 'array' && index !== positionals.length - 1) {\n throw new DefinitionError(\n path,\n `only the last positional may be an array (\"${field.name}\")`\n )\n }\n if (field.kind === 'boolean' || field.kind === 'object') {\n throw new DefinitionError(\n path,\n `positional \"${field.name}\" must not be a ${field.kind}`\n )\n }\n if (field.secret) {\n throw new DefinitionError(\n path,\n `secret \"${field.name}\" cannot be positional`\n )\n }\n if (field.required && seenOptional) {\n throw new DefinitionError(\n path,\n `required positional \"${field.name}\" follows an optional one`\n )\n }\n seenOptional ||= !field.required\n }\n\n const byFlag = new Map<string, FieldSpec>()\n for (const field of fields) {\n if (FRAMEWORK_FLAGS.some((flag) => flag.name === field.flag)) {\n throw new DefinitionError(\n path,\n `field \"${field.name}\" clashes with the framework flag --${field.flag}`\n )\n }\n const other = byFlag.get(field.flag)\n if (other) {\n throw new DefinitionError(\n path,\n `fields \"${other.name}\" and \"${field.name}\" both use --${field.flag}`\n )\n }\n byFlag.set(field.flag, field)\n }\n\n let outputJsonSchema: JsonSchema | undefined\n const spec: CommandSpec = {\n path,\n command,\n input,\n inputJsonSchema,\n get outputJsonSchema() {\n outputJsonSchema ??=\n command.output?.['~standard'].jsonSchema.output(JSON_SCHEMA_TARGET)\n return outputJsonSchema\n },\n fields,\n positionals,\n byName,\n byFlag,\n errors: [...(command.errors ?? []), ...BUILTIN_ERROR_CODES],\n }\n cache.set(command, spec)\n return spec\n}\n\n/** Follows a local `$ref` such as `#/$defs/Network`. */\nfunction deref(schema: JsonSchema, root: JsonSchema): JsonSchema {\n const ref = schema.$ref\n if (typeof ref !== 'string' || !ref.startsWith('#/')) {\n return schema\n }\n let target: unknown = root\n for (const part of ref.slice(2).split('/')) {\n target = (target as Record<string, unknown> | undefined)?.[part]\n }\n return (target as JsonSchema | undefined) ?? schema\n}\n\n/** Returns the single non-null JSON type a value must have, or `unknown`. */\nfunction kindOf(schema: JsonSchema, root: JsonSchema): FieldKind {\n const kinds = new Set<FieldKind>()\n const visit = (node: JsonSchema) => {\n const resolved = deref(node, root)\n const branches = (resolved.anyOf ?? resolved.oneOf) as\n | JsonSchema[]\n | undefined\n if (branches) {\n for (const branch of branches) {\n visit(branch)\n }\n return\n }\n const values =\n 'const' in resolved\n ? [resolved.const]\n : Array.isArray(resolved.enum)\n ? resolved.enum\n : undefined\n if (values) {\n for (const value of values) {\n if (value !== null) {\n kinds.add(kindOfValue(value))\n }\n }\n return\n }\n const types = ([] as unknown[]).concat(resolved.type ?? [])\n if (types.length === 0) {\n kinds.add('unknown')\n }\n for (const type of types) {\n if (type !== 'null') {\n kinds.add(type as FieldKind)\n }\n }\n }\n visit(schema)\n if (kinds.size === 2 && kinds.has('integer') && kinds.has('number')) {\n return 'number'\n }\n return kinds.size === 1 ? ([...kinds][0] as FieldKind) : 'unknown'\n}\n\n/** Maps a non-null JavaScript value to its JSON type. */\nfunction kindOfValue(value: unknown): FieldKind {\n if (Array.isArray(value)) {\n return 'array'\n }\n const type = typeof value\n return type === 'string' ||\n type === 'number' ||\n type === 'boolean' ||\n type === 'object'\n ? type\n : 'unknown'\n}\n", "import {\n type AnyCommand,\n type CliOptions,\n type Command,\n commandPathField,\n defineCommand,\n defineHandler,\n type Group,\n isBuiltin,\n markBuiltin,\n} from './define.ts'\nimport { CliError, DefinitionError } from './errors.ts'\nimport { fromJsonSchema } from './json-schema.ts'\nimport {\n FRAMEWORK_FLAGS,\n type FrameworkFlag,\n findNode,\n flagTokens,\n route,\n} from './route.ts'\nimport { type CommandSpec, type FieldSpec, resolveSpec } from './spec.ts'\n\n/** Shells with a completion script. */\nconst SHELLS = ['bash', 'zsh', 'fish'] as const\n\n/** A shell supported by `completion`. */\ntype Shell = (typeof SHELLS)[number]\n\n/** The hidden built-in the completion scripts call on each Tab. */\nexport const COMPLETE_COMMAND = '__complete'\n\n/** Output that tells the completion script to complete file paths. */\nconst FILES = ':files'\n\n/** A completion candidate. */\ninterface Candidate {\n value: string\n description?: string\n}\n\n/** Values completed for an option or positional, or file paths. */\ntype Values = Candidate[] | typeof FILES\n\n/** A flag a command accepts, for completion. */\ninterface Option {\n flag: string\n description: string | undefined\n /** The next argument is the flag's value. */\n takesValue: boolean\n values: Values\n /** May be given more than once. */\n repeatable: boolean\n /** Offered as a candidate; positional fields are accepted but not offered. */\n offered: boolean\n}\n\n/**\n * Lists the framework flags a command accepts, or the global ones for a\n * group. `--version` is offered only at the root, `-h` never.\n */\nfunction frameworkOptions(\n command: AnyCommand | undefined,\n isRoot = false\n): Option[] {\n const accepted = (flag: FrameworkFlag) =>\n flag.global\n ? flag.name !== 'version' || isRoot\n : command !== undefined && (flag.when?.(command) ?? true)\n return FRAMEWORK_FLAGS.filter(accepted).flatMap((flag) =>\n flagTokens(flag)\n .filter((token) => token.startsWith('--'))\n .map((token) => ({\n flag: token,\n description: flag.description,\n takesValue: flag.value !== undefined,\n values: flag.value\n ? (flag.value.choices?.map((value) => ({ value })) ?? FILES)\n : [],\n repeatable: false,\n offered: true,\n }))\n )\n}\n\n/**\n * Answers the hidden `__complete` built-in: `words` are the arguments after\n * the binary name, the last being the word under the cursor. Returns one\n * `value<TAB>description` line per candidate, or `:files` for file paths.\n */\nexport function complete(\n cli: CliOptions,\n root: Group,\n words: string[]\n): string {\n const current = words.at(-1) ?? ''\n let values: Values\n try {\n values = candidates(cli, root, words.slice(0, -1), current)\n } catch {\n // A broken definition must not print errors into the user's prompt.\n return ''\n }\n if (values === FILES) {\n return `${FILES}\\n`\n }\n return values\n .filter(({ value }) => value.startsWith(current) && !/[\\t\\n\\r]/.test(value))\n .map(\n ({ value, description }) =>\n `${value}${description ? `\\t${description.replace(/\\s+/g, ' ')}` : ''}\\n`\n )\n .join('')\n}\n\n/** Lists candidates for the word after `before`. */\nfunction candidates(\n cli: CliOptions,\n root: Group,\n before: string[],\n current: string\n): Values {\n const routed = route(root, before, cli.aliases)\n if (routed.kind === 'unknown') {\n return []\n }\n const { node, path, rest } = routed\n if (node.kind === 'group') {\n if (current.startsWith('-')) {\n return flagCandidates(frameworkOptions(undefined, path.length === 0), [])\n }\n return children(cli, node, path.length === 0)\n }\n return commandCandidates(\n cli,\n root,\n resolveSpec(node, path.join(' ')),\n rest,\n current\n )\n}\n\n/** Lists the commands of a group, with aliases and built-ins at the root. */\nfunction children(cli: CliOptions, group: Group, isRoot: boolean): Candidate[] {\n const list: Candidate[] = group.commands\n .filter((child) => !isBuiltin(child))\n .map((child) => ({ value: child.name, description: child.description }))\n if (!isRoot) {\n return list\n }\n for (const [alias, target] of Object.entries(cli.aliases ?? {})) {\n if (!alias.includes(' ')) {\n list.push({ value: alias, description: `Alias for ${target}` })\n }\n }\n for (const child of group.commands) {\n if (isBuiltin(child)) {\n list.push({ value: child.name, description: child.description })\n }\n }\n return list\n}\n\n/** Lists candidates within a command: flag values, flags, or positionals. */\nfunction commandCandidates(\n cli: CliOptions,\n root: Group,\n spec: CommandSpec,\n rest: string[],\n current: string\n): Values {\n const options = commandOptions(spec)\n const byFlag = new Map(options.map((option) => [option.flag, option]))\n const used: string[] = []\n const positionals: string[] = []\n let pending: Option | undefined\n let terminated = false\n for (const arg of rest) {\n if (pending) {\n pending = undefined\n } else if (terminated || arg === '-' || !arg.startsWith('-')) {\n positionals.push(arg)\n } else if (arg === '--') {\n terminated = true\n } else {\n const flag = arg.split('=')[0] as string\n used.push(flag)\n const option = byFlag.get(flag)\n if (option?.takesValue && !arg.includes('=')) {\n pending = option\n }\n }\n }\n if (pending) {\n return pending.values\n }\n if (!terminated && current.startsWith('-')) {\n const equals = current.indexOf('=')\n if (equals === -1) {\n return flagCandidates(options, used)\n }\n const values = byFlag.get(current.slice(0, equals))?.values\n if (!values || values === FILES) {\n return []\n }\n const prefix = current.slice(0, equals + 1)\n return values.map((candidate) => ({ value: `${prefix}${candidate.value}` }))\n }\n const last = spec.positionals.at(-1)\n const field =\n spec.positionals[positionals.length] ?? (last?.variadic ? last : undefined)\n if (field && field.name === commandPathField(spec.command)) {\n // The words given so far for this field, such as a group name.\n const words = positionals.slice(spec.positionals.indexOf(field))\n const target = findNode(root, words)\n return target?.kind === 'group' ? children(cli, target, false) : []\n }\n if (field) {\n return fieldValues(field)\n }\n return terminated || current !== '' ? [] : flagCandidates(options, used)\n}\n\n/** Lists the offered flags that may still be given. */\nfunction flagCandidates(options: Option[], used: string[]): Candidate[] {\n return options\n .filter(\n (option) =>\n option.offered && (option.repeatable || !used.includes(option.flag))\n )\n .map(({ flag, description }) => ({ value: flag, description }))\n}\n\n/** Lists every flag a command accepts, framework flags last. */\nfunction commandOptions(spec: CommandSpec): Option[] {\n const options: Option[] = spec.fields\n .filter((field) => !field.secret)\n .map((field) => ({\n flag: `--${field.flag}`,\n description: field.description,\n takesValue: field.kind !== 'boolean',\n values: fieldValues(field),\n repeatable: field.kind === 'array',\n offered: !field.positional,\n }))\n return [...options, ...frameworkOptions(spec.command)]\n}\n\n/** Lists the values of a field: its enum, file paths for strings, or nothing. */\nfunction fieldValues(field: FieldSpec): Values {\n if (field.enum) {\n return field.enum.map((value) => ({ value: String(value) }))\n }\n const kind = field.kind === 'array' ? field.itemKind : field.kind\n return kind === 'string' || kind === 'unknown' ? FILES : []\n}\n\n/**\n * Returns the completion script for a shell. The script asks the CLI for\n * candidates on each Tab through `__complete`, so it never goes stale.\n *\n * @see https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html\n * @see https://zsh.sourceforge.io/Doc/Release/Completion-System.html\n * @see https://fishshell.com/docs/current/completions.html\n */\nexport function completionScript(name: string, shell: Shell): string {\n if (!/^[A-Za-z0-9._-]+$/.test(name)) {\n throw new DefinitionError(\n 'completion',\n `the CLI name \"${name}\" cannot be used in a completion script`\n )\n }\n const id = name.replace(/[^A-Za-z0-9_]/g, '_')\n const header = `# ${shell} completion for ${name}, printed by \\`${name} completion ${shell}\\`.\\n# Candidates come from \\`${name} ${COMPLETE_COMMAND}\\`, so they match the installed version.\\n`\n if (shell === 'bash') {\n return `${header}_${id}_complete() {\n local line=\"\\${COMP_LINE:0:COMP_POINT}\" cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n local -a words\n read -ra words <<< \"$line\"\n if [[ -z $line || $line == *[[:space:]] ]]; then\n words+=('')\n fi\n local output\n output=\"$(${name} ${COMPLETE_COMMAND} \"\\${words[@]:1}\" 2>/dev/null)\" || return 0\n COMPREPLY=()\n if [[ $output == '${FILES}' ]]; then\n # compopt (bash 4+) quotes names and marks directories; bash 3.2 quotes here.\n local file quote=\n compopt -o filenames 2>/dev/null || quote=1\n while IFS= read -r file; do\n [[ -n $quote ]] && printf -v file '%q' \"$file\"\n COMPREPLY+=(\"$file\")\n done < <(compgen -f -- \"$cur\")\n return 0\n fi\n # Bash splits words at \"=\" and \":\"; complete only the part after them.\n local last=\"\\${words[\\${#words[@]}-1]}\" prefix candidate\n prefix=\"\\${last%\"$cur\"}\"\n while IFS=$'\\\\t' read -r candidate _; do\n if [[ -n $candidate && $candidate == \"$prefix\"* ]]; then\n COMPREPLY+=(\"\\${candidate#\"$prefix\"}\")\n fi\n done <<< \"$output\"\n}\ncomplete -F _${id}_complete ${name}\n`\n }\n if (shell === 'zsh') {\n return `#compdef ${name}\n${header}_${id}() {\n local -a lines items\n local line value description\n lines=(\"\\${(@f)$(${name} ${COMPLETE_COMMAND} \"\\${(@)words[2,CURRENT]}\" 2>/dev/null)}\")\n if [[ \\${lines[1]} == '${FILES}' ]]; then\n _files\n return\n fi\n for line in \"\\${lines[@]}\"; do\n [[ -n $line ]] || continue\n value=\\${line%%$'\\\\t'*}\n description=\\${line#*$'\\\\t'}\n if [[ $description == \"$line\" ]]; then\n items+=(\"\\${value//:/\\\\\\\\:}\")\n else\n items+=(\"\\${value//:/\\\\\\\\:}:$description\")\n fi\n done\n (( \\${#items} )) && _describe -t values value items\n}\nif [[ \"\\${funcstack[1]}\" == _${id} ]]; then\n _${id} \"$@\"\nelse\n compdef _${id} ${name}\nfi\n`\n }\n return `${header}function __${id}_complete\n set -l tokens (commandline -opc)\n set -e tokens[1]\n set -l current (commandline -ct)\n set -l output (${name} ${COMPLETE_COMMAND} $tokens \"$current\" 2>/dev/null)\n if test \"$output[1]\" = '${FILES}'\n __fish_complete_path \"$current\"\n return\n end\n for line in $output\n echo $line\n end\nend\ncomplete -c ${name} -f -a '(__${id}_complete)'\n`\n}\n\n/** Installation steps, printed by `completion` without a shell on a terminal. */\nfunction completionHelp(name: string): string {\n return `${name} completion: Print a shell completion script\n\nUsage:\n ${name} completion <${SHELLS.join('|')}>\n\nInstall:\n bash Add to ~/.bashrc: eval \"$(${name} completion bash)\"\n zsh Add to ~/.zshrc after compinit: source <(${name} completion zsh)\n fish ${name} completion fish > ~/.config/fish/completions/${name}.fish\n\nThe script asks ${name} for candidates on each Tab, so it stays current after upgrades.\n`\n}\n\n/** Input of the built-in `completion` command. */\ninterface CompletionInput {\n shell?: Shell\n}\n\nconst completionInput = fromJsonSchema<CompletionInput>({\n type: 'object',\n properties: {\n shell: {\n type: 'string',\n enum: SHELLS,\n description: 'Shell to print the script for',\n },\n },\n additionalProperties: false,\n})\n\n/**\n * Builds the built-in `completion` command. Its script is plain text in\n * every mode, because `eval \"$(acme completion bash)\"` reads it from a pipe.\n */\nexport function completionCommand(\n cli: CliOptions\n): Command<typeof completionInput, undefined> {\n const command: Command<typeof completionInput, undefined> = defineCommand({\n name: 'completion',\n description: 'Print a bash, zsh, or fish completion script',\n examples: [\n `eval \"$(${cli.name} completion bash)\"`,\n `source <(${cli.name} completion zsh)`,\n `${cli.name} completion fish > ~/.config/fish/completions/${cli.name}.fish`,\n ],\n input: completionInput,\n positionals: ['shell'],\n readOnly: true,\n human: (data) => String(data.text),\n handler: async () => ({ default: handler }),\n })\n const handler = defineHandler(command, ({ input, mode, ok }) => {\n if (input.shell) {\n return ok({ text: completionScript(cli.name, input.shell) })\n }\n if (mode.format === 'human') {\n return ok({ text: completionHelp(cli.name) })\n }\n throw new CliError({\n code: 'invalid_input',\n message: `Expected one shell: ${SHELLS.join(', ')}.`,\n details: [\n {\n path: 'shell',\n source: 'positional',\n message: `Expected one of ${SHELLS.join(', ')}`,\n },\n ],\n next: [\n {\n by: 'user',\n command: `${cli.name} completion --help`,\n description: 'Show how to install completions',\n },\n ],\n })\n })\n return markBuiltin(command, { plainText: true })\n}\n", "import {\n type AnyCommand,\n type CliOptions,\n type CommandNode,\n type Group,\n isBuiltin,\n} from './define.ts'\nimport { FRAMEWORK_FLAGS, type FrameworkFlag, flagTokens } from './route.ts'\nimport {\n type CommandSpec,\n type FieldSpec,\n type JsonSchema,\n resolveSpec,\n} from './spec.ts'\n\n/** The output contract, repeated in agent help. */\nconst CONTRACT =\n 'Output is one JSON object on stdout: \"data\" on success (exit code 0) or \"error\" on failure (exit code 1), then optional \"next\" steps.'\n\n/** A leaf command with its full path. */\nexport interface Leaf {\n path: string\n command: AnyCommand\n}\n\n/** Lists every command below `node` with its path, depth first, skipping built-ins. */\nexport function leaves(node: CommandNode, prefix: string[] = []): Leaf[] {\n if (node.kind === 'command') {\n return [{ path: prefix.join(' '), command: node }]\n }\n return node.commands\n .filter((child) => !isBuiltin(child))\n .flatMap((child) => leaves(child, [...prefix, child.name]))\n}\n\n/** Formats rows as two aligned columns. */\nfunction columns(rows: [string, string][], indent = ' '): string {\n const width = Math.min(32, Math.max(0, ...rows.map(([left]) => left.length)))\n return rows\n .map(([left, right]) =>\n right\n ? left.length > width\n ? `${indent}${left}\\n${indent}${' '.repeat(width + 2)}${right}`\n : `${indent}${left.padEnd(width)} ${right}`\n : `${indent}${left}`\n )\n .join('\\n')\n}\n\n/** Formats a framework flag as a help row, such as `-h, --help`. */\nfunction flagRow(flag: FrameworkFlag): [string, string] {\n const tokens = flagTokens(flag).join(', ')\n return [\n flag.value ? `${tokens} ${flag.value.label}` : tokens,\n flag.description,\n ]\n}\n\n/** Returns the value placeholder for a field, such as `<mainnet|calibration>`. */\nfunction valueLabel(field: FieldSpec): string {\n if (field.enum && field.enum.length <= 6) {\n return `<${field.enum.join('|')}>`\n }\n const kind = field.kind === 'array' ? field.itemKind : field.kind\n return `<${kind === 'unknown' ? 'value' : kind}>`\n}\n\n/** Returns the positional placeholders of a command, such as `<path>` and `[tags...]`. */\nfunction positionalUsage(spec: CommandSpec): string[] {\n return spec.positionals.map((field) => {\n const name = field.variadic ? `${field.name}...` : field.name\n return field.required ? `<${name}>` : `[${name}]`\n })\n}\n\n/** Returns the usage line for a command. */\nexport function usage(cli: CliOptions, spec: CommandSpec): string {\n const parts = [cli.name, spec.path, ...positionalUsage(spec)]\n for (const field of spec.fields) {\n if (!(field.positional || field.secret) && field.required) {\n parts.push(`--${field.flag} ${valueLabel(field)}`)\n }\n }\n if (\n spec.fields.some(\n (field) => !(field.positional || field.secret || field.required)\n )\n ) {\n parts.push('[flags]')\n }\n return parts.join(' ')\n}\n\n/** Describes a field's constraints after its description. */\nfunction fieldNotes(field: FieldSpec): string {\n const notes: string[] = []\n if (field.required && !field.positional) {\n notes.push('required')\n }\n if (field.default !== undefined && !field.secret) {\n notes.push(`default: ${JSON.stringify(field.default)}`)\n }\n if (field.kind === 'array' && !field.positional) {\n notes.push('repeatable')\n }\n if (field.env && !field.secret) {\n notes.push(`env: ${field.env}`)\n }\n const text = field.description ?? ''\n return notes.length > 0 ? `${text} (${notes.join('; ')})`.trim() : text\n}\n\n/** Lists the output fields of a JSON Schema as `name (type)`. */\nfunction outputFields(schema: JsonSchema | undefined): string | undefined {\n const properties = schema?.properties as\n | Record<string, JsonSchema>\n | undefined\n if (!properties) {\n return undefined\n }\n return Object.entries(properties)\n .map(([name, property]) => {\n const type = ([] as unknown[]).concat(property.type ?? 'object')\n return `${name} (${type.join('|')})`\n })\n .join(', ')\n}\n\n/** Lists the side-effect properties of a command. */\nfunction sideEffects(command: AnyCommand): string[] {\n const lines: string[] = []\n if (command.readOnly) {\n lines.push('Read-only; safe to retry.')\n } else if (command.idempotent) {\n lines.push('Idempotent; safe to repeat with the same input.')\n } else {\n lines.push('Changes state; not idempotent.')\n }\n if (typeof command.confirm === 'string') {\n lines.push(\n `Requires confirmation: ${command.confirm} Pass --yes when not interactive.`\n )\n } else if (command.confirm) {\n lines.push(\n 'May require confirmation depending on input; pass --yes when not interactive.'\n )\n }\n return lines\n}\n\n/** Renders help for a command in human or agent style. */\nexport function commandHelp(\n cli: CliOptions,\n spec: CommandSpec,\n agent: boolean\n): string {\n const { command } = spec\n const sections: string[] = []\n const examples = command.examples?.length\n ? `Examples:\\n${command.examples.map((example) => ` ${example}`).join('\\n')}`\n : undefined\n const positional = spec.positionals.map((field): [string, string] => [\n field.name,\n fieldNotes(field),\n ])\n const flags = spec.fields\n .filter((field) => !(field.positional || field.secret))\n .map((field): [string, string] => [\n field.kind === 'boolean'\n ? `--${field.flag}`\n : `--${field.flag} ${valueLabel(field)}`,\n fieldNotes(field),\n ])\n for (const flag of FRAMEWORK_FLAGS) {\n if (!flag.global && (flag.when?.(command) ?? true)) {\n flags.push(flagRow(flag))\n }\n }\n const environment = spec.fields\n .filter((field) => field.secret)\n .map((field): [string, string] => [\n field.env as string,\n `${field.description ?? field.name} (secret${field.required ? ', required' : ''})`,\n ])\n\n sections.push(`${cli.name} ${spec.path}: ${command.description}`)\n if (agent && examples) {\n sections.push(examples)\n }\n sections.push(`Usage:\\n ${usage(cli, spec)}`)\n if (positional.length > 0) {\n sections.push(`Arguments:\\n${columns(positional)}`)\n }\n sections.push(`Flags:\\n${columns(flags)}`)\n if (environment.length > 0) {\n sections.push(`Environment:\\n${columns(environment)}`)\n }\n if (agent) {\n const output = outputFields(spec.outputJsonSchema)\n if (output) {\n sections.push(`Output fields: ${output}`)\n }\n sections.push(`Error codes: ${spec.errors.join(', ')}`)\n sections.push(sideEffects(command).join('\\n'))\n sections.push(`${CONTRACT}\\nFull schema: ${cli.name} schema ${spec.path}`)\n } else {\n if (examples) {\n sections.push(examples)\n }\n sections.push(sideEffects(command).join('\\n'))\n sections.push(globalFlags())\n }\n return `${sections.join('\\n\\n')}\\n`\n}\n\n/** Renders help for the root or a group. */\nexport function groupHelp(\n cli: CliOptions,\n group: Group,\n path: string[],\n agent: boolean\n): string {\n const isRoot = path.length === 0\n const sections: string[] = []\n const title = isRoot\n ? `${cli.name} ${cli.version}${cli.description ? `: ${cli.description}` : ''}`\n : `${cli.name} ${path.join(' ')}: ${group.description}`\n sections.push(title)\n sections.push(`Usage:\\n ${[cli.name, ...path].join(' ')} <command> [flags]`)\n const rows = leaves(group, path).map(({ path: leafPath, command }) => {\n const markers = [\n command.readOnly ? 'read-only' : undefined,\n command.confirm ? 'confirm' : undefined,\n ].filter(Boolean)\n return [\n leafPath,\n `${command.description}${agent && markers.length > 0 ? ` [${markers.join(', ')}]` : ''}`,\n ] as [string, string]\n })\n sections.push(`Commands:\\n${columns(rows)}`)\n if (isRoot) {\n const builtins = group.commands\n .filter((node) => node.kind === 'command' && isBuiltin(node))\n .map((command): [string, string] => [\n [\n command.name,\n ...positionalUsage(resolveSpec(command as AnyCommand, command.name)),\n ].join(' '),\n command.description,\n ])\n if (builtins.length > 0) {\n sections.push(`Built-in:\\n${columns(builtins)}`)\n }\n }\n if (agent) {\n sections.push(\n `Run \"${cli.name} <command> --help\" for examples and flags, or \"${cli.name} schema <command>\" for JSON Schemas.\\n${CONTRACT}`\n )\n } else {\n sections.push(globalFlags())\n sections.push(`Run \"${cli.name} <command> --help\" for details.`)\n }\n return `${sections.join('\\n\\n')}\\n`\n}\n\n/** Lists the framework flags. */\nfunction globalFlags(): string {\n return `Global flags:\\n${columns(\n FRAMEWORK_FLAGS.filter((flag) => flag.global).map(flagRow)\n )}`\n}\n", "import {\n type AnyCommand,\n type CliOptions,\n type Command,\n type CommandNode,\n defineCommand,\n defineHandler,\n type Group,\n markBuiltin,\n} from './define.ts'\nimport type { ErrorRegistry } from './errors.ts'\nimport { leaves } from './help.ts'\nimport { fromJsonSchema } from './json-schema.ts'\nimport { closest, route, unknownCommand } from './route.ts'\nimport {\n type CommandSpec,\n JSON_SCHEMA_TARGET,\n type JsonSchema,\n resolveSpec,\n} from './spec.ts'\n\n/** Input of the built-in `schema` command. */\ninterface SchemaInput {\n command?: string[]\n list: boolean\n}\n\nconst schemaInput = fromJsonSchema<Partial<SchemaInput>, SchemaInput>({\n type: 'object',\n properties: {\n command: {\n type: 'array',\n items: { type: 'string' },\n description: 'Path of a command or group, such as \"<group> <command>\"',\n },\n list: {\n type: 'boolean',\n default: false,\n description: 'List the commands; the default without a command path',\n },\n },\n additionalProperties: false,\n})\n\n/** The built-in `schema` command. */\ntype SchemaCommand = Command<typeof schemaInput, undefined>\n\n/**\n * JSON Schema of the result envelope: exactly one of `data` and `error`,\n * then optional `next` steps. Each command's `output` describes `data`.\n *\n * @see https://github.com/hugomrdias/fil/blob/main/docs/agent-cli/guidelines.md#result-envelope\n */\nexport const RESULT_SCHEMA: JsonSchema = Object.freeze({\n $schema: 'https://json-schema.org/draft/2020-12/schema',\n oneOf: [\n {\n type: 'object',\n properties: {\n data: {\n type: ['object', 'array'],\n description: \"The command's output, described by its output schema\",\n },\n next: { $ref: '#/$defs/next' },\n },\n required: ['data'],\n additionalProperties: false,\n },\n {\n type: 'object',\n properties: {\n error: { $ref: '#/$defs/error' },\n next: { $ref: '#/$defs/next' },\n },\n required: ['error'],\n additionalProperties: false,\n },\n ],\n $defs: {\n error: {\n type: 'object',\n properties: {\n code: { type: 'string', description: 'Stable snake_case code' },\n message: { type: 'string' },\n retryable: {\n type: 'boolean',\n description: 'Running the same command again is safe and may succeed',\n },\n retryAfterSeconds: { type: 'number', minimum: 0 },\n details: { description: \"Shaped by the code's details schema\" },\n },\n required: ['code', 'message', 'retryable'],\n additionalProperties: false,\n },\n next: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n by: {\n enum: ['agent', 'user'],\n description: '\"user\" means a human must act; relay the step',\n },\n command: { type: 'string', description: 'Runnable as written' },\n description: { type: 'string' },\n },\n required: ['by', 'description'],\n additionalProperties: false,\n },\n },\n },\n})\n\n/** Summarizes a command for `schema --list`. */\nfunction summary(path: string, command: AnyCommand): Record<string, unknown> {\n return {\n command: path,\n description: command.description,\n readOnly: command.readOnly === true,\n idempotent: command.idempotent === true,\n confirm: command.confirm !== undefined,\n dryRun: command.dryRun === true,\n }\n}\n\n/**\n * Builds the `schema --list` data: the command tree with one-line\n * descriptions and the result envelope's JSON Schema, in one call.\n *\n * @see https://github.com/hugomrdias/fil/blob/main/docs/agent-cli/guidelines.md#discovery-and-schemas\n */\nexport function listSchema(\n cli: CliOptions,\n node: CommandNode,\n path: string[]\n): Record<string, unknown> {\n return {\n name: cli.name,\n version: cli.version,\n commands: leaves(node, path).map(({ path: leafPath, command }) =>\n summary(leafPath, command)\n ),\n ...(cli.aliases && path.length === 0 ? { aliases: cli.aliases } : {}),\n result: RESULT_SCHEMA,\n }\n}\n\n/** Builds the `schema <command>` data: JSON Schemas, error codes, and behavior of one command. */\nexport function commandSchema(\n cli: CliOptions,\n spec: CommandSpec,\n registry: Readonly<ErrorRegistry>\n): Record<string, unknown> {\n const { command } = spec\n let confirm: Record<string, unknown> | null = null\n if (typeof command.confirm === 'string') {\n confirm = { when: 'always', reason: command.confirm }\n } else if (command.confirm) {\n confirm = { when: 'conditional' }\n }\n return {\n command: spec.path,\n description: command.description,\n examples: command.examples ?? [],\n positionals: spec.positionals.map((field) => field.name),\n env: Object.fromEntries(\n spec.fields.flatMap((field) =>\n field.env ? [[field.name, field.env]] : []\n )\n ),\n secrets: spec.fields\n .filter((field) => field.secret)\n .map((field) => field.name),\n readOnly: command.readOnly === true,\n idempotent: command.idempotent === true,\n confirm,\n dryRun: command.dryRun === true,\n input: redactSecrets(spec),\n output: spec.outputJsonSchema ?? null,\n errors: describeErrors(registry, spec.errors),\n aliases: Object.entries(cli.aliases ?? {})\n .filter(([, target]) => target === spec.path)\n .map(([alias]) => alias),\n }\n}\n\n/** Maps each error code to its description and `details` JSON Schema, from the registry. */\nfunction describeErrors(\n registry: Readonly<ErrorRegistry>,\n codes: string[]\n): Record<string, { description: string | null; details: JsonSchema | null }> {\n return Object.fromEntries(\n codes.map((code) => {\n const definition = registry[code]\n return [\n code,\n {\n description: definition?.description ?? null,\n details:\n definition?.details?.['~standard'].jsonSchema.output(\n JSON_SCHEMA_TARGET\n ) ?? null,\n },\n ]\n })\n )\n}\n\n/** Removes defaults of secret fields from the input JSON Schema. */\nfunction redactSecrets(spec: CommandSpec): JsonSchema {\n const secrets = spec.fields.filter((field) => field.secret)\n if (secrets.length === 0) {\n return spec.inputJsonSchema\n }\n const properties = {\n ...(spec.inputJsonSchema.properties as Record<string, JsonSchema>),\n }\n for (const field of secrets) {\n const {\n default: _default,\n examples: _examples,\n ...rest\n } = properties[field.name] ?? {}\n properties[field.name] = rest\n }\n return { ...spec.inputJsonSchema, properties }\n}\n\n/**\n * Builds the built-in `schema` command, which prints the JSON Schemas of a\n * command, or the command list of the CLI or a group, as one JSON object.\n *\n * @see https://github.com/hugomrdias/fil/blob/main/docs/agent-cli/guidelines.md#discovery-and-schemas\n */\nexport function schemaCommand(\n cli: CliOptions,\n root: Group,\n errors: Readonly<ErrorRegistry>\n): SchemaCommand {\n const command: SchemaCommand = defineCommand({\n name: 'schema',\n description: 'JSON Schema for a command, or the command list',\n examples: [`${cli.name} schema --list`, `${cli.name} schema schema`],\n input: schemaInput,\n positionals: ['command'],\n readOnly: true,\n human: (data) => JSON.stringify(data, null, 2),\n handler: async () => ({ default: handler }),\n })\n const handler = defineHandler(command, ({ input, ok }) => {\n const words = input.command ?? []\n // Route like a command line, so an alias resolves to its canonical path.\n const routed = route(root, words, cli.aliases)\n const node =\n routed.kind === 'node' && routed.rest.length === 0\n ? routed.node\n : undefined\n if (!node) {\n throw unknownCommand(cli, {\n kind: 'unknown',\n group: root,\n path: [],\n word: words.join(' '),\n suggestion: closest(\n words.join(' '),\n leaves(root).map((leaf) => leaf.path)\n ),\n })\n }\n const path = routed.kind === 'node' ? routed.path : words\n return ok(\n node.kind === 'command'\n ? commandSchema(cli, resolveSpec(node, path.join(' ')), errors)\n : listSchema(cli, node, path)\n )\n })\n return markBuiltin(command, { commandPath: 'command' })\n}\n", "import { StringDecoder } from 'node:string_decoder'\nimport { parseArgs } from 'node:util'\nimport { type Env, parseBoolean } from './agent.ts'\nimport { CliError, type InputIssue } from './errors.ts'\nimport type { Io } from './io.ts'\nimport { closest, FRAMEWORK_FLAGS } from './route.ts'\nimport type { CommandSpec, FieldKind, FieldSpec } from './spec.ts'\n\n/** Framework values read while parsing a command's arguments. */\nexport interface FrameworkValues {\n input: string | undefined\n yes: boolean\n dryRun: boolean\n}\n\n/** Values collected from every source, where each came from, and the problems found. */\ninterface Collected {\n values: Record<string, unknown>\n sources: Record<string, string>\n issues: InputIssue[]\n}\n\n/** Validated input and where each value came from. */\nexport interface ResolvedInput {\n value: Record<string, unknown>\n sources: Record<string, string>\n framework: FrameworkValues\n}\n\n/**\n * Parses arguments, merges `--input` JSON and environment fallbacks, and\n * validates the result against the command's input schema. All problems are\n * reported at once as one `invalid_input` error.\n *\n * @see https://github.com/hugomrdias/fil/blob/main/docs/agent-cli/framework-design.md#execution-pipeline\n */\nexport async function resolveInput(\n spec: CommandSpec,\n args: string[],\n io: Io,\n signal: AbortSignal\n): Promise<ResolvedInput> {\n const collected: Collected = { values: {}, sources: {}, issues: [] }\n const { values, sources, issues } = collected\n const framework = parseCommandArgs(spec, args, collected)\n\n if (framework.input !== undefined) {\n const merged = await mergeInputJson(\n spec,\n framework.input,\n io,\n signal,\n collected\n )\n if (!merged) {\n // Every field would also be reported missing; report only the cause.\n throw invalidInput(issues)\n }\n }\n applyEnv(spec, io.env, collected)\n rejectControlCharacters(collected)\n\n const flagged = new Set(issues.map((issue) => issue.path))\n const result = await spec.input['~standard'].validate(values)\n if (result.issues) {\n for (const issue of result.issues) {\n const path = (issue.path ?? [])\n .map((part) =>\n typeof part === 'object' ? String(part.key) : String(part)\n )\n .join('.')\n const field = path.split('.')[0] ?? ''\n if (flagged.has(field)) {\n continue\n }\n const fieldSpec = spec.byName.get(field)\n const message =\n fieldSpec && values[field] === undefined && path === field\n ? missingMessage(fieldSpec)\n : issue.message\n const source = sources[field]\n issues.push(source ? { path, source, message } : { path, message })\n }\n }\n if (issues.length > 0 || !('value' in result)) {\n throw invalidInput(issues)\n }\n\n const value = result.value as Record<string, unknown>\n for (const field of spec.fields) {\n if (!(field.name in sources) && value[field.name] !== undefined) {\n sources[field.name] = 'default'\n }\n }\n return { value, sources, framework }\n}\n\n/** Creates the `invalid_input` error from all input issues. */\nexport function invalidInput(issues: InputIssue[]): CliError {\n const [first] = issues\n const summary = first\n ? `${first.path ? `${first.path}: ` : ''}${first.message}`\n : 'Invalid input'\n const more = issues.length > 1 ? ` (and ${issues.length - 1} more)` : ''\n const end = /[.?!]$/.test(summary) && !more ? '' : '.'\n return new CliError({\n code: 'invalid_input',\n message: `${summary}${more}${end}`,\n retryable: false,\n details: issues,\n })\n}\n\n/** Reads flags and positionals into `values`, reporting unknown or malformed ones. */\nfunction parseCommandArgs(\n spec: CommandSpec,\n args: string[],\n collected: Collected\n): FrameworkValues {\n const { values, sources, issues } = collected\n const framework: FrameworkValues = {\n input: undefined,\n yes: false,\n dryRun: false,\n }\n const frameworkFlags = new Map(\n FRAMEWORK_FLAGS.filter((flag) => flag.when?.(spec.command) ?? true).map(\n (flag) => [flag.name, flag]\n )\n )\n const options: Record<string, { type: 'string' | 'boolean' }> = {}\n for (const flag of frameworkFlags.values()) {\n options[flag.name] = { type: flag.value ? 'string' : 'boolean' }\n }\n for (const field of spec.fields) {\n options[field.flag] = {\n type: field.kind === 'boolean' ? 'boolean' : 'string',\n }\n }\n\n const { tokens } = parseArgs({\n args,\n options,\n strict: false,\n allowPositionals: true,\n allowNegative: true,\n tokens: true,\n })\n\n const flagIssue = (path: string, message: string) =>\n issues.push({ path, source: 'flag', message })\n const positionals: string[] = []\n // An unknown flag probably takes a value; skip it instead of reporting it twice.\n let skipIndex = -1\n for (const token of tokens) {\n if (token.kind === 'positional') {\n if (token.index !== skipIndex) {\n positionals.push(token.value)\n }\n continue\n }\n if (token.kind !== 'option') {\n continue\n }\n const negated = token.rawName.startsWith('--no-')\n const frameworkFlag = frameworkFlags.get(token.name)\n if (frameworkFlag) {\n if (negated && !frameworkFlag.negatable) {\n flagIssue(token.rawName, 'Unknown flag')\n } else if (!frameworkFlag.value && token.value !== undefined) {\n // `--yes=false` must not approve anything; switches take no value.\n flagIssue(token.rawName, `${token.rawName} does not take a value`)\n } else if (frameworkFlag.value) {\n if (token.value === undefined) {\n flagIssue(token.rawName, 'Requires a value')\n } else if (token.name === 'input') {\n framework.input = token.value\n }\n } else if (token.name === 'yes') {\n framework.yes = true\n } else if (token.name === 'dry-run') {\n framework.dryRun = true\n }\n continue\n }\n\n const field = spec.byFlag.get(token.name)\n if (!field) {\n if (token.value === undefined) {\n skipIndex = token.index + 1\n }\n const suggestion = closest(\n token.name,\n Object.keys(options).filter((name) => !spec.byFlag.get(name)?.secret)\n )\n flagIssue(\n token.rawName,\n suggestion\n ? `Unknown flag; did you mean --${suggestion}?`\n : 'Unknown flag'\n )\n continue\n }\n if (field.secret) {\n flagIssue(field.name, `Secret values are read only from ${field.env}`)\n continue\n }\n let value: unknown\n if (field.kind === 'boolean') {\n value = negated\n ? false\n : token.value === undefined\n ? true\n : coerce('boolean', token.value)\n } else if (negated) {\n flagIssue(\n field.name,\n `--no-${field.flag} is only valid for boolean flags`\n )\n continue\n } else if (token.value === undefined) {\n flagIssue(field.name, `--${field.flag} requires a value`)\n continue\n } else if (field.kind === 'array') {\n const list = (values[field.name] as unknown[] | undefined) ?? []\n list.push(coerce(field.itemKind, token.value))\n value = list\n } else if (field.name in values) {\n flagIssue(field.name, `--${field.flag} was given more than once`)\n continue\n } else {\n value = coerce(field.kind, token.value)\n }\n values[field.name] = value\n sources[field.name] = 'flag'\n }\n\n assignPositionals(spec, positionals, collected)\n if (framework.input === '-' && positionals.includes('-')) {\n flagIssue(\n '--input',\n 'Only one source can read stdin; \"-\" is also used as an argument'\n )\n }\n return framework\n}\n\n/** Assigns positional arguments to the command's positional fields in order. */\nfunction assignPositionals(\n spec: CommandSpec,\n positionals: string[],\n { values, sources, issues }: Collected\n): void {\n let index = 0\n for (const field of spec.positionals) {\n if (index >= positionals.length) {\n break\n }\n const taken = field.variadic\n ? positionals.slice(index)\n : [positionals[index] as string]\n index += taken.length\n if (field.name in values) {\n issues.push({\n path: field.name,\n source: 'positional',\n message: `Given both as an argument and as --${field.flag}`,\n })\n continue\n }\n values[field.name] = field.variadic\n ? taken.map((item) => coerce(field.itemKind, item))\n : coerce(field.kind, taken[0] as string)\n sources[field.name] = 'positional'\n }\n for (const extra of positionals.slice(index)) {\n issues.push({\n path: extra,\n source: 'positional',\n message: 'Unexpected argument',\n })\n }\n}\n\n/** Merges the `--input` JSON object, rejecting fields also given as arguments. */\nasync function mergeInputJson(\n spec: CommandSpec,\n location: string,\n io: Io,\n signal: AbortSignal,\n { values, sources, issues }: Collected\n): Promise<boolean> {\n let text: string\n try {\n // Loaded on use, so commands without --input never pay for node:fs.\n const { readFile } = process.getBuiltinModule('node:fs/promises')\n text =\n location === '-'\n ? await readStream(io.stdin, signal)\n : await readFile(location, { encoding: 'utf8', signal })\n } catch (error) {\n if (signal.aborted) {\n throw signal.reason\n }\n issues.push({\n path: '--input',\n source: 'flag',\n message: `Cannot read ${location === '-' ? 'stdin' : location}: ${(error as Error).message}`,\n })\n return false\n }\n let json: unknown\n try {\n json = JSON.parse(text)\n } catch {\n issues.push({ path: '--input', source: 'input', message: 'Not valid JSON' })\n return false\n }\n if (typeof json !== 'object' || json === null || Array.isArray(json)) {\n issues.push({\n path: '--input',\n source: 'input',\n message: 'Must be a JSON object',\n })\n return false\n }\n for (const [key, value] of Object.entries(json)) {\n const field = spec.byName.get(key)\n if (field?.secret) {\n issues.push({\n path: key,\n source: 'input',\n message: `Secret values are read only from ${field.env}`,\n })\n } else if (key in values) {\n issues.push({\n path: key,\n source: 'input',\n message: `Given both in --input and as ${sources[key] === 'positional' ? 'an argument' : `--${field?.flag ?? key}`}`,\n })\n } else {\n values[key] = value\n sources[key] = 'input'\n }\n }\n return true\n}\n\n/** Fills missing fields from their environment variables. */\nfunction applyEnv(\n spec: CommandSpec,\n env: Env,\n { values, sources, issues }: Collected\n): void {\n for (const field of spec.fields) {\n if (!field.env || field.name in values) {\n continue\n }\n const raw = env[field.env]\n if (raw === undefined || raw === '') {\n continue\n }\n let value: unknown\n if (field.kind === 'array') {\n value = raw.split(',').map((item) => coerce(field.itemKind, item.trim()))\n } else if (field.kind === 'boolean') {\n value = parseBoolean(raw)\n if (value === undefined) {\n issues.push({\n path: field.name,\n source: `env:${field.env}`,\n message: 'Expected true, false, 1, or 0',\n })\n continue\n }\n } else {\n value = coerce(field.kind, raw)\n }\n values[field.name] = value\n sources[field.name] = `env:${field.env}`\n }\n}\n\n/** Converts a string to a field's JSON type, leaving it unchanged if it does not fit. */\nfunction coerce(kind: FieldKind, raw: string): unknown {\n if (kind === 'number' || kind === 'integer') {\n // Decimal only: Number() would also accept \"0x10\", \" 5 \", and \"\".\n return DECIMAL.test(raw) ? Number(raw) : raw\n }\n if (kind === 'boolean') {\n return parseBoolean(raw) ?? raw\n }\n if (kind === 'object' || kind === 'array') {\n try {\n return JSON.parse(raw)\n } catch {\n return raw\n }\n }\n return raw\n}\n\n/** A decimal number such as `5`, `-1.5`, or `2e3`. */\nconst DECIMAL = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/\n\n/** C0 controls except tab, line feed, and carriage return, plus DEL. */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: detects control characters\nconst CONTROL = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/\n\n/**\n * Rejects control characters (such as ANSI escapes or NUL) in values from\n * flags, positionals, and environment variables, a common sign of a\n * garbled command line. `--input` JSON is exempt; it can encode any text.\n */\nfunction rejectControlCharacters({ values, sources, issues }: Collected): void {\n for (const [name, source] of Object.entries(sources)) {\n if (source === 'input') {\n continue\n }\n const items = ([] as unknown[]).concat(values[name])\n if (items.some((item) => typeof item === 'string' && CONTROL.test(item))) {\n issues.push({\n path: name,\n source,\n message: 'Contains control characters',\n })\n }\n }\n}\n\n/** Reads a stream to a string, giving up when `signal` aborts. */\nfunction readStream(\n stream: NodeJS.ReadableStream,\n signal: AbortSignal\n): Promise<string> {\n return new Promise((resolve, reject) => {\n signal.throwIfAborted()\n // Decodes across chunk boundaries so split multi-byte characters survive.\n const decoder = new StringDecoder('utf8')\n let text = ''\n const onData = (chunk: string | Buffer) => {\n text += typeof chunk === 'string' ? chunk : decoder.write(chunk)\n }\n const cleanup = () => {\n stream.off('data', onData)\n stream.off('end', onEnd)\n stream.off('error', onError)\n signal.removeEventListener('abort', onAbort)\n }\n const onEnd = () => {\n cleanup()\n resolve(text + decoder.end())\n }\n const onError = (error: Error) => {\n cleanup()\n reject(error)\n }\n const onAbort = () => {\n cleanup()\n stream.pause()\n reject(signal.reason)\n }\n stream.on('data', onData)\n stream.once('end', onEnd)\n stream.once('error', onError)\n signal.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/** Explains how to supply a missing required field. */\nfunction missingMessage(field: FieldSpec): string {\n if (field.secret) {\n return `Required; set ${field.env}`\n }\n const how = field.positional\n ? `pass <${field.name}> or --${field.flag}`\n : `pass --${field.flag}`\n return `Required; ${how}${field.env ? ` or set ${field.env}` : ''}`\n}\n", "import { styleText } from 'node:util'\nimport type { Env } from './agent.ts'\n\n/** A writable stream such as `process.stdout`. */\nexport interface OutputStream {\n write(chunk: string, callback?: (error?: Error | null) => void): boolean\n isTTY?: boolean\n}\n\n/** The process streams and environment a CLI runs with; replaced in tests. */\nexport interface Io {\n env: Env\n stdin: NodeJS.ReadableStream & { isTTY?: boolean }\n stdout: OutputStream\n stderr: OutputStream\n}\n\n/** Returns the real process streams and environment. */\nexport function processIo(): Io {\n return {\n env: process.env,\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n }\n}\n\n/** Writes a chunk and resolves when it has been handed to the OS. */\nexport function writeAsync(stream: OutputStream, chunk: string): Promise<void> {\n return new Promise((resolve) => {\n stream.write(chunk, () => resolve())\n })\n}\n\n/** Text styles used by human output. */\nexport type Style = Parameters<typeof styleText>[0]\n\n/**\n * Returns a styling function that colors only when allowed: never for\n * agents, and otherwise as `util.styleText` decides from the stream,\n * `NO_COLOR`, `FORCE_COLOR`, and `TERM`.\n */\nexport function styler(\n stream: OutputStream,\n enabled: boolean\n): (style: Style, text: string) => string {\n if (!enabled || !stream.isTTY) {\n return (_style, text) => text\n }\n return (style, text) =>\n styleText(style, text, { stream: stream as NodeJS.WritableStream })\n}\n", "import { detectAgent, isSet, parseBoolean } from './agent.ts'\nimport type { Mode } from './define.ts'\nimport type { InputIssue } from './errors.ts'\nimport type { Io } from './io.ts'\nimport type { GlobalFlags } from './route.ts'\n\n/** Returns `true` for a supported output format. */\nfunction isFormat(value: string | undefined): value is Mode['format'] {\n return value === 'json' || value === 'human'\n}\n\n/**\n * Resolves the output format, agent, and interactivity. Explicit flags win\n * over framework variables, which win over agent detection and TTYs.\n * Invalid values are returned as issues and otherwise ignored, so\n * discovery commands still work.\n *\n * @see https://github.com/hugomrdias/fil/blob/main/docs/agent-cli/guidelines.md#streams-and-modes\n */\nexport function resolveMode(\n flags: GlobalFlags,\n io: Io,\n prefix: string\n): { mode: Mode; issues: InputIssue[] } {\n const issues: InputIssue[] = []\n const agentVariable = `${prefix}_AGENT`\n const outputVariable = `${prefix}_OUTPUT`\n\n let override = flags.agent\n const rawAgent = io.env[agentVariable]\n if (override === undefined && rawAgent) {\n override = parseBoolean(rawAgent)\n if (override === undefined) {\n issues.push({\n path: agentVariable,\n source: `env:${agentVariable}`,\n message: 'Expected 1, 0, true, or false',\n })\n }\n }\n const detected = detectAgent(io.env)\n const agent =\n override === undefined ? detected : override && (detected || 'unknown')\n\n if (flags.format !== undefined && !isFormat(flags.format)) {\n issues.push({\n path: '--format',\n source: 'flag',\n message: 'Expected json or human',\n })\n }\n if (flags.json && flags.format === 'human') {\n issues.push({\n path: '--json',\n source: 'flag',\n message: 'Conflicts with --format human',\n })\n }\n const rawOutput = io.env[outputVariable]\n if (rawOutput && !isFormat(rawOutput)) {\n issues.push({\n path: outputVariable,\n source: `env:${outputVariable}`,\n message: 'Expected json or human',\n })\n }\n\n let format: Mode['format']\n if (flags.json) {\n format = 'json'\n } else if (isFormat(flags.format)) {\n format = flags.format\n } else if (isFormat(rawOutput)) {\n format = rawOutput\n } else if (agent || !io.stdout.isTTY) {\n format = 'json'\n } else {\n format = 'human'\n }\n\n const interactive =\n Boolean(io.stdin.isTTY && io.stdout.isTTY) && !agent && !isSet(io.env.CI)\n return { mode: { format, agent, interactive }, issues }\n}\n", "import type { CliOptions, Mode, ProgressEvent } from './define.ts'\nimport type { ErrorBody, InputIssue, Next } from './errors.ts'\nimport { type Io, styler, writeAsync } from './io.ts'\n\n/** Minimum interval between progress lines when no human is watching. */\nexport const PROGRESS_INTERVAL_MS = 15_000\n\n/** Returns the cursor to the line start and erases the line. */\nconst CLEAR_LINE = '\\r\\x1b[2K'\n\n/** The result of a successful command. */\nexport interface DataResult {\n data: unknown\n next?: Next[]\n}\n\n/** The result of a failed command. */\nexport interface ErrorResult {\n error: ErrorBody\n next?: Next[]\n}\n\n/**\n * A result object as written to stdout in machine mode: exactly one of\n * `data` and `error`, then optional `next` steps.\n *\n * @see https://github.com/hugomrdias/fil/blob/main/docs/agent-cli/guidelines.md#result-envelope\n */\nexport type ResultObject = DataResult | ErrorResult\n\n/** Returns `true` for the result of a failed command. */\nexport function isErrorResult(result: ResultObject): result is ErrorResult {\n return 'error' in result\n}\n\n/** What to print besides the result in human mode or on a usage error. */\nexport interface RenderExtras {\n /** Human-mode text for a successful result. */\n human?: string\n /** Usage line printed on a usage error in human mode. */\n usage?: string\n /** Full help printed to stderr on a usage error in agent mode. */\n help?: string\n}\n\n/**\n * Owns the streams for one invocation: stderr diagnostics and progress, and\n * the single final write of the result.\n */\nexport class Session {\n readonly cli: CliOptions\n readonly io: Io\n readonly mode: Mode\n readonly debug: boolean\n #rendered = false\n #statusLine = false\n #lastProgress = 0\n /** The latest stderr write; writes to one stream complete in order. */\n #pending: Promise<void> = Promise.resolve()\n readonly #style: ReturnType<typeof styler>\n\n /** Creates a session for the resolved mode. */\n constructor(cli: CliOptions, io: Io, mode: Mode, debug: boolean) {\n this.cli = cli\n this.io = io\n this.mode = mode\n this.debug = debug\n this.#style = styler(io.stderr, mode.format === 'human' && !mode.agent)\n }\n\n /** Writes a line to stderr, clearing any status line first. */\n log(message: string): void {\n this.#clearStatus()\n this.#stderr(`${message}\\n`)\n }\n\n /**\n * Shows progress: a rewritten status line on a human terminal, otherwise a\n * plain line at most every {@link PROGRESS_INTERVAL_MS}.\n */\n progress(event: ProgressEvent): void {\n const text = `${event.phase}: ${event.message}`\n if (\n this.mode.format === 'human' &&\n !this.mode.agent &&\n this.io.stderr.isTTY\n ) {\n this.#stderr(`${CLEAR_LINE}${this.#style('dim', text)}`)\n this.#statusLine = true\n return\n }\n const now = Date.now()\n if (now - this.#lastProgress >= PROGRESS_INTERVAL_MS) {\n this.#lastProgress = now\n this.log(`${this.cli.name}: ${text}`)\n }\n }\n\n /** Writes plain text to stdout, such as help or the version. */\n async text(text: string): Promise<void> {\n this.#rendered = true\n await this.flush()\n await writeAsync(this.io.stdout, text)\n }\n\n /**\n * Writes the result once: one JSON line in machine mode, or text in human\n * mode with errors and next steps on stderr.\n */\n async render(result: ResultObject, extras: RenderExtras = {}): Promise<void> {\n if (this.#rendered) {\n return\n }\n // Serialize first: if it throws, the error result can still be rendered.\n const json =\n this.mode.format === 'json' ? `${JSON.stringify(result)}\\n` : undefined\n this.#rendered = true\n const error = isErrorResult(result) ? result.error : undefined\n const { next } = result\n\n if (json !== undefined) {\n if (error) {\n this.log(`${this.cli.name}: ${error.message}`)\n if (extras.help && this.mode.agent) {\n this.log(extras.help)\n }\n }\n await this.flush()\n await writeAsync(this.io.stdout, json)\n return\n }\n\n if (error) {\n const style = this.#style\n const lines = [\n `${style(['bold', 'red'], 'Error:')} ${error.message} ${style('dim', `(${error.code})`)}`,\n ]\n if (Array.isArray(error.details)) {\n for (const issue of error.details as InputIssue[]) {\n if (issue && typeof issue === 'object' && 'message' in issue) {\n const source = issue.source\n ? style('dim', ` (${issue.source})`)\n : ''\n lines.push(` ${issue.path}${source}: ${issue.message}`)\n }\n }\n }\n if (extras.usage) {\n lines.push(`Usage: ${extras.usage}`)\n }\n this.log(lines.join('\\n'))\n } else if (extras.human) {\n await this.flush()\n await writeAsync(\n this.io.stdout,\n extras.human.endsWith('\\n') ? extras.human : `${extras.human}\\n`\n )\n }\n if (next?.length) {\n this.log(this.#formatNext(next))\n }\n await this.flush()\n }\n\n /** Clears any status line and waits until earlier stderr writes are handed to the OS. */\n async flush(): Promise<void> {\n this.#clearStatus()\n await this.#pending\n }\n\n /** Formats next steps for humans. */\n #formatNext(next: Next[]): string {\n const style = this.#style\n const lines = next.map((step) => {\n const who = step.by === 'user' ? style('yellow', 'You: ') : ''\n const command = step.command ? `\\n ${style('cyan', step.command)}` : ''\n return ` ${who}${step.description}${command}`\n })\n return `Next:\\n${lines.join('\\n')}`\n }\n\n /** Clears a human status line before other output. */\n #clearStatus(): void {\n if (this.#statusLine) {\n this.#statusLine = false\n this.#stderr(CLEAR_LINE)\n }\n }\n\n /** Queues a write to stderr. */\n #stderr(chunk: string): void {\n this.#pending = writeAsync(this.io.stderr, chunk)\n }\n}\n\n/** Formats command data for human mode when the command has no formatter. */\nexport function formatData(data: unknown): string | undefined {\n if (Array.isArray(data)) {\n return data.length > 0 ? JSON.stringify(data, null, 2) : undefined\n }\n if (data === null || typeof data !== 'object') {\n return data === undefined ? undefined : String(data)\n }\n const entries = Object.entries(data).filter(\n ([, value]) => value !== undefined\n )\n if (entries.length === 0) {\n return undefined\n }\n return entries\n .map(([key, value]) =>\n value !== null && typeof value === 'object'\n ? `${key}:\\n${JSON.stringify(value, null, 2).replace(/^/gm, ' ')}`\n : `${key}: ${String(value)}`\n )\n .join('\\n')\n}\n", "import { COMPLETE_COMMAND, complete, completionCommand } from './completion.ts'\nimport {\n type AnyCommand,\n type Checkpoint,\n type CliOptions,\n type Context,\n createOk,\n type Group,\n isBuiltin,\n isHandler,\n isOk,\n type Mode,\n printsPlainText,\n type Schema,\n} from './define.ts'\nimport { schemaCommand } from './discovery.ts'\nimport {\n CliError,\n DefinitionError,\n type ErrorRegistry,\n errorRegistry,\n type InputIssue,\n isCliError,\n TRANSIENT_ERROR_CODES,\n} from './errors.ts'\nimport { commandHelp, groupHelp, leaves, usage } from './help.ts'\nimport { type FrameworkValues, invalidInput, resolveInput } from './input.ts'\nimport { type Io, processIo } from './io.ts'\nimport { resolveMode } from './mode.ts'\nimport {\n type GlobalFlags,\n route,\n scanGlobalFlags,\n unknownCommand,\n} from './route.ts'\nimport {\n formatData,\n isErrorResult,\n type RenderExtras,\n type ResultObject,\n Session,\n} from './session.ts'\nimport { skillsGroup, skillsPath } from './skills.ts'\nimport { type CommandSpec, resolveSpec } from './spec.ts'\n\n/** Signals that cancel the running command. */\nconst SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const\n\n/** The outcome of a command that printed text, such as help. */\nconst TEXT_OUTCOME: Outcome = {\n exitCode: 0,\n result: undefined,\n signal: undefined,\n}\n\n/** The outcome of one invocation. */\nexport interface Outcome {\n exitCode: 0 | 1\n /** The result object, also written to stdout in machine mode. */\n result: ResultObject | undefined\n /** The signal to re-raise after an interruption. */\n signal: NodeJS.Signals | undefined\n}\n\n/** Options for {@link Cli.execute}. */\nexport interface ExecuteOptions {\n /** Aborted to interrupt the command, with the signal name as the reason. */\n signal?: AbortSignal\n /** Rejects with an uncaught error, which then becomes `internal_error`. */\n crash?: Promise<never>\n /** Checks results against output schemas, declared error codes, and `details` schemas. */\n strict?: boolean\n}\n\n/** A CLI created by {@link defineCli}. */\nexport interface Cli {\n readonly options: CliOptions\n /** The root group of the command tree, including the `skills` group. */\n readonly root: Group\n /** Framework variable prefix, such as `ACME`. */\n readonly envPrefix: string\n /** The full error registry: the framework's codes and the CLI's `errors`. */\n readonly errors: Readonly<ErrorRegistry>\n /** Runs with the real process: installs signal and crash handlers and sets the exit code. */\n run(argv?: string[]): Promise<void>\n /** Runs one invocation against the given streams without touching the process. */\n execute(args: string[], io: Io, options?: ExecuteOptions): Promise<Outcome>\n}\n\n/**\n * Defines a CLI from its command tree.\n *\n * @see https://github.com/hugomrdias/fil/blob/main/docs/agent-cli/framework-design.md\n */\nexport function defineCli(definition: CliOptions): Cli {\n const defines = (name: string) =>\n definition.commands.some((node) => node.name === name)\n // An application's own `skills` command replaces the framework's.\n const skills = defines('skills') ? undefined : definition.skills\n const errors = errorRegistry(definition.errors, Boolean(skills))\n const commands = [...definition.commands]\n const options: CliOptions = { ...definition, commands }\n const root: Group = {\n kind: 'group',\n name: options.name,\n description: options.description ?? '',\n commands,\n }\n if (skills) {\n commands.push(skillsGroup(definition, skills))\n }\n if (!defines('schema')) {\n commands.push(schemaCommand(options, root, errors))\n }\n if (!defines('completion')) {\n commands.push(completionCommand(options))\n }\n const envPrefix = (options.envPrefix ?? options.name)\n .toUpperCase()\n .replace(/[^A-Z0-9]+/g, '_')\n\n const execute = async (\n args: string[],\n io: Io,\n executeOptions: ExecuteOptions = {}\n ): Promise<Outcome> => {\n const controller = new AbortController()\n const signal = executeOptions.signal\n ? AbortSignal.any([controller.signal, executeOptions.signal])\n : controller.signal\n const flags = scanGlobalFlags(args)\n const { mode, issues: modeIssues } = resolveMode(flags, io, envPrefix)\n const session = new Session(options, io, mode, flags.debug)\n const invocation = new Invocation({\n cli: options,\n root,\n args,\n io,\n mode,\n modeIssues,\n flags,\n session,\n controller,\n signal,\n strict: executeOptions.strict === true,\n errors,\n })\n const work = invocation.run()\n try {\n return await (executeOptions.crash\n ? Promise.race([work, executeOptions.crash])\n : work)\n } catch (error) {\n const outcome = await invocation.fail(error)\n // Stop handler I/O that would otherwise keep the process alive.\n controller.abort(error)\n return outcome\n }\n }\n\n return {\n options,\n root,\n envPrefix,\n errors,\n execute,\n async run(argv = process.argv) {\n const controller = new AbortController()\n const onSignal = (signal: NodeJS.Signals) => controller.abort(signal)\n for (const signal of SIGNALS) {\n process.once(signal, onSignal)\n }\n process.stdout.on('error', (error: NodeJS.ErrnoException) => {\n if (error.code === 'EPIPE') {\n process.exit(0)\n }\n throw error\n })\n let finished = false\n const { promise: crash, reject: reportCrash } =\n Promise.withResolvers<never>()\n crash.catch(() => undefined)\n const onCrash = (error: unknown) => {\n if (finished) {\n process.stderr.write(\n `${options.name}: internal error after the result: ${String(error)}\\n`\n )\n process.exitCode = 1\n } else {\n reportCrash(error)\n }\n }\n process.on('uncaughtException', onCrash)\n process.on('unhandledRejection', onCrash)\n\n const outcome = await execute(argv.slice(2), processIo(), {\n signal: controller.signal,\n crash,\n })\n finished = true\n process.exitCode = outcome.exitCode\n for (const signal of SIGNALS) {\n process.off(signal, onSignal)\n }\n if (outcome.signal) {\n process.kill(process.pid, outcome.signal)\n }\n },\n }\n}\n\n/** State shared by the steps of one invocation. */\ninterface InvocationState {\n cli: CliOptions\n root: Group\n args: string[]\n io: Io\n mode: Mode\n modeIssues: InputIssue[]\n flags: GlobalFlags\n session: Session\n /** Aborted with a signal name. */\n controller: AbortController\n /** Aborted by `controller` or the caller's signal. */\n signal: AbortSignal\n strict: boolean\n /** The full error registry, built-in codes included. */\n errors: Readonly<ErrorRegistry>\n}\n\n/** Runs the execution pipeline for one argv. */\nclass Invocation {\n readonly #state: InvocationState\n #spec: CommandSpec | undefined\n #checkpoint: Checkpoint | undefined\n /** Agent help for the group a routing error happened in. */\n #groupHelp: string | undefined\n\n /** Creates an invocation. */\n constructor(state: InvocationState) {\n this.#state = state\n }\n\n /** Routes, parses, validates, gates, runs, and renders. */\n async run(): Promise<Outcome> {\n const { cli, root, args, flags, mode } = this.#state\n try {\n if (args[0] === COMPLETE_COMMAND) {\n return await this.#text(complete(cli, root, args.slice(1)))\n }\n const routed = route(root, args, cli.aliases)\n if (flags.version) {\n return await this.#text(`${cli.version}\\n`)\n }\n if (routed.kind === 'unknown') {\n this.#groupHelp = groupHelp(cli, routed.group, routed.path, true)\n throw unknownCommand(cli, routed)\n }\n const { node, path } = routed\n if (node.kind === 'group') {\n if (flags.help || mode.format === 'human') {\n return await this.#text(\n groupHelp(cli, node, path, Boolean(mode.agent))\n )\n }\n this.#groupHelp = groupHelp(cli, node, path, true)\n throw missingCommand(cli, node, path)\n }\n const spec = resolveSpec(node, path.join(' '))\n this.#spec = spec\n if (flags.help) {\n return await this.#text(commandHelp(cli, spec, Boolean(mode.agent)))\n }\n // Built-ins print the same JSON in every mode, so they ignore mode issues.\n if (this.#state.modeIssues.length > 0 && !isBuiltin(node)) {\n throw invalidInput(this.#state.modeIssues)\n }\n const outcome = await this.#command(spec, routed.rest)\n if (!isBuiltin(node)) {\n await this.#skillsNotice(path)\n }\n return outcome\n } catch (error) {\n return await this.fail(error)\n }\n }\n\n /** Converts any thrown value into an error result and renders it. */\n async fail(error: unknown): Promise<Outcome> {\n const { session, signal, cli } = this.#state\n const command = this.#spec?.command\n if (\n signal.aborted &&\n typeof signal.reason === 'string' &&\n signal.reason.startsWith('SIG')\n ) {\n return await this.#interrupted(signal.reason as NodeJS.Signals)\n }\n let cliError: CliError | undefined\n if (isCliError(error)) {\n cliError = error\n } else if (!(error instanceof DefinitionError) && cli.mapError) {\n try {\n const { default: mapError } = await cli.mapError()\n cliError = await mapError(error)\n } catch (mapFailure) {\n error = mapFailure\n }\n }\n if (!cliError) {\n if (session.debug && error instanceof Error && error.stack) {\n session.log(error.stack)\n }\n cliError = new CliError({\n code: 'internal_error',\n message: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`,\n retryable: false,\n next: [\n {\n by: 'user',\n description: `Report this problem with the output of the same command run with --debug`,\n },\n ],\n })\n }\n const result = errorResult(cliError, command)\n const extras: RenderExtras = {}\n if (cliError.code === 'invalid_input') {\n const spec = this.#spec\n extras.usage = spec && usage(cli, spec)\n extras.help = spec ? commandHelp(cli, spec, true) : this.#groupHelp\n }\n return await this.#finish(await this.#checked(result), extras)\n }\n\n /** Writes text such as help to stdout and returns a successful outcome. */\n async #text(text: string): Promise<Outcome> {\n await this.#state.session.text(text)\n return TEXT_OUTCOME\n }\n\n /** Validates input, applies the confirmation gate, and runs the handler. */\n async #command(spec: CommandSpec, rest: string[]): Promise<Outcome> {\n const { cli, io, session, signal, mode } = this.#state\n const { command } = spec\n const {\n value: input,\n sources,\n framework,\n } = await resolveInput(spec, rest, io, signal)\n if (session.debug) {\n session.log(describeSources(spec, input, sources))\n }\n await this.#confirm(command, input, framework)\n if (signal.aborted) {\n throw signal.reason\n }\n\n const module = await command.handler()\n const handler = (module as { default?: unknown } | undefined)?.default\n if (!isHandler(handler)) {\n throw new DefinitionError(\n spec.path,\n 'the handler module must default-export defineHandler(...)'\n )\n }\n const context: Context<undefined, undefined> = {\n input: input as Record<string, never>,\n signal,\n mode,\n dryRun: framework.dryRun,\n progress: (event) => session.progress(event),\n log: (message) => session.log(message),\n checkpoint: (checkpoint) => {\n this.#checkpoint = checkpoint\n const resume = checkpoint.next?.find((step) => step.command)?.command\n session.log(\n `${cli.name}: started ${checkpoint.id}${resume ? `; if interrupted, run: ${resume}` : ''}`\n )\n },\n ok: (data, options) => createOk(data ?? {}, options?.next),\n }\n const value = await handler.run(context)\n if (!isOk(value)) {\n throw new DefinitionError(\n spec.path,\n 'the handler must return ctx.ok(...)'\n )\n }\n const data = value.data\n let checked = await this.#checked({\n data,\n ...(value.next?.length ? { next: value.next } : {}),\n })\n const output: Schema | undefined = command.output\n if (this.#state.strict && !isErrorResult(checked)) {\n if (typeof data !== 'object' || data === null) {\n checked = contractViolation('data must be an object or an array')\n } else if (output) {\n const validation = await output['~standard'].validate(data)\n if (validation.issues) {\n checked = contractViolation(\n `output does not match the schema: ${validation.issues.map((issue) => issue.message).join('; ')}`\n )\n }\n }\n }\n const human = command.human ?? formatData\n const succeeded = !isErrorResult(checked)\n if (succeeded && printsPlainText(command)) {\n return await this.#text(human(data) ?? '')\n }\n return await this.#finish(checked, {\n human: succeeded ? human(data) : undefined,\n })\n }\n\n /** After a human-mode command, suggests updating project skills installed by another version. */\n async #skillsNotice(path: string[]): Promise<void> {\n const { cli, mode, session } = this.#state\n if (\n !cli.skills ||\n mode.format !== 'human' ||\n mode.agent ||\n path[0] === 'skills'\n ) {\n return\n }\n try {\n const { staleNotice } = await import('./skills.run.ts')\n const notice = await staleNotice(cli, skillsPath(cli.skills))\n if (notice) {\n session.log(notice)\n await session.flush()\n }\n } catch {\n // A notice never changes the outcome.\n }\n }\n\n /** Requires confirmation from a human or `--yes` when the command asks for it. */\n async #confirm(\n command: AnyCommand,\n input: Record<string, unknown>,\n framework: FrameworkValues\n ): Promise<void> {\n const { cli, args, io, mode, signal } = this.#state\n const reason =\n typeof command.confirm === 'function'\n ? command.confirm(input)\n : command.confirm\n if (!reason || framework.yes || framework.dryRun) {\n return\n }\n if (mode.interactive) {\n // Loaded on use, so other invocations never pay for node:readline.\n const { createInterface } = process.getBuiltinModule(\n 'node:readline/promises'\n )\n const readline = createInterface({\n input: io.stdin,\n output: io.stderr as NodeJS.WritableStream,\n })\n readline.on('SIGINT', () => this.#state.controller.abort('SIGINT'))\n try {\n const answer = await readline.question(`${reason} Continue? [y/N] `, {\n signal,\n })\n if (/^y(es)?$/i.test(answer.trim())) {\n return\n }\n } finally {\n readline.close()\n }\n throw new CliError({\n code: 'confirmation_required',\n message: 'Confirmation declined.',\n retryable: false,\n details: { reason },\n })\n }\n throw new CliError({\n code: 'confirmation_required',\n message: `${reason} Confirm with --yes.`,\n retryable: false,\n details: { reason },\n next: [\n {\n by: 'user',\n command: rerunWithYes(cli.name, args),\n description: 'Approve this action, then run it with --yes',\n },\n ],\n })\n }\n\n /** Renders the interrupted result for a signal. */\n async #interrupted(signalName: NodeJS.Signals): Promise<Outcome> {\n const result = errorResult(\n new CliError({\n code: 'interrupted',\n message: `Interrupted by ${signalName}.`,\n retryable: this.#spec?.command.idempotent === true,\n next: this.#checkpoint?.next,\n }),\n undefined\n )\n const outcome = await this.#finish(result, {})\n return { ...outcome, signal: signalName }\n }\n\n /** In strict mode, replaces a result that breaks the command's contract. */\n async #checked(result: ResultObject): Promise<ResultObject> {\n if (!this.#state.strict || !isErrorResult(result)) {\n return result\n }\n const { error } = result\n const spec = this.#spec\n if (spec) {\n if (!spec.errors.includes(error.code)) {\n return contractViolation(\n `error code \"${error.code}\" is not declared in errors`\n )\n }\n if (error.retryable && !spec.command.idempotent) {\n return contractViolation(\n `\"${error.code}\" is retryable but the command is neither readOnly nor idempotent`\n )\n }\n }\n const details = this.#state.errors[error.code]?.details\n if (details && error.details !== undefined) {\n const validation = await details['~standard'].validate(error.details)\n if (validation.issues) {\n return contractViolation(\n `details of \"${error.code}\" do not match the schema: ${validation.issues.map((issue) => issue.message).join('; ')}`\n )\n }\n }\n return result\n }\n\n /** Renders a result and returns the outcome. */\n async #finish(result: ResultObject, extras: RenderExtras): Promise<Outcome> {\n await this.#state.session.render(result, extras)\n return {\n exitCode: isErrorResult(result) ? 1 : 0,\n result,\n signal: undefined,\n }\n }\n}\n\n/** Builds an error result, applying the default `retryable` rules. */\nfunction errorResult(\n error: CliError,\n command: AnyCommand | undefined\n): ResultObject {\n const retryable =\n error.retryable ??\n (TRANSIENT_ERROR_CODES.has(error.code) && command?.idempotent === true)\n return {\n error: {\n code: error.code,\n message: error.message,\n retryable,\n ...(error.retryAfterSeconds === undefined\n ? {}\n : { retryAfterSeconds: error.retryAfterSeconds }),\n ...(error.details === undefined ? {} : { details: error.details }),\n },\n ...(error.next?.length ? { next: error.next } : {}),\n }\n}\n\n/** Builds the `internal_error` result for a broken command contract in strict mode. */\nfunction contractViolation(message: string): ResultObject {\n return errorResult(\n new CliError({\n code: 'internal_error',\n message: `Contract violation: ${message}.`,\n retryable: false,\n }),\n undefined\n )\n}\n\n/** Builds the error for a group invoked without a subcommand in machine mode. */\nfunction missingCommand(\n cli: CliOptions,\n group: Group,\n path: string[]\n): CliError {\n const commands = leaves(group, path).map((leaf) => leaf.path)\n return new CliError({\n code: 'invalid_input',\n message: `Missing command after \"${[cli.name, ...path].join(' ')}\".`,\n retryable: false,\n details: [\n {\n path: 'command',\n message: `Expected one of: ${commands.join(', ')}`,\n },\n ],\n next: [\n {\n by: 'agent',\n command: `${cli.name} schema --list`,\n description: 'List all commands with descriptions',\n },\n ],\n })\n}\n\n/** Lists each input value and its source for `--debug`, redacting secrets. */\nfunction describeSources(\n spec: CommandSpec,\n input: Record<string, unknown>,\n sources: Record<string, string>\n): string {\n const lines = spec.fields\n .filter((field) => field.name in sources)\n .map((field) => {\n const value = field.secret\n ? '<redacted>'\n : JSON.stringify(input[field.name])\n return ` ${field.name} = ${value} (${sources[field.name]})`\n })\n return `debug: input for ${spec.path}\\n${lines.join('\\n')}`\n}\n\n/** Quotes an argument for POSIX shells when needed. */\nfunction quote(arg: string): string {\n return /^[\\w@%+=:,./-]+$/.test(arg)\n ? arg\n : `'${arg.replaceAll(\"'\", `'\\\\''`)}'`\n}\n\n/** Returns the same command line with `--yes` added before any `--`. */\nfunction rerunWithYes(name: string, args: string[]): string {\n const terminator = args.indexOf('--')\n const withYes =\n terminator === -1\n ? [...args, '--yes']\n : [...args.slice(0, terminator), '--yes', ...args.slice(terminator)]\n return [name, ...withYes].map(quote).join(' ')\n}\n"],
|
|
5
|
+
"mappings": ";wKAIA,IAAMA,GAAwD,CAC5D,CAAC,aAAc,aAAa,EAC5B,CAAC,4BAA6B,aAAa,EAC3C,CAAC,kBAAmB,OAAO,EAC3B,CAAC,WAAY,OAAO,EACpB,CAAC,aAAc,YAAY,EAC3B,CAAC,eAAgB,QAAQ,EACzB,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", "command", "flagTokens", "flag", "frameworkToken", "arg", "scanGlobalFlags", "args", "flags", "index", "leadingWords", "words", "token", "findNode", "root", "path", "node", "name", "child", "candidate", "route", "aliases", "consumed", "position", "sortedAliases", "a", "b", "alias", "target", "aliasWords", "word", "targetPath", "resolved", "DefinitionError", "w", "group", "closest", "without", "unknownCommand", "cli", "routed", "attempted", "next", "CliError", "indexes", "_", "input", "candidates", "best", "bestDistance", "distance", "editDistance", "previous", "i", "current", "j", "JSON_SCHEMA_TARGET", "EMPTY_INPUT", "fromJsonSchema", "toFlag", "name", "cache", "resolveSpec", "command", "path", "cached", "input", "inputJsonSchema", "DefinitionError", "properties", "required", "positionalNames", "secrets", "env", "fields", "schema", "resolved", "deref", "kind", "kindOf", "items", "index", "byName", "field", "positionals", "seenOptional", "byFlag", "FRAMEWORK_FLAGS", "flag", "other", "outputJsonSchema", "spec", "BUILTIN_ERROR_CODES", "root", "ref", "target", "part", "kinds", "visit", "node", "branches", "branch", "values", "value", "kindOfValue", "types", "type", "SHELLS", "COMPLETE_COMMAND", "FILES", "frameworkOptions", "command", "isRoot", "accepted", "flag", "FRAMEWORK_FLAGS", "flagTokens", "token", "value", "complete", "cli", "root", "words", "current", "values", "candidates", "description", "before", "routed", "route", "node", "path", "rest", "flagCandidates", "children", "commandCandidates", "resolveSpec", "group", "list", "child", "isBuiltin", "alias", "target", "spec", "options", "commandOptions", "byFlag", "option", "used", "positionals", "pending", "terminated", "arg", "equals", "prefix", "candidate", "last", "field", "commandPathField", "findNode", "fieldValues", "kind", "completionScript", "name", "shell", "DefinitionError", "id", "header", "completionHelp", "completionInput", "fromJsonSchema", "completionCommand", "defineCommand", "data", "handler", "defineHandler", "input", "mode", "ok", "CliError", "markBuiltin", "CONTRACT", "leaves", "node", "prefix", "child", "isBuiltin", "columns", "rows", "indent", "width", "left", "right", "flagRow", "flag", "tokens", "flagTokens", "valueLabel", "field", "kind", "positionalUsage", "spec", "name", "usage", "cli", "parts", "fieldNotes", "notes", "text", "outputFields", "schema", "properties", "property", "type", "sideEffects", "command", "lines", "commandHelp", "agent", "sections", "examples", "example", "positional", "flags", "FRAMEWORK_FLAGS", "environment", "output", "globalFlags", "groupHelp", "group", "path", "isRoot", "title", "leafPath", "markers", "builtins", "resolveSpec", "schemaInput", "fromJsonSchema", "RESULT_SCHEMA", "summary", "path", "command", "listSchema", "cli", "node", "leaves", "leafPath", "commandSchema", "spec", "registry", "confirm", "field", "redactSecrets", "describeErrors", "target", "alias", "codes", "code", "definition", "JSON_SCHEMA_TARGET", "secrets", "properties", "_default", "_examples", "rest", "schemaCommand", "root", "errors", "defineCommand", "data", "handler", "defineHandler", "input", "ok", "words", "routed", "route", "unknownCommand", "closest", "leaf", "resolveSpec", "markBuiltin", "StringDecoder", "parseArgs", "resolveInput", "spec", "args", "io", "signal", "collected", "values", "sources", "issues", "framework", "parseCommandArgs", "mergeInputJson", "invalidInput", "applyEnv", "rejectControlCharacters", "flagged", "issue", "result", "path", "part", "field", "fieldSpec", "message", "missingMessage", "source", "value", "first", "summary", "more", "end", "CliError", "frameworkFlags", "FRAMEWORK_FLAGS", "flag", "options", "tokens", "parseArgs", "flagIssue", "positionals", "skipIndex", "token", "negated", "frameworkFlag", "suggestion", "closest", "name", "coerce", "list", "assignPositionals", "index", "taken", "item", "extra", "location", "text", "readFile", "readStream", "error", "json", "key", "env", "raw", "parseBoolean", "kind", "DECIMAL", "CONTROL", "stream", "resolve", "reject", "decoder", "StringDecoder", "onData", "chunk", "cleanup", "onEnd", "onError", "onAbort", "styleText", "processIo", "writeAsync", "stream", "chunk", "resolve", "styler", "enabled", "_style", "text", "style", "isFormat", "value", "resolveMode", "flags", "io", "prefix", "issues", "agentVariable", "outputVariable", "override", "rawAgent", "parseBoolean", "detected", "detectAgent", "agent", "rawOutput", "format", "interactive", "isSet", "PROGRESS_INTERVAL_MS", "CLEAR_LINE", "isErrorResult", "result", "Session", "#rendered", "#statusLine", "#lastProgress", "#pending", "#style", "cli", "io", "mode", "debug", "styler", "message", "#clearStatus", "#stderr", "event", "text", "now", "writeAsync", "extras", "json", "error", "next", "style", "lines", "issue", "source", "#formatNext", "step", "who", "command", "chunk", "formatData", "data", "entries", "value", "key", "SIGNALS", "TEXT_OUTCOME", "defineCli", "definition", "defines", "name", "node", "skills", "errors", "errorRegistry", "commands", "options", "root", "skillsGroup", "schemaCommand", "completionCommand", "envPrefix", "execute", "args", "io", "executeOptions", "controller", "signal", "flags", "scanGlobalFlags", "mode", "modeIssues", "resolveMode", "session", "Session", "invocation", "Invocation", "work", "error", "outcome", "argv", "onSignal", "finished", "crash", "reportCrash", "onCrash", "processIo", "#state", "#spec", "#checkpoint", "#groupHelp", "state", "cli", "COMPLETE_COMMAND", "#text", "complete", "routed", "route", "groupHelp", "unknownCommand", "path", "missingCommand", "spec", "resolveSpec", "commandHelp", "isBuiltin", "invalidInput", "#command", "#skillsNotice", "command", "#interrupted", "cliError", "isCliError", "DefinitionError", "mapError", "mapFailure", "CliError", "result", "errorResult", "extras", "usage", "#finish", "#checked", "text", "rest", "input", "sources", "framework", "resolveInput", "describeSources", "#confirm", "handler", "isHandler", "context", "event", "message", "checkpoint", "resume", "step", "data", "createOk", "value", "isOk", "checked", "output", "isErrorResult", "contractViolation", "validation", "issue", "human", "formatData", "succeeded", "printsPlainText", "staleNotice", "notice", "skillsPath", "reason", "createInterface", "readline", "answer", "rerunWithYes", "signalName", "details", "retryable", "TRANSIENT_ERROR_CODES", "group", "leaves", "leaf", "lines", "field", "quote", "arg", "terminator", "withYes"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
|
|
2
|
+
import{a as w}from"./chunk-ISML2NA2.js";import{a as z,b as F}from"./chunk-5EYSPKTK.js";import{B as D,E as l,K as E,L as $,M as S,N as L,P as b,Q as J,R as _,S as T,T as v}from"./chunk-4DUACCJB.js";import{k as p,o as A,p as I,q as g}from"./chunk-UJQDDRQD.js";import{o as m,p as O}from"./chunk-4BBXH7CB.js";import{createReadStream as Z}from"node:fs";import{rm as j,stat as y}from"node:fs/promises";import{basename as q,join as Q,resolve as W}from"node:path";var X={source:"fil"},V={source:"fil",withIPFSIndexing:""},G=96;async function B(e){let t=W(e.path),i=await y(t).catch(()=>{});if(!i||!(i.isFile()||i.isDirectory()))throw I(`No file or directory at ${e.path}.`,"path");let r=e.name??q(t);return i.isDirectory()?{sourcePath:t,kind:"folder",name:r}:(P(i.size),{sourcePath:t,kind:"file",name:r,size:i.size})}async function Ie(e,t){let i=await B(t),r=S(e.db,{action:"put",resourceRef:$("res"),chainId:e.chainId,payer:e.payer,input:{sourcePath:i.sourcePath,name:i.name,kind:i.kind,providerId:t.providerId?.toString()}});return await M(e,r.id)}async function be(e){let t=await B(e),i;if(t.kind==="file")i={kind:"file",name:t.name,size:t.size??0,files:1};else{let d=await w(t.sourcePath);P(d.size),i={kind:"folder",name:t.name,size:d.size,files:d.files,rootCid:d.rootCid.toString()}}if(!e.backend)return i;let r=await e.backend.selectPlacement({metadata:C(i.kind),providerId:e.providerId}),n=await e.backend.quote({size:i.size,placement:r});return{...i,placement:r,quote:n}}async function M(e,t){let i=L(e.db,t);if(!i)throw g(`Operation ${t} not found.`);if(i.executionStatus==="completed")return K(e,i);let r=J(e.db,t);try{return e.onOperation?.(r),r.action==="put"?await x(e,r):await re(e,r)}catch(n){throw b(e.db,r.id,{executionStatus:"failed",pid:null,error:e.signal?.aborted?"Interrupted":n instanceof Error?n.message:String(n)}),e.signal?.aborted?n:A(n,r.id)}finally{_(r.id)}}function K(e,t){let i=v(e.db,t.resourceRef);if(!i)throw g(`Resource ${t.resourceRef} of ${t.id} no longer exists.`);return N(e,t,i)}function N(e,t,i){return{operationId:t.id,state:t.action==="put"?"ready":"removal_pending",resource:i,urls:F(i,e.apiUrl)}}function H(e,t,i,r={}){E(e.db,()=>{T(e.db,i),b(e.db,t.id,{executionStatus:"completed",phase:"done",pid:null,error:null,checkpoint:r})})}function P(e){if(e<l.MIN_UPLOAD_SIZE||e>l.MAX_UPLOAD_SIZE)throw I(`Content must be between ${l.MIN_UPLOAD_SIZE} and ${l.MAX_UPLOAD_SIZE} bytes; got ${e}.`,"path")}function C(e){return e==="folder"?V:X}async function Y(e,t){let i=Z(e,{signal:t});return(await D(i)).toString()}function c(e,t,i,r){return b(e.db,t.id,{checkpoint:i,...r?{phase:r}:{}})}async function x(e,t){let{input:i}=t,r=i.kind??"file",n=i.name??"upload",d=e.signal;if(!i.sourcePath)throw new Error(`Operation ${t.id} has no source.`);let a=i.sourcePath;if(r==="folder"&&(a=Q(e.stagingDir(t.id),"folder.car"),!await y(a).catch(()=>{}))){if(t.checkpoint.pieceCid)throw new m({code:p.stagingMissing,message:`The staged CAR of ${t.id} is missing, so it cannot be resumed.`,next:[{by:"agent",command:`fil put ${i.sourcePath}`,description:"Start a new put of the same directory"}]});t=c(e,t,{},"packing"),e.progress?.({phase:"packing",message:`Packing ${i.sourcePath}`});let U=await w(i.sourcePath,a);t=c(e,t,{rootCid:U.rootCid.toString(),size:U.size})}d?.throwIfAborted();let o=(await y(a)).size;P(o),e.progress?.({phase:"hashing",message:"Computing PieceCID"});let u=await Y(a,d);if(t.checkpoint.pieceCid&&t.checkpoint.pieceCid!==u)throw new m({code:p.sourceChanged,message:`${a} changed since operation ${t.id} started.`,next:[{by:"agent",command:`fil put ${i.sourcePath}`,description:"Start a new put with the current content"}]});t=c(e,t,{pieceCid:u,size:o},"storing");let s=ie(t.checkpoint);if(!s){e.progress?.({phase:"placing",message:"Selecting a storage provider"}),s=await e.backend.selectPlacement({metadata:C(r),providerId:i.providerId?BigInt(i.providerId):void 0});let h=await e.backend.quote({size:o,placement:s});if(!h.ready)throw te(h);t=c(e,t,{providerId:s.providerId.toString(),serviceURL:s.serviceURL,payee:s.payee,...s.dataSetId==null?{}:{dataSetId:s.dataSetId.toString(),clientDataSetId:s.clientDataSetId?.toString()}})}t.checkpoint.commit||t.checkpoint.stored||(await e.backend.hasPiece({serviceURL:s.serviceURL,pieceCid:u})||(e.progress?.({phase:"uploading",message:`Uploading ${o} bytes to provider ${s.providerId}`}),await e.backend.upload({serviceURL:s.serviceURL,path:a,size:o,pieceCid:u})),t=c(e,t,{stored:!0}));let f=await ee(e,t,s,{pieceCid:u,name:n}),R=z({apiUrl:e.apiUrl,chainId:t.chainId,pieceCid:u,rootCid:t.checkpoint.rootCid}),k={ref:t.resourceRef,kind:r,name:n,chainId:t.chainId,payer:t.payer,pieceCid:u,...t.checkpoint.rootCid?{rootCid:t.checkpoint.rootCid}:{},size:o,copies:[{providerId:s.providerId.toString(),dataSetId:f.dataSetId.toString(),pieceId:f.pieceId.toString(),serviceURL:s.serviceURL}],url:R.browser,status:"active",createdAt:new Date().toISOString()};return H(e,t,k,{dataSetId:f.dataSetId.toString(),pieceId:f.pieceId.toString()}),r==="folder"&&await j(e.stagingDir(t.id),{recursive:!0,force:!0}).catch(()=>{}),{operationId:t.id,state:"ready",resource:k,urls:R}}async function ee(e,t,i,r){let n={name:r.name.slice(0,G),...t.checkpoint.rootCid?{ipfsRootCID:t.checkpoint.rootCid}:{}},d=t.checkpoint.commit;if(d){let o=await e.backend.findCommit({nonce:BigInt(d.nonce)});if(o)return o}t=c(e,t,{},"committing");let a=d;if(a||(e.progress?.({phase:"committing",message:"Signing the commit"}),a=await e.backend.signCommit({placement:i,pieceCid:r.pieceCid,metadata:C(t.input.kind??"file"),pieceMetadata:n}),t=c(e,t,{commit:a})),!t.checkpoint.statusUrl){e.progress?.({phase:"committing",message:a.created?"Creating data set and adding piece":"Adding piece"});let o=await e.backend.submitCommit({placement:i,pieceCid:r.pieceCid,commit:a,pieceMetadata:n});t=c(e,t,{statusUrl:o.statusUrl,transactionHash:o.transactionHash})}e.progress?.({phase:"committing",message:"Waiting for on-chain confirmation"});try{return await e.backend.waitForCommit({statusUrl:t.checkpoint.statusUrl,created:a.created})}catch(o){throw O(o)&&o.code===p.commitRejected&&c(e,t,{statusUrl:void 0,transactionHash:void 0}),o}}function te(e){return new m({code:p.insufficientFunds,message:e.needsApproval?"The payer must deposit USDFC and approve Warm Storage before uploading.":"The payer must deposit more USDFC before uploading.",details:{fundingUrl:e.fundingUrl,depositNeeded:e.depositNeeded.toString(),needsApproval:e.needsApproval},next:[{by:"user",description:`Fund the account at ${e.fundingUrl}`}]})}function ie(e){if(e.providerId&&e.serviceURL&&e.payee)return{providerId:BigInt(e.providerId),serviceURL:e.serviceURL,payee:e.payee,...e.dataSetId&&e.clientDataSetId?{dataSetId:BigInt(e.dataSetId),clientDataSetId:BigInt(e.clientDataSetId)}:{}}}async function ve(e,t){let i=v(e.db,t,e);if(!i)throw g(`No managed resource ${t} for this account.`,{by:"agent",command:"fil ls",description:"List managed resources"});if(i.status!=="active")throw I(`${t} is already pending removal.`,"ref");let[r]=i.copies;if(!r)throw new Error(`Resource ${t} has no stored copies.`);let n=S(e.db,{action:"delete",resourceRef:t,chainId:e.chainId,payer:e.payer,input:{},checkpoint:{providerId:r.providerId,serviceURL:r.serviceURL,dataSetId:r.dataSetId,pieceId:r.pieceId}});return await M(e,n.id)}async function re(e,t){let i=v(e.db,t.resourceRef);if(!i)throw g(`Resource ${t.resourceRef} no longer exists.`);let{serviceURL:r,dataSetId:n,pieceId:d}=t.checkpoint;if(!(r&&n&&d))throw new Error(`Operation ${t.id} is missing its removal target.`);if(!t.checkpoint.transactionHash){t=c(e,t,{},"removing"),e.progress?.({phase:"removing",message:`Scheduling removal of piece ${d}`});let{transactionHash:s}=await e.backend.schedulePieceRemoval({serviceURL:r,dataSetId:BigInt(n),pieceId:BigInt(d)});t=c(e,t,{transactionHash:s})}let a=t.checkpoint.transactionHash;if(e.progress?.({phase:"removing",message:"Waiting for the removal transaction"}),(await e.backend.waitForTransaction(a)).status!=="success")throw c(e,t,{transactionHash:void 0}),new m({code:p.removalReverted,message:`Removal transaction ${a} reverted; the piece is still stored.`});let u={...i,status:"removal_pending"};return H(e,t,u),N(e,t,u)}export{Ie as a,be as b,M as c,K as d,ve as e};
|
|
3
|
+
//# sourceMappingURL=chunk-IJ2NNDTJ.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/storage/jobs.ts"],
|
|
4
|
+
"sourcesContent": ["import { createReadStream } from 'node:fs'\nimport { rm, stat } from 'node:fs/promises'\nimport { basename, join, resolve } from 'node:path'\nimport type { DatabaseSync } from 'node:sqlite'\nimport * as Piece from '@filoz/synapse-core/piece'\nimport { SIZE_CONSTANTS } from '@filoz/synapse-core/utils'\nimport { CliError, isCliError } from 'clipact'\nimport {\n ErrorCodes,\n invalidInput,\n notFound,\n operationError,\n} from '../errors.ts'\nimport { transaction } from '../state/db.ts'\nimport { createId } from '../state/ids.ts'\nimport {\n acquireOperation,\n type Checkpoint,\n createOperation,\n getOperation,\n type Operation,\n releaseOperation,\n updateOperation,\n} from '../state/operations.ts'\nimport { getResource, type Resource, saveResource } from '../state/resources.ts'\nimport { packDirectory } from './pack.ts'\nimport type {\n CommittedPiece,\n Placement,\n StorageBackend,\n UploadQuote,\n} from './types.ts'\nimport { type RetrievalUrls, resourceUrls, retrievalUrls } from './urls.ts'\n\n/** Data-set metadata namespacing CLI uploads of raw files. */\nexport const FILE_DATA_SET_METADATA = { source: 'fil' }\n\n/**\n * Data-set metadata for folders. `withIPFSIndexing` asks Curio to index\n * the CAR so `/ipfs/<rootCid>` retrieval works.\n */\nexport const FOLDER_DATA_SET_METADATA = {\n source: 'fil',\n withIPFSIndexing: '',\n}\n\n/** Longest metadata value FWSS accepts. */\nconst MAX_METADATA_VALUE = 96\n\n/** A step of a job, reported as progress. */\nexport type JobPhase =\n | 'packing'\n | 'hashing'\n | 'placing'\n | 'uploading'\n | 'committing'\n | 'removing'\n\n/** Everything a put or delete job needs besides its saved record. */\nexport type JobContext = {\n db: DatabaseSync\n backend: StorageBackend\n chainId: string\n payer: string\n /** fil-api origin for retrieval links. */\n apiUrl: string\n /** Staging directory for an operation. */\n stagingDir: (operationId: string) => string\n /** Aborted on SIGINT, SIGTERM, or SIGHUP; stops at the next step. */\n signal?: AbortSignal\n /** Progress for the caller to report on stderr. */\n progress?: (event: { phase: JobPhase; message: string }) => void\n /** Called once the job's operation is saved and locked. */\n onOperation?: (operation: Operation) => void\n}\n\n/** Outcome of a put or delete, shaped for command output. */\nexport type JobResult = {\n operationId: string\n state: 'ready' | 'removal_pending'\n resource: Resource\n urls: RetrievalUrls\n}\n\n/** Options for {@link startPut}. */\nexport type StartPutOptions = {\n path: string\n name?: string | undefined\n providerId?: bigint | undefined\n}\n\n/** A file or directory checked for a put. */\ntype PutSource = {\n sourcePath: string\n kind: 'file' | 'folder'\n name: string\n /** Bytes of a file; directories are sized after packing. */\n size?: number\n}\n\n/** Check that `path` is a storable file or directory. */\nasync function inspectSource(options: StartPutOptions): Promise<PutSource> {\n const sourcePath = resolve(options.path)\n const stats = await stat(sourcePath).catch(() => undefined)\n if (!stats || !(stats.isFile() || stats.isDirectory())) {\n throw invalidInput(`No file or directory at ${options.path}.`, 'path')\n }\n const name = options.name ?? basename(sourcePath)\n if (stats.isDirectory()) return { sourcePath, kind: 'folder', name }\n assertPieceSize(stats.size)\n return { sourcePath, kind: 'file', name, size: stats.size }\n}\n\n/**\n * Validate the input, save a new put operation before any external mutation,\n * then run it.\n */\nexport async function startPut(\n ctx: JobContext,\n options: StartPutOptions\n): Promise<JobResult> {\n const source = await inspectSource(options)\n const op = createOperation(ctx.db, {\n action: 'put',\n resourceRef: createId('res'),\n chainId: ctx.chainId,\n payer: ctx.payer,\n input: {\n sourcePath: source.sourcePath,\n name: source.name,\n kind: source.kind,\n providerId: options.providerId?.toString(),\n },\n })\n return await runOperation(ctx, op.id)\n}\n\n/** What a put would do, from {@link estimatePut}. */\nexport type PutEstimate = {\n kind: 'file' | 'folder'\n name: string\n /** Bytes to store: the file, or the packed CAR. */\n size: number\n /** Files in a directory; 1 for a file. */\n files: number\n /** IPFS root CID of a directory. */\n rootCid?: string\n /** Chosen provider and quote, when a session key is available. */\n placement?: Placement\n quote?: UploadQuote\n}\n\n/** Options for {@link estimatePut}. */\nexport type EstimatePutOptions = StartPutOptions & {\n /** Prices the upload; omitted when not logged in. */\n backend?: StorageBackend | undefined\n}\n\n/**\n * Describe a put without side effects on providers or the chain: content\n * inventory, stored size, and, with a backend, the provider it would use and\n * what it would cost. Directories are packed only to measure the CAR;\n * nothing is written to disk.\n */\nexport async function estimatePut(\n options: EstimatePutOptions\n): Promise<PutEstimate> {\n const source = await inspectSource(options)\n let estimate: PutEstimate\n if (source.kind === 'file') {\n estimate = {\n kind: 'file',\n name: source.name,\n size: source.size ?? 0,\n files: 1,\n }\n } else {\n const packed = await packDirectory(source.sourcePath)\n assertPieceSize(packed.size)\n estimate = {\n kind: 'folder',\n name: source.name,\n size: packed.size,\n files: packed.files,\n rootCid: packed.rootCid.toString(),\n }\n }\n if (!options.backend) return estimate\n const placement = await options.backend.selectPlacement({\n metadata: metadataFor(estimate.kind),\n providerId: options.providerId,\n })\n const quote = await options.backend.quote({ size: estimate.size, placement })\n return { ...estimate, placement, quote }\n}\n\n/**\n * Run or resume an operation. A completed operation returns its saved\n * outcome. Otherwise this takes the execution lock, continues from the saved\n * checkpoint, and records failures so the job can be resumed with\n * `fil operations resume`.\n */\nexport async function runOperation(\n ctx: JobContext,\n operationId: string\n): Promise<JobResult> {\n const saved = getOperation(ctx.db, operationId)\n if (!saved) throw notFound(`Operation ${operationId} not found.`)\n if (saved.executionStatus === 'completed') return savedOutcome(ctx, saved)\n const op = acquireOperation(ctx.db, operationId)\n try {\n ctx.onOperation?.(op)\n return op.action === 'put'\n ? await runPut(ctx, op)\n : await runRemove(ctx, op)\n } catch (error) {\n updateOperation(ctx.db, op.id, {\n executionStatus: 'failed',\n pid: null,\n error: ctx.signal?.aborted\n ? 'Interrupted'\n : error instanceof Error\n ? error.message\n : String(error),\n })\n // clipact reports an interruption itself, with the checkpoint's steps.\n if (ctx.signal?.aborted) throw error\n throw operationError(error, op.id)\n } finally {\n releaseOperation(op.id)\n }\n}\n\n/** The saved outcome of a completed operation; nothing is re-run. */\nexport function savedOutcome(\n ctx: Pick<JobContext, 'db' | 'apiUrl'>,\n op: Operation\n): JobResult {\n const resource = getResource(ctx.db, op.resourceRef)\n if (!resource) {\n throw notFound(`Resource ${op.resourceRef} of ${op.id} no longer exists.`)\n }\n return jobResult(ctx, op, resource)\n}\n\n/** Shape a finished operation and its resource for command output. */\nfunction jobResult(\n ctx: Pick<JobContext, 'apiUrl'>,\n op: Operation,\n resource: Resource\n): JobResult {\n return {\n operationId: op.id,\n state: op.action === 'put' ? 'ready' : 'removal_pending',\n resource,\n urls: resourceUrls(resource, ctx.apiUrl),\n }\n}\n\n/**\n * Save the resource and mark the operation completed in one transaction, so\n * a stop at this point leaves a finished job, never a half-finished one.\n */\nfunction complete(\n ctx: JobContext,\n op: Operation,\n resource: Resource,\n checkpoint: Checkpoint = {}\n): void {\n transaction(ctx.db, () => {\n saveResource(ctx.db, resource)\n updateOperation(ctx.db, op.id, {\n executionStatus: 'completed',\n phase: 'done',\n pid: null,\n error: null,\n checkpoint,\n })\n })\n}\n\n/** Reject sizes outside the PDP piece limits. */\nfunction assertPieceSize(size: number): void {\n if (\n size < SIZE_CONSTANTS.MIN_UPLOAD_SIZE ||\n size > SIZE_CONSTANTS.MAX_UPLOAD_SIZE\n ) {\n throw invalidInput(\n `Content must be between ${SIZE_CONSTANTS.MIN_UPLOAD_SIZE} and ${SIZE_CONSTANTS.MAX_UPLOAD_SIZE} bytes; got ${size}.`,\n 'path'\n )\n }\n}\n\n/** Data-set metadata for a resource kind. */\nfunction metadataFor(kind: 'file' | 'folder') {\n return kind === 'folder' ? FOLDER_DATA_SET_METADATA : FILE_DATA_SET_METADATA\n}\n\n/**\n * Compute the PieceCID of a file by streaming it. Aborting `signal` destroys\n * the read stream, which stops the hashing.\n */\nasync function pieceCidOf(path: string, signal?: AbortSignal): Promise<string> {\n const stream = createReadStream(path, { signal })\n return (await Piece.calculate(stream)).toString()\n}\n\n/** Save checkpoint fields and return the updated operation. */\nfunction save(\n ctx: JobContext,\n op: Operation,\n checkpoint: Checkpoint,\n phase?: Operation['phase']\n): Operation {\n return updateOperation(ctx.db, op.id, {\n checkpoint,\n ...(phase ? { phase } : {}),\n })\n}\n\n/**\n * Put steps: pack (folders), identify, place, upload, commit, record. Each\n * step saves its result first, so a resumed job skips completed work and\n * never sends a second commit for the same content.\n */\nasync function runPut(ctx: JobContext, op: Operation): Promise<JobResult> {\n const { input } = op\n const kind = input.kind ?? 'file'\n const name = input.name ?? 'upload'\n const signal = ctx.signal\n if (!input.sourcePath) throw new Error(`Operation ${op.id} has no source.`)\n\n // Prepare the bytes to store.\n let uploadPath = input.sourcePath\n if (kind === 'folder') {\n uploadPath = join(ctx.stagingDir(op.id), 'folder.car')\n const staged = await stat(uploadPath).catch(() => undefined)\n if (!staged) {\n if (op.checkpoint.pieceCid) {\n throw new CliError({\n code: ErrorCodes.stagingMissing,\n message: `The staged CAR of ${op.id} is missing, so it cannot be resumed.`,\n next: [\n {\n by: 'agent',\n command: `fil put ${input.sourcePath}`,\n description: 'Start a new put of the same directory',\n },\n ],\n })\n }\n op = save(ctx, op, {}, 'packing')\n ctx.progress?.({\n phase: 'packing',\n message: `Packing ${input.sourcePath}`,\n })\n const packed = await packDirectory(input.sourcePath, uploadPath)\n op = save(ctx, op, {\n rootCid: packed.rootCid.toString(),\n size: packed.size,\n })\n }\n }\n\n signal?.throwIfAborted()\n const size = (await stat(uploadPath)).size\n assertPieceSize(size)\n ctx.progress?.({ phase: 'hashing', message: 'Computing PieceCID' })\n const pieceCid = await pieceCidOf(uploadPath, signal)\n if (op.checkpoint.pieceCid && op.checkpoint.pieceCid !== pieceCid) {\n throw new CliError({\n code: ErrorCodes.sourceChanged,\n message: `${uploadPath} changed since operation ${op.id} started.`,\n next: [\n {\n by: 'agent',\n command: `fil put ${input.sourcePath}`,\n description: 'Start a new put with the current content',\n },\n ],\n })\n }\n op = save(ctx, op, { pieceCid, size }, 'storing')\n\n // Choose a provider once; resumes reuse it.\n let placement = placementOf(op.checkpoint)\n if (!placement) {\n ctx.progress?.({\n phase: 'placing',\n message: 'Selecting a storage provider',\n })\n placement = await ctx.backend.selectPlacement({\n metadata: metadataFor(kind),\n providerId: input.providerId ? BigInt(input.providerId) : undefined,\n })\n const quote = await ctx.backend.quote({ size, placement })\n if (!quote.ready) throw insufficientFunds(quote)\n op = save(ctx, op, {\n providerId: placement.providerId.toString(),\n serviceURL: placement.serviceURL,\n payee: placement.payee,\n ...(placement.dataSetId == null\n ? {}\n : {\n dataSetId: placement.dataSetId.toString(),\n clientDataSetId: placement.clientDataSetId?.toString(),\n }),\n })\n }\n\n // Upload unless the provider already has the piece.\n if (!(op.checkpoint.commit || op.checkpoint.stored)) {\n const present = await ctx.backend.hasPiece({\n serviceURL: placement.serviceURL,\n pieceCid,\n })\n if (!present) {\n ctx.progress?.({\n phase: 'uploading',\n message: `Uploading ${size} bytes to provider ${placement.providerId}`,\n })\n await ctx.backend.upload({\n serviceURL: placement.serviceURL,\n path: uploadPath,\n size,\n pieceCid,\n })\n }\n op = save(ctx, op, { stored: true })\n }\n\n const committed = await commit(ctx, op, placement, { pieceCid, name })\n\n const urls = retrievalUrls({\n apiUrl: ctx.apiUrl,\n chainId: op.chainId,\n pieceCid,\n rootCid: op.checkpoint.rootCid,\n })\n const resource: Resource = {\n ref: op.resourceRef,\n kind,\n name,\n chainId: op.chainId,\n payer: op.payer,\n pieceCid,\n ...(op.checkpoint.rootCid ? { rootCid: op.checkpoint.rootCid } : {}),\n size,\n copies: [\n {\n providerId: placement.providerId.toString(),\n dataSetId: committed.dataSetId.toString(),\n pieceId: committed.pieceId.toString(),\n serviceURL: placement.serviceURL,\n },\n ],\n url: urls.browser,\n status: 'active',\n createdAt: new Date().toISOString(),\n }\n complete(ctx, op, resource, {\n dataSetId: committed.dataSetId.toString(),\n pieceId: committed.pieceId.toString(),\n })\n if (kind === 'folder') {\n await rm(ctx.stagingDir(op.id), { recursive: true, force: true }).catch(\n () => undefined\n )\n }\n return { operationId: op.id, state: 'ready', resource, urls }\n}\n\n/**\n * Commit the stored piece on chain exactly once. The commit is signed with a\n * fresh nonce and saved before it is sent. A resume first asks FWSS whether\n * that nonce was used; if so, the commit landed and nothing is sent. If not,\n * the same signature is sent again, and FWSS rejects any second use of its\n * nonce, so at most one commit takes effect.\n *\n * @see https://github.com/hugomrdias/fil/issues/1\n */\nasync function commit(\n ctx: JobContext,\n op: Operation,\n placement: Placement,\n piece: { pieceCid: string; name: string }\n): Promise<CommittedPiece> {\n const pieceMetadata: Record<string, string> = {\n name: piece.name.slice(0, MAX_METADATA_VALUE),\n ...(op.checkpoint.rootCid ? { ipfsRootCID: op.checkpoint.rootCid } : {}),\n }\n const saved = op.checkpoint.commit\n if (saved) {\n const landed = await ctx.backend.findCommit({ nonce: BigInt(saved.nonce) })\n if (landed) return landed\n }\n\n op = save(ctx, op, {}, 'committing')\n let signed = saved\n if (!signed) {\n ctx.progress?.({ phase: 'committing', message: 'Signing the commit' })\n signed = await ctx.backend.signCommit({\n placement,\n pieceCid: piece.pieceCid,\n metadata: metadataFor(op.input.kind ?? 'file'),\n pieceMetadata,\n })\n op = save(ctx, op, { commit: signed })\n }\n\n if (!op.checkpoint.statusUrl) {\n ctx.progress?.({\n phase: 'committing',\n message: signed.created\n ? 'Creating data set and adding piece'\n : 'Adding piece',\n })\n const submission = await ctx.backend.submitCommit({\n placement,\n pieceCid: piece.pieceCid,\n commit: signed,\n pieceMetadata,\n })\n op = save(ctx, op, {\n statusUrl: submission.statusUrl,\n transactionHash: submission.transactionHash,\n })\n }\n\n ctx.progress?.({\n phase: 'committing',\n message: 'Waiting for on-chain confirmation',\n })\n try {\n return await ctx.backend.waitForCommit({\n statusUrl: op.checkpoint.statusUrl as string,\n created: signed.created,\n })\n } catch (error) {\n if (isCliError(error) && error.code === ErrorCodes.commitRejected) {\n // A failed transaction leaves the nonce unused; forget its status so a\n // resume sends the same signature again.\n save(ctx, op, { statusUrl: undefined, transactionHash: undefined })\n }\n throw error\n }\n}\n\n/** Error returned when the payer cannot cover an upload. */\nfunction insufficientFunds(quote: UploadQuote): CliError {\n return new CliError({\n code: ErrorCodes.insufficientFunds,\n message: quote.needsApproval\n ? 'The payer must deposit USDFC and approve Warm Storage before uploading.'\n : 'The payer must deposit more USDFC before uploading.',\n details: {\n fundingUrl: quote.fundingUrl,\n depositNeeded: quote.depositNeeded.toString(),\n needsApproval: quote.needsApproval,\n },\n next: [\n {\n by: 'user',\n description: `Fund the account at ${quote.fundingUrl}`,\n },\n ],\n })\n}\n\n/** Rebuild a saved placement from a checkpoint. */\nfunction placementOf(checkpoint: Checkpoint): Placement | undefined {\n if (!(checkpoint.providerId && checkpoint.serviceURL && checkpoint.payee)) {\n return undefined\n }\n return {\n providerId: BigInt(checkpoint.providerId),\n serviceURL: checkpoint.serviceURL,\n payee: checkpoint.payee as `0x${string}`,\n ...(checkpoint.dataSetId && checkpoint.clientDataSetId\n ? {\n dataSetId: BigInt(checkpoint.dataSetId),\n clientDataSetId: BigInt(checkpoint.clientDataSetId),\n }\n : {}),\n }\n}\n\n/**\n * Save a new delete operation for a managed resource, then run it.\n */\nexport async function startRemove(\n ctx: JobContext,\n ref: string\n): Promise<JobResult> {\n const resource = getResource(ctx.db, ref, ctx)\n if (!resource) {\n throw notFound(`No managed resource ${ref} for this account.`, {\n by: 'agent',\n command: 'fil ls',\n description: 'List managed resources',\n })\n }\n if (resource.status !== 'active') {\n throw invalidInput(`${ref} is already pending removal.`, 'ref')\n }\n const [copy] = resource.copies\n if (!copy) throw new Error(`Resource ${ref} has no stored copies.`)\n const op = createOperation(ctx.db, {\n action: 'delete',\n resourceRef: ref,\n chainId: ctx.chainId,\n payer: ctx.payer,\n input: {},\n checkpoint: {\n providerId: copy.providerId,\n serviceURL: copy.serviceURL,\n dataSetId: copy.dataSetId,\n pieceId: copy.pieceId,\n },\n })\n return await runOperation(ctx, op.id)\n}\n\n/**\n * Schedule removal of the resource's piece and wait for the transaction.\n * The provider deletes the data at its next proving boundary, so the result\n * is `removal_pending`. A reverted transaction leaves the resource active.\n */\nasync function runRemove(ctx: JobContext, op: Operation): Promise<JobResult> {\n const resource = getResource(ctx.db, op.resourceRef)\n if (!resource) throw notFound(`Resource ${op.resourceRef} no longer exists.`)\n const { serviceURL, dataSetId, pieceId } = op.checkpoint\n if (!(serviceURL && dataSetId && pieceId)) {\n throw new Error(`Operation ${op.id} is missing its removal target.`)\n }\n if (!op.checkpoint.transactionHash) {\n op = save(ctx, op, {}, 'removing')\n ctx.progress?.({\n phase: 'removing',\n message: `Scheduling removal of piece ${pieceId}`,\n })\n const { transactionHash } = await ctx.backend.schedulePieceRemoval({\n serviceURL,\n dataSetId: BigInt(dataSetId),\n pieceId: BigInt(pieceId),\n })\n op = save(ctx, op, { transactionHash })\n }\n const hash = op.checkpoint.transactionHash as `0x${string}`\n ctx.progress?.({\n phase: 'removing',\n message: 'Waiting for the removal transaction',\n })\n const receipt = await ctx.backend.waitForTransaction(hash)\n if (receipt.status !== 'success') {\n // The reverted transaction had no effect; a resume signs a new one.\n save(ctx, op, { transactionHash: undefined })\n throw new CliError({\n code: ErrorCodes.removalReverted,\n message: `Removal transaction ${hash} reverted; the piece is still stored.`,\n })\n }\n const updated: Resource = { ...resource, status: 'removal_pending' }\n complete(ctx, op, updated)\n return jobResult(ctx, op, updated)\n}\n"],
|
|
5
|
+
"mappings": ";iTAAA,OAAS,oBAAAA,MAAwB,UACjC,OAAS,MAAAC,EAAI,QAAAC,MAAY,mBACzB,OAAS,YAAAC,EAAU,QAAAC,EAAM,WAAAC,MAAe,YAiCjC,IAAMC,EAAyB,CAAE,OAAQ,KAAM,EAMzCC,EAA2B,CACtC,OAAQ,MACR,iBAAkB,EACpB,EAGMC,EAAqB,GAsD3B,eAAeC,EAAcC,EAA8C,CACzE,IAAMC,EAAaC,EAAQF,EAAQ,IAAI,EACjCG,EAAQ,MAAMC,EAAKH,CAAU,EAAE,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AAMrE,EAAI,QAAQ,qBAAqB,CACjE,WAAAkE,EACA,UAAW,OAAOC,CAAS,EAC3B,QAAS,OAAOC,CAAO,CACzB,CAAC,EACDlE,EAAKwC,EAAK1C,EAAKE,EAAI,CAAE,gBAAAmE,CAAgB,CAAC,CACxC,CACA,IAAMC,EAAOpE,EAAG,WAAW,gBAM3B,GALAF,EAAI,WAAW,CACb,MAAO,WACP,QAAS,qCACX,CAAC,GACe,MAAMA,EAAI,QAAQ,mBAAmBsE,CAAI,GAC7C,SAAW,UAErB,MAAA5B,EAAK1C,EAAKE,EAAI,CAAE,gBAAiB,MAAU,CAAC,EACtC,IAAI6C,EAAS,CACjB,KAAMC,EAAW,gBACjB,QAAS,uBAAuBsB,CAAI,uCACtC,CAAC,EAEH,IAAMC,EAAoB,CAAE,GAAG9C,EAAU,OAAQ,iBAAkB,EACnE,OAAAI,EAAS7B,EAAKE,EAAIqE,CAAO,EAClB5C,EAAU3B,EAAKE,EAAIqE,CAAO,CACnC",
|
|
6
|
+
"names": ["createReadStream", "rm", "stat", "basename", "join", "resolve", "FILE_DATA_SET_METADATA", "FOLDER_DATA_SET_METADATA", "MAX_METADATA_VALUE", "inspectSource", "options", "sourcePath", "resolve", "stats", "stat", "invalidInput", "name", "basename", "assertPieceSize", "startPut", "ctx", "source", "op", "createOperation", "createId", "runOperation", "estimatePut", "estimate", "packed", "packDirectory", "placement", "metadataFor", "quote", "operationId", "saved", "getOperation", "notFound", "savedOutcome", "acquireOperation", "runPut", "runRemove", "error", "updateOperation", "operationError", "releaseOperation", "resource", "getResource", "jobResult", "resourceUrls", "complete", "checkpoint", "transaction", "saveResource", "size", "SIZE_CONSTANTS", "kind", "pieceCidOf", "path", "signal", "stream", "createReadStream", "calculate", "save", "phase", "input", "uploadPath", "join", "CliError", "ErrorCodes", "pieceCid", "placementOf", "insufficientFunds", "committed", "commit", "urls", "retrievalUrls", "rm", "piece", "pieceMetadata", "landed", "signed", "submission", "isCliError", "startRemove", "ref", "copy", "serviceURL", "dataSetId", "pieceId", "transactionHash", "hash", "updated"]
|
|
7
|
+
}
|