pi-smart-router 1.2.1 → 1.3.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.
Files changed (99) hide show
  1. package/.pi/extensions/smart-router/delegation-runtime.ts +12 -2
  2. package/.pi/extensions/smart-router/fleet-bootstrap.ts +22 -0
  3. package/.pi/extensions/smart-router/routing-context.ts +85 -11
  4. package/README.md +47 -1
  5. package/config/benchmark-profiles.json +124 -33
  6. package/dist/config/defaults.d.ts +2 -2
  7. package/dist/config/defaults.d.ts.map +1 -1
  8. package/dist/config/defaults.js +6 -3
  9. package/dist/config/defaults.js.map +1 -1
  10. package/dist/config/pi-model-mapper.d.ts +37 -1
  11. package/dist/config/pi-model-mapper.d.ts.map +1 -1
  12. package/dist/config/pi-model-mapper.js +120 -7
  13. package/dist/config/pi-model-mapper.js.map +1 -1
  14. package/dist/domain/delegation/delegation-context.d.ts +49 -0
  15. package/dist/domain/delegation/delegation-context.d.ts.map +1 -1
  16. package/dist/domain/delegation/delegation-context.js +92 -0
  17. package/dist/domain/delegation/delegation-context.js.map +1 -1
  18. package/dist/domain/judgment/answer-mapper.d.ts +49 -0
  19. package/dist/domain/judgment/answer-mapper.d.ts.map +1 -0
  20. package/dist/domain/judgment/answer-mapper.js +124 -0
  21. package/dist/domain/judgment/answer-mapper.js.map +1 -0
  22. package/dist/domain/judgment/index.d.ts +8 -0
  23. package/dist/domain/judgment/index.d.ts.map +1 -0
  24. package/dist/domain/judgment/index.js +8 -0
  25. package/dist/domain/judgment/index.js.map +1 -0
  26. package/dist/domain/judgment/judge-state.d.ts +70 -0
  27. package/dist/domain/judgment/judge-state.d.ts.map +1 -0
  28. package/dist/domain/judgment/judge-state.js +227 -0
  29. package/dist/domain/judgment/judge-state.js.map +1 -0
  30. package/dist/domain/judgment/questions.d.ts +58 -0
  31. package/dist/domain/judgment/questions.d.ts.map +1 -0
  32. package/dist/domain/judgment/questions.js +157 -0
  33. package/dist/domain/judgment/questions.js.map +1 -0
  34. package/dist/domain/matching/hydra-input.d.ts.map +1 -1
  35. package/dist/domain/matching/hydra-input.js +4 -17
  36. package/dist/domain/matching/hydra-input.js.map +1 -1
  37. package/dist/domain/pinning/loop-escalation.d.ts.map +1 -1
  38. package/dist/domain/pinning/loop-escalation.js +1 -49
  39. package/dist/domain/pinning/loop-escalation.js.map +1 -1
  40. package/dist/domain/pinning/tool-failure.d.ts +20 -0
  41. package/dist/domain/pinning/tool-failure.d.ts.map +1 -0
  42. package/dist/domain/pinning/tool-failure.js +62 -0
  43. package/dist/domain/pinning/tool-failure.js.map +1 -0
  44. package/dist/domain/pipeline/pipeline-stage.d.ts +11 -0
  45. package/dist/domain/pipeline/pipeline-stage.d.ts.map +1 -1
  46. package/dist/domain/pipeline/pipeline-stage.js +3 -0
  47. package/dist/domain/pipeline/pipeline-stage.js.map +1 -1
  48. package/dist/domain/pipeline/router-pipeline.d.ts +32 -6
  49. package/dist/domain/pipeline/router-pipeline.d.ts.map +1 -1
  50. package/dist/domain/pipeline/router-pipeline.js +49 -4
  51. package/dist/domain/pipeline/router-pipeline.js.map +1 -1
  52. package/dist/domain/pipeline/typed-judgment-stage.d.ts +44 -0
  53. package/dist/domain/pipeline/typed-judgment-stage.d.ts.map +1 -0
  54. package/dist/domain/pipeline/typed-judgment-stage.js +144 -0
  55. package/dist/domain/pipeline/typed-judgment-stage.js.map +1 -0
  56. package/dist/domain/ports/typed-judgment-port.d.ts +138 -0
  57. package/dist/domain/ports/typed-judgment-port.d.ts.map +1 -0
  58. package/dist/domain/ports/typed-judgment-port.js +28 -0
  59. package/dist/domain/ports/typed-judgment-port.js.map +1 -0
  60. package/dist/domain/types/entities.d.ts +42 -1
  61. package/dist/domain/types/entities.d.ts.map +1 -1
  62. package/dist/domain/types/index.d.ts +1 -1
  63. package/dist/domain/types/index.d.ts.map +1 -1
  64. package/dist/domain/types/schemas.d.ts +140 -0
  65. package/dist/domain/types/schemas.d.ts.map +1 -1
  66. package/dist/domain/types/schemas.js +191 -0
  67. package/dist/domain/types/schemas.js.map +1 -1
  68. package/dist/index.d.ts +5 -3
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/index.js.map +1 -1
  72. package/dist/infrastructure/judgment/jev-typed-judgment-adapter.d.ts +67 -0
  73. package/dist/infrastructure/judgment/jev-typed-judgment-adapter.d.ts.map +1 -0
  74. package/dist/infrastructure/judgment/jev-typed-judgment-adapter.js +411 -0
  75. package/dist/infrastructure/judgment/jev-typed-judgment-adapter.js.map +1 -0
  76. package/dist/infrastructure/persistence/sqlite-store.d.ts.map +1 -1
  77. package/dist/infrastructure/persistence/sqlite-store.js +37 -9
  78. package/dist/infrastructure/persistence/sqlite-store.js.map +1 -1
  79. package/package.json +1 -1
  80. package/src/config/defaults.ts +8 -1
  81. package/src/config/pi-model-mapper.ts +146 -7
  82. package/src/domain/delegation/delegation-context.ts +123 -0
  83. package/src/domain/judgment/answer-mapper.ts +210 -0
  84. package/src/domain/judgment/index.ts +32 -0
  85. package/src/domain/judgment/judge-state.ts +294 -0
  86. package/src/domain/judgment/questions.ts +198 -0
  87. package/src/domain/matching/hydra-input.ts +4 -19
  88. package/src/domain/pinning/loop-escalation.ts +1 -52
  89. package/src/domain/pinning/tool-failure.ts +66 -0
  90. package/src/domain/pipeline/pipeline-stage.ts +17 -0
  91. package/src/domain/pipeline/router-pipeline.ts +83 -6
  92. package/src/domain/pipeline/typed-judgment-stage.ts +165 -0
  93. package/src/domain/ports/typed-judgment-port.ts +186 -0
  94. package/src/domain/types/entities.ts +54 -0
  95. package/src/domain/types/index.ts +1 -0
  96. package/src/domain/types/schemas.ts +206 -0
  97. package/src/index.ts +19 -2
  98. package/src/infrastructure/judgment/jev-typed-judgment-adapter.ts +564 -0
  99. package/src/infrastructure/persistence/sqlite-store.ts +45 -9
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Typed-judgment answer mapper (SP-306, GitHub #185) — pure domain, no I/O.
3
+ *
4
+ * Maps raw {@link TypedJudgmentAnswers} (keyed by question id, SP-304 wire
5
+ * types) onto the normalized {@link TypedJudgment} signal consumed by the
6
+ * routing pipeline:
7
+ * - score answers are normalized by `(levels - 1)` onto 0–1;
8
+ * - noul answers pass through as the calibrated P(yes) from the wire;
9
+ * - a missing answer maps its fields to `null` (no signal);
10
+ * - malformed answers are **rejected** with `TypedJudgmentError`
11
+ * (`kind: 'invalid_response'`): unknown choice, answer/question kind
12
+ * mismatch, out-of-range or non-finite scores, out-of-range confidence,
13
+ * out-of-range or non-finite noul probability.
14
+ */
15
+
16
+ import {
17
+ TypedJudgmentError,
18
+ type TypedJudgmentAnswer,
19
+ type TypedJudgmentAnswers,
20
+ type TypedJudgmentChoiceAnswer,
21
+ type TypedJudgmentChoiceQuestion,
22
+ type TypedJudgmentNoulAnswer,
23
+ type TypedJudgmentScoreAnswer,
24
+ type TypedJudgmentScoreQuestion,
25
+ } from '../ports/typed-judgment-port.js';
26
+ import {
27
+ CAPABILITY_DESERVED_QUESTION,
28
+ CODE_GEN_QUESTION,
29
+ TASK_KIND_QUESTION,
30
+ TOOL_USE_QUESTION,
31
+ type TaskKind,
32
+ } from './questions.js';
33
+
34
+ /** Normalized, pipeline-ready typed judgment. Fields are `null` when the
35
+ * corresponding question was not answered (partial results allowed). */
36
+ export interface TypedJudgment {
37
+ /** Selected task kind, or `null` when `task_kind` was not answered. */
38
+ readonly taskKind: TaskKind | null;
39
+ /** Judge confidence in `taskKind` (0–1), or `null`. */
40
+ readonly taskKindConfidence: number | null;
41
+ /** `capability_deserved` normalized to 0–1 (`score / (levels - 1)`), or `null`. */
42
+ readonly capabilityDeserved: number | null;
43
+ /** Probability the task needs deep reasoning (noul P(yes)), or `null`. */
44
+ readonly deepReasoningP: number | null;
45
+ /** `code_gen` normalized to 0–1, or `null`. */
46
+ readonly codeGen: number | null;
47
+ /** `tool_use` normalized to 0–1, or `null`. */
48
+ readonly toolUse: number | null;
49
+ /** Probability the request is destructive (noul P(yes)), or `null`. */
50
+ readonly destructiveP: number | null;
51
+ /**
52
+ * Judge confidence (0–1) per answered question that carries one (choice
53
+ * and score answers). Noul answers carry no confidence on the wire.
54
+ */
55
+ readonly confidences: Readonly<Record<string, number>>;
56
+ }
57
+
58
+ function invalid(message: string): never {
59
+ throw new TypedJudgmentError('invalid_response', message);
60
+ }
61
+
62
+ function requireConfidence(value: number, questionId: string): number {
63
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
64
+ invalid(`question '${questionId}': confidence out of range 0–1`);
65
+ }
66
+ return value;
67
+ }
68
+
69
+ function mapChoiceAnswer(
70
+ question: TypedJudgmentChoiceQuestion,
71
+ answer: TypedJudgmentAnswer,
72
+ ): TypedJudgmentChoiceAnswer {
73
+ if (answer.kind !== 'choice') {
74
+ invalid(
75
+ `question '${question.id}': expected a choice answer, got '${answer.kind}'`,
76
+ );
77
+ }
78
+ if (!question.options.includes(answer.choice)) {
79
+ invalid(
80
+ `question '${question.id}': unknown choice '${answer.choice}'`,
81
+ );
82
+ }
83
+ requireConfidence(answer.confidence, question.id);
84
+ return answer;
85
+ }
86
+
87
+ function mapScoreAnswer(
88
+ question: TypedJudgmentScoreQuestion,
89
+ answer: TypedJudgmentAnswer,
90
+ ): number {
91
+ if (answer.kind !== 'score') {
92
+ invalid(
93
+ `question '${question.id}': expected a score answer, got '${answer.kind}'`,
94
+ );
95
+ }
96
+ const scoreAnswer = answer as TypedJudgmentScoreAnswer;
97
+ const levels = question.anchors.length;
98
+ const max = levels - 1;
99
+ if (max < 1) {
100
+ invalid(
101
+ `question '${question.id}': score scale needs at least two anchors`,
102
+ );
103
+ }
104
+ if (
105
+ !Number.isFinite(scoreAnswer.score) ||
106
+ !Number.isInteger(scoreAnswer.score) ||
107
+ scoreAnswer.score < 0 ||
108
+ scoreAnswer.score > max
109
+ ) {
110
+ invalid(
111
+ `question '${question.id}': score ${String(scoreAnswer.score)} out of range 0–${max}`,
112
+ );
113
+ }
114
+ requireConfidence(scoreAnswer.confidence, question.id);
115
+ // Normalized by (levels - 1) onto 0–1 (#185).
116
+ return scoreAnswer.score / max;
117
+ }
118
+
119
+ function mapNoulAnswer(
120
+ questionId: string,
121
+ answer: TypedJudgmentAnswer,
122
+ ): number {
123
+ if (answer.kind !== 'noul') {
124
+ invalid(
125
+ `question '${questionId}': expected a noul answer, got '${answer.kind}'`,
126
+ );
127
+ }
128
+ const probability = (answer as TypedJudgmentNoulAnswer).noul;
129
+ if (!Number.isFinite(probability) || probability < 0 || probability > 1) {
130
+ invalid(`question '${questionId}': noul probability out of range 0–1`);
131
+ }
132
+ return probability;
133
+ }
134
+
135
+ /**
136
+ * Map raw judge answers to the normalized {@link TypedJudgment} signal.
137
+ *
138
+ * @throws {TypedJudgmentError} with `kind: 'invalid_response'` when an
139
+ * answer is malformed (unknown choice, kind mismatch, out-of-range
140
+ * score/confidence). Callers follow the port's fail-open contract: any
141
+ * rejection means "no judgment available".
142
+ */
143
+ export function mapTypedJudgment(
144
+ answers: TypedJudgmentAnswers,
145
+ ): TypedJudgment {
146
+ const confidences: Record<string, number> = {};
147
+
148
+ let taskKind: TaskKind | null = null;
149
+ let taskKindConfidence: number | null = null;
150
+ const taskKindAnswer = answers[TASK_KIND_QUESTION.id];
151
+ if (taskKindAnswer !== undefined) {
152
+ const mapped = mapChoiceAnswer(TASK_KIND_QUESTION, taskKindAnswer);
153
+ taskKind = mapped.choice as TaskKind;
154
+ taskKindConfidence = mapped.confidence;
155
+ confidences[TASK_KIND_QUESTION.id] = mapped.confidence;
156
+ }
157
+
158
+ let capabilityDeserved: number | null = null;
159
+ const capabilityAnswer = answers[CAPABILITY_DESERVED_QUESTION.id];
160
+ if (capabilityAnswer !== undefined) {
161
+ capabilityDeserved = mapScoreAnswer(
162
+ CAPABILITY_DESERVED_QUESTION,
163
+ capabilityAnswer,
164
+ );
165
+ confidences[CAPABILITY_DESERVED_QUESTION.id] = (
166
+ capabilityAnswer as TypedJudgmentScoreAnswer
167
+ ).confidence;
168
+ }
169
+
170
+ let codeGen: number | null = null;
171
+ const codeGenAnswer = answers[CODE_GEN_QUESTION.id];
172
+ if (codeGenAnswer !== undefined) {
173
+ codeGen = mapScoreAnswer(CODE_GEN_QUESTION, codeGenAnswer);
174
+ confidences[CODE_GEN_QUESTION.id] = (
175
+ codeGenAnswer as TypedJudgmentScoreAnswer
176
+ ).confidence;
177
+ }
178
+
179
+ let toolUse: number | null = null;
180
+ const toolUseAnswer = answers[TOOL_USE_QUESTION.id];
181
+ if (toolUseAnswer !== undefined) {
182
+ toolUse = mapScoreAnswer(TOOL_USE_QUESTION, toolUseAnswer);
183
+ confidences[TOOL_USE_QUESTION.id] = (
184
+ toolUseAnswer as TypedJudgmentScoreAnswer
185
+ ).confidence;
186
+ }
187
+
188
+ let deepReasoningP: number | null = null;
189
+ const deepReasoningAnswer = answers['needs_deep_reasoning'];
190
+ if (deepReasoningAnswer !== undefined) {
191
+ deepReasoningP = mapNoulAnswer('needs_deep_reasoning', deepReasoningAnswer);
192
+ }
193
+
194
+ let destructiveP: number | null = null;
195
+ const destructiveAnswer = answers['destructive'];
196
+ if (destructiveAnswer !== undefined) {
197
+ destructiveP = mapNoulAnswer('destructive', destructiveAnswer);
198
+ }
199
+
200
+ return {
201
+ taskKind,
202
+ taskKindConfidence,
203
+ capabilityDeserved,
204
+ deepReasoningP,
205
+ codeGen,
206
+ toolUse,
207
+ destructiveP,
208
+ confidences,
209
+ };
210
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Typed-judgment domain module (SP-306, #185) — barrel export.
3
+ * Pure domain: no I/O, no infrastructure dependencies.
4
+ */
5
+
6
+ export {
7
+ ACTIVITY_LINE_MAX_CHARS,
8
+ ACK_DEEP_SESSION_MESSAGE_THRESHOLD,
9
+ JUDGE_STATE_TOKEN_CAP,
10
+ WORKSPACE_MAX_CHARS,
11
+ buildJudgeState,
12
+ isAcknowledgement,
13
+ type IsAcknowledgementOptions,
14
+ type JudgeStateOptions,
15
+ } from './judge-state.js';
16
+
17
+ export {
18
+ CAPABILITY_DESERVED_QUESTION,
19
+ CODE_GEN_QUESTION,
20
+ DESTRUCTIVE_QUESTION,
21
+ NEEDS_DEEP_REASONING_QUESTION,
22
+ TASK_KIND_OPTIONS,
23
+ TASK_KIND_QUESTION,
24
+ TOOL_USE_QUESTION,
25
+ TYPED_JUDGMENT_QUESTIONS,
26
+ TYPED_JUDGMENT_QUESTION_IDS,
27
+ TYPED_JUDGMENT_QUESTION_SET_VERSION,
28
+ type TaskKind,
29
+ type TypedJudgmentSixQuestionId,
30
+ } from './questions.js';
31
+
32
+ export { mapTypedJudgment, type TypedJudgment } from './answer-mapper.js';
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Judge state builder (SP-306, GitHub #185 / epic #183) — pure domain, no I/O.
3
+ *
4
+ * Builds a compact, human-readable JSON state for the typed-judgment stage.
5
+ * Measured on local OpenJev (epic #183): the HyDRA flag-prefix string
6
+ * (`buildHydraInput`) is unreadable to a judge; named JSON fields plus a short
7
+ * activity excerpt fixed most cases, and state size dominates latency
8
+ * (~385 ms for a short state vs 3.6–4.3 s for ~3k tokens).
9
+ *
10
+ * Hard guarantees:
11
+ * - The returned JSON never exceeds ~500 estimated tokens
12
+ * (`estimatePromptTokens` from `src/domain/matching/encoder-gate.ts`).
13
+ * Trim order: drop `recent_activity` lines (oldest first), then truncate
14
+ * the user message tail.
15
+ * - The state contains **no** spend, budget, price, or model-cost keys.
16
+ * - `recent_activity` holds at most 2 lines, each whitespace-collapsed and
17
+ * truncated — no raw tool output beyond the truncated lines.
18
+ */
19
+
20
+ import { estimatePromptTokens } from '../matching/encoder-gate.js';
21
+ import { isToolFailure } from '../pinning/tool-failure.js';
22
+ import type { Message, RoutingRequest } from '../types/index.js';
23
+
24
+ /** Hard cap on judge-state size, in estimated tokens (#185). */
25
+ export const JUDGE_STATE_TOKEN_CAP = 500;
26
+
27
+ /** Maximum characters per `recent_activity` line (post-collapse, pre-ellipsis). */
28
+ export const ACTIVITY_LINE_MAX_CHARS = 120;
29
+
30
+ /** Maximum characters of an operator-supplied `workspace` one-liner. */
31
+ export const WORKSPACE_MAX_CHARS = 120;
32
+
33
+ export interface JudgeStateOptions {
34
+ /**
35
+ * Operator-supplied workspace one-liner (e.g. repo label). Absent by
36
+ * default — when omitted or empty, no `workspace` key is emitted.
37
+ */
38
+ readonly workspace?: string | undefined;
39
+ /**
40
+ * Token cap override for tests/experiments. Default
41
+ * {@link JUDGE_STATE_TOKEN_CAP}. Measured with
42
+ * `estimatePromptTokens` (char-length proxy, turn-envelope parity).
43
+ */
44
+ readonly maxTokens?: number | undefined;
45
+ }
46
+
47
+ /** Shape of the judge state before serialization (mutable for trimming). */
48
+ interface JudgeStateShape {
49
+ latest_user_message: string;
50
+ session: {
51
+ messages: number;
52
+ tool_calls: number;
53
+ compactions: boolean;
54
+ context_tokens: number;
55
+ turn_type: string;
56
+ last_tool_failed: boolean;
57
+ };
58
+ workspace?: string;
59
+ recent_activity: string[];
60
+ }
61
+
62
+ /** Collapse all whitespace runs (including newlines) to single spaces. */
63
+ function collapseWhitespace(text: string): string {
64
+ return text.replace(/\s+/g, ' ').trim();
65
+ }
66
+
67
+ /** Truncate to `max` chars, appending an ellipsis when content was cut. */
68
+ function truncate(text: string, max: number): string {
69
+ if (text.length <= max) return text;
70
+ return `${text.slice(0, Math.max(0, max - 1))}…`;
71
+ }
72
+
73
+ /** Latest non-empty user message; falls back to `prompt_text`. */
74
+ function resolveLatestUserMessage(
75
+ request: RoutingRequest,
76
+ ): { text: string; index: number } {
77
+ const messages = request.messages;
78
+ if (messages) {
79
+ for (let i = messages.length - 1; i >= 0; i--) {
80
+ const message = messages[i]!;
81
+ if (message.role === 'user' && message.content.trim()) {
82
+ return { text: message.content, index: i };
83
+ }
84
+ }
85
+ }
86
+ return { text: request.prompt_text, index: -1 };
87
+ }
88
+
89
+ /**
90
+ * Whether the most recent tool-result message is a failure, using the shared
91
+ * `isToolFailure` precedence (SP-303): structured `is_error` / `status` win;
92
+ * body heuristic only when no structured signal is present. No new failure
93
+ * heuristics here. `false` when the session has no tool messages.
94
+ */
95
+ function resolveLastToolFailed(request: RoutingRequest): boolean {
96
+ const messages = request.messages;
97
+ if (!messages) return false;
98
+ for (let i = messages.length - 1; i >= 0; i--) {
99
+ const message = messages[i]!;
100
+ if (message.role === 'tool') {
101
+ return isToolFailure(message);
102
+ }
103
+ }
104
+ return false;
105
+ }
106
+
107
+ /** Count of tool-result messages in the session. */
108
+ function countToolCalls(messages: readonly Message[] | undefined): number {
109
+ if (!messages) return 0;
110
+ let count = 0;
111
+ for (const message of messages) {
112
+ if (message.role === 'tool') count += 1;
113
+ }
114
+ return count;
115
+ }
116
+
117
+ /**
118
+ * At most 2 activity lines from the tail of the session, excluding the
119
+ * message surfaced as `latest_user_message`. Chronological order; each line
120
+ * is `role: content` with whitespace collapsed and truncated to
121
+ * {@link ACTIVITY_LINE_MAX_CHARS}.
122
+ */
123
+ function buildRecentActivity(
124
+ request: RoutingRequest,
125
+ latestUserIndex: number,
126
+ ): string[] {
127
+ const messages = request.messages;
128
+ if (!messages || messages.length === 0) return [];
129
+
130
+ const lines: string[] = [];
131
+ for (let i = messages.length - 1; i >= 0 && lines.length < 2; i--) {
132
+ if (i === latestUserIndex) continue;
133
+ const message = messages[i]!;
134
+ const content = collapseWhitespace(message.content ?? '');
135
+ if (!content) continue;
136
+ lines.unshift(`${message.role}: ${truncate(content, ACTIVITY_LINE_MAX_CHARS)}`);
137
+ }
138
+ return lines;
139
+ }
140
+
141
+ /**
142
+ * Enforce the token cap. Trim order (#185): drop `recent_activity` lines
143
+ * (oldest first — the most recent activity carries the most signal), then
144
+ * truncate the tail of the user message.
145
+ */
146
+ function enforceTokenCap(state: JudgeStateShape, cap: number): string {
147
+ let json = JSON.stringify(state);
148
+ if (estimatePromptTokens(json) <= cap) return json;
149
+
150
+ while (state.recent_activity.length > 0) {
151
+ state.recent_activity.shift();
152
+ json = JSON.stringify(state);
153
+ if (estimatePromptTokens(json) <= cap) return json;
154
+ }
155
+
156
+ const excess = estimatePromptTokens(json) - cap;
157
+ if (excess > 0) {
158
+ state.latest_user_message = truncate(
159
+ state.latest_user_message,
160
+ Math.max(0, state.latest_user_message.length - excess),
161
+ );
162
+ json = JSON.stringify(state);
163
+ }
164
+ return json;
165
+ }
166
+
167
+ /**
168
+ * Build the judge state for a routing request as a JSON string.
169
+ *
170
+ * The state describes the *task* only — never spend, budget, price, or
171
+ * model cost (budget policy is code's job, not the judge's; see epic #183).
172
+ */
173
+ export function buildJudgeState(
174
+ request: RoutingRequest,
175
+ options?: JudgeStateOptions,
176
+ ): string {
177
+ const latest = resolveLatestUserMessage(request);
178
+
179
+ const state: JudgeStateShape = {
180
+ latest_user_message: latest.text,
181
+ session: {
182
+ messages: request.messages?.length ?? 0,
183
+ tool_calls: countToolCalls(request.messages),
184
+ compactions: request.compaction_flag === true,
185
+ context_tokens: request.estimated_input_tokens ?? 0,
186
+ turn_type: request.turn_type ?? 'unknown',
187
+ last_tool_failed: resolveLastToolFailed(request),
188
+ },
189
+ recent_activity: buildRecentActivity(request, latest.index),
190
+ };
191
+
192
+ const workspace = options?.workspace?.trim();
193
+ if (workspace) {
194
+ state.workspace = truncate(collapseWhitespace(workspace), WORKSPACE_MAX_CHARS);
195
+ }
196
+
197
+ return enforceTokenCap(state, options?.maxTokens ?? JUDGE_STATE_TOKEN_CAP);
198
+ }
199
+
200
+ // ─── Acknowledgement detector ────────────────────────────────────────────────
201
+
202
+ /**
203
+ * Session depth (message count) at/above which a session is "deep" for
204
+ * acknowledgement detection. Rule (#179): in deep sessions a bare
205
+ * continuation ("continue", "go ahead", …) is an instruction to keep working
206
+ * on the long-running task — not a conversational acknowledgement — so it
207
+ * must be judged, not skipped. Gate on session depth, not on text alone.
208
+ */
209
+ export const ACK_DEEP_SESSION_MESSAGE_THRESHOLD = 100;
210
+
211
+ /** Pleasantries that are acknowledgements at any session depth. */
212
+ const PLEASANTRY_ACKS: ReadonlySet<string> = new Set([
213
+ 'ok',
214
+ 'okay',
215
+ 'k',
216
+ 'kk',
217
+ 'thanks',
218
+ 'thank you',
219
+ 'thx',
220
+ 'ty',
221
+ 'thnx',
222
+ 'got it',
223
+ 'understood',
224
+ 'noted',
225
+ 'nice',
226
+ 'cool',
227
+ 'great',
228
+ 'perfect',
229
+ 'awesome',
230
+ 'lol',
231
+ ]);
232
+
233
+ /**
234
+ * Short continuations/affirmations that are acknowledgements only in shallow
235
+ * sessions; in deep sessions they mean "keep going" (#179).
236
+ */
237
+ const CONTINUATION_ACKS: ReadonlySet<string> = new Set([
238
+ 'continue',
239
+ 'go ahead',
240
+ 'go on',
241
+ 'keep going',
242
+ 'proceed',
243
+ 'carry on',
244
+ 'yes',
245
+ 'yep',
246
+ 'yeah',
247
+ 'sure',
248
+ 'sounds good',
249
+ 'looks good',
250
+ 'lgtm',
251
+ 'do it',
252
+ ]);
253
+
254
+ export interface IsAcknowledgementOptions {
255
+ /**
256
+ * Session depth in messages (e.g. `RoutingRequest.messages.length`).
257
+ * Defaults to 0 (shallow session).
258
+ */
259
+ readonly sessionDepth?: number | undefined;
260
+ }
261
+
262
+ /** Normalize for ack matching: lowercase, strip punctuation, collapse spaces. */
263
+ function normalizeAckText(text: string): string {
264
+ return text
265
+ .toLowerCase()
266
+ .replace(/[^\p{L}\p{N} ]+/gu, ' ')
267
+ .replace(/\s+/g, ' ')
268
+ .trim();
269
+ }
270
+
271
+ /**
272
+ * Detect acknowledgement-only turns (`ok`, `thanks`, `continue`, …) so the
273
+ * typed-judgment stage can skip the judge call. Pure text + depth check.
274
+ *
275
+ * Depth rule (#179): short continuations in deep sessions (≥
276
+ * {@link ACK_DEEP_SESSION_MESSAGE_THRESHOLD} messages) are **not**
277
+ * acknowledgements — they direct an ongoing agentic task.
278
+ */
279
+ export function isAcknowledgement(
280
+ text: string,
281
+ options?: IsAcknowledgementOptions,
282
+ ): boolean {
283
+ const normalized = normalizeAckText(text);
284
+ if (!normalized) return false;
285
+
286
+ if (PLEASANTRY_ACKS.has(normalized)) return true;
287
+
288
+ if (CONTINUATION_ACKS.has(normalized)) {
289
+ const depth = options?.sessionDepth ?? 0;
290
+ return depth < ACK_DEEP_SESSION_MESSAGE_THRESHOLD;
291
+ }
292
+
293
+ return false;
294
+ }