@principles/host-runtime 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,70 @@
1
+ import { type ActivatedPrinciple } from '@principles/core/runtime';
2
+ export interface AdaptiveAppendTargetRef {
3
+ readonly principleId: string;
4
+ readonly activationId: string;
5
+ readonly artifactId: string;
6
+ readonly revisionFingerprint: string;
7
+ }
8
+ export declare function fingerprintAdaptiveAppendRevision(principle: ActivatedPrinciple): string | null;
9
+ export interface AdaptiveBackgroundSelectionInput {
10
+ readonly workspaceDir: string;
11
+ readonly sessionId: string;
12
+ readonly turnId: string;
13
+ /** Current Owner prompt. Used ONLY for the decision request; never persisted. */
14
+ readonly promptContent: string;
15
+ /** Activation ids that the already-sent Native request contained. */
16
+ readonly nativeActivationIds: readonly string[];
17
+ /** Characters of the Native additionalContext actually encoded for this turn. */
18
+ readonly nativeChars: number;
19
+ /** The budget that Native ran under. */
20
+ readonly budgetChars: number;
21
+ /** Absolute end of the background window (turn start + TTL). */
22
+ readonly deadlineAt: number;
23
+ readonly env?: Record<string, string | undefined>;
24
+ readonly fetchImpl?: typeof fetch;
25
+ readonly now?: () => number;
26
+ }
27
+ export interface AdaptiveBackgroundDiagnostic {
28
+ readonly status: string;
29
+ readonly reason: string;
30
+ readonly sends: number;
31
+ }
32
+ export type AdaptiveBackgroundSelectionOutcome = {
33
+ readonly status: 'selected';
34
+ readonly target: AdaptiveAppendTargetRef;
35
+ /** The exact directive slice a later request may append. */
36
+ readonly directive: string;
37
+ readonly diagnostic: AdaptiveBackgroundDiagnostic;
38
+ } | {
39
+ readonly status: 'skipped' | 'unavailable';
40
+ readonly reason: string;
41
+ readonly diagnostic: AdaptiveBackgroundDiagnostic;
42
+ };
43
+ /** The one directive body, identical to what the shared packer would render. */
44
+ export declare function renderAppendDirective(principle: ActivatedPrinciple): string | null;
45
+ /**
46
+ * Runs ONE background selection for a turn whose Native request already left.
47
+ *
48
+ * Returns `selected` only when the shared measurement proves the target fits
49
+ * the budget Native did not use, and the shared revalidator proves the exact
50
+ * authorized revision still holds at decision time.
51
+ */
52
+ export declare function runAdaptiveBackgroundSelection(input: AdaptiveBackgroundSelectionInput): Promise<AdaptiveBackgroundSelectionOutcome>;
53
+ export type AdaptiveAppendRenderResult = {
54
+ readonly ok: true;
55
+ readonly directive: string;
56
+ readonly principle: ActivatedPrinciple;
57
+ } | {
58
+ readonly ok: false;
59
+ readonly reason: string;
60
+ };
61
+ /**
62
+ * Consume-time revalidation. Runs in the LATER hook process and therefore
63
+ * proves the authorization/body facts again — a background decision is not a
64
+ * license to append a revision that changed while the turn was running.
65
+ */
66
+ export declare function renderAcceptedAdaptiveAppend(input: {
67
+ readonly workspaceDir: string;
68
+ readonly target: AdaptiveAppendTargetRef;
69
+ readonly signal: AbortSignal;
70
+ }): Promise<AdaptiveAppendRenderResult>;
@@ -0,0 +1,165 @@
1
+ /**
2
+ * PRI-1196 — Adaptive Activation, background selection (Codex desktop).
3
+ *
4
+ * The synchronous path decides BEFORE the first model request. This module is
5
+ * the asynchronous counterpart: the first request already left as Native, and
6
+ * the decision runs in a detached process. It reuses the SAME candidate read,
7
+ * skip gate, decision protocol, authorization revalidation and capacity
8
+ * measurement as the synchronous path; only the orchestration differs.
9
+ *
10
+ * Append-only by construction: the feasible gap is the budget the sent Native
11
+ * did NOT use, and the target is never offered a replacement slot. The chosen
12
+ * directive is rendered for a LATER request of the same turn.
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+ import { escapeXml } from '@principles/core/prompt-builder';
16
+ import { measureSharedDirectiveBlockChars, renderPrinciplesToDirectives, } from '@principles/core/runtime';
17
+ import { readPromptActivationCandidates } from './active-principle-prompt.js';
18
+ import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
19
+ import { createAdaptivePriorityProviderForConfig, } from './adaptive-priority-provider.js';
20
+ import { loadPdConfigForPlugin } from './pd-config.js';
21
+ export function fingerprintAdaptiveAppendRevision(principle) {
22
+ if (!principle.artifactContentSha256)
23
+ return null;
24
+ return createHash('sha256').update(JSON.stringify([
25
+ principle.artifactContentSha256, principle.text, principle.authority, principle.approvedBy,
26
+ ])).digest('hex');
27
+ }
28
+ /** The one directive body, identical to what the shared packer would render. */
29
+ export function renderAppendDirective(principle) {
30
+ const rendered = renderPrinciplesToDirectives([principle], new Set([principle.principleId]), { escapeFn: escapeXml });
31
+ const start = rendered.indexOf('<directive ');
32
+ const end = rendered.indexOf('</directive>');
33
+ if (start < 0 || end < 0)
34
+ return null;
35
+ return rendered.slice(start, end + '</directive>'.length);
36
+ }
37
+ /**
38
+ * Runs ONE background selection for a turn whose Native request already left.
39
+ *
40
+ * Returns `selected` only when the shared measurement proves the target fits
41
+ * the budget Native did not use, and the shared revalidator proves the exact
42
+ * authorized revision still holds at decision time.
43
+ */
44
+ export async function runAdaptiveBackgroundSelection(input) {
45
+ let diagnostic = { status: 'skipped', reason: 'no_appendable_gap', sends: 0 };
46
+ const config = loadPdConfigForPlugin(input.workspaceDir);
47
+ if (!config.ok) {
48
+ return { status: 'unavailable', reason: 'config_invalid', diagnostic: { status: 'unavailable', reason: 'config_invalid', sends: 0 } };
49
+ }
50
+ const candidates = await readPromptActivationCandidates({ workspaceDir: input.workspaceDir, includeAuthority: true });
51
+ if (candidates.aborted || candidates.warnings.length > 0) {
52
+ const reason = candidates.aborted ? 'reader_aborted' : 'reader_warnings';
53
+ return { status: 'unavailable', reason, diagnostic: { status: 'unavailable', reason, sends: 0 } };
54
+ }
55
+ const nativeIds = new Set(input.nativeActivationIds);
56
+ const omitted = candidates.principles.filter((principle) => !nativeIds.has(principle.activationId));
57
+ const renderOptions = { escapeFn: escapeXml, selfReportInstruction: candidates.selfReportEnabled };
58
+ const remaining = input.budgetChars - input.nativeChars;
59
+ const feasible = remaining > 0
60
+ ? omitted.filter((principle) => measureSharedDirectiveBlockChars(principle, renderOptions) <= remaining)
61
+ : [];
62
+ if (feasible.length === 0) {
63
+ return { status: 'skipped', reason: 'no_appendable_gap', diagnostic };
64
+ }
65
+ const resolution = createAdaptivePriorityProviderForConfig(config.effective.config, input.workspaceDir, {
66
+ ...(input.env ? { env: input.env } : {}),
67
+ ...(input.fetchImpl ? { fetchImpl: input.fetchImpl } : {}),
68
+ ...(input.now ? { now: input.now } : {}),
69
+ outerDeadlineAt: input.deadlineAt,
70
+ // Nothing needs to be reserved for a second assembly: the directive is
71
+ // already rendered by the time the process exits.
72
+ outputReserveMs: 0,
73
+ onDiagnostic: (line) => {
74
+ diagnostic = { status: line.status, reason: line.reason, sends: line.sends };
75
+ },
76
+ });
77
+ if (!resolution.ok) {
78
+ return {
79
+ status: 'skipped',
80
+ reason: `needs_setup:${resolution.reason}`,
81
+ diagnostic: { status: 'needs_setup', reason: resolution.reason, sends: 0 },
82
+ };
83
+ }
84
+ // The provider only needs the host-supplied turn identity and prompt body.
85
+ const event = {
86
+ kind: 'before_prompt_build',
87
+ source: 'codex:adaptive_background_selection',
88
+ rawPayload: null,
89
+ context: {
90
+ workspaceDir: input.workspaceDir,
91
+ sessionId: input.sessionId,
92
+ turnId: input.turnId,
93
+ promptContent: input.promptContent,
94
+ },
95
+ };
96
+ const selection = await resolution.provider(event, feasible, {
97
+ excludedByBudget: feasible.length < omitted.length,
98
+ // Background mode is append-only: never offer a replacement slot.
99
+ replacementByActivationId: new Map(),
100
+ });
101
+ if (!selection) {
102
+ return { status: 'skipped', reason: diagnostic.reason, diagnostic };
103
+ }
104
+ const selected = feasible.find((principle) => principle.activationId === selection.activationId
105
+ && principle.artifactId === selection.artifactId);
106
+ if (!selected) {
107
+ return { status: 'unavailable', reason: 'selection_target_missing', diagnostic };
108
+ }
109
+ const revalidationBudgetMs = Math.max(1, Math.min(1500, input.deadlineAt - (input.now?.() ?? Date.now())));
110
+ if (!await revalidateAdaptivePrinciple(input.workspaceDir, selected, AbortSignal.timeout(revalidationBudgetMs))) {
111
+ return { status: 'unavailable', reason: 'target_changed', diagnostic };
112
+ }
113
+ const revisionFingerprint = fingerprintAdaptiveAppendRevision(selected);
114
+ if (!revisionFingerprint)
115
+ return { status: 'unavailable', reason: 'target_changed', diagnostic };
116
+ const directive = renderAppendDirective(selected);
117
+ if (directive === null) {
118
+ return { status: 'unavailable', reason: 'target_render_failed', diagnostic };
119
+ }
120
+ if (input.nativeChars + directive.length > input.budgetChars) {
121
+ return { status: 'unavailable', reason: 'budget_exhausted', diagnostic };
122
+ }
123
+ return {
124
+ status: 'selected',
125
+ target: {
126
+ principleId: selected.principleId,
127
+ activationId: selected.activationId,
128
+ artifactId: selected.artifactId,
129
+ revisionFingerprint,
130
+ },
131
+ directive,
132
+ diagnostic,
133
+ };
134
+ }
135
+ /**
136
+ * Consume-time revalidation. Runs in the LATER hook process and therefore
137
+ * proves the authorization/body facts again — a background decision is not a
138
+ * license to append a revision that changed while the turn was running.
139
+ */
140
+ export async function renderAcceptedAdaptiveAppend(input) {
141
+ const read = await readPromptActivationCandidates({
142
+ workspaceDir: input.workspaceDir,
143
+ includeAuthority: true,
144
+ noBusyWait: true,
145
+ });
146
+ if (read.aborted || read.warnings.length > 0)
147
+ return { ok: false, reason: 'authority_unavailable' };
148
+ const matches = read.principles.filter((principle) => principle.activationId === input.target.activationId && principle.artifactId === input.target.artifactId);
149
+ if (matches.length !== 1)
150
+ return { ok: false, reason: 'target_unavailable' };
151
+ const [principle] = matches;
152
+ if (!principle
153
+ || principle.principleId !== input.target.principleId
154
+ || fingerprintAdaptiveAppendRevision(principle) !== input.target.revisionFingerprint
155
+ || read.principles.filter((candidate) => candidate.principleId === principle.principleId).length !== 1) {
156
+ return { ok: false, reason: 'target_changed' };
157
+ }
158
+ if (!await revalidateAdaptivePrinciple(input.workspaceDir, principle, input.signal)) {
159
+ return { ok: false, reason: 'target_changed' };
160
+ }
161
+ const directive = renderAppendDirective(principle);
162
+ if (directive === null)
163
+ return { ok: false, reason: 'target_render_failed' };
164
+ return { ok: true, directive, principle };
165
+ }
@@ -9,7 +9,7 @@
9
9
  * mapping. Any missing identity/config/model keeps the Native path unchanged.
10
10
  */
11
11
  import type { HostEvent } from '@principles/core/host';
12
- import type { ActivatedPrinciple, PdConfig } from '@principles/core/runtime';
12
+ import { type ActivatedPrinciple, type PdConfig } from '@principles/core/runtime';
13
13
  import type { AdaptiveGapOptions } from './active-principle-prompt.js';
14
14
  import { type AdaptiveSelectionModel } from './adaptive-selection.js';
15
15
  /** Independent switch. `features.host.codex.enabled` remains the whole-hook gate. */
@@ -1,3 +1,4 @@
1
+ import { pdProviderCredentials } from '@principles/core/runtime';
1
2
  import { loadPdConfigForPlugin } from './pd-config.js';
2
3
  import { ADAPTIVE_SELECTION_LIMITS, runAdaptiveSelection, } from './adaptive-selection.js';
3
4
  import { decideAdaptiveSkip } from './adaptive-skip-decision.js';
@@ -38,12 +39,12 @@ export function resolveAdaptiveSelectionModel(config, env, flag = ADAPTIVE_ACTIV
38
39
  nextAction: 'Set endpoint (https URL), model and apiKeyEnv on adaptiveActivation',
39
40
  };
40
41
  }
41
- if (!Object.hasOwn(env, section.apiKeyEnv) || !env[section.apiKeyEnv]) {
42
+ if (pdProviderCredentials.resolve(section.apiKeyEnv, { env }).value === null) {
42
43
  return {
43
44
  ok: false,
44
45
  readiness: 'needs_setup',
45
- reason: `Environment variable '${section.apiKeyEnv}' is not set or empty`,
46
- nextAction: `Set the environment variable '${section.apiKeyEnv}' with a valid API key`,
46
+ reason: `No API key for '${section.apiKeyEnv}' in env or ~/.pd/credentials.yaml`,
47
+ nextAction: `Save an API key for '${section.apiKeyEnv}' in the console, or set the environment variable`,
47
48
  };
48
49
  }
49
50
  return {
@@ -1,4 +1,4 @@
1
- import type { ActivatedPrinciple } from '@principles/core/runtime';
1
+ import { type ActivatedPrinciple } from '@principles/core/runtime';
2
2
  import { type DecisionOutcome, type DecisionProtocolError, type DecisionRequestEnvelope } from './adaptive-decision-protocol.js';
3
3
  export declare const ADAPTIVE_SELECTION_LIMITS: {
4
4
  readonly maxCandidates: 12;
@@ -21,6 +21,7 @@
21
21
  * - Diagnostics never carry the raw prompt, the raw response, or credentials.
22
22
  */
23
23
  import crypto from 'node:crypto';
24
+ import { pdProviderCredentials } from '@principles/core/runtime';
24
25
  import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
25
26
  import { ADAPTIVE_DECISION_MAX_CANDIDATE_CHARS, adjudicateDecision, buildDecisionRequest, validateDecisionResponse, } from './adaptive-decision-protocol.js';
26
27
  export const ADAPTIVE_SELECTION_LIMITS = {
@@ -199,7 +200,7 @@ export function createDecisionSelector(options) {
199
200
  diagnostics.cancelledAt = now();
200
201
  fail('TURN_DEADLINE_EXCEEDED');
201
202
  }
202
- const apiKey = process.env[options.model.apiKeyEnv];
203
+ const apiKey = pdProviderCredentials.resolve(options.model.apiKeyEnv).value;
203
204
  if (!apiKey)
204
205
  fail('DECISION_CREDENTIAL_MISSING');
205
206
  const body = JSON.stringify(input.body);
package/dist/index.d.ts CHANGED
@@ -24,6 +24,7 @@ export * from './governance-signal-admission.js';
24
24
  export * from './signal-classifier.js';
25
25
  export * from './adaptive-selection.js';
26
26
  export * from './adaptive-priority-provider.js';
27
+ export * from './adaptive-background-append.js';
27
28
  export * from './signal-stage2-cycle.js';
28
29
  export * from './host-liveness-contract.js';
29
30
  export * from './internalization-consumer-governance.js';
package/dist/index.js CHANGED
@@ -43,6 +43,11 @@ export * from './governance-signal-admission.js';
43
43
  export * from './signal-classifier.js';
44
44
  export * from './adaptive-selection.js';
45
45
  export * from './adaptive-priority-provider.js';
46
+ // PRI-1196: background (async) Adaptive selection for the Codex host. Reuses
47
+ // the same candidates/gate/protocol/revalidation/capacity primitives; the
48
+ // first request goes out as Native and one directive may be appended later in
49
+ // the same turn.
50
+ export * from './adaptive-background-append.js';
46
51
  export * from './signal-stage2-cycle.js';
47
52
  export * from './host-liveness-contract.js';
48
53
  // PRI-624 Slice C: shared internalization consumer execution (OpenClaw
@@ -13,7 +13,7 @@
13
13
  * No second model runtime is introduced (ADR-0029: pi-ai is the only backend).
14
14
  */
15
15
  import path from 'node:path';
16
- import { PiAiRuntimeAdapter, RUNTIME_CONTRACT_SCHEMA_VERSION, SIGNAL_CLASSIFIER_SYSTEM_PROMPT, buildLlmPrompt, resolveLlmClassificationPayload, safeStringifyPreview, } from '@principles/core/runtime';
16
+ import { PiAiRuntimeAdapter, RUNTIME_CONTRACT_SCHEMA_VERSION, SIGNAL_CLASSIFIER_SYSTEM_PROMPT, buildLlmPrompt, resolveLlmClassificationPayload, pdProviderCredentials, safeStringifyPreview, } from '@principles/core/runtime';
17
17
  import { loadPdConfigForPlugin } from './pd-config.js';
18
18
  /**
19
19
  * The Stage-2 structured-output contract this classifier requests. It MUST stay
@@ -153,12 +153,12 @@ export function createSignalClassifierForWorkspace(workspaceDir, options = {}) {
153
153
  nextAction: `Set provider and model on runtime profile '${runtimeProfileId}'`,
154
154
  };
155
155
  }
156
- if (!Object.hasOwn(process.env, profile.apiKeyEnv) || !process.env[profile.apiKeyEnv]) {
156
+ if (pdProviderCredentials.resolve(profile.apiKeyEnv).value === null) {
157
157
  return {
158
158
  ok: false,
159
159
  readiness: 'needs_setup',
160
- reason: `Environment variable '${profile.apiKeyEnv}' is not set or empty`,
161
- nextAction: `Set the environment variable '${profile.apiKeyEnv}' with a valid API key`,
160
+ reason: `No API key for '${profile.apiKeyEnv}' in env or ~/.pd/credentials.yaml`,
161
+ nextAction: `Save an API key for '${profile.apiKeyEnv}' in the console, or set the environment variable`,
162
162
  };
163
163
  }
164
164
  const resolved = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.2.0",
3
+ "version": "4.3.0",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -35,8 +35,8 @@
35
35
  "lint": "eslint \"src/**/*.ts\""
36
36
  },
37
37
  "dependencies": {
38
- "@principles/core": "^7.7.0",
39
- "@principles/install-layout": "^0.8.1",
38
+ "@principles/core": "^7.9.0",
39
+ "@principles/install-layout": "^0.8.2",
40
40
  "better-sqlite3": "^13.0.3",
41
41
  "js-yaml": "^5.4.3"
42
42
  },
@@ -53,5 +53,5 @@
53
53
  "url": "git+https://github.com/csuzngjh/principles.git"
54
54
  },
55
55
  "license": "Apache-2.0",
56
- "gitHead": "7feb0044cae3768b8bf278dad1cb58e77410b6f9"
56
+ "gitHead": "97cac4b30eb64ad4b369d2f86f5c57a8053897eb"
57
57
  }