@microvac/plugin-task-routing 0.0.0-stage → 0.1.0-rc.30

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/src/router.js ADDED
@@ -0,0 +1,376 @@
1
+ // @ts-check
2
+ /**
3
+ * The routing loop of the `task-routing` plugin: reacts to task events,
4
+ * sweeps for missed tasks, asks the decider and applies the answers through
5
+ * the server's task routing port (`server/src/microvac/task-routing/port.ts`).
6
+ */
7
+ import {
8
+ adapterConfigFor,
9
+ allowlistKey,
10
+ buildRequest,
11
+ candidatesFor,
12
+ isConfident,
13
+ KEEP_MODEL,
14
+ NO_PROJECT,
15
+ normalizeSettings,
16
+ percent,
17
+ questionsFor,
18
+ readChoice,
19
+ routedComment,
20
+ } from "./routing.js";
21
+
22
+ /**
23
+ * @typedef {import("./routing.js").Task} Task
24
+ * @typedef {import("./routing.js").Agent} Agent
25
+ * @typedef {import("./routing.js").Project} Project
26
+ * @typedef {import("./routing.js").CompanySettings} CompanySettings
27
+ * @typedef {import("./routing.js").AllowlistEntry} AllowlistEntry
28
+ * @typedef {{ assigneeAgentId?: string, projectId?: string, adapterConfig?: Record<string, unknown> }} RoutingPatch
29
+ * @typedef {{ action: string, comment: string | null, details: Record<string, unknown> }} RoutingTrace
30
+ * @typedef {{ questionId: string, optionIds: string[] }} CardAnswer
31
+ * @typedef {{
32
+ * status: "succeeded", invocationId: string, answers: Record<string, import("./routing.js").Answer>,
33
+ * } | { status: "unavailable", reason: string } | { status: "failed", invocationId: string, errorCode: string }} DecisionResult
34
+ * @typedef {{
35
+ * companies(): Promise<string[]>,
36
+ * settings(companyId: string): Promise<unknown>,
37
+ * task(companyId: string, issueId: string): Promise<Task | null>,
38
+ * eligibleTaskIds(companyId: string, limit: number): Promise<string[]>,
39
+ * ancestorProjectId(companyId: string, issueId: string): Promise<string | null>,
40
+ * lastUnassignedAgentId(companyId: string, issueId: string): Promise<string | null>,
41
+ * routedBefore(companyId: string, issueId: string): Promise<boolean>,
42
+ * pendingCard(companyId: string, issueId: string): Promise<boolean>,
43
+ * agents(companyId: string): Promise<Agent[]>,
44
+ * projects(companyId: string): Promise<Project[]>,
45
+ * decide(companyId: string, issueId: string, request: unknown): Promise<DecisionResult>,
46
+ * apply(companyId: string, issueId: string, patch: RoutingPatch, trace: RoutingTrace): Promise<boolean>,
47
+ * postCard(companyId: string, issueId: string, card: { idempotencyKey: string, title: string, payload: unknown }): Promise<string | null>,
48
+ * card(companyId: string, interactionId: string): Promise<{ issueId: string, idempotencyKey: string | null, answers: CardAnswer[] } | null>,
49
+ * hesitation(companyId: string, issueId: string, interactionId: string): Promise<Record<string, unknown> | null>,
50
+ * log(companyId: string, issueId: string, action: string, details: Record<string, unknown>): Promise<void>,
51
+ * }} TaskRoutingPort
52
+ * @typedef {"applied" | "hesitated" | "failed" | "unavailable" | "skipped"} Outcome
53
+ */
54
+
55
+ export const CARD_KEY_PREFIX = "task-routing:";
56
+ const SWEEP_BATCH = 25;
57
+ const CARD_OPTIONS = 3;
58
+ /** Activity actions this plugin writes. */
59
+ export const ACTIONS = Object.freeze({
60
+ applied: "task_routing.applied",
61
+ hesitated: "task_routing.hesitated",
62
+ failed: "task_routing.failed",
63
+ });
64
+
65
+ /** Task fields whose change can make a task (in)eligible. */
66
+ const ROUTING_FIELDS = ["status", "assigneeAgentId", "assigneeUserId"];
67
+
68
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
69
+ function isRecord(value) {
70
+ return typeof value === "object" && value !== null && !Array.isArray(value);
71
+ }
72
+
73
+ export class TaskRouter {
74
+ /**
75
+ * @param {TaskRoutingPort} port
76
+ * @param {{ debounceMs?: number, logger?: { warn(data: unknown, message?: string): void } }} [options]
77
+ */
78
+ constructor(port, options = {}) {
79
+ this.port = port;
80
+ this.debounceMs = options.debounceMs ?? 1500;
81
+ this.logger = options.logger ?? console;
82
+ /** @type {Set<string>} */
83
+ this.inFlight = new Set();
84
+ /** @type {Map<string, ReturnType<typeof setTimeout>>} */
85
+ this.timers = new Map();
86
+ this.stopped = false;
87
+ /** @type {Promise<unknown> | null} */
88
+ this.sweeping = null;
89
+ }
90
+
91
+ stop() {
92
+ this.stopped = true;
93
+ for (const timer of this.timers.values()) clearTimeout(timer);
94
+ this.timers.clear();
95
+ }
96
+
97
+ /**
98
+ * A company live event. Task creations and status / assignee changes
99
+ * schedule a routing; an answered task routing card applies its choice.
100
+ * @param {{ companyId: string, type: string, payload: Record<string, unknown> }} event
101
+ */
102
+ handleEvent(event) {
103
+ if (this.stopped || event.type !== "activity.logged") return;
104
+ const payload = event.payload;
105
+ if (payload.entityType !== "issue" || typeof payload.entityId !== "string") return;
106
+ const details = isRecord(payload.details) ? payload.details : {};
107
+ if (payload.action === "issue.created") {
108
+ this.schedule(event.companyId, payload.entityId);
109
+ } else if (payload.action === "issue.updated") {
110
+ if (ROUTING_FIELDS.some((field) => field in details)) this.schedule(event.companyId, payload.entityId);
111
+ } else if (payload.action === "issue.thread_interaction_answered" && typeof details.interactionId === "string") {
112
+ void this.guard(this.answer(event.companyId, details.interactionId));
113
+ }
114
+ }
115
+
116
+ /** @param {string} companyId @param {string} issueId */
117
+ schedule(companyId, issueId) {
118
+ const existing = this.timers.get(issueId);
119
+ if (existing) clearTimeout(existing);
120
+ const timer = setTimeout(() => {
121
+ this.timers.delete(issueId);
122
+ void this.guard(this.route(companyId, issueId));
123
+ }, this.debounceMs);
124
+ /** @type {{ unref?: () => void }} */ (/** @type {unknown} */ (timer)).unref?.();
125
+ this.timers.set(issueId, timer);
126
+ }
127
+
128
+ /** @template T @param {Promise<T>} work */
129
+ async guard(work) {
130
+ try {
131
+ return await work;
132
+ } catch (error) {
133
+ this.logger.warn({ err: error }, "task routing failed");
134
+ return undefined;
135
+ }
136
+ }
137
+
138
+ /** Routes the eligible tasks of every enabled company, a batch per company. */
139
+ sweep() {
140
+ if (this.sweeping) return this.sweeping;
141
+ this.sweeping = (async () => {
142
+ try {
143
+ for (const companyId of await this.port.companies()) {
144
+ if (this.stopped) return;
145
+ const settings = normalizeSettings(await this.port.settings(companyId));
146
+ if (!settings.enabled) continue;
147
+ for (const issueId of await this.port.eligibleTaskIds(companyId, SWEEP_BATCH)) {
148
+ if (this.stopped) return;
149
+ const outcome = await this.guard(this.route(companyId, issueId));
150
+ // The decision model is off for this company: the next sweep retries.
151
+ if (outcome === "unavailable") break;
152
+ }
153
+ }
154
+ } finally {
155
+ this.sweeping = null;
156
+ }
157
+ })();
158
+ return this.sweeping;
159
+ }
160
+
161
+ /**
162
+ * Routes one task: inherits a project, asks the decider, applies its answers
163
+ * in one update or follows the hesitation policy.
164
+ * @param {string} companyId
165
+ * @param {string} issueId
166
+ * @returns {Promise<Outcome>}
167
+ */
168
+ async route(companyId, issueId) {
169
+ if (this.inFlight.has(issueId)) return "skipped";
170
+ this.inFlight.add(issueId);
171
+ try {
172
+ return await this.routeOnce(companyId, issueId);
173
+ } finally {
174
+ this.inFlight.delete(issueId);
175
+ }
176
+ }
177
+
178
+ /** @param {string} companyId @param {string} issueId @returns {Promise<Outcome>} */
179
+ async routeOnce(companyId, issueId) {
180
+ const settings = normalizeSettings(await this.port.settings(companyId));
181
+ if (!settings.enabled) return "skipped";
182
+ let task = await this.port.task(companyId, issueId);
183
+ if (!task || task.status !== "todo") return "skipped";
184
+
185
+ if (settings.projectRouting && task.parentId && !task.projectId && !task.hidden) {
186
+ const inherited = await this.port.ancestorProjectId(companyId, issueId);
187
+ if (inherited) {
188
+ await this.port.apply(companyId, issueId, { projectId: inherited }, {
189
+ action: ACTIONS.applied,
190
+ comment: null,
191
+ details: { projectId: inherited, source: "ancestor" },
192
+ });
193
+ task = await this.port.task(companyId, issueId);
194
+ if (!task) return "skipped";
195
+ }
196
+ }
197
+
198
+ const assigned = Boolean(task.assigneeAgentId || task.assigneeUserId);
199
+ const alreadyTriedProject = assigned ? await this.port.routedBefore(companyId, issueId) : false;
200
+ const questions = questionsFor(task, { settings, alreadyTriedProject });
201
+ if (!questions) return "skipped";
202
+ if (questions.assignee && (await this.port.pendingCard(companyId, issueId))) return "skipped";
203
+
204
+ const agents = questions.assignee ? await this.port.agents(companyId) : [];
205
+ const removed = questions.assignee ? await this.port.lastUnassignedAgentId(companyId, issueId) : null;
206
+ const candidates = candidatesFor(agents, removed ? [removed] : []);
207
+ if (questions.assignee && candidates.length === 0) {
208
+ await this.port.log(companyId, issueId, ACTIONS.failed, { reason: "no_candidates" });
209
+ return "failed";
210
+ }
211
+ const projects = questions.project ? await this.port.projects(companyId) : [];
212
+ if (questions.project && projects.length === 0) questions.project = false;
213
+ // A single candidate needs no decision (a choice needs two options).
214
+ const sole = questions.assignee && candidates.length === 1 ? candidates[0] : null;
215
+ const routingAssignee = questions.assignee;
216
+ const asked = { ...questions, assignee: questions.assignee && !sole };
217
+ if (!routingAssignee && !asked.project) return "skipped";
218
+
219
+ const request = buildRequest({ task, questions: asked, candidates, projects, allowlist: settings.allowlist });
220
+ /** @type {DecisionResult} */
221
+ let result = { status: "succeeded", invocationId: "", answers: {} };
222
+ if (Object.keys(request.questions).length > 0) {
223
+ result = await this.port.decide(companyId, issueId, request);
224
+ if (result.status === "unavailable") return "unavailable";
225
+ if (result.status === "failed") {
226
+ await this.port.log(companyId, issueId, ACTIONS.failed, { reason: result.errorCode, invocationId: result.invocationId });
227
+ return "failed";
228
+ }
229
+ }
230
+ const answers = result.answers;
231
+
232
+ const assignee = sole
233
+ ? { choice: sole.id, top: 1, ranked: [{ key: sole.id, probability: 1 }] }
234
+ : asked.assignee
235
+ ? readChoice(answers.assignee, Object.keys(request.questions.assignee?.criteria ?? {}))
236
+ : null;
237
+ const project = asked.project ? readChoice(answers.project, Object.keys(request.questions.project?.criteria ?? {})) : null;
238
+ const runSettings = asked.runSettings
239
+ ? readChoice(answers.runSettings, Object.keys(request.questions.runSettings?.criteria ?? {}))
240
+ : null;
241
+ if ((routingAssignee && !assignee) || (asked.project && !project) || (asked.runSettings && !runSettings)) {
242
+ await this.port.log(companyId, issueId, ACTIONS.failed, { reason: "invalid_answer", invocationId: result.invocationId });
243
+ return "failed";
244
+ }
245
+
246
+ /** @type {RoutingPatch} */
247
+ const patch = {};
248
+ /** @type {Record<string, unknown>} */
249
+ const details = result.invocationId ? { invocationId: result.invocationId } : {};
250
+ let projectName = null;
251
+ if (project && project.choice !== NO_PROJECT && isConfident(project, settings)) {
252
+ patch.projectId = project.choice;
253
+ projectName = projects.find((entry) => entry.id === project.choice)?.name ?? null;
254
+ details.projectId = project.choice;
255
+ details.projectProbability = project.top;
256
+ }
257
+ /** @type {AllowlistEntry | null} */
258
+ let entry = null;
259
+ if (runSettings && runSettings.choice !== KEEP_MODEL && isConfident(runSettings, settings)) {
260
+ entry = settings.allowlist.find((candidate) => allowlistKey(candidate) === runSettings.choice) ?? null;
261
+ if (entry) {
262
+ patch.adapterConfig = adapterConfigFor(entry);
263
+ details.runSettings = { model: entry.model, effort: entry.effort };
264
+ }
265
+ }
266
+
267
+ if (!assignee) {
268
+ // Project-only question on an assigned root task.
269
+ if (!patch.projectId) {
270
+ await this.port.log(companyId, issueId, ACTIONS.hesitated, { ...details, question: "project" });
271
+ return "hesitated";
272
+ }
273
+ const applied = await this.port.apply(companyId, issueId, patch, {
274
+ action: ACTIONS.applied,
275
+ comment: routedComment({ project: projectName }),
276
+ details,
277
+ });
278
+ return applied ? "applied" : "skipped";
279
+ }
280
+
281
+ const nameOf = (/** @type {string} */ id) => agents.find((agent) => agent.id === id)?.name ?? id;
282
+ const next = assignee.ranked.find((option) => option.key !== assignee.choice);
283
+ details.agentProbability = assignee.top;
284
+ if (isConfident(assignee, settings)) {
285
+ const applied = await this.port.apply(companyId, issueId, { ...patch, assigneeAgentId: assignee.choice }, {
286
+ action: ACTIONS.applied,
287
+ comment: routedComment({
288
+ agent: { name: nameOf(assignee.choice), probability: assignee.top },
289
+ next: next && next.probability > 0 ? { name: nameOf(next.key), probability: next.probability } : null,
290
+ project: projectName,
291
+ runSettings: entry,
292
+ }),
293
+ details: { ...details, agentId: assignee.choice },
294
+ });
295
+ return applied ? "applied" : "skipped";
296
+ }
297
+
298
+ const ranking = assignee.ranked.map((option) => ({ agentId: option.key, probability: option.probability }));
299
+ const fallback =
300
+ settings.hesitation === "fallback-agent" && settings.fallbackAgentId
301
+ ? candidatesFor(agents, []).find((agent) => agent.id === settings.fallbackAgentId) ?? null
302
+ : null;
303
+ if (fallback) {
304
+ const applied = await this.port.apply(companyId, issueId, { ...patch, assigneeAgentId: fallback.id }, {
305
+ action: ACTIONS.hesitated,
306
+ comment: routedComment({ agent: { name: fallback.name, probability: assignee.top }, fallback: true, project: projectName, runSettings: entry }),
307
+ details: { ...details, policy: "fallback-agent", agentId: fallback.id, ranking: ranking.slice(0, CARD_OPTIONS) },
308
+ });
309
+ return applied ? "applied" : "skipped";
310
+ }
311
+
312
+ const top = assignee.ranked.slice(0, CARD_OPTIONS);
313
+ const interactionId = await this.port.postCard(companyId, issueId, {
314
+ idempotencyKey: `${CARD_KEY_PREFIX}${issueId}:${result.invocationId}`,
315
+ title: "Who should take this task?",
316
+ payload: {
317
+ version: 1,
318
+ title: "Who should take this task?",
319
+ submitLabel: "Assign",
320
+ questions: [
321
+ {
322
+ id: "assignee",
323
+ prompt: "Task routing is not confident enough to assign this task. Pick the agent.",
324
+ selectionMode: "single",
325
+ required: true,
326
+ options: top.map((option) => {
327
+ const agent = agents.find((candidate) => candidate.id === option.key);
328
+ return {
329
+ id: option.key,
330
+ label: `${agent?.name ?? option.key} (${percent(option.probability)})`,
331
+ ...(agent?.title ? { description: agent.title } : {}),
332
+ };
333
+ }),
334
+ },
335
+ ],
336
+ },
337
+ });
338
+ await this.port.log(companyId, issueId, ACTIONS.hesitated, {
339
+ ...details,
340
+ policy: "decision-card",
341
+ interactionId,
342
+ ranking: ranking.slice(0, CARD_OPTIONS),
343
+ ...(patch.adapterConfig ? { adapterConfig: patch.adapterConfig } : {}),
344
+ });
345
+ return "hesitated";
346
+ }
347
+
348
+ /**
349
+ * An answered task routing card: assigns the chosen agent, with the
350
+ * project and run settings decided at hesitation time, in one update.
351
+ * @param {string} companyId
352
+ * @param {string} interactionId
353
+ * @returns {Promise<Outcome>}
354
+ */
355
+ async answer(companyId, interactionId) {
356
+ const card = await this.port.card(companyId, interactionId);
357
+ if (!card || !card.idempotencyKey?.startsWith(CARD_KEY_PREFIX)) return "skipped";
358
+ const agentId = card.answers.find((answer) => answer.questionId === "assignee")?.optionIds[0];
359
+ if (!agentId) return "skipped";
360
+ const task = await this.port.task(companyId, card.issueId);
361
+ if (!task || task.assigneeAgentId || task.assigneeUserId) return "skipped";
362
+ const agent = (await this.port.agents(companyId)).find((candidate) => candidate.id === agentId);
363
+ if (!agent) return "skipped";
364
+ const hesitation = (await this.port.hesitation(companyId, card.issueId, interactionId)) ?? {};
365
+ /** @type {RoutingPatch} */
366
+ const patch = { assigneeAgentId: agent.id };
367
+ if (typeof hesitation.projectId === "string" && !task.projectId) patch.projectId = hesitation.projectId;
368
+ if (isRecord(hesitation.adapterConfig)) patch.adapterConfig = hesitation.adapterConfig;
369
+ const applied = await this.port.apply(companyId, card.issueId, patch, {
370
+ action: ACTIONS.applied,
371
+ comment: `Routed to ${agent.name} (chosen on the decision card)`,
372
+ details: { source: "decision-card", interactionId, agentId: agent.id, ...(patch.projectId ? { projectId: patch.projectId } : {}) },
373
+ });
374
+ return applied ? "applied" : "skipped";
375
+ }
376
+ }
package/src/routing.js ADDED
@@ -0,0 +1,298 @@
1
+ // @ts-check
2
+ /**
3
+ * Pure routing rules of the `task-routing` plugin (`docs/microvac/task-routing.md`):
4
+ * eligibility, candidates, the decider request, reading its answers against
5
+ * the thresholds, and the English trace. No I/O here: `router.js` drives it.
6
+ */
7
+
8
+ /**
9
+ * @typedef {{ model: string, effort: string | null, whenToUse?: string }} AllowlistEntry
10
+ * @typedef {{
11
+ * enabled: boolean,
12
+ * minProbability: number,
13
+ * minMargin: number,
14
+ * hesitation: "decision-card" | "fallback-agent",
15
+ * fallbackAgentId: string | null,
16
+ * allowlist: AllowlistEntry[],
17
+ * projectRouting: boolean,
18
+ * }} CompanySettings
19
+ * @typedef {{
20
+ * id: string, companyId: string, identifier: string | null, title: string, description: string | null,
21
+ * status: string, assigneeAgentId: string | null, assigneeUserId: string | null,
22
+ * projectId: string | null, parentId: string | null, originKind: string, labels: string[],
23
+ * hidden: boolean, runSettingsSetByHuman: boolean,
24
+ * }} Task
25
+ * @typedef {{ id: string, name: string, title: string | null, capabilities: string | null, status: string, model: string | null, effort: string | null }} Agent
26
+ * @typedef {{ id: string, name: string, description: string | null }} Project
27
+ * @typedef {{ assignee: boolean, project: boolean, runSettings: boolean }} Questions
28
+ */
29
+
30
+ export const NO_AUTO_ROUTE_LABEL = "no-auto-route";
31
+ export const ROUTINE_EXECUTION = "routine_execution";
32
+ export const NO_PROJECT = "none";
33
+ export const KEEP_MODEL = "keep";
34
+ /** Decision model service limit on the serialized request. */
35
+ export const MAX_REQUEST_BYTES = 32_000;
36
+ /** Service limits on one `choice` question. */
37
+ const MAX_OPTIONS = 20;
38
+ const MAX_CRITERION_CHARS = 2000;
39
+ const MAX_OPTION_KEY_CHARS = 100;
40
+ const MAX_STATE_TEXT_CHARS = 6000;
41
+
42
+ /** @type {CompanySettings} */
43
+ export const DEFAULT_SETTINGS = Object.freeze({
44
+ enabled: false,
45
+ minProbability: 0.7,
46
+ minMargin: 0.15,
47
+ hesitation: "decision-card",
48
+ fallbackAgentId: null,
49
+ allowlist: [],
50
+ projectRouting: true,
51
+ });
52
+
53
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
54
+ function isRecord(value) {
55
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56
+ }
57
+
58
+ /** @param {unknown} value @param {number} fallback */
59
+ function unitInterval(value, fallback) {
60
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1 ? value : fallback;
61
+ }
62
+
63
+ /** @param {unknown} value @returns {string | null} */
64
+ function text(value) {
65
+ return typeof value === "string" && value.trim() ? value.trim() : null;
66
+ }
67
+
68
+ /**
69
+ * A company's stored settings with defaults filled in; anything malformed
70
+ * falls back to its default.
71
+ * @param {unknown} raw
72
+ * @returns {CompanySettings}
73
+ */
74
+ export function normalizeSettings(raw) {
75
+ const value = isRecord(raw) ? raw : {};
76
+ /** @type {AllowlistEntry[]} */
77
+ const allowlist = [];
78
+ if (Array.isArray(value.allowlist)) {
79
+ for (const entry of value.allowlist) {
80
+ if (!isRecord(entry)) continue;
81
+ const model = text(entry.model);
82
+ if (!model) continue;
83
+ const whenToUse = text(entry.whenToUse);
84
+ allowlist.push({ model, effort: text(entry.effort), ...(whenToUse ? { whenToUse } : {}) });
85
+ }
86
+ }
87
+ return {
88
+ enabled: value.enabled === true,
89
+ minProbability: unitInterval(value.minProbability, DEFAULT_SETTINGS.minProbability),
90
+ minMargin: unitInterval(value.minMargin, DEFAULT_SETTINGS.minMargin),
91
+ hesitation: value.hesitation === "fallback-agent" ? "fallback-agent" : "decision-card",
92
+ fallbackAgentId: text(value.fallbackAgentId),
93
+ allowlist,
94
+ projectRouting: value.projectRouting !== false,
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Which questions a task needs, or null when routing leaves it alone.
100
+ * `alreadyTriedProject`: the project-only question is asked once per task.
101
+ * @param {Task} task
102
+ * @param {{ settings: CompanySettings, alreadyTriedProject: boolean }} options
103
+ * @returns {Questions | null}
104
+ */
105
+ export function questionsFor(task, { settings, alreadyTriedProject }) {
106
+ if (task.hidden || task.originKind === ROUTINE_EXECUTION) return null;
107
+ if (task.labels.some((label) => label.trim().toLowerCase() === NO_AUTO_ROUTE_LABEL)) return null;
108
+ if (task.status !== "todo") return null;
109
+ const askProject = settings.projectRouting && !task.projectId && !task.parentId;
110
+ if (task.assigneeAgentId || task.assigneeUserId) {
111
+ // A root task already assigned but without project: only the project question, once.
112
+ return askProject && !alreadyTriedProject ? { assignee: false, project: true, runSettings: false } : null;
113
+ }
114
+ return {
115
+ assignee: true,
116
+ project: askProject,
117
+ runSettings: settings.allowlist.length > 0 && !task.runSettingsSetByHuman,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Agents a task can go to: every company agent but paused, terminated or
123
+ * pending approval ones (agents in error stay), minus the excluded ones.
124
+ * @param {Agent[]} agents
125
+ * @param {Iterable<string>} excluded
126
+ */
127
+ export function candidatesFor(agents, excluded) {
128
+ const skip = new Set(excluded);
129
+ return agents.filter(
130
+ (agent) => !skip.has(agent.id) && agent.status !== "paused" && agent.status !== "terminated" && agent.status !== "pending_approval",
131
+ );
132
+ }
133
+
134
+ /** @param {string} value @param {number} max */
135
+ function truncate(value, max) {
136
+ return value.length <= max ? value : `${value.slice(0, Math.max(0, max - 1)).trimEnd()}…`;
137
+ }
138
+
139
+ /** @param {Agent} agent @param {number} cap */
140
+ export function routingCard(agent, cap) {
141
+ const head = agent.title ? `${agent.name} — ${agent.title}` : agent.name;
142
+ const body = agent.capabilities?.trim() || "No routing card.";
143
+ return truncate(`${head}. ${body}`, cap);
144
+ }
145
+
146
+ /** @param {AllowlistEntry} entry */
147
+ export function allowlistKey(entry) {
148
+ return truncate(entry.effort ? `${entry.model}@${entry.effort}` : entry.model, MAX_OPTION_KEY_CHARS);
149
+ }
150
+
151
+ /** @param {AllowlistEntry} entry */
152
+ export function allowlistLabel(entry) {
153
+ return entry.effort ? `${entry.model} · ${entry.effort}` : entry.model;
154
+ }
155
+
156
+ /**
157
+ * The decider request: one `choice` question per needed decision, routing
158
+ * cards capped so the whole request stays under the service limit.
159
+ * @param {{ task: Task, questions: Questions, candidates: Agent[], projects: Project[], allowlist: AllowlistEntry[] }} input
160
+ */
161
+ export function buildRequest({ task, questions, candidates, projects, allowlist }) {
162
+ const state = {
163
+ task: {
164
+ identifier: task.identifier,
165
+ title: task.title,
166
+ description: truncate(task.description ?? "", MAX_STATE_TEXT_CHARS),
167
+ },
168
+ };
169
+ /** @param {number} cardCap */
170
+ const build = (cardCap) => {
171
+ /** @type {Record<string, { type: "choice", instructions: string, criteria: Record<string, string> }>} */
172
+ const decisionQuestions = {};
173
+ if (questions.assignee) {
174
+ decisionQuestions.assignee = {
175
+ type: "choice",
176
+ instructions:
177
+ "Pick the agent best suited to do this task, from their routing cards. Prefer the agent whose mission covers the request; answer with the agent's key.",
178
+ criteria: Object.fromEntries(candidates.slice(0, MAX_OPTIONS).map((agent) => [agent.id, routingCard(agent, cardCap)])),
179
+ };
180
+ }
181
+ if (questions.project) {
182
+ const listed = projects.slice(0, MAX_OPTIONS - 1);
183
+ decisionQuestions.project = {
184
+ type: "choice",
185
+ instructions: `Pick the project this task belongs to. Answer "${NO_PROJECT}" when no project clearly matches.`,
186
+ criteria: {
187
+ ...Object.fromEntries(
188
+ listed.map((project) => [
189
+ project.id,
190
+ truncate(project.description ? `${project.name}: ${project.description}` : project.name, Math.min(cardCap, MAX_CRITERION_CHARS)),
191
+ ]),
192
+ ),
193
+ [NO_PROJECT]: "No listed project matches this task.",
194
+ },
195
+ };
196
+ }
197
+ if (questions.runSettings) {
198
+ const listed = allowlist.slice(0, MAX_OPTIONS - 1);
199
+ decisionQuestions.runSettings = {
200
+ type: "choice",
201
+ instructions: `Pick the model and reasoning effort this task needs. Answer "${KEEP_MODEL}" when the agent's own model fits.`,
202
+ criteria: {
203
+ ...Object.fromEntries(
204
+ listed.map((entry) => [
205
+ allowlistKey(entry),
206
+ truncate(`${allowlistLabel(entry)}${entry.whenToUse ? `: ${entry.whenToUse}` : ""}`, MAX_CRITERION_CHARS),
207
+ ]),
208
+ ),
209
+ [KEEP_MODEL]: "Keep the agent's model and effort.",
210
+ },
211
+ };
212
+ }
213
+ return { state, questions: decisionQuestions };
214
+ };
215
+ let cap = MAX_CRITERION_CHARS;
216
+ let request = build(cap);
217
+ while (byteLength(request) > MAX_REQUEST_BYTES && cap > 80) {
218
+ cap = Math.floor(cap * 0.75);
219
+ request = build(cap);
220
+ }
221
+ if (byteLength(request) > MAX_REQUEST_BYTES) {
222
+ state.task.description = truncate(state.task.description, 500);
223
+ request = build(cap);
224
+ }
225
+ return request;
226
+ }
227
+
228
+ /** @param {unknown} value */
229
+ export function byteLength(value) {
230
+ return new TextEncoder().encode(JSON.stringify(value)).length;
231
+ }
232
+
233
+ /**
234
+ * @typedef {{ type: string, choice?: string, probabilities?: Record<string, number>, confidence?: number }} Answer
235
+ * @typedef {{ choice: string, top: number, ranked: { key: string, probability: number }[] }} Reading
236
+ */
237
+
238
+ /**
239
+ * Reads a `choice` answer: the chosen key must be one of the options;
240
+ * probabilities rank the options (missing ones: the confidence, else 0).
241
+ * Returns null for an invalid answer.
242
+ * @param {Answer | undefined} answer
243
+ * @param {string[]} options
244
+ * @returns {Reading | null}
245
+ */
246
+ export function readChoice(answer, options) {
247
+ if (!answer || answer.type !== "choice" || typeof answer.choice !== "string" || !options.includes(answer.choice)) return null;
248
+ const probabilities = isRecord(answer.probabilities) ? answer.probabilities : {};
249
+ const ranked = options
250
+ .map((key) => ({ key, probability: typeof probabilities[key] === "number" ? probabilities[key] : 0 }))
251
+ .sort((a, b) => b.probability - a.probability);
252
+ const chosen = ranked.find((entry) => entry.key === answer.choice);
253
+ let top = chosen?.probability ?? 0;
254
+ if (top === 0 && typeof answer.confidence === "number") top = answer.confidence;
255
+ return { choice: answer.choice, top, ranked };
256
+ }
257
+
258
+ /**
259
+ * Whether an answer clears the thresholds: top probability and margin over
260
+ * the best other option.
261
+ * @param {Reading} reading
262
+ * @param {Pick<CompanySettings, "minProbability" | "minMargin">} thresholds
263
+ */
264
+ export function isConfident(reading, thresholds) {
265
+ const second = reading.ranked.find((entry) => entry.key !== reading.choice)?.probability ?? 0;
266
+ return reading.top >= thresholds.minProbability && reading.top - second >= thresholds.minMargin;
267
+ }
268
+
269
+ /**
270
+ * The run settings an allowlist answer puts in `assigneeAdapterOverrides.adapterConfig`.
271
+ * The Hermes adapter reads `reasoningEffort`.
272
+ * @param {AllowlistEntry} entry
273
+ */
274
+ export function adapterConfigFor(entry) {
275
+ return { model: entry.model, ...(entry.effort ? { reasoningEffort: entry.effort } : {}) };
276
+ }
277
+
278
+ /** @param {number} value */
279
+ export function percent(value) {
280
+ return `${Math.round(value * 100)} %`;
281
+ }
282
+
283
+ /**
284
+ * The short English comment left on a routed task.
285
+ * @param {{ agent?: { name: string, probability: number } | null, next?: { name: string, probability: number } | null, project?: string | null, runSettings?: AllowlistEntry | null, fallback?: boolean }} trace
286
+ */
287
+ export function routedComment(trace) {
288
+ const parts = [];
289
+ if (trace.agent) {
290
+ const head = trace.fallback
291
+ ? `Routed to ${trace.agent.name} (fallback: no confident match)`
292
+ : `Routed to ${trace.agent.name} (${percent(trace.agent.probability)}${trace.next ? `, next: ${trace.next.name} ${percent(trace.next.probability)}` : ""})`;
293
+ parts.push(head);
294
+ }
295
+ if (trace.project) parts.push(trace.agent ? `project ${trace.project}` : `Routed to project ${trace.project}`);
296
+ if (trace.runSettings) parts.push(allowlistLabel(trace.runSettings));
297
+ return parts.join(" · ");
298
+ }