tnega 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/agent.js +2207 -513
- package/dist/agent.js.map +4 -4
- package/dist/bin.js +942 -469
- package/dist/bin.js.map +3 -3
- package/dist/cli-runtime.js +943 -469
- package/dist/cli-runtime.js.map +3 -3
- package/dist/coding-agent.js +1623 -162
- package/dist/coding-agent.js.map +4 -4
- package/dist/eval.js +422 -158
- package/dist/eval.js.map +3 -3
- package/dist/evolve.js +512 -326
- package/dist/evolve.js.map +4 -4
- package/dist/index.js +951 -469
- package/dist/index.js.map +3 -3
- package/dist/llm.js +47 -3
- package/dist/llm.js.map +3 -3
- package/dist/session.js +91 -5
- package/dist/session.js.map +2 -2
- package/dist/types/packages/agent/src/inbox-durable.d.ts +5 -0
- package/dist/types/packages/agent/src/live.d.ts +24 -8
- package/dist/types/packages/agent/src/service.d.ts +8 -2
- package/dist/types/packages/agent/src/types.d.ts +40 -2
- package/dist/types/packages/cli/src/config.d.ts +2 -0
- package/dist/types/packages/cli/src/index.d.ts +1 -0
- package/dist/types/packages/llm/src/types.d.ts +2 -0
- package/dist/types/packages/session/src/index.d.ts +68 -7
- package/dist/types/packages/session/src/invariant.d.ts +2 -0
- package/dist/types/src/index.d.ts +2 -2
- package/dist/web/assets/{index-45pokiBH.js → index-Bq0i29_u.js} +30 -30
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
package/dist/coding-agent.js
CHANGED
|
@@ -2484,9 +2484,9 @@ var require_validate = __commonJS({
|
|
|
2484
2484
|
}
|
|
2485
2485
|
}
|
|
2486
2486
|
function returnResults(it) {
|
|
2487
|
-
const { gen, schemaEnv, validateName, ValidationError, opts } = it;
|
|
2487
|
+
const { gen, schemaEnv, validateName, ValidationError: ValidationError2, opts } = it;
|
|
2488
2488
|
if (schemaEnv.$async) {
|
|
2489
|
-
gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${
|
|
2489
|
+
gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError2}(${names_1.default.vErrors})`));
|
|
2490
2490
|
} else {
|
|
2491
2491
|
gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
|
|
2492
2492
|
if (opts.unevaluated)
|
|
@@ -2838,14 +2838,14 @@ var require_validation_error = __commonJS({
|
|
|
2838
2838
|
"node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js"(exports) {
|
|
2839
2839
|
"use strict";
|
|
2840
2840
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
2841
|
-
var
|
|
2841
|
+
var ValidationError2 = class extends Error {
|
|
2842
2842
|
constructor(errors) {
|
|
2843
2843
|
super("validation failed");
|
|
2844
2844
|
this.errors = errors;
|
|
2845
2845
|
this.ajv = this.validation = true;
|
|
2846
2846
|
}
|
|
2847
2847
|
};
|
|
2848
|
-
exports.default =
|
|
2848
|
+
exports.default = ValidationError2;
|
|
2849
2849
|
}
|
|
2850
2850
|
});
|
|
2851
2851
|
|
|
@@ -10322,7 +10322,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
|
|
|
10322
10322
|
}
|
|
10323
10323
|
return propValues;
|
|
10324
10324
|
});
|
|
10325
|
-
const
|
|
10325
|
+
const isObject3 = isObject;
|
|
10326
10326
|
const catchall = def.catchall;
|
|
10327
10327
|
let value;
|
|
10328
10328
|
const memo2 = globalConfig.memoizer;
|
|
@@ -10330,7 +10330,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
|
|
|
10330
10330
|
inst._zod.parse = (payload, ctx) => {
|
|
10331
10331
|
value ?? (value = _normalized.value);
|
|
10332
10332
|
const input = payload.value;
|
|
10333
|
-
if (!
|
|
10333
|
+
if (!isObject3(input)) {
|
|
10334
10334
|
payload.issues.push({
|
|
10335
10335
|
expected: "object",
|
|
10336
10336
|
code: "invalid_type",
|
|
@@ -10449,7 +10449,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
|
|
|
10449
10449
|
return doc.compile();
|
|
10450
10450
|
};
|
|
10451
10451
|
let fastpass;
|
|
10452
|
-
const
|
|
10452
|
+
const isObject3 = isObject;
|
|
10453
10453
|
const jit = !globalConfig.jitless;
|
|
10454
10454
|
const allowsEval2 = allowsEval;
|
|
10455
10455
|
const fastEnabled = jit && allowsEval2.value;
|
|
@@ -10458,7 +10458,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
|
|
|
10458
10458
|
inst._zod.parse = (payload, ctx) => {
|
|
10459
10459
|
value ?? (value = _normalized.value);
|
|
10460
10460
|
const input = payload.value;
|
|
10461
|
-
if (!
|
|
10461
|
+
if (!isObject3(input)) {
|
|
10462
10462
|
payload.issues.push({
|
|
10463
10463
|
expected: "object",
|
|
10464
10464
|
code: "invalid_type",
|
|
@@ -18045,7 +18045,7 @@ function copyMessages(messages) {
|
|
|
18045
18045
|
copy.tool_calls = message.tool_calls.map((call) => ({
|
|
18046
18046
|
id: call.id,
|
|
18047
18047
|
name: call.name,
|
|
18048
|
-
arguments: call.arguments
|
|
18048
|
+
arguments: structuredClone(call.arguments)
|
|
18049
18049
|
}));
|
|
18050
18050
|
}
|
|
18051
18051
|
return copy;
|
|
@@ -18076,6 +18076,75 @@ function copyCompletion(completion) {
|
|
|
18076
18076
|
}
|
|
18077
18077
|
return copy;
|
|
18078
18078
|
}
|
|
18079
|
+
function canonicalMessages(messages) {
|
|
18080
|
+
return JSON.stringify(messages.map((message) => ({
|
|
18081
|
+
role: message.role,
|
|
18082
|
+
content: message.content,
|
|
18083
|
+
...message.name ? { name: message.name } : {},
|
|
18084
|
+
...message.tool_call_id ? { tool_call_id: message.tool_call_id } : {},
|
|
18085
|
+
...message.tool_calls?.length ? { tool_calls: message.tool_calls } : {},
|
|
18086
|
+
...message.toolOk !== void 0 ? { toolOk: message.toolOk } : {},
|
|
18087
|
+
...message.toolError ? {
|
|
18088
|
+
toolError: { name: message.toolError.name, message: message.toolError.message }
|
|
18089
|
+
} : {}
|
|
18090
|
+
})));
|
|
18091
|
+
}
|
|
18092
|
+
function freezeRequestData(data) {
|
|
18093
|
+
const visited = /* @__PURE__ */ new Set();
|
|
18094
|
+
const freeze = (value) => {
|
|
18095
|
+
if (typeof value !== "object" || value === null || visited.has(value)) return;
|
|
18096
|
+
visited.add(value);
|
|
18097
|
+
for (const child of Object.values(value)) freeze(child);
|
|
18098
|
+
Object.freeze(value);
|
|
18099
|
+
};
|
|
18100
|
+
freeze(data);
|
|
18101
|
+
}
|
|
18102
|
+
function lockStreamRequest(request) {
|
|
18103
|
+
freezeRequestData(request.messages);
|
|
18104
|
+
request.tools = Object.freeze(request.tools.map((tool) => {
|
|
18105
|
+
const schema = structuredClone(tool.schema);
|
|
18106
|
+
freezeRequestData(schema);
|
|
18107
|
+
return Object.freeze({ ...tool, schema });
|
|
18108
|
+
}));
|
|
18109
|
+
Object.freeze(request.options);
|
|
18110
|
+
Object.freeze(request);
|
|
18111
|
+
}
|
|
18112
|
+
function requestHeaderFor(request, input) {
|
|
18113
|
+
const system = input.find((message) => message.role === "system")?.content;
|
|
18114
|
+
const tools = request.tools.map((tool) => ({
|
|
18115
|
+
name: tool.schema.name,
|
|
18116
|
+
description: tool.schema.description,
|
|
18117
|
+
...tool.schema.parameters ? { parameters: tool.schema.parameters } : {}
|
|
18118
|
+
}));
|
|
18119
|
+
const config2 = {
|
|
18120
|
+
...request.options.provider ? { provider: request.options.provider } : {},
|
|
18121
|
+
...request.options.model ? { model: request.options.model } : {},
|
|
18122
|
+
...request.options.temperature !== void 0 ? { temperature: request.options.temperature } : {}
|
|
18123
|
+
};
|
|
18124
|
+
return {
|
|
18125
|
+
...Object.keys(config2).length ? { config: config2 } : {},
|
|
18126
|
+
...system !== void 0 ? { system } : {},
|
|
18127
|
+
...tools.length ? { tools } : {}
|
|
18128
|
+
};
|
|
18129
|
+
}
|
|
18130
|
+
async function* completeAsStream(llm, messages, tools, options) {
|
|
18131
|
+
const id = randomUUID();
|
|
18132
|
+
yield { type: "message_start", id };
|
|
18133
|
+
const completion = await llm.complete(messages, tools, options);
|
|
18134
|
+
if (completion.content) yield { type: "message_delta", id, delta: completion.content };
|
|
18135
|
+
for (let index = 0; index < (completion.toolCalls?.length ?? 0); index += 1) {
|
|
18136
|
+
const call = completion.toolCalls[index];
|
|
18137
|
+
yield { type: "toolcall_start", id: call.id, index, name: call.name };
|
|
18138
|
+
yield {
|
|
18139
|
+
type: "toolcall_end",
|
|
18140
|
+
id: call.id,
|
|
18141
|
+
index,
|
|
18142
|
+
name: call.name,
|
|
18143
|
+
arguments: call.arguments
|
|
18144
|
+
};
|
|
18145
|
+
}
|
|
18146
|
+
yield { type: "message_stop", id, finishReason: completion.finishReason };
|
|
18147
|
+
}
|
|
18079
18148
|
function isCancelCause(value) {
|
|
18080
18149
|
if (typeof value !== "object" || value === null) return false;
|
|
18081
18150
|
const record2 = value;
|
|
@@ -18096,6 +18165,13 @@ function cancelCauseFromSignal(signal) {
|
|
|
18096
18165
|
if (isCancelCause(reason)) return reason;
|
|
18097
18166
|
return { type: "abort" };
|
|
18098
18167
|
}
|
|
18168
|
+
function abortedToolError(signal) {
|
|
18169
|
+
const cause = cancelCauseFromSignal(signal);
|
|
18170
|
+
return {
|
|
18171
|
+
name: "AbortError",
|
|
18172
|
+
message: `tool call aborted: ${cause?.type ?? "abort"}`
|
|
18173
|
+
};
|
|
18174
|
+
}
|
|
18099
18175
|
function toTurnEndReason(fields) {
|
|
18100
18176
|
const { cancelled, turnError, finishReason, cancelCause } = fields;
|
|
18101
18177
|
if (cancelled || finishReason === "cancelled") {
|
|
@@ -18140,6 +18216,78 @@ async function cancellableDelay(ms, signal) {
|
|
|
18140
18216
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
18141
18217
|
});
|
|
18142
18218
|
}
|
|
18219
|
+
var AssistantStreamAttempt = class {
|
|
18220
|
+
constructor(session, turn, step, nextRevision) {
|
|
18221
|
+
this.session = session;
|
|
18222
|
+
this.turn = turn;
|
|
18223
|
+
this.step = step;
|
|
18224
|
+
this.nextRevision = nextRevision;
|
|
18225
|
+
}
|
|
18226
|
+
session;
|
|
18227
|
+
turn;
|
|
18228
|
+
step;
|
|
18229
|
+
nextRevision;
|
|
18230
|
+
attemptId = randomUUID();
|
|
18231
|
+
records = [];
|
|
18232
|
+
ended = false;
|
|
18233
|
+
start() {
|
|
18234
|
+
return { type: "assistant/stream", frame: {
|
|
18235
|
+
type: "start",
|
|
18236
|
+
attemptId: this.attemptId,
|
|
18237
|
+
revision: this.nextRevision(),
|
|
18238
|
+
turn: this.turn,
|
|
18239
|
+
step: this.step
|
|
18240
|
+
} };
|
|
18241
|
+
}
|
|
18242
|
+
push(chunk) {
|
|
18243
|
+
if (this.ended) throw new AgentError("assistant attempt is already settled");
|
|
18244
|
+
const record2 = { time: Date.now(), chunk: structuredClone(chunk) };
|
|
18245
|
+
const index = this.records.length;
|
|
18246
|
+
this.records.push(record2);
|
|
18247
|
+
return { type: "assistant/stream", frame: {
|
|
18248
|
+
type: "chunk",
|
|
18249
|
+
attemptId: this.attemptId,
|
|
18250
|
+
revision: this.nextRevision(),
|
|
18251
|
+
index,
|
|
18252
|
+
...structuredClone(record2)
|
|
18253
|
+
} };
|
|
18254
|
+
}
|
|
18255
|
+
async settle(message) {
|
|
18256
|
+
if (this.ended) throw new AgentError("assistant attempt is already settled");
|
|
18257
|
+
const eventType = message ? "assistant/message" : "assistant/attempt";
|
|
18258
|
+
let event;
|
|
18259
|
+
try {
|
|
18260
|
+
event = message ? await this.session.append("assistant/message", { ...message, stream: this.records }) : await this.session.append("assistant/attempt", { turn: this.turn, step: this.step, stream: this.records });
|
|
18261
|
+
} catch (cause) {
|
|
18262
|
+
this.ended = true;
|
|
18263
|
+
const frame = { type: "assistant/stream", frame: {
|
|
18264
|
+
type: "end",
|
|
18265
|
+
attemptId: this.attemptId,
|
|
18266
|
+
revision: this.nextRevision(),
|
|
18267
|
+
index: this.records.length,
|
|
18268
|
+
outcome: { kind: "abandoned" }
|
|
18269
|
+
} };
|
|
18270
|
+
throw new AttemptSettlementError(cause, frame);
|
|
18271
|
+
}
|
|
18272
|
+
this.ended = true;
|
|
18273
|
+
return { type: "assistant/stream", frame: {
|
|
18274
|
+
type: "end",
|
|
18275
|
+
attemptId: this.attemptId,
|
|
18276
|
+
revision: this.nextRevision(),
|
|
18277
|
+
index: this.records.length,
|
|
18278
|
+
outcome: { kind: "committed", eventType, seq: event.seq }
|
|
18279
|
+
} };
|
|
18280
|
+
}
|
|
18281
|
+
};
|
|
18282
|
+
var AttemptSettlementError = class extends Error {
|
|
18283
|
+
constructor(cause, frame) {
|
|
18284
|
+
super("assistant attempt settlement failed");
|
|
18285
|
+
this.cause = cause;
|
|
18286
|
+
this.frame = frame;
|
|
18287
|
+
}
|
|
18288
|
+
cause;
|
|
18289
|
+
frame;
|
|
18290
|
+
};
|
|
18143
18291
|
var AgentService = class {
|
|
18144
18292
|
constructor(ctx, config2 = {}) {
|
|
18145
18293
|
this.ctx = ctx;
|
|
@@ -18148,9 +18296,24 @@ var AgentService = class {
|
|
|
18148
18296
|
}
|
|
18149
18297
|
ctx;
|
|
18150
18298
|
config;
|
|
18299
|
+
async *settleAttempt(attempt, message) {
|
|
18300
|
+
try {
|
|
18301
|
+
yield await attempt.settle(message);
|
|
18302
|
+
} catch (error2) {
|
|
18303
|
+
if (error2 instanceof AttemptSettlementError) {
|
|
18304
|
+
yield error2.frame;
|
|
18305
|
+
throw error2.cause;
|
|
18306
|
+
}
|
|
18307
|
+
throw error2;
|
|
18308
|
+
}
|
|
18309
|
+
}
|
|
18151
18310
|
inbox;
|
|
18152
18311
|
_seriesStarted = false;
|
|
18153
18312
|
_persistedRequest = false;
|
|
18313
|
+
_streamRevision = 0;
|
|
18314
|
+
_attempt(session, turn, step) {
|
|
18315
|
+
return new AssistantStreamAttempt(session, turn, step, () => ++this._streamRevision);
|
|
18316
|
+
}
|
|
18154
18317
|
/** Call when a request begins an explicit new model-message series. */
|
|
18155
18318
|
startSeries() {
|
|
18156
18319
|
this._seriesStarted = true;
|
|
@@ -18164,7 +18327,7 @@ var AgentService = class {
|
|
|
18164
18327
|
return this._persistedRequest;
|
|
18165
18328
|
}
|
|
18166
18329
|
async run(input, options = {}) {
|
|
18167
|
-
return consumeAgentStream(this._stream(input, options
|
|
18330
|
+
return consumeAgentStream(this._stream(input, options));
|
|
18168
18331
|
}
|
|
18169
18332
|
async *runStream(input, options = {}) {
|
|
18170
18333
|
const iterator = this._stream(input, options)[Symbol.asyncIterator]();
|
|
@@ -18174,7 +18337,7 @@ var AgentService = class {
|
|
|
18174
18337
|
yield next.value;
|
|
18175
18338
|
}
|
|
18176
18339
|
}
|
|
18177
|
-
async *_stream(input, options = {}
|
|
18340
|
+
async *_stream(input, options = {}) {
|
|
18178
18341
|
const claimed = input ?? this.inbox.claim();
|
|
18179
18342
|
if (!claimed) throw new AgentError("no agent input available");
|
|
18180
18343
|
await this.config.hooks?.beforeRun?.(claimed, options);
|
|
@@ -18182,26 +18345,32 @@ var AgentService = class {
|
|
|
18182
18345
|
const tools = this._tools();
|
|
18183
18346
|
const llm = this._llm();
|
|
18184
18347
|
if (!llm) throw new AgentError("no LLM adapter available");
|
|
18348
|
+
const streamAdapter = llm.stream;
|
|
18349
|
+
const persistChunks = streamAdapter !== void 0;
|
|
18185
18350
|
const maxTurns = options.maxTurns ?? this.config.maxTurns ?? 64;
|
|
18186
18351
|
const maxSteps = options.maxSteps ?? this.config.maxSteps ?? 64;
|
|
18187
18352
|
const contextBudget = options.contextBudget ?? this.config.contextBudget;
|
|
18188
18353
|
const injected = this.inbox.injected();
|
|
18189
18354
|
this.ctx.emit("agent/start", { input: claimed, options, injected });
|
|
18190
18355
|
let messages = await this._initialMessages(claimed);
|
|
18356
|
+
let claimedMessages = messages.filter((message) => message.role === "user");
|
|
18191
18357
|
const steps = [];
|
|
18192
18358
|
let output = "";
|
|
18193
18359
|
let finishReason = "stop";
|
|
18360
|
+
let lengthReached = false;
|
|
18194
18361
|
this.ctx.emit("agent/turn-start", {
|
|
18195
18362
|
input: claimed,
|
|
18196
18363
|
messages: copyMessages(messages),
|
|
18197
18364
|
injected
|
|
18198
18365
|
});
|
|
18199
|
-
const turn = await session.nextTurn();
|
|
18200
|
-
|
|
18201
|
-
turn,
|
|
18202
|
-
|
|
18203
|
-
|
|
18204
|
-
|
|
18366
|
+
const turn = options.turn ?? await session.nextTurn();
|
|
18367
|
+
if (options.turn === void 0) {
|
|
18368
|
+
await session.append("turn/start", {
|
|
18369
|
+
turn,
|
|
18370
|
+
input: claimed.text ?? claimed,
|
|
18371
|
+
reason: "user"
|
|
18372
|
+
});
|
|
18373
|
+
}
|
|
18205
18374
|
let index = 0;
|
|
18206
18375
|
let finalTurnGranted = false;
|
|
18207
18376
|
let currentStepIndex;
|
|
@@ -18220,20 +18389,22 @@ var AgentService = class {
|
|
|
18220
18389
|
messages = await this._enforceContextBudget(session, contextBudget, messages);
|
|
18221
18390
|
}
|
|
18222
18391
|
const stepInput = copyMessages(messages);
|
|
18223
|
-
const preStep = this.ctx.
|
|
18392
|
+
const preStep = await this.ctx.waterfallAsync("agent/pre-step", {
|
|
18224
18393
|
index,
|
|
18225
18394
|
turn,
|
|
18226
18395
|
step: index,
|
|
18227
18396
|
messages: stepInput,
|
|
18397
|
+
claimedMessages: copyMessages(claimedMessages),
|
|
18228
18398
|
...options.signal ? { signal: options.signal } : {}
|
|
18229
18399
|
}, (payload) => payload);
|
|
18230
|
-
if (!preStep || !Array.isArray(preStep.messages) || !preStep.messages.length) {
|
|
18400
|
+
if (!preStep || preStep.admission === "reject" || !Array.isArray(preStep.messages) || !preStep.messages.length) {
|
|
18231
18401
|
break;
|
|
18232
18402
|
}
|
|
18233
18403
|
if (preStep.startsRequestSeries) this._seriesStarted = true;
|
|
18234
18404
|
await session.append("step/start", { turn, step: index });
|
|
18235
18405
|
currentStepIndex = index;
|
|
18236
18406
|
const requestedInput = copyMessages(preStep.messages);
|
|
18407
|
+
const admittedHistory = await session.deriveMessages();
|
|
18237
18408
|
this.ctx.emit("agent/step", {
|
|
18238
18409
|
index,
|
|
18239
18410
|
turn,
|
|
@@ -18245,93 +18416,85 @@ var AgentService = class {
|
|
|
18245
18416
|
maxSteps: maxSteps - steps.length
|
|
18246
18417
|
};
|
|
18247
18418
|
if (options.signal) completeOptions.signal = options.signal;
|
|
18248
|
-
const request = this.ctx.waterfall("agent/request", {
|
|
18249
|
-
index,
|
|
18250
|
-
messages: requestedInput,
|
|
18251
|
-
tools: availableTools,
|
|
18252
|
-
options: completeOptions
|
|
18253
|
-
}, (payload) => payload);
|
|
18254
|
-
if (!request || !request.options || !request.tools) {
|
|
18255
|
-
throw new AgentError("agent/request must return a request payload");
|
|
18256
|
-
}
|
|
18257
18419
|
let llmMessages = copyMessages(requestedInput);
|
|
18258
18420
|
let completion;
|
|
18259
|
-
|
|
18421
|
+
let activeAttempt;
|
|
18260
18422
|
let attempt = 0;
|
|
18261
|
-
let persistedStepInput = false;
|
|
18262
18423
|
while (true) {
|
|
18263
18424
|
if (options.signal?.aborted) {
|
|
18264
18425
|
finishReason = "cancelled";
|
|
18265
18426
|
break;
|
|
18266
18427
|
}
|
|
18267
18428
|
const streamEvents = [];
|
|
18429
|
+
activeAttempt = this._attempt(session, turn, index);
|
|
18430
|
+
yield activeAttempt.start();
|
|
18431
|
+
const streamRequest = {
|
|
18432
|
+
index,
|
|
18433
|
+
messages: copyMessages(requestedInput),
|
|
18434
|
+
tools: [...availableTools],
|
|
18435
|
+
options: { ...completeOptions }
|
|
18436
|
+
};
|
|
18268
18437
|
try {
|
|
18269
|
-
|
|
18270
|
-
|
|
18271
|
-
|
|
18272
|
-
|
|
18273
|
-
|
|
18274
|
-
|
|
18275
|
-
|
|
18276
|
-
|
|
18277
|
-
|
|
18278
|
-
|
|
18279
|
-
|
|
18280
|
-
|
|
18281
|
-
|
|
18282
|
-
|
|
18283
|
-
return streamMethod(payload.messages, payload.tools, payload.options);
|
|
18284
|
-
}
|
|
18285
|
-
);
|
|
18286
|
-
if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
|
|
18287
|
-
throw new AgentError("llm/stream must return an async iterable stream");
|
|
18288
|
-
}
|
|
18438
|
+
const request = await this.ctx.waterfallAsync("agent/request", {
|
|
18439
|
+
index,
|
|
18440
|
+
messages: copyMessages(requestedInput),
|
|
18441
|
+
tools: streamRequest.tools,
|
|
18442
|
+
options: streamRequest.options
|
|
18443
|
+
}, (payload) => payload);
|
|
18444
|
+
if (!request || !request.options || !request.tools) {
|
|
18445
|
+
throw new AgentError("agent/request must return a request payload");
|
|
18446
|
+
}
|
|
18447
|
+
streamRequest.tools = request.tools;
|
|
18448
|
+
streamRequest.options = request.options;
|
|
18449
|
+
let preparation;
|
|
18450
|
+
const prepareRequest = () => preparation ??= (async () => {
|
|
18451
|
+
lockStreamRequest(streamRequest);
|
|
18289
18452
|
llmMessages = copyMessages(streamRequest.messages);
|
|
18290
|
-
|
|
18291
|
-
|
|
18292
|
-
|
|
18293
|
-
|
|
18294
|
-
|
|
18295
|
-
|
|
18296
|
-
|
|
18297
|
-
|
|
18298
|
-
|
|
18299
|
-
|
|
18300
|
-
|
|
18301
|
-
|
|
18302
|
-
|
|
18303
|
-
|
|
18304
|
-
|
|
18305
|
-
|
|
18306
|
-
|
|
18307
|
-
|
|
18308
|
-
|
|
18309
|
-
|
|
18310
|
-
|
|
18311
|
-
|
|
18312
|
-
|
|
18313
|
-
|
|
18314
|
-
|
|
18315
|
-
|
|
18316
|
-
}
|
|
18317
|
-
persistedStepInput = true;
|
|
18453
|
+
await this._persistStepInput(session, streamRequest, llmMessages, admittedHistory);
|
|
18454
|
+
await this._assertReplayable(session, streamRequest, llmMessages);
|
|
18455
|
+
})();
|
|
18456
|
+
const stream = await this.ctx.waterfallAsync(
|
|
18457
|
+
"llm/stream",
|
|
18458
|
+
streamRequest,
|
|
18459
|
+
(payload) => (async function* () {
|
|
18460
|
+
await prepareRequest();
|
|
18461
|
+
yield* streamAdapter ? streamAdapter.call(llm, payload.messages, payload.tools, payload.options) : completeAsStream(llm, payload.messages, payload.tools, payload.options);
|
|
18462
|
+
})()
|
|
18463
|
+
);
|
|
18464
|
+
if (!stream || typeof stream[Symbol.asyncIterator] !== "function") {
|
|
18465
|
+
throw new AgentError("llm/stream must return an async iterable stream");
|
|
18466
|
+
}
|
|
18467
|
+
await prepareRequest();
|
|
18468
|
+
let chunkIndex = 0;
|
|
18469
|
+
for await (const event of stream) {
|
|
18470
|
+
streamEvents.push(structuredClone(event));
|
|
18471
|
+
yield activeAttempt.push(event);
|
|
18472
|
+
if (persistChunks && event.type === "message_delta") {
|
|
18473
|
+
await session.append("assistant/chunk", {
|
|
18474
|
+
id: event.id,
|
|
18475
|
+
content: event.delta,
|
|
18476
|
+
index: chunkIndex
|
|
18477
|
+
});
|
|
18478
|
+
chunkIndex += 1;
|
|
18318
18479
|
}
|
|
18319
|
-
|
|
18480
|
+
yield event;
|
|
18481
|
+
}
|
|
18482
|
+
completion = completionFromStreamEvents(streamEvents);
|
|
18483
|
+
if (completion.finishReason === "error" || completion.finishReason === "cancelled") {
|
|
18484
|
+
const terminalReason = completion.finishReason;
|
|
18485
|
+
completion = void 0;
|
|
18486
|
+
throw new AgentError(`LLM stream finished with ${terminalReason}`);
|
|
18320
18487
|
}
|
|
18321
18488
|
break;
|
|
18322
18489
|
} catch (error2) {
|
|
18323
|
-
|
|
18324
|
-
if (content) {
|
|
18325
|
-
await session.append("assistant/message", {
|
|
18326
|
-
content,
|
|
18327
|
-
interrupted: true
|
|
18328
|
-
});
|
|
18329
|
-
llmMessages = await session.deriveMessages();
|
|
18330
|
-
}
|
|
18490
|
+
yield activeAttempt.push({ type: "stream_error", error: toToolError(error2) });
|
|
18331
18491
|
if (options.signal?.aborted) {
|
|
18492
|
+
const content = partialStreamContent(streamEvents);
|
|
18493
|
+
yield* this.settleAttempt(activeAttempt, content ? { content, interrupted: true } : void 0);
|
|
18332
18494
|
finishReason = "cancelled";
|
|
18333
18495
|
break;
|
|
18334
18496
|
}
|
|
18497
|
+
yield* this.settleAttempt(activeAttempt);
|
|
18335
18498
|
attempt += 1;
|
|
18336
18499
|
const failure = toToolError(error2);
|
|
18337
18500
|
const decision = await this.ctx.waterfallAsync(
|
|
@@ -18340,14 +18503,14 @@ var AgentService = class {
|
|
|
18340
18503
|
index,
|
|
18341
18504
|
turn,
|
|
18342
18505
|
step: index,
|
|
18343
|
-
messages: copyMessages(
|
|
18344
|
-
tools:
|
|
18345
|
-
options:
|
|
18506
|
+
messages: copyMessages(streamRequest.messages),
|
|
18507
|
+
tools: [...streamRequest.tools],
|
|
18508
|
+
options: { ...streamRequest.options },
|
|
18346
18509
|
attempt,
|
|
18347
18510
|
error: error2,
|
|
18348
18511
|
failure,
|
|
18349
|
-
...
|
|
18350
|
-
...
|
|
18512
|
+
...streamRequest.options.provider ? { provider: streamRequest.options.provider } : {},
|
|
18513
|
+
...streamRequest.options.model ? { model: streamRequest.options.model } : {},
|
|
18351
18514
|
...options.signal ? { signal: options.signal } : {}
|
|
18352
18515
|
},
|
|
18353
18516
|
() => void 0
|
|
@@ -18372,16 +18535,30 @@ var AgentService = class {
|
|
|
18372
18535
|
await session.append("llm/retry-started", { retryId, retry: attempt });
|
|
18373
18536
|
}
|
|
18374
18537
|
}
|
|
18375
|
-
if (
|
|
18376
|
-
|
|
18538
|
+
if (!completion || !activeAttempt) {
|
|
18539
|
+
if (options.signal?.aborted) {
|
|
18540
|
+
finishReason = "cancelled";
|
|
18541
|
+
break;
|
|
18542
|
+
}
|
|
18543
|
+
throw new AgentError("LLM adapter did not produce a completion");
|
|
18544
|
+
}
|
|
18377
18545
|
const toolCalls = completion.toolCalls ?? [];
|
|
18378
|
-
if (
|
|
18546
|
+
if (completion.finishReason === "length") lengthReached = true;
|
|
18547
|
+
if (options.signal?.aborted && toolCalls.length === 0) {
|
|
18548
|
+
yield activeAttempt.push({ type: "stream_error", error: { name: "AbortError", message: "stream aborted" } });
|
|
18549
|
+
yield* this.settleAttempt(activeAttempt);
|
|
18550
|
+
finishReason = "cancelled";
|
|
18551
|
+
break;
|
|
18552
|
+
}
|
|
18553
|
+
if (finalTurnGranted && toolCalls.length && !options.signal?.aborted) {
|
|
18554
|
+
yield activeAttempt.push({ type: "stream_error", error: { name: "AgentError", message: "maximum turns reached" } });
|
|
18555
|
+
yield* this.settleAttempt(activeAttempt);
|
|
18379
18556
|
finishReason = "max_turns";
|
|
18380
18557
|
break;
|
|
18381
18558
|
}
|
|
18382
18559
|
const toolResults = [];
|
|
18383
18560
|
if (toolCalls.length) {
|
|
18384
|
-
|
|
18561
|
+
yield* this.settleAttempt(activeAttempt, {
|
|
18385
18562
|
content: completion.content ?? "",
|
|
18386
18563
|
toolCalls: toolCalls.map((call) => ({
|
|
18387
18564
|
id: call.id,
|
|
@@ -18402,18 +18579,30 @@ var AgentService = class {
|
|
|
18402
18579
|
if (options.signal) toolOptions.signal = options.signal;
|
|
18403
18580
|
const startedAt = Date.now();
|
|
18404
18581
|
let result;
|
|
18405
|
-
|
|
18406
|
-
result = await tools.execute(call.name, call.arguments, toolOptions);
|
|
18407
|
-
} catch (error2) {
|
|
18582
|
+
if (options.signal?.aborted) {
|
|
18408
18583
|
result = {
|
|
18409
18584
|
ok: false,
|
|
18410
18585
|
name: call.name,
|
|
18411
18586
|
callId: call.id,
|
|
18412
18587
|
input: call.arguments,
|
|
18413
|
-
error:
|
|
18588
|
+
error: abortedToolError(options.signal),
|
|
18414
18589
|
startedAt,
|
|
18415
18590
|
durationMs: Date.now() - startedAt
|
|
18416
18591
|
};
|
|
18592
|
+
} else {
|
|
18593
|
+
try {
|
|
18594
|
+
result = await tools.execute(call.name, call.arguments, toolOptions);
|
|
18595
|
+
} catch (error2) {
|
|
18596
|
+
result = {
|
|
18597
|
+
ok: false,
|
|
18598
|
+
name: call.name,
|
|
18599
|
+
callId: call.id,
|
|
18600
|
+
input: call.arguments,
|
|
18601
|
+
error: toToolError(error2),
|
|
18602
|
+
startedAt,
|
|
18603
|
+
durationMs: Date.now() - startedAt
|
|
18604
|
+
};
|
|
18605
|
+
}
|
|
18417
18606
|
}
|
|
18418
18607
|
toolResults.push(result);
|
|
18419
18608
|
const toolResultPayload = {
|
|
@@ -18455,7 +18644,7 @@ var AgentService = class {
|
|
|
18455
18644
|
output = completion.content;
|
|
18456
18645
|
}
|
|
18457
18646
|
if (!toolCalls.length) {
|
|
18458
|
-
|
|
18647
|
+
yield* this.settleAttempt(activeAttempt, { content: completion.content ?? "" });
|
|
18459
18648
|
}
|
|
18460
18649
|
await session.append("step/end", {
|
|
18461
18650
|
turn,
|
|
@@ -18466,19 +18655,19 @@ var AgentService = class {
|
|
|
18466
18655
|
currentStepIndex = void 0;
|
|
18467
18656
|
const nextMessages = this._extendMessages(llmMessages, completion, toolResults);
|
|
18468
18657
|
const concludesTurn = toolResults.some((result) => result.concludesTurn === true);
|
|
18469
|
-
|
|
18470
|
-
|
|
18471
|
-
|
|
18472
|
-
}
|
|
18473
|
-
if (toolCalls.length === 0) {
|
|
18474
|
-
finishReason = completion.finishReason === "length" ? "length" : completion.finishReason === "error" ? "error" : "stop";
|
|
18658
|
+
let nextStepMessages = await this._claimNextStepMessages();
|
|
18659
|
+
if ((toolCalls.length === 0 || concludesTurn) && nextStepMessages.length === 0) {
|
|
18660
|
+
finishReason = lengthReached ? "length" : completion.finishReason === "error" ? "error" : "stop";
|
|
18475
18661
|
const keepGoing = await this.ctx.serial("agent/turn-stopping", {
|
|
18476
18662
|
index,
|
|
18477
18663
|
turn,
|
|
18478
18664
|
steps: copySteps(steps),
|
|
18479
18665
|
finishReason
|
|
18480
18666
|
});
|
|
18481
|
-
if (!keepGoing)
|
|
18667
|
+
if (!keepGoing) {
|
|
18668
|
+
nextStepMessages = await this._claimNextStepMessages();
|
|
18669
|
+
if (nextStepMessages.length === 0) break;
|
|
18670
|
+
}
|
|
18482
18671
|
}
|
|
18483
18672
|
if (index + 1 >= maxTurns && !finalTurnGranted) {
|
|
18484
18673
|
finalTurnGranted = true;
|
|
@@ -18488,7 +18677,8 @@ var AgentService = class {
|
|
|
18488
18677
|
}
|
|
18489
18678
|
if (toolCalls.length) finishReason = "tool_calls";
|
|
18490
18679
|
index += 1;
|
|
18491
|
-
messages = nextMessages;
|
|
18680
|
+
messages = [...nextMessages, ...nextStepMessages];
|
|
18681
|
+
claimedMessages = nextStepMessages.filter((message) => message.role === "user");
|
|
18492
18682
|
}
|
|
18493
18683
|
} catch (error2) {
|
|
18494
18684
|
turnError = error2;
|
|
@@ -18574,23 +18764,22 @@ var AgentService = class {
|
|
|
18574
18764
|
});
|
|
18575
18765
|
return compactMessages.map((message) => copyMessages([message])[0]);
|
|
18576
18766
|
}
|
|
18577
|
-
async _persistStepInput(session, request, input) {
|
|
18578
|
-
const
|
|
18579
|
-
const
|
|
18580
|
-
|
|
18581
|
-
|
|
18582
|
-
|
|
18583
|
-
|
|
18584
|
-
|
|
18585
|
-
|
|
18586
|
-
|
|
18587
|
-
|
|
18588
|
-
|
|
18589
|
-
|
|
18590
|
-
|
|
18591
|
-
|
|
18592
|
-
|
|
18593
|
-
};
|
|
18767
|
+
async _persistStepInput(session, request, input, admittedHistory) {
|
|
18768
|
+
const surface = await session.deriveMessages();
|
|
18769
|
+
const owned = admittedHistory.filter((message) => !isUserOrSystemMessage(message));
|
|
18770
|
+
let ownerIndex = 0;
|
|
18771
|
+
for (const message of input) {
|
|
18772
|
+
if (isUserOrSystemMessage(message)) continue;
|
|
18773
|
+
const actual = canonicalMessages([message]);
|
|
18774
|
+
while (ownerIndex < owned.length && canonicalMessages([owned[ownerIndex]]) !== actual) {
|
|
18775
|
+
ownerIndex += 1;
|
|
18776
|
+
}
|
|
18777
|
+
if (ownerIndex === owned.length) {
|
|
18778
|
+
throw new AgentError("request is not reconstructable from session log: unowned or reordered assistant/tool message");
|
|
18779
|
+
}
|
|
18780
|
+
ownerIndex += 1;
|
|
18781
|
+
}
|
|
18782
|
+
const nextHeader = requestHeaderFor(request, input);
|
|
18594
18783
|
const previousHeader = session.requestHeader();
|
|
18595
18784
|
const isFirstRequest = !this._persistedRequest;
|
|
18596
18785
|
const isResume = isFirstRequest && previousHeader !== void 0;
|
|
@@ -18620,19 +18809,23 @@ var AgentService = class {
|
|
|
18620
18809
|
...request.options.provider ? { provider: request.options.provider } : {},
|
|
18621
18810
|
...request.options.model ? { model: request.options.model } : {}
|
|
18622
18811
|
};
|
|
18812
|
+
if (request.options.contextWindow !== void 0) {
|
|
18813
|
+
nextContext.contextWindow = request.options.contextWindow;
|
|
18814
|
+
}
|
|
18623
18815
|
const llmService = this.ctx.reflect.get("llm", false);
|
|
18624
18816
|
const routeCapacity = llmService?.routeCapacity?.();
|
|
18625
|
-
if (routeCapacity?.contextWindow !== void 0) {
|
|
18817
|
+
if (nextContext.contextWindow === void 0 && routeCapacity?.contextWindow !== void 0) {
|
|
18626
18818
|
nextContext.contextWindow = routeCapacity.contextWindow;
|
|
18627
18819
|
}
|
|
18628
18820
|
const previousContext = session.requestContext();
|
|
18629
18821
|
if (previousContext?.provider !== nextContext.provider || previousContext?.model !== nextContext.model || previousContext?.contextWindow !== nextContext.contextWindow || previousContext === void 0) {
|
|
18630
18822
|
await session.append("request/context", nextContext);
|
|
18631
18823
|
}
|
|
18632
|
-
const
|
|
18633
|
-
const
|
|
18634
|
-
const
|
|
18635
|
-
|
|
18824
|
+
const isSurfacePrefix = (messages) => canonicalMessages(messages.slice(0, surface.length)) === canonicalMessages(surface);
|
|
18825
|
+
const requested = surface.length > 0 && input[0]?.role === "system" && input[0].content === nextHeader.system && isSurfacePrefix(input.slice(1)) ? input.slice(1) : input;
|
|
18826
|
+
const tail = requested.slice(surface.length);
|
|
18827
|
+
if (isSurfacePrefix(requested) && tail.every(isUserOrSystemMessage)) {
|
|
18828
|
+
for (const message of tail) {
|
|
18636
18829
|
if (message.role === "user") {
|
|
18637
18830
|
await session.append("user/message", {
|
|
18638
18831
|
content: message.content,
|
|
@@ -18645,45 +18838,37 @@ var AgentService = class {
|
|
|
18645
18838
|
});
|
|
18646
18839
|
}
|
|
18647
18840
|
}
|
|
18648
|
-
};
|
|
18649
|
-
if (surface.length === 0) {
|
|
18650
|
-
await appendDurable(requested);
|
|
18651
18841
|
return;
|
|
18652
18842
|
}
|
|
18653
|
-
const
|
|
18654
|
-
|
|
18655
|
-
|
|
18656
|
-
|
|
18657
|
-
|
|
18658
|
-
if (seenUsers <= durableUsers) continue;
|
|
18659
|
-
newTail.push(message);
|
|
18660
|
-
}
|
|
18661
|
-
await appendDurable(newTail);
|
|
18843
|
+
const nodes = await session.surfaceEvents();
|
|
18844
|
+
await session.append("checkpoint", {
|
|
18845
|
+
messages: copyMessages(requested),
|
|
18846
|
+
surfaceOp: { op: "replace", start: nodes[0].seq, end: nodes.at(-1).seq }
|
|
18847
|
+
});
|
|
18662
18848
|
}
|
|
18663
|
-
async _assertReplayable(session, input) {
|
|
18849
|
+
async _assertReplayable(session, request, input) {
|
|
18664
18850
|
const reconstructed = await session.deriveMessages();
|
|
18665
|
-
const
|
|
18666
|
-
|
|
18667
|
-
|
|
18668
|
-
|
|
18669
|
-
|
|
18670
|
-
...message.tool_calls?.length ? { tool_calls: message.tool_calls.map((call) => ({
|
|
18671
|
-
id: call.id,
|
|
18672
|
-
name: call.name,
|
|
18673
|
-
args: JSON.stringify(call.arguments ?? {})
|
|
18674
|
-
})) } : {}
|
|
18675
|
-
}));
|
|
18676
|
-
const actual = canonical(input);
|
|
18677
|
-
const replay = canonical(reconstructed);
|
|
18678
|
-
if (JSON.stringify(actual) !== JSON.stringify(replay)) {
|
|
18851
|
+
const actual = canonicalMessages(input);
|
|
18852
|
+
const replay = canonicalMessages(reconstructed);
|
|
18853
|
+
const header = session.requestHeader();
|
|
18854
|
+
const headerOwnsPrefix = input[0]?.role === "system" && input[0].content === header?.system && canonicalMessages(input.slice(1)) === replay;
|
|
18855
|
+
if (actual !== replay && !headerOwnsPrefix) {
|
|
18679
18856
|
throw new AgentError(
|
|
18680
|
-
`request is not reconstructable from session log: actual=${
|
|
18857
|
+
`request is not reconstructable from session log: actual=${actual} replay=${replay}`
|
|
18681
18858
|
);
|
|
18682
18859
|
}
|
|
18860
|
+
const expected = requestHeaderFor(request, input);
|
|
18861
|
+
if (header?.system !== expected.system || JSON.stringify(header?.tools ?? []) !== JSON.stringify(expected.tools ?? []) || JSON.stringify(header?.config ?? {}) !== JSON.stringify(expected.config ?? {})) {
|
|
18862
|
+
throw new AgentError("request envelope is not reconstructable from session log");
|
|
18863
|
+
}
|
|
18864
|
+
}
|
|
18865
|
+
async _claimNextStepMessages() {
|
|
18866
|
+
const inputs = await this.config.claimNextStep?.() ?? [];
|
|
18867
|
+
return inputs.flatMap((input) => input.messages?.length ? copyMessages(input.messages) : input.text ? [{ role: "user", content: input.text }] : input.context !== void 0 ? [{ role: "user", content: stringify(input.context) }] : []);
|
|
18683
18868
|
}
|
|
18684
18869
|
async _initialMessages(input) {
|
|
18685
18870
|
const promptService = this.ctx.reflect.get("systemPrompt", false);
|
|
18686
|
-
const assembled = promptService ? (await promptService.assemble()).text.trim() : void 0;
|
|
18871
|
+
const assembled = promptService ? (await promptService.assemble({}, this.ctx)).text.trim() : void 0;
|
|
18687
18872
|
const systemPrompt = assembled || this.inbox.injected().get("agentSystem");
|
|
18688
18873
|
const systemMessage = typeof systemPrompt === "string" && systemPrompt ? [{ role: "system", content: systemPrompt }] : [];
|
|
18689
18874
|
if (input.messages?.length) {
|
|
@@ -18708,7 +18893,7 @@ var AgentService = class {
|
|
|
18708
18893
|
arguments: call.arguments
|
|
18709
18894
|
}));
|
|
18710
18895
|
}
|
|
18711
|
-
next.push(assistant);
|
|
18896
|
+
if (assistant.content || toolCalls.length) next.push(assistant);
|
|
18712
18897
|
for (const call of toolCalls) {
|
|
18713
18898
|
const result = toolResults.find((candidate) => candidate.callId === call.id);
|
|
18714
18899
|
const content = result ? result.ok ? stringify(result.output) : `error: ${result.error?.message ?? "unknown"}` : "error: missing tool result";
|
|
@@ -18738,7 +18923,8 @@ var AgentService = class {
|
|
|
18738
18923
|
return session;
|
|
18739
18924
|
}
|
|
18740
18925
|
_tools() {
|
|
18741
|
-
const
|
|
18926
|
+
const scoped = this.ctx.reflect.get("tools", false);
|
|
18927
|
+
const tools = scoped ?? this.ctx.tools;
|
|
18742
18928
|
if (!tools) throw new AgentError("tools service is required");
|
|
18743
18929
|
return tools;
|
|
18744
18930
|
}
|
|
@@ -18903,6 +19089,1281 @@ function defineAgent(definition) {
|
|
|
18903
19089
|
};
|
|
18904
19090
|
}
|
|
18905
19091
|
|
|
19092
|
+
// packages/core/src/utils.ts
|
|
19093
|
+
var DisposableList = class {
|
|
19094
|
+
sn = 0;
|
|
19095
|
+
map = /* @__PURE__ */ new Map();
|
|
19096
|
+
weak = /* @__PURE__ */ new WeakMap();
|
|
19097
|
+
get length() {
|
|
19098
|
+
return this.map.size;
|
|
19099
|
+
}
|
|
19100
|
+
push(value) {
|
|
19101
|
+
const sn = ++this.sn;
|
|
19102
|
+
this.map.set(sn, value);
|
|
19103
|
+
this.weak.set(value, sn);
|
|
19104
|
+
return () => this.map.delete(sn);
|
|
19105
|
+
}
|
|
19106
|
+
unshift(value) {
|
|
19107
|
+
const sn = ++this.sn;
|
|
19108
|
+
const entries = [...this.map.entries()];
|
|
19109
|
+
this.map.clear();
|
|
19110
|
+
this.map.set(sn, value);
|
|
19111
|
+
this.weak.set(value, sn);
|
|
19112
|
+
for (const [oldSn, oldValue] of entries) {
|
|
19113
|
+
this.map.set(oldSn, oldValue);
|
|
19114
|
+
}
|
|
19115
|
+
return () => this.map.delete(sn);
|
|
19116
|
+
}
|
|
19117
|
+
delete(value) {
|
|
19118
|
+
const sn = this.weak.get(value);
|
|
19119
|
+
if (!sn) return false;
|
|
19120
|
+
return this.map.delete(sn);
|
|
19121
|
+
}
|
|
19122
|
+
clear() {
|
|
19123
|
+
const values = [...this.map.values()];
|
|
19124
|
+
this.map.clear();
|
|
19125
|
+
return values.reverse();
|
|
19126
|
+
}
|
|
19127
|
+
[Symbol.iterator]() {
|
|
19128
|
+
return this.map.values();
|
|
19129
|
+
}
|
|
19130
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
19131
|
+
return [...this];
|
|
19132
|
+
}
|
|
19133
|
+
};
|
|
19134
|
+
var symbols = {
|
|
19135
|
+
shadow: /* @__PURE__ */ Symbol.for("tnega.shadow"),
|
|
19136
|
+
caller: /* @__PURE__ */ Symbol.for("tnega.caller"),
|
|
19137
|
+
receiver: /* @__PURE__ */ Symbol.for("tnega.receiver"),
|
|
19138
|
+
original: /* @__PURE__ */ Symbol.for("tnega.original"),
|
|
19139
|
+
metadata: /* @__PURE__ */ Symbol.for("tnega.metadata"),
|
|
19140
|
+
initHooks: /* @__PURE__ */ Symbol.for("tnega.initHooks"),
|
|
19141
|
+
checkProto: /* @__PURE__ */ Symbol.for("tnega.checkProto"),
|
|
19142
|
+
effect: /* @__PURE__ */ Symbol.for("tnega.effect"),
|
|
19143
|
+
filter: /* @__PURE__ */ Symbol.for("tnega.filter"),
|
|
19144
|
+
isolate: /* @__PURE__ */ Symbol.for("tnega.isolate"),
|
|
19145
|
+
intercept: /* @__PURE__ */ Symbol.for("tnega.intercept"),
|
|
19146
|
+
init: /* @__PURE__ */ Symbol.for("tnega.init"),
|
|
19147
|
+
check: /* @__PURE__ */ Symbol.for("tnega.check"),
|
|
19148
|
+
config: /* @__PURE__ */ Symbol.for("tnega.config"),
|
|
19149
|
+
invoke: /* @__PURE__ */ Symbol.for("tnega.invoke"),
|
|
19150
|
+
extend: /* @__PURE__ */ Symbol.for("tnega.extend"),
|
|
19151
|
+
tracker: /* @__PURE__ */ Symbol.for("tnega.tracker"),
|
|
19152
|
+
resolveConfig: /* @__PURE__ */ Symbol.for("tnega.resolveConfig")
|
|
19153
|
+
};
|
|
19154
|
+
var GeneratorFunction = function* () {
|
|
19155
|
+
}.constructor;
|
|
19156
|
+
var AsyncGeneratorFunction = async function* () {
|
|
19157
|
+
}.constructor;
|
|
19158
|
+
function isConstructor(func) {
|
|
19159
|
+
if (typeof func !== "function") return false;
|
|
19160
|
+
if (func instanceof GeneratorFunction) return false;
|
|
19161
|
+
if (AsyncGeneratorFunction !== Function && func instanceof AsyncGeneratorFunction) return false;
|
|
19162
|
+
return /^class\s/.test(Function.prototype.toString.call(func));
|
|
19163
|
+
}
|
|
19164
|
+
function isObject2(value) {
|
|
19165
|
+
return !!value && (typeof value === "object" || typeof value === "function");
|
|
19166
|
+
}
|
|
19167
|
+
function isNullable(value) {
|
|
19168
|
+
return value == null;
|
|
19169
|
+
}
|
|
19170
|
+
function joinPrototype(proto1, proto2) {
|
|
19171
|
+
if (proto1 === Object.prototype) return proto2;
|
|
19172
|
+
const result = Object.create(joinPrototype(Object.getPrototypeOf(proto1), proto2));
|
|
19173
|
+
for (const key of Reflect.ownKeys(proto1)) {
|
|
19174
|
+
Object.defineProperty(result, key, Reflect.getOwnPropertyDescriptor(proto1, key));
|
|
19175
|
+
}
|
|
19176
|
+
return result;
|
|
19177
|
+
}
|
|
19178
|
+
function getPropertyDescriptor(target, prop) {
|
|
19179
|
+
let proto = target;
|
|
19180
|
+
while (proto) {
|
|
19181
|
+
const desc = Reflect.getOwnPropertyDescriptor(proto, prop);
|
|
19182
|
+
if (desc) return desc;
|
|
19183
|
+
proto = Object.getPrototypeOf(proto);
|
|
19184
|
+
}
|
|
19185
|
+
}
|
|
19186
|
+
function getTraceable(ctx, value) {
|
|
19187
|
+
if (!isObject2(value)) return value;
|
|
19188
|
+
if (Object.hasOwn(value, symbols.shadow)) {
|
|
19189
|
+
return Object.getPrototypeOf(value);
|
|
19190
|
+
}
|
|
19191
|
+
const tracker = value[symbols.tracker];
|
|
19192
|
+
if (!tracker) return value;
|
|
19193
|
+
return createTraceable(ctx, value, tracker);
|
|
19194
|
+
}
|
|
19195
|
+
function withProps(target, props) {
|
|
19196
|
+
if (!props) return target;
|
|
19197
|
+
return new Proxy(target, {
|
|
19198
|
+
get: (target2, prop, receiver) => {
|
|
19199
|
+
if (prop in props && prop !== "constructor") return Reflect.get(props, prop, receiver);
|
|
19200
|
+
return Reflect.get(target2, prop, receiver);
|
|
19201
|
+
},
|
|
19202
|
+
set: (target2, prop, value, receiver) => {
|
|
19203
|
+
if (prop in props && prop !== "constructor") return Reflect.set(props, prop, value, receiver);
|
|
19204
|
+
return Reflect.set(target2, prop, value, receiver);
|
|
19205
|
+
}
|
|
19206
|
+
});
|
|
19207
|
+
}
|
|
19208
|
+
function withProp(target, prop, value) {
|
|
19209
|
+
return withProps(target, Object.defineProperty(/* @__PURE__ */ Object.create(null), prop, {
|
|
19210
|
+
value,
|
|
19211
|
+
writable: false
|
|
19212
|
+
}));
|
|
19213
|
+
}
|
|
19214
|
+
function createShadow(ctx, target, property, receiver) {
|
|
19215
|
+
if (!property) return receiver;
|
|
19216
|
+
const origin = getPropertyDescriptor(target, property)?.value;
|
|
19217
|
+
if (!origin) return receiver;
|
|
19218
|
+
return withProp(receiver, property, ctx.extend({ [symbols.shadow]: origin }));
|
|
19219
|
+
}
|
|
19220
|
+
function createShadowMethod(ctx, value, outer, shadow) {
|
|
19221
|
+
const proxy = new Proxy(value, {
|
|
19222
|
+
apply: (target, thisArg, args) => {
|
|
19223
|
+
if (thisArg === outer) thisArg = shadow;
|
|
19224
|
+
return getTraceable(ctx, Reflect.apply(target, thisArg, args));
|
|
19225
|
+
}
|
|
19226
|
+
});
|
|
19227
|
+
return proxy;
|
|
19228
|
+
}
|
|
19229
|
+
function createTraceable(ctx, value, tracker) {
|
|
19230
|
+
const caller = ctx[symbols.shadow] ?? ctx;
|
|
19231
|
+
if (ctx[symbols.shadow]) {
|
|
19232
|
+
ctx = Object.getPrototypeOf(ctx);
|
|
19233
|
+
}
|
|
19234
|
+
const proxy = new Proxy(value, {
|
|
19235
|
+
get: (target, prop, receiver) => {
|
|
19236
|
+
if (prop === symbols.original) return target;
|
|
19237
|
+
if (prop === symbols.caller) return caller;
|
|
19238
|
+
if (prop === tracker.property) return ctx;
|
|
19239
|
+
if (typeof prop === "symbol") {
|
|
19240
|
+
return Reflect.get(target, prop, receiver);
|
|
19241
|
+
}
|
|
19242
|
+
if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) {
|
|
19243
|
+
return Reflect.get(ctx, `${tracker.associate}.${prop}`, withProp(ctx, symbols.receiver, receiver));
|
|
19244
|
+
}
|
|
19245
|
+
let shadow;
|
|
19246
|
+
let innerValue;
|
|
19247
|
+
const desc = getPropertyDescriptor(target, prop);
|
|
19248
|
+
if (desc?.value !== void 0) {
|
|
19249
|
+
innerValue = desc.value;
|
|
19250
|
+
} else {
|
|
19251
|
+
shadow = createShadow(ctx, target, tracker.property, receiver);
|
|
19252
|
+
innerValue = Reflect.get(target, prop, shadow);
|
|
19253
|
+
}
|
|
19254
|
+
const innerTracker = innerValue?.[symbols.tracker];
|
|
19255
|
+
if (innerTracker) {
|
|
19256
|
+
return createTraceable(ctx, innerValue, innerTracker);
|
|
19257
|
+
} else if (!tracker.noShadow && typeof innerValue === "function") {
|
|
19258
|
+
shadow ??= createShadow(ctx, target, tracker.property, receiver);
|
|
19259
|
+
return createShadowMethod(ctx, innerValue, receiver, shadow);
|
|
19260
|
+
} else {
|
|
19261
|
+
return innerValue;
|
|
19262
|
+
}
|
|
19263
|
+
},
|
|
19264
|
+
set: (target, prop, value2, receiver) => {
|
|
19265
|
+
if (prop === symbols.original || prop === symbols.caller || prop === tracker.property) return false;
|
|
19266
|
+
if (typeof prop === "symbol") {
|
|
19267
|
+
return Reflect.set(target, prop, value2, receiver);
|
|
19268
|
+
}
|
|
19269
|
+
if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) {
|
|
19270
|
+
return Reflect.set(ctx, `${tracker.associate}.${prop}`, value2, withProp(ctx, symbols.receiver, receiver));
|
|
19271
|
+
}
|
|
19272
|
+
const shadow = createShadow(ctx, target, tracker.property, receiver);
|
|
19273
|
+
return Reflect.set(target, prop, value2, shadow);
|
|
19274
|
+
},
|
|
19275
|
+
apply: (target, thisArg, args) => {
|
|
19276
|
+
const receiver = tracker.noShadow ? proxy : createShadow(ctx, target, tracker.property, proxy);
|
|
19277
|
+
return applyTraceable(receiver, target, thisArg, args);
|
|
19278
|
+
}
|
|
19279
|
+
});
|
|
19280
|
+
return proxy;
|
|
19281
|
+
}
|
|
19282
|
+
function applyTraceable(proxy, value, thisArg, args) {
|
|
19283
|
+
if (!value[symbols.invoke]) return Reflect.apply(value, thisArg, args);
|
|
19284
|
+
return value[symbols.invoke].apply(proxy, args);
|
|
19285
|
+
}
|
|
19286
|
+
function createCallable(name, proto, tracker) {
|
|
19287
|
+
const self = function(...args) {
|
|
19288
|
+
const proxy = createTraceable(self.ctx, self, tracker);
|
|
19289
|
+
return Reflect.apply(proxy, this, args);
|
|
19290
|
+
};
|
|
19291
|
+
Object.defineProperty(self, "name", { value: name, configurable: true, writable: true });
|
|
19292
|
+
return Object.setPrototypeOf(self, proto);
|
|
19293
|
+
}
|
|
19294
|
+
function handleError(info, reason, getOuterStack) {
|
|
19295
|
+
const innerLines = info.error.stack.split("\n");
|
|
19296
|
+
if (typeof reason?.stack !== "string") {
|
|
19297
|
+
const outerError = new Error(reason);
|
|
19298
|
+
const lines2 = outerError.stack.split("\n");
|
|
19299
|
+
lines2.splice(1, Infinity, ...getOuterStack());
|
|
19300
|
+
outerError.stack = lines2.join("\n");
|
|
19301
|
+
throw outerError;
|
|
19302
|
+
}
|
|
19303
|
+
const lines = reason.stack.split("\n");
|
|
19304
|
+
const index = lines.indexOf(innerLines[2]);
|
|
19305
|
+
if (index === -1) throw reason;
|
|
19306
|
+
lines.splice(index - info.offset, Infinity, ...getOuterStack());
|
|
19307
|
+
reason.stack = lines.join("\n");
|
|
19308
|
+
throw reason;
|
|
19309
|
+
}
|
|
19310
|
+
function composeError(callback, getOuterStack = buildOuterStack()) {
|
|
19311
|
+
const info = { offset: 1, error: new Error() };
|
|
19312
|
+
try {
|
|
19313
|
+
const result = callback(info);
|
|
19314
|
+
if (isObject2(result) && "then" in result) {
|
|
19315
|
+
return result.then(void 0, (reason) => handleError(info, reason, getOuterStack));
|
|
19316
|
+
}
|
|
19317
|
+
return result;
|
|
19318
|
+
} catch (reason) {
|
|
19319
|
+
handleError(info, reason, getOuterStack);
|
|
19320
|
+
}
|
|
19321
|
+
}
|
|
19322
|
+
function buildOuterStack(offset = 0) {
|
|
19323
|
+
const outerError = new Error();
|
|
19324
|
+
return () => outerError.stack.split("\n").slice(3 + offset);
|
|
19325
|
+
}
|
|
19326
|
+
|
|
19327
|
+
// packages/core/src/events.ts
|
|
19328
|
+
function isBailed(value) {
|
|
19329
|
+
return value !== null && value !== false && value !== void 0;
|
|
19330
|
+
}
|
|
19331
|
+
var EventsService = class {
|
|
19332
|
+
constructor(ctx) {
|
|
19333
|
+
this.ctx = ctx;
|
|
19334
|
+
Object.defineProperty(this, symbols.tracker, {
|
|
19335
|
+
value: { property: "ctx", noShadow: true }
|
|
19336
|
+
});
|
|
19337
|
+
this.on("internal/listener", function(name, listener, options) {
|
|
19338
|
+
if (name === "internal/update" && !options.global) {
|
|
19339
|
+
const hooks = this.fiber._hooks["internal/update"] ??= new DisposableList();
|
|
19340
|
+
const method = options.prepend ? "unshift" : "push";
|
|
19341
|
+
return hooks[method](listener);
|
|
19342
|
+
}
|
|
19343
|
+
});
|
|
19344
|
+
this.on("internal/update", function(config2, noSave, next) {
|
|
19345
|
+
const cbs = [...this.fiber._hooks["internal/update"] ?? []];
|
|
19346
|
+
const _next = () => {
|
|
19347
|
+
const cb = cbs.shift() ?? next;
|
|
19348
|
+
return cb.call(this, config2, noSave, _next);
|
|
19349
|
+
};
|
|
19350
|
+
return _next();
|
|
19351
|
+
}, { global: true, prepend: true });
|
|
19352
|
+
}
|
|
19353
|
+
ctx;
|
|
19354
|
+
_hooks = /* @__PURE__ */ Object.create(null);
|
|
19355
|
+
_resolve(type, args) {
|
|
19356
|
+
const thisArg = typeof args[0] === "object" || typeof args[0] === "function" ? args.shift() : null;
|
|
19357
|
+
const name = args.shift();
|
|
19358
|
+
if (!name.startsWith("internal/") && this._hooks["internal/dispatch"]?.length) {
|
|
19359
|
+
this.emit("internal/dispatch", type, name, args, thisArg);
|
|
19360
|
+
}
|
|
19361
|
+
const filter = thisArg?.[Context.filter];
|
|
19362
|
+
return [thisArg, (this._hooks[name] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback)];
|
|
19363
|
+
}
|
|
19364
|
+
dispatch(type, args) {
|
|
19365
|
+
const [thisArg, callbacks] = this._resolve(type, args);
|
|
19366
|
+
return callbacks.map((callback) => callback.bind(thisArg));
|
|
19367
|
+
}
|
|
19368
|
+
async parallel(...args) {
|
|
19369
|
+
const [thisArg, callbacks] = this._resolve("parallel", args);
|
|
19370
|
+
const results = await Promise.allSettled(callbacks.map(async (callback) => Reflect.apply(callback, thisArg, args)));
|
|
19371
|
+
const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
|
|
19372
|
+
if (errors.length) throw new AggregateError(errors);
|
|
19373
|
+
}
|
|
19374
|
+
emit(...args) {
|
|
19375
|
+
const [thisArg, callbacks] = this._resolve("emit", args);
|
|
19376
|
+
for (const callback of callbacks) Reflect.apply(callback, thisArg, args);
|
|
19377
|
+
}
|
|
19378
|
+
async serial(...args) {
|
|
19379
|
+
const [thisArg, callbacks] = this._resolve("serial", args);
|
|
19380
|
+
for (const callback of callbacks) {
|
|
19381
|
+
const result = await Reflect.apply(callback, thisArg, args);
|
|
19382
|
+
if (isBailed(result)) return result;
|
|
19383
|
+
}
|
|
19384
|
+
}
|
|
19385
|
+
bail(...args) {
|
|
19386
|
+
const [thisArg, callbacks] = this._resolve("bail", args);
|
|
19387
|
+
for (const callback of callbacks) {
|
|
19388
|
+
const result = Reflect.apply(callback, thisArg, args);
|
|
19389
|
+
if (isBailed(result)) return result;
|
|
19390
|
+
}
|
|
19391
|
+
}
|
|
19392
|
+
waterfall(...args) {
|
|
19393
|
+
const [thisArg, callbacks] = this._resolve("waterfall", args);
|
|
19394
|
+
const inner = args.pop();
|
|
19395
|
+
const next = () => {
|
|
19396
|
+
const callback = callbacks.shift();
|
|
19397
|
+
return callback ? Reflect.apply(callback, thisArg, args) : inner(...args);
|
|
19398
|
+
};
|
|
19399
|
+
args.push(next);
|
|
19400
|
+
return next();
|
|
19401
|
+
}
|
|
19402
|
+
async waterfallAsync(...args) {
|
|
19403
|
+
const [thisArg, callbacks] = this._resolve("waterfallAsync", args);
|
|
19404
|
+
const inner = args.pop();
|
|
19405
|
+
const next = async () => {
|
|
19406
|
+
const callback = callbacks.shift();
|
|
19407
|
+
return callback ? await Reflect.apply(callback, thisArg, args) : inner(...args);
|
|
19408
|
+
};
|
|
19409
|
+
args.push(next);
|
|
19410
|
+
return next();
|
|
19411
|
+
}
|
|
19412
|
+
register(label, hooks, callback, options) {
|
|
19413
|
+
const method = options.prepend ? "unshift" : "push";
|
|
19414
|
+
return this.ctx.fiber.effect(() => {
|
|
19415
|
+
hooks[method]({ ctx: this.ctx, callback, ...options });
|
|
19416
|
+
return () => this.unregister(hooks, callback);
|
|
19417
|
+
}, label);
|
|
19418
|
+
}
|
|
19419
|
+
unregister(hooks, callback) {
|
|
19420
|
+
const index = hooks.findIndex((hook) => hook.callback === callback);
|
|
19421
|
+
if (index >= 0) {
|
|
19422
|
+
hooks.splice(index, 1);
|
|
19423
|
+
return true;
|
|
19424
|
+
}
|
|
19425
|
+
}
|
|
19426
|
+
on(name, listener, options = {}) {
|
|
19427
|
+
if (typeof options !== "object") {
|
|
19428
|
+
options = { prepend: options };
|
|
19429
|
+
}
|
|
19430
|
+
this.ctx.fiber.assertActive();
|
|
19431
|
+
listener = this.ctx.reflect.bind(listener);
|
|
19432
|
+
const result = this.bail(this.ctx, "internal/listener", name, listener, options);
|
|
19433
|
+
if (result) return result;
|
|
19434
|
+
const hooks = this._hooks[name] ??= [];
|
|
19435
|
+
return this.register(`ctx.on(${JSON.stringify(name)})`, hooks, listener, options);
|
|
19436
|
+
}
|
|
19437
|
+
once(name, listener, options = {}) {
|
|
19438
|
+
const dispose = this.on(name, function(...args) {
|
|
19439
|
+
dispose();
|
|
19440
|
+
return listener.apply(this, args);
|
|
19441
|
+
}, options);
|
|
19442
|
+
return dispose;
|
|
19443
|
+
}
|
|
19444
|
+
};
|
|
19445
|
+
|
|
19446
|
+
// packages/core/src/fiber.ts
|
|
19447
|
+
var INACTIVE = "__INACTIVE__";
|
|
19448
|
+
var ValidationError = class extends TypeError {
|
|
19449
|
+
name = "ValidationError";
|
|
19450
|
+
constructor(issues) {
|
|
19451
|
+
super("invalid config:\n" + issues.map((issue2) => {
|
|
19452
|
+
if (issue2.path) {
|
|
19453
|
+
return ` - ${issue2.message} (at ${issue2.path.join(".")})`;
|
|
19454
|
+
}
|
|
19455
|
+
return ` - ${issue2.message}`;
|
|
19456
|
+
}).join("\n"));
|
|
19457
|
+
}
|
|
19458
|
+
};
|
|
19459
|
+
function resolveConfig(runtime, config2) {
|
|
19460
|
+
if (!runtime.Config) return config2;
|
|
19461
|
+
const schema = runtime.Config;
|
|
19462
|
+
if (typeof schema === "function") return schema(config2);
|
|
19463
|
+
const validate2 = schema?.["~standard"]?.validate;
|
|
19464
|
+
if (typeof validate2 === "function") {
|
|
19465
|
+
const result = validate2(config2);
|
|
19466
|
+
if ("then" in result) {
|
|
19467
|
+
throw new TypeError("Async config validation is not supported");
|
|
19468
|
+
}
|
|
19469
|
+
if (result.issues) {
|
|
19470
|
+
throw new ValidationError(result.issues);
|
|
19471
|
+
}
|
|
19472
|
+
return result.value;
|
|
19473
|
+
}
|
|
19474
|
+
return config2;
|
|
19475
|
+
}
|
|
19476
|
+
var CordisErrorCode = {
|
|
19477
|
+
INACTIVE_EFFECT: "cannot create effect on inactive context"
|
|
19478
|
+
};
|
|
19479
|
+
var CordisError = class extends Error {
|
|
19480
|
+
constructor(code, message) {
|
|
19481
|
+
super(message ?? CordisErrorCode[code]);
|
|
19482
|
+
this.code = code;
|
|
19483
|
+
}
|
|
19484
|
+
code;
|
|
19485
|
+
};
|
|
19486
|
+
var Fiber = class {
|
|
19487
|
+
constructor(parent, config2, inject, runtime, getOuterStack) {
|
|
19488
|
+
this.parent = parent;
|
|
19489
|
+
this.inject = inject;
|
|
19490
|
+
this.runtime = runtime;
|
|
19491
|
+
const collect = (dispose) => {
|
|
19492
|
+
this._disposables.push(dispose);
|
|
19493
|
+
};
|
|
19494
|
+
if (runtime) {
|
|
19495
|
+
this.uid = parent.registry.counter;
|
|
19496
|
+
this.ctx = this.context = parent.extend({ fiber: this });
|
|
19497
|
+
const injectEntries = Object.entries(this.inject);
|
|
19498
|
+
if (injectEntries.length) {
|
|
19499
|
+
this.ctx[symbols.intercept] = Object.create(parent[symbols.intercept]);
|
|
19500
|
+
for (const [name, config3] of injectEntries) {
|
|
19501
|
+
if (isNullable(config3)) continue;
|
|
19502
|
+
this.ctx[symbols.intercept][name] = config3;
|
|
19503
|
+
}
|
|
19504
|
+
}
|
|
19505
|
+
this._runner = {
|
|
19506
|
+
epoch: INACTIVE,
|
|
19507
|
+
getOuterStack,
|
|
19508
|
+
execute: () => {
|
|
19509
|
+
if (isConstructor(runtime.callback)) {
|
|
19510
|
+
const instance = new runtime.callback(this.ctx, this.config);
|
|
19511
|
+
for (const hook of instance?.[symbols.initHooks] ?? []) {
|
|
19512
|
+
hook();
|
|
19513
|
+
}
|
|
19514
|
+
return instance?.[symbols.init]?.();
|
|
19515
|
+
} else {
|
|
19516
|
+
return runtime.callback(this.ctx, this.config);
|
|
19517
|
+
}
|
|
19518
|
+
},
|
|
19519
|
+
collect
|
|
19520
|
+
};
|
|
19521
|
+
this.context.emit(this, "internal/plugin");
|
|
19522
|
+
for (const name of Object.keys(this.inject)) {
|
|
19523
|
+
this._checkImpl(name);
|
|
19524
|
+
}
|
|
19525
|
+
this.dispose = parent.fiber.effect(() => {
|
|
19526
|
+
const remove = runtime.fibers.push(this);
|
|
19527
|
+
try {
|
|
19528
|
+
this.config = resolveConfig(runtime, config2);
|
|
19529
|
+
this._refresh();
|
|
19530
|
+
} catch (error2) {
|
|
19531
|
+
this.ctx.logger.error(error2);
|
|
19532
|
+
this._error = error2;
|
|
19533
|
+
}
|
|
19534
|
+
return async () => {
|
|
19535
|
+
this.uid = null;
|
|
19536
|
+
this.context.emit(this, "internal/plugin");
|
|
19537
|
+
if (this.ctx.registry.has(runtime.callback)) {
|
|
19538
|
+
remove();
|
|
19539
|
+
if (!runtime.fibers.length) {
|
|
19540
|
+
this.ctx.registry.delete(runtime.callback);
|
|
19541
|
+
}
|
|
19542
|
+
}
|
|
19543
|
+
this._setEpoch(INACTIVE);
|
|
19544
|
+
while (this.inertia) {
|
|
19545
|
+
await this.inertia;
|
|
19546
|
+
}
|
|
19547
|
+
};
|
|
19548
|
+
}, "ctx.plugin()");
|
|
19549
|
+
} else {
|
|
19550
|
+
this.uid = 0;
|
|
19551
|
+
this.ctx = this.context = parent;
|
|
19552
|
+
this.state = 2 /* ACTIVE */;
|
|
19553
|
+
this.store = /* @__PURE__ */ Object.create(null);
|
|
19554
|
+
this._runner = {
|
|
19555
|
+
epoch: "",
|
|
19556
|
+
getOuterStack,
|
|
19557
|
+
execute: () => {
|
|
19558
|
+
},
|
|
19559
|
+
collect
|
|
19560
|
+
};
|
|
19561
|
+
this.dispose = () => this.restart();
|
|
19562
|
+
}
|
|
19563
|
+
}
|
|
19564
|
+
parent;
|
|
19565
|
+
inject;
|
|
19566
|
+
runtime;
|
|
19567
|
+
uid;
|
|
19568
|
+
ctx;
|
|
19569
|
+
config;
|
|
19570
|
+
state = 0 /* PENDING */;
|
|
19571
|
+
dispose;
|
|
19572
|
+
store;
|
|
19573
|
+
inertia;
|
|
19574
|
+
_hooks = /* @__PURE__ */ Object.create(null);
|
|
19575
|
+
_disposables = new DisposableList();
|
|
19576
|
+
context;
|
|
19577
|
+
_error = void 0;
|
|
19578
|
+
_runner;
|
|
19579
|
+
_store = /* @__PURE__ */ Object.create(null);
|
|
19580
|
+
_restarting;
|
|
19581
|
+
get name() {
|
|
19582
|
+
if (this.runtime?.name) return this.runtime.name;
|
|
19583
|
+
let fiber = this.parent.fiber;
|
|
19584
|
+
while (fiber !== fiber.parent.fiber) {
|
|
19585
|
+
if (fiber.runtime?.name) return fiber.runtime.name;
|
|
19586
|
+
fiber = fiber.parent.fiber;
|
|
19587
|
+
}
|
|
19588
|
+
return "root";
|
|
19589
|
+
}
|
|
19590
|
+
assertActive() {
|
|
19591
|
+
if (this.uid !== null) return;
|
|
19592
|
+
throw new CordisError("INACTIVE_EFFECT");
|
|
19593
|
+
}
|
|
19594
|
+
_execute(runner) {
|
|
19595
|
+
const oldEpoch = runner.epoch;
|
|
19596
|
+
return composeError((info) => {
|
|
19597
|
+
const safeCollect = (dispose) => {
|
|
19598
|
+
if (typeof dispose === "function") {
|
|
19599
|
+
runner.collect(dispose);
|
|
19600
|
+
} else if (!isNullable(dispose)) {
|
|
19601
|
+
throw new TypeError("Invalid effect");
|
|
19602
|
+
}
|
|
19603
|
+
};
|
|
19604
|
+
const effect = runner.execute.call(this);
|
|
19605
|
+
if (typeof effect === "function") {
|
|
19606
|
+
return runner.collect(effect);
|
|
19607
|
+
} else if (isNullable(effect)) {
|
|
19608
|
+
return;
|
|
19609
|
+
} else if (!isObject2(effect)) {
|
|
19610
|
+
throw new TypeError("Invalid effect");
|
|
19611
|
+
} else if ("then" in effect) {
|
|
19612
|
+
return effect.then(safeCollect);
|
|
19613
|
+
} else if (Symbol.iterator in effect) {
|
|
19614
|
+
info.error = new Error();
|
|
19615
|
+
const iter = effect[Symbol.iterator]();
|
|
19616
|
+
while (true) {
|
|
19617
|
+
const result = iter.next();
|
|
19618
|
+
safeCollect(result.value);
|
|
19619
|
+
if (result.done) return;
|
|
19620
|
+
}
|
|
19621
|
+
} else if (Symbol.asyncIterator in effect) {
|
|
19622
|
+
const iter = effect[Symbol.asyncIterator]();
|
|
19623
|
+
return (async () => {
|
|
19624
|
+
await Promise.resolve();
|
|
19625
|
+
info.error = new Error();
|
|
19626
|
+
while (true) {
|
|
19627
|
+
if (runner.epoch !== oldEpoch) return;
|
|
19628
|
+
const result = await iter.next();
|
|
19629
|
+
safeCollect(result.value);
|
|
19630
|
+
if (result.done) return;
|
|
19631
|
+
}
|
|
19632
|
+
})();
|
|
19633
|
+
} else {
|
|
19634
|
+
throw new TypeError("Invalid effect");
|
|
19635
|
+
}
|
|
19636
|
+
}, runner.getOuterStack);
|
|
19637
|
+
}
|
|
19638
|
+
effect(execute, label = "anonymous") {
|
|
19639
|
+
this.assertActive();
|
|
19640
|
+
const disposables = [];
|
|
19641
|
+
const dispose = () => {
|
|
19642
|
+
let task2;
|
|
19643
|
+
for (const dispose2 of disposables.splice(0).reverse()) {
|
|
19644
|
+
if (task2) {
|
|
19645
|
+
task2 = task2.then(dispose2);
|
|
19646
|
+
} else {
|
|
19647
|
+
const result = dispose2();
|
|
19648
|
+
if (isObject2(result) && "then" in result) {
|
|
19649
|
+
task2 = result;
|
|
19650
|
+
}
|
|
19651
|
+
}
|
|
19652
|
+
}
|
|
19653
|
+
return task2;
|
|
19654
|
+
};
|
|
19655
|
+
const meta2 = { label, children: [] };
|
|
19656
|
+
const runner = {
|
|
19657
|
+
execute,
|
|
19658
|
+
epoch: true,
|
|
19659
|
+
collect: (dispose2) => {
|
|
19660
|
+
disposables.push(dispose2);
|
|
19661
|
+
this._disposables.delete(dispose2);
|
|
19662
|
+
if (dispose2[symbols.effect]) {
|
|
19663
|
+
meta2.children.push(dispose2[symbols.effect]);
|
|
19664
|
+
}
|
|
19665
|
+
},
|
|
19666
|
+
getOuterStack: buildOuterStack()
|
|
19667
|
+
};
|
|
19668
|
+
let task;
|
|
19669
|
+
try {
|
|
19670
|
+
task = this._execute(runner);
|
|
19671
|
+
} catch (reason) {
|
|
19672
|
+
dispose();
|
|
19673
|
+
throw reason;
|
|
19674
|
+
}
|
|
19675
|
+
task?.catch(dispose).catch((error2) => this.ctx.logger.error(error2));
|
|
19676
|
+
const wrapper = Object.defineProperty(() => {
|
|
19677
|
+
if (!runner.epoch) return;
|
|
19678
|
+
runner.epoch = false;
|
|
19679
|
+
return task ? task.then(dispose) : dispose();
|
|
19680
|
+
}, symbols.effect, { value: meta2 });
|
|
19681
|
+
const disposeAsync = () => {
|
|
19682
|
+
if (!runner.epoch) return;
|
|
19683
|
+
runner.epoch = false;
|
|
19684
|
+
return dispose();
|
|
19685
|
+
};
|
|
19686
|
+
wrapper.then = async (onFulfilled, onRejected) => {
|
|
19687
|
+
return Promise.resolve(task).then(() => disposeAsync).then(onFulfilled, onRejected);
|
|
19688
|
+
};
|
|
19689
|
+
disposables.push(this._disposables.push(wrapper));
|
|
19690
|
+
return wrapper;
|
|
19691
|
+
}
|
|
19692
|
+
getEffects() {
|
|
19693
|
+
return [...this._disposables].map((dispose) => dispose[symbols.effect]).filter(Boolean);
|
|
19694
|
+
}
|
|
19695
|
+
_getState() {
|
|
19696
|
+
if (this.uid === null) return 4 /* DISPOSED */;
|
|
19697
|
+
if (this._error) return 3 /* FAILED */;
|
|
19698
|
+
if (this._runner.epoch !== INACTIVE) return 2 /* ACTIVE */;
|
|
19699
|
+
return 0 /* PENDING */;
|
|
19700
|
+
}
|
|
19701
|
+
_updateState(callback) {
|
|
19702
|
+
const oldState = this.state;
|
|
19703
|
+
this.state = callback?.() ?? this._getState();
|
|
19704
|
+
if (oldState === this.state) return;
|
|
19705
|
+
this.context.emit(this, "internal/status", oldState);
|
|
19706
|
+
if (oldState !== 2 /* ACTIVE */ && this.state !== 2 /* ACTIVE */) return;
|
|
19707
|
+
for (const key of Reflect.ownKeys(this.ctx.reflect.store)) {
|
|
19708
|
+
const impl = this.ctx.reflect.store[key];
|
|
19709
|
+
if (!impl) continue;
|
|
19710
|
+
if (impl.fiber !== this) continue;
|
|
19711
|
+
this.ctx.reflect.notify([impl.name]);
|
|
19712
|
+
}
|
|
19713
|
+
}
|
|
19714
|
+
_checkImpl(name) {
|
|
19715
|
+
const impl = this.ctx.reflect._getImpl(name, true);
|
|
19716
|
+
if (!impl) return delete this._store[name];
|
|
19717
|
+
try {
|
|
19718
|
+
if (impl.check && !impl.check.call(getTraceable(this.ctx, impl.value))) {
|
|
19719
|
+
return delete this._store[name];
|
|
19720
|
+
}
|
|
19721
|
+
} catch (error2) {
|
|
19722
|
+
impl.fiber.ctx.logger.error(error2);
|
|
19723
|
+
return delete this._store[name];
|
|
19724
|
+
}
|
|
19725
|
+
this._store[name] = impl;
|
|
19726
|
+
}
|
|
19727
|
+
_refresh() {
|
|
19728
|
+
let epoch = "";
|
|
19729
|
+
for (const name of Object.keys(this.inject)) {
|
|
19730
|
+
const impl = this._store[name];
|
|
19731
|
+
if (!impl) {
|
|
19732
|
+
epoch = INACTIVE;
|
|
19733
|
+
break;
|
|
19734
|
+
}
|
|
19735
|
+
epoch += ":" + impl.fiber.uid;
|
|
19736
|
+
}
|
|
19737
|
+
this._setEpoch(epoch);
|
|
19738
|
+
}
|
|
19739
|
+
_setEpoch(epoch) {
|
|
19740
|
+
const oldEpoch = this._runner.epoch;
|
|
19741
|
+
if (epoch === oldEpoch) return;
|
|
19742
|
+
this._runner.epoch = epoch;
|
|
19743
|
+
if (this.inertia) return;
|
|
19744
|
+
this._updateState(() => {
|
|
19745
|
+
if (epoch !== INACTIVE && oldEpoch === INACTIVE) {
|
|
19746
|
+
this.inertia = this._reload();
|
|
19747
|
+
return 1 /* LOADING */;
|
|
19748
|
+
} else {
|
|
19749
|
+
this.inertia = this._unload();
|
|
19750
|
+
return 5 /* UNLOADING */;
|
|
19751
|
+
}
|
|
19752
|
+
});
|
|
19753
|
+
}
|
|
19754
|
+
async _reload() {
|
|
19755
|
+
this.store = { ...this._store };
|
|
19756
|
+
const oldEpoch = this._runner.epoch;
|
|
19757
|
+
try {
|
|
19758
|
+
await Promise.resolve();
|
|
19759
|
+
await this._execute(this._runner);
|
|
19760
|
+
} catch (reason) {
|
|
19761
|
+
this.ctx.logger.error(reason);
|
|
19762
|
+
this._error = reason;
|
|
19763
|
+
this._runner.epoch = INACTIVE;
|
|
19764
|
+
}
|
|
19765
|
+
this._updateState(() => {
|
|
19766
|
+
if (this._runner.epoch === oldEpoch) {
|
|
19767
|
+
this.inertia = void 0;
|
|
19768
|
+
} else {
|
|
19769
|
+
this.inertia = this._unload();
|
|
19770
|
+
return 5 /* UNLOADING */;
|
|
19771
|
+
}
|
|
19772
|
+
});
|
|
19773
|
+
}
|
|
19774
|
+
async _unload() {
|
|
19775
|
+
await Promise.all(this._disposables.clear().map(async (dispose) => {
|
|
19776
|
+
try {
|
|
19777
|
+
await composeError(async (info) => {
|
|
19778
|
+
await Promise.resolve();
|
|
19779
|
+
info.error = new Error();
|
|
19780
|
+
await dispose();
|
|
19781
|
+
}, this._runner.getOuterStack);
|
|
19782
|
+
} catch (reason) {
|
|
19783
|
+
this.ctx.logger.error(reason);
|
|
19784
|
+
}
|
|
19785
|
+
}));
|
|
19786
|
+
this.store = void 0;
|
|
19787
|
+
this._updateState(() => {
|
|
19788
|
+
if (this._runner.epoch === INACTIVE) {
|
|
19789
|
+
this.inertia = void 0;
|
|
19790
|
+
} else {
|
|
19791
|
+
this.inertia = this._reload();
|
|
19792
|
+
return 1 /* LOADING */;
|
|
19793
|
+
}
|
|
19794
|
+
});
|
|
19795
|
+
}
|
|
19796
|
+
async await() {
|
|
19797
|
+
while (this.inertia || this._restarting) {
|
|
19798
|
+
await Promise.all([this.inertia, this._restarting].filter((task) => !!task));
|
|
19799
|
+
}
|
|
19800
|
+
if (this._error) throw this._error;
|
|
19801
|
+
return this;
|
|
19802
|
+
}
|
|
19803
|
+
async restart() {
|
|
19804
|
+
const fiber = this.ctx.fiber;
|
|
19805
|
+
fiber.assertActive();
|
|
19806
|
+
if (fiber._restarting) return fiber._restarting.then(() => void 0);
|
|
19807
|
+
let resolve3;
|
|
19808
|
+
const restarting = new Promise((resolvePromise) => {
|
|
19809
|
+
resolve3 = resolvePromise;
|
|
19810
|
+
});
|
|
19811
|
+
fiber._restarting = restarting;
|
|
19812
|
+
try {
|
|
19813
|
+
await this._runRestart(fiber);
|
|
19814
|
+
} finally {
|
|
19815
|
+
fiber._restarting = void 0;
|
|
19816
|
+
resolve3();
|
|
19817
|
+
}
|
|
19818
|
+
}
|
|
19819
|
+
async _runRestart(fiber) {
|
|
19820
|
+
if (fiber.inertia) {
|
|
19821
|
+
fiber._setEpoch(INACTIVE);
|
|
19822
|
+
while (fiber.inertia) await fiber.inertia;
|
|
19823
|
+
}
|
|
19824
|
+
fiber._setEpoch(INACTIVE);
|
|
19825
|
+
fiber._refresh();
|
|
19826
|
+
while (fiber.inertia) await fiber.inertia;
|
|
19827
|
+
}
|
|
19828
|
+
update(config2, noSave = false) {
|
|
19829
|
+
const fiber = this.ctx.fiber;
|
|
19830
|
+
fiber.assertActive();
|
|
19831
|
+
config2 = resolveConfig(fiber.runtime, config2);
|
|
19832
|
+
fiber.context.waterfall(fiber.context, "internal/update", config2, noSave, () => {
|
|
19833
|
+
fiber.config = config2;
|
|
19834
|
+
fiber._error = void 0;
|
|
19835
|
+
return fiber.restart();
|
|
19836
|
+
});
|
|
19837
|
+
}
|
|
19838
|
+
};
|
|
19839
|
+
|
|
19840
|
+
// packages/core/src/logger.ts
|
|
19841
|
+
var Logger = class {
|
|
19842
|
+
constructor(options, service) {
|
|
19843
|
+
this.service = service;
|
|
19844
|
+
this.name = options.name;
|
|
19845
|
+
this.level = options.level;
|
|
19846
|
+
this.error = this._method("error");
|
|
19847
|
+
this.info = this._method("info");
|
|
19848
|
+
this.warn = this._method("warn");
|
|
19849
|
+
this.debug = this._method("debug");
|
|
19850
|
+
}
|
|
19851
|
+
service;
|
|
19852
|
+
name;
|
|
19853
|
+
level;
|
|
19854
|
+
error;
|
|
19855
|
+
info;
|
|
19856
|
+
warn;
|
|
19857
|
+
debug;
|
|
19858
|
+
_method(type) {
|
|
19859
|
+
return (...args) => this.service._log({ name: this.name, type, args });
|
|
19860
|
+
}
|
|
19861
|
+
};
|
|
19862
|
+
var LoggerService = class {
|
|
19863
|
+
buffer = [];
|
|
19864
|
+
ctx;
|
|
19865
|
+
_snMessage = 0;
|
|
19866
|
+
_snExporter = 0;
|
|
19867
|
+
exporters = /* @__PURE__ */ new Map();
|
|
19868
|
+
constructor(ctx) {
|
|
19869
|
+
const tracker = {
|
|
19870
|
+
property: "ctx",
|
|
19871
|
+
noShadow: true
|
|
19872
|
+
};
|
|
19873
|
+
const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
|
|
19874
|
+
Object.assign(self, this);
|
|
19875
|
+
self.ctx = ctx;
|
|
19876
|
+
Object.defineProperty(self, symbols.tracker, { value: tracker });
|
|
19877
|
+
self.exporter({
|
|
19878
|
+
export: (message) => {
|
|
19879
|
+
self.buffer.push(message);
|
|
19880
|
+
}
|
|
19881
|
+
});
|
|
19882
|
+
ctx.reflect.provide("logger", self);
|
|
19883
|
+
return self;
|
|
19884
|
+
}
|
|
19885
|
+
exporter(exporter) {
|
|
19886
|
+
return this.ctx.fiber.effect(() => {
|
|
19887
|
+
const id = ++this._snExporter;
|
|
19888
|
+
this.exporters.set(id, exporter);
|
|
19889
|
+
return () => this.exporters.delete(id);
|
|
19890
|
+
}, "ctx.logger.exporter()");
|
|
19891
|
+
}
|
|
19892
|
+
[symbols.invoke](name) {
|
|
19893
|
+
const caller = this[symbols.caller];
|
|
19894
|
+
const fiber = (caller ?? this.ctx).fiber;
|
|
19895
|
+
return new Logger({
|
|
19896
|
+
name: name ?? fiber.name
|
|
19897
|
+
}, this);
|
|
19898
|
+
}
|
|
19899
|
+
_log(message) {
|
|
19900
|
+
const sn = ++this._snMessage;
|
|
19901
|
+
const ts = Date.now();
|
|
19902
|
+
for (const exporter of this.exporters.values()) {
|
|
19903
|
+
if (exporter.level != null && exporter.level < 0) continue;
|
|
19904
|
+
exporter.export({ sn, ts, ...message });
|
|
19905
|
+
}
|
|
19906
|
+
}
|
|
19907
|
+
error(...args) {
|
|
19908
|
+
return this().error(...args);
|
|
19909
|
+
}
|
|
19910
|
+
info(...args) {
|
|
19911
|
+
return this().info(...args);
|
|
19912
|
+
}
|
|
19913
|
+
warn(...args) {
|
|
19914
|
+
return this().warn(...args);
|
|
19915
|
+
}
|
|
19916
|
+
debug(...args) {
|
|
19917
|
+
return this().debug(...args);
|
|
19918
|
+
}
|
|
19919
|
+
};
|
|
19920
|
+
|
|
19921
|
+
// packages/core/src/reflect.ts
|
|
19922
|
+
function enhanceError(error2) {
|
|
19923
|
+
const lines = error2.stack.split("\n");
|
|
19924
|
+
lines.splice(0, 2, `Error: ${error2.message}`);
|
|
19925
|
+
error2.stack = lines.join("\n");
|
|
19926
|
+
return error2;
|
|
19927
|
+
}
|
|
19928
|
+
var RESERVED_WORDS = ["prototype", "then"];
|
|
19929
|
+
function isSpecialProperty(prop) {
|
|
19930
|
+
return typeof prop === "symbol" || RESERVED_WORDS.includes(prop) || parseInt(prop).toString() === prop || prop.startsWith("_");
|
|
19931
|
+
}
|
|
19932
|
+
var ReflectService = class {
|
|
19933
|
+
constructor(ctx) {
|
|
19934
|
+
this.ctx = ctx;
|
|
19935
|
+
Object.defineProperty(this, symbols.tracker, {
|
|
19936
|
+
value: { property: "ctx", noShadow: true }
|
|
19937
|
+
});
|
|
19938
|
+
this.mixin("reflect", ["get", "set", "provide", "accessor", "mixin"]);
|
|
19939
|
+
this.mixin("fiber", ["runtime", "effect"]);
|
|
19940
|
+
this.mixin("registry", ["inject", "plugin"]);
|
|
19941
|
+
this.mixin("events", [
|
|
19942
|
+
"on",
|
|
19943
|
+
"once",
|
|
19944
|
+
"parallel",
|
|
19945
|
+
"emit",
|
|
19946
|
+
"serial",
|
|
19947
|
+
"bail",
|
|
19948
|
+
"waterfall",
|
|
19949
|
+
"waterfallAsync"
|
|
19950
|
+
]);
|
|
19951
|
+
}
|
|
19952
|
+
ctx;
|
|
19953
|
+
static handler = {
|
|
19954
|
+
get: (target, prop, ctx) => {
|
|
19955
|
+
if (isSpecialProperty(prop)) {
|
|
19956
|
+
return Reflect.get(target, prop, ctx);
|
|
19957
|
+
}
|
|
19958
|
+
if (Reflect.has(target, prop)) {
|
|
19959
|
+
return getTraceable(ctx, Reflect.get(target, prop, ctx));
|
|
19960
|
+
}
|
|
19961
|
+
const error2 = new Error(`cannot get property "${String(prop)}" without inject`);
|
|
19962
|
+
try {
|
|
19963
|
+
const def = target.reflect.props[prop];
|
|
19964
|
+
if (def?.type === "accessor") {
|
|
19965
|
+
return def.get.call(ctx, ctx[symbols.receiver], error2);
|
|
19966
|
+
}
|
|
19967
|
+
if (!ctx.fiber.runtime) return ctx.reflect.get(prop, false);
|
|
19968
|
+
return ctx.events.waterfall(ctx, "internal/get", prop, error2, () => {
|
|
19969
|
+
const key = target[symbols.isolate][prop];
|
|
19970
|
+
let fiber = (ctx[symbols.shadow] ?? ctx).fiber;
|
|
19971
|
+
while (true) {
|
|
19972
|
+
const impl = fiber.store?.[prop];
|
|
19973
|
+
if (impl) return getTraceable(ctx, impl.value);
|
|
19974
|
+
if (prop in fiber.inject) {
|
|
19975
|
+
error2.message = `cannot get required service "${String(prop)}" in inactive context`;
|
|
19976
|
+
throw error2;
|
|
19977
|
+
}
|
|
19978
|
+
if (!fiber.runtime) throw error2;
|
|
19979
|
+
if (fiber.parent[symbols.isolate][prop] !== key) throw error2;
|
|
19980
|
+
fiber = fiber.parent.fiber;
|
|
19981
|
+
}
|
|
19982
|
+
});
|
|
19983
|
+
} catch (e) {
|
|
19984
|
+
throw e === error2 ? enhanceError(e) : e;
|
|
19985
|
+
}
|
|
19986
|
+
},
|
|
19987
|
+
set: (target, prop, value, ctx) => {
|
|
19988
|
+
if (isSpecialProperty(prop)) {
|
|
19989
|
+
return Reflect.set(target, prop, value, ctx);
|
|
19990
|
+
}
|
|
19991
|
+
const error2 = new Error(`cannot set property "${String(prop)}" without provide`);
|
|
19992
|
+
const def = target.reflect.props[prop];
|
|
19993
|
+
try {
|
|
19994
|
+
if (def?.type === "accessor") {
|
|
19995
|
+
if (!def.set) return false;
|
|
19996
|
+
return def.set.call(ctx, value, ctx[symbols.receiver], error2);
|
|
19997
|
+
}
|
|
19998
|
+
if (!def && !ctx.fiber.runtime) {
|
|
19999
|
+
return Reflect.set(target, prop, value, ctx);
|
|
20000
|
+
}
|
|
20001
|
+
return ctx.events.waterfall(ctx, "internal/set", prop, value, error2, () => {
|
|
20002
|
+
if (!def) throw error2;
|
|
20003
|
+
return ctx.reflect.set(prop, value);
|
|
20004
|
+
});
|
|
20005
|
+
} catch (e) {
|
|
20006
|
+
throw e === error2 ? enhanceError(e) : e;
|
|
20007
|
+
}
|
|
20008
|
+
},
|
|
20009
|
+
has: (target, prop) => {
|
|
20010
|
+
if (isSpecialProperty(prop)) {
|
|
20011
|
+
return Reflect.has(target, prop);
|
|
20012
|
+
}
|
|
20013
|
+
if (Reflect.has(target, prop)) return true;
|
|
20014
|
+
return !!target.reflect.props[prop];
|
|
20015
|
+
}
|
|
20016
|
+
};
|
|
20017
|
+
store = /* @__PURE__ */ Object.create(null);
|
|
20018
|
+
props = /* @__PURE__ */ Object.create(null);
|
|
20019
|
+
get(name, strict = true) {
|
|
20020
|
+
return getTraceable(this.ctx, this._getImpl(name, strict)?.value);
|
|
20021
|
+
}
|
|
20022
|
+
_getImpl(name, strict = true) {
|
|
20023
|
+
const key = this.ctx[symbols.isolate][name];
|
|
20024
|
+
const impl = key && this.store[key];
|
|
20025
|
+
if (!impl) return;
|
|
20026
|
+
if (strict && impl.fiber.state !== 2 /* ACTIVE */) return;
|
|
20027
|
+
return impl;
|
|
20028
|
+
}
|
|
20029
|
+
set(name, value) {
|
|
20030
|
+
const key = this.ctx[symbols.isolate][name];
|
|
20031
|
+
const impl = key && this.store[key];
|
|
20032
|
+
if (!impl) {
|
|
20033
|
+
throw new Error(`cannot set property "${name}" without provide`);
|
|
20034
|
+
}
|
|
20035
|
+
if (impl.fiber !== this.ctx.fiber) {
|
|
20036
|
+
throw new Error(`cannot set property "${name}" in multiple fibers`);
|
|
20037
|
+
}
|
|
20038
|
+
impl.value = value;
|
|
20039
|
+
return true;
|
|
20040
|
+
}
|
|
20041
|
+
provide(name, value, check) {
|
|
20042
|
+
return this.ctx.fiber.effect(() => {
|
|
20043
|
+
if (!this.props[name]) {
|
|
20044
|
+
this.props[name] = { type: "service" };
|
|
20045
|
+
} else if (this.props[name].type !== "service") {
|
|
20046
|
+
throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
|
|
20047
|
+
}
|
|
20048
|
+
this.props[name] = { type: "service" };
|
|
20049
|
+
this.ctx.root[symbols.isolate][name] ??= Symbol(name);
|
|
20050
|
+
const key = this.ctx[symbols.isolate][name];
|
|
20051
|
+
const impl = {
|
|
20052
|
+
name,
|
|
20053
|
+
value,
|
|
20054
|
+
fiber: this.ctx.fiber,
|
|
20055
|
+
...check ? { check } : {}
|
|
20056
|
+
};
|
|
20057
|
+
if (key && this.store[key]) {
|
|
20058
|
+
throw new Error(`service "${name}" has been registered at <${this.store[key].fiber.name}>`);
|
|
20059
|
+
}
|
|
20060
|
+
this.store[key] = impl;
|
|
20061
|
+
this.ctx.fiber.store[name] = impl;
|
|
20062
|
+
if (this.ctx.fiber.state === 2 /* ACTIVE */) {
|
|
20063
|
+
this.notify([name]);
|
|
20064
|
+
}
|
|
20065
|
+
return async () => {
|
|
20066
|
+
delete this.store[key];
|
|
20067
|
+
const fibers = this.notify([name]);
|
|
20068
|
+
await Promise.allSettled(fibers.map((fiber) => fiber.await()));
|
|
20069
|
+
delete this.ctx.fiber.store[name];
|
|
20070
|
+
};
|
|
20071
|
+
}, `ctx.provide(${JSON.stringify(name)})`);
|
|
20072
|
+
}
|
|
20073
|
+
notify(names, filter = (ctx, name) => ctx[symbols.isolate][name] === this.ctx[symbols.isolate][name]) {
|
|
20074
|
+
const fibers = [];
|
|
20075
|
+
for (const runtime of this.ctx.registry.values()) {
|
|
20076
|
+
for (const fiber of runtime.fibers) {
|
|
20077
|
+
let hasUpdate = false;
|
|
20078
|
+
for (const name of names) {
|
|
20079
|
+
if (!(name in fiber.inject)) continue;
|
|
20080
|
+
if (!filter(fiber.ctx, name)) continue;
|
|
20081
|
+
hasUpdate = true;
|
|
20082
|
+
fiber._checkImpl(name);
|
|
20083
|
+
}
|
|
20084
|
+
if (!hasUpdate) continue;
|
|
20085
|
+
fiber._refresh();
|
|
20086
|
+
fibers.push(fiber);
|
|
20087
|
+
}
|
|
20088
|
+
}
|
|
20089
|
+
for (const name of names) {
|
|
20090
|
+
const self = Object.create(this.ctx);
|
|
20091
|
+
self[symbols.filter] = (target) => filter(target, name);
|
|
20092
|
+
this.ctx.events.emit(self, "internal/service", name, this._getImpl(name, false)?.value);
|
|
20093
|
+
}
|
|
20094
|
+
return fibers;
|
|
20095
|
+
}
|
|
20096
|
+
accessor(name, options) {
|
|
20097
|
+
return this.ctx.fiber.effect(() => {
|
|
20098
|
+
if (name in this.props) {
|
|
20099
|
+
throw new Error(`property "${name}" is already declared as ${this.props[name].type}`);
|
|
20100
|
+
}
|
|
20101
|
+
this.props[name] = { type: "accessor", ...options };
|
|
20102
|
+
return () => delete this.props[name];
|
|
20103
|
+
}, `ctx.accessor(${JSON.stringify(name)})`);
|
|
20104
|
+
}
|
|
20105
|
+
mixin(source, mixins) {
|
|
20106
|
+
return this.ctx.fiber.effect(() => {
|
|
20107
|
+
const entries = Array.isArray(mixins) ? mixins.map((key) => [key, key]) : Object.entries(mixins);
|
|
20108
|
+
const getTarget = (target) => target[source];
|
|
20109
|
+
return entries.map(([key, value]) => {
|
|
20110
|
+
return this.accessor(value, {
|
|
20111
|
+
get(receiver) {
|
|
20112
|
+
const service = getTarget(this);
|
|
20113
|
+
if (service == null) return service;
|
|
20114
|
+
const mixin = receiver ? withProps(receiver, service) : service;
|
|
20115
|
+
const result = Reflect.get(service, key, mixin);
|
|
20116
|
+
if (typeof result !== "function") return result;
|
|
20117
|
+
return result.bind(mixin ?? service);
|
|
20118
|
+
},
|
|
20119
|
+
set(value2, receiver) {
|
|
20120
|
+
const service = getTarget(this);
|
|
20121
|
+
const mixin = receiver ? withProps(receiver, service) : service;
|
|
20122
|
+
return Reflect.set(service, key, value2, mixin);
|
|
20123
|
+
}
|
|
20124
|
+
});
|
|
20125
|
+
});
|
|
20126
|
+
}, `ctx.mixin(${JSON.stringify(source)})`);
|
|
20127
|
+
}
|
|
20128
|
+
trace(value) {
|
|
20129
|
+
return getTraceable(this.ctx, value);
|
|
20130
|
+
}
|
|
20131
|
+
bind(callback) {
|
|
20132
|
+
return new Proxy(callback, {
|
|
20133
|
+
apply: (target, thisArg, args) => {
|
|
20134
|
+
return Reflect.apply(target, this.trace(thisArg), args.map((arg) => this.trace(arg)));
|
|
20135
|
+
},
|
|
20136
|
+
construct: (target, args, newTarget) => {
|
|
20137
|
+
return Reflect.construct(target, args.map((arg) => this.trace(arg)), newTarget);
|
|
20138
|
+
}
|
|
20139
|
+
});
|
|
20140
|
+
}
|
|
20141
|
+
};
|
|
20142
|
+
|
|
20143
|
+
// packages/core/src/registry.ts
|
|
20144
|
+
function isApplicable(object3) {
|
|
20145
|
+
return object3 && typeof object3 === "object" && typeof object3.apply === "function";
|
|
20146
|
+
}
|
|
20147
|
+
function resolveInject(inject, result = /* @__PURE__ */ Object.create(null)) {
|
|
20148
|
+
if (!inject) return result;
|
|
20149
|
+
if (Array.isArray(inject)) {
|
|
20150
|
+
for (const name of inject) {
|
|
20151
|
+
result[name] = null;
|
|
20152
|
+
}
|
|
20153
|
+
} else if (Reflect.has(inject, symbols.checkProto)) {
|
|
20154
|
+
Object.assign(result, resolveInject(Object.getPrototypeOf(inject)));
|
|
20155
|
+
for (const name of Object.keys(inject)) {
|
|
20156
|
+
result[name] = inject[name] ?? null;
|
|
20157
|
+
}
|
|
20158
|
+
} else {
|
|
20159
|
+
for (const name of Object.keys(inject)) {
|
|
20160
|
+
result[name] = inject[name] ?? null;
|
|
20161
|
+
}
|
|
20162
|
+
}
|
|
20163
|
+
return result;
|
|
20164
|
+
}
|
|
20165
|
+
var RegistryService = class {
|
|
20166
|
+
constructor(ctx) {
|
|
20167
|
+
this.ctx = ctx;
|
|
20168
|
+
Object.defineProperty(this, symbols.tracker, {
|
|
20169
|
+
value: { property: "ctx", noShadow: true }
|
|
20170
|
+
});
|
|
20171
|
+
}
|
|
20172
|
+
ctx;
|
|
20173
|
+
_counter = 0;
|
|
20174
|
+
_internal = /* @__PURE__ */ new Map();
|
|
20175
|
+
get counter() {
|
|
20176
|
+
return ++this._counter;
|
|
20177
|
+
}
|
|
20178
|
+
get size() {
|
|
20179
|
+
return this._internal.size;
|
|
20180
|
+
}
|
|
20181
|
+
resolve(plugin) {
|
|
20182
|
+
try {
|
|
20183
|
+
if (typeof plugin === "function") return plugin;
|
|
20184
|
+
if (isApplicable(plugin)) return plugin.apply;
|
|
20185
|
+
} catch {
|
|
20186
|
+
}
|
|
20187
|
+
}
|
|
20188
|
+
get(plugin) {
|
|
20189
|
+
const key = this.resolve(plugin);
|
|
20190
|
+
return key && this._internal.get(key);
|
|
20191
|
+
}
|
|
20192
|
+
has(plugin) {
|
|
20193
|
+
const key = this.resolve(plugin);
|
|
20194
|
+
return !!key && this._internal.has(key);
|
|
20195
|
+
}
|
|
20196
|
+
delete(plugin) {
|
|
20197
|
+
const key = this.resolve(plugin);
|
|
20198
|
+
const runtime = key && this._internal.get(key);
|
|
20199
|
+
if (!runtime) return;
|
|
20200
|
+
this._internal.delete(key);
|
|
20201
|
+
for (const fiber of [...runtime.fibers]) {
|
|
20202
|
+
fiber.dispose();
|
|
20203
|
+
}
|
|
20204
|
+
return runtime;
|
|
20205
|
+
}
|
|
20206
|
+
keys() {
|
|
20207
|
+
return this._internal.keys();
|
|
20208
|
+
}
|
|
20209
|
+
values() {
|
|
20210
|
+
return this._internal.values();
|
|
20211
|
+
}
|
|
20212
|
+
entries() {
|
|
20213
|
+
return this._internal.entries();
|
|
20214
|
+
}
|
|
20215
|
+
forEach(callback) {
|
|
20216
|
+
return this._internal.forEach(callback);
|
|
20217
|
+
}
|
|
20218
|
+
inject(inject, callback) {
|
|
20219
|
+
const name = callback.name || void 0;
|
|
20220
|
+
return this.plugin(Object.assign(
|
|
20221
|
+
{ inject, apply: callback },
|
|
20222
|
+
name ? { name } : {}
|
|
20223
|
+
));
|
|
20224
|
+
}
|
|
20225
|
+
plugin(plugin, config2, getOuterStack = buildOuterStack()) {
|
|
20226
|
+
const callback = this.resolve(plugin);
|
|
20227
|
+
if (!callback) throw new Error('invalid plugin, expect function or object with an "apply" method, received ' + typeof plugin);
|
|
20228
|
+
this.ctx.fiber.assertActive();
|
|
20229
|
+
let runtime = this._internal.get(callback);
|
|
20230
|
+
if (!runtime) {
|
|
20231
|
+
let name = plugin.name;
|
|
20232
|
+
if (name === "apply") name = void 0;
|
|
20233
|
+
runtime = {
|
|
20234
|
+
callback,
|
|
20235
|
+
fibers: new DisposableList(),
|
|
20236
|
+
...name ? { name } : {},
|
|
20237
|
+
...plugin.Config ? { Config: plugin.Config } : {}
|
|
20238
|
+
};
|
|
20239
|
+
this._internal.set(callback, runtime);
|
|
20240
|
+
}
|
|
20241
|
+
const fiber = new Fiber(this.ctx, config2, resolveInject(plugin.inject), runtime, getOuterStack);
|
|
20242
|
+
const wrapped = Object.create(fiber);
|
|
20243
|
+
wrapped.then = (onFulfilled, onRejected) => {
|
|
20244
|
+
return fiber.await().then(onFulfilled, onRejected);
|
|
20245
|
+
};
|
|
20246
|
+
return wrapped;
|
|
20247
|
+
}
|
|
20248
|
+
};
|
|
20249
|
+
|
|
20250
|
+
// packages/core/src/context.ts
|
|
20251
|
+
var Context = class _Context {
|
|
20252
|
+
static effect = symbols.effect;
|
|
20253
|
+
static filter = symbols.filter;
|
|
20254
|
+
static isolate = symbols.isolate;
|
|
20255
|
+
static intercept = symbols.intercept;
|
|
20256
|
+
static marker = /* @__PURE__ */ Symbol.for("tnega.is");
|
|
20257
|
+
static is(value) {
|
|
20258
|
+
return !!value?.[_Context.marker];
|
|
20259
|
+
}
|
|
20260
|
+
static {
|
|
20261
|
+
_Context.prototype[_Context.marker] = true;
|
|
20262
|
+
}
|
|
20263
|
+
constructor() {
|
|
20264
|
+
this[symbols.isolate] = /* @__PURE__ */ Object.create(null);
|
|
20265
|
+
this[symbols.intercept] = /* @__PURE__ */ Object.create(null);
|
|
20266
|
+
const self = new Proxy(this, ReflectService.handler);
|
|
20267
|
+
this.root = self;
|
|
20268
|
+
this.baseUrl = void 0;
|
|
20269
|
+
this.fiber = new Fiber(self, {}, /* @__PURE__ */ Object.create(null), null, () => []);
|
|
20270
|
+
this.reflect = new ReflectService(self);
|
|
20271
|
+
this.registry = new RegistryService(self);
|
|
20272
|
+
this.events = new EventsService(self);
|
|
20273
|
+
this.logger = new LoggerService(self);
|
|
20274
|
+
this.fiber._disposables.clear();
|
|
20275
|
+
return self;
|
|
20276
|
+
}
|
|
20277
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
20278
|
+
return `Context <${this.fiber.name}>`;
|
|
20279
|
+
}
|
|
20280
|
+
extend(meta2 = {}) {
|
|
20281
|
+
const shadow = Reflect.getOwnPropertyDescriptor(this, symbols.shadow)?.value;
|
|
20282
|
+
const self = Object.create(getTraceable(this, this));
|
|
20283
|
+
for (const prop of Reflect.ownKeys(meta2)) {
|
|
20284
|
+
Object.defineProperty(self, prop, Reflect.getOwnPropertyDescriptor(meta2, prop));
|
|
20285
|
+
}
|
|
20286
|
+
if (!shadow) return self;
|
|
20287
|
+
return Object.assign(Object.create(self), { [symbols.shadow]: shadow });
|
|
20288
|
+
}
|
|
20289
|
+
isolate(name, label) {
|
|
20290
|
+
const shadow = Object.create(this[symbols.isolate]);
|
|
20291
|
+
shadow[name] = label ?? Symbol(name);
|
|
20292
|
+
return this.extend({ [symbols.isolate]: shadow });
|
|
20293
|
+
}
|
|
20294
|
+
intercept(name, config2) {
|
|
20295
|
+
const intercept = Object.create(this[symbols.intercept]);
|
|
20296
|
+
intercept[name] = config2;
|
|
20297
|
+
return this.extend({ [symbols.intercept]: intercept });
|
|
20298
|
+
}
|
|
20299
|
+
};
|
|
20300
|
+
|
|
20301
|
+
// packages/core/src/service.ts
|
|
20302
|
+
var Service = class _Service {
|
|
20303
|
+
constructor(ctx, name) {
|
|
20304
|
+
this.ctx = ctx;
|
|
20305
|
+
name ??= this.constructor.provide;
|
|
20306
|
+
const tracker = {
|
|
20307
|
+
associate: name,
|
|
20308
|
+
property: "ctx"
|
|
20309
|
+
};
|
|
20310
|
+
const self = this[symbols.invoke] ? createCallable(name, joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker) : this;
|
|
20311
|
+
self.ctx = ctx;
|
|
20312
|
+
self.name = name;
|
|
20313
|
+
Object.defineProperty(self, symbols.tracker, { value: tracker });
|
|
20314
|
+
self.ctx.reflect.provide(name, self, this[symbols.check]);
|
|
20315
|
+
return self;
|
|
20316
|
+
}
|
|
20317
|
+
ctx;
|
|
20318
|
+
static init = symbols.init;
|
|
20319
|
+
static check = symbols.check;
|
|
20320
|
+
static config = symbols.config;
|
|
20321
|
+
static invoke = symbols.invoke;
|
|
20322
|
+
static extend = symbols.extend;
|
|
20323
|
+
static tracker = symbols.tracker;
|
|
20324
|
+
static resolveConfig = symbols.resolveConfig;
|
|
20325
|
+
name;
|
|
20326
|
+
[symbols.filter](ctx) {
|
|
20327
|
+
return ctx[symbols.isolate][this.name] === this.ctx[symbols.isolate][this.name];
|
|
20328
|
+
}
|
|
20329
|
+
[symbols.extend](props) {
|
|
20330
|
+
let self;
|
|
20331
|
+
if (this[_Service.invoke]) {
|
|
20332
|
+
self = createCallable(this.name, this, this[symbols.tracker]);
|
|
20333
|
+
} else {
|
|
20334
|
+
self = Object.create(this);
|
|
20335
|
+
}
|
|
20336
|
+
return Object.assign(self, props);
|
|
20337
|
+
}
|
|
20338
|
+
[symbols.resolveConfig](base, head) {
|
|
20339
|
+
let intercept = this.ctx[symbols.intercept];
|
|
20340
|
+
const configs = [];
|
|
20341
|
+
while (this.name in intercept) {
|
|
20342
|
+
if (Object.hasOwn(intercept, this.name)) {
|
|
20343
|
+
configs.unshift(intercept[this.name]);
|
|
20344
|
+
}
|
|
20345
|
+
intercept = Object.getPrototypeOf(intercept);
|
|
20346
|
+
}
|
|
20347
|
+
if (base) configs.unshift(base);
|
|
20348
|
+
if (head) configs.push(head);
|
|
20349
|
+
if (this["Config"]?.merge) {
|
|
20350
|
+
return this["Config"].merge(...configs);
|
|
20351
|
+
} else {
|
|
20352
|
+
return Object.assign({}, ...configs);
|
|
20353
|
+
}
|
|
20354
|
+
}
|
|
20355
|
+
static [Symbol.hasInstance](instance) {
|
|
20356
|
+
if (!instance) return false;
|
|
20357
|
+
let constructor = instance.constructor;
|
|
20358
|
+
while (constructor) {
|
|
20359
|
+
constructor = constructor.prototype?.constructor;
|
|
20360
|
+
if (constructor === this) return true;
|
|
20361
|
+
constructor &&= Object.getPrototypeOf(constructor);
|
|
20362
|
+
}
|
|
20363
|
+
return false;
|
|
20364
|
+
}
|
|
20365
|
+
};
|
|
20366
|
+
|
|
18906
20367
|
// packages/coding-agent/src/codingAgent.ts
|
|
18907
20368
|
var dynamic = (ctx) => ctx;
|
|
18908
20369
|
var CODING_SYSTEM_PROMPT = `You are Tnega, a coding agent running in a workspace session.
|