@ouro.bot/cli 0.1.0-alpha.21 → 0.1.0-alpha.211

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 (233) hide show
  1. package/README.md +187 -191
  2. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +1 -1
  4. package/changelog.json +1318 -0
  5. package/dist/arc/attention-types.js +8 -0
  6. package/dist/arc/cares.js +140 -0
  7. package/dist/arc/episodes.js +119 -0
  8. package/dist/arc/intentions.js +133 -0
  9. package/dist/arc/json-store.js +120 -0
  10. package/dist/arc/obligations.js +237 -0
  11. package/dist/arc/presence.js +185 -0
  12. package/dist/heart/active-work.js +832 -0
  13. package/dist/heart/agent-entry.js +37 -2
  14. package/dist/heart/auth/auth-flow.js +444 -0
  15. package/dist/heart/bridges/manager.js +358 -0
  16. package/dist/heart/bridges/state-machine.js +135 -0
  17. package/dist/heart/bridges/store.js +123 -0
  18. package/dist/heart/commitments.js +111 -0
  19. package/dist/heart/config-registry.js +305 -0
  20. package/dist/heart/config.js +59 -30
  21. package/dist/heart/core.js +606 -131
  22. package/dist/heart/cross-chat-delivery.js +146 -0
  23. package/dist/heart/daemon/agent-config-check.js +149 -0
  24. package/dist/heart/daemon/agent-discovery.js +81 -0
  25. package/dist/heart/daemon/agent-service.js +360 -0
  26. package/dist/heart/daemon/cadence.js +70 -0
  27. package/dist/heart/daemon/cli-defaults.js +557 -0
  28. package/dist/heart/daemon/cli-exec.js +1847 -0
  29. package/dist/heart/daemon/cli-parse.js +759 -0
  30. package/dist/heart/daemon/cli-render.js +316 -0
  31. package/dist/heart/daemon/cli-types.js +8 -0
  32. package/dist/heart/daemon/daemon-cli.js +29 -1163
  33. package/dist/heart/daemon/daemon-entry.js +182 -4
  34. package/dist/heart/daemon/daemon-health.js +136 -0
  35. package/dist/heart/daemon/daemon-runtime-sync.js +153 -12
  36. package/dist/heart/daemon/daemon-tombstone.js +123 -0
  37. package/dist/heart/daemon/daemon.js +491 -18
  38. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  39. package/dist/heart/daemon/hooks/bundle-meta.js +206 -0
  40. package/dist/heart/daemon/inner-status.js +89 -0
  41. package/dist/heart/daemon/launchd.js +165 -0
  42. package/dist/heart/daemon/log-tailer.js +4 -3
  43. package/dist/heart/daemon/message-router.js +17 -8
  44. package/dist/heart/daemon/os-cron-deps.js +134 -0
  45. package/dist/heart/daemon/ouro-bot-entry.js +1 -1
  46. package/dist/heart/daemon/process-manager.js +123 -0
  47. package/dist/heart/daemon/run-hooks.js +39 -0
  48. package/dist/heart/daemon/runtime-logging.js +58 -15
  49. package/dist/heart/daemon/runtime-metadata.js +101 -0
  50. package/dist/heart/daemon/runtime-mode.js +67 -0
  51. package/dist/heart/daemon/safe-mode.js +161 -0
  52. package/dist/heart/daemon/sense-manager.js +71 -2
  53. package/dist/heart/daemon/session-id-resolver.js +131 -0
  54. package/dist/heart/daemon/skill-management-installer.js +94 -0
  55. package/dist/heart/daemon/socket-client.js +202 -0
  56. package/dist/heart/daemon/task-scheduler.js +3 -25
  57. package/dist/heart/daemon/thoughts.js +507 -0
  58. package/dist/heart/delegation.js +62 -0
  59. package/dist/heart/habits/habit-migration.js +181 -0
  60. package/dist/heart/habits/habit-parser.js +119 -0
  61. package/dist/heart/habits/habit-scheduler.js +369 -0
  62. package/dist/heart/{daemon → hatch}/hatch-flow.js +29 -119
  63. package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
  64. package/dist/heart/{daemon → hatch}/specialist-prompt.js +10 -7
  65. package/dist/heart/{daemon → hatch}/specialist-tools.js +49 -3
  66. package/dist/heart/identity.js +144 -55
  67. package/dist/heart/kicks.js +2 -20
  68. package/dist/heart/mcp/mcp-server.js +608 -0
  69. package/dist/heart/migrate-config.js +127 -0
  70. package/dist/heart/model-capabilities.js +48 -0
  71. package/dist/heart/outlook/outlook-http.js +439 -0
  72. package/dist/heart/outlook/outlook-read.js +1618 -0
  73. package/dist/heart/outlook/outlook-render.js +1032 -0
  74. package/dist/heart/outlook/outlook-types.js +7 -0
  75. package/dist/heart/outlook/outlook-view.js +194 -0
  76. package/dist/heart/progress-story.js +42 -0
  77. package/dist/heart/provider-failover.js +88 -0
  78. package/dist/heart/provider-ping.js +162 -0
  79. package/dist/heart/providers/anthropic-token.js +163 -0
  80. package/dist/heart/providers/anthropic.js +187 -41
  81. package/dist/heart/providers/azure.js +116 -10
  82. package/dist/heart/providers/github-copilot.js +157 -0
  83. package/dist/heart/providers/minimax.js +33 -3
  84. package/dist/heart/providers/openai-codex.js +51 -16
  85. package/dist/heart/session-activity.js +172 -0
  86. package/dist/heart/session-recall.js +216 -0
  87. package/dist/heart/start-of-turn-packet.js +330 -0
  88. package/dist/heart/streaming.js +36 -27
  89. package/dist/heart/sync.js +217 -0
  90. package/dist/heart/target-resolution.js +127 -0
  91. package/dist/heart/tempo.js +93 -0
  92. package/dist/heart/temporal-view.js +41 -0
  93. package/dist/heart/tool-activity-callbacks.js +36 -0
  94. package/dist/heart/tool-description.js +135 -0
  95. package/dist/heart/tool-loop.js +200 -0
  96. package/dist/heart/turn-context.js +358 -0
  97. package/dist/heart/turn-coordinator.js +28 -0
  98. package/dist/heart/versioning/ouro-bot-global-installer.js +128 -0
  99. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  100. package/dist/heart/{daemon → versioning}/ouro-path-installer.js +78 -35
  101. package/dist/heart/versioning/ouro-version-manager.js +171 -0
  102. package/dist/heart/versioning/staged-restart.js +138 -0
  103. package/dist/heart/versioning/update-checker.js +111 -0
  104. package/dist/heart/versioning/update-hooks.js +138 -0
  105. package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +41 -3
  106. package/dist/mind/associative-recall.js +126 -66
  107. package/dist/mind/bundle-manifest.js +19 -1
  108. package/dist/mind/context.js +125 -14
  109. package/dist/mind/{memory.js → diary.js} +73 -96
  110. package/dist/mind/embedding-provider.js +60 -0
  111. package/dist/mind/file-state.js +179 -0
  112. package/dist/mind/first-impressions.js +16 -2
  113. package/dist/mind/friends/channel.js +56 -0
  114. package/dist/mind/friends/group-context.js +144 -0
  115. package/dist/mind/friends/store-file.js +36 -0
  116. package/dist/mind/friends/trust-explanation.js +74 -0
  117. package/dist/mind/friends/types.js +8 -0
  118. package/dist/mind/journal-index.js +161 -0
  119. package/dist/mind/obligation-steering.js +221 -0
  120. package/dist/mind/pending.js +76 -9
  121. package/dist/mind/phrases.js +1 -0
  122. package/dist/mind/prompt.js +795 -108
  123. package/dist/mind/scrutiny.js +173 -0
  124. package/dist/mind/token-estimate.js +8 -12
  125. package/dist/nerves/coverage/audit.js +1 -1
  126. package/dist/nerves/coverage/file-completeness.js +47 -5
  127. package/dist/nerves/coverage/run-artifacts.js +1 -1
  128. package/dist/nerves/event-buffer.js +111 -0
  129. package/dist/nerves/index.js +63 -3
  130. package/dist/nerves/observation.js +20 -0
  131. package/dist/nerves/runtime.js +5 -1
  132. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  133. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  134. package/dist/outlook-ui/index.html +15 -0
  135. package/dist/repertoire/ado-client.js +15 -56
  136. package/dist/repertoire/ado-semantic.js +11 -5
  137. package/dist/repertoire/api-client.js +71 -0
  138. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  139. package/dist/repertoire/coding/context-pack.js +330 -0
  140. package/dist/repertoire/coding/feedback.js +197 -30
  141. package/dist/repertoire/coding/manager.js +149 -2
  142. package/dist/repertoire/coding/spawner.js +55 -9
  143. package/dist/repertoire/coding/tools.js +170 -7
  144. package/dist/repertoire/github-client.js +14 -55
  145. package/dist/repertoire/graph-client.js +11 -52
  146. package/dist/repertoire/guardrails.js +291 -0
  147. package/dist/repertoire/mcp-client.js +254 -0
  148. package/dist/repertoire/mcp-manager.js +251 -0
  149. package/dist/repertoire/shell-sessions.js +133 -0
  150. package/dist/repertoire/skills.js +14 -23
  151. package/dist/repertoire/tasks/board.js +43 -5
  152. package/dist/repertoire/tasks/fix.js +182 -0
  153. package/dist/repertoire/tasks/index.js +28 -10
  154. package/dist/repertoire/tasks/lifecycle.js +2 -2
  155. package/dist/repertoire/tasks/parser.js +3 -2
  156. package/dist/repertoire/tasks/scanner.js +194 -37
  157. package/dist/repertoire/tasks/transitions.js +11 -28
  158. package/dist/repertoire/tools-base.js +31 -771
  159. package/dist/repertoire/tools-bluebubbles.js +94 -0
  160. package/dist/repertoire/tools-bridge.js +141 -0
  161. package/dist/repertoire/tools-config.js +266 -0
  162. package/dist/repertoire/tools-continuity.js +248 -0
  163. package/dist/repertoire/tools-files.js +342 -0
  164. package/dist/repertoire/tools-flow.js +62 -0
  165. package/dist/repertoire/tools-github.js +1 -6
  166. package/dist/repertoire/tools-memory.js +347 -0
  167. package/dist/repertoire/tools-session.js +682 -0
  168. package/dist/repertoire/tools-shell.js +120 -0
  169. package/dist/repertoire/tools-surface.js +228 -0
  170. package/dist/repertoire/tools-teams.js +12 -59
  171. package/dist/repertoire/tools.js +132 -124
  172. package/dist/scripts/claude-code-hook.js +41 -0
  173. package/dist/scripts/claude-code-stop-hook.js +47 -0
  174. package/dist/senses/attention-queue.js +97 -0
  175. package/dist/senses/bluebubbles-client.js +102 -3
  176. package/dist/senses/bluebubbles-entry.js +2 -0
  177. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  178. package/dist/senses/bluebubbles-media.js +118 -23
  179. package/dist/senses/bluebubbles-model.js +12 -4
  180. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  181. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  182. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  183. package/dist/senses/bluebubbles.js +1008 -102
  184. package/dist/senses/cli/adapter.js +274 -0
  185. package/dist/senses/cli/ink-app.js +156 -0
  186. package/dist/senses/cli/inline-diff.js +64 -0
  187. package/dist/senses/cli/message-list.js +51 -0
  188. package/dist/senses/cli/ouro-tui.js +358 -0
  189. package/dist/senses/cli/spinner-imperative.js +135 -0
  190. package/dist/senses/cli/spinner.js +101 -0
  191. package/dist/senses/cli/status-line.js +60 -0
  192. package/dist/senses/cli/streaming-markdown.js +526 -0
  193. package/dist/senses/cli/tool-display.js +83 -0
  194. package/dist/senses/cli/tool-render.js +85 -0
  195. package/dist/senses/cli/tui-store.js +198 -0
  196. package/dist/senses/cli/virtual-list.js +35 -0
  197. package/dist/senses/cli-entry.js +1 -1
  198. package/dist/senses/cli-layout.js +187 -0
  199. package/dist/senses/cli.js +508 -243
  200. package/dist/senses/commands.js +65 -1
  201. package/dist/senses/continuity.js +94 -0
  202. package/dist/senses/habit-turn-message.js +108 -0
  203. package/dist/senses/inner-dialog-worker.js +112 -19
  204. package/dist/senses/inner-dialog.js +591 -84
  205. package/dist/senses/pipeline.js +559 -0
  206. package/dist/senses/shared-turn.js +196 -0
  207. package/dist/senses/surface-tool.js +68 -0
  208. package/dist/senses/teams.js +667 -120
  209. package/dist/senses/trust-gate.js +112 -2
  210. package/package.json +16 -6
  211. package/skills/configure-dev-tools.md +81 -0
  212. package/subagents/README.md +4 -70
  213. package/dist/heart/daemon/subagent-installer.js +0 -134
  214. package/dist/senses/debug-activity.js +0 -107
  215. package/subagents/work-doer.md +0 -235
  216. package/subagents/work-merger.md +0 -618
  217. package/subagents/work-planner.md +0 -382
  218. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  219. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  220. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  221. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  222. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  223. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  224. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  225. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  226. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  227. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  228. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  229. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  230. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  231. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  232. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  233. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
@@ -7,6 +7,8 @@ exports.getModel = getModel;
7
7
  exports.getProvider = getProvider;
8
8
  exports.createSummarize = createSummarize;
9
9
  exports.getProviderDisplayLabel = getProviderDisplayLabel;
10
+ exports.isExternalStateQuery = isExternalStateQuery;
11
+ exports.getSettleRetryError = getSettleRetryError;
10
12
  exports.stripLastToolCalls = stripLastToolCalls;
11
13
  exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
12
14
  exports.isTransientError = isTransientError;
@@ -16,9 +18,7 @@ const config_1 = require("./config");
16
18
  const identity_1 = require("./identity");
17
19
  const tools_1 = require("../repertoire/tools");
18
20
  const channel_1 = require("../mind/friends/channel");
19
- // Kick detection preserved but disabled — see comment in agent loop below.
20
- // import { detectKick } from "./kicks";
21
- // import type { KickReason } from "./kicks";
21
+ const tools_2 = require("../repertoire/tools");
22
22
  const runtime_1 = require("../nerves/runtime");
23
23
  const context_1 = require("../mind/context");
24
24
  const prompt_1 = require("../mind/prompt");
@@ -27,71 +27,96 @@ const anthropic_1 = require("./providers/anthropic");
27
27
  const azure_1 = require("./providers/azure");
28
28
  const minimax_1 = require("./providers/minimax");
29
29
  const openai_codex_1 = require("./providers/openai-codex");
30
- let _providerRuntime = null;
30
+ const github_copilot_1 = require("./providers/github-copilot");
31
+ const pending_1 = require("../mind/pending");
32
+ const identity_2 = require("./identity");
33
+ const socket_client_1 = require("./daemon/socket-client");
34
+ const obligations_1 = require("../arc/obligations");
35
+ const tool_loop_1 = require("./tool-loop");
36
+ const _providerRuntimes = {
37
+ human: null,
38
+ agent: null,
39
+ };
40
+ function getProviderRuntimeFingerprint(facing) {
41
+ const config = (0, identity_1.loadAgentConfig)();
42
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
43
+ const provider = facingConfig.provider;
44
+ const model = facingConfig.model;
45
+ const providerConfig = (0, config_1.getProviderConfig)(provider);
46
+ return JSON.stringify({ provider, model, ...providerConfig });
47
+ }
31
48
  function createProviderRegistry() {
32
49
  const factories = {
33
50
  azure: azure_1.createAzureProviderRuntime,
34
51
  anthropic: anthropic_1.createAnthropicProviderRuntime,
35
52
  minimax: minimax_1.createMinimaxProviderRuntime,
36
53
  "openai-codex": openai_codex_1.createOpenAICodexProviderRuntime,
54
+ "github-copilot": github_copilot_1.createGithubCopilotProviderRuntime,
37
55
  };
38
56
  return {
39
- resolve() {
40
- const provider = (0, identity_1.loadAgentConfig)().provider;
41
- return factories[provider]();
57
+ resolve(provider, model) {
58
+ const resolvedProvider = provider ?? (0, identity_1.loadAgentConfig)().humanFacing.provider;
59
+ const resolvedModel = model ?? (0, identity_1.loadAgentConfig)().humanFacing.model;
60
+ return factories[resolvedProvider](resolvedModel);
42
61
  },
43
62
  };
44
63
  }
45
- function getProviderRuntime() {
46
- if (!_providerRuntime) {
47
- try {
48
- _providerRuntime = createProviderRegistry().resolve();
49
- }
50
- catch (error) {
51
- const msg = error instanceof Error ? error.message : String(error);
52
- (0, runtime_1.emitNervesEvent)({
53
- level: "error",
54
- event: "engine.provider_init_error",
55
- component: "engine",
56
- message: msg,
57
- meta: {},
58
- });
59
- // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
60
- console.error(`\n[fatal] ${msg}\n`);
61
- process.exit(1);
62
- throw new Error("unreachable");
63
- }
64
- if (!_providerRuntime) {
65
- (0, runtime_1.emitNervesEvent)({
66
- level: "error",
67
- event: "engine.provider_init_error",
68
- component: "engine",
69
- message: "provider runtime could not be initialized.",
70
- meta: {},
71
- });
72
- process.exit(1);
73
- throw new Error("unreachable");
64
+ function getProviderRuntime(facing = "human") {
65
+ try {
66
+ const fingerprint = getProviderRuntimeFingerprint(facing);
67
+ const cached = _providerRuntimes[facing];
68
+ if (!cached || cached.fingerprint !== fingerprint) {
69
+ const config = (0, identity_1.loadAgentConfig)();
70
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
71
+ const runtime = createProviderRegistry().resolve(facingConfig.provider, facingConfig.model);
72
+ _providerRuntimes[facing] = runtime ? { fingerprint, runtime } : null;
74
73
  }
75
74
  }
76
- return _providerRuntime;
75
+ catch (error) {
76
+ const msg = error instanceof Error ? error.message : String(error);
77
+ (0, runtime_1.emitNervesEvent)({
78
+ level: "error",
79
+ event: "engine.provider_init_error",
80
+ component: "engine",
81
+ message: msg,
82
+ meta: {},
83
+ });
84
+ // eslint-disable-next-line no-console -- pre-boot guard: provider init failure
85
+ console.error(`\n[fatal] ${msg}\n`);
86
+ process.exit(1);
87
+ throw new Error("unreachable");
88
+ }
89
+ if (!_providerRuntimes[facing]) {
90
+ (0, runtime_1.emitNervesEvent)({
91
+ level: "error",
92
+ event: "engine.provider_init_error",
93
+ component: "engine",
94
+ message: "provider runtime could not be initialized.",
95
+ meta: {},
96
+ });
97
+ process.exit(1);
98
+ throw new Error("unreachable");
99
+ }
100
+ return _providerRuntimes[facing].runtime;
77
101
  }
78
102
  /**
79
- * Clear the cached provider runtime so the next call to getProviderRuntime()
80
- * re-creates it from current config. Used by the adoption specialist to
81
- * switch provider context without restarting the process.
103
+ * Clear the cached provider runtime so the next access re-creates it from
104
+ * current config. Runtime access also auto-refreshes when the selected
105
+ * provider fingerprint changes on disk.
82
106
  */
83
107
  function resetProviderRuntime() {
84
- _providerRuntime = null;
108
+ _providerRuntimes.human = null;
109
+ _providerRuntimes.agent = null;
85
110
  }
86
- function getModel() {
87
- return getProviderRuntime().model;
111
+ function getModel(facing = "human") {
112
+ return getProviderRuntime(facing).model;
88
113
  }
89
- function getProvider() {
90
- return getProviderRuntime().id;
114
+ function getProvider(facing = "human") {
115
+ return getProviderRuntime(facing).id;
91
116
  }
92
- function createSummarize() {
117
+ function createSummarize(facing = "human") {
93
118
  return async (transcript, instruction) => {
94
- const runtime = getProviderRuntime();
119
+ const runtime = getProviderRuntime(facing);
95
120
  const client = runtime.client;
96
121
  const response = await client.chat.completions.create({
97
122
  model: runtime.model,
@@ -104,22 +129,30 @@ function createSummarize() {
104
129
  return response.choices?.[0]?.message?.content ?? transcript;
105
130
  };
106
131
  }
107
- function getProviderDisplayLabel() {
108
- const model = getModel();
132
+ function getProviderDisplayLabel(facing = "human") {
133
+ const config = (0, identity_1.loadAgentConfig)();
134
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
135
+ const provider = facingConfig.provider;
136
+ const model = facingConfig.model || "unknown";
109
137
  const providerLabelBuilders = {
110
- azure: () => `azure openai (${(0, config_1.getAzureConfig)().deployment || "default"}, model: ${model})`,
138
+ azure: () => {
139
+ const azureCfg = (0, config_1.getAzureConfig)();
140
+ return `azure openai (${azureCfg.deployment || "default"}, model: ${model})`;
141
+ },
111
142
  anthropic: () => `anthropic (${model})`,
112
143
  minimax: () => `minimax (${model})`,
113
144
  "openai-codex": () => `openai codex (${model})`,
145
+ /* v8 ignore next -- branch: tested via display label unit test @preserve */
146
+ "github-copilot": () => `github copilot (${model})`,
114
147
  };
115
- return providerLabelBuilders[getProvider()]();
148
+ return providerLabelBuilders[provider]();
116
149
  }
117
150
  // Re-export tools, execTool, summarizeArgs from ./tools for backward compat
118
- var tools_2 = require("../repertoire/tools");
119
- Object.defineProperty(exports, "tools", { enumerable: true, get: function () { return tools_2.tools; } });
120
- Object.defineProperty(exports, "execTool", { enumerable: true, get: function () { return tools_2.execTool; } });
121
- Object.defineProperty(exports, "summarizeArgs", { enumerable: true, get: function () { return tools_2.summarizeArgs; } });
122
- Object.defineProperty(exports, "getToolsForChannel", { enumerable: true, get: function () { return tools_2.getToolsForChannel; } });
151
+ var tools_3 = require("../repertoire/tools");
152
+ Object.defineProperty(exports, "tools", { enumerable: true, get: function () { return tools_3.tools; } });
153
+ Object.defineProperty(exports, "execTool", { enumerable: true, get: function () { return tools_3.execTool; } });
154
+ Object.defineProperty(exports, "summarizeArgs", { enumerable: true, get: function () { return tools_3.summarizeArgs; } });
155
+ Object.defineProperty(exports, "getToolsForChannel", { enumerable: true, get: function () { return tools_3.getToolsForChannel; } });
123
156
  // Re-export streaming functions for backward compat
124
157
  var streaming_1 = require("./streaming");
125
158
  Object.defineProperty(exports, "streamChatCompletion", { enumerable: true, get: function () { return streaming_1.streamChatCompletion; } });
@@ -129,6 +162,108 @@ Object.defineProperty(exports, "toResponsesTools", { enumerable: true, get: func
129
162
  // Re-export prompt functions for backward compat
130
163
  var prompt_2 = require("../mind/prompt");
131
164
  Object.defineProperty(exports, "buildSystem", { enumerable: true, get: function () { return prompt_2.buildSystem; } });
165
+ // Sole-call tools must be the only tool call in a turn. When they appear
166
+ // alongside other tools, the sole-call tool is rejected with this message.
167
+ const SOLE_CALL_REJECTION = {
168
+ settle: "rejected: settle must be the only tool call. finish your work first, then call settle alone.",
169
+ observe: "rejected: observe must be the only tool call. call observe alone when you want to stay silent.",
170
+ ponder: "rejected: ponder must be the only tool call. finish your other work first, then call ponder alone.",
171
+ rest: "rejected: rest must be the only tool call. finish your work first, then call rest alone.",
172
+ };
173
+ const DELEGATION_REASON_PROSE_HANDOFF = {
174
+ explicit_reflection: "something in the conversation called for reflection",
175
+ cross_session: "this touches other conversations",
176
+ bridge_state: "there's shared work spanning sessions",
177
+ task_state: "there are active tasks that relate to this",
178
+ non_fast_path_tool: "this needs tools beyond a simple reply",
179
+ unresolved_obligation: "there's an unresolved commitment from an earlier conversation",
180
+ };
181
+ function buildPonderHandoffPacket(params) {
182
+ const reasons = params.delegationDecision?.reasons ?? [];
183
+ const reasonProse = reasons.length > 0
184
+ ? reasons.map((r) => DELEGATION_REASON_PROSE_HANDOFF[r]).join("; ")
185
+ : "this felt like it needed more thought";
186
+ const whoAsked = params.currentSession
187
+ ? params.currentSession.friendId
188
+ : "no one -- just thinking";
189
+ let holdingLine;
190
+ if (params.outwardClosureRequired && params.currentSession) {
191
+ holdingLine = `i'm holding something for ${params.currentSession.friendId}`;
192
+ }
193
+ else {
194
+ holdingLine = "nothing -- just thinking";
195
+ }
196
+ return [
197
+ "## what i need to think about",
198
+ params.topic,
199
+ "",
200
+ "## why this came up",
201
+ reasonProse,
202
+ "",
203
+ "## who asked",
204
+ whoAsked,
205
+ "",
206
+ "## what i'm holding",
207
+ holdingLine,
208
+ "",
209
+ "## thinking mode",
210
+ params.mode,
211
+ ].join("\n");
212
+ }
213
+ function parseSettlePayload(argumentsText) {
214
+ try {
215
+ const parsed = JSON.parse(argumentsText);
216
+ if (typeof parsed === "string") {
217
+ return { answer: parsed };
218
+ }
219
+ if (!parsed || typeof parsed !== "object") {
220
+ return {};
221
+ }
222
+ const answer = typeof parsed.answer === "string" ? parsed.answer : undefined;
223
+ const rawIntent = parsed.intent;
224
+ const intent = rawIntent === "complete" || rawIntent === "blocked" || rawIntent === "direct_reply"
225
+ ? rawIntent
226
+ : undefined;
227
+ return { answer, intent };
228
+ }
229
+ catch {
230
+ return {};
231
+ }
232
+ }
233
+ /** Returns true when a tool call queries external state (GitHub, npm registry). */
234
+ function isExternalStateQuery(toolName, args) {
235
+ if (toolName !== "shell")
236
+ return false;
237
+ const cmd = String(args.command ?? "");
238
+ return /\bgh\s+(pr|run|api|issue)\b/.test(cmd) || /\bnpm\s+(view|info|show)\b/.test(cmd);
239
+ }
240
+ function getSettleRetryError(mustResolveBeforeHandoff, intent, sawSteeringFollowUp, _delegationDecision, sawSendMessageSelf, sawPonder, _sawQuerySession, currentObligation, innerJob, sawExternalStateQuery) {
241
+ // Delegation adherence removed: the delegation decision is surfaced in the
242
+ // system prompt as a suggestion. Hard-gating settle caused infinite
243
+ // rejection loops where the agent couldn't respond to the user at all.
244
+ // The agent is free to follow or ignore the delegation hint.
245
+ // 2. Pending obligation not addressed
246
+ if (innerJob?.obligationStatus === "pending" && !sawSendMessageSelf && !sawPonder) {
247
+ return "you're still holding something from an earlier conversation -- someone is waiting for your answer. finish the thought first, or ponder to keep working on it privately.";
248
+ }
249
+ // 3. mustResolveBeforeHandoff + missing intent
250
+ if (mustResolveBeforeHandoff && !intent) {
251
+ return "your settle is missing required intent. when you must keep going until done or blocked, call settle again with answer plus intent=complete, blocked, or direct_reply.";
252
+ }
253
+ // 4. mustResolveBeforeHandoff + direct_reply without follow-up
254
+ if (mustResolveBeforeHandoff && intent === "direct_reply" && !sawSteeringFollowUp) {
255
+ return "your settle used intent=direct_reply without a newer steering follow-up. continue the unresolved work, or call settle again with intent=complete or blocked when appropriate.";
256
+ }
257
+ // 5. mustResolveBeforeHandoff + complete while a live return loop is still active
258
+ if (mustResolveBeforeHandoff && intent === "complete" && currentObligation && !sawSteeringFollowUp) {
259
+ return "you still owe the live session a visible return on this work. don't end the turn yet — continue until you've brought back the external-state update, or use intent=blocked with the concrete blocker.";
260
+ }
261
+ // 6. External-state grounding: obligation + complete requires fresh external verification
262
+ if (intent === "complete" && currentObligation && !sawExternalStateQuery && !sawSteeringFollowUp) {
263
+ return "you're claiming this work is complete, but the external state hasn't been verified this turn. ground your claim with a fresh check (gh pr view, npm view, gh run view, etc.) before calling settle.";
264
+ }
265
+ return null;
266
+ }
132
267
  // Re-export kick utilities for backward compat
133
268
  var kicks_1 = require("./kicks");
134
269
  Object.defineProperty(exports, "hasToolIntent", { enumerable: true, get: function () { return kicks_1.hasToolIntent; } });
@@ -278,8 +413,17 @@ function classifyTransientError(err) {
278
413
  }
279
414
  const MAX_RETRIES = 3;
280
415
  const RETRY_BASE_MS = 2000;
416
+ const TRANSIENT_RETRY_LABELS = {
417
+ "auth-failure": "auth error",
418
+ "usage-limit": "usage limit",
419
+ "rate-limit": "rate limited",
420
+ "server-error": "server error",
421
+ "network-error": "network error",
422
+ "unknown": "error",
423
+ };
281
424
  async function runAgent(messages, callbacks, channel, signal, options) {
282
- const providerRuntime = getProviderRuntime();
425
+ const facing = (0, channel_1.channelToFacing)(channel);
426
+ const providerRuntime = getProviderRuntime(facing);
283
427
  const provider = providerRuntime.id;
284
428
  const toolChoiceRequired = options?.toolChoiceRequired ?? true;
285
429
  const traceId = options?.traceId;
@@ -305,7 +449,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
305
449
  // so turn execution remains consistent and non-fatal.
306
450
  if (channel) {
307
451
  try {
308
- const refreshed = await (0, prompt_1.buildSystem)(channel, options, currentContext);
452
+ const buildSystemOptions = {
453
+ ...options,
454
+ providerCapabilities: providerRuntime.capabilities,
455
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
456
+ };
457
+ const refreshed = await (0, prompt_1.buildSystem)(channel, buildSystemOptions, currentContext);
309
458
  upsertSystemPrompt(messages, refreshed);
310
459
  }
311
460
  catch (error) {
@@ -328,31 +477,77 @@ async function runAgent(messages, callbacks, channel, signal, options) {
328
477
  }
329
478
  }
330
479
  await (0, associative_recall_1.injectAssociativeRecall)(messages);
331
- // kickCount and lastKickReason preserved but unused while kick detection is disabled.
332
- // let kickCount = 0;
333
- // let lastKickReason: KickReason | null = null;
334
480
  let done = false;
335
481
  let lastUsage;
336
482
  let overflowRetried = false;
337
483
  let retryCount = 0;
484
+ let outcome = "settled";
485
+ let completion;
486
+ let terminalError;
487
+ let terminalErrorClassification;
488
+ let sawSteeringFollowUp = false;
489
+ let mustResolveBeforeHandoffActive = options?.mustResolveBeforeHandoff === true;
490
+ let currentReasoningEffort = "medium";
491
+ let sawSendMessageSelf = false;
492
+ let sawPonder = false;
493
+ let sawQuerySession = false;
494
+ let sawBridgeManage = false;
495
+ let sawExternalStateQuery = false;
496
+ const toolLoopState = (0, tool_loop_1.createToolLoopState)();
338
497
  // Prevent MaxListenersExceeded warning — each iteration adds a listener
339
498
  try {
340
499
  require("events").setMaxListeners(50, signal);
341
500
  }
342
501
  catch { /* unsupported */ }
343
502
  const toolPreferences = currentContext?.friend?.toolPreferences;
344
- const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined, currentContext);
503
+ const baseTools = options?.tools ?? (0, tools_1.getToolsForChannel)(channel ? (0, channel_1.getChannelCapabilities)(channel) : undefined, toolPreferences && Object.keys(toolPreferences).length > 0 ? toolPreferences : undefined, currentContext, providerRuntime.capabilities);
504
+ // Augment tool context with reasoning effort controls from provider
505
+ const augmentedToolContext = options?.toolContext
506
+ ? {
507
+ ...options.toolContext,
508
+ supportedReasoningEfforts: providerRuntime.supportedReasoningEfforts,
509
+ setReasoningEffort: (level) => { currentReasoningEffort = level; },
510
+ activeWorkFrame: options?.activeWorkFrame,
511
+ }
512
+ : undefined;
345
513
  // Rebase provider-owned turn state from canonical messages at user-turn start.
346
514
  // This prevents stale provider caches from replaying prior-turn context.
347
515
  providerRuntime.resetTurnState(messages);
348
516
  while (!done) {
349
- // When toolChoiceRequired is true (the default), include final_answer
350
- // so the model can signal completion. With tool_choice: required, the
351
- // model must call a tool every turn — final_answer is how it exits.
352
- // Overridable via options.toolChoiceRequired = false (e.g. CLI).
353
- const activeTools = toolChoiceRequired ? [...baseTools, tools_1.finalAnswerTool] : baseTools;
517
+ // Channel-based tool filtering:
518
+ // - Inner dialog: exclude send_message (delivery via surface), observe (no one to observe)
519
+ // - 1:1 sessions: exclude observe (can't ignore someone talking directly to you)
520
+ // - Group chats: observe available
521
+ //
522
+ // ponder, settle/rest, surface, and observe are always assembled based on channel context.
523
+ // ponder is available in ALL channels (outer: think privately, inner: keep turning).
524
+ // Inner dialog gets restTool instead of settleTool (rest = end turn, gated by attention queue).
525
+ // toolChoiceRequired only controls whether tool_choice: "required" is set in the API call.
526
+ const isInnerDialog = channel === "inner";
527
+ const filteredBaseTools = isInnerDialog
528
+ ? baseTools.filter((t) => t.function.name !== "send_message")
529
+ : baseTools;
530
+ const activeTools = [
531
+ ...filteredBaseTools,
532
+ tools_1.ponderTool,
533
+ ...(isInnerDialog ? [tools_2.surfaceToolDef, tools_1.restTool] : []),
534
+ ...((currentContext?.isGroupChat || options?.isReactionSignal) && !isInnerDialog ? [tools_1.observeTool] : []),
535
+ ...(!isInnerDialog ? [tools_1.settleTool] : []),
536
+ ];
354
537
  const steeringFollowUps = options?.drainSteeringFollowUps?.() ?? [];
355
538
  if (steeringFollowUps.length > 0) {
539
+ const hasSupersedingFollowUp = steeringFollowUps.some((followUp) => followUp.effect === "clear_and_supersede");
540
+ if (hasSupersedingFollowUp) {
541
+ mustResolveBeforeHandoffActive = false;
542
+ options?.setMustResolveBeforeHandoff?.(false);
543
+ outcome = "superseded";
544
+ break;
545
+ }
546
+ if (steeringFollowUps.some((followUp) => followUp.effect === "set_no_handoff")) {
547
+ mustResolveBeforeHandoffActive = true;
548
+ options?.setMustResolveBeforeHandoff?.(true);
549
+ }
550
+ sawSteeringFollowUp = true;
356
551
  for (const followUp of steeringFollowUps) {
357
552
  messages.push({ role: "user", content: followUp.text });
358
553
  }
@@ -360,8 +555,10 @@ async function runAgent(messages, callbacks, channel, signal, options) {
360
555
  }
361
556
  // Yield so pending I/O (stdin Ctrl-C) can be processed between iterations
362
557
  await new Promise((r) => setImmediate(r));
363
- if (signal?.aborted)
558
+ if (signal?.aborted) {
559
+ outcome = "aborted";
364
560
  break;
561
+ }
365
562
  try {
366
563
  callbacks.onModelStart();
367
564
  const result = await providerRuntime.streamTurn({
@@ -371,6 +568,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
371
568
  signal,
372
569
  traceId,
373
570
  toolChoiceRequired,
571
+ reasoningEffort: currentReasoningEffort,
572
+ eagerSettleStreaming: true,
374
573
  });
375
574
  // Track usage from the latest API call
376
575
  if (result.usage)
@@ -394,52 +593,76 @@ async function runAgent(messages, callbacks, channel, signal, options) {
394
593
  if (reasoningItems.length > 0) {
395
594
  msg._reasoning_items = reasoningItems;
396
595
  }
596
+ // Store thinking blocks (Anthropic) on the assistant message for round-tripping
597
+ const thinkingItems = result.outputItems.filter((item) => "type" in item && (item.type === "thinking" || item.type === "redacted_thinking"));
598
+ if (thinkingItems.length > 0) {
599
+ msg._thinking_blocks = thinkingItems;
600
+ }
601
+ // Phase annotation for Codex provider
602
+ const hasPhaseAnnotation = providerRuntime.capabilities.has("phase-annotation");
603
+ const isSoleSettle = result.toolCalls.length === 1 && result.toolCalls[0].name === "settle";
604
+ if (hasPhaseAnnotation) {
605
+ msg.phase = isSoleSettle ? "settle" : "commentary";
606
+ }
397
607
  if (!result.toolCalls.length) {
398
- // Kick detection is disabled while tool_choice: required + final_answer
399
- // is the primary loop control mechanism. The model should never reach
400
- // this path (tool_choice: required forces a tool call), but if it does,
401
- // accept the response as-is rather than risk false-positive kicks.
402
- //
403
- // Preserved for future use — re-enable by uncommenting:
404
- // const kick = detectKick(result.content, options);
405
- // if (kick) {
406
- // kickCount++;
407
- // lastKickReason = kick.reason;
408
- // callbacks.onKick?.();
409
- // const kickContent = result.content
410
- // ? result.content + "\n\n" + kick.message
411
- // : kick.message;
412
- // messages.push({ role: "assistant", content: kickContent });
413
- // providerRuntime.resetTurnState(messages);
414
- // continue;
415
- // }
608
+ // No tool calls — accept response as-is.
609
+ // (Kick detection disabled; tool_choice: required + settle
610
+ // is the primary loop control. See src/heart/kicks.ts to re-enable.)
416
611
  messages.push(msg);
417
612
  done = true;
418
613
  }
419
614
  else {
420
- // Check for final_answer sole call: intercept before tool execution
421
- const isSoleFinalAnswer = result.toolCalls.length === 1 && result.toolCalls[0].name === "final_answer";
422
- if (isSoleFinalAnswer) {
423
- // Extract answer from the tool call arguments.
424
- // Supports: {"answer":"text"}, "text" (JSON string), retry on failure.
425
- let answer;
426
- try {
427
- const parsed = JSON.parse(result.toolCalls[0].arguments);
428
- if (typeof parsed === "string") {
429
- answer = parsed;
430
- }
431
- else if (parsed.answer != null) {
432
- answer = parsed.answer;
433
- }
434
- // else: valid JSON but no answer field — answer stays undefined (retry)
615
+ // Check for settle sole call: intercept before tool execution
616
+ if (isSoleSettle) {
617
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed settle args @preserve */
618
+ const settleArgs = (() => { try {
619
+ return JSON.parse(result.toolCalls[0].arguments);
435
620
  }
436
621
  catch {
437
- // JSON parsing failed (e.g. truncated output) — answer stays undefined (retry)
622
+ return {};
623
+ } })();
624
+ callbacks.onToolStart("settle", settleArgs);
625
+ // Inner dialog attention queue gate: reject settle if items remain
626
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
627
+ if (isInnerDialog && attentionQueue && attentionQueue.length > 0) {
628
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
629
+ callbacks.onClearText?.();
630
+ messages.push(msg);
631
+ const gateMessage = "you're holding thoughts someone is waiting for — surface them before you settle.";
632
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
633
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
634
+ continue;
438
635
  }
439
- if (answer != null) {
440
- if (result.finalAnswerStreamed) {
636
+ // Extract answer from the tool call arguments.
637
+ // Supports: {"answer":"text","intent":"..."} or "text" (JSON string).
638
+ const { answer, intent } = parseSettlePayload(result.toolCalls[0].arguments);
639
+ // Inner dialog settle: no CompletionMetadata, "(settled)" ack
640
+ if (isInnerDialog) {
641
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
642
+ messages.push(msg);
643
+ const settled = "(settled)";
644
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: settled });
645
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, settled);
646
+ outcome = "settled";
647
+ done = true;
648
+ continue;
649
+ }
650
+ const retryError = getSettleRetryError(mustResolveBeforeHandoffActive, intent, sawSteeringFollowUp, options?.delegationDecision, sawSendMessageSelf, sawPonder, sawQuerySession, options?.currentObligation ?? null, options?.activeWorkFrame?.inner?.job, sawExternalStateQuery);
651
+ const deliveredAnswer = answer;
652
+ const validDirectReply = mustResolveBeforeHandoffActive && intent === "direct_reply" && sawSteeringFollowUp;
653
+ const validTerminalIntent = intent === "complete" || intent === "blocked";
654
+ const validClosure = deliveredAnswer != null
655
+ && !retryError
656
+ && (!mustResolveBeforeHandoffActive || validDirectReply || validTerminalIntent);
657
+ if (validClosure) {
658
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), true);
659
+ completion = {
660
+ answer: deliveredAnswer,
661
+ intent: validDirectReply ? "direct_reply" : intent === "blocked" ? "blocked" : "complete",
662
+ };
663
+ if (result.settleStreamed) {
441
664
  // The streaming layer already parsed and emitted the answer
442
- // progressively via FinalAnswerParser. Skip clearing and
665
+ // progressively via SettleParser. Skip clearing and
443
666
  // re-emitting to avoid double-delivery.
444
667
  }
445
668
  else {
@@ -447,37 +670,229 @@ async function runAgent(messages, callbacks, channel, signal, options) {
447
670
  callbacks.onClearText?.();
448
671
  // Emit the answer through the callback pipeline so channels receive it.
449
672
  // Never truncate -- channel adapters handle splitting long messages.
450
- callbacks.onTextChunk(answer);
673
+ callbacks.onTextChunk(deliveredAnswer);
451
674
  }
452
- // Keep the full assistant message (with tool_calls) for debuggability,
453
- // plus a synthetic tool response so the conversation stays valid on resume.
454
675
  messages.push(msg);
455
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: "(delivered)" });
456
- providerRuntime.appendToolOutput(result.toolCalls[0].id, "(delivered)");
457
- done = true;
676
+ if (validDirectReply) {
677
+ const resumeWork = "direct reply delivered. resume the unresolved obligation now and keep working until you can finish or clearly report that you are blocked.";
678
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: resumeWork });
679
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, resumeWork);
680
+ }
681
+ else {
682
+ const delivered = "(delivered)";
683
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: delivered });
684
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, delivered);
685
+ outcome = intent === "blocked" ? "blocked" : "settled";
686
+ done = true;
687
+ }
458
688
  }
459
689
  else {
460
- // Answer is undefined -- the model's final_answer was incomplete or
690
+ // Answer is undefined -- the model's settle was incomplete or
461
691
  // malformed. Clear any partial streamed text or noise, then push the
462
692
  // assistant msg + error tool result and let the model try again.
693
+ callbacks.onToolEnd("settle", (0, tools_1.summarizeArgs)("settle", settleArgs), false);
463
694
  callbacks.onClearText?.();
464
- const retryError = "your final_answer was incomplete or malformed. call final_answer again with your complete response.";
465
695
  messages.push(msg);
466
- messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: retryError });
467
- providerRuntime.appendToolOutput(result.toolCalls[0].id, retryError);
696
+ const toolRetryMessage = retryError
697
+ ?? "your settle was incomplete or malformed. call settle again with your complete response.";
698
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: toolRetryMessage });
699
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, toolRetryMessage);
700
+ }
701
+ continue;
702
+ }
703
+ // Check for observe sole call: intercept before tool execution
704
+ const isSoleObserve = result.toolCalls.length === 1 && result.toolCalls[0].name === "observe";
705
+ if (isSoleObserve) {
706
+ /* v8 ignore next -- defensive: JSON.parse catch for malformed observe args @preserve */
707
+ const observeArgs = (() => { try {
708
+ return JSON.parse(result.toolCalls[0].arguments);
468
709
  }
710
+ catch {
711
+ return {};
712
+ } })();
713
+ let reason;
714
+ if (typeof observeArgs?.reason === "string")
715
+ reason = observeArgs.reason;
716
+ callbacks.onToolStart("observe", observeArgs);
717
+ (0, runtime_1.emitNervesEvent)({
718
+ component: "engine",
719
+ event: "engine.observe",
720
+ message: "agent observed without responding",
721
+ meta: { ...(reason ? { reason } : {}) },
722
+ });
723
+ callbacks.onToolEnd("observe", (0, tools_1.summarizeArgs)("observe", observeArgs), true);
724
+ messages.push(msg);
725
+ const silenced = "(silenced)";
726
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: silenced });
727
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, silenced);
728
+ outcome = "observed";
729
+ done = true;
730
+ continue;
731
+ }
732
+ // Check for ponder sole call: intercept before tool execution
733
+ const isSolePonder = result.toolCalls.length === 1 && result.toolCalls[0].name === "ponder";
734
+ if (isSolePonder) {
735
+ let parsedArgs = {};
736
+ try {
737
+ parsedArgs = JSON.parse(result.toolCalls[0].arguments);
738
+ }
739
+ catch { /* ignore */ }
740
+ callbacks.onToolStart("ponder", parsedArgs);
741
+ const currentSession = options?.toolContext?.currentSession;
742
+ const isInnerChannel = currentSession?.friendId === "self" && currentSession?.channel === "inner";
743
+ if (!isInnerChannel) {
744
+ // Outer session: thought and say are required
745
+ const thought = typeof parsedArgs.thought === "string" ? parsedArgs.thought : undefined;
746
+ const say = typeof parsedArgs.say === "string" ? parsedArgs.say : undefined;
747
+ if (!thought || !say) {
748
+ callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), false);
749
+ messages.push(msg);
750
+ const errorMsg = "ponder requires both thought and say when called from a conversation. thought is what needs more thinking; say is what you tell them before going quiet.";
751
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: errorMsg });
752
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, errorMsg);
753
+ continue;
754
+ }
755
+ // Emit outward say text
756
+ callbacks.onClearText?.();
757
+ callbacks.onTextChunk(say);
758
+ // Build handoff packet and enqueue
759
+ const handoffContent = buildPonderHandoffPacket({
760
+ topic: thought,
761
+ mode: "reflect",
762
+ delegationDecision: options?.delegationDecision,
763
+ currentSession: currentSession ?? null,
764
+ currentObligation: options?.currentObligation ?? null,
765
+ outwardClosureRequired: options?.delegationDecision?.outwardClosureRequired ?? false,
766
+ });
767
+ const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_2.getAgentName)());
768
+ // Create obligation FIRST so we can attach its ID to the pending message
769
+ let createdObligationId;
770
+ if (currentSession) {
771
+ try {
772
+ const obligation = (0, obligations_1.createObligation)((0, identity_2.getAgentRoot)(), {
773
+ origin: {
774
+ friendId: currentSession.friendId,
775
+ channel: currentSession.channel,
776
+ key: currentSession.key,
777
+ },
778
+ content: thought,
779
+ });
780
+ createdObligationId = obligation.id;
781
+ }
782
+ catch {
783
+ /* v8 ignore next -- defensive: obligation store write failure should not break ponder @preserve */
784
+ }
785
+ }
786
+ const envelope = {
787
+ from: (0, identity_2.getAgentName)(),
788
+ friendId: "self",
789
+ channel: "inner",
790
+ key: "dialog",
791
+ content: handoffContent,
792
+ timestamp: Date.now(),
793
+ ...(currentSession ? {
794
+ delegatedFrom: {
795
+ friendId: currentSession.friendId,
796
+ channel: currentSession.channel,
797
+ key: currentSession.key,
798
+ },
799
+ obligationStatus: "pending",
800
+ /* v8 ignore next -- defensive: createdObligationId is undefined only when obligation store write fails @preserve */
801
+ ...(createdObligationId ? { obligationId: createdObligationId } : {}),
802
+ } : {}),
803
+ };
804
+ (0, pending_1.queuePendingMessage)(pendingDir, envelope);
805
+ try {
806
+ await (0, socket_client_1.requestInnerWake)((0, identity_2.getAgentName)());
807
+ }
808
+ catch { /* daemon may not be running */ }
809
+ callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), true);
810
+ sawPonder = true;
811
+ messages.push(msg);
812
+ const ack = "(pondering)";
813
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
814
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
815
+ (0, runtime_1.emitNervesEvent)({
816
+ component: "engine",
817
+ event: "engine.pondered",
818
+ message: "pondering",
819
+ meta: { hasThought: true, hasSay: true, contentSnippet: thought.slice(0, 80) },
820
+ });
821
+ }
822
+ else {
823
+ // Inner dialog: parameterless, enqueue synthetic pending WITHOUT delegatedFrom
824
+ const pendingDir = (0, pending_1.getInnerDialogPendingDir)((0, identity_2.getAgentName)());
825
+ const envelope = {
826
+ from: (0, identity_2.getAgentName)(),
827
+ friendId: "self",
828
+ channel: "inner",
829
+ key: "dialog",
830
+ content: "continuing to think...",
831
+ timestamp: Date.now(),
832
+ };
833
+ (0, pending_1.queuePendingMessage)(pendingDir, envelope);
834
+ callbacks.onToolEnd("ponder", (0, tools_1.summarizeArgs)("ponder", parsedArgs), true);
835
+ sawPonder = true;
836
+ messages.push(msg);
837
+ const ack = "(pondering)";
838
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
839
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
840
+ (0, runtime_1.emitNervesEvent)({
841
+ component: "engine",
842
+ event: "engine.pondered",
843
+ message: "pondering from inner dialog",
844
+ meta: { inner: true },
845
+ });
846
+ }
847
+ outcome = "pondered";
848
+ done = true;
849
+ continue;
850
+ }
851
+ // Check for rest sole call: intercept before tool execution
852
+ const isSoleRest = result.toolCalls.length === 1 && result.toolCalls[0].name === "rest";
853
+ if (isSoleRest) {
854
+ const restArgs = (() => { try {
855
+ return JSON.parse(result.toolCalls[0].arguments);
856
+ }
857
+ catch {
858
+ return {};
859
+ } })();
860
+ callbacks.onToolStart("rest", restArgs);
861
+ // Attention queue gate: reject rest if items remain
862
+ const attentionQueue = (augmentedToolContext ?? options?.toolContext)?.delegatedOrigins;
863
+ if (attentionQueue && attentionQueue.length > 0) {
864
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), false);
865
+ messages.push(msg);
866
+ const gateMessage = "you're holding thoughts someone is waiting for — surface them before you rest.";
867
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: gateMessage });
868
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, gateMessage);
869
+ continue;
870
+ }
871
+ callbacks.onToolEnd("rest", (0, tools_1.summarizeArgs)("rest", restArgs), true);
872
+ messages.push(msg);
873
+ const ack = "(resting)";
874
+ messages.push({ role: "tool", tool_call_id: result.toolCalls[0].id, content: ack });
875
+ providerRuntime.appendToolOutput(result.toolCalls[0].id, ack);
876
+ (0, runtime_1.emitNervesEvent)({
877
+ component: "engine",
878
+ event: "engine.rested",
879
+ message: "resting until next heartbeat",
880
+ meta: {},
881
+ });
882
+ outcome = "rested";
883
+ done = true;
469
884
  continue;
470
885
  }
471
886
  messages.push(msg);
472
- // SHARED: execute tools (final_answer in mixed calls is rejected inline)
887
+ // Execute tools (sole-call tools in mixed calls are rejected inline)
473
888
  for (const tc of result.toolCalls) {
474
889
  if (signal?.aborted)
475
890
  break;
476
- // Intercept final_answer in mixed call: reject it
477
- if (tc.name === "final_answer") {
478
- const rejection = "rejected: final_answer must be the only tool call. Finish your work first, then call final_answer alone.";
479
- messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
480
- providerRuntime.appendToolOutput(tc.id, rejection);
891
+ // Reject sole-call tools when mixed with other tool calls
892
+ const soleCallRejection = SOLE_CALL_REJECTION[tc.name];
893
+ if (soleCallRejection) {
894
+ messages.push({ role: "tool", tool_call_id: tc.id, content: soleCallRejection });
895
+ providerRuntime.appendToolOutput(tc.id, soleCallRejection);
481
896
  continue;
482
897
  }
483
898
  let args = {};
@@ -487,9 +902,32 @@ async function runAgent(messages, callbacks, channel, signal, options) {
487
902
  catch {
488
903
  /* ignore */
489
904
  }
905
+ if (tc.name === "send_message" && args.friendId === "self") {
906
+ sawSendMessageSelf = true;
907
+ }
908
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
909
+ if (tc.name === "query_session")
910
+ sawQuerySession = true;
911
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
912
+ if (tc.name === "bridge_manage")
913
+ sawBridgeManage = true;
914
+ /* v8 ignore next -- flag tested via truth-check integration tests @preserve */
915
+ if (isExternalStateQuery(tc.name, args))
916
+ sawExternalStateQuery = true;
490
917
  const argSummary = (0, tools_1.summarizeArgs)(tc.name, args);
491
- // Confirmation check for mutate tools
492
- if ((0, tools_1.isConfirmationRequired)(tc.name) && !options?.skipConfirmation) {
918
+ const toolLoop = (0, tool_loop_1.detectToolLoop)(toolLoopState, tc.name, args);
919
+ if (toolLoop.stuck) {
920
+ const rejection = `loop guard: ${toolLoop.message}`;
921
+ callbacks.onToolStart(tc.name, args);
922
+ callbacks.onToolEnd(tc.name, argSummary, false);
923
+ messages.push({ role: "tool", tool_call_id: tc.id, content: rejection });
924
+ providerRuntime.appendToolOutput(tc.id, rejection);
925
+ continue;
926
+ }
927
+ // Confirmation check for mutate tools.
928
+ // confirmationAlwaysRequired tools cannot be bypassed by skipConfirmation.
929
+ const needsConfirmation = (0, tools_1.isConfirmationRequired)(tc.name) && (!options?.skipConfirmation || (0, tools_1.isConfirmationAlwaysRequired)(tc.name));
930
+ if (needsConfirmation) {
493
931
  let decision = "denied";
494
932
  if (callbacks.onConfirmAction) {
495
933
  decision = await callbacks.onConfirmAction(tc.name, args);
@@ -508,14 +946,15 @@ async function runAgent(messages, callbacks, channel, signal, options) {
508
946
  let success;
509
947
  try {
510
948
  const execToolFn = options?.execTool ?? tools_1.execTool;
511
- toolResult = await execToolFn(tc.name, args, options?.toolContext);
949
+ toolResult = await execToolFn(tc.name, args, augmentedToolContext ?? options?.toolContext);
512
950
  success = true;
513
951
  }
514
952
  catch (e) {
515
953
  toolResult = `error: ${e}`;
516
954
  success = false;
517
955
  }
518
- callbacks.onToolEnd(tc.name, argSummary, success);
956
+ (0, tool_loop_1.recordToolOutcome)(toolLoopState, tc.name, args, toolResult, success);
957
+ callbacks.onToolEnd(tc.name, (0, tools_1.buildToolResultSummary)(tc.name, args, toolResult, success), success);
519
958
  messages.push({ role: "tool", tool_call_id: tc.id, content: toolResult });
520
959
  providerRuntime.appendToolOutput(tc.id, toolResult);
521
960
  }
@@ -525,6 +964,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
525
964
  // Abort is not an error — just stop cleanly
526
965
  if (signal?.aborted) {
527
966
  stripLastToolCalls(messages);
967
+ outcome = "aborted";
528
968
  break;
529
969
  }
530
970
  // Context overflow: trim aggressively and retry once
@@ -542,7 +982,16 @@ async function runAgent(messages, callbacks, channel, signal, options) {
542
982
  if (isTransientError(e) && retryCount < MAX_RETRIES) {
543
983
  retryCount++;
544
984
  const delay = RETRY_BASE_MS * Math.pow(2, retryCount - 1);
545
- const cause = classifyTransientError(e);
985
+ let classification;
986
+ try {
987
+ classification = providerRuntime.classifyError(e instanceof Error ? e : /* v8 ignore next -- defensive: errors are always Error instances @preserve */ new Error(String(e)));
988
+ }
989
+ catch {
990
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
991
+ classification = classifyTransientError(e);
992
+ }
993
+ /* v8 ignore next -- defensive: all classifications have labels @preserve */
994
+ const cause = TRANSIENT_RETRY_LABELS[classification] ?? classification;
546
995
  callbacks.onError(new Error(`${cause}, retrying in ${delay / 1000}s (${retryCount}/${MAX_RETRIES})...`), "transient");
547
996
  // Wait with abort support
548
997
  const aborted = await new Promise((resolve) => {
@@ -559,21 +1008,42 @@ async function runAgent(messages, callbacks, channel, signal, options) {
559
1008
  });
560
1009
  if (aborted) {
561
1010
  stripLastToolCalls(messages);
1011
+ outcome = "aborted";
562
1012
  break;
563
1013
  }
564
1014
  providerRuntime.resetTurnState(messages);
565
1015
  continue;
566
1016
  }
567
- callbacks.onError(e instanceof Error ? e : new Error(String(e)), "terminal");
1017
+ terminalError = e instanceof Error ? e : new Error(String(e));
1018
+ try {
1019
+ terminalErrorClassification = providerRuntime.classifyError(terminalError);
1020
+ }
1021
+ catch {
1022
+ /* v8 ignore next -- defensive: classifyError should not throw @preserve */
1023
+ terminalErrorClassification = "unknown";
1024
+ }
1025
+ /* v8 ignore start — auth-failure guidance: tested via provider error classification tests @preserve */
1026
+ if (terminalErrorClassification === "auth-failure") {
1027
+ const agentName = (0, identity_2.getAgentName)();
1028
+ const currentProvider = providerRuntime.id;
1029
+ callbacks.onError(new Error(`${currentProvider} (${providerRuntime.model}) encountered an error. ` +
1030
+ `Run \`ouro auth --agent ${agentName} --provider ${currentProvider}\` to refresh credentials, ` +
1031
+ `or \`ouro auth switch --agent ${agentName} --provider <other>\` to switch providers.`), "terminal");
1032
+ }
1033
+ else {
1034
+ callbacks.onError(terminalError, "terminal");
1035
+ }
1036
+ /* v8 ignore stop */
568
1037
  (0, runtime_1.emitNervesEvent)({
569
1038
  level: "error",
570
1039
  event: "engine.error",
571
1040
  trace_id: traceId,
572
1041
  component: "engine",
573
- message: e instanceof Error ? e.message : String(e),
574
- meta: {},
1042
+ message: terminalError.message,
1043
+ meta: { errorClassification: terminalErrorClassification },
575
1044
  });
576
1045
  stripLastToolCalls(messages);
1046
+ outcome = "errored";
577
1047
  done = true;
578
1048
  }
579
1049
  }
@@ -582,7 +1052,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
582
1052
  trace_id: traceId,
583
1053
  component: "engine",
584
1054
  message: "runAgent turn completed",
585
- meta: { done },
1055
+ meta: { done, sawPonder, sawQuerySession, sawBridgeManage },
586
1056
  });
587
- return { usage: lastUsage };
1057
+ return {
1058
+ usage: lastUsage,
1059
+ outcome,
1060
+ completion,
1061
+ ...(terminalError ? { error: terminalError, errorClassification: terminalErrorClassification } : {}),
1062
+ };
588
1063
  }