@principles/codex-adapter 0.10.1 → 0.12.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/pd-hook.js
CHANGED
|
@@ -5,7 +5,8 @@ import path from 'node:path';
|
|
|
5
5
|
import process from 'node:process';
|
|
6
6
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
7
7
|
import { appendEventLogLine, redactTelemetryString, isRuleHostEvaluatedEventData } from '@principles/core/runtime';
|
|
8
|
-
import { ADAPTIVE_SELECTION_LIMITS, createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
|
|
8
|
+
import { ADAPTIVE_SELECTION_LIMITS, createAdaptivePriorityProviderForConfig, createCodexRuleContextProvider, createProductionHostRuntime, loadPdConfigForPlugin, renderAcceptedAdaptiveAppend, resolveHostToolSemanticsForHook, resolveNearestPdWorkspace } from '@principles/host-runtime';
|
|
9
|
+
import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-risk';
|
|
9
10
|
import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from './tool-semantics.js';
|
|
10
11
|
import { computeFeatureFlagsFromConfig } from '@principles/core/runtime';
|
|
11
12
|
import { CodexHooksHostAdapter } from './host-adapter.js';
|
|
@@ -15,6 +16,7 @@ import { runGovernanceAdmission } from './ingestion/admission.js';
|
|
|
15
16
|
import { parseOwnerStatementPrefix, recordExplicitOwnerStatement } from './ingestion/explicit-owner-statement.js';
|
|
16
17
|
import { writeCurrentTurnContext, clearCurrentTurnContext } from './ingestion/turn-context.js';
|
|
17
18
|
import { recordCodexPromptDeliveryEvidence, recordCodexDenyEvidence } from './codex-evidence-recorder.js';
|
|
19
|
+
import { ADAPTIVE_APPEND_SCHEMA_VERSION, appendAdaptiveAppendFact, appendToolObservation, claimAdaptiveAppendResult, claimAdaptiveReportMarker, clearAdaptiveAppendTurn, clearStaleAdaptiveAppendState, currentHookIdentity, discardAdaptiveAppendJob, evaluateAppendOrdering, hasAdaptiveAppendTurn, markAdaptiveTurnEnded, markAdaptiveTurnStarted, readToolObservations, releaseAdaptiveAppendClaim, spawnAdaptiveBackgroundSelection, writeAdaptiveAppendJob, } from './ingestion/adaptive-append-state.js';
|
|
18
20
|
const MAX_DIAGNOSTIC = 500;
|
|
19
21
|
function diagnostic(reason, nextAction) {
|
|
20
22
|
const boundedReason = reason.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
|
|
@@ -66,15 +68,28 @@ function redactStringFields(data) {
|
|
|
66
68
|
* writer, so the Codex host path stays independent of the OpenClaw plugin
|
|
67
69
|
* (codex-adapter must not depend on principles-disciple — bundle guard).
|
|
68
70
|
*/
|
|
69
|
-
function codexEventEmitter(stateDir, evidence) {
|
|
71
|
+
function codexEventEmitter(stateDir, evidence, readAdaptiveFact) {
|
|
70
72
|
return {
|
|
71
73
|
recordRuntimeActivationsInjected(data) {
|
|
74
|
+
// Adaptive Activation fact for this turn. Appended ONLY on the final
|
|
75
|
+
// assembly basis: a selection whose id did not reach `activationIds`
|
|
76
|
+
// (dropped by budget, replaced, failed packing) is not an append.
|
|
77
|
+
const fact = readAdaptiveFact?.() ?? null;
|
|
78
|
+
const adaptive = fact === null
|
|
79
|
+
? undefined
|
|
80
|
+
: {
|
|
81
|
+
resultCode: `${fact.status}:${fact.reason}`.slice(0, 240),
|
|
82
|
+
scored: fact.sends > 0,
|
|
83
|
+
...(fact.targetActivationId !== null && data.activationIds.includes(fact.targetActivationId)
|
|
84
|
+
? { appendedActivationId: fact.targetActivationId }
|
|
85
|
+
: {}),
|
|
86
|
+
};
|
|
72
87
|
appendEventLogLine(stateDir, {
|
|
73
88
|
ts: new Date().toISOString(),
|
|
74
89
|
type: 'runtime_v2_prompt_activations_injected',
|
|
75
90
|
category: 'injected',
|
|
76
91
|
sessionId: data.sessionId,
|
|
77
|
-
data,
|
|
92
|
+
data: adaptive === undefined ? data : { ...data, adaptive },
|
|
78
93
|
});
|
|
79
94
|
// PD v2 Phase 1: the durable source line is appended — now record the
|
|
80
95
|
// normalized agent-context delivery attempts (submitted, not delivered).
|
|
@@ -113,6 +128,108 @@ function codexEventEmitter(stateDir, evidence) {
|
|
|
113
128
|
},
|
|
114
129
|
};
|
|
115
130
|
}
|
|
131
|
+
/** One bounded Adaptive fact line; evidence is best-effort and never blocks the hook. */
|
|
132
|
+
function emitBackgroundFact(key, fact) {
|
|
133
|
+
try {
|
|
134
|
+
appendAdaptiveAppendFact({
|
|
135
|
+
stateDir: key.stateDir,
|
|
136
|
+
sessionId: key.sessionId,
|
|
137
|
+
turnId: key.turnId,
|
|
138
|
+
workspaceDir: key.workspaceDir,
|
|
139
|
+
resultCode: fact.resultCode,
|
|
140
|
+
scored: fact.scored,
|
|
141
|
+
budget: fact.budget,
|
|
142
|
+
injectedCharCount: fact.injectedCharCount,
|
|
143
|
+
...(fact.appended ? { appended: fact.appended } : {}),
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// A failed evidence write must not change the host decision.
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** Emit at most ONE terminal drop fact for this turn. */
|
|
151
|
+
function reportBackgroundDrop(key, drop) {
|
|
152
|
+
if (!claimAdaptiveReportMarker({ ...key, reason: drop.reason }))
|
|
153
|
+
return;
|
|
154
|
+
emitBackgroundFact(key, {
|
|
155
|
+
resultCode: `skipped:background_${drop.reason}`,
|
|
156
|
+
scored: drop.scored,
|
|
157
|
+
budget: drop.budget,
|
|
158
|
+
injectedCharCount: 0,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Turn end: claim any ready result, record one honest terminal fact, mark the
|
|
163
|
+
* turn ended (a late selector must discard its decision) and clear the state.
|
|
164
|
+
*
|
|
165
|
+
* Unconditional mark/clear: Stop can land while the selector is still scoring,
|
|
166
|
+
* when neither a job nor a result exists. Returning early there used to skip
|
|
167
|
+
* the marker, so the late result landed in an ended turn with no terminal fact
|
|
168
|
+
* and the console stayed on "waiting for the next request" (P1-2).
|
|
169
|
+
*/
|
|
170
|
+
function finalizeBackgroundTurn(key) {
|
|
171
|
+
const claimed = claimAdaptiveAppendResult({ ...key, now: Date.now() });
|
|
172
|
+
if (claimed.status === 'ready') {
|
|
173
|
+
releaseAdaptiveAppendClaim(claimed.claimPath);
|
|
174
|
+
reportBackgroundDrop(key, { reason: 'turn_ended', scored: true, budget: claimed.result.budgetChars });
|
|
175
|
+
}
|
|
176
|
+
else if (claimed.status === 'expired') {
|
|
177
|
+
reportBackgroundDrop(key, { reason: 'expired', scored: true, budget: 0 });
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
reportBackgroundDrop(key, { reason: 'turn_ended', scored: false, budget: 0 });
|
|
181
|
+
}
|
|
182
|
+
markAdaptiveTurnEnded(key);
|
|
183
|
+
clearAdaptiveAppendTurn(key);
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* "Qualified read-only" is the existing semantic declaration plus the existing
|
|
187
|
+
* shell-risk classifier: a `write` kind, an unresolved kind, or an execute
|
|
188
|
+
* command that cannot be proven `safe` never qualifies.
|
|
189
|
+
*/
|
|
190
|
+
function resolveAppendToolFacts(kind, toolInput) {
|
|
191
|
+
if (kind === 'execute')
|
|
192
|
+
return { readOnly: classifyBashRisk(true, toolInput) === 'safe' };
|
|
193
|
+
return { readOnly: kind === 'read' || kind === 'search' };
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Consume-time proof. The decision may be seconds old, so the target's
|
|
197
|
+
* authorization/body is re-read through the shared revalidator, the installed
|
|
198
|
+
* hook identity must be unchanged, and the directive must still fit the
|
|
199
|
+
* Native budget reported for THIS turn.
|
|
200
|
+
*/
|
|
201
|
+
async function consumeBackgroundAppend(input) {
|
|
202
|
+
const currentIdentity = currentHookIdentity();
|
|
203
|
+
const storedIdentity = input.result.hookIdentity;
|
|
204
|
+
if (!currentIdentity || !storedIdentity)
|
|
205
|
+
return { ok: false, reason: 'version_unverified' };
|
|
206
|
+
if (currentIdentity.entryPath !== storedIdentity.entryPath || currentIdentity.mtimeMs !== storedIdentity.mtimeMs) {
|
|
207
|
+
return { ok: false, reason: 'version_changed' };
|
|
208
|
+
}
|
|
209
|
+
if (input.result.nativeActivationIds.includes(input.result.target.activationId)) {
|
|
210
|
+
return { ok: false, reason: 'already_native' };
|
|
211
|
+
}
|
|
212
|
+
const rendered = await renderAcceptedAdaptiveAppend({
|
|
213
|
+
workspaceDir: input.workspaceDir,
|
|
214
|
+
target: input.result.target,
|
|
215
|
+
signal: AbortSignal.timeout(1500),
|
|
216
|
+
});
|
|
217
|
+
if (!rendered.ok)
|
|
218
|
+
return { ok: false, reason: rendered.reason };
|
|
219
|
+
if (input.result.nativeChars + rendered.directive.length > input.result.budgetChars) {
|
|
220
|
+
return { ok: false, reason: 'budget_exhausted' };
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
ok: true,
|
|
224
|
+
directive: rendered.directive,
|
|
225
|
+
target: {
|
|
226
|
+
principleId: rendered.principle.principleId,
|
|
227
|
+
activationId: rendered.principle.activationId,
|
|
228
|
+
artifactId: rendered.principle.artifactId,
|
|
229
|
+
revisionFingerprint: input.result.target.revisionFingerprint,
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
116
233
|
/**
|
|
117
234
|
* PRI-813: admissible evaluation entry = the CANONICAL core schema guard
|
|
118
235
|
* (rc-1/rc-2, P4: no hand-rolled field copy that could drift from the
|
|
@@ -297,6 +414,11 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
297
414
|
return { stdout: {}, exitCode: 0, stderr: [diagnostic('host.codex_disabled', 'Enable PD in the selected Workspace .pd/config.yaml — in the existing "features:" block set host.codex: {enabled: true} (one flat key, not nested).')] };
|
|
298
415
|
}
|
|
299
416
|
const ingestionEnabled = flags.codex_conversation_ingestion?.enabled === true;
|
|
417
|
+
// PRI-1196: selection timing. Absent = 'sync' — every existing workspace
|
|
418
|
+
// keeps the historical behavior. Background mode never builds the sync
|
|
419
|
+
// provider, so this turn cannot be scored twice.
|
|
420
|
+
const adaptiveTiming = config.effective.config.adaptiveActivation?.timing === 'background' ? 'background' : 'sync';
|
|
421
|
+
const backgroundSelectionEnabled = flags['host.codex.adaptive_activation']?.enabled === true && adaptiveTiming === 'background';
|
|
300
422
|
if (event.kind === 'turn_complete') {
|
|
301
423
|
// Withdraw the live turn context: once the turn completes, the
|
|
302
424
|
// agent-assisted explicit entry must fail closed (turn_context_missing)
|
|
@@ -320,6 +442,19 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
320
442
|
const stderr = ingestionEnabled
|
|
321
443
|
? [...clearDiagnostics, ...await runConversationIngestion({ rawPayload: parsed, kind: event.kind, workspaceDir: resolution.workspaceDir, env: _env })]
|
|
322
444
|
: [...clearDiagnostics, diagnostic('feature_disabled', 'Enable bounded conversation ingestion in the selected Workspace .pd/config.yaml — in the existing "features:" block set codex_conversation_ingestion: {enabled: true} (one flat key, not nested).')];
|
|
445
|
+
// Clean up the background turn whenever THIS turn was tracked, even if the
|
|
446
|
+
// timing was switched back to `sync` mid-turn: the started marker outlives
|
|
447
|
+
// the setting, and leaving it behind would strand a late result (P1-2).
|
|
448
|
+
if (event.context.turnId !== undefined) {
|
|
449
|
+
const backgroundKey = {
|
|
450
|
+
workspaceDir: resolution.workspaceDir,
|
|
451
|
+
stateDir: path.join(resolution.workspaceDir, '.state'),
|
|
452
|
+
sessionId: event.context.sessionId,
|
|
453
|
+
turnId: event.context.turnId,
|
|
454
|
+
};
|
|
455
|
+
if (hasAdaptiveAppendTurn(backgroundKey))
|
|
456
|
+
finalizeBackgroundTurn(backgroundKey);
|
|
457
|
+
}
|
|
323
458
|
return { stdout: {}, exitCode: 0, stderr };
|
|
324
459
|
}
|
|
325
460
|
try {
|
|
@@ -330,6 +465,9 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
330
465
|
const clearDiagnostics = cleared.ok
|
|
331
466
|
? []
|
|
332
467
|
: [diagnostic(`turn_context_${cleared.reason}`, 'The turn context could not be withdrawn; the agent-assisted explicit entry stays fail-closed only via its staleness bound. Inspect the workspace .state directory.')];
|
|
468
|
+
// A SessionStart payload carries no turn_id, so per-turn cleanup is not
|
|
469
|
+
// addressable; sweep only residue above the age bound (P2-3).
|
|
470
|
+
clearStaleAdaptiveAppendState(resolution.workspaceDir, Date.now());
|
|
333
471
|
const health = await createProductionHostRuntime({ hostKind: 'codex' }).health(resolution.workspaceDir);
|
|
334
472
|
if (!health.ok)
|
|
335
473
|
return { stdout: {}, exitCode: 0, stderr: [...clearDiagnostics, diagnostic(health.reason ?? 'runtime_unhealthy', health.nextAction ?? 'Inspect the Workspace runtime.')] };
|
|
@@ -436,7 +574,8 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
436
574
|
// top of the PD hook. `host.codex.enabled` remains the whole-hook gate.
|
|
437
575
|
const adaptiveDiagnostics = [];
|
|
438
576
|
let adaptivePriorityProvider;
|
|
439
|
-
|
|
577
|
+
let adaptiveTurnFact = null;
|
|
578
|
+
if (event.kind === 'before_prompt_build' && flags['host.codex.adaptive_activation']?.enabled === true && adaptiveTiming === 'sync') {
|
|
440
579
|
const adaptive = createAdaptivePriorityProviderForConfig(config.effective.config, resolution.workspaceDir, {
|
|
441
580
|
env: _env,
|
|
442
581
|
...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),
|
|
@@ -444,13 +583,29 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
444
583
|
requestTimeoutMs: deps.requestTimeoutMs ?? CODEX_ADAPTIVE_DECISION_MS,
|
|
445
584
|
...(deps.minExecutableBudgetMs !== undefined ? { minExecutableBudgetMs: deps.minExecutableBudgetMs } : {}),
|
|
446
585
|
outerDeadlineAt: adaptiveDeadlineAt,
|
|
447
|
-
onDiagnostic: (line) => {
|
|
586
|
+
onDiagnostic: (line) => {
|
|
587
|
+
adaptiveDiagnostics.push(adaptiveSelectionDiagnostic(line));
|
|
588
|
+
adaptiveTurnFact = {
|
|
589
|
+
status: line.status,
|
|
590
|
+
reason: line.reason,
|
|
591
|
+
sends: line.sends,
|
|
592
|
+
targetActivationId: line.targetActivationId,
|
|
593
|
+
};
|
|
594
|
+
},
|
|
448
595
|
});
|
|
449
596
|
if (adaptive.ok) {
|
|
450
597
|
adaptivePriorityProvider = adaptive.provider;
|
|
451
598
|
}
|
|
452
599
|
else {
|
|
453
600
|
// rc-9: an enabled-but-unusable switch is observable, never silent.
|
|
601
|
+
// `sends: 0` is a fact, not an assumption: no request can leave when
|
|
602
|
+
// the effective configuration cannot build a model.
|
|
603
|
+
adaptiveTurnFact = {
|
|
604
|
+
status: 'needs_setup',
|
|
605
|
+
reason: adaptive.reason,
|
|
606
|
+
sends: 0,
|
|
607
|
+
targetActivationId: null,
|
|
608
|
+
};
|
|
454
609
|
adaptiveDiagnostics.push(diagnostic(`adaptive_activation_${adaptive.readiness}:${adaptive.reason}`, adaptive.nextAction));
|
|
455
610
|
}
|
|
456
611
|
}
|
|
@@ -471,6 +626,63 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
471
626
|
// defaults) and must be visible on stderr (rc-9).
|
|
472
627
|
? toolSemanticsResolution.warnings.map((warning) => diagnostic(warning, 're-run this host so it refreshes its persisted tool declaration'))
|
|
473
628
|
: [diagnostic(toolSemanticsResolution.reason, toolSemanticsResolution.nextAction)];
|
|
629
|
+
// PRI-1196: the background decision is bound to THIS host turn. The
|
|
630
|
+
// `started` marker (written below) keeps ordering observation alive for the
|
|
631
|
+
// whole turn, including the scoring window in which neither a job nor a
|
|
632
|
+
// result exists (P1-1).
|
|
633
|
+
const backgroundTurnKey = backgroundSelectionEnabled && event.context.turnId !== undefined
|
|
634
|
+
? {
|
|
635
|
+
workspaceDir: resolution.workspaceDir,
|
|
636
|
+
stateDir: path.join(resolution.workspaceDir, '.state'),
|
|
637
|
+
sessionId: event.context.sessionId,
|
|
638
|
+
turnId: event.context.turnId,
|
|
639
|
+
}
|
|
640
|
+
: null;
|
|
641
|
+
// Residue sweep runs on EVERY prompt build, including after the timing was
|
|
642
|
+
// switched back to `sync` or the switch was turned off — the job carries the
|
|
643
|
+
// Owner prompt and must not wait for the feature to be re-enabled (P2-1).
|
|
644
|
+
let turnStartedNow = 'failed';
|
|
645
|
+
if (event.kind === 'before_prompt_build') {
|
|
646
|
+
clearStaleAdaptiveAppendState(resolution.workspaceDir, Date.now());
|
|
647
|
+
if (backgroundTurnKey)
|
|
648
|
+
turnStartedNow = markAdaptiveTurnStarted(backgroundTurnKey);
|
|
649
|
+
}
|
|
650
|
+
const toolKind = toolSemantics.resolve(event.context.toolName ?? '');
|
|
651
|
+
const appendToolFacts = resolveAppendToolFacts(toolKind, event.context.toolInput);
|
|
652
|
+
if (backgroundTurnKey
|
|
653
|
+
&& event.context.toolCallId !== undefined
|
|
654
|
+
&& (event.kind === 'before_tool_call' || event.kind === 'after_tool_call')
|
|
655
|
+
&& hasAdaptiveAppendTurn(backgroundTurnKey)) {
|
|
656
|
+
appendToolObservation({
|
|
657
|
+
...backgroundTurnKey,
|
|
658
|
+
observation: {
|
|
659
|
+
phase: event.kind === 'before_tool_call' ? 'pre' : 'post',
|
|
660
|
+
toolCallId: event.context.toolCallId,
|
|
661
|
+
toolName: event.context.toolName ?? '',
|
|
662
|
+
canonicalKind: toolKind,
|
|
663
|
+
readOnly: appendToolFacts.readOnly,
|
|
664
|
+
at: Date.now(),
|
|
665
|
+
},
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
// Capture the Native assembly facts the background job must match. The
|
|
669
|
+
// emitter receives them from the runtime; no second prompt build is needed.
|
|
670
|
+
const nativeCapture = { value: null };
|
|
671
|
+
const baseEmitter = codexEventEmitter(path.join(resolution.workspaceDir, '.state'), evidenceContext, () => adaptiveTurnFact);
|
|
672
|
+
const events = {
|
|
673
|
+
...baseEmitter,
|
|
674
|
+
recordRuntimeActivationsInjected(data) {
|
|
675
|
+
nativeCapture.value = {
|
|
676
|
+
activationIds: [...data.activationIds],
|
|
677
|
+
injectedCharCount: data.injectedCharCount,
|
|
678
|
+
budget: data.budget,
|
|
679
|
+
capacitySource: data.budgetCapacitySource,
|
|
680
|
+
capacityStatus: data.budgetCapacityStatus,
|
|
681
|
+
contextWindowTokens: data.budgetContextWindowTokens,
|
|
682
|
+
};
|
|
683
|
+
baseEmitter.recordRuntimeActivationsInjected(data);
|
|
684
|
+
},
|
|
685
|
+
};
|
|
474
686
|
const result = await createProductionHostRuntime({
|
|
475
687
|
projectDir: requestedCwd,
|
|
476
688
|
hostKind: 'codex',
|
|
@@ -484,7 +696,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
484
696
|
currentToolUseId: event.context.toolCallId ?? '',
|
|
485
697
|
toolSemantics,
|
|
486
698
|
}),
|
|
487
|
-
events
|
|
699
|
+
events,
|
|
488
700
|
}).dispatch(event);
|
|
489
701
|
// PRI-813: the shared gate's evaluation facts leave through metadata —
|
|
490
702
|
// persist them here (telemetry persistence is host-side business; the
|
|
@@ -496,7 +708,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
496
708
|
// claims only what reached stdout (codex_permission_decision_encoded).
|
|
497
709
|
// V2 rules remain suspended by the shared gate when this provider reports
|
|
498
710
|
// unavailable history; that degraded state is preserved in stderr.
|
|
499
|
-
|
|
711
|
+
let encoded = adapter.encodeOutput(result, event.kind);
|
|
500
712
|
// CR-07 (A16): the explicit-statement receipt rides as additional context
|
|
501
713
|
// so the model can answer truthfully about what happened (received +
|
|
502
714
|
// queued), instead of guessing or claiming it is still waiting for input.
|
|
@@ -508,6 +720,148 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
508
720
|
: explicitReceiptContext;
|
|
509
721
|
}
|
|
510
722
|
}
|
|
723
|
+
const backgroundDiagnostics = [];
|
|
724
|
+
// PRI-1196 — background start. The Native body is ALREADY encoded above;
|
|
725
|
+
// this only writes a single-use job and hands it to a detached process.
|
|
726
|
+
// It never awaits the decision, and the child has no inherited stdio.
|
|
727
|
+
if (backgroundTurnKey && event.kind === 'before_prompt_build') {
|
|
728
|
+
const injection = nativeCapture.value;
|
|
729
|
+
if (injection === null) {
|
|
730
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: 0, injectedCharCount: 0 });
|
|
731
|
+
backgroundDiagnostics.push(diagnostic('adaptive_background_spawn_failed:native_assembly_missing', 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
const output = encoded;
|
|
735
|
+
const nativeText = output.hookSpecificOutput?.additionalContext;
|
|
736
|
+
const nativeChars = typeof nativeText === 'string' ? nativeText.length : injection.injectedCharCount;
|
|
737
|
+
try {
|
|
738
|
+
if (turnStartedNow === 'exists') {
|
|
739
|
+
// A retried/replayed UserPromptSubmit for the same turn must not
|
|
740
|
+
// start a second scoring request (P2-5). The `started` marker is the
|
|
741
|
+
// gate that survives the selector withdrawing its job.
|
|
742
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:already_started', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
743
|
+
}
|
|
744
|
+
else {
|
|
745
|
+
const written = writeAdaptiveAppendJob({
|
|
746
|
+
schemaVersion: ADAPTIVE_APPEND_SCHEMA_VERSION,
|
|
747
|
+
createdAt: Date.now(),
|
|
748
|
+
sessionId: event.context.sessionId,
|
|
749
|
+
turnId: backgroundTurnKey.turnId,
|
|
750
|
+
workspaceDir: resolution.workspaceDir,
|
|
751
|
+
promptContent: event.context.promptContent ?? '',
|
|
752
|
+
nativeActivationIds: injection.activationIds,
|
|
753
|
+
nativeChars,
|
|
754
|
+
budgetChars: injection.budget,
|
|
755
|
+
hookIdentity: currentHookIdentity(),
|
|
756
|
+
});
|
|
757
|
+
if (!written.ok) {
|
|
758
|
+
if (written.reason === 'already_started') {
|
|
759
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:already_started', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
760
|
+
}
|
|
761
|
+
else {
|
|
762
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
763
|
+
backgroundDiagnostics.push(diagnostic('adaptive_background_job_failed', 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
else {
|
|
767
|
+
const spawned = spawnAdaptiveBackgroundSelection(written.jobPath);
|
|
768
|
+
if (!spawned.ok) {
|
|
769
|
+
discardAdaptiveAppendJob(written.jobPath);
|
|
770
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
771
|
+
backgroundDiagnostics.push(diagnostic(`adaptive_background_spawn_failed:${spawned.reason}`, 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
|
|
772
|
+
}
|
|
773
|
+
else {
|
|
774
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawned', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
catch (error) {
|
|
780
|
+
emitBackgroundFact(backgroundTurnKey, { resultCode: 'background:spawn_failed', scored: false, budget: injection.budget, injectedCharCount: 0 });
|
|
781
|
+
backgroundDiagnostics.push(diagnostic(`adaptive_background_job_failed:${errorMessage(error)}`, 'The Native body was still encoded and sent; the background decision was skipped for this turn.'));
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
// PRI-1196 — consume at a qualified read-only tool boundary of the SAME
|
|
786
|
+
// turn. The claim rename makes replay/concurrency emit at most once.
|
|
787
|
+
if (backgroundTurnKey && event.kind === 'after_tool_call' && event.context.toolCallId !== undefined) {
|
|
788
|
+
const claimed = claimAdaptiveAppendResult({ ...backgroundTurnKey, now: Date.now() });
|
|
789
|
+
if (claimed.status === 'invalid') {
|
|
790
|
+
// The claim already withdrew the unreadable result; without a fact the
|
|
791
|
+
// console would keep showing "waiting for the next request" (rc-9, P2-2).
|
|
792
|
+
reportBackgroundDrop(backgroundTurnKey, { reason: claimed.reason ?? 'result_invalid', scored: true, budget: 0 });
|
|
793
|
+
}
|
|
794
|
+
else if (!appendToolFacts.readOnly) {
|
|
795
|
+
if (claimed.status === 'ready') {
|
|
796
|
+
releaseAdaptiveAppendClaim(claimed.claimPath);
|
|
797
|
+
reportBackgroundDrop(backgroundTurnKey, {
|
|
798
|
+
reason: toolKind === 'write' ? 'mutating_tool' : 'unknown_tool',
|
|
799
|
+
scored: true,
|
|
800
|
+
budget: claimed.result.budgetChars,
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
else {
|
|
805
|
+
const ordering = evaluateAppendOrdering(readToolObservations(backgroundTurnKey), event.context.toolCallId);
|
|
806
|
+
if (!ordering.ok) {
|
|
807
|
+
if (claimed.status === 'ready') {
|
|
808
|
+
releaseAdaptiveAppendClaim(claimed.claimPath);
|
|
809
|
+
reportBackgroundDrop(backgroundTurnKey, { reason: ordering.reason, scored: true, budget: claimed.result.budgetChars });
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
else if (claimed.status === 'expired') {
|
|
813
|
+
reportBackgroundDrop(backgroundTurnKey, { reason: 'expired', scored: true, budget: 0 });
|
|
814
|
+
}
|
|
815
|
+
else if (claimed.status === 'ready') {
|
|
816
|
+
const consumed = await consumeBackgroundAppend({
|
|
817
|
+
workspaceDir: resolution.workspaceDir,
|
|
818
|
+
result: claimed.result,
|
|
819
|
+
});
|
|
820
|
+
if (consumed.ok) {
|
|
821
|
+
// The appended directive is additional context for the NEXT model
|
|
822
|
+
// request; Native items and their order are untouched.
|
|
823
|
+
//
|
|
824
|
+
// This calls the Codex encoder DIRECTLY instead of routing the
|
|
825
|
+
// result through the shared dispatch: `hasValidResultSemantics`
|
|
826
|
+
// (host-runtime) deliberately forbids `after_tool_call` results
|
|
827
|
+
// carrying `additionalContext`, while the Codex host contract
|
|
828
|
+
// accepts exactly that shape (codex-adapter spec §5.3.2). The
|
|
829
|
+
// shared rule encodes the host-neutral default; the Codex adapter
|
|
830
|
+
// is the host authority for its own output shape. If upstream later
|
|
831
|
+
// generalises that rule, this direct call stays correct only as
|
|
832
|
+
// long as `encodeOutput` remains the Codex output authority.
|
|
833
|
+
encoded = adapter.encodeOutput({ decision: 'observe', source: event.source, additionalContext: consumed.directive }, 'after_tool_call');
|
|
834
|
+
emitBackgroundFact(backgroundTurnKey, {
|
|
835
|
+
resultCode: 'selected:background_appended',
|
|
836
|
+
scored: true,
|
|
837
|
+
budget: claimed.result.budgetChars,
|
|
838
|
+
injectedCharCount: consumed.directive.length,
|
|
839
|
+
appended: consumed.target,
|
|
840
|
+
});
|
|
841
|
+
// Terminal fact for this turn: a later Stop must not overwrite it
|
|
842
|
+
// with "turn ended" in "上一次结果".
|
|
843
|
+
claimAdaptiveReportMarker({ ...backgroundTurnKey, reason: 'appended' });
|
|
844
|
+
try {
|
|
845
|
+
recordCodexPromptDeliveryEvidence({
|
|
846
|
+
workspaceDir: resolution.workspaceDir,
|
|
847
|
+
sessionId: event.context.sessionId,
|
|
848
|
+
turnId: backgroundTurnKey.turnId,
|
|
849
|
+
injected: [consumed.target],
|
|
850
|
+
evidenceEnabled: evidenceContext.evidenceEnabled,
|
|
851
|
+
warn: evidenceContext.warn,
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
catch (error) {
|
|
855
|
+
evidenceDiagnostics.push(diagnostic(`codex_evidence_append_failed:${errorMessage(error)}`, 'The append was already encoded; evidence replay from the durable source is safe.'));
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
else {
|
|
859
|
+
reportBackgroundDrop(backgroundTurnKey, { reason: consumed.reason, scored: true, budget: claimed.result.budgetChars });
|
|
860
|
+
}
|
|
861
|
+
releaseAdaptiveAppendClaim(claimed.claimPath);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
511
865
|
if (result.decision === 'deny') {
|
|
512
866
|
try {
|
|
513
867
|
let liveActivationId;
|
|
@@ -550,7 +904,7 @@ export async function processHookInvocation(rawStdin, _env = process.env, cwd =
|
|
|
550
904
|
evidenceDiagnostics.push(diagnostic(`codex_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
|
|
551
905
|
}
|
|
552
906
|
}
|
|
553
|
-
const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics, ...adaptiveDiagnostics, ...toolSemanticsDiagnostics];
|
|
907
|
+
const stderr = [...(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic(warning, 'Inspect PD Workspace state and retry; the hook failed open.')), ...evaluationDiagnostics, ...evidenceDiagnostics, ...ingestionDiagnostics, ...explicitDiagnostics, ...adaptiveDiagnostics, ...toolSemanticsDiagnostics, ...backgroundDiagnostics];
|
|
554
908
|
return { stdout: encoded, exitCode: 0, stderr };
|
|
555
909
|
}
|
|
556
910
|
catch (error) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/codex-adapter",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Codex CLI host adapter for Principles Disciple — implements HostAdapter interface for OpenAI Codex CLI's stdin/stdout JSON hook model (ADR-0020).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -33,8 +33,8 @@
|
|
|
33
33
|
"lint": "eslint \"src/**/*.ts\""
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@principles/core": "^7.
|
|
37
|
-
"@principles/host-runtime": "^4.
|
|
36
|
+
"@principles/core": "^7.9.0",
|
|
37
|
+
"@principles/host-runtime": "^4.3.0",
|
|
38
38
|
"@principles/install-layout": "^0.8.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
@@ -52,5 +52,5 @@
|
|
|
52
52
|
"publishConfig": {
|
|
53
53
|
"access": "public"
|
|
54
54
|
},
|
|
55
|
-
"gitHead": "
|
|
55
|
+
"gitHead": "97cac4b30eb64ad4b369d2f86f5c57a8053897eb"
|
|
56
56
|
}
|