@causyne/agent 1.20.44 → 1.20.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.44",
3
+ "version": "1.20.50",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -2693,12 +2693,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2693
2693
  if (response.thinkingBlocks) {
2694
2694
  assistantMsg.thinking_blocks = response.thinkingBlocks;
2695
2695
  }
2696
- this.messages.push(assistantMsg);
2697
- // Prose accompanying pending actions is not an execution result.
2698
- // Tool events provide progress; terminal claims pass completion gates below.
2699
2696
  const externalActions = Array.isArray(response.externalActions)
2700
2697
  ? response.externalActions
2701
2698
  : [];
2699
+ if (externalActions.length > 0) {
2700
+ assistantMsg.external_actions = externalActions;
2701
+ }
2702
+ this.messages.push(assistantMsg);
2703
+ // Prose accompanying pending actions is not an execution result.
2704
+ // Tool events provide progress; terminal claims pass completion gates below.
2702
2705
  const completedExternalActions = externalActions.filter((a) => a && a.status === 'completed');
2703
2706
  const failedExternalActions = externalActions.filter((a) => a && a.status === 'failed');
2704
2707
  const hasExternalActions = completedExternalActions.length > 0;
@@ -2878,6 +2881,28 @@ You are operating in a text-and-code modality without direct image pixel renderi
2878
2881
  this.memoryManager.saveHistory(this.messages);
2879
2882
  continue;
2880
2883
  }
2884
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations === 3) {
2885
+ incompleteTurnContinuations++;
2886
+ if (response.content) {
2887
+ this.emitEvent({ type: 'agent_message', content: response.content });
2888
+ }
2889
+ this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
2890
+ this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
2891
+ this.messages.push({
2892
+ role: 'system',
2893
+ content: `[TASK COMPLETION MANDATE: You have completed your tool execution steps (${this.stepsCompleted} steps performed). Provide your complete final response, deliverables, and conclusions directly to the user now. Do not run any more background commands.]`
2894
+ });
2895
+ this.memoryManager.saveHistory(this.messages);
2896
+ continue;
2897
+ }
2898
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress || (typeof contentText === 'string' && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()))))) {
2899
+ this.emitEvent({
2900
+ type: 'error',
2901
+ message: 'The task stopped before completion after repeated incomplete turns without a final response. Work remains unfinished.'
2902
+ });
2903
+ this.memoryManager.saveHistory(this.messages);
2904
+ break;
2905
+ }
2881
2906
  if (hasExternalActions && !isIncompleteTurn && !isMidTaskProgress) {
2882
2907
  incompleteTurnContinuations = 0;
2883
2908
  }
package/src/agentLoop.ts CHANGED
@@ -2816,14 +2816,19 @@ You are operating in a text-and-code modality without direct image pixel renderi
2816
2816
  if (response.thinkingBlocks) {
2817
2817
  assistantMsg.thinking_blocks = response.thinkingBlocks;
2818
2818
  }
2819
+
2820
+ const externalActions = Array.isArray((response as any).externalActions)
2821
+ ? (response as any).externalActions
2822
+ : [];
2823
+ if (externalActions.length > 0) {
2824
+ assistantMsg.external_actions = externalActions;
2825
+ }
2826
+
2819
2827
  this.messages.push(assistantMsg);
2820
2828
 
2821
2829
  // Prose accompanying pending actions is not an execution result.
2822
2830
  // Tool events provide progress; terminal claims pass completion gates below.
2823
2831
 
2824
- const externalActions = Array.isArray((response as any).externalActions)
2825
- ? (response as any).externalActions
2826
- : [];
2827
2832
  const completedExternalActions = externalActions.filter((a: any) => a && a.status === 'completed');
2828
2833
  const failedExternalActions = externalActions.filter((a: any) => a && a.status === 'failed');
2829
2834
  const hasExternalActions = completedExternalActions.length > 0;
@@ -3017,6 +3022,30 @@ You are operating in a text-and-code modality without direct image pixel renderi
3017
3022
  continue;
3018
3023
  }
3019
3024
 
3025
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations === 3) {
3026
+ incompleteTurnContinuations++;
3027
+ if (response.content) {
3028
+ this.emitEvent({ type: 'agent_message', content: response.content });
3029
+ }
3030
+ this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
3031
+ this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
3032
+ this.messages.push({
3033
+ role: 'system',
3034
+ content: `[TASK COMPLETION MANDATE: You have completed your tool execution steps (${this.stepsCompleted} steps performed). Provide your complete final response, deliverables, and conclusions directly to the user now. Do not run any more background commands.]`
3035
+ });
3036
+ this.memoryManager.saveHistory(this.messages);
3037
+ continue;
3038
+ }
3039
+
3040
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress || (typeof contentText === 'string' && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()))))) {
3041
+ this.emitEvent({
3042
+ type: 'error',
3043
+ message: 'The task stopped before completion after repeated incomplete turns without a final response. Work remains unfinished.'
3044
+ });
3045
+ this.memoryManager.saveHistory(this.messages);
3046
+ break;
3047
+ }
3048
+
3020
3049
  if (hasExternalActions && !isIncompleteTurn && !isMidTaskProgress) {
3021
3050
  incompleteTurnContinuations = 0;
3022
3051
  }
package/src/commands.js CHANGED
@@ -1274,6 +1274,52 @@ export const COMMANDS = [
1274
1274
  return ok(`Refreshed ${providerToRefresh} models (${result.models.length} available, source: ${result.source}). Run /model list to view.`);
1275
1275
  }
1276
1276
 
1277
+ if (first === 'test') {
1278
+ const targetProvider = argv[1] || config.provider;
1279
+ const targetModel = argv[2] || (targetProvider === config.provider ? config.model : undefined);
1280
+ if (!targetProvider) return fail('No provider specified or configured. Run /setup first.');
1281
+
1282
+ const testConfig = { ...config, provider: targetProvider };
1283
+ if (targetModel) {
1284
+ testConfig.model = targetModel;
1285
+ } else if (targetProvider !== config.provider) {
1286
+ delete testConfig.model;
1287
+ }
1288
+ if (config.providerKeys && config.providerKeys[targetProvider]) {
1289
+ testConfig.apiKey = config.providerKeys[targetProvider];
1290
+ }
1291
+
1292
+ try {
1293
+ const { createProvider } = await import('./providers/factory.js');
1294
+ const providerInstance = createProvider(testConfig);
1295
+ const t0 = performance.now();
1296
+ const response = await providerInstance.chat([
1297
+ { role: 'user', content: 'Respond with exactly: OK' }
1298
+ ], { maxTokens: 16 });
1299
+ const latencyMs = Math.round(performance.now() - t0);
1300
+
1301
+ const outputLines = [
1302
+ `✅ API Call Test Succeeded: "${targetProvider}" / "${providerInstance.model || targetModel || 'default'}"`,
1303
+ '',
1304
+ ` • Round-trip Latency : ${latencyMs} ms`,
1305
+ ` • Response Content : ${JSON.stringify(response.content || '').slice(0, 80)}`,
1306
+ ` • Tokens Used : ${response.usage ? `${response.usage.promptTokens} in / ${response.usage.completionTokens} out` : 'unreported'}`,
1307
+ '',
1308
+ 'Wire format, credentials, and model endpoint are verified and accurate.'
1309
+ ];
1310
+ return ok(outputLines.join('\n'));
1311
+ } catch (err) {
1312
+ return fail(
1313
+ `❌ API Call Test Failed for "${targetProvider}" / "${targetModel || config.model || 'default'}":\n\n`
1314
+ + ` Error: ${err.message || err}\n\n`
1315
+ + `Checks:\n`
1316
+ + ` - Verify the API key in /setup.\n`
1317
+ + ` - Check if the model is active with "/model list ${targetProvider}".\n`
1318
+ + ` - Ensure the provider endpoint or account has sufficient quota.`
1319
+ );
1320
+ }
1321
+ }
1322
+
1277
1323
  const rawRequested = argv.join(' ').trim().replace(/^\/model\s+/i, '');
1278
1324
 
1279
1325
  // Helper to cleanly activate a provider + model, persist config, update live loop & prompt
@@ -954,6 +954,51 @@ export async function fetchLiveModels(provider, config = {}) {
954
954
  return data.data.map((m) => m.id || '').filter(Boolean).sort();
955
955
  }
956
956
  }
957
+ if (norm === 'xai') {
958
+ if (!apiKey)
959
+ return [];
960
+ const host = (baseUrl || 'https://api.x.ai/v1').replace(/\/+$/, '');
961
+ const res = await fetch(`${host}/models`, {
962
+ headers: { Authorization: `Bearer ${apiKey}` },
963
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
964
+ });
965
+ if (!res.ok)
966
+ return [];
967
+ const data = await res.json();
968
+ if (Array.isArray(data.data)) {
969
+ return data.data.map((m) => m.id || '').filter((id) => /^(grok)/i.test(id)).sort();
970
+ }
971
+ }
972
+ if (norm === 'moonshot') {
973
+ if (!apiKey)
974
+ return [];
975
+ const host = (baseUrl || 'https://api.moonshot.cn/v1').replace(/\/+$/, '');
976
+ const res = await fetch(`${host}/models`, {
977
+ headers: { Authorization: `Bearer ${apiKey}` },
978
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
979
+ });
980
+ if (!res.ok)
981
+ return [];
982
+ const data = await res.json();
983
+ if (Array.isArray(data.data)) {
984
+ return data.data.map((m) => m.id || '').filter((id) => /^(kimi|moonshot)/i.test(id)).sort();
985
+ }
986
+ }
987
+ if (norm === 'dashscope-byok' || norm === 'qwen') {
988
+ if (!apiKey)
989
+ return [];
990
+ const host = (baseUrl || 'https://dashscope.aliyuncs.com/compatible-mode/v1').replace(/\/+$/, '');
991
+ const res = await fetch(`${host}/models`, {
992
+ headers: { Authorization: `Bearer ${apiKey}` },
993
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
994
+ });
995
+ if (!res.ok)
996
+ return [];
997
+ const data = await res.json();
998
+ if (Array.isArray(data.data)) {
999
+ return data.data.map((m) => m.id || '').filter((id) => /^(qwen)/i.test(id)).sort();
1000
+ }
1001
+ }
957
1002
  if (norm === 'openai-compatible') {
958
1003
  if (!baseUrl)
959
1004
  return [];
@@ -978,37 +1023,74 @@ export async function fetchLiveModels(provider, config = {}) {
978
1023
  }
979
1024
  return [];
980
1025
  }
1026
+ function resolveEffectiveApiKey(norm, config = {}) {
1027
+ if (config.apiKey)
1028
+ return config.apiKey;
1029
+ const pKeys = config.providerKeys;
1030
+ if (pKeys) {
1031
+ if (pKeys[norm])
1032
+ return pKeys[norm];
1033
+ if (norm === 'qwen' && pKeys['dashscope-byok'])
1034
+ return pKeys['dashscope-byok'];
1035
+ if (norm === 'dashscope-byok' && pKeys['qwen'])
1036
+ return pKeys['qwen'];
1037
+ }
1038
+ const envMap = {
1039
+ anthropic: 'ANTHROPIC_API_KEY',
1040
+ openai: 'OPENAI_API_KEY',
1041
+ gemini: 'GEMINI_API_KEY',
1042
+ deepseek: 'DEEPSEEK_API_KEY',
1043
+ qwen: 'DASHSCOPE_API_KEY',
1044
+ 'dashscope-byok': 'DASHSCOPE_API_KEY',
1045
+ xai: 'XAI_API_KEY',
1046
+ moonshot: 'MOONSHOT_API_KEY'
1047
+ };
1048
+ const envVar = envMap[norm];
1049
+ if (envVar && process.env[envVar]) {
1050
+ return process.env[envVar];
1051
+ }
1052
+ return '';
1053
+ }
981
1054
  /**
982
1055
  * Resolve available models using dual-layer architecture:
983
1056
  * 1. Checks live query if forceRefresh is true.
984
1057
  * 2. Checks local cache if available and fresh.
985
- * 3. Falls back to static curated catalogue merged with any cached items.
1058
+ * 3. Falls back to static curated catalogue when unconfigured or offline.
986
1059
  */
987
1060
  export async function resolveAvailableModels(provider, config = {}, forceRefresh = false) {
988
1061
  const norm = normalizeProviderKey(provider);
989
1062
  const curated = getCuratedModels(norm);
990
1063
  const localAgent = isLocalOrAcpProvider(norm);
1064
+ const effectiveKey = resolveEffectiveApiKey(norm, config);
1065
+ const queryConfig = {};
1066
+ if (config.baseUrl)
1067
+ queryConfig.baseUrl = config.baseUrl;
1068
+ if (config.providerKeys)
1069
+ queryConfig.providerKeys = config.providerKeys;
1070
+ const keyToUse = effectiveKey || config.apiKey;
1071
+ if (keyToUse)
1072
+ queryConfig.apiKey = keyToUse;
991
1073
  if (forceRefresh) {
992
- const live = await fetchLiveModels(norm, config);
1074
+ const live = await fetchLiveModels(norm, queryConfig);
993
1075
  if (live.length > 0) {
994
- const models = localAgent ? [...new Set(live)] : [...new Set([...live, ...curated])];
995
- saveCachedModels(norm, models, { config });
1076
+ const models = [...new Set(live)];
1077
+ saveCachedModels(norm, models, { config: queryConfig });
996
1078
  return { models, source: 'live' };
997
1079
  }
998
1080
  }
999
- const cached = getCachedModels(norm, config);
1081
+ const cached = getCachedModels(norm, queryConfig);
1000
1082
  if (cached && cached.length > 0) {
1001
- const models = localAgent ? [...new Set(cached)] : [...new Set([...cached, ...curated])];
1083
+ const models = [...new Set(cached)];
1002
1084
  return { models, source: 'cache' };
1003
1085
  }
1004
1086
  // Attempt lazy background discovery if credentials exist. Peer agents and
1005
1087
  // Antigravity are credentialed by their own CLI login, so they qualify even
1006
1088
  // with no apiKey in Causyne's vault.
1007
- if (config.apiKey || norm === 'ollama' || localAgent) {
1008
- const live = await fetchLiveModels(norm, config);
1089
+ if (effectiveKey || norm === 'ollama' || localAgent) {
1090
+ const live = await fetchLiveModels(norm, queryConfig);
1009
1091
  if (live.length > 0) {
1010
- const models = localAgent ? [...new Set(live)] : [...new Set([...live, ...curated])];
1011
- saveCachedModels(norm, models, { config });
1092
+ const models = [...new Set(live)];
1093
+ saveCachedModels(norm, models, { config: queryConfig });
1012
1094
  return { models, source: 'live' };
1013
1095
  }
1014
1096
  }
@@ -1024,6 +1024,48 @@ export async function fetchLiveModels(
1024
1024
  }
1025
1025
  }
1026
1026
 
1027
+ if (norm === 'xai') {
1028
+ if (!apiKey) return [];
1029
+ const host = (baseUrl || 'https://api.x.ai/v1').replace(/\/+$/, '');
1030
+ const res = await fetch(`${host}/models`, {
1031
+ headers: { Authorization: `Bearer ${apiKey}` },
1032
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1033
+ });
1034
+ if (!res.ok) return [];
1035
+ const data = await res.json() as { data?: Array<{ id?: string }> };
1036
+ if (Array.isArray(data.data)) {
1037
+ return data.data.map((m) => m.id || '').filter((id) => /^(grok)/i.test(id)).sort();
1038
+ }
1039
+ }
1040
+
1041
+ if (norm === 'moonshot') {
1042
+ if (!apiKey) return [];
1043
+ const host = (baseUrl || 'https://api.moonshot.cn/v1').replace(/\/+$/, '');
1044
+ const res = await fetch(`${host}/models`, {
1045
+ headers: { Authorization: `Bearer ${apiKey}` },
1046
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1047
+ });
1048
+ if (!res.ok) return [];
1049
+ const data = await res.json() as { data?: Array<{ id?: string }> };
1050
+ if (Array.isArray(data.data)) {
1051
+ return data.data.map((m) => m.id || '').filter((id) => /^(kimi|moonshot)/i.test(id)).sort();
1052
+ }
1053
+ }
1054
+
1055
+ if (norm === 'dashscope-byok' || norm === 'qwen') {
1056
+ if (!apiKey) return [];
1057
+ const host = (baseUrl || 'https://dashscope.aliyuncs.com/compatible-mode/v1').replace(/\/+$/, '');
1058
+ const res = await fetch(`${host}/models`, {
1059
+ headers: { Authorization: `Bearer ${apiKey}` },
1060
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1061
+ });
1062
+ if (!res.ok) return [];
1063
+ const data = await res.json() as { data?: Array<{ id?: string }> };
1064
+ if (Array.isArray(data.data)) {
1065
+ return data.data.map((m) => m.id || '').filter((id) => /^(qwen)/i.test(id)).sort();
1066
+ }
1067
+ }
1068
+
1027
1069
  if (norm === 'openai-compatible') {
1028
1070
  if (!baseUrl) return [];
1029
1071
  const host = baseUrl.replace(/\/+$/, '');
@@ -1050,11 +1092,39 @@ export interface ModelResolutionResult {
1050
1092
  source: 'live' | 'cache' | 'catalogue';
1051
1093
  }
1052
1094
 
1095
+ function resolveEffectiveApiKey(
1096
+ norm: string,
1097
+ config: { apiKey?: string; providerKeys?: Record<string, string> } = {}
1098
+ ): string {
1099
+ if (config.apiKey) return config.apiKey;
1100
+ const pKeys = config.providerKeys;
1101
+ if (pKeys) {
1102
+ if (pKeys[norm]) return pKeys[norm]!;
1103
+ if (norm === 'qwen' && pKeys['dashscope-byok']) return pKeys['dashscope-byok']!;
1104
+ if (norm === 'dashscope-byok' && pKeys['qwen']) return pKeys['qwen']!;
1105
+ }
1106
+ const envMap: Record<string, string> = {
1107
+ anthropic: 'ANTHROPIC_API_KEY',
1108
+ openai: 'OPENAI_API_KEY',
1109
+ gemini: 'GEMINI_API_KEY',
1110
+ deepseek: 'DEEPSEEK_API_KEY',
1111
+ qwen: 'DASHSCOPE_API_KEY',
1112
+ 'dashscope-byok': 'DASHSCOPE_API_KEY',
1113
+ xai: 'XAI_API_KEY',
1114
+ moonshot: 'MOONSHOT_API_KEY'
1115
+ };
1116
+ const envVar = envMap[norm];
1117
+ if (envVar && process.env[envVar]) {
1118
+ return process.env[envVar]!;
1119
+ }
1120
+ return '';
1121
+ }
1122
+
1053
1123
  /**
1054
1124
  * Resolve available models using dual-layer architecture:
1055
1125
  * 1. Checks live query if forceRefresh is true.
1056
1126
  * 2. Checks local cache if available and fresh.
1057
- * 3. Falls back to static curated catalogue merged with any cached items.
1127
+ * 3. Falls back to static curated catalogue when unconfigured or offline.
1058
1128
  */
1059
1129
  export async function resolveAvailableModels(
1060
1130
  provider: string,
@@ -1064,30 +1134,36 @@ export async function resolveAvailableModels(
1064
1134
  const norm = normalizeProviderKey(provider);
1065
1135
  const curated = getCuratedModels(norm);
1066
1136
  const localAgent = isLocalOrAcpProvider(norm);
1137
+ const effectiveKey = resolveEffectiveApiKey(norm, config);
1138
+ const queryConfig: { apiKey?: string; baseUrl?: string; providerKeys?: Record<string, string> } = {};
1139
+ if (config.baseUrl) queryConfig.baseUrl = config.baseUrl;
1140
+ if (config.providerKeys) queryConfig.providerKeys = config.providerKeys;
1141
+ const keyToUse = effectiveKey || config.apiKey;
1142
+ if (keyToUse) queryConfig.apiKey = keyToUse;
1067
1143
 
1068
1144
  if (forceRefresh) {
1069
- const live = await fetchLiveModels(norm, config);
1145
+ const live = await fetchLiveModels(norm, queryConfig);
1070
1146
  if (live.length > 0) {
1071
- const models = localAgent ? [...new Set(live)] : [...new Set([...live, ...curated])];
1072
- saveCachedModels(norm, models, { config });
1147
+ const models = [...new Set(live)];
1148
+ saveCachedModels(norm, models, { config: queryConfig });
1073
1149
  return { models, source: 'live' };
1074
1150
  }
1075
1151
  }
1076
1152
 
1077
- const cached = getCachedModels(norm, config);
1153
+ const cached = getCachedModels(norm, queryConfig);
1078
1154
  if (cached && cached.length > 0) {
1079
- const models = localAgent ? [...new Set(cached)] : [...new Set([...cached, ...curated])];
1155
+ const models = [...new Set(cached)];
1080
1156
  return { models, source: 'cache' };
1081
1157
  }
1082
1158
 
1083
1159
  // Attempt lazy background discovery if credentials exist. Peer agents and
1084
1160
  // Antigravity are credentialed by their own CLI login, so they qualify even
1085
1161
  // with no apiKey in Causyne's vault.
1086
- if (config.apiKey || norm === 'ollama' || localAgent) {
1087
- const live = await fetchLiveModels(norm, config);
1162
+ if (effectiveKey || norm === 'ollama' || localAgent) {
1163
+ const live = await fetchLiveModels(norm, queryConfig);
1088
1164
  if (live.length > 0) {
1089
- const models = localAgent ? [...new Set(live)] : [...new Set([...live, ...curated])];
1090
- saveCachedModels(norm, models, { config });
1165
+ const models = [...new Set(live)];
1166
+ saveCachedModels(norm, models, { config: queryConfig });
1091
1167
  return { models, source: 'live' };
1092
1168
  }
1093
1169
  }
@@ -1,5 +1,11 @@
1
- const LAUNCH_VERBS = /\b(open|launch|start|run|play|serve|preview)\b/i;
2
- const CHANGE_VERBS = /\b(create|build|make|write|edit|fix|modify|change|update|implement|generate|refactor|delete|remove|install|deploy)\b/i;
1
+ const CREATIVE_WORDS = /\b(?:story|novel|fiction|narrative|lore|essay|poem|poetry|chapter|character|plot|dialogue|scene|cerita|kisah|dongeng|karangan|buku|tulisan|bab|paragraf|halaman)\b/i;
2
+ const INQUIRY_WORDS = /\b(?:explain|why|what|how|who|where|when|analyze|describe|tell\s+me|show\s+me\s+how|difference|summary|summarize|review|audit|jelaskan|kenapa|mengapa|bagaimana|siapa|apakah|analisis)\b/i;
3
+ const CHANGE_VERBS = /\b(?:create|build|make|write|edit|fix|modify|change|update|implement|generate|refactor|delete|remove|install|deploy|add|append|expand|continue|improve|refine|compose|draft|author|design|buat(?:kan)?|bikin|tulis(?:kan)?|ubah|ganti|perbaiki|tambah(?:kan)?|kembangkan|lanjut(?:kan)?|sambung(?:kan)?|membaut|maembuat|merancang|susun|crear|escribir|construir|modificar|actualizar|créer|écrire|modifier|erstellen|schreiben|bauen)\b/i;
4
+ const NON_LAUNCH_PHRASES = /\b(?:(?:run|runs|running)\s+(?:by|on|in|with|out|through)|(?:play|plays|playing)\s+(?:a\s+role|with)|(?:open|opens|opening)\s+(?:to|world|source|mind|ended|door)|(?:start|starts|starting)\s+(?:with|from)|(?:serve|serves|serving)\s+(?:as|to)|in\s+the\s+long\s+run|home\s+run)\b/i;
5
+ const IMPERATIVE_LAUNCH = /^\s*(?:please\s+|can\s+you\s+)?(?:open|launch|start|run|play|serve|preview)(?:\s+(?:it|this|that|app|application|project|game|server|service|dev|preview|up|now|here|locally))?\s*[.!?]?\s*$/i;
6
+ const TARGETED_LAUNCH = /\b(?:open|launch|start|run|play|serve|preview)\s+(?:up\s+)?(?:the\s+|this\s+|an?\s+)?(?:app|application|project|game|server|dev\s+server|website|site|page|ui|preview|demo|localhost|frontend|backend)\b/i;
7
+ const URL_OR_FILE_LAUNCH = /^\s*(?:open|preview)\s+(?:https?:\/\/|\/|~\/|\.\/|[a-zA-Z0-9_\-\.\/]+\.(?:html|htm|php|py|js|ts))\b/i;
8
+ const BROWSER_LAUNCH = /\b(?:open|view)\s+(?:in\s+)?(?:browser|chrome|safari)\b/i;
3
9
  const SERVER_COMMAND = /^\s*(?:python(?:3(?:\.\d+)?)?\s+(?:-u\s+)?(?:\S*\/)?server\.py\b|python(?:3(?:\.\d+)?)?\s+-m\s+http\.server\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b|(?:npx|bunx)\s+(?:vite|next\s+dev|http-server)\b|uvicorn\b|gunicorn\b|flask\s+run\b)/i;
4
10
  const READ_ONLY_COMMAND = /^\s*(?:pwd|ls|rg|grep|cat|head|tail|find|which|where|ps|pgrep|lsof|netstat|ss|git\s+(?:status|diff|log|show)|node\s+(?:-v|--version)|python(?:3(?:\.\d+)?)?\s+(?:-V|--version))\b/i;
5
11
  const OPEN_COMMAND = /^\s*(?:open|xdg-open|start)\s+\S+/i;
@@ -11,11 +17,29 @@ const MUTATION_TOOLS = new Set([
11
17
  'create_skill', 'manage_local_dependencies'
12
18
  ]);
13
19
  export function isLaunchOnlyPrompt(prompt) {
20
+ if (!prompt || typeof prompt !== 'string')
21
+ return false;
22
+ const trimmed = prompt.trim();
23
+ if (trimmed.length === 0)
24
+ return false;
25
+ if (trimmed.split(/\s+/).length > 25 || trimmed.length > 150)
26
+ return false;
14
27
  if (/\b(?:run|execute)\s+(?:the\s+)?(?:tests?|checks?|lint|benchmarks?|scripts?|commands?|tools?|creative_apps|resolve_act|memory_recall|native_engine|browser_act|fs_read|sysRun)\b/i.test(prompt))
15
28
  return false;
16
29
  if (/\b(?:verify|verification|verify_bridge|inspectActive|simulate|probe|audit|analyze|diagnose)\b/i.test(prompt))
17
30
  return false;
18
- return LAUNCH_VERBS.test(prompt) && !CHANGE_VERBS.test(prompt);
31
+ if (CREATIVE_WORDS.test(prompt))
32
+ return false;
33
+ if (INQUIRY_WORDS.test(prompt))
34
+ return false;
35
+ if (CHANGE_VERBS.test(prompt))
36
+ return false;
37
+ if (NON_LAUNCH_PHRASES.test(prompt))
38
+ return false;
39
+ return IMPERATIVE_LAUNCH.test(prompt)
40
+ || TARGETED_LAUNCH.test(prompt)
41
+ || URL_OR_FILE_LAUNCH.test(prompt)
42
+ || BROWSER_LAUNCH.test(prompt);
19
43
  }
20
44
  export function isServerLaunchCommand(command) {
21
45
  return SERVER_COMMAND.test(command.trim());
@@ -1,5 +1,12 @@
1
- const LAUNCH_VERBS = /\b(open|launch|start|run|play|serve|preview)\b/i;
2
- const CHANGE_VERBS = /\b(create|build|make|write|edit|fix|modify|change|update|implement|generate|refactor|delete|remove|install|deploy)\b/i;
1
+ const CREATIVE_WORDS = /\b(?:story|novel|fiction|narrative|lore|essay|poem|poetry|chapter|character|plot|dialogue|scene|cerita|kisah|dongeng|karangan|buku|tulisan|bab|paragraf|halaman)\b/i;
2
+ const INQUIRY_WORDS = /\b(?:explain|why|what|how|who|where|when|analyze|describe|tell\s+me|show\s+me\s+how|difference|summary|summarize|review|audit|jelaskan|kenapa|mengapa|bagaimana|siapa|apakah|analisis)\b/i;
3
+ const CHANGE_VERBS = /\b(?:create|build|make|write|edit|fix|modify|change|update|implement|generate|refactor|delete|remove|install|deploy|add|append|expand|continue|improve|refine|compose|draft|author|design|buat(?:kan)?|bikin|tulis(?:kan)?|ubah|ganti|perbaiki|tambah(?:kan)?|kembangkan|lanjut(?:kan)?|sambung(?:kan)?|membaut|maembuat|merancang|susun|crear|escribir|construir|modificar|actualizar|créer|écrire|modifier|erstellen|schreiben|bauen)\b/i;
4
+ const NON_LAUNCH_PHRASES = /\b(?:(?:run|runs|running)\s+(?:by|on|in|with|out|through)|(?:play|plays|playing)\s+(?:a\s+role|with)|(?:open|opens|opening)\s+(?:to|world|source|mind|ended|door)|(?:start|starts|starting)\s+(?:with|from)|(?:serve|serves|serving)\s+(?:as|to)|in\s+the\s+long\s+run|home\s+run)\b/i;
5
+
6
+ const IMPERATIVE_LAUNCH = /^\s*(?:please\s+|can\s+you\s+)?(?:open|launch|start|run|play|serve|preview)(?:\s+(?:it|this|that|app|application|project|game|server|service|dev|preview|up|now|here|locally))?\s*[.!?]?\s*$/i;
7
+ const TARGETED_LAUNCH = /\b(?:open|launch|start|run|play|serve|preview)\s+(?:up\s+)?(?:the\s+|this\s+|an?\s+)?(?:app|application|project|game|server|dev\s+server|website|site|page|ui|preview|demo|localhost|frontend|backend)\b/i;
8
+ const URL_OR_FILE_LAUNCH = /^\s*(?:open|preview)\s+(?:https?:\/\/|\/|~\/|\.\/|[a-zA-Z0-9_\-\.\/]+\.(?:html|htm|php|py|js|ts))\b/i;
9
+ const BROWSER_LAUNCH = /\b(?:open|view)\s+(?:in\s+)?(?:browser|chrome|safari)\b/i;
3
10
  const SERVER_COMMAND = /^\s*(?:python(?:3(?:\.\d+)?)?\s+(?:-u\s+)?(?:\S*\/)?server\.py\b|python(?:3(?:\.\d+)?)?\s+-m\s+http\.server\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b|(?:npx|bunx)\s+(?:vite|next\s+dev|http-server)\b|uvicorn\b|gunicorn\b|flask\s+run\b)/i;
4
11
  const READ_ONLY_COMMAND = /^\s*(?:pwd|ls|rg|grep|cat|head|tail|find|which|where|ps|pgrep|lsof|netstat|ss|git\s+(?:status|diff|log|show)|node\s+(?:-v|--version)|python(?:3(?:\.\d+)?)?\s+(?:-V|--version))\b/i;
5
12
  const OPEN_COMMAND = /^\s*(?:open|xdg-open|start)\s+\S+/i;
@@ -13,9 +20,23 @@ const MUTATION_TOOLS = new Set([
13
20
  ]);
14
21
 
15
22
  export function isLaunchOnlyPrompt(prompt: string): boolean {
23
+ if (!prompt || typeof prompt !== 'string') return false;
24
+ const trimmed = prompt.trim();
25
+ if (trimmed.length === 0) return false;
26
+ if (trimmed.split(/\s+/).length > 25 || trimmed.length > 150) return false;
27
+
16
28
  if (/\b(?:run|execute)\s+(?:the\s+)?(?:tests?|checks?|lint|benchmarks?|scripts?|commands?|tools?|creative_apps|resolve_act|memory_recall|native_engine|browser_act|fs_read|sysRun)\b/i.test(prompt)) return false;
17
29
  if (/\b(?:verify|verification|verify_bridge|inspectActive|simulate|probe|audit|analyze|diagnose)\b/i.test(prompt)) return false;
18
- return LAUNCH_VERBS.test(prompt) && !CHANGE_VERBS.test(prompt);
30
+
31
+ if (CREATIVE_WORDS.test(prompt)) return false;
32
+ if (INQUIRY_WORDS.test(prompt)) return false;
33
+ if (CHANGE_VERBS.test(prompt)) return false;
34
+ if (NON_LAUNCH_PHRASES.test(prompt)) return false;
35
+
36
+ return IMPERATIVE_LAUNCH.test(prompt)
37
+ || TARGETED_LAUNCH.test(prompt)
38
+ || URL_OR_FILE_LAUNCH.test(prompt)
39
+ || BROWSER_LAUNCH.test(prompt);
19
40
  }
20
41
 
21
42
  export function isServerLaunchCommand(command: string): boolean {
@@ -243,6 +243,29 @@ export function isAntigravityProvider(provider) {
243
243
  const p = String(provider).toLowerCase();
244
244
  return p === 'antigravity' || p === 'agy' || p.startsWith('antigravity/') || p.startsWith('agy/');
245
245
  }
246
+ export function isAntigravityModel(input) {
247
+ if (typeof input !== 'string' || !input.trim())
248
+ return false;
249
+ const trimmed = input.trim();
250
+ if (ANTIGRAVITY_MODEL_IDS[trimmed])
251
+ return true;
252
+ const lower = trimmed.toLowerCase();
253
+ for (const [key, slug] of Object.entries(ANTIGRAVITY_MODEL_IDS)) {
254
+ if (key.toLowerCase() === lower || slug.toLowerCase() === lower)
255
+ return true;
256
+ }
257
+ if (trimmed.includes('/') ||
258
+ trimmed.startsWith('deepseek') ||
259
+ trimmed.startsWith('qwen') ||
260
+ trimmed.startsWith('kimi') ||
261
+ trimmed.startsWith('gpt-4') ||
262
+ trimmed.startsWith('gpt-5') ||
263
+ trimmed.startsWith('o1') ||
264
+ trimmed.startsWith('o3')) {
265
+ return false;
266
+ }
267
+ return true;
268
+ }
246
269
  export function resolveAgyBinary() {
247
270
  const envPath = process.env.PATH || '';
248
271
  const searchDirs = [
@@ -676,7 +699,8 @@ export class AntigravityProvider extends LLMProvider {
676
699
  lastCumulativeUsage = null;
677
700
  constructor(config = {}) {
678
701
  super(config);
679
- this.model = config.model || 'Gemini 3.8 Flash (Low)';
702
+ const candidate = config.model;
703
+ this.model = (candidate && isAntigravityModel(candidate)) ? candidate : 'Gemini 3.8 Flash (Low)';
680
704
  this.command = config.command || resolveAgyBinary();
681
705
  this.printTimeout = typeof config.printTimeout === 'string' && config.printTimeout.trim()
682
706
  ? config.printTimeout.trim()
@@ -936,10 +960,11 @@ export class AntigravityProvider extends LLMProvider {
936
960
  '--print-timeout',
937
961
  launchOnly ? '90s' : this.printTimeout,
938
962
  '--model',
939
- modelSlug,
940
- '--effort',
941
- effort
963
+ modelSlug
942
964
  ];
965
+ if (effort && (modelSlug.endsWith(`-${effort}`) || /-(low|medium|high|xhigh|max)$/i.test(modelSlug))) {
966
+ args.push('--effort', effort);
967
+ }
943
968
  if (useConversation && this.currentConversationId) {
944
969
  args.push('--conversation', this.currentConversationId);
945
970
  }
@@ -246,6 +246,29 @@ export function isAntigravityProvider(provider?: string | null): boolean {
246
246
  return p === 'antigravity' || p === 'agy' || p.startsWith('antigravity/') || p.startsWith('agy/');
247
247
  }
248
248
 
249
+ export function isAntigravityModel(input?: string | null): boolean {
250
+ if (typeof input !== 'string' || !input.trim()) return false;
251
+ const trimmed = input.trim();
252
+ if (ANTIGRAVITY_MODEL_IDS[trimmed]) return true;
253
+ const lower = trimmed.toLowerCase();
254
+ for (const [key, slug] of Object.entries(ANTIGRAVITY_MODEL_IDS)) {
255
+ if (key.toLowerCase() === lower || slug.toLowerCase() === lower) return true;
256
+ }
257
+ if (
258
+ trimmed.includes('/') ||
259
+ trimmed.startsWith('deepseek') ||
260
+ trimmed.startsWith('qwen') ||
261
+ trimmed.startsWith('kimi') ||
262
+ trimmed.startsWith('gpt-4') ||
263
+ trimmed.startsWith('gpt-5') ||
264
+ trimmed.startsWith('o1') ||
265
+ trimmed.startsWith('o3')
266
+ ) {
267
+ return false;
268
+ }
269
+ return true;
270
+ }
271
+
249
272
  export function resolveAgyBinary(): string {
250
273
  const envPath = process.env.PATH || '';
251
274
  const searchDirs = [
@@ -694,7 +717,8 @@ export class AntigravityProvider extends LLMProvider {
694
717
 
695
718
  constructor(config: ProviderConfig = {}) {
696
719
  super(config);
697
- this.model = config.model || 'Gemini 3.8 Flash (Low)';
720
+ const candidate = config.model;
721
+ this.model = (candidate && isAntigravityModel(candidate)) ? candidate : 'Gemini 3.8 Flash (Low)';
698
722
  this.command = config.command || resolveAgyBinary();
699
723
  this.printTimeout = typeof config.printTimeout === 'string' && config.printTimeout.trim()
700
724
  ? config.printTimeout.trim()
@@ -969,11 +993,13 @@ export class AntigravityProvider extends LLMProvider {
969
993
  '--print-timeout',
970
994
  launchOnly ? '90s' : this.printTimeout,
971
995
  '--model',
972
- modelSlug,
973
- '--effort',
974
- effort
996
+ modelSlug
975
997
  ];
976
998
 
999
+ if (effort && (modelSlug.endsWith(`-${effort}`) || /-(low|medium|high|xhigh|max)$/i.test(modelSlug))) {
1000
+ args.push('--effort', effort);
1001
+ }
1002
+
977
1003
  if (useConversation && this.currentConversationId) {
978
1004
  args.push('--conversation', this.currentConversationId);
979
1005
  }
@@ -14,6 +14,7 @@ export class ChatRenderer {
14
14
  _activeReasoning?: boolean;
15
15
  handle(message: { type: string; [key: string]: unknown }): boolean;
16
16
  resetTurn(): void;
17
+ turnFooter(durationMs?: number): void;
17
18
  onAgentReasoning(message: { content?: string; streaming?: boolean; elapsedMs?: number }): void;
18
19
  renderReasoning(content: string, options?: { streaming?: boolean; durationText?: string; collapsed?: boolean; startLine?: number }): void;
19
20
  scrollThinkingPanel?(key: unknown, surface: unknown): boolean;
@@ -25,7 +25,7 @@ import { composerWidth, openingRows, sessionRows } from './layout.js';
25
25
  import { sessionComposerWidth } from './sessionSidebar.js';
26
26
  import { chatProseWidth, wrappedChatRows } from './textLayout.js';
27
27
  import { activityRows } from './activityLayout.js';
28
- import { cleanToolOutputPreview, normalizeHistoricalToolResult } from './toolOutputNormalizer.js';
28
+ import { cleanToolOutputPreview, normalizeHistoricalToolResult, normalizeHistoricalExternalAction } from './toolOutputNormalizer.js';
29
29
  import { formatMarkdownMath } from './markdownMath.js';
30
30
  import { renderThinkingFrame } from './thinkingBox.js';
31
31
 
@@ -590,17 +590,40 @@ export class ChatRenderer {
590
590
  this.resetTurn();
591
591
  this.renderUserMessage(msg.content);
592
592
  } else if (role === 'assistant') {
593
- // If assistant has textual content, render it
594
- const text = typeof msg.content === 'string'
595
- ? msg.content
596
- : (Array.isArray(msg.content)
597
- ? msg.content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
598
- : String(msg.content || ''));
599
- if (text.trim()) {
600
- this.renderAssistantMessage(text);
593
+ // 1. Restore reasoning content as an auto-minimized thinking box
594
+ const reasoning = typeof msg.reasoning_content === 'string'
595
+ ? msg.reasoning_content.trim()
596
+ : (Array.isArray(msg.thinking_blocks)
597
+ ? msg.thinking_blocks.map(b => (typeof b === 'string' ? b : b?.thinking || b?.text || '')).filter(Boolean).join('\n').trim()
598
+ : '');
599
+ if (reasoning) {
600
+ const meta = {
601
+ reasoning: true,
602
+ done: true,
603
+ streaming: false,
604
+ collapsed: true,
605
+ durationText: '',
606
+ content: reasoning,
607
+ scrollStart: 0
608
+ };
609
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
610
+ streaming: false,
611
+ durationText: '',
612
+ collapsed: Boolean(meta.collapsed),
613
+ startLine: 0
614
+ }), meta);
615
+ }
616
+
617
+ // 2. Restore external / native ACP tool executions
618
+ if (Array.isArray(msg.external_actions) && msg.external_actions.length > 0) {
619
+ for (const ext of msg.external_actions) {
620
+ const { toolName, args, result } = normalizeHistoricalExternalAction(ext);
621
+ this.onStepStart({ tool: toolName, args });
622
+ this.onStepComplete({ tool: toolName, result, elapsed: '' });
623
+ }
601
624
  }
602
625
 
603
- // If assistant invoked tool calls, render each tool step and pair with its result
626
+ // 3. If assistant invoked tool calls, render each tool step and pair with its result
604
627
  if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
605
628
  for (const call of msg.tool_calls) {
606
629
  const toolName = call.function?.name || call.name || 'tool';
@@ -647,6 +670,16 @@ export class ChatRenderer {
647
670
  }
648
671
  }
649
672
  }
673
+
674
+ // 4. If assistant has textual content, render it
675
+ const text = typeof msg.content === 'string'
676
+ ? msg.content
677
+ : (Array.isArray(msg.content)
678
+ ? msg.content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
679
+ : String(msg.content || ''));
680
+ if (text.trim()) {
681
+ this.renderAssistantMessage(text);
682
+ }
650
683
  } else if (role === 'tool') {
651
684
  // Standalone or un-paired tool message (e.g. from compacted session turns)
652
685
  if (!renderedToolMessages.has(msg)) {
@@ -757,7 +790,7 @@ export class ChatRenderer {
757
790
  scrollStart: 0
758
791
  };
759
792
  this.frame('reasoning', () => this.renderReasoning(meta.content, {
760
- streaming: true,
793
+ streaming: Boolean(meta.streaming),
761
794
  durationText: meta.durationText,
762
795
  collapsed: Boolean(meta.collapsed),
763
796
  startLine: Number(meta.scrollStart) || 0
@@ -770,7 +803,7 @@ export class ChatRenderer {
770
803
  if (meta.collapsed === undefined) meta.collapsed = false;
771
804
  if (meta.scrollStart === undefined) meta.scrollStart = 0;
772
805
  this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
773
- streaming: true,
806
+ streaming: Boolean(meta.streaming),
774
807
  durationText: meta.durationText,
775
808
  collapsed: Boolean(meta.collapsed),
776
809
  startLine: Number(meta.scrollStart) || 0
@@ -786,10 +819,10 @@ export class ChatRenderer {
786
819
  meta.done = true;
787
820
  meta.durationText = durationText;
788
821
  meta.content = content;
789
- if (meta.collapsed === undefined) meta.collapsed = false;
822
+ if (meta.collapsed === undefined) meta.collapsed = Boolean(msg.collapsed);
790
823
  if (meta.scrollStart === undefined) meta.scrollStart = 0;
791
824
  this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
792
- streaming: false,
825
+ streaming: Boolean(meta.streaming),
793
826
  durationText: meta.durationText,
794
827
  collapsed: Boolean(meta.collapsed),
795
828
  startLine: Number(meta.scrollStart) || 0
@@ -801,11 +834,11 @@ export class ChatRenderer {
801
834
  streaming: false,
802
835
  durationText,
803
836
  content,
804
- collapsed: false,
837
+ collapsed: Boolean(msg.collapsed),
805
838
  scrollStart: 0
806
839
  };
807
840
  this.frame('reasoning', () => this.renderReasoning(meta.content, {
808
- streaming: false,
841
+ streaming: Boolean(meta.streaming),
809
842
  durationText: meta.durationText,
810
843
  collapsed: Boolean(meta.collapsed),
811
844
  startLine: Number(meta.scrollStart) || 0
@@ -81,8 +81,37 @@ export class CodeStreamRenderer extends ChatRenderer {
81
81
  this.activeCode = null;
82
82
  this.modelNote = '';
83
83
  this.lastReasoning = '';
84
+ this.collapseFinishedReasoningFrames(true);
84
85
  super.resetTurn();
85
86
  }
87
+ turnFooter(durationMs) {
88
+ this.collapseFinishedReasoningFrames(true);
89
+ super.turnFooter(durationMs);
90
+ }
91
+ /**
92
+ * Auto-collapses completed thinking box frames when a session turn finishes,
93
+ * keeping the conversation viewport clean while preserving interactive click-to-expand.
94
+ */
95
+ collapseFinishedReasoningFrames(forceAll = false) {
96
+ const transcript = this.transcript;
97
+ if (!transcript || !Array.isArray(transcript.frames))
98
+ return;
99
+ let changed = false;
100
+ for (const frame of transcript.frames) {
101
+ if (frame?.meta?.reasoning === true && (forceAll || frame.meta.userInteracted !== true) && frame.meta.collapsed !== true) {
102
+ frame.meta.collapsed = true;
103
+ frame.meta.streaming = false;
104
+ frame.rows = null;
105
+ frame.renderedWidth = -1;
106
+ changed = true;
107
+ }
108
+ }
109
+ if (changed) {
110
+ transcript.cache = null;
111
+ transcript.revision++;
112
+ transcript.changed();
113
+ }
114
+ }
86
115
  handle(message) {
87
116
  if (message?.type === 'notice' && message.nativeStep === true) {
88
117
  this.stepCount = (this.stepCount || 0) + 1;
@@ -104,13 +133,15 @@ export class CodeStreamRenderer extends ChatRenderer {
104
133
  const note = content.trim().split('\n').at(-1) || '';
105
134
  this.modelNote = note.slice(-140);
106
135
  this.paintCodePanel(this.activeCode);
107
- if (message.streaming === false)
136
+ if (message.streaming === false) {
108
137
  this.lastReasoning = '';
138
+ }
109
139
  return true;
110
140
  }
111
141
  const handled = super.handle(message);
112
- if (message.streaming === false)
142
+ if (message.streaming === false) {
113
143
  this.lastReasoning = '';
144
+ }
114
145
  return handled;
115
146
  }
116
147
  if (['agent_message', 'agent_activity', 'notice', 'budget_warning', 'step_start', 'task_complete', 'error', 'agent_plan'].includes(message?.type || '')) {
@@ -119,6 +150,9 @@ export class CodeStreamRenderer extends ChatRenderer {
119
150
  }
120
151
  this._activeReasoning = false;
121
152
  this.lastReasoning = '';
153
+ if (message?.type === 'task_complete' || (message?.type === 'agent_message' && message.streaming !== true)) {
154
+ this.collapseFinishedReasoningFrames(true);
155
+ }
122
156
  if (['step_start', 'task_complete', 'error'].includes(message?.type || '')
123
157
  || (message?.type === 'agent_message' && message.streaming !== true)) {
124
158
  this.activeCode = null;
@@ -99,9 +99,39 @@ export class CodeStreamRenderer extends ChatRenderer {
99
99
  this.activeCode = null;
100
100
  this.modelNote = '';
101
101
  this.lastReasoning = '';
102
+ this.collapseFinishedReasoningFrames(true);
102
103
  super.resetTurn();
103
104
  }
104
105
 
106
+ override turnFooter(durationMs: number): void {
107
+ this.collapseFinishedReasoningFrames(true);
108
+ super.turnFooter(durationMs);
109
+ }
110
+
111
+ /**
112
+ * Auto-collapses completed thinking box frames when a session turn finishes,
113
+ * keeping the conversation viewport clean while preserving interactive click-to-expand.
114
+ */
115
+ collapseFinishedReasoningFrames(forceAll = false): void {
116
+ const transcript = this.transcript as unknown as CodeTranscript | null;
117
+ if (!transcript || !Array.isArray(transcript.frames)) return;
118
+ let changed = false;
119
+ for (const frame of transcript.frames) {
120
+ if (frame?.meta?.reasoning === true && (forceAll || frame.meta.userInteracted !== true) && frame.meta.collapsed !== true) {
121
+ frame.meta.collapsed = true;
122
+ frame.meta.streaming = false;
123
+ frame.rows = null;
124
+ frame.renderedWidth = -1;
125
+ changed = true;
126
+ }
127
+ }
128
+ if (changed) {
129
+ transcript.cache = null;
130
+ transcript.revision++;
131
+ transcript.changed();
132
+ }
133
+ }
134
+
105
135
  override handle(message: RendererEvent): boolean {
106
136
  if (message?.type === 'notice' && message.nativeStep === true) {
107
137
  this.stepCount = (this.stepCount || 0) + 1;
@@ -122,11 +152,15 @@ export class CodeStreamRenderer extends ChatRenderer {
122
152
  const note = content.trim().split('\n').at(-1) || '';
123
153
  this.modelNote = note.slice(-140);
124
154
  this.paintCodePanel(this.activeCode);
125
- if (message.streaming === false) this.lastReasoning = '';
155
+ if (message.streaming === false) {
156
+ this.lastReasoning = '';
157
+ }
126
158
  return true;
127
159
  }
128
160
  const handled = super.handle(message);
129
- if (message.streaming === false) this.lastReasoning = '';
161
+ if (message.streaming === false) {
162
+ this.lastReasoning = '';
163
+ }
130
164
  return handled;
131
165
  }
132
166
  if (['agent_message', 'agent_activity', 'notice', 'budget_warning', 'step_start', 'task_complete', 'error', 'agent_plan'].includes(message?.type || '')) {
@@ -135,6 +169,9 @@ export class CodeStreamRenderer extends ChatRenderer {
135
169
  }
136
170
  this._activeReasoning = false;
137
171
  this.lastReasoning = '';
172
+ if (message?.type === 'task_complete' || (message?.type === 'agent_message' && message.streaming !== true)) {
173
+ this.collapseFinishedReasoningFrames(true);
174
+ }
138
175
  if (['step_start', 'task_complete', 'error'].includes(message?.type || '')
139
176
  || (message?.type === 'agent_message' && message.streaming !== true)) {
140
177
  this.activeCode = null;
@@ -115,6 +115,7 @@ export function handleMessageMouse(host, loop, event) {
115
115
  const frame = Array.isArray(frames) ? frames.find(f => f.id === rawMarker.id) : null;
116
116
  if (frame && frame.meta && frame.meta.reasoning) {
117
117
  frame.meta.collapsed = !frame.meta.collapsed;
118
+ frame.meta.userInteracted = true;
118
119
  frame.rows = null;
119
120
  frame.renderedWidth = -1;
120
121
  if (transcript) {
@@ -22,7 +22,7 @@ export interface MessageMarker {
22
22
  id: number;
23
23
  kind: string;
24
24
  row: number;
25
- meta?: { messageText?: string; reasoning?: boolean; collapsed?: boolean } | null;
25
+ meta?: { messageText?: string; reasoning?: boolean; collapsed?: boolean; userInteracted?: boolean } | null;
26
26
  }
27
27
 
28
28
  interface MousePoint { x: number; y: number }
@@ -188,7 +188,7 @@ export function handleMessageMouse(
188
188
  const transcript = surface.transcript as unknown as {
189
189
  frames?: Array<{
190
190
  id: number;
191
- meta?: { reasoning?: boolean; collapsed?: boolean } | null;
191
+ meta?: { reasoning?: boolean; collapsed?: boolean; userInteracted?: boolean } | null;
192
192
  rows?: unknown;
193
193
  renderedWidth?: number;
194
194
  }>;
@@ -200,6 +200,7 @@ export function handleMessageMouse(
200
200
  const frame = Array.isArray(frames) ? frames.find(f => f.id === rawMarker.id) : null;
201
201
  if (frame && frame.meta && frame.meta.reasoning) {
202
202
  frame.meta.collapsed = !frame.meta.collapsed;
203
+ frame.meta.userInteracted = true;
203
204
  frame.rows = null;
204
205
  frame.renderedWidth = -1;
205
206
  if (transcript) {
@@ -9,7 +9,7 @@ import { paint, bold, dim, GLYPHS } from './theme.js';
9
9
  // @ts-expect-error untyped local TUI selectList
10
10
  import { fuzzyFilter } from './selectList.js';
11
11
  import { loadConfig, saveConfig } from '../config.js';
12
- import { getAvailableProvidersOverview, resolveAvailableProvidersOverview } from '../dynamicCatalogue.js';
12
+ import { getAvailableProvidersOverview, resolveAvailableProvidersOverview, resolveAvailableModels } from '../dynamicCatalogue.js';
13
13
  async function showConfiguringAnimation(providerLabel) {
14
14
  if (!process.stdout.isTTY)
15
15
  return;
@@ -407,6 +407,10 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
407
407
  config['providerKeys'][target.providerId] = existingKey;
408
408
  }
409
409
  store.saveConfig(config);
410
+ // Proactively refresh live models in the background for this active provider
411
+ if (existingKey || target.providerId === 'ollama') {
412
+ void resolveAvailableModels(target.providerId, { ...config, apiKey: existingKey }, true).catch(() => { });
413
+ }
410
414
  if (options.loop) {
411
415
  options.loop.config = config;
412
416
  if (typeof options.loop.updateTierLimits === 'function') {
@@ -442,6 +446,8 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
442
446
  config['providerKeys'] = providerKeys;
443
447
  config['providerKeys'][target.providerId] = cleanKey;
444
448
  store.saveConfig(config);
449
+ // Proactively refresh live models in the background with the newly saved key
450
+ void resolveAvailableModels(target.providerId, { ...config, apiKey: cleanKey }, true).catch(() => { });
445
451
  if (options.loop) {
446
452
  options.loop.config = config;
447
453
  if (typeof options.loop.updateTierLimits === 'function') {
@@ -13,6 +13,7 @@ import { loadConfig, saveConfig } from '../config.js';
13
13
  import {
14
14
  getAvailableProvidersOverview,
15
15
  resolveAvailableProvidersOverview,
16
+ resolveAvailableModels,
16
17
  type ProviderOverview
17
18
  } from '../dynamicCatalogue.js';
18
19
 
@@ -511,6 +512,11 @@ export async function runInteractiveModelPicker(
511
512
  }
512
513
  store.saveConfig(config);
513
514
 
515
+ // Proactively refresh live models in the background for this active provider
516
+ if (existingKey || target.providerId === 'ollama') {
517
+ void resolveAvailableModels(target.providerId, { ...config, apiKey: existingKey }, true).catch(() => {});
518
+ }
519
+
514
520
  if (options.loop) {
515
521
  options.loop.config = config;
516
522
  if (typeof options.loop.updateTierLimits === 'function') {
@@ -551,6 +557,9 @@ export async function runInteractiveModelPicker(
551
557
  config['providerKeys'][target.providerId] = cleanKey;
552
558
  store.saveConfig(config);
553
559
 
560
+ // Proactively refresh live models in the background with the newly saved key
561
+ void resolveAvailableModels(target.providerId, { ...config, apiKey: cleanKey }, true).catch(() => {});
562
+
554
563
  if (options.loop) {
555
564
  options.loop.config = config;
556
565
  if (typeof options.loop.updateTierLimits === 'function') {
package/src/tui/setup.js CHANGED
@@ -131,6 +131,9 @@ export async function runSetup(ui, providers, store, workspace = process.cwd())
131
131
  else
132
132
  delete saved.baseUrl;
133
133
  store.saveConfig(saved);
134
+ if (apiKey || provider.id === 'ollama' || isLocalAgent(provider.id)) {
135
+ void resolveAvailableModels(provider.id, saved, true).catch(() => { });
136
+ }
134
137
  return { provider: provider.id, model };
135
138
  }
136
139
  }
package/src/tui/setup.ts CHANGED
@@ -126,6 +126,9 @@ export async function runSetup(ui: SetupUI, providers: SetupProvider[], store: {
126
126
  const saved: Config = next;
127
127
  if (baseUrl) saved.baseUrl = baseUrl; else delete saved.baseUrl;
128
128
  store.saveConfig(saved);
129
+ if (apiKey || provider.id === 'ollama' || isLocalAgent(provider.id)) {
130
+ void resolveAvailableModels(provider.id, saved, true).catch(() => {});
131
+ }
129
132
  return { provider: provider.id, model };
130
133
  }
131
134
  }
@@ -1,4 +1,33 @@
1
1
  import fs from 'node:fs';
2
+ /**
3
+ * Normalizes an external/native action record for historical transcript restoration,
4
+ * reconstructing arguments and ensuring verified success/failure status.
5
+ */
6
+ export function normalizeHistoricalExternalAction(ext) {
7
+ const toolName = typeof ext?.name === 'string' && ext.name.trim() ? ext.name.trim() : 'tool';
8
+ const detail = typeof ext?.detail === 'string' ? ext.detail.trim() : '';
9
+ const status = typeof ext?.status === 'string' ? ext.status.toLowerCase().trim() : '';
10
+ const isFailed = status === 'failed' || status === 'error';
11
+ const success = !isFailed;
12
+ const rawParams = ext?.parameters && typeof ext.parameters === 'object' && !Array.isArray(ext.parameters)
13
+ ? { ...ext.parameters }
14
+ : {};
15
+ const lowerTool = toolName.toLowerCase();
16
+ const isFileTool = ['read_file', 'write_file', 'edit_file', 'fs_read', 'fs_write', 'fs_edit', 'view_file'].includes(lowerTool);
17
+ const isCommandTool = ['run_command', 'bash', 'terminal', 'sh', 'zsh', 'sysrun', 'sysrunbg'].includes(lowerTool);
18
+ const args = {
19
+ ...rawParams,
20
+ ...(detail ? { detail } : {}),
21
+ ...(detail && isFileTool && !rawParams.path && !rawParams.file_path && !rawParams.filePath ? { path: detail } : {}),
22
+ ...(detail && isCommandTool && !rawParams.command && !rawParams.cmd ? { command: detail } : {})
23
+ };
24
+ const result = {
25
+ success,
26
+ output: '',
27
+ ...(isFailed ? { error: typeof ext?.error === 'string' && ext.error ? ext.error : (detail || 'failed') } : {})
28
+ };
29
+ return { toolName, args, result };
30
+ }
2
31
  const DECAY_MARKER = '[decayed]';
3
32
  const SPILL_HEADER_PREFIX = '=== CAUSYNE TOOL OUTPUT';
4
33
  /**
@@ -14,6 +14,59 @@ export interface NormalizedHistoricalToolResult {
14
14
  plan?: Array<Record<string, unknown>> | undefined;
15
15
  }
16
16
 
17
+ export interface HistoricalExternalAction {
18
+ id?: string | undefined;
19
+ name?: string | undefined;
20
+ status?: string | undefined;
21
+ detail?: string | undefined;
22
+ parameters?: Record<string, unknown> | undefined;
23
+ error?: string | undefined;
24
+ }
25
+
26
+ export interface NormalizedExternalActionResult {
27
+ toolName: string;
28
+ args: Record<string, unknown>;
29
+ result: {
30
+ success: boolean;
31
+ output: string;
32
+ error?: string | undefined;
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Normalizes an external/native action record for historical transcript restoration,
38
+ * reconstructing arguments and ensuring verified success/failure status.
39
+ */
40
+ export function normalizeHistoricalExternalAction(ext: HistoricalExternalAction | null | undefined): NormalizedExternalActionResult {
41
+ const toolName = typeof ext?.name === 'string' && ext.name.trim() ? ext.name.trim() : 'tool';
42
+ const detail = typeof ext?.detail === 'string' ? ext.detail.trim() : '';
43
+ const status = typeof ext?.status === 'string' ? ext.status.toLowerCase().trim() : '';
44
+ const isFailed = status === 'failed' || status === 'error';
45
+ const success = !isFailed;
46
+
47
+ const rawParams = ext?.parameters && typeof ext.parameters === 'object' && !Array.isArray(ext.parameters)
48
+ ? { ...ext.parameters }
49
+ : {};
50
+ const lowerTool = toolName.toLowerCase();
51
+ const isFileTool = ['read_file', 'write_file', 'edit_file', 'fs_read', 'fs_write', 'fs_edit', 'view_file'].includes(lowerTool);
52
+ const isCommandTool = ['run_command', 'bash', 'terminal', 'sh', 'zsh', 'sysrun', 'sysrunbg'].includes(lowerTool);
53
+
54
+ const args: Record<string, unknown> = {
55
+ ...rawParams,
56
+ ...(detail ? { detail } : {}),
57
+ ...(detail && isFileTool && !rawParams.path && !rawParams.file_path && !rawParams.filePath ? { path: detail } : {}),
58
+ ...(detail && isCommandTool && !rawParams.command && !rawParams.cmd ? { command: detail } : {})
59
+ };
60
+
61
+ const result: { success: boolean; output: string; error?: string | undefined } = {
62
+ success,
63
+ output: '',
64
+ ...(isFailed ? { error: typeof ext?.error === 'string' && ext.error ? ext.error : (detail || 'failed') } : {})
65
+ };
66
+
67
+ return { toolName, args, result };
68
+ }
69
+
17
70
  const DECAY_MARKER = '[decayed]';
18
71
  const SPILL_HEADER_PREFIX = '=== CAUSYNE TOOL OUTPUT';
19
72