@ouro.bot/cli 0.1.0-alpha.5 → 0.1.0-alpha.50

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 (102) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +70 -9
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +5 -2
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +117 -188
  5. package/assets/ouroboros.png +0 -0
  6. package/changelog.json +242 -0
  7. package/dist/heart/active-work.js +157 -0
  8. package/dist/heart/bridges/manager.js +358 -0
  9. package/dist/heart/bridges/state-machine.js +135 -0
  10. package/dist/heart/bridges/store.js +123 -0
  11. package/dist/heart/config.js +81 -8
  12. package/dist/heart/core.js +145 -50
  13. package/dist/heart/daemon/agent-discovery.js +81 -0
  14. package/dist/heart/daemon/daemon-cli.js +1099 -164
  15. package/dist/heart/daemon/daemon-entry.js +14 -5
  16. package/dist/heart/daemon/daemon-runtime-sync.js +90 -0
  17. package/dist/heart/daemon/daemon.js +184 -9
  18. package/dist/heart/daemon/hatch-animation.js +10 -3
  19. package/dist/heart/daemon/hatch-flow.js +3 -20
  20. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  21. package/dist/heart/daemon/launchd.js +151 -0
  22. package/dist/heart/daemon/message-router.js +15 -6
  23. package/dist/heart/daemon/ouro-bot-entry.js +0 -0
  24. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  25. package/dist/heart/daemon/ouro-entry.js +0 -0
  26. package/dist/heart/daemon/ouro-path-installer.js +178 -0
  27. package/dist/heart/daemon/ouro-uti.js +11 -2
  28. package/dist/heart/daemon/process-manager.js +1 -1
  29. package/dist/heart/daemon/run-hooks.js +37 -0
  30. package/dist/heart/daemon/runtime-metadata.js +118 -0
  31. package/dist/heart/daemon/sense-manager.js +290 -0
  32. package/dist/heart/daemon/socket-client.js +202 -0
  33. package/dist/heart/daemon/specialist-orchestrator.js +53 -84
  34. package/dist/heart/daemon/specialist-prompt.js +64 -5
  35. package/dist/heart/daemon/specialist-tools.js +213 -58
  36. package/dist/heart/daemon/staged-restart.js +114 -0
  37. package/dist/heart/daemon/subagent-installer.js +48 -7
  38. package/dist/heart/daemon/thoughts.js +379 -0
  39. package/dist/heart/daemon/update-checker.js +111 -0
  40. package/dist/heart/daemon/update-hooks.js +138 -0
  41. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  42. package/dist/heart/delegation.js +62 -0
  43. package/dist/heart/identity.js +82 -4
  44. package/dist/heart/kicks.js +1 -19
  45. package/dist/heart/progress-story.js +42 -0
  46. package/dist/heart/providers/anthropic.js +16 -2
  47. package/dist/heart/sense-truth.js +61 -0
  48. package/dist/heart/session-activity.js +169 -0
  49. package/dist/heart/session-recall.js +116 -0
  50. package/dist/heart/streaming.js +96 -21
  51. package/dist/heart/turn-coordinator.js +28 -0
  52. package/dist/mind/associative-recall.js +14 -2
  53. package/dist/mind/bundle-manifest.js +70 -0
  54. package/dist/mind/context.js +27 -11
  55. package/dist/mind/first-impressions.js +16 -2
  56. package/dist/mind/friends/channel.js +43 -0
  57. package/dist/mind/friends/store-file.js +19 -0
  58. package/dist/mind/friends/types.js +9 -1
  59. package/dist/mind/memory.js +10 -3
  60. package/dist/mind/pending.js +72 -9
  61. package/dist/mind/phrases.js +1 -0
  62. package/dist/mind/prompt.js +266 -77
  63. package/dist/mind/token-estimate.js +8 -12
  64. package/dist/nerves/cli-logging.js +15 -2
  65. package/dist/repertoire/ado-client.js +4 -2
  66. package/dist/repertoire/coding/feedback.js +134 -0
  67. package/dist/repertoire/coding/index.js +4 -1
  68. package/dist/repertoire/coding/manager.js +62 -4
  69. package/dist/repertoire/coding/spawner.js +3 -3
  70. package/dist/repertoire/coding/tools.js +41 -2
  71. package/dist/repertoire/data/ado-endpoints.json +188 -0
  72. package/dist/repertoire/tasks/board.js +12 -0
  73. package/dist/repertoire/tasks/index.js +23 -9
  74. package/dist/repertoire/tasks/transitions.js +1 -2
  75. package/dist/repertoire/tools-base.js +462 -245
  76. package/dist/repertoire/tools-bluebubbles.js +93 -0
  77. package/dist/repertoire/tools-teams.js +58 -25
  78. package/dist/repertoire/tools.js +57 -35
  79. package/dist/senses/bluebubbles-client.js +484 -0
  80. package/dist/senses/bluebubbles-entry.js +13 -0
  81. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  82. package/dist/senses/bluebubbles-media.js +338 -0
  83. package/dist/senses/bluebubbles-model.js +261 -0
  84. package/dist/senses/bluebubbles-mutation-log.js +116 -0
  85. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  86. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  87. package/dist/senses/bluebubbles.js +1142 -0
  88. package/dist/senses/cli.js +340 -138
  89. package/dist/senses/continuity.js +94 -0
  90. package/dist/senses/debug-activity.js +148 -0
  91. package/dist/senses/inner-dialog-worker.js +47 -18
  92. package/dist/senses/inner-dialog.js +330 -84
  93. package/dist/senses/pipeline.js +256 -0
  94. package/dist/senses/teams.js +541 -129
  95. package/dist/senses/trust-gate.js +112 -2
  96. package/package.json +14 -3
  97. package/subagents/README.md +46 -33
  98. package/subagents/work-doer.md +28 -24
  99. package/subagents/work-merger.md +24 -30
  100. package/subagents/work-planner.md +44 -27
  101. package/dist/heart/daemon/specialist-session.js +0 -142
  102. package/dist/inner-worker-entry.js +0 -4
@@ -34,10 +34,14 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.MarkdownStreamer = exports.InputController = exports.Spinner = void 0;
37
+ exports.formatPendingPrefix = formatPendingPrefix;
38
+ exports.getCliContinuityIngressTexts = getCliContinuityIngressTexts;
37
39
  exports.handleSigint = handleSigint;
38
40
  exports.addHistory = addHistory;
39
41
  exports.renderMarkdown = renderMarkdown;
40
42
  exports.createCliCallbacks = createCliCallbacks;
43
+ exports.createDebouncedLines = createDebouncedLines;
44
+ exports.runCliSession = runCliSession;
41
45
  exports.main = main;
42
46
  const readline = __importStar(require("readline"));
43
47
  const os = __importStar(require("os"));
@@ -49,7 +53,6 @@ const format_1 = require("../mind/format");
49
53
  const config_1 = require("../heart/config");
50
54
  const context_1 = require("../mind/context");
51
55
  const pending_1 = require("../mind/pending");
52
- const prompt_refresh_1 = require("../mind/prompt-refresh");
53
56
  const commands_1 = require("./commands");
54
57
  const identity_1 = require("../heart/identity");
55
58
  const nerves_1 = require("../nerves");
@@ -59,7 +62,29 @@ const tokens_1 = require("../mind/friends/tokens");
59
62
  const cli_logging_1 = require("../nerves/cli-logging");
60
63
  const runtime_1 = require("../nerves/runtime");
61
64
  const trust_gate_1 = require("./trust-gate");
65
+ const pipeline_1 = require("./pipeline");
66
+ const channel_1 = require("../mind/friends/channel");
62
67
  const session_lock_1 = require("./session-lock");
68
+ const update_hooks_1 = require("../heart/daemon/update-hooks");
69
+ const bundle_meta_1 = require("../heart/daemon/hooks/bundle-meta");
70
+ const bundle_manifest_1 = require("../mind/bundle-manifest");
71
+ /**
72
+ * Format pending messages as content-prefix strings for injection into
73
+ * the next user message. Self-messages (from === agentName) become
74
+ * `[inner thought: {content}]`, inter-agent messages become
75
+ * `[message from {name}: {content}]`.
76
+ */
77
+ function formatPendingPrefix(messages, agentName) {
78
+ return messages
79
+ .map((msg) => msg.from === agentName
80
+ ? `[inner thought: ${msg.content}]`
81
+ : `[message from ${msg.from}: ${msg.content}]`)
82
+ .join("\n");
83
+ }
84
+ function getCliContinuityIngressTexts(input) {
85
+ const trimmed = input.trim();
86
+ return trimmed ? [trimmed] : [];
87
+ }
63
88
  // spinner that only touches stderr, cleans up after itself
64
89
  // exported for direct testability (stop-without-start branch)
65
90
  class Spinner {
@@ -70,12 +95,14 @@ class Spinner {
70
95
  msg = "";
71
96
  phrases = null;
72
97
  lastPhrase = "";
98
+ stopped = false;
73
99
  constructor(m = "working", phrases) {
74
100
  this.msg = m;
75
101
  if (phrases && phrases.length > 0)
76
102
  this.phrases = phrases;
77
103
  }
78
104
  start() {
105
+ this.stopped = false;
79
106
  process.stderr.write("\r\x1b[K");
80
107
  this.spin();
81
108
  this.iv = setInterval(() => this.spin(), 80);
@@ -84,15 +111,23 @@ class Spinner {
84
111
  }
85
112
  }
86
113
  spin() {
87
- process.stderr.write(`\r${this.frames[this.i]} ${this.msg}... `);
114
+ // Guard: clearInterval can't prevent already-dequeued callbacks
115
+ /* v8 ignore next -- race guard: timer callback fires after stop() @preserve */
116
+ if (this.stopped)
117
+ return;
118
+ process.stderr.write(`\r\x1b[K${this.frames[this.i]} ${this.msg}... `);
88
119
  this.i = (this.i + 1) % this.frames.length;
89
120
  }
90
121
  rotatePhrase() {
122
+ /* v8 ignore next -- race guard: timer callback fires after stop() @preserve */
123
+ if (this.stopped)
124
+ return;
91
125
  const next = (0, phrases_1.pickPhrase)(this.phrases, this.lastPhrase);
92
126
  this.lastPhrase = next;
93
127
  this.msg = next;
94
128
  }
95
129
  stop(ok) {
130
+ this.stopped = true;
96
131
  if (this.iv) {
97
132
  clearInterval(this.iv);
98
133
  this.iv = null;
@@ -297,12 +332,25 @@ function createCliCallbacks() {
297
332
  currentSpinner.start();
298
333
  },
299
334
  onModelStreamStart: () => {
300
- currentSpinner?.stop();
301
- currentSpinner = null;
335
+ // No-op: content callbacks (onTextChunk, onReasoningChunk) handle
336
+ // stopping the spinner. onModelStreamStart fires too early and
337
+ // doesn't fire at all for final_answer tool streaming.
338
+ },
339
+ onClearText: () => {
340
+ streamer.reset();
302
341
  },
303
342
  onTextChunk: (text) => {
343
+ // Stop spinner if still running — final_answer streaming and Anthropic
344
+ // tool-only responses bypass onModelStreamStart, so the spinner would
345
+ // otherwise keep running (and its \r writes overwrite response text).
346
+ if (currentSpinner) {
347
+ currentSpinner.stop();
348
+ currentSpinner = null;
349
+ }
304
350
  if (hadReasoning) {
305
- process.stdout.write("\n\n");
351
+ // Single newline to separate reasoning from reply — reasoning
352
+ // output often ends with its own trailing newline(s)
353
+ process.stdout.write("\n");
306
354
  hadReasoning = false;
307
355
  }
308
356
  const rendered = streamer.push(text);
@@ -311,6 +359,10 @@ function createCliCallbacks() {
311
359
  textDirty = text.length > 0 && !text.endsWith("\n");
312
360
  },
313
361
  onReasoningChunk: (text) => {
362
+ if (currentSpinner) {
363
+ currentSpinner.stop();
364
+ currentSpinner = null;
365
+ }
314
366
  hadReasoning = true;
315
367
  process.stdout.write(`\x1b[2m${text}\x1b[0m`);
316
368
  textDirty = text.length > 0 && !text.endsWith("\n");
@@ -368,88 +420,86 @@ function createCliCallbacks() {
368
420
  },
369
421
  };
370
422
  }
371
- async function main(agentName, options) {
372
- if (agentName)
373
- (0, identity_1.setAgentName)(agentName);
374
- const pasteDebounceMs = options?.pasteDebounceMs ?? 50;
375
- // Fail fast if provider is misconfigured (triggers human-readable error + exit)
376
- (0, core_1.getProvider)();
377
- const registry = (0, commands_1.createCommandRegistry)();
378
- (0, commands_1.registerDefaultCommands)(registry);
379
- // Resolve context kernel (identity + channel) for CLI
380
- const friendsPath = path.join((0, identity_1.getAgentRoot)(), "friends");
381
- const friendStore = new store_file_1.FileFriendStore(friendsPath);
382
- const username = os.userInfo().username;
383
- const hostname = os.hostname();
384
- const localExternalId = `${username}@${hostname}`;
385
- const resolver = new resolver_1.FriendResolver(friendStore, {
386
- provider: "local",
387
- externalId: localExternalId,
388
- displayName: username,
389
- channel: "cli",
390
- });
391
- const resolvedContext = await resolver.resolve();
392
- const cliToolContext = {
393
- /* v8 ignore next -- CLI has no OAuth sign-in; this no-op satisfies the interface @preserve */
394
- signin: async () => undefined,
395
- context: resolvedContext,
396
- friendStore,
397
- summarize: (0, core_1.createSummarize)(),
398
- };
399
- const friendId = resolvedContext.friend.id;
400
- const agentConfig = (0, identity_1.loadAgentConfig)();
401
- (0, cli_logging_1.configureCliRuntimeLogger)(friendId, {
402
- level: agentConfig.logging?.level,
403
- sinks: agentConfig.logging?.sinks,
404
- });
405
- const sessPath = (0, config_1.sessionPath)(friendId, "cli", "session");
406
- let sessionLock = null;
407
- try {
408
- sessionLock = (0, session_lock_1.acquireSessionLock)(`${sessPath}.lock`, (0, identity_1.getAgentName)());
423
+ // Debounced line iterator: collects rapid-fire lines (paste) into a single input.
424
+ // When the debounce timeout wins the race, the pending iter.next() is saved
425
+ // and reused in the next iteration to prevent it from silently consuming input.
426
+ async function* createDebouncedLines(source, debounceMs) {
427
+ if (debounceMs <= 0) {
428
+ yield* source;
429
+ return;
409
430
  }
410
- catch (error) {
411
- /* v8 ignore start -- integration: main() is interactive, lock tested in session-lock.test.ts @preserve */
412
- if (error instanceof session_lock_1.SessionLockError) {
413
- process.stderr.write(`${error.message}\n`);
414
- return;
431
+ const iter = source[Symbol.asyncIterator]();
432
+ let pending = null;
433
+ while (true) {
434
+ const first = pending ? await pending : await iter.next();
435
+ pending = null;
436
+ if (first.done)
437
+ break;
438
+ const lines = [first.value];
439
+ let more = true;
440
+ while (more) {
441
+ const nextPromise = iter.next();
442
+ const raced = await Promise.race([
443
+ nextPromise.then((r) => ({ kind: "line", result: r })),
444
+ new Promise((r) => setTimeout(() => r({ kind: "timeout" }), debounceMs)),
445
+ ]);
446
+ if (raced.kind === "timeout") {
447
+ pending = nextPromise;
448
+ more = false;
449
+ }
450
+ else if (raced.result.done) {
451
+ more = false;
452
+ }
453
+ else {
454
+ lines.push(raced.result.value);
455
+ }
415
456
  }
416
- throw error;
417
- /* v8 ignore stop */
457
+ yield lines.join("\n");
418
458
  }
419
- // Load existing session or start fresh
420
- const existing = (0, context_1.loadSession)(sessPath);
421
- const messages = existing?.messages && existing.messages.length > 0
422
- ? existing.messages
423
- : [{ role: "system", content: await (0, prompt_1.buildSystem)("cli", undefined, resolvedContext) }];
424
- // Pending queue drain: inject pending messages as harness-context + assistant-content pairs
425
- const pendingDir = (0, pending_1.getPendingDir)((0, identity_1.getAgentName)(), friendId, "cli", "session");
426
- const drainToMessages = () => {
427
- const pending = (0, pending_1.drainPending)(pendingDir);
428
- if (pending.length === 0)
429
- return 0;
430
- for (const msg of pending) {
431
- messages.push({ role: "user", name: "harness", content: `[proactive message from ${msg.from}]` });
432
- messages.push({ role: "assistant", content: msg.content });
433
- }
434
- return pending.length;
435
- };
436
- // Startup drain: deliver offline messages
437
- const startupCount = drainToMessages();
438
- if (startupCount > 0) {
439
- (0, context_1.saveSession)(sessPath, messages);
459
+ }
460
+ async function runCliSession(options) {
461
+ /* v8 ignore start -- integration: runCliSession is interactive, tested via E2E @preserve */
462
+ const pasteDebounceMs = options.pasteDebounceMs ?? 50;
463
+ const registry = (0, commands_1.createCommandRegistry)();
464
+ if (!options.disableCommands) {
465
+ (0, commands_1.registerDefaultCommands)(registry);
440
466
  }
467
+ const messages = options.messages
468
+ ?? [{ role: "system", content: await (0, prompt_1.buildSystem)("cli") }];
441
469
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
442
470
  const ctrl = new InputController(rl);
443
471
  let currentAbort = null;
444
472
  const history = [];
445
473
  let closed = false;
446
474
  rl.on("close", () => { closed = true; });
447
- // eslint-disable-next-line no-console -- terminal UX: startup banner
448
- console.log(`\n${(0, identity_1.getAgentName)()} (type /commands for help)\n`);
475
+ if (options.banner !== false) {
476
+ const bannerText = typeof options.banner === "string"
477
+ ? options.banner
478
+ : `${options.agentName} (type /commands for help)`;
479
+ // eslint-disable-next-line no-console -- terminal UX: startup banner
480
+ console.log(`\n${bannerText}\n`);
481
+ }
449
482
  const cliCallbacks = createCliCallbacks();
450
- process.stdout.write("\x1b[36m> \x1b[0m");
483
+ // exitOnToolCall machinery: wrap execTool to detect target tool
484
+ let exitToolResult;
485
+ let exitToolFired = false;
486
+ const resolvedExecTool = options.execTool;
487
+ const wrappedExecTool = options.exitOnToolCall && resolvedExecTool
488
+ ? async (name, args, ctx) => {
489
+ const result = await resolvedExecTool(name, args, ctx);
490
+ if (name === options.exitOnToolCall) {
491
+ exitToolResult = result;
492
+ exitToolFired = true;
493
+ // Abort immediately so the model doesn't generate more output
494
+ // (e.g. reasoning about calling final_answer after complete_adoption)
495
+ currentAbort?.abort();
496
+ }
497
+ return result;
498
+ }
499
+ : resolvedExecTool;
500
+ // Resolve toolChoiceRequired: use explicit option if set, else fall back to toggle
501
+ const getEffectiveToolChoiceRequired = () => options.toolChoiceRequired !== undefined ? options.toolChoiceRequired : (0, commands_1.getToolChoiceRequired)();
451
502
  // Ctrl-C at the input prompt: clear line or warn/exit
452
- // readline with terminal:true catches Ctrl-C in raw mode (no ^C echo)
453
503
  rl.on("SIGINT", () => {
454
504
  const rlInt = rl;
455
505
  const currentLine = rlInt.line || "";
@@ -470,38 +520,58 @@ async function main(agentName, options) {
470
520
  rl.close();
471
521
  }
472
522
  });
473
- // Debounced line iterator: collects rapid-fire lines (paste) into a single input
474
- async function* debouncedLines(source) {
475
- if (pasteDebounceMs <= 0) {
476
- yield* source;
477
- return;
523
+ const debouncedLines = (source) => createDebouncedLines(source, pasteDebounceMs);
524
+ (0, runtime_1.emitNervesEvent)({
525
+ component: "senses",
526
+ event: "senses.cli_session_start",
527
+ message: "runCliSession started",
528
+ meta: { agentName: options.agentName, hasExitOnToolCall: !!options.exitOnToolCall },
529
+ });
530
+ let exitReason = "user_quit";
531
+ // Auto-first-turn: process the last user message immediately so the agent
532
+ // speaks first (e.g. specialist greeting). Only triggers when explicitly opted in.
533
+ if (options.autoFirstTurn && messages.length > 0 && messages[messages.length - 1]?.role === "user") {
534
+ currentAbort = new AbortController();
535
+ const traceId = (0, nerves_1.createTraceId)();
536
+ ctrl.suppress(() => currentAbort.abort());
537
+ let result;
538
+ try {
539
+ result = await (0, core_1.runAgent)(messages, cliCallbacks, options.skipSystemPromptRefresh ? undefined : "cli", currentAbort.signal, {
540
+ toolChoiceRequired: getEffectiveToolChoiceRequired(),
541
+ traceId,
542
+ tools: options.tools,
543
+ execTool: wrappedExecTool,
544
+ toolContext: options.toolContext,
545
+ });
478
546
  }
479
- const iter = source[Symbol.asyncIterator]();
480
- while (true) {
481
- const first = await iter.next();
482
- if (first.done)
483
- break;
484
- // Collect any lines that arrive within the debounce window (paste detection)
485
- const lines = [first.value];
486
- let more = true;
487
- while (more) {
488
- const raced = await Promise.race([
489
- iter.next().then((r) => ({ kind: "line", result: r })),
490
- new Promise((r) => setTimeout(() => r({ kind: "timeout" }), pasteDebounceMs)),
491
- ]);
492
- if (raced.kind === "timeout") {
493
- more = false;
494
- }
495
- else if (raced.result.done) {
496
- more = false;
497
- }
498
- else {
499
- lines.push(raced.result.value);
500
- }
547
+ catch (err) {
548
+ // AbortError (Ctrl-C) -- silently continue to prompt
549
+ // All other errors: show the user what happened
550
+ if (!(err instanceof DOMException && err.name === "AbortError")) {
551
+ process.stderr.write(`\x1b[31m${err instanceof Error ? err.message : String(err)}\x1b[0m\n`);
552
+ }
553
+ }
554
+ cliCallbacks.flushMarkdown();
555
+ ctrl.restore();
556
+ currentAbort = null;
557
+ if (exitToolFired) {
558
+ exitReason = "tool_exit";
559
+ rl.close();
560
+ }
561
+ else {
562
+ const lastMsg = messages[messages.length - 1];
563
+ if (lastMsg?.role === "assistant" && !(typeof lastMsg.content === "string" ? lastMsg.content : "").trim()) {
564
+ process.stderr.write("\x1b[33m(empty response)\x1b[0m\n");
565
+ }
566
+ process.stdout.write("\n\n");
567
+ if (options.onTurnEnd) {
568
+ await options.onTurnEnd(messages, result ?? { usage: undefined });
501
569
  }
502
- yield lines.join("\n");
503
570
  }
504
571
  }
572
+ if (!exitToolFired) {
573
+ process.stdout.write("\x1b[36m> \x1b[0m");
574
+ }
505
575
  try {
506
576
  for await (const input of debouncedLines(rl)) {
507
577
  if (closed)
@@ -510,20 +580,18 @@ async function main(agentName, options) {
510
580
  process.stdout.write("\x1b[36m> \x1b[0m");
511
581
  continue;
512
582
  }
513
- const trustGate = (0, trust_gate_1.enforceTrustGate)({
514
- friend: resolvedContext.friend,
515
- provider: "local",
516
- externalId: localExternalId,
517
- channel: "cli",
518
- });
519
- if (!trustGate.allowed) {
520
- if (trustGate.reason === "stranger_first_reply") {
521
- process.stdout.write(`${trustGate.autoReply}\n`);
583
+ // Optional input gate (e.g. trust gate in main)
584
+ if (options.onInput) {
585
+ const gate = options.onInput(input);
586
+ if (!gate.allowed) {
587
+ if (gate.reply) {
588
+ process.stdout.write(`${gate.reply}\n`);
589
+ }
590
+ if (closed)
591
+ break;
592
+ process.stdout.write("\x1b[36m> \x1b[0m");
593
+ continue;
522
594
  }
523
- if (closed)
524
- break;
525
- process.stdout.write("\x1b[36m> \x1b[0m");
526
- continue;
527
595
  }
528
596
  // Check for slash commands
529
597
  const parsed = (0, commands_1.parseSlashCommand)(input);
@@ -536,7 +604,7 @@ async function main(agentName, options) {
536
604
  else if (dispatchResult.result.action === "new") {
537
605
  messages.length = 0;
538
606
  messages.push({ role: "system", content: await (0, prompt_1.buildSystem)("cli") });
539
- (0, context_1.deleteSession)(sessPath);
607
+ await options.onNewSession?.();
540
608
  // eslint-disable-next-line no-console -- terminal UX: session cleared
541
609
  console.log("session cleared");
542
610
  process.stdout.write("\x1b[36m> \x1b[0m");
@@ -550,55 +618,189 @@ async function main(agentName, options) {
550
618
  }
551
619
  }
552
620
  }
553
- // Re-style the echoed input lines (readline terminal:true echoes each line)
554
- // For multiline paste, each line was echoed separately — erase them all
621
+ // Re-style the echoed input lines
555
622
  const cols = process.stdout.columns || 80;
556
623
  const inputLines = input.split("\n");
557
624
  let echoRows = 0;
558
625
  for (const line of inputLines) {
559
- echoRows += Math.ceil((2 + line.length) / cols); // "> " prefix + line content
626
+ echoRows += Math.ceil((2 + line.length) / cols);
560
627
  }
561
628
  process.stdout.write(`\x1b[${echoRows}A\x1b[K` + `\x1b[1m> ${inputLines[0]}${inputLines.length > 1 ? ` (+${inputLines.length - 1} lines)` : ""}\x1b[0m\n\n`);
562
- messages.push({ role: "user", content: input });
563
629
  addHistory(history, input);
564
630
  currentAbort = new AbortController();
565
- const traceId = (0, nerves_1.createTraceId)();
566
631
  ctrl.suppress(() => currentAbort.abort());
567
632
  let result;
568
633
  try {
569
- result = await (0, core_1.runAgent)(messages, cliCallbacks, "cli", currentAbort.signal, {
570
- toolChoiceRequired: (0, commands_1.getToolChoiceRequired)(),
571
- toolContext: cliToolContext,
572
- traceId,
573
- });
634
+ if (options.runTurn) {
635
+ // Pipeline-based turn: the runTurn callback handles user message assembly,
636
+ // pending drain, trust gate, runAgent, postTurn, and token accumulation.
637
+ result = await options.runTurn(messages, input, cliCallbacks, currentAbort.signal);
638
+ }
639
+ else {
640
+ // Legacy path: inline runAgent (used by adoption specialist and tests)
641
+ const prefix = options.getContentPrefix?.();
642
+ messages.push({ role: "user", content: prefix ? `${prefix}\n\n${input}` : input });
643
+ const traceId = (0, nerves_1.createTraceId)();
644
+ result = await (0, core_1.runAgent)(messages, cliCallbacks, options.skipSystemPromptRefresh ? undefined : "cli", currentAbort.signal, {
645
+ toolChoiceRequired: getEffectiveToolChoiceRequired(),
646
+ traceId,
647
+ tools: options.tools,
648
+ execTool: wrappedExecTool,
649
+ toolContext: options.toolContext,
650
+ });
651
+ }
574
652
  }
575
- catch {
576
- // AbortError silently return to prompt
653
+ catch (err) {
654
+ // AbortError (Ctrl-C) -- silently return to prompt
655
+ // All other errors: show the user what happened
656
+ if (!(err instanceof DOMException && err.name === "AbortError")) {
657
+ process.stderr.write(`\x1b[31m${err instanceof Error ? err.message : String(err)}\x1b[0m\n`);
658
+ }
577
659
  }
578
660
  cliCallbacks.flushMarkdown();
579
661
  ctrl.restore();
580
662
  currentAbort = null;
663
+ // Check if exit tool was fired during this turn
664
+ if (exitToolFired) {
665
+ exitReason = "tool_exit";
666
+ break;
667
+ }
581
668
  // Safety net: never silently swallow an empty response
582
669
  const lastMsg = messages[messages.length - 1];
583
670
  if (lastMsg?.role === "assistant" && !(typeof lastMsg.content === "string" ? lastMsg.content : "").trim()) {
584
671
  process.stderr.write("\x1b[33m(empty response)\x1b[0m\n");
585
672
  }
586
673
  process.stdout.write("\n\n");
587
- (0, context_1.postTurn)(messages, sessPath, result?.usage);
588
- await (0, tokens_1.accumulateFriendTokens)(friendStore, resolvedContext.friend.id, result?.usage);
589
- // Post-turn: drain any pending messages that arrived during runAgent
590
- drainToMessages();
591
- // Post-turn: refresh system prompt so active sessions metadata is current
592
- await (0, prompt_refresh_1.refreshSystemPrompt)(messages, "cli", undefined, resolvedContext);
674
+ // Post-turn hook (session persistence, pending drain, prompt refresh, etc.)
675
+ if (options.onTurnEnd) {
676
+ await options.onTurnEnd(messages, result ?? { usage: undefined });
677
+ }
593
678
  if (closed)
594
679
  break;
595
680
  process.stdout.write("\x1b[36m> \x1b[0m");
596
681
  }
597
682
  }
598
683
  finally {
599
- sessionLock?.release();
600
684
  rl.close();
601
- // eslint-disable-next-line no-console -- terminal UX: goodbye
602
- console.log("bye");
685
+ if (options.banner !== false) {
686
+ // eslint-disable-next-line no-console -- terminal UX: goodbye
687
+ console.log("bye");
688
+ }
689
+ }
690
+ /* v8 ignore stop */
691
+ return { exitReason, toolResult: exitToolResult };
692
+ }
693
+ async function main(agentName, options) {
694
+ if (agentName)
695
+ (0, identity_1.setAgentName)(agentName);
696
+ const pasteDebounceMs = options?.pasteDebounceMs ?? 50;
697
+ // Fallback: apply pending updates for daemon-less direct CLI usage
698
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
699
+ await (0, update_hooks_1.applyPendingUpdates)((0, identity_1.getAgentBundlesRoot)(), (0, bundle_manifest_1.getPackageVersion)());
700
+ // Fail fast if provider is misconfigured (triggers human-readable error + exit)
701
+ (0, core_1.getProvider)();
702
+ // Resolve context kernel (identity + channel) for CLI
703
+ const friendsPath = path.join((0, identity_1.getAgentRoot)(), "friends");
704
+ const friendStore = new store_file_1.FileFriendStore(friendsPath);
705
+ const username = os.userInfo().username;
706
+ const hostname = os.hostname();
707
+ const localExternalId = `${username}@${hostname}`;
708
+ const resolver = new resolver_1.FriendResolver(friendStore, {
709
+ provider: "local",
710
+ externalId: localExternalId,
711
+ displayName: username,
712
+ channel: "cli",
713
+ });
714
+ const resolvedContext = await resolver.resolve();
715
+ const friendId = resolvedContext.friend.id;
716
+ const agentConfig = (0, identity_1.loadAgentConfig)();
717
+ (0, cli_logging_1.configureCliRuntimeLogger)(friendId, {
718
+ level: agentConfig.logging?.level,
719
+ sinks: agentConfig.logging?.sinks,
720
+ });
721
+ const sessPath = (0, config_1.sessionPath)(friendId, "cli", "session");
722
+ let sessionLock = null;
723
+ try {
724
+ sessionLock = (0, session_lock_1.acquireSessionLock)(`${sessPath}.lock`, (0, identity_1.getAgentName)());
725
+ }
726
+ catch (error) {
727
+ /* v8 ignore start -- integration: main() is interactive, lock tested in session-lock.test.ts @preserve */
728
+ if (error instanceof session_lock_1.SessionLockError) {
729
+ process.stderr.write(`${error.message}\n`);
730
+ return;
731
+ }
732
+ throw error;
733
+ /* v8 ignore stop */
734
+ }
735
+ // Load existing session or start fresh
736
+ const existing = (0, context_1.loadSession)(sessPath);
737
+ let sessionState = existing?.state;
738
+ const sessionMessages = existing?.messages && existing.messages.length > 0
739
+ ? existing.messages
740
+ : [{ role: "system", content: await (0, prompt_1.buildSystem)("cli", undefined, resolvedContext) }];
741
+ // Per-turn pipeline input: CLI capabilities and pending dir
742
+ const cliCapabilities = (0, channel_1.getChannelCapabilities)("cli");
743
+ const currentAgentName = (0, identity_1.getAgentName)();
744
+ const pendingDir = (0, pending_1.getPendingDir)(currentAgentName, friendId, "cli", "session");
745
+ const summarize = (0, core_1.createSummarize)();
746
+ try {
747
+ await runCliSession({
748
+ agentName: currentAgentName,
749
+ pasteDebounceMs,
750
+ messages: sessionMessages,
751
+ runTurn: async (messages, userInput, callbacks, signal) => {
752
+ // Run the full per-turn pipeline: resolve -> gate -> session -> drain -> runAgent -> postTurn -> tokens
753
+ // User message passed via input.messages so the pipeline can prepend pending messages to it.
754
+ const result = await (0, pipeline_1.handleInboundTurn)({
755
+ channel: "cli",
756
+ sessionKey: "session",
757
+ capabilities: cliCapabilities,
758
+ messages: [{ role: "user", content: userInput }],
759
+ continuityIngressTexts: getCliContinuityIngressTexts(userInput),
760
+ callbacks,
761
+ friendResolver: { resolve: () => Promise.resolve(resolvedContext) },
762
+ sessionLoader: { loadOrCreate: () => Promise.resolve({ messages, sessionPath: sessPath, state: sessionState }) },
763
+ pendingDir,
764
+ friendStore,
765
+ provider: "local",
766
+ externalId: localExternalId,
767
+ enforceTrustGate: trust_gate_1.enforceTrustGate,
768
+ drainPending: pending_1.drainPending,
769
+ drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)(currentAgentName, deferredFriendId),
770
+ runAgent: (msgs, cb, channel, sig, opts) => (0, core_1.runAgent)(msgs, cb, channel, sig, {
771
+ ...opts,
772
+ toolContext: {
773
+ /* v8 ignore next -- default no-op signin; pipeline provides the real one @preserve */
774
+ signin: async () => undefined,
775
+ ...opts?.toolContext,
776
+ summarize,
777
+ },
778
+ }),
779
+ postTurn: (turnMessages, sessionPathArg, usage, hooks, state) => {
780
+ (0, context_1.postTurn)(turnMessages, sessionPathArg, usage, hooks, state);
781
+ sessionState = state;
782
+ },
783
+ accumulateFriendTokens: tokens_1.accumulateFriendTokens,
784
+ signal,
785
+ runAgentOptions: {
786
+ toolChoiceRequired: (0, commands_1.getToolChoiceRequired)(),
787
+ traceId: (0, nerves_1.createTraceId)(),
788
+ },
789
+ });
790
+ // Handle gate rejection: display auto-reply if present
791
+ if (!result.gateResult.allowed) {
792
+ if ("autoReply" in result.gateResult && result.gateResult.autoReply) {
793
+ process.stdout.write(`${result.gateResult.autoReply}\n`);
794
+ }
795
+ }
796
+ return { usage: result.usage };
797
+ },
798
+ onNewSession: () => {
799
+ (0, context_1.deleteSession)(sessPath);
800
+ },
801
+ });
802
+ }
803
+ finally {
804
+ sessionLock?.release();
603
805
  }
604
806
  }