create-principles-disciple 1.148.11 → 1.150.1
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/_release/product-identity.json +1 -1
- package/codex-adapter/dist/pd-hook.d.ts +22 -1
- package/codex-adapter/dist/pd-hook.js +81 -7
- package/codex-adapter/dist/worker/workspace-worker.d.ts +15 -0
- package/codex-adapter/dist/worker/workspace-worker.js +7 -36
- package/codex-adapter/package.json +1 -1
- package/console/dist/server/index.js +21 -0
- package/console/dist/server/models/ActivationsConsoleModel.d.ts +3 -17
- package/console/dist/server/models/ActivationsConsoleModel.js +5 -44
- package/console/dist/server/routes/compatibility-scan.d.ts +18 -0
- package/console/dist/server/routes/compatibility-scan.js +33 -0
- package/console/dist/server/routes/diagnostician.d.ts +50 -0
- package/console/dist/server/routes/diagnostician.js +388 -0
- package/console/dist/shared/compatibility-scan-contract.d.ts +26 -0
- package/console/dist/shared/compatibility-scan-contract.js +1 -0
- package/console/dist/web/assets/app.js +31 -31
- package/core/dist/host/host-installer.d.ts +7 -0
- package/core/dist/host/host-installer.d.ts.map +1 -1
- package/core/dist/host/host-installer.js.map +1 -1
- package/core/dist/runtime/activation/index.d.ts +3 -3
- package/core/dist/runtime/activation/index.d.ts.map +1 -1
- package/core/dist/runtime/activation/index.js +1 -1
- package/core/dist/runtime/activation/index.js.map +1 -1
- package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts +25 -1
- package/core/dist/runtime/activation/promotion-readiness-evaluator.d.ts.map +1 -1
- package/core/dist/runtime/activation/promotion-readiness-evaluator.js +58 -1
- package/core/dist/runtime/activation/promotion-readiness-evaluator.js.map +1 -1
- package/core/dist/runtime/activation/promotion-readiness-reader.d.ts.map +1 -1
- package/core/dist/runtime/activation/promotion-readiness-reader.js +4 -2
- package/core/dist/runtime/activation/promotion-readiness-reader.js.map +1 -1
- package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts +28 -0
- package/core/dist/runtime/activation/rulecode-owner-decision-service.d.ts.map +1 -1
- package/core/dist/runtime/activation/rulecode-owner-decision-service.js +2 -0
- package/core/dist/runtime/activation/rulecode-owner-decision-service.js.map +1 -1
- package/core/dist/runtime/activation-compatibility-read-model.d.ts +20 -5
- package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
- package/core/dist/runtime/activation-compatibility-read-model.js +15 -3
- package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
- package/core/dist/runtime/admission-gate.d.ts +8 -1
- package/core/dist/runtime/admission-gate.d.ts.map +1 -1
- package/core/dist/runtime/admission-gate.js +2 -1
- package/core/dist/runtime/admission-gate.js.map +1 -1
- package/core/dist/runtime/config/pd-config-defaults.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-defaults.js +20 -2
- package/core/dist/runtime/config/pd-config-defaults.js.map +1 -1
- package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-validate.js +18 -0
- package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
- package/core/dist/runtime/context-payload.d.ts +48 -3
- package/core/dist/runtime/context-payload.d.ts.map +1 -1
- package/core/dist/runtime/context-payload.js +38 -0
- package/core/dist/runtime/context-payload.js.map +1 -1
- package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts +8 -2
- package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts.map +1 -1
- package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js +28 -2
- package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js.map +1 -1
- package/core/dist/runtime/diagnostician-candidate.d.ts +24 -0
- package/core/dist/runtime/diagnostician-candidate.d.ts.map +1 -0
- package/core/dist/runtime/diagnostician-candidate.js +55 -0
- package/core/dist/runtime/diagnostician-candidate.js.map +1 -0
- package/core/dist/runtime/evidence-guards.d.ts +10 -4
- package/core/dist/runtime/evidence-guards.d.ts.map +1 -1
- package/core/dist/runtime/evidence-guards.js +12 -5
- package/core/dist/runtime/evidence-guards.js.map +1 -1
- package/core/dist/runtime/evolution/evolution-types.d.ts +4 -4
- package/core/dist/runtime/evolution/evolution-types.d.ts.map +1 -1
- package/core/dist/runtime/evolution/evolution-types.js +1 -0
- package/core/dist/runtime/evolution/evolution-types.js.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-contract.js +14 -0
- package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +16 -0
- package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
- package/core/dist/runtime/index.d.ts +5 -2
- package/core/dist/runtime/index.d.ts.map +1 -1
- package/core/dist/runtime/index.js +6 -1
- package/core/dist/runtime/index.js.map +1 -1
- package/core/dist/runtime/internalization/index.d.ts +1 -0
- package/core/dist/runtime/internalization/index.d.ts.map +1 -1
- package/core/dist/runtime/internalization/index.js +2 -0
- package/core/dist/runtime/internalization/index.js.map +1 -1
- package/core/dist/runtime/internalization/rule-host-contracts.d.ts +10 -0
- package/core/dist/runtime/internalization/rule-host-contracts.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rule-host-evaluator.js +10 -10
- package/core/dist/runtime/internalization/rule-host-evaluator.js.map +1 -1
- package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +7 -6
- package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rule-host-input-builder.js +6 -2
- package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
- package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts +33 -0
- package/core/dist/runtime/internalization/rule-host-result-normalizer.d.ts.map +1 -0
- package/core/dist/runtime/internalization/rule-host-result-normalizer.js +61 -0
- package/core/dist/runtime/internalization/rule-host-result-normalizer.js.map +1 -0
- package/core/dist/runtime/internalization/rule-host-validator.d.ts.map +1 -1
- package/core/dist/runtime/internalization/rule-host-validator.js +17 -0
- package/core/dist/runtime/internalization/rule-host-validator.js.map +1 -1
- package/core/dist/runtime/pain-ingress-payload.d.ts +27 -2
- package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
- package/core/dist/runtime/pain-ingress-payload.js +45 -3
- package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
- package/core/dist/runtime/pain-ingress.d.ts +4 -2
- package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
- package/core/dist/runtime/pain-ingress.js +23 -3
- package/core/dist/runtime/pain-ingress.js.map +1 -1
- package/core/dist/runtime/pain-severity.d.ts +14 -0
- package/core/dist/runtime/pain-severity.d.ts.map +1 -0
- package/core/dist/runtime/pain-severity.js +14 -0
- package/core/dist/runtime/pain-severity.js.map +1 -0
- package/core/dist/runtime/pain-signal-bridge.d.ts +17 -3
- package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
- package/core/dist/runtime/pain-signal-bridge.js +6 -0
- package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
- package/core/dist/runtime/pain-signal-observability.d.ts.map +1 -1
- package/core/dist/runtime/pain-signal-observability.js +3 -2
- package/core/dist/runtime/pain-signal-observability.js.map +1 -1
- package/core/dist/runtime/pain-submit-capability.d.ts +164 -0
- package/core/dist/runtime/pain-submit-capability.d.ts.map +1 -0
- package/core/dist/runtime/pain-submit-capability.js +442 -0
- package/core/dist/runtime/pain-submit-capability.js.map +1 -0
- package/core/dist/runtime/pain-to-principle-service.d.ts +4 -0
- package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
- package/core/dist/runtime/pain-to-principle-service.js +2 -0
- package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
- package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts +56 -10
- package/core/dist/runtime/stalled-diagnostician-task-read-model.d.ts.map +1 -1
- package/core/dist/runtime/stalled-diagnostician-task-read-model.js +80 -4
- package/core/dist/runtime/stalled-diagnostician-task-read-model.js.map +1 -1
- package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
- package/core/dist/runtime/store/context/sqlite-context-assembler.js +11 -0
- package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
- package/core/dist/runtime/store/run/memory-run-store.d.ts +10 -0
- package/core/dist/runtime/store/run/memory-run-store.d.ts.map +1 -1
- package/core/dist/runtime/store/run/memory-run-store.js +21 -0
- package/core/dist/runtime/store/run/memory-run-store.js.map +1 -1
- package/core/dist/runtime/store/run/run-store.d.ts +12 -0
- package/core/dist/runtime/store/run/run-store.d.ts.map +1 -1
- package/core/dist/runtime/store/run/sqlite-run-store.d.ts +1 -0
- package/core/dist/runtime/store/run/sqlite-run-store.d.ts.map +1 -1
- package/core/dist/runtime/store/run/sqlite-run-store.js +14 -0
- package/core/dist/runtime/store/run/sqlite-run-store.js.map +1 -1
- package/core/dist/runtime/task-status.d.ts +9 -0
- package/core/dist/runtime/task-status.d.ts.map +1 -1
- package/core/dist/runtime/task-status.js +7 -1
- package/core/dist/runtime/task-status.js.map +1 -1
- package/core/dist/runtime/types/evidence-chain-contract.d.ts +18 -0
- package/core/dist/runtime/types/evidence-chain-contract.d.ts.map +1 -1
- package/core/dist/runtime/types/evidence-chain-contract.js +37 -7
- package/core/dist/runtime/types/evidence-chain-contract.js.map +1 -1
- package/core/package.json +5 -1
- package/dist/install-summary.d.ts +7 -0
- package/dist/install-summary.d.ts.map +1 -1
- package/dist/install-summary.js +4 -0
- package/dist/install-summary.js.map +1 -1
- package/dist/installer.d.ts +92 -8
- package/dist/installer.d.ts.map +1 -1
- package/dist/installer.js +215 -10
- package/dist/installer.js.map +1 -1
- package/dist/installers/codex-host-installer.d.ts +88 -1
- package/dist/installers/codex-host-installer.d.ts.map +1 -1
- package/dist/installers/codex-host-installer.js +350 -11
- package/dist/installers/codex-host-installer.js.map +1 -1
- package/dist/installers/index.d.ts +23 -0
- package/dist/installers/index.d.ts.map +1 -1
- package/dist/installers/index.js +38 -1
- package/dist/installers/index.js.map +1 -1
- package/dist/installers/legacy-workbuddy-skill.d.ts +59 -0
- package/dist/installers/legacy-workbuddy-skill.d.ts.map +1 -0
- package/dist/installers/legacy-workbuddy-skill.js +168 -0
- package/dist/installers/legacy-workbuddy-skill.js.map +1 -0
- package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
- package/dist/installers/workbuddy-host-installer.js +7 -0
- package/dist/installers/workbuddy-host-installer.js.map +1 -1
- package/host-runtime/dist/adaptive-priority-provider.d.ts +94 -0
- package/host-runtime/dist/adaptive-priority-provider.js +162 -0
- package/host-runtime/dist/adaptive-selection.d.ts +164 -0
- package/host-runtime/dist/adaptive-selection.js +506 -0
- package/host-runtime/dist/diagnostician-auto-run.d.ts +28 -0
- package/host-runtime/dist/diagnostician-auto-run.js +100 -0
- package/host-runtime/dist/host-tool-semantic-resolver.d.ts +42 -1
- package/host-runtime/dist/host-tool-semantic-resolver.js +80 -14
- package/host-runtime/dist/index.d.ts +4 -0
- package/host-runtime/dist/index.js +6 -0
- package/host-runtime/dist/production-rulehost-gate.js +17 -17
- package/host-runtime/dist/rulecode-event-collection.d.ts +31 -0
- package/host-runtime/dist/rulecode-event-collection.js +62 -0
- package/host-runtime/package.json +1 -1
- package/install-layout/dist/index.d.ts +1 -1
- package/install-layout/dist/index.js +1 -1
- package/install-layout/dist/pd-home.d.ts +9 -2
- package/install-layout/dist/pd-home.js +77 -14
- package/install-layout/package.json +1 -1
- package/package.json +4 -4
- package/pd-cli/dist/commands/diagnose.d.ts +30 -0
- package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
- package/pd-cli/dist/commands/diagnose.js +75 -0
- package/pd-cli/dist/commands/diagnose.js.map +1 -1
- package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
- package/pd-cli/dist/commands/pain-record.js +5 -4
- package/pd-cli/dist/commands/pain-record.js.map +1 -1
- package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
- package/pd-cli/dist/commands/pain-retry.js +2 -1
- package/pd-cli/dist/commands/pain-retry.js.map +1 -1
- package/pd-cli/dist/commands/runtime-activation.d.ts +6 -17
- package/pd-cli/dist/commands/runtime-activation.d.ts.map +1 -1
- package/pd-cli/dist/commands/runtime-activation.js +42 -48
- package/pd-cli/dist/commands/runtime-activation.js.map +1 -1
- package/pd-cli/dist/commands/runtime-compatibility-scan.d.ts +5 -2
- package/pd-cli/dist/commands/runtime-compatibility-scan.d.ts.map +1 -1
- package/pd-cli/dist/commands/runtime-compatibility-scan.js +22 -2
- package/pd-cli/dist/commands/runtime-compatibility-scan.js.map +1 -1
- package/pd-cli/dist/index.js +1 -0
- package/pd-cli/dist/index.js.map +1 -1
- package/pd-cli/dist/services/config-doctor.d.ts +9 -0
- package/pd-cli/dist/services/config-doctor.d.ts.map +1 -1
- package/pd-cli/dist/services/config-doctor.js +15 -0
- package/pd-cli/dist/services/config-doctor.js.map +1 -1
- package/pd-cli/dist/services/delivery-surfaces.js +1 -1
- package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
- package/pd-cli/package.json +1 -1
- package/pd-mcp-server/dist/budget.d.ts +1 -1
- package/pd-mcp-server/dist/budget.js +2 -2
- package/pd-mcp-server/dist/envelope.d.ts +15 -0
- package/pd-mcp-server/dist/envelope.js +49 -1
- package/pd-mcp-server/dist/index.d.ts +2 -0
- package/pd-mcp-server/dist/index.js +6 -0
- package/pd-mcp-server/dist/server.d.ts +83 -14
- package/pd-mcp-server/dist/server.js +251 -4
- package/pd-mcp-server/dist/version.d.ts +1 -1
- package/pd-mcp-server/dist/version.js +1 -1
- package/pd-mcp-server/dist/workspace.d.ts +4 -2
- package/pd-mcp-server/dist/workspace.js +5 -2
- package/pd-mcp-server/package.json +1 -1
- package/plugin/dist/bundle.js +443 -431
- package/plugin/dist/core/evolution-reducer.d.ts +2 -2
- package/plugin/dist/hooks/hook-tool-semantics.d.ts +25 -0
- package/plugin/dist/hooks/pain-ingress-adapter.d.ts +1 -1
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/dist/rulehost-evidence.js +1 -1
- package/plugin/openclaw.plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/release-manager/dist/installer.js +215 -10
- package/release-manager/dist/installers/codex-host-installer.js +350 -11
- package/release-manager/dist/installers/index.js +38 -1
- package/release-manager/dist/installers/legacy-workbuddy-skill.js +168 -0
- package/release-manager/dist/installers/workbuddy-host-installer.js +7 -0
- package/release-manager/package.json +1 -1
- package/workbuddy-adapter/dist/pd-hook.js +20 -4
- package/workbuddy-adapter/package.json +1 -1
- package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +123 -20
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adaptive Activation — shared selection protocol (SPEC v0.6 §4/§7/§9).
|
|
3
|
+
*
|
|
4
|
+
* ONE implementation of the bounded "current turn → pick at most one candidate"
|
|
5
|
+
* protocol, shared by the selector lab and the production host runtimes.
|
|
6
|
+
*
|
|
7
|
+
* Contract highlights (PRI-1122 measurement findings):
|
|
8
|
+
* - Candidates are sent with a LOCALLY PRECOMPUTED digest. The model can only
|
|
9
|
+
* copy it; it is never asked to compute a hash. A payload without digests
|
|
10
|
+
* makes every `selected` answer invalid by construction.
|
|
11
|
+
* - The incremental deadline is a FIRST-BYTE deadline, not a whole-generation
|
|
12
|
+
* wall clock. Once the endpoint has started answering, generation is bounded
|
|
13
|
+
* by its own window; late completions are still discarded.
|
|
14
|
+
* - One real send per turn, zero retries, zero repair, zero provider fallback.
|
|
15
|
+
* - Diagnostics never carry the raw prompt, the raw response, or credentials.
|
|
16
|
+
*/
|
|
17
|
+
import crypto from 'node:crypto';
|
|
18
|
+
import { PiAiRuntimeAdapter, StoreEventEmitter, } from '@principles/core/runtime';
|
|
19
|
+
import { readPromptActivationCandidates } from './active-principle-prompt.js';
|
|
20
|
+
import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
|
|
21
|
+
export const ADAPTIVE_SELECTION_LIMITS = {
|
|
22
|
+
maxCandidates: 12,
|
|
23
|
+
maxCandidateChars: 600,
|
|
24
|
+
maxPriorMessages: 4,
|
|
25
|
+
maxPriorMessageChars: 1200,
|
|
26
|
+
maxInputChars: 6000,
|
|
27
|
+
/** Admission (time-to-first-byte) deadline for the incremental step. */
|
|
28
|
+
firstByteTimeoutMs: 10_000,
|
|
29
|
+
/** Bounded completion window once the endpoint has started answering. */
|
|
30
|
+
generationTimeoutMs: 10_000,
|
|
31
|
+
maxOutputTokens: 512,
|
|
32
|
+
};
|
|
33
|
+
export function hash(value) {
|
|
34
|
+
return crypto.createHash('sha256').update(value, 'utf8').digest('hex');
|
|
35
|
+
}
|
|
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
|
+
function boundText(value, max) {
|
|
48
|
+
const text = value.replace(/\s+/gu, ' ').trim();
|
|
49
|
+
if (text.length <= max)
|
|
50
|
+
return text;
|
|
51
|
+
return `${text.slice(0, max - 1)}…`;
|
|
52
|
+
}
|
|
53
|
+
export function buildBoundedSelectionInput(input) {
|
|
54
|
+
const currentInstruction = input.currentInput.trim();
|
|
55
|
+
if (!currentInstruction)
|
|
56
|
+
return { ok: false, reason: 'CURRENT_INSTRUCTION_EMPTY' };
|
|
57
|
+
if (currentInstruction.length > ADAPTIVE_SELECTION_LIMITS.maxInputChars) {
|
|
58
|
+
return { ok: false, reason: 'CURRENT_INSTRUCTION_TOO_LARGE' };
|
|
59
|
+
}
|
|
60
|
+
const priorMessages = input.priorMessages ?? [];
|
|
61
|
+
const selectedPrior = priorMessages.slice(-ADAPTIVE_SELECTION_LIMITS.maxPriorMessages);
|
|
62
|
+
const boundedPrior = selectedPrior.map((message, index) => ({
|
|
63
|
+
text: boundText(message.text, ADAPTIVE_SELECTION_LIMITS.maxPriorMessageChars),
|
|
64
|
+
source: message.source ?? 'prior',
|
|
65
|
+
index,
|
|
66
|
+
}));
|
|
67
|
+
const entries = [];
|
|
68
|
+
for (const principle of input.candidates) {
|
|
69
|
+
if (!principle.artifactContentSha256)
|
|
70
|
+
continue;
|
|
71
|
+
if (!principle.text.trim())
|
|
72
|
+
continue;
|
|
73
|
+
const candidateText = boundText(principle.text, ADAPTIVE_SELECTION_LIMITS.maxCandidateChars);
|
|
74
|
+
entries.push({
|
|
75
|
+
ref: `c${entries.length + 1}`,
|
|
76
|
+
text: candidateText,
|
|
77
|
+
// Digest the body exactly as it goes on the wire, so the model can copy it
|
|
78
|
+
// and anyone can recompute it from the request it actually received.
|
|
79
|
+
digest: hash(candidateText),
|
|
80
|
+
principle,
|
|
81
|
+
});
|
|
82
|
+
if (entries.length >= ADAPTIVE_SELECTION_LIMITS.maxCandidates)
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
if (entries.length === 0)
|
|
86
|
+
return { ok: false, reason: 'NO_CANDIDATES' };
|
|
87
|
+
return {
|
|
88
|
+
ok: true,
|
|
89
|
+
input: {
|
|
90
|
+
payload: {
|
|
91
|
+
currentInstruction,
|
|
92
|
+
priorMessages: boundedPrior,
|
|
93
|
+
// The digest is part of the outbound contract: the model copies it.
|
|
94
|
+
candidates: entries.map((entry) => ({ ref: entry.ref, text: entry.text, digest: entry.digest })),
|
|
95
|
+
},
|
|
96
|
+
entries,
|
|
97
|
+
priorDropped: Math.max(0, priorMessages.length - selectedPrior.length),
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** rc-1/rc-2: parsed payloads are unknown until this guard passes. */
|
|
102
|
+
function isRecord(value) {
|
|
103
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
104
|
+
}
|
|
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
|
+
function outerDeadlineReached(now, outerDeadlineAt, signal) {
|
|
174
|
+
// Without an outer deadline this is an ordinary caller signal; keep the
|
|
175
|
+
// previous SELECTION_EXPIRED / TRANSPORT_FAILED classification for it.
|
|
176
|
+
return outerDeadlineAt !== undefined && (signal?.aborted === true || now() >= outerDeadlineAt);
|
|
177
|
+
}
|
|
178
|
+
function emptyDiagnostics(admissionDeadlineAt) {
|
|
179
|
+
return {
|
|
180
|
+
stage: 'idle',
|
|
181
|
+
admissionDeadlineAt,
|
|
182
|
+
completionDeadlineAt: null,
|
|
183
|
+
firstByteAt: null,
|
|
184
|
+
generationEndedAt: null,
|
|
185
|
+
cancelledAt: null,
|
|
186
|
+
httpStatus: null,
|
|
187
|
+
finishReason: 'unknown',
|
|
188
|
+
usage: null,
|
|
189
|
+
failures: [],
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function parseFinishMetadata(raw) {
|
|
193
|
+
const result = { finishReason: 'unknown', usage: null };
|
|
194
|
+
const absorb = (parsed) => {
|
|
195
|
+
if (!isRecord(parsed))
|
|
196
|
+
return;
|
|
197
|
+
const { choices } = parsed;
|
|
198
|
+
if (Array.isArray(choices) && choices.length > 0) {
|
|
199
|
+
const [first] = choices;
|
|
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
|
+
}
|
|
215
|
+
};
|
|
216
|
+
const trimmed = raw.trim();
|
|
217
|
+
if (!trimmed)
|
|
218
|
+
return result;
|
|
219
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
220
|
+
try {
|
|
221
|
+
absorb(JSON.parse(trimmed));
|
|
222
|
+
return result;
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
for (const line of trimmed.split(/\r?\n/u)) {
|
|
229
|
+
const payload = line.startsWith('data:') ? line.slice(5).trim() : '';
|
|
230
|
+
if (!payload || payload === '[DONE]')
|
|
231
|
+
continue;
|
|
232
|
+
try {
|
|
233
|
+
absorb(JSON.parse(payload));
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
// Ignore non-JSON keep-alives; diagnostics stay 'unknown' rather than guessing.
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return result;
|
|
240
|
+
}
|
|
241
|
+
export function createSingleModelSelector(options) {
|
|
242
|
+
const now = options.now ?? Date.now;
|
|
243
|
+
const Adapter = options.PiAiRuntimeAdapterImpl ?? PiAiRuntimeAdapter;
|
|
244
|
+
const generationTimeoutMs = options.generationTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.generationTimeoutMs;
|
|
245
|
+
const maxTokens = options.maxTokens ?? ADAPTIVE_SELECTION_LIMITS.maxOutputTokens;
|
|
246
|
+
const diagnostics = emptyDiagnostics(options.admissionDeadlineAt);
|
|
247
|
+
let sends = 0;
|
|
248
|
+
let status = 'not_sent';
|
|
249
|
+
let failure = null;
|
|
250
|
+
let finishMetadata = Promise.resolve({ finishReason: 'unknown', usage: null });
|
|
251
|
+
const fail = (code) => {
|
|
252
|
+
failure = code;
|
|
253
|
+
status = 'failed';
|
|
254
|
+
diagnostics.failures.push(code);
|
|
255
|
+
throw new Error(code);
|
|
256
|
+
};
|
|
257
|
+
const selector = async (input) => {
|
|
258
|
+
if (sends > 0)
|
|
259
|
+
fail('TRANSPORT_NOT_SENT');
|
|
260
|
+
if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
|
|
261
|
+
diagnostics.cancelledAt = now();
|
|
262
|
+
fail('TURN_DEADLINE_EXCEEDED');
|
|
263
|
+
}
|
|
264
|
+
if (now() >= options.admissionDeadlineAt) {
|
|
265
|
+
diagnostics.cancelledAt = now();
|
|
266
|
+
fail('SELECTION_EXPIRED');
|
|
267
|
+
}
|
|
268
|
+
const remainingAdmission = Math.max(1, options.admissionDeadlineAt - now());
|
|
269
|
+
const ttfbController = new AbortController();
|
|
270
|
+
const ttfbTimer = setTimeout(() => ttfbController.abort(new Error('ADMISSION_DEADLINE')), remainingAdmission);
|
|
271
|
+
ttfbTimer.unref?.();
|
|
272
|
+
let firstByteAt = null;
|
|
273
|
+
let completionDeadlineAt = null;
|
|
274
|
+
const guardedFetch = async (resource, init) => {
|
|
275
|
+
const url = resource instanceof Request ? resource.url : String(resource);
|
|
276
|
+
const requestInit = init ?? {};
|
|
277
|
+
if (options.model.url) {
|
|
278
|
+
if (url !== options.model.url)
|
|
279
|
+
fail('TRANSPORT_NOT_SENT');
|
|
280
|
+
}
|
|
281
|
+
else if (options.model.baseUrl) {
|
|
282
|
+
if (!url.startsWith(options.model.baseUrl))
|
|
283
|
+
fail('TRANSPORT_NOT_SENT');
|
|
284
|
+
}
|
|
285
|
+
else if (!url.startsWith('https://')) {
|
|
286
|
+
fail('TRANSPORT_NOT_SENT');
|
|
287
|
+
}
|
|
288
|
+
let body;
|
|
289
|
+
try {
|
|
290
|
+
const parsed = typeof requestInit.body === 'string' ? JSON.parse(requestInit.body) : null;
|
|
291
|
+
body = isRecord(parsed) ? parsed : null;
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
body = null;
|
|
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
|
+
]);
|
|
311
|
+
let response;
|
|
312
|
+
try {
|
|
313
|
+
response = await (options.fetchImpl ?? fetch)(url, { ...requestInit, signal: combined, redirect: 'error' });
|
|
314
|
+
}
|
|
315
|
+
catch (error) {
|
|
316
|
+
diagnostics.cancelledAt = now();
|
|
317
|
+
diagnostics.stage = 'admission';
|
|
318
|
+
fail(outerDeadlineReached(now, options.outerDeadlineAt, options.signal)
|
|
319
|
+
? 'TURN_DEADLINE_EXCEEDED'
|
|
320
|
+
: ttfbController.signal.aborted ? 'SELECTION_EXPIRED' : 'TRANSPORT_FAILED');
|
|
321
|
+
throw error;
|
|
322
|
+
}
|
|
323
|
+
// First byte is here: stop the admission clock, start the completion window.
|
|
324
|
+
firstByteAt = now();
|
|
325
|
+
diagnostics.firstByteAt = firstByteAt;
|
|
326
|
+
diagnostics.httpStatus = response.status;
|
|
327
|
+
clearTimeout(ttfbTimer);
|
|
328
|
+
if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
|
|
329
|
+
diagnostics.cancelledAt = firstByteAt;
|
|
330
|
+
fail('TURN_DEADLINE_EXCEEDED');
|
|
331
|
+
}
|
|
332
|
+
if (firstByteAt >= options.admissionDeadlineAt) {
|
|
333
|
+
diagnostics.cancelledAt = firstByteAt;
|
|
334
|
+
fail('SELECTION_EXPIRED');
|
|
335
|
+
}
|
|
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
|
+
diagnostics.stage = 'generation';
|
|
343
|
+
try {
|
|
344
|
+
const clone = response.clone();
|
|
345
|
+
finishMetadata = clone
|
|
346
|
+
.text()
|
|
347
|
+
.then((raw) => parseFinishMetadata(raw))
|
|
348
|
+
.catch(() => ({ finishReason: 'unknown', usage: null }));
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
finishMetadata = Promise.resolve({ finishReason: 'unknown', usage: null });
|
|
352
|
+
}
|
|
353
|
+
return response;
|
|
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
|
+
const run = await adapter.startRun({
|
|
371
|
+
agentSpec: { agentId: 'adaptive-principle-selector', schemaVersion: 'current' },
|
|
372
|
+
inputPayload: input.payload,
|
|
373
|
+
contextItems: [],
|
|
374
|
+
timeoutMs: remainingAdmission + generationTimeoutMs,
|
|
375
|
+
maxTokens,
|
|
376
|
+
systemPrompt: ADAPTIVE_SELECTOR_SYSTEM,
|
|
377
|
+
});
|
|
378
|
+
const output = await adapter.fetchOutput(run.runId);
|
|
379
|
+
const endedAt = now();
|
|
380
|
+
diagnostics.generationEndedAt = endedAt;
|
|
381
|
+
if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
|
|
382
|
+
diagnostics.cancelledAt = endedAt;
|
|
383
|
+
fail('TURN_DEADLINE_EXCEEDED');
|
|
384
|
+
}
|
|
385
|
+
if (!output)
|
|
386
|
+
fail('SELECTION_OUTPUT_INVALID');
|
|
387
|
+
if (completionDeadlineAt !== null && endedAt > completionDeadlineAt) {
|
|
388
|
+
diagnostics.cancelledAt = endedAt;
|
|
389
|
+
fail('SELECTION_EXPIRED');
|
|
390
|
+
}
|
|
391
|
+
const metadata = await finishMetadata;
|
|
392
|
+
diagnostics.finishReason = metadata.finishReason;
|
|
393
|
+
diagnostics.usage = metadata.usage;
|
|
394
|
+
diagnostics.stage = 'validate';
|
|
395
|
+
return output.payload;
|
|
396
|
+
}
|
|
397
|
+
catch (error) {
|
|
398
|
+
// An abort can surface while the adapter reads the body (the fetch call
|
|
399
|
+
// itself already resolved), so classify it here, at the transport edge.
|
|
400
|
+
if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
|
|
401
|
+
diagnostics.cancelledAt = now();
|
|
402
|
+
fail('TURN_DEADLINE_EXCEEDED');
|
|
403
|
+
}
|
|
404
|
+
throw error;
|
|
405
|
+
}
|
|
406
|
+
finally {
|
|
407
|
+
clearTimeout(ttfbTimer);
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
return {
|
|
411
|
+
select: selector,
|
|
412
|
+
report: () => ({ sends, status, failure, diagnostics }),
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Minimal host-facing selection step: read the current frozen candidates,
|
|
417
|
+
* make at most one bounded model call, verify ref+digest, then independently
|
|
418
|
+
* revalidate the chosen principle's content/revision/authorization.
|
|
419
|
+
*/
|
|
420
|
+
export async function runAdaptiveSelection(options) {
|
|
421
|
+
const earlyDiagnostics = emptyDiagnostics(options.admissionDeadlineAt);
|
|
422
|
+
const unavailable = (reason, stage) => {
|
|
423
|
+
earlyDiagnostics.stage = stage;
|
|
424
|
+
return { status: 'unavailable', target: null, reason, sends: 0, diagnostics: earlyDiagnostics };
|
|
425
|
+
};
|
|
426
|
+
const read = await readPromptActivationCandidates({
|
|
427
|
+
workspaceDir: options.workspaceDir,
|
|
428
|
+
includeAuthority: true,
|
|
429
|
+
});
|
|
430
|
+
if (read.aborted || read.warnings.length > 0) {
|
|
431
|
+
return unavailable(`candidates_unavailable:${read.warnings[0] ?? 'aborted'}`, 'idle');
|
|
432
|
+
}
|
|
433
|
+
const built = buildBoundedSelectionInput({
|
|
434
|
+
currentInput: options.currentPrompt,
|
|
435
|
+
candidates: read.principles,
|
|
436
|
+
});
|
|
437
|
+
if (!built.ok)
|
|
438
|
+
return unavailable(built.reason, 'idle');
|
|
439
|
+
const selector = createSingleModelSelector({
|
|
440
|
+
admissionDeadlineAt: options.admissionDeadlineAt,
|
|
441
|
+
model: options.model,
|
|
442
|
+
...(options.generationTimeoutMs !== undefined ? { generationTimeoutMs: options.generationTimeoutMs } : {}),
|
|
443
|
+
...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),
|
|
444
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
445
|
+
...(options.outerDeadlineAt !== undefined ? { outerDeadlineAt: options.outerDeadlineAt } : {}),
|
|
446
|
+
...(options.now ? { now: options.now } : {}),
|
|
447
|
+
...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
|
|
448
|
+
...(options.PiAiRuntimeAdapterImpl
|
|
449
|
+
? { PiAiRuntimeAdapterImpl: options.PiAiRuntimeAdapterImpl }
|
|
450
|
+
: {}),
|
|
451
|
+
});
|
|
452
|
+
let payload;
|
|
453
|
+
try {
|
|
454
|
+
payload = await selector.select(built.input);
|
|
455
|
+
}
|
|
456
|
+
catch {
|
|
457
|
+
const report = selector.report();
|
|
458
|
+
// The selector owns the failing stage and the failure code; do not
|
|
459
|
+
// overwrite either with a coarser guess.
|
|
460
|
+
const { diagnostics } = report;
|
|
461
|
+
const reason = report.failure ?? 'TRANSPORT_FAILED';
|
|
462
|
+
if (!diagnostics.failures.includes(reason))
|
|
463
|
+
diagnostics.failures.push(reason);
|
|
464
|
+
return { status: 'none', target: null, reason, sends: report.sends, diagnostics };
|
|
465
|
+
}
|
|
466
|
+
// The selector owns the timing facts (first byte, completion, cancellation).
|
|
467
|
+
const report = selector.report();
|
|
468
|
+
const { diagnostics } = report;
|
|
469
|
+
const { sends } = report;
|
|
470
|
+
const validated = validateSelectionResult(payload, built.input.entries);
|
|
471
|
+
if (!validated.ok) {
|
|
472
|
+
diagnostics.stage = 'validate';
|
|
473
|
+
diagnostics.failures.push(localFailureCode(validated.reason));
|
|
474
|
+
return { status: 'none', target: null, reason: validated.reason, sends, diagnostics };
|
|
475
|
+
}
|
|
476
|
+
if (!validated.selected) {
|
|
477
|
+
diagnostics.stage = 'done';
|
|
478
|
+
return { status: 'none', target: null, reason: validated.outcome, sends, diagnostics };
|
|
479
|
+
}
|
|
480
|
+
const target = validated.selected.principle;
|
|
481
|
+
diagnostics.stage = 'revalidate';
|
|
482
|
+
const now = options.now ?? Date.now;
|
|
483
|
+
const revalidationBudgetMs = options.generationTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.generationTimeoutMs;
|
|
484
|
+
const signal = options.signal ?? AbortSignal.timeout(options.outerDeadlineAt === undefined
|
|
485
|
+
? revalidationBudgetMs
|
|
486
|
+
: Math.max(1, Math.min(revalidationBudgetMs, options.outerDeadlineAt - now())));
|
|
487
|
+
const stillValid = await revalidateAdaptivePrinciple(options.workspaceDir, target, signal);
|
|
488
|
+
const stale = outerDeadlineReached(now, options.outerDeadlineAt, options.signal);
|
|
489
|
+
if (!stillValid || stale) {
|
|
490
|
+
diagnostics.stage = 'done';
|
|
491
|
+
if (stale && !diagnostics.failures.includes('TURN_DEADLINE_EXCEEDED')) {
|
|
492
|
+
diagnostics.failures.push('TURN_DEADLINE_EXCEEDED');
|
|
493
|
+
}
|
|
494
|
+
if (stale)
|
|
495
|
+
diagnostics.cancelledAt = diagnostics.cancelledAt ?? now();
|
|
496
|
+
return {
|
|
497
|
+
status: 'none',
|
|
498
|
+
target: null,
|
|
499
|
+
reason: stale ? 'TURN_DEADLINE_EXCEEDED' : 'revalidation_failed',
|
|
500
|
+
sends,
|
|
501
|
+
diagnostics,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
diagnostics.stage = 'done';
|
|
505
|
+
return { status: 'selected', target, reason: 'selected', sends, diagnostics };
|
|
506
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Quiet flag that owns the L3 half of the ladder. */
|
|
2
|
+
export declare const DIAGNOSTICIAN_AUTO_RUN_FLAG = "openclaw_diagnostician_consumer";
|
|
3
|
+
/** Owner string used for the diagnostics this module starts. */
|
|
4
|
+
export declare const DIAGNOSTICIAN_AUTO_RUN_OWNER = "pd-auto-diagnostician";
|
|
5
|
+
export type PendingDiagnosticianSkipReason = 'flag_off' | 'capability_disabled' | 'service_not_running' | 'no_candidate';
|
|
6
|
+
export interface PendingDiagnosticianRunResult {
|
|
7
|
+
readonly served: boolean;
|
|
8
|
+
readonly taskId?: string;
|
|
9
|
+
/** Present when nothing was served. */
|
|
10
|
+
readonly reason?: PendingDiagnosticianSkipReason | 'execution_failed';
|
|
11
|
+
readonly message?: string;
|
|
12
|
+
readonly nextAction?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface RunPendingDiagnosticianOptions {
|
|
15
|
+
readonly workspaceDir: string;
|
|
16
|
+
readonly owner?: string;
|
|
17
|
+
readonly limit?: number;
|
|
18
|
+
readonly now?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Precondition 1. Defaults to `true`: the only production caller IS the
|
|
21
|
+
* consumer timer. A non-service caller must pass `false` to get the
|
|
22
|
+
* `service_not_running` skip instead of silently starting work it has no
|
|
23
|
+
* timer to continue.
|
|
24
|
+
*/
|
|
25
|
+
readonly serviceStarted?: boolean;
|
|
26
|
+
readonly getEnvVar?: (name: string) => string | undefined;
|
|
27
|
+
}
|
|
28
|
+
export declare function runPendingDiagnosticianOnce(options: RunPendingDiagnosticianOptions): Promise<PendingDiagnosticianRunResult>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* L3 — one bounded automatic-diagnosis round (SPEC-PD-AGENT-PAIN-INGRESS-001
|
|
3
|
+
* §8.4 / TECHNICAL-DESIGN §8.4).
|
|
4
|
+
*
|
|
5
|
+
* The degradation ladder is: L2 Console request-driven, L3 OpenClaw automatic,
|
|
6
|
+
* L4 offline/manual. This module is ONLY the L3 body: it is called from the
|
|
7
|
+
* existing `internalization_auto_consumer` timer (no new timer, no new
|
|
8
|
+
* background process) and serves at most one diagnostician task per call.
|
|
9
|
+
*
|
|
10
|
+
* Three preconditions, each with its own reason so the Owner can tell WHY
|
|
11
|
+
* nothing happened:
|
|
12
|
+
* 1. `serviceStarted` — the tick that calls us is by definition the service;
|
|
13
|
+
* the flag exists so a non-service caller can state it is not running.
|
|
14
|
+
* 2. `openclaw_diagnostician_consumer` flag (quiet, default on).
|
|
15
|
+
* 3. Diagnostician capability (`internalAgents.agents.diagnostician.enabled`).
|
|
16
|
+
*
|
|
17
|
+
* A skip is never a failure: the task keeps its pending state and L2 can still
|
|
18
|
+
* serve it. Nothing is marked, mutated or deleted on any skip path.
|
|
19
|
+
*/
|
|
20
|
+
import * as path from 'node:path';
|
|
21
|
+
import { PrincipleTreeLedgerAdapter, createPainSignalBridge, createRuntimeStateHandle, pickDiagnosticianCandidate, resolveDiagnosticianCapability, } from '@principles/core/runtime';
|
|
22
|
+
import { loadFeatureFlagFromConfig, loadPdConfigForPlugin } from './pd-config.js';
|
|
23
|
+
/** Quiet flag that owns the L3 half of the ladder. */
|
|
24
|
+
export const DIAGNOSTICIAN_AUTO_RUN_FLAG = 'openclaw_diagnostician_consumer';
|
|
25
|
+
/** Owner string used for the diagnostics this module starts. */
|
|
26
|
+
export const DIAGNOSTICIAN_AUTO_RUN_OWNER = 'pd-auto-diagnostician';
|
|
27
|
+
const DEFAULT_CANDIDATE_LIMIT = 1;
|
|
28
|
+
export async function runPendingDiagnosticianOnce(options) {
|
|
29
|
+
if (options.serviceStarted === false) {
|
|
30
|
+
return {
|
|
31
|
+
served: false,
|
|
32
|
+
reason: 'service_not_running',
|
|
33
|
+
message: 'the internalization_auto_consumer service is not running',
|
|
34
|
+
nextAction: 'Start the OpenClaw service, or diagnose from Console (L2) which does not need a timer.',
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
const config = loadPdConfigForPlugin(options.workspaceDir);
|
|
38
|
+
const flag = loadFeatureFlagFromConfig(options.workspaceDir, DIAGNOSTICIAN_AUTO_RUN_FLAG);
|
|
39
|
+
if (!flag.enabled) {
|
|
40
|
+
return {
|
|
41
|
+
served: false,
|
|
42
|
+
reason: 'flag_off',
|
|
43
|
+
message: `features.${DIAGNOSTICIAN_AUTO_RUN_FLAG} is off`,
|
|
44
|
+
nextAction: 'Tasks stay pending for the Console request-driven path (L2); set the flag to true to re-enable automatic diagnosis.',
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const capability = resolveDiagnosticianCapability(config.effective);
|
|
48
|
+
if (!capability.available) {
|
|
49
|
+
return {
|
|
50
|
+
served: false,
|
|
51
|
+
reason: 'capability_disabled',
|
|
52
|
+
message: capability.message,
|
|
53
|
+
nextAction: capability.nextAction,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const handle = await createRuntimeStateHandle({ workspaceDir: options.workspaceDir, readonly: false });
|
|
57
|
+
try {
|
|
58
|
+
const now = options.now ?? new Date().toISOString();
|
|
59
|
+
const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.limit ?? DEFAULT_CANDIDATE_LIMIT, now);
|
|
60
|
+
if (candidate === null) {
|
|
61
|
+
return { served: false, reason: 'no_candidate' };
|
|
62
|
+
}
|
|
63
|
+
const stateDir = path.join(options.workspaceDir, '.state');
|
|
64
|
+
try {
|
|
65
|
+
const bridge = await createPainSignalBridge({
|
|
66
|
+
workspaceDir: options.workspaceDir,
|
|
67
|
+
stateDir,
|
|
68
|
+
ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
|
|
69
|
+
owner: options.owner ?? DIAGNOSTICIAN_AUTO_RUN_OWNER,
|
|
70
|
+
effectiveConfig: config.effective,
|
|
71
|
+
getEnvVar: options.getEnvVar ?? ((name) => process.env[name]),
|
|
72
|
+
});
|
|
73
|
+
const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
|
|
74
|
+
if (executed.status === 'failed') {
|
|
75
|
+
return {
|
|
76
|
+
served: false,
|
|
77
|
+
taskId: candidate.taskId,
|
|
78
|
+
reason: 'execution_failed',
|
|
79
|
+
...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
|
|
80
|
+
nextAction: 'Inspect the workspace runtime profile; the task keeps its pending/retry state for the next tick or Console (L2).',
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
return { served: true, taskId: candidate.taskId };
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
// A missing/!invalid runtime profile must not throw out of the timer that
|
|
87
|
+
// hosts us, and must not silently look like "no work" (rc-9).
|
|
88
|
+
return {
|
|
89
|
+
served: false,
|
|
90
|
+
taskId: candidate.taskId,
|
|
91
|
+
reason: 'execution_failed',
|
|
92
|
+
message: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200),
|
|
93
|
+
nextAction: 'Configure the workspace runtime profile; the task keeps its pending state for the next tick or Console (L2).',
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
await handle.close().catch(() => undefined);
|
|
99
|
+
}
|
|
100
|
+
}
|