@humain/humain-code 0.4.9 → 0.4.10
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/CHANGELOG.md +22 -0
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +39 -45
- package/dist/bundle/chunks/{chunk-6FVNSW6B.js → chunk-2QTTNAD4.js} +3353 -3938
- package/dist/bundle/chunks/chunk-76X5KOIA.js +28 -0
- package/dist/bundle/chunks/{chunk-KRMTBTWU.js → chunk-77EWF2NW.js} +1 -1
- package/dist/bundle/chunks/{chunk-RBKDBF5G.js → chunk-AS2Y2MO6.js} +36 -36
- package/dist/bundle/chunks/{chunk-4LAKI5IL.js → chunk-AUFEF24K.js} +1 -1
- package/dist/bundle/chunks/{chunk-P4YMUUSK.js → chunk-BCF7KZ3R.js} +739 -730
- package/dist/bundle/chunks/{chunk-W2QRCQBX.js → chunk-FF26YENK.js} +3 -4
- package/dist/bundle/chunks/{chunk-UZ5FVVCP.js → chunk-HMWAH7ZY.js} +1 -1
- package/dist/bundle/chunks/{chunk-F7UMX5BV.js → chunk-HSDTSUZE.js} +13 -2
- package/dist/bundle/chunks/chunk-I2ZWZAIV.js +751 -0
- package/dist/bundle/chunks/{chunk-GUUAEK6G.js → chunk-LCOHFEZZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-Z5LYSSTY.js → chunk-QSPDLT2R.js} +2 -2
- package/dist/bundle/chunks/{chunk-UBQSONVR.js → chunk-R5VIAWGA.js} +103 -145
- package/dist/bundle/chunks/{chunk-EMYNPLY5.js → chunk-V5ZF7Q7L.js} +1 -1
- package/dist/bundle/chunks/{chunk-LQ4S7CRR.js → chunk-VYIIPF57.js} +1 -1
- package/dist/bundle/chunks/chunk-WBJN6PEI.js +43 -0
- package/dist/bundle/chunks/{chunk-SWRU4BOC.js → chunk-XGO43DKL.js} +1 -1
- package/dist/bundle/chunks/{chunk-PMISFIBM.js → chunk-XMHLSV3I.js} +1 -1
- package/dist/bundle/chunks/{chunk-3E4SMILM.js → chunk-YJBE3IGR.js} +14 -14
- package/dist/bundle/chunks/{cli-ZKT34WPW.js → cli-5ACW3WND.js} +2 -2
- package/dist/bundle/chunks/{compat-HEUVP6UJ.js → compat-TQKA4I7M.js} +1 -1
- package/dist/bundle/chunks/{dist-NU2EIVT6.js → dist-WHC67QRM.js} +676 -550
- package/dist/bundle/chunks/dist-cjs-RL2OCAP2.js +179 -0
- package/dist/bundle/chunks/{easter-egg-3d-5KKDWEIA.js → easter-egg-3d-3L3IKAT6.js} +1 -1
- package/dist/bundle/chunks/{esm-NCUV2DF7.js → esm-763X2IA7.js} +1 -1
- package/dist/bundle/chunks/event-streams-R5OECII4.js +2 -0
- package/dist/bundle/chunks/{execute-OSBDNQU5.js → execute-4X6G65NZ.js} +1 -1
- package/dist/bundle/chunks/{extract-PYRMDATF.js → extract-DLZ425VI.js} +4 -4
- package/dist/bundle/chunks/github-copilot.js +32 -31
- package/dist/bundle/chunks/{google-generative-ai-H2F5Y5H2.js → google-generative-ai-JD2FVOIX.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-LFWD2AOO.js → google-vertex-PFBMDCBW.js} +1 -1
- package/dist/bundle/chunks/{host-6ZA6LK4C.js → host-4J7H7KDS.js} +1 -1
- package/dist/bundle/chunks/{node-XGNY74WT.js → node-W47VUEGE.js} +1 -1
- package/dist/bundle/chunks/{runtime-JFLZUNYP.js → runtime-SI76JZNE.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-ID2GA4GE.js +5 -0
- package/dist/bundle/cli-runtime.js +3 -3
- package/dist/bundle/flow/package.json +1 -1
- package/dist/bundle/index.js +17 -17
- package/dist/bundle/rpc-entry.js +3 -2
- package/dist/core/account-reporting.d.ts +109 -0
- package/dist/core/account-reporting.d.ts.map +1 -0
- package/dist/core/account-reporting.js +328 -0
- package/dist/core/account-reporting.js.map +1 -0
- package/dist/core/agent-session.d.ts +22 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +131 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/anthropic-account-reporting.d.ts +76 -0
- package/dist/core/anthropic-account-reporting.d.ts.map +1 -0
- package/dist/core/anthropic-account-reporting.js +380 -0
- package/dist/core/anthropic-account-reporting.js.map +1 -0
- package/dist/core/bedrock-account-reporting.d.ts +82 -0
- package/dist/core/bedrock-account-reporting.d.ts.map +1 -0
- package/dist/core/bedrock-account-reporting.js +402 -0
- package/dist/core/bedrock-account-reporting.js.map +1 -0
- package/dist/core/model-runtime.d.ts +17 -0
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +64 -10
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/oauth-account-pool.d.ts +4 -0
- package/dist/core/oauth-account-pool.d.ts.map +1 -1
- package/dist/core/oauth-account-pool.js +10 -3
- package/dist/core/oauth-account-pool.js.map +1 -1
- package/dist/humain/flow-accounts-host.d.ts +120 -0
- package/dist/humain/flow-accounts-host.d.ts.map +1 -0
- package/dist/humain/flow-accounts-host.js +346 -0
- package/dist/humain/flow-accounts-host.js.map +1 -0
- package/dist/humain/flow-command.d.ts +28 -0
- package/dist/humain/flow-command.d.ts.map +1 -0
- package/dist/humain/flow-command.js +226 -0
- package/dist/humain/flow-command.js.map +1 -0
- package/dist/humain/flow-loader.d.ts +4 -2
- package/dist/humain/flow-loader.d.ts.map +1 -1
- package/dist/humain/flow-loader.js +120 -91
- package/dist/humain/flow-loader.js.map +1 -1
- package/dist/humain/node-account-failure.d.ts +18 -0
- package/dist/humain/node-account-failure.d.ts.map +1 -0
- package/dist/humain/node-account-failure.js +73 -0
- package/dist/humain/node-account-failure.js.map +1 -0
- package/dist/humain/node-account-fallback.d.ts +85 -0
- package/dist/humain/node-account-fallback.d.ts.map +1 -0
- package/dist/humain/node-account-fallback.js +175 -0
- package/dist/humain/node-account-fallback.js.map +1 -0
- package/dist/humain/node-http.d.ts.map +1 -1
- package/dist/humain/node-http.js +11 -0
- package/dist/humain/node-http.js.map +1 -1
- package/dist/humain/node-provider.d.ts +4 -0
- package/dist/humain/node-provider.d.ts.map +1 -1
- package/dist/humain/node-provider.js +11 -0
- package/dist/humain/node-provider.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +5 -0
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +26 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +242 -19
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/docs/flow-profiles.md +57 -5
- package/docs/flow.md +119 -37
- package/docs/providers.md +37 -0
- package/npm-shrinkwrap.json +48 -6
- package/package.json +3 -2
- package/dist/bundle/chunks/chunk-JOKJ3CEL.js +0 -27
- package/dist/bundle/chunks/event-streams-CGCQQL5M.js +0 -2
- package/dist/bundle/chunks/virtual-modules-NPWQ6NBS.js +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow-loader.js","sourceRoot":"","sources":["../../src/humain/flow-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAG/D,OAAO,EAAE,WAAW,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAOvH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,k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wBACzD,CAAC;gCAAS,CAAC;4BACV,MAAM,aAAa,CAAC,IAAI,EAAE,GAAG,EAAE,UAAU,CAAC,CAAC;wBAC5C,CAAC;wBACD,OAAO;oBACR,CAAC;oBACD,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;gBAC/B,CAAC;aACD,CAAC,CAAC;QACJ,CAAC;IACF,CAAC,CAAC;AACH,CAAC","sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport type { FlowFailureClass } from \"@humain/humain-code-contracts/flow-common\";\nimport type { FlowEventFrameV1, FlowReceiptV1, FlowStatusV1 } from \"@humain/humain-code-contracts/flow-control\";\nimport { getAgentDir, getBundledFlowPackageDir, getBundledFlowProfilesDir, PACKAGE_NAME, VERSION } from \"../config.ts\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionFactory,\n\tRegisteredCommand,\n} from \"../core/extensions/types.ts\";\nimport { createTraceRedactor } from \"../core/trace/redaction.ts\";\nimport { sanitizeForTerminal } from \"../core/trace-client/sanitize.ts\";\n\n/**\n * Lazy loader for the private @humain/flow package.\n *\n * The CLI entry graph must not statically reach Flow: this module registers cheap stub commands and a flag, and\n * only loads Flow (one memoized dynamic import) the first time a stub runs. Flow is bundled as its own chunk.\n */\n\nexport const HUMAIN_FLOW_DISABLED_ENV = \"HUMAIN_TERMINAL_FLOW_DISABLED\";\nexport const HUMAIN_FLOW_PACKAGE_DIR_ENV = \"HUMAIN_TERMINAL_FLOW_PACKAGE_DIR\";\n\n/** Run-control surface Flow exposes to rpc mode (flow_status/pause/resume/cancel/message). */\nexport interface FlowRpcControl {\n\thandle(input: unknown): Promise<{ receipt: FlowReceiptV1; status?: FlowStatusV1 }>;\n\tactiveRunId(): string | undefined;\n}\n\nexport interface FlowModule {\n\tflowExtension: ExtensionFactory;\n\t/** Documented rpc hook: called once when Flow loads; `writeFrame` carries `flow_event` frames to the rpc host. */\n\tcreateFlowRpcControl?(options: {\n\t\twriteFrame?: (frame: FlowEventFrameV1) => void | Promise<void>;\n\t\tisDisabled?: () => boolean;\n\t\t/** Queues text on the host session as a follow-up (flow_message with no active run). */\n\t\tsendFollowUp?: (text: string) => Promise<void>;\n\t}): FlowRpcControl;\n\t/** B1 profile command; optional so test fakes need not provide it. Methods stay bivariant for the real signatures. */\n\trunFlowProfileCommand?(args: string, ctx: ExtensionCommandContext, deps: { store: unknown }): Promise<unknown>;\n\tcreateProfileStore?(options: { flowDir: string; builtInDir?: string }): unknown;\n}\n\nexport interface HumainFlowLoaderOptions {\n\t/** Test seam. Defaults to the single sanctioned dynamic import of @humain/flow. */\n\timportFlow?: () => Promise<FlowModule>;\n\tenv?: NodeJS.ProcessEnv;\n\t/** Directory holding Flow's agents/assets/package.json. Defaults to the bundled layout's flow/ dir. */\n\tflowPackageDir?: string;\n\t/** Built-in Flow profiles dir. Defaults to the bundled layout's assets/profiles; undefined lets Flow find its own. */\n\tbuiltInProfilesDir?: string;\n\t/** Flow profile store directory. Defaults to `<agentDir>/flow`. */\n\tflowDir?: string;\n}\n\nlet rpcControl: FlowRpcControl | undefined;\nlet disabledProbe: (() => boolean) | undefined;\nlet rpcOutput: ((frame: FlowEventFrameV1) => void | Promise<void>) | undefined;\nlet rpcLoader: (() => Promise<FlowRpcControl | undefined>) | undefined;\nlet rpcFollowUp: ((text: string) => Promise<void>) | undefined;\n\n/** The documented rpc hook: rpc mode reads Flow's run control here and never imports Flow itself. */\nexport function getFlowRpcControl(): FlowRpcControl | undefined {\n\treturn rpcControl;\n}\n\n/**\n * The documented rpc hook: loads Flow through the same lazy-load path the stub commands use and returns its run control.\n * Undefined when Flow is disabled (never loaded then), not wired, or fails to load.\n */\nexport async function loadFlowRpcControl(): Promise<FlowRpcControl | undefined> {\n\tif (rpcControl) return rpcControl;\n\tif (isFlowDisabled()) return undefined;\n\treturn rpcLoader?.();\n}\n\n/** True while Flow is switched off (flow.enabled=false or the env kill switch); rpc mode refuses flow_resume then. */\nexport function isFlowDisabled(): boolean {\n\treturn disabledProbe?.() ?? false;\n}\n\n/** The documented rpc hook: rpc mode registers where Flow's `flow_event` frames are written. */\nexport function setFlowRpcOutput(writer: ((frame: FlowEventFrameV1) => void | Promise<void>) | undefined): void {\n\trpcOutput = writer;\n}\n\n/** The documented rpc hook: rpc mode registers how direct-mode flow_message text is queued as a host follow-up. */\nexport function setFlowRpcFollowUp(queue: ((text: string) => Promise<void>) | undefined): void {\n\trpcFollowUp = queue;\n}\n\ntype CommandOptions = Omit<RegisteredCommand, \"name\" | \"sourceInfo\">;\ntype EventHandler = (...args: unknown[]) => unknown;\n\n/**\n * ExtensionAPI members that only record registrations (see core/extensions/loader.ts). They are staged while Flow's\n * factory runs and applied to the real pi only after the factory and the session_start replay succeed. Reads and\n * actions (getFlag, getSettings, exec, sendMessage, ...) and `events` stay live: they have no registration to undo\n * or are needed by the factory itself. Flow uses none of the live ones that subscribe (`events.on`).\n */\nconst STAGED_MEMBERS = new Set([\n\t\"on\",\n\t\"registerTool\",\n\t\"registerCommand\",\n\t\"registerShortcut\",\n\t\"registerFlag\",\n\t\"registerMessageRenderer\",\n\t\"registerMarkdownTransformer\",\n\t\"registerEntryRenderer\",\n\t\"registerProvider\",\n\t\"unregisterProvider\",\n\t\"registerMcpServer\",\n\t\"unregisterMcpServer\",\n\t\"registerVirtualModel\",\n\t\"unregisterVirtualModel\",\n]);\n\ninterface StagedCall {\n\tmember: string;\n\targs: unknown[];\n\tcancelled: boolean;\n\tunsubscribe?: () => void;\n}\n\n// Descriptions match the real Flow commands (packages/flow/src). flow-profile is served here through Flow's\n// runFlowProfileCommand.\nconst STUB_COMMANDS: Record<string, string> = {\n\tflow:\n\t\t\"Plan and dispatch a hierarchical agent run. \" +\n\t\t\"Args: <goal> [--task-class T] [--complexity N] [--risk low|medium|high|critical] \" +\n\t\t\"[--profile NAME] [--lead-size small|standard|large] [--cheap ALIAS] [--mid ALIAS] [--premium ALIAS] [--frontier ALIAS] [--model <capability>=ALIAS] [--effort LEVEL] \" +\n\t\t\"[--quality-floor F] [--cost-aggressiveness C] [--max-retries R] [--flow-admission FILE] \" +\n\t\t\"[--context FILE ...] [--with-last-reply] [--force]\\n\\n\" +\n\t\t\"With no triage flags, an LLM triage call (cheapest configured model) \" +\n\t\t\"auto-fills task_class, complexity, and risk from the goal text. \" +\n\t\t\"Models: flags > profile (orchestrator-profiles.json) > cost-tier resolver. See /flow-models.\",\n\t\"flow-continue\":\n\t\t\"Preview and explicitly confirm recovery in the original checkout. Args: [run-id] (no --yes or --force).\",\n\t\"flow-status\": \"Open the full live orchestration board (↑↓ PgUp/PgDn scroll, Esc closes without cancelling).\",\n\t\"flow-cancel\": \"Cancel the currently running /flow run, if any.\",\n\t\"flow-pause\": \"Pause the currently running /flow run, if any.\",\n\t\"flow-resume\": \"Resume a paused /flow run.\",\n\t\"flow-title\": \"Rename the active flow and display its title on the widget border.\",\n\t\"flow-models\":\n\t\t\"Manage which models /flow uses. Subcommands: show|list|validate [--live]|check|set|effort|use|new|pick|workflow. \" +\n\t\t\"Aliases like fable-5-1, opus-5-5, sonnet-5, gpt-6-sol, gpt-6-luna, astra resolve against your configured models.\",\n\t\"flow-profile\": \"List, show, select, import or edit Flow profiles. Args: [list|show|use|export|import|validate ...]\",\n\tomsg:\n\t\t\"Send a message to the running orchestration (queued, delivered to the next dispatched task). \" +\n\t\t\"Usage: /omsg <text> — the lead will see and respond to it. Use '\\\\n' for newlines if needed.\",\n};\n\n/**\n * Act on an already loaded run only; with Flow not loaded there is no run, so Flow is never imported for them. They\n * stay reachable when Flow is disabled so a live run can still be stopped. Every other stub is refused when disabled.\n */\nconst LOADED_RUN_COMMANDS = new Set([\"flow-cancel\", \"flow-status\", \"flow-pause\", \"flow-resume\"]);\n/** Kill switch: resume would restart dispatch, so it is refused while Flow is disabled (cancel, status and pause are not). */\nconst AVAILABLE_WHEN_DISABLED = new Set([\"flow-cancel\", \"flow-status\", \"flow-pause\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\n/**\n * Print/json mode has no UI: core makes ctx.ui.notify a no-op, so headless notices go to stderr as bare text.\n * Notice text can echo user args or env values, so it is redacted, stripped of terminal escapes, then redacted again\n * with the same redactor: the first pass catches secrets that stripping could otherwise mangle, the second catches\n * secrets that were split by escapes and are rejoined by stripping. Fails closed to a fixed line on any failure.\n * Replacing `ui` snapshots ui (descriptors preserve other ctx getters, so lazy getters on ctx stay live; same approach\n * as the runner's createCommandContext).\n */\nconst NOTICE_WITHHELD = \"[notice withheld: redaction unavailable]\";\n\nfunction safeNotice(message: string): string {\n\ttry {\n\t\tconst redactor = createTraceRedactor({ env: process.env });\n\t\treturn redactor.redactText(sanitizeForTerminal(redactor.redactText(message).text)).text;\n\t} catch {\n\t\treturn NOTICE_WITHHELD;\n\t}\n}\n\nfunction withHeadlessNotices(ctx: ExtensionCommandContext): ExtensionCommandContext {\n\tif (ctx.mode !== \"print\" && ctx.mode !== \"json\") return ctx;\n\tconst ui = Object.defineProperties({}, Object.getOwnPropertyDescriptors(ctx.ui)) as ExtensionCommandContext[\"ui\"];\n\tui.notify = (message: string) => {\n\t\tprocess.stderr.write(`${safeNotice(message)}\\n`);\n\t};\n\tconst wrapped = Object.defineProperties({}, Object.getOwnPropertyDescriptors(ctx)) as ExtensionCommandContext;\n\tObject.defineProperty(wrapped, \"ui\", { value: ui, enumerable: true, configurable: true });\n\treturn wrapped;\n}\n\n/**\n * Mirrors packages/flow emitRefusalSettled: an rpc /flow start that dispatches nothing still emits one terminal\n * `run_settled` frame so the host stops waiting. Built here because the entry graph must not reach @humain/flow.\n * Print/json refusals exit non-zero (mirrors flow's markHeadlessFailure). Never throws; no-op otherwise.\n */\nasync function settleRefusal(\n\tname: string,\n\tctx: ExtensionCommandContext,\n\tfailureClass: FlowFailureClass,\n): Promise<void> {\n\tif ((name === \"flow\" || name === \"flow-continue\") && (ctx.mode === \"print\" || ctx.mode === \"json\"))\n\t\tprocess.exitCode = 1;\n\tif (ctx.mode !== \"rpc\" || !rpcOutput || (name !== \"flow\" && name !== \"flow-continue\")) return;\n\ttry {\n\t\tconst runId = `flow-refused-${randomBytes(8).toString(\"hex\")}`;\n\t\tconst frame: FlowEventFrameV1 = {\n\t\t\ttype: \"flow_event\",\n\t\t\tevent: {\n\t\t\t\tschema: \"humain-flow-event\",\n\t\t\t\tschemaVersion: 1,\n\t\t\t\teventId: `${runId}.refused`,\n\t\t\t\trunId,\n\t\t\t\tseq: 1,\n\t\t\t\tts: new Date().toISOString(),\n\t\t\t\tprofile: {\n\t\t\t\t\tid: \"unknown\",\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tdigest: createHash(\"sha256\").update(\"unknown\", \"utf8\").digest(\"hex\"),\n\t\t\t\t},\n\t\t\t\tcauses: [],\n\t\t\t\tkind: \"run_settled\",\n\t\t\t\tpayload: { outcome: \"failed\", failureClass, settledCleanly: true, retryOffer: [\"direct\"], totals: {} },\n\t\t\t},\n\t\t};\n\t\tawait rpcOutput(frame);\n\t} catch {\n\t\t// Refusal must still notify; a dead transport is not the command's problem.\n\t}\n}\n\nfunction disabledReason(pi: ExtensionAPI, env: NodeJS.ProcessEnv): string | undefined {\n\tconst raw = env[HUMAIN_FLOW_DISABLED_ENV]?.trim().toLowerCase();\n\tif (raw === \"1\" || raw === \"true\") return `${HUMAIN_FLOW_DISABLED_ENV}=${raw}`;\n\ttry {\n\t\t// `flow` is not a typed Settings key: settings.json keeps unknown keys, so read it raw.\n\t\tconst flow = (pi.getSettings() as Record<string, unknown>).flow;\n\t\tif (isRecord(flow) && flow.enabled === false) return \"setting flow.enabled=false\";\n\t} catch {\n\t\t// Runtime not bound yet: treat as enabled.\n\t}\n\treturn undefined;\n}\n\n/**\n * Run flowExtension against a staging proxy. Stub commands are captured (so names never double-register); every other\n * registration is recorded and applied to the real pi only after the factory and the session_start replay succeed, so\n * a failed attempt leaves nothing behind and a retry starts from scratch. Late registration is supported by the\n * extension loader (handlers, tools, commands and flags are written to the live extension object), but\n * `session_start` has already fired by the time Flow loads, so the last session_start event is replayed to Flow's\n * staged session_start handlers.\n *\n * Commit is not transactional for non-handler members: if one throws midway, committed handlers are unsubscribed, and\n * tools/commands/flags/shortcuts/renderers (keyed maps in the extension loader) are simply overwritten on retry.\n */\nasync function runFlowExtension(\n\tpi: ExtensionAPI,\n\tflowExtension: ExtensionFactory,\n\tlastSessionStart: () => unknown[] | undefined,\n): Promise<Map<string, CommandOptions>> {\n\tconst captured = new Map<string, CommandOptions>();\n\tconst staged: StagedCall[] = [];\n\t// After a successful commit the proxy forwards live, so registrations made later (from handlers) reach the real pi.\n\tlet live = false;\n\tconst proxy = new Proxy(pi, {\n\t\tget(target, prop) {\n\t\t\tif (!live && typeof prop === \"string\" && STAGED_MEMBERS.has(prop)) {\n\t\t\t\treturn (...args: unknown[]) => {\n\t\t\t\t\tif (prop === \"registerCommand\" && typeof args[0] === \"string\" && args[0] in STUB_COMMANDS) {\n\t\t\t\t\t\tcaptured.set(args[0], args[1] as CommandOptions);\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\tconst call: StagedCall = { member: prop, args, cancelled: false };\n\t\t\t\t\tstaged.push(call);\n\t\t\t\t\tif (prop !== \"on\") return undefined;\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tcall.cancelled = true;\n\t\t\t\t\t\tcall.unsubscribe?.();\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst value: unknown = Reflect.get(target, prop, target);\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t});\n\tawait flowExtension(proxy);\n\n\tlet replayed: unknown[] | undefined;\n\tfor (let start = lastSessionStart(); start && start !== replayed; start = lastSessionStart()) {\n\t\treplayed = start;\n\t\tfor (const call of staged) {\n\t\t\tif (call.member === \"on\" && call.args[0] === \"session_start\" && !call.cancelled) {\n\t\t\t\tawait (call.args[1] as EventHandler)(...start);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Synchronous from the last replay check: no session_start can slip between replay and commit.\n\tconst committed: Array<() => void> = [];\n\ttry {\n\t\tfor (const call of staged) {\n\t\t\tif (call.cancelled) continue;\n\t\t\tconst result = (Reflect.get(pi, call.member) as (...args: unknown[]) => unknown).apply(pi, call.args);\n\t\t\tif (call.member === \"on\") {\n\t\t\t\tcall.unsubscribe = result as () => void;\n\t\t\t\tcommitted.push(call.unsubscribe);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tfor (const unsubscribe of committed) unsubscribe();\n\t\tthrow error;\n\t}\n\tlive = true;\n\treturn captured;\n}\n\nfunction isSameCliReleaseFlowDir(dir: string): boolean {\n\tif (!isAbsolute(dir) || VERSION === \"0.0.0\") return false;\n\ttry {\n\t\tconst manifest: unknown = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\"));\n\t\tif (!isRecord(manifest) || manifest.name !== \"@humain/flow\") return false;\n\t} catch {\n\t\treturn false;\n\t}\n\t// Bun ships flow/ beside package.json; bundled Node ships dist/bundle/flow/.\n\tfor (const root of [dirname(dir), resolve(dir, \"../../..\")]) {\n\t\ttry {\n\t\t\tconst manifest: unknown = JSON.parse(readFileSync(join(root, \"package.json\"), \"utf8\"));\n\t\t\tif (isRecord(manifest) && manifest.name === PACKAGE_NAME) return manifest.version === VERSION;\n\t\t} catch {\n\t\t\t// Missing or unreadable release metadata cannot validate an override.\n\t\t}\n\t}\n\treturn false;\n}\n\nexport function createHumainFlowLoaderExtensionFactory(options: HumainFlowLoaderOptions = {}): ExtensionFactory {\n\tconst env = options.env ?? process.env;\n\t// This is the single sanctioned lazy-load boundary for @humain/flow (see AGENTS.md \"No inline imports\" exception).\n\tconst importFlow = options.importFlow ?? (() => import(\"@humain/flow\"));\n\tconst flowPackageDir = options.flowPackageDir ?? getBundledFlowPackageDir();\n\tconst builtInProfilesDir = options.builtInProfilesDir ?? getBundledFlowProfilesDir();\n\tlet flowModule: Promise<FlowModule> | undefined;\n\n\treturn (pi) => {\n\t\tdisabledProbe = () => disabledReason(pi, env) !== undefined;\n\t\tlet lastStart: unknown[] | undefined;\n\t\tlet loaded: Promise<Map<string, CommandOptions>> | undefined;\n\n\t\tpi.on(\"session_start\", (event, ctx) => {\n\t\t\tlastStart = [event, ctx];\n\t\t});\n\t\tpi.registerFlag(\"profile\", { description: \"Flow profile id\", type: \"string\" });\n\t\tpi.registerFlag(\"flow-admission\", { description: \"Flow run admission file (JSON)\", type: \"string\" });\n\n\t\tconst loadModule = async (): Promise<FlowModule> => {\n\t\t\tconst override = env[HUMAIN_FLOW_PACKAGE_DIR_ENV];\n\t\t\tif (override && !isSameCliReleaseFlowDir(override)) delete env[HUMAIN_FLOW_PACKAGE_DIR_ENV];\n\t\t\tif (flowPackageDir && !env[HUMAIN_FLOW_PACKAGE_DIR_ENV]) env[HUMAIN_FLOW_PACKAGE_DIR_ENV] = flowPackageDir;\n\t\t\tflowModule ??= importFlow().then((module) => {\n\t\t\t\trpcControl = module.createFlowRpcControl?.({\n\t\t\t\t\twriteFrame: (frame) => rpcOutput?.(frame),\n\t\t\t\t\tisDisabled: isFlowDisabled,\n\t\t\t\t\tsendFollowUp: (text) =>\n\t\t\t\t\t\trpcFollowUp ? rpcFollowUp(text) : Promise.reject(new Error(\"host unavailable\")),\n\t\t\t\t});\n\t\t\t\treturn module;\n\t\t\t});\n\t\t\ttry {\n\t\t\t\treturn await flowModule;\n\t\t\t} catch (error) {\n\t\t\t\tflowModule = undefined;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\n\t\trpcLoader = async () => {\n\t\t\ttry {\n\t\t\t\tawait loadModule();\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn rpcControl;\n\t\t};\n\n\t\tconst load = (): Promise<Map<string, CommandOptions>> => {\n\t\t\tif (!loaded) {\n\t\t\t\tconst attempt = (async () => {\n\t\t\t\t\tconst module = await loadModule();\n\t\t\t\t\treturn runFlowExtension(pi, module.flowExtension, () => lastStart);\n\t\t\t\t})();\n\t\t\t\tloaded = attempt;\n\t\t\t\t// A failed load must be retryable on the next invocation.\n\t\t\t\tattempt.catch(() => {\n\t\t\t\t\tif (loaded === attempt) loaded = undefined;\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn loaded;\n\t\t};\n\n\t\tfor (const [name, description] of Object.entries(STUB_COMMANDS)) {\n\t\t\tpi.registerCommand(name, {\n\t\t\t\tdescription,\n\t\t\t\thandler: async (args: string, rawCtx: ExtensionCommandContext) => {\n\t\t\t\t\tconst ctx = withHeadlessNotices(rawCtx);\n\t\t\t\t\tconst reason = AVAILABLE_WHEN_DISABLED.has(name) ? undefined : disabledReason(pi, env);\n\t\t\t\t\tif (reason) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tctx.ui.notify(`Flow disabled (${reason}). /${name} is unavailable.`, \"warning\");\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait settleRefusal(name, ctx, \"config_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (name === \"flow-profile\") {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst module = await loadModule();\n\t\t\t\t\t\t\tif (!module.runFlowProfileCommand || !module.createProfileStore) {\n\t\t\t\t\t\t\t\tctx.ui.notify(\"/flow-profile is not available in this Flow build\", \"error\");\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst store = module.createProfileStore({\n\t\t\t\t\t\t\t\tflowDir: options.flowDir ?? join(getAgentDir(), \"flow\"),\n\t\t\t\t\t\t\t\t...(builtInProfilesDir !== undefined ? { builtInDir: builtInProfilesDir } : {}),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait module.runFlowProfileCommand(args, ctx, { store });\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\t\t`/flow-profile failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (LOADED_RUN_COMMANDS.has(name) && !loaded) {\n\t\t\t\t\t\tctx.ui.notify(\"no active run\", \"info\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet commands: Map<string, CommandOptions>;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcommands = await load();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\t\t`Failed to load Flow: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait settleRefusal(name, ctx, \"internal\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst real = commands.get(name);\n\t\t\t\t\tif (!real) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tctx.ui.notify(`/${name} is not available yet`, \"error\");\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait settleRefusal(name, ctx, \"internal\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tawait real.handler(args, ctx);\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"flow-loader.js","sourceRoot":"","sources":["../../src/humain/flow-loader.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,E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CAAC;oBACvD,CAAC;4BAAS,CAAC;wBACV,MAAM,aAAa,CAAC,OAAO,EAAE,GAAG,EAAE,UAAU,CAAC,CAAC;oBAC/C,CAAC;oBACD,OAAO;gBACR,CAAC;gBACD,wFAAwF;gBACxF,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YAC/B,CAAC;SACD,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC","sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport type { FlowFailureClass } from \"@humain/humain-code-contracts/flow-common\";\nimport type { FlowEventFrameV1, FlowReceiptV1, FlowStatusV1 } from \"@humain/humain-code-contracts/flow-control\";\nimport { getAgentDir, getBundledFlowPackageDir, getBundledFlowProfilesDir, PACKAGE_NAME, VERSION } from \"../config.ts\";\nimport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionFactory,\n\tRegisteredCommand,\n} from \"../core/extensions/types.ts\";\nimport { createTraceRedactor } from \"../core/trace/redaction.ts\";\nimport { sanitizeForTerminal } from \"../core/trace-client/sanitize.ts\";\nimport {\n\tcompleteFlowArguments,\n\tFLOW_SETUP_TERMINAL_ONLY,\n\ttype FlowSubcommand,\n\tflowBuildUnavailable,\n\tparseFlowCommand,\n\trenderFlowHelp,\n} from \"./flow-command.ts\";\n\n/**\n * Lazy loader for the private @humain/flow package.\n *\n * The CLI entry graph must not statically reach Flow: this module registers one cheap `/flow` stub and two flags, and\n * only loads Flow (one memoized dynamic import) the first time a subcommand needs it. Help, completion, unknown\n * commands and not-yet-available commands are answered statically and never import Flow. Flow is bundled as its own\n * chunk.\n */\n\nexport const HUMAIN_FLOW_DISABLED_ENV = \"HUMAIN_TERMINAL_FLOW_DISABLED\";\nexport const HUMAIN_FLOW_PACKAGE_DIR_ENV = \"HUMAIN_TERMINAL_FLOW_PACKAGE_DIR\";\n\n/** Run-control surface Flow exposes to rpc mode (flow_status/pause/resume/cancel/message). */\nexport interface FlowRpcControl {\n\thandle(input: unknown): Promise<{ receipt: FlowReceiptV1; status?: FlowStatusV1 }>;\n\tactiveRunId(): string | undefined;\n}\n\nexport interface FlowModule {\n\tflowExtension: ExtensionFactory;\n\t/** Documented rpc hook: called once when Flow loads; `writeFrame` carries `flow_event` frames to the rpc host. */\n\tcreateFlowRpcControl?(options: {\n\t\twriteFrame?: (frame: FlowEventFrameV1) => void | Promise<void>;\n\t\tisDisabled?: () => boolean;\n\t\t/** Queues text on the host session as a follow-up (flow_message with no active run). */\n\t\tsendFollowUp?: (text: string) => Promise<void>;\n\t}): FlowRpcControl;\n\t/** B1 profile command; optional so test fakes need not provide it. Methods stay bivariant for the real signatures. */\n\trunFlowProfileCommand?(args: string, ctx: ExtensionCommandContext, deps: { store: unknown }): Promise<unknown>;\n\tcreateProfileStore?(options: { flowDir: string; builtInDir?: string }): unknown;\n}\n\nexport interface HumainFlowLoaderOptions {\n\t/** Test seam. Defaults to the single sanctioned dynamic import of @humain/flow. */\n\timportFlow?: () => Promise<FlowModule>;\n\tenv?: NodeJS.ProcessEnv;\n\t/** Directory holding Flow's agents/assets/package.json. Defaults to the bundled layout's flow/ dir. */\n\tflowPackageDir?: string;\n\t/** Built-in Flow profiles dir. Defaults to the bundled layout's assets/profiles; undefined lets Flow find its own. */\n\tbuiltInProfilesDir?: string;\n\t/** Flow profile store directory. Defaults to `<agentDir>/flow`. */\n\tflowDir?: string;\n}\n\nlet rpcControl: FlowRpcControl | undefined;\nlet disabledProbe: (() => boolean) | undefined;\nlet rpcOutput: ((frame: FlowEventFrameV1) => void | Promise<void>) | undefined;\nlet rpcLoader: (() => Promise<FlowRpcControl | undefined>) | undefined;\nlet rpcFollowUp: ((text: string) => Promise<void>) | undefined;\n\n/** The documented rpc hook: rpc mode reads Flow's run control here and never imports Flow itself. */\nexport function getFlowRpcControl(): FlowRpcControl | undefined {\n\treturn rpcControl;\n}\n\n/**\n * The documented rpc hook: loads Flow through the same lazy-load path the stub commands use and returns its run control.\n * Undefined when Flow is disabled (never loaded then), not wired, or fails to load.\n */\nexport async function loadFlowRpcControl(): Promise<FlowRpcControl | undefined> {\n\tif (rpcControl) return rpcControl;\n\tif (isFlowDisabled()) return undefined;\n\treturn rpcLoader?.();\n}\n\n/** True while Flow is switched off (flow.enabled=false or the env kill switch); rpc mode refuses flow_resume then. */\nexport function isFlowDisabled(): boolean {\n\treturn disabledProbe?.() ?? false;\n}\n\n/** The documented rpc hook: rpc mode registers where Flow's `flow_event` frames are written. */\nexport function setFlowRpcOutput(writer: ((frame: FlowEventFrameV1) => void | Promise<void>) | undefined): void {\n\trpcOutput = writer;\n}\n\n/** The documented rpc hook: rpc mode registers how direct-mode flow_message text is queued as a host follow-up. */\nexport function setFlowRpcFollowUp(queue: ((text: string) => Promise<void>) | undefined): void {\n\trpcFollowUp = queue;\n}\n\ntype CommandOptions = Omit<RegisteredCommand, \"name\" | \"sourceInfo\">;\ntype EventHandler = (...args: unknown[]) => unknown;\n\n/**\n * ExtensionAPI members that only record registrations (see core/extensions/loader.ts). They are staged while Flow's\n * factory runs and applied to the real pi only after the factory and the session_start replay succeed. Reads and\n * actions (getFlag, getSettings, exec, sendMessage, ...) and `events` stay live: they have no registration to undo\n * or are needed by the factory itself. Flow uses none of the live ones that subscribe (`events.on`).\n */\nconst STAGED_MEMBERS = new Set([\n\t\"on\",\n\t\"registerTool\",\n\t\"registerCommand\",\n\t\"registerShortcut\",\n\t\"registerFlag\",\n\t\"registerMessageRenderer\",\n\t\"registerMarkdownTransformer\",\n\t\"registerEntryRenderer\",\n\t\"registerProvider\",\n\t\"unregisterProvider\",\n\t\"registerMcpServer\",\n\t\"unregisterMcpServer\",\n\t\"registerVirtualModel\",\n\t\"unregisterVirtualModel\",\n]);\n\ninterface StagedCall {\n\tmember: string;\n\targs: unknown[];\n\tcancelled: boolean;\n\tunsubscribe?: () => void;\n}\n\nconst FLOW_DESCRIPTION =\n\t\"Plan, run, and verify work with agents. Subcommands: run, continue, list, status, cancel, pause, resume, \" +\n\t\"title, message, hide, show, models, profile, setup. Use /flow help for usage.\";\n\n/**\n * Act on an already loaded run only; with Flow not loaded there is no run, so Flow is never imported for them. They\n * stay reachable when Flow is disabled so a live run can still be stopped. Every other subcommand is refused when\n * disabled.\n */\nconst LOADED_RUN_COMMANDS: ReadonlySet<FlowSubcommand> = new Set([\n\t\"cancel\",\n\t\"status\",\n\t\"pause\",\n\t\"resume\",\n\t\"hide\",\n\t\"show\",\n]);\n/** Kill switch: resume would restart dispatch, so it is refused while Flow is disabled (the others are not). */\nconst AVAILABLE_WHEN_DISABLED: ReadonlySet<FlowSubcommand> = new Set([\"cancel\", \"status\", \"pause\", \"hide\", \"show\"]);\n/** Copy when a loaded-run command finds no Flow loaded, so there is nothing to act on. */\nconst NO_LOADED_RUN_COPY: Partial<Record<FlowSubcommand, string>> = {\n\tcancel: \"No active Flow run to stop.\",\n\tstatus: \"No active Flow run. Start one with /flow run <goal>.\",\n\tpause: \"No active Flow run to pause.\",\n\tresume: \"No paused Flow run to resume.\",\n\thide: \"No current Flow widget to hide.\",\n\tshow: \"No current Flow widget to show.\",\n};\n/** Only these start (or recover) work, so only their refusals settle an rpc run. */\nconst START_COMMANDS: ReadonlySet<FlowSubcommand> = new Set([\"run\", \"continue\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\n/**\n * Print/json mode has no UI: core makes ctx.ui.notify a no-op, so headless notices go to stderr as bare text.\n * Notice text can echo user args or env values, so it is redacted, stripped of terminal escapes, then redacted again\n * with the same redactor: the first pass catches secrets that stripping could otherwise mangle, the second catches\n * secrets that were split by escapes and are rejoined by stripping. Fails closed to a fixed line on any failure.\n * Replacing `ui` snapshots ui (descriptors preserve other ctx getters, so lazy getters on ctx stay live; same approach\n * as the runner's createCommandContext).\n */\nconst NOTICE_WITHHELD = \"[notice withheld: redaction unavailable]\";\n\nfunction safeNotice(message: string): string {\n\ttry {\n\t\tconst redactor = createTraceRedactor({ env: process.env });\n\t\treturn redactor.redactText(sanitizeForTerminal(redactor.redactText(message).text)).text;\n\t} catch {\n\t\treturn NOTICE_WITHHELD;\n\t}\n}\n\nfunction withHeadlessNotices(ctx: ExtensionCommandContext): ExtensionCommandContext {\n\tif (ctx.mode !== \"print\" && ctx.mode !== \"json\") return ctx;\n\tconst ui = Object.defineProperties({}, Object.getOwnPropertyDescriptors(ctx.ui)) as ExtensionCommandContext[\"ui\"];\n\tui.notify = (message: string) => {\n\t\tprocess.stderr.write(`${safeNotice(message)}\\n`);\n\t};\n\tconst wrapped = Object.defineProperties({}, Object.getOwnPropertyDescriptors(ctx)) as ExtensionCommandContext;\n\tObject.defineProperty(wrapped, \"ui\", { value: ui, enumerable: true, configurable: true });\n\treturn wrapped;\n}\n\n/**\n * Mirrors packages/flow emitRefusalSettled: an rpc `/flow run` or `/flow continue` that dispatches nothing still emits one terminal\n * `run_settled` frame so the host stops waiting. Built here because the entry graph must not reach @humain/flow.\n * Print/json refusals exit non-zero (mirrors flow's markHeadlessFailure). Never throws; no-op otherwise.\n */\nasync function settleRefusal(\n\tcommand: FlowSubcommand,\n\tctx: ExtensionCommandContext,\n\tfailureClass: FlowFailureClass,\n): Promise<void> {\n\tif (!START_COMMANDS.has(command)) return;\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") process.exitCode = 1;\n\tif (ctx.mode !== \"rpc\" || !rpcOutput) return;\n\ttry {\n\t\tconst runId = `flow-refused-${randomBytes(8).toString(\"hex\")}`;\n\t\tconst frame: FlowEventFrameV1 = {\n\t\t\ttype: \"flow_event\",\n\t\t\tevent: {\n\t\t\t\tschema: \"humain-flow-event\",\n\t\t\t\tschemaVersion: 1,\n\t\t\t\teventId: `${runId}.refused`,\n\t\t\t\trunId,\n\t\t\t\tseq: 1,\n\t\t\t\tts: new Date().toISOString(),\n\t\t\t\tprofile: {\n\t\t\t\t\tid: \"unknown\",\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tdigest: createHash(\"sha256\").update(\"unknown\", \"utf8\").digest(\"hex\"),\n\t\t\t\t},\n\t\t\t\tcauses: [],\n\t\t\t\tkind: \"run_settled\",\n\t\t\t\tpayload: { outcome: \"failed\", failureClass, settledCleanly: true, retryOffer: [\"direct\"], totals: {} },\n\t\t\t},\n\t\t};\n\t\tawait rpcOutput(frame);\n\t} catch {\n\t\t// Refusal must still notify; a dead transport is not the command's problem.\n\t}\n}\n\nfunction disabledReason(pi: ExtensionAPI, env: NodeJS.ProcessEnv): string | undefined {\n\tconst raw = env[HUMAIN_FLOW_DISABLED_ENV]?.trim().toLowerCase();\n\tif (raw === \"1\" || raw === \"true\") return `${HUMAIN_FLOW_DISABLED_ENV}=${raw}`;\n\ttry {\n\t\t// `flow` is not a typed Settings key: settings.json keeps unknown keys, so read it raw.\n\t\tconst flow = (pi.getSettings() as Record<string, unknown>).flow;\n\t\tif (isRecord(flow) && flow.enabled === false) return \"setting flow.enabled=false\";\n\t} catch {\n\t\t// Runtime not bound yet: treat as enabled.\n\t}\n\treturn undefined;\n}\n\n/**\n * Run flowExtension against a staging proxy. The `/flow` command is captured (so names never double-register); every other\n * registration is recorded and applied to the real pi only after the factory and the session_start replay succeed, so\n * a failed attempt leaves nothing behind and a retry starts from scratch. Late registration is supported by the\n * extension loader (handlers, tools, commands and flags are written to the live extension object), but\n * `session_start` has already fired by the time Flow loads, so the last session_start event is replayed to Flow's\n * staged session_start handlers.\n *\n * Commit is not transactional for non-handler members: if one throws midway, committed handlers are unsubscribed, and\n * tools/commands/flags/shortcuts/renderers (keyed maps in the extension loader) are simply overwritten on retry.\n */\nasync function runFlowExtension(\n\tpi: ExtensionAPI,\n\tflowExtension: ExtensionFactory,\n\tlastSessionStart: () => unknown[] | undefined,\n): Promise<Map<string, CommandOptions>> {\n\tconst captured = new Map<string, CommandOptions>();\n\tconst staged: StagedCall[] = [];\n\t// After a successful commit the proxy forwards live, so registrations made later (from handlers) reach the real pi.\n\tlet live = false;\n\tconst proxy = new Proxy(pi, {\n\t\tget(target, prop) {\n\t\t\tif (!live && typeof prop === \"string\" && STAGED_MEMBERS.has(prop)) {\n\t\t\t\treturn (...args: unknown[]) => {\n\t\t\t\t\tif (prop === \"registerCommand\" && args[0] === \"flow\") {\n\t\t\t\t\t\tcaptured.set(args[0], args[1] as CommandOptions);\n\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t}\n\t\t\t\t\tconst call: StagedCall = { member: prop, args, cancelled: false };\n\t\t\t\t\tstaged.push(call);\n\t\t\t\t\tif (prop !== \"on\") return undefined;\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tcall.cancelled = true;\n\t\t\t\t\t\tcall.unsubscribe?.();\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst value: unknown = Reflect.get(target, prop, target);\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t});\n\tawait flowExtension(proxy);\n\n\tlet replayed: unknown[] | undefined;\n\tfor (let start = lastSessionStart(); start && start !== replayed; start = lastSessionStart()) {\n\t\treplayed = start;\n\t\tfor (const call of staged) {\n\t\t\tif (call.member === \"on\" && call.args[0] === \"session_start\" && !call.cancelled) {\n\t\t\t\tawait (call.args[1] as EventHandler)(...start);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Synchronous from the last replay check: no session_start can slip between replay and commit.\n\tconst committed: Array<() => void> = [];\n\ttry {\n\t\tfor (const call of staged) {\n\t\t\tif (call.cancelled) continue;\n\t\t\tconst result = (Reflect.get(pi, call.member) as (...args: unknown[]) => unknown).apply(pi, call.args);\n\t\t\tif (call.member === \"on\") {\n\t\t\t\tcall.unsubscribe = result as () => void;\n\t\t\t\tcommitted.push(call.unsubscribe);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tfor (const unsubscribe of committed) unsubscribe();\n\t\tthrow error;\n\t}\n\tlive = true;\n\treturn captured;\n}\n\nfunction isSameCliReleaseFlowDir(dir: string): boolean {\n\tif (!isAbsolute(dir) || VERSION === \"0.0.0\") return false;\n\ttry {\n\t\tconst manifest: unknown = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\"));\n\t\tif (!isRecord(manifest) || manifest.name !== \"@humain/flow\") return false;\n\t} catch {\n\t\treturn false;\n\t}\n\t// Bun ships flow/ beside package.json; bundled Node ships dist/bundle/flow/.\n\tfor (const root of [dirname(dir), resolve(dir, \"../../..\")]) {\n\t\ttry {\n\t\t\tconst manifest: unknown = JSON.parse(readFileSync(join(root, \"package.json\"), \"utf8\"));\n\t\t\tif (isRecord(manifest) && manifest.name === PACKAGE_NAME) return manifest.version === VERSION;\n\t\t} catch {\n\t\t\t// Missing or unreadable release metadata cannot validate an override.\n\t\t}\n\t}\n\treturn false;\n}\n\nexport function createHumainFlowLoaderExtensionFactory(options: HumainFlowLoaderOptions = {}): ExtensionFactory {\n\tconst env = options.env ?? process.env;\n\t// This is the single sanctioned lazy-load boundary for @humain/flow (see AGENTS.md \"No inline imports\" exception).\n\tconst importFlow = options.importFlow ?? (() => import(\"@humain/flow\"));\n\tconst flowPackageDir = options.flowPackageDir ?? getBundledFlowPackageDir();\n\tconst builtInProfilesDir = options.builtInProfilesDir ?? getBundledFlowProfilesDir();\n\tlet flowModule: Promise<FlowModule> | undefined;\n\n\treturn (pi) => {\n\t\tdisabledProbe = () => disabledReason(pi, env) !== undefined;\n\t\tlet lastStart: unknown[] | undefined;\n\t\tlet loaded: Promise<Map<string, CommandOptions>> | undefined;\n\n\t\tpi.on(\"session_start\", (event, ctx) => {\n\t\t\tlastStart = [event, ctx];\n\t\t});\n\t\tpi.registerFlag(\"profile\", { description: \"Flow profile id\", type: \"string\" });\n\t\tpi.registerFlag(\"flow-admission\", { description: \"Flow run admission file (JSON)\", type: \"string\" });\n\n\t\tconst loadModule = async (): Promise<FlowModule> => {\n\t\t\tconst override = env[HUMAIN_FLOW_PACKAGE_DIR_ENV];\n\t\t\tif (override && !isSameCliReleaseFlowDir(override)) delete env[HUMAIN_FLOW_PACKAGE_DIR_ENV];\n\t\t\tif (flowPackageDir && !env[HUMAIN_FLOW_PACKAGE_DIR_ENV]) env[HUMAIN_FLOW_PACKAGE_DIR_ENV] = flowPackageDir;\n\t\t\tflowModule ??= importFlow().then((module) => {\n\t\t\t\trpcControl = module.createFlowRpcControl?.({\n\t\t\t\t\twriteFrame: (frame) => rpcOutput?.(frame),\n\t\t\t\t\tisDisabled: isFlowDisabled,\n\t\t\t\t\tsendFollowUp: (text) =>\n\t\t\t\t\t\trpcFollowUp ? rpcFollowUp(text) : Promise.reject(new Error(\"host unavailable\")),\n\t\t\t\t});\n\t\t\t\treturn module;\n\t\t\t});\n\t\t\ttry {\n\t\t\t\treturn await flowModule;\n\t\t\t} catch (error) {\n\t\t\t\tflowModule = undefined;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\n\t\trpcLoader = async () => {\n\t\t\ttry {\n\t\t\t\tawait loadModule();\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn rpcControl;\n\t\t};\n\n\t\tconst load = (): Promise<Map<string, CommandOptions>> => {\n\t\t\tif (!loaded) {\n\t\t\t\tconst attempt = (async () => {\n\t\t\t\t\tconst module = await loadModule();\n\t\t\t\t\treturn runFlowExtension(pi, module.flowExtension, () => lastStart);\n\t\t\t\t})();\n\t\t\t\tloaded = attempt;\n\t\t\t\t// A failed load must be retryable on the next invocation.\n\t\t\t\tattempt.catch(() => {\n\t\t\t\t\tif (loaded === attempt) loaded = undefined;\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn loaded;\n\t\t};\n\n\t\tpi.registerCommand(\"flow\", {\n\t\t\tdescription: FLOW_DESCRIPTION,\n\t\t\tgetArgumentCompletions: completeFlowArguments,\n\t\t\thandler: async (args: string, rawCtx: ExtensionCommandContext) => {\n\t\t\t\tconst ctx = withHeadlessNotices(rawCtx);\n\t\t\t\tconst refuse = (message: string, level: \"warning\" | \"error\") => {\n\t\t\t\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") process.exitCode = 1;\n\t\t\t\t\tctx.ui.notify(message, level);\n\t\t\t\t};\n\t\t\t\tconst parsed = parseFlowCommand(args);\n\t\t\t\tif (\"error\" in parsed) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\trefuse(parsed.error, \"error\");\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (parsed.command) await settleRefusal(parsed.command, ctx, \"config_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst { command, payload } = parsed;\n\t\t\t\tif (command === \"help\") {\n\t\t\t\t\tctx.ui.notify(renderFlowHelp(payload.trim() || undefined), \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Secure account dialogs exist only in the terminal UI: refuse elsewhere before loading Flow.\n\t\t\t\tif (command === \"setup\" && ctx.mode !== \"tui\") {\n\t\t\t\t\trefuse(FLOW_SETUP_TERMINAL_ONLY, \"error\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst reason = AVAILABLE_WHEN_DISABLED.has(command) ? undefined : disabledReason(pi, env);\n\t\t\t\tif (reason) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tctx.ui.notify(`Flow disabled (${reason}). /flow ${command} is unavailable.`, \"warning\");\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait settleRefusal(command, ctx, \"config_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (command === \"profile\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst module = await loadModule();\n\t\t\t\t\t\tif (!module.runFlowProfileCommand || !module.createProfileStore) {\n\t\t\t\t\t\t\tctx.ui.notify(flowBuildUnavailable(command), \"error\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst store = module.createProfileStore({\n\t\t\t\t\t\t\tflowDir: options.flowDir ?? join(getAgentDir(), \"flow\"),\n\t\t\t\t\t\t\t...(builtInProfilesDir !== undefined ? { builtInDir: builtInProfilesDir } : {}),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait module.runFlowProfileCommand(payload, ctx, { store });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\t`/flow profile failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (LOADED_RUN_COMMANDS.has(command) && !loaded) {\n\t\t\t\t\tctx.ui.notify(NO_LOADED_RUN_COPY[command] ?? \"No active Flow run.\", \"info\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet commands: Map<string, CommandOptions>;\n\t\t\t\ttry {\n\t\t\t\t\tcommands = await load();\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t\t`Failed to load Flow: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t\t\"error\",\n\t\t\t\t\t\t);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait settleRefusal(command, ctx, \"internal\");\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst real = commands.get(\"flow\");\n\t\t\t\tif (!real) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tctx.ui.notify(flowBuildUnavailable(command), \"error\");\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait settleRefusal(command, ctx, \"internal\");\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Flow's own dispatcher re-parses the original arguments and slices the payload itself.\n\t\t\t\tawait real.handler(args, ctx);\n\t\t\t},\n\t\t});\n\t};\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HUMAIN Node failures that justify trying another stored Node key. Everything else (request errors,
|
|
3
|
+
* unavailable models, outages, unparsable bodies) is left to the normal error handling.
|
|
4
|
+
* `revoked-key` is kept for the task interface only: the Node contract has a single 401 class, reported as `invalid-key`.
|
|
5
|
+
*/
|
|
6
|
+
export type NodeAccountFailureReason = "invalid-key" | "revoked-key" | "rate-limit" | "weekly-cap" | "quota";
|
|
7
|
+
export interface NodeAccountFailure {
|
|
8
|
+
reason: NodeAccountFailureReason;
|
|
9
|
+
/** Server-reported delay before the key may be used again. */
|
|
10
|
+
retryAfterMs?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare function classifyNodeAccountFailure(status: number, body: unknown, headers: Headers): NodeAccountFailure | undefined;
|
|
13
|
+
/** Read the classification `withHumainNodeHttp` attached to a failed assistant message, validating its shape. */
|
|
14
|
+
export declare function getNodeAccountFailure(diagnostics: readonly {
|
|
15
|
+
type: string;
|
|
16
|
+
details?: unknown;
|
|
17
|
+
}[] | undefined): NodeAccountFailure | undefined;
|
|
18
|
+
//# sourceMappingURL=node-account-failure.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-account-failure.d.ts","sourceRoot":"","sources":["../../src/humain/node-account-failure.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,wBAAwB,GAAG,aAAa,GAAG,aAAa,GAAG,YAAY,GAAG,YAAY,GAAG,OAAO,CAAC;AAE7G,MAAM,WAAW,kBAAkB;IAClC,MAAM,EAAE,wBAAwB,CAAC;IACjC,8DAA8D;IAC9D,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AA4CD,wBAAgB,0BAA0B,CACzC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,OAAO,GACd,kBAAkB,GAAG,SAAS,CAShC;AAED,iHAAiH;AACjH,wBAAgB,qBAAqB,CACpC,WAAW,EAAE,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,EAAE,GAAG,SAAS,GACrE,kBAAkB,GAAG,SAAS,CAWhC"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
const REASONS = new Set([
|
|
2
|
+
"invalid-key",
|
|
3
|
+
"revoked-key",
|
|
4
|
+
"rate-limit",
|
|
5
|
+
"weekly-cap",
|
|
6
|
+
"quota",
|
|
7
|
+
]);
|
|
8
|
+
const AUTH_STATUS = 401;
|
|
9
|
+
const LIMIT_STATUS = 429;
|
|
10
|
+
// ponytail: HUMAIN Node error contract: 401 missing_api_key|invalid_api_key means the key is absent, revoked, inactive or incorrect (one
|
|
11
|
+
// class, so "revoked-key" is never produced); 429 carries the four limit codes below. Nothing else rotates. Re-check if Node adds codes.
|
|
12
|
+
const INVALID_KEY_CODES = new Set(["invalid_api_key", "missing_api_key"]);
|
|
13
|
+
const LIMIT_CODES = new Map([
|
|
14
|
+
["rate_limit_exceeded", "rate-limit"],
|
|
15
|
+
["weekly_cap_exceeded", "weekly-cap"],
|
|
16
|
+
["quota_exceeded", "quota"],
|
|
17
|
+
["partner_credit_limit_exceeded", "quota"],
|
|
18
|
+
]);
|
|
19
|
+
/** 366 days: no plausible limit window is longer, so a longer Retry-After is treated as unusable. */
|
|
20
|
+
const MAX_RETRY_AFTER_MS = 366 * 24 * 60 * 60 * 1000;
|
|
21
|
+
/**
|
|
22
|
+
* OpenAI-compatible endpoints put the Node code in `error.code`; `/messages` uses the Anthropic envelope
|
|
23
|
+
* `{type:"error", error:{type, message}}`, so the code is read from `error.type` when `error.code` is absent.
|
|
24
|
+
* A generic Anthropic type (`authentication_error`, `rate_limit_error`) without a Node code is not in any code set, so it never rotates keys (fail-safe).
|
|
25
|
+
*/
|
|
26
|
+
function errorCode(body) {
|
|
27
|
+
if (typeof body !== "object" || body === null || !("error" in body))
|
|
28
|
+
return undefined;
|
|
29
|
+
const error = body.error;
|
|
30
|
+
if (typeof error !== "object" || error === null)
|
|
31
|
+
return undefined;
|
|
32
|
+
if ("code" in error && typeof error.code === "string")
|
|
33
|
+
return error.code;
|
|
34
|
+
return "type" in error && typeof error.type === "string" ? error.type : undefined;
|
|
35
|
+
}
|
|
36
|
+
function retryAfterMs(headers, nowMs) {
|
|
37
|
+
const value = headers.get("retry-after")?.trim();
|
|
38
|
+
if (!value)
|
|
39
|
+
return undefined;
|
|
40
|
+
const delay = /^\d+(?:\.\d+)?$/u.test(value) ? Number(value) * 1000 : Date.parse(value) - nowMs;
|
|
41
|
+
return Number.isFinite(delay) && delay > 0 && delay <= MAX_RETRY_AFTER_MS ? Math.round(delay) : undefined;
|
|
42
|
+
}
|
|
43
|
+
export function classifyNodeAccountFailure(status, body, headers) {
|
|
44
|
+
const code = errorCode(body);
|
|
45
|
+
if (code === undefined)
|
|
46
|
+
return undefined;
|
|
47
|
+
let reason;
|
|
48
|
+
if (status === AUTH_STATUS && INVALID_KEY_CODES.has(code))
|
|
49
|
+
reason = "invalid-key";
|
|
50
|
+
else if (status === LIMIT_STATUS)
|
|
51
|
+
reason = LIMIT_CODES.get(code);
|
|
52
|
+
if (reason === undefined)
|
|
53
|
+
return undefined;
|
|
54
|
+
const delay = retryAfterMs(headers, Date.now());
|
|
55
|
+
return delay === undefined ? { reason } : { reason, retryAfterMs: delay };
|
|
56
|
+
}
|
|
57
|
+
/** Read the classification `withHumainNodeHttp` attached to a failed assistant message, validating its shape. */
|
|
58
|
+
export function getNodeAccountFailure(diagnostics) {
|
|
59
|
+
const details = diagnostics?.findLast((entry) => entry.type === "provider_http_error")?.details;
|
|
60
|
+
if (typeof details !== "object" || details === null || !("nodeAccountFailure" in details))
|
|
61
|
+
return undefined;
|
|
62
|
+
const value = details.nodeAccountFailure;
|
|
63
|
+
if (typeof value !== "object" || value === null || !("reason" in value))
|
|
64
|
+
return undefined;
|
|
65
|
+
if (typeof value.reason !== "string" || !REASONS.has(value.reason))
|
|
66
|
+
return undefined;
|
|
67
|
+
const reason = value.reason;
|
|
68
|
+
const delay = "retryAfterMs" in value ? value.retryAfterMs : undefined;
|
|
69
|
+
return typeof delay === "number" && Number.isFinite(delay) && delay > 0 && delay <= MAX_RETRY_AFTER_MS
|
|
70
|
+
? { reason, retryAfterMs: delay }
|
|
71
|
+
: { reason };
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=node-account-failure.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-account-failure.js","sourceRoot":"","sources":["../../src/humain/node-account-failure.ts"],"names":[],"mappings":"AAaA,MAAM,OAAO,GAAwB,IAAI,GAAG,CAA2B;IACtE,aAAa;IACb,aAAa;IACb,YAAY;IACZ,YAAY;IACZ,OAAO;CACP,CAAC,CAAC;AAEH,MAAM,WAAW,GAAG,GAAG,CAAC;AACxB,MAAM,YAAY,GAAG,GAAG,CAAC;AACzB,yIAAyI;AACzI,yIAAyI;AACzI,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC,CAAC,iBAAiB,EAAE,iBAAiB,CAAC,CAAC,CAAC;AAC/F,MAAM,WAAW,GAAkD,IAAI,GAAG,CAAC;IAC1E,CAAC,qBAAqB,EAAE,YAAY,CAAC;IACrC,CAAC,qBAAqB,EAAE,YAAY,CAAC;IACrC,CAAC,gBAAgB,EAAE,OAAO,CAAC;IAC3B,CAAC,+BAA+B,EAAE,OAAO,CAAC;CAC1C,CAAC,CAAC;AACH,qGAAqG;AACrG,MAAM,kBAAkB,GAAG,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAErD;;;;GAIG;AACH,SAAS,SAAS,CAAC,IAAa;IAC/B,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,OAAO,IAAI,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IACtF,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;IACzB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;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Y,EAAE,KAAK,EAAE;QACjC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC;AACf,CAAC","sourcesContent":["/**\n * HUMAIN Node failures that justify trying another stored Node key. Everything else (request errors,\n * unavailable models, outages, unparsable bodies) is left to the normal error handling.\n * `revoked-key` is kept for the task interface only: the Node contract has a single 401 class, reported as `invalid-key`.\n */\nexport type NodeAccountFailureReason = \"invalid-key\" | \"revoked-key\" | \"rate-limit\" | \"weekly-cap\" | \"quota\";\n\nexport interface NodeAccountFailure {\n\treason: NodeAccountFailureReason;\n\t/** Server-reported delay before the key may be used again. */\n\tretryAfterMs?: number;\n}\n\nconst REASONS: ReadonlySet<string> = new Set<NodeAccountFailureReason>([\n\t\"invalid-key\",\n\t\"revoked-key\",\n\t\"rate-limit\",\n\t\"weekly-cap\",\n\t\"quota\",\n]);\n\nconst AUTH_STATUS = 401;\nconst LIMIT_STATUS = 429;\n// ponytail: HUMAIN Node error contract: 401 missing_api_key|invalid_api_key means the key is absent, revoked, inactive or incorrect (one\n// class, so \"revoked-key\" is never produced); 429 carries the four limit codes below. Nothing else rotates. Re-check if Node adds codes.\nconst INVALID_KEY_CODES: ReadonlySet<string> = new Set([\"invalid_api_key\", \"missing_api_key\"]);\nconst LIMIT_CODES: ReadonlyMap<string, NodeAccountFailureReason> = new Map([\n\t[\"rate_limit_exceeded\", \"rate-limit\"],\n\t[\"weekly_cap_exceeded\", \"weekly-cap\"],\n\t[\"quota_exceeded\", \"quota\"],\n\t[\"partner_credit_limit_exceeded\", \"quota\"],\n]);\n/** 366 days: no plausible limit window is longer, so a longer Retry-After is treated as unusable. */\nconst MAX_RETRY_AFTER_MS = 366 * 24 * 60 * 60 * 1000;\n\n/**\n * OpenAI-compatible endpoints put the Node code in `error.code`; `/messages` uses the Anthropic envelope\n * `{type:\"error\", error:{type, message}}`, so the code is read from `error.type` when `error.code` is absent.\n * A generic Anthropic type (`authentication_error`, `rate_limit_error`) without a Node code is not in any code set, so it never rotates keys (fail-safe).\n */\nfunction errorCode(body: unknown): string | undefined {\n\tif (typeof body !== \"object\" || body === null || !(\"error\" in body)) return undefined;\n\tconst error = body.error;\n\tif (typeof error !== \"object\" || error === null) return undefined;\n\tif (\"code\" in error && typeof error.code === \"string\") return error.code;\n\treturn \"type\" in error && typeof error.type === \"string\" ? error.type : undefined;\n}\n\nfunction retryAfterMs(headers: Headers, nowMs: number): number | undefined {\n\tconst value = headers.get(\"retry-after\")?.trim();\n\tif (!value) return undefined;\n\tconst delay = /^\\d+(?:\\.\\d+)?$/u.test(value) ? Number(value) * 1000 : Date.parse(value) - nowMs;\n\treturn Number.isFinite(delay) && delay > 0 && delay <= MAX_RETRY_AFTER_MS ? Math.round(delay) : undefined;\n}\n\nexport function classifyNodeAccountFailure(\n\tstatus: number,\n\tbody: unknown,\n\theaders: Headers,\n): NodeAccountFailure | undefined {\n\tconst code = errorCode(body);\n\tif (code === undefined) return undefined;\n\tlet reason: NodeAccountFailureReason | undefined;\n\tif (status === AUTH_STATUS && INVALID_KEY_CODES.has(code)) reason = \"invalid-key\";\n\telse if (status === LIMIT_STATUS) reason = LIMIT_CODES.get(code);\n\tif (reason === undefined) return undefined;\n\tconst delay = retryAfterMs(headers, Date.now());\n\treturn delay === undefined ? { reason } : { reason, retryAfterMs: delay };\n}\n\n/** Read the classification `withHumainNodeHttp` attached to a failed assistant message, validating its shape. */\nexport function getNodeAccountFailure(\n\tdiagnostics: readonly { type: string; details?: unknown }[] | undefined,\n): NodeAccountFailure | undefined {\n\tconst details = diagnostics?.findLast((entry) => entry.type === \"provider_http_error\")?.details;\n\tif (typeof details !== \"object\" || details === null || !(\"nodeAccountFailure\" in details)) return undefined;\n\tconst value = details.nodeAccountFailure;\n\tif (typeof value !== \"object\" || value === null || !(\"reason\" in value)) return undefined;\n\tif (typeof value.reason !== \"string\" || !REASONS.has(value.reason)) return undefined;\n\tconst reason = value.reason as NodeAccountFailureReason;\n\tconst delay = \"retryAfterMs\" in value ? value.retryAfterMs : undefined;\n\treturn typeof delay === \"number\" && Number.isFinite(delay) && delay > 0 && delay <= MAX_RETRY_AFTER_MS\n\t\t? { reason, retryAfterMs: delay }\n\t\t: { reason };\n}\n"]}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { type AuthStorageBackend } from "../core/auth-storage.ts";
|
|
2
|
+
import { type PoolAccount } from "../core/oauth-account-pool.ts";
|
|
3
|
+
import type { NodeAccountFailure, NodeAccountFailureReason } from "./node-account-failure.ts";
|
|
4
|
+
/**
|
|
5
|
+
* Opt-in ordered HUMAIN Node key fallback. Policy and labels live in their own file, never in the credential
|
|
6
|
+
* payload: keys stay in the existing credential pool and are referenced here by opaque account key only.
|
|
7
|
+
*/
|
|
8
|
+
export interface NodeAccountFallbackPolicy {
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
/** Pool account keys to try, in order, after the serving key fails. */
|
|
11
|
+
accountKeys: string[];
|
|
12
|
+
/** Explicit opt-in to switch between different Node endpoints. Off means same endpoint only. */
|
|
13
|
+
allowCrossEndpoint?: boolean;
|
|
14
|
+
}
|
|
15
|
+
/** User-provided labels. Aliases are the pool account labels, so they are not duplicated here. */
|
|
16
|
+
export interface NodeAccountLabels {
|
|
17
|
+
/** Which HUMAIN Node user owns the key. Keys of one user share limits. */
|
|
18
|
+
nodeUser?: string;
|
|
19
|
+
/** Environment of the endpoint, for example Production or Staging. */
|
|
20
|
+
environment?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface NodeAccountMetadata {
|
|
23
|
+
policy: Required<NodeAccountFallbackPolicy>;
|
|
24
|
+
accounts: Record<string, NodeAccountLabels>;
|
|
25
|
+
}
|
|
26
|
+
export declare const NODE_FALLBACK_NONE_MESSAGE = "No usable HUMAIN Node fallback key is configured.";
|
|
27
|
+
export declare const NODE_SAME_USER_WARNING = "These keys belong to the same HUMAIN Node user and share its limits. A second key helps only if a key is invalid or revoked.";
|
|
28
|
+
export declare const NODE_MIXED_ENVIRONMENT_WARNING = "This fallback list mixes environments, such as production and staging. Requests could reach an account you did not intend.";
|
|
29
|
+
export declare const MAX_NODE_FALLBACK_KEYS = 16;
|
|
30
|
+
export declare const MAX_NODE_LABEL_LENGTH = 80;
|
|
31
|
+
/** Aliases only. Never pass keys into this function. */
|
|
32
|
+
export declare function formatNodeSwitchNotice(fromAlias: string, reason: NodeAccountFailureReason, toAlias: string): string;
|
|
33
|
+
/** Bounded, printable text without control or format characters. */
|
|
34
|
+
export declare function isSafeNodeText(value: unknown, max: number): value is string;
|
|
35
|
+
/** Lenient read: anything malformed degrades to the disabled default or is dropped. */
|
|
36
|
+
export declare function normalizeNodeAccountMetadata(value: unknown): NodeAccountMetadata;
|
|
37
|
+
/** Lock-protected metadata file. Reads are synchronous so the request path can consult the policy. */
|
|
38
|
+
export declare class NodeAccountMetadataStore {
|
|
39
|
+
private readonly backend;
|
|
40
|
+
constructor(backend: AuthStorageBackend);
|
|
41
|
+
read(): NodeAccountMetadata;
|
|
42
|
+
update(change: (current: NodeAccountMetadata) => NodeAccountMetadata): NodeAccountMetadata;
|
|
43
|
+
}
|
|
44
|
+
export declare class FileNodeAccountMetadataStore extends NodeAccountMetadataStore {
|
|
45
|
+
private readonly path;
|
|
46
|
+
constructor(path: string);
|
|
47
|
+
/** A missing file is the disabled default; reading must not create files for users who never opt in. */
|
|
48
|
+
read(): NodeAccountMetadata;
|
|
49
|
+
}
|
|
50
|
+
export declare class InMemoryNodeAccountMetadataStore extends NodeAccountMetadataStore {
|
|
51
|
+
constructor(initial?: unknown);
|
|
52
|
+
}
|
|
53
|
+
/** Endpoint a stored Node API-key account sends to; undefined for other credentials or an invalid URL. */
|
|
54
|
+
export declare function nodeAccountEndpoint(account: Pick<PoolAccount, "credential">, ambientBaseUrl: string | undefined): string | undefined;
|
|
55
|
+
/** Whether `to` may take over from the failed `from` under `policy`. Pure so it can run under the pool lock. */
|
|
56
|
+
export declare function isNodeFallbackTarget(policy: NodeAccountFallbackPolicy, from: PoolAccount, to: PoolAccount, ambientBaseUrl: string | undefined): boolean;
|
|
57
|
+
/** Epoch ms until which the failed key is unavailable: Retry-After when sent, else a bounded cooldown. */
|
|
58
|
+
export declare function nodeFailureExhaustedUntil(failure: NodeAccountFailure, nowMs: number): number;
|
|
59
|
+
export interface NodeAccountView {
|
|
60
|
+
key: string;
|
|
61
|
+
alias: string;
|
|
62
|
+
endpoint?: string;
|
|
63
|
+
nodeUser?: string;
|
|
64
|
+
environment?: string;
|
|
65
|
+
active: boolean;
|
|
66
|
+
inFallback: boolean;
|
|
67
|
+
}
|
|
68
|
+
export interface NodeFallbackAssessment {
|
|
69
|
+
/** Keys whose Node user must be asked for, in fallback order. */
|
|
70
|
+
needsNodeUserLabel: string[];
|
|
71
|
+
/** Keys whose endpoint environment label must be asked for, in fallback order. */
|
|
72
|
+
needsEnvironmentLabel: string[];
|
|
73
|
+
/** Fallback accounts that share one Node user and therefore its limits. */
|
|
74
|
+
sharedUserGroups: {
|
|
75
|
+
nodeUser: string;
|
|
76
|
+
accountKeys: string[];
|
|
77
|
+
}[];
|
|
78
|
+
warnings: string[];
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Setup signals for the accounts that matter to the policy: the fallback list plus the serving account.
|
|
82
|
+
* `accounts` must be in pool order; the fallback list order decides the result order.
|
|
83
|
+
*/
|
|
84
|
+
export declare function assessNodeFallback(accounts: readonly NodeAccountView[], policy: NodeAccountFallbackPolicy): NodeFallbackAssessment;
|
|
85
|
+
//# sourceMappingURL=node-account-fallback.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-account-fallback.d.ts","sourceRoot":"","sources":["../../src/humain/node-account-fallback.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,kBAAkB,EAAsD,MAAM,yBAAyB,CAAC;AACtH,OAAO,EAGN,KAAK,WAAW,EAChB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAG9F;;;GAGG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,MAAM,EAAE,CAAC;CACnB;AAID;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,QAAQ,EAAE,SAAS,eAAe,EAAE,EACpC,MAAM,EAAE,yBAAyB,GAC/B,sBAAsB,CAuBxB"}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { FileAuthStorageBackend, InMemoryAuthStorageBackend } from "../core/auth-storage.js";
|
|
3
|
+
import { ACCOUNT_RETURN_COOLDOWN_MS, ACCOUNT_RETURN_MAX_COOLDOWN_MS, } from "../core/oauth-account-pool.js";
|
|
4
|
+
import { describeHumainNodeEndpoint, HUMAIN_NODE_BASE_URL_ENV } from "./node-provider.js";
|
|
5
|
+
export const NODE_FALLBACK_NONE_MESSAGE = "No usable HUMAIN Node fallback key is configured.";
|
|
6
|
+
export const NODE_SAME_USER_WARNING = "These keys belong to the same HUMAIN Node user and share its limits. A second key helps only if a key is invalid or revoked.";
|
|
7
|
+
export const NODE_MIXED_ENVIRONMENT_WARNING = "This fallback list mixes environments, such as production and staging. Requests could reach an account you did not intend.";
|
|
8
|
+
export const MAX_NODE_FALLBACK_KEYS = 16;
|
|
9
|
+
export const MAX_NODE_LABEL_LENGTH = 80;
|
|
10
|
+
const REASON_TEXT = {
|
|
11
|
+
"invalid-key": "invalid key",
|
|
12
|
+
"revoked-key": "revoked key",
|
|
13
|
+
"rate-limit": "rate limit",
|
|
14
|
+
"weekly-cap": "weekly cap",
|
|
15
|
+
quota: "quota",
|
|
16
|
+
};
|
|
17
|
+
/** Aliases only. Never pass keys into this function. */
|
|
18
|
+
export function formatNodeSwitchNotice(fromAlias, reason, toAlias) {
|
|
19
|
+
return `HUMAIN Node key “${fromAlias}” failed (${REASON_TEXT[reason]}). Using “${toAlias}”.`;
|
|
20
|
+
}
|
|
21
|
+
function defaultMetadata() {
|
|
22
|
+
return { policy: { enabled: false, accountKeys: [], allowCrossEndpoint: false }, accounts: Object.create(null) };
|
|
23
|
+
}
|
|
24
|
+
function isRecord(value) {
|
|
25
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
26
|
+
}
|
|
27
|
+
/** Bounded, printable text without control or format characters. */
|
|
28
|
+
export function isSafeNodeText(value, max) {
|
|
29
|
+
return typeof value === "string" && value.length > 0 && value.length <= max && !/[\p{Cc}\p{Cf}]/u.test(value);
|
|
30
|
+
}
|
|
31
|
+
function isSafeKey(value) {
|
|
32
|
+
return isSafeNodeText(value, 320) && !(value in Object.prototype);
|
|
33
|
+
}
|
|
34
|
+
function normalizeLabel(value) {
|
|
35
|
+
const text = typeof value === "string" ? value.trim() : undefined;
|
|
36
|
+
return isSafeNodeText(text, MAX_NODE_LABEL_LENGTH) ? text : undefined;
|
|
37
|
+
}
|
|
38
|
+
/** Lenient read: anything malformed degrades to the disabled default or is dropped. */
|
|
39
|
+
export function normalizeNodeAccountMetadata(value) {
|
|
40
|
+
const metadata = defaultMetadata();
|
|
41
|
+
if (!isRecord(value))
|
|
42
|
+
return metadata;
|
|
43
|
+
const policy = value.policy;
|
|
44
|
+
if (isRecord(policy) &&
|
|
45
|
+
typeof policy.enabled === "boolean" &&
|
|
46
|
+
Array.isArray(policy.accountKeys) &&
|
|
47
|
+
policy.accountKeys.length <= MAX_NODE_FALLBACK_KEYS &&
|
|
48
|
+
policy.accountKeys.every(isSafeKey) &&
|
|
49
|
+
new Set(policy.accountKeys).size === policy.accountKeys.length) {
|
|
50
|
+
metadata.policy = {
|
|
51
|
+
enabled: policy.enabled,
|
|
52
|
+
accountKeys: [...policy.accountKeys],
|
|
53
|
+
allowCrossEndpoint: policy.allowCrossEndpoint === true,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if (isRecord(value.accounts)) {
|
|
57
|
+
for (const [key, labels] of Object.entries(value.accounts)) {
|
|
58
|
+
if (!isSafeKey(key) || !isRecord(labels))
|
|
59
|
+
continue;
|
|
60
|
+
const nodeUser = normalizeLabel(labels.nodeUser);
|
|
61
|
+
const environment = normalizeLabel(labels.environment);
|
|
62
|
+
if (nodeUser || environment) {
|
|
63
|
+
metadata.accounts[key] = {
|
|
64
|
+
...(nodeUser ? { nodeUser } : {}),
|
|
65
|
+
...(environment ? { environment } : {}),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return metadata;
|
|
71
|
+
}
|
|
72
|
+
function parse(content) {
|
|
73
|
+
try {
|
|
74
|
+
return normalizeNodeAccountMetadata(content ? JSON.parse(content) : undefined);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return defaultMetadata();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Lock-protected metadata file. Reads are synchronous so the request path can consult the policy. */
|
|
81
|
+
export class NodeAccountMetadataStore {
|
|
82
|
+
backend;
|
|
83
|
+
constructor(backend) {
|
|
84
|
+
this.backend = backend;
|
|
85
|
+
}
|
|
86
|
+
read() {
|
|
87
|
+
return this.backend.withLock((current) => ({ result: parse(current) }));
|
|
88
|
+
}
|
|
89
|
+
update(change) {
|
|
90
|
+
return this.backend.withLock((current) => {
|
|
91
|
+
const next = normalizeNodeAccountMetadata(change(parse(current)));
|
|
92
|
+
return { result: next, next: JSON.stringify({ version: 1, ...next }, null, 2) };
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
export class FileNodeAccountMetadataStore extends NodeAccountMetadataStore {
|
|
97
|
+
path;
|
|
98
|
+
constructor(path) {
|
|
99
|
+
super(new FileAuthStorageBackend(path));
|
|
100
|
+
this.path = path;
|
|
101
|
+
}
|
|
102
|
+
/** A missing file is the disabled default; reading must not create files for users who never opt in. */
|
|
103
|
+
read() {
|
|
104
|
+
return existsSync(this.path) ? super.read() : defaultMetadata();
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function memoryBackend(initial) {
|
|
108
|
+
const backend = new InMemoryAuthStorageBackend();
|
|
109
|
+
if (initial !== undefined)
|
|
110
|
+
backend.withLock(() => ({ result: undefined, next: JSON.stringify(initial) }));
|
|
111
|
+
return backend;
|
|
112
|
+
}
|
|
113
|
+
export class InMemoryNodeAccountMetadataStore extends NodeAccountMetadataStore {
|
|
114
|
+
constructor(initial) {
|
|
115
|
+
super(memoryBackend(initial));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Endpoint a stored Node API-key account sends to; undefined for other credentials or an invalid URL. */
|
|
119
|
+
export function nodeAccountEndpoint(account, ambientBaseUrl) {
|
|
120
|
+
const credential = account.credential;
|
|
121
|
+
if (credential.type !== "api_key")
|
|
122
|
+
return undefined;
|
|
123
|
+
const stored = credential.env?.[HUMAIN_NODE_BASE_URL_ENV];
|
|
124
|
+
return describeHumainNodeEndpoint(typeof stored === "string" ? stored : undefined, ambientBaseUrl);
|
|
125
|
+
}
|
|
126
|
+
/** Whether `to` may take over from the failed `from` under `policy`. Pure so it can run under the pool lock. */
|
|
127
|
+
export function isNodeFallbackTarget(policy, from, to, ambientBaseUrl) {
|
|
128
|
+
if (!policy.enabled || from.key === to.key || !policy.accountKeys.includes(to.key))
|
|
129
|
+
return false;
|
|
130
|
+
if (from.credential.type !== "api_key" || to.credential.type !== "api_key")
|
|
131
|
+
return false;
|
|
132
|
+
if (policy.allowCrossEndpoint === true)
|
|
133
|
+
return true;
|
|
134
|
+
const endpoint = nodeAccountEndpoint(from, ambientBaseUrl);
|
|
135
|
+
return endpoint !== undefined && endpoint === nodeAccountEndpoint(to, ambientBaseUrl);
|
|
136
|
+
}
|
|
137
|
+
/** Epoch ms until which the failed key is unavailable: Retry-After when sent, else a bounded cooldown. */
|
|
138
|
+
export function nodeFailureExhaustedUntil(failure, nowMs) {
|
|
139
|
+
if (failure.retryAfterMs !== undefined)
|
|
140
|
+
return nowMs + failure.retryAfterMs;
|
|
141
|
+
return nowMs + (failure.reason === "rate-limit" ? ACCOUNT_RETURN_COOLDOWN_MS : ACCOUNT_RETURN_MAX_COOLDOWN_MS);
|
|
142
|
+
}
|
|
143
|
+
const fold = (value) => value.trim().toLocaleLowerCase();
|
|
144
|
+
/**
|
|
145
|
+
* Setup signals for the accounts that matter to the policy: the fallback list plus the serving account.
|
|
146
|
+
* `accounts` must be in pool order; the fallback list order decides the result order.
|
|
147
|
+
*/
|
|
148
|
+
export function assessNodeFallback(accounts, policy) {
|
|
149
|
+
const scoped = [
|
|
150
|
+
...policy.accountKeys.flatMap((key) => accounts.find((account) => account.key === key) ?? []),
|
|
151
|
+
...accounts.filter((account) => account.active && !policy.accountKeys.includes(account.key)),
|
|
152
|
+
];
|
|
153
|
+
const groups = new Map();
|
|
154
|
+
for (const account of scoped) {
|
|
155
|
+
if (!account.nodeUser)
|
|
156
|
+
continue;
|
|
157
|
+
const group = groups.get(fold(account.nodeUser)) ?? { nodeUser: account.nodeUser, accountKeys: [] };
|
|
158
|
+
group.accountKeys.push(account.key);
|
|
159
|
+
groups.set(fold(account.nodeUser), group);
|
|
160
|
+
}
|
|
161
|
+
const sharedUserGroups = [...groups.values()].filter((group) => group.accountKeys.length > 1);
|
|
162
|
+
const environments = new Set(scoped.flatMap((account) => (account.environment ? [fold(account.environment)] : [])));
|
|
163
|
+
const warnings = [];
|
|
164
|
+
if (sharedUserGroups.length > 0)
|
|
165
|
+
warnings.push(NODE_SAME_USER_WARNING);
|
|
166
|
+
if (environments.size > 1)
|
|
167
|
+
warnings.push(NODE_MIXED_ENVIRONMENT_WARNING);
|
|
168
|
+
return {
|
|
169
|
+
needsNodeUserLabel: scoped.filter((account) => !account.nodeUser).map((account) => account.key),
|
|
170
|
+
needsEnvironmentLabel: scoped.filter((account) => !account.environment).map((account) => account.key),
|
|
171
|
+
sharedUserGroups,
|
|
172
|
+
warnings,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
//# sourceMappingURL=node-account-fallback.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-account-fallback.js","sourceRoot":"","sources":["../../src/humain/node-account-fallback.ts"],"names":[],"mappings":"AAAA,OA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ync } from \"node:fs\";\nimport { type AuthStorageBackend, FileAuthStorageBackend, InMemoryAuthStorageBackend } from \"../core/auth-storage.ts\";\nimport {\n\tACCOUNT_RETURN_COOLDOWN_MS,\n\tACCOUNT_RETURN_MAX_COOLDOWN_MS,\n\ttype PoolAccount,\n} from \"../core/oauth-account-pool.ts\";\nimport type { NodeAccountFailure, NodeAccountFailureReason } from \"./node-account-failure.ts\";\nimport { describeHumainNodeEndpoint, HUMAIN_NODE_BASE_URL_ENV } from \"./node-provider.ts\";\n\n/**\n * Opt-in ordered HUMAIN Node key fallback. Policy and labels live in their own file, never in the credential\n * payload: keys stay in the existing credential pool and are referenced here by opaque account key only.\n */\nexport interface NodeAccountFallbackPolicy {\n\tenabled: boolean;\n\t/** Pool account keys to try, in order, after the serving key fails. */\n\taccountKeys: string[];\n\t/** Explicit opt-in to switch between different Node endpoints. Off means same endpoint only. */\n\tallowCrossEndpoint?: boolean;\n}\n\n/** User-provided labels. Aliases are the pool account labels, so they are not duplicated here. */\nexport interface NodeAccountLabels {\n\t/** Which HUMAIN Node user owns the key. Keys of one user share limits. */\n\tnodeUser?: string;\n\t/** Environment of the endpoint, for example Production or Staging. */\n\tenvironment?: string;\n}\n\nexport interface NodeAccountMetadata {\n\tpolicy: Required<NodeAccountFallbackPolicy>;\n\taccounts: Record<string, NodeAccountLabels>;\n}\n\nexport const NODE_FALLBACK_NONE_MESSAGE = \"No usable HUMAIN Node fallback key is configured.\";\nexport const NODE_SAME_USER_WARNING =\n\t\"These keys belong to the same HUMAIN Node user and share its limits. A second key helps only if a key is invalid or revoked.\";\nexport const NODE_MIXED_ENVIRONMENT_WARNING =\n\t\"This fallback list mixes environments, such as production and staging. Requests could reach an account you did not intend.\";\n\nexport const MAX_NODE_FALLBACK_KEYS = 16;\nexport const MAX_NODE_LABEL_LENGTH = 80;\n\nconst REASON_TEXT: Record<NodeAccountFailureReason, string> = {\n\t\"invalid-key\": \"invalid key\",\n\t\"revoked-key\": \"revoked key\",\n\t\"rate-limit\": \"rate limit\",\n\t\"weekly-cap\": \"weekly cap\",\n\tquota: \"quota\",\n};\n\n/** Aliases only. Never pass keys into this function. */\nexport function formatNodeSwitchNotice(fromAlias: string, reason: NodeAccountFailureReason, toAlias: string): string {\n\treturn `HUMAIN Node key “${fromAlias}” failed (${REASON_TEXT[reason]}). Using “${toAlias}”.`;\n}\n\nfunction defaultMetadata(): NodeAccountMetadata {\n\treturn { policy: { enabled: false, accountKeys: [], allowCrossEndpoint: false }, accounts: Object.create(null) };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Bounded, printable text without control or format characters. */\nexport function isSafeNodeText(value: unknown, max: number): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= max && !/[\\p{Cc}\\p{Cf}]/u.test(value);\n}\n\nfunction isSafeKey(value: unknown): value is string {\n\treturn isSafeNodeText(value, 320) && !(value in Object.prototype);\n}\n\nfunction normalizeLabel(value: unknown): string | undefined {\n\tconst text = typeof value === \"string\" ? value.trim() : undefined;\n\treturn isSafeNodeText(text, MAX_NODE_LABEL_LENGTH) ? text : undefined;\n}\n\n/** Lenient read: anything malformed degrades to the disabled default or is dropped. */\nexport function normalizeNodeAccountMetadata(value: unknown): NodeAccountMetadata {\n\tconst metadata = defaultMetadata();\n\tif (!isRecord(value)) return metadata;\n\tconst policy = value.policy;\n\tif (\n\t\tisRecord(policy) &&\n\t\ttypeof policy.enabled === \"boolean\" &&\n\t\tArray.isArray(policy.accountKeys) &&\n\t\tpolicy.accountKeys.length <= MAX_NODE_FALLBACK_KEYS &&\n\t\tpolicy.accountKeys.every(isSafeKey) &&\n\t\tnew Set(policy.accountKeys).size === policy.accountKeys.length\n\t) {\n\t\tmetadata.policy = {\n\t\t\tenabled: policy.enabled,\n\t\t\taccountKeys: [...policy.accountKeys],\n\t\t\tallowCrossEndpoint: policy.allowCrossEndpoint === true,\n\t\t};\n\t}\n\tif (isRecord(value.accounts)) {\n\t\tfor (const [key, labels] of Object.entries(value.accounts)) {\n\t\t\tif (!isSafeKey(key) || !isRecord(labels)) continue;\n\t\t\tconst nodeUser = normalizeLabel(labels.nodeUser);\n\t\t\tconst environment = normalizeLabel(labels.environment);\n\t\t\tif (nodeUser || environment) {\n\t\t\t\tmetadata.accounts[key] = {\n\t\t\t\t\t...(nodeUser ? { nodeUser } : {}),\n\t\t\t\t\t...(environment ? { environment } : {}),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\treturn metadata;\n}\n\nfunction parse(content: string | undefined): NodeAccountMetadata {\n\ttry {\n\t\treturn normalizeNodeAccountMetadata(content ? JSON.parse(content) : undefined);\n\t} catch {\n\t\treturn defaultMetadata();\n\t}\n}\n\n/** Lock-protected metadata file. Reads are synchronous so the request path can consult the policy. */\nexport class NodeAccountMetadataStore {\n\tprivate readonly backend: AuthStorageBackend;\n\n\tconstructor(backend: AuthStorageBackend) {\n\t\tthis.backend = backend;\n\t}\n\n\tread(): NodeAccountMetadata {\n\t\treturn this.backend.withLock((current) => ({ result: parse(current) }));\n\t}\n\n\tupdate(change: (current: NodeAccountMetadata) => NodeAccountMetadata): NodeAccountMetadata {\n\t\treturn this.backend.withLock((current) => {\n\t\t\tconst next = normalizeNodeAccountMetadata(change(parse(current)));\n\t\t\treturn { result: next, next: JSON.stringify({ version: 1, ...next }, null, 2) };\n\t\t});\n\t}\n}\n\nexport class FileNodeAccountMetadataStore extends NodeAccountMetadataStore {\n\tprivate readonly path: string;\n\n\tconstructor(path: string) {\n\t\tsuper(new FileAuthStorageBackend(path));\n\t\tthis.path = path;\n\t}\n\n\t/** A missing file is the disabled default; reading must not create files for users who never opt in. */\n\toverride read(): NodeAccountMetadata {\n\t\treturn existsSync(this.path) ? super.read() : defaultMetadata();\n\t}\n}\n\nfunction memoryBackend(initial: unknown): AuthStorageBackend {\n\tconst backend = new InMemoryAuthStorageBackend();\n\tif (initial !== undefined) backend.withLock(() => ({ result: undefined, next: JSON.stringify(initial) }));\n\treturn backend;\n}\n\nexport class InMemoryNodeAccountMetadataStore extends NodeAccountMetadataStore {\n\tconstructor(initial?: unknown) {\n\t\tsuper(memoryBackend(initial));\n\t}\n}\n\n/** Endpoint a stored Node API-key account sends to; undefined for other credentials or an invalid URL. */\nexport function nodeAccountEndpoint(\n\taccount: Pick<PoolAccount, \"credential\">,\n\tambientBaseUrl: string | undefined,\n): string | undefined {\n\tconst credential = account.credential;\n\tif (credential.type !== \"api_key\") return undefined;\n\tconst stored = credential.env?.[HUMAIN_NODE_BASE_URL_ENV];\n\treturn describeHumainNodeEndpoint(typeof stored === \"string\" ? stored : undefined, ambientBaseUrl);\n}\n\n/** Whether `to` may take over from the failed `from` under `policy`. Pure so it can run under the pool lock. */\nexport function isNodeFallbackTarget(\n\tpolicy: NodeAccountFallbackPolicy,\n\tfrom: PoolAccount,\n\tto: PoolAccount,\n\tambientBaseUrl: string | undefined,\n): boolean {\n\tif (!policy.enabled || from.key === to.key || !policy.accountKeys.includes(to.key)) return false;\n\tif (from.credential.type !== \"api_key\" || to.credential.type !== \"api_key\") return false;\n\tif (policy.allowCrossEndpoint === true) return true;\n\tconst endpoint = nodeAccountEndpoint(from, ambientBaseUrl);\n\treturn endpoint !== undefined && endpoint === nodeAccountEndpoint(to, ambientBaseUrl);\n}\n\n/** Epoch ms until which the failed key is unavailable: Retry-After when sent, else a bounded cooldown. */\nexport function nodeFailureExhaustedUntil(failure: NodeAccountFailure, nowMs: number): number {\n\tif (failure.retryAfterMs !== undefined) return nowMs + failure.retryAfterMs;\n\treturn nowMs + (failure.reason === \"rate-limit\" ? ACCOUNT_RETURN_COOLDOWN_MS : ACCOUNT_RETURN_MAX_COOLDOWN_MS);\n}\n\nexport interface NodeAccountView {\n\tkey: string;\n\talias: string;\n\tendpoint?: string;\n\tnodeUser?: string;\n\tenvironment?: string;\n\tactive: boolean;\n\tinFallback: boolean;\n}\n\nexport interface NodeFallbackAssessment {\n\t/** Keys whose Node user must be asked for, in fallback order. */\n\tneedsNodeUserLabel: string[];\n\t/** Keys whose endpoint environment label must be asked for, in fallback order. */\n\tneedsEnvironmentLabel: string[];\n\t/** Fallback accounts that share one Node user and therefore its limits. */\n\tsharedUserGroups: { nodeUser: string; accountKeys: string[] }[];\n\twarnings: string[];\n}\n\nconst fold = (value: string) => value.trim().toLocaleLowerCase();\n\n/**\n * Setup signals for the accounts that matter to the policy: the fallback list plus the serving account.\n * `accounts` must be in pool order; the fallback list order decides the result order.\n */\nexport function assessNodeFallback(\n\taccounts: readonly NodeAccountView[],\n\tpolicy: NodeAccountFallbackPolicy,\n): NodeFallbackAssessment {\n\tconst scoped = [\n\t\t...policy.accountKeys.flatMap((key) => accounts.find((account) => account.key === key) ?? []),\n\t\t...accounts.filter((account) => account.active && !policy.accountKeys.includes(account.key)),\n\t];\n\tconst groups = new Map<string, { nodeUser: string; accountKeys: string[] }>();\n\tfor (const account of scoped) {\n\t\tif (!account.nodeUser) continue;\n\t\tconst group = groups.get(fold(account.nodeUser)) ?? { nodeUser: account.nodeUser, accountKeys: [] };\n\t\tgroup.accountKeys.push(account.key);\n\t\tgroups.set(fold(account.nodeUser), group);\n\t}\n\tconst sharedUserGroups = [...groups.values()].filter((group) => group.accountKeys.length > 1);\n\tconst environments = new Set(scoped.flatMap((account) => (account.environment ? [fold(account.environment)] : [])));\n\tconst warnings: string[] = [];\n\tif (sharedUserGroups.length > 0) warnings.push(NODE_SAME_USER_WARNING);\n\tif (environments.size > 1) warnings.push(NODE_MIXED_ENVIRONMENT_WARNING);\n\treturn {\n\t\tneedsNodeUserLabel: scoped.filter((account) => !account.nodeUser).map((account) => account.key),\n\t\tneedsEnvironmentLabel: scoped.filter((account) => !account.environment).map((account) => account.key),\n\t\tsharedUserGroups,\n\t\twarnings,\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-http.d.ts","sourceRoot":"","sources":["../../src/humain/node-http.ts"],"names":[],"mappings":"AAAA,OAAO,EAON,KAAK,eAAe,EAGpB,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"node-http.d.ts","sourceRoot":"","sources":["../../src/humain/node-http.ts"],"names":[],"mappings":"AAAA,OAAO,EAON,KAAK,eAAe,EAGpB,MAAM,uBAAuB,CAAC;AAoB/B,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,eAAe,GAAG,eAAe,CA8JxE"}
|
package/dist/humain/node-http.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { lazyStream, } from "@earendil-works/pi-ai";
|
|
2
|
+
import { classifyNodeAccountFailure } from "./node-account-failure.js";
|
|
2
3
|
function isJsonValue(value) {
|
|
3
4
|
if (value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
|
|
4
5
|
return true;
|
|
@@ -76,6 +77,16 @@ export function withHumainNodeHttp(api) {
|
|
|
76
77
|
httpError = { status: response.status, retryable };
|
|
77
78
|
if (code !== undefined)
|
|
78
79
|
httpError.code = redact(code);
|
|
80
|
+
// Lets the session switch to another configured Node key without re-reading the response.
|
|
81
|
+
const accountFailure = classifyNodeAccountFailure(response.status, responseBody, response.headers);
|
|
82
|
+
if (accountFailure) {
|
|
83
|
+
httpError.nodeAccountFailure = {
|
|
84
|
+
reason: accountFailure.reason,
|
|
85
|
+
...(accountFailure.retryAfterMs === undefined
|
|
86
|
+
? {}
|
|
87
|
+
: { retryAfterMs: accountFailure.retryAfterMs }),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
79
90
|
if (retryAfter) {
|
|
80
91
|
const retryAt = /^\d+(?:\.\d+)?$/u.test(retryAfter)
|
|
81
92
|
? Date.now() + Number(retryAfter) * 1000
|