@codelia/runtime 0.1.91 → 0.1.93

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.
package/dist/sdk.cjs CHANGED
@@ -276,6 +276,8 @@ var sendNotificationAsync = async (state, notify) => {
276
276
  }
277
277
  await sendAsync(notify);
278
278
  };
279
+ var transportBackpressureEvents = 0;
280
+ var getTransportBackpressureEvents = () => transportBackpressureEvents;
279
281
  var send = (msg) => {
280
282
  const { payload, label } = serializeMessage(msg);
281
283
  const writable = process.stdout.write(payload, (error) => {
@@ -284,6 +286,7 @@ var send = (msg) => {
284
286
  }
285
287
  });
286
288
  if (!writable) {
289
+ transportBackpressureEvents += 1;
287
290
  (0, import_logger.debugLog)(`transport.backpressure label=${label} bytes=${payload.length}`);
288
291
  }
289
292
  };
@@ -298,6 +301,7 @@ var sendAsync = async (msg) => new Promise((resolve) => {
298
301
  resolve();
299
302
  });
300
303
  if (!writable) {
304
+ transportBackpressureEvents += 1;
301
305
  (0, import_logger.debugLog)(`transport.backpressure label=${label} bytes=${payload.length}`);
302
306
  }
303
307
  });
@@ -347,12 +351,12 @@ var sendRunContext = (state, runId, contextLeftPercent) => {
347
351
  })
348
352
  );
349
353
  };
350
- var sendRunDiagnostics = (state, params) => {
351
- sendNotification(state, notificationMessage("run.diagnostics", params));
352
- };
353
354
  var sendRunMetrics = (state, params) => {
354
355
  sendNotification(state, notificationMessage("run.metrics", params));
355
356
  };
357
+ var sendRunSummary = (state, params) => {
358
+ sendNotification(state, notificationMessage("run.summary", params));
359
+ };
356
360
 
357
361
  // src/rpc/protocol.ts
358
362
  var MAX_ISSUES = 10;
@@ -368,8 +372,18 @@ var schemaFor = (method, slot) => {
368
372
  throw new Error(`${method} is a notification without a result`);
369
373
  return spec.result;
370
374
  };
375
+ var cachedProtocolAssertRaw;
376
+ var cachedProtocolAssertEnabled = false;
377
+ var isProtocolAssertEnabled = () => {
378
+ const raw = process.env.CODELIA_TEST_PROTOCOL_ASSERT;
379
+ if (raw !== cachedProtocolAssertRaw) {
380
+ cachedProtocolAssertRaw = raw;
381
+ cachedProtocolAssertEnabled = raw === "1";
382
+ }
383
+ return cachedProtocolAssertEnabled;
384
+ };
371
385
  var assertOutgoing = (method, slot, value) => {
372
- if (process.env.CODELIA_PROTOCOL_ASSERT !== "1") return;
386
+ if (!isProtocolAssertEnabled()) return;
373
387
  const result = schemaFor(method, slot).safeParse(value);
374
388
  if (!result.success)
375
389
  throw new Error(
@@ -760,9 +774,21 @@ var resolveTuiConfig = async (workingDir) => {
760
774
  const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
761
775
  const effective = import_config.configRegistry.resolve([globalConfig, projectConfig]);
762
776
  return {
763
- theme: effective.tui?.theme
777
+ ...effective.tui?.theme ? { theme: effective.tui.theme } : {},
778
+ ...effective.tui?.color_scheme ? { color_scheme: effective.tui.color_scheme } : {},
779
+ ...effective.tui?.image_protocol ? { image_protocol: effective.tui.image_protocol } : {}
764
780
  };
765
781
  };
782
+ var resolveAgentsEnabled = async (workingDir) => {
783
+ const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
784
+ const effective = import_config.configRegistry.resolve([globalConfig, projectConfig]);
785
+ return effective.agents?.enabled ?? true;
786
+ };
787
+ var resolveAuthOAuthBrowser = async (workingDir) => {
788
+ const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
789
+ const effective = import_config.configRegistry.resolve([globalConfig, projectConfig]);
790
+ return effective.auth?.oauth_browser;
791
+ };
766
792
  var resolvePermissionsConfig = async (workingDir) => {
767
793
  const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
768
794
  const effective = import_config.configRegistry.resolve([globalConfig, projectConfig]);
@@ -943,7 +969,7 @@ var hasDefinedGroup = (group, value) => {
943
969
  case "permissions":
944
970
  return Array.isArray(value?.permissions?.allow) || Array.isArray(value?.permissions?.deny);
945
971
  case "tui":
946
- return typeof value?.tui?.theme === "string" && value.tui.theme.trim().length > 0;
972
+ return typeof value?.tui?.theme === "string" && value.tui.theme.trim().length > 0 || value?.tui?.color_scheme !== void 0 || value?.tui?.image_protocol !== void 0;
947
973
  default:
948
974
  return false;
949
975
  }
@@ -5197,6 +5223,14 @@ var ApprovalDispatcher = class {
5197
5223
  return failure2?.outcome;
5198
5224
  }
5199
5225
  dispatch(options) {
5226
+ const nowMs = this.options.monotonicNow ?? (() => performance.now());
5227
+ const approvalStartedAt = options.onApprovalWaitMs ? nowMs() : 0;
5228
+ let approvalRecorded = false;
5229
+ const recordApprovalWait = () => {
5230
+ if (approvalRecorded || !options.onApprovalWaitMs) return;
5231
+ approvalRecorded = true;
5232
+ options.onApprovalWaitMs(Math.max(0, nowMs() - approvalStartedAt));
5233
+ };
5200
5234
  const request = Object.freeze({ ...options.request });
5201
5235
  const { id: id2, ...binding } = request;
5202
5236
  const receiptBinding = options.deduplicate ? digest(binding) : void 0;
@@ -5207,286 +5241,292 @@ var ApprovalDispatcher = class {
5207
5241
  ...options.signal ? [options.signal] : []
5208
5242
  ]) : options.signal;
5209
5243
  const dispatch = async () => {
5210
- const facts = options.evaluate();
5211
- const route = freezeRoute(routeApproval(facts));
5212
- let actor = facts.confinedAutoLaunch && route.kind === "immediate" ? "sandbox" : "rule";
5213
- const audit = (state, reason, taskId, diagnostic) => this.options.audit?.({
5214
- requestId: id2,
5215
- origin: request.origin,
5216
- subject: request.subject,
5217
- route: route.kind,
5218
- profile: route.profile,
5219
- actor,
5220
- state,
5221
- reason,
5222
- ...diagnostic ? { reviewDiagnostic: diagnostic } : {},
5223
- at: Date.now(),
5224
- ...taskId ? { taskId } : {},
5225
- ...request.runId ? { runId: request.runId } : {}
5226
- });
5227
- if (route.kind === "deny") {
5228
- audit("denied", route.reason);
5229
- return reject(route.reason);
5230
- }
5231
- const expire = (reason, diagnostic) => {
5232
- audit("expired", reason, void 0, diagnostic);
5233
- return reject(
5234
- diagnostic ? `${reason}: ${reviewDiagnosticText(diagnostic)}` : reason
5235
- );
5236
- };
5237
- const checkCurrent = (reviewing = false) => {
5238
- if (requestSignal?.aborted || !options.stillCurrent()) {
5239
- expire(
5240
- "approval_expired",
5241
- reviewing ? reviewDiagnostic(
5242
- requestSignal?.aborted ? "review_cancelled" : "review_authority_changed"
5243
- ) : void 0
5244
+ try {
5245
+ const facts = options.evaluate();
5246
+ const route = freezeRoute(routeApproval(facts));
5247
+ let actor = facts.confinedAutoLaunch && route.kind === "immediate" ? "sandbox" : "rule";
5248
+ const audit = (state, reason, taskId, diagnostic) => this.options.audit?.({
5249
+ requestId: id2,
5250
+ origin: request.origin,
5251
+ subject: request.subject,
5252
+ route: route.kind,
5253
+ profile: route.profile,
5254
+ actor,
5255
+ state,
5256
+ reason,
5257
+ ...diagnostic ? { reviewDiagnostic: diagnostic } : {},
5258
+ at: Date.now(),
5259
+ ...taskId ? { taskId } : {},
5260
+ ...request.runId ? { runId: request.runId } : {}
5261
+ });
5262
+ if (route.kind === "deny") {
5263
+ audit("denied", route.reason);
5264
+ return reject(route.reason);
5265
+ }
5266
+ const expire = (reason, diagnostic) => {
5267
+ audit("expired", reason, void 0, diagnostic);
5268
+ return reject(
5269
+ diagnostic ? `${reason}: ${reviewDiagnosticText(diagnostic)}` : reason
5270
+ );
5271
+ };
5272
+ const checkCurrent = (reviewing = false) => {
5273
+ if (requestSignal?.aborted || !options.stillCurrent()) {
5274
+ expire(
5275
+ "approval_expired",
5276
+ reviewing ? reviewDiagnostic(
5277
+ requestSignal?.aborted ? "review_cancelled" : "review_authority_changed"
5278
+ ) : void 0
5279
+ );
5280
+ }
5281
+ };
5282
+ checkCurrent();
5283
+ const unsandboxedEscalation = route.profile === "full-access" && route.additional.length === 1 && isUnsandboxedShellResource(route.additional[0]);
5284
+ const interactive = options.interactiveShell && request.subject === "shell" && (request.origin === "parent_agent" || request.origin === "operator") && ((route.profile === "development" || route.profile === "investigation") && !route.additional.length || unsandboxedEscalation) && this.options.confirmation?.confirm && this.options.confirmation.available?.() !== false ? options.interactiveShell : void 0;
5285
+ if (route.kind === "defer" && !interactive) {
5286
+ const diagnostic = options.reviewCoverageDiagnostic ?? reviewDiagnostic("review_evidence_unavailable");
5287
+ audit("denied", "review_evidence_unavailable", void 0, diagnostic);
5288
+ return rejectLocalReview(
5289
+ "review_evidence_unavailable",
5290
+ void 0,
5291
+ diagnostic
5244
5292
  );
5245
5293
  }
5246
- };
5247
- checkCurrent();
5248
- const unsandboxedEscalation = route.profile === "full-access" && route.additional.length === 1 && isUnsandboxedShellResource(route.additional[0]);
5249
- const interactive = options.interactiveShell && request.subject === "shell" && (request.origin === "parent_agent" || request.origin === "operator") && ((route.profile === "development" || route.profile === "investigation") && !route.additional.length || unsandboxedEscalation) && this.options.confirmation?.confirm && this.options.confirmation.available?.() !== false ? options.interactiveShell : void 0;
5250
- if (route.kind === "defer" && !interactive) {
5251
- const diagnostic = options.reviewCoverageDiagnostic ?? reviewDiagnostic("review_evidence_unavailable");
5252
- audit("denied", "review_evidence_unavailable", void 0, diagnostic);
5253
- return rejectLocalReview(
5254
- "review_evidence_unavailable",
5255
- void 0,
5256
- diagnostic
5257
- );
5258
- }
5259
- let save = options.save;
5260
- let saveScope;
5261
- let sessionGrant;
5262
- const version = route.kind === "review" ? this.options.review?.reviewVersion?.(request) : void 0;
5263
- if (route.kind !== "immediate") {
5264
- const retryKey = facts.autoReview && route.kind === "review" ? (0, import_node_crypto4.createHash)("sha256").update(
5265
- JSON.stringify([
5266
- request.owner,
5267
- request.intentVersion,
5268
- request.authorityVersion,
5294
+ let save = options.save;
5295
+ let saveScope;
5296
+ let sessionGrant;
5297
+ const version = route.kind === "review" ? this.options.review?.reviewVersion?.(request) : void 0;
5298
+ if (route.kind !== "immediate") {
5299
+ const retryKey = facts.autoReview && route.kind === "review" ? (0, import_node_crypto4.createHash)("sha256").update(
5300
+ JSON.stringify([
5301
+ request.owner,
5302
+ request.intentVersion,
5303
+ request.authorityVersion,
5304
+ version,
5305
+ options.reviewRetryKey ?? digest(binding)
5306
+ ])
5307
+ ).digest("hex") : void 0;
5308
+ const evidenceKey = retryKey === void 0 ? void 0 : `${retryKey}/${options.reviewRetryEvidenceKey ?? ""}`;
5309
+ const now = this.options.monotonicNow ?? (() => performance.now());
5310
+ const cachedFailure = retryKey === void 0 || evidenceKey === void 0 ? void 0 : this.reviewFailure(retryKey, now()) ?? this.reviewFailure(evidenceKey, now());
5311
+ let reviewReason;
5312
+ const reviewResult = cachedFailure ?? (route.kind === "review" ? await this.review(
5313
+ request,
5314
+ retryKey ?? receiptBinding ?? digest(binding),
5315
+ facts.reviewCategory,
5269
5316
  version,
5270
- options.reviewRetryKey ?? digest(binding)
5271
- ])
5272
- ).digest("hex") : void 0;
5273
- const evidenceKey = retryKey === void 0 ? void 0 : `${retryKey}/${options.reviewRetryEvidenceKey ?? ""}`;
5274
- const now = this.options.monotonicNow ?? (() => performance.now());
5275
- const cachedFailure = retryKey === void 0 || evidenceKey === void 0 ? void 0 : this.reviewFailure(retryKey, now()) ?? this.reviewFailure(evidenceKey, now());
5276
- let reviewReason;
5277
- const reviewResult = cachedFailure ?? (route.kind === "review" ? await this.review(
5278
- request,
5279
- retryKey ?? receiptBinding ?? digest(binding),
5280
- facts.reviewCategory,
5281
- version,
5282
- requestSignal,
5283
- interactive ? (reason) => {
5284
- reviewReason = reason;
5285
- } : void 0
5286
- ) : route.kind === "defer" ? failure(
5287
- "review_evidence_unavailable",
5288
- options.reviewCoverageDiagnostic ?? reviewDiagnostic("review_evidence_unavailable")
5289
- ) : { fallback: "ask_user", missing: "unspecified" });
5290
- const outcome = facts.autoReview && route.kind === "review" && typeof reviewResult === "object" && reviewResult.fallback === "ask_user" && reviewResult.missing === "unspecified" ? failure("review_inconclusive") : reviewResult;
5291
- const decision = typeof outcome === "object" ? outcome.fallback : outcome;
5292
- const failureDetails = typeof outcome === "object" && outcome.fallback !== "ask_user" ? outcome : void 0;
5293
- const diagnostic = failureDetails?.diagnostic;
5294
- const confirmationCause = failureDetails?.oneTimeConfirmation;
5295
- const manualPrivacyFallback = confirmationCause === "private_evidence";
5296
- const manualInconclusiveFallback = facts.autoReview === true && confirmationCause === "inconclusive";
5297
- const oneTimeConfirmation = manualPrivacyFallback || manualInconclusiveFallback;
5298
- if (confirmationCause === "inconclusive" || decision === "allow_once" || decision === "deny" || diagnostic && decision !== "review_evidence_unavailable" && diagnostic.code !== "review_preparation_failed")
5299
- actor = "review";
5300
- checkCurrent(route.kind === "review");
5301
- if (interactive && diagnostic && (diagnostic.code === "review_cancelled" || diagnostic.code === "review_authority_changed")) {
5302
- return expire("approval_expired", diagnostic);
5303
- }
5304
- if (decision === "deny" && !interactive) {
5305
- audit("denied", "review_denied");
5306
- return facts.autoReview ? rejectLocalReview("deny") : reject("review_denied");
5307
- }
5308
- if (retryKey !== void 0 && evidenceKey !== void 0 && outcome !== "allow_once" && outcome !== "deny" && !manualPrivacyFallback) {
5309
- if (!cachedFailure) {
5310
- if (this.localReviewFailures.size >= 256) {
5311
- const oldest = this.localReviewFailures.keys().next().value;
5312
- if (oldest !== void 0) this.localReviewFailures.delete(oldest);
5313
- }
5314
- const failureKey = decision === "review_unavailable" || decision === "review_not_delegated" ? retryKey : evidenceKey;
5315
- this.localReviewFailures.set(failureKey, {
5316
- outcome,
5317
- ...decision === "review_unavailable" ? { expiresAt: now() + 15e3 } : {}
5318
- });
5317
+ requestSignal,
5318
+ interactive ? (reason) => {
5319
+ reviewReason = reason;
5320
+ } : void 0
5321
+ ) : route.kind === "defer" ? failure(
5322
+ "review_evidence_unavailable",
5323
+ options.reviewCoverageDiagnostic ?? reviewDiagnostic("review_evidence_unavailable")
5324
+ ) : { fallback: "ask_user", missing: "unspecified" });
5325
+ const outcome = facts.autoReview && route.kind === "review" && typeof reviewResult === "object" && reviewResult.fallback === "ask_user" && reviewResult.missing === "unspecified" ? failure("review_inconclusive") : reviewResult;
5326
+ const decision = typeof outcome === "object" ? outcome.fallback : outcome;
5327
+ const failureDetails = typeof outcome === "object" && outcome.fallback !== "ask_user" ? outcome : void 0;
5328
+ const diagnostic = failureDetails?.diagnostic;
5329
+ const confirmationCause = failureDetails?.oneTimeConfirmation;
5330
+ const manualPrivacyFallback = confirmationCause === "private_evidence";
5331
+ const manualInconclusiveFallback = facts.autoReview === true && confirmationCause === "inconclusive";
5332
+ const oneTimeConfirmation = manualPrivacyFallback || manualInconclusiveFallback;
5333
+ if (confirmationCause === "inconclusive" || decision === "allow_once" || decision === "deny" || diagnostic && decision !== "review_evidence_unavailable" && diagnostic.code !== "review_preparation_failed")
5334
+ actor = "review";
5335
+ checkCurrent(route.kind === "review");
5336
+ if (interactive && diagnostic && (diagnostic.code === "review_cancelled" || diagnostic.code === "review_authority_changed")) {
5337
+ return expire("approval_expired", diagnostic);
5319
5338
  }
5320
- if (!manualInconclusiveFallback && !interactive) {
5321
- audit(
5322
- "denied",
5323
- decision === "ask_user" ? "review_user_decision_required" : decision,
5324
- void 0,
5325
- diagnostic
5326
- );
5327
- return outcome.fallback === "ask_user" ? rejectLocalReview("ask_user", outcome.missing) : rejectLocalReview(outcome.fallback, void 0, diagnostic);
5339
+ if (decision === "deny" && !interactive) {
5340
+ audit("denied", "review_denied");
5341
+ return facts.autoReview ? rejectLocalReview("deny") : reject("review_denied");
5328
5342
  }
5329
- }
5330
- if (decision !== "allow_once") {
5331
- if (decision === "deny") audit("review_failed", "review_denied");
5332
- else if (diagnostic)
5333
- audit("review_failed", decision, void 0, diagnostic);
5334
- const confirm = this.options.confirmation?.confirm;
5335
- if (!confirm || this.options.confirmation?.available?.() === false) {
5336
- if (manualInconclusiveFallback) {
5337
- audit("denied", "review_inconclusive");
5338
- return reject(
5339
- `${agentReviewReasons.review_inconclusive} Interactive confirmation is unavailable on this connection.`
5340
- );
5343
+ if (retryKey !== void 0 && evidenceKey !== void 0 && outcome !== "allow_once" && outcome !== "deny" && !manualPrivacyFallback) {
5344
+ if (!cachedFailure) {
5345
+ if (this.localReviewFailures.size >= 256) {
5346
+ const oldest = this.localReviewFailures.keys().next().value;
5347
+ if (oldest !== void 0)
5348
+ this.localReviewFailures.delete(oldest);
5349
+ }
5350
+ const failureKey = decision === "review_unavailable" || decision === "review_not_delegated" ? retryKey : evidenceKey;
5351
+ this.localReviewFailures.set(failureKey, {
5352
+ outcome,
5353
+ ...decision === "review_unavailable" ? { expiresAt: now() + 15e3 } : {}
5354
+ });
5341
5355
  }
5342
- if (manualPrivacyFallback)
5343
- return rejectLocalReview(
5344
- "review_evidence_unavailable",
5356
+ if (!manualInconclusiveFallback && !interactive) {
5357
+ audit(
5358
+ "denied",
5359
+ decision === "ask_user" ? "review_user_decision_required" : decision,
5345
5360
  void 0,
5346
5361
  diagnostic
5347
5362
  );
5348
- return reject(
5349
- diagnostic ? `confirmation_required: ${reviewDiagnosticText(diagnostic)}` : "confirmation_required"
5350
- );
5363
+ return outcome.fallback === "ask_user" ? rejectLocalReview("ask_user", outcome.missing) : rejectLocalReview(outcome.fallback, void 0, diagnostic);
5364
+ }
5351
5365
  }
5352
- if (manualInconclusiveFallback) audit("review_failed", decision);
5353
- actor = "user";
5354
- const withheld = manualPrivacyFallback || !!(interactive && diagnostic && isReviewPrivacyFailure(diagnostic.code));
5355
- const preview = withheld && diagnostic ? this.options.review?.privacyConfirmationPreview?.(
5356
- options.preview(),
5357
- request,
5358
- diagnostic
5359
- ) ?? "Command details are hidden here. Inspect the original shell proposal before choosing Run once." : options.preview();
5360
- const checkRouteCurrent = () => {
5361
- checkCurrent();
5362
- if (JSON.stringify(routeApproval(options.evaluate())) !== JSON.stringify(route))
5363
- return expire("authority_changed");
5364
- };
5365
- const ask = async (requestId, choices2, details = {}) => {
5366
- checkRouteCurrent();
5367
- const deadline = (this.options.deadline ?? AbortSignal.timeout)(
5368
- 12e4
5369
- );
5370
- const signal = requestSignal ? AbortSignal.any([deadline, requestSignal]) : deadline;
5371
- const reply = responseRecord(
5372
- await awaitAbortable(
5373
- signal,
5374
- () => confirm(
5375
- {
5376
- requestId,
5377
- subject: request.subject,
5378
- origin: request.origin,
5379
- preview,
5380
- route,
5381
- ...route.kind === "review" || route.kind === "defer" ? {
5382
- reviewFallback: decision === "deny" ? "review_denied" : decision,
5383
- ...reviewReason ? { reviewReason } : {},
5384
- ...diagnostic ? { reviewDiagnostic: diagnostic } : {},
5385
- ...manualPrivacyFallback ? { reviewWithheldForPrivacy: true } : {}
5386
- } : {},
5387
- expiresAt: Date.now() + 12e4,
5388
- choices: choices2,
5389
- ...options.escalation === "unsandboxed" ? {
5390
- escalation: "unsandboxed",
5391
- ...options.protectedPathsEnforced === false ? { protectedPathsEnforced: false } : {}
5392
- } : {},
5393
- ...details
5394
- },
5395
- signal
5396
- )
5397
- )
5398
- );
5399
- if (signal.aborted) return expire("approval_expired");
5400
- checkCurrent();
5401
- if (reply?.requestId !== requestId || !choices2.includes(reply.choice))
5402
- return reject("confirmation_required");
5403
- return reply.choice;
5404
- };
5405
- let choice2;
5406
- if (interactive) {
5407
- const propose = !withheld && !facts.opaque && !facts.humanOnly ? interactive.propose : void 0;
5408
- const selected = await selectShellAllowance({
5366
+ if (decision !== "allow_once") {
5367
+ if (decision === "deny") audit("review_failed", "review_denied");
5368
+ else if (diagnostic)
5369
+ audit("review_failed", decision, void 0, diagnostic);
5370
+ const confirm = this.options.confirmation?.confirm;
5371
+ if (!confirm || this.options.confirmation?.available?.() === false) {
5372
+ if (manualInconclusiveFallback) {
5373
+ audit("denied", "review_inconclusive");
5374
+ return reject(
5375
+ `${agentReviewReasons.review_inconclusive} Interactive confirmation is unavailable on this connection.`
5376
+ );
5377
+ }
5378
+ if (manualPrivacyFallback)
5379
+ return rejectLocalReview(
5380
+ "review_evidence_unavailable",
5381
+ void 0,
5382
+ diagnostic
5383
+ );
5384
+ return reject(
5385
+ diagnostic ? `confirmation_required: ${reviewDiagnosticText(diagnostic)}` : "confirmation_required"
5386
+ );
5387
+ }
5388
+ if (manualInconclusiveFallback) audit("review_failed", decision);
5389
+ actor = "user";
5390
+ const withheld = manualPrivacyFallback || !!(interactive && diagnostic && isReviewPrivacyFailure(diagnostic.code));
5391
+ const preview = withheld && diagnostic ? this.options.review?.privacyConfirmationPreview?.(
5392
+ options.preview(),
5409
5393
  request,
5410
- propose,
5411
- ask,
5412
- checkCurrent: checkRouteCurrent,
5413
- signal: requestSignal
5414
- });
5415
- choice2 = selected.choice;
5416
- save = selected.proposal;
5417
- } else {
5418
- const choices2 = [
5419
- "allow_once",
5420
- "deny_continue",
5421
- "deny_stop"
5422
- ];
5423
- if (!oneTimeConfirmation && save && !facts.opaque && !facts.humanOnly) {
5424
- if ("commit" in save) choices2.push("save_session");
5425
- choices2.push("save_project");
5394
+ diagnostic
5395
+ ) ?? "Command details are hidden here. Inspect the original shell proposal before choosing Run once." : options.preview();
5396
+ const checkRouteCurrent = () => {
5397
+ checkCurrent();
5398
+ if (JSON.stringify(routeApproval(options.evaluate())) !== JSON.stringify(route))
5399
+ return expire("authority_changed");
5400
+ };
5401
+ const ask = async (requestId, choices2, details = {}) => {
5402
+ checkRouteCurrent();
5403
+ const deadline = (this.options.deadline ?? AbortSignal.timeout)(
5404
+ 12e4
5405
+ );
5406
+ const signal = requestSignal ? AbortSignal.any([deadline, requestSignal]) : deadline;
5407
+ const reply = responseRecord(
5408
+ await awaitAbortable(
5409
+ signal,
5410
+ () => confirm(
5411
+ {
5412
+ requestId,
5413
+ subject: request.subject,
5414
+ origin: request.origin,
5415
+ preview,
5416
+ route,
5417
+ ...route.kind === "review" || route.kind === "defer" ? {
5418
+ reviewFallback: decision === "deny" ? "review_denied" : decision,
5419
+ ...reviewReason ? { reviewReason } : {},
5420
+ ...diagnostic ? { reviewDiagnostic: diagnostic } : {},
5421
+ ...manualPrivacyFallback ? { reviewWithheldForPrivacy: true } : {}
5422
+ } : {},
5423
+ expiresAt: Date.now() + 12e4,
5424
+ choices: choices2,
5425
+ ...options.escalation === "unsandboxed" ? {
5426
+ escalation: "unsandboxed",
5427
+ ...options.protectedPathsEnforced === false ? { protectedPathsEnforced: false } : {}
5428
+ } : {},
5429
+ ...details
5430
+ },
5431
+ signal
5432
+ )
5433
+ )
5434
+ );
5435
+ if (signal.aborted) return expire("approval_expired");
5436
+ checkCurrent();
5437
+ if (reply?.requestId !== requestId || !choices2.includes(reply.choice))
5438
+ return reject("confirmation_required");
5439
+ return reply.choice;
5440
+ };
5441
+ let choice2;
5442
+ if (interactive) {
5443
+ const propose = !withheld && !facts.opaque && !facts.humanOnly ? interactive.propose : void 0;
5444
+ const selected = await selectShellAllowance({
5445
+ request,
5446
+ propose,
5447
+ ask,
5448
+ checkCurrent: checkRouteCurrent,
5449
+ signal: requestSignal
5450
+ });
5451
+ choice2 = selected.choice;
5452
+ save = selected.proposal;
5453
+ } else {
5454
+ const choices2 = [
5455
+ "allow_once",
5456
+ "deny_continue",
5457
+ "deny_stop"
5458
+ ];
5459
+ if (!oneTimeConfirmation && save && !facts.opaque && !facts.humanOnly) {
5460
+ if ("commit" in save) choices2.push("save_session");
5461
+ choices2.push("save_project");
5462
+ }
5463
+ if (!oneTimeConfirmation && options.grantSession)
5464
+ choices2.push("grant_session");
5465
+ choice2 = await ask(
5466
+ id2,
5467
+ choices2,
5468
+ !oneTimeConfirmation ? {
5469
+ saveDescription: save?.description,
5470
+ grantDescription: options.grantSession?.description
5471
+ } : {}
5472
+ );
5473
+ }
5474
+ if (choice2 === "grant_session") sessionGrant = options.grantSession;
5475
+ if (choice2 === "save_session") saveScope = "session";
5476
+ if (choice2 === "save_project") saveScope = "project";
5477
+ if (choice2 === "deny_continue" || choice2 === "deny_stop") {
5478
+ audit("denied", "user_denied");
5479
+ return reject("user_denied", choice2 === "deny_stop");
5426
5480
  }
5427
- if (!oneTimeConfirmation && options.grantSession)
5428
- choices2.push("grant_session");
5429
- choice2 = await ask(
5430
- id2,
5431
- choices2,
5432
- !oneTimeConfirmation ? {
5433
- saveDescription: save?.description,
5434
- grantDescription: options.grantSession?.description
5435
- } : {}
5436
- );
5437
5481
  }
5438
- if (choice2 === "grant_session") sessionGrant = options.grantSession;
5439
- if (choice2 === "save_session") saveScope = "session";
5440
- if (choice2 === "save_project") saveScope = "project";
5441
- if (choice2 === "deny_continue" || choice2 === "deny_stop") {
5442
- audit("denied", "user_denied");
5443
- return reject("user_denied", choice2 === "deny_stop");
5482
+ checkCurrent(actor === "review");
5483
+ if (JSON.stringify(routeApproval(options.evaluate())) !== JSON.stringify(route)) {
5484
+ return expire(
5485
+ "authority_changed",
5486
+ actor === "review" ? reviewDiagnostic("review_authority_changed") : void 0
5487
+ );
5444
5488
  }
5445
5489
  }
5446
- checkCurrent(actor === "review");
5447
- if (JSON.stringify(routeApproval(options.evaluate())) !== JSON.stringify(route)) {
5448
- return expire(
5449
- "authority_changed",
5450
- actor === "review" ? reviewDiagnostic("review_authority_changed") : void 0
5451
- );
5452
- }
5453
- }
5454
- sessionGrant?.commit();
5455
- if (saveScope === "project" && save && "rememberProject" in save) {
5456
- try {
5457
- await save.rememberProject();
5458
- } catch (error) {
5459
- if (error instanceof Error && error.message === "approval_expired")
5460
- return expire("approval_expired");
5461
- audit("save_failed", "project_tool_rule_save_failed");
5462
- return reject(
5463
- "project_tool_rule_save_failed: Could not save this workspace permission to the personal policy store. The tool did not run."
5464
- );
5465
- }
5466
- }
5467
- let consumed = false;
5468
- const consume = (details) => {
5469
- if (consumed) reject("approval_already_consumed");
5470
- checkCurrent(actor === "review");
5471
- if (actor === "review" && (this.options.review?.stillApproved?.(request) === false || this.options.review?.reviewVersion && this.options.review.reviewVersion(request) !== version)) {
5472
- const diagnostic = reviewDiagnostic("review_authority_changed");
5473
- audit("expired", "review_authority_changed", void 0, diagnostic);
5474
- return reject(
5475
- `approval_expired: ${reviewDiagnosticText(diagnostic)}`
5476
- );
5477
- }
5478
- consumed = true;
5479
- if (saveScope && save && "commit" in save) {
5490
+ sessionGrant?.commit();
5491
+ if (saveScope === "project" && save && "rememberProject" in save) {
5480
5492
  try {
5481
- save.commit(saveScope);
5482
- } catch {
5483
- audit("save_failed", "launch_rule_save_failed");
5493
+ await save.rememberProject();
5494
+ } catch (error) {
5495
+ if (error instanceof Error && error.message === "approval_expired")
5496
+ return expire("approval_expired");
5497
+ audit("save_failed", "project_tool_rule_save_failed");
5498
+ return reject(
5499
+ "project_tool_rule_save_failed: Could not save this workspace permission to the personal policy store. The tool did not run."
5500
+ );
5484
5501
  }
5485
5502
  }
5486
- audit("dispatch", route.reason, details?.taskId);
5487
- };
5488
- if (!options.deferConsumption) consume();
5489
- return options.execute(consume, saveScope);
5503
+ let consumed = false;
5504
+ const consume = (details) => {
5505
+ if (consumed) reject("approval_already_consumed");
5506
+ checkCurrent(actor === "review");
5507
+ if (actor === "review" && (this.options.review?.stillApproved?.(request) === false || this.options.review?.reviewVersion && this.options.review.reviewVersion(request) !== version)) {
5508
+ const diagnostic = reviewDiagnostic("review_authority_changed");
5509
+ audit("expired", "review_authority_changed", void 0, diagnostic);
5510
+ return reject(
5511
+ `approval_expired: ${reviewDiagnosticText(diagnostic)}`
5512
+ );
5513
+ }
5514
+ consumed = true;
5515
+ if (saveScope && save && "commit" in save) {
5516
+ try {
5517
+ save.commit(saveScope);
5518
+ } catch {
5519
+ audit("save_failed", "launch_rule_save_failed");
5520
+ }
5521
+ }
5522
+ audit("dispatch", route.reason, details?.taskId);
5523
+ };
5524
+ if (!options.deferConsumption) consume();
5525
+ recordApprovalWait();
5526
+ return options.execute(consume, saveScope);
5527
+ } finally {
5528
+ recordApprovalWait();
5529
+ }
5490
5530
  };
5491
5531
  return receiptBinding !== void 0 ? this.requests.run(scope, id2, receiptBinding, dispatch) : Promise.resolve().then(dispatch);
5492
5532
  }
@@ -5925,14 +5965,14 @@ var readBrowserMode = (value) => {
5925
5965
  return null;
5926
5966
  };
5927
5967
  var hasSshSession = (env) => !!env.SSH_CONNECTION || !!env.SSH_CLIENT || !!env.SSH_TTY;
5928
- var resolveOAuthBrowserMode = (env = process.env) => {
5929
- const configured = readBrowserMode(env.CODELIA_OAUTH_BROWSER);
5968
+ var resolveOAuthBrowserMode = (configuredMode, env = process.env) => {
5969
+ const configured = readBrowserMode(configuredMode);
5930
5970
  if (configured) {
5931
5971
  return configured;
5932
5972
  }
5933
5973
  return hasSshSession(env) ? "manual" : "auto";
5934
5974
  };
5935
- var shouldAutoOpenOAuthBrowser = (env = process.env) => resolveOAuthBrowserMode(env) === "auto";
5975
+ var shouldAutoOpenOAuthBrowser = (configuredMode, env = process.env) => resolveOAuthBrowserMode(configuredMode, env) === "auto";
5936
5976
  var parseCallbackParams = (input) => {
5937
5977
  const trimmed = input.trim();
5938
5978
  if (!trimmed) {
@@ -6102,7 +6142,7 @@ var OPENAI_OAUTH_ORIGINATOR = "codelia";
6102
6142
  var OPENAI_OAUTH_USER_AGENT = "codelia-cli";
6103
6143
  var HTML_SUCCESS = "<!doctype html><html><head><title>codelia - Authorization successful</title></head><body><h2>Authorization successful</h2><p>You can close this window.</p></body></html>";
6104
6144
  var HTML_ERROR = (message) => `<!doctype html><html><head><title>codelia - Authorization failed</title></head><body><h2>Authorization failed</h2><pre>${message}</pre></body></html>`;
6105
- var clientId = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID;
6145
+ var clientId = () => DEFAULT_CLIENT_ID;
6106
6146
  var oauthPort = () => readPositiveIntEnv("CODELIA_OPENAI_OAUTH_PORT", DEFAULT_PORT);
6107
6147
  var buildAuthorizeUrl = (redirectUri, pkce, state) => {
6108
6148
  const params = new URLSearchParams({
@@ -6360,11 +6400,8 @@ var DEFAULT_CLIENT_ID2 = "app_EMoamEEZ73f0CkXaXp7hrann";
6360
6400
  var ISSUER2 = "https://auth.openai.com";
6361
6401
  var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
6362
6402
  var DEFAULT_INTERVAL_SECONDS = 5;
6363
- var clientId2 = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID2;
6364
- var deviceCodeTimeoutMs = () => readPositiveIntEnv(
6365
- "CODELIA_OPENAI_DEVICE_CODE_TIMEOUT_MS",
6366
- DEFAULT_TIMEOUT_MS
6367
- );
6403
+ var clientId2 = () => DEFAULT_CLIENT_ID2;
6404
+ var deviceCodeTimeoutMs = () => DEFAULT_TIMEOUT_MS;
6368
6405
  var cancelledError = () => new Error("device code login cancelled");
6369
6406
  var sleep = (ms, signal) => new Promise((resolve, reject2) => {
6370
6407
  if (signal?.aborted) {
@@ -7017,7 +7054,10 @@ var AuthResolver = class _AuthResolver {
7017
7054
  if (!supportsPick || !supportsPrompt) {
7018
7055
  throw new Error("UI does not support auth prompts");
7019
7056
  }
7020
- const prefersDeviceCode = resolveOAuthBrowserMode() === "manual";
7057
+ const configuredBrowser = await resolveAuthOAuthBrowser(
7058
+ this.state.runtimeWorkingDir ?? void 0
7059
+ ).catch(() => void 0);
7060
+ const prefersDeviceCode = resolveOAuthBrowserMode(configuredBrowser) === "manual";
7021
7061
  const pick = await requestUiPick(this.state, {
7022
7062
  title: "How would you like to connect OpenAI?",
7023
7063
  items: prefersDeviceCode ? [
@@ -7076,7 +7116,10 @@ var AuthResolver = class _AuthResolver {
7076
7116
  throw new Error("UI does not support device code confirmation");
7077
7117
  }
7078
7118
  const session = await createOpenAiDeviceCodeSession();
7079
- const shouldAutoOpen = shouldAutoOpenOAuthBrowser();
7119
+ const configuredBrowser = await resolveAuthOAuthBrowser(
7120
+ this.state.runtimeWorkingDir ?? void 0
7121
+ ).catch(() => void 0);
7122
+ const shouldAutoOpen = shouldAutoOpenOAuthBrowser(configuredBrowser);
7080
7123
  const confirm = await requestUiConfirm(this.state, {
7081
7124
  title: "OpenAI device code",
7082
7125
  message: [
@@ -7119,7 +7162,10 @@ var AuthResolver = class _AuthResolver {
7119
7162
  if (!supportsConfirm) {
7120
7163
  throw new Error("UI does not support OAuth confirmation");
7121
7164
  }
7122
- const shouldAutoOpen = shouldAutoOpenOAuthBrowser();
7165
+ const configuredBrowser = await resolveAuthOAuthBrowser(
7166
+ this.state.runtimeWorkingDir ?? void 0
7167
+ ).catch(() => void 0);
7168
+ const shouldAutoOpen = shouldAutoOpenOAuthBrowser(configuredBrowser);
7123
7169
  const canPasteCallback = !shouldAutoOpen && supportsPrompt;
7124
7170
  const session = await createOAuthSession({
7125
7171
  callbackMode: canPasteCallback ? "paste" : "server"
@@ -12473,6 +12519,7 @@ MCP environment keys: ${serviceLaunch.names.join(", ")}` : ""}`,
12473
12519
  } : {},
12474
12520
  ...confirmationOptions,
12475
12521
  deferConsumption: true,
12522
+ ...input.onApprovalWaitMs ? { onApprovalWaitMs: input.onApprovalWaitMs } : {},
12476
12523
  execute: (consume, saveScope) => execute((taskId) => {
12477
12524
  const boundLaunch = candidate && (saveScope || reliedOnRule);
12478
12525
  if (boundLaunch && backend.supportsExactLaunchBinding?.(candidate, protection) !== true)
@@ -13059,9 +13106,6 @@ var resolveRuntimeSandboxMode = async (environment, input = {}) => {
13059
13106
  const modeFlag = readFlag(args, "--sandbox-mode");
13060
13107
  if (modeFlag !== void 0)
13061
13108
  return parseMode(modeFlag, "--sandbox-mode", "cli", false);
13062
- const legacyFlag = readFlag(args, "--approval-mode");
13063
- if (legacyFlag !== void 0)
13064
- return parseMode(legacyFlag, "--approval-mode", "cli", true);
13065
13109
  if (env.CODELIA_SANDBOX_MODE !== void 0)
13066
13110
  return parseMode(
13067
13111
  env.CODELIA_SANDBOX_MODE,
@@ -13069,13 +13113,6 @@ var resolveRuntimeSandboxMode = async (environment, input = {}) => {
13069
13113
  "env",
13070
13114
  false
13071
13115
  );
13072
- if (env.CODELIA_APPROVAL_MODE !== void 0)
13073
- return parseMode(
13074
- env.CODELIA_APPROVAL_MODE,
13075
- "CODELIA_APPROVAL_MODE",
13076
- "env",
13077
- true
13078
- );
13079
13116
  const store = input.store ?? new import_storage12.ProjectsPolicyStore();
13080
13117
  const projectKey = await import_node_fs28.promises.realpath(root).catch((error) => {
13081
13118
  if (error.code !== "ENOENT") throw error;
@@ -13097,6 +13134,213 @@ var resolveRuntimeSandboxMode = async (environment, input = {}) => {
13097
13134
  return defaultSandboxMode;
13098
13135
  };
13099
13136
 
13137
+ // src/telemetry.ts
13138
+ var MAX_RECENT_CALLS = 64;
13139
+ var MAX_RECENT_TOOLS = 64;
13140
+ var cloneModelUsage = (entry) => ({
13141
+ ...entry
13142
+ });
13143
+ var createEmptyTelemetrySummary = () => ({
13144
+ total_calls: 0,
13145
+ total_tokens: 0,
13146
+ total_input_tokens: 0,
13147
+ total_output_tokens: 0,
13148
+ total_output_reasoning_tokens: 0,
13149
+ total_cached_input_tokens: 0,
13150
+ total_cache_creation_tokens: 0,
13151
+ total_input_image_tokens: 0,
13152
+ cache_hit_calls: 0,
13153
+ cache_miss_calls: 0,
13154
+ cache_unknown_calls: 0,
13155
+ total_cost_usd: null,
13156
+ retry_count: 0,
13157
+ retry_wait_ms: 0,
13158
+ tool_calls: 0,
13159
+ tool_errors: 0,
13160
+ tool_exec_ms: 0,
13161
+ tool_approval_wait_ms: 0,
13162
+ compaction_count: 0,
13163
+ compaction_duration_ms: 0,
13164
+ by_model: {}
13165
+ });
13166
+ var cloneTelemetrySummary = (summary) => ({
13167
+ ...summary,
13168
+ by_model: Object.fromEntries(
13169
+ Object.entries(summary.by_model).map(([model, entry]) => [
13170
+ model,
13171
+ cloneModelUsage(entry)
13172
+ ])
13173
+ )
13174
+ });
13175
+ var applyCallToSummary = (summary, call) => {
13176
+ const usage = call.usage ?? null;
13177
+ const inputTokens = usage?.input_tokens ?? 0;
13178
+ const outputTokens = usage?.output_tokens ?? 0;
13179
+ const reasoningTokens = usage?.output_reasoning_tokens ?? 0;
13180
+ const cachedTokens = usage?.input_cached_tokens ?? 0;
13181
+ const cacheCreationTokens = usage?.input_cache_creation_tokens ?? 0;
13182
+ const imageTokens = usage?.input_image_tokens ?? 0;
13183
+ const totalTokens = usage?.total_tokens ?? 0;
13184
+ const hitState = call.cache?.hit_state ?? (typeof usage?.input_cached_tokens === "number" ? cachedTokens > 0 ? "hit" : "miss" : "unknown");
13185
+ const validCost = typeof call.cost_usd === "number" && Number.isFinite(call.cost_usd) && call.cost_usd >= 0 ? call.cost_usd : null;
13186
+ summary.total_calls += 1;
13187
+ summary.total_tokens += totalTokens;
13188
+ summary.total_input_tokens += inputTokens;
13189
+ summary.total_output_tokens += outputTokens;
13190
+ summary.total_output_reasoning_tokens += reasoningTokens;
13191
+ summary.total_cached_input_tokens += cachedTokens;
13192
+ summary.total_cache_creation_tokens += cacheCreationTokens;
13193
+ summary.total_input_image_tokens += imageTokens;
13194
+ if (hitState === "hit") summary.cache_hit_calls += 1;
13195
+ else if (hitState === "miss") summary.cache_miss_calls += 1;
13196
+ else summary.cache_unknown_calls += 1;
13197
+ if (validCost !== null) {
13198
+ summary.total_cost_usd = (summary.total_cost_usd ?? 0) + validCost;
13199
+ }
13200
+ const modelKey = call.model ?? "unknown";
13201
+ const existing = summary.by_model[modelKey];
13202
+ if (!existing) {
13203
+ summary.by_model[modelKey] = {
13204
+ calls: 1,
13205
+ input_tokens: inputTokens,
13206
+ output_tokens: outputTokens,
13207
+ output_reasoning_tokens: reasoningTokens,
13208
+ cached_input_tokens: cachedTokens,
13209
+ cache_creation_tokens: cacheCreationTokens,
13210
+ input_image_tokens: imageTokens,
13211
+ cache_hit_calls: hitState === "hit" ? 1 : 0,
13212
+ cache_miss_calls: hitState === "miss" ? 1 : 0,
13213
+ cache_unknown_calls: hitState === "unknown" ? 1 : 0,
13214
+ total_tokens: totalTokens,
13215
+ cost_usd: validCost
13216
+ };
13217
+ } else {
13218
+ existing.calls += 1;
13219
+ existing.input_tokens += inputTokens;
13220
+ existing.output_tokens += outputTokens;
13221
+ existing.output_reasoning_tokens += reasoningTokens;
13222
+ existing.cached_input_tokens += cachedTokens;
13223
+ existing.cache_creation_tokens += cacheCreationTokens;
13224
+ existing.input_image_tokens += imageTokens;
13225
+ if (hitState === "hit") existing.cache_hit_calls += 1;
13226
+ else if (hitState === "miss") existing.cache_miss_calls += 1;
13227
+ else existing.cache_unknown_calls += 1;
13228
+ existing.total_tokens += totalTokens;
13229
+ if (validCost !== null) {
13230
+ existing.cost_usd = (existing.cost_usd ?? 0) + validCost;
13231
+ }
13232
+ }
13233
+ };
13234
+ var applyToolToSummary = (summary, record) => {
13235
+ summary.tool_calls += 1;
13236
+ if (record.status === "error") {
13237
+ summary.tool_errors += 1;
13238
+ }
13239
+ summary.tool_exec_ms += Math.max(
13240
+ 0,
13241
+ record.exec_duration_ms ?? record.duration_ms
13242
+ );
13243
+ summary.tool_approval_wait_ms += Math.max(0, record.approval_wait_ms ?? 0);
13244
+ };
13245
+ var applyRetryToSummary = (summary, delayMs) => {
13246
+ summary.retry_count += 1;
13247
+ summary.retry_wait_ms += Math.max(0, Math.round(delayMs));
13248
+ };
13249
+ var applyCompactionToSummary = (summary, durationMs) => {
13250
+ summary.compaction_count += 1;
13251
+ summary.compaction_duration_ms += Math.max(0, durationMs);
13252
+ };
13253
+ var RuntimeTelemetryStore = class {
13254
+ sessionSummary = createEmptyTelemetrySummary();
13255
+ currentRunId = null;
13256
+ currentRunSummary = null;
13257
+ recentCalls = [];
13258
+ recentTools = [];
13259
+ startupPhases = [];
13260
+ agentInitPhases = [];
13261
+ resetSession() {
13262
+ this.sessionSummary = createEmptyTelemetrySummary();
13263
+ this.currentRunId = null;
13264
+ this.currentRunSummary = null;
13265
+ this.recentCalls.length = 0;
13266
+ this.recentTools.length = 0;
13267
+ }
13268
+ beginRun(runId) {
13269
+ this.currentRunId = runId;
13270
+ this.currentRunSummary = createEmptyTelemetrySummary();
13271
+ }
13272
+ recordLlmCall(call) {
13273
+ applyCallToSummary(this.sessionSummary, call);
13274
+ if (this.currentRunId === call.run_id && this.currentRunSummary) {
13275
+ applyCallToSummary(this.currentRunSummary, call);
13276
+ }
13277
+ const { session: _session, ...callRecord } = call;
13278
+ this.recentCalls.push(callRecord);
13279
+ if (this.recentCalls.length > MAX_RECENT_CALLS) {
13280
+ this.recentCalls.shift();
13281
+ }
13282
+ }
13283
+ recordToolComplete(record) {
13284
+ applyToolToSummary(this.sessionSummary, record);
13285
+ if (this.currentRunId === record.run_id && this.currentRunSummary) {
13286
+ applyToolToSummary(this.currentRunSummary, record);
13287
+ }
13288
+ this.recentTools.push(record);
13289
+ if (this.recentTools.length > MAX_RECENT_TOOLS) {
13290
+ this.recentTools.shift();
13291
+ }
13292
+ }
13293
+ recordRetry(runId, delayMs) {
13294
+ applyRetryToSummary(this.sessionSummary, delayMs);
13295
+ if (this.currentRunId === runId && this.currentRunSummary) {
13296
+ applyRetryToSummary(this.currentRunSummary, delayMs);
13297
+ }
13298
+ }
13299
+ recordRetryWait(runId, waitMs) {
13300
+ const rounded = Math.max(0, Math.round(waitMs));
13301
+ this.sessionSummary.retry_wait_ms += rounded;
13302
+ if (this.currentRunId === runId && this.currentRunSummary) {
13303
+ this.currentRunSummary.retry_wait_ms += rounded;
13304
+ }
13305
+ }
13306
+ recordCompaction(runId, durationMs) {
13307
+ applyCompactionToSummary(this.sessionSummary, durationMs);
13308
+ if (this.currentRunId === runId && this.currentRunSummary) {
13309
+ applyCompactionToSummary(this.currentRunSummary, durationMs);
13310
+ }
13311
+ }
13312
+ recordStartupPhase(name2, durationMs) {
13313
+ this.startupPhases.push({
13314
+ name: name2,
13315
+ duration_ms: Math.max(0, Math.round(durationMs))
13316
+ });
13317
+ }
13318
+ setAgentInitPhases(phases) {
13319
+ this.agentInitPhases = phases.map((phase) => ({
13320
+ name: phase.name,
13321
+ duration_ms: Math.max(0, Math.round(phase.duration_ms))
13322
+ }));
13323
+ }
13324
+ getSessionSummary() {
13325
+ return cloneTelemetrySummary(this.sessionSummary);
13326
+ }
13327
+ getRunSummary() {
13328
+ return this.currentRunSummary ? cloneTelemetrySummary(this.currentRunSummary) : null;
13329
+ }
13330
+ getRecentCalls() {
13331
+ return this.recentCalls.slice();
13332
+ }
13333
+ getRecentTools() {
13334
+ return this.recentTools.slice();
13335
+ }
13336
+ getStartupPhases() {
13337
+ return this.startupPhases.slice();
13338
+ }
13339
+ getAgentInitPhases() {
13340
+ return this.agentInitPhases.slice();
13341
+ }
13342
+ };
13343
+
13100
13344
  // src/runtime-state.ts
13101
13345
  var RuntimeState = class {
13102
13346
  attachments;
@@ -13229,6 +13473,7 @@ var RuntimeState = class {
13229
13473
  set sessionId(value) {
13230
13474
  if (value === this.boundSessionId) return;
13231
13475
  this.boundSessionId = value;
13476
+ this.telemetry.resetSession();
13232
13477
  this.receiptOwner.abort();
13233
13478
  this.receiptOwner = new AbortController();
13234
13479
  this.signalApprovalChange();
@@ -13292,7 +13537,7 @@ var RuntimeState = class {
13292
13537
  currentModelName = null;
13293
13538
  currentModelSource = null;
13294
13539
  sessionModelOverride = null;
13295
- diagnosticsEnabled = false;
13540
+ telemetry = new RuntimeTelemetryStore();
13296
13541
  setRuntimeEnvironment(options) {
13297
13542
  this.effectiveEnvironment = resolveRuntimeEnvironment(options);
13298
13543
  const value = this.effectiveEnvironment.workspace.sandboxMode;
@@ -13936,25 +14181,6 @@ var toTrimmed = (value) => {
13936
14181
  const trimmed = value.trim();
13937
14182
  return trimmed.length > 0 ? trimmed : void 0;
13938
14183
  };
13939
- var parseBoolean = (value) => {
13940
- const normalized = toTrimmed(value)?.toLowerCase();
13941
- if (!normalized) return void 0;
13942
- if (normalized === "1" || normalized === "true") return true;
13943
- if (normalized === "0" || normalized === "false") return false;
13944
- return void 0;
13945
- };
13946
- var parsePositiveInt = (value) => {
13947
- const normalized = toTrimmed(value);
13948
- if (!normalized) return void 0;
13949
- const parsed = Number.parseInt(normalized, 10);
13950
- return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
13951
- };
13952
- var parseMarkers = (value) => {
13953
- const normalized = toTrimmed(value);
13954
- if (!normalized) return void 0;
13955
- const markers = normalized.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
13956
- return markers.length > 0 ? markers : void 0;
13957
- };
13958
14184
  var exists = async (targetPath) => {
13959
14185
  try {
13960
14186
  await import_node_fs30.promises.access(targetPath);
@@ -14025,37 +14251,12 @@ var findRootByMarkers = async (workingDir, markers, stopAtFsRoot, reader) => {
14025
14251
  }
14026
14252
  };
14027
14253
  var mergeConfig = (config, env = process.env) => {
14028
- const envConfig = AgentsConfigSchema.parse({
14029
- enabled: parseBoolean(env.CODELIA_AGENTS_ENABLED),
14030
- root: {
14031
- projectRootOverride: toTrimmed(env.CODELIA_AGENTS_ROOT),
14032
- markers: parseMarkers(env.CODELIA_AGENTS_MARKERS)
14033
- },
14034
- initial: {
14035
- maxFiles: parsePositiveInt(env.CODELIA_AGENTS_INITIAL_MAX_FILES),
14036
- maxBytes: parsePositiveInt(env.CODELIA_AGENTS_INITIAL_MAX_BYTES)
14037
- },
14038
- resolver: {
14039
- enabled: parseBoolean(env.CODELIA_AGENTS_RESOLVER_ENABLED),
14040
- maxFilesPerResolve: parsePositiveInt(
14041
- env.CODELIA_AGENTS_MAX_FILES_PER_RESOLVE
14042
- )
14043
- }
14044
- });
14254
+ const rootOverride = toTrimmed(env.CODELIA_AGENTS_ROOT);
14045
14255
  const merged = AgentsConfigSchema.parse({
14046
14256
  ...config ?? {},
14047
- ...envConfig,
14048
14257
  root: {
14049
14258
  ...config?.root ?? {},
14050
- ...envConfig.root ?? {}
14051
- },
14052
- initial: {
14053
- ...config?.initial ?? {},
14054
- ...envConfig.initial ?? {}
14055
- },
14056
- resolver: {
14057
- ...config?.resolver ?? {},
14058
- ...envConfig.resolver ?? {}
14259
+ ...rootOverride ? { projectRootOverride: rootOverride } : {}
14059
14260
  }
14060
14261
  });
14061
14262
  return {
@@ -16291,10 +16492,7 @@ var HTML_SUCCESS2 = "<!doctype html><html><head><title>codelia - MCP authorizati
16291
16492
  var HTML_ERROR2 = (message) => `<!doctype html><html><head><title>codelia - MCP authorization failed</title></head><body><h2>Authorization failed</h2><pre>${message}</pre></body></html>`;
16292
16493
  var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16293
16494
  var oauthPort2 = () => readPositiveIntEnv("CODELIA_MCP_OAUTH_PORT", DEFAULT_MCP_OAUTH_PORT);
16294
- var oauthWaitTimeoutMs = () => readPositiveIntEnv(
16295
- "CODELIA_MCP_OAUTH_TIMEOUT_MS",
16296
- DEFAULT_MCP_OAUTH_WAIT_TIMEOUT_MS
16297
- );
16495
+ var oauthWaitTimeoutMs = () => DEFAULT_MCP_OAUTH_WAIT_TIMEOUT_MS;
16298
16496
  var buildAuthorizeUrl2 = (authorizationUrl, redirectUri, clientId3, pkce, state, scope, resource) => {
16299
16497
  const url = new URL(authorizationUrl);
16300
16498
  url.searchParams.set("response_type", "code");
@@ -16606,6 +16804,7 @@ var requestMcpOAuthTokens = async (gateway, serverId, oauth2, errorMessage, sign
16606
16804
 
16607
16805
  // src/model-factory.ts
16608
16806
  var import_core10 = require("@codelia/core");
16807
+ var import_logger8 = require("@codelia/logger");
16609
16808
  var import_model_metadata = require("@codelia/model-metadata");
16610
16809
  var import_storage16 = require("@codelia/storage");
16611
16810
 
@@ -17092,17 +17291,12 @@ var requireApiKeyAuth = (provider, auth) => {
17092
17291
  }
17093
17292
  return auth.api_key;
17094
17293
  };
17095
- var envTruthy = (value) => {
17096
- if (!value) return false;
17097
- const normalized = value.trim().toLowerCase();
17098
- return normalized === "1" || normalized === "true";
17099
- };
17100
17294
  var buildOpenAiClientOptions = (getOpenAiAccessToken, auth, log2) => {
17101
17295
  if (auth.method === "api_key") {
17102
17296
  return { apiKey: auth.api_key };
17103
17297
  }
17104
17298
  let accountId = auth.oauth.account_id;
17105
- const enableDebugHttp = envTruthy(process.env.CODELIA_DEBUG);
17299
+ const enableDebugHttp = (0, import_logger8.isDebugEnabled)();
17106
17300
  const apiKey = async () => {
17107
17301
  if (!getOpenAiAccessToken) {
17108
17302
  throw new Error("OpenAI OAuth token refresh is unavailable");
@@ -17564,6 +17758,7 @@ var withOpenRouterDynamicModel = (registry, llm, entry) => {
17564
17758
  ...contextWindow ? { contextWindow } : {},
17565
17759
  ...maxInputTokens ? { maxInputTokens } : {},
17566
17760
  ...maxOutputTokens ? { maxOutputTokens } : {},
17761
+ ...entry.cost ? { cost: entry.cost } : {},
17567
17762
  ...entry.capabilities?.supportsVision !== void 0 ? { supportsVision: entry.capabilities.supportsVision } : {},
17568
17763
  ...entry.capabilities?.supportsTools !== void 0 ? { supportsTools: entry.capabilities.supportsTools } : {}
17569
17764
  }
@@ -19022,7 +19217,8 @@ var createRuntimeToolApproval = ({
19022
19217
  ...workspaceGrant ? { grantSession: workspaceGrant } : {},
19023
19218
  signal: state.approvalSignal(ctx.signal),
19024
19219
  execute,
19025
- deferConsumption: files?.deferConsumption
19220
+ deferConsumption: files?.deferConsumption,
19221
+ ...ctx.recordApprovalWaitMs ? { onApprovalWaitMs: ctx.recordApprovalWaitMs } : {}
19026
19222
  });
19027
19223
  };
19028
19224
  const authorize = async (origin, call, raw, ctx) => {
@@ -19290,12 +19486,6 @@ var toTrimmed2 = (value) => {
19290
19486
  const trimmed = value.trim();
19291
19487
  return trimmed ? trimmed : void 0;
19292
19488
  };
19293
- var parseMarkers2 = (value) => {
19294
- const normalized = toTrimmed2(value);
19295
- if (!normalized) return void 0;
19296
- const markers = normalized.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
19297
- return markers.length > 0 ? markers : void 0;
19298
- };
19299
19489
  var exists2 = async (targetPath) => {
19300
19490
  try {
19301
19491
  await import_node_fs35.promises.access(targetPath);
@@ -19394,7 +19584,7 @@ var SkillsResolver = class _SkillsResolver {
19394
19584
  const env = options.env ?? process.env;
19395
19585
  const workingDir = import_node_path38.default.resolve(options.workingDir);
19396
19586
  const rootOverride = toTrimmed2(env.CODELIA_AGENTS_ROOT);
19397
- const markers = parseMarkers2(env.CODELIA_AGENTS_MARKERS) ?? DEFAULT_MARKERS2;
19587
+ const markers = options.markers?.length ? options.markers : DEFAULT_MARKERS2;
19398
19588
  const rootDir = rootOverride ? import_node_path38.default.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers, options.reader);
19399
19589
  const homeDir = toTrimmed2(env.HOME) ?? import_node_os9.default.homedir();
19400
19590
  const userSkillsDir = import_node_path38.default.join(import_node_path38.default.resolve(homeDir), ".agents", "skills");
@@ -21616,6 +21806,12 @@ var AgentTreeCoordinator = class {
21616
21806
  isAvailable() {
21617
21807
  return this.factory.isAvailable();
21618
21808
  }
21809
+ getPerfStats() {
21810
+ return {
21811
+ active: this.active.size,
21812
+ maxConcurrent: this.parent?.subagent?.max_concurrent ?? DEFAULT_MAX_CONCURRENT
21813
+ };
21814
+ }
21619
21815
  serialize(fn) {
21620
21816
  const next = this.queue.then(fn, fn);
21621
21817
  this.queue = next.then(
@@ -23080,23 +23276,8 @@ var import_node_fs41 = require("fs");
23080
23276
  var import_core23 = require("@codelia/core");
23081
23277
  var import_zod33 = require("zod");
23082
23278
  var DEFAULT_READ_LIMIT = 2e3;
23083
- var DEFAULT_MAX_LINE_LENGTH = 1e3;
23084
- var DEFAULT_MAX_BYTES = 64 * 1024;
23085
- var parsePositiveIntEnv = (key, fallback) => {
23086
- const raw = process.env[key];
23087
- if (!raw) return fallback;
23088
- const parsed = Number.parseInt(raw, 10);
23089
- if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
23090
- return parsed;
23091
- };
23092
- var MAX_LINE_LENGTH = parsePositiveIntEnv(
23093
- "CODELIA_READ_MAX_LINE_LENGTH",
23094
- DEFAULT_MAX_LINE_LENGTH
23095
- );
23096
- var MAX_BYTES = parsePositiveIntEnv(
23097
- "CODELIA_READ_MAX_BYTES",
23098
- DEFAULT_MAX_BYTES
23099
- );
23279
+ var MAX_LINE_LENGTH = 1e3;
23280
+ var MAX_BYTES = 64 * 1024;
23100
23281
  var clipLongLine = (line) => {
23101
23282
  if (line.length <= MAX_LINE_LENGTH) {
23102
23283
  return line;
@@ -23881,7 +24062,8 @@ var createShellTool = (sandboxKey, options = {}) => {
23881
24062
  origin: getOperatorContext(ctx) ? "operator" : "parent_agent",
23882
24063
  signal: ctx.signal,
23883
24064
  owner: sessionContext?.sessionId ?? void 0,
23884
- reviewHistory: input.approval_context
24065
+ reviewHistory: input.approval_context,
24066
+ ...ctx.recordApprovalWaitMs ? { onApprovalWaitMs: ctx.recordApprovalWaitMs } : {}
23885
24067
  },
23886
24068
  async (admission) => {
23887
24069
  try {
@@ -24639,7 +24821,7 @@ var import_node_fs43 = require("fs");
24639
24821
  var import_node_path44 = __toESM(require("path"), 1);
24640
24822
  var import_core31 = require("@codelia/core");
24641
24823
  var import_zod41 = require("zod");
24642
- var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
24824
+ var DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
24643
24825
  var MAX_MAX_BYTES = 10 * 1024 * 1024;
24644
24826
  var MIME_BY_EXTENSION = {
24645
24827
  ".png": "image/png",
@@ -24710,7 +24892,7 @@ var createViewImageTool = (sandboxKey) => (0, import_core31.defineTool)({
24710
24892
  if (stat2.isDirectory()) {
24711
24893
  return `Path is a directory: ${input.file_path}`;
24712
24894
  }
24713
- const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES2;
24895
+ const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES;
24714
24896
  if (stat2.size > maxBytes) {
24715
24897
  return `Image too large: ${input.file_path} (${stat2.size} bytes > ${maxBytes} bytes)`;
24716
24898
  }
@@ -24747,7 +24929,7 @@ var import_core32 = require("@codelia/core");
24747
24929
  var import_zod42 = require("zod");
24748
24930
  var DEFAULT_TIMEOUT_MS4 = 1e4;
24749
24931
  var MAX_TIMEOUT_MS = 3e4;
24750
- var DEFAULT_MAX_BYTES3 = 2e5;
24932
+ var DEFAULT_MAX_BYTES2 = 2e5;
24751
24933
  var MAX_MAX_BYTES2 = 1e6;
24752
24934
  var TLS_ERROR_CODES = /* @__PURE__ */ new Set([
24753
24935
  "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
@@ -25007,7 +25189,7 @@ var createWebfetchTool = () => (0, import_core32.defineTool)({
25007
25189
  `Fetch timeout in ms. Default ${DEFAULT_TIMEOUT_MS4}, Max ${MAX_TIMEOUT_MS}.`
25008
25190
  ),
25009
25191
  max_bytes: import_zod42.z.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
25010
- `Max response bytes to keep. Default ${DEFAULT_MAX_BYTES3}, Max ${MAX_MAX_BYTES2}.`
25192
+ `Max response bytes to keep. Default ${DEFAULT_MAX_BYTES2}, Max ${MAX_MAX_BYTES2}.`
25011
25193
  )
25012
25194
  }),
25013
25195
  execute: async (input) => {
@@ -25021,7 +25203,7 @@ var createWebfetchTool = () => (0, import_core32.defineTool)({
25021
25203
  return `Unsupported URL protocol: ${url.protocol}`;
25022
25204
  }
25023
25205
  const timeoutMs = input.timeout_ms ?? DEFAULT_TIMEOUT_MS4;
25024
- const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES3;
25206
+ const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES2;
25025
25207
  const outputFormat = input.output_format ?? "markdown";
25026
25208
  const startedAt = Date.now();
25027
25209
  const controller = new AbortController();
@@ -25418,11 +25600,6 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn8) => {
25418
25600
  };
25419
25601
 
25420
25602
  // src/agent-factory.ts
25421
- var envTruthy2 = (value) => {
25422
- if (!value) return false;
25423
- const normalized = value.trim().toLowerCase();
25424
- return normalized === "1" || normalized === "true";
25425
- };
25426
25603
  var sleep2 = (ms) => new Promise((resolve) => {
25427
25604
  setTimeout(resolve, ms);
25428
25605
  });
@@ -25438,13 +25615,16 @@ var waitForUiConfirmSupport = async (state, timeoutMs = 5e3, signal) => {
25438
25615
  return !signal?.aborted && !!state.uiCapabilities?.supports_confirm;
25439
25616
  };
25440
25617
  var requestMcpOAuthTokens2 = async (state, serverId, oauth2, errorMessage, signal) => {
25618
+ const configuredBrowser = state.effectiveEnvironment.config.source === "disabled" ? void 0 : await resolveAuthOAuthBrowser(
25619
+ state.runtimeWorkingDir ?? void 0
25620
+ ).catch(() => void 0);
25441
25621
  const gateway = {
25442
25622
  runId: state.activeRunId ?? void 0,
25443
25623
  supportsPrompt: !!state.uiCapabilities?.supports_prompt,
25444
25624
  waitForConfirmSupport: () => waitForUiConfirmSupport(state, 5e3, signal),
25445
25625
  confirm: (params) => requestUiConfirm(state, params, signal),
25446
25626
  prompt: (params) => requestUiPrompt(state, params, signal),
25447
- shouldAutoOpenBrowser: shouldAutoOpenOAuthBrowser,
25627
+ shouldAutoOpenBrowser: () => shouldAutoOpenOAuthBrowser(configuredBrowser),
25448
25628
  openBrowser,
25449
25629
  log: import_logger.log
25450
25630
  };
@@ -25508,13 +25688,28 @@ var createAgentFactory = (state, options = {}) => {
25508
25688
  sandboxKey = createSandboxKey(ctx);
25509
25689
  }
25510
25690
  const reader = workspaceRoot && (environment.context.projectInstructions === "from-workspace" || environment.context.skills === "from-config") ? await runtimeResourceReader(state, workspaceRoot, ctx) : void 0;
25691
+ const initPhases = [];
25692
+ const measurePhase = async (name2, fn) => {
25693
+ const started = performance.now();
25694
+ try {
25695
+ return await fn();
25696
+ } finally {
25697
+ initPhases.push({
25698
+ name: name2,
25699
+ duration_ms: Math.max(0, Math.round(performance.now() - started))
25700
+ });
25701
+ }
25702
+ };
25511
25703
  if (environment.context.projectInstructions === "from-workspace" && workspaceRoot) {
25512
- agentsResolver = state.agentsResolver ?? await AgentsResolver.create(
25513
- workspaceRoot,
25514
- void 0,
25515
- void 0,
25516
- reader
25517
- );
25704
+ agentsResolver = await measurePhase("agents_resolver", async () => {
25705
+ const agentsEnabled = environment.config.source === "disabled" ? true : await resolveAgentsEnabled(workspaceRoot).catch(() => true);
25706
+ return state.agentsResolver ?? await AgentsResolver.create(
25707
+ workspaceRoot,
25708
+ { enabled: agentsEnabled },
25709
+ void 0,
25710
+ reader
25711
+ );
25712
+ });
25518
25713
  state.agentsResolver = agentsResolver;
25519
25714
  }
25520
25715
  if (environment.context.skills === "from-config" && workspaceRoot) {
@@ -25528,11 +25723,14 @@ var createAgentFactory = (state, options = {}) => {
25528
25723
  const message = error instanceof Error ? error.message : String(error);
25529
25724
  throw new Error(message);
25530
25725
  }
25531
- skillsResolver = state.skillsResolver ?? await SkillsResolver.create({
25532
- workingDir: workspaceRoot,
25533
- config: skillsConfig,
25534
- reader
25535
- });
25726
+ skillsResolver = await measurePhase(
25727
+ "skills_resolver",
25728
+ async () => state.skillsResolver ?? await SkillsResolver.create({
25729
+ workingDir: workspaceRoot,
25730
+ config: skillsConfig,
25731
+ reader
25732
+ })
25733
+ );
25536
25734
  state.skillsResolver = skillsResolver;
25537
25735
  state.updateSkillsSnapshot(workspaceRoot, skillsResolver.getSnapshot());
25538
25736
  }
@@ -25591,24 +25789,32 @@ var createAgentFactory = (state, options = {}) => {
25591
25789
  }
25592
25790
  let mcpTools = [];
25593
25791
  if (environment.tools.mcp === "from-config" && options.mcpManager) {
25594
- try {
25595
- mcpTools = await options.mcpManager.getTools({
25596
- onStatus: (message) => {
25597
- (0, import_logger.log)(`mcp: ${message}`);
25598
- },
25599
- requestOAuthTokens: async ({ server_id, oauth: oauth2, error, signal }) => {
25600
- return requestMcpOAuthTokensWithRunStatus(
25601
- state,
25792
+ mcpTools = await measurePhase("mcp_tools", async () => {
25793
+ try {
25794
+ return await options.mcpManager.getTools({
25795
+ onStatus: (message) => {
25796
+ (0, import_logger.log)(`mcp: ${message}`);
25797
+ },
25798
+ requestOAuthTokens: async ({
25602
25799
  server_id,
25603
- oauth2,
25800
+ oauth: oauth2,
25604
25801
  error,
25605
25802
  signal
25606
- );
25607
- }
25608
- });
25609
- } catch (error) {
25610
- (0, import_logger.log)(`failed to load mcp tools: ${String(error)}`);
25611
- }
25803
+ }) => {
25804
+ return requestMcpOAuthTokensWithRunStatus(
25805
+ state,
25806
+ server_id,
25807
+ oauth2,
25808
+ error,
25809
+ signal
25810
+ );
25811
+ }
25812
+ });
25813
+ } catch (error) {
25814
+ (0, import_logger.log)(`failed to load mcp tools: ${String(error)}`);
25815
+ return [];
25816
+ }
25817
+ });
25612
25818
  }
25613
25819
  const hostTools = environment.tools.host === "enabled" ? await loadRuntimeHostTools(environment.adapters.toolProviders ?? []) : [];
25614
25820
  const subagentConfig = options.subagents?.isAvailable() && workspaceRoot ? await resolveEnvironmentSubagentConfig(state, workspaceRoot) : void 0;
@@ -25630,13 +25836,16 @@ ${JSON.stringify(subagentConfig)}
25630
25836
  state,
25631
25837
  workspaceRoot
25632
25838
  );
25633
- executionEnvironmentContext = await buildExecutionEnvironmentContext({
25634
- workingDir: workspaceRoot,
25635
- sandboxRoot: ctx.rootDir,
25636
- config: executionEnvironmentConfig,
25637
- hostInfo: describeExecutionEnvironmentHost(state.sandboxMode.value),
25638
- probeOptions: { authorize: authorizeRuntimeShell(state) }
25639
- });
25839
+ executionEnvironmentContext = await measurePhase(
25840
+ "exec_env",
25841
+ () => buildExecutionEnvironmentContext({
25842
+ workingDir: workspaceRoot,
25843
+ sandboxRoot: ctx.rootDir,
25844
+ config: executionEnvironmentConfig,
25845
+ hostInfo: describeExecutionEnvironmentHost(state.sandboxMode.value),
25846
+ probeOptions: { authorize: authorizeRuntimeShell(state) }
25847
+ })
25848
+ );
25640
25849
  }
25641
25850
  state.executionEnvironmentContext = executionEnvironmentContext;
25642
25851
  if (logInitialExecutionEnvironmentDebug(executionEnvironmentContext, {
@@ -25782,12 +25991,12 @@ ${JSON.stringify(subagentConfig)}
25782
25991
  state.currentModelProvider = provider;
25783
25992
  state.currentModelName = resolvedModelName;
25784
25993
  state.currentModelSource = modelConfig.source;
25785
- const modelRegistry = environment.persistence.mode === "runtime" || getResponsesProvider(modelConfig, provider) ? await buildModelRegistry(llm, {
25786
- strict: provider !== "openrouter",
25787
- providers: modelConfig.providers
25788
- }) : buildConfiguredModelRegistry(modelConfig.providers);
25789
- const totalBudgetTrimEnabled = envTruthy2(
25790
- process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
25994
+ const modelRegistry = await measurePhase(
25995
+ "model_registry",
25996
+ async () => environment.persistence.mode === "runtime" || getResponsesProvider(modelConfig, provider) ? await buildModelRegistry(llm, {
25997
+ strict: provider !== "openrouter",
25998
+ providers: modelConfig.providers
25999
+ }) : buildConfiguredModelRegistry(modelConfig.providers)
25791
26000
  );
25792
26001
  const builtinTools = /* @__PURE__ */ new Set([...baseLocalTools, ...imageTools]);
25793
26002
  if (localSearchTool && environment.sourcePreset === "tui-local" && !environment.adapters.approvalToolAuthority && !environment.adapters.approvalToolEffect)
@@ -25922,7 +26131,7 @@ Original conversation messages remain available after compaction. When a summary
25922
26131
  systemPrompt: effectiveSystemPrompt,
25923
26132
  modelRegistry: modelRegistry ?? import_core37.DEFAULT_MODEL_REGISTRY,
25924
26133
  toolOutputCache: {
25925
- totalBudgetTrim: totalBudgetTrimEnabled
26134
+ totalBudgetTrim: false
25926
26135
  },
25927
26136
  services: {
25928
26137
  toolOutputCacheStore,
@@ -25931,11 +26140,13 @@ Original conversation messages remain available after compaction. When a summary
25931
26140
  }
25932
26141
  });
25933
26142
  state.canReadAttachment = canReadAttachment;
26143
+ state.telemetry.setAgentInitPhases(initPhases);
25934
26144
  state.recordAgentChatRoute(
25935
26145
  agent,
25936
- getResponsesProvider(modelConfig, provider) ? { kind: "named" } : {
26146
+ getResponsesProvider(modelConfig, provider) ? { kind: "named", metered: false } : {
25937
26147
  kind: "builtin",
25938
26148
  provider,
26149
+ metered: providerAuth.method === "api_key",
25939
26150
  apiBase: providerAuth.method === "api_key" ? builtinApiKeyBase(provider) : void 0
25940
26151
  }
25941
26152
  );
@@ -27442,7 +27653,7 @@ var McpManager = class {
27442
27653
  };
27443
27654
 
27444
27655
  // src/rpc/handlers.ts
27445
- var import_protocol46 = require("@codelia/protocol");
27656
+ var import_protocol48 = require("@codelia/protocol");
27446
27657
  var import_storage35 = require("@codelia/storage");
27447
27658
 
27448
27659
  // src/constants.ts
@@ -28379,6 +28590,25 @@ var CONFIG_KEYS = [
28379
28590
  writeVia: "model.set"
28380
28591
  },
28381
28592
  { key: "tui.theme", type: "string", fallback: null, writeVia: "theme.set" },
28593
+ {
28594
+ key: "tui.color_scheme",
28595
+ type: "enum",
28596
+ enum: ["dark", "light"],
28597
+ fallback: "dark"
28598
+ },
28599
+ {
28600
+ key: "tui.image_protocol",
28601
+ type: "enum",
28602
+ enum: ["halfblocks", "kitty"],
28603
+ fallback: "halfblocks"
28604
+ },
28605
+ {
28606
+ key: "auth.oauth_browser",
28607
+ type: "enum",
28608
+ enum: ["auto", "manual"],
28609
+ fallback: null
28610
+ },
28611
+ { key: "agents.enabled", type: "boolean", fallback: true },
28382
28612
  {
28383
28613
  key: "subagent.max_concurrent",
28384
28614
  type: "integer",
@@ -28631,8 +28861,68 @@ var createConfigHandlers = ({
28631
28861
  return { handleConfigGet, handleConfigSet };
28632
28862
  };
28633
28863
 
28634
- // src/rpc/context.ts
28864
+ // src/rpc/telemetry.ts
28635
28865
  var import_protocol19 = require("@codelia/protocol");
28866
+ var emptyUsage = (state) => ({
28867
+ provider: state.currentModelProvider,
28868
+ model: state.currentModelName,
28869
+ limit_tokens: null,
28870
+ used_tokens: null,
28871
+ input_tokens: null,
28872
+ left_percent: null,
28873
+ basis: "none",
28874
+ breakdown: []
28875
+ });
28876
+ var createTelemetryHandlers = ({
28877
+ state,
28878
+ subagents,
28879
+ log: log2
28880
+ }) => {
28881
+ const handleTelemetryGet = async (id2) => {
28882
+ try {
28883
+ const context = state.agent ? state.agent.getContextUsage() : emptyUsage(state);
28884
+ const mem = process.memoryUsage();
28885
+ const subagentStats = subagents?.getPerfStats() ?? {
28886
+ active: 0,
28887
+ maxConcurrent: 0
28888
+ };
28889
+ const result = {
28890
+ ...state.sessionId ? { session_id: state.sessionId } : {},
28891
+ active_run_id: state.activeRunId,
28892
+ context,
28893
+ session_summary: state.telemetry.getSessionSummary(),
28894
+ run_summary: state.telemetry.getRunSummary(),
28895
+ recent_calls: state.telemetry.getRecentCalls(),
28896
+ recent_tools: state.telemetry.getRecentTools(),
28897
+ runtime: {
28898
+ startup_phases: state.telemetry.getStartupPhases(),
28899
+ agent_init_phases: state.telemetry.getAgentInitPhases(),
28900
+ active_subagents: subagentStats.active,
28901
+ max_concurrent_subagents: subagentStats.maxConcurrent,
28902
+ backpressure_events: getTransportBackpressureEvents(),
28903
+ memory: {
28904
+ rss_bytes: mem.rss,
28905
+ heap_used_bytes: mem.heapUsed,
28906
+ heap_total_bytes: mem.heapTotal,
28907
+ external_bytes: mem.external,
28908
+ array_buffers_bytes: mem.arrayBuffers
28909
+ }
28910
+ }
28911
+ };
28912
+ sendRequestResult("telemetry.get", id2, result);
28913
+ } catch (error) {
28914
+ log2(`telemetry.get failed: ${String(error)}`);
28915
+ sendError(id2, {
28916
+ code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
28917
+ message: "telemetry unavailable"
28918
+ });
28919
+ }
28920
+ };
28921
+ return { handleTelemetryGet };
28922
+ };
28923
+
28924
+ // src/rpc/context.ts
28925
+ var import_protocol21 = require("@codelia/protocol");
28636
28926
  var createContextHandlers = ({
28637
28927
  state,
28638
28928
  log: log2
@@ -28769,7 +29059,7 @@ var createContextHandlers = ({
28769
29059
  sendRequestResult("context.inspect", id2, result);
28770
29060
  } catch (error) {
28771
29061
  sendError(id2, {
28772
- code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
29062
+ code: import_protocol21.RPC_ERROR_CODE.RUNTIME_INTERNAL,
28773
29063
  message: `context.inspect failed: ${String(error)}`
28774
29064
  });
28775
29065
  }
@@ -28778,8 +29068,8 @@ var createContextHandlers = ({
28778
29068
  };
28779
29069
 
28780
29070
  // src/rpc/context-usage.ts
28781
- var import_protocol21 = require("@codelia/protocol");
28782
- var emptyUsage = (state) => ({
29071
+ var import_protocol23 = require("@codelia/protocol");
29072
+ var emptyUsage2 = (state) => ({
28783
29073
  provider: state.currentModelProvider,
28784
29074
  model: state.currentModelName,
28785
29075
  limit_tokens: null,
@@ -28795,7 +29085,7 @@ var createContextUsageHandlers = ({
28795
29085
  }) => {
28796
29086
  const handleContextUsage = async (id2) => {
28797
29087
  try {
28798
- const usage = state.agent ? state.agent.getContextUsage() : emptyUsage(state);
29088
+ const usage = state.agent ? state.agent.getContextUsage() : emptyUsage2(state);
28799
29089
  const result = {
28800
29090
  ...usage,
28801
29091
  ...state.sessionId ? { session_id: state.sessionId } : {}
@@ -28804,7 +29094,7 @@ var createContextUsageHandlers = ({
28804
29094
  } catch (error) {
28805
29095
  log2(`context.usage failed: ${String(error)}`);
28806
29096
  sendError(id2, {
28807
- code: import_protocol21.RPC_ERROR_CODE.RUNTIME_INTERNAL,
29097
+ code: import_protocol23.RPC_ERROR_CODE.RUNTIME_INTERNAL,
28808
29098
  message: "context usage unavailable"
28809
29099
  });
28810
29100
  }
@@ -28837,7 +29127,7 @@ var createRunContextUsageEmitter = (options) => {
28837
29127
  // src/rpc/history.ts
28838
29128
  var import_node_fs45 = require("fs");
28839
29129
  var import_node_path47 = __toESM(require("path"), 1);
28840
- var import_protocol23 = require("@codelia/protocol");
29130
+ var import_protocol25 = require("@codelia/protocol");
28841
29131
  var import_storage29 = require("@codelia/storage");
28842
29132
  var DEFAULT_HISTORY_RUNS = 20;
28843
29133
  var DEFAULT_HISTORY_EVENTS = 1500;
@@ -29055,7 +29345,7 @@ var createHistoryHandlers = ({
29055
29345
  sessions = await sessionStateStore.list();
29056
29346
  } catch (error) {
29057
29347
  sendError(id2, {
29058
- code: import_protocol23.RPC_ERROR_CODE.SESSION_LIST_FAILED,
29348
+ code: import_protocol25.RPC_ERROR_CODE.SESSION_LIST_FAILED,
29059
29349
  message: `session list failed: ${String(error)}`
29060
29350
  });
29061
29351
  return;
@@ -29088,7 +29378,7 @@ var createHistoryHandlers = ({
29088
29378
  const sessionId = params?.session_id?.trim();
29089
29379
  if (!sessionId) {
29090
29380
  sendError(id2, {
29091
- code: import_protocol23.RPC_ERROR_CODE.INVALID_PARAMS,
29381
+ code: import_protocol25.RPC_ERROR_CODE.INVALID_PARAMS,
29092
29382
  message: "session_id is required"
29093
29383
  });
29094
29384
  return;
@@ -29172,7 +29462,7 @@ var createHistoryHandlers = ({
29172
29462
 
29173
29463
  // src/rpc/image.ts
29174
29464
  var import_config20 = require("@codelia/config");
29175
- var import_protocol25 = require("@codelia/protocol");
29465
+ var import_protocol27 = require("@codelia/protocol");
29176
29466
  function createImageHandlers(state) {
29177
29467
  const catalog = new ImageCatalog();
29178
29468
  let configuring = false;
@@ -29481,7 +29771,7 @@ Saved to ${scope} settings.`
29481
29771
  });
29482
29772
  } catch (error) {
29483
29773
  sendError(id2, {
29484
- code: import_protocol25.RPC_ERROR_CODE.INVALID_PARAMS,
29774
+ code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
29485
29775
  message: error instanceof ImageGenerationError ? error.message : "Image operation failed; check settings, artifact and runtime storage. No credentials were changed."
29486
29776
  });
29487
29777
  } finally {
@@ -29494,7 +29784,7 @@ Saved to ${scope} settings.`
29494
29784
  // src/rpc/model.ts
29495
29785
  var import_core38 = require("@codelia/core");
29496
29786
  var import_model_metadata3 = require("@codelia/model-metadata");
29497
- var import_protocol27 = require("@codelia/protocol");
29787
+ var import_protocol29 = require("@codelia/protocol");
29498
29788
  var import_shared_types9 = require("@codelia/shared-types");
29499
29789
  var isSupportedProvider = (provider, providers) => SUPPORTED_PROVIDERS.includes(provider) || Boolean(providers && Object.hasOwn(providers, provider));
29500
29790
  var resolveProviderModelEntry2 = (providerEntries, provider, model) => {
@@ -29887,7 +30177,7 @@ var createModelHandlers = ({
29887
30177
  }
29888
30178
  } catch (error) {
29889
30179
  sendError(id2, {
29890
- code: import_protocol27.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30180
+ code: import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
29891
30181
  message: String(error)
29892
30182
  });
29893
30183
  return;
@@ -29895,7 +30185,7 @@ var createModelHandlers = ({
29895
30185
  const provider = requestedProvider ?? configuredProvider ?? "openai";
29896
30186
  if (!isSupportedProvider(provider, providers)) {
29897
30187
  sendError(id2, {
29898
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30188
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
29899
30189
  message: `unsupported provider: ${provider}`
29900
30190
  });
29901
30191
  return;
@@ -29914,7 +30204,7 @@ var createModelHandlers = ({
29914
30204
  details = result2.details;
29915
30205
  } catch (error) {
29916
30206
  sendError(id2, {
29917
- code: import_protocol27.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30207
+ code: import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
29918
30208
  message: String(error)
29919
30209
  });
29920
30210
  return;
@@ -29945,7 +30235,7 @@ var createModelHandlers = ({
29945
30235
  const handleModelSet = async (id2, raw) => {
29946
30236
  if (state.activeRunId) {
29947
30237
  sendError(id2, {
29948
- code: import_protocol27.RPC_ERROR_CODE.RUNTIME_BUSY,
30238
+ code: import_protocol29.RPC_ERROR_CODE.RUNTIME_BUSY,
29949
30239
  message: "runtime busy"
29950
30240
  });
29951
30241
  return;
@@ -29962,7 +30252,7 @@ var createModelHandlers = ({
29962
30252
  const scope = params?.scope ?? "config";
29963
30253
  if (scope !== "config" && scope !== "session") {
29964
30254
  sendError(id2, {
29965
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30255
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
29966
30256
  message: `unsupported model scope: ${scope}`
29967
30257
  });
29968
30258
  return;
@@ -29971,7 +30261,7 @@ var createModelHandlers = ({
29971
30261
  if (params?.reset) {
29972
30262
  if (scope !== "session") {
29973
30263
  sendError(id2, {
29974
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30264
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
29975
30265
  message: "model reset is only supported for session scope"
29976
30266
  });
29977
30267
  return;
@@ -29982,7 +30272,7 @@ var createModelHandlers = ({
29982
30272
  const name3 = config.name;
29983
30273
  if (!name3) {
29984
30274
  sendError(id2, {
29985
- code: import_protocol27.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30275
+ code: import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
29986
30276
  message: "configured model name is missing"
29987
30277
  });
29988
30278
  return;
@@ -29998,7 +30288,7 @@ var createModelHandlers = ({
29998
30288
  );
29999
30289
  } catch (error) {
30000
30290
  sendError(id2, {
30001
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30291
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30002
30292
  message: String(error)
30003
30293
  });
30004
30294
  return;
@@ -30020,7 +30310,7 @@ var createModelHandlers = ({
30020
30310
  log2(`model.set reset session override -> ${provider2}/${name3}`);
30021
30311
  } catch (error) {
30022
30312
  sendError(id2, {
30023
- code: import_protocol27.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30313
+ code: import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30024
30314
  message: String(error)
30025
30315
  });
30026
30316
  }
@@ -30030,7 +30320,7 @@ var createModelHandlers = ({
30030
30320
  let name2 = params?.name?.trim();
30031
30321
  if (!name2) {
30032
30322
  sendError(id2, {
30033
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30323
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30034
30324
  message: "model name is required"
30035
30325
  });
30036
30326
  return;
@@ -30041,7 +30331,7 @@ var createModelHandlers = ({
30041
30331
  reasoning = resolveReasoningEffort(params.reasoning);
30042
30332
  } catch (error) {
30043
30333
  sendError(id2, {
30044
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30334
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30045
30335
  message: String(error)
30046
30336
  });
30047
30337
  return;
@@ -30051,7 +30341,7 @@ var createModelHandlers = ({
30051
30341
  const endpoint = getResponsesProvider(configured, provider);
30052
30342
  if (!isSupportedProvider(provider, configured.providers)) {
30053
30343
  sendError(id2, {
30054
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30344
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30055
30345
  message: `unsupported provider: ${provider}`
30056
30346
  });
30057
30347
  return;
@@ -30064,7 +30354,7 @@ var createModelHandlers = ({
30064
30354
  );
30065
30355
  if (!spec) {
30066
30356
  sendError(id2, {
30067
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30357
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30068
30358
  message: `unknown model: ${name2}`
30069
30359
  });
30070
30360
  return;
@@ -30097,7 +30387,7 @@ var createModelHandlers = ({
30097
30387
  await validateFastSelection(provider, name2, candidate.fast);
30098
30388
  } catch (error) {
30099
30389
  sendError(id2, {
30100
- code: import_protocol27.RPC_ERROR_CODE.INVALID_PARAMS,
30390
+ code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30101
30391
  message: String(error)
30102
30392
  });
30103
30393
  return;
@@ -30152,7 +30442,7 @@ var createModelHandlers = ({
30152
30442
  );
30153
30443
  } catch (error) {
30154
30444
  sendError(id2, {
30155
- code: import_protocol27.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30445
+ code: import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30156
30446
  message: String(error)
30157
30447
  });
30158
30448
  }
@@ -30163,7 +30453,7 @@ var createModelHandlers = ({
30163
30453
  // src/rpc/permissions.ts
30164
30454
  var import_node_fs46 = require("fs");
30165
30455
  var import_config_loader3 = require("@codelia/config-loader");
30166
- var import_protocol29 = require("@codelia/protocol");
30456
+ var import_protocol31 = require("@codelia/protocol");
30167
30457
  var import_storage30 = require("@codelia/storage");
30168
30458
  var MAX_RULE_FIELD_LENGTH = 4096;
30169
30459
  var RULE_FIELDS = ["tool", "command", "command_glob", "skill_name"];
@@ -30200,7 +30490,7 @@ var createPermissionsHandlers = ({
30200
30490
  const rejectUnsupported = (id2) => {
30201
30491
  if (supportsConfigReadWrite(state)) return false;
30202
30492
  sendError(id2, {
30203
- code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30493
+ code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS,
30204
30494
  message: "permission rules are not available for this runtime"
30205
30495
  });
30206
30496
  return true;
@@ -30212,7 +30502,7 @@ var createPermissionsHandlers = ({
30212
30502
  const params = parsed.params;
30213
30503
  if (params?.include_system !== void 0 && typeof params.include_system !== "boolean") {
30214
30504
  sendError(id2, {
30215
- code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30505
+ code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS,
30216
30506
  message: "include_system must be a boolean"
30217
30507
  });
30218
30508
  return;
@@ -30314,7 +30604,7 @@ var createPermissionsHandlers = ({
30314
30604
  const root = resolveConfigWorkspaceDir(state);
30315
30605
  if (!root || !localProjectAllows(state) || params.scope !== "project" || !configurableToolInvocations.has(params.remembered_tool)) {
30316
30606
  sendError(id2, {
30317
- code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30607
+ code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS,
30318
30608
  message: "Invalid remembered tool"
30319
30609
  });
30320
30610
  return;
@@ -30335,7 +30625,7 @@ var createPermissionsHandlers = ({
30335
30625
  });
30336
30626
  if (removed === "busy") {
30337
30627
  sendError(id2, {
30338
- code: import_protocol29.RPC_ERROR_CODE.RUNTIME_BUSY,
30628
+ code: import_protocol31.RPC_ERROR_CODE.RUNTIME_BUSY,
30339
30629
  message: "runtime busy"
30340
30630
  });
30341
30631
  return;
@@ -30347,7 +30637,7 @@ var createPermissionsHandlers = ({
30347
30637
  });
30348
30638
  } catch {
30349
30639
  sendError(id2, {
30350
- code: import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30640
+ code: import_protocol31.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30351
30641
  message: "Remembered tool removal failed"
30352
30642
  });
30353
30643
  }
@@ -30356,7 +30646,7 @@ var createPermissionsHandlers = ({
30356
30646
  const workspaceDir = resolveConfigWorkspaceDir(state);
30357
30647
  if (!workspaceDir || params.resource !== "workspace_write" || params.scope !== "session") {
30358
30648
  sendError(id2, {
30359
- code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30649
+ code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS,
30360
30650
  message: "Invalid workspace grant reference"
30361
30651
  });
30362
30652
  return;
@@ -30372,7 +30662,7 @@ var createPermissionsHandlers = ({
30372
30662
  const workspaceDir = resolveConfigWorkspaceDir(state);
30373
30663
  if (!workspaceDir || !/^[a-f0-9]{64}$/u.test(params.launch_rule_id) || params.scope !== "session" && params.scope !== "project" || state.effectiveEnvironment.sourcePreset !== "tui-local") {
30374
30664
  sendError(id2, {
30375
- code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30665
+ code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS,
30376
30666
  message: "Invalid launch rule reference"
30377
30667
  });
30378
30668
  return;
@@ -30392,7 +30682,7 @@ var createPermissionsHandlers = ({
30392
30682
  sendRequestResult("permissions.remove", id2, result);
30393
30683
  } catch {
30394
30684
  sendError(id2, {
30395
- code: import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30685
+ code: import_protocol31.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30396
30686
  message: "Launch rule removal failed"
30397
30687
  });
30398
30688
  }
@@ -30409,12 +30699,12 @@ var createPermissionsHandlers = ({
30409
30699
  return removeLaunchRule(id2, params);
30410
30700
  if (state.activeRunId) {
30411
30701
  sendError(id2, {
30412
- code: import_protocol29.RPC_ERROR_CODE.RUNTIME_BUSY,
30702
+ code: import_protocol31.RPC_ERROR_CODE.RUNTIME_BUSY,
30413
30703
  message: "runtime busy"
30414
30704
  });
30415
30705
  return;
30416
30706
  }
30417
- const invalid = (message) => sendError(id2, { code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS, message });
30707
+ const invalid = (message) => sendError(id2, { code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS, message });
30418
30708
  const scope = params?.scope;
30419
30709
  const kind = params?.kind;
30420
30710
  if (scope !== "global" && scope !== "project") {
@@ -30450,14 +30740,14 @@ var createPermissionsHandlers = ({
30450
30740
  });
30451
30741
  } catch {
30452
30742
  sendError(id2, {
30453
- code: import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30743
+ code: import_protocol31.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30454
30744
  message: `${scope} config write failed`
30455
30745
  });
30456
30746
  return;
30457
30747
  }
30458
30748
  if (removed === "busy") {
30459
30749
  sendError(id2, {
30460
- code: import_protocol29.RPC_ERROR_CODE.RUNTIME_BUSY,
30750
+ code: import_protocol31.RPC_ERROR_CODE.RUNTIME_BUSY,
30461
30751
  message: "runtime busy"
30462
30752
  });
30463
30753
  return;
@@ -30469,7 +30759,7 @@ var createPermissionsHandlers = ({
30469
30759
  const handleProjectAllowTrustSet = async (id2, raw) => {
30470
30760
  if (!supportsProjectAllowTrust(state)) {
30471
30761
  sendError(id2, {
30472
- code: import_protocol29.RPC_ERROR_CODE.METHOD_NOT_FOUND,
30762
+ code: import_protocol31.RPC_ERROR_CODE.METHOD_NOT_FOUND,
30473
30763
  message: "Project allow trust changes are unavailable for this runtime."
30474
30764
  });
30475
30765
  return;
@@ -30479,7 +30769,7 @@ var createPermissionsHandlers = ({
30479
30769
  const params = parsed.params;
30480
30770
  if (typeof params?.workspace !== "string" || typeof params.trusted !== "boolean" || typeof params.expected_revision !== "string" || !params.expected_revision) {
30481
30771
  sendError(id2, {
30482
- code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30772
+ code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS,
30483
30773
  message: "Expected a reviewed project allow list for this local workspace"
30484
30774
  });
30485
30775
  return;
@@ -30488,7 +30778,7 @@ var createPermissionsHandlers = ({
30488
30778
  await state.withAdmissionLock(async () => {
30489
30779
  if (state.activeRunId) {
30490
30780
  sendError(id2, {
30491
- code: import_protocol29.RPC_ERROR_CODE.RUNTIME_BUSY,
30781
+ code: import_protocol31.RPC_ERROR_CODE.RUNTIME_BUSY,
30492
30782
  message: "runtime busy"
30493
30783
  });
30494
30784
  return;
@@ -30496,7 +30786,7 @@ var createPermissionsHandlers = ({
30496
30786
  const root = resolveConfigWorkspaceDir(state);
30497
30787
  if (!root || (0, import_node_fs46.realpathSync)(root) !== params.workspace) {
30498
30788
  sendError(id2, {
30499
- code: import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS,
30789
+ code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS,
30500
30790
  message: "Workspace changed. Review the current project allow list again."
30501
30791
  });
30502
30792
  return;
@@ -30516,7 +30806,7 @@ var createPermissionsHandlers = ({
30516
30806
  } catch (error) {
30517
30807
  const changed = error instanceof Error && error.message === "project_allow_trust_changed";
30518
30808
  sendError(id2, {
30519
- code: changed ? import_protocol29.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol29.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30809
+ code: changed ? import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol31.RPC_ERROR_CODE.RUNTIME_INTERNAL,
30520
30810
  message: changed ? "The project allow list or its trust state changed. Review it again." : "Project allow trust is unavailable."
30521
30811
  });
30522
30812
  }
@@ -30901,7 +31191,7 @@ var buildResumeDiff = async (meta, state, options = {}) => {
30901
31191
  };
30902
31192
 
30903
31193
  // src/rpc/run.ts
30904
- var import_protocol33 = require("@codelia/protocol");
31194
+ var import_protocol35 = require("@codelia/protocol");
30905
31195
 
30906
31196
  // src/provider-errors.ts
30907
31197
  var import_core39 = require("@codelia/core");
@@ -30971,7 +31261,7 @@ var normalizeRunFailure = (error) => {
30971
31261
 
30972
31262
  // src/rpc/goals.ts
30973
31263
  var import_core40 = require("@codelia/core");
30974
- var import_protocol31 = require("@codelia/protocol");
31264
+ var import_protocol33 = require("@codelia/protocol");
30975
31265
  var import_storage31 = require("@codelia/storage");
30976
31266
  var import_zod47 = require("zod");
30977
31267
  var id = import_zod47.z.string().min(1).max(200);
@@ -31124,7 +31414,7 @@ var GoalController = class {
31124
31414
  handle(requestId, method, raw, serialize, interrupt, onError) {
31125
31415
  if (!this.enabled) {
31126
31416
  sendError(requestId, {
31127
- code: import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS,
31417
+ code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
31128
31418
  message: "Goals are unavailable on this connection."
31129
31419
  });
31130
31420
  return Promise.resolve();
@@ -31317,7 +31607,7 @@ var GoalController = class {
31317
31607
  reject(requestId, error) {
31318
31608
  const conflict = error instanceof GoalConflict ? error : null;
31319
31609
  sendError(requestId, {
31320
- code: conflict?.reason === "busy" ? import_protocol31.RPC_ERROR_CODE.RUNTIME_BUSY : conflict || error instanceof import_zod47.z.ZodError ? import_protocol31.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol31.RPC_ERROR_CODE.RUNTIME_INTERNAL,
31610
+ code: conflict?.reason === "busy" ? import_protocol33.RPC_ERROR_CODE.RUNTIME_BUSY : conflict || error instanceof import_zod47.z.ZodError ? import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol33.RPC_ERROR_CODE.RUNTIME_INTERNAL,
31321
31611
  message: conflict?.message ?? (error instanceof import_zod47.z.ZodError ? "Invalid goal parameters." : "Goal operation failed.")
31322
31612
  });
31323
31613
  }
@@ -32008,6 +32298,13 @@ var runInputLengthForDebug = (input) => {
32008
32298
  };
32009
32299
 
32010
32300
  // src/rpc/run-metrics.ts
32301
+ var import_core42 = require("@codelia/core");
32302
+ var nonEmpty = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
32303
+ var extractActualModel = (providerMeta) => {
32304
+ const meta = providerMeta;
32305
+ const rawServerModel = meta?.codex_metadata?.server_model ?? meta?.server_model;
32306
+ return typeof rawServerModel === "string" && rawServerModel.trim().length > 0 ? rawServerModel.trim() : null;
32307
+ };
32011
32308
  var buildRunMetrics = (record) => {
32012
32309
  const timing = record.output.timing;
32013
32310
  const tokens = record.output.usage?.output_tokens;
@@ -32024,6 +32321,45 @@ var buildRunMetrics = (record) => {
32024
32321
  ...validTiming ? { timing } : {}
32025
32322
  };
32026
32323
  };
32324
+ var buildCallRunMetrics = (input) => {
32325
+ const { record, request } = input;
32326
+ const usage = record.output.usage ?? null;
32327
+ const hasCacheMetric = typeof usage?.input_cached_tokens === "number";
32328
+ const cacheReadTokens = hasCacheMetric ? usage?.input_cached_tokens ?? 0 : 0;
32329
+ const cacheCreationTokens = usage?.input_cache_creation_tokens ?? 0;
32330
+ const inputTokens = usage?.input_tokens ?? 0;
32331
+ const hitState = hasCacheMetric ? cacheReadTokens > 0 ? "hit" : "miss" : "unknown";
32332
+ const requestModel = nonEmpty(request?.model);
32333
+ const usageModel = nonEmpty(usage?.model);
32334
+ const model = usageModel ?? requestModel ?? "unknown";
32335
+ const baseMetrics = buildRunMetrics(record);
32336
+ const modelCost = input.getModelCost ? (requestModel ? input.getModelCost(requestModel) : void 0) ?? input.getModelCost(model) : void 0;
32337
+ const costUsd = input.metered ? (0, import_core42.estimateUsageCostUsd)(usage, modelCost) : null;
32338
+ const actualModel = extractActualModel(record.output.provider_meta);
32339
+ return {
32340
+ ...baseMetrics,
32341
+ ...request?.provider ? { provider: request.provider } : {},
32342
+ model,
32343
+ ...actualModel ? { actual_model: actualModel } : {},
32344
+ request_ts: request?.ts ?? record.ts,
32345
+ response_ts: record.ts,
32346
+ latency_ms: Math.max(0, Math.round(input.latencyMs)),
32347
+ stop_reason: record.output.stop_reason ?? null,
32348
+ usage,
32349
+ cache: {
32350
+ hit_state: hitState,
32351
+ cache_read_tokens: cacheReadTokens,
32352
+ cache_creation_tokens: cacheCreationTokens,
32353
+ cache_read_ratio: hasCacheMetric && inputTokens > 0 ? Math.min(1, Math.max(0, cacheReadTokens / inputTokens)) : null
32354
+ },
32355
+ cost_usd: costUsd,
32356
+ cost_basis: costUsd !== null ? "api_list" : "unavailable",
32357
+ retry_count: Math.max(0, input.retryCount),
32358
+ retry_wait_ms: Math.max(0, input.retryWaitMs),
32359
+ provider_meta_summary: summarizeProviderMeta(record.output.provider_meta),
32360
+ ...input.context ? { context: input.context } : {}
32361
+ };
32362
+ };
32027
32363
 
32028
32364
  // src/rpc/text-delta-coalescer.ts
32029
32365
  var DEFAULT_TEXT_DELTA_FLUSH_MS = 40;
@@ -32158,10 +32494,6 @@ var mergeWorkspaceRootIntoSessionMeta = (meta, workspaceRoot) => {
32158
32494
  return Object.keys(nextMeta).length > 0 ? nextMeta : void 0;
32159
32495
  };
32160
32496
  var resolveSessionWorkspaceRoot = (state) => state.lastUiContext?.workspace_root ?? state.agentsResolver?.getRootDir() ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? void 0;
32161
- var toTimestampMs = (value) => {
32162
- const ms = Date.parse(value);
32163
- return Number.isFinite(ms) ? ms : null;
32164
- };
32165
32497
  var OPENAI_AUTO_WS_FALLBACK_WARNING = "Warning: OpenAI websocket auto mode fell back to HTTP. Continuing this run over HTTP.";
32166
32498
  var shouldEmitOpenAiWsFallbackWarning = (providerMeta) => {
32167
32499
  if (!providerMeta || typeof providerMeta !== "object" || Array.isArray(providerMeta)) {
@@ -32279,7 +32611,7 @@ var createRunHandlers = ({
32279
32611
  initialInput = normalizeRunInput(params.input);
32280
32612
  } catch (error) {
32281
32613
  sendError(id2, {
32282
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
32614
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
32283
32615
  message: String(error)
32284
32616
  });
32285
32617
  return;
@@ -32287,7 +32619,7 @@ var createRunHandlers = ({
32287
32619
  const attachmentIds = runAttachmentIds(initialInput);
32288
32620
  if (params.force_compaction && attachmentIds.length > 0) {
32289
32621
  sendError(id2, {
32290
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
32622
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
32291
32623
  message: "A compaction run cannot admit new attachments"
32292
32624
  });
32293
32625
  return;
@@ -32297,7 +32629,7 @@ var createRunHandlers = ({
32297
32629
  await beforeRunStart();
32298
32630
  } catch (error) {
32299
32631
  sendError(id2, {
32300
- code: import_protocol33.RPC_ERROR_CODE.RUNTIME_INTERNAL,
32632
+ code: import_protocol35.RPC_ERROR_CODE.RUNTIME_INTERNAL,
32301
32633
  message: `startup onboarding failed: ${String(error)}`
32302
32634
  });
32303
32635
  return;
@@ -32305,7 +32637,7 @@ var createRunHandlers = ({
32305
32637
  }
32306
32638
  if (state.activeRunId) {
32307
32639
  sendError(id2, {
32308
- code: import_protocol33.RPC_ERROR_CODE.RUNTIME_BUSY,
32640
+ code: import_protocol35.RPC_ERROR_CODE.RUNTIME_BUSY,
32309
32641
  message: "runtime busy"
32310
32642
  });
32311
32643
  return;
@@ -32322,14 +32654,14 @@ var createRunHandlers = ({
32322
32654
  resumeState = await sessionStateStore.load(requestedSessionId);
32323
32655
  } catch (error) {
32324
32656
  sendError(id2, {
32325
- code: import_protocol33.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
32657
+ code: import_protocol35.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
32326
32658
  message: `session load failed: ${String(error)}`
32327
32659
  });
32328
32660
  return;
32329
32661
  }
32330
32662
  if (!resumeState) {
32331
32663
  sendError(id2, {
32332
- code: import_protocol33.RPC_ERROR_CODE.SESSION_NOT_FOUND,
32664
+ code: import_protocol35.RPC_ERROR_CODE.SESSION_NOT_FOUND,
32333
32665
  message: "session not found"
32334
32666
  });
32335
32667
  return;
@@ -32340,7 +32672,7 @@ var createRunHandlers = ({
32340
32672
  resumeState = await sessionStateStore.load(state.sessionId);
32341
32673
  } catch (error) {
32342
32674
  sendError(id2, {
32343
- code: import_protocol33.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
32675
+ code: import_protocol35.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
32344
32676
  message: `session reload failed: ${String(error)}`
32345
32677
  });
32346
32678
  return;
@@ -32357,7 +32689,7 @@ var createRunHandlers = ({
32357
32689
  if (resumeState?.meta?.codelia_subagent) {
32358
32690
  restorePreviousModel();
32359
32691
  sendError(id2, {
32360
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
32692
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
32361
32693
  message: "Delegated sessions cannot be resumed as a root run"
32362
32694
  });
32363
32695
  return;
@@ -32382,7 +32714,7 @@ var createRunHandlers = ({
32382
32714
  } catch (error) {
32383
32715
  restorePreviousModel();
32384
32716
  sendError(id2, {
32385
- code: error instanceof AttachmentAdmissionError ? import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol33.RPC_ERROR_CODE.RUNTIME_INTERNAL,
32717
+ code: error instanceof AttachmentAdmissionError ? import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol35.RPC_ERROR_CODE.RUNTIME_INTERNAL,
32386
32718
  message: error instanceof Error ? error.message : String(error)
32387
32719
  });
32388
32720
  return;
@@ -32399,7 +32731,7 @@ var createRunHandlers = ({
32399
32731
  } catch (error) {
32400
32732
  restorePreviousModel();
32401
32733
  sendError(id2, {
32402
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
32734
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
32403
32735
  message: String(error)
32404
32736
  });
32405
32737
  return;
@@ -32418,7 +32750,7 @@ var createRunHandlers = ({
32418
32750
  } catch {
32419
32751
  restorePreviousModel();
32420
32752
  sendError(id2, {
32421
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
32753
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
32422
32754
  message: "Could not claim the attachments for this conversation. Upload them again."
32423
32755
  });
32424
32756
  return;
@@ -32538,22 +32870,30 @@ var createRunHandlers = ({
32538
32870
  }
32539
32871
  );
32540
32872
  const pendingLlmRequests = /* @__PURE__ */ new Map();
32873
+ const toolNamesByCallId = /* @__PURE__ */ new Map();
32874
+ let pendingRetryCount = 0;
32875
+ let pendingRetryWaitMs = 0;
32876
+ let activeRetry = null;
32877
+ const settleActiveRetryWait = (interrupted) => {
32878
+ if (!activeRetry) return;
32879
+ const { startedAtMs, plannedMs } = activeRetry;
32880
+ activeRetry = null;
32881
+ const waitMs = interrupted ? Math.min(
32882
+ plannedMs,
32883
+ Math.max(0, Math.round(performance.now() - startedAtMs))
32884
+ ) : plannedMs;
32885
+ pendingRetryWaitMs += waitMs;
32886
+ state.telemetry.recordRetryWait(runId, waitMs);
32887
+ };
32888
+ const runStartedAtMs = performance.now();
32889
+ state.telemetry.beginRun(runId);
32541
32890
  let openAiWsFallbackWarningShown = false;
32542
32891
  const streamDeltas = state.uiCapabilities?.supports_text_delta === true;
32543
- const diagnosticsActive = state.diagnosticsEnabled || state.uiCapabilities?.supports_run_diagnostics === true;
32544
32892
  const deltaCoalescer = streamDeltas ? createTextDeltaCoalescer({
32545
32893
  send: (event) => {
32546
32894
  if (!state.cancelRequested) sendAgentEvent(state, runId, event);
32547
32895
  }
32548
32896
  }) : null;
32549
- const emitRunDiagnostics = (params2) => {
32550
- if (!diagnosticsActive) return;
32551
- try {
32552
- sendRunDiagnostics(state, params2);
32553
- } catch (error) {
32554
- log2(`run diagnostics emit failed: ${String(error)}`);
32555
- }
32556
- };
32557
32897
  const emitOpenAiWsFallbackWarning = () => {
32558
32898
  if (openAiWsFallbackWarningShown) {
32559
32899
  return;
@@ -32582,68 +32922,44 @@ var createRunHandlers = ({
32582
32922
  }
32583
32923
  };
32584
32924
  const sessionAppend = (record) => {
32585
- if (record.type === "llm.response") {
32586
- try {
32587
- sendRunMetrics(state, buildRunMetrics(record));
32588
- } catch (error) {
32589
- log2(`run metrics emit failed: ${String(error)}`);
32925
+ try {
32926
+ if (record.type === "llm.request") {
32927
+ const modelName = record.model?.name ?? record.input.model ?? "unknown";
32928
+ pendingLlmRequests.set(record.seq, {
32929
+ ts: record.ts,
32930
+ startedAtMs: performance.now(),
32931
+ provider: record.model?.provider,
32932
+ model: modelName
32933
+ });
32590
32934
  }
32591
- }
32592
- if (diagnosticsActive) {
32593
- try {
32594
- if (record.type === "llm.request") {
32595
- const modelName = record.model?.name ?? record.input.model ?? "unknown";
32596
- pendingLlmRequests.set(record.seq, {
32597
- ts: record.ts,
32598
- provider: record.model?.provider,
32599
- model: modelName
32600
- });
32601
- }
32602
- if (record.type === "llm.response") {
32603
- const request = pendingLlmRequests.get(record.seq);
32604
- pendingLlmRequests.delete(record.seq);
32605
- const usage = record.output.usage ?? null;
32606
- const cacheReadTokens = usage?.input_cached_tokens ?? 0;
32607
- const cacheCreationTokens = usage?.input_cache_creation_tokens ?? 0;
32608
- const inputTokens = usage?.input_tokens ?? 0;
32609
- const hitState = usage ? cacheReadTokens > 0 ? "hit" : "miss" : "unknown";
32610
- const responseTsMs = toTimestampMs(record.ts);
32611
- const requestTsMs = request ? toTimestampMs(request.ts) : null;
32612
- const latencyMs = responseTsMs !== null && requestTsMs !== null ? Math.max(0, responseTsMs - requestTsMs) : 0;
32613
- const model = usage?.model ?? request?.model ?? "unknown";
32614
- const metrics = buildRunMetrics(record);
32615
- const diagnostics = {
32616
- run_id: runId,
32617
- seq: record.seq,
32618
- ...request?.provider ? { provider: request.provider } : {},
32619
- model,
32620
- request_ts: request?.ts ?? record.ts,
32621
- response_ts: record.ts,
32622
- latency_ms: latencyMs,
32623
- ...metrics.timing ? { timing: metrics.timing } : {},
32624
- output_tokens_per_second: metrics.output_tokens_per_second,
32625
- stop_reason: record.output.stop_reason ?? null,
32626
- usage,
32627
- cache: {
32628
- hit_state: hitState,
32629
- cache_read_tokens: cacheReadTokens,
32630
- cache_creation_tokens: cacheCreationTokens,
32631
- cache_read_ratio: usage ? cacheReadTokens / Math.max(inputTokens, 1) : null
32632
- },
32633
- cost_usd: null,
32634
- provider_meta_summary: summarizeProviderMeta(
32635
- record.output.provider_meta
32636
- )
32637
- };
32638
- emitRunDiagnostics({
32639
- run_id: runId,
32640
- kind: "llm_call",
32641
- call: diagnostics
32642
- });
32643
- }
32644
- } catch (error) {
32645
- log2(`run diagnostics build failed: ${String(error)}`);
32935
+ if (record.type === "llm.response") {
32936
+ settleActiveRetryWait(false);
32937
+ const request = pendingLlmRequests.get(record.seq);
32938
+ pendingLlmRequests.delete(record.seq);
32939
+ const latencyMs = request ? Math.max(0, Math.round(performance.now() - request.startedAtMs)) : 0;
32940
+ const route = state.reviewChatRoute;
32941
+ const retryCount = pendingRetryCount;
32942
+ const retryWaitMs = pendingRetryWaitMs;
32943
+ pendingRetryCount = 0;
32944
+ pendingRetryWaitMs = 0;
32945
+ const metrics = buildCallRunMetrics({
32946
+ record,
32947
+ request,
32948
+ latencyMs,
32949
+ metered: route?.kind === "builtin" && route.metered === true,
32950
+ getModelCost: (modelName) => runtimeAgent.getModelCost(modelName),
32951
+ retryCount,
32952
+ retryWaitMs,
32953
+ context: runtimeAgent.getContextSnapshot()
32954
+ });
32955
+ state.telemetry.recordLlmCall(metrics);
32956
+ sendRunMetrics(state, {
32957
+ ...metrics,
32958
+ session: state.telemetry.getSessionSummary()
32959
+ });
32646
32960
  }
32961
+ } catch (error) {
32962
+ log2(`run metrics build/emit failed: ${String(error)}`);
32647
32963
  }
32648
32964
  if (record.type === "llm.response" && shouldEmitOpenAiWsFallbackWarning(record.output.provider_meta)) {
32649
32965
  emitOpenAiWsFallbackWarning();
@@ -32756,12 +33072,23 @@ var createRunHandlers = ({
32756
33072
  let sessionSaveChain = Promise.resolve(true);
32757
33073
  let lastSessionSaveAt = 0;
32758
33074
  const polledUnconfirmedSteers = [];
32759
- const emitRunSummaryDiagnostics = () => {
32760
- emitRunDiagnostics({
32761
- run_id: runId,
32762
- kind: "run_summary",
32763
- summary: runtimeAgent.getUsageSummary()
32764
- });
33075
+ const emitRunSummary = () => {
33076
+ try {
33077
+ settleActiveRetryWait(true);
33078
+ const runSummary = state.telemetry.getRunSummary();
33079
+ if (!runSummary) return;
33080
+ sendRunSummary(state, {
33081
+ run_id: runId,
33082
+ duration_ms: Math.max(
33083
+ 0,
33084
+ Math.round(performance.now() - runStartedAtMs)
33085
+ ),
33086
+ run: runSummary,
33087
+ session: state.telemetry.getSessionSummary()
33088
+ });
33089
+ } catch (error) {
33090
+ log2(`run summary emit failed: ${String(error)}`);
33091
+ }
32765
33092
  };
32766
33093
  const buildTerminalStatusExtras = () => {
32767
33094
  state.closeRunSteers(runId);
@@ -32912,11 +33239,41 @@ var createRunHandlers = ({
32912
33239
  continue;
32913
33240
  }
32914
33241
  deltaCoalescer?.flush();
33242
+ if (event.type === "llm.retry") {
33243
+ settleActiveRetryWait(false);
33244
+ const delayMs = Math.max(0, event.delay_ms);
33245
+ pendingRetryCount += 1;
33246
+ state.telemetry.recordRetry(runId, 0);
33247
+ activeRetry = {
33248
+ startedAtMs: performance.now(),
33249
+ plannedMs: delayMs
33250
+ };
33251
+ }
33252
+ if (event.type === "tool_call") {
33253
+ toolNamesByCallId.set(event.tool_call_id, event.tool);
33254
+ }
33255
+ if (event.type === "step_complete") {
33256
+ const toolName = toolNamesByCallId.get(event.step_id) ?? "unknown";
33257
+ toolNamesByCallId.delete(event.step_id);
33258
+ state.telemetry.recordToolComplete({
33259
+ run_id: runId,
33260
+ tool_call_id: event.step_id,
33261
+ tool: toolName,
33262
+ status: event.status,
33263
+ duration_ms: event.duration_ms,
33264
+ ...event.exec_duration_ms !== void 0 ? { exec_duration_ms: event.exec_duration_ms } : {},
33265
+ ...event.approval_wait_ms !== void 0 ? { approval_wait_ms: event.approval_wait_ms } : {},
33266
+ finished_at: nowIso5()
33267
+ });
33268
+ }
32915
33269
  if (event.type === "final") {
32916
33270
  finalResponse = event.content;
32917
33271
  await queueSessionSave("final");
32918
33272
  }
32919
33273
  if (event.type === "compaction_complete") {
33274
+ if (event.compacted) {
33275
+ state.telemetry.recordCompaction(runId, event.duration_ms ?? 0);
33276
+ }
32920
33277
  logCompactionSnapshot(log2, runId, runtimeAgent, event.compacted);
32921
33278
  if (event.compacted) await queueSessionSave("compaction");
32922
33279
  }
@@ -32990,7 +33347,7 @@ var createRunHandlers = ({
32990
33347
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
32991
33348
  }
32992
33349
  await queueSessionSave("terminal");
32993
- emitRunSummaryDiagnostics();
33350
+ emitRunSummary();
32994
33351
  const status2 = state.cancelRequested ? "cancelled" : "completed";
32995
33352
  outcome = status2;
32996
33353
  const terminalExtras = buildTerminalStatusExtras();
@@ -33008,7 +33365,7 @@ var createRunHandlers = ({
33008
33365
  outcome = "cancelled";
33009
33366
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
33010
33367
  await queueSessionSave("cancelled");
33011
- emitRunSummaryDiagnostics();
33368
+ emitRunSummary();
33012
33369
  const terminalExtras2 = buildTerminalStatusExtras();
33013
33370
  emitRunStatus(
33014
33371
  runId,
@@ -33023,7 +33380,7 @@ var createRunHandlers = ({
33023
33380
  const safeFailure = normalizeRunFailure(err);
33024
33381
  logRunDebug(log2, runId, `stream.error ${safeFailure.debugMessage}`);
33025
33382
  await queueSessionSave("error");
33026
- emitRunSummaryDiagnostics();
33383
+ emitRunSummary();
33027
33384
  const terminalExtras = buildTerminalStatusExtras();
33028
33385
  emitRunStatus(
33029
33386
  runId,
@@ -33092,7 +33449,7 @@ var createRunHandlers = ({
33092
33449
  const runId = typeof params?.run_id === "string" ? params.run_id.trim() : "";
33093
33450
  if (!runId) {
33094
33451
  sendError(id2, {
33095
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
33452
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
33096
33453
  message: "run_id is required"
33097
33454
  });
33098
33455
  return Promise.resolve();
@@ -33112,7 +33469,7 @@ var createRunHandlers = ({
33112
33469
  const input = parseSteerInput(params.input);
33113
33470
  if ("error" in input) {
33114
33471
  sendError(id2, {
33115
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
33472
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
33116
33473
  message: input.error
33117
33474
  });
33118
33475
  return;
@@ -33120,7 +33477,7 @@ var createRunHandlers = ({
33120
33477
  const initialInput = input.value;
33121
33478
  if (!state.canSteerRun(runId)) {
33122
33479
  sendError(id2, {
33123
- code: import_protocol33.RPC_ERROR_CODE.RUN_NOT_FOUND,
33480
+ code: import_protocol35.RPC_ERROR_CODE.RUN_NOT_FOUND,
33124
33481
  message: "active run not found"
33125
33482
  });
33126
33483
  return;
@@ -33146,7 +33503,7 @@ var createRunHandlers = ({
33146
33503
  normalizedInput = await state.prepareRunImages(normalizedInput);
33147
33504
  } catch (error) {
33148
33505
  sendError(id2, {
33149
- code: error instanceof AttachmentAdmissionError ? import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol33.RPC_ERROR_CODE.RUNTIME_INTERNAL,
33506
+ code: error instanceof AttachmentAdmissionError ? import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol35.RPC_ERROR_CODE.RUNTIME_INTERNAL,
33150
33507
  message: error instanceof Error ? error.message : String(error)
33151
33508
  });
33152
33509
  return;
@@ -33160,7 +33517,7 @@ var createRunHandlers = ({
33160
33517
  );
33161
33518
  } catch {
33162
33519
  sendError(id2, {
33163
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
33520
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
33164
33521
  message: "Could not retain the attachments for this conversation. Upload them again."
33165
33522
  });
33166
33523
  return;
@@ -33169,7 +33526,7 @@ var createRunHandlers = ({
33169
33526
  if (!state.canSteerRun(runId)) {
33170
33527
  releaseAttachments?.();
33171
33528
  sendError(id2, {
33172
- code: import_protocol33.RPC_ERROR_CODE.RUN_NOT_FOUND,
33529
+ code: import_protocol35.RPC_ERROR_CODE.RUN_NOT_FOUND,
33173
33530
  message: "active run ended before steer could be queued"
33174
33531
  });
33175
33532
  return;
@@ -33204,7 +33561,7 @@ var createRunHandlers = ({
33204
33561
  const handleGoal = (id2, method, raw) => {
33205
33562
  if (!goals?.enabled) {
33206
33563
  sendError(id2, {
33207
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
33564
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
33208
33565
  message: "Goals are unavailable on this connection."
33209
33566
  });
33210
33567
  return Promise.resolve();
@@ -33243,7 +33600,7 @@ var createRunHandlers = ({
33243
33600
  return;
33244
33601
  }
33245
33602
  sendError(id2, {
33246
- code: import_protocol33.RPC_ERROR_CODE.RUN_NOT_FOUND,
33603
+ code: import_protocol35.RPC_ERROR_CODE.RUN_NOT_FOUND,
33247
33604
  message: "run not found"
33248
33605
  });
33249
33606
  };
@@ -33254,14 +33611,14 @@ var createRunHandlers = ({
33254
33611
  const open3 = async () => {
33255
33612
  if (!sessionId) {
33256
33613
  sendError(id2, {
33257
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
33614
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
33258
33615
  message: "session_id is required"
33259
33616
  });
33260
33617
  return;
33261
33618
  }
33262
33619
  if (state.activeRunId) {
33263
33620
  sendError(id2, {
33264
- code: import_protocol33.RPC_ERROR_CODE.RUNTIME_BUSY,
33621
+ code: import_protocol35.RPC_ERROR_CODE.RUNTIME_BUSY,
33265
33622
  message: "runtime busy"
33266
33623
  });
33267
33624
  return;
@@ -33277,21 +33634,21 @@ var createRunHandlers = ({
33277
33634
  opened = await sessionStateStore.load(sessionId);
33278
33635
  } catch (error) {
33279
33636
  sendError(id2, {
33280
- code: import_protocol33.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
33637
+ code: import_protocol35.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
33281
33638
  message: `session load failed: ${String(error)}`
33282
33639
  });
33283
33640
  return;
33284
33641
  }
33285
33642
  if (!opened) {
33286
33643
  sendError(id2, {
33287
- code: import_protocol33.RPC_ERROR_CODE.SESSION_NOT_FOUND,
33644
+ code: import_protocol35.RPC_ERROR_CODE.SESSION_NOT_FOUND,
33288
33645
  message: "session not found"
33289
33646
  });
33290
33647
  return;
33291
33648
  }
33292
33649
  if (opened.meta?.codelia_subagent) {
33293
33650
  sendError(id2, {
33294
- code: import_protocol33.RPC_ERROR_CODE.INVALID_PARAMS,
33651
+ code: import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
33295
33652
  message: "Delegated sessions cannot be opened as a root session"
33296
33653
  });
33297
33654
  return;
@@ -33329,7 +33686,7 @@ var createRunHandlers = ({
33329
33686
 
33330
33687
  // src/rpc/sandbox.ts
33331
33688
  var import_promises5 = require("fs/promises");
33332
- var import_protocol35 = require("@codelia/protocol");
33689
+ var import_protocol37 = require("@codelia/protocol");
33333
33690
  var import_storage32 = require("@codelia/storage");
33334
33691
  var choices = [
33335
33692
  {
@@ -33397,7 +33754,7 @@ var status = async (state, store) => {
33397
33754
  var handleSandbox = async (state, id2, method, params) => {
33398
33755
  if (!supportsSandboxModeManagement(state))
33399
33756
  return sendError(id2, {
33400
- code: import_protocol35.RPC_ERROR_CODE.METHOD_NOT_FOUND,
33757
+ code: import_protocol37.RPC_ERROR_CODE.METHOD_NOT_FOUND,
33401
33758
  message: "Sandbox management is unavailable."
33402
33759
  });
33403
33760
  if (method === "sandbox.get") {
@@ -33415,7 +33772,7 @@ var handleSandbox = async (state, id2, method, params) => {
33415
33772
  const { mode } = parsed.params;
33416
33773
  const store = new import_storage32.ProjectsPolicyStore();
33417
33774
  const fail = (reason) => sendError(id2, {
33418
- code: reason === "runtime_busy" || reason === "policy_store_busy" ? import_protocol35.RPC_ERROR_CODE.RUNTIME_BUSY : import_protocol35.RPC_ERROR_CODE.INVALID_PARAMS,
33775
+ code: reason === "runtime_busy" || reason === "policy_store_busy" ? import_protocol37.RPC_ERROR_CODE.RUNTIME_BUSY : import_protocol37.RPC_ERROR_CODE.INVALID_PARAMS,
33419
33776
  message: `Project sandbox mode could not be changed (${reason}).`,
33420
33777
  data: { reason }
33421
33778
  });
@@ -33441,11 +33798,11 @@ var handleSandbox = async (state, id2, method, params) => {
33441
33798
  };
33442
33799
 
33443
33800
  // src/rpc/session-lifecycle.ts
33444
- var import_protocol37 = require("@codelia/protocol");
33801
+ var import_protocol39 = require("@codelia/protocol");
33445
33802
  var createSessionUpdateHandler = (options) => async (id2, raw) => {
33446
33803
  if (!options.sessions.updateMetadata) {
33447
33804
  sendError(id2, {
33448
- code: import_protocol37.RPC_ERROR_CODE.INVALID_PARAMS,
33805
+ code: import_protocol39.RPC_ERROR_CODE.INVALID_PARAMS,
33449
33806
  message: "Session lifecycle updates are unavailable"
33450
33807
  });
33451
33808
  return;
@@ -33455,14 +33812,14 @@ var createSessionUpdateHandler = (options) => async (id2, raw) => {
33455
33812
  const params = parsed.params;
33456
33813
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(params.session_id) || params.pinned === void 0 && params.archived === void 0) {
33457
33814
  sendError(id2, {
33458
- code: import_protocol37.RPC_ERROR_CODE.INVALID_PARAMS,
33815
+ code: import_protocol39.RPC_ERROR_CODE.INVALID_PARAMS,
33459
33816
  message: "Expected session_id and a boolean pinned or archived update"
33460
33817
  });
33461
33818
  return;
33462
33819
  }
33463
33820
  if (params.archived && options.state.activeRunId && options.state.sessionId === params.session_id) {
33464
33821
  sendError(id2, {
33465
- code: import_protocol37.RPC_ERROR_CODE.RUNTIME_BUSY,
33822
+ code: import_protocol39.RPC_ERROR_CODE.RUNTIME_BUSY,
33466
33823
  message: "Wait for the active run before archiving this session"
33467
33824
  });
33468
33825
  return;
@@ -33483,7 +33840,7 @@ var createSessionUpdateHandler = (options) => async (id2, raw) => {
33483
33840
  sendRequestResult("session.update", id2, result);
33484
33841
  } catch (error) {
33485
33842
  sendError(id2, {
33486
- code: import_protocol37.RPC_ERROR_CODE.INVALID_PARAMS,
33843
+ code: import_protocol39.RPC_ERROR_CODE.INVALID_PARAMS,
33487
33844
  message: `Session update failed: ${String(error)}`
33488
33845
  });
33489
33846
  }
@@ -33491,17 +33848,17 @@ var createSessionUpdateHandler = (options) => async (id2, raw) => {
33491
33848
 
33492
33849
  // src/rpc/shell.ts
33493
33850
  var import_node_path49 = __toESM(require("path"), 1);
33494
- var import_protocol40 = require("@codelia/protocol");
33851
+ var import_protocol42 = require("@codelia/protocol");
33495
33852
  var import_storage33 = require("@codelia/storage");
33496
33853
 
33497
33854
  // src/rpc/shell-timeout.ts
33498
- var import_protocol39 = require("@codelia/protocol");
33855
+ var import_protocol41 = require("@codelia/protocol");
33499
33856
  var resolveRpcShellTimeoutSeconds = (requestedTimeout, background) => {
33500
33857
  if (requestedTimeout !== void 0) {
33501
33858
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
33502
33859
  return {
33503
33860
  error: {
33504
- code: import_protocol39.RPC_ERROR_CODE.INVALID_PARAMS,
33861
+ code: import_protocol41.RPC_ERROR_CODE.INVALID_PARAMS,
33505
33862
  message: "timeout_seconds must be a positive number"
33506
33863
  }
33507
33864
  };
@@ -33515,7 +33872,7 @@ var resolveRpcShellTimeoutSeconds = (requestedTimeout, background) => {
33515
33872
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
33516
33873
  return {
33517
33874
  error: {
33518
- code: import_protocol39.RPC_ERROR_CODE.INVALID_PARAMS,
33875
+ code: import_protocol41.RPC_ERROR_CODE.INVALID_PARAMS,
33519
33876
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
33520
33877
  }
33521
33878
  };
@@ -33576,7 +33933,7 @@ var parseShellOutputRequest = (params) => {
33576
33933
  if (!taskId) {
33577
33934
  return {
33578
33935
  error: {
33579
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
33936
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33580
33937
  message: "task_id is required"
33581
33938
  }
33582
33939
  };
@@ -33584,7 +33941,7 @@ var parseShellOutputRequest = (params) => {
33584
33941
  if (params?.stream !== "stdout" && params?.stream !== "stderr") {
33585
33942
  return {
33586
33943
  error: {
33587
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
33944
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33588
33945
  message: "stream must be stdout or stderr"
33589
33946
  }
33590
33947
  };
@@ -33592,7 +33949,7 @@ var parseShellOutputRequest = (params) => {
33592
33949
  if (params.line_number !== void 0 && (params.offset !== void 0 || params.limit !== void 0)) {
33593
33950
  return {
33594
33951
  error: {
33595
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
33952
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33596
33953
  message: "line_number cannot be combined with offset or limit"
33597
33954
  }
33598
33955
  };
@@ -33600,7 +33957,7 @@ var parseShellOutputRequest = (params) => {
33600
33957
  if (params.line_number === void 0 && (params.char_offset !== void 0 || params.char_limit !== void 0)) {
33601
33958
  return {
33602
33959
  error: {
33603
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
33960
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33604
33961
  message: "char_offset/char_limit require line_number"
33605
33962
  }
33606
33963
  };
@@ -33608,7 +33965,7 @@ var parseShellOutputRequest = (params) => {
33608
33965
  if (params.offset !== void 0 && (!Number.isFinite(params.offset) || params.offset < 0)) {
33609
33966
  return {
33610
33967
  error: {
33611
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
33968
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33612
33969
  message: "offset must be a non-negative number"
33613
33970
  }
33614
33971
  };
@@ -33616,7 +33973,7 @@ var parseShellOutputRequest = (params) => {
33616
33973
  if (params.limit !== void 0 && (!Number.isFinite(params.limit) || params.limit <= 0)) {
33617
33974
  return {
33618
33975
  error: {
33619
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
33976
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33620
33977
  message: "limit must be a positive number"
33621
33978
  }
33622
33979
  };
@@ -33624,7 +33981,7 @@ var parseShellOutputRequest = (params) => {
33624
33981
  if (params.line_number !== void 0 && (!Number.isFinite(params.line_number) || params.line_number <= 0)) {
33625
33982
  return {
33626
33983
  error: {
33627
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
33984
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33628
33985
  message: "line_number must be a positive number"
33629
33986
  }
33630
33987
  };
@@ -33632,7 +33989,7 @@ var parseShellOutputRequest = (params) => {
33632
33989
  if (params.char_offset !== void 0 && (!Number.isFinite(params.char_offset) || params.char_offset < 0)) {
33633
33990
  return {
33634
33991
  error: {
33635
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
33992
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33636
33993
  message: "char_offset must be a non-negative number"
33637
33994
  }
33638
33995
  };
@@ -33640,7 +33997,7 @@ var parseShellOutputRequest = (params) => {
33640
33997
  if (params.char_limit !== void 0 && (!Number.isFinite(params.char_limit) || params.char_limit <= 0)) {
33641
33998
  return {
33642
33999
  error: {
33643
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34000
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33644
34001
  message: "char_limit must be a positive number"
33645
34002
  }
33646
34003
  };
@@ -33694,7 +34051,7 @@ var parseTaskId = (value) => {
33694
34051
  var toTaskRpcError = (error) => {
33695
34052
  if (!(error instanceof TaskManagerError)) {
33696
34053
  return {
33697
- code: import_protocol40.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34054
+ code: import_protocol42.RPC_ERROR_CODE.RUNTIME_INTERNAL,
33698
34055
  message: String(error)
33699
34056
  };
33700
34057
  }
@@ -33703,17 +34060,17 @@ var toTaskRpcError = (error) => {
33703
34060
  case "invalid_task_id":
33704
34061
  case "unsupported_workspace_mode":
33705
34062
  return {
33706
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34063
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33707
34064
  message: error.message
33708
34065
  };
33709
34066
  case "manager_shutting_down":
33710
34067
  return {
33711
- code: import_protocol40.RPC_ERROR_CODE.RUNTIME_BUSY,
34068
+ code: import_protocol42.RPC_ERROR_CODE.RUNTIME_BUSY,
33712
34069
  message: error.message
33713
34070
  };
33714
34071
  default:
33715
34072
  return {
33716
- code: import_protocol40.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34073
+ code: import_protocol42.RPC_ERROR_CODE.RUNTIME_INTERNAL,
33717
34074
  message: error.message
33718
34075
  };
33719
34076
  }
@@ -33737,7 +34094,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
33737
34094
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
33738
34095
  return {
33739
34096
  error: {
33740
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34097
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33741
34098
  message: "wait_timeout_seconds must be a positive number"
33742
34099
  }
33743
34100
  };
@@ -33745,7 +34102,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
33745
34102
  if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
33746
34103
  return {
33747
34104
  error: {
33748
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34105
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33749
34106
  message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
33750
34107
  }
33751
34108
  };
@@ -33760,7 +34117,7 @@ var parseShellStartRequest = (state, params, options) => {
33760
34117
  if (!command.trim()) {
33761
34118
  return {
33762
34119
  error: {
33763
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34120
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33764
34121
  message: "command is required"
33765
34122
  }
33766
34123
  };
@@ -33776,7 +34133,7 @@ var parseShellStartRequest = (state, params, options) => {
33776
34133
  if (!cwd) {
33777
34134
  return {
33778
34135
  error: {
33779
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34136
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33780
34137
  message: "cwd is outside sandbox root"
33781
34138
  }
33782
34139
  };
@@ -33902,7 +34259,7 @@ var createShellHandlers = ({
33902
34259
  const requestedLimit = params?.limit;
33903
34260
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
33904
34261
  sendError(id2, {
33905
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34262
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33906
34263
  message: "limit must be a positive number"
33907
34264
  });
33908
34265
  return;
@@ -33920,7 +34277,7 @@ var createShellHandlers = ({
33920
34277
  const taskId = parseTaskId(params?.task_id);
33921
34278
  if (!taskId) {
33922
34279
  sendError(id2, {
33923
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34280
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33924
34281
  message: "task_id is required"
33925
34282
  });
33926
34283
  return;
@@ -33956,7 +34313,7 @@ var createShellHandlers = ({
33956
34313
  );
33957
34314
  if (!cacheId && liveContent === null && !isTerminalTaskState(task.state)) {
33958
34315
  sendError(id2, {
33959
- code: import_protocol40.RPC_ERROR_CODE.RUNTIME_BUSY,
34316
+ code: import_protocol42.RPC_ERROR_CODE.RUNTIME_BUSY,
33960
34317
  message: `shell output is not retained yet for running task: ${parsed.taskId}`
33961
34318
  });
33962
34319
  return;
@@ -33993,7 +34350,7 @@ var createShellHandlers = ({
33993
34350
  const taskId = parseTaskId(params?.task_id);
33994
34351
  if (!taskId) {
33995
34352
  sendError(id2, {
33996
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34353
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
33997
34354
  message: "task_id is required"
33998
34355
  });
33999
34356
  return;
@@ -34085,7 +34442,7 @@ var createShellHandlers = ({
34085
34442
  const taskId = parseTaskId(params?.task_id);
34086
34443
  if (!taskId) {
34087
34444
  sendError(id2, {
34088
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34445
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
34089
34446
  message: "task_id is required"
34090
34447
  });
34091
34448
  return;
@@ -34099,7 +34456,7 @@ var createShellHandlers = ({
34099
34456
  const waits = activeShellWaits.get(taskId);
34100
34457
  if (!waits || waits.size === 0) {
34101
34458
  sendError(id2, {
34102
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34459
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
34103
34460
  message: `no active shell.wait to detach for task: ${taskId}`
34104
34461
  });
34105
34462
  return;
@@ -34121,7 +34478,7 @@ var createShellHandlers = ({
34121
34478
  const taskId = parseTaskId(params?.task_id);
34122
34479
  if (!taskId) {
34123
34480
  sendError(id2, {
34124
- code: import_protocol40.RPC_ERROR_CODE.INVALID_PARAMS,
34481
+ code: import_protocol42.RPC_ERROR_CODE.INVALID_PARAMS,
34125
34482
  message: "task_id is required"
34126
34483
  });
34127
34484
  return;
@@ -34150,7 +34507,7 @@ var createShellHandlers = ({
34150
34507
 
34151
34508
  // src/rpc/skills.ts
34152
34509
  var import_node_path50 = __toESM(require("path"), 1);
34153
- var import_protocol42 = require("@codelia/protocol");
34510
+ var import_protocol44 = require("@codelia/protocol");
34154
34511
  var createSkillsHandlers = ({
34155
34512
  state,
34156
34513
  log: log2
@@ -34181,7 +34538,7 @@ var createSkillsHandlers = ({
34181
34538
  });
34182
34539
  } catch (error) {
34183
34540
  sendError(id2, {
34184
- code: import_protocol42.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34541
+ code: import_protocol44.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34185
34542
  message: `skills resolver init failed: ${String(error)}`
34186
34543
  });
34187
34544
  return;
@@ -34203,7 +34560,7 @@ var createSkillsHandlers = ({
34203
34560
  } catch (error) {
34204
34561
  log2(`skills.list error: ${String(error)}`);
34205
34562
  sendError(id2, {
34206
- code: import_protocol42.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34563
+ code: import_protocol44.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34207
34564
  message: `skills list failed: ${String(error)}`
34208
34565
  });
34209
34566
  }
@@ -34213,7 +34570,7 @@ var createSkillsHandlers = ({
34213
34570
 
34214
34571
  // src/rpc/task.ts
34215
34572
  var import_node_path51 = __toESM(require("path"), 1);
34216
- var import_protocol44 = require("@codelia/protocol");
34573
+ var import_protocol46 = require("@codelia/protocol");
34217
34574
  var import_storage34 = require("@codelia/storage");
34218
34575
  var DEFAULT_TRUNCATED2 = {
34219
34576
  stdout: false,
@@ -34263,7 +34620,7 @@ var parseTaskId2 = (value) => {
34263
34620
  var toTaskRpcError2 = (error) => {
34264
34621
  if (!(error instanceof TaskManagerError)) {
34265
34622
  return {
34266
- code: import_protocol44.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34623
+ code: import_protocol46.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34267
34624
  message: String(error)
34268
34625
  };
34269
34626
  }
@@ -34272,17 +34629,17 @@ var toTaskRpcError2 = (error) => {
34272
34629
  case "invalid_task_id":
34273
34630
  case "unsupported_workspace_mode":
34274
34631
  return {
34275
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34632
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34276
34633
  message: error.message
34277
34634
  };
34278
34635
  case "manager_shutting_down":
34279
34636
  return {
34280
- code: import_protocol44.RPC_ERROR_CODE.RUNTIME_BUSY,
34637
+ code: import_protocol46.RPC_ERROR_CODE.RUNTIME_BUSY,
34281
34638
  message: error.message
34282
34639
  };
34283
34640
  default:
34284
34641
  return {
34285
- code: import_protocol44.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34642
+ code: import_protocol46.RPC_ERROR_CODE.RUNTIME_INTERNAL,
34286
34643
  message: error.message
34287
34644
  };
34288
34645
  }
@@ -34335,7 +34692,7 @@ var parseShellSpawnRequest = (state, params, options) => {
34335
34692
  if (!command.trim()) {
34336
34693
  return {
34337
34694
  error: {
34338
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34695
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34339
34696
  message: "command is required for shell tasks"
34340
34697
  }
34341
34698
  };
@@ -34351,7 +34708,7 @@ var parseShellSpawnRequest = (state, params, options) => {
34351
34708
  if (!cwd) {
34352
34709
  return {
34353
34710
  error: {
34354
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34711
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34355
34712
  message: "cwd is outside sandbox root"
34356
34713
  }
34357
34714
  };
@@ -34431,7 +34788,7 @@ var createTaskHandlers = ({
34431
34788
  const handleTaskSpawn = async (id2, params) => {
34432
34789
  if (!params || !isTaskKind(params.kind)) {
34433
34790
  sendError(id2, {
34434
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34791
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34435
34792
  message: "kind must be shell or subagent"
34436
34793
  });
34437
34794
  return;
@@ -34439,7 +34796,7 @@ var createTaskHandlers = ({
34439
34796
  if (params.kind !== "shell") {
34440
34797
  if (params.kind !== "subagent" || !subagents?.isAvailable() || !getAgent) {
34441
34798
  sendError(id2, {
34442
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34799
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34443
34800
  message: `task kind ${params.kind} is not supported yet.`
34444
34801
  });
34445
34802
  return;
@@ -34523,21 +34880,21 @@ var createTaskHandlers = ({
34523
34880
  const requestedLimit = params?.limit;
34524
34881
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
34525
34882
  sendError(id2, {
34526
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34883
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34527
34884
  message: "limit must be a positive number"
34528
34885
  });
34529
34886
  return;
34530
34887
  }
34531
34888
  if (params?.kind !== void 0 && !isTaskKind(params.kind)) {
34532
34889
  sendError(id2, {
34533
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34890
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34534
34891
  message: "kind must be shell or subagent"
34535
34892
  });
34536
34893
  return;
34537
34894
  }
34538
34895
  if (params?.state !== void 0 && !isTaskState(params.state)) {
34539
34896
  sendError(id2, {
34540
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34897
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34541
34898
  message: "invalid task state"
34542
34899
  });
34543
34900
  return;
@@ -34555,7 +34912,7 @@ var createTaskHandlers = ({
34555
34912
  const taskId = parseTaskId2(params?.task_id);
34556
34913
  if (!taskId) {
34557
34914
  sendError(id2, {
34558
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34915
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34559
34916
  message: "task_id is required"
34560
34917
  });
34561
34918
  return;
@@ -34575,7 +34932,7 @@ var createTaskHandlers = ({
34575
34932
  const taskId = parseTaskId2(params?.task_id);
34576
34933
  if (!taskId) {
34577
34934
  sendError(id2, {
34578
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34935
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34579
34936
  message: "task_id is required"
34580
34937
  });
34581
34938
  return;
@@ -34596,7 +34953,7 @@ var createTaskHandlers = ({
34596
34953
  const taskId = parseTaskId2(params?.task_id);
34597
34954
  if (!taskId) {
34598
34955
  sendError(id2, {
34599
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34956
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34600
34957
  message: "task_id is required"
34601
34958
  });
34602
34959
  return;
@@ -34619,7 +34976,7 @@ var createTaskHandlers = ({
34619
34976
  const taskId = parseTaskId2(params?.task_id);
34620
34977
  if (!taskId) {
34621
34978
  sendError(id2, {
34622
- code: import_protocol44.RPC_ERROR_CODE.INVALID_PARAMS,
34979
+ code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
34623
34980
  message: "task_id is required"
34624
34981
  });
34625
34982
  return;
@@ -34884,6 +35241,11 @@ var createRuntimeHandlers = ({
34884
35241
  state,
34885
35242
  log: log2
34886
35243
  });
35244
+ const telemetryHandlers = createTelemetryHandlers({
35245
+ state,
35246
+ subagents,
35247
+ log: log2
35248
+ });
34887
35249
  const { handleSkillsList } = createSkillsHandlers({
34888
35250
  state,
34889
35251
  log: log2
@@ -34911,12 +35273,15 @@ var createRuntimeHandlers = ({
34911
35273
  const parsed = parseRequestParams("initialize", raw);
34912
35274
  if (!parsed.ok) return sendError(id2, parsed.error);
34913
35275
  const params = parsed.params;
34914
- let resolvedTheme;
35276
+ let resolvedTui;
34915
35277
  const environment2 = state.effectiveEnvironment;
34916
35278
  if (isTuiLocalEnvironment(environment2)) {
34917
35279
  try {
34918
35280
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
34919
- resolvedTheme = (await resolveEnvironmentTuiConfig(state, workingDir)).theme;
35281
+ const loaded = await resolveEnvironmentTuiConfig(state, workingDir);
35282
+ if (loaded.theme || loaded.color_scheme || loaded.image_protocol) {
35283
+ resolvedTui = loaded;
35284
+ }
34920
35285
  } catch (error) {
34921
35286
  log2(`initialize tui config load failed: ${String(error)}`);
34922
35287
  }
@@ -34955,7 +35320,7 @@ var createRuntimeHandlers = ({
34955
35320
  supports_run_cancel: true,
34956
35321
  supports_run_steer: true,
34957
35322
  supports_goals: Boolean(goalStore),
34958
- supports_run_diagnostics: true,
35323
+ supports_telemetry: true,
34959
35324
  supports_session_lifecycle: !!sessionStateStore.updateMetadata,
34960
35325
  supports_shell_exec: !!shellBackend,
34961
35326
  supports_shell_tasks: processEnabled,
@@ -34986,7 +35351,7 @@ var createRuntimeHandlers = ({
34986
35351
  supports_text_delta: true
34987
35352
  },
34988
35353
  ...localHost ? { local_host: localHost } : {},
34989
- ...localHost || resolvedTheme ? { tui: { theme: resolvedTheme, ...localHost } } : {}
35354
+ ...localHost || resolvedTui ? { tui: { ...resolvedTui, ...localHost } } : {}
34990
35355
  };
34991
35356
  sendRequestResult("initialize", id2, result);
34992
35357
  log2(`initialize from ${params.client?.name ?? "unknown"}`);
@@ -35004,7 +35369,7 @@ var createRuntimeHandlers = ({
35004
35369
  const handleThemeSet = async (id2, raw) => {
35005
35370
  if (state.activeRunId) {
35006
35371
  sendError(id2, {
35007
- code: import_protocol46.RPC_ERROR_CODE.RUNTIME_BUSY,
35372
+ code: import_protocol48.RPC_ERROR_CODE.RUNTIME_BUSY,
35008
35373
  message: "runtime busy"
35009
35374
  });
35010
35375
  return;
@@ -35014,14 +35379,14 @@ var createRuntimeHandlers = ({
35014
35379
  const name2 = parsed.params.name.trim().toLowerCase();
35015
35380
  if (!name2) {
35016
35381
  sendError(id2, {
35017
- code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
35382
+ code: import_protocol48.RPC_ERROR_CODE.INVALID_PARAMS,
35018
35383
  message: "theme name is required"
35019
35384
  });
35020
35385
  return;
35021
35386
  }
35022
35387
  if (!SUPPORTED_TUI_THEMES.has(name2)) {
35023
35388
  sendError(id2, {
35024
- code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
35389
+ code: import_protocol48.RPC_ERROR_CODE.INVALID_PARAMS,
35025
35390
  message: `unsupported theme: ${name2}`
35026
35391
  });
35027
35392
  return;
@@ -35037,7 +35402,7 @@ var createRuntimeHandlers = ({
35037
35402
  log2(`theme.set ${name2} scope=${target2.scope} path=${target2.path}`);
35038
35403
  } catch (error) {
35039
35404
  sendError(id2, {
35040
- code: import_protocol46.RPC_ERROR_CODE.RUNTIME_INTERNAL,
35405
+ code: import_protocol48.RPC_ERROR_CODE.RUNTIME_INTERNAL,
35041
35406
  message: String(error)
35042
35407
  });
35043
35408
  }
@@ -35058,7 +35423,7 @@ var createRuntimeHandlers = ({
35058
35423
  const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
35059
35424
  const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
35060
35425
  const rejectDisabled = (message) => sendError(req.id, {
35061
- code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
35426
+ code: import_protocol48.RPC_ERROR_CODE.INVALID_PARAMS,
35062
35427
  message
35063
35428
  });
35064
35429
  switch (req.method) {
@@ -35283,13 +35648,18 @@ var createRuntimeHandlers = ({
35283
35648
  if (!parsed.ok) return sendError(req.id, parsed.error);
35284
35649
  return contextUsageHandlers.handleContextUsage(req.id);
35285
35650
  }
35651
+ case "telemetry.get": {
35652
+ const parsed = parseRequestParams("telemetry.get", req.params);
35653
+ if (!parsed.ok) return sendError(req.id, parsed.error);
35654
+ return telemetryHandlers.handleTelemetryGet(req.id);
35655
+ }
35286
35656
  case "theme.set":
35287
35657
  if (!themeSetEnabled)
35288
35658
  return rejectDisabled("theme setting is disabled");
35289
35659
  return handleThemeSet(req.id, req.params);
35290
35660
  default:
35291
35661
  return sendError(req.id, {
35292
- code: import_protocol46.RPC_ERROR_CODE.METHOD_NOT_FOUND,
35662
+ code: import_protocol48.RPC_ERROR_CODE.METHOD_NOT_FOUND,
35293
35663
  message: "method not found"
35294
35664
  });
35295
35665
  }
@@ -35317,7 +35687,7 @@ var createRuntimeHandlers = ({
35317
35687
  if (msg.jsonrpc !== "2.0" || "method" in msg && typeof msg.method !== "string") {
35318
35688
  if (id2 !== void 0) {
35319
35689
  sendError(id2, {
35320
- code: import_protocol46.RPC_ERROR_CODE.INVALID_REQUEST,
35690
+ code: import_protocol48.RPC_ERROR_CODE.INVALID_REQUEST,
35321
35691
  message: "invalid request"
35322
35692
  });
35323
35693
  } else {
@@ -35334,7 +35704,7 @@ var createRuntimeHandlers = ({
35334
35704
  if (invalid) {
35335
35705
  if (id2 !== void 0)
35336
35706
  sendError(id2, {
35337
- code: import_protocol46.RPC_ERROR_CODE.INVALID_PARAMS,
35707
+ code: import_protocol48.RPC_ERROR_CODE.INVALID_PARAMS,
35338
35708
  message: invalid
35339
35709
  });
35340
35710
  else log2(`invalid rpc notification: ${msg.method}`);
@@ -35348,7 +35718,7 @@ var createRuntimeHandlers = ({
35348
35718
  if (!hasRpcResponse(id2)) {
35349
35719
  try {
35350
35720
  sendError(id2, {
35351
- code: import_protocol46.RPC_ERROR_CODE.RUNTIME_INTERNAL,
35721
+ code: import_protocol48.RPC_ERROR_CODE.RUNTIME_INTERNAL,
35352
35722
  message: "internal runtime error"
35353
35723
  });
35354
35724
  } catch {
@@ -35373,7 +35743,7 @@ var createRuntimeHandlers = ({
35373
35743
  handleResponse(msg);
35374
35744
  } else if (id2 !== void 0) {
35375
35745
  sendError(id2, {
35376
- code: import_protocol46.RPC_ERROR_CODE.INVALID_REQUEST,
35746
+ code: import_protocol48.RPC_ERROR_CODE.INVALID_REQUEST,
35377
35747
  message: "invalid request"
35378
35748
  });
35379
35749
  } else {
@@ -35585,12 +35955,11 @@ var prepareProcess = (input, options, channel) => {
35585
35955
  cwd: input.workspace_root,
35586
35956
  detached: process.platform !== "win32",
35587
35957
  stdio: ["pipe", "pipe", "pipe", "pipe"],
35588
- // Provider logging can write raw credentials/payloads outside the child contract.
35958
+ // Debug/provider logging can write raw credentials/payloads outside the child contract.
35589
35959
  env: {
35590
35960
  ...process.env,
35591
- CODELIA_PROVIDER_LOG: "0",
35592
- CODELIA_DEBUG: "0",
35593
- CODELIA_DIAGNOSTICS: "0"
35961
+ CODELIA_DEBUG: "",
35962
+ CODELIA_DEBUG_DIR: ""
35594
35963
  }
35595
35964
  }
35596
35965
  );
@@ -35786,21 +36155,20 @@ function normalizeChildResult(result) {
35786
36155
  }
35787
36156
 
35788
36157
  // src/runtime.ts
35789
- var envTruthy3 = (value) => {
35790
- if (!value) return false;
35791
- const normalized = value.trim().toLowerCase();
35792
- return normalized === "1" || normalized === "true";
35793
- };
35794
36158
  var startRuntime = async (options = {}) => {
35795
36159
  const state = new RuntimeState();
35796
36160
  state.setRuntimeEnvironment(options);
35797
36161
  const environment = state.effectiveEnvironment;
36162
+ const sandboxModeStart = performance.now();
35798
36163
  state.sandboxMode = await resolveRuntimeSandboxMode(environment);
36164
+ state.telemetry.recordStartupPhase(
36165
+ "sandbox_mode",
36166
+ performance.now() - sandboxModeStart
36167
+ );
35799
36168
  if (state.sandboxMode.legacy === "full-access")
35800
36169
  (0, import_logger.log)(
35801
36170
  "Legacy approval_mode full-access uses workspace-write. Specify --sandbox-mode full-access to disable OS isolation and keep command approval."
35802
36171
  );
35803
- state.diagnosticsEnabled = envTruthy3(process.env.CODELIA_DIAGNOSTICS);
35804
36172
  const workingDir = environment.workspace.root;
35805
36173
  if (workingDir) {
35806
36174
  state.runtimeWorkingDir = workingDir;
@@ -35810,15 +36178,22 @@ var startRuntime = async (options = {}) => {
35810
36178
  }
35811
36179
  state.attachments = createRuntimeAttachmentService(state);
35812
36180
  if (environment.context.projectInstructions === "from-workspace" && workingDir) {
36181
+ const agentsStart = performance.now();
35813
36182
  try {
36183
+ const agentsEnabled = environment.config.source === "disabled" ? true : await resolveAgentsEnabled(workingDir).catch(() => true);
35814
36184
  state.agentsResolver = await AgentsResolver.create(
35815
36185
  workingDir,
35816
- void 0,
36186
+ { enabled: agentsEnabled },
35817
36187
  void 0,
35818
36188
  await runtimeResourceReader(state, workingDir)
35819
36189
  );
35820
36190
  } catch (error) {
35821
36191
  (0, import_logger.log)(`agents resolver startup init failed: ${String(error)}`);
36192
+ } finally {
36193
+ state.telemetry.recordStartupPhase(
36194
+ "agents_resolver",
36195
+ performance.now() - agentsStart
36196
+ );
35822
36197
  }
35823
36198
  }
35824
36199
  const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage36.SessionStateStoreImpl({