@openape/apes 1.28.11 → 1.28.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-4KPKANZT.js → chunk-NYJSBFLG.js} +7 -5
- package/dist/chunk-NYJSBFLG.js.map +1 -0
- package/dist/{chunk-OOKB2IL2.js → chunk-ZEUSCNCH.js} +59 -9
- package/dist/chunk-ZEUSCNCH.js.map +1 -0
- package/dist/cli.js +624 -375
- package/dist/cli.js.map +1 -1
- package/dist/{http-6OKWT52Z.js → http-UPOTOYQV.js} +2 -2
- package/dist/index.d.ts +12 -0
- package/dist/index.js +2 -2
- package/dist/{orchestrator-CIDV7OGM.js → orchestrator-BDX3WK7Q.js} +2 -2
- package/dist/{server-WB77GNKJ.js → server-OAINN75J.js} +3 -3
- package/package.json +4 -4
- package/dist/chunk-4KPKANZT.js.map +0 -1
- package/dist/chunk-OOKB2IL2.js.map +0 -1
- /package/dist/{http-6OKWT52Z.js.map → http-UPOTOYQV.js.map} +0 -0
- /package/dist/{orchestrator-CIDV7OGM.js.map → orchestrator-BDX3WK7Q.js.map} +0 -0
- /package/dist/{server-WB77GNKJ.js.map → server-OAINN75J.js.map} +0 -0
|
@@ -43,11 +43,11 @@ async function getGrantsEndpoint(idpUrl) {
|
|
|
43
43
|
}
|
|
44
44
|
async function getAgentChallengeEndpoint(idpUrl) {
|
|
45
45
|
const disco = await discoverEndpoints(idpUrl);
|
|
46
|
-
return disco.ddisa_agent_challenge_endpoint || `${idpUrl}/api/
|
|
46
|
+
return disco.ddisa_auth_challenge_endpoint || disco.ddisa_agent_challenge_endpoint || `${idpUrl}/api/auth/challenge`;
|
|
47
47
|
}
|
|
48
48
|
async function getAgentAuthenticateEndpoint(idpUrl) {
|
|
49
49
|
const disco = await discoverEndpoints(idpUrl);
|
|
50
|
-
return disco.ddisa_agent_authenticate_endpoint || `${idpUrl}/api/
|
|
50
|
+
return disco.ddisa_auth_authenticate_endpoint || disco.ddisa_agent_authenticate_endpoint || `${idpUrl}/api/auth/authenticate`;
|
|
51
51
|
}
|
|
52
52
|
async function getDelegationsEndpoint(idpUrl) {
|
|
53
53
|
const disco = await discoverEndpoints(idpUrl);
|
|
@@ -73,7 +73,8 @@ async function refreshAgentToken() {
|
|
|
73
73
|
const challengeResp = await fetch(challengeUrl, {
|
|
74
74
|
method: "POST",
|
|
75
75
|
headers: { "Content-Type": "application/json" },
|
|
76
|
-
|
|
76
|
+
// Use canonical `id` field (the server's /api/auth/challenge handler expects `id`).
|
|
77
|
+
body: JSON.stringify({ id: auth.email })
|
|
77
78
|
});
|
|
78
79
|
if (!challengeResp.ok)
|
|
79
80
|
return null;
|
|
@@ -84,7 +85,8 @@ async function refreshAgentToken() {
|
|
|
84
85
|
const authResp = await fetch(authenticateUrl, {
|
|
85
86
|
method: "POST",
|
|
86
87
|
headers: { "Content-Type": "application/json" },
|
|
87
|
-
|
|
88
|
+
// Use canonical `id` field (the server's /api/auth/authenticate handler expects `id`).
|
|
89
|
+
body: JSON.stringify({ id: auth.email, challenge, signature })
|
|
88
90
|
});
|
|
89
91
|
if (!authResp.ok)
|
|
90
92
|
return null;
|
|
@@ -219,4 +221,4 @@ export {
|
|
|
219
221
|
ensureFreshToken,
|
|
220
222
|
apiFetch
|
|
221
223
|
};
|
|
222
|
-
//# sourceMappingURL=chunk-
|
|
224
|
+
//# sourceMappingURL=chunk-NYJSBFLG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/http.ts"],"sourcesContent":["import consola from 'consola'\nimport { getAuthToken, getIdpUrl, loadAuth, loadConfig, saveAuth } from './config'\n\nconst debug = process.argv.includes('--debug')\n\nexport class ApiError extends Error {\n constructor(public statusCode: number, message: string, public problemDetails?: Record<string, unknown>) {\n super(message)\n this.name = 'ApiError'\n }\n}\n\n// OIDC Discovery cache (one-time per CLI invocation)\nconst _discoveryCache: Record<string, Record<string, unknown>> = {}\n\nexport async function discoverEndpoints(idpUrl: string): Promise<Record<string, unknown>> {\n if (_discoveryCache[idpUrl]) {\n return _discoveryCache[idpUrl]\n }\n\n try {\n const response = await fetch(`${idpUrl}/.well-known/openid-configuration`)\n if (response.ok) {\n const data = await response.json() as Record<string, unknown>\n _discoveryCache[idpUrl] = data\n return data\n }\n }\n catch {}\n\n // Return empty if discovery fails (graceful degradation)\n _discoveryCache[idpUrl] = {}\n return {}\n}\n\nexport async function getGrantsEndpoint(idpUrl: string): Promise<string> {\n const disco = await discoverEndpoints(idpUrl)\n return (disco.openape_grants_endpoint as string) || `${idpUrl}/api/grants`\n}\n\nexport async function getAgentChallengeEndpoint(idpUrl: string): Promise<string> {\n const disco = await discoverEndpoints(idpUrl)\n // Read canonical ddisa_auth_challenge_endpoint (emitted by server since M3).\n // Fall back to legacy ddisa_agent_challenge_endpoint for backward-compat with older IdPs.\n return (disco.ddisa_auth_challenge_endpoint as string)\n || (disco.ddisa_agent_challenge_endpoint as string)\n || `${idpUrl}/api/auth/challenge`\n}\n\nexport async function getAgentAuthenticateEndpoint(idpUrl: string): Promise<string> {\n const disco = await discoverEndpoints(idpUrl)\n // Read canonical ddisa_auth_authenticate_endpoint (emitted by server since M3).\n // Fall back to legacy ddisa_agent_authenticate_endpoint for backward-compat with older IdPs.\n return (disco.ddisa_auth_authenticate_endpoint as string)\n || (disco.ddisa_agent_authenticate_endpoint as string)\n || `${idpUrl}/api/auth/authenticate`\n}\n\nexport async function getDelegationsEndpoint(idpUrl: string): Promise<string> {\n const disco = await discoverEndpoints(idpUrl)\n return (disco.openape_delegations_endpoint as string) || `${idpUrl}/api/delegations`\n}\n\n/**\n * Re-authenticate an agent using Ed25519 challenge-response.\n * Called automatically when the token is expired.\n */\nasync function refreshAgentToken(): Promise<string | null> {\n const auth = loadAuth()\n if (!auth)\n return null\n\n const config = loadConfig()\n const keyPath = config.agent?.key\n if (!keyPath)\n return null\n\n try {\n const { readFileSync } = await import('node:fs')\n const { sign } = await import('node:crypto')\n const { homedir } = await import('node:os')\n const { loadEd25519PrivateKey } = await import('./ssh-key.js')\n\n const resolved = keyPath.replace(/^~/, homedir())\n const keyContent = readFileSync(resolved, 'utf-8')\n const privateKey = loadEd25519PrivateKey(keyContent)\n\n const challengeUrl = await getAgentChallengeEndpoint(auth.idp)\n const challengeResp = await fetch(challengeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n // Use canonical `id` field (the server's /api/auth/challenge handler expects `id`).\n body: JSON.stringify({ id: auth.email }),\n })\n\n if (!challengeResp.ok)\n return null\n\n const { challenge } = await challengeResp.json() as { challenge: string }\n const { Buffer } = await import('node:buffer')\n const signature = sign(null, Buffer.from(challenge), privateKey).toString('base64')\n\n const authenticateUrl = await getAgentAuthenticateEndpoint(auth.idp)\n const authResp = await fetch(authenticateUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n // Use canonical `id` field (the server's /api/auth/authenticate handler expects `id`).\n body: JSON.stringify({ id: auth.email, challenge, signature }),\n })\n\n if (!authResp.ok)\n return null\n\n const { token, expires_in } = await authResp.json() as { token: string, expires_in: number }\n\n saveAuth({\n ...auth,\n access_token: token,\n expires_at: Math.floor(Date.now() / 1000) + (expires_in || 3600),\n })\n\n if (debug) {\n consola.debug('Token refreshed via Ed25519 challenge-response')\n }\n\n return token\n }\n catch {\n return null\n }\n}\n\n/**\n * Refresh an OAuth2 access token using a stored refresh_token. Used for\n * PKCE/browser login sessions where no Ed25519 agent key is configured.\n *\n * Serialized via a file lock so concurrent apes/ape-shell invocations don't\n * both consume the same rotating refresh token (which would revoke the\n * entire family server-side).\n */\nasync function refreshOAuthToken(): Promise<string | null> {\n const auth = loadAuth()\n if (!auth?.refresh_token)\n return null\n\n const { acquireAuthLock, releaseAuthLock } = await import('./auth-lock.js')\n const lock = await acquireAuthLock({ timeoutMs: 5000 })\n if (!lock) {\n // Another process is refreshing. It should have updated auth.json by now;\n // re-read and return whatever fresh token is there (may still be null).\n return getAuthToken()\n }\n\n try {\n // Re-read auth.json inside the lock — another holder may already have\n // refreshed while we were waiting, in which case we reuse the new token.\n const latest = loadAuth()\n if (latest?.expires_at && Date.now() / 1000 < latest.expires_at - 30)\n return latest.access_token\n\n const activeRefreshToken = latest?.refresh_token ?? auth.refresh_token\n if (!activeRefreshToken)\n return null\n\n const disco = await discoverEndpoints(auth.idp)\n const tokenEndpoint = (disco.token_endpoint as string) || `${auth.idp}/token`\n\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: activeRefreshToken,\n })\n\n const resp = await fetch(tokenEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n })\n\n if (!resp.ok) {\n // Family may have been revoked server-side — clear refresh_token to\n // prevent an infinite retry loop on every subsequent apes invocation.\n if (resp.status === 400 || resp.status === 401) {\n const base = latest ?? auth\n saveAuth({ ...base, refresh_token: undefined })\n }\n return null\n }\n\n const tokens = await resp.json() as {\n access_token: string\n refresh_token?: string\n expires_in?: number\n }\n\n const base = latest ?? auth\n saveAuth({\n ...base,\n access_token: tokens.access_token,\n refresh_token: tokens.refresh_token ?? base.refresh_token,\n expires_at: Math.floor(Date.now() / 1000) + (tokens.expires_in || 300),\n })\n\n if (debug)\n consola.debug('Token refreshed via OAuth refresh_token')\n\n return tokens.access_token\n }\n finally {\n await releaseAuthLock(lock)\n }\n}\n\n/**\n * Refresh the local IdP token if it has expired. Used by every code path\n * that needs an access token — `apiFetch` for IdP-bound HTTP calls, plus\n * any pure-introspection command (`apes whoami`, `apes config get …`)\n * that previously only read local auth state and surfaced a stale\n * \"expired\" without attempting renewal.\n *\n * Returns the fresh access token on success, or null when no refresh\n * path is available (no agent key AND no refresh_token, or both refresh\n * attempts failed). Callers decide what to do with null — `apiFetch`\n * throws \"Not authenticated\", `whoami` falls back to the on-disk state.\n */\nexport async function ensureFreshToken(): Promise<string | null> {\n const cached = getAuthToken()\n if (cached) return cached\n\n // Auto-refresh: priority (1) ed25519 agent key, (2) OAuth refresh_token.\n // Agent-key first because it is concurrency-safe — every challenge is\n // independent server-side, so parallel ape-shell spawns don't race.\n const agentToken = await refreshAgentToken()\n if (agentToken) return agentToken\n const oauthToken = await refreshOAuthToken()\n return oauthToken ?? null\n}\n\nexport async function apiFetch<T = unknown>(\n path: string,\n options: {\n method?: string\n body?: unknown\n idp?: string\n token?: string\n } = {},\n): Promise<T> {\n const token = options.token ?? await ensureFreshToken()\n\n if (!token) {\n throw new Error('Not authenticated (token expired). Run `apes login` first.')\n }\n\n let url: string\n if (path.startsWith('http')) {\n url = path\n }\n else {\n const idp = options.idp || getIdpUrl()\n if (!idp) {\n throw new Error('No IdP URL configured. Run `apes login` first or pass --idp.')\n }\n url = `${idp}${path}`\n }\n const method = options.method || 'GET'\n const headers: Record<string, string> = {\n 'Authorization': `Bearer ${token}`,\n 'Content-Type': 'application/json',\n }\n\n if (debug) {\n consola.debug(`${method} ${url}`)\n consola.debug(`Token: ${token.substring(0, 20)}...${token.substring(token.length - 10)}`)\n }\n\n const response = await fetch(url, {\n method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n })\n\n if (debug) {\n consola.debug(`Response: ${response.status} ${response.statusText}`)\n }\n\n if (!response.ok) {\n const contentType = response.headers.get('content-type') || ''\n\n // Parse RFC 7807 Problem Details\n if (contentType.includes('application/problem+json') || contentType.includes('application/json')) {\n try {\n const problem = await response.json() as Record<string, unknown>\n const message = (problem.detail as string) || (problem.title as string) || (problem.statusMessage as string) || (problem.message as string) || `${response.status} ${response.statusText}`\n throw new ApiError(response.status, message, problem)\n }\n catch (e) {\n if (e instanceof ApiError)\n throw e\n }\n }\n\n const text = await response.text()\n throw new ApiError(response.status, text || `${response.status} ${response.statusText}`)\n }\n\n return response.json() as Promise<T>\n}\n"],"mappings":";;;;;;;;;;AAAA,OAAO,aAAa;AAGpB,IAAM,QAAQ,QAAQ,KAAK,SAAS,SAAS;AAEtC,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YAAmB,YAAoB,SAAwB,gBAA0C;A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Ac,SAAS,QAAQ,IAAI,cAAc,KAAK;AAG5D,QAAI,YAAY,SAAS,0BAA0B,KAAK,YAAY,SAAS,kBAAkB,GAAG;AAChG,UAAI;AACF,cAAM,UAAU,MAAM,SAAS,KAAK;AACpC,cAAM,UAAW,QAAQ,UAAsB,QAAQ,SAAqB,QAAQ,iBAA6B,QAAQ,WAAsB,GAAG,SAAS,MAAM,IAAI,SAAS,UAAU;AACxL,cAAM,IAAI,SAAS,SAAS,QAAQ,SAAS,OAAO;AAAA,MACtD,SACO,GAAG;AACR,YAAI,aAAa;AACf,gBAAM;AAAA,MACV;AAAA,IACF;AAEA,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,UAAM,IAAI,SAAS,SAAS,QAAQ,QAAQ,GAAG,SAAS,MAAM,IAAI,SAAS,UAAU,EAAE;AAAA,EACzF;AAEA,SAAO,SAAS,KAAK;AACvB;","names":["base"]}
|
|
@@ -51,8 +51,10 @@ function capStdio(s) {
|
|
|
51
51
|
[truncated to ${MAX_STDIO_BYTES} bytes]`;
|
|
52
52
|
}
|
|
53
53
|
function runApeShell(cmd, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
54
|
+
const bypass = process.env.OPENAPE_BYPASS_APE_SHELL === "1";
|
|
55
|
+
const [execBin, execArgs] = bypass ? ["/bin/bash", ["-c", cmd]] : [BIN, ["-c", cmd]];
|
|
54
56
|
return new Promise((resolveResult) => {
|
|
55
|
-
const child = spawn(
|
|
57
|
+
const child = spawn(execBin, execArgs, {
|
|
56
58
|
env: { ...process.env, APE_WAIT: "1" },
|
|
57
59
|
stdio: ["ignore", "pipe", "pipe"]
|
|
58
60
|
});
|
|
@@ -87,7 +89,7 @@ function runApeShell(cmd, timeoutMs = DEFAULT_TIMEOUT_MS) {
|
|
|
87
89
|
stderr: "",
|
|
88
90
|
exit_code: -1,
|
|
89
91
|
error: spawnError.message,
|
|
90
|
-
hint: `Could not exec '${
|
|
92
|
+
hint: `Could not exec '${execBin}'. The agent host needs @openape/apes installed globally so ape-shell is on PATH (or set OPENAPE_BYPASS_APE_SHELL=1 to skip the gated shell entirely \u2014 meant for the OpenApe pod where the container IS the sandbox).`
|
|
91
93
|
});
|
|
92
94
|
return;
|
|
93
95
|
}
|
|
@@ -879,6 +881,52 @@ function previewJson(value, max = 500) {
|
|
|
879
881
|
}
|
|
880
882
|
return s.length > max ? `${s.slice(0, max)}\u2026` : s;
|
|
881
883
|
}
|
|
884
|
+
async function aggregateChatStream(res) {
|
|
885
|
+
if (!res.body) throw new Error("LiteLLM streaming response had no body");
|
|
886
|
+
const reader = res.body.getReader();
|
|
887
|
+
const decoder = new TextDecoder();
|
|
888
|
+
let buf = "";
|
|
889
|
+
let content = "";
|
|
890
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
891
|
+
let finishReason;
|
|
892
|
+
while (true) {
|
|
893
|
+
const { value, done } = await reader.read();
|
|
894
|
+
if (done) break;
|
|
895
|
+
buf += decoder.decode(value, { stream: true });
|
|
896
|
+
while (true) {
|
|
897
|
+
const nl = buf.indexOf("\n");
|
|
898
|
+
if (nl === -1) break;
|
|
899
|
+
const line = buf.slice(0, nl).trim();
|
|
900
|
+
buf = buf.slice(nl + 1);
|
|
901
|
+
if (!line.startsWith("data:")) continue;
|
|
902
|
+
const payload = line.slice(5).trim();
|
|
903
|
+
if (!payload || payload === "[DONE]") continue;
|
|
904
|
+
let chunk;
|
|
905
|
+
try {
|
|
906
|
+
chunk = JSON.parse(payload);
|
|
907
|
+
} catch {
|
|
908
|
+
continue;
|
|
909
|
+
}
|
|
910
|
+
const ch0 = chunk.choices?.[0];
|
|
911
|
+
const delta = ch0?.delta;
|
|
912
|
+
if (delta?.content) content += delta.content;
|
|
913
|
+
if (delta?.tool_calls) {
|
|
914
|
+
for (const tc of delta.tool_calls) {
|
|
915
|
+
const idx = tc.index ?? 0;
|
|
916
|
+
const existing = toolCalls.get(idx) ?? { id: "", type: "function", function: { name: "", arguments: "" } };
|
|
917
|
+
if (tc.id) existing.id = tc.id;
|
|
918
|
+
if (tc.function?.name) existing.function.name = tc.function.name;
|
|
919
|
+
if (tc.function?.arguments) existing.function.arguments += tc.function.arguments;
|
|
920
|
+
toolCalls.set(idx, existing);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
if (ch0?.finish_reason) finishReason = ch0.finish_reason;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
const message = { role: "assistant", content: content || null };
|
|
927
|
+
if (toolCalls.size > 0) message.tool_calls = Array.from(toolCalls.values());
|
|
928
|
+
return { choices: [{ message, finish_reason: finishReason }] };
|
|
929
|
+
}
|
|
882
930
|
async function runLoop(opts) {
|
|
883
931
|
const fetchFn = opts.fetchImpl ?? fetch;
|
|
884
932
|
const trace = [];
|
|
@@ -889,23 +937,25 @@ async function runLoop(opts) {
|
|
|
889
937
|
];
|
|
890
938
|
const tools = asOpenAiTools(opts.tools);
|
|
891
939
|
for (let step = 1; step <= opts.maxSteps; step++) {
|
|
940
|
+
const requestBody = {
|
|
941
|
+
model: opts.config.model,
|
|
942
|
+
messages,
|
|
943
|
+
...tools.length > 0 ? { tools, tool_choice: "auto" } : {},
|
|
944
|
+
...opts.streamAggregate ? { stream: true } : {}
|
|
945
|
+
};
|
|
892
946
|
const res = await fetchFn(`${opts.config.apiBase}/chat/completions`, {
|
|
893
947
|
method: "POST",
|
|
894
948
|
headers: {
|
|
895
949
|
"authorization": `Bearer ${opts.config.apiKey}`,
|
|
896
950
|
"content-type": "application/json"
|
|
897
951
|
},
|
|
898
|
-
body: JSON.stringify(
|
|
899
|
-
model: opts.config.model,
|
|
900
|
-
messages,
|
|
901
|
-
...tools.length > 0 ? { tools, tool_choice: "auto" } : {}
|
|
902
|
-
})
|
|
952
|
+
body: JSON.stringify(requestBody)
|
|
903
953
|
});
|
|
904
954
|
if (!res.ok) {
|
|
905
955
|
const text = await res.text().catch(() => "");
|
|
906
956
|
throw new Error(`LiteLLM ${res.status}: ${text.slice(0, 500)}`);
|
|
907
957
|
}
|
|
908
|
-
const data = await res.json();
|
|
958
|
+
const data = opts.streamAggregate ? await aggregateChatStream(res) : await res.json();
|
|
909
959
|
const choice = data.choices?.[0];
|
|
910
960
|
if (!choice) throw new Error("LiteLLM response had no choices");
|
|
911
961
|
const assistant = choice.message;
|
|
@@ -1014,4 +1064,4 @@ export {
|
|
|
1014
1064
|
runLoop,
|
|
1015
1065
|
RpcSessionMap
|
|
1016
1066
|
};
|
|
1017
|
-
//# sourceMappingURL=chunk-
|
|
1067
|
+
//# sourceMappingURL=chunk-ZEUSCNCH.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 // Container escape hatch: inside the OpenApe pod the container itself\n // IS the sandbox (kernel namespaces + read-only FS overlays) — there's\n // no DDISA layer to gate against, no upstream owner to approve grants,\n // and `ape-shell` would fail at the auth.json check. When\n // OPENAPE_BYPASS_APE_SHELL is set, exec the command via plain bash and\n // surface stdout/stderr/exit_code in the same shape.\n const bypass = process.env.OPENAPE_BYPASS_APE_SHELL === '1'\n const [execBin, execArgs] = bypass\n ? ['/bin/bash', ['-c', cmd]] as const\n : [BIN, ['-c', cmd]] as const\n return new Promise<ApeShellResult>((resolveResult) => {\n const child = spawn(execBin, execArgs, {\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 '${execBin}'. The agent host needs @openape/apes installed globally so ape-shell is on PATH (or set OPENAPE_BYPASS_APE_SHELL=1 to skip the gated shell entirely — meant for the OpenApe pod where the container IS the sandbox).`,\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 // First RESET the helper list (the empty value clears the inherited\n // osxkeychain helper — otherwise git still calls it on `store` and hangs\n // headless), then add ours that supplies $GH_TOKEN from the env.\n const ghAuth = /github\\.com/i.test(source)\n ? `git -C ${q(baseDir)} config credential.helper '' && git -C ${q(baseDir)} config --add 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 * Send `stream: true` to the LiteLLM proxy and aggregate the SSE\n * chunks locally into a single non-stream response. Workaround for\n * LiteLLM's chatgpt-OAuth provider whose non-stream `/v1/chat/\n * completions` returns an empty body (the chatgpt upstream only\n * emits content via the responses-API streaming path; the bridge\n * back to chat/completions fails to aggregate). Streaming + local\n * aggregation produces a correct response with every provider\n * LiteLLM ships, so this flag is safe to enable globally — it\n * defaults off only to keep existing JSON-fixture tests intact.\n */\n streamAggregate?: boolean\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\n// Stream aggregator — parses the SSE chunks LiteLLM emits when\n// `stream:true` is set and folds them into the same OpenAIChatResponse\n// shape the non-stream path returns. Handles two delta kinds:\n// - text content: simple concatenation\n// - tool_calls: keyed by `index`, the id arrives first, then the\n// function.name, then function.arguments piece by piece\n// Used by the chatgpt-OAuth pod path (see RunOptions.streamAggregate).\nasync function aggregateChatStream(res: Response): Promise<OpenAIChatResponse> {\n if (!res.body) throw new Error('LiteLLM streaming response had no body')\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buf = ''\n let content = ''\n const toolCalls = new Map<number, { id: string, type: 'function', function: { name: string, arguments: string } }>()\n let finishReason: string | undefined\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n buf += decoder.decode(value, { stream: true })\n while (true) {\n const nl = buf.indexOf('\\n')\n if (nl === -1) break\n const line = buf.slice(0, nl).trim()\n buf = buf.slice(nl + 1)\n if (!line.startsWith('data:')) continue\n const payload = line.slice(5).trim()\n if (!payload || payload === '[DONE]') continue\n let chunk: { choices?: Array<{ delta?: { content?: string, tool_calls?: Array<{ index?: number, id?: string, function?: { name?: string, arguments?: string } }> }, finish_reason?: string }> }\n try { chunk = JSON.parse(payload) }\n catch { continue }\n const ch0 = chunk.choices?.[0]\n const delta = ch0?.delta\n if (delta?.content) content += delta.content\n if (delta?.tool_calls) {\n for (const tc of delta.tool_calls) {\n const idx = tc.index ?? 0\n const existing = toolCalls.get(idx) ?? { id: '', type: 'function' as const, function: { name: '', arguments: '' } }\n if (tc.id) existing.id = tc.id\n if (tc.function?.name) existing.function.name = tc.function.name\n if (tc.function?.arguments) existing.function.arguments += tc.function.arguments\n toolCalls.set(idx, existing)\n }\n }\n if (ch0?.finish_reason) finishReason = ch0.finish_reason\n }\n }\n const message: ChatMessage = { role: 'assistant', content: content || null }\n if (toolCalls.size > 0) message.tool_calls = Array.from(toolCalls.values())\n return { choices: [{ message, finish_reason: finishReason }] }\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 requestBody = {\n model: opts.config.model,\n messages,\n ...(tools.length > 0 ? { tools, tool_choice: 'auto' } : {}),\n ...(opts.streamAggregate ? { stream: true } : {}),\n }\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(requestBody),\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 = opts.streamAggregate\n ? await aggregateChatStream(res)\n : 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,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;AAatB,IAAM,qBAAqB,IAAI,KAAK;AACpC,IAAM,kBAAkB,KAAK;AAC7B,IAAM,MAAM;AAWZ,SAAS,SAAS,GAAmB;AACnC,QAAM,MAAM,OAAO,KAAK,GAAG,MAAM;AACjC,MAAI,IAAI,cAAc,gBAAiB,QAAO;AAC9C,SAAO,GAAG,IAAI,SAAS,GAAG,eAAe,EAAE,SAAS,MAAM,CAAC;AAAA,gBAAmB,eAAe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Q;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"]}
|