@wraith-ai/core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,160 @@
1
+ import { extraRootOf, isInsideWorkspace, workspaceRelative, type ExtraRoot } from "../paths";
2
+ import { analyzeCommand } from "./command";
3
+ import { describeRule, ruleMatches, type RuleTarget } from "./match";
4
+ import type {
5
+ PermissionDecision,
6
+ PermissionPolicy,
7
+ PermissionPolicyInput,
8
+ PermissionQuery,
9
+ PermissionVerdict,
10
+ } from "./types";
11
+
12
+ /**
13
+ * Every matching rule is consulted and the strictest verdict wins: deny beats
14
+ * ask beats allow. Order and specificity do not matter, so a deny rule cannot
15
+ * carry an allowlist exception.
16
+ *
17
+ * `mode: "ask"` allows `safe` and `read` calls and stops `write`, `exec` and
18
+ * `network` for a human. `workspaceWrites: "allow"` lets `write` through inside
19
+ * the workspace. It cannot reach outside the workspace: the path check runs
20
+ * before this one. `yolo` allows any call that no rule matches.
21
+ */
22
+
23
+ export interface PolicyOptions {
24
+ /** Claimed paths are matched relative to this. */
25
+ cwd: string;
26
+ /**
27
+ * Directories outside the workspace the host opened. Path rules never reach
28
+ * them; tool-wide rules and the mode still do.
29
+ */
30
+ roots?: readonly ExtraRoot[];
31
+ }
32
+
33
+ const STRICTNESS: Record<PermissionDecision, number> = { allow: 0, ask: 1, deny: 2 };
34
+
35
+ export function createPermissionPolicy(
36
+ config: PermissionPolicyInput,
37
+ options: PolicyOptions,
38
+ ): PermissionPolicy {
39
+ const decideOne = (target: PlacedTarget, query: PermissionQuery): PermissionVerdict => {
40
+ let strictest: PermissionVerdict | undefined;
41
+
42
+ for (const rule of config.rules) {
43
+ if (!ruleMatches(rule, target)) continue;
44
+ const verdict: PermissionVerdict = {
45
+ decision: rule.decision,
46
+ rule,
47
+ reason: `${describeRule(rule)} says ${rule.decision}`,
48
+ };
49
+ if (strictest === undefined || STRICTNESS[verdict.decision] > STRICTNESS[strictest.decision]) {
50
+ strictest = verdict;
51
+ }
52
+ }
53
+
54
+ return strictest ?? defaultVerdict(config, query, target);
55
+ };
56
+
57
+ return {
58
+ decide(query: PermissionQuery): PermissionVerdict {
59
+ // Not overridable by a rule: rules are relative to the workspace, so `**`
60
+ // would otherwise reach the whole disk.
61
+ const inside: string[] = [];
62
+ let inRoot = false;
63
+
64
+ for (const path of query.claim.paths ?? []) {
65
+ if (isInsideWorkspace(options.cwd, path)) {
66
+ inside.push(path);
67
+ continue;
68
+ }
69
+ const root = extraRootOf(options, path);
70
+ if (root === undefined) {
71
+ return { decision: "deny", reason: `"${path}" is outside the workspace` };
72
+ }
73
+ if (query.danger === "write" && root.access === "read") {
74
+ return { decision: "deny", reason: `"${path}" is read-only` };
75
+ }
76
+ inRoot = true;
77
+ }
78
+
79
+ // Root paths are left out of the target, so no path rule can match them.
80
+ const target = toTarget(query, inside, inRoot, options.cwd);
81
+ if (query.claim.command === undefined) return decideOne(target, query);
82
+
83
+ // A shell line is several commands wearing one coat. Judge each of them.
84
+ const { segments, concerns } = analyzeCommand(query.claim.command);
85
+ let strictest: PermissionVerdict | undefined;
86
+
87
+ for (const segment of segments) {
88
+ const verdict = decideOne({ ...target, command: segment }, query);
89
+ if (strictest === undefined || STRICTNESS[verdict.decision] > STRICTNESS[strictest.decision]) {
90
+ strictest = verdict;
91
+ }
92
+ }
93
+
94
+ const combined = strictest ?? defaultVerdict(config, query, target);
95
+
96
+ // A rule may not approve what the text does not reveal. Concerns never
97
+ // harden the mode: with no rule matched, `yolo` still allows.
98
+ if (combined.decision === "allow" && combined.rule !== undefined && concerns.length > 0) {
99
+ return {
100
+ decision: "ask",
101
+ rule: combined.rule,
102
+ reason: `${combined.reason}, but the command uses ${concerns.join(", ")}`,
103
+ };
104
+ }
105
+
106
+ return combined;
107
+ },
108
+ };
109
+ }
110
+
111
+ /** A rule target plus where the claimed paths fell, which only the default needs. */
112
+ interface PlacedTarget extends RuleTarget {
113
+ /** Something was claimed in a root the host opened, and it may be written. */
114
+ inRoot: boolean;
115
+ }
116
+
117
+ function toTarget(
118
+ query: PermissionQuery,
119
+ inside: readonly string[],
120
+ inRoot: boolean,
121
+ cwd: string,
122
+ ): PlacedTarget {
123
+ const target: PlacedTarget = {
124
+ toolName: query.toolName,
125
+ paths: inside.map((path) => workspaceRelative(cwd, path)),
126
+ inRoot,
127
+ };
128
+ if (query.claim.command !== undefined) target.command = query.claim.command;
129
+ if (query.claim.url !== undefined) target.url = query.claim.url;
130
+ return target;
131
+ }
132
+
133
+ function defaultVerdict(
134
+ config: PermissionPolicyInput,
135
+ query: PermissionQuery,
136
+ target: PlacedTarget,
137
+ ): PermissionVerdict {
138
+ if (config.mode === "yolo") return { decision: "allow", reason: "permission mode is yolo" };
139
+ if (config.mode === "deny") return { decision: "deny", reason: "permission mode is deny" };
140
+
141
+ if (query.danger === "safe" || query.danger === "read") {
142
+ return { decision: "allow", reason: `${query.danger} calls do not need approval` };
143
+ }
144
+
145
+ if (query.danger === "write") {
146
+ // A root that takes writes is scratch space, never the project.
147
+ if (target.inRoot && target.paths.length === 0) {
148
+ return { decision: "allow", reason: "writes to the scratch directory are allowed" };
149
+ }
150
+
151
+ // Reached only for paths already known to be inside the workspace, after
152
+ // the escape check above, which this cannot override. A write that declares
153
+ // no path still asks: where it lands has not been established.
154
+ if (config.workspaceWrites === "allow" && target.paths.length > 0) {
155
+ return { decision: "allow", reason: "writes inside the workspace are allowed" };
156
+ }
157
+ }
158
+
159
+ return { decision: "ask", reason: `${query.danger} calls need approval` };
160
+ }
@@ -0,0 +1,159 @@
1
+ import type { ModelMessage } from "../agent/messages";
2
+ import type { Usage } from "../events/types";
3
+ import type {
4
+ PermissionDecision,
5
+ PermissionMode,
6
+ PermissionPolicyConfig,
7
+ PermissionRule,
8
+ WorkspaceWrites,
9
+ } from "../config/schema";
10
+ import type { FileChange } from "../tools/change";
11
+ import type { DangerLevel, ResourceClaim } from "../tools/define";
12
+
13
+ /**
14
+ * The tool declares what it does (`danger`) and what it touches (`resources`);
15
+ * the policy turns that into allow, ask or deny; the UI only asks the human,
16
+ * through `ApprovalHandler`.
17
+ *
18
+ * Rule shapes live in the zod config schema and are re-exported here, so
19
+ * permission code does not import from `config/`.
20
+ */
21
+
22
+ export type {
23
+ PermissionDecision,
24
+ PermissionMode,
25
+ PermissionPolicyConfig,
26
+ PermissionRule,
27
+ WorkspaceWrites,
28
+ };
29
+
30
+ /**
31
+ * The values, not just the types: the session log reads these back from disk
32
+ * and has to reject an author it does not know rather than guess one. A second
33
+ * hand-written list in the reader is how "denied" ends up attributed to a user
34
+ * who was never asked.
35
+ */
36
+ export const APPROVAL_DECISIONS = ["approved", "denied"] as const;
37
+
38
+ export type ApprovalDecision = (typeof APPROVAL_DECISIONS)[number];
39
+
40
+ /**
41
+ * Who answered. The registry cannot tell a human at a terminal from the
42
+ * classifier, so the handler says which it is; otherwise the log records
43
+ * "denied" without recording who decided it.
44
+ */
45
+ export const APPROVAL_DECIDED_BY = ["user", "classifier", "unattended"] as const;
46
+
47
+ export type ApprovalDecidedBy = (typeof APPROVAL_DECIDED_BY)[number];
48
+
49
+ export interface ApprovalResolution {
50
+ decision: ApprovalDecision;
51
+ /** Defaults to "user": a handler that answers without saying is a person. */
52
+ decidedBy?: ApprovalDecidedBy;
53
+ /** Shown and logged. A refusal the model cannot explain is one it repeats. */
54
+ reason?: string;
55
+ /** What answering cost, for handlers that call a model to answer. */
56
+ usage?: Usage;
57
+ }
58
+
59
+ export interface ApprovalRequest {
60
+ approvalId: string;
61
+ toolCallId: string;
62
+ toolName: string;
63
+ input: unknown;
64
+ danger: DangerLevel;
65
+ claim: ResourceClaim;
66
+ /** One line describing the call, ready to show. */
67
+ summary: string;
68
+ /** What the call would change on disk, when the tool can say before it runs. */
69
+ change?: FileChange;
70
+ /**
71
+ * The rule the question comes from, when one matched. An `ask` somebody wrote
72
+ * down means a person answers, so a handler that is not one stays out.
73
+ */
74
+ rule?: PermissionRule;
75
+ }
76
+
77
+ /**
78
+ * What the handler can learn about the conversation it is answering for. The
79
+ * classifier needs it and nothing else does: a single command is not decidable
80
+ * on its own. The session log does not hold the turn in progress; it is written
81
+ * only when the turn ends.
82
+ */
83
+ export interface ApprovalContext {
84
+ sessionId: string;
85
+ runId: string;
86
+ /** Conversation so far, including the turn in progress. */
87
+ messages: readonly ModelMessage[];
88
+ }
89
+
90
+ /**
91
+ * The promise may stay pending until a person answers.
92
+ *
93
+ * A bare decision stays valid; `ApprovalResolution` is for handlers that can
94
+ * say why. `undefined` means "I am not answering", which is not refusing: the
95
+ * registry treats it as no handler, so the refusal is recorded as `unattended`,
96
+ * never as the user's. Composing several handlers, and what silence means among
97
+ * them, is the host's.
98
+ *
99
+ * `context` is added to the signature, not substituted: one-argument handlers
100
+ * still compile, since TypeScript allows fewer parameters.
101
+ */
102
+ export type ApprovalHandler = (
103
+ request: ApprovalRequest,
104
+ context: ApprovalContext,
105
+ ) => Promise<ApprovalDecision | ApprovalResolution | undefined>;
106
+
107
+ /** The settled answer, with the fields the event and the log both carry. */
108
+ export interface ApprovalOutcome {
109
+ decision: ApprovalDecision;
110
+ decidedBy: ApprovalDecidedBy;
111
+ reason?: string;
112
+ usage?: Usage;
113
+ }
114
+
115
+ /** Normalises either handler return shape into the one the log records. */
116
+ export function resolveApproval(
117
+ answer: ApprovalDecision | ApprovalResolution,
118
+ fallback: ApprovalDecidedBy = "user",
119
+ ): ApprovalOutcome {
120
+ if (typeof answer === "string") return { decision: answer, decidedBy: fallback };
121
+ const outcome: ApprovalOutcome = {
122
+ decision: answer.decision,
123
+ decidedBy: answer.decidedBy ?? fallback,
124
+ };
125
+ if (answer.reason !== undefined) outcome.reason = answer.reason;
126
+ if (answer.usage !== undefined) outcome.usage = answer.usage;
127
+ return outcome;
128
+ }
129
+
130
+ export interface PermissionQuery {
131
+ toolName: string;
132
+ danger: DangerLevel;
133
+ claim: ResourceClaim;
134
+ }
135
+
136
+ export interface PermissionVerdict {
137
+ decision: PermissionDecision;
138
+ /** The rule that decided, when one did. */
139
+ rule?: PermissionRule;
140
+ /** Why, in a form a person can read. */
141
+ reason: string;
142
+ }
143
+
144
+ export interface PermissionPolicy {
145
+ decide(query: PermissionQuery): PermissionVerdict;
146
+ }
147
+
148
+ /**
149
+ * What building a policy needs, narrower than the parsed config.
150
+ *
151
+ * `classifier` is absent: it belongs to the approval layer, and a policy that
152
+ * could see it could obey it. `workspaceWrites` is optional, so callers written
153
+ * before it still compile.
154
+ */
155
+ export interface PermissionPolicyInput {
156
+ mode: PermissionMode;
157
+ workspaceWrites?: WorkspaceWrites;
158
+ rules: readonly PermissionRule[];
159
+ }
@@ -0,0 +1,107 @@
1
+ import type { Config } from "../config/schema";
2
+
3
+ /**
4
+ * Prompt caching, as far as the core is concerned.
5
+ *
6
+ * The core carries an intent: cache this conversation, keep it warm this long,
7
+ * and the session it belongs to. It never carries a vendor field name; the
8
+ * factory translates the intent into those.
9
+ *
10
+ * Every step resends the whole history, so without caching each turn pays
11
+ * again for the same prefix.
12
+ */
13
+
14
+ export type CacheTtl = "5m" | "1h" | "24h";
15
+
16
+ /**
17
+ * Whether an endpoint understands OpenAI's prompt-cache fields. Only the
18
+ * openai-compatible factory reads it, because only there is the vendor unknown.
19
+ */
20
+ export type CacheDialect = "openai" | "none";
21
+
22
+ export interface CacheOptions {
23
+ enabled: boolean;
24
+ ttl: CacheTtl;
25
+ /** Routing hint, one per session: same key, same machine, warm cache. */
26
+ key?: string;
27
+ dialect?: CacheDialect;
28
+ }
29
+
30
+ /** What a vendor can do about caching — for diagnostics, never for gating. */
31
+ export type CacheSupport = "automatic" | "signal" | "breakpoints" | "unknown";
32
+
33
+ /**
34
+ * On by default, and an hour by default: between two steps of a run stands a
35
+ * human approving a tool call, and five minutes of that is a cache that
36
+ * expired for full price.
37
+ */
38
+ export const DEFAULT_CACHE_OPTIONS: CacheOptions = { enabled: true, ttl: "1h" };
39
+
40
+ /** Global settings, overridden by whatever the provider entry says. */
41
+ export function cacheOptionsFor(
42
+ config: Config,
43
+ providerName: string,
44
+ key?: string,
45
+ ): CacheOptions {
46
+ const global = config.cache;
47
+ const local = config.providers[providerName]?.cache;
48
+
49
+ const options: CacheOptions = {
50
+ enabled: local?.enabled ?? global.enabled,
51
+ ttl: local?.ttl ?? global.ttl,
52
+ };
53
+
54
+ if (local?.dialect !== undefined) options.dialect = local.dialect;
55
+ return withCacheKey(options, key);
56
+ }
57
+
58
+ /**
59
+ * A key longer than a provider accepts is left out: the provider rejects or
60
+ * truncates it, and either way two sessions can collide.
61
+ */
62
+ export function withCacheKey(cache: CacheOptions, key: string | undefined): CacheOptions {
63
+ return key !== undefined && key !== "" && key.length <= 256 ? { ...cache, key } : cache;
64
+ }
65
+
66
+ export type ProviderOptionsMap = Record<string, Record<string, unknown>>;
67
+
68
+ /**
69
+ * What one request carries to stay on its cache. Sent per call, never kept on
70
+ * the model, so one model object serves every session.
71
+ */
72
+ export interface RequestFields {
73
+ providerOptions?: ProviderOptionsMap;
74
+ headers?: Record<string, string>;
75
+ }
76
+
77
+ /** A call's settings with its cache fields folded in; the profile's own win. */
78
+ export function withRequestFields<T extends { providerOptions?: ProviderOptionsMap }>(
79
+ settings: T,
80
+ fields: RequestFields,
81
+ ): T & { headers?: Record<string, string> } {
82
+ const providerOptions = mergeProviderOptions(fields.providerOptions, settings.providerOptions);
83
+ return {
84
+ ...settings,
85
+ ...(providerOptions === undefined ? {} : { providerOptions }),
86
+ ...(fields.headers === undefined ? {} : { headers: fields.headers }),
87
+ };
88
+ }
89
+
90
+ /**
91
+ * Merges what we derived from cache settings with what the user wrote in a
92
+ * model profile. The profile wins: an explicit setting in config must never be
93
+ * silently overwritten by a default we chose.
94
+ */
95
+ export function mergeProviderOptions(
96
+ derived: ProviderOptionsMap | undefined,
97
+ fromProfile: ProviderOptionsMap | undefined,
98
+ ): ProviderOptionsMap | undefined {
99
+ if (derived === undefined) return fromProfile;
100
+ if (fromProfile === undefined) return derived;
101
+
102
+ const merged: ProviderOptionsMap = { ...derived };
103
+ for (const [namespace, values] of Object.entries(fromProfile)) {
104
+ merged[namespace] = { ...merged[namespace], ...values };
105
+ }
106
+ return merged;
107
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * What a given model can actually be asked to do.
3
+ *
4
+ * Capability data may improve error messages but must never gate a call: the
5
+ * default answers "I don't know" to everything, and the provider decides.
6
+ *
7
+ * `models-dev.ts` implements this interface against models.dev. Everything
8
+ * above reads through it, so the source in use changes nothing for callers.
9
+ */
10
+
11
+ export interface ModelInfo {
12
+ /** What people call the model, when the catalog says. */
13
+ name?: string;
14
+ /**
15
+ * Whether the catalog says it reasons. `false` is an answer, absent is not:
16
+ * `/effort` tells the two apart and blocks neither.
17
+ */
18
+ reasoning?: boolean;
19
+ /** "2026-07-14". Newest first is the order of an empty search. */
20
+ releaseDate?: string;
21
+ status?: "alpha" | "beta" | "deprecated";
22
+ contextLimit?: number;
23
+ outputLimit?: number;
24
+ /** Effort levels this model accepts. Vocabularies differ per vendor. */
25
+ reasoningEfforts?: string[];
26
+ supportsTemperature?: boolean;
27
+ supportsToolCall?: boolean;
28
+ /**
29
+ * What the model takes in, as models.dev names it: "text", "image", "pdf",
30
+ * "audio", "video". Absent is "not known", never "text only".
31
+ */
32
+ input?: string[];
33
+ inputPricePerMillion?: number;
34
+ outputPricePerMillion?: number;
35
+ /**
36
+ * Cache rates, when the catalog publishes them. Missing ones are derived from
37
+ * the input rate; a bill computed from them is always labelled an estimate.
38
+ */
39
+ cacheReadPricePerMillion?: number;
40
+ cacheWritePricePerMillion?: number;
41
+ }
42
+
43
+ export interface ModelListing {
44
+ id: string;
45
+ info: ModelInfo;
46
+ }
47
+
48
+ /**
49
+ * Keyed by catalog table, not by provider: which table a provider reads is
50
+ * `catalogView`'s answer.
51
+ */
52
+ export interface ModelCapabilities {
53
+ lookup(table: string, modelId: string): ModelInfo | null;
54
+ /**
55
+ * What the catalog lists in a table, for a model picker. Never more than
56
+ * `lookup` finds: each row must resolve through `lookup`. Empty means "no
57
+ * list", never "no models"; a provider the catalog does not know still
58
+ * takes any id typed by hand.
59
+ */
60
+ list(table: string): readonly ModelListing[];
61
+ }
62
+
63
+ /** Knows nothing, blocks nothing: the default source. */
64
+ export const permissiveCapabilities: ModelCapabilities = {
65
+ lookup: () => null,
66
+ list: () => [],
67
+ };
68
+
69
+ /** Builds a capability source from a plain table, for tests and for config. */
70
+ export function capabilitiesFromTable(
71
+ table: Record<string, Record<string, ModelInfo>>,
72
+ ): ModelCapabilities {
73
+ return {
74
+ lookup: (name, modelId) => table[name]?.[modelId] ?? null,
75
+ list: (name) => Object.entries(table[name] ?? {}).map(([id, info]) => ({ id, info })),
76
+ };
77
+ }
@@ -0,0 +1,91 @@
1
+ import type { ModelCapabilities, ModelInfo, ModelListing } from "./capabilities";
2
+
3
+ /**
4
+ * How one provider type reads the capability catalog. The catalog itself only
5
+ * knows models.dev tables; what a backend serves differently from its table is
6
+ * the provider's knowledge, so it lives here and not in the catalog.
7
+ */
8
+
9
+ export interface CatalogView {
10
+ /** The models.dev table this provider reads. */
11
+ table: string;
12
+ /** Rows the backend really serves, when the table lists more. */
13
+ only?: ReadonlySet<string>;
14
+ /** This backend's own window for a model, where the table's is not it. */
15
+ contextLimit?: (modelId: string) => number;
16
+ }
17
+
18
+ /**
19
+ * The models the Codex backend on a ChatGPT subscription serves. The `openai`
20
+ * table lists everything the API does, and the backend refuses most of it. The
21
+ * catalog cannot tell the two apart, so this set is kept by hand.
22
+ */
23
+ export const CODEX_MODELS: ReadonlySet<string> = new Set([
24
+ "gpt-6.1-sol",
25
+ "gpt-6-astra",
26
+ "gpt-6-sol",
27
+ "gpt-6-luna",
28
+ "gpt-5.6-sol",
29
+ "gpt-5.6-luna",
30
+ "gpt-5.6-terra",
31
+ "gpt-5.5",
32
+ "gpt-5.4",
33
+ "gpt-5.4-mini",
34
+ "gpt-5.3-codex-spark",
35
+ ]);
36
+
37
+ /**
38
+ * The input window that backend gives on a ChatGPT login. The `openai` table
39
+ * lists the API's, several times larger, so these are kept by hand too.
40
+ */
41
+ const CODEX_WINDOW = 272_000;
42
+ const CODEX_WINDOWS: Readonly<Record<string, number>> = {
43
+ "gpt-6.1-sol": 500_000,
44
+ "gpt-5.3-codex-spark": 128_000,
45
+ };
46
+
47
+ const VIEWS_BY_TYPE: Readonly<Record<string, CatalogView>> = {
48
+ openrouter: { table: "openrouter" },
49
+ "openai-codex": {
50
+ table: "openai",
51
+ only: CODEX_MODELS,
52
+ contextLimit: (modelId) => CODEX_WINDOWS[modelId] ?? CODEX_WINDOW,
53
+ },
54
+ };
55
+
56
+ /**
57
+ * The table follows the provider's **type**, not its name: `codex` is what a
58
+ * config calls it and `openai` is what models.dev does. Any other type keeps
59
+ * the name, which is what a gateway called `groq` or `deepinfra` needs.
60
+ */
61
+ export function catalogView(providerName: string, type?: string): CatalogView {
62
+ return (type === undefined ? undefined : VIEWS_BY_TYPE[type]) ?? { table: providerName };
63
+ }
64
+
65
+ /** The tables a config's providers read, sorted and without repeats. */
66
+ export function catalogTables(providers: Readonly<Record<string, { readonly type: string }>>): string[] {
67
+ return [
68
+ ...new Set(Object.entries(providers).map(([name, provider]) => catalogView(name, provider.type).table)),
69
+ ].sort();
70
+ }
71
+
72
+ function seenThrough(view: CatalogView, modelId: string, info: ModelInfo): ModelInfo {
73
+ return view.contextLimit === undefined ? info : { ...info, contextLimit: view.contextLimit(modelId) };
74
+ }
75
+
76
+ export function lookupInView(
77
+ capabilities: ModelCapabilities,
78
+ view: CatalogView,
79
+ modelId: string,
80
+ ): ModelInfo | null {
81
+ const info = capabilities.lookup(view.table, modelId);
82
+ return info === null ? null : seenThrough(view, modelId, info);
83
+ }
84
+
85
+ /** What a picker offers for this provider; every row resolves through `lookupInView`. */
86
+ export function listInView(capabilities: ModelCapabilities, view: CatalogView): readonly ModelListing[] {
87
+ return capabilities
88
+ .list(view.table)
89
+ .filter(({ id }) => view.only === undefined || view.only.has(id))
90
+ .map(({ id, info }) => ({ id, info: seenThrough(view, id, info) }));
91
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Model discovery.
3
+ *
4
+ * Which models exist is the provider's business, so the core never carries a
5
+ * list — it asks. Both OpenRouter and every OpenAI-compatible endpoint expose
6
+ * `GET /models`; the shapes differ only in how much detail they add.
7
+ *
8
+ * Parsing is a pure function, so it is testable without a network call.
9
+ */
10
+
11
+ export interface CatalogModel {
12
+ id: string;
13
+ name?: string;
14
+ contextLength?: number;
15
+ /** USD per million input tokens, when the provider reports pricing. */
16
+ inputPricePerMillion?: number;
17
+ outputPricePerMillion?: number;
18
+ }
19
+
20
+ function asRecord(value: unknown): Record<string, unknown> | null {
21
+ return typeof value === "object" && value !== null && !Array.isArray(value)
22
+ ? (value as Record<string, unknown>)
23
+ : null;
24
+ }
25
+
26
+ function asFiniteNumber(value: unknown): number | undefined {
27
+ const parsed = typeof value === "string" ? Number(value) : value;
28
+ return typeof parsed === "number" && Number.isFinite(parsed) ? parsed : undefined;
29
+ }
30
+
31
+ function perMillion(value: unknown): number | undefined {
32
+ const parsed = asFiniteNumber(value);
33
+ return parsed === undefined ? undefined : parsed * 1_000_000;
34
+ }
35
+
36
+ /** Accepts both the OpenRouter payload and a bare OpenAI-compatible one. */
37
+ export function parseModelCatalog(payload: unknown): CatalogModel[] {
38
+ const root = asRecord(payload);
39
+ const list = Array.isArray(payload) ? payload : Array.isArray(root?.data) ? root.data : [];
40
+
41
+ const models: CatalogModel[] = [];
42
+ for (const raw of list) {
43
+ const entry = asRecord(raw);
44
+ const id = entry?.id;
45
+ if (typeof id !== "string" || id === "") continue;
46
+
47
+ const pricing = asRecord(entry?.pricing);
48
+ const model: CatalogModel = { id };
49
+
50
+ if (typeof entry?.name === "string") model.name = entry.name;
51
+
52
+ const context = asFiniteNumber(entry?.context_length ?? asRecord(entry?.top_provider)?.context_length);
53
+ if (context !== undefined) model.contextLength = context;
54
+
55
+ const input = perMillion(pricing?.prompt ?? pricing?.input);
56
+ if (input !== undefined) model.inputPricePerMillion = input;
57
+
58
+ const output = perMillion(pricing?.completion ?? pricing?.output);
59
+ if (output !== undefined) model.outputPricePerMillion = output;
60
+
61
+ models.push(model);
62
+ }
63
+
64
+ return models.sort((left, right) => left.id.localeCompare(right.id));
65
+ }