@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.
@@ -54,6 +54,7 @@ import {
54
54
  getResponsesProvider,
55
55
  getSandboxContext,
56
56
  getStoredProviderApiKey,
57
+ getTransportBackpressureEvents,
57
58
  hasRpcResponse,
58
59
  isDebugEnabled,
59
60
  isHomeDotTarget,
@@ -98,6 +99,8 @@ import {
98
99
  requestUiConfirm,
99
100
  requestUiPick,
100
101
  requestUiPrompt,
102
+ resolveAgentsEnabled,
103
+ resolveAuthOAuthBrowser,
101
104
  resolveConfigLayers,
102
105
  resolveConfigPath,
103
106
  resolveConfiguredReasoning,
@@ -126,9 +129,9 @@ import {
126
129
  sendNotificationAsync,
127
130
  sendRequestResult,
128
131
  sendRunContext,
129
- sendRunDiagnostics,
130
132
  sendRunMetrics,
131
133
  sendRunStatus,
134
+ sendRunSummary,
132
135
  setProviderChatAuth,
133
136
  shellBinPaths,
134
137
  shouldAutoOpenOAuthBrowser,
@@ -144,7 +147,7 @@ import {
144
147
  updateTuiTheme,
145
148
  withRpcResponseContext,
146
149
  workspacePathProtection
147
- } from "./chunk-X4222JDX.js";
150
+ } from "./chunk-K42SQONI.js";
148
151
 
149
152
  // src/permissions/launch-rules.ts
150
153
  import { spawnSync } from "child_process";
@@ -878,6 +881,14 @@ var ApprovalDispatcher = class {
878
881
  return failure2?.outcome;
879
882
  }
880
883
  dispatch(options) {
884
+ const nowMs = this.options.monotonicNow ?? (() => performance.now());
885
+ const approvalStartedAt = options.onApprovalWaitMs ? nowMs() : 0;
886
+ let approvalRecorded = false;
887
+ const recordApprovalWait = () => {
888
+ if (approvalRecorded || !options.onApprovalWaitMs) return;
889
+ approvalRecorded = true;
890
+ options.onApprovalWaitMs(Math.max(0, nowMs() - approvalStartedAt));
891
+ };
881
892
  const request = Object.freeze({ ...options.request });
882
893
  const { id: id2, ...binding } = request;
883
894
  const receiptBinding = options.deduplicate ? digest(binding) : void 0;
@@ -888,286 +899,292 @@ var ApprovalDispatcher = class {
888
899
  ...options.signal ? [options.signal] : []
889
900
  ]) : options.signal;
890
901
  const dispatch = async () => {
891
- const facts = options.evaluate();
892
- const route = freezeRoute(routeApproval(facts));
893
- let actor = facts.confinedAutoLaunch && route.kind === "immediate" ? "sandbox" : "rule";
894
- const audit = (state, reason, taskId, diagnostic) => this.options.audit?.({
895
- requestId: id2,
896
- origin: request.origin,
897
- subject: request.subject,
898
- route: route.kind,
899
- profile: route.profile,
900
- actor,
901
- state,
902
- reason,
903
- ...diagnostic ? { reviewDiagnostic: diagnostic } : {},
904
- at: Date.now(),
905
- ...taskId ? { taskId } : {},
906
- ...request.runId ? { runId: request.runId } : {}
907
- });
908
- if (route.kind === "deny") {
909
- audit("denied", route.reason);
910
- return reject(route.reason);
911
- }
912
- const expire = (reason, diagnostic) => {
913
- audit("expired", reason, void 0, diagnostic);
914
- return reject(
915
- diagnostic ? `${reason}: ${reviewDiagnosticText(diagnostic)}` : reason
916
- );
917
- };
918
- const checkCurrent = (reviewing = false) => {
919
- if (requestSignal?.aborted || !options.stillCurrent()) {
920
- expire(
921
- "approval_expired",
922
- reviewing ? reviewDiagnostic(
923
- requestSignal?.aborted ? "review_cancelled" : "review_authority_changed"
924
- ) : void 0
902
+ try {
903
+ const facts = options.evaluate();
904
+ const route = freezeRoute(routeApproval(facts));
905
+ let actor = facts.confinedAutoLaunch && route.kind === "immediate" ? "sandbox" : "rule";
906
+ const audit = (state, reason, taskId, diagnostic) => this.options.audit?.({
907
+ requestId: id2,
908
+ origin: request.origin,
909
+ subject: request.subject,
910
+ route: route.kind,
911
+ profile: route.profile,
912
+ actor,
913
+ state,
914
+ reason,
915
+ ...diagnostic ? { reviewDiagnostic: diagnostic } : {},
916
+ at: Date.now(),
917
+ ...taskId ? { taskId } : {},
918
+ ...request.runId ? { runId: request.runId } : {}
919
+ });
920
+ if (route.kind === "deny") {
921
+ audit("denied", route.reason);
922
+ return reject(route.reason);
923
+ }
924
+ const expire = (reason, diagnostic) => {
925
+ audit("expired", reason, void 0, diagnostic);
926
+ return reject(
927
+ diagnostic ? `${reason}: ${reviewDiagnosticText(diagnostic)}` : reason
928
+ );
929
+ };
930
+ const checkCurrent = (reviewing = false) => {
931
+ if (requestSignal?.aborted || !options.stillCurrent()) {
932
+ expire(
933
+ "approval_expired",
934
+ reviewing ? reviewDiagnostic(
935
+ requestSignal?.aborted ? "review_cancelled" : "review_authority_changed"
936
+ ) : void 0
937
+ );
938
+ }
939
+ };
940
+ checkCurrent();
941
+ const unsandboxedEscalation = route.profile === "full-access" && route.additional.length === 1 && isUnsandboxedShellResource(route.additional[0]);
942
+ 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;
943
+ if (route.kind === "defer" && !interactive) {
944
+ const diagnostic = options.reviewCoverageDiagnostic ?? reviewDiagnostic("review_evidence_unavailable");
945
+ audit("denied", "review_evidence_unavailable", void 0, diagnostic);
946
+ return rejectLocalReview(
947
+ "review_evidence_unavailable",
948
+ void 0,
949
+ diagnostic
925
950
  );
926
951
  }
927
- };
928
- checkCurrent();
929
- const unsandboxedEscalation = route.profile === "full-access" && route.additional.length === 1 && isUnsandboxedShellResource(route.additional[0]);
930
- 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;
931
- if (route.kind === "defer" && !interactive) {
932
- const diagnostic = options.reviewCoverageDiagnostic ?? reviewDiagnostic("review_evidence_unavailable");
933
- audit("denied", "review_evidence_unavailable", void 0, diagnostic);
934
- return rejectLocalReview(
935
- "review_evidence_unavailable",
936
- void 0,
937
- diagnostic
938
- );
939
- }
940
- let save = options.save;
941
- let saveScope;
942
- let sessionGrant;
943
- const version = route.kind === "review" ? this.options.review?.reviewVersion?.(request) : void 0;
944
- if (route.kind !== "immediate") {
945
- const retryKey = facts.autoReview && route.kind === "review" ? createHash3("sha256").update(
946
- JSON.stringify([
947
- request.owner,
948
- request.intentVersion,
949
- request.authorityVersion,
952
+ let save = options.save;
953
+ let saveScope;
954
+ let sessionGrant;
955
+ const version = route.kind === "review" ? this.options.review?.reviewVersion?.(request) : void 0;
956
+ if (route.kind !== "immediate") {
957
+ const retryKey = facts.autoReview && route.kind === "review" ? createHash3("sha256").update(
958
+ JSON.stringify([
959
+ request.owner,
960
+ request.intentVersion,
961
+ request.authorityVersion,
962
+ version,
963
+ options.reviewRetryKey ?? digest(binding)
964
+ ])
965
+ ).digest("hex") : void 0;
966
+ const evidenceKey = retryKey === void 0 ? void 0 : `${retryKey}/${options.reviewRetryEvidenceKey ?? ""}`;
967
+ const now = this.options.monotonicNow ?? (() => performance.now());
968
+ const cachedFailure = retryKey === void 0 || evidenceKey === void 0 ? void 0 : this.reviewFailure(retryKey, now()) ?? this.reviewFailure(evidenceKey, now());
969
+ let reviewReason;
970
+ const reviewResult = cachedFailure ?? (route.kind === "review" ? await this.review(
971
+ request,
972
+ retryKey ?? receiptBinding ?? digest(binding),
973
+ facts.reviewCategory,
950
974
  version,
951
- options.reviewRetryKey ?? digest(binding)
952
- ])
953
- ).digest("hex") : void 0;
954
- const evidenceKey = retryKey === void 0 ? void 0 : `${retryKey}/${options.reviewRetryEvidenceKey ?? ""}`;
955
- const now = this.options.monotonicNow ?? (() => performance.now());
956
- const cachedFailure = retryKey === void 0 || evidenceKey === void 0 ? void 0 : this.reviewFailure(retryKey, now()) ?? this.reviewFailure(evidenceKey, now());
957
- let reviewReason;
958
- const reviewResult = cachedFailure ?? (route.kind === "review" ? await this.review(
959
- request,
960
- retryKey ?? receiptBinding ?? digest(binding),
961
- facts.reviewCategory,
962
- version,
963
- requestSignal,
964
- interactive ? (reason) => {
965
- reviewReason = reason;
966
- } : void 0
967
- ) : route.kind === "defer" ? failure(
968
- "review_evidence_unavailable",
969
- options.reviewCoverageDiagnostic ?? reviewDiagnostic("review_evidence_unavailable")
970
- ) : { fallback: "ask_user", missing: "unspecified" });
971
- const outcome = facts.autoReview && route.kind === "review" && typeof reviewResult === "object" && reviewResult.fallback === "ask_user" && reviewResult.missing === "unspecified" ? failure("review_inconclusive") : reviewResult;
972
- const decision = typeof outcome === "object" ? outcome.fallback : outcome;
973
- const failureDetails = typeof outcome === "object" && outcome.fallback !== "ask_user" ? outcome : void 0;
974
- const diagnostic = failureDetails?.diagnostic;
975
- const confirmationCause = failureDetails?.oneTimeConfirmation;
976
- const manualPrivacyFallback = confirmationCause === "private_evidence";
977
- const manualInconclusiveFallback = facts.autoReview === true && confirmationCause === "inconclusive";
978
- const oneTimeConfirmation = manualPrivacyFallback || manualInconclusiveFallback;
979
- if (confirmationCause === "inconclusive" || decision === "allow_once" || decision === "deny" || diagnostic && decision !== "review_evidence_unavailable" && diagnostic.code !== "review_preparation_failed")
980
- actor = "review";
981
- checkCurrent(route.kind === "review");
982
- if (interactive && diagnostic && (diagnostic.code === "review_cancelled" || diagnostic.code === "review_authority_changed")) {
983
- return expire("approval_expired", diagnostic);
984
- }
985
- if (decision === "deny" && !interactive) {
986
- audit("denied", "review_denied");
987
- return facts.autoReview ? rejectLocalReview("deny") : reject("review_denied");
988
- }
989
- if (retryKey !== void 0 && evidenceKey !== void 0 && outcome !== "allow_once" && outcome !== "deny" && !manualPrivacyFallback) {
990
- if (!cachedFailure) {
991
- if (this.localReviewFailures.size >= 256) {
992
- const oldest = this.localReviewFailures.keys().next().value;
993
- if (oldest !== void 0) this.localReviewFailures.delete(oldest);
994
- }
995
- const failureKey = decision === "review_unavailable" || decision === "review_not_delegated" ? retryKey : evidenceKey;
996
- this.localReviewFailures.set(failureKey, {
997
- outcome,
998
- ...decision === "review_unavailable" ? { expiresAt: now() + 15e3 } : {}
999
- });
975
+ requestSignal,
976
+ interactive ? (reason) => {
977
+ reviewReason = reason;
978
+ } : void 0
979
+ ) : route.kind === "defer" ? failure(
980
+ "review_evidence_unavailable",
981
+ options.reviewCoverageDiagnostic ?? reviewDiagnostic("review_evidence_unavailable")
982
+ ) : { fallback: "ask_user", missing: "unspecified" });
983
+ const outcome = facts.autoReview && route.kind === "review" && typeof reviewResult === "object" && reviewResult.fallback === "ask_user" && reviewResult.missing === "unspecified" ? failure("review_inconclusive") : reviewResult;
984
+ const decision = typeof outcome === "object" ? outcome.fallback : outcome;
985
+ const failureDetails = typeof outcome === "object" && outcome.fallback !== "ask_user" ? outcome : void 0;
986
+ const diagnostic = failureDetails?.diagnostic;
987
+ const confirmationCause = failureDetails?.oneTimeConfirmation;
988
+ const manualPrivacyFallback = confirmationCause === "private_evidence";
989
+ const manualInconclusiveFallback = facts.autoReview === true && confirmationCause === "inconclusive";
990
+ const oneTimeConfirmation = manualPrivacyFallback || manualInconclusiveFallback;
991
+ if (confirmationCause === "inconclusive" || decision === "allow_once" || decision === "deny" || diagnostic && decision !== "review_evidence_unavailable" && diagnostic.code !== "review_preparation_failed")
992
+ actor = "review";
993
+ checkCurrent(route.kind === "review");
994
+ if (interactive && diagnostic && (diagnostic.code === "review_cancelled" || diagnostic.code === "review_authority_changed")) {
995
+ return expire("approval_expired", diagnostic);
1000
996
  }
1001
- if (!manualInconclusiveFallback && !interactive) {
1002
- audit(
1003
- "denied",
1004
- decision === "ask_user" ? "review_user_decision_required" : decision,
1005
- void 0,
1006
- diagnostic
1007
- );
1008
- return outcome.fallback === "ask_user" ? rejectLocalReview("ask_user", outcome.missing) : rejectLocalReview(outcome.fallback, void 0, diagnostic);
997
+ if (decision === "deny" && !interactive) {
998
+ audit("denied", "review_denied");
999
+ return facts.autoReview ? rejectLocalReview("deny") : reject("review_denied");
1009
1000
  }
1010
- }
1011
- if (decision !== "allow_once") {
1012
- if (decision === "deny") audit("review_failed", "review_denied");
1013
- else if (diagnostic)
1014
- audit("review_failed", decision, void 0, diagnostic);
1015
- const confirm = this.options.confirmation?.confirm;
1016
- if (!confirm || this.options.confirmation?.available?.() === false) {
1017
- if (manualInconclusiveFallback) {
1018
- audit("denied", "review_inconclusive");
1019
- return reject(
1020
- `${agentReviewReasons.review_inconclusive} Interactive confirmation is unavailable on this connection.`
1021
- );
1001
+ if (retryKey !== void 0 && evidenceKey !== void 0 && outcome !== "allow_once" && outcome !== "deny" && !manualPrivacyFallback) {
1002
+ if (!cachedFailure) {
1003
+ if (this.localReviewFailures.size >= 256) {
1004
+ const oldest = this.localReviewFailures.keys().next().value;
1005
+ if (oldest !== void 0)
1006
+ this.localReviewFailures.delete(oldest);
1007
+ }
1008
+ const failureKey = decision === "review_unavailable" || decision === "review_not_delegated" ? retryKey : evidenceKey;
1009
+ this.localReviewFailures.set(failureKey, {
1010
+ outcome,
1011
+ ...decision === "review_unavailable" ? { expiresAt: now() + 15e3 } : {}
1012
+ });
1022
1013
  }
1023
- if (manualPrivacyFallback)
1024
- return rejectLocalReview(
1025
- "review_evidence_unavailable",
1014
+ if (!manualInconclusiveFallback && !interactive) {
1015
+ audit(
1016
+ "denied",
1017
+ decision === "ask_user" ? "review_user_decision_required" : decision,
1026
1018
  void 0,
1027
1019
  diagnostic
1028
1020
  );
1029
- return reject(
1030
- diagnostic ? `confirmation_required: ${reviewDiagnosticText(diagnostic)}` : "confirmation_required"
1031
- );
1021
+ return outcome.fallback === "ask_user" ? rejectLocalReview("ask_user", outcome.missing) : rejectLocalReview(outcome.fallback, void 0, diagnostic);
1022
+ }
1032
1023
  }
1033
- if (manualInconclusiveFallback) audit("review_failed", decision);
1034
- actor = "user";
1035
- const withheld = manualPrivacyFallback || !!(interactive && diagnostic && isReviewPrivacyFailure(diagnostic.code));
1036
- const preview = withheld && diagnostic ? this.options.review?.privacyConfirmationPreview?.(
1037
- options.preview(),
1038
- request,
1039
- diagnostic
1040
- ) ?? "Command details are hidden here. Inspect the original shell proposal before choosing Run once." : options.preview();
1041
- const checkRouteCurrent = () => {
1042
- checkCurrent();
1043
- if (JSON.stringify(routeApproval(options.evaluate())) !== JSON.stringify(route))
1044
- return expire("authority_changed");
1045
- };
1046
- const ask = async (requestId, choices2, details = {}) => {
1047
- checkRouteCurrent();
1048
- const deadline = (this.options.deadline ?? AbortSignal.timeout)(
1049
- 12e4
1050
- );
1051
- const signal = requestSignal ? AbortSignal.any([deadline, requestSignal]) : deadline;
1052
- const reply = responseRecord(
1053
- await awaitAbortable(
1054
- signal,
1055
- () => confirm(
1056
- {
1057
- requestId,
1058
- subject: request.subject,
1059
- origin: request.origin,
1060
- preview,
1061
- route,
1062
- ...route.kind === "review" || route.kind === "defer" ? {
1063
- reviewFallback: decision === "deny" ? "review_denied" : decision,
1064
- ...reviewReason ? { reviewReason } : {},
1065
- ...diagnostic ? { reviewDiagnostic: diagnostic } : {},
1066
- ...manualPrivacyFallback ? { reviewWithheldForPrivacy: true } : {}
1067
- } : {},
1068
- expiresAt: Date.now() + 12e4,
1069
- choices: choices2,
1070
- ...options.escalation === "unsandboxed" ? {
1071
- escalation: "unsandboxed",
1072
- ...options.protectedPathsEnforced === false ? { protectedPathsEnforced: false } : {}
1073
- } : {},
1074
- ...details
1075
- },
1076
- signal
1077
- )
1078
- )
1079
- );
1080
- if (signal.aborted) return expire("approval_expired");
1081
- checkCurrent();
1082
- if (reply?.requestId !== requestId || !choices2.includes(reply.choice))
1083
- return reject("confirmation_required");
1084
- return reply.choice;
1085
- };
1086
- let choice2;
1087
- if (interactive) {
1088
- const propose = !withheld && !facts.opaque && !facts.humanOnly ? interactive.propose : void 0;
1089
- const selected = await selectShellAllowance({
1024
+ if (decision !== "allow_once") {
1025
+ if (decision === "deny") audit("review_failed", "review_denied");
1026
+ else if (diagnostic)
1027
+ audit("review_failed", decision, void 0, diagnostic);
1028
+ const confirm = this.options.confirmation?.confirm;
1029
+ if (!confirm || this.options.confirmation?.available?.() === false) {
1030
+ if (manualInconclusiveFallback) {
1031
+ audit("denied", "review_inconclusive");
1032
+ return reject(
1033
+ `${agentReviewReasons.review_inconclusive} Interactive confirmation is unavailable on this connection.`
1034
+ );
1035
+ }
1036
+ if (manualPrivacyFallback)
1037
+ return rejectLocalReview(
1038
+ "review_evidence_unavailable",
1039
+ void 0,
1040
+ diagnostic
1041
+ );
1042
+ return reject(
1043
+ diagnostic ? `confirmation_required: ${reviewDiagnosticText(diagnostic)}` : "confirmation_required"
1044
+ );
1045
+ }
1046
+ if (manualInconclusiveFallback) audit("review_failed", decision);
1047
+ actor = "user";
1048
+ const withheld = manualPrivacyFallback || !!(interactive && diagnostic && isReviewPrivacyFailure(diagnostic.code));
1049
+ const preview = withheld && diagnostic ? this.options.review?.privacyConfirmationPreview?.(
1050
+ options.preview(),
1090
1051
  request,
1091
- propose,
1092
- ask,
1093
- checkCurrent: checkRouteCurrent,
1094
- signal: requestSignal
1095
- });
1096
- choice2 = selected.choice;
1097
- save = selected.proposal;
1098
- } else {
1099
- const choices2 = [
1100
- "allow_once",
1101
- "deny_continue",
1102
- "deny_stop"
1103
- ];
1104
- if (!oneTimeConfirmation && save && !facts.opaque && !facts.humanOnly) {
1105
- if ("commit" in save) choices2.push("save_session");
1106
- choices2.push("save_project");
1052
+ diagnostic
1053
+ ) ?? "Command details are hidden here. Inspect the original shell proposal before choosing Run once." : options.preview();
1054
+ const checkRouteCurrent = () => {
1055
+ checkCurrent();
1056
+ if (JSON.stringify(routeApproval(options.evaluate())) !== JSON.stringify(route))
1057
+ return expire("authority_changed");
1058
+ };
1059
+ const ask = async (requestId, choices2, details = {}) => {
1060
+ checkRouteCurrent();
1061
+ const deadline = (this.options.deadline ?? AbortSignal.timeout)(
1062
+ 12e4
1063
+ );
1064
+ const signal = requestSignal ? AbortSignal.any([deadline, requestSignal]) : deadline;
1065
+ const reply = responseRecord(
1066
+ await awaitAbortable(
1067
+ signal,
1068
+ () => confirm(
1069
+ {
1070
+ requestId,
1071
+ subject: request.subject,
1072
+ origin: request.origin,
1073
+ preview,
1074
+ route,
1075
+ ...route.kind === "review" || route.kind === "defer" ? {
1076
+ reviewFallback: decision === "deny" ? "review_denied" : decision,
1077
+ ...reviewReason ? { reviewReason } : {},
1078
+ ...diagnostic ? { reviewDiagnostic: diagnostic } : {},
1079
+ ...manualPrivacyFallback ? { reviewWithheldForPrivacy: true } : {}
1080
+ } : {},
1081
+ expiresAt: Date.now() + 12e4,
1082
+ choices: choices2,
1083
+ ...options.escalation === "unsandboxed" ? {
1084
+ escalation: "unsandboxed",
1085
+ ...options.protectedPathsEnforced === false ? { protectedPathsEnforced: false } : {}
1086
+ } : {},
1087
+ ...details
1088
+ },
1089
+ signal
1090
+ )
1091
+ )
1092
+ );
1093
+ if (signal.aborted) return expire("approval_expired");
1094
+ checkCurrent();
1095
+ if (reply?.requestId !== requestId || !choices2.includes(reply.choice))
1096
+ return reject("confirmation_required");
1097
+ return reply.choice;
1098
+ };
1099
+ let choice2;
1100
+ if (interactive) {
1101
+ const propose = !withheld && !facts.opaque && !facts.humanOnly ? interactive.propose : void 0;
1102
+ const selected = await selectShellAllowance({
1103
+ request,
1104
+ propose,
1105
+ ask,
1106
+ checkCurrent: checkRouteCurrent,
1107
+ signal: requestSignal
1108
+ });
1109
+ choice2 = selected.choice;
1110
+ save = selected.proposal;
1111
+ } else {
1112
+ const choices2 = [
1113
+ "allow_once",
1114
+ "deny_continue",
1115
+ "deny_stop"
1116
+ ];
1117
+ if (!oneTimeConfirmation && save && !facts.opaque && !facts.humanOnly) {
1118
+ if ("commit" in save) choices2.push("save_session");
1119
+ choices2.push("save_project");
1120
+ }
1121
+ if (!oneTimeConfirmation && options.grantSession)
1122
+ choices2.push("grant_session");
1123
+ choice2 = await ask(
1124
+ id2,
1125
+ choices2,
1126
+ !oneTimeConfirmation ? {
1127
+ saveDescription: save?.description,
1128
+ grantDescription: options.grantSession?.description
1129
+ } : {}
1130
+ );
1131
+ }
1132
+ if (choice2 === "grant_session") sessionGrant = options.grantSession;
1133
+ if (choice2 === "save_session") saveScope = "session";
1134
+ if (choice2 === "save_project") saveScope = "project";
1135
+ if (choice2 === "deny_continue" || choice2 === "deny_stop") {
1136
+ audit("denied", "user_denied");
1137
+ return reject("user_denied", choice2 === "deny_stop");
1107
1138
  }
1108
- if (!oneTimeConfirmation && options.grantSession)
1109
- choices2.push("grant_session");
1110
- choice2 = await ask(
1111
- id2,
1112
- choices2,
1113
- !oneTimeConfirmation ? {
1114
- saveDescription: save?.description,
1115
- grantDescription: options.grantSession?.description
1116
- } : {}
1117
- );
1118
1139
  }
1119
- if (choice2 === "grant_session") sessionGrant = options.grantSession;
1120
- if (choice2 === "save_session") saveScope = "session";
1121
- if (choice2 === "save_project") saveScope = "project";
1122
- if (choice2 === "deny_continue" || choice2 === "deny_stop") {
1123
- audit("denied", "user_denied");
1124
- return reject("user_denied", choice2 === "deny_stop");
1140
+ checkCurrent(actor === "review");
1141
+ if (JSON.stringify(routeApproval(options.evaluate())) !== JSON.stringify(route)) {
1142
+ return expire(
1143
+ "authority_changed",
1144
+ actor === "review" ? reviewDiagnostic("review_authority_changed") : void 0
1145
+ );
1125
1146
  }
1126
1147
  }
1127
- checkCurrent(actor === "review");
1128
- if (JSON.stringify(routeApproval(options.evaluate())) !== JSON.stringify(route)) {
1129
- return expire(
1130
- "authority_changed",
1131
- actor === "review" ? reviewDiagnostic("review_authority_changed") : void 0
1132
- );
1133
- }
1134
- }
1135
- sessionGrant?.commit();
1136
- if (saveScope === "project" && save && "rememberProject" in save) {
1137
- try {
1138
- await save.rememberProject();
1139
- } catch (error) {
1140
- if (error instanceof Error && error.message === "approval_expired")
1141
- return expire("approval_expired");
1142
- audit("save_failed", "project_tool_rule_save_failed");
1143
- return reject(
1144
- "project_tool_rule_save_failed: Could not save this workspace permission to the personal policy store. The tool did not run."
1145
- );
1146
- }
1147
- }
1148
- let consumed = false;
1149
- const consume = (details) => {
1150
- if (consumed) reject("approval_already_consumed");
1151
- checkCurrent(actor === "review");
1152
- if (actor === "review" && (this.options.review?.stillApproved?.(request) === false || this.options.review?.reviewVersion && this.options.review.reviewVersion(request) !== version)) {
1153
- const diagnostic = reviewDiagnostic("review_authority_changed");
1154
- audit("expired", "review_authority_changed", void 0, diagnostic);
1155
- return reject(
1156
- `approval_expired: ${reviewDiagnosticText(diagnostic)}`
1157
- );
1158
- }
1159
- consumed = true;
1160
- if (saveScope && save && "commit" in save) {
1148
+ sessionGrant?.commit();
1149
+ if (saveScope === "project" && save && "rememberProject" in save) {
1161
1150
  try {
1162
- save.commit(saveScope);
1163
- } catch {
1164
- audit("save_failed", "launch_rule_save_failed");
1151
+ await save.rememberProject();
1152
+ } catch (error) {
1153
+ if (error instanceof Error && error.message === "approval_expired")
1154
+ return expire("approval_expired");
1155
+ audit("save_failed", "project_tool_rule_save_failed");
1156
+ return reject(
1157
+ "project_tool_rule_save_failed: Could not save this workspace permission to the personal policy store. The tool did not run."
1158
+ );
1165
1159
  }
1166
1160
  }
1167
- audit("dispatch", route.reason, details?.taskId);
1168
- };
1169
- if (!options.deferConsumption) consume();
1170
- return options.execute(consume, saveScope);
1161
+ let consumed = false;
1162
+ const consume = (details) => {
1163
+ if (consumed) reject("approval_already_consumed");
1164
+ checkCurrent(actor === "review");
1165
+ if (actor === "review" && (this.options.review?.stillApproved?.(request) === false || this.options.review?.reviewVersion && this.options.review.reviewVersion(request) !== version)) {
1166
+ const diagnostic = reviewDiagnostic("review_authority_changed");
1167
+ audit("expired", "review_authority_changed", void 0, diagnostic);
1168
+ return reject(
1169
+ `approval_expired: ${reviewDiagnosticText(diagnostic)}`
1170
+ );
1171
+ }
1172
+ consumed = true;
1173
+ if (saveScope && save && "commit" in save) {
1174
+ try {
1175
+ save.commit(saveScope);
1176
+ } catch {
1177
+ audit("save_failed", "launch_rule_save_failed");
1178
+ }
1179
+ }
1180
+ audit("dispatch", route.reason, details?.taskId);
1181
+ };
1182
+ if (!options.deferConsumption) consume();
1183
+ recordApprovalWait();
1184
+ return options.execute(consume, saveScope);
1185
+ } finally {
1186
+ recordApprovalWait();
1187
+ }
1171
1188
  };
1172
1189
  return receiptBinding !== void 0 ? this.requests.run(scope, id2, receiptBinding, dispatch) : Promise.resolve().then(dispatch);
1173
1190
  }
@@ -7036,6 +7053,7 @@ MCP environment keys: ${serviceLaunch.names.join(", ")}` : ""}`,
7036
7053
  } : {},
7037
7054
  ...confirmationOptions,
7038
7055
  deferConsumption: true,
7056
+ ...input.onApprovalWaitMs ? { onApprovalWaitMs: input.onApprovalWaitMs } : {},
7039
7057
  execute: (consume, saveScope) => execute((taskId) => {
7040
7058
  const boundLaunch = candidate && (saveScope || reliedOnRule);
7041
7059
  if (boundLaunch && backend.supportsExactLaunchBinding?.(candidate, protection) !== true)
@@ -7799,25 +7817,6 @@ var toTrimmed = (value) => {
7799
7817
  const trimmed = value.trim();
7800
7818
  return trimmed.length > 0 ? trimmed : void 0;
7801
7819
  };
7802
- var parseBoolean = (value) => {
7803
- const normalized = toTrimmed(value)?.toLowerCase();
7804
- if (!normalized) return void 0;
7805
- if (normalized === "1" || normalized === "true") return true;
7806
- if (normalized === "0" || normalized === "false") return false;
7807
- return void 0;
7808
- };
7809
- var parsePositiveInt = (value) => {
7810
- const normalized = toTrimmed(value);
7811
- if (!normalized) return void 0;
7812
- const parsed = Number.parseInt(normalized, 10);
7813
- return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0;
7814
- };
7815
- var parseMarkers = (value) => {
7816
- const normalized = toTrimmed(value);
7817
- if (!normalized) return void 0;
7818
- const markers = normalized.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
7819
- return markers.length > 0 ? markers : void 0;
7820
- };
7821
7820
  var exists = async (targetPath) => {
7822
7821
  try {
7823
7822
  await fs.access(targetPath);
@@ -7888,37 +7887,12 @@ var findRootByMarkers = async (workingDir, markers, stopAtFsRoot, reader) => {
7888
7887
  }
7889
7888
  };
7890
7889
  var mergeConfig = (config, env = process.env) => {
7891
- const envConfig = AgentsConfigSchema.parse({
7892
- enabled: parseBoolean(env.CODELIA_AGENTS_ENABLED),
7893
- root: {
7894
- projectRootOverride: toTrimmed(env.CODELIA_AGENTS_ROOT),
7895
- markers: parseMarkers(env.CODELIA_AGENTS_MARKERS)
7896
- },
7897
- initial: {
7898
- maxFiles: parsePositiveInt(env.CODELIA_AGENTS_INITIAL_MAX_FILES),
7899
- maxBytes: parsePositiveInt(env.CODELIA_AGENTS_INITIAL_MAX_BYTES)
7900
- },
7901
- resolver: {
7902
- enabled: parseBoolean(env.CODELIA_AGENTS_RESOLVER_ENABLED),
7903
- maxFilesPerResolve: parsePositiveInt(
7904
- env.CODELIA_AGENTS_MAX_FILES_PER_RESOLVE
7905
- )
7906
- }
7907
- });
7890
+ const rootOverride = toTrimmed(env.CODELIA_AGENTS_ROOT);
7908
7891
  const merged = AgentsConfigSchema.parse({
7909
7892
  ...config ?? {},
7910
- ...envConfig,
7911
7893
  root: {
7912
7894
  ...config?.root ?? {},
7913
- ...envConfig.root ?? {}
7914
- },
7915
- initial: {
7916
- ...config?.initial ?? {},
7917
- ...envConfig.initial ?? {}
7918
- },
7919
- resolver: {
7920
- ...config?.resolver ?? {},
7921
- ...envConfig.resolver ?? {}
7895
+ ...rootOverride ? { projectRootOverride: rootOverride } : {}
7922
7896
  }
7923
7897
  });
7924
7898
  return {
@@ -10163,10 +10137,7 @@ var HTML_SUCCESS = "<!doctype html><html><head><title>codelia - MCP authorizatio
10163
10137
  var HTML_ERROR = (message) => `<!doctype html><html><head><title>codelia - MCP authorization failed</title></head><body><h2>Authorization failed</h2><pre>${message}</pre></body></html>`;
10164
10138
  var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10165
10139
  var oauthPort = () => readPositiveIntEnv("CODELIA_MCP_OAUTH_PORT", DEFAULT_MCP_OAUTH_PORT);
10166
- var oauthWaitTimeoutMs = () => readPositiveIntEnv(
10167
- "CODELIA_MCP_OAUTH_TIMEOUT_MS",
10168
- DEFAULT_MCP_OAUTH_WAIT_TIMEOUT_MS
10169
- );
10140
+ var oauthWaitTimeoutMs = () => DEFAULT_MCP_OAUTH_WAIT_TIMEOUT_MS;
10170
10141
  var buildAuthorizeUrl = (authorizationUrl, redirectUri, clientId, pkce, state, scope, resource) => {
10171
10142
  const url = new URL(authorizationUrl);
10172
10143
  url.searchParams.set("response_type", "code");
@@ -10581,6 +10552,7 @@ var withOpenRouterDynamicModel = (registry, llm, entry) => {
10581
10552
  ...contextWindow ? { contextWindow } : {},
10582
10553
  ...maxInputTokens ? { maxInputTokens } : {},
10583
10554
  ...maxOutputTokens ? { maxOutputTokens } : {},
10555
+ ...entry.cost ? { cost: entry.cost } : {},
10584
10556
  ...entry.capabilities?.supportsVision !== void 0 ? { supportsVision: entry.capabilities.supportsVision } : {},
10585
10557
  ...entry.capabilities?.supportsTools !== void 0 ? { supportsTools: entry.capabilities.supportsTools } : {}
10586
10558
  }
@@ -12042,7 +12014,8 @@ var createRuntimeToolApproval = ({
12042
12014
  ...workspaceGrant ? { grantSession: workspaceGrant } : {},
12043
12015
  signal: state.approvalSignal(ctx.signal),
12044
12016
  execute,
12045
- deferConsumption: files?.deferConsumption
12017
+ deferConsumption: files?.deferConsumption,
12018
+ ...ctx.recordApprovalWaitMs ? { onApprovalWaitMs: ctx.recordApprovalWaitMs } : {}
12046
12019
  });
12047
12020
  };
12048
12021
  const authorize = async (origin, call, raw, ctx) => {
@@ -12314,12 +12287,6 @@ var toTrimmed2 = (value) => {
12314
12287
  const trimmed = value.trim();
12315
12288
  return trimmed ? trimmed : void 0;
12316
12289
  };
12317
- var parseMarkers2 = (value) => {
12318
- const normalized = toTrimmed2(value);
12319
- if (!normalized) return void 0;
12320
- const markers = normalized.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
12321
- return markers.length > 0 ? markers : void 0;
12322
- };
12323
12290
  var exists2 = async (targetPath) => {
12324
12291
  try {
12325
12292
  await fs3.access(targetPath);
@@ -12418,7 +12385,7 @@ var SkillsResolver = class _SkillsResolver {
12418
12385
  const env = options.env ?? process.env;
12419
12386
  const workingDir = path21.resolve(options.workingDir);
12420
12387
  const rootOverride = toTrimmed2(env.CODELIA_AGENTS_ROOT);
12421
- const markers = parseMarkers2(env.CODELIA_AGENTS_MARKERS) ?? DEFAULT_MARKERS2;
12388
+ const markers = options.markers?.length ? options.markers : DEFAULT_MARKERS2;
12422
12389
  const rootDir = rootOverride ? path21.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers, options.reader);
12423
12390
  const homeDir = toTrimmed2(env.HOME) ?? os3.homedir();
12424
12391
  const userSkillsDir = path21.join(path21.resolve(homeDir), ".agents", "skills");
@@ -13335,6 +13302,12 @@ var AgentTreeCoordinator = class {
13335
13302
  isAvailable() {
13336
13303
  return this.factory.isAvailable();
13337
13304
  }
13305
+ getPerfStats() {
13306
+ return {
13307
+ active: this.active.size,
13308
+ maxConcurrent: this.parent?.subagent?.max_concurrent ?? DEFAULT_MAX_CONCURRENT
13309
+ };
13310
+ }
13338
13311
  serialize(fn) {
13339
13312
  const next = this.queue.then(fn, fn);
13340
13313
  this.queue = next.then(
@@ -14799,23 +14772,8 @@ import { promises as fs7 } from "fs";
14799
14772
  import { defineTool as defineTool10 } from "@codelia/core";
14800
14773
  import { z as z28 } from "zod";
14801
14774
  var DEFAULT_READ_LIMIT = 2e3;
14802
- var DEFAULT_MAX_LINE_LENGTH = 1e3;
14803
- var DEFAULT_MAX_BYTES = 64 * 1024;
14804
- var parsePositiveIntEnv = (key, fallback) => {
14805
- const raw = process.env[key];
14806
- if (!raw) return fallback;
14807
- const parsed = Number.parseInt(raw, 10);
14808
- if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
14809
- return parsed;
14810
- };
14811
- var MAX_LINE_LENGTH = parsePositiveIntEnv(
14812
- "CODELIA_READ_MAX_LINE_LENGTH",
14813
- DEFAULT_MAX_LINE_LENGTH
14814
- );
14815
- var MAX_BYTES = parsePositiveIntEnv(
14816
- "CODELIA_READ_MAX_BYTES",
14817
- DEFAULT_MAX_BYTES
14818
- );
14775
+ var MAX_LINE_LENGTH = 1e3;
14776
+ var MAX_BYTES = 64 * 1024;
14819
14777
  var clipLongLine = (line) => {
14820
14778
  if (line.length <= MAX_LINE_LENGTH) {
14821
14779
  return line;
@@ -15600,7 +15558,8 @@ var createShellTool = (sandboxKey, options = {}) => {
15600
15558
  origin: getOperatorContext(ctx) ? "operator" : "parent_agent",
15601
15559
  signal: ctx.signal,
15602
15560
  owner: sessionContext?.sessionId ?? void 0,
15603
- reviewHistory: input.approval_context
15561
+ reviewHistory: input.approval_context,
15562
+ ...ctx.recordApprovalWaitMs ? { onApprovalWaitMs: ctx.recordApprovalWaitMs } : {}
15604
15563
  },
15605
15564
  async (admission) => {
15606
15565
  try {
@@ -16358,7 +16317,7 @@ import { promises as fs9 } from "fs";
16358
16317
  import path25 from "path";
16359
16318
  import { defineTool as defineTool18 } from "@codelia/core";
16360
16319
  import { z as z36 } from "zod";
16361
- var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
16320
+ var DEFAULT_MAX_BYTES = 5 * 1024 * 1024;
16362
16321
  var MAX_MAX_BYTES = 10 * 1024 * 1024;
16363
16322
  var MIME_BY_EXTENSION = {
16364
16323
  ".png": "image/png",
@@ -16429,7 +16388,7 @@ var createViewImageTool = (sandboxKey) => defineTool18({
16429
16388
  if (stat2.isDirectory()) {
16430
16389
  return `Path is a directory: ${input.file_path}`;
16431
16390
  }
16432
- const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES2;
16391
+ const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES;
16433
16392
  if (stat2.size > maxBytes) {
16434
16393
  return `Image too large: ${input.file_path} (${stat2.size} bytes > ${maxBytes} bytes)`;
16435
16394
  }
@@ -16466,7 +16425,7 @@ import { defineTool as defineTool19 } from "@codelia/core";
16466
16425
  import { z as z37 } from "zod";
16467
16426
  var DEFAULT_TIMEOUT_MS3 = 1e4;
16468
16427
  var MAX_TIMEOUT_MS = 3e4;
16469
- var DEFAULT_MAX_BYTES3 = 2e5;
16428
+ var DEFAULT_MAX_BYTES2 = 2e5;
16470
16429
  var MAX_MAX_BYTES2 = 1e6;
16471
16430
  var TLS_ERROR_CODES = /* @__PURE__ */ new Set([
16472
16431
  "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
@@ -16726,7 +16685,7 @@ var createWebfetchTool = () => defineTool19({
16726
16685
  `Fetch timeout in ms. Default ${DEFAULT_TIMEOUT_MS3}, Max ${MAX_TIMEOUT_MS}.`
16727
16686
  ),
16728
16687
  max_bytes: z37.number().int().positive().max(MAX_MAX_BYTES2).optional().describe(
16729
- `Max response bytes to keep. Default ${DEFAULT_MAX_BYTES3}, Max ${MAX_MAX_BYTES2}.`
16688
+ `Max response bytes to keep. Default ${DEFAULT_MAX_BYTES2}, Max ${MAX_MAX_BYTES2}.`
16730
16689
  )
16731
16690
  }),
16732
16691
  execute: async (input) => {
@@ -16740,7 +16699,7 @@ var createWebfetchTool = () => defineTool19({
16740
16699
  return `Unsupported URL protocol: ${url.protocol}`;
16741
16700
  }
16742
16701
  const timeoutMs = input.timeout_ms ?? DEFAULT_TIMEOUT_MS3;
16743
- const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES3;
16702
+ const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES2;
16744
16703
  const outputFormat = input.output_format ?? "markdown";
16745
16704
  const startedAt = Date.now();
16746
16705
  const controller = new AbortController();
@@ -17060,11 +17019,6 @@ var createSubagentTaskTools = (coordinator, ownerSession, spawn4) => {
17060
17019
  };
17061
17020
 
17062
17021
  // src/agent-factory.ts
17063
- var envTruthy = (value) => {
17064
- if (!value) return false;
17065
- const normalized = value.trim().toLowerCase();
17066
- return normalized === "1" || normalized === "true";
17067
- };
17068
17022
  var sleep = (ms) => new Promise((resolve) => {
17069
17023
  setTimeout(resolve, ms);
17070
17024
  });
@@ -17080,13 +17034,16 @@ var waitForUiConfirmSupport = async (state, timeoutMs = 5e3, signal) => {
17080
17034
  return !signal?.aborted && !!state.uiCapabilities?.supports_confirm;
17081
17035
  };
17082
17036
  var requestMcpOAuthTokens2 = async (state, serverId, oauth, errorMessage, signal) => {
17037
+ const configuredBrowser = state.effectiveEnvironment.config.source === "disabled" ? void 0 : await resolveAuthOAuthBrowser(
17038
+ state.runtimeWorkingDir ?? void 0
17039
+ ).catch(() => void 0);
17083
17040
  const gateway = {
17084
17041
  runId: state.activeRunId ?? void 0,
17085
17042
  supportsPrompt: !!state.uiCapabilities?.supports_prompt,
17086
17043
  waitForConfirmSupport: () => waitForUiConfirmSupport(state, 5e3, signal),
17087
17044
  confirm: (params) => requestUiConfirm(state, params, signal),
17088
17045
  prompt: (params) => requestUiPrompt(state, params, signal),
17089
- shouldAutoOpenBrowser: shouldAutoOpenOAuthBrowser,
17046
+ shouldAutoOpenBrowser: () => shouldAutoOpenOAuthBrowser(configuredBrowser),
17090
17047
  openBrowser,
17091
17048
  log
17092
17049
  };
@@ -17150,13 +17107,28 @@ var createAgentFactory = (state, options = {}) => {
17150
17107
  sandboxKey = createSandboxKey(ctx);
17151
17108
  }
17152
17109
  const reader = workspaceRoot && (environment.context.projectInstructions === "from-workspace" || environment.context.skills === "from-config") ? await runtimeResourceReader(state, workspaceRoot, ctx) : void 0;
17110
+ const initPhases = [];
17111
+ const measurePhase = async (name2, fn) => {
17112
+ const started = performance.now();
17113
+ try {
17114
+ return await fn();
17115
+ } finally {
17116
+ initPhases.push({
17117
+ name: name2,
17118
+ duration_ms: Math.max(0, Math.round(performance.now() - started))
17119
+ });
17120
+ }
17121
+ };
17153
17122
  if (environment.context.projectInstructions === "from-workspace" && workspaceRoot) {
17154
- agentsResolver = state.agentsResolver ?? await AgentsResolver.create(
17155
- workspaceRoot,
17156
- void 0,
17157
- void 0,
17158
- reader
17159
- );
17123
+ agentsResolver = await measurePhase("agents_resolver", async () => {
17124
+ const agentsEnabled = environment.config.source === "disabled" ? true : await resolveAgentsEnabled(workspaceRoot).catch(() => true);
17125
+ return state.agentsResolver ?? await AgentsResolver.create(
17126
+ workspaceRoot,
17127
+ { enabled: agentsEnabled },
17128
+ void 0,
17129
+ reader
17130
+ );
17131
+ });
17160
17132
  state.agentsResolver = agentsResolver;
17161
17133
  }
17162
17134
  if (environment.context.skills === "from-config" && workspaceRoot) {
@@ -17170,11 +17142,14 @@ var createAgentFactory = (state, options = {}) => {
17170
17142
  const message = error instanceof Error ? error.message : String(error);
17171
17143
  throw new Error(message);
17172
17144
  }
17173
- skillsResolver = state.skillsResolver ?? await SkillsResolver.create({
17174
- workingDir: workspaceRoot,
17175
- config: skillsConfig,
17176
- reader
17177
- });
17145
+ skillsResolver = await measurePhase(
17146
+ "skills_resolver",
17147
+ async () => state.skillsResolver ?? await SkillsResolver.create({
17148
+ workingDir: workspaceRoot,
17149
+ config: skillsConfig,
17150
+ reader
17151
+ })
17152
+ );
17178
17153
  state.skillsResolver = skillsResolver;
17179
17154
  state.updateSkillsSnapshot(workspaceRoot, skillsResolver.getSnapshot());
17180
17155
  }
@@ -17233,24 +17208,32 @@ var createAgentFactory = (state, options = {}) => {
17233
17208
  }
17234
17209
  let mcpTools = [];
17235
17210
  if (environment.tools.mcp === "from-config" && options.mcpManager) {
17236
- try {
17237
- mcpTools = await options.mcpManager.getTools({
17238
- onStatus: (message) => {
17239
- log(`mcp: ${message}`);
17240
- },
17241
- requestOAuthTokens: async ({ server_id, oauth, error, signal }) => {
17242
- return requestMcpOAuthTokensWithRunStatus(
17243
- state,
17211
+ mcpTools = await measurePhase("mcp_tools", async () => {
17212
+ try {
17213
+ return await options.mcpManager.getTools({
17214
+ onStatus: (message) => {
17215
+ log(`mcp: ${message}`);
17216
+ },
17217
+ requestOAuthTokens: async ({
17244
17218
  server_id,
17245
17219
  oauth,
17246
17220
  error,
17247
17221
  signal
17248
- );
17249
- }
17250
- });
17251
- } catch (error) {
17252
- log(`failed to load mcp tools: ${String(error)}`);
17253
- }
17222
+ }) => {
17223
+ return requestMcpOAuthTokensWithRunStatus(
17224
+ state,
17225
+ server_id,
17226
+ oauth,
17227
+ error,
17228
+ signal
17229
+ );
17230
+ }
17231
+ });
17232
+ } catch (error) {
17233
+ log(`failed to load mcp tools: ${String(error)}`);
17234
+ return [];
17235
+ }
17236
+ });
17254
17237
  }
17255
17238
  const hostTools = environment.tools.host === "enabled" ? await loadRuntimeHostTools(environment.adapters.toolProviders ?? []) : [];
17256
17239
  const subagentConfig = options.subagents?.isAvailable() && workspaceRoot ? await resolveEnvironmentSubagentConfig(state, workspaceRoot) : void 0;
@@ -17272,13 +17255,16 @@ ${JSON.stringify(subagentConfig)}
17272
17255
  state,
17273
17256
  workspaceRoot
17274
17257
  );
17275
- executionEnvironmentContext = await buildExecutionEnvironmentContext({
17276
- workingDir: workspaceRoot,
17277
- sandboxRoot: ctx.rootDir,
17278
- config: executionEnvironmentConfig,
17279
- hostInfo: describeExecutionEnvironmentHost(state.sandboxMode.value),
17280
- probeOptions: { authorize: authorizeRuntimeShell(state) }
17281
- });
17258
+ executionEnvironmentContext = await measurePhase(
17259
+ "exec_env",
17260
+ () => buildExecutionEnvironmentContext({
17261
+ workingDir: workspaceRoot,
17262
+ sandboxRoot: ctx.rootDir,
17263
+ config: executionEnvironmentConfig,
17264
+ hostInfo: describeExecutionEnvironmentHost(state.sandboxMode.value),
17265
+ probeOptions: { authorize: authorizeRuntimeShell(state) }
17266
+ })
17267
+ );
17282
17268
  }
17283
17269
  state.executionEnvironmentContext = executionEnvironmentContext;
17284
17270
  if (logInitialExecutionEnvironmentDebug(executionEnvironmentContext, {
@@ -17424,12 +17410,12 @@ ${JSON.stringify(subagentConfig)}
17424
17410
  state.currentModelProvider = provider;
17425
17411
  state.currentModelName = resolvedModelName;
17426
17412
  state.currentModelSource = modelConfig.source;
17427
- const modelRegistry = environment.persistence.mode === "runtime" || getResponsesProvider(modelConfig, provider) ? await buildModelRegistry(llm, {
17428
- strict: provider !== "openrouter",
17429
- providers: modelConfig.providers
17430
- }) : buildConfiguredModelRegistry(modelConfig.providers);
17431
- const totalBudgetTrimEnabled = envTruthy(
17432
- process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
17413
+ const modelRegistry = await measurePhase(
17414
+ "model_registry",
17415
+ async () => environment.persistence.mode === "runtime" || getResponsesProvider(modelConfig, provider) ? await buildModelRegistry(llm, {
17416
+ strict: provider !== "openrouter",
17417
+ providers: modelConfig.providers
17418
+ }) : buildConfiguredModelRegistry(modelConfig.providers)
17433
17419
  );
17434
17420
  const builtinTools = /* @__PURE__ */ new Set([...baseLocalTools, ...imageTools]);
17435
17421
  if (localSearchTool && environment.sourcePreset === "tui-local" && !environment.adapters.approvalToolAuthority && !environment.adapters.approvalToolEffect)
@@ -17564,7 +17550,7 @@ Original conversation messages remain available after compaction. When a summary
17564
17550
  systemPrompt: effectiveSystemPrompt,
17565
17551
  modelRegistry: modelRegistry ?? DEFAULT_MODEL_REGISTRY2,
17566
17552
  toolOutputCache: {
17567
- totalBudgetTrim: totalBudgetTrimEnabled
17553
+ totalBudgetTrim: false
17568
17554
  },
17569
17555
  services: {
17570
17556
  toolOutputCacheStore,
@@ -17573,11 +17559,13 @@ Original conversation messages remain available after compaction. When a summary
17573
17559
  }
17574
17560
  });
17575
17561
  state.canReadAttachment = canReadAttachment;
17562
+ state.telemetry.setAgentInitPhases(initPhases);
17576
17563
  state.recordAgentChatRoute(
17577
17564
  agent,
17578
- getResponsesProvider(modelConfig, provider) ? { kind: "named" } : {
17565
+ getResponsesProvider(modelConfig, provider) ? { kind: "named", metered: false } : {
17579
17566
  kind: "builtin",
17580
17567
  provider,
17568
+ metered: providerAuth.method === "api_key",
17581
17569
  apiBase: providerAuth.method === "api_key" ? builtinApiKeyBase(provider) : void 0
17582
17570
  }
17583
17571
  );
@@ -19097,7 +19085,7 @@ var McpManager = class {
19097
19085
 
19098
19086
  // src/rpc/handlers.ts
19099
19087
  import {
19100
- RPC_ERROR_CODE as RPC_ERROR_CODE21
19088
+ RPC_ERROR_CODE as RPC_ERROR_CODE22
19101
19089
  } from "@codelia/protocol";
19102
19090
  import {
19103
19091
  RunEventStoreFactoryImpl,
@@ -20052,6 +20040,25 @@ var CONFIG_KEYS = [
20052
20040
  writeVia: "model.set"
20053
20041
  },
20054
20042
  { key: "tui.theme", type: "string", fallback: null, writeVia: "theme.set" },
20043
+ {
20044
+ key: "tui.color_scheme",
20045
+ type: "enum",
20046
+ enum: ["dark", "light"],
20047
+ fallback: "dark"
20048
+ },
20049
+ {
20050
+ key: "tui.image_protocol",
20051
+ type: "enum",
20052
+ enum: ["halfblocks", "kitty"],
20053
+ fallback: "halfblocks"
20054
+ },
20055
+ {
20056
+ key: "auth.oauth_browser",
20057
+ type: "enum",
20058
+ enum: ["auto", "manual"],
20059
+ fallback: null
20060
+ },
20061
+ { key: "agents.enabled", type: "boolean", fallback: true },
20055
20062
  {
20056
20063
  key: "subagent.max_concurrent",
20057
20064
  type: "integer",
@@ -20304,9 +20311,69 @@ var createConfigHandlers = ({
20304
20311
  return { handleConfigGet, handleConfigSet };
20305
20312
  };
20306
20313
 
20314
+ // src/rpc/telemetry.ts
20315
+ import { RPC_ERROR_CODE as RPC_ERROR_CODE7 } from "@codelia/protocol";
20316
+ var emptyUsage = (state) => ({
20317
+ provider: state.currentModelProvider,
20318
+ model: state.currentModelName,
20319
+ limit_tokens: null,
20320
+ used_tokens: null,
20321
+ input_tokens: null,
20322
+ left_percent: null,
20323
+ basis: "none",
20324
+ breakdown: []
20325
+ });
20326
+ var createTelemetryHandlers = ({
20327
+ state,
20328
+ subagents,
20329
+ log: log2
20330
+ }) => {
20331
+ const handleTelemetryGet = async (id2) => {
20332
+ try {
20333
+ const context = state.agent ? state.agent.getContextUsage() : emptyUsage(state);
20334
+ const mem = process.memoryUsage();
20335
+ const subagentStats = subagents?.getPerfStats() ?? {
20336
+ active: 0,
20337
+ maxConcurrent: 0
20338
+ };
20339
+ const result = {
20340
+ ...state.sessionId ? { session_id: state.sessionId } : {},
20341
+ active_run_id: state.activeRunId,
20342
+ context,
20343
+ session_summary: state.telemetry.getSessionSummary(),
20344
+ run_summary: state.telemetry.getRunSummary(),
20345
+ recent_calls: state.telemetry.getRecentCalls(),
20346
+ recent_tools: state.telemetry.getRecentTools(),
20347
+ runtime: {
20348
+ startup_phases: state.telemetry.getStartupPhases(),
20349
+ agent_init_phases: state.telemetry.getAgentInitPhases(),
20350
+ active_subagents: subagentStats.active,
20351
+ max_concurrent_subagents: subagentStats.maxConcurrent,
20352
+ backpressure_events: getTransportBackpressureEvents(),
20353
+ memory: {
20354
+ rss_bytes: mem.rss,
20355
+ heap_used_bytes: mem.heapUsed,
20356
+ heap_total_bytes: mem.heapTotal,
20357
+ external_bytes: mem.external,
20358
+ array_buffers_bytes: mem.arrayBuffers
20359
+ }
20360
+ }
20361
+ };
20362
+ sendRequestResult("telemetry.get", id2, result);
20363
+ } catch (error) {
20364
+ log2(`telemetry.get failed: ${String(error)}`);
20365
+ sendError(id2, {
20366
+ code: RPC_ERROR_CODE7.RUNTIME_INTERNAL,
20367
+ message: "telemetry unavailable"
20368
+ });
20369
+ }
20370
+ };
20371
+ return { handleTelemetryGet };
20372
+ };
20373
+
20307
20374
  // src/rpc/context.ts
20308
20375
  import {
20309
- RPC_ERROR_CODE as RPC_ERROR_CODE7
20376
+ RPC_ERROR_CODE as RPC_ERROR_CODE8
20310
20377
  } from "@codelia/protocol";
20311
20378
  var createContextHandlers = ({
20312
20379
  state,
@@ -20444,7 +20511,7 @@ var createContextHandlers = ({
20444
20511
  sendRequestResult("context.inspect", id2, result);
20445
20512
  } catch (error) {
20446
20513
  sendError(id2, {
20447
- code: RPC_ERROR_CODE7.RUNTIME_INTERNAL,
20514
+ code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
20448
20515
  message: `context.inspect failed: ${String(error)}`
20449
20516
  });
20450
20517
  }
@@ -20453,8 +20520,8 @@ var createContextHandlers = ({
20453
20520
  };
20454
20521
 
20455
20522
  // src/rpc/context-usage.ts
20456
- import { RPC_ERROR_CODE as RPC_ERROR_CODE8 } from "@codelia/protocol";
20457
- var emptyUsage = (state) => ({
20523
+ import { RPC_ERROR_CODE as RPC_ERROR_CODE9 } from "@codelia/protocol";
20524
+ var emptyUsage2 = (state) => ({
20458
20525
  provider: state.currentModelProvider,
20459
20526
  model: state.currentModelName,
20460
20527
  limit_tokens: null,
@@ -20470,7 +20537,7 @@ var createContextUsageHandlers = ({
20470
20537
  }) => {
20471
20538
  const handleContextUsage = async (id2) => {
20472
20539
  try {
20473
- const usage = state.agent ? state.agent.getContextUsage() : emptyUsage(state);
20540
+ const usage = state.agent ? state.agent.getContextUsage() : emptyUsage2(state);
20474
20541
  const result = {
20475
20542
  ...usage,
20476
20543
  ...state.sessionId ? { session_id: state.sessionId } : {}
@@ -20479,7 +20546,7 @@ var createContextUsageHandlers = ({
20479
20546
  } catch (error) {
20480
20547
  log2(`context.usage failed: ${String(error)}`);
20481
20548
  sendError(id2, {
20482
- code: RPC_ERROR_CODE8.RUNTIME_INTERNAL,
20549
+ code: RPC_ERROR_CODE9.RUNTIME_INTERNAL,
20483
20550
  message: "context usage unavailable"
20484
20551
  });
20485
20552
  }
@@ -20513,7 +20580,7 @@ var createRunContextUsageEmitter = (options) => {
20513
20580
  import { promises as fs11 } from "fs";
20514
20581
  import path28 from "path";
20515
20582
  import {
20516
- RPC_ERROR_CODE as RPC_ERROR_CODE9
20583
+ RPC_ERROR_CODE as RPC_ERROR_CODE10
20517
20584
  } from "@codelia/protocol";
20518
20585
  import {
20519
20586
  readRunLogLines,
@@ -20737,7 +20804,7 @@ var createHistoryHandlers = ({
20737
20804
  sessions = await sessionStateStore.list();
20738
20805
  } catch (error) {
20739
20806
  sendError(id2, {
20740
- code: RPC_ERROR_CODE9.SESSION_LIST_FAILED,
20807
+ code: RPC_ERROR_CODE10.SESSION_LIST_FAILED,
20741
20808
  message: `session list failed: ${String(error)}`
20742
20809
  });
20743
20810
  return;
@@ -20770,7 +20837,7 @@ var createHistoryHandlers = ({
20770
20837
  const sessionId = params?.session_id?.trim();
20771
20838
  if (!sessionId) {
20772
20839
  sendError(id2, {
20773
- code: RPC_ERROR_CODE9.INVALID_PARAMS,
20840
+ code: RPC_ERROR_CODE10.INVALID_PARAMS,
20774
20841
  message: "session_id is required"
20775
20842
  });
20776
20843
  return;
@@ -20860,7 +20927,7 @@ import {
20860
20927
  parseImageGenerationConfig
20861
20928
  } from "@codelia/config";
20862
20929
  import {
20863
- RPC_ERROR_CODE as RPC_ERROR_CODE10
20930
+ RPC_ERROR_CODE as RPC_ERROR_CODE11
20864
20931
  } from "@codelia/protocol";
20865
20932
  function createImageHandlers(state) {
20866
20933
  const catalog = new ImageCatalog();
@@ -21170,7 +21237,7 @@ Saved to ${scope} settings.`
21170
21237
  });
21171
21238
  } catch (error) {
21172
21239
  sendError(id2, {
21173
- code: RPC_ERROR_CODE10.INVALID_PARAMS,
21240
+ code: RPC_ERROR_CODE11.INVALID_PARAMS,
21174
21241
  message: error instanceof ImageGenerationError ? error.message : "Image operation failed; check settings, artifact and runtime storage. No credentials were changed."
21175
21242
  });
21176
21243
  } finally {
@@ -21191,7 +21258,7 @@ import {
21191
21258
  } from "@codelia/core";
21192
21259
  import { ModelMetadataServiceImpl as ModelMetadataServiceImpl2 } from "@codelia/model-metadata";
21193
21260
  import {
21194
- RPC_ERROR_CODE as RPC_ERROR_CODE11
21261
+ RPC_ERROR_CODE as RPC_ERROR_CODE12
21195
21262
  } from "@codelia/protocol";
21196
21263
  import {
21197
21264
  isModelFastMode as isModelFastMode2
@@ -21587,7 +21654,7 @@ var createModelHandlers = ({
21587
21654
  }
21588
21655
  } catch (error) {
21589
21656
  sendError(id2, {
21590
- code: RPC_ERROR_CODE11.RUNTIME_INTERNAL,
21657
+ code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
21591
21658
  message: String(error)
21592
21659
  });
21593
21660
  return;
@@ -21595,7 +21662,7 @@ var createModelHandlers = ({
21595
21662
  const provider = requestedProvider ?? configuredProvider ?? "openai";
21596
21663
  if (!isSupportedProvider(provider, providers)) {
21597
21664
  sendError(id2, {
21598
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21665
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21599
21666
  message: `unsupported provider: ${provider}`
21600
21667
  });
21601
21668
  return;
@@ -21614,7 +21681,7 @@ var createModelHandlers = ({
21614
21681
  details = result2.details;
21615
21682
  } catch (error) {
21616
21683
  sendError(id2, {
21617
- code: RPC_ERROR_CODE11.RUNTIME_INTERNAL,
21684
+ code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
21618
21685
  message: String(error)
21619
21686
  });
21620
21687
  return;
@@ -21645,7 +21712,7 @@ var createModelHandlers = ({
21645
21712
  const handleModelSet = async (id2, raw) => {
21646
21713
  if (state.activeRunId) {
21647
21714
  sendError(id2, {
21648
- code: RPC_ERROR_CODE11.RUNTIME_BUSY,
21715
+ code: RPC_ERROR_CODE12.RUNTIME_BUSY,
21649
21716
  message: "runtime busy"
21650
21717
  });
21651
21718
  return;
@@ -21662,7 +21729,7 @@ var createModelHandlers = ({
21662
21729
  const scope = params?.scope ?? "config";
21663
21730
  if (scope !== "config" && scope !== "session") {
21664
21731
  sendError(id2, {
21665
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21732
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21666
21733
  message: `unsupported model scope: ${scope}`
21667
21734
  });
21668
21735
  return;
@@ -21671,7 +21738,7 @@ var createModelHandlers = ({
21671
21738
  if (params?.reset) {
21672
21739
  if (scope !== "session") {
21673
21740
  sendError(id2, {
21674
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21741
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21675
21742
  message: "model reset is only supported for session scope"
21676
21743
  });
21677
21744
  return;
@@ -21682,7 +21749,7 @@ var createModelHandlers = ({
21682
21749
  const name3 = config.name;
21683
21750
  if (!name3) {
21684
21751
  sendError(id2, {
21685
- code: RPC_ERROR_CODE11.RUNTIME_INTERNAL,
21752
+ code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
21686
21753
  message: "configured model name is missing"
21687
21754
  });
21688
21755
  return;
@@ -21698,7 +21765,7 @@ var createModelHandlers = ({
21698
21765
  );
21699
21766
  } catch (error) {
21700
21767
  sendError(id2, {
21701
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21768
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21702
21769
  message: String(error)
21703
21770
  });
21704
21771
  return;
@@ -21720,7 +21787,7 @@ var createModelHandlers = ({
21720
21787
  log2(`model.set reset session override -> ${provider2}/${name3}`);
21721
21788
  } catch (error) {
21722
21789
  sendError(id2, {
21723
- code: RPC_ERROR_CODE11.RUNTIME_INTERNAL,
21790
+ code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
21724
21791
  message: String(error)
21725
21792
  });
21726
21793
  }
@@ -21730,7 +21797,7 @@ var createModelHandlers = ({
21730
21797
  let name2 = params?.name?.trim();
21731
21798
  if (!name2) {
21732
21799
  sendError(id2, {
21733
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21800
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21734
21801
  message: "model name is required"
21735
21802
  });
21736
21803
  return;
@@ -21741,7 +21808,7 @@ var createModelHandlers = ({
21741
21808
  reasoning = resolveReasoningEffort(params.reasoning);
21742
21809
  } catch (error) {
21743
21810
  sendError(id2, {
21744
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21811
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21745
21812
  message: String(error)
21746
21813
  });
21747
21814
  return;
@@ -21751,7 +21818,7 @@ var createModelHandlers = ({
21751
21818
  const endpoint = getResponsesProvider(configured, provider);
21752
21819
  if (!isSupportedProvider(provider, configured.providers)) {
21753
21820
  sendError(id2, {
21754
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21821
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21755
21822
  message: `unsupported provider: ${provider}`
21756
21823
  });
21757
21824
  return;
@@ -21764,7 +21831,7 @@ var createModelHandlers = ({
21764
21831
  );
21765
21832
  if (!spec) {
21766
21833
  sendError(id2, {
21767
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21834
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21768
21835
  message: `unknown model: ${name2}`
21769
21836
  });
21770
21837
  return;
@@ -21797,7 +21864,7 @@ var createModelHandlers = ({
21797
21864
  await validateFastSelection(provider, name2, candidate.fast);
21798
21865
  } catch (error) {
21799
21866
  sendError(id2, {
21800
- code: RPC_ERROR_CODE11.INVALID_PARAMS,
21867
+ code: RPC_ERROR_CODE12.INVALID_PARAMS,
21801
21868
  message: String(error)
21802
21869
  });
21803
21870
  return;
@@ -21852,7 +21919,7 @@ var createModelHandlers = ({
21852
21919
  );
21853
21920
  } catch (error) {
21854
21921
  sendError(id2, {
21855
- code: RPC_ERROR_CODE11.RUNTIME_INTERNAL,
21922
+ code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
21856
21923
  message: String(error)
21857
21924
  });
21858
21925
  }
@@ -21864,7 +21931,7 @@ var createModelHandlers = ({
21864
21931
  import { realpathSync as realpathSync14 } from "fs";
21865
21932
  import { loadConfig as loadConfig2, removePermissionRules } from "@codelia/config-loader";
21866
21933
  import {
21867
- RPC_ERROR_CODE as RPC_ERROR_CODE12
21934
+ RPC_ERROR_CODE as RPC_ERROR_CODE13
21868
21935
  } from "@codelia/protocol";
21869
21936
  import { ProjectsPolicyStore as ProjectsPolicyStore4 } from "@codelia/storage";
21870
21937
  var MAX_RULE_FIELD_LENGTH = 4096;
@@ -21902,7 +21969,7 @@ var createPermissionsHandlers = ({
21902
21969
  const rejectUnsupported = (id2) => {
21903
21970
  if (supportsConfigReadWrite(state)) return false;
21904
21971
  sendError(id2, {
21905
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
21972
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
21906
21973
  message: "permission rules are not available for this runtime"
21907
21974
  });
21908
21975
  return true;
@@ -21914,7 +21981,7 @@ var createPermissionsHandlers = ({
21914
21981
  const params = parsed.params;
21915
21982
  if (params?.include_system !== void 0 && typeof params.include_system !== "boolean") {
21916
21983
  sendError(id2, {
21917
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
21984
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
21918
21985
  message: "include_system must be a boolean"
21919
21986
  });
21920
21987
  return;
@@ -22016,7 +22083,7 @@ var createPermissionsHandlers = ({
22016
22083
  const root = resolveConfigWorkspaceDir(state);
22017
22084
  if (!root || !localProjectAllows(state) || params.scope !== "project" || !configurableToolInvocations.has(params.remembered_tool)) {
22018
22085
  sendError(id2, {
22019
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
22086
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
22020
22087
  message: "Invalid remembered tool"
22021
22088
  });
22022
22089
  return;
@@ -22037,7 +22104,7 @@ var createPermissionsHandlers = ({
22037
22104
  });
22038
22105
  if (removed === "busy") {
22039
22106
  sendError(id2, {
22040
- code: RPC_ERROR_CODE12.RUNTIME_BUSY,
22107
+ code: RPC_ERROR_CODE13.RUNTIME_BUSY,
22041
22108
  message: "runtime busy"
22042
22109
  });
22043
22110
  return;
@@ -22049,7 +22116,7 @@ var createPermissionsHandlers = ({
22049
22116
  });
22050
22117
  } catch {
22051
22118
  sendError(id2, {
22052
- code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
22119
+ code: RPC_ERROR_CODE13.RUNTIME_INTERNAL,
22053
22120
  message: "Remembered tool removal failed"
22054
22121
  });
22055
22122
  }
@@ -22058,7 +22125,7 @@ var createPermissionsHandlers = ({
22058
22125
  const workspaceDir = resolveConfigWorkspaceDir(state);
22059
22126
  if (!workspaceDir || params.resource !== "workspace_write" || params.scope !== "session") {
22060
22127
  sendError(id2, {
22061
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
22128
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
22062
22129
  message: "Invalid workspace grant reference"
22063
22130
  });
22064
22131
  return;
@@ -22074,7 +22141,7 @@ var createPermissionsHandlers = ({
22074
22141
  const workspaceDir = resolveConfigWorkspaceDir(state);
22075
22142
  if (!workspaceDir || !/^[a-f0-9]{64}$/u.test(params.launch_rule_id) || params.scope !== "session" && params.scope !== "project" || state.effectiveEnvironment.sourcePreset !== "tui-local") {
22076
22143
  sendError(id2, {
22077
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
22144
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
22078
22145
  message: "Invalid launch rule reference"
22079
22146
  });
22080
22147
  return;
@@ -22094,7 +22161,7 @@ var createPermissionsHandlers = ({
22094
22161
  sendRequestResult("permissions.remove", id2, result);
22095
22162
  } catch {
22096
22163
  sendError(id2, {
22097
- code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
22164
+ code: RPC_ERROR_CODE13.RUNTIME_INTERNAL,
22098
22165
  message: "Launch rule removal failed"
22099
22166
  });
22100
22167
  }
@@ -22111,12 +22178,12 @@ var createPermissionsHandlers = ({
22111
22178
  return removeLaunchRule(id2, params);
22112
22179
  if (state.activeRunId) {
22113
22180
  sendError(id2, {
22114
- code: RPC_ERROR_CODE12.RUNTIME_BUSY,
22181
+ code: RPC_ERROR_CODE13.RUNTIME_BUSY,
22115
22182
  message: "runtime busy"
22116
22183
  });
22117
22184
  return;
22118
22185
  }
22119
- const invalid = (message) => sendError(id2, { code: RPC_ERROR_CODE12.INVALID_PARAMS, message });
22186
+ const invalid = (message) => sendError(id2, { code: RPC_ERROR_CODE13.INVALID_PARAMS, message });
22120
22187
  const scope = params?.scope;
22121
22188
  const kind = params?.kind;
22122
22189
  if (scope !== "global" && scope !== "project") {
@@ -22152,14 +22219,14 @@ var createPermissionsHandlers = ({
22152
22219
  });
22153
22220
  } catch {
22154
22221
  sendError(id2, {
22155
- code: RPC_ERROR_CODE12.RUNTIME_INTERNAL,
22222
+ code: RPC_ERROR_CODE13.RUNTIME_INTERNAL,
22156
22223
  message: `${scope} config write failed`
22157
22224
  });
22158
22225
  return;
22159
22226
  }
22160
22227
  if (removed === "busy") {
22161
22228
  sendError(id2, {
22162
- code: RPC_ERROR_CODE12.RUNTIME_BUSY,
22229
+ code: RPC_ERROR_CODE13.RUNTIME_BUSY,
22163
22230
  message: "runtime busy"
22164
22231
  });
22165
22232
  return;
@@ -22171,7 +22238,7 @@ var createPermissionsHandlers = ({
22171
22238
  const handleProjectAllowTrustSet = async (id2, raw) => {
22172
22239
  if (!supportsProjectAllowTrust(state)) {
22173
22240
  sendError(id2, {
22174
- code: RPC_ERROR_CODE12.METHOD_NOT_FOUND,
22241
+ code: RPC_ERROR_CODE13.METHOD_NOT_FOUND,
22175
22242
  message: "Project allow trust changes are unavailable for this runtime."
22176
22243
  });
22177
22244
  return;
@@ -22181,7 +22248,7 @@ var createPermissionsHandlers = ({
22181
22248
  const params = parsed.params;
22182
22249
  if (typeof params?.workspace !== "string" || typeof params.trusted !== "boolean" || typeof params.expected_revision !== "string" || !params.expected_revision) {
22183
22250
  sendError(id2, {
22184
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
22251
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
22185
22252
  message: "Expected a reviewed project allow list for this local workspace"
22186
22253
  });
22187
22254
  return;
@@ -22190,7 +22257,7 @@ var createPermissionsHandlers = ({
22190
22257
  await state.withAdmissionLock(async () => {
22191
22258
  if (state.activeRunId) {
22192
22259
  sendError(id2, {
22193
- code: RPC_ERROR_CODE12.RUNTIME_BUSY,
22260
+ code: RPC_ERROR_CODE13.RUNTIME_BUSY,
22194
22261
  message: "runtime busy"
22195
22262
  });
22196
22263
  return;
@@ -22198,7 +22265,7 @@ var createPermissionsHandlers = ({
22198
22265
  const root = resolveConfigWorkspaceDir(state);
22199
22266
  if (!root || realpathSync14(root) !== params.workspace) {
22200
22267
  sendError(id2, {
22201
- code: RPC_ERROR_CODE12.INVALID_PARAMS,
22268
+ code: RPC_ERROR_CODE13.INVALID_PARAMS,
22202
22269
  message: "Workspace changed. Review the current project allow list again."
22203
22270
  });
22204
22271
  return;
@@ -22218,7 +22285,7 @@ var createPermissionsHandlers = ({
22218
22285
  } catch (error) {
22219
22286
  const changed = error instanceof Error && error.message === "project_allow_trust_changed";
22220
22287
  sendError(id2, {
22221
- code: changed ? RPC_ERROR_CODE12.INVALID_PARAMS : RPC_ERROR_CODE12.RUNTIME_INTERNAL,
22288
+ code: changed ? RPC_ERROR_CODE13.INVALID_PARAMS : RPC_ERROR_CODE13.RUNTIME_INTERNAL,
22222
22289
  message: changed ? "The project allow list or its trust state changed. Review it again." : "Project allow trust is unavailable."
22223
22290
  });
22224
22291
  }
@@ -22604,14 +22671,14 @@ var buildResumeDiff = async (meta, state, options = {}) => {
22604
22671
 
22605
22672
  // src/rpc/run.ts
22606
22673
  import {
22607
- RPC_ERROR_CODE as RPC_ERROR_CODE14
22674
+ RPC_ERROR_CODE as RPC_ERROR_CODE15
22608
22675
  } from "@codelia/protocol";
22609
22676
 
22610
22677
  // src/rpc/goals.ts
22611
22678
  import {
22612
22679
  defineTool as defineTool22
22613
22680
  } from "@codelia/core";
22614
- import { RPC_ERROR_CODE as RPC_ERROR_CODE13 } from "@codelia/protocol";
22681
+ import { RPC_ERROR_CODE as RPC_ERROR_CODE14 } from "@codelia/protocol";
22615
22682
  import {
22616
22683
  getProcessIdentity as getProcessIdentity2
22617
22684
  } from "@codelia/storage";
@@ -22766,7 +22833,7 @@ var GoalController = class {
22766
22833
  handle(requestId, method, raw, serialize, interrupt, onError) {
22767
22834
  if (!this.enabled) {
22768
22835
  sendError(requestId, {
22769
- code: RPC_ERROR_CODE13.INVALID_PARAMS,
22836
+ code: RPC_ERROR_CODE14.INVALID_PARAMS,
22770
22837
  message: "Goals are unavailable on this connection."
22771
22838
  });
22772
22839
  return Promise.resolve();
@@ -22959,7 +23026,7 @@ var GoalController = class {
22959
23026
  reject(requestId, error) {
22960
23027
  const conflict = error instanceof GoalConflict ? error : null;
22961
23028
  sendError(requestId, {
22962
- code: conflict?.reason === "busy" ? RPC_ERROR_CODE13.RUNTIME_BUSY : conflict || error instanceof z40.ZodError ? RPC_ERROR_CODE13.INVALID_PARAMS : RPC_ERROR_CODE13.RUNTIME_INTERNAL,
23029
+ code: conflict?.reason === "busy" ? RPC_ERROR_CODE14.RUNTIME_BUSY : conflict || error instanceof z40.ZodError ? RPC_ERROR_CODE14.INVALID_PARAMS : RPC_ERROR_CODE14.RUNTIME_INTERNAL,
22963
23030
  message: conflict?.message ?? (error instanceof z40.ZodError ? "Invalid goal parameters." : "Goal operation failed.")
22964
23031
  });
22965
23032
  }
@@ -23650,6 +23717,15 @@ var runInputLengthForDebug = (input) => {
23650
23717
  };
23651
23718
 
23652
23719
  // src/rpc/run-metrics.ts
23720
+ import {
23721
+ estimateUsageCostUsd
23722
+ } from "@codelia/core";
23723
+ var nonEmpty = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
23724
+ var extractActualModel = (providerMeta) => {
23725
+ const meta = providerMeta;
23726
+ const rawServerModel = meta?.codex_metadata?.server_model ?? meta?.server_model;
23727
+ return typeof rawServerModel === "string" && rawServerModel.trim().length > 0 ? rawServerModel.trim() : null;
23728
+ };
23653
23729
  var buildRunMetrics = (record) => {
23654
23730
  const timing = record.output.timing;
23655
23731
  const tokens = record.output.usage?.output_tokens;
@@ -23666,6 +23742,45 @@ var buildRunMetrics = (record) => {
23666
23742
  ...validTiming ? { timing } : {}
23667
23743
  };
23668
23744
  };
23745
+ var buildCallRunMetrics = (input) => {
23746
+ const { record, request } = input;
23747
+ const usage = record.output.usage ?? null;
23748
+ const hasCacheMetric = typeof usage?.input_cached_tokens === "number";
23749
+ const cacheReadTokens = hasCacheMetric ? usage?.input_cached_tokens ?? 0 : 0;
23750
+ const cacheCreationTokens = usage?.input_cache_creation_tokens ?? 0;
23751
+ const inputTokens = usage?.input_tokens ?? 0;
23752
+ const hitState = hasCacheMetric ? cacheReadTokens > 0 ? "hit" : "miss" : "unknown";
23753
+ const requestModel = nonEmpty(request?.model);
23754
+ const usageModel = nonEmpty(usage?.model);
23755
+ const model = usageModel ?? requestModel ?? "unknown";
23756
+ const baseMetrics = buildRunMetrics(record);
23757
+ const modelCost = input.getModelCost ? (requestModel ? input.getModelCost(requestModel) : void 0) ?? input.getModelCost(model) : void 0;
23758
+ const costUsd = input.metered ? estimateUsageCostUsd(usage, modelCost) : null;
23759
+ const actualModel = extractActualModel(record.output.provider_meta);
23760
+ return {
23761
+ ...baseMetrics,
23762
+ ...request?.provider ? { provider: request.provider } : {},
23763
+ model,
23764
+ ...actualModel ? { actual_model: actualModel } : {},
23765
+ request_ts: request?.ts ?? record.ts,
23766
+ response_ts: record.ts,
23767
+ latency_ms: Math.max(0, Math.round(input.latencyMs)),
23768
+ stop_reason: record.output.stop_reason ?? null,
23769
+ usage,
23770
+ cache: {
23771
+ hit_state: hitState,
23772
+ cache_read_tokens: cacheReadTokens,
23773
+ cache_creation_tokens: cacheCreationTokens,
23774
+ cache_read_ratio: hasCacheMetric && inputTokens > 0 ? Math.min(1, Math.max(0, cacheReadTokens / inputTokens)) : null
23775
+ },
23776
+ cost_usd: costUsd,
23777
+ cost_basis: costUsd !== null ? "api_list" : "unavailable",
23778
+ retry_count: Math.max(0, input.retryCount),
23779
+ retry_wait_ms: Math.max(0, input.retryWaitMs),
23780
+ provider_meta_summary: summarizeProviderMeta(record.output.provider_meta),
23781
+ ...input.context ? { context: input.context } : {}
23782
+ };
23783
+ };
23669
23784
 
23670
23785
  // src/rpc/text-delta-coalescer.ts
23671
23786
  var DEFAULT_TEXT_DELTA_FLUSH_MS = 40;
@@ -23800,10 +23915,6 @@ var mergeWorkspaceRootIntoSessionMeta = (meta, workspaceRoot) => {
23800
23915
  return Object.keys(nextMeta).length > 0 ? nextMeta : void 0;
23801
23916
  };
23802
23917
  var resolveSessionWorkspaceRoot = (state) => state.lastUiContext?.workspace_root ?? state.agentsResolver?.getRootDir() ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? void 0;
23803
- var toTimestampMs = (value) => {
23804
- const ms = Date.parse(value);
23805
- return Number.isFinite(ms) ? ms : null;
23806
- };
23807
23918
  var OPENAI_AUTO_WS_FALLBACK_WARNING = "Warning: OpenAI websocket auto mode fell back to HTTP. Continuing this run over HTTP.";
23808
23919
  var shouldEmitOpenAiWsFallbackWarning = (providerMeta) => {
23809
23920
  if (!providerMeta || typeof providerMeta !== "object" || Array.isArray(providerMeta)) {
@@ -23921,7 +24032,7 @@ var createRunHandlers = ({
23921
24032
  initialInput = normalizeRunInput(params.input);
23922
24033
  } catch (error) {
23923
24034
  sendError(id2, {
23924
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24035
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
23925
24036
  message: String(error)
23926
24037
  });
23927
24038
  return;
@@ -23929,7 +24040,7 @@ var createRunHandlers = ({
23929
24040
  const attachmentIds = runAttachmentIds(initialInput);
23930
24041
  if (params.force_compaction && attachmentIds.length > 0) {
23931
24042
  sendError(id2, {
23932
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24043
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
23933
24044
  message: "A compaction run cannot admit new attachments"
23934
24045
  });
23935
24046
  return;
@@ -23939,7 +24050,7 @@ var createRunHandlers = ({
23939
24050
  await beforeRunStart();
23940
24051
  } catch (error) {
23941
24052
  sendError(id2, {
23942
- code: RPC_ERROR_CODE14.RUNTIME_INTERNAL,
24053
+ code: RPC_ERROR_CODE15.RUNTIME_INTERNAL,
23943
24054
  message: `startup onboarding failed: ${String(error)}`
23944
24055
  });
23945
24056
  return;
@@ -23947,7 +24058,7 @@ var createRunHandlers = ({
23947
24058
  }
23948
24059
  if (state.activeRunId) {
23949
24060
  sendError(id2, {
23950
- code: RPC_ERROR_CODE14.RUNTIME_BUSY,
24061
+ code: RPC_ERROR_CODE15.RUNTIME_BUSY,
23951
24062
  message: "runtime busy"
23952
24063
  });
23953
24064
  return;
@@ -23964,14 +24075,14 @@ var createRunHandlers = ({
23964
24075
  resumeState = await sessionStateStore.load(requestedSessionId);
23965
24076
  } catch (error) {
23966
24077
  sendError(id2, {
23967
- code: RPC_ERROR_CODE14.SESSION_LOAD_FAILED,
24078
+ code: RPC_ERROR_CODE15.SESSION_LOAD_FAILED,
23968
24079
  message: `session load failed: ${String(error)}`
23969
24080
  });
23970
24081
  return;
23971
24082
  }
23972
24083
  if (!resumeState) {
23973
24084
  sendError(id2, {
23974
- code: RPC_ERROR_CODE14.SESSION_NOT_FOUND,
24085
+ code: RPC_ERROR_CODE15.SESSION_NOT_FOUND,
23975
24086
  message: "session not found"
23976
24087
  });
23977
24088
  return;
@@ -23982,7 +24093,7 @@ var createRunHandlers = ({
23982
24093
  resumeState = await sessionStateStore.load(state.sessionId);
23983
24094
  } catch (error) {
23984
24095
  sendError(id2, {
23985
- code: RPC_ERROR_CODE14.SESSION_LOAD_FAILED,
24096
+ code: RPC_ERROR_CODE15.SESSION_LOAD_FAILED,
23986
24097
  message: `session reload failed: ${String(error)}`
23987
24098
  });
23988
24099
  return;
@@ -23999,7 +24110,7 @@ var createRunHandlers = ({
23999
24110
  if (resumeState?.meta?.codelia_subagent) {
24000
24111
  restorePreviousModel();
24001
24112
  sendError(id2, {
24002
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24113
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24003
24114
  message: "Delegated sessions cannot be resumed as a root run"
24004
24115
  });
24005
24116
  return;
@@ -24024,7 +24135,7 @@ var createRunHandlers = ({
24024
24135
  } catch (error) {
24025
24136
  restorePreviousModel();
24026
24137
  sendError(id2, {
24027
- code: error instanceof AttachmentAdmissionError ? RPC_ERROR_CODE14.INVALID_PARAMS : RPC_ERROR_CODE14.RUNTIME_INTERNAL,
24138
+ code: error instanceof AttachmentAdmissionError ? RPC_ERROR_CODE15.INVALID_PARAMS : RPC_ERROR_CODE15.RUNTIME_INTERNAL,
24028
24139
  message: error instanceof Error ? error.message : String(error)
24029
24140
  });
24030
24141
  return;
@@ -24041,7 +24152,7 @@ var createRunHandlers = ({
24041
24152
  } catch (error) {
24042
24153
  restorePreviousModel();
24043
24154
  sendError(id2, {
24044
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24155
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24045
24156
  message: String(error)
24046
24157
  });
24047
24158
  return;
@@ -24060,7 +24171,7 @@ var createRunHandlers = ({
24060
24171
  } catch {
24061
24172
  restorePreviousModel();
24062
24173
  sendError(id2, {
24063
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24174
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24064
24175
  message: "Could not claim the attachments for this conversation. Upload them again."
24065
24176
  });
24066
24177
  return;
@@ -24180,22 +24291,30 @@ var createRunHandlers = ({
24180
24291
  }
24181
24292
  );
24182
24293
  const pendingLlmRequests = /* @__PURE__ */ new Map();
24294
+ const toolNamesByCallId = /* @__PURE__ */ new Map();
24295
+ let pendingRetryCount = 0;
24296
+ let pendingRetryWaitMs = 0;
24297
+ let activeRetry = null;
24298
+ const settleActiveRetryWait = (interrupted) => {
24299
+ if (!activeRetry) return;
24300
+ const { startedAtMs, plannedMs } = activeRetry;
24301
+ activeRetry = null;
24302
+ const waitMs = interrupted ? Math.min(
24303
+ plannedMs,
24304
+ Math.max(0, Math.round(performance.now() - startedAtMs))
24305
+ ) : plannedMs;
24306
+ pendingRetryWaitMs += waitMs;
24307
+ state.telemetry.recordRetryWait(runId, waitMs);
24308
+ };
24309
+ const runStartedAtMs = performance.now();
24310
+ state.telemetry.beginRun(runId);
24183
24311
  let openAiWsFallbackWarningShown = false;
24184
24312
  const streamDeltas = state.uiCapabilities?.supports_text_delta === true;
24185
- const diagnosticsActive = state.diagnosticsEnabled || state.uiCapabilities?.supports_run_diagnostics === true;
24186
24313
  const deltaCoalescer = streamDeltas ? createTextDeltaCoalescer({
24187
24314
  send: (event) => {
24188
24315
  if (!state.cancelRequested) sendAgentEvent(state, runId, event);
24189
24316
  }
24190
24317
  }) : null;
24191
- const emitRunDiagnostics = (params2) => {
24192
- if (!diagnosticsActive) return;
24193
- try {
24194
- sendRunDiagnostics(state, params2);
24195
- } catch (error) {
24196
- log2(`run diagnostics emit failed: ${String(error)}`);
24197
- }
24198
- };
24199
24318
  const emitOpenAiWsFallbackWarning = () => {
24200
24319
  if (openAiWsFallbackWarningShown) {
24201
24320
  return;
@@ -24224,68 +24343,44 @@ var createRunHandlers = ({
24224
24343
  }
24225
24344
  };
24226
24345
  const sessionAppend = (record) => {
24227
- if (record.type === "llm.response") {
24228
- try {
24229
- sendRunMetrics(state, buildRunMetrics(record));
24230
- } catch (error) {
24231
- log2(`run metrics emit failed: ${String(error)}`);
24346
+ try {
24347
+ if (record.type === "llm.request") {
24348
+ const modelName = record.model?.name ?? record.input.model ?? "unknown";
24349
+ pendingLlmRequests.set(record.seq, {
24350
+ ts: record.ts,
24351
+ startedAtMs: performance.now(),
24352
+ provider: record.model?.provider,
24353
+ model: modelName
24354
+ });
24232
24355
  }
24233
- }
24234
- if (diagnosticsActive) {
24235
- try {
24236
- if (record.type === "llm.request") {
24237
- const modelName = record.model?.name ?? record.input.model ?? "unknown";
24238
- pendingLlmRequests.set(record.seq, {
24239
- ts: record.ts,
24240
- provider: record.model?.provider,
24241
- model: modelName
24242
- });
24243
- }
24244
- if (record.type === "llm.response") {
24245
- const request = pendingLlmRequests.get(record.seq);
24246
- pendingLlmRequests.delete(record.seq);
24247
- const usage = record.output.usage ?? null;
24248
- const cacheReadTokens = usage?.input_cached_tokens ?? 0;
24249
- const cacheCreationTokens = usage?.input_cache_creation_tokens ?? 0;
24250
- const inputTokens = usage?.input_tokens ?? 0;
24251
- const hitState = usage ? cacheReadTokens > 0 ? "hit" : "miss" : "unknown";
24252
- const responseTsMs = toTimestampMs(record.ts);
24253
- const requestTsMs = request ? toTimestampMs(request.ts) : null;
24254
- const latencyMs = responseTsMs !== null && requestTsMs !== null ? Math.max(0, responseTsMs - requestTsMs) : 0;
24255
- const model = usage?.model ?? request?.model ?? "unknown";
24256
- const metrics = buildRunMetrics(record);
24257
- const diagnostics = {
24258
- run_id: runId,
24259
- seq: record.seq,
24260
- ...request?.provider ? { provider: request.provider } : {},
24261
- model,
24262
- request_ts: request?.ts ?? record.ts,
24263
- response_ts: record.ts,
24264
- latency_ms: latencyMs,
24265
- ...metrics.timing ? { timing: metrics.timing } : {},
24266
- output_tokens_per_second: metrics.output_tokens_per_second,
24267
- stop_reason: record.output.stop_reason ?? null,
24268
- usage,
24269
- cache: {
24270
- hit_state: hitState,
24271
- cache_read_tokens: cacheReadTokens,
24272
- cache_creation_tokens: cacheCreationTokens,
24273
- cache_read_ratio: usage ? cacheReadTokens / Math.max(inputTokens, 1) : null
24274
- },
24275
- cost_usd: null,
24276
- provider_meta_summary: summarizeProviderMeta(
24277
- record.output.provider_meta
24278
- )
24279
- };
24280
- emitRunDiagnostics({
24281
- run_id: runId,
24282
- kind: "llm_call",
24283
- call: diagnostics
24284
- });
24285
- }
24286
- } catch (error) {
24287
- log2(`run diagnostics build failed: ${String(error)}`);
24356
+ if (record.type === "llm.response") {
24357
+ settleActiveRetryWait(false);
24358
+ const request = pendingLlmRequests.get(record.seq);
24359
+ pendingLlmRequests.delete(record.seq);
24360
+ const latencyMs = request ? Math.max(0, Math.round(performance.now() - request.startedAtMs)) : 0;
24361
+ const route = state.reviewChatRoute;
24362
+ const retryCount = pendingRetryCount;
24363
+ const retryWaitMs = pendingRetryWaitMs;
24364
+ pendingRetryCount = 0;
24365
+ pendingRetryWaitMs = 0;
24366
+ const metrics = buildCallRunMetrics({
24367
+ record,
24368
+ request,
24369
+ latencyMs,
24370
+ metered: route?.kind === "builtin" && route.metered === true,
24371
+ getModelCost: (modelName) => runtimeAgent.getModelCost(modelName),
24372
+ retryCount,
24373
+ retryWaitMs,
24374
+ context: runtimeAgent.getContextSnapshot()
24375
+ });
24376
+ state.telemetry.recordLlmCall(metrics);
24377
+ sendRunMetrics(state, {
24378
+ ...metrics,
24379
+ session: state.telemetry.getSessionSummary()
24380
+ });
24288
24381
  }
24382
+ } catch (error) {
24383
+ log2(`run metrics build/emit failed: ${String(error)}`);
24289
24384
  }
24290
24385
  if (record.type === "llm.response" && shouldEmitOpenAiWsFallbackWarning(record.output.provider_meta)) {
24291
24386
  emitOpenAiWsFallbackWarning();
@@ -24398,12 +24493,23 @@ var createRunHandlers = ({
24398
24493
  let sessionSaveChain = Promise.resolve(true);
24399
24494
  let lastSessionSaveAt = 0;
24400
24495
  const polledUnconfirmedSteers = [];
24401
- const emitRunSummaryDiagnostics = () => {
24402
- emitRunDiagnostics({
24403
- run_id: runId,
24404
- kind: "run_summary",
24405
- summary: runtimeAgent.getUsageSummary()
24406
- });
24496
+ const emitRunSummary = () => {
24497
+ try {
24498
+ settleActiveRetryWait(true);
24499
+ const runSummary = state.telemetry.getRunSummary();
24500
+ if (!runSummary) return;
24501
+ sendRunSummary(state, {
24502
+ run_id: runId,
24503
+ duration_ms: Math.max(
24504
+ 0,
24505
+ Math.round(performance.now() - runStartedAtMs)
24506
+ ),
24507
+ run: runSummary,
24508
+ session: state.telemetry.getSessionSummary()
24509
+ });
24510
+ } catch (error) {
24511
+ log2(`run summary emit failed: ${String(error)}`);
24512
+ }
24407
24513
  };
24408
24514
  const buildTerminalStatusExtras = () => {
24409
24515
  state.closeRunSteers(runId);
@@ -24554,11 +24660,41 @@ var createRunHandlers = ({
24554
24660
  continue;
24555
24661
  }
24556
24662
  deltaCoalescer?.flush();
24663
+ if (event.type === "llm.retry") {
24664
+ settleActiveRetryWait(false);
24665
+ const delayMs = Math.max(0, event.delay_ms);
24666
+ pendingRetryCount += 1;
24667
+ state.telemetry.recordRetry(runId, 0);
24668
+ activeRetry = {
24669
+ startedAtMs: performance.now(),
24670
+ plannedMs: delayMs
24671
+ };
24672
+ }
24673
+ if (event.type === "tool_call") {
24674
+ toolNamesByCallId.set(event.tool_call_id, event.tool);
24675
+ }
24676
+ if (event.type === "step_complete") {
24677
+ const toolName = toolNamesByCallId.get(event.step_id) ?? "unknown";
24678
+ toolNamesByCallId.delete(event.step_id);
24679
+ state.telemetry.recordToolComplete({
24680
+ run_id: runId,
24681
+ tool_call_id: event.step_id,
24682
+ tool: toolName,
24683
+ status: event.status,
24684
+ duration_ms: event.duration_ms,
24685
+ ...event.exec_duration_ms !== void 0 ? { exec_duration_ms: event.exec_duration_ms } : {},
24686
+ ...event.approval_wait_ms !== void 0 ? { approval_wait_ms: event.approval_wait_ms } : {},
24687
+ finished_at: nowIso4()
24688
+ });
24689
+ }
24557
24690
  if (event.type === "final") {
24558
24691
  finalResponse = event.content;
24559
24692
  await queueSessionSave("final");
24560
24693
  }
24561
24694
  if (event.type === "compaction_complete") {
24695
+ if (event.compacted) {
24696
+ state.telemetry.recordCompaction(runId, event.duration_ms ?? 0);
24697
+ }
24562
24698
  logCompactionSnapshot(log2, runId, runtimeAgent, event.compacted);
24563
24699
  if (event.compacted) await queueSessionSave("compaction");
24564
24700
  }
@@ -24632,7 +24768,7 @@ var createRunHandlers = ({
24632
24768
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
24633
24769
  }
24634
24770
  await queueSessionSave("terminal");
24635
- emitRunSummaryDiagnostics();
24771
+ emitRunSummary();
24636
24772
  const status2 = state.cancelRequested ? "cancelled" : "completed";
24637
24773
  outcome = status2;
24638
24774
  const terminalExtras = buildTerminalStatusExtras();
@@ -24650,7 +24786,7 @@ var createRunHandlers = ({
24650
24786
  outcome = "cancelled";
24651
24787
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
24652
24788
  await queueSessionSave("cancelled");
24653
- emitRunSummaryDiagnostics();
24789
+ emitRunSummary();
24654
24790
  const terminalExtras2 = buildTerminalStatusExtras();
24655
24791
  emitRunStatus(
24656
24792
  runId,
@@ -24665,7 +24801,7 @@ var createRunHandlers = ({
24665
24801
  const safeFailure = normalizeRunFailure(err);
24666
24802
  logRunDebug(log2, runId, `stream.error ${safeFailure.debugMessage}`);
24667
24803
  await queueSessionSave("error");
24668
- emitRunSummaryDiagnostics();
24804
+ emitRunSummary();
24669
24805
  const terminalExtras = buildTerminalStatusExtras();
24670
24806
  emitRunStatus(
24671
24807
  runId,
@@ -24734,7 +24870,7 @@ var createRunHandlers = ({
24734
24870
  const runId = typeof params?.run_id === "string" ? params.run_id.trim() : "";
24735
24871
  if (!runId) {
24736
24872
  sendError(id2, {
24737
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24873
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24738
24874
  message: "run_id is required"
24739
24875
  });
24740
24876
  return Promise.resolve();
@@ -24754,7 +24890,7 @@ var createRunHandlers = ({
24754
24890
  const input = parseSteerInput(params.input);
24755
24891
  if ("error" in input) {
24756
24892
  sendError(id2, {
24757
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24893
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24758
24894
  message: input.error
24759
24895
  });
24760
24896
  return;
@@ -24762,7 +24898,7 @@ var createRunHandlers = ({
24762
24898
  const initialInput = input.value;
24763
24899
  if (!state.canSteerRun(runId)) {
24764
24900
  sendError(id2, {
24765
- code: RPC_ERROR_CODE14.RUN_NOT_FOUND,
24901
+ code: RPC_ERROR_CODE15.RUN_NOT_FOUND,
24766
24902
  message: "active run not found"
24767
24903
  });
24768
24904
  return;
@@ -24788,7 +24924,7 @@ var createRunHandlers = ({
24788
24924
  normalizedInput = await state.prepareRunImages(normalizedInput);
24789
24925
  } catch (error) {
24790
24926
  sendError(id2, {
24791
- code: error instanceof AttachmentAdmissionError ? RPC_ERROR_CODE14.INVALID_PARAMS : RPC_ERROR_CODE14.RUNTIME_INTERNAL,
24927
+ code: error instanceof AttachmentAdmissionError ? RPC_ERROR_CODE15.INVALID_PARAMS : RPC_ERROR_CODE15.RUNTIME_INTERNAL,
24792
24928
  message: error instanceof Error ? error.message : String(error)
24793
24929
  });
24794
24930
  return;
@@ -24802,7 +24938,7 @@ var createRunHandlers = ({
24802
24938
  );
24803
24939
  } catch {
24804
24940
  sendError(id2, {
24805
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24941
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24806
24942
  message: "Could not retain the attachments for this conversation. Upload them again."
24807
24943
  });
24808
24944
  return;
@@ -24811,7 +24947,7 @@ var createRunHandlers = ({
24811
24947
  if (!state.canSteerRun(runId)) {
24812
24948
  releaseAttachments?.();
24813
24949
  sendError(id2, {
24814
- code: RPC_ERROR_CODE14.RUN_NOT_FOUND,
24950
+ code: RPC_ERROR_CODE15.RUN_NOT_FOUND,
24815
24951
  message: "active run ended before steer could be queued"
24816
24952
  });
24817
24953
  return;
@@ -24846,7 +24982,7 @@ var createRunHandlers = ({
24846
24982
  const handleGoal = (id2, method, raw) => {
24847
24983
  if (!goals?.enabled) {
24848
24984
  sendError(id2, {
24849
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
24985
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24850
24986
  message: "Goals are unavailable on this connection."
24851
24987
  });
24852
24988
  return Promise.resolve();
@@ -24885,7 +25021,7 @@ var createRunHandlers = ({
24885
25021
  return;
24886
25022
  }
24887
25023
  sendError(id2, {
24888
- code: RPC_ERROR_CODE14.RUN_NOT_FOUND,
25024
+ code: RPC_ERROR_CODE15.RUN_NOT_FOUND,
24889
25025
  message: "run not found"
24890
25026
  });
24891
25027
  };
@@ -24896,14 +25032,14 @@ var createRunHandlers = ({
24896
25032
  const open3 = async () => {
24897
25033
  if (!sessionId) {
24898
25034
  sendError(id2, {
24899
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
25035
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24900
25036
  message: "session_id is required"
24901
25037
  });
24902
25038
  return;
24903
25039
  }
24904
25040
  if (state.activeRunId) {
24905
25041
  sendError(id2, {
24906
- code: RPC_ERROR_CODE14.RUNTIME_BUSY,
25042
+ code: RPC_ERROR_CODE15.RUNTIME_BUSY,
24907
25043
  message: "runtime busy"
24908
25044
  });
24909
25045
  return;
@@ -24919,21 +25055,21 @@ var createRunHandlers = ({
24919
25055
  opened = await sessionStateStore.load(sessionId);
24920
25056
  } catch (error) {
24921
25057
  sendError(id2, {
24922
- code: RPC_ERROR_CODE14.SESSION_LOAD_FAILED,
25058
+ code: RPC_ERROR_CODE15.SESSION_LOAD_FAILED,
24923
25059
  message: `session load failed: ${String(error)}`
24924
25060
  });
24925
25061
  return;
24926
25062
  }
24927
25063
  if (!opened) {
24928
25064
  sendError(id2, {
24929
- code: RPC_ERROR_CODE14.SESSION_NOT_FOUND,
25065
+ code: RPC_ERROR_CODE15.SESSION_NOT_FOUND,
24930
25066
  message: "session not found"
24931
25067
  });
24932
25068
  return;
24933
25069
  }
24934
25070
  if (opened.meta?.codelia_subagent) {
24935
25071
  sendError(id2, {
24936
- code: RPC_ERROR_CODE14.INVALID_PARAMS,
25072
+ code: RPC_ERROR_CODE15.INVALID_PARAMS,
24937
25073
  message: "Delegated sessions cannot be opened as a root session"
24938
25074
  });
24939
25075
  return;
@@ -24972,7 +25108,7 @@ var createRunHandlers = ({
24972
25108
  // src/rpc/sandbox.ts
24973
25109
  import { realpath as realpath4, stat } from "fs/promises";
24974
25110
  import {
24975
- RPC_ERROR_CODE as RPC_ERROR_CODE15
25111
+ RPC_ERROR_CODE as RPC_ERROR_CODE16
24976
25112
  } from "@codelia/protocol";
24977
25113
  import { ProjectsPolicyStore as ProjectsPolicyStore5 } from "@codelia/storage";
24978
25114
  var choices = [
@@ -25041,7 +25177,7 @@ var status = async (state, store) => {
25041
25177
  var handleSandbox = async (state, id2, method, params) => {
25042
25178
  if (!supportsSandboxModeManagement(state))
25043
25179
  return sendError(id2, {
25044
- code: RPC_ERROR_CODE15.METHOD_NOT_FOUND,
25180
+ code: RPC_ERROR_CODE16.METHOD_NOT_FOUND,
25045
25181
  message: "Sandbox management is unavailable."
25046
25182
  });
25047
25183
  if (method === "sandbox.get") {
@@ -25059,7 +25195,7 @@ var handleSandbox = async (state, id2, method, params) => {
25059
25195
  const { mode } = parsed.params;
25060
25196
  const store = new ProjectsPolicyStore5();
25061
25197
  const fail = (reason) => sendError(id2, {
25062
- code: reason === "runtime_busy" || reason === "policy_store_busy" ? RPC_ERROR_CODE15.RUNTIME_BUSY : RPC_ERROR_CODE15.INVALID_PARAMS,
25198
+ code: reason === "runtime_busy" || reason === "policy_store_busy" ? RPC_ERROR_CODE16.RUNTIME_BUSY : RPC_ERROR_CODE16.INVALID_PARAMS,
25063
25199
  message: `Project sandbox mode could not be changed (${reason}).`,
25064
25200
  data: { reason }
25065
25201
  });
@@ -25085,11 +25221,11 @@ var handleSandbox = async (state, id2, method, params) => {
25085
25221
  };
25086
25222
 
25087
25223
  // src/rpc/session-lifecycle.ts
25088
- import { RPC_ERROR_CODE as RPC_ERROR_CODE16 } from "@codelia/protocol";
25224
+ import { RPC_ERROR_CODE as RPC_ERROR_CODE17 } from "@codelia/protocol";
25089
25225
  var createSessionUpdateHandler = (options) => async (id2, raw) => {
25090
25226
  if (!options.sessions.updateMetadata) {
25091
25227
  sendError(id2, {
25092
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
25228
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
25093
25229
  message: "Session lifecycle updates are unavailable"
25094
25230
  });
25095
25231
  return;
@@ -25099,14 +25235,14 @@ var createSessionUpdateHandler = (options) => async (id2, raw) => {
25099
25235
  const params = parsed.params;
25100
25236
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(params.session_id) || params.pinned === void 0 && params.archived === void 0) {
25101
25237
  sendError(id2, {
25102
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
25238
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
25103
25239
  message: "Expected session_id and a boolean pinned or archived update"
25104
25240
  });
25105
25241
  return;
25106
25242
  }
25107
25243
  if (params.archived && options.state.activeRunId && options.state.sessionId === params.session_id) {
25108
25244
  sendError(id2, {
25109
- code: RPC_ERROR_CODE16.RUNTIME_BUSY,
25245
+ code: RPC_ERROR_CODE17.RUNTIME_BUSY,
25110
25246
  message: "Wait for the active run before archiving this session"
25111
25247
  });
25112
25248
  return;
@@ -25127,7 +25263,7 @@ var createSessionUpdateHandler = (options) => async (id2, raw) => {
25127
25263
  sendRequestResult("session.update", id2, result);
25128
25264
  } catch (error) {
25129
25265
  sendError(id2, {
25130
- code: RPC_ERROR_CODE16.INVALID_PARAMS,
25266
+ code: RPC_ERROR_CODE17.INVALID_PARAMS,
25131
25267
  message: `Session update failed: ${String(error)}`
25132
25268
  });
25133
25269
  }
@@ -25136,20 +25272,20 @@ var createSessionUpdateHandler = (options) => async (id2, raw) => {
25136
25272
  // src/rpc/shell.ts
25137
25273
  import path30 from "path";
25138
25274
  import {
25139
- RPC_ERROR_CODE as RPC_ERROR_CODE18
25275
+ RPC_ERROR_CODE as RPC_ERROR_CODE19
25140
25276
  } from "@codelia/protocol";
25141
25277
  import {
25142
25278
  ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl3
25143
25279
  } from "@codelia/storage";
25144
25280
 
25145
25281
  // src/rpc/shell-timeout.ts
25146
- import { RPC_ERROR_CODE as RPC_ERROR_CODE17 } from "@codelia/protocol";
25282
+ import { RPC_ERROR_CODE as RPC_ERROR_CODE18 } from "@codelia/protocol";
25147
25283
  var resolveRpcShellTimeoutSeconds = (requestedTimeout, background) => {
25148
25284
  if (requestedTimeout !== void 0) {
25149
25285
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
25150
25286
  return {
25151
25287
  error: {
25152
- code: RPC_ERROR_CODE17.INVALID_PARAMS,
25288
+ code: RPC_ERROR_CODE18.INVALID_PARAMS,
25153
25289
  message: "timeout_seconds must be a positive number"
25154
25290
  }
25155
25291
  };
@@ -25163,7 +25299,7 @@ var resolveRpcShellTimeoutSeconds = (requestedTimeout, background) => {
25163
25299
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
25164
25300
  return {
25165
25301
  error: {
25166
- code: RPC_ERROR_CODE17.INVALID_PARAMS,
25302
+ code: RPC_ERROR_CODE18.INVALID_PARAMS,
25167
25303
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
25168
25304
  }
25169
25305
  };
@@ -25224,7 +25360,7 @@ var parseShellOutputRequest = (params) => {
25224
25360
  if (!taskId) {
25225
25361
  return {
25226
25362
  error: {
25227
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25363
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25228
25364
  message: "task_id is required"
25229
25365
  }
25230
25366
  };
@@ -25232,7 +25368,7 @@ var parseShellOutputRequest = (params) => {
25232
25368
  if (params?.stream !== "stdout" && params?.stream !== "stderr") {
25233
25369
  return {
25234
25370
  error: {
25235
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25371
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25236
25372
  message: "stream must be stdout or stderr"
25237
25373
  }
25238
25374
  };
@@ -25240,7 +25376,7 @@ var parseShellOutputRequest = (params) => {
25240
25376
  if (params.line_number !== void 0 && (params.offset !== void 0 || params.limit !== void 0)) {
25241
25377
  return {
25242
25378
  error: {
25243
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25379
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25244
25380
  message: "line_number cannot be combined with offset or limit"
25245
25381
  }
25246
25382
  };
@@ -25248,7 +25384,7 @@ var parseShellOutputRequest = (params) => {
25248
25384
  if (params.line_number === void 0 && (params.char_offset !== void 0 || params.char_limit !== void 0)) {
25249
25385
  return {
25250
25386
  error: {
25251
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25387
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25252
25388
  message: "char_offset/char_limit require line_number"
25253
25389
  }
25254
25390
  };
@@ -25256,7 +25392,7 @@ var parseShellOutputRequest = (params) => {
25256
25392
  if (params.offset !== void 0 && (!Number.isFinite(params.offset) || params.offset < 0)) {
25257
25393
  return {
25258
25394
  error: {
25259
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25395
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25260
25396
  message: "offset must be a non-negative number"
25261
25397
  }
25262
25398
  };
@@ -25264,7 +25400,7 @@ var parseShellOutputRequest = (params) => {
25264
25400
  if (params.limit !== void 0 && (!Number.isFinite(params.limit) || params.limit <= 0)) {
25265
25401
  return {
25266
25402
  error: {
25267
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25403
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25268
25404
  message: "limit must be a positive number"
25269
25405
  }
25270
25406
  };
@@ -25272,7 +25408,7 @@ var parseShellOutputRequest = (params) => {
25272
25408
  if (params.line_number !== void 0 && (!Number.isFinite(params.line_number) || params.line_number <= 0)) {
25273
25409
  return {
25274
25410
  error: {
25275
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25411
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25276
25412
  message: "line_number must be a positive number"
25277
25413
  }
25278
25414
  };
@@ -25280,7 +25416,7 @@ var parseShellOutputRequest = (params) => {
25280
25416
  if (params.char_offset !== void 0 && (!Number.isFinite(params.char_offset) || params.char_offset < 0)) {
25281
25417
  return {
25282
25418
  error: {
25283
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25419
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25284
25420
  message: "char_offset must be a non-negative number"
25285
25421
  }
25286
25422
  };
@@ -25288,7 +25424,7 @@ var parseShellOutputRequest = (params) => {
25288
25424
  if (params.char_limit !== void 0 && (!Number.isFinite(params.char_limit) || params.char_limit <= 0)) {
25289
25425
  return {
25290
25426
  error: {
25291
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25427
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25292
25428
  message: "char_limit must be a positive number"
25293
25429
  }
25294
25430
  };
@@ -25342,7 +25478,7 @@ var parseTaskId = (value) => {
25342
25478
  var toTaskRpcError = (error) => {
25343
25479
  if (!(error instanceof TaskManagerError)) {
25344
25480
  return {
25345
- code: RPC_ERROR_CODE18.RUNTIME_INTERNAL,
25481
+ code: RPC_ERROR_CODE19.RUNTIME_INTERNAL,
25346
25482
  message: String(error)
25347
25483
  };
25348
25484
  }
@@ -25351,17 +25487,17 @@ var toTaskRpcError = (error) => {
25351
25487
  case "invalid_task_id":
25352
25488
  case "unsupported_workspace_mode":
25353
25489
  return {
25354
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25490
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25355
25491
  message: error.message
25356
25492
  };
25357
25493
  case "manager_shutting_down":
25358
25494
  return {
25359
- code: RPC_ERROR_CODE18.RUNTIME_BUSY,
25495
+ code: RPC_ERROR_CODE19.RUNTIME_BUSY,
25360
25496
  message: error.message
25361
25497
  };
25362
25498
  default:
25363
25499
  return {
25364
- code: RPC_ERROR_CODE18.RUNTIME_INTERNAL,
25500
+ code: RPC_ERROR_CODE19.RUNTIME_INTERNAL,
25365
25501
  message: error.message
25366
25502
  };
25367
25503
  }
@@ -25385,7 +25521,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
25385
25521
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
25386
25522
  return {
25387
25523
  error: {
25388
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25524
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25389
25525
  message: "wait_timeout_seconds must be a positive number"
25390
25526
  }
25391
25527
  };
@@ -25393,7 +25529,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
25393
25529
  if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
25394
25530
  return {
25395
25531
  error: {
25396
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25532
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25397
25533
  message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
25398
25534
  }
25399
25535
  };
@@ -25408,7 +25544,7 @@ var parseShellStartRequest = (state, params, options) => {
25408
25544
  if (!command.trim()) {
25409
25545
  return {
25410
25546
  error: {
25411
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25547
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25412
25548
  message: "command is required"
25413
25549
  }
25414
25550
  };
@@ -25424,7 +25560,7 @@ var parseShellStartRequest = (state, params, options) => {
25424
25560
  if (!cwd) {
25425
25561
  return {
25426
25562
  error: {
25427
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25563
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25428
25564
  message: "cwd is outside sandbox root"
25429
25565
  }
25430
25566
  };
@@ -25550,7 +25686,7 @@ var createShellHandlers = ({
25550
25686
  const requestedLimit = params?.limit;
25551
25687
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
25552
25688
  sendError(id2, {
25553
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25689
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25554
25690
  message: "limit must be a positive number"
25555
25691
  });
25556
25692
  return;
@@ -25568,7 +25704,7 @@ var createShellHandlers = ({
25568
25704
  const taskId = parseTaskId(params?.task_id);
25569
25705
  if (!taskId) {
25570
25706
  sendError(id2, {
25571
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25707
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25572
25708
  message: "task_id is required"
25573
25709
  });
25574
25710
  return;
@@ -25604,7 +25740,7 @@ var createShellHandlers = ({
25604
25740
  );
25605
25741
  if (!cacheId && liveContent === null && !isTerminalTaskState(task.state)) {
25606
25742
  sendError(id2, {
25607
- code: RPC_ERROR_CODE18.RUNTIME_BUSY,
25743
+ code: RPC_ERROR_CODE19.RUNTIME_BUSY,
25608
25744
  message: `shell output is not retained yet for running task: ${parsed.taskId}`
25609
25745
  });
25610
25746
  return;
@@ -25641,7 +25777,7 @@ var createShellHandlers = ({
25641
25777
  const taskId = parseTaskId(params?.task_id);
25642
25778
  if (!taskId) {
25643
25779
  sendError(id2, {
25644
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25780
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25645
25781
  message: "task_id is required"
25646
25782
  });
25647
25783
  return;
@@ -25733,7 +25869,7 @@ var createShellHandlers = ({
25733
25869
  const taskId = parseTaskId(params?.task_id);
25734
25870
  if (!taskId) {
25735
25871
  sendError(id2, {
25736
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25872
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25737
25873
  message: "task_id is required"
25738
25874
  });
25739
25875
  return;
@@ -25747,7 +25883,7 @@ var createShellHandlers = ({
25747
25883
  const waits = activeShellWaits.get(taskId);
25748
25884
  if (!waits || waits.size === 0) {
25749
25885
  sendError(id2, {
25750
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25886
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25751
25887
  message: `no active shell.wait to detach for task: ${taskId}`
25752
25888
  });
25753
25889
  return;
@@ -25769,7 +25905,7 @@ var createShellHandlers = ({
25769
25905
  const taskId = parseTaskId(params?.task_id);
25770
25906
  if (!taskId) {
25771
25907
  sendError(id2, {
25772
- code: RPC_ERROR_CODE18.INVALID_PARAMS,
25908
+ code: RPC_ERROR_CODE19.INVALID_PARAMS,
25773
25909
  message: "task_id is required"
25774
25910
  });
25775
25911
  return;
@@ -25799,7 +25935,7 @@ var createShellHandlers = ({
25799
25935
  // src/rpc/skills.ts
25800
25936
  import path31 from "path";
25801
25937
  import {
25802
- RPC_ERROR_CODE as RPC_ERROR_CODE19
25938
+ RPC_ERROR_CODE as RPC_ERROR_CODE20
25803
25939
  } from "@codelia/protocol";
25804
25940
  var createSkillsHandlers = ({
25805
25941
  state,
@@ -25831,7 +25967,7 @@ var createSkillsHandlers = ({
25831
25967
  });
25832
25968
  } catch (error) {
25833
25969
  sendError(id2, {
25834
- code: RPC_ERROR_CODE19.RUNTIME_INTERNAL,
25970
+ code: RPC_ERROR_CODE20.RUNTIME_INTERNAL,
25835
25971
  message: `skills resolver init failed: ${String(error)}`
25836
25972
  });
25837
25973
  return;
@@ -25853,7 +25989,7 @@ var createSkillsHandlers = ({
25853
25989
  } catch (error) {
25854
25990
  log2(`skills.list error: ${String(error)}`);
25855
25991
  sendError(id2, {
25856
- code: RPC_ERROR_CODE19.RUNTIME_INTERNAL,
25992
+ code: RPC_ERROR_CODE20.RUNTIME_INTERNAL,
25857
25993
  message: `skills list failed: ${String(error)}`
25858
25994
  });
25859
25995
  }
@@ -25864,7 +26000,7 @@ var createSkillsHandlers = ({
25864
26000
  // src/rpc/task.ts
25865
26001
  import path32 from "path";
25866
26002
  import {
25867
- RPC_ERROR_CODE as RPC_ERROR_CODE20
26003
+ RPC_ERROR_CODE as RPC_ERROR_CODE21
25868
26004
  } from "@codelia/protocol";
25869
26005
  import { ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl4 } from "@codelia/storage";
25870
26006
  var DEFAULT_TRUNCATED2 = {
@@ -25915,7 +26051,7 @@ var parseTaskId2 = (value) => {
25915
26051
  var toTaskRpcError2 = (error) => {
25916
26052
  if (!(error instanceof TaskManagerError)) {
25917
26053
  return {
25918
- code: RPC_ERROR_CODE20.RUNTIME_INTERNAL,
26054
+ code: RPC_ERROR_CODE21.RUNTIME_INTERNAL,
25919
26055
  message: String(error)
25920
26056
  };
25921
26057
  }
@@ -25924,17 +26060,17 @@ var toTaskRpcError2 = (error) => {
25924
26060
  case "invalid_task_id":
25925
26061
  case "unsupported_workspace_mode":
25926
26062
  return {
25927
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26063
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
25928
26064
  message: error.message
25929
26065
  };
25930
26066
  case "manager_shutting_down":
25931
26067
  return {
25932
- code: RPC_ERROR_CODE20.RUNTIME_BUSY,
26068
+ code: RPC_ERROR_CODE21.RUNTIME_BUSY,
25933
26069
  message: error.message
25934
26070
  };
25935
26071
  default:
25936
26072
  return {
25937
- code: RPC_ERROR_CODE20.RUNTIME_INTERNAL,
26073
+ code: RPC_ERROR_CODE21.RUNTIME_INTERNAL,
25938
26074
  message: error.message
25939
26075
  };
25940
26076
  }
@@ -25987,7 +26123,7 @@ var parseShellSpawnRequest = (state, params, options) => {
25987
26123
  if (!command.trim()) {
25988
26124
  return {
25989
26125
  error: {
25990
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26126
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
25991
26127
  message: "command is required for shell tasks"
25992
26128
  }
25993
26129
  };
@@ -26003,7 +26139,7 @@ var parseShellSpawnRequest = (state, params, options) => {
26003
26139
  if (!cwd) {
26004
26140
  return {
26005
26141
  error: {
26006
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26142
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26007
26143
  message: "cwd is outside sandbox root"
26008
26144
  }
26009
26145
  };
@@ -26083,7 +26219,7 @@ var createTaskHandlers = ({
26083
26219
  const handleTaskSpawn = async (id2, params) => {
26084
26220
  if (!params || !isTaskKind(params.kind)) {
26085
26221
  sendError(id2, {
26086
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26222
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26087
26223
  message: "kind must be shell or subagent"
26088
26224
  });
26089
26225
  return;
@@ -26091,7 +26227,7 @@ var createTaskHandlers = ({
26091
26227
  if (params.kind !== "shell") {
26092
26228
  if (params.kind !== "subagent" || !subagents?.isAvailable() || !getAgent) {
26093
26229
  sendError(id2, {
26094
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26230
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26095
26231
  message: `task kind ${params.kind} is not supported yet.`
26096
26232
  });
26097
26233
  return;
@@ -26175,21 +26311,21 @@ var createTaskHandlers = ({
26175
26311
  const requestedLimit = params?.limit;
26176
26312
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
26177
26313
  sendError(id2, {
26178
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26314
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26179
26315
  message: "limit must be a positive number"
26180
26316
  });
26181
26317
  return;
26182
26318
  }
26183
26319
  if (params?.kind !== void 0 && !isTaskKind(params.kind)) {
26184
26320
  sendError(id2, {
26185
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26321
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26186
26322
  message: "kind must be shell or subagent"
26187
26323
  });
26188
26324
  return;
26189
26325
  }
26190
26326
  if (params?.state !== void 0 && !isTaskState(params.state)) {
26191
26327
  sendError(id2, {
26192
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26328
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26193
26329
  message: "invalid task state"
26194
26330
  });
26195
26331
  return;
@@ -26207,7 +26343,7 @@ var createTaskHandlers = ({
26207
26343
  const taskId = parseTaskId2(params?.task_id);
26208
26344
  if (!taskId) {
26209
26345
  sendError(id2, {
26210
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26346
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26211
26347
  message: "task_id is required"
26212
26348
  });
26213
26349
  return;
@@ -26227,7 +26363,7 @@ var createTaskHandlers = ({
26227
26363
  const taskId = parseTaskId2(params?.task_id);
26228
26364
  if (!taskId) {
26229
26365
  sendError(id2, {
26230
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26366
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26231
26367
  message: "task_id is required"
26232
26368
  });
26233
26369
  return;
@@ -26248,7 +26384,7 @@ var createTaskHandlers = ({
26248
26384
  const taskId = parseTaskId2(params?.task_id);
26249
26385
  if (!taskId) {
26250
26386
  sendError(id2, {
26251
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26387
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26252
26388
  message: "task_id is required"
26253
26389
  });
26254
26390
  return;
@@ -26271,7 +26407,7 @@ var createTaskHandlers = ({
26271
26407
  const taskId = parseTaskId2(params?.task_id);
26272
26408
  if (!taskId) {
26273
26409
  sendError(id2, {
26274
- code: RPC_ERROR_CODE20.INVALID_PARAMS,
26410
+ code: RPC_ERROR_CODE21.INVALID_PARAMS,
26275
26411
  message: "task_id is required"
26276
26412
  });
26277
26413
  return;
@@ -26536,6 +26672,11 @@ var createRuntimeHandlers = ({
26536
26672
  state,
26537
26673
  log: log2
26538
26674
  });
26675
+ const telemetryHandlers = createTelemetryHandlers({
26676
+ state,
26677
+ subagents,
26678
+ log: log2
26679
+ });
26539
26680
  const { handleSkillsList } = createSkillsHandlers({
26540
26681
  state,
26541
26682
  log: log2
@@ -26563,12 +26704,15 @@ var createRuntimeHandlers = ({
26563
26704
  const parsed = parseRequestParams("initialize", raw);
26564
26705
  if (!parsed.ok) return sendError(id2, parsed.error);
26565
26706
  const params = parsed.params;
26566
- let resolvedTheme;
26707
+ let resolvedTui;
26567
26708
  const environment2 = state.effectiveEnvironment;
26568
26709
  if (isTuiLocalEnvironment(environment2)) {
26569
26710
  try {
26570
26711
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
26571
- resolvedTheme = (await resolveEnvironmentTuiConfig(state, workingDir)).theme;
26712
+ const loaded = await resolveEnvironmentTuiConfig(state, workingDir);
26713
+ if (loaded.theme || loaded.color_scheme || loaded.image_protocol) {
26714
+ resolvedTui = loaded;
26715
+ }
26572
26716
  } catch (error) {
26573
26717
  log2(`initialize tui config load failed: ${String(error)}`);
26574
26718
  }
@@ -26607,7 +26751,7 @@ var createRuntimeHandlers = ({
26607
26751
  supports_run_cancel: true,
26608
26752
  supports_run_steer: true,
26609
26753
  supports_goals: Boolean(goalStore),
26610
- supports_run_diagnostics: true,
26754
+ supports_telemetry: true,
26611
26755
  supports_session_lifecycle: !!sessionStateStore.updateMetadata,
26612
26756
  supports_shell_exec: !!shellBackend,
26613
26757
  supports_shell_tasks: processEnabled,
@@ -26638,7 +26782,7 @@ var createRuntimeHandlers = ({
26638
26782
  supports_text_delta: true
26639
26783
  },
26640
26784
  ...localHost ? { local_host: localHost } : {},
26641
- ...localHost || resolvedTheme ? { tui: { theme: resolvedTheme, ...localHost } } : {}
26785
+ ...localHost || resolvedTui ? { tui: { ...resolvedTui, ...localHost } } : {}
26642
26786
  };
26643
26787
  sendRequestResult("initialize", id2, result);
26644
26788
  log2(`initialize from ${params.client?.name ?? "unknown"}`);
@@ -26656,7 +26800,7 @@ var createRuntimeHandlers = ({
26656
26800
  const handleThemeSet = async (id2, raw) => {
26657
26801
  if (state.activeRunId) {
26658
26802
  sendError(id2, {
26659
- code: RPC_ERROR_CODE21.RUNTIME_BUSY,
26803
+ code: RPC_ERROR_CODE22.RUNTIME_BUSY,
26660
26804
  message: "runtime busy"
26661
26805
  });
26662
26806
  return;
@@ -26666,14 +26810,14 @@ var createRuntimeHandlers = ({
26666
26810
  const name2 = parsed.params.name.trim().toLowerCase();
26667
26811
  if (!name2) {
26668
26812
  sendError(id2, {
26669
- code: RPC_ERROR_CODE21.INVALID_PARAMS,
26813
+ code: RPC_ERROR_CODE22.INVALID_PARAMS,
26670
26814
  message: "theme name is required"
26671
26815
  });
26672
26816
  return;
26673
26817
  }
26674
26818
  if (!SUPPORTED_TUI_THEMES.has(name2)) {
26675
26819
  sendError(id2, {
26676
- code: RPC_ERROR_CODE21.INVALID_PARAMS,
26820
+ code: RPC_ERROR_CODE22.INVALID_PARAMS,
26677
26821
  message: `unsupported theme: ${name2}`
26678
26822
  });
26679
26823
  return;
@@ -26689,7 +26833,7 @@ var createRuntimeHandlers = ({
26689
26833
  log2(`theme.set ${name2} scope=${target2.scope} path=${target2.path}`);
26690
26834
  } catch (error) {
26691
26835
  sendError(id2, {
26692
- code: RPC_ERROR_CODE21.RUNTIME_INTERNAL,
26836
+ code: RPC_ERROR_CODE22.RUNTIME_INTERNAL,
26693
26837
  message: String(error)
26694
26838
  });
26695
26839
  }
@@ -26710,7 +26854,7 @@ var createRuntimeHandlers = ({
26710
26854
  const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
26711
26855
  const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
26712
26856
  const rejectDisabled = (message) => sendError(req.id, {
26713
- code: RPC_ERROR_CODE21.INVALID_PARAMS,
26857
+ code: RPC_ERROR_CODE22.INVALID_PARAMS,
26714
26858
  message
26715
26859
  });
26716
26860
  switch (req.method) {
@@ -26935,13 +27079,18 @@ var createRuntimeHandlers = ({
26935
27079
  if (!parsed.ok) return sendError(req.id, parsed.error);
26936
27080
  return contextUsageHandlers.handleContextUsage(req.id);
26937
27081
  }
27082
+ case "telemetry.get": {
27083
+ const parsed = parseRequestParams("telemetry.get", req.params);
27084
+ if (!parsed.ok) return sendError(req.id, parsed.error);
27085
+ return telemetryHandlers.handleTelemetryGet(req.id);
27086
+ }
26938
27087
  case "theme.set":
26939
27088
  if (!themeSetEnabled)
26940
27089
  return rejectDisabled("theme setting is disabled");
26941
27090
  return handleThemeSet(req.id, req.params);
26942
27091
  default:
26943
27092
  return sendError(req.id, {
26944
- code: RPC_ERROR_CODE21.METHOD_NOT_FOUND,
27093
+ code: RPC_ERROR_CODE22.METHOD_NOT_FOUND,
26945
27094
  message: "method not found"
26946
27095
  });
26947
27096
  }
@@ -26969,7 +27118,7 @@ var createRuntimeHandlers = ({
26969
27118
  if (msg.jsonrpc !== "2.0" || "method" in msg && typeof msg.method !== "string") {
26970
27119
  if (id2 !== void 0) {
26971
27120
  sendError(id2, {
26972
- code: RPC_ERROR_CODE21.INVALID_REQUEST,
27121
+ code: RPC_ERROR_CODE22.INVALID_REQUEST,
26973
27122
  message: "invalid request"
26974
27123
  });
26975
27124
  } else {
@@ -26986,7 +27135,7 @@ var createRuntimeHandlers = ({
26986
27135
  if (invalid) {
26987
27136
  if (id2 !== void 0)
26988
27137
  sendError(id2, {
26989
- code: RPC_ERROR_CODE21.INVALID_PARAMS,
27138
+ code: RPC_ERROR_CODE22.INVALID_PARAMS,
26990
27139
  message: invalid
26991
27140
  });
26992
27141
  else log2(`invalid rpc notification: ${msg.method}`);
@@ -27000,7 +27149,7 @@ var createRuntimeHandlers = ({
27000
27149
  if (!hasRpcResponse(id2)) {
27001
27150
  try {
27002
27151
  sendError(id2, {
27003
- code: RPC_ERROR_CODE21.RUNTIME_INTERNAL,
27152
+ code: RPC_ERROR_CODE22.RUNTIME_INTERNAL,
27004
27153
  message: "internal runtime error"
27005
27154
  });
27006
27155
  } catch {
@@ -27025,7 +27174,7 @@ var createRuntimeHandlers = ({
27025
27174
  handleResponse(msg);
27026
27175
  } else if (id2 !== void 0) {
27027
27176
  sendError(id2, {
27028
- code: RPC_ERROR_CODE21.INVALID_REQUEST,
27177
+ code: RPC_ERROR_CODE22.INVALID_REQUEST,
27029
27178
  message: "invalid request"
27030
27179
  });
27031
27180
  } else {
@@ -27143,12 +27292,11 @@ var prepareProcess = (input, options, channel) => {
27143
27292
  cwd: input.workspace_root,
27144
27293
  detached: process.platform !== "win32",
27145
27294
  stdio: ["pipe", "pipe", "pipe", "pipe"],
27146
- // Provider logging can write raw credentials/payloads outside the child contract.
27295
+ // Debug/provider logging can write raw credentials/payloads outside the child contract.
27147
27296
  env: {
27148
27297
  ...process.env,
27149
- CODELIA_PROVIDER_LOG: "0",
27150
- CODELIA_DEBUG: "0",
27151
- CODELIA_DIAGNOSTICS: "0"
27298
+ CODELIA_DEBUG: "",
27299
+ CODELIA_DEBUG_DIR: ""
27152
27300
  }
27153
27301
  }
27154
27302
  );
@@ -27344,21 +27492,20 @@ function normalizeChildResult(result) {
27344
27492
  }
27345
27493
 
27346
27494
  // src/runtime.ts
27347
- var envTruthy2 = (value) => {
27348
- if (!value) return false;
27349
- const normalized = value.trim().toLowerCase();
27350
- return normalized === "1" || normalized === "true";
27351
- };
27352
27495
  var startRuntime = async (options = {}) => {
27353
27496
  const state = new RuntimeState();
27354
27497
  state.setRuntimeEnvironment(options);
27355
27498
  const environment = state.effectiveEnvironment;
27499
+ const sandboxModeStart = performance.now();
27356
27500
  state.sandboxMode = await resolveRuntimeSandboxMode(environment);
27501
+ state.telemetry.recordStartupPhase(
27502
+ "sandbox_mode",
27503
+ performance.now() - sandboxModeStart
27504
+ );
27357
27505
  if (state.sandboxMode.legacy === "full-access")
27358
27506
  log(
27359
27507
  "Legacy approval_mode full-access uses workspace-write. Specify --sandbox-mode full-access to disable OS isolation and keep command approval."
27360
27508
  );
27361
- state.diagnosticsEnabled = envTruthy2(process.env.CODELIA_DIAGNOSTICS);
27362
27509
  const workingDir = environment.workspace.root;
27363
27510
  if (workingDir) {
27364
27511
  state.runtimeWorkingDir = workingDir;
@@ -27368,15 +27515,22 @@ var startRuntime = async (options = {}) => {
27368
27515
  }
27369
27516
  state.attachments = createRuntimeAttachmentService(state);
27370
27517
  if (environment.context.projectInstructions === "from-workspace" && workingDir) {
27518
+ const agentsStart = performance.now();
27371
27519
  try {
27520
+ const agentsEnabled = environment.config.source === "disabled" ? true : await resolveAgentsEnabled(workingDir).catch(() => true);
27372
27521
  state.agentsResolver = await AgentsResolver.create(
27373
27522
  workingDir,
27374
- void 0,
27523
+ { enabled: agentsEnabled },
27375
27524
  void 0,
27376
27525
  await runtimeResourceReader(state, workingDir)
27377
27526
  );
27378
27527
  } catch (error) {
27379
27528
  log(`agents resolver startup init failed: ${String(error)}`);
27529
+ } finally {
27530
+ state.telemetry.recordStartupPhase(
27531
+ "agents_resolver",
27532
+ performance.now() - agentsStart
27533
+ );
27380
27534
  }
27381
27535
  }
27382
27536
  const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new SessionStateStoreImpl3({