@ouro.bot/cli 0.1.0-alpha.18 → 0.1.0-alpha.181

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 (185) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +3 -2
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +3 -3
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +187 -191
  5. package/changelog.json +1219 -0
  6. package/dist/heart/active-work.js +633 -0
  7. package/dist/heart/bridges/manager.js +358 -0
  8. package/dist/heart/bridges/state-machine.js +135 -0
  9. package/dist/heart/bridges/store.js +123 -0
  10. package/dist/heart/commitments.js +105 -0
  11. package/dist/heart/config.js +40 -30
  12. package/dist/heart/core.js +620 -124
  13. package/dist/heart/cross-chat-delivery.js +146 -0
  14. package/dist/heart/daemon/agent-discovery.js +81 -0
  15. package/dist/heart/daemon/agent-service.js +360 -0
  16. package/dist/heart/daemon/auth-flow.js +477 -0
  17. package/dist/heart/daemon/cadence.js +70 -0
  18. package/dist/heart/daemon/daemon-cli.js +2476 -206
  19. package/dist/heart/daemon/daemon-entry.js +157 -4
  20. package/dist/heart/daemon/daemon-health.js +136 -0
  21. package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
  22. package/dist/heart/daemon/daemon-tombstone.js +123 -0
  23. package/dist/heart/daemon/daemon.js +449 -17
  24. package/dist/heart/daemon/habit-migration.js +181 -0
  25. package/dist/heart/daemon/habit-parser.js +119 -0
  26. package/dist/heart/daemon/habit-scheduler.js +369 -0
  27. package/dist/heart/daemon/hatch-animation.js +10 -3
  28. package/dist/heart/daemon/hatch-flow.js +30 -111
  29. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  30. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  31. package/dist/heart/daemon/inner-status.js +89 -0
  32. package/dist/heart/daemon/launchd.js +165 -0
  33. package/dist/heart/daemon/log-tailer.js +4 -3
  34. package/dist/heart/daemon/mcp-server.js +591 -0
  35. package/dist/heart/daemon/message-router.js +17 -8
  36. package/dist/heart/daemon/os-cron-deps.js +134 -0
  37. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  38. package/dist/heart/daemon/ouro-path-installer.js +78 -34
  39. package/dist/heart/daemon/ouro-version-manager.js +171 -0
  40. package/dist/heart/daemon/outlook-http.js +399 -0
  41. package/dist/heart/daemon/outlook-read.js +1291 -0
  42. package/dist/heart/daemon/outlook-render.js +1032 -0
  43. package/dist/heart/daemon/outlook-types.js +7 -0
  44. package/dist/heart/daemon/outlook-view.js +194 -0
  45. package/dist/heart/daemon/process-manager.js +75 -0
  46. package/dist/heart/daemon/run-hooks.js +39 -0
  47. package/dist/heart/daemon/runtime-logging.js +58 -15
  48. package/dist/heart/daemon/runtime-metadata.js +219 -0
  49. package/dist/heart/daemon/runtime-mode.js +67 -0
  50. package/dist/heart/daemon/safe-mode.js +161 -0
  51. package/dist/heart/daemon/sense-manager.js +50 -2
  52. package/dist/heart/daemon/session-id-resolver.js +131 -0
  53. package/dist/heart/daemon/skill-management-installer.js +94 -0
  54. package/dist/heart/daemon/socket-client.js +202 -0
  55. package/dist/heart/daemon/specialist-orchestrator.js +2 -2
  56. package/dist/heart/daemon/specialist-prompt.js +13 -9
  57. package/dist/heart/daemon/specialist-tools.js +78 -9
  58. package/dist/heart/daemon/staged-restart.js +114 -0
  59. package/dist/heart/daemon/task-scheduler.js +3 -25
  60. package/dist/heart/daemon/thoughts.js +507 -0
  61. package/dist/heart/daemon/update-checker.js +111 -0
  62. package/dist/heart/daemon/update-hooks.js +138 -0
  63. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  64. package/dist/heart/delegation.js +62 -0
  65. package/dist/heart/identity.js +136 -55
  66. package/dist/heart/kicks.js +2 -20
  67. package/dist/heart/migrate-config.js +127 -0
  68. package/dist/heart/model-capabilities.js +48 -0
  69. package/dist/heart/obligations.js +197 -0
  70. package/dist/heart/progress-story.js +42 -0
  71. package/dist/heart/provider-failover.js +88 -0
  72. package/dist/heart/provider-ping.js +172 -0
  73. package/dist/heart/providers/anthropic-token.js +163 -0
  74. package/dist/heart/providers/anthropic.js +196 -36
  75. package/dist/heart/providers/azure.js +116 -10
  76. package/dist/heart/providers/github-copilot.js +157 -0
  77. package/dist/heart/providers/minimax.js +33 -3
  78. package/dist/heart/providers/openai-codex.js +51 -16
  79. package/dist/heart/session-activity.js +172 -0
  80. package/dist/heart/session-recall.js +216 -0
  81. package/dist/heart/streaming.js +62 -32
  82. package/dist/heart/target-resolution.js +127 -0
  83. package/dist/heart/tool-activity-callbacks.js +36 -0
  84. package/dist/heart/tool-description.js +135 -0
  85. package/dist/heart/tool-loop.js +200 -0
  86. package/dist/heart/turn-coordinator.js +28 -0
  87. package/dist/mind/associative-recall.js +122 -32
  88. package/dist/mind/bundle-manifest.js +14 -0
  89. package/dist/mind/context.js +125 -14
  90. package/dist/mind/{memory.js → diary.js} +70 -56
  91. package/dist/mind/file-state.js +179 -0
  92. package/dist/mind/first-impressions.js +16 -2
  93. package/dist/mind/friends/channel.js +56 -0
  94. package/dist/mind/friends/group-context.js +144 -0
  95. package/dist/mind/friends/store-file.js +19 -0
  96. package/dist/mind/friends/trust-explanation.js +74 -0
  97. package/dist/mind/friends/types.js +8 -0
  98. package/dist/mind/journal-index.js +161 -0
  99. package/dist/mind/obligation-steering.js +221 -0
  100. package/dist/mind/obligations.js +134 -0
  101. package/dist/mind/pending.js +76 -9
  102. package/dist/mind/phrases.js +1 -0
  103. package/dist/mind/prompt.js +721 -102
  104. package/dist/mind/scrutiny.js +173 -0
  105. package/dist/mind/token-estimate.js +8 -12
  106. package/dist/nerves/cli-logging.js +15 -2
  107. package/dist/nerves/coverage/audit.js +1 -1
  108. package/dist/nerves/coverage/run-artifacts.js +1 -1
  109. package/dist/nerves/event-buffer.js +111 -0
  110. package/dist/nerves/index.js +63 -3
  111. package/dist/nerves/observation.js +20 -0
  112. package/dist/nerves/runtime.js +5 -1
  113. package/dist/outlook-ui/assets/index-DN6vVYPm.css +1 -0
  114. package/dist/outlook-ui/assets/index-M1l1tDTX.js +61 -0
  115. package/dist/outlook-ui/index.html +15 -0
  116. package/dist/repertoire/ado-semantic.js +11 -5
  117. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  118. package/dist/repertoire/coding/context-pack.js +254 -0
  119. package/dist/repertoire/coding/feedback.js +197 -30
  120. package/dist/repertoire/coding/manager.js +149 -2
  121. package/dist/repertoire/coding/spawner.js +55 -9
  122. package/dist/repertoire/coding/tools.js +170 -7
  123. package/dist/repertoire/guardrails.js +291 -0
  124. package/dist/repertoire/mcp-client.js +254 -0
  125. package/dist/repertoire/mcp-manager.js +198 -0
  126. package/dist/repertoire/shell-sessions.js +133 -0
  127. package/dist/repertoire/skills.js +14 -23
  128. package/dist/repertoire/tasks/board.js +43 -5
  129. package/dist/repertoire/tasks/fix.js +182 -0
  130. package/dist/repertoire/tasks/index.js +28 -10
  131. package/dist/repertoire/tasks/lifecycle.js +2 -2
  132. package/dist/repertoire/tasks/parser.js +3 -2
  133. package/dist/repertoire/tasks/scanner.js +194 -37
  134. package/dist/repertoire/tasks/transitions.js +11 -28
  135. package/dist/repertoire/tools-base.js +1111 -327
  136. package/dist/repertoire/tools-bluebubbles.js +94 -0
  137. package/dist/repertoire/tools-github.js +1 -6
  138. package/dist/repertoire/tools-teams.js +12 -59
  139. package/dist/repertoire/tools.js +318 -124
  140. package/dist/scripts/claude-code-hook.js +41 -0
  141. package/dist/scripts/claude-code-stop-hook.js +47 -0
  142. package/dist/senses/attention-queue.js +97 -0
  143. package/dist/senses/bluebubbles-client.js +102 -3
  144. package/dist/senses/bluebubbles-entry.js +2 -0
  145. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  146. package/dist/senses/bluebubbles-media.js +118 -23
  147. package/dist/senses/bluebubbles-model.js +12 -4
  148. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  149. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  150. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  151. package/dist/senses/bluebubbles.js +1008 -102
  152. package/dist/senses/cli/adapter.js +274 -0
  153. package/dist/senses/cli/ink-app.js +156 -0
  154. package/dist/senses/cli/inline-diff.js +64 -0
  155. package/dist/senses/cli/message-list.js +51 -0
  156. package/dist/senses/cli/ouro-tui.js +323 -0
  157. package/dist/senses/cli/spinner-imperative.js +135 -0
  158. package/dist/senses/cli/spinner.js +101 -0
  159. package/dist/senses/cli/status-line.js +60 -0
  160. package/dist/senses/cli/streaming-markdown.js +525 -0
  161. package/dist/senses/cli/tool-display.js +83 -0
  162. package/dist/senses/cli/tool-render.js +85 -0
  163. package/dist/senses/cli/tui-store.js +198 -0
  164. package/dist/senses/cli/virtual-list.js +35 -0
  165. package/dist/senses/cli-entry.js +1 -1
  166. package/dist/senses/cli-layout.js +187 -0
  167. package/dist/senses/cli.js +593 -240
  168. package/dist/senses/commands.js +38 -1
  169. package/dist/senses/continuity.js +94 -0
  170. package/dist/senses/habit-turn-message.js +108 -0
  171. package/dist/senses/inner-dialog-worker.js +112 -19
  172. package/dist/senses/inner-dialog.js +592 -84
  173. package/dist/senses/pipeline.js +545 -0
  174. package/dist/senses/shared-turn.js +196 -0
  175. package/dist/senses/surface-tool.js +95 -0
  176. package/dist/senses/teams.js +667 -120
  177. package/dist/senses/trust-gate.js +112 -2
  178. package/package.json +16 -5
  179. package/skills/configure-dev-tools.md +81 -0
  180. package/subagents/README.md +4 -70
  181. package/dist/heart/daemon/subagent-installer.js +0 -134
  182. package/dist/senses/debug-activity.js +0 -107
  183. package/subagents/work-doer.md +0 -235
  184. package/subagents/work-merger.md +0 -618
  185. package/subagents/work-planner.md +0 -382
@@ -0,0 +1,477 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.readAgentConfigForAgent = readAgentConfigForAgent;
37
+ exports.writeAgentProviderSelection = writeAgentProviderSelection;
38
+ exports.loadAgentSecrets = loadAgentSecrets;
39
+ exports.writeProviderCredentials = writeProviderCredentials;
40
+ exports.writeAgentModel = writeAgentModel;
41
+ exports.collectRuntimeAuthCredentials = collectRuntimeAuthCredentials;
42
+ exports.resolveHatchCredentials = resolveHatchCredentials;
43
+ exports.runRuntimeAuthFlow = runRuntimeAuthFlow;
44
+ const child_process_1 = require("child_process");
45
+ const fs = __importStar(require("fs"));
46
+ const os = __importStar(require("os"));
47
+ const path = __importStar(require("path"));
48
+ const runtime_1 = require("../../nerves/runtime");
49
+ const identity_1 = require("../identity");
50
+ const migrate_config_1 = require("../migrate-config");
51
+ const ANTHROPIC_SETUP_TOKEN_PREFIX = "sk-ant-oat01-";
52
+ const ANTHROPIC_SETUP_TOKEN_MIN_LENGTH = 80;
53
+ const DEFAULT_SECRETS_TEMPLATE = {
54
+ providers: {
55
+ azure: {
56
+ modelName: "gpt-4o-mini",
57
+ apiKey: "",
58
+ endpoint: "",
59
+ deployment: "",
60
+ apiVersion: "2025-04-01-preview",
61
+ },
62
+ minimax: {
63
+ model: "MiniMax-M2.7",
64
+ apiKey: "",
65
+ },
66
+ anthropic: {
67
+ model: "claude-opus-4-6",
68
+ setupToken: "",
69
+ refreshToken: "",
70
+ expiresAt: 0,
71
+ },
72
+ "openai-codex": {
73
+ model: "gpt-5.4",
74
+ oauthAccessToken: "",
75
+ },
76
+ "github-copilot": {
77
+ model: "claude-sonnet-4.6",
78
+ githubToken: "",
79
+ baseUrl: "",
80
+ },
81
+ },
82
+ teams: {
83
+ clientId: "",
84
+ clientSecret: "",
85
+ tenantId: "",
86
+ },
87
+ oauth: {
88
+ graphConnectionName: "graph",
89
+ adoConnectionName: "ado",
90
+ githubConnectionName: "",
91
+ },
92
+ teamsChannel: {
93
+ skipConfirmation: true,
94
+ port: 3978,
95
+ },
96
+ integrations: {
97
+ perplexityApiKey: "",
98
+ openaiEmbeddingsApiKey: "",
99
+ },
100
+ };
101
+ function deepMerge(defaults, partial) {
102
+ const result = { ...defaults };
103
+ for (const key of Object.keys(partial)) {
104
+ const left = result[key];
105
+ const right = partial[key];
106
+ if (right !== null &&
107
+ typeof right === "object" &&
108
+ !Array.isArray(right) &&
109
+ left !== null &&
110
+ typeof left === "object" &&
111
+ !Array.isArray(left)) {
112
+ result[key] = deepMerge(left, right);
113
+ continue;
114
+ }
115
+ result[key] = right;
116
+ }
117
+ return result;
118
+ }
119
+ function readJsonRecord(filePath, label) {
120
+ try {
121
+ const raw = fs.readFileSync(filePath, "utf8");
122
+ const parsed = JSON.parse(raw);
123
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
124
+ throw new Error("expected object");
125
+ }
126
+ return parsed;
127
+ }
128
+ catch (error) {
129
+ throw new Error(`Failed to read ${label} at ${filePath}: ${String(error)}`);
130
+ }
131
+ }
132
+ function readAgentConfigForAgent(agentName, bundlesRoot = (0, identity_1.getAgentBundlesRoot)()) {
133
+ const agentRoot = path.join(bundlesRoot, `${agentName}.ouro`);
134
+ const configPath = path.join(agentRoot, "agent.json");
135
+ let parsed = readJsonRecord(configPath, "agent config");
136
+ // Inline migration: v1 -> v2
137
+ const version = typeof parsed.version === "number" ? parsed.version : 1;
138
+ if (version < 2) {
139
+ (0, migrate_config_1.migrateAgentConfigV1ToV2)(agentRoot);
140
+ parsed = readJsonRecord(configPath, "agent config");
141
+ }
142
+ // Validate v2 required facing fields
143
+ const humanFacing = parsed.humanFacing;
144
+ const agentFacing = parsed.agentFacing;
145
+ if (!humanFacing || typeof humanFacing !== "object") {
146
+ throw new Error(`agent.json at ${configPath} has unsupported provider '${String(parsed.provider)}'`);
147
+ }
148
+ const provider = humanFacing.provider;
149
+ if (provider !== "azure" &&
150
+ provider !== "anthropic" &&
151
+ provider !== "minimax" &&
152
+ provider !== "openai-codex" &&
153
+ provider !== "github-copilot") {
154
+ throw new Error(`agent.json at ${configPath} has unsupported provider '${String(provider)}'`);
155
+ }
156
+ if (!agentFacing || typeof agentFacing !== "object") {
157
+ throw new Error(`agent.json at ${configPath} has unsupported provider '${String(parsed.provider)}'`);
158
+ }
159
+ return {
160
+ configPath,
161
+ config: parsed,
162
+ };
163
+ }
164
+ function writeAgentProviderSelection(agentName, facing, provider, bundlesRoot = (0, identity_1.getAgentBundlesRoot)()) {
165
+ const { configPath, config } = readAgentConfigForAgent(agentName, bundlesRoot);
166
+ const facingKey = facing === "human" ? "humanFacing" : "agentFacing";
167
+ const nextConfig = {
168
+ ...config,
169
+ [facingKey]: { ...config[facingKey], provider },
170
+ };
171
+ fs.writeFileSync(configPath, `${JSON.stringify(nextConfig, null, 2)}\n`, "utf8");
172
+ (0, runtime_1.emitNervesEvent)({
173
+ component: "daemon",
174
+ event: "daemon.auth_provider_selected",
175
+ message: "updated agent provider selection after auth flow",
176
+ meta: { agentName, facing, provider, configPath },
177
+ });
178
+ return configPath;
179
+ }
180
+ function resolveAgentSecretsPath(agentName, deps = {}) {
181
+ if (deps.secretsRoot)
182
+ return path.join(deps.secretsRoot, agentName, "secrets.json");
183
+ const homeDir = deps.homeDir ?? os.homedir();
184
+ return (0, identity_1.getAgentSecretsPath)(agentName).replace(os.homedir(), homeDir);
185
+ }
186
+ function loadAgentSecrets(agentName, deps = {}) {
187
+ const secretsPath = resolveAgentSecretsPath(agentName, deps);
188
+ const secretsDir = path.dirname(secretsPath);
189
+ fs.mkdirSync(secretsDir, { recursive: true });
190
+ let onDisk = {};
191
+ try {
192
+ onDisk = readJsonRecord(secretsPath, "secrets config");
193
+ }
194
+ catch (error) {
195
+ const message = error.message;
196
+ if (!message.includes("ENOENT"))
197
+ throw error;
198
+ }
199
+ return {
200
+ secretsPath,
201
+ secrets: deepMerge(DEFAULT_SECRETS_TEMPLATE, onDisk),
202
+ };
203
+ }
204
+ function writeSecrets(secretsPath, secrets) {
205
+ fs.writeFileSync(secretsPath, `${JSON.stringify(secrets, null, 2)}\n`, "utf8");
206
+ }
207
+ function writeProviderCredentials(agentName, provider, credentials, deps = {}) {
208
+ const { secretsPath, secrets } = loadAgentSecrets(agentName, deps);
209
+ applyCredentials(secrets, provider, credentials);
210
+ writeSecrets(secretsPath, secrets);
211
+ return { secretsPath, secrets };
212
+ }
213
+ function writeAgentModel(agentName, facing, modelName, deps = {}) {
214
+ const { configPath, config } = readAgentConfigForAgent(agentName, deps.bundlesRoot);
215
+ const facingKey = facing === "human" ? "humanFacing" : "agentFacing";
216
+ const facingBlock = config[facingKey];
217
+ const previousModel = facingBlock.model;
218
+ const provider = facingBlock.provider;
219
+ const nextConfig = {
220
+ ...config,
221
+ [facingKey]: { ...facingBlock, model: modelName },
222
+ };
223
+ fs.writeFileSync(configPath, `${JSON.stringify(nextConfig, null, 2)}\n`, "utf8");
224
+ (0, runtime_1.emitNervesEvent)({
225
+ component: "daemon",
226
+ event: "daemon.config_model_updated",
227
+ message: "updated agent model in agent.json",
228
+ meta: { agentName, facing, provider, modelName, previousModel, configPath },
229
+ });
230
+ return { configPath, provider, previousModel };
231
+ }
232
+ function readCodexAccessToken(homeDir) {
233
+ const authPath = path.join(homeDir, ".codex", "auth.json");
234
+ try {
235
+ const raw = fs.readFileSync(authPath, "utf8");
236
+ const parsed = JSON.parse(raw);
237
+ const token = parsed?.tokens?.access_token;
238
+ return typeof token === "string" ? token.trim() : "";
239
+ }
240
+ catch {
241
+ return "";
242
+ }
243
+ }
244
+ function ensurePromptInput(promptInput, provider) {
245
+ if (promptInput)
246
+ return promptInput;
247
+ throw new Error(`No prompt input is available for ${provider} authentication.`);
248
+ }
249
+ function validateAnthropicToken(token) {
250
+ const trimmed = token.trim();
251
+ if (!trimmed) {
252
+ throw new Error("No Anthropic setup token was provided.");
253
+ }
254
+ if (!trimmed.startsWith(ANTHROPIC_SETUP_TOKEN_PREFIX)) {
255
+ throw new Error(`Invalid Anthropic setup token format. Expected prefix ${ANTHROPIC_SETUP_TOKEN_PREFIX}.`);
256
+ }
257
+ if (trimmed.length < ANTHROPIC_SETUP_TOKEN_MIN_LENGTH) {
258
+ throw new Error("Anthropic setup token looks too short.");
259
+ }
260
+ return trimmed;
261
+ }
262
+ async function collectRuntimeAuthCredentials(input, deps) {
263
+ const spawnSync = deps.spawnSync ?? child_process_1.spawnSync;
264
+ const homeDir = deps.homeDir ?? os.homedir();
265
+ if (input.provider === "github-copilot") {
266
+ let token = process.env.GH_TOKEN?.trim() || "";
267
+ if (!token) {
268
+ const result = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });
269
+ token = (result.status === 0 && result.stdout ? result.stdout.trim() : "");
270
+ }
271
+ if (!token) {
272
+ (0, runtime_1.emitNervesEvent)({
273
+ component: "daemon",
274
+ event: "daemon.auth_gh_login_start",
275
+ message: "starting gh auth login for runtime auth",
276
+ meta: { agentName: input.agentName },
277
+ });
278
+ const loginResult = spawnSync("gh", ["auth", "login"], { stdio: "inherit" });
279
+ if (loginResult.status !== 0) {
280
+ throw new Error("'gh auth login' failed. Install the GitHub CLI (gh) and try again.");
281
+ }
282
+ const retryResult = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });
283
+ /* v8 ignore next -- branch: retry after login always succeeds in tests @preserve */
284
+ token = (retryResult.status === 0 && retryResult.stdout ? retryResult.stdout.trim() : "");
285
+ /* v8 ignore next -- defensive: gh auth login succeeded but token still missing @preserve */
286
+ if (!token) {
287
+ throw new Error("gh auth login completed but no token was found. Run `gh auth login` and try again.");
288
+ }
289
+ }
290
+ const response = await fetch("https://api.github.com/copilot_internal/user", {
291
+ headers: { Authorization: `Bearer ${token}` },
292
+ });
293
+ if (!response.ok) {
294
+ throw new Error(`GitHub Copilot endpoint discovery failed (HTTP ${response.status}). Ensure your GitHub account has Copilot access.`);
295
+ }
296
+ const body = await response.json();
297
+ const baseUrl = body?.endpoints?.api;
298
+ /* v8 ignore next -- defensive: valid response but missing endpoints field @preserve */
299
+ if (!baseUrl) {
300
+ throw new Error("GitHub Copilot endpoint discovery returned no endpoints.api. Ensure your GitHub account has Copilot access.");
301
+ }
302
+ return { githubToken: token, baseUrl };
303
+ }
304
+ if (input.provider === "openai-codex") {
305
+ let token = readCodexAccessToken(homeDir);
306
+ if (!token) {
307
+ (0, runtime_1.emitNervesEvent)({
308
+ component: "daemon",
309
+ event: "daemon.auth_codex_login_start",
310
+ message: "starting codex login for runtime auth",
311
+ meta: { agentName: input.agentName },
312
+ });
313
+ const result = spawnSync("codex", ["login"], { stdio: "inherit" });
314
+ if (result.error) {
315
+ throw new Error(`Failed to run 'codex login': ${result.error.message}`);
316
+ }
317
+ if (result.status !== 0) {
318
+ throw new Error(`'codex login' exited with status ${result.status}.`);
319
+ }
320
+ token = readCodexAccessToken(homeDir);
321
+ if (!token) {
322
+ throw new Error("Codex login completed but no token was found in ~/.codex/auth.json. Re-run `codex login` and try again.");
323
+ }
324
+ }
325
+ return { oauthAccessToken: token };
326
+ }
327
+ if (input.provider === "anthropic") {
328
+ (0, runtime_1.emitNervesEvent)({
329
+ component: "daemon",
330
+ event: "daemon.auth_claude_setup_start",
331
+ message: "starting claude setup-token for runtime auth",
332
+ meta: { agentName: input.agentName },
333
+ });
334
+ const result = spawnSync("claude", ["setup-token"], { stdio: "inherit" });
335
+ if (result.error) {
336
+ throw new Error(`Failed to run 'claude setup-token': ${result.error.message}`);
337
+ }
338
+ if (result.status !== 0) {
339
+ throw new Error(`'claude setup-token' exited with status ${result.status}.`);
340
+ }
341
+ const prompt = ensurePromptInput(input.promptInput, input.provider);
342
+ const setupToken = validateAnthropicToken(await prompt("Paste the setup token from `claude setup-token`: "));
343
+ // Exchange the setup token for an access+refresh token pair so auto-refresh works.
344
+ // The setup token IS the initial access token — we use it as a refresh token to
345
+ // get back a proper token pair from the OAuth endpoint.
346
+ /* v8 ignore start -- token exchange: requires live Anthropic OAuth endpoint @preserve */
347
+ try {
348
+ const { refreshAnthropicToken } = await Promise.resolve().then(() => __importStar(require("../providers/anthropic-token")));
349
+ const tokenState = await refreshAnthropicToken(setupToken);
350
+ if (tokenState) {
351
+ return {
352
+ setupToken: tokenState.accessToken,
353
+ refreshToken: tokenState.refreshToken,
354
+ expiresAt: tokenState.expiresAt,
355
+ };
356
+ }
357
+ }
358
+ catch {
359
+ // Exchange failed — use the raw setup token as-is (it'll work until expiry)
360
+ }
361
+ /* v8 ignore stop */
362
+ return { setupToken };
363
+ }
364
+ if (input.provider === "minimax") {
365
+ const prompt = ensurePromptInput(input.promptInput, input.provider);
366
+ const apiKey = (await prompt("MiniMax API key: ")).trim();
367
+ if (!apiKey)
368
+ throw new Error("MiniMax API key is required.");
369
+ return { apiKey };
370
+ }
371
+ const prompt = ensurePromptInput(input.promptInput, input.provider);
372
+ const apiKey = (await prompt("Azure API key: ")).trim();
373
+ const endpoint = (await prompt("Azure endpoint: ")).trim();
374
+ const deployment = (await prompt("Azure deployment: ")).trim();
375
+ if (!apiKey || !endpoint || !deployment) {
376
+ throw new Error("Azure API key, endpoint, and deployment are required.");
377
+ }
378
+ return { apiKey, endpoint, deployment };
379
+ }
380
+ async function resolveHatchCredentials(input) {
381
+ const prompt = input.promptInput;
382
+ const credentials = { ...(input.credentials ?? {}) };
383
+ if (input.provider === "github-copilot" && !credentials.githubToken && input.runAuthFlow) {
384
+ const result = await input.runAuthFlow({
385
+ agentName: input.agentName,
386
+ provider: "github-copilot",
387
+ promptInput: prompt,
388
+ });
389
+ Object.assign(credentials, result.credentials);
390
+ }
391
+ if (input.provider === "anthropic" && !credentials.setupToken && input.runAuthFlow) {
392
+ const result = await input.runAuthFlow({
393
+ agentName: input.agentName,
394
+ provider: "anthropic",
395
+ promptInput: prompt,
396
+ });
397
+ Object.assign(credentials, result.credentials);
398
+ }
399
+ if (input.provider === "anthropic" && !credentials.setupToken && prompt) {
400
+ credentials.setupToken = await prompt("Anthropic setup-token: ");
401
+ }
402
+ if (input.provider === "openai-codex" && !credentials.oauthAccessToken && input.runAuthFlow) {
403
+ const result = await input.runAuthFlow({
404
+ agentName: input.agentName,
405
+ provider: "openai-codex",
406
+ promptInput: prompt,
407
+ });
408
+ Object.assign(credentials, result.credentials);
409
+ }
410
+ if (input.provider === "openai-codex" && !credentials.oauthAccessToken && prompt) {
411
+ credentials.oauthAccessToken = await prompt("OpenAI Codex OAuth token: ");
412
+ }
413
+ if (input.provider === "minimax" && !credentials.apiKey && prompt) {
414
+ credentials.apiKey = await prompt("MiniMax API key: ");
415
+ }
416
+ if (input.provider === "azure") {
417
+ if (!credentials.apiKey && prompt)
418
+ credentials.apiKey = await prompt("Azure API key: ");
419
+ if (!credentials.endpoint && prompt)
420
+ credentials.endpoint = await prompt("Azure endpoint: ");
421
+ if (!credentials.deployment && prompt)
422
+ credentials.deployment = await prompt("Azure deployment: ");
423
+ }
424
+ return credentials;
425
+ }
426
+ function applyCredentials(secrets, provider, credentials) {
427
+ if (provider === "anthropic") {
428
+ secrets.providers.anthropic.setupToken = credentials.setupToken.trim();
429
+ /* v8 ignore start -- token refresh fields: populated when OAuth exchange succeeds @preserve */
430
+ if (credentials.refreshToken)
431
+ secrets.providers.anthropic.refreshToken = credentials.refreshToken;
432
+ if (credentials.expiresAt)
433
+ secrets.providers.anthropic.expiresAt = credentials.expiresAt;
434
+ /* v8 ignore stop */
435
+ return;
436
+ }
437
+ if (provider === "github-copilot") {
438
+ secrets.providers["github-copilot"].githubToken = credentials.githubToken.trim();
439
+ secrets.providers["github-copilot"].baseUrl = credentials.baseUrl.trim();
440
+ return;
441
+ }
442
+ if (provider === "openai-codex") {
443
+ secrets.providers["openai-codex"].oauthAccessToken = credentials.oauthAccessToken.trim();
444
+ return;
445
+ }
446
+ if (provider === "minimax") {
447
+ secrets.providers.minimax.apiKey = credentials.apiKey.trim();
448
+ return;
449
+ }
450
+ secrets.providers.azure.apiKey = credentials.apiKey.trim();
451
+ secrets.providers.azure.endpoint = credentials.endpoint.trim();
452
+ secrets.providers.azure.deployment = credentials.deployment.trim();
453
+ }
454
+ async function runRuntimeAuthFlow(input, deps = {}) {
455
+ (0, runtime_1.emitNervesEvent)({
456
+ component: "daemon",
457
+ event: "daemon.auth_flow_start",
458
+ message: "starting runtime auth flow",
459
+ meta: { agentName: input.agentName, provider: input.provider },
460
+ });
461
+ const homeDir = deps.homeDir ?? os.homedir();
462
+ const credentials = await collectRuntimeAuthCredentials(input, deps);
463
+ const { secretsPath } = writeProviderCredentials(input.agentName, input.provider, credentials, { homeDir });
464
+ (0, runtime_1.emitNervesEvent)({
465
+ component: "daemon",
466
+ event: "daemon.auth_flow_end",
467
+ message: "completed runtime auth flow",
468
+ meta: { agentName: input.agentName, provider: input.provider, secretsPath },
469
+ });
470
+ return {
471
+ agentName: input.agentName,
472
+ provider: input.provider,
473
+ secretsPath,
474
+ message: `authenticated ${input.agentName} with ${input.provider}`,
475
+ credentials,
476
+ };
477
+ }
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_CADENCE_MS = void 0;
4
+ exports.parseCadenceToCron = parseCadenceToCron;
5
+ exports.parseCadenceToMs = parseCadenceToMs;
6
+ const runtime_1 = require("../../nerves/runtime");
7
+ exports.DEFAULT_CADENCE_MS = 30 * 60 * 1000; // 30 minutes
8
+ /**
9
+ * Parse a cadence shorthand (e.g. "30m", "2h", "1d") into a cron string.
10
+ * Also accepts raw cron strings (5 space-separated fields) and passes them through.
11
+ * Returns null for invalid input.
12
+ */
13
+ function parseCadenceToCron(raw) {
14
+ if (typeof raw !== "string")
15
+ return null;
16
+ const value = raw.trim();
17
+ if (!value)
18
+ return null;
19
+ // Cron format (minute hour day month weekday)
20
+ if (/^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/.test(value)) {
21
+ return value;
22
+ }
23
+ const cadenceMatch = /^(\d+)(m|h|d)$/.exec(value);
24
+ if (!cadenceMatch)
25
+ return null;
26
+ const interval = Number.parseInt(cadenceMatch[1], 10);
27
+ if (!Number.isFinite(interval) || interval <= 0)
28
+ return null;
29
+ (0, runtime_1.emitNervesEvent)({
30
+ event: "daemon.cadence_parsed",
31
+ component: "daemon",
32
+ message: "parsed cadence shorthand to cron",
33
+ meta: { raw: value, interval, unit: cadenceMatch[2] },
34
+ });
35
+ const unit = cadenceMatch[2];
36
+ if (unit === "m")
37
+ return `*/${interval} * * * *`;
38
+ if (unit === "h")
39
+ return `0 */${interval} * * *`;
40
+ return `0 0 */${interval} * *`;
41
+ }
42
+ /**
43
+ * Parse a cadence shorthand (e.g. "30m", "2h", "1d") into milliseconds.
44
+ * Returns null for invalid input.
45
+ */
46
+ function parseCadenceToMs(raw) {
47
+ if (typeof raw !== "string")
48
+ return null;
49
+ const value = raw.trim();
50
+ if (!value)
51
+ return null;
52
+ const match = /^(\d+)(m|h|d)$/.exec(value);
53
+ if (!match)
54
+ return null;
55
+ const interval = Number.parseInt(match[1], 10);
56
+ if (!Number.isFinite(interval) || interval <= 0)
57
+ return null;
58
+ (0, runtime_1.emitNervesEvent)({
59
+ event: "daemon.cadence_parsed_ms",
60
+ component: "daemon",
61
+ message: "parsed cadence shorthand to milliseconds",
62
+ meta: { raw: value, interval, unit: match[2] },
63
+ });
64
+ const unit = match[2];
65
+ if (unit === "m")
66
+ return interval * 60 * 1000;
67
+ if (unit === "h")
68
+ return interval * 60 * 60 * 1000;
69
+ return interval * 24 * 60 * 60 * 1000;
70
+ }