@mupt-ai/dari-gateway 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 (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +135 -2
  3. package/dari-gateway.example.yaml +28 -0
  4. package/package.json +42 -4
  5. package/src/bun.ts +4 -0
  6. package/src/context/eval_catalog.ts +11 -0
  7. package/src/context/interaction_fingerprint.ts +691 -0
  8. package/src/context/interaction_fingerprint_format.ts +189 -0
  9. package/src/context/interaction_lease_depth.ts +150 -0
  10. package/src/context/lease_history.ts +200 -0
  11. package/src/context/pricing.ts +30 -0
  12. package/src/context/provider_prompt_accounting.ts +241 -0
  13. package/src/context/routing_context.ts +337 -0
  14. package/src/http/auth.ts +43 -0
  15. package/src/http/errors.ts +114 -0
  16. package/src/http/handler.ts +110 -0
  17. package/src/http/http2_server.ts +122 -0
  18. package/src/http/serve.ts +119 -0
  19. package/src/index.ts +22 -0
  20. package/src/ingress/anthropic_messages.ts +162 -0
  21. package/src/ingress/anthropic_models.ts +28 -0
  22. package/src/ingress/chat_completions.ts +49 -0
  23. package/src/ingress/claude_code/request_context.ts +36 -0
  24. package/src/ingress/codex.ts +81 -0
  25. package/src/ingress/codex_models.ts +113 -0
  26. package/src/ingress/json.ts +113 -0
  27. package/src/ingress/models.ts +55 -0
  28. package/src/interaction/capabilities.ts +30 -0
  29. package/src/interaction/image.ts +12 -0
  30. package/src/interaction/portable_reasoning_state.ts +25 -0
  31. package/src/interaction/provider_continuation_state.ts +36 -0
  32. package/src/interaction/tool_identity.ts +65 -0
  33. package/src/interaction/types.ts +282 -0
  34. package/src/models/context_limits.ts +8 -0
  35. package/src/models/execution_provider.ts +22 -0
  36. package/src/models/gateways.ts +73 -0
  37. package/src/models/ids.ts +26 -0
  38. package/src/models/provider_defaults.ts +47 -0
  39. package/src/models/runtime_overrides.ts +221 -0
  40. package/src/observability/errors.ts +25 -0
  41. package/src/platform/platform.ts +204 -0
  42. package/src/platform/routing_contract.ts +6 -0
  43. package/src/protocol/input/anthropic_messages.ts +531 -0
  44. package/src/protocol/input/chat_completions.ts +255 -0
  45. package/src/protocol/input/chat_completions_validation.ts +293 -0
  46. package/src/protocol/input/openai_responses.ts +749 -0
  47. package/src/protocol/input/router_model.ts +53 -0
  48. package/src/protocol/output/anthropic_messages.ts +32 -0
  49. package/src/protocol/output/anthropic_messages_output.ts +129 -0
  50. package/src/protocol/output/anthropic_messages_stream.ts +281 -0
  51. package/src/protocol/output/chat_completions.ts +451 -0
  52. package/src/protocol/output/chat_reasoning_detail.ts +19 -0
  53. package/src/protocol/output/delivered_stream_snapshot.ts +31 -0
  54. package/src/protocol/output/openai_responses.ts +30 -0
  55. package/src/protocol/output/openai_responses_output.ts +159 -0
  56. package/src/protocol/output/openai_responses_stream.ts +631 -0
  57. package/src/protocol/output/sse_stream.ts +102 -0
  58. package/src/providers/anthropic_safeguards.ts +115 -0
  59. package/src/providers/aws_assume_role.ts +147 -0
  60. package/src/providers/cancel_estimate.ts +140 -0
  61. package/src/providers/execution.ts +800 -0
  62. package/src/providers/model_capabilities.ts +50 -0
  63. package/src/providers/pi.ts +499 -0
  64. package/src/providers/pi_context.ts +466 -0
  65. package/src/providers/pi_options.ts +416 -0
  66. package/src/providers/pi_output.ts +500 -0
  67. package/src/providers/provider_attempt_runner.ts +153 -0
  68. package/src/providers/provider_call.ts +433 -0
  69. package/src/providers/provider_reported_cost.ts +138 -0
  70. package/src/providers/reasoning.ts +59 -0
  71. package/src/providers/response_capture.ts +65 -0
  72. package/src/providers/stream_finalization.ts +264 -0
  73. package/src/providers/subscription_limits.ts +208 -0
  74. package/src/providers/subscription_usage.ts +99 -0
  75. package/src/runtime/claude_code/auxiliary_routing.ts +80 -0
  76. package/src/runtime/customer_disconnect.ts +66 -0
  77. package/src/runtime/explicit_model.ts +86 -0
  78. package/src/runtime/harness_identity/conversation.ts +87 -0
  79. package/src/runtime/harness_identity/extract.ts +323 -0
  80. package/src/runtime/harness_identity/index.ts +14 -0
  81. package/src/runtime/prepare_routed_completion.ts +224 -0
  82. package/src/runtime/provider_stream_lifecycle.ts +105 -0
  83. package/src/runtime/provider_stream_outcome.ts +83 -0
  84. package/src/runtime/request_tags.ts +34 -0
  85. package/src/runtime/routed_completion.ts +102 -0
  86. package/src/runtime/routed_protocol.ts +33 -0
  87. package/src/runtime/routed_runtime.ts +722 -0
  88. package/src/runtime/routing_lease.ts +273 -0
  89. package/src/runtime/runtime_reporter.ts +115 -0
  90. package/src/self_host/config.ts +173 -0
  91. package/src/self_host/main.ts +104 -0
  92. package/src/self_host/platform.ts +63 -0
  93. package/src/self_host/prefix_store.ts +315 -0
  94. package/src/self_host/resolve.ts +240 -0
  95. package/src/self_host/subscriptions/access.ts +43 -0
  96. package/src/self_host/subscriptions/http.ts +204 -0
  97. package/src/self_host/subscriptions/index.ts +43 -0
  98. package/src/self_host/subscriptions/oauth.ts +395 -0
  99. package/src/self_host/subscriptions/store.ts +339 -0
  100. package/src/strategies/auto_routing_selector.ts +72 -0
  101. package/src/strategies/eval_relevance.ts +57 -0
  102. package/src/strategies/fallback_decision.ts +30 -0
  103. package/src/strategies/priority_selector.ts +40 -0
  104. package/src/strategies/route_decision.ts +106 -0
  105. package/src/strategies/routing.ts +455 -0
  106. package/src/strategies/selector_projection.ts +207 -0
  107. package/src/telemetry/background.ts +40 -0
  108. package/src/telemetry/benchmark_replay.ts +160 -0
  109. package/src/telemetry/billing_finalization.ts +167 -0
  110. package/src/telemetry/ingest_values.ts +15 -0
  111. package/src/telemetry/model_cost.ts +14 -0
  112. package/src/telemetry/prefix_state.ts +183 -0
  113. package/src/telemetry/report.ts +832 -0
  114. package/src/telemetry/requests/interaction_observability.ts +258 -0
  115. package/src/telemetry/requests/retained_interaction_request.ts +20 -0
  116. package/src/telemetry/scrub.ts +38 -0
  117. package/src/telemetry/skills/claude/catalog.ts +119 -0
  118. package/src/telemetry/skills/claude/file_reads.ts +153 -0
  119. package/src/telemetry/skills/claude/observations.ts +450 -0
  120. package/src/telemetry/skills/codex/catalog.ts +171 -0
  121. package/src/telemetry/skills/codex/exec_file_reads.ts +55 -0
  122. package/src/telemetry/skills/codex/explicit.ts +116 -0
  123. package/src/telemetry/skills/codex/file_reads.ts +51 -0
  124. package/src/telemetry/skills/codex/identity.ts +21 -0
  125. package/src/telemetry/skills/observations.ts +94 -0
  126. package/src/telemetry/skills/paths.ts +82 -0
  127. package/src/telemetry/skills/pi.ts +276 -0
  128. package/src/telemetry/skills/shell_file_reads.ts +267 -0
  129. package/src/telemetry/skills/shell_words.ts +202 -0
  130. package/src/telemetry/tools/input.ts +16 -0
  131. package/src/telemetry/tools/observations.ts +349 -0
  132. package/src/telemetry/usage.ts +173 -0
  133. package/src/types.ts +150 -0
@@ -0,0 +1,450 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+
3
+ import type {
4
+ InteractionMessage,
5
+ InteractionRequest,
6
+ InteractionToolCall,
7
+ InteractionToolResult,
8
+ } from "../../../interaction/types";
9
+ import type {
10
+ SkillEvidenceSource,
11
+ SkillObservation,
12
+ } from "../observations";
13
+ import {
14
+ claudeAvailableSkillNames,
15
+ claudeSkillCapabilityId,
16
+ normalizedClaudeSkillName,
17
+ } from "./catalog";
18
+
19
+ const MAX_SKILL_PATH_CHARS = 16 * 1024;
20
+ const UNSAFE_DISPLAY_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u;
21
+ const BUDGET_REMINDER_PREFIX = "\n\n<system-reminder>\nUSD budget: ";
22
+ const BUDGET_REMINDER_SUFFIX = "\n</system-reminder>";
23
+
24
+ export function claudeSkillObservations(
25
+ request: InteractionRequest,
26
+ limit: number,
27
+ ): SkillObservation[] {
28
+ return request.requestPurpose === "tool_continuation"
29
+ ? confirmedSkillObservations(request, limit)
30
+ : request.requestPurpose === undefined
31
+ ? directSkillObservations(request, limit)
32
+ : [];
33
+ }
34
+
35
+ function directSkillObservations(
36
+ request: InteractionRequest,
37
+ limit: number,
38
+ ): SkillObservation[] {
39
+ const message = latestUserMessage(request);
40
+ if (message === undefined) return [];
41
+ const availableSkills = claudeAvailableSkillNames(request);
42
+ return directSkillNames(message, availableSkills)
43
+ .slice(0, limit)
44
+ .map((name) => observation(name, null, "skill_command_expansion"));
45
+ }
46
+
47
+ function confirmedSkillObservations(
48
+ request: InteractionRequest,
49
+ limit: number,
50
+ ): SkillObservation[] {
51
+ const confirmedGroups: SkillObservation[][] = [];
52
+ let confirmedCount = 0;
53
+ const skillCallsByResultIndex = callsByResultIndex(request);
54
+ const availableSkills = claudeAvailableSkillNames(request);
55
+ let index = request.items.length - 1;
56
+ while (index >= 0) {
57
+ while (index >= 0 && isBudgetStatusMessage(request.items[index])) index -= 1;
58
+ if (index < 0) break;
59
+ const expansionEvidence = skillExpansionEvidence(request.items[index]);
60
+ let resultStart = expansionEvidence === undefined ? index + 1 : index;
61
+ while (resultStart > 0) {
62
+ const item = request.items[resultStart - 1];
63
+ if (item.type !== "tool_result") break;
64
+ resultStart -= 1;
65
+ }
66
+ const resultEnd = expansionEvidence === undefined ? index + 1 : index;
67
+ if (resultStart === resultEnd) break;
68
+
69
+ const remaining = limit - confirmedCount;
70
+ const group: SkillObservation[] = [];
71
+ let inlineCount = 0;
72
+ let forkedCount = 0;
73
+ for (let resultIndex = resultStart; resultIndex < resultEnd; resultIndex += 1) {
74
+ const item = request.items[resultIndex];
75
+ if (item.type !== "tool_result") break;
76
+ const call = skillCallsByResultIndex.get(resultIndex);
77
+ const output = toolResultText(item);
78
+ if (call === undefined || item.isError === true || output === undefined) continue;
79
+ if (isInlineSkillResult(output, call.name)) {
80
+ if (expansionEvidence !== undefined) {
81
+ const evidence = expansionEvidence[inlineCount];
82
+ if (evidence?.name !== undefined && evidence.name !== call.name) {
83
+ return orderedGroups(confirmedGroups);
84
+ }
85
+ const redundantDirectInvocation = evidence?.name !== undefined
86
+ && latestUserBeforeCallIncludesDirectSkill(
87
+ request,
88
+ call.callIndex,
89
+ call.name,
90
+ availableSkills,
91
+ );
92
+ if (!redundantDirectInvocation && group.length < remaining) {
93
+ group.push(observation(
94
+ call.name,
95
+ item.callId,
96
+ "skill_tool_activation",
97
+ ));
98
+ }
99
+ }
100
+ inlineCount += 1;
101
+ continue;
102
+ }
103
+ if (isForkedSkillResult(output, call.name)) {
104
+ forkedCount += 1;
105
+ if (group.length < remaining) {
106
+ group.push(observation(
107
+ call.name,
108
+ item.callId,
109
+ "skill_tool_activation",
110
+ ));
111
+ }
112
+ }
113
+ }
114
+ if (expansionEvidence === undefined) {
115
+ if (forkedCount === 0) break;
116
+ } else if (inlineCount !== expansionEvidence.length) {
117
+ break;
118
+ }
119
+
120
+ confirmedGroups.push(group);
121
+ confirmedCount += group.length;
122
+ if (confirmedCount === limit) break;
123
+ index = resultStart - 1;
124
+ }
125
+ return orderedGroups(confirmedGroups);
126
+ }
127
+
128
+ function isBudgetStatusMessage(
129
+ item: InteractionRequest["items"][number],
130
+ ): boolean {
131
+ if (
132
+ item.type !== "message"
133
+ || (item.role !== "system" && item.role !== "developer")
134
+ || item.content.length !== 1
135
+ || item.content[0].type !== "text"
136
+ ) {
137
+ return false;
138
+ }
139
+ const lines = item.content[0].text.split("\n\n");
140
+ return lines.length > 0 && lines.every((line) => {
141
+ if (!line.startsWith("USD budget: ")) return false;
142
+ const value = line.slice("USD budget: ".length);
143
+ return value.length > 0 && value.length <= 256 && !/[\n<>]/u.test(value);
144
+ });
145
+ }
146
+
147
+ function orderedGroups(groups: SkillObservation[][]): SkillObservation[] {
148
+ groups.reverse();
149
+ return groups.flat();
150
+ }
151
+
152
+ function skillCallName(item: InteractionToolCall): string | undefined {
153
+ const input = item.input;
154
+ if (
155
+ item.kind !== "function"
156
+ || item.namespace !== undefined
157
+ || item.name !== "Skill"
158
+ || !isRecord(input)
159
+ ) {
160
+ return undefined;
161
+ }
162
+
163
+ const inputKeys = Object.keys(input);
164
+ if (
165
+ inputKeys.some((key) => key !== "skill" && key !== "args")
166
+ || (input.args !== undefined && typeof input.args !== "string")
167
+ ) {
168
+ return undefined;
169
+ }
170
+ return normalizedClaudeSkillName(input.skill);
171
+ }
172
+
173
+ function callsByResultIndex(
174
+ request: InteractionRequest,
175
+ ): Map<number, { name: string; callIndex: number }> {
176
+ const latestCalls = new Map<string, { name: string; callIndex: number } | null>();
177
+ const resultCalls = new Map<number, { name: string; callIndex: number }>();
178
+ for (let index = 0; index < request.items.length; index += 1) {
179
+ const item = request.items[index];
180
+ if (item.type === "tool_call") {
181
+ const name = skillCallName(item);
182
+ latestCalls.set(item.callId, name === undefined ? null : { name, callIndex: index });
183
+ continue;
184
+ }
185
+ if (item.type !== "tool_result") continue;
186
+ const call = latestCalls.get(item.callId);
187
+ if (call !== undefined && call !== null) resultCalls.set(index, call);
188
+ }
189
+ return resultCalls;
190
+ }
191
+
192
+ function skillExpansionEvidence(
193
+ item: InteractionRequest["items"][number],
194
+ ): Array<{ name?: string }> | undefined {
195
+ if (item.type !== "message" || item.role !== "user" || item.content.length === 0) {
196
+ return undefined;
197
+ }
198
+ const evidence: Array<{ name?: string }> = [];
199
+ for (const part of item.content) {
200
+ if (part.type !== "text") return undefined;
201
+ if (isSkillExpansion(part.text)) {
202
+ evidence.push({});
203
+ continue;
204
+ }
205
+ const name = alreadyLoadedSkillName(part.text);
206
+ if (name === undefined) return undefined;
207
+ evidence.push({ name });
208
+ }
209
+ return evidence;
210
+ }
211
+
212
+ function isForkedSkillResult(output: string, name: string): boolean {
213
+ const normalized = withoutBudgetReminders(output);
214
+ if (normalized === undefined) return false;
215
+ const launched = `Skill "${name}" launched (forked execution, running in the background).`;
216
+ if (
217
+ normalized === launched
218
+ || normalized === `${launched}\n\nRunning in the background as @${name}`
219
+ ) {
220
+ return true;
221
+ }
222
+ const completed = `Skill "${name}" completed (forked execution).\n\nResult:\n`;
223
+ return normalized.startsWith(completed)
224
+ && normalized.slice(completed.length).trim().length > 0;
225
+ }
226
+
227
+ function isInlineSkillResult(output: string, name: string): boolean {
228
+ return withoutBudgetReminders(output) === `Launching skill: ${name}`;
229
+ }
230
+
231
+ function withoutBudgetReminders(output: string): string | undefined {
232
+ const firstReminder = output.indexOf(BUDGET_REMINDER_PREFIX);
233
+ if (firstReminder < 0) return output;
234
+ let cursor = firstReminder;
235
+ while (cursor < output.length) {
236
+ if (!output.startsWith(BUDGET_REMINDER_PREFIX, cursor)) return undefined;
237
+ const valueStart = cursor + BUDGET_REMINDER_PREFIX.length;
238
+ const valueEnd = output.indexOf(BUDGET_REMINDER_SUFFIX, valueStart);
239
+ if (valueEnd < 0) return undefined;
240
+ const value = output.slice(valueStart, valueEnd);
241
+ if (value.length === 0 || value.length > 256 || /[\n<>]/u.test(value)) {
242
+ return undefined;
243
+ }
244
+ cursor = valueEnd + BUDGET_REMINDER_SUFFIX.length;
245
+ }
246
+ return output.slice(0, firstReminder);
247
+ }
248
+
249
+ function latestUserBeforeCallIncludesDirectSkill(
250
+ request: InteractionRequest,
251
+ callIndex: number,
252
+ name: string,
253
+ availableSkills: Set<string>,
254
+ ): boolean {
255
+ for (let index = callIndex - 1; index >= 0; index -= 1) {
256
+ const item = request.items[index];
257
+ if (item.type !== "message" || item.role !== "user") continue;
258
+ return directSkillNames(item, availableSkills).includes(name);
259
+ }
260
+ return false;
261
+ }
262
+
263
+ function alreadyLoadedSkillName(text: string): string | undefined {
264
+ const prefix = "Skill /";
265
+ const marker = " is already loaded above; instructions unchanged.";
266
+ if (!text.startsWith(prefix)) return undefined;
267
+ const markerIndex = text.indexOf(marker, prefix.length);
268
+ if (markerIndex < 0) return undefined;
269
+ const suffix = text.slice(markerIndex + marker.length);
270
+ if (suffix !== "" && !suffix.startsWith(" Arguments:")) return undefined;
271
+ return normalizedClaudeSkillName(text.slice(prefix.length, markerIndex));
272
+ }
273
+
274
+ function directSkillNames(
275
+ message: InteractionMessage,
276
+ availableSkills: Set<string>,
277
+ ): string[] {
278
+ const names: string[] = [];
279
+ for (let index = 0; index < message.content.length; index += 1) {
280
+ const command = message.content[index];
281
+ const expansion = message.content[index + 1];
282
+ if (command.type === "text" && expansion?.type === "text") {
283
+ const name = commandName(command.text);
284
+ if (
285
+ name !== undefined
286
+ && (
287
+ isSkillExpansion(expansion.text)
288
+ || (availableSkills.has(name) && isLegacyCommandBody(expansion.text))
289
+ )
290
+ ) {
291
+ names.push(name);
292
+ index += 1;
293
+ continue;
294
+ }
295
+ }
296
+
297
+ const backgroundName = directBackgroundSkillName(message, index);
298
+ if (backgroundName !== undefined) names.push(backgroundName);
299
+ }
300
+ return names;
301
+ }
302
+
303
+ function isLegacyCommandBody(text: string): boolean {
304
+ const trimmed = text.trim();
305
+ return trimmed.length > 0
306
+ && !trimmed.startsWith("<system-reminder>")
307
+ && !trimmed.startsWith("<local-command-")
308
+ && !trimmed.startsWith("<command-");
309
+ }
310
+
311
+ function directBackgroundSkillName(
312
+ message: InteractionMessage,
313
+ index: number,
314
+ ): string | undefined {
315
+ const current = message.content[index];
316
+ const previous = message.content[index - 1];
317
+ if (current?.type !== "text" || previous?.type !== "text") return undefined;
318
+
319
+ const lines = current.text.trimEnd().split("\n");
320
+ if (lines.length !== 2) return undefined;
321
+ const stdoutPrefix = "<local-command-stdout>Running in the background as @";
322
+ const stdoutSuffix = "</local-command-stdout>";
323
+ if (!lines[0]?.startsWith(stdoutPrefix) || !lines[0].endsWith(stdoutSuffix)) {
324
+ return undefined;
325
+ }
326
+ const stdoutName = normalizedClaudeSkillName(
327
+ lines[0].slice(stdoutPrefix.length, -stdoutSuffix.length),
328
+ );
329
+
330
+ const launchPrefix = "<forked-skill-launch>";
331
+ const launchSuffix = "</forked-skill-launch>";
332
+ const launchLine = lines[1];
333
+ if (!launchLine?.startsWith(launchPrefix) || !launchLine.endsWith(launchSuffix)) {
334
+ return undefined;
335
+ }
336
+
337
+ let launch: unknown;
338
+ try {
339
+ launch = JSON.parse(launchLine.slice(launchPrefix.length, -launchSuffix.length));
340
+ } catch {
341
+ return undefined;
342
+ }
343
+ if (!isRecord(launch) || Object.keys(launch).some(
344
+ (key) => key !== "agentId" && key !== "skillName" && key !== "description",
345
+ )) {
346
+ return undefined;
347
+ }
348
+ const name = normalizedClaudeSkillName(launch.skillName);
349
+ if (
350
+ name === undefined
351
+ || stdoutName !== name
352
+ || typeof launch.agentId !== "string"
353
+ || !/^[a-f0-9]{16,64}$/u.test(launch.agentId)
354
+ || typeof launch.description !== "string"
355
+ || (launch.description !== `/${name}` && !launch.description.startsWith(`/${name} `))
356
+ ) {
357
+ return undefined;
358
+ }
359
+
360
+ const command = previous.text.trimEnd();
361
+ return command === `/${name}` || command.startsWith(`/${name} `)
362
+ ? name
363
+ : undefined;
364
+ }
365
+
366
+ function toolResultText(result: InteractionToolResult): string | undefined {
367
+ if (typeof result.output === "string") return result.output;
368
+ if (
369
+ Array.isArray(result.output)
370
+ && result.output.length === 1
371
+ && result.output[0].type === "text"
372
+ ) {
373
+ return result.output[0].text;
374
+ }
375
+ return undefined;
376
+ }
377
+
378
+ function latestUserMessage(
379
+ request: InteractionRequest,
380
+ ): InteractionMessage | undefined {
381
+ for (let index = request.items.length - 1; index >= 0; index -= 1) {
382
+ const item = request.items[index];
383
+ if (item.type === "message" && (item.role === "system" || item.role === "developer")) {
384
+ continue;
385
+ }
386
+ return item.type === "message" && item.role === "user" ? item : undefined;
387
+ }
388
+ return undefined;
389
+ }
390
+
391
+ function commandName(text: string): string | undefined {
392
+ const firstBreak = text.indexOf("\n");
393
+ const secondBreak = firstBreak < 0 ? -1 : text.indexOf("\n", firstBreak + 1);
394
+ if (firstBreak < 0 || secondBreak < 0) return undefined;
395
+
396
+ const firstLine = text.slice(0, firstBreak);
397
+ const secondLine = text.slice(firstBreak + 1, secondBreak);
398
+ const rest = text.slice(secondBreak + 1);
399
+ const name = exactTagValue(firstLine, "command-message");
400
+ const hasExactArguments = rest.startsWith("<command-args>")
401
+ && (rest.endsWith("</command-args>") || rest.endsWith("</command-args>\n"));
402
+ if (
403
+ name === undefined
404
+ || secondLine !== `<command-name>/${name}</command-name>`
405
+ || (rest !== "" && !hasExactArguments)
406
+ ) {
407
+ return undefined;
408
+ }
409
+ return normalizedClaudeSkillName(name);
410
+ }
411
+
412
+ function isSkillExpansion(text: string): boolean {
413
+ const prefix = "Base directory for this skill: ";
414
+ if (!text.startsWith(prefix)) return false;
415
+ const pathEnd = text.indexOf("\n", prefix.length);
416
+ if (pathEnd < 0 || !text.slice(pathEnd).startsWith("\n\n")) return false;
417
+ const path = normalizedSkillPath(text.slice(prefix.length, pathEnd));
418
+ return path !== undefined && text.slice(pathEnd + 2).trim().length > 0;
419
+ }
420
+
421
+ function exactTagValue(line: string, tag: string): string | undefined {
422
+ const prefix = `<${tag}>`;
423
+ const suffix = `</${tag}>`;
424
+ return line.startsWith(prefix) && line.endsWith(suffix)
425
+ ? line.slice(prefix.length, -suffix.length)
426
+ : undefined;
427
+ }
428
+
429
+ function observation(
430
+ name: string,
431
+ toolCallId: string | null,
432
+ evidenceSource: SkillEvidenceSource,
433
+ ): SkillObservation {
434
+ return {
435
+ eventType: "skill_use",
436
+ toolCallId,
437
+ capabilityId: claudeSkillCapabilityId(name),
438
+ observedName: name,
439
+ evidenceSource,
440
+ };
441
+ }
442
+
443
+ function normalizedSkillPath(value: string): string | undefined {
444
+ const normalized = value.normalize("NFC");
445
+ return normalized.length > 0
446
+ && normalized.length <= MAX_SKILL_PATH_CHARS
447
+ && !UNSAFE_DISPLAY_CHARACTERS.test(normalized)
448
+ ? normalized
449
+ : undefined;
450
+ }
@@ -0,0 +1,171 @@
1
+ import type { InteractionRequest } from "../../../interaction/types";
2
+ import { normalizedCodexSkillName } from "./identity";
3
+ import {
4
+ joinedSkillPath,
5
+ normalizedAbsoluteSkillPath,
6
+ skillPathBasename,
7
+ type NormalizedSkillPath,
8
+ type PathPlatform,
9
+ } from "../paths";
10
+
11
+ const MAX_CATALOG_ENTRIES = 2_000;
12
+ const SKILLS_OPEN = "<skills_instructions>";
13
+ const SKILLS_CLOSE = "</skills_instructions>";
14
+ const SKILL_ROOTS = "### Skill roots\n";
15
+ const SKILLS_LIST = "### Available skills\n";
16
+ const FILE_LOCATOR = " (file: ";
17
+ const SKILL_ROOT = /^- `(?<alias>r[0-9]+)` = `(?<path>[^`\n]+)`$/u;
18
+
19
+ export type CatalogSkill = {
20
+ name: string;
21
+ path: NormalizedSkillPath;
22
+ };
23
+
24
+ export type CodexSkillCatalog = {
25
+ platform: PathPlatform;
26
+ byPath: ReadonlyMap<string, CatalogSkill>;
27
+ };
28
+
29
+ export function codexFileSkillCatalog(
30
+ request: InteractionRequest,
31
+ ): CodexSkillCatalog | undefined {
32
+ const instructionTexts = request.items.flatMap((item) => {
33
+ if (
34
+ item.type !== "message"
35
+ || (item.role !== "developer" && item.role !== "system")
36
+ ) return [];
37
+ return item.content.flatMap((part) => part.type === "text" ? [part.text] : []);
38
+ });
39
+ if (request.instructions !== undefined) instructionTexts.push(request.instructions);
40
+
41
+ let latestCatalog: CodexSkillCatalog | undefined;
42
+ for (const instructionText of instructionTexts) {
43
+ const blocks = skillInstructionBlocks(normalizedLineEndings(instructionText));
44
+ if (blocks === undefined) {
45
+ latestCatalog = undefined;
46
+ continue;
47
+ }
48
+ for (const block of blocks) {
49
+ const listStart = block.indexOf(SKILLS_LIST);
50
+ const roots = listStart < 0
51
+ ? undefined
52
+ : catalogRoots(block.slice(0, listStart));
53
+ latestCatalog = listStart < 0 || roots === undefined
54
+ ? undefined
55
+ : catalogEntries(
56
+ block.slice(listStart + SKILLS_LIST.length).split("\n"),
57
+ roots,
58
+ );
59
+ }
60
+ }
61
+ return latestCatalog;
62
+ }
63
+
64
+ function catalogRoots(
65
+ blockPrefix: string,
66
+ ): Map<string, NormalizedSkillPath> | undefined {
67
+ const roots = new Map<string, NormalizedSkillPath>();
68
+ const rootsStart = blockPrefix.indexOf(SKILL_ROOTS);
69
+ if (rootsStart < 0) return roots;
70
+ let platform: PathPlatform | undefined;
71
+ for (const line of blockPrefix.slice(rootsStart + SKILL_ROOTS.length).split("\n")) {
72
+ if (line.startsWith("### ")) break;
73
+ const match = line.match(SKILL_ROOT);
74
+ if (match?.groups === undefined) continue;
75
+ const path = normalizedAbsoluteSkillPath(match.groups.path);
76
+ if (
77
+ path === undefined
78
+ || roots.has(match.groups.alias)
79
+ || (platform !== undefined && path.platform !== platform)
80
+ ) return undefined;
81
+ platform = path.platform;
82
+ roots.set(match.groups.alias, path);
83
+ if (roots.size > MAX_CATALOG_ENTRIES) return undefined;
84
+ }
85
+ return roots;
86
+ }
87
+
88
+ function catalogEntries(
89
+ lines: string[],
90
+ roots: ReadonlyMap<string, NormalizedSkillPath>,
91
+ ): CodexSkillCatalog | undefined {
92
+ const catalog = new Map<string, CatalogSkill>();
93
+ const ambiguousPaths = new Set<string>();
94
+ let entryCount = 0;
95
+ let platform: PathPlatform | undefined;
96
+ for (const line of lines) {
97
+ if (line.startsWith("### ")) break;
98
+ const skill = catalogSkill(line, roots);
99
+ if (skill === undefined) continue;
100
+ entryCount += 1;
101
+ if (
102
+ entryCount > MAX_CATALOG_ENTRIES
103
+ || (platform !== undefined && skill.path.platform !== platform)
104
+ ) return undefined;
105
+ platform = skill.path.platform;
106
+ if (ambiguousPaths.has(skill.path.key)) continue;
107
+ const previous = catalog.get(skill.path.key);
108
+ if (previous !== undefined && previous.name !== skill.name) {
109
+ catalog.delete(skill.path.key);
110
+ ambiguousPaths.add(skill.path.key);
111
+ } else {
112
+ catalog.set(skill.path.key, skill);
113
+ }
114
+ }
115
+ return platform === undefined || catalog.size === 0
116
+ ? undefined
117
+ : { platform, byPath: catalog };
118
+ }
119
+
120
+ function catalogSkill(
121
+ line: string,
122
+ roots: ReadonlyMap<string, NormalizedSkillPath>,
123
+ ): CatalogSkill | undefined {
124
+ if (!line.startsWith("- ") || !line.endsWith(")")) return undefined;
125
+ const nameEnd = line.indexOf(": ", 2);
126
+ const locatorStart = line.lastIndexOf(FILE_LOCATOR);
127
+ if (nameEnd < 0 || locatorStart <= nameEnd) return undefined;
128
+ const name = normalizedCodexSkillName(line.slice(2, nameEnd));
129
+ const path = catalogPath(
130
+ line.slice(locatorStart + FILE_LOCATOR.length, -1),
131
+ roots,
132
+ );
133
+ return name === undefined
134
+ || path === undefined
135
+ || skillPathBasename(path).toLowerCase() !== "skill.md"
136
+ ? undefined
137
+ : { name, path };
138
+ }
139
+
140
+ function catalogPath(
141
+ locator: string,
142
+ roots: ReadonlyMap<string, NormalizedSkillPath>,
143
+ ): NormalizedSkillPath | undefined {
144
+ const absolute = normalizedAbsoluteSkillPath(locator);
145
+ if (absolute !== undefined) return absolute;
146
+ const separator = locator.indexOf("/");
147
+ if (separator <= 0) return undefined;
148
+ const root = roots.get(locator.slice(0, separator));
149
+ return root === undefined
150
+ ? undefined
151
+ : joinedSkillPath(root, locator.slice(separator + 1));
152
+ }
153
+
154
+ function normalizedLineEndings(value: string): string {
155
+ return value.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
156
+ }
157
+
158
+ function skillInstructionBlocks(text: string): string[] | undefined {
159
+ const blocks: string[] = [];
160
+ let cursor = 0;
161
+ while (cursor < text.length) {
162
+ const start = text.indexOf(SKILLS_OPEN, cursor);
163
+ if (start < 0) break;
164
+ const bodyStart = start + SKILLS_OPEN.length;
165
+ const end = text.indexOf(SKILLS_CLOSE, bodyStart);
166
+ if (end < 0) return undefined;
167
+ blocks.push(text.slice(bodyStart, end));
168
+ cursor = end + SKILLS_CLOSE.length;
169
+ }
170
+ return blocks;
171
+ }
@@ -0,0 +1,55 @@
1
+ import type { InteractionOutput } from "../../../interaction/types";
2
+ import { interactionToolInput } from "../../tools/input";
3
+ import { readPathsFromShellCommand } from "../shell_file_reads";
4
+ import type { CatalogSkill, CodexSkillCatalog } from "./catalog";
5
+
6
+ const MAX_COMMAND_CHARS = 64 * 1024;
7
+ const MAX_SKILL_PATH_CHARS = 16 * 1024;
8
+ const UNSAFE_DISPLAY_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u;
9
+ const UNSAFE_COMMAND_CHARACTERS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u;
10
+
11
+ export type CodexExecCommand = {
12
+ callId: string;
13
+ command: string;
14
+ workdir?: string;
15
+ };
16
+
17
+ export function codexExecCommand(
18
+ item: InteractionOutput["items"][number],
19
+ ): CodexExecCommand | undefined {
20
+ if (
21
+ item.type !== "tool_call"
22
+ || item.kind !== "function"
23
+ || item.namespace !== undefined
24
+ || item.name !== "exec_command"
25
+ ) return undefined;
26
+ const input = interactionToolInput(item);
27
+ if (input === undefined) return undefined;
28
+ const command = input.cmd;
29
+ const workdir = input.workdir;
30
+ if (
31
+ typeof command !== "string"
32
+ || command.length === 0
33
+ || command.length > MAX_COMMAND_CHARS
34
+ || UNSAFE_COMMAND_CHARACTERS.test(command)
35
+ || (workdir !== undefined && (
36
+ typeof workdir !== "string"
37
+ || workdir.length === 0
38
+ || workdir.length > MAX_SKILL_PATH_CHARS
39
+ || UNSAFE_DISPLAY_CHARACTERS.test(workdir)
40
+ ))
41
+ ) return undefined;
42
+ return workdir === undefined
43
+ ? { callId: item.callId, command }
44
+ : { callId: item.callId, command, workdir };
45
+ }
46
+
47
+ export function readSkillsFromCodexCommand(
48
+ input: CodexExecCommand,
49
+ catalog: CodexSkillCatalog,
50
+ ): CatalogSkill[] {
51
+ return readPathsFromShellCommand(input, catalog.platform).flatMap((path) => {
52
+ const skill = catalog.byPath.get(path.key);
53
+ return skill === undefined ? [] : [skill];
54
+ });
55
+ }