@ouro.bot/cli 0.1.0-alpha.6 → 0.1.0-alpha.60

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