@warlock.js/ai-cli 5.52.0 → 5.53.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/cjs/index.cjs +39 -11
- package/cjs/index.cjs.map +1 -1
- package/esm/cli-agent.mjs +4 -1
- package/esm/cli-agent.mjs.map +1 -1
- package/esm/contracts/options.type.d.mts +10 -4
- package/esm/contracts/options.type.d.mts.map +1 -1
- package/esm/session/environment.mjs +15 -2
- package/esm/session/environment.mjs.map +1 -1
- package/esm/stream/line-splitter.mjs +22 -10
- package/esm/stream/line-splitter.mjs.map +1 -1
- package/llms-full.txt +2 -0
- package/package.json +2 -2
- package/skills/run-cli-agents/SKILL.md +2 -0
package/esm/cli-agent.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { CliError } from "./errors.mjs";
|
|
|
2
2
|
import { cliModel } from "./model/cli-model.mjs";
|
|
3
3
|
import { buildInvocation, fitsCommandLine } from "./spawn/invocation.mjs";
|
|
4
4
|
import { assertCapabilities, probeCli } from "./probe/probe.mjs";
|
|
5
|
-
import { buildEnvironment } from "./session/environment.mjs";
|
|
5
|
+
import { buildEnvironment, warnInheritedEnvironment } from "./session/environment.mjs";
|
|
6
6
|
import { createRunDirectories, writeLaunchFiles } from "./session/run-directory.mjs";
|
|
7
7
|
import { cancelledSession, startSession } from "./session/session.mjs";
|
|
8
8
|
import { readEnv, resolveSpawnTarget } from "./spawn/resolve-command.mjs";
|
|
@@ -67,6 +67,7 @@ function createCliAgent(adapter, options = {}, host = currentHost()) {
|
|
|
67
67
|
const probeEnvironment = () => buildEnvironment({
|
|
68
68
|
source: host.env,
|
|
69
69
|
inherit: options.inheritEnv ?? true,
|
|
70
|
+
credentials: adapter.apiKeyEnv,
|
|
70
71
|
managed: [],
|
|
71
72
|
user: options.env,
|
|
72
73
|
platform: host.platform
|
|
@@ -158,9 +159,11 @@ function createCliAgent(adapter, options = {}, host = currentHost()) {
|
|
|
158
159
|
});
|
|
159
160
|
await writeLaunchFiles(chosen.plan.files ?? [], directories);
|
|
160
161
|
const apiKeyEnv = adapter.apiKeyEnv[0];
|
|
162
|
+
warnInheritedEnvironment(adapter.title, options.inheritEnv, host.env);
|
|
161
163
|
const env = buildEnvironment({
|
|
162
164
|
source: host.env,
|
|
163
165
|
inherit: options.inheritEnv ?? true,
|
|
166
|
+
credentials: adapter.apiKeyEnv,
|
|
164
167
|
managed: home === "inherit" ? [] : adapter.homeEnv,
|
|
165
168
|
plan: host.platform === "win32" ? chosen.plan.env : {
|
|
166
169
|
PWD: cwd,
|
package/esm/cli-agent.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-agent.mjs","names":[],"sources":["../../../../../../../packages/ai-cli/src/cli-agent.ts"],"sourcesContent":["import { accessSync, constants, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n CliAdapter,\n CliAgentOptions,\n CliLaunchContext,\n CliLaunchPlan,\n CliProbeResult,\n CliRunOptions,\n CliSession,\n} from \"./contracts\";\nimport type { ModelContract } from \"@warlock.js/ai\";\nimport { CliError } from \"./errors\";\nimport { type CliModelConfig, cliModel } from \"./model/cli-model\";\nimport { assertCapabilities, probeCli } from \"./probe/probe\";\nimport { buildEnvironment } from \"./session/environment\";\nimport { createRunDirectories, writeLaunchFiles } from \"./session/run-directory\";\nimport { cancelledSession, startSession } from \"./session/session\";\nimport { buildInvocation, fitsCommandLine, type Invocation } from \"./spawn/invocation\";\nimport {\n type CommandLookup,\n readEnv,\n resolveSpawnTarget,\n type SpawnTarget,\n} from \"./spawn/resolve-command\";\n\n/** A configured coding CLI: run prompts, probe the binary, or use it as an `ai.agent` model. */\nexport type CliAgent = {\n readonly adapter: CliAdapter;\n readonly options: Readonly<CliAgentOptions>;\n /**\n * Start a session. Rejects (with {@link CliError}) only for setup problems\n * — executable not found, a flag missing from `--help`, an unsupported\n * option; the run's own outcome is reported by `session.done()`.\n */\n run(prompt: string, options?: CliRunOptions): Promise<CliSession>;\n /** Run (or reuse) the capability probe: resolved executable, version and help text. */\n probe(): Promise<CliProbeResult>;\n /** This CLI as an `ai.agent` model (see {@link cliModel}). */\n model(config?: CliModelConfig): ModelContract;\n};\n\n/** Host facts, injectable for tests. */\nexport type CliHost = CommandLookup & { comspec: string };\n\nfunction isRunnableFile(filePath: string, platform: NodeJS.Platform): boolean {\n try {\n if (!statSync(filePath).isFile()) {\n return false;\n }\n\n if (platform !== \"win32\") {\n accessSync(filePath, constants.X_OK);\n }\n\n return true;\n } catch {\n return false;\n }\n}\n\n/** The current machine as a {@link CliHost}. */\nexport function currentHost(): CliHost {\n const platform = process.platform;\n\n return {\n platform,\n env: process.env,\n isFile: (filePath) => isRunnableFile(filePath, platform),\n readFile: (filePath) => {\n try {\n return readFileSync(filePath, \"utf8\");\n } catch {\n return undefined;\n }\n },\n execPath: process.execPath,\n comspec: readEnv(process.env, \"ComSpec\", platform) ?? \"cmd.exe\",\n };\n}\n\nfunction unsupported(adapter: CliAdapter, message: string): CliError {\n return new CliError(`${adapter.title}: ${message}`, {\n type: \"unsupported-option\",\n adapter: adapter.name,\n });\n}\n\n/**\n * Create a CLI agent from an adapter. The vendor factories\n * (`cli.claudeCode(...)`, `cli.codex(...)`, …) call this with their\n * built-in adapter; call it directly with your own {@link CliAdapter}.\n *\n * @example\n * const agent = createCliAgent(myAdapter, { model: \"fast\", permission: \"standard\" });\n * const session = await agent.run(\"Summarize README.md\", { cwd: \"/srv/repo\" });\n * console.log((await session.done()).text);\n */\nexport function createCliAgent(\n adapter: CliAdapter,\n options: CliAgentOptions = {},\n host: CliHost = currentHost(),\n): CliAgent {\n const probes = new Map<string, Promise<CliProbeResult>>();\n const command = options.command ?? adapter.command;\n\n const resolveTarget = (): SpawnTarget => {\n const target = resolveSpawnTarget(command, host);\n\n if (target === undefined) {\n throw new CliError(\n `${adapter.title}: could not find \"${command}\" on PATH. Install the CLI or pass its absolute path as \\`command\\`.`,\n { type: \"not-found\", adapter: adapter.name },\n );\n }\n\n return target;\n };\n\n const probeEnvironment = (): Record<string, string> =>\n buildEnvironment({\n source: host.env,\n inherit: options.inheritEnv ?? true,\n managed: [],\n user: options.env,\n platform: host.platform,\n });\n\n const probeTarget = (target: SpawnTarget): Promise<CliProbeResult> => {\n const cached = probes.get(target.executable);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const pending = probeCli({\n adapter,\n target,\n env: probeEnvironment(),\n cwd: path.resolve(options.cwd ?? process.cwd()),\n comspec: host.comspec,\n platform: host.platform,\n });\n\n probes.set(target.executable, pending);\n // A failed probe is retried on the next run instead of being cached.\n pending.catch(() => probes.delete(target.executable));\n\n return pending;\n };\n\n const run = async (prompt: string, runOptions: CliRunOptions = {}): Promise<CliSession> => {\n const merged: CliRunOptions = {\n ...options,\n ...runOptions,\n env: { ...options.env, ...runOptions.env },\n args: [...(options.args ?? []), ...(runOptions.args ?? [])],\n mcp: runOptions.mcp ?? options.mcp,\n };\n const permission = merged.permission ?? \"standard\";\n\n if (permission !== \"standard\" && permission !== \"bypass\") {\n throw unsupported(\n adapter,\n `unknown permission \"${String(permission)}\" (use \"standard\" or \"bypass\").`,\n );\n }\n\n if (merged.effort !== undefined && adapter.effort !== true) {\n throw unsupported(adapter, \"this CLI has no reasoning-effort control; drop `effort`.\");\n }\n\n const mcp =\n merged.mcp !== undefined && Object.keys(merged.mcp).length > 0 ? merged.mcp : undefined;\n\n if (mcp !== undefined && adapter.mcp !== true) {\n throw unsupported(adapter, \"this CLI cannot attach per-run MCP servers; drop `mcp`.\");\n }\n\n if (merged.apiKey !== undefined && adapter.apiKeyEnv.length === 0) {\n throw unsupported(adapter, \"this CLI reads no API key from the environment; drop `apiKey`.\");\n }\n\n const home = options.home ?? \"private\";\n\n if (home !== \"inherit\" && adapter.homeEnv.length === 0) {\n throw unsupported(\n adapter,\n 'this CLI cannot relocate its config home; use `home: \"inherit\"`.',\n );\n }\n\n const cwd = path.resolve(merged.cwd ?? process.cwd());\n const target = resolveTarget();\n const probe = options.probe === false ? undefined : await probeTarget(target);\n\n if (merged.signal?.aborted) {\n return cancelledSession(adapter.name, merged.resume);\n }\n\n const directories = await createRunDirectories(home, cwd);\n\n try {\n let chosen:\n | { plan: CliLaunchPlan; invocation: Invocation; context: CliLaunchContext }\n | undefined;\n const reasons: string[] = [];\n\n for (const transport of adapter.transports) {\n const context: CliLaunchContext = {\n prompt,\n transport,\n cwd,\n model: merged.model,\n effort: merged.effort,\n permission,\n resume: merged.resume,\n mcp,\n apiKey: merged.apiKey,\n home: directories.home,\n homeIsPrivate: directories.homeIsPrivate,\n runDir: directories.runDir,\n platform: host.platform,\n };\n const plan = adapter.plan(context);\n\n if (probe !== undefined) {\n assertCapabilities(adapter, probe, plan.requires);\n }\n\n const invocation = buildInvocation(\n target,\n [...plan.args, ...(merged.args ?? []), ...(plan.tail ?? [])],\n host.comspec,\n );\n\n if (\"refused\" in invocation) {\n reasons.push(`${transport}: ${invocation.refused}`);\n continue;\n }\n\n if (!fitsCommandLine(invocation, host.platform)) {\n reasons.push(`${transport}: the command line exceeds the platform limit`);\n continue;\n }\n\n chosen = { plan, invocation, context };\n break;\n }\n\n if (chosen === undefined) {\n throw new CliError(\n `${adapter.title}: the prompt cannot be passed to \"${target.executable}\" (${reasons.join(\"; \")}).`,\n { type: \"prompt-transport\", adapter: adapter.name, executable: target.executable },\n );\n }\n\n await writeLaunchFiles(chosen.plan.files ?? [], directories);\n\n const apiKeyEnv = adapter.apiKeyEnv[0];\n const env = buildEnvironment({\n source: host.env,\n inherit: options.inheritEnv ?? true,\n managed: home === \"inherit\" ? [] : adapter.homeEnv,\n // A CLI that prefers $PWD over its real cwd must not see the host's.\n plan: host.platform === \"win32\" ? chosen.plan.env : { PWD: cwd, ...chosen.plan.env },\n user: merged.env,\n apiKey:\n merged.apiKey !== undefined && apiKeyEnv !== undefined\n ? { name: apiKeyEnv, value: merged.apiKey }\n : undefined,\n platform: host.platform,\n });\n\n return startSession({\n adapter: adapter.name,\n invocation: chosen.invocation,\n cwd,\n env,\n stdin: chosen.plan.stdin,\n parser: adapter.parser(chosen.context),\n signal: merged.signal,\n timeoutMs: merged.timeoutMs,\n killGraceMs: options.killGraceMs ?? 2000,\n platform: host.platform,\n resume: merged.resume,\n cleanup: directories.dispose,\n });\n } catch (error) {\n await directories.dispose();\n throw error;\n }\n };\n\n const agent: CliAgent = {\n adapter,\n options,\n run,\n probe: () => probeTarget(resolveTarget()),\n model: (config) => cliModel(agent, config),\n };\n\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;AA6CA,SAAS,eAAe,UAAkB,UAAoC;CAC5E,IAAI;EACF,IAAI,CAAC,SAAS,QAAQ,CAAC,CAAC,OAAO,GAC7B,OAAO;EAGT,IAAI,aAAa,SACf,WAAW,UAAU,UAAU,IAAI;EAGrC,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAgB,cAAuB;CACrC,MAAM,WAAW,QAAQ;CAEzB,OAAO;EACL;EACA,KAAK,QAAQ;EACb,SAAS,aAAa,eAAe,UAAU,QAAQ;EACvD,WAAW,aAAa;GACtB,IAAI;IACF,OAAO,aAAa,UAAU,MAAM;GACtC,QAAQ;IACN;GACF;EACF;EACA,UAAU,QAAQ;EAClB,SAAS,QAAQ,QAAQ,KAAK,WAAW,QAAQ,KAAK;CACxD;AACF;AAEA,SAAS,YAAY,SAAqB,SAA2B;CACnE,OAAO,IAAI,SAAS,GAAG,QAAQ,MAAM,IAAI,WAAW;EAClD,MAAM;EACN,SAAS,QAAQ;CACnB,CAAC;AACH;;;;;;;;;;;AAYA,SAAgB,eACd,SACA,UAA2B,CAAC,GAC5B,OAAgB,YAAY,GAClB;CACV,MAAM,yBAAS,IAAI,IAAqC;CACxD,MAAM,UAAU,QAAQ,WAAW,QAAQ;CAE3C,MAAM,sBAAmC;EACvC,MAAM,SAAS,mBAAmB,SAAS,IAAI;EAE/C,IAAI,WAAW,QACb,MAAM,IAAI,SACR,GAAG,QAAQ,M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IAAI,SACR,GAAG,QAAQ,MAAM,oCAAoC,OAAO,WAAW,KAAK,QAAQ,KAAK,IAAI,EAAE,KAC/F;IAAE,MAAM;IAAoB,SAAS,QAAQ;IAAM,YAAY,OAAO;GAAW,CACnF;GAGF,MAAM,iBAAiB,OAAO,KAAK,SAAS,CAAC,GAAG,WAAW;GAE3D,MAAM,YAAY,QAAQ,UAAU;GACpC,MAAM,MAAM,iBAAiB;IAC3B,QAAQ,KAAK;IACb,SAAS,QAAQ,cAAc;IAC/B,SAAS,SAAS,YAAY,CAAC,IAAI,QAAQ;IAE3C,MAAM,KAAK,aAAa,UAAU,OAAO,KAAK,MAAM;KAAE,KAAK;KAAK,GAAG,OAAO,KAAK;IAAI;IACnF,MAAM,OAAO;IACb,QACE,OAAO,WAAW,UAAa,cAAc,SACzC;KAAE,MAAM;KAAW,OAAO,OAAO;IAAO,IACxC;IACN,UAAU,KAAK;GACjB,CAAC;GAED,OAAO,aAAa;IAClB,SAAS,QAAQ;IACjB,YAAY,OAAO;IACnB;IACA;IACA,OAAO,OAAO,KAAK;IACnB,QAAQ,QAAQ,OAAO,OAAO,OAAO;IACrC,QAAQ,OAAO;IACf,WAAW,OAAO;IAClB,aAAa,QAAQ,eAAe;IACpC,UAAU,KAAK;IACf,QAAQ,OAAO;IACf,SAAS,YAAY;GACvB,CAAC;EACH,SAAS,OAAO;GACd,MAAM,YAAY,QAAQ;GAC1B,MAAM;EACR;CACF;CAEA,MAAM,QAAkB;EACtB;EACA;EACA;EACA,aAAa,YAAY,cAAc,CAAC;EACxC,QAAQ,WAAW,SAAS,OAAO,MAAM;CAC3C;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"cli-agent.mjs","names":[],"sources":["../../../../../../../packages/ai-cli/src/cli-agent.ts"],"sourcesContent":["import { accessSync, constants, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n CliAdapter,\n CliAgentOptions,\n CliLaunchContext,\n CliLaunchPlan,\n CliProbeResult,\n CliRunOptions,\n CliSession,\n} from \"./contracts\";\nimport type { ModelContract } from \"@warlock.js/ai\";\nimport { CliError } from \"./errors\";\nimport { type CliModelConfig, cliModel } from \"./model/cli-model\";\nimport { assertCapabilities, probeCli } from \"./probe/probe\";\nimport { buildEnvironment, warnInheritedEnvironment } from \"./session/environment\";\nimport { createRunDirectories, writeLaunchFiles } from \"./session/run-directory\";\nimport { cancelledSession, startSession } from \"./session/session\";\nimport { buildInvocation, fitsCommandLine, type Invocation } from \"./spawn/invocation\";\nimport {\n type CommandLookup,\n readEnv,\n resolveSpawnTarget,\n type SpawnTarget,\n} from \"./spawn/resolve-command\";\n\n/** A configured coding CLI: run prompts, probe the binary, or use it as an `ai.agent` model. */\nexport type CliAgent = {\n readonly adapter: CliAdapter;\n readonly options: Readonly<CliAgentOptions>;\n /**\n * Start a session. Rejects (with {@link CliError}) only for setup problems\n * — executable not found, a flag missing from `--help`, an unsupported\n * option; the run's own outcome is reported by `session.done()`.\n */\n run(prompt: string, options?: CliRunOptions): Promise<CliSession>;\n /** Run (or reuse) the capability probe: resolved executable, version and help text. */\n probe(): Promise<CliProbeResult>;\n /** This CLI as an `ai.agent` model (see {@link cliModel}). */\n model(config?: CliModelConfig): ModelContract;\n};\n\n/** Host facts, injectable for tests. */\nexport type CliHost = CommandLookup & { comspec: string };\n\nfunction isRunnableFile(filePath: string, platform: NodeJS.Platform): boolean {\n try {\n if (!statSync(filePath).isFile()) {\n return false;\n }\n\n if (platform !== \"win32\") {\n accessSync(filePath, constants.X_OK);\n }\n\n return true;\n } catch {\n return false;\n }\n}\n\n/** The current machine as a {@link CliHost}. */\nexport function currentHost(): CliHost {\n const platform = process.platform;\n\n return {\n platform,\n env: process.env,\n isFile: (filePath) => isRunnableFile(filePath, platform),\n readFile: (filePath) => {\n try {\n return readFileSync(filePath, \"utf8\");\n } catch {\n return undefined;\n }\n },\n execPath: process.execPath,\n comspec: readEnv(process.env, \"ComSpec\", platform) ?? \"cmd.exe\",\n };\n}\n\nfunction unsupported(adapter: CliAdapter, message: string): CliError {\n return new CliError(`${adapter.title}: ${message}`, {\n type: \"unsupported-option\",\n adapter: adapter.name,\n });\n}\n\n/**\n * Create a CLI agent from an adapter. The vendor factories\n * (`cli.claudeCode(...)`, `cli.codex(...)`, …) call this with their\n * built-in adapter; call it directly with your own {@link CliAdapter}.\n *\n * @example\n * const agent = createCliAgent(myAdapter, { model: \"fast\", permission: \"standard\" });\n * const session = await agent.run(\"Summarize README.md\", { cwd: \"/srv/repo\" });\n * console.log((await session.done()).text);\n */\nexport function createCliAgent(\n adapter: CliAdapter,\n options: CliAgentOptions = {},\n host: CliHost = currentHost(),\n): CliAgent {\n const probes = new Map<string, Promise<CliProbeResult>>();\n const command = options.command ?? adapter.command;\n\n const resolveTarget = (): SpawnTarget => {\n const target = resolveSpawnTarget(command, host);\n\n if (target === undefined) {\n throw new CliError(\n `${adapter.title}: could not find \"${command}\" on PATH. Install the CLI or pass its absolute path as \\`command\\`.`,\n { type: \"not-found\", adapter: adapter.name },\n );\n }\n\n return target;\n };\n\n const probeEnvironment = (): Record<string, string> =>\n buildEnvironment({\n source: host.env,\n inherit: options.inheritEnv ?? true,\n credentials: adapter.apiKeyEnv,\n managed: [],\n user: options.env,\n platform: host.platform,\n });\n\n const probeTarget = (target: SpawnTarget): Promise<CliProbeResult> => {\n const cached = probes.get(target.executable);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const pending = probeCli({\n adapter,\n target,\n env: probeEnvironment(),\n cwd: path.resolve(options.cwd ?? process.cwd()),\n comspec: host.comspec,\n platform: host.platform,\n });\n\n probes.set(target.executable, pending);\n // A failed probe is retried on the next run instead of being cached.\n pending.catch(() => probes.delete(target.executable));\n\n return pending;\n };\n\n const run = async (prompt: string, runOptions: CliRunOptions = {}): Promise<CliSession> => {\n const merged: CliRunOptions = {\n ...options,\n ...runOptions,\n env: { ...options.env, ...runOptions.env },\n args: [...(options.args ?? []), ...(runOptions.args ?? [])],\n mcp: runOptions.mcp ?? options.mcp,\n };\n const permission = merged.permission ?? \"standard\";\n\n if (permission !== \"standard\" && permission !== \"bypass\") {\n throw unsupported(\n adapter,\n `unknown permission \"${String(permission)}\" (use \"standard\" or \"bypass\").`,\n );\n }\n\n if (merged.effort !== undefined && adapter.effort !== true) {\n throw unsupported(adapter, \"this CLI has no reasoning-effort control; drop `effort`.\");\n }\n\n const mcp =\n merged.mcp !== undefined && Object.keys(merged.mcp).length > 0 ? merged.mcp : undefined;\n\n if (mcp !== undefined && adapter.mcp !== true) {\n throw unsupported(adapter, \"this CLI cannot attach per-run MCP servers; drop `mcp`.\");\n }\n\n if (merged.apiKey !== undefined && adapter.apiKeyEnv.length === 0) {\n throw unsupported(adapter, \"this CLI reads no API key from the environment; drop `apiKey`.\");\n }\n\n const home = options.home ?? \"private\";\n\n if (home !== \"inherit\" && adapter.homeEnv.length === 0) {\n throw unsupported(\n adapter,\n 'this CLI cannot relocate its config home; use `home: \"inherit\"`.',\n );\n }\n\n const cwd = path.resolve(merged.cwd ?? process.cwd());\n const target = resolveTarget();\n const probe = options.probe === false ? undefined : await probeTarget(target);\n\n if (merged.signal?.aborted) {\n return cancelledSession(adapter.name, merged.resume);\n }\n\n const directories = await createRunDirectories(home, cwd);\n\n try {\n let chosen:\n | { plan: CliLaunchPlan; invocation: Invocation; context: CliLaunchContext }\n | undefined;\n const reasons: string[] = [];\n\n for (const transport of adapter.transports) {\n const context: CliLaunchContext = {\n prompt,\n transport,\n cwd,\n model: merged.model,\n effort: merged.effort,\n permission,\n resume: merged.resume,\n mcp,\n apiKey: merged.apiKey,\n home: directories.home,\n homeIsPrivate: directories.homeIsPrivate,\n runDir: directories.runDir,\n platform: host.platform,\n };\n const plan = adapter.plan(context);\n\n if (probe !== undefined) {\n assertCapabilities(adapter, probe, plan.requires);\n }\n\n const invocation = buildInvocation(\n target,\n [...plan.args, ...(merged.args ?? []), ...(plan.tail ?? [])],\n host.comspec,\n );\n\n if (\"refused\" in invocation) {\n reasons.push(`${transport}: ${invocation.refused}`);\n continue;\n }\n\n if (!fitsCommandLine(invocation, host.platform)) {\n reasons.push(`${transport}: the command line exceeds the platform limit`);\n continue;\n }\n\n chosen = { plan, invocation, context };\n break;\n }\n\n if (chosen === undefined) {\n throw new CliError(\n `${adapter.title}: the prompt cannot be passed to \"${target.executable}\" (${reasons.join(\"; \")}).`,\n { type: \"prompt-transport\", adapter: adapter.name, executable: target.executable },\n );\n }\n\n await writeLaunchFiles(chosen.plan.files ?? [], directories);\n\n const apiKeyEnv = adapter.apiKeyEnv[0];\n warnInheritedEnvironment(adapter.title, options.inheritEnv, host.env);\n const env = buildEnvironment({\n source: host.env,\n inherit: options.inheritEnv ?? true,\n credentials: adapter.apiKeyEnv,\n managed: home === \"inherit\" ? [] : adapter.homeEnv,\n // A CLI that prefers $PWD over its real cwd must not see the host's.\n plan: host.platform === \"win32\" ? chosen.plan.env : { PWD: cwd, ...chosen.plan.env },\n user: merged.env,\n apiKey:\n merged.apiKey !== undefined && apiKeyEnv !== undefined\n ? { name: apiKeyEnv, value: merged.apiKey }\n : undefined,\n platform: host.platform,\n });\n\n return startSession({\n adapter: adapter.name,\n invocation: chosen.invocation,\n cwd,\n env,\n stdin: chosen.plan.stdin,\n parser: adapter.parser(chosen.context),\n signal: merged.signal,\n timeoutMs: merged.timeoutMs,\n killGraceMs: options.killGraceMs ?? 2000,\n platform: host.platform,\n resume: merged.resume,\n cleanup: directories.dispose,\n });\n } catch (error) {\n await directories.dispose();\n throw error;\n }\n };\n\n const agent: CliAgent = {\n adapter,\n options,\n run,\n probe: () => probeTarget(resolveTarget()),\n model: (config) => cliModel(agent, config),\n };\n\n return agent;\n}\n"],"mappings":";;;;;;;;;;;;AA6CA,SAAS,eAAe,UAAkB,UAAoC;CAC5E,IAAI;EACF,IAAI,CAAC,SAAS,QAAQ,CAAC,CAAC,OAAO,GAC7B,OAAO;EAGT,IAAI,aAAa,SACf,WAAW,UAAU,UAAU,IAAI;EAGrC,OAAO;CACT,QAAQ;EACN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AAI;IACnF,MAAM,OAAO;IACb,QACE,OAAO,WAAW,UAAa,cAAc,SACzC;KAAE,MAAM;KAAW,OAAO,OAAO;IAAO,IACxC;IACN,UAAU,KAAK;GACjB,CAAC;GAED,OAAO,aAAa;IAClB,SAAS,QAAQ;IACjB,YAAY,OAAO;IACnB;IACA;IACA,OAAO,OAAO,KAAK;IACnB,QAAQ,QAAQ,OAAO,OAAO,OAAO;IACrC,QAAQ,OAAO;IACf,WAAW,OAAO;IAClB,aAAa,QAAQ,eAAe;IACpC,UAAU,KAAK;IACf,QAAQ,OAAO;IACf,SAAS,YAAY;GACvB,CAAC;EACH,SAAS,OAAO;GACd,MAAM,YAAY,QAAQ;GAC1B,MAAM;EACR;CACF;CAEA,MAAM,QAAkB;EACtB;EACA;EACA;EACA,aAAa,YAAY,cAAc,CAAC;EACxC,QAAQ,WAAW,SAAS,OAAO,MAAM;CAC3C;CAEA,OAAO;AACT"}
|
|
@@ -50,11 +50,17 @@ export type CliAgentOptions = CliRunOptions & {
|
|
|
50
50
|
/**
|
|
51
51
|
* Which of the current process's environment variables the CLI inherits.
|
|
52
52
|
* `true` (default) inherits everything except the adapter's own home
|
|
53
|
-
* variables; `
|
|
54
|
-
*
|
|
55
|
-
* set
|
|
53
|
+
* variables; `"curated"` passes the minimal system set plus the adapter's
|
|
54
|
+
* own API key variables (`apiKeyEnv`); `false` passes only the minimal
|
|
55
|
+
* system set (PATH, HOME, TEMP, locale, proxy and Windows system
|
|
56
|
+
* variables); a list passes the minimal set plus those names.
|
|
57
|
+
*
|
|
58
|
+
* With the default, the CLI sees every server secret (database URLs,
|
|
59
|
+
* signing keys, other providers' keys). Prefer `"curated"` and add what
|
|
60
|
+
* the CLI needs through `env`. In production, leaving this unset logs a
|
|
61
|
+
* one-time warning; set `true` explicitly to keep it and silence the warning.
|
|
56
62
|
*/
|
|
57
|
-
inheritEnv?: boolean | string[];
|
|
63
|
+
inheritEnv?: boolean | "curated" | string[];
|
|
58
64
|
/**
|
|
59
65
|
* Run the capability probe (`--help`/`--version`) before the first run.
|
|
60
66
|
* Default `true`. Turning it off skips the flag check — a CLI version
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.type.d.mts","names":[],"sources":["../../../../../../../../packages/ai-cli/src/contracts/options.type.ts"],"mappings":";;;;;;;;;;;;;;;;;YAiBY;;YAGA;;EAEV;;EAEA;;EAEA,SAAS;;EAET;;EAEA;;EAEA,SAAS;;EAET,aAAa;;EAEb,MAAM;;EAEN,MAAM;;EAEN;;EAEA;;;YAIU,kBAAkB;;EAE5B;;EAEA,OAAO
|
|
1
|
+
{"version":3,"file":"options.type.d.mts","names":[],"sources":["../../../../../../../../packages/ai-cli/src/contracts/options.type.ts"],"mappings":";;;;;;;;;;;;;;;;;YAiBY;;YAGA;;EAEV;;EAEA;;EAEA,SAAS;;EAET;;EAEA;;EAEA,SAAS;;EAET,aAAa;;EAEb,MAAM;;EAEN,MAAM;;EAEN;;EAEA;;;YAIU,kBAAkB;;EAE5B;;EAEA,OAAO;;;;;;;;;;;;;;EAcP;;;;;;EAMA;;EAEA;;;YAIU;EACV,QAAQ;;EAER;;EAEA;;EAEA,QAAQ;;EAER;EACA;EACA;;EAEA;;EAEA;EACA;;;YAIU;;WAED;;WAEA;;;;;WAKA,QAAQ,cAAc;;EAE/B,QAAQ,QAAQ;;EAEhB;;;YAIU;;EAEV;;EAEA;;EAEA"}
|
|
@@ -47,7 +47,8 @@ const MINIMAL_ENV = [
|
|
|
47
47
|
function buildEnvironment(input) {
|
|
48
48
|
const normalize = (name) => input.platform === "win32" ? name.toUpperCase() : name;
|
|
49
49
|
const managed = new Set(input.managed.map(normalize));
|
|
50
|
-
const
|
|
50
|
+
const extra = input.inherit === false ? [] : input.inherit === "curated" ? input.credentials ?? [] : input.inherit === true ? [] : input.inherit;
|
|
51
|
+
const allowed = input.inherit === true ? void 0 : new Set([...MINIMAL_ENV, ...extra].map(normalize));
|
|
51
52
|
const environment = {};
|
|
52
53
|
for (const [name, value] of Object.entries(input.source)) {
|
|
53
54
|
if (value === void 0 || managed.has(normalize(name))) continue;
|
|
@@ -65,7 +66,19 @@ function buildEnvironment(input) {
|
|
|
65
66
|
for (const [name, value] of Object.entries(input.user ?? {})) assign(name, value);
|
|
66
67
|
return environment;
|
|
67
68
|
}
|
|
69
|
+
let warnedInheritedEnvironment = false;
|
|
70
|
+
/**
|
|
71
|
+
* One console warning per process when a CLI agent runs in production with
|
|
72
|
+
* `inheritEnv` left at its default (`true`), which hands every server
|
|
73
|
+
* variable — database URLs, signing keys, other providers' keys — to a
|
|
74
|
+
* model-driven CLI.
|
|
75
|
+
*/
|
|
76
|
+
function warnInheritedEnvironment(title, inheritEnv, env) {
|
|
77
|
+
if (warnedInheritedEnvironment || inheritEnv !== void 0 || env.NODE_ENV !== "production") return;
|
|
78
|
+
warnedInheritedEnvironment = true;
|
|
79
|
+
console.warn(`[warlock-ai-cli] ${title} receives the whole server environment because \`inheritEnv\` is not set (default \`true\`). Set \`inheritEnv: "curated"\` to pass only the system variables and the CLI's own API key variable, or \`inheritEnv: true\` to keep the current behaviour and silence this warning.`);
|
|
80
|
+
}
|
|
68
81
|
|
|
69
82
|
//#endregion
|
|
70
|
-
export { MINIMAL_ENV, buildEnvironment };
|
|
83
|
+
export { MINIMAL_ENV, buildEnvironment, warnInheritedEnvironment };
|
|
71
84
|
//# sourceMappingURL=environment.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment.mjs","names":[],"sources":["../../../../../../../../packages/ai-cli/src/session/environment.ts"],"sourcesContent":["/**\n * Variables a CLI needs to start at all: executable lookup, home and temp\n * directories, locale, TLS/proxy settings and the Windows system set.\n * Passed through even with `inheritEnv: false`.\n */\nexport const MINIMAL_ENV = [\n \"PATH\",\n \"PATHEXT\",\n \"HOME\",\n \"USERPROFILE\",\n \"HOMEDRIVE\",\n \"HOMEPATH\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"SYSTEMROOT\",\n \"SYSTEMDRIVE\",\n \"WINDIR\",\n \"COMSPEC\",\n \"TEMP\",\n \"TMP\",\n \"TMPDIR\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TERM\",\n \"SHELL\",\n \"USER\",\n \"LOGNAME\",\n \"XDG_RUNTIME_DIR\",\n \"HTTP_PROXY\",\n \"HTTPS_PROXY\",\n \"NO_PROXY\",\n \"http_proxy\",\n \"https_proxy\",\n \"no_proxy\",\n \"NODE_EXTRA_CA_CERTS\",\n \"SSL_CERT_FILE\",\n \"SSL_CERT_DIR\",\n] as const;\n\nexport type BuildEnvironmentInput = {\n source: Record<string, string | undefined>;\n inherit: boolean | readonly string[];\n /** Variables the adapter manages (config home); never inherited from `source`. */\n managed: readonly string[];\n /** Adapter plan variables (config home, …). */\n plan?: Record<string, string>;\n /** Caller variables; win over everything else. */\n user?: Record<string, string>;\n /** API key and the variable it goes to. */\n apiKey?: { name: string; value: string };\n platform: NodeJS.Platform;\n};\n\n/**\n * Build a CLI's environment. Precedence, lowest first: inherited variables\n * (minus the adapter's managed home variables), the adapter plan, the API\n * key, then the caller's `env`. Windows variable names compare\n * case-insensitively.\n */\nexport function buildEnvironment(input: BuildEnvironmentInput): Record<string, string> {\n const normalize = (name: string): string =>\n input.platform === \"win32\" ? name.toUpperCase() : name;\n const managed = new Set(input.managed.map(normalize));\n const
|
|
1
|
+
{"version":3,"file":"environment.mjs","names":[],"sources":["../../../../../../../../packages/ai-cli/src/session/environment.ts"],"sourcesContent":["/**\n * Variables a CLI needs to start at all: executable lookup, home and temp\n * directories, locale, TLS/proxy settings and the Windows system set.\n * Passed through even with `inheritEnv: false`.\n */\nexport const MINIMAL_ENV = [\n \"PATH\",\n \"PATHEXT\",\n \"HOME\",\n \"USERPROFILE\",\n \"HOMEDRIVE\",\n \"HOMEPATH\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"SYSTEMROOT\",\n \"SYSTEMDRIVE\",\n \"WINDIR\",\n \"COMSPEC\",\n \"TEMP\",\n \"TMP\",\n \"TMPDIR\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TERM\",\n \"SHELL\",\n \"USER\",\n \"LOGNAME\",\n \"XDG_RUNTIME_DIR\",\n \"HTTP_PROXY\",\n \"HTTPS_PROXY\",\n \"NO_PROXY\",\n \"http_proxy\",\n \"https_proxy\",\n \"no_proxy\",\n \"NODE_EXTRA_CA_CERTS\",\n \"SSL_CERT_FILE\",\n \"SSL_CERT_DIR\",\n] as const;\n\nexport type BuildEnvironmentInput = {\n source: Record<string, string | undefined>;\n /**\n * `true` — everything; `false` — the minimal set; `\"curated\"` — the minimal\n * set plus `credentials`; a list — the minimal set plus those names.\n */\n inherit: boolean | \"curated\" | readonly string[];\n /** The adapter's own credential variables (`apiKeyEnv`), passed by `\"curated\"`. */\n credentials?: readonly string[];\n /** Variables the adapter manages (config home); never inherited from `source`. */\n managed: readonly string[];\n /** Adapter plan variables (config home, …). */\n plan?: Record<string, string>;\n /** Caller variables; win over everything else. */\n user?: Record<string, string>;\n /** API key and the variable it goes to. */\n apiKey?: { name: string; value: string };\n platform: NodeJS.Platform;\n};\n\n/**\n * Build a CLI's environment. Precedence, lowest first: inherited variables\n * (minus the adapter's managed home variables), the adapter plan, the API\n * key, then the caller's `env`. Windows variable names compare\n * case-insensitively.\n */\nexport function buildEnvironment(input: BuildEnvironmentInput): Record<string, string> {\n const normalize = (name: string): string =>\n input.platform === \"win32\" ? name.toUpperCase() : name;\n const managed = new Set(input.managed.map(normalize));\n const extra =\n input.inherit === false\n ? []\n : input.inherit === \"curated\"\n ? (input.credentials ?? [])\n : input.inherit === true\n ? []\n : input.inherit;\n const allowed =\n input.inherit === true ? undefined : new Set([...MINIMAL_ENV, ...extra].map(normalize));\n\n const environment: Record<string, string> = {};\n\n for (const [name, value] of Object.entries(input.source)) {\n if (value === undefined || managed.has(normalize(name))) {\n continue;\n }\n\n if (allowed !== undefined && !allowed.has(normalize(name))) {\n continue;\n }\n\n environment[name] = value;\n }\n\n const assign = (name: string, value: string): void => {\n if (input.platform === \"win32\") {\n for (const existing of Object.keys(environment)) {\n if (existing.toUpperCase() === name.toUpperCase()) {\n delete environment[existing];\n }\n }\n }\n\n environment[name] = value;\n };\n\n for (const [name, value] of Object.entries(input.plan ?? {})) {\n assign(name, value);\n }\n\n if (input.apiKey !== undefined) {\n assign(input.apiKey.name, input.apiKey.value);\n }\n\n for (const [name, value] of Object.entries(input.user ?? {})) {\n assign(name, value);\n }\n\n return environment;\n}\n\nlet warnedInheritedEnvironment = false;\n\n/**\n * One console warning per process when a CLI agent runs in production with\n * `inheritEnv` left at its default (`true`), which hands every server\n * variable — database URLs, signing keys, other providers' keys — to a\n * model-driven CLI.\n */\nexport function warnInheritedEnvironment(\n title: string,\n inheritEnv: boolean | \"curated\" | readonly string[] | undefined,\n env: Record<string, string | undefined>,\n): void {\n if (warnedInheritedEnvironment || inheritEnv !== undefined || env.NODE_ENV !== \"production\") {\n return;\n }\n\n warnedInheritedEnvironment = true;\n console.warn(\n `[warlock-ai-cli] ${title} receives the whole server environment because \\`inheritEnv\\` is not set (default \\`true\\`). ` +\n 'Set `inheritEnv: \"curated\"` to pass only the system variables and the CLI\\'s own API key variable, ' +\n \"or `inheritEnv: true` to keep the current behaviour and silence this warning.\",\n );\n}\n\n/** Re-arm the one-time `inheritEnv` warning. For tests. */\nexport function resetInheritedEnvironmentWarning(): void {\n warnedInheritedEnvironment = false;\n}\n"],"mappings":";;;;;;AAKA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;AA4BA,SAAgB,iBAAiB,OAAsD;CACrF,MAAM,aAAa,SACjB,MAAM,aAAa,UAAU,KAAK,YAAY,IAAI;CACpD,MAAM,UAAU,IAAI,IAAI,MAAM,QAAQ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
17
17
|
function createLineSplitter(onLine, onOverflow = () => void 0) {
|
|
18
18
|
const decoder = new StringDecoder("utf8");
|
|
19
|
-
let
|
|
19
|
+
let parts = [];
|
|
20
|
+
let pendingLength = 0;
|
|
20
21
|
let overflowed = false;
|
|
22
|
+
const takePending = (tail) => {
|
|
23
|
+
const line = parts.length === 0 ? tail : parts.join("") + tail;
|
|
24
|
+
parts = [];
|
|
25
|
+
pendingLength = 0;
|
|
26
|
+
return line;
|
|
27
|
+
};
|
|
21
28
|
const consume = (text) => {
|
|
22
|
-
|
|
23
|
-
let newline =
|
|
29
|
+
let start = 0;
|
|
30
|
+
let newline = text.indexOf("\n");
|
|
24
31
|
while (newline !== -1) {
|
|
25
|
-
const line =
|
|
26
|
-
|
|
32
|
+
const line = takePending(text.slice(start, newline)).replace(/\r$/, "");
|
|
33
|
+
start = newline + 1;
|
|
27
34
|
if (overflowed) overflowed = false;
|
|
28
35
|
else onLine(line);
|
|
29
|
-
newline =
|
|
36
|
+
newline = text.indexOf("\n", start);
|
|
37
|
+
}
|
|
38
|
+
if (start < text.length) {
|
|
39
|
+
parts.push(start === 0 ? text : text.slice(start));
|
|
40
|
+
pendingLength += text.length - start;
|
|
30
41
|
}
|
|
31
|
-
if (
|
|
32
|
-
|
|
42
|
+
if (pendingLength > 33554432) {
|
|
43
|
+
parts = [];
|
|
44
|
+
pendingLength = 0;
|
|
33
45
|
if (!overflowed) {
|
|
34
46
|
overflowed = true;
|
|
35
47
|
onOverflow();
|
|
@@ -42,8 +54,8 @@ function createLineSplitter(onLine, onOverflow = () => void 0) {
|
|
|
42
54
|
},
|
|
43
55
|
end() {
|
|
44
56
|
consume(decoder.end());
|
|
45
|
-
|
|
46
|
-
|
|
57
|
+
const rest = takePending("");
|
|
58
|
+
if (rest.length > 0 && !overflowed) onLine(rest.replace(/\r$/, ""));
|
|
47
59
|
}
|
|
48
60
|
};
|
|
49
61
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"line-splitter.mjs","names":[],"sources":["../../../../../../../../packages/ai-cli/src/stream/line-splitter.ts"],"sourcesContent":["import { StringDecoder } from \"node:string_decoder\";\n\n/** Longest line kept in memory; a longer one is dropped (reported via `onOverflow`). */\nexport const MAX_LINE_BYTES = 32 * 1024 * 1024;\n\n/**\n * Split a byte stream into lines. Multi-byte UTF-8 characters split across\n * chunks are decoded correctly, `\\r\\n` and `\\n` both end a line, and a final\n * line without a newline is flushed by `end()`.\n *\n * @example\n * const splitter = createLineSplitter((line) => console.log(line));\n * splitter.write(Buffer.from('{\"a\":1}\\n{\"b\"'));\n * splitter.write(Buffer.from(\":2}\\n\"));\n * splitter.end();\n */\nexport function createLineSplitter(\n onLine: (line: string) => void,\n onOverflow: () => void = () => undefined,\n): { write(chunk: Buffer): void; end(): void } {\n const decoder = new StringDecoder(\"utf8\");\n let
|
|
1
|
+
{"version":3,"file":"line-splitter.mjs","names":[],"sources":["../../../../../../../../packages/ai-cli/src/stream/line-splitter.ts"],"sourcesContent":["import { StringDecoder } from \"node:string_decoder\";\n\n/** Longest line kept in memory; a longer one is dropped (reported via `onOverflow`). */\nexport const MAX_LINE_BYTES = 32 * 1024 * 1024;\n\n/**\n * Split a byte stream into lines. Multi-byte UTF-8 characters split across\n * chunks are decoded correctly, `\\r\\n` and `\\n` both end a line, and a final\n * line without a newline is flushed by `end()`.\n *\n * @example\n * const splitter = createLineSplitter((line) => console.log(line));\n * splitter.write(Buffer.from('{\"a\":1}\\n{\"b\"'));\n * splitter.write(Buffer.from(\":2}\\n\"));\n * splitter.end();\n */\nexport function createLineSplitter(\n onLine: (line: string) => void,\n onOverflow: () => void = () => undefined,\n): { write(chunk: Buffer): void; end(): void } {\n const decoder = new StringDecoder(\"utf8\");\n // The unfinished line, kept as parts and joined only when its newline\n // arrives, so each chunk is scanned once however long the line grows.\n let parts: string[] = [];\n let pendingLength = 0;\n let overflowed = false;\n\n const takePending = (tail: string): string => {\n const line = parts.length === 0 ? tail : parts.join(\"\") + tail;\n\n parts = [];\n pendingLength = 0;\n\n return line;\n };\n\n const consume = (text: string): void => {\n let start = 0;\n let newline = text.indexOf(\"\\n\");\n\n while (newline !== -1) {\n const line = takePending(text.slice(start, newline)).replace(/\\r$/, \"\");\n\n start = newline + 1;\n\n if (overflowed) {\n overflowed = false;\n } else {\n onLine(line);\n }\n\n newline = text.indexOf(\"\\n\", start);\n }\n\n if (start < text.length) {\n parts.push(start === 0 ? text : text.slice(start));\n pendingLength += text.length - start;\n }\n\n if (pendingLength > MAX_LINE_BYTES) {\n parts = [];\n pendingLength = 0;\n\n if (!overflowed) {\n overflowed = true;\n onOverflow();\n }\n }\n };\n\n return {\n write(chunk: Buffer): void {\n consume(decoder.write(chunk));\n },\n end(): void {\n consume(decoder.end());\n\n const rest = takePending(\"\");\n\n if (rest.length > 0 && !overflowed) {\n onLine(rest.replace(/\\r$/, \"\"));\n }\n },\n };\n}\n"],"mappings":";;;;AAGA,MAAa,iBAAiB;;;;;;;;;;;;AAa9B,SAAgB,mBACd,QACA,mBAA+B,QACc;CAC7C,MAAM,UAAU,IAAI,cAAc,MAAM;CAGxC,IAAI,QAAkB,CAAC;CACvB,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,eAAe,SAAyB;EAC5C,MAAM,OAAO,MAAM,WAAW,IAAI,OAAO,MAAM,KAAK,EAAE,IAAI;EAE1D,QAAQ,CAAC;EACT,gBAAgB;EAEhB,OAAO;CACT;CAEA,MAAM,WAAW,SAAuB;EACtC,IAAI,QAAQ;EACZ,IAAI,UAAU,KAAK,QAAQ,IAAI;EAE/B,OAAO,YAAY,IAAI;GACrB,MAAM,OAAO,YAAY,KAAK,MAAM,OAAO,OAAO,CAAC,CAAC,CAAC,QAAQ,OAAO,EAAE;GAEtE,QAAQ,UAAU;GAElB,IAAI,YACF,aAAa;QAEb,OAAO,IAAI;GAGb,UAAU,KAAK,QAAQ,MAAM,KAAK;EACpC;EAEA,IAAI,QAAQ,KAAK,QAAQ;GACvB,MAAM,KAAK,UAAU,IAAI,OAAO,KAAK,MAAM,KAAK,CAAC;GACjD,iBAAiB,KAAK,SAAS;EACjC;EAEA,IAAI,0BAAgC;GAClC,QAAQ,CAAC;GACT,gBAAgB;GAEhB,IAAI,CAAC,YAAY;IACf,aAAa;IACb,WAAW;GACb;EACF;CACF;CAEA,OAAO;EACL,MAAM,OAAqB;GACzB,QAAQ,QAAQ,MAAM,KAAK,CAAC;EAC9B;EACA,MAAY;GACV,QAAQ,QAAQ,IAAI,CAAC;GAErB,MAAM,OAAO,YAAY,EAAE;GAE3B,IAAI,KAAK,SAAS,KAAK,CAAC,YACtB,OAAO,KAAK,QAAQ,OAAO,EAAE,CAAC;EAElC;CACF;AACF"}
|
package/llms-full.txt
CHANGED
|
@@ -186,6 +186,8 @@ console.log((await session.done()).text);
|
|
|
186
186
|
|
|
187
187
|
The adapter's home variable (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME`, `GROK_HOME`, …) is pointed at it.
|
|
188
188
|
|
|
189
|
+
**Environment.** `inheritEnv` decides which server variables the CLI sees. `true` (default) passes everything, so a model-driven CLI can read database URLs and signing keys. `"curated"` passes the minimal system set plus the adapter's own API key variables (`apiKeyEnv`); `false` passes the minimal set only; a list passes the minimal set plus those names. Prefer `"curated"` and add anything else through `env`. In production an unset `inheritEnv` logs a one-time warning; set `true` explicitly to keep the old behaviour without it.
|
|
190
|
+
|
|
189
191
|
## Use a CLI as an `ai.agent` model
|
|
190
192
|
|
|
191
193
|
```ts
|
package/package.json
CHANGED
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
"directory": "packages/ai-cli"
|
|
21
21
|
},
|
|
22
22
|
"peerDependencies": {
|
|
23
|
-
"@warlock.js/ai": "5.
|
|
23
|
+
"@warlock.js/ai": "5.53.1"
|
|
24
24
|
},
|
|
25
|
-
"version": "5.
|
|
25
|
+
"version": "5.53.1",
|
|
26
26
|
"main": "./cjs/index.cjs",
|
|
27
27
|
"module": "./esm/index.mjs",
|
|
28
28
|
"types": "./esm/index.d.mts",
|
|
@@ -152,6 +152,8 @@ console.log((await session.done()).text);
|
|
|
152
152
|
|
|
153
153
|
The adapter's home variable (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `COPILOT_HOME`, `GROK_HOME`, …) is pointed at it.
|
|
154
154
|
|
|
155
|
+
**Environment.** `inheritEnv` decides which server variables the CLI sees. `true` (default) passes everything, so a model-driven CLI can read database URLs and signing keys. `"curated"` passes the minimal system set plus the adapter's own API key variables (`apiKeyEnv`); `false` passes the minimal set only; a list passes the minimal set plus those names. Prefer `"curated"` and add anything else through `env`. In production an unset `inheritEnv` logs a one-time warning; set `true` explicitly to keep the old behaviour without it.
|
|
156
|
+
|
|
155
157
|
## Use a CLI as an `ai.agent` model
|
|
156
158
|
|
|
157
159
|
```ts
|