@ouro.bot/cli 0.1.0-alpha.1016 → 0.1.0-alpha.1018

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/changelog.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1018",
6
+ "changes": [
7
+ "Hatch and ouro vault create register vault accounts with Vaultwarden's current two-step flow (send-verification-email, then register/finish), falling back to the old /identity/accounts/register only on servers that lack it. When a server has signups closed, the error says to have its admin invite the agent's email.",
8
+ "OURO_VAULT_UNLOCK_STORE (for example plaintext-file on a headless appliance without secret-tool) picks the local vault unlock store for every ouro command when no --store is given. Hatch (interactive and --answers) and ouro vault create/replace/recover check for a usable unlock store before creating the vault account, so a missing store no longer leaves an orphaned account behind."
9
+ ]
10
+ },
11
+ {
12
+ "version": "0.1.0-alpha.1019",
13
+ "changes": [
14
+ "ouro hatch on a host with GH_TOKEN or GITHUB_TOKEN set: the github-copilot option it offers now looks up the account's Copilot endpoint first, so choosing it works instead of failing with 'no credentials configured'.",
15
+ "The hatchling vault unlock prompt during ouro hatch pauses the conversation view: the spinner stops, the prompt is visible, and what you type is hidden instead of being echoed into the chat input.",
16
+ "A failed complete_adoption no longer crashes ouro hatch with a JSON parse error: the guide explains the error and can retry, and quitting prints what went wrong."
17
+ ]
18
+ },
19
+ {
20
+ "version": "0.1.0-alpha.1021",
21
+ "changes": [
22
+ "A small host's install (npm config set omit optional) is now about 46 MB and 43 packages instead of 221 MB and 426: the bundled Bitwarden CLI and the terminal chat UI (ink, react) are optional packages too. Vault reads and writes are native, so bw is only fetched when a vault needs it, and without the chat UI ouro chats line by line. shell-quote, which the shell guardrails load, is now declared instead of arriving through ink, and a test keeps every runtime import declared. Native vault reads no longer need the access token to name the user (only writes do), and the edge benchmark's fake vault issues a real JWT, so it reads natively again."
23
+ ]
24
+ },
4
25
  {
5
26
  "version": "0.1.0-alpha.1016",
6
27
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1016",
2
+ "runtimeVersion": "0.1.0-alpha.1018",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1016</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1018</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -39,6 +39,7 @@ exports.storeProviderCredentials = storeProviderCredentials;
39
39
  exports.writeAgentModel = writeAgentModel;
40
40
  exports.readAccountPoolSettings = readAccountPoolSettings;
41
41
  exports.collectGithubCopilotPoolCredentials = collectGithubCopilotPoolCredentials;
42
+ exports.discoverGithubCopilotBaseUrl = discoverGithubCopilotBaseUrl;
42
43
  exports.collectRuntimeAuthCredentials = collectRuntimeAuthCredentials;
43
44
  exports.resolveHatchCredentials = resolveHatchCredentials;
44
45
  exports.runRuntimeAuthFlow = runRuntimeAuthFlow;
@@ -331,6 +332,21 @@ async function collectGithubCopilotPoolCredentials(input, settings, deps) {
331
332
  });
332
333
  return credentials;
333
334
  }
335
+ /** Ask GitHub which Copilot API endpoint serves this token's account (`endpoints.api`). */
336
+ async function discoverGithubCopilotBaseUrl(token, fetchImpl = fetch) {
337
+ const response = await fetchImpl("https://api.github.com/copilot_internal/user", {
338
+ headers: { Authorization: `Bearer ${token}` },
339
+ });
340
+ if (!response.ok) {
341
+ throw new Error(`GitHub Copilot endpoint discovery failed (HTTP ${response.status}). Ensure your GitHub account has Copilot access.`);
342
+ }
343
+ const body = await response.json();
344
+ const baseUrl = body?.endpoints?.api;
345
+ if (!baseUrl) {
346
+ throw new Error("GitHub Copilot endpoint discovery returned no endpoints.api. Ensure your GitHub account has Copilot access.");
347
+ }
348
+ return baseUrl;
349
+ }
334
350
  async function collectRuntimeAuthCredentials(input, deps) {
335
351
  const spawnSync = deps.spawnSync ?? child_process_1.spawnSync;
336
352
  const homeDir = deps.homeDir ?? os.homedir();
@@ -389,18 +405,7 @@ async function collectRuntimeAuthCredentials(input, deps) {
389
405
  }
390
406
  }
391
407
  writeAuthProgress(input, "checking GitHub Copilot access...");
392
- const response = await fetch("https://api.github.com/copilot_internal/user", {
393
- headers: { Authorization: `Bearer ${token}` },
394
- });
395
- if (!response.ok) {
396
- throw new Error(`GitHub Copilot endpoint discovery failed (HTTP ${response.status}). Ensure your GitHub account has Copilot access.`);
397
- }
398
- const body = await response.json();
399
- const baseUrl = body?.endpoints?.api;
400
- /* v8 ignore next -- defensive: valid response but missing endpoints field @preserve */
401
- if (!baseUrl) {
402
- throw new Error("GitHub Copilot endpoint discovery returned no endpoints.api. Ensure your GitHub account has Copilot access.");
403
- }
408
+ const baseUrl = await discoverGithubCopilotBaseUrl(token);
404
409
  return { githubToken: token, baseUrl };
405
410
  }
406
411
  if (input.provider === "openai-codex") {
@@ -591,7 +591,7 @@ async function defaultRunSerpentGuide() {
591
591
  });
592
592
  }
593
593
  // Scan environment variables for API keys using the shared helper
594
- const envCreds = (0, provider_discovery_1.scanEnvVarCredentials)(process.env);
594
+ const envCreds = await (0, provider_discovery_1.completeEnvDiscoveredCredentials)((0, provider_discovery_1.scanEnvVarCredentials)(process.env), (token) => (0, auth_flow_1.discoverGithubCopilotBaseUrl)(token));
595
595
  const envDiscovered = [];
596
596
  for (const cred of envCreds) {
597
597
  // Enrich with default model and first matching env var name (for display)
@@ -716,13 +716,17 @@ async function defaultRunSerpentGuide() {
716
716
  });
717
717
  // Build specialist tools
718
718
  const specialistTools = (0, specialist_tools_1.getSpecialistTools)();
719
+ let lastAdoptionError = null;
719
720
  const specialistExecTool = (0, specialist_tools_1.createSpecialistExecTool)({
720
721
  tempDir,
721
722
  credentials: selectedCredentialPayload,
722
723
  provider: providerRaw,
723
724
  bundlesRoot,
724
725
  animationWriter: (text) => process.stdout.write(text),
725
- promptSecret: defaultPromptSecret,
726
+ promptSecret: async (question) => {
727
+ const { withTerminalHandedOff } = await Promise.resolve().then(() => __importStar(require("../../senses/terminal-handoff")));
728
+ return withTerminalHandedOff(() => defaultPromptSecret(question));
729
+ },
726
730
  });
727
731
  // Run the serpent guide session via runCliSession
728
732
  const result = await runCliSession({
@@ -730,6 +734,12 @@ async function defaultRunSerpentGuide() {
730
734
  tools: specialistTools,
731
735
  execTool: specialistExecTool,
732
736
  exitOnToolCall: "complete_adoption",
737
+ // A failed adoption goes back to the guide, which explains it and can retry.
738
+ exitOnToolResult: (toolResult) => {
739
+ const outcome = (0, specialist_tools_1.parseAdoptionResult)(toolResult);
740
+ lastAdoptionError = outcome.ok ? null : outcome.error;
741
+ return outcome.ok;
742
+ },
733
743
  autoFirstTurn: true,
734
744
  banner: false,
735
745
  disableCommands: true,
@@ -740,10 +750,13 @@ async function defaultRunSerpentGuide() {
740
750
  ],
741
751
  });
742
752
  if (result.exitReason === "tool_exit" && result.toolResult) {
743
- const parsed = typeof result.toolResult === "string" ? JSON.parse(result.toolResult) : result.toolResult;
744
- if (parsed.success && parsed.agentName) {
745
- return parsed.agentName;
746
- }
753
+ const outcome = (0, specialist_tools_1.parseAdoptionResult)(result.toolResult);
754
+ if (outcome.ok)
755
+ return outcome.agentName;
756
+ lastAdoptionError = outcome.error;
757
+ }
758
+ if (lastAdoptionError) {
759
+ process.stdout.write(`\nhatch didn't finish: ${lastAdoptionError}\nfix that, then run \`ouro hatch\` again.\n`);
747
760
  }
748
761
  return null;
749
762
  }
@@ -1857,6 +1857,7 @@ function rejectGeneratedVaultUnlockSecret(action) {
1857
1857
  throw new Error(`vault ${action} no longer supports --generate-unlock-secret. Re-run without that flag and enter a human-chosen unlock secret; Ouro will not print vault unlock secrets.`);
1858
1858
  }
1859
1859
  async function createRepairVaultForAgent(input) {
1860
+ (0, vault_unlock_1.resolveVaultUnlockStore)({ agentName: input.agentName, email: input.email, serverUrl: input.serverUrl }, { homeDir: input.deps.homeDir, store: input.store });
1860
1861
  const result = await runCommandProgressPhase(input.progress, "creating vault account", () => (0, vault_setup_1.createVaultAccount)("Ouro credential vault", input.serverUrl, input.email, input.unlockSecret), (created) => created.success ? "created" : "failed");
1861
1862
  if (!result.success) {
1862
1863
  const message = [
@@ -1947,6 +1948,8 @@ async function executeVaultCreate(command, deps) {
1947
1948
  const email = command.email ?? config.vault?.email ?? configuredVault.email;
1948
1949
  const promptSecret = ensureVaultSecretPrompt(deps.promptSecret, "create", command.secretFile);
1949
1950
  const serverUrl = command.serverUrl ?? config.vault?.serverUrl ?? configuredVault.serverUrl;
1951
+ // Fail before creating the account when this machine has nowhere to keep the unlock secret.
1952
+ (0, vault_unlock_1.resolveVaultUnlockStore)({ agentName: command.agent, email, serverUrl }, { homeDir: deps.homeDir, store: command.store });
1950
1953
  const unlockSecret = await (0, vault_unlock_1.promptConfirmedVaultUnlockSecret)({
1951
1954
  promptSecret,
1952
1955
  question: `Choose Ouro vault unlock secret for ${email}: `,
@@ -8,6 +8,7 @@
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
10
  exports.scanEnvVarCredentials = scanEnvVarCredentials;
11
+ exports.completeEnvDiscoveredCredentials = completeEnvDiscoveredCredentials;
11
12
  exports.discoverInstalledAgentCredentials = discoverInstalledAgentCredentials;
12
13
  exports.describeDiscoveredCredentialSource = describeDiscoveredCredentialSource;
13
14
  exports.discoverWorkingProvider = discoverWorkingProvider;
@@ -40,6 +41,39 @@ function scanEnvVarCredentials(env) {
40
41
  }
41
42
  return results;
42
43
  }
44
+ /**
45
+ * Env-discovered GitHub Copilot credentials carry only a token; the runtime also needs the
46
+ * account's Copilot API endpoint. Fill it in the way `ouro auth` does, and drop the option
47
+ * when discovery fails, because offering it would only fail its ping.
48
+ */
49
+ async function completeEnvDiscoveredCredentials(credentials, discoverCopilotBaseUrl) {
50
+ const completed = [];
51
+ for (const credential of credentials) {
52
+ const token = credential.credentials.githubToken;
53
+ if (credential.provider !== "github-copilot" || !token || credential.providerConfig.baseUrl) {
54
+ completed.push(credential);
55
+ continue;
56
+ }
57
+ try {
58
+ const baseUrl = await discoverCopilotBaseUrl(token);
59
+ completed.push({
60
+ ...credential,
61
+ credentials: { ...credential.credentials, baseUrl },
62
+ providerConfig: { ...credential.providerConfig, baseUrl },
63
+ });
64
+ }
65
+ catch (error) {
66
+ (0, runtime_1.emitNervesEvent)({
67
+ level: "warn",
68
+ component: "daemon",
69
+ event: "daemon.env_copilot_endpoint_discovery_failed",
70
+ message: "skipping env github-copilot credential: endpoint discovery failed",
71
+ meta: { reason: error instanceof Error ? error.message : String(error) },
72
+ });
73
+ }
74
+ }
75
+ return completed;
76
+ }
43
77
  function stringifyProviderFields(fields) {
44
78
  const result = {};
45
79
  for (const [key, value] of Object.entries(fields)) {
@@ -51,7 +51,9 @@ const hatch_specialist_1 = require("./hatch-specialist");
51
51
  async function createHatchlingVault(agentName, unlockSecret) {
52
52
  const vault = (0, identity_1.resolveVaultConfig)(agentName);
53
53
  const { createVaultAccount } = await Promise.resolve().then(() => __importStar(require("../../repertoire/vault-setup")));
54
- const { storeVaultUnlockSecret } = await Promise.resolve().then(() => __importStar(require("../../repertoire/vault-unlock")));
54
+ const { resolveVaultUnlockStore, storeVaultUnlockSecret } = await Promise.resolve().then(() => __importStar(require("../../repertoire/vault-unlock")));
55
+ // Fail before creating the account when this machine has nowhere to keep the unlock secret.
56
+ resolveVaultUnlockStore({ agentName, email: vault.email, serverUrl: vault.serverUrl });
55
57
  const created = await createVaultAccount(agentName, vault.serverUrl, vault.email, unlockSecret);
56
58
  if (!created.success)
57
59
  throw new Error(`failed to create the vault for ${agentName}: ${created.error}`);
@@ -95,6 +95,7 @@ function buildSpecialistSystemPrompt(soulText, identityText, existingBundles, co
95
95
  "- `complete_adoption`: Finalize the bundle. Validates, asks the harness to collect and confirm the hatchling vault unlock secret through hidden terminal prompts, scaffolds structural dirs, moves to ~/AgentBundles/, writes secrets, plays hatch animation. I call this with `name` (PascalCase) and `handoff_message` (warm message for the human).",
96
96
  "- The complete_adoption tool triggers hidden terminal prompts for the hatchling vault unlock secret. I must never ask the human to type the vault unlock secret into chat, and I must never include it in tool arguments.",
97
97
  "- `settle`: End the conversation with a final message. I call this after complete_adoption succeeds.",
98
+ "- If complete_adoption returns `error: ...`, the hatch did not finish. I tell the human in plain words what went wrong and what they can do about it, without asking for any secret in chat. The bundle files are back in the temp directory, so once the problem is fixed I can call complete_adoption again.",
98
99
  "",
99
100
  "I must call `settle` when I am done to end the session cleanly.",
100
101
  ].join("\n"));
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.getSpecialistTools = getSpecialistTools;
37
+ exports.parseAdoptionResult = parseAdoptionResult;
37
38
  exports.createSpecialistExecTool = createSpecialistExecTool;
38
39
  const fs = __importStar(require("fs"));
39
40
  const path = __importStar(require("path"));
@@ -181,6 +182,14 @@ async function execCompleteAdoption(args, deps) {
181
182
  return "error: complete_adoption requires an interactive vault unlock secret prompt. Re-run `ouro hatch` in a terminal so the human can enter a hatchling vault unlock secret without echoing it.";
182
183
  }
183
184
  const vault = (0, identity_1.resolveVaultConfig)(name);
185
+ // Resolve the local unlock store before creating the vault account, so a machine without one
186
+ // fails here instead of leaving an orphaned account that a re-run can't register again.
187
+ try {
188
+ (0, vault_unlock_1.resolveVaultUnlockStore)({ agentName: name, email: vault.email, serverUrl: vault.serverUrl });
189
+ }
190
+ catch (error) {
191
+ return `error: no local store for the vault unlock secret, so no vault was created. ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
192
+ }
184
193
  let vaultUnlockSecret;
185
194
  try {
186
195
  vaultUnlockSecret = await (0, vault_unlock_1.promptConfirmedVaultUnlockSecret)({
@@ -209,9 +218,9 @@ async function execCompleteAdoption(args, deps) {
209
218
  await (0, hatch_flow_1.storeHatchlingProviderCredentials)(name, deps.provider, deps.credentials);
210
219
  }
211
220
  catch (e) {
212
- // Rollback: remove the moved bundle
221
+ // Rollback: put the files back in the temp directory so the guide can retry after a fix
213
222
  try {
214
- fs.rmSync(targetBundle, { recursive: true, force: true });
223
+ moveDir(targetBundle, deps.tempDir);
215
224
  }
216
225
  catch {
217
226
  // Best effort cleanup
@@ -260,6 +269,42 @@ async function execCompleteAdoption(args, deps) {
260
269
  });
261
270
  return JSON.stringify({ success: true, agentName: name, bundlePath: targetBundle });
262
271
  }
272
+ /**
273
+ * Read a complete_adoption result. Success is JSON; failures are plain `error: ...` text,
274
+ * which must reach the human as a failed adoption rather than a JSON parse crash.
275
+ */
276
+ function parseAdoptionResult(toolResult) {
277
+ let parsed = toolResult;
278
+ if (typeof toolResult === "string") {
279
+ try {
280
+ parsed = JSON.parse(toolResult);
281
+ }
282
+ catch {
283
+ const error = toolResult.trim().replace(/^error:\s*/i, "") || "complete_adoption returned nothing";
284
+ (0, runtime_1.emitNervesEvent)({
285
+ level: "warn",
286
+ component: "daemon",
287
+ event: "daemon.adoption_failed",
288
+ message: "complete_adoption reported a failure",
289
+ meta: { error },
290
+ });
291
+ return { ok: false, error };
292
+ }
293
+ }
294
+ const record = (parsed && typeof parsed === "object" ? parsed : {});
295
+ if (record.success === true && typeof record.agentName === "string" && record.agentName) {
296
+ return { ok: true, agentName: record.agentName };
297
+ }
298
+ const error = typeof record.error === "string" && record.error ? record.error : "complete_adoption did not report success";
299
+ (0, runtime_1.emitNervesEvent)({
300
+ level: "warn",
301
+ component: "daemon",
302
+ event: "daemon.adoption_failed",
303
+ message: "complete_adoption reported a failure",
304
+ meta: { error },
305
+ });
306
+ return { ok: false, error };
307
+ }
263
308
  /**
264
309
  * Create a specialist tool executor with the given dependencies captured in closure.
265
310
  */
@@ -6,20 +6,26 @@ exports.importOptional = importOptional;
6
6
  exports.describeStartupError = describeStartupError;
7
7
  const runtime_1 = require("../nerves/runtime");
8
8
  /**
9
- * Product SDKs listed in package.json optionalDependencies. npm installs them by default; a small
10
- * host can leave them out with `npm install --omit=optional` (about 97 MB and 138 packages), and
11
- * only the feature that needs one stops working.
9
+ * Packages listed in package.json optionalDependencies: the product SDKs, the terminal chat UI
10
+ * (ink and react; without them `ouro` chats line by line) and the bundled Bitwarden CLI (vault
11
+ * reads and writes are native; bw is only for vaults the native client does not support, and is
12
+ * then found on PATH or installed). npm installs them by default; a small host can leave them out
13
+ * with `npm install --omit=optional` (about 46 MB instead of 221 MB), and only the feature that
14
+ * needs one stops working.
12
15
  */
13
16
  exports.OPTIONAL_PACKAGES = [
14
17
  "@azure/identity",
15
18
  "@azure/storage-blob",
19
+ "@bitwarden/cli",
16
20
  "@microsoft/teams.api",
17
21
  "@microsoft/teams.apps",
18
22
  "@microsoft/teams.cards",
19
23
  "@microsoft/teams.common",
20
24
  "@microsoft/teams.dev",
21
25
  "@microsoft/teams.graph",
26
+ "ink",
22
27
  "mailparser",
28
+ "react",
23
29
  "smtp-server",
24
30
  "stripe",
25
31
  ];
@@ -276,6 +276,8 @@ class NativeVaultReader {
276
276
  meta: { email: this.email, update: existingId !== undefined },
277
277
  });
278
278
  const answer = await this.withSession(async (session) => {
279
+ if (!session.userId)
280
+ throw new NativeVaultUnsupportedError("writes with an access token that names no user");
279
281
  const itemKeyString = existing ? stringField(existing, "key") : undefined;
280
282
  const key = itemKeyString ? decryptKey(itemKeyString, session.userKey, "item key") : session.userKey;
281
283
  const login = field(existing, "login");
@@ -379,8 +381,6 @@ class NativeVaultReader {
379
381
  const expiresIn = Number(field(token, "expires_in"));
380
382
  const userKey = decryptKey(protectedKey, keys.stretched, "user key");
381
383
  const userId = tokenUserId(accessToken);
382
- if (!userId)
383
- throw new NativeVaultUnsupportedError("an access token without a user id");
384
384
  this.session = { accessToken, expiresAt: this.deps.now() + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600) * 1000, userKey, userId };
385
385
  return this.session;
386
386
  }
@@ -161,7 +161,71 @@ function generateRsaKeypair() {
161
161
  // ---------------------------------------------------------------------------
162
162
  const KDF_PBKDF2 = 0;
163
163
  const KDF_ITERATIONS = 600000;
164
- const REGISTER_ACCOUNT_PATH = "/identity/accounts/register";
164
+ const SEND_VERIFICATION_EMAIL_PATH = "/identity/accounts/register/send-verification-email";
165
+ const REGISTER_FINISH_PATH = "/identity/accounts/register/finish";
166
+ const LEGACY_REGISTER_ACCOUNT_PATH = "/identity/accounts/register";
167
+ const JSON_HEADERS = { "Content-Type": "application/json", Accept: "application/json" };
168
+ async function postJson(url, body) {
169
+ return fetch(url, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) });
170
+ }
171
+ async function readErrorDetail(res) {
172
+ try {
173
+ const body = await res.json();
174
+ return body.message ?? `HTTP ${res.status} ${res.statusText}`;
175
+ }
176
+ catch {
177
+ return `HTTP ${res.status} ${res.statusText}`;
178
+ }
179
+ }
180
+ function describeRegistrationFailure(detail, url, email) {
181
+ if (/registration not allowed/i.test(detail)) {
182
+ return `the vault server doesn't allow signups for ${email}; ask its admin to invite it (Vaultwarden admin → Invite User), then re-run. (${detail} from ${url})`;
183
+ }
184
+ return `${detail} from ${url}. Check --server; Ouro expects a Bitwarden/Vaultwarden identity API.`;
185
+ }
186
+ /** Vaultwarden returns the token as a JSON string when asked for JSON, or as plain text otherwise. */
187
+ async function readVerificationToken(res) {
188
+ const text = (await res.text()).trim();
189
+ try {
190
+ const parsed = JSON.parse(text);
191
+ return typeof parsed === "string" ? parsed : "";
192
+ }
193
+ catch {
194
+ return text;
195
+ }
196
+ }
197
+ /**
198
+ * Current Bitwarden/Vaultwarden registration: request a verification token, then finish
199
+ * registration with it. Servers that predate this flow (404 on send-verification-email)
200
+ * get the legacy single-step `/identity/accounts/register`.
201
+ */
202
+ async function registerAccount(serverUrl, agentName, email, payload) {
203
+ const verifyUrl = `${serverUrl}${SEND_VERIFICATION_EMAIL_PATH}`;
204
+ const verifyRes = await postJson(verifyUrl, { email, name: agentName, receiveMarketingEmails: false });
205
+ if (verifyRes.status === 404) {
206
+ const legacyUrl = `${serverUrl}${LEGACY_REGISTER_ACCOUNT_PATH}`;
207
+ const legacyRes = await postJson(legacyUrl, payload);
208
+ if (!legacyRes.ok)
209
+ return { ok: false, url: legacyUrl, error: describeRegistrationFailure(await readErrorDetail(legacyRes), legacyUrl, email) };
210
+ return { ok: true, url: legacyUrl };
211
+ }
212
+ if (!verifyRes.ok) {
213
+ return { ok: false, url: verifyUrl, error: describeRegistrationFailure(await readErrorDetail(verifyRes), verifyUrl, email) };
214
+ }
215
+ const token = verifyRes.status === 204 ? "" : await readVerificationToken(verifyRes);
216
+ if (!token) {
217
+ return {
218
+ ok: false,
219
+ url: verifyUrl,
220
+ error: `the vault server at ${serverUrl} requires email verification for new accounts and sent a link to ${email}; Ouro can't finish that unattended. Ask its admin to create or invite the account with verification off, or finish signup from that email, then re-run.`,
221
+ };
222
+ }
223
+ const finishUrl = `${serverUrl}${REGISTER_FINISH_PATH}`;
224
+ const finishRes = await postJson(finishUrl, { ...payload, emailVerificationToken: token });
225
+ if (!finishRes.ok)
226
+ return { ok: false, url: finishUrl, error: describeRegistrationFailure(await readErrorDetail(finishRes), finishUrl, email) };
227
+ return { ok: true, url: finishUrl };
228
+ }
165
229
  /**
166
230
  * Create a Bitwarden account on the configured Vaultwarden server.
167
231
  * Uses the Bitwarden registration API with standard KDF implementation.
@@ -184,35 +248,23 @@ async function createVaultAccount(agentName, serverUrl, email, masterPassword) {
184
248
  // Step 3: Generate RSA keypair, encrypt private key with the symmetric key
185
249
  const { publicKeyB64, privateKeyDer } = generateRsaKeypair();
186
250
  const encryptedPrivateKey = encryptWithStretchedKey(privateKeyDer, symKey);
187
- // Step 4: POST registration
188
- const registrationUrl = `${serverUrl}${REGISTER_ACCOUNT_PATH}`;
189
- const res = await fetch(registrationUrl, {
190
- method: "POST",
191
- headers: { "Content-Type": "application/json" },
192
- body: JSON.stringify({
193
- name: agentName,
194
- email,
195
- masterPasswordHash,
196
- masterPasswordHint: null,
197
- key: protectedSymKey,
198
- kdf: KDF_PBKDF2,
199
- kdfIterations: KDF_ITERATIONS,
200
- keys: {
201
- publicKey: publicKeyB64,
202
- encryptedPrivateKey,
203
- },
204
- }),
251
+ // Step 4: Register
252
+ const step = await registerAccount(serverUrl, agentName, email, {
253
+ name: agentName,
254
+ email,
255
+ masterPasswordHash,
256
+ masterPasswordHint: null,
257
+ key: protectedSymKey,
258
+ kdf: KDF_PBKDF2,
259
+ kdfIterations: KDF_ITERATIONS,
260
+ keys: {
261
+ publicKey: publicKeyB64,
262
+ encryptedPrivateKey,
263
+ },
205
264
  });
206
- if (!res.ok) {
207
- let errorDetail;
208
- try {
209
- const body = await res.json();
210
- errorDetail = body.message ?? `HTTP ${res.status} ${res.statusText}`;
211
- }
212
- catch {
213
- errorDetail = `HTTP ${res.status} ${res.statusText}`;
214
- }
215
- const endpointAwareError = `${errorDetail} from ${registrationUrl}. Check --server; Ouro expects a Bitwarden/Vaultwarden identity API.`;
265
+ if (!step.ok) {
266
+ const endpointAwareError = step.error;
267
+ const registrationUrl = step.url;
216
268
  (0, runtime_1.emitNervesEvent)({
217
269
  level: "error",
218
270
  event: "repertoire.vault_setup_error",
@@ -232,7 +284,7 @@ async function createVaultAccount(agentName, serverUrl, email, masterPassword) {
232
284
  }
233
285
  catch (err) {
234
286
  const reason = err instanceof Error ? err.message : String(err);
235
- const registrationUrl = `${serverUrl}${REGISTER_ACCOUNT_PATH}`;
287
+ const registrationUrl = `${serverUrl}${SEND_VERIFICATION_EMAIL_PATH}`;
236
288
  const endpointAwareError = `cannot reach vault registration endpoint ${registrationUrl}: ${reason}. Check network, DNS/TLS, and --server.`;
237
289
  (0, runtime_1.emitNervesEvent)({
238
290
  level: "error",
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.VAULT_UNLOCK_STORE_ENV = void 0;
36
37
  exports.vaultUnlockReplaceRecoverFix = vaultUnlockReplaceRecoverFix;
37
38
  exports.credentialVaultNotConfiguredError = credentialVaultNotConfiguredError;
38
39
  exports.isCredentialVaultNotConfiguredError = isCredentialVaultNotConfiguredError;
@@ -55,6 +56,8 @@ const os = __importStar(require("node:os"));
55
56
  const path = __importStar(require("node:path"));
56
57
  const runtime_1 = require("../nerves/runtime");
57
58
  const identity_1 = require("../heart/identity");
59
+ /** Machine-level unlock store choice used when no explicit `--store` is given. */
60
+ exports.VAULT_UNLOCK_STORE_ENV = "OURO_VAULT_UNLOCK_STORE";
58
61
  const VAULT_UNLOCK_SERVICE = "ouro.vault";
59
62
  const CREDENTIAL_VAULT_NOT_CONFIGURED_PREFIX = "credential vault is not configured in ";
60
63
  const PLAINTEXT_UNLOCK_DIR = path.join(".ouro-cli", "vault-unlock");
@@ -121,6 +124,7 @@ function missingSecureStoreMessage(config) {
121
124
  "On macOS, Ouro uses Keychain automatically.",
122
125
  "On Windows, Ouro uses a CurrentUser DPAPI-encrypted local file automatically.",
123
126
  "On Linux/WSL, install and configure Secret Service/libsecret, or choose the explicit plaintext fallback on a trusted machine.",
127
+ `On a headless appliance, set ${exports.VAULT_UNLOCK_STORE_ENV}=plaintext-file for the ouro service and every ouro command (hatch, vault, up) so they all use the plaintext fallback.`,
124
128
  "",
125
129
  config.agentName
126
130
  ? `Run \`ouro vault unlock --agent ${config.agentName} --store plaintext-file\` to store the vault unlock secret in a chmod 0600 local file.`
@@ -197,16 +201,26 @@ function lockedMessage(config, store) {
197
201
  lostUnlockSecretGuidance(config),
198
202
  ].join("\n");
199
203
  }
200
- function validateStoreKind(store) {
201
- const requested = store ?? "auto";
204
+ function validateStoreKind(requested) {
202
205
  if (!SUPPORTED_STORES.includes(requested)) {
203
206
  throw new Error(`unknown vault unlock store '${requested}'. Use auto|macos-keychain|windows-dpapi|linux-secret-service|plaintext-file.`);
204
207
  }
205
208
  return requested;
206
209
  }
210
+ function requestedStoreKind(deps) {
211
+ if (deps.store !== undefined)
212
+ return validateStoreKind(deps.store);
213
+ const fromEnv = (deps.env ?? process.env)[exports.VAULT_UNLOCK_STORE_ENV]?.trim();
214
+ if (!fromEnv)
215
+ return "auto";
216
+ if (!SUPPORTED_STORES.includes(fromEnv)) {
217
+ throw new Error(`${exports.VAULT_UNLOCK_STORE_ENV}='${fromEnv}' is not a vault unlock store. Use auto|macos-keychain|windows-dpapi|linux-secret-service|plaintext-file.`);
218
+ }
219
+ return fromEnv;
220
+ }
207
221
  function resolveVaultUnlockStore(config, deps = {}) {
208
222
  const canonicalConfig = canonicalizeVaultUnlockConfig(config);
209
- const requested = validateStoreKind(deps.store);
223
+ const requested = requestedStoreKind(deps);
210
224
  const currentPlatform = platform(deps);
211
225
  if (requested === "macos-keychain") {
212
226
  if (currentPlatform !== "darwin") {
@@ -522,7 +536,7 @@ function deleteFromStoreExact(config, store, deps) {
522
536
  return deleteFromPlaintextFileExact(config, deps);
523
537
  }
524
538
  function readFromAutoPlaintextFallback(config, deps) {
525
- if (deps.store !== undefined && deps.store !== "auto")
539
+ if (requestedStoreKind(deps) !== "auto")
526
540
  return null;
527
541
  const store = resolveVaultUnlockStore(config, { ...deps, store: "plaintext-file" });
528
542
  const loaded = readFromStore(config, store, deps);
@@ -597,11 +597,11 @@ function InputArea({ onSubmit, onCtrlC, history, queuedInputs, onPopQueue, agent
597
597
  })() }) })), (0, jsx_runtime_1.jsx)(ink_1.Text, { dimColor: true, children: "─".repeat(termWidth()) }), (0, jsx_runtime_1.jsxs)(ink_1.Box, { children: [(0, jsx_runtime_1.jsxs)(ink_1.Text, { dimColor: true, children: [" ", agentName, model ? ` · ${model}` : "", " \u00B7 /help"] }), (0, jsx_runtime_1.jsx)(ink_1.Box, { flexGrow: 1 }), tooltip ? (0, jsx_runtime_1.jsx)(ink_1.Text, { dimColor: true, children: tooltip }) : (0, jsx_runtime_1.jsx)(ink_1.Text, { dimColor: true, children: "opt+enter for newline" })] })] }));
598
598
  }
599
599
  // ─── Main TUI Component ─────────────────────────────────────────────
600
- function OuroTui({ agentName, model, completedMessages, inputHistory, queuedInputs, live, elapsedSeconds, contextPercent, onSubmit, onCtrlC, onPopQueue, cwd, resumeInfo, onImageMap, onHistoryAdd, }) {
600
+ function OuroTui({ agentName, model, completedMessages, inputHistory, queuedInputs, live, elapsedSeconds, contextPercent, onSubmit, onCtrlC, onPopQueue, cwd, resumeInfo, onImageMap, onHistoryAdd, paused, }) {
601
601
  return ((0, jsx_runtime_1.jsxs)(ink_1.Box, { flexDirection: "column", children: [(0, jsx_runtime_1.jsx)(ink_1.Static, { items: [{ id: "__header__" }, ...completedMessages], children: (item, index) => {
602
602
  if (index === 0) {
603
603
  return ((0, jsx_runtime_1.jsxs)(ink_1.Box, { flexDirection: "column", marginBottom: 2, children: [(0, jsx_runtime_1.jsx)(ink_1.Box, { marginTop: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { children: "" }) }), (0, jsx_runtime_1.jsx)(Header, { agentName: agentName, model: model, contextPercent: contextPercent, cwd: cwd, resumeInfo: resumeInfo }), (0, jsx_runtime_1.jsx)(ink_1.Text, { color: OURO.shadow, dimColor: true, children: " Ctrl-C twice to exit \u00b7 \u2191\u2193 history \u00b7 Esc clear \u00b7 opt+Enter newline" })] }, "header"));
604
604
  }
605
605
  return (0, jsx_runtime_1.jsx)(MessageBlock, { msg: item }, item.id);
606
- } }), (live.loading || live.streamingText || live.activeTool) ? (0, jsx_runtime_1.jsx)(ink_1.Box, { marginTop: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { children: "" }) }) : null, (0, jsx_runtime_1.jsx)(LiveArea, { live: live, elapsed: elapsedSeconds }), (live.loading || live.streamingText || live.activeTool) ? (0, jsx_runtime_1.jsx)(ink_1.Box, { marginBottom: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { children: "" }) }) : null, queuedInputs.length > 0 ? (0, jsx_runtime_1.jsx)(QueuedMessages, { items: queuedInputs }) : null, (0, jsx_runtime_1.jsx)(ink_1.Box, { marginTop: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { children: "" }) }), (0, jsx_runtime_1.jsx)(InputArea, { onSubmit: onSubmit, onCtrlC: onCtrlC, history: inputHistory, queuedInputs: queuedInputs, onPopQueue: onPopQueue, agentName: agentName, model: model, onImageMap: onImageMap, onHistoryAdd: onHistoryAdd })] }));
606
+ } }), paused ? null : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(live.loading || live.streamingText || live.activeTool) ? (0, jsx_runtime_1.jsx)(ink_1.Box, { marginTop: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { children: "" }) }) : null, (0, jsx_runtime_1.jsx)(LiveArea, { live: live, elapsed: elapsedSeconds }), (live.loading || live.streamingText || live.activeTool) ? (0, jsx_runtime_1.jsx)(ink_1.Box, { marginBottom: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { children: "" }) }) : null, queuedInputs.length > 0 ? (0, jsx_runtime_1.jsx)(QueuedMessages, { items: queuedInputs }) : null, (0, jsx_runtime_1.jsx)(ink_1.Box, { marginTop: 1, children: (0, jsx_runtime_1.jsx)(ink_1.Text, { children: "" }) }), (0, jsx_runtime_1.jsx)(InputArea, { onSubmit: onSubmit, onCtrlC: onCtrlC, history: inputHistory, queuedInputs: queuedInputs, onPopQueue: onPopQueue, agentName: agentName, model: model, onImageMap: onImageMap, onHistoryAdd: onHistoryAdd })] }))] }));
607
607
  }
@@ -33,11 +33,14 @@ class TuiStore {
33
33
  _headerShown = false;
34
34
  _inputHistory = [];
35
35
  _queuedInputs = [];
36
+ _paused = false;
36
37
  get completedMessages() { return this._completed; }
37
38
  get live() { return this._live; }
38
39
  get headerShown() { return this._headerShown; }
39
40
  get inputHistory() { return this._inputHistory; }
40
41
  get queuedInputs() { return this._queuedInputs; }
42
+ /** True while a hidden terminal prompt has the terminal (no live area, no input box). */
43
+ get paused() { return this._paused; }
41
44
  /** Elapsed seconds since spinner started — computed on demand, not stored */
42
45
  getElapsed() {
43
46
  if (this._live.loading && this._spinnerStart > 0) {
@@ -128,6 +131,14 @@ class TuiStore {
128
131
  this._live = { ...this._live, loading: false, kickMessage: (0, format_1.formatKick)() };
129
132
  this.notify();
130
133
  }
134
+ pause() {
135
+ this._paused = true;
136
+ this.notify();
137
+ }
138
+ resume() {
139
+ this._paused = false;
140
+ this.notify();
141
+ }
131
142
  suppressInput() {
132
143
  this._live = { ...this._live, inputSuppressed: true };
133
144
  this.notify();