@openape/apes 1.28.8 → 1.28.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -486,9 +486,11 @@ function buildCreateCommand(repo, taskId, branch) {
486
486
  `git -C ${q(baseDir)} worktree prune 2>/dev/null || true`,
487
487
  `rm -rf ${q(wt)} 2>/dev/null || true`
488
488
  ].join("; ");
489
+ const ghAuth = /github\.com/i.test(source) ? `git -C ${q(baseDir)} config credential.helper '!f() { echo username=x-access-token; echo "password=$GH_TOKEN"; }; f'` : "true";
489
490
  return [
490
491
  `mkdir -p ${q(reposRoot())} ${q(workRoot())}`,
491
492
  clone,
493
+ ghAuth,
492
494
  `git -C ${q(baseDir)} fetch --quiet || true`,
493
495
  `{ ${reset}; }`,
494
496
  `git -C ${q(baseDir)} worktree add -B ${q(br)} ${q(wt)}`,
@@ -1012,4 +1014,4 @@ export {
1012
1014
  runLoop,
1013
1015
  RpcSessionMap
1014
1016
  };
1015
- //# sourceMappingURL=chunk-SWRK4SWT.js.map
1017
+ //# sourceMappingURL=chunk-66NFSMCY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/duration.ts","../src/lib/agent-tools/ape-shell-exec.ts","../src/lib/agent-tools/bash.ts","../src/lib/agent-tools/file.ts","../src/lib/coding/forge.ts","../src/lib/agent-tools/forge.ts","../src/lib/agent-tools/git-worktree.ts","../src/lib/agent-tools/http.ts","../src/lib/agent-tools/mail.ts","../src/lib/agent-tools/tasks.ts","../src/lib/agent-tools/time.ts","../src/lib/coding/verify.ts","../src/lib/agent-tools/verify.ts","../src/lib/agent-tools/index.ts","../src/lib/agent-runtime.ts"],"sourcesContent":["export class CliError extends Error {\n constructor(message: string, public exitCode: number = 1) {\n super(message)\n this.name = 'CliError'\n }\n}\n\nexport class CliExit extends Error {\n constructor(public exitCode: number = 0) {\n super('')\n this.name = 'CliExit'\n }\n}\n","/**\n * Parse a human-readable duration string into seconds.\n * Supported formats: 30s, 5m, 1h, 7d\n */\nexport function parseDuration(value: string): number {\n const match = value.match(/^(\\d+)\\s*([smhd])$/)\n if (!match) {\n throw new Error(`Invalid duration format: \"${value}\". Use e.g. 30m, 1h, 7d`)\n }\n const amount = Number.parseInt(match[1]!, 10)\n switch (match[2]) {\n case 's': return amount\n case 'm': return amount * 60\n case 'h': return amount * 3600\n case 'd': return amount * 86400\n default: throw new Error(`Unknown duration unit: ${match[2]}`)\n }\n}\n","import { spawn } from 'node:child_process'\n\n// Shared gated-exec path. Every shell command an agent tool runs goes\n// through `ape-shell -c <cmd>`, which rewrites to `apes run --shell --\n// bash -c …` — i.e. the DDISA grant cycle + shapes-adapter matching,\n// identical to what the human owner types interactively. APE_WAIT=1\n// forces the blocking path so the tool returns a result instead of\n// exiting 75 with grant-pending instructions.\n//\n// bash.ts and git-worktree.ts both build on this so the gating is\n// guaranteed in one place — no tool can shell out un-gated by reaching\n// for child_process directly.\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000\nconst MAX_STDIO_BYTES = 64 * 1024\nconst BIN = 'ape-shell'\n\nexport interface ApeShellResult {\n stdout: string\n stderr: string\n exit_code: number\n timed_out?: boolean\n error?: string\n hint?: string\n}\n\nfunction capStdio(s: string): string {\n const buf = Buffer.from(s, 'utf8')\n if (buf.byteLength <= MAX_STDIO_BYTES) return s\n return `${buf.subarray(0, MAX_STDIO_BYTES).toString('utf8')}\\n[truncated to ${MAX_STDIO_BYTES} bytes]`\n}\n\nexport function runApeShell(cmd: string, timeoutMs: number = DEFAULT_TIMEOUT_MS): Promise<ApeShellResult> {\n return new Promise<ApeShellResult>((resolveResult) => {\n const child = spawn(BIN, ['-c', cmd], {\n env: { ...process.env, APE_WAIT: '1' },\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n let stdout = ''\n let stderr = ''\n let timedOut = false\n let spawnError: Error | null = null\n\n child.stdout!.on('data', (chunk: Buffer) => { stdout += chunk.toString('utf8') })\n child.stderr!.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })\n child.on('error', (err) => { spawnError = err as Error })\n\n const timer = setTimeout(() => {\n timedOut = true\n child.kill('SIGTERM')\n // Force-kill if SIGTERM doesn't take in 5s — happens when the\n // child is wedged waiting on an upstream grant approval.\n setTimeout(() => {\n try { child.kill('SIGKILL') }\n catch { /* already dead */ }\n }, 5000)\n }, timeoutMs)\n\n child.on('close', (code) => {\n clearTimeout(timer)\n if (spawnError) {\n resolveResult({\n stdout: '',\n stderr: '',\n exit_code: -1,\n error: spawnError.message,\n hint: `Could not exec '${BIN}'. The agent host needs @openape/apes installed globally so ape-shell is on PATH.`,\n })\n return\n }\n resolveResult({\n stdout: capStdio(stdout),\n stderr: capStdio(stderr),\n exit_code: code ?? -1,\n ...(timedOut ? { timed_out: true } : {}),\n })\n })\n })\n}\n\nexport const DEFAULTS = { DEFAULT_TIMEOUT_MS }\n","import type { ToolDefinition } from './index'\nimport { DEFAULTS, runApeShell } from './ape-shell-exec'\n\nexport const bashTools: ToolDefinition[] = [\n {\n name: 'bash',\n description:\n 'Run a shell command on the agent host. Every invocation goes through the OpenApe DDISA grant cycle — auto-approved if the owner has a matching YOLO scope, otherwise the owner gets a push notification to approve. Runs as the agent\\'s macOS user, so file/network access is limited to what that user can see. Returns stdout, stderr, and exit code. For repeated command patterns ask the owner to set up a YOLO scope so approvals don\\'t pile up.',\n parameters: {\n type: 'object',\n properties: {\n cmd: {\n type: 'string',\n description: 'Shell command to run, e.g. `ls -la ~/Documents`, `git status`, `curl -fsSL https://example.com`. The whole string is passed to `bash -c`; quote internally as needed.',\n },\n timeout_ms: {\n type: 'number',\n description: 'Wall-clock cap for the whole approval-and-run cycle in milliseconds. Default 300000 (5 min). Approval waits count against this budget.',\n },\n },\n required: ['cmd'],\n },\n execute: async (args: unknown) => {\n const a = args as { cmd?: unknown, timeout_ms?: unknown }\n if (typeof a.cmd !== 'string' || a.cmd.trim() === '') {\n throw new Error('cmd must be a non-empty string')\n }\n const timeout = typeof a.timeout_ms === 'number' && a.timeout_ms > 0\n ? a.timeout_ms\n : DEFAULTS.DEFAULT_TIMEOUT_MS\n return await runApeShell(a.cmd, timeout)\n },\n },\n]\n","import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, normalize, resolve } from 'node:path'\nimport type { ToolDefinition } from './index'\n\nconst MAX_BYTES = 1024 * 1024\n\n// All file ops are jailed inside the agent's $HOME. Path traversal\n// (`..`) is blocked by resolving the requested path against the home\n// dir and asserting the resolved path is still inside it.\nfunction jailPath(input: unknown): string {\n if (typeof input !== 'string' || input === '') {\n throw new Error('path must be a non-empty string')\n }\n const home = homedir()\n // Treat input as relative to home unless it starts with $HOME.\n const candidate = input.startsWith('~/')\n ? resolve(home, input.slice(2))\n : input.startsWith('/')\n ? normalize(input)\n : resolve(home, input)\n if (candidate !== home && !candidate.startsWith(`${home}/`)) {\n throw new Error(`path \"${input}\" resolves outside the agent's home`)\n }\n return candidate\n}\n\nexport const fileTools: ToolDefinition[] = [\n {\n name: 'file.read',\n description: 'Read a UTF-8 file from the agent\\'s home directory ($HOME). Capped at 1MB. Path traversal blocked.',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Path relative to $HOME (or absolute under $HOME). `..` segments are rejected.' },\n },\n required: ['path'],\n },\n execute: async (args: unknown) => {\n const a = args as { path: string }\n const p = jailPath(a.path)\n const content = readFileSync(p, 'utf8')\n if (Buffer.byteLength(content, 'utf8') > MAX_BYTES) {\n return { path: p, truncated: true, content: content.slice(0, MAX_BYTES) }\n }\n return { path: p, truncated: false, content }\n },\n },\n {\n name: 'file.write',\n description: 'Write a UTF-8 file under the agent\\'s home directory. Creates parent dirs as needed. 1MB max.',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Path relative to $HOME (or absolute under $HOME).' },\n content: { type: 'string', description: 'File body. Existing files are overwritten.' },\n },\n required: ['path', 'content'],\n },\n execute: async (args: unknown) => {\n const a = args as { path: string, content: string }\n if (typeof a.content !== 'string') throw new Error('content must be a string')\n if (Buffer.byteLength(a.content, 'utf8') > MAX_BYTES) {\n throw new Error(`content exceeds ${MAX_BYTES} byte cap`)\n }\n const p = jailPath(a.path)\n mkdirSync(dirname(p), { recursive: true })\n writeFileSync(p, a.content, { encoding: 'utf8' })\n return { path: p, bytes: Buffer.byteLength(a.content, 'utf8') }\n },\n },\n {\n name: 'file.edit',\n description: 'Replace an exact substring in a file under the agent\\'s home directory. Prefer this over file.write for edits — it touches only the changed region instead of rewriting the whole file. `old_string` must appear exactly once unless `replace_all` is true. Path traversal blocked, 1MB max.',\n parameters: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Path relative to $HOME (or absolute under $HOME).' },\n old_string: { type: 'string', description: 'Exact text to replace. Include enough surrounding context to be unique unless replace_all is set.' },\n new_string: { type: 'string', description: 'Replacement text. Must differ from old_string.' },\n replace_all: { type: 'boolean', description: 'Replace every occurrence instead of requiring a unique match. Default false.' },\n },\n required: ['path', 'old_string', 'new_string'],\n },\n execute: async (args: unknown) => {\n const a = args as { path?: unknown, old_string?: unknown, new_string?: unknown, replace_all?: unknown }\n if (typeof a.old_string !== 'string' || a.old_string === '') {\n throw new Error('old_string must be a non-empty string')\n }\n if (typeof a.new_string !== 'string') {\n throw new TypeError('new_string must be a string')\n }\n if (a.old_string === a.new_string) {\n throw new Error('old_string and new_string are identical — nothing to change')\n }\n const replaceAll = a.replace_all === true\n const p = jailPath(a.path)\n const before = readFileSync(p, 'utf8')\n\n const occurrences = before.split(a.old_string).length - 1\n if (occurrences === 0) {\n throw new Error('old_string not found in file')\n }\n if (occurrences > 1 && !replaceAll) {\n throw new Error(`old_string occurs ${occurrences} times — pass replace_all:true or add surrounding context to make it unique`)\n }\n\n const after = replaceAll\n ? before.split(a.old_string).join(a.new_string)\n : before.replace(a.old_string, a.new_string)\n\n if (Buffer.byteLength(after, 'utf8') > MAX_BYTES) {\n throw new Error(`result exceeds ${MAX_BYTES} byte cap`)\n }\n writeFileSync(p, after, { encoding: 'utf8' })\n return { path: p, replacements: replaceAll ? occurrences : 1 }\n },\n },\n]\n\nexport const _internal = { jailPath }\n","// Forge abstraction (M3): provider-agnostic PR/issue operations.\n//\n// Forges are NOT a closed enum baked into this library — that would lock\n// out anyone on Bitbucket / GitLab / Gitea / a self-hosted forge. They\n// are an open ADAPTER REGISTRY: GitHub (`gh`) and Azure DevOps (`az`)\n// ship built-in; anyone can `registerForge()` another (or load one from\n// recipe config). The actual CLIs are already shaped, so an adapter is\n// just \"how to recognise the remote + how to build the argv\" — the gated\n// ape-shell path executes it, no new gating machinery.\n//\n// Command-builders are pure (unit-tested). Free-text inputs (PR title/\n// body) are shell-escaped via `shq`; structured inputs (branch, pr id)\n// are charset-validated.\n\n// A forge id — 'github' / 'azure' built-in, or any registered adapter.\nexport type Forge = string\n\nconst BRANCH_RE = /^[\\w./-]{1,200}$/\nconst ID_RE = /^\\d{1,12}$/\n\n// POSIX-safe single-quote: wrap in '...' and replace any embedded\n// single quote with '\\'' . Makes arbitrary free text safe to pass\n// through `bash -c`.\nexport function shq(s: string): string {\n return `'${String(s).replace(/'/g, '\\'\\\\\\'\\'')}'`\n}\n\nexport function assertBranch(v: unknown): string {\n if (typeof v !== 'string' || !BRANCH_RE.test(v)) {\n throw new Error('branch must match ^[A-Za-z0-9._/-]{1,200}$')\n }\n return v\n}\n\nexport function assertId(v: unknown): string {\n if (typeof v !== 'string' && typeof v !== 'number') throw new Error('id required')\n const s = String(v)\n if (!ID_RE.test(s)) throw new Error('id must be a number')\n return s\n}\n\nexport interface PrCreateInput {\n forge: Forge\n title: string\n body: string\n head: string // source branch\n base?: string // target branch (default: repo default)\n}\n\nexport interface PrMergeInput {\n forge: Forge\n ref: string | number // GitHub: PR number or branch; others: PR/MR id\n auto?: boolean // arm \"merge when checks pass\" instead of immediate merge\n // Merge strategy is REPO policy, not ours. Only force squash when the\n // caller/recipe explicitly asks (squash:true); otherwise we add no\n // strategy flag and the forge/repo default applies.\n squash?: boolean\n deleteBranch?: boolean\n}\n\n// One forge's command vocabulary. Add a new forge by implementing this\n// and calling registerForge(). `matchesRemote` decides auto-detection.\nexport interface ForgeAdapter {\n id: string\n matchesRemote: (remoteUrl: string) => boolean\n prCreate: (input: PrCreateInput) => string\n prMerge: (input: PrMergeInput) => string\n prStatus: (ref: string | number) => string\n // `repo` is the target remote (URL or owner/name). Required for issue\n // lookups that run BEFORE the repo is cloned (e.g. the poll's\n // fetchIssue), where the CWD is not the repo — without it `gh issue\n // view` errors \"not a git repository\" / resolves the wrong repo.\n issueGet: (ref: string | number, repo?: string) => string\n}\n\n// --- Built-in adapters ---\n\nconst githubAdapter: ForgeAdapter = {\n id: 'github',\n matchesRemote: url => /github\\.com/i.test(url),\n prCreate: (i) => {\n const head = assertBranch(i.head)\n const parts = ['gh', 'pr', 'create', '--title', shq(i.title), '--body', shq(i.body), '--head', shq(head)]\n if (i.base !== undefined) parts.push('--base', shq(assertBranch(i.base)))\n return parts.join(' ')\n },\n prMerge: (i) => {\n const ref = String(i.ref)\n const refTok = ID_RE.test(ref) ? ref : assertBranch(ref)\n const parts = ['gh', 'pr', 'merge', shq(refTok)]\n if (i.squash === true) parts.push('--squash')\n if (i.auto) parts.push('--auto')\n if (i.deleteBranch) parts.push('--delete-branch')\n return parts.join(' ')\n },\n prStatus: (ref) => {\n const r = String(ref)\n const refTok = ID_RE.test(r) ? r : assertBranch(r)\n return `gh pr view ${shq(refTok)} --json state,mergeStateStatus,statusCheckRollup,reviewDecision`\n },\n issueGet: (ref, repo) => `gh issue view ${assertId(ref)}${repo ? ` --repo ${shq(repo)}` : ''} --json number,title,body,labels`,\n}\n\nconst azureAdapter: ForgeAdapter = {\n id: 'azure',\n matchesRemote: url => /dev\\.azure\\.com|visualstudio\\.com/i.test(url),\n prCreate: (i) => {\n const head = assertBranch(i.head)\n const parts = ['az', 'repos', 'pr', 'create', '--title', shq(i.title), '--description', shq(i.body), '--source-branch', shq(head)]\n if (i.base !== undefined) parts.push('--target-branch', shq(assertBranch(i.base)))\n return parts.join(' ')\n },\n prMerge: (i) => {\n const id = assertId(i.ref)\n const parts = ['az', 'repos', 'pr', 'update', '--id', id]\n if (i.auto) parts.push('--auto-complete', 'true')\n else parts.push('--status', 'completed')\n if (i.squash === true) parts.push('--merge-commit-message-style', 'squash')\n if (i.deleteBranch) parts.push('--delete-source-branch', 'true')\n return parts.join(' ')\n },\n prStatus: ref => `az repos pr show --id ${assertId(ref)}`,\n // Azure work items are org/project-scoped, not repo-scoped, so `repo`\n // doesn't apply here — the caller's `az` config (defaults.organization/\n // project) resolves it.\n issueGet: (ref, _repo) => `az boards work-item show --id ${assertId(ref)}`,\n}\n\n// --- Registry ---\n\nconst registry = new Map<string, ForgeAdapter>([\n [githubAdapter.id, githubAdapter],\n [azureAdapter.id, azureAdapter],\n])\n\n// Register (or override) a forge adapter — e.g. GitLab (`glab`), Gitea\n// (`tea`), Bitbucket, or a self-hosted forge. Recipes can ship adapters\n// so a team on any forge can use the coding agent.\nexport function registerForge(adapter: ForgeAdapter): void {\n registry.set(adapter.id, adapter)\n}\n\nexport function listForges(): string[] {\n return [...registry.keys()]\n}\n\nexport function getForge(id: string): ForgeAdapter {\n const a = registry.get(id)\n if (!a) {\n throw new Error(`unknown forge '${id}'. Registered: ${listForges().join(', ')}. Add one with registerForge().`)\n }\n return a\n}\n\n// Detect the forge from a git remote URL by asking each registered\n// adapter. Throws a helpful error (not a hard 2-provider rejection) so\n// the path to support a new forge is \"register an adapter\", not \"patch\n// this library\".\nexport function detectForge(remoteUrl: unknown): Forge {\n if (typeof remoteUrl !== 'string' || remoteUrl === '') {\n throw new Error('remote URL required to detect forge')\n }\n for (const a of registry.values()) {\n if (a.matchesRemote(remoteUrl)) return a.id\n }\n throw new Error(`no forge adapter matches remote: ${remoteUrl}. Registered: ${listForges().join(', ')}. Register one with registerForge() (e.g. GitLab/Bitbucket/Gitea).`)\n}\n\n// --- Public command builders (delegate to the resolved adapter) ---\n\nexport function buildPrCreate(input: PrCreateInput): string {\n return getForge(input.forge).prCreate(input)\n}\n\nexport function buildPrMerge(input: PrMergeInput): string {\n return getForge(input.forge).prMerge(input)\n}\n\nexport function buildPrStatus(forge: Forge, ref: string | number): string {\n return getForge(forge).prStatus(ref)\n}\n\nexport function buildIssueGet(forge: Forge, ref: string | number, repo?: string): string {\n return getForge(forge).issueGet(ref, repo)\n}\n\nexport const _internal = { shq, assertBranch, assertId, githubAdapter, azureAdapter, registry }\n","import type { ToolDefinition } from './index'\nimport type { Forge } from '../coding/forge'\nimport { runApeShell } from './ape-shell-exec'\nimport { buildIssueGet, buildPrCreate, buildPrMerge, buildPrStatus, detectForge } from '../coding/forge'\n\n// Resolve the forge from an explicit param or a remote URL. The\n// recipe/orchestration usually passes `forge` directly; `remote` is the\n// auto-detect fallback (git remote get-url origin). Any registered\n// adapter id is accepted (github/azure built-in, plus anything added via\n// registerForge) — getForge() validates downstream.\nfunction resolveForge(a: { forge?: unknown, remote?: unknown }): Forge {\n if (typeof a.forge === 'string' && a.forge !== '') return a.forge\n if (typeof a.remote === 'string') return detectForge(a.remote)\n throw new Error('provide a forge id (e.g. github, azure, or a registered adapter) or a remote URL to detect it')\n}\n\nconst forgeParam = { type: 'string', description: 'Target forge id (github, azure, or a registered adapter). Omit to auto-detect from `remote`.' }\nconst remoteParam = { type: 'string', description: 'git remote URL — used to auto-detect the forge when `forge` is omitted.' }\n\nexport const forgeTools: ToolDefinition[] = [\n {\n name: 'forge.pr.create',\n description: 'Open a pull request on GitHub (gh) or Azure DevOps (az). Gated via the DDISA grant cycle. Provider chosen by `forge` or auto-detected from `remote`.',\n parameters: {\n type: 'object',\n properties: {\n forge: forgeParam,\n remote: remoteParam,\n title: { type: 'string', description: 'PR title.' },\n body: { type: 'string', description: 'PR description / body.' },\n head: { type: 'string', description: 'Source branch.' },\n base: { type: 'string', description: 'Target branch. Omit for the repo default.' },\n },\n required: ['title', 'body', 'head'],\n },\n execute: async (args: unknown) => {\n const a = args as { forge?: unknown, remote?: unknown, title: string, body: string, head: string, base?: string }\n const cmd = buildPrCreate({ forge: resolveForge(a), title: a.title, body: a.body, head: a.head, base: a.base })\n return await runApeShell(cmd)\n },\n },\n {\n name: 'forge.pr.merge',\n description: 'Merge a PR — or with auto=true, arm \"merge when checks pass\" (gh --auto / az auto-complete) so the platform merges only on green CI. Gated. Never bypasses required checks (branch protection is the server-side gate).',\n parameters: {\n type: 'object',\n properties: {\n forge: forgeParam,\n remote: remoteParam,\n ref: { type: 'string', description: 'GitHub: PR number or branch. Azure: PR id.' },\n auto: { type: 'boolean', description: 'Arm merge-when-green instead of immediate merge. Recommended.' },\n squash: { type: 'boolean', description: 'Squash-merge. Default true.' },\n delete_branch: { type: 'boolean', description: 'Delete the source branch after merge.' },\n },\n required: ['ref'],\n },\n execute: async (args: unknown) => {\n const a = args as { forge?: unknown, remote?: unknown, ref: string, auto?: boolean, squash?: boolean, delete_branch?: boolean }\n const cmd = buildPrMerge({ forge: resolveForge(a), ref: a.ref, auto: a.auto, squash: a.squash, deleteBranch: a.delete_branch })\n return await runApeShell(cmd)\n },\n },\n {\n name: 'forge.pr.status',\n description: 'Fetch a PR\\'s state + checks + review decision. Gated (read).',\n parameters: {\n type: 'object',\n properties: { forge: forgeParam, remote: remoteParam, ref: { type: 'string', description: 'PR number/branch (GitHub) or id (Azure).' } },\n required: ['ref'],\n },\n execute: async (args: unknown) => {\n const a = args as { forge?: unknown, remote?: unknown, ref: string }\n return await runApeShell(buildPrStatus(resolveForge(a), a.ref))\n },\n },\n {\n name: 'forge.issue.get',\n description: 'Fetch an issue (GitHub) or work-item (Azure) — title, body, labels. Gated (read). Use to turn an assigned task into a coding run.',\n parameters: {\n type: 'object',\n properties: { forge: forgeParam, remote: remoteParam, ref: { type: 'string', description: 'Issue number (GitHub) or work-item id (Azure).' } },\n required: ['ref'],\n },\n execute: async (args: unknown) => {\n const a = args as { forge?: unknown, remote?: unknown, ref: string }\n // Pass the remote so the lookup works even when the CWD isn't the\n // target repo (e.g. before a clone).\n const repo = typeof a.remote === 'string' ? a.remote : undefined\n return await runApeShell(buildIssueGet(resolveForge(a), a.ref, repo))\n },\n },\n]\n","import { homedir } from 'node:os'\nimport { resolve } from 'node:path'\nimport process from 'node:process'\nimport type { ToolDefinition } from './index'\nimport { runApeShell } from './ape-shell-exec'\n\n// Worktree + clone roots. Default to ~/work and ~/repos but are\n// configurable per deployment via OPENAPE_CODING_WORK_DIR /\n// OPENAPE_CODING_REPOS_DIR (set by the recipe/nest). Must stay under\n// $HOME — the OS-confinement boundary the whole coding sandbox relies on.\nfunction jailedRoot(envVar: string, fallbackName: string): string {\n const home = homedir()\n const raw = process.env[envVar]\n const dir = raw ? resolve(raw) : resolve(home, fallbackName)\n if (dir !== home && !dir.startsWith(`${home}/`)) {\n throw new Error(`${envVar} (${dir}) must resolve inside the agent's home`)\n }\n return dir\n}\n\nfunction workRoot(): string {\n return jailedRoot('OPENAPE_CODING_WORK_DIR', 'work')\n}\n\nfunction reposRoot(): string {\n return jailedRoot('OPENAPE_CODING_REPOS_DIR', 'repos')\n}\n\n// Worktree lifecycle for the coding agent. All git invocations go\n// through the gated ape-shell path (runApeShell) — `git worktree add`\n// is a sandbox-leaving op, so it hits the DDISA grant / git-shape\n// matcher exactly like a terminal `apes run -- git …`.\n//\n// Layout (all under the agent's $HOME, OS-confined):\n// ~/repos/<base> cached bare-ish clone, one per repo\n// ~/work/<task_id> the per-task worktree the agent edits in\n//\n// Inputs are strictly validated + single-quoted before reaching the\n// shell. The charset rules reject quotes/metacharacters outright, so\n// the single-quoting can't be broken out of.\n\nconst TASK_ID_RE = /^[\\w.-]{1,64}$/\nconst BRANCH_RE = /^[\\w./-]{1,128}$/\n// Either an https/git remote URL, or a path (validated as jailed below).\nconst URL_RE = /^(?:https:\\/\\/|git@)[\\w@:/.-]{3,256}$/\n\nfunction assertTaskId(v: unknown): string {\n if (typeof v !== 'string' || !TASK_ID_RE.test(v)) {\n throw new Error('task_id must match ^[a-zA-Z0-9._-]{1,64}$')\n }\n return v\n}\n\nfunction assertBranch(v: unknown): string {\n if (typeof v !== 'string' || !BRANCH_RE.test(v)) {\n throw new Error('branch must match ^[A-Za-z0-9._/-]{1,128}$')\n }\n return v\n}\n\n// Resolve a repo reference to a base-clone dir + a clonable source.\n// URL → clone into ~/repos/<derived>. Local path → must be a git repo\n// already inside $HOME (jailed); used in place.\nexport function resolveRepo(repo: unknown): { source: string; baseDir: string; isUrl: boolean } {\n if (typeof repo !== 'string' || repo === '') {\n throw new Error('repo must be a non-empty string (URL or path under $HOME)')\n }\n const home = homedir()\n if (URL_RE.test(repo)) {\n const tail = repo.replace(/\\.git$/, '').replace(/[/:]+$/, '')\n const parts = tail.split(/[/:]/).filter(Boolean).slice(-2)\n const base = parts.join('-').replace(/[^\\w.-]/g, '')\n if (!base) throw new Error('could not derive a clone name from repo URL')\n return { source: repo, baseDir: resolve(reposRoot(), base), isUrl: true }\n }\n // Local path — jail under $HOME.\n const candidate = repo.startsWith('~/') ? resolve(home, repo.slice(2)) : resolve(home, repo)\n if (candidate !== home && !candidate.startsWith(`${home}/`)) {\n throw new Error(`repo path \"${repo}\" resolves outside the agent's home`)\n }\n return { source: candidate, baseDir: candidate, isUrl: false }\n}\n\nexport function worktreePathFor(taskId: string): string {\n return resolve(workRoot(), assertTaskId(taskId))\n}\n\nconst q = (s: string): string => `'${s}'` // safe: callers validate charset first\n\nexport function buildCreateCommand(repo: unknown, taskId: string, branch: string): string {\n const id = assertTaskId(taskId)\n const br = assertBranch(branch)\n const { source, baseDir, isUrl } = resolveRepo(repo)\n const wt = worktreePathFor(id)\n const clone = isUrl\n ? `if [ ! -d ${q(baseDir)}/.git ]; then git clone ${q(source)} ${q(baseDir)}; fi`\n : `test -d ${q(baseDir)}/.git`\n // A polling agent re-attempts the same issue (same task id → same branch\n // + worktree path) on every tick, so creation must be idempotent: tear\n // down any leftover worktree from a prior run, then add fresh with `-B`\n // (create-or-reset the branch). The cleanup group never fails the chain.\n const reset = [\n `git -C ${q(baseDir)} worktree remove --force ${q(wt)} 2>/dev/null || true`,\n `git -C ${q(baseDir)} worktree prune 2>/dev/null || true`,\n `rm -rf ${q(wt)} 2>/dev/null || true`,\n ].join('; ')\n // Non-interactive GitHub auth for the clone (shared by all its worktrees).\n // A spawned agent's git defaults to credential.helper=osxkeychain, which\n // hangs headless (no GUI) — so ANY `git push` the LLM runs itself would\n // block. Point credential.helper at $GH_TOKEN (read from the gated shell's\n // env at push time, never stored) so every git operation authenticates\n // without a prompt. GitHub-only; other forges keep their default helper.\n const ghAuth = /github\\.com/i.test(source)\n ? `git -C ${q(baseDir)} config credential.helper '!f() { echo username=x-access-token; echo \"password=$GH_TOKEN\"; }; f'`\n : 'true'\n return [\n `mkdir -p ${q(reposRoot())} ${q(workRoot())}`,\n clone,\n ghAuth,\n `git -C ${q(baseDir)} fetch --quiet || true`,\n `{ ${reset}; }`,\n `git -C ${q(baseDir)} worktree add -B ${q(br)} ${q(wt)}`,\n `echo ${q(wt)}`,\n ].join(' && ')\n}\n\nexport function buildRemoveCommand(repo: unknown, taskId: string): string {\n const id = assertTaskId(taskId)\n const { baseDir } = resolveRepo(repo)\n const wt = worktreePathFor(id)\n return `git -C ${q(baseDir)} worktree remove --force ${q(wt)} && git -C ${q(baseDir)} worktree prune`\n}\n\nexport function buildListCommand(): string {\n return `ls -1 ${q(workRoot())} 2>/dev/null || true`\n}\n\nexport const gitWorktreeTools: ToolDefinition[] = [\n {\n name: 'git.worktree',\n description: 'Manage isolated git worktrees for coding tasks. action=create clones the repo (cached under ~/repos) and adds a fresh worktree under ~/work/<task_id> on a new branch. action=remove tears it down. action=list shows current task worktrees. Git operations go through the DDISA grant cycle (git-shape).',\n parameters: {\n type: 'object',\n properties: {\n action: { type: 'string', enum: ['create', 'remove', 'list'], description: 'create | remove | list' },\n repo: { type: 'string', description: 'For create/remove: git remote URL (https/git@) or a path under $HOME to an existing clone.' },\n task_id: { type: 'string', description: 'For create/remove: identifier for the worktree, ^[a-zA-Z0-9._-]{1,64}$. The worktree lands at ~/work/<task_id>.' },\n branch: { type: 'string', description: 'For create: new branch name, ^[A-Za-z0-9._/-]{1,128}$.' },\n },\n required: ['action'],\n },\n execute: async (args: unknown) => {\n const a = args as { action?: unknown, repo?: unknown, task_id?: unknown, branch?: unknown }\n let cmd: string\n if (a.action === 'create') {\n if (typeof a.branch !== 'string') throw new Error('branch is required for action=create')\n cmd = buildCreateCommand(a.repo, assertTaskId(a.task_id), a.branch)\n }\n else if (a.action === 'remove') {\n cmd = buildRemoveCommand(a.repo, assertTaskId(a.task_id))\n }\n else if (a.action === 'list') {\n cmd = buildListCommand()\n }\n else {\n throw new Error('action must be one of: create, remove, list')\n }\n const res = await runApeShell(cmd)\n return {\n action: a.action,\n ...(a.action !== 'list' ? { worktree: worktreePathFor(assertTaskId(a.task_id)) } : {}),\n stdout: res.stdout,\n stderr: res.stderr,\n exit_code: res.exit_code,\n ...(res.error ? { error: res.error, hint: res.hint } : {}),\n }\n },\n },\n]\n\nexport const _internal = { resolveRepo, worktreePathFor, buildCreateCommand, buildRemoveCommand, buildListCommand, assertTaskId, assertBranch }\n","import type { ToolDefinition } from './index'\n\nconst MAX_BYTES = 1024 * 1024\n// Headers we never let the model set: hop-by-hop ones, host (we\n// don't want to spoof another origin) and authorization (the model\n// would otherwise be a step away from \"fetch tasks.openape.ai with my\n// own JWT\" — that's a manual escalation path, not a tool the agent\n// gets out of the box).\nconst FORBIDDEN_HEADERS = new Set([\n 'host',\n 'authorization',\n 'cookie',\n 'connection',\n 'transfer-encoding',\n 'upgrade',\n 'proxy-authorization',\n])\n\nfunction sanitizeHeaders(input: unknown): Record<string, string> {\n if (!input || typeof input !== 'object') return {}\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(input as Record<string, unknown>)) {\n if (typeof v !== 'string') continue\n if (FORBIDDEN_HEADERS.has(k.toLowerCase())) continue\n out[k] = v\n }\n return out\n}\n\nasync function readCappedBody(res: Response): Promise<string> {\n const buf = new Uint8Array(MAX_BYTES + 1)\n let written = 0\n const reader = res.body?.getReader()\n if (!reader) return await res.text()\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n if (written + value.byteLength > MAX_BYTES) {\n buf.set(value.subarray(0, MAX_BYTES - written), written)\n written = MAX_BYTES\n try { await reader.cancel() }\n catch { /* ignore */ }\n break\n }\n buf.set(value, written)\n written += value.byteLength\n }\n return new TextDecoder().decode(buf.subarray(0, written))\n}\n\nexport const httpTools: ToolDefinition[] = [\n {\n name: 'http.get',\n description: 'GET an HTTPS URL and return the response body (capped at 1MB). Useful for reading public APIs, RSS feeds, web pages.',\n parameters: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'Absolute HTTPS URL.' },\n headers: { type: 'object', description: 'Optional headers (Host, Authorization, Cookie are stripped).' },\n },\n required: ['url'],\n },\n execute: async (args: unknown) => {\n const a = args as { url: string, headers?: unknown }\n if (typeof a.url !== 'string' || !a.url.startsWith('http')) {\n throw new Error('url must be an http(s) URL')\n }\n const res = await fetch(a.url, { method: 'GET', headers: sanitizeHeaders(a.headers) })\n const body = await readCappedBody(res)\n return { status: res.status, headers: Object.fromEntries(res.headers), body }\n },\n },\n {\n name: 'http.post',\n description: 'POST JSON to an HTTPS URL and return the response body (capped at 1MB).',\n parameters: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'Absolute HTTPS URL.' },\n body: { description: 'JSON-serialisable payload.' },\n headers: { type: 'object', description: 'Optional headers (Host, Authorization, Cookie are stripped).' },\n },\n required: ['url', 'body'],\n },\n execute: async (args: unknown) => {\n const a = args as { url: string, body: unknown, headers?: unknown }\n if (typeof a.url !== 'string' || !a.url.startsWith('http')) {\n throw new Error('url must be an http(s) URL')\n }\n const res = await fetch(a.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...sanitizeHeaders(a.headers) },\n body: JSON.stringify(a.body),\n })\n const body = await readCappedBody(res)\n return { status: res.status, headers: Object.fromEntries(res.headers), body }\n },\n },\n]\n","import { execFileSync } from 'node:child_process'\nimport type { ToolDefinition } from './index'\n\n// Shell out to o365-cli for read-only mail access. Same auth model\n// as ape-tasks: the agent's macOS user has o365-cli installed +\n// authenticated, agent runs as that user.\n\nfunction o365(args: string[]): string {\n try {\n return execFileSync('o365-cli', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })\n }\n catch (err) {\n const e = err as { stderr?: Buffer | string, code?: string, message?: string }\n if (e.code === 'ENOENT') {\n throw new Error('o365-cli is not installed on this agent host')\n }\n const stderr = typeof e.stderr === 'string' ? e.stderr : e.stderr?.toString('utf8')\n throw new Error(`o365-cli failed: ${stderr ?? e.message ?? err}`)\n }\n}\n\nexport const mailTools: ToolDefinition[] = [\n {\n name: 'mail.list',\n description: 'List recent inbox messages via o365-cli. Optional `unread_only` and `limit`.',\n parameters: {\n type: 'object',\n properties: {\n limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },\n unread_only: { type: 'boolean', default: false },\n },\n required: [],\n },\n execute: async (args: unknown) => {\n const a = (args as { limit?: number, unread_only?: boolean }) ?? {}\n const argv = ['mail', 'list', '--json', '--limit', String(a.limit ?? 20)]\n if (a.unread_only) argv.push('--unread')\n const out = o365(argv)\n try { return JSON.parse(out) }\n catch { return { raw: out } }\n },\n },\n {\n name: 'mail.search',\n description: 'Search the inbox via o365-cli using a free-form query string.',\n parameters: {\n type: 'object',\n properties: {\n q: { type: 'string' },\n limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },\n },\n required: ['q'],\n },\n execute: async (args: unknown) => {\n const a = args as { q: string, limit?: number }\n if (typeof a.q !== 'string' || a.q.length === 0) throw new Error('q is required')\n const argv = ['mail', 'search', a.q, '--json', '--limit', String(a.limit ?? 20)]\n const out = o365(argv)\n try { return JSON.parse(out) }\n catch { return { raw: out } }\n },\n },\n]\n","import { execFileSync } from 'node:child_process'\nimport type { ToolDefinition } from './index'\n\n// Shell out to the user's `ape-tasks` CLI. The agent's macOS user\n// has its own ~/.config/apes/auth.json, so the CLI talks to\n// tasks.openape.ai as the agent's owner via the agent JWT (which\n// carries the owner-domain). For v1 we don't require a separate\n// agent identity for tasks — the tasks CLI authenticates with the\n// same auth.json the runtime uses.\n\nfunction ape(args: string[]): string {\n try {\n return execFileSync('ape-tasks', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })\n }\n catch (err) {\n const e = err as { stderr?: Buffer | string, message?: string }\n const stderr = typeof e.stderr === 'string' ? e.stderr : e.stderr?.toString('utf8')\n throw new Error(`ape-tasks failed: ${stderr ?? e.message ?? err}`)\n }\n}\n\nexport const tasksTools: ToolDefinition[] = [\n {\n name: 'tasks.list',\n description: 'List the owner\\'s open ape-tasks (the user\\'s personal task list at tasks.openape.ai).',\n parameters: {\n type: 'object',\n properties: {\n status: { type: 'string', enum: ['open', 'doing', 'done', 'archived'] },\n team_id: { type: 'string' },\n },\n required: [],\n },\n execute: async (args: unknown) => {\n const a = (args as { status?: string, team_id?: string }) ?? {}\n const argv = ['list', '--json']\n if (a.status) argv.push('--status', a.status)\n if (a.team_id) argv.push('--team', a.team_id)\n const out = ape(argv)\n try { return JSON.parse(out) }\n catch { return { raw: out } }\n },\n },\n {\n name: 'tasks.create',\n description: 'Create a new ape-task on the owner\\'s task list at tasks.openape.ai.',\n parameters: {\n type: 'object',\n properties: {\n title: { type: 'string' },\n notes: { type: 'string' },\n priority: { type: 'string', enum: ['low', 'med', 'high'] },\n due_at: { type: 'string', description: 'ISO date or +Nh/+Nd shorthand.' },\n },\n required: ['title'],\n },\n execute: async (args: unknown) => {\n const a = args as { title: string, notes?: string, priority?: string, due_at?: string }\n const argv = ['new', '--title', a.title, '--json']\n if (a.notes) argv.push('--notes', a.notes)\n if (a.priority) argv.push('--priority', a.priority)\n if (a.due_at) argv.push('--due', a.due_at)\n const out = ape(argv)\n try { return JSON.parse(out) }\n catch { return { raw: out } }\n },\n },\n]\n","import type { ToolDefinition } from './index'\n\nexport const timeTools: ToolDefinition[] = [\n {\n name: 'time.now',\n description: 'Returns the current UTC date and time as ISO 8601 plus epoch seconds. No inputs.',\n parameters: { type: 'object', properties: {}, required: [] },\n execute: async () => {\n const now = new Date()\n return {\n iso: now.toISOString(),\n epoch_seconds: Math.floor(now.getTime() / 1000),\n timezone_offset_minutes: -now.getTimezoneOffset(),\n }\n },\n },\n]\n","// Verification loop (M2). Runs the configured test/build command in a\n// worktree via the gated ape-shell path and reports pass/fail. This is\n// the local gate: the coding loop must NOT proceed to the PR/merge\n// phase on a non-zero exit. Branch protection is the second, server-\n// side gate.\n\nimport { runApeShell } from '../agent-tools/ape-shell-exec'\n\nexport interface VerifyResult {\n passed: boolean\n exit_code: number\n stdout: string\n stderr: string\n timed_out?: boolean\n}\n\nconst CWD_RE = /^[\\w./-]{1,256}$/\n\n// Run `command` in `cwd` (a worktree path). The command string is the\n// recipe-configured verify command (e.g. `pnpm test`). cwd is charset-\n// validated; both go through the gated path so the run is grant-scoped\n// exactly like a terminal invocation.\nexport async function runVerify(cwd: string, command: string, timeoutMs?: number): Promise<VerifyResult> {\n if (typeof cwd !== 'string' || !CWD_RE.test(cwd)) {\n throw new Error('cwd must match ^[A-Za-z0-9._/-]{1,256}$')\n }\n if (typeof command !== 'string' || command.trim() === '') {\n throw new Error('verify command must be a non-empty string')\n }\n // `cd <cwd> && <command>` — cwd validated above; command is the\n // operator-configured verify command (trusted recipe config, not\n // agent free-text).\n const res = await runApeShell(`cd '${cwd}' && ${command}`, timeoutMs)\n return {\n passed: res.exit_code === 0,\n exit_code: res.exit_code,\n stdout: res.stdout,\n stderr: res.stderr,\n ...(res.timed_out ? { timed_out: true } : {}),\n }\n}\n","import type { ToolDefinition } from './index'\nimport { runVerify } from '../coding/verify'\n\nexport const verifyTools: ToolDefinition[] = [\n {\n name: 'verify',\n description: 'Run the verification command (tests/build/lint) in a worktree and report pass/fail. The coding loop must NOT open or merge a PR when this fails. Runs through the DDISA grant cycle (same as bash). Returns { passed, exit_code, stdout, stderr }.',\n parameters: {\n type: 'object',\n properties: {\n cwd: { type: 'string', description: 'Worktree path to run in (e.g. ~/work/issue-42).' },\n command: { type: 'string', description: 'Verification command, e.g. `pnpm test` or `npm run build && npm test`.' },\n timeout_ms: { type: 'number', description: 'Wall-clock cap incl. approval wait. Default 300000.' },\n },\n required: ['cwd', 'command'],\n },\n execute: async (args: unknown) => {\n const a = args as { cwd?: unknown, command?: unknown, timeout_ms?: unknown }\n const timeout = typeof a.timeout_ms === 'number' && a.timeout_ms > 0 ? a.timeout_ms : undefined\n return await runVerify(a.cwd as string, a.command as string, timeout)\n },\n },\n]\n","// Built-in tool registry shipped with the apes binary. Each tool is\n// (a) an OpenAI tool-spec object (used as-is in the LiteLLM call's\n// `tools[]` parameter) and (b) an `execute` function called when the\n// model emits a `tool_calls` entry. Adding a new tool means\n// implementing it here AND adding an entry to\n// apps/openape-troop/server/tool-catalog.json so the SP validates\n// task specs against the same allowlist.\n//\n// The registry is keyed by string name (`time.now`, `http.get`, …).\n// `taskTools(spec.tools)` resolves a task's tool list to the slice of\n// the registry it can use. Unknown names abort the run before any\n// LLM call so the model can't invent a tool we haven't shipped.\n\nimport { bashTools } from './bash'\nimport { fileTools } from './file'\nimport { forgeTools } from './forge'\nimport { gitWorktreeTools } from './git-worktree'\nimport { httpTools } from './http'\nimport { mailTools } from './mail'\nimport { tasksTools } from './tasks'\nimport { timeTools } from './time'\nimport { verifyTools } from './verify'\n\nexport interface ToolDefinition {\n name: string\n description: string\n // OpenAI tool-spec shape: { type: 'object', properties: …, required: … }.\n // We don't constrain it further — the LLM's job to fill it in.\n parameters: Record<string, unknown>\n execute: (args: unknown) => Promise<unknown>\n}\n\nconst ALL_TOOLS: ToolDefinition[] = [\n ...timeTools,\n ...httpTools,\n ...fileTools,\n ...tasksTools,\n ...mailTools,\n ...bashTools,\n ...gitWorktreeTools,\n ...verifyTools,\n ...forgeTools,\n]\n\nexport const TOOLS: Record<string, ToolDefinition> = Object.fromEntries(\n ALL_TOOLS.map(t => [t.name, t]),\n)\n\n/**\n * Resolve a task spec's tool name list to ToolDefinitions. Throws on\n * unknown names — callers must surface that as a run-failure with a\n * clear \"unknown tool: foo\" final_message so the owner can see what\n * went wrong in the SP UI.\n */\nexport function taskTools(names: string[]): ToolDefinition[] {\n const out: ToolDefinition[] = []\n const missing: string[] = []\n for (const name of names) {\n const tool = TOOLS[name]\n if (!tool) missing.push(name)\n else out.push(tool)\n }\n if (missing.length > 0) {\n throw new Error(`unknown tool(s): ${missing.join(', ')}`)\n }\n return out\n}\n\n/**\n * Format the registry slice as the OpenAI `tools` param. Strips the\n * `execute` function — only the spec part goes to the LLM.\n *\n * Tool names get sent through `wireToolName()` because some upstreams\n * — notably ChatGPT's Responses API behind LiteLLM — enforce\n * `^[a-zA-Z0-9_-]+$` and reject our dotted catalog names like\n * `time.now`. Use `localToolName()` to map back when the model emits\n * a tool_call.\n */\nexport function asOpenAiTools(tools: ToolDefinition[]): { type: 'function', function: Omit<ToolDefinition, 'execute'> }[] {\n return tools.map(t => ({\n type: 'function' as const,\n function: { name: wireToolName(t.name), description: t.description, parameters: t.parameters },\n }))\n}\n\n/** Encode a local tool name (e.g. `time.now`) for the wire format. */\nexport function wireToolName(local: string): string {\n return local.replace(/\\./g, '_')\n}\n\n/**\n * Decode a tool name from the wire format back to its local form. The\n * encoding is `.` → `_`; we recover the original by looking for an\n * exact match in the catalog and only fall back to passing the name\n * through if no match is found (so unknown tool names still surface\n * as the obvious \"unknown tool\" error rather than silent rewrites).\n */\nexport function localToolName(wire: string): string {\n for (const t of Object.values(TOOLS)) {\n if (wireToolName(t.name) === wire) return t.name\n }\n return wire\n}\n","import { asOpenAiTools, localToolName, wireToolName } from './agent-tools'\nimport type { ToolDefinition } from './agent-tools'\n\n// Shared agent loop: send messages + tools to LiteLLM (OpenAI-\n// compatible chat-completions API), execute any tool_calls in the\n// response, append tool-result messages, loop until the model\n// returns a response with no tool_calls or we hit max_steps.\n//\n// Both `apes agents run` (cron) and `apes agents serve --rpc`\n// (chat-bridge subprocess) call into here so the LLM behaviour is\n// guaranteed identical between modes.\n\nexport interface ChatMessage {\n role: 'system' | 'user' | 'assistant' | 'tool'\n content: string | null\n // Assistant message tool calls\n tool_calls?: Array<{\n id: string\n type: 'function'\n function: { name: string, arguments: string }\n }>\n // Tool message metadata\n tool_call_id?: string\n name?: string\n}\n\nexport interface RuntimeConfig {\n apiBase: string // LITELLM_BASE_URL (e.g. \"http://127.0.0.1:4000/v1\")\n apiKey: string // LITELLM_API_KEY (or LITELLM_MASTER_KEY)\n model: string\n}\n\nexport interface TraceEntry {\n step: number\n type: 'assistant' | 'tool_call' | 'tool_result' | 'tool_error'\n // Stripped down for trace: don't carry full bodies\n preview: string\n tool?: string\n}\n\nexport interface RunResult {\n status: 'ok' | 'error'\n finalMessage: string | null\n stepCount: number\n trace: TraceEntry[]\n}\n\nexport interface RunStreamHandlers {\n onTextDelta?: (delta: string) => void\n onToolCall?: (call: { name: string, args: unknown }) => void\n onToolResult?: (result: { name: string, result: unknown }) => void\n onToolError?: (err: { name: string, error: string }) => void\n onDone?: (result: RunResult) => void\n}\n\nexport interface RunOptions {\n config: RuntimeConfig\n systemPrompt: string\n userMessage: string\n tools: ToolDefinition[]\n maxSteps: number\n // Pre-existing message history for continued sessions (RPC mode).\n // The system prompt is always prepended, even if `history` is\n // non-empty — the SP-stored prompt is canonical. Defaults to []\n // (a fresh single-user-turn conversation).\n history?: ChatMessage[]\n handlers?: RunStreamHandlers\n // Test seam — replace fetch (we always use the global fetch in\n // production). Tests pass a mock that returns canned responses.\n fetchImpl?: typeof fetch\n}\n\ninterface OpenAIChoice {\n message: ChatMessage\n finish_reason?: string\n}\ninterface OpenAIChatResponse {\n choices: OpenAIChoice[]\n}\n\nfunction previewJson(value: unknown, max = 500): string {\n let s: string\n try { s = JSON.stringify(value) }\n catch { s = String(value) }\n return s.length > max ? `${s.slice(0, max)}…` : s\n}\n\nexport async function runLoop(opts: RunOptions): Promise<RunResult> {\n const fetchFn = opts.fetchImpl ?? fetch\n const trace: TraceEntry[] = []\n const messages: ChatMessage[] = [\n { role: 'system', content: opts.systemPrompt },\n ...(opts.history ?? []),\n { role: 'user', content: opts.userMessage },\n ]\n const tools = asOpenAiTools(opts.tools)\n\n for (let step = 1; step <= opts.maxSteps; step++) {\n const res = await fetchFn(`${opts.config.apiBase}/chat/completions`, {\n method: 'POST',\n headers: {\n 'authorization': `Bearer ${opts.config.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n model: opts.config.model,\n messages,\n ...(tools.length > 0 ? { tools, tool_choice: 'auto' } : {}),\n }),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`LiteLLM ${res.status}: ${text.slice(0, 500)}`)\n }\n const data = await res.json() as OpenAIChatResponse\n const choice = data.choices?.[0]\n if (!choice) throw new Error('LiteLLM response had no choices')\n\n const assistant = choice.message\n messages.push(assistant)\n if (assistant.content) opts.handlers?.onTextDelta?.(assistant.content)\n\n trace.push({\n step,\n type: 'assistant',\n preview: previewJson({ content: assistant.content, tool_calls: assistant.tool_calls?.length ?? 0 }),\n })\n\n if (!assistant.tool_calls || assistant.tool_calls.length === 0) {\n const result: RunResult = {\n status: 'ok',\n finalMessage: assistant.content,\n stepCount: step,\n trace,\n }\n opts.handlers?.onDone?.(result)\n return result\n }\n\n // Execute each tool call; the model sees the result on the next turn.\n // Wire-format names (`time_now`) get decoded to local catalog names\n // (`time.now`) for lookup + handler events; we send back the same\n // wire name in the tool message so the next request validates.\n for (const call of assistant.tool_calls) {\n const wireName = call.function.name\n const localName = localToolName(wireName)\n const tool = opts.tools.find(t => t.name === localName)\n let parsedArgs: unknown\n try { parsedArgs = JSON.parse(call.function.arguments) }\n catch { parsedArgs = {} }\n opts.handlers?.onToolCall?.({ name: localName, args: parsedArgs })\n trace.push({ step, type: 'tool_call', tool: localName, preview: previewJson(parsedArgs) })\n\n let result: unknown\n let isError = false\n if (!tool) {\n result = `unknown tool: ${localName}`\n isError = true\n }\n else {\n try {\n result = await tool.execute(parsedArgs)\n }\n catch (err) {\n result = (err as Error)?.message ?? String(err)\n isError = true\n }\n }\n\n if (isError) {\n opts.handlers?.onToolError?.({ name: localName, error: String(result) })\n trace.push({ step, type: 'tool_error', tool: localName, preview: previewJson(result) })\n }\n else {\n opts.handlers?.onToolResult?.({ name: localName, result })\n trace.push({ step, type: 'tool_result', tool: localName, preview: previewJson(result) })\n }\n\n messages.push({\n role: 'tool',\n tool_call_id: call.id,\n name: wireToolName(localName),\n content: typeof result === 'string' ? result : JSON.stringify(result),\n })\n }\n }\n\n // Loop fell through max_steps without a no-tool-calls reply.\n const result: RunResult = {\n status: 'error',\n finalMessage: `max_steps (${opts.maxSteps}) reached without completion`,\n stepCount: opts.maxSteps,\n trace,\n }\n opts.handlers?.onDone?.(result)\n return result\n}\n\nexport interface RpcSession {\n messages: ChatMessage[]\n systemPrompt: string\n tools: ToolDefinition[]\n maxSteps: number\n lastTouched: number\n}\n\nconst RPC_SESSION_TTL_MS = 60 * 60 * 1000\n\nexport class RpcSessionMap {\n private sessions = new Map<string, RpcSession>()\n\n get(id: string): RpcSession | undefined {\n const s = this.sessions.get(id)\n if (s) s.lastTouched = Date.now()\n return s\n }\n\n put(id: string, s: RpcSession): void {\n s.lastTouched = Date.now()\n this.sessions.set(id, s)\n }\n\n evictStale(): void {\n const cutoff = Date.now() - RPC_SESSION_TTL_MS\n for (const [k, v] of this.sessions) {\n if (v.lastTouched < cutoff) this.sessions.delete(k)\n }\n }\n\n size(): number {\n return this.sessions.size\n }\n}\n"],"mappings":";;;AAAO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YAAY,SAAwB,WAAmB,GAAG;AACxD,UAAM,OAAO;AADqB;AAElC,SAAK,OAAO;AAAA,EACd;AAAA,EAHoC;AAItC;AAEO,IAAM,UAAN,cAAsB,MAAM;AAAA,EACjC,YAAmB,WAAmB,GAAG;AACvC,UAAM,EAAE;AADS;AAEjB,SAAK,OAAO;AAAA,EACd;AAAA,EAHmB;AAIrB;;;ACRO,SAAS,cAAc,OAAuB;AACnD,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OA,YAAW,WAAWA,UAAS,KAAK,UAAUA,OAAM;AAAA,MACtE,CAAC;AAAA,IACH;AAAA,EACF;AAGA,QAAM,SAAoB;AAAA,IACxB,QAAQ;AAAA,IACR,cAAc,cAAc,KAAK,QAAQ;AAAA,IACzC,WAAW,KAAK;AAAA,IAChB;AAAA,EACF;AACA,OAAK,UAAU,SAAS,MAAM;AAC9B,SAAO;AACT;AAUA,IAAM,qBAAqB,KAAK,KAAK;AAE9B,IAAM,gBAAN,MAAoB;AAAA,EACjB,WAAW,oBAAI,IAAwB;AAAA,EAE/C,IAAI,IAAoC;AACtC,UAAM,IAAI,KAAK,SAAS,IAAI,EAAE;AAC9B,QAAI,EAAG,GAAE,cAAc,KAAK,IAAI;AAChC,WAAO;AAAA,EACT;AAAA,EAEA,IAAI,IAAY,GAAqB;AACnC,MAAE,cAAc,KAAK,IAAI;AACzB,SAAK,SAAS,IAAI,IAAI,CAAC;AAAA,EACzB;AAAA,EAEA,aAAmB;AACjB,UAAM,SAAS,KAAK,IAAI,IAAI;AAC5B,eAAW,CAAC,GAAG,CAAC,KAAK,KAAK,UAAU;AAClC,UAAI,EAAE,cAAc,OAAQ,MAAK,SAAS,OAAO,CAAC;AAAA,IACpD;AAAA,EACF;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,SAAS;AAAA,EACvB;AACF;","names":["homedir","resolve","process","homedir","process","resolve","BRANCH_RE","assertBranch","MAX_BYTES","execFileSync","result"]}
package/dist/cli.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  runLoop,
14
14
  taskTools,
15
15
  worktreePathFor
16
- } from "./chunk-SWRK4SWT.js";
16
+ } from "./chunk-66NFSMCY.js";
17
17
  import {
18
18
  loadEd25519PrivateKey,
19
19
  readPublicKeyComment
@@ -2899,7 +2899,7 @@ Worktree: ${worktree}`,
2899
2899
  if (commitRes.exit_code !== 0) {
2900
2900
  return { branch, worktree, runStatus: "ok", changedFiles, decision, outcome: "run-failed", prRef: branch, reason: `commit failed: ${(commitRes.stderr || commitRes.stdout).slice(0, 300)}` };
2901
2901
  }
2902
- const pushRes = await shell(`git -C '${worktree}' -c credential.helper='!gh auth git-credential' push -u origin '${branch}'`);
2902
+ const pushRes = await shell(buildPushCommand(input.forge, input.repo, worktree, branch));
2903
2903
  if (pushRes.exit_code !== 0) {
2904
2904
  return { branch, worktree, runStatus: "ok", changedFiles, decision, outcome: "run-failed", prRef: branch, reason: `push failed: ${(pushRes.stderr || pushRes.stdout).slice(0, 300)}` };
2905
2905
  }
@@ -2931,6 +2931,14 @@ Automated by the OpenApe coding agent.`;
2931
2931
  function shqMsg(issue) {
2932
2932
  return `'${prTitle(issue).replace(/'/g, "'\\''")}'`;
2933
2933
  }
2934
+ function buildPushCommand(forge, repo, worktree, branch) {
2935
+ const base = `GIT_TERMINAL_PROMPT=0 git -C '${worktree}'`;
2936
+ if (forge === "github") {
2937
+ const slug = repo.replace(/^[a-z]+:\/\/[^/]+\//i, "").replace(/\.git$/, "").replace(/['"\s]/g, "");
2938
+ return `${base} push "https://x-access-token:\${GH_TOKEN}@github.com/${slug}.git" '${branch}'`;
2939
+ }
2940
+ return `${base} push -u origin '${branch}'`;
2941
+ }
2934
2942
 
2935
2943
  // src/lib/coding/llm-review.ts
2936
2944
  var DIFF_CAP2 = 48 * 1024;
@@ -3105,9 +3113,10 @@ function readLitellmConfig(model) {
3105
3113
  for (const k of ["LITELLM_API_KEY", "LITELLM_MASTER_KEY", "LITELLM_BASE_URL"]) {
3106
3114
  if (process2.env[k]) env[k] = process2.env[k];
3107
3115
  }
3108
- const apiKey = env.LITELLM_API_KEY || env.LITELLM_MASTER_KEY;
3109
3116
  const apiBase = (env.LITELLM_BASE_URL || "http://127.0.0.1:4000/v1").replace(/\/$/, "");
3110
- if (!apiKey) throw new CliError2("No LITELLM_API_KEY / LITELLM_MASTER_KEY in ~/litellm/.env or env.");
3117
+ const isLoopback = /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:\/|$)/.test(apiBase);
3118
+ const apiKey = env.LITELLM_API_KEY || env.LITELLM_MASTER_KEY || (isLoopback ? "sk-loopback-noauth" : "");
3119
+ if (!apiKey) throw new CliError2("No LITELLM_API_KEY / LITELLM_MASTER_KEY for non-loopback LITELLM_BASE_URL.");
3111
3120
  return { apiBase, apiKey, model: model || process2.env.APE_CHAT_BRIDGE_MODEL || "claude-haiku-4-5" };
3112
3121
  }
3113
3122
  function readPersona(file) {
@@ -6751,7 +6760,7 @@ var mcpCommand = defineCommand52({
6751
6760
  if (transport !== "stdio" && transport !== "sse") {
6752
6761
  throw new Error('Transport must be "stdio" or "sse"');
6753
6762
  }
6754
- const { startMcpServer } = await import("./server-2VKIFWFT.js");
6763
+ const { startMcpServer } = await import("./server-ZK3X66QJ.js");
6755
6764
  await startMcpServer(transport, port);
6756
6765
  }
6757
6766
  });
@@ -7389,7 +7398,7 @@ async function bestEffortGrantCount(idp) {
7389
7398
  }
7390
7399
  }
7391
7400
  async function runHealth(args) {
7392
- const version = true ? "1.28.8" : "0.0.0";
7401
+ const version = true ? "1.28.10" : "0.0.0";
7393
7402
  const auth = loadAuth();
7394
7403
  if (!auth) {
7395
7404
  throw new CliError("Not logged in. Run `apes login` first.", 1);
@@ -7662,10 +7671,10 @@ if (shellRewrite) {
7662
7671
  if (shellRewrite.action === "rewrite") {
7663
7672
  process.argv = shellRewrite.argv;
7664
7673
  } else if (shellRewrite.action === "version") {
7665
- console.log(`ape-shell ${"1.28.8"} (OpenApe DDISA shell wrapper)`);
7674
+ console.log(`ape-shell ${"1.28.10"} (OpenApe DDISA shell wrapper)`);
7666
7675
  process.exit(0);
7667
7676
  } else if (shellRewrite.action === "help") {
7668
- console.log(`ape-shell ${"1.28.8"} \u2014 OpenApe DDISA shell wrapper`);
7677
+ console.log(`ape-shell ${"1.28.10"} \u2014 OpenApe DDISA shell wrapper`);
7669
7678
  console.log("");
7670
7679
  console.log("Usage:");
7671
7680
  console.log(" ape-shell Start interactive grant-mediated REPL");
@@ -7723,7 +7732,7 @@ var configCommand = defineCommand64({
7723
7732
  var main = defineCommand64({
7724
7733
  meta: {
7725
7734
  name: "apes",
7726
- version: "1.28.8",
7735
+ version: "1.28.10",
7727
7736
  description: "Unified CLI for OpenApe"
7728
7737
  },
7729
7738
  subCommands: {
@@ -7781,7 +7790,7 @@ async function maybeRefreshAuth() {
7781
7790
  }
7782
7791
  }
7783
7792
  await maybeRefreshAuth();
7784
- await maybeWarnStaleVersion("1.28.8").catch(() => {
7793
+ await maybeWarnStaleVersion("1.28.10").catch(() => {
7785
7794
  });
7786
7795
  runMain(main).catch((err) => {
7787
7796
  if (err instanceof CliExit) {