piroboros 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +39 -0
  4. package/README.md +140 -2
  5. package/agents/astrelia.md +31 -0
  6. package/agents/avaritia.md +31 -0
  7. package/agents/elaria.md +31 -0
  8. package/agents/nytheria.md +32 -0
  9. package/agents/raskreia.md +32 -0
  10. package/agents/samaela.md +40 -0
  11. package/agents/vaelia.md +35 -0
  12. package/agents/vesperia.md +45 -0
  13. package/bin/piroboros.mjs +17 -0
  14. package/dist/auth.js +105 -0
  15. package/dist/base.js +19 -0
  16. package/dist/chat/budget.js +87 -0
  17. package/dist/chat/compactloop.js +63 -0
  18. package/dist/chat/compactor.js +530 -0
  19. package/dist/chat/extension.js +36 -0
  20. package/dist/chat/hook.js +40 -0
  21. package/dist/chat/log.js +317 -0
  22. package/dist/chat/outbound.js +114 -0
  23. package/dist/chat/plan.js +64 -0
  24. package/dist/chat/prompt.js +115 -0
  25. package/dist/chat/status.js +37 -0
  26. package/dist/chat/stuck.js +83 -0
  27. package/dist/chat/tools.js +163 -0
  28. package/dist/chat/tree.js +73 -0
  29. package/dist/chat/turn.js +305 -0
  30. package/dist/chat/view.js +163 -0
  31. package/dist/conclave/agents.js +113 -0
  32. package/dist/conclave/pipeline.js +715 -0
  33. package/dist/conclave/report.js +43 -0
  34. package/dist/config.js +614 -0
  35. package/dist/durable.js +177 -0
  36. package/dist/guard.js +346 -0
  37. package/dist/lock.js +56 -0
  38. package/dist/main.js +348 -0
  39. package/dist/memory/akashic/api.js +121 -0
  40. package/dist/memory/akashic/confusables.js +41 -0
  41. package/dist/memory/akashic/scanner.js +67 -0
  42. package/dist/memory/akashic/snapshot.js +31 -0
  43. package/dist/memory/akashic/store.js +1254 -0
  44. package/dist/memory/akashic/tools.js +168 -0
  45. package/dist/memory/akashic/vault.js +984 -0
  46. package/dist/memory/host.js +124 -0
  47. package/dist/memory/mnemosia/adapters/akashic-memories.js +180 -0
  48. package/dist/memory/mnemosia/adapters/contract.js +219 -0
  49. package/dist/memory/mnemosia/agents.js +387 -0
  50. package/dist/memory/mnemosia/brief.js +890 -0
  51. package/dist/memory/mnemosia/claims.js +609 -0
  52. package/dist/memory/mnemosia/conflicts.js +769 -0
  53. package/dist/memory/mnemosia/escalation.js +257 -0
  54. package/dist/memory/mnemosia/feedback.js +108 -0
  55. package/dist/memory/mnemosia/filters.js +248 -0
  56. package/dist/memory/mnemosia/intent.js +221 -0
  57. package/dist/memory/mnemosia/open.js +34 -0
  58. package/dist/memory/mnemosia/orchestrator.js +926 -0
  59. package/dist/memory/mnemosia/plan.js +266 -0
  60. package/dist/memory/mnemosia/policy.js +426 -0
  61. package/dist/memory/mnemosia/progressive.js +550 -0
  62. package/dist/memory/mnemosia/provenance.js +458 -0
  63. package/dist/memory/mnemosia/qualifiers.js +428 -0
  64. package/dist/memory/mnemosia/rank.js +525 -0
  65. package/dist/memory/mnemosia/relations.js +156 -0
  66. package/dist/memory/mnemosia/requirements.js +138 -0
  67. package/dist/memory/mnemosia/rerank.js +253 -0
  68. package/dist/memory/mnemosia/retention.js +174 -0
  69. package/dist/memory/mnemosia/rollback.js +337 -0
  70. package/dist/memory/mnemosia/select.js +607 -0
  71. package/dist/memory/mnemosia/similarity.js +164 -0
  72. package/dist/memory/mnemosia/situation.js +251 -0
  73. package/dist/memory/mnemosia/task.js +418 -0
  74. package/dist/memory/mnemosia/temporal.js +136 -0
  75. package/dist/memory/mnemosia/tokens.js +66 -0
  76. package/dist/memory/mnemosia/tools.js +160 -0
  77. package/dist/memory/mnemosia/trace.js +306 -0
  78. package/dist/memory/mnemosia/types.js +298 -0
  79. package/dist/models.js +360 -0
  80. package/dist/paths.js +103 -0
  81. package/dist/redact.js +79 -0
  82. package/dist/runtime.js +378 -0
  83. package/dist/search-format.js +102 -0
  84. package/dist/search.js +351 -0
  85. package/dist/setup.js +366 -0
  86. package/dist/shell.js +110 -0
  87. package/dist/skills.js +311 -0
  88. package/dist/telemetry.js +84 -0
  89. package/dist/tui/app.js +1011 -0
  90. package/dist/tui/commands.js +121 -0
  91. package/dist/tui/keys.js +83 -0
  92. package/dist/tui/pane.js +387 -0
  93. package/dist/tui/panel.js +60 -0
  94. package/dist/tui/picker.js +25 -0
  95. package/dist/tui/sanitize.js +59 -0
  96. package/dist/tui/settings.js +198 -0
  97. package/dist/tui/setup.js +256 -0
  98. package/dist/tui/theme.js +26 -0
  99. package/dist/tui/thinking/parse.js +1094 -0
  100. package/dist/tui/thinking/select.js +86 -0
  101. package/dist/tui/thinking/state.js +137 -0
  102. package/dist/tui/thinking/types.js +3 -0
  103. package/dist/tui/thinking/view.js +74 -0
  104. package/dist/tui/viewport.js +208 -0
  105. package/dist/undo.js +258 -0
  106. package/dist/web.js +933 -0
  107. package/docs/conclave.md +21 -0
  108. package/docs/configuration.md +48 -0
  109. package/docs/development.md +25 -0
  110. package/docs/interface.md +33 -0
  111. package/docs/memory.md +11 -0
  112. package/docs/privacy.md +13 -0
  113. package/docs/tools.md +20 -0
  114. package/docs/web.md +38 -0
  115. package/models.json.example +34 -0
  116. package/package.json +76 -4
  117. package/settings.json.example +29 -0
  118. package/skills/conclave/SKILL.md +76 -0
@@ -0,0 +1,298 @@
1
+ // Ported from mnemosia/types.ts @ f0a8ad4 (MIT; see NOTICE)
2
+ /**
3
+ * Mnemosia's domain model: the vocabulary every later module is written against.
4
+ *
5
+ * Three rules shape this file.
6
+ *
7
+ * 1. Every persisted or exchanged object carries `schemaVersion: "mnemosia/<entity>@1"`, so a
8
+ * consumer never has to guess which generation of a shape it is holding (design §7).
9
+ * 2. The trust boundary is expressed in the type system, not in review comments. `SYSTEM_POLICY`
10
+ * and `AGENT_POLICY` are members of `Channel` but not of `AdapterChannel`, which is the only
11
+ * channel type an `ArtifactEnvelope` accepts — so an adapter emitting a policy channel is a
12
+ * compile error, not a runtime check that someone might forget to write (design §5).
13
+ * 3. Fields the spec asks for that this corpus cannot honestly supply are dropped *in writing*,
14
+ * with the reason, rather than stubbed with a placeholder value. See DROPPED_ARTIFACT_FIELDS.
15
+ *
16
+ * Nothing here imports from the foundations. Mnemosia's domain model must not be a re-export of
17
+ * AkashicForge's, or the adapters would stop being a boundary; the one exception the
18
+ * design allows is `MemoryRecord`, which stays AkashicForge's type and is imported where it is
19
+ * actually used (writes.ts, later) rather than mirrored here.
20
+ */
21
+ /* ------------------------------------------------------------------------------------------------
22
+ * Schema versions
23
+ * ---------------------------------------------------------------------------------------------- */
24
+ /** One place to bump. A shape change that a consumer must notice changes the string here. */
25
+ export const SCHEMA_VERSION = {
26
+ artifactEnvelope: "mnemosia/artifact-envelope@1",
27
+ claim: "mnemosia/claim@1",
28
+ evidence: "mnemosia/evidence@1",
29
+ contextItem: "mnemosia/context-item@1",
30
+ traceEvent: "mnemosia/trace-event@1",
31
+ plannedQuery: "mnemosia/planned-query@1",
32
+ taskAnalysis: "mnemosia/task-analysis@1",
33
+ scopeAuthorization: "mnemosia/scope-authorization@1",
34
+ retrievalPlan: "mnemosia/retrieval-plan@1",
35
+ /* --- Phase 5 ------------------------------------------------------------------------------- */
36
+ /** A recorded run's re-executable inputs (design §10's `replayOrchestration`). See `replay.ts`. */
37
+ replayCapsule: "mnemosia/replay-capsule@1",
38
+ /** The observable outcome of a run, comparable across policy versions. See `replay.ts`. */
39
+ runFingerprint: "mnemosia/run-fingerprint@1",
40
+ /** A run bound to a named policy-registry version rather than to the current one. See `rollback.ts`. */
41
+ policyPin: "mnemosia/policy-pin@1",
42
+ /** Spec §22's eight-field change record. See `rollback.ts`. */
43
+ policyChangePacket: "mnemosia/policy-change-packet@1",
44
+ /** The Phase 5 reranking activation switch, off by default. See `rerank.ts`. */
45
+ rerankGate: "mnemosia/rerank-gate@1",
46
+ /* --- Phase B: situation and intent ------------------------------------------------------- */
47
+ /** Spec Stage 2's tiered situation analysis. See `situation.ts`. */
48
+ situationContext: "mnemosia/situation-context@1",
49
+ /** Spec Stage 3's bounded intent hypothesis set. See `intent.ts`. */
50
+ intentHypothesisSet: "mnemosia/intent-hypothesis-set@1",
51
+ /** Knowledge requirements derived from situation + intent. See `requirements.ts`. */
52
+ knowledgeRequirements: "mnemosia/knowledge-requirements@1",
53
+ /* --- Phase D: graph and specialist reuse -------------------------------------------------- */
54
+ /** Per-claim producing/requesting seat lineage recorded on every run's trace. See `trace.ts`. */
55
+ agentLineage: "mnemosia/agent-lineage@1",
56
+ };
57
+ /* ------------------------------------------------------------------------------------------------
58
+ * Channels — the trust boundary, enforced structurally
59
+ * ---------------------------------------------------------------------------------------------- */
60
+ /**
61
+ * Channels that originate inside the process and carry instruction authority. They are produced by
62
+ * Mnemosia, the host, or the live user turn. Retrieved bytes may never be labelled with one of
63
+ * these: that relabelling is precisely how a poisoned memory would acquire the authority to be
64
+ * obeyed instead of merely read.
65
+ *
66
+ * `USER_DIRECTIVE` sits here rather than with the adapter channels because it means *the user is
67
+ * saying this now*. A stored user message that Mnemosia retrieves is evidence about what a user
68
+ * once said, which is `RETRIEVED_EVIDENCE`, and the distinction is the whole point of the split.
69
+ */
70
+ export const PRIVILEGED_CHANNELS = ["SYSTEM_POLICY", "AGENT_POLICY", "USER_DIRECTIVE"];
71
+ /**
72
+ * The complete set of channels a source adapter is permitted to emit. `ArtifactEnvelope.channel`
73
+ * is typed as this, not as `Channel`, which is what makes the §5 guarantee mechanical.
74
+ */
75
+ export const ADAPTER_CHANNELS = ["RETRIEVED_EVIDENCE", "TOOL_OBSERVATION", "EXTERNAL_CONTENT"];
76
+ /** The six-way enum required on every ContextItem (design §12). */
77
+ export const CHANNELS = [...PRIVILEGED_CHANNELS, ...ADAPTER_CHANNELS];
78
+ /**
79
+ * A total, stable string identity for a scope.
80
+ *
81
+ * Three modules need to compare scopes for exact equality — claims.ts folds it into `claimId` so
82
+ * that the same sentence in two projects cannot collapse into one claim, task.ts builds the
83
+ * authorized set out of it, and filters.ts tests membership in that set. All three must agree
84
+ * byte-for-byte or the isolation invariant (spec §4, "project … scopes must not leak into one
85
+ * another") would hold in one module and not the next, so the definition lives here, once.
86
+ *
87
+ * The Phase 2 qualifiers are included even though nothing populates them yet: adding them later
88
+ * would silently change every `claimId` ever recorded, which is a schema bump, not a patch.
89
+ */
90
+ export function scopeKey(scope) {
91
+ return [scope.level, scope.project ?? "", scope.branch ?? "", scope.environment ?? ""].join("\u001f");
92
+ }
93
+ /* ------------------------------------------------------------------------------------------------
94
+ * ArtifactEnvelope (design §7, spec §10)
95
+ * ---------------------------------------------------------------------------------------------- */
96
+ /**
97
+ * Spec §10 fields Mnemosia deliberately does not carry. Recorded here, and not silently omitted,
98
+ * because "the field is absent" and "the field was considered and rejected for this reason" are
99
+ * different engineering claims and only the second one is honest.
100
+ *
101
+ * This constant is exported so a future reviewer diffing the spec against the code finds the
102
+ * answer in the code rather than in a document that may have drifted.
103
+ */
104
+ export const DROPPED_ARTIFACT_FIELDS = {
105
+ /**
106
+ * spec §10 `tenant` / `user`. Dropped: single user, single machine, and neither foundation has a
107
+ * tenancy column. Synthesizing a constant tenant id would create the appearance of isolation
108
+ * machinery that does not exist, which is worse than its absence (design §2, §3 PROHIBITED).
109
+ */
110
+ tenant: "no tenancy exists in either foundation; a constant value would fake isolation",
111
+ user: "single-user machine; AkashicForge stores no actor on a memory row, only on a mutation",
112
+ /**
113
+ * spec §10 `access_policy`. Dropped: there is no per-record ACL anywhere in the corpus. Access
114
+ * control here is the lifecycle state plus the scope filter, and both are already modelled.
115
+ */
116
+ access_policy: "no per-record ACL exists; lifecycle state and scope are the real access controls",
117
+ /**
118
+ * spec §10 `repository_scope`. Dropped as a separate field: AkashicForge's `project` already IS
119
+ * the repository, stored as a normalized absolute path. Two fields holding the same string would
120
+ * be two things to keep in sync and one more chance to disagree.
121
+ */
122
+ repository_scope: "identical to scope.project, which is already a normalized absolute repo path",
123
+ };
124
+ /** Which source, and which of its surfaces, produced an envelope. */
125
+ export const SOURCE_ID = {
126
+ akashicMemories: "akashic-memories",
127
+ };
128
+ /** What kind of thing the artifact is, independent of which provider stored it. */
129
+ export const SOURCE_TYPES = ["curated_memory", "conversation_message", "tool_output", "compaction_summary"];
130
+ /**
131
+ * `verified` requires a check that actually ran and passed. `unverified` means no integrity claim
132
+ * is available for this source — it is not a synonym for "probably fine". `failed` is hard-filtered
133
+ * before ranking and can never be resurrected by relevance (design §12).
134
+ */
135
+ export const INTEGRITY_STATUSES = ["verified", "unverified", "failed"];
136
+ /**
137
+ * Provider-neutral by construction. "fts5" and "bm25" are implementation
138
+ * details of a source; the domain only needs to know how the artifact was found, because that is
139
+ * what ranking and the audit trail reason about.
140
+ */
141
+ export const RETRIEVAL_METHODS = ["lexical_search", "recency_scan", "id_lookup", "structured_enumeration"];
142
+ /* ------------------------------------------------------------------------------------------------
143
+ * Claim / Evidence (design §7, spec §5.2–5.3)
144
+ * ---------------------------------------------------------------------------------------------- */
145
+ export const CLAIM_TYPES = ["FACT", "OBSERVATION", "DECISION", "CONSTRAINT", "PLAN", "PREFERENCE", "PROCEDURE", "HYPOTHESIS"];
146
+ export const CERTAINTIES = ["CONFIRMED", "PROBABLE", "SPECULATIVE", "UNKNOWN"];
147
+ export const EVIDENCE_RELATIONS = ["SUPPORTS", "CONTRADICTS", "SUPERSEDES", "QUALIFIES", "TEMPORAL_BOUND"];
148
+ /** AkashicForge's lifecycle vocabulary, mirrored because a Claim may carry one and `null` otherwise. */
149
+ export const LIFECYCLE_STATES = ["PROPOSED", "ACTIVE", "DISPUTED", "SUPERSEDED", "EXPIRED", "REVOKED", "QUARANTINED", "DELETED"];
150
+ /* ------------------------------------------------------------------------------------------------
151
+ * ContextItem (design §7, spec §5.5)
152
+ * ---------------------------------------------------------------------------------------------- */
153
+ /** The ten kinds spec §5.5 requires a ContextItem to identify itself as. */
154
+ export const CONTEXT_ITEM_KINDS = [
155
+ "confirmed_fact",
156
+ "user_claim",
157
+ "tool_observation",
158
+ "inference",
159
+ "plan",
160
+ "preference",
161
+ "hypothesis",
162
+ "constraint",
163
+ "conflict",
164
+ "recommendation",
165
+ ];
166
+ /** Briefing sections, in the order §10 assigns them soft budget shares. */
167
+ export const BRIEFING_SECTIONS = [
168
+ "confirmed_facts",
169
+ "previous_decisions",
170
+ "current_state",
171
+ "constraints",
172
+ "known_failures_or_rejected",
173
+ "preferences",
174
+ "conflicts",
175
+ "open_tasks",
176
+ "uncertainties_or_gaps",
177
+ ];
178
+ /* ------------------------------------------------------------------------------------------------
179
+ * Error taxonomy
180
+ * ---------------------------------------------------------------------------------------------- */
181
+ /**
182
+ * The five codes every provider failure is translated into (design §13). The class that carries
183
+ * them lives in adapters/contract.ts, next to the translation function, because the codes are
184
+ * domain vocabulary but the translation is adapter machinery.
185
+ */
186
+ export const ADAPTER_ERROR_CODES = ["unavailable", "timeout", "auth", "schema", "internal"];
187
+ /* ------------------------------------------------------------------------------------------------
188
+ * Retrieval state machine and audit vocabulary (design §6, §14)
189
+ * ---------------------------------------------------------------------------------------------- */
190
+ export const RETRIEVAL_STATES = [
191
+ "RECEIVE_REQUEST",
192
+ "ANALYZE_TASK",
193
+ "AUTHORIZE_SCOPE",
194
+ "PLAN_RETRIEVAL",
195
+ "EXECUTE_SOURCE_QUERIES",
196
+ "NORMALIZE_ARTIFACTS",
197
+ "EXTRACT_OR_RESOLVE_CLAIMS",
198
+ "DEDUPLICATE",
199
+ "APPLY_HARD_FILTERS",
200
+ "SCORE_CANDIDATES",
201
+ "DETECT_CONFLICTS",
202
+ "RESOLVE_OR_ESCALATE",
203
+ "SELECT_CONTEXT_SET",
204
+ "REQUEST_COMPRESSION",
205
+ "ASSEMBLE_BRIEFING",
206
+ "VALIDATE_BRIEFING",
207
+ "DELIVER",
208
+ "COLLECT_FEEDBACK",
209
+ ];
210
+ /** Terminal outcomes that end a run before DELIVER (design §6). */
211
+ export const EARLY_EXITS = [
212
+ "NO_MEMORY_REQUIRED",
213
+ "CLARIFICATION_REQUIRED",
214
+ "INSUFFICIENT_AUTHORIZATION",
215
+ "RETRIEVAL_UNAVAILABLE",
216
+ "PARTIAL_BRIEFING",
217
+ "INSUFFICIENT_INFORMATION",
218
+ ];
219
+ /**
220
+ * Design §14's event vocabulary, plus one added in Phase 2 and one added in Phase 3.
221
+ *
222
+ * `provenance` carries the shape of the claim graph — edge counts by relation, grounding states,
223
+ * the graph-distance histogram, the supersession chains. It is not a `transition` (the graph is
224
+ * built inside `APPLY_HARD_FILTERS`, which already emits its own) and it is not a `score` (nothing
225
+ * is weighted yet). Spec §12 requires that every input to a ranking decision be recoverable from the
226
+ * trace, and Phase 2's `evidence_strength` reads three quantities — distance, independent groups,
227
+ * contradictions — that exist only in this structure. Folding them into the per-candidate `score`
228
+ * payload would repeat the whole graph once per claim; giving them an event kind records it once.
229
+ *
230
+ * `mutation` is Phase 3's, and it is the one event kind that describes something Mnemosia did to a
231
+ * store rather than something she concluded about one. Every gate refusal, approval requirement,
232
+ * pre-flight lifecycle check, submission, replay, version conflict, rebase, retry and ledger row
233
+ * lands here. It is not an `outcome` — that kind terminates a *retrieval* run and there is exactly
234
+ * one per run, whereas a single recommendation can produce a refusal, a conflict, a rebase and a
235
+ * commit — and it is not a `transition`, which is design §6's retrieval state machine. Design §19
236
+ * item 2 makes autonomous mutation a human approval item; an approval item whose exercise is not
237
+ * separately identifiable in the audit log cannot be audited for compliance afterwards.
238
+ */
239
+ export const TRACE_EVENT_KINDS = [
240
+ "transition",
241
+ "adapter_result",
242
+ "claim_extracted",
243
+ "filter_reject",
244
+ "provenance",
245
+ "score",
246
+ "conflict",
247
+ /**
248
+ * Phase 4. Every escalation routed at `RESOLVE_OR_ESCALATE`, with the rule that fired, the target
249
+ * seat and whether it was dispatched or delivered to the requester as its own work item.
250
+ *
251
+ * It is not a `conflict` — that kind carries what `detectConflicts` *concluded* about the claims,
252
+ * and the whole Phase 2 discipline preserved here is that concluding and routing are different
253
+ * acts by different modules. It is not a `transition` either: `RESOLVE_OR_ESCALATE` already emits
254
+ * one, and an access escalation has no conflict behind it at all, so folding the two would make a
255
+ * replay unable to tell a run that escalated nothing from a run whose escalations were all
256
+ * conflict-derived.
257
+ */
258
+ "escalation",
259
+ /**
260
+ * Phase 5. One event per invocation of the model-assisted reranker (spec §12), carrying the
261
+ * reranker version, the gate that admitted it, the attempt count, the status, and every id the
262
+ * model returned that the deterministic stage had not admitted.
263
+ *
264
+ * It is not a `score` — that kind carries the *deterministic* signals and weights §12 requires to
265
+ * be recoverable, and a reranking decision has neither. A replay that could not tell "this order
266
+ * came from the six weights" from "this order came from a model" would make the whole
267
+ * deterministic-fallback guarantee unauditable. It is emitted whether the reranker ran or not, so
268
+ * "the gate was closed" and "no reranker was configured" are distinguishable facts in the log
269
+ * rather than a shared silence.
270
+ */
271
+ "rerank",
272
+ /**
273
+ * Phase B. One event per situation/intent/requirements stage between ANALYZE_TASK and
274
+ * PLAN_RETRIEVAL, carrying the tier counts, the bounded hypothesis set with its clarification
275
+ * recommendation, and the derived knowledge requirements. They are not `transition`s: they do
276
+ * not move the retrieval state machine, they annotate it — a replay must be able to tell "the
277
+ * plan was built from task analysis alone (Phase A)" from "the plan was built with situation
278
+ * and intent vocabulary (Phase B)".
279
+ */
280
+ "situation_analysis",
281
+ "intent_hypotheses",
282
+ "knowledge_requirements",
283
+ "selection",
284
+ "exclusion",
285
+ "validation",
286
+ "mutation",
287
+ /**
288
+ * Phase D. One event per run, emitted after APPLY_HARD_FILTERS has fixed the accepted claim set,
289
+ * carrying per-claim cross-agent lineage: which seat produced each accepted claim (when one is
290
+ * attributable via a `specialist-finding:<seat>` tag) and which seat requested the run, plus the
291
+ * always-numeric `joinCoverage` share of attributed claims. It is not a `provenance` — that kind
292
+ * carries graph statistics over claims and artifacts, and a seat attribution is a fact about
293
+ * *agents*, not about evidence structure. A replay that could not tell "no seat was attributable"
294
+ * from "lineage was never recorded" would make the D3 contract unauditable.
295
+ */
296
+ "agent_lineage",
297
+ "outcome",
298
+ ];
package/dist/models.js ADDED
@@ -0,0 +1,360 @@
1
+ import { createProvider, envApiKeyAuth, InMemoryCredentialStore, StringEnum } from "@earendil-works/pi-ai";
2
+ import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
3
+ import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
4
+ import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
5
+ import { builtinModels } from "@earendil-works/pi-ai/providers/all";
6
+ import { estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
7
+ import { ConfigError, homePaths, isModelRef, readJsonFile, splitModelRef } from "./config.js";
8
+ /** A string enum schema without anyOf, which every provider accepts. Re-exported for the memory tools (D18 seam). */
9
+ export { StringEnum };
10
+ /** Estimated tokens of one message, including a system message's tool declarations. */
11
+ export const estimateTokens = (message) => estimateMessageTokens(message);
12
+ /**
13
+ * Rearrange the cache marks of an Anthropic Messages payload. pi-ai marks the identity block, the system text, the
14
+ * last tool and the last user block. Marks go on the system text (which covers the tools, since tools come first),
15
+ * the last full view block, and the last user block: three of the four allowed. The block that holds the closing
16
+ * `</chat>` stays unmarked, because it changes whenever a line is appended. Does nothing when no mark is present
17
+ * (cache retention off).
18
+ */
19
+ export function markCache(payload) {
20
+ const p = payload;
21
+ if (p === null || typeof p !== "object")
22
+ return;
23
+ const system = Array.isArray(p.system) ? p.system : [];
24
+ const template = [...system].reverse().find((block) => block.cache_control !== undefined)?.cache_control;
25
+ if (template === undefined)
26
+ return;
27
+ system.slice(0, -1).forEach((block) => { delete block.cache_control; });
28
+ if (Array.isArray(p.tools))
29
+ for (const tool of p.tools)
30
+ delete tool.cache_control;
31
+ const content = p.messages?.[0]?.content;
32
+ if (!Array.isArray(content))
33
+ return;
34
+ const tail = content.findIndex((block) => block.type === "text" && typeof block.text === "string" && block.text.endsWith("</chat>"));
35
+ if (tail > 0)
36
+ content[tail - 1].cache_control = template;
37
+ }
38
+ /** Wrap a provider so its Anthropic Messages requests go through markCache. Other providers are returned as they are. */
39
+ function withCacheMarks(provider) {
40
+ if (!provider.getModels().some((model) => model.api === "anthropic-messages"))
41
+ return provider;
42
+ const wrap = (options) => ({
43
+ ...options,
44
+ onPayload: async (payload, model) => {
45
+ const replaced = await options?.onPayload?.(payload, model);
46
+ const next = replaced ?? payload;
47
+ if (model.api === "anthropic-messages")
48
+ markCache(next);
49
+ return next;
50
+ },
51
+ });
52
+ return { ...provider, stream: (model, context, options) => provider.stream(model, context, wrap(options)), streamSimple: (model, context, options) => provider.streamSimple(model, context, wrap(options)) };
53
+ }
54
+ /**
55
+ * Every environment variable a built-in provider's API-key auth looks up. pi-ai does not export its env-key
56
+ * table, so each provider's own `auth.apiKey.resolve` runs once against a recording context.
57
+ */
58
+ async function builtinEnvNames() {
59
+ const names = new Set();
60
+ const noop = new Proxy(() => undefined, { get: (_t, key) => (key === "env" ? async (name) => { names.add(name); return undefined; } : async () => undefined) });
61
+ for (const provider of builtinModels({ credentials: new InMemoryCredentialStore() }).getProviders()) {
62
+ await provider.auth.apiKey?.resolve({ ctx: noop, credential: undefined, signal: new AbortController().signal }).catch(() => undefined);
63
+ }
64
+ return names;
65
+ }
66
+ const BUILTIN_ENV_NAMES = await builtinEnvNames();
67
+ /** All built-in providers, with credentials resolved through the given store. */
68
+ export function createAppModels(credentials, extra = []) {
69
+ const models = builtinModels({ credentials });
70
+ for (const provider of models.getProviders())
71
+ models.setProvider(withCacheMarks(provider));
72
+ for (const provider of extra)
73
+ models.setProvider(provider);
74
+ return models;
75
+ }
76
+ /** `<ID>_API_KEY` with every character outside A-Z and 0-9 replaced by an underscore. Provider ids never contain `/`. */
77
+ export function apiKeyEnvName(providerId) {
78
+ return `${providerId.toUpperCase().replace(/[^A-Z0-9]/gu, "_")}_API_KEY`;
79
+ }
80
+ /* --- context rule (D24) -------------------------------------------------------------------------------- */
81
+ export const MAIN_MIN_TURN_TOKENS = 72_000;
82
+ export const COMPACTOR_MIN_TOKENS = 24_000;
83
+ const SYSTEM_RESERVE = 2_000;
84
+ /**
85
+ * Main and member models need contextWindow - maxTokens - 2,000 >= 72,000. The compactor needs
86
+ * contextWindow - maxTokens >= 24,000. A model that fails is listed as disabled, with the reason.
87
+ */
88
+ export function contextCheck(model, role) {
89
+ if (role === "compactor") {
90
+ const room = model.contextWindow - model.maxTokens;
91
+ return room >= COMPACTOR_MIN_TOKENS ? { ok: true } : { ok: false, reason: `context window ${model.contextWindow} minus max output ${model.maxTokens} leaves ${room} tokens; the compactor needs at least ${COMPACTOR_MIN_TOKENS}` };
92
+ }
93
+ const room = model.contextWindow - model.maxTokens - SYSTEM_RESERVE;
94
+ return room >= MAIN_MIN_TURN_TOKENS ? { ok: true } : { ok: false, reason: `context window ${model.contextWindow} minus max output ${model.maxTokens} minus ${SYSTEM_RESERVE} leaves ${room} tokens; at least ${MAIN_MIN_TURN_TOKENS} are required` };
95
+ }
96
+ /* --- custom providers (models.json) --------------------------------------------------------------------- */
97
+ export const CUSTOM_APIS = ["openai-completions", "openai-responses", "anthropic-messages"];
98
+ export class ModelsFileError extends ConfigError {
99
+ issues;
100
+ constructor(issues) {
101
+ super("models_invalid", `models.json is invalid:\n${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`);
102
+ this.issues = issues;
103
+ }
104
+ }
105
+ const THINKING_MAP_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
106
+ const isObj = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
107
+ /**
108
+ * Why a base URL breaks the convention for its API, or undefined when it is fine. `warn` problems do not stop the
109
+ * file from loading: an OpenAI-style server may use another path, for example Gemini's /v1beta/openai.
110
+ */
111
+ function baseUrlProblem(api, raw) {
112
+ let url;
113
+ try {
114
+ url = new URL(raw);
115
+ }
116
+ catch {
117
+ return { code: "base_url", message: `${JSON.stringify(raw)} is not a valid URL` };
118
+ }
119
+ if (url.protocol !== "https:" && url.protocol !== "http:")
120
+ return { code: "base_url", message: "must start with https:// or http://" };
121
+ if (url.username !== "" || url.password !== "")
122
+ return { code: "base_url", message: "must not contain a user name or password; use the API key instead" };
123
+ const path = url.pathname.replace(/\/+$/u, "");
124
+ if (api === "anthropic-messages" && path.endsWith("/v1"))
125
+ return { code: "base_url_anthropic_v1", message: `anthropic-messages needs the host root, because the client adds /v1/messages itself; remove the trailing /v1 (use ${url.origin}${path.slice(0, -3)})` };
126
+ if (api !== "anthropic-messages" && !path.endsWith("/v1"))
127
+ return { code: "base_url_openai_v1", warn: true, message: `${api} base URLs usually end in /v1, for example ${url.origin}/v1; check that the server expects this path` };
128
+ return undefined;
129
+ }
130
+ /**
131
+ * Validate models.json: `{ "providers": { "<id>": { "name"?, "models": [ ... ] } } }`. Every problem is
132
+ * collected and names its path. `reserved` holds ids that custom providers may not take (the built-in ones).
133
+ * Problems that do not stop the load are appended to `warnings` when given.
134
+ */
135
+ export function validateModelsFile(value, reserved = new Set(), warnings) {
136
+ const issues = [];
137
+ const add = (path, code, message) => { issues.push({ path, code, message }); };
138
+ const unknown = (obj, allowed, path) => {
139
+ for (const key of Object.keys(obj))
140
+ if (!allowed.includes(key))
141
+ add(`${path}.${key}`, "unknown_key", "unknown key");
142
+ };
143
+ if (!isObj(value))
144
+ throw new ModelsFileError([{ path: "(file)", code: "shape", message: "must hold a JSON object" }]);
145
+ for (const key of Object.keys(value))
146
+ if (key !== "providers")
147
+ add(key, "unknown_key", "unknown key");
148
+ if (!isObj(value.providers))
149
+ add("providers", "shape", 'must be an object keyed by provider id, for example {"providers":{"my-llm":{"models":[...]}}}');
150
+ const out = {};
151
+ const envNames = new Map();
152
+ // Ids compare case-insensitively, and a custom id may not read a built-in provider's key variable either.
153
+ const reservedLower = new Set([...reserved].map((r) => r.toLowerCase()));
154
+ const reservedEnv = new Set([...reserved].map(apiKeyEnvName).concat([...BUILTIN_ENV_NAMES]));
155
+ for (const [id, provider] of Object.entries(isObj(value.providers) ? value.providers : {})) {
156
+ const at = `providers.${id}`;
157
+ if (id === "" || id.includes("/")) {
158
+ add(at, "provider_id", 'a provider id must not be empty or contain "/"');
159
+ continue;
160
+ }
161
+ const env = apiKeyEnvName(id);
162
+ if (reservedLower.has(id.toLowerCase()) || reservedEnv.has(env)) {
163
+ add(at, "provider_reserved", "this id belongs to a built-in provider or reads its key variable; choose another");
164
+ continue;
165
+ }
166
+ const clash = envNames.get(env);
167
+ if (clash !== undefined) {
168
+ add(at, "env_name_clash", `${clash} and ${id} would both read ${env}; rename one`);
169
+ continue;
170
+ }
171
+ envNames.set(env, id);
172
+ if (!isObj(provider)) {
173
+ add(at, "shape", "must be an object");
174
+ continue;
175
+ }
176
+ unknown(provider, ["name", "models"], at);
177
+ if (provider.name !== undefined && (typeof provider.name !== "string" || provider.name === ""))
178
+ add(`${at}.name`, "model_field", "must be a non-empty string");
179
+ if (!Array.isArray(provider.models) || provider.models.length === 0) {
180
+ add(`${at}.models`, "shape", "must be a non-empty array");
181
+ continue;
182
+ }
183
+ const models = [];
184
+ const seen = new Set();
185
+ provider.models.forEach((raw, index) => {
186
+ const m = `${at}.models[${index}]`;
187
+ if (!isObj(raw)) {
188
+ add(m, "shape", "must be an object");
189
+ return;
190
+ }
191
+ unknown(raw, ["id", "name", "api", "baseUrl", "reasoning", "input", "cost", "contextWindow", "maxTokens", "compat", "thinkingLevelMap"], m);
192
+ let ok = true;
193
+ const bad = (field, message) => { add(`${m}.${field}`, "model_field", message); ok = false; };
194
+ if (typeof raw.id !== "string" || raw.id === "")
195
+ bad("id", "is required and must be a non-empty string");
196
+ else if (seen.has(raw.id))
197
+ bad("id", `duplicate model id ${raw.id}`);
198
+ else
199
+ seen.add(raw.id);
200
+ if (raw.name !== undefined && (typeof raw.name !== "string" || raw.name === ""))
201
+ bad("name", "must be a non-empty string");
202
+ if (!CUSTOM_APIS.includes(raw.api))
203
+ bad("api", `is required and must be one of ${CUSTOM_APIS.join(", ")}`);
204
+ if (typeof raw.baseUrl !== "string")
205
+ bad("baseUrl", "is required and must be a string");
206
+ else if (CUSTOM_APIS.includes(raw.api)) {
207
+ const problem = baseUrlProblem(raw.api, raw.baseUrl);
208
+ if (problem?.warn)
209
+ warnings?.push({ path: `${m}.baseUrl`, code: problem.code, message: problem.message });
210
+ else if (problem !== undefined) {
211
+ add(`${m}.baseUrl`, problem.code, problem.message);
212
+ ok = false;
213
+ }
214
+ }
215
+ if (raw.reasoning !== undefined && typeof raw.reasoning !== "boolean")
216
+ bad("reasoning", "must be true or false");
217
+ // ponytail: compat keys are not checked one by one, because the set belongs to the pi-ai version; pi-ai ignores unknown ones.
218
+ if (raw.compat !== undefined && !isObj(raw.compat))
219
+ bad("compat", "must be an object");
220
+ const map = raw.thinkingLevelMap;
221
+ if (map !== undefined && !(isObj(map) && Object.entries(map).every(([level, value]) => THINKING_MAP_LEVELS.includes(level) && (value === null || (typeof value === "string" && value !== "")))))
222
+ bad("thinkingLevelMap", `must map ${THINKING_MAP_LEVELS.join(", ")} to a non-empty string or null`);
223
+ if (map !== undefined && raw.reasoning !== true)
224
+ bad("thinkingLevelMap", 'needs "reasoning": true, because the map is only used for reasoning models');
225
+ if (raw.input !== undefined && !(Array.isArray(raw.input) && raw.input.length > 0 && raw.input.every((kind) => kind === "text" || kind === "image")))
226
+ bad("input", 'must be a non-empty array of "text" and "image"');
227
+ const cost = raw.cost;
228
+ if (cost !== undefined && !(isObj(cost) && ["input", "output", "cacheRead", "cacheWrite"].every((k) => typeof cost[k] === "number" && cost[k] >= 0) && Object.keys(cost).length === 4))
229
+ bad("cost", "must be an object with the non-negative numbers input, output, cacheRead and cacheWrite");
230
+ const posInt = (field) => {
231
+ const v = raw[field];
232
+ if (typeof v === "number" && Number.isInteger(v) && v > 0)
233
+ return v;
234
+ bad(field, "is required and must be a positive integer");
235
+ return undefined;
236
+ };
237
+ const contextWindow = posInt("contextWindow");
238
+ const maxTokens = posInt("maxTokens");
239
+ if (contextWindow !== undefined && maxTokens !== undefined) {
240
+ const room = contextWindow - maxTokens;
241
+ if (room < COMPACTOR_MIN_TOKENS) {
242
+ add(`${m}.contextWindow`, "context_too_small", `${contextWindow} minus maxTokens ${maxTokens} leaves ${room} tokens; every role needs at least ${COMPACTOR_MIN_TOKENS}, and the main model needs ${MAIN_MIN_TURN_TOKENS + SYSTEM_RESERVE}`);
243
+ ok = false;
244
+ }
245
+ }
246
+ if (!ok)
247
+ return;
248
+ models.push({
249
+ id: raw.id,
250
+ name: raw.name ?? raw.id,
251
+ api: raw.api,
252
+ baseUrl: raw.baseUrl,
253
+ reasoning: raw.reasoning ?? false,
254
+ input: raw.input ?? ["text"],
255
+ cost: raw.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
256
+ contextWindow: contextWindow,
257
+ maxTokens: maxTokens,
258
+ ...(raw.compat === undefined ? {} : { compat: raw.compat }),
259
+ ...(map === undefined ? {} : { thinkingLevelMap: map }),
260
+ });
261
+ });
262
+ out[id] = { name: provider.name ?? id, models };
263
+ }
264
+ if (issues.length > 0)
265
+ throw new ModelsFileError(issues);
266
+ return out;
267
+ }
268
+ function buildProvider(id, def) {
269
+ return withCacheMarks(createProvider({
270
+ id,
271
+ name: def.name,
272
+ auth: { apiKey: envApiKeyAuth(`${def.name} API key`, [apiKeyEnvName(id)]) },
273
+ models: def.models.map((m) => ({ ...m, provider: id })),
274
+ api: { "openai-completions": openAICompletionsApi(), "openai-responses": openAIResponsesApi(), "anthropic-messages": anthropicMessagesApi() },
275
+ }));
276
+ }
277
+ /** The shortest valid models.json, shown by setup. A test validates it. */
278
+ export const MODELS_JSON_EXAMPLE = JSON.stringify({
279
+ providers: { "my-llm": { models: [{ id: "chat", api: "openai-completions", baseUrl: "https://llm.example.com/v1", contextWindow: 200000, maxTokens: 16000 }] } },
280
+ }, null, 2);
281
+ export function customProviders(models, home) {
282
+ let registered = new Set();
283
+ const load = () => {
284
+ const builtIn = new Set(models.getProviders().map((p) => p.id).filter((id) => !registered.has(id)));
285
+ const raw = readJsonFile(homePaths(home).models);
286
+ const issues = [];
287
+ const defs = validateModelsFile(raw === undefined ? { providers: {} } : raw, builtIn, issues);
288
+ const warnings = issues.map((issue) => `models.json ${issue.path}: ${issue.message}`);
289
+ return { defs, ids: Object.keys(defs), ...(warnings.length > 0 ? { warnings } : {}) };
290
+ };
291
+ const failure = (error) => ({ ok: false, error: error instanceof Error ? error.message : String(error) });
292
+ return {
293
+ check() {
294
+ try {
295
+ const { defs: _defs, ...rest } = load();
296
+ return { ok: true, ...rest };
297
+ }
298
+ catch (error) {
299
+ return failure(error);
300
+ }
301
+ },
302
+ reload() {
303
+ try {
304
+ const { defs, ...rest } = load();
305
+ const next = Object.entries(defs).map(([id, def]) => buildProvider(id, def));
306
+ for (const id of registered)
307
+ if (!(id in defs))
308
+ models.deleteProvider(id);
309
+ for (const provider of next)
310
+ models.setProvider(provider);
311
+ registered = new Set(Object.keys(defs));
312
+ return { ok: true, ...rest };
313
+ }
314
+ catch (error) {
315
+ return failure(error);
316
+ }
317
+ },
318
+ };
319
+ }
320
+ /** Providers the wizard can offer: OAuth providers, and api-key providers that can ask for a key or already resolve. */
321
+ export function providerChoices(models) {
322
+ const out = [];
323
+ for (const provider of models.getProviders()) {
324
+ const methods = [];
325
+ const oauth = provider.auth.oauth;
326
+ const apiKey = provider.auth.apiKey;
327
+ const both = oauth !== undefined && apiKey !== undefined;
328
+ if (oauth !== undefined)
329
+ methods.push({ type: "oauth", label: `${provider.name} (sign in)`, interactive: true });
330
+ if (apiKey !== undefined)
331
+ methods.push({ type: "api_key", label: both ? `${provider.name} (API key)` : provider.name, interactive: apiKey.login !== undefined });
332
+ if (methods.length > 0)
333
+ out.push({ id: provider.id, name: provider.name, methods });
334
+ }
335
+ return out.sort((a, b) => a.name.localeCompare(b.name));
336
+ }
337
+ /** True when the provider's auth resolves now (a stored credential or ambient credentials). */
338
+ export async function hasAuth(models, providerId) {
339
+ try {
340
+ const result = await models.getAuth(providerId);
341
+ return result !== undefined;
342
+ }
343
+ catch {
344
+ return false;
345
+ }
346
+ }
347
+ export function modelChoices(models, providerId, role) {
348
+ return models.getModels(providerId).map((model) => ({ ref: `${providerId}/${model.id}`, model, check: contextCheck(model, role) }));
349
+ }
350
+ export function resolveModel(models, ref) {
351
+ if (!isModelRef(ref))
352
+ return undefined;
353
+ const { provider, modelId } = splitModelRef(ref);
354
+ return models.getModel(provider, modelId);
355
+ }
356
+ /** Run a login and persist the resulting credential through the store. */
357
+ export async function loginAndStore(models, store, providerId, type, interaction, deviceId) {
358
+ const credential = await models.login(providerId, type, interaction, { getDeviceId: deviceId, agentName: "piroboros" });
359
+ await store.modify(providerId, async () => credential);
360
+ }