@cortex-agent/server 2026.8.3 → 2026.8.6
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/defaults/config/thread-templates/agents/benchmark-coder.json +2 -2
- package/defaults/config/thread-templates/agents/benchmark-fixer.json +17 -0
- package/defaults/config/thread-templates/agents/benchmark-reviewer.json +5 -5
- package/defaults/config/thread-templates/templates/benchmark-coder-review-fix.json +21 -0
- package/defaults/plugins/cortex-system/skills/thread/SKILL.md +1 -0
- package/defaults/prompts/directives/benchmark-coder.md +1 -0
- package/defaults/prompts/directives/benchmark-fixer.md +1 -0
- package/defaults/prompts/directives/benchmark-reviewer.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-coder.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-fixer.md +1 -0
- package/defaults/prompts/systemPrompts/benchmark-reviewer.md +1 -0
- package/dist/agent-adapter/capabilities.d.ts +32 -1
- package/dist/agent-adapter/capabilities.js +39 -1
- package/dist/agent-adapter/claude/adapter.d.ts +15 -0
- package/dist/agent-adapter/claude/adapter.js +29 -7
- package/dist/agent-adapter/claude/spawn-args.d.ts +5 -2
- package/dist/agent-adapter/claude/spawn-args.js +29 -6
- package/dist/agent-adapter/index.js +11 -1
- package/dist/agent-adapter/normalize/tool-names.d.ts +4 -0
- package/dist/agent-adapter/normalize/tool-names.js +10 -0
- package/dist/agent-adapter/pi/adapter.d.ts +20 -8
- package/dist/agent-adapter/pi/adapter.js +130 -35
- package/dist/agent-adapter/pi/agent-dir.d.ts +20 -53
- package/dist/agent-adapter/pi/agent-dir.js +48 -89
- package/dist/agent-adapter/pi/custom-catalog.d.ts +10 -0
- package/dist/agent-adapter/pi/custom-catalog.js +42 -0
- package/dist/agent-adapter/pi/defaults.d.ts +9 -0
- package/dist/agent-adapter/pi/defaults.js +14 -4
- package/dist/agent-adapter/pi/discovery.d.ts +1 -3
- package/dist/agent-adapter/pi/discovery.js +3 -15
- package/dist/agent-adapter/pi/event-parser.js +8 -0
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -0
- package/dist/agent-adapter/pi/mcp-bridge.js +31 -6
- package/dist/agent-adapter/pi/mcp-duration.d.ts +28 -0
- package/dist/agent-adapter/pi/mcp-duration.js +48 -0
- package/dist/agent-adapter/pi/policy-guard.d.ts +40 -0
- package/dist/agent-adapter/pi/policy-guard.js +111 -0
- package/dist/agent-adapter/pi/providers-config.d.ts +62 -0
- package/dist/agent-adapter/pi/providers-config.js +101 -0
- package/dist/agent-adapter/pi/quota-probe.d.ts +11 -0
- package/dist/agent-adapter/pi/quota-probe.js +36 -0
- package/dist/agent-adapter/pi/quota-sink.d.ts +25 -0
- package/dist/agent-adapter/pi/quota-sink.js +31 -0
- package/dist/agent-adapter/pi/session-files.d.ts +2 -0
- package/dist/agent-adapter/pi/session-files.js +19 -0
- package/dist/agent-adapter/pi/session-support.d.ts +14 -3
- package/dist/agent-adapter/pi/session-support.js +8 -0
- package/dist/agent-adapter/pi/spawn-args.d.ts +11 -1
- package/dist/agent-adapter/pi/spawn-args.js +13 -0
- package/dist/agent-adapter/pi/tool-shims.d.ts +2 -2
- package/dist/agent-adapter/pi/tool-shims.js +32 -21
- package/dist/agent-adapter/pi/web-search.js +36 -8
- package/dist/agent-adapter/types.d.ts +14 -0
- package/dist/core/locales/en.d.ts +54 -1
- package/dist/core/locales/en.js +2 -0
- package/dist/core/locales/slices/commands.d.ts +12 -1
- package/dist/core/locales/slices/commands.js +24 -2
- package/dist/core/locales/slices/providers.d.ts +45 -0
- package/dist/core/locales/slices/providers.js +95 -0
- package/dist/core/locales/zh.js +2 -0
- package/dist/core/resilient-watch.d.ts +28 -0
- package/dist/core/resilient-watch.js +110 -0
- package/dist/core/settings.js +15 -20
- package/dist/core/types/agent-types.d.ts +6 -0
- package/dist/core/types/thread-types.d.ts +21 -3
- package/dist/core/utils.d.ts +21 -1
- package/dist/core/utils.js +37 -1
- package/dist/domain/agent-run/agent-run-cli.js +3 -1
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
- package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
- package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
- package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
- package/dist/domain/agent-run/identity.d.ts +5 -0
- package/dist/domain/agent-run/identity.js +4 -1
- package/dist/domain/agent-run/journal.d.ts +3 -2
- package/dist/domain/agent-run/manifest.js +11 -4
- package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
- package/dist/domain/agent-run/pinned-node-process.js +9 -0
- package/dist/domain/agent-run/role-surface.d.ts +2 -2
- package/dist/domain/agent-run/role-surface.js +7 -3
- package/dist/domain/agent-run/run-config.d.ts +10 -1
- package/dist/domain/agent-run/run-config.js +57 -6
- package/dist/domain/agent-run/runner.js +149 -31
- package/dist/domain/agents/facade.d.ts +37 -122
- package/dist/domain/agents/facade.js +47 -115
- package/dist/domain/agents/spawn-config.d.ts +135 -0
- package/dist/domain/agents/spawn-config.js +121 -0
- package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
- package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
- package/dist/domain/benchmark/arm-schema.d.ts +43 -0
- package/dist/domain/benchmark/arm-schema.js +243 -0
- package/dist/domain/benchmark/capabilities.d.ts +4 -0
- package/dist/domain/benchmark/capabilities.js +54 -0
- package/dist/domain/benchmark/decimal-text.d.ts +27 -0
- package/dist/domain/benchmark/decimal-text.js +67 -0
- package/dist/domain/benchmark/lease-echo.d.ts +43 -0
- package/dist/domain/benchmark/lease-echo.js +56 -0
- package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
- package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
- package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
- package/dist/domain/benchmark/policy-compiler.js +680 -0
- package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
- package/dist/domain/benchmark/resolved-policy.js +195 -0
- package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
- package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
- package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
- package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
- package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
- package/dist/domain/benchmark/variant-proposal.js +42 -0
- package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
- package/dist/domain/benchmark/workspace-lease.js +272 -0
- package/dist/domain/costs/codex-quota.d.ts +29 -0
- package/dist/domain/costs/codex-quota.js +102 -0
- package/dist/domain/costs/cost-tracker.d.ts +48 -9
- package/dist/domain/costs/cost-tracker.js +74 -18
- package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
- package/dist/domain/costs/rate-limit-throttle.js +61 -6
- package/dist/domain/costs/resume-registry.d.ts +3 -1
- package/dist/domain/costs/resume-registry.js +10 -1
- package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
- package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
- package/dist/domain/mcp/tools/cost.js +15 -6
- package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
- package/dist/domain/pi-providers/custom-provider-model.js +122 -0
- package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
- package/dist/domain/pi-providers/custom-provider-service.js +143 -0
- package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
- package/dist/domain/pi-providers/gateway-route-store.js +78 -0
- package/dist/domain/pi-providers/index.d.ts +4 -0
- package/dist/domain/pi-providers/index.js +8 -0
- package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
- package/dist/domain/pi-providers/models-json-store.js +77 -0
- package/dist/domain/remote/client-hot-reload.d.ts +9 -1
- package/dist/domain/remote/client-hot-reload.js +60 -12
- package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
- package/dist/domain/scheduling/jobs/_shared.js +11 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
- package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
- package/dist/domain/sessions/session-lifecycle.js +20 -1
- package/dist/domain/system/install-cli.js +8 -3
- package/dist/domain/system/system-notice.d.ts +4 -1
- package/dist/domain/system/system-notice.js +6 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
- package/dist/domain/tasks/dispatch-utils.js +24 -37
- package/dist/domain/threads/runner.d.ts +16 -1
- package/dist/domain/threads/runner.js +62 -8
- package/dist/domain/threads/template-loader.d.ts +5 -0
- package/dist/domain/threads/template-loader.js +120 -36
- package/dist/domain/threads/template-validate.d.ts +244 -0
- package/dist/domain/threads/template-validate.js +574 -0
- package/dist/domain/threads/template-validate.parity.d.ts +1 -0
- package/dist/domain/threads/template-validate.parity.js +47 -0
- package/dist/domain/threads/template-writer.d.ts +55 -0
- package/dist/domain/threads/template-writer.js +131 -0
- package/dist/domain/ui-service/app-router.d.ts +143 -1
- package/dist/domain/ui-service/app-router.js +29 -3
- package/dist/domain/ui-service/input-schemas.d.ts +228 -4
- package/dist/domain/ui-service/input-schemas.js +132 -1
- package/dist/domain/ui-service/mutate/config.d.ts +10 -1
- package/dist/domain/ui-service/mutate/config.js +45 -5
- package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
- package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
- package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
- package/dist/domain/ui-service/mutate/profiles.js +156 -0
- package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
- package/dist/domain/ui-service/mutate/schedules.js +53 -3
- package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
- package/dist/domain/ui-service/mutate/sessions.js +25 -1
- package/dist/domain/ui-service/mutate/system.d.ts +2 -1
- package/dist/domain/ui-service/mutate/system.js +17 -3
- package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
- package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
- package/dist/domain/ui-service/query/config.js +30 -0
- package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
- package/dist/domain/ui-service/query/custom-providers.js +13 -0
- package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
- package/dist/domain/ui-service/query/machine-detail.js +56 -0
- package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
- package/dist/domain/ui-service/query/machine-probe.js +136 -0
- package/dist/domain/ui-service/query/schedules.js +5 -0
- package/dist/domain/ui-service/query/sessions.js +8 -2
- package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
- package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
- package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
- package/dist/domain/ui-service/query/thread-templates.js +44 -7
- package/dist/domain/ui-service/types.d.ts +298 -7
- package/dist/domain/ui-service/ui-service.js +27 -3
- package/dist/entry/app.js +24 -3
- package/dist/entry/auth-cli.d.ts +4 -1
- package/dist/entry/auth-cli.js +10 -2
- package/dist/entry/cli-help.js +6 -2
- package/dist/entry/cli.js +2 -1
- package/dist/entry/daemon.d.ts +0 -11
- package/dist/entry/daemon.js +5 -49
- package/dist/entry/provider-cli.d.ts +16 -0
- package/dist/entry/provider-cli.js +203 -0
- package/dist/events/event-types.d.ts +2 -1
- package/dist/orchestration/agent-runner.js +3 -2
- package/dist/orchestration/routing/commands/cost.d.ts +8 -0
- package/dist/orchestration/routing/commands/cost.js +93 -21
- package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
- package/dist/orchestration/routing/commands/login-custom.js +89 -0
- package/dist/orchestration/routing/commands/login.d.ts +3 -0
- package/dist/orchestration/routing/commands/login.js +7 -0
- package/dist/orchestration/routing/message-router.js +48 -33
- package/dist/orchestration/routing/webhook.js +1 -1
- package/dist/orchestration/session-events.d.ts +2 -1
- package/dist/orchestration/session-events.js +1 -0
- package/dist/orchestration/thread-callback.js +1 -1
- package/dist/store/conversation-history-repo.d.ts +5 -1
- package/dist/store/conversation-history-repo.js +2 -1
- package/dist/store/cost-repo.d.ts +17 -0
- package/dist/store/cost-repo.js +47 -5
- package/dist/store/profile-repo.d.ts +0 -10
- package/dist/store/profile-repo.js +34 -56
- package/dist/store/session-registry-repo.d.ts +12 -0
- package/dist/store/session-registry-repo.js +16 -0
- package/package.json +1 -1
- package/web/dist/assets/index-DYMfaAi4.css +1 -0
- package/web/dist/assets/index-uOoZjGKa.js +141 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-DrNx9R6c.js +0 -139
- package/web/dist/assets/index-zpf3OSKC.css +0 -1
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { AgentSlotId } from '../../core/types/thread-types.js';
|
|
2
|
+
import type { CoderReviewVariant } from './arm-schema.js';
|
|
3
|
+
/** The pipeline thread's committed terminal state. */
|
|
4
|
+
export type ProposalTerminalState = 'completed' | 'failed' | 'cancelled' | 'timeout';
|
|
5
|
+
/** Why the step loop ended. The first four are the transition engine's own typed reasons; the
|
|
6
|
+
* last two are the orchestrator's, for a loop the engine never got to judge. */
|
|
7
|
+
export type ProposalStopReason = 'converged' | 'max_iterations' | 'cost_limit' | 'no_matching_transition' | 'admission_limit' | 'unavailable';
|
|
8
|
+
/** The last step actually executed. Null when the thread executed none. */
|
|
9
|
+
export interface ProposalFinalStep {
|
|
10
|
+
agentSlotId: AgentSlotId;
|
|
11
|
+
stage: string | null;
|
|
12
|
+
index: number;
|
|
13
|
+
}
|
|
14
|
+
/** Closed: five members and nothing else. The verdict text is the final step's last assistant
|
|
15
|
+
* message from the journal stream — never the artifact file, which accumulates every earlier
|
|
16
|
+
* step's text, and never the thread summary, which one backend never populates at all. */
|
|
17
|
+
export interface ProposalDecisionInput {
|
|
18
|
+
variant: CoderReviewVariant;
|
|
19
|
+
terminalState: ProposalTerminalState;
|
|
20
|
+
finalStep: ProposalFinalStep | null;
|
|
21
|
+
/** Null, not '', when the final step emitted no assistant message at all. */
|
|
22
|
+
finalAssistantText: string | null;
|
|
23
|
+
stopReason: ProposalStopReason;
|
|
24
|
+
}
|
|
25
|
+
export type ProposalBlockReason = 'thread_not_completed' | 'wrong_terminal_slot' | 'verdict_text_unavailable' | 'verdict_marker_absent' | 'iterations_exhausted';
|
|
26
|
+
export type ProposalIntent = {
|
|
27
|
+
kind: 'complete';
|
|
28
|
+
} | {
|
|
29
|
+
kind: 'block';
|
|
30
|
+
reason: ProposalBlockReason;
|
|
31
|
+
};
|
|
32
|
+
/** Which slot speaks each variant's verdict, and in which literal. The markers differ so that one
|
|
33
|
+
* variant's approval can never satisfy the other's contract, nor be matched by the other's
|
|
34
|
+
* convergence rule. */
|
|
35
|
+
export declare const VERDICT_BY_VARIANT: Readonly<Record<CoderReviewVariant, Readonly<{
|
|
36
|
+
slot: AgentSlotId;
|
|
37
|
+
marker: string;
|
|
38
|
+
}>>>;
|
|
39
|
+
/**
|
|
40
|
+
* What the pipeline concluded — and only that. Pure, total and synchronous: no clock, no store, no
|
|
41
|
+
* filesystem, no broker call and no bus event. `block` is the default arm and `complete` the
|
|
42
|
+
* guarded one, so an input this function does not recognise degrades to a block rather than to a
|
|
43
|
+
* false approval.
|
|
44
|
+
*/
|
|
45
|
+
export declare function variantProposal(input: ProposalDecisionInput): ProposalIntent;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// input: a coder-review variant and the five facts its pipeline thread ended with
|
|
2
|
+
// output: a complete or typed-block proposal intent, decided and never applied
|
|
3
|
+
// pos: The coder-review variant proposal decision
|
|
4
|
+
// >>> If I am updated, update my header and folder CORTEX.md <<<
|
|
5
|
+
/** Which slot speaks each variant's verdict, and in which literal. The markers differ so that one
|
|
6
|
+
* variant's approval can never satisfy the other's contract, nor be matched by the other's
|
|
7
|
+
* convergence rule. */
|
|
8
|
+
export const VERDICT_BY_VARIANT = Object.freeze({
|
|
9
|
+
'audit-retry': Object.freeze({ slot: 'benchmark-reviewer', marker: '[IMPL-APPROVED]' }),
|
|
10
|
+
'reviewer-fix': Object.freeze({ slot: 'benchmark-fixer', marker: '[FIX-VERIFIED]' }),
|
|
11
|
+
});
|
|
12
|
+
/** Named rather than written as `!== 'max_iterations'`: a stop reason added later must degrade to
|
|
13
|
+
* a block, and an exclusion test would silently admit it as an approval. */
|
|
14
|
+
const COMPLETABLE_STOP_REASONS = new Set([
|
|
15
|
+
'converged', 'cost_limit', 'no_matching_transition', 'admission_limit', 'unavailable',
|
|
16
|
+
]);
|
|
17
|
+
/**
|
|
18
|
+
* What the pipeline concluded — and only that. Pure, total and synchronous: no clock, no store, no
|
|
19
|
+
* filesystem, no broker call and no bus event. `block` is the default arm and `complete` the
|
|
20
|
+
* guarded one, so an input this function does not recognise degrades to a block rather than to a
|
|
21
|
+
* false approval.
|
|
22
|
+
*/
|
|
23
|
+
export function variantProposal(input) {
|
|
24
|
+
const verdict = VERDICT_BY_VARIANT[input.variant];
|
|
25
|
+
if (input.terminalState !== 'completed')
|
|
26
|
+
return { kind: 'block', reason: 'thread_not_completed' };
|
|
27
|
+
if (!verdict || input.finalStep?.agentSlotId !== verdict.slot) {
|
|
28
|
+
return { kind: 'block', reason: 'wrong_terminal_slot' };
|
|
29
|
+
}
|
|
30
|
+
// A dropped assistant event and a verdict that withholds the marker both block, but they are
|
|
31
|
+
// different facts about the run and only one of them is the model's decision.
|
|
32
|
+
if (input.finalAssistantText === null) {
|
|
33
|
+
return { kind: 'block', reason: 'verdict_text_unavailable' };
|
|
34
|
+
}
|
|
35
|
+
if (!input.finalAssistantText.includes(verdict.marker)) {
|
|
36
|
+
return { kind: 'block', reason: 'verdict_marker_absent' };
|
|
37
|
+
}
|
|
38
|
+
if (!COMPLETABLE_STOP_REASONS.has(input.stopReason)) {
|
|
39
|
+
return { kind: 'block', reason: 'iterations_exhausted' };
|
|
40
|
+
}
|
|
41
|
+
return { kind: 'complete' };
|
|
42
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { AgentSlotId } from '../../core/types/thread-types.js';
|
|
2
|
+
export type LeaseState = 'parent-writable' | 'draining' | 'thread-owned' | 'answer-frozen' | 'released';
|
|
3
|
+
/** Where a given step's backend process is placed. Closed set. */
|
|
4
|
+
export type WorkspacePlacement = 'shared-writable' | 'disposable-snapshot';
|
|
5
|
+
/** The two coder-review variants whose (variant, slot) pair fixes placement. */
|
|
6
|
+
export type CoderReviewVariant = 'audit-retry' | 'reviewer-fix';
|
|
7
|
+
export interface WriterIdentity {
|
|
8
|
+
agentSlotId: AgentSlotId;
|
|
9
|
+
stepIndex: number;
|
|
10
|
+
}
|
|
11
|
+
export interface LeaseView {
|
|
12
|
+
state: LeaseState;
|
|
13
|
+
/** null in every state except `thread-owned` while a writer grant is outstanding. */
|
|
14
|
+
writer: WriterIdentity | null;
|
|
15
|
+
/** The one shared writable root. Constant for the trial's lifetime. */
|
|
16
|
+
sharedRoot: string;
|
|
17
|
+
/** Monotonic, incremented on every state change; a stale grant is detected by epoch mismatch. */
|
|
18
|
+
epoch: number;
|
|
19
|
+
}
|
|
20
|
+
export interface WriterGrant {
|
|
21
|
+
readonly identity: WriterIdentity;
|
|
22
|
+
readonly epoch: number;
|
|
23
|
+
release(): void;
|
|
24
|
+
}
|
|
25
|
+
export type WorkspaceLeaseErrorDetail = 'not_thread_owned' | 'writer_already_held' | 'writer_not_held' | 'cwd_outside_grant' | 'drain_precondition_failed' | 'transition_not_implemented';
|
|
26
|
+
export declare class WorkspaceLeaseError extends Error {
|
|
27
|
+
readonly detail: WorkspaceLeaseErrorDetail;
|
|
28
|
+
constructor(detail: WorkspaceLeaseErrorDetail, message: string);
|
|
29
|
+
}
|
|
30
|
+
export interface WorkspaceLease {
|
|
31
|
+
/** Pure: no filesystem and no name lookup, so a policy guard can read it. */
|
|
32
|
+
read(): LeaseView;
|
|
33
|
+
beginDrain(): void;
|
|
34
|
+
completeDrain(): void;
|
|
35
|
+
abortDrain(detail: string): never;
|
|
36
|
+
/** Arms the next step: fixes its placement and returns the cwd it must run in. Idempotent per
|
|
37
|
+
* (agentSlotId, stepIndex). Takes a writer grant iff placement is `shared-writable`. */
|
|
38
|
+
armStep(input: WriterIdentity & {
|
|
39
|
+
placement: WorkspacePlacement;
|
|
40
|
+
}): {
|
|
41
|
+
cwd: string;
|
|
42
|
+
grant: WriterGrant | null;
|
|
43
|
+
};
|
|
44
|
+
/** Throws rather than returning false: this runs at a process boundary. */
|
|
45
|
+
assertAdmissible(cwd: string): void;
|
|
46
|
+
freeze(): never;
|
|
47
|
+
thaw(): never;
|
|
48
|
+
release(): void;
|
|
49
|
+
}
|
|
50
|
+
/** The trial roots a disposable snapshot is placed under. */
|
|
51
|
+
export interface TrialSnapshotPaths {
|
|
52
|
+
root: string;
|
|
53
|
+
tempDir: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Publish the run's lease for the duration of its steps. The per-step trial adapter is built by the
|
|
57
|
+
* caller that admits the run, which is strictly before the lease exists, so the selector cannot be
|
|
58
|
+
* handed down as a value — it is read back out of this scope at each spawn-config build
|
|
59
|
+
* (design section 16 (16.1) LS3).
|
|
60
|
+
*/
|
|
61
|
+
export declare function withActiveWorkspaceLease<T>(lease: WorkspaceLease, action: () => Promise<T>): Promise<T>;
|
|
62
|
+
/** The live lease state. Pure — `read()` performs no filesystem and no name lookup — and total: a
|
|
63
|
+
* step reached outside a lease scope has no state to select and fails closed. */
|
|
64
|
+
export declare function readActiveLeaseState(): LeaseState;
|
|
65
|
+
export interface WorkspaceLeaseInput {
|
|
66
|
+
sharedRoot: string;
|
|
67
|
+
threadId: string;
|
|
68
|
+
/** null when the run has no trial root — a disposable snapshot is then refused. */
|
|
69
|
+
trialPaths: TrialSnapshotPaths | null;
|
|
70
|
+
/** Live orchestrator counters: processes admitted and supervisor sessions held. */
|
|
71
|
+
admission: () => {
|
|
72
|
+
admitted: number;
|
|
73
|
+
sessions: number;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Placement is a function of (variant, slot) and of nothing else — never of a prompt, a template
|
|
77
|
+
* field or an environment variable. A pair no variant declares has no placement. */
|
|
78
|
+
export declare function resolveWorkspacePlacement(variant: CoderReviewVariant, agentSlotId: AgentSlotId): WorkspacePlacement;
|
|
79
|
+
export declare function assertRecursiveCopySupported(nodeVersion: string): void;
|
|
80
|
+
export declare function createWorkspaceLease(input: WorkspaceLeaseInput): WorkspaceLease;
|
|
81
|
+
export interface StepSettlement extends WriterIdentity {
|
|
82
|
+
stage: string | null;
|
|
83
|
+
/** The step's terminal assistant message, or null when the step produced none. */
|
|
84
|
+
terminalText: string | null;
|
|
85
|
+
}
|
|
86
|
+
export interface WorkspaceStepBoundary {
|
|
87
|
+
/** The cwd this step's backend process must run in. */
|
|
88
|
+
resolveStepWorkspace(identity: WriterIdentity): string;
|
|
89
|
+
/** Runs once per armed step, after its process exited and before the next transition is
|
|
90
|
+
* evaluated — including on the error path. */
|
|
91
|
+
settleStepWorkspace(input: StepSettlement): void;
|
|
92
|
+
}
|
|
93
|
+
export interface WorkspaceStepBoundaryInput {
|
|
94
|
+
lease: WorkspaceLease;
|
|
95
|
+
placement: (agentSlotId: AgentSlotId) => WorkspacePlacement;
|
|
96
|
+
/** The thread artifact a snapshot-placed step's terminal message is appended to. */
|
|
97
|
+
artifactPath: string;
|
|
98
|
+
}
|
|
99
|
+
export declare function createWorkspaceStepBoundary(input: WorkspaceStepBoundaryInput): WorkspaceStepBoundary;
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// input: shared writable root, optional trial snapshot root, admission counters
|
|
2
|
+
// output: lease state, per-step workspace placement and step-boundary settlement
|
|
3
|
+
// pos: Single-writer workspace lease for in-trial benchmark threads
|
|
4
|
+
// >>> If I am updated, update my header and folder CORTEX.md <<<
|
|
5
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
export class WorkspaceLeaseError extends Error {
|
|
9
|
+
detail;
|
|
10
|
+
constructor(detail, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.detail = detail;
|
|
13
|
+
this.name = 'WorkspaceLeaseError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const activeLease = new AsyncLocalStorage();
|
|
17
|
+
/**
|
|
18
|
+
* Publish the run's lease for the duration of its steps. The per-step trial adapter is built by the
|
|
19
|
+
* caller that admits the run, which is strictly before the lease exists, so the selector cannot be
|
|
20
|
+
* handed down as a value — it is read back out of this scope at each spawn-config build
|
|
21
|
+
* (design section 16 (16.1) LS3).
|
|
22
|
+
*/
|
|
23
|
+
export function withActiveWorkspaceLease(lease, action) {
|
|
24
|
+
return activeLease.run(lease, action);
|
|
25
|
+
}
|
|
26
|
+
/** The live lease state. Pure — `read()` performs no filesystem and no name lookup — and total: a
|
|
27
|
+
* step reached outside a lease scope has no state to select and fails closed. */
|
|
28
|
+
export function readActiveLeaseState() {
|
|
29
|
+
const lease = activeLease.getStore();
|
|
30
|
+
if (lease === undefined)
|
|
31
|
+
throw new Error('No benchmark workspace lease is in scope');
|
|
32
|
+
return lease.read().state;
|
|
33
|
+
}
|
|
34
|
+
const SNAPSHOT_DIR = 'review-snapshot';
|
|
35
|
+
/** Recursive copy is only stable from this major; below it the copy is an experimental API. */
|
|
36
|
+
const STABLE_RECURSIVE_COPY_MAJOR = 22;
|
|
37
|
+
const VARIANT_PLACEMENTS = {
|
|
38
|
+
'reviewer-fix': {
|
|
39
|
+
parent: 'shared-writable',
|
|
40
|
+
'benchmark-coder': 'shared-writable',
|
|
41
|
+
'benchmark-fixer': 'shared-writable',
|
|
42
|
+
},
|
|
43
|
+
'audit-retry': {
|
|
44
|
+
parent: 'shared-writable',
|
|
45
|
+
'benchmark-coder': 'shared-writable',
|
|
46
|
+
'benchmark-reviewer': 'disposable-snapshot',
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
/** Placement is a function of (variant, slot) and of nothing else — never of a prompt, a template
|
|
50
|
+
* field or an environment variable. A pair no variant declares has no placement. */
|
|
51
|
+
export function resolveWorkspacePlacement(variant, agentSlotId) {
|
|
52
|
+
const placement = VARIANT_PLACEMENTS[variant]?.[agentSlotId];
|
|
53
|
+
if (!placement) {
|
|
54
|
+
throw new Error(`No workspace placement is declared for ${variant}/${agentSlotId}`);
|
|
55
|
+
}
|
|
56
|
+
return placement;
|
|
57
|
+
}
|
|
58
|
+
export function assertRecursiveCopySupported(nodeVersion) {
|
|
59
|
+
const major = Number.parseInt(nodeVersion.split('.')[0] ?? '', 10);
|
|
60
|
+
if (!Number.isInteger(major) || major < STABLE_RECURSIVE_COPY_MAJOR) {
|
|
61
|
+
throw new Error(`A disposable workspace snapshot needs Node ${STABLE_RECURSIVE_COPY_MAJOR} or newer, `
|
|
62
|
+
+ `where the recursive copy is stable; this runtime reports Node ${nodeVersion}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function armKey(identity) {
|
|
66
|
+
return `${identity.agentSlotId}#${identity.stepIndex}`;
|
|
67
|
+
}
|
|
68
|
+
function describe(identity) {
|
|
69
|
+
return `${identity.agentSlotId} step ${identity.stepIndex}`;
|
|
70
|
+
}
|
|
71
|
+
export function createWorkspaceLease(input) {
|
|
72
|
+
let state = 'parent-writable';
|
|
73
|
+
let writer = null;
|
|
74
|
+
let writerEpoch = -1;
|
|
75
|
+
let epoch = 0;
|
|
76
|
+
let current = null;
|
|
77
|
+
const armed = new Map();
|
|
78
|
+
function requireThreadOwned(action) {
|
|
79
|
+
if (state !== 'thread-owned') {
|
|
80
|
+
throw new WorkspaceLeaseError('not_thread_owned', `${action} requires a thread-owned workspace; the lease is ${state}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function snapshotRoot(stepIndex) {
|
|
84
|
+
const trial = input.trialPaths;
|
|
85
|
+
if (!trial) {
|
|
86
|
+
throw new Error('A disposable workspace snapshot needs a trial root; this run declares none');
|
|
87
|
+
}
|
|
88
|
+
const root = path.join(trial.tempDir, SNAPSHOT_DIR, input.threadId, String(stepIndex));
|
|
89
|
+
if (!root.startsWith(trial.root)) {
|
|
90
|
+
throw new Error(`A workspace snapshot must be placed under the trial root: ${root}`);
|
|
91
|
+
}
|
|
92
|
+
if (root.startsWith(input.sharedRoot)) {
|
|
93
|
+
throw new Error(`A workspace snapshot must be placed outside the shared workspace: ${root}`);
|
|
94
|
+
}
|
|
95
|
+
return root;
|
|
96
|
+
}
|
|
97
|
+
function createSnapshot(stepIndex) {
|
|
98
|
+
assertRecursiveCopySupported(process.versions.node);
|
|
99
|
+
const root = snapshotRoot(stepIndex);
|
|
100
|
+
fs.mkdirSync(path.dirname(root), { recursive: true });
|
|
101
|
+
// A symlink is copied as a symlink: dereferencing would lift its target out of the workspace
|
|
102
|
+
// and present it to the scanner as a file this trial produced.
|
|
103
|
+
fs.cpSync(input.sharedRoot, root, {
|
|
104
|
+
recursive: true, dereference: false, preserveTimestamps: true,
|
|
105
|
+
force: true, errorOnExist: false,
|
|
106
|
+
});
|
|
107
|
+
return root;
|
|
108
|
+
}
|
|
109
|
+
function issueGrant(identity) {
|
|
110
|
+
epoch += 1;
|
|
111
|
+
writer = identity;
|
|
112
|
+
writerEpoch = epoch;
|
|
113
|
+
const granted = epoch;
|
|
114
|
+
return {
|
|
115
|
+
identity,
|
|
116
|
+
epoch: granted,
|
|
117
|
+
release() {
|
|
118
|
+
if (writer === null || writerEpoch !== granted) {
|
|
119
|
+
throw new WorkspaceLeaseError('writer_not_held', `The writer grant of ${describe(identity)} is no longer outstanding`);
|
|
120
|
+
}
|
|
121
|
+
writer = null;
|
|
122
|
+
writerEpoch = -1;
|
|
123
|
+
epoch += 1;
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
function armStep(request) {
|
|
128
|
+
requireThreadOwned('Arming a step');
|
|
129
|
+
const identity = {
|
|
130
|
+
agentSlotId: request.agentSlotId, stepIndex: request.stepIndex,
|
|
131
|
+
};
|
|
132
|
+
const key = armKey(identity);
|
|
133
|
+
const existing = armed.get(key);
|
|
134
|
+
if (existing) {
|
|
135
|
+
// Re-arming the same step is idempotent. Its snapshot is rebuilt only when the step
|
|
136
|
+
// boundary already discarded it, which happens when an interrupted step is re-run.
|
|
137
|
+
if (existing.placement === 'disposable-snapshot' && !fs.existsSync(existing.cwd)) {
|
|
138
|
+
createSnapshot(identity.stepIndex);
|
|
139
|
+
}
|
|
140
|
+
current = existing;
|
|
141
|
+
return { cwd: existing.cwd, grant: existing.grant };
|
|
142
|
+
}
|
|
143
|
+
if (request.placement === 'shared-writable') {
|
|
144
|
+
if (writer !== null) {
|
|
145
|
+
throw new WorkspaceLeaseError('writer_already_held', `The shared workspace is held by ${describe(writer)}; ${describe(identity)} cannot take it`);
|
|
146
|
+
}
|
|
147
|
+
const step = {
|
|
148
|
+
identity, placement: request.placement, cwd: input.sharedRoot, grant: issueGrant(identity),
|
|
149
|
+
};
|
|
150
|
+
armed.set(key, step);
|
|
151
|
+
current = step;
|
|
152
|
+
return { cwd: step.cwd, grant: step.grant };
|
|
153
|
+
}
|
|
154
|
+
const step = {
|
|
155
|
+
identity, placement: request.placement, cwd: createSnapshot(identity.stepIndex), grant: null,
|
|
156
|
+
};
|
|
157
|
+
armed.set(key, step);
|
|
158
|
+
current = step;
|
|
159
|
+
return { cwd: step.cwd, grant: null };
|
|
160
|
+
}
|
|
161
|
+
function assertAdmissible(cwd) {
|
|
162
|
+
requireThreadOwned('Spawning a benchmark step');
|
|
163
|
+
if (current === null) {
|
|
164
|
+
throw new WorkspaceLeaseError('cwd_outside_grant', `No step is armed; ${cwd || 'an empty cwd'} was not granted`);
|
|
165
|
+
}
|
|
166
|
+
if (cwd !== current.cwd) {
|
|
167
|
+
throw new WorkspaceLeaseError('cwd_outside_grant', `${cwd || 'An empty cwd'} is not the workspace armed for ${describe(current.identity)}`);
|
|
168
|
+
}
|
|
169
|
+
if (current.placement === 'shared-writable'
|
|
170
|
+
&& (writer === null || armKey(writer) !== armKey(current.identity))) {
|
|
171
|
+
throw new WorkspaceLeaseError('writer_not_held', `${describe(current.identity)} holds no writer grant on the shared workspace`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
read: () => ({ state, writer, sharedRoot: input.sharedRoot, epoch }),
|
|
176
|
+
beginDrain() {
|
|
177
|
+
if (state !== 'parent-writable') {
|
|
178
|
+
throw new WorkspaceLeaseError('drain_precondition_failed', `A drain starts from parent-writable; the lease is ${state}`);
|
|
179
|
+
}
|
|
180
|
+
state = 'draining';
|
|
181
|
+
epoch += 1;
|
|
182
|
+
},
|
|
183
|
+
// A precondition assertion, not a wait: it holds on the entry path of a run that has admitted
|
|
184
|
+
// nothing, and fails loudly the moment a parent with live work exists.
|
|
185
|
+
completeDrain() {
|
|
186
|
+
const { admitted, sessions } = input.admission();
|
|
187
|
+
if (state !== 'draining' || writer !== null || admitted !== 0 || sessions !== 0) {
|
|
188
|
+
throw new WorkspaceLeaseError('drain_precondition_failed', `The workspace cannot be taken: state=${state}, writer=${writer ? describe(writer) : 'none'}, `
|
|
189
|
+
+ `admitted=${admitted}, sessions=${sessions}`);
|
|
190
|
+
}
|
|
191
|
+
state = 'thread-owned';
|
|
192
|
+
epoch += 1;
|
|
193
|
+
},
|
|
194
|
+
abortDrain(detail) {
|
|
195
|
+
state = 'parent-writable';
|
|
196
|
+
writer = null;
|
|
197
|
+
writerEpoch = -1;
|
|
198
|
+
epoch += 1;
|
|
199
|
+
throw new WorkspaceLeaseError('drain_precondition_failed', `Workspace drain aborted: ${detail}`);
|
|
200
|
+
},
|
|
201
|
+
armStep,
|
|
202
|
+
assertAdmissible,
|
|
203
|
+
freeze() {
|
|
204
|
+
throw new WorkspaceLeaseError('transition_not_implemented', 'Freezing the workspace for an answer is not implemented here');
|
|
205
|
+
},
|
|
206
|
+
thaw() {
|
|
207
|
+
throw new WorkspaceLeaseError('transition_not_implemented', 'Thawing the workspace after an answer is not implemented here');
|
|
208
|
+
},
|
|
209
|
+
release() {
|
|
210
|
+
if (state === 'released')
|
|
211
|
+
return;
|
|
212
|
+
state = 'released';
|
|
213
|
+
writer = null;
|
|
214
|
+
writerEpoch = -1;
|
|
215
|
+
epoch += 1;
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/** One line naming the slot, the stage and the step index. Convergence markers are bracketed
|
|
220
|
+
* literals matched over the whole accumulated artifact, so a header that carries no bracket can
|
|
221
|
+
* neither contain a marker nor complete one. */
|
|
222
|
+
function stepHeader(input) {
|
|
223
|
+
const stage = input.stage ? ` (${input.stage})` : '';
|
|
224
|
+
const header = `--- snapshot step ${input.stepIndex}: ${input.agentSlotId}${stage} ---`;
|
|
225
|
+
if (header.includes('[') || header.includes(']')) {
|
|
226
|
+
throw new Error(`A step header may not carry a bracket: ${header}`);
|
|
227
|
+
}
|
|
228
|
+
return header;
|
|
229
|
+
}
|
|
230
|
+
function removeIfEmpty(directory) {
|
|
231
|
+
// Another thread of the same trial may hold a sibling snapshot; leave a non-empty parent alone.
|
|
232
|
+
try {
|
|
233
|
+
if (fs.readdirSync(directory).length === 0)
|
|
234
|
+
fs.rmdirSync(directory);
|
|
235
|
+
}
|
|
236
|
+
catch { }
|
|
237
|
+
}
|
|
238
|
+
function discardSnapshot(root) {
|
|
239
|
+
fs.rmSync(root, { recursive: true, force: true });
|
|
240
|
+
const threadDir = path.dirname(root);
|
|
241
|
+
removeIfEmpty(threadDir);
|
|
242
|
+
removeIfEmpty(path.dirname(threadDir));
|
|
243
|
+
}
|
|
244
|
+
export function createWorkspaceStepBoundary(input) {
|
|
245
|
+
const arms = new Map();
|
|
246
|
+
return {
|
|
247
|
+
resolveStepWorkspace(identity) {
|
|
248
|
+
const placement = input.placement(identity.agentSlotId);
|
|
249
|
+
const armedStep = input.lease.armStep({ ...identity, placement });
|
|
250
|
+
arms.set(armKey(identity), { placement, cwd: armedStep.cwd, grant: armedStep.grant });
|
|
251
|
+
return armedStep.cwd;
|
|
252
|
+
},
|
|
253
|
+
settleStepWorkspace(settlement) {
|
|
254
|
+
const key = armKey(settlement);
|
|
255
|
+
const step = arms.get(key);
|
|
256
|
+
if (!step)
|
|
257
|
+
return;
|
|
258
|
+
arms.delete(key);
|
|
259
|
+
try {
|
|
260
|
+
if (step.placement === 'disposable-snapshot' && settlement.terminalText) {
|
|
261
|
+
fs.appendFileSync(input.artifactPath, `\n${stepHeader(settlement)}\n${settlement.terminalText}\n`, 'utf8');
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
finally {
|
|
265
|
+
if (step.grant)
|
|
266
|
+
step.grant.release();
|
|
267
|
+
if (step.placement === 'disposable-snapshot')
|
|
268
|
+
discardSnapshot(step.cwd);
|
|
269
|
+
}
|
|
270
|
+
},
|
|
271
|
+
};
|
|
272
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Provider slug this reading is attributed to; matches the gateway route and profile provider. */
|
|
2
|
+
export declare const CODEX_PROVIDER = "openai-codex";
|
|
3
|
+
export interface QuotaWindow {
|
|
4
|
+
/** `seven_day` / `five_hour`, else `window_<minutes>m` for a length Codex has not used before. */
|
|
5
|
+
type: string;
|
|
6
|
+
/** Fraction in [0,1] — Codex reports whole percents, the throttle compares against 0.95. */
|
|
7
|
+
utilization: number;
|
|
8
|
+
/** Epoch seconds, matching the persisted provider-state shape. */
|
|
9
|
+
resetsAt: number;
|
|
10
|
+
}
|
|
11
|
+
export interface CodexQuotaReading {
|
|
12
|
+
provider: typeof CODEX_PROVIDER;
|
|
13
|
+
planType: string | null;
|
|
14
|
+
windows: QuotaWindow[];
|
|
15
|
+
}
|
|
16
|
+
export interface ParseQuotaOpts {
|
|
17
|
+
/** Injected clock: reset-after-seconds is relative, so the caller pins the reference point. */
|
|
18
|
+
nowMs: number;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Extract the quota state Codex broadcasts on every response. Returns null when the response
|
|
22
|
+
* carries no usable window — a non-Codex response, a fully disabled bucket, or a malformed
|
|
23
|
+
* reading. Null means "learned nothing", never "quota is fine".
|
|
24
|
+
*/
|
|
25
|
+
export declare function parseCodexQuotaHeaders(headers: Record<string, string>, opts: ParseQuotaOpts): CodexQuotaReading | null;
|
|
26
|
+
export declare function encodeQuotaNotice(reading: CodexQuotaReading): string;
|
|
27
|
+
/** Returns null for anything that is not a well-formed quota notice — an ordinary notification,
|
|
28
|
+
* a truncated payload, or a reading with no window. Callers treat null as "not for us". */
|
|
29
|
+
export declare function decodeQuotaNotice(message: unknown): CodexQuotaReading | null;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// input: Codex response headers, a clock reading, notice strings
|
|
2
|
+
// output: quota header parsing, reading types and the notice codec
|
|
3
|
+
// pos: Codex quota vocabulary shared by the PI child and the server
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
/** Provider slug this reading is attributed to; matches the gateway route and profile provider. */
|
|
6
|
+
export const CODEX_PROVIDER = 'openai-codex';
|
|
7
|
+
/** The two limit buckets Codex advertises per response. `secondary` is empty on plans without a
|
|
8
|
+
* short window (pro, 2026-08), so a bucket is only real when its window length is positive. */
|
|
9
|
+
const FAMILIES = ['primary', 'secondary'];
|
|
10
|
+
/** Named window lengths shared with the Claude throttle path, so state and UI stay one vocabulary. */
|
|
11
|
+
const WINDOW_TYPE_BY_MINUTES = {
|
|
12
|
+
10080: 'seven_day',
|
|
13
|
+
300: 'five_hour',
|
|
14
|
+
};
|
|
15
|
+
function lowerKeyed(headers) {
|
|
16
|
+
const map = new Map();
|
|
17
|
+
for (const [key, value] of Object.entries(headers))
|
|
18
|
+
map.set(key.toLowerCase(), value);
|
|
19
|
+
return map;
|
|
20
|
+
}
|
|
21
|
+
/** Absent, blank and unparsable values collapse to null: a missing reading must never read as 0. */
|
|
22
|
+
function num(map, key) {
|
|
23
|
+
const raw = map.get(key);
|
|
24
|
+
if (raw === undefined || raw.trim() === '')
|
|
25
|
+
return null;
|
|
26
|
+
const value = Number(raw);
|
|
27
|
+
return Number.isFinite(value) ? value : null;
|
|
28
|
+
}
|
|
29
|
+
function windowTypeFor(minutes) {
|
|
30
|
+
return WINDOW_TYPE_BY_MINUTES[minutes] ?? `window_${minutes}m`;
|
|
31
|
+
}
|
|
32
|
+
function resetsAtFor(map, family, nowMs) {
|
|
33
|
+
const absolute = num(map, `x-codex-${family}-reset-at`);
|
|
34
|
+
if (absolute !== null && absolute > 0)
|
|
35
|
+
return absolute;
|
|
36
|
+
const after = num(map, `x-codex-${family}-reset-after-seconds`);
|
|
37
|
+
return after === null ? null : Math.floor(nowMs / 1000) + after;
|
|
38
|
+
}
|
|
39
|
+
function windowFor(map, family, nowMs) {
|
|
40
|
+
const minutes = num(map, `x-codex-${family}-window-minutes`);
|
|
41
|
+
if (minutes === null || minutes <= 0)
|
|
42
|
+
return null;
|
|
43
|
+
const usedPercent = num(map, `x-codex-${family}-used-percent`);
|
|
44
|
+
if (usedPercent === null)
|
|
45
|
+
return null;
|
|
46
|
+
const resetsAt = resetsAtFor(map, family, nowMs);
|
|
47
|
+
if (resetsAt === null)
|
|
48
|
+
return null;
|
|
49
|
+
return { type: windowTypeFor(minutes), utilization: usedPercent / 100, resetsAt };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Extract the quota state Codex broadcasts on every response. Returns null when the response
|
|
53
|
+
* carries no usable window — a non-Codex response, a fully disabled bucket, or a malformed
|
|
54
|
+
* reading. Null means "learned nothing", never "quota is fine".
|
|
55
|
+
*/
|
|
56
|
+
export function parseCodexQuotaHeaders(headers, opts) {
|
|
57
|
+
const map = lowerKeyed(headers);
|
|
58
|
+
const windows = [];
|
|
59
|
+
for (const family of FAMILIES) {
|
|
60
|
+
const window = windowFor(map, family, opts.nowMs);
|
|
61
|
+
if (window)
|
|
62
|
+
windows.push(window);
|
|
63
|
+
}
|
|
64
|
+
if (windows.length === 0)
|
|
65
|
+
return null;
|
|
66
|
+
return { provider: CODEX_PROVIDER, planType: map.get('x-codex-plan-type') ?? null, windows };
|
|
67
|
+
}
|
|
68
|
+
// ─── Child → server wire form ─────────────────────────────────────
|
|
69
|
+
// The reading is observed inside the PI child, which reaches the server only over PI's RPC stream.
|
|
70
|
+
// `ctx.ui.notify` is the one fire-and-forget message on that stream, so a reading rides it as a
|
|
71
|
+
// prefixed JSON string; the prefix is what lets the parser tell it apart from real user notices.
|
|
72
|
+
const QUOTA_NOTICE_PREFIX = 'cortex:provider-quota:';
|
|
73
|
+
export function encodeQuotaNotice(reading) {
|
|
74
|
+
return QUOTA_NOTICE_PREFIX + JSON.stringify(reading);
|
|
75
|
+
}
|
|
76
|
+
/** Returns null for anything that is not a well-formed quota notice — an ordinary notification,
|
|
77
|
+
* a truncated payload, or a reading with no window. Callers treat null as "not for us". */
|
|
78
|
+
export function decodeQuotaNotice(message) {
|
|
79
|
+
if (typeof message !== 'string' || !message.startsWith(QUOTA_NOTICE_PREFIX))
|
|
80
|
+
return null;
|
|
81
|
+
const parsed = safeParse(message.slice(QUOTA_NOTICE_PREFIX.length));
|
|
82
|
+
if (!parsed || !Array.isArray(parsed.windows) || parsed.windows.length === 0)
|
|
83
|
+
return null;
|
|
84
|
+
const windows = parsed.windows.filter(isQuotaWindow);
|
|
85
|
+
if (windows.length !== parsed.windows.length)
|
|
86
|
+
return null;
|
|
87
|
+
return { provider: CODEX_PROVIDER, planType: typeof parsed.planType === 'string' ? parsed.planType : null, windows };
|
|
88
|
+
}
|
|
89
|
+
function safeParse(raw) {
|
|
90
|
+
try {
|
|
91
|
+
const value = JSON.parse(raw);
|
|
92
|
+
return value && typeof value === 'object' ? value : null;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function isQuotaWindow(value) {
|
|
99
|
+
const w = value;
|
|
100
|
+
return !!w && typeof w.type === 'string' && w.type.length > 0
|
|
101
|
+
&& Number.isFinite(w.utilization) && Number.isFinite(w.resetsAt);
|
|
102
|
+
}
|