@causyne/agent 1.20.8 → 1.20.9

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.
@@ -2,7 +2,7 @@ import { spawn } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
5
- import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall } from './base.js';
5
+ import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall, type ChatResponseUsage } from './base.js';
6
6
 
7
7
  /**
8
8
  * Baseline fallback models for instant offline availability.
@@ -507,6 +507,7 @@ export class AntigravityProvider extends LLMProvider {
507
507
  printTimeout: string;
508
508
  currentConversationId: string | null = null;
509
509
  lastTaskId: string | null = null;
510
+ private lastCumulativeUsage: { conversationId: string; input: number; output: number; thinking: number; cacheRead: number } | null = null;
510
511
 
511
512
  constructor(config: ProviderConfig = {}) {
512
513
  super(config);
@@ -586,7 +587,7 @@ export class AntigravityProvider extends LLMProvider {
586
587
  '[Environment State & Idempotency Directive]\n' +
587
588
  'Reuse relevant verified tool results from this session, and check uncertain prerequisites before relying on them.\n\n' +
588
589
  '[Language & Communication Directive]\n' +
589
- 'Dynamically reflect and match the exact language used by the user in their prompt. If the user writes in English, you must respond strictly in English. Default to English for all responses and reasoning. Never default to Indonesian or send canned greetings in Indonesian.'
590
+ 'Dynamically reflect and match the exact language used by the user in their prompt. Respond naturally in that same language. Never send conversational pleasantries or canned greetings.'
590
591
  );
591
592
 
592
593
  if (tools && tools.length > 0) {
@@ -763,16 +764,20 @@ export class AntigravityProvider extends LLMProvider {
763
764
  const currentSessionKey = (options as any).conversationId || (options as any).taskId || null;
764
765
  if (currentSessionKey && currentSessionKey !== this.lastTaskId) {
765
766
  this.currentConversationId = null;
767
+ this.lastCumulativeUsage = null;
766
768
  this.lastTaskId = currentSessionKey;
767
769
  }
768
770
  if (messages.length <= 1) {
769
771
  this.currentConversationId = null;
772
+ this.lastCumulativeUsage = null;
770
773
  }
771
774
 
772
775
  const useConversation = Boolean(this.currentConversationId);
776
+ const resumedConversationId = this.currentConversationId;
773
777
  const latestUserMessage = [...messages].reverse().find(message => message.role === 'user');
774
778
  const latestPrompt = typeof latestUserMessage?.content === 'string' ? latestUserMessage.content : '';
775
779
  const launchOnly = (options as any).taskIntent === 'launch' || isLaunchOnlyPrompt(latestPrompt);
780
+ const desktopTask = (options as any).taskArchetype === 'desktop_personalization';
776
781
  let promptText: string;
777
782
 
778
783
  if (useConversation) {
@@ -797,6 +802,13 @@ export class AntigravityProvider extends LLMProvider {
797
802
  'Do not create, edit, delete, install, or regenerate files. Do not claim the app opened unless a tool confirmed it. ' +
798
803
  'Use Causyne tool calls for commands and desktop opening.\n\n' + promptText;
799
804
  }
805
+ if (desktopTask) {
806
+ promptText = '[Current desktop task: finish and verify the requested change]\n' +
807
+ 'Use only the tools needed. Search and download alone are not completion. ' +
808
+ 'After setting the desktop picture, read back the actual system wallpaper and compare it with the intended image. ' +
809
+ 'If a command is denied or the readback does not confirm the change, report the blocker honestly. ' +
810
+ 'Keep native tool actions within 12; use Causyne tool calls when a native action is blocked.\n\n' + promptText;
811
+ }
800
812
 
801
813
  const modelSlug = resolveAgyModelId(this.model);
802
814
  const effort = resolveAgyEffort(this.model);
@@ -859,8 +871,39 @@ export class AntigravityProvider extends LLMProvider {
859
871
  detail?: string | undefined;
860
872
  }[] = [];
861
873
  let childClosed = false;
874
+ const terminateChild = () => {
875
+ try {
876
+ child.kill('SIGTERM');
877
+ setTimeout(() => {
878
+ if (!childClosed) child.kill('SIGKILL');
879
+ }, 1000).unref();
880
+ } catch {
881
+ // A process that already exited needs no further action.
882
+ }
883
+ };
884
+ const maxNativeActions = desktopTask ? 12 : Infinity;
885
+ let nativeActionStarts = 0;
886
+ const seenNativeActionSteps = new Set<number>();
887
+ // Antigravity's result usage is cumulative across the conversation, but
888
+ // DONE step updates carry usage for that step. Keep a turn-local subtotal
889
+ // so a single headless run cannot consume an entire task budget unseen.
890
+ const completedUsageSteps = new Set<number>();
891
+ const partialUsage: ChatResponseUsage = {
892
+ promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0,
893
+ thinkingTokens: 0, measurement: 'provider_reported', cacheMeasurement: 'provider_reported'
894
+ };
895
+ const tokenLimit = Number(options.maxTokensThisCall);
896
+ const enforceTokenLimit = Number.isFinite(tokenLimit) && tokenLimit > 0;
897
+ const wallTimer = desktopTask ? setTimeout(() => {
898
+ const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.') as Error & { code: string };
899
+ error.code = 'AGY_DESKTOP_TASK_LIMIT';
900
+ safeReject(error);
901
+ terminateChild();
902
+ }, 180_000) : null;
903
+ wallTimer?.unref();
862
904
 
863
905
  const cleanup = () => {
906
+ if (wallTimer) clearTimeout(wallTimer);
864
907
  if (options.signal) {
865
908
  options.signal.removeEventListener('abort', onAbort);
866
909
  }
@@ -881,14 +924,7 @@ export class AntigravityProvider extends LLMProvider {
881
924
  };
882
925
 
883
926
  const onAbort = () => {
884
- try {
885
- child.kill('SIGTERM');
886
- setTimeout(() => {
887
- if (!childClosed) child.kill('SIGKILL');
888
- }, 1000).unref();
889
- } catch {
890
- // ignore kill errors
891
- }
927
+ terminateChild();
892
928
  const abortErr = new Error('Turn aborted by user or timeout.');
893
929
  abortErr.name = 'AbortError';
894
930
  safeReject(abortErr);
@@ -931,15 +967,52 @@ export class AntigravityProvider extends LLMProvider {
931
967
  }
932
968
  } else if (event.event === 'step_update') {
933
969
  const stepUpdate = event.step_update;
970
+ const usage = stepUpdate?.usage;
971
+ const usageStepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
972
+ if (stepUpdate?.state === 'DONE' && usage && Number.isFinite(usageStepIndex)
973
+ && !completedUsageSteps.has(usageStepIndex)) {
974
+ const input = Number(usage.input_tokens);
975
+ const output = Number(usage.output_tokens);
976
+ if (Number.isFinite(input) && input >= 0 && Number.isFinite(output) && output >= 0) {
977
+ completedUsageSteps.add(usageStepIndex);
978
+ partialUsage.promptTokens += input;
979
+ partialUsage.completionTokens += output;
980
+ partialUsage.cachedPromptTokens = (partialUsage.cachedPromptTokens || 0)
981
+ + (Number(usage.cache_read_tokens) || 0);
982
+ partialUsage.thinkingTokens = (partialUsage.thinkingTokens || 0)
983
+ + (Number(usage.thinking_tokens) || 0);
984
+ if (enforceTokenLimit && partialUsage.promptTokens + partialUsage.completionTokens >= tokenLimit) {
985
+ this.currentConversationId = null;
986
+ const error = Object.assign(
987
+ new Error(`Antigravity token budget reached during this turn: at least ${partialUsage.promptTokens + partialUsage.completionTokens} tokens reported for a ${tokenLimit}-token remaining budget. The task outcome is unverified.`),
988
+ { code: 'AGY_TOKEN_BUDGET', partialUsage: { ...partialUsage } }
989
+ );
990
+ safeReject(error);
991
+ terminateChild();
992
+ return;
993
+ }
994
+ }
995
+ }
934
996
  const delta = stepUpdate?.text_delta;
935
997
  const stepType = stepUpdate?.step_type;
936
998
  if (stepType === 'tool') {
937
999
  const state = stepUpdate?.state;
1000
+ const stepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
1001
+ const newNativeAction = (state === 'ACTIVE' || (state === 'DONE' && Number.isFinite(stepIndex)))
1002
+ && (!Number.isFinite(stepIndex) || !seenNativeActionSteps.has(stepIndex));
1003
+ if (newNativeAction && Number.isFinite(stepIndex)) seenNativeActionSteps.add(stepIndex);
1004
+ if (desktopTask && newNativeAction && ++nativeActionStarts > maxNativeActions) {
1005
+ const error = new Error(`Antigravity exceeded ${maxNativeActions} native actions for this desktop task. Outcome is unverified.`) as Error & { code: string };
1006
+ error.code = 'AGY_NATIVE_ACTION_BUDGET';
1007
+ safeReject(error);
1008
+ terminateChild();
1009
+ return;
1010
+ }
938
1011
  const toolInfo = stepUpdate?.tool_info || {};
939
1012
  const name = stepUpdate?.tool_name || toolInfo?.name;
940
- const status = state === 'DONE'
941
- ? 'completed'
942
- : (state === 'ERROR' ? 'failed' : 'running');
1013
+ const status = state === 'DONE' || state === 'ERROR'
1014
+ ? (state === 'ERROR' || toolInfo?.error ? 'failed' : 'completed')
1015
+ : 'running';
943
1016
  const rawParams = (toolInfo && typeof toolInfo === 'object' && toolInfo.parameters) ||
944
1017
  (stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
945
1018
  (toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
@@ -1036,6 +1109,9 @@ export class AntigravityProvider extends LLMProvider {
1036
1109
 
1037
1110
  child.on('close', (code: number | null) => {
1038
1111
  childClosed = true;
1112
+ // A budget or user abort has already settled this call. Do not accept
1113
+ // a late result from the terminated process as a resumable session.
1114
+ if (isSettled) return;
1039
1115
  // Process any remaining bytes in stdoutBuffer
1040
1116
  if (stdoutBuffer.trim()) {
1041
1117
  try {
@@ -1055,9 +1131,10 @@ export class AntigravityProvider extends LLMProvider {
1055
1131
  }
1056
1132
  }
1057
1133
 
1058
- if (code !== 0 || finalResultObj?.status === 'ERROR') {
1134
+ if (code !== 0 || (finalResultObj?.status && finalResultObj.status !== 'SUCCESS')) {
1059
1135
  if (useConversation) this.currentConversationId = null;
1060
- const errDetail = finalResultObj?.error || stderrBuffer.trim() || `exit code ${code}`;
1136
+ const errDetail = finalResultObj?.error || stderrBuffer.trim() ||
1137
+ `terminal status ${finalResultObj?.status || 'unknown'}, exit code ${code}`;
1061
1138
  safeReject(new Error(`Antigravity Agent (agy) failed: ${errDetail}`));
1062
1139
  return;
1063
1140
  }
@@ -1148,16 +1225,34 @@ export class AntigravityProvider extends LLMProvider {
1148
1225
  const missingResultEvent =
1149
1226
  finalResultObj === null && deniedActions.length === 0 && toolCalls.length === 0;
1150
1227
 
1151
- const promptTokens = Number(finalResultObj?.usage?.input_tokens) || Math.ceil(promptText.length / 4);
1152
- const completionTokens = Number(finalResultObj?.usage?.output_tokens) || Math.ceil(rawContent.length / 4);
1153
- const thinkingTokens = Number(finalResultObj?.usage?.thinking_tokens) || 0;
1228
+ const usageIsReported = finalResultObj?.usage?.input_tokens != null
1229
+ && finalResultObj?.usage?.output_tokens != null
1230
+ && Number.isFinite(Number(finalResultObj.usage.input_tokens))
1231
+ && Number.isFinite(Number(finalResultObj.usage.output_tokens));
1232
+ const cumulative = {
1233
+ input: usageIsReported ? Number(finalResultObj.usage.input_tokens) : Math.ceil(promptText.length / 4),
1234
+ output: usageIsReported ? Number(finalResultObj.usage.output_tokens) : Math.ceil(rawContent.length / 4),
1235
+ thinking: Number(finalResultObj?.usage?.thinking_tokens) || 0,
1236
+ cacheRead: Number(finalResultObj?.usage?.cache_read_tokens) || 0
1237
+ };
1238
+ const prior = useConversation && resumedConversationId === this.lastCumulativeUsage?.conversationId
1239
+ ? this.lastCumulativeUsage : null;
1240
+ const delta = (current: number, previous: number): number => current >= previous ? current - previous : current;
1241
+ const promptTokens = prior && usageIsReported ? delta(cumulative.input, prior.input) : cumulative.input;
1242
+ const completionTokens = prior && usageIsReported ? delta(cumulative.output, prior.output) : cumulative.output;
1243
+ const thinkingTokens = prior && usageIsReported ? delta(cumulative.thinking, prior.thinking) : cumulative.thinking;
1244
+ const cachedPromptTokens = prior && usageIsReported ? delta(cumulative.cacheRead, prior.cacheRead) : cumulative.cacheRead;
1154
1245
 
1155
1246
  const response: ChatResponse = {
1156
1247
  content,
1157
1248
  usage: {
1158
1249
  promptTokens,
1159
- completionTokens: completionTokens + thinkingTokens,
1160
- cachedPromptTokens: Number(finalResultObj?.usage?.cache_read_tokens) || 0
1250
+ completionTokens,
1251
+ thinkingTokens,
1252
+ cachedPromptTokens,
1253
+ measurement: usageIsReported ? 'provider_reported' : 'text_estimate',
1254
+ cacheMeasurement: finalResultObj?.usage?.cache_read_tokens != null
1255
+ ? 'provider_reported' : 'unavailable'
1161
1256
  }
1162
1257
  };
1163
1258
 
@@ -1177,6 +1272,9 @@ export class AntigravityProvider extends LLMProvider {
1177
1272
  response.incompleteTurn = true;
1178
1273
  }
1179
1274
 
1275
+ if (usageIsReported && this.currentConversationId) {
1276
+ this.lastCumulativeUsage = { conversationId: this.currentConversationId, ...cumulative };
1277
+ }
1180
1278
  safeResolve(response);
1181
1279
  });
1182
1280
  });
@@ -1194,7 +1292,9 @@ export class AntigravityProvider extends LLMProvider {
1194
1292
  throw err;
1195
1293
  }
1196
1294
  const canRetryResetConversation =
1197
- hadConversation && !this.currentConversationId && (err as any)?.code !== 'AGY_NATIVE_ACTION_DENIED';
1295
+ hadConversation && !this.currentConversationId
1296
+ && (err as any)?.code !== 'AGY_NATIVE_ACTION_DENIED'
1297
+ && (err as any)?.code !== 'AGY_TOKEN_BUDGET';
1198
1298
  if (attempt < maxRetries && (this._isTransientError(err.message) || canRetryResetConversation)) {
1199
1299
  attempt++;
1200
1300
  const delay = attempt * 1200;
@@ -14,6 +14,8 @@ export interface ChatResponseUsage {
14
14
  promptTokens: number;
15
15
  completionTokens: number;
16
16
  cachedPromptTokens?: number | undefined;
17
+ measurement?: 'provider_reported' | 'text_estimate' | undefined;
18
+ cacheMeasurement?: 'provider_reported' | 'unavailable' | undefined;
17
19
  totalTokens?: number | undefined;
18
20
  thinkingTokens?: number | undefined;
19
21
  }
@@ -119,7 +119,9 @@ export class PiProvider extends LLMProvider {
119
119
  usage = {
120
120
  promptTokens: Number(data.input) || 0,
121
121
  completionTokens: Number(data.output) || 0,
122
- cachedPromptTokens: Number(data.cacheRead) || 0
122
+ cachedPromptTokens: Number(data.cacheRead) || 0,
123
+ measurement: data.input != null && data.output != null ? 'provider_reported' : 'text_estimate',
124
+ cacheMeasurement: data.cacheRead != null ? 'provider_reported' : 'unavailable'
123
125
  };
124
126
  }
125
127
  else if (record.type === 'agent_settled') {
@@ -45,7 +45,7 @@ export class PiProvider extends LLMProvider {
45
45
  let acknowledged = false;
46
46
  let settled = false;
47
47
  let finished = false;
48
- let usage = { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
48
+ let usage: ChatResponse['usage'] = { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
49
49
 
50
50
  const cleanup = (): void => {
51
51
  options.signal?.removeEventListener('abort', abort);
@@ -115,7 +115,9 @@ export class PiProvider extends LLMProvider {
115
115
  usage = {
116
116
  promptTokens: Number(data.input) || 0,
117
117
  completionTokens: Number(data.output) || 0,
118
- cachedPromptTokens: Number(data.cacheRead) || 0
118
+ cachedPromptTokens: Number(data.cacheRead) || 0,
119
+ measurement: data.input != null && data.output != null ? 'provider_reported' : 'text_estimate',
120
+ cacheMeasurement: data.cacheRead != null ? 'provider_reported' : 'unavailable'
119
121
  };
120
122
  } else if (record.type === 'agent_settled') {
121
123
  if (record.aborted) stopReason = 'aborted';
package/src/sandbox.js CHANGED
@@ -127,7 +127,7 @@ const SENSITIVE_WRITE_TARGETS = [
127
127
  // Shell startup files: an appended line runs on the user's next shell.
128
128
  /(^|\/)\.(bashrc|bash_profile|bash_login|profile|zshrc|zprofile|zshenv|zlogin)$/,
129
129
  /(^|\/)\.config\/fish\/config\.fish$/,
130
- // SSH: authorized_keys grants login; config can silently reroute connections.
130
+ // Remote session routing profiles and authentication credentials.
131
131
  /(^|\/)\.ssh\//,
132
132
  // Scheduled execution.
133
133
  /(^|\/)(crontab|cron\.d)(\/|$)/,
@@ -477,15 +477,12 @@ export class Sandbox {
477
477
  const masked = maskQuotedSpans(normalized);
478
478
 
479
479
 
480
- // L3 (local-path audit): classify the REDIRECTION TARGET, not just the verb.
481
- //
482
- // sandbox.validate() path-scopes tool ARGUMENTS, but a shell redirection
483
- // target is invisible to it, and the classifier only ever looked at the
484
- // command word. So `echo evil >> ~/.bashrc` and
485
- // `cat payload >> ~/.ssh/authorized_keys` both classified as SAFE and
486
- // auto-executed in every autonomy mode — persistence and remote access with
487
- // no approval prompt. Writing to these files is escalated regardless of
488
- // which harmless-looking command does the writing.
480
+ // L3 (local-path audit): classify the redirection target, not just the verb.
481
+ // Tool argument validation enforces boundaries on named arguments, but
482
+ // shell redirection targets appended via operators (>> or >) require independent
483
+ // audit. Writing into sensitive paths (such as user startup profiles, remote
484
+ // authentication directories, or agent configuration stores) must always escalate
485
+ // to extreme classification regardless of which command performs the redirection.
489
486
  if (redirectsIntoSensitiveTarget(masked)) return 'extreme';
490
487
  const executesQuotedText = INTERPRETER_INVOCATION.test(masked);
491
488
  const destructiveScanTarget = executesQuotedText ? normalized : masked;
@@ -0,0 +1,203 @@
1
+ /**
2
+ * @file src/smartToolsUse.ts
3
+ * SmartToolsUse & LazyPlaybook Engine.
4
+ *
5
+ * Provides intent-based tool preloading and lazy playbook disclosure.
6
+ * Other capabilities remain discoverable through tool_search.
7
+ *
8
+ * Authorship: Strict TypeScript (Causyne Agent).
9
+ */
10
+ import { PACK_PLAYBOOKS } from './toolPacks.js';
11
+ // ---------------------------------------------------------------------------
12
+ // Intent Matchers & Negative Filters
13
+ // ---------------------------------------------------------------------------
14
+ // Personalization / desktop actions (setting wallpaper, changing desktop background)
15
+ const DESKTOP_PERSONALIZATION_PATTERN = /\b(desktop (picture|wallpaper|background|image)|set wallpaper|change wallpaper)\b/i;
16
+ // Pure web search / retrieval without UI/frontend construction
17
+ const PURE_WEB_SEARCH_PATTERN = /\b(search(ing)? (the )?web|web search|look up online|find on google|brows(e|ing) (the )?web)\b/i;
18
+ const WEB_CONSTRUCTION_EXCLUSION = /\b(build|create|make|design|develop|scaffold|code|program|css|html|tailwind|component|frontend|front-end|landing page|website|webpage|dashboard)\b/i;
19
+ // System admin / process & terminal operations
20
+ const SYSTEM_ADMIN_PATTERN = /\b(kill process|kill port|check port|port \d+|lsof|ps aux|terminate process|zip folder|unzip file|extract archive|compress folder)\b/i;
21
+ // Simple file management operations
22
+ const SIMPLE_FILE_OP_PATTERN = /\b(list (the )?files|show files|count files|rename file(s)?|delete file(s)?|move file(s)?|clean (up )?folder)\b/i;
23
+ // Media generation intent (explicit creation of 3D, video, audio, or synthesized speech)
24
+ const EXPLICIT_MEDIA_GENERATION_PATTERN = /\b(blender|3d model|render 3d|render frame|render animation|da vinci|resolve|audio synth|synthesizer|text to speech|tts|voiceover|dubbing)\b/i;
25
+ // Explicit web engineering intent
26
+ const EXPLICIT_WEB_ENGINEERING_PATTERN = /\b(build.*(website|webpage|landing page|dashboard|ui component|frontend)|create.*(website|webpage|landing page|dashboard|ui)|develop.*(website|web app|webapp))\b/i;
27
+ // Explicit game development intent
28
+ const EXPLICIT_GAME_DEV_PATTERN = /\b(build.*game|create.*game|develop.*game|godot|unity|unreal|platformer 2d|rpg game|arcade game)\b/i;
29
+ /**
30
+ * Select tools to preload based on prompt intent. This is never an allowlist:
31
+ * tool_search can add capabilities as the task develops.
32
+ */
33
+ export function determineToolScope(prompt, _taskShape) {
34
+ const text = (prompt || '').trim();
35
+ if (!text) {
36
+ return { toolScope: null, archetype: 'empty', suppressedPacks: [] };
37
+ }
38
+ // 1. Desktop personalization (e.g. wallpaper / desktop background)
39
+ if (DESKTOP_PERSONALIZATION_PATTERN.test(text)) {
40
+ const tools = new Set([
41
+ 'sysRun',
42
+ 'web_search',
43
+ 'web_fetch',
44
+ 'fs_read',
45
+ 'fs_write',
46
+ 'fs_list',
47
+ 'update_plan',
48
+ 'tool_search'
49
+ ]);
50
+ return {
51
+ toolScope: tools,
52
+ archetype: 'desktop_personalization',
53
+ suppressedPacks: ['media', 'web', 'game', 'advanced', 'system'],
54
+ reason: 'Start with search and system execution; discover desktop or browser tools if direct execution is unsuitable.'
55
+ };
56
+ }
57
+ // 2. Pure web research (searching/fetching online information without web app construction)
58
+ if (PURE_WEB_SEARCH_PATTERN.test(text) && !WEB_CONSTRUCTION_EXCLUSION.test(text)) {
59
+ const tools = new Set([
60
+ 'web_search',
61
+ 'web_fetch',
62
+ 'sysRun',
63
+ 'fs_read',
64
+ 'fs_write',
65
+ 'update_plan',
66
+ 'tool_search'
67
+ ]);
68
+ return {
69
+ toolScope: tools,
70
+ archetype: 'web_research_only',
71
+ suppressedPacks: ['media', 'game', 'web', 'advanced'],
72
+ reason: 'Pure information retrieval requires web search tools; suppresses UI forge and creative packs.'
73
+ };
74
+ }
75
+ // 3. System process or archive administration
76
+ if (SYSTEM_ADMIN_PATTERN.test(text)) {
77
+ const tools = new Set([
78
+ 'sysRun',
79
+ 'proc_term',
80
+ 'process_list',
81
+ 'archive',
82
+ 'fs_read',
83
+ 'fs_list',
84
+ 'update_plan',
85
+ 'tool_search'
86
+ ]);
87
+ return {
88
+ toolScope: tools,
89
+ archetype: 'system_admin',
90
+ suppressedPacks: ['media', 'game', 'web'],
91
+ reason: 'System administration uses process and archive utilities; suppresses creative packs.'
92
+ };
93
+ }
94
+ // 4. Simple local file manipulation
95
+ if (SIMPLE_FILE_OP_PATTERN.test(text) && !EXPLICIT_WEB_ENGINEERING_PATTERN.test(text) && !EXPLICIT_GAME_DEV_PATTERN.test(text)) {
96
+ const tools = new Set([
97
+ 'fs_read',
98
+ 'fs_write',
99
+ 'fs_edit',
100
+ 'fs_list',
101
+ 'fs_search',
102
+ 'sysRun',
103
+ 'update_plan',
104
+ 'tool_search'
105
+ ]);
106
+ return {
107
+ toolScope: tools,
108
+ archetype: 'simple_file_op',
109
+ suppressedPacks: ['media', 'game', 'web', 'advanced'],
110
+ reason: 'Simple filesystem operation; suppresses external domain packs.'
111
+ };
112
+ }
113
+ // Default: unconstrained (standard progressive disclosure and packs apply)
114
+ return {
115
+ toolScope: null,
116
+ archetype: 'generalist',
117
+ suppressedPacks: []
118
+ };
119
+ }
120
+ /**
121
+ * Filter out packs that have been explicitly suppressed for a given prompt intent.
122
+ */
123
+ export function filterSuppressedPacks(candidatePacks, prompt) {
124
+ const result = new Set();
125
+ const scopeResult = determineToolScope(prompt);
126
+ const suppressed = new Set(scopeResult.suppressedPacks);
127
+ for (const pack of candidatePacks) {
128
+ if (!suppressed.has(pack)) {
129
+ result.add(pack);
130
+ }
131
+ }
132
+ return result;
133
+ }
134
+ /**
135
+ * Resolve lazy playbooks. Discloses full multi-page mandates only when tools from that
136
+ * domain have been actively invoked or explicitly demanded. Otherwise generates micro-indicators.
137
+ */
138
+ export function resolveLazyPlaybooks(unlockedPacks, observedTools = [], prompt = '') {
139
+ const packs = new Set(unlockedPacks);
140
+ const tools = new Set(observedTools);
141
+ const text = prompt || '';
142
+ const activePlaybooks = [];
143
+ const microAnnouncements = [];
144
+ const activeDomains = [];
145
+ let tokenSavings = 0;
146
+ // 1. Web Domain
147
+ if (packs.has('web')) {
148
+ const webToolInvoked = tools.has('ui_forge') ||
149
+ tools.has('browser_act') ||
150
+ tools.has('vision_inspect_ui') ||
151
+ tools.has('screenshot') ||
152
+ tools.has('astryx_oracle');
153
+ const webExplicitDemand = EXPLICIT_WEB_ENGINEERING_PATTERN.test(text);
154
+ if ((webToolInvoked || webExplicitDemand) && PACK_PLAYBOOKS.web) {
155
+ activePlaybooks.push(PACK_PLAYBOOKS.web);
156
+ activeDomains.push('web');
157
+ }
158
+ else {
159
+ microAnnouncements.push('- web: browser automation & UI forge available on demand via tool_search.');
160
+ tokenSavings += Math.round((PACK_PLAYBOOKS.web?.length || 0) / 4);
161
+ }
162
+ }
163
+ // 2. Media Domain
164
+ if (packs.has('media')) {
165
+ const mediaToolInvoked = tools.has('blender_act') ||
166
+ tools.has('creative_apps') ||
167
+ tools.has('native_engine') ||
168
+ tools.has('execute_procedural_media') ||
169
+ tools.has('generate_media_via_api') ||
170
+ tools.has('open_source_tool_provisioner');
171
+ const mediaExplicitDemand = EXPLICIT_MEDIA_GENERATION_PATTERN.test(text);
172
+ if ((mediaToolInvoked || mediaExplicitDemand) && PACK_PLAYBOOKS.media) {
173
+ activePlaybooks.push(PACK_PLAYBOOKS.media);
174
+ activeDomains.push('media');
175
+ }
176
+ else {
177
+ microAnnouncements.push('- media: 3D Blender, audio synthesis & creative engines available on demand via tool_search.');
178
+ tokenSavings += Math.round((PACK_PLAYBOOKS.media?.length || 0) / 4);
179
+ }
180
+ }
181
+ // 3. Game Domain
182
+ if (packs.has('game')) {
183
+ const gameToolInvoked = tools.has('godot_act') ||
184
+ tools.has('game_build_html5') ||
185
+ tools.has('game_scene_build') ||
186
+ tools.has('game_asset_harvest');
187
+ const gameExplicitDemand = EXPLICIT_GAME_DEV_PATTERN.test(text);
188
+ if ((gameToolInvoked || gameExplicitDemand) && PACK_PLAYBOOKS.game) {
189
+ activePlaybooks.push(PACK_PLAYBOOKS.game);
190
+ activeDomains.push('game');
191
+ }
192
+ else {
193
+ microAnnouncements.push('- game: Godot 2D/3D & HTML5 game development cascade available on demand via tool_search.');
194
+ tokenSavings += Math.round((PACK_PLAYBOOKS.game?.length || 0) / 4);
195
+ }
196
+ }
197
+ return {
198
+ fullPlaybooks: activePlaybooks.join('\n\n'),
199
+ microAnnouncements: microAnnouncements.join('\n'),
200
+ activePlaybookDomains: activeDomains,
201
+ tokenSavingsEstimate: tokenSavings
202
+ };
203
+ }