@ignitionai/cogitator 0.4.0 → 0.5.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/dist/src/pool.js CHANGED
@@ -1,4 +1,5 @@
1
- import { checkRequestAuthorization } from "./request-authorization.js";
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { requestAuthorization, checkRequestAuthorization } from "./request-authorization.js";
2
3
  export class PoolError extends Error {
3
4
  code;
4
5
  constructor(message, code) {
@@ -14,9 +15,87 @@ export class PiPool {
14
15
  opts;
15
16
  handles = new Map();
16
17
  eventListeners = new Set();
18
+ locks = new Map();
19
+ lockContext = new AsyncLocalStorage();
17
20
  constructor(opts) {
18
21
  this.opts = opts;
19
22
  }
23
+ async serial(id, action) {
24
+ const context = this.lockContext.getStore();
25
+ if (context?.id === id && context.active)
26
+ return action();
27
+ const previous = this.locks.get(id) ?? Promise.resolve();
28
+ const token = { id, active: true };
29
+ const next = previous.catch(() => undefined).then(() => this.lockContext.run(token, action));
30
+ this.locks.set(id, next);
31
+ try {
32
+ return await next;
33
+ }
34
+ finally {
35
+ token.active = false;
36
+ if (this.locks.get(id) === next)
37
+ this.locks.delete(id);
38
+ }
39
+ }
40
+ emit(id, event) {
41
+ this.opts.callbacks?.onEvent?.(id, event);
42
+ for (const listener of this.eventListeners)
43
+ listener(id, event);
44
+ }
45
+ client(id) { return this.live(id).client; }
46
+ async configure(id, apply, cancel) {
47
+ return this.serial(id, async () => {
48
+ const h = this.live(id);
49
+ if (h.pending)
50
+ throw new PoolError("configuration outstanding", "conflict");
51
+ const authorize = requestAuthorization.getStore();
52
+ const work = () => requestAuthorization.run(authorize ?? (() => { }), apply);
53
+ if (h.active || await this.streaming(h)) {
54
+ h.pending = work;
55
+ h.cancelPending = cancel;
56
+ return false;
57
+ }
58
+ await work();
59
+ return true;
60
+ });
61
+ }
62
+ async drain(h) {
63
+ if (h.dead || h.active)
64
+ return;
65
+ const pending = h.pending;
66
+ h.pending = undefined;
67
+ h.cancelPending = undefined;
68
+ if (pending) {
69
+ try {
70
+ await pending();
71
+ }
72
+ catch (error) {
73
+ this.emit(h.convId, { type: "configuration_error", error: String(error) });
74
+ }
75
+ }
76
+ while (!h.dead && !h.active && h.queue.length) {
77
+ const next = h.queue.shift();
78
+ this.queueChanged(h);
79
+ try {
80
+ await next.run();
81
+ }
82
+ catch (error) {
83
+ this.emit(h.convId, { type: "queue_error", message: next.text, error: String(error) });
84
+ }
85
+ }
86
+ }
87
+ queueChanged(h) {
88
+ this.emit(h.convId, { type: "queue_update", steering: [], followUp: h.queue.map(item => item.text) });
89
+ }
90
+ clearQueue(h) {
91
+ const count = h.queue.length;
92
+ const messages = h.queue.map(item => item.text);
93
+ h.queue = [];
94
+ if (count)
95
+ this.queueChanged(h);
96
+ if (count)
97
+ this.emit(h.convId, { type: "queue_cleared", count, messages, reason: "stopped" });
98
+ }
20
99
  /** Abonnement aux événements pi de toutes les conversations (fan-out SSE côté serveur). */
21
100
  onEvent(cb) {
22
101
  this.eventListeners.add(cb);
@@ -35,10 +114,11 @@ export class PiPool {
35
114
  }
36
115
  async streaming(h) {
37
116
  try {
38
- return (await h.client.getState()).isStreaming === true;
117
+ const state = await h.client.getState();
118
+ return h.active || state.isStreaming === true || state.isCompacting === true;
39
119
  }
40
120
  catch {
41
- return false; // process mort → considéré non-streaming, évincable
121
+ return true; // Unknown runtime state must never be evicted as idle.
42
122
  }
43
123
  }
44
124
  status(convId, status) {
@@ -49,37 +129,52 @@ export class PiPool {
49
129
  * Réutilise un process vivant ; reprend la session `.jsonl` si connue.
50
130
  */
51
131
  async ensure(convId, spawn) {
52
- const existing = this.handles.get(convId);
53
- if (existing && !existing.dead) {
54
- existing.lastActivityAt = Date.now();
55
- return {};
56
- }
57
- checkRequestAuthorization();
58
- await this.makeRoom();
59
- checkRequestAuthorization();
60
- const args = spawn.resumeSessionFile ? [...spawn.args, "--session", spawn.resumeSessionFile] : spawn.args;
61
- const client = this.opts.factory({ cwd: spawn.cwd, args, env: spawn.env });
62
- const handle = { convId, client, lastActivityAt: Date.now(), dead: false };
63
- this.handles.set(convId, handle);
64
- this.status(convId, "spawning");
65
- try {
66
- await client.start();
67
- const state = await client.getState();
68
- client.onEvent((event) => {
69
- handle.lastActivityAt = Date.now();
70
- this.opts.callbacks?.onEvent?.(convId, event);
71
- for (const l of this.eventListeners)
72
- l(convId, event);
132
+ return this.serial(convId, async () => {
133
+ const existing = this.handles.get(convId);
134
+ if (existing && !existing.dead) {
135
+ existing.lastActivityAt = Date.now();
136
+ return {};
137
+ }
138
+ const handle = await this.serial("pool:admission", async () => {
139
+ checkRequestAuthorization();
140
+ await this.makeRoom();
141
+ checkRequestAuthorization();
142
+ const args = spawn.resumeSessionFile ? [...spawn.args, "--session", spawn.resumeSessionFile] : spawn.args;
143
+ const client = this.opts.factory({ cwd: spawn.cwd, args, env: spawn.env });
144
+ const handle = { convId, client, lastActivityAt: Date.now(), dead: false, active: false, queue: [] };
145
+ this.handles.set(convId, handle);
146
+ return handle;
73
147
  });
74
- this.status(convId, "active");
75
- return { sessionFile: state.sessionFile };
76
- }
77
- catch (err) {
78
- handle.dead = true;
79
- this.handles.delete(convId);
80
- this.status(convId, "dead");
81
- throw err instanceof Error ? err : new Error(String(err));
82
- }
148
+ const { client } = handle;
149
+ this.status(convId, "spawning");
150
+ try {
151
+ await client.start();
152
+ const state = await client.getState();
153
+ client.onEvent((event) => {
154
+ if (handle.dead)
155
+ return;
156
+ handle.lastActivityAt = Date.now();
157
+ const type = event?.type;
158
+ if (type === "agent_start")
159
+ handle.active = true;
160
+ if (type === "agent_settled") {
161
+ handle.active = false;
162
+ this.lockContext.exit(() => { void this.serial(convId, () => this.drain(handle)); });
163
+ }
164
+ this.emit(convId, event);
165
+ });
166
+ await spawn.initialize?.(client);
167
+ this.status(convId, "active");
168
+ return { sessionFile: state.sessionFile };
169
+ }
170
+ catch (err) {
171
+ await client.stop().catch(() => undefined);
172
+ handle.dead = true;
173
+ this.handles.delete(convId);
174
+ this.status(convId, "dead");
175
+ throw err instanceof Error ? err : new Error(String(err));
176
+ }
177
+ });
83
178
  }
84
179
  /** Libère une place sous le plafond en évincant le plus vieux process non-streaming. */
85
180
  async makeRoom() {
@@ -88,14 +183,21 @@ export class PiPool {
88
183
  return;
89
184
  const oldestFirst = [...this.handles.values()].sort((a, b) => a.lastActivityAt - b.lastActivityAt);
90
185
  for (const h of oldestFirst) {
91
- if (await this.streaming(h))
186
+ if (this.locks.has(h.convId) || h.pending || await this.streaming(h))
92
187
  continue; // jamais de kill d'un travail en cours
93
188
  checkRequestAuthorization();
94
- await this.evict(h.convId);
95
- return;
189
+ if (await this.evictIdle(h))
190
+ return;
96
191
  }
97
192
  throw new PoolError("pool plein : toutes les sessions sont actives", "pool_full");
98
193
  }
194
+ evictIdle(h) {
195
+ return this.serial(h.convId, async () => {
196
+ if (this.handles.get(h.convId) !== h || h.pending || await this.streaming(h))
197
+ return false;
198
+ return this.evict(h.convId);
199
+ });
200
+ }
99
201
  live(convId) {
100
202
  const h = this.handles.get(convId);
101
203
  if (!h || h.dead)
@@ -104,43 +206,62 @@ export class PiPool {
104
206
  return h;
105
207
  }
106
208
  async prompt(convId, text, images) {
107
- const h = this.live(convId);
108
- try {
109
- // followUp : file comme le TUI quand un tour est en cours (sinon pi rejette le prompt)
110
- return await h.client.prompt(text, images, "followUp");
111
- }
112
- catch (err) {
113
- h.dead = true;
114
- this.status(convId, "dead");
115
- throw err;
116
- }
209
+ const authorize = requestAuthorization.getStore();
210
+ return this.serial(convId, async () => {
211
+ const h = this.live(convId);
212
+ const dispatch = async () => {
213
+ authorize?.();
214
+ h.active = true;
215
+ try {
216
+ const result = await h.client.prompt(text, images, "followUp");
217
+ if (result?.disposition === "handled")
218
+ h.active = (await h.client.getState()).isStreaming === true;
219
+ return result;
220
+ }
221
+ catch (error) {
222
+ await this.evict(convId);
223
+ throw error;
224
+ }
225
+ };
226
+ if (h.active || h.pending || await this.streaming(h)) {
227
+ h.queue.push({ text, run: dispatch });
228
+ this.queueChanged(h);
229
+ return { disposition: "queued" };
230
+ }
231
+ return dispatch();
232
+ });
117
233
  }
118
234
  async abort(convId) {
119
- try {
120
- await this.live(convId).client.abort();
121
- }
122
- catch {
123
- /* process déjà mort : abort est best-effort */
124
- }
125
- }
126
- async setModel(convId, provider, modelId) {
127
- const h = this.live(convId);
128
- await h.client.setModel(provider, modelId);
129
- h.lastActivityAt = Date.now();
235
+ return this.serial(convId, async () => {
236
+ try {
237
+ const h = this.live(convId);
238
+ this.clearQueue(h);
239
+ await h.client.abort();
240
+ }
241
+ catch {
242
+ /* process déjà mort : abort est best-effort */
243
+ }
244
+ });
130
245
  }
131
246
  async evict(convId) {
132
- const h = this.handles.get(convId);
133
- if (!h)
134
- return false;
135
- this.handles.delete(convId);
136
- try {
137
- await h.client.stop();
138
- }
139
- catch {
140
- /* stop best-effort */
141
- }
142
- this.status(convId, "idle");
143
- return true;
247
+ return this.serial(convId, async () => {
248
+ const h = this.handles.get(convId);
249
+ if (!h)
250
+ return false;
251
+ h.dead = true;
252
+ h.cancelPending?.();
253
+ h.pending = undefined;
254
+ this.clearQueue(h);
255
+ this.handles.delete(convId);
256
+ try {
257
+ await h.client.stop();
258
+ }
259
+ catch {
260
+ /* stop best-effort */
261
+ }
262
+ this.status(convId, "idle");
263
+ return true;
264
+ });
144
265
  }
145
266
  /** Recyclage idle : les process sans activité depuis idleMs et non-streaming sont stoppés. */
146
267
  async sweep(now = Date.now()) {
@@ -148,11 +269,11 @@ export class PiPool {
148
269
  for (const h of [...this.handles.values()]) {
149
270
  if (now - h.lastActivityAt < idleMs)
150
271
  continue;
151
- if (await this.streaming(h)) {
272
+ if (this.locks.has(h.convId) || h.pending || await this.streaming(h)) {
152
273
  h.lastActivityAt = now; // toujours en travail : on reporte
153
274
  continue;
154
275
  }
155
- await this.evict(h.convId);
276
+ await this.evictIdle(h);
156
277
  }
157
278
  }
158
279
  /** Attend l'événement `agent_settled` d'une conversation (suivi des runs cron). Rejette en timeout. */
@@ -166,7 +287,7 @@ export class PiPool {
166
287
  if (id !== convId)
167
288
  return;
168
289
  const type = event?.type;
169
- if (type === "agent_settled" || type === "agent_end") {
290
+ if (type === "agent_settled") {
170
291
  clearTimeout(timer);
171
292
  unsub();
172
293
  resolve();
@@ -0,0 +1,115 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { builtinModels } from "@earendil-works/pi-ai/providers/all";
3
+ import { atomicWriteJson, readJson } from "./json-files.js";
4
+ function fileCredentialStore(path) {
5
+ let queue = Promise.resolve();
6
+ const locked = (fn) => {
7
+ const run = queue.then(fn, fn);
8
+ queue = run.then(() => undefined, () => undefined);
9
+ return run;
10
+ };
11
+ const all = () => readJson(path, {});
12
+ return {
13
+ async read(providerId) {
14
+ return all()[providerId];
15
+ },
16
+ async list() {
17
+ return Object.entries(all()).map(([providerId, credential]) => ({ providerId, type: credential.type }));
18
+ },
19
+ modify(providerId, fn) {
20
+ return locked(async () => {
21
+ const file = all();
22
+ const next = await fn(file[providerId]);
23
+ if (next !== undefined) {
24
+ file[providerId] = next;
25
+ atomicWriteJson(path, file);
26
+ }
27
+ return next ?? file[providerId];
28
+ });
29
+ },
30
+ delete(providerId) {
31
+ return locked(async () => {
32
+ const file = all();
33
+ delete file[providerId];
34
+ atomicWriteJson(path, file);
35
+ });
36
+ },
37
+ };
38
+ }
39
+ function publicPrompt(prompt) {
40
+ return {
41
+ type: prompt.type,
42
+ message: prompt.message,
43
+ placeholder: "placeholder" in prompt ? prompt.placeholder : undefined,
44
+ options: prompt.type === "select" ? prompt.options.map((option) => ({ ...option })) : undefined,
45
+ };
46
+ }
47
+ export class ProviderLogins {
48
+ paths;
49
+ sessions = new Map();
50
+ constructor(paths) {
51
+ this.paths = paths;
52
+ }
53
+ start(providerId, type) {
54
+ const id = randomUUID();
55
+ const abort = new AbortController();
56
+ const session = { events: [], listeners: new Set(), abort };
57
+ this.sessions.set(id, session);
58
+ const emit = (event) => {
59
+ session.events.push(event);
60
+ for (const listener of session.listeners)
61
+ listener(event);
62
+ };
63
+ const models = builtinModels({ credentials: fileCredentialStore(this.paths.piAuthJson) });
64
+ void models.login(providerId, type, {
65
+ signal: abort.signal,
66
+ notify: (event) => emit(event),
67
+ prompt: (prompt) => new Promise((resolve, reject) => {
68
+ if (abort.signal.aborted) {
69
+ reject(abort.signal.reason instanceof Error ? abort.signal.reason : new Error("cancelled"));
70
+ return;
71
+ }
72
+ session.resolvePrompt = resolve;
73
+ session.rejectPrompt = reject;
74
+ emit({ type: "prompt", prompt: publicPrompt(prompt) });
75
+ }),
76
+ }, { agentName: "Cogitator" }).then(() => emit({ type: "done" }), (error) => {
77
+ if (abort.signal.aborted)
78
+ return;
79
+ emit({ type: "error", message: error instanceof Error ? error.message : "login failed" });
80
+ });
81
+ return { id };
82
+ }
83
+ has(id) {
84
+ return this.sessions.has(id);
85
+ }
86
+ subscribe(id, listener) {
87
+ const session = this.sessions.get(id);
88
+ if (!session)
89
+ return null;
90
+ session.listeners.add(listener);
91
+ return session.events;
92
+ }
93
+ unsubscribe(id, listener) {
94
+ this.sessions.get(id)?.listeners.delete(listener);
95
+ }
96
+ reply(id, value) {
97
+ const session = this.sessions.get(id);
98
+ if (!session?.resolvePrompt)
99
+ return false;
100
+ const resolve = session.resolvePrompt;
101
+ session.resolvePrompt = undefined;
102
+ session.rejectPrompt = undefined;
103
+ resolve(value);
104
+ return true;
105
+ }
106
+ cancel(id) {
107
+ const session = this.sessions.get(id);
108
+ if (!session)
109
+ return false;
110
+ session.rejectPrompt?.(new Error("cancelled"));
111
+ session.abort.abort();
112
+ this.sessions.delete(id);
113
+ return true;
114
+ }
115
+ }
@@ -1,6 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { existsSync, readdirSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { builtinProviders, getBuiltinModels, getBuiltinProviders } from "@earendil-works/pi-ai/providers/all";
4
5
  import { readJson, atomicWriteJson } from "./json-files.js";
5
6
  import { MCP_NAME, PROVIDER_ID } from "./schemas.js";
6
7
  export const API_PROTOCOLS = [
@@ -17,19 +18,71 @@ export const API_PROTOCOLS = [
17
18
  /** Limite imposée par pi sur la description d'un skill (frontmatter SKILL.md). */
18
19
  export const SKILL_DESCRIPTION_MAX = 1024;
19
20
  const AUTH_CHECK_TIMEOUT_MS = 15_000;
21
+ function mapStoreModels(models) {
22
+ return (models ?? []).map((m) => ({
23
+ id: String(m.id),
24
+ name: typeof m.name === "string" ? m.name : undefined,
25
+ reasoning: typeof m.reasoning === "boolean" ? m.reasoning : undefined,
26
+ }));
27
+ }
28
+ function overlayModels(base, extra) {
29
+ const byId = new Map(base.map((model) => [model.id, model]));
30
+ for (const model of extra)
31
+ byId.set(model.id, model);
32
+ const seen = new Set();
33
+ const out = [];
34
+ for (const model of extra) {
35
+ if (seen.has(model.id))
36
+ continue;
37
+ seen.add(model.id);
38
+ out.push(byId.get(model.id));
39
+ }
40
+ for (const model of base) {
41
+ if (seen.has(model.id))
42
+ continue;
43
+ seen.add(model.id);
44
+ out.push(model);
45
+ }
46
+ return out;
47
+ }
20
48
  export function readCatalog(paths) {
21
- const catalog = readJson(join(paths.piAgentDir, "models-store.json"), {});
49
+ const store = readJson(join(paths.piAgentDir, "models-store.json"), {});
22
50
  const customs = readJson(paths.piModelsJson, {}).providers ?? {};
23
51
  const out = new Map();
24
- for (const [id, entry] of Object.entries(catalog)) {
25
- out.set(id, (entry.models ?? []).map((m) => ({ id: String(m.id), name: m.name, reasoning: m.reasoning })));
52
+ for (const id of getBuiltinProviders()) {
53
+ out.set(id, getBuiltinModels(id).map((m) => ({ id: m.id, name: m.name, reasoning: m.reasoning })));
54
+ }
55
+ for (const [id, entry] of Object.entries(store)) {
56
+ if (!entry.models?.length)
57
+ continue;
58
+ const overlay = mapStoreModels(entry.models);
59
+ out.set(id, out.has(id) ? overlayModels(out.get(id), overlay) : overlay);
26
60
  }
27
61
  for (const [id, entry] of Object.entries(customs)) {
28
62
  const models = Array.isArray(entry.models) ? entry.models : [];
29
- out.set(id, models.map((m) => ({ id: String(m.id) }))); // un custom écrase le built-in éponyme
63
+ out.set(id, models.map((m) => ({ id: String(m.id) })));
64
+ }
65
+ for (const id of Object.keys(readAuth(paths))) {
66
+ if (!out.has(id))
67
+ out.set(id, []);
30
68
  }
31
69
  return out;
32
70
  }
71
+ let authMethodsCache;
72
+ export function authMethodsFor(id) {
73
+ if (!authMethodsCache) {
74
+ authMethodsCache = new Map();
75
+ for (const provider of builtinProviders()) {
76
+ const methods = [];
77
+ if (provider.auth.oauth)
78
+ methods.push({ type: "oauth", name: provider.auth.oauth.loginLabel ?? provider.auth.oauth.name });
79
+ if (provider.auth.apiKey)
80
+ methods.push({ type: "api_key", name: provider.auth.apiKey.name });
81
+ authMethodsCache.set(provider.id, methods);
82
+ }
83
+ }
84
+ return authMethodsCache.get(id) ?? [];
85
+ }
33
86
  function readAuth(paths) {
34
87
  return readJson(paths.piAuthJson, {});
35
88
  }
@@ -60,16 +113,21 @@ export async function listProviders(paths) {
60
113
  const catalog = readCatalog(paths);
61
114
  const auth = readAuth(paths);
62
115
  const customs = readJson(paths.piModelsJson, {}).providers ?? {};
63
- const view = async (id, source) => ({
64
- id,
65
- source,
66
- models: catalog.get(id) ?? [],
67
- auth: { configured: Boolean(auth[id]), type: auth[id]?.type ?? null, ready: await checkAuthReady(id) },
68
- });
69
- const views = await Promise.all([
70
- ...[...catalog.keys()].map((id) => view(id, customs[id] ? "custom" : "builtin")),
71
- ...Object.keys(customs).filter((id) => !catalog.has(id)).map((id) => view(id, "custom")),
72
- ]);
116
+ const ids = new Set([...catalog.keys(), ...Object.keys(auth), ...Object.keys(customs)]);
117
+ const views = await Promise.all([...ids].map(async (id) => {
118
+ const configured = Boolean(auth[id]);
119
+ return {
120
+ id,
121
+ source: customs[id] ? "custom" : "builtin",
122
+ models: catalog.get(id) ?? [],
123
+ auth: {
124
+ configured,
125
+ type: auth[id]?.type ?? null,
126
+ ready: configured ? await checkAuthReady(id) : false,
127
+ },
128
+ authMethods: authMethodsFor(id),
129
+ };
130
+ }));
73
131
  return views.sort((a, b) => a.id.localeCompare(b.id));
74
132
  }
75
133
  /** Un protocole API inconnu de pi est refusé (API_PROTOCOLS vient du catalogue pi). */
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Point de composition explicite des runtimes de conversation (Plan 0002 §6,
3
+ * I3 amendé) : UNE seule fabrique décide, selon `runtime_kind` figé à la
4
+ * création, d'acheminer vers le runtime classic (processus pi gérés par le
5
+ * pool) ou le runtime durable (harnais Durable du contrôleur, bail OS).
6
+ * Aucune autre partie du produit ne compose de runtime et aucune feature ne
7
+ * crée de processus ou de harnais non gérés.
8
+ */
9
+ /** runtime_kind figé à la création ; toute valeur historique/absente reste classic. */
10
+ export function runtimeKindOf(conv) {
11
+ return conv.runtime_kind === "durable" ? "durable" : "classic";
12
+ }
13
+ class ClassicRuntime {
14
+ deps;
15
+ kind = "classic";
16
+ constructor(deps) {
17
+ this.deps = deps;
18
+ }
19
+ async ensure(conv) {
20
+ return this.deps.spawner.ensure(conv);
21
+ }
22
+ async prompt(conv, text, _requestId, images) {
23
+ await this.deps.pool.prompt(conv.id, text, images);
24
+ return {};
25
+ }
26
+ async abort(conv) {
27
+ await this.deps.pool.abort(conv.id);
28
+ }
29
+ async evict(conv) {
30
+ await this.deps.pool.evict(conv.id);
31
+ }
32
+ isLive(conv) {
33
+ return this.deps.pool.isLive(conv.id);
34
+ }
35
+ async attachEvents() {
36
+ // Le fan-out classic se fait déjà au niveau serveur via pool.onEvent.
37
+ return () => { };
38
+ }
39
+ }
40
+ class DurableConversationRuntime {
41
+ deps;
42
+ kind = "durable";
43
+ constructor(deps) {
44
+ this.deps = deps;
45
+ }
46
+ async ensure() {
47
+ // Aucun processus pi : la runtime durable vit dans le contrôleur (gérée, avec bail).
48
+ return {};
49
+ }
50
+ async prompt(conv, text, requestId) {
51
+ if (!requestId)
52
+ throw new Error("requestId requis pour une conversation durable");
53
+ const runtime = await this.deps.durable.get(conv);
54
+ const accepted = await runtime.submit(text, requestId);
55
+ return { accepted: { requestId, ...accepted } };
56
+ }
57
+ async abort(conv) {
58
+ const runtime = this.deps.durable.getIfOpen(conv.id);
59
+ if (runtime)
60
+ await runtime.abort();
61
+ }
62
+ async evict(conv) {
63
+ await this.deps.durable.release(conv.id);
64
+ }
65
+ isLive(conv) {
66
+ return this.deps.durable.getIfOpen(conv.id) !== undefined;
67
+ }
68
+ async attachEvents(conv, send) {
69
+ const runtime = await this.deps.durable.get(conv);
70
+ return runtime.onCommitted((events) => {
71
+ for (const event of events)
72
+ send(event);
73
+ });
74
+ }
75
+ }
76
+ /**
77
+ * Fabrique unique de runtimes (I3 amendé) : la sélection se fait une fois par
78
+ * conversation selon son runtime_kind figé, puis la même instance est réutilisée.
79
+ */
80
+ export function composeRuntime(deps) {
81
+ const classic = new ClassicRuntime(deps);
82
+ const durable = new DurableConversationRuntime(deps);
83
+ const byConversation = new Map();
84
+ return (conv) => {
85
+ const cached = byConversation.get(conv.id);
86
+ if (cached)
87
+ return cached;
88
+ const runtime = runtimeKindOf(conv) === "durable" ? durable : classic;
89
+ byConversation.set(conv.id, runtime);
90
+ return runtime;
91
+ };
92
+ }