akarisp 0.1.0-alpha.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,204 @@
1
+ # AkariSP
2
+
3
+ A small runtime for browser-native LLM sessions (Chrome's Prompt API). It keeps one warm
4
+ **base session** and runs each task in its own **clone**, so repeated tasks don't pay session
5
+ creation every time and never share conversational context.
6
+
7
+ The same runtime also drives an application-created [WebLLM](#webllm) engine through
8
+ `akarisp/webllm`.
9
+
10
+ Zero runtime dependencies. No framework, no agent abstraction.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install akarisp@alpha
16
+ ```
17
+
18
+ The first release, `0.1.0-alpha.0`, is published under the `alpha` dist-tag. A plain
19
+ `npm install akarisp` installs the `latest` tag, which will exist only after a stable release.
20
+
21
+ ## Usage
22
+
23
+ ```js
24
+ import { createRuntime, TaskError } from 'akarisp';
25
+
26
+ const runtime = await createRuntime({
27
+ session: { initialPrompts: [{ role: 'system', content: 'Answer in one sentence.' }] },
28
+ limit: 1, // absolute cap on running tasks (default 1)
29
+ queueCapacity: 32, // waiting tasks beyond the limit (default 32); overflow is rejected
30
+ });
31
+
32
+ try {
33
+ const { output, timing } = await runtime.run('What is HTTP?', {
34
+ signal: AbortSignal.timeout(10_000),
35
+ });
36
+ console.log(output, timing); // { queueWait, acquire, prompt, total } in ms
37
+ } catch (e) {
38
+ if (e instanceof TaskError) {
39
+ // e.code: 'failed' | 'cancelled' | 'rejected' | 'closed' | 'broken'
40
+ // e.cause: original error or abort reason; e.timing: phases completed so far
41
+ }
42
+ }
43
+
44
+ await runtime.shutdown(); // cancels running tasks, rejects waiting ones, destroys all sessions
45
+ ```
46
+
47
+ Each `run()` clones the base, prompts the clone, and destroys it. The task's promise settles
48
+ only after its session is destroyed and its slot released.
49
+
50
+ ## Streaming
51
+
52
+ ```js
53
+ const stream = runtime.stream('Explain HTTP in two sentences.', {
54
+ signal: AbortSignal.timeout(10_000),
55
+ });
56
+ for await (const chunk of stream) {
57
+ output.textContent += chunk;
58
+ if (userClickedStop) break; // clone destroyed and slot released before the loop exits
59
+ }
60
+ console.log(stream.timing); // final TaskTiming; undefined until the stream has fully ended
61
+ ```
62
+
63
+ - Same limit, queue, cancellation, broken, and shutdown rules as `run()`; both share one queue.
64
+ - Lazy: nothing is queued or cloned until the first pull, so an unused stream costs nothing.
65
+ - Single use: iterating the same stream twice throws `TypeError`.
66
+ - `timing.prompt` runs until the loop sees the model's end; because chunks are pulled, it includes
67
+ the time your loop body spends on each chunk.
68
+ - `break` is not an error. Cancellation, timeout, model failure, and shutdown end the loop with a
69
+ `TaskError`, and cleanup happens even if you have stopped pulling chunks.
70
+
71
+ ## Templates
72
+
73
+ One runtime can hold a small fixed set of named warm base sessions and clone the one each task
74
+ names:
75
+
76
+ ```js
77
+ const runtime = await createRuntime({
78
+ session: { initialPrompts: [{ role: 'system', content: 'General assistant.' }] }, // optional default
79
+ templates: {
80
+ momentum: { initialPrompts: [{ role: 'system', content: 'You analyze momentum.' }] },
81
+ risk: { initialPrompts: [{ role: 'system', content: 'You analyze risk.' }] },
82
+ },
83
+ limit: 2,
84
+ });
85
+
86
+ await runtime.run(text, { template: 'momentum' });
87
+ for await (const chunk of runtime.stream(text, { template: 'risk' })) render(chunk);
88
+ await runtime.run(text); // uses the default `session` template
89
+ ```
90
+
91
+ - Each template value is passed to `LanguageModel.create()`; the runtime creates and owns every base.
92
+ - With `session`, omitting `template` uses it. With only `templates`, you must name one; otherwise
93
+ `run()` rejects and `stream()`'s first pull throws `TypeError`. Unknown names throw `TypeError`.
94
+ Neither consumes a queue entry or slot.
95
+ - All templates share one `limit` and one queue. A clone failure that breaks any base makes the whole
96
+ runtime `broken`. `shutdown()` destroys every base.
97
+
98
+ ## Snapshot
99
+
100
+ ```js
101
+ const { state, active, queued, limit, queueCapacity } = runtime.snapshot();
102
+ ```
103
+
104
+ Synchronous and read-only: it never waits, admits, cancels, or changes anything, and each call
105
+ returns a fresh plain object. `active` counts tasks holding a concurrency slot, including a task
106
+ whose session is still being destroyed; `queued` counts tasks waiting for a slot (a stream counts
107
+ only after its first pull). After `await runtime.shutdown()` it reports `closed` with `0/0`.
108
+
109
+ ## States
110
+
111
+ - `ready`: accepts tasks.
112
+ - `broken`: the provider's resource can no longer be trusted for new tasks. With the Prompt
113
+ API, this means a clone failed with `InvalidStateError`. For WebLLM, see [WebLLM](#webllm). Waiting and new tasks are rejected; tasks already holding a clone finish normally.
114
+ Create a new runtime.
115
+ - `closed`: after `shutdown()`. `shutdown()` is idempotent and never rejects.
116
+
117
+ ## Performance
118
+
119
+ AkariSP **amortizes** session initialization across repeated tasks; it does not eliminate it.
120
+ The base session is created once (`createRuntime`), after which each task pays a clone instead
121
+ of a full `LanguageModel.create()`. Measure it on your device with the benchmark in
122
+ [bench/README.md](bench/README.md).
123
+
124
+ ## WebLLM
125
+
126
+ ```js
127
+ import { CreateMLCEngine } from '@mlc-ai/web-llm'; // your dependency, not AkariSP's
128
+ import { createWebLLMRuntime } from 'akarisp/webllm';
129
+
130
+ const engine = await CreateMLCEngine('Qwen2.5-0.5B-Instruct-q4f16_1-MLC'); // you load the model
131
+ const runtime = await createWebLLMRuntime(engine, {
132
+ session: { initialPrompts: [{ role: 'system', content: 'Answer in one sentence.' }], temperature: 0 },
133
+ });
134
+ const { output } = await runtime.run('What is HTTP?');
135
+ await runtime.shutdown(); // also unloads the engine
136
+ ```
137
+
138
+ The returned runtime is the same `Runtime`: `run`, `stream`, `snapshot`, `shutdown`, templates,
139
+ `TaskError` codes, and timing behave as above. What differs:
140
+
141
+ - **Engine**: your application creates the engine and loads the model. AkariSP never
142
+ downloads a model and does not depend on `@mlc-ai/web-llm`.
143
+ - **Ownership**: once `createWebLLMRuntime` resolves, the runtime uses the engine exclusively
144
+ (run nothing else on it), and `shutdown()` unloads it after every task's cleanup. If creation
145
+ rejects, the engine is untouched.
146
+ - **`limit` must be 1**: one engine generates one request at a time. `limit > 1` throws
147
+ `TypeError`. Extra tasks wait in AkariSP's queue, where cancelling one never affects another.
148
+ - **Templates** are request configuration: `initialPrompts` plus request settings such as
149
+ `temperature`, all on the one engine. No per-template resource is created.
150
+ - **Tasks**: each task is one streaming request, also for `run()`. Cancellation, timeout,
151
+ `break`, and shutdown interrupt the generation and drain it before the slot is released, so
152
+ the next task starts cleanly.
153
+ - **`broken`**: the engine was unloaded or lost when a task started (`ModelNotLoadedError`,
154
+ `DeviceLostError`). Create a new engine and runtime.
155
+ - **Validated**: with `@mlc-ai/web-llm` 0.2.85 and Qwen2.5-0.5B-Instruct in Chrome with WebGPU
156
+ ([smoke/README.md](smoke/README.md)). Other WebLLM versions are unverified.
157
+ - **Types**: a `MLCEngine`, `WebWorkerMLCEngine`, or `MLCEngineInterface` is accepted without
158
+ a cast. This is verified with TypeScript `moduleResolution: "bundler"`. WebLLM 0.2.85's own
159
+ declarations do not resolve under `node16`/`nodenext`, where its types become `any`.
160
+
161
+ ## Package
162
+
163
+ - Entry points: `akarisp` (`createRuntime`, `TaskError`, and the types `Runtime`,
164
+ `RuntimeOptions`, `RuntimeSnapshot`, `TaskStream`, `TaskResult`, `TaskTiming`) and
165
+ `akarisp/webllm` (`createWebLLMRuntime`). No other path is importable.
166
+ - ESM only. On Node 23.9, `require('akarisp')` also returns the same exports through Node's
167
+ `require(esm)`; the package ships no CommonJS build.
168
+ - TypeScript declarations are included and verified with `moduleResolution` `bundler`,
169
+ `node16`, and `nodenext`.
170
+ - Zero runtime dependencies.
171
+
172
+ ## Development
173
+
174
+ Requires Node ≥ 22.18 (the test runner loads TypeScript directly). This is a development
175
+ requirement only; the package itself runs in browsers.
176
+
177
+ ```bash
178
+ npm test # node:test: core, browser and WebLLM adapters, boundary, packed-tarball consumer
179
+ npm run build # tsc → dist/
180
+ npm run test:browser # Playwright: compatibility page on Chromium / Firefox / WebKit engines
181
+ ```
182
+
183
+ ### Browser compatibility
184
+
185
+ AkariSP's browser integration uses the Prompt API exposed by the current browser. Importing
186
+ AkariSP is safe in any browser, but that does not mean the browser can run a local model, and
187
+ AkariSP cannot make the Prompt API available where the browser does not provide it. Use the
188
+ compatibility harness ([smoke/README.md](smoke/README.md)) to inspect the capabilities and
189
+ lifecycle behavior of a specific browser and version.
190
+
191
+ Source layout: `src/core/` is the provider-neutral runtime (no browser globals);
192
+ `src/browser/` maps it to the Prompt API's `LanguageModel`; `src/webllm/` maps it to an
193
+ injected WebLLM engine; `src/index.ts` and `src/webllm.ts` are the two public entries.
194
+
195
+ ### Public API snapshot
196
+
197
+ `api/akarisp.api.txt` records the public surface of the packed package. `npm test` fails if the
198
+ surface changes. After an intentional public API change, run `UPDATE_API=1 npm test` and review
199
+ the diff.
200
+
201
+ ### Release
202
+
203
+ `npm publish` uses `publishConfig.tag` (`alpha`), so a pre-release never lands on `latest` by
204
+ accident. `prepack` rebuilds `dist/` first.
@@ -0,0 +1,4 @@
1
+ import { type Runtime, type RuntimeOptions } from '../core/runtime.ts';
2
+ /** Create a runtime backed by the browser's built-in Prompt API. The native global is read
3
+ * only when a base session is created. */
4
+ export declare function createRuntime(options?: RuntimeOptions): Promise<Runtime>;
@@ -0,0 +1,15 @@
1
+ import { createCoreRuntime } from "../core/runtime.js";
2
+ // Owns one warm session per template (destroy) and nothing provider-wide, so no close().
3
+ const promptApi = {
4
+ create: (config) => LanguageModel.create(config),
5
+ start: (base, options) => base.clone(options),
6
+ // ponytail: InvalidStateError = base no longer trusted (005 research R2); revisit if the
7
+ // Prompt API spec defines destroyed-session errors differently.
8
+ broken: (e) => e instanceof DOMException && e.name === 'InvalidStateError',
9
+ destroy: (base) => base.destroy(),
10
+ };
11
+ /** Create a runtime backed by the browser's built-in Prompt API. The native global is read
12
+ * only when a base session is created. */
13
+ export function createRuntime(options) {
14
+ return createCoreRuntime(promptApi, options);
15
+ }
@@ -0,0 +1,85 @@
1
+ export interface Session {
2
+ prompt(input: Prompt, options: {
3
+ signal: AbortSignal;
4
+ }): Promise<string>;
5
+ promptStreaming(input: Prompt, options: {
6
+ signal: AbortSignal;
7
+ }): AsyncIterable<string>;
8
+ destroy(): void | Promise<void>;
9
+ }
10
+ export interface SessionProvider<B> {
11
+ create(config?: object): Promise<B>;
12
+ start(base: B, options: {
13
+ signal: AbortSignal;
14
+ }): Promise<Session>;
15
+ /** Consulted only when start() rejects and the task was not aborted: true = runtime broken. */
16
+ broken(error: unknown): boolean;
17
+ /** Per-template resource cleanup. */
18
+ destroy?(base: B): void | Promise<void>;
19
+ /** Provider-wide resource cleanup; shutdown only, after every destroy(base). */
20
+ close?(): void | Promise<void>;
21
+ }
22
+ type Prompt = string | readonly object[];
23
+ export interface RuntimeOptions {
24
+ /** Passed unchanged to the session provider's create() for the unnamed default template. */
25
+ session?: object;
26
+ /** Named templates: name → options passed unchanged to the session provider's create(). Fixed for the
27
+ * runtime's lifetime. If given without `session`, there is no default template. */
28
+ templates?: Record<string, object>;
29
+ /** Absolute cap on running tasks (slot acquire → start task session → prompt → destroy → release).
30
+ * Integer ≥ 1. Default 1. */
31
+ limit?: number;
32
+ /** Max waiting tasks. Finite integer ≥ 0. Default 32.
33
+ * When limit is reached and the queue is full, run() rejects. */
34
+ queueCapacity?: number;
35
+ }
36
+ export interface Runtime {
37
+ readonly state: 'ready' | 'broken' | 'closed';
38
+ /** Start a task session from the template's base → prompt → destroy the task session. */
39
+ run(input: Prompt, options?: {
40
+ signal?: AbortSignal;
41
+ template?: string;
42
+ }): Promise<TaskResult>;
43
+ /** Same lifecycle as run(), output as chunks. Lazy: nothing is admitted until the first
44
+ * pull. Single-use. Leaving the loop early destroys the task session before the loop exits. */
45
+ stream(input: Prompt, options?: {
46
+ signal?: AbortSignal;
47
+ template?: string;
48
+ }): TaskStream;
49
+ /** Synchronous, read-only view of current state. Never waits, never changes anything. */
50
+ snapshot(): RuntimeSnapshot;
51
+ /** Reject waiters, cancel running tasks, destroy all sessions. Idempotent and safe to
52
+ * call concurrently; never rejects. Resolves only after all cleanup is done. */
53
+ shutdown(): Promise<void>;
54
+ }
55
+ export interface RuntimeSnapshot {
56
+ readonly state: Runtime['state'];
57
+ /** Tasks holding a concurrency slot (task session started → prompt → task session destroyed). */
58
+ readonly active: number;
59
+ /** Tasks waiting for a slot. */
60
+ readonly queued: number;
61
+ readonly limit: number;
62
+ readonly queueCapacity: number;
63
+ }
64
+ export interface TaskStream extends AsyncIterable<string> {
65
+ /** undefined until the task has ended and its resources are cleaned up. */
66
+ readonly timing: TaskTiming | undefined;
67
+ }
68
+ export interface TaskResult {
69
+ output: string;
70
+ timing: TaskTiming;
71
+ }
72
+ /** Milliseconds. A field is set only if its phase completed; total is always set. */
73
+ export interface TaskTiming {
74
+ queueWait?: number;
75
+ acquire?: number;
76
+ prompt?: number;
77
+ total: number;
78
+ }
79
+ export declare class TaskError extends Error {
80
+ readonly code: 'failed' | 'cancelled' | 'rejected' | 'closed' | 'broken';
81
+ readonly timing: TaskTiming;
82
+ constructor(code: TaskError['code'], timing: TaskTiming, cause?: unknown);
83
+ }
84
+ export declare function createCoreRuntime<B>(provider: SessionProvider<B>, options?: RuntimeOptions): Promise<Runtime>;
85
+ export {};
@@ -0,0 +1,245 @@
1
+ export class TaskError extends Error {
2
+ code;
3
+ timing;
4
+ constructor(code, timing, cause) {
5
+ super(`Task ${code}`, { cause });
6
+ this.name = 'TaskError';
7
+ this.code = code;
8
+ this.timing = timing;
9
+ }
10
+ }
11
+ export async function createCoreRuntime(provider, options = {}) {
12
+ const { session, templates, limit = 1, queueCapacity = 32 } = options;
13
+ if (!Number.isInteger(limit) || limit < 1)
14
+ throw new TypeError('limit must be an integer >= 1');
15
+ if (!Number.isInteger(queueCapacity) || queueCapacity < 0) {
16
+ throw new TypeError('queueCapacity must be a finite integer >= 0');
17
+ }
18
+ if (templates && Object.keys(templates).length === 0 && session === undefined) {
19
+ throw new TypeError('templates is empty and no session was given');
20
+ }
21
+ // One warm base per template; key undefined = unnamed default. Fixed after creation.
22
+ const bases = new Map();
23
+ try {
24
+ // ponytail: sequential creation scales startup with template count; use Promise.allSettled
25
+ // if startup latency matters.
26
+ if (templates === undefined || session !== undefined)
27
+ bases.set(undefined, await provider.create(session));
28
+ for (const [name, config] of Object.entries(templates ?? {}))
29
+ bases.set(name, await provider.create(config));
30
+ }
31
+ catch (e) {
32
+ // No close(): provider-wide resources are owned only once creation succeeds.
33
+ for (const b of bases.values())
34
+ try {
35
+ await provider.destroy?.(b);
36
+ }
37
+ catch { }
38
+ throw e;
39
+ }
40
+ const pick = (template) => {
41
+ const base = bases.get(template);
42
+ if (base)
43
+ return base;
44
+ throw new TypeError(template === undefined
45
+ ? 'template is required: this runtime has no default session'
46
+ : `unknown template "${template}"`);
47
+ };
48
+ let state = 'ready';
49
+ const closer = new AbortController();
50
+ let running = 0;
51
+ const queue = [];
52
+ let closing;
53
+ let idle;
54
+ const drain = (code) => {
55
+ while (queue.length)
56
+ queue.shift()(code);
57
+ };
58
+ // Called only after the task session is destroyed, so `limit` also caps live task sessions.
59
+ const release = () => {
60
+ running--;
61
+ if (state === 'ready' && queue.length) {
62
+ running++;
63
+ queue.shift()();
64
+ }
65
+ if (running === 0)
66
+ idle?.();
67
+ };
68
+ // --- Task lifecycle shared by run() and stream() --------------------------------------
69
+ // State and pre-abort checks, then a slot now or a FIFO wait. Sets `total` on its errors.
70
+ const admit = async (signal) => {
71
+ const t0 = performance.now();
72
+ const timing = { total: 0 };
73
+ const fail = (code, cause) => {
74
+ timing.total = performance.now() - t0;
75
+ return new TaskError(code, timing, cause);
76
+ };
77
+ if (state !== 'ready')
78
+ throw fail(state);
79
+ if (signal?.aborted)
80
+ throw fail('cancelled', signal.reason);
81
+ if (running < limit) {
82
+ running++;
83
+ timing.queueWait = 0;
84
+ }
85
+ else if (queue.length < queueCapacity) {
86
+ await new Promise((resolve, reject) => {
87
+ const leave = (code, cause) => {
88
+ signal?.removeEventListener('abort', onAbort);
89
+ timing.queueWait = performance.now() - t0;
90
+ code ? reject(fail(code, cause)) : resolve();
91
+ };
92
+ const onAbort = () => {
93
+ queue.splice(queue.indexOf(leave), 1);
94
+ leave('cancelled', signal.reason);
95
+ };
96
+ signal?.addEventListener('abort', onAbort, { once: true });
97
+ queue.push(leave);
98
+ });
99
+ }
100
+ else {
101
+ throw fail('rejected');
102
+ }
103
+ // Now a running task holding a slot; the caller must end() it.
104
+ const sig = signal ? AbortSignal.any([signal, closer.signal]) : closer.signal;
105
+ return { t0, timing, sig };
106
+ };
107
+ // Errors thrown while running leave `total` to end().
108
+ const failure = (sig, timing, e) => sig.aborted ? new TaskError('cancelled', timing, sig.reason) : new TaskError('failed', timing, e);
109
+ const acquire = async (base, sig, timing) => {
110
+ if (sig.aborted)
111
+ throw new TaskError('cancelled', timing, sig.reason);
112
+ if (state === 'broken')
113
+ throw new TaskError('broken', timing); // broke while this task waited
114
+ const t1 = performance.now();
115
+ let task;
116
+ try {
117
+ task = await provider.start(base, { signal: sig });
118
+ }
119
+ catch (e) {
120
+ if (!sig.aborted && provider.broken(e)) {
121
+ if (state === 'ready') {
122
+ state = 'broken';
123
+ drain('broken');
124
+ }
125
+ throw new TaskError('broken', timing, e);
126
+ }
127
+ throw failure(sig, timing, e);
128
+ }
129
+ timing.acquire = performance.now() - t1;
130
+ return task; // caller owns it before checking sig.aborted, so end() destroys a late task
131
+ };
132
+ // Destroy → release slot → total. Runs before the task's outcome settles (FR-009b).
133
+ // A synchronous destroy() keeps the whole step synchronous (002: timing is published in the
134
+ // same turn as a paused consumer's abort); a returned promise is awaited, rejection swallowed.
135
+ const end = (task, t0, timing) => {
136
+ const done = () => {
137
+ release();
138
+ timing.total = performance.now() - t0;
139
+ };
140
+ let pending = undefined;
141
+ try {
142
+ pending = task?.destroy();
143
+ }
144
+ catch { }
145
+ if (pending)
146
+ return pending.then(done, done);
147
+ done();
148
+ };
149
+ return {
150
+ get state() { return state; },
151
+ snapshot: () => ({ state, active: running, queued: queue.length, limit, queueCapacity }),
152
+ async run(input, { signal, template } = {}) {
153
+ const base = pick(template); // before admission: a bad template consumes nothing
154
+ const { t0, timing, sig } = await admit(signal);
155
+ let task;
156
+ try {
157
+ task = await acquire(base, sig, timing);
158
+ if (sig.aborted)
159
+ throw new TaskError('cancelled', timing, sig.reason);
160
+ const t2 = performance.now();
161
+ const output = await task.prompt(input, { signal: sig }).catch((e) => { throw failure(sig, timing, e); });
162
+ timing.prompt = performance.now() - t2;
163
+ return { output, timing };
164
+ }
165
+ finally {
166
+ const pending = end(task, t0, timing);
167
+ if (pending)
168
+ await pending;
169
+ }
170
+ },
171
+ stream(input, { signal, template } = {}) {
172
+ let used = false;
173
+ const s = {
174
+ timing: undefined,
175
+ // Async generator: nothing runs before the first pull (lazy), and `break`/return()
176
+ // runs `finally` and cancels the provider stream before the loop exit completes.
177
+ async *[Symbol.asyncIterator]() {
178
+ if (used)
179
+ throw new TypeError('stream already consumed');
180
+ used = true;
181
+ const base = pick(template); // first pull, before admission
182
+ const { t0, timing, sig } = await admit(signal).catch((e) => {
183
+ s.timing = e.timing;
184
+ throw e;
185
+ });
186
+ let task;
187
+ let onAbort; // declared before cleanup, which reads it
188
+ let cleaning;
189
+ // Single-flight: every caller awaits the same cleanup.
190
+ const cleanup = () => (cleaning ??= (async () => {
191
+ if (onAbort)
192
+ sig.removeEventListener('abort', onAbort);
193
+ const pending = end(task, t0, timing);
194
+ if (pending)
195
+ await pending;
196
+ s.timing = timing;
197
+ })());
198
+ try {
199
+ task = await acquire(base, sig, timing);
200
+ if (sig.aborted)
201
+ throw new TaskError('cancelled', timing, sig.reason);
202
+ // The consumer may stop pulling while paused at `yield`; clean up on abort anyway.
203
+ onAbort = () => void cleanup();
204
+ sig.addEventListener('abort', onAbort, { once: true });
205
+ const t2 = performance.now();
206
+ try {
207
+ for await (const chunk of task.promptStreaming(input, { signal: sig })) {
208
+ yield chunk;
209
+ if (sig.aborted)
210
+ throw sig.reason; // resumed after abort; mapped below
211
+ }
212
+ }
213
+ catch (e) {
214
+ throw failure(sig, timing, e);
215
+ }
216
+ timing.prompt = performance.now() - t2;
217
+ }
218
+ finally {
219
+ await cleanup();
220
+ }
221
+ },
222
+ };
223
+ return s;
224
+ },
225
+ shutdown() {
226
+ // Stored synchronously, so repeated and concurrent calls share one cleanup.
227
+ return (closing ??= (async () => {
228
+ state = 'closed';
229
+ drain('closed');
230
+ closer.abort(new DOMException('Runtime closed', 'AbortError'));
231
+ if (running)
232
+ await new Promise((resolve) => { idle = resolve; });
233
+ for (const b of bases.values())
234
+ try {
235
+ await provider.destroy?.(b);
236
+ }
237
+ catch { }
238
+ try {
239
+ await provider.close?.();
240
+ }
241
+ catch { }
242
+ })());
243
+ },
244
+ };
245
+ }
@@ -0,0 +1,3 @@
1
+ export { createRuntime } from './browser/runtime.ts';
2
+ export { TaskError } from './core/runtime.ts';
3
+ export type { RuntimeOptions, Runtime, RuntimeSnapshot, TaskStream, TaskResult, TaskTiming } from './core/runtime.ts';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createRuntime } from "./browser/runtime.js";
2
+ export { TaskError } from "./core/runtime.js";
@@ -0,0 +1,27 @@
1
+ import { type Runtime, type RuntimeOptions } from '../core/runtime.ts';
2
+ type Chunk = {
3
+ choices: {
4
+ delta?: {
5
+ content?: string | null;
6
+ };
7
+ }[];
8
+ };
9
+ /** The subset of a WebLLM MLCEngine this module uses. */
10
+ export interface WebLLMEngine {
11
+ chat: {
12
+ completions: {
13
+ create(request: object): Promise<AsyncIterable<Chunk>>;
14
+ };
15
+ };
16
+ interruptGenerate(): void | Promise<void>;
17
+ getMessage(): Promise<string>;
18
+ unload(): Promise<void>;
19
+ }
20
+ /** Create a runtime on an application-created WebLLM engine.
21
+ *
22
+ * Ownership: once this resolves, the runtime uses the engine exclusively (do not run other
23
+ * generations on it) and unloads it at shutdown. If creation fails, the engine is untouched.
24
+ * `limit` must be 1: one engine generates one request at a time, and waiting tasks must stay in
25
+ * AkariSP's queue where cancellation is task-local (007 research E3, E4). */
26
+ export declare function createWebLLMRuntime(engine: WebLLMEngine, options?: RuntimeOptions): Promise<Runtime>;
27
+ export {};
@@ -0,0 +1,80 @@
1
+ import { createCoreRuntime } from "../core/runtime.js";
2
+ /** Create a runtime on an application-created WebLLM engine.
3
+ *
4
+ * Ownership: once this resolves, the runtime uses the engine exclusively (do not run other
5
+ * generations on it) and unloads it at shutdown. If creation fails, the engine is untouched.
6
+ * `limit` must be 1: one engine generates one request at a time, and waiting tasks must stay in
7
+ * AkariSP's queue where cancellation is task-local (007 research E3, E4). */
8
+ export async function createWebLLMRuntime(engine, options = {}) {
9
+ if (options.limit !== undefined && options.limit > 1) {
10
+ throw new TypeError('limit must be 1 for a WebLLM engine (one generation at a time)');
11
+ }
12
+ // A template is request configuration, so no destroy(base); the engine is the one
13
+ // provider-wide resource, so close() unloads it.
14
+ const provider = {
15
+ create: async (config = {}) => config,
16
+ start: async (base) => {
17
+ await engine.getMessage(); // throws ModelNotLoadedError once the engine is unloaded
18
+ return task(engine, base);
19
+ },
20
+ broken: (e) => ['ModelNotLoadedError', 'DeviceLostError'].includes(e?.name),
21
+ close: () => engine.unload(),
22
+ };
23
+ return createCoreRuntime(provider, options);
24
+ }
25
+ function task(engine, base) {
26
+ const { initialPrompts = [], ...settings } = base;
27
+ let it;
28
+ let pulled = false;
29
+ let done = false;
30
+ // Always streaming, also for prompt(): a non-streaming request after an interrupt returns ""
31
+ // in 0.2.85 (E5), while a streaming request resets the interrupt flag.
32
+ async function* promptStreaming(input, { signal }) {
33
+ const onAbort = () => void engine.interruptGenerate();
34
+ signal.addEventListener('abort', onAbort, { once: true });
35
+ try {
36
+ const messages = [...initialPrompts, ...(typeof input === 'string' ? [{ role: 'user', content: input }] : input)];
37
+ it = (await engine.chat.completions.create({ ...settings, messages, stream: true }))[Symbol.asyncIterator]();
38
+ // ponytail: manual next(), never for-await over `it`: leaving a for-await calls it.return(),
39
+ // which leaks the engine lock in 0.2.85 (E6). Switch once a release frees it in finally.
40
+ while (!signal.aborted) {
41
+ pulled = true;
42
+ const r = await it.next();
43
+ if (r.done) {
44
+ done = true;
45
+ break;
46
+ }
47
+ const text = r.value.choices[0]?.delta?.content;
48
+ if (text)
49
+ yield text;
50
+ }
51
+ if (signal.aborted)
52
+ throw signal.reason; // an interrupted generation ends without an error (E8)
53
+ }
54
+ finally {
55
+ signal.removeEventListener('abort', onAbort);
56
+ }
57
+ }
58
+ return {
59
+ promptStreaming,
60
+ async prompt(input, options) {
61
+ let output = '';
62
+ for await (const chunk of promptStreaming(input, options))
63
+ output += chunk;
64
+ return output;
65
+ },
66
+ // Interrupt and drain to the natural end: the only way 0.2.85 releases its lock (E6b).
67
+ // Called once per task by the core's end().
68
+ async destroy() {
69
+ if (!it || done)
70
+ return;
71
+ // ponytail: 0.2.85 resets the interrupt flag on the first next(), so an interrupt before it
72
+ // is lost; pulling first costs up to one time-to-first-token of cleanup latency.
73
+ if (!pulled && (await it.next()).done)
74
+ return;
75
+ await engine.interruptGenerate();
76
+ while (!(await it.next()).done)
77
+ ;
78
+ },
79
+ };
80
+ }
@@ -0,0 +1 @@
1
+ export { createWebLLMRuntime } from './webllm/runtime.ts';
package/dist/webllm.js ADDED
@@ -0,0 +1 @@
1
+ export { createWebLLMRuntime } from "./webllm/runtime.js";
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "akarisp",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Lightweight lifecycle runtime for browser LLM sessions: bounded queue, cancellation, and deterministic cleanup for the Chrome Prompt API and WebLLM",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/drow724/akariSP.git"
9
+ },
10
+ "type": "module",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./webllm": {
17
+ "types": "./dist/webllm.d.ts",
18
+ "default": "./dist/webllm.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "test": "node --test test/*.test.ts",
27
+ "test:browser": "playwright test",
28
+ "prepack": "npm run build"
29
+ },
30
+ "publishConfig": {
31
+ "tag": "alpha"
32
+ },
33
+ "devDependencies": {
34
+ "@playwright/test": "^1.63.0",
35
+ "typescript": "^5.9.3"
36
+ }
37
+ }