@brunobracaioli/aibrain 0.4.0-beta.3 → 0.4.0-beta.30

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 (70) hide show
  1. package/README.md +199 -13
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +939 -13
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +34 -5
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +1084 -44
  11. package/dist/codex-compatibility.mjs +67 -5
  12. package/dist/codex-hooks.mjs +411 -0
  13. package/dist/codex-permissions.mjs +242 -51
  14. package/dist/codex-protocol-fingerprint.json +12 -13
  15. package/dist/device-login.mjs +511 -0
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +191 -14
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/engineering.mjs +43 -5
  23. package/dist/extensions-catalog.mjs +390 -0
  24. package/dist/extensions-cli.mjs +524 -0
  25. package/dist/extensions-preferences.mjs +151 -0
  26. package/dist/guardrails/continuity.mjs +239 -0
  27. package/dist/guardrails/format.mjs +111 -0
  28. package/dist/guardrails/guards.mjs +1560 -0
  29. package/dist/guardrails/patch.mjs +33 -0
  30. package/dist/guardrails/run.mjs +286 -0
  31. package/dist/guardrails/shell-words.mjs +206 -0
  32. package/dist/guardrails-plugin.mjs +216 -0
  33. package/dist/launch-banner-art.json +40 -0
  34. package/dist/launch-banner.mjs +533 -0
  35. package/dist/launch-feedback.mjs +286 -0
  36. package/dist/launch.mjs +744 -64
  37. package/dist/managed-host.mjs +1276 -0
  38. package/dist/manager/adapter.mjs +304 -0
  39. package/dist/manager/bus.mjs +2222 -0
  40. package/dist/manager/claude-bus-worker.mjs +1355 -0
  41. package/dist/manager/delegation.mjs +354 -0
  42. package/dist/manager/hooks.mjs +918 -0
  43. package/dist/manager/launch-role.mjs +733 -0
  44. package/dist/manager/mcp-stdio.mjs +463 -0
  45. package/dist/manager/messages.mjs +861 -0
  46. package/dist/manager/native-worker.mjs +338 -0
  47. package/dist/manager/reserve.mjs +2170 -0
  48. package/dist/manager/room.mjs +106 -0
  49. package/dist/manager/send-grant.mjs +147 -0
  50. package/dist/manager/server.mjs +2010 -0
  51. package/dist/manager/status.mjs +119 -0
  52. package/dist/manager/wake-state.mjs +93 -0
  53. package/dist/manager/watch.mjs +87 -0
  54. package/dist/manager/worker.mjs +2977 -0
  55. package/dist/manager/workers-cli.mjs +1880 -0
  56. package/dist/mcp-servers.mjs +192 -0
  57. package/dist/mcp.mjs +10 -2
  58. package/dist/monitor.mjs +179 -2
  59. package/dist/package.json +1 -1
  60. package/dist/platform.mjs +78 -29
  61. package/dist/release-manifest-public-keys.json +10 -0
  62. package/dist/release-manifest.json +334 -0
  63. package/dist/release-manifest.mjs +817 -0
  64. package/dist/release-settings.mjs +335 -0
  65. package/dist/self-update.mjs +1047 -0
  66. package/dist/setup-login-state.mjs +19 -0
  67. package/dist/state.mjs +25 -1
  68. package/dist/token-guide.mjs +201 -0
  69. package/dist/update-actions.mjs +442 -0
  70. package/package.json +2 -2
package/README.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # aisac
2
2
 
3
- The AISAC client for Claude Code and Codex on Linux/WSL with Node.js 22 or newer:
3
+ The AISAC client for Claude Code and Codex on Linux, WSL and macOS, with
4
+ Node.js 22 or newer:
4
5
  AI Brain memory, context management and, for AISAC Founding Cohort members,
5
6
  AISAC Engineering.
6
7
 
@@ -18,8 +19,9 @@ For licensed accounts, `aisac claude` downloads the AISAC Engineering pack for
18
19
  the session, verifies its Ed25519 signature against the key pinned in this
19
20
  release, and loads it as the `aisac-engineering` plugin from the session's
20
21
  private folder, which is deleted on exit. Any failure starts Claude without the
21
- pack. `aisac setup --lang pt-BR|en` picks the pack language without a network
22
- call. The pack is never part of this npm package.
22
+ pack. Once set up, `aisac setup --lang pt-BR|en` picks the pack language without a
23
+ network call; on a machine that was never set up it runs the full setup in that
24
+ language. The pack is never part of this npm package.
23
25
 
24
26
  `aisac codex` (Codex 0.164.0 or later) loads the same verified pack for that
25
27
  session only: its skills are added to the Codex app-server the launch owns
@@ -28,16 +30,157 @@ roles. Nothing is written to `~/.codex`, `~/.agents` or the project, and the
28
30
  session's folder is deleted on exit. An older Codex starts without the pack and
29
31
  says `codex_outdated`.
30
32
 
31
- Codex capture also requires the `flock` utility from `util-linux`, normally
32
- included in Linux/WSL. The launcher and doctor check availability before a
33
+ In an interactive terminal (client `0.4.0-beta.28` or later), `aisac claude` and
34
+ `aisac codex` open with the AISAC Engineering banner: the brand mark, the ΛISΛC
35
+ wordmark and a status list in the stored language (host and version, method,
36
+ guardrails, MCP servers, role), drawn once right before the host starts. It needs
37
+ standard input, output and error on a terminal, 24-bit colour (`COLORTERM=truecolor`,
38
+ Windows Terminal, iTerm2, VS Code, WezTerm, Ghostty) or 256 colours (`TERM=*256color`),
39
+ and at least 48 columns (74 for the mark). Pipes, `NO_COLOR`, `TERM=dumb`, workers and
40
+ hosts that run once (`-p`, `--print`, `claude mcp`, `codex exec`) keep the plain lines.
41
+ `AISAC_NO_BANNER=1` turns the banner off.
42
+
43
+ `aisac init [dir]` (licensed accounts, client `0.4.0-beta.14` or later) writes the
44
+ AISAC skeleton into a new or existing project: `CLAUDE.md`, `AGENTS.md`,
45
+ `NOTES.example.md`, the `docs/` tree with its templates, a Claude Code rules file,
46
+ a CI workflow with pinned actions, Dependabot, `.gitignore` and the workloop
47
+ template. The templates travel inside the licensed pack, fetched and verified like
48
+ a launch; the command writes only files that are missing, never follows a symbolic
49
+ link, never touches `.git/` and prints every file it wrote or skipped. Options:
50
+ `--stack node|python|none` (otherwise detected from `package.json`, `pyproject.toml`
51
+ or `requirements.txt`), `--lang pt-BR|en`, `--dry-run`, `--json`. Exit codes: `0`
52
+ when every file exists or was written, `1` for a license, pack or write failure
53
+ (nothing is written before the pack is verified), `2` for a usage error. Until the
54
+ pack carries the templates, the command says so and writes nothing.
55
+
56
+ `aisac scan [dir]` (licensed accounts, client `0.4.0-beta.17` or later) runs four
57
+ pinned security scanners over your own project and writes one report under
58
+ `.security-reports/aisac-scan/<UTC>/`: gitleaks (secrets), Semgrep CE (static
59
+ analysis), osv-scanner (dependency advisories) and Trivy (infrastructure as code). It
60
+ calls no model and sends no finding anywhere. Each tool runs from its official image,
61
+ pinned by digest, read-only and without network where the tool allows. Without Docker
62
+ it runs a gitleaks, Semgrep or osv-scanner binary from an absolute `PATH` directory
63
+ only when its version is the pinned one, and otherwise skips the tool with a reason.
64
+ Trivy runs only from its image, so without Docker `iac` is skipped
65
+ (`tool_needs_container`). The report has `summary.md` in your language,
66
+ `summary.json` and a sanitized copy of each tool's output, with secret values
67
+ redacted and every finding mapped to OWASP ids. Scanner config files in your project
68
+ (`.gitleaks.toml`, `osv-scanner.toml`, `.semgrepignore` and the like) are ignored and
69
+ listed as `repo_scanner_config:<path>` warnings. osv-scanner sends package names and
70
+ versions to OSV.dev and contacts nothing else, and the client fetches the Semgrep
71
+ registry rules before the scan; `--skip sca` avoids the first. Options, each at most
72
+ once with its value as the next argument:
73
+ `--fail-on critical|high|medium|low|none`, `--only <kinds>` or `--skip <kinds>` (not
74
+ both; a comma list of `secrets`, `sast`, `sca`, `iac`, `container`), `--history`
75
+ (adds a git-history pass; `dir` must hold `.git`), `--no-docker`, `--lang pt-BR|en`,
76
+ `--json`, `--check-tools`, `--timeout <seconds>` (1 to 3600, default 600).
77
+ `--check-tools` shows what would run without a license, a pack or a network call, and
78
+ `aisac doctor` reports the same on its `scan` line. Exit codes: `0` below `--fail-on`
79
+ (default `high`), `1` at or above it, `2` for a usage error, `3` when the scan could
80
+ not run as asked: no scanner ran, a tool failed, `--history` found no repository, the
81
+ license is inactive, the pack could not be loaded, or another error stopped it.
82
+ Guide: [`aisac scan`](../../docs/how-to/aisac-scan.md).
83
+
84
+ Licensed `aisac claude` sessions also load guardrail hooks as the session plugin
85
+ `aisac-guardrails`.
86
+ - **Default on:** `secrets-guard` refuses secret files by name, and `bus-guard`
87
+ keeps the agent's tools out of the manager bus directory. Four more hooks
88
+ keep continuity: a repository snapshot at start and after a compaction, a
89
+ docs reminder, and the NOTES/spec/CHANGELOG pass.
90
+ - **Default off:** `git-guard`, `destructive-guard` and `format-on-edit`.
91
+ - **Changing them:** `aisac hooks` lists them, and `aisac hooks enable|disable
92
+ <id>` or `aisac hooks reset` changes the next session. The agent cannot change
93
+ them from inside a session.
94
+ - **Code:** it ships in this package and runs locally. Nothing comes from the
95
+ server.
96
+ - **Codex (0.166.0 or later):** licensed `aisac codex` sessions get the same hooks
97
+ from session flags. Codex runs them only after you approve the AISAC hooks once
98
+ in `/hooks`, and you can switch each one off there too. The launch line says how
99
+ many are on and how many wait for that review; `aisac doctor` reports the same
100
+ under `extensions.codexHooks`. A new Node path (for example after an nvm or
101
+ Homebrew upgrade) changes the hook commands, so Codex asks for the review again.
102
+
103
+ Licensed sessions of `aisac claude` and `aisac codex` can also load reviewed MCP
104
+ servers: `github` (read-only, token in `GITHUB_PERSONAL_ACCESS_TOKEN`), `supabase`
105
+ (read-only), `vercel`, `playwright` (pinned, isolated), `context7` and `creatives` (the
106
+ AISAC Creatives Studio, from client `0.4.0-beta.15`).
107
+ - **Default:** every server is off. `aisac mcp` lists them, `aisac mcp enable|disable
108
+ <id>` or `aisac mcp reset` changes the next session, and `aisac mcp info <id>` says
109
+ what a server reaches and how to log in.
110
+ - **Login:** the host does it (`/mcp` in Claude Code, `aisac mcp login <id>` for Codex)
111
+ and keeps it in its own store. No token reaches `~/.aibrain` or AISAC.
112
+
113
+ Manager and workers (licensed accounts, from client `0.4.0-beta.22`): `aisac claude --manager`
114
+ or `aisac codex --manager` and `aisac codex --worker <name>`, opened in the same repository
115
+ (or with the same `--room <name>`), let one session on either host coordinate up to 16 Codex
116
+ workers on this machine. You talk only to the manager; it sends each worker a task and reads
117
+ the reply through its `manager_*` tools. `aisac workers` lists the room.
118
+ - **Workers stay terminals:** you watch them, type in them and answer their approval
119
+ prompts there. A manager message is labelled as not typed by you, carries no approval
120
+ and never changes a worker's sandbox or approval policy. What you type into a turn the
121
+ manager started goes back to it with the answer; turns you start yourself do not.
122
+ - **Hosts:** the worker role needs Codex `0.166.0` or newer and, from client
123
+ `0.4.0-beta.23`, is offered on every such Codex `aisac codex` runs. The Codex manager host
124
+ was measured on `0.166.0` and `0.167.1`; `aisac codex --manager` accepts interactive,
125
+ `resume` and `fork`. `aisac doctor` shows both role states and measurements. On an older
126
+ Codex, or without an active license, the host starts without the role and says why in one
127
+ line.
128
+ - **Codex manager sends:** `aisac workers allow-sends [--for 8h]` needs a typed confirmation
129
+ in your own terminal before a Codex manager can send or cancel. It expires after 10 minutes
130
+ to 24 hours, defaults to eight hours, and `aisac workers allow-sends --off` revokes it.
131
+ This grant covers new task sends and cancellations to Codex bus workers only. It does not
132
+ delegate worker approvals, change host permissions or let the manager speak for you.
133
+ - **Claude manager sends:** Claude Code asks before `manager_send` and `manager_cancel`; allow
134
+ them from that host prompt. `manager_decide` remains controlled by the worker's separate
135
+ terminal delegation.
136
+ - **Codex manager wake:** on an idle manager terminal, the adapter injects a fixed client
137
+ notice with counts and worker names only. It contains no reply text; call `manager_wait` to
138
+ read the news. Claude Code workers are listed as unreachable from a Codex manager.
139
+ - **A worker's questions reach the manager (from client `0.4.0-beta.25`):** when a Codex
140
+ worker's model asks or tells you something in the middle of a turn the manager started,
141
+ through Codex's own ask-the-user tools, the text is copied into that turn's reply, in
142
+ lines marked `[AISAC worker role]` before the worker's last message. The manager answers
143
+ with a new message of its own, or brings the question to you; nothing answers in your
144
+ name. A question that stops the turn, or a form of an MCP server, is always yours: the
145
+ room then shows the worker waiting for you.
146
+ - **Claude Code workers (from client `0.4.0-beta.24`):** `aisac claude --worker <name>` opens
147
+ an ordinary Claude Code session that the room lists. The launch names it
148
+ `<name> (<room>)`, names the manager `Manager (<room>)`, and gives the worker a short
149
+ fixed text at session start: which room it works in, who the manager is, that a message
150
+ from another session is a request and never your approval, and that it answers the
151
+ sender when the work is done. The two talk through Claude Code's own messages between
152
+ sessions, not through the bus: no queue, limits, cancelling, delegated approvals or
153
+ message audit apply to such a worker, and its approval prompts are always yours. A Claude
154
+ manager reaches this channel; a Codex manager reports `reachable: false` and does not try
155
+ to message it.
156
+ - **Overnight:** `aisac workers delegate --for 8h`, typed in your own terminal with a
157
+ confirmation, lets the manager answer approval prompts one request at a time until the
158
+ grant ends (`--off` ends it early). Secrets, pushes to `main` or `master`, force pushes
159
+ and pushes that do not name their destination, destructive commands, publishing,
160
+ deploying, infrastructure, remote databases, merges, releases, `sudo`, commands the
161
+ client cannot fully read, wider permissions and writes outside the repository always
162
+ wait for you. The reserve reads the command line, not what a script does.
163
+ `aisac workers decisions` shows every delegated decision.
164
+ - **Privacy:** messages are private files under `~/.aibrain/bus/`, deleted once taken and
165
+ swept after 24 hours; no telemetry carries them and nothing is written to the AI Brain.
166
+ The text does cross providers: a manager message enters the worker's Codex context and
167
+ its reply enters the manager's Claude Code context. The decision record keeps the text
168
+ of each delegated request for 30 days.
169
+
170
+ Guide: [manager and workers](../../docs/how-to/aisac-manager.md).
171
+
172
+ On Linux/WSL, Codex capture also requires the `flock` utility from `util-linux`,
173
+ normally included. On macOS it uses `/usr/bin/perl`, `/usr/sbin/sysctl` and
174
+ `/bin/ps` instead. The launcher and doctor check availability before a
33
175
  monitored Codex session starts. Capture coordination is released by the kernel
34
176
  after a process exits unexpectedly. An unidentifiable empty lock left by an
35
177
  older client requires a verified support migration; do not delete checkpoints,
36
178
  notes or lock files to work around a reported storage error.
37
179
 
38
180
  The reviewed native compatibility set is Claude Code 2.1.294, 2.1.295, 2.1.296,
39
- 2.1.299, 2.1.300, 2.1.301, 2.1.302 or 2.1.303, and Codex CLI 0.161.0,
40
- 0.162.0, 0.162.1, 0.163.0 or 0.164.0. A newer stable Codex 0.x release may continue only
181
+ 2.1.299, 2.1.300, 2.1.301, 2.1.302, 2.1.303, 2.1.311, 2.1.322 or 2.1.323, and Codex CLI 0.161.0,
182
+ 0.162.0, 0.162.1, 0.163.0, 0.164.0, 0.166.0 or 0.167.1 (0.165.0 and 0.167.0 were never
183
+ qualified; 0.167.0 shares the 0.167.1 contract, so the structural probe admits it). A newer stable Codex 0.x release may continue only
41
184
  after its locally generated experimental protocol schemas and transport flags
42
185
  match the bundled adapter contract; prereleases, older releases and new majors
43
186
  remain rejected. Starting with beta14, newer stable Claude 2.1 patches can
@@ -48,11 +191,45 @@ equivalence with a tested native release. Unknown older patches, prereleases
48
191
  and other major/minor families remain rejected. No credentials, conversations,
49
192
  model requests or JEV calls are used by these compatibility probes.
50
193
 
194
+ This candidate supports a qualified private Codex installation as well as managed Claude
195
+ Code. Use `aisac setup --host-codex managed` or `aisac setup --host-claude managed` to keep
196
+ AISAC's executable choice independent of global CLI updates. `--host managed` selects it
197
+ for one launch. From `0.4.0-beta.27`, `aisac setup` checks the global hosts before the
198
+ disclosure and the token. At a terminal it offers the tested private copy when one is
199
+ incompatible; without a terminal it stops with the command to run. Downloads use the signed
200
+ manifest's exact lock and are checked before launch; your global executables remain unchanged. Explicit system mode stays authoritative,
201
+ and ambiguous legacy settings never authorize an automatic download. See
202
+ [managed hosts](../../docs/how-to/aibrain-subscriber-beta.md#managed-hosts) for consent,
203
+ environment overrides, cached/offline behavior and the shared-session-state limitation.
204
+
51
205
  Beta17 refreshes the Codex contract to 0.164.0, including its image-generation
52
206
  record formats. Native launch/resume qualification is separate from a new
53
207
  model/JEV compaction qualification. A later native release that changes the
54
208
  consumed contract can still require an AI Brain compatibility update.
55
209
 
210
+ `0.4.0-beta.9` refreshes the bundled contract to Codex 0.166.0. Its delta is
211
+ additive: optional item timing, an image generation id, an attach-to-source fork
212
+ flag and two error codes. See the
213
+ [Codex 0.166 qualification record](../../docs/reference/codex-166-compatibility-2026-11-04.md).
214
+
215
+ `0.4.0-beta.16` refreshes the bundled contract to Codex 0.167.1 and qualifies Claude Code
216
+ 2.1.311 and 2.1.322. The Codex delta is additive: audio inputs may reference an uploaded
217
+ file (`fileId` / `file_id`) instead of a URL, `initialize` gains the optional
218
+ `requiredHumanApproval` capability and `humanCommand` becomes an approval kind only
219
+ clients that declare it receive. See the
220
+ [Codex 0.167 qualification record](../../docs/reference/codex-167-compatibility-2026-11-11.md)
221
+ and the [Claude 2.1.322 record](../../docs/reference/claude-322-compatibility-2026-11-11.md).
222
+
223
+ `0.4.0-beta.17` adds `aisac scan`, keeps the pack's `scan/` rules out of every session
224
+ (like `init/`), and lets a command exit with `3`. The qualified Claude Code and Codex
225
+ versions are those of `0.4.0-beta.16`.
226
+
227
+ `0.4.0-beta.18` qualifies Claude Code 2.1.323. Its `claude plugin validate` type-checks the
228
+ hook modules, so the bundled plugin now type-checks under the host's tsconfig (typing only,
229
+ no behaviour change) and ships `provider-window.d.ts`; the host probe also reads an
230
+ inventory that the validator wraps across several notes. See the
231
+ [Claude 2.1.323 record](../../docs/reference/claude-323-compatibility-2026-11-12.md).
232
+
56
233
  The Codex terminal bridge permits the native session picker's separate read-only
57
234
  connection while keeping the primary conversation and monitor intact. A picker
58
235
  cannot compact, start a turn, inject history or take ownership of the primary
@@ -61,7 +238,9 @@ connection. Its failure or timeout closes only that auxiliary connection.
61
238
  ```sh
62
239
  # Install the published beta:
63
240
  npm install -g @aisac/cli@beta
64
- aisac setup --client both
241
+ aisac setup # browser sign-in, then configures clients on PATH
242
+ aisac setup --login # replace the AI Brain login without changing setup choices
243
+ aisac setup --paste-token # choose the manual masked-token alternative
65
244
  aisac doctor --json
66
245
  aisac claude
67
246
  aisac codex
@@ -72,11 +251,18 @@ then run `npm uninstall -g @brunobracaioli/aibrain` before
72
251
  `npm install -g @aisac/cli@beta`. Setup, notes and checkpoints are kept.
73
252
 
74
253
  Installation does not contact AI Brain, change native client configuration, or
75
- enable all paid accounts. Setup requires an existing AI Brain PAT, explicit
76
- versioned disclosure, and successful provider-free pilot access. Claude and
77
- Codex continue to own their own authentication. Windows native is unsupported;
78
- run the beta inside WSL. Pricing and general customer activation are outside
79
- this beta.
254
+ enable all paid accounts. At a terminal, `aisac setup` starts a browser sign-in:
255
+ enter the purchase email, compare the short code, and approve the request. The
256
+ token stays out of the clipboard. Browser opening is best effort; copy the printed
257
+ address when no browser opens. Use `--paste-token` for the manual masked prompt,
258
+ or `--token-file` for reviewed noninteractive automation. `aisac setup --login`
259
+ replaces only the AI Brain credential in an existing setup. Setup still requires
260
+ explicit versioned disclosure and successful provider-free pilot access. Claude
261
+ and Codex continue to own their own authentication. Windows native is unsupported;
262
+ run the beta inside WSL. On macOS, Codex capture locks with the system
263
+ `/usr/bin/perl` (`flock(2)`) and identifies the lock owner with `sysctl` and
264
+ `ps`, so nothing extra needs installing. Pricing and general customer
265
+ activation are outside this beta.
80
266
 
81
267
  For reviewed noninteractive automation only, use a private token file and
82
268
  explicitly acknowledge the displayed disclosure with
@@ -151,7 +151,7 @@ type Register = (
151
151
  ) => void;
152
152
 
153
153
  const MAX_RESULT_BYTES = 256 * 1024;
154
- const CLAUDE_HOOK_VERSION = '0.4.0-beta.1';
154
+ const CLAUDE_HOOK_VERSION = '0.4.0-beta.7';
155
155
  const MAX_DIAGNOSTIC_BYTE_COUNT = 128 * 1024 * 1024;
156
156
  const COOLDOWN_MS = 60_000;
157
157
  const MAX_TRUNCATED_CODE_POINTS = 300;
@@ -463,6 +463,10 @@ function v2WireOptions(options: V2Options): Record<string, unknown> {
463
463
 
464
464
  function safeErrorCategory(error: unknown): string {
465
465
  const record = isRecord(error) ? error : {};
466
+ // A coded error names its own reason; the keyword guess below would read
467
+ // "AI Brain plan does not meet the minimum estimated reduction" as invalid_plan.
468
+ if (COMPACT_ERROR_CODES.includes(record.compactErrorCode as CompactErrorCode))
469
+ return record.compactErrorCode as CompactErrorCode;
466
470
  const code = typeof record.code === 'string' ? record.code.toLowerCase() : '';
467
471
  const name = typeof record.name === 'string' ? record.name.toLowerCase() : '';
468
472
  const message = typeof record.message === 'string' ? record.message.toLowerCase() : '';
@@ -4504,11 +4508,19 @@ type ClaudeTelemetry = {
4504
4508
  disconnected(): boolean;
4505
4509
  flush(timeoutMs?: number): Promise<void>;
4506
4510
  };
4511
+ // The host tsconfig (lib es2023 only) declares no timers; the hook runtime provides them
4512
+ // on globalThis, so the handle stays opaque and the defaults are read from there.
4513
+ type ClaudeTimerHandle = unknown;
4507
4514
  type ClaudeTelemetryTimers = {
4508
- setTimeout(callback: () => void, delay: number): ReturnType<typeof setTimeout>;
4509
- clearTimeout(timer: ReturnType<typeof setTimeout>): void;
4515
+ setTimeout(callback: () => void, delay: number): ClaudeTimerHandle;
4516
+ clearTimeout(timer: ClaudeTimerHandle): void;
4510
4517
  };
4511
4518
 
4519
+ function hostTelemetryTimers(): ClaudeTelemetryTimers {
4520
+ const host = globalThis as unknown as ClaudeTelemetryTimers;
4521
+ return { setTimeout: host.setTimeout, clearTimeout: host.clearTimeout };
4522
+ }
4523
+
4512
4524
  const TELEMETRY_HELPER_MAX_STDOUT_BYTES = 8 * 1024;
4513
4525
 
4514
4526
  type TelemetryHelperConfiguration = 'none' | 'valid' | 'invalid';
@@ -4673,7 +4685,7 @@ export function createClaudeTelemetryReporter(
4673
4685
  getSessionId: () => PromiseLike<string> | string,
4674
4686
  sendReport: (payload: Record<string, unknown>) => PromiseLike<unknown> | unknown,
4675
4687
  now: () => number = () => Date.now(),
4676
- timers: ClaudeTelemetryTimers = { setTimeout, clearTimeout },
4688
+ timers: ClaudeTelemetryTimers = hostTelemetryTimers(),
4677
4689
  ): ClaudeTelemetry {
4678
4690
  const active =
4679
4691
  enabled === true &&
@@ -4748,7 +4760,7 @@ export function createClaudeTelemetryReporter(
4748
4760
  if (attempt.expired) return;
4749
4761
  if (!telemetryAckAccepted(response)) throw new Error('telemetry_report_rejected');
4750
4762
  })();
4751
- let timer: ReturnType<typeof setTimeout> | undefined;
4763
+ let timer: ClaudeTimerHandle | undefined;
4752
4764
  void (async () => {
4753
4765
  try {
4754
4766
  await Promise.race([
@@ -1,4 +1,4 @@
1
- import { register as registerContext } from './context-compaction.ts';
1
+ import { register as registerContext } from './context-compaction.js';
2
2
 
3
3
  export function register(on: Parameters<typeof registerContext>[0]): void {
4
4
  return registerContext(on, {
@@ -10,7 +10,7 @@ const contractTest: Parameters<typeof test>[2] = async ($, on) => {
10
10
  on('session.usage', () => ({
11
11
  value: (() => {
12
12
  usageCalls += 1;
13
- return { context: { percent: 90, tokens: 900, window: 1_000 } };
13
+ return { startedAt: 0, context: { percent: 90, tokens: 900, window: 1_000 }, rateLimits: [] };
14
14
  })(),
15
15
  }));
16
16
  on('ui.log', () => ({ value: undefined }));
@@ -23,17 +23,21 @@ const contractTest: Parameters<typeof test>[2] = async ($, on) => {
23
23
  };
24
24
  });
25
25
  on('turn.complete', () => ({ text: '' }));
26
- const prompt = await $.prompt.submit({ text: 'native-host-contract-input' });
26
+ const prompt = await $.prompt.submit({
27
+ text: 'native-host-contract-input',
28
+ wait: false,
29
+ origin: { kind: 'composer' },
30
+ });
27
31
  const tool = await $.tool.call({ tool: 'Read', file_path: 'native-host-contract.txt' });
28
32
  await $.turn.complete({
29
33
  turnId: 'native-contract-turn',
30
34
  answer: 'native-turn-contract-ok',
31
35
  durationMs: 1,
32
36
  isAborted: false,
33
- usage: null,
37
+ reason: 'answer',
34
38
  });
35
39
  expect(prompt.text).toBe('native-host-contract-ok');
36
- expect(tool.result.content).toBe('native-host-tool-ok');
40
+ expect((tool.result as { readonly content: unknown }).content).toBe('native-host-tool-ok');
37
41
  expect(usageCalls).toBe(1);
38
42
  expect(compactCalls).toBe(1);
39
43
  const monotonicEnd = globalThis.performance?.now?.();
@@ -0,0 +1,83 @@
1
+ import type { ProviderFitOptions, ProviderFitPreflight, ProviderFitProjection, ProviderFitProjectionMessage, ProviderFitProjectionPair } from './state-fitting.mjs';
2
+ export declare const PROVIDER_WINDOW_MAX_PAIRS = 200;
3
+ export declare const PROVIDER_WINDOW_MAX_MESSAGES = 1000;
4
+ export declare const PROVIDER_WINDOW_MAX_REFERENCES = 200;
5
+ export declare const PROVIDER_WINDOW_MAX_REQUEST_BYTES: number;
6
+ export declare const PROVIDER_WINDOW_REQUEST_HEADROOM_BYTES: number;
7
+ export declare const PROVIDER_WINDOW_MAX_SEARCH_ATTEMPTS = 12;
8
+ export declare const PROVIDER_WINDOW_MAX_STATE_TOKENS = 25000;
9
+ export declare const PROVIDER_WINDOW_MAX_REQUEST_TOKENS = 30000;
10
+ export declare const PROVIDER_WINDOW_MAX_RESERVED_TOKENS = 120000;
11
+ export declare const PROVIDER_WINDOW_OUTPUT_TOKEN_ALLOWANCE = 4000;
12
+ export type ProviderWindowMessage = ProviderFitProjectionMessage;
13
+ export interface ProviderWindowPair extends ProviderFitProjectionPair {
14
+ readonly callId: string;
15
+ readonly resultId: string;
16
+ readonly callMessage: number;
17
+ readonly resultMessage: number;
18
+ readonly resultText: string;
19
+ readonly protectedPair: boolean;
20
+ }
21
+ export interface ProviderWindowProjection {
22
+ readonly goal: string;
23
+ readonly messages: readonly ProviderWindowMessage[];
24
+ readonly pairs: readonly ProviderWindowPair[];
25
+ readonly protectedItemCount: number;
26
+ }
27
+ export interface ProviderWindowWireProjection {
28
+ readonly goal: string;
29
+ readonly messages: readonly {
30
+ readonly id: string;
31
+ readonly role: 'user' | 'assistant';
32
+ readonly text: string;
33
+ readonly call_ids: readonly string[];
34
+ readonly result_ids: readonly string[];
35
+ }[];
36
+ readonly pairs: readonly {
37
+ readonly id: string;
38
+ readonly tool: string;
39
+ readonly input_text: string;
40
+ readonly result_chars: number;
41
+ readonly result_is_error: boolean;
42
+ readonly eligibility: 'reproducible_read' | 'compatible_tool' | 'protected';
43
+ readonly pin_reasons: readonly string[];
44
+ }[];
45
+ readonly protected_item_count: number;
46
+ }
47
+ export interface ProviderWindowOptions extends ProviderFitOptions {
48
+ readonly preserveRecentMessages: number;
49
+ readonly maxPairs?: number;
50
+ readonly maxMessages?: number;
51
+ readonly maxReferencesPerMessage?: number;
52
+ readonly maxRequestBytes?: number;
53
+ readonly requestHeadroomBytes?: number;
54
+ readonly maxReservedTokens?: number;
55
+ /** Shared capacity snapshot limits. These are advisory; backend admission remains authoritative. */
56
+ readonly maxBatchesPerOperation?: number;
57
+ readonly outputTokenAllowance?: number;
58
+ }
59
+ export interface ProviderWindowPreflight extends ProviderFitPreflight {
60
+ readonly requestBytes: number;
61
+ readonly estimatedReservationTokens: number;
62
+ }
63
+ export interface ProviderWindowSuccess {
64
+ readonly ok: true;
65
+ readonly projection: ProviderWindowWireProjection;
66
+ readonly pairs: readonly ProviderWindowPair[];
67
+ readonly deferredPairs: readonly ProviderWindowPair[];
68
+ readonly preflight: ProviderWindowPreflight;
69
+ readonly attempts: number;
70
+ readonly anchorPairCount: number;
71
+ readonly selectedEligibleCount: number;
72
+ }
73
+ export type ProviderWindowFailureReason = 'anchor_overflow' | 'message_limit_exceeded' | 'no_feasible_window';
74
+ export interface ProviderWindowFailure {
75
+ readonly ok: false;
76
+ readonly reason: ProviderWindowFailureReason;
77
+ readonly attempts: number;
78
+ readonly anchorPairCount: number;
79
+ }
80
+ export type ProviderWindowResult = ProviderWindowSuccess | ProviderWindowFailure;
81
+ type ProviderFit = (projection: ProviderFitProjection, eligible: readonly ProviderFitProjectionPair[], options: ProviderFitOptions) => ProviderFitPreflight;
82
+ export declare function prepareProviderWindow(input: ProviderWindowProjection, options: ProviderWindowOptions, fit?: ProviderFit): ProviderWindowResult;
83
+ export {};