@orkestrel/agent 0.0.20 → 0.0.21
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/README.md +10 -10
- package/dist/src/core/index.cjs +414 -329
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +907 -724
- package/dist/src/core/index.d.ts +907 -724
- package/dist/src/core/index.js +414 -329
- package/dist/src/core/index.js.map +1 -1
- package/package.json +21 -22
package/dist/src/core/index.js
CHANGED
|
@@ -10,37 +10,37 @@ import { WorkspaceManager, isBinary, isText } from "@orkestrel/workspace";
|
|
|
10
10
|
import { createTokenBudget } from "@orkestrel/budget";
|
|
11
11
|
//#region src/core/constants.ts
|
|
12
12
|
/**
|
|
13
|
-
* Caps an {@link AgentInterface} turn's tool iterations by default —
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* `AgentOptions.limit`.
|
|
13
|
+
* Caps an {@link AgentInterface} turn's tool iterations by default — `10` context → provider →
|
|
14
|
+
* tools cycles before the loop stops, so a model that keeps requesting tools can never loop
|
|
15
|
+
* forever. Overridable per agent through `AgentOptions.limit`.
|
|
17
16
|
*/
|
|
18
17
|
var DEFAULT_AGENT_LIMIT = 10;
|
|
19
18
|
/**
|
|
20
19
|
* Names the zone an {@link AuthorityInterface}'s default fallback {@link AuthorityDecision}
|
|
21
|
-
* carries — the classification for a tool call that matched no rule. Paired with
|
|
22
|
-
* default `allowed: true` fallback, an unmatched call is allowed under this zone, so a
|
|
23
|
-
* rules list of denials acts as a denylist; a caller wanting deny-by-default supplies
|
|
24
|
-
*
|
|
20
|
+
* carries — `'default'`, the classification for a tool call that matched no rule. Paired with
|
|
21
|
+
* the default `allowed: true` fallback, an unmatched call is allowed under this zone, so a
|
|
22
|
+
* rules list of denials acts as a denylist; a caller wanting deny-by-default supplies an
|
|
23
|
+
* `allowed: false` `fallback` of their own (see `AuthorityOptions`).
|
|
25
24
|
*/
|
|
26
25
|
var DEFAULT_AUTHORITY_ZONE = "default";
|
|
27
26
|
/**
|
|
28
27
|
* Sets the default number of recent live messages a {@link ConversationInterface}'s `compact()`
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
28
|
+
* retains verbatim — `0`, so a manual `compact()` folds every current live message into one
|
|
29
|
+
* summarized section and keeps no tail. A caller retains a recent tail by passing `keep` (on
|
|
30
|
+
* {@link ConversationOptions}, {@link ConversationManagerOptions}, or per-fold through
|
|
31
|
+
* {@link CompactOptions}), folding only the older `count - keep` messages and leaving the most
|
|
32
|
+
* recent `keep` live for the next turn. Overridable everywhere `keep` is accepted.
|
|
34
33
|
*/
|
|
35
34
|
var DEFAULT_CONVERSATION_KEEP = 0;
|
|
36
35
|
/**
|
|
37
36
|
* Names the framing label a {@link ConversationInterface}'s `view()` prefixes onto each compacted
|
|
38
|
-
* section's summary so a small model reads it as a
|
|
39
|
-
* literal assistant turn to echo or treat as
|
|
37
|
+
* section's summary so a small model reads it as a condensed recap of earlier turns — the lean
|
|
38
|
+
* `'[Summary of earlier messages] '` marker, never a literal assistant turn to echo or treat as
|
|
39
|
+
* the live answer.
|
|
40
40
|
*
|
|
41
41
|
* @remarks
|
|
42
|
-
* Deliberately a
|
|
43
|
-
* bounded `prefix × sections` overhead and
|
|
42
|
+
* Deliberately a fixed, lean handful of tokens (a short bracketed marker) so the framing adds a
|
|
43
|
+
* bounded `prefix × sections` overhead and never an open-ended blow-up — the
|
|
44
44
|
* {@link ConversationInterface} no-bloat test guard pins exactly that. Kept here (beside
|
|
45
45
|
* {@link DEFAULT_CONVERSATION_KEEP}) as the conversation layer's one tunable framing constant, so
|
|
46
46
|
* the wording has a single source of truth as it is optimized against real small-model behavior
|
|
@@ -50,43 +50,46 @@ var DEFAULT_CONVERSATION_KEEP = 0;
|
|
|
50
50
|
var CONVERSATION_RECAP_PREFIX = "[Summary of earlier messages] ";
|
|
51
51
|
/**
|
|
52
52
|
* Names the opening tag a {@link import('./ThinkSplitter.js').ThinkSplitter} recognizes as the start of
|
|
53
|
-
* an in-content reasoning span — the de-facto wire convention thinking models
|
|
54
|
-
* family) emit their chain-of-thought under when a daemon renders it inline
|
|
55
|
-
* separate wire field. Paired with {@link THINK_CLOSE}.
|
|
53
|
+
* an in-content reasoning span — `'<think>'`, the de-facto wire convention thinking models
|
|
54
|
+
* (qwen3, DeepSeek-R1 family) emit their chain-of-thought under when a daemon renders it inline
|
|
55
|
+
* instead of on a separate wire field. Paired with {@link THINK_CLOSE}.
|
|
56
56
|
*/
|
|
57
57
|
var THINK_OPEN = "<think>";
|
|
58
58
|
/**
|
|
59
|
-
* Names the closing tag that ends a {@link THINK_OPEN} reasoning span
|
|
60
|
-
* (the model was cut off mid-reasoning) is treated as thinking to its end
|
|
61
|
-
* {@link import('./types.js').ThinkSplitterInterface.flush} settles it.
|
|
59
|
+
* Names the closing tag that ends a {@link THINK_OPEN} reasoning span — `'</think>'`. A span the
|
|
60
|
+
* stream never closes (the model was cut off mid-reasoning) is treated as thinking to its end,
|
|
61
|
+
* and {@link import('./types.js').ThinkSplitterInterface.flush} settles it.
|
|
62
62
|
*/
|
|
63
63
|
var THINK_CLOSE = "</think>";
|
|
64
64
|
/**
|
|
65
65
|
* Names the section header {@link import('./AgentContext.js').AgentContext}'s `build()` renders the
|
|
66
|
-
*
|
|
67
|
-
* system message
|
|
66
|
+
* active workspace's text files under — `'## Workspace'`, the leading line of the dedicated
|
|
67
|
+
* workspace block in the system message and the carrier-split counterpart to the documents and
|
|
68
|
+
* images section headers.
|
|
68
69
|
*
|
|
69
70
|
* @remarks
|
|
70
|
-
* `build()`
|
|
71
|
+
* `build()` owns the workspace render (a `Workspace` / `WorkspaceManager` stays file-focused — no
|
|
71
72
|
* `open` / `format` getters), so this header lives here as the agents module's one
|
|
72
73
|
* workspace-section framing constant rather than on a manager. Each workspace text file renders
|
|
73
|
-
* beneath it as a fenced `` File: <path>\n```<language>\n<text>\n``` `` block — the
|
|
74
|
+
* beneath it as a fenced `` File: <path>\n```<language>\n<text>\n``` `` block — the same framing
|
|
74
75
|
* the documents section uses — placed immediately after the documents section in the system block.
|
|
75
76
|
*/
|
|
76
77
|
var WORKSPACE_SECTION_HEADER = "## Workspace";
|
|
77
78
|
/**
|
|
78
|
-
* Estimates the per-message role
|
|
79
|
-
* adds on top of a message's content estimate —
|
|
80
|
-
* conversation turn carries (its role tag, delimiters) that
|
|
81
|
-
* content-only heuristic does not otherwise
|
|
79
|
+
* Estimates the per-message role and framing overhead {@link import('./helpers.js').estimateMessages}
|
|
80
|
+
* adds on top of a message's content estimate — `4` tokens for the fixed wire framing every
|
|
81
|
+
* conversation turn carries (its role tag, its delimiters) that
|
|
82
|
+
* {@link import('./helpers.js').estimateTokens}'s content-only heuristic does not otherwise
|
|
83
|
+
* capture.
|
|
82
84
|
*/
|
|
83
85
|
var MESSAGE_TOKEN_OVERHEAD = 4;
|
|
84
86
|
/**
|
|
85
|
-
* Names the coarse, deliberately
|
|
86
|
-
* charges for each attached image
|
|
87
|
+
* Names the coarse, deliberately approximate per-image token cost
|
|
88
|
+
* {@link import('./helpers.js').estimateMessages} charges for each attached image — `512`, because
|
|
89
|
+
* a base64 payload's length is no reliable token proxy.
|
|
87
90
|
*
|
|
88
91
|
* @remarks
|
|
89
|
-
* A base64 image payload's
|
|
92
|
+
* A base64 image payload's length is not a reliable token proxy (a vision model's actual image
|
|
90
93
|
* token cost depends on resolution / tiling, not byte size), so this is a fixed, coarse
|
|
91
94
|
* per-image estimate rather than a derivation from `image.length` — a planning heuristic, not an
|
|
92
95
|
* exact count.
|
|
@@ -96,8 +99,8 @@ var IMAGE_TOKEN_ESTIMATE = 512;
|
|
|
96
99
|
//#region src/core/errors.ts
|
|
97
100
|
/**
|
|
98
101
|
* Reports a provider stream cancelled mid-flight by its bound signal — thrown by a
|
|
99
|
-
* {@link ProviderInterface}'s `stream`, carrying the {@link ProviderResult} assembled
|
|
100
|
-
*
|
|
102
|
+
* {@link ProviderInterface}'s `stream`, carrying the {@link ProviderResult} assembled from
|
|
103
|
+
* whatever streamed before the cancel and the machine-readable `code` `'ABORT'`.
|
|
101
104
|
*
|
|
102
105
|
* @remarks
|
|
103
106
|
* Lets a caller recover the partial content (and any tool calls / usage seen so far)
|
|
@@ -116,7 +119,8 @@ var ProviderAbortError = class extends Error {
|
|
|
116
119
|
}
|
|
117
120
|
};
|
|
118
121
|
/**
|
|
119
|
-
* Narrows an unknown caught value to a {@link ProviderAbortError}
|
|
122
|
+
* Narrows an unknown caught value to a {@link ProviderAbortError} through `instanceof`, so a
|
|
123
|
+
* `catch` can recover its `partial` result.
|
|
120
124
|
*
|
|
121
125
|
* @param value - The value to test (typically a `catch` binding)
|
|
122
126
|
* @returns True if `value` is a {@link ProviderAbortError}; false otherwise
|
|
@@ -136,13 +140,13 @@ function isProviderAbortError(value) {
|
|
|
136
140
|
/**
|
|
137
141
|
* Reports an {@link AgentInterface} run that ended {@link AgentResult.partial} under a
|
|
138
142
|
* `partial` policy of `false` (the default) — thrown by an agent-job handler (a
|
|
139
|
-
* `createAgentQueue` / `createAgentRunner` job), carrying the partial
|
|
140
|
-
*
|
|
143
|
+
* `createAgentQueue` / `createAgentRunner` job), carrying the partial {@link AgentResult} so
|
|
144
|
+
* the failure stays inspectable, and the machine-readable `code` `'PARTIAL'`.
|
|
141
145
|
*
|
|
142
146
|
* @remarks
|
|
143
147
|
* A partial result means the agent was cancelled (an external `signal` abort, a queue /
|
|
144
148
|
* runner abort threaded in, a `timeout` deadline, or an exhausted token `budget`) rather
|
|
145
|
-
* than finishing naturally. For a durable
|
|
149
|
+
* than finishing naturally. For a durable job that is a failure by default: throwing this
|
|
146
150
|
* lets the Queue's retries re-run the job and a Runner's fail-fast abort its siblings.
|
|
147
151
|
* Set `partial: true` (see `AgentQueueOptions` / `AgentRunnerOptions`) to treat a
|
|
148
152
|
* partial as success instead, in which case this is never thrown. Narrow a caught value
|
|
@@ -162,7 +166,8 @@ var AgentJobError = class extends Error {
|
|
|
162
166
|
}
|
|
163
167
|
};
|
|
164
168
|
/**
|
|
165
|
-
* Narrows an unknown caught value to an {@link AgentJobError}
|
|
169
|
+
* Narrows an unknown caught value to an {@link AgentJobError} through `instanceof`, so a
|
|
170
|
+
* `catch` can recover its `partial` result.
|
|
166
171
|
*
|
|
167
172
|
* @param value - The value to test (typically a `catch` binding or a rejected enqueue)
|
|
168
173
|
* @returns True if `value` is an {@link AgentJobError}; false otherwise
|
|
@@ -180,12 +185,13 @@ function isAgentJobError(value) {
|
|
|
180
185
|
return value instanceof AgentJobError;
|
|
181
186
|
}
|
|
182
187
|
/**
|
|
183
|
-
* Reports a conversation with no {@link ConversationSummaryHandler} to fold its messages
|
|
184
|
-
*
|
|
185
|
-
*
|
|
188
|
+
* Reports a conversation with no {@link ConversationSummaryHandler} to fold its messages with,
|
|
189
|
+
* or with a `sections` cap below `1` — thrown by a {@link ConversationInterface}'s `compact()`
|
|
190
|
+
* or its construction, carrying the machine-readable `code`
|
|
191
|
+
* `'SUMMARIZER' | 'SECTIONS'`.
|
|
186
192
|
*
|
|
187
193
|
* @remarks
|
|
188
|
-
* Compaction
|
|
194
|
+
* Compaction requires a summarizer (it digests the folded slice into a section summary and
|
|
189
195
|
* regenerates the rollup); a conversation created without one can still store + `view()` its
|
|
190
196
|
* live tail, but a `compact()` is a programmer error and throws this with `'SUMMARIZER'`.
|
|
191
197
|
* A `sections` cap (on {@link import('./types.js').ConversationOptions} /
|
|
@@ -204,7 +210,8 @@ var ConversationError = class extends Error {
|
|
|
204
210
|
}
|
|
205
211
|
};
|
|
206
212
|
/**
|
|
207
|
-
* Narrows an unknown caught value to a {@link ConversationError}
|
|
213
|
+
* Narrows an unknown caught value to a {@link ConversationError} through `instanceof`, so a
|
|
214
|
+
* `catch` can branch on its `code`.
|
|
208
215
|
*
|
|
209
216
|
* @param value - The value to test (typically a `catch` binding)
|
|
210
217
|
* @returns True if `value` is a {@link ConversationError}; false otherwise
|
|
@@ -222,13 +229,16 @@ function isConversationError(value) {
|
|
|
222
229
|
return value instanceof ConversationError;
|
|
223
230
|
}
|
|
224
231
|
/**
|
|
225
|
-
* Reports a concurrent run that would corrupt
|
|
232
|
+
* Reports a concurrent run that would corrupt shared per-agent accounting, or a rehydration
|
|
226
233
|
* name absent from its registry pool — thrown synchronously by an {@link AgentInterface}'s
|
|
227
|
-
* `stream()` and by
|
|
228
|
-
* `code
|
|
234
|
+
* `stream()` (and so by `generate()`, which calls it) and by an
|
|
235
|
+
* {@link AgentRegistryInterface}'s accessors, carrying the machine-readable `code`
|
|
236
|
+
* `'CONCURRENCY' | 'REGISTRY'`. Synchronous means a fire-and-forget
|
|
237
|
+
* `agent.generate().catch(…)` never catches it: `await` the call inside `try`/`catch`, or wrap
|
|
238
|
+
* the call expression itself.
|
|
229
239
|
*
|
|
230
240
|
* @remarks
|
|
231
|
-
* `'CONCURRENCY'` reports a run already in flight on the same agent,
|
|
241
|
+
* `'CONCURRENCY'` reports a run already in flight on the same agent, plus a construction-level
|
|
232
242
|
* `window` (a shared context budget) or a construction-level `budget` with no per-run override
|
|
233
243
|
* (a shared cost budget) — a second concurrent `stream()` would race its charges against the
|
|
234
244
|
* same shared instance, corrupting the accounting. Use separate agents, or per-run `budget`
|
|
@@ -246,7 +256,8 @@ var AgentError = class extends Error {
|
|
|
246
256
|
}
|
|
247
257
|
};
|
|
248
258
|
/**
|
|
249
|
-
* Narrows an unknown caught value to an {@link AgentError}
|
|
259
|
+
* Narrows an unknown caught value to an {@link AgentError} through `instanceof`, so a `catch`
|
|
260
|
+
* can branch on its `code`.
|
|
250
261
|
*
|
|
251
262
|
* @param value - The value to test (typically a `catch` binding)
|
|
252
263
|
* @returns True if `value` is an {@link AgentError}; false otherwise
|
|
@@ -266,8 +277,11 @@ function isAgentError(value) {
|
|
|
266
277
|
//#endregion
|
|
267
278
|
//#region src/core/helpers.ts
|
|
268
279
|
/**
|
|
269
|
-
* Projects an unknown value onto
|
|
270
|
-
* {@link AgentResult}
|
|
280
|
+
* Projects an unknown value onto a fresh, exact `JSONValue` representation of an
|
|
281
|
+
* {@link AgentResult} — capturing each structural field once through a total boundary,
|
|
282
|
+
* accepting conforming accessors and inherited properties, preserving finite negative and
|
|
283
|
+
* fractional usage counts, dropping extras, and resolving `undefined` for a malformed field, a
|
|
284
|
+
* non-finite usage number, a throwing getter, or a hostile or revoked proxy.
|
|
271
285
|
*
|
|
272
286
|
* @remarks
|
|
273
287
|
* This is a total hostile-boundary projection. Each structural field is captured once
|
|
@@ -321,15 +335,16 @@ function agentResultToJSON(value) {
|
|
|
321
335
|
return captured.success ? parseJSONValue(captured.value) : void 0;
|
|
322
336
|
}
|
|
323
337
|
/**
|
|
324
|
-
* Filters a list of items by a {@link import('./types.js').ScopeInterface} allow-list of
|
|
325
|
-
*
|
|
326
|
-
*
|
|
338
|
+
* Filters a list of items by a {@link import('./types.js').ScopeInterface} allow-list of keys —
|
|
339
|
+
* `undefined` passes everything, `[]` passes nothing, and a non-empty list passes the listed keys
|
|
340
|
+
* alone, order preserved. The pure, total set-membership primitive the context's build step and
|
|
341
|
+
* the agent loop's tool-advertise step apply a scope through.
|
|
327
342
|
*
|
|
328
343
|
* @remarks
|
|
329
344
|
* Three-way by the allow-list's shape, so a `Scope` category cleanly expresses "all /
|
|
330
345
|
* none / only these":
|
|
331
|
-
* - `undefined` ⇒
|
|
332
|
-
* - `[]` (empty) ⇒
|
|
346
|
+
* - `undefined` ⇒ no constraint — every item passes (returned unchanged).
|
|
347
|
+
* - `[]` (empty) ⇒ none pass (no key is in an empty set).
|
|
333
348
|
* - a non-empty list ⇒ only items whose `key(item)` is in the list pass.
|
|
334
349
|
*
|
|
335
350
|
* Order-preserving (it filters `items` in place order, never reorders) and total — never
|
|
@@ -356,15 +371,15 @@ function filterAllowList(allow, items, key) {
|
|
|
356
371
|
return items.filter((item) => set.has(key(item)));
|
|
357
372
|
}
|
|
358
373
|
/**
|
|
359
|
-
* Estimates the context-token footprint of a string — the deterministic
|
|
360
|
-
* {@link estimateMessages} sums over a conversation's messages (the default
|
|
361
|
-
* estimator).
|
|
374
|
+
* Estimates the context-token footprint of a string — the deterministic `ceil(length / 4)`
|
|
375
|
+
* character heuristic {@link estimateMessages} sums over a conversation's messages (the default
|
|
376
|
+
* context-budget estimator).
|
|
362
377
|
*
|
|
363
378
|
* @remarks
|
|
364
379
|
* Approximates `ceil(length / 4)` (≈ four characters per token — the rough average for
|
|
365
380
|
* English text), so the same input always yields the same estimate (no model round-trip).
|
|
366
381
|
* Empty text is `0`. This is a planning heuristic for reasoning about how much a turn's
|
|
367
|
-
* messages cost the next request,
|
|
382
|
+
* messages cost the next request, not an exact tokenizer count — it never calls a provider,
|
|
368
383
|
* so the agent layer stays provider-agnostic and synchronous where it can be.
|
|
369
384
|
*
|
|
370
385
|
* @param text - The text to estimate (a section summary, a message's content)
|
|
@@ -381,16 +396,19 @@ function estimateTokens(text) {
|
|
|
381
396
|
return Math.ceil(text.length / 4);
|
|
382
397
|
}
|
|
383
398
|
/**
|
|
384
|
-
* Estimates the context-token footprint of a batch of messages —
|
|
385
|
-
*
|
|
386
|
-
*
|
|
399
|
+
* Estimates the context-token footprint of a batch of messages — each message's content plus
|
|
400
|
+
* {@link import('./constants.js').MESSAGE_TOKEN_OVERHEAD}, a tool-call JSON estimate, and
|
|
401
|
+
* {@link import('./constants.js').IMAGE_TOKEN_ESTIMATE} for each attached image. The default
|
|
402
|
+
* `consumer` estimator for an agent's context budget (the
|
|
403
|
+
* {@link import('./types.js').AgentOptions} `window`), total and never throwing, and a
|
|
404
|
+
* deliberate provider-agnostic approximation rather than an exact tokenizer count.
|
|
387
405
|
*
|
|
388
406
|
* @remarks
|
|
389
407
|
* Sums, per message, {@link estimateTokens} over its `content` (the `ceil(length / 4)` char
|
|
390
|
-
* heuristic)
|
|
391
|
-
* role/framing overhead)
|
|
392
|
-
* `calls`
|
|
393
|
-
* deliberately-approximate per-image cost — a base64 length is
|
|
408
|
+
* heuristic) plus {@link import('./constants.js').MESSAGE_TOKEN_OVERHEAD} (a fixed per-message
|
|
409
|
+
* role/framing overhead) plus, when present, {@link estimateTokens} over its JSON-stringified
|
|
410
|
+
* `calls` plus `images.length * `{@link import('./constants.js').IMAGE_TOKEN_ESTIMATE} (a coarse,
|
|
411
|
+
* deliberately-approximate per-image cost — a base64 length is not a token proxy). Deterministic
|
|
394
412
|
* and provider-free — the same messages always yield the same estimate, with an empty batch `0`.
|
|
395
413
|
* It is the fully-swappable default an agent's auto-compaction context budget charges each
|
|
396
414
|
* turn's new messages through; a caller wanting a sharper count supplies its own `consumer` to
|
|
@@ -422,15 +440,17 @@ function estimateMessages(messages) {
|
|
|
422
440
|
}, 0);
|
|
423
441
|
}
|
|
424
442
|
/**
|
|
425
|
-
* Runs one rehydrated agent and applies the partial-as-configurable-failure policy —
|
|
426
|
-
*
|
|
427
|
-
*
|
|
443
|
+
* Runs one rehydrated agent and applies the partial-as-configurable-failure policy — a partial
|
|
444
|
+
* run throws an {@link import('./errors.js').AgentJobError} unless the `partial` policy allows
|
|
445
|
+
* it, and a natural finish resolves. The shared job-handler step `createAgentQueue` and
|
|
446
|
+
* `createAgentRunner` both settle each job through, so the policy can never diverge between
|
|
447
|
+
* them.
|
|
428
448
|
*
|
|
429
449
|
* @remarks
|
|
430
|
-
* A turn that committed
|
|
431
|
-
*
|
|
432
|
-
* (the Queue's retries + a Runner's fail-fast then engage); the `partial` policy
|
|
433
|
-
* it as success instead. A natural finish
|
|
450
|
+
* A turn that committed partial (a cancel — abort / budget / timeout) is by default a
|
|
451
|
+
* failure, so it throws an {@link import('./errors.js').AgentJobError} carrying the partial
|
|
452
|
+
* (the Queue's retries + a Runner's fail-fast then engage); the `partial` policy resolves
|
|
453
|
+
* it as success instead. A natural finish always resolves with its result.
|
|
434
454
|
*
|
|
435
455
|
* @param agent - The rehydrated {@link AgentInterface} to run to its {@link AgentResult}
|
|
436
456
|
* @param partial - The partial policy. If `true`, a partial result resolves as success; if
|
|
@@ -482,9 +502,9 @@ function handleAgentRunnerJob(registry, partial, controller) {
|
|
|
482
502
|
return settleAgentJob(registry.build(controller.input, controller.signal), partial);
|
|
483
503
|
}
|
|
484
504
|
/**
|
|
485
|
-
* Renders a path-addressed text body as a fenced reference block —
|
|
486
|
-
*
|
|
487
|
-
* active
|
|
505
|
+
* Renders a path-addressed text body as a fenced reference block — a `File: <path>` label line
|
|
506
|
+
* over a language-tagged fence, the framing an
|
|
507
|
+
* {@link import('./AgentContext.js').AgentContext}'s active-workspace text-file render emits.
|
|
488
508
|
*
|
|
489
509
|
* @remarks
|
|
490
510
|
* Produces `` File: <path>\n```<language>\n<content>\n``` `` — the `File:` label line, then a
|
|
@@ -510,7 +530,8 @@ function renderFencedFile(path, language, content) {
|
|
|
510
530
|
return `File: ${path}\n\`\`\`${language}\n${content}\n\`\`\``;
|
|
511
531
|
}
|
|
512
532
|
/**
|
|
513
|
-
* Sanitizes one reported token count into a safe non-negative integer
|
|
533
|
+
* Sanitizes one reported token count into a safe non-negative integer — a non-finite or
|
|
534
|
+
* non-positive value becomes `0`, and a positive fractional value floors down.
|
|
514
535
|
*
|
|
515
536
|
* @param value - The token count to sanitize
|
|
516
537
|
* @returns The floored count, or `0` when the value is non-finite or non-positive
|
|
@@ -596,10 +617,11 @@ function sumUsage(running, next) {
|
|
|
596
617
|
}
|
|
597
618
|
/**
|
|
598
619
|
* Assembles the settled {@link AgentResult} from a run's {@link RunOutcome} — `thinking` and
|
|
599
|
-
* `usage` are carried only when the run surfaced them
|
|
620
|
+
* `usage` are carried only when the run surfaced them, and the loop-internal `exhausted` flag is
|
|
621
|
+
* left out.
|
|
600
622
|
*
|
|
601
623
|
* @remarks
|
|
602
|
-
* Pure and total. An absent optional is
|
|
624
|
+
* Pure and total. An absent optional is omitted rather than stored as `undefined` (the
|
|
603
625
|
* present-when-given convention the message store follows), so a settled result JSON
|
|
604
626
|
* round-trips without an explicit `undefined` field. `exhausted` is loop bookkeeping and does
|
|
605
627
|
* not reach the public result — the `exhaust` event carries it instead.
|
|
@@ -651,10 +673,10 @@ function denyCall(call, reason) {
|
|
|
651
673
|
}
|
|
652
674
|
/**
|
|
653
675
|
* Renders one context section — the resolved `open`, each item's rendering, and the resolved
|
|
654
|
-
* `close` when one exists, blank-line joined.
|
|
676
|
+
* `close` when one exists, blank-line joined; `undefined` when the section has no items.
|
|
655
677
|
*
|
|
656
678
|
* @remarks
|
|
657
|
-
* Pure and total. A section with
|
|
679
|
+
* Pure and total. A section with no items renders nothing (`undefined`), so an empty or fully
|
|
658
680
|
* scoped-out manager stays silent — its `open` / `close` never appear without items. `close`
|
|
659
681
|
* is the only optional slot: an unset one (there is no built-in close) drops the
|
|
660
682
|
* trailing line.
|
|
@@ -680,13 +702,13 @@ function renderSection(open, items, render, close) {
|
|
|
680
702
|
return lines.join("\n\n");
|
|
681
703
|
}
|
|
682
704
|
/**
|
|
683
|
-
* Resolves one section's
|
|
705
|
+
* Resolves one section's open text through the format cascade — manager-options override >
|
|
684
706
|
* provider default > built-in header.
|
|
685
707
|
*
|
|
686
708
|
* @remarks
|
|
687
|
-
* Pure and total. The leading text has
|
|
709
|
+
* Pure and total. The leading text has no per-item level. A manager's `open` already
|
|
688
710
|
* encapsulates `[options-override → built-in]`, so it is reached only when neither the
|
|
689
|
-
* override's `open` nor the provider's `open` applies — and there it
|
|
711
|
+
* override's `open` nor the provider's `open` applies — and there it is the built-in header.
|
|
690
712
|
*
|
|
691
713
|
* @typeParam T - The section item the manager renders
|
|
692
714
|
* @param manager - The section source (its `format` override + its built-in `open`)
|
|
@@ -703,13 +725,13 @@ function resolveOpen(manager, provider) {
|
|
|
703
725
|
return manager.format?.open ?? provider?.open ?? manager.open;
|
|
704
726
|
}
|
|
705
727
|
/**
|
|
706
|
-
* Resolves one section's
|
|
707
|
-
* provider default.
|
|
728
|
+
* Resolves one section's close text through the format cascade — manager-options override >
|
|
729
|
+
* provider default; `undefined` when neither sets one, because there is no built-in close.
|
|
708
730
|
*
|
|
709
731
|
* @remarks
|
|
710
|
-
* Pure and total. There is
|
|
732
|
+
* Pure and total. There is no built-in close, so a section with neither level set returns
|
|
711
733
|
* `undefined` and {@link renderSection} appends no closing line. Paired with
|
|
712
|
-
* {@link resolveOpen}, one level can
|
|
734
|
+
* {@link resolveOpen}, one level can wrap the whole group.
|
|
713
735
|
*
|
|
714
736
|
* @typeParam T - The section item the manager renders
|
|
715
737
|
* @param manager - The section source (its `format` override)
|
|
@@ -726,14 +748,14 @@ function resolveClose(manager, provider) {
|
|
|
726
748
|
return manager.format?.close ?? provider?.close;
|
|
727
749
|
}
|
|
728
750
|
/**
|
|
729
|
-
* Resolves
|
|
730
|
-
*
|
|
751
|
+
* Resolves one item's rendering through the format cascade — item override > manager-options
|
|
752
|
+
* override > provider default > built-in rendering.
|
|
731
753
|
*
|
|
732
754
|
* @remarks
|
|
733
755
|
* Pure and total. The item's own `override` is the most-specific level (a fully-rendered
|
|
734
756
|
* string for that item alone). A manager's `render(item)` already encapsulates
|
|
735
757
|
* `[options-override → built-in]`, so it is reached only when no higher level applies — and
|
|
736
|
-
* there it
|
|
758
|
+
* there it is the built-in rendering.
|
|
737
759
|
*
|
|
738
760
|
* @typeParam T - The section item being rendered (it may carry its own `override`)
|
|
739
761
|
* @param manager - The section source (its `format` override + its built-in `render`)
|
|
@@ -752,11 +774,11 @@ function resolveItem(manager, provider, item) {
|
|
|
752
774
|
return item.override ?? manager.format?.render?.(item) ?? provider?.render?.(item) ?? manager.render(item);
|
|
753
775
|
}
|
|
754
776
|
/**
|
|
755
|
-
* Copies a message with image data merged onto its `images` — the message's own images
|
|
756
|
-
*
|
|
777
|
+
* Copies a message with image data merged onto its `images` — the message's own images first,
|
|
778
|
+
* then the attached data, carrying `calls` only when present and never mutating the original.
|
|
757
779
|
*
|
|
758
780
|
* @remarks
|
|
759
|
-
* Pure and total: the original message is
|
|
781
|
+
* Pure and total: the original message is never mutated. `calls` is carried only when the
|
|
760
782
|
* source message has one (kept omitted otherwise, mirroring the store's present-when-given
|
|
761
783
|
* convention).
|
|
762
784
|
*
|
|
@@ -786,13 +808,14 @@ function attachImages(message, data) {
|
|
|
786
808
|
};
|
|
787
809
|
}
|
|
788
810
|
/**
|
|
789
|
-
* Attaches image data to a conversation's
|
|
790
|
-
*
|
|
811
|
+
* Attaches image data to a conversation's last user message — the turn a vision provider reads
|
|
812
|
+
* images off — as a new array with that one message replaced by its carrying copy, and unchanged
|
|
813
|
+
* when there is no data or no user turn.
|
|
791
814
|
*
|
|
792
815
|
* @remarks
|
|
793
|
-
* Pure and total: the conversation and its messages are
|
|
816
|
+
* Pure and total: the conversation and its messages are never mutated, and the returned array
|
|
794
817
|
* replaces exactly the one target message with the copy {@link attachImages} builds. Empty
|
|
795
|
-
* data returns the conversation unchanged; a conversation with
|
|
818
|
+
* data returns the conversation unchanged; a conversation with no user message returns it
|
|
796
819
|
* unchanged too (there is nowhere to attach, and the images already rode the system block).
|
|
797
820
|
*
|
|
798
821
|
* @param conversation - The messages to attach into (left unchanged)
|
|
@@ -816,11 +839,11 @@ function attachUserImages(conversation, data) {
|
|
|
816
839
|
return conversation.map((message, index) => index === target ? attachImages(message, data) : message);
|
|
817
840
|
}
|
|
818
841
|
/**
|
|
819
|
-
* Collects the `base64` payload of the
|
|
820
|
-
*
|
|
842
|
+
* Collects the `base64` payload of the image files in a workspace file list — the data an agent
|
|
843
|
+
* context attaches to the last user message.
|
|
821
844
|
*
|
|
822
845
|
* @remarks
|
|
823
|
-
* Pure and total. `isBinary`
|
|
846
|
+
* Pure and total. `isBinary` narrows the tagless content to its binary arm (a total guard,
|
|
824
847
|
* never an assertion), then the MIME prefix gates it to an image, so a text file and a non-image
|
|
825
848
|
* binary (a PDF) are both skipped. Order follows the file list.
|
|
826
849
|
*
|
|
@@ -839,12 +862,12 @@ function collectImageData(files) {
|
|
|
839
862
|
return data;
|
|
840
863
|
}
|
|
841
864
|
/**
|
|
842
|
-
* Builds the
|
|
843
|
-
*
|
|
865
|
+
* Builds the raw synthetic summary message for one compacted section — role `'assistant'`, the
|
|
866
|
+
* section's stable `id`, and its `summary` verbatim as content.
|
|
844
867
|
*
|
|
845
868
|
* @remarks
|
|
846
869
|
* Pure and total. This is the unframed form the rollup regeneration digests (a
|
|
847
|
-
* summary-of-summaries over the section summaries); the recap
|
|
870
|
+
* summary-of-summaries over the section summaries); the recap label is a `view()`
|
|
848
871
|
* presentation concern kept out of what the summarizer re-reads — see
|
|
849
872
|
* {@link buildRecapMessage}.
|
|
850
873
|
*
|
|
@@ -865,13 +888,13 @@ function buildSummaryMessage(section) {
|
|
|
865
888
|
};
|
|
866
889
|
}
|
|
867
890
|
/**
|
|
868
|
-
* Builds the
|
|
869
|
-
*
|
|
870
|
-
*
|
|
891
|
+
* Builds the framed recap message for one compacted section — the same role and stable `id` as
|
|
892
|
+
* {@link buildSummaryMessage}, with the content prefixed by {@link
|
|
893
|
+
* import('./constants.js').CONVERSATION_RECAP_PREFIX}.
|
|
871
894
|
*
|
|
872
895
|
* @remarks
|
|
873
|
-
* Pure and total. The prefix is what makes a small model read the message as a
|
|
874
|
-
*
|
|
896
|
+
* Pure and total. The prefix is what makes a small model read the message as a condensed
|
|
897
|
+
* recap of earlier turns rather than a literal assistant turn to echo or answer from. It is a
|
|
875
898
|
* fixed handful of tokens, so a conversation's `view()` stays lean however many sections it
|
|
876
899
|
* carries.
|
|
877
900
|
*
|
|
@@ -892,12 +915,12 @@ function buildRecapMessage(section) {
|
|
|
892
915
|
};
|
|
893
916
|
}
|
|
894
917
|
/**
|
|
895
|
-
* Intersects two scope category lists under the "`undefined` is the universal set" rule —
|
|
896
|
-
* primitive a scope narrows through.
|
|
918
|
+
* Intersects two scope category lists under the "`undefined` is the universal set" rule — a
|
|
919
|
+
* fresh copy that can only tighten, and the primitive a scope narrows through.
|
|
897
920
|
*
|
|
898
921
|
* @remarks
|
|
899
|
-
* Pure and total, and it can only
|
|
900
|
-
* constraint); `undefined` ∩ a list is a
|
|
922
|
+
* Pure and total, and it can only tighten: `undefined` ∩ `undefined` is `undefined` (still no
|
|
923
|
+
* constraint); `undefined` ∩ a list is a copy of that list (the `undefined` side imposes
|
|
901
924
|
* nothing); a list ∩ a list keeps the child keys the parent also allows, so a parent-excluded
|
|
902
925
|
* key can never be re-admitted. Every returned list is a fresh copy, so a later mutation of
|
|
903
926
|
* either input cannot leak into the result.
|
|
@@ -922,36 +945,37 @@ function intersectKeys(parent, child) {
|
|
|
922
945
|
//#endregion
|
|
923
946
|
//#region src/core/conversations/Conversation.ts
|
|
924
947
|
/**
|
|
925
|
-
* Represents a conversation — a live uncompacted tail of messages it
|
|
926
|
-
*
|
|
927
|
-
* `
|
|
928
|
-
* {@link ConversationSummaryHandler} seam
|
|
948
|
+
* Represents a conversation — a live uncompacted tail of messages it owns directly above a flat
|
|
949
|
+
* message store, plus compacted, summarized {@link Section}s, a regenerated rollup `summary`, and
|
|
950
|
+
* a `summarizable` flag, with on-demand `rehydrate` and substring `search`, driven by a
|
|
951
|
+
* provider-agnostic {@link ConversationSummaryHandler} seam so `core` never imports a provider.
|
|
952
|
+
* Observable through its own `emitter`.
|
|
929
953
|
*
|
|
930
954
|
* @remarks
|
|
931
|
-
* - **Live tail + sections.** The conversation
|
|
955
|
+
* - **Live tail + sections.** The conversation owns its live tail directly — `#messages` is an
|
|
932
956
|
* insertion-ordered `Map` of immutable {@link Message}s keyed by their minted id
|
|
933
|
-
* (the
|
|
957
|
+
* (the same store mechanics a flat manager had, folded in: `add` / `message` / `messages` /
|
|
934
958
|
* `remove` / `clear` / `count`), exactly as a `Workspace` owns its files (no separate
|
|
935
959
|
* per-value manager). `#sections` are the compacted history (oldest → newest), each a
|
|
936
|
-
* summarized slice that
|
|
960
|
+
* summarized slice that retains its originals. `#summary` is the rollup (a
|
|
937
961
|
* summary-of-summaries over all sections), regenerated on each compaction (`undefined`
|
|
938
962
|
* until the first).
|
|
939
|
-
* - **`view()`.** Each section folds to
|
|
963
|
+
* - **`view()`.** Each section folds to one synthetic summary message (role `'assistant'` — a
|
|
940
964
|
* prior-context recap — keyed by the section's stable `id`), then the live messages
|
|
941
|
-
* verbatim. The rollup `summary` is
|
|
942
|
-
* carries the per-section summaries, which
|
|
965
|
+
* verbatim. The rollup `summary` is not injected (it is separately pull-able); `view()`
|
|
966
|
+
* carries the per-section summaries, which are the compaction benefit.
|
|
943
967
|
* - **`compact()`.** Folds the oldest `count - keep` live messages into a new section
|
|
944
968
|
* (its `summary` from `#summarize`), removes them from the live tail by id, regenerates the
|
|
945
|
-
* rollup (a
|
|
969
|
+
* rollup (a second `#summarize` over all section summaries), and emits `summary` then
|
|
946
970
|
* `compact`. Returns the section, or `undefined` when nothing folds (`count <= keep`).
|
|
947
|
-
*
|
|
948
|
-
*
|
|
971
|
+
* Throws a {@link ConversationError} when no `#summarize` was supplied. A compaction calls
|
|
972
|
+
* the summarizer for the section digest and again for the rollup.
|
|
949
973
|
* - **`rehydrate(id)` / `search(query)`.** `rehydrate` returns a section's full original
|
|
950
974
|
* messages (`[]` for an unknown id) and emits `rehydrate` — a pure read (the caller decides
|
|
951
975
|
* whether to re-add them; `rehydrate` never reinserts). `search` is a case-insensitive
|
|
952
|
-
* substring scan of `content` across
|
|
976
|
+
* substring scan of `content` across all messages (every section's originals + the live tail).
|
|
953
977
|
* - **Observable.** The owned {@link emitter} ({@link ConversationEventMap}) carries
|
|
954
|
-
* `compact` / `summary` / `rehydrate`, emitted directly, strictly
|
|
978
|
+
* `compact` / `summary` / `rehydrate`, emitted directly, strictly after the state change;
|
|
955
979
|
* the emitter isolates a listener throw and routes it to its `error` handler (the `error`
|
|
956
980
|
* option), so a buggy observer can never corrupt a compaction.
|
|
957
981
|
*
|
|
@@ -1117,26 +1141,27 @@ var Conversation = class {
|
|
|
1117
1141
|
//#endregion
|
|
1118
1142
|
//#region src/core/conversations/ConversationManager.ts
|
|
1119
1143
|
/**
|
|
1120
|
-
* Registers {@link Conversation}s keyed by `id`, in insertion order,
|
|
1121
|
-
*
|
|
1122
|
-
* {@link import('../AgentContext.js').AgentContext} renders
|
|
1123
|
-
*
|
|
1124
|
-
*
|
|
1144
|
+
* Registers {@link Conversation}s keyed by `id`, in insertion order, with an active pointer —
|
|
1145
|
+
* the id-keyed store over the conversation layer, the `active` / `switch` seam the
|
|
1146
|
+
* {@link import('../AgentContext.js').AgentContext} renders, and the durable `open` / `save`
|
|
1147
|
+
* store seam. Event-free (a registry, like
|
|
1148
|
+
* {@link import('@orkestrel/workspace').WorkspaceManager}); the observability lives on each
|
|
1149
|
+
* {@link Conversation}.
|
|
1125
1150
|
*
|
|
1126
1151
|
* @remarks
|
|
1127
1152
|
* - **Registry.** Conversations live in an insertion-ordered `Map` keyed by `id`. `add(input?)`
|
|
1128
1153
|
* mints a {@link Conversation} (its `id` from `input` or `crypto.randomUUID()`), flowing the
|
|
1129
|
-
* manager's default `#summarize` / `#keep` in unless the `input`
|
|
1130
|
-
* it (an already-present `id`
|
|
1154
|
+
* manager's default `#summarize` / `#keep` in unless the `input` overrides them, and stores
|
|
1155
|
+
* it (an already-present `id` overwrites — last write wins). `count` is the map size,
|
|
1131
1156
|
* `conversation(id)` looks one up, `conversations()` lists them in insertion order.
|
|
1132
1157
|
* - **Active pointer.** `active` is the active conversation (the agent's message source the
|
|
1133
|
-
* context renders), `undefined` until the
|
|
1158
|
+
* context renders), `undefined` until the first `add` (which auto-activates it — a registry
|
|
1134
1159
|
* with conversations always has one active). A subsequent `add` leaves `active` unchanged.
|
|
1135
1160
|
* `switch(id)` re-points `active` to the conversation with `id` and returns it; an unknown `id`
|
|
1136
1161
|
* returns `undefined` and leaves `active` unchanged (the lenient lookup style — never throws,
|
|
1137
1162
|
* no new error code).
|
|
1138
|
-
* - **Removal.** `remove` drops one by id, or a batch — `true` only when
|
|
1139
|
-
* removed; removing the
|
|
1163
|
+
* - **Removal.** `remove` drops one by id, or a batch — `true` only when every supplied id was
|
|
1164
|
+
* removed; removing the active conversation sets `active` to `undefined`. `clear` empties the registry
|
|
1140
1165
|
* and sets `active` to `undefined`.
|
|
1141
1166
|
* - **Event-free.** A purely registry store — no Emitter, no events (each conversation owns
|
|
1142
1167
|
* its own observable `emitter`).
|
|
@@ -1236,15 +1261,15 @@ var ConversationManager = class {
|
|
|
1236
1261
|
//#endregion
|
|
1237
1262
|
//#region src/core/instructions/Instruction.ts
|
|
1238
1263
|
/**
|
|
1239
|
-
* Represents an immutable named directive —
|
|
1240
|
-
*
|
|
1241
|
-
*
|
|
1264
|
+
* Represents an immutable named directive — an {@link InstructionInterface} assembled once from
|
|
1265
|
+
* its input (`name` / `content`, an optional `priority` defaulting to `0`), the `id` minted at
|
|
1266
|
+
* construction.
|
|
1242
1267
|
*
|
|
1243
1268
|
* @remarks
|
|
1244
1269
|
* A thin immutable value object (mirroring {@link import('@orkestrel/tool').Tool}): the
|
|
1245
1270
|
* constructor mints a fresh `id` (`crypto.randomUUID()`), copies the input's `name` /
|
|
1246
1271
|
* `content`, resolves `priority` to the input's value or `0`, and carries the input's
|
|
1247
|
-
* per-item `override`
|
|
1272
|
+
* per-item `override` only when supplied (assigned when present, mirroring a
|
|
1248
1273
|
* message's `images` / `calls` present-when-given convention — kept absent otherwise).
|
|
1249
1274
|
* Never mutated after construction. An
|
|
1250
1275
|
* {@link import('./InstructionManager.js').InstructionManager} keys it by `name` and
|
|
@@ -1273,28 +1298,29 @@ var Instruction = class {
|
|
|
1273
1298
|
//#endregion
|
|
1274
1299
|
//#region src/core/instructions/InstructionManager.ts
|
|
1275
1300
|
/**
|
|
1276
|
-
* Registers the immutable {@link Instruction}s a richer context assembles a directives
|
|
1277
|
-
*
|
|
1301
|
+
* Registers the immutable {@link Instruction}s a richer context assembles a directives block
|
|
1302
|
+
* from — keyed by `name` so a re-`add` overwrites, last write wins, and listed by descending
|
|
1303
|
+
* `priority`, carrying the `open` / `render` build contract and an observable `emitter`.
|
|
1278
1304
|
*
|
|
1279
1305
|
* @remarks
|
|
1280
1306
|
* - **Registry.** Instructions live in an insertion-ordered `Map` keyed by `name`;
|
|
1281
|
-
* `add` takes one {@link InstructionInput} or a batch,
|
|
1282
|
-
* `id`, and a re-`add` of the same name
|
|
1283
|
-
* map size, `instruction(name)` looks one up, and `instructions()` lists them
|
|
1307
|
+
* `add` takes one {@link InstructionInput} or a batch, mints each instruction's
|
|
1308
|
+
* `id`, and a re-`add` of the same name overwrites it (last write wins). `count` is the
|
|
1309
|
+
* map size, `instruction(name)` looks one up, and `instructions()` lists them sorted by
|
|
1284
1310
|
* descending `priority` (a stable sort, so equal priorities keep insertion order).
|
|
1285
1311
|
* - **Build contract (with the manager-options override).** `open` is the section
|
|
1286
1312
|
* header a context renders the instructions under; `render(instruction)` renders one
|
|
1287
|
-
* instruction (its `content`). Each
|
|
1313
|
+
* instruction (its `content`). Each encapsulates the cascade's `[options-override →
|
|
1288
1314
|
* built-in]` half: when `InstructionManagerOptions.format` supplies an `open` /
|
|
1289
|
-
* `render`, `open` / `render` return
|
|
1315
|
+
* `render`, `open` / `render` return it, else the built-in — so a richer context
|
|
1290
1316
|
* reads one consistent pair and layers the provider default + per-item override on top
|
|
1291
1317
|
* (see {@link import('../AgentContext.js').AgentContext}). The per-item
|
|
1292
1318
|
* {@link InstructionInput.override} is round-tripped onto the stored instruction.
|
|
1293
|
-
* - **Removal.** `remove` drops one by name, or a batch — `true` only when
|
|
1319
|
+
* - **Removal.** `remove` drops one by name, or a batch — `true` only when every supplied
|
|
1294
1320
|
* name was removed; `clear` empties the registry.
|
|
1295
1321
|
* - **Observable.** The owned {@link emitter} ({@link InstructionManagerEventMap})
|
|
1296
1322
|
* carries `add` (the created instruction) / `remove` (the name) / `clear` for
|
|
1297
|
-
* fire-and-forget observers. Every event is emitted directly, strictly
|
|
1323
|
+
* fire-and-forget observers. Every event is emitted directly, strictly after the map
|
|
1298
1324
|
* mutation completes; the emitter isolates a listener throw and routes it to its `error`
|
|
1299
1325
|
* handler (the `error` option), so a buggy observer can never corrupt a mutation.
|
|
1300
1326
|
*
|
|
@@ -1373,58 +1399,59 @@ var InstructionManager = class {
|
|
|
1373
1399
|
/**
|
|
1374
1400
|
* Assembles a provider request from the richer turn context — the optional system prompt, the
|
|
1375
1401
|
* observable context managers (instructions / workspaces), the
|
|
1376
|
-
* {@link ConversationManagerInterface} message source
|
|
1377
|
-
*
|
|
1378
|
-
* {@link AgentContextInterface.apply}.
|
|
1402
|
+
* {@link ConversationManagerInterface} message source whose active conversation is `messages`, the
|
|
1403
|
+
* {@link ToolManagerInterface} registry, and an active {@link ScopeInterface} changed through
|
|
1404
|
+
* {@link AgentContextInterface.apply}. `build()` folds the scoped managers and the active
|
|
1405
|
+
* workspace into one system block, then the conversation, and never reads `tools`.
|
|
1379
1406
|
*
|
|
1380
1407
|
* @remarks
|
|
1381
1408
|
* - **Composition.** `system` is the optional system prompt; `instructions` / `tools` /
|
|
1382
1409
|
* `workspaces` / `conversations` are the registries passed in `options` (bring your own), or
|
|
1383
|
-
* fresh empty ones when omitted (so `workspaces` is
|
|
1384
|
-
* conversation's live tail (
|
|
1410
|
+
* fresh empty ones when omitted (so `workspaces` is always present); `messages` is the active
|
|
1411
|
+
* conversation's live tail (always defined — see the following item). `scope` is the active filter —
|
|
1385
1412
|
* `undefined` (the default) ⇒ no filtering; change it through `apply(scope)`. The structural
|
|
1386
1413
|
* `workspaces` / `conversations` registries are fixed at construction; switch their active
|
|
1387
1414
|
* members through their own `switch(id)` methods.
|
|
1388
|
-
* - **The message source — the conversation registry's
|
|
1389
|
-
* {@link ConversationManagerInterface}; the context
|
|
1390
|
-
* (at construction it `add`s a default when the manager has none), so the
|
|
1391
|
-
* getter — `this.#conversations.active` — is
|
|
1392
|
-
* conversation
|
|
1415
|
+
* - **The message source — the conversation registry's active conversation.** `conversations` is a
|
|
1416
|
+
* {@link ConversationManagerInterface}; the context ensures it always has an active conversation
|
|
1417
|
+
* (at construction it `add`s a default when the manager has none), so the dynamic `messages`
|
|
1418
|
+
* getter — `this.#conversations.active` — is always defined. `messages` returns the active
|
|
1419
|
+
* conversation itself (it owns the live tail + the message verbs directly, satisfying
|
|
1393
1420
|
* {@link MessageManagerInterface} structurally — the same reference, no duplication), and
|
|
1394
1421
|
* `build()` folds that conversation's `view()` (its per-section summaries + live tail) as the
|
|
1395
|
-
*
|
|
1422
|
+
* authoritative message inclusion — the scope does not filter the conversation (it owns inclusion
|
|
1396
1423
|
* through compaction; scope filters only instructions / tools / workspace files). Because `messages`
|
|
1397
|
-
* is read dynamically, an agent
|
|
1398
|
-
* conversation
|
|
1424
|
+
* is read dynamically, an agent switches the active
|
|
1425
|
+
* conversation between runs (`conversations.switch(id)`) to serve many threads (the real
|
|
1399
1426
|
* multi-conversation pattern); switch between runs, not during a run, and use separate agents
|
|
1400
1427
|
* for concurrent threads.
|
|
1401
1428
|
* - **`build(format?)` — the scoped assembly + the format cascade.** It folds, in order,
|
|
1402
|
-
* the system prompt then the scope-filtered instructions → the
|
|
1429
|
+
* the system prompt then the scope-filtered instructions → the active workspace's text files
|
|
1403
1430
|
* (each as a block: the section's resolved `open` text, each item's resolved rendering, then
|
|
1404
|
-
* any resolved `close` text) into
|
|
1405
|
-
* one part exists), then appends the
|
|
1406
|
-
* message inclusion through compaction — the scope does
|
|
1431
|
+
* any resolved `close` text) into one leading `system` message (prepended only when at least
|
|
1432
|
+
* one part exists), then appends the active conversation's `view()` (the conversation owns
|
|
1433
|
+
* message inclusion through compaction — the scope does not filter the conversation). Each
|
|
1407
1434
|
* `open` / item / `close`
|
|
1408
|
-
* resolves
|
|
1409
|
-
* per-section default) is the
|
|
1435
|
+
* resolves independently, most-specific-first — `build()`'s optional `format` (a provider's
|
|
1436
|
+
* per-section default) is the provider level: `open` = manager-options-override > provider >
|
|
1410
1437
|
* built-in; per item = item-override > manager-options-override > provider > built-in; `close` =
|
|
1411
|
-
* manager-options-override > provider (
|
|
1412
|
-
* {@link AgentContextInterface.build}). Passing
|
|
1438
|
+
* manager-options-override > provider (no built-in ⇒ no closing line when unset) (see
|
|
1439
|
+
* {@link AgentContextInterface.build}). Passing no `format` (and with no overrides / no per-item
|
|
1413
1440
|
* override) reproduces the built-in framing byte-for-byte (each section is its built-in header +
|
|
1414
1441
|
* items, no closing line). The active workspace's scoped-in image files' `base64` payload is attached to
|
|
1415
|
-
* the
|
|
1442
|
+
* the last user message (a vision provider reads images off a user turn); when no user message
|
|
1416
1443
|
* exists the attachment is skipped. Built fresh each call (recomputed, never cached), so it
|
|
1417
1444
|
* always reflects the current managers / messages / scope / active workspace; it never mutates a
|
|
1418
1445
|
* manager or the stored messages.
|
|
1419
|
-
* - **The
|
|
1446
|
+
* - **The active workspace, rendered by carrier — the sole document/image context.**
|
|
1420
1447
|
* `workspaces.active` (when set) has its {@link import('@orkestrel/workspace').FileInterface}s scope-filtered by `scope.files`,
|
|
1421
|
-
* then split:
|
|
1422
|
-
* blocks — placed right after the instructions section), and
|
|
1423
|
-
* to the last user message.
|
|
1424
|
-
* workspace nothing renders for workspaces. `build()`
|
|
1448
|
+
* then split: text files fold into a dedicated `## Workspace` system section (fenced reference
|
|
1449
|
+
* blocks — placed right after the instructions section), and image files' `base64` payload attaches
|
|
1450
|
+
* to the last user message. Active-only — never the other registered workspaces; with no active
|
|
1451
|
+
* workspace nothing renders for workspaces. `build()` owns this render (a `Workspace` /
|
|
1425
1452
|
* `WorkspaceManager` stays file-focused).
|
|
1426
1453
|
* - **Tools are structural, not in the prompt.** The registry is advertised to the provider
|
|
1427
|
-
* through `tools.definitions()` (scope-filtered by the loop),
|
|
1454
|
+
* through `tools.definitions()` (scope-filtered by the loop), never serialized into the
|
|
1428
1455
|
* message array — so `build()`'s output carries no tool content, scoped or not.
|
|
1429
1456
|
* - **Event-free context; observable managers.** The context itself owns no Emitter; the
|
|
1430
1457
|
* context managers each carry their own (the push observation surface).
|
|
@@ -1503,10 +1530,11 @@ var AgentContext = class {
|
|
|
1503
1530
|
//#endregion
|
|
1504
1531
|
//#region src/core/Channel.ts
|
|
1505
1532
|
/**
|
|
1506
|
-
* Buffers chunks in a minimal unbounded async channel — the eager pump
|
|
1507
|
-
*
|
|
1508
|
-
*
|
|
1509
|
-
*
|
|
1533
|
+
* Buffers chunks in a minimal unbounded async channel — the eager pump writes them in (`push`)
|
|
1534
|
+
* and ends it (`close` / `fail`) regardless of consumption, while a consumer reads them back live
|
|
1535
|
+
* through the `drain` async-iterator. Decoupling write from read is what lets a producer make
|
|
1536
|
+
* progress without a consumer pulling, and it is why an agent's `result` settles whether or not
|
|
1537
|
+
* its `events` are drained.
|
|
1510
1538
|
*
|
|
1511
1539
|
* @remarks
|
|
1512
1540
|
* The standard resolver-swap: a waiting `drain` parks on `#wake` (a void resolver);
|
|
@@ -1567,8 +1595,10 @@ var Channel = class {
|
|
|
1567
1595
|
//#region src/core/Agent.ts
|
|
1568
1596
|
/**
|
|
1569
1597
|
* Composes a {@link ProviderInterface}, an {@link AgentContext}, and a
|
|
1570
|
-
* {@link ToolManagerInterface} into a bounded context → provider → tools → repeat
|
|
1571
|
-
*
|
|
1598
|
+
* {@link ToolManagerInterface} into a bounded context → provider → tools → repeat turn, exposed
|
|
1599
|
+
* as both a one-shot `generate` and a live `stream` that share one private run — bounded by the
|
|
1600
|
+
* run `signal`, the `timeout`, and the `budget` folded through `AbortSignal.any`, paced by
|
|
1601
|
+
* `scheduler`, with tool iteration capped at `limit`.
|
|
1572
1602
|
*
|
|
1573
1603
|
* @remarks
|
|
1574
1604
|
* - **One loop, two faces.** A single private async generator (`#run`) drives the
|
|
@@ -1585,15 +1615,15 @@ var Channel = class {
|
|
|
1585
1615
|
* assistant message and stop.
|
|
1586
1616
|
* - **Bounded.** Each run arms one cancel through `createAbort({ signal: AbortSignal.any([
|
|
1587
1617
|
* …]) })` folding the external `signal`, the `timeout` deadline, and the `budget`
|
|
1588
|
-
* signal; `abort()` fires it. Any trip stops the loop and commits a
|
|
1589
|
-
* (the `result` promise
|
|
1618
|
+
* signal; `abort()` fires it. Any trip stops the loop and commits a partial result
|
|
1619
|
+
* (the `result` promise resolves, never rejects, on a cancel) — only a genuine
|
|
1590
1620
|
* provider / tool error rejects.
|
|
1591
1621
|
* - **Paced + capped.** The `scheduler` (when given) `yield`s between turns; tool
|
|
1592
1622
|
* iteration is capped at `limit`.
|
|
1593
|
-
* - **Two observation surfaces.** The
|
|
1594
|
-
* deltas (+ usage/tool chunks); the
|
|
1623
|
+
* - **Two observation surfaces.** The pull {@link AgentChunk} stream carries per-token
|
|
1624
|
+
* deltas (+ usage/tool chunks); the push {@link emitter} ({@link AgentEventMap}) carries
|
|
1595
1625
|
* lifecycle + usage/tool/deny moments for fire-and-forget observers. Every event is
|
|
1596
|
-
* emitted directly,
|
|
1626
|
+
* emitted directly, after the relevant state transition / settle; the emitter isolates a
|
|
1597
1627
|
* listener throw and routes it to its `error` handler (the `error` option), so a buggy
|
|
1598
1628
|
* observer can never escape into / reorder / corrupt the settle-once loop — observation is
|
|
1599
1629
|
* purely a side-channel.
|
|
@@ -1945,9 +1975,10 @@ var Agent = class {
|
|
|
1945
1975
|
//#endregion
|
|
1946
1976
|
//#region src/core/AgentRegistry.ts
|
|
1947
1977
|
/**
|
|
1948
|
-
* Makes a durable, JSON-serializable {@link AgentJobInput} runnable — holds the named
|
|
1949
|
-
*
|
|
1950
|
-
*
|
|
1978
|
+
* Makes a durable, JSON-serializable {@link AgentJobInput} runnable — holds the named pools of
|
|
1979
|
+
* live, non-serializable pieces (providers, tools, authorities, schedulers), throws on a name
|
|
1980
|
+
* absent from its pool, and `build`s a seeded, signal-wired {@link Agent} from a job's names and
|
|
1981
|
+
* data.
|
|
1951
1982
|
*
|
|
1952
1983
|
* @remarks
|
|
1953
1984
|
* - **Why it exists.** An `AgentJobInput` is serializable so it can survive a crash in a
|
|
@@ -1956,9 +1987,9 @@ var Agent = class {
|
|
|
1956
1987
|
* construct it once with the live pools, then a queue / runner handler calls `build`
|
|
1957
1988
|
* on each (possibly restored) job to get a ready agent.
|
|
1958
1989
|
* - **Accessors throw on a miss.** `provider` / `tool` / `authority` / `scheduler` resolve a
|
|
1959
|
-
* name against their pool and
|
|
1990
|
+
* name against their pool and throw an {@link AgentError} carrying `code: 'REGISTRY'` and
|
|
1960
1991
|
* the message `unknown <category>: <name>` when it is absent — an unknown name in a
|
|
1961
|
-
* rehydrated job is a programmer / config error that must fail
|
|
1992
|
+
* rehydrated job is a programmer / config error that must fail loudly at build time, never
|
|
1962
1993
|
* silently resolve to `undefined` and run an agent missing a dependency.
|
|
1963
1994
|
* - **`build` rehydrates.** Resolve the job's `provider`; assemble a fresh
|
|
1964
1995
|
* {@link ToolManager} from the `tools` names; rebuild the token `budget` from its
|
|
@@ -2039,18 +2070,20 @@ var AgentRegistry = class {
|
|
|
2039
2070
|
//#endregion
|
|
2040
2071
|
//#region src/core/Authority.ts
|
|
2041
2072
|
/**
|
|
2042
|
-
* Gates the agent loop's tool calls — the synchronous policy consulted before each call
|
|
2043
|
-
*
|
|
2073
|
+
* Gates the agent loop's tool calls — the synchronous policy consulted before each call runs,
|
|
2074
|
+
* turning one {@link AuthorityContext} into an {@link AuthorityDecision} by walking the ordered
|
|
2075
|
+
* rules first-match-wins and falling back to a configurable default, which allows an unmatched
|
|
2076
|
+
* call unless its `fallback` denies.
|
|
2044
2077
|
*
|
|
2045
2078
|
* @remarks
|
|
2046
2079
|
* - **Ordered, first-match-wins.** `evaluate` walks the configured rules in order and
|
|
2047
|
-
* returns the
|
|
2048
|
-
* `{ zone, allowed: rule.allowed ?? true, reason }` — a matched rule
|
|
2049
|
-
* default and
|
|
2080
|
+
* returns the first whose `match(context)` is true as
|
|
2081
|
+
* `{ zone, allowed: rule.allowed ?? true, reason }` — a matched rule allows by
|
|
2082
|
+
* default and denies only when its `allowed` is explicitly `false`.
|
|
2050
2083
|
* - **Fallback.** When no rule matches, `evaluate` returns the configured `fallback`.
|
|
2051
2084
|
* It defaults to `{ zone: DEFAULT_AUTHORITY_ZONE, allowed: true }` (allow-unmatched),
|
|
2052
|
-
* so a rules list of denials behaves as a
|
|
2053
|
-
* (an
|
|
2085
|
+
* so a rules list of denials behaves as a denylist. To make the gate deny-by-default
|
|
2086
|
+
* (an allowlist — only matched rules that allow get through), pass an `allowed: false`
|
|
2054
2087
|
* `fallback`.
|
|
2055
2088
|
* - **Consulted before each tool call.** The agent loop calls `evaluate({ call })` for
|
|
2056
2089
|
* every {@link import('@orkestrel/tool').ToolCall} the model emits; a denied call is fed
|
|
@@ -2093,14 +2126,15 @@ var Authority = class {
|
|
|
2093
2126
|
//#region src/core/validators.ts
|
|
2094
2127
|
/**
|
|
2095
2128
|
* Checks whether an `unknown` is structurally a {@link Message} record — the per-message step of
|
|
2096
|
-
* the {@link isConversationSnapshot} read-boundary
|
|
2097
|
-
*
|
|
2129
|
+
* the {@link isConversationSnapshot} and {@link isSection} read-boundary narrows, where a present
|
|
2130
|
+
* `calls` must be an array of valid {@link import('@orkestrel/tool').ToolCall}s. Total, never
|
|
2131
|
+
* throwing, and never an assertion; the conversation analogue of
|
|
2098
2132
|
* {@link import('@orkestrel/workspace').isFile}.
|
|
2099
2133
|
*
|
|
2100
2134
|
* @remarks
|
|
2101
|
-
* A total guard (it
|
|
2102
|
-
*
|
|
2103
|
-
* — a `calls` array
|
|
2135
|
+
* A total guard (it never throws — adversarial input returns `false`). It checks the message's
|
|
2136
|
+
* shape: a record with a `string` `id`, a `string` `role`, a `string` `content`, and — when present
|
|
2137
|
+
* — a `calls` array every element of which is a valid
|
|
2104
2138
|
* {@link import('@orkestrel/tool').ToolCall} ({@link isToolCall} — the
|
|
2105
2139
|
* fail-closed deepening: a tampered `calls` element rejects the message, so the snapshot
|
|
2106
2140
|
* reads back as absent rather than replaying a malformed call) and an `images` that is an array
|
|
@@ -2108,7 +2142,7 @@ var Authority = class {
|
|
|
2108
2142
|
* {@link import('./types.js').MessageRole}, so any storage-read role string is accepted
|
|
2109
2143
|
* defensively rather than rejected against the current literal set). Enough to safely impose the
|
|
2110
2144
|
* {@link Message} type at
|
|
2111
|
-
* a storage boundary
|
|
2145
|
+
* a storage boundary without a cast.
|
|
2112
2146
|
*
|
|
2113
2147
|
* @param value - The value to test (one element of a snapshot's `messages` / a section's `messages`)
|
|
2114
2148
|
* @returns True if `value` has the structural shape of a {@link Message}; false otherwise
|
|
@@ -2128,15 +2162,16 @@ function isMessage(value) {
|
|
|
2128
2162
|
return value.images === void 0 || isArray(value.images);
|
|
2129
2163
|
}
|
|
2130
2164
|
/**
|
|
2131
|
-
* Checks whether an `unknown` is structurally a {@link Section} record —
|
|
2132
|
-
*
|
|
2133
|
-
* read, never an
|
|
2165
|
+
* Checks whether an `unknown` is structurally a {@link Section} record — a `string` `id` and
|
|
2166
|
+
* `summary` beside a `messages` array of valid {@link Message}s, the per-section step of the
|
|
2167
|
+
* {@link isConversationSnapshot} read-boundary narrow. Total, never throwing, and never an
|
|
2168
|
+
* assertion.
|
|
2134
2169
|
*
|
|
2135
2170
|
* @remarks
|
|
2136
|
-
* A total guard (it
|
|
2137
|
-
*
|
|
2171
|
+
* A total guard (it never throws — adversarial input returns `false`). It checks the section's
|
|
2172
|
+
* shape: a record with a `string` `id`, a `string` `summary`, and a `messages` array every element
|
|
2138
2173
|
* of which is a valid {@link Message} record ({@link isMessage}). Enough to safely impose
|
|
2139
|
-
* the {@link Section} type at a storage boundary
|
|
2174
|
+
* the {@link Section} type at a storage boundary without a cast.
|
|
2140
2175
|
*
|
|
2141
2176
|
* @param value - The value to test (one element of a snapshot's `sections` array)
|
|
2142
2177
|
* @returns True if `value` has the structural shape of a {@link Section}; false otherwise
|
|
@@ -2154,19 +2189,20 @@ function isSection(value) {
|
|
|
2154
2189
|
return isArray(value.messages) && value.messages.every(isMessage);
|
|
2155
2190
|
}
|
|
2156
2191
|
/**
|
|
2157
|
-
* Narrows an `unknown` to a {@link ConversationSnapshot} —
|
|
2158
|
-
*
|
|
2192
|
+
* Narrows an `unknown` to a {@link ConversationSnapshot} — a `string` `id`, an optional `string`
|
|
2193
|
+
* `summary`, and valid `sections` and `messages` arrays; the total boundary guard for an
|
|
2194
|
+
* untrusted snapshot read (a storage row a
|
|
2159
2195
|
* {@link import('./conversations/stores/DatabaseConversationStore.js').DatabaseConversationStore}
|
|
2160
|
-
* reads back from its opaque JSON column, a snapshot loaded from disk). The
|
|
2161
|
-
* {@link import('@orkestrel/workspace').isWorkspaceSnapshot}.
|
|
2196
|
+
* reads back from its opaque JSON column, a snapshot loaded from disk), never throwing. The exact
|
|
2197
|
+
* analogue of {@link import('@orkestrel/workspace').isWorkspaceSnapshot}.
|
|
2162
2198
|
*
|
|
2163
2199
|
* @remarks
|
|
2164
|
-
* A total guard (it
|
|
2165
|
-
*
|
|
2166
|
-
* `undefined` until the first compaction), a `sections` array
|
|
2167
|
-
* {@link Section} ({@link isSection}), and a `messages` array
|
|
2200
|
+
* A total guard (it never throws — adversarial input returns `false`). It checks the snapshot's
|
|
2201
|
+
* shape: a `string` `id`, an optional `string` `summary` (present-or-absent — the rollup is
|
|
2202
|
+
* `undefined` until the first compaction), a `sections` array every element of which is a valid
|
|
2203
|
+
* {@link Section} ({@link isSection}), and a `messages` array every element of which is a
|
|
2168
2204
|
* valid {@link Message} ({@link isMessage}) — enough to safely impose the
|
|
2169
|
-
* {@link ConversationSnapshot} type at a storage boundary
|
|
2205
|
+
* {@link ConversationSnapshot} type at a storage boundary without a cast. The structural twin of
|
|
2170
2206
|
* {@link import('@orkestrel/workspace').isWorkspaceSnapshot}. A malformed blob (a non-record, a missing / non-string `id`, a
|
|
2171
2207
|
* non-string `summary` when present, a non-array `sections` / `messages`, or any malformed
|
|
2172
2208
|
* element) resolves `false`, so a
|
|
@@ -2195,37 +2231,39 @@ function isConversationSnapshot(value) {
|
|
|
2195
2231
|
//#region src/core/conversations/stores/DatabaseConversationStore.ts
|
|
2196
2232
|
/**
|
|
2197
2233
|
* Backs a {@link ConversationStoreInterface} with one table of the `databases` layer — a
|
|
2198
|
-
* conversation's durable state
|
|
2199
|
-
*
|
|
2200
|
-
* {@link
|
|
2234
|
+
* conversation's durable state is a row holding the snapshot as one opaque JSON column, narrowed
|
|
2235
|
+
* back on `get` by {@link import('../../validators.js').isConversationSnapshot}, so persistence
|
|
2236
|
+
* reduces to keyed point-access (`get` / `set` / `delete`) over a {@link TableInterface}. The
|
|
2237
|
+
* driver-pluggable twin of the plain-`Map`
|
|
2238
|
+
* {@link import('./MemoryConversationStore.js').MemoryConversationStore}, and the exact twin of
|
|
2201
2239
|
* {@link import('@orkestrel/workspace').DatabaseWorkspaceStore}.
|
|
2202
2240
|
*
|
|
2203
2241
|
* @remarks
|
|
2204
2242
|
* The store is driver-agnostic: it holds a single {@link TableInterface} whose backend (memory,
|
|
2205
2243
|
* JSON, SQLite, IndexedDB) is chosen by whoever builds it (the factories), so a JSON / SQLite /
|
|
2206
|
-
* IndexedDB backend swaps in
|
|
2244
|
+
* IndexedDB backend swaps in without touching the
|
|
2207
2245
|
* {@link import('../ConversationManager.js').ConversationManager} or the
|
|
2208
2246
|
* {@link import('../Conversation.js').Conversation} — the same seam as
|
|
2209
2247
|
* {@link import('@orkestrel/workspace').DatabaseWorkspaceStore}. The
|
|
2210
2248
|
* driver defaults to memory ({@link import('../../factories.js').createDatabaseConversationStore}
|
|
2211
|
-
* passes `createMemoryDriver()`), so it
|
|
2249
|
+
* passes `createMemoryDriver()`), so it also works in memory out of the box; you opt into the
|
|
2212
2250
|
* durable plumbing by passing a JSON / SQLite / IndexedDB driver.
|
|
2213
2251
|
*
|
|
2214
|
-
* The {@link ConversationSnapshot} is stored as
|
|
2252
|
+
* The {@link ConversationSnapshot} is stored as one opaque JSON column — the table is a row of
|
|
2215
2253
|
* `{ id; snapshot }` ({@link ConversationSnapshotRow}), the snapshot the whole JSON blob (a
|
|
2216
2254
|
* `rawShape` column the factory builds) — exactly as `DatabaseWorkspaceStore` stores its snapshot.
|
|
2217
|
-
* The snapshot is already a
|
|
2218
|
-
* lossless
|
|
2255
|
+
* The snapshot is already a complete, self-contained, pure-JSON payload, so storing it whole is
|
|
2256
|
+
* lossless and keeps the row type flat (`snapshot` reads back as `unknown`).
|
|
2219
2257
|
*
|
|
2220
|
-
* - **`set(snapshot)` upserts under the snapshot's
|
|
2258
|
+
* - **`set(snapshot)` upserts under the snapshot's own `id`** (no separate id param) — it writes
|
|
2221
2259
|
* the row `{ id: snapshot.id, snapshot }`.
|
|
2222
2260
|
* - **`get(id)` resolves the stored snapshot for an id**, narrowing the opaque JSON column back to
|
|
2223
2261
|
* a {@link ConversationSnapshot} ({@link import('../../validators.js').isConversationSnapshot} — the
|
|
2224
2262
|
* total guard for an untrusted storage read), or `undefined` if none is stored.
|
|
2225
2263
|
* - **`delete(id)` drops a snapshot by id**; an absent id is a no-op (no throw).
|
|
2226
2264
|
*
|
|
2227
|
-
*
|
|
2228
|
-
* explicit `delete`. The public surface is
|
|
2265
|
+
* Unlike a session store there is no idle-TTL / eviction — a persisted conversation lives until an
|
|
2266
|
+
* explicit `delete`. The public surface is exactly `get` / `set` / `delete` — no extra members (the
|
|
2229
2267
|
* method bijection with {@link ConversationStoreInterface}). Hydration stays a caller concern: a
|
|
2230
2268
|
* {@link import('../ConversationManager.js').ConversationManager} reads a snapshot back and rebuilds
|
|
2231
2269
|
* the live conversation through the `snapshot` option (its `open` / `save`).
|
|
@@ -2260,7 +2298,7 @@ var DatabaseConversationStore = class {
|
|
|
2260
2298
|
if (row === void 0) return void 0;
|
|
2261
2299
|
return isConversationSnapshot(row.snapshot) ? row.snapshot : void 0;
|
|
2262
2300
|
}
|
|
2263
|
-
/** Inserts or replaces under the snapshot's
|
|
2301
|
+
/** Inserts or replaces under the snapshot's own `id` (no separate id param) — the row is `{ id, snapshot }`. */
|
|
2264
2302
|
async set(snapshot) {
|
|
2265
2303
|
await this.#table.set({
|
|
2266
2304
|
id: snapshot.id,
|
|
@@ -2276,26 +2314,27 @@ var DatabaseConversationStore = class {
|
|
|
2276
2314
|
//#region src/core/conversations/stores/MemoryConversationStore.ts
|
|
2277
2315
|
/**
|
|
2278
2316
|
* Implements the {@link ConversationStoreInterface} in memory — a process-lifetime `Map` of
|
|
2279
|
-
* {@link ConversationSnapshot}s keyed by conversation id, the
|
|
2280
|
-
* {@link import('../../factories.js').createMemoryConversationStore} builds
|
|
2317
|
+
* {@link ConversationSnapshot}s keyed by conversation id, the default store
|
|
2318
|
+
* {@link import('../../factories.js').createMemoryConversationStore} builds and the default
|
|
2319
|
+
* backing for `open` / `save`. The exact twin of
|
|
2281
2320
|
* {@link import('@orkestrel/workspace').MemoryWorkspaceStore}.
|
|
2282
2321
|
*
|
|
2283
2322
|
* @remarks
|
|
2284
2323
|
* A plain `Map<string, ConversationSnapshot>` — the snapshot is already pure,
|
|
2285
2324
|
* self-contained JSON, so no encoding is needed for the memory tier. Like the
|
|
2286
2325
|
* {@link import('@orkestrel/workspace').MemoryWorkspaceStore} it twins,
|
|
2287
|
-
* there is
|
|
2288
|
-
* durable backend (JSON / SQLite / IndexedDB) swaps in through the
|
|
2326
|
+
* there is no idle-TTL and no eviction: a persisted conversation lives until an explicit `delete`. A
|
|
2327
|
+
* durable backend (JSON / SQLite / IndexedDB) swaps in through the same interface without touching
|
|
2289
2328
|
* the {@link import('../ConversationManager.js').ConversationManager} or the
|
|
2290
2329
|
* {@link import('../Conversation.js').Conversation} — its driver-pluggable twin is
|
|
2291
2330
|
* {@link import('./DatabaseConversationStore.js').DatabaseConversationStore} (the snapshot as one
|
|
2292
2331
|
* opaque JSON column).
|
|
2293
2332
|
*
|
|
2294
2333
|
* - **`get` resolves the persisted snapshot for an id**, or `undefined` if none is stored.
|
|
2295
|
-
* - **`set` inserts / replaces under the snapshot's
|
|
2334
|
+
* - **`set` inserts / replaces under the snapshot's own `id`** (no separate id param).
|
|
2296
2335
|
* - **`delete` drops a snapshot by id**; an absent id is a no-op (no throw).
|
|
2297
2336
|
*
|
|
2298
|
-
* The public surface is
|
|
2337
|
+
* The public surface is exactly `get` / `set` / `delete` — no extra members (the method
|
|
2299
2338
|
* bijection with {@link ConversationStoreInterface}). Hydration is a caller concern: a
|
|
2300
2339
|
* {@link import('../ConversationManager.js').ConversationManager} reads a snapshot back and rebuilds
|
|
2301
2340
|
* the live conversation through the `snapshot` option (its `open` / `save`).
|
|
@@ -2314,13 +2353,32 @@ var DatabaseConversationStore = class {
|
|
|
2314
2353
|
*/
|
|
2315
2354
|
var MemoryConversationStore = class {
|
|
2316
2355
|
#snapshots = /* @__PURE__ */ new Map();
|
|
2356
|
+
/**
|
|
2357
|
+
* Resolves the persisted snapshot for `id`, or `undefined` if none is stored.
|
|
2358
|
+
*
|
|
2359
|
+
* @param id - The conversation id to resolve (a {@link ConversationSnapshot.id})
|
|
2360
|
+
* @returns The persisted snapshot, or `undefined` if absent
|
|
2361
|
+
*/
|
|
2317
2362
|
get(id) {
|
|
2318
2363
|
return Promise.resolve(this.#snapshots.get(id));
|
|
2319
2364
|
}
|
|
2365
|
+
/**
|
|
2366
|
+
* Inserts or replaces a snapshot under its own `snapshot.id` (no separate id param —
|
|
2367
|
+
* mirroring {@link import('@orkestrel/workspace').WorkspaceStoreInterface}'s `set`).
|
|
2368
|
+
*
|
|
2369
|
+
* @param snapshot - The snapshot to store (keyed by its `id`)
|
|
2370
|
+
* @returns A promise that resolves after the snapshot is stored
|
|
2371
|
+
*/
|
|
2320
2372
|
set(snapshot) {
|
|
2321
2373
|
this.#snapshots.set(snapshot.id, snapshot);
|
|
2322
2374
|
return Promise.resolve();
|
|
2323
2375
|
}
|
|
2376
|
+
/**
|
|
2377
|
+
* Drops a snapshot by id; an absent id is a no-op (no throw).
|
|
2378
|
+
*
|
|
2379
|
+
* @param id - The conversation id to drop
|
|
2380
|
+
* @returns A promise that resolves after the snapshot is dropped
|
|
2381
|
+
*/
|
|
2324
2382
|
delete(id) {
|
|
2325
2383
|
this.#snapshots.delete(id);
|
|
2326
2384
|
return Promise.resolve();
|
|
@@ -2329,23 +2387,25 @@ var MemoryConversationStore = class {
|
|
|
2329
2387
|
//#endregion
|
|
2330
2388
|
//#region src/core/scopes/Scope.ts
|
|
2331
2389
|
/**
|
|
2332
|
-
* Represents a named, immutable filter over a richer context's items — an optional
|
|
2333
|
-
*
|
|
2334
|
-
*
|
|
2390
|
+
* Represents a named, immutable filter over a richer context's items — an optional allow-list per
|
|
2391
|
+
* category (`instructions` / `tools` / `files`), each keyed by that category's identity (an
|
|
2392
|
+
* instruction's `name`, a tool's `name`, a workspace file's `path`) and read as an allow-list:
|
|
2393
|
+
* `undefined` lets everything pass, `[]` lets nothing pass, and a non-empty list passes the listed
|
|
2394
|
+
* keys alone. `narrow` composes a tighter child by set intersection.
|
|
2335
2395
|
*
|
|
2336
2396
|
* @remarks
|
|
2337
|
-
* - **A category list is three-way.** `undefined` ⇒
|
|
2338
|
-
* pass); `[]` ⇒
|
|
2397
|
+
* - **A category list is three-way.** `undefined` ⇒ no constraint on that category (all
|
|
2398
|
+
* pass); `[]` ⇒ none pass; a non-empty list ⇒ only the listed keys pass. The build
|
|
2339
2399
|
* step / loop apply this through `filterAllowList`.
|
|
2340
|
-
* - **Immutable.** The `id` is minted at construction; every supplied list is
|
|
2400
|
+
* - **Immutable.** The `id` is minted at construction; every supplied list is copied in
|
|
2341
2401
|
* (so a later mutation of the caller's array can't leak in), and the lists are
|
|
2342
|
-
* `readonly`. A `Scope` is never mutated after construction — `narrow` returns a
|
|
2402
|
+
* `readonly`. A `Scope` is never mutated after construction — `narrow` returns a new
|
|
2343
2403
|
* one rather than altering this one.
|
|
2344
|
-
* - **`narrow` is set-
|
|
2345
|
-
* per category is the intersection of
|
|
2404
|
+
* - **`narrow` is set-intersection (immutable composition).** A child scope's visible set
|
|
2405
|
+
* per category is the intersection of this scope's list and the config's list — but
|
|
2346
2406
|
* `undefined` means "no constraint", so it acts as the universal set: intersecting
|
|
2347
2407
|
* `undefined` with a list yields the list, and `undefined` with `undefined` stays
|
|
2348
|
-
* `undefined`. Narrowing can only
|
|
2408
|
+
* `undefined`. Narrowing can only tighten, never widen — a key excluded by a parent
|
|
2349
2409
|
* can never be re-admitted by a child.
|
|
2350
2410
|
*
|
|
2351
2411
|
* @example
|
|
@@ -2385,8 +2445,9 @@ var Scope = class Scope {
|
|
|
2385
2445
|
//#endregion
|
|
2386
2446
|
//#region src/core/scopes/ScopeManager.ts
|
|
2387
2447
|
/**
|
|
2388
|
-
* Registers the named filters a richer context reuses — immutable {@link Scope}s keyed by
|
|
2389
|
-
*
|
|
2448
|
+
* Registers the named filters a richer context reuses — immutable {@link Scope}s keyed by their
|
|
2449
|
+
* minted `id`, in insertion order, where `create` always mints and stores rather than overwriting,
|
|
2450
|
+
* and an observable `emitter` reports each change.
|
|
2390
2451
|
*
|
|
2391
2452
|
* @remarks
|
|
2392
2453
|
* - **Registry.** Scopes live in an insertion-ordered `Map` keyed by their minted `id`;
|
|
@@ -2395,11 +2456,11 @@ var Scope = class Scope {
|
|
|
2395
2456
|
* one up, and `scopes()` lists them in insertion order. (Unlike the name-keyed
|
|
2396
2457
|
* instruction registry, a scope's key is its minted `id`, so two scopes may share a
|
|
2397
2458
|
* `name`; `create` therefore always adds — it never overwrites.)
|
|
2398
|
-
* - **Removal.** `remove` drops one by id, or a batch — `true` only when
|
|
2459
|
+
* - **Removal.** `remove` drops one by id, or a batch — `true` only when every supplied id
|
|
2399
2460
|
* was removed; `clear` empties the registry.
|
|
2400
2461
|
* - **Observable.** The owned {@link emitter} ({@link ScopeManagerEventMap}) carries
|
|
2401
2462
|
* `create` (the created scope) / `remove` (the id) / `clear`. Every event is emitted
|
|
2402
|
-
* directly, strictly
|
|
2463
|
+
* directly, strictly after the map mutation completes; the emitter isolates a listener
|
|
2403
2464
|
* throw and routes it to its `error` handler (the `error` option), so a buggy observer can
|
|
2404
2465
|
* never corrupt a mutation.
|
|
2405
2466
|
*
|
|
@@ -2459,24 +2520,25 @@ var ScopeManager = class {
|
|
|
2459
2520
|
//#endregion
|
|
2460
2521
|
//#region src/core/ThinkSplitter.ts
|
|
2461
2522
|
/**
|
|
2462
|
-
* Feeds raw content deltas through a tiny stream-stateful state machine that routes
|
|
2463
|
-
*
|
|
2464
|
-
*
|
|
2465
|
-
* {@link import('./types.js').ProviderResult.thinking}.
|
|
2523
|
+
* Feeds raw content deltas through a tiny stream-stateful state machine that routes everything
|
|
2524
|
+
* inside a `<think>…</think>` span to `thinking` and returns everything outside it as clean
|
|
2525
|
+
* content, so a provider yields the answer alone and surfaces the reasoning as
|
|
2526
|
+
* {@link import('./types.js').ProviderResult.thinking}. A tag split across deltas is held until
|
|
2527
|
+
* disambiguated, `flush()` settles the stream end, and one splitter serves one stream.
|
|
2466
2528
|
*
|
|
2467
2529
|
* @remarks
|
|
2468
2530
|
* - **Cross-chunk tags.** A tag may arrive split across wire deltas (`'<thi'` then
|
|
2469
|
-
* `'nk>'`): any suffix of the pending text that is a strict
|
|
2470
|
-
* scanned for is
|
|
2531
|
+
* `'nk>'`): any suffix of the pending text that is a strict prefix of a tag being
|
|
2532
|
+
* scanned for is held back (neither surfaced nor routed) until the next delta — or
|
|
2471
2533
|
* `flush()` — disambiguates it. A held tag prefix that never completes is real
|
|
2472
2534
|
* content; a held close-tag prefix inside a span is thinking.
|
|
2473
|
-
* - **The
|
|
2474
|
-
*
|
|
2475
|
-
*
|
|
2476
|
-
* close therefore
|
|
2535
|
+
* - **The implicit leading open (the qwen3-template shape).** Some chat templates
|
|
2536
|
+
* pre-seed `<think>` into the prompt scaffold, so the wire stream begins
|
|
2537
|
+
* mid-reasoning and only a bare `</think>` appears. Before any tag event, a bare
|
|
2538
|
+
* close therefore reclassifies everything surfaced so far (plus the pre-close
|
|
2477
2539
|
* pending) as thinking — `content` is corrected retroactively (the already-returned
|
|
2478
2540
|
* prefix cannot be recalled, so `content` is the authoritative accumulation). The
|
|
2479
|
-
* rule is
|
|
2541
|
+
* rule is one-shot: after any tag event a bare `</think>` is plain text.
|
|
2480
2542
|
* - **Multiple spans** accumulate onto `thinking` in stream order. A nested-looking
|
|
2481
2543
|
* `<think>` inside an open span is thinking text (no nesting is tracked — the
|
|
2482
2544
|
* first `</think>` closes the span), matching how the models emit it.
|
|
@@ -2578,16 +2640,16 @@ var ThinkSplitter = class {
|
|
|
2578
2640
|
//#region src/core/factories.ts
|
|
2579
2641
|
/**
|
|
2580
2642
|
* Creates a conversation — a {@link ConversationInterface} grouping messages above a flat
|
|
2581
|
-
* message store it
|
|
2643
|
+
* message store it owns directly, with compaction into summarized sections, a regenerated
|
|
2582
2644
|
* rollup `summary`, on-demand `rehydrate`, and substring `search`, driven by a
|
|
2583
2645
|
* provider-agnostic {@link ConversationSummaryHandler} seam.
|
|
2584
2646
|
*
|
|
2585
2647
|
* @remarks
|
|
2586
2648
|
* Append turns through the conversation's own `add` (the live tail it owns); `view()` is the model input
|
|
2587
2649
|
* (each section as a summary message, then the live tail). `compact()` folds the older live
|
|
2588
|
-
* messages into a summarized {@link Section} and regenerates the rollup — it
|
|
2650
|
+
* messages into a summarized {@link Section} and regenerates the rollup — it requires
|
|
2589
2651
|
* a `summarize` (omitted ⇒ `compact()` throws a `ConversationError`); `keep` retains a recent
|
|
2590
|
-
* tail (default `DEFAULT_CONVERSATION_KEEP` — fold
|
|
2652
|
+
* tail (default `DEFAULT_CONVERSATION_KEEP` — fold all). `rehydrate(id)` / `search(query)` read
|
|
2591
2653
|
* the retained originals. Observable (`emitter` — `compact` / `summary` / `rehydrate`), wired
|
|
2592
2654
|
* through the reserved `on` option; the emitter isolates a listener throw and routes it to
|
|
2593
2655
|
* its `error` handler (the `error` option), so it can never corrupt a compaction.
|
|
@@ -2595,20 +2657,39 @@ var ThinkSplitter = class {
|
|
|
2595
2657
|
* @param options - Optional `id` / `on` hooks + the `summarize` seam + `keep` (see {@link ConversationOptions})
|
|
2596
2658
|
* @returns A working {@link ConversationInterface}
|
|
2597
2659
|
*
|
|
2598
|
-
* @example
|
|
2660
|
+
* @example Conversations & compaction
|
|
2599
2661
|
* ```ts
|
|
2600
|
-
* import type { ProviderInterface } from '@orkestrel/agent'
|
|
2601
2662
|
* import { createConversation } from '@orkestrel/agent'
|
|
2663
|
+
* import type { ProviderInterface } from '@orkestrel/agent'
|
|
2602
2664
|
*
|
|
2603
2665
|
* declare const provider: ProviderInterface // any concrete implementation supplied by the host app
|
|
2666
|
+
* // The summarizer seam — built from the provider by the runtime; core stays provider-agnostic.
|
|
2667
|
+
* // Append the instruction as the FINAL user turn: a chat model emits nothing when the prompt
|
|
2668
|
+
* // ends on an assistant turn, so a leading-system instruction is unreliable.
|
|
2604
2669
|
* const conversation = createConversation({
|
|
2605
|
-
* // Append the instruction as the FINAL user turn — a chat model emits nothing when the
|
|
2606
|
-
* // prompt ends on an assistant turn, so a leading-system instruction is unreliable.
|
|
2607
2670
|
* summarize: async (messages) =>
|
|
2608
|
-
* (
|
|
2671
|
+
* (
|
|
2672
|
+
* await provider.generate(
|
|
2673
|
+
* [
|
|
2674
|
+
* ...messages,
|
|
2675
|
+
* { id: 's', role: 'user', content: 'Summarize the conversation so far concisely.' },
|
|
2676
|
+
* ],
|
|
2677
|
+
* AbortSignal.timeout(30_000),
|
|
2678
|
+
* )
|
|
2679
|
+
* ).content,
|
|
2680
|
+
* keep: 2, // retain the two most recent turns verbatim on each compaction
|
|
2609
2681
|
* })
|
|
2610
|
-
* conversation.add(
|
|
2611
|
-
*
|
|
2682
|
+
* conversation.add([
|
|
2683
|
+
* { role: 'user', content: 'My name is Ada.' },
|
|
2684
|
+
* { role: 'assistant', content: 'Nice to meet you, Ada.' },
|
|
2685
|
+
* { role: 'user', content: 'What did I say my name was?' },
|
|
2686
|
+
* ])
|
|
2687
|
+
*
|
|
2688
|
+
* const section = await conversation.compact() // folds the older turns → a summarized section
|
|
2689
|
+
* conversation.view() // [<section summary message>, ...the retained recent tail] — the model input
|
|
2690
|
+
* conversation.summary // the regenerated rollup (a summary-of-summaries over all sections)
|
|
2691
|
+
* conversation.search('ada') // case-insensitive across sections' originals + the live tail
|
|
2692
|
+
* section && conversation.rehydrate(section.id) // the section's full original messages (a pure read)
|
|
2612
2693
|
* ```
|
|
2613
2694
|
*/
|
|
2614
2695
|
function createConversation(options) {
|
|
@@ -2616,21 +2697,22 @@ function createConversation(options) {
|
|
|
2616
2697
|
}
|
|
2617
2698
|
/**
|
|
2618
2699
|
* Creates a conversation registry — a {@link ConversationManagerInterface} holding
|
|
2619
|
-
* {@link ConversationInterface}s keyed by their `id
|
|
2700
|
+
* {@link ConversationInterface}s keyed by their `id`, in insertion order, with an active pointer:
|
|
2620
2701
|
* the id-keyed store over the conversation layer plus the `active` / `switch` seam the context
|
|
2621
|
-
* renders.
|
|
2702
|
+
* renders. `add` auto-activates the first conversation and flows the registry's default
|
|
2703
|
+
* `summarize` / `keep` into every conversation it creates.
|
|
2622
2704
|
*
|
|
2623
2705
|
* @remarks
|
|
2624
2706
|
* Starts empty; `add(input?)` mints a {@link ConversationInterface} (its `id` from the input
|
|
2625
2707
|
* or a random UUID), flowing the manager's default `summarize` / `keep` in unless the input
|
|
2626
2708
|
* overrides them, and stores it (an already-present `id` overwrites — last write wins) — and
|
|
2627
|
-
*
|
|
2709
|
+
* auto-activates the first one (a registry with conversations always has one `active`); a later
|
|
2628
2710
|
* `add` leaves `active` unchanged. `switch(id)` re-points `active` (an unknown `id` returns
|
|
2629
2711
|
* `undefined`, leaving `active` unchanged — lenient, never throws); `conversation(id)` /
|
|
2630
2712
|
* `conversations()` look up; `remove` (one or a batch) reports `true` only when every supplied id
|
|
2631
|
-
* was removed
|
|
2713
|
+
* was removed and clears `active` if it was a removed one; `clear` empties it and clears `active`.
|
|
2632
2714
|
* Event-free
|
|
2633
|
-
* (each conversation owns its own observable `emitter`). A conversation created with
|
|
2715
|
+
* (each conversation owns its own observable `emitter`). A conversation created with neither a
|
|
2634
2716
|
* manager default nor a per-`add` `summarize` cannot `compact` (it throws a `ConversationError`).
|
|
2635
2717
|
*
|
|
2636
2718
|
* @param options - Optional default `summarize` / `keep` (see {@link ConversationManagerOptions})
|
|
@@ -2651,7 +2733,7 @@ function createConversationManager(options) {
|
|
|
2651
2733
|
/**
|
|
2652
2734
|
* Creates the in-memory conversation store — a {@link ConversationStoreInterface} backed by a
|
|
2653
2735
|
* process-lifetime `Map` of {@link import('./types.js').ConversationSnapshot}s keyed by conversation
|
|
2654
|
-
* id, the
|
|
2736
|
+
* id, the default backing for the durable {@link ConversationManagerInterface.open} /
|
|
2655
2737
|
* {@link ConversationManagerInterface.save} seam. The exact twin of
|
|
2656
2738
|
* {@link import('@orkestrel/workspace').createMemoryWorkspaceStore}.
|
|
2657
2739
|
*
|
|
@@ -2659,10 +2741,10 @@ function createConversationManager(options) {
|
|
|
2659
2741
|
* A plain `Map` (the snapshot is already pure JSON, so no encoding is needed for the memory tier),
|
|
2660
2742
|
* the structural twin of {@link import('@orkestrel/workspace').createMemoryWorkspaceStore}.
|
|
2661
2743
|
* `get` / `set` / `delete` are async (the
|
|
2662
|
-
* same shape a durable backend fits);
|
|
2744
|
+
* same shape a durable backend fits); unlike a session store there is no idle-TTL / eviction — a
|
|
2663
2745
|
* persisted conversation lives until an explicit `delete`. Its driver-pluggable twin is
|
|
2664
2746
|
* {@link createDatabaseConversationStore} (the snapshot as one opaque JSON column over a `databases`
|
|
2665
|
-
* table) — for a
|
|
2747
|
+
* table) — for a durable store pass it a JSON / SQLite / IndexedDB driver, and it swaps in without
|
|
2666
2748
|
* touching the manager or the conversation. Hydration stays a manager concern: read a snapshot back
|
|
2667
2749
|
* and rebuild the live conversation through the `snapshot` option (re-supplying the live
|
|
2668
2750
|
* `summarize` / `keep`).
|
|
@@ -2684,23 +2766,24 @@ function createMemoryConversationStore() {
|
|
|
2684
2766
|
return new MemoryConversationStore();
|
|
2685
2767
|
}
|
|
2686
2768
|
/**
|
|
2687
|
-
* Creates a {@link DatabaseConversationStore} over any {@link DriverInterface}
|
|
2688
|
-
* driver-pluggable backing for the conversation persistence
|
|
2769
|
+
* Creates a {@link DatabaseConversationStore} over any {@link DriverInterface}, defaulting to
|
|
2770
|
+
* `createMemoryDriver()` — the durable, driver-pluggable backing for the conversation persistence
|
|
2771
|
+
* seam, holding each snapshot as one opaque JSON column and standing as the opt-in twin of
|
|
2689
2772
|
* {@link createMemoryConversationStore}. The exact twin of
|
|
2690
2773
|
* {@link import('@orkestrel/workspace').createDatabaseWorkspaceStore}.
|
|
2691
2774
|
*
|
|
2692
2775
|
* @remarks
|
|
2693
2776
|
* Builds a one-table database (`conversations`, keyed by `id`) over the supplied driver, the snapshot
|
|
2694
|
-
* held as
|
|
2777
|
+
* held as one opaque JSON column — the column map is `{ id; snapshot }` where `snapshot` is a
|
|
2695
2778
|
* `rawShape` (a JSON blob), exactly as
|
|
2696
2779
|
* {@link import('@orkestrel/workspace').createDatabaseWorkspaceStore} stores its snapshot. The
|
|
2697
|
-
* snapshot is already a
|
|
2698
|
-
*
|
|
2699
|
-
* {@link import('./validators.js').isConversationSnapshot}). The `driver`
|
|
2700
|
-
* {@link createMemoryDriver}, so the store
|
|
2780
|
+
* snapshot is already a complete, self-contained, pure-JSON payload, so storing it whole is lossless
|
|
2781
|
+
* and keeps the row type flat (the column reads back as `unknown`, narrowed on `get` by
|
|
2782
|
+
* {@link import('./validators.js').isConversationSnapshot}). The `driver` defaults to
|
|
2783
|
+
* {@link createMemoryDriver}, so the store also works in memory out of the box; pass a server
|
|
2701
2784
|
* `createJSONDriver` / `createSQLiteDriver` (or a browser IndexedDB driver) for a persistent one —
|
|
2702
2785
|
* the durability is the driver's job, the store engine is shared. It swaps in behind
|
|
2703
|
-
* {@link ConversationStoreInterface}
|
|
2786
|
+
* {@link ConversationStoreInterface} without touching the manager or the conversation.
|
|
2704
2787
|
*
|
|
2705
2788
|
* @param driver - The storage backend the snapshots persist to (defaults to {@link createMemoryDriver})
|
|
2706
2789
|
* @returns A {@link ConversationStoreInterface} over the driver
|
|
@@ -2755,7 +2838,7 @@ function createInstruction(input) {
|
|
|
2755
2838
|
* immutable instructions keyed by `name`, listed by descending `priority`.
|
|
2756
2839
|
*
|
|
2757
2840
|
* @remarks
|
|
2758
|
-
* Starts empty; `add` (one or a batch)
|
|
2841
|
+
* Starts empty; `add` (one or a batch) mints each `id` and overwrites a same-name
|
|
2759
2842
|
* instruction (last write wins); `instructions()` lists them sorted by descending
|
|
2760
2843
|
* `priority` (stable for ties); `open` / `render` are the build contract a richer
|
|
2761
2844
|
* context renders an instructions block with; `remove` (one or a batch) reports `true` only
|
|
@@ -2786,9 +2869,9 @@ function createInstructionManager(options) {
|
|
|
2786
2869
|
* per-category allow-lists, the `id` minted at construction.
|
|
2787
2870
|
*
|
|
2788
2871
|
* @remarks
|
|
2789
|
-
* Each list is
|
|
2790
|
-
*
|
|
2791
|
-
* tighter child by set-
|
|
2872
|
+
* Each list is three-way: `undefined` ⇒ no constraint on that category (all pass), `[]` ⇒
|
|
2873
|
+
* none pass, a non-empty list ⇒ only the listed keys pass. `narrow(config)` composes a
|
|
2874
|
+
* tighter child by set-intersection (an `undefined` side imposing no constraint). Stored
|
|
2792
2875
|
* immutable — never mutated after creation (`narrow` returns a new scope).
|
|
2793
2876
|
*
|
|
2794
2877
|
* @param input - `name` (required) and the optional `instructions` / `tools` / `files`
|
|
@@ -2834,19 +2917,20 @@ function createScopeManager(options) {
|
|
|
2834
2917
|
return new ScopeManager(options);
|
|
2835
2918
|
}
|
|
2836
2919
|
/**
|
|
2837
|
-
* Creates a richer turn context — an {@link AgentContextInterface} assembling a provider
|
|
2838
|
-
*
|
|
2839
|
-
* the conversation
|
|
2920
|
+
* Creates a richer turn context — an {@link AgentContextInterface} assembling a provider request
|
|
2921
|
+
* from the optional system prompt, the instruction registry, the workspace registry (the only
|
|
2922
|
+
* document channel), the conversation registry that is its `messages` source, the tool registry,
|
|
2923
|
+
* and the active scope, which `build()` folds into the next turn's input.
|
|
2840
2924
|
*
|
|
2841
2925
|
* @remarks
|
|
2842
2926
|
* `system` is the optional system prompt; `tools` / `instructions` / `workspaces` are pre-built
|
|
2843
|
-
* managers to reuse (empty ones are created when omitted, so `context.workspaces` is
|
|
2927
|
+
* managers to reuse (empty ones are created when omitted, so `context.workspaces` is always
|
|
2844
2928
|
* present); `scope` is the initial active filter (`undefined` ⇒ no filtering, changeable afterwards
|
|
2845
2929
|
* through `context.apply(...)`). The `messages` store is always fresh. `build()` folds the scoped
|
|
2846
|
-
* instructions —
|
|
2930
|
+
* instructions — plus the active workspace's scope-filtered text files (fenced) — into one leading
|
|
2847
2931
|
* `system` message and appends the scoped conversation (attaching the active workspace's
|
|
2848
2932
|
* scope-filtered image files' `base64` payload to the last user message), built fresh each call; the active
|
|
2849
|
-
* workspace is the
|
|
2933
|
+
* workspace is the sole document/image context. Tools are advertised structurally (through
|
|
2850
2934
|
* `tools.definitions()`, scope-filtered by the loop), never serialized into the prompt.
|
|
2851
2935
|
*
|
|
2852
2936
|
* @param options - Optional `system` / `tools` / `instructions` / `workspaces` / `scope`
|
|
@@ -2873,10 +2957,10 @@ function createAgentContext(options) {
|
|
|
2873
2957
|
* `generate` and a live `stream`.
|
|
2874
2958
|
*
|
|
2875
2959
|
* @remarks
|
|
2876
|
-
* One private loop drives the turn; `generate`
|
|
2960
|
+
* One private loop drives the turn; `generate` drains the same stream `stream`
|
|
2877
2961
|
* exposes, so they can never diverge. Each turn is bounded by one cancel folded from
|
|
2878
2962
|
* `signal` + `timeout` + `budget` (through `AbortSignal.any`) — any trip (or `abort()`)
|
|
2879
|
-
* commits a
|
|
2963
|
+
* commits a partial result (the stream's `result` resolves on a cancel, rejects only
|
|
2880
2964
|
* on a genuine provider / tool error). The `scheduler` paces between turns; tool
|
|
2881
2965
|
* iteration is capped at `limit` (default `DEFAULT_AGENT_LIMIT`). Tools are advertised
|
|
2882
2966
|
* structurally through `context.tools.definitions()`. Two observation surfaces: the
|
|
@@ -2912,18 +2996,19 @@ function createAgent(provider, options) {
|
|
|
2912
2996
|
return new Agent(provider, options);
|
|
2913
2997
|
}
|
|
2914
2998
|
/**
|
|
2915
|
-
* Creates a stream-stateful `<think>` separator — a {@link ThinkSplitterInterface} that
|
|
2916
|
-
* splits a thinking model's in-content `<think>…</think>` reasoning spans away from
|
|
2917
|
-
*
|
|
2918
|
-
*
|
|
2999
|
+
* Creates a fresh stream-stateful `<think>` separator — a {@link ThinkSplitterInterface} that
|
|
3000
|
+
* splits a thinking model's in-content `<think>…</think>` reasoning spans away from the answer,
|
|
3001
|
+
* delta by delta, so a provider yields clean content alone and surfaces the accumulated
|
|
3002
|
+
* reasoning as {@link import('./types.js').ProviderResult.thinking}. One splitter serves one
|
|
3003
|
+
* stream.
|
|
2919
3004
|
*
|
|
2920
3005
|
* @remarks
|
|
2921
3006
|
* Feed each raw wire delta through `split(delta)` (it returns the clean content to
|
|
2922
3007
|
* surface — possibly `''` mid-think) and settle the stream end with `flush()` (a held
|
|
2923
|
-
* partial open tag that never completed returns as final content; an
|
|
2924
|
-
* span lands on `thinking`). Tags split
|
|
3008
|
+
* partial open tag that never completed returns as final content; an unclosed think
|
|
3009
|
+
* span lands on `thinking`). Tags split across deltas are held back until
|
|
2925
3010
|
* disambiguated, multiple spans accumulate in order, and a nested-looking `<think>`
|
|
2926
|
-
* inside an open span is thinking text. One splitter serves
|
|
3011
|
+
* inside an open span is thinking text. One splitter serves one stream — create
|
|
2927
3012
|
* a fresh one per provider call.
|
|
2928
3013
|
*
|
|
2929
3014
|
* @returns A fresh {@link ThinkSplitterInterface} (state empty, outside any span)
|
|
@@ -2950,7 +3035,7 @@ function createThinkSplitter() {
|
|
|
2950
3035
|
* Write and read are decoupled, so the producer never waits for a consumer: an agent's eager
|
|
2951
3036
|
* pump writes each chunk into one, which is why a run's `result` settles whether or not the
|
|
2952
3037
|
* live events are drained. A value pushed at an already-parked consumer is delivered, buffered
|
|
2953
|
-
* values are yielded before the end is reported, and the
|
|
3038
|
+
* values are yielded before the end is reported, and the first failure wins.
|
|
2954
3039
|
*
|
|
2955
3040
|
* @typeParam T - The value type the channel carries
|
|
2956
3041
|
* @returns A fresh, empty {@link ChannelInterface}
|
|
@@ -2976,11 +3061,11 @@ function createChannel() {
|
|
|
2976
3061
|
* to the configured default when none match.
|
|
2977
3062
|
*
|
|
2978
3063
|
* @remarks
|
|
2979
|
-
* `rules` are evaluated in order — the
|
|
2980
|
-
* rule
|
|
3064
|
+
* `rules` are evaluated in order — the first whose `match` is true decides (a matched
|
|
3065
|
+
* rule allows unless its `allowed` is explicitly `false`). When no rule matches, the
|
|
2981
3066
|
* `fallback` decides; it defaults to `{ zone: DEFAULT_AUTHORITY_ZONE, allowed: true }`
|
|
2982
|
-
* (allow-unmatched — a rules list of denials acts as a
|
|
2983
|
-
* `allowed: false` `fallback` to flip the gate to deny-by-default (an
|
|
3067
|
+
* (allow-unmatched — a rules list of denials acts as a denylist). Pass an
|
|
3068
|
+
* `allowed: false` `fallback` to flip the gate to deny-by-default (an allowlist). Wire
|
|
2984
3069
|
* the result into `createAgent` through `AgentOptions.authority`: a denied call is fed back
|
|
2985
3070
|
* to the model as a denial `ToolResult` (not executed, no budget cost), so the model
|
|
2986
3071
|
* can react. Synchronous — `evaluate` returns the verdict directly.
|
|
@@ -3010,7 +3095,7 @@ function createAuthority(options) {
|
|
|
3010
3095
|
*
|
|
3011
3096
|
* @remarks
|
|
3012
3097
|
* `providers` is required; `tools` / `authorities` / `schedulers` are optional pools.
|
|
3013
|
-
* The accessors (`provider` / `tool` / `authority` / `scheduler`)
|
|
3098
|
+
* The accessors (`provider` / `tool` / `authority` / `scheduler`) throw an
|
|
3014
3099
|
* {@link import('./errors.js').AgentError} carrying `code: 'REGISTRY'` and the message
|
|
3015
3100
|
* `unknown <category>: <name>` on an unregistered name — a misconfigured or crash-restored
|
|
3016
3101
|
* job fails loudly rather than running with a missing dependency. `build(input, signal)`
|
|
@@ -3040,7 +3125,7 @@ function createAgentRegistry(options) {
|
|
|
3040
3125
|
}
|
|
3041
3126
|
/**
|
|
3042
3127
|
* Creates a durable, bounded-concurrency agent-job queue — a {@link QueueInterface} over
|
|
3043
|
-
* serializable {@link AgentJobInput}s that
|
|
3128
|
+
* serializable {@link AgentJobInput}s that composes `createQueue`: each job is rehydrated
|
|
3044
3129
|
* through the `registry` into a live {@link AgentInterface}, run to its {@link AgentResult},
|
|
3045
3130
|
* and subjected to the partial-as-configurable-failure policy.
|
|
3046
3131
|
*
|
|
@@ -3053,9 +3138,9 @@ function createAgentRegistry(options) {
|
|
|
3053
3138
|
* (for example `createMemoryQueueStore` / `createDatabaseQueueStore`) persists outstanding
|
|
3054
3139
|
* jobs; `restore()` re-enqueues them after a restart and the `registry` rehydrates the
|
|
3055
3140
|
* live pieces from the names — so a job survives a crash.
|
|
3056
|
-
* - **Partial policy.** A partial result
|
|
3141
|
+
* - **Partial policy.** A partial result throws an
|
|
3057
3142
|
* {@link import('./errors.js').AgentJobError} by default, so a job cancelled by its
|
|
3058
|
-
* attempt deadline / a queue abort
|
|
3143
|
+
* attempt deadline / a queue abort retries while attempts remain; `partial: true`
|
|
3059
3144
|
* resolves the partial as success instead.
|
|
3060
3145
|
* - **Cancellation threads through.** The handler passes `context.signal` into
|
|
3061
3146
|
* `registry.build`, so a queue `abort()` or a per-attempt timeout cancels the in-flight
|
|
@@ -3088,21 +3173,21 @@ function createAgentQueue(options) {
|
|
|
3088
3173
|
}
|
|
3089
3174
|
/**
|
|
3090
3175
|
* Creates an agent-job runner — a {@link RunnerInterface} over serializable
|
|
3091
|
-
* {@link AgentJobInput}s that
|
|
3092
|
-
*
|
|
3093
|
-
*
|
|
3176
|
+
* {@link AgentJobInput}s that composes `createRunner` (one-shot, ordered, fail-fast), each unit
|
|
3177
|
+
* rehydrated through the `registry` and subjected to the partial policy. The runner also carries
|
|
3178
|
+
* sub-agent fan-out: a parent job's handler can `controller.spawn(childJob)`.
|
|
3094
3179
|
*
|
|
3095
3180
|
* @remarks
|
|
3096
3181
|
* - **Composes the substrate (no new engine).** Bounded `concurrency`, `retries`, the
|
|
3097
3182
|
* per-attempt `timeout`, ordered results, and fail-fast are all the backing Runner's;
|
|
3098
3183
|
* the handler adds only rehydration + the partial policy.
|
|
3099
3184
|
* - **Sub-agent fan-out.** Each unit's handler receives a `ControllerInterface` whose
|
|
3100
|
-
* `spawn(childJob)` launches a
|
|
3185
|
+
* `spawn(childJob)` launches a child agent job through the same bounded queue (the
|
|
3101
3186
|
* child's result joins the run after the declared units, in spawn order). On a bounded
|
|
3102
|
-
* runner,
|
|
3187
|
+
* runner, fan out and return — do not inline-`await` a spawn from within the handler (a
|
|
3103
3188
|
* slot-holding handler awaiting its own spawn can deadlock; see `ControllerInterface`).
|
|
3104
3189
|
* - **Partial policy + cancellation.** Same as `createAgentQueue`: a partial result
|
|
3105
|
-
*
|
|
3190
|
+
* throws by default (the run's fail-fast engages), `partial: true` resolves it; the
|
|
3106
3191
|
* handler threads `controller.signal` into `registry.build`, so a runner abort / a
|
|
3107
3192
|
* per-attempt timeout cancels the agent.
|
|
3108
3193
|
*
|