@ouro.bot/cli 0.1.0-alpha.1011 → 0.1.0-alpha.1014

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.
@@ -1,9 +1,43 @@
1
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
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
5
38
  Object.defineProperty(exports, "__esModule", { value: true });
6
39
  exports.classifyGithubCopilotError = classifyGithubCopilotError;
40
+ exports.createGithubCopilotPooledCaller = createGithubCopilotPooledCaller;
7
41
  exports.createGithubCopilotProviderRuntime = createGithubCopilotProviderRuntime;
8
42
  const openai_1 = __importDefault(require("openai"));
9
43
  const config_1 = require("../config");
@@ -11,10 +45,38 @@ const runtime_1 = require("../../nerves/runtime");
11
45
  const streaming_1 = require("../streaming");
12
46
  const model_capabilities_1 = require("../model-capabilities");
13
47
  const error_classification_1 = require("./error-classification");
48
+ const path = __importStar(require("path"));
49
+ const account_pool_1 = require("./account-pool");
50
+ const fleet_readings_1 = require("../quota/fleet-readings");
14
51
  function classifyGithubCopilotError(error) {
15
52
  return (0, error_classification_1.classifyHttpError)(error);
16
53
  }
17
- function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGithubCopilotConfig)()) {
54
+ /**
55
+ * The agent's account pool for this turn, when `ouro auth` discovered one; null for a single account.
56
+ * Without an owning agent (a daemon-side ping, provider discovery) the pool still switches on a 402 or 429,
57
+ * but keeps no state between calls, writes no switch log and publishes nothing.
58
+ */
59
+ function createGithubCopilotPooledCaller(config, owner) {
60
+ const accounts = (0, account_pool_1.parseAccountPool)(config.accountPool);
61
+ if (accounts.length === 0)
62
+ return null;
63
+ const makeClient = (account) => new openai_1.default({ apiKey: account.githubToken, baseURL: account.baseUrl, maxRetries: 0 });
64
+ if (!owner)
65
+ return (0, account_pool_1.createPooledCaller)(new account_pool_1.AccountPool(accounts, { agent: "(unowned)", switchLog: "", appendLine: () => { } }), makeClient);
66
+ const gist = config.fleetGistId && config.fleetGistToken ? { gistId: config.fleetGistId, token: config.fleetGistToken } : null;
67
+ const pool = (0, account_pool_1.getAccountPool)(accounts, {
68
+ agent: owner.agentName,
69
+ machine: config.fleetMachine,
70
+ switchLog: path.join(owner.agentRoot, "state", "account-switches.jsonl"),
71
+ burnDir: path.join(owner.agentRoot, "state", "account-burn"),
72
+ /* v8 ignore start -- network readers and publisher: each is tested in its own module @preserve */
73
+ loadReadings: async () => (0, fleet_readings_1.mergeReadings)(await (0, fleet_readings_1.loadFleetQuota)(gist), await (0, account_pool_1.fetchDirectReadings)(accounts)),
74
+ publishBurn: gist ? (burn) => (0, fleet_readings_1.publishAgentBurn)(gist, burn) : undefined,
75
+ /* v8 ignore stop */
76
+ });
77
+ return (0, account_pool_1.createPooledCaller)(pool, makeClient);
78
+ }
79
+ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGithubCopilotConfig)(), owner) {
18
80
  (0, runtime_1.emitNervesEvent)({
19
81
  component: "engine",
20
82
  event: "engine.provider_init",
@@ -33,11 +95,14 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
33
95
  /* v8 ignore next -- branch: capability detection tested via unit test @preserve */
34
96
  if (modelCaps.reasoningEffort)
35
97
  capabilities.add("reasoning-effort");
36
- const client = new openai_1.default({
98
+ // With an account pool the account is chosen here, between turns; a 402 or 429 moves it mid-request.
99
+ const pooled = createGithubCopilotPooledCaller(config, owner);
100
+ const client = pooled ? pooled.client() : new openai_1.default({
37
101
  apiKey: config.githubToken,
38
102
  baseURL: config.baseUrl,
39
103
  maxRetries: 0,
40
104
  });
105
+ const callModel = (fallback, request) => pooled ? pooled.call((pooledClient) => request(pooledClient)) : request(fallback);
41
106
  if (isCompletionsModel) {
42
107
  // Chat completions path (Claude models via Copilot)
43
108
  return {
@@ -69,7 +134,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
69
134
  if (request.toolChoiceRequired)
70
135
  params.tool_choice = "auto";
71
136
  try {
72
- return await (0, streaming_1.streamChatCompletion)(this.client, params, request.callbacks, request.signal, request.eagerSettleStreaming);
137
+ return await callModel(this.client, (turnClient) => (0, streaming_1.streamChatCompletion)(turnClient, params, request.callbacks, request.signal, request.eagerSettleStreaming));
73
138
  }
74
139
  catch (error) {
75
140
  throw error instanceof Error ? error : new Error(String(error));
@@ -78,7 +143,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
78
143
  /* v8 ignore stop */
79
144
  /* v8 ignore start -- ping: tested via provider-ping.test.ts @preserve */
80
145
  async ping(signal) {
81
- await this.client.chat.completions.create({ model: this.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] }, { signal });
146
+ await callModel(this.client, (turnClient) => turnClient.chat.completions.create({ model: this.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] }, { signal }));
82
147
  },
83
148
  /* v8 ignore stop */
84
149
  /* v8 ignore next 3 -- delegation: classification logic tested via classifyGithubCopilotError @preserve */
@@ -125,7 +190,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
125
190
  if (request.toolChoiceRequired)
126
191
  params.tool_choice = "required";
127
192
  try {
128
- const result = await (0, streaming_1.streamResponsesApi)(this.client, params, request.callbacks, request.signal, request.eagerSettleStreaming);
193
+ const result = await callModel(this.client, (turnClient) => (0, streaming_1.streamResponsesApi)(turnClient, params, request.callbacks, request.signal, request.eagerSettleStreaming));
129
194
  for (const item of result.outputItems)
130
195
  nativeInput.push(item);
131
196
  return result;
@@ -137,7 +202,7 @@ function createGithubCopilotProviderRuntime(model, config = (0, config_1.getGith
137
202
  /* v8 ignore stop */
138
203
  /* v8 ignore start -- ping: tested via provider-ping.test.ts @preserve */
139
204
  async ping(signal) {
140
- await this.client.responses.create({ model: this.model, input: "ping", max_output_tokens: 16 }, { signal });
205
+ await callModel(this.client, (turnClient) => turnClient.responses.create({ model: this.model, input: "ping", max_output_tokens: 16 }, { signal }));
141
206
  },
142
207
  /* v8 ignore stop */
143
208
  /* v8 ignore next 3 -- delegation: classification logic tested via classifyGithubCopilotError @preserve */
@@ -0,0 +1,222 @@
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.LOCAL_BALANCER_STATE = void 0;
37
+ exports.readingsFromBalancerState = readingsFromBalancerState;
38
+ exports.mergeReadings = mergeReadings;
39
+ exports.readFleetQuota = readFleetQuota;
40
+ exports.directReading = directReading;
41
+ exports.agentBurnFileName = agentBurnFileName;
42
+ exports.agentBurnContent = agentBurnContent;
43
+ exports.loadFleetQuota = loadFleetQuota;
44
+ exports.publishAgentBurn = publishAgentBurn;
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
+ /**
50
+ * Quota readings for agents, from the same places the Copilot app balancer (`quota-balance.mjs`) keeps them:
51
+ * its local state first (`~/.config/mac-fleet/quota-balance.json`), then the fleet gist (`<machine>.quota.txt`).
52
+ * Agents publish their own burn to the same gist as `<machine>.<agent>.quota.txt`.
53
+ */
54
+ exports.LOCAL_BALANCER_STATE = path.join(".config", "mac-fleet", "quota-balance.json");
55
+ function isRecord(value) {
56
+ return !!value && typeof value === "object" && !Array.isArray(value);
57
+ }
58
+ const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
59
+ const str = (value) => (typeof value === "string" && value ? value : null);
60
+ /** Readings from one balancer state object: `{ readings: { "login@host": { pct, overage_permitted, at, reset } } }`. */
61
+ function readingsFromBalancerState(state, source) {
62
+ if (!isRecord(state) || !isRecord(state.readings))
63
+ return [];
64
+ const out = [];
65
+ for (const [key, raw] of Object.entries(state.readings)) {
66
+ if (!isRecord(raw) || num(raw.pct) === null)
67
+ continue;
68
+ out.push({
69
+ key,
70
+ leftPct: num(raw.pct),
71
+ burnPerH: num(raw.burn_per_h),
72
+ dryAt: str(raw.dry_at),
73
+ overageOk: raw.overage_permitted === true,
74
+ at: str(raw.at),
75
+ reset: str(raw.reset),
76
+ remaining: num(raw.remaining),
77
+ entitlement: num(raw.entitlement),
78
+ source,
79
+ });
80
+ }
81
+ return out;
82
+ }
83
+ const timeOf = (reading) => {
84
+ const at = Date.parse(reading.at ?? "");
85
+ return Number.isNaN(at) ? -Infinity : at;
86
+ };
87
+ /** Freshest reading per account. On a tie the earlier list wins, so pass local readings first. */
88
+ function mergeReadings(...lists) {
89
+ const out = new Map();
90
+ for (const list of lists) {
91
+ for (const reading of list) {
92
+ const prev = out.get(reading.key);
93
+ if (!prev || timeOf(reading) > timeOf(prev))
94
+ out.set(reading.key, reading);
95
+ }
96
+ }
97
+ return [...out.values()];
98
+ }
99
+ /** Every reading in the fleet: local balancer state first, then each other Mac's `<machine>.quota.txt` in the gist. */
100
+ function readFleetQuota(sources) {
101
+ const local = readingsFromBalancerState(sources.localState, "local");
102
+ const fleet = [];
103
+ const files = isRecord(sources.gist) && isRecord(sources.gist.files) ? sources.gist.files : {};
104
+ for (const [name, file] of Object.entries(files)) {
105
+ const match = /^([^.]+)\.quota\.txt$/.exec(name);
106
+ if (!match || !isRecord(file) || typeof file.content !== "string")
107
+ continue;
108
+ try {
109
+ fleet.push(readingsFromBalancerState(JSON.parse(file.content), `fleet:${match[1]}`));
110
+ }
111
+ catch {
112
+ // A half-written file is skipped; the next read picks it up.
113
+ }
114
+ }
115
+ const readings = mergeReadings(local, ...fleet);
116
+ (0, runtime_1.emitNervesEvent)({
117
+ component: "engine",
118
+ event: "engine.fleet_quota_read",
119
+ message: "read fleet quota readings",
120
+ meta: { local: local.length, gistFiles: fleet.length, accounts: readings.length },
121
+ });
122
+ return readings;
123
+ }
124
+ /** A reading from an account's own `/copilot_internal/user` answer. */
125
+ function directReading(key, body, at) {
126
+ if (!isRecord(body) || !isRecord(body.quota_snapshots) || !isRecord(body.quota_snapshots.premium_interactions))
127
+ return null;
128
+ const snap = body.quota_snapshots.premium_interactions;
129
+ const leftPct = snap.unlimited === true ? 100 : num(snap.percent_remaining);
130
+ if (leftPct === null)
131
+ return null;
132
+ return {
133
+ key,
134
+ leftPct,
135
+ burnPerH: null,
136
+ dryAt: null,
137
+ overageOk: snap.overage_permitted === true,
138
+ at,
139
+ reset: str(body.quota_reset_date_utc),
140
+ remaining: num(snap.remaining),
141
+ entitlement: num(snap.entitlement),
142
+ source: "direct",
143
+ };
144
+ }
145
+ function agentBurnFileName(machine, agent) {
146
+ return `${machine}.${agent}.quota.txt`;
147
+ }
148
+ /**
149
+ * The agent's file, in the shape the Copilot app balancer reads (`parseAgentQuota` in quota-balance.mjs):
150
+ * `{machine, agent, at, readings: [{key, leftPct, burnPerH, dryAt, overageOk, at, remaining, entitlement, reset}]}`.
151
+ * `burnPerH` is this agent's own requests an hour on that account.
152
+ */
153
+ function agentBurnContent(burn) {
154
+ const keys = [...new Set([...burn.readings.map((reading) => reading.key), ...Object.keys(burn.requestsPerH)])];
155
+ const readings = keys.map((key) => {
156
+ const reading = burn.readings.find((candidate) => candidate.key === key);
157
+ return {
158
+ key,
159
+ leftPct: reading?.leftPct ?? null,
160
+ burnPerH: burn.requestsPerH[key] ?? 0,
161
+ dryAt: reading?.dryAt ?? null,
162
+ overageOk: reading?.overageOk ?? false,
163
+ at: reading?.at ?? burn.at,
164
+ ...(reading?.remaining != null ? { remaining: reading.remaining } : {}),
165
+ ...(reading?.entitlement != null ? { entitlement: reading.entitlement } : {}),
166
+ ...(reading?.reset ? { reset: reading.reset } : {}),
167
+ };
168
+ });
169
+ return `${JSON.stringify({ machine: burn.machine, agent: burn.agent, at: burn.at, current: burn.current, readings }, null, 2)}\n`;
170
+ }
171
+ const gistUrl = (gistId) => `https://api.github.com/gists/${gistId}`;
172
+ const gistHeaders = (token) => ({
173
+ Authorization: `token ${token}`,
174
+ Accept: "application/vnd.github+json",
175
+ "User-Agent": "ouro-account-pool",
176
+ });
177
+ /** Load local balancer state and the fleet gist; either may be missing. */
178
+ async function loadFleetQuota(gist, io = {}) {
179
+ const readFile = io.readFile ?? ((file) => fs.readFileSync(file, "utf8"));
180
+ let localState;
181
+ try {
182
+ localState = JSON.parse(readFile(path.join(io.homeDir ?? os.homedir(), exports.LOCAL_BALANCER_STATE)));
183
+ }
184
+ catch {
185
+ localState = undefined;
186
+ }
187
+ let gistBody;
188
+ if (gist) {
189
+ try {
190
+ const response = await (io.fetch ?? fetch)(gistUrl(gist.gistId), { headers: gistHeaders(gist.token), signal: AbortSignal.timeout(15000) });
191
+ gistBody = response.ok ? await response.json() : undefined;
192
+ }
193
+ catch {
194
+ gistBody = undefined;
195
+ }
196
+ }
197
+ return readFleetQuota({ localState, gist: gistBody });
198
+ }
199
+ /** Write this agent's burn to the fleet gist. Returns false (never throws) when the gist can't be written. */
200
+ async function publishAgentBurn(gist, burn, io = {}) {
201
+ let ok = false;
202
+ try {
203
+ const response = await (io.fetch ?? fetch)(gistUrl(gist.gistId), {
204
+ method: "PATCH",
205
+ headers: { ...gistHeaders(gist.token), "Content-Type": "application/json" },
206
+ body: JSON.stringify({ files: { [agentBurnFileName(burn.machine, burn.agent)]: { content: agentBurnContent(burn) } } }),
207
+ signal: AbortSignal.timeout(15000),
208
+ });
209
+ ok = response.ok;
210
+ }
211
+ catch {
212
+ ok = false;
213
+ }
214
+ (0, runtime_1.emitNervesEvent)({
215
+ level: ok ? "info" : "warn",
216
+ component: "engine",
217
+ event: "engine.agent_burn_published",
218
+ message: ok ? "published agent burn to the fleet gist" : "could not publish agent burn to the fleet gist",
219
+ meta: { agent: burn.agent, machine: burn.machine, ok },
220
+ });
221
+ return ok;
222
+ }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_TRANCHE_CAPS = void 0;
4
+ exports.usedPct = usedPct;
5
+ exports.trancheCap = trancheCap;
6
+ exports.pickByTranche = pickByTranche;
7
+ const runtime_1 = require("../../nerves/runtime");
8
+ /** Fill every account to 30% used, then 60%, then 90%, then squeeze the last 10% from each (Ari, 2026-11-09). */
9
+ exports.DEFAULT_TRANCHE_CAPS = [30, 60, 90, 100];
10
+ /**
11
+ * These mirror `usedPct`, `trancheCap` and `pickByTranche` in the Copilot app balancer
12
+ * (desk `setup/quota-balance.mjs`), so agents and the app fill accounts the same way.
13
+ */
14
+ /** Percent of included requests used, or null with no reading. */
15
+ function usedPct(reading) {
16
+ if (!reading || reading.leftPct === null)
17
+ return null;
18
+ return Math.max(0, Math.min(100, 100 - reading.leftPct));
19
+ }
20
+ function byKey(readings) {
21
+ return new Map(readings.map((reading) => [reading.key, reading]));
22
+ }
23
+ /**
24
+ * The current cap: the lowest cap that some eligible account with a reading is still below. It rises only once
25
+ * every eligible account has reached it. When every one is at 100 it stays 100.
26
+ */
27
+ function trancheCap(readings, eligible, caps = exports.DEFAULT_TRANCHE_CAPS) {
28
+ const map = byKey(readings);
29
+ const used = eligible.map((key) => usedPct(map.get(key))).filter((value) => value !== null);
30
+ const cap = caps.find((candidate) => used.some((value) => value < candidate)) ?? caps[caps.length - 1];
31
+ (0, runtime_1.emitNervesEvent)({
32
+ component: "engine",
33
+ event: "engine.quota_tranche_cap",
34
+ message: "computed the quota tranche cap",
35
+ meta: { cap, eligible: eligible.length },
36
+ });
37
+ return cap;
38
+ }
39
+ /**
40
+ * Stay on `current` while it is eligible and below the cap; else the first account in `order` that is eligible
41
+ * and below it, then any eligible one; null when none is (included requests spent everywhere: overage).
42
+ */
43
+ function pickByTranche(current, readings, eligible, order, cap) {
44
+ const map = byKey(readings);
45
+ const below = (key) => {
46
+ if (key === null || !eligible.includes(key))
47
+ return false;
48
+ const used = usedPct(map.get(key));
49
+ return used !== null && used < cap;
50
+ };
51
+ const picked = below(current) ? current : order.find(below) ?? eligible.find(below) ?? null;
52
+ (0, runtime_1.emitNervesEvent)({
53
+ component: "engine",
54
+ event: "engine.quota_tranche_pick",
55
+ message: "picked an account by quota tranche",
56
+ meta: { current, picked, cap },
57
+ });
58
+ return picked;
59
+ }
@@ -58,6 +58,7 @@ exports.provisionMailboxRegistry = provisionMailboxRegistry;
58
58
  exports.ensureMailboxRegistry = ensureMailboxRegistry;
59
59
  const crypto = __importStar(require("node:crypto"));
60
60
  const runtime_1 = require("../nerves/runtime");
61
+ const optional_packages_1 = require("../heart/optional-packages");
61
62
  const LOCAL_PART_LIMIT = 64;
62
63
  const SNIPPET_LIMIT = 240;
63
64
  const RAW_OBJECT_PREFIX = "raw";
@@ -455,7 +456,7 @@ function privateMailEnvelopeReadableText(privateEnvelope) {
455
456
  }
456
457
  async function parsePrivateMailEnvelope(rawMime) {
457
458
  // mailparser and its charset tables cost about 19 MB per process; load it on the first parse.
458
- const { simpleParser } = await Promise.resolve().then(() => __importStar(require("mailparser")));
459
+ const { simpleParser } = await (0, optional_packages_1.importOptional)("mailparser", "Reading mail", () => Promise.resolve().then(() => __importStar(require("mailparser"))));
459
460
  const parsed = await simpleParser(rawMime);
460
461
  const html = typeof parsed.html === "string" ? parsed.html : undefined;
461
462
  const parsedText = parsed.text ?? "";
@@ -43,6 +43,7 @@ var __importStar = (this && this.__importStar) || (function () {
43
43
  })();
44
44
  Object.defineProperty(exports, "__esModule", { value: true });
45
45
  exports.createStripeClient = createStripeClient;
46
+ const optional_packages_1 = require("../heart/optional-packages");
46
47
  const credential_access_1 = require("./credential-access");
47
48
  const runtime_1 = require("../nerves/runtime");
48
49
  // ---------------------------------------------------------------------------
@@ -62,7 +63,7 @@ async function createStripeClient() {
62
63
  const store = (0, credential_access_1.getCredentialStore)();
63
64
  const apiKey = await store.getRawSecret("stripe.com", "restrictedKey");
64
65
  // Stripe's SDK is about 10 MB and 185 modules; only agents that issue cards load it.
65
- const { default: StripeConstructor } = await Promise.resolve().then(() => __importStar(require("stripe")));
66
+ const { default: StripeConstructor } = await (0, optional_packages_1.importOptional)("stripe", "Virtual cards", () => Promise.resolve().then(() => __importStar(require("stripe"))));
66
67
  const StripeFactory = StripeConstructor;
67
68
  const stripe = new StripeFactory(apiKey);
68
69
  return {
@@ -52,15 +52,17 @@ const runtime_1 = require("../nerves/runtime");
52
52
  Promise.resolve().then(() => __importStar(require("./mail"))).then(async ({ startMailSenseApp }) => {
53
53
  await startMailSenseApp({ agentName });
54
54
  })
55
- .catch((error) => {
55
+ .catch(async (error) => {
56
+ const { describeStartupError } = await Promise.resolve().then(() => __importStar(require("../heart/optional-packages")));
57
+ const detail = describeStartupError(error, "the Mail sense");
56
58
  (0, runtime_1.emitNervesEvent)({
57
59
  level: "error",
58
60
  component: "senses",
59
61
  event: "senses.entry_error",
60
62
  message: "Mail entrypoint failed",
61
- meta: { entry: "mail", agentName, error: error instanceof Error ? error.message : String(error) },
63
+ meta: { entry: "mail", agentName, error: detail },
62
64
  });
63
65
  // eslint-disable-next-line no-console -- fatal startup guard for sense process
64
- console.error(error instanceof Error ? error.message : String(error));
66
+ console.error(detail);
65
67
  process.exit(1);
66
68
  });
@@ -53,6 +53,7 @@ const identity_1 = require("../../heart/identity");
53
53
  const reach_channel_1 = require("../../heart/reach-channel");
54
54
  const runtime_1 = require("../../nerves/runtime");
55
55
  const notice_outbox_1 = require("./notice-outbox");
56
+ const optional_packages_1 = require("../../heart/optional-packages");
56
57
  /**
57
58
  * The owner notice: after a judged return, the agent's owner hears what happened in one short plain message on their
58
59
  * own channel. It is deterministic, written here and sent with no model turn, so the owner hears about every return the
@@ -277,7 +278,7 @@ function chooseTeamsBot(tenantId, primary, secondary) {
277
278
  }
278
279
  /* v8 ignore start -- the live Teams SDK client; its token and REST calls need a real bot registration @preserve */
279
280
  async function liveBotApi(config) {
280
- const { App } = await Promise.resolve().then(() => __importStar(require("@microsoft/teams.apps")));
281
+ const { App } = await (0, optional_packages_1.importOptional)("@microsoft/teams.apps", "Teams owner notices", () => Promise.resolve().then(() => __importStar(require("@microsoft/teams.apps"))));
281
282
  const app = new App({
282
283
  clientId: config.clientId,
283
284
  ...(config.clientSecret ? { clientSecret: config.clientSecret } : {}),
@@ -61,15 +61,17 @@ Promise.resolve().then(() => __importStar(require("../heart/runtime-credentials"
61
61
  const { startTeamsApp } = await Promise.resolve().then(() => __importStar(require("./teams")));
62
62
  startTeamsApp();
63
63
  })
64
- .catch((error) => {
64
+ .catch(async (error) => {
65
+ const { describeStartupError } = await Promise.resolve().then(() => __importStar(require("../heart/optional-packages")));
66
+ const detail = describeStartupError(error, "the Teams sense");
65
67
  (0, runtime_1.emitNervesEvent)({
66
68
  level: "error",
67
69
  component: "senses",
68
70
  event: "senses.entry_error",
69
71
  message: "Teams entrypoint failed",
70
- meta: { entry: "teams", agentName, error: error instanceof Error ? error.message : String(error) },
72
+ meta: { entry: "teams", agentName, error: detail },
71
73
  });
72
74
  // eslint-disable-next-line no-console -- fatal startup guard for sense process
73
- console.error(error instanceof Error ? error.message : String(error));
75
+ console.error(detail);
74
76
  process.exit(1);
75
77
  });