@ouro.bot/cli 0.1.0-alpha.1021 → 0.1.0-alpha.1023

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,33 @@
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.1023",
6
+ "changes": [
7
+ "Habits run again. The private runtime policy allows a habit wake that carries verified daemon provenance (habit, matching habit-trigger and habit-occurrence refs, and the habit scheduler, habit.poke or habit.probe as source), where before every habit fire was denied as default policy deny. A denied private-turn decision no longer reserves its idempotency key, so a habit whose first attempt was denied, and then retried after a provider credential revision change, runs on its next fire instead of failing forever with idempotency-key fingerprint mismatch."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1020",
12
+ "changes": [
13
+ "Images that MCP tools return (for example a plugin's screenshot tool) now reach the model: vision models get them in a message right after the step's tool results, and other models get a note that images were left out. GitHub Copilot requests that carry images send the Copilot-Vision-Request header, and the Anthropic provider sends base64 images as image blocks."
14
+ ]
15
+ },
16
+ {
17
+ "version": "0.1.0-alpha.1018",
18
+ "changes": [
19
+ "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.",
20
+ "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."
21
+ ]
22
+ },
23
+ {
24
+ "version": "0.1.0-alpha.1019",
25
+ "changes": [
26
+ "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'.",
27
+ "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.",
28
+ "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."
29
+ ]
30
+ },
4
31
  {
5
32
  "version": "0.1.0-alpha.1021",
6
33
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1021",
2
+ "runtimeVersion": "0.1.0-alpha.1023",
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.1021</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1023</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") {
@@ -25,6 +25,7 @@ const source_grounding_1 = require("./source-grounding");
25
25
  const shelf_claims_1 = require("./shelf-claims");
26
26
  const reply_style_1 = require("./reply-style");
27
27
  const tools_1 = require("../repertoire/tools");
28
+ const tool_images_1 = require("./tool-images");
28
29
  const tool_arguments_1 = require("../repertoire/tool-arguments");
29
30
  const session_events_1 = require("./session-events");
30
31
  const tool_approval_1 = require("./tool-approval");
@@ -2354,6 +2355,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2354
2355
  }
2355
2356
  await streamCallbackBuffer?.flush();
2356
2357
  pushGenerated(msg);
2358
+ const batchToolImages = [];
2357
2359
  // Every pre-dispatch gate accepted the complete batch.
2358
2360
  for (const tc of result.toolCalls) {
2359
2361
  if (signal?.aborted)
@@ -2587,16 +2589,20 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2587
2589
  let toolResult;
2588
2590
  let success;
2589
2591
  let invoked = false;
2592
+ const toolImages = [];
2593
+ const withToolImageSink = (context) => context
2594
+ ? { ...context, attachToolImages: (images) => { toolImages.push(...images); } }
2595
+ : context;
2590
2596
  try {
2591
2597
  const routineActionSelection = approvalCalls.find((entry) => entry.call.id === tc.id)?.routineActionSelection;
2592
2598
  const executionToolContext = routineActionSelection && augmentedToolContext ? { ...augmentedToolContext, routineActionSelection } : augmentedToolContext;
2593
2599
  if (options?.execTool && !relationship) {
2594
2600
  invoked = true;
2595
- toolResult = await options.execTool(tc.name, args, trustedToolContext);
2601
+ toolResult = await options.execTool(tc.name, args, withToolImageSink(trustedToolContext));
2596
2602
  success = true;
2597
2603
  }
2598
2604
  else {
2599
- const execution = await (0, tools_1.executeTool)(tc.name, args, executionToolContext, options?.execTool);
2605
+ const execution = await (0, tools_1.executeTool)(tc.name, args, withToolImageSink(executionToolContext), options?.execTool);
2600
2606
  invoked = execution.kind !== "rejected_before_handler";
2601
2607
  success = execution.kind === "handler_succeeded";
2602
2608
  toolResult = "error" in execution ? `error: ${execution.error}` : execution.text;
@@ -2606,6 +2612,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2606
2612
  toolResult = `error: ${e}`;
2607
2613
  success = false;
2608
2614
  }
2615
+ if (success && toolImages.length > 0) {
2616
+ const visible = (0, tool_images_1.canModelSeeToolImages)(providerRuntime.model);
2617
+ toolResult = `${toolResult}${toolResult ? "\n\n" : ""}${(0, tool_images_1.toolImagesNote)(toolImages.length, providerRuntime.model, visible)}`;
2618
+ if (visible)
2619
+ batchToolImages.push({ toolName: tc.name, callId: tc.id, images: toolImages });
2620
+ }
2609
2621
  if (invoked && requiredToolCallNames.includes(tc.name) && !options?.requiredToolCalls?.requireSuccessfulResults)
2610
2622
  dispatchedRequiredToolCalls.add(tc.name);
2611
2623
  turnToolRecords.push({ name: tc.name, args, result: toolResult });
@@ -2646,6 +2658,11 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2646
2658
  callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, modelResult, success, toolSelection), success);
2647
2659
  callbacks.onToolResult?.(messages);
2648
2660
  }
2661
+ if (batchToolImages.length > 0 && !signal?.aborted) {
2662
+ pushGenerated((0, tool_images_1.buildToolImagesMessage)(batchToolImages));
2663
+ // Responses-API providers keep native input; rebuild it so the images reach the next call.
2664
+ providerRuntime.resetTurnState(messages);
2665
+ }
2649
2666
  }
2650
2667
  }
2651
2668
  catch (e) {
@@ -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
  */
@@ -180,34 +180,25 @@ function recordPrivateTurnDecision(decision, deps = {}) {
180
180
  };
181
181
  try {
182
182
  const matchingRows = readRows(ledgerPath).filter((row) => row.idempotencyKey === candidate.idempotencyKey);
183
- const anchor = matchingRows[0];
184
- if (anchor) {
185
- if (anchor.requestFingerprint !== candidate.requestFingerprint) {
186
- const mismatch = mismatchDecision(candidate, anchor);
187
- const writtenMismatch = writeRow(ledgerPath, mismatch);
188
- emitDecisionRecorded(deps, { level: "warn", decision: writtenMismatch });
189
- return writtenMismatch;
190
- }
191
- const priorExecutable = matchingRows.find((row) => row.requestFingerprint === candidate.requestFingerprint && row.executable);
192
- if (priorExecutable && candidate.executable) {
193
- return duplicateDecision(priorExecutable);
194
- }
195
- const latestSameFingerprint = [...matchingRows].reverse().find((row) => row.requestFingerprint === candidate.requestFingerprint);
196
- if (latestSameFingerprint
197
- && latestSameFingerprint.result === candidate.result
198
- && latestSameFingerprint.executable === candidate.executable
199
- && latestSameFingerprint.deniedReason === candidate.deniedReason
200
- && latestSameFingerprint.denialCode === candidate.denialCode) {
201
- return latestSameFingerprint;
202
- }
203
- if (priorExecutable && !candidate.executable) {
204
- const written = writeRow(ledgerPath, candidate);
205
- emitDecisionRecorded(deps, { level: "warn", decision: written });
206
- return written;
207
- }
208
- const written = writeRow(ledgerPath, candidate);
209
- emitDecisionRecorded(deps, { level: written.result === "allow" ? "info" : "warn", decision: written });
210
- return written;
183
+ // Only an executable allow reserves a key. A deny spent nothing, so a later request under the
184
+ // same key (for example after a provider credential revision change) is evaluated afresh.
185
+ const anchor = matchingRows.find((row) => row.executable);
186
+ if (anchor && anchor.requestFingerprint !== candidate.requestFingerprint) {
187
+ const mismatch = mismatchDecision(candidate, anchor);
188
+ const writtenMismatch = writeRow(ledgerPath, mismatch);
189
+ emitDecisionRecorded(deps, { level: "warn", decision: writtenMismatch });
190
+ return writtenMismatch;
191
+ }
192
+ if (anchor && candidate.executable) {
193
+ return duplicateDecision(anchor);
194
+ }
195
+ const latestSameFingerprint = [...matchingRows].reverse().find((row) => row.requestFingerprint === candidate.requestFingerprint);
196
+ if (latestSameFingerprint
197
+ && latestSameFingerprint.result === candidate.result
198
+ && latestSameFingerprint.executable === candidate.executable
199
+ && latestSameFingerprint.deniedReason === candidate.deniedReason
200
+ && latestSameFingerprint.denialCode === candidate.denialCode) {
201
+ return latestSameFingerprint;
211
202
  }
212
203
  const written = writeRow(ledgerPath, candidate);
213
204
  emitDecisionRecorded(deps, { level: written.result === "allow" ? "info" : "warn", decision: written });
@@ -184,6 +184,19 @@ async function evaluatePolicy(request, context, deps) {
184
184
  reason: "verified daemon await check",
185
185
  };
186
186
  }
187
+ const habitTrigger = request.triggerSource.startsWith("habit-") ? request.triggerSource.slice("habit-".length) : "";
188
+ if (habitTrigger.length > 0
189
+ && hasNonEmptyOriginRef(originRefs, "habit")
190
+ && hasOriginRef(originRefs, "habit-trigger", habitTrigger)
191
+ && hasNonEmptyOriginRef(originRefs, "habit-occurrence")
192
+ && (hasOriginRef(originRefs, "daemon-entry", "habit-scheduler")
193
+ || hasOriginRef(originRefs, "daemon-command", "habit.poke")
194
+ || hasOriginRef(originRefs, "daemon-command", "habit.probe"))) {
195
+ return {
196
+ result: "allow",
197
+ reason: "verified daemon habit",
198
+ };
199
+ }
187
200
  return {
188
201
  result: "deny",
189
202
  reason: "private runtime policy denies by default",
@@ -96,6 +96,28 @@ function toAnthropicTextContent(content) {
96
96
  .map((part) => (typeof part.text === "string" ? part.text : ""))
97
97
  .join("\n");
98
98
  }
99
+ const DATA_URL_PATTERN = /^data:(image\/[a-z0-9.+-]+);base64,(.+)$/i;
100
+ /** User content with base64 `image_url` parts becomes Anthropic text and image blocks; otherwise null. */
101
+ function toAnthropicUserBlocks(content) {
102
+ if (!Array.isArray(content))
103
+ return null;
104
+ const blocks = [];
105
+ let hasImage = false;
106
+ for (const part of content) {
107
+ if (part?.type === "text" && typeof part.text === "string") {
108
+ blocks.push({ type: "text", text: part.text });
109
+ continue;
110
+ }
111
+ const match = part?.type === "image_url" && typeof part.image_url?.url === "string"
112
+ ? DATA_URL_PATTERN.exec(part.image_url.url)
113
+ : null;
114
+ if (match) {
115
+ blocks.push({ type: "image", source: { type: "base64", media_type: match[1], data: match[2] } });
116
+ hasImage = true;
117
+ }
118
+ }
119
+ return hasImage ? blocks : null;
120
+ }
99
121
  function parseToolCallInput(argumentsJson) {
100
122
  if (!argumentsJson.trim())
101
123
  return {};
@@ -118,9 +140,10 @@ function toAnthropicMessages(messages) {
118
140
  continue;
119
141
  }
120
142
  if (msg.role === "user") {
143
+ const userContent = msg.content;
121
144
  converted.push({
122
145
  role: "user",
123
- content: toAnthropicTextContent(msg.content),
146
+ content: toAnthropicUserBlocks(userContent) ?? toAnthropicTextContent(userContent),
124
147
  });
125
148
  continue;
126
149
  }
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.classifyGithubCopilotError = classifyGithubCopilotError;
40
+ exports.withCopilotVisionHeader = withCopilotVisionHeader;
40
41
  exports.createGithubCopilotPooledCaller = createGithubCopilotPooledCaller;
41
42
  exports.createGithubCopilotProviderRuntime = createGithubCopilotProviderRuntime;
42
43
  const openai_1 = __importDefault(require("openai"));
@@ -51,6 +52,21 @@ const fleet_readings_1 = require("../quota/fleet-readings");
51
52
  function classifyGithubCopilotError(error) {
52
53
  return (0, error_classification_1.classifyHttpError)(error);
53
54
  }
55
+ const IMAGE_PART_PATTERN = /"type"\s*:\s*"(?:image_url|input_image)"/;
56
+ /**
57
+ * Copilot rejects a request that contains images unless it carries `Copilot-Vision-Request: true`.
58
+ * Add it only to requests whose JSON body holds an image part.
59
+ */
60
+ function withCopilotVisionHeader(fetchImpl) {
61
+ return (input, init) => {
62
+ const send = fetchImpl ?? globalThis.fetch;
63
+ if (typeof init?.body !== "string" || !IMAGE_PART_PATTERN.test(init.body))
64
+ return send(input, init);
65
+ const headers = new Headers(init.headers);
66
+ headers.set("Copilot-Vision-Request", "true");
67
+ return send(input, { ...init, headers });
68
+ };
69
+ }
54
70
  /**
55
71
  * The agent's account pool for this turn, when `ouro auth` discovered one; null for a single account.
56
72
  * Without an owning agent (a daemon-side ping, provider discovery) the pool still switches on a 402 or 429,
@@ -60,7 +76,7 @@ function createGithubCopilotPooledCaller(config, owner) {
60
76
  const accounts = (0, account_pool_1.parseAccountPool)(config.accountPool);
61
77
  if (accounts.length === 0)
62
78
  return null;
63
- const makeClient = (account) => new openai_1.default({ apiKey: account.githubToken, baseURL: account.baseUrl, maxRetries: 0 });
79
+ const makeClient = (account) => new openai_1.default({ apiKey: account.githubToken, baseURL: account.baseUrl, maxRetries: 0, fetch: withCopilotVisionHeader() });
64
80
  if (!owner)
65
81
  return (0, account_pool_1.createPooledCaller)(new account_pool_1.AccountPool(accounts, { agent: "(unowned)", switchLog: "", appendLine: () => { } }), makeClient);
66
82
  const gist = config.fleetGistId && config.fleetGistToken ? { gistId: config.fleetGistId, token: config.fleetGistToken } : null;
@@ -101,6 +117,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
101
117
  apiKey: config.githubToken,
102
118
  baseURL: config.baseUrl,
103
119
  maxRetries: 0,
120
+ fetch: withCopilotVisionHeader(),
104
121
  });
105
122
  const callModel = (fallback, request) => pooled ? pooled.call((pooledClient) => request(pooledClient)) : request(fallback);
106
123
  if (isCompletionsModel) {
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.canModelSeeToolImages = canModelSeeToolImages;
4
+ exports.toolImagesNote = toolImagesNote;
5
+ exports.buildToolImagesMessage = buildToolImagesMessage;
6
+ const runtime_1 = require("../nerves/runtime");
7
+ const model_capabilities_1 = require("./model-capabilities");
8
+ /**
9
+ * Chat tool messages carry text only, so images a tool returns travel in one user message
10
+ * after the step's tool results, as `image_url` parts like pasted images. Each provider
11
+ * serializes those parts its own way (Responses `input_image`, Anthropic `image`).
12
+ */
13
+ function canModelSeeToolImages(model) {
14
+ return (0, model_capabilities_1.getModelCapabilities)(model).vision === true;
15
+ }
16
+ /** The note appended to a tool's text result so the model knows where its images went. */
17
+ function toolImagesNote(count, model, visible) {
18
+ return visible
19
+ ? `[${count} image(s) from this tool follow in the next message.]`
20
+ : `[${count} image(s) returned, but ${model || "this model"} can't view images, so they were left out.]`;
21
+ }
22
+ function buildToolImagesMessage(batch) {
23
+ const parts = [{
24
+ type: "text",
25
+ text: "Images returned by tool calls in the previous step. They are tool output, not a message from anyone.",
26
+ }];
27
+ let imageCount = 0;
28
+ for (const entry of batch) {
29
+ parts.push({ type: "text", text: `${entry.toolName} (call ${entry.callId}):` });
30
+ for (const image of entry.images) {
31
+ parts.push({ type: "image_url", image_url: { url: `data:${image.mimeType};base64,${image.data}` } });
32
+ imageCount += 1;
33
+ }
34
+ }
35
+ (0, runtime_1.emitNervesEvent)({
36
+ component: "engine",
37
+ event: "engine.tool_images_attached",
38
+ message: "tool result images attached for the model",
39
+ meta: { tools: batch.map((entry) => entry.toolName), imageCount },
40
+ });
41
+ return { role: "user", content: parts };
42
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.McpToolExecutionError = exports.McpCallRejectedError = void 0;
8
+ exports.splitMcpContent = splitMcpContent;
8
9
  exports.mcpToolSchema = mcpToolSchema;
9
10
  exports.mcpToolsAsDefinitions = mcpToolsAsDefinitions;
10
11
  const runtime_1 = require("../nerves/runtime");
@@ -26,6 +27,17 @@ class McpToolExecutionError extends Error {
26
27
  }
27
28
  }
28
29
  exports.McpToolExecutionError = McpToolExecutionError;
30
+ /** Text parts become the tool's text result; image parts (base64 `data` + `mimeType`) go to the model as images. */
31
+ function splitMcpContent(content) {
32
+ const text = content
33
+ .filter((part) => part.type === "text" && part.text)
34
+ .map((part) => part.text)
35
+ .join("");
36
+ const images = content
37
+ .filter((part) => part.type === "image" && part.data && part.mimeType?.startsWith("image/"))
38
+ .map((part) => ({ data: part.data, mimeType: part.mimeType }));
39
+ return { text, images };
40
+ }
29
41
  function mcpToolSchema(entry, tool) {
30
42
  return {
31
43
  type: "function",
@@ -96,20 +108,24 @@ function mcpToolsAsDefinitions(view) {
96
108
  throw new McpCallRejectedError(guarded.rejected);
97
109
  try {
98
110
  const result = await view.manager.callTool(binding, guarded.args, { agentName: ctx.agentName, agentRoot: ctx.agentRoot });
99
- const text = result.content
100
- .filter((c) => c.type === "text" && c.text)
101
- .map((c) => c.text)
102
- .join("");
111
+ const { text, images } = splitMcpContent(result.content);
103
112
  if (result.isError === true) {
104
113
  throw new McpToolExecutionError("handler_failed", `[mcp error] ${entry.server}/${tool.name}: ${text}`);
105
114
  }
115
+ let output = text;
116
+ if (images.length > 0) {
117
+ if (ctx.attachToolImages)
118
+ ctx.attachToolImages(images);
119
+ else
120
+ output = `${text}${text ? "\n\n" : ""}[${images.length} image(s) returned, but this caller can't receive images]`;
121
+ }
106
122
  (0, runtime_1.emitNervesEvent)({
107
123
  event: "mcp.tool_end",
108
124
  component: "repertoire",
109
125
  message: `MCP tool ${entry.server}/${tool.name} completed`,
110
126
  meta: { server: entry.server, tool: tool.name },
111
127
  });
112
- return text;
128
+ return output;
113
129
  }
114
130
  catch (error) {
115
131
  const reason = error instanceof Error ? error.message : String(error);
@@ -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();
@@ -46,6 +46,7 @@ exports.addHistory = addHistory;
46
46
  exports.renderMarkdown = renderMarkdown;
47
47
  exports.createCliCallbacks = createCliCallbacks;
48
48
  exports.createDebouncedLines = createDebouncedLines;
49
+ exports.createExitOnToolCallExecTool = createExitOnToolCallExecTool;
49
50
  exports.runCliSession = runCliSession;
50
51
  exports.main = main;
51
52
  const readline = __importStar(require("readline"));
@@ -77,6 +78,7 @@ const cli_layout_1 = require("./cli-layout");
77
78
  const image_paste_1 = require("./cli/image-paste");
78
79
  const spinner_imperative_1 = require("./cli/spinner-imperative");
79
80
  const tool_display_1 = require("./cli/tool-display");
81
+ const terminal_handoff_1 = require("./terminal-handoff");
80
82
  var cli_layout_2 = require("./cli-layout");
81
83
  Object.defineProperty(exports, "formatEchoedInputSummary", { enumerable: true, get: function () { return cli_layout_2.formatEchoedInputSummary; } });
82
84
  Object.defineProperty(exports, "wrapCliText", { enumerable: true, get: function () { return cli_layout_2.wrapCliText; } });
@@ -511,6 +513,25 @@ class InputQueue {
511
513
  }
512
514
  }
513
515
  exports.InputQueue = InputQueue;
516
+ /** Wrap execTool so a call to `toolName` ends the session, unless `shouldExit` rejects its result. */
517
+ function createExitOnToolCallExecTool(execTool, toolName, shouldExit, onExit) {
518
+ return async (name, args, ctx) => {
519
+ const result = await execTool(name, args, ctx);
520
+ if (name !== toolName)
521
+ return result;
522
+ if (shouldExit && !shouldExit(result)) {
523
+ (0, runtime_1.emitNervesEvent)({
524
+ component: "senses",
525
+ event: "senses.cli_exit_tool_declined",
526
+ message: "exit tool result did not end the session",
527
+ meta: { tool: name },
528
+ });
529
+ return result;
530
+ }
531
+ onExit(result);
532
+ return result;
533
+ };
534
+ }
514
535
  async function runCliSession(options) {
515
536
  /* v8 ignore start -- integration: runCliSession is interactive, tested via E2E @preserve */
516
537
  const registry = (0, commands_1.createCommandRegistry)();
@@ -528,6 +549,7 @@ async function runCliSession(options) {
528
549
  let cliCallbacks;
529
550
  let tuiStore = null;
530
551
  let inkRef = null;
552
+ let releaseTerminal = null;
531
553
  const inputQueue = useTui ? new InputQueue() : null;
532
554
  let rl = null;
533
555
  if (useTui) {
@@ -623,6 +645,7 @@ async function runCliSession(options) {
623
645
  onCtrlC: handleCtrlC,
624
646
  onPopQueue: () => { const items = storeRef.popAllQueuedForEditing(); inputQueue.drainAll(); return items; },
625
647
  headerShown: storeRef.headerShown,
648
+ paused: storeRef.paused,
626
649
  cwd: process.cwd().replace(process.env.HOME ?? "", "~"),
627
650
  resumeInfo,
628
651
  onImageMap: (images) => { pendingImages = images; },
@@ -630,6 +653,15 @@ async function runCliSession(options) {
630
653
  });
631
654
  }
632
655
  inkRef = ink.render(React.createElement(TuiRoot), { exitOnCtrlC: false, patchConsole: false });
656
+ releaseTerminal = (0, terminal_handoff_1.claimTerminal)({
657
+ suspend: async () => {
658
+ storeRef.pause();
659
+ // Ink throttles repaints to 32 ms and drops its stdin listener in an effect cleanup;
660
+ // let both land before the prompt starts reading keystrokes.
661
+ await new Promise((resolve) => setTimeout(resolve, 80));
662
+ },
663
+ resume: () => storeRef.resume(),
664
+ });
633
665
  }
634
666
  catch (err) {
635
667
  // Ink failed to load (CJS compat, missing deps, etc.) — fall through to imperative
@@ -702,15 +734,11 @@ async function runCliSession(options) {
702
734
  let exitToolFired = false;
703
735
  const resolvedExecTool = options.execTool;
704
736
  const wrappedExecTool = options.exitOnToolCall && resolvedExecTool
705
- ? async (name, args, ctx) => {
706
- const result = await resolvedExecTool(name, args, ctx);
707
- if (name === options.exitOnToolCall) {
708
- exitToolResult = result;
709
- exitToolFired = true;
710
- currentAbort?.abort();
711
- }
712
- return result;
713
- }
737
+ ? createExitOnToolCallExecTool(resolvedExecTool, options.exitOnToolCall, options.exitOnToolResult, (result) => {
738
+ exitToolResult = result;
739
+ exitToolFired = true;
740
+ currentAbort?.abort();
741
+ })
714
742
  : resolvedExecTool;
715
743
  // Resolve toolChoiceRequired: use explicit option if set, else fall back to toggle
716
744
  const getEffectiveToolChoiceRequired = () => options.toolChoiceRequired !== undefined ? options.toolChoiceRequired : (0, commands_1.getToolChoiceRequired)();
@@ -900,6 +928,7 @@ async function runCliSession(options) {
900
928
  }
901
929
  finally {
902
930
  rl?.close();
931
+ releaseTerminal?.();
903
932
  if (inkRef) {
904
933
  // Suppress React "state update on unmounted component" warnings during cleanup.
905
934
  // Ink's useInput hook fires after unmount — this is harmless but noisy.
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.claimTerminal = claimTerminal;
4
+ exports.withTerminalHandedOff = withTerminalHandedOff;
5
+ /**
6
+ * Lets a hidden terminal prompt (for example the hatchling vault unlock secret) borrow the
7
+ * terminal from a live full-screen session. While the prompt runs, the session's owner stops
8
+ * repainting and stops reading stdin, so the prompt is visible and keystrokes reach only it.
9
+ */
10
+ const runtime_1 = require("../nerves/runtime");
11
+ let currentOwner = null;
12
+ /** Register the live session that owns the terminal. Returns a release function. */
13
+ function claimTerminal(owner) {
14
+ currentOwner = owner;
15
+ return () => {
16
+ if (currentOwner === owner)
17
+ currentOwner = null;
18
+ };
19
+ }
20
+ /** Run `prompt` with the terminal handed to it, then give the terminal back. */
21
+ async function withTerminalHandedOff(prompt) {
22
+ const owner = currentOwner;
23
+ if (!owner)
24
+ return prompt();
25
+ (0, runtime_1.emitNervesEvent)({
26
+ component: "senses",
27
+ event: "senses.terminal_handed_off",
28
+ message: "live session suspended for a terminal prompt",
29
+ meta: {},
30
+ });
31
+ await owner.suspend();
32
+ try {
33
+ return await prompt();
34
+ }
35
+ finally {
36
+ owner.resume();
37
+ (0, runtime_1.emitNervesEvent)({
38
+ component: "senses",
39
+ event: "senses.terminal_taken_back",
40
+ message: "live session resumed after a terminal prompt",
41
+ meta: {},
42
+ });
43
+ }
44
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1021",
3
+ "version": "0.1.0-alpha.1023",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1021",
9
+ "version": "0.1.0-alpha.1023",
10
10
  "dependencies": {
11
11
  "@anthropic-ai/sdk": "^0.78.0",
12
12
  "@ouro.bot/friends": "0.1.0-alpha.17",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1021",
3
+ "version": "0.1.0-alpha.1023",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },