totemlayer 0.1.59 → 0.1.66
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/README.md +34 -4
- package/bin/agent-memory.mjs +12 -1
- package/bin/agent-profile.mjs +16 -1
- package/bin/agent-runner.mjs +12 -3
- package/bin/automatic-runtime.mjs +11 -116
- package/bin/inference-broker.mjs +361 -0
- package/bin/isolated-agent-entry.mjs +35 -0
- package/bin/managed-mcp.mjs +68 -0
- package/bin/model-adapter.mjs +244 -103
- package/bin/native/darwin-lifetime +0 -0
- package/bin/native/darwin-lifetime.json +1 -0
- package/bin/network-runtime.mjs +19 -39
- package/bin/network.mjs +2 -2
- package/bin/process-isolation.mjs +258 -0
- package/bin/runtime-archive.mjs +131 -0
- package/bin/runtime-installation.mjs +63 -4
- package/bin/runtime-lock.mjs +118 -0
- package/bin/runtime-update.mjs +345 -0
- package/bin/sdk/inspector.js +1 -1
- package/bin/totem.mjs +11 -5
- package/bin/update-health.mjs +10 -0
- package/bin/update-trust.mjs +7 -0
- package/bin/worker-core/adapters.mjs +52 -14
- package/bin/worker-core/errors.mjs +8 -0
- package/package.json +3 -2
- package/scripts/build-native.mjs +60 -0
- package/scripts/prepare.mjs +1 -0
package/README.md
CHANGED
|
@@ -27,7 +27,7 @@ To configure execution later, rerun setup with `--provider` and the adapter's se
|
|
|
27
27
|
|
|
28
28
|
## Connect with automatic listener setup
|
|
29
29
|
|
|
30
|
-
Configure a local MCP server using command `npx` and arguments `--yes`, `--ignore-scripts`, `--package=https://totemlayer.com/downloads/totemlayer-0.1.
|
|
30
|
+
Configure a local MCP server using command `npx` and arguments `--yes`, `--ignore-scripts`, `--package=https://totemlayer.com/downloads/totemlayer-0.1.66.tgz`, `totem`, `connect`, `--provider`, and `codex` (or `claude` for Claude Code). The host runs the connection itself; the owner does not run a separate listener command. Node.js 22.14 or newer and the selected signed-in client must be available.
|
|
31
31
|
|
|
32
32
|
During browser sign-in, `totem_get_connection_status` reports progress. Normal tools appear after the approved identity is pinned privately. Codex verifies identity, startup and the saved chat callback before receiving work; reconnect preserves bindings and pauses. Missing capabilities leave work queued. A remote HTTP connector cannot install local software.
|
|
33
33
|
|
|
@@ -45,7 +45,7 @@ For a hosted connection, add these settings to your client's MCP configuration:
|
|
|
45
45
|
For a local stdio connection, install the CLI with Node.js 22.14 or newer:
|
|
46
46
|
|
|
47
47
|
```sh
|
|
48
|
-
npm install --global --ignore-scripts https://totemlayer.com/downloads/totemlayer-0.1.
|
|
48
|
+
npm install --global --ignore-scripts https://totemlayer.com/downloads/totemlayer-0.1.66.tgz
|
|
49
49
|
```
|
|
50
50
|
|
|
51
51
|
Save your agent's connection key in a private file. Protect it with mode 0600 on macOS/Linux or your user's filesystem ACL on Windows. Configure these fields in your client's MCP settings:
|
|
@@ -64,7 +64,7 @@ Reload the client if needed, discover the available tools, and call `totem_get_i
|
|
|
64
64
|
Run the guided installer on the host where your agent will execute work:
|
|
65
65
|
|
|
66
66
|
```sh
|
|
67
|
-
npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.
|
|
67
|
+
npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.66.tgz totem install
|
|
68
68
|
```
|
|
69
69
|
|
|
70
70
|
The installer opens Totem sign-in and saves the approved connection privately. It checks your configured agent runtime, configures supported clients, and starts the listener when an authorized executor is available. The supervised listener is enabled by default for this setup and starts when you sign in to the computer on hosts with a supported user service manager. It recovers after a process exit and retries temporary connection failures. An explicit stop stays paused across restarts.
|
|
@@ -74,7 +74,7 @@ For manual setup, use `totem mcp install` with a supported client and the privat
|
|
|
74
74
|
For a host without a browser:
|
|
75
75
|
|
|
76
76
|
```sh
|
|
77
|
-
npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.
|
|
77
|
+
npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.66.tgz totem login --device-login --no-browser
|
|
78
78
|
```
|
|
79
79
|
|
|
80
80
|
Open the printed link on your own device and compare the connection code. Preserve existing MCP entries; inspect conflicts before replacing them. If an executor is unavailable, the saved connection remains available while you complete runtime setup.
|
|
@@ -146,3 +146,33 @@ An AI app such as Instinct or Codex may reject a setup, start, or listener tool
|
|
|
146
146
|
Ask the owner to inspect the host app's approval or review controls for that operation. If the host offers no approval path or explanation, direct the owner to that host's support. Do not promise an approve-once button, infer permission from a "Full access" label, change agents or credentials, disable safeguards, or use another execution path to bypass the denial.
|
|
147
147
|
|
|
148
148
|
A command denied before execution cannot write Totem status. Saved configuration and verified identity do not prove that the worker started. Keep startup and message delivery marked unverified. When Totem itself observes an approval denial, it saves the cause and recovery and pauses automatic startup attempts. After the owner resolves the host decision, explicitly run totem start --profile <profile> once to resume, inspect totem status --profile <profile>, and verify an authorized incoming message and reply. Do not repeat setup or reauthorize credentials solely because of a host denial.
|
|
149
|
+
|
|
150
|
+
### Native turn cleanup
|
|
151
|
+
|
|
152
|
+
On macOS 13 or later, the CLI's bundled native supervisor starts a temporary
|
|
153
|
+
launchd job for each turn. Its descendants remain in one kernel resource
|
|
154
|
+
coalition even if they change sessions or process groups. Completion, cancellation,
|
|
155
|
+
timeouts, output limits, and loss of the calling process trigger cleanup; Totem
|
|
156
|
+
waits for the kernel to reap the coalition before settling the turn. Ordinary
|
|
157
|
+
subprocesses remain available within the same filesystem and network sandbox.
|
|
158
|
+
No VM or permanently installed launch service is needed. macOS must permit the
|
|
159
|
+
temporary job to start. A missing supervisor stops execution; a failure to confirm
|
|
160
|
+
cleanup does not become a successful result. Force-killing the trusted supervisor
|
|
161
|
+
itself is outside this guarantee.
|
|
162
|
+
When approved code is in a macOS protected folder such as Documents, the parent
|
|
163
|
+
copies only its explicit code files and approved executable package into the
|
|
164
|
+
temporary turn folder. Relative code layout is preserved and command arguments
|
|
165
|
+
are updated; unrelated owner files remain unavailable. Code that hardcodes its
|
|
166
|
+
original protected location must use its staged path instead.
|
|
167
|
+
|
|
168
|
+
Build the universal supervisor on macOS with `node packages/cli/scripts/build-native.mjs`. The CLI package includes the binary; installation requires no compiler.
|
|
169
|
+
|
|
170
|
+
## Automatic MCP and receiver updates
|
|
171
|
+
|
|
172
|
+
Install version 0.1.66 or newer once, or update the local plugin to that version. After that, the existing receiver checks for releases every 15 minutes while its host is running. Local MCP connections also check in the background. Downloads must have a valid Totem release signature and matching SHA-256 hash; dependencies are bundled and no package installation scripts run during an automatic update.
|
|
173
|
+
|
|
174
|
+
An update changes only the managed code directory. Existing identities, credentials, permissions, message cursors, journals, and receiver pauses remain in place. Receiver workers finish active work before upgrading. An open MCP session keeps its loaded tools until the host opens its next connection. Hosted MCP tools continue to update on the server.
|
|
175
|
+
|
|
176
|
+
`totem update status` shows the installed version and last check. `totem update check` checks now. `totem update pause` disables automatic downloads; `totem update resume` enables them. For a plugin connection, add its `--provider codex` or `--provider claude` selection. `TOTEM_AUTO_UPDATE=0` also disables checks. Pausing updates does not pause message receiving.
|
|
177
|
+
|
|
178
|
+
Unverified downloads and failed health checks leave working code installed. A receiver that repeatedly crashes immediately after an update falls back to its retained previous version and quarantines the failed version. An offline or sleeping computer checks after it resumes; updates do not wake a closed laptop or add a wake mechanism to an external AI host.
|
package/bin/agent-memory.mjs
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
/** Explicit owner restrictions apply to tools, consolidation, and server checkpoints. */
|
|
2
|
+
export function allowsMemoryWrites(text) {
|
|
3
|
+
const value = String(text ?? "")
|
|
4
|
+
.normalize("NFKC")
|
|
5
|
+
.replace(/\p{Cf}/gu, "")
|
|
6
|
+
.replace(/\s+/gu, " ");
|
|
7
|
+
return !/\bread[\s-]*only\b|\b(?:do\s+not|don['’]t|never|no)\b[^.!?;\n]{0,100}\b(?:memory|memories|remember|save|store)\b|\b(?:keep|leave|preserve)\b[^.!?;\n]{0,40}\bmemor(?:y|ies)\b[^.!?;\n]{0,30}\bunchanged\b/i.test(
|
|
8
|
+
value,
|
|
9
|
+
);
|
|
10
|
+
}
|
|
11
|
+
|
|
1
12
|
/** Fetch before each model turn. Missing support on an older host is explicit and compatible. */
|
|
2
13
|
export async function agentMemoryPrompt(
|
|
3
14
|
client,
|
|
@@ -44,7 +55,7 @@ export async function learnAgentMemory({
|
|
|
44
55
|
signal,
|
|
45
56
|
emit = () => {},
|
|
46
57
|
}) {
|
|
47
|
-
if (!client.memory?.get || !client.memory?.update) return;
|
|
58
|
+
if (!allowsMemoryWrites(turn.user) || !client.memory?.get || !client.memory?.update) return;
|
|
48
59
|
const stateKey = `memory:${key}`;
|
|
49
60
|
let state = await journal.read(stateKey);
|
|
50
61
|
if (state?.done) return;
|
package/bin/agent-profile.mjs
CHANGED
|
@@ -186,6 +186,10 @@ async function normalizedSettings(input, directory) {
|
|
|
186
186
|
"commandArgs",
|
|
187
187
|
"agentUrl",
|
|
188
188
|
"agentTokenEnv",
|
|
189
|
+
"codePaths",
|
|
190
|
+
"inferenceOrigin",
|
|
191
|
+
"inferenceProtocol",
|
|
192
|
+
"inferenceTokenEnv",
|
|
189
193
|
"ollamaUrl",
|
|
190
194
|
"nimUrl",
|
|
191
195
|
"codexThreadId",
|
|
@@ -299,7 +303,18 @@ async function normalizedSettings(input, directory) {
|
|
|
299
303
|
repositoryRoots,
|
|
300
304
|
stateDirectory,
|
|
301
305
|
...Object.fromEntries(
|
|
302
|
-
[
|
|
306
|
+
[
|
|
307
|
+
"command",
|
|
308
|
+
"commandArgs",
|
|
309
|
+
"agentUrl",
|
|
310
|
+
"agentTokenEnv",
|
|
311
|
+
"codePaths",
|
|
312
|
+
"inferenceOrigin",
|
|
313
|
+
"inferenceProtocol",
|
|
314
|
+
"inferenceTokenEnv",
|
|
315
|
+
"ollamaUrl",
|
|
316
|
+
"nimUrl",
|
|
317
|
+
]
|
|
303
318
|
.filter((key) => input[key] !== undefined)
|
|
304
319
|
.map((key) => [key, input[key]]),
|
|
305
320
|
),
|
package/bin/agent-runner.mjs
CHANGED
|
@@ -437,7 +437,16 @@ export async function runAgentSession(profile, options = {}) {
|
|
|
437
437
|
})),
|
|
438
438
|
provider: profile.client ?? profile.provider,
|
|
439
439
|
adapterSettings: Object.fromEntries(
|
|
440
|
-
[
|
|
440
|
+
[
|
|
441
|
+
"command",
|
|
442
|
+
"commandArgs",
|
|
443
|
+
"agentUrl",
|
|
444
|
+
"agentTokenEnv",
|
|
445
|
+
"codePaths",
|
|
446
|
+
"inferenceOrigin",
|
|
447
|
+
"inferenceProtocol",
|
|
448
|
+
"inferenceTokenEnv",
|
|
449
|
+
]
|
|
441
450
|
.filter((key) => profile[key] !== undefined)
|
|
442
451
|
.map((key) => [key, profile[key]]),
|
|
443
452
|
),
|
|
@@ -593,8 +602,8 @@ export async function agentStartMain(args, options = {}) {
|
|
|
593
602
|
.map((name) => [name, environment[name]]),
|
|
594
603
|
),
|
|
595
604
|
});
|
|
596
|
-
|
|
597
|
-
env[
|
|
605
|
+
for (const name of [profile.agentTokenEnv, profile.inferenceTokenEnv])
|
|
606
|
+
if (name && environment[name]) env[name] = environment[name];
|
|
598
607
|
delete env.TOTEM_NETWORK_API_KEY_FILE;
|
|
599
608
|
delete env.TOTEM_BASE_URL;
|
|
600
609
|
if (["local", "hosted"].includes(environment.TOTEM_RUNTIME_HOST_KIND))
|
|
@@ -1,18 +1,16 @@
|
|
|
1
|
+
import { checkRuntimeUpdate } from "./runtime-update.mjs";
|
|
2
|
+
import { acquireSupervisorLock } from "./runtime-lock.mjs";
|
|
3
|
+
export { acquireSupervisorLock, processIdentity, readSupervisorOwner } from "./runtime-lock.mjs";
|
|
1
4
|
import { startupDiagnostic } from "./startup-diagnostics.mjs";
|
|
2
5
|
import { DEFAULT_LISTENER_POLL_MS } from "./sdk/listener.js";
|
|
3
|
-
import { opendir, rm, readFile
|
|
6
|
+
import { opendir, rm, readFile } from "node:fs/promises";
|
|
4
7
|
import { join } from "node:path";
|
|
5
|
-
import { randomUUID } from "node:crypto";
|
|
6
|
-
import { execFile } from "node:child_process";
|
|
7
|
-
import { promisify } from "node:util";
|
|
8
|
-
import { powershellInvocation } from "./platform-client.mjs";
|
|
9
8
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
10
9
|
import { fileURLToPath } from "node:url";
|
|
11
10
|
import { Totem } from "./sdk/index.js";
|
|
12
11
|
import { readAgentCredential, readAgentProfile } from "./agent-profile.mjs";
|
|
13
12
|
import { agentStartMain, readAgentRuntimeStatus, requestStop } from "./agent-runner.mjs";
|
|
14
13
|
import {
|
|
15
|
-
privateDirectory,
|
|
16
14
|
privateRead,
|
|
17
15
|
privateWrite,
|
|
18
16
|
runtimeRoot,
|
|
@@ -194,116 +192,6 @@ export async function superviseOnce(env = process.env, options = {}) {
|
|
|
194
192
|
}
|
|
195
193
|
return results;
|
|
196
194
|
}
|
|
197
|
-
const execute = promisify(execFile);
|
|
198
|
-
export async function processIdentity(pid) {
|
|
199
|
-
if (!Number.isSafeInteger(pid) || pid <= 1) return null;
|
|
200
|
-
try {
|
|
201
|
-
process.kill(pid, 0);
|
|
202
|
-
} catch (error) {
|
|
203
|
-
if (error.code === "ESRCH") return null;
|
|
204
|
-
throw error;
|
|
205
|
-
}
|
|
206
|
-
// PID reuse across reboot must not make an abandoned lock permanent. A failed
|
|
207
|
-
// process inspection is uncertainty, never evidence that another owner died.
|
|
208
|
-
const invocation =
|
|
209
|
-
process.platform === "win32"
|
|
210
|
-
? powershellInvocation(
|
|
211
|
-
`$p=Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}';if(!$p){exit 1};$p|Select-Object ProcessId,CreationDate,CommandLine|ConvertTo-Json -Compress`,
|
|
212
|
-
process.env,
|
|
213
|
-
)
|
|
214
|
-
: { command: "ps", args: ["-p", String(pid), "-o", "lstart=", "-o", "args="] };
|
|
215
|
-
const result = await execute(invocation.command, invocation.args, {
|
|
216
|
-
encoding: "utf8",
|
|
217
|
-
timeout: 3000,
|
|
218
|
-
maxBuffer: 8192,
|
|
219
|
-
});
|
|
220
|
-
if (!result.stdout.trim()) throw new Error("Cannot verify the supervisor process identity.");
|
|
221
|
-
return result.stdout.trim();
|
|
222
|
-
}
|
|
223
|
-
export async function readSupervisorOwner(lock) {
|
|
224
|
-
const info = await lstat(lock);
|
|
225
|
-
if (
|
|
226
|
-
!info.isDirectory() ||
|
|
227
|
-
info.isSymbolicLink() ||
|
|
228
|
-
(process.getuid && info.uid !== process.getuid()) ||
|
|
229
|
-
(process.platform !== "win32" && (info.mode & 0o777) !== 0o700)
|
|
230
|
-
)
|
|
231
|
-
throw new Error("Unsafe supervisor lock.");
|
|
232
|
-
const names = await readdir(lock);
|
|
233
|
-
if (!names.length) return null;
|
|
234
|
-
if (names.length !== 1 || !/^(?:owner|owner-[a-f0-9-]{36})\.json$/.test(names[0]))
|
|
235
|
-
throw new Error("The supervisor lock contains unrecognized state.");
|
|
236
|
-
const owner = await privateRead(join(lock, names[0]));
|
|
237
|
-
if (
|
|
238
|
-
!Number.isSafeInteger(owner?.pid) ||
|
|
239
|
-
owner.pid <= 1 ||
|
|
240
|
-
(names[0] !== "owner.json" &&
|
|
241
|
-
(names[0] !== `owner-${owner.token}.json` ||
|
|
242
|
-
typeof owner.identity !== "string" ||
|
|
243
|
-
!owner.identity))
|
|
244
|
-
)
|
|
245
|
-
throw new Error("Invalid supervisor owner.");
|
|
246
|
-
return { file: names[0], owner };
|
|
247
|
-
}
|
|
248
|
-
export async function acquireSupervisorLock(directory, options = {}) {
|
|
249
|
-
const lock = join(directory, "supervisor.lock");
|
|
250
|
-
const stage = join(directory, `supervisor-start-${randomUUID()}`);
|
|
251
|
-
const token = randomUUID();
|
|
252
|
-
const ownerFile = `owner-${token}.json`;
|
|
253
|
-
const identity = options.processIdentity ?? processIdentity;
|
|
254
|
-
await privateDirectory(directory);
|
|
255
|
-
const owner = { pid: process.pid, token, identity: await identity(process.pid) };
|
|
256
|
-
if (!owner.identity) throw new Error("Cannot verify this supervisor process.");
|
|
257
|
-
await privateDirectory(stage);
|
|
258
|
-
await privateWrite(join(stage, ownerFile), owner);
|
|
259
|
-
const removeObserved = async (file) => {
|
|
260
|
-
if (file)
|
|
261
|
-
await unlink(join(lock, file)).catch((error) => {
|
|
262
|
-
if (error.code !== "ENOENT") throw error;
|
|
263
|
-
});
|
|
264
|
-
// Never recursively delete or rename the shared lock path. A replacement
|
|
265
|
-
// contains its own unique owner file and makes rmdir fail with ENOTEMPTY.
|
|
266
|
-
await rmdir(lock).catch((error) => {
|
|
267
|
-
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code)) throw error;
|
|
268
|
-
});
|
|
269
|
-
};
|
|
270
|
-
try {
|
|
271
|
-
for (let attempt = 0; attempt < 3; attempt++) {
|
|
272
|
-
const snapshot = await lstat(lock).catch((error) => {
|
|
273
|
-
if (error.code !== "ENOENT") throw error;
|
|
274
|
-
return null;
|
|
275
|
-
});
|
|
276
|
-
if (snapshot) {
|
|
277
|
-
const current = await readSupervisorOwner(lock).catch((error) => {
|
|
278
|
-
if (error.code !== "ENOENT") throw error;
|
|
279
|
-
return undefined;
|
|
280
|
-
});
|
|
281
|
-
if (current === undefined) continue;
|
|
282
|
-
if (!current) {
|
|
283
|
-
if (Date.now() - snapshot.mtimeMs < (options.emptyLockGraceMs ?? 30000))
|
|
284
|
-
throw new Error("Another supervisor is starting. Wait before retrying.");
|
|
285
|
-
} else {
|
|
286
|
-
const actual = await identity(current.owner.pid);
|
|
287
|
-
if (actual && (!current.owner.identity || current.owner.identity === actual))
|
|
288
|
-
throw Object.assign(new Error("The Totem supervisor is already running."), {
|
|
289
|
-
code: "SUPERVISOR_ALREADY_RUNNING",
|
|
290
|
-
});
|
|
291
|
-
}
|
|
292
|
-
await removeObserved(current?.file);
|
|
293
|
-
}
|
|
294
|
-
try {
|
|
295
|
-
// Publish owner and lock together. New installations never expose an empty lock.
|
|
296
|
-
await rename(stage, lock);
|
|
297
|
-
return () => removeObserved(ownerFile);
|
|
298
|
-
} catch (error) {
|
|
299
|
-
if (!["EEXIST", "ENOTEMPTY", "ENOENT"].includes(error.code)) throw error;
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
throw new Error("Another supervisor is starting. Wait before retrying.");
|
|
303
|
-
} finally {
|
|
304
|
-
await rm(stage, { recursive: true, force: true });
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
195
|
export async function automaticRuntimeMain(env = process.env, options = {}) {
|
|
308
196
|
const directory = join(runtimeRoot(env), "runtime");
|
|
309
197
|
const releaseLock = await acquireSupervisorLock(directory, options);
|
|
@@ -336,6 +224,13 @@ export async function automaticRuntimeMain(env = process.env, options = {}) {
|
|
|
336
224
|
updatedAt: new Date().toISOString(),
|
|
337
225
|
});
|
|
338
226
|
await superviseOnce(environment, options);
|
|
227
|
+
await (options.checkUpdate ?? checkRuntimeUpdate)(environment).catch(() => {});
|
|
228
|
+
const installed = await privateRead(join(directory, "current.json")).catch(() => ({}));
|
|
229
|
+
if (installed.version && installed.version !== (options.packageVersion ?? PACKAGE_VERSION)) {
|
|
230
|
+
// The launcher reloads the supervisor; existing workers finish their active work first.
|
|
231
|
+
process.exitCode = 75;
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
339
234
|
await sleep(options.intervalMs ?? DEFAULT_LISTENER_POLL_MS, undefined, {
|
|
340
235
|
signal: options.signal
|
|
341
236
|
? AbortSignal.any([controller.signal, options.signal])
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { readPrivateRuntimeJson } from "./mission-agent-session.mjs";
|
|
8
|
+
|
|
9
|
+
export function isolationError(code, message) {
|
|
10
|
+
return Object.assign(new Error(message), { status: 422, code });
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function privateAuth(path) {
|
|
14
|
+
try {
|
|
15
|
+
return await readPrivateRuntimeJson(path, 32768);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error.code === "ENOENT") return null;
|
|
18
|
+
throw isolationError(
|
|
19
|
+
"PROVIDER_AUTH_REQUIRED",
|
|
20
|
+
"The provider's private authentication needs attention.",
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Provider secrets stay in this parent process; never copy them into an agent home. */
|
|
26
|
+
export async function inferenceAuthority(provider, environment = process.env, options = {}) {
|
|
27
|
+
if (provider === "codex") {
|
|
28
|
+
if (environment.OPENAI_API_KEY)
|
|
29
|
+
return {
|
|
30
|
+
protocol: "responses",
|
|
31
|
+
origin: "https://api.openai.com",
|
|
32
|
+
prefix: "/v1",
|
|
33
|
+
headers: { authorization: `Bearer ${environment.OPENAI_API_KEY}` },
|
|
34
|
+
};
|
|
35
|
+
const auth = await privateAuth(
|
|
36
|
+
join(environment.CODEX_HOME ?? join(environment.HOME ?? homedir(), ".codex"), "auth.json"),
|
|
37
|
+
);
|
|
38
|
+
if (auth?.OPENAI_API_KEY)
|
|
39
|
+
return {
|
|
40
|
+
protocol: "responses",
|
|
41
|
+
origin: "https://api.openai.com",
|
|
42
|
+
prefix: "/v1",
|
|
43
|
+
headers: { authorization: `Bearer ${auth.OPENAI_API_KEY}` },
|
|
44
|
+
};
|
|
45
|
+
if (typeof auth?.tokens?.access_token === "string" && auth.tokens.access_token)
|
|
46
|
+
return {
|
|
47
|
+
protocol: "responses",
|
|
48
|
+
origin: "https://chatgpt.com",
|
|
49
|
+
prefix: "/backend-api/codex",
|
|
50
|
+
headers: {
|
|
51
|
+
authorization: `Bearer ${auth.tokens.access_token}`,
|
|
52
|
+
...(typeof auth.tokens.account_id === "string"
|
|
53
|
+
? { "chatgpt-account-id": auth.tokens.account_id }
|
|
54
|
+
: {}),
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
if (provider === "claude") {
|
|
59
|
+
if (environment.ANTHROPIC_API_KEY)
|
|
60
|
+
return {
|
|
61
|
+
protocol: "anthropic",
|
|
62
|
+
origin: "https://api.anthropic.com",
|
|
63
|
+
prefix: "/v1",
|
|
64
|
+
headers: { "x-api-key": environment.ANTHROPIC_API_KEY, "anthropic-version": "2023-06-01" },
|
|
65
|
+
};
|
|
66
|
+
let token = environment.CLAUDE_CODE_OAUTH_TOKEN;
|
|
67
|
+
if (!token) {
|
|
68
|
+
const auth = await privateAuth(
|
|
69
|
+
join(
|
|
70
|
+
environment.CLAUDE_CONFIG_DIR ?? join(environment.HOME ?? homedir(), ".claude"),
|
|
71
|
+
".credentials.json",
|
|
72
|
+
),
|
|
73
|
+
);
|
|
74
|
+
token = auth?.claudeAiOauth?.accessToken;
|
|
75
|
+
}
|
|
76
|
+
if (!token && (options.platform ?? process.platform) === "darwin") {
|
|
77
|
+
try {
|
|
78
|
+
// Keychain output stays in the trusted parent. No refresh credential is
|
|
79
|
+
// copied into the child, its files, or inference request bodies.
|
|
80
|
+
const readKeychain =
|
|
81
|
+
options.readKeychain ??
|
|
82
|
+
(async () => {
|
|
83
|
+
const result = await promisify(execFile)(
|
|
84
|
+
"/usr/bin/security",
|
|
85
|
+
["find-generic-password", "-s", "Claude Code-credentials", "-w"],
|
|
86
|
+
{
|
|
87
|
+
timeout: 10000,
|
|
88
|
+
maxBuffer: 32768,
|
|
89
|
+
env: { PATH: "/usr/bin:/bin" },
|
|
90
|
+
},
|
|
91
|
+
);
|
|
92
|
+
return result.stdout;
|
|
93
|
+
});
|
|
94
|
+
token = JSON.parse(await readKeychain())?.claudeAiOauth?.accessToken;
|
|
95
|
+
} catch {
|
|
96
|
+
/* Missing, locked, or unavailable credentials need owner attention. */
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (typeof token === "string" && token)
|
|
100
|
+
return {
|
|
101
|
+
protocol: "anthropic",
|
|
102
|
+
origin: "https://api.anthropic.com",
|
|
103
|
+
prefix: "/v1",
|
|
104
|
+
headers: {
|
|
105
|
+
authorization: `Bearer ${token}`,
|
|
106
|
+
"anthropic-version": "2023-06-01",
|
|
107
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
throw isolationError(
|
|
112
|
+
"PROVIDER_AUTH_REQUIRED",
|
|
113
|
+
"Configure the selected provider's API key or supported private login in the parent runtime. Provider credentials are never passed to the isolated agent.",
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function plainText(value, type) {
|
|
118
|
+
if (typeof value === "string") return value;
|
|
119
|
+
if (!Array.isArray(value))
|
|
120
|
+
throw isolationError("INFERENCE_REQUEST_DENIED", "Only text inference is allowed.");
|
|
121
|
+
return value.map((item) => {
|
|
122
|
+
if (
|
|
123
|
+
!item ||
|
|
124
|
+
!["text", "input_text", "output_text"].includes(item.type) ||
|
|
125
|
+
typeof item.text !== "string"
|
|
126
|
+
)
|
|
127
|
+
throw isolationError("INFERENCE_REQUEST_DENIED", "Only text inference is allowed.");
|
|
128
|
+
return { type: type ?? item.type, text: item.text };
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Reconstruct the data-plane request: no server tools, uploads, URLs, or account history. */
|
|
133
|
+
export function inferenceRequest(protocol, input, selectedModel) {
|
|
134
|
+
if (
|
|
135
|
+
!input ||
|
|
136
|
+
typeof input !== "object" ||
|
|
137
|
+
Array.isArray(input) ||
|
|
138
|
+
input.previous_response_id ||
|
|
139
|
+
input.conversation ||
|
|
140
|
+
input.prompt ||
|
|
141
|
+
input.background
|
|
142
|
+
)
|
|
143
|
+
throw isolationError(
|
|
144
|
+
"INFERENCE_REQUEST_DENIED",
|
|
145
|
+
"Persistent provider state is unavailable in this session.",
|
|
146
|
+
);
|
|
147
|
+
if (
|
|
148
|
+
typeof input.model !== "string" ||
|
|
149
|
+
!input.model ||
|
|
150
|
+
(selectedModel && selectedModel !== "default" && input.model !== selectedModel)
|
|
151
|
+
)
|
|
152
|
+
throw isolationError(
|
|
153
|
+
"INFERENCE_REQUEST_DENIED",
|
|
154
|
+
"The requested model is outside this session.",
|
|
155
|
+
);
|
|
156
|
+
const body = { model: input.model, stream: input.stream === true };
|
|
157
|
+
for (const key of [
|
|
158
|
+
"temperature",
|
|
159
|
+
"top_p",
|
|
160
|
+
"max_tokens",
|
|
161
|
+
"max_output_tokens",
|
|
162
|
+
"reasoning",
|
|
163
|
+
"text",
|
|
164
|
+
"output_config",
|
|
165
|
+
"thinking",
|
|
166
|
+
])
|
|
167
|
+
if (input[key] !== undefined) body[key] = input[key];
|
|
168
|
+
if (protocol === "responses") {
|
|
169
|
+
body.store = false;
|
|
170
|
+
body.tools = [];
|
|
171
|
+
body.tool_choice = "none";
|
|
172
|
+
if (input.instructions !== undefined) {
|
|
173
|
+
if (typeof input.instructions !== "string")
|
|
174
|
+
throw isolationError("INFERENCE_REQUEST_DENIED", "Text instructions are required.");
|
|
175
|
+
body.instructions = input.instructions;
|
|
176
|
+
}
|
|
177
|
+
if (typeof input.input === "string") body.input = input.input;
|
|
178
|
+
// New Codex clients place tool declarations in input as well as tools.
|
|
179
|
+
// Discard the catalog; calls, results and provider handles still fail below.
|
|
180
|
+
else if (Array.isArray(input.input))
|
|
181
|
+
body.input = input.input
|
|
182
|
+
.filter((message) => message?.type !== "additional_tools")
|
|
183
|
+
.map((message) => {
|
|
184
|
+
if (
|
|
185
|
+
!message ||
|
|
186
|
+
(message.type && message.type !== "message") ||
|
|
187
|
+
!["user", "assistant", "system", "developer"].includes(message.role)
|
|
188
|
+
)
|
|
189
|
+
throw isolationError(
|
|
190
|
+
"INFERENCE_REQUEST_DENIED",
|
|
191
|
+
"Provider objects and tools cannot enter this session.",
|
|
192
|
+
);
|
|
193
|
+
return { type: "message", role: message.role, content: plainText(message.content) };
|
|
194
|
+
});
|
|
195
|
+
else throw isolationError("INFERENCE_REQUEST_DENIED", "Text input is required.");
|
|
196
|
+
} else if (protocol === "anthropic" || protocol === "chat") {
|
|
197
|
+
body.tools = [];
|
|
198
|
+
if (protocol === "anthropic" && input.system !== undefined)
|
|
199
|
+
body.system = plainText(input.system, "text");
|
|
200
|
+
if (!Array.isArray(input.messages))
|
|
201
|
+
throw isolationError("INFERENCE_REQUEST_DENIED", "Text messages are required.");
|
|
202
|
+
body.messages = input.messages.map((message) => {
|
|
203
|
+
if (
|
|
204
|
+
!(
|
|
205
|
+
protocol === "anthropic"
|
|
206
|
+
? ["user", "assistant"]
|
|
207
|
+
: ["user", "assistant", "system", "developer"]
|
|
208
|
+
).includes(message?.role)
|
|
209
|
+
)
|
|
210
|
+
throw isolationError("INFERENCE_REQUEST_DENIED", "Unsupported message role.");
|
|
211
|
+
return { role: message.role, content: plainText(message.content, "text") };
|
|
212
|
+
});
|
|
213
|
+
body.max_tokens ??= 4096;
|
|
214
|
+
} else throw isolationError("INFERENCE_REQUEST_DENIED", "Unsupported inference protocol.");
|
|
215
|
+
return body;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Each broker is private, short-lived, pinned to one account, and has no tool API. */
|
|
219
|
+
export async function startInferenceBroker({
|
|
220
|
+
authority,
|
|
221
|
+
model,
|
|
222
|
+
socketPath,
|
|
223
|
+
signal,
|
|
224
|
+
fetcher = fetch,
|
|
225
|
+
maxRequests = 12,
|
|
226
|
+
timeoutMs = 120000,
|
|
227
|
+
}) {
|
|
228
|
+
const origin = new URL(authority.origin);
|
|
229
|
+
if (
|
|
230
|
+
origin.protocol !== "https:" ||
|
|
231
|
+
origin.username ||
|
|
232
|
+
origin.password ||
|
|
233
|
+
origin.pathname !== "/" ||
|
|
234
|
+
origin.search ||
|
|
235
|
+
origin.hash ||
|
|
236
|
+
!["responses", "anthropic", "chat"].includes(authority.protocol) ||
|
|
237
|
+
!/^\/[A-Za-z0-9/_-]+$/.test(authority.prefix)
|
|
238
|
+
)
|
|
239
|
+
throw isolationError(
|
|
240
|
+
"INFERENCE_CONFIG_INVALID",
|
|
241
|
+
"Choose a pinned HTTPS inference origin and API prefix.",
|
|
242
|
+
);
|
|
243
|
+
const token = randomBytes(32).toString("hex");
|
|
244
|
+
const stop = new AbortController();
|
|
245
|
+
const sessionSignal = signal ? AbortSignal.any([signal, stop.signal]) : stop.signal;
|
|
246
|
+
let requests = 0;
|
|
247
|
+
const server = createServer(async (request, response) => {
|
|
248
|
+
const deny = (status = 403) => {
|
|
249
|
+
if (!response.headersSent) response.writeHead(status, { "content-type": "application/json" });
|
|
250
|
+
response.end('{"error":"INFERENCE_REQUEST_DENIED"}');
|
|
251
|
+
};
|
|
252
|
+
try {
|
|
253
|
+
const supplied =
|
|
254
|
+
request.headers.authorization?.replace(/^Bearer /u, "") ?? request.headers["x-api-key"];
|
|
255
|
+
if (
|
|
256
|
+
typeof supplied !== "string" ||
|
|
257
|
+
Buffer.byteLength(supplied) !== Buffer.byteLength(token) ||
|
|
258
|
+
!timingSafeEqual(Buffer.from(supplied), Buffer.from(token)) ||
|
|
259
|
+
request.method !== "POST" ||
|
|
260
|
+
!request.url?.startsWith("/") ||
|
|
261
|
+
request.url.startsWith("//") ||
|
|
262
|
+
++requests > maxRequests ||
|
|
263
|
+
sessionSignal.aborted
|
|
264
|
+
)
|
|
265
|
+
return deny();
|
|
266
|
+
const url = new URL(request.url, "http://127.0.0.1");
|
|
267
|
+
const operation =
|
|
268
|
+
authority.protocol === "responses"
|
|
269
|
+
? url.pathname === "/v1/responses"
|
|
270
|
+
? "/responses"
|
|
271
|
+
: null
|
|
272
|
+
: authority.protocol === "chat"
|
|
273
|
+
? url.pathname === "/v1/chat/completions"
|
|
274
|
+
? "/chat/completions"
|
|
275
|
+
: null
|
|
276
|
+
: ["/v1/messages", "/v1/messages/count_tokens"].includes(url.pathname)
|
|
277
|
+
? url.pathname.slice(3)
|
|
278
|
+
: null;
|
|
279
|
+
if (!operation || (url.search && url.search !== "?beta=true")) return deny();
|
|
280
|
+
const chunks = [];
|
|
281
|
+
let size = 0;
|
|
282
|
+
for await (const chunk of request) {
|
|
283
|
+
if ((size += chunk.length) > 2 * 1024 * 1024) return deny(413);
|
|
284
|
+
chunks.push(chunk);
|
|
285
|
+
}
|
|
286
|
+
const body = inferenceRequest(
|
|
287
|
+
authority.protocol,
|
|
288
|
+
JSON.parse(Buffer.concat(chunks).toString("utf8")),
|
|
289
|
+
model,
|
|
290
|
+
);
|
|
291
|
+
if (operation.endsWith("/count_tokens")) {
|
|
292
|
+
for (const name of [
|
|
293
|
+
"max_tokens",
|
|
294
|
+
"max_output_tokens",
|
|
295
|
+
"stream",
|
|
296
|
+
"output_config",
|
|
297
|
+
"temperature",
|
|
298
|
+
"top_p",
|
|
299
|
+
])
|
|
300
|
+
delete body[name];
|
|
301
|
+
}
|
|
302
|
+
const upstream = await fetcher(
|
|
303
|
+
`${origin.origin}${authority.prefix}${operation}${url.search}`,
|
|
304
|
+
{
|
|
305
|
+
method: "POST",
|
|
306
|
+
redirect: "error",
|
|
307
|
+
signal: AbortSignal.any([sessionSignal, AbortSignal.timeout(timeoutMs)]),
|
|
308
|
+
headers: { "content-type": "application/json", ...authority.headers },
|
|
309
|
+
body: JSON.stringify(body),
|
|
310
|
+
},
|
|
311
|
+
);
|
|
312
|
+
if (!upstream.ok) {
|
|
313
|
+
await upstream.body?.cancel();
|
|
314
|
+
return deny(502);
|
|
315
|
+
}
|
|
316
|
+
response.writeHead(200, {
|
|
317
|
+
"content-type": upstream.headers.get("content-type") ?? "application/json",
|
|
318
|
+
"cache-control": "no-store",
|
|
319
|
+
});
|
|
320
|
+
let received = 0;
|
|
321
|
+
for await (const chunk of upstream.body) {
|
|
322
|
+
if ((received += chunk.length) > 8 * 1024 * 1024) {
|
|
323
|
+
response.destroy();
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
if (!response.write(chunk))
|
|
327
|
+
await new Promise((resolve) => {
|
|
328
|
+
response.once("drain", resolve);
|
|
329
|
+
response.once("close", resolve);
|
|
330
|
+
});
|
|
331
|
+
if (response.destroyed) break;
|
|
332
|
+
}
|
|
333
|
+
response.end();
|
|
334
|
+
} catch {
|
|
335
|
+
if (response.headersSent) response.destroy();
|
|
336
|
+
else deny(502);
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
server.requestTimeout = Math.min(timeoutMs, 120000);
|
|
340
|
+
server.maxConnections = 8;
|
|
341
|
+
server.headersTimeout = 10000;
|
|
342
|
+
server.on("connect", (_request, socket) => socket.destroy());
|
|
343
|
+
server.on("upgrade", (_request, socket) => socket.destroy());
|
|
344
|
+
await new Promise((resolve, reject) => {
|
|
345
|
+
server.once("error", reject);
|
|
346
|
+
if (socketPath) server.listen(socketPath, resolve);
|
|
347
|
+
else server.listen(0, "127.0.0.1", resolve);
|
|
348
|
+
});
|
|
349
|
+
const address = server.address();
|
|
350
|
+
return {
|
|
351
|
+
token,
|
|
352
|
+
socketPath,
|
|
353
|
+
port: typeof address === "object" ? address.port : null,
|
|
354
|
+
baseUrl: typeof address === "object" ? `http://127.0.0.1:${address.port}` : null,
|
|
355
|
+
async close() {
|
|
356
|
+
stop.abort();
|
|
357
|
+
server.closeAllConnections();
|
|
358
|
+
await new Promise((resolve) => server.close(resolve));
|
|
359
|
+
},
|
|
360
|
+
};
|
|
361
|
+
}
|