@cortex-agent/server 2026.8.3-2 → 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/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/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/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-XqBCYtkw.js +0 -139
- package/web/dist/assets/index-zpf3OSKC.css +0 -1
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** PI request protocols a custom provider may speak (PI docs/models.md §Supported APIs). */
|
|
2
|
+
export declare const CUSTOM_PROVIDER_APIS: readonly ["anthropic-messages", "openai-completions", "openai-responses", "google-generative-ai"];
|
|
3
|
+
export type CustomProviderApi = typeof CUSTOM_PROVIDER_APIS[number];
|
|
4
|
+
/** aistatus auth styles (node_modules/aistatus AUTH_STYLES): how the gateway presents the key. */
|
|
5
|
+
export type GatewayAuthStyle = 'anthropic' | 'openai' | 'google';
|
|
6
|
+
export interface CustomProviderModelSpec {
|
|
7
|
+
id: string;
|
|
8
|
+
contextWindow?: number;
|
|
9
|
+
maxTokens?: number;
|
|
10
|
+
reasoning?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface CustomProviderInput {
|
|
13
|
+
name: string;
|
|
14
|
+
api: CustomProviderApi;
|
|
15
|
+
/** Real upstream endpoint. Stored in gateway.yaml, never in the PI catalog. */
|
|
16
|
+
upstreamUrl: string;
|
|
17
|
+
/** Upstream key. `undefined` keeps whatever is already stored; `''` clears it. */
|
|
18
|
+
apiKey?: string;
|
|
19
|
+
models: CustomProviderModelSpec[];
|
|
20
|
+
headers?: Record<string, string>;
|
|
21
|
+
compat?: Record<string, unknown>;
|
|
22
|
+
}
|
|
23
|
+
export type CustomProviderIssue = 'name-required' | 'name-charset' | 'name-reserved' | 'api-invalid' | 'upstream-required' | 'upstream-scheme' | 'models-required' | 'model-id-required' | 'model-id-duplicate';
|
|
24
|
+
/** Same charset the profile loader enforces on a PI provider name (domain/agents/profile-manager). */
|
|
25
|
+
export declare const CUSTOM_PROVIDER_NAME_RE: RegExp;
|
|
26
|
+
/**
|
|
27
|
+
* Written as the PI-side `apiKey` so PI counts the provider as authenticated and lists its models.
|
|
28
|
+
* The real upstream secret lives in the gateway route; the gateway does not check inbound keys.
|
|
29
|
+
*/
|
|
30
|
+
export declare const GATEWAY_PLACEHOLDER_KEY = "cortex-gateway";
|
|
31
|
+
export declare function gatewayAuthStyle(api: CustomProviderApi): GatewayAuthStyle;
|
|
32
|
+
/**
|
|
33
|
+
* Gateway endpoint section a custom provider's route belongs to. The mode is always the provider
|
|
34
|
+
* name; the endpoint follows the protocol, because an Anthropic-protocol endpoint can also serve
|
|
35
|
+
* the Claude backend, whose mode URL is fixed at `/m/<mode>/anthropic`. Other protocols have no
|
|
36
|
+
* such caller, so their route sits in a section named after the provider.
|
|
37
|
+
*/
|
|
38
|
+
export declare function gatewayEndpoint(api: CustomProviderApi, name: string): string;
|
|
39
|
+
/**
|
|
40
|
+
* PI's baseUrl for a custom provider: the gateway's mode route, so every call is accounted and
|
|
41
|
+
* throttled like any other route.
|
|
42
|
+
*/
|
|
43
|
+
export declare function customProviderBaseUrl(gatewayUrl: string, name: string, api: CustomProviderApi): string;
|
|
44
|
+
export interface ValidateCustomProviderOpts {
|
|
45
|
+
/** Provider ids PI already owns — a custom definition may not shadow one. */
|
|
46
|
+
reservedNames?: string[];
|
|
47
|
+
}
|
|
48
|
+
export declare function validateCustomProvider(input: CustomProviderInput, opts?: ValidateCustomProviderOpts): CustomProviderIssue[];
|
|
49
|
+
/** Normalize free-form input: trim strings, drop empty optional maps, keep declared model fields. */
|
|
50
|
+
export declare function normalizeCustomProvider(input: CustomProviderInput): CustomProviderInput;
|
|
51
|
+
/** The `providers.<name>` object written into PI's models.json. Carries no upstream secret. */
|
|
52
|
+
export declare function buildModelsJsonEntry(input: CustomProviderInput, gatewayUrl: string): Record<string, unknown>;
|
|
53
|
+
export declare function readEntryModels(entry: Record<string, unknown>): CustomProviderModelSpec[];
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// input: user-supplied custom provider definitions
|
|
2
|
+
// output: validation issues, gateway auth styles, PI catalog entries
|
|
3
|
+
// pos: Shape and rules of a user-defined PI provider
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
/** PI request protocols a custom provider may speak (PI docs/models.md §Supported APIs). */
|
|
6
|
+
export const CUSTOM_PROVIDER_APIS = [
|
|
7
|
+
'anthropic-messages',
|
|
8
|
+
'openai-completions',
|
|
9
|
+
'openai-responses',
|
|
10
|
+
'google-generative-ai',
|
|
11
|
+
];
|
|
12
|
+
/** Same charset the profile loader enforces on a PI provider name (domain/agents/profile-manager). */
|
|
13
|
+
export const CUSTOM_PROVIDER_NAME_RE = /^[a-zA-Z0-9_-]+$/;
|
|
14
|
+
/**
|
|
15
|
+
* Written as the PI-side `apiKey` so PI counts the provider as authenticated and lists its models.
|
|
16
|
+
* The real upstream secret lives in the gateway route; the gateway does not check inbound keys.
|
|
17
|
+
*/
|
|
18
|
+
export const GATEWAY_PLACEHOLDER_KEY = 'cortex-gateway';
|
|
19
|
+
const AUTH_STYLE_BY_API = {
|
|
20
|
+
'anthropic-messages': 'anthropic',
|
|
21
|
+
'openai-completions': 'openai',
|
|
22
|
+
'openai-responses': 'openai',
|
|
23
|
+
'google-generative-ai': 'google',
|
|
24
|
+
};
|
|
25
|
+
export function gatewayAuthStyle(api) {
|
|
26
|
+
return AUTH_STYLE_BY_API[api];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Gateway endpoint section a custom provider's route belongs to. The mode is always the provider
|
|
30
|
+
* name; the endpoint follows the protocol, because an Anthropic-protocol endpoint can also serve
|
|
31
|
+
* the Claude backend, whose mode URL is fixed at `/m/<mode>/anthropic`. Other protocols have no
|
|
32
|
+
* such caller, so their route sits in a section named after the provider.
|
|
33
|
+
*/
|
|
34
|
+
export function gatewayEndpoint(api, name) {
|
|
35
|
+
return api === 'anthropic-messages' ? 'anthropic' : name;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* PI's baseUrl for a custom provider: the gateway's mode route, so every call is accounted and
|
|
39
|
+
* throttled like any other route.
|
|
40
|
+
*/
|
|
41
|
+
export function customProviderBaseUrl(gatewayUrl, name, api) {
|
|
42
|
+
return `${gatewayUrl.replace(/\/+$/, '')}/m/${name}/${gatewayEndpoint(api, name)}`;
|
|
43
|
+
}
|
|
44
|
+
export function validateCustomProvider(input, opts = {}) {
|
|
45
|
+
const issues = [];
|
|
46
|
+
const name = input.name?.trim() ?? '';
|
|
47
|
+
if (!name)
|
|
48
|
+
issues.push('name-required');
|
|
49
|
+
else if (!CUSTOM_PROVIDER_NAME_RE.test(name))
|
|
50
|
+
issues.push('name-charset');
|
|
51
|
+
else if (opts.reservedNames?.includes(name))
|
|
52
|
+
issues.push('name-reserved');
|
|
53
|
+
if (!CUSTOM_PROVIDER_APIS.includes(input.api))
|
|
54
|
+
issues.push('api-invalid');
|
|
55
|
+
const upstream = input.upstreamUrl?.trim() ?? '';
|
|
56
|
+
if (!upstream)
|
|
57
|
+
issues.push('upstream-required');
|
|
58
|
+
else if (!/^https?:\/\/\S+$/i.test(upstream))
|
|
59
|
+
issues.push('upstream-scheme');
|
|
60
|
+
const models = input.models ?? [];
|
|
61
|
+
if (models.length === 0) {
|
|
62
|
+
issues.push('models-required');
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
const ids = models.map((m) => m.id?.trim() ?? '');
|
|
66
|
+
if (ids.some((id) => !id))
|
|
67
|
+
issues.push('model-id-required');
|
|
68
|
+
else if (new Set(ids).size !== ids.length)
|
|
69
|
+
issues.push('model-id-duplicate');
|
|
70
|
+
}
|
|
71
|
+
return issues;
|
|
72
|
+
}
|
|
73
|
+
/** Normalize free-form input: trim strings, drop empty optional maps, keep declared model fields. */
|
|
74
|
+
export function normalizeCustomProvider(input) {
|
|
75
|
+
return {
|
|
76
|
+
...input,
|
|
77
|
+
name: input.name?.trim() ?? '',
|
|
78
|
+
upstreamUrl: input.upstreamUrl?.trim() ?? '',
|
|
79
|
+
models: (input.models ?? []).map((model) => ({
|
|
80
|
+
...model,
|
|
81
|
+
id: model.id?.trim() ?? '',
|
|
82
|
+
})),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** The `providers.<name>` object written into PI's models.json. Carries no upstream secret. */
|
|
86
|
+
export function buildModelsJsonEntry(input, gatewayUrl) {
|
|
87
|
+
const entry = {
|
|
88
|
+
baseUrl: customProviderBaseUrl(gatewayUrl, input.name, input.api),
|
|
89
|
+
api: input.api,
|
|
90
|
+
apiKey: GATEWAY_PLACEHOLDER_KEY,
|
|
91
|
+
models: input.models.map((model) => {
|
|
92
|
+
const spec = { id: model.id };
|
|
93
|
+
if (model.contextWindow !== undefined)
|
|
94
|
+
spec.contextWindow = model.contextWindow;
|
|
95
|
+
if (model.maxTokens !== undefined)
|
|
96
|
+
spec.maxTokens = model.maxTokens;
|
|
97
|
+
if (model.reasoning !== undefined)
|
|
98
|
+
spec.reasoning = model.reasoning;
|
|
99
|
+
return spec;
|
|
100
|
+
}),
|
|
101
|
+
};
|
|
102
|
+
if (input.headers && Object.keys(input.headers).length > 0)
|
|
103
|
+
entry.headers = input.headers;
|
|
104
|
+
if (input.compat && Object.keys(input.compat).length > 0)
|
|
105
|
+
entry.compat = input.compat;
|
|
106
|
+
return entry;
|
|
107
|
+
}
|
|
108
|
+
export function readEntryModels(entry) {
|
|
109
|
+
const models = Array.isArray(entry.models) ? entry.models : [];
|
|
110
|
+
return models
|
|
111
|
+
.filter((model) => !!model && typeof model === 'object')
|
|
112
|
+
.map((model) => {
|
|
113
|
+
const spec = { id: String(model.id ?? '') };
|
|
114
|
+
if (typeof model.contextWindow === 'number')
|
|
115
|
+
spec.contextWindow = model.contextWindow;
|
|
116
|
+
if (typeof model.maxTokens === 'number')
|
|
117
|
+
spec.maxTokens = model.maxTokens;
|
|
118
|
+
if (typeof model.reasoning === 'boolean')
|
|
119
|
+
spec.reasoning = model.reasoning;
|
|
120
|
+
return spec;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { type CustomProviderApi, type CustomProviderInput, type CustomProviderIssue, type CustomProviderModelSpec } from './custom-provider-model.js';
|
|
2
|
+
export interface CustomProviderStores {
|
|
3
|
+
/** PI's user catalog (`~/.pi/agent/models.json`). */
|
|
4
|
+
modelsPath: string;
|
|
5
|
+
/** The gateway config the running gateway watches (`~/.aistatus/gateway.yaml`). */
|
|
6
|
+
gatewayPath: string;
|
|
7
|
+
/** Gateway base URL every custom provider is routed through. */
|
|
8
|
+
gatewayUrl: string;
|
|
9
|
+
/** Provider ids PI already owns, so a definition cannot shadow a built-in. */
|
|
10
|
+
reservedNames?: string[];
|
|
11
|
+
/** Called after a successful change so provider discovery and account status can refresh. */
|
|
12
|
+
onChanged?: () => void;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The host files a custom provider lives in: PI's own catalog and the gateway config it routes to.
|
|
16
|
+
* A change invalidates the provider discovery cache the same way a login does, so a provider defined
|
|
17
|
+
* from any surface reaches the next spawn without waiting out the cache TTL.
|
|
18
|
+
*/
|
|
19
|
+
export declare function defaultCustomProviderStores(): CustomProviderStores;
|
|
20
|
+
/** Secret-free view of a stored custom provider. */
|
|
21
|
+
export interface CustomProviderView {
|
|
22
|
+
name: string;
|
|
23
|
+
api: CustomProviderApi;
|
|
24
|
+
models: CustomProviderModelSpec[];
|
|
25
|
+
/** Upstream from the gateway route, or null when the route is missing. */
|
|
26
|
+
upstreamUrl: string | null;
|
|
27
|
+
hasApiKey: boolean;
|
|
28
|
+
/** Whether a gateway route backs this definition. False means calls will 404 at the gateway. */
|
|
29
|
+
routed: boolean;
|
|
30
|
+
headers?: Record<string, string>;
|
|
31
|
+
compat?: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
export type CustomProviderFailure = CustomProviderIssue | 'write-failed' | 'not-found';
|
|
34
|
+
export type CustomProviderResult = {
|
|
35
|
+
ok: true;
|
|
36
|
+
provider: CustomProviderView;
|
|
37
|
+
} | {
|
|
38
|
+
ok: false;
|
|
39
|
+
errors: CustomProviderFailure[];
|
|
40
|
+
};
|
|
41
|
+
export type CustomProviderRemoval = {
|
|
42
|
+
ok: true;
|
|
43
|
+
} | {
|
|
44
|
+
ok: false;
|
|
45
|
+
errors: CustomProviderFailure[];
|
|
46
|
+
};
|
|
47
|
+
export declare function listCustomProviders(stores: CustomProviderStores): CustomProviderView[];
|
|
48
|
+
export declare function getCustomProvider(stores: CustomProviderStores, name: string): CustomProviderView | null;
|
|
49
|
+
/**
|
|
50
|
+
* Create or update a custom provider. The gateway route is written first — an unreferenced route is
|
|
51
|
+
* inert — and the PI catalog second, because that write is what makes the provider visible to PI.
|
|
52
|
+
* A failed catalog write therefore rolls the route back to its previous state.
|
|
53
|
+
*
|
|
54
|
+
* `apiKey` semantics: `undefined` keeps the stored upstream key (so an edit need not retype it),
|
|
55
|
+
* `''` clears it and lets the gateway pass the caller's own key through.
|
|
56
|
+
*/
|
|
57
|
+
export declare function upsertCustomProvider(stores: CustomProviderStores, input: CustomProviderInput): CustomProviderResult;
|
|
58
|
+
/** Remove a custom provider from both files. Built-in overrides are not custom and are refused. */
|
|
59
|
+
export declare function removeCustomProvider(stores: CustomProviderStores, name: string): CustomProviderRemoval;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// input: custom provider definitions and the two files that hold them
|
|
2
|
+
// output: list, upsert and remove operations spanning catalog and gateway
|
|
3
|
+
// pos: Orchestration of user-defined PI providers
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { createLogger } from '../../core/log.js';
|
|
6
|
+
import { GATEWAY_URL } from '../costs/gateway-manager.js';
|
|
7
|
+
import { piProviderDiscovery } from '../../agent-adapter/pi/discovery.js';
|
|
8
|
+
import { buildModelsJsonEntry, gatewayAuthStyle, gatewayEndpoint, normalizeCustomProvider, readEntryModels, validateCustomProvider, } from './custom-provider-model.js';
|
|
9
|
+
import { USER_PI_MODELS_PATH, readCustomProviderEntries, removeModelsJsonProvider, upsertModelsJsonProvider, } from './models-json-store.js';
|
|
10
|
+
import { GATEWAY_CONFIG_PATH, readGatewayRoute, removeGatewayRoute, upsertGatewayRoute, } from './gateway-route-store.js';
|
|
11
|
+
const log = createLogger('pi-custom-providers');
|
|
12
|
+
/**
|
|
13
|
+
* The host files a custom provider lives in: PI's own catalog and the gateway config it routes to.
|
|
14
|
+
* A change invalidates the provider discovery cache the same way a login does, so a provider defined
|
|
15
|
+
* from any surface reaches the next spawn without waiting out the cache TTL.
|
|
16
|
+
*/
|
|
17
|
+
export function defaultCustomProviderStores() {
|
|
18
|
+
return {
|
|
19
|
+
modelsPath: USER_PI_MODELS_PATH,
|
|
20
|
+
gatewayPath: GATEWAY_CONFIG_PATH,
|
|
21
|
+
gatewayUrl: GATEWAY_URL,
|
|
22
|
+
onChanged: () => piProviderDiscovery.refresh(),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function routeKeys(route) {
|
|
26
|
+
const keys = route?.keys;
|
|
27
|
+
if (!Array.isArray(keys))
|
|
28
|
+
return [];
|
|
29
|
+
return keys.filter((key) => typeof key === 'string' && key.length > 0);
|
|
30
|
+
}
|
|
31
|
+
function viewOf(name, entry, route) {
|
|
32
|
+
const view = {
|
|
33
|
+
name,
|
|
34
|
+
api: entry.api,
|
|
35
|
+
models: readEntryModels(entry),
|
|
36
|
+
upstreamUrl: typeof route?.base_url === 'string' ? route.base_url : null,
|
|
37
|
+
hasApiKey: routeKeys(route).length > 0,
|
|
38
|
+
routed: route !== null,
|
|
39
|
+
};
|
|
40
|
+
if (entry.headers && typeof entry.headers === 'object') {
|
|
41
|
+
view.headers = entry.headers;
|
|
42
|
+
}
|
|
43
|
+
if (entry.compat && typeof entry.compat === 'object') {
|
|
44
|
+
view.compat = entry.compat;
|
|
45
|
+
}
|
|
46
|
+
return view;
|
|
47
|
+
}
|
|
48
|
+
/** The route an entry's protocol places it on: mode is always the name, endpoint follows the api. */
|
|
49
|
+
function routeOf(stores, name, entry) {
|
|
50
|
+
const endpoint = gatewayEndpoint(entry.api, name);
|
|
51
|
+
return readGatewayRoute(stores.gatewayPath, endpoint, name);
|
|
52
|
+
}
|
|
53
|
+
export function listCustomProviders(stores) {
|
|
54
|
+
const entries = readCustomProviderEntries(stores.modelsPath);
|
|
55
|
+
return Object.entries(entries).map(([name, entry]) => (viewOf(name, entry, routeOf(stores, name, entry))));
|
|
56
|
+
}
|
|
57
|
+
export function getCustomProvider(stores, name) {
|
|
58
|
+
const entry = readCustomProviderEntries(stores.modelsPath)[name];
|
|
59
|
+
if (!entry)
|
|
60
|
+
return null;
|
|
61
|
+
return viewOf(name, entry, routeOf(stores, name, entry));
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Create or update a custom provider. The gateway route is written first — an unreferenced route is
|
|
65
|
+
* inert — and the PI catalog second, because that write is what makes the provider visible to PI.
|
|
66
|
+
* A failed catalog write therefore rolls the route back to its previous state.
|
|
67
|
+
*
|
|
68
|
+
* `apiKey` semantics: `undefined` keeps the stored upstream key (so an edit need not retype it),
|
|
69
|
+
* `''` clears it and lets the gateway pass the caller's own key through.
|
|
70
|
+
*/
|
|
71
|
+
export function upsertCustomProvider(stores, input) {
|
|
72
|
+
const provider = normalizeCustomProvider(input);
|
|
73
|
+
const issues = validateCustomProvider(provider, { reservedNames: stores.reservedNames });
|
|
74
|
+
if (issues.length > 0)
|
|
75
|
+
return { ok: false, errors: issues };
|
|
76
|
+
const { name } = provider;
|
|
77
|
+
const endpoint = gatewayEndpoint(provider.api, name);
|
|
78
|
+
const previousRoute = readGatewayRoute(stores.gatewayPath, endpoint, name);
|
|
79
|
+
const keys = input.apiKey === undefined ? routeKeys(previousRoute) : [input.apiKey].filter(Boolean);
|
|
80
|
+
try {
|
|
81
|
+
upsertGatewayRoute(stores.gatewayPath, {
|
|
82
|
+
endpoint,
|
|
83
|
+
mode: name,
|
|
84
|
+
base_url: provider.upstreamUrl,
|
|
85
|
+
auth_style: gatewayAuthStyle(provider.api),
|
|
86
|
+
keys,
|
|
87
|
+
passthrough: keys.length === 0,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
log.warn(`Failed to write the gateway route for '${name}': ${err.message}`);
|
|
92
|
+
return { ok: false, errors: ['write-failed'] };
|
|
93
|
+
}
|
|
94
|
+
const entry = buildModelsJsonEntry(provider, stores.gatewayUrl);
|
|
95
|
+
try {
|
|
96
|
+
upsertModelsJsonProvider(stores.modelsPath, name, entry);
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
log.warn(`Failed to write the PI catalog entry for '${name}': ${err.message}`);
|
|
100
|
+
restoreRoute(stores, endpoint, name, previousRoute);
|
|
101
|
+
return { ok: false, errors: ['write-failed'] };
|
|
102
|
+
}
|
|
103
|
+
stores.onChanged?.();
|
|
104
|
+
return {
|
|
105
|
+
ok: true,
|
|
106
|
+
provider: viewOf(name, entry, readGatewayRoute(stores.gatewayPath, endpoint, name)),
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function restoreRoute(stores, endpoint, name, previousRoute) {
|
|
110
|
+
try {
|
|
111
|
+
if (!previousRoute) {
|
|
112
|
+
removeGatewayRoute(stores.gatewayPath, endpoint, name);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
upsertGatewayRoute(stores.gatewayPath, {
|
|
116
|
+
endpoint,
|
|
117
|
+
mode: name,
|
|
118
|
+
base_url: String(previousRoute.base_url ?? ''),
|
|
119
|
+
auth_style: String(previousRoute.auth_style ?? 'bearer'),
|
|
120
|
+
keys: routeKeys(previousRoute),
|
|
121
|
+
passthrough: previousRoute.passthrough === true,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
log.warn(`Failed to roll the gateway route for '${name}' back: ${err.message}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Remove a custom provider from both files. Built-in overrides are not custom and are refused. */
|
|
129
|
+
export function removeCustomProvider(stores, name) {
|
|
130
|
+
const entry = readCustomProviderEntries(stores.modelsPath)[name];
|
|
131
|
+
if (!entry)
|
|
132
|
+
return { ok: false, errors: ['not-found'] };
|
|
133
|
+
try {
|
|
134
|
+
removeModelsJsonProvider(stores.modelsPath, name);
|
|
135
|
+
removeGatewayRoute(stores.gatewayPath, gatewayEndpoint(entry.api, name), name);
|
|
136
|
+
}
|
|
137
|
+
catch (err) {
|
|
138
|
+
log.warn(`Failed to remove custom provider '${name}': ${err.message}`);
|
|
139
|
+
return { ok: false, errors: ['write-failed'] };
|
|
140
|
+
}
|
|
141
|
+
stores.onChanged?.();
|
|
142
|
+
return { ok: true };
|
|
143
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The config file the running gateway watches; edits are hot-reloaded within ~1s. */
|
|
2
|
+
export declare const GATEWAY_CONFIG_PATH: string;
|
|
3
|
+
export interface GatewayRouteSpec {
|
|
4
|
+
/** Endpoint section (URL segment after the mode): `/m/<mode>/<endpoint>`. */
|
|
5
|
+
endpoint: string;
|
|
6
|
+
/** Mode name (billing/route selector). */
|
|
7
|
+
mode: string;
|
|
8
|
+
base_url: string;
|
|
9
|
+
auth_style: string;
|
|
10
|
+
/** Managed upstream keys. Empty means the gateway forwards the caller's own key. */
|
|
11
|
+
keys: string[];
|
|
12
|
+
passthrough: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** The stored route config, or null when that endpoint/mode pair is absent. */
|
|
15
|
+
export declare function readGatewayRoute(gatewayPath: string, endpoint: string, mode: string): Record<string, unknown> | null;
|
|
16
|
+
/**
|
|
17
|
+
* Write one route, replacing it if it already exists. This is the update path the discovery merge
|
|
18
|
+
* deliberately lacks — `mergeGatewayConfig` is add-only so it can never clobber hand-maintained
|
|
19
|
+
* routes, which also means it can never edit one.
|
|
20
|
+
*/
|
|
21
|
+
export declare function upsertGatewayRoute(gatewayPath: string, route: GatewayRouteSpec): void;
|
|
22
|
+
/** Remove one route, dropping the endpoint section once its last mode is gone. */
|
|
23
|
+
export declare function removeGatewayRoute(gatewayPath: string, endpoint: string, mode: string): boolean;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// input: a gateway.yaml path and one endpoint/mode route
|
|
2
|
+
// output: single-route reads, upserts and removals preserving every other route
|
|
3
|
+
// pos: Route-level editing of the aistatus gateway config
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'fs';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import * as os from 'os';
|
|
8
|
+
import { createLogger } from '../../core/log.js';
|
|
9
|
+
import { readGatewayYaml, serializeGatewayYaml, } from '../../core/gateway-generator.js';
|
|
10
|
+
const log = createLogger('pi-custom-providers');
|
|
11
|
+
/** The config file the running gateway watches; edits are hot-reloaded within ~1s. */
|
|
12
|
+
export const GATEWAY_CONFIG_PATH = path.join(os.homedir(), '.aistatus', 'gateway.yaml');
|
|
13
|
+
function readDocument(gatewayPath) {
|
|
14
|
+
const parsed = readGatewayYaml(gatewayPath);
|
|
15
|
+
if (!parsed)
|
|
16
|
+
return { top: {}, endpoints: {} };
|
|
17
|
+
return { top: { ...parsed.top }, endpoints: parsed.endpoints };
|
|
18
|
+
}
|
|
19
|
+
function writeDocument(gatewayPath, doc) {
|
|
20
|
+
mkdirSync(path.dirname(gatewayPath), { recursive: true });
|
|
21
|
+
if (existsSync(gatewayPath)) {
|
|
22
|
+
try {
|
|
23
|
+
copyFileSync(gatewayPath, `${gatewayPath}.bak`);
|
|
24
|
+
}
|
|
25
|
+
catch (err) {
|
|
26
|
+
log.warn(`Failed to back up ${gatewayPath}: ${err.message}`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const content = serializeGatewayYaml({
|
|
30
|
+
endpoints: doc.endpoints,
|
|
31
|
+
top: doc.top,
|
|
32
|
+
preservedCustom: [],
|
|
33
|
+
droppedFromDiscovery: [],
|
|
34
|
+
});
|
|
35
|
+
writeFileSync(gatewayPath, content, 'utf8');
|
|
36
|
+
}
|
|
37
|
+
/** The stored route config, or null when that endpoint/mode pair is absent. */
|
|
38
|
+
export function readGatewayRoute(gatewayPath, endpoint, mode) {
|
|
39
|
+
const { endpoints } = readDocument(gatewayPath);
|
|
40
|
+
return endpoints[endpoint]?.[mode] ?? null;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Write one route, replacing it if it already exists. This is the update path the discovery merge
|
|
44
|
+
* deliberately lacks — `mergeGatewayConfig` is add-only so it can never clobber hand-maintained
|
|
45
|
+
* routes, which also means it can never edit one.
|
|
46
|
+
*/
|
|
47
|
+
export function upsertGatewayRoute(gatewayPath, route) {
|
|
48
|
+
const doc = readDocument(gatewayPath);
|
|
49
|
+
const config = {
|
|
50
|
+
base_url: route.base_url,
|
|
51
|
+
auth_style: route.auth_style,
|
|
52
|
+
passthrough: route.passthrough,
|
|
53
|
+
};
|
|
54
|
+
if (route.keys.length > 0)
|
|
55
|
+
config.keys = [...route.keys];
|
|
56
|
+
doc.endpoints[route.endpoint] = { ...doc.endpoints[route.endpoint], [route.mode]: config };
|
|
57
|
+
doc.top.port ??= 9880;
|
|
58
|
+
doc.top.status_check ??= true;
|
|
59
|
+
// Never steal the active billing mode from an existing config; only seed it on a fresh file.
|
|
60
|
+
if (typeof doc.top.mode !== 'string' || doc.top.mode === '')
|
|
61
|
+
doc.top.mode = route.mode;
|
|
62
|
+
writeDocument(gatewayPath, doc);
|
|
63
|
+
}
|
|
64
|
+
/** Remove one route, dropping the endpoint section once its last mode is gone. */
|
|
65
|
+
export function removeGatewayRoute(gatewayPath, endpoint, mode) {
|
|
66
|
+
const doc = readDocument(gatewayPath);
|
|
67
|
+
const modes = doc.endpoints[endpoint];
|
|
68
|
+
if (!modes || !(mode in modes))
|
|
69
|
+
return false;
|
|
70
|
+
const remaining = { ...modes };
|
|
71
|
+
delete remaining[mode];
|
|
72
|
+
if (Object.keys(remaining).length === 0)
|
|
73
|
+
delete doc.endpoints[endpoint];
|
|
74
|
+
else
|
|
75
|
+
doc.endpoints[endpoint] = remaining;
|
|
76
|
+
writeDocument(gatewayPath, doc);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { CUSTOM_PROVIDER_APIS, CUSTOM_PROVIDER_NAME_RE, GATEWAY_PLACEHOLDER_KEY, customProviderBaseUrl, gatewayAuthStyle, gatewayEndpoint, validateCustomProvider, type CustomProviderApi, type CustomProviderInput, type CustomProviderIssue, type CustomProviderModelSpec, } from './custom-provider-model.js';
|
|
2
|
+
export { USER_PI_MODELS_PATH, isCustomProviderEntry, readCustomProviderEntries, readProvidersBlock, } from './models-json-store.js';
|
|
3
|
+
export { GATEWAY_CONFIG_PATH, type GatewayRouteSpec } from './gateway-route-store.js';
|
|
4
|
+
export { defaultCustomProviderStores, getCustomProvider, listCustomProviders, removeCustomProvider, upsertCustomProvider, type CustomProviderFailure, type CustomProviderRemoval, type CustomProviderResult, type CustomProviderStores, type CustomProviderView, } from './custom-provider-service.js';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// input: custom provider model, stores and service modules
|
|
2
|
+
// output: the public custom PI provider API
|
|
3
|
+
// pos: Entry point of the PI provider domain
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
export { CUSTOM_PROVIDER_APIS, CUSTOM_PROVIDER_NAME_RE, GATEWAY_PLACEHOLDER_KEY, customProviderBaseUrl, gatewayAuthStyle, gatewayEndpoint, validateCustomProvider, } from './custom-provider-model.js';
|
|
6
|
+
export { USER_PI_MODELS_PATH, isCustomProviderEntry, readCustomProviderEntries, readProvidersBlock, } from './models-json-store.js';
|
|
7
|
+
export { GATEWAY_CONFIG_PATH } from './gateway-route-store.js';
|
|
8
|
+
export { defaultCustomProviderStores, getCustomProvider, listCustomProviders, removeCustomProvider, upsertCustomProvider, } from './custom-provider-service.js';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { isCustomProviderEntry, readCustomProviderEntries, readProvidersBlock, } from '../../agent-adapter/pi/custom-catalog.js';
|
|
2
|
+
export { USER_PI_MODELS_PATH } from '../../agent-adapter/pi/agent-dir.js';
|
|
3
|
+
/** Write one provider block, replacing it wholesale and leaving every other key untouched. */
|
|
4
|
+
export declare function upsertModelsJsonProvider(modelsPath: string, name: string, entry: Record<string, unknown>): void;
|
|
5
|
+
/** Remove one provider block. Returns false when the name was not present. */
|
|
6
|
+
export declare function removeModelsJsonProvider(modelsPath: string, name: string): boolean;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// input: a PI models.json path and provider entries
|
|
2
|
+
// output: merge-preserving reads, writes and removals of provider blocks
|
|
3
|
+
// pos: Persistence of PI's user-owned provider catalog
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'fs';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import { createLogger } from '../../core/log.js';
|
|
8
|
+
// The catalog file format is the PI adapter's to know: it is the same file the adapter mirrors into
|
|
9
|
+
// the per-spawn catalog, so both sides must agree on what counts as a user-defined provider.
|
|
10
|
+
export { isCustomProviderEntry, readCustomProviderEntries, readProvidersBlock, } from '../../agent-adapter/pi/custom-catalog.js';
|
|
11
|
+
export { USER_PI_MODELS_PATH } from '../../agent-adapter/pi/agent-dir.js';
|
|
12
|
+
const log = createLogger('pi-custom-providers');
|
|
13
|
+
function readDocument(modelsPath) {
|
|
14
|
+
if (!existsSync(modelsPath))
|
|
15
|
+
return {};
|
|
16
|
+
try {
|
|
17
|
+
const parsed = JSON.parse(readFileSync(modelsPath, 'utf8'));
|
|
18
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
19
|
+
return {};
|
|
20
|
+
return parsed;
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
log.warn(`Unreadable PI models.json at ${modelsPath}: ${err.message}`);
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function providersOf(doc) {
|
|
28
|
+
const providers = doc.providers;
|
|
29
|
+
if (!providers || typeof providers !== 'object' || Array.isArray(providers))
|
|
30
|
+
return {};
|
|
31
|
+
return providers;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Replace the file with `doc`, keeping the previous content as `<path>.bak`. Written through a
|
|
35
|
+
* temp file + rename so a crash mid-write cannot leave PI with a truncated catalog.
|
|
36
|
+
*/
|
|
37
|
+
function writeDocument(modelsPath, doc) {
|
|
38
|
+
mkdirSync(path.dirname(modelsPath), { recursive: true });
|
|
39
|
+
if (existsSync(modelsPath)) {
|
|
40
|
+
try {
|
|
41
|
+
copyFileSync(modelsPath, `${modelsPath}.bak`);
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
log.warn(`Failed to back up ${modelsPath}: ${err.message}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const tmp = `${modelsPath}.tmp.${process.pid}.${Date.now()}`;
|
|
48
|
+
try {
|
|
49
|
+
writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
|
|
50
|
+
renameSync(tmp, modelsPath);
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
try {
|
|
54
|
+
if (existsSync(tmp))
|
|
55
|
+
unlinkSync(tmp);
|
|
56
|
+
}
|
|
57
|
+
catch { /* ignore */ }
|
|
58
|
+
throw err;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Write one provider block, replacing it wholesale and leaving every other key untouched. */
|
|
62
|
+
export function upsertModelsJsonProvider(modelsPath, name, entry) {
|
|
63
|
+
const doc = readDocument(modelsPath);
|
|
64
|
+
const providers = { ...providersOf(doc) };
|
|
65
|
+
providers[name] = entry;
|
|
66
|
+
writeDocument(modelsPath, { ...doc, providers });
|
|
67
|
+
}
|
|
68
|
+
/** Remove one provider block. Returns false when the name was not present. */
|
|
69
|
+
export function removeModelsJsonProvider(modelsPath, name) {
|
|
70
|
+
const doc = readDocument(modelsPath);
|
|
71
|
+
const providers = { ...providersOf(doc) };
|
|
72
|
+
if (!(name in providers))
|
|
73
|
+
return false;
|
|
74
|
+
delete providers[name];
|
|
75
|
+
writeDocument(modelsPath, { ...doc, providers });
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { PlatformAdapter, MessageRef } from '../../../platform/index.js';
|
|
2
2
|
import type { AgentResult } from '../../../core/types/agent-types.js';
|
|
3
3
|
export declare function buildProgressUpdater(adapter: PlatformAdapter, statusMsg: MessageRef, startTime: number, effectiveProfile: string, sessionName: string): (progress: Record<string, any> | null) => void;
|
|
4
|
-
export declare function finalizeThreadSuccess(adapter: PlatformAdapter, channel: string, statusMsg: MessageRef | null, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, sessionOrigin, statusPrefix }: {
|
|
4
|
+
export declare function finalizeThreadSuccess(adapter: PlatformAdapter, channel: string, statusMsg: MessageRef | null, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, sessionOrigin, statusPrefix, scheduleId }: {
|
|
5
5
|
startTime: number;
|
|
6
6
|
sessionName: string;
|
|
7
7
|
result: AgentResult | null;
|
|
@@ -15,4 +15,7 @@ export declare function finalizeThreadSuccess(adapter: PlatformAdapter, channel:
|
|
|
15
15
|
* a dispatch thread (origin 'thread') from a direct session. */
|
|
16
16
|
sessionOrigin: 'scheduled' | 'thread';
|
|
17
17
|
statusPrefix: string;
|
|
18
|
+
/** ScheduleTask.id whose fire produced this run (scheduled-task job). Persisted on the session
|
|
19
|
+
* record so the UI can group runs by schedule and render the trigger card. */
|
|
20
|
+
scheduleId?: string | null;
|
|
18
21
|
}): Promise<void>;
|
|
@@ -22,16 +22,25 @@ export function buildProgressUpdater(adapter, statusMsg, startTime, effectivePro
|
|
|
22
22
|
});
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
-
export async function finalizeThreadSuccess(adapter, channel, statusMsg, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, sessionOrigin, statusPrefix }) {
|
|
25
|
+
export async function finalizeThreadSuccess(adapter, channel, statusMsg, { startTime, sessionName, result, threadResult, project, trigger, label, sessionKind, sessionOrigin, statusPrefix, scheduleId }) {
|
|
26
26
|
const { elapsedStr, elapsedS } = computeElapsed(startTime);
|
|
27
27
|
if (result?.sessionId) {
|
|
28
|
+
// Register under the thread's last-step TRACK id: the conversation transcript and the
|
|
29
|
+
// session.message stream are keyed by it (threads/runner.ts step recorder), so registering
|
|
30
|
+
// the backend id instead yields a session with no transcript. The step registration for the
|
|
31
|
+
// same track id (origin 'thread') is intentionally overwritten — one record per run. The
|
|
32
|
+
// backend id is kept as backendSessionId, the resume target if the user replies to the run.
|
|
33
|
+
const steps = threadResult.thread?.steps ?? [];
|
|
34
|
+
const trackSessionId = steps.length > 0 ? steps[steps.length - 1]?.sessionId : null;
|
|
28
35
|
await sessionStore.registerSession(sessionName, {
|
|
29
|
-
sessionId: result.sessionId, channel,
|
|
36
|
+
sessionId: trackSessionId || result.sessionId, channel,
|
|
30
37
|
backend: getActiveBackend(), kind: sessionKind,
|
|
31
38
|
origin: sessionOrigin,
|
|
32
39
|
label,
|
|
33
40
|
profileName: getActiveProfile(channel),
|
|
34
41
|
projectId: project,
|
|
42
|
+
backendSessionId: result.sessionId,
|
|
43
|
+
scheduleId: scheduleId ?? null,
|
|
35
44
|
});
|
|
36
45
|
}
|
|
37
46
|
const metrics = formatMetricsSuffix({ costUsd: threadResult.totalCostUsd, numTurns: threadResult.totalNumTurns });
|
|
@@ -133,6 +133,7 @@ async function runScheduledTaskAsync({ normalizedMessage, message, projectId, sc
|
|
|
133
133
|
await finalizeThreadSuccess(adapter, projectId, statusMsg, {
|
|
134
134
|
startTime, sessionName, result, threadResult, project: projectId, trigger: 'scheduled',
|
|
135
135
|
label: message?.substring(0, 60) || null, sessionKind: 'scheduled', sessionOrigin: 'scheduled', statusPrefix: 'Done',
|
|
136
|
+
scheduleId: scheduleTaskId || null,
|
|
136
137
|
});
|
|
137
138
|
}
|
|
138
139
|
}
|