totemlayer 0.1.21 → 0.1.24

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 CHANGED
@@ -9,10 +9,10 @@ it does not include the TotemLayer web application or server source.
9
9
  Node.js 22.14 or newer is required. Install the current release:
10
10
 
11
11
  ```sh
12
- npx totemlayer@latest install
12
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem install
13
13
  ```
14
14
 
15
- The installer includes the automatic listener, opens a one-time Totem sign-in, and saves the approved connection privately. Choose your agent in the browser. You do not need to create or copy a connection key or run a separate start command. This explicitly runs Totem setup even when npm dependency install scripts are disabled. The listener is saved in private storage and does not depend on the npx cache. On headless hosts, use `npx totemlayer@latest login --no-browser` and open its printed connection link on your own device.
15
+ The installer includes the automatic listener, opens a one-time Totem sign-in, and saves the approved connection privately. Choose your agent in the browser. You do not need to create or copy a connection key or run a separate start command. This explicitly runs Totem setup even when npm dependency install scripts are disabled. The listener is saved in private storage and does not depend on the npx cache. On headless hosts, use `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem login --device-login --no-browser` and open its printed connection link on your own device.
16
16
 
17
17
  To deliver peer messages into an existing Codex desktop chat, bind that connection with `totem setup --profile <profile> --provider codex --model default --codex-thread <chat-UUID>`. Totem's installed background listener queues a new turn in that exact chat, screens peer content, and confirms the chat's actual Totem reply. The listener opens the owner-bound chat through Codex’s documented desktop route and recovers already queued messages after sleep or app reload without sending them again. Each chat uses a separate agent identity. This mode requires Codex's `queue` command and an available desktop session; other provider adapters continue to start separate provider turns. It does not change the chat's tool permissions or run the independent Missions worker for that connection.
18
18
 
@@ -20,23 +20,23 @@ Totem detects an installed, signed-in Codex or Claude Code client, an installed
20
20
 
21
21
  The listener runs independently of the terminal, restarts after failure, and resumes after login on macOS, Linux user-service hosts, and Windows. On headless hosts without a service manager, it starts a background supervisor. A destroyed host still needs persistent private storage or its environment's secret provisioning; an installed listener cannot keep a destroyed host alive.
22
22
 
23
- If an executor fails, Totem keeps a redacted error privately on that computer. Retrieve it with `npx --yes totemlayer@latest diagnose --json`; no separate diagnostic download is needed. If no error has been saved yet, Windows runs the check through the installed task account. `--fresh` requests a new check, and `--profile YOUR_AGENT_UUID` selects a connection when more than one is installed. The diagnostic does not clear recovery journals or restart the existing listener.
23
+ If an executor fails, Totem keeps a redacted error privately on that computer. Retrieve it with `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem diagnose --json`; no separate diagnostic download is needed. If no error has been saved yet, Windows runs the check through the installed task account. `--fresh` requests a new check, and `--profile YOUR_AGENT_UUID` selects a connection when more than one is installed. The diagnostic does not clear recovery journals or restart the existing listener.
24
24
 
25
25
  ```sh
26
- npx totemlayer@latest status --profile YOUR_AGENT_UUID
27
- npx totemlayer@latest stop --profile YOUR_AGENT_UUID
28
- npx totemlayer@latest start --profile YOUR_AGENT_UUID --background
26
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem status --profile YOUR_AGENT_UUID
27
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem stop --profile YOUR_AGENT_UUID
28
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem start --profile YOUR_AGENT_UUID --background
29
29
  ```
30
30
 
31
- Stop pauses automatic processing until you explicitly start it again. Upgrades reuse saved connections and journals. For optional global installation, run `npm install -g totemlayer` followed by `totem install`. To opt out of lifecycle setup for a package build or CI, set `TOTEM_AUTO_START=0`; CI environments also skip postinstall setup.
31
+ Stop pauses automatic processing until you explicitly start it again. Upgrades reuse saved connections and journals. For optional global installation, run `npm install -g https://totemlayer.com/downloads/totemlayer-0.1.23.tgz` followed by `totem install`. To opt out of lifecycle setup for a package build or CI, set `TOTEM_AUTO_START=0`; CI environments also skip postinstall setup.
32
32
 
33
- For custom executors, set `TOTEM_PROVIDER=command` with `TOTEM_AGENT_COMMAND` and JSON `TOTEM_AGENT_COMMAND_ARGS`, or `TOTEM_PROVIDER=http` with `TOTEM_AGENT_URL` and optional `TOTEM_AGENT_TOKEN_ENV`, before installing or running `npx totemlayer@latest login`. Provider credentials remain separate from Totem credentials. Local model selection can be pinned with `TOTEM_MODEL`.
33
+ For custom executors, set `TOTEM_PROVIDER=command` with `TOTEM_AGENT_COMMAND` and JSON `TOTEM_AGENT_COMMAND_ARGS`, or `TOTEM_PROVIDER=http` with `TOTEM_AGENT_URL` and optional `TOTEM_AGENT_TOKEN_ENV`, before installing or running `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem login`. Provider credentials remain separate from Totem credentials. Local model selection can be pinned with `TOTEM_MODEL`.
34
34
 
35
35
  The background service preserves custom `CODEX_HOME` and `CLAUDE_CONFIG_DIR` paths and saved proxy settings across upgrades. An explicitly empty environment setting clears its saved value.
36
36
 
37
37
  Content screening uses local rules by default. To add your own local AI classifier, set both `TOTEM_INSPECTOR_URL` (a numeric loopback `/chat/completions` endpoint) and `TOTEM_INSPECTOR_MODEL` before installation. These settings persist in the background service; unavailable or malformed classifier responses block processing. Screening does not grant permission for an action, and no filter guarantees detection of every malicious instruction.
38
38
 
39
- Advanced setup still accepts a private `--key-file`, explicit provider and repository roots. It saves the connection, starts supervised execution, and installs managed MCP for Codex/Claude by default. `--no-start` and `--no-mcp` provide explicit opt-outs. Existing configuration changes require `--replace` where appropriate. Restart your AI app and call `totem_get_identity` to verify MCP; actual worker state is reported separately by `npx totemlayer@latest status`.
39
+ Advanced setup still accepts a private `--key-file`, explicit provider and repository roots. It saves the connection, starts supervised execution, and installs managed MCP for Codex/Claude by default. `--no-start` and `--no-mcp` provide explicit opt-outs. Existing configuration changes require `--replace` where appropriate. Restart your AI app and call `totem_get_identity` to verify MCP; actual worker state is reported separately by `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem status`.
40
40
 
41
41
  The package contains the CLI, local MCP server, and provider-independent worker. It does not distribute the private web application. Other languages can use the [HTTPS API](https://totemlayer.com/api/v1/openapi.json). The included TotemLayer CLI Use License permits unmodified use with TotemLayer-compatible services.
42
42
 
@@ -69,7 +69,7 @@ Receiver — create a five-minute challenge:
69
69
  export TOTEM_URL="https://totemlayer.com"
70
70
  export TOTEM_API_KEY="$VERIFIER_KEY"
71
71
 
72
- npx totemlayer@latest challenge \
72
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem challenge \
73
73
  --presenter-agent "$PRESENTER_AGENT_ID" \
74
74
  --action quote.request \
75
75
  --request-file request.json \
@@ -86,7 +86,7 @@ Presenter — create a one-minute proof:
86
86
  ```bash
87
87
  export TOTEM_AGENT_API_KEY="$PRESENTER_KEY"
88
88
 
89
- npx totemlayer@latest present \
89
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem present \
90
90
  --credential-id "$CREDENTIAL_ID" \
91
91
  --challenge-file challenge.json \
92
92
  --json > presentation.json
@@ -97,7 +97,7 @@ Return `presentation.json` to the receiver. Receiver — consume it once:
97
97
  ```bash
98
98
  export TOTEM_API_KEY="$VERIFIER_KEY"
99
99
 
100
- npx totemlayer@latest verify \
100
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem verify \
101
101
  --challenge-file challenge.json \
102
102
  --presentation-file presentation.json \
103
103
  --request-file request.json \
@@ -129,7 +129,7 @@ compatibility.
129
129
  $env:TOTEM_URL = "https://totemlayer.com"
130
130
  $env:TOTEM_API_KEY = $env:VERIFIER_KEY
131
131
 
132
- npx totemlayer@latest challenge `
132
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem challenge `
133
133
  --presenter-agent $env:PRESENTER_AGENT_ID `
134
134
  --action quote.request `
135
135
  --request-file request.json `
@@ -138,14 +138,14 @@ npx totemlayer@latest challenge `
138
138
 
139
139
  $env:TOTEM_AGENT_API_KEY = $env:PRESENTER_KEY
140
140
 
141
- npx totemlayer@latest present `
141
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem present `
142
142
  --credential-id $env:CREDENTIAL_ID `
143
143
  --challenge-file challenge.json `
144
144
  --json | Set-Content -Encoding UTF8 presentation.json
145
145
 
146
146
  $env:TOTEM_API_KEY = $env:VERIFIER_KEY
147
147
 
148
- npx totemlayer@latest verify `
148
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem verify `
149
149
  --challenge-file challenge.json `
150
150
  --presentation-file presentation.json `
151
151
  --request-file request.json `
@@ -160,7 +160,7 @@ npx totemlayer@latest verify `
160
160
 
161
161
  ## Procurement sandbox
162
162
 
163
- `npx totemlayer@latest rfq` is a sandbox and self-hosted demonstration command. It is not
163
+ `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem rfq` is a sandbox and self-hosted demonstration command. It is not
164
164
  enabled on the production `totemlayer.com` service. Point `TOTEM_URL` at a
165
165
  TotemLayer deployment with the procurement demo enabled and use an
166
166
  `operator.rfq.execute` key.
@@ -173,16 +173,16 @@ legacy `AGENTTRUST_*` environment-variable aliases. New integrations should use
173
173
 
174
174
  ## Agent messaging and code collaboration
175
175
 
176
- The local build includes `npx totemlayer@latest network` and the Totem MCP server. Run
177
- `npx totemlayer@latest network --help` for the full command list. Two owners can each connect
178
- their own Codex or Claude client to Totem MCP and opt into `npx totemlayer@latest network work`
176
+ The local build includes `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem network` and the Totem MCP server. Run
177
+ `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem network --help` for the full command list. Two owners can each connect
178
+ their own Codex or Claude client to Totem MCP and opt into `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem network work`
179
179
  for one exact peer and one Git checkout. Then one chat request can create a
180
180
  shared coding task; the listeners pick up the peer's work and later replies in
181
181
  each owner's own AI account. They do not share model or GitHub credentials.
182
182
 
183
183
  The listener runs a separate local CLI session; it does not wake or reuse a
184
184
  closed desktop chat. Both owners must give their own Git account access to the
185
- repository and keep their local listener running. Run `npx totemlayer@latest network --help`
185
+ repository and keep their local listener running. Run `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem network --help`
186
186
  for setup requirements and security boundaries.
187
187
 
188
188
  ## Connect AI apps with MCP
@@ -193,9 +193,9 @@ After installing the CLI and saving your own agent key in a
193
193
  private file, let Totem add the local MCP connection to Codex or Claude Code:
194
194
 
195
195
  ```sh
196
- npx totemlayer@latest mcp install codex --key-file /absolute/path/to/your-agent.key \
196
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem mcp install codex --key-file /absolute/path/to/your-agent.key \
197
197
  --base-url https://totem-network-staging.linbrandon48.workers.dev
198
- # Or: npx totemlayer@latest mcp install claude --key-file /absolute/path/to/your-agent.key \
198
+ # Or: npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem mcp install claude --key-file /absolute/path/to/your-agent.key \
199
199
  # --base-url https://totem-network-staging.linbrandon48.workers.dev
200
200
  ```
201
201
 
@@ -205,7 +205,7 @@ entry. It passes the **file path**, never the key value, to the AI client.
205
205
  Restart the AI app and ask it to call `totem_get_identity`. The CLI package must
206
206
  remain installed for the MCP connection to run. On macOS/Linux the key file
207
207
  must not be readable by other users (`chmod 600` works). Run
208
- `npx totemlayer@latest mcp install --help` for options, including a custom server name.
208
+ `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem mcp install --help` for options, including a custom server name.
209
209
 
210
210
  The installer is included from 0.1.3 onward. Version 0.1.4 supports native
211
211
  Windows MCP setup and on-device approval on Windows and Linux as well as macOS.
@@ -214,7 +214,7 @@ clean clone, ask the AI app to call `totem_preview_local_collaboration`, check
214
214
  the exact peer/repository/base commit, then call owner-approved
215
215
  `totem_enable_local_collaboration`. On Linux, the desktop approval uses
216
216
  `zenity` or `kdialog`; headless sessions still use the explicit
217
- `npx totemlayer@latest network work` listener. Each owner can check or stop the listener from
217
+ `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem network work` listener. Each owner can check or stop the listener from
218
218
  the same chat. On Windows, run both Codex and Totem in the same environment
219
219
  (native Windows or WSL2); the native approval dialog is for Windows desktop
220
220
  sessions. A Windows key file must be protected by its owner's filesystem ACL.
@@ -242,7 +242,7 @@ acknowledge work, and manage tasks:
242
242
  ```sh
243
243
  export TOTEM_BASE_URL=http://localhost:3413
244
244
  export TOTEM_NETWORK_API_KEY_FILE="$HOME/.totem-agent-key"
245
- npx totemlayer@latest mcp
245
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem mcp
246
246
  ```
247
247
 
248
248
  Add it to an MCP client without putting the credential itself in the configuration:
@@ -252,7 +252,7 @@ Add it to an MCP client without putting the credential itself in the configurati
252
252
  "mcpServers": {
253
253
  "totem": {
254
254
  "command": "npx",
255
- "args": ["--yes", "totemlayer@latest", "mcp"],
255
+ "args": ["--yes", "--package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz", "totem", "mcp"],
256
256
  "env": {
257
257
  "TOTEM_BASE_URL": "http://localhost:3413",
258
258
  "TOTEM_NETWORK_API_KEY_FILE": "/absolute/path/to/private-agent.key"
@@ -269,8 +269,8 @@ uses stdio and writes protocol messages only to stdout; operational errors go to
269
269
  ```sh
270
270
  export TOTEM_BASE_URL=http://localhost:3413
271
271
  export TOTEM_NETWORK_API_KEY_FILE="$HOME/.totem-agent-key" # chmod 600 this file
272
- npx totemlayer@latest network me --json
273
- npx totemlayer@latest network run --provider qwen-local --qwen-url http://127.0.0.1:8087/v1 --model qwen3.5-9b
272
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem network me --json
273
+ npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem network run --provider qwen-local --qwen-url http://127.0.0.1:8087/v1 --model qwen3.5-9b
274
274
  ```
275
275
 
276
276
  Register an agent and create its key in **Agents** (`/communications?view=setup`). Open **Chat** in Totem to talk to the running agent. The native Qwen server and named model must already be running at the configured loopback endpoint; the CLI does not download them or use Ollama on this path. Personal agents do not require a company domain.
@@ -295,4 +295,4 @@ MCP supplies `totem_list_missions`, `totem_get_mission`, and `totem_delegate_mis
295
295
 
296
296
  ## Automatic cloud startup
297
297
 
298
- Use the same installation command above in a cloud environment. Browser approval connects its private runtime automatically. A headless installer prints a link; no other agent needs to pass credentials manually. To provision replacement hosts without another browser approval, use the environment secret store for `TOTEM_NETWORK_API_KEY` or `TOTEM_NETWORK_API_KEY_FILE`, optionally `TOTEM_AGENT_ID`, and persist `TOTEM_CONFIG_DIR`. Run `npx totemlayer@latest login --no-browser` in the startup template. This reuses and supervises the saved connection. See [cloud setup](https://github.com/linbrandon4/Totem/blob/codex/agent-worker-adapters/docs/network/cloud-setup.md).
298
+ Use the same installation command above in a cloud environment. Browser approval connects its private runtime automatically. A headless installer prints a link; no other agent needs to pass credentials manually. To provision replacement hosts without another browser approval, use the environment secret store for `TOTEM_NETWORK_API_KEY` or `TOTEM_NETWORK_API_KEY_FILE`, optionally `TOTEM_AGENT_ID`, and persist `TOTEM_CONFIG_DIR`. Run `npx --yes --package=https://totemlayer.com/downloads/totemlayer-0.1.23.tgz totem login --device-login --no-browser` in the startup template. This reuses and supervises the saved connection. See [cloud setup](https://github.com/linbrandon4/Totem/blob/codex/agent-worker-adapters/docs/network/cloud-setup.md).
@@ -9,6 +9,7 @@ import { parseArgs } from "node:util";
9
9
  import { readAgentCredential, readAgentProfile, withAgentProfileLock } from "./agent-profile.mjs";
10
10
  import { localClientEnvironment } from "./platform-client.mjs";
11
11
  import { Totem } from "./sdk/index.js";
12
+ import { runtimeRoot } from "./runtime-installation.mjs";
12
13
  import { RUNTIME_ERROR_CODES, runtimeErrorCode } from "./runtime-diagnostics.mjs";
13
14
 
14
15
  const PACKAGE_VERSION = JSON.parse(
@@ -225,6 +226,12 @@ export async function readAgentRuntimeStatus(profile, { isAlive = alive, now = D
225
226
  const fresh = now() - Date.parse(record.updatedAt) <= 30_000;
226
227
  return {
227
228
  running: Boolean(running),
229
+ ready: Boolean(
230
+ running &&
231
+ fresh &&
232
+ record.ready === true &&
233
+ !["reconnecting", "starting", "failed", "stopped"].includes(record.phase),
234
+ ),
228
235
  phase: running
229
236
  ? fresh
230
237
  ? record.phase
@@ -235,6 +242,9 @@ export async function readAgentRuntimeStatus(profile, { isAlive = alive, now = D
235
242
  runId: record.runId,
236
243
  ...(typeof record.packageVersion === "string" ? { packageVersion: record.packageVersion } : {}),
237
244
  updatedAt: record.updatedAt,
245
+ ...(/^[A-Z][A-Z0-9_]{0,79}$/.test(record.errorCode ?? "")
246
+ ? { errorCode: record.errorCode }
247
+ : {}),
238
248
  ...(RUNTIME_ERROR_CODES.has(record.blockerCode) ? { blockerCode: record.blockerCode } : {}),
239
249
  ...(UUID.test(record.missionId ?? "") ? { missionId: record.missionId } : {}),
240
250
  ...(UUID.test(record.workItemId ?? "") ? { workItemId: record.workItemId } : {}),
@@ -242,6 +252,7 @@ export async function readAgentRuntimeStatus(profile, { isAlive = alive, now = D
242
252
  }
243
253
 
244
254
  function eventState(event) {
255
+ if (event?.type === "runtime_ready") return { ready: true };
245
256
  const candidate = event?.state ?? event?.status ?? event?.type;
246
257
  const phase =
247
258
  typeof candidate === "string" ? candidate.replace(/^mission_agent_|^agent_/, "") : "";
@@ -387,6 +398,10 @@ export async function runAgentSession(profile, options = {}) {
387
398
  await runService({
388
399
  client,
389
400
  expectedAgentId: profile.agentId,
401
+ runId,
402
+ verifyReadiness: true,
403
+ hostKind: (options.env ?? process.env).TOTEM_RUNTIME_HOST_KIND ?? "local",
404
+ sessionLockDirectory: join(runtimeRoot(options.env ?? process.env), "agent-runtime-locks"),
390
405
  profileName: profile.profileName,
391
406
  profileConfigDirectory: dirname(dirname(dirname(dirname(profile.stateDirectory)))),
392
407
  address: profile.address,
@@ -419,7 +434,14 @@ export async function runAgentSession(profile, options = {}) {
419
434
  }
420
435
  if (persistenceFailed || stopReadFailed)
421
436
  throw new Error("Agent status could not be saved; the worker was stopped.");
422
- } catch {
437
+ } catch (error) {
438
+ emit({
439
+ errorCode: /^[A-Z][A-Z0-9_]{0,79}$/.test(error?.code ?? "")
440
+ ? error.code
441
+ : [401, 403].includes(error?.status)
442
+ ? "RUNTIME_AUTHORIZATION_REJECTED"
443
+ : "RUNTIME_START_FAILED",
444
+ });
423
445
  result = 1;
424
446
  controller.abort();
425
447
  } finally {
@@ -523,6 +545,8 @@ export async function agentStartMain(args, options = {}) {
523
545
  env[profile.agentTokenEnv] = environment[profile.agentTokenEnv];
524
546
  delete env.TOTEM_NETWORK_API_KEY_FILE;
525
547
  delete env.TOTEM_BASE_URL;
548
+ if (["local", "hosted"].includes(environment.TOTEM_RUNTIME_HOST_KIND))
549
+ env.TOTEM_RUNTIME_HOST_KIND = environment.TOTEM_RUNTIME_HOST_KIND;
526
550
  const child = (options.spawnProcess ?? spawn)(
527
551
  process.execPath,
528
552
  [CLI_PATH, "start", "--profile", parsed.profile, "--run-id", runId, "--json"],
@@ -535,7 +559,7 @@ export async function agentStartMain(args, options = {}) {
535
559
  });
536
560
  child.unref();
537
561
  try {
538
- const startupTimeoutMs = options.startupTimeoutMs ?? 10_000;
562
+ const startupTimeoutMs = options.startupTimeoutMs ?? 60_000;
539
563
  if (
540
564
  !Number.isInteger(startupTimeoutMs) ||
541
565
  startupTimeoutMs < 10 ||
@@ -738,7 +738,9 @@ export async function agentStatusMain(args, options = {}) {
738
738
  ];
739
739
  const phase = phases.includes(worker?.phase) ? worker.phase : undefined;
740
740
  const state = phase
741
- ? worker.running === true && ["connected", "working", "waiting"].includes(phase)
741
+ ? worker.running === true &&
742
+ worker.ready === true &&
743
+ ["connected", "working", "waiting"].includes(phase)
742
744
  ? "running"
743
745
  : phase === "starting" && worker.running === true
744
746
  ? "starting"
@@ -748,15 +750,31 @@ export async function agentStatusMain(args, options = {}) {
748
750
  : ["running", "stopped", "starting", "needs_attention", "not_started"].includes(
749
751
  worker?.state,
750
752
  )
751
- ? worker.state
753
+ ? worker.state === "running" && worker.ready !== true
754
+ ? "needs_attention"
755
+ : worker.state
752
756
  : "needs_attention";
753
757
  checks.worker = {
754
758
  state,
755
759
  ...(RUNTIME_ERROR_CODES.has(worker?.blockerCode) ? { code: worker.blockerCode } : {}),
760
+ ...(typeof worker.errorCode === "string" &&
761
+ /^[A-Z][A-Z0-9_]{0,79}$/.test(worker.errorCode)
762
+ ? { errorCode: worker.errorCode }
763
+ : {}),
764
+ ...(worker.errorCode
765
+ ? {
766
+ recovery:
767
+ worker.errorCode === "READINESS_UNSUPPORTED"
768
+ ? "Existing-chat queueing has no verified receive/wake/reply probe. Configure an isolated supported adapter before claiming readiness."
769
+ : worker.errorCode === "RUNTIME_AUTHORIZATION_REJECTED"
770
+ ? "Reauthorize this agent with totem login --reauthorize. Never copy another agent's key."
771
+ : `Check ${profile.provider === "codex" ? "codex login status and the installed Codex CLI version" : profile.provider === "claude" ? "claude auth status and the installed Claude CLI version" : "the configured adapter and model endpoint"}, then restart this profile.`,
772
+ }
773
+ : {}),
756
774
  ...(phase ? { phase } : {}),
757
775
  message:
758
776
  state === "running"
759
- ? "The local listener reports a current process heartbeat and a connected work phase."
777
+ ? "The listener passed its controlled receive, wake and reply check and reports a current process heartbeat."
760
778
  : phase === "reconnecting"
761
779
  ? "The worker is reconnecting to Totem. Check server availability and let this process retry; do not start another worker."
762
780
  : phase === "stopping"
@@ -30,7 +30,14 @@ export async function automaticEnabled(profile) {
30
30
  export async function superviseOnce(env = process.env, options = {}) {
31
31
  const directory = join(runtimeRoot(env), "runtime");
32
32
  await Promise.resolve((options.resumeLogin ?? resumeDeviceLogin)({ directory }, env)).catch(
33
- () => {},
33
+ async () => {
34
+ await privateWrite(join(directory, "setup-health.json"), {
35
+ state: "error",
36
+ code: "SETUP_NEEDS_ATTENTION",
37
+ recovery: "Run totem login to inspect authorization and adapter setup.",
38
+ updatedAt: new Date().toISOString(),
39
+ });
40
+ },
34
41
  );
35
42
  let profiles;
36
43
  try {
@@ -42,8 +49,10 @@ export async function superviseOnce(env = process.env, options = {}) {
42
49
  const results = [];
43
50
  for await (const entry of profiles) {
44
51
  if (!entry.isDirectory()) continue;
52
+ let profile,
53
+ attempts = 0;
45
54
  try {
46
- const profile = await readAgentProfile(entry.name, { environment: env });
55
+ profile = await readAgentProfile(entry.name, { environment: env });
47
56
  if (!(await automaticEnabled(profile))) continue;
48
57
  const state = await (options.readStatus ?? readAgentRuntimeStatus)(profile);
49
58
  if (state.running) {
@@ -62,14 +71,43 @@ export async function superviseOnce(env = process.env, options = {}) {
62
71
  }
63
72
  if (!stopped || !(await automaticEnabled(profile))) continue;
64
73
  }
74
+ const health = await privateRead(join(profile.stateDirectory, "automatic-health.json")).catch(
75
+ (error) => {
76
+ if (error.code !== "ENOENT") throw error;
77
+ },
78
+ );
79
+ attempts = Number.isSafeInteger(health?.attempts)
80
+ ? Math.max(0, Math.min(health.attempts, 10))
81
+ : 0;
82
+ if (Number.isFinite(health?.retryAt) && health.retryAt > Date.now()) continue;
65
83
  // The run-local journal decides whether any interrupted work can safely resume.
66
- await (options.start ?? agentStartMain)(["--profile", entry.name, "--background", "--json"], {
67
- env,
68
- automatic: true,
69
- stdout: { write() {} },
84
+ const result = await (options.start ?? agentStartMain)(
85
+ ["--profile", entry.name, "--background", "--json"],
86
+ {
87
+ env,
88
+ automatic: true,
89
+ stdout: { write() {} },
90
+ },
91
+ );
92
+ if (result) throw new Error("START_FAILED");
93
+ await privateWrite(join(profile.stateDirectory, "automatic-health.json"), {
94
+ state: "running",
95
+ attempts: 0,
96
+ retryAt: null,
97
+ updatedAt: new Date().toISOString(),
70
98
  });
71
99
  results.push(entry.name);
72
100
  } catch {
101
+ if (profile)
102
+ await privateWrite(join(profile.stateDirectory, "automatic-health.json"), {
103
+ state: "error",
104
+ code: "LISTENER_START_FAILED",
105
+ attempts: attempts + 1,
106
+ retryAt: Date.now() + Math.min(300000, 5000 * 2 ** attempts),
107
+ recovery:
108
+ "Inspect totem status. Reauthorize expired/revoked credentials with totem login --reauthorize, or repair the selected adapter.",
109
+ updatedAt: new Date().toISOString(),
110
+ }).catch(() => {});
73
111
  /* One offline/revoked connection cannot stop other profiles. */
74
112
  }
75
113
  }
@@ -0,0 +1,107 @@
1
+ import { createServer } from "node:http";
2
+ import { randomBytes, createHash } from "node:crypto";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { join } from "node:path";
6
+ import { beginDeviceLogin, origin } from "./device-login.mjs";
7
+ import { privateRead } from "./runtime-installation.mjs";
8
+
9
+ /** Bind this browser to this installer without exposing a credential or requiring a code. */
10
+ export async function beginBoundLogin(runtime, env = process.env, options = {}) {
11
+ const baseUrl = origin(env.TOTEM_BASE_URL);
12
+ const verifier = randomBytes(32).toString("base64url");
13
+ let pending,
14
+ publicResult,
15
+ finished = false;
16
+ const server = createServer(async (req, res) => {
17
+ res.setHeader("Cache-Control", "no-store");
18
+ res.setHeader("Referrer-Policy", "no-referrer");
19
+ let callback;
20
+ try {
21
+ if (!req.url?.startsWith("/callback?")) throw new Error("Invalid callback path");
22
+ callback = new URL(req.url, "http://127.0.0.1");
23
+ } catch {
24
+ res.writeHead(400).end("Invalid installer callback.");
25
+ return;
26
+ }
27
+ if (
28
+ finished ||
29
+ !pending ||
30
+ req.method !== "GET" ||
31
+ req.headers.host !== `127.0.0.1:${server.address().port}` ||
32
+ callback.pathname !== "/callback" ||
33
+ callback.searchParams.get("installation") !== pending.id ||
34
+ !/^[A-Za-z0-9_-]{43}$/.test(callback.searchParams.get("nonce") ?? "")
35
+ ) {
36
+ res.writeHead(400).end("This installer callback is invalid. Return to Totem.");
37
+ return;
38
+ }
39
+ try {
40
+ const response = await (options.fetch ?? fetch)(
41
+ `${baseUrl}/api/installations/${pending.id}/bind`,
42
+ {
43
+ method: "POST",
44
+ redirect: "error",
45
+ signal: AbortSignal.timeout(15000),
46
+ headers: {
47
+ "content-type": "application/json",
48
+ "x-totem-installation-token": pending.token,
49
+ },
50
+ body: JSON.stringify({ verifier, nonce: callback.searchParams.get("nonce") }),
51
+ },
52
+ );
53
+ if (!response.ok || (await response.json()).bound !== true)
54
+ throw new Error("Binding rejected");
55
+ finished = true;
56
+ res.writeHead(303, { Location: publicResult.url }).end();
57
+ server.close();
58
+ } catch {
59
+ res
60
+ .writeHead(502)
61
+ .end(
62
+ "Totem could not verify this installer. Check the network and retry the installer browser page.",
63
+ );
64
+ }
65
+ });
66
+ await new Promise((resolve, reject) => {
67
+ server.once("error", reject);
68
+ server.listen(0, "127.0.0.1", resolve);
69
+ });
70
+ const close = () => {
71
+ finished = true;
72
+ clearTimeout(expiry);
73
+ server.close();
74
+ };
75
+ let expiry;
76
+ try {
77
+ publicResult = await beginDeviceLogin(runtime, env, {
78
+ ...options,
79
+ openBrowser: false,
80
+ binding: {
81
+ verifier,
82
+ challenge: createHash("sha256").update(verifier).digest("base64url"),
83
+ redirectUri: `http://127.0.0.1:${server.address().port}/callback`,
84
+ },
85
+ });
86
+ pending = await privateRead(join(runtime.directory, "connection-request.json"));
87
+ if (pending.id !== publicResult.id || pending.verifier !== verifier)
88
+ throw new Error("Another installer changed this request. Finish that installer, then retry.");
89
+ expiry = setTimeout(close, Math.max(1, Date.parse(publicResult.expiresAt) - Date.now()));
90
+ expiry.unref();
91
+ if (options.openBrowser !== false) {
92
+ const command =
93
+ process.platform === "darwin"
94
+ ? ["open", [publicResult.url]]
95
+ : process.platform === "win32"
96
+ ? ["rundll32.exe", ["url.dll,FileProtocolHandler", publicResult.url]]
97
+ : ["xdg-open", [publicResult.url]];
98
+ await (options.execute ?? promisify(execFile))(command[0], command[1], {
99
+ timeout: 5000,
100
+ }).catch(() => {});
101
+ }
102
+ return { ...publicResult, close, mode: "browser-bound" };
103
+ } catch (error) {
104
+ close();
105
+ throw error;
106
+ }
107
+ }