@r_masseater/masseater-utils 0.2.1 → 0.3.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.
- package/README.md +13 -10
- package/dist/client-BS-MCJ0I.mjs +39695 -0
- package/dist/client-BS-MCJ0I.mjs.map +1 -0
- package/dist/model-server/process.d.mts +1 -0
- package/dist/model-server/process.mjs +6532 -0
- package/dist/model-server/process.mjs.map +1 -0
- package/dist/model-server.d.mts +5126 -0
- package/dist/model-server.mjs +336 -0
- package/dist/model-server.mjs.map +1 -0
- package/package.json +6 -2
- package/skills/use-model-server/SKILL.md +50 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { $n as fail, $o as orElse, Aa as makeUnsafe$1, Br as runForkWith, Co as take, Ea as done, Es as dual, Ga as scopeRemoveFinalizerUnsafe, Go as getOrElse, Gr as runSync, Hr as runPromiseExit, Ia as fiberEnterUninterruptibleUnsafe, Jn as context, Jr as runSyncWith, K as startServer, Kr as runSyncExit, Lr as runCallback, Mn as runIn, Mr as provideService, Or as orDie, Qi as void_$1, Qo as none, Qr as succeed, Rr as runCallbackWith, So as map, St as TaggedError, Ta as _await, Ur as runPromiseExitWith, Vn as cached, Vr as runPromise, Wo as fromNullishOr, Wr as runPromiseWith, Xn as die, Xo as map$1, Yo as liftPredicate, Z as NonEmptyString, Zn as ensuring, Zo as match, _a as forkUnsafe, aa as makeMemoMapUnsafe, ai as timeout, ar as forEach, br as map$2, ct as layer, do as millis, ea as buildWithMemoMap, es as some, ha as close, hi as withFiber, ho as chunksOf, in as Path, ir as fnUntraced, jo as Reference, jr as provideContext, kn as await_, kr as orElseSucceed, ks as pipe, n as withClient, ni as tap, nr as flatMap, pi as void_, qr as runSyncExitWith, rr as flatten, rt as option, t as probe, ti as sync, ur as gen, wo as zipWith, xo as join, ya as makeUnsafe, yo as flatten$1, yt as String, zr as runFork } from "./client-BS-MCJ0I.mjs";
|
|
2
|
+
globalThis.Number;
|
|
3
|
+
/**
|
|
4
|
+
* Provides a multiplication operation on `number`s.
|
|
5
|
+
*
|
|
6
|
+
* **When to use**
|
|
7
|
+
*
|
|
8
|
+
* Use to multiply two numbers.
|
|
9
|
+
*
|
|
10
|
+
* **Example** (Multiplying numbers)
|
|
11
|
+
*
|
|
12
|
+
* ```ts import.meta.vitest
|
|
13
|
+
* import { Number } from "effect"
|
|
14
|
+
*
|
|
15
|
+
* Number.multiply(2, 3) // => 6
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @see {@link multiplyAll} for multiplying an iterable of numbers
|
|
19
|
+
*
|
|
20
|
+
* @stability stable
|
|
21
|
+
* @category math
|
|
22
|
+
* @since 2.0.0
|
|
23
|
+
*/
|
|
24
|
+
const multiply = /*#__PURE__*/ dual(2, (self, that) => self * that);
|
|
25
|
+
/**
|
|
26
|
+
* Takes an `Iterable` of `number`s and returns their sum as a single `number`.
|
|
27
|
+
*
|
|
28
|
+
* **When to use**
|
|
29
|
+
*
|
|
30
|
+
* Use to sum all numbers in an iterable.
|
|
31
|
+
*
|
|
32
|
+
* **Example** (Summing an iterable)
|
|
33
|
+
*
|
|
34
|
+
* ```ts import.meta.vitest
|
|
35
|
+
* import { Number } from "effect"
|
|
36
|
+
*
|
|
37
|
+
* Number.sumAll([2, 3, 4]) // => 9
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* @see {@link sum} for adding two numbers
|
|
41
|
+
* @see {@link ReducerSum} for summing through APIs that consume a `Reducer`
|
|
42
|
+
*
|
|
43
|
+
* @stability stable
|
|
44
|
+
* @category math
|
|
45
|
+
* @since 2.0.0
|
|
46
|
+
*/
|
|
47
|
+
const sumAll = (collection) => {
|
|
48
|
+
let out = 0;
|
|
49
|
+
for (const n of collection) out += n;
|
|
50
|
+
return out;
|
|
51
|
+
};
|
|
52
|
+
// ../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/ManagedRuntime.js
|
|
53
|
+
/**
|
|
54
|
+
* Runs many effects against services built once from a `Layer`.
|
|
55
|
+
*
|
|
56
|
+
* A `ManagedRuntime` builds the services from a layer, keeps those services
|
|
57
|
+
* available for repeated effect runs, and releases acquired resources when it
|
|
58
|
+
* is disposed. This module includes the runtime type, a constructor, a guard,
|
|
59
|
+
* and runners for connecting Effect programs to JavaScript entry points such as
|
|
60
|
+
* promises, callbacks, and synchronous code.
|
|
61
|
+
*
|
|
62
|
+
* @stability stable
|
|
63
|
+
* @since 2.0.0
|
|
64
|
+
*/
|
|
65
|
+
const TypeId = "~effect/ManagedRuntime";
|
|
66
|
+
const DisposingRuntimes = /*#__PURE__*/ Reference("effect/ManagedRuntime/DisposingRuntimes", { defaultValue: () => /* @__PURE__ */ new Set() });
|
|
67
|
+
/**
|
|
68
|
+
* Creates a `ManagedRuntime` from a layer.
|
|
69
|
+
*
|
|
70
|
+
* **When to use**
|
|
71
|
+
*
|
|
72
|
+
* Use to create a reusable runtime from a `Layer` for application entry points
|
|
73
|
+
* or integration code that runs many effects without rebuilding services.
|
|
74
|
+
*
|
|
75
|
+
* **Details**
|
|
76
|
+
*
|
|
77
|
+
* The layer is built lazily on first use and its context is cached for
|
|
78
|
+
* subsequent runs. Resources acquired by the layer are owned by the runtime and
|
|
79
|
+
* are released when `dispose` or `disposeEffect` is run. `options.memoMap` can
|
|
80
|
+
* be used to share layer memoization with other layer builds.
|
|
81
|
+
*
|
|
82
|
+
* **Gotchas**
|
|
83
|
+
*
|
|
84
|
+
* Dispose the runtime when it is no longer needed. A runtime cannot be reused
|
|
85
|
+
* after disposal.
|
|
86
|
+
*
|
|
87
|
+
* A failed layer build is also cached: subsequent runs return the same build
|
|
88
|
+
* failure without rebuilding the layer. For transient failures, retry inside
|
|
89
|
+
* the layer before passing it to `make`, or dispose the runtime and create a
|
|
90
|
+
* new one to attempt a fresh build.
|
|
91
|
+
*
|
|
92
|
+
* **Example** (Creating a managed runtime)
|
|
93
|
+
*
|
|
94
|
+
* ```ts import.meta.vitest
|
|
95
|
+
* import { Context, Effect, Layer, ManagedRuntime } from "effect"
|
|
96
|
+
*
|
|
97
|
+
* const notifications: Array<string> = []
|
|
98
|
+
*
|
|
99
|
+
* class Notifications extends Context.Service<Notifications, {
|
|
100
|
+
* readonly notify: (message: string) => Effect.Effect<void>
|
|
101
|
+
* }>()("Notifications") {
|
|
102
|
+
* static readonly layer = Layer.succeed(this)({
|
|
103
|
+
* notify: Effect.fn("Notifications.notify")((message) =>
|
|
104
|
+
* Effect.sync(() => notifications.push(message))
|
|
105
|
+
* )
|
|
106
|
+
* })
|
|
107
|
+
* }
|
|
108
|
+
*
|
|
109
|
+
* const runtime = ManagedRuntime.make(Notifications.layer)
|
|
110
|
+
*
|
|
111
|
+
* const program = Effect.flatMap(
|
|
112
|
+
* Notifications,
|
|
113
|
+
* (_) => _.notify("Hello, world!")
|
|
114
|
+
* ).pipe(Effect.ensuring(runtime.disposeEffect))
|
|
115
|
+
*
|
|
116
|
+
* await runtime.runPromise(program)
|
|
117
|
+
* notifications // => ["Hello, world!"]
|
|
118
|
+
* ```
|
|
119
|
+
*
|
|
120
|
+
* @see {@link ManagedRuntime} for the returned runtime interface
|
|
121
|
+
* @see {@link Layer.MemoMap} for shared layer memoization
|
|
122
|
+
* @see {@link Layer.build} for lower-level scoped layer construction
|
|
123
|
+
*
|
|
124
|
+
* @stability stable
|
|
125
|
+
* @category constructors
|
|
126
|
+
* @since 2.0.0
|
|
127
|
+
*/
|
|
128
|
+
const make = (layer, options) => {
|
|
129
|
+
const memoMap = options?.memoMap ?? makeMemoMapUnsafe();
|
|
130
|
+
const scope = makeUnsafe("sequential");
|
|
131
|
+
const layerScope = forkUnsafe(scope, "sequential");
|
|
132
|
+
const fiberScope = forkUnsafe(scope, "parallel");
|
|
133
|
+
const managedFibers = /* @__PURE__ */ new WeakSet();
|
|
134
|
+
const disposingFibers = /* @__PURE__ */ new WeakSet();
|
|
135
|
+
const defaultRunOptions = { onFiberStart(fiber) {
|
|
136
|
+
managedFibers.add(fiber);
|
|
137
|
+
if (disposingFibers.has(fiber)) return;
|
|
138
|
+
runIn(fiber, fiberScope);
|
|
139
|
+
} };
|
|
140
|
+
const mergeRunOptions = (options) => options ? {
|
|
141
|
+
...options,
|
|
142
|
+
onFiberStart: options.onFiberStart ? (fiber) => {
|
|
143
|
+
defaultRunOptions.onFiberStart(fiber);
|
|
144
|
+
options.onFiberStart(fiber);
|
|
145
|
+
} : defaultRunOptions.onFiberStart
|
|
146
|
+
} : defaultRunOptions;
|
|
147
|
+
let buildFiber;
|
|
148
|
+
let disposed;
|
|
149
|
+
const contextEffect = withFiber((fiber) => {
|
|
150
|
+
if (!buildFiber) buildFiber = runFork(tap(buildWithMemoMap(layer, memoMap, layerScope), (context) => sync(() => {
|
|
151
|
+
self.cachedContext = context;
|
|
152
|
+
})), {
|
|
153
|
+
scheduler: fiber.cache.scheduler,
|
|
154
|
+
onFiberStart(fiber) {
|
|
155
|
+
managedFibers.add(fiber);
|
|
156
|
+
runIn(fiber, fiberScope);
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
return flatten(await_(buildFiber));
|
|
160
|
+
});
|
|
161
|
+
const self = {
|
|
162
|
+
[TypeId]: TypeId,
|
|
163
|
+
memoMap,
|
|
164
|
+
scope,
|
|
165
|
+
contextEffect,
|
|
166
|
+
cachedContext: void 0,
|
|
167
|
+
context() {
|
|
168
|
+
return self.cachedContext === void 0 ? runPromise(self.contextEffect) : Promise.resolve(self.cachedContext);
|
|
169
|
+
},
|
|
170
|
+
dispose() {
|
|
171
|
+
return runPromise(self.disposeEffect);
|
|
172
|
+
},
|
|
173
|
+
[Symbol.asyncDispose]() {
|
|
174
|
+
return self.dispose();
|
|
175
|
+
},
|
|
176
|
+
disposeEffect: withFiber((fiber) => {
|
|
177
|
+
if (disposed !== void 0) {
|
|
178
|
+
if (fiber.getRef(DisposingRuntimes).has(self)) return void_;
|
|
179
|
+
for (let current = fiber; current; current = current._parent) if (managedFibers.has(current)) return void_;
|
|
180
|
+
return _await(disposed);
|
|
181
|
+
}
|
|
182
|
+
fiberEnterUninterruptibleUnsafe(fiber);
|
|
183
|
+
const done$1 = disposed = makeUnsafe$1();
|
|
184
|
+
for (let current = fiber; current; current = current._parent) {
|
|
185
|
+
disposingFibers.add(current);
|
|
186
|
+
scopeRemoveFinalizerUnsafe(fiberScope, current);
|
|
187
|
+
}
|
|
188
|
+
self.contextEffect = die("ManagedRuntime disposed");
|
|
189
|
+
self.cachedContext = void 0;
|
|
190
|
+
return close(self.scope, void_$1).pipe(provideService(DisposingRuntimes, new Set(fiber.getRef(DisposingRuntimes)).add(self)), ensuring(done(done$1, void_$1)));
|
|
191
|
+
}),
|
|
192
|
+
runFork(effect, options) {
|
|
193
|
+
return self.cachedContext === void 0 ? runFork(provide(self, effect), mergeRunOptions(options)) : runForkWith(self.cachedContext)(effect, mergeRunOptions(options));
|
|
194
|
+
},
|
|
195
|
+
runCallback(effect, options) {
|
|
196
|
+
return self.cachedContext === void 0 ? runCallback(provide(self, effect), mergeRunOptions(options)) : runCallbackWith(self.cachedContext)(effect, mergeRunOptions(options));
|
|
197
|
+
},
|
|
198
|
+
runSyncExit(effect) {
|
|
199
|
+
return self.cachedContext === void 0 ? runSyncExit(provide(self, effect)) : runSyncExitWith(self.cachedContext)(effect);
|
|
200
|
+
},
|
|
201
|
+
runSync(effect) {
|
|
202
|
+
return self.cachedContext === void 0 ? runSync(provide(self, effect)) : runSyncWith(self.cachedContext)(effect);
|
|
203
|
+
},
|
|
204
|
+
runPromiseExit(effect, options) {
|
|
205
|
+
return self.cachedContext === void 0 ? runPromiseExit(provide(self, effect), mergeRunOptions(options)) : runPromiseExitWith(self.cachedContext)(effect, mergeRunOptions(options));
|
|
206
|
+
},
|
|
207
|
+
runPromise(effect, options) {
|
|
208
|
+
return self.cachedContext === void 0 ? runPromise(provide(self, effect), mergeRunOptions(options)) : runPromiseWith(self.cachedContext)(effect, mergeRunOptions(options));
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
return self;
|
|
212
|
+
};
|
|
213
|
+
function provide(managed, effect) {
|
|
214
|
+
return flatMap(managed.contextEffect, (context) => provideContext(effect, context));
|
|
215
|
+
}
|
|
216
|
+
// src/entities/embedding/model/text.ts
|
|
217
|
+
const SEARCH_TASK = "search result";
|
|
218
|
+
const NO_TITLE = "none";
|
|
219
|
+
const EMPTY = 0;
|
|
220
|
+
const ARITY = 2;
|
|
221
|
+
const asQuery = (text) => `task: ${SEARCH_TASK} | query: ${text}`;
|
|
222
|
+
const asDocument = ({ text, title = NO_TITLE }) => `title: ${title} | text: ${text}`;
|
|
223
|
+
const dot = dual(ARITY, (left, right) => sumAll(zipWith(left, right, multiply)));
|
|
224
|
+
const normalize = (vector) => pipe(Math.sqrt(dot(vector, vector)), liftPredicate((length) => length > EMPTY), match({
|
|
225
|
+
onNone: () => vector,
|
|
226
|
+
onSome: (length) => pipe(vector, map((value) => value / length))
|
|
227
|
+
}));
|
|
228
|
+
const truncate = dual(ARITY, (vector, dimensions) => normalize(take(vector, dimensions)));
|
|
229
|
+
// src/shared/lib/cache.ts
|
|
230
|
+
const taggedError = TaggedError;
|
|
231
|
+
var CacheRootError = class extends taggedError()("CacheRootError", { message: String }) {};
|
|
232
|
+
const SEPARATOR = "/";
|
|
233
|
+
const CACHE_DIRECTORY_NAME = ".cache";
|
|
234
|
+
const variable$1 = (name) => option(NonEmptyString(name)).pipe(orElseSucceed(none));
|
|
235
|
+
const baseDirectory = gen(function* baseDirectory() {
|
|
236
|
+
const cacheHome = yield* variable$1("XDG_CACHE_HOME");
|
|
237
|
+
const home = yield* variable$1("HOME");
|
|
238
|
+
const profile = yield* variable$1("USERPROFILE");
|
|
239
|
+
return pipe(cacheHome, orElse(() => pipe(orElse(home, () => profile), map$1((directory) => `${directory}${SEPARATOR}${CACHE_DIRECTORY_NAME}`))));
|
|
240
|
+
});
|
|
241
|
+
const cacheRootEffect = (segments) => baseDirectory.pipe(flatMap(match({
|
|
242
|
+
onNone: () => fail(CacheRootError.make({ message: "set XDG_CACHE_HOME or HOME" })),
|
|
243
|
+
onSome: (base) => succeed(pipe([base, ...segments], join(SEPARATOR)))
|
|
244
|
+
})));
|
|
245
|
+
// src/shared/api/model-server/location.ts
|
|
246
|
+
const PROTOCOL_VERSION = 1;
|
|
247
|
+
const NAME = "model-server";
|
|
248
|
+
const FALLBACK_TEMPORARY = "/tmp";
|
|
249
|
+
const FALLBACK_USER = "user";
|
|
250
|
+
const variable = (name) => option(NonEmptyString(name)).pipe(orElseSucceed(none));
|
|
251
|
+
const userId = () => pipe(fromNullishOr(globalThis.process.getuid), map$1((read) => `${read.call(globalThis.process)}`), getOrElse(() => FALLBACK_USER));
|
|
252
|
+
const defaultSocket = fnUntraced(function* defaultSocket() {
|
|
253
|
+
const path = yield* Path;
|
|
254
|
+
const temporary = yield* variable("TMPDIR");
|
|
255
|
+
return path.join(getOrElse(temporary, () => FALLBACK_TEMPORARY), `${NAME}-${userId()}`, `v${PROTOCOL_VERSION}.sock`);
|
|
256
|
+
});
|
|
257
|
+
/** @internal */
|
|
258
|
+
const resolveLocation = fnUntraced(function* resolveLocation(options) {
|
|
259
|
+
return {
|
|
260
|
+
socket: yield* match(fromNullishOr(options.socket), {
|
|
261
|
+
onNone: defaultSocket,
|
|
262
|
+
onSome: succeed
|
|
263
|
+
}),
|
|
264
|
+
cache: yield* match(fromNullishOr(options.cache), {
|
|
265
|
+
onNone: () => cacheRootEffect([NAME]),
|
|
266
|
+
onSome: succeed
|
|
267
|
+
})
|
|
268
|
+
};
|
|
269
|
+
});
|
|
270
|
+
// src/app/model-server.ts
|
|
271
|
+
const EMBEDDING_GEMMA_2 = {
|
|
272
|
+
model: "onnx-community/embeddinggemma-2-ONNX",
|
|
273
|
+
dtype: "q4",
|
|
274
|
+
dimensions: 768
|
|
275
|
+
};
|
|
276
|
+
const DEFAULT_TIMEOUT_MILLIS = 3e4;
|
|
277
|
+
const DEFAULT_IDLE_MILLIS = 9e5;
|
|
278
|
+
const DEFAULT_MAX_TOKENS = 512;
|
|
279
|
+
const DEFAULT_BATCH_SIZE = 8;
|
|
280
|
+
const SERVER_ENTRY = "@r_masseater/masseater-utils/model-server/process";
|
|
281
|
+
const node = make(layer);
|
|
282
|
+
const serverEntry = fnUntraced(function* serverEntry() {
|
|
283
|
+
return yield* (yield* Path).fromFileUrl(new URL(import.meta.resolve(SERVER_ENTRY)));
|
|
284
|
+
});
|
|
285
|
+
const callServer = fnUntraced(function* callServer(options, use) {
|
|
286
|
+
const location = yield* resolveLocation(options);
|
|
287
|
+
const server = yield* serverEntry();
|
|
288
|
+
const services = yield* context();
|
|
289
|
+
const start = yield* cached(startServer(location, {
|
|
290
|
+
server,
|
|
291
|
+
idleMillis: options.idleMillis ?? DEFAULT_IDLE_MILLIS,
|
|
292
|
+
engine: fromNullishOr(options.engine)
|
|
293
|
+
}).pipe(provideContext(services), orDie));
|
|
294
|
+
return yield* withClient({
|
|
295
|
+
socket: location.socket,
|
|
296
|
+
onOpenError: some(start),
|
|
297
|
+
use
|
|
298
|
+
});
|
|
299
|
+
});
|
|
300
|
+
const using = (options, use) => {
|
|
301
|
+
const timeout$1 = millis(options.timeoutMillis ?? DEFAULT_TIMEOUT_MILLIS);
|
|
302
|
+
return node.runPromise(callServer(options, use).pipe(timeout(timeout$1)));
|
|
303
|
+
};
|
|
304
|
+
const keyOf = (options) => ({
|
|
305
|
+
model: options.model ?? EMBEDDING_GEMMA_2.model,
|
|
306
|
+
dtype: options.dtype ?? EMBEDDING_GEMMA_2.dtype
|
|
307
|
+
});
|
|
308
|
+
const embed = (options) => {
|
|
309
|
+
const key = keyOf(options);
|
|
310
|
+
const maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
311
|
+
const toDimensions = truncate(options.dimensions ?? EMBEDDING_GEMMA_2.dimensions);
|
|
312
|
+
const batches = chunksOf(options.texts, options.batchSize ?? DEFAULT_BATCH_SIZE);
|
|
313
|
+
const flatten = (vectors) => pipe(vectors, flatten$1, map(toDimensions));
|
|
314
|
+
const embedAll = (client) => {
|
|
315
|
+
const embedBatch = (texts) => client.Embed({
|
|
316
|
+
...key,
|
|
317
|
+
texts,
|
|
318
|
+
maxTokens
|
|
319
|
+
});
|
|
320
|
+
return forEach(batches, embedBatch, { concurrency: 1 }).pipe(map$2(flatten));
|
|
321
|
+
};
|
|
322
|
+
return using(options, embedAll);
|
|
323
|
+
};
|
|
324
|
+
const prepare = (options) => using(options, (client) => client.Load(keyOf(options)));
|
|
325
|
+
const warm = (options) => using(options, (client) => client.Warm(keyOf(options)));
|
|
326
|
+
const stateOf = (found) => match(found, {
|
|
327
|
+
onNone: () => ({ running: false }),
|
|
328
|
+
onSome: (running) => ({
|
|
329
|
+
running: true,
|
|
330
|
+
...running
|
|
331
|
+
})
|
|
332
|
+
});
|
|
333
|
+
const status = (options) => node.runPromise(resolveLocation(options).pipe(flatMap((location) => probe(location.socket)), map$2(stateOf)));
|
|
334
|
+
export { EMBEDDING_GEMMA_2, asDocument, asQuery, dot, embed, prepare, status, warm };
|
|
335
|
+
|
|
336
|
+
//# sourceMappingURL=model-server.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-server.mjs","names":["Layer.makeMemoMapUnsafe","Scope.makeUnsafe","Scope.forkUnsafe","Effect.withFiber","Effect.runFork","Effect.tap","Layer.buildWithMemoMap","Effect.sync","Effect.flatten","Fiber.await","Effect.runPromise","Effect.void","Deferred.await","done","Deferred.makeUnsafe","Effect.die","Scope.close","Exit.void","Effect.provideService","Effect.ensuring","Deferred.done","Effect.runForkWith","Effect.runCallback","Effect.runCallbackWith","Effect.runSyncExit","Effect.runSyncExitWith","Effect.runSync","Effect.runSyncWith","Effect.runPromiseExit","Effect.runPromiseExitWith","Effect.runPromiseWith","Effect.flatMap","Effect.provideContext","Fn.dual","Num.sumAll","Arr.zipWith","Num.multiply","Option.liftPredicate","Option.match","Arr.map","Arr.take","Schema.TaggedError","Schema.String","variable","Config.option","Config.NonEmptyString","Effect.orElseSucceed","Option.none","Effect.gen","Option.orElse","Option.map","Effect.flatMap","Option.match","Effect.fail","Effect.succeed","Arr.join","Config.option","Config.NonEmptyString","Effect.orElseSucceed","Option.none","Option.fromNullishOr","Option.map","Option.getOrElse","Effect.fnUntraced","Path.Path","Option.match","Effect.succeed","ManagedRuntime.make","nodeServices","Effect.fnUntraced","Path.Path","Effect.context","Effect.cached","Option.fromNullishOr","Effect.provideContext","Effect.orDie","Option.some","timeout","Duration.millis","Effect.timeout","Arr.chunksOf","Arr.flatten","Arr.map","Effect.forEach","Effect.map","Option.match","Effect.flatMap"],"sources":["../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Number.js","../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/ManagedRuntime.js","../src/entities/embedding/model/text.ts","../src/shared/lib/cache.ts","../src/shared/api/model-server/location.ts","../src/app/model-server.ts"],"sourcesContent":["/**\n * Works with TypeScript `number` values.\n *\n * This module exposes the native `Number` constructor together with helpers for\n * checking, parsing, arithmetic, safe division, comparison, range checks,\n * clamping, rounding, ordering, equivalence, and numeric aggregation.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Equ from \"./Equivalence.js\";\nimport { dual } from \"./Function.js\";\nimport * as Option from \"./Option.js\";\nimport * as order from \"./Order.js\";\nimport * as predicate from \"./Predicate.js\";\nimport * as Reducer from \"./Reducer.js\";\n/**\n * Exposes the global number constructor.\n *\n * **When to use**\n *\n * Use to access native JavaScript numeric coercion from the Effect module\n * namespace.\n *\n * **Gotchas**\n *\n * This follows native `Number` coercion rules, including empty strings\n * becoming `0` and invalid numeric strings becoming `NaN`.\n *\n * @see {@link parse} for parsing strings into an `Option`\n *\n * **Example** (Coercing values to numbers)\n *\n * ```ts import.meta.vitest\n * import { Number as N } from \"effect\"\n *\n * N.Number(\"42\") // => 42\n * N.Number(\"3.14\") // => 3.14\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const Number = globalThis.Number;\n/**\n * Checks whether a value is a `number`.\n *\n * **When to use**\n *\n * Use to validate unknown input and narrow it to `number`.\n *\n * **Example** (Checking for numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isNumber(2) // => true\n * Number.isNumber(\"2\") // => false\n * ```\n *\n * @stability stable\n * @category guards\n * @since 2.0.0\n */\nexport const isNumber = predicate.isNumber;\n/**\n * Provides an addition operation on `number`s.\n *\n * **When to use**\n *\n * Use to add two numbers.\n *\n * **Example** (Adding numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.sum(2, 3) // => 5\n * ```\n *\n * @see {@link sumAll} for summing an iterable of numbers\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const sum = /*#__PURE__*/dual(2, (self, that) => self + that);\n/**\n * Provides a multiplication operation on `number`s.\n *\n * **When to use**\n *\n * Use to multiply two numbers.\n *\n * **Example** (Multiplying numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.multiply(2, 3) // => 6\n * ```\n *\n * @see {@link multiplyAll} for multiplying an iterable of numbers\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const multiply = /*#__PURE__*/dual(2, (self, that) => self * that);\n/**\n * Provides a subtraction operation on `number`s.\n *\n * **When to use**\n *\n * Use to subtract one number from another.\n *\n * **Example** (Subtracting numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.subtract(2, 3) // => -1\n * ```\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const subtract = /*#__PURE__*/dual(2, (self, that) => self - that);\n/**\n * Divides `number`s safely, returning `Option.none()` if the divisor is `0`.\n *\n * **When to use**\n *\n * Use to divide numbers while representing division by zero as `Option.none`.\n *\n * **Example** (Dividing numbers safely)\n *\n * ```ts import.meta.vitest\n * import { Number, Option } from \"effect\"\n *\n * Number.divide(6, 3) // => Option.some(2)\n * Number.divide(6, 0) // => Option.none()\n * ```\n *\n * @see {@link divideUnsafe} for division that throws when the divisor is zero\n * @see {@link remainder} for the numeric remainder operation\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const divide = /*#__PURE__*/dual(2, (self, that) => that === 0 ? Option.none() : Option.some(self / that));\n/**\n * Divides two `number` values without returning an `Option`.\n *\n * **When to use**\n *\n * Use to divide `number` values where the divisor is known to be non-zero and\n * a plain `number` result is preferred over handling `Option.none`.\n *\n * **Gotchas**\n *\n * Throws a `RangeError` if the divisor is `0`.\n *\n * **Example** (Dividing numbers unsafely)\n *\n * ```ts import.meta.vitest\n * import { Number, Result } from \"effect\"\n *\n * Number.divideUnsafe(6, 3) // => 2\n *\n * const failure = Result.try({\n * try: () => Number.divideUnsafe(6, 0),\n * catch: (error) => (error as Error).message\n * })\n * Result.merge(failure) // => \"Division by zero\"\n * ```\n *\n * @see {@link divide} for division that returns `Option.none` when the divisor is zero\n *\n * @stability stable\n * @category math\n * @since 4.0.0\n */\nexport const divideUnsafe = /*#__PURE__*/dual(2, (self, that) => Option.getOrThrowWith(divide(self, that), () => new RangeError(\"Division by zero\")));\n/**\n * Returns the result of adding `1` to a given number.\n *\n * **When to use**\n *\n * Use to increment a numeric counter by one.\n *\n * **Example** (Incrementing a number)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.increment(2) // => 3\n * ```\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const increment = n => n + 1;\n/**\n * Decrements a number by `1`.\n *\n * **When to use**\n *\n * Use to decrement a numeric counter by one.\n *\n * **Example** (Decrementing a number)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.decrement(3) // => 2\n * ```\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const decrement = n => n - 1;\n/**\n * Order instance for `number` values.\n *\n * **When to use**\n *\n * Use when you need to sort or compare numbers through APIs that accept an\n * ordering instance.\n *\n * **Example** (Comparing numbers)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.Order(1, 2) // => -1\n * Number.Order(2, 1) // => 1\n * Number.Order(1, 1) // => 0\n * ```\n *\n * @stability stable\n * @category instances\n * @since 2.0.0\n */\nexport const Order = order.Number;\n/**\n * Equivalence instance for numbers where `NaN` is considered equal to `NaN`.\n *\n * **When to use**\n *\n * Use when checking numeric equality through APIs that accept an equivalence\n * relation.\n *\n * **Example** (Comparing numbers for equivalence)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.Equivalence(1, 1) // => true\n * Number.Equivalence(1, 2) // => false\n * Number.Equivalence(NaN, NaN) // => true\n * ```\n *\n * @stability stable\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence = Equ.Number;\n/**\n * Returns `true` if the first argument is less than the second, otherwise `false`.\n *\n * **When to use**\n *\n * Use to test whether one number is strictly less than another.\n *\n * **Example** (Checking less-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isLessThan(2, 3) // => true\n * Number.isLessThan(3, 3) // => false\n * Number.isLessThan(4, 3) // => false\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThan = /*#__PURE__*/order.isLessThan(Order);\n/**\n * Returns a function that checks if a given `number` is less than or equal to the provided one.\n *\n * **When to use**\n *\n * Use to test whether one number is less than or equal to another.\n *\n * **Example** (Checking less-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isLessThanOrEqualTo(2, 3) // => true\n * Number.isLessThanOrEqualTo(3, 3) // => true\n * Number.isLessThanOrEqualTo(4, 3) // => false\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 4.0.0\n */\nexport const isLessThanOrEqualTo = /*#__PURE__*/order.isLessThanOrEqualTo(Order);\n/**\n * Returns `true` if the first argument is greater than the second, otherwise `false`.\n *\n * **When to use**\n *\n * Use to test whether one number is strictly greater than another.\n *\n * **Example** (Checking greater-than comparisons)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isGreaterThan(2, 3) // => false\n * Number.isGreaterThan(3, 3) // => false\n * Number.isGreaterThan(4, 3) // => true\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThan = /*#__PURE__*/order.isGreaterThan(Order);\n/**\n * Returns a function that checks if a given `number` is greater than or equal to the provided one.\n *\n * **When to use**\n *\n * Use to test whether one number is greater than or equal to another.\n *\n * **Example** (Checking greater-than-or-equal comparisons)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.isGreaterThanOrEqualTo(2, 3) // => false\n * Number.isGreaterThanOrEqualTo(3, 3) // => true\n * Number.isGreaterThanOrEqualTo(4, 3) // => true\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 4.0.0\n */\nexport const isGreaterThanOrEqualTo = /*#__PURE__*/order.isGreaterThanOrEqualTo(Order);\n/**\n * Checks whether a `number` is between a `minimum` and `maximum` value (inclusive).\n *\n * **When to use**\n *\n * Use to test whether a number falls inside an inclusive range.\n *\n * **Example** (Checking inclusive ranges)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * const between = Number.between({ minimum: 0, maximum: 5 })\n *\n * between(3) // => true\n * between(-1) // => false\n * between(6) // => false\n * ```\n *\n * @see {@link clamp} for forcing a number into an inclusive range\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const between = /*#__PURE__*/order.isBetween(Order);\n/**\n * Restricts the given `number` to be within the range specified by the `minimum` and `maximum` values.\n *\n * **When to use**\n *\n * Use to force a number into an inclusive range.\n *\n * **Details**\n *\n * - If the `number` is less than the `minimum` value, the function returns the `minimum` value.\n * - If the `number` is greater than the `maximum` value, the function returns the `maximum` value.\n * - Otherwise, it returns the original `number`.\n * - `NaN` is ordered below every non-`NaN` number by `Number.Order`, so it is\n * clamped to `minimum`.\n *\n * **Example** (Clamping to a range)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * const clamp = Number.clamp({ minimum: 1, maximum: 5 })\n *\n * clamp(3) // => 3\n * clamp(0) // => 1\n * clamp(6) // => 5\n * ```\n *\n * @see {@link between} for checking whether a number is already inside a range\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const clamp = /*#__PURE__*/order.clamp(Order);\n/**\n * Returns the minimum between two `number`s.\n *\n * **When to use**\n *\n * Use to select the smaller of two numbers.\n *\n * **Example** (Finding the minimum)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.min(2, 3) // => 2\n * ```\n *\n * @see {@link max} for selecting the larger value\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const min = /*#__PURE__*/order.min(Order);\n/**\n * Returns the maximum between two `number`s.\n *\n * **When to use**\n *\n * Use to select the larger of two numbers.\n *\n * **Example** (Finding the maximum)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.max(2, 3) // => 3\n * ```\n *\n * @see {@link min} for selecting the smaller value\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const max = /*#__PURE__*/order.max(Order);\n/**\n * Determines the sign of a given `number`.\n *\n * **When to use**\n *\n * Use to classify a number as negative, zero, or positive.\n *\n * **Example** (Determining the sign)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.sign(-5) // => -1\n * Number.sign(0) // => 0\n * Number.sign(5) // => 1\n * ```\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const sign = n => Order(n, 0);\n/**\n * Takes an `Iterable` of `number`s and returns their sum as a single `number`.\n *\n * **When to use**\n *\n * Use to sum all numbers in an iterable.\n *\n * **Example** (Summing an iterable)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.sumAll([2, 3, 4]) // => 9\n * ```\n *\n * @see {@link sum} for adding two numbers\n * @see {@link ReducerSum} for summing through APIs that consume a `Reducer`\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const sumAll = collection => {\n let out = 0;\n for (const n of collection) {\n out += n;\n }\n return out;\n};\n/**\n * Takes an `Iterable` of `number`s and returns their multiplication as a single `number`.\n *\n * **When to use**\n *\n * Use to multiply all numbers in an iterable.\n *\n * **Example** (Multiplying an iterable)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.multiplyAll([2, 3, 4]) // => 24\n * ```\n *\n * @see {@link multiply} for multiplying two numbers\n * @see {@link ReducerMultiply} for multiplying through APIs that consume a `Reducer`\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const multiplyAll = collection => {\n let out = 1;\n for (const n of collection) {\n if (n === 0) {\n return 0;\n }\n out *= n;\n }\n return out;\n};\n/**\n * Returns the remainder left over when one operand is divided by a second operand, always taking the sign of the dividend.\n *\n * **When to use**\n *\n * Use to compute a numeric remainder while preserving decimal precision better\n * than direct JavaScript `%` for decimal operands.\n *\n * **Example** (Calculating remainders)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.remainder(2, 2) // => 0\n * Number.remainder(3, 2) // => 1\n * Number.remainder(-4, 2) // => -0\n * ```\n *\n * @see {@link divide} for quotient calculation with division-by-zero represented as `Option.none`\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const remainder = /*#__PURE__*/dual(2, (self, divisor) => {\n if (!globalThis.Number.isFinite(self) || !globalThis.Number.isFinite(divisor) || divisor === 0) {\n return NaN;\n }\n if (globalThis.Number.isInteger(self) && globalThis.Number.isInteger(divisor)) {\n return self % divisor;\n }\n const [selfCoefficient, selfExponent] = toScientificInteger(self);\n const [divisorCoefficient, divisorExponent] = toScientificInteger(divisor);\n const exponent = Math.min(selfExponent, divisorExponent);\n const selfInteger = selfCoefficient * BigInt(10) ** BigInt(selfExponent - exponent);\n const divisorInteger = divisorCoefficient * BigInt(10) ** BigInt(divisorExponent - exponent);\n const out = selfInteger % divisorInteger;\n if (out === BigInt(0)) {\n return self < 0 || Object.is(self, -0) ? -0 : 0;\n }\n const remainder = globalThis.Number(`${out}e${exponent}`);\n return remainder === 0 ? Math.sign(self) * globalThis.Number.MIN_VALUE : remainder;\n});\nfunction toScientificInteger(n) {\n if (globalThis.Number.isInteger(n)) {\n return [BigInt(n), 0];\n }\n const scientific = Math.abs(n).toExponential();\n const eIndex = scientific.indexOf(\"e\");\n const digits = scientific.slice(0, eIndex).replace(\".\", \"\");\n const coefficient = BigInt(digits) * (n < 0 ? -BigInt(1) : BigInt(1));\n return [coefficient, globalThis.Number(scientific.slice(eIndex + 1)) - digits.length + 1];\n}\n/**\n * Returns the next power of 2 from the given number.\n *\n * **When to use**\n *\n * Use to round a number up to the next power of two.\n *\n * **Example** (Finding the next power of two)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.nextPow2(5) // => 8\n * Number.nextPow2(17) // => 32\n * ```\n *\n * @stability stable\n * @category math\n * @since 2.0.0\n */\nexport const nextPow2 = n => {\n const nextPow = Math.pow(2, Math.ceil(Math.log2(n)));\n return Math.max(nextPow < n ? nextPow * 2 : nextPow, 2);\n};\n/**\n * Parses a `number` from a `string` safely using the `Number()` function.\n * The following special string values are supported: \"NaN\", \"Infinity\", \"-Infinity\".\n *\n * **When to use**\n *\n * Use to parse numeric text without throwing on invalid input.\n *\n * **Example** (Parsing numbers from strings)\n *\n * ```ts import.meta.vitest\n * import { Number, Option } from \"effect\"\n *\n * Number.parse(\"42\") // => Option.some(42)\n * Number.parse(\"3.14\") // => Option.some(3.14)\n * Number.parse(\"NaN\") // => Option.some(NaN)\n * Number.parse(\"Infinity\") // => Option.some(Infinity)\n * Number.parse(\"-Infinity\") // => Option.some(-Infinity)\n * Number.parse(\"not a number\") // => Option.none()\n * ```\n *\n * @see {@link Number} for native constructor coercion\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const parse = s => {\n if (s === \"NaN\") {\n return Option.some(NaN);\n }\n if (s === \"Infinity\") {\n return Option.some(Infinity);\n }\n if (s === \"-Infinity\") {\n return Option.some(-Infinity);\n }\n if (s.trim() === \"\") {\n return Option.none();\n }\n const n = Number(s);\n return Number.isNaN(n) ? Option.none() : Option.some(n);\n};\n/**\n * Returns the number rounded with the given precision.\n *\n * **When to use**\n *\n * Use to round a number to a fixed number of decimal places.\n *\n * **Example** (Rounding with precision)\n *\n * ```ts import.meta.vitest\n * import { Number } from \"effect\"\n *\n * Number.round(1.1234, 2) // => 1.12\n * Number.round(1.567, 2) // => 1.57\n * ```\n *\n * @stability stable\n * @category math\n * @since 3.8.0\n */\nexport const round = /*#__PURE__*/dual(2, (self, precision) => {\n const factor = Math.pow(10, precision);\n return Math.round(self * factor) / factor;\n});\n/**\n * Reducer for combining `number`s using addition.\n *\n * **When to use**\n *\n * Use to sum many numbers through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `0`, so `combineAll([])` returns `0`.\n *\n * @see {@link sumAll} for summing an iterable directly\n * @see {@link ReducerMultiply} for multiplying number values\n *\n * @stability stable\n * @category math\n * @since 4.0.0\n */\nexport const ReducerSum = /*#__PURE__*/Reducer.make((a, b) => a + b, 0);\n/**\n * Reducer for combining `number`s using multiplication.\n *\n * **When to use**\n *\n * Use to multiply many numbers through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `1`, so reducing an empty collection returns `1`.\n *\n * **Gotchas**\n *\n * Reducing an iterable short-circuits when it sees `0`, so later elements are\n * not consumed.\n *\n * @see {@link multiplyAll} for multiplying an iterable directly\n *\n * @stability stable\n * @category math\n * @since 4.0.0\n */\nexport const ReducerMultiply = /*#__PURE__*/Reducer.make((a, b) => a * b, 1, collection => {\n let acc = 1;\n for (const n of collection) {\n if (n === 0) return 0;\n acc *= n;\n }\n return acc;\n});\n/**\n * Reducer for reducing `number`s by keeping the maximum value.\n *\n * **When to use**\n *\n * Use to keep the largest number through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `-Infinity`, so reducing an empty collection returns\n * `-Infinity`.\n *\n * **Gotchas**\n *\n * `NaN` values propagate through `Math.max`.\n *\n * @see {@link ReducerMin} for keeping the smallest number\n * @see {@link max} for comparing two numbers directly\n *\n * @stability stable\n * @category math\n * @since 4.0.0\n */\nexport const ReducerMax = /*#__PURE__*/Reducer.make((a, b) => Math.max(a, b), -Infinity);\n/**\n * Reducer for reducing `number`s by keeping the minimum value.\n *\n * **When to use**\n *\n * Use to keep the smallest number through APIs that consume a `Reducer`.\n *\n * **Details**\n *\n * The reducer starts from `Infinity`, so reducing an empty collection returns\n * `Infinity`.\n *\n * **Gotchas**\n *\n * `NaN` values propagate through `Math.min`.\n *\n * @see {@link ReducerMax} for keeping the largest number\n * @see {@link min} for comparing two numbers directly\n *\n * @stability stable\n * @category math\n * @since 4.0.0\n */\nexport const ReducerMin = /*#__PURE__*/Reducer.make((a, b) => Math.min(a, b), Infinity);\n//# sourceMappingURL=Number.js.map","/// <reference lib=\"esnext.disposable\" preserve=\"true\" />\n/**\n * Runs many effects against services built once from a `Layer`.\n *\n * A `ManagedRuntime` builds the services from a layer, keeps those services\n * available for repeated effect runs, and releases acquired resources when it\n * is disposed. This module includes the runtime type, a constructor, a guard,\n * and runners for connecting Effect programs to JavaScript entry points such as\n * promises, callbacks, and synchronous code.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Context from \"./Context.js\";\nimport * as Deferred from \"./Deferred.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport * as Fiber from \"./Fiber.js\";\nimport { fiberEnterUninterruptibleUnsafe, scopeRemoveFinalizerUnsafe } from \"./internal/effect.js\";\nimport * as Layer from \"./Layer.js\";\nimport { hasProperty } from \"./Predicate.js\";\nimport * as Scope from \"./Scope.js\";\nconst TypeId = \"~effect/ManagedRuntime\";\n/**\n * Checks whether the provided argument is a `ManagedRuntime`.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before treating it as a `ManagedRuntime`.\n *\n * **Details**\n *\n * The guard checks the internal `ManagedRuntime` marker property. It does not\n * build the layer or inspect the runtime's services.\n *\n * **Gotchas**\n *\n * Disposed runtimes still carry the marker, so this guard does not prove the\n * runtime is still usable.\n *\n * @see {@link make} for creating managed runtimes this guard recognizes\n *\n * @stability stable\n * @category guards\n * @since 3.9.0\n */\nexport const isManagedRuntime = input => hasProperty(input, TypeId);\n// The runtimes whose disposal the current fiber is running. A disposal adds its\n// runtime to the set it inherits, so a finalizer that disposes another runtime\n// still belongs to the outer disposals. Finalizers and their parallel fibers\n// inherit the set from the disposing fiber. It is not provided to the layer\n// build, because finalizers of layers shared through a MemoMap run with the\n// build context of the runtime that built them, which may not be the runtime\n// disposing them.\nconst DisposingRuntimes = /*#__PURE__*/Context.Reference(\"effect/ManagedRuntime/DisposingRuntimes\", {\n defaultValue: () => new Set()\n});\n/**\n * Creates a `ManagedRuntime` from a layer.\n *\n * **When to use**\n *\n * Use to create a reusable runtime from a `Layer` for application entry points\n * or integration code that runs many effects without rebuilding services.\n *\n * **Details**\n *\n * The layer is built lazily on first use and its context is cached for\n * subsequent runs. Resources acquired by the layer are owned by the runtime and\n * are released when `dispose` or `disposeEffect` is run. `options.memoMap` can\n * be used to share layer memoization with other layer builds.\n *\n * **Gotchas**\n *\n * Dispose the runtime when it is no longer needed. A runtime cannot be reused\n * after disposal.\n *\n * A failed layer build is also cached: subsequent runs return the same build\n * failure without rebuilding the layer. For transient failures, retry inside\n * the layer before passing it to `make`, or dispose the runtime and create a\n * new one to attempt a fresh build.\n *\n * **Example** (Creating a managed runtime)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Layer, ManagedRuntime } from \"effect\"\n *\n * const notifications: Array<string> = []\n *\n * class Notifications extends Context.Service<Notifications, {\n * readonly notify: (message: string) => Effect.Effect<void>\n * }>()(\"Notifications\") {\n * static readonly layer = Layer.succeed(this)({\n * notify: Effect.fn(\"Notifications.notify\")((message) =>\n * Effect.sync(() => notifications.push(message))\n * )\n * })\n * }\n *\n * const runtime = ManagedRuntime.make(Notifications.layer)\n *\n * const program = Effect.flatMap(\n * Notifications,\n * (_) => _.notify(\"Hello, world!\")\n * ).pipe(Effect.ensuring(runtime.disposeEffect))\n *\n * await runtime.runPromise(program)\n * notifications // => [\"Hello, world!\"]\n * ```\n *\n * @see {@link ManagedRuntime} for the returned runtime interface\n * @see {@link Layer.MemoMap} for shared layer memoization\n * @see {@link Layer.build} for lower-level scoped layer construction\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (layer, options) => {\n const memoMap = options?.memoMap ?? Layer.makeMemoMapUnsafe();\n const scope = Scope.makeUnsafe(\"sequential\");\n const layerScope = Scope.forkUnsafe(scope, \"sequential\");\n const fiberScope = Scope.forkUnsafe(scope, \"parallel\");\n // Fibers started by the runtime, including the layer build, are interrupted\n // and awaited by its disposal, so they and their child fibers must not wait\n // for it.\n const managedFibers = new WeakSet();\n const disposingFibers = new WeakSet();\n const defaultRunOptions = {\n onFiberStart(fiber) {\n managedFibers.add(fiber);\n if (disposingFibers.has(fiber)) return;\n Fiber.runIn(fiber, fiberScope);\n }\n };\n const mergeRunOptions = options => options ? {\n ...options,\n onFiberStart: options.onFiberStart ? fiber => {\n defaultRunOptions.onFiberStart(fiber);\n options.onFiberStart(fiber);\n } : defaultRunOptions.onFiberStart\n } : defaultRunOptions;\n let buildFiber;\n let disposed;\n const contextEffect = Effect.withFiber(fiber => {\n if (!buildFiber) {\n buildFiber = Effect.runFork(Effect.tap(Layer.buildWithMemoMap(layer, memoMap, layerScope), context => Effect.sync(() => {\n self.cachedContext = context;\n })), {\n scheduler: fiber.cache.scheduler,\n // Unlike requests, the build joins fiberScope even if it disposed the\n // runtime, so disposal still interrupts it.\n onFiberStart(fiber) {\n managedFibers.add(fiber);\n Fiber.runIn(fiber, fiberScope);\n }\n });\n }\n return Effect.flatten(Fiber.await(buildFiber));\n });\n const self = {\n [TypeId]: TypeId,\n memoMap,\n scope,\n contextEffect: contextEffect,\n cachedContext: undefined,\n context() {\n return self.cachedContext === undefined ? Effect.runPromise(self.contextEffect) : Promise.resolve(self.cachedContext);\n },\n dispose() {\n return Effect.runPromise(self.disposeEffect);\n },\n [Symbol.asyncDispose]() {\n return self.dispose();\n },\n disposeEffect: Effect.withFiber(fiber => {\n if (disposed !== undefined) {\n if (fiber.getRef(DisposingRuntimes).has(self)) return Effect.void;\n for (let current = fiber; current; current = current._parent) {\n if (managedFibers.has(current)) return Effect.void;\n }\n return Deferred.await(disposed);\n }\n // Once `disposed` is set the close must run, or later calls would wait forever.\n fiberEnterUninterruptibleUnsafe(fiber);\n const done = disposed = Deferred.makeUnsafe();\n // Closing fiberScope interrupts and awaits every managed fiber. Exempt the\n // disposing fiber and its ancestors, which would otherwise await themselves.\n for (let current = fiber; current; current = current._parent) {\n disposingFibers.add(current);\n scopeRemoveFinalizerUnsafe(fiberScope, current);\n }\n ;\n self.contextEffect = Effect.die(\"ManagedRuntime disposed\");\n self.cachedContext = undefined;\n return Scope.close(self.scope, Exit.void).pipe(Effect.provideService(DisposingRuntimes, new Set(fiber.getRef(DisposingRuntimes)).add(self)), Effect.ensuring(Deferred.done(done, Exit.void)));\n }),\n runFork(effect, options) {\n return self.cachedContext === undefined ? Effect.runFork(provide(self, effect), mergeRunOptions(options)) : Effect.runForkWith(self.cachedContext)(effect, mergeRunOptions(options));\n },\n runCallback(effect, options) {\n return self.cachedContext === undefined ? Effect.runCallback(provide(self, effect), mergeRunOptions(options)) : Effect.runCallbackWith(self.cachedContext)(effect, mergeRunOptions(options));\n },\n runSyncExit(effect) {\n return self.cachedContext === undefined ? Effect.runSyncExit(provide(self, effect)) : Effect.runSyncExitWith(self.cachedContext)(effect);\n },\n runSync(effect) {\n return self.cachedContext === undefined ? Effect.runSync(provide(self, effect)) : Effect.runSyncWith(self.cachedContext)(effect);\n },\n runPromiseExit(effect, options) {\n return self.cachedContext === undefined ? Effect.runPromiseExit(provide(self, effect), mergeRunOptions(options)) : Effect.runPromiseExitWith(self.cachedContext)(effect, mergeRunOptions(options));\n },\n runPromise(effect, options) {\n return self.cachedContext === undefined ? Effect.runPromise(provide(self, effect), mergeRunOptions(options)) : Effect.runPromiseWith(self.cachedContext)(effect, mergeRunOptions(options));\n }\n };\n return self;\n};\nfunction provide(managed, effect) {\n return Effect.flatMap(managed.contextEffect, context => Effect.provideContext(effect, context));\n}\n//# sourceMappingURL=ManagedRuntime.js.map","import { Array as Arr, Function as Fn, Number as Num, Option, pipe } from \"effect\";\n\nconst SEARCH_TASK = \"search result\";\nconst NO_TITLE = \"none\";\nconst EMPTY = 0;\nconst ARITY = 2;\n\nexport interface Document {\n readonly text: string;\n readonly title?: string;\n}\n\nexport const asQuery = (text: string): string => `task: ${SEARCH_TASK} | query: ${text}`;\n\nexport const asDocument = ({ text, title = NO_TITLE }: Document): string =>\n `title: ${title} | text: ${text}`;\n\nexport const dot: {\n (right: readonly number[]): (left: readonly number[]) => number;\n (left: readonly number[], right: readonly number[]): number;\n} = Fn.dual(ARITY, (left: readonly number[], right: readonly number[]): number =>\n Num.sumAll(Arr.zipWith(left, right, Num.multiply)),\n);\n\nconst normalize = (vector: readonly number[]): readonly number[] =>\n pipe(\n Math.sqrt(dot(vector, vector)),\n Option.liftPredicate((length) => length > EMPTY),\n Option.match({\n onNone: () => vector,\n onSome: (length) =>\n pipe(\n vector,\n Arr.map((value) => value / length),\n ),\n }),\n );\n\nexport const truncate: {\n (dimensions: number): (vector: readonly number[]) => readonly number[];\n (vector: readonly number[], dimensions: number): readonly number[];\n} = Fn.dual(ARITY, (vector: readonly number[], dimensions: number): readonly number[] =>\n normalize(Arr.take(vector, dimensions)),\n);\n","import { Array as Arr, Config, Effect, Option, Schema, pipe } from \"effect\";\n\nconst taggedError = Schema.TaggedError;\n\nexport class CacheRootError extends taggedError<\n CacheRootError,\n { readonly brand: unique symbol }\n>()(\"CacheRootError\", { message: Schema.String }) {}\n\nconst SEPARATOR = \"/\";\nexport const CACHE_DIRECTORY_NAME = \".cache\";\n\nconst variable = (name: string): Effect.Effect<Option.Option<string>> =>\n Config.option(Config.NonEmptyString(name)).pipe(Effect.orElseSucceed(Option.none));\n\nconst baseDirectory: Effect.Effect<Option.Option<string>> = Effect.gen(function* baseDirectory() {\n const cacheHome = yield* variable(\"XDG_CACHE_HOME\");\n const home = yield* variable(\"HOME\");\n const profile = yield* variable(\"USERPROFILE\");\n return pipe(\n cacheHome,\n Option.orElse(() =>\n pipe(\n Option.orElse(home, () => profile),\n Option.map((directory) => `${directory}${SEPARATOR}${CACHE_DIRECTORY_NAME}`),\n ),\n ),\n );\n});\n\nexport const cacheRootEffect = (\n segments: readonly string[],\n): Effect.Effect<string, CacheRootError> =>\n baseDirectory.pipe(\n Effect.flatMap(\n Option.match({\n onNone: () => Effect.fail(CacheRootError.make({ message: \"set XDG_CACHE_HOME or HOME\" })),\n onSome: (base) => Effect.succeed(pipe([base, ...segments], Arr.join(SEPARATOR))),\n }),\n ),\n );\n\nexport const cacheRootOf = (segments: readonly string[]): Promise<string> =>\n Effect.runPromise(cacheRootEffect(segments));\n","import { Config, Effect, Option, Path, pipe } from \"effect\";\n\nimport { cacheRootEffect } from \"#/shared/lib/cache.ts\";\nimport type { CacheRootError } from \"#/shared/lib/cache.ts\";\n\nconst PROTOCOL_VERSION = 1;\nconst NAME = \"model-server\";\nconst FALLBACK_TEMPORARY = \"/tmp\";\nconst FALLBACK_USER = \"user\";\n\nexport interface Location {\n readonly socket: string;\n readonly cache: string;\n}\n\nexport interface LocationOptions {\n readonly socket?: string;\n readonly cache?: string;\n}\n\nconst variable = (name: string): Effect.Effect<Option.Option<string>> =>\n Config.option(Config.NonEmptyString(name)).pipe(Effect.orElseSucceed(Option.none));\n\nconst userId = (): string =>\n pipe(\n Option.fromNullishOr(globalThis.process.getuid),\n Option.map((read) => `${read.call(globalThis.process)}`),\n Option.getOrElse(() => FALLBACK_USER),\n );\n\nconst defaultSocket = Effect.fnUntraced(function* defaultSocket() {\n const path = yield* Path.Path;\n const temporary = yield* variable(\"TMPDIR\");\n return path.join(\n Option.getOrElse(temporary, () => FALLBACK_TEMPORARY),\n `${NAME}-${userId()}`,\n `v${PROTOCOL_VERSION}.sock`,\n );\n});\n\n/** @internal */\nexport const resolveLocation = Effect.fnUntraced(function* resolveLocation(\n options: LocationOptions,\n): Effect.fn.Return<Location, CacheRootError, Path.Path> {\n const socket = yield* Option.match(Option.fromNullishOr(options.socket), {\n onNone: defaultSocket,\n onSome: Effect.succeed,\n });\n const cache = yield* Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => cacheRootEffect([NAME]),\n onSome: Effect.succeed,\n });\n return { socket, cache };\n});\n","import { layer as nodeServices } from \"@effect/platform-node/NodeServices\";\nimport { Array as Arr, Duration, Effect, ManagedRuntime, Option, Path, pipe } from \"effect\";\nimport type { FileSystem } from \"effect\";\nimport type { ChildProcessSpawner } from \"effect/process\";\n\nimport { truncate } from \"#/entities/embedding/index.ts\";\nimport { startServer } from \"#/features/start-server/index.ts\";\nimport { probe, withClient, resolveLocation } from \"#/shared/api/model-server/index.ts\";\nimport type {\n ModelClient,\n ModelKey,\n Status,\n LocationOptions,\n} from \"#/shared/api/model-server/index.ts\";\n\nexport { asDocument, asQuery, dot } from \"#/entities/embedding/index.ts\";\nexport type { Document } from \"#/entities/embedding/index.ts\";\n\nexport const EMBEDDING_GEMMA_2 = {\n model: \"onnx-community/embeddinggemma-2-ONNX\",\n dtype: \"q4\",\n dimensions: 768,\n} as const;\n\nexport interface ServerOptions extends LocationOptions {\n readonly timeoutMillis?: number;\n readonly idleMillis?: number;\n readonly engine?: string;\n}\n\nexport interface ModelOptions extends ServerOptions {\n readonly model?: string;\n readonly dtype?: string;\n}\n\nexport interface EmbedOptions extends ModelOptions {\n readonly texts: readonly string[];\n readonly dimensions?: number;\n readonly maxTokens?: number;\n readonly batchSize?: number;\n}\n\nconst DEFAULT_TIMEOUT_MILLIS = 30_000;\nconst DEFAULT_IDLE_MILLIS = 900_000;\nconst DEFAULT_MAX_TOKENS = 512;\nconst DEFAULT_BATCH_SIZE = 8;\nconst SERVER_ENTRY = \"@r_masseater/masseater-utils/model-server/process\";\n\nconst node = ManagedRuntime.make(nodeServices);\n\nconst serverEntry = Effect.fnUntraced(function* serverEntry() {\n const path = yield* Path.Path;\n return yield* path.fromFileUrl(new URL(import.meta.resolve(SERVER_ENTRY)));\n});\n\nconst callServer = Effect.fnUntraced(function* callServer<Value, Failure>(\n options: ServerOptions,\n use: (client: ModelClient) => Effect.Effect<Value, Failure>,\n) {\n const location = yield* resolveLocation(options);\n const server = yield* serverEntry();\n const services = yield* Effect.context<\n FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner\n >();\n const start = yield* Effect.cached(\n startServer(location, {\n server,\n idleMillis: options.idleMillis ?? DEFAULT_IDLE_MILLIS,\n engine: Option.fromNullishOr(options.engine),\n }).pipe(Effect.provideContext(services), Effect.orDie),\n );\n return yield* withClient({ socket: location.socket, onOpenError: Option.some(start), use });\n});\n\nconst using = <Value, Failure>(\n options: ServerOptions,\n use: (client: ModelClient) => Effect.Effect<Value, Failure>,\n): Promise<Value> => {\n const timeout = Duration.millis(options.timeoutMillis ?? DEFAULT_TIMEOUT_MILLIS);\n return node.runPromise(callServer(options, use).pipe(Effect.timeout(timeout)));\n};\n\nconst keyOf = (options: ModelOptions): ModelKey => ({\n model: options.model ?? EMBEDDING_GEMMA_2.model,\n dtype: options.dtype ?? EMBEDDING_GEMMA_2.dtype,\n});\n\nexport const embed = (options: EmbedOptions): Promise<readonly (readonly number[])[]> => {\n const key = keyOf(options);\n const maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;\n const toDimensions = truncate(options.dimensions ?? EMBEDDING_GEMMA_2.dimensions);\n const batches = Arr.chunksOf(options.texts, options.batchSize ?? DEFAULT_BATCH_SIZE);\n const flatten = (\n vectors: readonly (readonly (readonly number[])[])[],\n ): readonly (readonly number[])[] => pipe(vectors, Arr.flatten, Arr.map(toDimensions));\n const embedAll = (\n client: ModelClient,\n ): Effect.Effect<readonly (readonly number[])[], unknown> => {\n const embedBatch = (texts: readonly string[]): ReturnType<ModelClient[\"Embed\"]> =>\n client.Embed({ ...key, texts, maxTokens });\n return Effect.forEach(batches, embedBatch, { concurrency: 1 }).pipe(Effect.map(flatten));\n };\n return using(options, embedAll);\n};\n\nexport const prepare = (options: ModelOptions): Promise<void> =>\n using(options, (client) => client.Load(keyOf(options)));\n\nexport const warm = (options: ModelOptions): Promise<void> =>\n using(options, (client) => client.Warm(keyOf(options)));\n\nexport type ServerState = { readonly running: false } | ({ readonly running: true } & Status);\n\nconst stateOf = (found: Option.Option<Status>): ServerState =>\n Option.match(found, {\n onNone: (): ServerState => ({ running: false }),\n onSome: (running): ServerState => ({ running: true, ...running }),\n });\n\nexport const status = (options: LocationOptions): Promise<ServerState> =>\n node.runPromise(\n resolveLocation(options).pipe(\n Effect.flatMap((location) => probe(location.socket)),\n Effect.map(stateOf),\n ),\n );\n"],"ignoreList":[0,1],"mappings":";AA4CsB,WAAW;;;;;;;;;;;;;;;;;;;;;;AAiEjC,MAAa,WAAwB,mBAAK,IAAI,MAAM,SAAS,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;;;;AAgZxE,MAAa,UAAS,eAAc;CAClC,IAAI,MAAM;CACV,KAAK,MAAM,KAAK,YACd,OAAO;CAET,OAAO;AACT;;;;;;;;;;;;;;AC7eA,MAAM,SAAS;AAgCf,MAAM,oBAAiC,wBAAkB,2CAA2C,EAClG,oCAAoB,IAAI,IAAI,EAC9B,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DD,MAAa,QAAQ,OAAO,YAAY;CACtC,MAAM,UAAU,SAAS,WAAWA,kBAAwB;CAC5D,MAAM,QAAQC,WAAiB,YAAY;CAC3C,MAAM,aAAaC,WAAiB,OAAO,YAAY;CACvD,MAAM,aAAaA,WAAiB,OAAO,UAAU;CAIrD,MAAM,gCAAgB,IAAI,QAAQ;CAClC,MAAM,kCAAkB,IAAI,QAAQ;CACpC,MAAM,oBAAoB,EACxB,aAAa,OAAO;EAClB,cAAc,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AQ,YAAY,CAAC;CACrF,MAAM,YACJ,WAC2D;EAC3D,MAAM,cAAc,UAClB,OAAO,MAAM;GAAE,GAAG;GAAK;GAAO;EAAU,CAAC;EAC3C,OAAOC,QAAe,SAAS,YAAY,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,KAAKC,MAAW,OAAO,CAAC;CACzF;CACA,OAAO,MAAM,SAAS,QAAQ;AAChC;AAEA,MAAa,WAAW,YACtB,MAAM,UAAU,WAAW,OAAO,KAAK,MAAM,OAAO,CAAC,CAAC;AAExD,MAAa,QAAQ,YACnB,MAAM,UAAU,WAAW,OAAO,KAAK,MAAM,OAAO,CAAC,CAAC;AAIxD,MAAM,WAAW,UACfC,MAAa,OAAO;CAClB,eAA4B,EAAE,SAAS,MAAM;CAC7C,SAAS,aAA0B;EAAE,SAAS;EAAM,GAAG;CAAQ;AACjE,CAAC;AAEH,MAAa,UAAU,YACrB,KAAK,WACH,gBAAgB,OAAO,CAAC,CAAC,KACvBC,SAAgB,aAAa,MAAM,SAAS,MAAM,CAAC,GACnDF,MAAW,OAAO,CACpB,CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@r_masseater/masseater-utils",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "The small shared libraries of masseater's repositories as subpaths of one package: a chip row for React, Claude Code plugin helpers, Effect entry points for Node.js and GitHub Actions, file import mapping, Node package readers, OTLP assertions for Vitest and Cloudflare Workers tracing.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"actions",
|
|
@@ -39,7 +39,8 @@
|
|
|
39
39
|
"type": "module",
|
|
40
40
|
"sideEffects": [
|
|
41
41
|
"*.css",
|
|
42
|
-
"./dist/vitest-otlp/setup.mjs"
|
|
42
|
+
"./dist/vitest-otlp/setup.mjs",
|
|
43
|
+
"./dist/model-server/process.mjs"
|
|
43
44
|
],
|
|
44
45
|
"imports": {
|
|
45
46
|
"#/*": "./src/*"
|
|
@@ -49,6 +50,8 @@
|
|
|
49
50
|
"./skerm.css": "./src/app/skerm.css",
|
|
50
51
|
"./usage-meter": "./dist/usage-meter.mjs",
|
|
51
52
|
"./usage-meter/report": "./dist/usage-meter/report.mjs",
|
|
53
|
+
"./model-server": "./dist/model-server.mjs",
|
|
54
|
+
"./model-server/process": "./dist/model-server/process.mjs",
|
|
52
55
|
"./plugin-kit": "./dist/plugin-kit.mjs",
|
|
53
56
|
"./node-main": "./dist/node-main.mjs",
|
|
54
57
|
"./hook-flags": "./dist/hook-flags.mjs",
|
|
@@ -101,6 +104,7 @@
|
|
|
101
104
|
"@bufbuild/protobuf": "2.17.0",
|
|
102
105
|
"@cloudflare/workers-types": "5.20261129.1",
|
|
103
106
|
"@effect/platform-node": "4.2.0",
|
|
107
|
+
"@effect/platform-node-shared": "4.2.0",
|
|
104
108
|
"@effect/vitest": "4.2.0",
|
|
105
109
|
"@npmcli/package-json": "8.0.1",
|
|
106
110
|
"@opentelemetry/api": "1.10.0",
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: use-model-server
|
|
3
|
+
description: >
|
|
4
|
+
Use when a Claude Code plugin hook or script needs a local model, such as text embeddings for
|
|
5
|
+
search: the model-server subpath of @r_masseater/masseater-utils runs one resident process per user that every plugin shares,
|
|
6
|
+
started on the first call and stopped when idle. Covers embed, warm, prepare, status and the
|
|
7
|
+
EmbeddingGemma 2 prefixes.
|
|
8
|
+
metadata:
|
|
9
|
+
type: core
|
|
10
|
+
library: "@r_masseater/masseater-utils"
|
|
11
|
+
sources:
|
|
12
|
+
- src/app/model-server*
|
|
13
|
+
- src/entities/embedding/model/text.ts
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
# use-model-server
|
|
17
|
+
|
|
18
|
+
Loading a model takes seconds and gigabytes, and a hook runs as a new process each time. A plugin that loads its own model pays that on every hook and holds a second copy beside every other plugin. This subpath keeps one process per user that holds the models, so a hook pays only a socket round trip, about 35 ms for one query.
|
|
19
|
+
|
|
20
|
+
## Setup
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
bun add @r_masseater/masseater-utils
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Commit the `bun.lock` that `bun add` writes. The package bundles what it needs; the inference runtime installs itself into the user's cache folder on the first call.
|
|
27
|
+
|
|
28
|
+
## Embed
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { asDocument, asQuery, dot, embed } from "@r_masseater/masseater-utils/model-server";
|
|
32
|
+
|
|
33
|
+
const prompt = "add a table to D1";
|
|
34
|
+
const [query] = await embed({ texts: [asQuery(prompt)], timeoutMillis: 2000 });
|
|
35
|
+
const documents = await embed({
|
|
36
|
+
texts: [asDocument({ title: "db", text: "Schema, migrations and connections" })],
|
|
37
|
+
});
|
|
38
|
+
const score = dot(query, documents[0]);
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- Prefix a search query with `asQuery` and a searched text with `asDocument({ title, text })`. Without the prefixes the model still works but ranks worse.
|
|
42
|
+
- Vectors are normalized, so `dot(query, document)` is the cosine similarity.
|
|
43
|
+
- Embed the documents once and keep their vectors keyed by a hash of their text. Embed only the query in a hook.
|
|
44
|
+
- Keep texts short. `maxTokens` defaults to 512; long batches use gigabytes of memory.
|
|
45
|
+
|
|
46
|
+
## Hooks
|
|
47
|
+
|
|
48
|
+
- Call `warm({})` from `SessionStart`. It returns at once and the server loads the model in the background.
|
|
49
|
+
- In `UserPromptSubmit` or `PostToolUse`, pass a short `timeoutMillis` and fall back to something without the model when `embed` rejects. The first run of a machine installs the runtime and downloads the model, which takes minutes.
|
|
50
|
+
- `status({})` says whether a server runs and which models it holds, without starting one.
|