@aisac/cli 0.0.0-stage → 0.4.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +166 -2
  2. package/dist/assets/claude/.claude-plugin/plugin.json +147 -0
  3. package/dist/assets/claude/hooks/context-compaction.ts +6930 -0
  4. package/dist/assets/claude/hooks/hooks.json +3 -0
  5. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +18 -0
  6. package/dist/assets/claude/hooks/native-host-contract.test.ts +51 -0
  7. package/dist/assets/claude/hooks/provider-window.js +263 -0
  8. package/dist/assets/claude/hooks/state-fitting.d.mts +47 -0
  9. package/dist/assets/claude/hooks/state-fitting.mjs +324 -0
  10. package/dist/assets/codex-context-compaction.mjs +4689 -0
  11. package/dist/assets/context-selection-fitting.mjs +194 -0
  12. package/dist/assets/context-state-fitting.mjs +324 -0
  13. package/dist/assets/context-telemetry-reporter.mjs +305 -0
  14. package/dist/assets/jev-paid-pilot-terminal.mjs +1066 -0
  15. package/dist/claude-checkpoint.mjs +1338 -0
  16. package/dist/claude-compatibility.mjs +506 -0
  17. package/dist/claude-observation.mjs +1338 -0
  18. package/dist/cli.mjs +771 -0
  19. package/dist/codex-compatibility.mjs +481 -0
  20. package/dist/codex-diagnostics.mjs +447 -0
  21. package/dist/codex-permissions.mjs +590 -0
  22. package/dist/codex-protocol-fingerprint.json +131 -0
  23. package/dist/context-telemetry.mjs +257 -0
  24. package/dist/engineering-pack-public-key.json +10 -0
  25. package/dist/engineering-pack.mjs +722 -0
  26. package/dist/engineering.mjs +194 -0
  27. package/dist/launch.mjs +690 -0
  28. package/dist/mcp.mjs +962 -0
  29. package/dist/monitor.mjs +133 -0
  30. package/dist/package.json +5 -0
  31. package/dist/platform.mjs +126 -0
  32. package/dist/policy.mjs +218 -0
  33. package/dist/state.mjs +408 -0
  34. package/dist/telemetry-report.mjs +133 -0
  35. package/package.json +24 -4
@@ -0,0 +1,3 @@
1
+ {
2
+ "modules": ["./context-compaction.ts"]
3
+ }
@@ -0,0 +1,18 @@
1
+ import { register as registerContext } from './context-compaction.ts';
2
+
3
+ export function register(on: Parameters<typeof registerContext>[0]): void {
4
+ return registerContext(on, {
5
+ enabled: true,
6
+ disclosed: true,
7
+ policyVersion: 2,
8
+ compactAtPercent: 60,
9
+ keepThreshold: 0.5,
10
+ preserveRecentMessages: 6,
11
+ minReductionRatio: 0.25,
12
+ truncateHeadChars: 300,
13
+ maxStateTokens: 25_000,
14
+ maxRequestTokens: 30_000,
15
+ compactionStrategy: 'native_summary_notes',
16
+ preservationMode: 'upstream_compatible',
17
+ });
18
+ }
@@ -0,0 +1,51 @@
1
+ import { expect, test } from 'claude-code/testing';
2
+
3
+ const contractTest: Parameters<typeof test>[2] = async ($, on) => {
4
+ const monotonicStart = globalThis.performance?.now?.();
5
+ expect(Number.isFinite(monotonicStart)).toBe(true);
6
+ on('prompt.submit', () => ({ text: 'native-host-contract-ok' }));
7
+ on('tool.call', () => ({ result: { content: 'native-host-tool-ok' } }));
8
+ on('session.messages', () => ({ value: [] }));
9
+ let usageCalls = 0;
10
+ on('session.usage', () => ({
11
+ value: (() => {
12
+ usageCalls += 1;
13
+ return { context: { percent: 90, tokens: 900, window: 1_000 } };
14
+ })(),
15
+ }));
16
+ on('ui.log', () => ({ value: undefined }));
17
+ on('ui.toast', () => ({ value: undefined }));
18
+ let compactCalls = 0;
19
+ on('session.compact', () => {
20
+ compactCalls += 1;
21
+ return {
22
+ messages: [{ role: 'assistant', text: 'native-summary-contract-ok', toolUses: [] }],
23
+ };
24
+ });
25
+ on('turn.complete', () => ({ text: '' }));
26
+ const prompt = await $.prompt.submit({ text: 'native-host-contract-input' });
27
+ const tool = await $.tool.call({ tool: 'Read', file_path: 'native-host-contract.txt' });
28
+ await $.turn.complete({
29
+ turnId: 'native-contract-turn',
30
+ answer: 'native-turn-contract-ok',
31
+ durationMs: 1,
32
+ isAborted: false,
33
+ usage: null,
34
+ });
35
+ expect(prompt.text).toBe('native-host-contract-ok');
36
+ expect(tool.result.content).toBe('native-host-tool-ok');
37
+ expect(usageCalls).toBe(1);
38
+ expect(compactCalls).toBe(1);
39
+ const monotonicEnd = globalThis.performance?.now?.();
40
+ expect(Number.isFinite(monotonicEnd)).toBe(true);
41
+ expect(
42
+ typeof monotonicStart === 'number' &&
43
+ typeof monotonicEnd === 'number' &&
44
+ monotonicEnd >= monotonicStart,
45
+ ).toBe(true);
46
+ };
47
+
48
+ test(
49
+ 'AI Brain enabled host contract invokes usage and native compaction through the dispatcher',
50
+ contractTest,
51
+ );
@@ -0,0 +1,263 @@
1
+ import { preflightProviderState } from './state-fitting.mjs';
2
+ export const PROVIDER_WINDOW_MAX_PAIRS = 200;
3
+ export const PROVIDER_WINDOW_MAX_MESSAGES = 1_000;
4
+ export const PROVIDER_WINDOW_MAX_REFERENCES = 200;
5
+ export const PROVIDER_WINDOW_MAX_REQUEST_BYTES = 512 * 1024;
6
+ export const PROVIDER_WINDOW_REQUEST_HEADROOM_BYTES = 16 * 1024;
7
+ export const PROVIDER_WINDOW_MAX_SEARCH_ATTEMPTS = 12;
8
+ export const PROVIDER_WINDOW_MAX_STATE_TOKENS = 25_000;
9
+ export const PROVIDER_WINDOW_MAX_REQUEST_TOKENS = 30_000;
10
+ export const PROVIDER_WINDOW_MAX_RESERVED_TOKENS = 120_000;
11
+ export const PROVIDER_WINDOW_OUTPUT_TOKEN_ALLOWANCE = 4_000;
12
+ function utf8Bytes(value) {
13
+ return new TextEncoder().encode(JSON.stringify(value)).byteLength;
14
+ }
15
+ function anchorMessageIds(messages, preserveRecentMessages) {
16
+ return new Set(messages
17
+ .slice(0, 1)
18
+ .concat(messages.slice(Math.max(0, messages.length - preserveRecentMessages)))
19
+ .map((message) => message.id));
20
+ }
21
+ function pairIdsFromMessages(messages) {
22
+ return new Set(messages.flatMap((message) => [...message.callIds, ...message.resultIds]));
23
+ }
24
+ function compareEligible(a, b) {
25
+ return b.resultChars - a.resultChars || a.callMessage - b.callMessage || a.id.localeCompare(b.id);
26
+ }
27
+ function uniqueMarkerId(messages) {
28
+ const ids = new Set(messages.map((message) => message.id));
29
+ let candidate = 'provider-window-omitted';
30
+ let sequence = 0;
31
+ while (ids.has(candidate))
32
+ candidate = `provider-window-omitted-${++sequence}`;
33
+ return candidate;
34
+ }
35
+ function abbreviatedText(text, limit) {
36
+ if (text.length <= limit)
37
+ return text;
38
+ if (limit <= 0)
39
+ return `[historical message omitted; ${text.length} chars]`;
40
+ const head = Math.max(1, Math.floor(limit * 0.65));
41
+ const tail = Math.max(1, limit - head);
42
+ return `${text.slice(0, head)}…[omitted ${text.length - head - tail} chars]…${text.slice(-tail)}`;
43
+ }
44
+ function boundedMessages(messages, selectedIds, anchorIds, maxMessages) {
45
+ const filtered = messages.map((message) => ({
46
+ ...message,
47
+ callIds: message.callIds.filter((id) => selectedIds.has(id)),
48
+ resultIds: message.resultIds.filter((id) => selectedIds.has(id)),
49
+ }));
50
+ if (filtered.length <= maxMessages)
51
+ return filtered;
52
+ const retained = filtered.filter((message) => anchorIds.has(message.id) || message.callIds.length > 0 || message.resultIds.length > 0);
53
+ if (retained.length > maxMessages)
54
+ return null;
55
+ const output = [];
56
+ const usedIds = new Set(filtered.map((message) => message.id));
57
+ let markerSequence = 0;
58
+ let omitted = 0;
59
+ let markerPending = false;
60
+ const flush = () => {
61
+ if (!markerPending)
62
+ return;
63
+ let markerId = uniqueMarkerId(output);
64
+ while (usedIds.has(markerId))
65
+ markerId = `provider-window-omitted-${++markerSequence}`;
66
+ usedIds.add(markerId);
67
+ output.push({
68
+ id: markerId,
69
+ role: 'user',
70
+ text: `[${omitted} historical messages omitted from provider window]`,
71
+ callIds: [],
72
+ resultIds: [],
73
+ });
74
+ omitted = 0;
75
+ markerPending = false;
76
+ };
77
+ for (const message of filtered) {
78
+ if (anchorIds.has(message.id) || message.callIds.length > 0 || message.resultIds.length > 0) {
79
+ flush();
80
+ output.push(message);
81
+ }
82
+ else {
83
+ omitted += 1;
84
+ markerPending = true;
85
+ }
86
+ }
87
+ flush();
88
+ return output.length <= maxMessages ? output : null;
89
+ }
90
+ function transportMessages(messages, anchorIds, textLimit) {
91
+ if (textLimit === null)
92
+ return messages;
93
+ return messages.map((message) => anchorIds.has(message.id)
94
+ ? message
95
+ : { ...message, text: abbreviatedText(message.text, textLimit) });
96
+ }
97
+ function toWireProjection(input, selectedPairs, messages) {
98
+ return {
99
+ goal: input.goal,
100
+ messages: messages.map((message) => ({
101
+ id: message.id,
102
+ role: message.role,
103
+ text: message.text,
104
+ call_ids: [...message.callIds],
105
+ result_ids: [...message.resultIds],
106
+ })),
107
+ pairs: selectedPairs.map((pair) => ({
108
+ id: pair.id,
109
+ tool: pair.tool,
110
+ input_text: pair.inputText,
111
+ result_chars: pair.resultChars,
112
+ result_is_error: pair.resultIsError,
113
+ eligibility: pair.protectedPair ? 'protected' : pair.eligibility,
114
+ pin_reasons: [...pair.pinReasons],
115
+ })),
116
+ protected_item_count: input.protectedItemCount,
117
+ };
118
+ }
119
+ function toFitProjection(input, selectedPairs, messages) {
120
+ return {
121
+ goal: input.goal,
122
+ protectedItemCount: input.protectedItemCount,
123
+ messages,
124
+ pairs: selectedPairs,
125
+ };
126
+ }
127
+ function candidate(input, rankedEligible, mandatoryIds, count, options, fit) {
128
+ const selectedIds = new Set(mandatoryIds);
129
+ rankedEligible.slice(0, count).forEach((pair) => selectedIds.add(pair.id));
130
+ const selectedPairs = input.pairs.filter((pair) => selectedIds.has(pair.id));
131
+ if (selectedPairs.length > options.maxPairs)
132
+ return null;
133
+ const anchorIds = anchorMessageIds(input.messages, options.preserveRecentMessages);
134
+ const messages = boundedMessages(input.messages, selectedIds, anchorIds, options.maxMessages);
135
+ if (messages === null)
136
+ return null;
137
+ if (messages.some((message) => message.callIds.length > options.maxReferencesPerMessage ||
138
+ message.resultIds.length > options.maxReferencesPerMessage))
139
+ return null;
140
+ const eligible = selectedPairs.filter((pair) => !pair.protectedPair);
141
+ if (count === 0 && eligible.length === 0)
142
+ return null;
143
+ const textLimits = [null, 4_096, 1_024, 256, 64, 0];
144
+ for (const textLimit of textLimits) {
145
+ const transportReadyMessages = transportMessages(messages, anchorIds, textLimit);
146
+ const wire = toWireProjection(input, selectedPairs, transportReadyMessages);
147
+ const requestBytes = utf8Bytes({ projection: wire });
148
+ if (requestBytes + options.requestHeadroomBytes > options.maxRequestBytes)
149
+ continue;
150
+ const preflight = fit(toFitProjection(input, selectedPairs, transportReadyMessages), eligible, options);
151
+ if (!preflight.fits)
152
+ return null;
153
+ const maxBatches = options.maxBatchesPerOperation ?? 4;
154
+ if (!Number.isSafeInteger(maxBatches) || maxBatches < 1 || preflight.batchCount > maxBatches)
155
+ return null;
156
+ const outputAllowance = options.outputTokenAllowance ?? PROVIDER_WINDOW_OUTPUT_TOKEN_ALLOWANCE;
157
+ if (!Number.isSafeInteger(outputAllowance) || outputAllowance < 0)
158
+ return null;
159
+ const estimatedReservationTokens = ((preflight.requestTokens ?? Number.POSITIVE_INFINITY) + outputAllowance) *
160
+ preflight.batchCount;
161
+ if (estimatedReservationTokens > options.maxReservedTokens)
162
+ return null;
163
+ return {
164
+ ok: true,
165
+ projection: wire,
166
+ pairs: selectedPairs,
167
+ deferredPairs: input.pairs.filter((pair) => !selectedIds.has(pair.id)),
168
+ preflight: { ...preflight, requestBytes, estimatedReservationTokens },
169
+ attempts: 0,
170
+ anchorPairCount: mandatoryIds.size,
171
+ selectedEligibleCount: eligible.length,
172
+ };
173
+ }
174
+ return null;
175
+ }
176
+ export function prepareProviderWindow(input, options, fit = preflightProviderState) {
177
+ const limits = {
178
+ maxPairs: Math.min(options.maxPairs ?? PROVIDER_WINDOW_MAX_PAIRS, PROVIDER_WINDOW_MAX_PAIRS),
179
+ maxMessages: Math.min(options.maxMessages ?? PROVIDER_WINDOW_MAX_MESSAGES, PROVIDER_WINDOW_MAX_MESSAGES),
180
+ maxReferencesPerMessage: Math.min(options.maxReferencesPerMessage ?? PROVIDER_WINDOW_MAX_REFERENCES, PROVIDER_WINDOW_MAX_REFERENCES),
181
+ maxRequestBytes: Math.min(options.maxRequestBytes ?? PROVIDER_WINDOW_MAX_REQUEST_BYTES, PROVIDER_WINDOW_MAX_REQUEST_BYTES),
182
+ requestHeadroomBytes: Math.max(options.requestHeadroomBytes ?? PROVIDER_WINDOW_REQUEST_HEADROOM_BYTES, PROVIDER_WINDOW_REQUEST_HEADROOM_BYTES),
183
+ maxReservedTokens: Math.min(options.maxReservedTokens ?? PROVIDER_WINDOW_MAX_RESERVED_TOKENS, PROVIDER_WINDOW_MAX_RESERVED_TOKENS),
184
+ };
185
+ const fitOptions = {
186
+ ...options,
187
+ preserveRecentMessages: Math.min(Math.max(1, options.preserveRecentMessages), limits.maxMessages),
188
+ maxStateTokens: Math.min(options.maxStateTokens, PROVIDER_WINDOW_MAX_STATE_TOKENS),
189
+ maxRequestTokens: Math.min(options.maxRequestTokens, PROVIDER_WINDOW_MAX_REQUEST_TOKENS),
190
+ maxBatchesPerOperation: Math.min(Math.max(1, options.maxBatchesPerOperation ?? 4), 4),
191
+ outputTokenAllowance: Math.min(Math.max(0, options.outputTokenAllowance ?? PROVIDER_WINDOW_OUTPUT_TOKEN_ALLOWANCE), PROVIDER_WINDOW_OUTPUT_TOKEN_ALLOWANCE),
192
+ };
193
+ const anchors = anchorMessageIds(input.messages, fitOptions.preserveRecentMessages);
194
+ const mandatoryIds = pairIdsFromMessages(input.messages.filter((message) => anchors.has(message.id)));
195
+ if (mandatoryIds.size > limits.maxPairs)
196
+ return {
197
+ ok: false,
198
+ reason: 'anchor_overflow',
199
+ attempts: 0,
200
+ anchorPairCount: mandatoryIds.size,
201
+ };
202
+ const rankedEligible = input.pairs
203
+ .filter((pair) => !pair.protectedPair && !mandatoryIds.has(pair.id))
204
+ .sort(compareEligible);
205
+ const mandatoryEligibleCount = input.pairs.filter((pair) => mandatoryIds.has(pair.id) && !pair.protectedPair).length;
206
+ if (rankedEligible.length === 0 && mandatoryEligibleCount === 0)
207
+ return {
208
+ ok: false,
209
+ reason: 'no_feasible_window',
210
+ attempts: 0,
211
+ anchorPairCount: mandatoryIds.size,
212
+ };
213
+ const maxCount = Math.min(rankedEligible.length, limits.maxPairs - mandatoryIds.size);
214
+ let low = mandatoryEligibleCount > 0 ? 0 : 1;
215
+ let high = maxCount;
216
+ let best = null;
217
+ let bestCount = 0;
218
+ let attempts = 0;
219
+ while (low <= high && attempts < PROVIDER_WINDOW_MAX_SEARCH_ATTEMPTS) {
220
+ const count = Math.floor((low + high) / 2);
221
+ const result = candidate(input, rankedEligible, mandatoryIds, count, {
222
+ ...limits,
223
+ preserveRecentMessages: fitOptions.preserveRecentMessages,
224
+ maxStateTokens: fitOptions.maxStateTokens,
225
+ maxRequestTokens: fitOptions.maxRequestTokens,
226
+ maxReservedTokens: limits.maxReservedTokens,
227
+ maxBatchesPerOperation: fitOptions.maxBatchesPerOperation,
228
+ outputTokenAllowance: fitOptions.outputTokenAllowance,
229
+ }, fit);
230
+ attempts += 1;
231
+ if (result !== null) {
232
+ best = { ...result, attempts };
233
+ bestCount = count;
234
+ low = count + 1;
235
+ }
236
+ else
237
+ high = count - 1;
238
+ }
239
+ if (best === null)
240
+ return {
241
+ ok: false,
242
+ reason: 'no_feasible_window',
243
+ attempts,
244
+ anchorPairCount: mandatoryIds.size,
245
+ };
246
+ const final = candidate(input, rankedEligible, mandatoryIds, bestCount, {
247
+ ...limits,
248
+ preserveRecentMessages: fitOptions.preserveRecentMessages,
249
+ maxStateTokens: fitOptions.maxStateTokens,
250
+ maxRequestTokens: fitOptions.maxRequestTokens,
251
+ maxReservedTokens: limits.maxReservedTokens,
252
+ maxBatchesPerOperation: fitOptions.maxBatchesPerOperation,
253
+ outputTokenAllowance: fitOptions.outputTokenAllowance,
254
+ }, fit);
255
+ if (final === null)
256
+ return {
257
+ ok: false,
258
+ reason: 'no_feasible_window',
259
+ attempts: attempts + 1,
260
+ anchorPairCount: mandatoryIds.size,
261
+ };
262
+ return { ...final, attempts: attempts + 1 };
263
+ }
@@ -0,0 +1,47 @@
1
+ export type ProviderFitPreflightReason = 'fits' | 'budget_exceeded';
2
+
3
+ export interface ProviderFitPreflight {
4
+ readonly fits: boolean;
5
+ readonly reason: ProviderFitPreflightReason;
6
+ readonly stage: string | null;
7
+ readonly stateTokens: number | null;
8
+ readonly requestTokens: number | null;
9
+ readonly batchCount: number;
10
+ }
11
+
12
+ export interface ProviderFitProjectionMessage {
13
+ readonly id: string;
14
+ readonly role: 'user' | 'assistant';
15
+ readonly text: string;
16
+ readonly callIds: readonly string[];
17
+ readonly resultIds: readonly string[];
18
+ }
19
+
20
+ export interface ProviderFitProjectionPair {
21
+ readonly id: string;
22
+ readonly tool: string;
23
+ readonly inputText: string;
24
+ readonly resultChars: number;
25
+ readonly resultIsError: boolean;
26
+ readonly eligibility: 'reproducible_read' | 'compatible_tool' | 'protected';
27
+ readonly pinReasons: readonly string[];
28
+ }
29
+
30
+ export interface ProviderFitProjection {
31
+ readonly goal: string;
32
+ readonly messages: readonly ProviderFitProjectionMessage[];
33
+ readonly pairs: readonly ProviderFitProjectionPair[];
34
+ readonly protectedItemCount: number;
35
+ }
36
+
37
+ export interface ProviderFitOptions {
38
+ readonly preserveRecentMessages: number;
39
+ readonly maxStateTokens: number;
40
+ readonly maxRequestTokens: number;
41
+ }
42
+
43
+ export function preflightProviderState(
44
+ projection: ProviderFitProjection,
45
+ eligible: readonly ProviderFitProjectionPair[],
46
+ options: ProviderFitOptions,
47
+ ): ProviderFitPreflight;