@agency-lang/memento 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +64 -2
  2. package/dist/agency/embed.d.ts +22 -0
  3. package/dist/agency/embed.js +458 -0
  4. package/dist/agencyApi.d.ts +98 -0
  5. package/dist/agencyApi.js +237 -0
  6. package/dist/embed.d.ts +45 -0
  7. package/dist/embed.js +77 -0
  8. package/dist/engine/files/engine.d.ts +85 -0
  9. package/dist/engine/files/engine.js +284 -0
  10. package/dist/engine/files/lock.d.ts +18 -0
  11. package/dist/engine/files/lock.js +247 -0
  12. package/dist/engine/files/manifest.d.ts +43 -0
  13. package/dist/engine/files/manifest.js +111 -0
  14. package/dist/engine/files/safe-delete.d.ts +19 -0
  15. package/dist/engine/files/safe-delete.js +79 -0
  16. package/dist/engine/files/segments.d.ts +17 -0
  17. package/dist/engine/files/segments.js +128 -0
  18. package/dist/engine/memory/engine.d.ts +27 -0
  19. package/dist/engine/memory/engine.js +87 -0
  20. package/dist/engine/open.d.ts +7 -0
  21. package/dist/engine/open.js +28 -0
  22. package/dist/engine/shared/filter.d.ts +7 -0
  23. package/dist/engine/shared/filter.js +72 -0
  24. package/dist/engine/shared/keyword.d.ts +27 -0
  25. package/dist/engine/shared/keyword.js +92 -0
  26. package/dist/engine/shared/settings.d.ts +5 -0
  27. package/dist/engine/shared/settings.js +9 -0
  28. package/dist/engine/shared/state.d.ts +58 -0
  29. package/dist/engine/shared/state.js +275 -0
  30. package/dist/engine/shared/tokens.d.ts +15 -0
  31. package/dist/engine/shared/tokens.js +23 -0
  32. package/dist/engine/shared/vectors.d.ts +36 -0
  33. package/dist/engine/shared/vectors.js +70 -0
  34. package/dist/engine/types.d.ts +121 -0
  35. package/dist/engine/types.js +1 -0
  36. package/dist/files.d.ts +75 -0
  37. package/dist/files.js +190 -0
  38. package/dist/filter.d.ts +3 -0
  39. package/dist/filter.js +80 -0
  40. package/dist/fusion.d.ts +24 -0
  41. package/dist/fusion.js +26 -0
  42. package/dist/ids.d.ts +2 -0
  43. package/dist/ids.js +19 -0
  44. package/dist/index.d.ts +4 -0
  45. package/dist/index.js +3 -0
  46. package/dist/local.d.ts +36 -0
  47. package/dist/local.js +75 -0
  48. package/dist/memento.d.ts +151 -0
  49. package/dist/memento.js +470 -0
  50. package/dist/query.d.ts +50 -0
  51. package/dist/query.js +138 -0
  52. package/dist/rows.d.ts +17 -0
  53. package/dist/rows.js +90 -0
  54. package/dist/stem.d.ts +2 -0
  55. package/dist/stem.js +121 -0
  56. package/dist/types.d.ts +246 -0
  57. package/dist/types.js +3 -0
  58. package/dist/vectors.d.ts +2 -0
  59. package/dist/vectors.js +10 -0
  60. package/dist/windows.d.ts +44 -0
  61. package/dist/windows.js +77 -0
  62. package/index.agency +268 -0
  63. package/index.js +1803 -0
  64. package/package.json +55 -4
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # Memento
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A local memory layer: load documents into a folder on disk, then search them
4
+ in plain words. There is no database and no server. A store is a folder you
5
+ can copy or back up.
6
+
7
+ ```
8
+ pnpm add @agency-lang/memento agency-lang
9
+ ```
10
+
11
+ `agency-lang` is a peer dependency, and your project must have exactly one
12
+ copy of it. Node 22.13 or newer.
13
+
14
+ ## From TypeScript
15
+
16
+ ```ts
17
+ import { Memento } from "@agency-lang/memento";
18
+
19
+ const store = await Memento.open({ type: "files", path: "~/memento/notes" });
20
+
21
+ await store.add([{ id: "roof", title: "Roofer", text: "Paid $4,200 in May." }]);
22
+ await store.addFiles(["~/notes/**/*.md"]);
23
+
24
+ const hits = await store.search("what did the roof cost");
25
+ console.log(hits[0]?.document.title, hits[0]?.excerpt);
26
+
27
+ await store.close();
28
+ ```
29
+
30
+ A store searches by keyword. Open it with an embedding model and it also
31
+ searches by meaning:
32
+
33
+ ```ts
34
+ const store = await Memento.open(
35
+ { type: "files", path: "~/memento/notes" },
36
+ { models: { embedding: "openai:text-embedding-3-small" } },
37
+ );
38
+ ```
39
+
40
+ A store records its embedding model when it is made, and every later open
41
+ must name the same one. `Memento.settings(storage)` reads it without opening
42
+ the store.
43
+
44
+ ## From Agency
45
+
46
+ ```
47
+ import { createStore, addFiles, search } from "pkg::@agency-lang/memento"
48
+
49
+ node main() {
50
+ createStore("~/memento/notes")
51
+ addFiles("~/memento/notes", ["~/notes/**/*.md"])
52
+ return search("~/memento/notes", "what did the roof cost")
53
+ }
54
+ ```
55
+
56
+ Each function asks for approval before it touches a store, and before it
57
+ sends text to an embedding model. Every approval names the store's folder, so
58
+ a policy can allow one store and not another.
59
+
60
+ ## More
61
+
62
+ The doc comments in the package's types are the API documentation. The
63
+ repository's `docs/dev/package.md` describes the design, and
64
+ `docs/dev/agency-module.md` describes the Agency functions and their
65
+ approvals.
@@ -0,0 +1,22 @@
1
+ // The types of the node that `agency compile src/agency` writes to embed.js
2
+ // beside this file. The generated JavaScript is not part of the TypeScript
3
+ // program: tsc cannot name some of its inferred types in a declaration file.
4
+ // This file is copied into dist/ with it. Keep it in step with embed.agency.
5
+
6
+ export type EmbedInput = {
7
+ groups: string[][][];
8
+ model: string;
9
+ provider: string;
10
+ kind: string;
11
+ };
12
+
13
+ export type EmbedOutput = { vectors: number[][]; model: string };
14
+
15
+ /** A compiled node's result: its return value in `data`, and what the run spent. */
16
+ export type EmbedNodeRun = {
17
+ data: { success: true; value: EmbedOutput } | { success: false; error: string };
18
+ usage: { cost: { totalCost: number }; tokens: { inputTokens: number }; entries: unknown[] };
19
+ traceId: string;
20
+ };
21
+
22
+ export function embedTexts(input: EmbedInput): Promise<EmbedNodeRun>;
@@ -0,0 +1,458 @@
1
+ import { print, printJSON, input, sleep, saveDraft, _guard, _budgetOutcome, _pairsOf, read, write, writeBinary, readBinary, range, callback, map, mapWithIndex, filter, exclude, find, findIndex, reduce, flatMap, every, some, count, sortBy, unique, groupBy, flatten, setAgentCwd, getAgentCwd, applyAgentCwd, Call } from "agency-lang/stdlib/index.js";
2
+ import { embedMany } from "agency-lang/stdlib/embedding.js";
3
+ import { redact } from "agency-lang/stdlib/tag.js";
4
+ import { z } from "agency-lang/zod";
5
+ import {
6
+ RuntimeContext,
7
+ ThreadStore,
8
+ Runner,
9
+ setupNode,
10
+ claimFrameForScope,
11
+ runNode,
12
+ callHook,
13
+ checkpointFor as __checkpoint_impl,
14
+ getCheckpointFor as __getCheckpoint_impl,
15
+ restoreFor as __restore_impl,
16
+ _runFor as __runtime_run_impl,
17
+ interrupt,
18
+ isInterrupt,
19
+ hasInterrupts,
20
+ resolveCliInterrupts,
21
+ reportBudgetExceededAndExit,
22
+ flushPendingStatelogPosts,
23
+ isDebugger,
24
+ isPaused,
25
+ respondToInterrupts as _respondToInterrupts,
26
+ respondToInterruptsForServe as _respondToInterruptsForServe,
27
+ resumeFromCheckpoint as _resumeFromCheckpoint,
28
+ resumeCliFromCheckpoint as _resumeCliFromCheckpoint,
29
+ rewindFrom as _rewindFrom,
30
+ patchCheckpoint as _patchCheckpoint,
31
+ runExportedFunction as _runExportedFunction,
32
+ runExportedFunctionForServe as _runExportedFunctionForServe,
33
+ runNodeForServe as _runNodeForServe,
34
+ RunControlSignal,
35
+ AgencyAbort,
36
+ isAborted,
37
+ __registerGlobalsInit,
38
+ __registerCallbacksInit,
39
+ __enterCallable,
40
+ registerModuleFingerprint as __registerModuleFingerprint,
41
+ success,
42
+ runtimeFailure,
43
+ isFailure,
44
+ AgencyFunction as __AgencyFunction,
45
+ __call,
46
+ __callMethod,
47
+ withChildRun as __withChildRun,
48
+ functionRefReviver as __functionRefReviver,
49
+ createLogger as __createLogger,
50
+ defaultHost as __defaultHost,
51
+ path,
52
+ runCliEntry
53
+ } from "agency-lang/runtime";
54
+ const __host = __defaultHost();
55
+ const __dirname = __host.system.moduleDir(import.meta.url);
56
+ const __sourceFile = path.join(__dirname, "embed.agency");
57
+ const __globalCtx = new RuntimeContext({
58
+ statelogConfig: {
59
+ host: "",
60
+ apiKey: __host.settings.read("STATELOG_API_KEY") || "",
61
+ projectId: "",
62
+ debugMode: false,
63
+ observability: true,
64
+ logFile: "log.jsonl"
65
+ },
66
+ smoltalkDefaults: {
67
+ apiKey: {
68
+ openAi: __host.settings.read("OPENAI_API_KEY") || "",
69
+ google: __host.settings.read("GEMINI_API_KEY") || "",
70
+ anthropic: __host.settings.read("ANTHROPIC_API_KEY") || "",
71
+ openRouter: __host.settings.read("OPENROUTER_API_KEY") || "",
72
+ deepInfra: __host.settings.read("DEEPINFRA_API_KEY") || "",
73
+ liteLlm: __host.settings.read("LITELLM_API_KEY") || "",
74
+ openAiCompat: __host.settings.read("OPENAI_COMPAT_API_KEY") || "",
75
+ groq: __host.settings.read("GROQ_API_KEY") || "",
76
+ typesafe: __host.settings.read("TYPESAFE_API_KEY") || ""
77
+ },
78
+ baseUrl: {
79
+ liteLlm: __host.settings.read("LITELLM_BASE_URL") || "",
80
+ openAiCompat: __host.settings.read("OPENAI_COMPAT_BASE_URL") || ""
81
+ },
82
+ model: "gpt-5-mini",
83
+ logLevel: "warn",
84
+ provider: "openai-responses"
85
+ },
86
+ dirname: __dirname,
87
+ host: __host,
88
+ logLevel: "info",
89
+ traceConfig: {
90
+ program: "src/agency/embed.agency"
91
+ }
92
+ });
93
+ const graph = __globalCtx.graph;
94
+ function approve(value) {
95
+ return { type: "approve", value };
96
+ }
97
+ function reject(reason) {
98
+ return { type: "reject", value: reason };
99
+ }
100
+ function propagate() {
101
+ return { type: "propagate" };
102
+ }
103
+ function pass() {
104
+ return { type: "pass" };
105
+ }
106
+ const respondToInterrupts = (interrupts, responses, opts) => _respondToInterrupts({ ctx: __globalCtx, interrupts, responses, overrides: opts?.overrides, edits: opts?.edits, at: opts?.at, metadata: opts?.metadata, callbacks: opts?.callbacks, abortSignal: opts?.abortSignal, pauseSignal: opts?.pauseSignal, invocation: opts?.invocation });
107
+ const resumeFromCheckpoint = (paused, opts) => _resumeFromCheckpoint({ ctx: __globalCtx, paused, edits: opts?.edits, metadata: opts?.metadata, callbacks: opts?.callbacks, abortSignal: opts?.abortSignal, pauseSignal: opts?.pauseSignal, invocation: opts?.invocation });
108
+ const rewindFrom = (checkpoint2, overrides, opts) => _rewindFrom({ ctx: __globalCtx, checkpoint: checkpoint2, overrides, edits: opts?.edits, at: opts?.at, metadata: opts?.metadata, callbacks: opts?.callbacks, invocation: opts?.invocation, abortSignal: opts?.abortSignal, pauseSignal: opts?.pauseSignal });
109
+ const __resumeFromCheckpoint = (checkpoint2, overrides, edits) => _resumeCliFromCheckpoint({ ctx: __globalCtx, checkpoint: checkpoint2, overrides, edits });
110
+ const patchCheckpoint = (checkpoint2, edits) => _patchCheckpoint(checkpoint2, edits, __globalCtx.host.settings);
111
+ const __invokeFunction = (fn, namedArgs) => _runExportedFunction({ ctx: __globalCtx, fn, namedArgs, initializeGlobals: __initializeGlobals });
112
+ const __invokeFunctionForServe = (fn, namedArgs, invocation) => _runExportedFunctionForServe({ ctx: __globalCtx, fn, namedArgs, invocation, initializeGlobals: __initializeGlobals });
113
+ const __invokeNodeForServe = (nodeName, data, invocation) => _runNodeForServe({ ctx: __globalCtx, nodeName, data, invocation, initializeGlobals: __initializeGlobals });
114
+ const __respondToInterruptsForServe = (interrupts, responses, opts) => _respondToInterruptsForServe({ ctx: __globalCtx, interrupts, responses, overrides: opts?.overrides, edits: opts?.edits, at: opts?.at, metadata: opts?.metadata, invocation: opts?.invocation, abortSignal: opts?.abortSignal, pauseSignal: opts?.pauseSignal });
115
+ const __setDebugger = (dbg) => {
116
+ __globalCtx.debuggerState = dbg;
117
+ };
118
+ const __getDebugger = () => __globalCtx.debuggerState;
119
+ const __setTraceFile = (filePath) => {
120
+ __globalCtx.traceConfig.traceFile = filePath;
121
+ };
122
+ const __setLLMClient = (client) => {
123
+ __globalCtx.setLLMClient(client);
124
+ };
125
+ const __getCheckpoints = () => __globalCtx.checkpoints;
126
+ const __toolRegistry = __functionRefReviver.registry ??= {};
127
+ function __registerTool(value, _aliasName) {
128
+ if (__AgencyFunction.isAgencyFunction(value)) {
129
+ __toolRegistry[`${value.module}:${value.name}`] = value;
130
+ }
131
+ }
132
+ const checkpoint = __AgencyFunction.create({ name: "checkpoint", module: "__runtime", fn: __checkpoint_impl, params: [], toolDefinition: null }, __toolRegistry);
133
+ const getCheckpoint = __AgencyFunction.create({ name: "getCheckpoint", module: "__runtime", fn: __getCheckpoint_impl, params: [{ name: "checkpointId", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
134
+ const restore = __AgencyFunction.create({ name: "restore", module: "__runtime", fn: __restore_impl, params: [{ name: "checkpointIdOrCheckpoint", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "options", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
135
+ const _run = __AgencyFunction.create({ name: "_run", module: "__runtime", fn: __runtime_run_impl, params: [{ name: "compiled", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "node", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "args", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "wallClock", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "memory", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "ipcPayload", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "stdout", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "configOverrides", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "cwd", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "maxDepth", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
136
+ function setLLMClient(client) {
137
+ __globalCtx.setLLMClient(client);
138
+ }
139
+ function registerTools(tools) {
140
+ for (const tool of tools) {
141
+ if (__AgencyFunction.isAgencyFunction(tool)) {
142
+ __toolRegistry[`${tool.module}:${tool.name}`] = tool;
143
+ }
144
+ }
145
+ }
146
+ __registerModuleFingerprint("src/agency/embed.agency", "d13ac4bfe379157d9148c36fea31a4142ceab63e48db944e94daaa395741ae00");
147
+ __registerTool(print);
148
+ __registerTool(printJSON);
149
+ __registerTool(input);
150
+ __registerTool(sleep);
151
+ __registerTool(saveDraft);
152
+ __registerTool(_guard);
153
+ __registerTool(_budgetOutcome);
154
+ __registerTool(_pairsOf);
155
+ __registerTool(read);
156
+ __registerTool(write);
157
+ __registerTool(writeBinary);
158
+ __registerTool(readBinary);
159
+ __registerTool(range);
160
+ __registerTool(callback);
161
+ __registerTool(map);
162
+ __registerTool(mapWithIndex);
163
+ __registerTool(filter);
164
+ __registerTool(exclude);
165
+ __registerTool(find);
166
+ __registerTool(findIndex);
167
+ __registerTool(reduce);
168
+ __registerTool(flatMap);
169
+ __registerTool(every);
170
+ __registerTool(some);
171
+ __registerTool(count);
172
+ __registerTool(sortBy);
173
+ __registerTool(unique);
174
+ __registerTool(groupBy);
175
+ __registerTool(flatten);
176
+ __registerTool(setAgentCwd);
177
+ __registerTool(getAgentCwd);
178
+ __registerTool(applyAgentCwd);
179
+ __registerTool(Call);
180
+ __registerTool(embedMany);
181
+ __registerTool(redact);
182
+ async function __initializeGlobals(__run) {
183
+ const __ctx = __run.ctx;
184
+ if (__ctx.globals.isInitialized("src/agency/embed.agency")) {
185
+ return;
186
+ }
187
+ __ctx.globals.markInitialized("src/agency/embed.agency");
188
+ }
189
+ __registerGlobalsInit("src/agency/embed.agency", __initializeGlobals);
190
+ async function __registerTopLevelCallbacks(__run) {
191
+ const __ctx = __run.ctx;
192
+ }
193
+ __registerCallbacksInit("src/agency/embed.agency", __registerTopLevelCallbacks);
194
+ __functionRefReviver.registry = __toolRegistry;
195
+ const EmbedInput = z.object({ "groups": z.array(z.array(z.array(z.string()))), "model": z.string(), "provider": z.string(), "kind": z.string() });
196
+ graph.node("embedTexts", async (__state) => {
197
+ const __setupData = setupNode({
198
+ state: __state
199
+ });
200
+ const __run = __setupData.run;
201
+ const __stack = __setupData.stack;
202
+ const __step = __setupData.step;
203
+ const __self = __setupData.self;
204
+ const __activation = __self;
205
+ const __ctx = __run.ctx;
206
+ let __forked;
207
+ let __functionCompleted = false;
208
+ claimFrameForScope(__stack, "embedTexts", "src/agency/embed.agency", __run.log);
209
+ const runner = new Runner(__ctx, __stack, { nodeContext: true, state: __stack, moduleId: "src/agency/embed.agency", scopeName: "embedTexts", stack: __run.stack, threads: __setupData.threads });
210
+ return await __enterCallable(__run, "embedTexts", [], async (__run2) => {
211
+ if (!__state.isResume) {
212
+ __stack.args["input"] = __state.data.input;
213
+ }
214
+ try {
215
+ await __withChildRun(__run2, {
216
+ ctx: __ctx,
217
+ stack: __ctx.stateStack,
218
+ threads: __setupData.threads
219
+ }, "its body", async (__run3) => {
220
+ await runner.hook(0, __run3, async (__run4) => {
221
+ await callHook(__run4, {
222
+ name: "onNodeStart",
223
+ data: {
224
+ nodeName: "embedTexts"
225
+ }
226
+ });
227
+ });
228
+ await runner.step(1, __run3, async (runner2, __run4) => {
229
+ __stack.locals.vectors = [];
230
+ });
231
+ await runner.loop(2, __run3, async (__run4) => __stack.args.input.groups, async (group, _, runner2, __run4) => {
232
+ await runner2.step(0, __run4, async (runner3, __run5) => {
233
+ __stack.locals.results = await runner3.fork(0, __run5, group, async (__run6, __forkItem, __forkIndex, __forkBranchStack) => {
234
+ const __bstack = __forkBranchStack.getNewState();
235
+ const __self2 = __bstack.locals;
236
+ const __bframe___block_0 = __bstack;
237
+ claimFrameForScope(__bstack, "__block_0", "src/agency/embed.agency", __run6.log);
238
+ const batch = __forkItem;
239
+ __bstack.args["batch"] = __forkItem;
240
+ const runner4 = new Runner(__ctx, __bstack, { state: __bstack, moduleId: "src/agency/embed.agency", scopeName: "__block_0", stack: __run6.stack, threads: __run6.threads });
241
+ try {
242
+ await runner4.step(0, __run6, async (runner5, __run7) => {
243
+ runner5.halt(await __call(__run7, embedMany, {
244
+ type: "named",
245
+ positionalArgs: [__bstack.args.batch],
246
+ namedArgs: {
247
+ model: __stack.args.input.model,
248
+ provider: __stack.args.input.provider
249
+ }
250
+ }));
251
+ return;
252
+ });
253
+ return runner4.halted ? runner4.haltResult : void 0;
254
+ } finally {
255
+ __forkBranchStack.release(__bstack);
256
+ }
257
+ }, "all", __run5.stack, false, void 0);
258
+ if (hasInterrupts(__stack.locals.results)) {
259
+ runner3.halt({
260
+ ...__state,
261
+ data: __stack.locals.results
262
+ });
263
+ return;
264
+ }
265
+ if (isAborted(__stack.locals.results)) {
266
+ throw __stack.locals.results.toError();
267
+ }
268
+ });
269
+ await runner2.loop(1, __run4, async (__run5) => __stack.locals.results, async (result, _2, runner3, __run5) => {
270
+ await runner3.step(0, __run5, async (runner4, __run6) => {
271
+ __stack.locals.__hoist_0 = await isFailure(result);
272
+ if (hasInterrupts(__stack.locals.__hoist_0)) {
273
+ runner4.halt({
274
+ ...__state,
275
+ data: __stack.locals.__hoist_0
276
+ });
277
+ return;
278
+ }
279
+ if (isAborted(__stack.locals.__hoist_0)) {
280
+ throw __stack.locals.__hoist_0.toError();
281
+ }
282
+ });
283
+ await runner3.ifElse(1, __run5, [
284
+ {
285
+ condition: async (__run6) => __stack.locals.__hoist_0,
286
+ body: async (runner4, __run6) => {
287
+ await runner4.step(0, __run6, async (runner5, __run7) => {
288
+ runner5.halt({
289
+ messages: __run7.threads,
290
+ data: result
291
+ });
292
+ return;
293
+ });
294
+ }
295
+ }
296
+ ]);
297
+ await runner3.step(2, __run5, async (runner4, __run6) => {
298
+ __stack.locals.vectors = await __callMethod(__run6, __stack.locals.vectors, "concat", {
299
+ type: "positional",
300
+ args: [result.value.vectors]
301
+ });
302
+ });
303
+ });
304
+ });
305
+ await runner.step(3, __run3, async (runner2, __run4) => {
306
+ });
307
+ await runner.step(4, __run3, async (runner2, __run4) => {
308
+ const __funcResult = await __call(__run4, redact, {
309
+ type: "positional",
310
+ args: [__stack.locals.vectors]
311
+ });
312
+ if (hasInterrupts(__funcResult)) {
313
+ runner2.halt({
314
+ ...__state,
315
+ data: __funcResult
316
+ });
317
+ return;
318
+ }
319
+ if (isAborted(__funcResult)) {
320
+ throw __funcResult.toError();
321
+ }
322
+ });
323
+ await runner.step(5, __run3, async (runner2, __run4) => {
324
+ runner2.halt({
325
+ messages: __run4.threads,
326
+ data: await success({
327
+ "vectors": __stack.locals.vectors,
328
+ "model": __stack.args.input.model
329
+ })
330
+ });
331
+ return;
332
+ });
333
+ });
334
+ if (runner.halted) return runner.haltResult;
335
+ await runner.hook(6, __run2, async (__run3) => {
336
+ await callHook(__run3, {
337
+ name: "onNodeEnd",
338
+ data: {
339
+ nodeName: "embedTexts",
340
+ data: void 0
341
+ }
342
+ });
343
+ });
344
+ return {
345
+ messages: __run2.threads,
346
+ data: void 0
347
+ };
348
+ } catch (__error) {
349
+ if (__error instanceof RunControlSignal) {
350
+ throw __error;
351
+ }
352
+ if (__error instanceof AgencyAbort) {
353
+ throw __error;
354
+ }
355
+ {
356
+ const __errMsg = __error instanceof Error ? __error.message : String(__error);
357
+ const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
358
+ const __log = __createLogger(__ctx.logLevel, __ctx.host.settings);
359
+ __log.error(`Node embedTexts crashed: ${__errMsg}`);
360
+ if (__errStack) __log.error(__errStack);
361
+ __run2.log?.error?.({
362
+ errorType: "runtimeError",
363
+ message: __errMsg,
364
+ functionName: "embedTexts"
365
+ });
366
+ }
367
+ return {
368
+ messages: __run2.threads,
369
+ data: runtimeFailure(__error, { functionName: "embedTexts" })
370
+ };
371
+ }
372
+ }, (__run2, __failure) => {
373
+ return {
374
+ messages: __run2.threads,
375
+ data: __failure
376
+ };
377
+ });
378
+ });
379
+ async function embedTexts(input2, { messages: __invocationMessages, callbacks: __invocationCallbacks, config: __invocationConfig, traceId: __invocationTraceId, policy: __invocationPolicy, host: __invocationHost, invocationInput: __invocationInput, abortSignal: __invocationAbortSignal, pauseSignal: __invocationPauseSignal, inputOverride: __invocationInputOverride, logFile: __invocationLogFile, onJobStarted: __invocationOnJobStarted } = {}) {
380
+ return runNode({
381
+ ctx: __globalCtx,
382
+ nodeName: "embedTexts",
383
+ data: {
384
+ input: input2
385
+ },
386
+ messages: __invocationMessages,
387
+ callbacks: __invocationCallbacks,
388
+ invocation: {
389
+ config: __invocationConfig,
390
+ traceId: __invocationTraceId,
391
+ policy: __invocationPolicy,
392
+ host: __invocationHost,
393
+ inputOverride: __invocationInputOverride,
394
+ logFile: __invocationLogFile,
395
+ onJobStarted: __invocationOnJobStarted
396
+ },
397
+ input: __invocationInput,
398
+ abortSignal: __invocationAbortSignal,
399
+ pauseSignal: __invocationPauseSignal,
400
+ initializeGlobals: __initializeGlobals
401
+ });
402
+ }
403
+ const __embedTextsNodeParams = ["input"];
404
+ if (__host.system.isMainModule(import.meta.url)) {
405
+ try {
406
+ const initialState = {
407
+ messages: new ThreadStore(),
408
+ data: {}
409
+ };
410
+ const __result = await runCliEntry({
411
+ nodeNames: ["embedTexts"],
412
+ startNode: (nodeName) => runNode({
413
+ ctx: __globalCtx,
414
+ nodeName,
415
+ data: initialState.data,
416
+ messages: initialState.messages,
417
+ initializeGlobals: __initializeGlobals
418
+ }),
419
+ resume: __resumeFromCheckpoint
420
+ });
421
+ await resolveCliInterrupts(__result, respondToInterrupts);
422
+ } catch (__error) {
423
+ await reportBudgetExceededAndExit(__error);
424
+ console.error(`
425
+ Agent crashed: ${__error.message}`);
426
+ await flushPendingStatelogPosts();
427
+ throw __error;
428
+ }
429
+ }
430
+ var stdin_default = graph;
431
+ const __sourceMap = { "src/agency/embed.agency:embedTexts": { "1": { "line": 19, "col": 2 }, "2": { "line": 20, "col": 2 }, "4": { "line": 32, "col": 2 }, "5": { "line": 33, "col": 2 }, "2.0": { "line": 21, "col": 4 }, "2.1.0": { "line": 25, "col": 10 }, "2.1.1.0": { "line": 26, "col": 8 }, "2.1.1": { "line": 25, "col": 6 }, "2.1.2": { "line": 28, "col": 6 }, "2.1": { "line": 24, "col": 4 } }, "src/agency/embed.agency:__block_0": { "0": { "line": 22, "col": 6 } } };
432
+ export {
433
+ __embedTextsNodeParams,
434
+ __getCheckpoints,
435
+ __getDebugger,
436
+ __invokeFunction,
437
+ __invokeFunctionForServe,
438
+ __invokeNodeForServe,
439
+ __respondToInterruptsForServe,
440
+ __setDebugger,
441
+ __setLLMClient,
442
+ __setTraceFile,
443
+ __sourceMap,
444
+ __toolRegistry,
445
+ approve,
446
+ stdin_default as default,
447
+ embedTexts,
448
+ hasInterrupts,
449
+ interrupt,
450
+ isDebugger,
451
+ isInterrupt,
452
+ isPaused,
453
+ patchCheckpoint,
454
+ reject,
455
+ respondToInterrupts,
456
+ resumeFromCheckpoint,
457
+ rewindFrom
458
+ };
@@ -0,0 +1,98 @@
1
+ import type { AddFilesResult, Condition, Document, Hit, LengthRange } from "./types.ts";
2
+ /** A document with its date as an ISO string, such as "2024-01-01T00:00:00.000Z". */
3
+ export type JsonDocument = Omit<Document, "createdAt"> & {
4
+ createdAt?: string;
5
+ };
6
+ /** A hit without the document's text. `excerpt` holds the part that matched. */
7
+ export type JsonHit = Omit<Hit, "document"> & {
8
+ document: Omit<JsonDocument, "text">;
9
+ };
10
+ /** The dates of a filter as ISO strings. */
11
+ export type JsonDateRange = {
12
+ after?: string;
13
+ before?: string;
14
+ };
15
+ export type JsonCondition = Omit<Condition, "date"> & {
16
+ date?: JsonDateRange;
17
+ };
18
+ /** Each optional field may also be null. Agency has one nothing-value, so a field it leaves out arrives as null. */
19
+ type OrNull<T> = {
20
+ [K in keyof T]: undefined extends T[K] ? T[K] | null : T[K];
21
+ };
22
+ /** A document as Agency sends it. */
23
+ export type AgencyDocument = OrNull<JsonDocument>;
24
+ /** A filter as Agency sends it: one condition, with null for every field it leaves out. */
25
+ export type AgencyCondition = OrNull<Omit<JsonCondition, "date" | "lengthChars">> & {
26
+ date?: OrNull<JsonDateRange> | null;
27
+ lengthChars?: OrNull<LengthRange> | null;
28
+ };
29
+ /** Where the embedding model runs. Empty for a store with no model. */
30
+ export type RunsOn = "local" | "hosted" | "";
31
+ /** What every interrupt shows about a store. `store` is absolute. `embeddingModel` is "" for a store with none. */
32
+ export type StoreInfo = {
33
+ store: string;
34
+ embeddingModel: string;
35
+ runsOn: RunsOn;
36
+ };
37
+ /** What `add` shows before it writes. `replaces` counts the documents whose ids the store already holds. */
38
+ export type AddInfo = StoreInfo & {
39
+ replaces: number;
40
+ };
41
+ /** A file `addFiles` will read: the path the glob matched, and the folder and name of the file it really is. */
42
+ export type ChangedFile = {
43
+ path: string;
44
+ dir: string;
45
+ filename: string;
46
+ };
47
+ /**
48
+ * What `planStoreFiles` found, and everything `loadStoreFiles` needs to read
49
+ * the changed files. `replaces` counts the changed files the store has
50
+ * loaded before.
51
+ */
52
+ export type StoreFilesPlan = StoreInfo & {
53
+ files: number;
54
+ changed: ChangedFile[];
55
+ replaces: number;
56
+ skipped: number;
57
+ unreadable: string[];
58
+ };
59
+ export declare function describeStore(store: string, base: string): Promise<StoreInfo>;
60
+ /** Checks that `createStoreAt` can create a store here with this model, and creates nothing. */
61
+ export declare function describeNewStore(store: string, embeddingModel: string, base: string): Promise<StoreInfo>;
62
+ /** `describeStore`, with how many of the documents would replace one the store holds. Loads the store to find out. */
63
+ export declare function describeAdd(store: string, documents: AgencyDocument[], base: string): Promise<AddInfo>;
64
+ export declare function createStoreAt(store: string, embeddingModel: string): Promise<{
65
+ store: string;
66
+ }>;
67
+ /** `approved` is what the caller approved: the store, its embedding model and where the model runs. A store that no longer matches fails. */
68
+ export declare function searchStore(approved: StoreInfo, query: string, limit: number, filter: AgencyCondition | null): Promise<JsonHit[]>;
69
+ export declare function getStoredDocuments(store: string, ids: string[]): Promise<JsonDocument[]>;
70
+ export declare function storeStats(store: string): Promise<{
71
+ documents: number;
72
+ files: number;
73
+ bytes: number;
74
+ embeddingModel: string;
75
+ }>;
76
+ /** `approved` is what the caller approved: the store, its embedding model and where the model runs. A store that no longer matches fails. */
77
+ export declare function addDocuments(approved: StoreInfo, documents: AgencyDocument[]): Promise<{
78
+ documents: number;
79
+ }>;
80
+ export declare function removeDocuments(store: string, ids: string[]): Promise<{
81
+ removed: number;
82
+ }>;
83
+ /** Lists and compares the files the globs match. Reads no file's contents and writes nothing. A relative glob starts at `base`. */
84
+ export declare function planStoreFiles(store: string, globs: string[], base: string): Promise<StoreFilesPlan>;
85
+ /**
86
+ * Reads the plan's changed files and no others. A file that changed after the
87
+ * plan waits for the next plan. Fails when a file now points somewhere other
88
+ * than the real path approved, or when the store's embedding model is no
89
+ * longer what the plan says. A plan with nothing changed opens no store.
90
+ */
91
+ export declare function loadStoreFiles(plan: StoreFilesPlan): Promise<AddFilesResult>;
92
+ /** A filter from Agency as a Condition. A null field means the field was not given, except inside `meta`, where null is a value. */
93
+ export declare function toCondition(filter: AgencyCondition): Condition;
94
+ /** A document from Agency as a Document. A null field means the field was not given. */
95
+ export declare function toDocument(document: AgencyDocument): Document;
96
+ export declare function toJsonDocument(document: Document): JsonDocument;
97
+ export declare function toJsonHit(hit: Hit): JsonHit;
98
+ export {};