Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

protocol.ts

257 lines9.3 KB

1import type { ProviderApprovalDecision } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3​
4const NonEmptyString = Schema.String.check(Schema.isMinLength(1));
5​
6const MuseUsage = Schema.Struct({
7 inputTokens: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
8 outputTokens: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
9 cachedTokens: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
10 reasoningTokens: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
11 cacheReadTokens: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
12 cacheWriteTokens: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
13});
14​
15export const MuseItem = Schema.Struct({
16 entryId: Schema.optional(Schema.String),
17 children: Schema.optional(
18 Schema.Array(
19 Schema.Struct({
20 childId: NonEmptyString,
21 attempt: Schema.Int,
22 status: Schema.String,
23 label: Schema.optional(Schema.String),
24 terminal: Schema.optional(Schema.String),
25 durationMs: Schema.optional(Schema.Finite),
26 /** Present on a failed attempt, even one whose `terminal` is `completed`. */
27 failureKind: Schema.optional(Schema.String),
28 failureReason: Schema.optional(Schema.String),
29 }),
30 ),
31 ),
32 finalSummary: Schema.optional(Schema.String),
33 itemId: NonEmptyString,
34 kind: NonEmptyString,
35 revision: Schema.Int.check(Schema.isGreaterThan(0)),
36 status: NonEmptyString,
37 turnId: Schema.optional(Schema.NullOr(Schema.String)),
38 text: Schema.optional(Schema.String),
39 summary: Schema.optional(Schema.Array(Schema.String)),
40 tool: Schema.optional(Schema.String),
41 args: Schema.optional(Schema.String),
42 visibleOutput: Schema.optional(Schema.String),
43 truncated: Schema.optional(Schema.Boolean),
44 failureReason: Schema.optional(Schema.String),
45 fallbackText: Schema.optional(Schema.String),
46 commandText: Schema.optional(Schema.String),
47 exitCode: Schema.optional(Schema.Int),
48 durationMs: Schema.optional(Schema.Finite),
49 subagentId: Schema.optional(Schema.String),
50 childSessionId: Schema.optional(Schema.String),
51 objective: Schema.optional(Schema.String),
52 role: Schema.optional(Schema.String),
53 controlStatus: Schema.optional(Schema.String),
54 result: Schema.optional(
55 Schema.Struct({ summary: Schema.String, text: Schema.optional(Schema.String) }),
56 ),
57 usage: Schema.optional(MuseUsage),
58 outcome: Schema.optional(Schema.String),
59 trigger: Schema.optional(Schema.String),
60 reason: Schema.optional(Schema.String),
61});
62export type MuseItem = typeof MuseItem.Type;
63​
64export const MuseSessionResult = Schema.Struct({
65 session: Schema.Struct({
66 sessionId: NonEmptyString,
67 modelId: Schema.optional(Schema.NullOr(Schema.String)),
68 activeTurnId: Schema.optional(Schema.NullOr(Schema.String)),
69 }),
70 history: Schema.optional(
71 Schema.Struct({
72 items: Schema.NullOr(Schema.Array(MuseItem)),
73 snapshot: Schema.optional(
74 Schema.NullOr(
75 Schema.Struct({
76 schemaVersion: Schema.optional(Schema.Int),
77 state: Schema.Struct({ items: Schema.Array(MuseItem) }),
78 }),
79 ),
80 ),
81 }),
82 ),
83});
84export const MuseTurnStartResult = Schema.Struct({ turnId: NonEmptyString });
85​
86export const MuseApproval = Schema.Struct({
87 approvalId: NonEmptyString,
88 protectedWrite: Schema.optional(Schema.Boolean),
89 judgeEscalated: Schema.optional(Schema.Boolean),
90 sessionId: NonEmptyString,
91 turnId: Schema.optional(Schema.String),
92 itemId: Schema.optional(Schema.String),
93 toolName: Schema.optional(Schema.String),
94 rawArgs: Schema.optional(Schema.String),
95 /** Set when a workflow child asks; `turnId` is then the child's run, not a session turn. */
96 subagentOrigin: Schema.optional(Schema.Struct({ subagentId: NonEmptyString })),
97 currentRequirementId: Schema.Struct({ approvalId: NonEmptyString, sourceIndex: Schema.Int }),
98 availableChoices: Schema.Array(
99 Schema.Struct({
100 choiceId: NonEmptyString,
101 label: Schema.String,
102 decision: NonEmptyString,
103 scope: Schema.String,
104 }),
105 ),
106 subject: Schema.Struct({
107 kind: Schema.String,
108 access: Schema.optional(Schema.String),
109 command: Schema.optional(Schema.String),
110 path: Schema.optional(Schema.String),
111 host: Schema.optional(Schema.String),
112 target: Schema.optional(Schema.String),
113 }),
114});
115export type MuseApproval = typeof MuseApproval.Type;
116​
117export const MuseUserInput = Schema.Struct({
118 userInputId: NonEmptyString,
119 sessionId: NonEmptyString,
120 turnId: NonEmptyString,
121 questions: Schema.Array(
122 Schema.Struct({
123 id: NonEmptyString,
124 header: Schema.String,
125 question: Schema.String,
126 options: Schema.Array(
127 Schema.Struct({ label: Schema.String, description: Schema.optional(Schema.String) }),
128 ),
129 selection: Schema.Struct({
130 mode: Schema.Literals(["single", "multiple"]),
131 minSelections: Schema.optional(Schema.Int),
132 maxSelections: Schema.optional(Schema.Int),
133 }),
134 }),
135 ),
136});
137export type MuseUserInput = typeof MuseUserInput.Type;
138​
139export const MuseTokenUsageEvent = Schema.Struct({
140 turnId: NonEmptyString,
141 promptTokens: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
142 usage: MuseUsage,
143});
144export const MuseContextUsage = Schema.Struct({
145 usedTokens: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
146 windowTokens: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
147});
148export const MuseTodoList = Schema.Struct({
149 items: Schema.Array(Schema.Struct({ text: Schema.String, status: Schema.String })),
150});
151export const MuseTurnCompleted = Schema.Struct({
152 turnId: NonEmptyString,
153 terminal: NonEmptyString,
154 reason: Schema.optional(Schema.String),
155 error: Schema.optional(
156 Schema.Struct({
157 message: Schema.String,
158 // Present when Muse recognized the stop as a used-up quota.
159 quota: Schema.optional(Schema.Struct({ resetsAtMs: Schema.Finite })),
160 }),
161 ),
162 usage: Schema.optional(MuseUsage),
163});
164/** The latest instant a JavaScript Date holds; formatting a later one throws. */
165export const LATEST_DATE_MS = 8.64e15;
166const DateMillis = Schema.Finite.check(
167 Schema.isGreaterThan(0),
168 Schema.isLessThanOrEqualTo(LATEST_DATE_MS),
169);
170/**
171 * `usage/changed` params: the Meta subscription windows the latest model
172 * response reported. Percentages are Meta's, verbatim, and may exceed 100.
173 */
174export const MuseSubscriptionUsage = Schema.Struct({
175 observedAtMs: DateMillis,
176 tier: Schema.String,
177 window: Schema.Struct({
178 usedPercent: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
179 windowDurationMins: Schema.Finite.check(Schema.isGreaterThan(0)),
180 resetsAtMs: DateMillis,
181 }),
182 weekly: Schema.Struct({
183 usedPercent: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
184 resetsAtMs: DateMillis,
185 }),
186});
187export type MuseSubscriptionUsage = typeof MuseSubscriptionUsage.Type;
188export const MuseTurnRetryScheduled = Schema.Struct({
189 turnId: NonEmptyString,
190 nextAttempt: Schema.Int.check(Schema.isGreaterThan(0)),
191 maxAttempts: Schema.Int.check(Schema.isGreaterThan(0)),
192 reason: NonEmptyString,
193 retryDelayMs: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0)),
194});
195export const MuseCompactResult = Schema.Struct({
196 status: Schema.String,
197 reason: Schema.optional(Schema.String),
198});
199​
200export const MuseItemEvent = Schema.Struct({ item: MuseItem });
201export const MuseDelta = Schema.Struct({
202 itemId: NonEmptyString,
203 delta: Schema.String,
204 field: Schema.optional(Schema.String),
205});
206​
207export function museApprovalDecision(
208 choice: Pick<MuseApproval["availableChoices"][number], "decision" | "scope">,
209): ProviderApprovalDecision | undefined {
210 switch (choice.decision) {
211 case "approved":
212 return "accept";
213 case "approvedForSession":
214 return "acceptForSession";
215 case "approvedPolicyAmendment":
216 return choice.scope === "session"
217 ? "acceptForSession"
218 : choice.scope === "localPersistent"
219 ? "acceptAlways"
220 : undefined;
221 case "denied":
222 case "deniedPolicyAmendment":
223 return "decline";
224 case "abort":
225 return "cancel";
226 default:
227 return undefined;
228 }
230​
231/**
232 * Muse shell approvals offer no `denied` choice, only `abort` ("Reject"), so
233 * `decline` falls back to it.
234 */
235export function museApprovalChoices(approval: Pick<MuseApproval, "availableChoices">) {
236 const choices = new Map<ProviderApprovalDecision, MuseApproval["availableChoices"][number]>();
237 const rank = (choice: MuseApproval["availableChoices"][number]) =>
238 (choice.scope === "once" ? 0 : choice.scope === "session" ? 2 : 4) +
239 (choice.decision.endsWith("PolicyAmendment") ? 1 : 0);
240 for (const choice of approval.availableChoices) {
241 const decision = museApprovalDecision(choice);
242 if (!decision) continue;
243 const previous = choices.get(decision);
244 if (!previous || rank(choice) < rank(previous)) choices.set(decision, choice);
245 }
246 const abort = choices.get("cancel");
247 if (!choices.has("decline") && abort) choices.set("decline", abort);
248 return choices;
250​
251export function museApprovalOptions(approval: Pick<MuseApproval, "availableChoices">) {
252 const choices = museApprovalChoices(approval);
253 const declineChoiceId = choices.get("decline")?.choiceId;
254 return [...choices]
255 .filter(([decision, choice]) => decision !== "cancel" || choice.choiceId !== declineChoiceId)
256 .map(([decision, choice]) => ({ decision, label: choice.label }));