@ouro.bot/cli 0.1.0-alpha.22 → 0.1.0-alpha.220

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