@openape/apes 1.20.0 → 1.21.0

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.
@@ -37,6 +37,90 @@ function parseDuration(value) {
37
37
  }
38
38
  }
39
39
 
40
+ // src/lib/agent-tools/bash.ts
41
+ import { spawn } from "child_process";
42
+ var DEFAULT_TIMEOUT_MS = 5 * 60 * 1e3;
43
+ var MAX_STDIO_BYTES = 64 * 1024;
44
+ var BIN = "ape-shell";
45
+ function capStdio(s) {
46
+ const buf = Buffer.from(s, "utf8");
47
+ if (buf.byteLength <= MAX_STDIO_BYTES) return s;
48
+ return `${buf.subarray(0, MAX_STDIO_BYTES).toString("utf8")}
49
+ [truncated to ${MAX_STDIO_BYTES} bytes]`;
50
+ }
51
+ var bashTools = [
52
+ {
53
+ name: "bash",
54
+ description: "Run a shell command on the agent host. Every invocation goes through the OpenApe DDISA grant cycle \u2014 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.",
55
+ parameters: {
56
+ type: "object",
57
+ properties: {
58
+ cmd: {
59
+ type: "string",
60
+ 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."
61
+ },
62
+ timeout_ms: {
63
+ type: "number",
64
+ description: "Wall-clock cap for the whole approval-and-run cycle in milliseconds. Default 300000 (5 min). Approval waits count against this budget."
65
+ }
66
+ },
67
+ required: ["cmd"]
68
+ },
69
+ execute: async (args) => {
70
+ const a = args;
71
+ if (typeof a.cmd !== "string" || a.cmd.trim() === "") {
72
+ throw new Error("cmd must be a non-empty string");
73
+ }
74
+ const timeout = typeof a.timeout_ms === "number" && a.timeout_ms > 0 ? a.timeout_ms : DEFAULT_TIMEOUT_MS;
75
+ return await new Promise((resolveResult) => {
76
+ const child = spawn(BIN, ["-c", a.cmd], {
77
+ env: { ...process.env, APE_WAIT: "1" },
78
+ stdio: ["ignore", "pipe", "pipe"]
79
+ });
80
+ let stdout = "";
81
+ let stderr = "";
82
+ let timedOut = false;
83
+ let spawnError = null;
84
+ child.stdout.on("data", (chunk) => {
85
+ stdout += chunk.toString("utf8");
86
+ });
87
+ child.stderr.on("data", (chunk) => {
88
+ stderr += chunk.toString("utf8");
89
+ });
90
+ child.on("error", (err) => {
91
+ spawnError = err;
92
+ });
93
+ const timer = setTimeout(() => {
94
+ timedOut = true;
95
+ child.kill("SIGTERM");
96
+ setTimeout(() => {
97
+ try {
98
+ child.kill("SIGKILL");
99
+ } catch {
100
+ }
101
+ }, 5e3);
102
+ }, timeout);
103
+ child.on("close", (code) => {
104
+ clearTimeout(timer);
105
+ if (spawnError) {
106
+ resolveResult({
107
+ error: spawnError.message,
108
+ hint: `Could not exec '${BIN}'. The agent host needs @openape/apes installed globally so ape-shell is on PATH.`
109
+ });
110
+ return;
111
+ }
112
+ resolveResult({
113
+ stdout: capStdio(stdout),
114
+ stderr: capStdio(stderr),
115
+ exit_code: code ?? -1,
116
+ ...timedOut ? { timed_out: true } : {}
117
+ });
118
+ });
119
+ });
120
+ }
121
+ }
122
+ ];
123
+
40
124
  // src/lib/agent-tools/file.ts
41
125
  import { mkdirSync, readFileSync, writeFileSync } from "fs";
42
126
  import { homedir } from "os";
@@ -343,7 +427,8 @@ var ALL_TOOLS = [
343
427
  ...httpTools,
344
428
  ...fileTools,
345
429
  ...tasksTools,
346
- ...mailTools
430
+ ...mailTools,
431
+ ...bashTools
347
432
  ];
348
433
  var TOOLS = Object.fromEntries(
349
434
  ALL_TOOLS.map((t) => [t.name, t])
@@ -515,4 +600,4 @@ export {
515
600
  runLoop,
516
601
  RpcSessionMap
517
602
  };
518
- //# sourceMappingURL=chunk-TDSCDH5P.js.map
603
+ //# sourceMappingURL=chunk-FRCNYDTR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/duration.ts","../src/lib/agent-tools/bash.ts","../src/lib/agent-tools/file.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/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'\nimport type { ToolDefinition } from './index'\n\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000\nconst MAX_STDIO_BYTES = 64 * 1024\n\n// Spawning `ape-shell -c <cmd>` (instead of building the inner\n// `apes run --shell -- bash -c …` ourselves) keeps the tool aligned\n// with what the human owner types interactively. ape-shell rewrites\n// to the same `apes run --shell` flow, so the grant cycle and the\n// shapes-adapter detection are identical to a terminal invocation.\n// APE_WAIT=1 forces the blocking path — the tool must return a\n// result, not exit-75 with grant-pending instructions.\nconst BIN = 'ape-shell'\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 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 : DEFAULT_TIMEOUT_MS\n\n return await new Promise<unknown>((resolveResult) => {\n const child = spawn(BIN, ['-c', a.cmd as string], {\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 }, timeout)\n\n child.on('close', (code) => {\n clearTimeout(timer)\n if (spawnError) {\n resolveResult({\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 },\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\nexport const _internal = { jailPath }\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","// 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 { httpTools } from './http'\nimport { mailTools } from './mail'\nimport { tasksTools } from './tasks'\nimport { timeTools } from './time'\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]\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;AACF;AAEO,IAAM,UAAN,cAAsB,MAAM;AAAA,EACjC,YAAmB,WAAmB,GAAG;AACvC,UAAM,EAAE;AADS;AAEjB,SAAK,OAAO;AAAA,EACd;AACF;;;ACRO,SAAS,cAAc,OAAuB;AACnD,QAAM,QAAQ,MAAM,MAAM,oBAAoB;AAC9C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,6BAA6B,KAAK,yBAAyB;AAAA,EAC7E;AACA,QAAM,SAAS,OAAO,SAAS,MAAM,CAAC,GAAI,EAAE;AAC5C,UAAQ,MAAM,CAAC,GAAG;AAAA,IAChB,KAAK;AAAK,aAAO;AAAA,IACjB,KAAK;AAAK,aAAO,SAAS;AAAA,IAC1B,KAAK;AAAK,aAAO,SAAS;AAAA,IAC1B,KAAK;AAAK,aAAO,SAAS;AAAA,IAC1B;AAAS,YAAM,IAAI,MAAM,0BAA0B,MAAM,CAAC,CAAC,EAAE;AAAA,EAC/D;AACF;;;ACjBA,SAAS,aAAa;AAGtB,IAAM,qBAAqB,IAAI,KAAK;AACpC,IAAM,kBAAkB,KAAK;AAS7B,IAAM,MAAM;AAEZ,SAAS,SAAS,GAAmB;AACnC,QAAM,MAAM,OAAO,KAAK,GAAG,MAAM;AACjC,MAAI,IAAI,cAAc,gBAAiB,QAAO;AAC9C,SAAO,GAAG,IAAI,SAAS,GAAG,eAAe,EAAE,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eAAe,MAAM,WAAW,SAAS,YAAYA,OAAM,EAAE,CAAC;AAAA,MACzF;AAEA,eAAS,KAAK;AAAA,QACZ,MAAM;AAAA,QACN,cAAc,KAAK;AAAA,QACnB,MAAM,aAAa,SAAS;AAAA,QAC5B,SAAS,OAAOA,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":["MAX_BYTES","execFileSync","result"]}
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  parseDuration,
12
12
  runLoop,
13
13
  taskTools
14
- } from "./chunk-TDSCDH5P.js";
14
+ } from "./chunk-FRCNYDTR.js";
15
15
  import {
16
16
  loadEd25519PrivateKey,
17
17
  readPublicKeyComment
@@ -6428,7 +6428,7 @@ var mcpCommand = defineCommand48({
6428
6428
  if (transport !== "stdio" && transport !== "sse") {
6429
6429
  throw new Error('Transport must be "stdio" or "sse"');
6430
6430
  }
6431
- const { startMcpServer } = await import("./server-WKCSHOBY.js");
6431
+ const { startMcpServer } = await import("./server-CRHBOCNS.js");
6432
6432
  await startMcpServer(transport, port);
6433
6433
  }
6434
6434
  });
@@ -7066,7 +7066,7 @@ async function bestEffortGrantCount(idp) {
7066
7066
  }
7067
7067
  }
7068
7068
  async function runHealth(args) {
7069
- const version = true ? "1.20.0" : "0.0.0";
7069
+ const version = true ? "1.21.0" : "0.0.0";
7070
7070
  const auth = loadAuth();
7071
7071
  if (!auth) {
7072
7072
  throw new CliError("Not logged in. Run `apes login` first.", 1);
@@ -7339,10 +7339,10 @@ if (shellRewrite) {
7339
7339
  if (shellRewrite.action === "rewrite") {
7340
7340
  process.argv = shellRewrite.argv;
7341
7341
  } else if (shellRewrite.action === "version") {
7342
- console.log(`ape-shell ${"1.20.0"} (OpenApe DDISA shell wrapper)`);
7342
+ console.log(`ape-shell ${"1.21.0"} (OpenApe DDISA shell wrapper)`);
7343
7343
  process.exit(0);
7344
7344
  } else if (shellRewrite.action === "help") {
7345
- console.log(`ape-shell ${"1.20.0"} \u2014 OpenApe DDISA shell wrapper`);
7345
+ console.log(`ape-shell ${"1.21.0"} \u2014 OpenApe DDISA shell wrapper`);
7346
7346
  console.log("");
7347
7347
  console.log("Usage:");
7348
7348
  console.log(" ape-shell Start interactive grant-mediated REPL");
@@ -7400,7 +7400,7 @@ var configCommand = defineCommand60({
7400
7400
  var main = defineCommand60({
7401
7401
  meta: {
7402
7402
  name: "apes",
7403
- version: "1.20.0",
7403
+ version: "1.21.0",
7404
7404
  description: "Unified CLI for OpenApe"
7405
7405
  },
7406
7406
  subCommands: {
@@ -7457,7 +7457,7 @@ async function maybeRefreshAuth() {
7457
7457
  }
7458
7458
  }
7459
7459
  await maybeRefreshAuth();
7460
- await maybeWarnStaleVersion("1.20.0").catch(() => {
7460
+ await maybeWarnStaleVersion("1.21.0").catch(() => {
7461
7461
  });
7462
7462
  runMain(main).catch((err) => {
7463
7463
  if (err instanceof CliExit) {
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  parseDuration,
8
8
  runLoop,
9
9
  taskTools
10
- } from "./chunk-TDSCDH5P.js";
10
+ } from "./chunk-FRCNYDTR.js";
11
11
  import {
12
12
  appendAuditLog,
13
13
  buildExactCommandGrantRequest,
@@ -304,7 +304,7 @@ function registerAdapterTools(server) {
304
304
  async function startMcpServer(transport, port) {
305
305
  const server = new McpServer({
306
306
  name: "apes",
307
- version: true ? "1.20.0" : "0.1.0"
307
+ version: true ? "1.21.0" : "0.1.0"
308
308
  });
309
309
  registerStaticTools(server);
310
310
  registerAdapterTools(server);
@@ -332,4 +332,4 @@ async function startMcpServer(transport, port) {
332
332
  export {
333
333
  startMcpServer
334
334
  };
335
- //# sourceMappingURL=server-WKCSHOBY.js.map
335
+ //# sourceMappingURL=server-CRHBOCNS.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openape/apes",
3
- "version": "1.20.0",
3
+ "version": "1.21.0",
4
4
  "turbo": {
5
5
  "tags": [
6
6
  "publishable"
@@ -32,8 +32,8 @@
32
32
  "shell-quote": "^1.8.3",
33
33
  "zod": "^4.3.6",
34
34
  "@openape/core": "0.16.0",
35
- "@openape/proxy": "0.4.3",
36
- "@openape/grants": "0.11.5"
35
+ "@openape/grants": "0.11.5",
36
+ "@openape/proxy": "0.4.3"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@types/node": "^25.3.5",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/duration.ts","../src/lib/agent-tools/file.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/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 { 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\nexport const _internal = { jailPath }\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","// 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 { fileTools } from './file'\nimport { httpTools } from './http'\nimport { mailTools } from './mail'\nimport { tasksTools } from './tasks'\nimport { timeTools } from './time'\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]\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;AACF;AAEO,IAAM,UAAN,cAAsB,MAAM;AAAA,EACjC,YAAmB,WAAmB,GAAG;AACvC,UAAM,EAAE;AADS;AAEjB,SAAK,OAAO;AAAA,EACd;AACF;;;ACRO,SAAS,cAAc,OAAuB;AACnD,QAAM,QAAQ,MAAM,MAAM,oBAAoB;AAC9C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,6BAA6B,KAAK,yBAAyB;AAAA,EAC7E;AACA,QAAM,SAAS,OAAO,SAAS,MAAM,CAAC,GAAI,EAAE;AAC5C,UAAQ,MAAM,CAAC,GAAG;AAAA,IAChB,KAAK;AAAK,aAAO;AAAA,IACjB,KAAK;AAAK,aAAO,SAAS;AAAA,IAC1B,KAAK;AAAK,aAAO,SAAS;AAAA,IAC1B,KAAK;AAAK,aAAO,SAAS;AAAA,IAC1B;AAAS,YAAM,IAAI,MAAM,0BAA0B,MAAM,C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