@aragon-agent/core 0.2.63 → 0.2.65

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/CHANGELOG.md CHANGED
@@ -1,12 +1,32 @@
1
- # Changelog
2
-
3
- All notable changes to `@aragon-agent/core` are documented here. Entries at
4
- `0.1.x` and earlier refer to the package by its former name, `@argon-agent/core`
5
- — those releases really were published under that name, so they are left as they
6
- were written.
7
-
1
+ # Changelog
2
+
3
+ All notable changes to `@aragon-agent/core` are documented here. Entries at
4
+ `0.1.x` and earlier refer to the package by its former name, `@argon-agent/core`
5
+ — those releases really were published under that name, so they are left as they
6
+ were written.
7
+
8
8
  ## Unreleased
9
9
 
10
+ ### Changed
11
+
12
+ - **Behaviour change: pictures returned by a tool now reach the model.** A successful tool result that
13
+ contains an `image` block (`imageResult(...)`, or `multiResult([...])` with an image) is kept in the
14
+ history as a `ContentPart[]` and sent with the next request. Until now the agent loop flattened every
15
+ image to the text `[image: image/png]`, so the `ToolResultContent` image type and the helpers were
16
+ present but inert. Text-only results are unchanged (a `string`, blocks joined with `\n`), and an error
17
+ result (`isError: true`) is still flattened to text. No new export (the runtime export count is
18
+ unchanged).
19
+ - **The adapters now put a tool picture on the wire.** Anthropic already supported images inside
20
+ `tool_result` and needed no change. **OpenAI** keeps the text in the `tool` message (plus a short
21
+ "the image follows" line) and sends the picture in a `user` message with an `image_url` part, placed
22
+ after the last consecutive `tool` message of the assistant turn (OpenAI requires them to be contiguous).
23
+ **Google** keeps the text in `functionResponse` and sends the picture in a following `user` turn with
24
+ `inlineData`. The OpenAI adapter no longer `JSON.stringify`s an array `tool_result.content` (a text-only
25
+ array is joined with `\n`).
26
+ - **Migration.** If your host's tools return `imageResult(...)` and you run a model that cannot read
27
+ images, install `AgentConfig.projectMessages` to replace the pixels with text for that model (it only
28
+ rewrites the copy sent to the provider). A host whose tools never return images sees no difference.
29
+
10
30
  ### Fixed
11
31
 
12
32
  - Model context resolution now reads explicit OpenAI-compatible, Anthropic and
@@ -17,361 +37,368 @@ were written.
17
37
  deadline. All three adapters accept cancellation; cancelled or invalidated
18
38
  lookups cannot overwrite current metadata. Clearing one provider's cache leaves
19
39
  other providers' pending discoveries intact.
20
-
40
+
21
41
  ### Added
22
42
 
43
+ - **Multimodal steering, request-time projection, image token estimate.** `Agent.steer(text, id?, parts?)`
44
+ queues a multimodal message (`SteeringMessage.parts`; absent = byte-identical text path);
45
+ `AgentConfig.projectMessages` rewrites the history copy sent to the provider only (the message
46
+ manager is never touched; no projection configured = unchanged); `IMAGE_TOKEN_ESTIMATE` (1600,
47
+ was an implicit ~256) is exported and drives `estimatePromptTokens` for image parts. One new
48
+ runtime export (`IMAGE_TOKEN_ESTIMATE`, 86 → 87). Sessions without images are unaffected.
49
+
23
50
  - **Steering 精确接收回执。** `Agent.steer(text, id?)` 兼容原单参数调用,
24
51
  历史接收后发出 `steering_accepted`,只确认当前批次的 ID;新增类型
25
52
  `SteeringMessage` 和 `SteeringAcceptedEvent`,无新增运行时导出。
26
53
  `drainSteeringItems()` 与原 `drainSteering()` 共用一个队列。
27
54
  接收早于异步压缩,未执行工具先补齐 skipped 结果;无工具响应在结束前再次检查
28
55
  steering,避免流式输出期间提交的消息滞留。回执仅代表历史接收,不代表回答完成。
29
-
30
- - **Tail relief — the last rung of the compaction ladder.** `relieveTail` joins
31
- the root barrel with `TailReliefOptions` and `TailReliefResult` (85 → 86
32
- runtime exports), and `compaction_end` gains an optional `tailRelief` field.
33
-
34
- Every existing rung operates on the HEAD of a history. When the RETAINED tail
35
- is what does not fit — a few turns carrying several 100 KB tool results — each
36
- of them reports success or "nothing to drop" while the conversation stays
37
- un-sendable. `relieveTail` clips oversized `tool_result` bodies in place,
38
- oldest first, and stops as soon as the projection is under budget.
39
-
40
- It is **structure-preserving by construction**: no message is removed, no
41
- `toolCallId` is touched, no role changes, so a history that passed
42
- `validateHistory` before still passes after. That is what makes it safe to run
43
- on an already-spliced history, and it is why relief clips rather than drops.
44
- Every clip is announced in the text the model reads, at the exact place the
45
- data was removed, through a `marker` callback the host supplies — this package
46
- owns no glyphs.
47
-
48
- `compaction_end.tailRelief` is optional, so a subscriber that does not know
49
- about it is unaffected.
50
-
51
- - **Context compaction — one injected port, and the engine refuses a bad
52
- splice.** `AgentConfig.contextManager?: ContextManager` is called at every turn
53
- boundary (after the steering drain, before `turn_start`). When it says so, the
54
- engine hands it a **copy** of the history, adopts whatever comes back — and
55
- validates it first.
56
-
57
- `findSafeCutIndices`, `planCompaction` and `validateHistory` join the root
58
- barrel, along with `CHARS_PER_TOKEN`, which was module-private (81 → 85 runtime
59
- exports). Two new `AgentEvent` members, `compaction_start` and
60
- `compaction_end`, carry the story; a consumer with a `default` branch is
61
- unaffected.
62
-
63
- **The mechanism is here; the policy is the host's.** This package holds a
64
- `ModelRef` and never a `ModelInfo`, so the threshold, the summarizer, the
65
- prompt and the failure ladder are all decisions on the other side of the port.
66
-
67
- Four properties are load-bearing and each is asserted by a test:
68
-
69
- - **Off is free.** With no `contextManager` the checkpoint is one `if` against
70
- an absent field — no promise allocation, no events, no behaviour change.
71
- - **The engine validates and may refuse.** An orphan `tool_result`, an unclosed
72
- `tool_call`, an empty array or a history that grew is not adopted; the run
73
- continues on the original and `compaction_end` reports
74
- `invalid_history: <reason>`. An orphan `tool_result` is an unrecoverable 400
75
- on Anthropic, so a host bug must not be able to produce one.
76
- - **The call cannot hang the run.** `compaction_start` pauses the idle
77
- watchdog, so the engine races `compact()` against the run's signal **and** a
78
- 120 s ceiling of its own, and emits `compaction_end` from a `finally` — which
79
- is what resumes the watchdog. A non-settling promise, an ignored signal or a
80
- malformed return value each degrade to "compaction did not happen".
81
- - **The host gets a copy.** `ctx.messages` is a shallow copy, so a host that
82
- splices it in place cannot corrupt engine state before the gate sees it.
83
-
84
- **`compaction` is now a legitimate word in the engine**, which makes RT-4's
85
- original claim ("no history-trimming API exists") false by design. That guard
86
- now asserts the narrower and more useful thing: history shrinks in exactly one
87
- place, and that place goes through `validateHistory`. The skill digest's
88
- `force=true` escape hatch — added for a *truncated* earlier copy — covers a
89
- *compacted-away* one unchanged, and is pinned by a test.
90
-
91
- - **`llm/retry.ts` — retry with exponential backoff, ON BY DEFAULT.**
92
- `RETRY_LIMITS`, `DEFAULT_RETRY_POLICY`, `isRetryableError`,
93
- `computeBackoffDelay`, `parseRetryAfterMs` and `withRetry` are exported from the
94
- root barrel (75 → 81 runtime exports). `ProviderRegistry.stream()` wraps every
95
- provider stream, so the agent loop, every subagent and `ProviderRegistry`
96
- itself inherit retry with no call-site changes.
97
-
98
- A transient failure — 429, 529, 5xx, DNS/TLS/ECONNRESET, 408 — is now retried
99
- up to **10 times** with an increasing, equal-jittered interval
100
- (1 s → 2 → 4 → 8 → 16 → 30 s, capped at 30 s per wait) under a **240 s**
101
- wall-clock budget measured from the first failure. `auth_error`,
102
- `invalid_request`, `context_overflow` and `unknown` are never retried: ten
103
- retries of a bad API key is three minutes of looking broken.
104
-
105
- A user abort is never retried, and this is the load-bearing detail:
106
- `wrapFetchError` marks an `AbortError` `retryable: true`, so
107
- `isRetryableError` reads `signal.aborted` **before** `err.retryable`. An
108
- aborted request yields no further event of any kind — in particular no `error`
109
- — so nothing fabricates a network failure out of Esc.
110
-
111
- `Retry-After` (and `x-ratelimit-reset-after` /
112
- `anthropic-ratelimit-requests-reset` / `anthropic-ratelimit-input-tokens-reset`)
113
- is honoured as a **floor**, never a replacement, and a value above 60 s is
114
- surfaced immediately rather than waited out.
115
-
116
- - **Three new `StreamEvent` variants** — `RetryScheduledEvent`,
117
- `RetryAttemptEvent`, `StreamRestartEvent`. Additive: `consumeStream` ignores
118
- anything that is not `done`/`error`, and a consumer with a `default` branch is
119
- unaffected. `retry_scheduled` carries `resumeAt` (an absolute instant) rather
120
- than a tick stream, so a UI owns its own clock.
121
-
122
- - **`ProviderRegistry` holds a policy.** New `ProviderRegistryOptions`,
123
- `setRetryPolicy(policy | null)` and `getRetryPolicy()`;
124
- `initProviders(options?)` forwards them. `undefined` means the product default,
125
- an explicit `null` means opt out.
126
-
127
- - **`LLMError` gains a 7th optional field `retryAfterMs`**, and
128
- `classifyHttpError` an optional 4th parameter `headers?: Headers`. Both
129
- additive; every existing call site compiles unchanged.
130
-
131
- - **`Agent` pauses its idle watchdog across a backoff.** A 30 s wait would
132
- otherwise be read as a wedged call and abort the run at `idleTimeout`.
133
-
134
- - **`llm/output-limits.ts` — one authority for the output-token cap.**
135
- `DEFAULT_MAX_OUTPUT_TOKENS` (64000), `MIN_MAX_OUTPUT_TOKENS`,
136
- `SAFE_FALLBACK_MAX_OUTPUT_TOKENS`, `ABSOLUTE_MAX_OUTPUT_TOKENS`,
137
- `THINKING_HEADROOM_TOKENS`, `CONTEXT_SAFETY_MARGIN_TOKENS`,
138
- `resolveOutputTokens`, `staticCeilingFor`, `learnModelCeiling`,
139
- `getLearnedCeiling`, `clearLearnedCeilings` and `estimatePromptTokens` are all
140
- exported from the root barrel. The three provider adapters no longer carry
141
- private copies of the default; they resolve through this module.
142
-
143
- The resolver treats the default as an *ambition* and the model's real ceiling
144
- as the law, ranking four sources — learned-from-error > discovery > a static
145
- per-model table > the product default — so an over-large cap is clamped instead
146
- of becoming an HTTP 400 that ends the run. It also reconciles Anthropic's
147
- `max_tokens > thinking.budget_tokens` invariant, which `--thinking xhigh` broke
148
- on every request.
149
-
150
- - **`llm/output-limit-recovery.ts` — one-shot self-healing.**
151
- `classifyOutputLimitFailure`, `sendWithOutputLimitRecovery`, `learnTokenField`,
152
- `getLearnedTokenField` and `clearLearnedTokenFields`. A 400 that names an
153
- output-limit problem is repaired and re-sent **once** — never a loop — and what
154
- was learned is remembered for the rest of the process. A 2xx is returned with
155
- its body untouched, so streaming is unaffected. OpenAI's reasoning family,
156
- which rejects `max_tokens` in favour of `max_completion_tokens`, is handled by
157
- a heuristic plus this memo.
158
-
159
- - **`LLMRequest.modelLimits?: { maxOutputTokens?, contextWindow? }`** — optional
160
- caller-supplied metadata. Supplying `contextWindow` enables the
161
- `max_tokens + prompt <= context` guard on OpenAI. Every existing caller
162
- compiles unchanged.
163
-
164
- ### Changed
165
-
166
- - **BEHAVIOUR CHANGE — retry is on by default for embedders.** A failing call
167
- that used to end immediately can now take up to ~3 minutes to fail. The budget
168
- bounds it; `initProviders({ retryPolicy: null })` or `setRetryPolicy(null)`
169
- restores the old behaviour exactly, and `maxRetries: 0` short-circuits the
170
- wrapper so the opted-out path is byte-identical.
171
-
172
- - **BEHAVIOUR CHANGE — a truncated stream is now a loud error instead of a
173
- silent success.** All three adapters used to end their SSE loop by
174
- *unconditionally* yielding `done` with whatever had accumulated. A stream
175
- closed gracefully mid-answer — a proxy idle cut, a load-balancer timeout, an
176
- HTTP/2 GOAWAY, `[DONE]` never arriving — therefore surfaced as **success
177
- carrying a truncated answer**, which no layer above the adapter could tell from
178
- a real one. Each adapter now tracks its own terminal sentinel
179
- (`message_stop` / `[DONE]` **or** a `finish_reason` / a chunk carrying
180
- `finishReason`) and yields a retryable `network_error` when the stream ends
181
- without it. Consequences:
182
-
183
- - the mid-answer disconnection case is now retried and recovered;
184
- - `ProviderRegistry.complete()` / `provider.complete()` change from returning a
185
- partial `AssistantMessage` to **throwing** for a truncated stream;
186
- - an **abort** is explicitly excluded and still yields `done`, and an empty but
187
- complete turn is still a success.
188
-
189
- This is deliberately **not** behind the retry switch: an adapter that reports a
190
- truncated stream honestly should do so whether or not retry is enabled.
191
-
192
- - **HTTP 408 is now `errorType: 'timeout'`, `retryable: true`** (it used to fall
193
- into `unknown` / non-retryable).
194
-
195
- - **`ProviderRegistry.complete()` now routes through `this.stream()`** instead of
196
- `provider.complete()`. Behaviour-preserving — all three adapters implement
197
- `complete` as exactly `consumeStream(this.stream(request))` — except that the
198
- registry's version is now the retrying one.
199
-
200
- - `ModelRegistry.buildRuntimeModel` defaults `maxOutputTokens` to
201
- `DEFAULT_MAX_OUTPUT_TOKENS` rather than a private `16384`, the built-in
202
- Anthropic catalog entries carry their real ceilings, and `registerDefaults` /
203
- `discoverModels` seed the shared ceiling cache. `listModels` on the Anthropic
204
- and OpenAI adapters now maps through the static table instead of asserting the
205
- product default for every model — neither API reports an output ceiling, and
206
- claiming otherwise outranked the correct value for every small model.
207
-
208
- ### Notes
209
-
210
- - **`streamLLM` / `completeLLM` diverge from a registry you build yourself.**
211
- They resolve through `getProviderRegistry()`, which lazily calls
212
- `initProviders()` with no arguments, so they always carry
213
- `DEFAULT_RETRY_POLICY` and do not observe a policy installed elsewhere. For one
214
- policy everywhere, call `setProviderRegistry(initProviders({ retryPolicy }))`
215
- once at startup.
216
-
217
- - **A half-open connection is still not covered** (no FIN, no RST). It produces
218
- no event, so `withRetry` never wakes and the idle watchdog aborts the run. A
219
- per-attempt stall timer is not safe at this layer: Anthropic's `ping` frames
220
- are swallowed by the adapter, so a long extended-thinking pause and a dead
221
- socket look identical at the `StreamEvent` layer.
222
-
223
- ## 0.3.0
224
-
225
- ### Added
226
-
227
- - **`Agent.pauseIdleWatchdog()` / `Agent.resumeIdleWatchdog()`** — suspend and
228
- restart the idle watchdog around a tool that blocks on a human. Both are
229
- idempotent, and a paused watchdog also swallows `kick()`, so an event arriving
230
- mid-wait cannot silently re-arm it. Always pair them in a `try/finally`: a
231
- throw inside the wait must not leave the watchdog disarmed for the rest of the
232
- run. The host is the only party that can know a person is being waited on —
233
- from inside the loop that call is indistinguishable from a wedged network
234
- request.
235
-
236
- - **`AgentConfig.timeouts.toolTimeoutOverrides?: Record<string, number>`** —
237
- per-tool ceilings keyed by tool name, forwarded to `ToolExecutor`'s existing
238
- `timeoutOverrides`. This is pure wiring of a capability the executor already
239
- had and that was unreachable through `Agent`.
240
-
241
- Read this before relying on it: `ToolExecutor` expresses a timeout by aborting
242
- `context.signal` and then *continuing to await* the tool's promise — there is
243
- no `Promise.race`. A tool that never observes `context.signal` is therefore
244
- never timed out, and the number set here is inert for it, with no error
245
- anywhere. See *Blocking on a human* in `API.md`.
246
-
247
- ### Fixed
248
-
249
- - `IdleWatchdog.stop()` now clears the paused flag. Without it a run aborted
250
- while paused would leave the watchdog deaf for every subsequent run, because
251
- `start()` goes through `kick()` and `kick()` returns early while paused.
252
-
253
- ### Notes
254
-
255
- - **No change to the export surface.** The two new members are instance methods
256
- and the third is a config field, so `src/index.ts` and the `EXPECTED` list in
257
- `public-api.test.ts` are untouched.
258
-
259
- ## 0.2.0
260
-
261
- ### Breaking
262
-
263
- - **The package is renamed `@argon-agent/core` → `@aragon-agent/core`.** The
264
- brand was always meant to be *Aragon*, matching AragonMesh; the missing `a`
265
- was a typo that reached the registry. `@argon-agent/core` is deprecated and
266
- receives no further releases.
267
-
268
- Every subpath keeps its shape — only the scope changes:
269
-
270
- ```diff
271
- - import { Agent } from '@argon-agent/core';
272
- + import { Agent } from '@aragon-agent/core';
273
- - import type { LlmMessage } from '@argon-agent/core/llm/types';
274
- + import type { LlmMessage } from '@aragon-agent/core/llm/types';
275
- ```
276
-
277
- - **The exported alias `ArgonAgent` is now `AragonAgent`.** It remains an alias
278
- of `Agent`, which is unchanged — code importing `Agent` needs no edit.
279
-
280
- ### Added
281
-
282
- - **Skill system (pure-logic half).** New `src/skills/` module and a `./skills`
283
- subpath export: `SkillRegistry`, `parseFrontmatter`,
284
- `validateSkillFrontmatter`, `validateStagedSkill`, `renderSkillCatalog`,
285
- `renderSkillBody`, `renderSkillInvocation`, `applySkillArguments`,
286
- `suggestSkillNames`, `sanitizeForPromptBlock`, `createSkillTool`, and the
287
- `SKILL_*` budget constants. The root runtime surface grows from 33 to 56
288
- value exports; see `API.md`.
289
- - **`rankCatalogRecords(records, { usage, now })`** — orders the Level 1 catalog
290
- by scope, then by usage recency and frequency, using integer buckets so the
291
- result stays byte-reproducible. Invariant: called without a usage map it is
292
- element-for-element identical to `catalogRecords()`, which is what keeps every
293
- existing catalog snapshot valid.
294
- - **`createSkillFindTool(deps)` / `renderSkillFindResults(query, matched, opts)`**
295
- — the `skill_find` tool and its rendering, for reaching skills that did not fit
296
- in the catalog. Searches only the injected registry: no network, no
297
- `activation: manual` skills, and an explicit refusal to invent an install
298
- source when nothing matches. Same sanitisation and byte budget discipline as
299
- the catalog (`SKILL_FIND_MAX_BYTES`).
300
- - Types `SkillIntegrity`, `SkillUsageStat`, `SkillUsageMap`, `SkillFindOptions`;
301
- `SkillRecord.integrity`; optional `SkillManifestSource.resolvedRef` and
302
- `SkillManifest.updatedAt` / `previousVersion` (additive — the manifest schema
303
- version is deliberately unchanged so an older CLI still reads them).
304
- - All filesystem access goes through the injected `SkillHost` port, so the
305
- package still imports no `node:*` builtin outside the one grandfathered
306
- `node:crypto` in `llm/providers/google.ts`.
307
- - **Release tooling for the scope change.** `npm run verify:brand` derives the
308
- list of files that would enter the tarball from `npm pack --dry-run --json`
309
- and refuses the release if any of them still mentions the old brand — README
310
- included, with only the four documented exceptions. It runs inside
311
- `publish-latest.ps1` and cannot be skipped. `npm run preflight` answers "would
312
- a real publish succeed?" before any version file is touched, and
313
- `npm run verify:published` checks afterwards that the registry really serves
314
- the renamed package, README and repository link included.
315
-
316
- ### Changed
317
-
318
- - `no-host-coupling.test.ts` now also asserts that **no** file under `src/`
319
- imports a `node:*` builtin, with a single documented allowlist entry and a
320
- self-check so the assertion cannot pass vacuously. This guarantee was
321
- previously assumed but never actually checked.
322
- - Added a repository-level PowerShell release workflow that versions, verifies,
323
- and publishes Core before the dependent CLI, with dry-run rollback and
324
- partial-release resume support.
325
-
326
- ### Security
327
-
328
- - Every span of third-party text is passed through `sanitizeForPromptBlock()`
329
- before it is concatenated into a tagged prompt block. Without it a skill
330
- description containing `</available_skills>` could close the block and have
331
- the text after it read as top-level system-prompt instructions.
332
- - All skill budgets are measured in UTF-8 **bytes**. A character-based budget
333
- is ~3x under-counted for CJK text, which pushed results past `ToolExecutor`'s
334
- 100 000-byte ceiling and truncated the closing tag off the block.
335
-
336
- ## 0.1.0
337
-
338
- Initial extraction of the ArgonAgent engine from the AragonMesh code base
339
- (`server/agent-core/`) into a standalone, publishable package.
340
-
341
- - Zero-coupling agent engine: LLM provider adapters (Anthropic, OpenAI,
342
- Google), streaming, provider registry, model registry.
343
- - Tool system: typed tool definitions, registry, JSON-Schema validator (with
344
- built-in fallback), executor.
345
- - Engine: multi-turn agent loop, message manager, steering queue, idle
346
- watchdog.
347
- - Optional isolated-vm CodeAct sandbox (lazy-loaded).
348
- - Adds the `ArgonAgent` export as an alias of the `Agent` class.
349
-
350
- Publish-readiness (still part of the unreleased `0.1.0`):
351
-
352
- - Added `publishConfig.access:"public"` (required for scoped public publish),
353
- a `prepublishOnly` build guard, and a package-directory `LICENSE`.
354
- - `files` now ships `CHANGELOG.md` alongside `dist`.
355
- - Added `typesVersions` so consumers on the legacy `moduleResolution:"node"`
356
- can resolve the subpath type declarations.
357
- - Declared `sideEffects:false` (the barrel is pure re-exports) to aid
358
- downstream tree-shaking.
359
- - Added discovery metadata: `keywords` / `author` / `repository` / `homepage`
360
- / `bugs`.
361
- - Added a compile-checked `examples/minimal.ts` usage sample (not shipped in the
362
- tarball).
363
-
364
- Reuse-verification harness (still part of the unreleased `0.1.0`):
365
-
366
- - Added `examples/consumer-smoke/run.mjs` + the `verify:dist` script: runs the
367
- built `dist/` like an external consumer (Node package self-referencing →
368
- `exports` map → `dist/`), driving `ArgonAgent` end-to-end with an offline stub
369
- provider and asserting every `exports` subpath resolves at runtime.
370
- - Added a public-API contract snapshot (`src/__tests__/public-api.test.ts` +
371
- `API.md`) that freezes the runtime export surface against silent drift.
372
- - Added a `no-host-coupling` guard test that forbids host-repo imports
373
- (`@server/`, `@shared/`, `@/`, out-of-package `../../../`) and legacy-brand
374
- leakage on the public surface.
375
- - Added a publish guard: `scripts/check-publishable.mjs` (wired into
376
- `prepublishOnly`) hard-blocks publishing while the `<ORG>` placeholder remains
377
- in `package.json`, and `scripts/stamp-org.mjs` replaces it in one command.
56
+
57
+ - **Tail relief — the last rung of the compaction ladder.** `relieveTail` joins
58
+ the root barrel with `TailReliefOptions` and `TailReliefResult` (85 → 86
59
+ runtime exports), and `compaction_end` gains an optional `tailRelief` field.
60
+
61
+ Every existing rung operates on the HEAD of a history. When the RETAINED tail
62
+ is what does not fit — a few turns carrying several 100 KB tool results — each
63
+ of them reports success or "nothing to drop" while the conversation stays
64
+ un-sendable. `relieveTail` clips oversized `tool_result` bodies in place,
65
+ oldest first, and stops as soon as the projection is under budget.
66
+
67
+ It is **structure-preserving by construction**: no message is removed, no
68
+ `toolCallId` is touched, no role changes, so a history that passed
69
+ `validateHistory` before still passes after. That is what makes it safe to run
70
+ on an already-spliced history, and it is why relief clips rather than drops.
71
+ Every clip is announced in the text the model reads, at the exact place the
72
+ data was removed, through a `marker` callback the host supplies — this package
73
+ owns no glyphs.
74
+
75
+ `compaction_end.tailRelief` is optional, so a subscriber that does not know
76
+ about it is unaffected.
77
+
78
+ - **Context compaction — one injected port, and the engine refuses a bad
79
+ splice.** `AgentConfig.contextManager?: ContextManager` is called at every turn
80
+ boundary (after the steering drain, before `turn_start`). When it says so, the
81
+ engine hands it a **copy** of the history, adopts whatever comes back — and
82
+ validates it first.
83
+
84
+ `findSafeCutIndices`, `planCompaction` and `validateHistory` join the root
85
+ barrel, along with `CHARS_PER_TOKEN`, which was module-private (81 → 85 runtime
86
+ exports). Two new `AgentEvent` members, `compaction_start` and
87
+ `compaction_end`, carry the story; a consumer with a `default` branch is
88
+ unaffected.
89
+
90
+ **The mechanism is here; the policy is the host's.** This package holds a
91
+ `ModelRef` and never a `ModelInfo`, so the threshold, the summarizer, the
92
+ prompt and the failure ladder are all decisions on the other side of the port.
93
+
94
+ Four properties are load-bearing and each is asserted by a test:
95
+
96
+ - **Off is free.** With no `contextManager` the checkpoint is one `if` against
97
+ an absent field — no promise allocation, no events, no behaviour change.
98
+ - **The engine validates and may refuse.** An orphan `tool_result`, an unclosed
99
+ `tool_call`, an empty array or a history that grew is not adopted; the run
100
+ continues on the original and `compaction_end` reports
101
+ `invalid_history: <reason>`. An orphan `tool_result` is an unrecoverable 400
102
+ on Anthropic, so a host bug must not be able to produce one.
103
+ - **The call cannot hang the run.** `compaction_start` pauses the idle
104
+ watchdog, so the engine races `compact()` against the run's signal **and** a
105
+ 120 s ceiling of its own, and emits `compaction_end` from a `finally` — which
106
+ is what resumes the watchdog. A non-settling promise, an ignored signal or a
107
+ malformed return value each degrade to "compaction did not happen".
108
+ - **The host gets a copy.** `ctx.messages` is a shallow copy, so a host that
109
+ splices it in place cannot corrupt engine state before the gate sees it.
110
+
111
+ **`compaction` is now a legitimate word in the engine**, which makes RT-4's
112
+ original claim ("no history-trimming API exists") false by design. That guard
113
+ now asserts the narrower and more useful thing: history shrinks in exactly one
114
+ place, and that place goes through `validateHistory`. The skill digest's
115
+ `force=true` escape hatch — added for a *truncated* earlier copy — covers a
116
+ *compacted-away* one unchanged, and is pinned by a test.
117
+
118
+ - **`llm/retry.ts` — retry with exponential backoff, ON BY DEFAULT.**
119
+ `RETRY_LIMITS`, `DEFAULT_RETRY_POLICY`, `isRetryableError`,
120
+ `computeBackoffDelay`, `parseRetryAfterMs` and `withRetry` are exported from the
121
+ root barrel (75 → 81 runtime exports). `ProviderRegistry.stream()` wraps every
122
+ provider stream, so the agent loop, every subagent and `ProviderRegistry`
123
+ itself inherit retry with no call-site changes.
124
+
125
+ A transient failure — 429, 529, 5xx, DNS/TLS/ECONNRESET, 408 — is now retried
126
+ up to **10 times** with an increasing, equal-jittered interval
127
+ (1 s → 2 → 4 → 8 → 16 → 30 s, capped at 30 s per wait) under a **240 s**
128
+ wall-clock budget measured from the first failure. `auth_error`,
129
+ `invalid_request`, `context_overflow` and `unknown` are never retried: ten
130
+ retries of a bad API key is three minutes of looking broken.
131
+
132
+ A user abort is never retried, and this is the load-bearing detail:
133
+ `wrapFetchError` marks an `AbortError` `retryable: true`, so
134
+ `isRetryableError` reads `signal.aborted` **before** `err.retryable`. An
135
+ aborted request yields no further event of any kind — in particular no `error`
136
+ — so nothing fabricates a network failure out of Esc.
137
+
138
+ `Retry-After` (and `x-ratelimit-reset-after` /
139
+ `anthropic-ratelimit-requests-reset` / `anthropic-ratelimit-input-tokens-reset`)
140
+ is honoured as a **floor**, never a replacement, and a value above 60 s is
141
+ surfaced immediately rather than waited out.
142
+
143
+ - **Three new `StreamEvent` variants** — `RetryScheduledEvent`,
144
+ `RetryAttemptEvent`, `StreamRestartEvent`. Additive: `consumeStream` ignores
145
+ anything that is not `done`/`error`, and a consumer with a `default` branch is
146
+ unaffected. `retry_scheduled` carries `resumeAt` (an absolute instant) rather
147
+ than a tick stream, so a UI owns its own clock.
148
+
149
+ - **`ProviderRegistry` holds a policy.** New `ProviderRegistryOptions`,
150
+ `setRetryPolicy(policy | null)` and `getRetryPolicy()`;
151
+ `initProviders(options?)` forwards them. `undefined` means the product default,
152
+ an explicit `null` means opt out.
153
+
154
+ - **`LLMError` gains a 7th optional field `retryAfterMs`**, and
155
+ `classifyHttpError` an optional 4th parameter `headers?: Headers`. Both
156
+ additive; every existing call site compiles unchanged.
157
+
158
+ - **`Agent` pauses its idle watchdog across a backoff.** A 30 s wait would
159
+ otherwise be read as a wedged call and abort the run at `idleTimeout`.
160
+
161
+ - **`llm/output-limits.ts` — one authority for the output-token cap.**
162
+ `DEFAULT_MAX_OUTPUT_TOKENS` (64000), `MIN_MAX_OUTPUT_TOKENS`,
163
+ `SAFE_FALLBACK_MAX_OUTPUT_TOKENS`, `ABSOLUTE_MAX_OUTPUT_TOKENS`,
164
+ `THINKING_HEADROOM_TOKENS`, `CONTEXT_SAFETY_MARGIN_TOKENS`,
165
+ `resolveOutputTokens`, `staticCeilingFor`, `learnModelCeiling`,
166
+ `getLearnedCeiling`, `clearLearnedCeilings` and `estimatePromptTokens` are all
167
+ exported from the root barrel. The three provider adapters no longer carry
168
+ private copies of the default; they resolve through this module.
169
+
170
+ The resolver treats the default as an *ambition* and the model's real ceiling
171
+ as the law, ranking four sources — learned-from-error > discovery > a static
172
+ per-model table > the product default — so an over-large cap is clamped instead
173
+ of becoming an HTTP 400 that ends the run. It also reconciles Anthropic's
174
+ `max_tokens > thinking.budget_tokens` invariant, which `--thinking xhigh` broke
175
+ on every request.
176
+
177
+ - **`llm/output-limit-recovery.ts` — one-shot self-healing.**
178
+ `classifyOutputLimitFailure`, `sendWithOutputLimitRecovery`, `learnTokenField`,
179
+ `getLearnedTokenField` and `clearLearnedTokenFields`. A 400 that names an
180
+ output-limit problem is repaired and re-sent **once** — never a loop — and what
181
+ was learned is remembered for the rest of the process. A 2xx is returned with
182
+ its body untouched, so streaming is unaffected. OpenAI's reasoning family,
183
+ which rejects `max_tokens` in favour of `max_completion_tokens`, is handled by
184
+ a heuristic plus this memo.
185
+
186
+ - **`LLMRequest.modelLimits?: { maxOutputTokens?, contextWindow? }`** — optional
187
+ caller-supplied metadata. Supplying `contextWindow` enables the
188
+ `max_tokens + prompt <= context` guard on OpenAI. Every existing caller
189
+ compiles unchanged.
190
+
191
+ ### Changed
192
+
193
+ - **BEHAVIOUR CHANGE — retry is on by default for embedders.** A failing call
194
+ that used to end immediately can now take up to ~3 minutes to fail. The budget
195
+ bounds it; `initProviders({ retryPolicy: null })` or `setRetryPolicy(null)`
196
+ restores the old behaviour exactly, and `maxRetries: 0` short-circuits the
197
+ wrapper so the opted-out path is byte-identical.
198
+
199
+ - **BEHAVIOUR CHANGE — a truncated stream is now a loud error instead of a
200
+ silent success.** All three adapters used to end their SSE loop by
201
+ *unconditionally* yielding `done` with whatever had accumulated. A stream
202
+ closed gracefully mid-answer — a proxy idle cut, a load-balancer timeout, an
203
+ HTTP/2 GOAWAY, `[DONE]` never arriving — therefore surfaced as **success
204
+ carrying a truncated answer**, which no layer above the adapter could tell from
205
+ a real one. Each adapter now tracks its own terminal sentinel
206
+ (`message_stop` / `[DONE]` **or** a `finish_reason` / a chunk carrying
207
+ `finishReason`) and yields a retryable `network_error` when the stream ends
208
+ without it. Consequences:
209
+
210
+ - the mid-answer disconnection case is now retried and recovered;
211
+ - `ProviderRegistry.complete()` / `provider.complete()` change from returning a
212
+ partial `AssistantMessage` to **throwing** for a truncated stream;
213
+ - an **abort** is explicitly excluded and still yields `done`, and an empty but
214
+ complete turn is still a success.
215
+
216
+ This is deliberately **not** behind the retry switch: an adapter that reports a
217
+ truncated stream honestly should do so whether or not retry is enabled.
218
+
219
+ - **HTTP 408 is now `errorType: 'timeout'`, `retryable: true`** (it used to fall
220
+ into `unknown` / non-retryable).
221
+
222
+ - **`ProviderRegistry.complete()` now routes through `this.stream()`** instead of
223
+ `provider.complete()`. Behaviour-preserving — all three adapters implement
224
+ `complete` as exactly `consumeStream(this.stream(request))` — except that the
225
+ registry's version is now the retrying one.
226
+
227
+ - `ModelRegistry.buildRuntimeModel` defaults `maxOutputTokens` to
228
+ `DEFAULT_MAX_OUTPUT_TOKENS` rather than a private `16384`, the built-in
229
+ Anthropic catalog entries carry their real ceilings, and `registerDefaults` /
230
+ `discoverModels` seed the shared ceiling cache. `listModels` on the Anthropic
231
+ and OpenAI adapters now maps through the static table instead of asserting the
232
+ product default for every model — neither API reports an output ceiling, and
233
+ claiming otherwise outranked the correct value for every small model.
234
+
235
+ ### Notes
236
+
237
+ - **`streamLLM` / `completeLLM` diverge from a registry you build yourself.**
238
+ They resolve through `getProviderRegistry()`, which lazily calls
239
+ `initProviders()` with no arguments, so they always carry
240
+ `DEFAULT_RETRY_POLICY` and do not observe a policy installed elsewhere. For one
241
+ policy everywhere, call `setProviderRegistry(initProviders({ retryPolicy }))`
242
+ once at startup.
243
+
244
+ - **A half-open connection is still not covered** (no FIN, no RST). It produces
245
+ no event, so `withRetry` never wakes and the idle watchdog aborts the run. A
246
+ per-attempt stall timer is not safe at this layer: Anthropic's `ping` frames
247
+ are swallowed by the adapter, so a long extended-thinking pause and a dead
248
+ socket look identical at the `StreamEvent` layer.
249
+
250
+ ## 0.3.0
251
+
252
+ ### Added
253
+
254
+ - **`Agent.pauseIdleWatchdog()` / `Agent.resumeIdleWatchdog()`** — suspend and
255
+ restart the idle watchdog around a tool that blocks on a human. Both are
256
+ idempotent, and a paused watchdog also swallows `kick()`, so an event arriving
257
+ mid-wait cannot silently re-arm it. Always pair them in a `try/finally`: a
258
+ throw inside the wait must not leave the watchdog disarmed for the rest of the
259
+ run. The host is the only party that can know a person is being waited on —
260
+ from inside the loop that call is indistinguishable from a wedged network
261
+ request.
262
+
263
+ - **`AgentConfig.timeouts.toolTimeoutOverrides?: Record<string, number>`** —
264
+ per-tool ceilings keyed by tool name, forwarded to `ToolExecutor`'s existing
265
+ `timeoutOverrides`. This is pure wiring of a capability the executor already
266
+ had and that was unreachable through `Agent`.
267
+
268
+ Read this before relying on it: `ToolExecutor` expresses a timeout by aborting
269
+ `context.signal` and then *continuing to await* the tool's promise — there is
270
+ no `Promise.race`. A tool that never observes `context.signal` is therefore
271
+ never timed out, and the number set here is inert for it, with no error
272
+ anywhere. See *Blocking on a human* in `API.md`.
273
+
274
+ ### Fixed
275
+
276
+ - `IdleWatchdog.stop()` now clears the paused flag. Without it a run aborted
277
+ while paused would leave the watchdog deaf for every subsequent run, because
278
+ `start()` goes through `kick()` and `kick()` returns early while paused.
279
+
280
+ ### Notes
281
+
282
+ - **No change to the export surface.** The two new members are instance methods
283
+ and the third is a config field, so `src/index.ts` and the `EXPECTED` list in
284
+ `public-api.test.ts` are untouched.
285
+
286
+ ## 0.2.0
287
+
288
+ ### Breaking
289
+
290
+ - **The package is renamed `@argon-agent/core` → `@aragon-agent/core`.** The
291
+ brand was always meant to be *Aragon*, matching AragonMesh; the missing `a`
292
+ was a typo that reached the registry. `@argon-agent/core` is deprecated and
293
+ receives no further releases.
294
+
295
+ Every subpath keeps its shape — only the scope changes:
296
+
297
+ ```diff
298
+ - import { Agent } from '@argon-agent/core';
299
+ + import { Agent } from '@aragon-agent/core';
300
+ - import type { LlmMessage } from '@argon-agent/core/llm/types';
301
+ + import type { LlmMessage } from '@aragon-agent/core/llm/types';
302
+ ```
303
+
304
+ - **The exported alias `ArgonAgent` is now `AragonAgent`.** It remains an alias
305
+ of `Agent`, which is unchanged — code importing `Agent` needs no edit.
306
+
307
+ ### Added
308
+
309
+ - **Skill system (pure-logic half).** New `src/skills/` module and a `./skills`
310
+ subpath export: `SkillRegistry`, `parseFrontmatter`,
311
+ `validateSkillFrontmatter`, `validateStagedSkill`, `renderSkillCatalog`,
312
+ `renderSkillBody`, `renderSkillInvocation`, `applySkillArguments`,
313
+ `suggestSkillNames`, `sanitizeForPromptBlock`, `createSkillTool`, and the
314
+ `SKILL_*` budget constants. The root runtime surface grows from 33 to 56
315
+ value exports; see `API.md`.
316
+ - **`rankCatalogRecords(records, { usage, now })`** — orders the Level 1 catalog
317
+ by scope, then by usage recency and frequency, using integer buckets so the
318
+ result stays byte-reproducible. Invariant: called without a usage map it is
319
+ element-for-element identical to `catalogRecords()`, which is what keeps every
320
+ existing catalog snapshot valid.
321
+ - **`createSkillFindTool(deps)` / `renderSkillFindResults(query, matched, opts)`**
322
+ — the `skill_find` tool and its rendering, for reaching skills that did not fit
323
+ in the catalog. Searches only the injected registry: no network, no
324
+ `activation: manual` skills, and an explicit refusal to invent an install
325
+ source when nothing matches. Same sanitisation and byte budget discipline as
326
+ the catalog (`SKILL_FIND_MAX_BYTES`).
327
+ - Types `SkillIntegrity`, `SkillUsageStat`, `SkillUsageMap`, `SkillFindOptions`;
328
+ `SkillRecord.integrity`; optional `SkillManifestSource.resolvedRef` and
329
+ `SkillManifest.updatedAt` / `previousVersion` (additive — the manifest schema
330
+ version is deliberately unchanged so an older CLI still reads them).
331
+ - All filesystem access goes through the injected `SkillHost` port, so the
332
+ package still imports no `node:*` builtin outside the one grandfathered
333
+ `node:crypto` in `llm/providers/google.ts`.
334
+ - **Release tooling for the scope change.** `npm run verify:brand` derives the
335
+ list of files that would enter the tarball from `npm pack --dry-run --json`
336
+ and refuses the release if any of them still mentions the old brand — README
337
+ included, with only the four documented exceptions. It runs inside
338
+ `publish-latest.ps1` and cannot be skipped. `npm run preflight` answers "would
339
+ a real publish succeed?" before any version file is touched, and
340
+ `npm run verify:published` checks afterwards that the registry really serves
341
+ the renamed package, README and repository link included.
342
+
343
+ ### Changed
344
+
345
+ - `no-host-coupling.test.ts` now also asserts that **no** file under `src/`
346
+ imports a `node:*` builtin, with a single documented allowlist entry and a
347
+ self-check so the assertion cannot pass vacuously. This guarantee was
348
+ previously assumed but never actually checked.
349
+ - Added a repository-level PowerShell release workflow that versions, verifies,
350
+ and publishes Core before the dependent CLI, with dry-run rollback and
351
+ partial-release resume support.
352
+
353
+ ### Security
354
+
355
+ - Every span of third-party text is passed through `sanitizeForPromptBlock()`
356
+ before it is concatenated into a tagged prompt block. Without it a skill
357
+ description containing `</available_skills>` could close the block and have
358
+ the text after it read as top-level system-prompt instructions.
359
+ - All skill budgets are measured in UTF-8 **bytes**. A character-based budget
360
+ is ~3x under-counted for CJK text, which pushed results past `ToolExecutor`'s
361
+ 100 000-byte ceiling and truncated the closing tag off the block.
362
+
363
+ ## 0.1.0
364
+
365
+ Initial extraction of the ArgonAgent engine from the AragonMesh code base
366
+ (`server/agent-core/`) into a standalone, publishable package.
367
+
368
+ - Zero-coupling agent engine: LLM provider adapters (Anthropic, OpenAI,
369
+ Google), streaming, provider registry, model registry.
370
+ - Tool system: typed tool definitions, registry, JSON-Schema validator (with
371
+ built-in fallback), executor.
372
+ - Engine: multi-turn agent loop, message manager, steering queue, idle
373
+ watchdog.
374
+ - Optional isolated-vm CodeAct sandbox (lazy-loaded).
375
+ - Adds the `ArgonAgent` export as an alias of the `Agent` class.
376
+
377
+ Publish-readiness (still part of the unreleased `0.1.0`):
378
+
379
+ - Added `publishConfig.access:"public"` (required for scoped public publish),
380
+ a `prepublishOnly` build guard, and a package-directory `LICENSE`.
381
+ - `files` now ships `CHANGELOG.md` alongside `dist`.
382
+ - Added `typesVersions` so consumers on the legacy `moduleResolution:"node"`
383
+ can resolve the subpath type declarations.
384
+ - Declared `sideEffects:false` (the barrel is pure re-exports) to aid
385
+ downstream tree-shaking.
386
+ - Added discovery metadata: `keywords` / `author` / `repository` / `homepage`
387
+ / `bugs`.
388
+ - Added a compile-checked `examples/minimal.ts` usage sample (not shipped in the
389
+ tarball).
390
+
391
+ Reuse-verification harness (still part of the unreleased `0.1.0`):
392
+
393
+ - Added `examples/consumer-smoke/run.mjs` + the `verify:dist` script: runs the
394
+ built `dist/` like an external consumer (Node package self-referencing →
395
+ `exports` map → `dist/`), driving `ArgonAgent` end-to-end with an offline stub
396
+ provider and asserting every `exports` subpath resolves at runtime.
397
+ - Added a public-API contract snapshot (`src/__tests__/public-api.test.ts` +
398
+ `API.md`) that freezes the runtime export surface against silent drift.
399
+ - Added a `no-host-coupling` guard test that forbids host-repo imports
400
+ (`@server/`, `@shared/`, `@/`, out-of-package `../../../`) and legacy-brand
401
+ leakage on the public surface.
402
+ - Added a publish guard: `scripts/check-publishable.mjs` (wired into
403
+ `prepublishOnly`) hard-blocks publishing while the `<ORG>` placeholder remains
404
+ in `package.json`, and `scripts/stamp-org.mjs` replaces it in one command.