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

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.
Files changed (39) hide show
  1. package/changelog.json +34 -0
  2. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
  3. package/deploy/unraid/sanctuary.xml +1 -1
  4. package/dist/heart/auth/auth-flow.js +17 -12
  5. package/dist/heart/core.js +19 -2
  6. package/dist/heart/daemon/agent-discovery.js +22 -5
  7. package/dist/heart/daemon/agent-home.js +101 -47
  8. package/dist/heart/daemon/cli-defaults.js +27 -6
  9. package/dist/heart/daemon/cli-exec.js +95 -1
  10. package/dist/heart/daemon/cli-help.js +7 -0
  11. package/dist/heart/daemon/cli-parse.js +38 -2
  12. package/dist/heart/daemon/daemon-entry.js +121 -1
  13. package/dist/heart/daemon/launchd.js +3 -0
  14. package/dist/heart/daemon/mcp-canary.js +2 -1
  15. package/dist/heart/daemon/os-cron-deps.js +4 -0
  16. package/dist/heart/daemon/presence-daemon.js +263 -0
  17. package/dist/heart/daemon/presence-roster.js +217 -0
  18. package/dist/heart/daemon/presence.js +380 -0
  19. package/dist/heart/daemon/provider-discovery.js +34 -0
  20. package/dist/heart/daemon/sense-manager.js +111 -35
  21. package/dist/heart/hatch/hatch-flow.js +3 -1
  22. package/dist/heart/hatch/specialist-prompt.js +1 -0
  23. package/dist/heart/hatch/specialist-tools.js +47 -2
  24. package/dist/heart/private-runtime/ledger.js +19 -28
  25. package/dist/heart/private-runtime/policy.js +13 -0
  26. package/dist/heart/providers/anthropic.js +24 -1
  27. package/dist/heart/providers/github-copilot.js +18 -1
  28. package/dist/heart/tool-images.js +42 -0
  29. package/dist/mind/prompt.js +2 -0
  30. package/dist/mind/where-am-i.js +122 -0
  31. package/dist/repertoire/mcp-tools.js +21 -5
  32. package/dist/repertoire/vault-setup.js +82 -30
  33. package/dist/repertoire/vault-unlock.js +18 -4
  34. package/dist/senses/cli/ouro-tui.js +2 -2
  35. package/dist/senses/cli/tui-store.js +11 -0
  36. package/dist/senses/cli.js +38 -9
  37. package/dist/senses/terminal-handoff.js +44 -0
  38. package/npm-shrinkwrap.json +2 -2
  39. package/package.json +1 -1
@@ -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.1024",
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.1024",
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.1024",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },