xtrium 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.
- package/LICENSE +21 -0
- package/README.md +75 -2
- package/assets/fonts/ibm-plex-mono-LICENSE.txt +93 -0
- package/assets/fonts/ibm-plex-mono-latin-500-normal.woff +0 -0
- package/assets/fonts/ibm-plex-mono-latin-600-normal.woff +0 -0
- package/assets/fonts/inter-LICENSE.txt +93 -0
- package/assets/fonts/inter-latin-500-normal.woff +0 -0
- package/assets/fonts/inter-latin-700-normal.woff +0 -0
- package/dist/index.js +4348 -0
- package/package.json +45 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,4348 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { Command } from "commander";
|
|
5
|
+
|
|
6
|
+
// src/commands/account.ts
|
|
7
|
+
import { spinner } from "@clack/prompts";
|
|
8
|
+
|
|
9
|
+
// package.json
|
|
10
|
+
var package_default = {
|
|
11
|
+
name: "xtrium",
|
|
12
|
+
version: "0.2.0",
|
|
13
|
+
description: "Upload a redacted, reviewed record of how you work with AI coding tools to your Xtrium Atrium.",
|
|
14
|
+
homepage: "https://xtrium.co",
|
|
15
|
+
license: "MIT",
|
|
16
|
+
type: "module",
|
|
17
|
+
bin: {
|
|
18
|
+
xtrium: "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
files: [
|
|
21
|
+
"dist",
|
|
22
|
+
"assets",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
engines: {
|
|
26
|
+
node: ">=22"
|
|
27
|
+
},
|
|
28
|
+
scripts: {
|
|
29
|
+
build: "tsup",
|
|
30
|
+
dev: "tsup --watch",
|
|
31
|
+
lint: "eslint .",
|
|
32
|
+
typecheck: "tsc --noEmit",
|
|
33
|
+
test: "vitest run"
|
|
34
|
+
},
|
|
35
|
+
dependencies: {
|
|
36
|
+
"@clack/prompts": "1.8.1",
|
|
37
|
+
"@napi-rs/keyring": "2.1.2",
|
|
38
|
+
"@resvg/resvg-js": "2.6.2",
|
|
39
|
+
commander: "15.0.0",
|
|
40
|
+
"libphonenumber-js": "1.13.14",
|
|
41
|
+
satori: "0.63.2",
|
|
42
|
+
zod: "4.6.7"
|
|
43
|
+
},
|
|
44
|
+
devDependencies: {
|
|
45
|
+
"@types/node": "^26.6.6",
|
|
46
|
+
"@types/react": "^19.3.0",
|
|
47
|
+
"@xtrium/ai-workflow": "workspace:*",
|
|
48
|
+
"@xtrium/config": "workspace:*",
|
|
49
|
+
"@xtrium/redact": "workspace:*",
|
|
50
|
+
"@xtrium/schemas": "workspace:*",
|
|
51
|
+
"@xtrium/ui": "workspace:*",
|
|
52
|
+
eslint: "^10.14.0",
|
|
53
|
+
tsup: "9.0.0",
|
|
54
|
+
typescript: "^7.0.2",
|
|
55
|
+
vitest: "^5.1.0"
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// ../../packages/schemas/src/cli.ts
|
|
60
|
+
import { z } from "zod";
|
|
61
|
+
var CLI_TOKEN_SCOPES = ["ai_workflow:upload"];
|
|
62
|
+
var cliTokenScopeSchema = z.enum(CLI_TOKEN_SCOPES);
|
|
63
|
+
var USER_CODE_ALPHABET = "ABCDEFGHJKMNPQRTUVWXY346789";
|
|
64
|
+
var USER_CODE_LENGTH = 8;
|
|
65
|
+
var USER_CODE_PATTERN = new RegExp(`^[${USER_CODE_ALPHABET}]+$`);
|
|
66
|
+
var userCodeSchema = z.string().trim().toUpperCase().transform((value) => value.replace(/[\s-]/g, "")).pipe(
|
|
67
|
+
z.string().length(USER_CODE_LENGTH, "Enter the 8-character code shown in your terminal.").regex(USER_CODE_PATTERN, "That code contains characters the CLI never shows.")
|
|
68
|
+
).transform((value) => `${value.slice(0, 4)}-${value.slice(4)}`);
|
|
69
|
+
var deviceCodeRequestSchema = z.object({ client_name: z.string().trim().min(1).max(64).optional() }).strict();
|
|
70
|
+
var deviceCodeResponseSchema = z.object({
|
|
71
|
+
device_code: z.string(),
|
|
72
|
+
user_code: z.string(),
|
|
73
|
+
verification_uri: z.url(),
|
|
74
|
+
verification_uri_complete: z.url(),
|
|
75
|
+
expires_in: z.number().int().positive(),
|
|
76
|
+
interval: z.number().int().positive()
|
|
77
|
+
});
|
|
78
|
+
var deviceTokenRequestSchema = z.object({
|
|
79
|
+
grant_type: z.literal("urn:ietf:params:oauth:grant-type:device_code"),
|
|
80
|
+
device_code: z.string().min(1).max(128)
|
|
81
|
+
}).strict();
|
|
82
|
+
var deviceTokenResponseSchema = z.object({
|
|
83
|
+
access_token: z.string(),
|
|
84
|
+
token_type: z.literal("Bearer"),
|
|
85
|
+
scope: cliTokenScopeSchema,
|
|
86
|
+
expires_in: z.number().int().positive()
|
|
87
|
+
});
|
|
88
|
+
var DEVICE_TOKEN_ERRORS = [
|
|
89
|
+
"authorization_pending",
|
|
90
|
+
"slow_down",
|
|
91
|
+
"access_denied",
|
|
92
|
+
"expired_token",
|
|
93
|
+
"invalid_grant"
|
|
94
|
+
];
|
|
95
|
+
var deviceTokenErrorSchema = z.object({ error: z.enum(DEVICE_TOKEN_ERRORS) });
|
|
96
|
+
var whoamiResponseSchema = z.object({
|
|
97
|
+
handle: z.string(),
|
|
98
|
+
scope: cliTokenScopeSchema,
|
|
99
|
+
expires_at: z.iso.datetime()
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
// ../../packages/schemas/src/ai-workflow.ts
|
|
103
|
+
import { z as z2 } from "zod";
|
|
104
|
+
var AI_WORKFLOW_TOOLS = ["claude_code", "codex"];
|
|
105
|
+
var aiWorkflowToolSchema = z2.enum(AI_WORKFLOW_TOOLS);
|
|
106
|
+
var BUNDLE_FORMAT = "xtrium-ai-workflow";
|
|
107
|
+
var BUNDLE_VERSION = 2;
|
|
108
|
+
var MIB = 1024 * 1024;
|
|
109
|
+
var BUNDLE_MAX_BYTES = 64 * MIB;
|
|
110
|
+
var BUNDLE_MAX_UNCOMPRESSED_BYTES = 512 * MIB;
|
|
111
|
+
var BUNDLE_PART_BYTES = 8 * MIB;
|
|
112
|
+
var BUNDLE_MAX_PARTS = Math.ceil(BUNDLE_MAX_BYTES / BUNDLE_PART_BYTES);
|
|
113
|
+
var BUNDLE_MAX_LINE_BYTES = 4 * MIB;
|
|
114
|
+
var BUNDLE_MAX_SESSIONS = 5e3;
|
|
115
|
+
var BUNDLE_MAX_EVENTS_PER_SESSION = 2e4;
|
|
116
|
+
var EVENT_TEXT_MAX = 8e3;
|
|
117
|
+
var INSTRUCTION_TEXT_MAX = 64e3;
|
|
118
|
+
var sha256HexSchema = z2.string().regex(/^[0-9a-f]{64}$/);
|
|
119
|
+
var isoSchema = z2.iso.datetime({ offset: true });
|
|
120
|
+
var shortText = (max) => z2.string().max(max);
|
|
121
|
+
var eventBase = { at: isoSchema.optional() };
|
|
122
|
+
var modelIdSchema = z2.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:/[\]-]{0,99}$/);
|
|
123
|
+
var AI_WORKFLOW_EFFORTS = [
|
|
124
|
+
"none",
|
|
125
|
+
"minimal",
|
|
126
|
+
"low",
|
|
127
|
+
"medium",
|
|
128
|
+
"high",
|
|
129
|
+
"xhigh",
|
|
130
|
+
"max"
|
|
131
|
+
];
|
|
132
|
+
var effortSchema = z2.enum(AI_WORKFLOW_EFFORTS);
|
|
133
|
+
var tokenCountSchema = z2.number().int().min(0).max(1e8);
|
|
134
|
+
var bundleEventSchema = z2.discriminatedUnion("kind", [
|
|
135
|
+
z2.object({ kind: z2.literal("user_prompt"), text: shortText(EVENT_TEXT_MAX + 64), ...eventBase }).strict(),
|
|
136
|
+
z2.object({
|
|
137
|
+
kind: z2.literal("assistant_text"),
|
|
138
|
+
text: shortText(EVENT_TEXT_MAX + 64),
|
|
139
|
+
...eventBase
|
|
140
|
+
}).strict(),
|
|
141
|
+
z2.object({
|
|
142
|
+
kind: z2.literal("tool_call"),
|
|
143
|
+
name: shortText(200),
|
|
144
|
+
argsSummary: shortText(400),
|
|
145
|
+
/** The model a subagent call (`Agent`, `Task`) asked for, when it named one. */
|
|
146
|
+
model: modelIdSchema.optional(),
|
|
147
|
+
...eventBase
|
|
148
|
+
}).strict(),
|
|
149
|
+
z2.object({
|
|
150
|
+
kind: z2.literal("tool_result"),
|
|
151
|
+
summary: shortText(400),
|
|
152
|
+
lines: z2.number().int().min(0),
|
|
153
|
+
exitCode: z2.number().int().optional(),
|
|
154
|
+
...eventBase
|
|
155
|
+
}).strict(),
|
|
156
|
+
z2.object({
|
|
157
|
+
kind: z2.literal("file_edit"),
|
|
158
|
+
path: shortText(1100),
|
|
159
|
+
linesChanged: z2.number().int().min(0),
|
|
160
|
+
...eventBase
|
|
161
|
+
}).strict(),
|
|
162
|
+
/**
|
|
163
|
+
* One model response: the model and effort it ran with (null when not recorded), the context it read (input, cache
|
|
164
|
+
* read and cache creation tokens) and the tokens it wrote. Counts and ids only, never content.
|
|
165
|
+
*/
|
|
166
|
+
z2.object({
|
|
167
|
+
kind: z2.literal("model_turn"),
|
|
168
|
+
model: modelIdSchema.nullable(),
|
|
169
|
+
effort: effortSchema.nullable(),
|
|
170
|
+
contextTokens: tokenCountSchema,
|
|
171
|
+
outputTokens: tokenCountSchema,
|
|
172
|
+
...eventBase
|
|
173
|
+
}).strict(),
|
|
174
|
+
/** The tool compacted the conversation: how it was started and the context before and after, when recorded. */
|
|
175
|
+
z2.object({
|
|
176
|
+
kind: z2.literal("compaction"),
|
|
177
|
+
trigger: z2.enum(["manual", "auto"]).nullable(),
|
|
178
|
+
preTokens: tokenCountSchema.nullable(),
|
|
179
|
+
postTokens: tokenCountSchema.nullable(),
|
|
180
|
+
...eventBase
|
|
181
|
+
}).strict()
|
|
182
|
+
]);
|
|
183
|
+
var countSchema = z2.number().int().min(0);
|
|
184
|
+
var bundleHeaderSchema = z2.object({
|
|
185
|
+
type: z2.literal("header"),
|
|
186
|
+
format: z2.literal(BUNDLE_FORMAT),
|
|
187
|
+
version: z2.union([z2.literal(1), z2.literal(2)]),
|
|
188
|
+
cliVersion: shortText(40).min(1),
|
|
189
|
+
createdAt: isoSchema,
|
|
190
|
+
tools: z2.array(
|
|
191
|
+
z2.object({ tool: aiWorkflowToolSchema, versions: z2.array(shortText(40)).max(100) }).strict()
|
|
192
|
+
).min(1).max(AI_WORKFLOW_TOOLS.length),
|
|
193
|
+
dateRange: z2.object({ start: isoSchema, end: isoSchema }).strict(),
|
|
194
|
+
counts: z2.object({
|
|
195
|
+
sessions: countSchema.max(BUNDLE_MAX_SESSIONS),
|
|
196
|
+
events: countSchema,
|
|
197
|
+
instructionFiles: countSchema,
|
|
198
|
+
setups: countSchema,
|
|
199
|
+
excludedSessions: countSchema,
|
|
200
|
+
excludedEvents: countSchema,
|
|
201
|
+
collapsedOutputs: countSchema
|
|
202
|
+
}).strict(),
|
|
203
|
+
/** What local redaction removed, as counts only (never the removed text). */
|
|
204
|
+
redaction: z2.object({
|
|
205
|
+
secrets: countSchema,
|
|
206
|
+
personal: countSchema,
|
|
207
|
+
blocklist: countSchema,
|
|
208
|
+
paths: countSchema,
|
|
209
|
+
byType: z2.record(z2.string().regex(/^[a-z0-9-]{1,40}$/), countSchema)
|
|
210
|
+
}).strict()
|
|
211
|
+
}).strict();
|
|
212
|
+
var aiWorkflowRedactionCountsSchema = z2.object({
|
|
213
|
+
secrets: countSchema,
|
|
214
|
+
personal: countSchema,
|
|
215
|
+
blocklist: countSchema,
|
|
216
|
+
paths: countSchema
|
|
217
|
+
}).strict();
|
|
218
|
+
var bundleSessionSchema = z2.object({
|
|
219
|
+
type: z2.literal("session"),
|
|
220
|
+
tool: aiWorkflowToolSchema,
|
|
221
|
+
id: shortText(200).min(1),
|
|
222
|
+
project: shortText(1100),
|
|
223
|
+
startedAt: isoSchema,
|
|
224
|
+
endedAt: isoSchema,
|
|
225
|
+
toolVersion: shortText(40).nullable(),
|
|
226
|
+
events: z2.array(bundleEventSchema).max(BUNDLE_MAX_EVENTS_PER_SESSION)
|
|
227
|
+
}).strict();
|
|
228
|
+
var bundleInstructionFileSchema = z2.object({
|
|
229
|
+
type: z2.literal("instruction_file"),
|
|
230
|
+
tool: aiWorkflowToolSchema,
|
|
231
|
+
project: shortText(1100),
|
|
232
|
+
kind: z2.enum(["claude_md", "memory"]),
|
|
233
|
+
/** The file's name (`CLAUDE.md`, a memory file name), redacted. */
|
|
234
|
+
name: shortText(300),
|
|
235
|
+
text: shortText(INSTRUCTION_TEXT_MAX + 64),
|
|
236
|
+
bytes: countSchema
|
|
237
|
+
}).strict();
|
|
238
|
+
var bundleSetupSchema = z2.object({
|
|
239
|
+
type: z2.literal("setup"),
|
|
240
|
+
tool: aiWorkflowToolSchema,
|
|
241
|
+
project: shortText(1100).nullable(),
|
|
242
|
+
skills: z2.array(shortText(120)).max(500),
|
|
243
|
+
hooks: z2.array(z2.object({ event: shortText(60), matcher: shortText(200).nullable() }).strict()).max(500)
|
|
244
|
+
}).strict();
|
|
245
|
+
var bundleBodyRecordSchema = z2.discriminatedUnion("type", [
|
|
246
|
+
bundleSessionSchema,
|
|
247
|
+
bundleInstructionFileSchema,
|
|
248
|
+
bundleSetupSchema
|
|
249
|
+
]);
|
|
250
|
+
var beginUploadRequestSchema = z2.object({
|
|
251
|
+
cliVersion: shortText(40).min(1),
|
|
252
|
+
tools: z2.array(aiWorkflowToolSchema).min(1).max(AI_WORKFLOW_TOOLS.length),
|
|
253
|
+
dateRange: z2.object({ start: isoSchema, end: isoSchema }).strict(),
|
|
254
|
+
sessionCount: z2.number().int().min(1).max(BUNDLE_MAX_SESSIONS),
|
|
255
|
+
sizeBytes: z2.number().int().min(1).max(BUNDLE_MAX_BYTES),
|
|
256
|
+
sha256: sha256HexSchema
|
|
257
|
+
}).strict();
|
|
258
|
+
var beginUploadResponseSchema = z2.object({
|
|
259
|
+
uploadId: z2.uuid(),
|
|
260
|
+
/** `received` when this exact bundle was already accepted (nothing to send again). */
|
|
261
|
+
status: z2.enum(["uploading", "received"]),
|
|
262
|
+
partSize: z2.number().int().positive(),
|
|
263
|
+
partCount: z2.number().int().min(1).max(BUNDLE_MAX_PARTS)
|
|
264
|
+
});
|
|
265
|
+
var PART_URLS_PER_REQUEST = 8;
|
|
266
|
+
var partUrlsRequestSchema = z2.object({
|
|
267
|
+
partNumbers: z2.array(z2.number().int().min(1).max(BUNDLE_MAX_PARTS)).min(1).max(PART_URLS_PER_REQUEST)
|
|
268
|
+
}).strict();
|
|
269
|
+
var partUrlsResponseSchema = z2.object({
|
|
270
|
+
parts: z2.array(
|
|
271
|
+
z2.object({
|
|
272
|
+
partNumber: z2.number().int().min(1),
|
|
273
|
+
url: z2.url(),
|
|
274
|
+
sizeBytes: z2.number().int().positive()
|
|
275
|
+
})
|
|
276
|
+
),
|
|
277
|
+
expiresAt: isoSchema
|
|
278
|
+
});
|
|
279
|
+
var etagSchema = z2.string().regex(/^"?[0-9A-Za-z-]{1,128}"?$/);
|
|
280
|
+
var completeUploadRequestSchema = z2.object({
|
|
281
|
+
parts: z2.array(
|
|
282
|
+
z2.object({ partNumber: z2.number().int().min(1).max(BUNDLE_MAX_PARTS), etag: etagSchema }).strict()
|
|
283
|
+
).min(1).max(BUNDLE_MAX_PARTS),
|
|
284
|
+
signature: z2.string().regex(/^[0-9a-f]{64}$/)
|
|
285
|
+
}).strict();
|
|
286
|
+
var UPLOAD_REJECT_REASONS = [
|
|
287
|
+
"size_mismatch",
|
|
288
|
+
"hash_mismatch",
|
|
289
|
+
"bad_signature",
|
|
290
|
+
"not_gzip",
|
|
291
|
+
"too_large",
|
|
292
|
+
"bad_format",
|
|
293
|
+
"counts_mismatch",
|
|
294
|
+
"unredacted_secret",
|
|
295
|
+
"expired",
|
|
296
|
+
"superseded"
|
|
297
|
+
];
|
|
298
|
+
var uploadRejectReasonSchema = z2.enum(UPLOAD_REJECT_REASONS);
|
|
299
|
+
var completeUploadResponseSchema = z2.discriminatedUnion("status", [
|
|
300
|
+
z2.object({ status: z2.literal("received"), uploadId: z2.uuid() }),
|
|
301
|
+
z2.object({ status: z2.literal("rejected"), uploadId: z2.uuid(), reason: uploadRejectReasonSchema })
|
|
302
|
+
]);
|
|
303
|
+
var uploadErrorSchema = z2.object({
|
|
304
|
+
error: z2.enum([
|
|
305
|
+
"invalid_token",
|
|
306
|
+
"invalid_request",
|
|
307
|
+
"no_atrium",
|
|
308
|
+
"suspended",
|
|
309
|
+
"rate_limited",
|
|
310
|
+
"not_found",
|
|
311
|
+
"not_uploading",
|
|
312
|
+
"upload_incomplete",
|
|
313
|
+
"library_full"
|
|
314
|
+
]),
|
|
315
|
+
message: z2.string().max(300)
|
|
316
|
+
});
|
|
317
|
+
var SIGNATURE_SALT = "xtrium-cli";
|
|
318
|
+
var SIGNATURE_INFO = "ai-workflow-bundle/v1";
|
|
319
|
+
async function signingKey(token) {
|
|
320
|
+
const encoder = new TextEncoder();
|
|
321
|
+
const base = await crypto.subtle.importKey("raw", encoder.encode(token), "HKDF", false, [
|
|
322
|
+
"deriveKey"
|
|
323
|
+
]);
|
|
324
|
+
return crypto.subtle.deriveKey(
|
|
325
|
+
{
|
|
326
|
+
name: "HKDF",
|
|
327
|
+
hash: "SHA-256",
|
|
328
|
+
salt: encoder.encode(SIGNATURE_SALT),
|
|
329
|
+
info: encoder.encode(SIGNATURE_INFO)
|
|
330
|
+
},
|
|
331
|
+
base,
|
|
332
|
+
{ name: "HMAC", hash: "SHA-256", length: 256 },
|
|
333
|
+
false,
|
|
334
|
+
["sign", "verify"]
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
var toHex = (bytes) => Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
338
|
+
var signedMessage = (uploadId, sha256) => new TextEncoder().encode(`${uploadId}:${sha256}`);
|
|
339
|
+
async function signBundle(token, uploadId, sha256) {
|
|
340
|
+
const mac = await crypto.subtle.sign(
|
|
341
|
+
"HMAC",
|
|
342
|
+
await signingKey(token),
|
|
343
|
+
signedMessage(uploadId, sha256)
|
|
344
|
+
);
|
|
345
|
+
return toHex(mac);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ../../packages/schemas/src/ai-workflow-card.ts
|
|
349
|
+
import { z as z3 } from "zod";
|
|
350
|
+
var AI_WORKFLOW_TOPICS = [
|
|
351
|
+
"TypeScript",
|
|
352
|
+
"JavaScript",
|
|
353
|
+
"Python",
|
|
354
|
+
"Ruby",
|
|
355
|
+
"Go",
|
|
356
|
+
"Rust",
|
|
357
|
+
"Java",
|
|
358
|
+
"Kotlin",
|
|
359
|
+
"Swift",
|
|
360
|
+
"C",
|
|
361
|
+
"C++",
|
|
362
|
+
"C#",
|
|
363
|
+
"PHP",
|
|
364
|
+
"Scala",
|
|
365
|
+
"Elixir",
|
|
366
|
+
"SQL",
|
|
367
|
+
"Shell",
|
|
368
|
+
"CSS",
|
|
369
|
+
"HTML",
|
|
370
|
+
"Vue",
|
|
371
|
+
"Svelte",
|
|
372
|
+
"Markdown docs",
|
|
373
|
+
"YAML config",
|
|
374
|
+
"TOML config",
|
|
375
|
+
"Terraform",
|
|
376
|
+
"Docker",
|
|
377
|
+
"Protocol Buffers",
|
|
378
|
+
"GraphQL",
|
|
379
|
+
"Jupyter notebooks",
|
|
380
|
+
"R",
|
|
381
|
+
"Dart",
|
|
382
|
+
"Lua",
|
|
383
|
+
"Zig"
|
|
384
|
+
];
|
|
385
|
+
var aiWorkflowTopicSchema = z3.enum(AI_WORKFLOW_TOPICS);
|
|
386
|
+
var CARD_FEATURES = ["planMode", "todos", "subagents", "mcp", "skillsUsed"];
|
|
387
|
+
var cardFeatureSchema = z3.enum(CARD_FEATURES);
|
|
388
|
+
var CARD_FEATURE_LABELS = {
|
|
389
|
+
planMode: "Plan mode",
|
|
390
|
+
todos: "To-do lists",
|
|
391
|
+
subagents: "Subagents",
|
|
392
|
+
mcp: "MCP tools",
|
|
393
|
+
skillsUsed: "Skills and custom commands"
|
|
394
|
+
};
|
|
395
|
+
var CARD_THEMES = ["retro", "slate"];
|
|
396
|
+
var cardThemeSchema = z3.enum(CARD_THEMES);
|
|
397
|
+
var CARD_TOP = 3;
|
|
398
|
+
var CARD_MIN_CODE_CHANGE_SESSIONS = 5;
|
|
399
|
+
var MAX_COUNT = 1e6;
|
|
400
|
+
var count = z3.number().int().min(0).max(MAX_COUNT);
|
|
401
|
+
var day = z3.iso.date();
|
|
402
|
+
var aiWorkflowCardSchema = z3.object({
|
|
403
|
+
version: z3.literal(1),
|
|
404
|
+
theme: cardThemeSchema,
|
|
405
|
+
sessions: count.min(1),
|
|
406
|
+
/** Distinct days (on the person's clock) with at least one session. */
|
|
407
|
+
activeDays: count.min(1),
|
|
408
|
+
dateRange: z3.object({ start: day, end: day }).strict(),
|
|
409
|
+
tools: z3.array(aiWorkflowToolSchema).min(1).max(2),
|
|
410
|
+
codeChangeSessions: count,
|
|
411
|
+
/** Sessions that changed files and ran a test or build afterwards. */
|
|
412
|
+
verifiedCodeChangeSessions: count,
|
|
413
|
+
features: z3.array(z3.object({ feature: cardFeatureSchema, sessions: count.min(1) }).strict()).max(CARD_TOP),
|
|
414
|
+
/** Empty when the person left topics out (`--no-topics`). */
|
|
415
|
+
topics: z3.array(z3.object({ topic: aiWorkflowTopicSchema, sessions: count.min(1) }).strict()).max(CARD_TOP)
|
|
416
|
+
}).strict().superRefine((card2, ctx) => {
|
|
417
|
+
const issue = (message) => {
|
|
418
|
+
ctx.addIssue({ code: "custom", message });
|
|
419
|
+
};
|
|
420
|
+
if (card2.dateRange.start > card2.dateRange.end) issue("dateRange starts after it ends");
|
|
421
|
+
const spanDays = Math.round((Date.parse(card2.dateRange.end) - Date.parse(card2.dateRange.start)) / 864e5) + 1;
|
|
422
|
+
if (card2.activeDays > Math.min(card2.sessions, spanDays)) {
|
|
423
|
+
issue("activeDays exceeds the sessions or the days in the range");
|
|
424
|
+
}
|
|
425
|
+
if (card2.codeChangeSessions > card2.sessions) issue("codeChangeSessions exceeds sessions");
|
|
426
|
+
if (card2.verifiedCodeChangeSessions > card2.codeChangeSessions) {
|
|
427
|
+
issue("verifiedCodeChangeSessions exceeds codeChangeSessions");
|
|
428
|
+
}
|
|
429
|
+
if (new Set(card2.tools).size !== card2.tools.length) issue("a tool is listed twice");
|
|
430
|
+
for (const list of [card2.features, card2.topics]) {
|
|
431
|
+
if (list.some((entry) => entry.sessions > card2.sessions)) issue("a count exceeds sessions");
|
|
432
|
+
}
|
|
433
|
+
if (new Set(card2.features.map((f) => f.feature)).size !== card2.features.length) {
|
|
434
|
+
issue("a feature is listed twice");
|
|
435
|
+
}
|
|
436
|
+
if (new Set(card2.topics.map((t) => t.topic)).size !== card2.topics.length) {
|
|
437
|
+
issue("a topic is listed twice");
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
function testAfterChangePercent(card2) {
|
|
441
|
+
if (card2.codeChangeSessions < CARD_MIN_CODE_CHANGE_SESSIONS) return null;
|
|
442
|
+
return Math.round(card2.verifiedCodeChangeSessions / card2.codeChangeSessions * 100);
|
|
443
|
+
}
|
|
444
|
+
var shareCardRequestSchema = z3.object({ card: aiWorkflowCardSchema }).strict();
|
|
445
|
+
var shareCardResponseSchema = z3.object({
|
|
446
|
+
url: z3.url(),
|
|
447
|
+
handle: z3.string().min(1).max(64),
|
|
448
|
+
/** False while the Atrium is a draft: the card page shows once the Atrium is published. */
|
|
449
|
+
visible: z3.boolean()
|
|
450
|
+
}).strict();
|
|
451
|
+
|
|
452
|
+
// src/errors.ts
|
|
453
|
+
var CliError = class extends Error {
|
|
454
|
+
name = "CliError";
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
// src/api.ts
|
|
458
|
+
var TIMEOUT_MS = 15e3;
|
|
459
|
+
var COMPLETE_TIMEOUT_MS = 3e5;
|
|
460
|
+
var XtriumApi = class {
|
|
461
|
+
constructor(origin, userAgent, fetchImpl = fetch) {
|
|
462
|
+
this.origin = origin;
|
|
463
|
+
this.userAgent = userAgent;
|
|
464
|
+
this.fetchImpl = fetchImpl;
|
|
465
|
+
}
|
|
466
|
+
origin;
|
|
467
|
+
userAgent;
|
|
468
|
+
fetchImpl;
|
|
469
|
+
async startDeviceLogin(clientName) {
|
|
470
|
+
const response = await this.request("/api/cli/device", {
|
|
471
|
+
method: "POST",
|
|
472
|
+
body: JSON.stringify({ client_name: clientName })
|
|
473
|
+
});
|
|
474
|
+
if (response.status === 429) throw tooMany(response);
|
|
475
|
+
if (!response.ok) throw unexpected(response);
|
|
476
|
+
const body = await readBody(response, deviceCodeResponseSchema);
|
|
477
|
+
if (new URL(body.verification_uri_complete).origin !== this.origin) {
|
|
478
|
+
throw new CliError("The server answered with a sign-in link on another site; stopping.");
|
|
479
|
+
}
|
|
480
|
+
return body;
|
|
481
|
+
}
|
|
482
|
+
async pollDeviceLogin(deviceCode) {
|
|
483
|
+
const response = await this.request("/api/cli/token", {
|
|
484
|
+
method: "POST",
|
|
485
|
+
body: JSON.stringify({
|
|
486
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
487
|
+
device_code: deviceCode
|
|
488
|
+
})
|
|
489
|
+
});
|
|
490
|
+
if (response.ok) {
|
|
491
|
+
return { status: "issued", token: await readBody(response, deviceTokenResponseSchema) };
|
|
492
|
+
}
|
|
493
|
+
if (response.status === 400) {
|
|
494
|
+
return { status: (await readBody(response, deviceTokenErrorSchema)).error };
|
|
495
|
+
}
|
|
496
|
+
if (response.status === 429) throw tooMany(response);
|
|
497
|
+
throw unexpected(response);
|
|
498
|
+
}
|
|
499
|
+
/** Who the token belongs to, or null when the server no longer accepts it (expired or revoked). */
|
|
500
|
+
async whoami(token, timeoutMs = TIMEOUT_MS) {
|
|
501
|
+
const response = await this.request("/api/cli/whoami", { method: "GET" }, token, timeoutMs);
|
|
502
|
+
if (response.status === 401) return null;
|
|
503
|
+
if (!response.ok) throw unexpected(response);
|
|
504
|
+
return readBody(response, whoamiResponseSchema);
|
|
505
|
+
}
|
|
506
|
+
/** Asks the server to revoke the token. Succeeds when the token is already unknown or revoked. */
|
|
507
|
+
async revoke(token) {
|
|
508
|
+
const response = await this.request("/api/cli/token", { method: "DELETE" }, token);
|
|
509
|
+
if (response.status === 429) throw tooMany(response);
|
|
510
|
+
if (!response.ok) throw unexpected(response);
|
|
511
|
+
}
|
|
512
|
+
/** Starts an AI Workflow upload (or finds the one already started for this bundle). */
|
|
513
|
+
async beginUpload(token, body) {
|
|
514
|
+
const response = await this.request(
|
|
515
|
+
"/api/ai-workflow/uploads",
|
|
516
|
+
{ method: "POST", body: JSON.stringify(body) },
|
|
517
|
+
token
|
|
518
|
+
);
|
|
519
|
+
if (!response.ok) throw await uploadFailure(response);
|
|
520
|
+
return readBody(response, beginUploadResponseSchema);
|
|
521
|
+
}
|
|
522
|
+
/** Presigned URLs for some parts of an upload. */
|
|
523
|
+
async partUrls(token, uploadId, partNumbers) {
|
|
524
|
+
const response = await this.request(
|
|
525
|
+
`/api/ai-workflow/uploads/${encodeURIComponent(uploadId)}/parts`,
|
|
526
|
+
{ method: "POST", body: JSON.stringify({ partNumbers }) },
|
|
527
|
+
token
|
|
528
|
+
);
|
|
529
|
+
if (!response.ok) throw await uploadFailure(response);
|
|
530
|
+
return readBody(response, partUrlsResponseSchema);
|
|
531
|
+
}
|
|
532
|
+
/** Finishes an upload: the server checks the bundle and accepts or refuses it. */
|
|
533
|
+
async completeUpload(token, uploadId, body) {
|
|
534
|
+
const response = await this.request(
|
|
535
|
+
`/api/ai-workflow/uploads/${encodeURIComponent(uploadId)}/complete`,
|
|
536
|
+
{ method: "POST", body: JSON.stringify(body) },
|
|
537
|
+
token,
|
|
538
|
+
COMPLETE_TIMEOUT_MS
|
|
539
|
+
);
|
|
540
|
+
if (!response.ok) throw await uploadFailure(response);
|
|
541
|
+
return readBody(response, completeUploadResponseSchema);
|
|
542
|
+
}
|
|
543
|
+
/** Shows the card at `/{handle}/card`, replacing the one shared before. The server draws the image itself. */
|
|
544
|
+
async shareCard(token, card2) {
|
|
545
|
+
const response = await this.request(
|
|
546
|
+
"/api/ai-workflow/card",
|
|
547
|
+
{ method: "PUT", body: JSON.stringify({ card: card2 }) },
|
|
548
|
+
token
|
|
549
|
+
);
|
|
550
|
+
if (!response.ok) throw await uploadFailure(response);
|
|
551
|
+
return readBody(response, shareCardResponseSchema);
|
|
552
|
+
}
|
|
553
|
+
/** Takes the shared card down. Succeeds when none is shared. */
|
|
554
|
+
async unshareCard(token) {
|
|
555
|
+
const response = await this.request("/api/ai-workflow/card", { method: "DELETE" }, token);
|
|
556
|
+
if (!response.ok) throw await uploadFailure(response);
|
|
557
|
+
}
|
|
558
|
+
async request(path, init, token, timeoutMs = TIMEOUT_MS) {
|
|
559
|
+
const headers = {
|
|
560
|
+
accept: "application/json",
|
|
561
|
+
"user-agent": this.userAgent
|
|
562
|
+
};
|
|
563
|
+
if (init.body !== void 0) headers["content-type"] = "application/json";
|
|
564
|
+
if (token !== void 0) headers.authorization = `Bearer ${token}`;
|
|
565
|
+
try {
|
|
566
|
+
return await this.fetchImpl(new URL(path, this.origin), {
|
|
567
|
+
...init,
|
|
568
|
+
headers,
|
|
569
|
+
redirect: "error",
|
|
570
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
571
|
+
});
|
|
572
|
+
} catch {
|
|
573
|
+
throw new CliError(`Could not reach ${this.origin}. Check your connection and try again.`);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
async function readBody(response, schema) {
|
|
578
|
+
let value;
|
|
579
|
+
try {
|
|
580
|
+
value = await response.json();
|
|
581
|
+
} catch {
|
|
582
|
+
throw new CliError("The server sent a response this CLI does not understand.");
|
|
583
|
+
}
|
|
584
|
+
const parsed = schema.safeParse(value);
|
|
585
|
+
if (!parsed.success) {
|
|
586
|
+
throw new CliError(
|
|
587
|
+
"The server sent a response this CLI does not understand. Update xtrium and try again."
|
|
588
|
+
);
|
|
589
|
+
}
|
|
590
|
+
return parsed.data;
|
|
591
|
+
}
|
|
592
|
+
function tooMany(response) {
|
|
593
|
+
const retry = Number(response.headers.get("retry-after"));
|
|
594
|
+
const wait = Number.isFinite(retry) && retry > 0 ? ` Try again in ${Math.ceil(retry / 60)} min.` : "";
|
|
595
|
+
return new CliError(`Too many requests from this network.${wait}`);
|
|
596
|
+
}
|
|
597
|
+
function unexpected(response) {
|
|
598
|
+
return new CliError(`The server answered ${response.status}. Try again later.`);
|
|
599
|
+
}
|
|
600
|
+
async function uploadFailure(response) {
|
|
601
|
+
if (response.status === 401) {
|
|
602
|
+
return new CliError("Your token expired or was revoked. Run `xtrium login` and try again.");
|
|
603
|
+
}
|
|
604
|
+
if (response.status === 429) return tooMany(response);
|
|
605
|
+
let value = null;
|
|
606
|
+
try {
|
|
607
|
+
value = await response.json();
|
|
608
|
+
} catch {
|
|
609
|
+
}
|
|
610
|
+
const parsed = uploadErrorMessageSchema.safeParse(value);
|
|
611
|
+
return parsed.success ? new CliError(parsed.data.message) : unexpected(response);
|
|
612
|
+
}
|
|
613
|
+
var uploadErrorMessageSchema = uploadErrorSchema.pick({ message: true });
|
|
614
|
+
|
|
615
|
+
// src/config.ts
|
|
616
|
+
import { homedir } from "os";
|
|
617
|
+
import { join } from "path";
|
|
618
|
+
import { z as z4 } from "zod";
|
|
619
|
+
var DEFAULT_SERVER = "https://xtrium.co";
|
|
620
|
+
function serverOrigin(env = process.env) {
|
|
621
|
+
const raw = env.XTRIUM_URL?.trim();
|
|
622
|
+
if (raw === void 0 || raw === "") return DEFAULT_SERVER;
|
|
623
|
+
const parsed = z4.url().safeParse(raw);
|
|
624
|
+
if (!parsed.success) throw new CliError(`XTRIUM_URL is not a URL: ${raw}`);
|
|
625
|
+
const url = new URL(parsed.data);
|
|
626
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
|
|
627
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
|
|
628
|
+
throw new CliError("XTRIUM_URL must use https (plain http is allowed only for localhost).");
|
|
629
|
+
}
|
|
630
|
+
return url.origin;
|
|
631
|
+
}
|
|
632
|
+
function configDir(env = process.env) {
|
|
633
|
+
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
634
|
+
if (xdg !== void 0 && xdg !== "") return join(xdg, "xtrium");
|
|
635
|
+
const appData = env.APPDATA?.trim();
|
|
636
|
+
if (process.platform === "win32" && appData !== void 0 && appData !== "") {
|
|
637
|
+
return join(appData, "xtrium");
|
|
638
|
+
}
|
|
639
|
+
return join(homedir(), ".config", "xtrium");
|
|
640
|
+
}
|
|
641
|
+
function sourceRoots(env = process.env) {
|
|
642
|
+
const claude = env.CLAUDE_CONFIG_DIR?.trim();
|
|
643
|
+
const codex = env.CODEX_HOME?.trim();
|
|
644
|
+
return {
|
|
645
|
+
claudeDir: claude !== void 0 && claude !== "" ? claude : join(homedir(), ".claude"),
|
|
646
|
+
codexDir: codex !== void 0 && codex !== "" ? codex : join(homedir(), ".codex")
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/credentials.ts
|
|
651
|
+
import { join as join2 } from "path";
|
|
652
|
+
import { z as z5 } from "zod";
|
|
653
|
+
|
|
654
|
+
// src/private-file.ts
|
|
655
|
+
import { chmod, mkdir, readFile, rename, writeFile } from "fs/promises";
|
|
656
|
+
import { dirname } from "path";
|
|
657
|
+
async function writePrivateFile(path, text) {
|
|
658
|
+
const dir = dirname(path);
|
|
659
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
660
|
+
const temporary = `${path}.${String(process.pid)}.partial`;
|
|
661
|
+
await writeFile(
|
|
662
|
+
temporary,
|
|
663
|
+
text,
|
|
664
|
+
typeof text === "string" ? { encoding: "utf8", mode: 384 } : { mode: 384 }
|
|
665
|
+
);
|
|
666
|
+
await chmod(temporary, 384);
|
|
667
|
+
await rename(temporary, path);
|
|
668
|
+
}
|
|
669
|
+
async function readOptionalFile(path) {
|
|
670
|
+
try {
|
|
671
|
+
return await readFile(path, "utf8");
|
|
672
|
+
} catch (error) {
|
|
673
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return null;
|
|
674
|
+
throw error;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// src/credentials.ts
|
|
679
|
+
var KEYRING_SERVICE = "xtrium";
|
|
680
|
+
var credentialsFileSchema = z5.record(z5.string(), z5.object({ token: z5.string().min(1) }).strict());
|
|
681
|
+
async function systemKeyring() {
|
|
682
|
+
let AsyncEntry;
|
|
683
|
+
try {
|
|
684
|
+
({ AsyncEntry } = await import("@napi-rs/keyring"));
|
|
685
|
+
} catch {
|
|
686
|
+
return null;
|
|
687
|
+
}
|
|
688
|
+
const entry = (account) => new AsyncEntry(KEYRING_SERVICE, account, { linux: { store: "secret-service" } });
|
|
689
|
+
return {
|
|
690
|
+
get: (account) => entry(account).getPassword(),
|
|
691
|
+
set: (account, secret) => entry(account).setPassword(secret),
|
|
692
|
+
delete: async (account) => {
|
|
693
|
+
await entry(account).deletePassword();
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
var CredentialStore = class {
|
|
698
|
+
constructor(dir, keyring) {
|
|
699
|
+
this.dir = dir;
|
|
700
|
+
this.keyring = keyring;
|
|
701
|
+
}
|
|
702
|
+
dir;
|
|
703
|
+
keyring;
|
|
704
|
+
get filePath() {
|
|
705
|
+
return join2(this.dir, "credentials.json");
|
|
706
|
+
}
|
|
707
|
+
/** Saves the token for `origin`, in the keychain when one works, otherwise in the private file. */
|
|
708
|
+
async save(origin, token) {
|
|
709
|
+
if (this.keyring !== null) {
|
|
710
|
+
try {
|
|
711
|
+
await this.keyring.set(origin, token);
|
|
712
|
+
await this.removeFromFile(origin);
|
|
713
|
+
return "keychain";
|
|
714
|
+
} catch {
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
const file = await this.readFile();
|
|
718
|
+
file[origin] = { token };
|
|
719
|
+
await this.writeFile(file);
|
|
720
|
+
return "file";
|
|
721
|
+
}
|
|
722
|
+
async load(origin) {
|
|
723
|
+
if (this.keyring !== null) {
|
|
724
|
+
try {
|
|
725
|
+
const token = await this.keyring.get(origin);
|
|
726
|
+
if (token !== null && token !== "") return token;
|
|
727
|
+
} catch {
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return (await this.readFile())[origin]?.token ?? null;
|
|
731
|
+
}
|
|
732
|
+
/** Removes the token for `origin` from both places. */
|
|
733
|
+
async remove(origin) {
|
|
734
|
+
if (this.keyring !== null) {
|
|
735
|
+
try {
|
|
736
|
+
await this.keyring.delete(origin);
|
|
737
|
+
} catch {
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
await this.removeFromFile(origin);
|
|
741
|
+
}
|
|
742
|
+
async removeFromFile(origin) {
|
|
743
|
+
const file = await this.readFile();
|
|
744
|
+
if (!(origin in file)) return;
|
|
745
|
+
delete file[origin];
|
|
746
|
+
await this.writeFile(file);
|
|
747
|
+
}
|
|
748
|
+
async readFile() {
|
|
749
|
+
const text = await readOptionalFile(this.filePath);
|
|
750
|
+
if (text === null) return {};
|
|
751
|
+
try {
|
|
752
|
+
const parsed = credentialsFileSchema.safeParse(JSON.parse(text));
|
|
753
|
+
return parsed.success ? parsed.data : {};
|
|
754
|
+
} catch {
|
|
755
|
+
return {};
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
async writeFile(file) {
|
|
759
|
+
await writePrivateFile(this.filePath, `${JSON.stringify(file, null, 2)}
|
|
760
|
+
`);
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
|
|
764
|
+
// src/context.ts
|
|
765
|
+
var CLI_VERSION = package_default.version;
|
|
766
|
+
var consoleOutput = {
|
|
767
|
+
info: (text) => {
|
|
768
|
+
process.stdout.write(`${text}
|
|
769
|
+
`);
|
|
770
|
+
},
|
|
771
|
+
error: (text) => {
|
|
772
|
+
process.stderr.write(`${text}
|
|
773
|
+
`);
|
|
774
|
+
}
|
|
775
|
+
};
|
|
776
|
+
function accountContext(keyring) {
|
|
777
|
+
return {
|
|
778
|
+
api: new XtriumApi(serverOrigin(), `xtrium-cli/${CLI_VERSION} node/${process.versions.node}`),
|
|
779
|
+
credentials: new CredentialStore(configDir(), keyring),
|
|
780
|
+
out: consoleOutput,
|
|
781
|
+
sleep: (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)),
|
|
782
|
+
interactive: process.stdout.isTTY
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// src/commands/account.ts
|
|
787
|
+
var SLOW_DOWN_STEP_SECONDS = 5;
|
|
788
|
+
async function login(ctx) {
|
|
789
|
+
const { api, credentials, out } = ctx;
|
|
790
|
+
const existing = await credentials.load(api.origin);
|
|
791
|
+
if (existing !== null) {
|
|
792
|
+
const me2 = await api.whoami(existing);
|
|
793
|
+
if (me2 !== null) {
|
|
794
|
+
out.info(
|
|
795
|
+
`Already signed in as @${me2.handle}. Run \`xtrium logout\` first to switch accounts.`
|
|
796
|
+
);
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
await credentials.remove(api.origin);
|
|
800
|
+
}
|
|
801
|
+
const device = await api.startDeviceLogin(`xtrium CLI ${CLI_VERSION}`);
|
|
802
|
+
out.info("Open this page in your browser, check that it shows the same code, and approve:");
|
|
803
|
+
out.info(` ${device.verification_uri_complete}`);
|
|
804
|
+
out.info(` Code: ${device.user_code}`);
|
|
805
|
+
const wait = ctx.interactive ? spinner() : null;
|
|
806
|
+
wait?.start("Waiting for approval");
|
|
807
|
+
let token;
|
|
808
|
+
try {
|
|
809
|
+
token = await waitForApproval(ctx, device);
|
|
810
|
+
} catch (error) {
|
|
811
|
+
wait?.stop("Not signed in");
|
|
812
|
+
throw error;
|
|
813
|
+
}
|
|
814
|
+
wait?.stop("Approved");
|
|
815
|
+
const location = await credentials.save(api.origin, token);
|
|
816
|
+
const me = await api.whoami(token);
|
|
817
|
+
if (me === null) throw new CliError("The new token was not accepted. Run `xtrium login` again.");
|
|
818
|
+
out.info(`Signed in as @${me.handle}. ${describeToken(me)}`);
|
|
819
|
+
out.info(
|
|
820
|
+
location === "keychain" ? "The token is in your system keychain." : "No system keychain was available, so the token is in credentials.json in the xtrium config folder (readable only by you)."
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
async function waitForApproval(ctx, device) {
|
|
824
|
+
const deadline = Date.now() + device.expires_in * 1e3;
|
|
825
|
+
let intervalSeconds = device.interval;
|
|
826
|
+
while (Date.now() < deadline) {
|
|
827
|
+
await ctx.sleep(intervalSeconds * 1e3);
|
|
828
|
+
const result = await ctx.api.pollDeviceLogin(device.device_code);
|
|
829
|
+
switch (result.status) {
|
|
830
|
+
case "issued":
|
|
831
|
+
return result.token.access_token;
|
|
832
|
+
case "authorization_pending":
|
|
833
|
+
continue;
|
|
834
|
+
case "slow_down":
|
|
835
|
+
intervalSeconds += SLOW_DOWN_STEP_SECONDS;
|
|
836
|
+
continue;
|
|
837
|
+
case "access_denied":
|
|
838
|
+
throw new CliError("The sign-in request was denied.");
|
|
839
|
+
case "expired_token":
|
|
840
|
+
throw new CliError("The code expired. Run `xtrium login` again.");
|
|
841
|
+
case "invalid_grant":
|
|
842
|
+
throw new CliError("This sign-in request is no longer valid. Run `xtrium login` again.");
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
throw new CliError("The code expired. Run `xtrium login` again.");
|
|
846
|
+
}
|
|
847
|
+
async function logout(ctx) {
|
|
848
|
+
const { api, credentials, out } = ctx;
|
|
849
|
+
const token = await credentials.load(api.origin);
|
|
850
|
+
if (token === null) {
|
|
851
|
+
out.info("Not signed in.");
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
let revoked = true;
|
|
855
|
+
try {
|
|
856
|
+
await api.revoke(token);
|
|
857
|
+
} catch {
|
|
858
|
+
revoked = false;
|
|
859
|
+
}
|
|
860
|
+
await credentials.remove(api.origin);
|
|
861
|
+
out.info(
|
|
862
|
+
revoked ? "Signed out. The token was revoked and removed from this machine." : "Signed out on this machine, but the server could not be reached to revoke the token. Revoke it on your account page."
|
|
863
|
+
);
|
|
864
|
+
}
|
|
865
|
+
async function whoami(ctx) {
|
|
866
|
+
const { api, credentials, out } = ctx;
|
|
867
|
+
const token = await credentials.load(api.origin);
|
|
868
|
+
if (token === null) throw new CliError("Not signed in. Run `xtrium login`.");
|
|
869
|
+
const me = await api.whoami(token);
|
|
870
|
+
if (me === null) {
|
|
871
|
+
await credentials.remove(api.origin);
|
|
872
|
+
throw new CliError("Your token expired or was revoked. Run `xtrium login`.");
|
|
873
|
+
}
|
|
874
|
+
out.info(`@${me.handle} on ${api.origin}. ${describeToken(me)}`);
|
|
875
|
+
}
|
|
876
|
+
function describeToken(me) {
|
|
877
|
+
return `The token can upload AI Workflow data only and expires ${me.expires_at.slice(0, 10)}.`;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// src/commands/card.ts
|
|
881
|
+
import { writeFile as writeFile2 } from "fs/promises";
|
|
882
|
+
import { resolve } from "path";
|
|
883
|
+
|
|
884
|
+
// ../../packages/ai-workflow/src/stats.ts
|
|
885
|
+
var PLAN_MODE_TOOLS = /* @__PURE__ */ new Set(["ExitPlanMode", "EnterPlanMode"]);
|
|
886
|
+
var TODO_TOOLS = /* @__PURE__ */ new Set(["TodoWrite", "TaskCreate", "TaskUpdate", "update_plan"]);
|
|
887
|
+
var SUBAGENT_TOOLS = /* @__PURE__ */ new Set(["Agent", "Task"]);
|
|
888
|
+
var SKILL_TOOLS = /* @__PURE__ */ new Set(["Skill"]);
|
|
889
|
+
var SHELL_TOOLS = /* @__PURE__ */ new Set(["Bash", "exec_command", "shell", "local_shell", "PowerShell"]);
|
|
890
|
+
var BUILT_IN_COMMANDS = /* @__PURE__ */ new Set([
|
|
891
|
+
"clear",
|
|
892
|
+
"compact",
|
|
893
|
+
"model",
|
|
894
|
+
"help",
|
|
895
|
+
"effort",
|
|
896
|
+
"config",
|
|
897
|
+
"resume",
|
|
898
|
+
"init",
|
|
899
|
+
"exit",
|
|
900
|
+
"cost",
|
|
901
|
+
"login",
|
|
902
|
+
"logout",
|
|
903
|
+
"status",
|
|
904
|
+
"memory",
|
|
905
|
+
"permissions",
|
|
906
|
+
"agents",
|
|
907
|
+
"mcp",
|
|
908
|
+
"hooks",
|
|
909
|
+
"ide",
|
|
910
|
+
"doctor",
|
|
911
|
+
"fast",
|
|
912
|
+
"context",
|
|
913
|
+
"rewind",
|
|
914
|
+
"usage"
|
|
915
|
+
]);
|
|
916
|
+
var TEST_OR_BUILD = /\b(test|tests|vitest|jest|pytest|mocha|playwright|rspec|phpunit|ctest|tsc|typecheck|build|compile|cargo (test|build|check)|go (test|build|vet)|mvn|gradle|make|dotnet (test|build))\b/i;
|
|
917
|
+
var CORRECTION_START = /^\s*(no\b|nope\b|wrong\b|that'?s (not|wrong)|not (what|quite|right)|try again|again\b|still\b|undo\b|revert\b|stop\b|wait\b|actually\b|instead\b)/i;
|
|
918
|
+
var CORRECTION_PHRASE = /\b(doesn'?t work|didn'?t work|not working|you (missed|forgot|broke|ignored)|that'?s wrong|is wrong|still (fails|failing|broken|wrong))\b/i;
|
|
919
|
+
var TOPICS = {
|
|
920
|
+
ts: "TypeScript",
|
|
921
|
+
tsx: "TypeScript",
|
|
922
|
+
mts: "TypeScript",
|
|
923
|
+
cts: "TypeScript",
|
|
924
|
+
js: "JavaScript",
|
|
925
|
+
jsx: "JavaScript",
|
|
926
|
+
mjs: "JavaScript",
|
|
927
|
+
cjs: "JavaScript",
|
|
928
|
+
py: "Python",
|
|
929
|
+
rb: "Ruby",
|
|
930
|
+
go: "Go",
|
|
931
|
+
rs: "Rust",
|
|
932
|
+
java: "Java",
|
|
933
|
+
kt: "Kotlin",
|
|
934
|
+
swift: "Swift",
|
|
935
|
+
c: "C",
|
|
936
|
+
h: "C",
|
|
937
|
+
cc: "C++",
|
|
938
|
+
cpp: "C++",
|
|
939
|
+
hpp: "C++",
|
|
940
|
+
cs: "C#",
|
|
941
|
+
php: "PHP",
|
|
942
|
+
scala: "Scala",
|
|
943
|
+
ex: "Elixir",
|
|
944
|
+
exs: "Elixir",
|
|
945
|
+
sql: "SQL",
|
|
946
|
+
sh: "Shell",
|
|
947
|
+
bash: "Shell",
|
|
948
|
+
zsh: "Shell",
|
|
949
|
+
css: "CSS",
|
|
950
|
+
scss: "CSS",
|
|
951
|
+
html: "HTML",
|
|
952
|
+
vue: "Vue",
|
|
953
|
+
svelte: "Svelte",
|
|
954
|
+
md: "Markdown docs",
|
|
955
|
+
mdx: "Markdown docs",
|
|
956
|
+
yml: "YAML config",
|
|
957
|
+
yaml: "YAML config",
|
|
958
|
+
toml: "TOML config",
|
|
959
|
+
tf: "Terraform",
|
|
960
|
+
dockerfile: "Docker",
|
|
961
|
+
proto: "Protocol Buffers",
|
|
962
|
+
graphql: "GraphQL",
|
|
963
|
+
ipynb: "Jupyter notebooks",
|
|
964
|
+
r: "R",
|
|
965
|
+
dart: "Dart",
|
|
966
|
+
lua: "Lua",
|
|
967
|
+
zig: "Zig"
|
|
968
|
+
};
|
|
969
|
+
var MAX_TOPICS = 12;
|
|
970
|
+
function topicOf(path) {
|
|
971
|
+
const name = path.split(/[\\/]/).pop()?.toLowerCase() ?? "";
|
|
972
|
+
if (name === "dockerfile") return TOPICS.dockerfile ?? null;
|
|
973
|
+
const dot = name.lastIndexOf(".");
|
|
974
|
+
if (dot <= 0) return null;
|
|
975
|
+
return TOPICS[name.slice(dot + 1)] ?? null;
|
|
976
|
+
}
|
|
977
|
+
function isSlashCommand(text) {
|
|
978
|
+
const match = /^\/([a-z0-9][a-z0-9:_-]{0,60})(\s|$)/i.exec(text.trim());
|
|
979
|
+
return match?.[1]?.toLowerCase() ?? null;
|
|
980
|
+
}
|
|
981
|
+
function isCorrection(text) {
|
|
982
|
+
return CORRECTION_START.test(text) || CORRECTION_PHRASE.test(text);
|
|
983
|
+
}
|
|
984
|
+
function isTestOrBuild(name, args) {
|
|
985
|
+
return SHELL_TOOLS.has(name) && TEST_OR_BUILD.test(args);
|
|
986
|
+
}
|
|
987
|
+
function median(values) {
|
|
988
|
+
if (values.length === 0) return null;
|
|
989
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
990
|
+
const mid = Math.floor(sorted.length / 2);
|
|
991
|
+
const value = sorted.length % 2 === 1 ? sorted[mid] ?? 0 : ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2;
|
|
992
|
+
return Math.round(value);
|
|
993
|
+
}
|
|
994
|
+
var month = (iso) => iso.slice(0, 7);
|
|
995
|
+
function sessionSignals(session) {
|
|
996
|
+
const out = {
|
|
997
|
+
planMode: false,
|
|
998
|
+
todos: false,
|
|
999
|
+
subagents: false,
|
|
1000
|
+
mcp: false,
|
|
1001
|
+
usedSkill: false,
|
|
1002
|
+
skills: [],
|
|
1003
|
+
edited: false,
|
|
1004
|
+
verified: false,
|
|
1005
|
+
firstPromptChars: null,
|
|
1006
|
+
followUps: 0,
|
|
1007
|
+
corrections: [],
|
|
1008
|
+
topics: /* @__PURE__ */ new Set(),
|
|
1009
|
+
editedPaths: []
|
|
1010
|
+
};
|
|
1011
|
+
const skills = /* @__PURE__ */ new Set();
|
|
1012
|
+
let prompts = 0;
|
|
1013
|
+
for (const event of session.events) {
|
|
1014
|
+
if (event.kind === "user_prompt") {
|
|
1015
|
+
const command = isSlashCommand(event.text);
|
|
1016
|
+
if (command !== null) {
|
|
1017
|
+
if (!BUILT_IN_COMMANDS.has(command)) {
|
|
1018
|
+
out.usedSkill = true;
|
|
1019
|
+
skills.add(command);
|
|
1020
|
+
}
|
|
1021
|
+
continue;
|
|
1022
|
+
}
|
|
1023
|
+
if (prompts === 0) out.firstPromptChars = event.text.length;
|
|
1024
|
+
else {
|
|
1025
|
+
out.followUps += 1;
|
|
1026
|
+
if (isCorrection(event.text)) out.corrections.push(event.text.length);
|
|
1027
|
+
}
|
|
1028
|
+
prompts += 1;
|
|
1029
|
+
} else if (event.kind === "tool_call") {
|
|
1030
|
+
if (PLAN_MODE_TOOLS.has(event.name)) out.planMode = true;
|
|
1031
|
+
if (TODO_TOOLS.has(event.name)) out.todos = true;
|
|
1032
|
+
if (SUBAGENT_TOOLS.has(event.name)) out.subagents = true;
|
|
1033
|
+
if (SKILL_TOOLS.has(event.name)) {
|
|
1034
|
+
out.usedSkill = true;
|
|
1035
|
+
skills.add(skillName(event.argsSummary));
|
|
1036
|
+
}
|
|
1037
|
+
if (event.name.startsWith("mcp__")) out.mcp = true;
|
|
1038
|
+
if (out.edited && isTestOrBuild(event.name, event.argsSummary)) out.verified = true;
|
|
1039
|
+
} else if (event.kind === "file_edit") {
|
|
1040
|
+
out.edited = true;
|
|
1041
|
+
out.editedPaths.push(event.path);
|
|
1042
|
+
const topic = topicOf(event.path);
|
|
1043
|
+
if (topic !== null) out.topics.add(topic);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
out.skills = [...skills].filter((name) => name !== "");
|
|
1047
|
+
return out;
|
|
1048
|
+
}
|
|
1049
|
+
function skillName(args) {
|
|
1050
|
+
return args.trim().split(/\s+/)[0]?.replace(/^\//, "").toLowerCase().slice(0, 120) ?? "";
|
|
1051
|
+
}
|
|
1052
|
+
function sessionContext(session) {
|
|
1053
|
+
const out = {
|
|
1054
|
+
turns: 0,
|
|
1055
|
+
windowPeaks: [],
|
|
1056
|
+
compactions: [],
|
|
1057
|
+
models: /* @__PURE__ */ new Map(),
|
|
1058
|
+
efforts: /* @__PURE__ */ new Map(),
|
|
1059
|
+
subagentCalls: 0,
|
|
1060
|
+
subagentCallsOtherModel: 0
|
|
1061
|
+
};
|
|
1062
|
+
let peak = 0;
|
|
1063
|
+
let model = null;
|
|
1064
|
+
const close = (reported) => {
|
|
1065
|
+
const value = Math.max(peak, reported ?? 0);
|
|
1066
|
+
if (value > 0) out.windowPeaks.push(value);
|
|
1067
|
+
peak = 0;
|
|
1068
|
+
};
|
|
1069
|
+
for (const event of session.events) {
|
|
1070
|
+
if (event.kind === "model_turn") {
|
|
1071
|
+
out.turns += 1;
|
|
1072
|
+
peak = Math.max(peak, event.contextTokens);
|
|
1073
|
+
if (event.model !== null) {
|
|
1074
|
+
model = event.model;
|
|
1075
|
+
out.models.set(event.model, (out.models.get(event.model) ?? 0) + 1);
|
|
1076
|
+
}
|
|
1077
|
+
if (event.effort !== null) {
|
|
1078
|
+
out.efforts.set(event.effort, (out.efforts.get(event.effort) ?? 0) + 1);
|
|
1079
|
+
}
|
|
1080
|
+
} else if (event.kind === "compaction") {
|
|
1081
|
+
close(event.preTokens);
|
|
1082
|
+
const freed = event.preTokens !== null && event.postTokens !== null ? Math.max(0, event.preTokens - event.postTokens) : null;
|
|
1083
|
+
out.compactions.push({ trigger: event.trigger, freed });
|
|
1084
|
+
} else if (event.kind === "tool_call" && SUBAGENT_TOOLS.has(event.name)) {
|
|
1085
|
+
out.subagentCalls += 1;
|
|
1086
|
+
if (event.model !== void 0 && event.model !== model) out.subagentCallsOtherModel += 1;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
close(null);
|
|
1090
|
+
return out;
|
|
1091
|
+
}
|
|
1092
|
+
function sessionKinds(session, signals) {
|
|
1093
|
+
const kinds = [];
|
|
1094
|
+
if (signals.planMode) kinds.push("plan_mode");
|
|
1095
|
+
if (signals.edited) kinds.push("edited_files");
|
|
1096
|
+
else if (session.events.some((event) => event.kind === "tool_call")) kinds.push("read_only");
|
|
1097
|
+
return kinds;
|
|
1098
|
+
}
|
|
1099
|
+
var MAX_MODELS = 10;
|
|
1100
|
+
var MAX_MODELS_PER_KIND = 5;
|
|
1101
|
+
function addAll(into, from) {
|
|
1102
|
+
for (const [key, n] of from) into.set(key, (into.get(key) ?? 0) + n);
|
|
1103
|
+
}
|
|
1104
|
+
function ranked(counts, max) {
|
|
1105
|
+
return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, max);
|
|
1106
|
+
}
|
|
1107
|
+
var ContextCounter = class {
|
|
1108
|
+
sessions = 0;
|
|
1109
|
+
turns = 0;
|
|
1110
|
+
peaks = [];
|
|
1111
|
+
compactionsPerSession = [];
|
|
1112
|
+
triggers = { manual: 0, auto: 0, none: 0 };
|
|
1113
|
+
freed = [];
|
|
1114
|
+
models = /* @__PURE__ */ new Map();
|
|
1115
|
+
efforts = /* @__PURE__ */ new Map();
|
|
1116
|
+
changedModel = 0;
|
|
1117
|
+
changedEffort = 0;
|
|
1118
|
+
subagentCalls = 0;
|
|
1119
|
+
subagentCallsOtherModel = 0;
|
|
1120
|
+
kinds = /* @__PURE__ */ new Map();
|
|
1121
|
+
add(context, kinds) {
|
|
1122
|
+
if (context.turns === 0) return;
|
|
1123
|
+
this.sessions += 1;
|
|
1124
|
+
this.turns += context.turns;
|
|
1125
|
+
this.peaks.push(...context.windowPeaks);
|
|
1126
|
+
if (context.compactions.length > 0) this.compactionsPerSession.push(context.compactions.length);
|
|
1127
|
+
for (const compaction of context.compactions) {
|
|
1128
|
+
if (compaction.trigger === "manual") this.triggers.manual += 1;
|
|
1129
|
+
else if (compaction.trigger === "auto") this.triggers.auto += 1;
|
|
1130
|
+
else this.triggers.none += 1;
|
|
1131
|
+
if (compaction.freed !== null) this.freed.push(compaction.freed);
|
|
1132
|
+
}
|
|
1133
|
+
addAll(this.models, context.models);
|
|
1134
|
+
addAll(this.efforts, context.efforts);
|
|
1135
|
+
if (context.models.size > 1) this.changedModel += 1;
|
|
1136
|
+
if (context.efforts.size > 1) this.changedEffort += 1;
|
|
1137
|
+
this.subagentCalls += context.subagentCalls;
|
|
1138
|
+
this.subagentCallsOtherModel += context.subagentCallsOtherModel;
|
|
1139
|
+
for (const kind of kinds) {
|
|
1140
|
+
const entry = this.kinds.get(kind) ?? {
|
|
1141
|
+
sessions: 0,
|
|
1142
|
+
models: /* @__PURE__ */ new Map(),
|
|
1143
|
+
efforts: /* @__PURE__ */ new Map()
|
|
1144
|
+
};
|
|
1145
|
+
entry.sessions += 1;
|
|
1146
|
+
addAll(entry.models, context.models);
|
|
1147
|
+
addAll(entry.efforts, context.efforts);
|
|
1148
|
+
this.kinds.set(kind, entry);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
finish() {
|
|
1152
|
+
if (this.sessions === 0) return void 0;
|
|
1153
|
+
const kindOrder = ["plan_mode", "edited_files", "read_only"];
|
|
1154
|
+
return {
|
|
1155
|
+
sessionsWithTurns: this.sessions,
|
|
1156
|
+
turns: this.turns,
|
|
1157
|
+
windows: this.peaks.length,
|
|
1158
|
+
windowPeakHighest: this.peaks.reduce((a, b) => Math.max(a, b), 0),
|
|
1159
|
+
windowPeakMedian: median(this.peaks) ?? 0,
|
|
1160
|
+
sessionsCompacted: this.compactionsPerSession.length,
|
|
1161
|
+
compactionsPerSessionMedian: median(this.compactionsPerSession) ?? 0,
|
|
1162
|
+
compactionsPerSessionMost: this.compactionsPerSession.reduce((a, b) => Math.max(a, b), 0),
|
|
1163
|
+
manualCompactions: this.triggers.manual,
|
|
1164
|
+
autoCompactions: this.triggers.auto,
|
|
1165
|
+
untriggeredCompactions: this.triggers.none,
|
|
1166
|
+
freedMedianTokens: median(this.freed),
|
|
1167
|
+
models: ranked(this.models, MAX_MODELS).map(([model, turns]) => ({ model, turns })),
|
|
1168
|
+
efforts: ranked(this.efforts, MAX_MODELS).map(([effort, turns]) => ({ effort, turns })),
|
|
1169
|
+
sessionsChangedModel: this.changedModel,
|
|
1170
|
+
sessionsChangedEffort: this.changedEffort,
|
|
1171
|
+
subagentCalls: this.subagentCalls,
|
|
1172
|
+
subagentCallsOtherModel: this.subagentCallsOtherModel,
|
|
1173
|
+
bySessionKind: kindOrder.flatMap((kind) => {
|
|
1174
|
+
const entry = this.kinds.get(kind);
|
|
1175
|
+
if (entry === void 0) return [];
|
|
1176
|
+
return [
|
|
1177
|
+
{
|
|
1178
|
+
kind,
|
|
1179
|
+
sessions: entry.sessions,
|
|
1180
|
+
models: ranked(entry.models, MAX_MODELS_PER_KIND).map(([model, turns]) => ({
|
|
1181
|
+
model,
|
|
1182
|
+
turns
|
|
1183
|
+
})),
|
|
1184
|
+
efforts: ranked(entry.efforts, MAX_MODELS).map(([effort, turns]) => ({
|
|
1185
|
+
effort,
|
|
1186
|
+
turns
|
|
1187
|
+
}))
|
|
1188
|
+
}
|
|
1189
|
+
];
|
|
1190
|
+
})
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
var StatsCounter = class {
|
|
1195
|
+
context = new ContextCounter();
|
|
1196
|
+
sessions = 0;
|
|
1197
|
+
projects = /* @__PURE__ */ new Set();
|
|
1198
|
+
toolSessions = /* @__PURE__ */ new Map();
|
|
1199
|
+
features = {
|
|
1200
|
+
planMode: 0,
|
|
1201
|
+
todos: 0,
|
|
1202
|
+
subagents: 0,
|
|
1203
|
+
mcp: 0,
|
|
1204
|
+
skillsUsed: 0,
|
|
1205
|
+
instructionFiles: 0,
|
|
1206
|
+
memoryFiles: 0
|
|
1207
|
+
};
|
|
1208
|
+
skillsSetUp = /* @__PURE__ */ new Set();
|
|
1209
|
+
hooks = 0;
|
|
1210
|
+
codeChange = 0;
|
|
1211
|
+
verified = 0;
|
|
1212
|
+
firstPrompts = [];
|
|
1213
|
+
followUps = 0;
|
|
1214
|
+
corrections = [];
|
|
1215
|
+
topics = /* @__PURE__ */ new Map();
|
|
1216
|
+
addSession(session) {
|
|
1217
|
+
this.sessions += 1;
|
|
1218
|
+
this.projects.add(session.project);
|
|
1219
|
+
this.toolSessions.set(session.tool, (this.toolSessions.get(session.tool) ?? 0) + 1);
|
|
1220
|
+
const signals = sessionSignals(session);
|
|
1221
|
+
this.context.add(sessionContext(session), sessionKinds(session, signals));
|
|
1222
|
+
if (signals.firstPromptChars !== null) this.firstPrompts.push(signals.firstPromptChars);
|
|
1223
|
+
this.followUps += signals.followUps;
|
|
1224
|
+
this.corrections.push(...signals.corrections);
|
|
1225
|
+
if (signals.planMode) this.features.planMode += 1;
|
|
1226
|
+
if (signals.todos) this.features.todos += 1;
|
|
1227
|
+
if (signals.subagents) this.features.subagents += 1;
|
|
1228
|
+
if (signals.mcp) this.features.mcp += 1;
|
|
1229
|
+
if (signals.usedSkill) this.features.skillsUsed += 1;
|
|
1230
|
+
if (signals.edited) this.codeChange += 1;
|
|
1231
|
+
if (signals.verified) this.verified += 1;
|
|
1232
|
+
const at = month(session.startedAt);
|
|
1233
|
+
for (const topic of signals.topics) {
|
|
1234
|
+
const entry = this.topics.get(topic);
|
|
1235
|
+
if (entry === void 0) this.topics.set(topic, { sessions: 1, first: at, last: at });
|
|
1236
|
+
else {
|
|
1237
|
+
entry.sessions += 1;
|
|
1238
|
+
if (at < entry.first) entry.first = at;
|
|
1239
|
+
if (at > entry.last) entry.last = at;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
addInstructionFile(file) {
|
|
1244
|
+
if (file.kind === "claude_md") this.features.instructionFiles += 1;
|
|
1245
|
+
else this.features.memoryFiles += 1;
|
|
1246
|
+
}
|
|
1247
|
+
addSetup(setup) {
|
|
1248
|
+
for (const skill of setup.skills) this.skillsSetUp.add(skill.toLowerCase());
|
|
1249
|
+
this.hooks += setup.hooks.length;
|
|
1250
|
+
}
|
|
1251
|
+
finish(context) {
|
|
1252
|
+
const topics = [...this.topics.entries()].map(([topic, entry]) => ({
|
|
1253
|
+
topic,
|
|
1254
|
+
sessions: entry.sessions,
|
|
1255
|
+
firstMonth: entry.first,
|
|
1256
|
+
lastMonth: entry.last
|
|
1257
|
+
})).sort((a, b) => b.sessions - a.sessions || a.topic.localeCompare(b.topic)).slice(0, MAX_TOPICS);
|
|
1258
|
+
const contextStats = this.context.finish();
|
|
1259
|
+
return {
|
|
1260
|
+
sessions: this.sessions,
|
|
1261
|
+
projects: this.projects.size,
|
|
1262
|
+
dateRange: { start: context.dateRange.start, end: context.dateRange.end },
|
|
1263
|
+
tools: context.tools.map((entry) => ({
|
|
1264
|
+
tool: entry.tool,
|
|
1265
|
+
sessions: this.toolSessions.get(entry.tool) ?? 0,
|
|
1266
|
+
versions: [...entry.versions].sort().slice(-20)
|
|
1267
|
+
})).filter((entry) => entry.sessions > 0),
|
|
1268
|
+
features: {
|
|
1269
|
+
...this.features,
|
|
1270
|
+
skillsSetUp: this.skillsSetUp.size,
|
|
1271
|
+
hooks: this.hooks
|
|
1272
|
+
},
|
|
1273
|
+
codeChangeSessions: this.codeChange,
|
|
1274
|
+
verifiedCodeChangeSessions: this.verified,
|
|
1275
|
+
firstPromptMedianChars: median(this.firstPrompts),
|
|
1276
|
+
followUpPrompts: this.followUps,
|
|
1277
|
+
corrections: this.corrections.length,
|
|
1278
|
+
correctionMedianChars: median(this.corrections),
|
|
1279
|
+
topics,
|
|
1280
|
+
secretsCaught: context.secretsCaught,
|
|
1281
|
+
...contextStats === void 0 ? {} : { context: contextStats }
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
|
|
1286
|
+
// ../../packages/ai-workflow/src/card.ts
|
|
1287
|
+
function localDay(iso) {
|
|
1288
|
+
const date = new Date(iso);
|
|
1289
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1290
|
+
return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
1291
|
+
}
|
|
1292
|
+
var CardCounter = class {
|
|
1293
|
+
stats = new StatsCounter();
|
|
1294
|
+
days = /* @__PURE__ */ new Set();
|
|
1295
|
+
tools = /* @__PURE__ */ new Set();
|
|
1296
|
+
first = null;
|
|
1297
|
+
last = null;
|
|
1298
|
+
sessions = 0;
|
|
1299
|
+
addSession(session) {
|
|
1300
|
+
this.sessions += 1;
|
|
1301
|
+
this.stats.addSession(session);
|
|
1302
|
+
this.tools.add(session.tool);
|
|
1303
|
+
const start = localDay(session.startedAt);
|
|
1304
|
+
const end = localDay(session.endedAt);
|
|
1305
|
+
this.days.add(start);
|
|
1306
|
+
if (this.first === null || start < this.first) this.first = start;
|
|
1307
|
+
const latest = end > start ? end : start;
|
|
1308
|
+
if (this.last === null || latest > this.last) this.last = latest;
|
|
1309
|
+
}
|
|
1310
|
+
finish(options) {
|
|
1311
|
+
if (this.sessions === 0 || this.first === null || this.last === null) return null;
|
|
1312
|
+
const stats = this.stats.finish({
|
|
1313
|
+
dateRange: { start: this.first, end: this.last },
|
|
1314
|
+
tools: [...this.tools].map((tool) => ({ tool, versions: [] })),
|
|
1315
|
+
secretsCaught: 0
|
|
1316
|
+
});
|
|
1317
|
+
const features = CARD_FEATURES.map((feature) => ({
|
|
1318
|
+
feature,
|
|
1319
|
+
sessions: stats.features[feature]
|
|
1320
|
+
})).filter((entry) => entry.sessions > 0).sort((a, b) => b.sessions - a.sessions).slice(0, CARD_TOP);
|
|
1321
|
+
const topics = options.topics ? stats.topics.flatMap((entry) => {
|
|
1322
|
+
const topic = aiWorkflowTopicSchema.safeParse(entry.topic);
|
|
1323
|
+
return topic.success ? [{ topic: topic.data, sessions: entry.sessions }] : [];
|
|
1324
|
+
}) : [];
|
|
1325
|
+
return {
|
|
1326
|
+
version: 1,
|
|
1327
|
+
theme: options.theme,
|
|
1328
|
+
sessions: stats.sessions,
|
|
1329
|
+
activeDays: this.days.size,
|
|
1330
|
+
dateRange: { start: this.first, end: this.last },
|
|
1331
|
+
tools: [...this.tools].sort(),
|
|
1332
|
+
codeChangeSessions: stats.codeChangeSessions,
|
|
1333
|
+
verifiedCodeChangeSessions: stats.verifiedCodeChangeSessions,
|
|
1334
|
+
features,
|
|
1335
|
+
topics: topics.slice(0, CARD_TOP)
|
|
1336
|
+
};
|
|
1337
|
+
}
|
|
1338
|
+
};
|
|
1339
|
+
|
|
1340
|
+
// ../../packages/ui/src/lib/theme-colors.ts
|
|
1341
|
+
var THEME_COLORS = {
|
|
1342
|
+
retro: {
|
|
1343
|
+
background: "#0a0f0b",
|
|
1344
|
+
text: "#c8f7d0",
|
|
1345
|
+
"text-muted": "#8fb89a",
|
|
1346
|
+
accent: "#39ff6a",
|
|
1347
|
+
border: "#37805a"
|
|
1348
|
+
},
|
|
1349
|
+
"slate-dark": {
|
|
1350
|
+
background: "#0f1115",
|
|
1351
|
+
text: "#e6e8ec",
|
|
1352
|
+
"text-muted": "#9ba4b3",
|
|
1353
|
+
accent: "#22c55e",
|
|
1354
|
+
border: "#667085"
|
|
1355
|
+
},
|
|
1356
|
+
"slate-light": {
|
|
1357
|
+
background: "#ffffff",
|
|
1358
|
+
text: "#14171c",
|
|
1359
|
+
"text-muted": "#4b5563",
|
|
1360
|
+
accent: "#166534",
|
|
1361
|
+
border: "#7a8494"
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
|
|
1365
|
+
// ../../packages/ai-workflow/src/card-layout.ts
|
|
1366
|
+
var CARD_SIZE = { width: 1200, height: 630 };
|
|
1367
|
+
var CARD_FONTS = [
|
|
1368
|
+
{ name: "Inter", file: "inter-latin-500-normal.woff", weight: 500 },
|
|
1369
|
+
{ name: "Inter", file: "inter-latin-700-normal.woff", weight: 700 },
|
|
1370
|
+
{ name: "IBM Plex Mono", file: "ibm-plex-mono-latin-500-normal.woff", weight: 500 },
|
|
1371
|
+
{ name: "IBM Plex Mono", file: "ibm-plex-mono-latin-600-normal.woff", weight: 600 }
|
|
1372
|
+
];
|
|
1373
|
+
var TOOL_LABELS = {
|
|
1374
|
+
claude_code: "Claude Code",
|
|
1375
|
+
codex: "Codex"
|
|
1376
|
+
};
|
|
1377
|
+
var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
1378
|
+
function h(style, ...children) {
|
|
1379
|
+
return {
|
|
1380
|
+
type: "div",
|
|
1381
|
+
key: null,
|
|
1382
|
+
props: { style: { display: "flex", ...style }, children }
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
function monthOf(day2) {
|
|
1386
|
+
const [year, month2] = day2.split("-");
|
|
1387
|
+
return `${MONTHS[Number(month2) - 1] ?? ""} ${year ?? ""}`;
|
|
1388
|
+
}
|
|
1389
|
+
function cardDateRange(card2) {
|
|
1390
|
+
const start = monthOf(card2.dateRange.start);
|
|
1391
|
+
const end = monthOf(card2.dateRange.end);
|
|
1392
|
+
return start === end ? start : `${start} \u2013 ${end}`;
|
|
1393
|
+
}
|
|
1394
|
+
var number = (n) => n.toLocaleString("en-US");
|
|
1395
|
+
function cardFooter(handle) {
|
|
1396
|
+
return handle === null ? "xtrium.co \u2014 make your own Atrium" : `xtrium.co/${handle}`;
|
|
1397
|
+
}
|
|
1398
|
+
var plural = (n, word) => `${number(n)} ${word}${n === 1 ? "" : "s"}`;
|
|
1399
|
+
function cardLines(card2) {
|
|
1400
|
+
const percent = testAfterChangePercent(card2);
|
|
1401
|
+
const lines = [
|
|
1402
|
+
`${plural(card2.sessions, "session")} on ${plural(card2.activeDays, "day")}, ${cardDateRange(card2)}, with ${card2.tools.map((tool) => TOOL_LABELS[tool]).join(" and ")}`
|
|
1403
|
+
];
|
|
1404
|
+
if (percent !== null) {
|
|
1405
|
+
lines.push(
|
|
1406
|
+
`${String(percent)}% of sessions that changed code then ran tests or a build (${number(card2.verifiedCodeChangeSessions)} of ${number(card2.codeChangeSessions)})`
|
|
1407
|
+
);
|
|
1408
|
+
}
|
|
1409
|
+
if (card2.features.length > 0) {
|
|
1410
|
+
lines.push(`Most used: ${card2.features.map((f) => CARD_FEATURE_LABELS[f.feature]).join(", ")}`);
|
|
1411
|
+
}
|
|
1412
|
+
if (card2.topics.length > 0) {
|
|
1413
|
+
lines.push(`Most worked on: ${card2.topics.map((t) => t.topic).join(", ")}`);
|
|
1414
|
+
}
|
|
1415
|
+
return lines;
|
|
1416
|
+
}
|
|
1417
|
+
function cardElement(card2, handle) {
|
|
1418
|
+
const colors = THEME_COLORS[card2.theme === "slate" ? "slate-dark" : "retro"];
|
|
1419
|
+
const mono = card2.theme === "retro";
|
|
1420
|
+
const bold = mono ? 600 : 700;
|
|
1421
|
+
const percent = testAfterChangePercent(card2);
|
|
1422
|
+
const stat4 = (value, label) => h(
|
|
1423
|
+
{ flexDirection: "column", gap: 6, flexGrow: 1, flexBasis: 0, minWidth: 0 },
|
|
1424
|
+
h({ fontSize: 80, fontWeight: bold, color: colors.accent, lineHeight: 1 }, value),
|
|
1425
|
+
h({ fontSize: 24, color: colors["text-muted"], lineHeight: 1.25 }, label)
|
|
1426
|
+
);
|
|
1427
|
+
const list = (title, rows) => h(
|
|
1428
|
+
{ flexDirection: "column", gap: 6, flexGrow: 1, flexBasis: 0, minWidth: 0 },
|
|
1429
|
+
h({ fontSize: 24, color: colors["text-muted"], textTransform: "uppercase" }, title),
|
|
1430
|
+
...rows.map(
|
|
1431
|
+
(row) => h(
|
|
1432
|
+
{ fontSize: 28, fontWeight: 500, gap: 14 },
|
|
1433
|
+
h({ color: colors.text }, row.label),
|
|
1434
|
+
h({ color: colors["text-muted"] }, number(row.sessions))
|
|
1435
|
+
)
|
|
1436
|
+
)
|
|
1437
|
+
);
|
|
1438
|
+
const stats = [
|
|
1439
|
+
stat4(number(card2.sessions), card2.sessions === 1 ? "session" : "sessions"),
|
|
1440
|
+
stat4(number(card2.activeDays), card2.activeDays === 1 ? "active day" : "active days")
|
|
1441
|
+
];
|
|
1442
|
+
if (percent !== null) {
|
|
1443
|
+
stats.push(stat4(`${String(percent)}%`, "of code changes, then a test or build"));
|
|
1444
|
+
}
|
|
1445
|
+
const lists = [];
|
|
1446
|
+
if (card2.features.length > 0) {
|
|
1447
|
+
lists.push(
|
|
1448
|
+
list(
|
|
1449
|
+
"Most used",
|
|
1450
|
+
card2.features.map((f) => ({ label: CARD_FEATURE_LABELS[f.feature], sessions: f.sessions }))
|
|
1451
|
+
)
|
|
1452
|
+
);
|
|
1453
|
+
}
|
|
1454
|
+
if (card2.topics.length > 0) {
|
|
1455
|
+
lists.push(
|
|
1456
|
+
list(
|
|
1457
|
+
"Most worked on",
|
|
1458
|
+
card2.topics.map((t) => ({ label: t.topic, sessions: t.sessions }))
|
|
1459
|
+
)
|
|
1460
|
+
);
|
|
1461
|
+
}
|
|
1462
|
+
return h(
|
|
1463
|
+
{
|
|
1464
|
+
width: CARD_SIZE.width,
|
|
1465
|
+
height: CARD_SIZE.height,
|
|
1466
|
+
boxSizing: "border-box",
|
|
1467
|
+
overflow: "hidden",
|
|
1468
|
+
flexDirection: "column",
|
|
1469
|
+
justifyContent: "space-between",
|
|
1470
|
+
padding: "40px 60px",
|
|
1471
|
+
background: colors.background,
|
|
1472
|
+
color: colors.text,
|
|
1473
|
+
border: `10px solid ${colors.border}`,
|
|
1474
|
+
fontFamily: mono ? "IBM Plex Mono" : "Inter"
|
|
1475
|
+
},
|
|
1476
|
+
h(
|
|
1477
|
+
{ flexDirection: "column", gap: 10 },
|
|
1478
|
+
h(
|
|
1479
|
+
{ justifyContent: "space-between", alignItems: "baseline" },
|
|
1480
|
+
h({ fontSize: 38, fontWeight: bold, color: colors.accent }, "Xtrium"),
|
|
1481
|
+
h({ fontSize: 24, color: colors["text-muted"] }, "AI WORKFLOW \xB7 SELF-REPORTED")
|
|
1482
|
+
),
|
|
1483
|
+
h(
|
|
1484
|
+
{ fontSize: 30, fontWeight: 500, color: colors.text },
|
|
1485
|
+
`${card2.tools.map((tool) => TOOL_LABELS[tool]).join(" + ")} \xB7 ${cardDateRange(card2)}`
|
|
1486
|
+
)
|
|
1487
|
+
),
|
|
1488
|
+
h({ gap: 40 }, ...stats),
|
|
1489
|
+
lists.length > 0 ? h({ gap: 40 }, ...lists) : h({}),
|
|
1490
|
+
h(
|
|
1491
|
+
{ justifyContent: "space-between", alignItems: "baseline" },
|
|
1492
|
+
h({ fontSize: 34, fontWeight: bold, color: colors.accent }, cardFooter(handle)),
|
|
1493
|
+
h({ fontSize: 22, color: colors["text-muted"] }, "made with npx xtrium card")
|
|
1494
|
+
)
|
|
1495
|
+
);
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
// src/card-render.ts
|
|
1499
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
1500
|
+
import { Resvg } from "@resvg/resvg-js";
|
|
1501
|
+
import satori from "satori";
|
|
1502
|
+
var FONT_DIR = new URL("../assets/fonts/", import.meta.url);
|
|
1503
|
+
async function renderCard(card2, handle) {
|
|
1504
|
+
const fonts = await Promise.all(
|
|
1505
|
+
CARD_FONTS.map(async (font) => ({
|
|
1506
|
+
name: font.name,
|
|
1507
|
+
data: await readFile2(new URL(font.file, FONT_DIR)),
|
|
1508
|
+
weight: font.weight,
|
|
1509
|
+
style: "normal"
|
|
1510
|
+
}))
|
|
1511
|
+
);
|
|
1512
|
+
const svg = await satori(cardElement(card2, handle), { ...CARD_SIZE, fonts });
|
|
1513
|
+
const png = new Resvg(svg, { fitTo: { mode: "width", value: CARD_SIZE.width } }).render().asPng();
|
|
1514
|
+
return { svg, png };
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// src/adapters/claude-code.ts
|
|
1518
|
+
import { stat as stat2 } from "fs/promises";
|
|
1519
|
+
import { basename, dirname as dirname2, join as join5 } from "path";
|
|
1520
|
+
import { z as z7 } from "zod";
|
|
1521
|
+
|
|
1522
|
+
// src/events.ts
|
|
1523
|
+
var TOOLS = ["claude_code", "codex"];
|
|
1524
|
+
var TOOL_LABELS2 = { claude_code: "Claude Code", codex: "Codex" };
|
|
1525
|
+
var SUMMARY_MAX = 160;
|
|
1526
|
+
var ARGS_MAX = 200;
|
|
1527
|
+
function oneLine(text, max) {
|
|
1528
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
1529
|
+
return flat.length <= max ? flat : `${flat.slice(0, max - 1)}\u2026`;
|
|
1530
|
+
}
|
|
1531
|
+
function summarizeOutput(output) {
|
|
1532
|
+
const lines = output.split("\n");
|
|
1533
|
+
while (lines.length > 0 && lines[lines.length - 1]?.trim() === "") lines.pop();
|
|
1534
|
+
if (lines.length === 0) return { summary: "(no output)", lines: 0 };
|
|
1535
|
+
const first = lines.find((line) => line.trim() !== "") ?? "";
|
|
1536
|
+
return { summary: oneLine(first, SUMMARY_MAX), lines: lines.length };
|
|
1537
|
+
}
|
|
1538
|
+
var SUMMARY_KEYS = [
|
|
1539
|
+
"command",
|
|
1540
|
+
"cmd",
|
|
1541
|
+
"file_path",
|
|
1542
|
+
"path",
|
|
1543
|
+
"pattern",
|
|
1544
|
+
"query",
|
|
1545
|
+
"url",
|
|
1546
|
+
"skill",
|
|
1547
|
+
"description"
|
|
1548
|
+
];
|
|
1549
|
+
function summarizeArgs(args) {
|
|
1550
|
+
if (typeof args === "string") return oneLine(args, ARGS_MAX);
|
|
1551
|
+
if (typeof args !== "object" || args === null || Array.isArray(args)) return "";
|
|
1552
|
+
const record = args;
|
|
1553
|
+
for (const key of SUMMARY_KEYS) {
|
|
1554
|
+
const value = record[key];
|
|
1555
|
+
if (typeof value === "string" && value.trim() !== "") return oneLine(value, ARGS_MAX);
|
|
1556
|
+
if (Array.isArray(value) && value.every((part) => typeof part === "string")) {
|
|
1557
|
+
return oneLine(value.join(" "), ARGS_MAX);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
return oneLine(Object.keys(record).join(", "), ARGS_MAX);
|
|
1561
|
+
}
|
|
1562
|
+
function countDiffLines(lines) {
|
|
1563
|
+
let count2 = 0;
|
|
1564
|
+
for (const line of lines) {
|
|
1565
|
+
if (line.startsWith("+++") || line.startsWith("---")) continue;
|
|
1566
|
+
if (line.startsWith("+") || line.startsWith("-")) count2 += 1;
|
|
1567
|
+
}
|
|
1568
|
+
return count2;
|
|
1569
|
+
}
|
|
1570
|
+
function countContentLines(content) {
|
|
1571
|
+
if (content === "") return 0;
|
|
1572
|
+
const lines = content.split("\n");
|
|
1573
|
+
return content.endsWith("\n") ? lines.length - 1 : lines.length;
|
|
1574
|
+
}
|
|
1575
|
+
function isoOrUndefined(value) {
|
|
1576
|
+
if (typeof value !== "string") return void 0;
|
|
1577
|
+
const time = Date.parse(value);
|
|
1578
|
+
return Number.isNaN(time) ? void 0 : new Date(time).toISOString();
|
|
1579
|
+
}
|
|
1580
|
+
function withTime(event, at) {
|
|
1581
|
+
return at === void 0 ? event : { ...event, at };
|
|
1582
|
+
}
|
|
1583
|
+
function modelIdOrNull(value) {
|
|
1584
|
+
const parsed = modelIdSchema.safeParse(value);
|
|
1585
|
+
return parsed.success ? parsed.data : null;
|
|
1586
|
+
}
|
|
1587
|
+
function effortOrNull(value) {
|
|
1588
|
+
const parsed = effortSchema.safeParse(value);
|
|
1589
|
+
return parsed.success ? parsed.data : null;
|
|
1590
|
+
}
|
|
1591
|
+
var TOKENS_MAX = 1e8;
|
|
1592
|
+
function tokensOrNull(value) {
|
|
1593
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? Math.min(value, TOKENS_MAX) : null;
|
|
1594
|
+
}
|
|
1595
|
+
function tokens(value) {
|
|
1596
|
+
return tokensOrNull(value) ?? 0;
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
// src/adapters/claude-setup.ts
|
|
1600
|
+
import { readdir as readdir2, readFile as readFile3 } from "fs/promises";
|
|
1601
|
+
import { join as join4 } from "path";
|
|
1602
|
+
import { z as z6 } from "zod";
|
|
1603
|
+
|
|
1604
|
+
// src/adapters/files.ts
|
|
1605
|
+
import { lstat, readdir, stat } from "fs/promises";
|
|
1606
|
+
import { join as join3 } from "path";
|
|
1607
|
+
async function fileSize(path) {
|
|
1608
|
+
try {
|
|
1609
|
+
const info = await stat(path);
|
|
1610
|
+
return info.isFile() ? info.size : null;
|
|
1611
|
+
} catch {
|
|
1612
|
+
return null;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
async function findFiles(root, suffix, maxDepth, skipDirs = /* @__PURE__ */ new Set()) {
|
|
1616
|
+
const found = [];
|
|
1617
|
+
async function walk(dir, depth) {
|
|
1618
|
+
let entries;
|
|
1619
|
+
try {
|
|
1620
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
1621
|
+
} catch {
|
|
1622
|
+
return;
|
|
1623
|
+
}
|
|
1624
|
+
for (const entry of entries) {
|
|
1625
|
+
const path = join3(dir, entry.name);
|
|
1626
|
+
if (entry.isDirectory()) {
|
|
1627
|
+
if (depth < maxDepth && !skipDirs.has(entry.name)) await walk(path, depth + 1);
|
|
1628
|
+
} else if (entry.isFile() && entry.name.endsWith(suffix)) {
|
|
1629
|
+
found.push(path);
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
try {
|
|
1634
|
+
if (!(await lstat(root)).isDirectory()) return [];
|
|
1635
|
+
} catch {
|
|
1636
|
+
return [];
|
|
1637
|
+
}
|
|
1638
|
+
await walk(root, 0);
|
|
1639
|
+
return found.sort();
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// src/adapters/claude-setup.ts
|
|
1643
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
1644
|
+
var MAX_ENTRIES = 500;
|
|
1645
|
+
var hooksSchema = z6.record(
|
|
1646
|
+
z6.string(),
|
|
1647
|
+
z6.array(z6.looseObject({ matcher: z6.string().optional() })).catch([])
|
|
1648
|
+
);
|
|
1649
|
+
var settingsSchema = z6.looseObject({ hooks: hooksSchema.optional() });
|
|
1650
|
+
async function skillNames(dir) {
|
|
1651
|
+
let entries;
|
|
1652
|
+
try {
|
|
1653
|
+
entries = await readdir2(dir, { withFileTypes: true });
|
|
1654
|
+
} catch {
|
|
1655
|
+
return [];
|
|
1656
|
+
}
|
|
1657
|
+
const names = [];
|
|
1658
|
+
for (const entry of entries) {
|
|
1659
|
+
if (!entry.isDirectory()) continue;
|
|
1660
|
+
if (await fileSize(join4(dir, entry.name, "SKILL.md")) !== null) names.push(entry.name);
|
|
1661
|
+
}
|
|
1662
|
+
return names.sort().slice(0, MAX_ENTRIES);
|
|
1663
|
+
}
|
|
1664
|
+
async function hookNames(path) {
|
|
1665
|
+
const size = await fileSize(path);
|
|
1666
|
+
if (size === null || size > MAX_SETTINGS_BYTES) return [];
|
|
1667
|
+
let value;
|
|
1668
|
+
try {
|
|
1669
|
+
value = JSON.parse(await readFile3(path, "utf8"));
|
|
1670
|
+
} catch {
|
|
1671
|
+
return [];
|
|
1672
|
+
}
|
|
1673
|
+
const settings = settingsSchema.safeParse(value);
|
|
1674
|
+
if (!settings.success || settings.data.hooks === void 0) return [];
|
|
1675
|
+
return Object.entries(settings.data.hooks).flatMap(
|
|
1676
|
+
([event, groups]) => groups.map((group) => ({
|
|
1677
|
+
event: event.slice(0, 60),
|
|
1678
|
+
matcher: group.matcher?.slice(0, 200) ?? null
|
|
1679
|
+
}))
|
|
1680
|
+
);
|
|
1681
|
+
}
|
|
1682
|
+
async function claudeSetup(claudeDir, project) {
|
|
1683
|
+
const base = project === null ? claudeDir : join4(project, ".claude");
|
|
1684
|
+
const settingsFiles = project === null ? [join4(claudeDir, "settings.json")] : [join4(base, "settings.json"), join4(base, "settings.local.json")];
|
|
1685
|
+
const hooks = [];
|
|
1686
|
+
for (const file of settingsFiles) hooks.push(...await hookNames(file));
|
|
1687
|
+
return { skills: await skillNames(join4(base, "skills")), hooks: hooks.slice(0, MAX_ENTRIES) };
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
// src/adapters/lines.ts
|
|
1691
|
+
import { createReadStream } from "fs";
|
|
1692
|
+
import { createInterface } from "readline";
|
|
1693
|
+
var MAX_LINE_CHARS = 8 * 1024 * 1024;
|
|
1694
|
+
async function* readJsonObjects(path, stats) {
|
|
1695
|
+
const lines = createInterface({
|
|
1696
|
+
input: createReadStream(path, { encoding: "utf8" }),
|
|
1697
|
+
crlfDelay: Infinity
|
|
1698
|
+
});
|
|
1699
|
+
for await (const line of lines) {
|
|
1700
|
+
if (line.trim() === "") continue;
|
|
1701
|
+
stats.lines += 1;
|
|
1702
|
+
if (line.length > MAX_LINE_CHARS) {
|
|
1703
|
+
stats.skippedLines += 1;
|
|
1704
|
+
continue;
|
|
1705
|
+
}
|
|
1706
|
+
let value;
|
|
1707
|
+
try {
|
|
1708
|
+
value = JSON.parse(line);
|
|
1709
|
+
} catch {
|
|
1710
|
+
stats.skippedLines += 1;
|
|
1711
|
+
continue;
|
|
1712
|
+
}
|
|
1713
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1714
|
+
stats.skippedLines += 1;
|
|
1715
|
+
continue;
|
|
1716
|
+
}
|
|
1717
|
+
yield value;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
// src/adapters/version.ts
|
|
1722
|
+
var TESTED_MAJOR = { claude_code: 2, codex: 0 };
|
|
1723
|
+
function highestVersion(versions) {
|
|
1724
|
+
let best = null;
|
|
1725
|
+
let bestText = null;
|
|
1726
|
+
for (const text of versions) {
|
|
1727
|
+
const parts = parseVersion(text);
|
|
1728
|
+
if (parts === null) continue;
|
|
1729
|
+
if (best === null || compare(parts, best) > 0) {
|
|
1730
|
+
best = parts;
|
|
1731
|
+
bestText = text;
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
return bestText;
|
|
1735
|
+
}
|
|
1736
|
+
function versionNote(tool, version) {
|
|
1737
|
+
if (version === null) return null;
|
|
1738
|
+
const parts = parseVersion(version);
|
|
1739
|
+
if (parts === null) return null;
|
|
1740
|
+
const [major = 0] = parts;
|
|
1741
|
+
if (major <= TESTED_MAJOR[tool]) return null;
|
|
1742
|
+
return `${TOOL_LABELS2[tool]} ${version} is newer than this CLI was tested with; update xtrium if counts look wrong.`;
|
|
1743
|
+
}
|
|
1744
|
+
function parseVersion(text) {
|
|
1745
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(text.trim());
|
|
1746
|
+
if (match === null) return null;
|
|
1747
|
+
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
1748
|
+
}
|
|
1749
|
+
function compare(a, b) {
|
|
1750
|
+
for (let index = 0; index < 3; index += 1) {
|
|
1751
|
+
const diff = (a[index] ?? 0) - (b[index] ?? 0);
|
|
1752
|
+
if (diff !== 0) return diff;
|
|
1753
|
+
}
|
|
1754
|
+
return 0;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
// src/adapters/claude-code.ts
|
|
1758
|
+
var recordSchema = z7.looseObject({
|
|
1759
|
+
type: z7.string(),
|
|
1760
|
+
sessionId: z7.string(),
|
|
1761
|
+
cwd: z7.string().optional(),
|
|
1762
|
+
version: z7.string().optional(),
|
|
1763
|
+
timestamp: z7.string().optional(),
|
|
1764
|
+
isSidechain: z7.boolean().optional(),
|
|
1765
|
+
isMeta: z7.boolean().optional(),
|
|
1766
|
+
origin: z7.looseObject({ kind: z7.string() }).optional(),
|
|
1767
|
+
message: z7.looseObject({
|
|
1768
|
+
content: z7.unknown(),
|
|
1769
|
+
id: z7.string().optional(),
|
|
1770
|
+
model: z7.unknown().optional(),
|
|
1771
|
+
usage: z7.looseObject({}).optional()
|
|
1772
|
+
}).optional(),
|
|
1773
|
+
toolUseResult: z7.unknown().optional(),
|
|
1774
|
+
effort: z7.unknown().optional(),
|
|
1775
|
+
subtype: z7.string().optional(),
|
|
1776
|
+
compactMetadata: z7.looseObject({}).optional()
|
|
1777
|
+
});
|
|
1778
|
+
var textBlockSchema = z7.looseObject({ type: z7.literal("text"), text: z7.string() });
|
|
1779
|
+
var toolUseBlockSchema = z7.looseObject({
|
|
1780
|
+
type: z7.literal("tool_use"),
|
|
1781
|
+
id: z7.string(),
|
|
1782
|
+
name: z7.string(),
|
|
1783
|
+
input: z7.unknown()
|
|
1784
|
+
});
|
|
1785
|
+
var toolResultBlockSchema = z7.looseObject({
|
|
1786
|
+
type: z7.literal("tool_result"),
|
|
1787
|
+
tool_use_id: z7.string(),
|
|
1788
|
+
content: z7.union([z7.string(), z7.array(z7.unknown())]).optional(),
|
|
1789
|
+
is_error: z7.boolean().optional()
|
|
1790
|
+
});
|
|
1791
|
+
var fileEditResultSchema = z7.looseObject({
|
|
1792
|
+
filePath: z7.string(),
|
|
1793
|
+
type: z7.string().optional(),
|
|
1794
|
+
content: z7.string().optional(),
|
|
1795
|
+
structuredPatch: z7.array(z7.looseObject({ lines: z7.array(z7.string()) }))
|
|
1796
|
+
});
|
|
1797
|
+
var GENERATED_PREFIXES = [
|
|
1798
|
+
"<local-command-",
|
|
1799
|
+
"<task-notification",
|
|
1800
|
+
"<system-reminder",
|
|
1801
|
+
"<bash-input",
|
|
1802
|
+
"<bash-stdout",
|
|
1803
|
+
"<bash-stderr",
|
|
1804
|
+
"[Request interrupted"
|
|
1805
|
+
];
|
|
1806
|
+
function encodeProjectDir(cwd) {
|
|
1807
|
+
return cwd.replace(/[^a-zA-Z0-9]/g, "-");
|
|
1808
|
+
}
|
|
1809
|
+
var claudeCodeAdapter = {
|
|
1810
|
+
tool: "claude_code",
|
|
1811
|
+
async findTranscripts(roots) {
|
|
1812
|
+
const projects = join5(roots.claudeDir, "projects");
|
|
1813
|
+
const files = await findFiles(projects, ".jsonl", 1);
|
|
1814
|
+
return files.filter((file) => dirname2(dirname2(file)) === projects);
|
|
1815
|
+
},
|
|
1816
|
+
async parse(file) {
|
|
1817
|
+
let bytes;
|
|
1818
|
+
try {
|
|
1819
|
+
bytes = (await stat2(file)).size;
|
|
1820
|
+
} catch {
|
|
1821
|
+
return { status: "unsupported", file, bytes: 0, reason: "the file could not be read" };
|
|
1822
|
+
}
|
|
1823
|
+
const stats = { skippedLines: 0, lines: 0 };
|
|
1824
|
+
const events = [];
|
|
1825
|
+
const versions = /* @__PURE__ */ new Set();
|
|
1826
|
+
const toolNames = /* @__PURE__ */ new Map();
|
|
1827
|
+
const turns = /* @__PURE__ */ new Map();
|
|
1828
|
+
let recognized = 0;
|
|
1829
|
+
let project = null;
|
|
1830
|
+
let first;
|
|
1831
|
+
let last;
|
|
1832
|
+
try {
|
|
1833
|
+
for await (const raw of readJsonObjects(file, stats)) {
|
|
1834
|
+
const parsed = recordSchema.safeParse(raw);
|
|
1835
|
+
if (!parsed.success) continue;
|
|
1836
|
+
const record = parsed.data;
|
|
1837
|
+
recognized += 1;
|
|
1838
|
+
if (record.isSidechain === true) continue;
|
|
1839
|
+
if (record.version !== void 0) versions.add(record.version);
|
|
1840
|
+
if (project === null && record.cwd !== void 0 && record.cwd !== "") project = record.cwd;
|
|
1841
|
+
const at = isoOrUndefined(record.timestamp);
|
|
1842
|
+
if (at !== void 0) {
|
|
1843
|
+
if (first === void 0 || at < first) first = at;
|
|
1844
|
+
if (last === void 0 || at > last) last = at;
|
|
1845
|
+
}
|
|
1846
|
+
if (record.type === "user") readUser(record, at, toolNames, events);
|
|
1847
|
+
else if (record.type === "assistant") {
|
|
1848
|
+
readTurn(record, at, turns, events);
|
|
1849
|
+
readAssistant(record, at, toolNames, events);
|
|
1850
|
+
} else if (record.type === "system" && record.subtype === "compact_boundary") {
|
|
1851
|
+
const meta = record.compactMetadata ?? {};
|
|
1852
|
+
const trigger = meta.trigger === "manual" || meta.trigger === "auto" ? meta.trigger : null;
|
|
1853
|
+
events.push(
|
|
1854
|
+
withTime(
|
|
1855
|
+
{
|
|
1856
|
+
kind: "compaction",
|
|
1857
|
+
trigger,
|
|
1858
|
+
preTokens: tokensOrNull(meta.preTokens),
|
|
1859
|
+
postTokens: tokensOrNull(meta.postTokens)
|
|
1860
|
+
},
|
|
1861
|
+
at
|
|
1862
|
+
)
|
|
1863
|
+
);
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
} catch {
|
|
1867
|
+
return { status: "unsupported", file, bytes, reason: "the file could not be read" };
|
|
1868
|
+
}
|
|
1869
|
+
if (stats.lines > 0 && recognized === 0) {
|
|
1870
|
+
return {
|
|
1871
|
+
status: "unsupported",
|
|
1872
|
+
file,
|
|
1873
|
+
bytes,
|
|
1874
|
+
reason: "no Claude Code transcript records were found in it"
|
|
1875
|
+
};
|
|
1876
|
+
}
|
|
1877
|
+
if (events.length === 0) return { status: "empty", file, bytes };
|
|
1878
|
+
const fallbackTime = (await stat2(file)).mtime.toISOString();
|
|
1879
|
+
const toolVersion = highestVersion(versions);
|
|
1880
|
+
const session = {
|
|
1881
|
+
tool: "claude_code",
|
|
1882
|
+
id: basename(file, ".jsonl"),
|
|
1883
|
+
project: project ?? basename(dirname2(file)),
|
|
1884
|
+
startedAt: first ?? fallbackTime,
|
|
1885
|
+
endedAt: last ?? fallbackTime,
|
|
1886
|
+
toolVersion,
|
|
1887
|
+
events
|
|
1888
|
+
};
|
|
1889
|
+
return {
|
|
1890
|
+
status: "ok",
|
|
1891
|
+
session,
|
|
1892
|
+
file,
|
|
1893
|
+
bytes,
|
|
1894
|
+
skippedLines: stats.skippedLines,
|
|
1895
|
+
versionNote: versionNote("claude_code", toolVersion)
|
|
1896
|
+
};
|
|
1897
|
+
},
|
|
1898
|
+
async findInstructionFiles(roots, project) {
|
|
1899
|
+
const found = [];
|
|
1900
|
+
for (const path of [join5(project, "CLAUDE.md"), join5(project, ".claude", "CLAUDE.md")]) {
|
|
1901
|
+
const bytes = await fileSize(path);
|
|
1902
|
+
if (bytes !== null) found.push({ kind: "claude_md", path, bytes });
|
|
1903
|
+
}
|
|
1904
|
+
const memoryDir = join5(roots.claudeDir, "projects", encodeProjectDir(project), "memory");
|
|
1905
|
+
for (const path of await findFiles(memoryDir, ".md", 0)) {
|
|
1906
|
+
const bytes = await fileSize(path);
|
|
1907
|
+
if (bytes !== null) found.push({ kind: "memory", path, bytes });
|
|
1908
|
+
}
|
|
1909
|
+
return found;
|
|
1910
|
+
},
|
|
1911
|
+
findSetup(roots, project) {
|
|
1912
|
+
return claudeSetup(roots.claudeDir, project);
|
|
1913
|
+
}
|
|
1914
|
+
};
|
|
1915
|
+
function readUser(record, at, toolNames, events) {
|
|
1916
|
+
const content = record.message?.content;
|
|
1917
|
+
if (typeof content === "string") {
|
|
1918
|
+
if (record.isMeta === true) return;
|
|
1919
|
+
if (record.origin !== void 0 && record.origin.kind !== "human") return;
|
|
1920
|
+
const text2 = promptText(content);
|
|
1921
|
+
if (text2 !== null) events.push(withTime({ kind: "user_prompt", text: text2 }, at));
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
if (!Array.isArray(content)) return;
|
|
1925
|
+
const texts = [];
|
|
1926
|
+
const resultCount = content.filter(
|
|
1927
|
+
(block) => toolResultBlockSchema.safeParse(block).success
|
|
1928
|
+
).length;
|
|
1929
|
+
for (const block of content) {
|
|
1930
|
+
const text2 = textBlockSchema.safeParse(block);
|
|
1931
|
+
if (text2.success) {
|
|
1932
|
+
texts.push(text2.data.text);
|
|
1933
|
+
continue;
|
|
1934
|
+
}
|
|
1935
|
+
const result = toolResultBlockSchema.safeParse(block);
|
|
1936
|
+
if (!result.success) continue;
|
|
1937
|
+
const output = resultText(result.data.content);
|
|
1938
|
+
const name = toolNames.get(result.data.tool_use_id);
|
|
1939
|
+
const exitCode = name === "Bash" ? bashExitCode(result.data.is_error === true, output) : null;
|
|
1940
|
+
events.push(
|
|
1941
|
+
withTime(
|
|
1942
|
+
{
|
|
1943
|
+
kind: "tool_result",
|
|
1944
|
+
...summarizeOutput(output),
|
|
1945
|
+
...exitCode === null ? {} : { exitCode }
|
|
1946
|
+
},
|
|
1947
|
+
at
|
|
1948
|
+
)
|
|
1949
|
+
);
|
|
1950
|
+
if (resultCount === 1 && result.data.is_error !== true) {
|
|
1951
|
+
const edit = fileEditResultSchema.safeParse(record.toolUseResult);
|
|
1952
|
+
if (edit.success) events.push(withTime(fileEdit(edit.data), at));
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
if (record.isMeta === true || texts.length === 0) return;
|
|
1956
|
+
const text = promptText(texts.join("\n"));
|
|
1957
|
+
if (text !== null) events.push(withTime({ kind: "user_prompt", text }, at));
|
|
1958
|
+
}
|
|
1959
|
+
function readTurn(record, at, turns, events) {
|
|
1960
|
+
const message = record.message;
|
|
1961
|
+
if (message?.id === void 0 || message.usage === void 0) return;
|
|
1962
|
+
if (message.model === "<synthetic>") return;
|
|
1963
|
+
const usage = message.usage;
|
|
1964
|
+
const outputTokens = tokens(usage.output_tokens);
|
|
1965
|
+
const seen = turns.get(message.id);
|
|
1966
|
+
if (seen !== void 0) {
|
|
1967
|
+
seen.outputTokens = Math.max(seen.outputTokens, outputTokens);
|
|
1968
|
+
return;
|
|
1969
|
+
}
|
|
1970
|
+
const turn = withTime(
|
|
1971
|
+
{
|
|
1972
|
+
kind: "model_turn",
|
|
1973
|
+
model: modelIdOrNull(message.model),
|
|
1974
|
+
effort: effortOrNull(record.effort),
|
|
1975
|
+
contextTokens: Math.min(
|
|
1976
|
+
tokens(usage.input_tokens) + tokens(usage.cache_read_input_tokens) + tokens(usage.cache_creation_input_tokens),
|
|
1977
|
+
1e8
|
|
1978
|
+
),
|
|
1979
|
+
outputTokens
|
|
1980
|
+
},
|
|
1981
|
+
at
|
|
1982
|
+
);
|
|
1983
|
+
turns.set(message.id, turn);
|
|
1984
|
+
events.push(turn);
|
|
1985
|
+
}
|
|
1986
|
+
function readAssistant(record, at, toolNames, events) {
|
|
1987
|
+
const content = record.message?.content;
|
|
1988
|
+
if (!Array.isArray(content)) return;
|
|
1989
|
+
for (const block of content) {
|
|
1990
|
+
const text = textBlockSchema.safeParse(block);
|
|
1991
|
+
if (text.success) {
|
|
1992
|
+
if (text.data.text.trim() !== "") {
|
|
1993
|
+
events.push(withTime({ kind: "assistant_text", text: text.data.text }, at));
|
|
1994
|
+
}
|
|
1995
|
+
continue;
|
|
1996
|
+
}
|
|
1997
|
+
const call = toolUseBlockSchema.safeParse(block);
|
|
1998
|
+
if (call.success) {
|
|
1999
|
+
toolNames.set(call.data.id, call.data.name);
|
|
2000
|
+
const model = SUBAGENT_TOOLS2.has(call.data.name) ? subagentModel(call.data.input) : null;
|
|
2001
|
+
events.push(
|
|
2002
|
+
withTime(
|
|
2003
|
+
{
|
|
2004
|
+
kind: "tool_call",
|
|
2005
|
+
name: call.data.name,
|
|
2006
|
+
argsSummary: summarizeArgs(call.data.input),
|
|
2007
|
+
...model === null ? {} : { model }
|
|
2008
|
+
},
|
|
2009
|
+
at
|
|
2010
|
+
)
|
|
2011
|
+
);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
var SUBAGENT_TOOLS2 = /* @__PURE__ */ new Set(["Agent", "Task"]);
|
|
2016
|
+
function subagentModel(input) {
|
|
2017
|
+
if (typeof input !== "object" || input === null) return null;
|
|
2018
|
+
return modelIdOrNull(input.model);
|
|
2019
|
+
}
|
|
2020
|
+
function promptText(content) {
|
|
2021
|
+
const trimmed = content.trim();
|
|
2022
|
+
if (trimmed === "") return null;
|
|
2023
|
+
const command = /<command-name>([^<]*)<\/command-name>/.exec(trimmed);
|
|
2024
|
+
if (command !== null) {
|
|
2025
|
+
const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(trimmed)?.[1]?.trim() ?? "";
|
|
2026
|
+
const name = (command[1] ?? "").trim();
|
|
2027
|
+
return args === "" ? name : `${name} ${args}`;
|
|
2028
|
+
}
|
|
2029
|
+
if (GENERATED_PREFIXES.some((prefix) => trimmed.startsWith(prefix))) return null;
|
|
2030
|
+
return trimmed;
|
|
2031
|
+
}
|
|
2032
|
+
function resultText(content) {
|
|
2033
|
+
if (typeof content === "string") return content;
|
|
2034
|
+
if (content === void 0) return "";
|
|
2035
|
+
return content.map((block) => {
|
|
2036
|
+
const text = textBlockSchema.safeParse(block);
|
|
2037
|
+
return text.success ? text.data.text : "";
|
|
2038
|
+
}).filter((text) => text !== "").join("\n");
|
|
2039
|
+
}
|
|
2040
|
+
function bashExitCode(isError, output) {
|
|
2041
|
+
if (!isError) return 0;
|
|
2042
|
+
const match = /^Exit code (\d+)/.exec(output.trim());
|
|
2043
|
+
return match === null ? null : Number(match[1]);
|
|
2044
|
+
}
|
|
2045
|
+
function fileEdit(result) {
|
|
2046
|
+
const linesChanged = result.type === "create" && result.content !== void 0 ? countContentLines(result.content) : countDiffLines(result.structuredPatch.flatMap((hunk) => hunk.lines));
|
|
2047
|
+
return { kind: "file_edit", path: oneLine(result.filePath, 1024), linesChanged };
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
// src/adapters/codex.ts
|
|
2051
|
+
import { stat as stat3 } from "fs/promises";
|
|
2052
|
+
import { join as join6 } from "path";
|
|
2053
|
+
import { z as z8 } from "zod";
|
|
2054
|
+
var recordSchema2 = z8.looseObject({
|
|
2055
|
+
type: z8.string(),
|
|
2056
|
+
timestamp: z8.string().optional(),
|
|
2057
|
+
payload: z8.looseObject({ type: z8.string().optional() })
|
|
2058
|
+
});
|
|
2059
|
+
var turnContextSchema = z8.looseObject({
|
|
2060
|
+
model: z8.unknown().optional(),
|
|
2061
|
+
effort: z8.unknown().optional()
|
|
2062
|
+
});
|
|
2063
|
+
var usageSchema = z8.looseObject({ input_tokens: z8.unknown(), output_tokens: z8.unknown() });
|
|
2064
|
+
var tokenCountSchema2 = z8.looseObject({
|
|
2065
|
+
info: z8.looseObject({
|
|
2066
|
+
last_token_usage: usageSchema,
|
|
2067
|
+
total_token_usage: z8.looseObject({ total_tokens: z8.unknown() })
|
|
2068
|
+
})
|
|
2069
|
+
});
|
|
2070
|
+
var sessionMetaSchema = z8.looseObject({
|
|
2071
|
+
id: z8.string(),
|
|
2072
|
+
cwd: z8.string(),
|
|
2073
|
+
cli_version: z8.string().optional(),
|
|
2074
|
+
timestamp: z8.string().optional()
|
|
2075
|
+
});
|
|
2076
|
+
var messageSchema = z8.looseObject({ message: z8.string() });
|
|
2077
|
+
var functionCallSchema = z8.looseObject({
|
|
2078
|
+
name: z8.string(),
|
|
2079
|
+
arguments: z8.string(),
|
|
2080
|
+
call_id: z8.string()
|
|
2081
|
+
});
|
|
2082
|
+
var customCallSchema = z8.looseObject({
|
|
2083
|
+
name: z8.string(),
|
|
2084
|
+
input: z8.string(),
|
|
2085
|
+
call_id: z8.string()
|
|
2086
|
+
});
|
|
2087
|
+
var callOutputSchema = z8.looseObject({ call_id: z8.string(), output: z8.unknown() });
|
|
2088
|
+
var execEndSchema = z8.looseObject({ call_id: z8.string(), exit_code: z8.number().int() });
|
|
2089
|
+
var webSearchSchema = z8.looseObject({ action: z8.looseObject({ query: z8.string() }) });
|
|
2090
|
+
var customOutputBodySchema = z8.looseObject({
|
|
2091
|
+
output: z8.string(),
|
|
2092
|
+
metadata: z8.looseObject({ exit_code: z8.number().int() }).optional()
|
|
2093
|
+
});
|
|
2094
|
+
var patchEndSchema = z8.looseObject({
|
|
2095
|
+
success: z8.boolean(),
|
|
2096
|
+
changes: z8.record(
|
|
2097
|
+
z8.string(),
|
|
2098
|
+
z8.looseObject({
|
|
2099
|
+
type: z8.string(),
|
|
2100
|
+
unified_diff: z8.string().optional(),
|
|
2101
|
+
content: z8.string().optional()
|
|
2102
|
+
})
|
|
2103
|
+
)
|
|
2104
|
+
});
|
|
2105
|
+
var codexAdapter = {
|
|
2106
|
+
tool: "codex",
|
|
2107
|
+
async findTranscripts(roots) {
|
|
2108
|
+
const files = await findFiles(join6(roots.codexDir, "sessions"), ".jsonl", 3);
|
|
2109
|
+
return files.filter((file) => /(^|\/)rollout-[^/]*\.jsonl$/.test(file));
|
|
2110
|
+
},
|
|
2111
|
+
async parse(file) {
|
|
2112
|
+
let bytes;
|
|
2113
|
+
try {
|
|
2114
|
+
bytes = (await stat3(file)).size;
|
|
2115
|
+
} catch {
|
|
2116
|
+
return { status: "unsupported", file, bytes: 0, reason: "the file could not be read" };
|
|
2117
|
+
}
|
|
2118
|
+
const stats = { skippedLines: 0, lines: 0 };
|
|
2119
|
+
const events = [];
|
|
2120
|
+
const exitCodes = /* @__PURE__ */ new Map();
|
|
2121
|
+
const turn = { model: null, effort: null, total: null };
|
|
2122
|
+
let meta = null;
|
|
2123
|
+
let first;
|
|
2124
|
+
let last;
|
|
2125
|
+
try {
|
|
2126
|
+
for await (const raw of readJsonObjects(file, stats)) {
|
|
2127
|
+
const parsed = recordSchema2.safeParse(raw);
|
|
2128
|
+
if (!parsed.success) continue;
|
|
2129
|
+
const { type, payload } = parsed.data;
|
|
2130
|
+
const at = isoOrUndefined(parsed.data.timestamp);
|
|
2131
|
+
if (at !== void 0) {
|
|
2132
|
+
if (first === void 0 || at < first) first = at;
|
|
2133
|
+
if (last === void 0 || at > last) last = at;
|
|
2134
|
+
}
|
|
2135
|
+
if (type === "session_meta") {
|
|
2136
|
+
const value = sessionMetaSchema.safeParse(payload);
|
|
2137
|
+
if (value.success && meta === null) meta = value.data;
|
|
2138
|
+
} else if (type === "turn_context") {
|
|
2139
|
+
const value = turnContextSchema.safeParse(payload);
|
|
2140
|
+
if (value.success) {
|
|
2141
|
+
turn.model = modelIdOrNull(value.data.model);
|
|
2142
|
+
turn.effort = effortOrNull(value.data.effort);
|
|
2143
|
+
}
|
|
2144
|
+
} else if (type === "compacted") {
|
|
2145
|
+
events.push(
|
|
2146
|
+
withTime({ kind: "compaction", trigger: null, preTokens: null, postTokens: null }, at)
|
|
2147
|
+
);
|
|
2148
|
+
} else if (type === "event_msg") {
|
|
2149
|
+
if (payload.type === "token_count") readTokenCount(payload, at, turn, events);
|
|
2150
|
+
else readEventMessage(payload, at, exitCodes, events);
|
|
2151
|
+
} else if (type === "response_item") {
|
|
2152
|
+
readResponseItem(payload, at, exitCodes, events);
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
} catch {
|
|
2156
|
+
return { status: "unsupported", file, bytes, reason: "the file could not be read" };
|
|
2157
|
+
}
|
|
2158
|
+
if (stats.lines === 0) return { status: "empty", file, bytes };
|
|
2159
|
+
if (meta === null) {
|
|
2160
|
+
return {
|
|
2161
|
+
status: "unsupported",
|
|
2162
|
+
file,
|
|
2163
|
+
bytes,
|
|
2164
|
+
reason: "no Codex session_meta record was found in it"
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
if (events.length === 0) return { status: "empty", file, bytes };
|
|
2168
|
+
const metaTime = isoOrUndefined(meta.timestamp);
|
|
2169
|
+
const toolVersion = meta.cli_version ?? null;
|
|
2170
|
+
const session = {
|
|
2171
|
+
tool: "codex",
|
|
2172
|
+
id: meta.id,
|
|
2173
|
+
project: meta.cwd,
|
|
2174
|
+
startedAt: first ?? metaTime ?? (await stat3(file)).mtime.toISOString(),
|
|
2175
|
+
endedAt: last ?? metaTime ?? (await stat3(file)).mtime.toISOString(),
|
|
2176
|
+
toolVersion,
|
|
2177
|
+
events
|
|
2178
|
+
};
|
|
2179
|
+
return {
|
|
2180
|
+
status: "ok",
|
|
2181
|
+
session,
|
|
2182
|
+
file,
|
|
2183
|
+
bytes,
|
|
2184
|
+
skippedLines: stats.skippedLines,
|
|
2185
|
+
versionNote: versionNote("codex", toolVersion)
|
|
2186
|
+
};
|
|
2187
|
+
},
|
|
2188
|
+
findInstructionFiles() {
|
|
2189
|
+
return Promise.resolve([]);
|
|
2190
|
+
},
|
|
2191
|
+
findSetup() {
|
|
2192
|
+
return Promise.resolve(null);
|
|
2193
|
+
}
|
|
2194
|
+
};
|
|
2195
|
+
function readTokenCount(payload, at, turn, events) {
|
|
2196
|
+
const value = tokenCountSchema2.safeParse(payload);
|
|
2197
|
+
if (!value.success) return;
|
|
2198
|
+
const total = tokens(value.data.info.total_token_usage.total_tokens);
|
|
2199
|
+
if (total === turn.total) return;
|
|
2200
|
+
turn.total = total;
|
|
2201
|
+
const contextTokens = tokens(value.data.info.last_token_usage.input_tokens);
|
|
2202
|
+
if (contextTokens === 0) return;
|
|
2203
|
+
events.push(
|
|
2204
|
+
withTime(
|
|
2205
|
+
{
|
|
2206
|
+
kind: "model_turn",
|
|
2207
|
+
model: turn.model,
|
|
2208
|
+
effort: turn.effort,
|
|
2209
|
+
contextTokens,
|
|
2210
|
+
outputTokens: tokens(value.data.info.last_token_usage.output_tokens)
|
|
2211
|
+
},
|
|
2212
|
+
at
|
|
2213
|
+
)
|
|
2214
|
+
);
|
|
2215
|
+
}
|
|
2216
|
+
function readEventMessage(payload, at, exitCodes, events) {
|
|
2217
|
+
switch (payload.type) {
|
|
2218
|
+
case "user_message": {
|
|
2219
|
+
const value = messageSchema.safeParse(payload);
|
|
2220
|
+
if (value.success && value.data.message.trim() !== "") {
|
|
2221
|
+
events.push(withTime({ kind: "user_prompt", text: value.data.message.trim() }, at));
|
|
2222
|
+
}
|
|
2223
|
+
return;
|
|
2224
|
+
}
|
|
2225
|
+
case "agent_message": {
|
|
2226
|
+
const value = messageSchema.safeParse(payload);
|
|
2227
|
+
if (value.success && value.data.message.trim() !== "") {
|
|
2228
|
+
events.push(withTime({ kind: "assistant_text", text: value.data.message }, at));
|
|
2229
|
+
}
|
|
2230
|
+
return;
|
|
2231
|
+
}
|
|
2232
|
+
case "exec_command_end": {
|
|
2233
|
+
const value = execEndSchema.safeParse(payload);
|
|
2234
|
+
if (value.success) exitCodes.set(value.data.call_id, value.data.exit_code);
|
|
2235
|
+
return;
|
|
2236
|
+
}
|
|
2237
|
+
case "patch_apply_end": {
|
|
2238
|
+
const value = patchEndSchema.safeParse(payload);
|
|
2239
|
+
if (!value.success || !value.data.success) return;
|
|
2240
|
+
for (const [path, change] of Object.entries(value.data.changes)) {
|
|
2241
|
+
const linesChanged = change.unified_diff !== void 0 ? countDiffLines(change.unified_diff.split("\n")) : countContentLines(change.content ?? "");
|
|
2242
|
+
events.push(withTime({ kind: "file_edit", path: oneLine(path, 1024), linesChanged }, at));
|
|
2243
|
+
}
|
|
2244
|
+
return;
|
|
2245
|
+
}
|
|
2246
|
+
default:
|
|
2247
|
+
return;
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
function readResponseItem(payload, at, exitCodes, events) {
|
|
2251
|
+
switch (payload.type) {
|
|
2252
|
+
case "function_call": {
|
|
2253
|
+
const value = functionCallSchema.safeParse(payload);
|
|
2254
|
+
if (!value.success) return;
|
|
2255
|
+
events.push(
|
|
2256
|
+
withTime(
|
|
2257
|
+
{
|
|
2258
|
+
kind: "tool_call",
|
|
2259
|
+
name: value.data.name,
|
|
2260
|
+
argsSummary: summarizeArgs(parseJson(value.data.arguments) ?? value.data.arguments)
|
|
2261
|
+
},
|
|
2262
|
+
at
|
|
2263
|
+
)
|
|
2264
|
+
);
|
|
2265
|
+
return;
|
|
2266
|
+
}
|
|
2267
|
+
case "custom_tool_call": {
|
|
2268
|
+
const value = customCallSchema.safeParse(payload);
|
|
2269
|
+
if (!value.success) return;
|
|
2270
|
+
const argsSummary = value.data.name === "apply_patch" ? patchedFiles(value.data.input) : summarizeArgs(value.data.input);
|
|
2271
|
+
events.push(withTime({ kind: "tool_call", name: value.data.name, argsSummary }, at));
|
|
2272
|
+
return;
|
|
2273
|
+
}
|
|
2274
|
+
case "web_search_call": {
|
|
2275
|
+
const value = webSearchSchema.safeParse(payload);
|
|
2276
|
+
if (!value.success) return;
|
|
2277
|
+
events.push(
|
|
2278
|
+
withTime(
|
|
2279
|
+
{
|
|
2280
|
+
kind: "tool_call",
|
|
2281
|
+
name: "web_search",
|
|
2282
|
+
argsSummary: oneLine(value.data.action.query, 200)
|
|
2283
|
+
},
|
|
2284
|
+
at
|
|
2285
|
+
)
|
|
2286
|
+
);
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
case "function_call_output": {
|
|
2290
|
+
const value = callOutputSchema.safeParse(payload);
|
|
2291
|
+
if (!value.success) return;
|
|
2292
|
+
const output = typeof value.data.output === "string" ? value.data.output : "";
|
|
2293
|
+
const exitCode = exitCodes.get(value.data.call_id) ?? processExitCode(output);
|
|
2294
|
+
events.push(
|
|
2295
|
+
withTime(
|
|
2296
|
+
{
|
|
2297
|
+
kind: "tool_result",
|
|
2298
|
+
...summarizeOutput(commandOutput(output)),
|
|
2299
|
+
...exitCode === null ? {} : { exitCode }
|
|
2300
|
+
},
|
|
2301
|
+
at
|
|
2302
|
+
)
|
|
2303
|
+
);
|
|
2304
|
+
return;
|
|
2305
|
+
}
|
|
2306
|
+
case "custom_tool_call_output": {
|
|
2307
|
+
const value = callOutputSchema.safeParse(payload);
|
|
2308
|
+
if (!value.success) return;
|
|
2309
|
+
const raw = typeof value.data.output === "string" ? value.data.output : "";
|
|
2310
|
+
const body = customOutputBodySchema.safeParse(parseJson(raw));
|
|
2311
|
+
const output = body.success ? body.data.output : raw;
|
|
2312
|
+
const exitCode = body.success ? body.data.metadata?.exit_code : void 0;
|
|
2313
|
+
events.push(
|
|
2314
|
+
withTime(
|
|
2315
|
+
{
|
|
2316
|
+
kind: "tool_result",
|
|
2317
|
+
...summarizeOutput(output),
|
|
2318
|
+
...exitCode === void 0 ? {} : { exitCode }
|
|
2319
|
+
},
|
|
2320
|
+
at
|
|
2321
|
+
)
|
|
2322
|
+
);
|
|
2323
|
+
return;
|
|
2324
|
+
}
|
|
2325
|
+
default:
|
|
2326
|
+
return;
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
function parseJson(text) {
|
|
2330
|
+
try {
|
|
2331
|
+
return JSON.parse(text);
|
|
2332
|
+
} catch {
|
|
2333
|
+
return void 0;
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
function patchedFiles(input) {
|
|
2337
|
+
const files = [...input.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map(
|
|
2338
|
+
(match) => (match[1] ?? "").trim()
|
|
2339
|
+
);
|
|
2340
|
+
return files.length > 0 ? oneLine(files.join(", "), 200) : summarizeArgs(input);
|
|
2341
|
+
}
|
|
2342
|
+
function commandOutput(output) {
|
|
2343
|
+
const marker = output.indexOf("\nOutput:\n");
|
|
2344
|
+
return marker === -1 ? output : output.slice(marker + "\nOutput:\n".length);
|
|
2345
|
+
}
|
|
2346
|
+
function processExitCode(output) {
|
|
2347
|
+
const match = /Process exited with code (\d+)/.exec(output);
|
|
2348
|
+
return match === null ? null : Number(match[1]);
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
// src/discover.ts
|
|
2352
|
+
var ADAPTERS = [claudeCodeAdapter, codexAdapter];
|
|
2353
|
+
var PARSE_CONCURRENCY = 8;
|
|
2354
|
+
async function scanSources(roots, adapters = ADAPTERS) {
|
|
2355
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
2356
|
+
const unsupported = [];
|
|
2357
|
+
const notes = /* @__PURE__ */ new Set();
|
|
2358
|
+
let skippedLines = 0;
|
|
2359
|
+
for (const adapter of adapters) {
|
|
2360
|
+
const files = await adapter.findTranscripts(roots);
|
|
2361
|
+
const results = await mapLimit(files, PARSE_CONCURRENCY, (file) => adapter.parse(file));
|
|
2362
|
+
for (const result of results) {
|
|
2363
|
+
if (result.status === "unsupported") {
|
|
2364
|
+
unsupported.push({ tool: adapter.tool, file: result.file, reason: result.reason });
|
|
2365
|
+
continue;
|
|
2366
|
+
}
|
|
2367
|
+
if (result.status === "empty") continue;
|
|
2368
|
+
skippedLines += result.skippedLines;
|
|
2369
|
+
if (result.versionNote !== null) notes.add(result.versionNote);
|
|
2370
|
+
addSession(byKey, result);
|
|
2371
|
+
}
|
|
2372
|
+
for (const summary of byKey.values()) {
|
|
2373
|
+
if (summary.tool === adapter.tool) {
|
|
2374
|
+
summary.instructionFiles = await adapter.findInstructionFiles(roots, summary.project);
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
const projects = [...byKey.values()].sort(
|
|
2379
|
+
(a, b) => a.lastAt === b.lastAt ? a.project.localeCompare(b.project) : a.lastAt < b.lastAt ? 1 : -1
|
|
2380
|
+
);
|
|
2381
|
+
return { projects, unsupported, skippedLines, versionNotes: [...notes] };
|
|
2382
|
+
}
|
|
2383
|
+
function projectKey(tool, project) {
|
|
2384
|
+
return `${tool}\0${project}`;
|
|
2385
|
+
}
|
|
2386
|
+
function addSession(byKey, result) {
|
|
2387
|
+
const { session } = result;
|
|
2388
|
+
const key = projectKey(session.tool, session.project);
|
|
2389
|
+
const existing = byKey.get(key);
|
|
2390
|
+
if (existing === void 0) {
|
|
2391
|
+
byKey.set(key, {
|
|
2392
|
+
tool: session.tool,
|
|
2393
|
+
project: session.project,
|
|
2394
|
+
sessions: 1,
|
|
2395
|
+
firstAt: session.startedAt,
|
|
2396
|
+
lastAt: session.endedAt,
|
|
2397
|
+
bytes: result.bytes,
|
|
2398
|
+
instructionFiles: []
|
|
2399
|
+
});
|
|
2400
|
+
return;
|
|
2401
|
+
}
|
|
2402
|
+
existing.sessions += 1;
|
|
2403
|
+
existing.bytes += result.bytes;
|
|
2404
|
+
if (session.startedAt < existing.firstAt) existing.firstAt = session.startedAt;
|
|
2405
|
+
if (session.endedAt > existing.lastAt) existing.lastAt = session.endedAt;
|
|
2406
|
+
}
|
|
2407
|
+
async function mapLimit(items, limit, run) {
|
|
2408
|
+
const results = new Array(items.length);
|
|
2409
|
+
let next = 0;
|
|
2410
|
+
async function worker() {
|
|
2411
|
+
while (next < items.length) {
|
|
2412
|
+
const index = next;
|
|
2413
|
+
next += 1;
|
|
2414
|
+
results[index] = await run(items[index]);
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
|
|
2418
|
+
return results;
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
// src/commands/card.ts
|
|
2422
|
+
var HANDLE_TIMEOUT_MS = 4e3;
|
|
2423
|
+
var DEFAULT_OUT = "xtrium-card";
|
|
2424
|
+
function parseSince(text, now) {
|
|
2425
|
+
const trimmed = text.trim();
|
|
2426
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
|
|
2427
|
+
const [year, month2, day2] = trimmed.split("-").map(Number);
|
|
2428
|
+
const date = new Date(year ?? 0, (month2 ?? 1) - 1, day2 ?? 1);
|
|
2429
|
+
if (!Number.isNaN(date.getTime()) && date.getDate() === day2) return date;
|
|
2430
|
+
}
|
|
2431
|
+
const span = /^(\d{1,4})([dwmy])$/.exec(trimmed);
|
|
2432
|
+
if (span !== null) {
|
|
2433
|
+
const amount = Number(span[1]);
|
|
2434
|
+
const date = new Date(now);
|
|
2435
|
+
if (span[2] === "d") date.setDate(date.getDate() - amount);
|
|
2436
|
+
if (span[2] === "w") date.setDate(date.getDate() - amount * 7);
|
|
2437
|
+
if (span[2] === "m") date.setMonth(date.getMonth() - amount);
|
|
2438
|
+
if (span[2] === "y") date.setFullYear(date.getFullYear() - amount);
|
|
2439
|
+
return date;
|
|
2440
|
+
}
|
|
2441
|
+
throw new CliError(
|
|
2442
|
+
`--since takes a date (2026-01-31) or a span such as 30d, 8w, 6m or 1y, not "${text}".`
|
|
2443
|
+
);
|
|
2444
|
+
}
|
|
2445
|
+
function outputPaths(cwd, out) {
|
|
2446
|
+
const base = resolve(cwd, (out ?? DEFAULT_OUT).replace(/\.(png|svg)$/i, ""));
|
|
2447
|
+
return { png: `${base}.png`, svg: `${base}.svg` };
|
|
2448
|
+
}
|
|
2449
|
+
async function countHistory(roots, adapters, since, topics, theme) {
|
|
2450
|
+
const counter = new CardCounter();
|
|
2451
|
+
const from = since?.toISOString() ?? null;
|
|
2452
|
+
for (const adapter of adapters) {
|
|
2453
|
+
const files = await adapter.findTranscripts(roots);
|
|
2454
|
+
await mapLimit(files, PARSE_CONCURRENCY, async (file) => {
|
|
2455
|
+
const result = await adapter.parse(file);
|
|
2456
|
+
if (result.status !== "ok") return;
|
|
2457
|
+
if (from !== null && result.session.startedAt < from) return;
|
|
2458
|
+
counter.addSession(result.session);
|
|
2459
|
+
});
|
|
2460
|
+
}
|
|
2461
|
+
return counter.finish({ theme, topics });
|
|
2462
|
+
}
|
|
2463
|
+
async function card(options, deps) {
|
|
2464
|
+
const theme = cardThemeSchema.safeParse(options.theme);
|
|
2465
|
+
if (!theme.success) throw new CliError(`--theme is retro or slate, not "${options.theme}".`);
|
|
2466
|
+
if (options.share && options.unshare) throw new CliError("Use --share or --unshare, not both.");
|
|
2467
|
+
const { out } = deps;
|
|
2468
|
+
if (options.unshare) {
|
|
2469
|
+
const account = await deps.account();
|
|
2470
|
+
const token = await account.credentials.load(account.api.origin);
|
|
2471
|
+
if (token === null) throw new CliError("Not signed in. Run `xtrium login` first.");
|
|
2472
|
+
await account.api.unshareCard(token);
|
|
2473
|
+
out.info("Your shared card was taken down.");
|
|
2474
|
+
return;
|
|
2475
|
+
}
|
|
2476
|
+
const since = options.since === void 0 ? null : parseSince(options.since, deps.now());
|
|
2477
|
+
const counted = await countHistory(
|
|
2478
|
+
deps.roots,
|
|
2479
|
+
deps.adapters ?? ADAPTERS,
|
|
2480
|
+
since,
|
|
2481
|
+
options.topics,
|
|
2482
|
+
theme.data
|
|
2483
|
+
);
|
|
2484
|
+
if (counted === null) {
|
|
2485
|
+
throw new CliError(
|
|
2486
|
+
since === null ? "No Claude Code or Codex sessions were found on this machine." : "No Claude Code or Codex sessions were found in that period."
|
|
2487
|
+
);
|
|
2488
|
+
}
|
|
2489
|
+
let handle = null;
|
|
2490
|
+
let shared = null;
|
|
2491
|
+
let checkedHandle = false;
|
|
2492
|
+
if (options.share) {
|
|
2493
|
+
const account = await deps.account();
|
|
2494
|
+
const token = await account.credentials.load(account.api.origin);
|
|
2495
|
+
if (token === null) {
|
|
2496
|
+
throw new CliError(
|
|
2497
|
+
"Sharing puts the card on your Atrium, so it needs an account: run `xtrium login` first."
|
|
2498
|
+
);
|
|
2499
|
+
}
|
|
2500
|
+
const response = await account.api.shareCard(token, counted);
|
|
2501
|
+
handle = response.handle;
|
|
2502
|
+
shared = response.visible ? `Shared at ${response.url}` : `Saved for ${response.url}; it shows there once your Atrium is published.`;
|
|
2503
|
+
} else {
|
|
2504
|
+
const account = await deps.account();
|
|
2505
|
+
const token = await account.credentials.load(account.api.origin);
|
|
2506
|
+
if (token !== null) {
|
|
2507
|
+
checkedHandle = true;
|
|
2508
|
+
try {
|
|
2509
|
+
handle = (await account.api.whoami(token, HANDLE_TIMEOUT_MS))?.handle ?? null;
|
|
2510
|
+
} catch {
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
}
|
|
2514
|
+
const paths = outputPaths(deps.cwd, options.out);
|
|
2515
|
+
const { svg, png } = await renderCard(counted, handle);
|
|
2516
|
+
await writeFile2(paths.png, png);
|
|
2517
|
+
await writeFile2(paths.svg, svg);
|
|
2518
|
+
out.info("Your card (counted on this machine, no AI):");
|
|
2519
|
+
for (const line of cardLines(counted)) out.info(` ${line}`);
|
|
2520
|
+
out.info(`Wrote ${paths.png} and ${paths.svg}`);
|
|
2521
|
+
if (shared !== null) {
|
|
2522
|
+
out.info(shared);
|
|
2523
|
+
out.info("Sent: the numbers above and their labels only. Take it down with --unshare.");
|
|
2524
|
+
} else if (checkedHandle) {
|
|
2525
|
+
out.info(
|
|
2526
|
+
handle === null ? "Could not reach xtrium.co to add your Atrium's address; the card says \u201Cmake your own Atrium\u201D." : `The card links to xtrium.co/${handle} (the only thing asked of the server). Nothing was uploaded.`
|
|
2527
|
+
);
|
|
2528
|
+
} else {
|
|
2529
|
+
out.info("Nothing was sent anywhere. Add --share to show it on your Atrium.");
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
|
|
2533
|
+
// src/commands/review.ts
|
|
2534
|
+
import { spinner as spinner2 } from "@clack/prompts";
|
|
2535
|
+
|
|
2536
|
+
// src/manifest.ts
|
|
2537
|
+
import { join as join7 } from "path";
|
|
2538
|
+
import { z as z9 } from "zod";
|
|
2539
|
+
var manifestSchema = z9.object({
|
|
2540
|
+
version: z9.literal(1),
|
|
2541
|
+
savedAt: z9.iso.datetime(),
|
|
2542
|
+
selections: z9.array(z9.object({ tool: z9.enum(TOOLS), project: z9.string().min(1) }).strict())
|
|
2543
|
+
}).strict();
|
|
2544
|
+
function manifestPath(dir) {
|
|
2545
|
+
return join7(dir, "manifest.json");
|
|
2546
|
+
}
|
|
2547
|
+
async function saveManifest(dir, selections, now = /* @__PURE__ */ new Date()) {
|
|
2548
|
+
const manifest = { version: 1, savedAt: now.toISOString(), selections };
|
|
2549
|
+
await writePrivateFile(manifestPath(dir), `${JSON.stringify(manifest, null, 2)}
|
|
2550
|
+
`);
|
|
2551
|
+
return manifest;
|
|
2552
|
+
}
|
|
2553
|
+
async function loadManifest(dir) {
|
|
2554
|
+
const text = await readOptionalFile(manifestPath(dir));
|
|
2555
|
+
if (text === null) return null;
|
|
2556
|
+
let value;
|
|
2557
|
+
try {
|
|
2558
|
+
value = JSON.parse(text);
|
|
2559
|
+
} catch {
|
|
2560
|
+
return null;
|
|
2561
|
+
}
|
|
2562
|
+
const parsed = manifestSchema.safeParse(value);
|
|
2563
|
+
return parsed.success ? parsed.data : null;
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
// src/review-server.ts
|
|
2567
|
+
import { randomBytes, timingSafeEqual } from "crypto";
|
|
2568
|
+
import { createServer } from "http";
|
|
2569
|
+
|
|
2570
|
+
// ../../packages/redact/src/entropy.ts
|
|
2571
|
+
function shannonEntropy(value) {
|
|
2572
|
+
if (value.length === 0) return 0;
|
|
2573
|
+
const counts = /* @__PURE__ */ new Map();
|
|
2574
|
+
for (const char of value) counts.set(char, (counts.get(char) ?? 0) + 1);
|
|
2575
|
+
let bits = 0;
|
|
2576
|
+
for (const count2 of counts.values()) {
|
|
2577
|
+
const p = count2 / value.length;
|
|
2578
|
+
bits -= p * Math.log2(p);
|
|
2579
|
+
}
|
|
2580
|
+
return bits;
|
|
2581
|
+
}
|
|
2582
|
+
var ENTROPY_MIN_LENGTH = 21;
|
|
2583
|
+
var HEX_MIN_LENGTH = 32;
|
|
2584
|
+
var HEX_MIN_ENTROPY = 3;
|
|
2585
|
+
var MIXED_MIN_ENTROPY = 4.2;
|
|
2586
|
+
var MIXED_LENGTH_MARGIN = 1.1;
|
|
2587
|
+
var MAX_WORDINESS = 0.4;
|
|
2588
|
+
function wordiness(token) {
|
|
2589
|
+
let inWords = 0;
|
|
2590
|
+
for (const match of token.matchAll(/[a-z]{3,}/g)) inWords += match[0].length;
|
|
2591
|
+
return token.length === 0 ? 0 : inWords / token.length;
|
|
2592
|
+
}
|
|
2593
|
+
function looksRandom(token) {
|
|
2594
|
+
if (token.length < ENTROPY_MIN_LENGTH) return false;
|
|
2595
|
+
if (!/[0-9]/.test(token) || !/[A-Za-z]/.test(token)) return false;
|
|
2596
|
+
if (/^[0-9a-f]+$/.test(token) || /^[0-9A-F]+$/.test(token)) {
|
|
2597
|
+
return token.length >= HEX_MIN_LENGTH && shannonEntropy(token) >= HEX_MIN_ENTROPY;
|
|
2598
|
+
}
|
|
2599
|
+
const pieces = token.split(/[_\-./=+]/).filter((piece) => piece.length > 0);
|
|
2600
|
+
if (pieces.length > 2 && pieces.every((piece) => piece.length <= 12)) return false;
|
|
2601
|
+
const entropy = shannonEntropy(token);
|
|
2602
|
+
if (entropy >= MIXED_MIN_ENTROPY) return true;
|
|
2603
|
+
return entropy >= Math.log2(token.length) - MIXED_LENGTH_MARGIN && wordiness(token) < MAX_WORDINESS;
|
|
2604
|
+
}
|
|
2605
|
+
|
|
2606
|
+
// ../../packages/redact/src/secrets.ts
|
|
2607
|
+
var rule = (id, pattern, group = 0) => ({ id, pattern, group });
|
|
2608
|
+
var B = "(?<![A-Za-z0-9_-])";
|
|
2609
|
+
var E = "(?![A-Za-z0-9_-])";
|
|
2610
|
+
var SECRET_RULES = [
|
|
2611
|
+
rule(
|
|
2612
|
+
"private-key",
|
|
2613
|
+
/-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\s\S]{64,}?-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----/g
|
|
2614
|
+
),
|
|
2615
|
+
rule(
|
|
2616
|
+
"aws-access-token",
|
|
2617
|
+
new RegExp(`${B}((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})${E}`, "g"),
|
|
2618
|
+
1
|
|
2619
|
+
),
|
|
2620
|
+
rule("github-fine-grained-pat", new RegExp(`${B}(github_pat_[A-Za-z0-9_]{82})${E}`, "g"), 1),
|
|
2621
|
+
rule("github-pat", new RegExp(`${B}(ghp_[A-Za-z0-9]{36})${E}`, "g"), 1),
|
|
2622
|
+
rule("github-oauth", new RegExp(`${B}(gho_[A-Za-z0-9]{36})${E}`, "g"), 1),
|
|
2623
|
+
rule("github-app-token", new RegExp(`${B}((?:ghu|ghs)_[A-Za-z0-9]{36})${E}`, "g"), 1),
|
|
2624
|
+
rule("github-refresh-token", new RegExp(`${B}(ghr_[A-Za-z0-9]{36})${E}`, "g"), 1),
|
|
2625
|
+
rule("gitlab-pat", new RegExp(`${B}(glpat-[A-Za-z0-9_-]{20,})${E}`, "g"), 1),
|
|
2626
|
+
rule("gitlab-ptt", new RegExp(`${B}(glptt-[A-Za-z0-9_-]{40})${E}`, "g"), 1),
|
|
2627
|
+
rule("gitlab-rrt", new RegExp(`${B}(GR1348941[A-Za-z0-9_-]{20})${E}`, "g"), 1),
|
|
2628
|
+
rule(
|
|
2629
|
+
"slack-webhook-url",
|
|
2630
|
+
/https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9+/]{43,56}/g
|
|
2631
|
+
),
|
|
2632
|
+
rule("slack-token", new RegExp(`${B}(xox[abposre]-[0-9A-Za-z-]{10,250})${E}`, "g"), 1),
|
|
2633
|
+
rule("slack-app-token", /\b(xapp-\d-[A-Z0-9]+-\d+-[a-z0-9]+)\b/gi, 1),
|
|
2634
|
+
rule(
|
|
2635
|
+
"stripe-access-token",
|
|
2636
|
+
new RegExp(`${B}((?:sk|rk)_(?:test|live|prod)_[A-Za-z0-9]{10,99})${E}`, "g"),
|
|
2637
|
+
1
|
|
2638
|
+
),
|
|
2639
|
+
rule("gcp-api-key", new RegExp(`${B}(AIza[A-Za-z0-9_-]{35})${E}`, "g"), 1),
|
|
2640
|
+
rule(
|
|
2641
|
+
"anthropic-api-key",
|
|
2642
|
+
new RegExp(`${B}(sk-ant-(?:api03|admin01)-[A-Za-z0-9_-]{93}AA)${E}`, "g"),
|
|
2643
|
+
1
|
|
2644
|
+
),
|
|
2645
|
+
rule(
|
|
2646
|
+
"openai-api-key",
|
|
2647
|
+
new RegExp(
|
|
2648
|
+
`${B}(sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,200}|sk-[A-Za-z0-9]{20}T3BlbkFJ[A-Za-z0-9]{20})${E}`,
|
|
2649
|
+
"g"
|
|
2650
|
+
),
|
|
2651
|
+
1
|
|
2652
|
+
),
|
|
2653
|
+
rule("npm-access-token", new RegExp(`${B}(npm_[A-Za-z0-9]{36})${E}`, "g"), 1),
|
|
2654
|
+
rule("pypi-upload-token", /pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,1000}/g),
|
|
2655
|
+
rule("sendgrid-api-token", new RegExp(`${B}(SG\\.[A-Za-z0-9=_.-]{66})${E}`, "g"), 1),
|
|
2656
|
+
rule("twilio-api-key", new RegExp(`${B}(SK[0-9a-fA-F]{32})${E}`, "g"), 1),
|
|
2657
|
+
rule("shopify-token", new RegExp(`${B}(shp(?:at|ca|pa|ss)_[a-fA-F0-9]{32})${E}`, "g"), 1),
|
|
2658
|
+
rule("digitalocean-token", new RegExp(`${B}(do[opr]_v1_[a-f0-9]{64})${E}`, "g"), 1),
|
|
2659
|
+
rule("hashicorp-vault-token", new RegExp(`${B}(hv[sb]\\.[A-Za-z0-9_-]{90,120})${E}`, "g"), 1),
|
|
2660
|
+
rule("doppler-api-token", /\b(dp\.pt\.[a-z0-9]{43})\b/gi, 1),
|
|
2661
|
+
rule("databricks-api-token", new RegExp(`${B}(dapi[a-f0-9]{32}(?:-\\d)?)${E}`, "g"), 1),
|
|
2662
|
+
rule("linear-api-key", /\b(lin_api_[a-z0-9]{40})\b/gi, 1),
|
|
2663
|
+
rule("postman-api-token", /\b(PMAK-[a-f0-9]{24}-[a-f0-9]{34})\b/gi, 1),
|
|
2664
|
+
rule("huggingface-access-token", new RegExp(`${B}(hf_[A-Za-z]{34})${E}`, "g"), 1),
|
|
2665
|
+
rule("age-secret-key", /AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}/g),
|
|
2666
|
+
rule("resend-api-key", new RegExp(`${B}(re_[A-Za-z0-9]{8}_[A-Za-z0-9]{24})${E}`, "g"), 1),
|
|
2667
|
+
rule(
|
|
2668
|
+
"jwt",
|
|
2669
|
+
/\b(ey[A-Za-z0-9]{17,}\.ey[A-Za-z0-9/\\_-]{17,}\.(?:[A-Za-z0-9/\\_-]{10,}={0,2})?)/g,
|
|
2670
|
+
1
|
|
2671
|
+
),
|
|
2672
|
+
// The password of a URL with credentials (database and broker connection strings, basic-auth URLs).
|
|
2673
|
+
rule(
|
|
2674
|
+
"url-credentials",
|
|
2675
|
+
/\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|rediss|amqps?|https?|ftp):\/\/[^:\s/@]{1,100}:([^@\s/]{3,200})@/gi,
|
|
2676
|
+
1
|
|
2677
|
+
),
|
|
2678
|
+
// `.env` lines and shell assignments without quotes (`export STRIPE_SECRET=…`, `API_TOKEN=… pnpm dev`): an upper-case
|
|
2679
|
+
// name ending in a secret word. Placeholders, numbers and plain words are skipped in `secret-spans.ts`.
|
|
2680
|
+
rule(
|
|
2681
|
+
"env-assignment",
|
|
2682
|
+
/(?<![A-Za-z0-9_])[A-Z][A-Z0-9_]*(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD|PWD|PASS|CREDENTIALS?|DSN|AUTH)\s*=\s*(?!["'`])([^\s"'`;&|]{6,300})/g,
|
|
2683
|
+
1
|
|
2684
|
+
),
|
|
2685
|
+
// Secrets passed as command-line flags (`--password=…`, `--token …`, `-p…` is too ambiguous and not matched).
|
|
2686
|
+
rule(
|
|
2687
|
+
"cli-secret-flag",
|
|
2688
|
+
/(?<![A-Za-z0-9_-])--(?:password|passwd|token|api-key|apikey|secret|client-secret|auth-token|access-token)(?:=|\s+)(?!["'`-])([^\s"'`;&|]{6,300})/gi,
|
|
2689
|
+
1
|
|
2690
|
+
),
|
|
2691
|
+
// A secret named in prose or a header without quotes ("the salt is …", "Authorization: Bearer …"): a token of 16+
|
|
2692
|
+
// characters with letters and digits that is not made of words (checked in `secret-spans.ts`).
|
|
2693
|
+
rule(
|
|
2694
|
+
"secret-in-prose",
|
|
2695
|
+
/\b(?:api[_ -]?key|secret|token|password|passwd|passphrase|salt|credentials?|bearer)\b(?:\s+(?:is|was|of|for|here|now|value|=|:))*\s*[:=]?\s+([A-Za-z0-9+/_.=-]{16,300})/gi,
|
|
2696
|
+
1
|
|
2697
|
+
),
|
|
2698
|
+
// gitleaks' generic-api-key: a value assigned to a secret-sounding name. Placeholders are skipped in `secret-spans.ts`.
|
|
2699
|
+
rule(
|
|
2700
|
+
"generic-api-key",
|
|
2701
|
+
/(?:api[_-]?key|apikey|secret|token|passw(?:or)?d|pwd|client[_-]?secret|access[_-]?key|auth[_-]?key|private[_-]?key)["']?\s*(?::|=|:=|=>)\s*["'`]([^"'`\s]{8,200})["'`]/gi,
|
|
2702
|
+
1
|
|
2703
|
+
)
|
|
2704
|
+
];
|
|
2705
|
+
|
|
2706
|
+
// ../../packages/redact/src/spans.ts
|
|
2707
|
+
function acceptSpans(accepted, candidates) {
|
|
2708
|
+
const added = [];
|
|
2709
|
+
for (const span of candidates) {
|
|
2710
|
+
if (span.end <= span.start) continue;
|
|
2711
|
+
if (accepted.some((other) => span.start < other.end && other.start < span.end)) continue;
|
|
2712
|
+
accepted.push(span);
|
|
2713
|
+
added.push(span);
|
|
2714
|
+
}
|
|
2715
|
+
return added;
|
|
2716
|
+
}
|
|
2717
|
+
function regexSpans(text, pattern, type, group = 0) {
|
|
2718
|
+
const flags = new Set(pattern.flags);
|
|
2719
|
+
flags.add("g");
|
|
2720
|
+
flags.add("d");
|
|
2721
|
+
const global = new RegExp(pattern.source, [...flags].join(""));
|
|
2722
|
+
const spans = [];
|
|
2723
|
+
for (const match of text.matchAll(global)) {
|
|
2724
|
+
const range = match.indices?.[group];
|
|
2725
|
+
if (range === void 0) continue;
|
|
2726
|
+
spans.push({ start: range[0], end: range[1], type });
|
|
2727
|
+
}
|
|
2728
|
+
return spans;
|
|
2729
|
+
}
|
|
2730
|
+
|
|
2731
|
+
// ../../packages/redact/src/secret-spans.ts
|
|
2732
|
+
var MARKER_PREFIX = "\xABREDACTED:";
|
|
2733
|
+
var PLACEHOLDER = /^(?:x{3,}|\*{3,}|\.{3,}|changeme|change_me|example|placeholder|password|secret|token|test|dummy|redacted|null|undefined|none|todo|true|false|your[_-].*|<.*>|\$\{.*\}|\$\(.*|\$[A-Za-z_]\w*|\{\{.*\}\}|%.*%|process\.env.*|env\..*)$/i;
|
|
2734
|
+
var ASSIGNMENT_RULES = /* @__PURE__ */ new Set([
|
|
2735
|
+
"generic-api-key",
|
|
2736
|
+
"url-credentials",
|
|
2737
|
+
"env-assignment",
|
|
2738
|
+
"cli-secret-flag",
|
|
2739
|
+
"secret-in-prose"
|
|
2740
|
+
]);
|
|
2741
|
+
function isPlaceholder(rule2, value) {
|
|
2742
|
+
if (value.includes(MARKER_PREFIX)) return true;
|
|
2743
|
+
if (!ASSIGNMENT_RULES.has(rule2.id)) return false;
|
|
2744
|
+
if (PLACEHOLDER.test(value)) return true;
|
|
2745
|
+
if (rule2.id === "url-credentials") return false;
|
|
2746
|
+
if (rule2.id === "secret-in-prose") {
|
|
2747
|
+
return !/[0-9]/.test(value) || !/[A-Za-z]/.test(value) || wordiness(value) >= MAX_WORDINESS;
|
|
2748
|
+
}
|
|
2749
|
+
if (/^\d+$/.test(value)) return true;
|
|
2750
|
+
return !/[0-9]/.test(value) && !/[^A-Za-z]/.test(value);
|
|
2751
|
+
}
|
|
2752
|
+
function ruleSpans(text, rule2) {
|
|
2753
|
+
const flags = rule2.pattern.flags.includes("d") ? rule2.pattern.flags : `${rule2.pattern.flags}d`;
|
|
2754
|
+
const pattern = new RegExp(rule2.pattern.source, flags);
|
|
2755
|
+
const spans = [];
|
|
2756
|
+
for (const match of text.matchAll(pattern)) {
|
|
2757
|
+
const group = rule2.group ?? 0;
|
|
2758
|
+
const value = match[group];
|
|
2759
|
+
const range = match.indices?.[group];
|
|
2760
|
+
if (value === void 0 || range === void 0) continue;
|
|
2761
|
+
if (isPlaceholder(rule2, value)) continue;
|
|
2762
|
+
spans.push({ start: range[0], end: range[1], type: rule2.id });
|
|
2763
|
+
}
|
|
2764
|
+
return spans;
|
|
2765
|
+
}
|
|
2766
|
+
var ENTROPY_TOKEN = /[A-Za-z0-9+/=_-]{21,}/g;
|
|
2767
|
+
function findSecrets(text) {
|
|
2768
|
+
const accepted = [];
|
|
2769
|
+
for (const rule2 of SECRET_RULES) acceptSpans(accepted, ruleSpans(text, rule2));
|
|
2770
|
+
const entropy = [];
|
|
2771
|
+
for (const match of text.matchAll(ENTROPY_TOKEN)) {
|
|
2772
|
+
if (!looksRandom(match[0])) continue;
|
|
2773
|
+
entropy.push({ start: match.index, end: match.index + match[0].length, type: "high-entropy" });
|
|
2774
|
+
}
|
|
2775
|
+
acceptSpans(accepted, entropy);
|
|
2776
|
+
return accepted.sort((a, b) => a.start - b.start);
|
|
2777
|
+
}
|
|
2778
|
+
|
|
2779
|
+
// ../../packages/redact/src/transcript.ts
|
|
2780
|
+
import { z as z10 } from "zod";
|
|
2781
|
+
|
|
2782
|
+
// ../../packages/redact/src/personal.ts
|
|
2783
|
+
import { findPhoneNumbersInText } from "libphonenumber-js/max";
|
|
2784
|
+
var EMAIL = /(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]{1,64}@(?:[A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,24}(?![A-Za-z0-9-])/g;
|
|
2785
|
+
function emailSpans(text) {
|
|
2786
|
+
return regexSpans(text, EMAIL, "email");
|
|
2787
|
+
}
|
|
2788
|
+
function phoneSpans(text) {
|
|
2789
|
+
const spans = [];
|
|
2790
|
+
for (const found of findPhoneNumbersInText(text, { defaultCountry: "US" })) {
|
|
2791
|
+
const raw = text.slice(found.startsAt, found.endsAt);
|
|
2792
|
+
if (!raw.startsWith("+") && !/[\s().-]/.test(raw)) continue;
|
|
2793
|
+
if (/\//.test(raw) || /^\d{4}-\d{2}-\d{2}/.test(raw) || /^\d+\.\d+$/.test(raw)) continue;
|
|
2794
|
+
const before = text[found.startsAt - 1] ?? "";
|
|
2795
|
+
const after = text[found.endsAt] ?? "";
|
|
2796
|
+
if (/[\d:./-]/.test(before) || /[\d:/]/.test(after)) continue;
|
|
2797
|
+
spans.push({ start: found.startsAt, end: found.endsAt, type: "phone" });
|
|
2798
|
+
}
|
|
2799
|
+
return spans;
|
|
2800
|
+
}
|
|
2801
|
+
var OCTET = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
|
|
2802
|
+
var IPV4 = new RegExp(`(?<![\\d.])${OCTET}(?:\\.${OCTET}){3}(?![\\d.]|\\.\\d)`, "g");
|
|
2803
|
+
var IPV6 = /(?<![\w:.])(?:[0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}(?![\w:.])/g;
|
|
2804
|
+
function harmlessIp(ip) {
|
|
2805
|
+
return ip.startsWith("127.") || ip === "0.0.0.0" || ip === "::" || ip === "::1";
|
|
2806
|
+
}
|
|
2807
|
+
function ipSpans(text) {
|
|
2808
|
+
const v4 = regexSpans(text, IPV4, "ip").filter(
|
|
2809
|
+
(span) => !harmlessIp(text.slice(span.start, span.end))
|
|
2810
|
+
);
|
|
2811
|
+
const v6 = regexSpans(text, IPV6, "ip").filter((span) => {
|
|
2812
|
+
const ip = text.slice(span.start, span.end);
|
|
2813
|
+
if (harmlessIp(ip)) return false;
|
|
2814
|
+
const groups = ip.split(":");
|
|
2815
|
+
return (ip.includes("::") || groups.length === 8) && /[0-9a-fA-F]{2}/.test(ip);
|
|
2816
|
+
});
|
|
2817
|
+
return [...v4, ...v6];
|
|
2818
|
+
}
|
|
2819
|
+
var STREET_SUFFIX = "(?:Street|St|Avenue|Ave|Road|Rd|Boulevard|Blvd|Lane|Ln|Drive|Dr|Court|Ct|Way|Place|Pl|Terrace|Ter|Parkway|Pkwy|Highway|Hwy|Circle|Cir|Square|Sq|Trail|Trl)";
|
|
2820
|
+
var STREET = new RegExp(
|
|
2821
|
+
`\\b\\d{1,6}[A-Za-z]?\\s+(?:[NSEW]\\.?\\s+)?(?:[A-Z][a-z]+\\.?\\s+){1,4}${STREET_SUFFIX}\\b\\.?(?:,?\\s*(?:Apt|Apartment|Suite|Ste|Unit|#)\\.?\\s*[A-Za-z0-9-]{1,8})?`,
|
|
2822
|
+
"g"
|
|
2823
|
+
);
|
|
2824
|
+
var PO_BOX = /\bP\.?\s?O\.?\s+Box\s+\d{1,8}\b/gi;
|
|
2825
|
+
function addressSpans(text) {
|
|
2826
|
+
return [...regexSpans(text, STREET, "address"), ...regexSpans(text, PO_BOX, "address")];
|
|
2827
|
+
}
|
|
2828
|
+
var URL_PATTERN = /\bhttps?:\/\/[^\s"'<>`)\]]+/g;
|
|
2829
|
+
var TOKEN_PARAM = /[?&#](?:access_?token|refresh_?token|id_?token|token|auth|key|api_?key|apikey|sig|signature|secret|client_secret|password|pass|code|session|sessionid|sid|jwt|x-amz-signature|x-amz-credential|x-amz-security-token|x-goog-signature|sv|se)=([^&#\s]{4,})/gi;
|
|
2830
|
+
function urlTokenSpans(text) {
|
|
2831
|
+
const spans = [];
|
|
2832
|
+
for (const url of text.matchAll(URL_PATTERN)) {
|
|
2833
|
+
for (const param of url[0].matchAll(new RegExp(TOKEN_PARAM.source, "gid"))) {
|
|
2834
|
+
const range = param.indices?.[1];
|
|
2835
|
+
if (range === void 0) continue;
|
|
2836
|
+
spans.push({ start: url.index + range[0], end: url.index + range[1], type: "url-token" });
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
return spans;
|
|
2840
|
+
}
|
|
2841
|
+
var HOME = /(?:(?<![\w/])\/(?:home|Users)\/[^/\s"'`:]+|\b[A-Za-z]:\\Users\\[^\\\s"'`:]+)/g;
|
|
2842
|
+
function homeSpans(text) {
|
|
2843
|
+
return regexSpans(text, HOME, "home");
|
|
2844
|
+
}
|
|
2845
|
+
var FIRST_NAMES = new Set(
|
|
2846
|
+
"aaron abdul adam adrian ahmed aisha alan alex alexander alexandra ali alice alicia amanda amir amy ana andre andrea andrew angela anna anne anthony arjun ashley ben benjamin beth brandon brian bruce camila carla carlos carol caroline catherine charles charlie chen chris christina christine christopher claire daniel david deborah diana diego dmitri donald dylan elena elizabeth emily emma eric erin ethan eva fatima felix fernando francesca frank gabriel gary george grace hannah hao harry heather helen henry hiroshi hugo ian isabel jack jacob james jamie jane jason javier jennifer jessica jin john jonathan jordan jose joseph joshua juan julia julie justin karen kate katherine kathryn kevin kim laura lauren lei li liam linda lisa lucas lucy luis maria mark martin mary matthew maya megan mei melissa michael michelle mike mohammed nancy natalie nathan nicholas nicole nina noah olga olivia omar oscar pablo patricia patrick paul peter priya rachel rahul raj rebecca richard robert ryan sam samantha samuel sandra sara sarah scott sean sergei sofia sophia stephanie steve steven susan thomas tim timothy tom tyler victor victoria vikram wei william yuki yusuf zoe".split(" ")
|
|
2847
|
+
);
|
|
2848
|
+
var NOT_PEOPLE = new Set(
|
|
2849
|
+
"claude codex chatgpt gpt gemini copilot cursor aider sonnet opus haiku fable anthropic openai github gitlab google apple microsoft amazon vercel neon docker node react next vue svelte python rust go java swift kotlin typescript javascript linux windows mac macos ios android chrome firefox safari slack discord notion jira monday tuesday wednesday thursday friday saturday sunday january february march april may june july august september october november december team all everyone there folks guys world again me him her them you it this that the a an and or but if then".split(" ")
|
|
2850
|
+
);
|
|
2851
|
+
var CAP = "[A-Z][a-z]+(?:[-'][A-Z][a-z]+)?";
|
|
2852
|
+
var NAME_PAIR = new RegExp(`\\b(${CAP})\\s+(${CAP})\\b`, "g");
|
|
2853
|
+
var cueAlternation = (words) => words.map((word) => word.replace(/^[a-z]/, (letter) => `[${letter}${letter.toUpperCase()}]`)).join("|");
|
|
2854
|
+
var STRONG_CUE = new RegExp(
|
|
2855
|
+
`\\b(?:${cueAlternation(["hi", "hey", "hello", "dear", "thanks", "thank you", "cc", "ping", "asked", "told", "emailed", "messaged", "talked to", "spoke with", "spoke to"])})[,:]?\\s+(${CAP}(?:\\s+${CAP})?)\\b`,
|
|
2856
|
+
"g"
|
|
2857
|
+
);
|
|
2858
|
+
var WEAK_CUE = new RegExp(
|
|
2859
|
+
`\\b(?:${cueAlternation(["ask", "tell", "email", "message", "call", "called", "met", "meet", "according to", "per", "from", "with", "and"])})\\s+(${CAP}(?:\\s+${CAP})?)\\b`,
|
|
2860
|
+
"g"
|
|
2861
|
+
);
|
|
2862
|
+
var HONORIFIC = new RegExp(`\\b(?:Mr|Mrs|Ms|Mx|Dr|Prof)\\.?\\s+(${CAP}(?:\\s+${CAP})?)\\b`, "g");
|
|
2863
|
+
var TRAILER = new RegExp(
|
|
2864
|
+
`\\b(?:Author|[Cc]o-[Aa]uthored-[Bb]y|Signed-off-by|Reviewed-by|Reported-by|Acked-by|Tested-by)\\s*:\\s*(${CAP}(?:\\s+${CAP}){0,2})`,
|
|
2865
|
+
"g"
|
|
2866
|
+
);
|
|
2867
|
+
var SPEAKER = new RegExp(
|
|
2868
|
+
`\\b(${CAP})\\s+(?:said|says|wants|wanted|asked|thinks|thought|mentioned|wrote|suggested|replied|approved|reviewed)\\b`,
|
|
2869
|
+
"g"
|
|
2870
|
+
);
|
|
2871
|
+
function notPerson(name) {
|
|
2872
|
+
return name.split(/\s+/).some((word) => NOT_PEOPLE.has(word.toLowerCase()));
|
|
2873
|
+
}
|
|
2874
|
+
function personSpans(text) {
|
|
2875
|
+
const spans = [];
|
|
2876
|
+
const add = (start, value) => {
|
|
2877
|
+
if (notPerson(value)) return;
|
|
2878
|
+
spans.push({ start, end: start + value.length, type: "person" });
|
|
2879
|
+
};
|
|
2880
|
+
for (const match of text.matchAll(new RegExp(NAME_PAIR.source, "gd"))) {
|
|
2881
|
+
const first = match[1];
|
|
2882
|
+
const range = match.indices?.[0];
|
|
2883
|
+
if (first === void 0 || range === void 0 || !FIRST_NAMES.has(first.toLowerCase()))
|
|
2884
|
+
continue;
|
|
2885
|
+
add(range[0], match[0]);
|
|
2886
|
+
}
|
|
2887
|
+
for (const pattern of [STRONG_CUE, WEAK_CUE, HONORIFIC, TRAILER]) {
|
|
2888
|
+
for (const match of text.matchAll(new RegExp(pattern.source, "gd"))) {
|
|
2889
|
+
const value = match[1];
|
|
2890
|
+
const range = match.indices?.[1];
|
|
2891
|
+
if (value === void 0 || range === void 0) continue;
|
|
2892
|
+
if (pattern === WEAK_CUE && !FIRST_NAMES.has((value.split(/\s+/)[0] ?? "").toLowerCase()))
|
|
2893
|
+
continue;
|
|
2894
|
+
add(range[0], value);
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
for (const match of text.matchAll(new RegExp(SPEAKER.source, "gd"))) {
|
|
2898
|
+
const name = match[1];
|
|
2899
|
+
const range = match.indices?.[1];
|
|
2900
|
+
if (name === void 0 || range === void 0 || !FIRST_NAMES.has(name.toLowerCase())) continue;
|
|
2901
|
+
add(range[0], name);
|
|
2902
|
+
}
|
|
2903
|
+
return spans;
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
// ../../packages/redact/src/transcript.ts
|
|
2907
|
+
var BLOCKLIST_KINDS = ["company", "client", "host", "codename", "person"];
|
|
2908
|
+
var BLOCKLIST_TERM_MAX = 100;
|
|
2909
|
+
var blocklistEntrySchema = z10.object({
|
|
2910
|
+
term: z10.string().trim().min(2, "Blocklist terms are at least 2 characters.").max(BLOCKLIST_TERM_MAX).refine((term) => !/[\n\r\t«»]/.test(term), "One line, without \xAB or \xBB."),
|
|
2911
|
+
kind: z10.enum(BLOCKLIST_KINDS)
|
|
2912
|
+
}).strict();
|
|
2913
|
+
var NUMBERED = {
|
|
2914
|
+
email: "EMAIL",
|
|
2915
|
+
phone: "PHONE",
|
|
2916
|
+
ip: "IP",
|
|
2917
|
+
address: "ADDRESS",
|
|
2918
|
+
person: "PERSON",
|
|
2919
|
+
company: "COMPANY",
|
|
2920
|
+
client: "CLIENT",
|
|
2921
|
+
host: "HOST",
|
|
2922
|
+
codename: "CODENAME"
|
|
2923
|
+
};
|
|
2924
|
+
var PERSONAL_TYPES = /* @__PURE__ */ new Set(["email", "phone", "ip", "address", "person"]);
|
|
2925
|
+
var BLOCKLIST_TYPES = new Set(BLOCKLIST_KINDS);
|
|
2926
|
+
function escapeRegex(text) {
|
|
2927
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2928
|
+
}
|
|
2929
|
+
var TranscriptRedactor = class {
|
|
2930
|
+
numbers = /* @__PURE__ */ new Map();
|
|
2931
|
+
blocklist;
|
|
2932
|
+
constructor(blocklist = []) {
|
|
2933
|
+
this.blocklist = [...blocklist].map((entry) => blocklistEntrySchema.parse(entry)).sort((a, b) => b.term.length - a.term.length).map((entry) => ({
|
|
2934
|
+
kind: entry.kind,
|
|
2935
|
+
pattern: new RegExp(
|
|
2936
|
+
`(?<![A-Za-z0-9])${escapeRegex(entry.term).replace(/\s+/g, "\\s+")}(?![A-Za-z0-9])`,
|
|
2937
|
+
"gi"
|
|
2938
|
+
)
|
|
2939
|
+
}));
|
|
2940
|
+
}
|
|
2941
|
+
/** The spans to remove from `text`, non-overlapping and in order. */
|
|
2942
|
+
spans(text) {
|
|
2943
|
+
const accepted = [];
|
|
2944
|
+
acceptSpans(accepted, findSecrets(text));
|
|
2945
|
+
acceptSpans(accepted, urlTokenSpans(text));
|
|
2946
|
+
acceptSpans(accepted, emailSpans(text));
|
|
2947
|
+
for (const entry of this.blocklist) {
|
|
2948
|
+
const found = [];
|
|
2949
|
+
for (const match of text.matchAll(entry.pattern)) {
|
|
2950
|
+
found.push({ start: match.index, end: match.index + match[0].length, type: entry.kind });
|
|
2951
|
+
}
|
|
2952
|
+
acceptSpans(accepted, found);
|
|
2953
|
+
}
|
|
2954
|
+
acceptSpans(accepted, ipSpans(text));
|
|
2955
|
+
acceptSpans(accepted, phoneSpans(text));
|
|
2956
|
+
acceptSpans(accepted, addressSpans(text));
|
|
2957
|
+
acceptSpans(accepted, personSpans(text));
|
|
2958
|
+
acceptSpans(accepted, homeSpans(text));
|
|
2959
|
+
return accepted.sort((a, b) => a.start - b.start);
|
|
2960
|
+
}
|
|
2961
|
+
redact(text) {
|
|
2962
|
+
const segments = [];
|
|
2963
|
+
const counts = {};
|
|
2964
|
+
let at = 0;
|
|
2965
|
+
for (const span of this.spans(text)) {
|
|
2966
|
+
if (span.start > at) segments.push({ kept: text.slice(at, span.start) });
|
|
2967
|
+
const removed = text.slice(span.start, span.end);
|
|
2968
|
+
segments.push({
|
|
2969
|
+
removed,
|
|
2970
|
+
placeholder: this.placeholder(span.type, removed),
|
|
2971
|
+
type: span.type
|
|
2972
|
+
});
|
|
2973
|
+
counts[span.type] = (counts[span.type] ?? 0) + 1;
|
|
2974
|
+
at = span.end;
|
|
2975
|
+
}
|
|
2976
|
+
if (at < text.length) segments.push({ kept: text.slice(at) });
|
|
2977
|
+
const out = segments.map((segment) => "kept" in segment ? segment.kept : segment.placeholder);
|
|
2978
|
+
return { text: out.join(""), segments, counts };
|
|
2979
|
+
}
|
|
2980
|
+
placeholder(type, value) {
|
|
2981
|
+
if (type === "home") return "~";
|
|
2982
|
+
const label = NUMBERED[type];
|
|
2983
|
+
if (label === void 0) return `\xABREDACTED:${type}\xBB`;
|
|
2984
|
+
const key = type === "phone" ? value.replace(/[^\d+]/g, "") : value.toLowerCase().replace(/\s+/g, " ");
|
|
2985
|
+
let byValue = this.numbers.get(type);
|
|
2986
|
+
if (byValue === void 0) {
|
|
2987
|
+
byValue = /* @__PURE__ */ new Map();
|
|
2988
|
+
this.numbers.set(type, byValue);
|
|
2989
|
+
}
|
|
2990
|
+
let n = byValue.get(key);
|
|
2991
|
+
if (n === void 0) {
|
|
2992
|
+
n = byValue.size + 1;
|
|
2993
|
+
byValue.set(key, n);
|
|
2994
|
+
}
|
|
2995
|
+
return `\xAB${label}_${String(n)}\xBB`;
|
|
2996
|
+
}
|
|
2997
|
+
};
|
|
2998
|
+
function redactionGroup(type) {
|
|
2999
|
+
if (type === "home") return "path";
|
|
3000
|
+
if (PERSONAL_TYPES.has(type)) return "personal";
|
|
3001
|
+
if (BLOCKLIST_TYPES.has(type)) return "blocklist";
|
|
3002
|
+
return "secret";
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
// src/review-server.ts
|
|
3006
|
+
import { z as z13 } from "zod";
|
|
3007
|
+
|
|
3008
|
+
// src/approved.ts
|
|
3009
|
+
import { createHash } from "crypto";
|
|
3010
|
+
import { readFile as readFile4, rm } from "fs/promises";
|
|
3011
|
+
import { join as join8 } from "path";
|
|
3012
|
+
import { z as z11 } from "zod";
|
|
3013
|
+
var approvedSchema = z11.object({
|
|
3014
|
+
version: z11.literal(1),
|
|
3015
|
+
approvedAt: z11.iso.datetime(),
|
|
3016
|
+
sha256: sha256HexSchema,
|
|
3017
|
+
sizeBytes: z11.number().int().positive(),
|
|
3018
|
+
cliVersion: z11.string().min(1),
|
|
3019
|
+
tools: z11.array(aiWorkflowToolSchema).min(1),
|
|
3020
|
+
dateRange: z11.object({
|
|
3021
|
+
start: z11.iso.datetime({ offset: true }),
|
|
3022
|
+
end: z11.iso.datetime({ offset: true })
|
|
3023
|
+
}),
|
|
3024
|
+
sessionCount: z11.number().int().positive(),
|
|
3025
|
+
redaction: z11.object({
|
|
3026
|
+
secrets: z11.number(),
|
|
3027
|
+
personal: z11.number(),
|
|
3028
|
+
blocklist: z11.number(),
|
|
3029
|
+
paths: z11.number()
|
|
3030
|
+
})
|
|
3031
|
+
}).strict();
|
|
3032
|
+
var uploadStateSchema = z11.object({
|
|
3033
|
+
version: z11.literal(1),
|
|
3034
|
+
origin: z11.string(),
|
|
3035
|
+
sha256: sha256HexSchema,
|
|
3036
|
+
uploadId: z11.uuid(),
|
|
3037
|
+
parts: z11.array(z11.object({ partNumber: z11.number().int().min(1), etag: z11.string() }).strict())
|
|
3038
|
+
}).strict();
|
|
3039
|
+
var folder = (dir) => join8(dir, "upload");
|
|
3040
|
+
var bundlePath = (dir) => join8(folder(dir), "bundle.jsonl.gz");
|
|
3041
|
+
var metaPath = (dir) => join8(folder(dir), "bundle.json");
|
|
3042
|
+
var statePath = (dir) => join8(folder(dir), "upload-state.json");
|
|
3043
|
+
async function readJson(path, schema) {
|
|
3044
|
+
const text = await readOptionalFile(path);
|
|
3045
|
+
if (text === null) return null;
|
|
3046
|
+
try {
|
|
3047
|
+
const parsed = schema.safeParse(JSON.parse(text));
|
|
3048
|
+
return parsed.success ? parsed.data : null;
|
|
3049
|
+
} catch {
|
|
3050
|
+
return null;
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
async function saveApproved(dir, built, now = /* @__PURE__ */ new Date()) {
|
|
3054
|
+
const meta = {
|
|
3055
|
+
version: 1,
|
|
3056
|
+
approvedAt: now.toISOString(),
|
|
3057
|
+
sha256: built.sha256,
|
|
3058
|
+
sizeBytes: built.bytes.length,
|
|
3059
|
+
cliVersion: built.header.cliVersion,
|
|
3060
|
+
tools: built.tools,
|
|
3061
|
+
dateRange: built.header.dateRange,
|
|
3062
|
+
sessionCount: built.header.counts.sessions,
|
|
3063
|
+
redaction: {
|
|
3064
|
+
secrets: built.header.redaction.secrets,
|
|
3065
|
+
personal: built.header.redaction.personal,
|
|
3066
|
+
blocklist: built.header.redaction.blocklist,
|
|
3067
|
+
paths: built.header.redaction.paths
|
|
3068
|
+
}
|
|
3069
|
+
};
|
|
3070
|
+
await rm(statePath(dir), { force: true });
|
|
3071
|
+
await writePrivateFile(bundlePath(dir), built.bytes);
|
|
3072
|
+
await writePrivateFile(metaPath(dir), `${JSON.stringify(meta, null, 2)}
|
|
3073
|
+
`);
|
|
3074
|
+
return meta;
|
|
3075
|
+
}
|
|
3076
|
+
async function loadApproved(dir) {
|
|
3077
|
+
const meta = await readJson(metaPath(dir), approvedSchema);
|
|
3078
|
+
if (meta === null) return null;
|
|
3079
|
+
let bytes;
|
|
3080
|
+
try {
|
|
3081
|
+
bytes = await readFile4(bundlePath(dir));
|
|
3082
|
+
} catch {
|
|
3083
|
+
return null;
|
|
3084
|
+
}
|
|
3085
|
+
if (createHash("sha256").update(bytes).digest("hex") !== meta.sha256) return null;
|
|
3086
|
+
return { meta, bytes };
|
|
3087
|
+
}
|
|
3088
|
+
async function loadUploadState(dir) {
|
|
3089
|
+
return readJson(statePath(dir), uploadStateSchema);
|
|
3090
|
+
}
|
|
3091
|
+
async function saveUploadState(dir, state) {
|
|
3092
|
+
await writePrivateFile(statePath(dir), `${JSON.stringify(uploadStateSchema.parse(state))}
|
|
3093
|
+
`);
|
|
3094
|
+
}
|
|
3095
|
+
async function removeApproved(dir) {
|
|
3096
|
+
await rm(folder(dir), { recursive: true, force: true });
|
|
3097
|
+
}
|
|
3098
|
+
|
|
3099
|
+
// src/bundle.ts
|
|
3100
|
+
import { createHash as createHash2 } from "crypto";
|
|
3101
|
+
import { gzipSync } from "zlib";
|
|
3102
|
+
|
|
3103
|
+
// src/redaction.ts
|
|
3104
|
+
var TOOL_OUTPUT_KEEP_LINES = 3;
|
|
3105
|
+
function addCounts(into, from) {
|
|
3106
|
+
for (const [type, n] of Object.entries(from)) into[type] = (into[type] ?? 0) + n;
|
|
3107
|
+
return into;
|
|
3108
|
+
}
|
|
3109
|
+
function groupCounts(counts) {
|
|
3110
|
+
const totals = { secrets: 0, personal: 0, blocklist: 0, paths: 0 };
|
|
3111
|
+
for (const [type, n] of Object.entries(counts)) {
|
|
3112
|
+
const group = redactionGroup(type);
|
|
3113
|
+
if (group === "secret") totals.secrets += n;
|
|
3114
|
+
else if (group === "personal") totals.personal += n;
|
|
3115
|
+
else if (group === "blocklist") totals.blocklist += n;
|
|
3116
|
+
else totals.paths += n;
|
|
3117
|
+
}
|
|
3118
|
+
return totals;
|
|
3119
|
+
}
|
|
3120
|
+
function capText(text, max) {
|
|
3121
|
+
if (text.length <= max) return text;
|
|
3122
|
+
let cut = text.slice(0, max);
|
|
3123
|
+
const open = cut.lastIndexOf("\xAB");
|
|
3124
|
+
if (open > cut.lastIndexOf("\xBB")) cut = cut.slice(0, open);
|
|
3125
|
+
return `${cut}[\u2026 ${(text.length - cut.length).toLocaleString("en-US")} more characters]`;
|
|
3126
|
+
}
|
|
3127
|
+
var Redacting = class {
|
|
3128
|
+
counts = {};
|
|
3129
|
+
redactor;
|
|
3130
|
+
constructor(blocklist) {
|
|
3131
|
+
this.redactor = new TranscriptRedactor(blocklist);
|
|
3132
|
+
}
|
|
3133
|
+
/** Redacts one text, adding to this item's counts; `diff` is null when nothing was removed. */
|
|
3134
|
+
text(value, max, counts = {}) {
|
|
3135
|
+
const out = this.redactor.redact(value);
|
|
3136
|
+
addCounts(counts, out.counts);
|
|
3137
|
+
addCounts(this.counts, out.counts);
|
|
3138
|
+
const removed = out.segments.some((segment) => !("kept" in segment));
|
|
3139
|
+
return { text: capText(out.text, max), diff: removed ? out.segments : null };
|
|
3140
|
+
}
|
|
3141
|
+
};
|
|
3142
|
+
function outputLabel(lines, exitCode) {
|
|
3143
|
+
const exit = exitCode === void 0 ? "" : `, exit ${String(exitCode)}`;
|
|
3144
|
+
return `[tool output: ${lines.toLocaleString("en-US")} ${lines === 1 ? "line" : "lines"}${exit}]`;
|
|
3145
|
+
}
|
|
3146
|
+
function keptModel(model, r, counts) {
|
|
3147
|
+
const out = r.text(model, 100, counts);
|
|
3148
|
+
return out.diff === null && out.text === model ? model : null;
|
|
3149
|
+
}
|
|
3150
|
+
function redactEvent(event, r) {
|
|
3151
|
+
const counts = {};
|
|
3152
|
+
const at = event.at === void 0 ? {} : { at: event.at };
|
|
3153
|
+
switch (event.kind) {
|
|
3154
|
+
case "user_prompt":
|
|
3155
|
+
case "assistant_text": {
|
|
3156
|
+
const out = r.text(event.text, EVENT_TEXT_MAX, counts);
|
|
3157
|
+
return {
|
|
3158
|
+
event: { kind: event.kind, text: out.text, ...at },
|
|
3159
|
+
diff: out.diff,
|
|
3160
|
+
counts,
|
|
3161
|
+
collapsed: false
|
|
3162
|
+
};
|
|
3163
|
+
}
|
|
3164
|
+
case "tool_call": {
|
|
3165
|
+
const name = r.text(event.name, 200, counts);
|
|
3166
|
+
const args = r.text(event.argsSummary, 400, counts);
|
|
3167
|
+
const model = event.model === void 0 ? null : keptModel(event.model, r, counts);
|
|
3168
|
+
return {
|
|
3169
|
+
event: {
|
|
3170
|
+
kind: "tool_call",
|
|
3171
|
+
name: name.text,
|
|
3172
|
+
argsSummary: args.text,
|
|
3173
|
+
...model === null ? {} : { model },
|
|
3174
|
+
...at
|
|
3175
|
+
},
|
|
3176
|
+
diff: args.diff ?? name.diff,
|
|
3177
|
+
counts,
|
|
3178
|
+
collapsed: false
|
|
3179
|
+
};
|
|
3180
|
+
}
|
|
3181
|
+
case "tool_result": {
|
|
3182
|
+
const exit = event.exitCode === void 0 ? {} : { exitCode: event.exitCode };
|
|
3183
|
+
if (event.lines > TOOL_OUTPUT_KEEP_LINES) {
|
|
3184
|
+
return {
|
|
3185
|
+
event: {
|
|
3186
|
+
kind: "tool_result",
|
|
3187
|
+
summary: outputLabel(event.lines, event.exitCode),
|
|
3188
|
+
lines: event.lines,
|
|
3189
|
+
...exit,
|
|
3190
|
+
...at
|
|
3191
|
+
},
|
|
3192
|
+
diff: null,
|
|
3193
|
+
counts,
|
|
3194
|
+
collapsed: true
|
|
3195
|
+
};
|
|
3196
|
+
}
|
|
3197
|
+
const out = r.text(event.summary, 400, counts);
|
|
3198
|
+
return {
|
|
3199
|
+
event: { kind: "tool_result", summary: out.text, lines: event.lines, ...exit, ...at },
|
|
3200
|
+
diff: out.diff,
|
|
3201
|
+
counts,
|
|
3202
|
+
collapsed: false
|
|
3203
|
+
};
|
|
3204
|
+
}
|
|
3205
|
+
case "file_edit": {
|
|
3206
|
+
const out = r.text(event.path, 1100, counts);
|
|
3207
|
+
return {
|
|
3208
|
+
event: { kind: "file_edit", path: out.text, linesChanged: event.linesChanged, ...at },
|
|
3209
|
+
diff: out.diff,
|
|
3210
|
+
counts,
|
|
3211
|
+
collapsed: false
|
|
3212
|
+
};
|
|
3213
|
+
}
|
|
3214
|
+
case "model_turn": {
|
|
3215
|
+
const model = event.model === null ? null : keptModel(event.model, r, counts);
|
|
3216
|
+
return { event: { ...event, model }, diff: null, counts, collapsed: false };
|
|
3217
|
+
}
|
|
3218
|
+
case "compaction":
|
|
3219
|
+
return { event: { ...event }, diff: null, counts, collapsed: false };
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
var sessionKey = (tool, id) => `session:${tool}:${id}`;
|
|
3223
|
+
function redactSession(session, blocklist) {
|
|
3224
|
+
const r = new Redacting(blocklist);
|
|
3225
|
+
const projectCounts = {};
|
|
3226
|
+
const project = r.text(session.project, 1100, projectCounts).text;
|
|
3227
|
+
return {
|
|
3228
|
+
kind: "session",
|
|
3229
|
+
key: sessionKey(session.tool, session.id),
|
|
3230
|
+
tool: session.tool,
|
|
3231
|
+
id: session.id,
|
|
3232
|
+
project,
|
|
3233
|
+
startedAt: session.startedAt,
|
|
3234
|
+
endedAt: session.endedAt,
|
|
3235
|
+
toolVersion: session.toolVersion,
|
|
3236
|
+
events: session.events.map((event) => redactEvent(event, r)),
|
|
3237
|
+
projectCounts
|
|
3238
|
+
};
|
|
3239
|
+
}
|
|
3240
|
+
function redactInstructionFile(tool, project, file, text, blocklist) {
|
|
3241
|
+
const r = new Redacting(blocklist);
|
|
3242
|
+
const name = file.kind === "claude_md" ? file.path.slice(project.length + 1) : file.path.split(/[\\/]/).pop() ?? "";
|
|
3243
|
+
const body = r.text(text, INSTRUCTION_TEXT_MAX);
|
|
3244
|
+
return {
|
|
3245
|
+
kind: "instruction_file",
|
|
3246
|
+
key: `file:${tool}:${file.path}`,
|
|
3247
|
+
tool,
|
|
3248
|
+
project: r.text(project, 1100).text,
|
|
3249
|
+
fileKind: file.kind,
|
|
3250
|
+
name: r.text(name, 300).text,
|
|
3251
|
+
text: body.text,
|
|
3252
|
+
diff: body.diff,
|
|
3253
|
+
bytes: file.bytes,
|
|
3254
|
+
counts: r.counts
|
|
3255
|
+
};
|
|
3256
|
+
}
|
|
3257
|
+
function redactSetup(tool, project, setup, blocklist) {
|
|
3258
|
+
const r = new Redacting(blocklist);
|
|
3259
|
+
return {
|
|
3260
|
+
kind: "setup",
|
|
3261
|
+
key: `setup:${tool}:${project ?? "~"}`,
|
|
3262
|
+
tool,
|
|
3263
|
+
project: project === null ? null : r.text(project, 1100).text,
|
|
3264
|
+
skills: setup.skills.map((skill) => r.text(skill, 120).text),
|
|
3265
|
+
hooks: setup.hooks.map((hook) => ({
|
|
3266
|
+
event: r.text(hook.event, 60).text,
|
|
3267
|
+
matcher: hook.matcher === null ? null : r.text(hook.matcher, 200).text
|
|
3268
|
+
})),
|
|
3269
|
+
counts: r.counts
|
|
3270
|
+
};
|
|
3271
|
+
}
|
|
3272
|
+
function itemCounts(item, excludedEvents = /* @__PURE__ */ new Set()) {
|
|
3273
|
+
if (item.kind !== "session") return item.counts;
|
|
3274
|
+
const total = { ...item.projectCounts };
|
|
3275
|
+
item.events.forEach((event, index) => {
|
|
3276
|
+
if (!excludedEvents.has(index)) addCounts(total, event.counts);
|
|
3277
|
+
});
|
|
3278
|
+
return total;
|
|
3279
|
+
}
|
|
3280
|
+
|
|
3281
|
+
// src/bundle.ts
|
|
3282
|
+
function buildBundle(items, exclusions, cliVersion, now = /* @__PURE__ */ new Date()) {
|
|
3283
|
+
const excludedItems = new Set(exclusions.excludedItems);
|
|
3284
|
+
const records = [];
|
|
3285
|
+
const counts = {};
|
|
3286
|
+
const versions = /* @__PURE__ */ new Map();
|
|
3287
|
+
let start = null;
|
|
3288
|
+
let end = null;
|
|
3289
|
+
let events = 0;
|
|
3290
|
+
let excludedEvents = 0;
|
|
3291
|
+
let collapsedOutputs = 0;
|
|
3292
|
+
let sessions = 0;
|
|
3293
|
+
let excludedSessions = 0;
|
|
3294
|
+
let instructionFiles = 0;
|
|
3295
|
+
let setups = 0;
|
|
3296
|
+
for (const item of items) {
|
|
3297
|
+
if (excludedItems.has(item.key)) {
|
|
3298
|
+
if (item.kind === "session") excludedSessions += 1;
|
|
3299
|
+
continue;
|
|
3300
|
+
}
|
|
3301
|
+
if (item.kind === "session") {
|
|
3302
|
+
const dropped = new Set(exclusions.excludedEvents[item.key] ?? []);
|
|
3303
|
+
const kept = item.events.filter((_, index) => !dropped.has(index));
|
|
3304
|
+
excludedEvents += item.events.length - kept.length;
|
|
3305
|
+
if (kept.length === 0) {
|
|
3306
|
+
excludedSessions += 1;
|
|
3307
|
+
continue;
|
|
3308
|
+
}
|
|
3309
|
+
sessions += 1;
|
|
3310
|
+
events += kept.length;
|
|
3311
|
+
collapsedOutputs += kept.filter((event) => event.collapsed).length;
|
|
3312
|
+
addCounts(counts, itemCounts(item, dropped));
|
|
3313
|
+
const tool = versions.get(item.tool) ?? /* @__PURE__ */ new Set();
|
|
3314
|
+
if (item.toolVersion !== null) tool.add(item.toolVersion);
|
|
3315
|
+
versions.set(item.tool, tool);
|
|
3316
|
+
if (start === null || item.startedAt < start) start = item.startedAt;
|
|
3317
|
+
if (end === null || item.endedAt > end) end = item.endedAt;
|
|
3318
|
+
records.push({
|
|
3319
|
+
type: "session",
|
|
3320
|
+
tool: item.tool,
|
|
3321
|
+
id: item.id,
|
|
3322
|
+
project: item.project,
|
|
3323
|
+
startedAt: item.startedAt,
|
|
3324
|
+
endedAt: item.endedAt,
|
|
3325
|
+
toolVersion: item.toolVersion,
|
|
3326
|
+
events: kept.map((event) => event.event)
|
|
3327
|
+
});
|
|
3328
|
+
} else if (item.kind === "instruction_file") {
|
|
3329
|
+
instructionFiles += 1;
|
|
3330
|
+
addCounts(counts, item.counts);
|
|
3331
|
+
records.push({
|
|
3332
|
+
type: "instruction_file",
|
|
3333
|
+
tool: item.tool,
|
|
3334
|
+
project: item.project,
|
|
3335
|
+
kind: item.fileKind,
|
|
3336
|
+
name: item.name,
|
|
3337
|
+
text: item.text,
|
|
3338
|
+
bytes: item.bytes
|
|
3339
|
+
});
|
|
3340
|
+
} else {
|
|
3341
|
+
setups += 1;
|
|
3342
|
+
addCounts(counts, item.counts);
|
|
3343
|
+
records.push({
|
|
3344
|
+
type: "setup",
|
|
3345
|
+
tool: item.tool,
|
|
3346
|
+
project: item.project,
|
|
3347
|
+
skills: item.skills,
|
|
3348
|
+
hooks: item.hooks
|
|
3349
|
+
});
|
|
3350
|
+
}
|
|
3351
|
+
}
|
|
3352
|
+
if (sessions === 0 || start === null || end === null) {
|
|
3353
|
+
throw new CliError(
|
|
3354
|
+
"Nothing to upload: every session is excluded. Include at least one in `xtrium review`."
|
|
3355
|
+
);
|
|
3356
|
+
}
|
|
3357
|
+
if (sessions > BUNDLE_MAX_SESSIONS) {
|
|
3358
|
+
throw new CliError(
|
|
3359
|
+
`That is ${String(sessions)} sessions; at most ${String(BUNDLE_MAX_SESSIONS)} fit in one upload. Exclude some, or choose fewer projects in \`xtrium scan\`.`
|
|
3360
|
+
);
|
|
3361
|
+
}
|
|
3362
|
+
const tools = [...versions.keys()].sort();
|
|
3363
|
+
const header = bundleHeaderSchema.parse({
|
|
3364
|
+
type: "header",
|
|
3365
|
+
format: BUNDLE_FORMAT,
|
|
3366
|
+
version: BUNDLE_VERSION,
|
|
3367
|
+
cliVersion,
|
|
3368
|
+
createdAt: now.toISOString(),
|
|
3369
|
+
tools: tools.map((tool) => ({
|
|
3370
|
+
tool,
|
|
3371
|
+
versions: [...versions.get(tool) ?? []].sort().slice(0, 100)
|
|
3372
|
+
})),
|
|
3373
|
+
dateRange: { start, end },
|
|
3374
|
+
counts: {
|
|
3375
|
+
sessions,
|
|
3376
|
+
events,
|
|
3377
|
+
instructionFiles,
|
|
3378
|
+
setups,
|
|
3379
|
+
excludedSessions,
|
|
3380
|
+
excludedEvents,
|
|
3381
|
+
collapsedOutputs
|
|
3382
|
+
},
|
|
3383
|
+
redaction: { ...groupCounts(counts), byType: counts }
|
|
3384
|
+
});
|
|
3385
|
+
const lines = [
|
|
3386
|
+
JSON.stringify(header),
|
|
3387
|
+
...records.map((record) => JSON.stringify(bundleBodyRecordSchema.parse(record)))
|
|
3388
|
+
];
|
|
3389
|
+
const bytes = gzipSync(Buffer.from(`${lines.join("\n")}
|
|
3390
|
+
`, "utf8"), { level: 9 });
|
|
3391
|
+
if (bytes.length > BUNDLE_MAX_BYTES) {
|
|
3392
|
+
throw new CliError(
|
|
3393
|
+
`The bundle is ${(bytes.length / 1024 / 1024).toFixed(1)} MB compressed; the limit is ${String(BUNDLE_MAX_BYTES / 1024 / 1024)} MB. Exclude some sessions or choose fewer projects.`
|
|
3394
|
+
);
|
|
3395
|
+
}
|
|
3396
|
+
return { bytes, sha256: createHash2("sha256").update(bytes).digest("hex"), header, tools };
|
|
3397
|
+
}
|
|
3398
|
+
|
|
3399
|
+
// src/review-page.ts
|
|
3400
|
+
var STYLE = `
|
|
3401
|
+
:root { color-scheme: light dark; --bg: #f7f7f5; --panel: #ffffff; --text: #1d1d1b; --muted: #66665f; --line: #deded8;
|
|
3402
|
+
--accent: #2f5d50; --removed: #fde2e1; --removed-text: #8a1c17; --placeholder: #e3eefb; --placeholder-text: #1d4f91; }
|
|
3403
|
+
@media (prefers-color-scheme: dark) { :root { --bg: #151514; --panel: #1f1f1d; --text: #ecece7; --muted: #a3a39b;
|
|
3404
|
+
--line: #34342f; --accent: #8fc7b4; --removed: #4a1f1d; --removed-text: #ffb4ae; --placeholder: #1d3350;
|
|
3405
|
+
--placeholder-text: #a9cbf5; } }
|
|
3406
|
+
* { box-sizing: border-box; }
|
|
3407
|
+
body { margin: 0; font: 14px/1.45 system-ui, sans-serif; background: var(--bg); color: var(--text); }
|
|
3408
|
+
header { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; gap: 12px; align-items: center;
|
|
3409
|
+
justify-content: space-between; padding: 12px 16px; background: var(--panel); border-bottom: 1px solid var(--line); }
|
|
3410
|
+
h1 { font-size: 16px; margin: 0; }
|
|
3411
|
+
.muted { color: var(--muted); }
|
|
3412
|
+
main { display: grid; grid-template-columns: minmax(260px, 360px) 1fr; gap: 0; min-height: calc(100vh - 60px); }
|
|
3413
|
+
@media (max-width: 760px) { main { grid-template-columns: 1fr; } }
|
|
3414
|
+
nav { border-right: 1px solid var(--line); overflow: auto; max-height: calc(100vh - 60px); }
|
|
3415
|
+
nav button.item { display: block; width: 100%; text-align: left; padding: 10px 14px; border: 0;
|
|
3416
|
+
border-bottom: 1px solid var(--line); background: none; color: inherit; font: inherit; cursor: pointer; }
|
|
3417
|
+
nav button.item[aria-current="true"] { background: var(--placeholder); }
|
|
3418
|
+
nav .excluded { opacity: .5; text-decoration: line-through; }
|
|
3419
|
+
section { padding: 16px; overflow: auto; max-height: calc(100vh - 60px); }
|
|
3420
|
+
.row { display: grid; grid-template-columns: 110px 1fr auto; gap: 10px; padding: 8px 0; border-bottom: 1px solid var(--line); }
|
|
3421
|
+
.row.excluded .text { opacity: .45; text-decoration: line-through; }
|
|
3422
|
+
.kind { font-size: 12px; color: var(--muted); }
|
|
3423
|
+
.text { white-space: pre-wrap; word-break: break-word; }
|
|
3424
|
+
.diff { white-space: pre-wrap; word-break: break-word; margin-top: 6px; font-size: 12px; color: var(--muted); }
|
|
3425
|
+
del { background: var(--removed); color: var(--removed-text); text-decoration: line-through; }
|
|
3426
|
+
ins { background: var(--placeholder); color: var(--placeholder-text); text-decoration: none; }
|
|
3427
|
+
button.action { font: inherit; padding: 6px 12px; border-radius: 6px; border: 1px solid var(--line);
|
|
3428
|
+
background: var(--panel); color: inherit; cursor: pointer; }
|
|
3429
|
+
button.primary { background: var(--accent); color: var(--panel); border-color: var(--accent); }
|
|
3430
|
+
fieldset { border: 1px solid var(--line); border-radius: 8px; margin: 0 0 16px; padding: 10px 12px; }
|
|
3431
|
+
fieldset input, fieldset select { font: inherit; padding: 4px 6px; }
|
|
3432
|
+
ul.terms { list-style: none; padding: 0; margin: 8px 0 0; display: flex; flex-wrap: wrap; gap: 6px; }
|
|
3433
|
+
ul.terms li { border: 1px solid var(--line); border-radius: 999px; padding: 2px 4px 2px 10px; }
|
|
3434
|
+
.status { min-height: 1.4em; }
|
|
3435
|
+
`;
|
|
3436
|
+
var SCRIPT = `
|
|
3437
|
+
const $ = (tag, props = {}, ...children) => {
|
|
3438
|
+
const node = document.createElement(tag);
|
|
3439
|
+
for (const [key, value] of Object.entries(props)) {
|
|
3440
|
+
if (key === "text") node.textContent = value;
|
|
3441
|
+
else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
|
|
3442
|
+
else node.setAttribute(key, value);
|
|
3443
|
+
}
|
|
3444
|
+
for (const child of children) if (child) node.append(child);
|
|
3445
|
+
return node;
|
|
3446
|
+
};
|
|
3447
|
+
let state = null;
|
|
3448
|
+
let current = null;
|
|
3449
|
+
const statusLine = document.getElementById("status");
|
|
3450
|
+
async function call(path, body) {
|
|
3451
|
+
const response = await fetch(path, body === undefined ? {} : {
|
|
3452
|
+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
3453
|
+
const data = await response.json();
|
|
3454
|
+
if (!response.ok) throw new Error(data.error || "Request failed");
|
|
3455
|
+
return data;
|
|
3456
|
+
}
|
|
3457
|
+
function removedText(removed) {
|
|
3458
|
+
const parts = [];
|
|
3459
|
+
if (removed.secrets) parts.push(removed.secrets + " secrets");
|
|
3460
|
+
if (removed.personal) parts.push(removed.personal + " personal");
|
|
3461
|
+
if (removed.blocklist) parts.push(removed.blocklist + " blocklist");
|
|
3462
|
+
return parts.join(" \xB7 ");
|
|
3463
|
+
}
|
|
3464
|
+
function renderTotals() {
|
|
3465
|
+
const kept = state.items.filter((item) => !item.excluded);
|
|
3466
|
+
const sessions = kept.filter((item) => item.kind === "session").length;
|
|
3467
|
+
const totals = kept.reduce((sum, item) => ({ secrets: sum.secrets + item.removed.secrets,
|
|
3468
|
+
personal: sum.personal + item.removed.personal, blocklist: sum.blocklist + item.removed.blocklist }),
|
|
3469
|
+
{ secrets: 0, personal: 0, blocklist: 0 });
|
|
3470
|
+
document.getElementById("totals").textContent = sessions + " sessions included \xB7 removed: " +
|
|
3471
|
+
totals.secrets + " secrets, " + totals.personal + " personal details, " + totals.blocklist + " blocklist terms";
|
|
3472
|
+
}
|
|
3473
|
+
function renderList() {
|
|
3474
|
+
const nav = document.getElementById("list");
|
|
3475
|
+
nav.replaceChildren(...state.items.map((item) => $("button", {
|
|
3476
|
+
class: "item", "aria-current": String(current === item.key), onclick: () => open(item.key) },
|
|
3477
|
+
$("div", { class: item.excluded ? "excluded" : "", text: item.title }),
|
|
3478
|
+
$("div", { class: "muted", text: item.detail + (item.excludedEvents ? " \xB7 " + item.excludedEvents + " excluded" : "") +
|
|
3479
|
+
(removedText(item.removed) ? " \xB7 " + removedText(item.removed) : "") }))));
|
|
3480
|
+
}
|
|
3481
|
+
function diffNode(segments) {
|
|
3482
|
+
const node = $("div", { class: "diff" }, $("span", { text: "Before redaction: " }));
|
|
3483
|
+
for (const segment of segments) {
|
|
3484
|
+
if ("kept" in segment) node.append(document.createTextNode(segment.kept));
|
|
3485
|
+
else node.append($("del", { text: segment.removed }), $("ins", { text: segment.placeholder }));
|
|
3486
|
+
}
|
|
3487
|
+
return node;
|
|
3488
|
+
}
|
|
3489
|
+
function eventText(event) {
|
|
3490
|
+
switch (event.kind) {
|
|
3491
|
+
case "user_prompt": case "assistant_text": return event.text;
|
|
3492
|
+
case "tool_call": return event.name + ": " + event.argsSummary + (event.model ? " (model " + event.model + ")" : "");
|
|
3493
|
+
case "tool_result": return event.summary + (event.exitCode === undefined ? "" : " (exit " + event.exitCode + ")");
|
|
3494
|
+
case "file_edit": return event.path + " (" + event.linesChanged + " lines)";
|
|
3495
|
+
case "model_turn": return (event.model || "model not recorded") + (event.effort ? " \xB7 effort " + event.effort : "") +
|
|
3496
|
+
" \xB7 " + count(event.contextTokens) + " tokens of context, " + count(event.outputTokens) + " written";
|
|
3497
|
+
case "compaction": return (event.trigger ? event.trigger + " compaction" : "Compaction") +
|
|
3498
|
+
(event.preTokens === null ? "" : " \xB7 " + count(event.preTokens) + " tokens before") +
|
|
3499
|
+
(event.postTokens === null ? "" : ", " + count(event.postTokens) + " after");
|
|
3500
|
+
}
|
|
3501
|
+
return "";
|
|
3502
|
+
}
|
|
3503
|
+
const count = (n) => n.toLocaleString("en-US");
|
|
3504
|
+
const KIND_LABELS = { user_prompt: "You", assistant_text: "Assistant", tool_call: "Tool call",
|
|
3505
|
+
tool_result: "Tool result", file_edit: "File edit", model_turn: "Model turn", compaction: "Compaction" };
|
|
3506
|
+
async function open(key) {
|
|
3507
|
+
current = key;
|
|
3508
|
+
renderList();
|
|
3509
|
+
const detail = await call("/api/item?key=" + encodeURIComponent(key));
|
|
3510
|
+
const summary = state.items.find((item) => item.key === key);
|
|
3511
|
+
const pane = document.getElementById("detail");
|
|
3512
|
+
const toggle = $("button", { class: "action", text: summary.excluded ? "Include this item" : "Exclude this item",
|
|
3513
|
+
onclick: async () => { state = await call("/api/exclude", { key, excluded: !summary.excluded }); renderTotals(); open(key); } });
|
|
3514
|
+
const head = $("div", {}, $("h2", { text: summary.title }), $("p", { class: "muted", text: summary.detail }), toggle);
|
|
3515
|
+
const body = $("div");
|
|
3516
|
+
if (detail.kind === "session") {
|
|
3517
|
+
for (const row of detail.events) {
|
|
3518
|
+
const box = $("input", { type: "checkbox", title: "Include this line" });
|
|
3519
|
+
box.checked = !row.excluded;
|
|
3520
|
+
box.addEventListener("change", async () => {
|
|
3521
|
+
state = await call("/api/exclude-event", { key, index: row.index, excluded: !box.checked });
|
|
3522
|
+
renderTotals(); renderList(); line.classList.toggle("excluded", !box.checked);
|
|
3523
|
+
});
|
|
3524
|
+
const text = $("div", {}, $("div", { class: "text", text: eventText(row.event) }), row.diff ? diffNode(row.diff) : null);
|
|
3525
|
+
const line = $("div", { class: "row" + (row.excluded ? " excluded" : "") },
|
|
3526
|
+
$("div", { class: "kind", text: KIND_LABELS[row.event.kind] || row.event.kind }), text, box);
|
|
3527
|
+
body.append(line);
|
|
3528
|
+
}
|
|
3529
|
+
} else if (detail.kind === "instruction_file") {
|
|
3530
|
+
body.append($("div", { class: "text", text: detail.text }), detail.diff ? diffNode(detail.diff) : null);
|
|
3531
|
+
} else {
|
|
3532
|
+
body.append($("h3", { text: "Skills" }), $("div", { class: "text", text: detail.skills.join(", ") || "none" }),
|
|
3533
|
+
$("h3", { text: "Hooks" }), $("div", { class: "text", text: detail.hooks.map((hook) =>
|
|
3534
|
+
hook.event + (hook.matcher ? " (" + hook.matcher + ")" : "")).join("\\n") || "none" }));
|
|
3535
|
+
}
|
|
3536
|
+
pane.replaceChildren(head, body);
|
|
3537
|
+
}
|
|
3538
|
+
function renderBlocklist() {
|
|
3539
|
+
const list = document.getElementById("terms");
|
|
3540
|
+
list.replaceChildren(...state.blocklist.map((entry, index) => $("li", {},
|
|
3541
|
+
document.createTextNode(entry.term + " (" + entry.kind + ") "),
|
|
3542
|
+
$("button", { class: "action", text: "Remove", onclick: () => saveTerms(state.blocklist.filter((_, i) => i !== index)) }))));
|
|
3543
|
+
const select = document.getElementById("kind");
|
|
3544
|
+
if (!select.options.length) for (const kind of state.blocklistKinds) select.append($("option", { value: kind, text: kind }));
|
|
3545
|
+
}
|
|
3546
|
+
async function saveTerms(entries) {
|
|
3547
|
+
statusLine.textContent = "Redacting again\u2026";
|
|
3548
|
+
try {
|
|
3549
|
+
state = await call("/api/blocklist", { entries });
|
|
3550
|
+
statusLine.textContent = "Blocklist saved on this machine.";
|
|
3551
|
+
renderAll();
|
|
3552
|
+
if (current) open(current);
|
|
3553
|
+
} catch (error) { statusLine.textContent = error.message; }
|
|
3554
|
+
}
|
|
3555
|
+
function renderAll() { renderTotals(); renderList(); renderBlocklist(); }
|
|
3556
|
+
document.getElementById("add").addEventListener("click", () => {
|
|
3557
|
+
const input = document.getElementById("term");
|
|
3558
|
+
const term = input.value.trim();
|
|
3559
|
+
if (!term) return;
|
|
3560
|
+
input.value = "";
|
|
3561
|
+
saveTerms([...state.blocklist, { term, kind: document.getElementById("kind").value }]);
|
|
3562
|
+
});
|
|
3563
|
+
document.getElementById("approve").addEventListener("click", async () => {
|
|
3564
|
+
statusLine.textContent = "Building the bundle\u2026";
|
|
3565
|
+
try {
|
|
3566
|
+
const { approved } = await call("/api/approve", {});
|
|
3567
|
+
statusLine.textContent = "Approved: " + approved.sessionCount + " sessions, " +
|
|
3568
|
+
(approved.sizeBytes / 1024).toFixed(0) + " KB. Run xtrium upload in your terminal. You can close this tab.";
|
|
3569
|
+
document.getElementById("approve").disabled = true;
|
|
3570
|
+
} catch (error) { statusLine.textContent = error.message; }
|
|
3571
|
+
});
|
|
3572
|
+
call("/api/state").then((data) => { state = data; renderAll(); if (state.items[0]) open(state.items[0].key); });
|
|
3573
|
+
`;
|
|
3574
|
+
function reviewPage(nonce) {
|
|
3575
|
+
return `<!doctype html>
|
|
3576
|
+
<html lang="en">
|
|
3577
|
+
<head>
|
|
3578
|
+
<meta charset="utf-8">
|
|
3579
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
3580
|
+
<title>Xtrium review</title>
|
|
3581
|
+
<style nonce="${nonce}">${STYLE}</style>
|
|
3582
|
+
</head>
|
|
3583
|
+
<body>
|
|
3584
|
+
<header>
|
|
3585
|
+
<div><h1>Review before upload</h1><div id="totals" class="muted"></div></div>
|
|
3586
|
+
<div><button id="approve" class="action primary">Approve for upload</button></div>
|
|
3587
|
+
</header>
|
|
3588
|
+
<main>
|
|
3589
|
+
<nav id="list" aria-label="Sessions and files"></nav>
|
|
3590
|
+
<section>
|
|
3591
|
+
<fieldset>
|
|
3592
|
+
<legend>Your blocklist (saved on this machine, applied to everything)</legend>
|
|
3593
|
+
<label>Term <input id="term" maxlength="100" placeholder="Employer, client, host, codename"></label>
|
|
3594
|
+
<label>Kind <select id="kind"></select></label>
|
|
3595
|
+
<button id="add" class="action">Add</button>
|
|
3596
|
+
<ul id="terms" class="terms"></ul>
|
|
3597
|
+
</fieldset>
|
|
3598
|
+
<p id="status" class="status muted" role="status"></p>
|
|
3599
|
+
<div id="detail"></div>
|
|
3600
|
+
</section>
|
|
3601
|
+
</main>
|
|
3602
|
+
<script nonce="${nonce}">${SCRIPT}</script>
|
|
3603
|
+
</body>
|
|
3604
|
+
</html>`;
|
|
3605
|
+
}
|
|
3606
|
+
|
|
3607
|
+
// src/review-state.ts
|
|
3608
|
+
import { join as join9 } from "path";
|
|
3609
|
+
import { z as z12 } from "zod";
|
|
3610
|
+
var BLOCKLIST_MAX_ENTRIES = 500;
|
|
3611
|
+
var blocklistFileSchema = z12.object({
|
|
3612
|
+
version: z12.literal(1),
|
|
3613
|
+
entries: z12.array(blocklistEntrySchema).max(BLOCKLIST_MAX_ENTRIES)
|
|
3614
|
+
}).strict();
|
|
3615
|
+
var ITEM_KEY = z12.string().min(1).max(1200);
|
|
3616
|
+
var reviewFileSchema = z12.object({
|
|
3617
|
+
version: z12.literal(1),
|
|
3618
|
+
excludedItems: z12.array(ITEM_KEY).max(1e5),
|
|
3619
|
+
excludedEvents: z12.record(ITEM_KEY, z12.array(z12.number().int().min(0)).max(1e5))
|
|
3620
|
+
}).strict();
|
|
3621
|
+
var blocklistPath = (dir) => join9(dir, "blocklist.json");
|
|
3622
|
+
var reviewPath = (dir) => join9(dir, "review.json");
|
|
3623
|
+
async function readJson2(path, schema) {
|
|
3624
|
+
const text = await readOptionalFile(path);
|
|
3625
|
+
if (text === null) return null;
|
|
3626
|
+
try {
|
|
3627
|
+
const parsed = schema.safeParse(JSON.parse(text));
|
|
3628
|
+
return parsed.success ? parsed.data : null;
|
|
3629
|
+
} catch {
|
|
3630
|
+
return null;
|
|
3631
|
+
}
|
|
3632
|
+
}
|
|
3633
|
+
async function loadBlocklist(dir) {
|
|
3634
|
+
return (await readJson2(blocklistPath(dir), blocklistFileSchema))?.entries ?? [];
|
|
3635
|
+
}
|
|
3636
|
+
async function saveBlocklist(dir, entries) {
|
|
3637
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3638
|
+
const unique = entries.map((entry) => blocklistEntrySchema.parse(entry)).filter((entry) => {
|
|
3639
|
+
const key = `${entry.kind}:${entry.term.toLowerCase()}`;
|
|
3640
|
+
if (seen.has(key)) return false;
|
|
3641
|
+
seen.add(key);
|
|
3642
|
+
return true;
|
|
3643
|
+
}).slice(0, BLOCKLIST_MAX_ENTRIES);
|
|
3644
|
+
await writePrivateFile(
|
|
3645
|
+
blocklistPath(dir),
|
|
3646
|
+
`${JSON.stringify({ version: 1, entries: unique }, null, 2)}
|
|
3647
|
+
`
|
|
3648
|
+
);
|
|
3649
|
+
return unique;
|
|
3650
|
+
}
|
|
3651
|
+
async function loadExclusions(dir) {
|
|
3652
|
+
return await readJson2(reviewPath(dir), reviewFileSchema) ?? {
|
|
3653
|
+
version: 1,
|
|
3654
|
+
excludedItems: [],
|
|
3655
|
+
excludedEvents: {}
|
|
3656
|
+
};
|
|
3657
|
+
}
|
|
3658
|
+
async function saveExclusions(dir, exclusions) {
|
|
3659
|
+
const data = reviewFileSchema.parse(exclusions);
|
|
3660
|
+
await writePrivateFile(reviewPath(dir), `${JSON.stringify(data)}
|
|
3661
|
+
`);
|
|
3662
|
+
}
|
|
3663
|
+
|
|
3664
|
+
// src/sources.ts
|
|
3665
|
+
import { readFile as readFile5 } from "fs/promises";
|
|
3666
|
+
var INSTRUCTION_FILE_MAX_BYTES = 1024 * 1024;
|
|
3667
|
+
var hasSetup = (setup) => setup !== null && (setup.skills.length > 0 || setup.hooks.length > 0);
|
|
3668
|
+
async function readSelectedSources(roots, selections, adapters = ADAPTERS) {
|
|
3669
|
+
const chosen = new Set(selections.map((s) => projectKey(s.tool, s.project)));
|
|
3670
|
+
const sources = { sessions: [], files: [], setups: [] };
|
|
3671
|
+
for (const adapter of adapters) {
|
|
3672
|
+
const projects = selections.filter((s) => s.tool === adapter.tool).map((s) => s.project);
|
|
3673
|
+
if (projects.length === 0) continue;
|
|
3674
|
+
const files = await adapter.findTranscripts(roots);
|
|
3675
|
+
const results = await mapLimit(files, PARSE_CONCURRENCY, (file) => adapter.parse(file));
|
|
3676
|
+
for (const result of results) {
|
|
3677
|
+
if (result.status !== "ok") continue;
|
|
3678
|
+
if (!chosen.has(projectKey(result.session.tool, result.session.project))) continue;
|
|
3679
|
+
sources.sessions.push(result.session);
|
|
3680
|
+
}
|
|
3681
|
+
const userSetup = await adapter.findSetup(roots, null);
|
|
3682
|
+
if (hasSetup(userSetup))
|
|
3683
|
+
sources.setups.push({ tool: adapter.tool, project: null, setup: userSetup });
|
|
3684
|
+
for (const project of projects) {
|
|
3685
|
+
for (const file of await adapter.findInstructionFiles(roots, project)) {
|
|
3686
|
+
if (file.bytes > INSTRUCTION_FILE_MAX_BYTES) continue;
|
|
3687
|
+
try {
|
|
3688
|
+
sources.files.push({
|
|
3689
|
+
tool: adapter.tool,
|
|
3690
|
+
project,
|
|
3691
|
+
file,
|
|
3692
|
+
text: await readFile5(file.path, "utf8")
|
|
3693
|
+
});
|
|
3694
|
+
} catch {
|
|
3695
|
+
}
|
|
3696
|
+
}
|
|
3697
|
+
const setup = await adapter.findSetup(roots, project);
|
|
3698
|
+
if (hasSetup(setup)) sources.setups.push({ tool: adapter.tool, project, setup });
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
sources.sessions.sort((a, b) => b.startedAt.localeCompare(a.startedAt));
|
|
3702
|
+
return sources;
|
|
3703
|
+
}
|
|
3704
|
+
function redactSources(sources, blocklist) {
|
|
3705
|
+
return [
|
|
3706
|
+
...sources.sessions.map((session) => redactSession(session, blocklist)),
|
|
3707
|
+
...sources.files.map(
|
|
3708
|
+
(f) => redactInstructionFile(f.tool, f.project, f.file, f.text, blocklist)
|
|
3709
|
+
),
|
|
3710
|
+
...sources.setups.map((s) => redactSetup(s.tool, s.project, s.setup, blocklist))
|
|
3711
|
+
];
|
|
3712
|
+
}
|
|
3713
|
+
|
|
3714
|
+
// src/review-server.ts
|
|
3715
|
+
var COOKIE = "xtrium_review";
|
|
3716
|
+
var MAX_BODY_BYTES = 64 * 1024;
|
|
3717
|
+
var REVIEW_IDLE_MS = 60 * 60 * 1e3;
|
|
3718
|
+
var keySchema = z13.string().min(1).max(1200);
|
|
3719
|
+
var excludeSchema = z13.object({ key: keySchema, excluded: z13.boolean() }).strict();
|
|
3720
|
+
var excludeEventSchema = z13.object({ key: keySchema, index: z13.number().int().min(0), excluded: z13.boolean() }).strict();
|
|
3721
|
+
var blocklistSchema = z13.object({ entries: z13.array(blocklistEntrySchema).max(BLOCKLIST_MAX_ENTRIES) }).strict();
|
|
3722
|
+
function sameSecret(a, b) {
|
|
3723
|
+
const left = Buffer.from(a);
|
|
3724
|
+
const right = Buffer.from(b);
|
|
3725
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
3726
|
+
}
|
|
3727
|
+
function cookieValue(request) {
|
|
3728
|
+
for (const part of (request.headers.cookie ?? "").split(";")) {
|
|
3729
|
+
const [name, ...rest] = part.trim().split("=");
|
|
3730
|
+
if (name === COOKIE) return rest.join("=");
|
|
3731
|
+
}
|
|
3732
|
+
return null;
|
|
3733
|
+
}
|
|
3734
|
+
async function readBody2(request) {
|
|
3735
|
+
const chunks = [];
|
|
3736
|
+
let size = 0;
|
|
3737
|
+
for await (const chunk of request) {
|
|
3738
|
+
const buffer = chunk;
|
|
3739
|
+
size += buffer.length;
|
|
3740
|
+
if (size > MAX_BODY_BYTES) throw new Error("body too large");
|
|
3741
|
+
chunks.push(buffer);
|
|
3742
|
+
}
|
|
3743
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
3744
|
+
}
|
|
3745
|
+
function send(response, status, body, type, extra = {}) {
|
|
3746
|
+
response.writeHead(status, {
|
|
3747
|
+
"content-type": type,
|
|
3748
|
+
"cache-control": "no-store",
|
|
3749
|
+
"x-content-type-options": "nosniff",
|
|
3750
|
+
"referrer-policy": "no-referrer",
|
|
3751
|
+
"x-frame-options": "DENY",
|
|
3752
|
+
...extra
|
|
3753
|
+
});
|
|
3754
|
+
response.end(body);
|
|
3755
|
+
}
|
|
3756
|
+
var sendJson = (response, status, value) => {
|
|
3757
|
+
send(response, status, JSON.stringify(value), "application/json; charset=utf-8");
|
|
3758
|
+
};
|
|
3759
|
+
function itemSummary(item, exclusions) {
|
|
3760
|
+
const droppedEvents = new Set(exclusions.excludedEvents[item.key] ?? []);
|
|
3761
|
+
const base = {
|
|
3762
|
+
key: item.key,
|
|
3763
|
+
kind: item.kind,
|
|
3764
|
+
tool: item.tool,
|
|
3765
|
+
excluded: exclusions.excludedItems.includes(item.key),
|
|
3766
|
+
removed: groupCounts(itemCounts(item, droppedEvents))
|
|
3767
|
+
};
|
|
3768
|
+
switch (item.kind) {
|
|
3769
|
+
case "session":
|
|
3770
|
+
return {
|
|
3771
|
+
...base,
|
|
3772
|
+
title: item.project,
|
|
3773
|
+
detail: `${item.startedAt.slice(0, 16).replace("T", " ")} \xB7 ${String(item.events.length)} events`,
|
|
3774
|
+
excludedEvents: droppedEvents.size
|
|
3775
|
+
};
|
|
3776
|
+
case "instruction_file":
|
|
3777
|
+
return {
|
|
3778
|
+
...base,
|
|
3779
|
+
title: `${item.project} \xB7 ${item.name}`,
|
|
3780
|
+
detail: item.fileKind === "memory" ? "memory file" : "instruction file",
|
|
3781
|
+
excludedEvents: 0
|
|
3782
|
+
};
|
|
3783
|
+
case "setup":
|
|
3784
|
+
return {
|
|
3785
|
+
...base,
|
|
3786
|
+
title: item.project ?? "Your own settings (all projects)",
|
|
3787
|
+
detail: `${String(item.skills.length)} skills \xB7 ${String(item.hooks.length)} hooks`,
|
|
3788
|
+
excludedEvents: 0
|
|
3789
|
+
};
|
|
3790
|
+
}
|
|
3791
|
+
}
|
|
3792
|
+
function itemDetail(item, exclusions) {
|
|
3793
|
+
const droppedEvents = new Set(exclusions.excludedEvents[item.key] ?? []);
|
|
3794
|
+
switch (item.kind) {
|
|
3795
|
+
case "session":
|
|
3796
|
+
return {
|
|
3797
|
+
kind: item.kind,
|
|
3798
|
+
key: item.key,
|
|
3799
|
+
events: item.events.map((event, index) => ({
|
|
3800
|
+
index,
|
|
3801
|
+
event: event.event,
|
|
3802
|
+
diff: event.diff,
|
|
3803
|
+
excluded: droppedEvents.has(index)
|
|
3804
|
+
}))
|
|
3805
|
+
};
|
|
3806
|
+
case "instruction_file":
|
|
3807
|
+
return { kind: item.kind, key: item.key, text: item.text, diff: item.diff };
|
|
3808
|
+
case "setup":
|
|
3809
|
+
return { kind: item.kind, key: item.key, skills: item.skills, hooks: item.hooks };
|
|
3810
|
+
}
|
|
3811
|
+
}
|
|
3812
|
+
async function startReviewServer(options) {
|
|
3813
|
+
const linkToken = randomBytes(32).toString("base64url");
|
|
3814
|
+
const sessionSecret = randomBytes(32).toString("base64url");
|
|
3815
|
+
let linkUsed = false;
|
|
3816
|
+
let blocklist = options.blocklist;
|
|
3817
|
+
const exclusions = structuredClone(options.exclusions);
|
|
3818
|
+
let items = redactSources(options.sources, blocklist);
|
|
3819
|
+
const byKey = () => new Map(items.map((item) => [item.key, item]));
|
|
3820
|
+
let index = byKey();
|
|
3821
|
+
let finish = () => void 0;
|
|
3822
|
+
const done = new Promise((resolve2) => {
|
|
3823
|
+
finish = resolve2;
|
|
3824
|
+
});
|
|
3825
|
+
let idle;
|
|
3826
|
+
const server = createServer((request, response) => {
|
|
3827
|
+
handle(request, response).catch(() => {
|
|
3828
|
+
if (!response.headersSent)
|
|
3829
|
+
sendJson(response, 500, { error: "Something went wrong on this page." });
|
|
3830
|
+
});
|
|
3831
|
+
});
|
|
3832
|
+
const state = () => ({
|
|
3833
|
+
items: items.map((item) => itemSummary(item, exclusions)),
|
|
3834
|
+
blocklist,
|
|
3835
|
+
blocklistKinds: BLOCKLIST_KINDS
|
|
3836
|
+
});
|
|
3837
|
+
async function persistExclusions() {
|
|
3838
|
+
exclusions.excludedItems = exclusions.excludedItems.filter((key) => index.has(key));
|
|
3839
|
+
for (const key of Object.keys(exclusions.excludedEvents)) {
|
|
3840
|
+
if (!index.has(key)) delete exclusions.excludedEvents[key];
|
|
3841
|
+
}
|
|
3842
|
+
await saveExclusions(options.configDir, exclusions);
|
|
3843
|
+
}
|
|
3844
|
+
async function handle(request, response) {
|
|
3845
|
+
resetIdle();
|
|
3846
|
+
const port2 = server.address().port;
|
|
3847
|
+
const origin = `http://127.0.0.1:${String(port2)}`;
|
|
3848
|
+
if (request.headers.host !== `127.0.0.1:${String(port2)}`) {
|
|
3849
|
+
send(response, 421, "Wrong host.", "text/plain; charset=utf-8");
|
|
3850
|
+
return;
|
|
3851
|
+
}
|
|
3852
|
+
const url = new URL(request.url ?? "/", origin);
|
|
3853
|
+
if (request.method === "GET" && url.pathname === "/" && url.searchParams.has("token")) {
|
|
3854
|
+
const token = url.searchParams.get("token") ?? "";
|
|
3855
|
+
if (linkUsed || !sameSecret(token, linkToken)) {
|
|
3856
|
+
send(
|
|
3857
|
+
response,
|
|
3858
|
+
403,
|
|
3859
|
+
"This review link was already used or is wrong. Run `xtrium review` again.",
|
|
3860
|
+
"text/plain; charset=utf-8"
|
|
3861
|
+
);
|
|
3862
|
+
return;
|
|
3863
|
+
}
|
|
3864
|
+
linkUsed = true;
|
|
3865
|
+
send(response, 303, "", "text/plain; charset=utf-8", {
|
|
3866
|
+
location: "/",
|
|
3867
|
+
"set-cookie": `${COOKIE}=${sessionSecret}; HttpOnly; SameSite=Strict; Path=/`
|
|
3868
|
+
});
|
|
3869
|
+
return;
|
|
3870
|
+
}
|
|
3871
|
+
const cookie = cookieValue(request);
|
|
3872
|
+
if (cookie === null || !sameSecret(cookie, sessionSecret)) {
|
|
3873
|
+
send(response, 403, "Open the link printed by `xtrium review`.", "text/plain; charset=utf-8");
|
|
3874
|
+
return;
|
|
3875
|
+
}
|
|
3876
|
+
if (request.method === "GET" && url.pathname === "/") {
|
|
3877
|
+
const nonce = randomBytes(16).toString("base64");
|
|
3878
|
+
send(response, 200, reviewPage(nonce), "text/html; charset=utf-8", {
|
|
3879
|
+
"content-security-policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`
|
|
3880
|
+
});
|
|
3881
|
+
return;
|
|
3882
|
+
}
|
|
3883
|
+
if (request.method === "GET" && url.pathname === "/api/state") {
|
|
3884
|
+
sendJson(response, 200, state());
|
|
3885
|
+
return;
|
|
3886
|
+
}
|
|
3887
|
+
if (request.method === "GET" && url.pathname === "/api/item") {
|
|
3888
|
+
const item = index.get(url.searchParams.get("key") ?? "");
|
|
3889
|
+
if (item === void 0) sendJson(response, 404, { error: "No such item." });
|
|
3890
|
+
else sendJson(response, 200, itemDetail(item, exclusions));
|
|
3891
|
+
return;
|
|
3892
|
+
}
|
|
3893
|
+
if (request.method !== "POST") {
|
|
3894
|
+
sendJson(response, 405, { error: "Not allowed." });
|
|
3895
|
+
return;
|
|
3896
|
+
}
|
|
3897
|
+
if (request.headers.origin !== origin || !(request.headers["content-type"] ?? "").startsWith("application/json")) {
|
|
3898
|
+
sendJson(response, 403, { error: "Changes are accepted only from this page." });
|
|
3899
|
+
return;
|
|
3900
|
+
}
|
|
3901
|
+
let body;
|
|
3902
|
+
try {
|
|
3903
|
+
body = await readBody2(request);
|
|
3904
|
+
} catch {
|
|
3905
|
+
sendJson(response, 400, { error: "That request could not be read." });
|
|
3906
|
+
return;
|
|
3907
|
+
}
|
|
3908
|
+
switch (url.pathname) {
|
|
3909
|
+
case "/api/exclude": {
|
|
3910
|
+
const input = excludeSchema.safeParse(body);
|
|
3911
|
+
if (!input.success || !index.has(input.data.key)) break;
|
|
3912
|
+
const set = new Set(exclusions.excludedItems);
|
|
3913
|
+
if (input.data.excluded) set.add(input.data.key);
|
|
3914
|
+
else set.delete(input.data.key);
|
|
3915
|
+
exclusions.excludedItems = [...set];
|
|
3916
|
+
await persistExclusions();
|
|
3917
|
+
sendJson(response, 200, state());
|
|
3918
|
+
return;
|
|
3919
|
+
}
|
|
3920
|
+
case "/api/exclude-event": {
|
|
3921
|
+
const input = excludeEventSchema.safeParse(body);
|
|
3922
|
+
const item = input.success ? index.get(input.data.key) : void 0;
|
|
3923
|
+
if (!input.success || item?.kind !== "session" || input.data.index >= item.events.length)
|
|
3924
|
+
break;
|
|
3925
|
+
const set = new Set(exclusions.excludedEvents[input.data.key] ?? []);
|
|
3926
|
+
if (input.data.excluded) set.add(input.data.index);
|
|
3927
|
+
else set.delete(input.data.index);
|
|
3928
|
+
exclusions.excludedEvents[input.data.key] = [...set].sort((a, b) => a - b);
|
|
3929
|
+
await persistExclusions();
|
|
3930
|
+
sendJson(response, 200, state());
|
|
3931
|
+
return;
|
|
3932
|
+
}
|
|
3933
|
+
case "/api/blocklist": {
|
|
3934
|
+
const input = blocklistSchema.safeParse(body);
|
|
3935
|
+
if (!input.success) {
|
|
3936
|
+
sendJson(response, 400, {
|
|
3937
|
+
error: input.error.issues[0]?.message ?? "Check the blocklist terms."
|
|
3938
|
+
});
|
|
3939
|
+
return;
|
|
3940
|
+
}
|
|
3941
|
+
blocklist = await saveBlocklist(options.configDir, input.data.entries);
|
|
3942
|
+
items = redactSources(options.sources, blocklist);
|
|
3943
|
+
index = byKey();
|
|
3944
|
+
sendJson(response, 200, state());
|
|
3945
|
+
return;
|
|
3946
|
+
}
|
|
3947
|
+
case "/api/approve": {
|
|
3948
|
+
let approved;
|
|
3949
|
+
try {
|
|
3950
|
+
approved = await saveApproved(
|
|
3951
|
+
options.configDir,
|
|
3952
|
+
buildBundle(items, exclusions, options.cliVersion)
|
|
3953
|
+
);
|
|
3954
|
+
} catch (error) {
|
|
3955
|
+
if (!(error instanceof CliError)) throw error;
|
|
3956
|
+
sendJson(response, 400, { error: error.message });
|
|
3957
|
+
return;
|
|
3958
|
+
}
|
|
3959
|
+
sendJson(response, 200, { approved });
|
|
3960
|
+
finish(approved);
|
|
3961
|
+
return;
|
|
3962
|
+
}
|
|
3963
|
+
}
|
|
3964
|
+
sendJson(response, 400, { error: "That request is not valid." });
|
|
3965
|
+
}
|
|
3966
|
+
function resetIdle() {
|
|
3967
|
+
if (idle !== void 0) clearTimeout(idle);
|
|
3968
|
+
idle = setTimeout(() => {
|
|
3969
|
+
finish(null);
|
|
3970
|
+
}, options.idleMs ?? REVIEW_IDLE_MS);
|
|
3971
|
+
idle.unref();
|
|
3972
|
+
}
|
|
3973
|
+
await new Promise((resolve2, reject) => {
|
|
3974
|
+
server.once("error", reject);
|
|
3975
|
+
server.listen(0, "127.0.0.1", () => {
|
|
3976
|
+
resolve2();
|
|
3977
|
+
});
|
|
3978
|
+
});
|
|
3979
|
+
resetIdle();
|
|
3980
|
+
const port = server.address().port;
|
|
3981
|
+
const close = async () => {
|
|
3982
|
+
if (idle !== void 0) clearTimeout(idle);
|
|
3983
|
+
server.closeAllConnections();
|
|
3984
|
+
await new Promise(
|
|
3985
|
+
(resolve2) => server.close(() => {
|
|
3986
|
+
resolve2();
|
|
3987
|
+
})
|
|
3988
|
+
);
|
|
3989
|
+
};
|
|
3990
|
+
return { url: `http://127.0.0.1:${String(port)}/?token=${linkToken}`, done, close };
|
|
3991
|
+
}
|
|
3992
|
+
|
|
3993
|
+
// src/commands/review.ts
|
|
3994
|
+
async function review(env) {
|
|
3995
|
+
const { out } = env;
|
|
3996
|
+
const manifest = await loadManifest(env.configDir);
|
|
3997
|
+
if (manifest === null || manifest.selections.length === 0) {
|
|
3998
|
+
throw new CliError("No projects chosen yet. Run `xtrium scan` first.");
|
|
3999
|
+
}
|
|
4000
|
+
const progress = env.interactive ? spinner2() : null;
|
|
4001
|
+
progress?.start("Reading and redacting the chosen projects");
|
|
4002
|
+
const sources = await readSelectedSources(env.roots, manifest.selections);
|
|
4003
|
+
progress?.stop(
|
|
4004
|
+
`Read ${String(sources.sessions.length)} ${sources.sessions.length === 1 ? "session" : "sessions"}`
|
|
4005
|
+
);
|
|
4006
|
+
if (sources.sessions.length === 0) {
|
|
4007
|
+
throw new CliError("The chosen projects have no sessions any more. Run `xtrium scan` again.");
|
|
4008
|
+
}
|
|
4009
|
+
const server = await startReviewServer({
|
|
4010
|
+
sources,
|
|
4011
|
+
blocklist: await loadBlocklist(env.configDir),
|
|
4012
|
+
exclusions: await loadExclusions(env.configDir),
|
|
4013
|
+
configDir: env.configDir,
|
|
4014
|
+
cliVersion: env.cliVersion
|
|
4015
|
+
});
|
|
4016
|
+
out.info(
|
|
4017
|
+
"Open this page in your browser to review what would be uploaded (it works only on this machine):"
|
|
4018
|
+
);
|
|
4019
|
+
out.info(` ${server.url}`);
|
|
4020
|
+
out.info("The link works once. Press Ctrl+C to stop without approving.");
|
|
4021
|
+
const result = await Promise.race([server.done, env.interrupted.then(() => null)]);
|
|
4022
|
+
await server.close();
|
|
4023
|
+
if (result === null) {
|
|
4024
|
+
out.info("Review stopped. Nothing was approved; your exclusions and blocklist are saved.");
|
|
4025
|
+
return null;
|
|
4026
|
+
}
|
|
4027
|
+
out.info(
|
|
4028
|
+
`Approved ${String(result.sessionCount)} ${result.sessionCount === 1 ? "session" : "sessions"} (${(result.sizeBytes / 1024).toFixed(0)} KB). Removed ${String(result.redaction.secrets)} secrets, ${String(result.redaction.personal)} personal details and ${String(result.redaction.blocklist)} blocklist terms. Run \`xtrium upload\` to send it.`
|
|
4029
|
+
);
|
|
4030
|
+
return result;
|
|
4031
|
+
}
|
|
4032
|
+
|
|
4033
|
+
// src/commands/scan.ts
|
|
4034
|
+
import { isCancel, multiselect, spinner as spinner3 } from "@clack/prompts";
|
|
4035
|
+
|
|
4036
|
+
// src/format.ts
|
|
4037
|
+
import { homedir as homedir2 } from "os";
|
|
4038
|
+
function formatBytes(bytes) {
|
|
4039
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
4040
|
+
const units = ["KB", "MB", "GB"];
|
|
4041
|
+
let value = bytes / 1024;
|
|
4042
|
+
let unit = 0;
|
|
4043
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
4044
|
+
value /= 1024;
|
|
4045
|
+
unit += 1;
|
|
4046
|
+
}
|
|
4047
|
+
return `${value >= 10 ? value.toFixed(0) : value.toFixed(1)} ${units[unit] ?? "GB"}`;
|
|
4048
|
+
}
|
|
4049
|
+
function formatDateRange(firstAt, lastAt) {
|
|
4050
|
+
const first = firstAt.slice(0, 10);
|
|
4051
|
+
const last = lastAt.slice(0, 10);
|
|
4052
|
+
return first === last ? first : `${first} \u2192 ${last}`;
|
|
4053
|
+
}
|
|
4054
|
+
function displayPath(path, home = homedir2()) {
|
|
4055
|
+
if (home !== "" && (path === home || path.startsWith(`${home}/`))) {
|
|
4056
|
+
return `~${path.slice(home.length)}`;
|
|
4057
|
+
}
|
|
4058
|
+
return path;
|
|
4059
|
+
}
|
|
4060
|
+
function describeInstructions(project) {
|
|
4061
|
+
const claudeMd = project.instructionFiles.filter((file) => file.kind === "claude_md").length;
|
|
4062
|
+
const memories = project.instructionFiles.filter((file) => file.kind === "memory").length;
|
|
4063
|
+
const parts = [];
|
|
4064
|
+
if (claudeMd > 0) parts.push(`${claudeMd} CLAUDE.md`);
|
|
4065
|
+
if (memories > 0) parts.push(`${memories} ${memories === 1 ? "memory" : "memories"}`);
|
|
4066
|
+
return parts.join(", ");
|
|
4067
|
+
}
|
|
4068
|
+
function projectTable(projects, home) {
|
|
4069
|
+
const header = ["Tool", "Project", "Sessions", "Dates", "Size", "Instructions"];
|
|
4070
|
+
const rows = projects.map((project) => [
|
|
4071
|
+
TOOL_LABELS2[project.tool],
|
|
4072
|
+
displayPath(project.project, home),
|
|
4073
|
+
String(project.sessions),
|
|
4074
|
+
formatDateRange(project.firstAt, project.lastAt),
|
|
4075
|
+
formatBytes(project.bytes),
|
|
4076
|
+
describeInstructions(project)
|
|
4077
|
+
]);
|
|
4078
|
+
const widths = header.map(
|
|
4079
|
+
(title, column) => Math.max(title.length, ...rows.map((row) => (row[column] ?? "").length))
|
|
4080
|
+
);
|
|
4081
|
+
const line = (cells) => cells.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(" ").trimEnd();
|
|
4082
|
+
return [line(header), ...rows.map(line)].join("\n");
|
|
4083
|
+
}
|
|
4084
|
+
|
|
4085
|
+
// src/commands/scan.ts
|
|
4086
|
+
async function scan(options, env) {
|
|
4087
|
+
const { roots, out } = env;
|
|
4088
|
+
const progress = env.interactive ? spinner3() : null;
|
|
4089
|
+
progress?.start("Reading Claude Code and Codex history");
|
|
4090
|
+
const report = await scanSources(roots);
|
|
4091
|
+
progress?.stop(
|
|
4092
|
+
`Found ${report.projects.length} ${report.projects.length === 1 ? "project" : "projects"}`
|
|
4093
|
+
);
|
|
4094
|
+
for (const note of report.versionNotes) out.error(`Note: ${note}`);
|
|
4095
|
+
if (report.unsupported.length > 0) {
|
|
4096
|
+
out.error(
|
|
4097
|
+
`Skipped ${report.unsupported.length} ${report.unsupported.length === 1 ? "file" : "files"} in an unsupported format:`
|
|
4098
|
+
);
|
|
4099
|
+
for (const item of report.unsupported.slice(0, 5)) {
|
|
4100
|
+
out.error(` ${TOOL_LABELS2[item.tool]}: ${displayPath(item.file)}: ${item.reason}`);
|
|
4101
|
+
}
|
|
4102
|
+
if (report.unsupported.length > 5) out.error(` \u2026and ${report.unsupported.length - 5} more`);
|
|
4103
|
+
}
|
|
4104
|
+
if (report.skippedLines > 0) {
|
|
4105
|
+
out.error(
|
|
4106
|
+
`Skipped ${report.skippedLines} unreadable ${report.skippedLines === 1 ? "line" : "lines"} (corrupt or cut off); the rest of each file was read.`
|
|
4107
|
+
);
|
|
4108
|
+
}
|
|
4109
|
+
if (report.projects.length === 0) {
|
|
4110
|
+
out.info(
|
|
4111
|
+
`No Claude Code or Codex sessions found (looked in ${displayPath(roots.claudeDir)}/projects and ${displayPath(roots.codexDir)}/sessions).`
|
|
4112
|
+
);
|
|
4113
|
+
return;
|
|
4114
|
+
}
|
|
4115
|
+
out.info(projectTable(report.projects));
|
|
4116
|
+
if (options.list || !env.interactive) {
|
|
4117
|
+
if (!options.list) out.info("\nRun `xtrium scan` in a terminal to choose projects.");
|
|
4118
|
+
return;
|
|
4119
|
+
}
|
|
4120
|
+
const previous = await loadManifest(env.configDir);
|
|
4121
|
+
const chosen = await multiselect({
|
|
4122
|
+
message: "Choose the projects to include (space to select, enter to confirm). Nothing is selected yet.",
|
|
4123
|
+
options: report.projects.map((project) => ({
|
|
4124
|
+
value: projectKey(project.tool, project.project),
|
|
4125
|
+
label: `${TOOL_LABELS2[project.tool]} \xB7 ${displayPath(project.project)}`,
|
|
4126
|
+
hint: hint(project)
|
|
4127
|
+
})),
|
|
4128
|
+
initialValues: [],
|
|
4129
|
+
required: false
|
|
4130
|
+
});
|
|
4131
|
+
if (isCancel(chosen)) {
|
|
4132
|
+
out.info("Cancelled. Nothing was saved.");
|
|
4133
|
+
return;
|
|
4134
|
+
}
|
|
4135
|
+
const keys = new Set(chosen);
|
|
4136
|
+
const selections = report.projects.filter((project) => keys.has(projectKey(project.tool, project.project))).map((project) => ({ tool: project.tool, project: project.project }));
|
|
4137
|
+
await saveManifest(env.configDir, selections);
|
|
4138
|
+
const replaced = previous === null ? "" : ` It replaces your previous selection of ${previous.selections.length}.`;
|
|
4139
|
+
out.info(
|
|
4140
|
+
`Saved ${selections.length} ${selections.length === 1 ? "project" : "projects"} to ${displayPath(manifestPath(env.configDir))}.${replaced} Nothing has left this machine.`
|
|
4141
|
+
);
|
|
4142
|
+
}
|
|
4143
|
+
function hint(project) {
|
|
4144
|
+
const parts = [
|
|
4145
|
+
`${project.sessions} ${project.sessions === 1 ? "session" : "sessions"}`,
|
|
4146
|
+
formatDateRange(project.firstAt, project.lastAt),
|
|
4147
|
+
formatBytes(project.bytes)
|
|
4148
|
+
];
|
|
4149
|
+
const instructions = describeInstructions(project);
|
|
4150
|
+
if (instructions !== "") parts.push(instructions);
|
|
4151
|
+
return parts.join(" \xB7 ");
|
|
4152
|
+
}
|
|
4153
|
+
|
|
4154
|
+
// src/commands/upload.ts
|
|
4155
|
+
import { spinner as spinner4 } from "@clack/prompts";
|
|
4156
|
+
var PART_ATTEMPTS = 3;
|
|
4157
|
+
var PART_TIMEOUT_MS = 12e4;
|
|
4158
|
+
var REJECTED = {
|
|
4159
|
+
size_mismatch: "the server received a different size than was sent",
|
|
4160
|
+
hash_mismatch: "the server received different bytes than were sent",
|
|
4161
|
+
bad_signature: "the bundle's signature did not match this machine's token",
|
|
4162
|
+
not_gzip: "the bundle is not a gzip file",
|
|
4163
|
+
too_large: "the bundle is too large",
|
|
4164
|
+
bad_format: "the bundle is not in the format the server reads",
|
|
4165
|
+
counts_mismatch: "the bundle's counts do not match its contents",
|
|
4166
|
+
unredacted_secret: "the server found a secret the local redaction missed",
|
|
4167
|
+
expired: "the upload took too long and expired",
|
|
4168
|
+
superseded: "a newer upload from this account replaced it"
|
|
4169
|
+
};
|
|
4170
|
+
function safePartUrl(url) {
|
|
4171
|
+
const parsed = new URL(url);
|
|
4172
|
+
return parsed.protocol === "https:" || parsed.protocol === "http:" && (parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost");
|
|
4173
|
+
}
|
|
4174
|
+
async function upload(ctx, configDir2, fetchImpl = fetch) {
|
|
4175
|
+
const { api, credentials, out } = ctx;
|
|
4176
|
+
const approved = await loadApproved(configDir2);
|
|
4177
|
+
if (approved === null) {
|
|
4178
|
+
throw new CliError("Nothing approved to upload. Run `xtrium review` and approve first.");
|
|
4179
|
+
}
|
|
4180
|
+
const token = await credentials.load(api.origin);
|
|
4181
|
+
if (token === null) throw new CliError("Not signed in. Run `xtrium login` first.");
|
|
4182
|
+
const { meta, bytes } = approved;
|
|
4183
|
+
const begun = await api.beginUpload(token, {
|
|
4184
|
+
cliVersion: meta.cliVersion,
|
|
4185
|
+
tools: meta.tools,
|
|
4186
|
+
dateRange: meta.dateRange,
|
|
4187
|
+
sessionCount: meta.sessionCount,
|
|
4188
|
+
sizeBytes: meta.sizeBytes,
|
|
4189
|
+
sha256: meta.sha256
|
|
4190
|
+
});
|
|
4191
|
+
if (begun.status === "received") {
|
|
4192
|
+
await removeApproved(configDir2);
|
|
4193
|
+
out.info("This bundle was already uploaded and accepted. Removed the local copy.");
|
|
4194
|
+
return;
|
|
4195
|
+
}
|
|
4196
|
+
const previous = await loadUploadState(configDir2);
|
|
4197
|
+
const state = previous !== null && previous.origin === api.origin && previous.sha256 === meta.sha256 && previous.uploadId === begun.uploadId ? previous : {
|
|
4198
|
+
version: 1,
|
|
4199
|
+
origin: api.origin,
|
|
4200
|
+
sha256: meta.sha256,
|
|
4201
|
+
uploadId: begun.uploadId,
|
|
4202
|
+
parts: []
|
|
4203
|
+
};
|
|
4204
|
+
const done = new Set(state.parts.map((part) => part.partNumber));
|
|
4205
|
+
const missing = Array.from({ length: begun.partCount }, (_, i) => i + 1).filter(
|
|
4206
|
+
(n) => !done.has(n)
|
|
4207
|
+
);
|
|
4208
|
+
if (done.size > 0 && missing.length > 0) {
|
|
4209
|
+
out.info(
|
|
4210
|
+
`Resuming: ${String(done.size)} of ${String(begun.partCount)} parts were already sent.`
|
|
4211
|
+
);
|
|
4212
|
+
}
|
|
4213
|
+
const progress = ctx.interactive ? spinner4() : null;
|
|
4214
|
+
progress?.start(`Uploading ${(meta.sizeBytes / 1024 / 1024).toFixed(1)} MB`);
|
|
4215
|
+
try {
|
|
4216
|
+
for (let i = 0; i < missing.length; i += PART_URLS_PER_REQUEST) {
|
|
4217
|
+
const batch = missing.slice(i, i + PART_URLS_PER_REQUEST);
|
|
4218
|
+
const signed = await api.partUrls(token, begun.uploadId, batch);
|
|
4219
|
+
for (const part of signed.parts) {
|
|
4220
|
+
if (!safePartUrl(part.url))
|
|
4221
|
+
throw new CliError("The server sent an upload link that is not https; stopping.");
|
|
4222
|
+
const start = (part.partNumber - 1) * begun.partSize;
|
|
4223
|
+
const body = bytes.subarray(start, start + begun.partSize);
|
|
4224
|
+
if (body.length !== part.sizeBytes)
|
|
4225
|
+
throw new CliError("The server expected a different part size; stopping.");
|
|
4226
|
+
const etag = await putPart(fetchImpl, ctx.sleep, part.url, body);
|
|
4227
|
+
state.parts.push({ partNumber: part.partNumber, etag });
|
|
4228
|
+
await saveUploadState(configDir2, state);
|
|
4229
|
+
progress?.message(
|
|
4230
|
+
`Uploaded ${String(state.parts.length)} of ${String(begun.partCount)} parts`
|
|
4231
|
+
);
|
|
4232
|
+
}
|
|
4233
|
+
}
|
|
4234
|
+
progress?.message("Checking the bundle on the server");
|
|
4235
|
+
const result = await api.completeUpload(token, begun.uploadId, {
|
|
4236
|
+
parts: [...state.parts].sort((a, b) => a.partNumber - b.partNumber),
|
|
4237
|
+
signature: await signBundle(token, begun.uploadId, meta.sha256)
|
|
4238
|
+
});
|
|
4239
|
+
if (result.status === "rejected") {
|
|
4240
|
+
progress?.stop("Refused");
|
|
4241
|
+
await removeApproved(configDir2);
|
|
4242
|
+
throw new CliError(
|
|
4243
|
+
`The server refused the bundle: ${REJECTED[result.reason]}. Run \`xtrium review\` and approve again.`
|
|
4244
|
+
);
|
|
4245
|
+
}
|
|
4246
|
+
} catch (error) {
|
|
4247
|
+
progress?.stop("Stopped");
|
|
4248
|
+
throw error;
|
|
4249
|
+
}
|
|
4250
|
+
progress?.stop("Uploaded");
|
|
4251
|
+
await removeApproved(configDir2);
|
|
4252
|
+
out.info(
|
|
4253
|
+
`Uploaded ${String(meta.sessionCount)} ${meta.sessionCount === 1 ? "session" : "sessions"}. The local copy was removed. It is stored privately for your AI Workflow profile; nothing is published until you approve it on your dashboard.`
|
|
4254
|
+
);
|
|
4255
|
+
}
|
|
4256
|
+
async function putPart(fetchImpl, sleep, url, body) {
|
|
4257
|
+
let lastError = "";
|
|
4258
|
+
for (let attempt = 1; attempt <= PART_ATTEMPTS; attempt += 1) {
|
|
4259
|
+
try {
|
|
4260
|
+
const response = await fetchImpl(url, {
|
|
4261
|
+
method: "PUT",
|
|
4262
|
+
// Only the exact length is signed; fetch sends it from the body.
|
|
4263
|
+
body,
|
|
4264
|
+
redirect: "error",
|
|
4265
|
+
signal: AbortSignal.timeout(PART_TIMEOUT_MS)
|
|
4266
|
+
});
|
|
4267
|
+
const etag = response.headers.get("etag");
|
|
4268
|
+
if (response.ok && etag !== null && etag !== "") return etag;
|
|
4269
|
+
lastError = `storage answered ${String(response.status)}`;
|
|
4270
|
+
if (response.status < 500 && response.status !== 408) break;
|
|
4271
|
+
} catch {
|
|
4272
|
+
lastError = "the connection failed";
|
|
4273
|
+
}
|
|
4274
|
+
if (attempt < PART_ATTEMPTS)
|
|
4275
|
+
await new Promise((resolve2) => setTimeout(resolve2, 1e3 * attempt));
|
|
4276
|
+
}
|
|
4277
|
+
throw new CliError(
|
|
4278
|
+
`A part could not be uploaded (${lastError}). Run \`xtrium upload\` again to continue.`
|
|
4279
|
+
);
|
|
4280
|
+
}
|
|
4281
|
+
|
|
4282
|
+
// src/index.ts
|
|
4283
|
+
function action(run) {
|
|
4284
|
+
return async (...args) => {
|
|
4285
|
+
try {
|
|
4286
|
+
await run(...args);
|
|
4287
|
+
} catch (error) {
|
|
4288
|
+
consoleOutput.error(
|
|
4289
|
+
error instanceof CliError ? error.message : `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
|
|
4290
|
+
);
|
|
4291
|
+
process.exitCode = 1;
|
|
4292
|
+
}
|
|
4293
|
+
};
|
|
4294
|
+
}
|
|
4295
|
+
var program = new Command().name("xtrium").description(
|
|
4296
|
+
"Share how you work with AI coding tools on your Xtrium Atrium. Everything is chosen and reviewed on your machine first."
|
|
4297
|
+
).version(CLI_VERSION, "-v, --version");
|
|
4298
|
+
program.command("login").description("Sign in through your browser (the token can only upload AI Workflow data)").action(action(async () => login(accountContext(await systemKeyring()))));
|
|
4299
|
+
program.command("logout").description("Revoke this machine's token and remove it").action(action(async () => logout(accountContext(await systemKeyring()))));
|
|
4300
|
+
program.command("whoami").description("Show which Atrium this machine is signed in to").action(action(async () => whoami(accountContext(await systemKeyring()))));
|
|
4301
|
+
program.command("scan").description("List your Claude Code and Codex projects and choose which to include").option("--list", "only print the list, without choosing", false).action(
|
|
4302
|
+
action(
|
|
4303
|
+
async (options) => scan(options, {
|
|
4304
|
+
roots: sourceRoots(),
|
|
4305
|
+
configDir: configDir(),
|
|
4306
|
+
out: consoleOutput,
|
|
4307
|
+
interactive: process.stdin.isTTY && process.stdout.isTTY
|
|
4308
|
+
})
|
|
4309
|
+
)
|
|
4310
|
+
);
|
|
4311
|
+
program.command("review").description(
|
|
4312
|
+
"Check the chosen projects, redacted, on a page on this machine, and approve what to upload"
|
|
4313
|
+
).action(
|
|
4314
|
+
action(async () => {
|
|
4315
|
+
const interrupted = new Promise((resolve2) => {
|
|
4316
|
+
process.once("SIGINT", () => {
|
|
4317
|
+
resolve2();
|
|
4318
|
+
});
|
|
4319
|
+
});
|
|
4320
|
+
await review({
|
|
4321
|
+
roots: sourceRoots(),
|
|
4322
|
+
configDir: configDir(),
|
|
4323
|
+
out: consoleOutput,
|
|
4324
|
+
interactive: process.stdout.isTTY,
|
|
4325
|
+
cliVersion: CLI_VERSION,
|
|
4326
|
+
interrupted
|
|
4327
|
+
});
|
|
4328
|
+
})
|
|
4329
|
+
);
|
|
4330
|
+
program.command("upload").description("Upload the bundle you approved in `xtrium review` to your Atrium").action(action(async () => upload(accountContext(await systemKeyring()), configDir())));
|
|
4331
|
+
program.command("card").description(
|
|
4332
|
+
"Make a shareable image of facts from your Claude Code and Codex history (offline, no account, no AI)"
|
|
4333
|
+
).option("--theme <style>", "retro or slate", "retro").option("--since <when>", "only sessions since a date (2026-01-31) or a span (30d, 6m, 1y)").option("--out <path>", "where to write the PNG and SVG (default ./xtrium-card)").option("--no-topics", "leave the topics you worked on off the card").option(
|
|
4334
|
+
"--share",
|
|
4335
|
+
"show the card on your Atrium, with a link preview (needs `xtrium login`)",
|
|
4336
|
+
false
|
|
4337
|
+
).option("--unshare", "take the shared card down", false).action(
|
|
4338
|
+
action(
|
|
4339
|
+
async (options) => card(options, {
|
|
4340
|
+
roots: sourceRoots(),
|
|
4341
|
+
out: consoleOutput,
|
|
4342
|
+
cwd: process.cwd(),
|
|
4343
|
+
now: () => /* @__PURE__ */ new Date(),
|
|
4344
|
+
account: async () => accountContext(await systemKeyring())
|
|
4345
|
+
})
|
|
4346
|
+
)
|
|
4347
|
+
);
|
|
4348
|
+
await program.parseAsync();
|