@letta-ai/letta-code 0.34.41 → 0.34.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/mcp-client.js +2 -2
  2. package/dist/mcp-client.js.map +1 -1
  3. package/dist/mcp-oauth.js +2 -2
  4. package/dist/mcp-oauth.js.map +1 -1
  5. package/dist/types/agent/model.d.ts +17 -2
  6. package/dist/types/agent/model.d.ts.map +1 -1
  7. package/dist/types/backend/api/usage-cost.d.ts +8 -0
  8. package/dist/types/backend/api/usage-cost.d.ts.map +1 -0
  9. package/dist/types/backend/backend.d.ts.map +1 -1
  10. package/dist/types/backend/dev/provider-turn-executor.d.ts +3 -2
  11. package/dist/types/backend/dev/provider-turn-executor.d.ts.map +1 -1
  12. package/dist/types/backend/local/compaction.d.ts +9 -1
  13. package/dist/types/backend/local/compaction.d.ts.map +1 -1
  14. package/dist/types/backend/local/local-backend.d.ts +1 -1
  15. package/dist/types/backend/local/local-backend.d.ts.map +1 -1
  16. package/dist/types/permissions/checker.d.ts.map +1 -1
  17. package/dist/types/permissions/cross-agent-guard.d.ts.map +1 -1
  18. package/dist/types/permissions/file-path-args.d.ts +5 -0
  19. package/dist/types/permissions/file-path-args.d.ts.map +1 -0
  20. package/dist/types/permissions/matcher.d.ts.map +1 -1
  21. package/dist/types/permissions/workspace-sandbox.d.ts.map +1 -1
  22. package/dist/types/telemetry/index.d.ts +3 -1
  23. package/dist/types/telemetry/index.d.ts.map +1 -1
  24. package/dist/types/telemetry/permission-mode.d.ts +9 -0
  25. package/dist/types/telemetry/permission-mode.d.ts.map +1 -0
  26. package/dist/types/tools/manager.d.ts.map +1 -1
  27. package/dist/types/tools/toolset-catalog.d.ts +1 -1
  28. package/dist/types/tools/workflow/sdk-spawner.d.ts.map +1 -1
  29. package/dist/types/types/approval-classification-protocol.d.ts +2 -0
  30. package/dist/types/types/approval-classification-protocol.d.ts.map +1 -1
  31. package/dist/types/types/protocol.d.ts +6 -1
  32. package/dist/types/types/protocol.d.ts.map +1 -1
  33. package/dist/types/usage/cost.d.ts +24 -0
  34. package/dist/types/usage/cost.d.ts.map +1 -0
  35. package/dist/types/utils/file-path.d.ts +1 -1
  36. package/dist/types/utils/file-path.d.ts.map +1 -1
  37. package/letta.js +1148 -887
  38. package/npm-shrinkwrap.json +10 -10
  39. package/package.json +2 -2
  40. package/scripts/check-test-coverage.cjs +1 -0
  41. package/scripts/run-unit-tests.cjs +1 -0
  42. package/scripts/source-file-size-baseline.json +2 -2
  43. package/skills/image-generation/SKILL.md +135 -5
package/letta.js CHANGED
@@ -6077,7 +6077,7 @@ var package_default;
6077
6077
  var init_package = __esm(() => {
6078
6078
  package_default = {
6079
6079
  name: "@letta-ai/letta-code",
6080
- version: "0.34.41",
6080
+ version: "0.34.42",
6081
6081
  lettaStartupLogProtocol: 1,
6082
6082
  lettaConfigDirProtocol: 1,
6083
6083
  description: "Letta Code is a CLI tool for interacting with stateful Letta agents from the terminal.",
@@ -6355,7 +6355,7 @@ var init_package = __esm(() => {
6355
6355
  },
6356
6356
  lettaLifecycleProtocol: 1,
6357
6357
  lettaRuntimeGraphProtocol: 1,
6358
- lettaRuntimeGraphSha512: "sha512-gHcHVmklkUeqqpTVejsfApLCP0eRu1B5ylvQWamErORv3+Yv0gGllkDfjDkLE+WBPBI+eeQ6zn+iFUeQRLxmOg==",
6358
+ lettaRuntimeGraphSha512: "sha512-as/Tt/szwM5xbE6Ed+71tbFySlLxLNVCv+4uzwp7mhDTJsWMNeNtnlB+GCMMJmpIcmz6XVDriHNDctZ63hgj+Q==",
6359
6359
  patchedDependencies: {
6360
6360
  "@earendil-works/pi-ai@0.99.1": "patches/@earendil-works%2Fpi-ai@0.99.1.patch"
6361
6361
  }
@@ -6930,7 +6930,7 @@ class TelemetryManager {
6930
6930
  data: {
6931
6931
  ...data,
6932
6932
  session_id: this.sessionId,
6933
- agent_id: this.currentAgentId || undefined,
6933
+ agent_id: type === "permission_mode_changed" ? data.agent_id : this.currentAgentId || undefined,
6934
6934
  agent_origin: this.currentAgentOrigin || undefined,
6935
6935
  surface: this.surface,
6936
6936
  backend: resolveTelemetryBackend()
@@ -7064,6 +7064,9 @@ class TelemetryManager {
7064
7064
  platform: process.platform
7065
7065
  });
7066
7066
  }
7067
+ trackPermissionModeChanged(data) {
7068
+ this.track("permission_mode_changed", data);
7069
+ }
7067
7070
  trackError(errorType, errorMessage, context, options) {
7068
7071
  if (!this.isCloudUser()) {
7069
7072
  return;
@@ -99045,6 +99048,132 @@ var init_reflection_runs = __esm(() => {
99045
99048
  init_strip_ansi();
99046
99049
  });
99047
99050
 
99051
+ // src/usage/cost.ts
99052
+ function resolveCostModel(handle) {
99053
+ const slash = handle.indexOf("/");
99054
+ if (slash < 1)
99055
+ return;
99056
+ const provider = handle.slice(0, slash);
99057
+ return catalog.getModel(providerAliases[provider] ?? provider, handle.slice(slash + 1));
99058
+ }
99059
+ function calculateUsageCost(model, usage) {
99060
+ const rawProvider = typeof model === "string" ? model.split("/")[0] : model?.provider;
99061
+ const provider = rawProvider ? providerAliases[rawProvider] ?? rawProvider : undefined;
99062
+ if (provider && ["ollama", "lmstudio", "llama-cpp"].includes(provider))
99063
+ return 0;
99064
+ const resolved2 = typeof model === "string" ? resolveCostModel(model) : model;
99065
+ if (!resolved2)
99066
+ return null;
99067
+ if (![resolved2.cost, ...resolved2.cost.tiers ?? []].some((rates) => [rates.input, rates.output, rates.cacheRead, rates.cacheWrite].some((rate) => rate > 0)))
99068
+ return null;
99069
+ const counts = [
99070
+ usage.input,
99071
+ usage.output,
99072
+ usage.cacheRead ?? 0,
99073
+ usage.cacheWrite ?? 0,
99074
+ usage.cacheWrite1h ?? 0,
99075
+ usage.reasoningSeparate ?? 0
99076
+ ];
99077
+ if (counts.some((count) => !Number.isFinite(count) || count < 0) || (usage.cacheWrite1h ?? 0) > (usage.cacheWrite ?? 0))
99078
+ return null;
99079
+ const cost = calculateCost(resolved2, {
99080
+ input: usage.input,
99081
+ output: usage.output + (usage.reasoningSeparate ?? 0),
99082
+ cacheRead: usage.cacheRead ?? 0,
99083
+ cacheWrite: usage.cacheWrite ?? 0,
99084
+ cacheWrite1h: usage.cacheWrite1h,
99085
+ totalTokens: 0,
99086
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
99087
+ }).total;
99088
+ return Number.isFinite(cost) && cost >= 0 ? cost : null;
99089
+ }
99090
+ function priceUsageEvent(event, model) {
99091
+ if (event.message_type !== "usage_statistics")
99092
+ return event;
99093
+ const fields = event;
99094
+ const count = (key, fallback = 0) => fields[key] == null ? fallback : typeof fields[key] === "number" ? fields[key] : Number.NaN;
99095
+ const prompt = count("prompt_tokens", Number.NaN);
99096
+ const output = count("completion_tokens", Number.NaN);
99097
+ const cacheRead = count("cached_input_tokens");
99098
+ const cacheWrite = count("cache_write_tokens");
99099
+ const total = count("total_tokens", Number.NaN);
99100
+ const cached = cacheRead + cacheWrite;
99101
+ let input = prompt;
99102
+ if (cached > 0) {
99103
+ if (total === prompt + output)
99104
+ input -= cached;
99105
+ else if (total !== prompt + output + cached)
99106
+ input = Number.NaN;
99107
+ }
99108
+ return {
99109
+ ...event,
99110
+ api_cost_usd: calculateUsageCost(model, {
99111
+ input,
99112
+ output,
99113
+ cacheRead,
99114
+ cacheWrite,
99115
+ cacheWrite1h: count("cache_write_1h_tokens")
99116
+ })
99117
+ };
99118
+ }
99119
+ var catalog, providerAliases;
99120
+ var init_cost = __esm(() => {
99121
+ init_dist2();
99122
+ init_all();
99123
+ catalog = builtinModels();
99124
+ providerAliases = {
99125
+ google_ai: "google",
99126
+ "google-ai": "google",
99127
+ google_vertex: "google-vertex",
99128
+ bedrock: "amazon-bedrock",
99129
+ "openai-responses": "openai",
99130
+ "chatgpt-plus-pro": "openai-codex",
99131
+ chatgpt_oauth: "openai-codex",
99132
+ moonshot: "moonshotai",
99133
+ "kimi-code": "kimi-coding",
99134
+ moonshot_coding: "kimi-coding",
99135
+ "zai-coding": "zai",
99136
+ azure: "azure-openai-responses",
99137
+ zai_coding: "zai",
99138
+ "llama.cpp": "llama-cpp"
99139
+ };
99140
+ });
99141
+
99142
+ // src/backend/api/usage-cost.ts
99143
+ async function conversationCostModel(client, conversationId, agentId, overrideModel) {
99144
+ if (overrideModel)
99145
+ return overrideModel;
99146
+ if (conversationId !== "default") {
99147
+ const conversation = await client.conversations.retrieve(conversationId);
99148
+ if (conversation.model)
99149
+ return conversation.model;
99150
+ agentId = conversation.agent_id;
99151
+ }
99152
+ if (!agentId)
99153
+ return null;
99154
+ const agent = await client.agents.retrieve(agentId);
99155
+ return agent.model ?? agent.llm_config?.handle ?? null;
99156
+ }
99157
+ function withClientUsageCost(stream11, resolveModel) {
99158
+ if (typeof stream11?.[Symbol.asyncIterator] !== "function")
99159
+ return;
99160
+ const iterate = stream11[Symbol.asyncIterator].bind(stream11);
99161
+ let model;
99162
+ stream11[Symbol.asyncIterator] = async function* () {
99163
+ for await (const event of { [Symbol.asyncIterator]: iterate }) {
99164
+ if (event.message_type !== "usage_statistics") {
99165
+ yield event;
99166
+ continue;
99167
+ }
99168
+ model ??= resolveModel().catch(() => null);
99169
+ yield priceUsageEvent(event, await model);
99170
+ }
99171
+ };
99172
+ }
99173
+ var init_usage_cost = __esm(() => {
99174
+ init_cost();
99175
+ });
99176
+
99048
99177
  // src/backend/backend-mode.ts
99049
99178
  function resolveBackendMode() {
99050
99179
  return configuredBackendMode ?? (isLocalBackendEnvEnabled() ? "local" : "api");
@@ -102980,14 +103109,14 @@ var init_memfs_git_proxy = __esm(() => {
102980
103109
  // src/utils/file-path.ts
102981
103110
  import * as os2 from "node:os";
102982
103111
  import * as path7 from "node:path";
102983
- function expandFilePath(filePath, userCwd) {
103112
+ function expandFilePath(filePath, userCwd, env4 = process.env, homeDir = os2.homedir()) {
102984
103113
  let expanded = filePath;
102985
103114
  if (expanded === "~" || expanded.startsWith("~/")) {
102986
- expanded = path7.join(os2.homedir(), expanded.slice(1));
103115
+ expanded = path7.join(homeDir, expanded.slice(1));
102987
103116
  }
102988
103117
  expanded = expanded.replace(/\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (match2, braced, unbraced) => {
102989
103118
  const name = braced ?? unbraced ?? "";
102990
- return process.env[name] ?? match2;
103119
+ return env4[name] ?? match2;
102991
103120
  });
102992
103121
  return path7.isAbsolute(expanded) ? expanded : path7.resolve(userCwd, expanded);
102993
103122
  }
@@ -106094,7 +106223,6 @@ var init_model_handles = __esm(() => {
106094
106223
  var exports_model = {};
106095
106224
  __export(exports_model, {
106096
106225
  withReasoningEffortUpdateArg: () => withReasoningEffortUpdateArg,
106097
- shouldPreserveContextWindowForModelSelection: () => shouldPreserveContextWindowForModelSelection,
106098
106226
  resolveModelHandleFromLlmConfig: () => resolveModelHandleFromLlmConfig,
106099
106227
  resolveModelByLlmConfig: () => resolveModelByLlmConfig,
106100
106228
  resolveModel: () => resolveModel,
@@ -106121,6 +106249,7 @@ __export(exports_model, {
106121
106249
  getChatGptFastRegistryHandleForModelHandle: () => getChatGptFastRegistryHandleForModelHandle,
106122
106250
  getByokOpenAIReasoningTierOptions: () => getByokOpenAIReasoningTierOptions,
106123
106251
  formatAvailableModels: () => formatAvailableModels,
106252
+ contextWindowToPreserveForModelSelection: () => contextWindowToPreserveForModelSelection,
106124
106253
  LEGACY_SERVER_CONTEXT_WINDOW_CLAMP: () => LEGACY_SERVER_CONTEXT_WINDOW_CLAMP,
106125
106254
  CHATGPT_FAST_SERVICE_TIER: () => CHATGPT_FAST_SERVICE_TIER
106126
106255
  });
@@ -106290,7 +106419,10 @@ function preservableContextWindow(current, modelHandle) {
106290
106419
  const matchesPreset = models2.some((m2) => m2.handle === registryHandle && m2.updateArgs?.context_window === LEGACY_SERVER_CONTEXT_WINDOW_CLAMP);
106291
106420
  return matchesPreset ? current : undefined;
106292
106421
  }
106293
- function shouldPreserveContextWindowForModelSelection(input) {
106422
+ function contextWindowToPreserveForModelSelection(input) {
106423
+ return isSameVariantModelSelection(input) ? preservableContextWindow(input.currentLlmConfig?.context_window, input.selectedModelHandle) : undefined;
106424
+ }
106425
+ function isSameVariantModelSelection(input) {
106294
106426
  const currentRegistryModelHandle = normalizeModelHandleForRegistry(input.currentModelHandle ?? buildModelHandleFromConfig(input.currentLlmConfig));
106295
106427
  const selectedRegistryModelHandle = normalizeModelHandleForRegistry(input.selectedModelHandle);
106296
106428
  if (selectedRegistryModelHandle === null || selectedRegistryModelHandle !== currentRegistryModelHandle) {
@@ -116070,357 +116202,6 @@ var init_pi_models_runtime = __esm(() => {
116070
116202
  ]);
116071
116203
  });
116072
116204
 
116073
- // src/backend/dev/pi-model-factory.ts
116074
- import { validateHeaderValue as validateHeaderValue2 } from "node:http";
116075
- function isUnselectedLocalModelHandle(model) {
116076
- return typeof model !== "string" || model.length === 0 || model === "auto" || model === UNSELECTED_LOCAL_MODEL_HANDLE || model.startsWith("letta/");
116077
- }
116078
- function normalizeOpenAICompatibleLocalModelHandle(model) {
116079
- if (!model?.startsWith("openai/"))
116080
- return model;
116081
- const nestedHandle = model.slice("openai/".length);
116082
- const nestedProvider = resolveProviderFromModelHandle(nestedHandle);
116083
- if (!nestedProvider)
116084
- return model;
116085
- return getPiProviderSpec(nestedProvider).localModelDiscovery === "openai-compatible" ? nestedHandle : model;
116086
- }
116087
- function settingString(value) {
116088
- return typeof value === "string" && value.length > 0 ? value : undefined;
116089
- }
116090
- function thinkingLevelSetting(value, preserveMax) {
116091
- const effort = settingString(value);
116092
- if (effort === "max")
116093
- return preserveMax ? "max" : "xhigh";
116094
- if (effort === "none")
116095
- return "none";
116096
- return effort === "minimal" || effort === "low" || effort === "medium" || effort === "high" || effort === "xhigh" ? effort : undefined;
116097
- }
116098
- function modelIdFromHandle(modelHandle) {
116099
- if (!modelHandle)
116100
- return;
116101
- return modelHandle.slice(modelHandle.indexOf("/") + 1);
116102
- }
116103
- function alwaysOnZaiThinking(modelId) {
116104
- return modelId === "glm-5.3" || modelId === "glm-5-turbo" || modelId === "glm-5.2-highspeed";
116105
- }
116106
- function reasoningForSettings(modelSettings, modelHandle, model) {
116107
- const thinking = isRecord2(modelSettings.thinking) ? modelSettings.thinking : undefined;
116108
- const modelId = modelIdFromHandle(modelHandle);
116109
- const preserveMax = modelId?.startsWith("gpt-5.6") === true || modelId?.startsWith("gpt-6") === true;
116110
- const nestedReasoning = isRecord2(modelSettings.reasoning) ? modelSettings.reasoning : undefined;
116111
- const rawEffort = nestedReasoning?.reasoning_effort ?? modelSettings.effort ?? modelSettings.reasoning_effort;
116112
- const explicit = thinkingLevelSetting(normalizeReasoningEffortForModel(modelHandle, typeof rawEffort === "string" ? rawEffort : undefined), preserveMax);
116113
- if (alwaysOnZaiThinking(modelId)) {
116114
- return explicit === "medium" || explicit === "minimal" ? "low" : explicit ?? "low";
116115
- }
116116
- if (model?.provider === "openrouter" && model.thinkingLevelMap?.off === null) {
116117
- if (!explicit || explicit === "none")
116118
- return;
116119
- const clamped = clampThinkingLevel(model, explicit);
116120
- return clamped === "off" ? undefined : clamped;
116121
- }
116122
- if (thinking?.type === "disabled")
116123
- return;
116124
- return explicit;
116125
- }
116126
- function applyPiEnvOverrides(overrides) {
116127
- if (!overrides)
116128
- return () => {};
116129
- const previous = new Map;
116130
- for (const [key, value] of Object.entries(overrides)) {
116131
- previous.set(key, process.env[key]);
116132
- if (value === undefined) {
116133
- delete process.env[key];
116134
- } else {
116135
- process.env[key] = value;
116136
- }
116137
- }
116138
- return () => {
116139
- for (const [key, value] of previous) {
116140
- if (value === undefined) {
116141
- delete process.env[key];
116142
- } else {
116143
- process.env[key] = value;
116144
- }
116145
- }
116146
- };
116147
- }
116148
- function hasEnvValue2(value) {
116149
- return typeof value === "string" && value.length > 0;
116150
- }
116151
- function inferDefaultProviderFromStandardKeys() {
116152
- const hasOpenAIKey = hasEnvValue2(process.env.OPENAI_API_KEY);
116153
- const hasAnthropicKey = hasEnvValue2(process.env.ANTHROPIC_API_KEY);
116154
- if (!hasOpenAIKey && hasAnthropicKey)
116155
- return "anthropic";
116156
- return DEFAULT_PI_PROVIDER;
116157
- }
116158
- function resolvePiProvider(provider = process.env.LETTA_CODE_DEV_PI_PROVIDER ?? inferDefaultProviderFromStandardKeys()) {
116159
- if (isPiProvider(provider))
116160
- return provider;
116161
- if (getRegisteredPiProvider(provider))
116162
- return provider;
116163
- throw new Error(`Unknown pi provider "${provider}". Expected ${expectedPiProviderList()}.`);
116164
- }
116165
- function resolvePiProviderFromAgent(model, modelSettings = {}) {
116166
- const registeredProvider = resolveRegisteredPiProviderFromModelHandle(model);
116167
- if (registeredProvider)
116168
- return registeredProvider;
116169
- const handleProvider = resolveProviderFromModelHandle(model);
116170
- if (handleProvider)
116171
- return handleProvider;
116172
- const settingsProvider = resolveProviderFromProviderType(modelSettings.provider_type);
116173
- if (settingsProvider)
116174
- return settingsProvider;
116175
- if (model && !isUnselectedLocalModelHandle(model)) {
116176
- const slashIndex = model.indexOf("/");
116177
- if (slashIndex > 0) {
116178
- throw new Error(`Model provider "${model.slice(0, slashIndex)}" is not registered. Load or repair the provider mod, or choose another model with /model.`);
116179
- }
116180
- }
116181
- return resolvePiProvider();
116182
- }
116183
- function resolvePiModelFromAgent(model, provider) {
116184
- return stripProviderHandlePrefix(model, provider);
116185
- }
116186
- function localProviderRecord(providerNames, storageDir) {
116187
- for (const providerName of providerNames) {
116188
- const record4 = getLocalProviderRecordByName(providerName, storageDir);
116189
- if (record4)
116190
- return record4;
116191
- }
116192
- return null;
116193
- }
116194
- function localProviderConnection(providerNames, storageDir) {
116195
- const record4 = localProviderRecord(providerNames, storageDir);
116196
- return {
116197
- baseURL: record4?.base_url,
116198
- timeout: resolveLocalProviderTimeout({
116199
- configuredTimeout: record4?.timeout,
116200
- providerIds: providerNames
116201
- }),
116202
- ...record4 ? { record: record4 } : {}
116203
- };
116204
- }
116205
- function isZaiCodingBaseURL(baseURL) {
116206
- return typeof baseURL === "string" && baseURL.includes("/coding/");
116207
- }
116208
- function resolveZaiConnection(options) {
116209
- const regularRecord = localProviderRecord(["zai", LOCAL_ZAI_PROVIDER_NAME], options.storageDir);
116210
- const codingRecord = localProviderRecord(["zai_coding", LOCAL_ZAI_CODING_PROVIDER_NAME], options.storageDir);
116211
- const regularKey = localProviderApiKeyFromRecord(regularRecord) ?? process.env.ZAI_API_KEY ?? process.env.ZHIPU_API_KEY;
116212
- const codingKey = localProviderApiKeyFromRecord(codingRecord) ?? process.env.ZAI_CODING_API_KEY;
116213
- const regularConnection = {
116214
- providerName: "zai",
116215
- baseURL: regularRecord?.base_url ?? process.env.ZAI_BASE_URL ?? "https://api.z.ai/api/paas/v4",
116216
- apiKey: regularKey,
116217
- timeout: resolveLocalProviderTimeout({
116218
- configuredTimeout: regularRecord?.timeout,
116219
- providerIds: [LOCAL_ZAI_PROVIDER_NAME, "zai"]
116220
- })
116221
- };
116222
- const codingConnection = {
116223
- providerName: "zai-coding",
116224
- baseURL: codingRecord?.base_url ?? process.env.ZAI_CODING_BASE_URL ?? "https://api.z.ai/api/coding/paas/v4",
116225
- apiKey: codingKey,
116226
- timeout: resolveLocalProviderTimeout({
116227
- configuredTimeout: codingRecord?.timeout,
116228
- providerIds: [LOCAL_ZAI_CODING_PROVIDER_NAME, "zai-coding"]
116229
- })
116230
- };
116231
- const reuseRegularKeyOnCodingEndpoint = () => ({
116232
- ...codingConnection,
116233
- apiKey: regularKey,
116234
- timeout: regularConnection.timeout
116235
- });
116236
- const publishedWantsCoding = isZaiCodingBaseURL(options.publishedBaseURL);
116237
- const hasDedicatedCodingRecord = Boolean(codingKey);
116238
- if (options.preferredProviderType === "zai_coding" && codingKey) {
116239
- return codingConnection;
116240
- }
116241
- if (options.preferredProviderType === "zai" && regularKey) {
116242
- if (!hasDedicatedCodingRecord && publishedWantsCoding) {
116243
- return reuseRegularKeyOnCodingEndpoint();
116244
- }
116245
- return regularConnection;
116246
- }
116247
- if (codingKey)
116248
- return codingConnection;
116249
- if (regularKey) {
116250
- return publishedWantsCoding ? reuseRegularKeyOnCodingEndpoint() : regularConnection;
116251
- }
116252
- return codingConnection;
116253
- }
116254
- function fallbackCatalogModelId(provider, modelId) {
116255
- if (provider !== "openai")
116256
- return;
116257
- const withoutReleaseDate = modelId.replace(/-\d{4}-\d{2}-\d{2}$/, "");
116258
- return withoutReleaseDate === modelId ? undefined : withoutReleaseDate;
116259
- }
116260
- function withOverrides(model, overrides) {
116261
- return {
116262
- ...model,
116263
- ...overrides.baseURL ? { baseUrl: overrides.baseURL } : {},
116264
- ...overrides.headers ? { headers: { ...model.headers, ...overrides.headers } } : {},
116265
- ...overrides.contextWindow ? { contextWindow: overrides.contextWindow } : {},
116266
- ...overrides.maxTokens ? { maxTokens: overrides.maxTokens } : {}
116267
- };
116268
- }
116269
- function nonNullHeaders(headers) {
116270
- return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null));
116271
- }
116272
- function mergeHeaders3(...headers) {
116273
- const merged = {};
116274
- for (const header of headers) {
116275
- if (!header)
116276
- continue;
116277
- Object.assign(merged, header);
116278
- }
116279
- return Object.keys(merged).length > 0 ? merged : undefined;
116280
- }
116281
- function numericSetting(value) {
116282
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
116283
- }
116284
- function bedrockLocalProviderOptions(record4) {
116285
- if (!record4)
116286
- return {};
116287
- const providerOptions = {};
116288
- const envOverrides = {};
116289
- if (record4.region) {
116290
- providerOptions.region = record4.region;
116291
- envOverrides.AWS_REGION = record4.region;
116292
- envOverrides.AWS_DEFAULT_REGION = record4.region;
116293
- }
116294
- if (record4.profile) {
116295
- providerOptions.profile = record4.profile;
116296
- envOverrides.AWS_PROFILE = record4.profile;
116297
- }
116298
- if (record4.auth.type === "api" && record4.auth.key) {
116299
- if (record4.access_key) {
116300
- envOverrides.AWS_ACCESS_KEY_ID = record4.access_key;
116301
- envOverrides.AWS_SECRET_ACCESS_KEY = record4.auth.key;
116302
- } else {
116303
- providerOptions.bearerToken = record4.auth.key;
116304
- envOverrides.AWS_BEARER_TOKEN_BEDROCK = record4.auth.key;
116305
- }
116306
- }
116307
- return {
116308
- ...Object.keys(providerOptions).length > 0 ? { providerOptions } : {},
116309
- ...Object.keys(envOverrides).length > 0 ? { envOverrides } : {}
116310
- };
116311
- }
116312
- async function resolvePiModelForAgent(modelHandle, modelSettings = {}, options = {}) {
116313
- const concreteModelHandle = normalizeOpenAICompatibleLocalModelHandle(isUnselectedLocalModelHandle(modelHandle) ? undefined : modelHandle);
116314
- const provider = options.provider ? resolvePiProvider(options.provider) : resolvePiProviderFromAgent(concreteModelHandle, modelSettings);
116315
- const registeredProvider = getRegisteredPiProvider(provider);
116316
- const spec = isPiProvider(provider) ? getPiProviderSpec(provider) : undefined;
116317
- const modelId = options.model ?? (registeredProvider ? stripRegisteredProviderHandlePrefix(concreteModelHandle, provider) : undefined) ?? (spec ? resolvePiModelFromAgent(concreteModelHandle, spec.id) : undefined) ?? registeredProvider?.config.models?.[0]?.id ?? (spec?.defaultModel ? resolvePiModelFromAgent(spec.defaultModel, spec.id) : undefined) ?? process.env.LETTA_CODE_DEV_PI_MODEL ?? "";
116318
- const storageDir = options.localProviderAuthStorageDir;
116319
- const modelsRuntime = options.modelsRuntime ?? new LocalPiModelsRuntime({
116320
- ...storageDir ? { storageDir } : {}
116321
- });
116322
- const preferredProviderType = typeof modelSettings.provider_type === "string" ? modelSettings.provider_type : options.preferredProviderType;
116323
- const localNames = registeredProvider ? localNamesForProviderId(provider) : spec?.localProviderNames ?? [provider];
116324
- let connection = localProviderConnection(localNames, storageDir);
116325
- let baseURL = connection.baseURL ?? spec?.baseUrlEnv?.() ?? spec?.defaultBaseURL ?? registeredProvider?.config.baseUrl;
116326
- let headers = mergeHeaders3(spec?.headers?.());
116327
- let providerOptions;
116328
- let envOverrides;
116329
- let oauthCredentials;
116330
- if (!modelId) {
116331
- throw new Error(`No model selected for provider "${provider}". Choose an available model with /model.`);
116332
- }
116333
- const runtimeProviderId = registeredProvider ? provider : spec && modelsRuntime.isRuntimeManagedProvider(spec.id) ? spec.id : spec?.piProvider;
116334
- if (!runtimeProviderId) {
116335
- throw new Error(`Unknown model "${modelId}" for provider "${provider}". ` + "Register the provider with models before using it.");
116336
- }
116337
- const fallbackModelId = !registeredProvider && spec?.piProvider ? fallbackCatalogModelId(spec.piProvider, modelId) : undefined;
116338
- const { model: publishedModel, auth: authResult } = await modelsRuntime.resolveTurn(runtimeProviderId, modelId, fallbackModelId, options.abortSignal);
116339
- connection = {
116340
- ...connection,
116341
- apiKey: authResult?.auth.apiKey === LOCAL_PROVIDER_NO_API_KEY ? undefined : authResult?.auth.apiKey
116342
- };
116343
- if (authResult?.auth.baseUrl)
116344
- baseURL = authResult.auth.baseUrl;
116345
- if (authResult?.auth.headers) {
116346
- headers = mergeHeaders3(headers, nonNullHeaders(authResult.auth.headers));
116347
- }
116348
- if (connection.record?.auth.type === "oauth") {
116349
- const stored = await modelsRuntime.getStoredCredential(runtimeProviderId);
116350
- oauthCredentials = stored?.type === "oauth" ? stored : undefined;
116351
- }
116352
- if (provider === "zai") {
116353
- const zai = resolveZaiConnection({
116354
- storageDir,
116355
- preferredProviderType: preferredProviderType === "zai" || preferredProviderType === "zai_coding" ? preferredProviderType : undefined,
116356
- publishedBaseURL: publishedModel?.baseUrl
116357
- });
116358
- connection = {
116359
- apiKey: zai.apiKey,
116360
- baseURL: zai.baseURL,
116361
- timeout: zai.timeout
116362
- };
116363
- baseURL = zai.baseURL;
116364
- }
116365
- if (connection.apiKey) {
116366
- try {
116367
- validateHeaderValue2("Authorization", `Bearer ${connection.apiKey}`);
116368
- } catch {
116369
- throw new Error(`API key for ${provider} is not a valid header value. Reconnect this provider with /connect.`);
116370
- }
116371
- }
116372
- if (provider === "amazon-bedrock") {
116373
- const bedrock = bedrockLocalProviderOptions(connection.record);
116374
- providerOptions = bedrock.providerOptions;
116375
- envOverrides = bedrock.envOverrides;
116376
- }
116377
- if (!publishedModel) {
116378
- throw new Error(`Unknown model "${modelId}" for provider "${provider}". ` + "Choose an available model with /model.");
116379
- }
116380
- const hookedModel = oauthCredentials && registeredProvider?.config.oauth?.modifyModels ? registeredProvider.config.oauth.modifyModels([structuredClone(publishedModel)], oauthCredentials)[0] ?? publishedModel : publishedModel;
116381
- const configuredContextWindow = numericSetting(modelSettings.context_window_limit);
116382
- const isLocalOllama = modelsRuntime.isBuiltInLocalOllamaProvider(runtimeProviderId);
116383
- const contextWindow = configuredContextWindow && isLocalOllama ? Math.min(configuredContextWindow, hookedModel.contextWindow) : configuredContextWindow;
116384
- const configuredMaxTokens = numericSetting(modelSettings.max_tokens);
116385
- const maxTokens = isLocalOllama ? Math.min(configuredMaxTokens ?? hookedModel.maxTokens, contextWindow ?? hookedModel.contextWindow) : configuredMaxTokens;
116386
- const allowBaseUrlOverride = !registeredProvider && spec !== undefined && !modelsRuntime.isRuntimeManagedProvider(spec.id);
116387
- const overrides = {
116388
- ...allowBaseUrlOverride && baseURL && baseURL !== hookedModel.baseUrl ? { baseURL } : {},
116389
- ...contextWindow && contextWindow !== hookedModel.contextWindow ? { contextWindow } : {},
116390
- ...maxTokens && maxTokens !== hookedModel.maxTokens ? { maxTokens } : {}
116391
- };
116392
- const model = Object.keys(overrides).length > 0 ? withOverrides(hookedModel, overrides) : hookedModel;
116393
- return {
116394
- provider,
116395
- model,
116396
- apiKey: connection.apiKey,
116397
- timeout: connection.timeout,
116398
- headers,
116399
- providerOptions,
116400
- envOverrides
116401
- };
116402
- }
116403
- var DEFAULT_PI_PROVIDER = "openai", UNSELECTED_LOCAL_MODEL_HANDLE = "local/default";
116404
- var init_pi_model_factory = __esm(() => {
116405
- init_dist2();
116406
- init_local_pi_credential_store();
116407
- init_local_provider_auth_store();
116408
- init_local_provider_timeout();
116409
- init_openai_reasoning_effort();
116410
- init_pi_models_runtime();
116411
- init_pi_provider_mod_registry();
116412
- init_pi_provider_registry();
116413
- });
116414
-
116415
- // src/backend/dev/pi-request-headers.ts
116416
- function resolvePiRequestHeaders(input) {
116417
- return {
116418
- ...input.configuredHeaders,
116419
- "x-letta-request-kind": input.requestKind,
116420
- ...input.provider === "opencode-go" ? { "x-opencode-session": input.conversationId } : {}
116421
- };
116422
- }
116423
-
116424
116205
  // src/backend/local/local-context-estimate.ts
116425
116206
  function positiveUsageNumber(value) {
116426
116207
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
@@ -116544,6 +116325,662 @@ function estimateLocalContextTokens(messages) {
116544
116325
  }
116545
116326
  var IMAGE_TOKEN_ESTIMATE = 1200;
116546
116327
 
116328
+ // src/backend/dev/provider-turn-executor.ts
116329
+ var exports_provider_turn_executor = {};
116330
+ __export(exports_provider_turn_executor, {
116331
+ shouldCompactForContextPressure: () => shouldCompactForContextPressure,
116332
+ providerStreamPart: () => providerStreamPart,
116333
+ providerLocalMessage: () => providerLocalMessage,
116334
+ providerLettaChunk: () => providerLettaChunk,
116335
+ estimateProviderRequestBytes: () => estimateProviderRequestBytes,
116336
+ estimateProviderPromptFloorTokens: () => estimateProviderPromptFloorTokens,
116337
+ estimateProviderContextTokens: () => estimateProviderContextTokens,
116338
+ contextTokensFromUsage: () => contextTokensFromUsage,
116339
+ contextCompactionThreshold: () => contextCompactionThreshold,
116340
+ buildProviderTurnInput: () => buildProviderTurnInput,
116341
+ ProviderTurnExecutor: () => ProviderTurnExecutor
116342
+ });
116343
+ import { randomUUID as randomUUID10 } from "node:crypto";
116344
+ function providerStreamPart(part, model) {
116345
+ return { type: "provider-part", part, model };
116346
+ }
116347
+ function providerLocalMessage(message) {
116348
+ return { type: "local-message", message };
116349
+ }
116350
+ function providerLettaChunk(chunk) {
116351
+ return { type: "letta-chunk", chunk };
116352
+ }
116353
+
116354
+ class MissingProviderStreamAdapter {
116355
+ async* stream() {
116356
+ yield {
116357
+ type: "error",
116358
+ error: new Error("Provider turn adapter is not configured for this dev backend")
116359
+ };
116360
+ }
116361
+ }
116362
+ function bodyListField(body, key) {
116363
+ const value = body[key];
116364
+ return Array.isArray(value) ? value : [];
116365
+ }
116366
+ function buildProviderTurnInput(input) {
116367
+ return {
116368
+ conversationId: input.conversationId,
116369
+ agentId: input.agentId,
116370
+ agent: input.agent,
116371
+ systemPrompt: input.systemPrompt,
116372
+ midConversationSystemPrompt: input.midConversationSystemPrompt,
116373
+ body: input.body,
116374
+ history: input.history,
116375
+ uiMessages: input.uiMessages,
116376
+ clientTools: bodyListField(input.body, "client_tools"),
116377
+ clientSkills: bodyListField(input.body, "client_skills")
116378
+ };
116379
+ }
116380
+ function stringifyToolInput(input) {
116381
+ if (typeof input === "string")
116382
+ return input;
116383
+ return JSON.stringify(input ?? {});
116384
+ }
116385
+ function createLocalMessageChunk(message) {
116386
+ return markLocalStateChunkOnly(attachLocalMessage({ message_type: "local_message" }, message));
116387
+ }
116388
+ function createProviderErrorChunks(error4) {
116389
+ const info = normalizeLocalProviderError(error4);
116390
+ return [
116391
+ {
116392
+ message_type: "error_message",
116393
+ message: info.message,
116394
+ detail: info.detail,
116395
+ error_type: info.error_type,
116396
+ retryable: info.retryable
116397
+ },
116398
+ {
116399
+ message_type: "stop_reason",
116400
+ stop_reason: info.stop_reason
116401
+ }
116402
+ ];
116403
+ }
116404
+ function contextTokensFromUsage(usage) {
116405
+ return contextTokensFromLocalUsage(usage);
116406
+ }
116407
+ function estimateSerializedTokens(value) {
116408
+ if (value === undefined || value === null)
116409
+ return 0;
116410
+ try {
116411
+ const serialized = typeof value === "string" ? value : JSON.stringify(value) ?? "";
116412
+ return Math.ceil(serialized.length / 4);
116413
+ } catch {
116414
+ return 0;
116415
+ }
116416
+ }
116417
+ function estimateProviderContextTokens(input) {
116418
+ const contextEstimate = estimateLocalContextTokens(input.uiMessages);
116419
+ if (contextEstimate.lastUsageIndex !== null) {
116420
+ return contextEstimate.tokens > 0 ? contextEstimate.tokens : undefined;
116421
+ }
116422
+ const systemPromptTokens = estimateSerializedTokens(input.systemPrompt ?? input.agent.system);
116423
+ const messageTokens = contextEstimate.tokens;
116424
+ const toolTokens = estimateSerializedTokens(input.clientTools);
116425
+ const total = systemPromptTokens + messageTokens + toolTokens;
116426
+ return total > 0 ? total : undefined;
116427
+ }
116428
+ function estimateProviderPromptFloorTokens(input) {
116429
+ return estimateSerializedTokens(input.systemPrompt ?? input.agent.system) + estimateSerializedTokens(input.clientTools);
116430
+ }
116431
+ function contextCompactionThreshold(contextWindow) {
116432
+ if (typeof contextWindow !== "number" || !Number.isFinite(contextWindow) || contextWindow <= 0) {
116433
+ return;
116434
+ }
116435
+ const reserveTokens = Math.min(LOCAL_CONTEXT_COMPACTION_RESERVE_TOKENS, Math.max(1, Math.floor(contextWindow * LOCAL_SMALL_CONTEXT_COMPACTION_RESERVE_RATIO)));
116436
+ return Math.max(0, contextWindow - reserveTokens);
116437
+ }
116438
+ function shouldCompactForContextPressure(input) {
116439
+ const threshold = contextCompactionThreshold(input.contextWindow);
116440
+ return input.contextTokens !== undefined && threshold !== undefined && input.contextTokens > threshold;
116441
+ }
116442
+ function serializedLength(value) {
116443
+ if (value === undefined || value === null)
116444
+ return 0;
116445
+ try {
116446
+ const serialized = typeof value === "string" ? value : JSON.stringify(value) ?? "";
116447
+ return serialized.length;
116448
+ } catch {
116449
+ return 0;
116450
+ }
116451
+ }
116452
+ function estimateProviderRequestBytes(input) {
116453
+ const systemPromptBytes = serializedLength(input.systemPrompt ?? input.agent.system);
116454
+ const messageBytes = serializedLength(input.uiMessages);
116455
+ const toolBytes = serializedLength(input.clientTools);
116456
+ const total = systemPromptBytes + messageBytes + toolBytes;
116457
+ return total > 0 ? total : undefined;
116458
+ }
116459
+ function createUsageStatisticsChunk(usage, model, contextTokensEstimate) {
116460
+ const costUsd = usage ? calculateUsageCost(model, usage) : null;
116461
+ const promptTokens = usage?.input;
116462
+ const completionTokens = usage?.output;
116463
+ const totalTokens = usage?.totalTokens;
116464
+ const usageContextTokens = usage ? contextTokensFromUsage(usage) : undefined;
116465
+ const contextTokens = usageContextTokens ?? contextTokensEstimate;
116466
+ const cachedInputTokens = usage?.cacheRead;
116467
+ const cacheWriteTokens = usage?.cacheWrite;
116468
+ const reasoningTokens = usage?.reasoning;
116469
+ return {
116470
+ message_type: "usage_statistics",
116471
+ step_count: 1,
116472
+ api_cost_usd: costUsd,
116473
+ ...usage?.cacheWrite1h !== undefined ? { cache_write_1h_tokens: usage.cacheWrite1h } : {},
116474
+ ...promptTokens !== undefined ? { prompt_tokens: promptTokens } : {},
116475
+ ...completionTokens !== undefined ? { completion_tokens: completionTokens } : {},
116476
+ ...totalTokens !== undefined ? { total_tokens: totalTokens } : {},
116477
+ ...cachedInputTokens !== undefined ? { cached_input_tokens: cachedInputTokens } : {},
116478
+ ...cacheWriteTokens !== undefined ? { cache_write_tokens: cacheWriteTokens } : {},
116479
+ ...reasoningTokens !== undefined ? { reasoning_tokens: reasoningTokens } : {},
116480
+ ...contextTokens !== undefined ? { context_tokens: contextTokens } : {}
116481
+ };
116482
+ }
116483
+ function errorFromAssistantEvent(part) {
116484
+ if (part.type !== "error")
116485
+ return new Error("Unknown provider stream error");
116486
+ return new Error(part.error.errorMessage ?? "Unknown local provider error");
116487
+ }
116488
+ function contentMatchesMessageType(content, messageType) {
116489
+ if (!content || typeof content !== "object" || !("type" in content)) {
116490
+ return false;
116491
+ }
116492
+ return messageType === "assistant_message" ? content.type === "text" : content.type === "thinking";
116493
+ }
116494
+ function contiguousContentStartIndex(partial3, contentIndex, messageType) {
116495
+ let startIndex = contentIndex;
116496
+ while (startIndex > 0 && contentMatchesMessageType(partial3.content[startIndex - 1], messageType)) {
116497
+ startIndex -= 1;
116498
+ }
116499
+ if (messageType === "reasoning_message") {
116500
+ for (let index = startIndex;index <= contentIndex; index++) {
116501
+ const content = partial3.content[index];
116502
+ if (content?.type === "thinking" && content.thinking.length > 0) {
116503
+ return index;
116504
+ }
116505
+ }
116506
+ }
116507
+ return startIndex;
116508
+ }
116509
+ function projectsLocalOutput(content) {
116510
+ if (content.type === "text")
116511
+ return true;
116512
+ if (content.type === "thinking")
116513
+ return content.thinking.length > 0;
116514
+ return content.type === "toolCall" && typeof content.id === "string";
116515
+ }
116516
+ function identityForContentSegment(identities, prefix, contentIndex, partial3, messageType) {
116517
+ const contentStartIndex = contiguousContentStartIndex(partial3, contentIndex, messageType);
116518
+ const existing = identities.get(contentStartIndex);
116519
+ if (existing)
116520
+ return existing;
116521
+ const identity = {
116522
+ otid: `${prefix}-${contentStartIndex}-${randomUUID10()}`,
116523
+ contentStartIndex,
116524
+ useSourceMessageId: messageType === "assistant_message" && !partial3.content.slice(0, contentStartIndex).some(projectsLocalOutput)
116525
+ };
116526
+ identities.set(contentStartIndex, identity);
116527
+ return identity;
116528
+ }
116529
+ function createProviderLettaStream(events, contextTokensEstimate) {
116530
+ const controller = new AbortController;
116531
+ return {
116532
+ controller,
116533
+ async* [Symbol.asyncIterator]() {
116534
+ let sawToolCall = false;
116535
+ let pendingStopReason;
116536
+ let sawUsageStatistics = false;
116537
+ const assistantIdentities = new Map;
116538
+ const reasoningIdentities = new Map;
116539
+ try {
116540
+ for await (const event of events) {
116541
+ if (event.type === "error") {
116542
+ yield* createProviderErrorChunks(event.error);
116543
+ return;
116544
+ }
116545
+ if (event.type === "local-message") {
116546
+ yield createLocalMessageChunk(event.message);
116547
+ continue;
116548
+ }
116549
+ if (event.type === "letta-chunk") {
116550
+ yield event.chunk;
116551
+ continue;
116552
+ }
116553
+ const { part } = event;
116554
+ if (part.type === "text_delta") {
116555
+ const identity = identityForContentSegment(assistantIdentities, "provider-assistant", part.contentIndex, part.partial, "assistant_message");
116556
+ yield attachLocalSegmentIdentity({
116557
+ message_type: "assistant_message",
116558
+ otid: identity.otid,
116559
+ content: [{ type: "text", text: part.delta }]
116560
+ }, identity);
116561
+ continue;
116562
+ }
116563
+ if (part.type === "thinking_delta") {
116564
+ const identity = identityForContentSegment(reasoningIdentities, "provider-reasoning", part.contentIndex, part.partial, "reasoning_message");
116565
+ yield attachLocalSegmentIdentity({
116566
+ message_type: "reasoning_message",
116567
+ otid: identity.otid,
116568
+ reasoning: part.delta
116569
+ }, identity);
116570
+ continue;
116571
+ }
116572
+ if (part.type === "toolcall_end") {
116573
+ sawToolCall = true;
116574
+ yield {
116575
+ message_type: "approval_request_message",
116576
+ tool_call: {
116577
+ tool_call_id: part.toolCall.id,
116578
+ name: part.toolCall.name,
116579
+ arguments: stringifyToolInput(part.toolCall.arguments)
116580
+ }
116581
+ };
116582
+ continue;
116583
+ }
116584
+ if (part.type === "done") {
116585
+ if (!sawUsageStatistics) {
116586
+ sawUsageStatistics = true;
116587
+ yield createUsageStatisticsChunk(part.message.usage, event.model, contextTokensEstimate);
116588
+ }
116589
+ pendingStopReason = {
116590
+ message_type: "stop_reason",
116591
+ stop_reason: sawToolCall || part.reason === "toolUse" ? "requires_approval" : part.reason === "length" ? "max_tokens_exceeded" : "end_turn"
116592
+ };
116593
+ continue;
116594
+ }
116595
+ if (part.type === "error") {
116596
+ yield* createProviderErrorChunks(errorFromAssistantEvent(part));
116597
+ return;
116598
+ }
116599
+ }
116600
+ if (pendingStopReason) {
116601
+ yield pendingStopReason;
116602
+ } else if (sawToolCall) {
116603
+ yield {
116604
+ message_type: "stop_reason",
116605
+ stop_reason: "requires_approval"
116606
+ };
116607
+ }
116608
+ } catch (error4) {
116609
+ yield* createProviderErrorChunks(error4);
116610
+ }
116611
+ }
116612
+ };
116613
+ }
116614
+
116615
+ class ProviderTurnExecutor {
116616
+ adapter;
116617
+ constructor(adapter = new MissingProviderStreamAdapter) {
116618
+ this.adapter = adapter;
116619
+ }
116620
+ async execute(input) {
116621
+ const providerInput = buildProviderTurnInput(input);
116622
+ const events = await this.adapter.stream(providerInput);
116623
+ return createProviderLettaStream(events, estimateProviderContextTokens(providerInput));
116624
+ }
116625
+ }
116626
+ var LOCAL_CONTEXT_COMPACTION_RESERVE_TOKENS = 16384, LOCAL_SMALL_CONTEXT_COMPACTION_RESERVE_RATIO = 0.2;
116627
+ var init_provider_turn_executor = __esm(() => {
116628
+ init_local_stream_chunks();
116629
+ init_cost();
116630
+ init_local_provider_errors();
116631
+ });
116632
+
116633
+ // src/backend/dev/pi-model-factory.ts
116634
+ import { validateHeaderValue as validateHeaderValue2 } from "node:http";
116635
+ function isUnselectedLocalModelHandle(model) {
116636
+ return typeof model !== "string" || model.length === 0 || model === "auto" || model === UNSELECTED_LOCAL_MODEL_HANDLE || model.startsWith("letta/");
116637
+ }
116638
+ function normalizeOpenAICompatibleLocalModelHandle(model) {
116639
+ if (!model?.startsWith("openai/"))
116640
+ return model;
116641
+ const nestedHandle = model.slice("openai/".length);
116642
+ const nestedProvider = resolveProviderFromModelHandle(nestedHandle);
116643
+ if (!nestedProvider)
116644
+ return model;
116645
+ return getPiProviderSpec(nestedProvider).localModelDiscovery === "openai-compatible" ? nestedHandle : model;
116646
+ }
116647
+ function settingString(value) {
116648
+ return typeof value === "string" && value.length > 0 ? value : undefined;
116649
+ }
116650
+ function thinkingLevelSetting(value, preserveMax) {
116651
+ const effort = settingString(value);
116652
+ if (effort === "max")
116653
+ return preserveMax ? "max" : "xhigh";
116654
+ if (effort === "none")
116655
+ return "none";
116656
+ return effort === "minimal" || effort === "low" || effort === "medium" || effort === "high" || effort === "xhigh" ? effort : undefined;
116657
+ }
116658
+ function modelIdFromHandle(modelHandle) {
116659
+ if (!modelHandle)
116660
+ return;
116661
+ return modelHandle.slice(modelHandle.indexOf("/") + 1);
116662
+ }
116663
+ function alwaysOnZaiThinking(modelId) {
116664
+ return modelId === "glm-5.3" || modelId === "glm-5-turbo" || modelId === "glm-5.2-highspeed";
116665
+ }
116666
+ function reasoningForSettings(modelSettings, modelHandle, model) {
116667
+ const thinking = isRecord2(modelSettings.thinking) ? modelSettings.thinking : undefined;
116668
+ const modelId = modelIdFromHandle(modelHandle);
116669
+ const preserveMax = modelId?.startsWith("gpt-5.6") === true || modelId?.startsWith("gpt-6") === true;
116670
+ const nestedReasoning = isRecord2(modelSettings.reasoning) ? modelSettings.reasoning : undefined;
116671
+ const rawEffort = nestedReasoning?.reasoning_effort ?? modelSettings.effort ?? modelSettings.reasoning_effort;
116672
+ const explicit = thinkingLevelSetting(normalizeReasoningEffortForModel(modelHandle, typeof rawEffort === "string" ? rawEffort : undefined), preserveMax);
116673
+ if (alwaysOnZaiThinking(modelId)) {
116674
+ return explicit === "medium" || explicit === "minimal" ? "low" : explicit ?? "low";
116675
+ }
116676
+ if (model?.provider === "openrouter" && model.thinkingLevelMap?.off === null) {
116677
+ if (!explicit || explicit === "none")
116678
+ return;
116679
+ const clamped = clampThinkingLevel(model, explicit);
116680
+ return clamped === "off" ? undefined : clamped;
116681
+ }
116682
+ if (thinking?.type === "disabled")
116683
+ return;
116684
+ return explicit;
116685
+ }
116686
+ function applyPiEnvOverrides(overrides) {
116687
+ if (!overrides)
116688
+ return () => {};
116689
+ const previous = new Map;
116690
+ for (const [key, value] of Object.entries(overrides)) {
116691
+ previous.set(key, process.env[key]);
116692
+ if (value === undefined) {
116693
+ delete process.env[key];
116694
+ } else {
116695
+ process.env[key] = value;
116696
+ }
116697
+ }
116698
+ return () => {
116699
+ for (const [key, value] of previous) {
116700
+ if (value === undefined) {
116701
+ delete process.env[key];
116702
+ } else {
116703
+ process.env[key] = value;
116704
+ }
116705
+ }
116706
+ };
116707
+ }
116708
+ function hasEnvValue2(value) {
116709
+ return typeof value === "string" && value.length > 0;
116710
+ }
116711
+ function inferDefaultProviderFromStandardKeys() {
116712
+ const hasOpenAIKey = hasEnvValue2(process.env.OPENAI_API_KEY);
116713
+ const hasAnthropicKey = hasEnvValue2(process.env.ANTHROPIC_API_KEY);
116714
+ if (!hasOpenAIKey && hasAnthropicKey)
116715
+ return "anthropic";
116716
+ return DEFAULT_PI_PROVIDER;
116717
+ }
116718
+ function resolvePiProvider(provider = process.env.LETTA_CODE_DEV_PI_PROVIDER ?? inferDefaultProviderFromStandardKeys()) {
116719
+ if (isPiProvider(provider))
116720
+ return provider;
116721
+ if (getRegisteredPiProvider(provider))
116722
+ return provider;
116723
+ throw new Error(`Unknown pi provider "${provider}". Expected ${expectedPiProviderList()}.`);
116724
+ }
116725
+ function resolvePiProviderFromAgent(model, modelSettings = {}) {
116726
+ const registeredProvider = resolveRegisteredPiProviderFromModelHandle(model);
116727
+ if (registeredProvider)
116728
+ return registeredProvider;
116729
+ const handleProvider = resolveProviderFromModelHandle(model);
116730
+ if (handleProvider)
116731
+ return handleProvider;
116732
+ const settingsProvider = resolveProviderFromProviderType(modelSettings.provider_type);
116733
+ if (settingsProvider)
116734
+ return settingsProvider;
116735
+ if (model && !isUnselectedLocalModelHandle(model)) {
116736
+ const slashIndex = model.indexOf("/");
116737
+ if (slashIndex > 0) {
116738
+ throw new Error(`Model provider "${model.slice(0, slashIndex)}" is not registered. Load or repair the provider mod, or choose another model with /model.`);
116739
+ }
116740
+ }
116741
+ return resolvePiProvider();
116742
+ }
116743
+ function resolvePiModelFromAgent(model, provider) {
116744
+ return stripProviderHandlePrefix(model, provider);
116745
+ }
116746
+ function localProviderRecord(providerNames, storageDir) {
116747
+ for (const providerName of providerNames) {
116748
+ const record4 = getLocalProviderRecordByName(providerName, storageDir);
116749
+ if (record4)
116750
+ return record4;
116751
+ }
116752
+ return null;
116753
+ }
116754
+ function localProviderConnection(providerNames, storageDir) {
116755
+ const record4 = localProviderRecord(providerNames, storageDir);
116756
+ return {
116757
+ baseURL: record4?.base_url,
116758
+ timeout: resolveLocalProviderTimeout({
116759
+ configuredTimeout: record4?.timeout,
116760
+ providerIds: providerNames
116761
+ }),
116762
+ ...record4 ? { record: record4 } : {}
116763
+ };
116764
+ }
116765
+ function isZaiCodingBaseURL(baseURL) {
116766
+ return typeof baseURL === "string" && baseURL.includes("/coding/");
116767
+ }
116768
+ function resolveZaiConnection(options) {
116769
+ const regularRecord = localProviderRecord(["zai", LOCAL_ZAI_PROVIDER_NAME], options.storageDir);
116770
+ const codingRecord = localProviderRecord(["zai_coding", LOCAL_ZAI_CODING_PROVIDER_NAME], options.storageDir);
116771
+ const regularKey = localProviderApiKeyFromRecord(regularRecord) ?? process.env.ZAI_API_KEY ?? process.env.ZHIPU_API_KEY;
116772
+ const codingKey = localProviderApiKeyFromRecord(codingRecord) ?? process.env.ZAI_CODING_API_KEY;
116773
+ const regularConnection = {
116774
+ providerName: "zai",
116775
+ baseURL: regularRecord?.base_url ?? process.env.ZAI_BASE_URL ?? "https://api.z.ai/api/paas/v4",
116776
+ apiKey: regularKey,
116777
+ timeout: resolveLocalProviderTimeout({
116778
+ configuredTimeout: regularRecord?.timeout,
116779
+ providerIds: [LOCAL_ZAI_PROVIDER_NAME, "zai"]
116780
+ })
116781
+ };
116782
+ const codingConnection = {
116783
+ providerName: "zai-coding",
116784
+ baseURL: codingRecord?.base_url ?? process.env.ZAI_CODING_BASE_URL ?? "https://api.z.ai/api/coding/paas/v4",
116785
+ apiKey: codingKey,
116786
+ timeout: resolveLocalProviderTimeout({
116787
+ configuredTimeout: codingRecord?.timeout,
116788
+ providerIds: [LOCAL_ZAI_CODING_PROVIDER_NAME, "zai-coding"]
116789
+ })
116790
+ };
116791
+ const reuseRegularKeyOnCodingEndpoint = () => ({
116792
+ ...codingConnection,
116793
+ apiKey: regularKey,
116794
+ timeout: regularConnection.timeout
116795
+ });
116796
+ const publishedWantsCoding = isZaiCodingBaseURL(options.publishedBaseURL);
116797
+ const hasDedicatedCodingRecord = Boolean(codingKey);
116798
+ if (options.preferredProviderType === "zai_coding" && codingKey) {
116799
+ return codingConnection;
116800
+ }
116801
+ if (options.preferredProviderType === "zai" && regularKey) {
116802
+ if (!hasDedicatedCodingRecord && publishedWantsCoding) {
116803
+ return reuseRegularKeyOnCodingEndpoint();
116804
+ }
116805
+ return regularConnection;
116806
+ }
116807
+ if (codingKey)
116808
+ return codingConnection;
116809
+ if (regularKey) {
116810
+ return publishedWantsCoding ? reuseRegularKeyOnCodingEndpoint() : regularConnection;
116811
+ }
116812
+ return codingConnection;
116813
+ }
116814
+ function fallbackCatalogModelId(provider, modelId) {
116815
+ if (provider !== "openai")
116816
+ return;
116817
+ const withoutReleaseDate = modelId.replace(/-\d{4}-\d{2}-\d{2}$/, "");
116818
+ return withoutReleaseDate === modelId ? undefined : withoutReleaseDate;
116819
+ }
116820
+ function withOverrides(model, overrides) {
116821
+ return {
116822
+ ...model,
116823
+ ...overrides.baseURL ? { baseUrl: overrides.baseURL } : {},
116824
+ ...overrides.headers ? { headers: { ...model.headers, ...overrides.headers } } : {},
116825
+ ...overrides.contextWindow ? { contextWindow: overrides.contextWindow } : {},
116826
+ ...overrides.maxTokens ? { maxTokens: overrides.maxTokens } : {}
116827
+ };
116828
+ }
116829
+ function nonNullHeaders(headers) {
116830
+ return Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null));
116831
+ }
116832
+ function mergeHeaders3(...headers) {
116833
+ const merged = {};
116834
+ for (const header of headers) {
116835
+ if (!header)
116836
+ continue;
116837
+ Object.assign(merged, header);
116838
+ }
116839
+ return Object.keys(merged).length > 0 ? merged : undefined;
116840
+ }
116841
+ function numericSetting(value) {
116842
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
116843
+ }
116844
+ function bedrockLocalProviderOptions(record4) {
116845
+ if (!record4)
116846
+ return {};
116847
+ const providerOptions = {};
116848
+ const envOverrides = {};
116849
+ if (record4.region) {
116850
+ providerOptions.region = record4.region;
116851
+ envOverrides.AWS_REGION = record4.region;
116852
+ envOverrides.AWS_DEFAULT_REGION = record4.region;
116853
+ }
116854
+ if (record4.profile) {
116855
+ providerOptions.profile = record4.profile;
116856
+ envOverrides.AWS_PROFILE = record4.profile;
116857
+ }
116858
+ if (record4.auth.type === "api" && record4.auth.key) {
116859
+ if (record4.access_key) {
116860
+ envOverrides.AWS_ACCESS_KEY_ID = record4.access_key;
116861
+ envOverrides.AWS_SECRET_ACCESS_KEY = record4.auth.key;
116862
+ } else {
116863
+ providerOptions.bearerToken = record4.auth.key;
116864
+ envOverrides.AWS_BEARER_TOKEN_BEDROCK = record4.auth.key;
116865
+ }
116866
+ }
116867
+ return {
116868
+ ...Object.keys(providerOptions).length > 0 ? { providerOptions } : {},
116869
+ ...Object.keys(envOverrides).length > 0 ? { envOverrides } : {}
116870
+ };
116871
+ }
116872
+ async function resolvePiModelForAgent(modelHandle, modelSettings = {}, options = {}) {
116873
+ const concreteModelHandle = normalizeOpenAICompatibleLocalModelHandle(isUnselectedLocalModelHandle(modelHandle) ? undefined : modelHandle);
116874
+ const provider = options.provider ? resolvePiProvider(options.provider) : resolvePiProviderFromAgent(concreteModelHandle, modelSettings);
116875
+ const registeredProvider = getRegisteredPiProvider(provider);
116876
+ const spec = isPiProvider(provider) ? getPiProviderSpec(provider) : undefined;
116877
+ const modelId = options.model ?? (registeredProvider ? stripRegisteredProviderHandlePrefix(concreteModelHandle, provider) : undefined) ?? (spec ? resolvePiModelFromAgent(concreteModelHandle, spec.id) : undefined) ?? registeredProvider?.config.models?.[0]?.id ?? (spec?.defaultModel ? resolvePiModelFromAgent(spec.defaultModel, spec.id) : undefined) ?? process.env.LETTA_CODE_DEV_PI_MODEL ?? "";
116878
+ const storageDir = options.localProviderAuthStorageDir;
116879
+ const modelsRuntime = options.modelsRuntime ?? new LocalPiModelsRuntime({
116880
+ ...storageDir ? { storageDir } : {}
116881
+ });
116882
+ const preferredProviderType = typeof modelSettings.provider_type === "string" ? modelSettings.provider_type : options.preferredProviderType;
116883
+ const localNames = registeredProvider ? localNamesForProviderId(provider) : spec?.localProviderNames ?? [provider];
116884
+ let connection = localProviderConnection(localNames, storageDir);
116885
+ let baseURL = connection.baseURL ?? spec?.baseUrlEnv?.() ?? spec?.defaultBaseURL ?? registeredProvider?.config.baseUrl;
116886
+ let headers = mergeHeaders3(spec?.headers?.());
116887
+ let providerOptions;
116888
+ let envOverrides;
116889
+ let oauthCredentials;
116890
+ if (!modelId) {
116891
+ throw new Error(`No model selected for provider "${provider}". Choose an available model with /model.`);
116892
+ }
116893
+ const runtimeProviderId = registeredProvider ? provider : spec && modelsRuntime.isRuntimeManagedProvider(spec.id) ? spec.id : spec?.piProvider;
116894
+ if (!runtimeProviderId) {
116895
+ throw new Error(`Unknown model "${modelId}" for provider "${provider}". ` + "Register the provider with models before using it.");
116896
+ }
116897
+ const fallbackModelId = !registeredProvider && spec?.piProvider ? fallbackCatalogModelId(spec.piProvider, modelId) : undefined;
116898
+ const { model: publishedModel, auth: authResult } = await modelsRuntime.resolveTurn(runtimeProviderId, modelId, fallbackModelId, options.abortSignal);
116899
+ connection = {
116900
+ ...connection,
116901
+ apiKey: authResult?.auth.apiKey === LOCAL_PROVIDER_NO_API_KEY ? undefined : authResult?.auth.apiKey
116902
+ };
116903
+ if (authResult?.auth.baseUrl)
116904
+ baseURL = authResult.auth.baseUrl;
116905
+ if (authResult?.auth.headers) {
116906
+ headers = mergeHeaders3(headers, nonNullHeaders(authResult.auth.headers));
116907
+ }
116908
+ if (connection.record?.auth.type === "oauth") {
116909
+ const stored = await modelsRuntime.getStoredCredential(runtimeProviderId);
116910
+ oauthCredentials = stored?.type === "oauth" ? stored : undefined;
116911
+ }
116912
+ if (provider === "zai") {
116913
+ const zai = resolveZaiConnection({
116914
+ storageDir,
116915
+ preferredProviderType: preferredProviderType === "zai" || preferredProviderType === "zai_coding" ? preferredProviderType : undefined,
116916
+ publishedBaseURL: publishedModel?.baseUrl
116917
+ });
116918
+ connection = {
116919
+ apiKey: zai.apiKey,
116920
+ baseURL: zai.baseURL,
116921
+ timeout: zai.timeout
116922
+ };
116923
+ baseURL = zai.baseURL;
116924
+ }
116925
+ if (connection.apiKey) {
116926
+ try {
116927
+ validateHeaderValue2("Authorization", `Bearer ${connection.apiKey}`);
116928
+ } catch {
116929
+ throw new Error(`API key for ${provider} is not a valid header value. Reconnect this provider with /connect.`);
116930
+ }
116931
+ }
116932
+ if (provider === "amazon-bedrock") {
116933
+ const bedrock = bedrockLocalProviderOptions(connection.record);
116934
+ providerOptions = bedrock.providerOptions;
116935
+ envOverrides = bedrock.envOverrides;
116936
+ }
116937
+ if (!publishedModel) {
116938
+ throw new Error(`Unknown model "${modelId}" for provider "${provider}". ` + "Choose an available model with /model.");
116939
+ }
116940
+ const hookedModel = oauthCredentials && registeredProvider?.config.oauth?.modifyModels ? registeredProvider.config.oauth.modifyModels([structuredClone(publishedModel)], oauthCredentials)[0] ?? publishedModel : publishedModel;
116941
+ const configuredContextWindow = numericSetting(modelSettings.context_window_limit);
116942
+ const isLocalOllama = modelsRuntime.isBuiltInLocalOllamaProvider(runtimeProviderId);
116943
+ const contextWindow = configuredContextWindow && isLocalOllama ? Math.min(configuredContextWindow, hookedModel.contextWindow) : configuredContextWindow;
116944
+ const configuredMaxTokens = numericSetting(modelSettings.max_tokens);
116945
+ const maxTokens = isLocalOllama ? Math.min(configuredMaxTokens ?? hookedModel.maxTokens, contextWindow ?? hookedModel.contextWindow) : configuredMaxTokens;
116946
+ const allowBaseUrlOverride = !registeredProvider && spec !== undefined && !modelsRuntime.isRuntimeManagedProvider(spec.id);
116947
+ const overrides = {
116948
+ ...allowBaseUrlOverride && baseURL && baseURL !== hookedModel.baseUrl ? { baseURL } : {},
116949
+ ...contextWindow && contextWindow !== hookedModel.contextWindow ? { contextWindow } : {},
116950
+ ...maxTokens && maxTokens !== hookedModel.maxTokens ? { maxTokens } : {}
116951
+ };
116952
+ const model = Object.keys(overrides).length > 0 ? withOverrides(hookedModel, overrides) : hookedModel;
116953
+ return {
116954
+ provider,
116955
+ model,
116956
+ apiKey: connection.apiKey,
116957
+ timeout: connection.timeout,
116958
+ headers,
116959
+ providerOptions,
116960
+ envOverrides
116961
+ };
116962
+ }
116963
+ var DEFAULT_PI_PROVIDER = "openai", UNSELECTED_LOCAL_MODEL_HANDLE = "local/default";
116964
+ var init_pi_model_factory = __esm(() => {
116965
+ init_dist2();
116966
+ init_local_pi_credential_store();
116967
+ init_local_provider_auth_store();
116968
+ init_local_provider_timeout();
116969
+ init_openai_reasoning_effort();
116970
+ init_pi_models_runtime();
116971
+ init_pi_provider_mod_registry();
116972
+ init_pi_provider_registry();
116973
+ });
116974
+
116975
+ // src/backend/dev/pi-request-headers.ts
116976
+ function resolvePiRequestHeaders(input) {
116977
+ return {
116978
+ ...input.configuredHeaders,
116979
+ "x-letta-request-kind": input.requestKind,
116980
+ ...input.provider === "opencode-go" ? { "x-opencode-session": input.conversationId } : {}
116981
+ };
116982
+ }
116983
+
116547
116984
  // src/backend/local/local-model-config.ts
116548
116985
  function supportedThinkingLevelsForRegistration(model) {
116549
116986
  return getSupportedThinkingLevels(model);
@@ -116744,7 +117181,14 @@ var init_local_model_config = __esm(() => {
116744
117181
  });
116745
117182
 
116746
117183
  // src/backend/local/compaction.ts
116747
- function assertLocalCompactionProgress(stats, mode) {
117184
+ function assertLocalPressureBudget(tokens, mode, maxMessageTokens = Number.POSITIVE_INFINITY) {
117185
+ if (tokens <= maxMessageTokens)
117186
+ return;
117187
+ const ErrorType2 = mode === "all" ? LocalIrreducibleContextError : LocalSlidingWindowCompactionPlanningError;
117188
+ throw new ErrorType2("Compaction would still exceed the pressure threshold.");
117189
+ }
117190
+ function assertLocalCompactionProgress(stats, mode, maxMessageTokens = Number.POSITIVE_INFINITY) {
117191
+ assertLocalPressureBudget(stats.context_tokens_after ?? 0, mode, maxMessageTokens);
116748
117192
  const hasProgress = (stats.messages_count_after ?? Number.POSITIVE_INFINITY) < (stats.messages_count_before ?? 0) || (stats.context_tokens_after ?? Number.POSITIVE_INFINITY) < (stats.context_tokens_before ?? 0);
116749
117193
  if (hasProgress)
116750
117194
  return;
@@ -117215,6 +117659,14 @@ The following is a summary of the previous messages:
117215
117659
  ...stats ? { compaction_stats: stats } : {}
117216
117660
  });
117217
117661
  }
117662
+ function localCompactionSettingsForStorage(settings3) {
117663
+ if (settings3 === undefined || settings3 === null)
117664
+ return settings3;
117665
+ const hasLocalSetting = Object.hasOwn(settings3, "mode") || Object.hasOwn(settings3, "prompt") || Object.hasOwn(settings3, "clip_chars") || Object.hasOwn(settings3, "sliding_window_percentage");
117666
+ if (!hasLocalSetting)
117667
+ return;
117668
+ return { ...settings3 };
117669
+ }
117218
117670
  var ALL_WORD_LIMIT = 500, SLIDING_WORD_LIMIT = 300, SUMMARY_TRUNCATION_SUFFIX = "... [summary truncated to fit]", LOCAL_SUMMARY_TOOL_RETURN_TRUNCATION_CHARS = 2000, FABLE_5_MODEL_ID = "claude-fable-5", FABLE_COMPACTION_SUMMARY_FALLBACK_MODEL = "anthropic/claude-opus-4-8", FABLE_COMPACTION_SUMMARY_FALLBACK_CONTEXT_WINDOW = 1e6, FABLE_COMPACTION_SUMMARY_FALLBACK_MAX_TOKENS = 128000, TRANSCRIPT_FALLBACK_MAX_CHARS = 120000, TRANSCRIPT_FALLBACK_MAX_CHAR_STEPS, LOCAL_DEFAULT_COMPACTION_MODE = "sliding_window", LOCAL_DEFAULT_SLIDING_WINDOW_PERCENTAGE = 0.3, LocalSlidingWindowCompactionPlanningError, LocalIrreducibleContextError, LOCAL_ALL_COMPACTION_PROMPT, LOCAL_SLIDING_WINDOW_COMPACTION_PROMPT;
117219
117671
  var init_compaction = __esm(() => {
117220
117672
  init_dist2();
@@ -117357,307 +117809,6 @@ var init_initial_memory = __esm(() => {
117357
117809
  init_create_agent_request();
117358
117810
  });
117359
117811
 
117360
- // src/backend/dev/provider-turn-executor.ts
117361
- var exports_provider_turn_executor = {};
117362
- __export(exports_provider_turn_executor, {
117363
- shouldCompactForContextPressure: () => shouldCompactForContextPressure,
117364
- providerStreamPart: () => providerStreamPart,
117365
- providerLocalMessage: () => providerLocalMessage,
117366
- providerLettaChunk: () => providerLettaChunk,
117367
- estimateProviderRequestBytes: () => estimateProviderRequestBytes,
117368
- estimateProviderPromptFloorTokens: () => estimateProviderPromptFloorTokens,
117369
- estimateProviderContextTokens: () => estimateProviderContextTokens,
117370
- contextTokensFromUsage: () => contextTokensFromUsage,
117371
- contextCompactionThreshold: () => contextCompactionThreshold,
117372
- buildProviderTurnInput: () => buildProviderTurnInput,
117373
- ProviderTurnExecutor: () => ProviderTurnExecutor
117374
- });
117375
- import { randomUUID as randomUUID10 } from "node:crypto";
117376
- function providerStreamPart(part) {
117377
- return { type: "provider-part", part };
117378
- }
117379
- function providerLocalMessage(message) {
117380
- return { type: "local-message", message };
117381
- }
117382
- function providerLettaChunk(chunk) {
117383
- return { type: "letta-chunk", chunk };
117384
- }
117385
-
117386
- class MissingProviderStreamAdapter {
117387
- async* stream() {
117388
- yield {
117389
- type: "error",
117390
- error: new Error("Provider turn adapter is not configured for this dev backend")
117391
- };
117392
- }
117393
- }
117394
- function bodyListField(body, key) {
117395
- const value = body[key];
117396
- return Array.isArray(value) ? value : [];
117397
- }
117398
- function buildProviderTurnInput(input) {
117399
- return {
117400
- conversationId: input.conversationId,
117401
- agentId: input.agentId,
117402
- agent: input.agent,
117403
- systemPrompt: input.systemPrompt,
117404
- midConversationSystemPrompt: input.midConversationSystemPrompt,
117405
- body: input.body,
117406
- history: input.history,
117407
- uiMessages: input.uiMessages,
117408
- clientTools: bodyListField(input.body, "client_tools"),
117409
- clientSkills: bodyListField(input.body, "client_skills")
117410
- };
117411
- }
117412
- function stringifyToolInput(input) {
117413
- if (typeof input === "string")
117414
- return input;
117415
- return JSON.stringify(input ?? {});
117416
- }
117417
- function createLocalMessageChunk(message) {
117418
- return markLocalStateChunkOnly(attachLocalMessage({ message_type: "local_message" }, message));
117419
- }
117420
- function createProviderErrorChunks(error4) {
117421
- const info = normalizeLocalProviderError(error4);
117422
- return [
117423
- {
117424
- message_type: "error_message",
117425
- message: info.message,
117426
- detail: info.detail,
117427
- error_type: info.error_type,
117428
- retryable: info.retryable
117429
- },
117430
- {
117431
- message_type: "stop_reason",
117432
- stop_reason: info.stop_reason
117433
- }
117434
- ];
117435
- }
117436
- function contextTokensFromUsage(usage) {
117437
- return contextTokensFromLocalUsage(usage);
117438
- }
117439
- function estimateSerializedTokens(value) {
117440
- if (value === undefined || value === null)
117441
- return 0;
117442
- try {
117443
- const serialized = typeof value === "string" ? value : JSON.stringify(value) ?? "";
117444
- return Math.ceil(serialized.length / 4);
117445
- } catch {
117446
- return 0;
117447
- }
117448
- }
117449
- function estimateProviderContextTokens(input) {
117450
- const contextEstimate = estimateLocalContextTokens(input.uiMessages);
117451
- if (contextEstimate.lastUsageIndex !== null) {
117452
- return contextEstimate.tokens > 0 ? contextEstimate.tokens : undefined;
117453
- }
117454
- const systemPromptTokens = estimateSerializedTokens(input.systemPrompt ?? input.agent.system);
117455
- const messageTokens = contextEstimate.tokens;
117456
- const toolTokens = estimateSerializedTokens(input.clientTools);
117457
- const total = systemPromptTokens + messageTokens + toolTokens;
117458
- return total > 0 ? total : undefined;
117459
- }
117460
- function estimateProviderPromptFloorTokens(input) {
117461
- return estimateSerializedTokens(input.systemPrompt ?? input.agent.system) + estimateSerializedTokens(input.clientTools);
117462
- }
117463
- function contextCompactionThreshold(contextWindow) {
117464
- if (typeof contextWindow !== "number" || !Number.isFinite(contextWindow) || contextWindow <= 0) {
117465
- return;
117466
- }
117467
- const reserveTokens = Math.min(LOCAL_CONTEXT_COMPACTION_RESERVE_TOKENS, Math.max(1, Math.floor(contextWindow * LOCAL_SMALL_CONTEXT_COMPACTION_RESERVE_RATIO)));
117468
- return Math.max(0, contextWindow - reserveTokens);
117469
- }
117470
- function shouldCompactForContextPressure(input) {
117471
- const threshold = contextCompactionThreshold(input.contextWindow);
117472
- return input.contextTokens !== undefined && threshold !== undefined && input.contextTokens > threshold;
117473
- }
117474
- function serializedLength(value) {
117475
- if (value === undefined || value === null)
117476
- return 0;
117477
- try {
117478
- const serialized = typeof value === "string" ? value : JSON.stringify(value) ?? "";
117479
- return serialized.length;
117480
- } catch {
117481
- return 0;
117482
- }
117483
- }
117484
- function estimateProviderRequestBytes(input) {
117485
- const systemPromptBytes = serializedLength(input.systemPrompt ?? input.agent.system);
117486
- const messageBytes = serializedLength(input.uiMessages);
117487
- const toolBytes = serializedLength(input.clientTools);
117488
- const total = systemPromptBytes + messageBytes + toolBytes;
117489
- return total > 0 ? total : undefined;
117490
- }
117491
- function createUsageStatisticsChunk(usage, contextTokensEstimate) {
117492
- const promptTokens = usage?.input;
117493
- const completionTokens = usage?.output;
117494
- const totalTokens = usage?.totalTokens;
117495
- const usageContextTokens = usage ? contextTokensFromUsage(usage) : undefined;
117496
- const contextTokens = usageContextTokens ?? contextTokensEstimate;
117497
- const cachedInputTokens = usage?.cacheRead;
117498
- const cacheWriteTokens = usage?.cacheWrite;
117499
- const reasoningTokens = usage?.reasoning;
117500
- return {
117501
- message_type: "usage_statistics",
117502
- step_count: 1,
117503
- ...promptTokens !== undefined ? { prompt_tokens: promptTokens } : {},
117504
- ...completionTokens !== undefined ? { completion_tokens: completionTokens } : {},
117505
- ...totalTokens !== undefined ? { total_tokens: totalTokens } : {},
117506
- ...cachedInputTokens !== undefined ? { cached_input_tokens: cachedInputTokens } : {},
117507
- ...cacheWriteTokens !== undefined ? { cache_write_tokens: cacheWriteTokens } : {},
117508
- ...reasoningTokens !== undefined ? { reasoning_tokens: reasoningTokens } : {},
117509
- ...contextTokens !== undefined ? { context_tokens: contextTokens } : {}
117510
- };
117511
- }
117512
- function errorFromAssistantEvent(part) {
117513
- if (part.type !== "error")
117514
- return new Error("Unknown provider stream error");
117515
- return new Error(part.error.errorMessage ?? "Unknown local provider error");
117516
- }
117517
- function contentMatchesMessageType(content, messageType) {
117518
- if (!content || typeof content !== "object" || !("type" in content)) {
117519
- return false;
117520
- }
117521
- return messageType === "assistant_message" ? content.type === "text" : content.type === "thinking";
117522
- }
117523
- function contiguousContentStartIndex(partial3, contentIndex, messageType) {
117524
- let startIndex = contentIndex;
117525
- while (startIndex > 0 && contentMatchesMessageType(partial3.content[startIndex - 1], messageType)) {
117526
- startIndex -= 1;
117527
- }
117528
- if (messageType === "reasoning_message") {
117529
- for (let index = startIndex;index <= contentIndex; index++) {
117530
- const content = partial3.content[index];
117531
- if (content?.type === "thinking" && content.thinking.length > 0) {
117532
- return index;
117533
- }
117534
- }
117535
- }
117536
- return startIndex;
117537
- }
117538
- function projectsLocalOutput(content) {
117539
- if (content.type === "text")
117540
- return true;
117541
- if (content.type === "thinking")
117542
- return content.thinking.length > 0;
117543
- return content.type === "toolCall" && typeof content.id === "string";
117544
- }
117545
- function identityForContentSegment(identities, prefix, contentIndex, partial3, messageType) {
117546
- const contentStartIndex = contiguousContentStartIndex(partial3, contentIndex, messageType);
117547
- const existing = identities.get(contentStartIndex);
117548
- if (existing)
117549
- return existing;
117550
- const identity = {
117551
- otid: `${prefix}-${contentStartIndex}-${randomUUID10()}`,
117552
- contentStartIndex,
117553
- useSourceMessageId: messageType === "assistant_message" && !partial3.content.slice(0, contentStartIndex).some(projectsLocalOutput)
117554
- };
117555
- identities.set(contentStartIndex, identity);
117556
- return identity;
117557
- }
117558
- function createProviderLettaStream(events, contextTokensEstimate) {
117559
- const controller = new AbortController;
117560
- return {
117561
- controller,
117562
- async* [Symbol.asyncIterator]() {
117563
- let sawToolCall = false;
117564
- let pendingStopReason;
117565
- let sawUsageStatistics = false;
117566
- const assistantIdentities = new Map;
117567
- const reasoningIdentities = new Map;
117568
- try {
117569
- for await (const event of events) {
117570
- if (event.type === "error") {
117571
- yield* createProviderErrorChunks(event.error);
117572
- return;
117573
- }
117574
- if (event.type === "local-message") {
117575
- yield createLocalMessageChunk(event.message);
117576
- continue;
117577
- }
117578
- if (event.type === "letta-chunk") {
117579
- yield event.chunk;
117580
- continue;
117581
- }
117582
- const { part } = event;
117583
- if (part.type === "text_delta") {
117584
- const identity = identityForContentSegment(assistantIdentities, "provider-assistant", part.contentIndex, part.partial, "assistant_message");
117585
- yield attachLocalSegmentIdentity({
117586
- message_type: "assistant_message",
117587
- otid: identity.otid,
117588
- content: [{ type: "text", text: part.delta }]
117589
- }, identity);
117590
- continue;
117591
- }
117592
- if (part.type === "thinking_delta") {
117593
- const identity = identityForContentSegment(reasoningIdentities, "provider-reasoning", part.contentIndex, part.partial, "reasoning_message");
117594
- yield attachLocalSegmentIdentity({
117595
- message_type: "reasoning_message",
117596
- otid: identity.otid,
117597
- reasoning: part.delta
117598
- }, identity);
117599
- continue;
117600
- }
117601
- if (part.type === "toolcall_end") {
117602
- sawToolCall = true;
117603
- yield {
117604
- message_type: "approval_request_message",
117605
- tool_call: {
117606
- tool_call_id: part.toolCall.id,
117607
- name: part.toolCall.name,
117608
- arguments: stringifyToolInput(part.toolCall.arguments)
117609
- }
117610
- };
117611
- continue;
117612
- }
117613
- if (part.type === "done") {
117614
- if (!sawUsageStatistics) {
117615
- sawUsageStatistics = true;
117616
- yield createUsageStatisticsChunk(part.message.usage, contextTokensEstimate);
117617
- }
117618
- pendingStopReason = {
117619
- message_type: "stop_reason",
117620
- stop_reason: sawToolCall || part.reason === "toolUse" ? "requires_approval" : part.reason === "length" ? "max_tokens_exceeded" : "end_turn"
117621
- };
117622
- continue;
117623
- }
117624
- if (part.type === "error") {
117625
- yield* createProviderErrorChunks(errorFromAssistantEvent(part));
117626
- return;
117627
- }
117628
- }
117629
- if (pendingStopReason) {
117630
- yield pendingStopReason;
117631
- } else if (sawToolCall) {
117632
- yield {
117633
- message_type: "stop_reason",
117634
- stop_reason: "requires_approval"
117635
- };
117636
- }
117637
- } catch (error4) {
117638
- yield* createProviderErrorChunks(error4);
117639
- }
117640
- }
117641
- };
117642
- }
117643
-
117644
- class ProviderTurnExecutor {
117645
- adapter;
117646
- constructor(adapter = new MissingProviderStreamAdapter) {
117647
- this.adapter = adapter;
117648
- }
117649
- async execute(input) {
117650
- const providerInput = buildProviderTurnInput(input);
117651
- const events = await this.adapter.stream(providerInput);
117652
- return createProviderLettaStream(events, estimateProviderContextTokens(providerInput));
117653
- }
117654
- }
117655
- var LOCAL_CONTEXT_COMPACTION_RESERVE_TOKENS = 16384, LOCAL_SMALL_CONTEXT_COMPACTION_RESERVE_RATIO = 0.2;
117656
- var init_provider_turn_executor = __esm(() => {
117657
- init_local_stream_chunks();
117658
- init_local_provider_errors();
117659
- });
117660
-
117661
117812
  // src/backend/dev/pi-image-elision.ts
117662
117813
  function localProviderRequestByteLimit() {
117663
117814
  const raw = process.env[LOCAL_PROVIDER_REQUEST_BYTE_LIMIT_ENV];
@@ -118220,7 +118371,7 @@ class PiStreamAdapter {
118220
118371
  finalLocalMessage = toLocalAssistantMessage(part.message, input);
118221
118372
  yield providerLocalMessage(finalLocalMessage);
118222
118373
  }
118223
- yield providerStreamPart(part);
118374
+ yield providerStreamPart(part, resolved2.model);
118224
118375
  }
118225
118376
  if (streamError)
118226
118377
  throw streamError;
@@ -118773,14 +118924,6 @@ function validateLocalCompactionSettingsRecord(settings3) {
118773
118924
  throw new Error(`Local backend compaction currently supports only modes "all" and "sliding_window" (received "${String(settings3.mode)}").`);
118774
118925
  }
118775
118926
  }
118776
- function localCompactionSettingsForStorage(settings3) {
118777
- if (settings3 === undefined || settings3 === null)
118778
- return settings3;
118779
- const hasLocalSetting = hasOwn5(settings3, "mode") || hasOwn5(settings3, "prompt") || hasOwn5(settings3, "clip_chars") || hasOwn5(settings3, "sliding_window_percentage");
118780
- if (!hasLocalSetting)
118781
- return;
118782
- return { ...settings3 };
118783
- }
118784
118927
  function formatMidConversationMemoryUpdate(compiled) {
118785
118928
  return [
118786
118929
  "<memory_update>",
@@ -118798,6 +118941,7 @@ var init_local_backend = __esm(() => {
118798
118941
  init_memory_git();
118799
118942
  init_headless_backend();
118800
118943
  init_pi_models_runtime();
118944
+ init_provider_turn_executor();
118801
118945
  init_settings_manager();
118802
118946
  init_compaction();
118803
118947
  init_initial_memory();
@@ -119011,8 +119155,10 @@ var init_local_backend = __esm(() => {
119011
119155
  stats: result.stats
119012
119156
  };
119013
119157
  }
119014
- async compactForContextPressure(input, _pressure) {
119015
- const result = await runLocalPressureCompaction(() => this.compactLocalConversation(input.conversationId, input.agentId, "context_window_limit"));
119158
+ async compactForContextPressure(input, pressure) {
119159
+ const messageTokens = estimateLocalMessageTokens2(this.store.listLocalMessages(input.conversationId, input.agentId));
119160
+ const fixedTokens = Math.max(0, pressure.contextTokens - messageTokens);
119161
+ const result = await runLocalPressureCompaction(() => this.compactLocalConversation(input.conversationId, input.agentId, "context_window_limit", undefined, (contextCompactionThreshold(pressure.contextWindow) ?? 0) - fixedTokens));
119016
119162
  if (!result)
119017
119163
  return null;
119018
119164
  return {
@@ -119074,31 +119220,33 @@ var init_local_backend = __esm(() => {
119074
119220
  slidingWindowPercentage: typeof mergedSettings.sliding_window_percentage === "number" ? mergedSettings.sliding_window_percentage : LOCAL_DEFAULT_SLIDING_WINDOW_PERCENTAGE
119075
119221
  };
119076
119222
  }
119077
- async compactLocalConversation(conversationId, agentId, trigger, body) {
119223
+ async compactLocalConversation(conversationId, agentId, trigger, body, maxMessageTokens) {
119078
119224
  await this.emitCompactStart(conversationId, agentId, trigger);
119079
- const result = await this.compactLocalConversationInner(conversationId, agentId, trigger, body);
119225
+ const result = await this.compactLocalConversationInner(conversationId, agentId, trigger, body, maxMessageTokens);
119080
119226
  await this.emitCompactEnd(conversationId, agentId, trigger, result.stats);
119081
119227
  return result;
119082
119228
  }
119083
- async compactLocalConversationInner(conversationId, agentId, trigger, body) {
119229
+ async compactLocalConversationInner(conversationId, agentId, trigger, body, maxMessageTokens) {
119084
119230
  const agent = this.effectiveAgentForConversation(conversationId, agentId);
119085
- const settings3 = this.resolveCompactionSettings(agent, body);
119086
- let result;
119231
+ const settings3 = {
119232
+ ...this.resolveCompactionSettings(agent, body),
119233
+ maxMessageTokens
119234
+ };
119087
119235
  if (settings3.mode === "sliding_window") {
119088
119236
  try {
119089
- result = await this.compactLocalConversationSlidingWindow(conversationId, agentId, agent, trigger, settings3);
119090
- if (result.stats.context_window === undefined || result.stats.context_tokens_after === undefined || result.stats.context_tokens_after < result.stats.context_window) {
119237
+ const result2 = await this.compactLocalConversationSlidingWindow(conversationId, agentId, agent, trigger, settings3);
119238
+ if (result2.stats.context_window === undefined || result2.stats.context_tokens_after === undefined || result2.stats.context_tokens_after < result2.stats.context_window) {
119091
119239
  await this.compileAndMaybePersistSystemPrompt(conversationId, agentId, {
119092
119240
  dryRun: false
119093
119241
  });
119094
- return result;
119242
+ return result2;
119095
119243
  }
119096
119244
  } catch (error4) {
119097
119245
  if (!isLocalSlidingWindowCompactionPlanningError(error4))
119098
119246
  throw error4;
119099
119247
  }
119100
119248
  }
119101
- result = await this.compactLocalConversationAll(conversationId, agentId, agent, trigger, {
119249
+ const result = await this.compactLocalConversationAll(conversationId, agentId, agent, trigger, {
119102
119250
  ...settings3,
119103
119251
  mode: "all",
119104
119252
  prompt: settings3.prompt
@@ -119112,6 +119260,8 @@ var init_local_backend = __esm(() => {
119112
119260
  const messages = this.store.listLocalMessages(conversationId, agentId);
119113
119261
  const contextTokensBefore = estimateLocalMessageTokens2(messages);
119114
119262
  const plan = planLocalAllCompaction(messages);
119263
+ const keptTokens = estimateLocalMessageTokens2(plan.messagesToKeep);
119264
+ assertLocalPressureBudget(keptTokens, "all", settings3.maxMessageTokens);
119115
119265
  const summary = await summarizeLocalMessagesAll({
119116
119266
  conversationId,
119117
119267
  agent,
@@ -119125,11 +119275,12 @@ var init_local_backend = __esm(() => {
119125
119275
  const stats = {
119126
119276
  trigger,
119127
119277
  context_tokens_before: contextTokensBefore,
119128
- context_tokens_after: Math.ceil(summary.length / 4) + estimateLocalMessageTokens2(plan.messagesToKeep),
119278
+ context_tokens_after: Math.ceil(summary.length / 4) + keptTokens,
119129
119279
  context_window: this.effectiveContextWindow(conversationId, agentId),
119130
119280
  messages_count_before: messages.length,
119131
119281
  messages_count_after: 1 + plan.messagesToKeep.length
119132
119282
  };
119283
+ assertLocalPressureBudget(stats.context_tokens_after ?? 0, "all", settings3.maxMessageTokens);
119133
119284
  return finishLocalFullCompaction({
119134
119285
  messages,
119135
119286
  summary,
@@ -119153,6 +119304,7 @@ var init_local_backend = __esm(() => {
119153
119304
  slidingWindowPercentage: settings3.slidingWindowPercentage,
119154
119305
  contextWindow
119155
119306
  });
119307
+ assertLocalPressureBudget(estimateLocalMessageTokens2(plan.messagesToKeep), "sliding_window", settings3.maxMessageTokens);
119156
119308
  const summary = await summarizeLocalMessagesSlidingWindow({
119157
119309
  conversationId,
119158
119310
  agent,
@@ -119172,7 +119324,7 @@ var init_local_backend = __esm(() => {
119172
119324
  messages_count_before: messages.length,
119173
119325
  messages_count_after: 1 + plan.messagesToKeep.length
119174
119326
  };
119175
- assertLocalCompactionProgress(stats, "sliding_window");
119327
+ assertLocalCompactionProgress(stats, "sliding_window", settings3.maxMessageTokens);
119176
119328
  const storeResult = this.store.compactConversationAll({
119177
119329
  conversationId,
119178
119330
  agentId,
@@ -119457,11 +119609,14 @@ class APIBackend {
119457
119609
  message: `Connection error: expected text/event-stream, received ${contentType || "no content type"} (HTTP ${response.status}).`
119458
119610
  });
119459
119611
  }
119612
+ withClientUsageCost(stream11, () => conversationCostModel(client, conversationId, body?.agent_id, body.override_model));
119460
119613
  return stream11;
119461
119614
  }
119462
119615
  async streamConversationMessages(conversationId, body, options) {
119463
119616
  const client = await this.getClient();
119464
- return client.conversations.messages.stream(conversationId, body, options);
119617
+ const stream11 = await client.conversations.messages.stream(conversationId, body, options);
119618
+ withClientUsageCost(stream11, () => conversationCostModel(client, conversationId, body?.agent_id));
119619
+ return stream11;
119465
119620
  }
119466
119621
  async cancelConversation(conversationIdOrAgentId) {
119467
119622
  const client = await this.getClient();
@@ -119489,7 +119644,12 @@ class APIBackend {
119489
119644
  }
119490
119645
  async streamRunMessages(runId, body, options) {
119491
119646
  const client = await this.getClient();
119492
- return client.runs.messages.stream(runId, body, options);
119647
+ const stream11 = await client.runs.messages.stream(runId, body, options);
119648
+ withClientUsageCost(stream11, async () => {
119649
+ const run = await client.runs.retrieve(runId);
119650
+ return conversationCostModel(client, run.conversation_id ?? "default", run.agent_id);
119651
+ });
119652
+ return stream11;
119493
119653
  }
119494
119654
  async forkConversation(conversationId, options) {
119495
119655
  if (this.forkConversationOverride) {
@@ -119599,6 +119759,7 @@ var init_backend = __esm(() => {
119599
119759
  init_reflection();
119600
119760
  init_reflection_runs();
119601
119761
  init_server_url();
119762
+ init_usage_cost();
119602
119763
  init_backend_mode();
119603
119764
  init_local_backend();
119604
119765
  init_paths();
@@ -120882,6 +121043,57 @@ var init_personality = __esm(() => {
120882
121043
  execFile4 = promisify5(execFileCb2);
120883
121044
  });
120884
121045
 
121046
+ // src/agent/resumed-agent-model.ts
121047
+ async function prepareResumedAgentModel(options) {
121048
+ const {
121049
+ agent,
121050
+ modelIdentifier,
121051
+ modelHandle,
121052
+ createsConversation,
121053
+ localModelCatalog
121054
+ } = options;
121055
+ if (modelHandle) {
121056
+ const updateArgs2 = getModelUpdateArgs(modelIdentifier);
121057
+ const selectedContextWindow = updateArgs2?.context_window;
121058
+ const preservedContextWindow2 = contextWindowToPreserveForModelSelection({
121059
+ currentModelHandle: agent.model,
121060
+ currentLlmConfig: agent.llm_config,
121061
+ selectedModelHandle: modelHandle,
121062
+ selectedContextWindow: typeof selectedContextWindow === "number" ? selectedContextWindow : undefined
121063
+ });
121064
+ if (createsConversation) {
121065
+ const contextWindow = preservedContextWindow2 ?? updateArgs2?.context_window;
121066
+ return {
121067
+ agent,
121068
+ conversationModel: {
121069
+ model: modelHandle,
121070
+ model_settings: buildModelSettings(modelHandle, updateArgs2, localModelCatalog),
121071
+ ...typeof contextWindow === "number" && {
121072
+ context_window_limit: contextWindow
121073
+ }
121074
+ }
121075
+ };
121076
+ }
121077
+ return {
121078
+ agent: await updateAgentLLMConfig(agent.id, modelHandle, updateArgs2, preservedContextWindow2 !== undefined ? { contextWindowOverride: preservedContextWindow2 } : undefined)
121079
+ };
121080
+ }
121081
+ const presetRefresh = getModelPresetUpdateForAgent(agent);
121082
+ if (!presetRefresh)
121083
+ return { agent };
121084
+ const { updateArgs, needsUpdate } = getResumeRefreshArgs(presetRefresh.updateArgs, agent);
121085
+ if (!needsUpdate)
121086
+ return { agent };
121087
+ const preservedContextWindow = preservableContextWindow(agent.llm_config?.context_window, presetRefresh.modelHandle);
121088
+ return {
121089
+ agent: await updateAgentLLMConfig(agent.id, presetRefresh.modelHandle, updateArgs, preservedContextWindow !== undefined ? { contextWindowOverride: preservedContextWindow } : undefined)
121090
+ };
121091
+ }
121092
+ var init_resumed_agent_model = __esm(() => {
121093
+ init_model();
121094
+ init_modify();
121095
+ });
121096
+
120885
121097
  // src/browser-discovery-server.ts
120886
121098
  import {
120887
121099
  createServer as createServer3
@@ -211838,7 +212050,7 @@ var init_mcp_client = __esm(() => {
211838
212050
  init_streamableHttp();
211839
212051
  DEFAULT_CLIENT_INFO = {
211840
212052
  name: "letta-code",
211841
- version: "0.34.41"
212053
+ version: "0.34.42"
211842
212054
  };
211843
212055
  });
211844
212056
 
@@ -221258,8 +221470,47 @@ var init_cli_permissions_instance = __esm(() => {
221258
221470
  cliPermissions = getCliPermissions();
221259
221471
  });
221260
221472
 
221261
- // src/permissions/cross-agent-guard.ts
221473
+ // src/permissions/file-path-args.ts
221262
221474
  import { homedir as homedir12 } from "node:os";
221475
+ function expandPathArgs(toolName2, toolArgs, workingDirectory, env6 = process.env, homeDir) {
221476
+ if (!CWD_FILE_PATH_TOOLS.has(canonicalToolName(toolName2)))
221477
+ return toolArgs;
221478
+ let expandedArgs = toolArgs;
221479
+ for (const key2 of FILE_PATH_KEYS) {
221480
+ const value = toolArgs[key2];
221481
+ if (typeof value !== "string" || value.length === 0)
221482
+ continue;
221483
+ if (process.platform !== "win32" && /^[a-zA-Z]:[\\/]/.test(value)) {
221484
+ continue;
221485
+ }
221486
+ expandedArgs = {
221487
+ ...expandedArgs,
221488
+ [key2]: expandFilePath(value, workingDirectory, env6, homeDir ?? env6.HOME ?? homedir12())
221489
+ };
221490
+ }
221491
+ return expandedArgs;
221492
+ }
221493
+ var FILE_PATH_KEYS, CWD_FILE_PATH_TOOLS;
221494
+ var init_file_path_args = __esm(() => {
221495
+ init_file_path();
221496
+ init_canonical();
221497
+ FILE_PATH_KEYS = ["file_path", "path", "notebook_path"];
221498
+ CWD_FILE_PATH_TOOLS = new Set([
221499
+ "Read",
221500
+ "Write",
221501
+ "Edit",
221502
+ "Glob",
221503
+ "Grep",
221504
+ "ListDir",
221505
+ "ReadLSP",
221506
+ "ViewImage",
221507
+ "SetWorkingDirectory",
221508
+ "EnterWorktree"
221509
+ ]);
221510
+ });
221511
+
221512
+ // src/permissions/cross-agent-guard.ts
221513
+ import { homedir as homedir13 } from "node:os";
221263
221514
  function isSubagentProcess2(env6) {
221264
221515
  return env6.LETTA_CODE_AGENT_ROLE === "subagent";
221265
221516
  }
@@ -221340,7 +221591,7 @@ function extractFilePath(toolArgs) {
221340
221591
  function isRecursivePathTool(toolName2) {
221341
221592
  return RECURSIVE_CANONICAL_TOOLS.has(canonicalToolName(toolName2));
221342
221593
  }
221343
- function extractTargetAgentPaths(toolName2, toolArgs, workingDirectory, env6 = process.env, homeDir = homedir12()) {
221594
+ function extractTargetAgentPaths(toolName2, toolArgs, workingDirectory, env6 = process.env, homeDir = homedir13()) {
221344
221595
  const agentIds = new Set;
221345
221596
  let anyAgentScoped = false;
221346
221597
  const recursive = isRecursivePathTool(toolName2);
@@ -221403,7 +221654,8 @@ function buildReason(offending, allowed) {
221403
221654
  }
221404
221655
  function evaluateCrossAgentGuard(toolName2, toolArgs, workingDirectory, options = {}) {
221405
221656
  const env6 = options.env ?? process.env;
221406
- const homeDir = env6.HOME ?? homedir12();
221657
+ const homeDir = env6.HOME ?? homedir13();
221658
+ toolArgs = expandPathArgs(toolName2, toolArgs, workingDirectory, env6, homeDir);
221407
221659
  if (isMemoryGuardDisabled(options)) {
221408
221660
  return null;
221409
221661
  }
@@ -221438,6 +221690,7 @@ var init_cross_agent_guard = __esm(() => {
221438
221690
  init_policy();
221439
221691
  init_canonical();
221440
221692
  init_cli_permissions_instance();
221693
+ init_file_path_args();
221441
221694
  init_memory_paths();
221442
221695
  init_sandbox_policy();
221443
221696
  RECURSIVE_CANONICAL_TOOLS = new Set(["Glob", "Grep", "ListDir"]);
@@ -221504,6 +221757,7 @@ function isWriteTool(toolName2) {
221504
221757
  function evaluateWorkspaceSandboxGuard(toolName2, toolArgs, workingDirectory, sandbox) {
221505
221758
  if (!sandbox || isShellToolName(toolName2))
221506
221759
  return null;
221760
+ toolArgs = expandPathArgs(toolName2, toolArgs, workingDirectory);
221507
221761
  const paths = targetPaths(toolName2, toolArgs, workingDirectory);
221508
221762
  for (const path16 of paths) {
221509
221763
  const insideWorkspace = isWithin2(path16, sandbox.root);
@@ -221522,6 +221776,7 @@ var init_workspace_sandbox = __esm(() => {
221522
221776
  init_policy();
221523
221777
  init_canonical();
221524
221778
  init_cross_agent_guard();
221779
+ init_file_path_args();
221525
221780
  init_sandbox_policy();
221526
221781
  });
221527
221782
 
@@ -221842,7 +222097,7 @@ var init_truncation = __esm(() => {
221842
222097
  });
221843
222098
 
221844
222099
  // src/tools/impl/windows-command-safety.ts
221845
- import { homedir as homedir13 } from "node:os";
222100
+ import { homedir as homedir14 } from "node:os";
221846
222101
  import { win32 as win323 } from "node:path";
221847
222102
  function parseCommands(input) {
221848
222103
  const commands = [];
@@ -221998,7 +222253,7 @@ function findProtectedCmdTarget(command, cwd2, homeDirectory, env6, depth = 0) {
221998
222253
  function assertSafeWindowsCommand(command, options = {}) {
221999
222254
  if ((options.platform ?? process.platform) !== "win32")
222000
222255
  return;
222001
- const target2 = findProtectedCmdTarget(command, options.cwd ?? process.cwd(), options.homeDirectory ?? homedir13(), options.env ?? process.env);
222256
+ const target2 = findProtectedCmdTarget(command, options.cwd ?? process.cwd(), options.homeDirectory ?? homedir14(), options.env ?? process.env);
222002
222257
  if (target2) {
222003
222258
  throw new Error(`Refusing to run a cmd removal against protected Windows path: ${target2}`);
222004
222259
  }
@@ -227077,7 +227332,7 @@ var init_esm4 = __esm(() => {
227077
227332
  });
227078
227333
 
227079
227334
  // src/permissions/matcher.ts
227080
- import { resolve as resolve21 } from "node:path";
227335
+ import { resolve as resolve21, win32 as win324 } from "node:path";
227081
227336
  function toolForMatch(toolName2, options) {
227082
227337
  return options?.canonicalizeToolNames === false ? toolName2 : canonicalToolName(toolName2);
227083
227338
  }
@@ -227161,8 +227416,8 @@ function matchesFilePattern(query3, pattern4, workingDirectory, options) {
227161
227416
  globPattern = globPattern.slice(2);
227162
227417
  }
227163
227418
  if (globPattern.startsWith("~/")) {
227164
- const homedir14 = __require("node:os").homedir();
227165
- globPattern = globPattern.replace(/^~/, homedir14);
227419
+ const homedir15 = process.env.HOME ?? __require("node:os").homedir();
227420
+ globPattern = globPattern.replace(/^~/, homedir15);
227166
227421
  }
227167
227422
  globPattern = normalizeAbsolutePattern(globPattern, workingDirectory);
227168
227423
  const windowsContext = isWindowsContext(workingDirectory);
@@ -227174,7 +227429,8 @@ function matchesFilePattern(query3, pattern4, workingDirectory, options) {
227174
227429
  });
227175
227430
  }
227176
227431
  const normalizedWorkingDir = normalizePath2(workingDirectory);
227177
- const relativeFilePath = filePath.startsWith("/") ? absoluteFilePath.replace(`${normalizedWorkingDir}/`, "") : filePath;
227432
+ const windowsWorkingDir = process.platform === "win32" ? normalizePath2(resolve21(workingDirectory)) : normalizedWorkingDir;
227433
+ const relativeFilePath = isWindowsAbsolutePath(filePath) ? normalizePath2(win324.relative(canonicalizeWindowsAbsolutePath(windowsWorkingDir), absoluteFilePath)) : filePath.startsWith("/") ? absoluteFilePath.replace(`${normalizedWorkingDir}/`, "") : filePath;
227178
227434
  return minimatch(relativeFilePath, globPattern) || minimatch(absoluteFilePath, globPattern);
227179
227435
  }
227180
227436
  function matchesBashPattern(query3, pattern4, options) {
@@ -227328,7 +227584,7 @@ var init_read_only_letta = __esm(() => {
227328
227584
  });
227329
227585
 
227330
227586
  // src/permissions/read-only-shell.ts
227331
- import { homedir as homedir14 } from "node:os";
227587
+ import { homedir as homedir15 } from "node:os";
227332
227588
  import { resolve as resolve23 } from "node:path";
227333
227589
  function isSafeConditionalTest(condition, options) {
227334
227590
  let tokens = tokenizeShellWords(condition);
@@ -228123,7 +228379,7 @@ function expandScopedVariables(value, env6, shellVars) {
228123
228379
  return "";
228124
228380
  }
228125
228381
  if (name === "HOME") {
228126
- return homedir14();
228382
+ return homedir15();
228127
228383
  }
228128
228384
  const scopedValue = shellVars[name];
228129
228385
  if (typeof scopedValue === "string") {
@@ -228712,7 +228968,7 @@ __export(exports_checker, {
228712
228968
  checkPermissionWithHooks: () => checkPermissionWithHooks,
228713
228969
  checkPermission: () => checkPermission
228714
228970
  });
228715
- import { posix as posix3, resolve as resolve24, win32 as win324 } from "node:path";
228971
+ import { posix as posix3, resolve as resolve24, win32 as win325 } from "node:path";
228716
228972
  function envFlagEnabled(name) {
228717
228973
  const value = process.env[name];
228718
228974
  if (!value)
@@ -228735,6 +228991,7 @@ function shouldAttachTrace(result2) {
228735
228991
  return result2.decision === "ask" || result2.decision === "alwaysAsk" || result2.decision === "deny";
228736
228992
  }
228737
228993
  function checkPermission(toolName2, toolArgs, permissions, workingDirectory = process.cwd(), modeState, agentId, modTools = getAvailableModToolsRegistry()) {
228994
+ toolArgs = expandPathArgs(toolName2, toolArgs, workingDirectory);
228738
228995
  const engine4 = isPermissionsV2Enabled() ? "v2" : "v1";
228739
228996
  const primary = checkPermissionForEngine(engine4, toolName2, toolArgs, permissions, workingDirectory, modeState, agentId, modTools);
228740
228997
  let result2 = primary.result;
@@ -229075,8 +229332,8 @@ function checkPermissionForEngine(engine4, toolName2, toolArgs, permissions, wor
229075
229332
  trace
229076
229333
  };
229077
229334
  }
229078
- function isPathWithin(child, root2, pathImpl = process.platform === "win32" ? win324 : posix3) {
229079
- const caseInsensitive = pathImpl === win324;
229335
+ function isPathWithin(child, root2, pathImpl = process.platform === "win32" ? win325 : posix3) {
229336
+ const caseInsensitive = pathImpl === win325;
229080
229337
  const normalizedChild = caseInsensitive ? child.toLowerCase() : child;
229081
229338
  const normalizedRoot = caseInsensitive ? root2.toLowerCase() : root2;
229082
229339
  const rel = pathImpl.relative(normalizedRoot, normalizedChild);
@@ -229198,6 +229455,7 @@ function getDefaultDecision(toolName2, toolArgs, modTools = getAvailableModTools
229198
229455
  return "ask";
229199
229456
  }
229200
229457
  async function checkPermissionWithHooks(toolName2, toolArgs, permissions, workingDirectory = process.cwd(), modeState, agentId, modPermissions = getAvailableModPermissionsRegistry(), modTools = getAvailableModToolsRegistry(), modPermissionOptions = {}) {
229458
+ toolArgs = expandPathArgs(toolName2, toolArgs, workingDirectory);
229201
229459
  let result2 = checkPermission(toolName2, toolArgs, permissions, workingDirectory, modeState, agentId, modTools);
229202
229460
  if (result2.decision !== "deny") {
229203
229461
  const modDecision = await checkModPermissions({
@@ -229253,6 +229511,7 @@ var init_checker = __esm(() => {
229253
229511
  init_canonical();
229254
229512
  init_cli_permissions_instance();
229255
229513
  init_cross_agent_guard();
229514
+ init_file_path_args();
229256
229515
  init_matcher();
229257
229516
  init_memory_write_allowance();
229258
229517
  init_mode();
@@ -229288,10 +229547,10 @@ __export(exports_loader, {
229288
229547
  });
229289
229548
  import { createHash as createHash8 } from "node:crypto";
229290
229549
  import { readFileSync as readFileSync34, statSync as statSync17, watch } from "node:fs";
229291
- import { homedir as homedir15 } from "node:os";
229550
+ import { homedir as homedir16 } from "node:os";
229292
229551
  import { dirname as dirname23, join as join54, resolve as resolve25 } from "node:path";
229293
229552
  function getUserSettingsPaths(options = {}) {
229294
- const homeDir = options.homeDir || homedir15();
229553
+ const homeDir = options.homeDir || homedir16();
229295
229554
  const env6 = { ...process.env, HOME: homeDir };
229296
229555
  if (options.configDir !== undefined) {
229297
229556
  env6.LETTA_CONFIG_DIR = options.configDir;
@@ -229567,8 +229826,8 @@ __export(exports_analyzer, {
229567
229826
  parseAbsoluteCommandPaths: () => parseAbsoluteCommandPaths,
229568
229827
  analyzeApprovalContext: () => analyzeApprovalContext
229569
229828
  });
229570
- import { homedir as homedir16 } from "node:os";
229571
- import { dirname as dirname24, relative as relative5, resolve as resolve26, win32 as win325 } from "node:path";
229829
+ import { homedir as homedir17 } from "node:os";
229830
+ import { dirname as dirname24, relative as relative5, resolve as resolve26, win32 as win326 } from "node:path";
229572
229831
  function normalizeOsPath(path19) {
229573
229832
  return path19.replace(/\\/g, "/");
229574
229833
  }
@@ -229577,24 +229836,24 @@ function isWindowsPath(path19) {
229577
229836
  }
229578
229837
  function resolvePathForContext(basePath, targetPath) {
229579
229838
  const windows = isWindowsPath(basePath) || isWindowsPath(targetPath);
229580
- return windows ? win325.resolve(basePath, targetPath) : resolve26(basePath, targetPath);
229839
+ return windows ? win326.resolve(basePath, targetPath) : resolve26(basePath, targetPath);
229581
229840
  }
229582
229841
  function relativePathForContext(basePath, targetPath) {
229583
229842
  const windows = isWindowsPath(basePath) || isWindowsPath(targetPath);
229584
- return windows ? win325.relative(basePath, targetPath) : relative5(basePath, targetPath);
229843
+ return windows ? win326.relative(basePath, targetPath) : relative5(basePath, targetPath);
229585
229844
  }
229586
229845
  function isPathWithinDirectory(path19, directory) {
229587
229846
  const windows = isWindowsPath(path19) || isWindowsPath(directory);
229588
229847
  const normalizedPath = normalizeOsPath(path19);
229589
229848
  const normalizedDirectory = normalizeOsPath(directory);
229590
- const relativePath = normalizeOsPath(windows ? win325.relative(normalizedDirectory.toLowerCase(), normalizedPath.toLowerCase()) : relativePathForContext(normalizedDirectory, normalizedPath));
229849
+ const relativePath = normalizeOsPath(windows ? win326.relative(normalizedDirectory.toLowerCase(), normalizedPath.toLowerCase()) : relativePathForContext(normalizedDirectory, normalizedPath));
229591
229850
  if (relativePath === "") {
229592
229851
  return true;
229593
229852
  }
229594
229853
  return !relativePath.startsWith("../") && relativePath !== ".." && !relativePath.startsWith("/") && !/^[a-zA-Z]:\//.test(relativePath);
229595
229854
  }
229596
229855
  function dirnameForContext(path19) {
229597
- return isWindowsPath(path19) ? win325.dirname(path19) : dirname24(path19);
229856
+ return isWindowsPath(path19) ? win326.dirname(path19) : dirname24(path19);
229598
229857
  }
229599
229858
  function formatAbsoluteRulePath(path19) {
229600
229859
  const normalized = normalizeOsPath(path19).replace(/\/+$/, "");
@@ -229604,7 +229863,7 @@ function formatAbsoluteRulePath(path19) {
229604
229863
  return `//${normalized.replace(/^\/+/, "")}`;
229605
229864
  }
229606
229865
  function formatDisplayPath(path19) {
229607
- return normalizeOsPath(path19).replace(normalizeOsPath(homedir16()), "~");
229866
+ return normalizeOsPath(path19).replace(normalizeOsPath(homedir17()), "~");
229608
229867
  }
229609
229868
  function analyzeApprovalContext(toolName2, toolArgs, workingDirectory) {
229610
229869
  const canonicalTool = canonicalToolName(toolNameForPermissionCheck(toolName2, toolArgs));
@@ -233601,7 +233860,7 @@ async function executeToolInner(name, args, options) {
233601
233860
  let invocationRedactions = captureSecretRedactions(scopedAgentId);
233602
233861
  let outputStreamer = null;
233603
233862
  try {
233604
- let enhancedArgs = args;
233863
+ let enhancedArgs = expandPathArgs(internalName, args, workingDirectory);
233605
233864
  if (options?.signal) {
233606
233865
  enhancedArgs = { ...enhancedArgs, signal: options.signal };
233607
233866
  }
@@ -233811,6 +234070,7 @@ var init_manager2 = __esm(async () => {
233811
234070
  init_conversation_handle();
233812
234071
  init_permission_registry();
233813
234072
  init_tool_registry();
234073
+ init_file_path_args();
233814
234074
  init_openai_codex_provider();
233815
234075
  init_runtime_context();
233816
234076
  init_runtime_execution_settings();
@@ -234759,7 +235019,7 @@ async function buildToolCatalog(deps, agentId, options = {}) {
234759
235019
  return alias !== undefined && options.toolName?.startsWith(`mcp__${alias}__`) === true;
234760
235020
  });
234761
235021
  }
234762
- const catalog = [];
235022
+ const catalog2 = [];
234763
235023
  const connections = [];
234764
235024
  const usedNames = new Set;
234765
235025
  try {
@@ -234779,7 +235039,7 @@ async function buildToolCatalog(deps, agentId, options = {}) {
234779
235039
  throw new Error("MCP server alias was not assigned");
234780
235040
  for (const tool of [...tools].sort((left, right) => left.id.localeCompare(right.id))) {
234781
235041
  const name = uniqueMcpName(formatServerMcpToolName(server2.serverName, alias, tool.name), usedNames);
234782
- catalog.push({
235042
+ catalog2.push({
234783
235043
  schema: {
234784
235044
  name,
234785
235045
  ...tool.title ? { title: tool.title } : {},
@@ -234821,14 +235081,14 @@ async function buildToolCatalog(deps, agentId, options = {}) {
234821
235081
  throw new Error("MCP server alias was not assigned");
234822
235082
  for (const tool of connection.tools) {
234823
235083
  const name = uniqueMcpName(formatClientMcpToolName(alias, tool.name), usedNames);
234824
- catalog.push({
235084
+ catalog2.push({
234825
235085
  schema: { ...tool, name },
234826
235086
  target: { kind: "client", connection, rawName: tool.name }
234827
235087
  });
234828
235088
  }
234829
235089
  }
234830
235090
  return {
234831
- tools: catalog,
235091
+ tools: catalog2,
234832
235092
  excludedHostedStdioServers,
234833
235093
  close: async () => {
234834
235094
  await Promise.allSettled(connections.map((connection) => connection.close()));
@@ -234889,15 +235149,15 @@ async function runGet(deps, agentId, selector, stdout) {
234889
235149
  return 0;
234890
235150
  }
234891
235151
  async function runTools(deps, agentId, serverSelector, full, stdout) {
234892
- const catalog = await buildToolCatalog(deps, agentId, { serverSelector });
235152
+ const catalog2 = await buildToolCatalog(deps, agentId, { serverSelector });
234893
235153
  try {
234894
- await printJson(stdout, catalog.tools.map((tool) => full ? tool.schema : {
235154
+ await printJson(stdout, catalog2.tools.map((tool) => full ? tool.schema : {
234895
235155
  name: tool.schema.name,
234896
235156
  ...tool.schema.title ? { title: tool.schema.title } : {},
234897
235157
  ...tool.schema.description ? { description: tool.schema.description } : {}
234898
235158
  }));
234899
235159
  } finally {
234900
- await catalog.close();
235160
+ await catalog2.close();
234901
235161
  }
234902
235162
  return 0;
234903
235163
  }
@@ -234905,16 +235165,16 @@ async function runSchema(deps, agentId, toolName2, stdout) {
234905
235165
  if (!toolName2) {
234906
235166
  throw new McpCliError("invalid_arguments", "Usage: letta mcp schema <tool-name>");
234907
235167
  }
234908
- const catalog = await buildToolCatalog(deps, agentId, { toolName: toolName2 });
235168
+ const catalog2 = await buildToolCatalog(deps, agentId, { toolName: toolName2 });
234909
235169
  try {
234910
- const tool = catalog.tools.find((candidate) => candidate.schema.name === toolName2);
235170
+ const tool = catalog2.tools.find((candidate) => candidate.schema.name === toolName2);
234911
235171
  if (!tool) {
234912
235172
  throw new McpCliError("tool_not_found", `MCP tool '${toolName2}' is not available`);
234913
235173
  }
234914
235174
  await printJson(stdout, tool.schema);
234915
235175
  return 0;
234916
235176
  } finally {
234917
- await catalog.close();
235177
+ await catalog2.close();
234918
235178
  }
234919
235179
  }
234920
235180
  async function runSearch(parsed, deps, agentId, stdout) {
@@ -234930,14 +235190,14 @@ async function runSearch(parsed, deps, agentId, stdout) {
234930
235190
  if (request.searchMode === "vector") {
234931
235191
  return searchLocalMcpTools({ tools: [], ...request });
234932
235192
  }
234933
- const catalog2 = await buildToolCatalog(deps, agentId);
235193
+ const catalog3 = await buildToolCatalog(deps, agentId);
234934
235194
  try {
234935
235195
  return searchLocalMcpTools({
234936
- tools: catalog2.tools.map((tool) => tool.schema),
235196
+ tools: catalog3.tools.map((tool) => tool.schema),
234937
235197
  ...request
234938
235198
  });
234939
235199
  } finally {
234940
- await catalog2.close();
235200
+ await catalog3.close();
234941
235201
  }
234942
235202
  }
234943
235203
  const includeLocal = hasClientLocalServers && request.searchMode !== "vector";
@@ -234949,13 +235209,13 @@ async function runSearch(parsed, deps, agentId, stdout) {
234949
235209
  const catalogPromise = buildToolCatalog(deps, agentId, {
234950
235210
  ...includeLocal ? {} : { targetKind: "server" }
234951
235211
  });
234952
- let catalog;
235212
+ let catalog2;
234953
235213
  try {
234954
235214
  const [searchResults, resolvedCatalog] = await Promise.all([
234955
235215
  searchPromise,
234956
235216
  catalogPromise
234957
235217
  ]);
234958
- catalog = resolvedCatalog;
235218
+ catalog2 = resolvedCatalog;
234959
235219
  const serverResults = searchResults.flatMap((result2) => {
234960
235220
  const callable = resolvedCatalog.tools.find((tool) => tool.target.kind === "server" && tool.target.toolId === result2.toolId);
234961
235221
  if (!callable) {
@@ -234979,7 +235239,7 @@ async function runSearch(parsed, deps, agentId, stdout) {
234979
235239
  });
234980
235240
  return mergeMcpSearchResults(serverResults, localResults, request.limit);
234981
235241
  } finally {
234982
- const catalogToClose = catalog ?? await catalogPromise.catch(() => {
235242
+ const catalogToClose = catalog2 ?? await catalogPromise.catch(() => {
234983
235243
  return;
234984
235244
  });
234985
235245
  await catalogToClose?.close();
@@ -234997,8 +235257,8 @@ async function runCall(parsed, deps, agentId, stdout) {
234997
235257
  await printJson(stdout, result2);
234998
235258
  return result2.isError === true ? 2 : 0;
234999
235259
  }
235000
- async function callCatalogTool(catalog, deps, agentId, toolName2, args, options) {
235001
- const tool = catalog.tools.find((candidate) => candidate.schema.name === toolName2);
235260
+ async function callCatalogTool(catalog2, deps, agentId, toolName2, args, options) {
235261
+ const tool = catalog2.tools.find((candidate) => candidate.schema.name === toolName2);
235002
235262
  if (!tool) {
235003
235263
  throw new McpCliError("tool_not_found", `MCP tool '${toolName2}' is not available`);
235004
235264
  }
@@ -235017,11 +235277,11 @@ async function callCatalogTool(catalog, deps, agentId, toolName2, args, options)
235017
235277
  }));
235018
235278
  }
235019
235279
  async function callAgentMcpTool(agentId, toolName2, args, deps = {}) {
235020
- const catalog = await buildToolCatalog(deps, agentId, { toolName: toolName2 });
235280
+ const catalog2 = await buildToolCatalog(deps, agentId, { toolName: toolName2 });
235021
235281
  try {
235022
- return await callCatalogTool(catalog, deps, agentId, toolName2, args);
235282
+ return await callCatalogTool(catalog2, deps, agentId, toolName2, args);
235023
235283
  } finally {
235024
- await catalog.close();
235284
+ await catalog2.close();
235025
235285
  }
235026
235286
  }
235027
235287
  function createAgentMcpSession(agentId, deps = {}) {
@@ -235040,9 +235300,9 @@ function createAgentMcpSession(agentId, deps = {}) {
235040
235300
  const load = (alias) => {
235041
235301
  if (closed)
235042
235302
  throw new Error("MCP session is closed");
235043
- let catalog = catalogs.get(alias);
235044
- if (!catalog) {
235045
- catalog = getServers().then((servers2) => {
235303
+ let catalog2 = catalogs.get(alias);
235304
+ if (!catalog2) {
235305
+ catalog2 = getServers().then((servers2) => {
235046
235306
  if (closed)
235047
235307
  throw new Error("MCP session is closed");
235048
235308
  return buildToolCatalog(deps, agentId, {
@@ -235053,9 +235313,9 @@ function createAgentMcpSession(agentId, deps = {}) {
235053
235313
  catalogs.delete(alias);
235054
235314
  throw error5;
235055
235315
  });
235056
- catalogs.set(alias, catalog);
235316
+ catalogs.set(alias, catalog2);
235057
235317
  }
235058
- return catalog;
235318
+ return catalog2;
235059
235319
  };
235060
235320
  return {
235061
235321
  callTool: async (toolName2, args, options) => callCatalogTool(await load(serverAliasGroup(toolName2.slice("mcp__".length))), deps, agentId, toolName2, args, options),
@@ -235067,13 +235327,13 @@ function createAgentMcpSession(agentId, deps = {}) {
235067
235327
  })));
235068
235328
  const groups = new Set([...aliases.values()].map(serverAliasGroup));
235069
235329
  const loaded = await Promise.all([...groups].map(load));
235070
- return loaded.flatMap((catalog) => catalog.tools.map((tool) => tool.schema));
235330
+ return loaded.flatMap((catalog2) => catalog2.tools.map((tool) => tool.schema));
235071
235331
  },
235072
235332
  close: async () => {
235073
235333
  closed = true;
235074
235334
  const pending2 = [...catalogs.values()];
235075
235335
  catalogs.clear();
235076
- await Promise.allSettled(pending2.map(async (catalog) => (await catalog).close()));
235336
+ await Promise.allSettled(pending2.map(async (catalog2) => (await catalog2).close()));
235077
235337
  }
235078
235338
  };
235079
235339
  }
@@ -240356,8 +240616,8 @@ var require_constants2 = __commonJS((exports, module3) => {
240356
240616
  "@": { type: "at", open: "(?:", close: ")" }
240357
240617
  };
240358
240618
  },
240359
- globChars(win326) {
240360
- return win326 === true ? WINDOWS_CHARS : POSIX_CHARS;
240619
+ globChars(win327) {
240620
+ return win327 === true ? WINDOWS_CHARS : POSIX_CHARS;
240361
240621
  }
240362
240622
  };
240363
240623
  });
@@ -240365,7 +240625,7 @@ var require_constants2 = __commonJS((exports, module3) => {
240365
240625
  // node_modules/picomatch/lib/utils.js
240366
240626
  var require_utils2 = __commonJS((exports) => {
240367
240627
  var path28 = __require("path");
240368
- var win326 = process.platform === "win32";
240628
+ var win327 = process.platform === "win32";
240369
240629
  var {
240370
240630
  REGEX_BACKSLASH,
240371
240631
  REGEX_REMOVE_BACKSLASH,
@@ -240393,7 +240653,7 @@ var require_utils2 = __commonJS((exports) => {
240393
240653
  if (options && typeof options.windows === "boolean") {
240394
240654
  return options.windows;
240395
240655
  }
240396
- return win326 === true || path28.sep === "\\";
240656
+ return win327 === true || path28.sep === "\\";
240397
240657
  };
240398
240658
  exports.escapeLast = (input, char, lastIdx) => {
240399
240659
  const idx = input.lastIndexOf(char, lastIdx);
@@ -240778,8 +241038,8 @@ var require_parse3 = __commonJS((exports, module3) => {
240778
241038
  const bos = { type: "bos", value: "", output: opts.prepend || "" };
240779
241039
  const tokens = [bos];
240780
241040
  const capture = opts.capture ? "" : "?:";
240781
- const win326 = utils.isWindows(options);
240782
- const PLATFORM_CHARS = constants6.globChars(win326);
241041
+ const win327 = utils.isWindows(options);
241042
+ const PLATFORM_CHARS = constants6.globChars(win327);
240783
241043
  const EXTGLOB_CHARS = constants6.extglobChars(PLATFORM_CHARS);
240784
241044
  const {
240785
241045
  DOT_LITERAL,
@@ -241451,7 +241711,7 @@ var require_parse3 = __commonJS((exports, module3) => {
241451
241711
  throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max2}`);
241452
241712
  }
241453
241713
  input = REPLACEMENTS[input] || input;
241454
- const win326 = utils.isWindows(options);
241714
+ const win327 = utils.isWindows(options);
241455
241715
  const {
241456
241716
  DOT_LITERAL,
241457
241717
  SLASH_LITERAL,
@@ -241462,7 +241722,7 @@ var require_parse3 = __commonJS((exports, module3) => {
241462
241722
  NO_DOTS_SLASH,
241463
241723
  STAR,
241464
241724
  START_ANCHOR
241465
- } = constants6.globChars(win326);
241725
+ } = constants6.globChars(win327);
241466
241726
  const nodot = opts.dot ? NO_DOTS : NO_DOT;
241467
241727
  const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
241468
241728
  const capture = opts.capture ? "" : "?:";
@@ -246329,12 +246589,12 @@ var init_subagent_process = __esm(() => {
246329
246589
  });
246330
246590
 
246331
246591
  // src/utils/native-cli-env.ts
246332
- import { homedir as homedir17 } from "node:os";
246592
+ import { homedir as homedir18 } from "node:os";
246333
246593
  import { join as join62 } from "node:path";
246334
246594
  function withNativeCliPath(env6, platform7 = process.platform) {
246335
246595
  if (platform7 === "win32")
246336
246596
  return { ...env6 };
246337
- const nativeBin = join62(env6.HOME || homedir17(), ".local", "bin");
246597
+ const nativeBin = join62(env6.HOME || homedir18(), ".local", "bin");
246338
246598
  const paths = (env6.PATH ?? "/usr/bin:/bin").split(":");
246339
246599
  if (!paths.includes(nativeBin))
246340
246600
  paths.push(nativeBin);
@@ -247234,7 +247494,7 @@ class CodexAppServerClient {
247234
247494
  await this.request("initialize", {
247235
247495
  clientInfo: {
247236
247496
  name: "letta-code",
247237
- version: "0.34.41"
247497
+ version: "0.34.42"
247238
247498
  },
247239
247499
  capabilities: null
247240
247500
  });
@@ -248952,7 +249212,7 @@ import {
248952
249212
  rm as rm8,
248953
249213
  stat as stat10
248954
249214
  } from "node:fs/promises";
248955
- import { homedir as homedir18, tmpdir as tmpdir13 } from "node:os";
249215
+ import { homedir as homedir19, tmpdir as tmpdir13 } from "node:os";
248956
249216
  import { join as join64 } from "node:path";
248957
249217
  async function hashNativeSessionPrefix(input, size2) {
248958
249218
  const hash3 = createHash10("sha256");
@@ -249189,7 +249449,7 @@ async function entries(path30, directories) {
249189
249449
  async function findNativeSessionPath(source, sessionId, env6 = process.env) {
249190
249450
  if (!UUID2.test(sessionId))
249191
249451
  return;
249192
- const home = env6.HOME || homedir18();
249452
+ const home = env6.HOME || homedir19();
249193
249453
  if (source === "claude_code") {
249194
249454
  const projects = join64(env6.CLAUDE_CONFIG_DIR || join64(home, ".claude"), "projects");
249195
249455
  for (const project of await entries(projects, true)) {
@@ -251200,7 +251460,7 @@ function isMemoryWorkerSession(env6 = process.env) {
251200
251460
  var MEMORY_WORKER_SESSION_ENV = "LETTA_MEMORY_WORKER_SESSION";
251201
251461
 
251202
251462
  // src/agent/subagents/subagent-launcher.ts
251203
- import { homedir as homedir19 } from "node:os";
251463
+ import { homedir as homedir20 } from "node:os";
251204
251464
  import { join as join67 } from "node:path";
251205
251465
  function resolveSubagentWorkingDirectory(env6 = process.env, fallbackCwd = getCurrentWorkingDirectory(), options = {}) {
251206
251466
  if (options.subagentType === "reflection" && options.launchProfile === "memory-subagent" && options.memoryScope) {
@@ -251259,7 +251519,7 @@ function resolveMemorySubagentScratchpad(parentProcessEnv, subagentId) {
251259
251519
  return configuredScratchpad;
251260
251520
  }
251261
251521
  const configuredTranscriptRoot = parentProcessEnv[TRANSCRIPT_ROOT_ENV];
251262
- const transcriptRoot = configuredTranscriptRoot?.trim() || join67(resolveGlobalConfigDir(parentProcessEnv, homedir19()), "transcripts");
251522
+ const transcriptRoot = configuredTranscriptRoot?.trim() || join67(resolveGlobalConfigDir(parentProcessEnv, homedir20()), "transcripts");
251263
251523
  const scope = subagentId ? encodeURIComponent(subagentId) : crypto.randomUUID();
251264
251524
  return join67(transcriptRoot, "background", scope);
251265
251525
  }
@@ -254406,14 +254666,14 @@ var init_send_agent_message = __esm(async () => {
254406
254666
 
254407
254667
  // src/helpers/working-directory.ts
254408
254668
  import { realpath as realpath5, stat as stat11 } from "node:fs/promises";
254409
- import { homedir as homedir20 } from "node:os";
254669
+ import { homedir as homedir21 } from "node:os";
254410
254670
  import path30 from "node:path";
254411
254671
  function expandHome(value) {
254412
254672
  if (value === "~") {
254413
- return homedir20();
254673
+ return homedir21();
254414
254674
  }
254415
254675
  if (value.startsWith(`~${path30.sep}`) || value.startsWith("~/")) {
254416
- return path30.join(homedir20(), value.slice(2));
254676
+ return path30.join(homedir21(), value.slice(2));
254417
254677
  }
254418
254678
  return value;
254419
254679
  }
@@ -256359,7 +256619,7 @@ function usageTokensFromEvent(event) {
256359
256619
  const total = event.total_tokens;
256360
256620
  return typeof total === "number" && Number.isFinite(total) ? total : undefined;
256361
256621
  }
256362
- async function drainTurn(query3, usage, stop, maxToolCalls, onUsage, onStarted) {
256622
+ async function drainTurn(query3, usage, stop, maxToolCalls, onUsage, onStarted, model) {
256363
256623
  let assistantText2 = "";
256364
256624
  let resultText;
256365
256625
  let success = false;
@@ -256376,6 +256636,8 @@ async function drainTurn(query3, usage, stop, maxToolCalls, onUsage, onStarted)
256376
256636
  if (message2.type === "assistant")
256377
256637
  assistantText2 += message2.content ?? "";
256378
256638
  if (message2.type === "stream_event") {
256639
+ if (message2.event)
256640
+ message2.event = priceUsageEvent(message2.event, model);
256379
256641
  const tokens = usageTokensFromEvent(message2.event);
256380
256642
  if (tokens !== undefined) {
256381
256643
  usage.totalTokens = (usage.totalTokens ?? 0) + tokens;
@@ -256588,7 +256850,7 @@ ${prompt}` : prompt,
256588
256850
  }
256589
256851
  hooks?.onStarted?.(id2);
256590
256852
  }
256591
- }),
256853
+ }, model),
256592
256854
  stopped
256593
256855
  ]);
256594
256856
  if (!finished2 && query3.conversationId) {
@@ -256663,6 +256925,7 @@ var init_sdk_spawner = __esm(async () => {
256663
256925
  init_backend2();
256664
256926
  init_tool_registry();
256665
256927
  init_tool_name_mapping();
256928
+ init_cost();
256666
256929
  await init_tool_definitions();
256667
256930
  DEFAULT_SUBAGENT_TIMEOUT_MS = 10 * 60 * 1000;
256668
256931
  });
@@ -268661,9 +268924,13 @@ function defaultIsProcessAlive2(pid) {
268661
268924
  function getDefaultBootTimeMs() {
268662
268925
  return Date.now() - uptime2() * 1000;
268663
268926
  }
268664
- function isOwnerAlive2(record6, deps) {
268927
+ async function isOwnerAlive2(record6, deps) {
268665
268928
  if (!deps.isProcessAlive(record6.pid))
268666
268929
  return false;
268930
+ if (record6.started) {
268931
+ const started = await deps.getProcessStartTime(record6.pid);
268932
+ return started === null || started === record6.started;
268933
+ }
268667
268934
  const acquiredAtMs = Date.parse(record6.acquiredAt);
268668
268935
  if (!Number.isFinite(acquiredAtMs) || acquiredAtMs >= deps.bootTimeMs - BOOT_TIME_SLACK_MS2) {
268669
268936
  return true;
@@ -268697,7 +268964,7 @@ function getManualListenerScopeHash(scope) {
268697
268964
  function parseLockRecord(raw2, expectedScopeHash) {
268698
268965
  try {
268699
268966
  const parsed = JSON.parse(raw2);
268700
- if (parsed.version !== 1 || !Number.isSafeInteger(parsed.pid) || (parsed.pid ?? 0) <= 0 || typeof parsed.ownerToken !== "string" || parsed.ownerToken.length === 0 || typeof parsed.acquiredAt !== "string" || parsed.scopeHash !== expectedScopeHash) {
268967
+ if (parsed.version !== 1 || !Number.isSafeInteger(parsed.pid) || (parsed.pid ?? 0) <= 0 || typeof parsed.ownerToken !== "string" || parsed.ownerToken.length === 0 || typeof parsed.acquiredAt !== "string" || parsed.started !== undefined && (typeof parsed.started !== "string" || parsed.started.length === 0) || parsed.scopeHash !== expectedScopeHash) {
268701
268968
  return null;
268702
268969
  }
268703
268970
  return parsed;
@@ -268754,7 +269021,7 @@ async function recoverDeadOwner(lockPath, staleContents, recoveryOwnerContents,
268754
269021
  if (!claimOwner) {
268755
269022
  throw new ManualListenerLockUnavailableError(`Listener lock recovery record is invalid: ${claimPath}`, lockPath);
268756
269023
  }
268757
- if (isOwnerAlive2(claimOwner, deps)) {
269024
+ if (await isOwnerAlive2(claimOwner, deps)) {
268758
269025
  return false;
268759
269026
  }
268760
269027
  }
@@ -268787,16 +269054,20 @@ async function acquireManualListenerLock(scope, overrides = {}) {
268787
269054
  isProcessAlive: defaultIsProcessAlive2,
268788
269055
  bootTimeMs: getDefaultBootTimeMs(),
268789
269056
  getProcessCommand,
269057
+ getOwnProcessStartTime,
269058
+ getProcessStartTime,
268790
269059
  ...overrides
268791
269060
  };
268792
269061
  const listenerLockDir = path33.join(deps.lockRoot, "listeners");
268793
269062
  const lockPath = path33.join(listenerLockDir, `manual-${scopeHash}.lock`);
269063
+ const started = await deps.getOwnProcessStartTime() ?? undefined;
268794
269064
  const ownerRecord2 = {
268795
269065
  version: 1,
268796
269066
  pid: deps.processId,
268797
269067
  ownerToken: deps.ownerToken,
268798
269068
  acquiredAt: new Date().toISOString(),
268799
- scopeHash
269069
+ scopeHash,
269070
+ ...started ? { started } : {}
268800
269071
  };
268801
269072
  const ownerContents = JSON.stringify(ownerRecord2);
268802
269073
  try {
@@ -268846,7 +269117,7 @@ async function acquireManualListenerLock(scope, overrides = {}) {
268846
269117
  if (!incumbent) {
268847
269118
  throw new ManualListenerLockUnavailableError(`Listener lock is corrupt or belongs to an incompatible version: ${lockPath}`, lockPath);
268848
269119
  }
268849
- if (isOwnerAlive2(incumbent, deps)) {
269120
+ if (await isOwnerAlive2(incumbent, deps)) {
268850
269121
  throw new ManualListenerAlreadyRunningError(incumbent.pid, lockPath);
268851
269122
  }
268852
269123
  const recovered = await recoverDeadOwner(lockPath, incumbentContents, ownerContents, scopeHash, deps);
@@ -271980,7 +272251,7 @@ function reasoningEffortForThinkingLevel(level) {
271980
272251
  }
271981
272252
  function toRuntimeCatalogModels(entries2) {
271982
272253
  const ids = uniqueLocalModelIds(entries2);
271983
- const catalog = [];
272254
+ const catalog2 = [];
271984
272255
  for (const entry of entries2) {
271985
272256
  const baseId = ids.get(entry.handle) ?? entry.handle;
271986
272257
  const levels = entry.reasoningLevels ?? [];
@@ -271997,7 +272268,7 @@ function toRuntimeCatalogModels(entries2) {
271997
272268
  } : {},
271998
272269
  parallel_tool_calls: true
271999
272270
  };
272000
- catalog.push({
272271
+ catalog2.push({
272001
272272
  id: effort ? `${baseId}-${effort}` : baseId,
272002
272273
  handle: entry.handle,
272003
272274
  label: entry.label,
@@ -272007,7 +272278,7 @@ function toRuntimeCatalogModels(entries2) {
272007
272278
  });
272008
272279
  }
272009
272280
  }
272010
- return catalog;
272281
+ return catalog2;
272011
272282
  }
272012
272283
  async function refreshRuntimeModelCatalog(source, options) {
272013
272284
  const sourceChanged = activeCatalogSource !== source;
@@ -272658,9 +272929,9 @@ var init_paths2 = __esm(() => {
272658
272929
 
272659
272930
  // src/mods/mod-diagnostics-file.ts
272660
272931
  import { mkdirSync as mkdirSync42, writeFileSync as writeFileSync37 } from "node:fs";
272661
- import { homedir as homedir21 } from "node:os";
272932
+ import { homedir as homedir22 } from "node:os";
272662
272933
  import path35 from "node:path";
272663
- function getDefaultModDiagnosticsRoot(homeDirectory = homedir21()) {
272934
+ function getDefaultModDiagnosticsRoot(homeDirectory = homedir22()) {
272664
272935
  return path35.join(resolveDefaultGlobalModsDirectory(homeDirectory), "diagnostics");
272665
272936
  }
272666
272937
  function getModDiagnosticsLatestFilePath(rootDirectory = getDefaultModDiagnosticsRoot()) {
@@ -444317,13 +444588,12 @@ async function applyModelUpdateForRuntime(params) {
444317
444588
  agentId,
444318
444589
  conversationId
444319
444590
  });
444320
- const shouldPreserveContextWindow = shouldPreserveContextWindowForModelSelection({
444591
+ const preservedContextWindow = contextWindowToPreserveForModelSelection({
444321
444592
  currentModelHandle: currentModelScope.modelHandle,
444322
444593
  currentLlmConfig: currentModelScope.llmConfig,
444323
444594
  selectedModelHandle: model.handle,
444324
444595
  selectedContextWindow
444325
444596
  });
444326
- const preservedContextWindow = shouldPreserveContextWindow ? preservableContextWindow(currentModelScope.llmConfig?.context_window, model.handle) : undefined;
444327
444597
  const updateOptions = preservedContextWindow !== undefined ? { contextWindowOverride: preservedContextWindow } : undefined;
444328
444598
  const updateArgsForRequest = { ...updateArgs };
444329
444599
  let modelSettings = null;
@@ -446167,10 +446437,21 @@ async function applyRuntimeStartState(parsed, context3, scope, scopedRuntime) {
446167
446437
  }
446168
446438
  const state2 = getOrCreateConversationPermissionModeStateRef(context3.runtime, scope.agent_id, scope.conversation_id);
446169
446439
  if (!(parsed.mode_is_default && state2.explicit)) {
446440
+ const previousMode = state2.mode;
446170
446441
  state2.mode = mode;
446171
446442
  if (!parsed.mode_is_default)
446172
446443
  state2.explicit = true;
446173
446444
  persistPermissionModeMapForRuntime(context3.runtime);
446445
+ if (previousMode !== mode) {
446446
+ telemetry.trackPermissionModeChanged({
446447
+ agent_id: scope.agent_id,
446448
+ conversation_id: scope.conversation_id,
446449
+ prev_mode: previousMode,
446450
+ new_mode: mode,
446451
+ source: "runtime_start",
446452
+ mode_is_default: parsed.mode_is_default === true
446453
+ });
446454
+ }
446174
446455
  }
446175
446456
  }
446176
446457
  if (parsed.cwd !== undefined || workspaceSandbox) {
@@ -446272,6 +446553,7 @@ var init_runtime_start = __esm(async () => {
446272
446553
  init_sandbox_policy();
446273
446554
  init_workspace_sandbox();
446274
446555
  init_settings_manager();
446556
+ init_telemetry();
446275
446557
  init_cwd();
446276
446558
  init_permission_mode();
446277
446559
  init_runtime_start_validation();
@@ -447155,9 +447437,20 @@ function handleModeChange(msg, socket, runtime, scope) {
447155
447437
  });
447156
447438
  return;
447157
447439
  }
447440
+ const previousMode = current.mode;
447158
447441
  current.mode = incomingMode;
447159
447442
  current.explicit = true;
447160
447443
  persistPermissionModeMapForRuntime(runtime);
447444
+ if (previousMode !== incomingMode) {
447445
+ telemetry.trackPermissionModeChanged({
447446
+ agent_id: agentId,
447447
+ conversation_id: conversationId,
447448
+ prev_mode: previousMode,
447449
+ new_mode: incomingMode,
447450
+ source: "user_toggle",
447451
+ mode_is_default: false
447452
+ });
447453
+ }
447161
447454
  emitRuntimeStateUpdates(runtime, scope);
447162
447455
  if (isDebugEnabled()) {
447163
447456
  console.log(`[Listen] Mode changed to: ${msg.mode}`);
@@ -447436,6 +447729,7 @@ var init_control_inputs = __esm(async () => {
447436
447729
  init_backend2();
447437
447730
  init_constants2();
447438
447731
  init_mode();
447732
+ init_telemetry();
447439
447733
  init_error_reporting();
447440
447734
  init_debug();
447441
447735
  init_cwd();
@@ -455350,12 +455644,16 @@ async function handleApprovalStop(params) {
455350
455644
  agent_id: agentId,
455351
455645
  conversation_id: conversationId
455352
455646
  };
455647
+ const classificationPermissionMode = turnPermissionModeState.mode;
455648
+ const classificationPermissionModeState = {
455649
+ mode: classificationPermissionMode
455650
+ };
455353
455651
  const { autoAllowed, autoDenied, needsUserInput } = await classifyApprovals2(approvals, {
455354
455652
  treatAskAsDeny: false,
455355
455653
  requireArgsForAutoApprove: true,
455356
455654
  missingNameReason: "Tool call incomplete - missing name",
455357
455655
  workingDirectory: turnWorkingDirectory,
455358
- permissionModeState: turnPermissionModeState,
455656
+ permissionModeState: classificationPermissionModeState,
455359
455657
  agentId: agentId ?? undefined,
455360
455658
  toolContextId: turnToolContextId ?? undefined
455361
455659
  });
@@ -455376,7 +455674,8 @@ async function handleApprovalStop(params) {
455376
455674
  ...createLifecycleMessageBase("approval_classification_end", classificationRunId),
455377
455675
  auto_allowed_tool_call_ids: autoAllowed.map((entry) => entry.approval.toolCallId),
455378
455676
  auto_denied_tool_call_ids: autoDenied.map((entry) => entry.approval.toolCallId),
455379
- user_input_tool_call_ids: needsUserInput.map((entry) => entry.approval.toolCallId)
455677
+ user_input_tool_call_ids: needsUserInput.map((entry) => entry.approval.toolCallId),
455678
+ permission_mode: classificationPermissionMode
455380
455679
  };
455381
455680
  emitCanonicalMessageDelta(socket, runtime, classificationEnd, classificationScope);
455382
455681
  const continuationWasFullyAutoHandled = needsUserInput.length === 0;
@@ -455536,7 +455835,7 @@ async function handleApprovalStop(params) {
455536
455835
  requireArgsForAutoApprove: true,
455537
455836
  missingNameReason: "Tool call incomplete - missing name",
455538
455837
  workingDirectory: turnWorkingDirectory,
455539
- permissionModeState: turnPermissionModeState,
455838
+ permissionModeState: classificationPermissionModeState,
455540
455839
  agentId: agentId ?? undefined,
455541
455840
  toolContextId: turnToolContextId ?? undefined
455542
455841
  });
@@ -458416,7 +458715,7 @@ var init_core5 = __esm(() => {
458416
458715
  // node_modules/@letta-ai/trajectory/dist/adapters/deepagents/index.js
458417
458716
  import { spawn as spawn11 } from "node:child_process";
458418
458717
  import { accessSync as accessSync2, constants as constants6 } from "node:fs";
458419
- import { homedir as homedir22 } from "node:os";
458718
+ import { homedir as homedir23 } from "node:os";
458420
458719
  import { join as join86 } from "node:path";
458421
458720
  import { fileURLToPath as fileURLToPath9 } from "node:url";
458422
458721
  async function normalizeCheckpoint(input) {
@@ -458441,7 +458740,7 @@ async function decodeCheckpoint(input) {
458441
458740
  }
458442
458741
  async function loadDeepAgentsCheckpoint(checkpoint) {
458443
458742
  validateLocation(checkpoint);
458444
- const path43 = checkpoint.path ?? join86(homedir22(), ".deepagents", "sessions.db");
458743
+ const path43 = checkpoint.path ?? join86(homedir23(), ".deepagents", "sessions.db");
458445
458744
  const python = checkpoint.pythonExecutable ?? process.env.PYTHON ?? "python3";
458446
458745
  const helper = resolveHelperPath();
458447
458746
  return await new Promise((resolve38, reject2) => {
@@ -458790,10 +459089,10 @@ var init_listing_shared = __esm(() => {
458790
459089
  });
458791
459090
 
458792
459091
  // node_modules/@letta-ai/trajectory/dist/adapters/claude-code/list.js
458793
- import { homedir as homedir23 } from "node:os";
459092
+ import { homedir as homedir24 } from "node:os";
458794
459093
  import { basename as basename25, join as join88 } from "node:path";
458795
459094
  async function listClaudeCodeTrajectories(root2) {
458796
- const base2 = root2 ?? join88(homedir23(), ".claude", "projects");
459095
+ const base2 = root2 ?? join88(homedir24(), ".claude", "projects");
458797
459096
  const items3 = [];
458798
459097
  for (const project of safeReadDir(base2)) {
458799
459098
  if (!project.isDirectory)
@@ -458815,10 +459114,10 @@ var init_list = __esm(() => {
458815
459114
  });
458816
459115
 
458817
459116
  // node_modules/@letta-ai/trajectory/dist/adapters/codex/list.js
458818
- import { homedir as homedir24 } from "node:os";
459117
+ import { homedir as homedir25 } from "node:os";
458819
459118
  import { basename as basename26, join as join89 } from "node:path";
458820
459119
  async function listCodexTrajectories(root2) {
458821
- const base2 = root2 ?? join89(homedir24(), ".codex", "sessions");
459120
+ const base2 = root2 ?? join89(homedir25(), ".codex", "sessions");
458822
459121
  const items3 = [];
458823
459122
  for (const path43 of collectFiles(base2, ".jsonl", 4)) {
458824
459123
  const listing = listingFromFile(basename26(path43, ".jsonl"), path43);
@@ -458832,7 +459131,7 @@ var init_list2 = __esm(() => {
458832
459131
  });
458833
459132
 
458834
459133
  // node_modules/@letta-ai/trajectory/dist/adapters/deepagents/list.js
458835
- import { homedir as homedir25 } from "node:os";
459134
+ import { homedir as homedir26 } from "node:os";
458836
459135
  import { join as join90 } from "node:path";
458837
459136
  async function listDeepAgentsTrajectories(root2) {
458838
459137
  const path43 = resolveStorePath(root2);
@@ -458854,7 +459153,7 @@ async function listDeepAgentsTrajectories(root2) {
458854
459153
  }
458855
459154
  function resolveStorePath(root2) {
458856
459155
  if (root2 === undefined)
458857
- return join90(homedir25(), ".deepagents", "sessions.db");
459156
+ return join90(homedir26(), ".deepagents", "sessions.db");
458858
459157
  return root2.endsWith(".db") ? root2 : join90(root2, "sessions.db");
458859
459158
  }
458860
459159
  var init_list3 = __esm(() => {
@@ -458862,7 +459161,7 @@ var init_list3 = __esm(() => {
458862
459161
  });
458863
459162
 
458864
459163
  // node_modules/@letta-ai/trajectory/dist/adapters/hermes/list.js
458865
- import { homedir as homedir26 } from "node:os";
459164
+ import { homedir as homedir27 } from "node:os";
458866
459165
  import { join as join91 } from "node:path";
458867
459166
  async function listHermesTrajectories(root2) {
458868
459167
  const path43 = resolveStorePath2(root2);
@@ -458890,7 +459189,7 @@ async function listHermesTrajectories(root2) {
458890
459189
  }
458891
459190
  function resolveStorePath2(root2) {
458892
459191
  if (root2 === undefined)
458893
- return join91(homedir26(), ".hermes", "state.db");
459192
+ return join91(homedir27(), ".hermes", "state.db");
458894
459193
  return root2.endsWith(".db") ? root2 : join91(root2, "state.db");
458895
459194
  }
458896
459195
  function numeric2(value) {
@@ -458901,10 +459200,10 @@ var init_list4 = __esm(() => {
458901
459200
  });
458902
459201
 
458903
459202
  // node_modules/@letta-ai/trajectory/dist/adapters/letta-code/list.js
458904
- import { homedir as homedir27 } from "node:os";
459203
+ import { homedir as homedir28 } from "node:os";
458905
459204
  import { join as join92 } from "node:path";
458906
459205
  async function listLettaCodeTrajectories(root2) {
458907
- const base2 = root2 ?? join92(homedir27(), ".letta", "transcripts");
459206
+ const base2 = root2 ?? join92(homedir28(), ".letta", "transcripts");
458908
459207
  const items3 = [];
458909
459208
  for (const agent of safeReadDir(base2)) {
458910
459209
  if (!agent.isDirectory)
@@ -458927,7 +459226,7 @@ var init_list5 = __esm(() => {
458927
459226
 
458928
459227
  // node_modules/@letta-ai/trajectory/dist/adapters/openclaw/list.js
458929
459228
  import { existsSync as existsSync62 } from "node:fs";
458930
- import { homedir as homedir28 } from "node:os";
459229
+ import { homedir as homedir29 } from "node:os";
458931
459230
  import { basename as basename27, join as join93 } from "node:path";
458932
459231
  async function listOpenClawTrajectories(root2) {
458933
459232
  const base2 = root2 ?? defaultStateDir();
@@ -458952,20 +459251,20 @@ function defaultStateDir() {
458952
459251
  const override = process.env.OPENCLAW_STATE_DIR?.trim() || process.env.CLAWDBOT_STATE_DIR?.trim();
458953
459252
  if (override)
458954
459253
  return override;
458955
- const current = join93(homedir28(), ".openclaw");
459254
+ const current = join93(homedir29(), ".openclaw");
458956
459255
  if (existsSync62(current))
458957
459256
  return current;
458958
- return join93(homedir28(), ".clawdbot");
459257
+ return join93(homedir29(), ".clawdbot");
458959
459258
  }
458960
459259
  var init_list6 = __esm(() => {
458961
459260
  init_listing_shared();
458962
459261
  });
458963
459262
 
458964
459263
  // node_modules/@letta-ai/trajectory/dist/adapters/openhands/list.js
458965
- import { homedir as homedir29 } from "node:os";
459264
+ import { homedir as homedir30 } from "node:os";
458966
459265
  import { join as join94 } from "node:path";
458967
459266
  async function listOpenHandsTrajectories(root2) {
458968
- const base2 = root2 ?? join94(homedir29(), ".openhands", "sessions");
459267
+ const base2 = root2 ?? join94(homedir30(), ".openhands", "sessions");
458969
459268
  const items3 = [];
458970
459269
  for (const entry of safeReadDir(base2)) {
458971
459270
  if (!entry.isDirectory)
@@ -463858,11 +464157,11 @@ var init_grep_in_files = __esm(() => {
463858
464157
 
463859
464158
  // src/websocket/listener/write-file-command.ts
463860
464159
  import { appendFile as appendFile2, mkdir as mkdir16, rename as rename3, writeFile as writeFile18 } from "node:fs/promises";
463861
- import { homedir as homedir30 } from "node:os";
464160
+ import { homedir as homedir31 } from "node:os";
463862
464161
  import path44 from "node:path";
463863
464162
  function resolveBinaryWritePath(target2) {
463864
464163
  if (target2 === "~" || target2.startsWith("~/")) {
463865
- return path44.join(process.env.HOME || homedir30(), target2.slice(1));
464164
+ return path44.join(process.env.HOME || homedir31(), target2.slice(1));
463866
464165
  }
463867
464166
  if (!path44.isAbsolute(target2)) {
463868
464167
  throw new Error("write_file requires an absolute path or a ~/ path");
@@ -463924,7 +464223,7 @@ var init_write_file_command = __esm(() => {
463924
464223
 
463925
464224
  // src/websocket/listener/file-commands.ts
463926
464225
  import { readdir as readdir10, readFile as readFile26 } from "node:fs/promises";
463927
- import { homedir as homedir31 } from "node:os";
464226
+ import { homedir as homedir32 } from "node:os";
463928
464227
  import path45 from "node:path";
463929
464228
  function trackListenerError3(errorType, error5, context3) {
463930
464229
  trackBoundaryError({
@@ -463944,7 +464243,7 @@ function isWithinOrEqual(parent, child) {
463944
464243
  return relative11 === "" || !relative11.startsWith("..") && !path45.isAbsolute(relative11);
463945
464244
  }
463946
464245
  function getHomeDirectory() {
463947
- return normalizeAbsPath(process.env.HOME || homedir31());
464246
+ return normalizeAbsPath(process.env.HOME || homedir32());
463948
464247
  }
463949
464248
  function isHomeDirectory(absPath) {
463950
464249
  return normalizeAbsPath(absPath) === getHomeDirectory();
@@ -476487,8 +476786,8 @@ async function listExternalWorkerModels(worker, deps = {}) {
476487
476786
  const server2 = new OpenCodeServer(cwd2, env6);
476488
476787
  try {
476489
476788
  await server2.connect();
476490
- const catalog = await server2.request("/config/providers");
476491
- for (const provider of catalog.providers) {
476789
+ const catalog2 = await server2.request("/config/providers");
476790
+ for (const provider of catalog2.providers) {
476492
476791
  for (const [id2, model] of Object.entries(provider.models))
476493
476792
  models3.push({
476494
476793
  id: `${provider.id}/${id2}`,
@@ -476499,8 +476798,8 @@ async function listExternalWorkerModels(worker, deps = {}) {
476499
476798
  await server2.close();
476500
476799
  }
476501
476800
  } else {
476502
- const catalog = await (deps.listNativeModels ?? listNativeModels)(worker, cwd2, env6);
476503
- for (const model of catalog) {
476801
+ const catalog2 = await (deps.listNativeModels ?? listNativeModels)(worker, cwd2, env6);
476802
+ for (const model of catalog2) {
476504
476803
  if (!isRecord2(model))
476505
476804
  throw new Error("Invalid native model catalog entry");
476506
476805
  const id2 = worker === "codex" ? model.model : worker === "cursor" ? model.id : model.value;
@@ -476642,12 +476941,12 @@ async function runModelSubcommand(argv) {
476642
476941
  await settingsManager.initialize();
476643
476942
  const local = getBackend().capabilities.localModelCatalog;
476644
476943
  await initializeModelCatalog();
476645
- let catalog = [...models2];
476944
+ let catalog2 = [...models2];
476646
476945
  const byokCapabilities = new Map;
476647
476946
  if (local && values4.hosted)
476648
- catalog = [];
476947
+ catalog2 = [];
476649
476948
  if (!local) {
476650
- const known = new Set(catalog.map((entry) => entry.handle));
476949
+ const known = new Set(catalog2.map((entry) => entry.handle));
476651
476950
  try {
476652
476951
  const available = await getAvailableModelHandles();
476653
476952
  for (const entry of available.models) {
@@ -476657,9 +476956,9 @@ async function runModelSubcommand(argv) {
476657
476956
  }
476658
476957
  if (values4.byok || values4.hosted) {
476659
476958
  const byokHandles = new Set(available.models.filter((entry) => entry.providerCategory === "byok").map((entry) => entry.handle));
476660
- catalog = catalog.filter((entry) => values4.byok ? byokHandles.has(entry.handle) : !byokHandles.has(entry.handle));
476959
+ catalog2 = catalog2.filter((entry) => values4.byok ? byokHandles.has(entry.handle) : !byokHandles.has(entry.handle));
476661
476960
  }
476662
- catalog.push(...available.models.filter((entry) => !values4.hosted && entry.providerCategory === "byok" && !known.has(entry.handle)).map((entry) => ({
476961
+ catalog2.push(...available.models.filter((entry) => !values4.hosted && entry.providerCategory === "byok" && !known.has(entry.handle)).map((entry) => ({
476663
476962
  id: entry.handle,
476664
476963
  handle: entry.handle,
476665
476964
  label: entry.label,
@@ -476673,7 +476972,7 @@ async function runModelSubcommand(argv) {
476673
476972
  console.error(`Warning: BYOK catalog unavailable: ${error5 instanceof Error ? error5.message : String(error5)}`);
476674
476973
  }
476675
476974
  }
476676
- const rows = catalog.map((entry) => ({
476975
+ const rows = catalog2.map((entry) => ({
476677
476976
  id: entry.id,
476678
476977
  handle: entry.handle,
476679
476978
  label: entry.label,
@@ -488169,6 +488468,19 @@ var init_startup_docker_check = __esm(() => {
488169
488468
  init_server_url();
488170
488469
  });
488171
488470
 
488471
+ // src/agent/subagents/subagent-conversation.ts
488472
+ async function createSubagentConversation(cloudBackend, parentConversationId, agentId, create8) {
488473
+ if (!cloudBackend || !parentConversationId || parentConversationId === "default") {
488474
+ return "default";
488475
+ }
488476
+ const body3 = {
488477
+ agent_id: agentId,
488478
+ parent_conversation_id: parentConversationId,
488479
+ is_subagent: true
488480
+ };
488481
+ return (await create8(body3)).id;
488482
+ }
488483
+
488172
488484
  // src/headless-message-sender.ts
488173
488485
  function buildHeadlessSenderReminder(isAgentLaunch, fromAgentId, env6 = process.env) {
488174
488486
  if (isAgentLaunch && isMemoryWorkerSession(env6)) {
@@ -488328,50 +488640,6 @@ async function handleBootstrapSessionState(params) {
488328
488640
  }
488329
488641
  var init_bootstrap_handler = () => {};
488330
488642
 
488331
- // src/agent/headless-model-startup.ts
488332
- async function prepareExistingHeadlessModel(options) {
488333
- const {
488334
- agent,
488335
- modelIdentifier,
488336
- modelHandle,
488337
- createsConversation,
488338
- localModelCatalog
488339
- } = options;
488340
- if (modelHandle) {
488341
- const updateArgs2 = getModelUpdateArgs(modelIdentifier);
488342
- if (createsConversation) {
488343
- const contextWindow = updateArgs2?.context_window;
488344
- return {
488345
- agent,
488346
- conversationModel: {
488347
- model: modelHandle,
488348
- model_settings: buildModelSettings(modelHandle, updateArgs2, localModelCatalog),
488349
- ...typeof contextWindow === "number" && {
488350
- context_window_limit: contextWindow
488351
- }
488352
- }
488353
- };
488354
- }
488355
- return {
488356
- agent: await updateAgentLLMConfig(agent.id, modelHandle, updateArgs2)
488357
- };
488358
- }
488359
- const presetRefresh = getModelPresetUpdateForAgent(agent);
488360
- if (!presetRefresh)
488361
- return { agent };
488362
- const { updateArgs, needsUpdate } = getResumeRefreshArgs(presetRefresh.updateArgs, agent);
488363
- if (!needsUpdate)
488364
- return { agent };
488365
- const preservedContextWindow = preservableContextWindow(agent.llm_config?.context_window, presetRefresh.modelHandle);
488366
- return {
488367
- agent: await updateAgentLLMConfig(agent.id, presetRefresh.modelHandle, updateArgs, preservedContextWindow !== undefined ? { contextWindowOverride: preservedContextWindow } : undefined)
488368
- };
488369
- }
488370
- var init_headless_model_startup = __esm(() => {
488371
- init_model();
488372
- init_modify();
488373
- });
488374
-
488375
488643
  // src/agent/list-messages-handler.ts
488376
488644
  import { randomUUID as randomUUID63 } from "node:crypto";
488377
488645
  async function handleListMessages(params) {
@@ -490058,7 +490326,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
490058
490326
  console.error(`Error: Invalid model "${model}"`);
490059
490327
  process.exit(1);
490060
490328
  }
490061
- const prepared = await prepareExistingHeadlessModel({
490329
+ const prepared = await prepareResumedAgentModel({
490062
490330
  agent,
490063
490331
  modelIdentifier: model,
490064
490332
  modelHandle: modelHandle ?? undefined,
@@ -490211,7 +490479,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
490211
490479
  conversationId = conversation.id;
490212
490480
  conversationOpenReason = "new";
490213
490481
  } else if (isSubagent) {
490214
- conversationId = "default";
490482
+ conversationId = await createSubagentConversation(backend3.capabilities.environmentRouting, process.env.LETTA_PARENT_CONVERSATION_ID, agent.id, startupBackend.createConversation);
490215
490483
  conversationOpenReason = "startup";
490216
490484
  } else {
490217
490485
  const conversation = await startupBackend.createConversation({
@@ -492464,13 +492732,13 @@ var init_headless = __esm(async () => {
492464
492732
  init_chatgpt_plan_rotation();
492465
492733
  init_context();
492466
492734
  init_create5();
492467
- init_headless_model_startup();
492468
492735
  init_list_messages_handler();
492469
492736
  init_model();
492470
492737
  init_modify();
492471
492738
  init_personality();
492472
492739
  init_personality_presets();
492473
492740
  init_prompt_assets();
492741
+ init_resumed_agent_model();
492474
492742
  init_skill_sources();
492475
492743
  init_backend2();
492476
492744
  init_accumulator();
@@ -492958,7 +493226,7 @@ function formatElapsedLabel(ms) {
492958
493226
  var BYTES_PER_TOKEN = 4;
492959
493227
 
492960
493228
  // src/cli/helpers/window-title-config.ts
492961
- import { homedir as homedir32 } from "node:os";
493229
+ import { homedir as homedir33 } from "node:os";
492962
493230
  import { basename as basename33, resolve as resolve42 } from "node:path";
492963
493231
  function isWindowTitleField(value) {
492964
493232
  return WINDOW_TITLE_FIELDS.includes(value);
@@ -493128,7 +493396,7 @@ function formatDirectoryDisplay(directory) {
493128
493396
  if (!directory)
493129
493397
  return null;
493130
493398
  const resolved2 = resolve42(directory);
493131
- const home = homedir32();
493399
+ const home = homedir33();
493132
493400
  if (resolved2 === home)
493133
493401
  return "~";
493134
493402
  if (resolved2.startsWith(`${home}/`)) {
@@ -493802,10 +494070,10 @@ var init_cli_mod_context = __esm(() => {
493802
494070
  import { execFile as execFileCb4 } from "node:child_process";
493803
494071
  import { existsSync as existsSync74 } from "node:fs";
493804
494072
  import { appendFile as appendFile3, chmod, mkdir as mkdir19, writeFile as writeFile22 } from "node:fs/promises";
493805
- import { homedir as homedir33 } from "node:os";
494073
+ import { homedir as homedir34 } from "node:os";
493806
494074
  import { join as join109 } from "node:path";
493807
494075
  import { promisify as promisify19 } from "node:util";
493808
- function getReflectionArenaHfCacheRoot(env6 = process.env, fallbackHome = homedir33()) {
494076
+ function getReflectionArenaHfCacheRoot(env6 = process.env, fallbackHome = homedir34()) {
493809
494077
  return join109(resolveGlobalConfigDir(env6, fallbackHome), "reflection-arena", "hf-upload");
493810
494078
  }
493811
494079
  function buildGitEnv(token2, askpassPath) {
@@ -495422,7 +495690,7 @@ import {
495422
495690
  readFileSync as readFileSync54,
495423
495691
  writeFileSync as writeFileSync47
495424
495692
  } from "node:fs";
495425
- import { homedir as homedir34, platform as platform10 } from "node:os";
495693
+ import { homedir as homedir35, platform as platform10 } from "node:os";
495426
495694
  import { dirname as dirname41, join as join111 } from "node:path";
495427
495695
  function detectTerminalType() {
495428
495696
  if (process.env.CURSOR_TRACE_ID || process.env.CURSOR_CHANNEL) {
@@ -495455,7 +495723,7 @@ function getKeybindingsPath(terminal) {
495455
495723
  }[terminal];
495456
495724
  const os7 = platform10();
495457
495725
  if (os7 === "darwin") {
495458
- return join111(homedir34(), "Library", "Application Support", appName, "User", "keybindings.json");
495726
+ return join111(homedir35(), "Library", "Application Support", appName, "User", "keybindings.json");
495459
495727
  }
495460
495728
  if (os7 === "win32") {
495461
495729
  const appData = process.env.APPDATA;
@@ -495464,7 +495732,7 @@ function getKeybindingsPath(terminal) {
495464
495732
  return join111(appData, appName, "User", "keybindings.json");
495465
495733
  }
495466
495734
  if (os7 === "linux") {
495467
- return join111(homedir34(), ".config", appName, "User", "keybindings.json");
495735
+ return join111(homedir35(), ".config", appName, "User", "keybindings.json");
495468
495736
  }
495469
495737
  return null;
495470
495738
  }
@@ -495621,10 +495889,10 @@ function getWezTermConfigPath() {
495621
495889
  if (existsSync75(xdgPath))
495622
495890
  return xdgPath;
495623
495891
  }
495624
- const configPath = join111(homedir34(), ".config", "wezterm", "wezterm.lua");
495892
+ const configPath = join111(homedir35(), ".config", "wezterm", "wezterm.lua");
495625
495893
  if (existsSync75(configPath))
495626
495894
  return configPath;
495627
- return join111(homedir34(), ".wezterm.lua");
495895
+ return join111(homedir35(), ".wezterm.lua");
495628
495896
  }
495629
495897
  function stripLuaCommentsFromLine(line, blockCommentEnd) {
495630
495898
  let code2 = "";
@@ -513924,11 +514192,11 @@ var init_use_chatgpt_rate_limit_state = __esm(() => {
513924
514192
 
513925
514193
  // src/utils/aws-credentials.ts
513926
514194
  import { readFile as readFile35 } from "node:fs/promises";
513927
- import { homedir as homedir35 } from "node:os";
514195
+ import { homedir as homedir36 } from "node:os";
513928
514196
  import { join as join116 } from "node:path";
513929
514197
  async function parseAwsCredentials() {
513930
- const credentialsPath = join116(homedir35(), ".aws", "credentials");
513931
- const configPath = join116(homedir35(), ".aws", "config");
514198
+ const credentialsPath = join116(homedir36(), ".aws", "credentials");
514199
+ const configPath = join116(homedir36(), ".aws", "config");
513932
514200
  const profiles = new Map;
513933
514201
  try {
513934
514202
  const content = await readFile35(credentialsPath, "utf-8");
@@ -524089,7 +524357,7 @@ __export(exports_shell_aliases, {
524089
524357
  clearAliasCache: () => clearAliasCache
524090
524358
  });
524091
524359
  import { existsSync as existsSync80, readFileSync as readFileSync56 } from "node:fs";
524092
- import { homedir as homedir36 } from "node:os";
524360
+ import { homedir as homedir37 } from "node:os";
524093
524361
  import { join as join119 } from "node:path";
524094
524362
  function parseAliasesFromFile(filePath) {
524095
524363
  const aliases = new Map;
@@ -524159,7 +524427,7 @@ function loadAliases(forceReload = false) {
524159
524427
  if (aliasCache && !forceReload) {
524160
524428
  return aliasCache;
524161
524429
  }
524162
- const home = homedir36();
524430
+ const home = homedir37();
524163
524431
  const allAliases = new Map;
524164
524432
  for (const file of ALIAS_FILES) {
524165
524433
  const filePath = join119(home, file);
@@ -524569,15 +524837,13 @@ function useConfigurationHandlers(ctx) {
524569
524837
  });
524570
524838
  return;
524571
524839
  }
524572
- const currentLlmConfig = llmConfigRef.current;
524573
- const shouldPreserveContextWindow = shouldPreserveContextWindowForModelSelection({
524840
+ const preservedContextWindow = contextWindowToPreserveForModelSelection({
524574
524841
  currentModelHandle,
524575
524842
  currentModelId,
524576
- currentLlmConfig,
524843
+ currentLlmConfig: llmConfigRef.current,
524577
524844
  selectedModelHandle: modelHandle,
524578
524845
  selectedContextWindow
524579
524846
  });
524580
- const preservedContextWindow = shouldPreserveContextWindow ? preservableContextWindow(currentLlmConfig?.context_window, modelHandle) : undefined;
524581
524847
  const modelUpdateArgsForRequest = model2.updateArgs ? { ...model2.updateArgs } : undefined;
524582
524848
  const updateOptions = preservedContextWindow !== undefined ? { contextWindowOverride: preservedContextWindow } : undefined;
524583
524849
  await withCommandLock(async () => {
@@ -539574,24 +539840,18 @@ Error: ${message2}`);
539574
539840
  const resuming = !!(agentIdArg || isResumingProject || isReusingExistingAgent);
539575
539841
  setIsResumingSession(resuming);
539576
539842
  if (resuming) {
539577
- if (model) {
539578
- const modelHandle = resolveModel(model);
539579
- if (!modelHandle) {
539580
- console.error(`Error: Invalid model "${model}"`);
539581
- process.exit(1);
539582
- }
539583
- const updateArgs = getModelUpdateArgs(model);
539584
- agent = await updateAgentLLMConfig(agent.id, modelHandle, updateArgs);
539585
- } else {
539586
- const presetRefresh = getModelPresetUpdateForAgent(agent);
539587
- if (presetRefresh) {
539588
- const { updateArgs: resumeRefreshUpdateArgs, needsUpdate } = getResumeRefreshArgs(presetRefresh.updateArgs, agent);
539589
- if (needsUpdate) {
539590
- const preservedContextWindow = preservableContextWindow(agent.llm_config?.context_window, presetRefresh.modelHandle);
539591
- agent = await updateAgentLLMConfig(agent.id, presetRefresh.modelHandle, resumeRefreshUpdateArgs, preservedContextWindow !== undefined ? { contextWindowOverride: preservedContextWindow } : undefined);
539592
- }
539593
- }
539843
+ const modelHandle = model ? resolveModel(model) : undefined;
539844
+ if (model && !modelHandle) {
539845
+ console.error(`Error: Invalid model "${model}"`);
539846
+ process.exit(1);
539594
539847
  }
539848
+ ({ agent } = await prepareResumedAgentModel({
539849
+ agent,
539850
+ modelIdentifier: model,
539851
+ modelHandle: modelHandle ?? undefined,
539852
+ createsConversation: false,
539853
+ localModelCatalog: backend3.capabilities.localModelCatalog
539854
+ }));
539595
539855
  if (systemPromptPreset2) {
539596
539856
  try {
539597
539857
  await memfsSyncPromise;
@@ -539863,6 +540123,7 @@ var init_src5 = __esm(async () => {
539863
540123
  init_modify();
539864
540124
  init_personality();
539865
540125
  init_personality_presets();
540126
+ init_resumed_agent_model();
539866
540127
  init_skill_sources();
539867
540128
  init_oauth();
539868
540129
  init_backend2();
@@ -542259,4 +542520,4 @@ function registerBunOAuthFlows() {
542259
542520
  registerBunOAuthFlows();
542260
542521
  await init_src5().then(() => exports_src2);
542261
542522
 
542262
- //# debugId=2A43851F6B354BA164756E2164756E21
542523
+ //# debugId=0B57802CC3CE1F5E64756E2164756E21