@agentchatme/agent-core 0.3.1 → 0.4.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/presets/claude-code.ts","../src/presets/semver.ts","../src/presets/types.ts","../src/presets/codex.ts","../src/presets/index.ts"],"sourcesContent":["import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { clientHeadersOf } from '../client-identity.js'\nimport { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunRequest, RunRunner } from '../integration/runner.js'\nimport { spawnRun } from '../integration/spawn-run.js'\nimport { atomicWriteFile } from '../util/fsutil.js'\nimport { log } from '../util/log.js'\nimport { spawnCommandSync } from '../util/spawn.js'\nimport { VERSION } from '../version.js'\nimport { semverAtLeast } from './semver.js'\nimport { withoutInheritedKey, type Preset, type PresetContext, type PresetInspection } from './types.js'\n\n// ─── Claude Code: one headless run (`claude -p`) ────────────────────────────\n//\n// `claude -p` on the box, riding the user's own Claude Code sign-in and user\n// configuration. The run's output is discarded by `spawnRun`: the agent's only\n// way to say anything on AgentChat is the hosted send tool during the run.\n//\n// The flags, verified against `claude --help` (2.1.316) and\n// code.claude.com/docs/en/cli-reference.md, headless.md, permission-modes.md:\n//\n// --permission-prompts none anything that would prompt is denied, never\n// waited on; the permission mode and allow rules\n// still decide every call first (v2.1.259+).\n// --tools <list> restricts the BUILT-IN tool set; does not affect\n// MCP tools. Listing Glob/Grep explicitly provides\n// the dedicated search tools.\n// --allowedTools <rules> pre-approves. `mcp__agentchat__*` is the whole\n// hosted server; `Bash` pre-approves every shell\n// command (dropped as a broad rule only in auto mode).\n// --disallowedTools <rules> denies. Deny rules win over allow rules, and a\n// `Read(<path>)` rule covers every built-in tool\n// that reads files (Read, Grep, Glob — docs:\n// permissions.md \"Read & Edit\"). Used to keep a\n// run's file tools off the key store. `//`\n// prefixes an absolute path in rule syntax.\n// --permission-mode default Manual: reads need no approval, everything else\n// prompts (and is therefore denied here).\n// --permission-mode acceptEdits file edits and common filesystem commands in\n// the working directory need no approval.\n// --dangerously-skip-permissions = bypassPermissions.\n// --mcp-config <file> --strict-mcp-config\n// the hosted server from a file, and ONLY it: a\n// listener's run acts as the listener's agent,\n// never as whatever key the user scope registers.\n//\n// Whatever the profile, every AgentChat hosted tool is pre-approved: the run\n// exists to read the tray and decide or send through them.\n\nexport const CLAUDE_CODE_PRESET = 'claude-code'\n\n/**\n * Two flags set the floor:\n * * `--permission-prompts none` — Claude Code v2.1.259.\n * * `CLAUDE_CODE_MCP_STARTUP_WAIT_MS` — bounds how long the first\n * non-interactive turn waits for the MCP servers `--allowedTools` names to\n * connect. Added in v2.1.274. Without it a run could start before the\n * hosted inbox tool is there.\n */\nexport const MIN_CLAUDE_CODE_VERSION = '2.1.274'\n\n/** The MCP server name the runs see; every hosted tool is `mcp__agentchat__<tool>`, as the served texts spell them. */\nexport const CLAUDE_MCP_SERVER_NAME = 'agentchat'\nexport const AGENTCHAT_TOOL_ALLOW = `mcp__${CLAUDE_MCP_SERVER_NAME}__*`\n\n/** Built-in tools an `answer` run keeps: read-only files plus the web. */\nexport const ANSWER_TOOLS = ['Read', 'Glob', 'Grep', 'WebSearch', 'WebFetch'] as const\n\n/** Built-in tools a `work` run additionally pre-approves. */\nexport const WORK_TOOLS = ['Bash', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit'] as const\n\n/** Env a parent Claude Code session leaks that would make the child think it is nested. */\nexport const PARENT_ENV_KEYS = [\n 'CLAUDECODE',\n 'CLAUDE_CODE_CHILD_SESSION',\n 'CLAUDE_CODE_SESSION_ID',\n 'CLAUDE_CODE_ENTRYPOINT',\n 'CLAUDE_CODE_EXECPATH',\n 'CLAUDE_CODE_EFFORT_LEVEL',\n 'CLAUDE_EFFORT',\n 'AI_AGENT',\n]\n\n/**\n * How long the first turn of a `-p` run waits for a still-connecting MCP\n * server that `--allowedTools` names. Claude Code's own built-in wait is short\n * (2 s since 2.1.284), and a remote server over a cold network can take\n * longer; the run must not start without the inbox tool.\n */\nconst MCP_STARTUP_WAIT_MS = '15000'\n\n/** Claude Code's supported relocation knob. Unset is NOT the same as `~/.claude`. */\nexport function claudeConfigDirFrom(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const override = env['CLAUDE_CONFIG_DIR']\n return override !== undefined && override.trim().length > 0 ? path.resolve(override) : undefined\n}\n\n/** `~/.claude`, or the relocated config dir. */\nexport function claudeHomeFor(configDirOverride: string | undefined): string {\n return configDirOverride ?? path.join(os.homedir(), '.claude')\n}\n\n/**\n * Where Claude Code keeps user-scoped MCP servers (and so any key registered\n * there): `~/.claude.json`, or `$CLAUDE_CONFIG_DIR/.claude.json`.\n */\nexport function claudeUserStatePathFor(configDirOverride: string | undefined): string {\n return configDirOverride !== undefined ? path.join(configDirOverride, '.claude.json') : path.join(os.homedir(), '.claude.json')\n}\n\nfunction claudeProcessEnv(configDirOverride: string | undefined, source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env = { ...source }\n if (configDirOverride === undefined) delete env['CLAUDE_CONFIG_DIR']\n else env['CLAUDE_CONFIG_DIR'] = configDirOverride\n return env\n}\n\nexport function buildClaudeEnv(configDirOverride: string | undefined, source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const env = claudeProcessEnv(configDirOverride, source)\n for (const key of PARENT_ENV_KEYS) delete env[key]\n env['DISABLE_AUTOUPDATER'] = '1'\n const wait = Number(env['CLAUDE_CODE_MCP_STARTUP_WAIT_MS'])\n if (!Number.isFinite(wait) || wait < Number(MCP_STARTUP_WAIT_MS)) env['CLAUDE_CODE_MCP_STARTUP_WAIT_MS'] = MCP_STARTUP_WAIT_MS\n return env\n}\n\n/**\n * Is Claude Code signed in? `claude auth status` prints JSON with a boolean\n * `loggedIn` and exits 0 if logged in, 1 if not. When that JSON is there it is\n * the answer. The file/keychain probes are a fallback for builds without the\n * subcommand; the keychain probe is existence-only and never prompts — a\n * resident listener must never trigger a keychain prompt.\n */\nexport function claudeIsLoggedIn(configDirOverride?: string, command = 'claude'): boolean {\n const status = spawnCommandSync(command, ['auth', 'status'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: claudeProcessEnv(configDirOverride, process.env),\n })\n if (!status.error) {\n try {\n const parsed = JSON.parse(String(status.stdout ?? '').trim()) as { loggedIn?: unknown }\n if (typeof parsed?.loggedIn === 'boolean') return parsed.loggedIn\n } catch {\n /* no JSON: an older build; fall through to the file and keychain */\n }\n if (status.status === 0) return true\n }\n\n const configDir = claudeHomeFor(configDirOverride)\n if (fs.existsSync(path.join(configDir, '.credentials.json'))) return true\n if (process.platform !== 'darwin') return false\n const keychain = spawnCommandSync('security', ['find-generic-password', '-s', 'Claude Code-credentials'], {\n encoding: 'utf-8',\n timeout: 5_000,\n })\n return !keychain.error && keychain.status === 0\n}\n\nexport function inspectClaudeRuntime(configDirOverride?: string, command = 'claude'): PresetInspection {\n const version = spawnCommandSync(command, ['--version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: claudeProcessEnv(configDirOverride, process.env),\n })\n if (version.error) return { ok: false, detail: `claude CLI not found on PATH (${version.error.message})` }\n const rendered = String(version.stdout || version.stderr).trim()\n if (version.status !== 0) return { ok: false, detail: rendered || `claude --version exited ${version.status}` }\n return semverAtLeast(rendered, MIN_CLAUDE_CODE_VERSION)\n ? { ok: true, detail: rendered }\n : {\n ok: false,\n detail: `${rendered || 'unrecognized version'}; AgentChat requires Claude Code >= ${MIN_CLAUDE_CODE_VERSION} (for --permission-prompts none and CLAUDE_CODE_MCP_STARTUP_WAIT_MS)`,\n }\n}\n\n/**\n * The entry of `denied` that is `dir` or contains it, or null. Whole path\n * segments only: `~/.claude/agentchat` does not contain `~/.claude/agentchat-workdir`.\n */\nexport function deniedAncestorOf(dir: string, denied: readonly string[]): string | null {\n const target = path.resolve(dir)\n for (const raw of denied) {\n const root = path.resolve(raw)\n if (target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) return root\n }\n return null\n}\n\nexport function claudeProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\n case 'answer':\n return [\n '--permission-mode',\n 'default',\n '--permission-prompts',\n 'none',\n '--tools',\n ANSWER_TOOLS.join(','),\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS].join(','),\n ]\n case 'work':\n return [\n '--permission-mode',\n 'acceptEdits',\n '--permission-prompts',\n 'none',\n '--allowedTools',\n [AGENTCHAT_TOOL_ALLOW, ...ANSWER_TOOLS, ...WORK_TOOLS].join(','),\n ]\n case 'full':\n return ['--dangerously-skip-permissions', '--permission-prompts', 'none', '--allowedTools', AGENTCHAT_TOOL_ALLOW]\n }\n}\n\nexport interface ClaudeRunArgOptions {\n /** `AGENTCHAT_RUN_MAX_BUDGET_USD`: stop the run once estimated spend reaches this (print mode only). */\n readonly maxBudgetUsd?: string | undefined\n /**\n * Absolute paths the run's file tools may not read (a directory covers its\n * tree). Rendered as `Read(//<path>)` / `Read(//<dir>/**)` deny rules. A\n * prompt-injected run could otherwise read the key and send it; the wake\n * text should not be the only guard. POSIX paths only — on Windows the\n * rule syntax for drive paths is undocumented, so nothing is rendered.\n */\n readonly denyReadPaths?: readonly string[] | undefined\n /**\n * A `--mcp-config` file holding the hosted server with the agent's key;\n * with it, `--strict-mcp-config` makes it the run's only MCP server. Absent:\n * the run uses the user-scope server the integration registered.\n */\n readonly mcpConfigPath?: string | undefined\n}\n\n/** Whether a path can be carried by a `Read(//<path>)` rule in a comma/space-separated list: absolute POSIX, no comma, no whitespace. */\nfunction expressible(raw: string): boolean {\n return raw.startsWith('/') && !/[,\\s]/.test(raw)\n}\n\n/**\n * The deny paths no rule can carry: on Windows all of them (the rule syntax\n * for drive paths is undocumented), elsewhere a relative path or one with a\n * comma or whitespace. A run would be able to read these.\n */\nexport function inexpressibleDenyPaths(paths: readonly string[]): string[] {\n return process.platform === 'win32' ? [...paths] : paths.filter((p) => !expressible(p))\n}\n\n/** `/Users/x/.claude/agentchat` → `Read(//Users/x/.claude/agentchat/**)` and `Read(//Users/x/.claude/agentchat)`. Paths no rule can carry are left out (`inexpressibleDenyPaths`). */\nexport function readDenyRules(paths: readonly string[]): string[] {\n if (process.platform === 'win32') return []\n const rules: string[] = []\n for (const raw of paths) {\n if (!expressible(raw)) continue\n const clean = raw.replace(/\\/+$/, '')\n rules.push(`Read(/${clean})`, `Read(/${clean}/**)`)\n }\n return rules\n}\n\n/**\n * The full argument list for one headless run. The prompt goes on STDIN, not\n * as a positional: the variadic `--allowedTools` (and `--mcp-config`) would\n * otherwise swallow a trailing positional (verified on 2.1.220; `cat file |\n * claude -p` is the documented piped form).\n */\nexport function claudeRunArgs(profile: RunProfile, options: ClaudeRunArgOptions = {}): string[] {\n const budget = options.maxBudgetUsd?.trim()\n const deny = readDenyRules(options.denyReadPaths ?? [])\n return [\n '-p',\n '--output-format',\n 'text',\n // A wake run is not a conversation to resume; keep it out of the user's\n // session list and off the disk.\n '--no-session-persistence',\n ...(budget !== undefined && /^\\d+(\\.\\d+)?$/.test(budget) ? ['--max-budget-usd', budget] : []),\n // Variadic, so it is closed by the boolean flag right after it.\n ...(options.mcpConfigPath !== undefined ? ['--mcp-config', options.mcpConfigPath, '--strict-mcp-config'] : []),\n ...claudeProfileArgs(profile),\n // Last: the option is variadic and the prompt arrives on stdin, so there\n // is no positional for it to swallow.\n ...(deny.length > 0 ? ['--disallowedTools', deny.join(',')] : []),\n ]\n}\n\n/** The `--mcp-config` document: the hosted server, by HTTP, with the agent's key. Owner-only on disk. */\n/**\n * The `--mcp-config` file a listener's run is given: the hosted tool server\n * with this agent's key, and the client headers that name the runtime to it\n * (`X-AgentChat-Client: claude-code`, `-Version`: the front door that placed\n * the run). The hosted tool server names a client only from these headers:\n * without them a run is an unknown client and is shown the wake-webhook\n * tools, a second way of being woken that the listener makes unnecessary.\n */\nexport function claudeMcpConfig(apiBase: string, apiKey: string, clientVersion: string = VERSION): string {\n const headers = { Authorization: `Bearer ${apiKey}`, ...clientHeadersOf({ runtime: 'claude-code', version: clientVersion }) }\n return `${JSON.stringify({ mcpServers: { [CLAUDE_MCP_SERVER_NAME]: { type: 'http', url: hostedMcpUrl(apiBase), headers } } }, null, 2)}\\n`\n}\n\nexport interface ClaudeRunnerOptions {\n readonly configDir: string | undefined\n /**\n * The run's working directory; the `work` profile edits and runs shell here.\n * Must lie outside `denyReadPaths`, or the run cannot read its own cwd —\n * preflight says so once and still runs.\n */\n readonly workdir: string\n readonly profile: RunProfile\n /** Paths every run's file tools are denied: the key store (identity home, the user-scope MCP state). */\n readonly denyReadPaths: readonly string[]\n /** See `ClaudeRunArgOptions.mcpConfigPath`. */\n readonly mcpConfigPath?: string\n /** The one-line fix printed when the workdir sits inside a denied path. */\n readonly workdirAdvice?: string\n /**\n * A deny path no rule can carry (a comma or whitespace in it; every path on\n * Windows): `warn` (default) logs it once and runs — the run can then read\n * that path; `refuse` fails preflight with the reason, so no run starts.\n */\n readonly inexpressibleDeny?: 'warn' | 'refuse'\n /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n}\n\nexport class ClaudeRunner implements RunRunner {\n readonly name = 'claude'\n private readonly command: string\n /** The workdir warning is one line per process, not one per preflight (preflight repeats every few minutes). */\n private warnedWorkdir = false\n private warnedDeny = false\n\n constructor(private readonly options: ClaudeRunnerOptions) {\n this.command = options.command ?? 'claude'\n }\n\n /** The denied path the configured workdir sits in, or null when the run can read its own cwd. */\n workdirDeniedBy(): string | null {\n return deniedAncestorOf(this.options.workdir, this.options.denyReadPaths)\n }\n\n async preflight(): Promise<RunPreflight> {\n const runtime = inspectClaudeRuntime(this.options.configDir, this.command)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n if (!claudeIsLoggedIn(this.options.configDir, this.command)) {\n return { ok: false, detail: 'claude is not signed in (run `claude` once and sign in)' }\n }\n // A cwd inside the key store is an operator choice the deny rules then\n // make unreadable to the run. Said once, with the fix; the run still\n // starts — the hosted tools do not need the cwd.\n const denied = this.workdirDeniedBy()\n if (denied !== null && !this.warnedWorkdir) {\n this.warnedWorkdir = true\n log.warn(\n `the run workdir ${this.options.workdir} is inside ${denied}, which every run's file tools are denied: runs cannot read their own working directory.${this.options.workdirAdvice ? ` ${this.options.workdirAdvice}` : ''}`,\n )\n }\n const uncovered = inexpressibleDenyPaths(this.options.denyReadPaths)\n if (uncovered.length > 0) {\n const why =\n process.platform === 'win32'\n ? `Claude Code's rule syntax for Windows paths is undocumented, so no read-deny rule is given for ${uncovered.join(', ')}`\n : `no read-deny rule can carry ${uncovered.join(', ')} (a comma or whitespace in the path)`\n if (this.options.inexpressibleDeny === 'refuse') return { ok: false, detail: `${why}: a run could read the key there. Use an identity home whose path has no comma or whitespace (--home).` }\n if (!this.warnedDeny) {\n this.warnedDeny = true\n log.warn(`${why}: runs can read those paths.`)\n }\n }\n if (this.options.mcpConfigPath !== undefined && !fs.existsSync(this.options.mcpConfigPath)) {\n return { ok: false, detail: `the hosted tool config ${this.options.mcpConfigPath} is missing` }\n }\n // Owner-only on creation, as the identity home is. Creation only: an\n // operator's own workspace keeps its permissions.\n fs.mkdirSync(this.options.workdir, { recursive: true, mode: 0o700 })\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. */\n args(): string[] {\n return claudeRunArgs(this.options.profile, {\n maxBudgetUsd: (this.options.env ?? process.env)['AGENTCHAT_RUN_MAX_BUDGET_USD'],\n denyReadPaths: this.options.denyReadPaths,\n mcpConfigPath: this.options.mcpConfigPath,\n })\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const args = this.args()\n log.debug(`claude ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.options.workdir,\n env: buildClaudeEnv(this.options.configDir, this.options.env ?? process.env),\n stdin: request.prompt,\n budgetMs: request.budgetMs,\n // Stopping SIGTERMs this run's process group instead of orphaning it.\n ...(request.signal ? { signal: request.signal } : {}),\n // The engine records a group invite as offered the moment the process\n // has spawned, so a run cut short still counts as the one offer.\n ...(request.onStarted ? { onStarted: request.onStarted } : {}),\n })\n }\n}\n\n/** Where a listener keeps the `--mcp-config` file for this preset, inside its identity home. */\nexport function claudeMcpConfigPath(home: string): string {\n return path.join(home, 'presets', `${CLAUDE_CODE_PRESET}.mcp.json`)\n}\n\nexport const claudeCodePreset: Preset = {\n name: CLAUDE_CODE_PRESET,\n describeMcp({ home, apiBase }) {\n return [\n `--mcp-config ${claudeMcpConfigPath(home)} (owner-only): ${CLAUDE_MCP_SERVER_NAME} → ${hostedMcpUrl(apiBase)}, Authorization: Bearer <this home's key>, X-AgentChat-Client: claude-code`,\n '--strict-mcp-config: no other MCP server (user, project or plugin) is loaded in these runs',\n ]\n },\n label: 'Claude Code',\n runtime: 'claude-code',\n // Every run's file tools are denied the identity home.\n serviceEnv: ['CLAUDE_CONFIG_DIR'],\n readsIdentityHome: false,\n inspect(env = process.env, command = 'claude') {\n const configDir = claudeConfigDirFrom(env)\n const runtime = inspectClaudeRuntime(configDir, command)\n if (!runtime.ok) return runtime\n return claudeIsLoggedIn(configDir, command)\n ? { ok: true, detail: `${runtime.detail}, signed in` }\n : { ok: false, detail: `${runtime.detail}, not signed in (run \\`claude\\` once and sign in)` }\n },\n runner(ctx: PresetContext): RunRunner {\n // A key in the listener's own environment is not handed to its runs.\n const env = withoutInheritedKey(ctx.env ?? process.env)\n const configDir = claudeConfigDirFrom(env)\n const mcpConfigPath = claudeMcpConfigPath(ctx.home)\n // Rewritten for every identity the listener serves: the runs act as THIS agent.\n atomicWriteFile(mcpConfigPath, claudeMcpConfig(ctx.apiBase, ctx.apiKey, ctx.clientVersion ?? VERSION), 0o600)\n return new ClaudeRunner({\n configDir,\n workdir: ctx.workdir,\n profile: ctx.profile,\n // The listener's home (its key and this file), the user-scope MCP state\n // and an integration's identity home beside it: no run reads a key.\n denyReadPaths: [ctx.home, claudeUserStatePathFor(configDir), path.join(claudeHomeFor(configDir), 'agentchat')],\n mcpConfigPath,\n workdirAdvice: 'Start the listener from a directory outside it, or pass --workdir.',\n // On POSIX a listener's run must not start with its key readable; on\n // Windows no rule exists at all (documented), so it warns.\n inexpressibleDeny: process.platform === 'win32' ? 'warn' : 'refuse',\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n })\n },\n}\n","/** `actual` (any text containing `x.y.z`) is at least `minimum`. False when either has no version in it. */\nexport function semverAtLeast(actual: string, minimum: string): boolean {\n const parse = (value: string): [number, number, number] | null => {\n const match = value.match(/(\\d+)\\.(\\d+)\\.(\\d+)/)\n return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null\n }\n const a = parse(actual)\n const b = parse(minimum)\n if (a === null || b === null) return false\n for (let index = 0; index < 3; index++) {\n if (a[index] !== b[index]) return (a[index] ?? 0) > (b[index] ?? 0)\n }\n return true\n}\n","import type { TextsRuntime } from 'agentchatme'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunRunner } from '../integration/runner.js'\n\n// ─── Presets: how to start one headless run of a known coding agent ─────────\n//\n// The engine (everything in this package outside `presets/`) names no coding\n// agent and never imports from here; `tests/core-is-host-agnostic`\n// asserts both. A preset is the one place that does: the flags a runtime's\n// headless mode takes per run profile, how to tell it is installed and signed\n// in, and how a run of it reaches the hosted AgentChat tools AS a given agent.\n//\n// Two front doors select one, and only ever for the run command: the\n// `agentchat listen --preset <name>` listener (@agentchatme/cli; its identity\n// is the listener's own home, injected into each run), and the runtime's own\n// integration package (its identity home and placement stay the integration's). A preset\n// never decides which identity home is acted on — the caller passes it.\n\n/** What a preset needs to build a runner acting as one agent. */\nexport interface PresetContext {\n /** The identity home of the agent the runs act as. Runs' file tools are kept off it where the runtime allows. */\n readonly home: string\n /** The run's working directory. */\n readonly workdir: string\n readonly profile: RunProfile\n /** The agent's key and API base, for the hosted tool server the runs reach. Never put on argv. */\n readonly apiKey: string\n readonly apiBase: string\n /** The environment runs inherit (defaults to `process.env`). */\n readonly env?: NodeJS.ProcessEnv\n /** Test seam: the runtime's binary. */\n readonly command?: string\n /**\n * The version the runs name in `X-AgentChat-Client-Version`: the front door\n * that placed them (the `agentchat` listener passes its own). Defaults to\n * this engine's version. The client name is the runtime's (`claude-code`,\n * `codex`): a run the listener wakes needs no wake-webhook tools, and the\n * hosted tools spell their names per runtime by it.\n */\n readonly clientVersion?: string\n}\n\nexport interface PresetInspection {\n readonly ok: boolean\n readonly detail: string\n}\n\nexport interface Preset {\n /** The name a user types (`--preset <name>`). */\n readonly name: string\n /** Human name for output. */\n readonly label: string\n /** How the served texts spell the hosted tools for this runtime (`GET /v1/texts?runtime=`). */\n readonly runtime: TextsRuntime\n /** Is the runtime installed, new enough and signed in? For `doctor` and `status`. */\n inspect(env?: NodeJS.ProcessEnv, command?: string): PresetInspection\n /**\n * A runner whose runs act as the agent in `ctx`: the hosted tool server is\n * given to each run with that agent's key (a file or an environment\n * variable, never an argument), whatever the runtime's own configuration\n * registers. May write owner-only files into `ctx.home`.\n */\n runner(ctx: PresetContext): RunRunner\n /**\n * The hosted-tool configuration a listener's run of this preset sees, as\n * lines for `doctor` (keys never printed): what the run is given, and what\n * of the user's own configuration still applies.\n */\n describeMcp(ctx: { readonly home: string; readonly apiBase: string; readonly env?: NodeJS.ProcessEnv }): string[]\n /** Variables a service must capture for this runtime (where it keeps its config, when relocated). */\n readonly serviceEnv: readonly string[]\n /** Whether the run can read files under the identity home (decides how the manual is pointed to). */\n readonly readsIdentityHome: boolean\n}\n\n/** The environment a listener's preset runs inherit: the caller's, minus any `AGENTCHAT_API_KEY` in it. */\nexport function withoutInheritedKey(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const copy = { ...env }\n delete copy['AGENTCHAT_API_KEY']\n return copy\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { clientHeadersOf } from '../client-identity.js'\nimport { hostedMcpUrl } from '../integration/mcp-probe.js'\nimport type { RunProfile } from '../integration/profile.js'\nimport type { RunOutcome, RunPreflight, RunRequest, RunRunner } from '../integration/runner.js'\nimport { spawnRun } from '../integration/spawn-run.js'\nimport { log } from '../util/log.js'\nimport { spawnCommandSync } from '../util/spawn.js'\nimport { VERSION } from '../version.js'\nimport { semverAtLeast } from './semver.js'\nimport { withoutInheritedKey, type Preset, type PresetContext, type PresetInspection } from './types.js'\n\n// ─── Codex: one headless run (`codex exec`) ─────────────────────────────────\n//\n// `codex exec` on the box, riding the user's own Codex sign-in and config. The\n// run's output is discarded by `spawnRun`. Flags, verified against `codex exec\n// --help` (codex-cli 0.154.0) and the openai/codex sources:\n//\n// -s, --sandbox read-only|workspace-write|danger-full-access\n// the sandbox policy for model-generated commands\n// --dangerously-bypass-approvals-and-sandbox\n// skip all confirmation prompts and run unsandboxed\n// -c approval_policy=\"never\" `codex exec` already defaults to `never` in\n// headless mode — passed explicitly so a run can\n// never wait on an approval, whatever a profile\n// or requirements file says.\n// -c mcp_servers.<name>.<key>=… per-run config overrides (TOML values): how a\n// listener points the hosted server at its own\n// agent's key, whatever config.toml registers.\n// --json events as JSONL on stdout (discarded; the first\n// event is how \"started\" is told from \"never got\n// going\")\n// --skip-git-repo-check the run's working directory is not a repository\n// --ephemeral no session files on disk for a wake run\n// -C <dir> the working root\n//\n// The hosted AgentChat tools reach the run through `[mcp_servers.agentchat]`\n// (bearer token from an environment variable named in the config, never the\n// key itself), with `default_tools_approval_mode = \"approve\"` so they never\n// prompt. Web search follows the user's own `web_search` setting.\n\nexport const CODEX_PRESET = 'codex'\n\n/** `--ephemeral`, `--sandbox`, `-C`, `--json` all exist on this version; older builds were not checked. */\nexport const MIN_CODEX_VERSION = '0.154.0'\n\n/** The `[mcp_servers.<name>]` table the runs use; tools are `mcp__agentchat__<tool>`, as the served texts spell them. */\nexport const CODEX_MCP_SERVER_NAME = 'agentchat'\n\n/**\n * The variable a listener's runs read the bearer token from. Deliberately not\n * `AGENTCHAT_API_KEY`: Codex loads `$CODEX_HOME/.env` at startup, where an\n * installed integration keeps ITS agent's key under that name.\n */\nexport const LISTENER_KEY_ENV = 'AGENTCHAT_LISTENER_API_KEY'\n\n/**\n * The final positional argument: `-` tells `codex exec` to read its\n * instructions from stdin (\"If not provided as an argument (or if `-` is\n * used), instructions are read from stdin\").\n */\nexport const CODEX_PROMPT_FROM_STDIN = '-'\n\n/** Codex's config root. Honouring CODEX_HOME matters: users relocate it. */\nexport function codexHomeFrom(env: NodeJS.ProcessEnv = process.env): string {\n const override = env['CODEX_HOME']\n if (override !== undefined && override.trim().length > 0) return path.resolve(override)\n return path.join(os.homedir(), '.codex')\n}\n\nexport function inspectCodexRuntime(codexHome: string, command = 'codex'): PresetInspection {\n const result = spawnCommandSync(command, ['--version'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, CODEX_HOME: codexHome },\n })\n if (result.error) return { ok: false, detail: `codex CLI not found on PATH (${result.error.message})` }\n const rendered = String(result.stdout || result.stderr).trim()\n if (result.status !== 0) return { ok: false, detail: rendered || `codex --version exited ${result.status}` }\n return semverAtLeast(rendered, MIN_CODEX_VERSION)\n ? { ok: true, detail: rendered }\n : { ok: false, detail: `${rendered || 'unrecognized version'}; AgentChat requires Codex >= ${MIN_CODEX_VERSION}` }\n}\n\n/** `codex login status` exits 0 when signed in. */\nexport function codexIsLoggedIn(codexHome: string, command = 'codex'): PresetInspection {\n const status = spawnCommandSync(command, ['login', 'status'], {\n encoding: 'utf-8',\n timeout: 10_000,\n windowsHide: true,\n env: { ...process.env, CODEX_HOME: codexHome },\n })\n if (status.error) return { ok: false, detail: status.error.message }\n const detail = `${status.stdout ?? ''}${status.stderr ?? ''}`.trim().slice(0, 200)\n return status.status === 0 ? { ok: true, detail: detail || 'signed in' } : { ok: false, detail: detail || 'codex is not signed in (run `codex login`)' }\n}\n\nexport function codexProfileArgs(profile: RunProfile): string[] {\n switch (profile) {\n case 'answer':\n return ['--sandbox', 'read-only', '-c', 'approval_policy=\"never\"']\n case 'work':\n return ['--sandbox', 'workspace-write', '-c', 'approval_policy=\"never\"']\n case 'full':\n return ['--dangerously-bypass-approvals-and-sandbox']\n }\n}\n\n/** Where a run's hosted tool server points, and which variable carries its bearer token. */\nexport interface CodexMcpOverride {\n readonly url: string\n readonly keyEnv: string\n /** The version named in `X-AgentChat-Client-Version` (the front door that placed the run). Defaults to this engine's. */\n readonly clientVersion?: string\n}\n\n/**\n * `{\"X-AgentChat-Client\" = \"codex\", \"X-AgentChat-Client-Version\" = \"<version>\"}`:\n * the client headers that name the runtime to the hosted tool server, as a\n * TOML inline table for `-c …http_headers=`. Codex parses a `-c` value as\n * TOML (inline tables included) since before 0.154.0, and sends\n * `http_headers` on every request to a streamable-HTTP server. Without them\n * a run is an unknown client and is shown the wake-webhook tools.\n */\nexport function codexClientHeadersToml(clientVersion: string = VERSION): string {\n const pairs = Object.entries(clientHeadersOf({ runtime: 'codex', version: clientVersion })).map(([name, value]) => `${JSON.stringify(name)} = ${JSON.stringify(value)}`)\n return `{ ${pairs.join(', ')} }`\n}\n\n/** The `-c` overrides that make `[mcp_servers.agentchat]` this agent's, for one run. TOML values, no key in them. */\nexport function codexMcpOverrideArgs(override: CodexMcpOverride): string[] {\n const table = `mcp_servers.${CODEX_MCP_SERVER_NAME}`\n return [\n '-c',\n `${table}.url=${JSON.stringify(override.url)}`,\n '-c',\n `${table}.bearer_token_env_var=${JSON.stringify(override.keyEnv)}`,\n '-c',\n `${table}.default_tools_approval_mode=\"approve\"`,\n '-c',\n `${table}.http_headers=${codexClientHeadersToml(override.clientVersion ?? VERSION)}`,\n ]\n}\n\n/**\n * The full argument list for one headless run. The prompt is NOT an argument:\n * the runner writes it to stdin and closes it. An argument cannot carry it on\n * Windows — npm installs codex as a `.cmd` shim, cross-spawn runs that through\n * cmd.exe, and cmd.exe ends the command at the first line break, so every line\n * after the first was silently dropped (caught by CI on windows-latest).\n */\nexport function codexRunArgs(profile: RunProfile, options: { workdir: string; mcp?: CodexMcpOverride }): string[] {\n return [\n 'exec',\n '--json',\n '--skip-git-repo-check',\n '--ephemeral',\n '-C',\n options.workdir,\n ...codexProfileArgs(profile),\n ...(options.mcp !== undefined ? codexMcpOverrideArgs(options.mcp) : []),\n CODEX_PROMPT_FROM_STDIN,\n ]\n}\n\nexport interface CodexRunnerOptions {\n readonly codexHome: string\n /** The run's working root (`-C`); the `work` profile may write here. */\n readonly workdir: string\n readonly profile: RunProfile\n /** The agent's key, read per run (a credential change between runs is followed). Null: none is set. */\n readonly apiKey: () => string | null\n /** The variable the key is set under in the run's environment. */\n readonly keyEnv: string\n /** Point the hosted server at this agent for each run (`-c` overrides); absent, config.toml decides. */\n readonly mcp?: CodexMcpOverride\n /** Test seam: the binary to run. */\n readonly command?: string\n readonly env?: NodeJS.ProcessEnv\n}\n\nexport class CodexRunner implements RunRunner {\n readonly name = 'codex'\n private readonly command: string\n\n constructor(private readonly options: CodexRunnerOptions) {\n this.command = options.command ?? 'codex'\n }\n\n async preflight(): Promise<RunPreflight> {\n const runtime = inspectCodexRuntime(this.options.codexHome, this.command)\n if (!runtime.ok) return { ok: false, detail: runtime.detail }\n const auth = codexIsLoggedIn(this.options.codexHome, this.command)\n if (!auth.ok) return { ok: false, detail: `codex login status failed: ${auth.detail}` }\n fs.mkdirSync(this.options.workdir, { recursive: true })\n return { ok: true }\n }\n\n /** The exact argv one run uses — exported for tests to pin per profile. */\n args(): string[] {\n return codexRunArgs(this.options.profile, { workdir: this.options.workdir, ...(this.options.mcp !== undefined ? { mcp: this.options.mcp } : {}) })\n }\n\n /** The child environment: Codex's home and the key the hosted server needs, under the configured name. */\n env(): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...(this.options.env ?? process.env), CODEX_HOME: this.options.codexHome }\n const key = this.options.apiKey()\n if (key !== null) env[this.options.keyEnv] = key\n return env\n }\n\n async start(request: RunRequest): Promise<RunOutcome> {\n const args = this.args()\n log.debug(`codex ${args.join(' ')} (prompt on stdin, ${request.kind} run ${request.runId})`)\n return spawnRun({\n command: this.command,\n args,\n cwd: this.options.workdir,\n env: this.env(),\n // Written to stdin and then closed: `codex exec -` reads its\n // instructions until EOF. Never as an argument (see codexRunArgs).\n stdin: request.prompt,\n budgetMs: request.budgetMs,\n ...(request.signal ? { signal: request.signal } : {}),\n ...(request.onStarted ? { onStarted: request.onStarted } : {}),\n })\n }\n}\n\n/**\n * The keys of `[mcp_servers.agentchat]` in a config.toml, or null when the\n * table is absent. Keys only — a value can be a secret. A line scan, not a\n * TOML parser: enough to say what a run's `-c` overrides merge over.\n */\nexport function agentchatTableKeys(configToml: string): string[] | null {\n const lines = configToml.split(/\\r?\\n/)\n const header = new RegExp(`^\\\\s*\\\\[mcp_servers\\\\.${CODEX_MCP_SERVER_NAME}\\\\]\\\\s*(#.*)?$`)\n const start = lines.findIndex((line) => header.test(line))\n if (start < 0) return null\n const keys: string[] = []\n for (const line of lines.slice(start + 1)) {\n if (/^\\s*\\[/.test(line)) break\n const match = /^\\s*([A-Za-z0-9_.-]+)\\s*=/.exec(line)\n if (match?.[1] !== undefined) keys.push(match[1])\n }\n return keys\n}\n\nexport const codexPreset: Preset = {\n name: CODEX_PRESET,\n describeMcp({ apiBase, env = process.env }) {\n const file = path.join(codexHomeFrom(env), 'config.toml')\n let own: string[] | null = null\n try {\n own = agentchatTableKeys(fs.readFileSync(file, 'utf-8'))\n } catch {\n own = null\n }\n return [\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.url=\"${hostedMcpUrl(apiBase)}\"`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.bearer_token_env_var=\"${LISTENER_KEY_ENV}\" (the key set in the run's environment, never on argv)`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.default_tools_approval_mode=\"approve\"`,\n `-c mcp_servers.${CODEX_MCP_SERVER_NAME}.http_headers={ \"X-AgentChat-Client\" = \"codex\", \"X-AgentChat-Client-Version\" = <the listener's version> } (names the runtime to the hosted tools)`,\n own === null\n ? `${file}: no [mcp_servers.${CODEX_MCP_SERVER_NAME}] of its own — the run sees only the overrides above`\n : `${file}: [mcp_servers.${CODEX_MCP_SERVER_NAME}] also sets ${own.length > 0 ? own.join(', ') : 'nothing'}; the overrides above replace their keys, the others still apply (how codex merges -c over an existing table is not verified on a real codex)`,\n ]\n },\n label: 'Codex',\n runtime: 'codex',\n // A read-only sandbox reads the whole filesystem.\n serviceEnv: ['CODEX_HOME'],\n readsIdentityHome: true,\n inspect(env = process.env, command = 'codex') {\n const home = codexHomeFrom(env)\n const runtime = inspectCodexRuntime(home, command)\n if (!runtime.ok) return runtime\n const auth = codexIsLoggedIn(home, command)\n return auth.ok ? { ok: true, detail: `${runtime.detail}, signed in` } : { ok: false, detail: `${runtime.detail}, not signed in: ${auth.detail}` }\n },\n runner(ctx: PresetContext): RunRunner {\n // A key in the listener's own environment is not handed to its runs.\n const env = withoutInheritedKey(ctx.env ?? process.env)\n const apiKey = ctx.apiKey\n return new CodexRunner({\n codexHome: codexHomeFrom(env),\n workdir: ctx.workdir,\n profile: ctx.profile,\n apiKey: () => apiKey,\n keyEnv: LISTENER_KEY_ENV,\n mcp: { url: hostedMcpUrl(ctx.apiBase), keyEnv: LISTENER_KEY_ENV, clientVersion: ctx.clientVersion ?? VERSION },\n ...(ctx.command !== undefined ? { command: ctx.command } : {}),\n env,\n })\n },\n}\n","// ─── @agentchatme/agent-core/presets ────────────────────────────────────────\n//\n// How to start one headless run of a known coding agent, shared by the\n// `agentchat listen --preset <name>` listener and each runtime's own\n// integration package (one copy of the flags, never two). The only module of\n// this package that names a coding agent; the engine never imports it.\n\nimport { claudeCodePreset } from './claude-code.js'\nimport { codexPreset } from './codex.js'\nimport type { Preset } from './types.js'\n\nexport type { Preset, PresetContext, PresetInspection } from './types.js'\nexport { semverAtLeast } from './semver.js'\nexport {\n CLAUDE_CODE_PRESET,\n MIN_CLAUDE_CODE_VERSION,\n CLAUDE_MCP_SERVER_NAME,\n AGENTCHAT_TOOL_ALLOW,\n ANSWER_TOOLS,\n WORK_TOOLS,\n PARENT_ENV_KEYS,\n claudeConfigDirFrom,\n claudeHomeFor,\n claudeUserStatePathFor,\n buildClaudeEnv,\n claudeIsLoggedIn,\n inspectClaudeRuntime,\n deniedAncestorOf,\n claudeProfileArgs,\n readDenyRules,\n inexpressibleDenyPaths,\n claudeRunArgs,\n claudeMcpConfig,\n claudeMcpConfigPath,\n ClaudeRunner,\n claudeCodePreset,\n type ClaudeRunArgOptions,\n type ClaudeRunnerOptions,\n} from './claude-code.js'\nexport {\n CODEX_PRESET,\n MIN_CODEX_VERSION,\n CODEX_MCP_SERVER_NAME,\n LISTENER_KEY_ENV,\n CODEX_PROMPT_FROM_STDIN,\n codexHomeFrom,\n inspectCodexRuntime,\n codexIsLoggedIn,\n codexProfileArgs,\n codexMcpOverrideArgs,\n codexClientHeadersToml,\n codexRunArgs,\n agentchatTableKeys,\n CodexRunner,\n codexPreset,\n type CodexMcpOverride,\n type CodexRunnerOptions,\n} from './codex.js'\n\n/** Every preset, by the name a user types. */\nexport const PRESETS: Readonly<Record<string, Preset>> = Object.freeze({\n [claudeCodePreset.name]: claudeCodePreset,\n [codexPreset.name]: codexPreset,\n})\n\nexport function presetNamed(name: string): Preset | null {\n return Object.prototype.hasOwnProperty.call(PRESETS, name) ? (PRESETS[name] ?? null) : null\n}\n\nexport function presetNames(): string[] {\n return Object.keys(PRESETS)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,YAAY,UAAU;;;ACDf,SAAS,cAAc,QAAgB,SAA0B;AACtE,QAAM,QAAQ,CAAC,UAAmD;AAChE,UAAM,QAAQ,MAAM,MAAM,qBAAqB;AAC/C,WAAO,QAAQ,CAAC,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI;AAAA,EAC1E;AACA,QAAM,IAAI,MAAM,MAAM;AAC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AAAA,EACzB,CAAC,YAAY,IAAI,GAAG;AACtB,CAAC;AAEM,SAAS,YAAY,MAA6B;AACvD,SAAO,OAAO,UAAU,eAAe,KAAK,SAAS,IAAI,IAAK,QAAQ,IAAI,KAAK,OAAQ;AACzF;AAEO,SAAS,cAAwB;AACtC,SAAO,OAAO,KAAK,OAAO;AAC5B;","names":["fs","os","path"]}
@@ -0,0 +1,130 @@
1
+ declare const RUN_PROFILES: readonly ["answer", "work", "full"];
2
+ type RunProfile = (typeof RUN_PROFILES)[number];
3
+ declare const RUN_PROFILE_ENV = "AGENTCHAT_RUN_PROFILE";
4
+ declare const DEFAULT_RUN_PROFILE: RunProfile;
5
+ declare function isRunProfile(value: unknown): value is RunProfile;
6
+ /** `AGENTCHAT_RUN_PROFILE`, defaulting to `answer`; an unknown value is `answer` too. */
7
+ declare function resolveRunProfile(env?: NodeJS.ProcessEnv): RunProfile;
8
+ /** The one switch: `AGENTCHAT_INTEGRATION=off` holds no socket and starts no run. Tools and manual stay. */
9
+ declare const INTEGRATION_ENV = "AGENTCHAT_INTEGRATION";
10
+ /**
11
+ * The previous spelling of the switch (a legacy name: compatibility reader
12
+ * only). Still read, because a service installed before the rename captured
13
+ * it into its unit file, and that unit must keep meaning what the operator
14
+ * set; `AGENTCHAT_INTEGRATION` wins when both are set. Contract v1 (section 7,
15
+ * old integration settings) removes it on `INTEGRATION_ENV_LEGACY_REMOVAL`;
16
+ * tests/legacy-env-removal.test.ts fails from that day, so the reader is
17
+ * deleted in a release rather than remembered. Until then an `off` here is
18
+ * honoured — never silently dropped, which would turn on an integration its
19
+ * operator switched off.
20
+ */
21
+ declare const INTEGRATION_ENV_LEGACY = "AGENTCHAT_DOORBELL";
22
+ /** The day contract v1 drops `AGENTCHAT_DOORBELL` (UTC). */
23
+ declare const INTEGRATION_ENV_LEGACY_REMOVAL = "2027-02-01";
24
+ /** Which switch turned the integration off, or null when it is on. The new spelling wins when both are set. */
25
+ declare function integrationDisabledBy(env?: NodeJS.ProcessEnv): string | null;
26
+ declare function integrationDisabled(env?: NodeJS.ProcessEnv): boolean;
27
+ /** A run's time budget. Killed past it; that counts as a failed run. */
28
+ declare const RUN_BUDGET_ENV = "AGENTCHAT_RUN_BUDGET_MS";
29
+ declare const DEFAULT_RUN_BUDGET_MS: number;
30
+ declare function resolveRunBudgetMs(env?: NodeJS.ProcessEnv): number;
31
+
32
+ /** `invite` when the tray held only pending invites (the served invite prompt); `wake` otherwise. */
33
+ type RunKind = 'wake' | 'invite';
34
+ /**
35
+ * The wake that started a run, named as the webhook wake names it (contract
36
+ * v1): `messages`, `reminder`, `invite`, `unanswered` (with `step`, the
37
+ * re-wake rung) — or another reason a newer server sends. Facts about the
38
+ * signal only, never content.
39
+ */
40
+ interface RunWake {
41
+ readonly reason: string;
42
+ readonly step?: number;
43
+ }
44
+ interface RunRequest {
45
+ readonly kind: RunKind;
46
+ /** The wake that started this run (the newest since the previous run started). */
47
+ readonly wake?: RunWake;
48
+ /** The prompt for this kind of run: the served text (the kit's receive loop picks it), then the manual pointer. */
49
+ readonly prompt: string;
50
+ /** Unique per run; for logs and for runtimes that want a session name. */
51
+ readonly runId: string;
52
+ /** The run is killed past this budget and counts as failed. */
53
+ readonly budgetMs: number;
54
+ /**
55
+ * Aborted when the integration is stopping (daemon shutdown, identity
56
+ * change). A runner passes it to `spawnRun`, which SIGTERMs the
57
+ * run's process group and SIGKILLs after a grace; the outcome is `failed`
58
+ * with an "interrupted" detail. Optional so a runner that cannot interrupt
59
+ * still satisfies the contract.
60
+ */
61
+ readonly signal?: AbortSignal;
62
+ /**
63
+ * Called once, as soon as the runtime's process has been started. The
64
+ * engine no longer needs it (pending invites are on the tray, so nothing
65
+ * is recorded locally); kept so a caller can observe the start. A runner
66
+ * built on `spawnRun` passes it through.
67
+ */
68
+ readonly onStarted?: () => void;
69
+ }
70
+ /**
71
+ * `not_started` — the runtime never got going: binary missing, or a non-zero
72
+ * exit with NOTHING ON STDOUT (an auth gate, a bad flag, a missing config —
73
+ * all of which print their complaint on stderr and quit; stderr does not
74
+ * count as output). `failed` — it produced output and exited non-zero, or was
75
+ * interrupted. `timed_out` — it ran past its budget and was killed. `ok` —
76
+ * exit 0. Anything but `ok` leaves the cards on the tray: there is no local retry —
77
+ * the server re-wakes an agent for cards it has not answered (contract v1, D3).
78
+ */
79
+ type RunOutcomeState = 'ok' | 'failed' | 'timed_out' | 'not_started';
80
+ interface RunOutcome {
81
+ readonly state: RunOutcomeState;
82
+ readonly exitCode: number | null;
83
+ readonly durationMs: number;
84
+ /** Bounded, credential-redacted diagnostic. Never message content. */
85
+ readonly detail?: string;
86
+ }
87
+ interface RunPreflight {
88
+ ok: boolean;
89
+ detail?: string;
90
+ }
91
+ interface RunRunner {
92
+ /** Short runtime name for logs and status, e.g. the CLI's binary name. */
93
+ readonly name: string;
94
+ /**
95
+ * Is the runtime usable right now (binary present, signed in)? Called
96
+ * before the socket is held: an integration whose runtime is not usable
97
+ * holds no socket, and the supervisor asks again with a backoff.
98
+ */
99
+ preflight(): Promise<RunPreflight>;
100
+ /** Start one run and wait for it. Never throws — returns an outcome. */
101
+ start(request: RunRequest): Promise<RunOutcome>;
102
+ }
103
+ /** The agent a runner's runs act as: what a `RunnerFactory` is given for each identity the integration serves. */
104
+ interface RunnerIdentity {
105
+ /** The identity home. */
106
+ readonly home: string;
107
+ /** Bare handle. */
108
+ readonly handle: string;
109
+ /** The agent's key. A runner hands it to its runs only as a file or an environment variable, never on argv. */
110
+ readonly apiKey: string;
111
+ readonly apiBase: string;
112
+ /** The run's working directory. */
113
+ readonly workdir: string;
114
+ }
115
+ /**
116
+ * Builds the runner for one identity. For runners whose runs must be told
117
+ * which agent they act as (a listener's preset writes the agent's hosted tool
118
+ * config; a forwarder reads that agent's tray): the resident supervisor calls
119
+ * `create` again whenever the credential changes.
120
+ */
121
+ interface RunnerFactory {
122
+ /** Short runtime name for logs and status, before any identity is known. */
123
+ readonly name: string;
124
+ create(identity: RunnerIdentity): RunRunner;
125
+ }
126
+ /** A runner, or a factory of one per identity. */
127
+ type RunnerSource = RunRunner | RunnerFactory;
128
+ declare function isRunnerFactory(source: RunnerSource): source is RunnerFactory;
129
+
130
+ export { DEFAULT_RUN_BUDGET_MS as D, INTEGRATION_ENV as I, type RunnerSource as R, type RunProfile as a, type RunRunner as b, type RunOutcome as c, type RunKind as d, type RunOutcomeState as e, type RunPreflight as f, type RunRequest as g, type RunWake as h, type RunnerFactory as i, type RunnerIdentity as j, DEFAULT_RUN_PROFILE as k, INTEGRATION_ENV_LEGACY as l, INTEGRATION_ENV_LEGACY_REMOVAL as m, RUN_BUDGET_ENV as n, RUN_PROFILES as o, RUN_PROFILE_ENV as p, integrationDisabled as q, integrationDisabledBy as r, isRunProfile as s, isRunnerFactory as t, resolveRunBudgetMs as u, resolveRunProfile as v };
@@ -0,0 +1,380 @@
1
+ import { TextsRuntime, AgentChatClientIdentity, integration } from 'agentchatme';
2
+ import { z } from 'zod';
3
+
4
+ interface IntegrationClient {
5
+ readonly runtime: TextsRuntime;
6
+ readonly version: string;
7
+ /**
8
+ * The client name sent to the server when it is not the runtime itself —
9
+ * a front door that serves several runtimes (the `agentchat` listener)
10
+ * names itself here, and `runtime` stays what the texts are rendered for.
11
+ */
12
+ readonly name?: string;
13
+ }
14
+ /** The name this client identifies as: its own `name`, else its runtime. */
15
+ declare function clientNameOf(client: IntegrationClient): string;
16
+ /**
17
+ * The SDK's client identity for this integration. The SDK types client names
18
+ * as a closed union and the server normalises whatever arrives, so the
19
+ * runtime name is passed through as-is; the union widens on the SDK side.
20
+ */
21
+ declare function clientIdentityOf(client: IntegrationClient): AgentChatClientIdentity;
22
+ /** The same identity as headers, for the one raw request this package still makes (the MCP probe). */
23
+ declare function clientHeadersOf(client: IntegrationClient): Record<string, string>;
24
+
25
+ declare const INTEGRATION_STATUS_FILE = "integration.status.json";
26
+ /** The file a daemon before the rename writes; read when the current one is absent. */
27
+ declare const LEGACY_STATUS_FILE = "doorbell.status.json";
28
+ /**
29
+ * The socket word. `blocked` is the SDK's own word for it (`RealtimeState`):
30
+ * the server refused the credential on the hello and a fresh hello is tried
31
+ * every 10–15 min until one is accepted — not an end state. Daemons before
32
+ * this release wrote `terminal` for it; readers map that on the way in.
33
+ */
34
+ declare const SOCKET_STATES: readonly ["off", "idle", "connecting", "ready", "reconnecting", "blocked", "closed"];
35
+ type SocketState = (typeof SOCKET_STATES)[number];
36
+ type TextsSource = 'server' | 'cache' | 'none';
37
+ interface TextsStatus {
38
+ /** Where the texts a run starts with came from. */
39
+ source: TextsSource;
40
+ fetched_at: string | null;
41
+ /** The served text set's version. */
42
+ version: string | null;
43
+ manual_version: string | null;
44
+ }
45
+ interface IntegrationLastRun {
46
+ kind: 'wake' | 'invite';
47
+ started_at: string;
48
+ ended_at: string;
49
+ state: 'ok' | 'failed' | 'timed_out' | 'not_started';
50
+ exit_code: number | null;
51
+ duration_ms: number;
52
+ detail: string | null;
53
+ }
54
+ interface IntegrationStatus {
55
+ version: 2;
56
+ updated_at: string;
57
+ pid: number;
58
+ runtime: string | null;
59
+ handle: string | null;
60
+ profile: string;
61
+ socket: SocketState;
62
+ wakes: number;
63
+ wakes_absorbed: number;
64
+ invites: number;
65
+ runs_started: number;
66
+ runs_ok: number;
67
+ runs_failed: number;
68
+ runs_timed_out: number;
69
+ runs_not_started: number;
70
+ /** Wakes whose tray count came back empty, so no run started. */
71
+ runs_skipped_empty: number;
72
+ last_run: IntegrationLastRun | null;
73
+ retry_rung: number;
74
+ retry_due_at: string | null;
75
+ last_error: string | null;
76
+ texts: TextsStatus | null;
77
+ /** The socket capabilities the server accepted (`ack`, `heartbeat`, `rewake`); null before a hello, or from an older daemon. */
78
+ capabilities?: string[] | null;
79
+ /** The receive loop's most recent wake cycles, oldest first (the kit's `status().recentCycles`, reduced); null from an older daemon. */
80
+ recent_cycles?: IntegrationCycle[] | null;
81
+ /** The socket's backpressure: true while it refuses new messages because handlers are behind (the kit's `intakePaused`); null from an older daemon. */
82
+ intake_paused?: boolean | null;
83
+ }
84
+ /** One wake cycle as the status file keeps it: what it found and how it ended. Counts and outcomes only. */
85
+ interface IntegrationCycle {
86
+ at: string;
87
+ /** The kit's cycle outcome: `empty`, `nothing_owed`, `run_completed`, `run_failed`, `abandoned`, … */
88
+ outcome: string;
89
+ cards: number;
90
+ invites: number;
91
+ /** Why it did not finish, bounded; null when it did. */
92
+ failure: string | null;
93
+ }
94
+ /** Cycle outcomes that mean a wake was owed something and it did not get done. */
95
+ declare const FAILED_CYCLE_OUTCOMES: ReadonlySet<string>;
96
+ /** How many of the newest cycles in a row did not get done, with the newest failure; null when the newest cycle did. */
97
+ declare function failedCyclesInARow(status: Pick<IntegrationStatus, 'recent_cycles'> | null): {
98
+ count: number;
99
+ latest: IntegrationCycle;
100
+ } | null;
101
+ /** This many failed cycles in a row is a warning in `status` and `doctor`: one is a hiccup, three is a pattern. */
102
+ declare const REPEATED_FAILED_CYCLES = 3;
103
+ declare function integrationStatusPath(home: string): string;
104
+ /** Best effort: the status file is diagnostics, never a dependency of waking. */
105
+ declare function writeIntegrationStatus(home: string, status: IntegrationStatus): void;
106
+ /** The current file, or — when a daemon from before the rename is the one running — the file it writes. */
107
+ declare function readIntegrationStatus(home: string): IntegrationStatus | null;
108
+ /** Remove both spellings: a stale legacy file must not outlive the daemon that wrote it. */
109
+ declare function clearIntegrationStatus(home: string): void;
110
+ /** Age of the status file, in ms, or null when absent. */
111
+ declare function integrationStatusAge(status: IntegrationStatus | null, now?: number): number | null;
112
+ /** Human lines for `status`. Pure. */
113
+ declare function formatIntegrationStatus(status: IntegrationStatus | null, now?: number): string[];
114
+
115
+ declare const DEFAULT_API_BASE = "https://api.agentchat.me";
116
+ declare const CredentialsSchema: z.ZodObject<{
117
+ api_key: z.ZodString;
118
+ handle: z.ZodString;
119
+ api_base: z.ZodOptional<z.ZodString>;
120
+ created_at: z.ZodOptional<z.ZodString>;
121
+ }, "strip", z.ZodTypeAny, {
122
+ api_key: string;
123
+ handle: string;
124
+ api_base?: string | undefined;
125
+ created_at?: string | undefined;
126
+ }, {
127
+ api_key: string;
128
+ handle: string;
129
+ api_base?: string | undefined;
130
+ created_at?: string | undefined;
131
+ }>;
132
+ type Credentials = z.infer<typeof CredentialsSchema>;
133
+ interface ResolvedIdentity {
134
+ apiKey: string;
135
+ apiBase: string;
136
+ /** Handle is only known when it came from the credentials file. */
137
+ handle: string | null;
138
+ source: 'env' | 'file';
139
+ }
140
+ declare function credentialsPath(home: string): string;
141
+ declare function pendingPath(home: string): string;
142
+ declare function statePath(home: string): string;
143
+ /** Read the credential stored in `home`, or null when absent/malformed. */
144
+ declare function readCredentials(home: string): Credentials | null;
145
+ /**
146
+ * The identity an integration should act as, for one specific home.
147
+ * `AGENTCHAT_API_KEY` overrides the file; `AGENTCHAT_API_BASE` overrides the
148
+ * base URL. Neither is host-specific, so both are read from the environment.
149
+ */
150
+ interface ResolveIdentityOptions {
151
+ /**
152
+ * Whether `AGENTCHAT_API_KEY` may override the home's credentials (default
153
+ * true). A resident listener passes false: the agent it serves is the one
154
+ * its home holds, whatever happens to be exported in the shell that
155
+ * started it.
156
+ */
157
+ readonly envKey?: boolean;
158
+ }
159
+ /** `AGENTCHAT_API_KEY` from the environment when it is set and well-formed, else null. */
160
+ declare function envApiKey(env?: NodeJS.ProcessEnv): string | null;
161
+ declare function resolveIdentity(home: string, options?: ResolveIdentityOptions): ResolvedIdentity | null;
162
+ declare function writeCredentials(home: string, creds: Credentials): void;
163
+ /** Delete the credential and any half-finished registration in `home`.
164
+ * Touches nothing outside `home` — that is the caller's whole agent. */
165
+ declare function clearCredentials(home: string): boolean;
166
+ declare const PendingSchema: z.ZodObject<{
167
+ kind: z.ZodDefault<z.ZodEnum<["register", "recover"]>>;
168
+ pending_id: z.ZodString;
169
+ email: z.ZodString;
170
+ handle: z.ZodOptional<z.ZodString>;
171
+ api_base: z.ZodOptional<z.ZodString>;
172
+ created_at: z.ZodString;
173
+ }, "strip", z.ZodTypeAny, {
174
+ created_at: string;
175
+ kind: "register" | "recover";
176
+ pending_id: string;
177
+ email: string;
178
+ handle?: string | undefined;
179
+ api_base?: string | undefined;
180
+ }, {
181
+ created_at: string;
182
+ pending_id: string;
183
+ email: string;
184
+ handle?: string | undefined;
185
+ api_base?: string | undefined;
186
+ kind?: "register" | "recover" | undefined;
187
+ }>;
188
+ type PendingRegistration = z.infer<typeof PendingSchema>;
189
+ declare function readPending(home: string): PendingRegistration | null;
190
+ declare function writePending(home: string, pending: PendingRegistration): void;
191
+ declare function clearPending(home: string): void;
192
+
193
+ type Verdict = 'PASS' | 'WARN' | 'FAIL';
194
+ interface DoctorCheck {
195
+ name: string;
196
+ verdict: Verdict;
197
+ detail: string;
198
+ }
199
+ /** What the shared `status` hands a host's extra lines: what it already fetched from the served texts (one fetch per command). */
200
+ interface StatusContext {
201
+ identityLine: string | null;
202
+ /**
203
+ * The served `identity_line_template` from the same texts, or null when none
204
+ * are in hand: what `readAnchorHandleAt` recognises an unmarked block by, in
205
+ * whatever words the server serves today.
206
+ */
207
+ identityLineTemplate: string | null;
208
+ /** The manual the served texts announce (`texts.manual`), or null when none are in hand — what `checkManual` compares the skill file with. */
209
+ manual: ServedManual | null;
210
+ }
211
+ /** What the shared doctor hands a host's extra checks. */
212
+ interface DoctorContext {
213
+ fix?: boolean;
214
+ /** The served identity line for this agent, or null when the server could not be reached and nothing is cached. */
215
+ identityLine: string | null;
216
+ /** The served `identity_line_template`, or null when none are in hand (see `StatusContext`). */
217
+ identityLineTemplate: string | null;
218
+ /** The manual the served texts announce, or null when none are in hand (`--fix` syncs the skill file to it). */
219
+ manual: ServedManual | null;
220
+ }
221
+ /**
222
+ * Everything the shared identity commands need to know about ONE coding agent.
223
+ *
224
+ * This is the seam. The register / login / recover / status / logout / doctor
225
+ * flows are the same everywhere because they are a contract with the AgentChat
226
+ * server; what differs per host is only what is described here. An integration
227
+ * builds one of these and gets the commands back.
228
+ *
229
+ * Note what is NOT here: any way to name a *different* host. A profile
230
+ * describes the caller and nothing else, so a command built from it cannot
231
+ * reach another agent's files. That is the same property the per-repo split
232
+ * gives, kept intact while the flow itself is shared once.
233
+ *
234
+ * The path-ish fields are functions, not strings: `CODEX_HOME` and friends are
235
+ * read per call, and evaluating them at module load would freeze a value the
236
+ * user can still change.
237
+ */
238
+ interface HostProfile {
239
+ /** Human name for output, e.g. `Claude Code`. */
240
+ label: string;
241
+ /** Stable machine identifier for `--json`, e.g. `claude-code`. */
242
+ id: string;
243
+ /** How this integration names itself to the server: the texts runtime and its own version. */
244
+ client: IntegrationClient;
245
+ /** THE identity home for this agent. */
246
+ home(): string;
247
+ /**
248
+ * This host's always-loaded instruction file. Absent for a front door whose
249
+ * runtime has none it can place a line in (the `agentchat` listener runs an
250
+ * owner's command): no identity line is placed, checked or removed.
251
+ */
252
+ anchorFile?(): string;
253
+ /** Exactly what a user types to reach this integration. */
254
+ invocation(): string;
255
+ /**
256
+ * The identity block this host places for `handle` from the served identity
257
+ * line (normally `renderAnchorBlock`, the kit's shape with the handle line).
258
+ * Throws when the line does not name the handle; nothing is written then.
259
+ */
260
+ renderAnchor(identityLine: string, handle: string): string;
261
+ /**
262
+ * What to call the anchor in output. Defaults to the instruction file's own
263
+ * basename (`CLAUDE.md`, `AGENTS.md`), which is what a user actually looks
264
+ * for on disk.
265
+ */
266
+ anchorLabel?: string;
267
+ /**
268
+ * Whether this host is wired up enough for an anchor to mean anything.
269
+ * An integration uses this so it never writes an identity block announcing
270
+ * a phone number before its own placement is actually in place.
271
+ */
272
+ isWired?(): boolean;
273
+ /**
274
+ * Place the integration's texts for a freshly established identity: the
275
+ * identity line, the manual, the hosted tool server with the key, and
276
+ * whatever the key's home is on this runtime. Called after register, login
277
+ * and recover (every time the key changes), and by `doctor --fix`.
278
+ * `identityLine` is the served line for this agent (fetched just before,
279
+ * or the cached one), or null when neither could be had — the host then
280
+ * leaves the anchor for `doctor --fix` and says so. `manual` is what the
281
+ * same texts announce (`syncManual` brings the skill file to it), or null.
282
+ * Returns report lines. When absent, only the anchor is written.
283
+ */
284
+ place?(handle: string, apiKey: string, identityLine: string | null, manual: ServedManual | null): string[] | Promise<string[]>;
285
+ /**
286
+ * Undo `place` for the identity being signed out: remove the key from the
287
+ * tool server registration and anything else that would still authenticate
288
+ * as the old identity. The anchor is removed by the shared flow. Returns
289
+ * report lines.
290
+ *
291
+ * `identity` is the identity AS IT WAS BEFORE the credential was cleared
292
+ * (its key and API base), or null when there was none: a host recognises
293
+ * its own registration by that key and that server, and guessing either
294
+ * after the fact left a non-default `api_base` entry classified as foreign
295
+ * and the key still registered.
296
+ */
297
+ unplace?(identity: ResolvedIdentity | null): string[];
298
+ /** Host-specific doctor checks, appended after the shared ones. */
299
+ extraDoctorChecks?(context: DoctorContext): DoctorCheck[] | Promise<DoctorCheck[]>;
300
+ /**
301
+ * Host-specific `status` lines (placement, probes), printed after the shared
302
+ * ones in text mode. The served identity line and manual come along so the
303
+ * host does not fetch `/v1/texts` a second time.
304
+ */
305
+ extraStatus?(context: StatusContext): string[] | Promise<string[]>;
306
+ /** Extra lines printed after a successful logout. */
307
+ logoutHints?(): string[];
308
+ }
309
+ /** The label to use for this host's anchor in user-facing output. */
310
+ declare function anchorLabelOf(profile: HostProfile): string;
311
+
312
+ /** What the served texts announce: `Texts['manual']`, with the optional integrity hash. */
313
+ type ServedManual = integration.ServedManual;
314
+ declare const MANUAL_MAX_BYTES: number;
315
+ declare const MANUAL_FETCH_TIMEOUT_MS: 10000;
316
+ declare const MANUAL_MAX_REDIRECTS: 3;
317
+ /** `fetch`'s shape, injectable for tests. Defaults to the platform's own; called with `redirect: 'manual'`. */
318
+ type ManualFetch = integration.ManualFetch;
319
+ /**
320
+ * - `current` — the file already is the announced manual (version, and hash when announced); nothing fetched.
321
+ * - `updated` — the announced manual was written (downloaded, or the bundled copy when it is that manual).
322
+ * - `kept` — the existing file was left as it was: nothing announced to compare with, or no verified copy could be had.
323
+ * - `fallback` — no file existed and nothing verified could be had: the bundled copy was written.
324
+ * - `failed` — no file existed and none could be written.
325
+ */
326
+ type ManualSyncState = integration.ManualSyncState;
327
+ interface ManualSyncResult extends Omit<integration.ManualSyncResult, 'source'> {
328
+ /** Where the written bytes came from, when some were written. */
329
+ readonly source: 'download' | 'bundled' | null;
330
+ }
331
+ interface SyncManualOptions {
332
+ /** The skill file, e.g. `<skills dir>/agentchat/SKILL.md`. The integration knows where; this package never derives it. */
333
+ readonly path: string;
334
+ /** `texts.manual` from the served texts (or their identity-home cache); null when none are in hand. */
335
+ readonly served: ServedManual | null;
336
+ /**
337
+ * The API base the texts were fetched from (the identity's `api_base`). It
338
+ * decides where a download may go; null (unknown) or a plain-HTTP base off
339
+ * loopback means no download at all.
340
+ */
341
+ readonly apiBase: string | null;
342
+ readonly fetch?: ManualFetch;
343
+ readonly timeoutMs?: number;
344
+ readonly maxBytes?: number;
345
+ readonly signal?: AbortSignal;
346
+ }
347
+ /** The version the file at `file` carries, or null when it is missing or names none. */
348
+ declare function readManualVersion(file: string): string | null;
349
+ /** A kit result in this package's words (the fallback is the bundled copy). */
350
+ declare function fromKitResult(result: integration.ManualSyncResult): ManualSyncResult;
351
+ /**
352
+ * Bring the skill file at `path` to the announced manual (the kit's
353
+ * `syncManual`, the bundled copy as fallback). Never throws.
354
+ */
355
+ declare function syncManual(options: SyncManualOptions): Promise<ManualSyncResult>;
356
+ declare function describeManualSync(result: ManualSyncResult): string;
357
+ type ManualCheckState = 'current' | 'stale' | 'unchecked' | 'missing';
358
+ interface ManualCheck {
359
+ readonly state: ManualCheckState;
360
+ readonly path: string;
361
+ readonly version: string | null;
362
+ readonly served: string | null;
363
+ /** current → PASS; stale or unchecked → WARN (the agent still has a manual); missing → FAIL. */
364
+ readonly verdict: Verdict;
365
+ /** `current (2.2.1)`, `stale (have 2.1.2, served 2.2.1)`, `unchecked (have 2.2.1; …)`, `missing`. */
366
+ readonly summary: string;
367
+ /** The summary and the file. */
368
+ readonly detail: string;
369
+ }
370
+ interface CheckManualOptions {
371
+ readonly path: string;
372
+ /** What the served texts announce; null when none are in hand. */
373
+ readonly served: ServedManual | null;
374
+ /** The API base the texts came from; a base no download would be made from is named in the summary. */
375
+ readonly apiBase: string | null;
376
+ }
377
+ /** Compare the skill file with the announced manual. Reads one file; no network. */
378
+ declare function checkManual(options: CheckManualOptions): ManualCheck;
379
+
380
+ export { resolveIdentity as $, clientIdentityOf as A, clientNameOf as B, type CheckManualOptions as C, DEFAULT_API_BASE as D, credentialsPath as E, FAILED_CYCLE_OUTCOMES as F, describeManualSync as G, type HostProfile as H, type IntegrationClient as I, envApiKey as J, failedCyclesInARow as K, LEGACY_STATUS_FILE as L, type ManualFetch as M, formatIntegrationStatus as N, fromKitResult as O, type PendingRegistration as P, integrationStatusAge as Q, REPEATED_FAILED_CYCLES as R, type SocketState as S, type TextsStatus as T, integrationStatusPath as U, type Verdict as V, pendingPath as W, readCredentials as X, readIntegrationStatus as Y, readManualVersion as Z, readPending as _, type IntegrationStatus as a, statePath as a0, syncManual as a1, writeCredentials as a2, writeIntegrationStatus as a3, writePending as a4, type Credentials as b, type DoctorCheck as c, type DoctorContext as d, INTEGRATION_STATUS_FILE as e, type IntegrationCycle as f, type IntegrationLastRun as g, MANUAL_FETCH_TIMEOUT_MS as h, MANUAL_MAX_BYTES as i, MANUAL_MAX_REDIRECTS as j, type ManualCheck as k, type ManualCheckState as l, type ManualSyncResult as m, type ManualSyncState as n, type ResolveIdentityOptions as o, type ResolvedIdentity as p, SOCKET_STATES as q, type ServedManual as r, type StatusContext as s, type SyncManualOptions as t, anchorLabelOf as u, checkManual as v, clearCredentials as w, clearIntegrationStatus as x, clearPending as y, clientHeadersOf as z };