@ouro.bot/cli 0.1.0-alpha.2 → 0.1.0-alpha.200

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