@cydm/pie 4.8.0 → 4.9.0

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 (49) hide show
  1. package/README.md +51 -27
  2. package/dist/builtin/extensions/ask-user/index.js +4 -4
  3. package/dist/builtin/extensions/cron/index.js +906 -158
  4. package/dist/builtin/extensions/im-forward/README.md +4 -2
  5. package/dist/builtin/extensions/im-forward/index.js +6822 -3951
  6. package/dist/builtin/extensions/memory/index.js +76 -28
  7. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  8. package/dist/builtin/extensions/pie-ipc/index.js +282 -58
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +227 -75
  11. package/dist/builtin/extensions/plan-mode/index.js +5 -5
  12. package/dist/builtin/extensions/subagent/index.js +8 -8
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +26 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
  18. package/dist/builtin/skills/chrome-devtools-axi/{cli-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +293 -64
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-4UIUMTHG.js} +993 -371
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BA4Z27XT.js} +4 -3
  26. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-DBDU3RRN.js} +1364 -446
  27. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-EEC5PJTC.js} +11 -9
  28. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  29. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-LRHNAG4V.js} +349 -288
  30. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  31. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-PN6B54VT.js} +104 -22
  32. package/dist/chunks/{chunk-NHV2CALB.js → chunk-WYXUF4MP.js} +388 -32
  33. package/dist/chunks/{chunk-4PR34UZF.js → chunk-Z5KL6AO2.js} +159 -145
  34. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-RASJSVZY.js} +1 -1
  35. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  36. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-5TLYILYR.js} +2 -2
  37. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-VPKDBV23.js} +5 -5
  38. package/dist/chunks/{src-B44QWSGM.js → src-2XI5P62J.js} +2 -2
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-6QGGDHIW.js} +3 -3
  40. package/dist/chunks/{src-Q7LU27C2.js → src-CCEENRKC.js} +31 -1
  41. package/dist/chunks/{src-CLE5ILN4.js → src-DI4MCAGT.js} +20 -4
  42. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-SYVWIPPW.js} +2 -2
  43. package/dist/cli.js +1890 -1489
  44. package/models.schema.json +271 -0
  45. package/package.json +2 -2
  46. package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
  47. package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
  48. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-WBL73KRI.js} +3 -3
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
package/dist/cli.js CHANGED
@@ -4,9 +4,6 @@ import {
4
4
  AuthStorage,
5
5
  FileAuthStorageBackend
6
6
  } from "./chunks/chunk-SW2E33UL.js";
7
- import {
8
- ModelRegistry
9
- } from "./chunks/chunk-NHV2CALB.js";
10
7
  import {
11
8
  FileCache,
12
9
  FileManager,
@@ -22,19 +19,20 @@ import {
22
19
  normalizeFileManagerPlatform,
23
20
  resolvePath,
24
21
  understandReadFile
25
- } from "./chunks/chunk-4PR34UZF.js";
22
+ } from "./chunks/chunk-Z5KL6AO2.js";
26
23
  import {
24
+ distillExitCode,
27
25
  distillWorkerLogPath,
28
26
  readDistillWorkerLog,
29
27
  runDistillAuto,
30
28
  runDistillWorkerMain,
31
29
  spawnDistillAutoWorker,
32
30
  spawnDistillWorker
33
- } from "./chunks/chunk-Z2FKA2ZH.js";
31
+ } from "./chunks/chunk-PN6B54VT.js";
34
32
  import {
35
33
  SessionOwnershipLifecycle,
36
34
  claimSessionOwnership
37
- } from "./chunks/chunk-CGSFBWOM.js";
35
+ } from "./chunks/chunk-WBL73KRI.js";
38
36
  import {
39
37
  CLI_RETRY_MAX_RETRIES,
40
38
  classifyCliFailure,
@@ -51,22 +49,7 @@ import {
51
49
  logTransportLifecycle,
52
50
  setYoloGrantListener,
53
51
  truncateHeadTail
54
- } from "./chunks/chunk-LAJXWOKS.js";
55
- import {
56
- VERSION,
57
- getAgentDir,
58
- getBuiltinDir,
59
- getConfigDir,
60
- getCustomThemesDir,
61
- getLogsDir,
62
- getPackageDir,
63
- getProjectSettingsPath,
64
- getRuntimeLogPath,
65
- getSessionsDir,
66
- getSettingsPath,
67
- getThemesDir,
68
- migrateConfigFromAgentDir
69
- } from "./chunks/chunk-CBDQJMUI.js";
52
+ } from "./chunks/chunk-EEC5PJTC.js";
70
53
  import {
71
54
  BUILTIN_TOOL_CAPABILITY_METADATA,
72
55
  MemoryStore,
@@ -94,7 +77,7 @@ import {
94
77
  shouldPreserveExecutionStateForUserText,
95
78
  supersedeExecutionState,
96
79
  todayKey
97
- } from "./chunks/chunk-BLDI2GRF.js";
80
+ } from "./chunks/chunk-DBDU3RRN.js";
98
81
  import {
99
82
  AGENTS_CONTEXT_FILE_NAME,
100
83
  AgentSessionController,
@@ -134,9 +117,30 @@ import {
134
117
  setEnablementInMap,
135
118
  setExtensionEnabledInSettings,
136
119
  verifyPreparedCompactionCommit
137
- } from "./chunks/chunk-Y3I2UV5Y.js";
138
- import "./chunks/chunk-5KI4Y4LA.js";
120
+ } from "./chunks/chunk-LRHNAG4V.js";
121
+ import "./chunks/chunk-BA4Z27XT.js";
122
+ import {
123
+ ModelRegistry
124
+ } from "./chunks/chunk-WYXUF4MP.js";
125
+ import "./chunks/chunk-F7EBZTZO.js";
126
+ import "./chunks/chunk-ZPJ3BNQB.js";
139
127
  import {
128
+ VERSION,
129
+ getAgentDir,
130
+ getBuiltinDir,
131
+ getConfigDir,
132
+ getCustomThemesDir,
133
+ getLogsDir,
134
+ getPackageDir,
135
+ getProjectSettingsPath,
136
+ getRuntimeLogPath,
137
+ getSessionsDir,
138
+ getSettingsPath,
139
+ getThemesDir,
140
+ migrateConfigFromAgentDir
141
+ } from "./chunks/chunk-CBDQJMUI.js";
142
+ import {
143
+ ALL_THINKING_LEVELS,
140
144
  Deref,
141
145
  Errors,
142
146
  ExtendsUndefinedCheck,
@@ -148,15 +152,18 @@ import {
148
152
  TransformEncodeCheckError,
149
153
  completeSimple,
150
154
  createLogger,
155
+ describeThinkingLevel,
151
156
  format_exports,
152
157
  getLogger,
153
158
  getModelCacheCapability,
159
+ getModelThinkingCapabilities,
160
+ isThinkingSelectionLevel,
161
+ resolveThinkingSelection,
154
162
  setLogger,
155
163
  streamSimple,
156
- type_exports
157
- } from "./chunks/chunk-3W3SXVPB.js";
158
- import "./chunks/chunk-F7EBZTZO.js";
159
- import "./chunks/chunk-ZPJ3BNQB.js";
164
+ type_exports,
165
+ validateExplicitThinkingSelection
166
+ } from "./chunks/chunk-4UIUMTHG.js";
160
167
  import {
161
168
  IsArray,
162
169
  IsBigInt,
@@ -51327,88 +51334,6 @@ var require_dist2 = __commonJS({
51327
51334
  import * as fs23 from "fs";
51328
51335
  import * as path25 from "path";
51329
51336
 
51330
- // src/cli-args.ts
51331
- var FLAGS_WITH_VALUES = /* @__PURE__ */ new Set(["--session-id", "--extension-path", "--developer-instructions", "--developer-instructions-file", "--worker-token"]);
51332
- var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--raw-output", "--json-output", "--json-events", "--resume-required", "--idle"]);
51333
- var HELP_FLAGS = /* @__PURE__ */ new Set(["help", "--help", "-h"]);
51334
- var COMMANDS = /* @__PURE__ */ new Set(["chat", "help"]);
51335
- function parseCliInvocation(args) {
51336
- let command;
51337
- let showHelp2 = false;
51338
- let testCommand;
51339
- let sessionId;
51340
- const positionals = [];
51341
- for (let i = 0; i < args.length; i += 1) {
51342
- const arg = args[i];
51343
- if (!arg) continue;
51344
- if (HELP_FLAGS.has(arg)) {
51345
- showHelp2 = true;
51346
- if (arg === "help") {
51347
- command = "help";
51348
- }
51349
- continue;
51350
- }
51351
- if (arg === "--test-command" || arg === "-t") {
51352
- const next = args[i + 1];
51353
- testCommand = next && !next.startsWith("-") ? next : "/settings";
51354
- if (next && !next.startsWith("-")) {
51355
- i += 1;
51356
- }
51357
- continue;
51358
- }
51359
- if (arg === "--session-id") {
51360
- const next = args[i + 1];
51361
- if (next && !next.startsWith("-")) {
51362
- sessionId = next;
51363
- i += 1;
51364
- }
51365
- continue;
51366
- }
51367
- if (arg.startsWith("--session-id=")) {
51368
- sessionId = arg.slice("--session-id=".length);
51369
- continue;
51370
- }
51371
- if (FLAGS_WITH_VALUES.has(arg)) {
51372
- i += 1;
51373
- continue;
51374
- }
51375
- if (BOOLEAN_FLAGS.has(arg)) {
51376
- continue;
51377
- }
51378
- if (!arg.startsWith("-") && !command && COMMANDS.has(arg)) {
51379
- command = arg;
51380
- continue;
51381
- }
51382
- if (!arg.startsWith("-")) {
51383
- positionals.push(arg);
51384
- }
51385
- }
51386
- if (showHelp2 || command === "help") {
51387
- return { showHelp: true };
51388
- }
51389
- if (testCommand) {
51390
- return sessionId !== void 0 ? { showHelp: false, testCommand, sessionId } : { showHelp: false, testCommand };
51391
- }
51392
- const initialPrompt = positionals.join(" ").trim() || void 0;
51393
- if (sessionId !== void 0) {
51394
- return { showHelp: false, initialPrompt, sessionId };
51395
- }
51396
- return {
51397
- showHelp: false,
51398
- initialPrompt
51399
- };
51400
- }
51401
- function parseRepeatedFlag(args, flag) {
51402
- const values = [];
51403
- for (let i = 0; i < args.length; i += 1) {
51404
- if (args[i] === flag && args[i + 1]) {
51405
- values.push(args[i + 1]);
51406
- i += 1;
51407
- }
51408
- }
51409
- return values;
51410
- }
51411
-
51412
51337
  // src/debug/file-logger.ts
51413
51338
  import * as fs from "fs";
51414
51339
  import * as path from "path";
@@ -51660,6 +51585,429 @@ function flushEarlyLogs() {
51660
51585
  _earlyLogs = [];
51661
51586
  }
51662
51587
 
51588
+ // src/core/defaults.ts
51589
+ var DEFAULT_THINKING_LEVEL = "medium";
51590
+ var DEFAULT_YOLO_MODE = true;
51591
+
51592
+ // src/core/model-resolver.ts
51593
+ function normalizeProviderName(provider) {
51594
+ return provider.toLowerCase().replace(/[^a-z]/g, "");
51595
+ }
51596
+ function selectFallbackModel(registry, preferred) {
51597
+ const availableModels = registry.getAvailable();
51598
+ if (preferred?.provider && preferred?.modelId) {
51599
+ const exact = availableModels.find(
51600
+ (model) => model.provider === preferred.provider && model.id === preferred.modelId
51601
+ );
51602
+ if (exact) return exact;
51603
+ }
51604
+ if (preferred?.provider) {
51605
+ const sameProvider = availableModels.find((model) => model.provider === preferred.provider);
51606
+ if (sameProvider) return sameProvider;
51607
+ }
51608
+ return availableModels[0] || registry.getAll()[0];
51609
+ }
51610
+ function resolveConfiguredModel(registry, provider, modelId) {
51611
+ const exact = registry.find(provider, modelId);
51612
+ if (exact) {
51613
+ return { model: exact, provider, modelId, corrected: false };
51614
+ }
51615
+ const allModels = registry.getAll();
51616
+ if (allModels.length === 0) {
51617
+ throw new Error("No registered models are available.");
51618
+ }
51619
+ const sameIdMatches = allModels.filter((model) => model.id === modelId);
51620
+ const normalizedProviderMatches = sameIdMatches.filter(
51621
+ (model) => normalizeProviderName(model.provider) === normalizeProviderName(provider)
51622
+ );
51623
+ if (normalizedProviderMatches.length === 1) {
51624
+ const matched = normalizedProviderMatches[0];
51625
+ return {
51626
+ model: matched,
51627
+ provider: matched.provider,
51628
+ modelId: matched.id,
51629
+ corrected: true,
51630
+ warning: `Configured model "${provider}/${modelId}" was not found. Using "${matched.provider}/${matched.id}" instead.`
51631
+ };
51632
+ }
51633
+ if (sameIdMatches.length === 1) {
51634
+ const matched = sameIdMatches[0];
51635
+ return {
51636
+ model: matched,
51637
+ provider: matched.provider,
51638
+ modelId: matched.id,
51639
+ corrected: true,
51640
+ warning: `Configured model "${provider}/${modelId}" was not found. Reusing the available model "${matched.provider}/${matched.id}".`
51641
+ };
51642
+ }
51643
+ const providerModels = registry.getByProvider(provider);
51644
+ if (providerModels.length > 0) {
51645
+ const fallback2 = providerModels[0];
51646
+ return {
51647
+ model: fallback2,
51648
+ provider: fallback2.provider,
51649
+ modelId: fallback2.id,
51650
+ corrected: true,
51651
+ warning: `Configured model "${provider}/${modelId}" was not found. Falling back to "${fallback2.provider}/${fallback2.id}".`
51652
+ };
51653
+ }
51654
+ const fallback = selectFallbackModel(registry);
51655
+ if (!fallback) {
51656
+ throw new Error("No registered models are available.");
51657
+ }
51658
+ return {
51659
+ model: fallback,
51660
+ provider: fallback.provider,
51661
+ modelId: fallback.id,
51662
+ corrected: true,
51663
+ warning: `Configured model "${provider}/${modelId}" was not found. Falling back to "${fallback.provider}/${fallback.id}".`
51664
+ };
51665
+ }
51666
+ function findInitialModel(options) {
51667
+ const configDefaults = options.registry.getConfigDefaults();
51668
+ const configuredProvider = options.configuredProvider || configDefaults?.provider;
51669
+ const configuredModelId = options.configuredModelId || configDefaults?.modelId;
51670
+ const resolved = configuredProvider && configuredModelId ? resolveConfiguredModel(options.registry, configuredProvider, configuredModelId) : void 0;
51671
+ const apiKey = resolved ? options.registry.getApiKey(resolved.model) : void 0;
51672
+ if (!resolved || !apiKey) {
51673
+ const fallback = selectFallbackModel(options.registry, {
51674
+ provider: configuredProvider,
51675
+ modelId: configuredModelId
51676
+ });
51677
+ if (!fallback) {
51678
+ return {
51679
+ model: void 0,
51680
+ apiKey: void 0,
51681
+ provider: void 0,
51682
+ modelId: void 0,
51683
+ unconfigured: true,
51684
+ warning: "No models are configured. Add one in ~/.pie/models.json before sending messages."
51685
+ };
51686
+ }
51687
+ const fallbackKey = options.registry.getApiKey(fallback);
51688
+ if (!fallbackKey) {
51689
+ throw new Error(`No API key found for provider "${resolved?.provider || fallback.provider}".`);
51690
+ }
51691
+ return {
51692
+ model: fallback,
51693
+ apiKey: fallbackKey,
51694
+ provider: fallback.provider,
51695
+ modelId: fallback.id,
51696
+ warning: resolved ? resolved.warning || `No API key found for "${resolved.provider}". Using "${fallback.provider}/${fallback.id}" instead.` : configuredProvider && configuredModelId ? `Configured model "${configuredProvider}/${configuredModelId}" was not found. Using "${fallback.provider}/${fallback.id}" instead.` : void 0
51697
+ };
51698
+ }
51699
+ return {
51700
+ model: resolved.model,
51701
+ apiKey,
51702
+ provider: resolved.provider,
51703
+ modelId: resolved.modelId,
51704
+ warning: resolved.warning
51705
+ };
51706
+ }
51707
+ function restoreModelFromSession(options) {
51708
+ const savedProvider = options.savedProvider;
51709
+ const restored = options.registry.find(savedProvider, options.savedModelId);
51710
+ if (restored && options.registry.getApiKey(restored)) {
51711
+ return { model: restored };
51712
+ }
51713
+ if (options.currentModel) {
51714
+ return {
51715
+ model: options.currentModel,
51716
+ fallbackMessage: `Could not restore model ${savedProvider}/${options.savedModelId}. Using ${options.currentModel.provider}/${options.currentModel.id}.`
51717
+ };
51718
+ }
51719
+ const fallback = selectFallbackModel(options.registry, {
51720
+ provider: savedProvider,
51721
+ modelId: options.savedModelId
51722
+ });
51723
+ return fallback ? {
51724
+ model: fallback,
51725
+ fallbackMessage: `Could not restore model ${savedProvider}/${options.savedModelId}. Using ${fallback.provider}/${fallback.id}.`
51726
+ } : { model: void 0 };
51727
+ }
51728
+
51729
+ // src/core/session-model-metadata.ts
51730
+ function getSavedSessionModelSelection(activeSession) {
51731
+ if (!activeSession) return {};
51732
+ const provider = typeof activeSession.metadata.provider === "string" ? activeSession.metadata.provider : typeof activeSession.metadata.defaultProvider === "string" ? activeSession.metadata.defaultProvider : void 0;
51733
+ const modelId = typeof activeSession.metadata.modelId === "string" ? activeSession.metadata.modelId : typeof activeSession.metadata.defaultModel === "string" ? activeSession.metadata.defaultModel : void 0;
51734
+ const thinkingLevel = typeof activeSession.metadata.thinkingLevel === "string" ? activeSession.metadata.thinkingLevel : void 0;
51735
+ return { provider, modelId, thinkingLevel };
51736
+ }
51737
+ function syncSessionModelMetadata(sessionManager, model, thinkingLevel, options) {
51738
+ const activeSession = sessionManager.getActiveSession();
51739
+ if (!activeSession || !model) return;
51740
+ if (options?.isFallback) {
51741
+ if (options.preserveThinkingLevel && typeof activeSession.metadata.thinkingLevel === "string") {
51742
+ return;
51743
+ }
51744
+ activeSession.metadata.thinkingLevel = thinkingLevel;
51745
+ activeSession.isDirty = true;
51746
+ return;
51747
+ }
51748
+ activeSession.metadata.provider = model.provider;
51749
+ activeSession.metadata.modelId = model.id;
51750
+ activeSession.metadata.defaultProvider = model.provider;
51751
+ activeSession.metadata.defaultModel = model.id;
51752
+ if (!options?.preserveThinkingLevel || typeof activeSession.metadata.thinkingLevel !== "string") {
51753
+ activeSession.metadata.thinkingLevel = thinkingLevel;
51754
+ }
51755
+ activeSession.isDirty = true;
51756
+ }
51757
+ function restoreSessionModelState(options) {
51758
+ const { provider, modelId, thinkingLevel } = getSavedSessionModelSelection(options.activeSession);
51759
+ if (!provider || !modelId) {
51760
+ return {
51761
+ model: options.currentModel,
51762
+ thinkingLevel
51763
+ };
51764
+ }
51765
+ if (options.managerScopedSelection && options.currentModel) {
51766
+ return {
51767
+ model: options.currentModel,
51768
+ thinkingLevel,
51769
+ fallbackMessage: `Manager workspace model ${options.currentModel.provider}/${options.currentModel.id} kept (session had ${provider}/${modelId}).`
51770
+ };
51771
+ }
51772
+ const restored = restoreModelFromSession({
51773
+ registry: options.registry,
51774
+ savedProvider: provider,
51775
+ savedModelId: modelId,
51776
+ currentModel: options.currentModel
51777
+ });
51778
+ return {
51779
+ model: restored.model,
51780
+ thinkingLevel,
51781
+ fallbackMessage: restored.fallbackMessage
51782
+ };
51783
+ }
51784
+
51785
+ // src/core/interactive-model-state.ts
51786
+ var THINKING_LEVELS = [...ALL_THINKING_LEVELS];
51787
+ var THINKING_LEVEL_DESCRIPTIONS = {
51788
+ off: "Disable thinking when supported (or omit request)",
51789
+ minimal: "Very brief reasoning",
51790
+ low: "Light reasoning",
51791
+ medium: "Moderate reasoning",
51792
+ high: "Deep reasoning",
51793
+ xhigh: "Extra-high reasoning effort (model-dependent)",
51794
+ max: "Maximum native reasoning effort (model-dependent)"
51795
+ };
51796
+ function isThinkingLevel(value) {
51797
+ return isThinkingSelectionLevel(value);
51798
+ }
51799
+ function resolveFooterThinkingState(model, requested) {
51800
+ const resolution = resolveThinkingSelection(model, requested);
51801
+ return {
51802
+ thinkingLevel: requested,
51803
+ effectiveThinkingLevel: resolution.effective,
51804
+ thinkingClamped: resolution.clamped,
51805
+ resolution
51806
+ };
51807
+ }
51808
+ function buildThinkingSelectorOptions(model) {
51809
+ const cap = getModelThinkingCapabilities(model);
51810
+ const levels = cap.wireConfigurable ? [...cap.supportedLevels] : cap.reasoningCapable ? ["off", "minimal", "low", "medium", "high", "xhigh"] : ["off"];
51811
+ const descriptions = {};
51812
+ for (const level of levels) {
51813
+ descriptions[level] = describeThinkingLevel(model, level);
51814
+ }
51815
+ const modelLabel = model ? `${model.provider}/${model.id}` : "current model";
51816
+ const subtitle = cap.wireConfigurable ? `Supported thinking levels for ${modelLabel} (mode: ${cap.mode})` : cap.reasoningCapable ? `${modelLabel} uses built-in reasoning (wire effort not configurable)` : `${modelLabel} does not support thinking`;
51817
+ return { levels, descriptions, subtitle };
51818
+ }
51819
+ function resolveInitialThinkingLevel(options) {
51820
+ if (options.explicitThinkingLevel && isThinkingLevel(options.explicitThinkingLevel)) {
51821
+ return options.explicitThinkingLevel;
51822
+ }
51823
+ const sessionLevel = options.session?.metadata.thinkingLevel;
51824
+ if (typeof sessionLevel === "string" && isThinkingLevel(sessionLevel)) {
51825
+ return sessionLevel;
51826
+ }
51827
+ return options.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
51828
+ }
51829
+ function maskApiKey(key) {
51830
+ if (key.length <= 6) return "***";
51831
+ return key.slice(0, 6) + "***";
51832
+ }
51833
+ function applyThinkingLevel(options) {
51834
+ options.agent.setThinkingLevel(options.level);
51835
+ if (options.persist !== false) {
51836
+ options.settingsManager.setDefaultThinkingLevel(options.level);
51837
+ }
51838
+ syncSessionModelMetadata(options.sessionManager, options.model, options.level);
51839
+ }
51840
+ function switchInteractiveModel(options) {
51841
+ const [provider, modelId] = options.fullModelId.split("/");
51842
+ const model = options.registry.find(provider, modelId);
51843
+ if (!model) {
51844
+ throw new Error(`Model "${options.fullModelId}" not found`);
51845
+ }
51846
+ const apiKey = options.registry.getApiKey(model);
51847
+ options.agent.setModel(model);
51848
+ if (apiKey) {
51849
+ options.agent.apiKey = apiKey;
51850
+ fileLogger.log("cli", `Switched model to ${options.fullModelId}, updated API key`, {
51851
+ keyPrefix: maskApiKey(apiKey)
51852
+ });
51853
+ } else {
51854
+ fileLogger.log("cli", `Switched model to ${options.fullModelId}, no API key found`);
51855
+ }
51856
+ options.settingsManager.setDefaultModelAndProvider(provider, modelId);
51857
+ syncSessionModelMetadata(options.sessionManager, model, options.thinkingLevel, {
51858
+ preserveThinkingLevel: options.preserveSessionThinkingLevel
51859
+ });
51860
+ const thinkingResolution = resolveThinkingSelection(model, options.thinkingLevel);
51861
+ return { model, apiKey, thinkingResolution };
51862
+ }
51863
+ function restoreInteractiveSessionState(options) {
51864
+ const restored = restoreSessionModelState({
51865
+ activeSession: options.activeSession,
51866
+ registry: options.registry,
51867
+ currentModel: options.currentModel
51868
+ });
51869
+ const thinkingLevel = restored.thinkingLevel && isThinkingLevel(restored.thinkingLevel) ? restored.thinkingLevel : void 0;
51870
+ if (thinkingLevel) {
51871
+ options.agent.setThinkingLevel(thinkingLevel);
51872
+ }
51873
+ let apiKey;
51874
+ if (restored.model) {
51875
+ options.agent.setModel(restored.model);
51876
+ apiKey = options.registry.getApiKey(restored.model);
51877
+ if (apiKey) {
51878
+ options.agent.apiKey = apiKey;
51879
+ }
51880
+ }
51881
+ return {
51882
+ model: restored.model,
51883
+ apiKey,
51884
+ thinkingLevel,
51885
+ fallbackMessage: restored.fallbackMessage
51886
+ };
51887
+ }
51888
+
51889
+ // src/cli-args.ts
51890
+ var FLAGS_WITH_VALUES = /* @__PURE__ */ new Set(["--session-id", "--thinking", "--extension-path", "--developer-instructions", "--developer-instructions-file", "--worker-token"]);
51891
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--raw-output", "--json-output", "--json-events", "--resume-required", "--idle"]);
51892
+ var HELP_FLAGS = /* @__PURE__ */ new Set(["help", "--help", "-h"]);
51893
+ var COMMANDS = /* @__PURE__ */ new Set(["chat", "help"]);
51894
+ function parseCliInvocation(args) {
51895
+ let command;
51896
+ let showHelp2 = false;
51897
+ let testCommand;
51898
+ let sessionId;
51899
+ let thinkingLevel;
51900
+ const positionals = [];
51901
+ for (let i = 0; i < args.length; i += 1) {
51902
+ const arg = args[i];
51903
+ if (!arg) continue;
51904
+ if (HELP_FLAGS.has(arg)) {
51905
+ showHelp2 = true;
51906
+ if (arg === "help") {
51907
+ command = "help";
51908
+ }
51909
+ continue;
51910
+ }
51911
+ if (arg === "--test-command" || arg === "-t") {
51912
+ const next = args[i + 1];
51913
+ testCommand = next && !next.startsWith("-") ? next : "/settings";
51914
+ if (next && !next.startsWith("-")) {
51915
+ i += 1;
51916
+ }
51917
+ continue;
51918
+ }
51919
+ if (arg === "--session-id") {
51920
+ const next = args[i + 1];
51921
+ if (next && !next.startsWith("-")) {
51922
+ sessionId = next;
51923
+ i += 1;
51924
+ }
51925
+ continue;
51926
+ }
51927
+ if (arg.startsWith("--session-id=")) {
51928
+ sessionId = arg.slice("--session-id=".length);
51929
+ continue;
51930
+ }
51931
+ if (arg === "--thinking") {
51932
+ const next = args[i + 1];
51933
+ if (next && !next.startsWith("-")) {
51934
+ thinkingLevel = next;
51935
+ i += 1;
51936
+ } else {
51937
+ thinkingLevel = "";
51938
+ }
51939
+ continue;
51940
+ }
51941
+ if (arg.startsWith("--thinking=")) {
51942
+ thinkingLevel = arg.slice("--thinking=".length);
51943
+ continue;
51944
+ }
51945
+ if (FLAGS_WITH_VALUES.has(arg)) {
51946
+ i += 1;
51947
+ continue;
51948
+ }
51949
+ if (BOOLEAN_FLAGS.has(arg)) {
51950
+ continue;
51951
+ }
51952
+ if (!arg.startsWith("-") && !command && COMMANDS.has(arg)) {
51953
+ command = arg;
51954
+ continue;
51955
+ }
51956
+ if (!arg.startsWith("-")) {
51957
+ positionals.push(arg);
51958
+ }
51959
+ }
51960
+ if (showHelp2 || command === "help") {
51961
+ return { showHelp: true };
51962
+ }
51963
+ if (testCommand) {
51964
+ return {
51965
+ showHelp: false,
51966
+ testCommand,
51967
+ ...sessionId !== void 0 ? { sessionId } : {},
51968
+ ...thinkingLevel !== void 0 ? { thinkingLevel } : {}
51969
+ };
51970
+ }
51971
+ const initialPrompt = positionals.join(" ").trim() || void 0;
51972
+ return {
51973
+ showHelp: false,
51974
+ initialPrompt,
51975
+ ...sessionId !== void 0 ? { sessionId } : {},
51976
+ ...thinkingLevel !== void 0 ? { thinkingLevel } : {}
51977
+ };
51978
+ }
51979
+ function parseRepeatedFlag(args, flag) {
51980
+ const values = [];
51981
+ for (let i = 0; i < args.length; i += 1) {
51982
+ if (args[i] === flag && args[i + 1]) {
51983
+ values.push(args[i + 1]);
51984
+ i += 1;
51985
+ }
51986
+ }
51987
+ return values;
51988
+ }
51989
+ function resolveJsonEventsDetailFlag(args) {
51990
+ for (let index = 0; index < args.length; index += 1) {
51991
+ const arg = args[index];
51992
+ if (arg === "--event-detail") {
51993
+ const raw = args[index + 1] ?? "";
51994
+ return raw === "compact" || raw === "full" ? { value: raw } : { error: raw || "(missing)" };
51995
+ }
51996
+ if (arg.startsWith("--event-detail=")) {
51997
+ const raw = arg.slice("--event-detail=".length);
51998
+ return raw === "compact" || raw === "full" ? { value: raw } : { error: raw };
51999
+ }
52000
+ }
52001
+ return { value: "compact" };
52002
+ }
52003
+ function resolveExplicitThinkingFlag(raw, argv, sessionId) {
52004
+ if (raw === void 0) return { ok: true };
52005
+ if (isThinkingLevel(raw)) return { ok: true, value: raw };
52006
+ const message = `Invalid --thinking value: "${raw}". Supported: ${ALL_THINKING_LEVELS.join("|")}`;
52007
+ const jsonEvent = argv.includes("--json-events") ? JSON.stringify({ type: "turn.failed", sessionId: sessionId ?? "", error: message, source: "external" }) : void 0;
52008
+ return { ok: false, message, jsonEvent };
52009
+ }
52010
+
51663
52011
  // src/logging/runtime-logger.ts
51664
52012
  function stringifyContext(context) {
51665
52013
  if (!context || Object.keys(context).length === 0) {
@@ -53239,11 +53587,47 @@ var CHAT_SPEC = {
53239
53587
  { name: "prompt", required: false, description: "Initial prompt (starts print mode instead of the TUI)." }
53240
53588
  ]
53241
53589
  };
53590
+ var MANAGER_SPEC = {
53591
+ path: "manager",
53592
+ summary: "Manage the background Pie resident manager (start/status/stop/tail/upgrade).",
53593
+ usage: "manager [start|status|stop|tail|upgrade] [--install-service | --uninstall-service] [--follow] [--lines <n>] [--json] [--target <ver>] [--force]",
53594
+ flags: [
53595
+ { name: "--install-service", kind: "boolean", description: "Install and start a platform background service for the resident manager." },
53596
+ { name: "--uninstall-service", kind: "boolean", description: "Uninstall the resident manager platform service." },
53597
+ { name: "--follow", kind: "boolean", description: "Follow resident manager log events (with tail)." },
53598
+ { name: "--lines", kind: "string", description: "Number of recent log lines to print (with tail)." },
53599
+ { name: "--json", kind: "boolean", description: "Emit raw JSONL log lines (with tail)." },
53600
+ { name: "--target", kind: "string", description: "Target @cydm/pie version or 'latest' (with upgrade)." },
53601
+ { name: "--force", kind: "boolean", description: "Force upgrade even if already on target version (with upgrade)." }
53602
+ ],
53603
+ positional: [
53604
+ { name: "subcommand", required: false, description: "Lifecycle or observation action: start (default), status, stop, tail, or upgrade." }
53605
+ ]
53606
+ };
53607
+ var MEMORY_SPEC = {
53608
+ path: "memory",
53609
+ summary: "Inspect, distill, and schedule session memory (distill/schedule/status/log).",
53610
+ usage: "memory <distill|schedule|status|log> [--date YYYY-MM-DD | --auto] [--memory-root <dir>] [--time HH:MM] [-n <lines>]",
53611
+ flags: [
53612
+ { name: "--date", kind: "string", description: "Local YYYY-MM-DD date to distill (default yesterday)." },
53613
+ { name: "--auto", kind: "boolean", description: "Catch up missing distillation checkpoints over the last 7 days." },
53614
+ { name: "--worker", kind: "boolean", description: "Run distillation in-process (internal detached worker mode)." },
53615
+ { name: "--memory-root", kind: "string", description: "Override the memory storage directory (default ~/.pie/memory)." },
53616
+ { name: "--sessions-dir", kind: "string", description: "Override the sessions directory scanned during distillation." },
53617
+ { name: "--time", kind: "string", description: "Daily local HH:MM schedule time (with schedule on)." },
53618
+ { name: "-n", kind: "string", description: "Number of worker log lines to print (with log)." }
53619
+ ],
53620
+ positional: [
53621
+ { name: "subcommand", required: true, description: "Memory action: distill, schedule, status, or log." }
53622
+ ]
53623
+ };
53242
53624
  var MANAGEMENT_COMMAND_SPECS = [
53243
53625
  CHAT_SPEC,
53244
53626
  DOCTOR_SPEC,
53245
53627
  MODELS_INIT_SPEC,
53246
53628
  MODELS_VALIDATE_SPEC,
53629
+ MANAGER_SPEC,
53630
+ MEMORY_SPEC,
53247
53631
  SESSIONS_LIST_SPEC,
53248
53632
  SESSIONS_READ_SPEC,
53249
53633
  SESSIONS_RENAME_SPEC,
@@ -53563,6 +53947,7 @@ function runCapabilitiesCommand(args) {
53563
53947
 
53564
53948
  // src/commands/memory-cli.ts
53565
53949
  import * as fs5 from "node:fs";
53950
+ import { homedir as homedir2 } from "node:os";
53566
53951
  import * as path5 from "node:path";
53567
53952
  import { pathToFileURL } from "node:url";
53568
53953
  var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -53621,6 +54006,17 @@ function parseMemoryRootFlag(args) {
53621
54006
  if (parsed.value !== void 0 && parsed.value.length === 0) return { error: "--memory-root requires a value" };
53622
54007
  return parsed;
53623
54008
  }
54009
+ function parseSessionsDirFlag(args) {
54010
+ const parsed = parseFlag(args, "--sessions-dir");
54011
+ if (parsed.error) return parsed;
54012
+ if (parsed.value !== void 0) {
54013
+ if (!path5.isAbsolute(parsed.value)) {
54014
+ return { error: `--sessions-dir must be an absolute path, got "${parsed.value}"` };
54015
+ }
54016
+ return { value: path5.resolve(parsed.value) };
54017
+ }
54018
+ return {};
54019
+ }
53624
54020
  function parseLogLimit(args) {
53625
54021
  for (const name of ["-n", "--lines"]) {
53626
54022
  const parsed = parseFlag(args, name);
@@ -53649,6 +54045,8 @@ async function runMemoryCommand(args) {
53649
54045
  const auto = rest.includes("--auto");
53650
54046
  const dateFlag = parseDateFlag(rest);
53651
54047
  if (dateFlag.error) die(dateFlag.error);
54048
+ const sessionsDirFlag = parseSessionsDirFlag(rest);
54049
+ if (sessionsDirFlag.error) die(sessionsDirFlag.error);
53652
54050
  if (auto && dateFlag.value !== void 0) die("--auto and --date are mutually exclusive");
53653
54051
  if (rest.includes("--worker")) {
53654
54052
  const workerRootFlag = parseMemoryRootFlag(rest);
@@ -53656,26 +54054,26 @@ async function runMemoryCommand(args) {
53656
54054
  const workerRoot = workerRootFlag.value;
53657
54055
  if (!workerRoot) die("--worker requires --memory-root");
53658
54056
  if (auto) {
53659
- const summary = await runDistillAuto(workerRoot);
54057
+ const summary = await runDistillAuto(workerRoot, 7, void 0, sessionsDirFlag.value);
53660
54058
  console.log(summary.lines.join("\n"));
53661
- process.exitCode = summary.ok ? 0 : 1;
54059
+ process.exitCode = distillExitCode(summary);
53662
54060
  return;
53663
54061
  }
53664
54062
  const date2 = dateFlag.value ?? yesterdayKey();
53665
- const result = await runDistillWorkerMain(workerRoot, date2);
54063
+ const result = await runDistillWorkerMain(workerRoot, date2, false, sessionsDirFlag.value);
53666
54064
  if (result.busy) {
53667
54065
  console.log(`memory distill ${date2}: busy \u2014 another distillation worker holds the lock; nothing recorded, retry later`);
53668
54066
  return;
53669
54067
  }
53670
54068
  if (!result.ok) {
53671
54069
  console.error(`memory distill ${date2}: ${result.status ?? "failed"}${result.error ? `: ${result.error}` : ""}`);
53672
- process.exit(1);
54070
+ process.exit(distillExitCode(result));
53673
54071
  }
53674
54072
  console.log(`memory distill ${date2}: ${result.status}`);
53675
54073
  return;
53676
54074
  }
53677
54075
  if (auto) {
53678
- const spawned2 = spawnDistillAutoWorker(root);
54076
+ const spawned2 = spawnDistillAutoWorker(root, sessionsDirFlag.value);
53679
54077
  console.log(spawned2 ? `memory distill --auto: detached worker started (log: ${distillWorkerLogPath(root)})` : `memory distill --auto: could not spawn worker (log: ${distillWorkerLogPath(root)})`);
53680
54078
  process.exitCode = spawned2 ? 0 : 1;
53681
54079
  return;
@@ -53686,7 +54084,7 @@ async function runMemoryCommand(args) {
53686
54084
  console.log(`memory distill ${date}: already distilled (checkpoint present)`);
53687
54085
  return;
53688
54086
  }
53689
- const spawned = spawnDistillWorker(root, date);
54087
+ const spawned = spawnDistillWorker(root, date, sessionsDirFlag.value);
53690
54088
  console.log(spawned ? `memory distill ${date}: detached worker started (log: ${distillWorkerLogPath(root)})` : `memory distill ${date}: could not spawn worker (log: ${distillWorkerLogPath(root)})`);
53691
54089
  process.exitCode = spawned ? 0 : 1;
53692
54090
  return;
@@ -53725,6 +54123,14 @@ async function cronStore() {
53725
54123
  const { Store, configPath } = await import(entryUrl);
53726
54124
  return { Store, configPath };
53727
54125
  }
54126
+ function resolvedSessionsDirOverride() {
54127
+ const override = process.env.PIE_SESSIONS_DIR;
54128
+ if (!override) return void 0;
54129
+ if (override === "~") return path5.join(homedir2(), "sessions");
54130
+ if (override.startsWith("~/")) return path5.join(homedir2(), override.slice(2));
54131
+ if (!path5.isAbsolute(override)) return void 0;
54132
+ return path5.resolve(override);
54133
+ }
53728
54134
  function managedMemoryCommand() {
53729
54135
  const entry = process.argv[1] ? path5.resolve(process.argv[1]) : null;
53730
54136
  if (!entry) throw new Error("cannot determine the CLI entrypoint for the managed schedule");
@@ -53735,7 +54141,19 @@ function managedMemoryCommand() {
53735
54141
  else if (/^--(?:import|loader|experimental-loader)$/.test(arg) && i + 1 < process.execArgv.length)
53736
54142
  loaderArgs.push(arg, process.execArgv[++i]);
53737
54143
  }
53738
- return [process.execPath, ...loaderArgs, entry, "memory", "distill", "--worker", "--auto", "--memory-root", path5.join(getConfigDir(), "memory")];
54144
+ const sessionsDir = resolvedSessionsDirOverride();
54145
+ return [
54146
+ process.execPath,
54147
+ ...loaderArgs,
54148
+ entry,
54149
+ "memory",
54150
+ "distill",
54151
+ "--worker",
54152
+ "--auto",
54153
+ "--memory-root",
54154
+ path5.join(getConfigDir(), "memory"),
54155
+ ...sessionsDir ? ["--sessions-dir", sessionsDir] : []
54156
+ ];
53739
54157
  }
53740
54158
  function timeToCron(value) {
53741
54159
  const match = value.match(/^(\d{1,2}):(\d{2})$/);
@@ -55113,6 +55531,20 @@ var CommandTree = class {
55113
55531
  }
55114
55532
  return results;
55115
55533
  }
55534
+ /**
55535
+ * Resolve a single-segment command alias (e.g. "yolo" -> "settings/yolo")
55536
+ * when EXACTLY ONE non-hidden executable node in the tree has that exact
55537
+ * leaf name (case-insensitive). Returns null on zero or ambiguous matches so
55538
+ * collisions like "list" never silently guess.
55539
+ */
55540
+ findUniqueByName(name) {
55541
+ const needle = name.trim().toLowerCase();
55542
+ if (!needle || needle.includes("/")) return null;
55543
+ const matches = this.searchByName(needle).filter(
55544
+ (match) => match.node.name.toLowerCase() === needle && typeof match.node.handler === "function"
55545
+ );
55546
+ return matches.length === 1 ? matches[0] : null;
55547
+ }
55116
55548
  /**
55117
55549
  * Get all paths for autocomplete
55118
55550
  * Returns paths without leading slash to match cache format
@@ -55204,7 +55636,7 @@ function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, ca
55204
55636
  extension.commands.set(cmdPath.join("/"), registeredCmd);
55205
55637
  commandTree.register(cmdPath, {
55206
55638
  description: command.description,
55207
- handler: command.handler,
55639
+ handler: (ctx, args) => command.handler(ctx, args),
55208
55640
  hidden: command.hidden === true
55209
55641
  });
55210
55642
  },
@@ -55306,6 +55738,12 @@ function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, ca
55306
55738
  getCurrentModel() {
55307
55739
  return actions?.getCurrentModel?.();
55308
55740
  },
55741
+ getThinkingLevel() {
55742
+ return actions?.getThinkingLevel?.();
55743
+ },
55744
+ getThinkingStatus() {
55745
+ return actions?.getThinkingStatus?.();
55746
+ },
55309
55747
  registerProvider(name, config) {
55310
55748
  if (!actions?.registerProvider) throw new Error("registerProvider is not available in this host mode");
55311
55749
  return actions.registerProvider(name, config);
@@ -61738,6 +62176,151 @@ var Kt = g.parseInline;
61738
62176
  var Xt = b.parse;
61739
62177
  var Jt = x.lex;
61740
62178
 
62179
+ // ../../packages/tui/src/components/markdown-table.ts
62180
+ function getLongestWordWidth(text, maxWidth) {
62181
+ const words = text.split(/\s+/).filter((word) => word.length > 0);
62182
+ let longest = 0;
62183
+ for (const word of words) {
62184
+ longest = Math.max(longest, visibleWidth(word));
62185
+ }
62186
+ if (maxWidth === void 0) {
62187
+ return longest;
62188
+ }
62189
+ return Math.min(longest, maxWidth);
62190
+ }
62191
+ function wrapCellText(text, maxWidth) {
62192
+ return wrapTextWithAnsi(text, Math.max(1, maxWidth));
62193
+ }
62194
+ function renderMarkdownTable(token, availableWidth, renderInlineTokens, bold) {
62195
+ const lines = [];
62196
+ const numCols = token.header.length;
62197
+ if (numCols === 0) {
62198
+ return lines;
62199
+ }
62200
+ const borderOverhead = 3 * numCols + 1;
62201
+ const availableForCells = availableWidth - borderOverhead;
62202
+ if (availableForCells < numCols) {
62203
+ const fallbackLines = token.raw ? wrapTextWithAnsi(token.raw, availableWidth) : [];
62204
+ fallbackLines.push("");
62205
+ return fallbackLines;
62206
+ }
62207
+ const maxUnbrokenWordWidth = 30;
62208
+ const naturalWidths = [];
62209
+ const minWordWidths = [];
62210
+ for (let i = 0; i < numCols; i++) {
62211
+ const headerText = renderInlineTokens(token.header[i]?.tokens || []);
62212
+ naturalWidths[i] = visibleWidth(headerText);
62213
+ minWordWidths[i] = Math.max(1, getLongestWordWidth(headerText, maxUnbrokenWordWidth));
62214
+ }
62215
+ for (const row of token.rows) {
62216
+ for (let i = 0; i < row.length; i++) {
62217
+ const cellText = renderInlineTokens(row[i]?.tokens || []);
62218
+ naturalWidths[i] = Math.max(naturalWidths[i] || 0, visibleWidth(cellText));
62219
+ minWordWidths[i] = Math.max(
62220
+ minWordWidths[i] || 1,
62221
+ getLongestWordWidth(cellText, maxUnbrokenWordWidth)
62222
+ );
62223
+ }
62224
+ }
62225
+ let minColumnWidths = minWordWidths;
62226
+ let minCellsWidth = minColumnWidths.reduce((a, b2) => a + b2, 0);
62227
+ if (minCellsWidth > availableForCells) {
62228
+ minColumnWidths = new Array(numCols).fill(1);
62229
+ const remaining = availableForCells - numCols;
62230
+ if (remaining > 0) {
62231
+ const totalWeight = minWordWidths.reduce((total, width) => total + Math.max(0, width - 1), 0);
62232
+ const growth = minWordWidths.map((width) => {
62233
+ const weight = Math.max(0, width - 1);
62234
+ return totalWeight > 0 ? Math.floor(weight / totalWeight * remaining) : 0;
62235
+ });
62236
+ for (let i = 0; i < numCols; i++) {
62237
+ minColumnWidths[i] += growth[i] ?? 0;
62238
+ }
62239
+ const allocated = growth.reduce((total, width) => total + width, 0);
62240
+ let leftover = remaining - allocated;
62241
+ for (let i = 0; leftover > 0 && i < numCols; i++) {
62242
+ minColumnWidths[i]++;
62243
+ leftover--;
62244
+ }
62245
+ }
62246
+ minCellsWidth = minColumnWidths.reduce((a, b2) => a + b2, 0);
62247
+ }
62248
+ const totalNaturalWidth = naturalWidths.reduce((a, b2) => a + b2, 0) + borderOverhead;
62249
+ let columnWidths;
62250
+ if (totalNaturalWidth <= availableWidth) {
62251
+ columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index]));
62252
+ } else {
62253
+ const totalGrowPotential = naturalWidths.reduce((total, width, index) => {
62254
+ return total + Math.max(0, width - minColumnWidths[index]);
62255
+ }, 0);
62256
+ const extraWidth = Math.max(0, availableForCells - minCellsWidth);
62257
+ columnWidths = minColumnWidths.map((minWidth, index) => {
62258
+ const naturalWidth = naturalWidths[index];
62259
+ const minWidthDelta = Math.max(0, naturalWidth - minWidth);
62260
+ let grow = 0;
62261
+ if (totalGrowPotential > 0) {
62262
+ grow = Math.floor(minWidthDelta / totalGrowPotential * extraWidth);
62263
+ }
62264
+ return minWidth + grow;
62265
+ });
62266
+ const allocated = columnWidths.reduce((a, b2) => a + b2, 0);
62267
+ let remaining = availableForCells - allocated;
62268
+ while (remaining > 0) {
62269
+ let grew = false;
62270
+ for (let i = 0; i < numCols && remaining > 0; i++) {
62271
+ if (columnWidths[i] < naturalWidths[i]) {
62272
+ columnWidths[i]++;
62273
+ remaining--;
62274
+ grew = true;
62275
+ }
62276
+ }
62277
+ if (!grew) {
62278
+ break;
62279
+ }
62280
+ }
62281
+ }
62282
+ const topBorderCells = columnWidths.map((w2) => "\u2500".repeat(w2));
62283
+ lines.push(`\u250C\u2500${topBorderCells.join("\u2500\u252C\u2500")}\u2500\u2510`);
62284
+ const headerCellLines = token.header.map((cell, i) => {
62285
+ const text = renderInlineTokens(cell.tokens || []);
62286
+ return wrapCellText(text, columnWidths[i]);
62287
+ });
62288
+ const headerLineCount = Math.max(...headerCellLines.map((c) => c.length));
62289
+ for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) {
62290
+ const rowParts = headerCellLines.map((cellLines, colIdx) => {
62291
+ const text = cellLines[lineIdx] || "";
62292
+ const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
62293
+ return bold(padded);
62294
+ });
62295
+ lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`);
62296
+ }
62297
+ const separatorCells = columnWidths.map((w2) => "\u2500".repeat(w2));
62298
+ const separatorLine = `\u251C\u2500${separatorCells.join("\u2500\u253C\u2500")}\u2500\u2524`;
62299
+ lines.push(separatorLine);
62300
+ for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
62301
+ const row = token.rows[rowIndex];
62302
+ const rowCellLines = row.map((cell, i) => {
62303
+ const text = renderInlineTokens(cell.tokens || []);
62304
+ return wrapCellText(text, columnWidths[i]);
62305
+ });
62306
+ const rowLineCount = Math.max(...rowCellLines.map((c) => c.length));
62307
+ for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) {
62308
+ const rowParts = rowCellLines.map((cellLines, colIdx) => {
62309
+ const text = cellLines[lineIdx] || "";
62310
+ return text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
62311
+ });
62312
+ lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`);
62313
+ }
62314
+ if (rowIndex < token.rows.length - 1) {
62315
+ lines.push(separatorLine);
62316
+ }
62317
+ }
62318
+ const bottomBorderCells = columnWidths.map((w2) => "\u2500".repeat(w2));
62319
+ lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\u2500\u2518`);
62320
+ lines.push("");
62321
+ return lines;
62322
+ }
62323
+
61741
62324
  // ../../packages/tui/src/components/markdown.ts
61742
62325
  function appendLines(target, source) {
61743
62326
  for (let i = 0; i < source.length; i++) {
@@ -62318,161 +62901,16 @@ var Markdown = class {
62318
62901
  }
62319
62902
  return fragments;
62320
62903
  }
62321
- /**
62322
- * Get the visible width of the longest word in a string.
62323
- */
62324
- getLongestWordWidth(text, maxWidth) {
62325
- const words = text.split(/\s+/).filter((word) => word.length > 0);
62326
- let longest = 0;
62327
- for (const word of words) {
62328
- longest = Math.max(longest, visibleWidth(word));
62329
- }
62330
- if (maxWidth === void 0) {
62331
- return longest;
62332
- }
62333
- return Math.min(longest, maxWidth);
62334
- }
62335
- /**
62336
- * Wrap a table cell to fit into a column.
62337
- *
62338
- * Delegates to wrapTextWithAnsi() so ANSI codes + long tokens are handled
62339
- * consistently with the rest of the renderer.
62340
- */
62341
- wrapCellText(text, maxWidth) {
62342
- return wrapTextWithAnsi(text, Math.max(1, maxWidth));
62343
- }
62344
62904
  /**
62345
62905
  * Render a table with width-aware cell wrapping.
62346
- * Cells that don't fit are wrapped to multiple lines.
62347
62906
  */
62348
62907
  renderTable(token, availableWidth) {
62349
- const lines = [];
62350
- const numCols = token.header.length;
62351
- if (numCols === 0) {
62352
- return lines;
62353
- }
62354
- const borderOverhead = 3 * numCols + 1;
62355
- const availableForCells = availableWidth - borderOverhead;
62356
- if (availableForCells < numCols) {
62357
- const fallbackLines = token.raw ? wrapTextWithAnsi(token.raw, availableWidth) : [];
62358
- fallbackLines.push("");
62359
- return fallbackLines;
62360
- }
62361
- const maxUnbrokenWordWidth = 30;
62362
- const naturalWidths = [];
62363
- const minWordWidths = [];
62364
- for (let i = 0; i < numCols; i++) {
62365
- const headerText = this.renderInlineTokens(token.header[i]?.tokens || []);
62366
- naturalWidths[i] = visibleWidth(headerText);
62367
- minWordWidths[i] = Math.max(1, this.getLongestWordWidth(headerText, maxUnbrokenWordWidth));
62368
- }
62369
- for (const row of token.rows) {
62370
- for (let i = 0; i < row.length; i++) {
62371
- const cellText = this.renderInlineTokens(row[i]?.tokens || []);
62372
- naturalWidths[i] = Math.max(naturalWidths[i] || 0, visibleWidth(cellText));
62373
- minWordWidths[i] = Math.max(
62374
- minWordWidths[i] || 1,
62375
- this.getLongestWordWidth(cellText, maxUnbrokenWordWidth)
62376
- );
62377
- }
62378
- }
62379
- let minColumnWidths = minWordWidths;
62380
- let minCellsWidth = minColumnWidths.reduce((a, b2) => a + b2, 0);
62381
- if (minCellsWidth > availableForCells) {
62382
- minColumnWidths = new Array(numCols).fill(1);
62383
- const remaining = availableForCells - numCols;
62384
- if (remaining > 0) {
62385
- const totalWeight = minWordWidths.reduce((total, width) => total + Math.max(0, width - 1), 0);
62386
- const growth = minWordWidths.map((width) => {
62387
- const weight = Math.max(0, width - 1);
62388
- return totalWeight > 0 ? Math.floor(weight / totalWeight * remaining) : 0;
62389
- });
62390
- for (let i = 0; i < numCols; i++) {
62391
- minColumnWidths[i] += growth[i] ?? 0;
62392
- }
62393
- const allocated = growth.reduce((total, width) => total + width, 0);
62394
- let leftover = remaining - allocated;
62395
- for (let i = 0; leftover > 0 && i < numCols; i++) {
62396
- minColumnWidths[i]++;
62397
- leftover--;
62398
- }
62399
- }
62400
- minCellsWidth = minColumnWidths.reduce((a, b2) => a + b2, 0);
62401
- }
62402
- const totalNaturalWidth = naturalWidths.reduce((a, b2) => a + b2, 0) + borderOverhead;
62403
- let columnWidths;
62404
- if (totalNaturalWidth <= availableWidth) {
62405
- columnWidths = naturalWidths.map((width, index) => Math.max(width, minColumnWidths[index]));
62406
- } else {
62407
- const totalGrowPotential = naturalWidths.reduce((total, width, index) => {
62408
- return total + Math.max(0, width - minColumnWidths[index]);
62409
- }, 0);
62410
- const extraWidth = Math.max(0, availableForCells - minCellsWidth);
62411
- columnWidths = minColumnWidths.map((minWidth, index) => {
62412
- const naturalWidth = naturalWidths[index];
62413
- const minWidthDelta = Math.max(0, naturalWidth - minWidth);
62414
- let grow = 0;
62415
- if (totalGrowPotential > 0) {
62416
- grow = Math.floor(minWidthDelta / totalGrowPotential * extraWidth);
62417
- }
62418
- return minWidth + grow;
62419
- });
62420
- const allocated = columnWidths.reduce((a, b2) => a + b2, 0);
62421
- let remaining = availableForCells - allocated;
62422
- while (remaining > 0) {
62423
- let grew = false;
62424
- for (let i = 0; i < numCols && remaining > 0; i++) {
62425
- if (columnWidths[i] < naturalWidths[i]) {
62426
- columnWidths[i]++;
62427
- remaining--;
62428
- grew = true;
62429
- }
62430
- }
62431
- if (!grew) {
62432
- break;
62433
- }
62434
- }
62435
- }
62436
- const topBorderCells = columnWidths.map((w2) => "\u2500".repeat(w2));
62437
- lines.push(`\u250C\u2500${topBorderCells.join("\u2500\u252C\u2500")}\u2500\u2510`);
62438
- const headerCellLines = token.header.map((cell, i) => {
62439
- const text = this.renderInlineTokens(cell.tokens || []);
62440
- return this.wrapCellText(text, columnWidths[i]);
62441
- });
62442
- const headerLineCount = Math.max(...headerCellLines.map((c) => c.length));
62443
- for (let lineIdx = 0; lineIdx < headerLineCount; lineIdx++) {
62444
- const rowParts = headerCellLines.map((cellLines, colIdx) => {
62445
- const text = cellLines[lineIdx] || "";
62446
- const padded = text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
62447
- return this.theme.bold(padded);
62448
- });
62449
- lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`);
62450
- }
62451
- const separatorCells = columnWidths.map((w2) => "\u2500".repeat(w2));
62452
- const separatorLine = `\u251C\u2500${separatorCells.join("\u2500\u253C\u2500")}\u2500\u2524`;
62453
- lines.push(separatorLine);
62454
- for (let rowIndex = 0; rowIndex < token.rows.length; rowIndex++) {
62455
- const row = token.rows[rowIndex];
62456
- const rowCellLines = row.map((cell, i) => {
62457
- const text = this.renderInlineTokens(cell.tokens || []);
62458
- return this.wrapCellText(text, columnWidths[i]);
62459
- });
62460
- const rowLineCount = Math.max(...rowCellLines.map((c) => c.length));
62461
- for (let lineIdx = 0; lineIdx < rowLineCount; lineIdx++) {
62462
- const rowParts = rowCellLines.map((cellLines, colIdx) => {
62463
- const text = cellLines[lineIdx] || "";
62464
- return text + " ".repeat(Math.max(0, columnWidths[colIdx] - visibleWidth(text)));
62465
- });
62466
- lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`);
62467
- }
62468
- if (rowIndex < token.rows.length - 1) {
62469
- lines.push(separatorLine);
62470
- }
62471
- }
62472
- const bottomBorderCells = columnWidths.map((w2) => "\u2500".repeat(w2));
62473
- lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\u2500\u2518`);
62474
- lines.push("");
62475
- return lines;
62908
+ return renderMarkdownTable(
62909
+ token,
62910
+ availableWidth,
62911
+ (tokens) => this.renderInlineTokens(tokens),
62912
+ (text) => this.theme.bold(text)
62913
+ );
62476
62914
  }
62477
62915
  };
62478
62916
 
@@ -63830,6 +64268,8 @@ var ExtensionRunner = class {
63830
64268
  getSessionName: () => runner.actions.getSessionName?.(),
63831
64269
  getSessionDisplayName: () => runner.actions.getSessionDisplayName?.() ?? runner.actions.getSessionName?.(),
63832
64270
  getCurrentModel: () => runner.actions.getCurrentModel?.(),
64271
+ getThinkingLevel: () => runner.actions.getThinkingLevel?.(),
64272
+ getThinkingStatus: () => runner.actions.getThinkingStatus?.(),
63833
64273
  registerProvider: (name, config) => {
63834
64274
  if (!runner.actions.registerProvider) throw new Error("registerProvider is not available in this host mode");
63835
64275
  return runner.trackUnregisterHandle(runner.actions.registerProvider(name, config));
@@ -64140,282 +64580,6 @@ function wrapToolsWithExtensions(tools, runner) {
64140
64580
  return tools.map((tool) => wrapToolWithExtensions(tool, runner));
64141
64581
  }
64142
64582
 
64143
- // src/core/defaults.ts
64144
- var DEFAULT_THINKING_LEVEL = "medium";
64145
- var DEFAULT_YOLO_MODE = true;
64146
-
64147
- // src/core/model-resolver.ts
64148
- function normalizeProviderName(provider) {
64149
- return provider.toLowerCase().replace(/[^a-z]/g, "");
64150
- }
64151
- function selectFallbackModel(registry, preferred) {
64152
- const availableModels = registry.getAvailable();
64153
- if (preferred?.provider && preferred?.modelId) {
64154
- const exact = availableModels.find(
64155
- (model) => model.provider === preferred.provider && model.id === preferred.modelId
64156
- );
64157
- if (exact) return exact;
64158
- }
64159
- if (preferred?.provider) {
64160
- const sameProvider = availableModels.find((model) => model.provider === preferred.provider);
64161
- if (sameProvider) return sameProvider;
64162
- }
64163
- return availableModels[0] || registry.getAll()[0];
64164
- }
64165
- function resolveConfiguredModel(registry, provider, modelId) {
64166
- const exact = registry.find(provider, modelId);
64167
- if (exact) {
64168
- return { model: exact, provider, modelId, corrected: false };
64169
- }
64170
- const allModels = registry.getAll();
64171
- if (allModels.length === 0) {
64172
- throw new Error("No registered models are available.");
64173
- }
64174
- const sameIdMatches = allModels.filter((model) => model.id === modelId);
64175
- const normalizedProviderMatches = sameIdMatches.filter(
64176
- (model) => normalizeProviderName(model.provider) === normalizeProviderName(provider)
64177
- );
64178
- if (normalizedProviderMatches.length === 1) {
64179
- const matched = normalizedProviderMatches[0];
64180
- return {
64181
- model: matched,
64182
- provider: matched.provider,
64183
- modelId: matched.id,
64184
- corrected: true,
64185
- warning: `Configured model "${provider}/${modelId}" was not found. Using "${matched.provider}/${matched.id}" instead.`
64186
- };
64187
- }
64188
- if (sameIdMatches.length === 1) {
64189
- const matched = sameIdMatches[0];
64190
- return {
64191
- model: matched,
64192
- provider: matched.provider,
64193
- modelId: matched.id,
64194
- corrected: true,
64195
- warning: `Configured model "${provider}/${modelId}" was not found. Reusing the available model "${matched.provider}/${matched.id}".`
64196
- };
64197
- }
64198
- const providerModels = registry.getByProvider(provider);
64199
- if (providerModels.length > 0) {
64200
- const fallback2 = providerModels[0];
64201
- return {
64202
- model: fallback2,
64203
- provider: fallback2.provider,
64204
- modelId: fallback2.id,
64205
- corrected: true,
64206
- warning: `Configured model "${provider}/${modelId}" was not found. Falling back to "${fallback2.provider}/${fallback2.id}".`
64207
- };
64208
- }
64209
- const fallback = selectFallbackModel(registry);
64210
- if (!fallback) {
64211
- throw new Error("No registered models are available.");
64212
- }
64213
- return {
64214
- model: fallback,
64215
- provider: fallback.provider,
64216
- modelId: fallback.id,
64217
- corrected: true,
64218
- warning: `Configured model "${provider}/${modelId}" was not found. Falling back to "${fallback.provider}/${fallback.id}".`
64219
- };
64220
- }
64221
- function findInitialModel(options) {
64222
- const configDefaults = options.registry.getConfigDefaults();
64223
- const configuredProvider = options.configuredProvider || configDefaults?.provider;
64224
- const configuredModelId = options.configuredModelId || configDefaults?.modelId;
64225
- const resolved = configuredProvider && configuredModelId ? resolveConfiguredModel(options.registry, configuredProvider, configuredModelId) : void 0;
64226
- const apiKey = resolved ? options.registry.getApiKey(resolved.model) : void 0;
64227
- if (!resolved || !apiKey) {
64228
- const fallback = selectFallbackModel(options.registry, {
64229
- provider: configuredProvider,
64230
- modelId: configuredModelId
64231
- });
64232
- if (!fallback) {
64233
- return {
64234
- model: void 0,
64235
- apiKey: void 0,
64236
- provider: void 0,
64237
- modelId: void 0,
64238
- unconfigured: true,
64239
- warning: "No models are configured. Add one in ~/.pie/models.json before sending messages."
64240
- };
64241
- }
64242
- const fallbackKey = options.registry.getApiKey(fallback);
64243
- if (!fallbackKey) {
64244
- throw new Error(`No API key found for provider "${resolved?.provider || fallback.provider}".`);
64245
- }
64246
- return {
64247
- model: fallback,
64248
- apiKey: fallbackKey,
64249
- provider: fallback.provider,
64250
- modelId: fallback.id,
64251
- warning: resolved ? resolved.warning || `No API key found for "${resolved.provider}". Using "${fallback.provider}/${fallback.id}" instead.` : configuredProvider && configuredModelId ? `Configured model "${configuredProvider}/${configuredModelId}" was not found. Using "${fallback.provider}/${fallback.id}" instead.` : void 0
64252
- };
64253
- }
64254
- return {
64255
- model: resolved.model,
64256
- apiKey,
64257
- provider: resolved.provider,
64258
- modelId: resolved.modelId,
64259
- warning: resolved.warning
64260
- };
64261
- }
64262
- function restoreModelFromSession(options) {
64263
- const savedProvider = options.savedProvider;
64264
- const restored = options.registry.find(savedProvider, options.savedModelId);
64265
- if (restored && options.registry.getApiKey(restored)) {
64266
- return { model: restored };
64267
- }
64268
- if (options.currentModel) {
64269
- return {
64270
- model: options.currentModel,
64271
- fallbackMessage: `Could not restore model ${savedProvider}/${options.savedModelId}. Using ${options.currentModel.provider}/${options.currentModel.id}.`
64272
- };
64273
- }
64274
- const fallback = selectFallbackModel(options.registry, {
64275
- provider: savedProvider,
64276
- modelId: options.savedModelId
64277
- });
64278
- return fallback ? {
64279
- model: fallback,
64280
- fallbackMessage: `Could not restore model ${savedProvider}/${options.savedModelId}. Using ${fallback.provider}/${fallback.id}.`
64281
- } : { model: void 0 };
64282
- }
64283
-
64284
- // src/core/session-model-metadata.ts
64285
- function getSavedSessionModelSelection(activeSession) {
64286
- if (!activeSession) return {};
64287
- const provider = typeof activeSession.metadata.provider === "string" ? activeSession.metadata.provider : typeof activeSession.metadata.defaultProvider === "string" ? activeSession.metadata.defaultProvider : void 0;
64288
- const modelId = typeof activeSession.metadata.modelId === "string" ? activeSession.metadata.modelId : typeof activeSession.metadata.defaultModel === "string" ? activeSession.metadata.defaultModel : void 0;
64289
- const thinkingLevel = typeof activeSession.metadata.thinkingLevel === "string" ? activeSession.metadata.thinkingLevel : void 0;
64290
- return { provider, modelId, thinkingLevel };
64291
- }
64292
- function syncSessionModelMetadata(sessionManager, model, thinkingLevel, options) {
64293
- const activeSession = sessionManager.getActiveSession();
64294
- if (!activeSession || !model) return;
64295
- if (options?.isFallback) {
64296
- activeSession.metadata.thinkingLevel = thinkingLevel;
64297
- activeSession.isDirty = true;
64298
- return;
64299
- }
64300
- activeSession.metadata.provider = model.provider;
64301
- activeSession.metadata.modelId = model.id;
64302
- activeSession.metadata.defaultProvider = model.provider;
64303
- activeSession.metadata.defaultModel = model.id;
64304
- activeSession.metadata.thinkingLevel = thinkingLevel;
64305
- activeSession.isDirty = true;
64306
- }
64307
- function restoreSessionModelState(options) {
64308
- const { provider, modelId, thinkingLevel } = getSavedSessionModelSelection(options.activeSession);
64309
- if (!provider || !modelId) {
64310
- return {
64311
- model: options.currentModel,
64312
- thinkingLevel
64313
- };
64314
- }
64315
- if (options.managerScopedSelection && options.currentModel) {
64316
- return {
64317
- model: options.currentModel,
64318
- thinkingLevel,
64319
- fallbackMessage: `Manager workspace model ${options.currentModel.provider}/${options.currentModel.id} kept (session had ${provider}/${modelId}).`
64320
- };
64321
- }
64322
- const restored = restoreModelFromSession({
64323
- registry: options.registry,
64324
- savedProvider: provider,
64325
- savedModelId: modelId,
64326
- currentModel: options.currentModel
64327
- });
64328
- return {
64329
- model: restored.model,
64330
- thinkingLevel,
64331
- fallbackMessage: restored.fallbackMessage
64332
- };
64333
- }
64334
-
64335
- // src/core/interactive-model-state.ts
64336
- var THINKING_LEVELS = [
64337
- "off",
64338
- "minimal",
64339
- "low",
64340
- "medium",
64341
- "high",
64342
- "xhigh"
64343
- ];
64344
- var THINKING_LEVEL_DESCRIPTIONS = {
64345
- off: "No reasoning",
64346
- minimal: "Very brief reasoning (~1k tokens)",
64347
- low: "Light reasoning (~2k tokens)",
64348
- medium: "Moderate reasoning (~8k tokens)",
64349
- high: "Deep reasoning (~16k tokens)",
64350
- xhigh: "Maximum reasoning (~32k tokens)"
64351
- };
64352
- function isThinkingLevel(value) {
64353
- return THINKING_LEVELS.includes(value);
64354
- }
64355
- function resolveInitialThinkingLevel(options) {
64356
- const sessionLevel = options.session?.metadata.thinkingLevel;
64357
- if (typeof sessionLevel === "string" && isThinkingLevel(sessionLevel)) {
64358
- return sessionLevel;
64359
- }
64360
- return options.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
64361
- }
64362
- function maskApiKey(key) {
64363
- if (key.length <= 6) return "***";
64364
- return key.slice(0, 6) + "***";
64365
- }
64366
- function applyThinkingLevel(options) {
64367
- options.agent.setThinkingLevel(options.level);
64368
- if (options.persist !== false) {
64369
- options.settingsManager.setDefaultThinkingLevel(options.level);
64370
- }
64371
- syncSessionModelMetadata(options.sessionManager, options.model, options.level);
64372
- }
64373
- function switchInteractiveModel(options) {
64374
- const [provider, modelId] = options.fullModelId.split("/");
64375
- const model = options.registry.find(provider, modelId);
64376
- if (!model) {
64377
- throw new Error(`Model "${options.fullModelId}" not found`);
64378
- }
64379
- const apiKey = options.registry.getApiKey(model);
64380
- options.agent.setModel(model);
64381
- if (apiKey) {
64382
- options.agent.apiKey = apiKey;
64383
- fileLogger.log("cli", `Switched model to ${options.fullModelId}, updated API key`, {
64384
- keyPrefix: maskApiKey(apiKey)
64385
- });
64386
- } else {
64387
- fileLogger.log("cli", `Switched model to ${options.fullModelId}, no API key found`);
64388
- }
64389
- options.settingsManager.setDefaultModelAndProvider(provider, modelId);
64390
- syncSessionModelMetadata(options.sessionManager, model, options.thinkingLevel);
64391
- return { model, apiKey };
64392
- }
64393
- function restoreInteractiveSessionState(options) {
64394
- const restored = restoreSessionModelState({
64395
- activeSession: options.activeSession,
64396
- registry: options.registry,
64397
- currentModel: options.currentModel
64398
- });
64399
- const thinkingLevel = restored.thinkingLevel && isThinkingLevel(restored.thinkingLevel) ? restored.thinkingLevel : void 0;
64400
- if (thinkingLevel) {
64401
- options.agent.setThinkingLevel(thinkingLevel);
64402
- }
64403
- let apiKey;
64404
- if (restored.model) {
64405
- options.agent.setModel(restored.model);
64406
- apiKey = options.registry.getApiKey(restored.model);
64407
- if (apiKey) {
64408
- options.agent.apiKey = apiKey;
64409
- }
64410
- }
64411
- return {
64412
- model: restored.model,
64413
- apiKey,
64414
- thinkingLevel,
64415
- fallbackMessage: restored.fallbackMessage
64416
- };
64417
- }
64418
-
64419
64583
  // src/keybindings.ts
64420
64584
  import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
64421
64585
  import { join as join7 } from "path";
@@ -65182,85 +65346,8 @@ var TypeCompiler;
65182
65346
  // src/theme/theme.ts
65183
65347
  var import_chalk = __toESM(require_source(), 1);
65184
65348
  var import_cli_highlight = __toESM(require_dist(), 1);
65185
- var ColorValueSchema = Type.Union([
65186
- Type.String(),
65187
- // hex "#ff0000", var ref "primary", or empty ""
65188
- Type.Integer({ minimum: 0, maximum: 255 })
65189
- // 256-color index
65190
- ]);
65191
- var ThemeJsonSchema = Type.Object({
65192
- $schema: Type.Optional(Type.String()),
65193
- name: Type.String(),
65194
- vars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)),
65195
- colors: Type.Object({
65196
- // Core UI (10 colors)
65197
- accent: ColorValueSchema,
65198
- border: ColorValueSchema,
65199
- borderAccent: ColorValueSchema,
65200
- borderMuted: ColorValueSchema,
65201
- success: ColorValueSchema,
65202
- error: ColorValueSchema,
65203
- warning: ColorValueSchema,
65204
- muted: ColorValueSchema,
65205
- dim: ColorValueSchema,
65206
- text: ColorValueSchema,
65207
- thinkingText: ColorValueSchema,
65208
- // Backgrounds & Content Text (11 colors)
65209
- selectedBg: ColorValueSchema,
65210
- userMessageBg: ColorValueSchema,
65211
- userMessageText: ColorValueSchema,
65212
- customMessageBg: ColorValueSchema,
65213
- customMessageText: ColorValueSchema,
65214
- customMessageLabel: ColorValueSchema,
65215
- toolPendingBg: ColorValueSchema,
65216
- toolSuccessBg: ColorValueSchema,
65217
- toolErrorBg: ColorValueSchema,
65218
- toolTitle: ColorValueSchema,
65219
- toolOutput: ColorValueSchema,
65220
- // Markdown (10 colors)
65221
- mdHeading: ColorValueSchema,
65222
- mdLink: ColorValueSchema,
65223
- mdLinkUrl: ColorValueSchema,
65224
- mdCode: ColorValueSchema,
65225
- mdCodeBlock: ColorValueSchema,
65226
- mdCodeBlockBorder: ColorValueSchema,
65227
- mdQuote: ColorValueSchema,
65228
- mdQuoteBorder: ColorValueSchema,
65229
- mdHr: ColorValueSchema,
65230
- mdListBullet: ColorValueSchema,
65231
- // Tool Diffs (3 colors)
65232
- toolDiffAdded: ColorValueSchema,
65233
- toolDiffRemoved: ColorValueSchema,
65234
- toolDiffContext: ColorValueSchema,
65235
- // Syntax Highlighting (9 colors)
65236
- syntaxComment: ColorValueSchema,
65237
- syntaxKeyword: ColorValueSchema,
65238
- syntaxFunction: ColorValueSchema,
65239
- syntaxVariable: ColorValueSchema,
65240
- syntaxString: ColorValueSchema,
65241
- syntaxNumber: ColorValueSchema,
65242
- syntaxType: ColorValueSchema,
65243
- syntaxOperator: ColorValueSchema,
65244
- syntaxPunctuation: ColorValueSchema,
65245
- // Thinking Level Borders (6 colors)
65246
- thinkingOff: ColorValueSchema,
65247
- thinkingMinimal: ColorValueSchema,
65248
- thinkingLow: ColorValueSchema,
65249
- thinkingMedium: ColorValueSchema,
65250
- thinkingHigh: ColorValueSchema,
65251
- thinkingXhigh: ColorValueSchema,
65252
- // Bash Mode (1 color)
65253
- bashMode: ColorValueSchema
65254
- }),
65255
- export: Type.Optional(
65256
- Type.Object({
65257
- pageBg: Type.Optional(ColorValueSchema),
65258
- cardBg: Type.Optional(ColorValueSchema),
65259
- infoBg: Type.Optional(ColorValueSchema)
65260
- })
65261
- )
65262
- });
65263
- var validateThemeJson = TypeCompiler.Compile(ThemeJsonSchema);
65349
+
65350
+ // src/theme/color-utils.ts
65264
65351
  function detectColorMode() {
65265
65352
  const colorterm = process.env.COLORTERM;
65266
65353
  if (colorterm === "truecolor" || colorterm === "24bit") {
@@ -65397,6 +65484,87 @@ function resolveThemeColors(colors, vars = {}) {
65397
65484
  }
65398
65485
  return resolved;
65399
65486
  }
65487
+
65488
+ // src/theme/theme.ts
65489
+ var ColorValueSchema = Type.Union([
65490
+ Type.String(),
65491
+ // hex "#ff0000", var ref "primary", or empty ""
65492
+ Type.Integer({ minimum: 0, maximum: 255 })
65493
+ // 256-color index
65494
+ ]);
65495
+ var ThemeJsonSchema = Type.Object({
65496
+ $schema: Type.Optional(Type.String()),
65497
+ name: Type.String(),
65498
+ vars: Type.Optional(Type.Record(Type.String(), ColorValueSchema)),
65499
+ colors: Type.Object({
65500
+ // Core UI (10 colors)
65501
+ accent: ColorValueSchema,
65502
+ border: ColorValueSchema,
65503
+ borderAccent: ColorValueSchema,
65504
+ borderMuted: ColorValueSchema,
65505
+ success: ColorValueSchema,
65506
+ error: ColorValueSchema,
65507
+ warning: ColorValueSchema,
65508
+ muted: ColorValueSchema,
65509
+ dim: ColorValueSchema,
65510
+ text: ColorValueSchema,
65511
+ thinkingText: ColorValueSchema,
65512
+ // Backgrounds & Content Text (11 colors)
65513
+ selectedBg: ColorValueSchema,
65514
+ userMessageBg: ColorValueSchema,
65515
+ userMessageText: ColorValueSchema,
65516
+ customMessageBg: ColorValueSchema,
65517
+ customMessageText: ColorValueSchema,
65518
+ customMessageLabel: ColorValueSchema,
65519
+ toolPendingBg: ColorValueSchema,
65520
+ toolSuccessBg: ColorValueSchema,
65521
+ toolErrorBg: ColorValueSchema,
65522
+ toolTitle: ColorValueSchema,
65523
+ toolOutput: ColorValueSchema,
65524
+ // Markdown (10 colors)
65525
+ mdHeading: ColorValueSchema,
65526
+ mdLink: ColorValueSchema,
65527
+ mdLinkUrl: ColorValueSchema,
65528
+ mdCode: ColorValueSchema,
65529
+ mdCodeBlock: ColorValueSchema,
65530
+ mdCodeBlockBorder: ColorValueSchema,
65531
+ mdQuote: ColorValueSchema,
65532
+ mdQuoteBorder: ColorValueSchema,
65533
+ mdHr: ColorValueSchema,
65534
+ mdListBullet: ColorValueSchema,
65535
+ // Tool Diffs (3 colors)
65536
+ toolDiffAdded: ColorValueSchema,
65537
+ toolDiffRemoved: ColorValueSchema,
65538
+ toolDiffContext: ColorValueSchema,
65539
+ // Syntax Highlighting (9 colors)
65540
+ syntaxComment: ColorValueSchema,
65541
+ syntaxKeyword: ColorValueSchema,
65542
+ syntaxFunction: ColorValueSchema,
65543
+ syntaxVariable: ColorValueSchema,
65544
+ syntaxString: ColorValueSchema,
65545
+ syntaxNumber: ColorValueSchema,
65546
+ syntaxType: ColorValueSchema,
65547
+ syntaxOperator: ColorValueSchema,
65548
+ syntaxPunctuation: ColorValueSchema,
65549
+ // Thinking Level Borders (6 colors)
65550
+ thinkingOff: ColorValueSchema,
65551
+ thinkingMinimal: ColorValueSchema,
65552
+ thinkingLow: ColorValueSchema,
65553
+ thinkingMedium: ColorValueSchema,
65554
+ thinkingHigh: ColorValueSchema,
65555
+ thinkingXhigh: ColorValueSchema,
65556
+ // Bash Mode (1 color)
65557
+ bashMode: ColorValueSchema
65558
+ }),
65559
+ export: Type.Optional(
65560
+ Type.Object({
65561
+ pageBg: Type.Optional(ColorValueSchema),
65562
+ cardBg: Type.Optional(ColorValueSchema),
65563
+ infoBg: Type.Optional(ColorValueSchema)
65564
+ })
65565
+ )
65566
+ });
65567
+ var validateThemeJson = TypeCompiler.Compile(ThemeJsonSchema);
65400
65568
  var Theme = class {
65401
65569
  name;
65402
65570
  sourcePath;
@@ -65467,6 +65635,7 @@ var Theme = class {
65467
65635
  case "high":
65468
65636
  return (str2) => this.fg("thinkingHigh", str2);
65469
65637
  case "xhigh":
65638
+ case "max":
65470
65639
  return (str2) => this.fg("thinkingXhigh", str2);
65471
65640
  default:
65472
65641
  return (str2) => this.fg("thinkingOff", str2);
@@ -69387,6 +69556,19 @@ function normalizeSessionTitle(raw) {
69387
69556
  return title;
69388
69557
  }
69389
69558
 
69559
+ // src/commands/interactive-resume-restart.ts
69560
+ var pendingResumeRestart = null;
69561
+ function scheduleResumeRestartAfterExit(restart) {
69562
+ if (pendingResumeRestart) return false;
69563
+ pendingResumeRestart = restart;
69564
+ return true;
69565
+ }
69566
+ function takePendingResumeRestart() {
69567
+ const restart = pendingResumeRestart;
69568
+ pendingResumeRestart = null;
69569
+ return restart;
69570
+ }
69571
+
69390
69572
  // src/commands/interactive-session-commands.ts
69391
69573
  import { spawn as spawn2 } from "node:child_process";
69392
69574
  function textFromContentBlock(block) {
@@ -69508,7 +69690,6 @@ async function loadSession(host, sessionId) {
69508
69690
  });
69509
69691
  if (restored.thinkingLevel) {
69510
69692
  host.thinkingLevel = restored.thinkingLevel;
69511
- host.footer.setState({ thinkingLevel: restored.thinkingLevel });
69512
69693
  }
69513
69694
  if (restored.model) {
69514
69695
  host.options.model = restored.model;
@@ -69520,6 +69701,14 @@ async function loadSession(host, sessionId) {
69520
69701
  contextWindow: restored.model.contextWindow ?? 0
69521
69702
  });
69522
69703
  }
69704
+ if (restored.thinkingLevel || restored.model) {
69705
+ const footerThinking = resolveFooterThinkingState(host.options.model, host.thinkingLevel);
69706
+ host.footer.setState({
69707
+ thinkingLevel: footerThinking.thinkingLevel,
69708
+ effectiveThinkingLevel: footerThinking.effectiveThinkingLevel,
69709
+ thinkingClamped: footerThinking.thinkingClamped
69710
+ });
69711
+ }
69523
69712
  if (restored.fallbackMessage) {
69524
69713
  host.showWarning(restored.fallbackMessage);
69525
69714
  }
@@ -69962,14 +70151,9 @@ var SettingsSelectorComponent = class extends Container {
69962
70151
  settingsList;
69963
70152
  constructor(config, callbacks) {
69964
70153
  super();
69965
- const THINKING_DESCRIPTIONS = {
69966
- off: "No reasoning",
69967
- minimal: "Very brief reasoning (~1k tokens)",
69968
- low: "Light reasoning (~2k tokens)",
69969
- medium: "Moderate reasoning (~8k tokens)",
69970
- high: "Deep reasoning (~16k tokens)",
69971
- xhigh: "Maximum reasoning (~32k tokens)"
69972
- };
70154
+ const thinkingOptions = config.availableThinkingLevels?.length ? config.availableThinkingLevels : ["off", "minimal", "low", "medium", "high", "xhigh"];
70155
+ const thinkingDescriptions = config.thinkingLevelDescriptions ?? THINKING_LEVEL_DESCRIPTIONS;
70156
+ const thinkingCurrentDisplay = config.effectiveThinkingLevel && config.effectiveThinkingLevel !== config.thinkingLevel ? `${config.effectiveThinkingLevel} (req ${config.thinkingLevel})` : config.thinkingLevel;
69973
70157
  const items = [
69974
70158
  {
69975
70159
  id: "model",
@@ -69994,17 +70178,17 @@ var SettingsSelectorComponent = class extends Container {
69994
70178
  {
69995
70179
  id: "thinking",
69996
70180
  label: "Thinking",
69997
- description: "Reasoning depth for thinking-capable models",
69998
- currentValue: config.thinkingLevel,
70181
+ description: "Reasoning depth for the active model",
70182
+ currentValue: thinkingCurrentDisplay,
69999
70183
  submenu: (currentValue, done) => new SelectSubmenu(
70000
70184
  "Thinking Level",
70001
- "Select reasoning depth for thinking-capable models",
70002
- ["off", "minimal", "low", "medium", "high", "xhigh"].map((level) => ({
70185
+ config.thinkingSubtitle ?? "Select reasoning depth for the active model",
70186
+ thinkingOptions.map((level) => ({
70003
70187
  value: level,
70004
70188
  label: level,
70005
- description: THINKING_DESCRIPTIONS[level]
70189
+ description: thinkingDescriptions[level] ?? THINKING_LEVEL_DESCRIPTIONS[level]
70006
70190
  })),
70007
- currentValue,
70191
+ thinkingOptions.includes(config.thinkingLevel) ? config.thinkingLevel : config.effectiveThinkingLevel ?? currentValue,
70008
70192
  (value) => {
70009
70193
  callbacks.onThinkingLevelChange(value);
70010
70194
  done(value);
@@ -72869,9 +73053,15 @@ function showSettingsSelector(host, focusItem) {
72869
73053
  const currentProvider = host.options.model?.provider || "unknown";
72870
73054
  const currentFullId = `${currentProvider}/${currentModelId}`;
72871
73055
  const availableModels = host.options.modelRegistry.listAvailableModels();
73056
+ const thinkingOpts = buildThinkingSelectorOptions(host.options.model);
73057
+ const footerThinking = resolveFooterThinkingState(host.options.model, host.thinkingLevel);
72872
73058
  const selector = new SettingsSelectorComponent(
72873
73059
  {
72874
73060
  thinkingLevel: host.thinkingLevel,
73061
+ effectiveThinkingLevel: footerThinking.effectiveThinkingLevel,
73062
+ availableThinkingLevels: thinkingOpts.levels,
73063
+ thinkingLevelDescriptions: thinkingOpts.descriptions,
73064
+ thinkingSubtitle: thinkingOpts.subtitle,
72875
73065
  currentTheme: getCurrentThemeName(),
72876
73066
  availableThemes: getAvailableThemes(),
72877
73067
  currentModel: currentFullId,
@@ -73081,6 +73271,7 @@ function handleHotkeysCommand(host) {
73081
73271
  `${theme.fg("dim", kb.getKeys("exit").join(" / "))} ${theme.fg("muted", "Exit")}`,
73082
73272
  `${theme.fg("dim", kb.getKeys("interrupt").join(" / "))} ${theme.fg("muted", "Interrupt")}`,
73083
73273
  `${theme.fg("dim", kb.getKeys("expandTools").join(" / "))} ${theme.fg("muted", "Expand/collapse tools")}`,
73274
+ `${theme.fg("dim", kb.getKeys("cycleThinkingLevel").join(" / "))} ${theme.fg("muted", "Cycle thinking level")}`,
73084
73275
  `${theme.fg("dim", kb.getKeys("toggleYolo").join(" / "))} ${theme.fg("muted", "Toggle YOLO mode")}`,
73085
73276
  "",
73086
73277
  theme.fg("muted", "Editor shortcuts:"),
@@ -73114,15 +73305,32 @@ function handleHotkeysCommand(host) {
73114
73305
  host.ui.requestRender();
73115
73306
  }
73116
73307
  function handleThinkingCommand(host, level) {
73117
- if (!level) {
73308
+ const trimmed = level?.trim();
73309
+ if (!trimmed) {
73118
73310
  host.showThinkingLevelSelector();
73119
73311
  return;
73120
73312
  }
73121
- if (!isThinkingLevel(level)) {
73122
- host.showStatus(`Usage: /settings thinking <level> (${THINKING_LEVELS.join("/")})`);
73313
+ const validation = validateExplicitThinkingSelection(host.options.model, trimmed);
73314
+ if (!validation.ok) {
73315
+ host.showStatus(validation.error);
73123
73316
  return;
73124
73317
  }
73125
- host.setThinkingLevel(level);
73318
+ host.setThinkingLevel(validation.level);
73319
+ }
73320
+ function cycleThinkingLevel(host) {
73321
+ const model = host.options.model;
73322
+ const cap = getModelThinkingCapabilities(model);
73323
+ const modelLabel = model ? `${model.provider}/${model.id}` : "current model";
73324
+ if (!cap.configurable || cap.supportedLevels.length <= 1) {
73325
+ host.showStatus(
73326
+ cap.reasoningCapable ? `${modelLabel} uses built-in reasoning (thinking levels are not configurable on the wire)` : `${modelLabel} does not support thinking`
73327
+ );
73328
+ return;
73329
+ }
73330
+ const currentEffective = resolveThinkingSelection(model, host.thinkingLevel).effective;
73331
+ const idx = cap.supportedLevels.indexOf(currentEffective);
73332
+ const nextLevel = cap.supportedLevels[(idx + 1) % cap.supportedLevels.length];
73333
+ host.setThinkingLevel(nextLevel);
73126
73334
  }
73127
73335
  async function handleCalmCommand(host, args) {
73128
73336
  const mode = (args || "").trim().toLowerCase();
@@ -73182,7 +73390,13 @@ async function handleYoloCommand(host, args) {
73182
73390
  }
73183
73391
  function setThinkingLevel(host, level, options) {
73184
73392
  host.thinkingLevel = level;
73185
- host.footer.setState({ thinkingLevel: host.thinkingLevel });
73393
+ host.thinkingLevelEphemeral = false;
73394
+ const footerThinking = resolveFooterThinkingState(host.options.model, level);
73395
+ host.footer.setState({
73396
+ thinkingLevel: footerThinking.thinkingLevel,
73397
+ effectiveThinkingLevel: footerThinking.effectiveThinkingLevel,
73398
+ thinkingClamped: footerThinking.thinkingClamped
73399
+ });
73186
73400
  applyThinkingLevel({
73187
73401
  level,
73188
73402
  agent: host.agent,
@@ -73196,10 +73410,13 @@ function setThinkingLevel(host, level, options) {
73196
73410
  // wrote settings.json + legacy config for remote/self controls).
73197
73411
  persist: options?.persist
73198
73412
  });
73199
- host.showStatus(`Thinking level: ${host.thinkingLevel}`);
73413
+ const status = footerThinking.thinkingClamped && footerThinking.effectiveThinkingLevel !== level ? `Thinking level: ${level} (effective: ${footerThinking.effectiveThinkingLevel})` : `Thinking level: ${level}`;
73414
+ host.showStatus(status);
73200
73415
  }
73201
73416
  function syncSessionModelMetadata2(host) {
73202
- syncSessionModelMetadata(host.sessionManager, host.options.model, host.thinkingLevel);
73417
+ syncSessionModelMetadata(host.sessionManager, host.options.model, host.thinkingLevel, {
73418
+ preserveThinkingLevel: host.thinkingLevelEphemeral
73419
+ });
73203
73420
  }
73204
73421
  async function switchModel(host, fullModelId) {
73205
73422
  const result = switchInteractiveModel({
@@ -73208,7 +73425,8 @@ async function switchModel(host, fullModelId) {
73208
73425
  agent: host.agent,
73209
73426
  settingsManager: host.options.settingsManager,
73210
73427
  sessionManager: host.sessionManager,
73211
- thinkingLevel: host.thinkingLevel
73428
+ thinkingLevel: host.thinkingLevel,
73429
+ preserveSessionThinkingLevel: host.thinkingLevelEphemeral
73212
73430
  });
73213
73431
  host.options.model = result.model;
73214
73432
  if (result.apiKey) {
@@ -73216,22 +73434,28 @@ async function switchModel(host, fullModelId) {
73216
73434
  }
73217
73435
  host.footer.setState({
73218
73436
  modelName: fullModelId,
73219
- contextWindow: result.model.contextWindow ?? 0
73437
+ contextWindow: result.model.contextWindow ?? 0,
73438
+ thinkingLevel: host.thinkingLevel,
73439
+ effectiveThinkingLevel: result.thinkingResolution.effective,
73440
+ thinkingClamped: result.thinkingResolution.clamped
73220
73441
  });
73221
- host.showStatus(`Model: ${fullModelId}`);
73442
+ const thinkingNote = result.thinkingResolution.clamped && result.thinkingResolution.effective !== host.thinkingLevel ? ` (thinking: ${result.thinkingResolution.effective}, requested ${host.thinkingLevel})` : "";
73443
+ host.showStatus(`Model: ${fullModelId}${thinkingNote}`);
73222
73444
  await host.initializeFileManager();
73223
73445
  }
73224
73446
  function showThinkingLevelSelector(host) {
73225
73447
  host.showSelector((done) => {
73226
73448
  const container = new Container();
73449
+ const selectorOpts = buildThinkingSelectorOptions(host.options.model);
73450
+ const currentEffective = resolveThinkingSelection(host.options.model, host.thinkingLevel).effective;
73227
73451
  container.addChild(new Text(theme.bold(theme.fg("accent", "Thinking Level")), 0, 0));
73228
73452
  container.addChild(new Spacer(1));
73229
- container.addChild(new Text(theme.fg("muted", "Select reasoning depth for thinking-capable models"), 0, 0));
73453
+ container.addChild(new Text(theme.fg("muted", selectorOpts.subtitle), 0, 0));
73230
73454
  container.addChild(new Spacer(1));
73231
- const options = THINKING_LEVELS.map((value) => ({
73455
+ const options = selectorOpts.levels.map((value) => ({
73232
73456
  value,
73233
73457
  label: value,
73234
- description: THINKING_LEVEL_DESCRIPTIONS[value]
73458
+ description: selectorOpts.descriptions[value] ?? THINKING_LEVEL_DESCRIPTIONS[value]
73235
73459
  }));
73236
73460
  const selectList = new SelectList(
73237
73461
  options,
@@ -73244,7 +73468,7 @@ function showThinkingLevelSelector(host) {
73244
73468
  noMatch: (text) => theme.fg("dim", text)
73245
73469
  }
73246
73470
  );
73247
- const currentIndex = options.findIndex((o) => o.value === host.thinkingLevel);
73471
+ const currentIndex = options.findIndex((o) => o.value === host.thinkingLevel) !== -1 ? options.findIndex((o) => o.value === host.thinkingLevel) : options.findIndex((o) => o.value === currentEffective);
73248
73472
  if (currentIndex !== -1) {
73249
73473
  selectList.setSelectedIndex(currentIndex);
73250
73474
  }
@@ -73330,12 +73554,6 @@ function handleCtrlC(host) {
73330
73554
  }
73331
73555
  }
73332
73556
  var exitingHosts = /* @__PURE__ */ new WeakSet();
73333
- var pendingResumeRestart = null;
73334
- function scheduleResumeRestartAfterExit(restart) {
73335
- if (pendingResumeRestart) return false;
73336
- pendingResumeRestart = restart;
73337
- return true;
73338
- }
73339
73557
  function cleanupAndExit(host) {
73340
73558
  if (exitingHosts.has(host)) return;
73341
73559
  exitingHosts.add(host);
@@ -73350,8 +73568,7 @@ function cleanupAndExit(host) {
73350
73568
  process.exitCode = 1;
73351
73569
  }
73352
73570
  console.log(`[Cleanup] Goodbye!${sessionId ? ` session: ${sessionId}` : ""}`);
73353
- const restart = pendingResumeRestart;
73354
- pendingResumeRestart = null;
73571
+ const restart = takePendingResumeRestart();
73355
73572
  if (restart) {
73356
73573
  restart();
73357
73574
  return;
@@ -73607,6 +73824,11 @@ function registerBuiltinCommands(host) {
73607
73824
  }
73608
73825
  commandTree.register(entry.path, { description: entry.description, handler });
73609
73826
  }
73827
+ commandTree.register(["think"], {
73828
+ description: "Set thinking level (alias for /settings/thinking)",
73829
+ handler: (_2, args) => host.handleThinkingCommand(args),
73830
+ hidden: true
73831
+ });
73610
73832
  for (const skill of host.skills) {
73611
73833
  commandTree.register(["skills", `skill:${skill.name}`], {
73612
73834
  description: skill.description,
@@ -74255,18 +74477,20 @@ function setupInteractiveEditorSubmitHandler(host) {
74255
74477
  const potentialArgs = spaceIdx === -1 ? "" : text.slice(spaceIdx + 1).trim();
74256
74478
  const firstPartSegments = firstPart.slice(1).split("/").filter(Boolean);
74257
74479
  const exactMatch = commandTree.find(firstPartSegments);
74258
- if (exactMatch?.handler) {
74480
+ const uniqueAlias = !exactMatch && firstPartSegments.length === 1 ? commandTree.findUniqueByName(firstPartSegments[0]) : null;
74481
+ const resolvedCommand = exactMatch?.handler ? { node: exactMatch, path: firstPart } : uniqueAlias?.node.handler ? { node: uniqueAlias.node, path: `/${uniqueAlias.path}` } : null;
74482
+ if (resolvedCommand) {
74259
74483
  if (shouldQueueUserInput(host)) {
74260
- if (firstPart === "/sessions/compact") {
74484
+ if (resolvedCommand.path === "/sessions/compact") {
74261
74485
  host.showStatus("Wait for the current response to finish before compacting");
74262
74486
  return;
74263
74487
  }
74264
- showBusyCommandStatus(host, firstPart);
74488
+ showBusyCommandStatus(host, resolvedCommand.path);
74265
74489
  return;
74266
74490
  }
74267
74491
  host.editor.setText("");
74268
74492
  try {
74269
- const result = await exactMatch.handler(host.createExtensionContextForCommands(), potentialArgs);
74493
+ const result = await resolvedCommand.node.handler(host.createExtensionContextForCommands(), potentialArgs);
74270
74494
  if (result) {
74271
74495
  host.chatContainer.addChild(new Spacer(1));
74272
74496
  host.chatContainer.addChild(new Text(`[${text}]`, 1, 0));
@@ -76262,6 +76486,10 @@ function setupInteractiveKeybindings(host) {
76262
76486
  host.toggleToolsExpansion();
76263
76487
  return { consume: true };
76264
76488
  }
76489
+ if (host.keybindings.matches(data, "cycleThinkingLevel") && mainEditorOwnsInput(host)) {
76490
+ host.cycleThinkingLevel?.();
76491
+ return { consume: true };
76492
+ }
76265
76493
  if (host.keybindings.matches(data, "toggleYolo") && mainEditorOwnsInput(host)) {
76266
76494
  host.toggleYoloMode?.();
76267
76495
  return { consume: true };
@@ -77203,8 +77431,13 @@ var FooterComponent = class {
77203
77431
  const statsLeft = statsParts.join(" ");
77204
77432
  const modelName = state.modelName || "no-model";
77205
77433
  let rightSide = modelName;
77206
- if (state.thinkingLevel) {
77207
- rightSide += `-${state.thinkingLevel}`;
77434
+ const effective = state.effectiveThinkingLevel ?? state.thinkingLevel;
77435
+ if (effective) {
77436
+ if (state.thinkingClamped && state.thinkingLevel && effective !== state.thinkingLevel) {
77437
+ rightSide += `-${effective} (req ${state.thinkingLevel})`;
77438
+ } else {
77439
+ rightSide += `-${effective}`;
77440
+ }
77208
77441
  }
77209
77442
  const statsLeftWidth = visibleWidth(statsLeft);
77210
77443
  const rightWidth = visibleWidth(rightSide);
@@ -77500,13 +77733,16 @@ function setupUI(host) {
77500
77733
  host.footer.setAutoCompactEnabled(host.options.settingsManager.getAutoCompactEnabled());
77501
77734
  const usage2 = calculateContextUsage(host);
77502
77735
  const contextWindow = host.options.model?.contextWindow ?? 0;
77736
+ const footerThinking = resolveFooterThinkingState(host.options.model, host.thinkingLevel);
77503
77737
  host.footer.setState({
77504
77738
  modelName: host.options.model ? `${host.options.model.provider}/${host.options.model.id}` : "unknown",
77505
77739
  status: "ready",
77506
77740
  planMode: host.planModeEnabled,
77507
77741
  calmMode: host.calmMode,
77508
77742
  yoloMode: Boolean(host.yoloMode),
77509
- thinkingLevel: host.thinkingLevel,
77743
+ thinkingLevel: footerThinking.thinkingLevel,
77744
+ effectiveThinkingLevel: footerThinking.effectiveThinkingLevel,
77745
+ thinkingClamped: footerThinking.thinkingClamped,
77510
77746
  inputTokens: usage2.input,
77511
77747
  outputTokens: usage2.output,
77512
77748
  cacheRead: usage2.cacheRead,
@@ -77741,7 +77977,8 @@ var HierarchicalSelectorComponent = class extends Container {
77741
77977
  if (node.isCategory) {
77742
77978
  props.onNavigate([...props.path, node.name]);
77743
77979
  } else {
77744
- const searchArgs = this.searchText.trim();
77980
+ const spaceIdx = this.searchText.indexOf(" ");
77981
+ const searchArgs = spaceIdx === -1 ? "" : this.searchText.slice(spaceIdx + 1).trim();
77745
77982
  props.onSelect([...props.path, node.name], node, searchArgs);
77746
77983
  }
77747
77984
  };
@@ -77886,7 +78123,7 @@ function showHierarchicalMenu(host, initialPath = []) {
77886
78123
  },
77887
78124
  onSelect: async (selectedPath, node, searchArgs) => {
77888
78125
  if (node.handler) {
77889
- const args = searchArgs || (selectedPath.length > path26.length ? selectedPath.slice(path26.length).join(" ") : void 0);
78126
+ const args = searchArgs?.trim() || void 0;
77890
78127
  const commandPath = "/" + selectedPath.join("/");
77891
78128
  if (!args && host.isInteractiveCommand(commandPath)) {
77892
78129
  done();
@@ -77976,6 +78213,9 @@ async function executeCommand(host, command) {
77976
78213
  break;
77977
78214
  }
77978
78215
  }
78216
+ if (!node && pathParts.length === 1) {
78217
+ node = commandTree.findUniqueByName(pathParts[0])?.node ?? null;
78218
+ }
77979
78219
  if (node?.handler) {
77980
78220
  await node.handler(host.createExtensionContextForCommands(), args);
77981
78221
  } else {
@@ -79390,7 +79630,8 @@ function beginUserInput(host, extensionIsCurrent = () => true) {
79390
79630
  const looksLikeImage = /\.(png|jpe?g|gif|webp|bmp|heic|tiff?)$/i.test(file.path);
79391
79631
  const needsFallback = looksLikeImage && (!handlerAtCapture || !modelIsImageCapable);
79392
79632
  if (needsFallback) {
79393
- const described = await host.describeImageFile?.(file.path, file.displayName);
79633
+ const fallbackName = file.displayName ?? file.path;
79634
+ const described = await host.describeImageFile?.(file.path, fallbackName);
79394
79635
  if (described === void 0) {
79395
79636
  mentions.push(`[image attachment "${file.displayName}" could not be delivered: the active model has no image input and no vision fallback is configured]`);
79396
79637
  } else {
@@ -79513,16 +79754,27 @@ async function loadInteractiveExtensions(host) {
79513
79754
  applyIpcControl: async (control, payload) => {
79514
79755
  if (control === "thinking.set") {
79515
79756
  const level = payload && typeof payload === "object" && "level" in payload ? String(payload.level) : void 0;
79516
- const valid = ["off", "minimal", "low", "medium", "high", "xhigh"];
79517
- if (!level || !valid.includes(level)) return { ok: false, message: `thinking.set requires payload.level as one of ${valid.join("|")}` };
79757
+ if (!level) return { ok: false, message: "thinking.set requires payload.level" };
79758
+ const validation = validateExplicitThinkingSelection(host.options.model, level);
79759
+ if (!validation.ok) return { ok: false, message: validation.error };
79518
79760
  if (!host.setThinkingLevelForIpcControl) return { ok: false, message: "host does not expose a thinking-level path" };
79519
79761
  try {
79520
- host.setThinkingLevelForIpcControl(level);
79521
- return { ok: true, message: `thinking level set to ${level} (applies from the next agent execution)` };
79762
+ host.setThinkingLevelForIpcControl(validation.level);
79763
+ const effNote = validation.resolved.clamped && validation.resolved.effective !== validation.level ? ` (effective: ${validation.resolved.effective})` : "";
79764
+ return { ok: true, message: `thinking level set to ${validation.level}${effNote} (applies from the next agent execution)` };
79522
79765
  } catch (error) {
79523
79766
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
79524
79767
  }
79525
79768
  }
79769
+ if (control === "turn.abort") {
79770
+ const busy = host.isProcessing || host.agent.state.isStreaming;
79771
+ if (!busy) return { ok: true, message: "already idle (no active turn)" };
79772
+ host.abortAgent();
79773
+ return { ok: true, message: "active turn interrupted" };
79774
+ }
79775
+ if (control === "session.shutdown") {
79776
+ return { ok: false, message: "interactive TUI sessions cannot be shut down remotely" };
79777
+ }
79526
79778
  if (control !== "model.set") return { ok: false, message: `unknown control: ${control}` };
79527
79779
  if (!host.switchModel) return { ok: false, message: "host does not expose a model switch path" };
79528
79780
  const ref = payload && typeof payload === "object" && "model" in payload ? String(payload.model) : void 0;
@@ -79534,7 +79786,9 @@ async function loadInteractiveExtensions(host) {
79534
79786
  if (!host.options.modelRegistry.getApiKey(model)) return { ok: false, message: `model "${ref}" has no API key configured` };
79535
79787
  try {
79536
79788
  await host.switchModel(ref);
79537
- return { ok: true, message: `model set to ${ref}` };
79789
+ const resolved = resolveThinkingSelection(model, host.thinkingLevel ?? host.agent.state.thinkingLevel);
79790
+ const effNote = resolved.clamped && resolved.effective !== resolved.requested ? ` (thinking: ${resolved.effective}, requested ${resolved.requested})` : "";
79791
+ return { ok: true, message: `model set to ${ref}${effNote}` };
79538
79792
  } catch (error) {
79539
79793
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
79540
79794
  }
@@ -79590,6 +79844,17 @@ async function loadInteractiveExtensions(host) {
79590
79844
  const model = host.options.model;
79591
79845
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : void 0;
79592
79846
  },
79847
+ getThinkingLevel: () => host.thinkingLevel,
79848
+ getThinkingStatus: () => {
79849
+ const requested = host.thinkingLevel ?? host.agent.state.thinkingLevel;
79850
+ const resolved = resolveThinkingSelection(host.options.model, requested);
79851
+ return {
79852
+ requested: resolved.requested,
79853
+ effective: resolved.effective,
79854
+ supportedLevels: resolved.supportedLevels,
79855
+ configurable: resolved.configurable
79856
+ };
79857
+ },
79593
79858
  registerProvider: (name, config) => {
79594
79859
  const unregister = host.options.modelRegistry.registerProvider(name, config);
79595
79860
  host.noteRuntimeModeChanged("extension_register_provider");
@@ -79792,6 +80057,7 @@ var InteractiveMode = class {
79792
80057
  _turnIndex = 0;
79793
80058
  _semanticTurnIndex = 0;
79794
80059
  thinkingLevel = DEFAULT_THINKING_LEVEL;
80060
+ thinkingLevelEphemeral = false;
79795
80061
  toolOutputExpanded = false;
79796
80062
  planModeEnabled = false;
79797
80063
  pendingPlanModeTransition = null;
@@ -79977,7 +80243,7 @@ var InteractiveMode = class {
79977
80243
  configDir: this.options.configDir,
79978
80244
  fileObservationState: this.options.fileObservationState,
79979
80245
  skills: this.skills,
79980
- getActiveSessionId: () => this.sessionManager.getActiveSessionId(),
80246
+ getActiveSessionId: () => this.sessionManager.getActiveSessionId() ?? void 0,
79981
80247
  getAgentModel: () => this.options.model,
79982
80248
  resolveToolModel: (purpose) => this.options.modelRegistry.resolveToolModel(purpose, this.options.model),
79983
80249
  resolveToolModelCandidates: this.options.modelRegistry.resolveToolModelCandidates ? (purpose) => this.options.modelRegistry.resolveToolModelCandidates(purpose, this.options.model) : void 0,
@@ -80107,8 +80373,9 @@ var InteractiveMode = class {
80107
80373
  }
80108
80374
  async init() {
80109
80375
  const activeSession = this.sessionManager.getActiveSession();
80110
- this.thinkingLevel = resolveInitialThinkingLevel({ session: activeSession, settingsManager: this.options.settingsManager });
80111
- const { Agent } = await import("./chunks/src-B44QWSGM.js");
80376
+ this.thinkingLevelEphemeral = Boolean(this.options.explicitThinkingLevel);
80377
+ this.thinkingLevel = resolveInitialThinkingLevel({ explicitThinkingLevel: this.options.explicitThinkingLevel, session: activeSession, settingsManager: this.options.settingsManager });
80378
+ const { Agent } = await import("./chunks/src-2XI5P62J.js");
80112
80379
  this.agent = new Agent({
80113
80380
  initialState: {
80114
80381
  systemPrompt: this.buildSystemPrompt(),
@@ -80288,6 +80555,9 @@ var InteractiveMode = class {
80288
80555
  handleThinkingCommand(level) {
80289
80556
  return handleThinkingCommand(this, level);
80290
80557
  }
80558
+ cycleThinkingLevel() {
80559
+ return cycleThinkingLevel(this);
80560
+ }
80291
80561
  async handleYoloCommand(args) {
80292
80562
  return handleYoloCommand(this, args);
80293
80563
  }
@@ -80485,13 +80755,12 @@ var InteractiveMode = class {
80485
80755
  }
80486
80756
  const merged = /* @__PURE__ */ new Map();
80487
80757
  const context = this.extensionRunner?.createContext();
80488
- for (const extension of this.extensions) {
80489
- for (const [key, shortcut] of extension.shortcuts) {
80490
- if (merged.has(key)) continue;
80491
- merged.set(key, {
80492
- key,
80493
- handler: () => shortcut.handler(context)
80494
- });
80758
+ if (context) {
80759
+ for (const extension of this.extensions) {
80760
+ for (const [key, shortcut] of extension.shortcuts) {
80761
+ if (merged.has(key)) continue;
80762
+ merged.set(key, { key, handler: () => shortcut.handler(context) });
80763
+ }
80495
80764
  }
80496
80765
  }
80497
80766
  this.extensionShortcutsCache = { extensions: this.extensions, runner: this.extensionRunner, shortcuts: merged };
@@ -80500,7 +80769,7 @@ var InteractiveMode = class {
80500
80769
  /** Live mention handler for extension-driven attachments (duck-typed onto
80501
80770
  * InteractiveExtensionLoaderHost); undefined while attachments init. */
80502
80771
  async describeImageFile(filePath, displayName) {
80503
- const { describeImageViaUnderstandingChain } = await import("./chunks/host-image-fallback-N7RHNPYN.js");
80772
+ const { describeImageViaUnderstandingChain } = await import("./chunks/host-image-fallback-RASJSVZY.js");
80504
80773
  return describeImageViaUnderstandingChain({ modelRegistry: this.options.modelRegistry, getAgentModel: () => this.agent?.state.model, filePath, displayName });
80505
80774
  }
80506
80775
  activeModelInputs() {
@@ -80867,6 +81136,7 @@ async function composeCliRuntime(params) {
80867
81136
  cwd,
80868
81137
  sessionManager,
80869
81138
  sessionId,
81139
+ explicitThinkingLevel: params.explicitThinkingLevel,
80870
81140
  skills,
80871
81141
  skillsSection,
80872
81142
  knowledgeSection,
@@ -80895,7 +81165,8 @@ async function composeCliRuntime(params) {
80895
81165
  extensionPaths: params.extensionPaths,
80896
81166
  extensionFlags: params.extensionFlags,
80897
81167
  compositionTrace,
80898
- sessionModelFallback: restoredViaFallback
81168
+ sessionModelFallback: restoredViaFallback,
81169
+ explicitThinkingLevel: params.explicitThinkingLevel
80899
81170
  };
80900
81171
  return interactiveOptions;
80901
81172
  }
@@ -81126,7 +81397,7 @@ async function runPrintMode(params) {
81126
81397
  `);
81127
81398
  console.log("Assistant: ");
81128
81399
  }
81129
- const { Agent: AgentClass } = await import("./chunks/src-B44QWSGM.js");
81400
+ const { Agent: AgentClass } = await import("./chunks/src-2XI5P62J.js");
81130
81401
  let agent;
81131
81402
  const printModeExtensions = await loadPrintModeExtensions({
81132
81403
  cwd: runtime.cwd,
@@ -81161,7 +81432,24 @@ async function runPrintMode(params) {
81161
81432
  knowledgeSection: runtime.knowledgeSection,
81162
81433
  tools: printModeTools
81163
81434
  });
81164
- const printThinkingLevel = resolveInitialThinkingLevel({ session: runtime.sessionManager.getActiveSession(), settingsManager: runtime.settingsManager });
81435
+ if (runtime.explicitThinkingLevel) {
81436
+ const validation = validateExplicitThinkingSelection(runtime.model, runtime.explicitThinkingLevel);
81437
+ if (!validation.ok) {
81438
+ if (params.jsonOutput) {
81439
+ console.log(JSON.stringify({ ok: false, error: validation.error, provider: runtime.provider, modelId: runtime.modelId }));
81440
+ } else {
81441
+ console.error(`Error: ${validation.error}`);
81442
+ }
81443
+ process.exitCode = 2;
81444
+ disarmWatchdog();
81445
+ return;
81446
+ }
81447
+ }
81448
+ const printThinkingLevel = resolveInitialThinkingLevel({
81449
+ explicitThinkingLevel: runtime.explicitThinkingLevel,
81450
+ session: runtime.sessionManager.getActiveSession(),
81451
+ settingsManager: runtime.settingsManager
81452
+ });
81165
81453
  const sessionTrace = new SessionTraceWriter(runtime.paths.sessionsDir, runtime.sessionManager);
81166
81454
  agent = new AgentClass({
81167
81455
  initialState: {
@@ -81331,6 +81619,8 @@ async function runPrintMode(params) {
81331
81619
 
81332
81620
  // src/app/json-events-mode.ts
81333
81621
  import readline from "node:readline";
81622
+
81623
+ // src/app/json-events-output.ts
81334
81624
  import * as fs21 from "node:fs";
81335
81625
 
81336
81626
  // src/app/jsonl-writer.ts
@@ -81370,104 +81660,7 @@ function createJsonlWriter(io) {
81370
81660
  };
81371
81661
  }
81372
81662
 
81373
- // src/app/json-events-mode.ts
81374
- import * as os9 from "node:os";
81375
-
81376
- // src/runtime/headless-session-commands.ts
81377
- function buildHeadlessContextReport(params) {
81378
- const usage2 = calculateCliContextUsage({
81379
- messages: params.messages,
81380
- latestCompactionTimestamp: params.latestCompactionTimestamp ?? null
81381
- });
81382
- const limit = params.contextWindow && params.contextWindow > 0 ? autoCompactLimit(params.contextWindow, params.reserveTokens) : null;
81383
- return {
81384
- estimatedTokens: usage2.tokens,
81385
- contextWindow: params.contextWindow ?? 0,
81386
- percent: usage2.tokens !== null && params.contextWindow && params.contextWindow > 0 ? Math.round(usage2.tokens / params.contextWindow * 1e3) / 10 : null,
81387
- providerMeasuredTokens: usage2.providerMeasuredTokens,
81388
- providerMeasuredAt: usage2.providerMeasuredAt,
81389
- measurementMatchesCurrentContext: usage2.measurementMatchesCurrentContext,
81390
- autoCompactEnabled: params.autoCompactEnabled,
81391
- autoCompactLimitTokens: limit,
81392
- pendingQueuedInputs: params.controller.pendingMessageCount,
81393
- isStreaming: params.controller.isStreaming,
81394
- basis: "estimate",
81395
- generatedAt: Date.now()
81396
- };
81397
- }
81398
- function autoCompactLimit(contextWindow, reserveTokens) {
81399
- const limit = getAutoCompactTokenLimit(contextWindow, reserveTokens);
81400
- return typeof limit === "number" ? limit : null;
81401
- }
81402
- async function runHeadlessManualCompact(params) {
81403
- const { controller } = params;
81404
- if (manualCompactInFlight.has(controller)) {
81405
- return { status: "refused", reason: "a manual compaction is already running; wait for it to finish" };
81406
- }
81407
- const gate = () => {
81408
- if (controller.isStreaming) return "a turn is streaming; retry when idle";
81409
- if (controller.hasQueuedMessages) return `${controller.pendingMessageCount} input(s) still queued; retry when idle`;
81410
- return void 0;
81411
- };
81412
- const firstGate = gate();
81413
- if (firstGate) return { status: "refused", reason: firstGate };
81414
- const sessionId = controller.sessionManager.getActiveSession()?.id ?? "";
81415
- const messageCount = controller.agent.state.messages.length;
81416
- if (messageCount === 0) {
81417
- return { status: "refused", reason: "nothing to compact yet" };
81418
- }
81419
- const before = await params.emitBeforeCompact({ reason: "manual", messageCount });
81420
- if (before?.cancel) {
81421
- return { status: "refused", reason: "cancelled by an extension (session:before_compact)" };
81422
- }
81423
- const afterSession = controller.sessionManager.getActiveSession()?.id ?? "";
81424
- if (afterSession !== sessionId) {
81425
- return { status: "refused", reason: "session changed during the pre-compact hook; nothing started" };
81426
- }
81427
- const secondGate = gate();
81428
- if (secondGate) return { status: "refused", reason: secondGate };
81429
- if (manualCompactInFlight.has(controller)) {
81430
- return { status: "refused", reason: "a manual compaction is already running; wait for it to finish" };
81431
- }
81432
- manualCompactInFlight.add(controller);
81433
- void (async () => {
81434
- let outcome;
81435
- try {
81436
- const result = await controller.runAutoCompact("manual", false);
81437
- outcome = {
81438
- ok: !result?.aborted,
81439
- detail: result?.aborted ? "compaction aborted (extension cancel or session change)" : `compaction committed (tokensBefore=${result?.tokensBefore ?? "?"}, savings=${result?.tokenSavings ?? "?"})`
81440
- };
81441
- } catch (error) {
81442
- outcome = {
81443
- ok: false,
81444
- detail: `compaction failed: ${error instanceof Error ? error.message : String(error)}`
81445
- };
81446
- } finally {
81447
- manualCompactInFlight.delete(controller);
81448
- }
81449
- params.onSettled?.(outcome);
81450
- })();
81451
- return { status: "accepted", sessionId };
81452
- }
81453
- var manualCompactInFlight = /* @__PURE__ */ new WeakSet();
81454
- function isManualCompactionInFlight(controller) {
81455
- return manualCompactInFlight.has(controller);
81456
- }
81457
-
81458
- // src/app/host-idle.ts
81459
- var PENDING_RECOVERY = /* @__PURE__ */ new Set([
81460
- "retry_pending",
81461
- "retrying",
81462
- "compacting"
81463
- ]);
81464
- function hostIsIdle(controller) {
81465
- if (!controller) return true;
81466
- if (controller.isStreaming || controller.hasQueuedMessages) return false;
81467
- return !PENDING_RECOVERY.has(controller.turnRecoveryState);
81468
- }
81469
-
81470
- // src/app/json-events-mode.ts
81663
+ // src/app/json-events-protocol.ts
81471
81664
  var MAX_EVENT_OBJECT_KEYS = 50;
81472
81665
  var MAX_EVENT_ARRAY_ITEMS = 50;
81473
81666
  var MAX_EVENT_VALUE_DEPTH = 4;
@@ -81475,69 +81668,9 @@ var MAX_EVENT_STRING_LENGTH = 4e3;
81475
81668
  var COMPACT_EVENT_STRING_LENGTH = 800;
81476
81669
  var FULL_DETAIL = "full";
81477
81670
  var COMPACT_DETAIL = "compact";
81478
- async function describeImageViaUnderstanding(params, filePath, displayName) {
81479
- try {
81480
- const { understandReadFile: understandReadFile2 } = await import("./chunks/read-file-understanding-FMPXR6EJ.js");
81481
- const ext = filePath.toLowerCase().split(".").pop() ?? "";
81482
- const mime = ext === "png" ? "image/png" : ext === "gif" ? "image/gif" : ext === "webp" ? "image/webp" : "image/jpeg";
81483
- const agentModel = params.getAgent?.()?.state?.model;
81484
- const result = await understandReadFile2(
81485
- {
81486
- configDir: process.env.PIE_CODING_AGENT_DIR || `${os9.homedir()}/.pie`,
81487
- cwd: process.cwd(),
81488
- getAgentModel: () => agentModel,
81489
- getSessionId: () => void 0,
81490
- resolveToolModel: (purpose, current) => params.runtime.modelRegistry.resolveToolModel(purpose, current),
81491
- resolveToolModelCandidates: (purpose, current) => params.runtime.modelRegistry.resolveToolModelCandidates(purpose, current)
81492
- },
81493
- { absolutePath: filePath, displayPath: displayName, mimeType: mime, kind: "image" }
81494
- );
81495
- if (result.isError) return void 0;
81496
- const text = result.content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim();
81497
- return text || void 0;
81498
- } catch {
81499
- return void 0;
81500
- }
81501
- }
81502
- function createNoOpExtensionUIContext2() {
81503
- return {
81504
- // Embedded eventSink: notifications surface as stdout events for the
81505
- // GUI host (toasts, logs); they never render anywhere inside pie. The
81506
- // dialog methods stay no-op — capabilities.interactiveUI is false and
81507
- // extensions must gate dialogs on that axis.
81508
- notify: (message, type) => {
81509
- writeEvent({
81510
- type: "ui.notification",
81511
- message: truncateForEvent(message, MAX_EVENT_STRING_LENGTH).value,
81512
- ...type ? { level: type } : {}
81513
- });
81514
- },
81515
- select: async () => void 0,
81516
- confirm: async () => false,
81517
- input: async () => void 0,
81518
- editor: async () => void 0,
81519
- custom: async () => void 0
81520
- };
81521
- }
81522
- process.stdout.on("error", (error) => {
81523
- if (error.code === "EPIPE") return;
81524
- throw error;
81525
- });
81526
- var writeJsonl = createJsonlWriter({
81527
- isTTY: () => !!process.stdout.isTTY,
81528
- writeSync: (buffer, offset) => fs21.writeSync(1, buffer, offset, buffer.length - offset),
81529
- writeAsync: (buffer) => process.stdout.write(buffer)
81530
- });
81531
- function writeEvent(event) {
81532
- const line = `${JSON.stringify(event)}
81533
- `;
81534
- if (eventSinkOverride) {
81535
- eventSinkOverride(line);
81536
- return;
81537
- }
81538
- writeJsonl(line);
81671
+ function isRecord3(value) {
81672
+ return !!value && typeof value === "object" && !Array.isArray(value);
81539
81673
  }
81540
- var eventSinkOverride;
81541
81674
  function toJsonValue(value, depth = 0, cap = MAX_EVENT_STRING_LENGTH) {
81542
81675
  if (value === null) return null;
81543
81676
  if (typeof value === "string") {
@@ -81561,9 +81694,6 @@ function toJsonValue(value, depth = 0, cap = MAX_EVENT_STRING_LENGTH) {
81561
81694
  }
81562
81695
  return result;
81563
81696
  }
81564
- function isRecord3(value) {
81565
- return !!value && typeof value === "object" && !Array.isArray(value);
81566
- }
81567
81697
  function truncateForEvent(text, cap) {
81568
81698
  if (text.length <= cap) {
81569
81699
  return { value: text, truncated: false, fullLength: text.length };
@@ -81652,6 +81782,47 @@ function parseInput(line) {
81652
81782
  }
81653
81783
  return null;
81654
81784
  }
81785
+
81786
+ // src/app/json-events-output.ts
81787
+ process.stdout.on("error", (error) => {
81788
+ if (error.code === "EPIPE") return;
81789
+ throw error;
81790
+ });
81791
+ var writeJsonl = createJsonlWriter({
81792
+ isTTY: () => !!process.stdout.isTTY,
81793
+ writeSync: (buffer, offset) => fs21.writeSync(1, buffer, offset, buffer.length - offset),
81794
+ writeAsync: (buffer) => process.stdout.write(buffer)
81795
+ });
81796
+ function writeEvent(event) {
81797
+ const line = `${JSON.stringify(event)}
81798
+ `;
81799
+ if (eventSinkOverride) {
81800
+ eventSinkOverride(line);
81801
+ return;
81802
+ }
81803
+ writeJsonl(line);
81804
+ }
81805
+ var eventSinkOverride;
81806
+ function createNoOpExtensionUIContext2() {
81807
+ return {
81808
+ // Embedded eventSink: notifications surface as stdout events for the
81809
+ // GUI host (toasts, logs); they never render anywhere inside pie. The
81810
+ // dialog methods stay no-op — capabilities.interactiveUI is false and
81811
+ // extensions must gate dialogs on that axis.
81812
+ notify: (message, type) => {
81813
+ writeEvent({
81814
+ type: "ui.notification",
81815
+ message: truncateForEvent(message, MAX_EVENT_STRING_LENGTH).value,
81816
+ ...type ? { level: type } : {}
81817
+ });
81818
+ },
81819
+ select: async () => void 0,
81820
+ confirm: async () => false,
81821
+ input: async () => void 0,
81822
+ editor: async () => void 0,
81823
+ custom: async () => void 0
81824
+ };
81825
+ }
81655
81826
  function assistantTextFromAgent(agent) {
81656
81827
  const messages = agent?.state.messages ?? [];
81657
81828
  const lastMessage = messages[messages.length - 1];
@@ -81703,42 +81874,506 @@ function extractJsonEventsToolProgressText(partialResult) {
81703
81874
  }
81704
81875
  return "";
81705
81876
  }
81706
- function makeQueueExternalUserInput(context) {
81707
- return (controller, text) => {
81708
- if (!context.activeTurn() || context.activeTurn().finalized) {
81709
- const isNew = !context.claimExternalTurn.hasOpenFrame?.();
81710
- const claimed = context.claimExternalTurn();
81711
- if (isNew) {
81712
- writeEvent({
81713
- type: "turn.started",
81714
- sessionId: context.sessionId,
81715
- turnId: claimed.turnId,
81716
- source: "external"
81717
- });
81877
+
81878
+ // src/app/json-events-sidechat.ts
81879
+ function createJsonEventsSidechatService(ctx) {
81880
+ const completedSessionControlRequests = /* @__PURE__ */ new Map();
81881
+ const completedSidechatRequests = /* @__PURE__ */ new Map();
81882
+ const runtime = () => ctx.getRuntime();
81883
+ const agent = () => ctx.getAgent();
81884
+ const controller = () => ctx.getController();
81885
+ const trace = () => ctx.getTrace();
81886
+ const envelopeRegistry = () => ctx.getEnvelopeRegistry();
81887
+ const activeTurn = () => ctx.getActiveTurn();
81888
+ const sessionId = ctx.sessionId;
81889
+ function sessionMismatchError(requestedSessionId) {
81890
+ return `session mismatch: JSON events process is bound to ${sessionId}, received ${requestedSessionId}`;
81891
+ }
81892
+ function isSessionMismatch(message) {
81893
+ return typeof message.sessionId === "string" && message.sessionId !== sessionId;
81894
+ }
81895
+ function failureDetail(detail) {
81896
+ if (!detail) return { error: "turn failed" };
81897
+ if (typeof detail === "string") return { error: detail };
81898
+ return {
81899
+ error: detail.message,
81900
+ code: detail.code,
81901
+ recoverable: detail.recoverable,
81902
+ // Intake failures attach the supported envelope kinds so an embedder
81903
+ // can self-correct without probing.
81904
+ ...detail.hostContextKinds ? { hostContextKinds: detail.hostContextKinds } : {}
81905
+ };
81906
+ }
81907
+ function errorToFailureDetail(error) {
81908
+ if (error instanceof CliSessionResumeError || error instanceof SessionControlError) {
81909
+ const detail = error;
81910
+ return {
81911
+ message: detail.message,
81912
+ code: detail.code,
81913
+ recoverable: detail.recoverable
81914
+ };
81915
+ }
81916
+ return error instanceof Error ? error.message : String(error);
81917
+ }
81918
+ function sessionControlStore() {
81919
+ return new FileSessionStore(sessionControlSessionsDir());
81920
+ }
81921
+ function sessionControlSessionsDir() {
81922
+ return runtime()?.paths.sessionsDir ?? getSessionsDir();
81923
+ }
81924
+ function invalidSessionControl(message) {
81925
+ return new SessionControlError("invalid_request", message);
81926
+ }
81927
+ function requireSessionControlString(value, field) {
81928
+ const normalized = value?.trim();
81929
+ if (!normalized) {
81930
+ throw invalidSessionControl(`${field} is required`);
81931
+ }
81932
+ return normalized;
81933
+ }
81934
+ function requireSessionControlBase(message) {
81935
+ const requestedSessionId = requireSessionControlString(
81936
+ message.sessionId,
81937
+ "sessionId"
81938
+ );
81939
+ const requestId = requireSessionControlString(
81940
+ message.requestId,
81941
+ "requestId"
81942
+ );
81943
+ if (requestedSessionId !== sessionId) {
81944
+ throw new SessionControlError(
81945
+ "session_mismatch",
81946
+ sessionMismatchError(requestedSessionId),
81947
+ false
81948
+ );
81949
+ }
81950
+ if (activeTurn() && !activeTurn().finalized) {
81951
+ throw new SessionControlError(
81952
+ "session_busy",
81953
+ `Cannot ${message.type.slice("session.".length)} session while a turn is active`
81954
+ );
81955
+ }
81956
+ return { sessionId: requestedSessionId, requestId };
81957
+ }
81958
+ function resolveRewindEntryId(message) {
81959
+ const entryId = message.entryId?.trim();
81960
+ if (!entryId) {
81961
+ throw invalidSessionControl("entryId is required");
81962
+ }
81963
+ return entryId;
81964
+ }
81965
+ function writeSessionControlFailure(message, operation, error) {
81966
+ const detail = error instanceof SessionControlError ? error : new SessionControlError(
81967
+ "session_io_error",
81968
+ error instanceof Error ? error.message : String(error)
81969
+ );
81970
+ writeEvent({
81971
+ type: "session.failed",
81972
+ sessionId: message.sessionId || sessionId,
81973
+ requestId: message.requestId,
81974
+ operation,
81975
+ error: detail.message,
81976
+ code: detail.code,
81977
+ recoverable: detail.recoverable
81978
+ });
81979
+ }
81980
+ async function saveRuntimeSessionForControl() {
81981
+ const rt = runtime();
81982
+ if (!rt?.sessionManager.getActiveSession()) return;
81983
+ try {
81984
+ await rt.sessionManager.save();
81985
+ } catch (error) {
81986
+ throw new SessionControlError(
81987
+ "session_io_error",
81988
+ error instanceof Error ? error.message : String(error)
81989
+ );
81990
+ }
81991
+ }
81992
+ async function syncRuntimeAfterRewind(controlSessionId) {
81993
+ if (ctx.mockResponse !== void 0) return;
81994
+ const rt = runtime();
81995
+ if (rt?.sessionManager.getActiveSessionId() !== controlSessionId)
81996
+ return;
81997
+ if (!rt) return;
81998
+ const loaded = await rt.sessionManager.loadSession(controlSessionId, {
81999
+ warnIfMissing: false
82000
+ });
82001
+ if (!loaded) {
82002
+ const exists = await runtime()?.sessionManager.hasSession(
82003
+ controlSessionId
82004
+ );
82005
+ throw new SessionControlError(
82006
+ exists ? "session_unrecoverable" : "session_not_found",
82007
+ exists ? `Session could not be recovered: ${controlSessionId}` : `Session not found: ${controlSessionId}`,
82008
+ !exists
82009
+ );
82010
+ }
82011
+ controller()?.syncFromActiveSession();
82012
+ }
82013
+ async function handleSessionRewind(message) {
82014
+ try {
82015
+ const { sessionId: controlSessionId, requestId } = requireSessionControlBase(message);
82016
+ const cached = completedSessionControlRequests.get(requestId);
82017
+ if (cached) {
82018
+ writeEvent(cached);
82019
+ return;
81718
82020
  }
82021
+ const entryId = resolveRewindEntryId(message);
82022
+ await saveRuntimeSessionForControl();
82023
+ const result = await rewindStoredSession({
82024
+ store: sessionControlStore(),
82025
+ sessionId: controlSessionId,
82026
+ entryId
82027
+ });
82028
+ await syncRuntimeAfterRewind(controlSessionId);
82029
+ ctx.setMockActiveEntryId(result.activeEntryId);
82030
+ const event = {
82031
+ type: "session.rewound",
82032
+ sessionId: controlSessionId,
82033
+ requestId,
82034
+ entryId: result.entryId,
82035
+ activeEntryId: result.activeEntryId
82036
+ };
82037
+ completedSessionControlRequests.set(requestId, event);
82038
+ writeEvent(event);
82039
+ } catch (error) {
82040
+ writeSessionControlFailure(message, "rewind", error);
81719
82041
  }
81720
- void controller.prompt(
81721
- {
81722
- role: "user",
81723
- content: [{ type: "text", text }],
81724
- timestamp: Date.now()
81725
- },
81726
- {
81727
- source: "interactive",
81728
- streamingBehavior: "followUp",
81729
- displayText: text,
81730
- clearEditor: false,
81731
- deliverWhileStreaming: false
82042
+ }
82043
+ async function handleSessionFork(message) {
82044
+ try {
82045
+ const { sessionId: controlSessionId, requestId } = requireSessionControlBase(message);
82046
+ const sourceEntryId = requireSessionControlString(
82047
+ message.fromEntryId,
82048
+ "fromEntryId"
82049
+ );
82050
+ const targetSessionId = requireSessionControlString(
82051
+ message.targetSessionId,
82052
+ "targetSessionId"
82053
+ );
82054
+ const name = requireSessionControlString(message.name, "name");
82055
+ const forkCwd = message.cwd?.trim() || void 0;
82056
+ const cached = completedSessionControlRequests.get(requestId);
82057
+ if (cached) {
82058
+ writeEvent(cached);
82059
+ return;
82060
+ }
82061
+ await saveRuntimeSessionForControl();
82062
+ const result = await forkStoredSession({
82063
+ store: sessionControlStore(),
82064
+ sessionsDir: sessionControlSessionsDir(),
82065
+ sourceSessionId: controlSessionId,
82066
+ sourceEntryId,
82067
+ targetSessionId,
82068
+ name,
82069
+ cwd: forkCwd,
82070
+ requestId
82071
+ });
82072
+ const event = {
82073
+ type: "session.forked",
82074
+ sessionId: controlSessionId,
82075
+ requestId,
82076
+ sourceSessionId: result.sourceSessionId,
82077
+ sourceEntryId: result.sourceEntryId,
82078
+ targetSessionId: result.targetSessionId,
82079
+ targetActiveEntryId: result.targetActiveEntryId
82080
+ };
82081
+ completedSessionControlRequests.set(requestId, event);
82082
+ writeEvent(event);
82083
+ } catch (error) {
82084
+ writeSessionControlFailure(message, "fork", error);
82085
+ }
82086
+ }
82087
+ function writeSidechatFailure(message, error, code) {
82088
+ writeEvent({
82089
+ type: "sidechat.failed",
82090
+ sessionId,
82091
+ requestId: message.requestId.trim(),
82092
+ error,
82093
+ code
82094
+ });
82095
+ }
82096
+ async function handleSidechat(message) {
82097
+ if (isSessionMismatch(message)) {
82098
+ writeSidechatFailure(
82099
+ message,
82100
+ sessionMismatchError(message.sessionId),
82101
+ "session_mismatch"
82102
+ );
82103
+ return;
82104
+ }
82105
+ const requestId = message.requestId.trim();
82106
+ if (!requestId) {
82107
+ writeSidechatFailure(message, "requestId is required", "invalid_request");
82108
+ return;
82109
+ }
82110
+ const cached = completedSidechatRequests.get(requestId);
82111
+ if (cached) {
82112
+ writeEvent(cached);
82113
+ return;
82114
+ }
82115
+ if (activeTurn() && !activeTurn().finalized) {
82116
+ writeSidechatFailure(
82117
+ message,
82118
+ "Cannot run sidechat while a turn is active",
82119
+ "session_busy"
82120
+ );
82121
+ return;
82122
+ }
82123
+ const startedAt = Date.now();
82124
+ if (ctx.mockResponse !== void 0) {
82125
+ const hostContextFailure = ctx.validateIntakeHostContext(message);
82126
+ if (hostContextFailure) {
82127
+ writeSidechatFailure(
82128
+ message,
82129
+ hostContextFailure.message,
82130
+ hostContextFailure.code
82131
+ );
82132
+ return;
82133
+ }
82134
+ writeEvent({ type: "sidechat.started", sessionId, requestId });
82135
+ const event = {
82136
+ type: "sidechat.completed",
82137
+ sessionId,
82138
+ requestId,
82139
+ text: ctx.mockResponse,
82140
+ durationMs: Date.now() - startedAt
82141
+ };
82142
+ completedSidechatRequests.set(requestId, event);
82143
+ writeEvent(event);
82144
+ return;
82145
+ }
82146
+ writeEvent({ type: "sidechat.started", sessionId, requestId });
82147
+ const sidechatController = new AbortController();
82148
+ let abortKind;
82149
+ ctx.setActiveSidechat({
82150
+ abort: () => {
82151
+ if (!abortKind) abortKind = "interrupted";
82152
+ sidechatController.abort();
81732
82153
  }
81733
- ).then(void 0, () => {
81734
82154
  });
82155
+ try {
82156
+ await ctx.ensureRuntime(runtime()?.cwd);
82157
+ const hostContextFailure = ctx.validateIntakeHostContext(message);
82158
+ if (hostContextFailure) {
82159
+ writeSidechatFailure(
82160
+ message,
82161
+ hostContextFailure.message,
82162
+ hostContextFailure.code
82163
+ );
82164
+ return;
82165
+ }
82166
+ const rt = runtime();
82167
+ if (!agent() || !rt) {
82168
+ throw new Error("JSON events runtime was not initialized");
82169
+ }
82170
+ if (rt?.initialModel.unconfigured) {
82171
+ writeSidechatFailure(
82172
+ message,
82173
+ rt.initialModel.warning || "No models are configured."
82174
+ );
82175
+ return;
82176
+ }
82177
+ if (sidechatController.signal.aborted) {
82178
+ writeSidechatFailure(
82179
+ message,
82180
+ "sidechat aborted before dispatch",
82181
+ "sidechat_interrupted"
82182
+ );
82183
+ return;
82184
+ }
82185
+ const parent = agent();
82186
+ const sideRegistry = envelopeRegistry();
82187
+ const sideTrace = trace();
82188
+ const sideApiKey = rt.apiKey;
82189
+ const snapshot = structuredClone(parent.state.messages);
82190
+ const { Agent: AgentClass } = await import("./chunks/src-2XI5P62J.js");
82191
+ const sideAgent = new AgentClass({
82192
+ initialState: {
82193
+ systemPrompt: parent.state.systemPrompt,
82194
+ model: parent.state.model,
82195
+ thinkingLevel: parent.state.thinkingLevel,
82196
+ tools: [],
82197
+ messages: snapshot
82198
+ },
82199
+ apiKey: sideApiKey,
82200
+ // The sidechat snapshot clones the parent's stored history, including
82201
+ // persisted hostContext facts; project them like the main agent does.
82202
+ transformContext: async (messages) => projectCliHostEnvelopes(
82203
+ messages,
82204
+ (outcome) => sideTrace?.noteRuntimeEvent(
82205
+ outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
82206
+ outcome.audit
82207
+ ),
82208
+ sideRegistry
82209
+ ),
82210
+ // Same body-free transport timeline as the main agent: a sidechat is
82211
+ // an independent Responses request and previously had no record at all
82212
+ // when it stalled. `streamSimple` matches the host default when the
82213
+ // caller injected no stream function.
82214
+ streamFn: ctx.transportStreamFn
82215
+ });
82216
+ sidechatController.signal.addEventListener(
82217
+ "abort",
82218
+ () => sideAgent.abort(),
82219
+ { once: true }
82220
+ );
82221
+ const timer = setTimeout(() => {
82222
+ if (!abortKind) abortKind = "timeout";
82223
+ sidechatController.abort();
82224
+ }, ctx.sidechatTimeoutMs);
82225
+ timer.unref?.();
82226
+ try {
82227
+ await sideAgent.prompt(ctx.sidechatPromptBlocks(message));
82228
+ } finally {
82229
+ clearTimeout(timer);
82230
+ }
82231
+ if (abortKind) {
82232
+ const code = abortKind === "timeout" ? "sidechat_timeout" : "sidechat_interrupted";
82233
+ writeSidechatFailure(
82234
+ message,
82235
+ sideAgent.state.error || "sidechat aborted",
82236
+ code
82237
+ );
82238
+ return;
82239
+ }
82240
+ const failure = sideAgent.state.error;
82241
+ if (failure) {
82242
+ writeSidechatFailure(message, failure);
82243
+ return;
82244
+ }
82245
+ const sidechatText = assistantTextFromAgent(sideAgent);
82246
+ const capped = sidechatText === void 0 ? void 0 : truncateForEvent(sidechatText, ctx.eventStringCap);
82247
+ const event = {
82248
+ type: "sidechat.completed",
82249
+ sessionId,
82250
+ requestId,
82251
+ text: capped?.value,
82252
+ ...capped?.truncated ? { truncated: true, fullLength: capped.fullLength } : {},
82253
+ usage: assistantUsageFromAgent(sideAgent),
82254
+ durationMs: Date.now() - startedAt
82255
+ };
82256
+ completedSidechatRequests.set(requestId, event);
82257
+ writeEvent(event);
82258
+ } catch (error) {
82259
+ const detail = errorToFailureDetail(error);
82260
+ writeSidechatFailure(
82261
+ message,
82262
+ typeof detail === "string" ? detail : detail.message,
82263
+ typeof detail === "string" ? void 0 : detail.code
82264
+ );
82265
+ } finally {
82266
+ ctx.setActiveSidechat(null);
82267
+ }
82268
+ }
82269
+ return {
82270
+ handleSessionRewind,
82271
+ handleSessionFork,
82272
+ handleSidechat,
82273
+ getCachedSidechatResult: (requestId) => completedSidechatRequests.get(requestId),
82274
+ sessionMismatchError,
82275
+ isSessionMismatch,
82276
+ errorToFailureDetail,
82277
+ failureDetail
81735
82278
  };
81736
82279
  }
81737
- function isJournalOnlyControlAudit(customType, data) {
81738
- if (customType !== "pie.ipc.control") return false;
81739
- const control = data?.control;
81740
- return control === "session.context" || control === "session.compact";
82280
+
82281
+ // src/app/host-idle.ts
82282
+ var PENDING_RECOVERY = /* @__PURE__ */ new Set([
82283
+ "retry_pending",
82284
+ "retrying",
82285
+ "compacting"
82286
+ ]);
82287
+ function hostIsIdle(controller) {
82288
+ if (!controller) return true;
82289
+ if (controller.isStreaming || controller.hasQueuedMessages) return false;
82290
+ return !PENDING_RECOVERY.has(controller.turnRecoveryState);
81741
82291
  }
82292
+
82293
+ // src/runtime/headless-session-commands.ts
82294
+ function buildHeadlessContextReport(params) {
82295
+ const usage2 = calculateCliContextUsage({
82296
+ messages: params.messages,
82297
+ latestCompactionTimestamp: params.latestCompactionTimestamp ?? null
82298
+ });
82299
+ const limit = params.contextWindow && params.contextWindow > 0 ? autoCompactLimit(params.contextWindow, params.reserveTokens) : null;
82300
+ return {
82301
+ estimatedTokens: usage2.tokens,
82302
+ contextWindow: params.contextWindow ?? 0,
82303
+ percent: usage2.tokens !== null && params.contextWindow && params.contextWindow > 0 ? Math.round(usage2.tokens / params.contextWindow * 1e3) / 10 : null,
82304
+ providerMeasuredTokens: usage2.providerMeasuredTokens,
82305
+ providerMeasuredAt: usage2.providerMeasuredAt,
82306
+ measurementMatchesCurrentContext: usage2.measurementMatchesCurrentContext,
82307
+ autoCompactEnabled: params.autoCompactEnabled,
82308
+ autoCompactLimitTokens: limit,
82309
+ pendingQueuedInputs: params.controller.pendingMessageCount,
82310
+ isStreaming: params.controller.isStreaming,
82311
+ basis: "estimate",
82312
+ generatedAt: Date.now()
82313
+ };
82314
+ }
82315
+ function autoCompactLimit(contextWindow, reserveTokens) {
82316
+ const limit = getAutoCompactTokenLimit(contextWindow, reserveTokens ?? 0);
82317
+ return typeof limit === "number" ? limit : null;
82318
+ }
82319
+ async function runHeadlessManualCompact(params) {
82320
+ const { controller } = params;
82321
+ if (manualCompactInFlight.has(controller)) {
82322
+ return { status: "refused", reason: "a manual compaction is already running; wait for it to finish" };
82323
+ }
82324
+ const gate = () => {
82325
+ if (controller.isStreaming) return "a turn is streaming; retry when idle";
82326
+ if (controller.hasQueuedMessages) return `${controller.pendingMessageCount} input(s) still queued; retry when idle`;
82327
+ return void 0;
82328
+ };
82329
+ const firstGate = gate();
82330
+ if (firstGate) return { status: "refused", reason: firstGate };
82331
+ const sessionId = controller.sessionManager.getActiveSession()?.id ?? "";
82332
+ const messageCount = controller.agent.state.messages.length;
82333
+ if (messageCount === 0) {
82334
+ return { status: "refused", reason: "nothing to compact yet" };
82335
+ }
82336
+ const before = await params.emitBeforeCompact({ reason: "manual", messageCount });
82337
+ if (before?.cancel) {
82338
+ return { status: "refused", reason: "cancelled by an extension (session:before_compact)" };
82339
+ }
82340
+ const afterSession = controller.sessionManager.getActiveSession()?.id ?? "";
82341
+ if (afterSession !== sessionId) {
82342
+ return { status: "refused", reason: "session changed during the pre-compact hook; nothing started" };
82343
+ }
82344
+ const secondGate = gate();
82345
+ if (secondGate) return { status: "refused", reason: secondGate };
82346
+ if (manualCompactInFlight.has(controller)) {
82347
+ return { status: "refused", reason: "a manual compaction is already running; wait for it to finish" };
82348
+ }
82349
+ manualCompactInFlight.add(controller);
82350
+ void (async () => {
82351
+ let outcome;
82352
+ try {
82353
+ const result = await controller.runAutoCompact("manual", false);
82354
+ outcome = {
82355
+ ok: !result?.aborted,
82356
+ detail: result?.aborted ? "compaction aborted (extension cancel or session change)" : `compaction committed (tokensBefore=${result?.tokensBefore ?? "?"}, savings=${result?.tokenSavings ?? "?"})`
82357
+ };
82358
+ } catch (error) {
82359
+ outcome = {
82360
+ ok: false,
82361
+ detail: `compaction failed: ${error instanceof Error ? error.message : String(error)}`
82362
+ };
82363
+ } finally {
82364
+ manualCompactInFlight.delete(controller);
82365
+ }
82366
+ params.onSettled?.(outcome);
82367
+ })();
82368
+ return { status: "accepted", sessionId };
82369
+ }
82370
+ var manualCompactInFlight = /* @__PURE__ */ new WeakSet();
82371
+ function isManualCompactionInFlight(controller) {
82372
+ return manualCompactInFlight.has(controller);
82373
+ }
82374
+
82375
+ // src/app/json-events-extensions.ts
82376
+ import * as os9 from "node:os";
81742
82377
  async function loadJsonModeExtensions(params) {
81743
82378
  const uiContext = createNoOpExtensionUIContext2();
81744
82379
  const executionState = new ExecutionStateManager();
@@ -81909,6 +82544,23 @@ async function loadJsonModeExtensions(params) {
81909
82544
  const modelId = params.runtime.modelId;
81910
82545
  return provider && modelId ? `${provider}/${modelId}` : void 0;
81911
82546
  },
82547
+ getThinkingLevel: () => params.getAgent()?.state.thinkingLevel ?? resolveInitialThinkingLevel({
82548
+ session: params.runtime.sessionManager.getActiveSession(),
82549
+ settingsManager: params.runtime.settingsManager
82550
+ }),
82551
+ getThinkingStatus: () => {
82552
+ const requested = params.getAgent()?.state.thinkingLevel ?? resolveInitialThinkingLevel({
82553
+ session: params.runtime.sessionManager.getActiveSession(),
82554
+ settingsManager: params.runtime.settingsManager
82555
+ });
82556
+ const resolved = resolveThinkingSelection(params.runtime.model, requested);
82557
+ return {
82558
+ requested: resolved.requested,
82559
+ effective: resolved.effective,
82560
+ supportedLevels: resolved.supportedLevels,
82561
+ configurable: resolved.configurable
82562
+ };
82563
+ },
81912
82564
  getSessionMetadata: () => ({
81913
82565
  ...params.runtime.sessionManager.getActiveSession()?.metadata ?? {}
81914
82566
  }),
@@ -81967,27 +82619,30 @@ async function loadJsonModeExtensions(params) {
81967
82619
  params.runtime.provider = provider;
81968
82620
  params.runtime.modelId = modelId;
81969
82621
  params.runtime.apiKey = apiKey;
81970
- return { ok: true, message: `model set to ${ref}` };
82622
+ const resolved = resolveThinkingSelection(model, liveAgent.state.thinkingLevel);
82623
+ const effNote = resolved.clamped && resolved.effective !== resolved.requested ? ` (thinking: ${resolved.effective}, requested ${resolved.requested})` : "";
82624
+ return { ok: true, message: `model set to ${ref}${effNote}` };
81971
82625
  } catch (error) {
81972
82626
  return { ok: false, message: error instanceof Error ? error.message : String(error) };
81973
82627
  }
81974
82628
  }
81975
82629
  if (control === "thinking.set") {
81976
82630
  const level = payload && typeof payload === "object" && "level" in payload ? String(payload.level) : void 0;
81977
- const valid = ["off", "minimal", "low", "medium", "high", "xhigh"];
81978
- if (!level || !valid.includes(level))
81979
- return { ok: false, message: `thinking.set requires payload.level as one of ${valid.join("|")}` };
82631
+ if (!level) return { ok: false, message: "thinking.set requires payload.level" };
81980
82632
  const liveAgent = params.getAgent();
81981
82633
  if (!liveAgent) return { ok: false, message: "runtime not composed" };
82634
+ const validation = validateExplicitThinkingSelection(params.runtime.model, level);
82635
+ if (!validation.ok) return { ok: false, message: validation.error };
81982
82636
  applyThinkingLevel({
81983
- level,
82637
+ level: validation.level,
81984
82638
  agent: liveAgent,
81985
82639
  settingsManager: params.runtime.settingsManager,
81986
82640
  sessionManager: params.runtime.sessionManager,
81987
82641
  model: params.runtime.model,
81988
82642
  persist: false
81989
82643
  });
81990
- return { ok: true, message: `thinking level set to ${level} (applies from the next agent execution)` };
82644
+ const effNote = validation.resolved.clamped && validation.resolved.effective !== validation.level ? ` (effective: ${validation.resolved.effective})` : "";
82645
+ return { ok: true, message: `thinking level set to ${validation.level}${effNote} (applies from the next agent execution)` };
81991
82646
  }
81992
82647
  if (control === "session.context") {
81993
82648
  const controller = params.getController();
@@ -82044,6 +82699,21 @@ async function loadJsonModeExtensions(params) {
82044
82699
  if (receipt.status === "refused") return { ok: false, message: receipt.reason };
82045
82700
  return { ok: true, message: `manual compaction submitted for ${receipt.sessionId || "session"}; the outcome is observable via session.context (lastCompactOutcome) \u2014 a controller-side refusal (busy/transitioning) also lands there` };
82046
82701
  }
82702
+ if (control === "turn.abort") {
82703
+ if (!params.abortActiveTurn) return { ok: false, message: "host does not support remote turn abort" };
82704
+ const aborted = params.abortActiveTurn();
82705
+ return { ok: true, message: aborted ? "active turn interrupted" : "already idle (no active turn)" };
82706
+ }
82707
+ if (control === "session.shutdown") {
82708
+ if (process.env.PIE_PROC_CURATED_NAME === "manager") {
82709
+ return { ok: false, message: "manager host cannot be shut down via remote panel control" };
82710
+ }
82711
+ if (!params.idle || !params.requestShutdown) {
82712
+ return { ok: false, message: "host does not support remote shutdown" };
82713
+ }
82714
+ const scheduled = params.requestShutdown("ipc_control");
82715
+ return scheduled ? { ok: true, message: "graceful shutdown scheduled" } : { ok: false, message: "shutdown unavailable or already in progress" };
82716
+ }
82047
82717
  return { ok: false, message: `unknown control: ${control}` };
82048
82718
  },
82049
82719
  yoloMode: false
@@ -82138,6 +82808,68 @@ async function loadJsonModeExtensions(params) {
82138
82808
  throw error;
82139
82809
  }
82140
82810
  }
82811
+ function isJournalOnlyControlAudit(customType, data) {
82812
+ if (customType !== "pie.ipc.control") return false;
82813
+ const control = data?.control;
82814
+ return control === "session.context" || control === "session.compact" || control === "turn.abort" || control === "session.shutdown";
82815
+ }
82816
+ async function describeImageViaUnderstanding(params, filePath, displayName) {
82817
+ try {
82818
+ const { understandReadFile: understandReadFile2 } = await import("./chunks/read-file-understanding-VPKDBV23.js");
82819
+ const ext = filePath.toLowerCase().split(".").pop() ?? "";
82820
+ const mime = ext === "png" ? "image/png" : ext === "gif" ? "image/gif" : ext === "webp" ? "image/webp" : "image/jpeg";
82821
+ const agentModel = params.getAgent?.()?.state?.model;
82822
+ const result = await understandReadFile2(
82823
+ {
82824
+ configDir: process.env.PIE_CODING_AGENT_DIR || `${os9.homedir()}/.pie`,
82825
+ cwd: process.cwd(),
82826
+ getAgentModel: () => agentModel,
82827
+ getSessionId: () => void 0,
82828
+ resolveToolModel: (purpose, current) => params.runtime.modelRegistry.resolveToolModel(purpose, current),
82829
+ resolveToolModelCandidates: (purpose, current) => params.runtime.modelRegistry.resolveToolModelCandidates(purpose, current)
82830
+ },
82831
+ { absolutePath: filePath, displayPath: displayName, mimeType: mime, kind: "image" }
82832
+ );
82833
+ if (result.isError) return void 0;
82834
+ const text = result.content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim();
82835
+ return text || void 0;
82836
+ } catch {
82837
+ return void 0;
82838
+ }
82839
+ }
82840
+
82841
+ // src/app/json-events-mode.ts
82842
+ function makeQueueExternalUserInput(context) {
82843
+ return (controller, text) => {
82844
+ if (!context.activeTurn() || context.activeTurn().finalized) {
82845
+ const isNew = !context.claimExternalTurn.hasOpenFrame?.();
82846
+ const claimed = context.claimExternalTurn();
82847
+ if (isNew) {
82848
+ writeEvent({
82849
+ type: "turn.started",
82850
+ sessionId: context.sessionId,
82851
+ turnId: claimed.turnId,
82852
+ source: "external"
82853
+ });
82854
+ }
82855
+ }
82856
+ void controller.prompt(
82857
+ {
82858
+ role: "user",
82859
+ content: [{ type: "text", text }],
82860
+ timestamp: Date.now()
82861
+ },
82862
+ {
82863
+ source: "interactive",
82864
+ streamingBehavior: "followUp",
82865
+ displayText: text,
82866
+ clearEditor: false,
82867
+ deliverWhileStreaming: false
82868
+ }
82869
+ ).then(void 0, () => {
82870
+ });
82871
+ };
82872
+ }
82141
82873
  function createJsonEventsTransportStreamFn(streamFn) {
82142
82874
  return createTransportDiagnosticsStreamFn(streamFn ?? streamSimple, logTransportLifecycle);
82143
82875
  }
@@ -82146,8 +82878,15 @@ async function runJsonEventsMode(params) {
82146
82878
  const eventStringCap = eventDetail === FULL_DETAIL ? MAX_EVENT_STRING_LENGTH : COMPACT_EVENT_STRING_LENGTH;
82147
82879
  const sessionId = params.explicitSessionId || params.runtime?.sessionManager.getActiveSession()?.id || `pie-json-${Date.now()}`;
82148
82880
  let activeTurn = null;
82881
+ let fatalStartupHandled = false;
82149
82882
  let runtime = params.runtime;
82150
82883
  let envelopeRegistry = createCliHostEnvelopeRegistry();
82884
+ function sidechatPromptBlocks(message) {
82885
+ return message.hostContext ? [message.hostContext, { type: "text", text: message.prompt }] : [{ type: "text", text: message.prompt }];
82886
+ }
82887
+ function validateIntakeHostContext(message) {
82888
+ return message.hostContext !== void 0 ? intakeHostContextFailure(message.hostContext, envelopeRegistry) : void 0;
82889
+ }
82151
82890
  let agent;
82152
82891
  let controller;
82153
82892
  let disposeAgentSubscription;
@@ -82173,11 +82912,10 @@ async function runJsonEventsMode(params) {
82173
82912
  let mockActiveEntryId;
82174
82913
  let thinkingLevel = DEFAULT_THINKING_LEVEL;
82175
82914
  let thinkingLevelInitialized = false;
82915
+ let thinkingLevelEphemeral = Boolean(params.explicitThinkingLevel);
82176
82916
  let defaultRuntime;
82177
82917
  let defaultModelState;
82178
82918
  let publishRecoveryDone = false;
82179
- const completedSessionControlRequests = /* @__PURE__ */ new Map();
82180
- const completedSidechatRequests = /* @__PURE__ */ new Map();
82181
82919
  let externalTurn = null;
82182
82920
  let externalTurnSeq = 0;
82183
82921
  const claimExternalTurn = Object.assign(
@@ -82203,6 +82941,8 @@ async function runJsonEventsMode(params) {
82203
82941
  const ensureRuntimeInFlight = /* @__PURE__ */ new Map();
82204
82942
  let compositionChain = Promise.resolve();
82205
82943
  let runtimeClosing = false;
82944
+ let ipcShutdownRequested = false;
82945
+ let triggerResidentShutdown;
82206
82946
  let compositionGeneration = 0;
82207
82947
  let activeSidechat = null;
82208
82948
  let activeSidechatPromise = null;
@@ -82219,6 +82959,37 @@ async function runJsonEventsMode(params) {
82219
82959
  const sidechatTimeoutMs = Number(
82220
82960
  process.env.PIE_JSON_EVENTS_SIDECHAT_TIMEOUT_MS || 3e5
82221
82961
  );
82962
+ function writeSidechatFailureLocal(message, error, code) {
82963
+ writeEvent({
82964
+ type: "sidechat.failed",
82965
+ sessionId,
82966
+ requestId: message.requestId.trim(),
82967
+ error,
82968
+ code
82969
+ });
82970
+ }
82971
+ const sidechatService = createJsonEventsSidechatService({
82972
+ sessionId,
82973
+ eventStringCap,
82974
+ sidechatTimeoutMs,
82975
+ ...params.mockResponse !== void 0 ? { mockResponse: params.mockResponse } : {},
82976
+ transportStreamFn: createJsonEventsTransportStreamFn(params.streamFn),
82977
+ getRuntime: () => runtime,
82978
+ getAgent: () => agent,
82979
+ getController: () => controller,
82980
+ getEnvelopeRegistry: () => envelopeRegistry,
82981
+ getTrace: () => trace,
82982
+ getActiveTurn: () => activeTurn,
82983
+ setMockActiveEntryId: (id) => {
82984
+ mockActiveEntryId = id;
82985
+ },
82986
+ ensureRuntime: (requestedCwd) => ensureRuntime(requestedCwd),
82987
+ validateIntakeHostContext,
82988
+ sidechatPromptBlocks,
82989
+ setActiveSidechat: (handle) => {
82990
+ activeSidechat = handle;
82991
+ }
82992
+ });
82222
82993
  await prewarmRuntime();
82223
82994
  writeEvent({
82224
82995
  type: "agent.ready",
@@ -82234,12 +83005,6 @@ async function runJsonEventsMode(params) {
82234
83005
  if (activeSidechatPromise === promise) activeSidechatPromise = null;
82235
83006
  });
82236
83007
  }
82237
- function sessionMismatchError(requestedSessionId) {
82238
- return `session mismatch: JSON events process is bound to ${sessionId}, received ${requestedSessionId}`;
82239
- }
82240
- function isSessionMismatch(message) {
82241
- return typeof message.sessionId === "string" && message.sessionId !== sessionId;
82242
- }
82243
83008
  function delay(ms) {
82244
83009
  return new Promise((resolve7) => setTimeout(resolve7, Math.max(0, ms)));
82245
83010
  }
@@ -82393,373 +83158,6 @@ async function runJsonEventsMode(params) {
82393
83158
  display(chunk);
82394
83159
  }
82395
83160
  }
82396
- function failureDetail(detail) {
82397
- if (!detail) return { error: "turn failed" };
82398
- if (typeof detail === "string") return { error: detail };
82399
- return {
82400
- error: detail.message,
82401
- code: detail.code,
82402
- recoverable: detail.recoverable,
82403
- // Intake failures attach the supported envelope kinds so an embedder
82404
- // can self-correct without probing.
82405
- ...detail.hostContextKinds ? { hostContextKinds: detail.hostContextKinds } : {}
82406
- };
82407
- }
82408
- function errorToFailureDetail(error) {
82409
- if (error instanceof CliSessionResumeError || error instanceof SessionControlError) {
82410
- return {
82411
- message: error.message,
82412
- code: error.code,
82413
- recoverable: error.recoverable
82414
- };
82415
- }
82416
- return error instanceof Error ? error.message : String(error);
82417
- }
82418
- function sessionControlStore() {
82419
- return new FileSessionStore(sessionControlSessionsDir());
82420
- }
82421
- function sessionControlSessionsDir() {
82422
- return runtime?.paths.sessionsDir ?? getSessionsDir();
82423
- }
82424
- function invalidSessionControl(message) {
82425
- return new SessionControlError("invalid_request", message);
82426
- }
82427
- function requireSessionControlString(value, field) {
82428
- const normalized = value?.trim();
82429
- if (!normalized) {
82430
- throw invalidSessionControl(`${field} is required`);
82431
- }
82432
- return normalized;
82433
- }
82434
- function requireSessionControlBase(message) {
82435
- const requestedSessionId = requireSessionControlString(
82436
- message.sessionId,
82437
- "sessionId"
82438
- );
82439
- const requestId = requireSessionControlString(
82440
- message.requestId,
82441
- "requestId"
82442
- );
82443
- if (requestedSessionId !== sessionId) {
82444
- throw new SessionControlError(
82445
- "session_mismatch",
82446
- sessionMismatchError(requestedSessionId),
82447
- false
82448
- );
82449
- }
82450
- if (activeTurn && !activeTurn.finalized) {
82451
- throw new SessionControlError(
82452
- "session_busy",
82453
- `Cannot ${message.type.slice("session.".length)} session while a turn is active`
82454
- );
82455
- }
82456
- return { sessionId: requestedSessionId, requestId };
82457
- }
82458
- function resolveRewindEntryId(message) {
82459
- const entryId = message.entryId?.trim();
82460
- if (!entryId) {
82461
- throw invalidSessionControl("entryId is required");
82462
- }
82463
- return entryId;
82464
- }
82465
- function writeSessionControlFailure(message, operation, error) {
82466
- const detail = error instanceof SessionControlError ? error : new SessionControlError(
82467
- "session_io_error",
82468
- error instanceof Error ? error.message : String(error)
82469
- );
82470
- writeEvent({
82471
- type: "session.failed",
82472
- sessionId: message.sessionId || sessionId,
82473
- requestId: message.requestId,
82474
- operation,
82475
- error: detail.message,
82476
- code: detail.code,
82477
- recoverable: detail.recoverable
82478
- });
82479
- }
82480
- async function saveRuntimeSessionForControl() {
82481
- if (!runtime?.sessionManager.getActiveSession()) return;
82482
- try {
82483
- await runtime.sessionManager.save();
82484
- } catch (error) {
82485
- throw new SessionControlError(
82486
- "session_io_error",
82487
- error instanceof Error ? error.message : String(error)
82488
- );
82489
- }
82490
- }
82491
- async function syncRuntimeAfterRewind(controlSessionId) {
82492
- if (params.mockResponse !== void 0) return;
82493
- if (runtime?.sessionManager.getActiveSessionId() !== controlSessionId)
82494
- return;
82495
- const loaded = await runtime.sessionManager.loadSession(controlSessionId, {
82496
- warnIfMissing: false
82497
- });
82498
- if (!loaded) {
82499
- const exists = await runtime.sessionManager.hasSession(controlSessionId);
82500
- throw new SessionControlError(
82501
- exists ? "session_unrecoverable" : "session_not_found",
82502
- exists ? `Session could not be recovered: ${controlSessionId}` : `Session not found: ${controlSessionId}`,
82503
- !exists
82504
- );
82505
- }
82506
- controller?.syncFromActiveSession();
82507
- }
82508
- async function handleSessionRewind(message) {
82509
- try {
82510
- const { sessionId: controlSessionId, requestId } = requireSessionControlBase(message);
82511
- const cached = completedSessionControlRequests.get(requestId);
82512
- if (cached) {
82513
- writeEvent(cached);
82514
- return;
82515
- }
82516
- const entryId = resolveRewindEntryId(message);
82517
- await saveRuntimeSessionForControl();
82518
- const result = await rewindStoredSession({
82519
- store: sessionControlStore(),
82520
- sessionId: controlSessionId,
82521
- entryId
82522
- });
82523
- await syncRuntimeAfterRewind(controlSessionId);
82524
- mockActiveEntryId = result.activeEntryId;
82525
- const event = {
82526
- type: "session.rewound",
82527
- sessionId: controlSessionId,
82528
- requestId,
82529
- entryId: result.entryId,
82530
- activeEntryId: result.activeEntryId
82531
- };
82532
- completedSessionControlRequests.set(requestId, event);
82533
- writeEvent(event);
82534
- } catch (error) {
82535
- writeSessionControlFailure(message, "rewind", error);
82536
- }
82537
- }
82538
- async function handleSessionFork(message) {
82539
- try {
82540
- const { sessionId: controlSessionId, requestId } = requireSessionControlBase(message);
82541
- const sourceEntryId = requireSessionControlString(
82542
- message.fromEntryId,
82543
- "fromEntryId"
82544
- );
82545
- const targetSessionId = requireSessionControlString(
82546
- message.targetSessionId,
82547
- "targetSessionId"
82548
- );
82549
- const name = requireSessionControlString(message.name, "name");
82550
- const forkCwd = message.cwd?.trim() || void 0;
82551
- const cached = completedSessionControlRequests.get(requestId);
82552
- if (cached) {
82553
- writeEvent(cached);
82554
- return;
82555
- }
82556
- await saveRuntimeSessionForControl();
82557
- const result = await forkStoredSession({
82558
- store: sessionControlStore(),
82559
- sessionsDir: sessionControlSessionsDir(),
82560
- sourceSessionId: controlSessionId,
82561
- sourceEntryId,
82562
- targetSessionId,
82563
- name,
82564
- cwd: forkCwd,
82565
- requestId
82566
- });
82567
- const event = {
82568
- type: "session.forked",
82569
- sessionId: controlSessionId,
82570
- requestId,
82571
- sourceSessionId: result.sourceSessionId,
82572
- sourceEntryId: result.sourceEntryId,
82573
- targetSessionId: result.targetSessionId,
82574
- targetActiveEntryId: result.targetActiveEntryId
82575
- };
82576
- completedSessionControlRequests.set(requestId, event);
82577
- writeEvent(event);
82578
- } catch (error) {
82579
- writeSessionControlFailure(message, "fork", error);
82580
- }
82581
- }
82582
- function writeSidechatFailure(message, error, code) {
82583
- writeEvent({
82584
- type: "sidechat.failed",
82585
- sessionId,
82586
- requestId: message.requestId.trim(),
82587
- error,
82588
- code
82589
- });
82590
- }
82591
- async function handleSidechat(message) {
82592
- if (isSessionMismatch(message)) {
82593
- writeSidechatFailure(
82594
- message,
82595
- sessionMismatchError(message.sessionId),
82596
- "session_mismatch"
82597
- );
82598
- return;
82599
- }
82600
- const requestId = message.requestId.trim();
82601
- if (!requestId) {
82602
- writeSidechatFailure(message, "requestId is required", "invalid_request");
82603
- return;
82604
- }
82605
- const cached = completedSidechatRequests.get(requestId);
82606
- if (cached) {
82607
- writeEvent(cached);
82608
- return;
82609
- }
82610
- if (activeTurn && !activeTurn.finalized) {
82611
- writeSidechatFailure(
82612
- message,
82613
- "Cannot run sidechat while a turn is active",
82614
- "session_busy"
82615
- );
82616
- return;
82617
- }
82618
- const startedAt = Date.now();
82619
- if (params.mockResponse !== void 0) {
82620
- const hostContextFailure = validateIntakeHostContext(message);
82621
- if (hostContextFailure) {
82622
- writeSidechatFailure(
82623
- message,
82624
- hostContextFailure.message,
82625
- hostContextFailure.code
82626
- );
82627
- return;
82628
- }
82629
- writeEvent({ type: "sidechat.started", sessionId, requestId });
82630
- const event = {
82631
- type: "sidechat.completed",
82632
- sessionId,
82633
- requestId,
82634
- text: params.mockResponse,
82635
- durationMs: Date.now() - startedAt
82636
- };
82637
- completedSidechatRequests.set(requestId, event);
82638
- writeEvent(event);
82639
- return;
82640
- }
82641
- writeEvent({ type: "sidechat.started", sessionId, requestId });
82642
- const sidechatController = new AbortController();
82643
- let abortKind;
82644
- activeSidechat = {
82645
- abort: () => {
82646
- if (!abortKind) abortKind = "interrupted";
82647
- sidechatController.abort();
82648
- }
82649
- };
82650
- try {
82651
- await ensureRuntime(runtime?.cwd);
82652
- const hostContextFailure = validateIntakeHostContext(message);
82653
- if (hostContextFailure) {
82654
- writeSidechatFailure(
82655
- message,
82656
- hostContextFailure.message,
82657
- hostContextFailure.code
82658
- );
82659
- return;
82660
- }
82661
- if (!agent || !runtime) {
82662
- throw new Error("JSON events runtime was not initialized");
82663
- }
82664
- if (runtime.initialModel.unconfigured) {
82665
- writeSidechatFailure(
82666
- message,
82667
- runtime.initialModel.warning || "No models are configured."
82668
- );
82669
- return;
82670
- }
82671
- if (sidechatController.signal.aborted) {
82672
- writeSidechatFailure(
82673
- message,
82674
- "sidechat aborted before dispatch",
82675
- "sidechat_interrupted"
82676
- );
82677
- return;
82678
- }
82679
- const parent = agent;
82680
- const sideRegistry = envelopeRegistry;
82681
- const sideTrace = trace;
82682
- const sideApiKey = runtime.apiKey;
82683
- const snapshot = structuredClone(parent.state.messages);
82684
- const { Agent: AgentClass } = await import("./chunks/src-B44QWSGM.js");
82685
- const sideAgent = new AgentClass({
82686
- initialState: {
82687
- systemPrompt: parent.state.systemPrompt,
82688
- model: parent.state.model,
82689
- thinkingLevel: parent.state.thinkingLevel,
82690
- tools: [],
82691
- messages: snapshot
82692
- },
82693
- apiKey: sideApiKey,
82694
- // The sidechat snapshot clones the parent's stored history, including
82695
- // persisted hostContext facts; project them like the main agent does.
82696
- transformContext: async (messages) => projectCliHostEnvelopes(
82697
- messages,
82698
- (outcome) => sideTrace?.noteRuntimeEvent(
82699
- outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
82700
- outcome.audit
82701
- ),
82702
- sideRegistry
82703
- ),
82704
- // Same body-free transport timeline as the main agent: a sidechat is
82705
- // an independent Responses request and previously had no record at all
82706
- // when it stalled. `streamSimple` matches the host default when the
82707
- // caller injected no stream function.
82708
- streamFn: createJsonEventsTransportStreamFn(params.streamFn)
82709
- });
82710
- sidechatController.signal.addEventListener(
82711
- "abort",
82712
- () => sideAgent.abort(),
82713
- { once: true }
82714
- );
82715
- const timer = setTimeout(() => {
82716
- if (!abortKind) abortKind = "timeout";
82717
- sidechatController.abort();
82718
- }, sidechatTimeoutMs);
82719
- timer.unref?.();
82720
- try {
82721
- await sideAgent.prompt(sidechatPromptBlocks(message));
82722
- } finally {
82723
- clearTimeout(timer);
82724
- }
82725
- if (abortKind) {
82726
- const code = abortKind === "timeout" ? "sidechat_timeout" : "sidechat_interrupted";
82727
- writeSidechatFailure(
82728
- message,
82729
- sideAgent.state.error || "sidechat aborted",
82730
- code
82731
- );
82732
- return;
82733
- }
82734
- const failure = sideAgent.state.error;
82735
- if (failure) {
82736
- writeSidechatFailure(message, failure);
82737
- return;
82738
- }
82739
- const sidechatText = assistantTextFromAgent(sideAgent);
82740
- const capped = sidechatText === void 0 ? void 0 : truncateForEvent(sidechatText, eventStringCap);
82741
- const event = {
82742
- type: "sidechat.completed",
82743
- sessionId,
82744
- requestId,
82745
- text: capped?.value,
82746
- ...capped?.truncated ? { truncated: true, fullLength: capped.fullLength } : {},
82747
- usage: assistantUsageFromAgent(sideAgent),
82748
- durationMs: Date.now() - startedAt
82749
- };
82750
- completedSidechatRequests.set(requestId, event);
82751
- writeEvent(event);
82752
- } catch (error) {
82753
- const detail = errorToFailureDetail(error);
82754
- writeSidechatFailure(
82755
- message,
82756
- typeof detail === "string" ? detail : detail.message,
82757
- typeof detail === "string" ? void 0 : detail.code
82758
- );
82759
- } finally {
82760
- activeSidechat = null;
82761
- }
82762
- }
82763
83161
  function finalize(kind, detail) {
82764
83162
  const turn = activeTurn;
82765
83163
  if (!turn || turn.finalized) return;
@@ -82784,7 +83182,7 @@ async function runJsonEventsMode(params) {
82784
83182
  break;
82785
83183
  }
82786
83184
  case "failed":
82787
- writeEvent({ type: "turn.failed", ...base, ...failureDetail(detail) });
83185
+ writeEvent({ type: "turn.failed", ...base, ...sidechatService.failureDetail(detail) });
82788
83186
  break;
82789
83187
  case "cancelled":
82790
83188
  writeEvent({
@@ -83181,6 +83579,23 @@ async function runJsonEventsMode(params) {
83181
83579
  trace = void 0;
83182
83580
  cleanupBashOutputArtifacts();
83183
83581
  }
83582
+ function handleFatalStartupError(error, alreadyEmitted = false) {
83583
+ const isResumeError = error instanceof CliSessionResumeError;
83584
+ const isThinkingError = error instanceof Error && error.name === "InvalidThinkingSelectionError";
83585
+ if (!isResumeError && !isThinkingError) return false;
83586
+ if (fatalStartupHandled) return true;
83587
+ fatalStartupHandled = true;
83588
+ if (!alreadyEmitted) {
83589
+ writeEvent({
83590
+ type: "turn.failed",
83591
+ sessionId: params.explicitSessionId ?? "",
83592
+ error: isResumeError ? `resume-required failed: ${error.message}` : error.message,
83593
+ source: "external"
83594
+ });
83595
+ }
83596
+ process.exit(isResumeError ? 1 : 2);
83597
+ return true;
83598
+ }
83184
83599
  async function prewarmRuntime() {
83185
83600
  if (params.mockResponse !== void 0) return;
83186
83601
  if (!params.createRuntime && !params.runtime) return;
@@ -83194,15 +83609,7 @@ async function runJsonEventsMode(params) {
83194
83609
  void ensureRuntime().then(resolve7, reject).finally(() => clearTimeout(timer));
83195
83610
  });
83196
83611
  } catch (error) {
83197
- if (error instanceof CliSessionResumeError) {
83198
- writeEvent({
83199
- type: "turn.failed",
83200
- sessionId: params.explicitSessionId ?? "",
83201
- error: `resume-required failed: ${error.message}`,
83202
- source: "external"
83203
- });
83204
- process.exit(1);
83205
- }
83612
+ handleFatalStartupError(error);
83206
83613
  }
83207
83614
  }
83208
83615
  async function ensureRuntime(requestedCwd) {
@@ -83215,7 +83622,8 @@ async function runJsonEventsMode(params) {
83215
83622
  compositionChain = composed.catch(() => {
83216
83623
  });
83217
83624
  ensureRuntimeInFlight.set(effectiveCwd, composed);
83218
- void composed.finally(() => ensureRuntimeInFlight.delete(effectiveCwd)).catch(() => {
83625
+ void composed.finally(() => ensureRuntimeInFlight.delete(effectiveCwd)).catch((error) => {
83626
+ handleFatalStartupError(error);
83219
83627
  });
83220
83628
  return composed;
83221
83629
  }
@@ -83276,7 +83684,15 @@ async function runJsonEventsMode(params) {
83276
83684
  }
83277
83685
  return;
83278
83686
  }
83279
- const { Agent: AgentClass } = await import("./chunks/src-B44QWSGM.js");
83687
+ if (!thinkingLevelInitialized && params.explicitThinkingLevel) {
83688
+ const validation = validateExplicitThinkingSelection(runtime.model, params.explicitThinkingLevel);
83689
+ if (!validation.ok) {
83690
+ const err = new Error(validation.error);
83691
+ err.name = "InvalidThinkingSelectionError";
83692
+ throw err;
83693
+ }
83694
+ }
83695
+ const { Agent: AgentClass } = await import("./chunks/src-2XI5P62J.js");
83280
83696
  if (runtimeClosing) return;
83281
83697
  const compositionRegistry = createCliHostEnvelopeRegistry();
83282
83698
  const jsonModeExtensions = await loadJsonModeExtensions({
@@ -83288,6 +83704,19 @@ async function runJsonEventsMode(params) {
83288
83704
  generation: compositionGeneration,
83289
83705
  getGeneration: () => compositionGeneration,
83290
83706
  queueExternalInput,
83707
+ abortActiveTurn: () => {
83708
+ const busy = Boolean(activeTurn && !activeTurn.finalized || externalTurn && !externalTurn.finalized || controller && !hostIsIdle(controller));
83709
+ if (!busy) return false;
83710
+ if (activeTurn && !activeTurn.finalized) activeTurn.interrupted = true;
83711
+ controller?.abort();
83712
+ return true;
83713
+ },
83714
+ requestShutdown: (reason) => {
83715
+ if (!triggerResidentShutdown || runtimeClosing || ipcShutdownRequested) return false;
83716
+ ipcShutdownRequested = true;
83717
+ setTimeout(() => triggerResidentShutdown?.(reason ?? "IPC", false), 50).unref?.();
83718
+ return true;
83719
+ },
83291
83720
  ensureRuntimeReady: async () => {
83292
83721
  if (controller && !runtimeClosing) return true;
83293
83722
  try {
@@ -83303,15 +83732,15 @@ async function runJsonEventsMode(params) {
83303
83732
  return;
83304
83733
  }
83305
83734
  extensionRunner = jsonModeExtensions.runner;
83735
+ const activeRuntime = runtime;
83306
83736
  {
83307
- const activeSessionId = runtime.sessionManager.getActiveSessionId();
83737
+ const activeSessionId = activeRuntime.sessionManager.getActiveSessionId();
83738
+ const activeMetadata = activeRuntime.sessionManager.getActiveSession()?.metadata ?? {};
83308
83739
  await enqueueBridgeEmission(
83309
83740
  () => jsonModeExtensions.runner.emit({
83310
83741
  type: "session:changed",
83311
83742
  sessionId: activeSessionId ?? null,
83312
- metadata: {
83313
- ...runtime.sessionManager.getActiveSession()?.metadata ?? {}
83314
- }
83743
+ metadata: { ...activeMetadata }
83315
83744
  }) ?? Promise.resolve()
83316
83745
  );
83317
83746
  }
@@ -83337,6 +83766,10 @@ async function runJsonEventsMode(params) {
83337
83766
  appendSystemPrompt: params.developerInstructions,
83338
83767
  tools
83339
83768
  });
83769
+ if (!thinkingLevelInitialized) {
83770
+ thinkingLevelInitialized = true;
83771
+ thinkingLevel = resolveInitialThinkingLevel({ explicitThinkingLevel: params.explicitThinkingLevel, session: runtime.sessionManager.getActiveSession(), settingsManager: runtime.settingsManager });
83772
+ }
83340
83773
  agent = new AgentClass({
83341
83774
  initialState: {
83342
83775
  systemPrompt: baseSystemPrompt,
@@ -83359,85 +83792,85 @@ async function runJsonEventsMode(params) {
83359
83792
  // Body-free transport timeline for the main (JSON-events) agent.
83360
83793
  streamFn: createJsonEventsTransportStreamFn(params.streamFn)
83361
83794
  });
83362
- controller = new AgentSessionController({
83363
- agent,
83364
- sessionManager: runtime.sessionManager,
83365
- cwd: runtime.cwd,
83366
- baseSystemPrompt,
83367
- prepareTurn: async (context) => {
83368
- const result = await jsonModeExtensions.runner.emitBeforeAgentStart({
83369
- type: "before_agent_start",
83370
- messages: context.messages,
83371
- baseSystemPrompt: context.baseSystemPrompt ?? baseSystemPrompt,
83372
- source: context.source
83373
- });
83374
- return {
83375
- systemPrompt: result?.systemPrompt ?? context.baseSystemPrompt ?? baseSystemPrompt,
83376
- messages: result?.messages?.length ? [...context.messages, ...result.messages] : context.messages
83377
- };
83378
- },
83379
- retry: createCliRetryPolicy(),
83380
- onExecutionEnd: async ({ messages }) => {
83381
- const lastAssistant = [...messages].reverse().find((m2) => m2.role === "assistant");
83382
- const retrying = recoveryPending && (!activeTurn?.finalized || externalTurn !== null);
83383
- if (retrying) {
83384
- const failedAssistant = [...messages].reverse().find(
83385
- (m2) => m2.role === "assistant" && (m2.stopReason === "error" || m2.stopReason === "aborted")
83386
- );
83387
- if (failedAssistant)
83795
+ {
83796
+ const runtime2 = activeRuntime;
83797
+ controller = new AgentSessionController({
83798
+ agent,
83799
+ sessionManager: runtime2.sessionManager,
83800
+ cwd: runtime2.cwd,
83801
+ baseSystemPrompt,
83802
+ prepareTurn: async (context) => {
83803
+ const result = await jsonModeExtensions.runner.emitBeforeAgentStart({
83804
+ type: "before_agent_start",
83805
+ messages: context.messages,
83806
+ baseSystemPrompt: context.baseSystemPrompt ?? baseSystemPrompt,
83807
+ source: context.source
83808
+ });
83809
+ return {
83810
+ systemPrompt: result?.systemPrompt ?? context.baseSystemPrompt ?? baseSystemPrompt,
83811
+ messages: result?.messages?.length ? [...context.messages, ...result.messages] : context.messages
83812
+ };
83813
+ },
83814
+ retry: createCliRetryPolicy(),
83815
+ onExecutionEnd: async ({ messages }) => {
83816
+ const lastAssistant = [...messages].reverse().find((m2) => m2.role === "assistant");
83817
+ const retrying = recoveryPending && (!activeTurn?.finalized || externalTurn !== null);
83818
+ if (retrying) {
83819
+ const failedAssistant = [...messages].reverse().find(
83820
+ (m2) => m2.role === "assistant" && (m2.stopReason === "error" || m2.stopReason === "aborted")
83821
+ );
83822
+ if (failedAssistant)
83823
+ await enqueueBridgeEmission(
83824
+ () => jsonModeExtensions.runner.emit({
83825
+ type: "message:end",
83826
+ message: failedAssistant
83827
+ })
83828
+ );
83829
+ return;
83830
+ }
83831
+ if (lastAssistant)
83388
83832
  await enqueueBridgeEmission(
83389
83833
  () => jsonModeExtensions.runner.emit({
83390
83834
  type: "message:end",
83391
- message: failedAssistant
83835
+ message: lastAssistant
83392
83836
  })
83393
83837
  );
83394
- return;
83395
- }
83396
- if (lastAssistant)
83397
83838
  await enqueueBridgeEmission(
83398
- () => jsonModeExtensions.runner.emit({
83399
- type: "message:end",
83400
- message: lastAssistant
83401
- })
83839
+ () => jsonModeExtensions.runner.emit({ type: "agent:end", messages })
83402
83840
  );
83403
- await enqueueBridgeEmission(
83404
- () => jsonModeExtensions.runner.emit({ type: "agent:end", messages })
83405
- );
83406
- },
83407
- getAutoCompactDecision: ({ message, messages }) => createCliAutoCompactDecision({
83408
- message,
83409
- messages,
83410
- contextWindow: runtime.model.contextWindow ?? 0,
83411
- autoCompactEnabled: runtime.settingsManager.getAutoCompactEnabled(),
83412
- reserveTokens: runtime.settingsManager.getAutoCompactReserveTokens(),
83413
- latestCompactionTimestamp: runtime.sessionManager.getLatestCompactionTimestamp(),
83414
- isContextOverflowError: isCliContextOverflowError
83415
- }),
83416
- getCompactionBudgetTokens: createCliCompactionBudget(() => ({
83417
- contextWindow: runtime.model.contextWindow,
83418
- reserveTokens: runtime.settingsManager.getAutoCompactReserveTokens()
83419
- })),
83420
- compaction: {
83421
- modelView: (message) => projectCliHostEnvelopes([message], void 0, compositionRegistry)[0],
83422
- compact: async (context) => createCliAutoCompactionResult({
83423
- context,
83424
- envelopeRegistry: compositionRegistry,
83425
- model: runtime.model,
83426
- apiKey: runtime.apiKey,
83427
- systemPrompt: agent?.state.systemPrompt ?? baseSystemPrompt,
83428
- onProjection: (outcome) => trace?.noteRuntimeEvent(
83429
- outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
83430
- outcome.audit
83431
- )
83432
- })
83433
- },
83434
- classifyFailure: (context) => classifyCliFailure(context),
83435
- onEvent: handleControllerEvent
83436
- });
83437
- trace = new SessionTraceWriter(
83438
- runtime.paths.sessionsDir,
83439
- runtime.sessionManager
83440
- );
83841
+ },
83842
+ getAutoCompactDecision: ({ message, messages }) => createCliAutoCompactDecision({
83843
+ message,
83844
+ messages,
83845
+ contextWindow: runtime2.model.contextWindow ?? 0,
83846
+ autoCompactEnabled: runtime2.settingsManager.getAutoCompactEnabled(),
83847
+ reserveTokens: runtime2.settingsManager.getAutoCompactReserveTokens(),
83848
+ latestCompactionTimestamp: runtime2.sessionManager.getLatestCompactionTimestamp(),
83849
+ isContextOverflowError: isCliContextOverflowError
83850
+ }),
83851
+ getCompactionBudgetTokens: createCliCompactionBudget(() => ({
83852
+ contextWindow: runtime2.model.contextWindow,
83853
+ reserveTokens: runtime2.settingsManager.getAutoCompactReserveTokens()
83854
+ })),
83855
+ compaction: {
83856
+ modelView: (message) => projectCliHostEnvelopes([message], void 0, compositionRegistry)[0],
83857
+ compact: async (context) => createCliAutoCompactionResult({
83858
+ context,
83859
+ envelopeRegistry: compositionRegistry,
83860
+ model: runtime2.model,
83861
+ apiKey: runtime2.apiKey,
83862
+ systemPrompt: agent?.state.systemPrompt ?? baseSystemPrompt,
83863
+ onProjection: (outcome) => trace?.noteRuntimeEvent(
83864
+ outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
83865
+ outcome.audit
83866
+ )
83867
+ })
83868
+ },
83869
+ classifyFailure: (context) => classifyCliFailure(context),
83870
+ onEvent: handleControllerEvent
83871
+ });
83872
+ }
83873
+ trace = new SessionTraceWriter(runtime.paths.sessionsDir, runtime.sessionManager);
83441
83874
  attachAgentEventsToSessionTrace({ agent, trace });
83442
83875
  agent.setTools(
83443
83876
  wrapToolsWithExtensions(agent.state.tools, jsonModeExtensions.runner)
@@ -83485,14 +83918,6 @@ async function runJsonEventsMode(params) {
83485
83918
  }) ?? Promise.resolve());
83486
83919
  }
83487
83920
  });
83488
- if (!thinkingLevelInitialized) {
83489
- thinkingLevelInitialized = true;
83490
- thinkingLevel = resolveInitialThinkingLevel({
83491
- session: runtime.sessionManager.getActiveSession(),
83492
- settingsManager: runtime.settingsManager
83493
- });
83494
- agent.setThinkingLevel(thinkingLevel);
83495
- }
83496
83921
  }
83497
83922
  function metadataSelection(metadata, key) {
83498
83923
  if (!metadata || !(key in metadata)) return void 0;
@@ -83524,63 +83949,42 @@ async function runJsonEventsMode(params) {
83524
83949
  function applyRuntimeSelection(message) {
83525
83950
  if (!runtime || !agent) return;
83526
83951
  const requestedModel = metadataSelection(message.metadata, "model");
83527
- const requestedThinkingLevel = metadataSelection(
83528
- message.metadata,
83529
- "thinkingLevel"
83530
- );
83952
+ const requestedThinkingLevel = metadataSelection(message.metadata, "thinkingLevel");
83953
+ let pendingModel;
83531
83954
  if (requestedModel !== void 0) {
83532
83955
  if (requestedModel === null) {
83533
- const defaults = defaultModelState;
83534
- if (defaults) {
83535
- agent.setModel(defaults.model);
83536
- agent.apiKey = defaults.apiKey;
83537
- runtime.model = defaults.model;
83538
- runtime.provider = defaults.provider;
83539
- runtime.modelId = defaults.modelId;
83540
- runtime.apiKey = defaults.apiKey;
83541
- }
83956
+ if (defaultModelState) pendingModel = { ...defaultModelState };
83542
83957
  } else {
83543
83958
  const parsed = parseRequestedModel(requestedModel);
83544
- if (!parsed)
83545
- throw new Error(
83546
- `model must use profile/modelId format: ${requestedModel}`
83547
- );
83548
- const { provider, modelId } = parsed;
83549
- const model = runtime.modelRegistry.find(provider, modelId);
83959
+ if (!parsed) throw new Error(`model must use profile/modelId format: ${requestedModel}`);
83960
+ const model = runtime.modelRegistry.find(parsed.provider, parsed.modelId);
83550
83961
  if (!model) throw new Error(`Model "${requestedModel}" not found`);
83551
- const apiKey = runtime.modelRegistry.getApiKey(model);
83552
- agent.setModel(model);
83553
- agent.apiKey = apiKey;
83554
- runtime.model = model;
83555
- runtime.provider = provider;
83556
- runtime.modelId = modelId;
83557
- runtime.apiKey = apiKey;
83962
+ pendingModel = { model, provider: parsed.provider, modelId: parsed.modelId, apiKey: runtime.modelRegistry.getApiKey(model) };
83558
83963
  }
83559
83964
  }
83965
+ const candidateModel = pendingModel ? pendingModel.model : runtime.model;
83966
+ let validatedThinking;
83560
83967
  if (requestedThinkingLevel !== void 0) {
83561
83968
  const nextLevel = requestedThinkingLevel === null ? "off" : requestedThinkingLevel;
83562
- if (!isThinkingLevel(nextLevel))
83563
- throw new Error(`Unsupported thinkingLevel: ${nextLevel}`);
83564
- thinkingLevel = nextLevel;
83969
+ const validation = validateExplicitThinkingSelection(candidateModel, nextLevel);
83970
+ if (!validation.ok) throw new Error(validation.error);
83971
+ validatedThinking = validation.level;
83972
+ }
83973
+ if (pendingModel) {
83974
+ agent.setModel(pendingModel.model);
83975
+ agent.apiKey = pendingModel.apiKey;
83976
+ runtime.model = pendingModel.model;
83977
+ runtime.provider = pendingModel.provider;
83978
+ runtime.modelId = pendingModel.modelId;
83979
+ runtime.apiKey = pendingModel.apiKey ?? "";
83980
+ }
83981
+ if (validatedThinking !== void 0) {
83982
+ thinkingLevel = validatedThinking;
83565
83983
  thinkingLevelInitialized = true;
83566
- applyThinkingLevel({
83567
- level: thinkingLevel,
83568
- agent,
83569
- settingsManager: runtime.settingsManager,
83570
- sessionManager: runtime.sessionManager,
83571
- model: runtime.model,
83572
- // Per-request programmatic override: apply to this agent/session
83573
- // only. Persisting here let headless runs (eval harnesses default
83574
- // thinkingLevel to "off") silently rewrite the interactive user's
83575
- // saved default, so new windows booted with thinking off.
83576
- persist: false
83577
- });
83984
+ thinkingLevelEphemeral = false;
83985
+ applyThinkingLevel({ level: thinkingLevel, agent, settingsManager: runtime.settingsManager, sessionManager: runtime.sessionManager, model: runtime.model, persist: false });
83578
83986
  } else {
83579
- syncSessionModelMetadata(
83580
- runtime.sessionManager,
83581
- runtime.model,
83582
- thinkingLevel
83583
- );
83987
+ syncSessionModelMetadata(runtime.sessionManager, runtime.model, agent.state.thinkingLevel, { preserveThinkingLevel: thinkingLevelEphemeral });
83584
83988
  }
83585
83989
  }
83586
83990
  function promptInputFor(message) {
@@ -83591,19 +83995,13 @@ async function runJsonEventsMode(params) {
83591
83995
  const content = promptInputFor(message);
83592
83996
  return { role: "user", content, timestamp: Date.now() };
83593
83997
  }
83594
- function sidechatPromptBlocks(message) {
83595
- return message.hostContext ? [message.hostContext, { type: "text", text: message.prompt }] : [{ type: "text", text: message.prompt }];
83596
- }
83597
- function validateIntakeHostContext(message) {
83598
- return message.hostContext !== void 0 ? intakeHostContextFailure(message.hostContext, envelopeRegistry) : void 0;
83599
- }
83600
83998
  async function runTurn(message) {
83601
- if (isSessionMismatch(message)) {
83999
+ if (sidechatService.isSessionMismatch(message)) {
83602
84000
  writeEvent({
83603
84001
  type: "turn.failed",
83604
84002
  sessionId,
83605
84003
  turnId: message.turnId,
83606
- error: sessionMismatchError(message.sessionId)
84004
+ error: sidechatService.sessionMismatchError(message.sessionId ?? "")
83607
84005
  });
83608
84006
  return;
83609
84007
  }
@@ -83665,7 +84063,7 @@ async function runJsonEventsMode(params) {
83665
84063
  try {
83666
84064
  mockActiveEntryId = persistMockTurn(message, params.mockResponse);
83667
84065
  } catch (error) {
83668
- finalize("failed", errorToFailureDetail(error));
84066
+ finalize("failed", sidechatService.errorToFailureDetail(error));
83669
84067
  if (activeTurn === turn) emitSettled(turn);
83670
84068
  if (activeTurn === turn) activeTurn = null;
83671
84069
  return;
@@ -83684,9 +84082,10 @@ async function runJsonEventsMode(params) {
83684
84082
  try {
83685
84083
  await ensureRuntime(message.cwd);
83686
84084
  } catch (error) {
83687
- finalize("failed", errorToFailureDetail(error));
84085
+ finalize("failed", sidechatService.errorToFailureDetail(error));
83688
84086
  if (activeTurn === turn) emitSettled(turn);
83689
84087
  if (activeTurn === turn) activeTurn = null;
84088
+ handleFatalStartupError(error, true);
83690
84089
  return;
83691
84090
  }
83692
84091
  if (activeTurn !== turn || turn.finalized || turn.interrupted) {
@@ -83882,12 +84281,12 @@ async function runJsonEventsMode(params) {
83882
84281
  }
83883
84282
  }
83884
84283
  async function interrupt(message) {
83885
- if (isSessionMismatch(message)) {
84284
+ if (sidechatService.isSessionMismatch(message)) {
83886
84285
  writeEvent({
83887
84286
  type: "turn.cancelled",
83888
84287
  sessionId,
83889
84288
  turnId: message.turnId || "no-active-turn",
83890
- reason: sessionMismatchError(message.sessionId)
84289
+ reason: sidechatService.sessionMismatchError(message.sessionId ?? "")
83891
84290
  });
83892
84291
  return;
83893
84292
  }
@@ -83921,7 +84320,10 @@ async function runJsonEventsMode(params) {
83921
84320
  controller?.abort();
83922
84321
  }
83923
84322
  function shutdownActiveTurn(reason) {
83924
- if (!activeTurn || activeTurn.finalized) return;
84323
+ if (!activeTurn || activeTurn.finalized) {
84324
+ if (externalTurn && !externalTurn.finalized || controller && !hostIsIdle(controller)) controller?.abort();
84325
+ return;
84326
+ }
83925
84327
  if (params.mockResponse !== void 0) {
83926
84328
  if (activeTurn.outputStarted) return;
83927
84329
  activeTurn.interrupted = true;
@@ -83939,35 +84341,26 @@ async function runJsonEventsMode(params) {
83939
84341
  input.close();
83940
84342
  const keepalive = setInterval(() => {
83941
84343
  }, 3e4);
83942
- let signalled = false;
84344
+ let shutdownStarted = false;
84345
+ let osStopSignals = 0;
83943
84346
  let hardDeadline;
83944
- const shutdown = (signal) => {
83945
- if (signalled) {
83946
- writeEvent({
83947
- type: "shutdown.pending",
83948
- sessionId,
83949
- reason: `force:${signal}`
83950
- });
84347
+ const shutdown = (signal, isOsSignal = true) => {
84348
+ if (isOsSignal) osStopSignals += 1;
84349
+ if (shutdownStarted) {
84350
+ if (!isOsSignal || osStopSignals < 2) return;
84351
+ writeEvent({ type: "shutdown.pending", sessionId, reason: `force:${signal}` });
83951
84352
  process.exit(1);
83952
84353
  return;
83953
84354
  }
83954
- signalled = true;
83955
- writeEvent({
83956
- type: "shutdown.pending",
83957
- sessionId,
83958
- reason: `signal:${signal}`
83959
- });
84355
+ shutdownStarted = true;
84356
+ writeEvent({ type: "shutdown.pending", sessionId, reason: `signal:${signal}` });
83960
84357
  runtimeClosing = true;
83961
84358
  shutdownActiveTurn(`signal:${signal}`);
83962
84359
  sidechatChainStopped = true;
83963
84360
  activeSidechat?.abort();
83964
84361
  clearInterval(keepalive);
83965
84362
  hardDeadline = setTimeout(() => {
83966
- writeEvent({
83967
- type: "shutdown.pending",
83968
- sessionId,
83969
- reason: "deadline-exceeded"
83970
- });
84363
+ writeEvent({ type: "shutdown.pending", sessionId, reason: "deadline-exceeded" });
83971
84364
  process.exit(0);
83972
84365
  }, 15e3);
83973
84366
  hardDeadline.unref?.();
@@ -83976,6 +84369,10 @@ async function runJsonEventsMode(params) {
83976
84369
  await activeTurnPromise;
83977
84370
  await activeSidechatPromise;
83978
84371
  await Promise.allSettled([...ensureRuntimeInFlight.values()]);
84372
+ if (agent) await Promise.race([agent.waitForIdle().catch(() => {
84373
+ }), new Promise((r) => setTimeout(r, 3e3))]);
84374
+ await rawBridgeQueue.catch(() => {
84375
+ });
83979
84376
  await disposeRuntime("shutdown");
83980
84377
  } finally {
83981
84378
  if (hardDeadline) clearTimeout(hardDeadline);
@@ -83983,6 +84380,7 @@ async function runJsonEventsMode(params) {
83983
84380
  }
83984
84381
  })();
83985
84382
  };
84383
+ triggerResidentShutdown = shutdown;
83986
84384
  process.on("SIGTERM", () => shutdown("SIGTERM"));
83987
84385
  process.on("SIGINT", () => shutdown("SIGINT"));
83988
84386
  process.on("SIGHUP", () => {
@@ -84016,11 +84414,11 @@ async function runJsonEventsMode(params) {
84016
84414
  continue;
84017
84415
  }
84018
84416
  if (message.type === "session.rewind") {
84019
- await handleSessionRewind(message);
84417
+ await sidechatService.handleSessionRewind(message);
84020
84418
  continue;
84021
84419
  }
84022
84420
  if (message.type === "session.fork") {
84023
- await handleSessionFork(message);
84421
+ await sidechatService.handleSessionFork(message);
84024
84422
  continue;
84025
84423
  }
84026
84424
  if (message.type === "sidechat.request") {
@@ -84028,13 +84426,13 @@ async function runJsonEventsMode(params) {
84028
84426
  trackSidechatPromise(
84029
84427
  prior.then(async () => {
84030
84428
  if (sidechatChainStopped) {
84031
- const cached = completedSidechatRequests.get(
84429
+ const cached = sidechatService.getCachedSidechatResult(
84032
84430
  message.requestId.trim()
84033
84431
  );
84034
84432
  if (cached) {
84035
84433
  writeEvent(cached);
84036
84434
  } else {
84037
- writeSidechatFailure(
84435
+ writeSidechatFailureLocal(
84038
84436
  message,
84039
84437
  "sidechat discarded on shutdown",
84040
84438
  "sidechat_interrupted"
@@ -84042,8 +84440,8 @@ async function runJsonEventsMode(params) {
84042
84440
  }
84043
84441
  return;
84044
84442
  }
84045
- await handleSidechat(message).catch((error) => {
84046
- writeSidechatFailure(
84443
+ await sidechatService.handleSidechat(message).catch((error) => {
84444
+ writeSidechatFailureLocal(
84047
84445
  message,
84048
84446
  error instanceof Error ? error.message : String(error)
84049
84447
  );
@@ -84128,6 +84526,8 @@ Commands:
84128
84526
  doctor Diagnose local Pie configuration and runtime dependencies
84129
84527
  models init Create a starter ~/.pie/models.json
84130
84528
  models validate Validate ~/.pie/models.json
84529
+ manager Manage the background Pie resident manager (start/stop/status/tail/upgrade)
84530
+ memory Inspect, distill, and schedule session memory
84131
84531
  sessions List, read, rename, rewind, and fork Pie sessions
84132
84532
  extensions List and enable/disable extensions (list/enable/disable)
84133
84533
  permissions Explain Pie tool and shell safety defaults
@@ -84143,6 +84543,9 @@ Interactive Mode Key Bindings:
84143
84543
  Ctrl+C Exit
84144
84544
  Ctrl+D Exit
84145
84545
  Ctrl+O Expand/collapse tool output
84546
+ Ctrl+X Toggle YOLO mode (Alt+O alias)
84547
+ Ctrl+R Set up or toggle IM forwarding (Alt+I alias)
84548
+ Shift+Tab Cycle thinking level (supported presets for active model)
84146
84549
 
84147
84550
  Environment Variables:
84148
84551
  <PROVIDER>_API_KEY Provider-specific API key (for example KIMI_API_KEY, BIGMODEL_API_KEY)
@@ -84158,6 +84561,7 @@ Print Mode Options:
84158
84561
  --json-events Run JSONL protocol mode over stdin/stdout
84159
84562
  --idle Resident mode (with --json-events): no stdin loop, runs until SIGTERM/SIGINT; input arrives via extension intake (IM/IPC), stdout events are the log
84160
84563
  --session-id Reuse or create a specific session in non-interactive mode
84564
+ --thinking <lvl> Set per-run thinking level (off|minimal|low|medium|high|xhigh|max; does not overwrite saved default)
84161
84565
  --resume-required In JSON-events mode, fail if --session-id cannot be resumed
84162
84566
  --no-cd Resume without restarting in the session's project directory
84163
84567
  --developer-instructions <text> Append stable host/developer instructions in JSON-events mode
@@ -84226,7 +84630,8 @@ var STABLE_CLI_COMMANDS = {
84226
84630
  sessions: "sessions",
84227
84631
  extensions: "extensions",
84228
84632
  permissions: "permissions",
84229
- manager: "manager"
84633
+ manager: "manager",
84634
+ memory: "memory"
84230
84635
  };
84231
84636
  async function runWithJsonEventsConsoleIsolation(fn) {
84232
84637
  const originalLog = console.log;
@@ -84246,23 +84651,9 @@ async function runWithJsonEventsConsoleIsolation(fn) {
84246
84651
  }
84247
84652
  async function createCliTestStreamFnFromEnv() {
84248
84653
  if (!process.env.PIE_TEST_MOCK_STREAM_SEQUENCE) return void 0;
84249
- return (await import("./chunks/test-stream-OR3EJBNF.js")).createTestStreamFnFromSequenceEnv();
84250
- }
84251
- function resolveJsonEventsDetailFlag() {
84252
- for (let index = 0; index < process.argv.length; index += 1) {
84253
- const arg = process.argv[index];
84254
- if (arg === "--event-detail") {
84255
- const raw = process.argv[index + 1] ?? "";
84256
- return raw === "compact" || raw === "full" ? { value: raw } : { error: raw || "(missing)" };
84257
- }
84258
- if (arg.startsWith("--event-detail=")) {
84259
- const raw = arg.slice("--event-detail=".length);
84260
- return raw === "compact" || raw === "full" ? { value: raw } : { error: raw };
84261
- }
84262
- }
84263
- return { value: "compact" };
84654
+ return (await import("./chunks/test-stream-SYVWIPPW.js")).createTestStreamFnFromSequenceEnv();
84264
84655
  }
84265
- async function startChat(initialPrompt, testCommand, explicitSessionId) {
84656
+ async function startChat(initialPrompt, testCommand, explicitSessionId, explicitThinkingLevel) {
84266
84657
  const rawOutput = process.argv.includes("--raw-output");
84267
84658
  const jsonOutput = process.argv.includes("--json-output");
84268
84659
  const jsonEvents = process.argv.includes("--json-events");
@@ -84275,7 +84666,7 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
84275
84666
  console.error("--idle requires --session-id: a resident host needs a stable identity across restarts.");
84276
84667
  process.exit(2);
84277
84668
  }
84278
- const detailFlag = resolveJsonEventsDetailFlag();
84669
+ const detailFlag = resolveJsonEventsDetailFlag(process.argv);
84279
84670
  if ("error" in detailFlag) {
84280
84671
  console.error(`Invalid --event-detail value: ${detailFlag.error}. Use compact or full.`);
84281
84672
  process.exit(2);
@@ -84301,6 +84692,7 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
84301
84692
  }
84302
84693
  await runJsonEventsMode({
84303
84694
  explicitSessionId,
84695
+ explicitThinkingLevel,
84304
84696
  resumeRequired,
84305
84697
  developerInstructions,
84306
84698
  eventDetail,
@@ -84308,6 +84700,7 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
84308
84700
  streamFn: await createCliTestStreamFnFromEnv(),
84309
84701
  createRuntime: async ({ cwd, sessionId }) => composeCliRuntime({
84310
84702
  explicitSessionId: explicitSessionId ?? sessionId,
84703
+ explicitThinkingLevel,
84311
84704
  extensionPaths,
84312
84705
  extensionFlags,
84313
84706
  cwd,
@@ -84338,7 +84731,7 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
84338
84731
  process.exit(2);
84339
84732
  }
84340
84733
  try {
84341
- runtime = await composeCliRuntime({ explicitSessionId, extensionPaths, extensionFlags });
84734
+ runtime = await composeCliRuntime({ explicitSessionId, explicitThinkingLevel, extensionPaths, extensionFlags });
84342
84735
  } catch (error) {
84343
84736
  if (error instanceof CliMissingApiKeyError) {
84344
84737
  console.error(`Error: ${error.message}`);
@@ -84357,6 +84750,13 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
84357
84750
  process.exit(process.exitCode ?? 0);
84358
84751
  return;
84359
84752
  }
84753
+ if (explicitThinkingLevel && !runtime.initialModel.unconfigured) {
84754
+ const validation = validateExplicitThinkingSelection(runtime.model, explicitThinkingLevel);
84755
+ if (!validation.ok) {
84756
+ console.error(`Error: ${validation.error}`);
84757
+ process.exit(2);
84758
+ }
84759
+ }
84360
84760
  process.env.PIE_TUI_ACTIVE = "1";
84361
84761
  const runtimeLogger = initializeCliRuntimeLogger(runtime.sessionId, { mode: "interactive_tui" });
84362
84762
  const restoreConsoleInterception = installInteractiveConsoleInterception(runtimeLogger);
@@ -84409,43 +84809,36 @@ async function main() {
84409
84809
  process.exitCode = 1;
84410
84810
  return;
84411
84811
  }
84412
- if (args[0] === STABLE_CLI_COMMANDS.capabilities) {
84413
- runCapabilitiesCommand(args.slice(1));
84812
+ const sub = args[0];
84813
+ const subArgs = args.slice(1);
84814
+ if (sub === STABLE_CLI_COMMANDS.capabilities) {
84815
+ runCapabilitiesCommand(subArgs);
84414
84816
  return;
84415
84817
  }
84416
- if (args[0] === STABLE_CLI_COMMANDS.doctor) {
84417
- await runDoctorCommand(args.slice(1));
84418
- return;
84419
- }
84420
- if (args[0] === STABLE_CLI_COMMANDS.models) {
84421
- try {
84422
- await runModelsCommand(args.slice(1));
84423
- } catch (error) {
84424
- console.error(error instanceof Error ? error.message : String(error));
84425
- process.exitCode = 1;
84426
- }
84818
+ if (sub === STABLE_CLI_COMMANDS.doctor) {
84819
+ await runDoctorCommand(subArgs);
84427
84820
  return;
84428
84821
  }
84429
- if (args[0] === STABLE_CLI_COMMANDS.sessions) {
84430
- await runSessionsCommand(args.slice(1));
84822
+ if (sub === STABLE_CLI_COMMANDS.sessions) {
84823
+ await runSessionsCommand(subArgs);
84431
84824
  return;
84432
84825
  }
84433
- if (args[0] === STABLE_CLI_COMMANDS.extensions) {
84434
- await runExtensionsCommand(args.slice(1));
84826
+ if (sub === STABLE_CLI_COMMANDS.extensions) {
84827
+ await runExtensionsCommand(subArgs);
84435
84828
  return;
84436
84829
  }
84437
- if (args[0] === STABLE_CLI_COMMANDS.permissions) {
84438
- runPermissionsCommand(args.slice(1));
84830
+ if (sub === STABLE_CLI_COMMANDS.permissions) {
84831
+ runPermissionsCommand(subArgs);
84439
84832
  return;
84440
84833
  }
84441
- if (args[0] === "memory") {
84442
- await runMemoryCommand(args.slice(1));
84834
+ if (sub === STABLE_CLI_COMMANDS.memory) {
84835
+ await runMemoryCommand(subArgs);
84443
84836
  return;
84444
84837
  }
84445
- if (args[0] === STABLE_CLI_COMMANDS.manager) {
84446
- const { runManagerCommand } = await import("./chunks/manager-cli-NEZA46M5.js");
84838
+ if (sub === STABLE_CLI_COMMANDS.models || sub === STABLE_CLI_COMMANDS.manager) {
84447
84839
  try {
84448
- await runManagerCommand(args.slice(1));
84840
+ if (sub === STABLE_CLI_COMMANDS.models) await runModelsCommand(subArgs);
84841
+ else await (await import("./chunks/manager-cli-Y6HM3MHA.js")).runManagerCommand(subArgs);
84449
84842
  } catch (error) {
84450
84843
  console.error(error instanceof Error ? error.message : String(error));
84451
84844
  process.exitCode = 1;
@@ -84457,6 +84850,14 @@ async function main() {
84457
84850
  showHelp();
84458
84851
  return;
84459
84852
  }
84853
+ const thinkingFlag = resolveExplicitThinkingFlag(parsed.thinkingLevel, process.argv, parsed.sessionId);
84854
+ if (!thinkingFlag.ok) {
84855
+ if (thinkingFlag.jsonEvent) process.stdout.write(`${thinkingFlag.jsonEvent}
84856
+ `);
84857
+ console.error(thinkingFlag.message);
84858
+ process.exit(2);
84859
+ }
84860
+ const explicitThinkingLevel = thinkingFlag.value;
84460
84861
  if (parsed.sessionId) {
84461
84862
  const decision = decideSessionResumeRestart(args, parsed.sessionId, process.cwd());
84462
84863
  if (decision) {
@@ -84471,10 +84872,10 @@ async function main() {
84471
84872
  }
84472
84873
  }
84473
84874
  if (parsed.testCommand) {
84474
- await startChat(void 0, parsed.testCommand, parsed.sessionId);
84875
+ await startChat(void 0, parsed.testCommand, parsed.sessionId, explicitThinkingLevel);
84475
84876
  return;
84476
84877
  }
84477
- await startChat(parsed.initialPrompt, void 0, parsed.sessionId);
84878
+ await startChat(parsed.initialPrompt, void 0, parsed.sessionId, explicitThinkingLevel);
84478
84879
  }
84479
84880
  main().catch((err) => {
84480
84881
  logError("Fatal error", err);