@aragon-agent/core 0.2.82 → 0.2.84

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,404 +1,404 @@
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
- ## Unreleased
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
-
30
- ### Fixed
31
-
32
- - Model context resolution now reads explicit OpenAI-compatible, Anthropic and
33
- Google API limits, preserves their provenance, and resolves endpoint-scoped
34
- discovery before catalog/alias fallbacks. Unknown limits stay marked as such.
35
- Context metadata does not imply known pricing.
36
- - Google/Anthropic discovery follows bounded pagination under a single 15-second
37
- deadline. All three adapters accept cancellation; cancelled or invalidated
38
- lookups cannot overwrite current metadata. Clearing one provider's cache leaves
39
- other providers' pending discoveries intact.
40
-
41
- ### Added
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
-
50
- - **Steering 精确接收回执。** `Agent.steer(text, id?)` 兼容原单参数调用,
51
- 历史接收后发出 `steering_accepted`,只确认当前批次的 ID;新增类型
52
- `SteeringMessage` 和 `SteeringAcceptedEvent`,无新增运行时导出。
53
- `drainSteeringItems()` 与原 `drainSteering()` 共用一个队列。
54
- 接收早于异步压缩,未执行工具先补齐 skipped 结果;无工具响应在结束前再次检查
55
- steering,避免流式输出期间提交的消息滞留。回执仅代表历史接收,不代表回答完成。
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.
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
+ ## Unreleased
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
+
30
+ ### Fixed
31
+
32
+ - Model context resolution now reads explicit OpenAI-compatible, Anthropic and
33
+ Google API limits, preserves their provenance, and resolves endpoint-scoped
34
+ discovery before catalog/alias fallbacks. Unknown limits stay marked as such.
35
+ Context metadata does not imply known pricing.
36
+ - Google/Anthropic discovery follows bounded pagination under a single 15-second
37
+ deadline. All three adapters accept cancellation; cancelled or invalidated
38
+ lookups cannot overwrite current metadata. Clearing one provider's cache leaves
39
+ other providers' pending discoveries intact.
40
+
41
+ ### Added
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
+
50
+ - **Steering 精确接收回执。** `Agent.steer(text, id?)` 兼容原单参数调用,
51
+ 历史接收后发出 `steering_accepted`,只确认当前批次的 ID;新增类型
52
+ `SteeringMessage` 和 `SteeringAcceptedEvent`,无新增运行时导出。
53
+ `drainSteeringItems()` 与原 `drainSteering()` 共用一个队列。
54
+ 接收早于异步压缩,未执行工具先补齐 skipped 结果;无工具响应在结束前再次检查
55
+ steering,避免流式输出期间提交的消息滞留。回执仅代表历史接收,不代表回答完成。
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.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 AragonAgent contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AragonAgent contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,147 +1,147 @@
1
- # @aragon-agent/core
2
-
3
- The publishable **AragonAgent** engine: a zero-coupling, dependency-injected
4
- TypeScript agent runtime.
5
-
6
- ## Requirements
7
-
8
- - **Node.js ≥ 18** — the engine relies on the global `fetch` / `AbortController`
9
- built into Node 18+.
10
- - **ESM-only** — this package ships as native ES modules (`"type": "module"`).
11
- Consume it with `import`; it cannot be `require()`-d from CommonJS.
12
- - **Optional native deps** — `ajv` and `isolated-vm` are `optionalDependencies`:
13
- the package works without them (a built-in validator fallback is used, and the
14
- sandbox modules are lazy-loaded). Install `isolated-vm` only if you use the
15
- `@aragon-agent/core/sandbox/*` CodeAct sandbox.
16
-
17
- ## Install
18
-
19
- ```bash
20
- npm install @aragon-agent/core
21
- # optional — only if you use the isolated-vm CodeAct sandbox:
22
- npm install isolated-vm
23
- ```
24
-
25
- `ajv` and `isolated-vm` are **optional dependencies**:
26
-
27
- - `ajv` — used by the tool param validator when present; a built-in fallback
28
- validator is used otherwise.
29
- - `isolated-vm` — used only by the `@aragon-agent/core/sandbox/*` modules, which
30
- are lazy-loaded and never imported from the package root (`isolated-vm` is
31
- incompatible with some embedded V8 runtimes such as Electron's).
32
-
33
- ## Usage
34
-
35
- ```ts
36
- import { AragonAgent, getProviderRegistry, initProviders } from '@aragon-agent/core';
37
-
38
- initProviders();
39
-
40
- const agent = new AragonAgent({
41
- systemPrompt: 'You are a coding agent.',
42
- model: { providerId: 'anthropic', modelId: 'claude-...', baseUrl: '...' },
43
- tools: [],
44
- providerRegistry: getProviderRegistry(),
45
- getApiKey: () => process.env.ANTHROPIC_API_KEY,
46
- });
47
-
48
- await agent.prompt('Hello');
49
- ```
50
-
51
- `AragonAgent` is an alias of the engine's `Agent` class.
52
-
53
- A complete, type-checked version of this snippet (a dummy tool + provider setup
54
- + agent construction) lives in [`examples/minimal.ts`](./examples/minimal.ts).
55
- It is compile-only (never hits the network) and is not part of the published
56
- tarball.
57
-
58
- ## Entry points
59
-
60
- | Import path | Contents |
61
- | -------------------------------- | ----------------------------------------- |
62
- | `@aragon-agent/core` | Full barrel (engine, LLM, tools, types). |
63
- | `@aragon-agent/core/llm/types` | LLM message / streaming / model types. |
64
- | `@aragon-agent/core/llm/providers`| Provider registry + `streamLLM`/`completeLLM`. |
65
- | `@aragon-agent/core/tools/types` | Tool system types. |
66
- | `@aragon-agent/core/tools/helpers`| `textResult` / `errorResult` / `defineTool`. |
67
- | `@aragon-agent/core/sandbox/*` | Optional isolated-vm CodeAct sandbox. |
68
-
69
- ## Build
70
-
71
- ```bash
72
- npm run build # tsc → dist/*.js + *.d.ts
73
- npm test # vitest (smoke + public-api contract + no-host-coupling guard)
74
- ```
75
-
76
- ## Verifying reuse
77
-
78
- `npm test` and `examples/minimal.ts` only prove the package **compiles**. To
79
- prove the built `dist/` can actually be **run** by an external consumer:
80
-
81
- ```bash
82
- npm run verify:dist # build dist/, then run examples/consumer-smoke/run.mjs
83
- ```
84
-
85
- `run.mjs` imports this package **by its own name** (`@aragon-agent/core`) via
86
- Node's *package self-referencing*, so Node resolves it through
87
- `package.json#exports` → `./dist/index.js` — the same `(exports map + NodeNext +
88
- .js extension)` path that an external project's `npm install @aragon-agent/core`
89
- hits, **without** placing the package in `node_modules`. It injects an offline
90
- stub LLM provider, runs one `AragonAgent.prompt()` turn end-to-end (zero network),
91
- and asserts the `exports` subpaths all resolve at runtime. Success prints
92
- `[consumer-smoke] OK`.
93
-
94
- For the unambiguous "another project installs and reuses it" check (which also
95
- covers running **without** the optional `ajv` / `isolated-vm` deps), see the
96
- pack-into-a-fresh-project golden verification in
97
- [`examples/consumer-smoke/README.md`](./examples/consumer-smoke/README.md).
98
-
99
- The runtime public-API surface is frozen by `src/__tests__/public-api.test.ts`
100
- and documented for humans in [`API.md`](./API.md); a `no-host-coupling` test
101
- keeps the package free of host-repo imports and legacy brand leakage.
102
-
103
- ## Publishing
104
-
105
- This package is published to the public npm registry. Run the release from the
106
- **package directory** so the package-level `prepublishOnly` hook fires and a
107
- fresh `dist/` is built:
108
-
109
- ```bash
110
- cd packages/core
111
- npm run build # produce dist/
112
- npm pack --dry-run --json # inspect the tarball file list (no upload)
113
- npm publish # publishConfig.access:"public" is baked in
114
- ```
115
-
116
- (From the repo root you can equivalently run `npm publish -w packages/core`.)
117
-
118
- Notes:
119
-
120
- - **`publishConfig.access` is set to `"public"`**, so no `--access public` flag
121
- is needed — scoped packages would otherwise default to restricted/private.
122
- - **The publishing account must own the `@aragon-agent` npm scope/org** before
123
- the first publish. Even with `access:"public"`, publishing under a scope you
124
- do not own fails with 403/404. Create the `@aragon-agent` org on npmjs (or
125
- switch to a scope your account owns and rename the package accordingly).
126
- - **`files` is the load-bearing whitelist.** The repo's `.gitignore` ignores
127
- `dist/`, but npm's `files: ["dist", "CHANGELOG.md"]` takes precedence and
128
- ships the built output. Do not "simplify" the `files` field away, or the
129
- published tarball will be empty. `npm pack --dry-run --json` should always
130
- list `dist/index.js`.
131
- - Repository metadata points to
132
- `https://github.com/xdrshjr/AragonAgent`.
133
-
134
- If the repository moves, use the helper script or update
135
- `repository` / `homepage` / `bugs` before publishing:
136
-
137
- ```bash
138
- node scripts/stamp-org.mjs <org> # or: ARAGON_REPO_ORG=<org> node scripts/stamp-org.mjs
139
- node scripts/check-publishable.mjs # exits non-zero if the placeholder remains in package.json
140
- ```
141
-
142
- `prepublishOnly` runs `check-publishable.mjs` before the build, so any publish
143
- attempt with an unstamped placeholder is hard-blocked automatically.
144
-
145
- ## License
146
-
147
- MIT.
1
+ # @aragon-agent/core
2
+
3
+ The publishable **AragonAgent** engine: a zero-coupling, dependency-injected
4
+ TypeScript agent runtime.
5
+
6
+ ## Requirements
7
+
8
+ - **Node.js ≥ 18** — the engine relies on the global `fetch` / `AbortController`
9
+ built into Node 18+.
10
+ - **ESM-only** — this package ships as native ES modules (`"type": "module"`).
11
+ Consume it with `import`; it cannot be `require()`-d from CommonJS.
12
+ - **Optional native deps** — `ajv` and `isolated-vm` are `optionalDependencies`:
13
+ the package works without them (a built-in validator fallback is used, and the
14
+ sandbox modules are lazy-loaded). Install `isolated-vm` only if you use the
15
+ `@aragon-agent/core/sandbox/*` CodeAct sandbox.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install @aragon-agent/core
21
+ # optional — only if you use the isolated-vm CodeAct sandbox:
22
+ npm install isolated-vm
23
+ ```
24
+
25
+ `ajv` and `isolated-vm` are **optional dependencies**:
26
+
27
+ - `ajv` — used by the tool param validator when present; a built-in fallback
28
+ validator is used otherwise.
29
+ - `isolated-vm` — used only by the `@aragon-agent/core/sandbox/*` modules, which
30
+ are lazy-loaded and never imported from the package root (`isolated-vm` is
31
+ incompatible with some embedded V8 runtimes such as Electron's).
32
+
33
+ ## Usage
34
+
35
+ ```ts
36
+ import { AragonAgent, getProviderRegistry, initProviders } from '@aragon-agent/core';
37
+
38
+ initProviders();
39
+
40
+ const agent = new AragonAgent({
41
+ systemPrompt: 'You are a coding agent.',
42
+ model: { providerId: 'anthropic', modelId: 'claude-...', baseUrl: '...' },
43
+ tools: [],
44
+ providerRegistry: getProviderRegistry(),
45
+ getApiKey: () => process.env.ANTHROPIC_API_KEY,
46
+ });
47
+
48
+ await agent.prompt('Hello');
49
+ ```
50
+
51
+ `AragonAgent` is an alias of the engine's `Agent` class.
52
+
53
+ A complete, type-checked version of this snippet (a dummy tool + provider setup
54
+ + agent construction) lives in [`examples/minimal.ts`](./examples/minimal.ts).
55
+ It is compile-only (never hits the network) and is not part of the published
56
+ tarball.
57
+
58
+ ## Entry points
59
+
60
+ | Import path | Contents |
61
+ | -------------------------------- | ----------------------------------------- |
62
+ | `@aragon-agent/core` | Full barrel (engine, LLM, tools, types). |
63
+ | `@aragon-agent/core/llm/types` | LLM message / streaming / model types. |
64
+ | `@aragon-agent/core/llm/providers`| Provider registry + `streamLLM`/`completeLLM`. |
65
+ | `@aragon-agent/core/tools/types` | Tool system types. |
66
+ | `@aragon-agent/core/tools/helpers`| `textResult` / `errorResult` / `defineTool`. |
67
+ | `@aragon-agent/core/sandbox/*` | Optional isolated-vm CodeAct sandbox. |
68
+
69
+ ## Build
70
+
71
+ ```bash
72
+ npm run build # tsc → dist/*.js + *.d.ts
73
+ npm test # vitest (smoke + public-api contract + no-host-coupling guard)
74
+ ```
75
+
76
+ ## Verifying reuse
77
+
78
+ `npm test` and `examples/minimal.ts` only prove the package **compiles**. To
79
+ prove the built `dist/` can actually be **run** by an external consumer:
80
+
81
+ ```bash
82
+ npm run verify:dist # build dist/, then run examples/consumer-smoke/run.mjs
83
+ ```
84
+
85
+ `run.mjs` imports this package **by its own name** (`@aragon-agent/core`) via
86
+ Node's *package self-referencing*, so Node resolves it through
87
+ `package.json#exports` → `./dist/index.js` — the same `(exports map + NodeNext +
88
+ .js extension)` path that an external project's `npm install @aragon-agent/core`
89
+ hits, **without** placing the package in `node_modules`. It injects an offline
90
+ stub LLM provider, runs one `AragonAgent.prompt()` turn end-to-end (zero network),
91
+ and asserts the `exports` subpaths all resolve at runtime. Success prints
92
+ `[consumer-smoke] OK`.
93
+
94
+ For the unambiguous "another project installs and reuses it" check (which also
95
+ covers running **without** the optional `ajv` / `isolated-vm` deps), see the
96
+ pack-into-a-fresh-project golden verification in
97
+ [`examples/consumer-smoke/README.md`](./examples/consumer-smoke/README.md).
98
+
99
+ The runtime public-API surface is frozen by `src/__tests__/public-api.test.ts`
100
+ and documented for humans in [`API.md`](./API.md); a `no-host-coupling` test
101
+ keeps the package free of host-repo imports and legacy brand leakage.
102
+
103
+ ## Publishing
104
+
105
+ This package is published to the public npm registry. Run the release from the
106
+ **package directory** so the package-level `prepublishOnly` hook fires and a
107
+ fresh `dist/` is built:
108
+
109
+ ```bash
110
+ cd packages/core
111
+ npm run build # produce dist/
112
+ npm pack --dry-run --json # inspect the tarball file list (no upload)
113
+ npm publish # publishConfig.access:"public" is baked in
114
+ ```
115
+
116
+ (From the repo root you can equivalently run `npm publish -w packages/core`.)
117
+
118
+ Notes:
119
+
120
+ - **`publishConfig.access` is set to `"public"`**, so no `--access public` flag
121
+ is needed — scoped packages would otherwise default to restricted/private.
122
+ - **The publishing account must own the `@aragon-agent` npm scope/org** before
123
+ the first publish. Even with `access:"public"`, publishing under a scope you
124
+ do not own fails with 403/404. Create the `@aragon-agent` org on npmjs (or
125
+ switch to a scope your account owns and rename the package accordingly).
126
+ - **`files` is the load-bearing whitelist.** The repo's `.gitignore` ignores
127
+ `dist/`, but npm's `files: ["dist", "CHANGELOG.md"]` takes precedence and
128
+ ships the built output. Do not "simplify" the `files` field away, or the
129
+ published tarball will be empty. `npm pack --dry-run --json` should always
130
+ list `dist/index.js`.
131
+ - Repository metadata points to
132
+ `https://github.com/xdrshjr/AragonAgent`.
133
+
134
+ If the repository moves, use the helper script or update
135
+ `repository` / `homepage` / `bugs` before publishing:
136
+
137
+ ```bash
138
+ node scripts/stamp-org.mjs <org> # or: ARAGON_REPO_ORG=<org> node scripts/stamp-org.mjs
139
+ node scripts/check-publishable.mjs # exits non-zero if the placeholder remains in package.json
140
+ ```
141
+
142
+ `prepublishOnly` runs `check-publishable.mjs` before the build, so any publish
143
+ attempt with an unstamped placeholder is hard-blocked automatically.
144
+
145
+ ## License
146
+
147
+ MIT.
@@ -34,14 +34,14 @@ export class ConsoleCapture {
34
34
  }
35
35
  this.entries.push(entry);
36
36
  });
37
- await context.evalClosure(`
38
- const _capture = $0;
39
- globalThis.console = {
40
- log: (...args) => _capture.applySync(undefined, ['log', args.map(String).join(' ')]),
41
- warn: (...args) => _capture.applySync(undefined, ['warn', args.map(String).join(' ')]),
42
- error: (...args) => _capture.applySync(undefined, ['error', args.map(String).join(' ')]),
43
- info: (...args) => _capture.applySync(undefined, ['info', args.map(String).join(' ')]),
44
- };
37
+ await context.evalClosure(`
38
+ const _capture = $0;
39
+ globalThis.console = {
40
+ log: (...args) => _capture.applySync(undefined, ['log', args.map(String).join(' ')]),
41
+ warn: (...args) => _capture.applySync(undefined, ['warn', args.map(String).join(' ')]),
42
+ error: (...args) => _capture.applySync(undefined, ['error', args.map(String).join(' ')]),
43
+ info: (...args) => _capture.applySync(undefined, ['info', args.map(String).join(' ')]),
44
+ };
45
45
  `, [captureRef], { arguments: { reference: true } });
46
46
  }
47
47
  /**
@@ -75,10 +75,10 @@ export class HttpBridge {
75
75
  });
76
76
  // Register fetch in the sandbox. The sandbox function serializes
77
77
  // arguments to JSON, sends to host, and deserializes the response.
78
- await context.evalClosure(`globalThis.fetch = async function(url, options) {
79
- const requestJson = JSON.stringify({ url, options });
80
- const responseJson = await $0.apply(undefined, [requestJson], { result: { promise: true } });
81
- return JSON.parse(responseJson);
78
+ await context.evalClosure(`globalThis.fetch = async function(url, options) {
79
+ const requestJson = JSON.stringify({ url, options });
80
+ const responseJson = await $0.apply(undefined, [requestJson], { result: { promise: true } });
81
+ return JSON.parse(responseJson);
82
82
  }`, [fetchRef], { arguments: { reference: true } });
83
83
  }
84
84
  // ---------------------------------------------------------------------------
@@ -91,8 +91,8 @@ export class ToolBridge {
91
91
  // $0 is the ivm.Reference to the host callback.
92
92
  // The sandbox function JSON-stringifies args before sending to host,
93
93
  // and awaits the promise returned by the host callback.
94
- await context.evalClosure(`globalThis.${fnName} = async function(args) {
95
- return await $0.apply(undefined, [JSON.stringify(args)], { result: { promise: true } });
94
+ await context.evalClosure(`globalThis.${fnName} = async function(args) {
95
+ return await $0.apply(undefined, [JSON.stringify(args)], { result: { promise: true } });
96
96
  }`, [callback], { arguments: { reference: true } });
97
97
  }
98
98
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aragon-agent/core",
3
- "version": "0.2.82",
3
+ "version": "0.2.84",
4
4
  "description": "AragonAgent core engine — LLM provider adapters, streaming, tool registry/execution, steering, idle watchdog, and an optional isolated-vm sandbox.",
5
5
  "license": "MIT",
6
6
  "author": "AragonAgent contributors",