@agent-tasks/mcp-server 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/errors.js ADDED
@@ -0,0 +1,798 @@
1
+ // Teaching-error layer (block tier). Normative reference:
2
+ // docs/response-contract-v1.md's "Error shape (block tier)" section. A call
3
+ // that cannot proceed at all returns
4
+ // { ok: false, error: { code, message, recipe, allowedNext, detail? } }
5
+ // instead of a bare HTTP status or a backend error string forwarded
6
+ // verbatim. `recipe` names the concrete corrective call; `allowedNext` lists
7
+ // only verb names the caller can call immediately (machine-checkable,
8
+ // unlike the receipt layer's free-form `next[]` — see receipt.ts).
9
+ //
10
+ // mapBackendError(status, body, verbContext?) is the single entry point:
11
+ // tools.ts's wrap() is its only call site (mirrors receipt.ts's relationship
12
+ // to the receipt-projection helpers). `verbContext`, when supplied, is the
13
+ // calling tool's own registered name (e.g. "task_finish") — used only where
14
+ // the correct recipe genuinely depends on which verb was called (today:
15
+ // `precondition_failed`, which the live backend can raise from task_start,
16
+ // task_finish, and two deprecated v1 routes with different correct retry
17
+ // targets; and `cross_repo_pr_rejected`, whose pull_requests_create emit
18
+ // site sends owner/repo rather than a prUrl, so the default task_submit_pr
19
+ // recipe would misdirect it). Every other catalog entry is verb-independent
20
+ // by construction.
21
+ //
22
+ // Catalog seed (docs/response-contract-v1.md's "Catalog seed" list, plus
23
+ // pr_author_mismatch from the read_first context on backend/src/routes/
24
+ // tasks.ts): not_claimed, already_claimed, precondition_failed,
25
+ // cross_repo_pr_rejected, pr_author_mismatch, force_admin_only,
26
+ // respec_conflict, result_not_plain_string. Plus low_confidence (422, the
27
+ // pre-claim confidence gate on task_start / the deprecated tasks_claim,
28
+ // backend/src/services/confidence-gate.ts via backend/src/middleware/
29
+ // error.ts's lowConfidence helper): NOT in the contract's original seed
30
+ // list, added on review (rc-v1-C005 round 1) to close an information-loss
31
+ // gap the generic degrade path left on the highest-traffic verb — see
32
+ // lowConfidenceError below. Every other backend error degrades to the
33
+ // generic shape (status-derived code, message passthrough, recipe ->
34
+ // workflow_primer, and now also a clamped passthrough of any structured
35
+ // body.details — see genericDegrade) rather than being forwarded as raw
36
+ // text. rc-v1-C006 adds two more client-side-only entries for the
37
+ // projectSlug addressing feature: project_addressing_conflict and
38
+ // unknown_project_slug (see both below, near the end of the catalog
39
+ // section) — neither is a backend error mapBackendError ever sees.
40
+ //
41
+ // No em dashes in this file's exported/emitted prose (repo convention,
42
+ // enforced today only for primer.ts's exported strings, applied here too
43
+ // since these messages are caller-facing prose of the same kind).
44
+ //
45
+ // ── Response budget invariant ───────────────────────────────────────────
46
+ //
47
+ // INVARIANT: the serialized form of any TeachingError this module builds
48
+ // (serializeTeachingError's output, exactly what a caller receives) is
49
+ // always <= ERROR_BUDGET_CHARS (1200 chars, the wire-format size measured
50
+ // through serializeResult exactly as server.ts emits it) for arbitrary
51
+ // adversarial backend input. `code`, `message` (itself already clamped to
52
+ // MESSAGE_CHAR_BUDGET), `recipe` (clamped to RECIPE_CHAR_BUDGET), and
53
+ // `allowedNext` are always preserved WHOLE regardless of size, since the
54
+ // contract mandates all four unconditionally; `detail` is the one
55
+ // auxiliary field, and the only field this module ever sacrifices to hold
56
+ // the invariant.
57
+ //
58
+ // The per-field clamps below (DETAIL_CLAMP, DETAIL_KEY_CLAMP,
59
+ // DETAIL_ENTRY_CHAR_BUDGET, MESSAGE_CHAR_BUDGET, RECIPE_CHAR_BUDGET) each
60
+ // bound a single field, never their sum: several near-max fields at once
61
+ // (precondition_failed's failed[] with several entries, each carrying an
62
+ // optional `error` string alongside rule/message, or a wide generic
63
+ // `details` object) can still exceed the budget in total even when every
64
+ // individual field stayed within its own clamp. buildTeachingError's own
65
+ // enforceErrorBudget step is the single place that actually guarantees the
66
+ // TOTAL: it re-measures the whole serialized object after construction
67
+ // and, only when still over budget, first re-clamps `detail` harder (same
68
+ // recursive clamp, tighter limits), then, if that is still not enough,
69
+ // replaces `detail` entirely with a small, visible summary object instead
70
+ // of truncating it into something silently misleading or dropping it
71
+ // without a trace.
72
+ // ── Budget / clamp constants ────────────────────────────────────────────
73
+ //
74
+ // Mirrors receipt.ts's DETAIL_CLAMP / ENTRY_CHAR_BUDGET convention (same
75
+ // reason: an unclamped array or a long backend string can blow the response
76
+ // budget on its own). Kept local to this module rather than imported from
77
+ // receipt.ts since the two layers clamp different shapes (string[] there,
78
+ // {rule,message} objects here) and have independent budgets.
79
+ /** Max entries kept in a detail array before it is clamped + counted. */
80
+ const DETAIL_CLAMP = 5;
81
+ /** Max distinct keys kept in a detail OBJECT before it is clamped + counted
82
+ * (the object counterpart to DETAIL_CLAMP's array-entry cap). An object
83
+ * with many keys, or long key names, is exactly as capable of blowing the
84
+ * response budget as an oversized array or string, and per-VALUE clamping
85
+ * alone does nothing to bound key count or key-name length. */
86
+ const DETAIL_KEY_CLAMP = 12;
87
+ /** Per-entry char bound for a detail array's own string fields, and for a
88
+ * detail object's own key names and string values. */
89
+ const DETAIL_ENTRY_CHAR_BUDGET = 60;
90
+ /** Char bound for the top-level `message` and `recipe` strings — these can
91
+ * carry a raw backend message (a zod validation error, for one, can run to
92
+ * thousands of chars) or, for `recipe`, a hand-authored corrective sentence
93
+ * that must itself never grow into a prose blob. */
94
+ const MESSAGE_CHAR_BUDGET = 300;
95
+ const RECIPE_CHAR_BUDGET = 240;
96
+ const TRUNCATION_MARKER = "...";
97
+ /** Hard ceiling on the whole serialized teaching error (JSON.stringify(x,
98
+ * null, 2), the exact wire format serializeTeachingError/serializeResult
99
+ * emit). See the file header's "Response budget invariant" section: this
100
+ * is the number enforceErrorBudget (below) actually holds the line at,
101
+ * since the per-field clamps above only ever bound one field at a time. */
102
+ const ERROR_BUDGET_CHARS = 1200;
103
+ /** Tighter versions of DETAIL_CLAMP / DETAIL_KEY_CLAMP /
104
+ * DETAIL_ENTRY_CHAR_BUDGET, used only by enforceErrorBudget's second
105
+ * ("harder reclamp") pass, when the normal clamp still was not enough to
106
+ * bring the total under ERROR_BUDGET_CHARS. */
107
+ const HARD_DETAIL_CLAMP = 2;
108
+ const HARD_DETAIL_KEY_CLAMP = 3;
109
+ const HARD_DETAIL_ENTRY_CHAR_BUDGET = 20;
110
+ function clamp(value, maxChars) {
111
+ return value.length > maxChars
112
+ ? value.slice(0, maxChars - TRUNCATION_MARKER.length) + TRUNCATION_MARKER
113
+ : value;
114
+ }
115
+ function buildTeachingError(opts) {
116
+ const err = {
117
+ ok: false,
118
+ error: {
119
+ code: opts.code,
120
+ message: clamp(opts.message, MESSAGE_CHAR_BUDGET),
121
+ recipe: clamp(opts.recipe, RECIPE_CHAR_BUDGET),
122
+ allowedNext: opts.allowedNext,
123
+ ...(opts.detail ? { detail: opts.detail } : {}),
124
+ },
125
+ };
126
+ // Single choke point for every TeachingError this module ever constructs
127
+ // (every catalog entry, the generic degrade path, and
128
+ // resultMustBePlainStringError all call buildTeachingError): the response
129
+ // budget invariant documented in the file header is enforced HERE, not
130
+ // duplicated at each call site or bolted onto mapBackendError's return
131
+ // path, so a future catalog entry gets it for free. enforceErrorBudget is
132
+ // defined further down (near clampDetailValue, which it reuses); function
133
+ // declarations are hoisted, so the forward reference is fine.
134
+ return enforceErrorBudget(err);
135
+ }
136
+ /** Serializes a TeachingError exactly as server.ts's serializeResult would
137
+ * (JSON.stringify(x, null, 2) for a non-string result — a teaching error is
138
+ * always an object, never a string, so the two are always equal for this
139
+ * input). Defined locally rather than importing serializeResult from
140
+ * server.ts to avoid a circular import (server.ts -> tools.ts -> errors.ts);
141
+ * tests/errors.test.ts asserts the two stay equal for every catalog entry. */
142
+ export function serializeTeachingError(err) {
143
+ return JSON.stringify(err, null, 2);
144
+ }
145
+ function asBackendBody(body) {
146
+ return body && typeof body === "object" ? body : {};
147
+ }
148
+ function backendMessage(body, status) {
149
+ return typeof body.message === "string" && body.message.length > 0
150
+ ? body.message
151
+ : `request failed with status ${status}`;
152
+ }
153
+ // ── Catalog entries ─────────────────────────────────────────────────────
154
+ // 1. Acting without a claim. task_finish, task_submit_pr, and task_abandon
155
+ // all return 403 `forbidden` with a message matching this shape when the
156
+ // caller does not hold the claim on the task (backend/src/routes/tasks.ts:
157
+ // POST /tasks/:id/finish, POST /tasks/:id/submit-pr, POST
158
+ // /tasks/:id/abandon). The backend's own `error` code is the generic
159
+ // "forbidden" (shared with unrelated 403s like missing-scope and
160
+ // access-denied), so this catalog entry is message-pattern matched, not
161
+ // code matched, and mints its own more specific `not_claimed` code.
162
+ const NOT_CLAIMED_PATTERN = /do not hold .*claim/i;
163
+ function notClaimedError(message) {
164
+ return buildTeachingError({
165
+ code: "not_claimed",
166
+ message,
167
+ recipe: "call task_start to claim this task first",
168
+ allowedNext: ["task_start"],
169
+ });
170
+ }
171
+ // 2. Claim wall / solo multi-task. task_pickup and task_start both return
172
+ // 409 `already_claimed` when the caller already holds an active claim
173
+ // (backend/src/routes/tasks.ts: POST /tasks/pickup, POST
174
+ // /tasks/:id/start). The backend's own code is already specific, so it is
175
+ // kept verbatim as this entry's code.
176
+ function alreadyClaimedError(message) {
177
+ return buildTeachingError({
178
+ code: "already_claimed",
179
+ message,
180
+ recipe: "call task_finish or task_abandon on your current task before claiming another",
181
+ allowedNext: ["task_finish", "task_abandon"],
182
+ });
183
+ }
184
+ // 3. Branch precondition. task_start / task_finish / tasks_transition [POST
185
+ // /tasks/:id/transition] / (the two deprecated v1 routes tasks_update
186
+ // [PATCH /tasks/:id] and tasks_claim [POST /tasks/:id/claim]) all return 422
187
+ // `precondition_failed` with a structured `failed: [{rule, message, error?}]`
188
+ // array (backend/src/routes/tasks.ts, backend/src/services/transition-rules.ts:
189
+ // TransitionRule is exactly "branchPresent" | "prPresent" | "ciGreen" |
190
+ // "prMerged", so `failed` never actually exceeds 4 entries today). The
191
+ // per-rule detail is kept STRUCTURED (each rule named individually), not
192
+ // collapsed into the prose `message` the backend also sends (which
193
+ // concatenates every failing rule's own message into one string) — the
194
+ // outer `message` here is a short, own-authored summary instead, so a
195
+ // caller reading just `error.message` still gets something scannable.
196
+ //
197
+ // The clamp (DETAIL_CLAMP entries, DETAIL_ENTRY_CHAR_BUDGET chars each) is
198
+ // applied unconditionally, same as receipt.ts's DETAIL_CLAMP convention,
199
+ // even though the fixed 4-rule set means it can never actually bite against
200
+ // the live backend — a future rule addition, or a malformed/spoofed body in
201
+ // a test fixture, must not be able to blow the response budget. This clamp
202
+ // bounds each FIELD on its own, not the sum of all of them; the aggregate
203
+ // invariant that the WHOLE response never blows the budget is what
204
+ // buildTeachingError's enforceErrorBudget step (see the file header)
205
+ // actually guarantees, since several near-max failed[] entries at once can
206
+ // still add up past ERROR_BUDGET_CHARS even though each stayed clamped.
207
+ //
208
+ // The real backend's TransitionRule values (backend/src/services/
209
+ // transition-rules.ts) and their RULE_MESSAGES prose. That prose is
210
+ // diagnostic ("what's wrong"), not corrective ("what to do"): at
211
+ // DETAIL_ENTRY_CHAR_BUDGET (60 chars) every one of the four real messages
212
+ // gets clamped exactly where its instruction half starts (measured:
213
+ // branchPresent's own message truncates to "No branch recorded on this
214
+ // task. PATCH /api/tasks/:id with branchNam..."). Rather than truncate the
215
+ // corrective away, each known rule gets its own short, own-authored
216
+ // corrective here instead of the backend's message, kept whole. The
217
+ // truncating clamp is kept as the fallback for any OTHER rule name (a
218
+ // future rule addition, or a malformed/spoofed body in a test fixture), so
219
+ // the unconditional-clamp property above still holds for anything this
220
+ // module does not know about.
221
+ // Exported so tests/errors.test.ts can assert this map's key set stays in
222
+ // sync with the real backend's transition-rules.ts RULE_MESSAGES (a
223
+ // same-workspace-idiom drift guard, not a runtime consumer outside this
224
+ // module).
225
+ export const KNOWN_RULE_CORRECTIVES = {
226
+ branchPresent: "record the branch via task_submit_pr",
227
+ prPresent: "create the PR then task_submit_pr",
228
+ ciGreen: "wait for CI to pass on the PR",
229
+ prMerged: "merge the PR first",
230
+ };
231
+ function preconditionFailedError(body, verbContext) {
232
+ const rawFailed = Array.isArray(body.failed) ? body.failed : [];
233
+ const rules = rawFailed.map((f) => (typeof f.rule === "string" ? f.rule : "unknown"));
234
+ // `rule` is clamped even though the real backend's TransitionRule values
235
+ // are short: this function's input is untrusted response data, not a
236
+ // value this module controls, so a malformed/oversized `rule` string
237
+ // must not be able to blow the per-field budget either. Three near-max
238
+ // fields (rule/message/error) on several entries at once can still add
239
+ // up past the RESPONSE budget even with every field individually
240
+ // clamped here; buildTeachingError's enforceErrorBudget step is what
241
+ // actually holds that aggregate line (see the file header). `message`
242
+ // is the known rule's own-authored corrective (whole, never truncated)
243
+ // when the rule is one of the four real ones, or the backend's own
244
+ // message clamped otherwise (see KNOWN_RULE_CORRECTIVES above). The
245
+ // optional per-rule `error` field (present today on ciGreen/prMerged
246
+ // when the underlying GitHub call itself failed — e.g. "GitHub
247
+ // unreachable" vs. a clean "CI red", the only thing distinguishing the
248
+ // two) is included, clamped, whenever the backend actually sent one.
249
+ const clampedFailed = rawFailed.slice(0, DETAIL_CLAMP).map((f) => {
250
+ const rawRule = typeof f.rule === "string" ? f.rule : "unknown";
251
+ const rawMessage = typeof f.message === "string" ? f.message : "";
252
+ const corrective = KNOWN_RULE_CORRECTIVES[rawRule];
253
+ return {
254
+ rule: clamp(rawRule, DETAIL_ENTRY_CHAR_BUDGET),
255
+ message: corrective ?? clamp(rawMessage, DETAIL_ENTRY_CHAR_BUDGET),
256
+ ...(typeof f.error === "string" && f.error.length > 0
257
+ ? { error: clamp(f.error, DETAIL_ENTRY_CHAR_BUDGET) }
258
+ : {}),
259
+ };
260
+ });
261
+ const needsSubmitPr = rules.includes("branchPresent") || rules.includes("prPresent");
262
+ // task_finish is the contract's own documented context for this trap
263
+ // ("blocks task_finish with 422 precondition_failed") and the correct
264
+ // fallback for every call site this module does not thread verbContext
265
+ // through today (only task_start, task_finish, tasks_claim, tasks_update,
266
+ // and tasks_transition can actually raise this error; see tools.ts's
267
+ // wrap() call sites for those five).
268
+ const retryVerb = verbContext ?? "task_finish";
269
+ const recipe = needsSubmitPr
270
+ ? `run \`gh pr create\`, call task_submit_pr with the branch/PR metadata, then retry ${retryVerb}`
271
+ : `wait for the remaining precondition(s) to clear (see error.detail.failed), then retry ${retryVerb}`;
272
+ const allowedNext = needsSubmitPr ? ["task_submit_pr", retryVerb] : [retryVerb];
273
+ return buildTeachingError({
274
+ code: "precondition_failed",
275
+ message: rules.length > 0
276
+ ? `${rules.length} workflow gate${rules.length === 1 ? "" : "s"} not yet satisfied: ${rules
277
+ .slice(0, DETAIL_CLAMP)
278
+ .join(", ")}`
279
+ : "a workflow gate is not yet satisfied",
280
+ recipe,
281
+ allowedNext: Array.from(new Set(allowedNext)),
282
+ detail: { failed: clampedFailed, totalFailed: rawFailed.length },
283
+ });
284
+ }
285
+ // 4. cross_repo_pr_rejected. A prUrl (or, for pull_requests_create, an
286
+ // owner/repo pair) that does not point at project.githubRepo is rejected
287
+ // with 400 from four backend sites: POST /tasks/:id/submit-pr
288
+ // (task_submit_pr's own emit site), POST /tasks/:id/finish (a work-claim
289
+ // task_finish call that also carries prUrl), PATCH /tasks/:id (the
290
+ // deprecated tasks_update agent-write path), and, differently shaped, POST
291
+ // /pull-requests (backend/src/routes/github.ts, pull_requests_create's own
292
+ // emit site — rejected BEFORE a PR is even created on GitHub, from an
293
+ // owner/repo pair rather than a prUrl). Backend code kept verbatim; the
294
+ // recipe branches on verbContext because pull_requests_create's own caller
295
+ // sent owner/repo, not a prUrl (see crossRepoRejectedError below).
296
+ function crossRepoRejectedError(message, verbContext) {
297
+ if (verbContext === "pull_requests_create") {
298
+ return buildTeachingError({
299
+ code: "cross_repo_pr_rejected",
300
+ message,
301
+ recipe: "call pull_requests_create again with owner/repo matching this project's own repo",
302
+ allowedNext: ["pull_requests_create"],
303
+ });
304
+ }
305
+ return buildTeachingError({
306
+ code: "cross_repo_pr_rejected",
307
+ message,
308
+ recipe: "call task_submit_pr again with a prUrl on this project's own repo, or set deliverableRepo at create time when the deliverable is intentionally a different repo",
309
+ allowedNext: ["task_submit_pr"],
310
+ });
311
+ }
312
+ // 5. pr_author_mismatch. task_submit_pr rejects a prUrl whose PR was not
313
+ // authored by the delegation user, 403 (backend/src/routes/tasks.ts:
314
+ // POST /tasks/:id/submit-pr). Backend code kept verbatim.
315
+ function prAuthorMismatchError(message) {
316
+ return buildTeachingError({
317
+ code: "pr_author_mismatch",
318
+ message,
319
+ recipe: "open the PR under the delegation user's own GitHub login, then call task_submit_pr again with that prUrl",
320
+ allowedNext: ["task_submit_pr"],
321
+ });
322
+ }
323
+ // 6. transition force=admin-only. tasks_transition / POST
324
+ // /tasks/:id/transition { force: true } returns 403 `forbidden` for
325
+ // non-admins (backend/src/routes/tasks.ts: POST /tasks/:id/transition,
326
+ // message "Only team admins can force a transition"). Same generic backend
327
+ // code as not_claimed, message-pattern matched, own code minted. No self-service
328
+ // corrective call exists (this is genuinely an admin-only wall), so
329
+ // allowedNext is empty by design, not an oversight — the recipe itself
330
+ // still names the concrete action ("do not pass force:true"), satisfying
331
+ // the "never just 'invalid request'" rule without inventing a verb.
332
+ const FORCE_ADMIN_ONLY_PATTERN = /admins? can force a transition/i;
333
+ function forceAdminOnlyError(message) {
334
+ return buildTeachingError({
335
+ code: "force_admin_only",
336
+ message,
337
+ recipe: "do not pass force:true; only a project admin can use the force-transition escape hatch",
338
+ allowedNext: [],
339
+ });
340
+ }
341
+ // 7. Description immutability. task_respec only edits an OPEN, unclaimed
342
+ // task; any other state is rejected with 409 `conflict` (backend/src/
343
+ // routes/tasks.ts, RESPEC_STATE_CONFLICT_MESSAGE = "Task must be open and
344
+ // unclaimed to respec"). The backend's own code ("conflict") is shared with
345
+ // other unrelated 409s (middleware/error.ts's generic conflict() helper),
346
+ // so this entry is message-pattern matched and mints its own code.
347
+ const RESPEC_CONFLICT_PATTERN = /open and unclaimed to respec/i;
348
+ function respecConflictError(message) {
349
+ return buildTeachingError({
350
+ code: "respec_conflict",
351
+ message,
352
+ recipe: "task_respec only works on an open, unclaimed task; call task_abandon first if you hold the claim, then retry task_respec",
353
+ allowedNext: ["task_abandon", "task_respec"],
354
+ });
355
+ }
356
+ // 8. task_finish `result` (and the deprecated tasks_update's) as plain
357
+ // string. Unlike the other catalog entries, the backend performs NO
358
+ // validation of this today (`result` is stored verbatim as free text) —
359
+ // this trap exists only at the mcp-server layer, triggered locally in
360
+ // tools.ts's task_finish and tasks_update handlers BEFORE any request is
361
+ // sent, not mapped from a backend error. Exported separately (not reachable
362
+ // via mapBackendError, which only ever sees a real AgentTasksApiError) and
363
+ // paired with looksLikeStructuredWrapper, the detector tools.ts calls.
364
+ // Inline formatting tags a caller might legitimately use in ordinary prose
365
+ // (markdown-adjacent emphasis, e.g. "<b>Done</b>" as a whole result). A LONE
366
+ // pair using one of these is never, on its own, a structured-wrapper signal
367
+ // — see hasSuspiciousTagPair below. An unlisted tag (<result>, <Foo>, <div>,
368
+ // ...) is still suspect, and MULTIPLE tag pairs (even multiple inline-
369
+ // formatting ones) are still suspect: the allowance is deliberately scoped
370
+ // to a single lone pair.
371
+ const INLINE_FORMATTING_TAGS = new Set(["b", "i", "em", "strong", "code"]);
372
+ // Finds every non-overlapping complete "<tag ...>...</tag>" pair in a
373
+ // string (global, lazy inner match so a sibling pair right after a closing
374
+ // tag is found as its own match rather than the scan running past it to a
375
+ // later same-named closing tag).
376
+ const TAG_PAIR_PATTERN = /<([a-zA-Z][\w:-]*)\b[^>]*>[\s\S]*?<\/\1>/g;
377
+ // A pathological string (many '<' characters with no matching closing tag)
378
+ // can make TAG_PAIR_PATTERN's lazy, backtracking-capable inner match blow up
379
+ // combinatorially on long input (measured: ~18.4s scanning a single 400k-char
380
+ // adversarial string). tools.ts's task_finish and tasks_update both cap
381
+ // `result` at 5000 chars today, but this guard must not itself become the
382
+ // next unbounded-input path for some future caller that forgets to cap its
383
+ // own input before handing it to looksLikeStructuredWrapper, so it is
384
+ // bounded here too, defensively, independent of any caller-side cap. Only
385
+ // the leading TAG_SCAN_CHAR_LIMIT chars are scanned for a suspicious tag
386
+ // pair; a legitimate tag pair sitting entirely past that point in an
387
+ // already-pathologically-long value is missed, an accepted trade-off since a
388
+ // value that long is already well outside "plain prose result text"
389
+ // territory regardless.
390
+ const TAG_SCAN_CHAR_LIMIT = 6000;
391
+ /** True when `trimmed` contains a tag pair this guard treats as suspicious.
392
+ * Zero matches: never suspicious (plain prose that merely mentions an
393
+ * unclosed tag, e.g. "fixed the <Foo> component", never matches at all).
394
+ * More than one matched pair: always suspicious, regardless of tag name —
395
+ * a caller wrapping two separate pieces in their own tags (or repeating an
396
+ * inline-formatting tag) is exactly the kind of LLM mistake this guard
397
+ * exists to catch, so the inline-formatting allowance below is
398
+ * deliberately scoped to a LONE pair only. Exactly one matched pair: a
399
+ * lone INLINE_FORMATTING_TAGS pair is never suspicious (regardless of
400
+ * position — a bolded lead-in like "<b>Warning:</b> ..." is ordinary
401
+ * prose); any other single tag is suspicious only when it sits at the
402
+ * leading or trailing edge of the value (a whole-string wrap, a tag
403
+ * followed by trailing prose, or leading prose followed by a tag) — NOT
404
+ * when it is embedded mid-sentence with prose on both sides, which stays
405
+ * deliberately uncovered (indistinguishable from a caller quoting a
406
+ * tag-like token in normal prose; see tests/errors.test.ts's
407
+ * "embedded mid-sentence" case for the documented boundary). */
408
+ function hasSuspiciousTagPair(trimmed) {
409
+ const matches = Array.from(trimmed.matchAll(TAG_PAIR_PATTERN));
410
+ if (matches.length === 0)
411
+ return false;
412
+ if (matches.length > 1)
413
+ return true;
414
+ const [match] = matches;
415
+ const tag = match[1].toLowerCase();
416
+ if (INLINE_FORMATTING_TAGS.has(tag))
417
+ return false;
418
+ const start = match.index ?? 0;
419
+ const end = start + match[0].length;
420
+ return start === 0 || end === trimmed.length;
421
+ }
422
+ /** True when `value` (trimmed) looks like an LLM-style structured wrapper
423
+ * around what should be plain prose: an `<?xml` preamble, a fenced code
424
+ * block (the single most common mistake — wrapping the whole answer, or a
425
+ * JSON payload, in a \`\`\` / \`\`\`json fence), valid whole-string JSON, or
426
+ * a suspicious tag pair (see hasSuspiciousTagPair). Deliberately NOT
427
+ * triggered by a value that merely contains an angle bracket or a brace
428
+ * somewhere in ordinary prose, or by a single inline-formatting tag pair
429
+ * (e.g. a result of exactly "<b>Done</b>") — both stay legitimate prose. */
430
+ export function looksLikeStructuredWrapper(value) {
431
+ const trimmed = value.trim();
432
+ if (trimmed.length === 0)
433
+ return false;
434
+ // <?xml preamble: an LLM that started emitting an XML document.
435
+ if (/^<\?xml\b/i.test(trimmed))
436
+ return true;
437
+ // A fenced code block anywhere, so long as the fence starts at the
438
+ // beginning of a line — not just when it opens the whole string, since a
439
+ // caller often prefaces the fence with a sentence of prose.
440
+ if (/^```/m.test(trimmed))
441
+ return true;
442
+ if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
443
+ (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
444
+ try {
445
+ JSON.parse(trimmed);
446
+ return true;
447
+ }
448
+ catch {
449
+ // Starts/ends with a brace but is not valid JSON on its own — fall
450
+ // through to the tag-pair check below rather than assuming prose.
451
+ }
452
+ }
453
+ return hasSuspiciousTagPair(trimmed.length > TAG_SCAN_CHAR_LIMIT ? trimmed.slice(0, TAG_SCAN_CHAR_LIMIT) : trimmed);
454
+ }
455
+ export function resultMustBePlainStringError(verb = "task_finish") {
456
+ return buildTeachingError({
457
+ code: "result_not_plain_string",
458
+ message: "result must be plain prose or markdown text, not wrapped in XML or JSON tags",
459
+ recipe: `resubmit ${verb} with result as plain text (no <tag>...</tag> or {...} wrapping)`,
460
+ allowedNext: [verb],
461
+ });
462
+ }
463
+ // 9. low_confidence. task_start's (and the deprecated tasks_claim's)
464
+ // pre-claim confidence gate rejects a claim below the project's confidence
465
+ // threshold with 422 `low_confidence` (backend/src/services/
466
+ // confidence-gate.ts's evaluateConfidenceGate, via backend/src/middleware/
467
+ // error.ts's lowConfidence helper: POST /tasks/:id/start, POST
468
+ // /tasks/:id/claim). NOT in the contract's original catalog seed (see the
469
+ // file header above) — added on review because the generic degrade path
470
+ // was silently DROPPING body.details (score, threshold, missing[],
471
+ // nextActions) on this specific, highest-traffic verb: a caller saw only a
472
+ // generic message and a workflow_primer recipe, with no way to learn WHY
473
+ // the claim was blocked short of re-deriving it independently. task_respec
474
+ // is the contract's own documented corrective for CONFIDENCE_BELOW_THRESHOLD
475
+ // (docs/response-contract-v1.md's deviation catalog; receipt.ts's
476
+ // confidenceDeviation uses the same corrective for task_create/
477
+ // task_respec's own low-score case), so it is named here too.
478
+ function lowConfidenceError(body, message) {
479
+ const details = body.details && typeof body.details === "object" && !Array.isArray(body.details)
480
+ ? body.details
481
+ : {};
482
+ const score = typeof details.score === "number" ? details.score : undefined;
483
+ const threshold = typeof details.threshold === "number" ? details.threshold : undefined;
484
+ const rawMissing = Array.isArray(details.missing)
485
+ ? details.missing.filter((m) => typeof m === "string")
486
+ : [];
487
+ // Same DETAIL_CLAMP/DETAIL_ENTRY_CHAR_BUDGET convention as
488
+ // precondition_failed's `failed[]` above: the backend scorer can
489
+ // populate up to 9 field names (see receipt.ts's confidenceDeviation),
490
+ // already in surfacing-priority order.
491
+ const missing = rawMissing.slice(0, DETAIL_CLAMP).map((m) => clamp(m, DETAIL_ENTRY_CHAR_BUDGET));
492
+ return buildTeachingError({
493
+ code: "low_confidence",
494
+ message,
495
+ recipe: "call task_respec to raise the description/templateData above the confidence threshold, then retry",
496
+ allowedNext: ["task_respec"],
497
+ detail: {
498
+ ...(score !== undefined ? { score } : {}),
499
+ ...(threshold !== undefined ? { threshold } : {}),
500
+ missing,
501
+ totalMissing: rawMissing.length,
502
+ },
503
+ });
504
+ }
505
+ // 10. project_addressing_conflict / unknown_project_slug. rc-v1-C006's
506
+ // projectSlug alternative to projectId (task_create, and project_tasks via
507
+ // the same client-side resolver, client.ts's withResolvedProjectSlug):
508
+ // neither trap is a backend error the real API ever raises with these
509
+ // codes, so neither is reachable via mapBackendError below. Both are raised
510
+ // directly by the calling tool's own handler in tools.ts, same pattern as
511
+ // catalog entry #8 (resultMustBePlainStringError) — a client-side guard
512
+ // checked before, or in place of, any network call.
513
+ //
514
+ // project_addressing_conflict covers BOTH directions of the same "exactly
515
+ // one of projectId/projectSlug" requirement, not just "both provided":
516
+ // task_create's own client-side guard (tools.ts) also rejects the mirror-
517
+ // image mistake, neither field set. That case used to throw a bare,
518
+ // unteaching Error (rc-v1-C006 round-2 review, LOW) instead of going
519
+ // through this catalog. Rather than mint a second, near-duplicate code for
520
+ // what is really the same "exactly one" constraint violated the other way,
521
+ // `reason` selects direction-specific message/recipe/allowedNext under the
522
+ // SAME code: "both" needs no extra corrective (the caller already named
523
+ // both candidates, it just needs to pick one), but "neither" used to point
524
+ // at projects_list as the self-service way to find the project.
525
+ //
526
+ // rc-v1-C007 pruned projects_list out of the DEFAULT tool registration
527
+ // (tools.ts's LEGACY_VERB_NAMES); it is opt-in only via
528
+ // AGENT_TASKS_MCP_LEGACY=1 now. task_create and project_tasks (this
529
+ // catalog entry's only two real call sites) both stay in the default
530
+ // registration, so a default-mode caller can trip "neither_provided"
531
+ // without ever having projects_list available to them. `allowedNext` MUST
532
+ // list only verb names callable immediately (docs/response-contract-v1.md's
533
+ // error-shape section), so "neither"'s allowedNext no longer names
534
+ // projects_list unconditionally; `recipe` still mentions it, but only as
535
+ // the legacy-flag option, alongside the always-available "ask the
536
+ // operator" fallback.
537
+ export function projectAddressingConflictError(verb, reason = "both_provided") {
538
+ if (reason === "neither_provided") {
539
+ return buildTeachingError({
540
+ code: "project_addressing_conflict",
541
+ message: "neither projectId nor projectSlug was provided; pass exactly one",
542
+ recipe: `ask the operator for this project's slug or id (or, with AGENT_TASKS_MCP_LEGACY=1 set, call projects_list), then resubmit ${verb} with projectId or projectSlug set`,
543
+ allowedNext: [verb],
544
+ });
545
+ }
546
+ return buildTeachingError({
547
+ code: "project_addressing_conflict",
548
+ message: "projectId and projectSlug were both provided; pass exactly one",
549
+ recipe: `resubmit ${verb} with only one of projectId or projectSlug`,
550
+ allowedNext: [verb],
551
+ });
552
+ }
553
+ // Raised when client.ts's slug resolver gets a 404 on a FRESH (not
554
+ // cache-served) slug lookup — see client.ts's ProjectSlugNotFoundError and
555
+ // withResolvedProjectSlug. `recipe` used to name projects_list
556
+ // unconditionally as the concrete corrective call for "how do I find the
557
+ // actual available slugs". Same rc-v1-C007 constraint as
558
+ // projectAddressingConflictError above: projects_list is legacy-gated now,
559
+ // task_create and project_tasks (both default-registered) are this
560
+ // catalog entry's real call sites, so `allowedNext` no longer names it
561
+ // (only the calling verb does); `recipe` still offers it as the
562
+ // legacy-flag option alongside the always-available operator fallback.
563
+ export function unknownProjectSlugError(slug, verb) {
564
+ return buildTeachingError({
565
+ code: "unknown_project_slug",
566
+ message: `no project found for slug "${slug}"`,
567
+ recipe: "ask the operator for the correct project slug or id (or, with AGENT_TASKS_MCP_LEGACY=1 set, call projects_list to see the available slugs)",
568
+ allowedNext: [verb],
569
+ });
570
+ }
571
+ // ── Generic degrade path ────────────────────────────────────────────────
572
+ //
573
+ // Any backend error not matched by one of the catalog entries above
574
+ // degrades structurally instead of being forwarded as raw text: the code is
575
+ // derived from the HTTP status (NOT the backend's own `error` field — that
576
+ // field is only trustworthy as a catalog SIGNAL, matched explicitly above;
577
+ // echoing it verbatim here would silently grow the catalog by accident
578
+ // every time the backend adds a new code), the message is passed through
579
+ // (clamped), the recipe points at workflow_primer, the one call every
580
+ // caller can always make to recover — AND, when the backend body carried a
581
+ // structured `details` object, a clamped copy of it survives into
582
+ // `error.detail` instead of being dropped. Before this, any uncataloged
583
+ // error with a `details` payload (not just low_confidence, which is now
584
+ // its own catalog entry above) silently lost that payload; this closes the
585
+ // gap for the whole degrade class, not just the one verb that happened to
586
+ // earn its own catalog entry.
587
+ const GENERIC_DETAIL_MAX_DEPTH = 3;
588
+ /** Writes `key: value` into `out`, disambiguating on collision instead of
589
+ * silently overwriting the earlier entry. A collision here means two
590
+ * DISTINCT original keys clamped down to the identical truncated name
591
+ * (e.g. several keys sharing a long common prefix beyond the char
592
+ * budget). Without this, the second write would clobber the first with
593
+ * no trace, which is exactly the kind of silent data loss this whole
594
+ * module exists to avoid. */
595
+ function setClampedKey(out, key, value) {
596
+ if (!(key in out)) {
597
+ out[key] = value;
598
+ return;
599
+ }
600
+ let suffix = 2;
601
+ while (`${key}~${suffix}` in out)
602
+ suffix++;
603
+ out[`${key}~${suffix}`] = value;
604
+ }
605
+ /** Recursively clamps an arbitrary JSON-ish detail value: every string is
606
+ * char-clamped, every array is entry-clamped, and every object's key
607
+ * COUNT is entry-clamped too (an object with many keys, or long key
608
+ * names, is exactly as capable of blowing the response budget as an
609
+ * oversized array or string, and per-VALUE clamping alone does nothing to
610
+ * bound key count or key-name length). Surviving keys' NAMES are
611
+ * themselves char-clamped, colliding clamped names are disambiguated
612
+ * rather than overwritten (see setClampedKey), and a `totalKeys` marker
613
+ * is added whenever any key was dropped, so the drop is never silent.
614
+ * Kept values are clamped the same way, recursively. `depth` guards
615
+ * against a pathological/cyclic input from untrusted response data. */
616
+ function clampDetailValue(value, depth, opts = {}) {
617
+ const arrayClamp = opts.arrayClamp ?? DETAIL_CLAMP;
618
+ const keyClamp = opts.keyClamp ?? DETAIL_KEY_CLAMP;
619
+ const entryChars = opts.entryChars ?? DETAIL_ENTRY_CHAR_BUDGET;
620
+ if (depth > GENERIC_DETAIL_MAX_DEPTH)
621
+ return "[detail nested too deep, truncated]";
622
+ if (typeof value === "string")
623
+ return clamp(value, entryChars);
624
+ if (Array.isArray(value)) {
625
+ return value.slice(0, arrayClamp).map((v) => clampDetailValue(v, depth + 1, opts));
626
+ }
627
+ if (value && typeof value === "object") {
628
+ const entries = Object.entries(value);
629
+ const out = {};
630
+ for (const [k, v] of entries.slice(0, keyClamp)) {
631
+ setClampedKey(out, clamp(k, entryChars), clampDetailValue(v, depth + 1, opts));
632
+ }
633
+ if (entries.length > keyClamp)
634
+ out.totalKeys = entries.length;
635
+ return out;
636
+ }
637
+ // number, boolean, null, undefined: passed through unchanged.
638
+ return value;
639
+ }
640
+ /** Clamps a whole `details` object for the generic degrade path. Returns
641
+ * undefined (so buildTeachingError omits `detail` entirely) when the
642
+ * backend sent nothing usable — not an object, an array, or empty.
643
+ * Delegates straight to clampDetailValue (depth 0) rather than its own
644
+ * parallel key-walk: the top-level object needs exactly the same
645
+ * key-count/key-name clamping clampDetailValue's object branch already
646
+ * does for every NESTED object, so a wide top-level `details` (many keys,
647
+ * or long key names) and a wide NESTED object are both bounded by the one
648
+ * code path. */
649
+ function clampGenericDetail(details) {
650
+ if (!details || typeof details !== "object" || Array.isArray(details))
651
+ return undefined;
652
+ const out = clampDetailValue(details, 0);
653
+ return Object.keys(out).length > 0 ? out : undefined;
654
+ }
655
+ // Bookkeeping fields a catalog entry or clampDetailValue itself may already
656
+ // have set to record a TRUE original count (precondition_failed's
657
+ // totalFailed, low_confidence's totalMissing, clampDetailValue's own
658
+ // totalKeys). A second, harder clamp pass over an already-clamped object
659
+ // must not re-derive these from the intermediate object's own (already
660
+ // shrunk) entry count -- that would silently replace an accurate original
661
+ // count with a smaller, misleading one. See reclampDetailHarder below.
662
+ const DETAIL_TOTAL_MARKER_KEYS = ["totalFailed", "totalMissing", "totalKeys"];
663
+ /** Re-clamps a detail object with the HARD_* limits, WITHOUT letting the
664
+ * pass corrupt any totalFailed/totalMissing/totalKeys marker already
665
+ * present (see DETAIL_TOTAL_MARKER_KEYS): those numbers are pulled out
666
+ * first, the remaining data-bearing keys are clamped harder on their own,
667
+ * and the original markers are restored afterward, overwriting whatever
668
+ * (smaller, intermediate-count) marker clampDetailValue's own object
669
+ * branch may have added while re-clamping the rest. */
670
+ function reclampDetailHarder(detail) {
671
+ const preservedMarkers = {};
672
+ const rest = {};
673
+ for (const [k, v] of Object.entries(detail)) {
674
+ if (DETAIL_TOTAL_MARKER_KEYS.includes(k) && typeof v === "number") {
675
+ preservedMarkers[k] = v;
676
+ }
677
+ else {
678
+ rest[k] = v;
679
+ }
680
+ }
681
+ const reclampedRest = clampDetailValue(rest, 0, {
682
+ arrayClamp: HARD_DETAIL_CLAMP,
683
+ keyClamp: HARD_DETAIL_KEY_CLAMP,
684
+ entryChars: HARD_DETAIL_ENTRY_CHAR_BUDGET,
685
+ });
686
+ return { ...reclampedRest, ...preservedMarkers };
687
+ }
688
+ /** Enforces the response budget invariant documented in the file header.
689
+ * buildTeachingError's own per-field clamps (MESSAGE_CHAR_BUDGET,
690
+ * RECIPE_CHAR_BUDGET) and each catalog entry's own array/key clamps
691
+ * bound individual FIELDS, never their sum: several near-max fields at
692
+ * once can still exceed ERROR_BUDGET_CHARS in total. This is the one
693
+ * place that actually guarantees the total. `code`, `message`, `recipe`,
694
+ * and `allowedNext` are never touched here (the contract mandates them
695
+ * whole, regardless of size). Only `detail`, the one field the contract
696
+ * marks auxiliary, is ever degraded, and NEVER silently: first a harder
697
+ * recursive re-clamp (same clampDetailValue walk, tighter HARD_* limits),
698
+ * and, only if that still is not enough, a small visible summary object
699
+ * replaces `detail` entirely, so a caller always sees that something was
700
+ * omitted rather than getting a truncated, possibly-misleading fragment. */
701
+ function enforceErrorBudget(err) {
702
+ if (serializeTeachingError(err).length <= ERROR_BUDGET_CHARS)
703
+ return err;
704
+ if (err.error.detail) {
705
+ const reclamped = {
706
+ ...err,
707
+ error: {
708
+ ...err.error,
709
+ detail: reclampDetailHarder(err.error.detail),
710
+ },
711
+ };
712
+ if (serializeTeachingError(reclamped).length <= ERROR_BUDGET_CHARS)
713
+ return reclamped;
714
+ }
715
+ // Still over budget even after the harder reclamp (or there was no
716
+ // `detail` to reclamp at all): replace `detail` with a small, fixed-size
717
+ // summary instead of silently dropping or truncating it. `totalFailed` /
718
+ // `totalKeys` are carried over when cheaply available (already computed
719
+ // by the catalog entry or by clampDetailValue's own key-count marker)
720
+ // since a caller who cannot see the detail at least learns how much of
721
+ // it there was.
722
+ const priorDetail = err.error.detail;
723
+ const totalFailed = typeof priorDetail?.totalFailed === "number" ? priorDetail.totalFailed : undefined;
724
+ const totalMissing = typeof priorDetail?.totalMissing === "number" ? priorDetail.totalMissing : undefined;
725
+ const totalKeys = typeof priorDetail?.totalKeys === "number"
726
+ ? priorDetail.totalKeys
727
+ : priorDetail && typeof priorDetail === "object"
728
+ ? Object.keys(priorDetail).length
729
+ : undefined;
730
+ return {
731
+ ...err,
732
+ error: {
733
+ ...err.error,
734
+ detail: {
735
+ omitted: true,
736
+ reason: "detail exceeded the error budget",
737
+ ...(totalFailed !== undefined ? { totalFailed } : {}),
738
+ ...(totalMissing !== undefined ? { totalMissing } : {}),
739
+ ...(totalKeys !== undefined ? { totalKeys } : {}),
740
+ },
741
+ },
742
+ };
743
+ }
744
+ // The backend's own body.error string is the most specific code available
745
+ // and consumers key on it (the mcp-bridge governance suite asserts a 409
746
+ // claim_blocked stays visible end to end), so the degrade passes it
747
+ // through when present; the status-derived http_<status> form is only the
748
+ // fallback for bodies that carry no code at all. Clamped like every other
749
+ // caller-visible string so a pathological body cannot blow the budget.
750
+ function genericDegrade(status, message, details, bodyCode) {
751
+ const code = typeof bodyCode === "string" && bodyCode.length > 0
752
+ ? clamp(bodyCode, DETAIL_ENTRY_CHAR_BUDGET)
753
+ : `http_${status}`;
754
+ return buildTeachingError({
755
+ code,
756
+ message,
757
+ recipe: "call workflow_primer for the full lifecycle reference and today's known traps",
758
+ allowedNext: ["workflow_primer"],
759
+ detail: clampGenericDetail(details),
760
+ });
761
+ }
762
+ /**
763
+ * Maps a backend AgentTasksApiError's (status, body) to the teaching-error
764
+ * shape. `verbContext`, when supplied, is the calling tool's own registered
765
+ * name — see the precondition_failed catalog entry above for the one place
766
+ * it changes the output.
767
+ */
768
+ export function mapBackendError(status, rawBody, verbContext) {
769
+ const body = asBackendBody(rawBody);
770
+ const code = typeof body.error === "string" ? body.error : undefined;
771
+ const message = backendMessage(body, status);
772
+ if (status === 403 && code === "forbidden" && NOT_CLAIMED_PATTERN.test(message)) {
773
+ return notClaimedError(message);
774
+ }
775
+ if (status === 403 && code === "forbidden" && FORCE_ADMIN_ONLY_PATTERN.test(message)) {
776
+ return forceAdminOnlyError(message);
777
+ }
778
+ if (status === 409 && code === "already_claimed") {
779
+ return alreadyClaimedError(message);
780
+ }
781
+ if (status === 422 && code === "precondition_failed") {
782
+ return preconditionFailedError(body, verbContext);
783
+ }
784
+ if (status === 422 && code === "low_confidence") {
785
+ return lowConfidenceError(body, message);
786
+ }
787
+ if (status === 400 && code === "cross_repo_pr_rejected") {
788
+ return crossRepoRejectedError(message, verbContext);
789
+ }
790
+ if (status === 403 && code === "pr_author_mismatch") {
791
+ return prAuthorMismatchError(message);
792
+ }
793
+ if (status === 409 && code === "conflict" && RESPEC_CONFLICT_PATTERN.test(message)) {
794
+ return respecConflictError(message);
795
+ }
796
+ return genericDegrade(status, message, body.details, body.error);
797
+ }
798
+ //# sourceMappingURL=errors.js.map