superagent-skill 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +120 -2
- package/SKILL.md +143 -0
- package/bin/superagent.js +3 -0
- package/lib/cli.mjs +1717 -0
- package/lib/index.mjs +70 -0
- package/lib/settings-D0qG6Mo8.mjs +2968 -0
- package/package.json +57 -4
- package/prompts/delivery.md +4 -0
- package/prompts/scope.md +5 -0
|
@@ -0,0 +1,2968 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { lstat, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import { basename, delimiter, join } from "node:path";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
// src/core/model.ts
|
|
7
|
+
/** Stable key of a thread across the whole domain. */
|
|
8
|
+
const threadKey = (ref) => `${ref.source}:${ref.id}`;
|
|
9
|
+
/**
|
|
10
|
+
* Normalizes valid timestamps to `Date#toISOString` form so stored timestamps compare lexicographically in memory and SQL;
|
|
11
|
+
* values that do not parse as a timestamp are returned unchanged.
|
|
12
|
+
*/
|
|
13
|
+
function isoTime(value) {
|
|
14
|
+
const time = Date.parse(value);
|
|
15
|
+
return Number.isFinite(time) ? new Date(time).toISOString() : value;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The tickets whose worker decides a person's follow-up: those it reached on their own Threads that can still decide it
|
|
19
|
+
* and did not hand it back. A ticket can while it is live, also once a person dropped its Subscription to the Thread, and
|
|
20
|
+
* while it is ended, not by a person, with the Trigger waiting to resume it. None once a person sent it to Eval, or while
|
|
21
|
+
* an Eval holds it, which an earlier version may have queued. While a ticket owns it, the message goes to no Eval, and the
|
|
22
|
+
* main Session may only stop the work on it.
|
|
23
|
+
*/
|
|
24
|
+
function followupOwners(trigger, records) {
|
|
25
|
+
if (!trigger.human) return [];
|
|
26
|
+
const disposition = records.triggers.disposition(trigger.id);
|
|
27
|
+
if (!disposition || disposition.requeued) return [];
|
|
28
|
+
const returned = new Set(disposition.handbacks?.map((item) => item.ticketId));
|
|
29
|
+
const reached = disposition.fanout.filter((id) => !returned.has(id) && !disposition.context?.includes(id));
|
|
30
|
+
if (!reached.length || records.threads.get(threadKey(trigger.threads[0]))?.evaluating?.triggerIds.includes(trigger.id)) return [];
|
|
31
|
+
return reached.filter((id) => {
|
|
32
|
+
const ticket = records.tickets.get(id);
|
|
33
|
+
return !!ticket && (liveTicket(ticket) || ticket.ended?.by !== "human" && ticket.inputs.some((input) => input.kind === "trigger" && input.triggerId === trigger.id && ticket.undelivered.includes(input.id)));
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Whether a Decision settled what a person's message asks for: a stop on it, taken or refused, decides only that ticket's
|
|
38
|
+
* work, routing it to a ticket leaves it to that ticket's worker, and an unavailable one decided nothing.
|
|
39
|
+
*/
|
|
40
|
+
const settled = (decision) => !["stop", "unavailable"].includes(decision.kind) && !decision.reason.some((reason) => [
|
|
41
|
+
"stopNotExplicit",
|
|
42
|
+
"stopUnknown",
|
|
43
|
+
"routed"
|
|
44
|
+
].includes(reason.code));
|
|
45
|
+
/** Whether a ticket is open: it has not ended. */
|
|
46
|
+
const liveTicket = (ticket) => !ticket.ended;
|
|
47
|
+
/** How a ticket ended. */
|
|
48
|
+
const ticketOutcome = (ticket) => ticket.ended?.outcome;
|
|
49
|
+
const runningAssignment = (ticket) => ticket.assignments.find((assignment) => assignment.state === "running");
|
|
50
|
+
/**
|
|
51
|
+
* Whether a Trigger reached a ticket: it started the ticket, came to it as an Input, or is on a Thread the ticket subscribes
|
|
52
|
+
* to; with `context` false, not a Thread the ticket follows only for context, where its worker may read but not write.
|
|
53
|
+
*/
|
|
54
|
+
function reached(ticket, trigger, thread, context = true) {
|
|
55
|
+
if (ticket.origin.triggerId === trigger.id) return true;
|
|
56
|
+
const input = ticket.inputs.some((item) => item.kind === "trigger" && item.triggerId === trigger.id);
|
|
57
|
+
return trigger.threads.some((ref) => {
|
|
58
|
+
const current = thread(threadKey(ref));
|
|
59
|
+
return current?.subscriptions.includes(ticket.id) === true && (context || !current.context?.includes(ticket.id));
|
|
60
|
+
}) || input && (context || !trigger.threads.every((ref) => thread(threadKey(ref))?.context?.includes(ticket.id)));
|
|
61
|
+
}
|
|
62
|
+
const latestAssignment = (ticket) => ticket.assignments.at(-1);
|
|
63
|
+
/** The latest report any of a ticket's Assignments made, which is what the ticket last said. */
|
|
64
|
+
const latestReport = (ticket) => ticket.assignments.findLast((assignment) => assignment.report)?.report;
|
|
65
|
+
/**
|
|
66
|
+
* Until when a ticket's worker had a turn to read what reached it: its latest report, but a progress report when `progress`
|
|
67
|
+
* is false, or the end of its latest turn, whichever is later.
|
|
68
|
+
*/
|
|
69
|
+
function readUntil(ticket, progress = true) {
|
|
70
|
+
return [(ticket.assignments.findLast((assignment) => assignment.report && (progress || assignment.report.state !== "progress"))?.report)?.at ?? "", ...ticket.assignments.map((assignment) => assignment.idleAt ?? "")].reduce((a, b) => a > b ? a : b);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Whether a ticket waits for a person: its latest Assignment reported blocked or failed, and no person's message reached it
|
|
74
|
+
* since. A later report that is neither, a person's message, or a retry, which starts a new Assignment, lifts it.
|
|
75
|
+
*/
|
|
76
|
+
function waitsForPerson(ticket) {
|
|
77
|
+
const report = latestAssignment(ticket)?.report;
|
|
78
|
+
if (report?.state !== "blocked" && report?.state !== "failed") return false;
|
|
79
|
+
return !ticket.inputs.some((input) => input.kind === "trigger" && input.human && !input.context && input.at > report.at);
|
|
80
|
+
}
|
|
81
|
+
// src/core/errors.ts
|
|
82
|
+
/** User-facing error codes mapped to their category ('missing' or 'refused') and English message template. */
|
|
83
|
+
const USER_ERRORS = {
|
|
84
|
+
unknownTicket: ["missing", "Unknown ticket"],
|
|
85
|
+
unknownProblem: ["missing", "Unavailable Eval not found"],
|
|
86
|
+
unknownTrigger: ["missing", "Unknown trigger"],
|
|
87
|
+
unknownAssignment: ["missing", "Unknown assignment"],
|
|
88
|
+
unknownBlock: ["missing", "Unknown settings block: {block}"],
|
|
89
|
+
unknownPromptRevision: ["missing", "Unknown prompt revision {revision}"],
|
|
90
|
+
unknownPromptPart: ["refused", "Unknown built-in prompt part {part}"],
|
|
91
|
+
ticketEnded: ["refused", "Ticket has ended"],
|
|
92
|
+
assignmentEnded: ["refused", "Assignment has ended; a newer assignment owns this ticket"],
|
|
93
|
+
evalFinished: ["refused", "Eval {eval} has finished or a later eval replaced it; decide the trigger's current eval"],
|
|
94
|
+
notAdmissible: ["refused", "Trigger is not admissible: {reason}"],
|
|
95
|
+
notExplicit: ["refused", "An accept through orchestrator_route is for explicit requests from allowed senders; assess proactive candidates with orchestrator_eval and orchestrator_eval_decide"],
|
|
96
|
+
ticketStopped: ["refused", "A person stopped this ticket; new work needs an accept through orchestrator_route"],
|
|
97
|
+
mandateRevoked: ["refused", "The current policy no longer holds this ticket's mandate; new work needs an accept through orchestrator_route"],
|
|
98
|
+
notRetryable: ["refused", "Only an open ticket can be retried, and only when its worker last reported failed or blocked and no person has sent a message since, or when delivering an Input to its worker failed"],
|
|
99
|
+
sourceThread: ["refused", "This is the thread the ticket started on; it stays subscribed"],
|
|
100
|
+
followedThread: ["refused", "This thread is the ticket's own, such as its pull request's; it stays subscribed"],
|
|
101
|
+
notFollowing: ["refused", "This ticket does not follow that thread"],
|
|
102
|
+
questionWithResult: ["refused", "A question for a person cannot also be a ready result or an answer; report it separately"],
|
|
103
|
+
askerWithoutQuestion: ["refused", "The message that raised a question needs the question it raised"],
|
|
104
|
+
notAsker: ["refused", "A question must name the person's message that raised it, which reached this ticket"],
|
|
105
|
+
notAnswerable: ["refused", "An answer must name the person's question it answers, which reached this ticket"],
|
|
106
|
+
ackEnded: ["refused", "Ticket ended; do not acknowledge historical requests"],
|
|
107
|
+
notReached: ["refused", "Trigger does not belong to this worker"],
|
|
108
|
+
handedBack: ["refused", "This ticket handed that trigger back already"],
|
|
109
|
+
handedBackHere: ["refused", "The worker of this ticket handed that trigger back as beyond it: accept it as new work, attach it to another ticket, or ignore it"],
|
|
110
|
+
workerDecides: ["refused", "This message reached ticket {tickets} on its thread: its worker decides whether it belongs there and hands back what does not, which then arrives as a candidate. Only a stop goes through orchestrator_route, with kind stop"],
|
|
111
|
+
ackNoChannel: ["refused", "Acknowledgement requires an assigned human source message"],
|
|
112
|
+
ackNotPerson: ["refused", "Use the original human trigger, not a bot, CI or worker report"],
|
|
113
|
+
notReady: ["refused", "Ticket is not ready for delivery. Keep progress internal and wait for a verified ready report; do not relabel progress as an answer or send it through another channel."],
|
|
114
|
+
notAttention: ["refused", "Attention requires the ticket's current attention question in human_action. Routine unfinished work stays internal."],
|
|
115
|
+
notQuestion: ["refused", "An answer must target the original human question, not a worker report or automated trigger"],
|
|
116
|
+
noAnswer: ["refused", "No worker answer is ready for this human trigger. Wait for the worker's report, or request one with orchestrator_ticket_request_status, which acts only on a worker that reported waiting; ordinary progress cannot be relabelled as an answer."],
|
|
117
|
+
noChannel: ["refused", "No reply channel for this ticket or trigger"],
|
|
118
|
+
panelOnlyEnvironment: ["refused", "The execution environment (ticket directory, prepare command, blocked commands) can only be changed in the management panel"],
|
|
119
|
+
panelOnlyAccounts: ["refused", "Source fields that setup reads, such as account CLIs, can only be changed in the management panel"],
|
|
120
|
+
setupComplete: ["refused", "Setup is complete"],
|
|
121
|
+
modelUnavailable: ["refused", "The {block} model is not available: {error}"],
|
|
122
|
+
promptTooLong: ["refused", "Prompt configuration exceeds {limit} characters"],
|
|
123
|
+
promptPlaceholders: ["refused", "The “{part}” template must keep {placeholders}, which the system fills in"],
|
|
124
|
+
promptPartEmpty: ["refused", "The “{part}” part cannot be empty; reset it to follow its built-in text"],
|
|
125
|
+
sourceNotInstalled: ["refused", "The {source} Source kind is not installed"],
|
|
126
|
+
noLabels: ["refused", "This Source has no names to refresh"],
|
|
127
|
+
nothingToSync: ["refused", "The {source} Source's part of the Policy has nothing to sync from, or the Source is off or waiting for setup"]
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* Structured error thrown by Engine parts and application services when a caller request is invalid or references missing state.
|
|
131
|
+
* Tool handlers and HTTP routes inspect its code and missing flag to return appropriate status responses, while the web panel localizes the code.
|
|
132
|
+
*/
|
|
133
|
+
var UserError = class extends Error {
|
|
134
|
+
code;
|
|
135
|
+
values;
|
|
136
|
+
missing;
|
|
137
|
+
constructor(code, values = {}) {
|
|
138
|
+
const [kind, text] = USER_ERRORS[code];
|
|
139
|
+
super(text.replace(/\{(\w+)\}/g, (match, name) => values[name] ?? match));
|
|
140
|
+
this.code = code;
|
|
141
|
+
this.values = values;
|
|
142
|
+
this.missing = kind === "missing";
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
// src/core/ids.ts
|
|
146
|
+
/** Stable content-derived identifiers; equal inputs always produce the same id. */
|
|
147
|
+
function key(...values) {
|
|
148
|
+
return createHash("sha256").update(JSON.stringify(values)).digest("hex").slice(0, 32);
|
|
149
|
+
}
|
|
150
|
+
// src/core/part.ts
|
|
151
|
+
/** Shared base class and configuration for Engine domain parts. */
|
|
152
|
+
/**
|
|
153
|
+
* Base class for Intake, Evals, Tickets, Assignments, and Replies providing shared access to repositories, policy, clock, and event emission.
|
|
154
|
+
* Each subclass mutates its own domain aggregates and delegates cross-aggregate changes to sibling parts within the transaction opened by Engine.
|
|
155
|
+
*/
|
|
156
|
+
var EnginePart = class {
|
|
157
|
+
options;
|
|
158
|
+
repo;
|
|
159
|
+
constructor(options) {
|
|
160
|
+
this.options = options;
|
|
161
|
+
this.repo = options.repo;
|
|
162
|
+
}
|
|
163
|
+
now() {
|
|
164
|
+
return this.options.now?.() ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
165
|
+
}
|
|
166
|
+
policy() {
|
|
167
|
+
return this.options.policy();
|
|
168
|
+
}
|
|
169
|
+
/** The tickets whose worker decides a person's follow-up: see `followupOwners`. */
|
|
170
|
+
owners(trigger) {
|
|
171
|
+
return followupOwners(trigger, this.repo);
|
|
172
|
+
}
|
|
173
|
+
/** Refuse a main-Session routing of a follow-up a ticket's worker still decides. */
|
|
174
|
+
leftToWorkers(trigger) {
|
|
175
|
+
const owners = this.owners(trigger);
|
|
176
|
+
if (owners.length) throw new UserError("workerDecides", { tickets: owners.join(", ") });
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Record that a ticket's worker hands back a Trigger that reached the ticket, with why, and queue it for Eval when the
|
|
180
|
+
* ticket decided it and no other ticket still does. One the ticket did not decide, such as a bot's, one a person sent to
|
|
181
|
+
* Eval or one on a Thread it follows for context, went to Eval without it.
|
|
182
|
+
* @returns whether it was queued.
|
|
183
|
+
*/
|
|
184
|
+
handBack(ticketId, trigger, reason) {
|
|
185
|
+
const decided = this.owners(trigger).includes(ticketId);
|
|
186
|
+
const disposition = this.repo.triggers.disposition(trigger.id) ?? {
|
|
187
|
+
fanout: [],
|
|
188
|
+
at: this.now()
|
|
189
|
+
};
|
|
190
|
+
const handbacks = [...disposition.handbacks ?? [], {
|
|
191
|
+
ticketId,
|
|
192
|
+
reason,
|
|
193
|
+
at: this.now()
|
|
194
|
+
}];
|
|
195
|
+
this.repo.triggers.saveDisposition(trigger.id, {
|
|
196
|
+
...disposition,
|
|
197
|
+
handbacks
|
|
198
|
+
});
|
|
199
|
+
return decided && !this.owners(trigger).length && this.queueForEval(trigger);
|
|
200
|
+
}
|
|
201
|
+
/** Record that a ticket's worker took a person's message up as within the ticket, by acknowledging or answering it. */
|
|
202
|
+
takeUp(ticketId, triggerId) {
|
|
203
|
+
const disposition = this.repo.triggers.disposition(triggerId);
|
|
204
|
+
if (disposition && !disposition.acked?.includes(ticketId)) this.repo.triggers.saveDisposition(triggerId, {
|
|
205
|
+
...disposition,
|
|
206
|
+
acked: [...disposition.acked ?? [], ticketId]
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
/** Queue a Trigger on its primary Thread for the next Eval, unless it waits there already or an Eval holds it. */
|
|
210
|
+
queueForEval(trigger) {
|
|
211
|
+
const primary = this.thread(trigger.threads[0]);
|
|
212
|
+
if (primary.pending.includes(trigger.id) || primary.evaluating?.triggerIds.includes(trigger.id)) return false;
|
|
213
|
+
primary.pending.push(trigger.id);
|
|
214
|
+
this.repo.threads.save(primary);
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
emit(type, data) {
|
|
218
|
+
this.options.emit?.({
|
|
219
|
+
type,
|
|
220
|
+
at: this.now(),
|
|
221
|
+
data
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
require(ticketId) {
|
|
225
|
+
const ticket = this.repo.tickets.get(ticketId);
|
|
226
|
+
if (!ticket) throw new UserError("unknownTicket");
|
|
227
|
+
return ticket;
|
|
228
|
+
}
|
|
229
|
+
/** Returns the stored Thread or an unsaved empty Thread aggregate. */
|
|
230
|
+
thread(ref) {
|
|
231
|
+
const k = threadKey(ref);
|
|
232
|
+
return this.repo.threads.get(k) ?? {
|
|
233
|
+
key: k,
|
|
234
|
+
ref: {
|
|
235
|
+
source: ref.source,
|
|
236
|
+
id: ref.id
|
|
237
|
+
},
|
|
238
|
+
createdAt: this.now(),
|
|
239
|
+
subscriptions: [],
|
|
240
|
+
correlated: [],
|
|
241
|
+
pending: [],
|
|
242
|
+
meta: {}
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
ticketsOnThread(thread) {
|
|
246
|
+
return thread.subscriptions.flatMap((id) => {
|
|
247
|
+
const ticket = this.repo.tickets.get(id);
|
|
248
|
+
return ticket ? [ticket] : [];
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
source(ticket) {
|
|
252
|
+
return this.repo.triggers.get(ticket.origin.triggerId);
|
|
253
|
+
}
|
|
254
|
+
reaches(ticket, trigger, context = true) {
|
|
255
|
+
return reached(ticket, trigger, (k) => this.repo.threads.get(k), context);
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
// src/core/stage.ts
|
|
259
|
+
/** Ticket stage classification and retry eligibility (docs/003). */
|
|
260
|
+
/** Classifies a ticket's stage; the rules follow the table in docs/003 in order, where the first matching row wins. */
|
|
261
|
+
function ticketStage(ticket) {
|
|
262
|
+
if (ticket.ended) return { stage: "ended" };
|
|
263
|
+
if (ticket.delivery) return {
|
|
264
|
+
stage: "person",
|
|
265
|
+
action: "delivery"
|
|
266
|
+
};
|
|
267
|
+
if (ticket.attention) return {
|
|
268
|
+
stage: "person",
|
|
269
|
+
action: "answer"
|
|
270
|
+
};
|
|
271
|
+
const assignment = latestAssignment(ticket);
|
|
272
|
+
const report = assignment?.report?.state;
|
|
273
|
+
if (report === "ready") return {
|
|
274
|
+
stage: "person",
|
|
275
|
+
action: "review"
|
|
276
|
+
};
|
|
277
|
+
if ((report === "blocked" || report === "failed") && waitsForPerson(ticket)) return {
|
|
278
|
+
stage: "person",
|
|
279
|
+
action: report
|
|
280
|
+
};
|
|
281
|
+
if (!assignment || assignment.state === "pending") return {
|
|
282
|
+
stage: "working",
|
|
283
|
+
action: "queued"
|
|
284
|
+
};
|
|
285
|
+
if (report === "waiting" || assignment.state === "ended") return { stage: "idle" };
|
|
286
|
+
return { stage: "working" };
|
|
287
|
+
}
|
|
288
|
+
/** True when an open ticket is stalled on a blocked/failed report without a newer human follow-up, or has a failed input delivery. */
|
|
289
|
+
function canRetry(ticket) {
|
|
290
|
+
return !ticket.ended && (waitsForPerson(ticket) || !!ticket.delivery);
|
|
291
|
+
}
|
|
292
|
+
// src/core/tickets.ts
|
|
293
|
+
/** Tickets: their lifecycle from an accept to their end, their Subscriptions and their Inputs. */
|
|
294
|
+
const sameChannel = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
295
|
+
/** Whether an Input is a message no person wrote, such as CI's, a bot's, or the main Session's note. */
|
|
296
|
+
const automatic = (input) => input?.kind === "note" || input?.kind === "trigger" && !input.human;
|
|
297
|
+
/**
|
|
298
|
+
* Whether a ticket's worker read a Trigger Input before `until`, its latest report or turn end: its Session took the message
|
|
299
|
+
* into a step before then. One delivered before reads were recorded counts as read once it reached the worker by then.
|
|
300
|
+
*/
|
|
301
|
+
const readBefore = (input, until) => input.readAt === void 0 ? (input.deliveredAt && input.deliveredAt > input.at ? input.deliveredAt : input.at) <= until : !!input.readAt && input.readAt < until;
|
|
302
|
+
const STATUS_REQUEST = "Report the current ticket status with orchestrator_report. This is a status-only request: do not resume implementation or perform external actions.";
|
|
303
|
+
/**
|
|
304
|
+
* Manages each ticket's lifecycle: creates the ticket for an accept decision with its Mandate, Subscriptions, and first
|
|
305
|
+
* Assignment, binds and attaches Threads, adds Inputs, resumes, retries, restarts, and ends tickets, and drops Subscriptions.
|
|
306
|
+
* Coordinates with Replies for the acknowledgement an accept carries and with Executor to start, deliver to, and stop assignments.
|
|
307
|
+
* Intake, Evals, Assignments, and Engine delegate ticket and subscription mutations here.
|
|
308
|
+
*/
|
|
309
|
+
var Tickets = class extends EnginePart {
|
|
310
|
+
replies;
|
|
311
|
+
constructor(options, replies) {
|
|
312
|
+
super(options);
|
|
313
|
+
this.replies = replies;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Create the ticket an accept decided, under `mandate`, with the Channels and Threads of the Eval's Triggers, its first
|
|
317
|
+
* Assignment, and the acknowledgement the accept carries, and queue its launch. Its origin is the admissible Trigger that
|
|
318
|
+
* gave the Eval its strength, or the Eval's last Trigger for an Eval recorded before `primary` existed.
|
|
319
|
+
*/
|
|
320
|
+
create(id, decisionId, mandate, evaluation, outcome, at) {
|
|
321
|
+
const { triggerIds } = evaluation;
|
|
322
|
+
const primary = this.repo.triggers.get(evaluation.primary ?? triggerIds.at(-1));
|
|
323
|
+
const origin = {
|
|
324
|
+
triggerId: primary?.id ?? triggerIds[0],
|
|
325
|
+
triggerIds
|
|
326
|
+
};
|
|
327
|
+
let ticket = {
|
|
328
|
+
id,
|
|
329
|
+
title: outcome.title,
|
|
330
|
+
decisionId,
|
|
331
|
+
mandate,
|
|
332
|
+
channels: [],
|
|
333
|
+
assignments: [],
|
|
334
|
+
inputs: [],
|
|
335
|
+
undelivered: [],
|
|
336
|
+
createdAt: at,
|
|
337
|
+
updatedAt: at,
|
|
338
|
+
origin
|
|
339
|
+
};
|
|
340
|
+
for (const triggerId of triggerIds) {
|
|
341
|
+
const channel = this.repo.triggers.get(triggerId)?.channel;
|
|
342
|
+
if (channel && !ticket.channels.some((item) => sameChannel(item, channel))) ticket.channels.push(channel);
|
|
343
|
+
}
|
|
344
|
+
ticket = this.options.prepareTicket?.(ticket, outcome) ?? ticket;
|
|
345
|
+
const assignment = this.newAssignment(ticket);
|
|
346
|
+
this.repo.tickets.save(ticket);
|
|
347
|
+
for (const triggerId of triggerIds) for (const ref of this.repo.triggers.get(triggerId)?.threads ?? []) this.subscribe(id, ref);
|
|
348
|
+
if (outcome.acknowledgement && primary) this.replies.acknowledgeAccepted(id, primary, outcome.acknowledgement);
|
|
349
|
+
this.options.executor.start(this.require(id), assignment);
|
|
350
|
+
this.emit("ticket.created", {
|
|
351
|
+
ticketId: id,
|
|
352
|
+
decisionId,
|
|
353
|
+
strength: mandate.strength
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Subscribes an open ticket to `thread` and records it in `ticket.follows` (`own` when opened by the ticket).
|
|
358
|
+
* @throws UserError when the ticket is unknown or has ended.
|
|
359
|
+
*/
|
|
360
|
+
bind(ticketId, thread, own) {
|
|
361
|
+
if (!liveTicket(this.require(ticketId))) throw new UserError("ticketEnded");
|
|
362
|
+
this.subscribe(ticketId, thread);
|
|
363
|
+
const ticket = this.require(ticketId);
|
|
364
|
+
const followed = threadKey(thread);
|
|
365
|
+
const follow = ticket.follows?.find((item) => item.thread === followed);
|
|
366
|
+
if (follow) {
|
|
367
|
+
follow.own ||= own;
|
|
368
|
+
delete follow.closed;
|
|
369
|
+
} else ticket.follows = [...ticket.follows ?? [], {
|
|
370
|
+
thread: followed,
|
|
371
|
+
own
|
|
372
|
+
}];
|
|
373
|
+
ticket.updatedAt = this.now();
|
|
374
|
+
this.repo.tickets.save(ticket);
|
|
375
|
+
return ticket;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Record that a Thread open tickets follow closed, and end each one done with its Threads (see `followsDone`), unless its
|
|
379
|
+
* work has not finished (see `unfinished`); such work ends the ticket once it reports ready.
|
|
380
|
+
*/
|
|
381
|
+
threadClosed(thread, outcome, at) {
|
|
382
|
+
const closed = threadKey(thread);
|
|
383
|
+
for (const ticket of this.repo.tickets.open()) {
|
|
384
|
+
const follow = ticket.follows?.find((item) => item.thread === closed && !item.closed);
|
|
385
|
+
if (!follow) continue;
|
|
386
|
+
follow.closed = {
|
|
387
|
+
at,
|
|
388
|
+
outcome
|
|
389
|
+
};
|
|
390
|
+
this.repo.tickets.save(ticket);
|
|
391
|
+
const done = this.followsDone(ticket);
|
|
392
|
+
if (!done || this.unfinished(ticket, at)) continue;
|
|
393
|
+
const resumed = Date.parse(latestAssignment(ticket)?.createdAt ?? "") > Date.parse(at);
|
|
394
|
+
this.end(ticket.id, "executor", done.outcome, resumed ? this.now() : done.at);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* How a ticket that follows Threads is done with them: once no Thread it opened (`own`) is still open, or, when it opened none,
|
|
399
|
+
* once every one it follows closed. It ends as the latest close among those Threads did; undefined while it is not done.
|
|
400
|
+
*/
|
|
401
|
+
followsDone(ticket) {
|
|
402
|
+
const follows = ticket.follows ?? [];
|
|
403
|
+
const own = follows.filter((item) => item.own);
|
|
404
|
+
const counted = own.length ? own : follows;
|
|
405
|
+
if (!counted.length || counted.some((item) => !item.closed)) return void 0;
|
|
406
|
+
return counted.map((item) => item.closed).sort((a, b) => a.at.localeCompare(b.at)).at(-1);
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* The Trigger to attach to a ticket, once the ticket may take it.
|
|
410
|
+
* @throws UserError when the trigger or ticket is unknown, a ticket's worker still decides the trigger, a person stopped the ticket, or an ended ticket's Mandate no longer revalidates.
|
|
411
|
+
*/
|
|
412
|
+
attachable(ticketId, triggerId) {
|
|
413
|
+
const trigger = this.repo.triggers.get(triggerId);
|
|
414
|
+
if (!trigger) throw new UserError("unknownTrigger");
|
|
415
|
+
this.leftToWorkers(trigger);
|
|
416
|
+
const current = this.require(ticketId);
|
|
417
|
+
if (current.ended?.by === "human") throw new UserError("ticketStopped");
|
|
418
|
+
if (!liveTicket(current) && !this.policy().revalidate(current.mandate)) throw new UserError("mandateRevoked");
|
|
419
|
+
return trigger;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Subscribe a ticket to an attached Trigger's Threads and add the Trigger as an Input, with its note. The ticket's worker
|
|
423
|
+
* then decides it, as it decides a message that reached the ticket on its own Thread; a worker that does not hold the
|
|
424
|
+
* message as its ticket's takes it as a new Input, which wakes an ended ticket as any attached message does.
|
|
425
|
+
*/
|
|
426
|
+
attach(ticketId, trigger, note) {
|
|
427
|
+
for (const ref of trigger.threads) this.subscribe(ticketId, ref);
|
|
428
|
+
const current = this.repo.triggers.disposition(trigger.id) ?? {
|
|
429
|
+
fanout: [],
|
|
430
|
+
at: this.now()
|
|
431
|
+
};
|
|
432
|
+
const { context, requeued, ...disposition } = current;
|
|
433
|
+
const followed = context?.filter((id) => id !== ticketId);
|
|
434
|
+
this.repo.triggers.saveDisposition(trigger.id, {
|
|
435
|
+
...disposition,
|
|
436
|
+
fanout: [.../* @__PURE__ */ new Set([...disposition.fanout, ticketId])],
|
|
437
|
+
...followed?.length ? { context: followed } : {}
|
|
438
|
+
});
|
|
439
|
+
const ticket = this.require(ticketId);
|
|
440
|
+
const id = key("input", ticketId, "trigger", trigger.id);
|
|
441
|
+
const existing = ticket.inputs.find((input) => input.id === id);
|
|
442
|
+
const at = this.now();
|
|
443
|
+
const input = (inputId) => ({
|
|
444
|
+
id: inputId,
|
|
445
|
+
kind: "trigger",
|
|
446
|
+
triggerId: trigger.id,
|
|
447
|
+
at,
|
|
448
|
+
...note ? { note } : {},
|
|
449
|
+
...trigger.human ? { human: true } : {}
|
|
450
|
+
});
|
|
451
|
+
if (existing?.kind !== "trigger") this.addInput(ticket, input(id));
|
|
452
|
+
else if (note && ticket.undelivered.includes(id)) {
|
|
453
|
+
existing.note = note;
|
|
454
|
+
ticket.updatedAt = at;
|
|
455
|
+
this.repo.tickets.save(ticket);
|
|
456
|
+
} else if (requeued || !current.fanout.includes(ticketId) || context?.includes(ticketId) || !liveTicket(ticket)) this.addInput(ticket, input(key("input", ticketId, "trigger", trigger.id, "attached", at)));
|
|
457
|
+
else if (note) this.addInput(ticket, input(key("input", ticketId, "trigger", trigger.id, "note", note)));
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Ask a running worker whose latest report is `waiting` for a status report; leaves any other ticket alone.
|
|
461
|
+
* @returns whether the status request input was queued.
|
|
462
|
+
* @throws UserError when the ticket is unknown.
|
|
463
|
+
*/
|
|
464
|
+
requestStatus(ticketId) {
|
|
465
|
+
const ticket = this.require(ticketId);
|
|
466
|
+
if (!liveTicket(ticket) || runningAssignment(ticket)?.report?.state !== "waiting") return false;
|
|
467
|
+
this.addInput(ticket, {
|
|
468
|
+
id: `status:${ticketId}:${ticket.updatedAt}`,
|
|
469
|
+
kind: "text",
|
|
470
|
+
text: STATUS_REQUEST,
|
|
471
|
+
at: this.now()
|
|
472
|
+
});
|
|
473
|
+
return true;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Stops a ticket on behalf of a human, ending any active assignments.
|
|
477
|
+
* @throws UserError when the ticket is unknown.
|
|
478
|
+
*/
|
|
479
|
+
stop(ticketId, reason) {
|
|
480
|
+
this.end(ticketId, "human", "stopped", this.now(), reason);
|
|
481
|
+
return this.require(ticketId);
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Ends the stalled assignment of a retryable open ticket (`failed`, `blocked`, or failed input delivery) and starts a new one.
|
|
485
|
+
* @throws UserError when the ticket is unknown or not retryable.
|
|
486
|
+
*/
|
|
487
|
+
retry(ticketId) {
|
|
488
|
+
const ticket = this.require(ticketId);
|
|
489
|
+
const latest = latestAssignment(ticket);
|
|
490
|
+
if (!canRetry(ticket) || !latest) throw new UserError("notRetryable");
|
|
491
|
+
this.endAssignment(ticket, latest, "retried");
|
|
492
|
+
this.requeueUntaken(ticket, latest);
|
|
493
|
+
const assignment = this.newAssignment(ticket);
|
|
494
|
+
ticket.updatedAt = this.now();
|
|
495
|
+
this.repo.tickets.save(ticket);
|
|
496
|
+
this.options.executor.stop(ticket, latest, "retried");
|
|
497
|
+
this.options.executor.start(ticket, assignment);
|
|
498
|
+
return ticket;
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Drops a ticket's Subscription to a Thread its worker found unrelated, and hands back, with `reason`, the person's messages there that the ticket decides.
|
|
502
|
+
* @throws UserError when the ticket is unknown, or `thread` is an origin thread, a bound `follows` thread, or not subscribed.
|
|
503
|
+
*/
|
|
504
|
+
markUnrelated(ticketId, thread, reason) {
|
|
505
|
+
const ticket = this.require(ticketId);
|
|
506
|
+
if (this.source(ticket)?.threads.some((ref) => threadKey(ref) === thread)) throw new UserError("sourceThread");
|
|
507
|
+
if (ticket.follows?.some((item) => item.thread === thread)) throw new UserError("followedThread");
|
|
508
|
+
if (!this.repo.threads.get(thread)?.subscriptions.includes(ticketId)) throw new UserError("notFollowing");
|
|
509
|
+
this.dropSubscriptions(thread, "executor", ticketId, reason);
|
|
510
|
+
for (const trigger of this.triggersOf(ticket)) if (trigger.threads.some((ref) => threadKey(ref) === thread) && this.owners(trigger).includes(ticketId)) this.handBack(ticketId, trigger, reason);
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Tell each open ticket a Policy change bears on how it does, oldest first, so their deliveries queue in the order they
|
|
514
|
+
* were accepted; the others are left alone.
|
|
515
|
+
*/
|
|
516
|
+
policyChanged(from, to, effects) {
|
|
517
|
+
const at = this.now();
|
|
518
|
+
for (const ticket of this.repo.tickets.open().sort((a, b) => a.createdAt.localeCompare(b.createdAt))) {
|
|
519
|
+
const effect = effects.get(ticket.id);
|
|
520
|
+
if (effect) this.addInput(ticket, {
|
|
521
|
+
id: key("input", ticket.id, "policy", from, to, at),
|
|
522
|
+
kind: "policy-changed",
|
|
523
|
+
from,
|
|
524
|
+
to,
|
|
525
|
+
at,
|
|
526
|
+
effect
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Drop a Thread's Subscriptions, every ticket's or only `ticketId`'s, and say so; false when none dropped. A ticket that
|
|
532
|
+
* followed the Thread follows it no more, so its close no longer ends the ticket. Each ticket keeps deciding the messages
|
|
533
|
+
* it received from the Thread.
|
|
534
|
+
*/
|
|
535
|
+
dropSubscriptions(thread, by, ticketId, reason) {
|
|
536
|
+
const current = this.repo.threads.get(thread);
|
|
537
|
+
const tickets = current?.subscriptions.filter((id) => ticketId === void 0 || id === ticketId) ?? [];
|
|
538
|
+
if (!current || !tickets.length) return false;
|
|
539
|
+
current.subscriptions = current.subscriptions.filter((id) => !tickets.includes(id));
|
|
540
|
+
this.repo.threads.save(current);
|
|
541
|
+
for (const id of tickets) {
|
|
542
|
+
const ticket = this.repo.tickets.get(id);
|
|
543
|
+
if (!ticket?.follows?.some((item) => item.thread === thread)) continue;
|
|
544
|
+
const { follows: before, ...rest } = ticket;
|
|
545
|
+
const follows = before.filter((item) => item.thread !== thread);
|
|
546
|
+
this.repo.tickets.save(follows.length ? {
|
|
547
|
+
...rest,
|
|
548
|
+
follows
|
|
549
|
+
} : rest);
|
|
550
|
+
}
|
|
551
|
+
for (const id of tickets) this.emit("thread.unsubscribed", {
|
|
552
|
+
threadKey: current.key,
|
|
553
|
+
ticketId: id,
|
|
554
|
+
by,
|
|
555
|
+
...reason ? { reason } : {}
|
|
556
|
+
});
|
|
557
|
+
return true;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Add an Input once (idempotently) and ask the Executor to deliver it, or to launch again a pending Assignment whose launch
|
|
561
|
+
* failed once no person is waited for: a Policy change alone does not launch it again.
|
|
562
|
+
*/
|
|
563
|
+
addInput(ticket, input) {
|
|
564
|
+
if (ticket.inputs.some((existing) => existing.id === input.id)) return;
|
|
565
|
+
ticket.inputs.push(input);
|
|
566
|
+
ticket.updatedAt = this.now();
|
|
567
|
+
const held = liveTicket(ticket) && automatic(input) && waitsForPerson(ticket);
|
|
568
|
+
if (!held) ticket.undelivered.push(input.id);
|
|
569
|
+
this.repo.tickets.save(ticket);
|
|
570
|
+
if (!liveTicket(ticket) || held) return;
|
|
571
|
+
const running = runningAssignment(ticket), latest = latestAssignment(ticket);
|
|
572
|
+
if (running) this.options.executor.deliver(ticket, running);
|
|
573
|
+
else if (latest?.state === "pending" && !waitsForPerson(ticket)) this.options.executor.start(ticket, latest);
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Resume an ended ticket under its unchanged Mandate when a person's message on one of its Threads waits for it: no Eval
|
|
577
|
+
* and no Decision, since nothing new is authorized. One whose Mandate the current Policy no longer holds stays ended and
|
|
578
|
+
* takes nothing (see `refuse`). While processing is paused the message waits, and the first pass after the pause resumes
|
|
579
|
+
* the ticket under the Policy then. Reads the ticket afresh, so it is idempotent and leaves an already-resumed ticket alone.
|
|
580
|
+
*/
|
|
581
|
+
wake(ticketId) {
|
|
582
|
+
const ticket = this.repo.tickets.get(ticketId);
|
|
583
|
+
if (!ticket || liveTicket(ticket) || ticket.ended?.by === "human" || !ticket.undelivered.length) return;
|
|
584
|
+
const policy = this.policy();
|
|
585
|
+
if (policy.paused) return;
|
|
586
|
+
if (!policy.revalidate(ticket.mandate)) {
|
|
587
|
+
this.refuse(ticket);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
const first = ticket.undelivered.map((id) => ticket.inputs.find((input) => input.id === id)).find((input) => input?.kind === "trigger" && input.human);
|
|
591
|
+
if (first?.kind !== "trigger") return;
|
|
592
|
+
const at = this.now();
|
|
593
|
+
delete ticket.ended;
|
|
594
|
+
ticket.updatedAt = at;
|
|
595
|
+
const assignment = this.newAssignment(ticket);
|
|
596
|
+
const resumed = {
|
|
597
|
+
id: key("input", ticket.id, "resumed", first.triggerId),
|
|
598
|
+
kind: "resumed",
|
|
599
|
+
triggerId: first.triggerId,
|
|
600
|
+
at
|
|
601
|
+
};
|
|
602
|
+
ticket.inputs.push(resumed);
|
|
603
|
+
ticket.undelivered.unshift(resumed.id);
|
|
604
|
+
this.repo.tickets.save(ticket);
|
|
605
|
+
this.options.executor.start(ticket, assignment);
|
|
606
|
+
this.emit("ticket.resumed", {
|
|
607
|
+
ticketId,
|
|
608
|
+
triggerId: first.triggerId
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
/** The Triggers of a ticket's trigger Inputs, or of those of them whose Input ids are `ids`. */
|
|
612
|
+
triggersOf(ticket, ids) {
|
|
613
|
+
return ticket.inputs.flatMap((input) => input.kind === "trigger" && (!ids || ids.includes(input.id)) ? this.repo.triggers.get(input.triggerId) ?? [] : []);
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Whether a ticket's worker took a person's message up, by acknowledging or answering it. A message acknowledged before
|
|
617
|
+
* acknowledgements were recorded on it has only the acknowledgement's message in the outbox.
|
|
618
|
+
*/
|
|
619
|
+
takenUp(ticket, trigger) {
|
|
620
|
+
const acked = this.repo.triggers.disposition(trigger.id)?.acked;
|
|
621
|
+
return acked ? acked.includes(ticket.id) : this.options.outbox.status(key("ack", trigger.id)) !== void 0;
|
|
622
|
+
}
|
|
623
|
+
/** The person's messages among a ticket's Inputs `ids` that it decides and its worker did not take up. */
|
|
624
|
+
untaken(ticket, ids) {
|
|
625
|
+
return this.triggersOf(ticket, ids).filter((trigger) => this.owners(trigger).includes(ticket.id) && !this.takenUp(ticket, trigger));
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* A ticket that ended, or cannot resume, lets go of the messages its worker never received, `waiting`, and of the person's
|
|
629
|
+
* messages it decided but may not have taken up, `left`: it no longer counts as having reached them, and each of `left`
|
|
630
|
+
* that no other ticket decides goes to Eval, as a person's message that reached no ticket does, unless a ticket took it
|
|
631
|
+
* up, a Decision settled it, or it is the message a stop ended this ticket on.
|
|
632
|
+
*/
|
|
633
|
+
letGo(ticketId, waiting, left) {
|
|
634
|
+
for (const trigger of [...waiting, ...left]) {
|
|
635
|
+
const disposition = this.repo.triggers.disposition(trigger.id);
|
|
636
|
+
if (disposition?.fanout.includes(ticketId)) this.repo.triggers.saveDisposition(trigger.id, {
|
|
637
|
+
...disposition,
|
|
638
|
+
fanout: disposition.fanout.filter((id) => id !== ticketId)
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
for (const trigger of left) {
|
|
642
|
+
const disposition = this.repo.triggers.disposition(trigger.id);
|
|
643
|
+
const decision = disposition?.decisionId ? this.repo.decisions.get(disposition.decisionId) : void 0;
|
|
644
|
+
const stopped = decision?.kind === "stop" && decision.ticketId === ticketId && !disposition?.handbacks?.length;
|
|
645
|
+
const decided = !!decision && (settled(decision) || stopped);
|
|
646
|
+
if (!this.owners(trigger).length && !disposition?.acked?.length && !decided) this.queueForEval(trigger);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
/** An ended ticket that cannot resume takes none of the messages that waited for it (see `letGo`). */
|
|
650
|
+
refuse(ticket) {
|
|
651
|
+
const waiting = this.triggersOf(ticket, ticket.undelivered), left = this.untaken(ticket, ticket.undelivered);
|
|
652
|
+
ticket.undelivered = [];
|
|
653
|
+
this.repo.tickets.save(ticket);
|
|
654
|
+
this.letGo(ticket.id, waiting, left);
|
|
655
|
+
}
|
|
656
|
+
/** Replace a ticket's running Assignment with a new one that receives `note` first, and queue it for launch. */
|
|
657
|
+
restart(ticket, running, reason, note) {
|
|
658
|
+
const at = this.now();
|
|
659
|
+
const input = {
|
|
660
|
+
id: key("input", ticket.id, "restart", running.id, at),
|
|
661
|
+
kind: "text",
|
|
662
|
+
text: note,
|
|
663
|
+
at
|
|
664
|
+
};
|
|
665
|
+
ticket.inputs.push(input);
|
|
666
|
+
this.endAssignment(ticket, running, reason);
|
|
667
|
+
this.requeueUntaken(ticket, running);
|
|
668
|
+
const assignment = this.newAssignment(ticket);
|
|
669
|
+
ticket.undelivered.push(input.id);
|
|
670
|
+
ticket.updatedAt = at;
|
|
671
|
+
this.repo.tickets.save(ticket);
|
|
672
|
+
this.options.executor.stop(ticket, running, reason);
|
|
673
|
+
this.options.executor.start(ticket, assignment);
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Put back, ahead of what waits, the Trigger Inputs delivered to `replaced` that no step of its worker took: a cancel may
|
|
677
|
+
* have dropped them, or a step that claimed them was cut off, and the new Assignment's launch takes a copy still waiting
|
|
678
|
+
* in the Session out, so its delivery is the only one. An earlier end let go of what earlier Assignments left.
|
|
679
|
+
*/
|
|
680
|
+
requeueUntaken(ticket, replaced) {
|
|
681
|
+
const untaken = ticket.inputs.filter((input) => input.kind === "trigger" && input.readAt === null && input.deliveredTo === replaced.id && !ticket.undelivered.includes(input.id));
|
|
682
|
+
ticket.undelivered.unshift(...untaken.map((input) => input.id));
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* End a ticket with its outcome. `at` records when the ending fact happened, such as a PR merge, and `reason` says
|
|
686
|
+
* why in words, by default the outcome. The ticket lets go (see `letGo`) of the messages its worker never received, and of
|
|
687
|
+
* the person's messages it decides that its worker did not read before its latest report or turn end, the report that
|
|
688
|
+
* ends the ticket included (see `readBefore`), and neither acknowledged, answered nor handed back: one may have come while
|
|
689
|
+
* the worker wrote the report that ends the ticket, or after its turn ended, and either way it can no longer hand it back.
|
|
690
|
+
*/
|
|
691
|
+
end(ticketId, by, outcome, at = this.now(), reason) {
|
|
692
|
+
const ticket = this.require(ticketId);
|
|
693
|
+
if (!liveTicket(ticket)) return;
|
|
694
|
+
const stopping = ticket.assignments.filter((assignment) => assignment.state !== "ended");
|
|
695
|
+
const why = reason && reason !== outcome ? { reason } : {};
|
|
696
|
+
const until = readUntil(ticket);
|
|
697
|
+
const waiting = this.triggersOf(ticket, ticket.undelivered);
|
|
698
|
+
const left = this.untaken(ticket, ticket.inputs.flatMap((input) => input.kind === "trigger" && (!readBefore(input, until) || ticket.undelivered.includes(input.id)) ? [input.id] : []));
|
|
699
|
+
ticket.ended = {
|
|
700
|
+
at,
|
|
701
|
+
by,
|
|
702
|
+
outcome,
|
|
703
|
+
...why
|
|
704
|
+
};
|
|
705
|
+
ticket.undelivered = [];
|
|
706
|
+
ticket.updatedAt = this.now();
|
|
707
|
+
delete ticket.attention;
|
|
708
|
+
delete ticket.delivery;
|
|
709
|
+
for (const assignment of stopping) {
|
|
710
|
+
assignment.state = "ended";
|
|
711
|
+
assignment.endedAt = at;
|
|
712
|
+
}
|
|
713
|
+
this.repo.tickets.save(ticket);
|
|
714
|
+
this.letGo(ticketId, waiting, left);
|
|
715
|
+
this.emit("ticket.ended", {
|
|
716
|
+
ticketId,
|
|
717
|
+
by,
|
|
718
|
+
outcome,
|
|
719
|
+
...why
|
|
720
|
+
});
|
|
721
|
+
for (const assignment of stopping) this.options.executor.stop(ticket, assignment, reason ?? outcome);
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Whether a ticket's work has not finished at a close at `at`: its worker took up a person's message the ticket decides and
|
|
725
|
+
* has not reported other than progress, or ended a turn, since its Session took that message into a step, or work resumed
|
|
726
|
+
* after the close, whose Assignment started after it, has no ready report or Input arrived after that report; a Policy
|
|
727
|
+
* change asks for no work.
|
|
728
|
+
*/
|
|
729
|
+
unfinished(ticket, at) {
|
|
730
|
+
const until = readUntil(ticket, false);
|
|
731
|
+
const taken = this.triggersOf(ticket, ticket.inputs.flatMap((input) => input.kind === "trigger" && !readBefore(input, until) ? [input.id] : [])).some((trigger) => this.owners(trigger).includes(ticket.id) && this.takenUp(ticket, trigger));
|
|
732
|
+
const latest = latestAssignment(ticket);
|
|
733
|
+
if (taken || !(Date.parse(latest?.createdAt ?? "") > Date.parse(at))) return taken;
|
|
734
|
+
const report = latest?.report;
|
|
735
|
+
const later = ticket.inputs.some((input) => input.kind !== "policy-changed" && Date.parse(input.at) > Date.parse(report?.at ?? ""));
|
|
736
|
+
return report?.state !== "ready" || ticket.undelivered.length > 0 || later;
|
|
737
|
+
}
|
|
738
|
+
/** Add a pending Assignment; a failed delivery to the one before it no longer concerns the ticket. */
|
|
739
|
+
newAssignment(ticket) {
|
|
740
|
+
const assignment = {
|
|
741
|
+
id: key("assignment", ticket.id, String(ticket.assignments.length)),
|
|
742
|
+
state: "pending",
|
|
743
|
+
createdAt: this.now()
|
|
744
|
+
};
|
|
745
|
+
ticket.assignments.push(assignment);
|
|
746
|
+
delete ticket.delivery;
|
|
747
|
+
return assignment;
|
|
748
|
+
}
|
|
749
|
+
endAssignment(ticket, assignment, reason) {
|
|
750
|
+
assignment.state = "ended";
|
|
751
|
+
assignment.endedAt = this.now();
|
|
752
|
+
assignment.endedReason = reason;
|
|
753
|
+
this.emit("assignment.ended", {
|
|
754
|
+
ticketId: ticket.id,
|
|
755
|
+
assignmentId: assignment.id,
|
|
756
|
+
reason
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* Give an open ticket's Executor a fact as a note Input, such as what another ticket found; it grants nothing (see `TicketInput`).
|
|
761
|
+
* @throws UserError when the ticket is unknown or has ended.
|
|
762
|
+
*/
|
|
763
|
+
note(ticketId, text) {
|
|
764
|
+
const ticket = this.require(ticketId);
|
|
765
|
+
if (!liveTicket(ticket)) throw new UserError("ticketEnded");
|
|
766
|
+
const at = this.now();
|
|
767
|
+
this.addInput(ticket, {
|
|
768
|
+
id: key("input", ticketId, "note", at, text),
|
|
769
|
+
kind: "note",
|
|
770
|
+
text,
|
|
771
|
+
at
|
|
772
|
+
});
|
|
773
|
+
return this.require(ticketId);
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Subscribe an open ticket to a Thread its Executor found related, for context: see `Thread.context`.
|
|
777
|
+
* @returns false when the ticket follows the Thread already.
|
|
778
|
+
* @throws UserError when the ticket is unknown or has ended.
|
|
779
|
+
*/
|
|
780
|
+
followForContext(ticketId, ref) {
|
|
781
|
+
if (!liveTicket(this.require(ticketId))) throw new UserError("ticketEnded");
|
|
782
|
+
if (this.thread(ref).subscriptions.includes(ticketId)) return false;
|
|
783
|
+
this.subscribe(ticketId, ref);
|
|
784
|
+
const thread = this.thread(ref);
|
|
785
|
+
thread.context = [...thread.context ?? [], ticketId];
|
|
786
|
+
this.repo.threads.save(thread);
|
|
787
|
+
return true;
|
|
788
|
+
}
|
|
789
|
+
/** Subscribe a ticket to a Thread; later Triggers on it reach the ticket as Inputs, as the ticket's own once it was for context. */
|
|
790
|
+
subscribe(ticketId, ref) {
|
|
791
|
+
const thread = this.thread(ref);
|
|
792
|
+
if (!thread.subscriptions.includes(ticketId)) {
|
|
793
|
+
thread.subscriptions.push(ticketId);
|
|
794
|
+
this.emit("thread.subscribed", {
|
|
795
|
+
threadKey: thread.key,
|
|
796
|
+
ticketId
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
if (thread.context?.includes(ticketId)) thread.context = thread.context.filter((id) => id !== ticketId);
|
|
800
|
+
this.repo.threads.save(thread);
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
// src/core/assignments.ts
|
|
804
|
+
/** What the Executor and its workers report about the Assignments that run tickets. */
|
|
805
|
+
const RECOVERY_NOTE = "The host restarted during this ticket. Inspect the current worktree, git history and GitHub state before continuing. Do not repeat an already completed external operation. Finish the original assignment and report its status.";
|
|
806
|
+
/**
|
|
807
|
+
* Assignments records what the Executor and its workers report about the Assignments that run tickets: one started, Inputs
|
|
808
|
+
* reached it or failed to, its worker's Session took Inputs into a step, a turn of its worker ended, a host restart
|
|
809
|
+
* interrupted it, and a worker's report with its question for a person. It depends on
|
|
810
|
+
* Tickets to restart or end a ticket and on Replies to withdraw a question a report replaced; the Engine routes the
|
|
811
|
+
* Executor's lifecycle callbacks and its workers' reports here.
|
|
812
|
+
*/
|
|
813
|
+
var Assignments = class extends EnginePart {
|
|
814
|
+
tickets;
|
|
815
|
+
replies;
|
|
816
|
+
constructor(options, tickets, replies) {
|
|
817
|
+
super(options);
|
|
818
|
+
this.tickets = tickets;
|
|
819
|
+
this.replies = replies;
|
|
820
|
+
}
|
|
821
|
+
/** Marks a non-ended assignment running, queues delivery of waiting undelivered inputs on an open ticket, and emits `assignment.started`. */
|
|
822
|
+
started(ticketId, assignmentId) {
|
|
823
|
+
const ticket = this.require(ticketId);
|
|
824
|
+
const assignment = ticket.assignments.find((item) => item.id === assignmentId);
|
|
825
|
+
if (!assignment || assignment.state === "ended") return;
|
|
826
|
+
assignment.state = "running";
|
|
827
|
+
assignment.startedAt ??= this.now();
|
|
828
|
+
ticket.updatedAt = this.now();
|
|
829
|
+
this.repo.tickets.save(ticket);
|
|
830
|
+
if (liveTicket(ticket) && ticket.undelivered.length) this.options.executor.deliver(ticket, assignment);
|
|
831
|
+
this.emit("assignment.started", {
|
|
832
|
+
ticketId,
|
|
833
|
+
assignmentId
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Marks `inputIds` delivered on the ticket's running assignment and clears any prior `delivery` failure; ignored if no
|
|
838
|
+
* longer running. Its worker reads each once its Session takes it into a step (see `read`).
|
|
839
|
+
*/
|
|
840
|
+
delivered(ticketId, assignmentId, inputIds) {
|
|
841
|
+
const ticket = this.running(ticketId, assignmentId);
|
|
842
|
+
if (!ticket) return;
|
|
843
|
+
ticket.undelivered = ticket.undelivered.filter((id) => !inputIds.includes(id));
|
|
844
|
+
ticket.updatedAt = this.now();
|
|
845
|
+
runningAssignment(ticket).deliveredAt = ticket.updatedAt;
|
|
846
|
+
for (const input of ticket.inputs) if (input.kind === "trigger" && inputIds.includes(input.id)) {
|
|
847
|
+
input.readAt ??= null;
|
|
848
|
+
input.deliveredTo = assignmentId;
|
|
849
|
+
}
|
|
850
|
+
delete ticket.delivery;
|
|
851
|
+
this.repo.tickets.save(ticket);
|
|
852
|
+
}
|
|
853
|
+
/** Records when the worker's Session of an open ticket took `inputIds` into a step, from which its model reads them. */
|
|
854
|
+
read(ticketId, inputIds) {
|
|
855
|
+
const ticket = this.require(ticketId);
|
|
856
|
+
if (!liveTicket(ticket)) return;
|
|
857
|
+
for (const input of ticket.inputs) if (input.kind === "trigger" && inputIds.includes(input.id)) input.readAt ||= this.now();
|
|
858
|
+
this.repo.tickets.save(ticket);
|
|
859
|
+
}
|
|
860
|
+
turnEnded(ticketId, assignmentId) {
|
|
861
|
+
const ticket = this.running(ticketId, assignmentId);
|
|
862
|
+
if (!ticket) return;
|
|
863
|
+
runningAssignment(ticket).idleAt = this.now();
|
|
864
|
+
this.repo.tickets.save(ticket);
|
|
865
|
+
}
|
|
866
|
+
deliveryFailed(ticketId, assignmentId, error) {
|
|
867
|
+
const ticket = this.running(ticketId, assignmentId);
|
|
868
|
+
if (!ticket) return;
|
|
869
|
+
ticket.delivery = {
|
|
870
|
+
error: error.slice(0, 300),
|
|
871
|
+
at: this.now()
|
|
872
|
+
};
|
|
873
|
+
this.repo.tickets.save(ticket);
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Handles a running assignment interrupted by a host restart: restarts it with a recovery note unless its latest report is
|
|
877
|
+
* `waiting`, `ready`, `blocked`, or `failed` and no input was delivered after that report, in which case it keeps its
|
|
878
|
+
* session and flushes any waiting undelivered inputs.
|
|
879
|
+
*/
|
|
880
|
+
interrupted(ticketId, assignmentId) {
|
|
881
|
+
const ticket = this.running(ticketId, assignmentId);
|
|
882
|
+
const running = ticket && runningAssignment(ticket);
|
|
883
|
+
if (!ticket || !running) return;
|
|
884
|
+
const report = running.report;
|
|
885
|
+
const busy = !!running.deliveredAt && !!report && running.deliveredAt >= report.at;
|
|
886
|
+
if (!(!!report && [
|
|
887
|
+
"waiting",
|
|
888
|
+
"ready",
|
|
889
|
+
"blocked",
|
|
890
|
+
"failed"
|
|
891
|
+
].includes(report.state) && !busy)) this.tickets.restart(ticket, running, "hostRestarted", RECOVERY_NOTE);
|
|
892
|
+
else if (ticket.undelivered.length) this.options.executor.deliver(ticket, running);
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Records a worker status report on an open ticket's current assignment, updating `attention`, `answers`, held automated
|
|
896
|
+
* inputs, and ending the ticket when `dropped` or when `ready` and not waiting on followed threads (`followsDone`).
|
|
897
|
+
* @throws UserError for an unknown or ended ticket, an ended assignment, a question combined with a ready result or answer,
|
|
898
|
+
* or a question/answer referencing a non-human or unreached trigger.
|
|
899
|
+
*/
|
|
900
|
+
report(ticketId, report) {
|
|
901
|
+
const ticket = this.require(ticketId);
|
|
902
|
+
if (!liveTicket(ticket)) throw new UserError("ticketEnded");
|
|
903
|
+
if (report.question && (report.state === "ready" || report.answers)) throw new UserError("questionWithResult");
|
|
904
|
+
if (report.askedBy && !report.question) throw new UserError("askerWithoutQuestion");
|
|
905
|
+
const person = (id, channel) => {
|
|
906
|
+
const trigger = this.repo.triggers.get(id);
|
|
907
|
+
return !!trigger?.human && (!channel || !!trigger.channel) && this.reaches(ticket, trigger, false);
|
|
908
|
+
};
|
|
909
|
+
if (report.askedBy && !person(report.askedBy, true)) throw new UserError("notAsker");
|
|
910
|
+
if (report.answers && !person(report.answers, false)) throw new UserError("notAnswerable");
|
|
911
|
+
const assignment = runningAssignment(ticket) ?? latestAssignment(ticket);
|
|
912
|
+
if (!assignment) throw new UserError("unknownAssignment");
|
|
913
|
+
if (assignment.state === "ended") throw new UserError("assignmentEnded");
|
|
914
|
+
const at = this.now();
|
|
915
|
+
const previous = ticket.attention;
|
|
916
|
+
const ask = (question) => ({
|
|
917
|
+
id: key("attention", ticketId, question, at),
|
|
918
|
+
question,
|
|
919
|
+
...report.askedBy ? { triggerId: report.askedBy } : {}
|
|
920
|
+
});
|
|
921
|
+
const asked = report.question && report.question !== previous?.question ? ask(report.question) : previous;
|
|
922
|
+
const attention = report.question === null || report.state === "ready" ? void 0 : asked;
|
|
923
|
+
if (attention) ticket.attention = attention;
|
|
924
|
+
else delete ticket.attention;
|
|
925
|
+
if (previous && previous.id !== attention?.id) this.replies.withdrawAttention(previous.id);
|
|
926
|
+
assignment.report = {
|
|
927
|
+
state: report.state,
|
|
928
|
+
summary: report.summary,
|
|
929
|
+
at
|
|
930
|
+
};
|
|
931
|
+
ticket.updatedAt = at;
|
|
932
|
+
if (report.answers && !ticket.answers?.includes(report.answers)) ticket.answers = [...ticket.answers ?? [], report.answers];
|
|
933
|
+
if (report.answers) this.takeUp(ticketId, report.answers);
|
|
934
|
+
if (report.state === "blocked" || report.state === "failed") ticket.undelivered = ticket.undelivered.filter((id) => !automatic(ticket.inputs.find((input) => input.id === id)));
|
|
935
|
+
this.repo.tickets.save(ticket);
|
|
936
|
+
const ready = !ticket.follows?.length ? "completed" : this.tickets.followsDone(ticket)?.outcome;
|
|
937
|
+
const outcome = report.state === "dropped" ? this.tickets.followsDone(ticket)?.outcome ?? "dropped" : report.state === "ready" ? ready : void 0;
|
|
938
|
+
if (outcome) this.tickets.end(ticketId, "executor", outcome, at);
|
|
939
|
+
return this.require(ticketId);
|
|
940
|
+
}
|
|
941
|
+
/** The ticket, while it is open and `assignmentId` runs it. */
|
|
942
|
+
running(ticketId, assignmentId) {
|
|
943
|
+
const ticket = this.require(ticketId);
|
|
944
|
+
return liveTicket(ticket) && runningAssignment(ticket)?.id === assignmentId ? ticket : void 0;
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
// src/core/reasons.ts
|
|
948
|
+
/**
|
|
949
|
+
* Structured reason codes and templates for decisions, filtered triggers, and ended assignments.
|
|
950
|
+
* Policy gates and source scopes may also emit their own literal reason codes.
|
|
951
|
+
*/
|
|
952
|
+
const REASONS = {
|
|
953
|
+
said: "{text}",
|
|
954
|
+
timeout: "Assessment timed out",
|
|
955
|
+
policyChanged: "Policy changed during assessment",
|
|
956
|
+
noAdmissible: "No admissible trigger",
|
|
957
|
+
startedTicket: "Already started ticket {ticket}",
|
|
958
|
+
acceptedBefore: "Trigger {trigger} was accepted before",
|
|
959
|
+
routed: "Routed to ticket {ticket}",
|
|
960
|
+
explicitRouted: "Explicit request from an allowed sender routed by the orchestrator",
|
|
961
|
+
humanStop: "Human asked to stop",
|
|
962
|
+
legacyImport: "Imported from the pre-domain-model task record",
|
|
963
|
+
forwarded: "Forwarded to the worker of the Ticket already on this Thread",
|
|
964
|
+
senderNotMember: "The sender is not on the Source's list",
|
|
965
|
+
retried: "Retried by a person",
|
|
966
|
+
hostRestarted: "dsh-superagent restarted",
|
|
967
|
+
stopUnknown: "Stop target is unknown or already ended",
|
|
968
|
+
stopNotExplicit: "A stop needs an explicit request from a sender on the list",
|
|
969
|
+
directionUnsettled: "Implementation intent or target direction is not established, or a product/design decision is still required",
|
|
970
|
+
noRuleMatched: "No enabled admission rule matched",
|
|
971
|
+
ignoredFromCard: "Ignored from its card, without a rule assessment",
|
|
972
|
+
observed: "Observe mode: would accept ({text})"
|
|
973
|
+
};
|
|
974
|
+
const said = (text) => ({
|
|
975
|
+
code: "said",
|
|
976
|
+
values: { text }
|
|
977
|
+
});
|
|
978
|
+
/** Formats reasons in English (prefixed by `triggerId` when present) for agent consumption. */
|
|
979
|
+
function reasonText(reasons) {
|
|
980
|
+
return [reasons ?? []].flat().map((reason) => {
|
|
981
|
+
const text = (REASONS[reason.code] ?? reason.code).replace(/\{(\w+)\}/g, (match, name) => reason.values?.[name] ?? match);
|
|
982
|
+
return reason.triggerId ? `${reason.triggerId}: ${text}` : text;
|
|
983
|
+
}).join("; ");
|
|
984
|
+
}
|
|
985
|
+
// src/core/evals.ts
|
|
986
|
+
/** Evals: the Thread-level assessments of queued Triggers, and the Decisions they end with. */
|
|
987
|
+
/** An outcome's reason: a code it carries, else the words its assessor or person wrote. */
|
|
988
|
+
const reasonOf = (reason) => [typeof reason === "string" ? said(reason) : reason];
|
|
989
|
+
const stronger = (a, b) => a === "explicit" || b === "explicit" ? "explicit" : "inferred";
|
|
990
|
+
/** How many times in a row an expired Eval queues its Triggers again before it is recorded unavailable. */
|
|
991
|
+
const REQUEUES = 2;
|
|
992
|
+
/**
|
|
993
|
+
* Evals runs the Evals of Threads: it batches a Thread's queued Triggers into one Eval, takes its strength, actor, and basis
|
|
994
|
+
* from the gate, asks the assessor, keeps its deadline through a pause, and records the Decision it ends with: accept, stop,
|
|
995
|
+
* ignore, or unavailable. It depends on Tickets to create the ticket an accept decides and to end the one a stop names; the
|
|
996
|
+
* Engine routes the main Session's decisions, people's replays, worker handbacks, and the pass's Eval work here.
|
|
997
|
+
*/
|
|
998
|
+
var Evals = class extends EnginePart {
|
|
999
|
+
tickets;
|
|
1000
|
+
constructor(options, tickets) {
|
|
1001
|
+
super(options);
|
|
1002
|
+
this.tickets = tickets;
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Expire a Thread's Eval past its deadline (see `expire`), unless processing is paused: then the Eval notes when the
|
|
1006
|
+
* processing pause began, and once processing resumes its deadline moves forward by the pause's length. An Eval whose
|
|
1007
|
+
* candidate has not reached the assessor's Session does not expire.
|
|
1008
|
+
*/
|
|
1009
|
+
due(thread, policy) {
|
|
1010
|
+
const evaluation = thread.evaluating;
|
|
1011
|
+
if (!evaluation || policy.paused && evaluation.pausedAt) return;
|
|
1012
|
+
const now = this.now();
|
|
1013
|
+
if (policy.paused) evaluation.pausedAt = now;
|
|
1014
|
+
else if (evaluation.pausedAt) {
|
|
1015
|
+
evaluation.deadline = new Date(Date.parse(evaluation.deadline) + Date.parse(now) - Date.parse(evaluation.pausedAt)).toISOString();
|
|
1016
|
+
delete evaluation.pausedAt;
|
|
1017
|
+
} else if (evaluation.delivered && evaluation.deadline <= now) {
|
|
1018
|
+
this.expire(thread);
|
|
1019
|
+
return;
|
|
1020
|
+
} else return;
|
|
1021
|
+
this.repo.threads.save(thread);
|
|
1022
|
+
}
|
|
1023
|
+
/** An Eval's candidate reached the assessor's Session: its deadline counts from now. */
|
|
1024
|
+
delivered(evalId, policy) {
|
|
1025
|
+
const thread = this.repo.threads.active().find((item) => item.evaluating?.id === evalId);
|
|
1026
|
+
if (!thread?.evaluating || thread.evaluating.delivered) return;
|
|
1027
|
+
const now = this.now();
|
|
1028
|
+
thread.evaluating.delivered = now;
|
|
1029
|
+
thread.evaluating.deadline = new Date(Date.parse(now) + policy.evalTimeoutMs).toISOString();
|
|
1030
|
+
this.repo.threads.save(thread);
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* An Eval past its deadline queues its Triggers again for a fresh Eval, up to `REQUEUES` times in a row, so a busy
|
|
1034
|
+
* assessor does not drop requests; after that it is recorded unavailable.
|
|
1035
|
+
*/
|
|
1036
|
+
expire(thread) {
|
|
1037
|
+
const expired = (thread.expired ?? 0) + 1;
|
|
1038
|
+
if (expired > REQUEUES) {
|
|
1039
|
+
this.finish(thread, thread.evaluating, {
|
|
1040
|
+
kind: "unavailable",
|
|
1041
|
+
reason: [{ code: "timeout" }]
|
|
1042
|
+
});
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
const { id, triggerIds } = thread.evaluating;
|
|
1046
|
+
delete thread.evaluating;
|
|
1047
|
+
thread.expired = expired;
|
|
1048
|
+
thread.pending = [...triggerIds, ...thread.pending.filter((item) => !triggerIds.includes(item))];
|
|
1049
|
+
this.repo.threads.save(thread);
|
|
1050
|
+
this.options.assessor.release?.(id);
|
|
1051
|
+
}
|
|
1052
|
+
/** Start one Eval of the Triggers queued on a Thread, judged by the gate, and ask the assessor for it. */
|
|
1053
|
+
start(threadKeyValue, policy) {
|
|
1054
|
+
const thread = this.repo.threads.get(threadKeyValue);
|
|
1055
|
+
const at = this.now();
|
|
1056
|
+
const delivered = (id) => {
|
|
1057
|
+
const trigger = this.repo.triggers.get(id);
|
|
1058
|
+
return !!trigger && this.owners(trigger).length > 0;
|
|
1059
|
+
};
|
|
1060
|
+
if (thread.pending.some(delivered)) {
|
|
1061
|
+
const followups = thread.pending.filter(delivered);
|
|
1062
|
+
thread.pending = thread.pending.filter((id) => !followups.includes(id));
|
|
1063
|
+
this.repo.threads.save(thread);
|
|
1064
|
+
for (const triggerId of followups) this.emit("trigger.followup", { triggerId });
|
|
1065
|
+
if (!thread.pending.length) return;
|
|
1066
|
+
}
|
|
1067
|
+
const accepted = this.accepted(thread.key);
|
|
1068
|
+
const started = thread.pending.filter((id) => accepted.has(id));
|
|
1069
|
+
const startedTicket = (id) => ({
|
|
1070
|
+
code: "startedTicket",
|
|
1071
|
+
triggerId: id,
|
|
1072
|
+
values: { ticket: accepted.get(id).ticketId }
|
|
1073
|
+
});
|
|
1074
|
+
if (started.length) this.ignore(thread, started, started.map(startedTicket), policy, at);
|
|
1075
|
+
const triggers = thread.pending.flatMap((id) => {
|
|
1076
|
+
const trigger = this.repo.triggers.get(id);
|
|
1077
|
+
return trigger ? [trigger] : [];
|
|
1078
|
+
});
|
|
1079
|
+
const tickets = this.ticketsOnThread(thread);
|
|
1080
|
+
const reasons = [];
|
|
1081
|
+
let strongest;
|
|
1082
|
+
for (const trigger of triggers) {
|
|
1083
|
+
const gate = policy.gate(trigger, thread, tickets, this.options.scope.scope(trigger));
|
|
1084
|
+
if (!gate.admissible) {
|
|
1085
|
+
reasons.push({
|
|
1086
|
+
code: gate.reason,
|
|
1087
|
+
triggerId: trigger.id
|
|
1088
|
+
});
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
const later = gate.strength === strongest?.strength && trigger.at >= strongest.trigger.at;
|
|
1092
|
+
if (!strongest || stronger(strongest.strength, gate.strength) !== strongest.strength || later) strongest = {
|
|
1093
|
+
trigger,
|
|
1094
|
+
strength: gate.strength,
|
|
1095
|
+
basis: gate.basis
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
if (!strongest) {
|
|
1099
|
+
if (thread.pending.length) this.ignore(thread, [...thread.pending], reasons.length ? reasons : [{ code: "noAdmissible" }], policy, at);
|
|
1100
|
+
this.repo.threads.save(thread);
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
const evalId = key("eval", thread.key, policy.version, at, ...thread.pending);
|
|
1104
|
+
const deadline = new Date(Date.parse(at) + policy.evalTimeoutMs).toISOString();
|
|
1105
|
+
const { strength, trigger: { actor }, basis } = strongest;
|
|
1106
|
+
thread.evaluating = {
|
|
1107
|
+
id: evalId,
|
|
1108
|
+
threadKey: thread.key,
|
|
1109
|
+
triggerIds: thread.pending,
|
|
1110
|
+
primary: strongest.trigger.id,
|
|
1111
|
+
strength,
|
|
1112
|
+
actor,
|
|
1113
|
+
basis,
|
|
1114
|
+
policyVersion: policy.version,
|
|
1115
|
+
startedAt: at,
|
|
1116
|
+
deadline
|
|
1117
|
+
};
|
|
1118
|
+
thread.pending = [];
|
|
1119
|
+
this.repo.threads.save(thread);
|
|
1120
|
+
for (const trigger of triggers) this.repo.triggers.saveDisposition(trigger.id, {
|
|
1121
|
+
...this.repo.triggers.disposition(trigger.id) ?? {
|
|
1122
|
+
fanout: [],
|
|
1123
|
+
at
|
|
1124
|
+
},
|
|
1125
|
+
evalId
|
|
1126
|
+
});
|
|
1127
|
+
this.emit("eval.started", {
|
|
1128
|
+
evalId,
|
|
1129
|
+
threadKey: thread.key,
|
|
1130
|
+
triggerIds: thread.evaluating.triggerIds,
|
|
1131
|
+
strength: strongest.strength
|
|
1132
|
+
});
|
|
1133
|
+
this.options.assessor.request(this.candidateOf(thread));
|
|
1134
|
+
}
|
|
1135
|
+
/** The candidate of the Eval that holds `triggerId`, or undefined while no Eval holds it. */
|
|
1136
|
+
candidate(triggerId) {
|
|
1137
|
+
const thread = this.holding(triggerId);
|
|
1138
|
+
return thread && this.candidateOf(thread);
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* Decide a Trigger: the Eval that holds it, or a direct Eval of it alone when none does.
|
|
1142
|
+
* @throws UserError when the Trigger is unknown or not admissible, `outcome.evalId` names an Eval that has finished, a
|
|
1143
|
+
* ticket's worker still decides the Trigger and the outcome is not a stop, or an inferred candidate is accepted outside `auto`
|
|
1144
|
+
* mode or without enabled matching rules.
|
|
1145
|
+
*/
|
|
1146
|
+
decide(triggerId, outcome) {
|
|
1147
|
+
const trigger = this.repo.triggers.get(triggerId);
|
|
1148
|
+
if (!trigger) throw new UserError("unknownTrigger");
|
|
1149
|
+
const held = this.holding(triggerId);
|
|
1150
|
+
if (outcome.evalId && held?.evaluating?.id !== outcome.evalId) throw new UserError("evalFinished", { eval: outcome.evalId });
|
|
1151
|
+
const earlier = outcome.kind === "accept" ? this.accepted(threadKey(trigger.threads[0])).get(triggerId) : void 0;
|
|
1152
|
+
if (earlier) {
|
|
1153
|
+
const others = held?.evaluating?.triggerIds.filter((id) => id !== triggerId) ?? [];
|
|
1154
|
+
if (held && others.length) this.reassess(held, {
|
|
1155
|
+
code: "acceptedBefore",
|
|
1156
|
+
values: { trigger: triggerId }
|
|
1157
|
+
}, [triggerId]);
|
|
1158
|
+
else if (held) this.finish(held, held.evaluating, {
|
|
1159
|
+
kind: "ignore",
|
|
1160
|
+
reason: [{
|
|
1161
|
+
code: "startedTicket",
|
|
1162
|
+
triggerId,
|
|
1163
|
+
values: { ticket: earlier.ticketId }
|
|
1164
|
+
}]
|
|
1165
|
+
});
|
|
1166
|
+
return earlier;
|
|
1167
|
+
}
|
|
1168
|
+
if (outcome.kind !== "stop") this.leftToWorkers(trigger);
|
|
1169
|
+
const thread = held ?? this.thread(trigger.threads[0]);
|
|
1170
|
+
const evaluation = held?.evaluating ?? this.directEval(thread, trigger, outcome.kind, outcome.kind === "stop" ? outcome.ticketId : void 0);
|
|
1171
|
+
if (outcome.kind === "accept" && evaluation.strength !== "explicit" && !this.policy().admitsInferred(outcome.rules ?? [])) throw new UserError("notExplicit");
|
|
1172
|
+
return this.decideEval(thread, evaluation, outcome);
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Queue a stored Trigger for a fresh Eval on its primary Thread and emit `trigger.requeued`; returns false while an Eval holds it.
|
|
1176
|
+
* @throws UserError when the Trigger is unknown.
|
|
1177
|
+
*/
|
|
1178
|
+
reevaluate(triggerId) {
|
|
1179
|
+
if (!this.requeue(triggerId)) return false;
|
|
1180
|
+
this.emit("trigger.requeued", { triggerId });
|
|
1181
|
+
return true;
|
|
1182
|
+
}
|
|
1183
|
+
/** Queue a Trigger for a fresh Eval on its primary Thread; false while an Eval holds it. */
|
|
1184
|
+
requeue(triggerId) {
|
|
1185
|
+
const trigger = this.repo.triggers.get(triggerId);
|
|
1186
|
+
if (!trigger) throw new UserError("unknownTrigger");
|
|
1187
|
+
if (this.holding(triggerId)) return false;
|
|
1188
|
+
this.queueForEval(trigger);
|
|
1189
|
+
const disposition = this.repo.triggers.disposition(triggerId) ?? {
|
|
1190
|
+
fanout: [],
|
|
1191
|
+
at: this.now()
|
|
1192
|
+
};
|
|
1193
|
+
this.repo.triggers.saveDisposition(triggerId, {
|
|
1194
|
+
...disposition,
|
|
1195
|
+
requeued: true
|
|
1196
|
+
});
|
|
1197
|
+
return true;
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* Record that a ticket's Executor hands back a Trigger that reached it as beyond the ticket, and queue it for a fresh Eval
|
|
1201
|
+
* when the ticket decided it and no other ticket still does (see `handBack`): the gate judges it as any message on its
|
|
1202
|
+
* Thread, and its candidate carries the reasons, so no requeue notice comes before it. The ticket keeps its Subscription,
|
|
1203
|
+
* and hands a Trigger back once.
|
|
1204
|
+
* @returns whether it was queued: false while another ticket decides it, and for one the ticket did not decide.
|
|
1205
|
+
*/
|
|
1206
|
+
handback(ticketId, triggerId, reason) {
|
|
1207
|
+
if (!this.require(ticketId).inputs.some((input) => input.kind === "trigger" && input.triggerId === triggerId)) throw new UserError("notReached");
|
|
1208
|
+
if (this.repo.triggers.disposition(triggerId)?.handbacks?.some((item) => item.ticketId === ticketId)) throw new UserError("handedBack");
|
|
1209
|
+
return this.handBack(ticketId, this.repo.triggers.get(triggerId), reason);
|
|
1210
|
+
}
|
|
1211
|
+
/**
|
|
1212
|
+
* Marks an `unavailable` Decision dismissed so the overview lists it no more.
|
|
1213
|
+
* @throws UserError when the Decision is unknown or not `unavailable`.
|
|
1214
|
+
*/
|
|
1215
|
+
dismiss(decisionId) {
|
|
1216
|
+
const decision = this.repo.decisions.get(decisionId);
|
|
1217
|
+
if (decision?.kind !== "unavailable") throw new UserError("unknownProblem");
|
|
1218
|
+
decision.dismissed = true;
|
|
1219
|
+
this.repo.decisions.save(decision);
|
|
1220
|
+
return decision;
|
|
1221
|
+
}
|
|
1222
|
+
/** Take a Trigger out of its Thread's queue because it was routed by hand. */
|
|
1223
|
+
withdraw(trigger) {
|
|
1224
|
+
const thread = this.repo.threads.get(threadKey(trigger.threads[0]));
|
|
1225
|
+
if (!thread?.pending.includes(trigger.id)) return;
|
|
1226
|
+
thread.pending = thread.pending.filter((id) => id !== trigger.id);
|
|
1227
|
+
this.repo.threads.save(thread);
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* End the Eval that holds a Trigger routed to a ticket, since the ticket has it now: one that holds other Triggers too
|
|
1231
|
+
* queues them again for a fresh Eval without it.
|
|
1232
|
+
*/
|
|
1233
|
+
routed(triggerId, ticketId) {
|
|
1234
|
+
const held = this.holding(triggerId);
|
|
1235
|
+
const reason = {
|
|
1236
|
+
code: "routed",
|
|
1237
|
+
values: { ticket: ticketId }
|
|
1238
|
+
};
|
|
1239
|
+
if (held?.evaluating?.triggerIds.length === 1) this.finish(held, held.evaluating, {
|
|
1240
|
+
kind: "ignore",
|
|
1241
|
+
reason: [reason]
|
|
1242
|
+
});
|
|
1243
|
+
else if (held) this.reassess(held, {
|
|
1244
|
+
...reason,
|
|
1245
|
+
triggerId
|
|
1246
|
+
}, [triggerId]);
|
|
1247
|
+
}
|
|
1248
|
+
/** Start the Evals in progress again under the new Policy version, and say that it changed. */
|
|
1249
|
+
policyChanged(from, to) {
|
|
1250
|
+
for (const thread of this.repo.threads.active()) if (thread.evaluating) this.reassess(thread, { code: "policyChanged" });
|
|
1251
|
+
this.emit("policy.changed", {
|
|
1252
|
+
from,
|
|
1253
|
+
to
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
/** End a Thread's Eval as unavailable for `reason` and queue its Triggers, except `without`, for a new Eval ahead of the others. */
|
|
1257
|
+
reassess(thread, reason, without = []) {
|
|
1258
|
+
const ids = thread.evaluating.triggerIds.filter((id) => !without.includes(id));
|
|
1259
|
+
const decision = this.finish(thread, thread.evaluating, {
|
|
1260
|
+
kind: "unavailable",
|
|
1261
|
+
reason: [reason]
|
|
1262
|
+
});
|
|
1263
|
+
const current = this.repo.threads.get(thread.key);
|
|
1264
|
+
current.pending = [...ids, ...current.pending.filter((id) => !ids.includes(id))];
|
|
1265
|
+
this.repo.threads.save(current);
|
|
1266
|
+
return decision;
|
|
1267
|
+
}
|
|
1268
|
+
/** The Thread whose Eval holds a Trigger: an Eval runs on the primary Thread of each Trigger it holds. */
|
|
1269
|
+
holding(triggerId) {
|
|
1270
|
+
const trigger = this.repo.triggers.get(triggerId);
|
|
1271
|
+
const thread = trigger && this.repo.threads.get(threadKey(trigger.threads[0]));
|
|
1272
|
+
return thread?.evaluating?.triggerIds.includes(triggerId) ? thread : void 0;
|
|
1273
|
+
}
|
|
1274
|
+
candidateOf(thread) {
|
|
1275
|
+
const evaluation = thread.evaluating;
|
|
1276
|
+
const triggers = evaluation.triggerIds.flatMap((id) => {
|
|
1277
|
+
const trigger = this.repo.triggers.get(id);
|
|
1278
|
+
return trigger ? [trigger] : [];
|
|
1279
|
+
});
|
|
1280
|
+
const { id: evalId, strength, policyVersion } = evaluation;
|
|
1281
|
+
return {
|
|
1282
|
+
evalId,
|
|
1283
|
+
thread,
|
|
1284
|
+
triggers,
|
|
1285
|
+
strength,
|
|
1286
|
+
policyVersion,
|
|
1287
|
+
tickets: this.ticketsOnThread(thread)
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* Record that the queued Triggers `ids` of a Thread start no Eval, for `reason`, and take them out of its queue. Its id
|
|
1292
|
+
* differs from an Eval's, so it never replaces the Decision of an earlier Eval of the same Triggers.
|
|
1293
|
+
*/
|
|
1294
|
+
ignore(thread, ids, reason, policy, at) {
|
|
1295
|
+
const evaluation = {
|
|
1296
|
+
id: key("eval", thread.key, "ignored", policy.version, at, ...ids),
|
|
1297
|
+
threadKey: thread.key,
|
|
1298
|
+
triggerIds: ids,
|
|
1299
|
+
strength: "inferred",
|
|
1300
|
+
actor: {
|
|
1301
|
+
source: thread.ref.source,
|
|
1302
|
+
id: ""
|
|
1303
|
+
},
|
|
1304
|
+
basis: { via: "followup" },
|
|
1305
|
+
policyVersion: policy.version,
|
|
1306
|
+
startedAt: at,
|
|
1307
|
+
deadline: at
|
|
1308
|
+
};
|
|
1309
|
+
this.record(thread, evaluation, {
|
|
1310
|
+
kind: "ignore",
|
|
1311
|
+
reason
|
|
1312
|
+
});
|
|
1313
|
+
thread.pending = thread.pending.filter((id) => !ids.includes(id));
|
|
1314
|
+
delete thread.expired;
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* The accept Decisions of the Triggers whose primary Thread is `threadKey`, by Trigger: what each one started. An Eval and
|
|
1318
|
+
* its Decision run on its Triggers' primary Thread, so the Thread's Decisions, read by their index, hold them all.
|
|
1319
|
+
*/
|
|
1320
|
+
accepted(threadKey) {
|
|
1321
|
+
const accepted = /* @__PURE__ */ new Map();
|
|
1322
|
+
for (const decision of this.repo.decisions.byThread(threadKey)) {
|
|
1323
|
+
if (decision.kind !== "accept" || !decision.ticketId) continue;
|
|
1324
|
+
for (const id of decision.triggerIds) if (!accepted.has(id)) accepted.set(id, decision);
|
|
1325
|
+
}
|
|
1326
|
+
return accepted;
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* A gate-only Eval of one Trigger, for an outcome decided without a queued Eval, such as on a follow-up that reached a
|
|
1330
|
+
* ticket. It is decided at once, beside an Eval its Thread may have in progress, and takes the Trigger out of the queue.
|
|
1331
|
+
* Its id names the outcome's kind, so a stop and an accept of one message at the same moment are two Decisions.
|
|
1332
|
+
*/
|
|
1333
|
+
directEval(thread, trigger, kind, ticketId) {
|
|
1334
|
+
const policy = this.policy();
|
|
1335
|
+
const gate = policy.gate(trigger, thread, this.ticketsOnThread(thread), this.options.scope.scope(trigger));
|
|
1336
|
+
if (!gate.admissible) throw new UserError("notAdmissible", { reason: gate.reason });
|
|
1337
|
+
const at = this.now();
|
|
1338
|
+
if (thread.pending.includes(trigger.id)) {
|
|
1339
|
+
thread.pending = thread.pending.filter((id) => id !== trigger.id);
|
|
1340
|
+
this.repo.threads.save(thread);
|
|
1341
|
+
}
|
|
1342
|
+
return {
|
|
1343
|
+
id: key("eval", thread.key, "direct", trigger.id, kind, ...ticketId ? [ticketId] : [], at),
|
|
1344
|
+
threadKey: thread.key,
|
|
1345
|
+
triggerIds: [trigger.id],
|
|
1346
|
+
primary: trigger.id,
|
|
1347
|
+
strength: gate.strength,
|
|
1348
|
+
actor: trigger.actor,
|
|
1349
|
+
basis: gate.basis,
|
|
1350
|
+
policyVersion: policy.version,
|
|
1351
|
+
startedAt: at,
|
|
1352
|
+
deadline: at
|
|
1353
|
+
};
|
|
1354
|
+
}
|
|
1355
|
+
/** Apply an outcome to an Eval of a Thread: the one in progress, or a gate-only one. */
|
|
1356
|
+
decideEval(thread, evaluation, outcome) {
|
|
1357
|
+
const audit = outcome.audit ? { audit: outcome.audit } : {};
|
|
1358
|
+
if (this.policy().version !== evaluation.policyVersion) {
|
|
1359
|
+
if (thread.evaluating?.id === evaluation.id) return this.reassess(thread, { code: "policyChanged" });
|
|
1360
|
+
return this.finish(thread, evaluation, {
|
|
1361
|
+
kind: "unavailable",
|
|
1362
|
+
reason: [{ code: "policyChanged" }],
|
|
1363
|
+
...audit
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
const unassessed = outcome.kind === "ignore" && evaluation.strength !== "explicit" && !outcome.audit ? [{ code: "ignoredFromCard" }] : [];
|
|
1367
|
+
if (outcome.kind === "ignore" || outcome.kind === "unavailable") return this.finish(thread, evaluation, {
|
|
1368
|
+
kind: outcome.kind,
|
|
1369
|
+
reason: [...unassessed, ...reasonOf(outcome.reason)],
|
|
1370
|
+
...audit
|
|
1371
|
+
});
|
|
1372
|
+
if (outcome.kind === "stop") {
|
|
1373
|
+
const ticket = this.repo.tickets.get(outcome.ticketId);
|
|
1374
|
+
if (!ticket || !liveTicket(ticket)) return this.finish(thread, evaluation, {
|
|
1375
|
+
kind: "ignore",
|
|
1376
|
+
reason: [{ code: "stopUnknown" }],
|
|
1377
|
+
...audit
|
|
1378
|
+
});
|
|
1379
|
+
if (evaluation.strength !== "explicit") return this.finish(thread, evaluation, {
|
|
1380
|
+
kind: "ignore",
|
|
1381
|
+
reason: [{ code: "stopNotExplicit" }],
|
|
1382
|
+
...audit
|
|
1383
|
+
});
|
|
1384
|
+
const decision = this.finish(thread, evaluation, {
|
|
1385
|
+
kind: "stop",
|
|
1386
|
+
reason: reasonOf(outcome.reason),
|
|
1387
|
+
ticketId: ticket.id,
|
|
1388
|
+
...audit
|
|
1389
|
+
});
|
|
1390
|
+
this.tickets.end(ticket.id, "human", "stopped", this.now(), typeof outcome.reason === "string" ? outcome.reason : void 0);
|
|
1391
|
+
return decision;
|
|
1392
|
+
}
|
|
1393
|
+
return this.accept(thread, evaluation, outcome);
|
|
1394
|
+
}
|
|
1395
|
+
/** Record an accept with the Mandate the Eval gives, and have Tickets create its ticket. */
|
|
1396
|
+
accept(thread, evaluation, outcome) {
|
|
1397
|
+
const at = this.now();
|
|
1398
|
+
const basis = {
|
|
1399
|
+
...evaluation.basis,
|
|
1400
|
+
...outcome.rules ? { rules: outcome.rules } : {}
|
|
1401
|
+
};
|
|
1402
|
+
const { strength, policyVersion, actor } = evaluation;
|
|
1403
|
+
const mandate = {
|
|
1404
|
+
strength,
|
|
1405
|
+
policyVersion,
|
|
1406
|
+
basis,
|
|
1407
|
+
actor,
|
|
1408
|
+
scope: outcome.scope
|
|
1409
|
+
};
|
|
1410
|
+
const ticketId = key("ticket", evaluation.id);
|
|
1411
|
+
const audit = outcome.audit ? { audit: outcome.audit } : {};
|
|
1412
|
+
const decision = this.finish(thread, evaluation, {
|
|
1413
|
+
kind: "accept",
|
|
1414
|
+
reason: reasonOf(outcome.reason),
|
|
1415
|
+
...audit,
|
|
1416
|
+
mandate,
|
|
1417
|
+
ticketId
|
|
1418
|
+
});
|
|
1419
|
+
this.tickets.create(ticketId, decision.id, mandate, evaluation, outcome, at);
|
|
1420
|
+
return decision;
|
|
1421
|
+
}
|
|
1422
|
+
/** Record an Eval's Decision; the Thread's own Eval ends with it, while a gate-only one leaves the Thread's Eval going. */
|
|
1423
|
+
finish(thread, evaluation, outcome) {
|
|
1424
|
+
const decision = this.record(thread, evaluation, outcome);
|
|
1425
|
+
if (thread.evaluating?.id !== evaluation.id) return decision;
|
|
1426
|
+
delete thread.evaluating;
|
|
1427
|
+
delete thread.expired;
|
|
1428
|
+
this.repo.threads.save(thread);
|
|
1429
|
+
this.options.assessor.release?.(evaluation.id);
|
|
1430
|
+
return decision;
|
|
1431
|
+
}
|
|
1432
|
+
record(thread, evaluation, outcome) {
|
|
1433
|
+
const at = this.now();
|
|
1434
|
+
const decision = {
|
|
1435
|
+
id: key("decision", evaluation.id),
|
|
1436
|
+
evalId: evaluation.id,
|
|
1437
|
+
threadKey: thread.key,
|
|
1438
|
+
triggerIds: evaluation.triggerIds,
|
|
1439
|
+
policyVersion: evaluation.policyVersion,
|
|
1440
|
+
at,
|
|
1441
|
+
kind: outcome.kind,
|
|
1442
|
+
reason: outcome.reason,
|
|
1443
|
+
strength: evaluation.strength,
|
|
1444
|
+
...outcome.ticketId ? { ticketId: outcome.ticketId } : {},
|
|
1445
|
+
...outcome.mandate ? { mandate: outcome.mandate } : {},
|
|
1446
|
+
...outcome.audit ? { audit: outcome.audit } : {}
|
|
1447
|
+
};
|
|
1448
|
+
this.repo.decisions.save(decision);
|
|
1449
|
+
for (const id of evaluation.triggerIds) {
|
|
1450
|
+
const disposition = this.repo.triggers.disposition(id) ?? {
|
|
1451
|
+
fanout: [],
|
|
1452
|
+
at
|
|
1453
|
+
};
|
|
1454
|
+
this.repo.triggers.saveDisposition(id, {
|
|
1455
|
+
...disposition,
|
|
1456
|
+
evalId: evaluation.id,
|
|
1457
|
+
decisionId: decision.id
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
this.emit("decision.recorded", {
|
|
1461
|
+
decisionId: decision.id,
|
|
1462
|
+
kind: decision.kind,
|
|
1463
|
+
threadKey: thread.key
|
|
1464
|
+
});
|
|
1465
|
+
return decision;
|
|
1466
|
+
}
|
|
1467
|
+
};
|
|
1468
|
+
// src/core/intake.ts
|
|
1469
|
+
/** Trigger ingestion, thread correlation, subscription fan-out, and evaluation queuing. */
|
|
1470
|
+
/**
|
|
1471
|
+
* Ingests incoming triggers from Sources, deduplicating and filtering them against SourceScope before recording thread correlations.
|
|
1472
|
+
* Fans listened triggers out to subscribed tickets via Tickets and queues for Eval, on its primary thread, every trigger no
|
|
1473
|
+
* ticket's worker decides (see `followupOwners`).
|
|
1474
|
+
* Engine delegates trigger reception to this part.
|
|
1475
|
+
*/
|
|
1476
|
+
var Intake = class extends EnginePart {
|
|
1477
|
+
tickets;
|
|
1478
|
+
constructor(options, tickets) {
|
|
1479
|
+
super(options);
|
|
1480
|
+
this.tickets = tickets;
|
|
1481
|
+
}
|
|
1482
|
+
receive(received) {
|
|
1483
|
+
const trigger = {
|
|
1484
|
+
...received,
|
|
1485
|
+
at: isoTime(received.at)
|
|
1486
|
+
};
|
|
1487
|
+
if (!trigger.threads.length) throw new Error("A trigger must belong to at least one thread");
|
|
1488
|
+
if (this.repo.triggers.get(trigger.id)) return "duplicate";
|
|
1489
|
+
const at = this.now();
|
|
1490
|
+
const filter = this.options.scope.scope(trigger);
|
|
1491
|
+
if (!filter.listened) {
|
|
1492
|
+
this.repo.triggers.save(trigger);
|
|
1493
|
+
this.repo.triggers.saveDisposition(trigger.id, {
|
|
1494
|
+
filtered: { code: filter.reason },
|
|
1495
|
+
fanout: [],
|
|
1496
|
+
at
|
|
1497
|
+
});
|
|
1498
|
+
return "filtered";
|
|
1499
|
+
}
|
|
1500
|
+
this.repo.triggers.save(trigger);
|
|
1501
|
+
const keys = trigger.threads.map(threadKey);
|
|
1502
|
+
const reached = /* @__PURE__ */ new Map();
|
|
1503
|
+
for (const ref of trigger.threads) {
|
|
1504
|
+
const thread = this.thread(ref);
|
|
1505
|
+
if (!thread.lastAt || trigger.at > thread.lastAt) thread.lastAt = trigger.at;
|
|
1506
|
+
thread.correlated = [.../* @__PURE__ */ new Set([...thread.correlated, ...keys.filter((other) => other !== thread.key)])];
|
|
1507
|
+
for (const ticketId of thread.subscriptions) {
|
|
1508
|
+
const ticket = this.repo.tickets.get(ticketId);
|
|
1509
|
+
const followed = !!thread.context?.includes(ticketId);
|
|
1510
|
+
const resumes = trigger.human && ticket?.ended?.by !== "human" && !followed;
|
|
1511
|
+
if (!ticket || !liveTicket(ticket) && !resumes) continue;
|
|
1512
|
+
reached.set(ticketId, {
|
|
1513
|
+
ticket,
|
|
1514
|
+
context: followed && (reached.get(ticketId)?.context ?? true)
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
this.repo.threads.save(thread);
|
|
1518
|
+
}
|
|
1519
|
+
for (const [ticketId, { ticket, context: followed }] of reached) this.tickets.addInput(ticket, {
|
|
1520
|
+
id: key("input", ticketId, "trigger", trigger.id),
|
|
1521
|
+
kind: "trigger",
|
|
1522
|
+
triggerId: trigger.id,
|
|
1523
|
+
at,
|
|
1524
|
+
...trigger.human ? { human: true } : {},
|
|
1525
|
+
...followed ? { context: true } : {}
|
|
1526
|
+
});
|
|
1527
|
+
const fanout = [...reached.keys()], context = fanout.filter((id) => reached.get(id).context);
|
|
1528
|
+
const disposition = {
|
|
1529
|
+
fanout,
|
|
1530
|
+
...context.length ? { context } : {},
|
|
1531
|
+
at
|
|
1532
|
+
};
|
|
1533
|
+
this.repo.triggers.saveDisposition(trigger.id, disposition);
|
|
1534
|
+
if (!this.owners(trigger).length) this.queueForEval(trigger);
|
|
1535
|
+
for (const ticketId of fanout) this.tickets.wake(ticketId);
|
|
1536
|
+
this.emit("trigger.received", {
|
|
1537
|
+
triggerId: trigger.id,
|
|
1538
|
+
threads: trigger.threads.map(threadKey)
|
|
1539
|
+
});
|
|
1540
|
+
return "stored";
|
|
1541
|
+
}
|
|
1542
|
+
};
|
|
1543
|
+
// src/core/replies.ts
|
|
1544
|
+
/** The Engine's messages to Channels, each by the rule that allows it. */
|
|
1545
|
+
/**
|
|
1546
|
+
* Replies writes the Engine's messages to Channels through the Outbox port: an acknowledgement, the answer to a person's
|
|
1547
|
+
* question, a ticket's result, and its question for a person, each only when its rule allows it, under a deterministic id
|
|
1548
|
+
* that keeps it from going out twice (idempotent). The Engine routes `reply` here; Tickets asks it for the acknowledgement
|
|
1549
|
+
* an accept carries, and Assignments asks it to withdraw a question a report replaced.
|
|
1550
|
+
*/
|
|
1551
|
+
var Replies = class extends EnginePart {
|
|
1552
|
+
/**
|
|
1553
|
+
* Queue a message for the Channel its purpose names: an acknowledgement or an answer goes where that person's message was
|
|
1554
|
+
* written, attention where the message that raised the question was (or to the ticket's starting conversation), and a
|
|
1555
|
+
* result to the conversation where the ticket started (`result` is allowed only for a ticket in `ready`, `completed`,
|
|
1556
|
+
* `merged`, or `dropped`). Each message is queued at most once (idempotent). An acknowledgement, even one already queued,
|
|
1557
|
+
* records that the ticket's worker took the message up.
|
|
1558
|
+
* @throws UserError when the ticket or trigger is unknown or the purpose's rule refuses it, such as a result of a ticket
|
|
1559
|
+
* that is not ready, completed, merged, or dropped.
|
|
1560
|
+
*/
|
|
1561
|
+
reply(request) {
|
|
1562
|
+
return request.purpose === "acknowledgement" ? this.acknowledge(request) : this.answer(request);
|
|
1563
|
+
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Queue the acknowledgement an accept carries where the message that started the ticket was written, if it has a Channel
|
|
1566
|
+
* and a person wrote it.
|
|
1567
|
+
*/
|
|
1568
|
+
acknowledgeAccepted(ticketId, trigger, text) {
|
|
1569
|
+
if (trigger.channel && trigger.human) this.options.outbox.send({
|
|
1570
|
+
id: key("ack", trigger.id),
|
|
1571
|
+
channel: trigger.channel,
|
|
1572
|
+
text,
|
|
1573
|
+
kind: "acknowledgement",
|
|
1574
|
+
ticketId
|
|
1575
|
+
});
|
|
1576
|
+
}
|
|
1577
|
+
/** Withdraw a ticket's question for a person from the outbox, unless it went out already. */
|
|
1578
|
+
withdrawAttention(attentionId) {
|
|
1579
|
+
this.options.outbox.withdraw(key("attention-reply", attentionId));
|
|
1580
|
+
}
|
|
1581
|
+
acknowledge(request) {
|
|
1582
|
+
const ticket = this.require(request.ticketId);
|
|
1583
|
+
if (!liveTicket(ticket)) throw new UserError("ackEnded");
|
|
1584
|
+
const trigger = this.repo.triggers.get(request.triggerId);
|
|
1585
|
+
if (!trigger) throw new UserError("unknownTrigger");
|
|
1586
|
+
if (!this.reaches(ticket, trigger, false)) throw new UserError("notReached");
|
|
1587
|
+
if (!trigger.channel) throw new UserError("ackNoChannel");
|
|
1588
|
+
const id = key("ack", trigger.id);
|
|
1589
|
+
const existing = this.options.outbox.status(id);
|
|
1590
|
+
if (!existing && !trigger.human) throw new UserError("ackNotPerson");
|
|
1591
|
+
if (!existing) this.options.outbox.send({
|
|
1592
|
+
id,
|
|
1593
|
+
channel: trigger.channel,
|
|
1594
|
+
text: request.text,
|
|
1595
|
+
kind: "acknowledgement",
|
|
1596
|
+
ticketId: ticket.id
|
|
1597
|
+
});
|
|
1598
|
+
this.takeUp(ticket.id, trigger.id);
|
|
1599
|
+
return {
|
|
1600
|
+
id,
|
|
1601
|
+
status: this.options.outbox.status(id) ?? "pending",
|
|
1602
|
+
reused: existing !== void 0
|
|
1603
|
+
};
|
|
1604
|
+
}
|
|
1605
|
+
answer(request) {
|
|
1606
|
+
const trigger = request.triggerId ? this.repo.triggers.get(request.triggerId) : void 0;
|
|
1607
|
+
if (request.triggerId && !trigger) throw new UserError("unknownTrigger");
|
|
1608
|
+
const ticket = request.ticketId ? this.require(request.ticketId) : trigger ? this.repo.tickets.list().find((item) => this.reaches(item, trigger)) : void 0;
|
|
1609
|
+
if (request.purpose === "result") {
|
|
1610
|
+
const outcome = ticket && ticketOutcome(ticket);
|
|
1611
|
+
const reported = !!ticket && liveTicket(ticket) && latestAssignment(ticket)?.report?.state === "ready";
|
|
1612
|
+
if (!ticket || !(outcome === "merged" || outcome === "completed" || outcome === "dropped" || reported)) throw new UserError("notReady");
|
|
1613
|
+
}
|
|
1614
|
+
const attention = request.purpose === "attention" ? ticket?.attention : void 0;
|
|
1615
|
+
if (request.purpose === "attention" && (!attention || attention.question !== request.question)) throw new UserError("notAttention");
|
|
1616
|
+
if (request.purpose === "answer" && !trigger?.human) throw new UserError("notQuestion");
|
|
1617
|
+
const id = attention ? key("attention-reply", attention.id) : key("reply", trigger?.id ?? ticket?.id ?? "", request.text);
|
|
1618
|
+
const existing = this.options.outbox.status(id);
|
|
1619
|
+
const ready = !ticket || !trigger || ticket.answers?.includes(trigger.id);
|
|
1620
|
+
if (request.purpose === "answer" && !ready && !existing) throw new UserError("noAnswer");
|
|
1621
|
+
const asker = attention?.triggerId ? this.repo.triggers.get(attention.triggerId) : void 0;
|
|
1622
|
+
const channel = request.purpose === "answer" ? trigger.channel : asker?.channel ?? (ticket ? this.sourceChannel(ticket) : void 0);
|
|
1623
|
+
if (!channel) throw new UserError("noChannel");
|
|
1624
|
+
this.options.outbox.send({
|
|
1625
|
+
id,
|
|
1626
|
+
channel,
|
|
1627
|
+
text: request.text,
|
|
1628
|
+
kind: "reply",
|
|
1629
|
+
...ticket ? { ticketId: ticket.id } : {}
|
|
1630
|
+
});
|
|
1631
|
+
if (request.purpose === "answer" && ticket && trigger && ticket.answers?.includes(trigger.id)) {
|
|
1632
|
+
ticket.answers = ticket.answers.filter((item) => item !== trigger.id);
|
|
1633
|
+
this.repo.tickets.save(ticket);
|
|
1634
|
+
}
|
|
1635
|
+
return {
|
|
1636
|
+
id,
|
|
1637
|
+
status: this.options.outbox.status(id) ?? "pending",
|
|
1638
|
+
reused: existing !== void 0
|
|
1639
|
+
};
|
|
1640
|
+
}
|
|
1641
|
+
/** The conversation a ticket started in: its origin Trigger's Channel, else its first Channel. */
|
|
1642
|
+
sourceChannel(ticket) {
|
|
1643
|
+
return this.source(ticket)?.channel ?? ticket.channels[0];
|
|
1644
|
+
}
|
|
1645
|
+
};
|
|
1646
|
+
// src/core/engine.ts
|
|
1647
|
+
/** The domain Engine: the single entry point of the core, and the role interfaces its callers receive. */
|
|
1648
|
+
/**
|
|
1649
|
+
* Single transactional entry point for mutating Triggers, Threads, Decisions, Tickets, and Assignments.
|
|
1650
|
+
* Coordinates Intake, Evals, Tickets, Assignments, and Replies inside synchronous repository transactions while queuing side
|
|
1651
|
+
* effects through ports. Callers receive role-scoped `Pick` interfaces rather than the full engine.
|
|
1652
|
+
*/
|
|
1653
|
+
var Engine = class {
|
|
1654
|
+
options;
|
|
1655
|
+
repo;
|
|
1656
|
+
replies;
|
|
1657
|
+
tickets;
|
|
1658
|
+
assignments;
|
|
1659
|
+
evals;
|
|
1660
|
+
intake;
|
|
1661
|
+
constructor(options) {
|
|
1662
|
+
this.options = options;
|
|
1663
|
+
this.repo = options.repo;
|
|
1664
|
+
this.replies = new Replies(options);
|
|
1665
|
+
this.tickets = new Tickets(options, this.replies);
|
|
1666
|
+
this.assignments = new Assignments(options, this.tickets, this.replies);
|
|
1667
|
+
this.evals = new Evals(options, this.tickets);
|
|
1668
|
+
this.intake = new Intake(options, this.tickets);
|
|
1669
|
+
}
|
|
1670
|
+
/**
|
|
1671
|
+
* A Source's request to take in a Trigger: store it once, fan it out to the tickets that subscribe to its Threads (to an
|
|
1672
|
+
* ended one only a person's message, which resumes it at once unless processing is paused, and to none a person stopped),
|
|
1673
|
+
* and queue it for Eval on its primary Thread unless a ticket's worker decides it (see `followupOwners`).
|
|
1674
|
+
* Triggers that arrive while an Eval of that Thread runs wait together for the next one.
|
|
1675
|
+
*/
|
|
1676
|
+
receive(trigger) {
|
|
1677
|
+
return this.repo.atomic(() => this.intake.receive(trigger));
|
|
1678
|
+
}
|
|
1679
|
+
/**
|
|
1680
|
+
* A Source's request to make an open ticket follow one of its Threads, such as a pull request's, `own` when the ticket
|
|
1681
|
+
* opened it: the ticket subscribes to it, and a ready report ends it only once `followsDone` holds (see `Tickets.followsDone`).
|
|
1682
|
+
* @throws UserError when the ticket is unknown or has ended.
|
|
1683
|
+
*/
|
|
1684
|
+
bindThread(ticketId, thread, own) {
|
|
1685
|
+
return this.repo.atomic(() => this.tickets.bind(ticketId, thread, own));
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* A Source's fact that a Thread closed, such as its pull request's merge, at the time it happened. An open ticket that
|
|
1689
|
+
* follows it ends once it is done with the Threads it follows, unless work resumed since the close has not finished, or
|
|
1690
|
+
* its worker took up a person's message the ticket decides after its latest report.
|
|
1691
|
+
*/
|
|
1692
|
+
threadClosed(thread, outcome, at) {
|
|
1693
|
+
this.repo.atomic(() => {
|
|
1694
|
+
this.tickets.threadClosed(thread, outcome, isoTime(at));
|
|
1695
|
+
});
|
|
1696
|
+
}
|
|
1697
|
+
/**
|
|
1698
|
+
* Requeues overdue Evals up to `REQUEUES` times before recording `unavailable` (undelivered Evals never expire), starts the
|
|
1699
|
+
* Evals of Threads whose queued Triggers wait, and resumes ended tickets a person's message reached while processing was
|
|
1700
|
+
* paused. While processing is paused, nothing expires: each Eval in progress notes when the pause began, and its deadline
|
|
1701
|
+
* moves forward by the pause's length once processing resumes. Each Eval and each ticket update takes one transaction.
|
|
1702
|
+
*/
|
|
1703
|
+
evaluateDue() {
|
|
1704
|
+
const policy = this.options.policy();
|
|
1705
|
+
for (const thread of this.repo.threads.active()) if (thread.evaluating) this.repo.atomic(() => {
|
|
1706
|
+
this.evals.due(thread, policy);
|
|
1707
|
+
});
|
|
1708
|
+
if (policy.paused) return;
|
|
1709
|
+
for (const ticket of this.repo.tickets.active()) if (!liveTicket(ticket) && ticket.undelivered.length) this.repo.atomic(() => {
|
|
1710
|
+
this.tickets.wake(ticket.id);
|
|
1711
|
+
});
|
|
1712
|
+
for (const thread of this.repo.threads.active()) if (thread.pending.length && !thread.evaluating) this.repo.atomic(() => {
|
|
1713
|
+
this.evals.start(thread.key, policy);
|
|
1714
|
+
});
|
|
1715
|
+
}
|
|
1716
|
+
/** The candidate of the Eval that holds a Trigger, as its assessor sees it; undefined while no Eval holds it. */
|
|
1717
|
+
candidate(triggerId) {
|
|
1718
|
+
return this.evals.candidate(triggerId);
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* Decide a Trigger: the Eval that holds it, or a direct Eval of it alone when none does, such as a person's explicit
|
|
1722
|
+
* request the main Session routes. A proactive candidate is accepted only in `auto` mode with enabled rules its assessment
|
|
1723
|
+
* matched, and a Trigger that already started a ticket returns that ticket's Decision. An invalid stop is recorded as
|
|
1724
|
+
* `ignore`; one judged under an older Policy as `unavailable`.
|
|
1725
|
+
* @throws UserError when the Trigger is unknown or not admissible, `outcome.evalId` names an Eval that has finished, a
|
|
1726
|
+
* ticket's worker still decides the Trigger and the outcome is not a stop, or an inferred candidate is accepted outside `auto`
|
|
1727
|
+
* mode or without enabled matching rules.
|
|
1728
|
+
*/
|
|
1729
|
+
decide(triggerId, outcome) {
|
|
1730
|
+
return this.repo.atomic(() => this.evals.decide(triggerId, outcome));
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* Attach a Trigger to a ticket that the message points at: the ticket follows the Trigger's Threads and receives it as an
|
|
1734
|
+
* Input with the routing note, and the Eval that holds the Trigger ends, since the ticket has it now; the other Triggers of
|
|
1735
|
+
* its batch wait for a fresh Eval. A note for an Input the worker already received goes out as a new Input, and so does a
|
|
1736
|
+
* message the ticket let go, read for context only, or had before it ended. An ended ticket resumes under its Mandate, at
|
|
1737
|
+
* once unless processing is paused.
|
|
1738
|
+
* @throws UserError for a ticket a person stopped, which withdrew its Mandate, or one whose Mandate the Policy no longer holds.
|
|
1739
|
+
*/
|
|
1740
|
+
attach(ticketId, triggerId, note) {
|
|
1741
|
+
return this.repo.atomic(() => {
|
|
1742
|
+
if (this.repo.triggers.disposition(triggerId)?.handbacks?.some((item) => item.ticketId === ticketId)) throw new UserError("handedBackHere");
|
|
1743
|
+
const trigger = this.tickets.attachable(ticketId, triggerId);
|
|
1744
|
+
this.evals.withdraw(trigger);
|
|
1745
|
+
this.tickets.attach(ticketId, trigger, note);
|
|
1746
|
+
this.evals.routed(triggerId, ticketId);
|
|
1747
|
+
this.tickets.wake(ticketId);
|
|
1748
|
+
return this.repo.tickets.get(ticketId);
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
/**
|
|
1752
|
+
* Ask a running worker that waits in `waiting` state for its status; any other worker is left alone.
|
|
1753
|
+
* @returns whether the worker was asked.
|
|
1754
|
+
* @throws UserError when the ticket is unknown.
|
|
1755
|
+
*/
|
|
1756
|
+
requestStatus(ticketId) {
|
|
1757
|
+
return this.repo.atomic(() => this.tickets.requestStatus(ticketId));
|
|
1758
|
+
}
|
|
1759
|
+
/**
|
|
1760
|
+
* Queue a message for the Channel its purpose names: an acknowledgement or an answer goes where the person's message was
|
|
1761
|
+
* written, attention where the message that raised the question was, else, like a result, to the conversation the ticket
|
|
1762
|
+
* started in. A message queued before is not queued again (see `Replies.reply`).
|
|
1763
|
+
* @throws UserError when the ticket or trigger is unknown or the purpose's rule refuses it, such as a result of a ticket that
|
|
1764
|
+
* is not ready, completed, merged, or dropped.
|
|
1765
|
+
*/
|
|
1766
|
+
reply(request) {
|
|
1767
|
+
return this.repo.atomic(() => this.replies.reply(request));
|
|
1768
|
+
}
|
|
1769
|
+
/** The assessor delivered an Eval's candidate to its Session: the Eval's deadline counts from now. */
|
|
1770
|
+
candidateDelivered(evalId) {
|
|
1771
|
+
this.repo.atomic(() => {
|
|
1772
|
+
this.evals.delivered(evalId, this.options.policy());
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Queue a stored Trigger for a fresh Eval, such as a person's replay; returns false while an Eval holds it.
|
|
1777
|
+
* @throws UserError when the trigger is unknown.
|
|
1778
|
+
*/
|
|
1779
|
+
reevaluate(triggerId) {
|
|
1780
|
+
return this.repo.atomic(() => this.evals.reevaluate(triggerId));
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* A person dismisses the problem an unavailable Decision shows: the overview lists it no more.
|
|
1784
|
+
* @throws UserError for a Decision that is unknown or not unavailable.
|
|
1785
|
+
*/
|
|
1786
|
+
dismiss(decisionId) {
|
|
1787
|
+
return this.repo.atomic(() => this.evals.dismiss(decisionId));
|
|
1788
|
+
}
|
|
1789
|
+
/**
|
|
1790
|
+
* Drop every ticket's Subscription to a Thread, until a new Decision subscribes one again.
|
|
1791
|
+
* @returns whether a Subscription was dropped.
|
|
1792
|
+
*/
|
|
1793
|
+
unsubscribe(thread) {
|
|
1794
|
+
return this.repo.atomic(() => this.tickets.dropSubscriptions(thread, "person"));
|
|
1795
|
+
}
|
|
1796
|
+
/**
|
|
1797
|
+
* A person stops a ticket, which withdraws its Mandate: it ends and receives nothing more.
|
|
1798
|
+
* @throws UserError when the ticket is unknown.
|
|
1799
|
+
*/
|
|
1800
|
+
stopTicket(ticketId, reason) {
|
|
1801
|
+
return this.repo.atomic(() => this.tickets.stop(ticketId, reason));
|
|
1802
|
+
}
|
|
1803
|
+
/**
|
|
1804
|
+
* A person retries a ticket whose worker reported failed or blocked (or whose input delivery failed): the stalled
|
|
1805
|
+
* Assignment ends and a new one starts under the same Mandate.
|
|
1806
|
+
* @throws UserError when the ticket is unknown, has ended, or is not retryable.
|
|
1807
|
+
*/
|
|
1808
|
+
retryTicket(ticketId) {
|
|
1809
|
+
return this.repo.atomic(() => this.tickets.retry(ticketId));
|
|
1810
|
+
}
|
|
1811
|
+
/**
|
|
1812
|
+
* The Executor's fact that an Assignment runs; the Inputs that wait for it go out.
|
|
1813
|
+
* @throws UserError when the ticket is unknown.
|
|
1814
|
+
*/
|
|
1815
|
+
assignmentStarted(ticketId, assignmentId) {
|
|
1816
|
+
this.repo.atomic(() => {
|
|
1817
|
+
this.assignments.started(ticketId, assignmentId);
|
|
1818
|
+
});
|
|
1819
|
+
}
|
|
1820
|
+
/**
|
|
1821
|
+
* The Executor's fact that Inputs reached the Assignment that runs the ticket, which clears a failed delivery. A fact about
|
|
1822
|
+
* an Assignment that no longer runs is dropped. Its worker reads each once its Session takes it into a step (`inputsRead`).
|
|
1823
|
+
*/
|
|
1824
|
+
inputsDelivered(ticketId, assignmentId, inputIds) {
|
|
1825
|
+
this.repo.atomic(() => {
|
|
1826
|
+
this.assignments.delivered(ticketId, assignmentId, inputIds);
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
/**
|
|
1830
|
+
* The Executor's fact that the worker's Session of an open ticket took the messages that carried Inputs into a step, from
|
|
1831
|
+
* which its model reads them: a report or the end of a turn after that counts them as read at the ticket's end.
|
|
1832
|
+
* @throws UserError when the ticket is unknown.
|
|
1833
|
+
*/
|
|
1834
|
+
inputsRead(ticketId, inputIds) {
|
|
1835
|
+
this.repo.atomic(() => {
|
|
1836
|
+
this.assignments.read(ticketId, inputIds);
|
|
1837
|
+
});
|
|
1838
|
+
}
|
|
1839
|
+
/** The Executor's fact that a turn of the worker of the Assignment that runs the ticket ended, after a report too. */
|
|
1840
|
+
turnEnded(ticketId, assignmentId) {
|
|
1841
|
+
this.repo.atomic(() => {
|
|
1842
|
+
this.assignments.turnEnded(ticketId, assignmentId);
|
|
1843
|
+
});
|
|
1844
|
+
}
|
|
1845
|
+
/** The Executor's fact that delivering Inputs to the Assignment that runs the ticket failed; the ticket shows it until a delivery succeeds. */
|
|
1846
|
+
deliveryFailed(ticketId, assignmentId, error) {
|
|
1847
|
+
this.repo.atomic(() => {
|
|
1848
|
+
this.assignments.deliveryFailed(ticketId, assignmentId, error);
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* A worker's request, through its Executor, to mark a Thread attached to its ticket unrelated, for `reason`: only that
|
|
1853
|
+
* ticket's Subscription drops, until a new Decision subscribes it again.
|
|
1854
|
+
* @throws UserError when the ticket is unknown, or for the Thread the ticket started on, one a Source bound it to (such as
|
|
1855
|
+
* its pull request's), or one it does not follow.
|
|
1856
|
+
*/
|
|
1857
|
+
markUnrelated(ticketId, thread, reason) {
|
|
1858
|
+
this.repo.atomic(() => {
|
|
1859
|
+
this.tickets.markUnrelated(ticketId, thread, reason);
|
|
1860
|
+
});
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* An Executor's Subscription to a Thread it found related, for context: see `Tickets.followForContext` and `Thread.context`.
|
|
1864
|
+
* @returns false when the ticket already follows the Thread.
|
|
1865
|
+
* @throws UserError when the ticket is unknown or has ended.
|
|
1866
|
+
*/
|
|
1867
|
+
followForContext(ticketId, thread) {
|
|
1868
|
+
return this.repo.atomic(() => this.tickets.followForContext(ticketId, thread));
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* A fact the main Session gives an open ticket's Executor: see `Tickets.note`.
|
|
1872
|
+
* @throws UserError when the ticket is unknown or has ended.
|
|
1873
|
+
*/
|
|
1874
|
+
note(ticketId, text) {
|
|
1875
|
+
return this.repo.atomic(() => this.tickets.note(ticketId, text));
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* An Executor's hand-back of a message that reached its ticket but asks for more than it: see `Evals.handback`.
|
|
1879
|
+
* @returns whether it was queued for Eval: false while another ticket still decides it, and for one this ticket did not decide (see `Evals.handback`).
|
|
1880
|
+
* @throws UserError when the ticket or trigger is unknown, the trigger did not reach the ticket, or the ticket already handed it back.
|
|
1881
|
+
*/
|
|
1882
|
+
handback(ticketId, triggerId, reason) {
|
|
1883
|
+
return this.repo.atomic(() => this.evals.handback(ticketId, triggerId, reason));
|
|
1884
|
+
}
|
|
1885
|
+
/** Takes in a ticket that a command of this Engine did not write, such as one reloaded from the disk between commands. */
|
|
1886
|
+
updateTicket(ticket) {
|
|
1887
|
+
this.repo.atomic(() => {
|
|
1888
|
+
const live = this.repo.tickets.get(ticket.id);
|
|
1889
|
+
if (!live || live.updatedAt <= ticket.updatedAt) this.repo.tickets.save(ticket);
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* Record a report on an open ticket's current Assignment. Its question for a person (`attention`) is asked, kept, or
|
|
1894
|
+
* cleared (`null` or a `ready` report), and a replaced attention question whose reply has not been sent yet is withdrawn
|
|
1895
|
+
* from the outbox. A `blocked` or `failed` report holds back automated inputs until a human message arrives. A `dropped`
|
|
1896
|
+
* report ends the ticket, and a `ready` report ends it: `completed` without followed Threads, else with the `followsDone`
|
|
1897
|
+
* outcome once `followsDone` holds.
|
|
1898
|
+
* @throws UserError for an unknown or ended ticket, an ended assignment, a question that comes with a ready result or an
|
|
1899
|
+
* answer, or a question or answer that names a message that is not a person's or did not reach the ticket.
|
|
1900
|
+
*/
|
|
1901
|
+
report(ticketId, report) {
|
|
1902
|
+
return this.repo.atomic(() => {
|
|
1903
|
+
const ticket = this.assignments.report(ticketId, report);
|
|
1904
|
+
this.options.executor.refresh?.(ticket);
|
|
1905
|
+
return ticket;
|
|
1906
|
+
});
|
|
1907
|
+
}
|
|
1908
|
+
/**
|
|
1909
|
+
* Handles an assignment that was running when the host stopped: restarts it with a recovery note unless its latest report is
|
|
1910
|
+
* `waiting`, `ready`, `blocked`, or `failed` and no Input reached its worker after that report, in which case it keeps its
|
|
1911
|
+
* Session and state and gets the Inputs that wait for it.
|
|
1912
|
+
*/
|
|
1913
|
+
assignmentInterrupted(ticketId, assignmentId) {
|
|
1914
|
+
this.repo.atomic(() => {
|
|
1915
|
+
this.assignments.interrupted(ticketId, assignmentId);
|
|
1916
|
+
});
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* The Policy changed: each open ticket in `effects` is told how the change bears on it, and Evals in progress start again
|
|
1920
|
+
* under the new version.
|
|
1921
|
+
*/
|
|
1922
|
+
policyChanged(from, to, effects = /* @__PURE__ */ new Map()) {
|
|
1923
|
+
this.repo.atomic(() => {
|
|
1924
|
+
this.tickets.policyChanged(from, to, effects);
|
|
1925
|
+
this.evals.policyChanged(from, to);
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
};
|
|
1929
|
+
// src/core/limits.ts
|
|
1930
|
+
/** Validation bounds shared between host schemas and management panel forms. */
|
|
1931
|
+
const LIMITS = {
|
|
1932
|
+
ruleName: 100,
|
|
1933
|
+
ruleInstruction: 2e3,
|
|
1934
|
+
evalTimeoutSeconds: {
|
|
1935
|
+
min: 30,
|
|
1936
|
+
max: 600
|
|
1937
|
+
},
|
|
1938
|
+
maxWorkers: {
|
|
1939
|
+
min: 1,
|
|
1940
|
+
max: 16
|
|
1941
|
+
},
|
|
1942
|
+
prepareCommand: 4e3,
|
|
1943
|
+
promptMaxChars: {
|
|
1944
|
+
min: 1e3,
|
|
1945
|
+
max: 1e6
|
|
1946
|
+
},
|
|
1947
|
+
admissionContextMaxPages: {
|
|
1948
|
+
min: 1,
|
|
1949
|
+
max: 100
|
|
1950
|
+
},
|
|
1951
|
+
admissionContextTimeoutMs: {
|
|
1952
|
+
min: 1,
|
|
1953
|
+
max: 9e4
|
|
1954
|
+
}
|
|
1955
|
+
};
|
|
1956
|
+
new Intl.Segmenter("zh", { granularity: "word" });
|
|
1957
|
+
/** Case-insensitive comparison for GitHub logins and repository names. */
|
|
1958
|
+
const sameName = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
1959
|
+
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1960
|
+
// src/infra/environment.ts
|
|
1961
|
+
/**
|
|
1962
|
+
* Writes the CLI shims and the isolated git configuration that bind a run to the agent's accounts.
|
|
1963
|
+
*
|
|
1964
|
+
* Each shim strips its own directory from PATH before it execs, so a wrapper script that resolves `gh` by name reaches the
|
|
1965
|
+
* real binary instead of looping. The git configuration replaces the operator's global configuration for the run, so a
|
|
1966
|
+
* worker cannot push with the operator's credentials.
|
|
1967
|
+
*
|
|
1968
|
+
* These are guardrails, not an OS boundary: a run shares the operator's OS user and can read their home directory.
|
|
1969
|
+
*/
|
|
1970
|
+
const MARKER = "# Written by superagent on every start; edits are lost.";
|
|
1971
|
+
/** Commands the shims provide, which a blocked list must never shadow. */
|
|
1972
|
+
const WORKER_COMMANDS = [
|
|
1973
|
+
"gh",
|
|
1974
|
+
"git",
|
|
1975
|
+
"lark-cli"
|
|
1976
|
+
];
|
|
1977
|
+
const workerBin = (stateDir) => join(stateDir, "worker-bin");
|
|
1978
|
+
const workerGitConfig = (stateDir) => join(stateDir, "worker-gitconfig");
|
|
1979
|
+
const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
1980
|
+
const gitQuote = (value) => `"${value.replace(/[\\"]/g, (char) => `\\${char}`)}"`;
|
|
1981
|
+
const credentialHelper = (cli) => `!${shellQuote(cli)} auth git-credential`;
|
|
1982
|
+
async function written(file) {
|
|
1983
|
+
try {
|
|
1984
|
+
const stat = await lstat(file);
|
|
1985
|
+
if (!stat.isFile() || stat.size > 4096) return false;
|
|
1986
|
+
return (await readFile(file, "utf8")).includes(MARKER);
|
|
1987
|
+
} catch {
|
|
1988
|
+
return false;
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
async function own(file, content) {
|
|
1992
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
1993
|
+
await writeFile(temporary, content, { mode: 384 });
|
|
1994
|
+
await rename(temporary, file);
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Writes the shims and git configuration, refusing to overwrite files it did not write.
|
|
1998
|
+
* @throws when a file in the shim directory or at the git configuration path was written by something else.
|
|
1999
|
+
*/
|
|
2000
|
+
async function writeEnvironment(accounts, blockedCommands) {
|
|
2001
|
+
const dir = workerBin(accounts.stateDir);
|
|
2002
|
+
await mkdir(dir, { recursive: true });
|
|
2003
|
+
const before = await readdir(dir);
|
|
2004
|
+
for (const name of before) if (!await written(join(dir, name))) throw new Error(`The file ${join(dir, name)} was not written by superagent; move it away or choose another state directory.`);
|
|
2005
|
+
const kept = /* @__PURE__ */ new Set();
|
|
2006
|
+
const shim = async (name, body) => {
|
|
2007
|
+
const temporary = join(dir, `.${name}.${process.pid}.tmp`);
|
|
2008
|
+
await writeFile(temporary, `#!/bin/sh\n${MARKER}\n${body}\n`, { mode: 493 });
|
|
2009
|
+
await rename(temporary, join(dir, name));
|
|
2010
|
+
kept.add(name);
|
|
2011
|
+
};
|
|
2012
|
+
const withoutShims = [
|
|
2013
|
+
`self=${shellQuote(dir)}`,
|
|
2014
|
+
"rest=",
|
|
2015
|
+
"IFS=:",
|
|
2016
|
+
"set -f",
|
|
2017
|
+
"for entry in $PATH; do [ \"$entry\" = \"$self\" ] || rest=\"${rest:+$rest:}$entry\"; done",
|
|
2018
|
+
"set +f",
|
|
2019
|
+
"unset IFS",
|
|
2020
|
+
"PATH=$rest",
|
|
2021
|
+
"export PATH"
|
|
2022
|
+
].join("\n");
|
|
2023
|
+
const run = (program) => `${withoutShims}\nexec ${shellQuote(program)} "$@"`;
|
|
2024
|
+
const fail = (message) => `echo ${shellQuote(message)} >&2\nexit 1`;
|
|
2025
|
+
await shim("gh", run(accounts.githubCli));
|
|
2026
|
+
await shim("lark-cli", accounts.feishuCli ? run(accounts.feishuCli) : fail("lark-cli is unavailable: this installation has no Feishu bot."));
|
|
2027
|
+
for (const name of new Set(blockedCommands.filter((name) => !WORKER_COMMANDS.includes(name)))) await shim(name, fail(`${name} is blocked in this installation; use gh, which acts as ${accounts.agentLogin}.`));
|
|
2028
|
+
for (const name of before) if (!kept.has(name)) await unlink(join(dir, name));
|
|
2029
|
+
await own(workerGitConfig(accounts.stateDir), [
|
|
2030
|
+
MARKER,
|
|
2031
|
+
"[user]",
|
|
2032
|
+
" useConfigOnly = true",
|
|
2033
|
+
"[credential]",
|
|
2034
|
+
" helper =",
|
|
2035
|
+
"[credential \"https://github.com\"]",
|
|
2036
|
+
`\thelper = ${gitQuote(credentialHelper(accounts.githubCli))}`,
|
|
2037
|
+
"[url \"https://github.com/\"]",
|
|
2038
|
+
" insteadOf = git@github.com:",
|
|
2039
|
+
" insteadOf = ssh://git@github.com:",
|
|
2040
|
+
"[filter \"lfs\"]",
|
|
2041
|
+
" clean = git-lfs clean -- %f",
|
|
2042
|
+
" smudge = git-lfs smudge -- %f",
|
|
2043
|
+
" process = git-lfs filter-process",
|
|
2044
|
+
" required = true"
|
|
2045
|
+
].join("\n") + "\n");
|
|
2046
|
+
}
|
|
2047
|
+
/** Environment variables a run receives, with the shim directory first on PATH. */
|
|
2048
|
+
function runEnvironment(accounts, variables) {
|
|
2049
|
+
return {
|
|
2050
|
+
...variables,
|
|
2051
|
+
PATH: [workerBin(accounts.stateDir), process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin"].join(delimiter),
|
|
2052
|
+
GIT_CONFIG_GLOBAL: workerGitConfig(accounts.stateDir),
|
|
2053
|
+
GIT_CONFIG_SYSTEM: "/dev/null",
|
|
2054
|
+
GIT_TERMINAL_PROMPT: "0"
|
|
2055
|
+
};
|
|
2056
|
+
}
|
|
2057
|
+
// src/core/policy.ts
|
|
2058
|
+
/**
|
|
2059
|
+
* Runtime settings schemas, assessment validation, and policy gate evaluation.
|
|
2060
|
+
* Who may originate work is configured per Source in that Source's own identities; the Policy never maps a person across Sources.
|
|
2061
|
+
*/
|
|
2062
|
+
const RuleIdSchema = z.string().regex(/^[a-zA-Z0-9_-]{1,80}$/);
|
|
2063
|
+
const RuleMatchSchema = z.object({
|
|
2064
|
+
rule_id: RuleIdSchema,
|
|
2065
|
+
reason: z.string().trim().min(1).max(500)
|
|
2066
|
+
}).strict();
|
|
2067
|
+
const RuleAssessmentSchema = RuleMatchSchema.extend({ matched: z.boolean() }).strict();
|
|
2068
|
+
const AdmissionDirectionSchema = z.object({
|
|
2069
|
+
implementation_requested: z.boolean(),
|
|
2070
|
+
target_basis: z.enum([
|
|
2071
|
+
"specified",
|
|
2072
|
+
"existing-standard",
|
|
2073
|
+
"undetermined"
|
|
2074
|
+
]),
|
|
2075
|
+
requires_design_decision: z.boolean(),
|
|
2076
|
+
evidence: z.string().trim().min(1).max(700)
|
|
2077
|
+
}).strict();
|
|
2078
|
+
/** Check whether an assessment established implementation intent and a settled target without open design decisions. */
|
|
2079
|
+
function directionAllowed(value) {
|
|
2080
|
+
const result = AdmissionDirectionSchema.safeParse(value);
|
|
2081
|
+
return result.success && result.data.implementation_requested && result.data.target_basis !== "undetermined" && !result.data.requires_design_decision;
|
|
2082
|
+
}
|
|
2083
|
+
const DEFAULT_RULES = [{
|
|
2084
|
+
id: "copy",
|
|
2085
|
+
name: "Copy fixes",
|
|
2086
|
+
enabled: true,
|
|
2087
|
+
instruction: "Explicit requests to correct a typo, wording, punctuation or existing translation. Preserve product promises and business meaning."
|
|
2088
|
+
}, {
|
|
2089
|
+
id: "visual",
|
|
2090
|
+
name: "Visual fixes",
|
|
2091
|
+
enabled: true,
|
|
2092
|
+
instruction: "Explicit implementation requests for local spacing, alignment, overflow or styling, with a specified target or an objectively established existing standard/correct state to restore. Locating an element or calling it inconsistent, unattractive or hard to understand does not establish a target. Do not invent visual style, information hierarchy, rendering or interaction decisions. No redesign, new interaction or behavior. A known spacing defect does not authorize adjacent undefined restyling; assess only a clearly separable authorized scope. If direction or scope is unsettled, observe only: no acknowledgement, worker or unsolicited question."
|
|
2093
|
+
}];
|
|
2094
|
+
/** An assessment rule; its instruction may also specify PR reviewers and whether to wait for their approval. */
|
|
2095
|
+
const RuleSchema$1 = z.object({
|
|
2096
|
+
id: RuleIdSchema,
|
|
2097
|
+
name: z.string().trim().min(1).max(LIMITS.ruleName),
|
|
2098
|
+
enabled: z.boolean(),
|
|
2099
|
+
instruction: z.string().trim().min(1).max(LIMITS.ruleInstruction)
|
|
2100
|
+
}).strict();
|
|
2101
|
+
const RoleModelSchema = z.object({
|
|
2102
|
+
provider: z.string().trim().min(1),
|
|
2103
|
+
model: z.string().trim().min(1),
|
|
2104
|
+
reasoningEffort: z.string().trim().min(1).optional()
|
|
2105
|
+
}).strict();
|
|
2106
|
+
const AllowedSchema = z.object({
|
|
2107
|
+
id: z.string().trim().min(1).max(200),
|
|
2108
|
+
name: z.string().trim().max(100).optional()
|
|
2109
|
+
}).strict();
|
|
2110
|
+
const Weak = z.enum(["inferred", "ignore"]);
|
|
2111
|
+
const AdmissionRowSchema = z.object({
|
|
2112
|
+
listedUnaddressed: Weak.optional(),
|
|
2113
|
+
unlistedAddressed: z.enum([
|
|
2114
|
+
"explicit",
|
|
2115
|
+
"inferred",
|
|
2116
|
+
"ignore"
|
|
2117
|
+
]).optional(),
|
|
2118
|
+
unlistedUnaddressed: Weak.optional()
|
|
2119
|
+
}).strict();
|
|
2120
|
+
const AdmissionTableSchema = z.record(z.string(), AdmissionRowSchema);
|
|
2121
|
+
const SourcePolicySchema = z.object({
|
|
2122
|
+
allowed: z.array(AllowedSchema).default([]),
|
|
2123
|
+
admission: AdmissionTableSchema.default({})
|
|
2124
|
+
}).catchall(z.unknown());
|
|
2125
|
+
const PolicyConfigSchema = z.object({
|
|
2126
|
+
rules: z.array(RuleSchema$1).refine((rules) => new Set(rules.map((rule) => rule.id)).size === rules.length, "Duplicate rule IDs").default(DEFAULT_RULES),
|
|
2127
|
+
sources: z.record(z.string().regex(/^[a-z][a-z0-9-]*$/), SourcePolicySchema).default({})
|
|
2128
|
+
}).strict();
|
|
2129
|
+
const EvalConfigSchema = z.object({
|
|
2130
|
+
mode: z.enum([
|
|
2131
|
+
"off",
|
|
2132
|
+
"observe",
|
|
2133
|
+
"auto"
|
|
2134
|
+
]).default("observe"),
|
|
2135
|
+
timeoutSeconds: z.number().int().min(LIMITS.evalTimeoutSeconds.min).max(LIMITS.evalTimeoutSeconds.max).default(120),
|
|
2136
|
+
model: RoleModelSchema.nullable().default(null)
|
|
2137
|
+
}).strict();
|
|
2138
|
+
const CommandNameSchema = z.string().regex(/^[A-Za-z0-9._-]+$/).refine((name) => name !== "." && name !== "..", "Not a command name").refine((name) => !WORKER_COMMANDS.includes(name), `${WORKER_COMMANDS.join(", ")} cannot be blocked`);
|
|
2139
|
+
/** Executor settings: worker model, concurrency, ticket directory root (empty defaults to `<stateDir>/work`), `prepare` command, and blocked commands. */
|
|
2140
|
+
const ExecutorConfigSchema = z.object({
|
|
2141
|
+
model: RoleModelSchema.nullable().default(null),
|
|
2142
|
+
maxWorkers: z.number().int().min(LIMITS.maxWorkers.min).max(LIMITS.maxWorkers.max).default(3),
|
|
2143
|
+
directory: z.string().trim().refine((path) => path === "" || path.startsWith("/"), "An absolute path, or empty for <stateDir>/work").default(""),
|
|
2144
|
+
prepare: z.string().max(LIMITS.prepareCommand).default(""),
|
|
2145
|
+
blockedCommands: z.array(CommandNameSchema).default([])
|
|
2146
|
+
}).strict();
|
|
2147
|
+
const SourceInstanceSchema = z.object({
|
|
2148
|
+
enabled: z.boolean().default(true),
|
|
2149
|
+
config: z.record(z.string(), z.unknown()).default({})
|
|
2150
|
+
}).strict();
|
|
2151
|
+
z.object({
|
|
2152
|
+
paused: z.boolean().default(false),
|
|
2153
|
+
sources: z.record(z.string().regex(/^[a-z][a-z0-9-]*$/), SourceInstanceSchema).default({}),
|
|
2154
|
+
policy: PolicyConfigSchema.default(() => PolicyConfigSchema.parse({})),
|
|
2155
|
+
eval: EvalConfigSchema.default(() => EvalConfigSchema.parse({})),
|
|
2156
|
+
executor: ExecutorConfigSchema.default(() => ExecutorConfigSchema.parse({}))
|
|
2157
|
+
}).strict();
|
|
2158
|
+
// src/state/files.ts
|
|
2159
|
+
/**
|
|
2160
|
+
* File-backed durable state.
|
|
2161
|
+
*
|
|
2162
|
+
* Every aggregate is one JSON file under the state directory. The layout is meant to be read by a person or an agent with
|
|
2163
|
+
* `ls` and `cat`, so no index is required to answer "what is open" or "what happened": the directory names carry the answer.
|
|
2164
|
+
*
|
|
2165
|
+
* ```
|
|
2166
|
+
* state/
|
|
2167
|
+
* triggers/<thread>/<at>-<id>.json
|
|
2168
|
+
* threads/<threadKey>.json
|
|
2169
|
+
* tickets/<id>/ticket.json
|
|
2170
|
+
* tickets/<id>/log.md
|
|
2171
|
+
* decisions/<id>.json
|
|
2172
|
+
* outbox/<id>.json
|
|
2173
|
+
* meta/<key>.json
|
|
2174
|
+
* ```
|
|
2175
|
+
*
|
|
2176
|
+
* Writes go through a temporary file and a rename, so a reader never sees half a file. `atomic` serialises writers in
|
|
2177
|
+
* process and buffers file writes until the outermost transaction commits, so a failed unit of work leaves no trace.
|
|
2178
|
+
*/
|
|
2179
|
+
const encode = (value) => Buffer.from(value).toString("base64url");
|
|
2180
|
+
const decode = (value) => Buffer.from(value, "base64url").toString();
|
|
2181
|
+
var FileRepositories = class {
|
|
2182
|
+
stateDir;
|
|
2183
|
+
pending = [];
|
|
2184
|
+
depth = 0;
|
|
2185
|
+
queue = Promise.resolve();
|
|
2186
|
+
/** Every file that exists now, refreshed by `refresh`; lookups read only what this lists, so scans stay cheap. */
|
|
2187
|
+
disk = /* @__PURE__ */ new Map();
|
|
2188
|
+
constructor(stateDir) {
|
|
2189
|
+
this.stateDir = stateDir;
|
|
2190
|
+
}
|
|
2191
|
+
/** Creates the directories and loads every stored file into memory. Call once before use. */
|
|
2192
|
+
async open() {
|
|
2193
|
+
for (const dir of [
|
|
2194
|
+
"triggers",
|
|
2195
|
+
"threads",
|
|
2196
|
+
"tickets",
|
|
2197
|
+
"decisions",
|
|
2198
|
+
"outbox",
|
|
2199
|
+
"meta"
|
|
2200
|
+
]) await mkdir(join(this.stateDir, dir), { recursive: true });
|
|
2201
|
+
await this.refresh();
|
|
2202
|
+
}
|
|
2203
|
+
async refresh() {
|
|
2204
|
+
const read = async (dir) => {
|
|
2205
|
+
try {
|
|
2206
|
+
return await readdir(join(this.stateDir, dir));
|
|
2207
|
+
} catch {
|
|
2208
|
+
return [];
|
|
2209
|
+
}
|
|
2210
|
+
};
|
|
2211
|
+
const all = /* @__PURE__ */ new Map();
|
|
2212
|
+
const load = async (path) => {
|
|
2213
|
+
try {
|
|
2214
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
2215
|
+
} catch {
|
|
2216
|
+
return;
|
|
2217
|
+
}
|
|
2218
|
+
};
|
|
2219
|
+
for (const name of await read("threads")) {
|
|
2220
|
+
const value = await load(join(this.stateDir, "threads", name));
|
|
2221
|
+
if (value) all.set(`thread:${decode(name.replace(/\.json$/, ""))}`, value);
|
|
2222
|
+
}
|
|
2223
|
+
for (const name of await read("decisions")) {
|
|
2224
|
+
const value = await load(join(this.stateDir, "decisions", name));
|
|
2225
|
+
if (value) all.set(`decision:${name.replace(/\.json$/, "")}`, value);
|
|
2226
|
+
}
|
|
2227
|
+
for (const name of await read("outbox")) {
|
|
2228
|
+
const value = await load(join(this.stateDir, "outbox", name));
|
|
2229
|
+
if (value) all.set(`outbox:${name.replace(/\.json$/, "")}`, value);
|
|
2230
|
+
}
|
|
2231
|
+
for (const name of await read("meta")) {
|
|
2232
|
+
const value = await load(join(this.stateDir, "meta", name));
|
|
2233
|
+
if (value) all.set(`meta:${decode(name.replace(/\.json$/, ""))}`, value);
|
|
2234
|
+
}
|
|
2235
|
+
for (const name of await read("tickets")) {
|
|
2236
|
+
const value = await load(join(this.stateDir, "tickets", name, "ticket.json"));
|
|
2237
|
+
if (value) all.set(`ticket:${name}`, value);
|
|
2238
|
+
}
|
|
2239
|
+
for (const name of await read("triggers")) for (const file of await read(join("triggers", name))) {
|
|
2240
|
+
const value = await load(join(this.stateDir, "triggers", name, file));
|
|
2241
|
+
if (value) all.set(`trigger:${decode(name)}:${file.replace(/\.json$/, "")}`, value);
|
|
2242
|
+
}
|
|
2243
|
+
this.disk = all;
|
|
2244
|
+
}
|
|
2245
|
+
/**
|
|
2246
|
+
* Writes every change and re-reads every file, so a reader in this process sees what other writers stored and other
|
|
2247
|
+
* processes see what this one did. A long-running poller calls this between rounds.
|
|
2248
|
+
*/
|
|
2249
|
+
async reload() {
|
|
2250
|
+
await this.flush();
|
|
2251
|
+
await this.refresh();
|
|
2252
|
+
}
|
|
2253
|
+
pathOf(op) {
|
|
2254
|
+
return join(this.stateDir, op.path);
|
|
2255
|
+
}
|
|
2256
|
+
triggerDir(thread) {
|
|
2257
|
+
return join("triggers", encode(thread));
|
|
2258
|
+
}
|
|
2259
|
+
/** Writes and deletes buffered until the outermost transaction commits. */
|
|
2260
|
+
write(path, value) {
|
|
2261
|
+
const op = {
|
|
2262
|
+
path,
|
|
2263
|
+
value: JSON.stringify(value, null, 2)
|
|
2264
|
+
};
|
|
2265
|
+
this.pending.push(op);
|
|
2266
|
+
this.apply(op);
|
|
2267
|
+
}
|
|
2268
|
+
remove(path) {
|
|
2269
|
+
const op = {
|
|
2270
|
+
path,
|
|
2271
|
+
value: void 0
|
|
2272
|
+
};
|
|
2273
|
+
this.pending.push(op);
|
|
2274
|
+
this.apply(op);
|
|
2275
|
+
}
|
|
2276
|
+
/** Applies a pending operation to the in-memory view so reads inside the same transaction see it. */
|
|
2277
|
+
apply(op) {
|
|
2278
|
+
const logical = this.logicalKey(op);
|
|
2279
|
+
if (op.value === void 0) {
|
|
2280
|
+
this.disk.delete(logical);
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
this.disk.set(logical, JSON.parse(op.value));
|
|
2284
|
+
}
|
|
2285
|
+
/**
|
|
2286
|
+
* The in-memory name a file path maps to, matching the names `refresh` builds. Files at the top of a directory are named
|
|
2287
|
+
* after their key alone, so their name is the encoded key; a trigger sits one directory deeper, under a thread.
|
|
2288
|
+
*/
|
|
2289
|
+
logicalKey(op) {
|
|
2290
|
+
const [kind, ...rest] = op.path.split("/");
|
|
2291
|
+
const name = rest.join("/").replace(/\.json$/, "");
|
|
2292
|
+
if (kind === "tickets") return `ticket:${rest[0]}`;
|
|
2293
|
+
if (kind === "threads") return `thread:${decode(basename(name))}`;
|
|
2294
|
+
if (kind === "decisions") return `decision:${decode(name)}`;
|
|
2295
|
+
if (kind === "outbox") return `outbox:${decode(name)}`;
|
|
2296
|
+
if (kind === "meta") return `meta:${decode(name)}`;
|
|
2297
|
+
return `trigger:${decode(rest[0])}:${rest.slice(1).join("/").replace(/\.json$/, "")}`;
|
|
2298
|
+
}
|
|
2299
|
+
async commit(ops) {
|
|
2300
|
+
for (const op of ops) {
|
|
2301
|
+
const path = this.pathOf(op);
|
|
2302
|
+
if (op.value === void 0) {
|
|
2303
|
+
await rm(path, { force: true });
|
|
2304
|
+
continue;
|
|
2305
|
+
}
|
|
2306
|
+
await mkdir(join(path, ".."), { recursive: true });
|
|
2307
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
2308
|
+
await writeFile(temporary, op.value, "utf8");
|
|
2309
|
+
await rename(temporary, path);
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Runs `work` as one unit: its writes and deletes become visible in memory at once and reach disk only when the outermost
|
|
2314
|
+
* call commits. A thrown error discards them.
|
|
2315
|
+
*/
|
|
2316
|
+
atomic(work) {
|
|
2317
|
+
const level = this.depth++;
|
|
2318
|
+
const outer = level === 0;
|
|
2319
|
+
const before = this.pending.length;
|
|
2320
|
+
const undo = outer ? new Map([...this.disk].map(([name, value]) => [name, value])) : void 0;
|
|
2321
|
+
try {
|
|
2322
|
+
const value = work();
|
|
2323
|
+
if (outer) {
|
|
2324
|
+
const ops = this.pending.splice(0);
|
|
2325
|
+
this.depth = 0;
|
|
2326
|
+
const previous = this.queue;
|
|
2327
|
+
this.queue = previous.then(() => this.commit(ops)).then(() => {
|
|
2328
|
+
if (previous !== this.queue) return;
|
|
2329
|
+
for (const op of ops) this.apply(op);
|
|
2330
|
+
}).catch(() => {});
|
|
2331
|
+
} else this.depth--;
|
|
2332
|
+
return value;
|
|
2333
|
+
} catch (error) {
|
|
2334
|
+
this.pending.splice(before);
|
|
2335
|
+
if (undo) {
|
|
2336
|
+
this.disk = undo;
|
|
2337
|
+
this.depth = 0;
|
|
2338
|
+
} else this.depth = level;
|
|
2339
|
+
throw error;
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
/**
|
|
2343
|
+
* Commits every buffered write and waits for the earlier ones. Call before the process exits. A write made outside a
|
|
2344
|
+
* transaction, such as the loop's cursor, waits here too.
|
|
2345
|
+
*/
|
|
2346
|
+
async flush() {
|
|
2347
|
+
if (this.pending.length) this.queue = this.queue.then(() => this.commit(this.pending.splice(0))).catch(() => {});
|
|
2348
|
+
await this.queue;
|
|
2349
|
+
}
|
|
2350
|
+
triggers = {
|
|
2351
|
+
get: (id) => this.findTrigger(id),
|
|
2352
|
+
save: (trigger) => {
|
|
2353
|
+
const at = trigger.at.replace(/[:.]/g, "-");
|
|
2354
|
+
this.write(join(this.triggerDir(threadKey(trigger.threads[0])), `${at}-${encode(trigger.id)}.json`), trigger);
|
|
2355
|
+
},
|
|
2356
|
+
list: () => {
|
|
2357
|
+
const all = [];
|
|
2358
|
+
for (const [name, value] of this.disk) if (name.startsWith("trigger:")) all.push(value);
|
|
2359
|
+
return all;
|
|
2360
|
+
},
|
|
2361
|
+
disposition: (id) => this.findMeta(`disposition:${id}`),
|
|
2362
|
+
saveDisposition: (id, value) => this.write(join("meta", `${encode(`disposition:${id}`)}.json`), value)
|
|
2363
|
+
};
|
|
2364
|
+
findTrigger(id) {
|
|
2365
|
+
for (const [name, value] of this.disk) if (name.startsWith("trigger:") && value.id === id) return value;
|
|
2366
|
+
}
|
|
2367
|
+
findMeta(metaKey) {
|
|
2368
|
+
return this.disk.get(`meta:${metaKey}`);
|
|
2369
|
+
}
|
|
2370
|
+
threads = {
|
|
2371
|
+
get: (thread) => this.disk.get(`thread:${thread}`),
|
|
2372
|
+
save: (thread) => this.write(join("threads", `${encode(thread.key)}.json`), thread),
|
|
2373
|
+
list: () => [...this.disk.entries()].filter(([name]) => name.startsWith("thread:")).map(([, value]) => value),
|
|
2374
|
+
active: () => this.threads.list().filter((thread) => thread.pending.length > 0 || thread.evaluating !== void 0)
|
|
2375
|
+
};
|
|
2376
|
+
tickets = {
|
|
2377
|
+
get: (id) => this.disk.get(`ticket:${id}`),
|
|
2378
|
+
save: (ticket) => this.write(join("tickets", ticket.id, "ticket.json"), ticket),
|
|
2379
|
+
list: () => [...this.disk.entries()].filter(([name]) => name.startsWith("ticket:")).map(([, value]) => value),
|
|
2380
|
+
open: () => this.tickets.list().filter((ticket) => ticket.ended === void 0),
|
|
2381
|
+
active: () => this.tickets.list().filter((ticket) => ticket.undelivered.length > 0 || ["pending", "running"].includes(ticket.assignments.at(-1)?.state ?? ""))
|
|
2382
|
+
};
|
|
2383
|
+
decisions = {
|
|
2384
|
+
get: (id) => this.disk.get(`decision:${id}`),
|
|
2385
|
+
save: (decision) => this.write(join("decisions", `${encode(decision.id)}.json`), decision),
|
|
2386
|
+
byThread: (thread) => this.decisions.list().filter((decision) => decision.threadKey === thread),
|
|
2387
|
+
list: () => [...this.disk.entries()].filter(([name]) => name.startsWith("decision:")).map(([, value]) => value)
|
|
2388
|
+
};
|
|
2389
|
+
/** Stores arbitrary named state, such as a Source's cursor. */
|
|
2390
|
+
getMeta(name) {
|
|
2391
|
+
return this.findMeta(name);
|
|
2392
|
+
}
|
|
2393
|
+
setMeta(name, value) {
|
|
2394
|
+
if (value === void 0) this.remove(join("meta", `${encode(name)}.json`));
|
|
2395
|
+
else this.write(join("meta", `${encode(name)}.json`), value);
|
|
2396
|
+
}
|
|
2397
|
+
/** Every stored key, for `status` and debugging. */
|
|
2398
|
+
keys() {
|
|
2399
|
+
return [...this.disk.keys()].sort();
|
|
2400
|
+
}
|
|
2401
|
+
};
|
|
2402
|
+
/** Reads the state directory as plain files without opening it for writing, for a status command or an agent. */
|
|
2403
|
+
async function readState(stateDir) {
|
|
2404
|
+
try {
|
|
2405
|
+
await stat(stateDir);
|
|
2406
|
+
} catch {
|
|
2407
|
+
return {
|
|
2408
|
+
tickets: [],
|
|
2409
|
+
threads: [],
|
|
2410
|
+
decisions: [],
|
|
2411
|
+
triggers: [],
|
|
2412
|
+
exists: false
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
const repo = new FileRepositories(stateDir);
|
|
2416
|
+
await repo.open();
|
|
2417
|
+
return {
|
|
2418
|
+
tickets: repo.tickets.list(),
|
|
2419
|
+
threads: repo.threads.list(),
|
|
2420
|
+
decisions: repo.decisions.list(),
|
|
2421
|
+
triggers: repo.triggers.list(),
|
|
2422
|
+
exists: true
|
|
2423
|
+
};
|
|
2424
|
+
}
|
|
2425
|
+
// src/agents/process.ts
|
|
2426
|
+
/**
|
|
2427
|
+
* Runs one agent process and collects its streams.
|
|
2428
|
+
*
|
|
2429
|
+
* Every runner shares this: it starts the CLI with the prompt on stdin, collects stdout and stderr under a size cap, honours
|
|
2430
|
+
* the abort signal and the timeout, and returns the exit code. What differs between agents is only their argv and the shape
|
|
2431
|
+
* of their events, which each runner turns into `AgentResult`.
|
|
2432
|
+
*/
|
|
2433
|
+
const CAP = 4 << 20;
|
|
2434
|
+
function runProcess(program, argv, options) {
|
|
2435
|
+
return new Promise((resolve) => {
|
|
2436
|
+
const child = spawn(program, argv, {
|
|
2437
|
+
cwd: options.cwd,
|
|
2438
|
+
env: options.env,
|
|
2439
|
+
stdio: [
|
|
2440
|
+
"pipe",
|
|
2441
|
+
"pipe",
|
|
2442
|
+
"pipe"
|
|
2443
|
+
]
|
|
2444
|
+
});
|
|
2445
|
+
let stdout = "";
|
|
2446
|
+
let stderr = "";
|
|
2447
|
+
let timedOut = false;
|
|
2448
|
+
let aborted = false;
|
|
2449
|
+
const append = (current, chunk) => current.length >= CAP ? current : current + chunk.toString("utf8").slice(0, CAP - current.length);
|
|
2450
|
+
child.stdout.on("data", (chunk) => {
|
|
2451
|
+
stdout = append(stdout, chunk);
|
|
2452
|
+
});
|
|
2453
|
+
child.stderr.on("data", (chunk) => {
|
|
2454
|
+
stderr = append(stderr, chunk);
|
|
2455
|
+
});
|
|
2456
|
+
const finish = (exitCode) => {
|
|
2457
|
+
clearTimeout(timer);
|
|
2458
|
+
options.signal.removeEventListener("abort", stop);
|
|
2459
|
+
resolve({
|
|
2460
|
+
exitCode,
|
|
2461
|
+
stdout,
|
|
2462
|
+
stderr,
|
|
2463
|
+
timedOut,
|
|
2464
|
+
aborted
|
|
2465
|
+
});
|
|
2466
|
+
};
|
|
2467
|
+
const stop = () => {
|
|
2468
|
+
aborted = true;
|
|
2469
|
+
child.kill("SIGTERM");
|
|
2470
|
+
setTimeout(() => child.kill("SIGKILL"), 5e3).unref();
|
|
2471
|
+
};
|
|
2472
|
+
const timer = setTimeout(() => {
|
|
2473
|
+
timedOut = true;
|
|
2474
|
+
stop();
|
|
2475
|
+
}, options.timeoutMs ?? 18e5);
|
|
2476
|
+
options.signal.addEventListener("abort", stop, { once: true });
|
|
2477
|
+
child.on("error", (error) => {
|
|
2478
|
+
stderr += `\n${String(error)}`;
|
|
2479
|
+
finish(-1);
|
|
2480
|
+
});
|
|
2481
|
+
child.on("close", (code) => finish(code ?? -1));
|
|
2482
|
+
child.stdin.end(options.stdin);
|
|
2483
|
+
});
|
|
2484
|
+
}
|
|
2485
|
+
// src/agents/types.ts
|
|
2486
|
+
/**
|
|
2487
|
+
* The output every runner must produce.
|
|
2488
|
+
*
|
|
2489
|
+
* A coding agent has no structured tool channel when it runs as a subprocess, so the report is a convention instead: the
|
|
2490
|
+
* agent writes it to `REPORT_FILE` in its working directory before it stops. Every runner reads that one file, which keeps
|
|
2491
|
+
* the contract identical across agents and needs no per-agent parsing.
|
|
2492
|
+
*/
|
|
2493
|
+
const REPORT_FILE = ".superagent/report.json";
|
|
2494
|
+
/** Reads the report an agent left, or `undefined` when it wrote none or wrote an unusable one. */
|
|
2495
|
+
async function readReport(cwd) {
|
|
2496
|
+
const { readFile } = await import("node:fs/promises");
|
|
2497
|
+
const { join } = await import("node:path");
|
|
2498
|
+
try {
|
|
2499
|
+
const parsed = JSON.parse(await readFile(join(cwd, REPORT_FILE), "utf8"));
|
|
2500
|
+
if (parsed && typeof parsed === "object" && typeof parsed.summary === "string" && parsed.summary.trim()) return parsed;
|
|
2501
|
+
return;
|
|
2502
|
+
} catch {
|
|
2503
|
+
return;
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
/** Instructions that tell an agent to write the report, appended to every composed prompt. */
|
|
2507
|
+
function reportInstructions() {
|
|
2508
|
+
return [
|
|
2509
|
+
"",
|
|
2510
|
+
"## Report",
|
|
2511
|
+
"",
|
|
2512
|
+
`Before you stop, write \`${REPORT_FILE}\` in your working directory as one JSON object with these keys:`,
|
|
2513
|
+
"",
|
|
2514
|
+
"- `summary` (required): one short sentence a person can act on, under 200 characters. It is the reply the person sees,",
|
|
2515
|
+
" so leave file names, test counts and other evidence out of it; put that in your pull request or your last message.",
|
|
2516
|
+
"- `state`: `ready` when the work is ready for review, `blocked` when a person must supply something, `failed` when it cannot finish.",
|
|
2517
|
+
"- `prs`: the pull request URLs you opened, when any.",
|
|
2518
|
+
"- `question`: what the person must supply, when `state` is `blocked`.",
|
|
2519
|
+
"",
|
|
2520
|
+
"Write nothing else to that file. If you cannot write it, say the same in your last message."
|
|
2521
|
+
].join("\n");
|
|
2522
|
+
}
|
|
2523
|
+
// src/agents/claude.ts
|
|
2524
|
+
/** Runs a task on Claude Code (`claude -p`), which prints a stream-json transcript. */
|
|
2525
|
+
var ClaudeRunner = class {
|
|
2526
|
+
binary;
|
|
2527
|
+
name = "claude";
|
|
2528
|
+
constructor(binary = "claude") {
|
|
2529
|
+
this.binary = binary;
|
|
2530
|
+
}
|
|
2531
|
+
async available() {
|
|
2532
|
+
return (await runProcess(this.binary, ["--version"], {
|
|
2533
|
+
cwd: process.cwd(),
|
|
2534
|
+
env: { ...process.env },
|
|
2535
|
+
stdin: "",
|
|
2536
|
+
signal: AbortSignal.timeout(1e4)
|
|
2537
|
+
})).exitCode === 0;
|
|
2538
|
+
}
|
|
2539
|
+
async run(run) {
|
|
2540
|
+
const argv = [
|
|
2541
|
+
"-p",
|
|
2542
|
+
"--output-format",
|
|
2543
|
+
"stream-json",
|
|
2544
|
+
"--verbose",
|
|
2545
|
+
"--dangerously-skip-permissions",
|
|
2546
|
+
...run.model ? ["--model", run.model] : []
|
|
2547
|
+
];
|
|
2548
|
+
const result = await runProcess(this.binary, argv, {
|
|
2549
|
+
cwd: run.cwd,
|
|
2550
|
+
env: run.env,
|
|
2551
|
+
stdin: run.prompt,
|
|
2552
|
+
signal: run.signal,
|
|
2553
|
+
timeoutMs: run.timeoutMs
|
|
2554
|
+
});
|
|
2555
|
+
const report = await readReport(run.cwd);
|
|
2556
|
+
return {
|
|
2557
|
+
ok: result.exitCode === 0 && !result.timedOut,
|
|
2558
|
+
finalText: lastResultText(result.stdout),
|
|
2559
|
+
...report ? { report } : {},
|
|
2560
|
+
exitCode: result.exitCode,
|
|
2561
|
+
raw: result.stdout
|
|
2562
|
+
};
|
|
2563
|
+
}
|
|
2564
|
+
};
|
|
2565
|
+
/** Reads the final `result` event's text, or the last assistant message, from a Claude stream-json transcript. */
|
|
2566
|
+
function lastResultText(stdout) {
|
|
2567
|
+
let last = "";
|
|
2568
|
+
for (const line of stdout.split("\n")) {
|
|
2569
|
+
if (!line.trim()) continue;
|
|
2570
|
+
try {
|
|
2571
|
+
const event = JSON.parse(line);
|
|
2572
|
+
if (event.type === "result" && typeof event.result === "string") last = event.result;
|
|
2573
|
+
else if (event.type === "assistant") {
|
|
2574
|
+
const text = event.message?.content?.filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
|
|
2575
|
+
if (text) last = text;
|
|
2576
|
+
}
|
|
2577
|
+
} catch {}
|
|
2578
|
+
}
|
|
2579
|
+
return last;
|
|
2580
|
+
}
|
|
2581
|
+
// src/agents/codex.ts
|
|
2582
|
+
/** Runs a task on Codex CLI (`codex exec`), which prints JSONL events and can write its last message to a file. */
|
|
2583
|
+
var CodexRunner = class {
|
|
2584
|
+
binary;
|
|
2585
|
+
name = "codex";
|
|
2586
|
+
constructor(binary = "codex") {
|
|
2587
|
+
this.binary = binary;
|
|
2588
|
+
}
|
|
2589
|
+
async available() {
|
|
2590
|
+
return (await runProcess(this.binary, ["--version"], {
|
|
2591
|
+
cwd: process.cwd(),
|
|
2592
|
+
env: { ...process.env },
|
|
2593
|
+
stdin: "",
|
|
2594
|
+
signal: AbortSignal.timeout(1e4)
|
|
2595
|
+
})).exitCode === 0;
|
|
2596
|
+
}
|
|
2597
|
+
async run(run) {
|
|
2598
|
+
const lastMessage = join(run.cwd, ".superagent", "codex-last-message.txt");
|
|
2599
|
+
const argv = [
|
|
2600
|
+
"exec",
|
|
2601
|
+
"--sandbox",
|
|
2602
|
+
"danger-full-access",
|
|
2603
|
+
"--skip-git-repo-check",
|
|
2604
|
+
"--json",
|
|
2605
|
+
"-o",
|
|
2606
|
+
lastMessage,
|
|
2607
|
+
"-C",
|
|
2608
|
+
run.cwd,
|
|
2609
|
+
...run.model ? ["-m", run.model] : [],
|
|
2610
|
+
"-"
|
|
2611
|
+
];
|
|
2612
|
+
const result = await runProcess(this.binary, argv, {
|
|
2613
|
+
cwd: run.cwd,
|
|
2614
|
+
env: run.env,
|
|
2615
|
+
stdin: run.prompt,
|
|
2616
|
+
signal: run.signal,
|
|
2617
|
+
timeoutMs: run.timeoutMs
|
|
2618
|
+
});
|
|
2619
|
+
const finalText = await readFile(lastMessage, "utf8").catch(() => "");
|
|
2620
|
+
await rm(lastMessage, { force: true });
|
|
2621
|
+
const report = await readReport(run.cwd);
|
|
2622
|
+
return {
|
|
2623
|
+
ok: result.exitCode === 0 && !result.timedOut,
|
|
2624
|
+
finalText: finalText.trim() || lastAssistantMessage(result.stdout),
|
|
2625
|
+
...report ? { report } : {},
|
|
2626
|
+
exitCode: result.exitCode,
|
|
2627
|
+
raw: result.stdout
|
|
2628
|
+
};
|
|
2629
|
+
}
|
|
2630
|
+
};
|
|
2631
|
+
/** Reads the last `agent_message` item from a Codex JSONL stream, for when no last-message file was written. */
|
|
2632
|
+
function lastAssistantMessage(stdout) {
|
|
2633
|
+
let found = "";
|
|
2634
|
+
for (const line of stdout.split("\n")) {
|
|
2635
|
+
if (!line.trim()) continue;
|
|
2636
|
+
try {
|
|
2637
|
+
const event = JSON.parse(line);
|
|
2638
|
+
if (event.type === "item.completed" && event.item?.type === "agent_message" && typeof event.item.text === "string") found = event.item.text;
|
|
2639
|
+
} catch {}
|
|
2640
|
+
}
|
|
2641
|
+
return found;
|
|
2642
|
+
}
|
|
2643
|
+
// src/agents/opencode.ts
|
|
2644
|
+
/** Runs a task on opencode (`opencode run`), which prints JSON events with `--format json`. */
|
|
2645
|
+
var OpencodeRunner = class {
|
|
2646
|
+
binary;
|
|
2647
|
+
name = "opencode";
|
|
2648
|
+
constructor(binary = "opencode") {
|
|
2649
|
+
this.binary = binary;
|
|
2650
|
+
}
|
|
2651
|
+
async available() {
|
|
2652
|
+
return (await runProcess(this.binary, ["--version"], {
|
|
2653
|
+
cwd: process.cwd(),
|
|
2654
|
+
env: { ...process.env },
|
|
2655
|
+
stdin: "",
|
|
2656
|
+
signal: AbortSignal.timeout(1e4)
|
|
2657
|
+
})).exitCode === 0;
|
|
2658
|
+
}
|
|
2659
|
+
async run(run) {
|
|
2660
|
+
const argv = [
|
|
2661
|
+
"run",
|
|
2662
|
+
"--format",
|
|
2663
|
+
"json",
|
|
2664
|
+
"--dir",
|
|
2665
|
+
run.cwd,
|
|
2666
|
+
...run.model ? ["--model", run.model] : [],
|
|
2667
|
+
"-"
|
|
2668
|
+
];
|
|
2669
|
+
const result = await runProcess(this.binary, argv, {
|
|
2670
|
+
cwd: run.cwd,
|
|
2671
|
+
env: run.env,
|
|
2672
|
+
stdin: run.prompt,
|
|
2673
|
+
signal: run.signal,
|
|
2674
|
+
timeoutMs: run.timeoutMs
|
|
2675
|
+
});
|
|
2676
|
+
const report = await readReport(run.cwd);
|
|
2677
|
+
return {
|
|
2678
|
+
ok: result.exitCode === 0 && !result.timedOut,
|
|
2679
|
+
finalText: lastText(result.stdout),
|
|
2680
|
+
...report ? { report } : {},
|
|
2681
|
+
exitCode: result.exitCode,
|
|
2682
|
+
raw: result.stdout
|
|
2683
|
+
};
|
|
2684
|
+
}
|
|
2685
|
+
};
|
|
2686
|
+
/** Reads the last assistant text part from an opencode JSON event stream. */
|
|
2687
|
+
function lastText(stdout) {
|
|
2688
|
+
let last = "";
|
|
2689
|
+
for (const line of stdout.split("\n")) {
|
|
2690
|
+
if (!line.trim()) continue;
|
|
2691
|
+
try {
|
|
2692
|
+
const event = JSON.parse(line);
|
|
2693
|
+
if (event.type === "text" && typeof event.part?.text === "string") last = event.part.text;
|
|
2694
|
+
} catch {}
|
|
2695
|
+
}
|
|
2696
|
+
return last;
|
|
2697
|
+
}
|
|
2698
|
+
// src/agents/index.ts
|
|
2699
|
+
/**
|
|
2700
|
+
* The runner registry: which coding-agent CLIs a configuration may name, and how a name becomes a runner.
|
|
2701
|
+
*
|
|
2702
|
+
* Adding an agent means one file that implements `AgentRunner` and one line in `RUNNERS`. Nothing else in the project knows
|
|
2703
|
+
* which agent ran a ticket, which is what keeps the rest of the system portable.
|
|
2704
|
+
*/
|
|
2705
|
+
const FACTORIES = {
|
|
2706
|
+
claude: () => new ClaudeRunner(),
|
|
2707
|
+
codex: () => new CodexRunner(),
|
|
2708
|
+
opencode: () => new OpencodeRunner()
|
|
2709
|
+
};
|
|
2710
|
+
const AGENT_NAMES = Object.keys(FACTORIES);
|
|
2711
|
+
/** Builds the runner a configuration names. */
|
|
2712
|
+
function runnerFor(name, binary) {
|
|
2713
|
+
if (binary) {
|
|
2714
|
+
const Runner = {
|
|
2715
|
+
claude: ClaudeRunner,
|
|
2716
|
+
codex: CodexRunner,
|
|
2717
|
+
opencode: OpencodeRunner
|
|
2718
|
+
}[name];
|
|
2719
|
+
return new Runner(binary);
|
|
2720
|
+
}
|
|
2721
|
+
return FACTORIES[name]();
|
|
2722
|
+
}
|
|
2723
|
+
/** Which registered agents are installed, for `superagent doctor`. */
|
|
2724
|
+
async function installed() {
|
|
2725
|
+
const entries = await Promise.all(AGENT_NAMES.map(async (name) => [name, await runnerFor(name).available()]));
|
|
2726
|
+
return Object.fromEntries(entries);
|
|
2727
|
+
}
|
|
2728
|
+
// src/settings.ts
|
|
2729
|
+
/**
|
|
2730
|
+
* The whole configuration of an installation, in one file a person can read and edit.
|
|
2731
|
+
*
|
|
2732
|
+
* `settings.yaml` sits beside the state so `cat` answers "how is this set up". The parser below accepts the small YAML
|
|
2733
|
+
* subset a configuration needs — mappings, sequences, scalars, block strings — rather than adding a YAML dependency to a
|
|
2734
|
+
* tool that runs from a checkout. Writing uses the same subset, so round trips stay readable.
|
|
2735
|
+
*/
|
|
2736
|
+
const ExecutorSchema = z.object({
|
|
2737
|
+
/** Which coding agent runs a ticket. */
|
|
2738
|
+
agent: z.enum(AGENT_NAMES).default("claude"),
|
|
2739
|
+
/** The CLI to start for that agent; defaults to the agent's own name on PATH. */
|
|
2740
|
+
binary: z.string().optional(),
|
|
2741
|
+
/** The model argument, when the agent takes one. */
|
|
2742
|
+
model: z.string().optional(),
|
|
2743
|
+
/** How long a round waits for the event stream to send its first line, since a push may arrive at once. */
|
|
2744
|
+
streamIdleMs: z.number().int().min(1).max(6e4).default(300),
|
|
2745
|
+
/** How many tickets may run at once. */
|
|
2746
|
+
maxWorkers: z.number().int().min(1).max(16).default(1),
|
|
2747
|
+
/** A ticket that runs longer than this is stopped. */
|
|
2748
|
+
timeoutMinutes: z.number().int().min(1).max(720).default(60),
|
|
2749
|
+
/** Shell command that prepares a worktree; `$DSH_SUPERAGENT_*` variables are set before it runs. */
|
|
2750
|
+
prepare: z.string().default(""),
|
|
2751
|
+
/** Commands a ticket may not run. */
|
|
2752
|
+
blockedCommands: z.array(z.string()).default([])
|
|
2753
|
+
});
|
|
2754
|
+
const RuleSchema = z.object({
|
|
2755
|
+
/** The id an assessment names; `unasked` is reserved for the verdict that a message asks for work at all. */
|
|
2756
|
+
id: z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/, "lowercase letters, digits, _ and -"),
|
|
2757
|
+
name: z.string().min(1),
|
|
2758
|
+
enabled: z.boolean().default(true),
|
|
2759
|
+
/** What kind of work the rule admits, in the words the assessor reads. */
|
|
2760
|
+
instruction: z.string().min(1)
|
|
2761
|
+
});
|
|
2762
|
+
/** Proactive work: whether an unaddressed message of the owner may become a ticket, and the rules that bound it. */
|
|
2763
|
+
const PolicySchema = z.object({
|
|
2764
|
+
/** `off` never assesses an unaddressed message, `observe` records what it would accept, `auto` accepts it. */
|
|
2765
|
+
mode: z.enum([
|
|
2766
|
+
"off",
|
|
2767
|
+
"observe",
|
|
2768
|
+
"auto"
|
|
2769
|
+
]).default("observe"),
|
|
2770
|
+
rules: z.array(RuleSchema).default([])
|
|
2771
|
+
});
|
|
2772
|
+
const SettingsSchema = z.object({
|
|
2773
|
+
/** Where tickets, triggers and logs live, as an absolute path. */
|
|
2774
|
+
stateDir: z.string().min(1),
|
|
2775
|
+
/** The directory whose clone each ticket's worktree comes from. */
|
|
2776
|
+
checkout: z.string().min(1),
|
|
2777
|
+
github: z.object({
|
|
2778
|
+
enabled: z.boolean().default(true),
|
|
2779
|
+
repository: z.string().regex(/^[\w.-]+\/[\w.-]+$/, "expected owner/name"),
|
|
2780
|
+
/** The CLI that acts as the agent's account, such as `gh-agent`. */
|
|
2781
|
+
cli: z.string().default("gh"),
|
|
2782
|
+
/** How often to poll notifications, in seconds. */
|
|
2783
|
+
pollSeconds: z.number().int().min(15).max(3600).default(60),
|
|
2784
|
+
/** GitHub logins that may ask for work. Empty accepts nobody. */
|
|
2785
|
+
allowed: z.array(z.string()).default([])
|
|
2786
|
+
}).optional(),
|
|
2787
|
+
feishu: z.object({
|
|
2788
|
+
enabled: z.boolean().default(true),
|
|
2789
|
+
/** The CLI that acts as the bot. */
|
|
2790
|
+
cli: z.string().default("lark-cli"),
|
|
2791
|
+
/** Chats to listen to, by id, with the display name the agent uses when it mentions them. */
|
|
2792
|
+
chats: z.array(z.object({
|
|
2793
|
+
chatId: z.string(),
|
|
2794
|
+
name: z.string()
|
|
2795
|
+
})).default([]),
|
|
2796
|
+
/** Whether a direct message to the bot may become a ticket. */
|
|
2797
|
+
directMessages: z.boolean().default(true),
|
|
2798
|
+
/** Feishu open ids that may ask for work; `syncChat`, when set, fills this list from the chat's members. */
|
|
2799
|
+
allowed: z.array(z.string()).default([]),
|
|
2800
|
+
syncChat: z.string().optional()
|
|
2801
|
+
}).optional(),
|
|
2802
|
+
executor: ExecutorSchema.optional().transform((value) => ExecutorSchema.parse(value ?? {})),
|
|
2803
|
+
policy: PolicySchema.optional().transform((value) => PolicySchema.parse(value ?? {})),
|
|
2804
|
+
/** Who assesses a candidate and with what: the `claude` CLI, or a runner named here. */
|
|
2805
|
+
assess: z.object({
|
|
2806
|
+
agent: z.enum(AGENT_NAMES).default("claude"),
|
|
2807
|
+
binary: z.string().optional(),
|
|
2808
|
+
model: z.string().optional()
|
|
2809
|
+
}).optional().transform((value) => ({
|
|
2810
|
+
agent: "claude",
|
|
2811
|
+
...value
|
|
2812
|
+
})),
|
|
2813
|
+
/** Branch names the agent pushes, as a prefix followed by the ticket's short name. */
|
|
2814
|
+
branchPrefix: z.string().default("agent/"),
|
|
2815
|
+
/** The operator's own instructions, appended to every ticket's prompt in their words. */
|
|
2816
|
+
prompts: z.string().default("")
|
|
2817
|
+
});
|
|
2818
|
+
/** The default an installation starts from, for `superagent init`. */
|
|
2819
|
+
function defaultSettings(cwd, home) {
|
|
2820
|
+
return SettingsSchema.parse({
|
|
2821
|
+
stateDir: join(home, ".superagent"),
|
|
2822
|
+
checkout: cwd,
|
|
2823
|
+
executor: {}
|
|
2824
|
+
});
|
|
2825
|
+
}
|
|
2826
|
+
const SETTINGS_FILE = "settings.yaml";
|
|
2827
|
+
async function readSettings(path) {
|
|
2828
|
+
let text;
|
|
2829
|
+
try {
|
|
2830
|
+
text = await readFile(path, "utf8");
|
|
2831
|
+
} catch (error) {
|
|
2832
|
+
throw new Error(`No configuration at ${path}; run \`superagent init\` there first.`, { cause: error });
|
|
2833
|
+
}
|
|
2834
|
+
const parsed = SettingsSchema.safeParse(parseYaml(text));
|
|
2835
|
+
if (!parsed.success) throw new Error(`The configuration at ${path} is invalid:\n${formatIssues(parsed.error)}`);
|
|
2836
|
+
return parsed.data;
|
|
2837
|
+
}
|
|
2838
|
+
async function writeSettings(path, settings) {
|
|
2839
|
+
await writeFile(path, [
|
|
2840
|
+
"# superagent configuration",
|
|
2841
|
+
"# Edit by hand or through `superagent config set <path> <value>`.",
|
|
2842
|
+
"",
|
|
2843
|
+
stringifyYaml(settings),
|
|
2844
|
+
""
|
|
2845
|
+
].join("\n"), "utf8");
|
|
2846
|
+
}
|
|
2847
|
+
function formatIssues(error) {
|
|
2848
|
+
return error.issues.map((issue) => ` ${issue.path.join(".") || "(root)"}: ${issue.message}`).join("\n");
|
|
2849
|
+
}
|
|
2850
|
+
/** Parses the configuration subset; indentation must be spaces and tabs are refused. */
|
|
2851
|
+
function parseYaml(text) {
|
|
2852
|
+
const lines = text.split("\n");
|
|
2853
|
+
let index = 0;
|
|
2854
|
+
const indentOf = (line) => line.length - line.trimStart().length;
|
|
2855
|
+
const isSkippable = (line) => !line.trim() || line.trimStart().startsWith("#");
|
|
2856
|
+
function parseBlock(indent) {
|
|
2857
|
+
while (index < lines.length && isSkippable(lines[index])) index++;
|
|
2858
|
+
if (index >= lines.length || indentOf(lines[index]) < indent) return null;
|
|
2859
|
+
const line = lines[index];
|
|
2860
|
+
if (line.trimStart().startsWith("- ")) return parseSequence(indentOf(line));
|
|
2861
|
+
return parseMapping(indentOf(line));
|
|
2862
|
+
}
|
|
2863
|
+
function parseSequence(indent) {
|
|
2864
|
+
const items = [];
|
|
2865
|
+
while (index < lines.length) {
|
|
2866
|
+
const line = lines[index];
|
|
2867
|
+
if (isSkippable(line)) {
|
|
2868
|
+
index++;
|
|
2869
|
+
continue;
|
|
2870
|
+
}
|
|
2871
|
+
if (indentOf(line) < indent) break;
|
|
2872
|
+
if (indentOf(line) > indent) throw new Error(`Unexpected indentation on line ${index + 1}`);
|
|
2873
|
+
const trimmed = line.trimStart();
|
|
2874
|
+
if (!trimmed.startsWith("- ")) break;
|
|
2875
|
+
const rest = trimmed.slice(2).trim();
|
|
2876
|
+
index++;
|
|
2877
|
+
if (!rest) {
|
|
2878
|
+
items.push(parseBlock(indent + 2));
|
|
2879
|
+
continue;
|
|
2880
|
+
}
|
|
2881
|
+
if (/^[\w.-]+:(\s|$)/.test(rest)) {
|
|
2882
|
+
lines[index - 1] = " ".repeat(indent + 2) + rest;
|
|
2883
|
+
index--;
|
|
2884
|
+
items.push(parseMapping(indent + 2));
|
|
2885
|
+
continue;
|
|
2886
|
+
}
|
|
2887
|
+
items.push(scalar(rest));
|
|
2888
|
+
}
|
|
2889
|
+
return items;
|
|
2890
|
+
}
|
|
2891
|
+
function parseMapping(indent) {
|
|
2892
|
+
const map = {};
|
|
2893
|
+
while (index < lines.length) {
|
|
2894
|
+
const line = lines[index];
|
|
2895
|
+
if (isSkippable(line)) {
|
|
2896
|
+
index++;
|
|
2897
|
+
continue;
|
|
2898
|
+
}
|
|
2899
|
+
if (indentOf(line) < indent) break;
|
|
2900
|
+
if (indentOf(line) > indent) throw new Error(`Unexpected indentation on line ${index + 1}`);
|
|
2901
|
+
const trimmed = line.trimStart();
|
|
2902
|
+
const match = /^([\w.$-]+):(?:\s+(.*))?$/.exec(trimmed);
|
|
2903
|
+
if (!match) throw new Error(`Cannot read line ${index + 1}: ${trimmed}`);
|
|
2904
|
+
const [, name, rest = ""] = match;
|
|
2905
|
+
index++;
|
|
2906
|
+
if (rest === "|") {
|
|
2907
|
+
const body = [];
|
|
2908
|
+
while (index < lines.length && (!lines[index].trim() || indentOf(lines[index]) > indent)) {
|
|
2909
|
+
body.push(lines[index].slice(indent + 2));
|
|
2910
|
+
index++;
|
|
2911
|
+
}
|
|
2912
|
+
map[name] = body.join("\n").replace(/\n+$/, "");
|
|
2913
|
+
} else if (rest.trim() === "") {
|
|
2914
|
+
while (index < lines.length && isSkippable(lines[index])) index++;
|
|
2915
|
+
const next = lines[index];
|
|
2916
|
+
map[name] = next && indentOf(next) > indent ? parseBlock(indentOf(next)) : null;
|
|
2917
|
+
} else map[name] = scalar(rest.trim());
|
|
2918
|
+
}
|
|
2919
|
+
return map;
|
|
2920
|
+
}
|
|
2921
|
+
return parseBlock(0) ?? {};
|
|
2922
|
+
}
|
|
2923
|
+
function scalar(text) {
|
|
2924
|
+
if (text === "null" || text === "~" || text === "") return null;
|
|
2925
|
+
if (text === "true") return true;
|
|
2926
|
+
if (text === "false") return false;
|
|
2927
|
+
if (/^-?\d+$/.test(text)) return Number(text);
|
|
2928
|
+
if (text.startsWith("\"") || text.startsWith("'")) try {
|
|
2929
|
+
return JSON.parse(text.startsWith("'") ? `"${text.slice(1, -1).replace(/"/g, "\\\"")}"` : text);
|
|
2930
|
+
} catch {
|
|
2931
|
+
return text.slice(1, -1);
|
|
2932
|
+
}
|
|
2933
|
+
if (text.startsWith("[") && text.endsWith("]")) {
|
|
2934
|
+
const body = text.slice(1, -1).trim();
|
|
2935
|
+
return body ? body.split(",").map((item) => scalar(item.trim())) : [];
|
|
2936
|
+
}
|
|
2937
|
+
if (text.startsWith("{") && text.endsWith("}")) {
|
|
2938
|
+
const body = text.slice(1, -1).trim();
|
|
2939
|
+
if (!body) return {};
|
|
2940
|
+
return Object.fromEntries(body.split(",").map((pair) => {
|
|
2941
|
+
const [name, ...value] = pair.split(":");
|
|
2942
|
+
return [name.trim(), scalar(value.join(":").trim())];
|
|
2943
|
+
}));
|
|
2944
|
+
}
|
|
2945
|
+
return text;
|
|
2946
|
+
}
|
|
2947
|
+
/** Writes the same subset back, quoting only what would otherwise read as something else. */
|
|
2948
|
+
function stringifyYaml(value, indent = 0) {
|
|
2949
|
+
const pad = " ".repeat(indent);
|
|
2950
|
+
if (value === null || value === void 0) return "null";
|
|
2951
|
+
if (typeof value === "boolean" || typeof value === "number") return String(value);
|
|
2952
|
+
if (typeof value === "string") return needsQuote(value) ? JSON.stringify(value) : value;
|
|
2953
|
+
if (Array.isArray(value)) {
|
|
2954
|
+
if (value.length === 0) return "[]";
|
|
2955
|
+
return value.map((item) => {
|
|
2956
|
+
const nested = stringifyYaml(item, indent + 2);
|
|
2957
|
+
return typeof item === "object" && item !== null ? `${pad}- ${nested.slice(indent + 2)}` : `${pad}- ${nested}`;
|
|
2958
|
+
}).join("\n");
|
|
2959
|
+
}
|
|
2960
|
+
const entries = Object.entries(value).filter(([, item]) => item !== void 0);
|
|
2961
|
+
if (entries.length === 0) return "{}";
|
|
2962
|
+
return entries.map(([name, item]) => {
|
|
2963
|
+
if (item !== null && typeof item === "object" && (Array.isArray(item) ? item.length > 0 : Object.keys(item).length > 0)) return `${pad}${name}:\n${stringifyYaml(item, indent + 2)}`;
|
|
2964
|
+
return `${pad}${name}: ${stringifyYaml(item, indent + 2)}`;
|
|
2965
|
+
}).join("\n");
|
|
2966
|
+
}
|
|
2967
|
+
const needsQuote = (text) => text === "" || /^[\s"'-]|[:#]|\s$|^(true|false|null|~|-?\d+(\.\d+)?)$/.test(text);
|
|
2968
|
+
export { ticketStage as A, readUntil as B, escapeRegExp as C, reasonText as D, REASONS as E, isoTime as F, waitsForPerson as G, settled as H, latestAssignment as I, latestReport as L, USER_ERRORS as M, UserError as N, said as O, followupOwners as P, liveTicket as R, writeEnvironment as S, Engine as T, threadKey as U, runningAssignment as V, ticketOutcome as W, AdmissionDirectionSchema as _, readSettings as a, directionAllowed as b, AGENT_NAMES as c, REPORT_FILE as d, readReport as f, readState as g, FileRepositories as h, parseYaml as i, key as j, canRetry as k, installed as l, runProcess as m, SettingsSchema as n, stringifyYaml as o, reportInstructions as p, defaultSettings as r, writeSettings as s, SETTINGS_FILE as t, runnerFor as u, RuleAssessmentSchema as v, sameName as w, runEnvironment as x, RuleMatchSchema as y, reached as z };
|