@nyte-ai/plugin 0.0.0-stage → 0.0.18

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 (134) hide show
  1. package/LICENSE +21 -0
  2. package/THIRD-PARTY-NOTICES.md +800 -0
  3. package/dist/chunks/billing-0y7dfkp2.js +146 -0
  4. package/dist/chunks/billing-2v3g7rd9.js +190 -0
  5. package/dist/chunks/billing-3j77ss7y.js +86 -0
  6. package/dist/chunks/billing-3scqmkzb.js +559 -0
  7. package/dist/chunks/billing-6z2kgtyt.js +51 -0
  8. package/dist/chunks/billing-8rjk35gr.js +444 -0
  9. package/dist/chunks/billing-9mfedmsh.js +373 -0
  10. package/dist/chunks/billing-9nn3yp18.js +176 -0
  11. package/dist/chunks/billing-9qc0eqh4.js +174 -0
  12. package/dist/chunks/billing-a9vqn66p.js +351 -0
  13. package/dist/chunks/billing-bv5zr32b.js +369 -0
  14. package/dist/chunks/billing-cy1rg619.js +302 -0
  15. package/dist/chunks/billing-ejx2hv52.js +323 -0
  16. package/dist/chunks/billing-h13r0byk.js +80 -0
  17. package/dist/chunks/billing-j643d12p.js +197 -0
  18. package/dist/chunks/billing-k2p1t25n.js +109 -0
  19. package/dist/chunks/billing-kn3d30b4.js +276 -0
  20. package/dist/chunks/billing-mvc33pv6.js +36 -0
  21. package/dist/chunks/billing-s4rrspsk.js +7 -0
  22. package/dist/chunks/billing-svrhh5a5.js +307 -0
  23. package/dist/chunks/billing-sxc70w72.js +161 -0
  24. package/dist/chunks/billing-t1qrxe16.js +41 -0
  25. package/dist/chunks/billing-tzr3cebf.js +20 -0
  26. package/dist/chunks/billing-wmcbg6fw.js +52 -0
  27. package/dist/chunks/billing-wmkxkypm.js +527 -0
  28. package/dist/chunks/billing-ye3wk5r3.js +205 -0
  29. package/dist/chunks/billing-zfpm2rt0.js +29 -0
  30. package/dist/examples/claude-code/LICENSE +21 -0
  31. package/dist/examples/claude-code/billing.d.ts +7 -0
  32. package/dist/examples/claude-code/billing.js +11 -0
  33. package/dist/examples/claude-code/claude-cli.d.ts +35 -0
  34. package/dist/examples/claude-code/claude-cli.js +15 -0
  35. package/dist/examples/claude-code/env.d.ts +1 -0
  36. package/dist/examples/claude-code/env.js +6 -0
  37. package/dist/examples/claude-code/index.d.ts +24 -0
  38. package/dist/examples/claude-code/index.js +149 -0
  39. package/dist/examples/claude-code/inert-mcp.d.ts +1 -0
  40. package/dist/examples/claude-code/inert-mcp.js +6 -0
  41. package/dist/examples/claude-code/model-catalog.d.ts +27 -0
  42. package/dist/examples/claude-code/model-catalog.js +12 -0
  43. package/dist/examples/claude-code/process.d.ts +22 -0
  44. package/dist/examples/claude-code/process.js +25 -0
  45. package/dist/examples/claude-code/replay.d.ts +4 -0
  46. package/dist/examples/claude-code/replay.js +11 -0
  47. package/dist/examples/claude-code/stream.d.ts +3 -0
  48. package/dist/examples/claude-code/stream.js +16 -0
  49. package/dist/examples/claude-code/transcript.d.ts +83 -0
  50. package/dist/examples/claude-code/transcript.js +23 -0
  51. package/dist/examples/claude-code/turn-relay.d.ts +48 -0
  52. package/dist/examples/claude-code/turn-relay.js +9 -0
  53. package/dist/examples/claude-code/wire.d.ts +372 -0
  54. package/dist/examples/claude-code/wire.js +18 -0
  55. package/dist/src/acp/connection.d.ts +24 -0
  56. package/dist/src/acp/connection.js +8 -0
  57. package/dist/src/acp/index.d.ts +54 -0
  58. package/dist/src/acp/index.js +1004 -0
  59. package/dist/src/acp/registry.d.ts +18 -0
  60. package/dist/src/acp/registry.js +8 -0
  61. package/dist/src/acp/thread.d.ts +46 -0
  62. package/dist/src/acp/thread.js +7 -0
  63. package/dist/src/acp/transcript.d.ts +8 -0
  64. package/dist/src/acp/transcript.js +11 -0
  65. package/dist/src/acp/translate.d.ts +33 -0
  66. package/dist/src/acp/translate.js +20 -0
  67. package/dist/src/approvals/approvals.d.ts +189 -0
  68. package/dist/src/approvals/approvals.js +143 -0
  69. package/dist/src/approvals/schema.d.ts +169 -0
  70. package/dist/src/approvals/schema.js +18 -0
  71. package/dist/src/bash-description.d.ts +30 -0
  72. package/dist/src/bash-description.js +18 -0
  73. package/dist/src/browser-tools.d.ts +25 -0
  74. package/dist/src/browser-tools.js +246 -0
  75. package/dist/src/canvas/canvas-compile.d.ts +48 -0
  76. package/dist/src/canvas/canvas-compile.js +8 -0
  77. package/dist/src/canvas/canvas-libraries.d.ts +32 -0
  78. package/dist/src/canvas/canvas-libraries.js +6 -0
  79. package/dist/src/canvas/canvas-preview.d.ts +107 -0
  80. package/dist/src/canvas/canvas-preview.js +12 -0
  81. package/dist/src/canvas/canvas-protocol.d.ts +184 -0
  82. package/dist/src/canvas/canvas-protocol.js +75 -0
  83. package/dist/src/canvas/canvas.d.ts +50 -0
  84. package/dist/src/canvas/canvas.js +221 -0
  85. package/dist/src/canvas/schema.d.ts +47 -0
  86. package/dist/src/canvas/schema.js +8 -0
  87. package/dist/src/claude-code-sdk/index.d.ts +35 -0
  88. package/dist/src/claude-code-sdk/index.js +368 -0
  89. package/dist/src/claude-code-sdk/session.d.ts +48 -0
  90. package/dist/src/claude-code-sdk/session.js +7 -0
  91. package/dist/src/claude-code-sdk/transcript.d.ts +19 -0
  92. package/dist/src/claude-code-sdk/transcript.js +15 -0
  93. package/dist/src/claude-code-sdk/translate.d.ts +18 -0
  94. package/dist/src/claude-code-sdk/translate.js +20 -0
  95. package/dist/src/client/mount.d.ts +44 -0
  96. package/dist/src/client/mount.js +252 -0
  97. package/dist/src/client/notifications.d.ts +35 -0
  98. package/dist/src/client/notifications.js +26 -0
  99. package/dist/src/client/presentation.d.ts +336 -0
  100. package/dist/src/client/presentation.js +373 -0
  101. package/dist/src/client/transcript-tui.d.ts +23 -0
  102. package/dist/src/client/transcript-tui.js +20 -0
  103. package/dist/src/client/transcript.d.ts +23 -0
  104. package/dist/src/client/transcript.js +51 -0
  105. package/dist/src/client.d.ts +53 -0
  106. package/dist/src/client.js +22 -0
  107. package/dist/src/codemode-runtime.d.ts +11 -0
  108. package/dist/src/codemode-runtime.js +10 -0
  109. package/dist/src/codemode-worker.d.ts +1 -0
  110. package/dist/src/codemode-worker.js +2 -0
  111. package/dist/src/codemode.d.ts +21 -0
  112. package/dist/src/codemode.js +170 -0
  113. package/dist/src/core.d.ts +43 -0
  114. package/dist/src/core.js +11 -0
  115. package/dist/src/openai-astra-context.d.ts +23 -0
  116. package/dist/src/openai-astra-context.js +14 -0
  117. package/dist/src/openai-compaction.d.ts +15 -0
  118. package/dist/src/openai-compaction.js +55 -0
  119. package/dist/src/question/client/questions-tui.d.ts +9 -0
  120. package/dist/src/question/client/questions-tui.js +19 -0
  121. package/dist/src/question/client/questions.d.ts +9 -0
  122. package/dist/src/question/client/questions.js +160 -0
  123. package/dist/src/question/question.d.ts +63 -0
  124. package/dist/src/question/question.js +9 -0
  125. package/dist/src/question/schema.d.ts +101 -0
  126. package/dist/src/question/schema.js +14 -0
  127. package/dist/src/rename.d.ts +78 -0
  128. package/dist/src/rename.js +78 -0
  129. package/dist/src/telemetry.d.ts +36 -0
  130. package/dist/src/telemetry.js +84 -0
  131. package/dist/src/web-search.d.ts +78 -0
  132. package/dist/src/web-search.js +219 -0
  133. package/package.json +190 -3
  134. package/README.md +0 -3
@@ -0,0 +1,323 @@
1
+ import {
2
+ messageSchema2,
3
+ matchesRecord2
4
+ } from "./billing-0y7dfkp2.js";
5
+
6
+ // examples/claude-code/transcript.ts
7
+ import { Type } from "typebox";
8
+ import { Value } from "typebox/value";
9
+ import {
10
+ getDeclaredTools,
11
+ getInitialSystemMessage,
12
+ hasToolRedefinitions,
13
+ renderSystemMessageUpdate
14
+ } from "@nyte-ai/ai";
15
+ var TOOL_PREFIX2 = "mcp__nyte__";
16
+ var NATIVE_REPLAY_DIAGNOSTIC = "claude-code.native-assistant.v1";
17
+ var NATIVE_TOOL_CHANGES_BETA2 = "mid-conversation-tool-changes-2026-07-01";
18
+ var DEFERRED_TOOL_PLACEHOLDER = {
19
+ name: "__nyte_deferred_placeholder__",
20
+ description: "Reserved placeholder. Never available. Never call this.",
21
+ input_schema: { type: "object", properties: {}, required: [] },
22
+ defer_loading: true
23
+ };
24
+ function sanitizeSurrogates(text) {
25
+ return text.replace(/[\uD800-\uDFFF]/gu, "�");
26
+ }
27
+ function assistantProjection(message) {
28
+ const text = message.content.filter((block) => block.type === "text").map((block) => block.text).join("").trim();
29
+ const toolCalls = message.content.filter((block) => block.type === "toolCall").map((block) => ({ id: block.id, name: block.name, input: structuredClone(block.arguments) }));
30
+ return { text, toolCalls };
31
+ }
32
+ var projectionSchema = Type.Object({
33
+ text: Type.String(),
34
+ toolCalls: Type.Array(Type.Object({
35
+ id: Type.String(),
36
+ name: Type.String(),
37
+ input: Type.Record(Type.String(), Type.Unknown())
38
+ }))
39
+ });
40
+ var replayCarrierSchema = Type.Object({
41
+ version: Type.Literal(1),
42
+ message: messageSchema2,
43
+ projection: projectionSchema,
44
+ initialUserPrefix: Type.Optional(Type.Array(Type.Unknown())),
45
+ initialSystemMessages: Type.Optional(Type.Array(Type.Unknown()))
46
+ });
47
+ function replayCarrier(message) {
48
+ const diagnostic = message.diagnostics?.find((item) => item.type === NATIVE_REPLAY_DIAGNOSTIC);
49
+ const candidate = diagnostic?.details?.carrier;
50
+ return Value.Check(replayCarrierSchema, candidate) ? candidate : undefined;
51
+ }
52
+ function replayMetadata(messages, key) {
53
+ for (let index = messages.length - 1;index >= 0; index--) {
54
+ const message = messages[index];
55
+ if (message?.role !== "assistant")
56
+ continue;
57
+ const value = replayCarrier(message)?.[key];
58
+ if (value)
59
+ return structuredClone(value);
60
+ }
61
+ return;
62
+ }
63
+ function getInitialUserPrefix2(messages) {
64
+ return replayMetadata(messages, "initialUserPrefix");
65
+ }
66
+ function getInitialSystemMessages2(messages) {
67
+ return replayMetadata(messages, "initialSystemMessages");
68
+ }
69
+ function imageBlock(block) {
70
+ return {
71
+ type: "image",
72
+ source: { type: "base64", media_type: block.mimeType, data: block.data }
73
+ };
74
+ }
75
+ function userContent(content) {
76
+ if (typeof content === "string")
77
+ return content ? [{ type: "text", text: sanitizeSurrogates(content) }] : [];
78
+ return content.map((block) => block.type === "text" ? { type: "text", text: sanitizeSurrogates(block.text) } : imageBlock(block));
79
+ }
80
+ function toolResultContent(message) {
81
+ const hasImages = message.content.some((block) => block.type === "image");
82
+ if (!hasImages) {
83
+ return sanitizeSurrogates(message.content.filter((block) => block.type === "text").map((block) => block.text).join(`
84
+ `));
85
+ }
86
+ return message.content.map((block) => block.type === "text" ? { type: "text", text: sanitizeSurrogates(block.text) } : imageBlock(block));
87
+ }
88
+ function canonicalAssistantContent(message) {
89
+ const blocks = [];
90
+ for (const block of message.content) {
91
+ if (block.type === "text" && block.text.trim()) {
92
+ blocks.push({ type: "text", text: sanitizeSurrogates(block.text) });
93
+ } else if (block.type === "thinking" && block.thinking.trim() && block.thinkingSignature) {
94
+ if (block.redacted) {
95
+ blocks.push({ type: "redacted_thinking", data: block.thinkingSignature });
96
+ } else {
97
+ blocks.push({
98
+ type: "thinking",
99
+ thinking: sanitizeSurrogates(block.thinking),
100
+ signature: block.thinkingSignature
101
+ });
102
+ }
103
+ } else if (block.type === "toolCall") {
104
+ blocks.push({
105
+ type: "tool_use",
106
+ id: block.id,
107
+ name: `${TOOL_PREFIX2}${block.name}`,
108
+ input: structuredClone(block.arguments)
109
+ });
110
+ }
111
+ }
112
+ return blocks;
113
+ }
114
+ function assistantContent(message) {
115
+ const carrier = replayCarrier(message);
116
+ if (carrier && JSON.stringify(assistantProjection(message)) === JSON.stringify(carrier.projection)) {
117
+ return structuredClone(carrier.message.content);
118
+ }
119
+ if (carrier) {
120
+ return canonicalAssistantContent({
121
+ ...message,
122
+ content: message.content.filter((block) => block.type !== "thinking")
123
+ });
124
+ }
125
+ return canonicalAssistantContent(message);
126
+ }
127
+ function prepareFrames2(messages) {
128
+ const frames = [];
129
+ for (const message of messages) {
130
+ if (message.role === "system")
131
+ continue;
132
+ let role;
133
+ let blocks;
134
+ if (message.role === "user") {
135
+ role = "user";
136
+ blocks = userContent(message.content);
137
+ } else if (message.role === "assistant") {
138
+ role = "assistant";
139
+ blocks = assistantContent(message);
140
+ } else {
141
+ role = "user";
142
+ blocks = [
143
+ {
144
+ type: "tool_result",
145
+ tool_use_id: message.toolCallId,
146
+ content: toolResultContent(message),
147
+ is_error: message.isError
148
+ }
149
+ ];
150
+ }
151
+ if (blocks.length === 0)
152
+ continue;
153
+ const previous = frames.at(-1);
154
+ if (role === "user" && previous?.type === "user") {
155
+ previous.message.content.push(...blocks);
156
+ } else {
157
+ frames.push({ type: role, message: { role, content: blocks } });
158
+ }
159
+ }
160
+ const final = frames.at(-1);
161
+ if (!final || final.type !== "user" || final.message.content.length === 0) {
162
+ throw new Error("Claude Code history must end in a non-empty user or tool-result message");
163
+ }
164
+ for (let index = 0;index < frames.length - 1; index++) {
165
+ const frame = frames[index];
166
+ if (frame?.type === "user")
167
+ frame.shouldQuery = false;
168
+ }
169
+ return frames;
170
+ }
171
+ function withoutNullVariant(schema) {
172
+ if (Array.isArray(schema))
173
+ return schema.map(withoutNullVariant);
174
+ if (!matchesRecord2(schema))
175
+ return schema;
176
+ const output = {};
177
+ for (const [key, value] of Object.entries(schema))
178
+ output[key] = withoutNullVariant(value);
179
+ if (Array.isArray(output.type) && output.type.includes("null")) {
180
+ const remaining = output.type.filter((value) => value !== "null");
181
+ output.type = remaining.length === 1 ? remaining[0] : remaining;
182
+ }
183
+ if (Array.isArray(output.anyOf)) {
184
+ const nonNull = output.anyOf.filter((branch) => !(matchesRecord2(branch) && branch.type === "null"));
185
+ if (nonNull.length === 1 && nonNull.length !== output.anyOf.length) {
186
+ const replacement = nonNull[0];
187
+ delete output.anyOf;
188
+ if (replacement && typeof replacement === "object")
189
+ Object.assign(output, replacement);
190
+ }
191
+ }
192
+ return output;
193
+ }
194
+ function normalizeInputSchema(schema) {
195
+ const normalized = withoutNullVariant(schema);
196
+ if (!matchesRecord2(normalized))
197
+ throw new Error("Tool input schema must be an object");
198
+ for (const key of ["oneOf", "allOf", "anyOf"])
199
+ delete normalized[key];
200
+ if (!normalized.type)
201
+ normalized.type = "object";
202
+ if (normalized.type === "object" && (!normalized.properties || typeof normalized.properties !== "object")) {
203
+ normalized.properties = {};
204
+ }
205
+ return normalized;
206
+ }
207
+ function prepareTools2(tools) {
208
+ const names = new Set;
209
+ const manifest = [];
210
+ const nativeTools = [];
211
+ for (const tool of tools) {
212
+ if (!/^[A-Za-z0-9_-]{1,50}$/u.test(tool.name) || names.has(tool.name)) {
213
+ throw new Error("Claude Code tool names must be unique ASCII identifiers of at most 50 characters");
214
+ }
215
+ names.add(tool.name);
216
+ const schema = normalizeInputSchema(tool.parameters);
217
+ manifest.push({ name: tool.name, description: tool.description, inputSchema: schema });
218
+ nativeTools.push({
219
+ name: `${TOOL_PREFIX2}${tool.name}`,
220
+ description: tool.description,
221
+ input_schema: schema
222
+ });
223
+ }
224
+ return { manifest, nativeTools, names };
225
+ }
226
+ function nativeSystemBlocks(message) {
227
+ const blocks = [];
228
+ const text = renderSystemMessageUpdate(message);
229
+ if (text)
230
+ blocks.push({ type: "text", text: sanitizeSurrogates(text) });
231
+ for (const tool of message.toolsRemoved ?? []) {
232
+ blocks.push({
233
+ type: "tool_removal",
234
+ tool: { type: "tool_reference", name: `${TOOL_PREFIX2}${tool.name}` }
235
+ });
236
+ }
237
+ for (const tool of message.toolsAdded ?? []) {
238
+ blocks.push({
239
+ type: "tool_addition",
240
+ tool: { type: "tool_reference", name: `${TOOL_PREFIX2}${tool.name}` }
241
+ });
242
+ }
243
+ return blocks;
244
+ }
245
+ function prepareNativeTranscript2(messages, supported) {
246
+ const initial = getInitialSystemMessage(messages);
247
+ const initialTools = initial?.toolsAdded ?? [];
248
+ if (!supported || initialTools.length === 0 || hasToolRedefinitions(messages))
249
+ return;
250
+ const declared = getDeclaredTools(messages);
251
+ const prepared = prepareTools2(declared);
252
+ const nativeByName = new Map(prepared.nativeTools.map((tool) => [String(tool.name).slice(TOOL_PREFIX2.length), tool]));
253
+ const initialNames = new Set(initialTools.map((tool) => tool.name));
254
+ const initialNative = initialTools.map((tool) => {
255
+ const native = nativeByName.get(tool.name);
256
+ if (native === undefined)
257
+ throw new Error(`Missing declared tool ${tool.name}`);
258
+ return structuredClone(native);
259
+ });
260
+ const final = initialNative.at(-1);
261
+ if (final)
262
+ final.cache_control = { type: "ephemeral", ttl: "1h" };
263
+ const laterNative = declared.filter((tool) => !initialNames.has(tool.name)).map((tool) => ({ ...structuredClone(nativeByName.get(tool.name)), defer_loading: true }));
264
+ const systemInjections = [];
265
+ let pending = [];
266
+ let assistantOrdinal = 0;
267
+ const flush = (beforeAssistant) => {
268
+ for (const content of pending)
269
+ systemInjections.push({ beforeAssistant, content });
270
+ pending = [];
271
+ };
272
+ for (let index = 1;index < messages.length; index++) {
273
+ const message = messages[index];
274
+ if (message === undefined)
275
+ continue;
276
+ if (message.role === "system") {
277
+ const blocks = nativeSystemBlocks(message);
278
+ if (blocks.length)
279
+ pending.push(blocks);
280
+ } else if (message.role === "assistant" && assistantContent(message).length > 0) {
281
+ flush(assistantOrdinal);
282
+ assistantOrdinal += 1;
283
+ }
284
+ }
285
+ flush(null);
286
+ return {
287
+ requestTools: [...initialNative, structuredClone(DEFERRED_TOOL_PLACEHOLDER), ...laterNative],
288
+ systemInjections
289
+ };
290
+ }
291
+ function buildExtraBody2(nativeTools, options, adaptive) {
292
+ const body = { tools: nativeTools };
293
+ if (options?.maxTokens !== undefined)
294
+ body.max_tokens = options.maxTokens;
295
+ if (options?.reasoning) {
296
+ if (adaptive)
297
+ body.thinking = { type: "adaptive" };
298
+ body.output_config = {
299
+ effort: options.reasoning === "minimal" ? "low" : options.reasoning
300
+ };
301
+ } else {
302
+ body.thinking = { type: "disabled" };
303
+ body.context_management = { edits: [] };
304
+ }
305
+ return body;
306
+ }
307
+ function makeReplayDiagnostic2(message, output, initialUserPrefix, initialSystemMessages) {
308
+ return {
309
+ type: NATIVE_REPLAY_DIAGNOSTIC,
310
+ timestamp: Date.now(),
311
+ details: {
312
+ carrier: {
313
+ version: 1,
314
+ message: structuredClone(message),
315
+ projection: assistantProjection(output),
316
+ ...initialUserPrefix ? { initialUserPrefix: structuredClone(initialUserPrefix) } : {},
317
+ ...initialSystemMessages ? { initialSystemMessages: structuredClone(initialSystemMessages) } : {}
318
+ }
319
+ }
320
+ };
321
+ }
322
+
323
+ export { TOOL_PREFIX2, NATIVE_TOOL_CHANGES_BETA2, getInitialUserPrefix2, getInitialSystemMessages2, prepareFrames2, prepareTools2, prepareNativeTranscript2, buildExtraBody2, makeReplayDiagnostic2 };
@@ -0,0 +1,80 @@
1
+ // src/approvals/schema.ts
2
+ import { standard, ToolClassType } from "@nyte-ai/schema";
3
+ import { Type } from "typebox";
4
+ var policy = standard(Type.Union([Type.Literal("ask"), Type.Literal("auto-edit"), Type.Literal("full")]));
5
+ var PERMISSIONS2 = "permissions";
6
+ var approvalPolicy2 = policy;
7
+ var APPROVAL_POLICIES2 = [
8
+ { value: "ask", label: "Ask first", description: "Asks before every command and file change" },
9
+ {
10
+ value: "auto-edit",
11
+ label: "Auto-edit",
12
+ description: "Edits workspace files, asks before commands and anything outside"
13
+ },
14
+ { value: "full", label: "Full access", description: "Runs every tool without asking" }
15
+ ];
16
+ var reasonType = Type.Union([
17
+ Type.Literal("shell"),
18
+ Type.Literal("edit"),
19
+ Type.Literal("outside"),
20
+ Type.Literal("tool")
21
+ ]);
22
+ var decision = Type.Union([
23
+ Type.Literal("once"),
24
+ Type.Literal("session"),
25
+ Type.Literal("deny"),
26
+ Type.Null()
27
+ ]);
28
+ var state = standard(Type.Object({ tool: Type.String(), class: ToolClassType, reason: reasonType, decision }));
29
+ var empty = standard(Type.Object({}));
30
+ var actions = { once: { input: empty }, session: { input: empty }, deny: { input: empty } };
31
+ var APPROVAL_ACTIONS2 = [
32
+ { action: "once", label: "Allow once" },
33
+ { action: "session", label: "Allow for this session" },
34
+ { action: "deny", label: "Deny" }
35
+ ];
36
+ function approvalPrompt2(current) {
37
+ const subject = current.class;
38
+ switch (subject.kind) {
39
+ case "shell":
40
+ return { title: "Run this command?", detail: subject.command };
41
+ case "edit":
42
+ return {
43
+ title: current.reason === "outside" ? "Edit outside the workspace?" : "Edit this file?",
44
+ detail: subject.path
45
+ };
46
+ case "read":
47
+ case "list":
48
+ return { title: `Use ${current.tool}?`, detail: subject.path };
49
+ case "delegate":
50
+ return { title: `Use ${current.tool}?`, detail: subject.title ?? "" };
51
+ case "custom":
52
+ return { title: `Use ${current.tool}?`, detail: subject.label };
53
+ default: {
54
+ const exhaustive = subject;
55
+ return exhaustive;
56
+ }
57
+ }
58
+ }
59
+ var approval2 = {
60
+ kind: "ask/approval",
61
+ state,
62
+ actions,
63
+ fallback: (current, { id }) => {
64
+ const prompt = approvalPrompt2(current);
65
+ return `${prompt.title} ${prompt.detail} (${id})${current.decision === null ? "" : ` Answered: ${current.decision}`}`;
66
+ }
67
+ };
68
+ function openApprovals2(view) {
69
+ return (view?.parts ?? []).flatMap((part) => {
70
+ if (part.partKind !== approval2.kind || part.status.kind !== "live")
71
+ return [];
72
+ const checked = approval2.state["~standard"].validate(part.state);
73
+ if (checked instanceof Promise || checked.issues !== undefined || checked.value.decision !== null)
74
+ return [];
75
+ const { tool, reason } = checked.value;
76
+ return [{ part: part.id, tool, class: checked.value.class, reason }];
77
+ });
78
+ }
79
+
80
+ export { PERMISSIONS2, approvalPolicy2, APPROVAL_POLICIES2, APPROVAL_ACTIONS2, approvalPrompt2, approval2, openApprovals2 };
@@ -0,0 +1,197 @@
1
+ import {
2
+ matchesRecord2,
3
+ parseRequest2,
4
+ parseRequestMessages2
5
+ } from "./billing-0y7dfkp2.js";
6
+
7
+ // examples/claude-code/replay.ts
8
+ function withoutCacheControl(value) {
9
+ if (Array.isArray(value))
10
+ return value.map(withoutCacheControl);
11
+ if (!matchesRecord2(value))
12
+ return value;
13
+ const output = {};
14
+ for (const [key, child] of Object.entries(value)) {
15
+ if (key !== "cache_control")
16
+ output[key] = withoutCacheControl(child);
17
+ }
18
+ return output;
19
+ }
20
+ function requestMessages(body) {
21
+ if (!body)
22
+ return;
23
+ try {
24
+ return parseRequest2(body).messages;
25
+ } catch {
26
+ return;
27
+ }
28
+ }
29
+ function deriveInitialUserPrefix2(body, canonicalContent) {
30
+ if (canonicalContent.length === 0)
31
+ return;
32
+ const actual = requestMessages(body)?.[0];
33
+ if (actual?.role !== "user" || !Array.isArray(actual.content) || actual.content.length < canonicalContent.length) {
34
+ return;
35
+ }
36
+ const suffix = actual.content.slice(-canonicalContent.length).map(withoutCacheControl);
37
+ if (JSON.stringify(suffix) !== JSON.stringify(canonicalContent.map(withoutCacheControl)))
38
+ return;
39
+ return structuredClone(actual.content.slice(0, -canonicalContent.length));
40
+ }
41
+ function deriveInitialSystemMessages2(body) {
42
+ const messages = requestMessages(body);
43
+ if (messages?.[0]?.role !== "user")
44
+ return;
45
+ let end = 1;
46
+ while (messages[end]?.role === "system")
47
+ end += 1;
48
+ const systems = messages.slice(1, end);
49
+ let trailingStart = messages.length;
50
+ while (trailingStart > end && messages[trailingStart - 1]?.role === "system")
51
+ trailingStart -= 1;
52
+ if (trailingStart < messages.length)
53
+ systems.push(...messages.slice(trailingStart));
54
+ return systems.length ? structuredClone(systems) : undefined;
55
+ }
56
+ function contentText(content) {
57
+ if (typeof content === "string")
58
+ return content;
59
+ if (!Array.isArray(content))
60
+ return "";
61
+ return content.map((block) => matchesRecord2(block) && typeof block.text === "string" ? block.text : "").join("");
62
+ }
63
+ function setCacheBreakpoint(message) {
64
+ if (typeof message.content === "string") {
65
+ message.content = [
66
+ { type: "text", text: message.content, cache_control: { type: "ephemeral", ttl: "1h" } }
67
+ ];
68
+ return;
69
+ }
70
+ if (!Array.isArray(message.content) || message.content.length === 0)
71
+ return;
72
+ const last = message.content.at(-1);
73
+ if (!matchesRecord2(last))
74
+ return;
75
+ last.cache_control = { type: "ephemeral", ttl: "1h" };
76
+ }
77
+ function setReplayCacheBreakpoints(messages) {
78
+ const userIndexes = messages.map((message, index) => message.role === "user" ? index : -1).filter((index) => index >= 0);
79
+ if (userIndexes.length >= 3) {
80
+ for (const message of messages) {
81
+ if (message.role === "system")
82
+ message.content = withoutCacheControl(message.content);
83
+ }
84
+ const previousIndex = userIndexes.at(-2);
85
+ const previous = previousIndex === undefined ? undefined : messages[previousIndex];
86
+ if (previous)
87
+ setCacheBreakpoint(previous);
88
+ }
89
+ const final = messages.at(-1);
90
+ if (final)
91
+ setCacheBreakpoint(final);
92
+ }
93
+ function removeRepeatedUserReminders(messages, prefix) {
94
+ const reminder = contentText(prefix).trimEnd();
95
+ if (!reminder || !prefix)
96
+ return;
97
+ const normalizedPrefix = JSON.stringify(prefix.map(withoutCacheControl));
98
+ for (let index = 1;index < messages.length; index++) {
99
+ const message = messages[index];
100
+ if (message?.role !== "user" || !Array.isArray(message.content))
101
+ continue;
102
+ const leading = message.content.slice(0, prefix.length).map(withoutCacheControl);
103
+ if (JSON.stringify(leading) === normalizedPrefix)
104
+ message.content.splice(0, prefix.length);
105
+ const toolResult = message.content.findLast((block) => matchesRecord2(block) && block.type === "tool_result");
106
+ if (!matchesRecord2(toolResult))
107
+ continue;
108
+ const suffix = `
109
+ ${reminder}`;
110
+ if (typeof toolResult.content === "string" && toolResult.content.endsWith(suffix)) {
111
+ toolResult.content = toolResult.content.slice(0, -suffix.length);
112
+ } else if (Array.isArray(toolResult.content)) {
113
+ const final = toolResult.content.at(-1);
114
+ if (matchesRecord2(final) && final.type === "text" && typeof final.text === "string") {
115
+ if (final.text === reminder)
116
+ toolResult.content.pop();
117
+ else if (final.text.endsWith(suffix))
118
+ final.text = final.text.slice(0, -suffix.length);
119
+ }
120
+ }
121
+ }
122
+ }
123
+ function injectNativeSystemMessages(messages, injections) {
124
+ const byAssistant = new Map;
125
+ const trailing = [];
126
+ for (const injection of injections) {
127
+ const message = { role: "system", content: structuredClone(injection.content) };
128
+ if (injection.beforeAssistant === null)
129
+ trailing.push(message);
130
+ else {
131
+ const pending = byAssistant.get(injection.beforeAssistant) ?? [];
132
+ pending.push(message);
133
+ byAssistant.set(injection.beforeAssistant, pending);
134
+ }
135
+ }
136
+ const output = [];
137
+ let assistantOrdinal = 0;
138
+ for (const message of messages) {
139
+ if (message.role === "assistant") {
140
+ output.push(...byAssistant.get(assistantOrdinal) ?? []);
141
+ byAssistant.delete(assistantOrdinal);
142
+ assistantOrdinal += 1;
143
+ }
144
+ output.push(message);
145
+ }
146
+ if (byAssistant.size > 0)
147
+ throw new Error("Claude Code request lost an assistant boundary needed by system history");
148
+ output.push(...trailing);
149
+ return output;
150
+ }
151
+ function normalizeLeadingSystemCache(system) {
152
+ if (!Array.isArray(system))
153
+ return;
154
+ for (const block of system) {
155
+ if (matchesRecord2(block))
156
+ delete block.cache_control;
157
+ }
158
+ const last = system.at(-1);
159
+ if (matchesRecord2(last)) {
160
+ last.cache_control = { type: "ephemeral", ttl: "1h" };
161
+ }
162
+ }
163
+ function rewriteInitialRequest2(body, prefix, canonicalContent, initialSystemMessages, nativeSystemInjections) {
164
+ const payload = parseRequest2(body);
165
+ let messages = payload.messages;
166
+ const first = messages?.[0];
167
+ if (first?.role !== "user" || !Array.isArray(first.content)) {
168
+ throw new Error("Claude Code request is missing its initial user message");
169
+ }
170
+ if (prefix)
171
+ first.content = [...structuredClone(prefix), ...structuredClone(canonicalContent)];
172
+ if (initialSystemMessages?.length && messages) {
173
+ let systemEnd = 1;
174
+ while (messages[systemEnd]?.role === "system")
175
+ systemEnd += 1;
176
+ messages.splice(1, systemEnd - 1, ...parseRequestMessages2(structuredClone(initialSystemMessages)));
177
+ const initialText = initialSystemMessages.map((message) => matchesRecord2(message) ? contentText(message.content) : "").join(`
178
+ `);
179
+ while (messages.at(-1)?.role === "system") {
180
+ const trailingText = contentText(messages.at(-1)?.content);
181
+ if (!trailingText || !initialText.includes(trailingText))
182
+ break;
183
+ messages.pop();
184
+ }
185
+ removeRepeatedUserReminders(messages, prefix);
186
+ }
187
+ if (nativeSystemInjections) {
188
+ messages = injectNativeSystemMessages(messages, nativeSystemInjections);
189
+ payload.messages = messages;
190
+ normalizeLeadingSystemCache(payload.system);
191
+ }
192
+ if (initialSystemMessages?.length || nativeSystemInjections)
193
+ setReplayCacheBreakpoints(messages);
194
+ return Buffer.from(JSON.stringify(payload));
195
+ }
196
+
197
+ export { deriveInitialUserPrefix2, deriveInitialSystemMessages2, rewriteInitialRequest2 };