@orkestrel/agent 0.0.10 → 0.0.12

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.
@@ -1,10 +1,12 @@
1
- import { isArray, isNumber, isRecord, isString, rawShape, stringShape } from "@orkestrel/contract";
1
+ import { isArray, isRecord, isString, rawShape, stringShape } from "@orkestrel/contract";
2
2
  import { createDatabase, createMemoryDriver } from "@orkestrel/database";
3
3
  import { createQueue } from "@orkestrel/queue";
4
4
  import { createDeferred, createRunner } from "@orkestrel/workflow";
5
5
  import { createAbort } from "@orkestrel/abort";
6
6
  import { createTimeout } from "@orkestrel/timeout";
7
7
  import { Emitter } from "@orkestrel/emitter";
8
+ import { ToolManager, isToolCall } from "@orkestrel/tool";
9
+ import { WorkspaceManager, isBinary, isText } from "@orkestrel/workspace";
8
10
  import { createTokenBudget } from "@orkestrel/budget";
9
11
  //#region src/core/constants.ts
10
12
  /**
@@ -90,53 +92,6 @@ var MESSAGE_TOKEN_OVERHEAD = 4;
90
92
  * exact count.
91
93
  */
92
94
  var IMAGE_TOKEN_ESTIMATE = 512;
93
- /**
94
- * The extension→language table {@link import('./helpers.js').inferLanguage} reads to
95
- * map a file path's extension to a fenced-code language tag. Covers the common source /
96
- * markup / data extensions; an unlisted extension falls back to `'text'`.
97
- */
98
- var EXTENSION_TO_LANGUAGE = Object.freeze({
99
- ts: "typescript",
100
- tsx: "typescript",
101
- js: "javascript",
102
- jsx: "javascript",
103
- mjs: "javascript",
104
- cjs: "javascript",
105
- json: "json",
106
- md: "markdown",
107
- html: "html",
108
- htm: "html",
109
- css: "css",
110
- scss: "scss",
111
- sass: "sass",
112
- less: "less",
113
- vue: "vue",
114
- svelte: "svelte",
115
- py: "python",
116
- rb: "ruby",
117
- rs: "rust",
118
- go: "go",
119
- java: "java",
120
- kt: "kotlin",
121
- swift: "swift",
122
- c: "c",
123
- cpp: "cpp",
124
- h: "c",
125
- hpp: "cpp",
126
- cs: "csharp",
127
- php: "php",
128
- sql: "sql",
129
- sh: "bash",
130
- bash: "bash",
131
- zsh: "bash",
132
- ps1: "powershell",
133
- yaml: "yaml",
134
- yml: "yaml",
135
- toml: "toml",
136
- xml: "xml",
137
- svg: "xml",
138
- txt: "text"
139
- });
140
95
  //#endregion
141
96
  //#region src/core/errors.ts
142
97
  /**
@@ -260,45 +215,6 @@ function isConversationError(value) {
260
215
  return value instanceof ConversationError;
261
216
  }
262
217
  /**
263
- * An error thrown by the in-memory {@link import('./workspaces/Workspace.js').Workspace} edit
264
- * surface.
265
- *
266
- * @remarks
267
- * Carries a {@link WorkspaceErrorCode} and an optional `context` bag naming the offending
268
- * path / range. Thrown for a text-only operation aimed at an image file (`MODALITY` — a
269
- * ranged read / write, `prepend`, or `append`), an invalid `search` / `replace` regular
270
- * expression (`PATTERN`), and a structurally invalid ranged-write {@link import('./types.js').Range}
271
- * (`RANGE` — inverted, or a sub-1 line / column).
272
- */
273
- var WorkspaceError = class extends Error {
274
- code;
275
- context;
276
- constructor(code, message, context) {
277
- super(message);
278
- this.name = "WorkspaceError";
279
- this.code = code;
280
- if (context !== void 0) this.context = context;
281
- }
282
- };
283
- /**
284
- * Narrow an unknown caught value to a {@link WorkspaceError}.
285
- *
286
- * @param value - The value to test (typically a `catch` binding)
287
- * @returns `true` when `value` is a {@link WorkspaceError}
288
- *
289
- * @example
290
- * ```ts
291
- * try {
292
- * workspace.prepend('icon.png', '// header')
293
- * } catch (error) {
294
- * if (isWorkspaceError(error) && error.code === 'MODALITY') skipBinary()
295
- * }
296
- * ```
297
- */
298
- function isWorkspaceError(value) {
299
- return value instanceof WorkspaceError;
300
- }
301
- /**
302
218
  * Thrown synchronously by an {@link AgentInterface}'s `stream()` when a concurrent run would
303
219
  * corrupt SHARED per-agent accounting — carries a machine-readable `code`.
304
220
  *
@@ -551,7 +467,7 @@ var Conversation = class {
551
467
  * The registry of {@link Conversation}s keyed by `id`, in insertion order, WITH an active pointer
552
468
  * — the §9 store over the conversation layer PLUS the `active` / `switch` seam the
553
469
  * {@link import('../AgentContext.js').AgentContext} renders. Event-free (a registry, like
554
- * {@link import('../workspaces/WorkspaceManager.js').WorkspaceManager}); the observability lives
470
+ * {@link import('@orkestrel/workspace').WorkspaceManager}); the observability lives
555
471
  * on each {@link Conversation}.
556
472
  *
557
473
  * @remarks
@@ -666,30 +582,6 @@ var ConversationManager = class {
666
582
  //#endregion
667
583
  //#region src/core/helpers.ts
668
584
  /**
669
- * Infer a fenced-code language tag from a file path's extension — what a workspace text file
670
- * (or the {@link fencedFile} renderer) renders its content block as.
671
- *
672
- * @remarks
673
- * Reads the extension after the last `.` (case-insensitive) and maps it through a
674
- * fixed extension→language table. An unknown extension, or a path with no extension,
675
- * falls back to `'text'` (a safe, language-agnostic fence). Total — never throws.
676
- *
677
- * @param path - The document's file path (e.g. `'src/main.ts'`)
678
- * @returns The inferred language tag (e.g. `'typescript'`), or `'text'` when unknown
679
- *
680
- * @example
681
- * ```ts
682
- * inferLanguage('src/main.ts') // 'typescript'
683
- * inferLanguage('README.md') // 'markdown'
684
- * inferLanguage('LICENSE') // 'text'
685
- * ```
686
- */
687
- function inferLanguage(path) {
688
- const dot = path.lastIndexOf(".");
689
- if (dot === -1) return "text";
690
- return EXTENSION_TO_LANGUAGE[path.slice(dot + 1).toLowerCase()] ?? "text";
691
- }
692
- /**
693
585
  * Filter a list of items by a {@link import('./types.js').ScopeInterface} allow-list of
694
586
  * keys — the pure, total set-membership primitive the context's build step and the agent
695
587
  * loop's tool-advertise step apply a scope through.
@@ -850,201 +742,22 @@ function handleAgentRunnerJob(registry, allowPartial, controller) {
850
742
  return settleAgentJob(registry.build(controller.input, controller.signal), allowPartial);
851
743
  }
852
744
  /**
853
- * Whether a {@link FileContent} is the TEXT arm — the narrowing guard for the text-vs-binary
854
- * union (AGENTS §14: narrow an untyped arm via a guard, never an `as`).
855
- *
856
- * @remarks
857
- * Tests `'text' in content` structurally — there is no `modality` discriminant. A `true`
858
- * narrows `content` to `{ text: string; language: string }`, unlocking `.text` / `.language`.
859
- * Total — never throws.
860
- *
861
- * @param content - The file content to test
862
- * @returns `true` when `content` is the text arm (carries `text` + `language`)
863
- *
864
- * @example
865
- * ```ts
866
- * if (isText(file.content)) file.content.text // the literal text + .language
867
- * ```
868
- */
869
- function isText(content) {
870
- return "text" in content;
871
- }
872
- /**
873
- * Whether a {@link FileContent} is the BINARY arm — the narrowing guard for the text-vs-binary
874
- * union (AGENTS §14: narrow an untyped arm via a guard, never an `as`).
875
- *
876
- * @remarks
877
- * Tests `'data' in content` structurally — there is no `modality` discriminant. A `true`
878
- * narrows `content` to `{ data: string; mime: BinaryMIME }`, unlocking `.data` / `.mime`. An
879
- * image is a binary whose `mime` starts with `image/` ({@link isImage}). Total — never throws.
880
- *
881
- * @param content - The file content to test
882
- * @returns `true` when `content` is the binary arm (carries base64 `data` + `mime`)
883
- *
884
- * @example
885
- * ```ts
886
- * if (isBinary(file.content)) file.content.data // the base64 payload + .mime
887
- * ```
888
- */
889
- function isBinary(content) {
890
- return "data" in content;
891
- }
892
- /**
893
- * Whether a {@link FileContent} is an IMAGE — a {@link isBinary} arm whose `mime` is an
894
- * `image/*` type (an image is just a binary with an image MIME).
895
- *
896
- * @remarks
897
- * Narrows to the binary arm first, then checks the `image/` MIME prefix — so a future
898
- * non-image binary (a PDF, `'application/pdf'`) is binary but NOT an image. Total — never
899
- * throws.
900
- *
901
- * @param content - The file content to test
902
- * @returns `true` when `content` is a binary arm with an `image/*` MIME
903
- *
904
- * @example
905
- * ```ts
906
- * isImage({ data: '<base64>', mime: 'image/png' }) // true
907
- * isImage({ text: 'hi', language: 'text' }) // false
908
- * ```
909
- */
910
- function isImage(content) {
911
- return isBinary(content) && content.mime.startsWith("image/");
912
- }
913
- /**
914
- * Whether an `unknown` is structurally a {@link FileInterface} record — the per-file step of the
915
- * {@link isWorkspaceSnapshot} read-boundary narrow (AGENTS §14: narrow an untrusted storage read
916
- * via a guard, never an `as`).
917
- *
918
- * @remarks
919
- * A total guard (it NEVER throws — adversarial input returns `false`). It checks the file's SHAPE:
920
- * a record with a `string` `path`, a `string` `state`, `number` `size` / `lines`, and a `content`
921
- * that is EITHER the TEXT arm (`{ text: string; language: string }`) OR the BINARY arm
922
- * (`{ data: string; mime: string }`) — the tagless {@link FileContent} union, told apart
923
- * structurally exactly as {@link isText} / {@link isBinary} do (no `modality` discriminant). Enough
924
- * to safely impose the {@link FileInterface} type at a storage boundary WITHOUT a cast; the `mime`
925
- * is left as a broad `string` here (an open {@link BinaryMIME}, so any storage-read MIME string is
926
- * accepted defensively rather than rejected against the current literal set).
927
- *
928
- * @param value - The value to test (one element of a snapshot's opaque `files` array)
929
- * @returns `true` when `value` has the structural shape of a {@link FileInterface}
930
- *
931
- * @example
932
- * ```ts
933
- * isFile({ path: 'a.ts', content: { text: 'x', language: 'typescript' }, state: 'created', size: 1, lines: 1 }) // true
934
- * isFile({ path: 'a.png', content: { data: 'AAAA', mime: 'image/png' }, state: 'created', size: 3, lines: 0 }) // true
935
- * isFile({ path: 'a.ts' }) // false (missing content / state / size / lines)
936
- * ```
937
- */
938
- function isFile(value) {
939
- if (!isRecord(value)) return false;
940
- if (!isString(value.path) || !isString(value.state)) return false;
941
- if (!isNumber(value.size) || !isNumber(value.lines)) return false;
942
- if (!isRecord(value.content)) return false;
943
- const text = isString(value.content.text) && isString(value.content.language);
944
- const binary = isString(value.content.data) && isString(value.content.mime);
945
- return text || binary;
946
- }
947
- /**
948
- * Narrow an `unknown` to a {@link WorkspaceSnapshot} — the AGENTS §14 boundary guard for an
949
- * UNTRUSTED snapshot read (a storage row a
950
- * {@link import('./workspaces/stores/DatabaseWorkspaceStore.js').DatabaseWorkspaceStore} reads back
951
- * from its opaque JSON column, a snapshot loaded from disk).
952
- *
953
- * @remarks
954
- * A total guard (it NEVER throws — adversarial input returns `false`). It checks the snapshot's
955
- * SHAPE: a `string` `id` and a `files` array EVERY element of which is a valid {@link FileInterface}
956
- * record ({@link isFile}) — enough to safely impose the {@link WorkspaceSnapshot} type at a storage
957
- * boundary WITHOUT a cast. The structural twin of
958
- * the analogous `isWorkflowSnapshot` in `@orkestrel/workflow`. A malformed blob (a non-record, a
959
- * missing / non-string `id`, a non-array `files`, or any malformed file element) resolves `false`,
960
- * so a {@link import('./workspaces/stores/DatabaseWorkspaceStore.js').DatabaseWorkspaceStore} read
961
- * yields `undefined` rather than a broken workspace.
962
- *
963
- * @param value - The value to test (an opaque storage read)
964
- * @returns `true` when `value` has the structural shape of a {@link WorkspaceSnapshot}
965
- *
966
- * @example
967
- * ```ts
968
- * isWorkspaceSnapshot({ id: 'w1', files: [] }) // true
969
- * isWorkspaceSnapshot({ id: 'w1', files: 'nope' }) // false
970
- * isWorkspaceSnapshot({ files: [] }) // false (missing id)
971
- * ```
972
- */
973
- function isWorkspaceSnapshot(value) {
974
- return isRecord(value) && isString(value.id) && isArray(value.files) && value.files.every(isFile);
975
- }
976
- /**
977
- * Whether an `unknown` is structurally a {@link ToolCall} record — the per-call step of the
978
- * {@link isMessage} read-boundary narrow (AGENTS §14: narrow an untrusted storage read via a
979
- * guard, never an `as`).
980
- *
981
- * @remarks
982
- * A total guard (it NEVER throws — adversarial input returns `false`). It checks the call's
983
- * SHAPE: a record with a `string` `id`, a `string` `name`, and a record `arguments` — the real
984
- * {@link ToolCall} shape a restored assistant turn replays to a provider. This is the ASI06
985
- * fail-CLOSED element check: a tampered persisted call (`null`, a bare string, a non-record
986
- * `arguments`) fails the guard, so {@link isMessage} — and through it
987
- * {@link isConversationSnapshot} — rejects the whole snapshot and a poisoned store row reads
988
- * back as ABSENT instead of replaying a malformed call into a chat template.
989
- *
990
- * @param value - The value to test (one element of an assistant message's `calls`)
991
- * @returns `true` when `value` has the structural shape of a {@link ToolCall}
992
- *
993
- * @example
994
- * ```ts
995
- * isToolCall({ id: 'c1', name: 'search', arguments: { q: 'acme' } }) // true
996
- * isToolCall({ id: 'c1', name: 'search' }) // false (missing arguments)
997
- * isToolCall({ id: 'c1', name: 123, arguments: {} }) // false (non-string name)
998
- * ```
999
- */
1000
- function isToolCall(value) {
1001
- if (!isRecord(value)) return false;
1002
- return isString(value.id) && isString(value.name) && isRecord(value.arguments);
1003
- }
1004
- /**
1005
- * Project a {@link ToolResult} into the MCP `CallToolResult` shape — a top-level `error`
1006
- * maps to a single `isError: true` text block (the failure reason), otherwise the `value`
1007
- * is JSON-stringified into a single text block with no `isError`.
1008
- *
1009
- * @param result - The {@link ToolResult} to project (as returned by {@link import('./tools/ToolManager.js').ToolManager.execute})
1010
- * @returns The equivalent {@link ToolCallResult}
1011
- *
1012
- * @example
1013
- * ```ts
1014
- * buildToolResult({ id: 'c1', name: 'search', error: 'max depth' })
1015
- * // { content: [{ type: 'text', text: 'max depth' }], isError: true }
1016
- * buildToolResult({ id: 'c1', name: 'search', value: { count: 1 } })
1017
- * // { content: [{ type: 'text', text: '{"count":1}' }] }
1018
- * ```
1019
- */
1020
- function buildToolResult(result) {
1021
- if (result.error !== void 0) return {
1022
- content: [{
1023
- type: "text",
1024
- text: result.error
1025
- }],
1026
- isError: true
1027
- };
1028
- return { content: [{
1029
- type: "text",
1030
- text: JSON.stringify(result.value)
1031
- }] };
1032
- }
1033
- /**
1034
745
  * Whether an `unknown` is structurally a {@link MessageInterface} record — the per-message step of
1035
746
  * the {@link isConversationSnapshot} read-boundary narrow (AGENTS §14: narrow an untrusted storage
1036
- * read via a guard, never an `as`). The conversation analogue of {@link isFile}.
747
+ * read via a guard, never an `as`). The conversation analogue of
748
+ * {@link import('@orkestrel/workspace').isFile}.
1037
749
  *
1038
750
  * @remarks
1039
751
  * A total guard (it NEVER throws — adversarial input returns `false`). It checks the message's
1040
752
  * SHAPE: a record with a `string` `id`, a `string` `role`, a `string` `content`, and — WHEN present
1041
- * — a `calls` array EVERY element of which is a valid {@link ToolCall} ({@link isToolCall} — the
753
+ * — a `calls` array EVERY element of which is a valid
754
+ * {@link import('@orkestrel/tool').ToolCall} ({@link isToolCall} — the
1042
755
  * ASI06 fail-closed deepening: a tampered `calls` element rejects the message, so the snapshot
1043
756
  * reads back as absent rather than replaying a malformed call) and an `images` that is an array
1044
757
  * (an absent optional passes). The `role` is left as a broad `string` here (an open
1045
758
  * {@link import('./types.js').MessageRole}, so any storage-read role string is accepted
1046
- * defensively rather than rejected against the current literal set) — exactly as {@link isFile}
1047
- * accepts a broad `state` / `mime`. Enough to safely impose the {@link MessageInterface} type at
759
+ * defensively rather than rejected against the current literal set). Enough to safely impose the
760
+ * {@link MessageInterface} type at
1048
761
  * a storage boundary WITHOUT a cast.
1049
762
  *
1050
763
  * @param value - The value to test (one element of a snapshot's `messages` / a section's `messages`)
@@ -1095,7 +808,7 @@ function isSection(value) {
1095
808
  * UNTRUSTED snapshot read (a storage row a
1096
809
  * {@link import('./conversations/stores/DatabaseConversationStore.js').DatabaseConversationStore}
1097
810
  * reads back from its opaque JSON column, a snapshot loaded from disk). The EXACT analogue of
1098
- * {@link isWorkspaceSnapshot}.
811
+ * {@link import('@orkestrel/workspace').isWorkspaceSnapshot}.
1099
812
  *
1100
813
  * @remarks
1101
814
  * A total guard (it NEVER throws — adversarial input returns `false`). It checks the snapshot's
@@ -1104,7 +817,7 @@ function isSection(value) {
1104
817
  * {@link SectionInterface} ({@link isSection}), and a `messages` array EVERY element of which is a
1105
818
  * valid {@link MessageInterface} ({@link isMessage}) — enough to safely impose the
1106
819
  * {@link ConversationSnapshot} type at a storage boundary WITHOUT a cast. The structural twin of
1107
- * {@link isWorkspaceSnapshot}. A malformed blob (a non-record, a missing / non-string `id`, a
820
+ * {@link import('@orkestrel/workspace').isWorkspaceSnapshot}. A malformed blob (a non-record, a missing / non-string `id`, a
1108
821
  * non-string `summary` when present, a non-array `sections` / `messages`, or any malformed
1109
822
  * element) resolves `false`, so a
1110
823
  * {@link import('./conversations/stores/DatabaseConversationStore.js').DatabaseConversationStore}
@@ -1129,273 +842,6 @@ function isConversationSnapshot(value) {
1129
842
  return isArray(value.messages) && value.messages.every(isMessage);
1130
843
  }
1131
844
  /**
1132
- * Compute the byte size of a {@link FileContent} — the `size` a {@link FileInterface} derives
1133
- * once when built.
1134
- *
1135
- * @remarks
1136
- * Dispatches on {@link isText}: a text arm is its UTF-8 byte length (via `new
1137
- * TextEncoder().encode(text).length` — the standard Web/Node API, so a multi-byte
1138
- * character like `'é'` or `'😀'` counts as its real encoded bytes, NOT its character
1139
- * count); a binary arm is the decoded payload byte length of its base64 `data` (via
1140
- * {@link decodedSize}, computed arithmetically — no `atob` / `Buffer`). Total — never throws.
1141
- *
1142
- * @param content - The file content to size
1143
- * @returns The byte size (UTF-8 bytes for text; decoded payload bytes for binary)
1144
- *
1145
- * @example
1146
- * ```ts
1147
- * computeSize({ text: 'café', language: 'text' }) // 5 (é is two bytes)
1148
- * computeSize({ data: 'AAAA', mime: 'image/png' }) // 3
1149
- * ```
1150
- */
1151
- function computeSize(content) {
1152
- if (isText(content)) return new TextEncoder().encode(content.text).length;
1153
- return decodedSize(content.data);
1154
- }
1155
- /**
1156
- * Count the lines of a {@link FileContent} — the `lines` a {@link FileInterface} derives once
1157
- * when built.
1158
- *
1159
- * @remarks
1160
- * A text arm's line count is `0` for the empty string, otherwise one more than the
1161
- * number of newline (`\n`) separators it contains — so `'a'` is one line, `'a\nb'` is two,
1162
- * and a trailing newline `'a\n'` counts the empty final line as two. A binary arm has no
1163
- * lines and returns `0`. Total — never throws.
1164
- *
1165
- * @param content - The file content to count lines for
1166
- * @returns The line count (text line count; `0` for a binary arm or empty text)
1167
- *
1168
- * @example
1169
- * ```ts
1170
- * countLines({ text: '', language: 'text' }) // 0
1171
- * countLines({ text: 'a\nb\nc', language: 'text' }) // 3
1172
- * countLines({ data: 'AAAA', mime: 'image/png' }) // 0
1173
- * ```
1174
- */
1175
- function countLines(content) {
1176
- if (!isText(content)) return 0;
1177
- if (content.text.length === 0) return 0;
1178
- let count = 1;
1179
- for (const character of content.text) if (character === "\n") count += 1;
1180
- return count;
1181
- }
1182
- /**
1183
- * Compute the decoded byte length of a base64 string ARITHMETICALLY — the image-payload
1184
- * sizing primitive {@link computeSize} uses, with no `atob` / `Buffer` decode.
1185
- *
1186
- * @remarks
1187
- * A base64 string encodes each group of 3 input bytes as 4 characters, so a well-formed
1188
- * string's length is a multiple of 4 and its decoded length is `(length / 4) * 3` MINUS
1189
- * the trailing `=` padding (one `=` ⇒ the last group held 2 bytes, two `==` ⇒ 1 byte).
1190
- * The padding is counted from the trailing `=` characters, so both the `=` and `==` cases
1191
- * are handled. The empty string decodes to `0`. Total — never throws (a malformed,
1192
- * non-multiple-of-4 length still yields a defined non-negative estimate via `floor`).
1193
- *
1194
- * @param base64 - The base64-encoded string (e.g. an image's `data`)
1195
- * @returns The decoded payload's byte length
1196
- *
1197
- * @example
1198
- * ```ts
1199
- * decodedSize('') // 0
1200
- * decodedSize('AAAA') // 3 (no padding)
1201
- * decodedSize('AAA=') // 2 (one '=')
1202
- * decodedSize('AA==') // 1 (two '=')
1203
- * ```
1204
- */
1205
- function decodedSize(base64) {
1206
- if (base64.length === 0) return 0;
1207
- let padding = 0;
1208
- if (base64.endsWith("==")) padding = 2;
1209
- else if (base64.endsWith("=")) padding = 1;
1210
- return Math.floor(base64.length / 4) * 3 - padding;
1211
- }
1212
- /**
1213
- * Whether a {@link Range} is STRUCTURALLY valid — the predicate a ranged `write` checks
1214
- * before applying (a `false` here is the `RANGE` throw).
1215
- *
1216
- * @remarks
1217
- * Structural validity is independent of any content: every component must be `>= 1`
1218
- * (1-based lines and columns), and `start` must not come after `end` (an inverted range
1219
- * is invalid). A range that is structurally valid but reaches PAST the end of a specific
1220
- * text is still valid — it is {@link clampRange}d to the bounds when applied, not rejected.
1221
- * Total — never throws.
1222
- *
1223
- * @param range - The range to validate
1224
- * @returns `true` when every component is `>= 1` and `start` is at or before `end`
1225
- *
1226
- * @example
1227
- * ```ts
1228
- * isValidRange({ start: { line: 1, column: 1 }, end: { line: 2, column: 1 } }) // true
1229
- * isValidRange({ start: { line: 2, column: 1 }, end: { line: 1, column: 1 } }) // false (inverted)
1230
- * isValidRange({ start: { line: 0, column: 1 }, end: { line: 1, column: 1 } }) // false (sub-1 line)
1231
- * ```
1232
- */
1233
- function isValidRange(range) {
1234
- if (range.start.line < 1 || range.start.column < 1) return false;
1235
- if (range.end.line < 1 || range.end.column < 1) return false;
1236
- if (range.start.line > range.end.line) return false;
1237
- return !(range.start.line === range.end.line && range.start.column > range.end.column);
1238
- }
1239
- /**
1240
- * Clamp a 1-based {@link Position} to the bounds of `text` — every component pinned into a
1241
- * caret that actually exists in the content.
1242
- *
1243
- * @remarks
1244
- * `line` is pinned to `[1, lineCount]` and `column` to `[1, lineLength + 1]` of the
1245
- * resolved line (column `lineLength + 1` is the caret just past the line's last
1246
- * character). So a position beyond the end of the text resolves to the end rather than
1247
- * overflowing. Total — never throws.
1248
- *
1249
- * @param text - The text the position addresses
1250
- * @param position - The 1-based position to clamp
1251
- * @returns The clamped {@link Position}
1252
- *
1253
- * @example
1254
- * ```ts
1255
- * clampPosition('ab\ncd', { line: 9, column: 9 }) // { line: 2, column: 3 } (end of 'cd')
1256
- * ```
1257
- */
1258
- function clampPosition(text, position) {
1259
- const lines = text.split("\n");
1260
- const line = Math.max(1, Math.min(position.line, lines.length));
1261
- const lineText = lines[line - 1] ?? "";
1262
- return {
1263
- line,
1264
- column: Math.max(1, Math.min(position.column, lineText.length + 1))
1265
- };
1266
- }
1267
- /**
1268
- * Clamp both ends of a {@link Range} to the bounds of `text` — the actual span a ranged
1269
- * read / write applies (and the `range` a {@link import('./types.js').ReadResult} reports).
1270
- *
1271
- * @remarks
1272
- * Clamps `start` and `end` independently via {@link clampPosition}, so a range reaching
1273
- * past the end of the content is trimmed to the content's end. Total — never throws.
1274
- *
1275
- * @param text - The text the range addresses
1276
- * @param range - The 1-based range to clamp
1277
- * @returns The clamped {@link Range}
1278
- *
1279
- * @example
1280
- * ```ts
1281
- * clampRange('ab\ncd', { start: { line: 1, column: 1 }, end: { line: 9, column: 9 } })
1282
- * // { start: { line: 1, column: 1 }, end: { line: 2, column: 3 } }
1283
- * ```
1284
- */
1285
- function clampRange(text, range) {
1286
- return {
1287
- start: clampPosition(text, range.start),
1288
- end: clampPosition(text, range.end)
1289
- };
1290
- }
1291
- /**
1292
- * Convert a 1-based {@link Position} to a 0-based string offset into `text` — the indexing
1293
- * primitive {@link sliceRange} / {@link spliceRange} use, clamped to `text.length`.
1294
- *
1295
- * @remarks
1296
- * Sums each preceding line's length plus its `\n` separator, then adds the `column - 1`
1297
- * within the target line, capped at `text.length`. Total — never throws (an out-of-bounds
1298
- * position yields a defined in-range offset).
1299
- *
1300
- * @param text - The text to index into
1301
- * @param position - The 1-based position to resolve
1302
- * @returns The 0-based offset (in `[0, text.length]`)
1303
- *
1304
- * @example
1305
- * ```ts
1306
- * offsetAt('ab\ncd', { line: 2, column: 1 }) // 3 (just after 'ab\n')
1307
- * ```
1308
- */
1309
- function offsetAt(text, position) {
1310
- const lines = text.split("\n");
1311
- let offset = 0;
1312
- for (let index = 0; index < position.line - 1 && index < lines.length; index += 1) offset += (lines[index]?.length ?? 0) + 1;
1313
- offset += position.column - 1;
1314
- return Math.min(offset, text.length);
1315
- }
1316
- /**
1317
- * Slice the substring of `text` spanned by a {@link Range} (start INCLUSIVE, end
1318
- * EXCLUSIVE), clamping the range to the text's bounds first — the read half of the ranged
1319
- * edit surface.
1320
- *
1321
- * @remarks
1322
- * Clamps via {@link clampRange}, resolves each end to an offset via {@link offsetAt}, and
1323
- * returns `text.slice(startOffset, endOffset)`. Total — never throws.
1324
- *
1325
- * @param text - The text to slice
1326
- * @param range - The 1-based range to extract
1327
- * @returns The spanned substring (empty when the clamped span is empty)
1328
- *
1329
- * @example
1330
- * ```ts
1331
- * sliceRange('hello\nworld', { start: { line: 1, column: 1 }, end: { line: 1, column: 6 } }) // 'hello'
1332
- * ```
1333
- */
1334
- function sliceRange(text, range) {
1335
- const clamped = clampRange(text, range);
1336
- return text.slice(offsetAt(text, clamped.start), offsetAt(text, clamped.end));
1337
- }
1338
- /**
1339
- * Replace the span of `text` covered by a {@link Range} with `replacement` (start
1340
- * INCLUSIVE, end EXCLUSIVE), clamping the range to the text's bounds first — the write
1341
- * half of the ranged edit surface.
1342
- *
1343
- * @remarks
1344
- * Clamps via {@link clampRange}, then stitches `before + replacement + after` around the
1345
- * resolved offsets. An empty span (`start === end`) becomes a pure insertion. Total —
1346
- * never throws.
1347
- *
1348
- * @param text - The original text
1349
- * @param range - The 1-based range to overwrite
1350
- * @param replacement - The text to splice in place of the spanned range
1351
- * @returns The text with the spanned range replaced by `replacement`
1352
- *
1353
- * @example
1354
- * ```ts
1355
- * spliceRange('hello', { start: { line: 1, column: 1 }, end: { line: 1, column: 6 } }, 'bye') // 'bye'
1356
- * ```
1357
- */
1358
- function spliceRange(text, range, replacement) {
1359
- const clamped = clampRange(text, range);
1360
- const start = offsetAt(text, clamped.start);
1361
- const end = offsetAt(text, clamped.end);
1362
- return text.slice(0, start) + replacement + text.slice(end);
1363
- }
1364
- /**
1365
- * Assemble a 1-based nested {@link Range} from four FLAT caret integers — the bridge a
1366
- * workspace-editing tool (see `@orkestrel/tool`) uses from its small-model FLAT surface back to the
1367
- * nested {@link Range} the {@link import('./workspaces/Workspace.js').Workspace} edit surface
1368
- * speaks. Published as a public helper for that consumer.
1369
- *
1370
- * @remarks
1371
- * Pairs `(fromLine, fromColumn)` into `start` and `(toLine, toColumn)` into `end` verbatim — a pure
1372
- * structural lift, no validation (a structurally invalid range is rejected downstream by the ranged
1373
- * `write` it feeds, via {@link isValidRange}). Total — never throws. Zero-Node.
1374
- *
1375
- * @param fromLine - The 1-based start line
1376
- * @param fromColumn - The 1-based start column
1377
- * @param toLine - The 1-based end line
1378
- * @param toColumn - The 1-based end column
1379
- * @returns The `{ start, end }` {@link Range}
1380
- *
1381
- * @example
1382
- * ```ts
1383
- * rangeOf(1, 11, 1, 12) // { start: { line: 1, column: 11 }, end: { line: 1, column: 12 } }
1384
- * ```
1385
- */
1386
- function rangeOf(fromLine, fromColumn, toLine, toColumn) {
1387
- return {
1388
- start: {
1389
- line: fromLine,
1390
- column: fromColumn
1391
- },
1392
- end: {
1393
- line: toLine,
1394
- column: toColumn
1395
- }
1396
- };
1397
- }
1398
- /**
1399
845
  * Render a path-addressed text body as a fenced reference block — the framing an
1400
846
  * {@link import('./AgentContext.js').AgentContext}'s ACTIVE-workspace text-file render emits (the
1401
847
  * active workspace is the SOLE document/image context).
@@ -1405,7 +851,7 @@ function rangeOf(fromLine, fromColumn, toLine, toColumn) {
1405
851
  * fenced code block tagged with `language`, the `content` verbatim inside. Pure string assembly,
1406
852
  * total — never throws. The one fenced-file format string for the whole module — `AgentContext.build()`
1407
853
  * frames an active workspace's text files with it (each carries its own `language` on its
1408
- * {@link FileContent} text arm).
854
+ * {@link import('@orkestrel/workspace').FileContent} text arm).
1409
855
  *
1410
856
  * @param path - The file path shown on the `File:` label line
1411
857
  * @param language - The fenced-code language tag (e.g. `'typescript'`)
@@ -1424,29 +870,6 @@ function fencedFile(path, language, content) {
1424
870
  return `File: ${path}\n\`\`\`${language}\n${content}\n\`\`\``;
1425
871
  }
1426
872
  /**
1427
- * Escape a string's regex-special characters so it matches LITERALLY inside a `RegExp` — the
1428
- * primitive a {@link import('./workspaces/Workspace.js').Workspace} search builds a literal-text
1429
- * search pattern through (as opposed to a caller-supplied regex pattern).
1430
- *
1431
- * @remarks
1432
- * Prefixes every character in the class `. * + ? ^ $ { } ( ) | [ ] \` with a backslash, so the
1433
- * escaped string, when compiled into a `RegExp`, matches only its own literal characters — no
1434
- * character acts as a quantifier, anchor, group, or class. Pure string assembly, total — never
1435
- * throws.
1436
- *
1437
- * @param value - The text to escape for literal use inside a `RegExp` pattern
1438
- * @returns `value` with every regex-special character backslash-escaped
1439
- *
1440
- * @example
1441
- * ```ts
1442
- * escapeRegExp('a.b*c') // 'a\\.b\\*c'
1443
- * new RegExp(escapeRegExp('a.b*c')).test('a.b*c') // true
1444
- * ```
1445
- */
1446
- function escapeRegExp(value) {
1447
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1448
- }
1449
- /**
1450
873
  * Sanitize one reported token count into a safe non-negative integer.
1451
874
  *
1452
875
  * @param value - The token count to sanitize
@@ -1488,7 +911,7 @@ function sanitizeUsage(usage) {
1488
911
  * at construction.
1489
912
  *
1490
913
  * @remarks
1491
- * A thin immutable value object (mirroring {@link import('../tools/Tool.js').Tool}): the
914
+ * A thin immutable value object (mirroring {@link import('@orkestrel/tool').Tool}): the
1492
915
  * constructor mints a fresh `id` (`crypto.randomUUID()`), copies the input's `name` /
1493
916
  * `content`, resolves `priority` to the input's value or `0`, and carries the input's
1494
917
  * per-item `format` override ONLY when supplied (assigned just when present, mirroring a
@@ -1569,549 +992,49 @@ var InstructionManager = class {
1569
992
  get emitter() {
1570
993
  return this.#emitter;
1571
994
  }
1572
- get count() {
1573
- return this.#instructions.size;
1574
- }
1575
- get description() {
1576
- return this.#format?.open ?? "## Instructions";
1577
- }
1578
- get framing() {
1579
- return this.#format;
1580
- }
1581
- add(input) {
1582
- if (isArray(input)) return input.map((one) => this.#create(one));
1583
- return this.#create(input);
1584
- }
1585
- instruction(name) {
1586
- return this.#instructions.get(name);
1587
- }
1588
- instructions() {
1589
- return [...this.#instructions.values()].sort((a, b) => b.priority - a.priority);
1590
- }
1591
- format(instruction) {
1592
- return this.#format?.render?.(instruction) ?? instruction.content;
1593
- }
1594
- remove(names) {
1595
- if (isArray(names)) {
1596
- let removed = false;
1597
- for (const name of names) if (this.#delete(name)) removed = true;
1598
- return removed;
1599
- }
1600
- return this.#delete(names);
1601
- }
1602
- clear() {
1603
- this.#instructions.clear();
1604
- this.#emitter.emit("clear");
1605
- }
1606
- #create(input) {
1607
- const instruction = new Instruction(input);
1608
- this.#instructions.set(instruction.name, instruction);
1609
- this.#emitter.emit("add", instruction);
1610
- return instruction;
1611
- }
1612
- #delete(name) {
1613
- const removed = this.#instructions.delete(name);
1614
- if (removed) this.#emitter.emit("remove", name);
1615
- return removed;
1616
- }
1617
- };
1618
- //#endregion
1619
- //#region src/core/tools/ToolManager.ts
1620
- /**
1621
- * The tool registry the agent loop dispatches model tool-calls through — resolves
1622
- * names, lists {@link ToolDefinition}s for the provider, and executes calls with
1623
- * per-call error isolation.
1624
- *
1625
- * @remarks
1626
- * - **Registry.** Tools live in an insertion-ordered `Map` keyed by `tool.name`;
1627
- * `add` takes one or a batch (§9.2) and a re-`add` of the same name OVERWRITES it
1628
- * (last write wins). `count` is the map size, `tool(name)` looks one up, `tools()`
1629
- * lists them in insertion order, and `definitions()` maps each to a plain
1630
- * {@link ToolDefinition} (`name` / `description?` / `parameters?`, the `execute`
1631
- * handler stripped) — exactly what a provider advertises to the model, with
1632
- * `tool.summary ?? tool.description` advertised as `description` (a lean `summary`
1633
- * stands in for the full text when set).
1634
- * - **Per-call error isolation (the load-bearing part).** `execute` resolves a
1635
- * {@link ToolCall}'s tool by name and ALWAYS resolves a {@link ToolResult}: an
1636
- * unknown name → `{ id, name, error: 'tool not found: <name>' }`; a successful run →
1637
- * `{ id, name, value }`; a handler throw is CAUGHT into `{ id, name, error }` (an
1638
- * `Error`'s message, else the stringified throw). A tool throw never escapes — it
1639
- * becomes a result the model can react to.
1640
- * - **Batch never fails as a whole.** `execute(calls)` runs every call via
1641
- * `Promise.all(calls.map(...))` and resolves the results correlated by `id` in the
1642
- * input order — a mix of success, throw, and not-found all resolve; one bad call
1643
- * does not reject the batch.
1644
- * - **Event-free.** A purely functional registry — no Emitter, no events.
1645
- *
1646
- * @example
1647
- * ```ts
1648
- * const manager = new ToolManager()
1649
- * manager.add(new Tool({ name: 'add', execute: (a) => Number(a.x) + Number(a.y) }))
1650
- * const result = await manager.execute({ id: '1', name: 'add', arguments: { x: 1, y: 2 } })
1651
- * result.value // 3
1652
- * ```
1653
- */
1654
- var ToolManager = class {
1655
- #tools = /* @__PURE__ */ new Map();
1656
- get count() {
1657
- return this.#tools.size;
1658
- }
1659
- add(tools) {
1660
- if (isArray(tools)) {
1661
- for (const tool of tools) this.#tools.set(tool.name, tool);
1662
- return;
1663
- }
1664
- this.#tools.set(tools.name, tools);
1665
- }
1666
- tool(name) {
1667
- return this.#tools.get(name);
1668
- }
1669
- tools() {
1670
- return [...this.#tools.values()];
1671
- }
1672
- definitions() {
1673
- return [...this.#tools.values()].map((tool) => this.#definition(tool));
1674
- }
1675
- execute(call) {
1676
- if (isArray(call)) return Promise.all(call.map((one) => this.#run(one)));
1677
- return this.#run(call);
1678
- }
1679
- remove(names) {
1680
- if (isArray(names)) {
1681
- let removed = false;
1682
- for (const name of names) if (this.#tools.delete(name)) removed = true;
1683
- return removed;
1684
- }
1685
- return this.#tools.delete(names);
1686
- }
1687
- clear() {
1688
- this.#tools.clear();
1689
- }
1690
- async #run(call) {
1691
- const tool = this.#tools.get(call.name);
1692
- if (tool === void 0) return {
1693
- id: call.id,
1694
- name: call.name,
1695
- error: `tool not found: ${call.name}`
1696
- };
1697
- try {
1698
- const value = await tool.execute(call.arguments);
1699
- return {
1700
- id: call.id,
1701
- name: call.name,
1702
- value
1703
- };
1704
- } catch (error) {
1705
- return {
1706
- id: call.id,
1707
- name: call.name,
1708
- error: error instanceof Error ? error.message : String(error)
1709
- };
1710
- }
1711
- }
1712
- #definition(tool) {
1713
- const definition = { name: tool.name };
1714
- const description = tool.summary ?? tool.description;
1715
- if (description !== void 0) definition.description = description;
1716
- if (tool.parameters !== void 0) definition.parameters = tool.parameters;
1717
- return definition;
1718
- }
1719
- };
1720
- //#endregion
1721
- //#region src/core/workspaces/Workspace.ts
1722
- /**
1723
- * A mutable, `path`-keyed working set of immutable {@link FileInterface}s — the
1724
- * in-memory editing surface over the file primitive.
1725
- *
1726
- * @remarks
1727
- * - **Registry.** Files live in an insertion-ordered `Map` keyed by `path`; `count` is the
1728
- * map size, `file(path)` looks one up, and `files()` lists them in insertion order.
1729
- * - **Write replaces the File (§11 immutability).** Every edit MINTS a replacement
1730
- * {@link FileInterface} (via {@link import('../factories.js').createFile}) rather than
1731
- * mutating in place, transitioning `state` to `'created'` for a brand-new path or
1732
- * `'modified'` for an existing one. A whole-file string write preserves an existing text
1733
- * file's `language`, else infers it from the `path` (`inferLanguage`); writing a string
1734
- * onto an existing BINARY path replaces it with a text file (a deliberate retype). A
1735
- * ranged `write` splices a `Range` of an existing text file.
1736
- * - **Modality rules.** Text-only ops on a binary file are rejected: a ranged `read` /
1737
- * `write`, `prepend`, and `append` throw `MODALITY`; a plain `read(path)` of a binary
1738
- * file returns `undefined`; `search` / `replace` skip binary files (0 matches).
1739
- * - **In-memory removal.** `remove(path)` / `remove(paths)` drop files outright (no
1740
- * tombstone — the `'loaded'` / `'deleted'` states are reserved for a future FileStore);
1741
- * `remove()` and `clear()` both empty the registry and emit the single `clear` signal.
1742
- * The disk/sync lifecycle (`load` / `revert` / `accept` / `purge` / `dirty`) is NOT part
1743
- * of this surface.
1744
- * - **Observable (§13).** The owned {@link emitter} ({@link WorkspaceEventMap}) carries
1745
- * `write` (the resulting file) / `remove` (the path) / `move` (`{ from, to }`) / `clear`.
1746
- * Every event is emitted directly, strictly AFTER the map mutation completes; the
1747
- * emitter isolates a listener throw and routes it to its `error` handler, so a buggy
1748
- * observer can never corrupt a mutation.
1749
- *
1750
- * @example
1751
- * ```ts
1752
- * const workspace = new Workspace()
1753
- * workspace.write('src/main.ts', 'const x = 1')
1754
- * workspace.file('src/main.ts')?.state // 'created'
1755
- * workspace.append('src/main.ts', '\nconst y = 2')
1756
- * workspace.file('src/main.ts')?.state // 'modified'
1757
- * workspace.read('src/main.ts') // 'const x = 1\nconst y = 2'
1758
- * ```
1759
- */
1760
- var Workspace = class {
1761
- #id;
1762
- #files = /* @__PURE__ */ new Map();
1763
- #emitter;
1764
- constructor(options, seed) {
1765
- this.#id = options?.id ?? crypto.randomUUID();
1766
- this.#emitter = new Emitter({
1767
- ...options?.on === void 0 ? {} : { on: options.on },
1768
- ...options?.error === void 0 ? {} : { error: options.error }
1769
- });
1770
- if (seed) for (const [path, file] of seed) this.#files.set(path, file);
1771
- }
1772
- get id() {
1773
- return this.#id;
1774
- }
1775
- get emitter() {
1776
- return this.#emitter;
1777
- }
1778
- get count() {
1779
- return this.#files.size;
1780
- }
1781
- file(path) {
1782
- return this.#files.get(path);
1783
- }
1784
- files() {
1785
- return [...this.#files.values()];
1786
- }
1787
- read(path, range) {
1788
- if (isArray(path)) {
1789
- const result = {};
1790
- for (const one of path) {
1791
- const file = this.#files.get(one);
1792
- if (file && isText(file.content)) result[one] = file.content.text;
1793
- }
1794
- return result;
1795
- }
1796
- const file = this.#files.get(path);
1797
- if (!file) return void 0;
1798
- if (!range) return isText(file.content) ? file.content.text : void 0;
1799
- if (!isText(file.content)) throw new WorkspaceError("MODALITY", `Cannot read a range of a binary file: ${path}`, { path });
1800
- return {
1801
- content: sliceRange(file.content.text, range),
1802
- range: clampRange(file.content.text, range)
1803
- };
1804
- }
1805
- has(path) {
1806
- if (isArray(path)) return path.some((one) => this.#files.has(one));
1807
- return this.#files.has(path);
1808
- }
1809
- search(query, options) {
1810
- const pattern = this.#pattern(query, options);
1811
- const limit = options?.limit;
1812
- const matches = [];
1813
- for (const file of this.#files.values()) {
1814
- if (limit !== void 0 && matches.length >= limit) break;
1815
- if (!isText(file.content)) continue;
1816
- const lines = file.content.text.split("\n");
1817
- for (let index = 0; index < lines.length; index += 1) {
1818
- if (limit !== void 0 && matches.length >= limit) break;
1819
- const lineText = lines[index] ?? "";
1820
- pattern.lastIndex = 0;
1821
- let hit = pattern.exec(lineText);
1822
- while (hit !== null) {
1823
- if (limit !== void 0 && matches.length >= limit) break;
1824
- matches.push({
1825
- path: file.path,
1826
- line: index + 1,
1827
- column: hit.index + 1,
1828
- length: hit[0].length,
1829
- content: lineText
1830
- });
1831
- if (hit[0].length === 0) pattern.lastIndex += 1;
1832
- hit = pattern.exec(lineText);
1833
- }
1834
- }
1835
- }
1836
- return matches;
1837
- }
1838
- replace(query, replacement, options) {
1839
- const pattern = this.#pattern(query, options);
1840
- const limit = options?.limit;
1841
- let replaced = 0;
1842
- let files = 0;
1843
- for (const [path, file] of this.#files) {
1844
- if (limit !== void 0 && replaced >= limit) break;
1845
- if (!isText(file.content)) continue;
1846
- const remaining = limit === void 0 ? void 0 : limit - replaced;
1847
- let count = 0;
1848
- pattern.lastIndex = 0;
1849
- const next = file.content.text.replace(pattern, (match) => {
1850
- if (remaining !== void 0 && count >= remaining) return match;
1851
- count += 1;
1852
- return replacement;
1853
- });
1854
- if (count > 0) {
1855
- replaced += count;
1856
- files += 1;
1857
- this.write(path, next);
1858
- }
1859
- }
1860
- return {
1861
- query,
1862
- replaced,
1863
- files
1864
- };
1865
- }
1866
- write(path, content, range) {
1867
- if (isRecord(path)) {
1868
- for (const [one, text] of Object.entries(path)) this.#write(one, text);
1869
- return;
1870
- }
1871
- const text = content ?? "";
1872
- if (!range) {
1873
- this.#write(path, text);
1874
- return;
1875
- }
1876
- this.#splice(path, text, range);
1877
- }
1878
- prepend(path, content) {
1879
- if (isRecord(path)) {
1880
- for (const [one, text] of Object.entries(path)) this.#prepend(one, text);
1881
- return;
1882
- }
1883
- this.#prepend(path, content ?? "");
1884
- }
1885
- append(path, content) {
1886
- if (isRecord(path)) {
1887
- for (const [one, text] of Object.entries(path)) this.#append(one, text);
1888
- return;
1889
- }
1890
- this.#append(path, content ?? "");
1891
- }
1892
- move(from, to) {
1893
- if (isRecord(from)) {
1894
- let moved = false;
1895
- for (const [one, target] of Object.entries(from)) if (this.#move(one, target)) moved = true;
1896
- return moved;
1897
- }
1898
- return this.#move(from, to ?? "");
1899
- }
1900
- remove(path) {
1901
- if (path === void 0) {
1902
- this.#files.clear();
1903
- this.#emitter.emit("clear");
1904
- return;
1905
- }
1906
- if (isArray(path)) {
1907
- let removed = false;
1908
- for (const one of path) if (this.#remove(one)) removed = true;
1909
- return removed;
1910
- }
1911
- return this.#remove(path);
1912
- }
1913
- clear() {
1914
- this.#files.clear();
1915
- this.#emitter.emit("clear");
1916
- }
1917
- snapshot() {
1918
- return {
1919
- id: this.#id,
1920
- files: this.files()
1921
- };
1922
- }
1923
- #write(path, content) {
1924
- const existing = this.#files.get(path);
1925
- const file = createFile({
1926
- path,
1927
- content: {
1928
- text: content,
1929
- language: existing && isText(existing.content) ? existing.content.language : inferLanguage(path)
1930
- },
1931
- state: existing ? "modified" : "created"
1932
- });
1933
- this.#files.set(path, file);
1934
- this.#emitter.emit("write", file);
1935
- }
1936
- #splice(path, content, range) {
1937
- const existing = this.#files.get(path);
1938
- if (!existing || !isText(existing.content)) throw new WorkspaceError("MODALITY", `Cannot splice a range of a non-text file: ${path}`, { path });
1939
- if (!isValidRange(range)) throw new WorkspaceError("RANGE", `Invalid range for file: ${path}`, {
1940
- path,
1941
- range
1942
- });
1943
- const file = createFile({
1944
- path,
1945
- content: {
1946
- text: spliceRange(existing.content.text, range, content),
1947
- language: existing.content.language
1948
- },
1949
- state: "modified"
1950
- });
1951
- this.#files.set(path, file);
1952
- this.#emitter.emit("write", file);
1953
- }
1954
- #prepend(path, content) {
1955
- this.#write(path, content + this.#text(path, "prepend"));
1956
- }
1957
- #append(path, content) {
1958
- this.#write(path, this.#text(path, "append") + content);
1959
- }
1960
- #text(path, operation) {
1961
- const existing = this.#files.get(path);
1962
- if (!existing) return "";
1963
- if (!isText(existing.content)) throw new WorkspaceError("MODALITY", `Cannot ${operation} text to a binary file: ${path}`, { path });
1964
- return existing.content.text;
1965
- }
1966
- #move(from, to) {
1967
- const file = this.#files.get(from);
1968
- if (!file) return false;
1969
- const moved = createFile({
1970
- path: to,
1971
- content: file.content,
1972
- state: "modified"
1973
- });
1974
- this.#files.delete(from);
1975
- this.#files.set(to, moved);
1976
- this.#emitter.emit("move", {
1977
- from,
1978
- to
1979
- });
1980
- return true;
1981
- }
1982
- #remove(path) {
1983
- const removed = this.#files.delete(path);
1984
- if (removed) this.#emitter.emit("remove", path);
1985
- return removed;
1986
- }
1987
- #pattern(query, options) {
1988
- const source = options?.regex === true ? query : escapeRegExp(query);
1989
- const flags = options?.exact === false ? "gi" : "g";
1990
- try {
1991
- return new RegExp(source, flags);
1992
- } catch {
1993
- throw new WorkspaceError("PATTERN", `Invalid search pattern: ${query}`, { query });
1994
- }
1995
- }
1996
- };
1997
- //#endregion
1998
- //#region src/core/workspaces/WorkspaceManager.ts
1999
- /**
2000
- * The registry of {@link Workspace}s keyed by `id`, in insertion order, WITH an active pointer
2001
- * — the §9 store over the workspace layer PLUS the `active` / `switch` seam the context renders.
2002
- * Event-free (a registry, like {@link ConversationManager}); the observability lives on each
2003
- * {@link Workspace}.
2004
- *
2005
- * @remarks
2006
- * - **Registry.** Workspaces live in an insertion-ordered `Map` keyed by `id`. `add(input?)`
2007
- * mints a {@link Workspace} (its `id` from `input` or `crypto.randomUUID()`), flowing the
2008
- * manager's default `on` / `error` in unless the `input` OVERRIDES them, and stores it (an
2009
- * already-present `id` OVERWRITES — last write wins). `count` is the map size, `workspace(id)`
2010
- * looks one up, `workspaces()` lists them in insertion order.
2011
- * - **Active pointer.** `active` is the active workspace (what the context renders), `undefined`
2012
- * until the FIRST `add` (which auto-activates it — a registry with workspaces always has one
2013
- * active). A subsequent `add` leaves `active` unchanged. `switch(id)` re-points `active` to the
2014
- * workspace with `id` and returns it; an unknown `id` returns `undefined` and leaves `active`
2015
- * unchanged (the lenient lookup style — never throws, no new error code).
2016
- * - **Removal.** `remove` drops one by id, or a batch (§9.2) — `true` when any was removed;
2017
- * removing the ACTIVE workspace sets `active` to `undefined`. `clear` empties the registry and
2018
- * sets `active` to `undefined`.
2019
- * - **Durable open / save (the optional `store`).** With a {@link WorkspaceStoreInterface} supplied
2020
- * (the `store` option), `open(id)` HYDRATES a workspace on a registry miss — it `store.get(id)`s
2021
- * the snapshot and rebuilds a fresh {@link Workspace} through the constructor `seed`
2022
- * (`snapshot.files` → path → File), then activates it — and `save(id)` PERSISTS a registered
2023
- * workspace's `snapshot()`. Both are LENIENT without a store (open resolves only registered ids,
2024
- * save is a no-op `false`), consistent with the lenient `switch`.
2025
- * - **Event-free.** A purely registry store — no Emitter, no events (each workspace owns its own
2026
- * observable `emitter`).
2027
- *
2028
- * @example
2029
- * ```ts
2030
- * const manager = new WorkspaceManager()
2031
- * const first = manager.add() // auto-activates — active === first
2032
- * manager.add({ id: 'scratch' }) // leaves active unchanged
2033
- * manager.switch('scratch') // re-points active to the 'scratch' workspace
2034
- * manager.count // 2
2035
- * ```
2036
- */
2037
- var WorkspaceManager = class {
2038
- #workspaces = /* @__PURE__ */ new Map();
2039
- #active;
2040
- #on;
2041
- #error;
2042
- #store;
2043
- constructor(options) {
2044
- this.#on = options?.on;
2045
- this.#error = options?.error;
2046
- this.#store = options?.store;
2047
- }
2048
- get count() {
2049
- return this.#workspaces.size;
2050
- }
2051
- get active() {
2052
- return this.#active === void 0 ? void 0 : this.#workspaces.get(this.#active);
995
+ get count() {
996
+ return this.#instructions.size;
2053
997
  }
2054
- workspace(id) {
2055
- return this.#workspaces.get(id);
998
+ get description() {
999
+ return this.#format?.open ?? "## Instructions";
2056
1000
  }
2057
- workspaces() {
2058
- return [...this.#workspaces.values()];
1001
+ get framing() {
1002
+ return this.#format;
2059
1003
  }
2060
1004
  add(input) {
2061
- const on = input?.on ?? this.#on;
2062
- const error = input?.error ?? this.#error;
2063
- const workspace = new Workspace({
2064
- ...input?.id === void 0 ? {} : { id: input.id },
2065
- ...on === void 0 ? {} : { on },
2066
- ...error === void 0 ? {} : { error }
2067
- }, input?.seed);
2068
- this.#workspaces.set(workspace.id, workspace);
2069
- if (this.#active === void 0) this.#active = workspace.id;
2070
- return workspace;
1005
+ if (isArray(input)) return input.map((one) => this.#create(one));
1006
+ return this.#create(input);
2071
1007
  }
2072
- switch(id) {
2073
- const workspace = this.#workspaces.get(id);
2074
- if (workspace === void 0) return void 0;
2075
- this.#active = id;
2076
- return workspace;
1008
+ instruction(name) {
1009
+ return this.#instructions.get(name);
2077
1010
  }
2078
- async open(id) {
2079
- const existing = this.#workspaces.get(id);
2080
- if (existing !== void 0) {
2081
- this.#active = id;
2082
- return existing;
2083
- }
2084
- if (this.#store === void 0) return void 0;
2085
- const snapshot = await this.#store.get(id);
2086
- if (snapshot === void 0) return void 0;
2087
- const workspace = this.add({
2088
- id,
2089
- seed: snapshot.files.map((file) => [file.path, file])
2090
- });
2091
- this.#active = workspace.id;
2092
- return workspace;
1011
+ instructions() {
1012
+ return [...this.#instructions.values()].sort((a, b) => b.priority - a.priority);
2093
1013
  }
2094
- async save(id) {
2095
- const workspace = this.#workspaces.get(id);
2096
- if (this.#store === void 0 || workspace === void 0) return false;
2097
- await this.#store.set(workspace.snapshot());
2098
- return true;
1014
+ format(instruction) {
1015
+ return this.#format?.render?.(instruction) ?? instruction.content;
2099
1016
  }
2100
- remove(ids) {
2101
- if (isArray(ids)) {
1017
+ remove(names) {
1018
+ if (isArray(names)) {
2102
1019
  let removed = false;
2103
- for (const id of ids) if (this.#drop(id)) removed = true;
1020
+ for (const name of names) if (this.#delete(name)) removed = true;
2104
1021
  return removed;
2105
1022
  }
2106
- return this.#drop(ids);
1023
+ return this.#delete(names);
2107
1024
  }
2108
1025
  clear() {
2109
- this.#workspaces.clear();
2110
- this.#active = void 0;
1026
+ this.#instructions.clear();
1027
+ this.#emitter.emit("clear");
2111
1028
  }
2112
- #drop(id) {
2113
- const removed = this.#workspaces.delete(id);
2114
- if (removed && this.#active === id) this.#active = void 0;
1029
+ #create(input) {
1030
+ const instruction = new Instruction(input);
1031
+ this.#instructions.set(instruction.name, instruction);
1032
+ this.#emitter.emit("add", instruction);
1033
+ return instruction;
1034
+ }
1035
+ #delete(name) {
1036
+ const removed = this.#instructions.delete(name);
1037
+ if (removed) this.#emitter.emit("remove", name);
2115
1038
  return removed;
2116
1039
  }
2117
1040
  };
@@ -2121,15 +1044,17 @@ var WorkspaceManager = class {
2121
1044
  * The richer turn context the agent loop assembles a provider request from — the optional
2122
1045
  * system prompt, the observable context managers (instructions / workspaces), the
2123
1046
  * {@link ConversationManagerInterface} message source (whose active conversation IS `messages`),
2124
- * the {@link ToolManagerInterface} registry, and a mutable active {@link ScopeInterface}.
1047
+ * the {@link ToolManagerInterface} registry, and an active {@link ScopeInterface} changed through
1048
+ * {@link AgentContextInterface.apply}.
2125
1049
  *
2126
1050
  * @remarks
2127
1051
  * - **Composition.** `system` is the optional system prompt; `instructions` / `tools` /
2128
1052
  * `workspaces` / `conversations` are the registries passed in `options` (bring your own), or
2129
1053
  * fresh empty ones when omitted (so `workspaces` is ALWAYS present); `messages` is the ACTIVE
2130
1054
  * conversation's live tail (ALWAYS defined — see below). `scope` is the active filter —
2131
- * `undefined` (the default) ⇒ no filtering; settable afterwards. `workspaces` / `conversations`
2132
- * are likewise SETTABLE (swap the whole registry between runs).
1055
+ * `undefined` (the default) ⇒ no filtering; change it through `apply(scope)`. The structural
1056
+ * `workspaces` / `conversations` registries are fixed at construction; switch their active
1057
+ * members through their own `switch(id)` methods.
2133
1058
  * - **The message source — the conversation registry's ACTIVE conversation.** `conversations` is a
2134
1059
  * {@link ConversationManagerInterface}; the context ENSURES it always has an active conversation
2135
1060
  * (at construction it `add`s a default when the manager has none), so the DYNAMIC `messages`
@@ -2207,27 +1132,20 @@ var AgentContext = class {
2207
1132
  get workspaces() {
2208
1133
  return this.#workspaces;
2209
1134
  }
2210
- set workspaces(value) {
2211
- this.#workspaces = value;
2212
- }
2213
1135
  get messages() {
2214
1136
  return this.#conversations.active ?? this.#ensure();
2215
1137
  }
2216
1138
  get conversations() {
2217
1139
  return this.#conversations;
2218
1140
  }
2219
- set conversations(value) {
2220
- this.#conversations = value;
2221
- if (this.#conversations.active === void 0) this.#conversations.add();
2222
- }
2223
1141
  get tools() {
2224
1142
  return this.#tools;
2225
1143
  }
2226
1144
  get scope() {
2227
1145
  return this.#scope;
2228
1146
  }
2229
- set scope(value) {
2230
- this.#scope = value;
1147
+ apply(scope) {
1148
+ this.#scope = scope;
2231
1149
  }
2232
1150
  build(format) {
2233
1151
  const scope = this.#scope;
@@ -2293,7 +1211,7 @@ var AgentContext = class {
2293
1211
  }
2294
1212
  #workspaceImages(files) {
2295
1213
  const data = [];
2296
- for (const file of files) if (isBinary(file.content) && isImage(file.content)) data.push(file.content.data);
1214
+ for (const file of files) if (isBinary(file.content) && file.content.mime.startsWith("image/")) data.push(file.content.data);
2297
1215
  return data;
2298
1216
  }
2299
1217
  #ensure() {
@@ -2627,7 +1545,7 @@ var Agent = class {
2627
1545
  };
2628
1546
  const toolMessage = this.#context.messages.add({
2629
1547
  role: "tool",
2630
- content: JSON.stringify(outcomeResult.value ?? outcomeResult.error)
1548
+ content: outcomeResult.success ? JSON.stringify(outcomeResult.value) : outcomeResult.error
2631
1549
  });
2632
1550
  messages.push(toolMessage);
2633
1551
  }
@@ -2704,6 +1622,7 @@ var Agent = class {
2704
1622
  }
2705
1623
  #denial(call, reason) {
2706
1624
  return {
1625
+ success: false,
2707
1626
  id: call.id,
2708
1627
  name: call.name,
2709
1628
  error: reason !== void 0 ? `denied: ${reason}` : "denied by authority"
@@ -2877,8 +1796,8 @@ var AgentRegistry = class {
2877
1796
  * (an ALLOWLIST — only matched rules that allow get through), pass an `allowed: false`
2878
1797
  * `fallback`.
2879
1798
  * - **Consulted before each tool call.** The agent loop calls `evaluate({ call })` for
2880
- * every {@link import('./types.js').ToolCall} the model emits; a denied call is fed
2881
- * back to the model as a denial {@link import('./types.js').ToolResult} (a `tool`
1799
+ * every {@link import('@orkestrel/tool').ToolCall} the model emits; a denied call is fed
1800
+ * back to the model as a denial {@link import('@orkestrel/tool').ToolResult} (a `tool`
2882
1801
  * chunk + a tool message) instead of being executed — no tool run, no budget cost —
2883
1802
  * so the model sees the denial and can react.
2884
1803
  * - **Synchronous now.** The async human-approval handshake (request / grant / deny) is
@@ -2921,7 +1840,7 @@ var Authority = class {
2921
1840
  * conversation's durable state IS a row, so persistence reduces to keyed point-access (`get` / `set`
2922
1841
  * / `delete`) over a {@link TableInterface}, the driver-pluggable twin of the plain-`Map`
2923
1842
  * {@link import('./MemoryConversationStore.js').MemoryConversationStore}. The EXACT twin of
2924
- * {@link import('../../workspaces/stores/DatabaseWorkspaceStore.js').DatabaseWorkspaceStore}.
1843
+ * {@link import('@orkestrel/workspace').DatabaseWorkspaceStore}.
2925
1844
  *
2926
1845
  * @remarks
2927
1846
  * The store is driver-agnostic: it holds a single {@link TableInterface} whose backend (memory,
@@ -2929,7 +1848,7 @@ var Authority = class {
2929
1848
  * IndexedDB backend swaps in WITHOUT touching the
2930
1849
  * {@link import('../ConversationManager.js').ConversationManager} or the
2931
1850
  * {@link import('../Conversation.js').Conversation} — the same seam as
2932
- * {@link import('../../workspaces/stores/DatabaseWorkspaceStore.js').DatabaseWorkspaceStore}. The
1851
+ * {@link import('@orkestrel/workspace').DatabaseWorkspaceStore}. The
2933
1852
  * driver defaults to memory ({@link import('../../factories.js').createDatabaseConversationStore}
2934
1853
  * passes `createMemoryDriver()`), so it ALSO works in memory out of the box; you opt into the
2935
1854
  * durable plumbing by passing a JSON / SQLite / IndexedDB driver.
@@ -3000,12 +1919,12 @@ var DatabaseConversationStore = class {
3000
1919
  * The in-memory {@link ConversationStoreInterface} — a process-lifetime `Map` of
3001
1920
  * {@link ConversationSnapshot}s keyed by conversation id, the DEFAULT store
3002
1921
  * {@link import('../../factories.js').createMemoryConversationStore} builds. The EXACT twin of
3003
- * {@link import('../../workspaces/stores/MemoryWorkspaceStore.js').MemoryWorkspaceStore}.
1922
+ * {@link import('@orkestrel/workspace').MemoryWorkspaceStore}.
3004
1923
  *
3005
1924
  * @remarks
3006
1925
  * A plain `Map<string, ConversationSnapshot>` (AGENTS §21 — the snapshot is already pure,
3007
1926
  * self-contained JSON, so no encoding is needed for the memory tier). Like the
3008
- * {@link import('../../workspaces/stores/MemoryWorkspaceStore.js').MemoryWorkspaceStore} it twins,
1927
+ * {@link import('@orkestrel/workspace').MemoryWorkspaceStore} it twins,
3009
1928
  * there is NO idle-TTL and NO eviction: a persisted conversation lives until an explicit `delete`. A
3010
1929
  * durable backend (JSON / SQLite / IndexedDB) swaps in through the SAME interface without touching
3011
1930
  * the {@link import('../ConversationManager.js').ConversationManager} or the
@@ -3303,238 +2222,8 @@ var ThinkSplitter = class {
3303
2222
  }
3304
2223
  };
3305
2224
  //#endregion
3306
- //#region src/core/tools/Tool.ts
3307
- /**
3308
- * A registered tool — its {@link import('../types.js').ToolDefinition} schema (the
3309
- * `name` / `description` / `parameters` the model sees) bound to the `execute`
3310
- * handler that runs a call.
3311
- *
3312
- * @remarks
3313
- * A thin value object: the constructor stores the schema fields and the handler, and
3314
- * `execute` delegates to the handler verbatim. `parameters` is kept by reference (the
3315
- * open JSON-Schema the provider forwards as-is) — not cloned. The handler's `args` is
3316
- * the model-supplied `unknown` arguments record, narrowed inside the handler (§14);
3317
- * isolating a throw is the {@link ToolManager}'s job, not this class's. Event-free —
3318
- * no Emitter, no events.
3319
- *
3320
- * @example
3321
- * ```ts
3322
- * const tool = new Tool({
3323
- * name: 'add',
3324
- * description: 'Add two numbers',
3325
- * parameters: { type: 'object', properties: { a: { type: 'number' }, b: { type: 'number' } } },
3326
- * execute: (args) => Number(args.a) + Number(args.b),
3327
- * })
3328
- * ```
3329
- */
3330
- var Tool = class {
3331
- name;
3332
- description;
3333
- summary;
3334
- parameters;
3335
- #execute;
3336
- constructor(options) {
3337
- this.name = options.name;
3338
- if (options.description !== void 0) this.description = options.description;
3339
- if (options.summary !== void 0) this.summary = options.summary;
3340
- if (options.parameters !== void 0) this.parameters = options.parameters;
3341
- this.#execute = options.execute;
3342
- }
3343
- execute(args) {
3344
- return this.#execute(args);
3345
- }
3346
- };
3347
- //#endregion
3348
- //#region src/core/workspaces/stores/DatabaseWorkspaceStore.ts
3349
- /**
3350
- * A {@link WorkspaceStoreInterface} backed by one table of the `databases` layer — a workspace's
3351
- * durable state IS a row, so persistence reduces to keyed point-access (`get` / `set` / `delete`)
3352
- * over a {@link TableInterface}, the driver-pluggable twin of the plain-`Map`
3353
- * {@link import('./MemoryWorkspaceStore.js').MemoryWorkspaceStore}.
3354
- *
3355
- * @remarks
3356
- * The store is driver-agnostic: it holds a single {@link TableInterface} whose backend (memory,
3357
- * JSON, SQLite, IndexedDB) is chosen by whoever builds it (the factories), so a JSON / SQLite /
3358
- * IndexedDB backend swaps in WITHOUT touching the
3359
- * {@link import('../WorkspaceManager.js').WorkspaceManager} or the
3360
- * {@link import('../Workspace.js').Workspace} — the same seam as
3361
- * the analogous `DatabaseWorkflowStore` in `@orkestrel/workflow`. The
3362
- * driver defaults to memory ({@link import('../../factories.js').createDatabaseWorkspaceStore}
3363
- * passes `createMemoryDriver()`), so it ALSO works in memory out of the box; you opt into the
3364
- * durable plumbing by passing a JSON / SQLite / IndexedDB driver.
3365
- *
3366
- * The {@link WorkspaceSnapshot} is stored as ONE OPAQUE JSON COLUMN — the table is a row of
3367
- * `{ id; snapshot }` ({@link WorkspaceSnapshotRow}), the snapshot the whole JSON blob (a `rawShape`
3368
- * column the factory builds) — exactly as `DatabaseWorkflowStore` stores its snapshot. The snapshot
3369
- * is already a COMPLETE, self-contained, pure-JSON payload, so storing it whole is lossless AND
3370
- * keeps the row type flat (`snapshot` reads back as `unknown`).
3371
- *
3372
- * - **`set(snapshot)` upserts under the snapshot's OWN `id`** (no separate id param) — it writes
3373
- * the row `{ id: snapshot.id, snapshot }`.
3374
- * - **`get(id)` resolves the stored snapshot for an id**, narrowing the opaque JSON column back to
3375
- * a {@link WorkspaceSnapshot} ({@link import('../../helpers.js').isWorkspaceSnapshot} — the AGENTS
3376
- * §14 boundary narrow for an untrusted storage read), or `undefined` if none is stored.
3377
- * - **`delete(id)` drops a snapshot by id**; an absent id is a no-op (no throw).
3378
- *
3379
- * UNLIKE a session store there is NO idle-TTL / eviction — a persisted workspace lives until an
3380
- * explicit `delete`. The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the
3381
- * §22 method bijection with {@link WorkspaceStoreInterface}). Hydration stays a caller concern: a
3382
- * {@link import('../WorkspaceManager.js').WorkspaceManager} reads a snapshot back and rebuilds the
3383
- * live workspace through the constructor `seed` (its `open` / `save`).
3384
- *
3385
- * @example
3386
- * ```ts
3387
- * import { createDatabaseWorkspaceStore, createMemoryDriver, createWorkspace } from '@src/core'
3388
- *
3389
- * const store = createDatabaseWorkspaceStore(createMemoryDriver()) // a durable driver swaps in here
3390
- * const workspace = createWorkspace()
3391
- * workspace.write('notes.txt', 'hello')
3392
- * await store.set(workspace.snapshot()) // persist the workspace (one JSON column)
3393
- * const snapshot = await store.get(workspace.id)
3394
- * await store.delete(workspace.id) // drop it
3395
- * ```
3396
- */
3397
- var DatabaseWorkspaceStore = class {
3398
- #table;
3399
- /**
3400
- * Wrap a table as a workspace store.
3401
- *
3402
- * @param table - The {@link TableInterface} holding the snapshots — its row is the
3403
- * {@link WorkspaceSnapshotRow} `{ id; snapshot }` shape (the snapshot one opaque JSON column)
3404
- */
3405
- constructor(table) {
3406
- this.#table = table;
3407
- }
3408
- /** Resolve the persisted snapshot for `id`, narrowing the opaque JSON column back to a `WorkspaceSnapshot`. */
3409
- async get(id) {
3410
- const row = await this.#table.get(id);
3411
- if (row === void 0) return void 0;
3412
- return isWorkspaceSnapshot(row.snapshot) ? row.snapshot : void 0;
3413
- }
3414
- /** Insert or replace under the snapshot's OWN `id` (no separate id param) — the row is `{ id, snapshot }`. */
3415
- async set(snapshot) {
3416
- await this.#table.set({
3417
- id: snapshot.id,
3418
- snapshot
3419
- });
3420
- }
3421
- /** Drop a snapshot by id; an absent id is a no-op (no throw). */
3422
- async delete(id) {
3423
- await this.#table.remove(id);
3424
- }
3425
- };
3426
- //#endregion
3427
- //#region src/core/workspaces/stores/MemoryWorkspaceStore.ts
3428
- /**
3429
- * The in-memory {@link WorkspaceStoreInterface} — a process-lifetime `Map` of
3430
- * {@link WorkspaceSnapshot}s keyed by workspace id, the DEFAULT store
3431
- * {@link import('../../factories.js').createMemoryWorkspaceStore} builds.
3432
- *
3433
- * @remarks
3434
- * A plain `Map<string, WorkspaceSnapshot>` (AGENTS §21 — the snapshot is already pure,
3435
- * self-contained JSON, so no encoding is needed for the memory tier). Like the
3436
- * the analogous `MemoryWorkflowStore` in `@orkestrel/workflow` it twins,
3437
- * there is NO idle-TTL and NO eviction: a persisted workspace lives until an explicit `delete`. A
3438
- * durable backend (JSON / SQLite / IndexedDB) swaps in through the SAME interface without touching
3439
- * the {@link import('../WorkspaceManager.js').WorkspaceManager} or the
3440
- * {@link import('../Workspace.js').Workspace} — its driver-pluggable twin is
3441
- * {@link import('./DatabaseWorkspaceStore.js').DatabaseWorkspaceStore} (the snapshot as one opaque
3442
- * JSON column).
3443
- *
3444
- * - **`get` resolves the persisted snapshot for an id**, or `undefined` if none is stored.
3445
- * - **`set` inserts / replaces under the snapshot's OWN `id`** (no separate id param).
3446
- * - **`delete` drops a snapshot by id**; an absent id is a no-op (no throw).
3447
- *
3448
- * The public surface is EXACTLY `get` / `set` / `delete` — no extra members (the §22 method
3449
- * bijection with {@link WorkspaceStoreInterface}). Hydration is a caller concern: a
3450
- * {@link import('../WorkspaceManager.js').WorkspaceManager} reads a snapshot back and rebuilds the
3451
- * live workspace through the constructor `seed` (its `open` / `save`).
3452
- *
3453
- * @example
3454
- * ```ts
3455
- * import { createMemoryWorkspaceStore, createWorkspace } from '@src/core'
3456
- *
3457
- * const store = createMemoryWorkspaceStore()
3458
- * const workspace = createWorkspace()
3459
- * workspace.write('notes.txt', 'hello')
3460
- * await store.set(workspace.snapshot()) // persist the workspace
3461
- * const snapshot = await store.get(workspace.id)
3462
- * await store.delete(workspace.id) // drop it
3463
- * ```
3464
- */
3465
- var MemoryWorkspaceStore = class {
3466
- #snapshots = /* @__PURE__ */ new Map();
3467
- get(id) {
3468
- return Promise.resolve(this.#snapshots.get(id));
3469
- }
3470
- set(snapshot) {
3471
- this.#snapshots.set(snapshot.id, snapshot);
3472
- return Promise.resolve();
3473
- }
3474
- delete(id) {
3475
- this.#snapshots.delete(id);
3476
- return Promise.resolve();
3477
- }
3478
- };
3479
- //#endregion
3480
2225
  //#region src/core/factories.ts
3481
2226
  /**
3482
- * Create a tool — a {@link ToolInterface} binding a {@link ToolDefinition} schema
3483
- * (the `name` / `description` / `parameters` the model sees) to the `execute` handler
3484
- * that runs a call.
3485
- *
3486
- * @remarks
3487
- * Only `name` is required (it keys the tool in a {@link ToolManagerInterface} and is
3488
- * what the model calls); `description` / `parameters` are the optional JSON-Schema the
3489
- * provider advertises (forwarded verbatim). The handler's `args` is the model-supplied
3490
- * `unknown` arguments record — narrow it inside (§14); a `createToolManager` registry
3491
- * isolates a throw into a `ToolResult.error`.
3492
- *
3493
- * @param options - `name` (required), optional `description` / `parameters`, and the
3494
- * `execute` handler (see {@link ToolOptions})
3495
- * @returns A working {@link ToolInterface}
3496
- *
3497
- * @example
3498
- * ```ts
3499
- * import { createTool } from '@src/core'
3500
- *
3501
- * const add = createTool({
3502
- * name: 'add',
3503
- * description: 'Add two numbers',
3504
- * execute: (args) => Number(args.a) + Number(args.b),
3505
- * })
3506
- * ```
3507
- */
3508
- function createTool(options) {
3509
- return new Tool(options);
3510
- }
3511
- /**
3512
- * Create a tool registry — a {@link ToolManagerInterface} that resolves tool names,
3513
- * lists {@link ToolDefinition}s for the provider, and executes calls with per-call
3514
- * error isolation.
3515
- *
3516
- * @remarks
3517
- * Starts empty; `add` registers one tool or a batch (§9.2), `definitions()` yields the
3518
- * schemas to hand a provider, and `execute` runs a {@link ToolCall} (or a batch),
3519
- * ALWAYS resolving a {@link ToolResult} — a handler throw becomes an `error` result and
3520
- * an unknown name a not-found `error`, so a tool throw never escapes and a batch never
3521
- * fails as a whole.
3522
- *
3523
- * @returns An empty {@link ToolManagerInterface}
3524
- *
3525
- * @example
3526
- * ```ts
3527
- * import { createTool, createToolManager } from '@src/core'
3528
- *
3529
- * const tools = createToolManager()
3530
- * tools.add(createTool({ name: 'add', execute: (a) => Number(a.x) + Number(a.y) }))
3531
- * const result = await tools.execute({ id: '1', name: 'add', arguments: { x: 1, y: 2 } })
3532
- * ```
3533
- */
3534
- function createToolManager() {
3535
- return new ToolManager();
3536
- }
3537
- /**
3538
2227
  * Create a conversation — a {@link ConversationInterface} grouping messages above a flat
3539
2228
  * message store it OWNS DIRECTLY, with compaction into summarized sections, a regenerated
3540
2229
  * rollup `summary`, on-demand `rehydrate`, and substring `search`, driven by a
@@ -3608,11 +2297,13 @@ function createConversationManager(options) {
3608
2297
  * Create the in-memory conversation store — a {@link ConversationStoreInterface} backed by a
3609
2298
  * process-lifetime `Map` of {@link import('./types.js').ConversationSnapshot}s keyed by conversation
3610
2299
  * id, the DEFAULT backing for the durable {@link ConversationManagerInterface.open} /
3611
- * {@link ConversationManagerInterface.save} seam. The EXACT twin of {@link createMemoryWorkspaceStore}.
2300
+ * {@link ConversationManagerInterface.save} seam. The exact twin of
2301
+ * {@link import('@orkestrel/workspace').createMemoryWorkspaceStore}.
3612
2302
  *
3613
2303
  * @remarks
3614
2304
  * A plain `Map` (the snapshot is already pure JSON, so no encoding is needed for the memory tier),
3615
- * the structural twin of {@link createMemoryWorkspaceStore}. `get` / `set` / `delete` are async (the
2305
+ * the structural twin of {@link import('@orkestrel/workspace').createMemoryWorkspaceStore}.
2306
+ * `get` / `set` / `delete` are async (the
3616
2307
  * same shape a durable backend fits); UNLIKE a session store there is NO idle-TTL / eviction — a
3617
2308
  * persisted conversation lives until an explicit `delete`. Its driver-pluggable twin is
3618
2309
  * {@link createDatabaseConversationStore} (the snapshot as one opaque JSON column over a `databases`
@@ -3640,12 +2331,14 @@ function createMemoryConversationStore() {
3640
2331
  /**
3641
2332
  * Create a {@link DatabaseConversationStore} over any {@link DriverInterface} — the durable,
3642
2333
  * driver-pluggable backing for the conversation persistence seam, the opt-in twin of
3643
- * {@link createMemoryConversationStore}. The EXACT twin of {@link createDatabaseWorkspaceStore}.
2334
+ * {@link createMemoryConversationStore}. The exact twin of
2335
+ * {@link import('@orkestrel/workspace').createDatabaseWorkspaceStore}.
3644
2336
  *
3645
2337
  * @remarks
3646
2338
  * Builds a one-table database (`conversations`, keyed by `id`) over the supplied driver, the snapshot
3647
2339
  * held as ONE OPAQUE JSON COLUMN — the column map is `{ id; snapshot }` where `snapshot` is a
3648
- * `rawShape` (a JSON blob), exactly as {@link createDatabaseWorkspaceStore} stores its snapshot. The
2340
+ * `rawShape` (a JSON blob), exactly as
2341
+ * {@link import('@orkestrel/workspace').createDatabaseWorkspaceStore} stores its snapshot. The
3649
2342
  * snapshot is already a COMPLETE, self-contained, pure-JSON payload, so storing it whole is lossless
3650
2343
  * AND keeps the row type FLAT (the column reads back as `unknown`, narrowed on `get` by
3651
2344
  * {@link import('./helpers.js').isConversationSnapshot}). The `driver` DEFAULTS to
@@ -3669,12 +2362,13 @@ function createMemoryConversationStore() {
3669
2362
  * ```
3670
2363
  */
3671
2364
  function createDatabaseConversationStore(driver = createMemoryDriver()) {
2365
+ const columns = {
2366
+ id: stringShape(),
2367
+ snapshot: rawShape({})
2368
+ };
3672
2369
  return new DatabaseConversationStore(createDatabase({
3673
2370
  driver,
3674
- tables: { conversations: {
3675
- id: stringShape(),
3676
- snapshot: rawShape({})
3677
- } }
2371
+ tables: { conversations: columns }
3678
2372
  }).table("conversations"));
3679
2373
  }
3680
2374
  /**
@@ -3790,8 +2484,8 @@ function createScopeManager(options) {
3790
2484
  * @remarks
3791
2485
  * `system` is the optional system prompt; `tools` / `instructions` / `workspaces` are pre-built
3792
2486
  * managers to reuse (empty ones are created when omitted, so `context.workspaces` is ALWAYS
3793
- * present); `scope` is the initial active filter (`undefined` ⇒ no filtering, mutable afterwards
3794
- * via `context.scope`). The `messages` store is always fresh. `build()` folds the scoped
2487
+ * present); `scope` is the initial active filter (`undefined` ⇒ no filtering, changeable afterwards
2488
+ * via `context.apply(...)`). The `messages` store is always fresh. `build()` folds the scoped
3795
2489
  * instructions — PLUS the ACTIVE workspace's scope-filtered text files (fenced) — into ONE leading
3796
2490
  * `system` message and appends the scoped conversation (attaching the active workspace's
3797
2491
  * scope-filtered image files' `data` to the last user message), built fresh each call; the active
@@ -3941,8 +2635,9 @@ function createAuthority(options) {
3941
2635
  *
3942
2636
  * @example
3943
2637
  * ```ts
2638
+ * import { createAgentRegistry } from '@src/core'
3944
2639
  * import type { ProviderInterface } from '@src/core'
3945
- * import { createAgentRegistry, createTool } from '@src/core'
2640
+ * import { createTool } from '@orkestrel/tool'
3946
2641
  *
3947
2642
  * declare const provider: ProviderInterface // any concrete implementation supplied by the host app
3948
2643
  * const registry = createAgentRegistry({
@@ -4047,213 +2742,7 @@ function createAgentRunner(options) {
4047
2742
  handler: handleAgentRunnerJob.bind(void 0, registry, allowPartial)
4048
2743
  });
4049
2744
  }
4050
- /**
4051
- * Create a file — an immutable {@link FileInterface} from its `path` + {@link FileContent}
4052
- * and optional {@link import('./types.js').FileState}, with `size` / `lines` DERIVED from the
4053
- * content.
4054
- *
4055
- * @remarks
4056
- * Returns a PLAIN `Object.freeze`d record (NOT a class instance) — the `path` IS its identity
4057
- * (there is no `id`). Only `path` / `content` are required; `state` defaults to `'created'`
4058
- * when omitted. `size` (via {@link computeSize}) and `lines` (via {@link countLines}) are
4059
- * computed from the content here (so they never drift from it). Frozen + plain, so it
4060
- * `structuredClone`s losslessly and is never mutated after creation.
4061
- *
4062
- * @param input - `path` / `content` (required) and an optional `state` (see {@link FileInput})
4063
- * @returns A frozen {@link FileInterface} record
4064
- *
4065
- * @example
4066
- * ```ts
4067
- * import { createFile, createTextContent } from '@src/core'
4068
- *
4069
- * const file = createFile({ path: 'src/main.ts', content: createTextContent('const x = 1', 'typescript') })
4070
- * file.lines // 1
4071
- * ```
4072
- */
4073
- function createFile(input) {
4074
- return Object.freeze({
4075
- path: input.path,
4076
- content: input.content,
4077
- state: input.state ?? "created",
4078
- size: computeSize(input.content),
4079
- lines: countLines(input.content)
4080
- });
4081
- }
4082
- /**
4083
- * Build the TEXT {@link FileContent} arm — the §4.2.3 split constructor for text (a separate
4084
- * function per arm, not one constructor dispatching on a discriminator parameter).
4085
- *
4086
- * @param text - The literal text body
4087
- * @param language - The fenced-code language the text renders as (e.g. `'typescript'`)
4088
- * @returns A `{ text; language }` content arm
4089
- *
4090
- * @example
4091
- * ```ts
4092
- * import { createTextContent } from '@src/core'
4093
- *
4094
- * createTextContent('const x = 1', 'typescript') // { text: 'const x = 1', language: 'typescript' }
4095
- * ```
4096
- */
4097
- function createTextContent(text, language) {
4098
- return {
4099
- text,
4100
- language
4101
- };
4102
- }
4103
- /**
4104
- * Build the BINARY {@link FileContent} arm — the §4.2.3 split constructor for binary (a
4105
- * separate function per arm, not one constructor dispatching on a discriminator parameter).
4106
- * An image is just a binary with an image {@link BinaryMIME}.
4107
- *
4108
- * @param data - The base64-encoded binary payload
4109
- * @param mime - The {@link BinaryMIME} that labels the payload
4110
- * @returns A `{ data; mime }` content arm
4111
- *
4112
- * @example
4113
- * ```ts
4114
- * import { createBinaryContent } from '@src/core'
4115
- *
4116
- * createBinaryContent('<base64>', 'image/png') // { data: '<base64>', mime: 'image/png' }
4117
- * ```
4118
- */
4119
- function createBinaryContent(data, mime) {
4120
- return {
4121
- data,
4122
- mime
4123
- };
4124
- }
4125
- /**
4126
- * Create a workspace — a mutable, `path`-keyed working set of immutable
4127
- * {@link FileInterface}s with the in-memory edit surface (read / write / search / replace /
4128
- * move / remove), observable through its `EmitterInterface` (from `@orkestrel/emitter`).
4129
- *
4130
- * @param options - Optional initial {@link import('./types.js').WorkspaceEventMap} listeners (`on`) and the emitter's `error` handler (see {@link WorkspaceOptions})
4131
- * @returns A working {@link WorkspaceInterface}
4132
- *
4133
- * @example
4134
- * ```ts
4135
- * import { createWorkspace } from '@src/core'
4136
- *
4137
- * const workspace = createWorkspace({ on: { write: (file) => console.log(file.path) } })
4138
- * workspace.write('src/main.ts', 'const x = 1')
4139
- * workspace.file('src/main.ts')?.state // 'created'
4140
- * ```
4141
- */
4142
- function createWorkspace(options) {
4143
- return new Workspace(options);
4144
- }
4145
- /**
4146
- * Create the in-memory workspace store — a {@link WorkspaceStoreInterface} backed by a
4147
- * process-lifetime `Map` of {@link import('./types.js').WorkspaceSnapshot}s keyed by workspace id,
4148
- * the DEFAULT backing for the durable {@link WorkspaceManagerInterface.open} /
4149
- * {@link WorkspaceManagerInterface.save} seam.
4150
- *
4151
- * @remarks
4152
- * A plain `Map` (the snapshot is already pure JSON, so no encoding is needed for the memory tier),
4153
- * the structural twin of the analogous `createMemoryWorkflowStore` in `@orkestrel/workflow`.
4154
- * `get` / `set` / `delete` are async (the same shape a durable backend fits); UNLIKE a session
4155
- * store there is NO idle-TTL / eviction — a persisted workspace lives until an explicit `delete`.
4156
- * Its driver-pluggable twin is {@link createDatabaseWorkspaceStore} (the snapshot as one opaque
4157
- * JSON column over a `databases` table) — for a DURABLE store pass it a JSON / SQLite / IndexedDB
4158
- * driver, and it swaps in WITHOUT touching the manager or the workspace. Hydration stays a manager
4159
- * concern: read a snapshot back and rebuild the live workspace through the constructor `seed`.
4160
- *
4161
- * @returns A memory-backed {@link WorkspaceStoreInterface}
4162
- *
4163
- * @example
4164
- * ```ts
4165
- * import { createMemoryWorkspaceStore, createWorkspaceManager } from '@src/core'
4166
- *
4167
- * const store = createMemoryWorkspaceStore()
4168
- * const manager = createWorkspaceManager({ store })
4169
- * const workspace = manager.add()
4170
- * workspace.write('notes.txt', 'hello')
4171
- * await manager.save(workspace.id) // persist the workspace
4172
- * ```
4173
- */
4174
- function createMemoryWorkspaceStore() {
4175
- return new MemoryWorkspaceStore();
4176
- }
4177
- /**
4178
- * Create a {@link DatabaseWorkspaceStore} over any {@link DriverInterface} — the durable,
4179
- * driver-pluggable backing for the workspace persistence seam, the opt-in twin of
4180
- * {@link createMemoryWorkspaceStore}.
4181
- *
4182
- * @remarks
4183
- * Builds a one-table database (`workspaces`, keyed by `id`) over the supplied driver, the snapshot
4184
- * held as ONE OPAQUE JSON COLUMN — the column map is `{ id; snapshot }` where `snapshot` is a
4185
- * `rawShape` (a JSON blob), exactly as
4186
- * the analogous `createDatabaseWorkflowStore` in `@orkestrel/workflow` stores its snapshot. The
4187
- * snapshot is already a COMPLETE, self-contained, pure-JSON payload, so storing it whole is lossless
4188
- * AND keeps the row type FLAT (the column reads back as `unknown`, narrowed on `get` by
4189
- * {@link import('./helpers.js').isWorkspaceSnapshot}). The `driver` DEFAULTS to
4190
- * {@link createMemoryDriver}, so the store ALSO works in memory out of the box; pass a server
4191
- * `createJSONDriver` / `createSQLiteDriver` (or a browser IndexedDB driver) for a persistent one —
4192
- * the durability is the driver's job, the store engine is shared. It swaps in behind
4193
- * {@link WorkspaceStoreInterface} WITHOUT touching the manager or the workspace.
4194
- *
4195
- * @param driver - The storage backend the snapshots persist to (defaults to {@link createMemoryDriver})
4196
- * @returns A {@link WorkspaceStoreInterface} over the driver
4197
- *
4198
- * @example
4199
- * ```ts
4200
- * import { createDatabaseWorkspaceStore, createMemoryDriver, createWorkspaceManager } from '@src/core'
4201
- *
4202
- * const store = createDatabaseWorkspaceStore(createMemoryDriver()) // a durable driver swaps in here
4203
- * const manager = createWorkspaceManager({ store })
4204
- * const workspace = manager.add()
4205
- * workspace.write('notes.txt', 'hello')
4206
- * await manager.save(workspace.id) // persist the workspace (one JSON column)
4207
- * ```
4208
- */
4209
- function createDatabaseWorkspaceStore(driver = createMemoryDriver()) {
4210
- return new DatabaseWorkspaceStore(createDatabase({
4211
- driver,
4212
- tables: { workspaces: {
4213
- id: stringShape(),
4214
- snapshot: rawShape({})
4215
- } }
4216
- }).table("workspaces"));
4217
- }
4218
- /**
4219
- * Create a workspace registry — a {@link WorkspaceManagerInterface} holding
4220
- * {@link WorkspaceInterface}s keyed by their `id` (in insertion order) WITH an active pointer:
4221
- * the §9 store over the workspace layer plus the `active` / `switch` seam the context renders.
4222
- *
4223
- * @remarks
4224
- * Starts empty; `add(input?)` mints a {@link WorkspaceInterface} (its `id` from the input or a
4225
- * random UUID), flowing the manager's default `on` / `error` in unless the input overrides them,
4226
- * and stores it (an already-present `id` overwrites — last write wins) — and AUTO-ACTIVATES the
4227
- * FIRST one (a registry with workspaces always has one `active`); a later `add` leaves `active`
4228
- * unchanged. `switch(id)` re-points `active` (an unknown `id` returns `undefined`, leaving
4229
- * `active` unchanged — lenient, never throws); `workspace(id)` / `workspaces()` look up;
4230
- * `remove` (one or a batch, §9.2) reports whether any was removed AND clears `active` if it was
4231
- * the removed one; `clear` empties it and clears `active`. Event-free (each workspace owns its
4232
- * own observable `emitter`).
4233
- *
4234
- * With the optional `store` ({@link WorkspaceStoreInterface}, e.g. `createMemoryWorkspaceStore` /
4235
- * `createDatabaseWorkspaceStore`), `open(id)` HYDRATES a workspace on a registry miss (rebuilding it
4236
- * through the constructor `seed` from the snapshot's `files`, then activating it) and `save(id)`
4237
- * PERSISTS a registered workspace's `snapshot()`. Both are LENIENT without a store (open resolves
4238
- * only registered ids, save is a no-op `false`).
4239
- *
4240
- * @param options - Optional default `on` / `error` for created workspaces + the durable `store`
4241
- * (see {@link WorkspaceManagerOptions})
4242
- * @returns An empty {@link WorkspaceManagerInterface}
4243
- *
4244
- * @example
4245
- * ```ts
4246
- * import { createWorkspaceManager } from '@src/core'
4247
- *
4248
- * const workspaces = createWorkspaceManager()
4249
- * const scratch = workspaces.add() // auto-activates — workspaces.active === scratch
4250
- * scratch.write('notes.txt', 'hello')
4251
- * ```
4252
- */
4253
- function createWorkspaceManager(options) {
4254
- return new WorkspaceManager(options);
4255
- }
4256
2745
  //#endregion
4257
- export { Agent, AgentContext, AgentError, AgentJobError, AgentRegistry, Authority, CONVERSATION_RECAP_PREFIX, Channel, Conversation, ConversationError, ConversationManager, DEFAULT_AGENT_LIMIT, DEFAULT_AUTHORITY_ZONE, DEFAULT_CONVERSATION_KEEP, DatabaseConversationStore, DatabaseWorkspaceStore, EXTENSION_TO_LANGUAGE, IMAGE_TOKEN_ESTIMATE, Instruction, InstructionManager, MESSAGE_TOKEN_OVERHEAD, MemoryConversationStore, MemoryWorkspaceStore, ProviderAbortError, Scope, ScopeManager, THINK_CLOSE, THINK_OPEN, ThinkSplitter, Tool, ToolManager, WORKSPACE_SECTION_HEADER, Workspace, WorkspaceError, WorkspaceManager, buildToolResult, clampPosition, clampRange, computeSize, countLines, createAgent, createAgentContext, createAgentQueue, createAgentRegistry, createAgentRunner, createAuthority, createBinaryContent, createConversation, createConversationManager, createDatabaseConversationStore, createDatabaseWorkspaceStore, createFile, createInstruction, createInstructionManager, createMemoryConversationStore, createMemoryWorkspaceStore, createScope, createScopeManager, createTextContent, createThinkSplitter, createTool, createToolManager, createWorkspace, createWorkspaceManager, decodedSize, escapeRegExp, estimateMessages, estimateTokens, fencedFile, filterAllowList, handleAgentQueueJob, handleAgentRunnerJob, inferLanguage, isAgentError, isAgentJobError, isBinary, isConversationError, isConversationSnapshot, isFile, isImage, isMessage, isProviderAbortError, isSection, isText, isToolCall, isValidRange, isWorkspaceError, isWorkspaceSnapshot, offsetAt, rangeOf, sanitizeToken, sanitizeUsage, settleAgentJob, sliceRange, spliceRange };
2746
+ export { Agent, AgentContext, AgentError, AgentJobError, AgentRegistry, Authority, CONVERSATION_RECAP_PREFIX, Channel, Conversation, ConversationError, ConversationManager, DEFAULT_AGENT_LIMIT, DEFAULT_AUTHORITY_ZONE, DEFAULT_CONVERSATION_KEEP, DatabaseConversationStore, IMAGE_TOKEN_ESTIMATE, Instruction, InstructionManager, MESSAGE_TOKEN_OVERHEAD, MemoryConversationStore, ProviderAbortError, Scope, ScopeManager, THINK_CLOSE, THINK_OPEN, ThinkSplitter, WORKSPACE_SECTION_HEADER, createAgent, createAgentContext, createAgentQueue, createAgentRegistry, createAgentRunner, createAuthority, createConversation, createConversationManager, createDatabaseConversationStore, createInstruction, createInstructionManager, createMemoryConversationStore, createScope, createScopeManager, createThinkSplitter, estimateMessages, estimateTokens, fencedFile, filterAllowList, handleAgentQueueJob, handleAgentRunnerJob, isAgentError, isAgentJobError, isConversationError, isConversationSnapshot, isMessage, isProviderAbortError, isSection, sanitizeToken, sanitizeUsage, settleAgentJob };
4258
2747
 
4259
2748
  //# sourceMappingURL=index.js.map