@principles/host-runtime 3.4.1 → 4.0.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/active-principle-prompt.d.ts +13 -0
- package/dist/active-principle-prompt.js +87 -10
- package/dist/adaptive-decision-protocol.d.ts +129 -0
- package/dist/adaptive-decision-protocol.js +176 -0
- package/dist/adaptive-priority-provider.d.ts +38 -13
- package/dist/adaptive-priority-provider.js +70 -66
- package/dist/adaptive-selection.d.ts +71 -64
- package/dist/adaptive-selection.js +220 -329
- package/dist/adaptive-skip-decision.d.ts +26 -14
- package/dist/adaptive-skip-decision.js +33 -29
- package/dist/codex-disclosure.d.ts +12 -7
- package/dist/codex-disclosure.js +12 -7
- package/dist/codex-rule-context-provider.js +4 -1
- package/dist/conversation-ingestion/pipeline.d.ts +8 -0
- package/dist/conversation-ingestion/pipeline.js +6 -1
- package/dist/conversation-ingestion/text-policy.d.ts +3 -4
- package/dist/conversation-ingestion/text-policy.js +3 -4
- package/dist/governance-observation-store.d.ts +73 -1
- package/dist/governance-observation-store.js +251 -14
- package/dist/governance-signal-admission.d.ts +19 -3
- package/dist/governance-signal-admission.js +12 -4
- package/dist/host-tool-declaration.d.ts +18 -2
- package/dist/host-tool-declaration.js +67 -11
- package/dist/host-tool-semantic-resolver.d.ts +7 -0
- package/dist/host-tool-semantic-resolver.js +22 -2
- package/dist/index.d.ts +3 -0
- package/dist/index.js +17 -0
- package/dist/production-rulehost-gate.d.ts +36 -1
- package/dist/production-rulehost-gate.js +106 -4
- package/dist/trajectory-retention.d.ts +147 -0
- package/dist/trajectory-retention.js +907 -0
- package/package.json +4 -4
|
@@ -4,46 +4,42 @@
|
|
|
4
4
|
* ONE implementation of the bounded "current turn → pick at most one candidate"
|
|
5
5
|
* protocol, shared by the selector lab and the production host runtimes.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* PRI-1182 replaced the free-form chat-completions selector with the verified
|
|
8
|
+
* Decisions scoring protocol (`scripts/dev/adaptive-selector-lab/diagnostic.mjs`):
|
|
9
|
+
* one POST carries every candidate's applicability condition plus one
|
|
10
|
+
* "insufficient context" condition; the model returns an INDEPENDENT score per
|
|
11
|
+
* question; PD validates and adjudicates locally
|
|
12
|
+
* (`adaptive-decision-protocol.ts`). The model is never asked to emit a
|
|
13
|
+
* decision, a ref, or a digest.
|
|
14
|
+
*
|
|
15
|
+
* Contract highlights, unchanged from PRI-1122:
|
|
11
16
|
* - The incremental deadline is a FIRST-BYTE deadline, not a whole-generation
|
|
12
17
|
* wall clock. Once the endpoint has started answering, generation is bounded
|
|
13
18
|
* by its own window; late completions are still discarded.
|
|
14
19
|
* - One real send per turn, zero retries, zero repair, zero provider fallback.
|
|
20
|
+
* - The host deadline can only shorten the request's own short limit.
|
|
15
21
|
* - Diagnostics never carry the raw prompt, the raw response, or credentials.
|
|
16
22
|
*/
|
|
17
23
|
import crypto from 'node:crypto';
|
|
18
|
-
import { PDRuntimeError, PiAiRuntimeAdapter, StoreEventEmitter, } from '@principles/core/runtime';
|
|
19
|
-
import { readPromptActivationCandidates } from './active-principle-prompt.js';
|
|
20
24
|
import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
|
|
25
|
+
import { ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS, adjudicateDecision, buildDecisionRequest, validateDecisionResponse, } from './adaptive-decision-protocol.js';
|
|
21
26
|
export const ADAPTIVE_SELECTION_LIMITS = {
|
|
22
27
|
maxCandidates: 12,
|
|
23
|
-
maxCandidateChars:
|
|
28
|
+
maxCandidateChars: ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS,
|
|
24
29
|
maxPriorMessages: 4,
|
|
25
30
|
maxPriorMessageChars: 1200,
|
|
26
31
|
maxInputChars: 6000,
|
|
27
|
-
/**
|
|
28
|
-
|
|
29
|
-
/** Bounded
|
|
30
|
-
|
|
31
|
-
|
|
32
|
+
/** Total time from sending a decision request to validating the full response. */
|
|
33
|
+
requestTimeoutMs: 2000,
|
|
34
|
+
/** Bounded outbound payload (current instruction + candidate snapshot + conditions). */
|
|
35
|
+
maxPayloadChars: 20_000,
|
|
36
|
+
/** Bounded response body; a Decisions answer table is a few KB at most. */
|
|
37
|
+
maxResponseBytes: 65_536,
|
|
38
|
+
/** Bounded provider usage projection is unnecessary: only token counts are kept. */
|
|
32
39
|
};
|
|
33
40
|
export function hash(value) {
|
|
34
41
|
return crypto.createHash('sha256').update(value, 'utf8').digest('hex');
|
|
35
42
|
}
|
|
36
|
-
export const ADAPTIVE_SELECTOR_SYSTEM = [
|
|
37
|
-
'你是 Principles Disciple 的原则选择器。只判断:当前用户输入是否需要追加一条已批准原则。',
|
|
38
|
-
'候选只在「当前输入明确要求交付、实现、修复、审查或验证,且这条原则会改变你这一步的做法」时才算适用。',
|
|
39
|
-
'通用礼貌、闲聊、元问题、与当前任务无关的原则一律不选。',
|
|
40
|
-
'只能返回下面三种 JSON 之一,不要 Markdown、不要解释:',
|
|
41
|
-
'{"status":"selected","id":"候选引用(例如 c1)","digest":"该候选随附的 digest 原样复制;不要计算或改写","reason":"一句话理由"}',
|
|
42
|
-
'{"status":"none_applicable","id":null,"digest":null,"reason":"一句话理由"}',
|
|
43
|
-
'{"status":"uncertain","id":null,"digest":null,"reason":"一句话理由"}',
|
|
44
|
-
'digest 由本地预计算并随候选下发;必须逐字符原样返回所选候选的 digest。',
|
|
45
|
-
'最多只能选一条。',
|
|
46
|
-
].join('\n');
|
|
47
43
|
function boundText(value, max) {
|
|
48
44
|
const text = value.replace(/\s+/gu, ' ').trim();
|
|
49
45
|
if (text.length <= max)
|
|
@@ -71,11 +67,14 @@ export function buildBoundedSelectionInput(input) {
|
|
|
71
67
|
if (!principle.text.trim())
|
|
72
68
|
continue;
|
|
73
69
|
const candidateText = boundText(principle.text, ADAPTIVE_SELECTION_LIMITS.maxCandidateChars);
|
|
70
|
+
const outgoing = input.replacementByActivationId?.get(principle.activationId);
|
|
74
71
|
entries.push({
|
|
72
|
+
...(outgoing ? { replaces: boundText(outgoing.text, ADAPTIVE_SELECTION_LIMITS.maxCandidateChars) } : {}),
|
|
75
73
|
ref: `c${entries.length + 1}`,
|
|
76
74
|
text: candidateText,
|
|
77
|
-
//
|
|
78
|
-
//
|
|
75
|
+
// The digest stays part of the frozen candidate snapshot even though the
|
|
76
|
+
// Decisions protocol scores question ids instead of asking for a ref: it
|
|
77
|
+
// lets a later reader recompute exactly what was sent.
|
|
79
78
|
digest: hash(candidateText),
|
|
80
79
|
principle,
|
|
81
80
|
});
|
|
@@ -90,8 +89,7 @@ export function buildBoundedSelectionInput(input) {
|
|
|
90
89
|
payload: {
|
|
91
90
|
currentInstruction,
|
|
92
91
|
priorMessages: boundedPrior,
|
|
93
|
-
|
|
94
|
-
candidates: entries.map((entry) => ({ ref: entry.ref, text: entry.text, digest: entry.digest })),
|
|
92
|
+
candidates: entries.map(({ ref, text, digest, replaces }) => ({ ref, text, digest, ...(replaces !== undefined ? { replaces } : {}) })),
|
|
95
93
|
},
|
|
96
94
|
entries,
|
|
97
95
|
priorDropped: Math.max(0, priorMessages.length - selectedPrior.length),
|
|
@@ -102,152 +100,92 @@ export function buildBoundedSelectionInput(input) {
|
|
|
102
100
|
function isRecord(value) {
|
|
103
101
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
104
102
|
}
|
|
105
|
-
export function parseSelectionShape(value) {
|
|
106
|
-
if (!isRecord(value)) {
|
|
107
|
-
return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
|
|
108
|
-
}
|
|
109
|
-
const { status } = value;
|
|
110
|
-
const { id } = value;
|
|
111
|
-
const { digest } = value;
|
|
112
|
-
if (status === 'selected') {
|
|
113
|
-
if (typeof id !== 'string' || !id)
|
|
114
|
-
return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
|
|
115
|
-
if (typeof digest !== 'string' || !digest)
|
|
116
|
-
return { ok: false, reason: 'SELECTION_DIGEST_INVALID' };
|
|
117
|
-
return { ok: true, selection: { status: 'selected', id, digest } };
|
|
118
|
-
}
|
|
119
|
-
if (status === 'none_applicable' || status === 'uncertain') {
|
|
120
|
-
if (id !== null && id !== undefined)
|
|
121
|
-
return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
|
|
122
|
-
if (digest !== null && digest !== undefined)
|
|
123
|
-
return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
|
|
124
|
-
return { ok: true, selection: { status, id: null, digest: null } };
|
|
125
|
-
}
|
|
126
|
-
return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
|
|
127
|
-
}
|
|
128
|
-
export function validateSelectionResult(value, entries) {
|
|
129
|
-
const parsed = parseSelectionShape(value);
|
|
130
|
-
if (!parsed.ok) {
|
|
131
|
-
return {
|
|
132
|
-
ok: false,
|
|
133
|
-
reason: parsed.reason,
|
|
134
|
-
refValid: null,
|
|
135
|
-
digestValid: null,
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
const { selection } = parsed;
|
|
139
|
-
if (selection.status !== 'selected') {
|
|
140
|
-
return {
|
|
141
|
-
ok: true,
|
|
142
|
-
selected: null,
|
|
143
|
-
outcome: selection.status === 'uncertain' ? 'uncertain' : 'no_increment',
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
const entry = entries.find((candidate) => candidate.ref === selection.id);
|
|
147
|
-
if (!entry) {
|
|
148
|
-
return { ok: false, reason: 'SELECTION_REFERENCE_INVALID', refValid: false, digestValid: null };
|
|
149
|
-
}
|
|
150
|
-
// Two independent computations of the wire-body digest must agree: the value
|
|
151
|
-
// frozen into the candidate table and a fresh hash of the frozen body.
|
|
152
|
-
if (selection.digest !== entry.digest || selection.digest !== hash(entry.text)) {
|
|
153
|
-
return { ok: false, reason: 'SELECTION_DIGEST_INVALID', refValid: true, digestValid: false };
|
|
154
|
-
}
|
|
155
|
-
if (entries.some((candidate) => candidate !== entry && candidate.principle.principleId === entry.principle.principleId)) {
|
|
156
|
-
return { ok: false, reason: 'SELECTION_AMBIGUOUS', refValid: true, digestValid: true };
|
|
157
|
-
}
|
|
158
|
-
return { ok: true, selected: entry, outcome: 'selected' };
|
|
159
|
-
}
|
|
160
|
-
export function localFailureCode(reason) {
|
|
161
|
-
if (reason === 'SELECTION_OUTPUT_INVALID')
|
|
162
|
-
return 'SELECTION_OUTPUT_INVALID';
|
|
163
|
-
if (reason === 'SELECTION_DIGEST_INVALID')
|
|
164
|
-
return 'SELECTION_DIGEST_INVALID';
|
|
165
|
-
if (reason === 'SELECTION_REFERENCE_INVALID')
|
|
166
|
-
return 'SELECTION_REFERENCE_INVALID';
|
|
167
|
-
if (reason === 'SELECTION_AMBIGUOUS')
|
|
168
|
-
return 'SELECTION_AMBIGUOUS';
|
|
169
|
-
if (reason === 'SELECTION_EXPIRED')
|
|
170
|
-
return 'SELECTION_EXPIRED';
|
|
171
|
-
return 'SELECTION_OUTPUT_INVALID';
|
|
172
|
-
}
|
|
173
103
|
function outerDeadlineReached(now, outerDeadlineAt, signal) {
|
|
174
104
|
// Without an outer deadline this is an ordinary caller signal; keep the
|
|
175
105
|
// previous SELECTION_EXPIRED / TRANSPORT_FAILED classification for it.
|
|
176
106
|
return outerDeadlineAt !== undefined && (signal?.aborted === true || now() >= outerDeadlineAt);
|
|
177
107
|
}
|
|
178
|
-
|
|
108
|
+
/**
|
|
109
|
+
* The provider caps every model window at the host deadline, so the host
|
|
110
|
+
* deadline can ALSO be the admission/generation deadline. Two timers then end
|
|
111
|
+
* at the same instant: either may run first, and `Date.now()` can still read
|
|
112
|
+
* one millisecond short of the deadline, which made "which controller
|
|
113
|
+
* aborted" decide the diagnostic. The expired window's own deadline is the
|
|
114
|
+
* authority (P4): when it is the host window, the host window is the cause.
|
|
115
|
+
*/
|
|
116
|
+
function deadlineIsHostWindow(outerDeadlineAt, expiredAt) {
|
|
117
|
+
return outerDeadlineAt !== undefined && expiredAt !== null && expiredAt >= outerDeadlineAt;
|
|
118
|
+
}
|
|
119
|
+
function emptyDiagnostics() {
|
|
179
120
|
return {
|
|
180
121
|
stage: 'idle',
|
|
181
|
-
|
|
122
|
+
requestDeadlineAt: null,
|
|
123
|
+
requestSentAt: null,
|
|
182
124
|
completionDeadlineAt: null,
|
|
183
125
|
firstByteAt: null,
|
|
184
126
|
generationEndedAt: null,
|
|
127
|
+
validatedAt: null,
|
|
185
128
|
cancelledAt: null,
|
|
186
129
|
httpStatus: null,
|
|
187
130
|
finishReason: 'unknown',
|
|
131
|
+
modelObserved: null,
|
|
132
|
+
providerObserved: null,
|
|
188
133
|
usage: null,
|
|
134
|
+
decision: null,
|
|
189
135
|
failures: [],
|
|
190
136
|
};
|
|
191
137
|
}
|
|
192
|
-
function
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
if (isRecord(first)) {
|
|
201
|
-
const finish = first.finish_reason;
|
|
202
|
-
if (typeof finish === 'string' && finish)
|
|
203
|
-
result.finishReason = finish;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
const { usage } = parsed;
|
|
207
|
-
if (isRecord(usage)) {
|
|
208
|
-
const input = usage.prompt_tokens ?? usage.input_tokens;
|
|
209
|
-
const output = usage.completion_tokens ?? usage.output_tokens;
|
|
210
|
-
result.usage = {
|
|
211
|
-
inputTokens: typeof input === 'number' ? input : null,
|
|
212
|
-
outputTokens: typeof output === 'number' ? output : null,
|
|
213
|
-
};
|
|
214
|
-
}
|
|
138
|
+
function projectUsage(value) {
|
|
139
|
+
if (!isRecord(value))
|
|
140
|
+
return null;
|
|
141
|
+
const input = value.input_tokens ?? value.prompt_tokens;
|
|
142
|
+
const output = value.output_tokens ?? value.completion_tokens;
|
|
143
|
+
return {
|
|
144
|
+
inputTokens: typeof input === 'number' && Number.isFinite(input) ? input : null,
|
|
145
|
+
outputTokens: typeof output === 'number' && Number.isFinite(output) ? output : null,
|
|
215
146
|
};
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}
|
|
224
|
-
catch {
|
|
225
|
-
return result;
|
|
147
|
+
}
|
|
148
|
+
async function readBoundedBody(response, maxBytes, controller) {
|
|
149
|
+
if (!response.body) {
|
|
150
|
+
const text = await response.text();
|
|
151
|
+
if (Buffer.byteLength(text, 'utf8') > maxBytes) {
|
|
152
|
+
controller.abort(new Error('RESPONSE_TOO_LARGE'));
|
|
153
|
+
throw new Error('SELECTION_OUTPUT_INVALID');
|
|
226
154
|
}
|
|
155
|
+
return text;
|
|
227
156
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
157
|
+
const reader = response.body.getReader();
|
|
158
|
+
const chunks = [];
|
|
159
|
+
let bytes = 0;
|
|
160
|
+
try {
|
|
161
|
+
for (;;) {
|
|
162
|
+
const part = await reader.read();
|
|
163
|
+
if (part.done)
|
|
164
|
+
break;
|
|
165
|
+
bytes += part.value.byteLength;
|
|
166
|
+
if (bytes > maxBytes) {
|
|
167
|
+
controller.abort(new Error('RESPONSE_TOO_LARGE'));
|
|
168
|
+
throw new Error('SELECTION_OUTPUT_INVALID');
|
|
169
|
+
}
|
|
170
|
+
chunks.push(Buffer.from(part.value));
|
|
237
171
|
}
|
|
172
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
reader.releaseLock();
|
|
238
176
|
}
|
|
239
|
-
return result;
|
|
240
177
|
}
|
|
241
|
-
|
|
178
|
+
/**
|
|
179
|
+
* One Decisions POST per turn. Every failure is classified at the transport
|
|
180
|
+
* edge; the caller never sees provider text, headers or credentials.
|
|
181
|
+
*/
|
|
182
|
+
export function createDecisionSelector(options) {
|
|
242
183
|
const now = options.now ?? Date.now;
|
|
243
|
-
const
|
|
244
|
-
const
|
|
245
|
-
const maxTokens = options.maxTokens ?? ADAPTIVE_SELECTION_LIMITS.maxOutputTokens;
|
|
246
|
-
const diagnostics = emptyDiagnostics(options.admissionDeadlineAt);
|
|
184
|
+
const requestTimeoutMs = options.requestTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.requestTimeoutMs;
|
|
185
|
+
const diagnostics = emptyDiagnostics();
|
|
247
186
|
let sends = 0;
|
|
248
187
|
let status = 'not_sent';
|
|
249
188
|
let failure = null;
|
|
250
|
-
let finishMetadata = Promise.resolve({ finishReason: 'unknown', usage: null });
|
|
251
189
|
const fail = (code) => {
|
|
252
190
|
failure = code;
|
|
253
191
|
status = 'failed';
|
|
@@ -261,179 +199,123 @@ export function createSingleModelSelector(options) {
|
|
|
261
199
|
diagnostics.cancelledAt = now();
|
|
262
200
|
fail('TURN_DEADLINE_EXCEEDED');
|
|
263
201
|
}
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
fail('
|
|
202
|
+
const apiKey = process.env[options.model.apiKeyEnv];
|
|
203
|
+
if (!apiKey)
|
|
204
|
+
fail('DECISION_CREDENTIAL_MISSING');
|
|
205
|
+
const body = JSON.stringify(input.body);
|
|
206
|
+
const sentAt = now();
|
|
207
|
+
if (outerDeadlineReached(() => sentAt, options.outerDeadlineAt, options.signal)) {
|
|
208
|
+
diagnostics.cancelledAt = sentAt;
|
|
209
|
+
fail('TURN_DEADLINE_EXCEEDED');
|
|
267
210
|
}
|
|
268
|
-
const
|
|
269
|
-
const
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
}
|
|
296
|
-
if (!body || body.model !== options.model.model)
|
|
297
|
-
fail('TRANSPORT_NOT_SENT');
|
|
298
|
-
if (body.max_tokens !== maxTokens)
|
|
299
|
-
fail('TRANSPORT_NOT_SENT');
|
|
300
|
-
const apiKey = process.env[options.model.apiKeyEnv];
|
|
301
|
-
if (!apiKey)
|
|
302
|
-
fail('TRANSPORT_NOT_SENT');
|
|
303
|
-
sends += 1;
|
|
304
|
-
status = 'sent';
|
|
305
|
-
diagnostics.stage = 'admission';
|
|
306
|
-
const combined = AbortSignal.any([
|
|
307
|
-
...(requestInit.signal ? [requestInit.signal] : []),
|
|
308
|
-
ttfbController.signal,
|
|
309
|
-
...(options.signal ? [options.signal] : []),
|
|
310
|
-
]);
|
|
211
|
+
const deadlineAt = Math.min(sentAt + requestTimeoutMs, options.outerDeadlineAt ?? Infinity);
|
|
212
|
+
const controller = new AbortController();
|
|
213
|
+
const deadlineError = new Error('DECISION_DEADLINE');
|
|
214
|
+
const timer = setTimeout(() => controller.abort(deadlineError), Math.max(1, deadlineAt - sentAt));
|
|
215
|
+
timer.unref?.();
|
|
216
|
+
const signal = options.signal
|
|
217
|
+
? AbortSignal.any([options.signal, controller.signal])
|
|
218
|
+
: controller.signal;
|
|
219
|
+
const expire = () => {
|
|
220
|
+
controller.abort(deadlineError);
|
|
221
|
+
diagnostics.cancelledAt = now();
|
|
222
|
+
return fail(outerDeadlineReached(now, options.outerDeadlineAt, options.signal)
|
|
223
|
+
|| deadlineIsHostWindow(options.outerDeadlineAt, deadlineAt)
|
|
224
|
+
? 'TURN_DEADLINE_EXCEEDED'
|
|
225
|
+
: 'SELECTION_EXPIRED');
|
|
226
|
+
};
|
|
227
|
+
const checkDeadline = () => {
|
|
228
|
+
if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)
|
|
229
|
+
|| controller.signal.reason === deadlineError || now() >= deadlineAt)
|
|
230
|
+
expire();
|
|
231
|
+
};
|
|
232
|
+
sends += 1;
|
|
233
|
+
status = 'sent';
|
|
234
|
+
diagnostics.stage = 'admission';
|
|
235
|
+
diagnostics.requestSentAt = sentAt;
|
|
236
|
+
diagnostics.requestDeadlineAt = deadlineAt;
|
|
237
|
+
try {
|
|
311
238
|
let response;
|
|
312
239
|
try {
|
|
313
|
-
response = await (options.fetchImpl ?? fetch)(
|
|
240
|
+
response = await (options.fetchImpl ?? fetch)(options.model.endpoint, {
|
|
241
|
+
method: 'POST',
|
|
242
|
+
headers: {
|
|
243
|
+
'Content-Type': 'application/json',
|
|
244
|
+
Authorization: `Bearer ${apiKey}`,
|
|
245
|
+
},
|
|
246
|
+
body,
|
|
247
|
+
signal,
|
|
248
|
+
redirect: 'error',
|
|
249
|
+
});
|
|
314
250
|
}
|
|
315
|
-
catch
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
fail(outerDeadlineReached(now, options.outerDeadlineAt, options.signal)
|
|
319
|
-
? 'TURN_DEADLINE_EXCEEDED'
|
|
320
|
-
: ttfbController.signal.aborted ? 'SELECTION_EXPIRED' : 'TRANSPORT_FAILED');
|
|
321
|
-
throw error;
|
|
251
|
+
catch {
|
|
252
|
+
checkDeadline();
|
|
253
|
+
return fail('TRANSPORT_FAILED');
|
|
322
254
|
}
|
|
323
|
-
|
|
324
|
-
firstByteAt = now();
|
|
325
|
-
diagnostics.firstByteAt = firstByteAt;
|
|
255
|
+
diagnostics.firstByteAt = now();
|
|
326
256
|
diagnostics.httpStatus = response.status;
|
|
327
|
-
|
|
328
|
-
if (
|
|
329
|
-
|
|
330
|
-
fail('
|
|
331
|
-
}
|
|
332
|
-
if (firstByteAt >= options.admissionDeadlineAt) {
|
|
333
|
-
diagnostics.cancelledAt = firstByteAt;
|
|
334
|
-
fail('SELECTION_EXPIRED');
|
|
257
|
+
checkDeadline();
|
|
258
|
+
if (!response.ok) {
|
|
259
|
+
controller.abort();
|
|
260
|
+
return fail('TRANSPORT_HTTP_ERROR');
|
|
335
261
|
}
|
|
336
|
-
// Headers arriving is not completion: the generation window may never
|
|
337
|
-
// extend past the host deadline.
|
|
338
|
-
completionDeadlineAt = options.outerDeadlineAt === undefined
|
|
339
|
-
? firstByteAt + generationTimeoutMs
|
|
340
|
-
: Math.min(firstByteAt + generationTimeoutMs, options.outerDeadlineAt);
|
|
341
|
-
diagnostics.completionDeadlineAt = completionDeadlineAt;
|
|
342
262
|
diagnostics.stage = 'generation';
|
|
263
|
+
diagnostics.completionDeadlineAt = deadlineAt;
|
|
264
|
+
let raw;
|
|
343
265
|
try {
|
|
344
|
-
|
|
345
|
-
finishMetadata = clone
|
|
346
|
-
.text()
|
|
347
|
-
.then((raw) => parseFinishMetadata(raw))
|
|
348
|
-
.catch(() => ({ finishReason: 'unknown', usage: null }));
|
|
266
|
+
raw = await readBoundedBody(response, ADAPTIVE_SELECTION_LIMITS.maxResponseBytes, controller);
|
|
349
267
|
}
|
|
350
268
|
catch {
|
|
351
|
-
|
|
269
|
+
checkDeadline();
|
|
270
|
+
return fail('SELECTION_OUTPUT_INVALID');
|
|
352
271
|
}
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
try {
|
|
356
|
-
const adapter = new Adapter({
|
|
357
|
-
provider: options.model.provider,
|
|
358
|
-
model: options.model.model,
|
|
359
|
-
...(options.model.baseUrl ? { baseUrl: options.model.baseUrl } : {}),
|
|
360
|
-
apiKeyEnv: options.model.apiKeyEnv,
|
|
361
|
-
maxRetries: 0,
|
|
362
|
-
maxRepairAttempts: 0,
|
|
363
|
-
outputPathStrategy: 'free_form_only',
|
|
364
|
-
reasoning: 'low',
|
|
365
|
-
timeoutMs: remainingAdmission + generationTimeoutMs,
|
|
366
|
-
maxTokens,
|
|
367
|
-
fetch: guardedFetch,
|
|
368
|
-
eventEmitter: new StoreEventEmitter(),
|
|
369
|
-
});
|
|
370
|
-
let run;
|
|
272
|
+
checkDeadline();
|
|
273
|
+
let parsed;
|
|
371
274
|
try {
|
|
372
|
-
|
|
373
|
-
agentSpec: { agentId: 'adaptive-principle-selector', schemaVersion: 'current' },
|
|
374
|
-
inputPayload: input.payload,
|
|
375
|
-
contextItems: [],
|
|
376
|
-
// S5: the last caller that reached the adapter without a schema ref.
|
|
377
|
-
// `adaptive-selection-output` is registered in OUTPUT_SCHEMA_REGISTRY
|
|
378
|
-
// (principles-core), so the structural shape is validated by the
|
|
379
|
-
// shared path instead of relying on the host guard alone.
|
|
380
|
-
// Scope note: this is the ONLY change here. The admission/completion
|
|
381
|
-
// deadline semantics are owned by PRI-1170 (merged as 030d0035,
|
|
382
|
-
// #2513); they are intentionally untouched to avoid a second timing
|
|
383
|
-
// system in this file.
|
|
384
|
-
outputSchemaRef: 'adaptive-selection-output',
|
|
385
|
-
timeoutMs: remainingAdmission + generationTimeoutMs,
|
|
386
|
-
maxTokens,
|
|
387
|
-
systemPrompt: ADAPTIVE_SELECTOR_SYSTEM,
|
|
388
|
-
});
|
|
275
|
+
parsed = JSON.parse(raw);
|
|
389
276
|
}
|
|
390
|
-
catch
|
|
391
|
-
|
|
392
|
-
// structurally incomplete answer (e.g. `selected` without a digest)
|
|
393
|
-
// is rejected there — before the host guard could label it
|
|
394
|
-
// SELECTION_DIGEST_INVALID / SELECTION_REFERENCE_INVALID. Map it to
|
|
395
|
-
// the host contract code so the reason stays diagnosable instead of
|
|
396
|
-
// degrading to TRANSPORT_FAILED in runAdaptiveSelection (rc-9).
|
|
397
|
-
if (error instanceof PDRuntimeError && error.category === 'output_invalid') {
|
|
398
|
-
// An unregistered schema ref is a deployment fault, not a malformed
|
|
399
|
-
// answer. Keeping the codes distinct stops operators from debugging
|
|
400
|
-
// the model when the registry is the actual problem.
|
|
401
|
-
fail(error.details?.parseFailureReason === 'unknown_output_schema_ref'
|
|
402
|
-
? 'SELECTION_SCHEMA_UNAVAILABLE'
|
|
403
|
-
: 'SELECTION_OUTPUT_INVALID');
|
|
404
|
-
}
|
|
405
|
-
throw error;
|
|
277
|
+
catch {
|
|
278
|
+
return fail('SELECTION_OUTPUT_INVALID');
|
|
406
279
|
}
|
|
407
|
-
const output = await adapter.fetchOutput(run.runId);
|
|
408
280
|
const endedAt = now();
|
|
409
281
|
diagnostics.generationEndedAt = endedAt;
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
diagnostics.
|
|
418
|
-
fail('SELECTION_EXPIRED');
|
|
282
|
+
checkDeadline();
|
|
283
|
+
diagnostics.usage = projectUsage(isRecord(parsed) ? parsed.usage : undefined);
|
|
284
|
+
// Record what the endpoint actually claimed BEFORE validating it, so the
|
|
285
|
+
// acceptance report can state observed model/provider instead of
|
|
286
|
+
// inferring a route from the request.
|
|
287
|
+
if (isRecord(parsed)) {
|
|
288
|
+
diagnostics.modelObserved = typeof parsed.model === 'string' ? parsed.model : null;
|
|
289
|
+
diagnostics.providerObserved = typeof parsed.provider === 'string' ? parsed.provider : null;
|
|
419
290
|
}
|
|
420
|
-
const metadata = await finishMetadata;
|
|
421
|
-
diagnostics.finishReason = metadata.finishReason;
|
|
422
|
-
diagnostics.usage = metadata.usage;
|
|
423
291
|
diagnostics.stage = 'validate';
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
292
|
+
const validated = validateDecisionResponse(parsed, {
|
|
293
|
+
model: options.model.model,
|
|
294
|
+
questionIds: input.questionIds,
|
|
295
|
+
...(options.model.provider !== undefined ? { provider: options.model.provider } : {}),
|
|
296
|
+
...(options.model.allowedResponseModels !== undefined
|
|
297
|
+
? { allowedResponseModels: options.model.allowedResponseModels }
|
|
298
|
+
: {}),
|
|
299
|
+
});
|
|
300
|
+
if (!validated.ok)
|
|
301
|
+
return fail(validated.reason);
|
|
302
|
+
// The envelope is measured to a VALIDATED table, not to the last byte:
|
|
303
|
+
// a table that only parses after the completion deadline is expired even
|
|
304
|
+
// though the body arrived, so the caller never applies a late decision.
|
|
305
|
+
diagnostics.validatedAt = now();
|
|
306
|
+
checkDeadline();
|
|
307
|
+
diagnostics.finishReason = 'decisions';
|
|
308
|
+
const outcome = adjudicateDecision(validated.scores, input.candidates);
|
|
309
|
+
diagnostics.decision = {
|
|
310
|
+
status: outcome.status,
|
|
311
|
+
ref: outcome.ref,
|
|
312
|
+
reason: outcome.reason,
|
|
313
|
+
scores: validated.scores,
|
|
314
|
+
};
|
|
315
|
+
return outcome;
|
|
434
316
|
}
|
|
435
317
|
finally {
|
|
436
|
-
clearTimeout(
|
|
318
|
+
clearTimeout(timer);
|
|
437
319
|
}
|
|
438
320
|
};
|
|
439
321
|
return {
|
|
@@ -442,45 +324,48 @@ export function createSingleModelSelector(options) {
|
|
|
442
324
|
};
|
|
443
325
|
}
|
|
444
326
|
/**
|
|
445
|
-
* Minimal host-facing selection step:
|
|
446
|
-
* make at most one bounded
|
|
447
|
-
* revalidate the chosen principle's content/revision/authorization.
|
|
327
|
+
* Minimal host-facing selection step: use the current frozen Native gap,
|
|
328
|
+
* make at most one bounded Decisions request, adjudicate locally, then
|
|
329
|
+
* independently revalidate the chosen principle's content/revision/authorization.
|
|
448
330
|
*/
|
|
449
331
|
export async function runAdaptiveSelection(options) {
|
|
450
|
-
const earlyDiagnostics = emptyDiagnostics(
|
|
332
|
+
const earlyDiagnostics = emptyDiagnostics();
|
|
451
333
|
const unavailable = (reason, stage) => {
|
|
452
334
|
earlyDiagnostics.stage = stage;
|
|
453
335
|
return { status: 'unavailable', target: null, reason, sends: 0, diagnostics: earlyDiagnostics };
|
|
454
336
|
};
|
|
455
|
-
const read = await readPromptActivationCandidates({
|
|
456
|
-
workspaceDir: options.workspaceDir,
|
|
457
|
-
includeAuthority: true,
|
|
458
|
-
});
|
|
459
|
-
if (read.aborted || read.warnings.length > 0) {
|
|
460
|
-
return unavailable(`candidates_unavailable:${read.warnings[0] ?? 'aborted'}`, 'idle');
|
|
461
|
-
}
|
|
462
337
|
const built = buildBoundedSelectionInput({
|
|
463
338
|
currentInput: options.currentPrompt,
|
|
464
|
-
candidates:
|
|
339
|
+
candidates: options.candidates,
|
|
340
|
+
replacementByActivationId: options.replacementByActivationId,
|
|
465
341
|
});
|
|
466
342
|
if (!built.ok)
|
|
467
343
|
return unavailable(built.reason, 'idle');
|
|
468
|
-
const
|
|
469
|
-
|
|
344
|
+
const request = buildDecisionRequest({
|
|
345
|
+
model: options.model.model,
|
|
346
|
+
...(options.model.provider !== undefined ? { provider: options.model.provider } : {}),
|
|
347
|
+
currentInstruction: built.input.payload.currentInstruction,
|
|
348
|
+
priorMessages: built.input.payload.priorMessages,
|
|
349
|
+
candidates: built.input.payload.candidates,
|
|
350
|
+
maxPayloadChars: ADAPTIVE_SELECTION_LIMITS.maxPayloadChars,
|
|
351
|
+
});
|
|
352
|
+
if (!request.ok)
|
|
353
|
+
return unavailable(request.reason, 'idle');
|
|
354
|
+
const selector = createDecisionSelector({
|
|
470
355
|
model: options.model,
|
|
471
|
-
...(options.
|
|
472
|
-
...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),
|
|
356
|
+
...(options.requestTimeoutMs !== undefined ? { requestTimeoutMs: options.requestTimeoutMs } : {}),
|
|
473
357
|
...(options.signal ? { signal: options.signal } : {}),
|
|
474
358
|
...(options.outerDeadlineAt !== undefined ? { outerDeadlineAt: options.outerDeadlineAt } : {}),
|
|
475
359
|
...(options.now ? { now: options.now } : {}),
|
|
476
360
|
...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
|
|
477
|
-
...(options.PiAiRuntimeAdapterImpl
|
|
478
|
-
? { PiAiRuntimeAdapterImpl: options.PiAiRuntimeAdapterImpl }
|
|
479
|
-
: {}),
|
|
480
361
|
});
|
|
481
|
-
let
|
|
362
|
+
let decision;
|
|
482
363
|
try {
|
|
483
|
-
|
|
364
|
+
decision = await selector.select({
|
|
365
|
+
body: request.body,
|
|
366
|
+
questionIds: request.questionIds,
|
|
367
|
+
candidates: built.input.entries,
|
|
368
|
+
});
|
|
484
369
|
}
|
|
485
370
|
catch {
|
|
486
371
|
const report = selector.report();
|
|
@@ -496,20 +381,26 @@ export async function runAdaptiveSelection(options) {
|
|
|
496
381
|
const report = selector.report();
|
|
497
382
|
const { diagnostics } = report;
|
|
498
383
|
const { sends } = report;
|
|
499
|
-
|
|
500
|
-
if (!validated.ok) {
|
|
501
|
-
diagnostics.stage = 'validate';
|
|
502
|
-
diagnostics.failures.push(localFailureCode(validated.reason));
|
|
503
|
-
return { status: 'none', target: null, reason: validated.reason, sends, diagnostics };
|
|
504
|
-
}
|
|
505
|
-
if (!validated.selected) {
|
|
384
|
+
if (decision.status !== 'selected') {
|
|
506
385
|
diagnostics.stage = 'done';
|
|
507
|
-
return {
|
|
386
|
+
return {
|
|
387
|
+
status: 'none',
|
|
388
|
+
target: null,
|
|
389
|
+
reason: decision.status === 'uncertain' ? 'uncertain' : 'no_increment',
|
|
390
|
+
sends,
|
|
391
|
+
diagnostics,
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
const selected = built.input.entries.find((entry) => entry.ref === decision.ref);
|
|
395
|
+
if (!selected) {
|
|
396
|
+
diagnostics.stage = 'validate';
|
|
397
|
+
diagnostics.failures.push('SELECTION_OUTPUT_INVALID');
|
|
398
|
+
return { status: 'none', target: null, reason: 'SELECTION_OUTPUT_INVALID', sends, diagnostics };
|
|
508
399
|
}
|
|
509
|
-
const target =
|
|
400
|
+
const target = selected.principle;
|
|
510
401
|
diagnostics.stage = 'revalidate';
|
|
511
402
|
const now = options.now ?? Date.now;
|
|
512
|
-
const revalidationBudgetMs = options.
|
|
403
|
+
const revalidationBudgetMs = options.requestTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.requestTimeoutMs;
|
|
513
404
|
const signal = options.signal ?? AbortSignal.timeout(options.outerDeadlineAt === undefined
|
|
514
405
|
? revalidationBudgetMs
|
|
515
406
|
: Math.max(1, Math.min(revalidationBudgetMs, options.outerDeadlineAt - now())));
|