@qilin-agent/agent 0.0.0-stage → 3.1.3
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 +21 -0
- package/README.i18n.yaml +91 -0
- package/README.md +184 -2
- package/README.zh.md +185 -0
- package/lib/index.js +700 -0
- package/lib/types/archive-admission.d.ts +24 -0
- package/lib/types/archive-admission.js +35 -0
- package/lib/types/consumed-work.d.ts +39 -0
- package/lib/types/consumed-work.js +93 -0
- package/lib/types/dispatch.d.ts +111 -0
- package/lib/types/dispatch.js +95 -0
- package/lib/types/index.d.ts +379 -0
- package/lib/types/index.js +468 -0
- package/lib/types/model-selection.d.ts +50 -0
- package/lib/types/model-selection.js +95 -0
- package/lib/types/projection.d.ts +9 -0
- package/lib/types/projection.js +2 -0
- package/lib/types/runtime-types.d.ts +410 -0
- package/lib/types/runtime-types.js +8 -0
- package/lib/types/types.d.ts +95 -0
- package/lib/types/types.js +7 -0
- package/package.json +55 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
import { Service, getTraceable, symbols } from "@qilin-agent/kylin";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
import { isPromise } from "node:util/types";
|
|
4
|
+
import { scopeTarget } from "@qilin-agent/scope";
|
|
5
|
+
import { boundContextSummary, createUserMessage } from "@qilin-agent/llm";
|
|
6
|
+
//#region lib/types/archive-admission.js
|
|
7
|
+
/**
|
|
8
|
+
* The `turn` family of the Workspace registry's archive admission: whether a
|
|
9
|
+
* Session's own Agent is inside a turn, and its cancel when the Session is
|
|
10
|
+
* archived with its work. Installed by the registry's constructor, so it
|
|
11
|
+
* answers for every Agent the registry publishes.
|
|
12
|
+
*
|
|
13
|
+
* @module @qilin-agent/agent
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Answer `workspace/session-activity` with the `turn` family while the
|
|
17
|
+
* Session's Agent is running (a turn waiting for an approval or an answer
|
|
18
|
+
* included), and `workspace/session-stop` by cancelling that turn the way
|
|
19
|
+
* the user's own stop does — `agent.cancel({ kind: 'user' })`, but without
|
|
20
|
+
* the stop button's `keepInbox`, so queued input is discarded with a logged
|
|
21
|
+
* inbox splice instead of waking the archived Session later. Nothing is
|
|
22
|
+
* awaited to settlement. Both listeners live as long as `ctx`'s fiber.
|
|
23
|
+
* @param ctx - the registry's registration context.
|
|
24
|
+
* @param lookup - the registry's live-Agent lookup by Session id.
|
|
25
|
+
*/
|
|
26
|
+
function installTurnArchiveAdmission(ctx, lookup) {
|
|
27
|
+
ctx.on("workspace/session-activity", async ({ sessionId }, next) => {
|
|
28
|
+
const running = lookup(sessionId)?.status === "running";
|
|
29
|
+
const rest = await next();
|
|
30
|
+
if (!running) return rest;
|
|
31
|
+
return [{ kind: "turn" }, ...rest];
|
|
32
|
+
});
|
|
33
|
+
ctx.on("workspace/session-stop", ({ sessionId }) => {
|
|
34
|
+
const agent = lookup(sessionId);
|
|
35
|
+
if (agent?.status === "running") agent.cancel({ kind: "user" });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region lib/types/consumed-work.js
|
|
40
|
+
/**
|
|
41
|
+
* How one agent log accounts for the work it consumed.
|
|
42
|
+
*
|
|
43
|
+
* The turn and step vocabulary alone cannot answer this. A turn that stops
|
|
44
|
+
* before its first step leaves a `turn/end` shaped exactly like the balanced
|
|
45
|
+
* no-op turns a rejection or an empty claim produces, so reading turns in
|
|
46
|
+
* isolation either credits cut-short work as finished or convicts every no-op.
|
|
47
|
+
* The missing fact is the inbox's own record: {@link Inbox} logs each mutation
|
|
48
|
+
* with `removedCount` and marks a cancellation `outcome: 'canceled'`, which
|
|
49
|
+
* separates a turn claiming its input from work being dropped unrun.
|
|
50
|
+
*
|
|
51
|
+
* @module @qilin-agent/agent/consumed-work
|
|
52
|
+
*/
|
|
53
|
+
/**
|
|
54
|
+
* Whether a turn that consumed input but never reached a step ends in a way
|
|
55
|
+
* that accounts for that input. Only a `completed` end does not: it had
|
|
56
|
+
* nothing left to run once its claim was rewritten away. A `blocked` end is
|
|
57
|
+
* that input's ending too — the pre-step rejection that produced it discarded
|
|
58
|
+
* the claimed messages, so the work it took will never run.
|
|
59
|
+
* @param reason - the turn's recorded ending.
|
|
60
|
+
* @returns whether the ending accounts for the input the turn took.
|
|
61
|
+
*/
|
|
62
|
+
function accountsForClaim(reason) {
|
|
63
|
+
switch (reason.kind) {
|
|
64
|
+
case "completed": return false;
|
|
65
|
+
case "blocked":
|
|
66
|
+
case "aborted":
|
|
67
|
+
case "interrupted":
|
|
68
|
+
case "error": return true;
|
|
69
|
+
/* v8 ignore next 5 -- unreachable: `max-tokens` requires a step and short-circuits
|
|
70
|
+
* before this call; `forked` exists only in constructor seed history, while production
|
|
71
|
+
* callers fold an operation-owned suffix. `TurnEndReasonMap` is merge-extensible, so a
|
|
72
|
+
* backend-added variant cannot be listed; an unnameable ending over consumed input must
|
|
73
|
+
* not read as success. */
|
|
74
|
+
default: return true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Fold one agent log, or an owned suffix of one, into its account of consumed
|
|
79
|
+
* work. Single pass, and every input is the log itself: no caller has to sample
|
|
80
|
+
* live state before cancelling, so a cancellation issued by anyone — the owner's
|
|
81
|
+
* teardown, an ancestor's interrupt, an unloading plugin — reads the same.
|
|
82
|
+
* @param events - the log, or an owned suffix, to fold.
|
|
83
|
+
* @returns the accounting turn when one closed, and whether work was dropped unrun after it.
|
|
84
|
+
*/
|
|
85
|
+
function foldConsumedWork(events) {
|
|
86
|
+
const stepped = /* @__PURE__ */ new Set();
|
|
87
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
88
|
+
let open;
|
|
89
|
+
let end;
|
|
90
|
+
let droppedUnrun = false;
|
|
91
|
+
for (const event of events) switch (event.type) {
|
|
92
|
+
case "turn/start":
|
|
93
|
+
open = event.data.turn;
|
|
94
|
+
break;
|
|
95
|
+
case "step/start":
|
|
96
|
+
stepped.add(event.data.turn);
|
|
97
|
+
break;
|
|
98
|
+
case "agent/inbox/spliced": {
|
|
99
|
+
const { removedCount, outcome, inserted } = event.data;
|
|
100
|
+
if (removedCount === void 0) break;
|
|
101
|
+
if (outcome === "canceled") droppedUnrun ||= inserted.length === 0;
|
|
102
|
+
else if (open !== void 0) claimed.add(open);
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
case "turn/end": {
|
|
106
|
+
const { turn, reason } = event.data;
|
|
107
|
+
open = void 0;
|
|
108
|
+
if (stepped.delete(turn) || claimed.delete(turn) && accountsForClaim(reason)) {
|
|
109
|
+
end = event;
|
|
110
|
+
droppedUnrun = false;
|
|
111
|
+
}
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
default: break;
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
...end === void 0 ? {} : { end },
|
|
118
|
+
droppedUnrun
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region lib/types/model-selection.js
|
|
123
|
+
/**
|
|
124
|
+
* Agent-scoped model selection shared by runtime entry points.
|
|
125
|
+
* @module @qilin-agent/agent/model-selection
|
|
126
|
+
*/
|
|
127
|
+
function sameRoute(left, right) {
|
|
128
|
+
return left.provider === right.provider && left.model === right.model;
|
|
129
|
+
}
|
|
130
|
+
function routeLabel(route, other) {
|
|
131
|
+
return route.provider === other.provider ? route.model : `${route.provider}/${route.model}`;
|
|
132
|
+
}
|
|
133
|
+
function modelSwitchNotice(previous, selected) {
|
|
134
|
+
const from = routeLabel(previous, selected);
|
|
135
|
+
const to = routeLabel(selected, previous);
|
|
136
|
+
return createUserMessage({
|
|
137
|
+
content: [{
|
|
138
|
+
type: "text",
|
|
139
|
+
text: `[model changed: assistant turns above this point were generated by ${from}; the session continues with ${to}]`
|
|
140
|
+
}],
|
|
141
|
+
source: {
|
|
142
|
+
kind: "model-selection",
|
|
143
|
+
form: "notice",
|
|
144
|
+
summary: boundContextSummary(`${from} → ${to}`)
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Couple one mutable selection to Agent-scoped prompt assembly and request routing.
|
|
150
|
+
* Prompt assembly snapshots the selected model before delegating, then applies
|
|
151
|
+
* its provider/model pair and effort to request config so a
|
|
152
|
+
* concurrent switch takes effect on a later step instead of splitting the two
|
|
153
|
+
* surfaces. An absent selected effort clears any inherited effort, restoring
|
|
154
|
+
* the selected model's provider/default behavior.
|
|
155
|
+
*
|
|
156
|
+
* A provider/model change appends a durable user-role notice to the next
|
|
157
|
+
* admitted request. It compares the assembled selection with the latest
|
|
158
|
+
* request header; effort-only changes and empty no-request decisions add no
|
|
159
|
+
* notice. Failure before header persistence repeats the notice on the next
|
|
160
|
+
* request.
|
|
161
|
+
*
|
|
162
|
+
* @param agentCtx - The selected Agent's scoped context.
|
|
163
|
+
* @param selection - Mutable selection owned by the calling entry point.
|
|
164
|
+
* @returns Disposer for all scoped waterfall listeners.
|
|
165
|
+
*/
|
|
166
|
+
function installModelSelection(agentCtx, selection) {
|
|
167
|
+
const disposeAssembly = agentCtx.on("system-prompt/assemble", async (_assembly, _context, next) => {
|
|
168
|
+
const selected = selection.current;
|
|
169
|
+
const assembled = await next();
|
|
170
|
+
selection.assembled = selected;
|
|
171
|
+
if (selected === void 0) return assembled;
|
|
172
|
+
return {
|
|
173
|
+
...assembled,
|
|
174
|
+
variables: {
|
|
175
|
+
...assembled.variables,
|
|
176
|
+
provider: selected.provider,
|
|
177
|
+
model: selected.model
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
});
|
|
181
|
+
const disposeRequest = agentCtx.on("agent/request", async (_payload, next) => {
|
|
182
|
+
const resolved = await next();
|
|
183
|
+
const selected = selection.assembled;
|
|
184
|
+
if (selected === void 0) return resolved;
|
|
185
|
+
const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved;
|
|
186
|
+
return {
|
|
187
|
+
...withoutInheritedEffort,
|
|
188
|
+
provider: selected.provider,
|
|
189
|
+
model: selected.model,
|
|
190
|
+
...selected.reasoningEffort === void 0 ? {} : { reasoningEffort: selected.reasoningEffort }
|
|
191
|
+
};
|
|
192
|
+
});
|
|
193
|
+
const disposeNotice = agentCtx.on("agent/pre-step", async ({ agent, messages, signal, step }, next) => {
|
|
194
|
+
const decision = await next();
|
|
195
|
+
if (decision.kind === "reject" || signal.aborted) return decision;
|
|
196
|
+
if (decision.messages.length === 0 && (step === 1 || messages.length > 0)) return decision;
|
|
197
|
+
const selected = selection.assembled;
|
|
198
|
+
const previous = agent.session.requestHeader()?.config;
|
|
199
|
+
if (selected === void 0 || previous === void 0 || sameRoute(selected, previous)) return decision;
|
|
200
|
+
return {
|
|
201
|
+
...decision,
|
|
202
|
+
messages: [...decision.messages, modelSwitchNotice(previous, selected)]
|
|
203
|
+
};
|
|
204
|
+
}, { prepend: true });
|
|
205
|
+
return () => {
|
|
206
|
+
disposeAssembly();
|
|
207
|
+
disposeRequest();
|
|
208
|
+
disposeNotice();
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
//#endregion
|
|
212
|
+
//#region lib/types/dispatch.js
|
|
213
|
+
/**
|
|
214
|
+
* Agent-scoped dispatch and prompt assembly helpers. The fused dispatcher
|
|
215
|
+
* {@link agentEvents} couples the agent subject to its scope carrier, so the
|
|
216
|
+
* scope key and the payload's `agent` cannot diverge; repeat dispatchers (the
|
|
217
|
+
* loop driver) build it once in the agent's constructor and reuse it.
|
|
218
|
+
* @module @qilin-agent/agent/dispatch
|
|
219
|
+
*/
|
|
220
|
+
/**
|
|
221
|
+
* Build the fused scope carrier for one agent subject.
|
|
222
|
+
*
|
|
223
|
+
* The carrier is a stateless routing object. {@link agentEvents} accepts an
|
|
224
|
+
* existing carrier, so callers that dispatch repeatedly for the same agent
|
|
225
|
+
* (the loop driver) build it once in the agent's constructor and reuse it,
|
|
226
|
+
* keeping hot-path dispatches allocation-free.
|
|
227
|
+
* @param agent - the subject agent and scope key.
|
|
228
|
+
* @returns the carrier passed as the event dispatcher `this` value.
|
|
229
|
+
*/
|
|
230
|
+
function agentCarrier(agent) {
|
|
231
|
+
return scopeTarget(agent, agent);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Build a dispatcher that couples the agent subject to its scope carrier.
|
|
235
|
+
* @param ctx - the context to dispatch through (any context of the app).
|
|
236
|
+
* @param agent - the subject agent; also the scope-carrier key.
|
|
237
|
+
* @param carrier - the scope carrier to dispatch through; defaults to
|
|
238
|
+
* {@link agentCarrier} for the agent. Pass a constructor-built carrier to
|
|
239
|
+
* avoid rebuilding it for every dispatch.
|
|
240
|
+
* @returns the fused dispatcher.
|
|
241
|
+
*/
|
|
242
|
+
function agentEvents(ctx, agent, carrier = agentCarrier(agent)) {
|
|
243
|
+
const fused = (payload) => ({
|
|
244
|
+
...payload,
|
|
245
|
+
agent
|
|
246
|
+
});
|
|
247
|
+
return {
|
|
248
|
+
emit(name, payload) {
|
|
249
|
+
const args = [
|
|
250
|
+
carrier,
|
|
251
|
+
name,
|
|
252
|
+
fused(payload)
|
|
253
|
+
];
|
|
254
|
+
const callbacks = ctx.events.dispatch("emit", args);
|
|
255
|
+
for (const callback of callbacks) try {
|
|
256
|
+
const returned = callback(...args);
|
|
257
|
+
Promise.resolve(returned).catch((error) => {
|
|
258
|
+
ctx.logger.warn(`agent event "${name}" listener rejected: ${String(error)}`);
|
|
259
|
+
});
|
|
260
|
+
} catch (error) {
|
|
261
|
+
ctx.logger.warn(`agent event "${name}" listener threw: ${String(error)}`);
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
async serial(name, payload) {
|
|
265
|
+
const serial = ctx.serial;
|
|
266
|
+
return await serial(carrier, name, fused(payload));
|
|
267
|
+
},
|
|
268
|
+
waterfall(name, payload, ...rest) {
|
|
269
|
+
const waterfall = ctx.waterfall;
|
|
270
|
+
return waterfall(carrier, name, fused(payload), ...rest);
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Emit one contained agent notification without allocating a retained dispatcher.
|
|
276
|
+
* @param ctx - the context to dispatch through.
|
|
277
|
+
* @param agent - the subject agent and scope key.
|
|
278
|
+
* @param name - the agent-subject event to emit.
|
|
279
|
+
* @param payload - the event's payload fields; `agent` is injected.
|
|
280
|
+
*/
|
|
281
|
+
function emitAgentEvent(ctx, agent, name, payload) {
|
|
282
|
+
agentEvents(ctx, agent).emit(name, payload);
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Build the prompt assembly context with agent and scope set together, so
|
|
286
|
+
* agent-scoped prompt and tool contributions cannot be silently omitted.
|
|
287
|
+
* @param agent - the agent the assembly is for.
|
|
288
|
+
* @param signal - the current turn's explicit control signal, when assembly belongs to a turn.
|
|
289
|
+
* @returns the context to pass to `assemble()`.
|
|
290
|
+
*/
|
|
291
|
+
function assembleContextFor(agent, signal) {
|
|
292
|
+
return {
|
|
293
|
+
agent,
|
|
294
|
+
scope: agent,
|
|
295
|
+
...signal === void 0 ? {} : { signal }
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
//#endregion
|
|
299
|
+
//#region lib/types/index.js
|
|
300
|
+
/**
|
|
301
|
+
* Agent service: live registry, factory delegation, and process-local
|
|
302
|
+
* initiator scope. Concrete creation and driving belong to the loop.
|
|
303
|
+
*
|
|
304
|
+
* @module @qilin-agent/agent
|
|
305
|
+
*/
|
|
306
|
+
/** Thrown when create/resume is called before an agent factory is registered. */
|
|
307
|
+
const NO_FACTORY_MESSAGE = "no agent factory registered (load an agent-loop plugin)";
|
|
308
|
+
const NO_INITIATOR_MESSAGE = "no initiating agent is active";
|
|
309
|
+
const DISPOSED_INITIATOR_MESSAGE = "agent initiator scope is disposed";
|
|
310
|
+
/**
|
|
311
|
+
* Agent service (`ctx.agents`): tracks live agents and carries the initiating
|
|
312
|
+
* Agent through one process-local asynchronous driver chain. Agent *creation*
|
|
313
|
+
* is provided by whichever plugin implements the {@link AgentFactory}
|
|
314
|
+
* (`@qilin-agent/agent-loop`), registered via {@link setFactory}.
|
|
315
|
+
*
|
|
316
|
+
* Initiator methods provide same-process causal attribution only. Ambient
|
|
317
|
+
* presence is neither liveness proof nor authorization; subjects and owners
|
|
318
|
+
* remain explicit, as does identity at worker, process, persistence, and wire
|
|
319
|
+
* boundaries. Returned Promise boundaries drain during teardown, except a
|
|
320
|
+
* nested lineage that starts an owning-fiber unload is excluded from its own drain.
|
|
321
|
+
*/
|
|
322
|
+
var AgentRegistry = class extends Service {
|
|
323
|
+
store = /* @__PURE__ */ new Map();
|
|
324
|
+
factory;
|
|
325
|
+
initiators = new AsyncLocalStorage();
|
|
326
|
+
initiatorRuns = new AsyncLocalStorage();
|
|
327
|
+
initiatorState = "active";
|
|
328
|
+
activeInitiatorRuns = 0;
|
|
329
|
+
initiatorDrain;
|
|
330
|
+
initiatorDisposal;
|
|
331
|
+
constructor(ctx) {
|
|
332
|
+
super(ctx, "agents");
|
|
333
|
+
ctx.inject(["typert"], (typeCtx) => {
|
|
334
|
+
typeCtx.typert.lookups.register("agent", {
|
|
335
|
+
parameter: "agent",
|
|
336
|
+
wire: "agentId",
|
|
337
|
+
hostTypeSymbol: "@qilin-agent/agent#Agent",
|
|
338
|
+
wireTypeSymbol: "@qilin-agent/session/types#SessionId",
|
|
339
|
+
resolve: (sessionId) => this.get(sessionId)
|
|
340
|
+
});
|
|
341
|
+
typeCtx.typert.contexts.registerHost("agent", {
|
|
342
|
+
wire: "agentId",
|
|
343
|
+
wireTypeSymbol: "@qilin-agent/session/types#SessionId",
|
|
344
|
+
resolve: (sessionId) => this.get(sessionId)?.ctx
|
|
345
|
+
});
|
|
346
|
+
});
|
|
347
|
+
ctx.on("internal/status", (fiber) => {
|
|
348
|
+
if (fiber.state === 5 && this.hasLifecycleAncestor(fiber)) this.closeInitiators();
|
|
349
|
+
});
|
|
350
|
+
ctx.effect(function* () {
|
|
351
|
+
yield () => this.disposeInitiators();
|
|
352
|
+
yield () => {
|
|
353
|
+
this.closeInitiators();
|
|
354
|
+
};
|
|
355
|
+
}.bind(this), "agents.initiatorLifecycle()");
|
|
356
|
+
installTurnArchiveAdmission(ctx, (sessionId) => this.get(sessionId));
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Read the Agent that initiated the inherited asynchronous driver chain.
|
|
360
|
+
* Use this optional form for logging, tracing, metrics, or host attribution
|
|
361
|
+
* that also supports agentless calls. When a parent creates a child, setup
|
|
362
|
+
* reports the causal parent while the setup callback's Agent parameter
|
|
363
|
+
* identifies the child.
|
|
364
|
+
* @returns the inherited Agent, or `undefined` outside an initiator boundary
|
|
365
|
+
* and inside an explicit clearing boundary.
|
|
366
|
+
* @throws when this service instance has been disposed.
|
|
367
|
+
*/
|
|
368
|
+
currentInitiator() {
|
|
369
|
+
this.assertInitiatorsReadable();
|
|
370
|
+
return this.initiators.getStore();
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Read the initiating Agent and fail when no initiator boundary is active.
|
|
374
|
+
* Use this for private helpers contractually below a driver, or for a
|
|
375
|
+
* deployment-owned outbound request whose contract forbids agentless calls.
|
|
376
|
+
* Generic or direct-call paths use optional lookup or explicit request fields.
|
|
377
|
+
* @returns the inherited Agent.
|
|
378
|
+
* @throws when no initiator is active or this service instance has been disposed.
|
|
379
|
+
*/
|
|
380
|
+
requireInitiator() {
|
|
381
|
+
const agent = this.currentInitiator();
|
|
382
|
+
if (agent === void 0) throw new Error(NO_INITIATOR_MESSAGE);
|
|
383
|
+
return agent;
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Run an operation with one exact Agent as its process-local initiator. The
|
|
387
|
+
* exact synchronous value or Promise returned by the operation is preserved.
|
|
388
|
+
* Custom drivers and test harnesses wrap their complete returned foreground
|
|
389
|
+
* lifetime.
|
|
390
|
+
* A queue or wire receiver may establish this boundary only after validating
|
|
391
|
+
* explicit identity and resolving the exact live Agent; this method does neither.
|
|
392
|
+
* Detached work remains owned by the subsystem that starts it.
|
|
393
|
+
* @param agent - initiating Agent to inherit; presence is neither liveness proof nor authorization.
|
|
394
|
+
* @param operation - synchronous or asynchronous operation to invoke.
|
|
395
|
+
* @returns the exact value returned by `operation`.
|
|
396
|
+
* @throws when the initiator scope is closing/disposed, or when `operation` throws.
|
|
397
|
+
*/
|
|
398
|
+
withInitiator(agent, operation) {
|
|
399
|
+
return this.runWithInitiator(agent, operation);
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Run an operation inside a boundary that hides any inherited initiating
|
|
403
|
+
* Agent. The exact synchronous value or Promise is preserved.
|
|
404
|
+
* Use this while creating lazy shared timers, queue pumps, pool maintenance,
|
|
405
|
+
* watchers, or exporters so they do not inherit the first Agent that happens
|
|
406
|
+
* to initialize them. It clears only initiator attribution, not explicit
|
|
407
|
+
* fields, and does not own or drain detached resources.
|
|
408
|
+
* @param operation - synchronous or asynchronous operation to invoke without an initiator.
|
|
409
|
+
* @returns the exact value returned by `operation`.
|
|
410
|
+
* @throws when the initiator scope is closing/disposed, or when `operation` throws.
|
|
411
|
+
*/
|
|
412
|
+
withoutInitiator(operation) {
|
|
413
|
+
return this.runWithInitiator(void 0, operation);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Register the agent-creation factory (the loop calls this on construction,
|
|
417
|
+
* effect-scoped). A traced Cordis service is canonicalized to its concrete
|
|
418
|
+
* target; each create/resume call is then traced through that caller's
|
|
419
|
+
* context so ownership follows the caller without stacking proxy layers.
|
|
420
|
+
* Throws if a factory is already registered. Returns the disposer; on
|
|
421
|
+
* dispose the factory slot is cleared.
|
|
422
|
+
* @param factory - the loop-owned factory {@link create}/{@link resume} delegate to.
|
|
423
|
+
* @returns the disposer that clears the factory slot. The exact
|
|
424
|
+
* Cordis effect disposer (single-shot): composite (generator) effects may
|
|
425
|
+
* yield it directly — exact identity nests the teardown in order.
|
|
426
|
+
*/
|
|
427
|
+
setFactory(factory) {
|
|
428
|
+
return this.ctx.effect(() => {
|
|
429
|
+
if (this.factory !== void 0) throw new Error("an agent factory is already registered");
|
|
430
|
+
const target = factory[symbols.original] ?? factory;
|
|
431
|
+
this.factory = { target };
|
|
432
|
+
return () => {
|
|
433
|
+
this.factory = void 0;
|
|
434
|
+
};
|
|
435
|
+
}, "agents.setFactory()");
|
|
436
|
+
}
|
|
437
|
+
/** Return the active creation factory. */
|
|
438
|
+
requireFactory() {
|
|
439
|
+
if (this.factory === void 0) throw new Error(NO_FACTORY_MESSAGE);
|
|
440
|
+
return this.factory;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Create and publish a new agent through the registered factory.
|
|
444
|
+
* Distinct from {@link register} (which records an already-constructed
|
|
445
|
+
* agent): this constructs the agent and its session. Rejects if no factory is
|
|
446
|
+
* registered or creation/setup fails. The resolved {@link AgentHandle} lets
|
|
447
|
+
* the owner tear down exactly this agent.
|
|
448
|
+
* @param options - shared identity, optional live parent, session seed/metadata, and agent options.
|
|
449
|
+
* @returns the handle after setup, rollback-covered publication, and loop start complete.
|
|
450
|
+
*/
|
|
451
|
+
async create(options) {
|
|
452
|
+
const ownerCtx = this.ctx;
|
|
453
|
+
const { target } = this.requireFactory();
|
|
454
|
+
const receiver = getTraceable(ownerCtx, target);
|
|
455
|
+
return Reflect.apply(target.createAgent, receiver, [ownerCtx, options]);
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Load a persisted session and resume an agent on it through the registered
|
|
459
|
+
* factory. Rejects if no factory is registered; the factory rejects if
|
|
460
|
+
* session persistence is not configured or persistence/setup fails.
|
|
461
|
+
* @param options - persisted identity, optional live parent, configuration, and setup.
|
|
462
|
+
* @returns the handle after setup, rollback-covered publication, and loop start complete.
|
|
463
|
+
*/
|
|
464
|
+
async resume(options) {
|
|
465
|
+
const ownerCtx = this.ctx;
|
|
466
|
+
const { target } = this.requireFactory();
|
|
467
|
+
const receiver = getTraceable(ownerCtx, target);
|
|
468
|
+
return Reflect.apply(target.resume, receiver, [ownerCtx, options]);
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Register a live agent with source `startup`. Rejects if the id is already registered or a
|
|
472
|
+
* serial `agent/created` listener fails. Emits `agent/disposed`
|
|
473
|
+
* when the calling fiber is disposed — both with the agent's scope carrier
|
|
474
|
+
* (`scopeTarget(agent, agent)`): the subject is the agent in hand, so the
|
|
475
|
+
* emits are scope-filtered regardless of which context invoked `register`
|
|
476
|
+
* (calling through `agent.ctx` scopes EFFECTS; dispatch scoping always
|
|
477
|
+
* requires passing the carrier). The entry is a runtime root; factory-backed
|
|
478
|
+
* creation uses `options.parentAgent` for child ownership. Await the registration before using the agent.
|
|
479
|
+
* @param agent - the already-constructed agent to record in the store.
|
|
480
|
+
* @returns the awaitable Cordis effect disposer (single-shot; a repeat call
|
|
481
|
+
* returns undefined without awaiting an in-flight teardown). Exact
|
|
482
|
+
* identity is load-bearing: a composite (generator) effect that owns a
|
|
483
|
+
* teardown ORDER — the agent factory's lifecycle chain — must yield THIS
|
|
484
|
+
* function so Cordis nests the unregistration at that yield position;
|
|
485
|
+
* yielding a wrapper would leave it disposing as a concurrent sibling on
|
|
486
|
+
* owner unload, unregistering the agent (and emitting `agent/disposed`)
|
|
487
|
+
* while its final turn is still draining.
|
|
488
|
+
*/
|
|
489
|
+
register(agent) {
|
|
490
|
+
return this.ctx.effect(async function* () {
|
|
491
|
+
yield this.enter(agent, void 0);
|
|
492
|
+
await this.announce(agent, "startup");
|
|
493
|
+
}.bind(this), "agents.register()");
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Insert an already-constructed agent without announcing it. This is the
|
|
497
|
+
* advanced ordered-lifecycle primitive used by the async agent factory: it
|
|
498
|
+
* first completes setup while the agent is unpublished, then assigns the
|
|
499
|
+
* returned detach closure into its pre-installed composite teardown before
|
|
500
|
+
* calling {@link announce}. Ordinary callers use {@link register}.
|
|
501
|
+
* @param agent - the prepared, unpublished agent.
|
|
502
|
+
* @param owner - explicitly supplied live runtime owner, or
|
|
503
|
+
* undefined for a top-level runtime root. This is runtime ownership, not
|
|
504
|
+
* the resumed session's durable parent lineage.
|
|
505
|
+
* @returns an idempotent closure that removes this exact entry and emits
|
|
506
|
+
* `agent/disposed` with listener failures contained. When called from a
|
|
507
|
+
* `agent/created` listener, removal and disposal wait until the serial
|
|
508
|
+
* creation dispatch settles.
|
|
509
|
+
*/
|
|
510
|
+
enter(agent, owner) {
|
|
511
|
+
const id = agent.id;
|
|
512
|
+
if (id !== agent.session.id) throw new Error(`agent id "${id}" does not match session id "${agent.session.id}"`);
|
|
513
|
+
const carrier = scopeTarget(agent, agent);
|
|
514
|
+
if (this.store.has(id)) throw new Error(`agent "${id}" is already registered`);
|
|
515
|
+
const entry = {
|
|
516
|
+
id,
|
|
517
|
+
agent,
|
|
518
|
+
owner,
|
|
519
|
+
carrier,
|
|
520
|
+
announced: false,
|
|
521
|
+
announcing: false,
|
|
522
|
+
detachRequested: false
|
|
523
|
+
};
|
|
524
|
+
this.store.set(id, entry);
|
|
525
|
+
let entered = true;
|
|
526
|
+
const detach = () => {
|
|
527
|
+
if (!entered) return;
|
|
528
|
+
entered = false;
|
|
529
|
+
if (entry.announcing) {
|
|
530
|
+
entry.detachRequested = true;
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
this.detachEntered(entry);
|
|
534
|
+
};
|
|
535
|
+
return detach;
|
|
536
|
+
}
|
|
537
|
+
/** Remove one exact entered agent and emit its paired disposal when announced. */
|
|
538
|
+
detachEntered(entry) {
|
|
539
|
+
entry.detachRequested = false;
|
|
540
|
+
/* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */
|
|
541
|
+
if (this.store.get(entry.id) !== entry) return;
|
|
542
|
+
this.store.delete(entry.id);
|
|
543
|
+
if (!entry.announced) return;
|
|
544
|
+
this.emitDisposed(entry);
|
|
545
|
+
}
|
|
546
|
+
/** Emit the paired disposal edge through the entry's stable carrier. */
|
|
547
|
+
emitDisposed(entry) {
|
|
548
|
+
const args = [
|
|
549
|
+
entry.carrier,
|
|
550
|
+
"agent/disposed",
|
|
551
|
+
{ agent: entry.agent }
|
|
552
|
+
];
|
|
553
|
+
for (const callback of this.ctx.events.dispatch("emit", args)) try {
|
|
554
|
+
const returned = callback(...args);
|
|
555
|
+
Promise.resolve(returned).catch((error) => {
|
|
556
|
+
this.ctx.logger.warn(`agent "${entry.id}": agent/disposed listener rejected: ${String(error)}`);
|
|
557
|
+
});
|
|
558
|
+
} catch (error) {
|
|
559
|
+
this.ctx.logger.warn(`agent "${entry.id}": agent/disposed listener threw: ${String(error)}`);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Announce an agent previously inserted with {@link enter}.
|
|
564
|
+
* @param agent - the live inserted agent to announce.
|
|
565
|
+
* @param source - fresh creation, resume, clear, or compaction source.
|
|
566
|
+
* @param signal - optional factory initialization cancellation signal passed to listeners.
|
|
567
|
+
* @returns completion of the serial creation listeners; a listener failure rejects.
|
|
568
|
+
* @throws if `agent` is not the exact live registry entry for its id, or its
|
|
569
|
+
* creation announcement already began (including a reentrant call from a
|
|
570
|
+
* creation listener).
|
|
571
|
+
*/
|
|
572
|
+
async announce(agent, source, signal) {
|
|
573
|
+
const entry = this.store.get(agent.id);
|
|
574
|
+
if (entry === void 0 || entry.agent !== agent) throw new Error(`agent "${agent.id}" is not live in this registry`);
|
|
575
|
+
if (entry.announced || entry.announcing) throw new Error(`agent "${entry.id}" was already announced`);
|
|
576
|
+
entry.announcing = true;
|
|
577
|
+
entry.announced = true;
|
|
578
|
+
try {
|
|
579
|
+
await this.ctx.serial(entry.carrier, "agent/created", {
|
|
580
|
+
agent: entry.agent,
|
|
581
|
+
source,
|
|
582
|
+
...signal === void 0 ? {} : { signal }
|
|
583
|
+
});
|
|
584
|
+
} finally {
|
|
585
|
+
entry.announcing = false;
|
|
586
|
+
if (entry.detachRequested) this.detachEntered(entry);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Look up a live agent.
|
|
591
|
+
* @param id - the shared agent/session id to look up.
|
|
592
|
+
* @returns the agent, or undefined when no live agent has that id.
|
|
593
|
+
*/
|
|
594
|
+
get(id) {
|
|
595
|
+
return this.store.get(id)?.agent;
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Test whether a live agent was created through one exact parent agent's
|
|
599
|
+
* scoped context. Runtime ownership is independent of durable session
|
|
600
|
+
* lineage and remains unambiguous when unrelated providers reuse an id.
|
|
601
|
+
* @param id - the candidate child agent's shared agent/session id.
|
|
602
|
+
* @param owner - the expected runtime creator agent.
|
|
603
|
+
* @returns true only while the exact child entry is live under that owner.
|
|
604
|
+
*/
|
|
605
|
+
isOwnedBy(id, owner) {
|
|
606
|
+
return this.store.get(id)?.owner === owner;
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* All live agents, in registration order.
|
|
610
|
+
* @returns a fresh array; mutating it does not affect the registry.
|
|
611
|
+
*/
|
|
612
|
+
list() {
|
|
613
|
+
return [...this.store.values()].map((entry) => entry.agent);
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* All live top-level agents in registration order. A top-level agent was
|
|
617
|
+
* created without an owning agent context; durable session lineage does not
|
|
618
|
+
* affect this runtime relation, so a resumed fork may still be a root.
|
|
619
|
+
* @returns a fresh array; mutating it does not affect the registry.
|
|
620
|
+
*/
|
|
621
|
+
roots() {
|
|
622
|
+
return [...this.store.values()].filter((entry) => entry.owner === void 0).map((entry) => entry.agent);
|
|
623
|
+
}
|
|
624
|
+
/** Reject new initiator boundaries while inherited continuations drain. */
|
|
625
|
+
closeInitiators() {
|
|
626
|
+
if (this.initiatorState === "active") this.initiatorState = "closing";
|
|
627
|
+
}
|
|
628
|
+
/** Wait for returned-Promise boundaries, then invalidate retained references. */
|
|
629
|
+
disposeInitiators() {
|
|
630
|
+
return this.initiatorDisposal ??= (async () => {
|
|
631
|
+
this.closeInitiators();
|
|
632
|
+
this.releaseReentrantInitiatorRuns();
|
|
633
|
+
if (this.activeInitiatorRuns !== 0) {
|
|
634
|
+
this.initiatorDrain ??= Promise.withResolvers();
|
|
635
|
+
await this.initiatorDrain.promise;
|
|
636
|
+
}
|
|
637
|
+
this.initiatorState = "disposed";
|
|
638
|
+
this.initiators.disable();
|
|
639
|
+
this.initiatorRuns.disable();
|
|
640
|
+
})();
|
|
641
|
+
}
|
|
642
|
+
/** Establish one tracked initiator or clearing boundary. */
|
|
643
|
+
runWithInitiator(agent, operation) {
|
|
644
|
+
if (this.initiatorState !== "active") throw new Error(DISPOSED_INITIATOR_MESSAGE);
|
|
645
|
+
const run = {
|
|
646
|
+
active: true,
|
|
647
|
+
parent: this.initiatorRuns.getStore()
|
|
648
|
+
};
|
|
649
|
+
this.activeInitiatorRuns += 1;
|
|
650
|
+
let result;
|
|
651
|
+
try {
|
|
652
|
+
result = this.initiatorRuns.run(run, () => this.initiators.run(agent, operation));
|
|
653
|
+
} catch (error) {
|
|
654
|
+
this.releaseInitiatorRun(run);
|
|
655
|
+
throw error;
|
|
656
|
+
}
|
|
657
|
+
if (isPromise(result)) try {
|
|
658
|
+
Promise.prototype.then.call(result, () => {
|
|
659
|
+
this.releaseInitiatorRun(run);
|
|
660
|
+
}, () => {
|
|
661
|
+
this.releaseInitiatorRun(run);
|
|
662
|
+
});
|
|
663
|
+
} catch {
|
|
664
|
+
this.releaseInitiatorRun(run);
|
|
665
|
+
}
|
|
666
|
+
else this.releaseInitiatorRun(run);
|
|
667
|
+
return result;
|
|
668
|
+
}
|
|
669
|
+
/** Whether one unloading fiber owns this service's lifecycle. */
|
|
670
|
+
hasLifecycleAncestor(candidate) {
|
|
671
|
+
let fiber = this.ctx.fiber;
|
|
672
|
+
while (true) {
|
|
673
|
+
if (fiber === candidate) return true;
|
|
674
|
+
const parent = fiber.parent.fiber;
|
|
675
|
+
if (parent === fiber) return false;
|
|
676
|
+
fiber = parent;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
assertInitiatorsReadable() {
|
|
680
|
+
if (this.initiatorState === "disposed") throw new Error(DISPOSED_INITIATOR_MESSAGE);
|
|
681
|
+
}
|
|
682
|
+
/** Exclude the boundary chain that initiated this teardown from its own drain. */
|
|
683
|
+
releaseReentrantInitiatorRuns() {
|
|
684
|
+
let run = this.initiatorRuns.getStore();
|
|
685
|
+
while (run !== void 0) {
|
|
686
|
+
this.releaseInitiatorRun(run);
|
|
687
|
+
run = run.parent;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
releaseInitiatorRun(run) {
|
|
691
|
+
if (!run.active) return;
|
|
692
|
+
run.active = false;
|
|
693
|
+
this.activeInitiatorRuns -= 1;
|
|
694
|
+
if (this.activeInitiatorRuns !== 0) return;
|
|
695
|
+
this.initiatorDrain?.resolve();
|
|
696
|
+
this.initiatorDrain = void 0;
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
//#endregion
|
|
700
|
+
export { AgentRegistry, AgentRegistry as default, agentCarrier, agentEvents, assembleContextFor, emitAgentEvent, foldConsumedWork, installModelSelection };
|