@wildo-ai/wildo-cli 1.1.15 → 1.1.16
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/dist/src/commands/context/journey.command.d.ts.map +1 -1
- package/dist/src/commands/context/journey.command.js +12 -0
- package/dist/src/commands/context/journey.command.js.map +1 -1
- package/dist/src/commands/creation/drive.command.d.ts.map +1 -1
- package/dist/src/commands/creation/drive.command.js +2 -1
- package/dist/src/commands/creation/drive.command.js.map +1 -1
- package/dist/src/commands/local/dev.command.d.ts +44 -0
- package/dist/src/commands/local/dev.command.d.ts.map +1 -1
- package/dist/src/commands/local/dev.command.js +74 -3
- package/dist/src/commands/local/dev.command.js.map +1 -1
- package/dist/src/commands/providers/grant-export.command.d.ts +16 -0
- package/dist/src/commands/providers/grant-export.command.d.ts.map +1 -0
- package/dist/src/commands/providers/grant-export.command.js +78 -0
- package/dist/src/commands/providers/grant-export.command.js.map +1 -0
- package/dist/src/commands/providers/grant-import.command.d.ts +15 -0
- package/dist/src/commands/providers/grant-import.command.d.ts.map +1 -0
- package/dist/src/commands/providers/grant-import.command.js +78 -0
- package/dist/src/commands/providers/grant-import.command.js.map +1 -0
- package/dist/src/kernel/command-runner.d.ts.map +1 -1
- package/dist/src/kernel/command-runner.js +4 -6
- package/dist/src/kernel/command-runner.js.map +1 -1
- package/dist/src/kernel/hooks.d.ts.map +1 -1
- package/dist/src/kernel/hooks.js +2 -1
- package/dist/src/kernel/hooks.js.map +1 -1
- package/dist/src/kernel/json-document-output.d.ts +7 -0
- package/dist/src/kernel/json-document-output.d.ts.map +1 -1
- package/dist/src/kernel/json-document-output.js +8 -0
- package/dist/src/kernel/json-document-output.js.map +1 -1
- package/dist/src/kernel/types.d.ts +8 -0
- package/dist/src/kernel/types.d.ts.map +1 -1
- package/dist/src/kernel/types.js.map +1 -1
- package/dist/src/services/application/app-bootstrap.service.d.ts +24 -6
- package/dist/src/services/application/app-bootstrap.service.d.ts.map +1 -1
- package/dist/src/services/application/app-bootstrap.service.js +46 -13
- package/dist/src/services/application/app-bootstrap.service.js.map +1 -1
- package/dist/src/services/application/app-local-runtime-addresses.service.d.ts +1 -1
- package/dist/src/services/application/app-local-runtime-addresses.service.d.ts.map +1 -1
- package/dist/src/services/application/app-local-runtime-addresses.service.js.map +1 -1
- package/dist/src/services/application/app-runtime-targets.service.d.ts.map +1 -1
- package/dist/src/services/application/app-runtime-targets.service.js +7 -1
- package/dist/src/services/application/app-runtime-targets.service.js.map +1 -1
- package/dist/src/services/application/application-runtime-bootstrap.service.d.ts +13 -0
- package/dist/src/services/application/application-runtime-bootstrap.service.d.ts.map +1 -1
- package/dist/src/services/application/application-runtime-bootstrap.service.js +32 -0
- package/dist/src/services/application/application-runtime-bootstrap.service.js.map +1 -1
- package/dist/src/services/application/environment-provider-configurations.service.d.ts +7 -0
- package/dist/src/services/application/environment-provider-configurations.service.d.ts.map +1 -1
- package/dist/src/services/application/environment-provider-configurations.service.js +1 -1
- package/dist/src/services/application/environment-provider-configurations.service.js.map +1 -1
- package/dist/src/services/application/local-tunnel.service.d.ts.map +1 -1
- package/dist/src/services/application/local-tunnel.service.js +2 -1
- package/dist/src/services/application/local-tunnel.service.js.map +1 -1
- package/dist/src/services/companion/companion-client.service.d.ts +17 -0
- package/dist/src/services/companion/companion-client.service.d.ts.map +1 -1
- package/dist/src/services/companion/companion-client.service.js +21 -0
- package/dist/src/services/companion/companion-client.service.js.map +1 -1
- package/dist/src/services/companion/creation-drive.service.d.ts +18 -0
- package/dist/src/services/companion/creation-drive.service.d.ts.map +1 -1
- package/dist/src/services/companion/creation-drive.service.js +70 -1
- package/dist/src/services/companion/creation-drive.service.js.map +1 -1
- package/dist/src/services/deployment/docker/docker-compose-generator.service.d.ts +10 -1
- package/dist/src/services/deployment/docker/docker-compose-generator.service.d.ts.map +1 -1
- package/dist/src/services/deployment/docker/docker-compose-generator.service.js +24 -10
- package/dist/src/services/deployment/docker/docker-compose-generator.service.js.map +1 -1
- package/dist/src/services/deployment/framework-pod-network-membership.d.ts.map +1 -1
- package/dist/src/services/deployment/framework-pod-network-membership.js +5 -0
- package/dist/src/services/deployment/framework-pod-network-membership.js.map +1 -1
- package/dist/src/services/deployment/local-dev-late-workspace-members.service.d.ts +43 -4
- package/dist/src/services/deployment/local-dev-late-workspace-members.service.d.ts.map +1 -1
- package/dist/src/services/deployment/local-dev-late-workspace-members.service.js +116 -9
- package/dist/src/services/deployment/local-dev-late-workspace-members.service.js.map +1 -1
- package/dist/src/services/environment/authored-infra-config.utils.d.ts +4 -3
- package/dist/src/services/environment/authored-infra-config.utils.d.ts.map +1 -1
- package/dist/src/services/environment/authored-infra-config.utils.js +4 -3
- package/dist/src/services/environment/authored-infra-config.utils.js.map +1 -1
- package/dist/src/services/framework/package-install.service.d.ts +7 -0
- package/dist/src/services/framework/package-install.service.d.ts.map +1 -1
- package/dist/src/services/framework/package-install.service.js +8 -1
- package/dist/src/services/framework/package-install.service.js.map +1 -1
- package/dist/src/services/registry/application-provider-connection.service.d.ts +16 -1
- package/dist/src/services/registry/application-provider-connection.service.d.ts.map +1 -1
- package/dist/src/services/registry/application-provider-connection.service.js +23 -0
- package/dist/src/services/registry/application-provider-connection.service.js.map +1 -1
- package/dist/src/services/registry/provider-grant-transfer.service.d.ts +48 -0
- package/dist/src/services/registry/provider-grant-transfer.service.d.ts.map +1 -0
- package/dist/src/services/registry/provider-grant-transfer.service.js +144 -0
- package/dist/src/services/registry/provider-grant-transfer.service.js.map +1 -0
- package/dist/src/services/registry/provider-module-scaffold.service.d.ts.map +1 -1
- package/dist/src/services/registry/provider-module-scaffold.service.js +10 -3
- package/dist/src/services/registry/provider-module-scaffold.service.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +19 -19
- package/templates/infra/docker-compose/docker-compose.wildo-platform.yml.hbs +2 -0
- package/templates/saas/i18n/email/system/remote-agent-task-updated/labels.en.ts +11 -0
- package/templates/saas/i18n/email/system/remote-agent-task-updated/template.tsx +56 -0
- package/templates/saas/i18n/engine/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.en.ts +61 -0
- package/templates/saas/i18n/engine/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.fr.ts +61 -0
- package/templates/saas/scenarios/add-technical-doc/files/technical-doc/docusaurus.config.ts.hbs +5 -4
- package/templates/saas/scenarios/add-technical-doc/files/technical-doc/package.json.hbs +1 -1
- package/templates/saas/scenarios/add-technical-doc/files/technical-doc/scripts/substitute-api-origin.mjs +97 -32
- package/templates/saas/scenarios/add-technical-doc/files/technical-doc/src/plugins/api-reference-pages.ts +7 -6
- package/wildo-framework.info.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-tunnel.service.js","sourceRoot":"","sources":["../../../../src/services/application/local-tunnel.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AAC1F,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAsB;IAC3D,sDAAsD;IACtD,kBAAkB;CACnB,CAAC;AA6CF,MAAM,CAAC,MAAM,6BAA6B,GAAG,IAAI,CAAC,aAAa,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC;AAEzF,4EAA4E;AAC5E,MAAM,UAAU,sBAAsB,CAAC,OAAe,OAAO,EAAE;IAC7D,OAAO,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,QAA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C5B,SAAS,EAAE,MAAM,CAAC,YAAY;gBAC9B,WAAW,EAAE,KAAK,CAAC,WAAW;gBAC9B,wBAAwB,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,wBAAwB,IAAI,EAAE,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC;aACjG;SACF;QACD,OAAO,EAAE,IAAI;KACd,CAAC;AACJ,CAAC","sourcesContent":["/**\n * A locally-managed Cloudflare tunnel that gives a local application a public HTTPS origin while it runs (#3907).\n *\n * ## What it is for\n *\n * An outside party (an A2A client following the agent card, an MCP client, a push receiver, a vendor webhook) cannot\n * reach `http://localhost`. A named tunnel ends TLS at Cloudflare's edge and forwards to the local backend, which keeps\n * listening on plain http: the 2026-08-14 failure (a backend port advertising https with no certificate) cannot recur.\n *\n * ## The shape, and why\n *\n * - **One public origin per application** (`https://<app>-<machine>.wildo.ai`). The engine derives the OAuth issuer, every\n * audience and the A2A card `url` from the default frontend's `publicUrl` + `/api/v1`, as behind a deployed ingress, so\n * the tunnel path-routes that origin: the protocol paths go to the backend, everything else answers 404\n * ({@link TUNNEL_FORWARDED_API_PATHS}). The frontend is not exposed until Cloudflare Access fronts it.\n * - **One `cloudflared` process per MACHINE**, whose ingress is the union of every application that is up plus the\n * declared extras (a test receiver). Two connectors of one named tunnel with different ingress would answer each\n * other's requests: two connectors of one tunnel are replicas, and \"Replicas do not support traffic steering\".\n * - **Only the default frontend's `publicUrl` follows the tunnel**, and only while the recorded process is alive\n * ({@link readLiveApplicationTunnel}); the local listen origin stays a configured browser origin\n * (`additionalBrowserOrigins`). See `AppBootstrapService.buildRuntimeEndpoints`.\n *\n * Off by default: nothing here runs unless `wildo local tunnel up` is asked, and a running dev stack (which signs in with\n * known local credentials) is never reachable by accident.\n *\n * spec-cite: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/deploy-tunnels/deploy-cloudflared-replicas/\n * (fetched 2026-11-16): \"Replicas do not support traffic steering (such as round-robin or hash-based routing).\" and\n * \"Cloudflare retries with other replicas, but there is no guarantee about which one is chosen.\"\n */\nimport { spawn, execFile, execFileSync } from 'child_process';\nimport { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'fs';\nimport { homedir } from 'os';\nimport { dirname, join } from 'path';\nimport { promisify } from 'util';\n\n/**\n * The backend paths an outside party must reach, forwarded through the tunnel; every other path answers 404.\n *\n * The API's protocol surfaces (`/api/v1/a2a…`, `/api/v1/mcp…`, the OAuth endpoints, the discovery documents and the\n * webhooks) and the root RFC 8414 / RFC 9728 discovery aliases. Not `/api/v1/auth/*` (sign-in), not the resource API,\n * not `/internal/*`, not `/health*`: a dev stack signs in with known credentials and must not be reachable beyond the\n * protocol doors.\n */\nexport const TUNNEL_FORWARDED_API_PATHS: readonly string[] = [\n '^/api/v1/(a2a|mcp|oauth|\\\\.well-known|webhooks)(/|$)',\n '^/\\\\.well-known/',\n];\n\n/** One application's entry in the machine's tunnel. */\nexport interface TunnelApplicationRoute {\n readonly hostname: string;\n readonly backendPort: number;\n}\n\n/** A hostname the tunnel serves that is not an application: a test receiver. */\nexport interface TunnelExtraRoute {\n readonly hostname: string;\n /** `http://127.0.0.1:<port>`: always a local service. */\n readonly service: string;\n}\n\n/** What an application records while its public origin is the tunnel's. Machine-local, gitignored, throwaway. */\nexport interface ApplicationTunnelState {\n readonly schemaVersion: 1;\n readonly tunnelName: string;\n readonly hostname: string;\n /** `https://<hostname>`: the default frontend's `publicUrl` while the tunnel runs. */\n readonly publicOrigin: string;\n /** The frontend service whose `publicUrl` follows the tunnel: the one the backend resolves as its default. */\n readonly frontendServiceName: string;\n readonly backendPort: number;\n}\n\n/** The machine's one tunnel process and everything it serves. */\nexport interface MachineTunnelState {\n readonly schemaVersion: 1;\n readonly tunnelName: string;\n readonly pid: number | null;\n readonly configPath: string;\n readonly logPath: string;\n /** Keyed by application root. */\n readonly applications: Record<string, TunnelApplicationRoute>;\n readonly extras: readonly TunnelExtraRoute[];\n /**\n * The credentials file the tunnel was started with when it was GIVEN (`--credentials-file`), on a machine with no\n * Cloudflare login (#3907 item 3, the QA VM). A restart then reuses it instead of asking the account, which that\n * machine cannot do. Absent when the tunnel was found through this machine's login.\n */\n readonly givenCredentialsFile?: string;\n}\n\nexport const APPLICATION_TUNNEL_STATE_FILE = join('.wildo-saas', 'state', 'tunnel.json');\n\n/** `~/.wildo/tunnel`: the machine's tunnel files. Overridable for tests. */\nexport function machineTunnelDirectory(home: string = homedir()): string {\n return join(home, '.wildo', 'tunnel');\n}\n\nexport function applicationTunnelStatePath(appRoot: string): string {\n return join(appRoot, APPLICATION_TUNNEL_STATE_FILE);\n}\n\nfunction readJson<T>(path: string): T | null {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as T;\n } catch {\n return null;\n }\n}\n\nfunction writeJson(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n\nexport function readMachineTunnelState(directory: string = machineTunnelDirectory()): MachineTunnelState | null {\n return readJson<MachineTunnelState>(join(directory, 'state.json'));\n}\n\nexport function writeMachineTunnelState(state: MachineTunnelState, directory: string = machineTunnelDirectory()): void {\n writeJson(join(directory, 'state.json'), state);\n}\n\nexport function readApplicationTunnelState(appRoot: string): ApplicationTunnelState | null {\n return readJson<ApplicationTunnelState>(applicationTunnelStatePath(appRoot));\n}\n\nexport function writeApplicationTunnelState(appRoot: string, state: ApplicationTunnelState): void {\n writeJson(applicationTunnelStatePath(appRoot), state);\n}\n\nexport function removeApplicationTunnelState(appRoot: string): void {\n rmSync(applicationTunnelStatePath(appRoot), { force: true });\n}\n\n/**\n * Whether `pid` is the machine's tunnel: a live process this user owns that runs `cloudflared` with `configPath`.\n *\n * A pid alone is not enough (#3907 review F4): after a reboot it may name an unrelated process, which the command would\n * then signal and the env generation would believe is the tunnel. So the process's own command line must name both.\n */\nexport function processIsTunnel(pid: number | null | undefined, configPath: string): boolean {\n if (!pid || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n } catch {\n return false;\n }\n try {\n const command = execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' });\n return command.includes('cloudflared') && command.includes(configPath);\n } catch {\n return false;\n }\n}\n\n/**\n * The application's tunnel, only when it is in effect: its state exists, the machine's tunnel serves it, and the\n * recorded `cloudflared` process is alive. A state left behind by a crash or a reboot is IGNORED (and named by\n * `staleReason`), so the next env generation never advertises a dead issuer.\n */\nexport function readLiveApplicationTunnel(\n appRoot: string,\n directory: string = machineTunnelDirectory(),\n isTunnel: (pid: number | null | undefined, configPath: string) => boolean = processIsTunnel,\n): { readonly live: ApplicationTunnelState | null; readonly staleReason: string | null } {\n const state = readApplicationTunnelState(appRoot);\n if (!state) return { live: null, staleReason: null };\n const machine = readMachineTunnelState(directory);\n if (!machine || machine.applications[appRoot]?.hostname !== state.hostname) {\n return { live: null, staleReason: `the machine's tunnel does not serve ${state.hostname}` };\n }\n if (!isTunnel(machine.pid, machine.configPath)) {\n return { live: null, staleReason: `the tunnel process (pid ${machine.pid ?? 'none'}) is not running` };\n }\n return { live: state, staleReason: null };\n}\n\n/**\n * The `cloudflared` ingress for the machine's tunnel: per application, the forwarded API paths to its backend and a 404\n * for everything else on its hostname; then the extras; then a catch-all 404.\n *\n * spec-cite: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/local-management/configuration-file/\n * (fetched 2026-11-16): the ingress check shows \"the first rule that matches\", and \"Configuration files that contain\n * ingress rules must always include a catch-all rule that concludes the file.\"\n */\nexport function buildTunnelIngressYaml(input: {\n readonly tunnelName: string;\n readonly credentialsFile: string;\n readonly applications: readonly TunnelApplicationRoute[];\n readonly extras: readonly TunnelExtraRoute[];\n}): string {\n const lines = [\n `tunnel: ${input.tunnelName}`,\n `credentials-file: ${input.credentialsFile}`,\n 'ingress:',\n ];\n for (const application of input.applications) {\n for (const path of TUNNEL_FORWARDED_API_PATHS) {\n lines.push(` - hostname: ${application.hostname}`, ` path: ${JSON.stringify(path)}`, ` service: http://127.0.0.1:${application.backendPort}`);\n }\n lines.push(` - hostname: ${application.hostname}`, ' service: http_status:404');\n }\n for (const extra of input.extras) {\n lines.push(` - hostname: ${extra.hostname}`, ` service: ${extra.service}`);\n }\n lines.push(' - service: http_status:404', '');\n return lines.join('\\n');\n}\n\n/** The `cloudflared` operations the command needs, injectable for tests. */\nexport interface CloudflaredRunner {\n /** Run a `cloudflared` subcommand to completion; resolves its stdout, rejects with its stderr. */\n exec(args: readonly string[]): Promise<string>;\n /** Start `cloudflared` detached with its output in `logPath`; resolves the pid. */\n startDetached(args: readonly string[], logPath: string): number;\n /** Stop a process this command started. */\n stop(pid: number): void;\n}\n\nexport const systemCloudflaredRunner: CloudflaredRunner = {\n async exec(args) {\n const { stdout } = await promisify(execFile)('cloudflared', [...args], { maxBuffer: 8 * 1024 * 1024 });\n return stdout;\n },\n startDetached(args, logPath) {\n mkdirSync(dirname(logPath), { recursive: true });\n const out = openSync(logPath, 'a');\n const child = spawn('cloudflared', [...args], { detached: true, stdio: ['ignore', out, out] });\n child.unref();\n if (!child.pid) throw new Error('cloudflared did not start');\n return child.pid;\n },\n stop(pid) {\n try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ }\n },\n};\n\n/** `cloudflared tunnel list --output json`, read defensively: anything but an array is no tunnel. */\nasync function listTunnels(runner: CloudflaredRunner, tunnelName: string): Promise<Array<{ id?: string; name?: string }>> {\n const parsed = JSON.parse(await runner.exec(['tunnel', 'list', '--output', 'json', '--name', tunnelName])) as unknown;\n return Array.isArray(parsed) ? parsed as Array<{ id?: string; name?: string }> : [];\n}\n\n/** The named tunnel's id, creating the tunnel when this machine's `cert.pem` login has none by that name. */\nexport async function ensureNamedTunnel(runner: CloudflaredRunner, tunnelName: string): Promise<{ readonly id: string; readonly created: boolean }> {\n const existing = (await listTunnels(runner, tunnelName)).find((tunnel) => tunnel.name === tunnelName && tunnel.id);\n if (existing?.id) return { id: existing.id, created: false };\n await runner.exec(['tunnel', 'create', tunnelName]);\n const created = (await listTunnels(runner, tunnelName)).find((tunnel) => tunnel.name === tunnelName && tunnel.id);\n if (!created?.id) throw new Error(`cloudflared created no tunnel named ${tunnelName}`);\n return { id: created.id, created: true };\n}\n\n/**\n * Route `hostname` to the tunnel, or refuse.\n *\n * `cloudflared tunnel route dns` already SUCCEEDS when the record routes to this tunnel (\"is already configured to route\n * to your tunnel\"), so the idempotent case needs no handling. The error it raises for an existing record (\"An A, AAAA, or\n * CNAME record with that host already exists\") is the case where the hostname points ELSEWHERE — another tunnel, or a\n * record someone else made. That is never tolerated (#3907 review F1): the application would advertise an issuer, its\n * audiences and its agent card on a host another party serves, and outside clients would send their tokens there.\n */\nexport async function routeHostname(runner: CloudflaredRunner, tunnelName: string, hostname: string): Promise<void> {\n try {\n await runner.exec(['tunnel', 'route', 'dns', tunnelName, hostname]);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const elsewhere = /already exists/i.test(message)\n ? ' A record that already exists points somewhere else; remove it or choose another hostname.'\n : '';\n throw new Error(`${hostname} could not be routed to the tunnel '${tunnelName}': ${message.trim()}.${elsewhere} Nothing was changed.`);\n }\n}\n\n/** Wait until `cloudflared` reports a registered connection in its log, or the process ends; `false` on timeout. */\nexport async function waitForTunnelConnection(\n logPath: string,\n pid: number,\n configPath: string,\n options: { timeoutMs?: number; isTunnel?: typeof processIsTunnel; readLog?: (path: string) => string; sleep?: (ms: number) => Promise<void> } = {},\n): Promise<boolean> {\n const isTunnel = options.isTunnel ?? processIsTunnel;\n const readLog = options.readLog ?? ((path: string) => { try { return readFileSync(path, 'utf8'); } catch { return ''; } });\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const startLength = readLog(logPath).length;\n const deadline = Date.now() + (options.timeoutMs ?? 30_000);\n while (Date.now() < deadline) {\n if (/Registered tunnel connection/.test(readLog(logPath).slice(startLength))) return true;\n if (!isTunnel(pid, configPath)) return false;\n await sleep(500);\n }\n return false;\n}\n\n/** Wait until a stopped `cloudflared` has exited, so two connectors with different ingress never overlap (review F12). */\nexport async function waitForTunnelExit(pid: number, configPath: string, options: { timeoutMs?: number; isTunnel?: typeof processIsTunnel; sleep?: (ms: number) => Promise<void> } = {}): Promise<boolean> {\n const isTunnel = options.isTunnel ?? processIsTunnel;\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const deadline = Date.now() + (options.timeoutMs ?? 40_000);\n while (Date.now() < deadline) {\n if (!isTunnel(pid, configPath)) return true;\n await sleep(500);\n }\n return !isTunnel(pid, configPath);\n}\n\n/** The credentials file `cloudflared tunnel create` wrote for a locally-managed tunnel. */\nexport function credentialsFileOf(tunnelId: string, home: string = homedir()): string {\n return join(home, '.cloudflared', `${tunnelId}.json`);\n}\n\n/** Whether `cloudflared` is installed and logged in (`cert.pem`), with what to do when it is not. */\n/**\n * The tunnel id a credentials file holds (`TunnelID`), read without ever returning or logging the secret beside it.\n * Refuses a file that is not one (#3907 item 3: the QA VM receives the file as a CI secret, so a malformed secret must\n * fail here, by name, rather than as a cloudflared connection that never registers).\n */\nexport function tunnelIdOfCredentialsFile(path: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n throw new Error(`${path} is not a readable tunnel credentials file (JSON).`);\n }\n const id = (parsed as { TunnelID?: unknown } | null)?.TunnelID;\n if (typeof id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u.test(id)) {\n throw new Error(`${path} names no TunnelID: it is not a tunnel credentials file.`);\n }\n return id;\n}\n\nexport function cloudflaredReadiness(home: string = homedir()): string | null {\n return existsSync(join(home, '.cloudflared', 'cert.pem'))\n ? null\n : 'No Cloudflare login on this machine: run `cloudflared tunnel login` once (it writes ~/.cloudflared/cert.pem).';\n}\n\n/** A runtime endpoint as the env generation writes it (`RuntimeEndpointUrls` in `@wildo-ai/platform-core-shared`). */\ninterface WritableRuntimeEndpoint {\n publicUrl: string;\n internalUrl: string;\n additionalBrowserOrigins?: string[];\n}\n\n/**\n * The runtime endpoints with a live tunnel applied: ONLY the tunnel's frontend gets the public origin as its `publicUrl`,\n * and keeps the local listen origin as an additional browser origin, so the developer's own browser still passes every\n * origin check. Every other endpoint (the backend's included: the SPA builds its WebSocket URL from it) is unchanged.\n * Returns the input when there is no tunnel, or when its frontend has no endpoint (named in `skipped`).\n */\nexport function applyTunnelToRuntimeEndpoints<T extends Record<string, WritableRuntimeEndpoint>>(\n endpoints: T,\n tunnel: Pick<ApplicationTunnelState, 'publicOrigin' | 'frontendServiceName'> | null,\n): { readonly endpoints: T; readonly skipped: string | null } {\n if (!tunnel) return { endpoints, skipped: null };\n const local = endpoints[tunnel.frontendServiceName];\n if (!local) return { endpoints, skipped: `the tunnel names frontend '${tunnel.frontendServiceName}', which has no local endpoint` };\n const localOrigin = new URL(local.publicUrl).origin;\n return {\n endpoints: {\n ...endpoints,\n [tunnel.frontendServiceName]: {\n publicUrl: tunnel.publicOrigin,\n internalUrl: local.internalUrl,\n additionalBrowserOrigins: [...new Set([...(local.additionalBrowserOrigins ?? []), localOrigin])],\n },\n },\n skipped: null,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"local-tunnel.service.js","sourceRoot":"","sources":["../../../../src/services/application/local-tunnel.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AAC1F,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,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AAS,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;IACpD,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,8BAA8B,MAAM,CAAC,mBAAmB,gCAAgC,EAAE,CAAC;IACpI,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC;IACpD,OAAO;QACL,SAAS,EAAE;YACT,GAAG,SAAS;YACZ,CAAC,MAAM,CAAC,mBAAmB,CAAC,EAAE;gBAC5B,SAAS,EAAE,MAAM,CAAC,YAAY;gBAC9B,WAAW,EAAE,KAAK,CAAC,WAAW;gBAC9B,wBAAwB,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,wBAAwB,IAAI,EAAE,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC;aACjG;SACF;QACD,OAAO,EAAE,IAAI;KACd,CAAC;AACJ,CAAC","sourcesContent":["/**\n * A locally-managed Cloudflare tunnel that gives a local application a public HTTPS origin while it runs (#3907).\n *\n * ## What it is for\n *\n * An outside party (an A2A client following the agent card, an MCP client, a push receiver, a vendor webhook) cannot\n * reach `http://localhost`. A named tunnel ends TLS at Cloudflare's edge and forwards to the local backend, which keeps\n * listening on plain http: the 2026-08-14 failure (a backend port advertising https with no certificate) cannot recur.\n *\n * ## The shape, and why\n *\n * - **One public origin per application** (`https://<app>-<machine>.wildo.ai`). The engine derives the OAuth issuer, every\n * audience and the A2A card `url` from the default frontend's `publicUrl` + `/api/v1`, as behind a deployed ingress, so\n * the tunnel path-routes that origin: the protocol paths go to the backend, everything else answers 404\n * ({@link TUNNEL_FORWARDED_API_PATHS}). The frontend is not exposed until Cloudflare Access fronts it.\n * - **One `cloudflared` process per MACHINE**, whose ingress is the union of every application that is up plus the\n * declared extras (a test receiver). Two connectors of one named tunnel with different ingress would answer each\n * other's requests: two connectors of one tunnel are replicas, and \"Replicas do not support traffic steering\".\n * - **Only the default frontend's `publicUrl` follows the tunnel**, and only while the recorded process is alive\n * ({@link readLiveApplicationTunnel}); the local listen origin stays a configured browser origin\n * (`additionalBrowserOrigins`). See `AppBootstrapService.buildRuntimeEndpoints`.\n *\n * Off by default: nothing here runs unless `wildo local tunnel up` is asked, and a running dev stack (which signs in with\n * known local credentials) is never reachable by accident.\n *\n * spec-cite: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/deploy-tunnels/deploy-cloudflared-replicas/\n * (fetched 2026-11-16): \"Replicas do not support traffic steering (such as round-robin or hash-based routing).\" and\n * \"Cloudflare retries with other replicas, but there is no guarantee about which one is chosen.\"\n */\nimport { spawn, execFile, execFileSync } from 'child_process';\nimport { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'fs';\nimport { homedir } from 'os';\nimport { dirname, join } from 'path';\nimport { promisify } from 'util';\nimport { describeCaughtError } from '@wildo-ai/saas-models';\n\n/**\n * The backend paths an outside party must reach, forwarded through the tunnel; every other path answers 404.\n *\n * The API's protocol surfaces (`/api/v1/a2a…`, `/api/v1/mcp…`, the OAuth endpoints, the discovery documents and the\n * webhooks) and the root RFC 8414 / RFC 9728 discovery aliases. Not `/api/v1/auth/*` (sign-in), not the resource API,\n * not `/internal/*`, not `/health*`: a dev stack signs in with known credentials and must not be reachable beyond the\n * protocol doors.\n */\nexport const TUNNEL_FORWARDED_API_PATHS: readonly string[] = [\n '^/api/v1/(a2a|mcp|oauth|\\\\.well-known|webhooks)(/|$)',\n '^/\\\\.well-known/',\n];\n\n/** One application's entry in the machine's tunnel. */\nexport interface TunnelApplicationRoute {\n readonly hostname: string;\n readonly backendPort: number;\n}\n\n/** A hostname the tunnel serves that is not an application: a test receiver. */\nexport interface TunnelExtraRoute {\n readonly hostname: string;\n /** `http://127.0.0.1:<port>`: always a local service. */\n readonly service: string;\n}\n\n/** What an application records while its public origin is the tunnel's. Machine-local, gitignored, throwaway. */\nexport interface ApplicationTunnelState {\n readonly schemaVersion: 1;\n readonly tunnelName: string;\n readonly hostname: string;\n /** `https://<hostname>`: the default frontend's `publicUrl` while the tunnel runs. */\n readonly publicOrigin: string;\n /** The frontend service whose `publicUrl` follows the tunnel: the one the backend resolves as its default. */\n readonly frontendServiceName: string;\n readonly backendPort: number;\n}\n\n/** The machine's one tunnel process and everything it serves. */\nexport interface MachineTunnelState {\n readonly schemaVersion: 1;\n readonly tunnelName: string;\n readonly pid: number | null;\n readonly configPath: string;\n readonly logPath: string;\n /** Keyed by application root. */\n readonly applications: Record<string, TunnelApplicationRoute>;\n readonly extras: readonly TunnelExtraRoute[];\n /**\n * The credentials file the tunnel was started with when it was GIVEN (`--credentials-file`), on a machine with no\n * Cloudflare login (#3907 item 3, the QA VM). A restart then reuses it instead of asking the account, which that\n * machine cannot do. Absent when the tunnel was found through this machine's login.\n */\n readonly givenCredentialsFile?: string;\n}\n\nexport const APPLICATION_TUNNEL_STATE_FILE = join('.wildo-saas', 'state', 'tunnel.json');\n\n/** `~/.wildo/tunnel`: the machine's tunnel files. Overridable for tests. */\nexport function machineTunnelDirectory(home: string = homedir()): string {\n return join(home, '.wildo', 'tunnel');\n}\n\nexport function applicationTunnelStatePath(appRoot: string): string {\n return join(appRoot, APPLICATION_TUNNEL_STATE_FILE);\n}\n\nfunction readJson<T>(path: string): T | null {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as T;\n } catch {\n return null;\n }\n}\n\nfunction writeJson(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n\nexport function readMachineTunnelState(directory: string = machineTunnelDirectory()): MachineTunnelState | null {\n return readJson<MachineTunnelState>(join(directory, 'state.json'));\n}\n\nexport function writeMachineTunnelState(state: MachineTunnelState, directory: string = machineTunnelDirectory()): void {\n writeJson(join(directory, 'state.json'), state);\n}\n\nexport function readApplicationTunnelState(appRoot: string): ApplicationTunnelState | null {\n return readJson<ApplicationTunnelState>(applicationTunnelStatePath(appRoot));\n}\n\nexport function writeApplicationTunnelState(appRoot: string, state: ApplicationTunnelState): void {\n writeJson(applicationTunnelStatePath(appRoot), state);\n}\n\nexport function removeApplicationTunnelState(appRoot: string): void {\n rmSync(applicationTunnelStatePath(appRoot), { force: true });\n}\n\n/**\n * Whether `pid` is the machine's tunnel: a live process this user owns that runs `cloudflared` with `configPath`.\n *\n * A pid alone is not enough (#3907 review F4): after a reboot it may name an unrelated process, which the command would\n * then signal and the env generation would believe is the tunnel. So the process's own command line must name both.\n */\nexport function processIsTunnel(pid: number | null | undefined, configPath: string): boolean {\n if (!pid || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n } catch {\n return false;\n }\n try {\n const command = execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' });\n return command.includes('cloudflared') && command.includes(configPath);\n } catch {\n return false;\n }\n}\n\n/**\n * The application's tunnel, only when it is in effect: its state exists, the machine's tunnel serves it, and the\n * recorded `cloudflared` process is alive. A state left behind by a crash or a reboot is IGNORED (and named by\n * `staleReason`), so the next env generation never advertises a dead issuer.\n */\nexport function readLiveApplicationTunnel(\n appRoot: string,\n directory: string = machineTunnelDirectory(),\n isTunnel: (pid: number | null | undefined, configPath: string) => boolean = processIsTunnel,\n): { readonly live: ApplicationTunnelState | null; readonly staleReason: string | null } {\n const state = readApplicationTunnelState(appRoot);\n if (!state) return { live: null, staleReason: null };\n const machine = readMachineTunnelState(directory);\n if (!machine || machine.applications[appRoot]?.hostname !== state.hostname) {\n return { live: null, staleReason: `the machine's tunnel does not serve ${state.hostname}` };\n }\n if (!isTunnel(machine.pid, machine.configPath)) {\n return { live: null, staleReason: `the tunnel process (pid ${machine.pid ?? 'none'}) is not running` };\n }\n return { live: state, staleReason: null };\n}\n\n/**\n * The `cloudflared` ingress for the machine's tunnel: per application, the forwarded API paths to its backend and a 404\n * for everything else on its hostname; then the extras; then a catch-all 404.\n *\n * spec-cite: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/local-management/configuration-file/\n * (fetched 2026-11-16): the ingress check shows \"the first rule that matches\", and \"Configuration files that contain\n * ingress rules must always include a catch-all rule that concludes the file.\"\n */\nexport function buildTunnelIngressYaml(input: {\n readonly tunnelName: string;\n readonly credentialsFile: string;\n readonly applications: readonly TunnelApplicationRoute[];\n readonly extras: readonly TunnelExtraRoute[];\n}): string {\n const lines = [\n `tunnel: ${input.tunnelName}`,\n `credentials-file: ${input.credentialsFile}`,\n 'ingress:',\n ];\n for (const application of input.applications) {\n for (const path of TUNNEL_FORWARDED_API_PATHS) {\n lines.push(` - hostname: ${application.hostname}`, ` path: ${JSON.stringify(path)}`, ` service: http://127.0.0.1:${application.backendPort}`);\n }\n lines.push(` - hostname: ${application.hostname}`, ' service: http_status:404');\n }\n for (const extra of input.extras) {\n lines.push(` - hostname: ${extra.hostname}`, ` service: ${extra.service}`);\n }\n lines.push(' - service: http_status:404', '');\n return lines.join('\\n');\n}\n\n/** The `cloudflared` operations the command needs, injectable for tests. */\nexport interface CloudflaredRunner {\n /** Run a `cloudflared` subcommand to completion; resolves its stdout, rejects with its stderr. */\n exec(args: readonly string[]): Promise<string>;\n /** Start `cloudflared` detached with its output in `logPath`; resolves the pid. */\n startDetached(args: readonly string[], logPath: string): number;\n /** Stop a process this command started. */\n stop(pid: number): void;\n}\n\nexport const systemCloudflaredRunner: CloudflaredRunner = {\n async exec(args) {\n const { stdout } = await promisify(execFile)('cloudflared', [...args], { maxBuffer: 8 * 1024 * 1024 });\n return stdout;\n },\n startDetached(args, logPath) {\n mkdirSync(dirname(logPath), { recursive: true });\n const out = openSync(logPath, 'a');\n const child = spawn('cloudflared', [...args], { detached: true, stdio: ['ignore', out, out] });\n child.unref();\n if (!child.pid) throw new Error('cloudflared did not start');\n return child.pid;\n },\n stop(pid) {\n try { process.kill(pid, 'SIGTERM'); } catch { /* already gone */ }\n },\n};\n\n/** `cloudflared tunnel list --output json`, read defensively: anything but an array is no tunnel. */\nasync function listTunnels(runner: CloudflaredRunner, tunnelName: string): Promise<Array<{ id?: string; name?: string }>> {\n const parsed = JSON.parse(await runner.exec(['tunnel', 'list', '--output', 'json', '--name', tunnelName])) as unknown;\n return Array.isArray(parsed) ? parsed as Array<{ id?: string; name?: string }> : [];\n}\n\n/** The named tunnel's id, creating the tunnel when this machine's `cert.pem` login has none by that name. */\nexport async function ensureNamedTunnel(runner: CloudflaredRunner, tunnelName: string): Promise<{ readonly id: string; readonly created: boolean }> {\n const existing = (await listTunnels(runner, tunnelName)).find((tunnel) => tunnel.name === tunnelName && tunnel.id);\n if (existing?.id) return { id: existing.id, created: false };\n await runner.exec(['tunnel', 'create', tunnelName]);\n const created = (await listTunnels(runner, tunnelName)).find((tunnel) => tunnel.name === tunnelName && tunnel.id);\n if (!created?.id) throw new Error(`cloudflared created no tunnel named ${tunnelName}`);\n return { id: created.id, created: true };\n}\n\n/**\n * Route `hostname` to the tunnel, or refuse.\n *\n * `cloudflared tunnel route dns` already SUCCEEDS when the record routes to this tunnel (\"is already configured to route\n * to your tunnel\"), so the idempotent case needs no handling. The error it raises for an existing record (\"An A, AAAA, or\n * CNAME record with that host already exists\") is the case where the hostname points ELSEWHERE — another tunnel, or a\n * record someone else made. That is never tolerated (#3907 review F1): the application would advertise an issuer, its\n * audiences and its agent card on a host another party serves, and outside clients would send their tokens there.\n */\nexport async function routeHostname(runner: CloudflaredRunner, tunnelName: string, hostname: string): Promise<void> {\n try {\n await runner.exec(['tunnel', 'route', 'dns', tunnelName, hostname]);\n } catch (error) {\n const message = describeCaughtError(error);\n const elsewhere = /already exists/i.test(message)\n ? ' A record that already exists points somewhere else; remove it or choose another hostname.'\n : '';\n throw new Error(`${hostname} could not be routed to the tunnel '${tunnelName}': ${message.trim()}.${elsewhere} Nothing was changed.`);\n }\n}\n\n/** Wait until `cloudflared` reports a registered connection in its log, or the process ends; `false` on timeout. */\nexport async function waitForTunnelConnection(\n logPath: string,\n pid: number,\n configPath: string,\n options: { timeoutMs?: number; isTunnel?: typeof processIsTunnel; readLog?: (path: string) => string; sleep?: (ms: number) => Promise<void> } = {},\n): Promise<boolean> {\n const isTunnel = options.isTunnel ?? processIsTunnel;\n const readLog = options.readLog ?? ((path: string) => { try { return readFileSync(path, 'utf8'); } catch { return ''; } });\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const startLength = readLog(logPath).length;\n const deadline = Date.now() + (options.timeoutMs ?? 30_000);\n while (Date.now() < deadline) {\n if (/Registered tunnel connection/.test(readLog(logPath).slice(startLength))) return true;\n if (!isTunnel(pid, configPath)) return false;\n await sleep(500);\n }\n return false;\n}\n\n/** Wait until a stopped `cloudflared` has exited, so two connectors with different ingress never overlap (review F12). */\nexport async function waitForTunnelExit(pid: number, configPath: string, options: { timeoutMs?: number; isTunnel?: typeof processIsTunnel; sleep?: (ms: number) => Promise<void> } = {}): Promise<boolean> {\n const isTunnel = options.isTunnel ?? processIsTunnel;\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const deadline = Date.now() + (options.timeoutMs ?? 40_000);\n while (Date.now() < deadline) {\n if (!isTunnel(pid, configPath)) return true;\n await sleep(500);\n }\n return !isTunnel(pid, configPath);\n}\n\n/** The credentials file `cloudflared tunnel create` wrote for a locally-managed tunnel. */\nexport function credentialsFileOf(tunnelId: string, home: string = homedir()): string {\n return join(home, '.cloudflared', `${tunnelId}.json`);\n}\n\n/** Whether `cloudflared` is installed and logged in (`cert.pem`), with what to do when it is not. */\n/**\n * The tunnel id a credentials file holds (`TunnelID`), read without ever returning or logging the secret beside it.\n * Refuses a file that is not one (#3907 item 3: the QA VM receives the file as a CI secret, so a malformed secret must\n * fail here, by name, rather than as a cloudflared connection that never registers).\n */\nexport function tunnelIdOfCredentialsFile(path: string): string {\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n throw new Error(`${path} is not a readable tunnel credentials file (JSON).`);\n }\n const id = (parsed as { TunnelID?: unknown } | null)?.TunnelID;\n if (typeof id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u.test(id)) {\n throw new Error(`${path} names no TunnelID: it is not a tunnel credentials file.`);\n }\n return id;\n}\n\nexport function cloudflaredReadiness(home: string = homedir()): string | null {\n return existsSync(join(home, '.cloudflared', 'cert.pem'))\n ? null\n : 'No Cloudflare login on this machine: run `cloudflared tunnel login` once (it writes ~/.cloudflared/cert.pem).';\n}\n\n/** A runtime endpoint as the env generation writes it (`RuntimeEndpointUrls` in `@wildo-ai/platform-core-shared`). */\ninterface WritableRuntimeEndpoint {\n publicUrl: string;\n internalUrl: string;\n additionalBrowserOrigins?: string[];\n}\n\n/**\n * The runtime endpoints with a live tunnel applied: ONLY the tunnel's frontend gets the public origin as its `publicUrl`,\n * and keeps the local listen origin as an additional browser origin, so the developer's own browser still passes every\n * origin check. Every other endpoint (the backend's included: the SPA builds its WebSocket URL from it) is unchanged.\n * Returns the input when there is no tunnel, or when its frontend has no endpoint (named in `skipped`).\n */\nexport function applyTunnelToRuntimeEndpoints<T extends Record<string, WritableRuntimeEndpoint>>(\n endpoints: T,\n tunnel: Pick<ApplicationTunnelState, 'publicOrigin' | 'frontendServiceName'> | null,\n): { readonly endpoints: T; readonly skipped: string | null } {\n if (!tunnel) return { endpoints, skipped: null };\n const local = endpoints[tunnel.frontendServiceName];\n if (!local) return { endpoints, skipped: `the tunnel names frontend '${tunnel.frontendServiceName}', which has no local endpoint` };\n const localOrigin = new URL(local.publicUrl).origin;\n return {\n endpoints: {\n ...endpoints,\n [tunnel.frontendServiceName]: {\n publicUrl: tunnel.publicOrigin,\n internalUrl: local.internalUrl,\n additionalBrowserOrigins: [...new Set([...(local.additionalBrowserOrigins ?? []), localOrigin])],\n },\n },\n skipped: null,\n };\n}\n"]}
|
|
@@ -47,6 +47,23 @@ export declare function readCompanionProviderAccountRefusal(error: unknown): Mod
|
|
|
47
47
|
*/
|
|
48
48
|
export declare const COMPANION_UNREACHABLE_EXIT_CODE = 2;
|
|
49
49
|
export declare function companionFailureExitCode(error: unknown): number;
|
|
50
|
+
/**
|
|
51
|
+
* The connection to the companion CLOSED before the request got its whole answer (#4021): undici's `fetch failed` with a
|
|
52
|
+
* `SocketError` cause (`UND_ERR_SOCKET`: "other side closed" before the head, "terminated" mid-body). The companion was
|
|
53
|
+
* reached and did not finish answering, so this is neither a refusal (it said nothing) nor an unreachable companion (it
|
|
54
|
+
* was there when the request went out).
|
|
55
|
+
*
|
|
56
|
+
* Reference run 44052185141 (its log carries no error cause; the shape is reproduced against undici 7.30.2): a companion
|
|
57
|
+
* that stops while it holds a request (a restart after a dependency install, with the drive's loop request parked at the
|
|
58
|
+
* restart window) closes its HTTP server, which waits for that request until its bounded 5000 ms step gives up, and exits;
|
|
59
|
+
* the held socket is then closed from the companion's side and the client sees exactly this. `wildo creation drive` read
|
|
60
|
+
* it as the loop's refusal and stopped, twice.
|
|
61
|
+
*
|
|
62
|
+
* Kept OUT of {@link companionFailureExitCode}'s unreachable set on purpose: a closed connection does not say the
|
|
63
|
+
* companion is down, only that it stopped answering THIS request. A caller that can ask the companion whether it
|
|
64
|
+
* restarted (the drive reads its process start time) decides; the others report it as the failure it is.
|
|
65
|
+
*/
|
|
66
|
+
export declare function isCompanionConnectionClosedBeforeAnswer(error: unknown): boolean;
|
|
50
67
|
/**
|
|
51
68
|
* The CLIENT gave up waiting — the companion may still be doing the work. Distinct from
|
|
52
69
|
* {@link CompanionRefusalError} (the companion answered no) and from an unreachable companion, because a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"companion-client.service.d.ts","sourceRoot":"","sources":["../../../../src/services/companion/companion-client.service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAYH,OAAO,EAAmF,KAAK,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AAC1J,OAAO,EAGL,2BAA2B,EAC5B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAyOlE;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;aAG5B,MAAM,EAAE,MAAM;IAC9B;;;OAGG;aACa,OAAO,CAAC,EAAE,oBAAoB;gBAN9C,OAAO,EAAE,MAAM,EACC,MAAM,EAAE,MAAM;IAC9B;;;OAGG;IACa,OAAO,CAAC,EAAE,oBAAoB;CAKjD;AAED,qDAAqD;AACrD,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC5C;AAmBD;;;;;;GAMG;AACH,wBAAgB,mCAAmC,CAAC,KAAK,EAAE,OAAO,GAAG,2BAA2B,GAAG,SAAS,CAK3G;AAED;;;;;;GAMG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AACjD,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAE/D;AAED;;;;;;GAMG;AACH,qBAAa,4BAA6B,SAAQ,KAAK;aAClB,SAAS,EAAE,MAAM;gBAAjB,SAAS,EAAE,MAAM;CAIrD;AAED,eAAO,MAAM,eAAe;kBAElB,MAAM,SACN,WAAW,YACP,sBAAsB,gBACnB,2BAA2B,GACvC,OAAO,CAAC,QAAQ,CAAC;QAaV,CAAC,QAAQ,MAAM,YAAY,sBAAsB,GAAG,OAAO,CAAC,CAAC,CAAC;SAM7D,CAAC,QACJ,MAAM,SACL,OAAO,YACJ,sBAAsB,gBACnB,2BAA2B,GACvC,OAAO,CAAC,CAAC,CAAC;IAeb,uCAAuC;mBAClB,sBAAsB,GAAG,OAAO,CAAC,OAAO,CAAC;CAS/D,CAAC"}
|
|
1
|
+
{"version":3,"file":"companion-client.service.d.ts","sourceRoot":"","sources":["../../../../src/services/companion/companion-client.service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG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B,2BAA2B,GACvC,OAAO,CAAC,CAAC,CAAC;IAeb,uCAAuC;mBAClB,sBAAsB,GAAG,OAAO,CAAC,OAAO,CAAC;CAS/D,CAAC"}
|
|
@@ -286,6 +286,27 @@ export const COMPANION_UNREACHABLE_EXIT_CODE = 2;
|
|
|
286
286
|
export function companionFailureExitCode(error) {
|
|
287
287
|
return isTransientConnectionError(error) || error instanceof CompanionTokenAbsentError ? COMPANION_UNREACHABLE_EXIT_CODE : 1;
|
|
288
288
|
}
|
|
289
|
+
/**
|
|
290
|
+
* The connection to the companion CLOSED before the request got its whole answer (#4021): undici's `fetch failed` with a
|
|
291
|
+
* `SocketError` cause (`UND_ERR_SOCKET`: "other side closed" before the head, "terminated" mid-body). The companion was
|
|
292
|
+
* reached and did not finish answering, so this is neither a refusal (it said nothing) nor an unreachable companion (it
|
|
293
|
+
* was there when the request went out).
|
|
294
|
+
*
|
|
295
|
+
* Reference run 44052185141 (its log carries no error cause; the shape is reproduced against undici 7.30.2): a companion
|
|
296
|
+
* that stops while it holds a request (a restart after a dependency install, with the drive's loop request parked at the
|
|
297
|
+
* restart window) closes its HTTP server, which waits for that request until its bounded 5000 ms step gives up, and exits;
|
|
298
|
+
* the held socket is then closed from the companion's side and the client sees exactly this. `wildo creation drive` read
|
|
299
|
+
* it as the loop's refusal and stopped, twice.
|
|
300
|
+
*
|
|
301
|
+
* Kept OUT of {@link companionFailureExitCode}'s unreachable set on purpose: a closed connection does not say the
|
|
302
|
+
* companion is down, only that it stopped answering THIS request. A caller that can ask the companion whether it
|
|
303
|
+
* restarted (the drive reads its process start time) decides; the others report it as the failure it is.
|
|
304
|
+
*/
|
|
305
|
+
export function isCompanionConnectionClosedBeforeAnswer(error) {
|
|
306
|
+
if (!(error instanceof Error))
|
|
307
|
+
return false;
|
|
308
|
+
return error.cause?.code === 'UND_ERR_SOCKET';
|
|
309
|
+
}
|
|
289
310
|
/**
|
|
290
311
|
* The CLIENT gave up waiting — the companion may still be doing the work. Distinct from
|
|
291
312
|
* {@link CompanionRefusalError} (the companion answered no) and from an unreachable companion, because a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"companion-client.service.js","sourceRoot":"","sources":["../../../../src/services/companion/companion-client.service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,gFAAgF;AAChF,gFAAgF;AAChF,iFAAiF;AACjF,gDAAgD;AAChD,wEAAwE;AACxE,6EAA6E;AAC7E,gFAAgF;AAChF,6EAA6E;AAC7E,6BAA6B;AAC7B,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,2BAA2B,EAAE,iCAAiC,EAAE,eAAe,EAAoC,MAAM,uBAAuB,CAAC;AAC1J,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAE9H;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,IAAI,iBAAoC,CAAC;AACzC,SAAS,mBAAmB;IAC1B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvB,iBAAiB,GAAG,IAAI,KAAK,CAAC;YAC5B,cAAc,EAAE,CAAC;YACjB,WAAW,EAAE,CAAC;YACd,gBAAgB,EAAE,EAAE,GAAG,MAAM;SAC9B,CAAC,CAAC;IACL,CAAC;IACD,OAAO,iBAAiB,CAAC;AAC3B,CAAC;AAED,SAAS,UAAU,CAAC,OAAgC;IAClD,MAAM,IAAI,GAAG,OAAO,EAAE,IAAI,IAAI,sBAAsB,CAAC;IACrD,OAAO,OAAO,EAAE,OAAO,IAAI,oBAAoB,IAAI,EAAE,CAAC;AACxD,CAAC;AAED,wEAAwE;AACxE,MAAM,yBAAyB,GAAG,CAAC,CAAC;AACpC,+EAA+E;AAC/E,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC;;;;;GAKG;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AC,EAAE,CAAC;QAChB,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,SAAS,kBAAkB,CAAC,IAAiB;IAC3C,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;IACpD,OAAO,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM;QAC1C,CAAC,CAAC,2BAA2B,CAAC,SAAS;QACvC,CAAC,CAAC,2BAA2B,CAAC,QAAQ,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * CompanionClientService — HTTP client for companion REST API.\n *\n * IMPLEMENTATION: DONE — get, post, ping, 10s timeout via AbortSignal.timeout.\n * Protocol (endpoints, payloads) TBD when companion service is defined.\n */\n\n// BOTH fetch and Agent must come from the SAME undici. Node's GLOBAL fetch is a\n// different undici (bundled 8.x on Node 26) whose dispatch-handler interface is\n// incompatible with this package's Agent (6.x) — passing our Agent as the global\n// fetch's `dispatcher` fails every request with\n// `InvalidArgumentError: invalid onError method (UND_ERR_INVALID_ARG)`.\n// That silently broke every long-running companion RPC (labels / translate /\n// email generation) when the toolchain moved to Node 26. Importing undici's own\n// fetch keeps the dispatcher/handler pair version-coherent regardless of the\n// Node-bundled undici major.\nimport { Agent, fetch } from 'undici';\nimport { ErrorCustomMessageReference, ModelProviderAccountRefusalSchema, WildoHeaderKeys, type ModelProviderAccountRefusal } from '@wildo-ai/saas-models';\nimport {\n COMPANION_DEFAULT_PORT,\n COMPANION_DEFAULT_TIMEOUT_MS,\n CompanionRequestRetryPolicy,\n} from './companion.schemas';\nimport type { CompanionClientOptions } from './companion.schemas';\nimport { COMPANION_TOKEN_HEADER, CompanionTokenAbsentError, readCompanionTokenNoFollow } from './companion-local-token.utils';\n\n/**\n * Lazily-built `undici.Agent` with long head/body timeouts for companion\n * RPCs. Required because Node's native `fetch` (undici under the hood)\n * defaults to `headersTimeout: 300_000` (5 min) — even if the caller\n * passes `AbortSignal.timeout(...)` with a longer ceiling, undici will\n * still give up at 5 min waiting for response headers.\n *\n * The companion's labelling, translation, and email generation endpoints\n * legitimately exceed 5 min (LLM batch jobs). The companion-side fix is\n * in `engine/saas-backend-lib` (`appConfiguration.runtime.httpServerConfiguration`);\n * this is the matching client-side fix. Both must move together — a\n * 30-min server-side `requestTimeout` is useless if the client gives up\n * at 5 min.\n *\n * Both dispatcher timeouts are OFF (0): each request's `AbortSignal.timeout(timeoutMs)`\n * is the one authority over how long the client waits. They were 31 minutes, \"slightly\n * above the 30-min companion server timeout\", and that cut every request whose own\n * deadline is longer: `wildo creation drive` holds a loop request for up to 6 hours, and\n * on reference run 42713670241 (#3204) every loop that took over 31 minutes ended in\n * `fetch failed` (`UND_ERR_HEADERS_TIMEOUT`), which the drive read as the loop's refusal\n * and stopped on five times. The companion's 30-minute `requestTimeout` bounds RECEIVING\n * a request, never the time to answer it, so it does not cut a long loop.\n */\nlet _longRunningAgent: Agent | undefined;\nfunction getLongRunningAgent(): Agent {\n if (!_longRunningAgent) {\n _longRunningAgent = new Agent({\n headersTimeout: 0,\n bodyTimeout: 0,\n keepAliveTimeout: 31 * 60_000,\n });\n }\n return _longRunningAgent;\n}\n\nfunction getBaseUrl(options?: CompanionClientOptions): string {\n const port = options?.port ?? COMPANION_DEFAULT_PORT;\n return options?.baseUrl ?? `http://localhost:${port}`;\n}\n\n/** Attempts (including the first) for transient connection failures. */\nconst CONNECTION_RETRY_ATTEMPTS = 4;\n/** Delay between connection-retry attempts (≈1.2s total across 4 attempts). */\nconst CONNECTION_RETRY_DELAY_MS = 400;\n\n/**\n * A transient connection failure — the companion is briefly unreachable, e.g.\n * mid-restart after a source edit (dev watcher → runtime-supervisor). undici's\n * `fetch` throws `TypeError: fetch failed` with the underlying error on `.cause`.\n * We retry ONLY these (never timeouts or HTTP status errors, which are real).\n */\nfunction isTransientConnectionError(err: unknown): boolean {\n if (!(err instanceof Error)) {\n return false;\n }\n const code = (err as { cause?: { code?: string } }).cause?.code;\n return code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ECONNABORTED' || code === 'EAI_AGAIN';\n}\n\n/**\n * undici gave up waiting for the head or the body (`fetch failed` with a timeout cause). The client stopped waiting, the\n * companion may still be working: a {@link CompanionRequestTimeoutError}, never a refusal of the request.\n */\nfunction isDispatcherTimeout(err: Error): boolean {\n const code = (err as { cause?: { code?: string } }).cause?.code;\n return code === 'UND_ERR_HEADERS_TIMEOUT' || code === 'UND_ERR_BODY_TIMEOUT';\n}\n\nasync function fetchWithTimeout(\n url: string,\n init: RequestInit & { timeoutMs?: number },\n options?: CompanionClientOptions,\n retryPolicy: CompanionRequestRetryPolicy = defaultRetryPolicy(init),\n): Promise<Response> {\n const timeoutMs = init.timeoutMs ?? options?.timeoutMs ?? COMPANION_DEFAULT_TIMEOUT_MS;\n const attempts = retryPolicy === CompanionRequestRetryPolicy.SAFE_READ ? CONNECTION_RETRY_ATTEMPTS : 1;\n\n let lastError: unknown;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n // Fresh signal per attempt — an aborted/consumed AbortSignal can't be reused.\n const signal = AbortSignal.timeout(timeoutMs);\n try {\n // The cast bridges the AMBIENT `RequestInit` this function's signature uses\n // (undici-types via @types/node) and the imported undici's own structurally\n // identical `RequestInit` — the two type packages declare nominal twins\n // (FormData/Blob) that TypeScript refuses to unify across module identities.\n // Runtime-coherent by construction: fetch, Agent and the init all come from\n // the same imported undici (see the import note at the top of this file).\n return await fetch(url, {\n ...init,\n signal,\n dispatcher: getLongRunningAgent(),\n } as unknown as Parameters<typeof fetch>[1]);\n } catch (err) {\n if (err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError' || isDispatcherTimeout(err))) {\n throw new CompanionRequestTimeoutError(timeoutMs);\n }\n lastError = err;\n // Retry a briefly-unreachable companion (mid-restart); fail fast otherwise.\n if (attempt < attempts && isTransientConnectionError(err)) {\n await new Promise((resolve) => setTimeout(resolve, CONNECTION_RETRY_DELAY_MS));\n continue;\n }\n throw err;\n }\n }\n throw lastError;\n}\n\n/**\n * Methods that need no companion token — the same set the companion's own floor lets through.\n *\n * Kept as the METHOD rather than as a list of mutating routes for the reason the server side gives at\n * `COMPANION_TOKEN_FLOOR_UNGATED_METHODS`: the two ends must agree, and a verb is the only\n * discriminator both can compute without maintaining a copy of the other's route table.\n */\nconst COMPANION_TOKEN_UNGATED_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);\n\n/**\n * Attach the machine-local companion token to a mutating request (P-29b).\n *\n * This is the CLIENT half of one invariant, and it lives HERE — at the single point every CLI\n * companion request funnels through — rather than at each of the eight call sites that build one.\n * Those call sites are four near-identical `resolveCompanionClientOptions` copies plus an inline\n * object literal in `charts-audit.command.ts`; a per-call-site attach would have been five hand-applied\n * copies of a rule, and the sixth would have been written without it.\n *\n * An explicitly-supplied token header WINS: `requestAuthorizedLocalCompanion` sets one, and a caller\n * that has gone to the trouble of naming a credential must not have it silently replaced.\n *\n * A failed read is raised, not swallowed. Sending the request without the token would trade a local\n * error that names the token file for a remote 401 that names the same file one hop further away —\n * and the local one can say WHY (the file is missing, or its mode is too broad), which the server\n * cannot know.\n *\n * **An ABSENT `appRoot` sends nothing and lets the companion refuse**, and that decision was\n * re-examined on 2026-09-10 rather than reversed. Raising locally instead was tried: it makes every\n * mutating call require an application root, which is true of the CLI's real callers and NOT of a\n * request whose only problem is a companion that has restarted — so the refusal has to be legible\n * wherever it comes from, not only in the one branch that can see it early. That is what\n * `describeCompanionFailure` below does, and it covers the stale-token case the local throw could\n * not. The branch is reachable: a `wildo` invocation with no targeted app resolves\n * `{ timeoutMs }` alone (`companion-client-options.utils.ts`).\n */\nasync function resolveCompanionTokenHeader(\n method: string,\n headers: Headers,\n options?: CompanionClientOptions,\n): Promise<void> {\n if (COMPANION_TOKEN_UNGATED_METHODS.has(method.toUpperCase())) return;\n if (options?.appRoot === undefined || headers.has(COMPANION_TOKEN_HEADER)) return;\n headers.set(COMPANION_TOKEN_HEADER, await readCompanionTokenNoFollow(options.appRoot));\n}\n\n/**\n * Turn a companion failure into a sentence that names the CAUSE, not only the status.\n *\n * A `401` from the companion carries `type: AUTHENTICATION`, a severity and a correlation id, and\n * NOTHING else — measured against the running companion on 2026-09-10. `sanitizeErrorForClient`\n * strips the explanatory context before it leaves the process, deliberately: a refusal must not teach\n * an unauthorized caller where the credential lives. The sentence that does explain is in the\n * COMPANION'S log, under the same correlation id.\n *\n * So `Companion API /api/companion/x: 401 Unauthorized` is all a CLI user would otherwise see, and it\n * reads as \"the thing I asked for failed\" rather than \"I sent no credential\" — the defect class this\n * whole change closed for three callers outside the CLI. The client is the one place that knows both\n * halves (which application it targeted, and whether it attached anything), so it is the one place\n * that can say which of the two happened.\n */\nfunction describeCompanionFailure(\n path: string,\n method: string,\n response: Response,\n options?: CompanionClientOptions,\n refusal?: string,\n): string {\n const base = refusal === undefined\n ? `Companion API ${path}: ${response.status} ${response.statusText}`\n : `Companion API ${path}: ${response.status} ${response.statusText} — ${refusal}`;\n if (response.status !== 401) return base;\n /*\n * The floor is VERB-discriminated, so this explanation has to be too — and the same set the attach\n * reads is the one that decides here, twenty lines apart in one file rather than two copies. A 401\n * on a READ is not a missing mutation credential: it comes from somewhere else entirely, and\n * telling the caller to check its companion token would send them to the wrong place.\n */\n if (COMPANION_TOKEN_UNGATED_METHODS.has(method.toUpperCase())) {\n return `${base} — this is a READ, which the companion's local-token floor does not gate, so the `\n + 'refusal is not about the machine-local token.';\n }\n return options?.appRoot === undefined\n ? `${base} — this route mutates and needs the machine-local companion token, and no targeted `\n + 'application was resolved, so none was sent. Run the command from inside a Wildo application.'\n : `${base} — the companion refused the token read from ${options.appRoot}/.wildo-saas/state/`\n + 'companion.token. It mints a fresh one on every boot, so this usually means it restarted; '\n + 'the companion\\'s own log carries the full refusal under the response\\'s correlation id.';\n}\n\n/**\n * The companion's own explanation of a refusal, when the body carries one.\n *\n * A refused REQUEST (a 4xx) answers with the reason the handler wrote — the engine's error envelope\n * allow-lists `message` in `details` for VALIDATION, CONFLICT and RATE_LIMIT. Without reading it, a\n * caller saw `400 Bad Request` and nothing else, and the refusal naming the fix (\"`get` takes `refs` OR\n * `aspectKeys`\") reached nobody (#1459, found on the first live `wildo context elements` run).\n *\n * Every OTHER type loses its `details` to the client sanitizer, so a refusal whose words matter (a 404\n * among them) carries them as `userGuidance` instead: when there is no `details.message`, read its\n * `explanation` and its `resolution`, joined when both are present (#1588). The raw text is right here — the CLI has no label tree to resolve\n * the guidance key against.\n *\n * Best-effort and non-throwing: an empty or non-JSON body simply yields no detail, and the status line\n * stands on its own as before.\n */\nasync function readRefusalDetail(response: Response): Promise<string | undefined> {\n try {\n const body = await response.clone().json() as {\n error?: { details?: { message?: unknown }; userGuidance?: { explanation?: unknown; resolution?: unknown } };\n };\n const text = (value: unknown): string | undefined => (typeof value === 'string' && value.trim().length > 0 ? value : undefined);\n const details = text(body?.error?.details?.message);\n if (details) return details;\n // Both halves when both are present: the resolution is the actionable one (#1588 review F4).\n const guidance = [text(body?.error?.userGuidance?.explanation), text(body?.error?.userGuidance?.resolution)].filter((part): part is string => part !== undefined);\n return guidance.length > 0 ? guidance.join(' ') : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The companion ANSWERED, with a non-2xx status (#1588): carries that status, so a caller can tell a\n * refusal from a companion that is not there without parsing the message.\n */\nexport class CompanionRefusalError extends Error {\n public constructor(\n message: string,\n public readonly status: number,\n /**\n * What the answer's body said, when it was the engine's error shape: its stable message reference (`error.customMessageReference`)\n * and the facts its reference admits (`error.details`). How a caller branches on WHY without parsing the message (#3204).\n */\n public readonly refusal?: CompanionRefusalBody,\n ) {\n super(message);\n this.name = 'CompanionRefusalError';\n }\n}\n\n/** The machine-readable half of a refusal's body. */\nexport interface CompanionRefusalBody {\n readonly reference?: string;\n readonly details?: Record<string, unknown>;\n}\n\n/** The reference and admitted details of a refusal's body, or `undefined` when the body is not the engine's error shape. */\nasync function readRefusalBody(response: Response): Promise<CompanionRefusalBody | undefined> {\n try {\n const body = await response.clone().json() as { error?: { customMessageReference?: unknown; details?: unknown } };\n const reference = typeof body?.error?.customMessageReference === 'string' ? body.error.customMessageReference : undefined;\n const details = body?.error?.details !== null && typeof body?.error?.details === 'object' && !Array.isArray(body.error.details)\n ? body.error.details as Record<string, unknown>\n : undefined;\n return reference === undefined && details === undefined ? undefined : { ...(reference !== undefined ? { reference } : {}), ...(details !== undefined ? { details } : {}) };\n } catch {\n return undefined;\n }\n}\n\n/** Who refused, when the answer named only WHY: the engine's wire carries the reason alone (least disclosure). */\nconst UNNAMED_PROVIDER = 'the companion\\'s model provider';\n\n/**\n * The model provider ACCOUNT's refusal a companion answer carried (#3204): the engine answers it `502` with the reference\n * `model_provider_account_refused` and only the classified `details.reason`, since the provider and its words are the\n * operator's billing state and that answer can reach an end user. So the refusal read here names the reason, and points\n * at the companion's log for the rest. (The creation loop's own interruption carries the whole refusal.) `undefined` for\n * any other failure.\n */\nexport function readCompanionProviderAccountRefusal(error: unknown): ModelProviderAccountRefusal | undefined {\n if (!(error instanceof CompanionRefusalError) || error.refusal?.reference !== ErrorCustomMessageReference.MODEL_PROVIDER_ACCOUNT_REFUSED) return undefined;\n const reason = ModelProviderAccountRefusalSchema.shape.reason.safeParse(error.refusal.details?.reason);\n if (!reason.success) return undefined;\n return { reason: reason.data, provider: UNNAMED_PROVIDER, providerMessage: 'the companion\\'s log names the provider and quotes its answer' };\n}\n\n/**\n * The creation console's exit code for a failed companion call (#1652): 2 when the companion could not\n * be REACHED (nothing listening, connection reset, or a companion that never started here and so\n * left no token), 1 for everything else — a refusal it answered, a\n * timeout, a malformed request. The distinction is the one an agent branches on: \"fix what you sent\"\n * versus \"start the stack\", and it must not be recovered by parsing an error message.\n */\nexport const COMPANION_UNREACHABLE_EXIT_CODE = 2;\nexport function companionFailureExitCode(error: unknown): number {\n return isTransientConnectionError(error) || error instanceof CompanionTokenAbsentError ? COMPANION_UNREACHABLE_EXIT_CODE : 1;\n}\n\n/**\n * The CLIENT gave up waiting — the companion may still be doing the work. Distinct from\n * {@link CompanionRefusalError} (the companion answered no) and from an unreachable companion, because a\n * caller whose request STARTS work must not report a timeout as a failure: `wildo creation answer` on a\n * playbook round is refused fast when the answer is wrong and otherwise holds the request open for the\n * whole continuation, so a timeout there means the answer was admitted and the run is still going.\n */\nexport class CompanionRequestTimeoutError extends Error {\n public constructor(public readonly timeoutMs: number) {\n super(`Companion API request timed out after ${timeoutMs}ms`);\n this.name = 'CompanionRequestTimeoutError';\n }\n}\n\nexport const CompanionClient = {\n async request(\n path: string,\n init: RequestInit = {},\n options?: CompanionClientOptions,\n retryPolicy: CompanionRequestRetryPolicy = defaultRetryPolicy(init),\n ): Promise<Response> {\n const base = getBaseUrl(options);\n const headers = new Headers(options?.headers);\n new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n await resolveCompanionTokenHeader(init.method ?? 'GET', headers, options);\n return fetchWithTimeout(\n `${base}${path.startsWith('/') ? path : `/${path}`}`,\n { ...init, headers },\n options,\n retryPolicy,\n );\n },\n\n async get<T>(path: string, options?: CompanionClientOptions): Promise<T> {\n const res = await CompanionClient.request(path, {}, options, CompanionRequestRetryPolicy.SAFE_READ);\n if (!res.ok) throw new CompanionRefusalError(describeCompanionFailure(path, 'GET', res, options, await readRefusalDetail(res)), res.status, await readRefusalBody(res));\n return res.json() as Promise<T>;\n },\n\n async post<T>(\n path: string,\n body?: unknown,\n options?: CompanionClientOptions,\n retryPolicy: CompanionRequestRetryPolicy = CompanionRequestRetryPolicy.NO_RETRY,\n ): Promise<T> {\n const res = await CompanionClient.request(\n path,\n {\n method: 'POST',\n headers: { [WildoHeaderKeys.CONTENT_TYPE]: 'application/json' },\n body: body ? JSON.stringify(body) : undefined,\n },\n options,\n retryPolicy,\n );\n if (!res.ok) throw new CompanionRefusalError(describeCompanionFailure(path, 'POST', res, options, await readRefusalDetail(res)), res.status, await readRefusalBody(res));\n return res.json() as Promise<T>;\n },\n\n /** Check if companion is reachable. */\n async ping(options?: CompanionClientOptions): Promise<boolean> {\n try {\n const base = getBaseUrl(options);\n const res = await fetchWithTimeout(`${base}/health`, { method: 'GET' }, options, CompanionRequestRetryPolicy.SAFE_READ);\n return res.ok;\n } catch {\n return false;\n }\n },\n};\n\n/**\n * Reads and heads are safe by their transport semantics. Every other method\n * starts no-retry unless a caller declares a stronger semantic contract.\n */\nfunction defaultRetryPolicy(init: RequestInit): CompanionRequestRetryPolicy {\n const method = (init.method ?? 'GET').toUpperCase();\n return method === 'GET' || method === 'HEAD'\n ? CompanionRequestRetryPolicy.SAFE_READ\n : CompanionRequestRetryPolicy.NO_RETRY;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"companion-client.service.js","sourceRoot":"","sources":["../../../../src/services/companion/companion-client.service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,gFAAgF;AAChF,gFAAgF;AAChF,iFAAiF;AACjF,gDAAgD;AAChD,wEAAwE;AACxE,6EAA6E;AAC7E,gFAAgF;AAChF,6EAA6E;AAC7E,6BAA6B;AAC7B,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,2BAA2B,EAAE,iCAAiC,EAAE,eAAe,EAAoC,MAAM,uBAAuB,CAAC;AAC1J,OAAO,EACL,sBAAsB,EACtB,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAE9H;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,IAAI,iBAAoC,CAAC;AACzC,SAAS,mBAAmB;IAC1B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvB,iBAAiB,GAAG,IAAI,KAAK,CAAC;YAC5B,cAAc,EAAE,CAAC;YACjB,WAAW,EAAE,CAAC;YACd,gBAAgB,EAAE,EAAE,GAAG,MAAM;SAC9B,C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G,CAAC,EAAE;YAAE,MAAM,IAAI,qBAAqB,CAAC,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;QACzK,OAAO,GAAG,CAAC,IAAI,EAAgB,CAAC;IAClC,CAAC;IAED,uCAAuC;IACvC,KAAK,CAAC,IAAI,CAAC,OAAgC;QACzC,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC;YACjC,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,GAAG,IAAI,SAAS,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,2BAA2B,CAAC,SAAS,CAAC,CAAC;YACxH,OAAO,GAAG,CAAC,EAAE,CAAC;QAChB,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,SAAS,kBAAkB,CAAC,IAAiB;IAC3C,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;IACpD,OAAO,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM;QAC1C,CAAC,CAAC,2BAA2B,CAAC,SAAS;QACvC,CAAC,CAAC,2BAA2B,CAAC,QAAQ,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * CompanionClientService — HTTP client for companion REST API.\n *\n * IMPLEMENTATION: DONE — get, post, ping, 10s timeout via AbortSignal.timeout.\n * Protocol (endpoints, payloads) TBD when companion service is defined.\n */\n\n// BOTH fetch and Agent must come from the SAME undici. Node's GLOBAL fetch is a\n// different undici (bundled 8.x on Node 26) whose dispatch-handler interface is\n// incompatible with this package's Agent (6.x) — passing our Agent as the global\n// fetch's `dispatcher` fails every request with\n// `InvalidArgumentError: invalid onError method (UND_ERR_INVALID_ARG)`.\n// That silently broke every long-running companion RPC (labels / translate /\n// email generation) when the toolchain moved to Node 26. Importing undici's own\n// fetch keeps the dispatcher/handler pair version-coherent regardless of the\n// Node-bundled undici major.\nimport { Agent, fetch } from 'undici';\nimport { ErrorCustomMessageReference, ModelProviderAccountRefusalSchema, WildoHeaderKeys, type ModelProviderAccountRefusal } from '@wildo-ai/saas-models';\nimport {\n COMPANION_DEFAULT_PORT,\n COMPANION_DEFAULT_TIMEOUT_MS,\n CompanionRequestRetryPolicy,\n} from './companion.schemas';\nimport type { CompanionClientOptions } from './companion.schemas';\nimport { COMPANION_TOKEN_HEADER, CompanionTokenAbsentError, readCompanionTokenNoFollow } from './companion-local-token.utils';\n\n/**\n * Lazily-built `undici.Agent` with long head/body timeouts for companion\n * RPCs. Required because Node's native `fetch` (undici under the hood)\n * defaults to `headersTimeout: 300_000` (5 min) — even if the caller\n * passes `AbortSignal.timeout(...)` with a longer ceiling, undici will\n * still give up at 5 min waiting for response headers.\n *\n * The companion's labelling, translation, and email generation endpoints\n * legitimately exceed 5 min (LLM batch jobs). The companion-side fix is\n * in `engine/saas-backend-lib` (`appConfiguration.runtime.httpServerConfiguration`);\n * this is the matching client-side fix. Both must move together — a\n * 30-min server-side `requestTimeout` is useless if the client gives up\n * at 5 min.\n *\n * Both dispatcher timeouts are OFF (0): each request's `AbortSignal.timeout(timeoutMs)`\n * is the one authority over how long the client waits. They were 31 minutes, \"slightly\n * above the 30-min companion server timeout\", and that cut every request whose own\n * deadline is longer: `wildo creation drive` holds a loop request for up to 6 hours, and\n * on reference run 42713670241 (#3204) every loop that took over 31 minutes ended in\n * `fetch failed` (`UND_ERR_HEADERS_TIMEOUT`), which the drive read as the loop's refusal\n * and stopped on five times. The companion's 30-minute `requestTimeout` bounds RECEIVING\n * a request, never the time to answer it, so it does not cut a long loop.\n */\nlet _longRunningAgent: Agent | undefined;\nfunction getLongRunningAgent(): Agent {\n if (!_longRunningAgent) {\n _longRunningAgent = new Agent({\n headersTimeout: 0,\n bodyTimeout: 0,\n keepAliveTimeout: 31 * 60_000,\n });\n }\n return _longRunningAgent;\n}\n\nfunction getBaseUrl(options?: CompanionClientOptions): string {\n const port = options?.port ?? COMPANION_DEFAULT_PORT;\n return options?.baseUrl ?? `http://localhost:${port}`;\n}\n\n/** Attempts (including the first) for transient connection failures. */\nconst CONNECTION_RETRY_ATTEMPTS = 4;\n/** Delay between connection-retry attempts (≈1.2s total across 4 attempts). */\nconst CONNECTION_RETRY_DELAY_MS = 400;\n\n/**\n * A transient connection failure — the companion is briefly unreachable, e.g.\n * mid-restart after a source edit (dev watcher → runtime-supervisor). undici's\n * `fetch` throws `TypeError: fetch failed` with the underlying error on `.cause`.\n * We retry ONLY these (never timeouts or HTTP status errors, which are real).\n */\nfunction isTransientConnectionError(err: unknown): boolean {\n if (!(err instanceof Error)) {\n return false;\n }\n const code = (err as { cause?: { code?: string } }).cause?.code;\n return code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ECONNABORTED' || code === 'EAI_AGAIN';\n}\n\n/**\n * undici gave up waiting for the head or the body (`fetch failed` with a timeout cause). The client stopped waiting, the\n * companion may still be working: a {@link CompanionRequestTimeoutError}, never a refusal of the request.\n */\nfunction isDispatcherTimeout(err: Error): boolean {\n const code = (err as { cause?: { code?: string } }).cause?.code;\n return code === 'UND_ERR_HEADERS_TIMEOUT' || code === 'UND_ERR_BODY_TIMEOUT';\n}\n\nasync function fetchWithTimeout(\n url: string,\n init: RequestInit & { timeoutMs?: number },\n options?: CompanionClientOptions,\n retryPolicy: CompanionRequestRetryPolicy = defaultRetryPolicy(init),\n): Promise<Response> {\n const timeoutMs = init.timeoutMs ?? options?.timeoutMs ?? COMPANION_DEFAULT_TIMEOUT_MS;\n const attempts = retryPolicy === CompanionRequestRetryPolicy.SAFE_READ ? CONNECTION_RETRY_ATTEMPTS : 1;\n\n let lastError: unknown;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n // Fresh signal per attempt — an aborted/consumed AbortSignal can't be reused.\n const signal = AbortSignal.timeout(timeoutMs);\n try {\n // The cast bridges the AMBIENT `RequestInit` this function's signature uses\n // (undici-types via @types/node) and the imported undici's own structurally\n // identical `RequestInit` — the two type packages declare nominal twins\n // (FormData/Blob) that TypeScript refuses to unify across module identities.\n // Runtime-coherent by construction: fetch, Agent and the init all come from\n // the same imported undici (see the import note at the top of this file).\n return await fetch(url, {\n ...init,\n signal,\n dispatcher: getLongRunningAgent(),\n } as unknown as Parameters<typeof fetch>[1]);\n } catch (err) {\n if (err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError' || isDispatcherTimeout(err))) {\n throw new CompanionRequestTimeoutError(timeoutMs);\n }\n lastError = err;\n // Retry a briefly-unreachable companion (mid-restart); fail fast otherwise.\n if (attempt < attempts && isTransientConnectionError(err)) {\n await new Promise((resolve) => setTimeout(resolve, CONNECTION_RETRY_DELAY_MS));\n continue;\n }\n throw err;\n }\n }\n throw lastError;\n}\n\n/**\n * Methods that need no companion token — the same set the companion's own floor lets through.\n *\n * Kept as the METHOD rather than as a list of mutating routes for the reason the server side gives at\n * `COMPANION_TOKEN_FLOOR_UNGATED_METHODS`: the two ends must agree, and a verb is the only\n * discriminator both can compute without maintaining a copy of the other's route table.\n */\nconst COMPANION_TOKEN_UNGATED_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);\n\n/**\n * Attach the machine-local companion token to a mutating request (P-29b).\n *\n * This is the CLIENT half of one invariant, and it lives HERE — at the single point every CLI\n * companion request funnels through — rather than at each of the eight call sites that build one.\n * Those call sites are four near-identical `resolveCompanionClientOptions` copies plus an inline\n * object literal in `charts-audit.command.ts`; a per-call-site attach would have been five hand-applied\n * copies of a rule, and the sixth would have been written without it.\n *\n * An explicitly-supplied token header WINS: `requestAuthorizedLocalCompanion` sets one, and a caller\n * that has gone to the trouble of naming a credential must not have it silently replaced.\n *\n * A failed read is raised, not swallowed. Sending the request without the token would trade a local\n * error that names the token file for a remote 401 that names the same file one hop further away —\n * and the local one can say WHY (the file is missing, or its mode is too broad), which the server\n * cannot know.\n *\n * **An ABSENT `appRoot` sends nothing and lets the companion refuse**, and that decision was\n * re-examined on 2026-09-10 rather than reversed. Raising locally instead was tried: it makes every\n * mutating call require an application root, which is true of the CLI's real callers and NOT of a\n * request whose only problem is a companion that has restarted — so the refusal has to be legible\n * wherever it comes from, not only in the one branch that can see it early. That is what\n * `describeCompanionFailure` below does, and it covers the stale-token case the local throw could\n * not. The branch is reachable: a `wildo` invocation with no targeted app resolves\n * `{ timeoutMs }` alone (`companion-client-options.utils.ts`).\n */\nasync function resolveCompanionTokenHeader(\n method: string,\n headers: Headers,\n options?: CompanionClientOptions,\n): Promise<void> {\n if (COMPANION_TOKEN_UNGATED_METHODS.has(method.toUpperCase())) return;\n if (options?.appRoot === undefined || headers.has(COMPANION_TOKEN_HEADER)) return;\n headers.set(COMPANION_TOKEN_HEADER, await readCompanionTokenNoFollow(options.appRoot));\n}\n\n/**\n * Turn a companion failure into a sentence that names the CAUSE, not only the status.\n *\n * A `401` from the companion carries `type: AUTHENTICATION`, a severity and a correlation id, and\n * NOTHING else — measured against the running companion on 2026-09-10. `sanitizeErrorForClient`\n * strips the explanatory context before it leaves the process, deliberately: a refusal must not teach\n * an unauthorized caller where the credential lives. The sentence that does explain is in the\n * COMPANION'S log, under the same correlation id.\n *\n * So `Companion API /api/companion/x: 401 Unauthorized` is all a CLI user would otherwise see, and it\n * reads as \"the thing I asked for failed\" rather than \"I sent no credential\" — the defect class this\n * whole change closed for three callers outside the CLI. The client is the one place that knows both\n * halves (which application it targeted, and whether it attached anything), so it is the one place\n * that can say which of the two happened.\n */\nfunction describeCompanionFailure(\n path: string,\n method: string,\n response: Response,\n options?: CompanionClientOptions,\n refusal?: string,\n): string {\n const base = refusal === undefined\n ? `Companion API ${path}: ${response.status} ${response.statusText}`\n : `Companion API ${path}: ${response.status} ${response.statusText} — ${refusal}`;\n if (response.status !== 401) return base;\n /*\n * The floor is VERB-discriminated, so this explanation has to be too — and the same set the attach\n * reads is the one that decides here, twenty lines apart in one file rather than two copies. A 401\n * on a READ is not a missing mutation credential: it comes from somewhere else entirely, and\n * telling the caller to check its companion token would send them to the wrong place.\n */\n if (COMPANION_TOKEN_UNGATED_METHODS.has(method.toUpperCase())) {\n return `${base} — this is a READ, which the companion's local-token floor does not gate, so the `\n + 'refusal is not about the machine-local token.';\n }\n return options?.appRoot === undefined\n ? `${base} — this route mutates and needs the machine-local companion token, and no targeted `\n + 'application was resolved, so none was sent. Run the command from inside a Wildo application.'\n : `${base} — the companion refused the token read from ${options.appRoot}/.wildo-saas/state/`\n + 'companion.token. It mints a fresh one on every boot, so this usually means it restarted; '\n + 'the companion\\'s own log carries the full refusal under the response\\'s correlation id.';\n}\n\n/**\n * The companion's own explanation of a refusal, when the body carries one.\n *\n * A refused REQUEST (a 4xx) answers with the reason the handler wrote — the engine's error envelope\n * allow-lists `message` in `details` for VALIDATION, CONFLICT and RATE_LIMIT. Without reading it, a\n * caller saw `400 Bad Request` and nothing else, and the refusal naming the fix (\"`get` takes `refs` OR\n * `aspectKeys`\") reached nobody (#1459, found on the first live `wildo context elements` run).\n *\n * Every OTHER type loses its `details` to the client sanitizer, so a refusal whose words matter (a 404\n * among them) carries them as `userGuidance` instead: when there is no `details.message`, read its\n * `explanation` and its `resolution`, joined when both are present (#1588). The raw text is right here — the CLI has no label tree to resolve\n * the guidance key against.\n *\n * Best-effort and non-throwing: an empty or non-JSON body simply yields no detail, and the status line\n * stands on its own as before.\n */\nasync function readRefusalDetail(response: Response): Promise<string | undefined> {\n try {\n const body = await response.clone().json() as {\n error?: { details?: { message?: unknown }; userGuidance?: { explanation?: unknown; resolution?: unknown } };\n };\n const text = (value: unknown): string | undefined => (typeof value === 'string' && value.trim().length > 0 ? value : undefined);\n const details = text(body?.error?.details?.message);\n if (details) return details;\n // Both halves when both are present: the resolution is the actionable one (#1588 review F4).\n const guidance = [text(body?.error?.userGuidance?.explanation), text(body?.error?.userGuidance?.resolution)].filter((part): part is string => part !== undefined);\n return guidance.length > 0 ? guidance.join(' ') : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The companion ANSWERED, with a non-2xx status (#1588): carries that status, so a caller can tell a\n * refusal from a companion that is not there without parsing the message.\n */\nexport class CompanionRefusalError extends Error {\n public constructor(\n message: string,\n public readonly status: number,\n /**\n * What the answer's body said, when it was the engine's error shape: its stable message reference (`error.customMessageReference`)\n * and the facts its reference admits (`error.details`). How a caller branches on WHY without parsing the message (#3204).\n */\n public readonly refusal?: CompanionRefusalBody,\n ) {\n super(message);\n this.name = 'CompanionRefusalError';\n }\n}\n\n/** The machine-readable half of a refusal's body. */\nexport interface CompanionRefusalBody {\n readonly reference?: string;\n readonly details?: Record<string, unknown>;\n}\n\n/** The reference and admitted details of a refusal's body, or `undefined` when the body is not the engine's error shape. */\nasync function readRefusalBody(response: Response): Promise<CompanionRefusalBody | undefined> {\n try {\n const body = await response.clone().json() as { error?: { customMessageReference?: unknown; details?: unknown } };\n const reference = typeof body?.error?.customMessageReference === 'string' ? body.error.customMessageReference : undefined;\n const details = body?.error?.details !== null && typeof body?.error?.details === 'object' && !Array.isArray(body.error.details)\n ? body.error.details as Record<string, unknown>\n : undefined;\n return reference === undefined && details === undefined ? undefined : { ...(reference !== undefined ? { reference } : {}), ...(details !== undefined ? { details } : {}) };\n } catch {\n return undefined;\n }\n}\n\n/** Who refused, when the answer named only WHY: the engine's wire carries the reason alone (least disclosure). */\nconst UNNAMED_PROVIDER = 'the companion\\'s model provider';\n\n/**\n * The model provider ACCOUNT's refusal a companion answer carried (#3204): the engine answers it `502` with the reference\n * `model_provider_account_refused` and only the classified `details.reason`, since the provider and its words are the\n * operator's billing state and that answer can reach an end user. So the refusal read here names the reason, and points\n * at the companion's log for the rest. (The creation loop's own interruption carries the whole refusal.) `undefined` for\n * any other failure.\n */\nexport function readCompanionProviderAccountRefusal(error: unknown): ModelProviderAccountRefusal | undefined {\n if (!(error instanceof CompanionRefusalError) || error.refusal?.reference !== ErrorCustomMessageReference.MODEL_PROVIDER_ACCOUNT_REFUSED) return undefined;\n const reason = ModelProviderAccountRefusalSchema.shape.reason.safeParse(error.refusal.details?.reason);\n if (!reason.success) return undefined;\n return { reason: reason.data, provider: UNNAMED_PROVIDER, providerMessage: 'the companion\\'s log names the provider and quotes its answer' };\n}\n\n/**\n * The creation console's exit code for a failed companion call (#1652): 2 when the companion could not\n * be REACHED (nothing listening, connection reset, or a companion that never started here and so\n * left no token), 1 for everything else — a refusal it answered, a\n * timeout, a malformed request. The distinction is the one an agent branches on: \"fix what you sent\"\n * versus \"start the stack\", and it must not be recovered by parsing an error message.\n */\nexport const COMPANION_UNREACHABLE_EXIT_CODE = 2;\nexport function companionFailureExitCode(error: unknown): number {\n return isTransientConnectionError(error) || error instanceof CompanionTokenAbsentError ? COMPANION_UNREACHABLE_EXIT_CODE : 1;\n}\n\n/**\n * The connection to the companion CLOSED before the request got its whole answer (#4021): undici's `fetch failed` with a\n * `SocketError` cause (`UND_ERR_SOCKET`: \"other side closed\" before the head, \"terminated\" mid-body). The companion was\n * reached and did not finish answering, so this is neither a refusal (it said nothing) nor an unreachable companion (it\n * was there when the request went out).\n *\n * Reference run 44052185141 (its log carries no error cause; the shape is reproduced against undici 7.30.2): a companion\n * that stops while it holds a request (a restart after a dependency install, with the drive's loop request parked at the\n * restart window) closes its HTTP server, which waits for that request until its bounded 5000 ms step gives up, and exits;\n * the held socket is then closed from the companion's side and the client sees exactly this. `wildo creation drive` read\n * it as the loop's refusal and stopped, twice.\n *\n * Kept OUT of {@link companionFailureExitCode}'s unreachable set on purpose: a closed connection does not say the\n * companion is down, only that it stopped answering THIS request. A caller that can ask the companion whether it\n * restarted (the drive reads its process start time) decides; the others report it as the failure it is.\n */\nexport function isCompanionConnectionClosedBeforeAnswer(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n return (error as { cause?: { code?: string } }).cause?.code === 'UND_ERR_SOCKET';\n}\n\n/**\n * The CLIENT gave up waiting — the companion may still be doing the work. Distinct from\n * {@link CompanionRefusalError} (the companion answered no) and from an unreachable companion, because a\n * caller whose request STARTS work must not report a timeout as a failure: `wildo creation answer` on a\n * playbook round is refused fast when the answer is wrong and otherwise holds the request open for the\n * whole continuation, so a timeout there means the answer was admitted and the run is still going.\n */\nexport class CompanionRequestTimeoutError extends Error {\n public constructor(public readonly timeoutMs: number) {\n super(`Companion API request timed out after ${timeoutMs}ms`);\n this.name = 'CompanionRequestTimeoutError';\n }\n}\n\nexport const CompanionClient = {\n async request(\n path: string,\n init: RequestInit = {},\n options?: CompanionClientOptions,\n retryPolicy: CompanionRequestRetryPolicy = defaultRetryPolicy(init),\n ): Promise<Response> {\n const base = getBaseUrl(options);\n const headers = new Headers(options?.headers);\n new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n await resolveCompanionTokenHeader(init.method ?? 'GET', headers, options);\n return fetchWithTimeout(\n `${base}${path.startsWith('/') ? path : `/${path}`}`,\n { ...init, headers },\n options,\n retryPolicy,\n );\n },\n\n async get<T>(path: string, options?: CompanionClientOptions): Promise<T> {\n const res = await CompanionClient.request(path, {}, options, CompanionRequestRetryPolicy.SAFE_READ);\n if (!res.ok) throw new CompanionRefusalError(describeCompanionFailure(path, 'GET', res, options, await readRefusalDetail(res)), res.status, await readRefusalBody(res));\n return res.json() as Promise<T>;\n },\n\n async post<T>(\n path: string,\n body?: unknown,\n options?: CompanionClientOptions,\n retryPolicy: CompanionRequestRetryPolicy = CompanionRequestRetryPolicy.NO_RETRY,\n ): Promise<T> {\n const res = await CompanionClient.request(\n path,\n {\n method: 'POST',\n headers: { [WildoHeaderKeys.CONTENT_TYPE]: 'application/json' },\n body: body ? JSON.stringify(body) : undefined,\n },\n options,\n retryPolicy,\n );\n if (!res.ok) throw new CompanionRefusalError(describeCompanionFailure(path, 'POST', res, options, await readRefusalDetail(res)), res.status, await readRefusalBody(res));\n return res.json() as Promise<T>;\n },\n\n /** Check if companion is reachable. */\n async ping(options?: CompanionClientOptions): Promise<boolean> {\n try {\n const base = getBaseUrl(options);\n const res = await fetchWithTimeout(`${base}/health`, { method: 'GET' }, options, CompanionRequestRetryPolicy.SAFE_READ);\n return res.ok;\n } catch {\n return false;\n }\n },\n};\n\n/**\n * Reads and heads are safe by their transport semantics. Every other method\n * starts no-retry unless a caller declares a stronger semantic contract.\n */\nfunction defaultRetryPolicy(init: RequestInit): CompanionRequestRetryPolicy {\n const method = (init.method ?? 'GET').toUpperCase();\n return method === 'GET' || method === 'HEAD'\n ? CompanionRequestRetryPolicy.SAFE_READ\n : CompanionRequestRetryPolicy.NO_RETRY;\n}\n"]}
|
|
@@ -32,6 +32,12 @@
|
|
|
32
32
|
* the working tree; the run records survive). The restart itself is on the intervention ledger when the companion
|
|
33
33
|
* booted with runs in flight (#2231), and the driver also counts the restarts it saw, from the companion's start time.
|
|
34
34
|
*
|
|
35
|
+
* A restart reaches the driver in one of two shapes: nothing listens (connection refused), or the companion stopped while
|
|
36
|
+
* it HELD the loop request, which the client sees as the connection closing before any answer (`UND_ERR_SOCKET`; #4021,
|
|
37
|
+
* reference run 44052185141, where a dependency install's restart stopped the drive `loop-refused` twice). The second is
|
|
38
|
+
* never read as a restart on its own: the next status the companion answers settles it by its process start time, a new
|
|
39
|
+
* one resuming the drive and the same one stopping it {@link CreationDriveStopRule.LOOP_CONNECTION_LOST}.
|
|
40
|
+
*
|
|
35
41
|
* ## Holds it respects
|
|
36
42
|
*
|
|
37
43
|
* - a person's `wildo build stop` (#3206) is a STOP: a stopped build is never resumed unattended;
|
|
@@ -86,6 +92,13 @@ export declare enum CreationDriveStopRule {
|
|
|
86
92
|
LANES_FAILED = "lanes-failed",
|
|
87
93
|
/** The companion refused to run the loop (a preflight failure, a refusal whose remedy is a decision). */
|
|
88
94
|
LOOP_REFUSED = "loop-refused",
|
|
95
|
+
/**
|
|
96
|
+
* The connection closed before the companion answered the loop, and the companion did NOT restart (#4021): the same
|
|
97
|
+
* process, by its start time, answered the next read. Not a refusal (it said nothing) and not a restart (which the drive
|
|
98
|
+
* waits through), so something between the drive and the companion cut the request. The loop may still run there:
|
|
99
|
+
* `wildo creation pulse` shows it; run the drive again, which waits for it before choosing.
|
|
100
|
+
*/
|
|
101
|
+
LOOP_CONNECTION_LOST = "loop-connection-lost",
|
|
89
102
|
/** The autonomy posture leaves acceptance to a person: a marked critical gate is armed. */
|
|
90
103
|
ACCEPTANCE_HELD_FOR_PERSON = "acceptance-held-for-person",
|
|
91
104
|
/** The creation preflight found what would stop the run, before the first round. */
|
|
@@ -222,6 +235,11 @@ export interface CreationDrivePort {
|
|
|
222
235
|
readonly isClientTimeout: (error: unknown) => boolean;
|
|
223
236
|
/** The companion answered "not now" (503: a derivation still in progress, as after a restart). A wait, never an error. */
|
|
224
237
|
readonly isNotReadyYet: (error: unknown) => boolean;
|
|
238
|
+
/**
|
|
239
|
+
* The connection closed while the request waited for the companion's answer (#4021): it was reached and said nothing.
|
|
240
|
+
* What a companion that stops while it holds a request leaves behind; whether it RESTARTED is the status's start time.
|
|
241
|
+
*/
|
|
242
|
+
readonly isConnectionClosedBeforeAnswer: (error: unknown) => boolean;
|
|
225
243
|
/** The companion refused because a loop or composite already runs (409). */
|
|
226
244
|
readonly isAlreadyRunning: (error: unknown) => boolean;
|
|
227
245
|
/** The provider account's refusal (#3204) the companion ANSWERED with (a model call outside the loop's own steps), or `undefined`. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"creation-drive.service.d.ts","sourceRoot":"","sources":["../../../../src/services/companion/creation-drive.service.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"creation-drive.service.d.ts","sourceRoot":"","sources":["../../../../src/services/companion/creation-drive.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,OAAO,EAIL,KAAK,oBAAoB,EACzB,KAAK,2BAA2B,EAChC,KAAK,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CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;IAChC,4IAA4I;IAC5I,QAAQ,CAAC,sBAAsB,CAAC,EAAE,2BAA2B,CAAC;CAC/D;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE;IACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC;CAClC,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAyO/B"}
|
|
@@ -32,6 +32,12 @@
|
|
|
32
32
|
* the working tree; the run records survive). The restart itself is on the intervention ledger when the companion
|
|
33
33
|
* booted with runs in flight (#2231), and the driver also counts the restarts it saw, from the companion's start time.
|
|
34
34
|
*
|
|
35
|
+
* A restart reaches the driver in one of two shapes: nothing listens (connection refused), or the companion stopped while
|
|
36
|
+
* it HELD the loop request, which the client sees as the connection closing before any answer (`UND_ERR_SOCKET`; #4021,
|
|
37
|
+
* reference run 44052185141, where a dependency install's restart stopped the drive `loop-refused` twice). The second is
|
|
38
|
+
* never read as a restart on its own: the next status the companion answers settles it by its process start time, a new
|
|
39
|
+
* one resuming the drive and the same one stopping it {@link CreationDriveStopRule.LOOP_CONNECTION_LOST}.
|
|
40
|
+
*
|
|
35
41
|
* ## Holds it respects
|
|
36
42
|
*
|
|
37
43
|
* - a person's `wildo build stop` (#3206) is a STOP: a stopped build is never resumed unattended;
|
|
@@ -87,6 +93,13 @@ export var CreationDriveStopRule;
|
|
|
87
93
|
CreationDriveStopRule["LANES_FAILED"] = "lanes-failed";
|
|
88
94
|
/** The companion refused to run the loop (a preflight failure, a refusal whose remedy is a decision). */
|
|
89
95
|
CreationDriveStopRule["LOOP_REFUSED"] = "loop-refused";
|
|
96
|
+
/**
|
|
97
|
+
* The connection closed before the companion answered the loop, and the companion did NOT restart (#4021): the same
|
|
98
|
+
* process, by its start time, answered the next read. Not a refusal (it said nothing) and not a restart (which the drive
|
|
99
|
+
* waits through), so something between the drive and the companion cut the request. The loop may still run there:
|
|
100
|
+
* `wildo creation pulse` shows it; run the drive again, which waits for it before choosing.
|
|
101
|
+
*/
|
|
102
|
+
CreationDriveStopRule["LOOP_CONNECTION_LOST"] = "loop-connection-lost";
|
|
90
103
|
/** The autonomy posture leaves acceptance to a person: a marked critical gate is armed. */
|
|
91
104
|
CreationDriveStopRule["ACCEPTANCE_HELD_FOR_PERSON"] = "acceptance-held-for-person";
|
|
92
105
|
/** The creation preflight found what would stop the run, before the first round. */
|
|
@@ -283,6 +296,11 @@ function judgeChosenStop(rationale, requirements) {
|
|
|
283
296
|
return stop(CreationDriveStopRule.REQUIREMENTS_OPEN, `the loop chose to stop (${rationale}) while ${requirementsWithItems} of ${standing.requirementCount} requirement(s) carry ${standing.openItems.length} open item(s): `
|
|
284
297
|
+ `${named.join('; ')}${rest > 0 ? `; and ${rest} more` : ''}. Start refinement on them, or decide they are out of scope: wildo creation feed`);
|
|
285
298
|
}
|
|
299
|
+
/** `fetch failed (other side closed)`: the transport's line and its cause's, since `fetch failed` alone names nothing. */
|
|
300
|
+
function describeClosedConnection(error) {
|
|
301
|
+
const cause = error?.cause?.message;
|
|
302
|
+
return typeof cause === 'string' && cause.length > 0 ? `${describeCaughtError(error)} (${cause})` : describeCaughtError(error);
|
|
303
|
+
}
|
|
286
304
|
function stop(rule, waitingFor) {
|
|
287
305
|
return { action: CreationDriveAction.STOP, rule, waitingFor };
|
|
288
306
|
}
|
|
@@ -322,6 +340,12 @@ export async function runCreationDrive(port, options) {
|
|
|
322
340
|
let networkWaitSinceMs;
|
|
323
341
|
/** The standing read for the last loop's chosen stop (#3701); cleared when a loop runs, so a stale one never judges. */
|
|
324
342
|
let requirements;
|
|
343
|
+
/**
|
|
344
|
+
* The loop request whose connection closed before the companion answered (#4021), and the companion's start time when
|
|
345
|
+
* it was sent. Settled by the next status the companion answers: a new start time is a restart, waited through and
|
|
346
|
+
* resumed; the same one stops the drive {@link CreationDriveStopRule.LOOP_CONNECTION_LOST}.
|
|
347
|
+
*/
|
|
348
|
+
let loopConnectionLost;
|
|
325
349
|
const finish = (rule, waitingFor, providerAccountRefusal) => {
|
|
326
350
|
port.progress(`Stopped: ${rule} — ${waitingFor}`);
|
|
327
351
|
return {
|
|
@@ -372,7 +396,8 @@ export async function runCreationDrive(port, options) {
|
|
|
372
396
|
* A companion that does not answer, answers "not yet" (503: after a restart its first feed derivation is still
|
|
373
397
|
* running), or answers late is a WAIT, bounded; anything else is a defect worth surfacing (review of 6fe527ed3).
|
|
374
398
|
*/
|
|
375
|
-
|
|
399
|
+
// A read whose connection closed before the answer (#4021) is the same wait: a companion stopping under it.
|
|
400
|
+
if (!port.isCompanionUnreachable(error) && !port.isNotReadyYet(error) && !port.isClientTimeout(error) && !port.isConnectionClosedBeforeAnswer(error))
|
|
376
401
|
throw error;
|
|
377
402
|
unreachableSince ??= port.now();
|
|
378
403
|
if (port.now() - unreachableSince >= CREATION_DRIVE_COMPANION_DOWN_LIMIT_MS) {
|
|
@@ -394,6 +419,22 @@ export async function runCreationDrive(port, options) {
|
|
|
394
419
|
companionRestarts += 1;
|
|
395
420
|
port.progress(`The companion restarted (now since ${status.companionStartedAt}); re-reading its state`);
|
|
396
421
|
}
|
|
422
|
+
if (loopConnectionLost !== undefined) {
|
|
423
|
+
const lost = loopConnectionLost;
|
|
424
|
+
loopConnectionLost = undefined;
|
|
425
|
+
/*
|
|
426
|
+
* The companion's own process start time is the restart signal (the status route computes it once per process), so
|
|
427
|
+
* the closed connection is never read as a restart on its own. A restart was counted just above and the drive goes
|
|
428
|
+
* on from the durable rows; the same process means the request was cut by something else, which is no refusal the
|
|
429
|
+
* drive can name and no restart it can wait through.
|
|
430
|
+
*/
|
|
431
|
+
// An unknown start time cannot show a restart, so it stops rather than resume on a guess (fails closed).
|
|
432
|
+
if (lost.companionStartedAt === undefined || status.companionStartedAt === lost.companionStartedAt) {
|
|
433
|
+
return finish(CreationDriveStopRule.LOOP_CONNECTION_LOST, `the connection closed before the companion answered the loop (${lost.cause}), and the companion did not restart (running since ${status.companionStartedAt}); `
|
|
434
|
+
+ 'the loop may still run there (wildo creation pulse): run the drive again, which waits for it');
|
|
435
|
+
}
|
|
436
|
+
port.progress('The loop\'s connection closed because the companion restarted; resuming from its state');
|
|
437
|
+
}
|
|
397
438
|
companionStartedAt = status.companionStartedAt;
|
|
398
439
|
/*
|
|
399
440
|
* The goal is the requirements' to call (#3701): once the last loop chose to stop with nothing since, read where the
|
|
@@ -404,6 +445,22 @@ export async function runCreationDrive(port, options) {
|
|
|
404
445
|
requirements = { standing: await port.readRequirementsStanding() };
|
|
405
446
|
}
|
|
406
447
|
catch (error) {
|
|
448
|
+
/*
|
|
449
|
+
* A companion that stopped under this read (a held restart is released the moment the loop leaves nothing busy, and
|
|
450
|
+
* this read derives for a while), is down, or is not ready yet has not said the standing is unreadable (#4021): wait,
|
|
451
|
+
* bounded as any outage, WITHOUT marking that the drive waited, so the restarted companion is asked the same question
|
|
452
|
+
* for the same chosen stop. A client timeout is kept as an unread standing: the companion answered nothing late,
|
|
453
|
+
* which is a slow derivation rather than an absent companion.
|
|
454
|
+
*/
|
|
455
|
+
if (port.isCompanionUnreachable(error) || port.isConnectionClosedBeforeAnswer(error) || port.isNotReadyYet(error)) {
|
|
456
|
+
unreachableSince ??= port.now();
|
|
457
|
+
if (port.now() - unreachableSince >= CREATION_DRIVE_COMPANION_DOWN_LIMIT_MS) {
|
|
458
|
+
return finish(CreationDriveStopRule.COMPANION_UNREACHABLE, `the companion has not answered since ${new Date(unreachableSince).toISOString()}: wildo local dev`);
|
|
459
|
+
}
|
|
460
|
+
port.progress(`Waiting: ${CreationDriveWaitReason.COMPANION_DOWN} — the companion did not answer where the application stands; asking again`);
|
|
461
|
+
await port.sleep(CREATION_DRIVE_POLL_INTERVAL_MS);
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
407
464
|
requirements = { unreadBecause: describeCaughtError(error) };
|
|
408
465
|
}
|
|
409
466
|
}
|
|
@@ -455,6 +512,18 @@ export async function runCreationDrive(port, options) {
|
|
|
455
512
|
});
|
|
456
513
|
}
|
|
457
514
|
catch (error) {
|
|
515
|
+
/*
|
|
516
|
+
* The connection closed before the companion answered (#4021): a companion that stops while it holds the loop request
|
|
517
|
+
* (a restart after a dependency install) leaves exactly this. Reference run 44052185141 stopped `loop-refused: fetch
|
|
518
|
+
* failed` on it twice. Not decided here: the next status read settles it by the companion's start time, waiting
|
|
519
|
+
* (bounded, as any unreachable companion) while it is down or not ready.
|
|
520
|
+
*/
|
|
521
|
+
if (port.isConnectionClosedBeforeAnswer(error)) {
|
|
522
|
+
loopConnectionLost = { companionStartedAt, cause: describeClosedConnection(error) };
|
|
523
|
+
lastLoop = undefined;
|
|
524
|
+
port.progress(`Loop ${loops}: the connection closed before the companion answered; asking whether it restarted`);
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
458
527
|
// The companion went away under the loop, the client stopped waiting while it goes on, or another loop holds the
|
|
459
528
|
// subject: the next read decides (a restart is a wait, a running loop is a wait). Anything else is its refusal.
|
|
460
529
|
if (port.isCompanionUnreachable(error) || port.isClientTimeout(error) || port.isAlreadyRunning(error) || port.isNotReadyYet(error)) {
|