@causyne/agent 1.20.96 → 1.20.98
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 +1 -1
- package/src/agentLoop.js +18 -3
- package/src/agentLoop.ts +21 -3
- package/src/budget/budgetPolicy.js +47 -42
- package/src/budget/budgetPolicy.ts +44 -42
- package/src/providers/antigravity.js +30 -18
- package/src/providers/antigravity.ts +27 -19
- package/src/tokenTracker.ts +2 -0
- package/src/tui/completion.js +6 -35
- package/src/tui/inlineSlash.js +93 -0
- package/src/tui/inlineSlash.ts +121 -0
- package/src/tui/prompt.js +81 -3
package/package.json
CHANGED
package/src/agentLoop.js
CHANGED
|
@@ -6,7 +6,7 @@ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/e
|
|
|
6
6
|
import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
|
|
7
7
|
import { waitForAbortableDelay } from './agent/abortableDelay.js';
|
|
8
8
|
import { normalizeAgentFailure } from './agent/providerFailure.js';
|
|
9
|
-
import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime } from './budget/budgetPolicy.js';
|
|
9
|
+
import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime, DEFAULT_AGY_TASK_TOKENS } from './budget/budgetPolicy.js';
|
|
10
10
|
import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
|
|
11
11
|
import { createHash, randomUUID } from 'crypto';
|
|
12
12
|
import { execFileSync } from 'node:child_process';
|
|
@@ -1725,7 +1725,10 @@ export class AgentLoop {
|
|
|
1725
1725
|
});
|
|
1726
1726
|
this.tokenTracker.setEnforcedTaskLimit(guardLimit);
|
|
1727
1727
|
const taskArchetype = determineToolScope(this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype;
|
|
1728
|
-
|
|
1728
|
+
// A workspace category must not create an unrequested 180-second kill switch.
|
|
1729
|
+
const strictDesktopWallMs = this.tokenTracker.budget?.enabled && this.tokenTracker.budget?.hardStop
|
|
1730
|
+
? this.tokenTracker.budget.maxWallTimeMs : undefined;
|
|
1731
|
+
this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype, strictDesktopWallMs);
|
|
1729
1732
|
if (!this.llm) {
|
|
1730
1733
|
throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
|
|
1731
1734
|
}
|
|
@@ -2056,6 +2059,7 @@ export class AgentLoop {
|
|
|
2056
2059
|
const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
|
|
2057
2060
|
const recoveryPaths = new Set();
|
|
2058
2061
|
let modelCallIndex = 0;
|
|
2062
|
+
let softUsageNoticeIssued = false;
|
|
2059
2063
|
let mediaExplorationRecoveries = 0;
|
|
2060
2064
|
let taskMutationCount = 0;
|
|
2061
2065
|
let reasoningOnlyRecoveries = 0;
|
|
@@ -2515,9 +2519,13 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2515
2519
|
hardBudget: hardBudget,
|
|
2516
2520
|
// The peer can perform multiple billable model steps inside one
|
|
2517
2521
|
// chat() call. The per-call bound is independent of autonomy mode.
|
|
2522
|
+
// Only explicit hard budgets constrain the peer. No synthetic 32k sub-limit.
|
|
2518
2523
|
maxTokensThisCall: isAntigravityPeer(this.config.provider)
|
|
2519
|
-
? peerCallTokenCeiling(configuredRemainingBudget)
|
|
2524
|
+
? (hardBudget ? peerCallTokenCeiling(configuredRemainingBudget) ?? undefined : undefined)
|
|
2520
2525
|
: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
|
|
2526
|
+
onBudgetAdvisory: (details) => {
|
|
2527
|
+
this.emitEvent({ type: 'notice', message: `Usage advisory: ${details.usedTokens.toLocaleString()} fresh tokens during this ${details.scope}; no implicit hard stop. /stop cancels; configure a hard budget to enforce a ceiling.` });
|
|
2528
|
+
},
|
|
2521
2529
|
tokenBudgetBasis: isAntigravityPeer(this.config.provider) ? 'noncached'
|
|
2522
2530
|
: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
|
|
2523
2531
|
tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
|
|
@@ -2814,6 +2822,13 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2814
2822
|
? 'external_subscription_unavailable' : 'rate_card_estimate',
|
|
2815
2823
|
callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
|
|
2816
2824
|
});
|
|
2825
|
+
// Soft advisory only; repeated status frames must not consume tokens or stop work.
|
|
2826
|
+
if (isAntigravityPeer(this.config.provider) && !hardBudget && !softUsageNoticeIssued
|
|
2827
|
+
&& this.tokenTracker.taskTokens >= DEFAULT_AGY_TASK_TOKENS) {
|
|
2828
|
+
softUsageNoticeIssued = true;
|
|
2829
|
+
this.emitEvent({ type: 'notice', message: `Task usage passed ${DEFAULT_AGY_TASK_TOKENS.toLocaleString()} fresh tokens. This is an advisory, not a stop. Use /stop or set a user hard budget to limit further calls.` });
|
|
2830
|
+
auditLog.log({ event: 'task_usage_advisory', taskId: this.taskId, freshTokens: this.tokenTracker.taskTokens });
|
|
2831
|
+
}
|
|
2817
2832
|
const cachedTokens = response.usage.cachedPromptTokens || 0;
|
|
2818
2833
|
if (cachedTokens > 0) {
|
|
2819
2834
|
this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
|
package/src/agentLoop.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { getProcessEntitlementGate, EntitlementAccessError } from './licensing/e
|
|
|
6
6
|
import { repairUnansweredToolCalls, validateToolCallBatch } from './agent/toolTurnIntegrity.js';
|
|
7
7
|
import { waitForAbortableDelay } from './agent/abortableDelay.js';
|
|
8
8
|
import { normalizeAgentFailure } from './agent/providerFailure.js';
|
|
9
|
-
import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime } from './budget/budgetPolicy.js';
|
|
9
|
+
import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime, DEFAULT_AGY_TASK_TOKENS } from './budget/budgetPolicy.js';
|
|
10
10
|
import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
|
|
11
11
|
import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
|
|
12
12
|
import { createHash, randomUUID } from 'crypto';
|
|
@@ -1787,7 +1787,10 @@ export class AgentLoop {
|
|
|
1787
1787
|
const taskArchetype = determineToolScope(
|
|
1788
1788
|
this.currentTaskPrompt || this.userPrompt || '', this.taskShape
|
|
1789
1789
|
).archetype;
|
|
1790
|
-
|
|
1790
|
+
// A workspace category must not create an unrequested 180-second kill switch.
|
|
1791
|
+
const strictDesktopWallMs = this.tokenTracker.budget?.enabled && this.tokenTracker.budget?.hardStop
|
|
1792
|
+
? this.tokenTracker.budget.maxWallTimeMs : undefined;
|
|
1793
|
+
this._taskWallDeadlineAt = desktopDeadline(Date.now(), taskArchetype, strictDesktopWallMs);
|
|
1791
1794
|
if (!this.llm) {
|
|
1792
1795
|
throw new Error("API Key Required. Causyne is a 100% Sovereign BYOK Engine. Please configure your API Provider and Key in Settings.");
|
|
1793
1796
|
}
|
|
@@ -2137,6 +2140,7 @@ export class AgentLoop {
|
|
|
2137
2140
|
const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
|
|
2138
2141
|
const recoveryPaths = new Set<string>();
|
|
2139
2142
|
let modelCallIndex = 0;
|
|
2143
|
+
let softUsageNoticeIssued = false;
|
|
2140
2144
|
let mediaExplorationRecoveries = 0;
|
|
2141
2145
|
let taskMutationCount = 0;
|
|
2142
2146
|
let reasoningOnlyRecoveries = 0;
|
|
@@ -2625,9 +2629,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2625
2629
|
hardBudget: hardBudget,
|
|
2626
2630
|
// The peer can perform multiple billable model steps inside one
|
|
2627
2631
|
// chat() call. The per-call bound is independent of autonomy mode.
|
|
2632
|
+
// Only explicit hard budgets constrain the peer. No synthetic 32k sub-limit.
|
|
2628
2633
|
maxTokensThisCall: isAntigravityPeer(this.config.provider)
|
|
2629
|
-
? peerCallTokenCeiling(configuredRemainingBudget)
|
|
2634
|
+
? (hardBudget ? peerCallTokenCeiling(configuredRemainingBudget) ?? undefined : undefined)
|
|
2630
2635
|
: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
|
|
2636
|
+
onBudgetAdvisory: (details: { scope: string; usedTokens: number; threshold: number }) => {
|
|
2637
|
+
this.emitEvent({ type: 'notice', message:
|
|
2638
|
+
`Usage advisory: ${details.usedTokens.toLocaleString()} fresh tokens during this ${details.scope}; no implicit hard stop. /stop cancels; configure a hard budget to enforce a ceiling.` });
|
|
2639
|
+
},
|
|
2631
2640
|
tokenBudgetBasis: isAntigravityPeer(this.config.provider) ? 'noncached'
|
|
2632
2641
|
: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
|
|
2633
2642
|
tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
|
|
@@ -2924,6 +2933,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2924
2933
|
)
|
|
2925
2934
|
});
|
|
2926
2935
|
|
|
2936
|
+
// Soft advisory only; repeated status frames must not consume tokens or stop work.
|
|
2937
|
+
if (isAntigravityPeer(this.config.provider) && !hardBudget && !softUsageNoticeIssued
|
|
2938
|
+
&& this.tokenTracker.taskTokens >= DEFAULT_AGY_TASK_TOKENS) {
|
|
2939
|
+
softUsageNoticeIssued = true;
|
|
2940
|
+
this.emitEvent({ type: 'notice', message:
|
|
2941
|
+
`Task usage passed ${DEFAULT_AGY_TASK_TOKENS.toLocaleString()} fresh tokens. This is an advisory, not a stop. Use /stop or set a user hard budget to limit further calls.` });
|
|
2942
|
+
auditLog.log({ event: 'task_usage_advisory', taskId: this.taskId, freshTokens: this.tokenTracker.taskTokens });
|
|
2943
|
+
}
|
|
2944
|
+
|
|
2927
2945
|
const cachedTokens = response.usage.cachedPromptTokens || 0;
|
|
2928
2946
|
if (cachedTokens > 0) {
|
|
2929
2947
|
this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Causyne
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* Causyne resource policy, version 2.
|
|
3
|
+
*
|
|
4
|
+
* Design invariant: an inferred task category, autonomy mode or provider name
|
|
5
|
+
* must NEVER fabricate a hard resource ceiling. Explicit user/worker ceilings
|
|
6
|
+
* remain hard. Default thresholds are advisory telemetry only.
|
|
7
|
+
*
|
|
8
|
+
* Native tool-stall protections and provider operation timeouts are separate
|
|
9
|
+
* safety controls and remain active outside this policy.
|
|
6
10
|
*/
|
|
7
|
-
export const DEFAULT_AGY_TASK_TOKENS = 80_000;
|
|
8
|
-
export const DEFAULT_AGY_CALL_TOKENS = 32_000;
|
|
9
|
-
export const DEFAULT_AGY_NATIVE_ACTIONS = 128;
|
|
10
|
-
export const DEFAULT_DESKTOP_NATIVE_ACTIONS = 12;
|
|
11
|
-
export const DESKTOP_TASK_WALL_MS = 180_000;
|
|
11
|
+
export const DEFAULT_AGY_TASK_TOKENS = 80_000; // non-blocking advisory only
|
|
12
|
+
export const DEFAULT_AGY_CALL_TOKENS = 32_000; // non-blocking advisory only
|
|
13
|
+
export const DEFAULT_AGY_NATIVE_ACTIONS = 128; // retained for UI guidance only
|
|
14
|
+
export const DEFAULT_DESKTOP_NATIVE_ACTIONS = 12; // retained for UI guidance only
|
|
15
|
+
export const DESKTOP_TASK_WALL_MS = 180_000; // legacy hint, not a default deadline
|
|
12
16
|
const TERMINAL_BUDGET_CODES = new Set([
|
|
13
|
-
'TASK_TOKEN_BUDGET',
|
|
14
|
-
'
|
|
15
|
-
'
|
|
16
|
-
'AGY_TOKEN_BUDGET',
|
|
17
|
-
'AGY_NATIVE_ACTION_BUDGET',
|
|
18
|
-
'AGY_TASK_DEADLINE',
|
|
19
|
-
'TASK_WALL_BUDGET'
|
|
17
|
+
'TASK_TOKEN_BUDGET', 'PROVIDER_TOKEN_BUDGET',
|
|
18
|
+
'AGY_DESKTOP_TASK_LIMIT', 'AGY_TOKEN_BUDGET',
|
|
19
|
+
'AGY_NATIVE_ACTION_BUDGET', 'AGY_TASK_DEADLINE', 'TASK_WALL_BUDGET'
|
|
20
20
|
]);
|
|
21
21
|
export function positiveSafeInteger(value) {
|
|
22
22
|
if (typeof value !== 'number' && typeof value !== 'string')
|
|
@@ -29,36 +29,37 @@ export function positiveSafeInteger(value) {
|
|
|
29
29
|
export function isAntigravityPeer(provider) {
|
|
30
30
|
return /^(?:antigravity|agy)(?:$|[/:\s])/i.test(String(provider ?? '').trim());
|
|
31
31
|
}
|
|
32
|
-
/**
|
|
33
|
-
* Explicit worker ceiling remains strict. An enabled user task limit is
|
|
34
|
-
* authoritative even if its previous 'hardStop' flag was false. In the absence
|
|
35
|
-
* of explicit limits, only Antigravity peers get the conservative default.
|
|
36
|
-
* Other BYOK providers retain their existing policy.
|
|
37
|
-
*/
|
|
32
|
+
/** Only an explicit worker limit or enabled, HARD user budget can stop a task. */
|
|
38
33
|
export function resolveTaskTokenCeiling(options) {
|
|
39
34
|
const worker = positiveSafeInteger(options.workerLimit);
|
|
40
|
-
const configured = options.configured?.enabled === true
|
|
35
|
+
const configured = options.configured?.enabled === true && options.configured.hardStop === true
|
|
41
36
|
? positiveSafeInteger(options.configured.maxTokensPerTask)
|
|
42
37
|
: null;
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
38
|
+
if (worker === null)
|
|
39
|
+
return configured;
|
|
40
|
+
if (configured === null)
|
|
41
|
+
return worker;
|
|
42
|
+
return Math.min(worker, configured);
|
|
47
43
|
}
|
|
48
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* The entire remaining explicitly authorized ceiling is usable in one call.
|
|
46
|
+
* No silent 32k sub-ceiling: doing so discards successful peer output.
|
|
47
|
+
* Missing/unbounded input means no token checkpoint, not a hidden default.
|
|
48
|
+
* Zero is an explicit exhausted limit.
|
|
49
|
+
*/
|
|
49
50
|
export function peerCallTokenCeiling(remaining) {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
return
|
|
53
|
-
? DEFAULT_AGY_CALL_TOKENS
|
|
54
|
-
: Math.min(DEFAULT_AGY_CALL_TOKENS, configuredRemaining);
|
|
51
|
+
if (remaining === 0 || remaining === '0')
|
|
52
|
+
return 0;
|
|
53
|
+
return positiveSafeInteger(remaining);
|
|
55
54
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
55
|
+
/**
|
|
56
|
+
* Native action count becomes a hard stop only when an explicit option is set.
|
|
57
|
+
* Independently, the peer's repetition / no-progress circuit breakers remain.
|
|
58
|
+
*/
|
|
59
|
+
export function peerNativeActionCeiling(configured, _desktopTask) {
|
|
60
|
+
if (configured === 0 || configured === '0')
|
|
61
|
+
return 0;
|
|
62
|
+
return positiveSafeInteger(configured);
|
|
62
63
|
}
|
|
63
64
|
export function isTerminalBudgetFailure(error) {
|
|
64
65
|
if (!error || typeof error !== 'object')
|
|
@@ -78,9 +79,13 @@ export function hasBillablePartialUsage(error) {
|
|
|
78
79
|
export function shouldRetryPeerError(error, aborted = false) {
|
|
79
80
|
return !aborted && !isTerminalBudgetFailure(error) && !hasBillablePartialUsage(error);
|
|
80
81
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
/** User opt-in only: the old 180-second desktop hard stop was task-breaking. */
|
|
83
|
+
export function desktopDeadline(startMs, archetype, hardWallMs) {
|
|
84
|
+
const limit = positiveSafeInteger(hardWallMs);
|
|
85
|
+
if (archetype !== 'desktop_personalization' || !Number.isFinite(startMs) || limit === null)
|
|
86
|
+
return null;
|
|
87
|
+
const deadline = startMs + limit;
|
|
88
|
+
return Number.isSafeInteger(deadline) ? deadline : null;
|
|
84
89
|
}
|
|
85
90
|
export function remainingDesktopTime(deadlineMs, nowMs = Date.now()) {
|
|
86
91
|
if (typeof deadlineMs !== 'number' || !Number.isFinite(deadlineMs))
|
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Causyne
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* Causyne resource policy, version 2.
|
|
3
|
+
*
|
|
4
|
+
* Design invariant: an inferred task category, autonomy mode or provider name
|
|
5
|
+
* must NEVER fabricate a hard resource ceiling. Explicit user/worker ceilings
|
|
6
|
+
* remain hard. Default thresholds are advisory telemetry only.
|
|
7
|
+
*
|
|
8
|
+
* Native tool-stall protections and provider operation timeouts are separate
|
|
9
|
+
* safety controls and remain active outside this policy.
|
|
6
10
|
*/
|
|
7
|
-
export const DEFAULT_AGY_TASK_TOKENS = 80_000;
|
|
8
|
-
export const DEFAULT_AGY_CALL_TOKENS = 32_000;
|
|
9
|
-
export const DEFAULT_AGY_NATIVE_ACTIONS = 128;
|
|
10
|
-
export const DEFAULT_DESKTOP_NATIVE_ACTIONS = 12;
|
|
11
|
-
export const DESKTOP_TASK_WALL_MS = 180_000;
|
|
11
|
+
export const DEFAULT_AGY_TASK_TOKENS = 80_000; // non-blocking advisory only
|
|
12
|
+
export const DEFAULT_AGY_CALL_TOKENS = 32_000; // non-blocking advisory only
|
|
13
|
+
export const DEFAULT_AGY_NATIVE_ACTIONS = 128; // retained for UI guidance only
|
|
14
|
+
export const DEFAULT_DESKTOP_NATIVE_ACTIONS = 12; // retained for UI guidance only
|
|
15
|
+
export const DESKTOP_TASK_WALL_MS = 180_000; // legacy hint, not a default deadline
|
|
12
16
|
|
|
13
17
|
const TERMINAL_BUDGET_CODES = new Set([
|
|
14
|
-
'TASK_TOKEN_BUDGET',
|
|
15
|
-
'
|
|
16
|
-
'
|
|
17
|
-
'AGY_TOKEN_BUDGET',
|
|
18
|
-
'AGY_NATIVE_ACTION_BUDGET',
|
|
19
|
-
'AGY_TASK_DEADLINE',
|
|
20
|
-
'TASK_WALL_BUDGET'
|
|
18
|
+
'TASK_TOKEN_BUDGET', 'PROVIDER_TOKEN_BUDGET',
|
|
19
|
+
'AGY_DESKTOP_TASK_LIMIT', 'AGY_TOKEN_BUDGET',
|
|
20
|
+
'AGY_NATIVE_ACTION_BUDGET', 'AGY_TASK_DEADLINE', 'TASK_WALL_BUDGET'
|
|
21
21
|
]);
|
|
22
22
|
|
|
23
23
|
export interface TaskBudgetOptions {
|
|
@@ -25,6 +25,7 @@ export interface TaskBudgetOptions {
|
|
|
25
25
|
workerLimit?: unknown;
|
|
26
26
|
configured?: {
|
|
27
27
|
enabled?: boolean | undefined;
|
|
28
|
+
hardStop?: boolean | undefined;
|
|
28
29
|
maxTokensPerTask?: unknown;
|
|
29
30
|
} | null | undefined;
|
|
30
31
|
}
|
|
@@ -40,37 +41,35 @@ export function isAntigravityPeer(provider: unknown): boolean {
|
|
|
40
41
|
return /^(?:antigravity|agy)(?:$|[/:\s])/i.test(String(provider ?? '').trim());
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
/**
|
|
44
|
-
* Explicit worker ceiling remains strict. An enabled user task limit is
|
|
45
|
-
* authoritative even if its previous 'hardStop' flag was false. In the absence
|
|
46
|
-
* of explicit limits, only Antigravity peers get the conservative default.
|
|
47
|
-
* Other BYOK providers retain their existing policy.
|
|
48
|
-
*/
|
|
44
|
+
/** Only an explicit worker limit or enabled, HARD user budget can stop a task. */
|
|
49
45
|
export function resolveTaskTokenCeiling(options: TaskBudgetOptions): number | null {
|
|
50
46
|
const worker = positiveSafeInteger(options.workerLimit);
|
|
51
|
-
const configured = options.configured?.enabled === true
|
|
47
|
+
const configured = options.configured?.enabled === true && options.configured.hardStop === true
|
|
52
48
|
? positiveSafeInteger(options.configured.maxTokensPerTask)
|
|
53
49
|
: null;
|
|
54
|
-
|
|
55
|
-
if (
|
|
56
|
-
return
|
|
50
|
+
if (worker === null) return configured;
|
|
51
|
+
if (configured === null) return worker;
|
|
52
|
+
return Math.min(worker, configured);
|
|
57
53
|
}
|
|
58
54
|
|
|
59
|
-
/**
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
55
|
+
/**
|
|
56
|
+
* The entire remaining explicitly authorized ceiling is usable in one call.
|
|
57
|
+
* No silent 32k sub-ceiling: doing so discards successful peer output.
|
|
58
|
+
* Missing/unbounded input means no token checkpoint, not a hidden default.
|
|
59
|
+
* Zero is an explicit exhausted limit.
|
|
60
|
+
*/
|
|
61
|
+
export function peerCallTokenCeiling(remaining: unknown): number | null {
|
|
62
|
+
if (remaining === 0 || remaining === '0') return 0;
|
|
63
|
+
return positiveSafeInteger(remaining);
|
|
66
64
|
}
|
|
67
65
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
66
|
+
/**
|
|
67
|
+
* Native action count becomes a hard stop only when an explicit option is set.
|
|
68
|
+
* Independently, the peer's repetition / no-progress circuit breakers remain.
|
|
69
|
+
*/
|
|
70
|
+
export function peerNativeActionCeiling(configured: unknown, _desktopTask: boolean): number | null {
|
|
71
|
+
if (configured === 0 || configured === '0') return 0;
|
|
72
|
+
return positiveSafeInteger(configured);
|
|
74
73
|
}
|
|
75
74
|
|
|
76
75
|
export function isTerminalBudgetFailure(error: unknown): boolean {
|
|
@@ -92,9 +91,12 @@ export function shouldRetryPeerError(error: unknown, aborted = false): boolean {
|
|
|
92
91
|
return !aborted && !isTerminalBudgetFailure(error) && !hasBillablePartialUsage(error);
|
|
93
92
|
}
|
|
94
93
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
94
|
+
/** User opt-in only: the old 180-second desktop hard stop was task-breaking. */
|
|
95
|
+
export function desktopDeadline(startMs: number, archetype: string, hardWallMs?: unknown): number | null {
|
|
96
|
+
const limit = positiveSafeInteger(hardWallMs);
|
|
97
|
+
if (archetype !== 'desktop_personalization' || !Number.isFinite(startMs) || limit === null) return null;
|
|
98
|
+
const deadline = startMs + limit;
|
|
99
|
+
return Number.isSafeInteger(deadline) ? deadline : null;
|
|
98
100
|
}
|
|
99
101
|
|
|
100
102
|
export function remainingDesktopTime(deadlineMs: unknown, nowMs = Date.now()): number | null {
|
|
@@ -17,7 +17,7 @@ import fs from 'node:fs';
|
|
|
17
17
|
import path from 'node:path';
|
|
18
18
|
import { isLaunchOnlyPrompt } from '../launchIntent.js';
|
|
19
19
|
import { LLMProvider } from './base.js';
|
|
20
|
-
import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError,
|
|
20
|
+
import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError, DEFAULT_AGY_CALL_TOKENS } from '../budget/budgetPolicy.js';
|
|
21
21
|
import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
|
|
22
22
|
/**
|
|
23
23
|
* Baseline fallback models for instant offline availability.
|
|
@@ -955,7 +955,7 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
955
955
|
'Use only the tools needed. Search and download alone are not completion. ' +
|
|
956
956
|
'After setting the desktop picture, read back the actual system wallpaper and compare it with the intended image. ' +
|
|
957
957
|
'If a command is denied or the readback does not confirm the change, report the blocker honestly. ' +
|
|
958
|
-
'
|
|
958
|
+
'Avoid repeated or unnecessary actions; use Causyne tools when a native action is blocked.\n\n' + promptText;
|
|
959
959
|
}
|
|
960
960
|
const taskArchetype = options.taskArchetype || determineToolScope(latestPrompt).archetype;
|
|
961
961
|
const webOrGameTask = taskArchetype === 'web_engineering' || taskArchetype === 'game_development';
|
|
@@ -1021,7 +1021,7 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1021
1021
|
// A process that already exited needs no further action.
|
|
1022
1022
|
}
|
|
1023
1023
|
};
|
|
1024
|
-
const configuredActions =
|
|
1024
|
+
const configuredActions = options.maxNativeActions;
|
|
1025
1025
|
const maxNativeActions = peerNativeActionCeiling(configuredActions, desktopTask);
|
|
1026
1026
|
let nativeActionStarts = 0;
|
|
1027
1027
|
let lastMutationActionIndex = 0;
|
|
@@ -1042,19 +1042,24 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1042
1042
|
promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0,
|
|
1043
1043
|
thinkingTokens: 0, measurement: 'provider_reported', cacheMeasurement: 'provider_reported'
|
|
1044
1044
|
};
|
|
1045
|
-
//
|
|
1046
|
-
//
|
|
1047
|
-
// disabled. Users can set a lower task budget through the existing UI.
|
|
1048
|
-
const remainingTaskBudget = Number(options.maxTokensThisCall);
|
|
1049
|
-
const rawTokenLimit = Number(options.tokenLimit);
|
|
1045
|
+
// Never invent a 32k token limit or 180s task deadline for a user.
|
|
1046
|
+
// Explicit user hard caps are still enforced on streamed steps.
|
|
1050
1047
|
const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
const
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1048
|
+
const tokenLimit = peerCallTokenCeiling(options.maxTokensThisCall)
|
|
1049
|
+
?? peerCallTokenCeiling(options.tokenLimit);
|
|
1050
|
+
const wallMs = desktopTask ? remainingWall : null;
|
|
1051
|
+
let softCallNoticeIssued = false;
|
|
1052
|
+
const noteSoftUsage = (usedTokens) => {
|
|
1053
|
+
if (tokenLimit !== null || softCallNoticeIssued || usedTokens < DEFAULT_AGY_CALL_TOKENS)
|
|
1054
|
+
return;
|
|
1055
|
+
softCallNoticeIssued = true;
|
|
1056
|
+
if (typeof options.onBudgetAdvisory === 'function') {
|
|
1057
|
+
try {
|
|
1058
|
+
options.onBudgetAdvisory({ scope: 'provider call', usedTokens, threshold: DEFAULT_AGY_CALL_TOKENS });
|
|
1059
|
+
}
|
|
1060
|
+
catch { /* UI callbacks must not break the peer's stream. */ }
|
|
1061
|
+
}
|
|
1062
|
+
};
|
|
1058
1063
|
const wallTimer = wallMs !== null ? setTimeout(() => {
|
|
1059
1064
|
const error = createBudgetError('AGY_DESKTOP_TASK_LIMIT', 'Antigravity exceeded the remaining desktop task wall-clock allowance. Outcome is unverified.');
|
|
1060
1065
|
safeReject(error);
|
|
@@ -1116,6 +1121,11 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1116
1121
|
}
|
|
1117
1122
|
options.signal.addEventListener('abort', onAbort, { once: true });
|
|
1118
1123
|
}
|
|
1124
|
+
if (tokenLimit === 0) {
|
|
1125
|
+
safeReject(createBudgetError('AGY_TOKEN_BUDGET', 'Explicit per-call token allowance is exhausted.'));
|
|
1126
|
+
terminateChild();
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1119
1129
|
// Feed prompt directly into child process stdin, then close stdin
|
|
1120
1130
|
try {
|
|
1121
1131
|
child.stdin.on('error', () => { });
|
|
@@ -1170,7 +1180,8 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1170
1180
|
const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
|
|
1171
1181
|
const uncachedTotal = noncachedTokens(partialUsage);
|
|
1172
1182
|
const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
|
|
1173
|
-
|
|
1183
|
+
noteSoftUsage(spentAgainstLimit);
|
|
1184
|
+
if (tokenLimit !== null && spentAgainstLimit >= tokenLimit) {
|
|
1174
1185
|
const error = Object.assign(createBudgetError('AGY_TOKEN_BUDGET', `Antigravity reached the ${tokenLimit}-token per-call ceiling. Outcome is unverified.`), { tokenLimit, partialUsage: { ...partialUsage } });
|
|
1175
1186
|
safeReject(error);
|
|
1176
1187
|
terminateChild();
|
|
@@ -1268,7 +1279,7 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1268
1279
|
}
|
|
1269
1280
|
if (newNativeAction) {
|
|
1270
1281
|
nativeActionStarts++;
|
|
1271
|
-
if (nativeActionStarts > maxNativeActions) {
|
|
1282
|
+
if (maxNativeActions !== null && nativeActionStarts > maxNativeActions) {
|
|
1272
1283
|
const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`);
|
|
1273
1284
|
error.code = 'AGY_NATIVE_ACTION_BUDGET';
|
|
1274
1285
|
safeReject(error);
|
|
@@ -1636,7 +1647,8 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1636
1647
|
const reportedTotal = promptTokens + completionTokens;
|
|
1637
1648
|
const uncachedTotal = noncachedTokens(response.usage);
|
|
1638
1649
|
const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
|
|
1639
|
-
|
|
1650
|
+
noteSoftUsage(spentAgainstLimit);
|
|
1651
|
+
if (tokenLimit !== null && spentAgainstLimit >= tokenLimit) {
|
|
1640
1652
|
Object.assign(partialUsage, response.usage);
|
|
1641
1653
|
safeReject(Object.assign(createBudgetError('AGY_TOKEN_BUDGET', `Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`), { tokenLimit, partialUsage: { ...partialUsage } }));
|
|
1642
1654
|
return;
|
|
@@ -16,7 +16,7 @@ import fs from 'node:fs';
|
|
|
16
16
|
import path from 'node:path';
|
|
17
17
|
import { isLaunchOnlyPrompt } from '../launchIntent.js';
|
|
18
18
|
import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall, type ChatResponseUsage } from './base.js';
|
|
19
|
-
import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError,
|
|
19
|
+
import { peerCallTokenCeiling, peerNativeActionCeiling, shouldRetryPeerError, remainingDesktopTime, createBudgetError, DEFAULT_AGY_CALL_TOKENS } from '../budget/budgetPolicy.js';
|
|
20
20
|
import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
|
|
21
21
|
|
|
22
22
|
/**
|
|
@@ -984,7 +984,7 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
984
984
|
'Use only the tools needed. Search and download alone are not completion. ' +
|
|
985
985
|
'After setting the desktop picture, read back the actual system wallpaper and compare it with the intended image. ' +
|
|
986
986
|
'If a command is denied or the readback does not confirm the change, report the blocker honestly. ' +
|
|
987
|
-
'
|
|
987
|
+
'Avoid repeated or unnecessary actions; use Causyne tools when a native action is blocked.\n\n' + promptText;
|
|
988
988
|
}
|
|
989
989
|
|
|
990
990
|
const taskArchetype = (options as any).taskArchetype || determineToolScope(latestPrompt).archetype;
|
|
@@ -1062,7 +1062,7 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1062
1062
|
// A process that already exited needs no further action.
|
|
1063
1063
|
}
|
|
1064
1064
|
};
|
|
1065
|
-
const configuredActions =
|
|
1065
|
+
const configuredActions = options.maxNativeActions;
|
|
1066
1066
|
const maxNativeActions = peerNativeActionCeiling(configuredActions, desktopTask);
|
|
1067
1067
|
let nativeActionStarts = 0;
|
|
1068
1068
|
let lastMutationActionIndex = 0;
|
|
@@ -1083,20 +1083,21 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1083
1083
|
promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0,
|
|
1084
1084
|
thinkingTokens: 0, measurement: 'provider_reported', cacheMeasurement: 'provider_reported'
|
|
1085
1085
|
};
|
|
1086
|
-
//
|
|
1087
|
-
//
|
|
1088
|
-
// disabled. Users can set a lower task budget through the existing UI.
|
|
1089
|
-
const remainingTaskBudget = Number(options.maxTokensThisCall);
|
|
1090
|
-
const rawTokenLimit = Number((options as any).tokenLimit);
|
|
1086
|
+
// Never invent a 32k token limit or 180s task deadline for a user.
|
|
1087
|
+
// Explicit user hard caps are still enforced on streamed steps.
|
|
1091
1088
|
const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
const
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1089
|
+
const tokenLimit = peerCallTokenCeiling(options.maxTokensThisCall)
|
|
1090
|
+
?? peerCallTokenCeiling((options as any).tokenLimit);
|
|
1091
|
+
const wallMs = desktopTask ? remainingWall : null;
|
|
1092
|
+
let softCallNoticeIssued = false;
|
|
1093
|
+
const noteSoftUsage = (usedTokens: number): void => {
|
|
1094
|
+
if (tokenLimit !== null || softCallNoticeIssued || usedTokens < DEFAULT_AGY_CALL_TOKENS) return;
|
|
1095
|
+
softCallNoticeIssued = true;
|
|
1096
|
+
if (typeof (options as any).onBudgetAdvisory === 'function') {
|
|
1097
|
+
try { (options as any).onBudgetAdvisory({ scope: 'provider call', usedTokens, threshold: DEFAULT_AGY_CALL_TOKENS }); }
|
|
1098
|
+
catch { /* UI callbacks must not break the peer's stream. */ }
|
|
1099
|
+
}
|
|
1100
|
+
};
|
|
1100
1101
|
const wallTimer = wallMs !== null ? setTimeout(() => {
|
|
1101
1102
|
const error = createBudgetError('AGY_DESKTOP_TASK_LIMIT',
|
|
1102
1103
|
'Antigravity exceeded the remaining desktop task wall-clock allowance. Outcome is unverified.');
|
|
@@ -1160,6 +1161,11 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1160
1161
|
}
|
|
1161
1162
|
options.signal.addEventListener('abort', onAbort, { once: true });
|
|
1162
1163
|
}
|
|
1164
|
+
if (tokenLimit === 0) {
|
|
1165
|
+
safeReject(createBudgetError('AGY_TOKEN_BUDGET', 'Explicit per-call token allowance is exhausted.'));
|
|
1166
|
+
terminateChild();
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1163
1169
|
|
|
1164
1170
|
// Feed prompt directly into child process stdin, then close stdin
|
|
1165
1171
|
try {
|
|
@@ -1213,7 +1219,8 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1213
1219
|
const reportedTotal = partialUsage.promptTokens + partialUsage.completionTokens;
|
|
1214
1220
|
const uncachedTotal = noncachedTokens(partialUsage);
|
|
1215
1221
|
const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
|
|
1216
|
-
|
|
1222
|
+
noteSoftUsage(spentAgainstLimit);
|
|
1223
|
+
if (tokenLimit !== null && spentAgainstLimit >= tokenLimit) {
|
|
1217
1224
|
const error = Object.assign(
|
|
1218
1225
|
createBudgetError('AGY_TOKEN_BUDGET',
|
|
1219
1226
|
`Antigravity reached the ${tokenLimit}-token per-call ceiling. Outcome is unverified.`),
|
|
@@ -1318,7 +1325,7 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1318
1325
|
|
|
1319
1326
|
if (newNativeAction) {
|
|
1320
1327
|
nativeActionStarts++;
|
|
1321
|
-
if (nativeActionStarts > maxNativeActions) {
|
|
1328
|
+
if (maxNativeActions !== null && nativeActionStarts > maxNativeActions) {
|
|
1322
1329
|
const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`) as Error & { code: string };
|
|
1323
1330
|
error.code = 'AGY_NATIVE_ACTION_BUDGET';
|
|
1324
1331
|
safeReject(error);
|
|
@@ -1695,7 +1702,8 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1695
1702
|
const reportedTotal = promptTokens + completionTokens;
|
|
1696
1703
|
const uncachedTotal = noncachedTokens(response.usage);
|
|
1697
1704
|
const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
|
|
1698
|
-
|
|
1705
|
+
noteSoftUsage(spentAgainstLimit);
|
|
1706
|
+
if (tokenLimit !== null && spentAgainstLimit >= tokenLimit) {
|
|
1699
1707
|
Object.assign(partialUsage, response.usage);
|
|
1700
1708
|
safeReject(Object.assign(createBudgetError('AGY_TOKEN_BUDGET',
|
|
1701
1709
|
`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
|
package/src/tokenTracker.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface TokenBudgetConfig {
|
|
|
30
30
|
hardStop?: boolean;
|
|
31
31
|
maxTokensPerDay?: number;
|
|
32
32
|
maxTokensPerTask?: number;
|
|
33
|
+
/** Optional HARD wall-clock ceiling for desktop-personalization tasks only. */
|
|
34
|
+
maxWallTimeMs?: number;
|
|
33
35
|
maxCostUsd?: number;
|
|
34
36
|
alertThresholdTokens?: number;
|
|
35
37
|
warningThreshold?: number;
|
package/src/tui/completion.js
CHANGED
|
@@ -18,6 +18,7 @@ import { listCommands } from '../commands.js';
|
|
|
18
18
|
import { listCompiledSkills as listSkillsForCompletion } from '../skillsManager.js';
|
|
19
19
|
import { sanitize, shortenHome } from './text.js';
|
|
20
20
|
import { WorkspaceFileIndex } from './workspaceFileIndex.js';
|
|
21
|
+
import { detectInlineSlashTrigger } from './inlineSlash.js';
|
|
21
22
|
export { WorkspaceFileIndex as FileIndex };
|
|
22
23
|
|
|
23
24
|
export const MAX_VISIBLE = 8;
|
|
@@ -312,44 +313,14 @@ function directoryItems(root, partial) {
|
|
|
312
313
|
// ---------------------------------------------------------------------------
|
|
313
314
|
|
|
314
315
|
/**
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
* that merely mentions `/usr/local/bin` from opening a command picker, the same
|
|
319
|
-
* rule parseCommand() enforces when the line is finally submitted.
|
|
316
|
+
* Find a slash command or @ reference at the current caret position.
|
|
317
|
+
* Slash detection works at any whitespace-delimited token boundary. Execution
|
|
318
|
+
* remains exclusive to explicit selection; normal prompt dispatch is unchanged.
|
|
320
319
|
*/
|
|
321
320
|
export function detectTrigger(text, cursor) {
|
|
322
321
|
const before = text.slice(0, cursor);
|
|
323
|
-
|
|
324
|
-
if (
|
|
325
|
-
return { kind: 'command', start: 0, query: before.slice(1) };
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
// `/command <argument>` — the command's OWN suggestions.
|
|
329
|
-
//
|
|
330
|
-
// Completion used to stop dead at the space: `/skills d` offered nothing, so
|
|
331
|
-
// the only way to reach a skill was to submit `/skills` bare and browse. With
|
|
332
|
-
// a hundred of them that is a poor trade for someone who already knows the
|
|
333
|
-
// name they want.
|
|
334
|
-
//
|
|
335
|
-
// openclaw's contract (src/tui/commands.ts): a command declares its argument
|
|
336
|
-
// completions and the prompt asks it for the ones matching what has been typed
|
|
337
|
-
// — `getArgumentCompletions(prefix)`. Same shape here, generic over every
|
|
338
|
-
// command, so `/mcp`, `/model` and the rest can adopt it by adding one
|
|
339
|
-
// function and nothing in this file changes.
|
|
340
|
-
//
|
|
341
|
-
// Anchored, and a single argument token only: a second word ends the
|
|
342
|
-
// completion rather than trying to complete inside a sentence. opencode hides
|
|
343
|
-
// its picker on exactly the same condition.
|
|
344
|
-
const argument = before.match(/^\/([a-z0-9_?-]+)[ \t]+(\S*)$/i);
|
|
345
|
-
if (argument) {
|
|
346
|
-
return {
|
|
347
|
-
kind: 'command-argument',
|
|
348
|
-
command: argument[1],
|
|
349
|
-
start: cursor - argument[2].length,
|
|
350
|
-
query: argument[2]
|
|
351
|
-
};
|
|
352
|
-
}
|
|
322
|
+
const slash = detectInlineSlashTrigger(text, cursor);
|
|
323
|
+
if (slash) return slash;
|
|
353
324
|
|
|
354
325
|
// 1. Quoted @ file mention: @"pixel2d games/ or @'pixel2d games/
|
|
355
326
|
// Supports spaces in directory or file names
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slash completion framing for the Causyne chat composer.
|
|
3
|
+
*
|
|
4
|
+
* This is intentionally a lexical, zero-model operation. It never executes a
|
|
5
|
+
* command. Only an explicit picker selection can hand a command to ChatPrompt.
|
|
6
|
+
* Existing command dispatch keeps its beginning-of-input parser unchanged.
|
|
7
|
+
*/
|
|
8
|
+
const ARGUMENT = /(?:^|[ \t\r\n])\/([a-z0-9_?-]+)[ \t]+([^\s]*)$/i;
|
|
9
|
+
const COMMAND = /(?:^|[ \t\r\n])\/([a-z0-9_?-]*)$/i;
|
|
10
|
+
/**
|
|
11
|
+
* Find a complete slash prefix at the caret, even when other prose precedes it.
|
|
12
|
+
* A slash must start a whitespace-delimited token: URLs, division, and paths
|
|
13
|
+
* with inner slashes do not open the command menu.
|
|
14
|
+
*
|
|
15
|
+
* Offsets are UTF-16 code units, which is the existing completion.js contract.
|
|
16
|
+
*/
|
|
17
|
+
export function detectInlineSlashTrigger(text, cursor) {
|
|
18
|
+
if (typeof text !== 'string' || !Number.isFinite(cursor))
|
|
19
|
+
return null;
|
|
20
|
+
if (cursor < 0 || cursor > text.length)
|
|
21
|
+
return null;
|
|
22
|
+
const before = text.slice(0, cursor);
|
|
23
|
+
const argument = ARGUMENT.exec(before);
|
|
24
|
+
if (argument) {
|
|
25
|
+
const fragment = argument[0];
|
|
26
|
+
const offset = cursor - fragment.length + fragment.indexOf('/');
|
|
27
|
+
const query = argument[2] ?? '';
|
|
28
|
+
return {
|
|
29
|
+
kind: 'command-argument',
|
|
30
|
+
command: argument[1] ?? '',
|
|
31
|
+
query,
|
|
32
|
+
start: cursor - query.length,
|
|
33
|
+
tokenStart: offset,
|
|
34
|
+
inline: before.slice(0, offset).trim().length > 0
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const command = COMMAND.exec(before);
|
|
38
|
+
if (!command)
|
|
39
|
+
return null;
|
|
40
|
+
const fragment = command[0];
|
|
41
|
+
const offset = cursor - fragment.length + fragment.indexOf('/');
|
|
42
|
+
return {
|
|
43
|
+
kind: 'command',
|
|
44
|
+
query: command[1] ?? '',
|
|
45
|
+
start: offset,
|
|
46
|
+
tokenStart: offset,
|
|
47
|
+
inline: before.slice(0, offset).trim().length > 0
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Remove the command token, NOT the surrounding draft.
|
|
52
|
+
* An editor caret can sit in the middle of a token. In that case, remove the
|
|
53
|
+
* untyped suffix of the same token too, stopping at the following whitespace.
|
|
54
|
+
*/
|
|
55
|
+
export function removeInlineSlashToken(text, cursor, trigger) {
|
|
56
|
+
if (typeof text !== 'string' || !Number.isFinite(cursor)) {
|
|
57
|
+
throw new TypeError('Invalid inline command text or cursor');
|
|
58
|
+
}
|
|
59
|
+
const position = Math.trunc(cursor);
|
|
60
|
+
const start = trigger.tokenStart;
|
|
61
|
+
if (!Number.isInteger(start) || start < 0 || start >= text.length ||
|
|
62
|
+
position < start || position > text.length || text[start] !== '/') {
|
|
63
|
+
throw new RangeError('Stale inline command selection');
|
|
64
|
+
}
|
|
65
|
+
const actual = text.slice(start, position);
|
|
66
|
+
if (trigger.kind === 'command') {
|
|
67
|
+
if (actual !== `/${trigger.query}`) {
|
|
68
|
+
throw new RangeError('Stale inline command selection');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
const argument = /^\/([a-z0-9_?-]+)[ \t]+([^\s]*)$/i.exec(actual);
|
|
73
|
+
if (!argument || argument[1] !== trigger.command || argument[2] !== trigger.query) {
|
|
74
|
+
throw new RangeError('Stale inline command selection');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const suffix = text.slice(position);
|
|
78
|
+
const trailingToken = trigger.kind === 'command'
|
|
79
|
+
? /^[a-z0-9_?-]*/i.exec(suffix)?.[0] ?? ''
|
|
80
|
+
: /^[^\s]*/.exec(suffix)?.[0] ?? '';
|
|
81
|
+
const end = position + trailingToken.length;
|
|
82
|
+
return {
|
|
83
|
+
text: text.slice(0, start) + text.slice(end),
|
|
84
|
+
cursor: start
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Compiled-skill menu entries are the only commands that consume the current
|
|
89
|
+
* draft as their task instruction. Management commands keep the draft intact.
|
|
90
|
+
*/
|
|
91
|
+
export function isInlineSkillInvocation(command) {
|
|
92
|
+
return /^\/skills\s+[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(command);
|
|
93
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slash completion framing for the Causyne chat composer.
|
|
3
|
+
*
|
|
4
|
+
* This is intentionally a lexical, zero-model operation. It never executes a
|
|
5
|
+
* command. Only an explicit picker selection can hand a command to ChatPrompt.
|
|
6
|
+
* Existing command dispatch keeps its beginning-of-input parser unchanged.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type SlashTrigger =
|
|
10
|
+
| {
|
|
11
|
+
readonly kind: 'command';
|
|
12
|
+
readonly query: string;
|
|
13
|
+
readonly start: number;
|
|
14
|
+
readonly tokenStart: number;
|
|
15
|
+
readonly inline: boolean;
|
|
16
|
+
}
|
|
17
|
+
| {
|
|
18
|
+
readonly kind: 'command-argument';
|
|
19
|
+
readonly command: string;
|
|
20
|
+
readonly query: string;
|
|
21
|
+
readonly start: number;
|
|
22
|
+
readonly tokenStart: number;
|
|
23
|
+
readonly inline: boolean;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export interface RemovedSlashToken {
|
|
27
|
+
readonly text: string;
|
|
28
|
+
readonly cursor: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const ARGUMENT = /(?:^|[ \t\r\n])\/([a-z0-9_?-]+)[ \t]+([^\s]*)$/i;
|
|
32
|
+
const COMMAND = /(?:^|[ \t\r\n])\/([a-z0-9_?-]*)$/i;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Find a complete slash prefix at the caret, even when other prose precedes it.
|
|
36
|
+
* A slash must start a whitespace-delimited token: URLs, division, and paths
|
|
37
|
+
* with inner slashes do not open the command menu.
|
|
38
|
+
*
|
|
39
|
+
* Offsets are UTF-16 code units, which is the existing completion.js contract.
|
|
40
|
+
*/
|
|
41
|
+
export function detectInlineSlashTrigger(text: string, cursor: number): SlashTrigger | null {
|
|
42
|
+
if (typeof text !== 'string' || !Number.isFinite(cursor)) return null;
|
|
43
|
+
if (cursor < 0 || cursor > text.length) return null;
|
|
44
|
+
|
|
45
|
+
const before = text.slice(0, cursor);
|
|
46
|
+
const argument = ARGUMENT.exec(before);
|
|
47
|
+
if (argument) {
|
|
48
|
+
const fragment = argument[0];
|
|
49
|
+
const offset = cursor - fragment.length + fragment.indexOf('/');
|
|
50
|
+
const query = argument[2] ?? '';
|
|
51
|
+
return {
|
|
52
|
+
kind: 'command-argument',
|
|
53
|
+
command: argument[1] ?? '',
|
|
54
|
+
query,
|
|
55
|
+
start: cursor - query.length,
|
|
56
|
+
tokenStart: offset,
|
|
57
|
+
inline: before.slice(0, offset).trim().length > 0
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const command = COMMAND.exec(before);
|
|
62
|
+
if (!command) return null;
|
|
63
|
+
const fragment = command[0];
|
|
64
|
+
const offset = cursor - fragment.length + fragment.indexOf('/');
|
|
65
|
+
return {
|
|
66
|
+
kind: 'command',
|
|
67
|
+
query: command[1] ?? '',
|
|
68
|
+
start: offset,
|
|
69
|
+
tokenStart: offset,
|
|
70
|
+
inline: before.slice(0, offset).trim().length > 0
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Remove the command token, NOT the surrounding draft.
|
|
76
|
+
* An editor caret can sit in the middle of a token. In that case, remove the
|
|
77
|
+
* untyped suffix of the same token too, stopping at the following whitespace.
|
|
78
|
+
*/
|
|
79
|
+
export function removeInlineSlashToken(
|
|
80
|
+
text: string,
|
|
81
|
+
cursor: number,
|
|
82
|
+
trigger: SlashTrigger
|
|
83
|
+
): RemovedSlashToken {
|
|
84
|
+
if (typeof text !== 'string' || !Number.isFinite(cursor)) {
|
|
85
|
+
throw new TypeError('Invalid inline command text or cursor');
|
|
86
|
+
}
|
|
87
|
+
const position = Math.trunc(cursor);
|
|
88
|
+
const start = trigger.tokenStart;
|
|
89
|
+
if (!Number.isInteger(start) || start < 0 || start >= text.length ||
|
|
90
|
+
position < start || position > text.length || text[start] !== '/') {
|
|
91
|
+
throw new RangeError('Stale inline command selection');
|
|
92
|
+
}
|
|
93
|
+
const actual = text.slice(start, position);
|
|
94
|
+
if (trigger.kind === 'command') {
|
|
95
|
+
if (actual !== `/${trigger.query}`) {
|
|
96
|
+
throw new RangeError('Stale inline command selection');
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
const argument = /^\/([a-z0-9_?-]+)[ \t]+([^\s]*)$/i.exec(actual);
|
|
100
|
+
if (!argument || argument[1] !== trigger.command || argument[2] !== trigger.query) {
|
|
101
|
+
throw new RangeError('Stale inline command selection');
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const suffix = text.slice(position);
|
|
105
|
+
const trailingToken = trigger.kind === 'command'
|
|
106
|
+
? /^[a-z0-9_?-]*/i.exec(suffix)?.[0] ?? ''
|
|
107
|
+
: /^[^\s]*/.exec(suffix)?.[0] ?? '';
|
|
108
|
+
const end = position + trailingToken.length;
|
|
109
|
+
return {
|
|
110
|
+
text: text.slice(0, start) + text.slice(end),
|
|
111
|
+
cursor: start
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Compiled-skill menu entries are the only commands that consume the current
|
|
117
|
+
* draft as their task instruction. Management commands keep the draft intact.
|
|
118
|
+
*/
|
|
119
|
+
export function isInlineSkillInvocation(command: string): boolean {
|
|
120
|
+
return /^\/skills\s+[a-z0-9_.-]+\/[a-z0-9_.-]+$/i.test(command);
|
|
121
|
+
}
|
package/src/tui/prompt.js
CHANGED
|
@@ -22,6 +22,7 @@ import { TerminalInputFramer, INPUT_PREFIX_TIMEOUT_MS, shouldTreatAsAtomicPaste
|
|
|
22
22
|
import { LineEditor } from './lineEditor.js';
|
|
23
23
|
import { PromptHistory } from './history.js';
|
|
24
24
|
import { FileIndex, suggest, applyCompletion, detectTrigger, renderPicker, MAX_VISIBLE } from './completion.js';
|
|
25
|
+
import { removeInlineSlashToken, isInlineSkillInvocation } from './inlineSlash.js';
|
|
25
26
|
import { paint, dim, bold, GLYPHS, terminalWidth, HAS_COLOR } from './theme.js';
|
|
26
27
|
import { barBlock, GUTTER } from './block.js';
|
|
27
28
|
import { composerGeometry } from './composerGeometry.js';
|
|
@@ -1446,6 +1447,12 @@ export class ChatPrompt {
|
|
|
1446
1447
|
}
|
|
1447
1448
|
|
|
1448
1449
|
if (item) {
|
|
1450
|
+
if (this.completion.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
|
|
1451
|
+
const selectedCommand = this.completion.kind === 'command'
|
|
1452
|
+
? item.value : `/${this.completion.command} ${item.value}`;
|
|
1453
|
+
this.runInlineSlashSelection(selectedCommand);
|
|
1454
|
+
return true;
|
|
1455
|
+
}
|
|
1449
1456
|
if (this.completion.kind === 'command') {
|
|
1450
1457
|
// A skill entry goes onto the line so the user can say what to do
|
|
1451
1458
|
// with it; clicking it used to invoke it immediately with no task.
|
|
@@ -1466,8 +1473,14 @@ export class ChatPrompt {
|
|
|
1466
1473
|
}
|
|
1467
1474
|
return true;
|
|
1468
1475
|
}
|
|
1469
|
-
if (key.name === 'enter' && !key.alt) {
|
|
1476
|
+
if (key.name === 'enter' && !key.alt && !key.shift) {
|
|
1470
1477
|
const item = this.completion.items && this.completion.items[this.selected];
|
|
1478
|
+
if (item && this.completion.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
|
|
1479
|
+
const selectedCommand = this.completion.kind === 'command'
|
|
1480
|
+
? item.value : `/${this.completion.command} ${item.value}`;
|
|
1481
|
+
this.runInlineSlashSelection(selectedCommand);
|
|
1482
|
+
return true;
|
|
1483
|
+
}
|
|
1471
1484
|
if (this.completion.kind === 'command' && item) {
|
|
1472
1485
|
if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
|
|
1473
1486
|
this.acceptCompletion();
|
|
@@ -1486,10 +1499,22 @@ export class ChatPrompt {
|
|
|
1486
1499
|
this.acceptCompletion();
|
|
1487
1500
|
return true;
|
|
1488
1501
|
}
|
|
1489
|
-
if (key.name === 'tab') {
|
|
1502
|
+
if (key.name === 'tab') {
|
|
1503
|
+
if (this.completion?.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
|
|
1504
|
+
// Tab must never silently turn an unsent message into a local command.
|
|
1505
|
+
this.notice = 'Press Enter to run the selected command; your unsent draft is preserved.';
|
|
1506
|
+
this.scheduleDraw();
|
|
1507
|
+
return true;
|
|
1508
|
+
}
|
|
1509
|
+
this.acceptCompletion();
|
|
1510
|
+
return true;
|
|
1511
|
+
}
|
|
1490
1512
|
if (key.name === 'escape') {
|
|
1513
|
+
const dismissed = this.completion;
|
|
1491
1514
|
this.completion = null;
|
|
1492
|
-
|
|
1515
|
+
// Only discard a standalone leading command token. Never erase a
|
|
1516
|
+
// longer draft just because its first character happens to be /.
|
|
1517
|
+
if (!dismissed?.inline && /^\s*\/[a-z0-9_?-]*$/i.test(this.editor.getText())) {
|
|
1493
1518
|
this.editor.clear();
|
|
1494
1519
|
}
|
|
1495
1520
|
this.scheduleDraw();
|
|
@@ -1523,6 +1548,56 @@ export class ChatPrompt {
|
|
|
1523
1548
|
this.submit();
|
|
1524
1549
|
}
|
|
1525
1550
|
|
|
1551
|
+
/**
|
|
1552
|
+
* Execute an explicitly selected slash action from anywhere in a draft.
|
|
1553
|
+
* Ordinary commands run through submit() with the unsent draft suspended;
|
|
1554
|
+
* selecting a compiled skill applies it to the draft as its instruction.
|
|
1555
|
+
* Neither path changes parseCommand() or interprets ambient prose as control.
|
|
1556
|
+
*/
|
|
1557
|
+
runInlineSlashSelection(value) {
|
|
1558
|
+
const trigger = this.completion;
|
|
1559
|
+
if (!trigger?.inline || (trigger.kind !== 'command' && trigger.kind !== 'command-argument')) {
|
|
1560
|
+
this.submitPickedCommand(value);
|
|
1561
|
+
return;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
const currentText = this.editor.getText();
|
|
1565
|
+
const currentCursor = this.cursorOffset();
|
|
1566
|
+
let remaining;
|
|
1567
|
+
try {
|
|
1568
|
+
remaining = removeInlineSlashToken(currentText, currentCursor, trigger);
|
|
1569
|
+
} catch (error) {
|
|
1570
|
+
// The draft might have changed since the last render. Never execute a
|
|
1571
|
+
// command selected against stale input or erase user-authored text.
|
|
1572
|
+
this.notice = 'The command text changed. Reopen the / menu and select again.';
|
|
1573
|
+
this.completion = null;
|
|
1574
|
+
this.scheduleDraw();
|
|
1575
|
+
return;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
const consumeDraft = isInlineSkillInvocation(value) && remaining.text.trim().length > 0;
|
|
1579
|
+
const commandText = consumeDraft ? `${value} ${remaining.text.trim()}` : value;
|
|
1580
|
+
|
|
1581
|
+
// submit() itself protects the queue, but return early here to avoid
|
|
1582
|
+
// discarding the unfinished inline token when the command was not queued.
|
|
1583
|
+
if (this.busy && this.queue.length >= 32 && !/^\/(?:stop|interrupt)$/i.test(commandText)) {
|
|
1584
|
+
this.notice = '32 queued messages: command not submitted; your draft is unchanged.';
|
|
1585
|
+
this.scheduleDraw();
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
this.completion = null;
|
|
1590
|
+
try {
|
|
1591
|
+
this.editor.setText(commandText);
|
|
1592
|
+
this.submit(); // existing history, permission and command-dispatch boundary
|
|
1593
|
+
} finally {
|
|
1594
|
+
this.editor.setText(consumeDraft ? '' : remaining.text);
|
|
1595
|
+
if (!consumeDraft) this.setCursorOffset(remaining.cursor);
|
|
1596
|
+
this.completion = null;
|
|
1597
|
+
this.scheduleDraw();
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1526
1601
|
acceptCompletion() {
|
|
1527
1602
|
const item = this.completion.items[this.selected];
|
|
1528
1603
|
if (!item) { this.completion = null; return; }
|
|
@@ -1845,6 +1920,9 @@ export class ChatPrompt {
|
|
|
1845
1920
|
const matched = this.completion.total || this.completion.items.length;
|
|
1846
1921
|
const hidden = matched - drawn.length;
|
|
1847
1922
|
if (hidden > 0) drawn.push(dim(` ${GLYPHS.ellipsis} ${hidden} more`));
|
|
1923
|
+
if (this.completion?.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
|
|
1924
|
+
drawn.push(dim(' ' + truncate('Enter run · Esc dismiss · draft protected', Math.max(0, width - 5))));
|
|
1925
|
+
}
|
|
1848
1926
|
return drawn;
|
|
1849
1927
|
}
|
|
1850
1928
|
}
|