@layernorm/overlay-agent-bridge-protocol 0.4.2 → 0.5.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/dist/index.js CHANGED
@@ -1,15 +1,14 @@
1
- import { z } from 'zod';
2
- import { driveSyncStatusSchema } from './drive.js';
3
- export * from './drive.js';
4
- export * from './drive-recovery.js';
1
+ import { z } from 'zod/v3';
2
+ import { localToolsCapabilitySchema } from './local-tools.js';
3
+ export * from './local-tools.js';
4
+ /**
5
+ * Contract between Overlay and an Agent Host: enrollment, device-signed host
6
+ * requests, capability advertisement and local tools. The host serves Overlay's
7
+ * own tools on its machine; it runs no third-party agent harness.
8
+ */
5
9
  export const OVERLAY_AGENT_PROTOCOL_VERSION = 1;
6
- export const MAX_COMMANDS_PER_POLL = 50;
7
- export const MAX_COMMAND_BYTES = 128 * 1024;
8
- export const MAX_EVENTS_PER_BATCH = 100;
9
- export const MAX_EVENT_BATCH_BYTES = 512 * 1024;
10
10
  export const MAX_HOST_REQUEST_BYTES = 512 * 1024;
11
11
  const identifier = z.string().trim().min(1).max(200);
12
- const jsonObject = z.record(z.string(), z.unknown());
13
12
  export const filesystemGrantSchema = z.discriminatedUnion('mode', [
14
13
  z.object({
15
14
  mode: z.literal('selected_roots'),
@@ -19,80 +18,12 @@ export const filesystemGrantSchema = z.discriminatedUnion('mode', [
19
18
  mode: z.literal('all_user_files'),
20
19
  }).strict(),
21
20
  ]);
22
- /** Negotiated extension: emitted only after remoteLifecycleVersion=2 enrollment. */
23
- export const executionFenceSchema = z.object({
24
- attemptId: identifier, generation: z.number().int().positive(), hostBootId: identifier.optional(),
25
- }).strict();
26
- export const recoveryCapabilitiesSchema = z.object({
27
- liveReattachment: z.boolean(), sessionLoading: z.boolean(), interruptedTurnContinuation: z.boolean(),
28
- approvalRestoration: z.boolean(), providerCheckpoints: z.boolean(),
29
- fencedSessionRestoration: z.boolean().optional(),
30
- }).strict();
31
- export const adapterSelectOptionSchema = z.object({
32
- id: identifier, label: z.string().trim().min(1).max(200), description: z.string().max(2000).optional(),
33
- }).strict();
34
- export const adapterSelectSchema = z.object({
35
- configId: identifier.optional(), currentValue: identifier.optional(), values: z.array(adapterSelectOptionSchema).min(1).max(200),
36
- }).strict();
37
- export const adapterOptionsSchema = z.object({
38
- model: adapterSelectSchema.optional(), mode: adapterSelectSchema.optional(), effort: adapterSelectSchema.optional(),
39
- discoveredAt: z.number().int().nonnegative(),
40
- }).strict();
41
- export const adapterCapabilitySchema = z.object({
42
- id: identifier,
43
- displayName: z.string().trim().min(1).max(200),
44
- protocol: z.enum(['fake', 'acp', 'eve', 'native']),
45
- version: z.string().trim().min(1).max(100).optional(),
46
- recovery: recoveryCapabilitiesSchema.optional(),
47
- options: adapterOptionsSchema.optional(),
48
- supports: z.object({
49
- prompt: z.boolean(),
50
- approval: z.boolean(),
51
- cancel: z.boolean(),
52
- resume: z.boolean(),
53
- }).strict(),
54
- }).strict();
55
- export const streamingCapabilitiesSchema = z.object({ textDeltas: z.literal(true), heartbeats: z.literal(true) }).strict();
56
21
  export const hostCapabilitiesSchema = z.object({
57
22
  protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
58
- remoteLifecycleVersion: z.literal(2).optional(),
59
- streaming: streamingCapabilitiesSchema.optional(),
60
- mcp: z.object({ approvalBridge: z.literal(true) }).strict().optional(),
61
- drive: z.object({ version: z.literal(1) }).strict().optional(),
23
+ localTools: localToolsCapabilitySchema,
62
24
  hostVersion: z.string().trim().min(1).max(100),
63
25
  platform: z.string().trim().min(1).max(200),
64
- adapters: z.array(adapterCapabilitySchema).max(100),
65
26
  filesystem: filesystemGrantSchema,
66
- maxConcurrentRuns: z.number().int().positive().max(1_000),
67
- }).strict();
68
- /** A host asks for the provider credentials of one run; the secret is never part of a stored command. */
69
- export const runCredentialsRequestSchema = z.object({
70
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
71
- runId: identifier,
72
- }).strict();
73
- /** A Cloud host discovers options using its sole enabled binding for this adapter. */
74
- export const providerDiscoveryCredentialsRequestSchema = z.object({
75
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
76
- adapterId: identifier,
77
- }).strict();
78
- export const providerCredentialsRequestSchema = z.union([runCredentialsRequestSchema, providerDiscoveryCredentialsRequestSchema]);
79
- export const driveCredentialsRequestSchema = z.object({
80
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION), runId: identifier, sessionId: identifier,
81
- execution: executionFenceSchema.omit({ hostBootId: true }).optional(),
82
- }).strict();
83
- export const driveCredentialsResponseSchema = z.object({
84
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
85
- token: z.string().min(32).max(8192).regex(/^ovdrive_[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/),
86
- expiresAt: z.number().int().positive(),
87
- scope: z.discriminatedUnion('kind', [
88
- z.object({ kind: z.literal('personal'), workspaceId: identifier, ownerUserId: identifier }).strict(),
89
- z.object({ kind: z.literal('workspace'), workspaceId: identifier }).strict(),
90
- ]),
91
- }).strict();
92
- export const runCredentialsResponseSchema = z.object({
93
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
94
- /** Provider environment for the run or isolated option probe, never stored in commands or capabilities. */
95
- env: z.record(z.string().min(1).max(128), z.string().min(1).max(8_192)),
96
27
  }).strict();
97
28
  export const enrollmentRequestSchema = z.object({
98
29
  code: z.string().trim().min(16).max(512),
@@ -101,7 +32,7 @@ export const enrollmentRequestSchema = z.object({
101
32
  hostVersion: z.string().trim().min(1).max(100),
102
33
  platform: z.string().trim().min(1).max(200),
103
34
  capabilities: hostCapabilitiesSchema,
104
- kind: z.enum(['local', 'vps', 'overlay_cloud', 'external']).default('local'),
35
+ kind: z.enum(['local', 'vps', 'external']).default('local'),
105
36
  }).strict();
106
37
  export const enrollmentResponseSchema = z.object({
107
38
  protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
@@ -116,22 +47,20 @@ export const initialCredentialRequestSchema = z.object({
116
47
  proofChallenge: z.string().trim().min(32).max(512),
117
48
  signature: z.string().trim().min(32).max(16_384),
118
49
  }).strict();
50
+ /** Scopes a host credential carries. Local tools poll with `commands:poll` and answer with `events:write`. */
51
+ export const AGENT_HOST_CREDENTIAL_METHODS = [
52
+ 'agent:heartbeat',
53
+ 'agent:capabilities:update',
54
+ 'agent:commands:poll',
55
+ 'agent:events:write',
56
+ 'agent:credentials:refresh',
57
+ ];
119
58
  export const environmentCredentialResponseSchema = z.object({
120
59
  protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
121
60
  workspaceId: identifier,
122
61
  environmentId: identifier,
123
62
  audience: z.literal('overlay-agent-control-plane'),
124
- methods: z.array(z.enum([
125
- 'agent:heartbeat',
126
- 'agent:capabilities:update',
127
- 'agent:commands:poll',
128
- 'agent:commands:ack',
129
- 'agent:events:write',
130
- 'agent:artifacts:write',
131
- 'agent:credentials:refresh',
132
- 'agent:run-credentials',
133
- 'agent:drive-credentials',
134
- ])).min(1),
63
+ methods: z.array(z.enum(AGENT_HOST_CREDENTIAL_METHODS)).min(1),
135
64
  token: z.string().trim().min(32).max(512),
136
65
  expiresAt: z.number().int().positive(),
137
66
  filesystemGrant: filesystemGrantSchema,
@@ -155,643 +84,4 @@ export function canonicalHostRequestProof(input) {
155
84
  input.tokenSha256,
156
85
  ].join('\n');
157
86
  }
158
- const commandBase = z.object({
159
- execution: executionFenceSchema.optional(),
160
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
161
- commandId: identifier,
162
- environmentId: identifier,
163
- workspaceId: identifier,
164
- runId: identifier,
165
- sequence: z.number().int().positive(),
166
- issuedAt: z.number().int().nonnegative(),
167
- });
168
- const sessionCommand = {
169
- bindingId: identifier,
170
- adapterId: identifier,
171
- workingDirectory: z.string().trim().min(1),
172
- };
173
- export const nativeRestorationSchema = z.object({
174
- previousExecution: executionFenceSchema,
175
- providerStop: z.object({ provider: z.literal('box'), leaseId: identifier, providerReference: identifier,
176
- observedAt: z.number().int().nonnegative() }).strict(),
177
- }).strict();
178
- export const startAdapterPayloadSchema = z.object({ ...sessionCommand, prompt: z.string(), sessionId: identifier.optional(),
179
- fresh: z.boolean().optional(), restore: nativeRestorationSchema.optional(), metadata: jsonObject.default({}),
180
- }).strict().refine(payload => !payload.restore || (payload.fresh !== true && Boolean(payload.sessionId)), {
181
- message: 'Native restoration requires the original session and cannot start fresh',
182
- });
183
- export const agentHostCommandSchema = z.discriminatedUnion('type', [
184
- commandBase.extend({
185
- type: z.literal('start'),
186
- payload: startAdapterPayloadSchema,
187
- }).strict(),
188
- commandBase.extend({
189
- type: z.literal('prompt'),
190
- payload: z.object({ prompt: z.string() }).strict(),
191
- }).strict(),
192
- commandBase.extend({
193
- type: z.literal('approval_response'),
194
- payload: z.object({ requestKey: identifier, optionId: identifier }).strict(),
195
- }).strict(),
196
- commandBase.extend({
197
- type: z.literal('elicitation_response'),
198
- payload: z.object({ requestKey: identifier, action: z.enum(['accept', 'decline', 'cancel']), content: jsonObject.optional() }).strict(),
199
- }).strict(),
200
- commandBase.extend({ type: z.literal('cancel'), payload: z.object({ reason: z.string().max(2_000).optional() }).strict() }).strict(),
201
- commandBase.extend({ type: z.literal('reconnect'), payload: z.object({ remoteSessionId: identifier }).strict() }).strict(),
202
- commandBase.extend({ type: z.literal('observe'), payload: z.object({}).strict() }).strict(),
203
- commandBase.extend({ type: z.literal('shutdown'), payload: z.object({ reason: z.string().max(2_000).optional() }).strict() }).strict(),
204
- ]);
205
- export const commandPollResponseSchema = z.object({
206
- streaming: streamingCapabilitiesSchema.optional(),
207
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
208
- commands: z.array(agentHostCommandSchema).max(MAX_COMMANDS_PER_POLL),
209
- retryAfterMs: z.number().int().min(100).max(60_000).optional(),
210
- // Highest command sequence the host may skip: every row below it is resolved
211
- // server-side. Only negotiated lifecycle-v2 hosts receive it; legacy schemas are strict.
212
- resolvedThroughSequence: z.number().int().min(0).optional(),
213
- }).strict().superRefine((response, context) => {
214
- for (let index = 0; index < response.commands.length; index += 1) {
215
- if (new TextEncoder().encode(JSON.stringify(response.commands[index])).byteLength > MAX_COMMAND_BYTES) {
216
- context.addIssue({ code: z.ZodIssueCode.custom, path: ['commands', index], message: 'command exceeds byte limit' });
217
- }
218
- }
219
- });
220
- export const commandAcknowledgementSchema = z.object({
221
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
222
- commandId: identifier,
223
- environmentId: identifier,
224
- accepted: z.boolean(),
225
- error: z.object({ code: identifier, message: z.string().max(2_000) }).strict().optional(),
226
- }).strict();
227
- const eventBase = z.object({
228
- execution: executionFenceSchema.optional(),
229
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
230
- eventId: identifier,
231
- environmentId: identifier,
232
- runId: identifier,
233
- sourceSequence: z.number().int().positive(),
234
- occurredAt: z.number().int().nonnegative(),
235
- });
236
- export const agentHeartbeatPayloadSchema = z.object({ quietMs: z.number().int().nonnegative(),
237
- openTools: z.array(z.object({ actionId: identifier, title: z.string().max(2000), runningMs: z.number().int().nonnegative() }).strict()).max(20),
238
- stalled: z.boolean().optional(), process: z.enum(['live', 'lost', 'unknown']).optional(),
239
- }).strict();
240
- export const nativeStartRequestSchema = z.object({ commandId: identifier, remoteSessionId: identifier, adapterId: identifier,
241
- sourceEventCursor: z.number().int().nonnegative().safe() }).strict();
242
- export const nativeStartAdmissionSchema = z.object({ commandId: identifier, attemptId: identifier,
243
- generation: z.number().int().positive().safe(), hostBootId: identifier,
244
- sourceEventCursor: z.number().int().nonnegative().safe(), canonicalTextOffset: z.number().int().nonnegative().safe(),
245
- hardDeadlineAt: z.number().int().positive().safe() }).strict();
246
- export const agentHostEventSchema = z.discriminatedUnion('type', [
247
- eventBase.extend({ type: z.literal('session_preparing'), payload: z.object({}).strict() }).strict(),
248
- eventBase.extend({ type: z.literal('native_start_requested'), payload: nativeStartRequestSchema }).strict(),
249
- eventBase.extend({ type: z.literal('process_observation'), payload: z.object({ process: z.enum(['live', 'lost', 'unknown']), recoveryOutcome: z.enum(['attached_live', 'restored', 'requires_new_attempt', 'unavailable']).optional() }).strict() }).strict(),
250
- eventBase.extend({ type: z.literal('session_started'), payload: z.object({ remoteSessionId: identifier, adapterId: identifier,
251
- restorationCommandId: identifier.optional() }).strict() }).strict(),
252
- eventBase.extend({ type: z.literal('text_checkpoint'), payload: z.object({ text: z.string(), final: z.boolean().optional(), offset: z.number().int().nonnegative().optional() }).strict() }).strict(),
253
- eventBase.extend({ type: z.literal('text_delta'), payload: z.object({ offset: z.number().int().nonnegative(), text: z.string().min(1).max(64 * 1024) }).strict() }).strict(),
254
- eventBase.extend({ type: z.literal('heartbeat'), payload: agentHeartbeatPayloadSchema }).strict(),
255
- eventBase.extend({ type: z.literal('action'), payload: z.object({ actionId: identifier, title: z.string().max(2_000), status: z.enum(['started', 'updated', 'completed', 'failed']), detail: z.string().max(20_000).optional() }).strict() }).strict(),
256
- eventBase.extend({ type: z.literal('approval_requested'), payload: z.object({ requestKey: identifier, prompt: z.string().max(20_000), options: z.array(z.object({ id: identifier, label: z.string().max(500) }).strict()).min(1).max(20), context: jsonObject.default({}) }).strict() }).strict(),
257
- eventBase.extend({ type: z.literal('elicitation_requested'), payload: z.object({ requestKey: identifier, prompt: z.string().max(20_000), requestedSchema: jsonObject, context: jsonObject.default({}) }).strict() }).strict(),
258
- eventBase.extend({ type: z.literal('plan'), payload: z.object({ entries: z.array(z.object({ id: identifier, title: z.string().max(2_000), status: z.enum(['pending', 'in_progress', 'completed', 'failed']) }).strict()).max(100) }).strict() }).strict(),
259
- eventBase.extend({ type: z.literal('commands_update'), payload: z.object({ commands: z.array(z.object({
260
- name: z.string().trim().min(1).max(200),
261
- description: z.string().max(2_000).optional(),
262
- inputHint: z.string().max(500).optional(),
263
- }).strict()).max(100) }).strict() }).strict(),
264
- eventBase.extend({ type: z.literal('diff'), payload: z.object({ diffId: identifier, title: z.string().max(2_000), patch: z.string().max(200_000), language: z.string().max(100).optional() }).strict() }).strict(),
265
- eventBase.extend({ type: z.literal('terminal'), payload: z.object({ terminalId: identifier, title: z.string().max(2_000), summary: z.string().max(20_000), exitCode: z.number().int().optional(), status: z.enum(['running', 'completed', 'failed']) }).strict() }).strict(),
266
- eventBase.extend({ type: z.literal('artifact'), payload: z.object({ name: z.string().min(1).max(500), mediaType: z.string().min(1).max(200), size: z.number().int().nonnegative(), sha256: z.string().regex(/^[a-f0-9]{64}$/), uploadReference: identifier }).strict() }).strict(),
267
- eventBase.extend({ type: z.literal('drive_sync'), payload: driveSyncStatusSchema }).strict(),
268
- eventBase.extend({ type: z.literal('completed'), payload: z.object({ summary: z.string().max(20_000).optional(), usage: jsonObject.default({}) }).strict() }).strict(),
269
- eventBase.extend({ type: z.literal('failed'), payload: z.object({ code: identifier, message: z.string().max(20_000), retryable: z.boolean() }).strict() }).strict(),
270
- eventBase.extend({ type: z.literal('cancelled'), payload: z.object({ reason: z.string().max(2_000).optional() }).strict() }).strict(),
271
- ]);
272
- export const artifactUploadRequestSchema = z.object({
273
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
274
- runId: identifier,
275
- name: z.string().trim().min(1).max(500),
276
- mediaType: z.string().trim().min(1).max(200),
277
- size: z.number().int().positive().max(25 * 1024 * 1024),
278
- sha256: z.string().regex(/^[a-f0-9]{64}$/),
279
- }).strict();
280
- export const artifactUploadResponseSchema = z.object({
281
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
282
- artifactId: identifier,
283
- uploadReference: identifier,
284
- uploadUrl: z.string().url(),
285
- headers: z.record(z.string(), z.string()).default({}),
286
- expiresAt: z.number().int().positive(),
287
- }).strict();
288
- export const artifactCompleteRequestSchema = z.object({
289
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
290
- uploadReference: identifier,
291
- }).strict();
292
- export const eventBatchSchema = z.object({
293
- protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION),
294
- environmentId: identifier,
295
- runId: identifier,
296
- events: z.array(agentHostEventSchema).min(1).max(MAX_EVENTS_PER_BATCH),
297
- }).strict().superRefine((batch, context) => {
298
- for (let index = 0; index < batch.events.length; index += 1) {
299
- const current = batch.events[index];
300
- if (current.environmentId !== batch.environmentId || current.runId !== batch.runId) {
301
- context.addIssue({ code: z.ZodIssueCode.custom, path: ['events', index], message: 'event scope must match batch scope' });
302
- }
303
- if (index > 0 && current.sourceSequence !== batch.events[index - 1].sourceSequence + 1) {
304
- context.addIssue({ code: z.ZodIssueCode.custom, path: ['events', index, 'sourceSequence'], message: 'event sequences must be contiguous' });
305
- }
306
- }
307
- if (new TextEncoder().encode(JSON.stringify(batch)).byteLength > MAX_EVENT_BATCH_BYTES) {
308
- context.addIssue({ code: z.ZodIssueCode.custom, path: ['events'], message: 'event batch exceeds byte limit' });
309
- }
310
- });
311
- export const eventAcknowledgementSchema = z.discriminatedUnion('accepted', [
312
- z.object({ protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION), accepted: z.literal(true), acknowledgedSequence: z.number().int().nonnegative(),
313
- nativeStartAdmission: nativeStartAdmissionSchema.optional() }).strict(),
314
- z.object({ protocolVersion: z.literal(OVERLAY_AGENT_PROTOCOL_VERSION), accepted: z.literal(false), expectedSequence: z.number().int().positive() }).strict(),
315
- ]);
316
- // ---- Agent profiles (imported Claude Code / Codex config) ----
317
- /**
318
- * Agent profiles: the part of a person's Claude Code or Codex setup that can move to an agent on Overlay Cloud
319
- * (instructions, skills, commands, subagents, MCP servers), and the rules that decide what may leave their computer.
320
- *
321
- * This module is pure and shared. The Agent Host runs it on the person's own machine so secrets are removed
322
- * before anything is uploaded, and Overlay runs it again on receipt, so a modified or older client cannot
323
- * smuggle one in. Nothing here reads the file system: callers pass in text files and get back what is safe.
324
- */
325
- export const AGENT_PROFILE_HARNESSES = ['claude-code', 'codex'];
326
- export function isAgentProfileHarness(value) {
327
- return typeof value === 'string' && AGENT_PROFILE_HARNESSES.includes(value);
328
- }
329
- export const AGENT_PROFILE_LIMITS = {
330
- maxFiles: 3_000,
331
- maxFileBytes: 256 * 1024,
332
- maxTotalBytes: 12 * 1024 * 1024,
333
- maxPathLength: 300,
334
- };
335
- const SECRET_TEXT_PATTERNS = [
336
- /sk-ant-[A-Za-z0-9_-]{16,}/g,
337
- /sk-(?:proj-)?[A-Za-z0-9_-]{32,}/g,
338
- /gh[pousr]_[A-Za-z0-9]{30,}/g,
339
- /github_pat_[A-Za-z0-9_]{40,}/g,
340
- /xox[abprs]-[A-Za-z0-9-]{20,}/g,
341
- /AKIA[0-9A-Z]{16}/g,
342
- /AIza[0-9A-Za-z_-]{30,}/g,
343
- /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
344
- /eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,
345
- /Bearer\s+[A-Za-z0-9._~+/=-]{30,}/g,
346
- ];
347
- const SECRET_NAME = /(?:^|[_-])(?:key|token|secret|password|passwd|pass|auth|authorization|credential|credentials|cookie)(?:$|[_-])|apikey|api_key/i;
348
- /** A value that is, or contains, a credential: a known token shape, or a long unbroken high-entropy string. */
349
- export function looksLikeSecret(value) {
350
- const text = value.trim();
351
- if (!text)
352
- return false;
353
- for (const pattern of SECRET_TEXT_PATTERNS) {
354
- pattern.lastIndex = 0;
355
- if (pattern.test(text))
356
- return true;
357
- }
358
- // Long, no spaces, mixed letters and digits: an opaque token rather than a word, a path, or a URL.
359
- return text.length >= 28 && /^[A-Za-z0-9_\-+/=.]+$/.test(text) && /[A-Za-z]/.test(text) && /\d/.test(text) && !text.includes('/');
360
- }
361
- /** Replaces secret-looking text; returns the cleaned text and how many replacements were made. */
362
- export function redactSecretText(text) {
363
- let count = 0;
364
- let out = text;
365
- for (const pattern of SECRET_TEXT_PATTERNS) {
366
- pattern.lastIndex = 0;
367
- out = out.replace(pattern, () => { count += 1; return '[REDACTED]'; });
368
- }
369
- return { text: out, count };
370
- }
371
- /** Environment-variable style name for a secret value: `GITHUB_TOKEN`, or `SERVER_HEADER` when nothing better is known. */
372
- export function secretEnvName(...parts) {
373
- const name = parts.join('_').toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, '');
374
- return /^[A-Z_]/.test(name) ? name : `S_${name}`;
375
- }
376
- const DENIED_SEGMENT = /^(?:\.env(?:\..*)?|\.git|node_modules|\.credentials\.json|credentials\.json|auth\.json|\.netrc|id_(?:rsa|ed25519|ecdsa)(?:\.pub)?|.*\.(?:pem|key|p12|pfx|keychain))$/i;
377
- const CLAUDE_RULES = [
378
- { test: (p) => p === 'CLAUDE.md', sanitize: 'text' },
379
- { test: (p) => p === 'settings.json', sanitize: 'settings' },
380
- { test: (p) => p === 'claude.json', sanitize: 'mcp-source' },
381
- { test: (p) => /^agents\/.+\.md$/.test(p), sanitize: 'text' },
382
- { test: (p) => /^commands\/.+\.md$/.test(p), sanitize: 'text' },
383
- { test: (p) => /^output-styles\/.+\.md$/.test(p), sanitize: 'text' },
384
- { test: (p) => p.startsWith('skills/') && p.length > 'skills/'.length, sanitize: 'text' },
385
- ];
386
- const CODEX_RULES = [
387
- { test: (p) => p === 'AGENTS.md', sanitize: 'text' },
388
- { test: (p) => p === 'config.toml', sanitize: 'codex-config' },
389
- { test: (p) => /^prompts\/.+\.md$/.test(p), sanitize: 'text' },
390
- { test: (p) => p.startsWith('skills/') && p.length > 'skills/'.length, sanitize: 'text' },
391
- ];
392
- /** Why a path is not part of the import, for the paths a person's folder upload contained. */
393
- const NOT_IMPORTED = [
394
- { test: (p) => /^(?:\.credentials\.json|auth\.json)$/.test(p), reason: 'Sign-in credentials are never imported.' },
395
- { test: (p) => p.startsWith('plugins/'), reason: 'Plugins are not imported; their skills and commands are not copied.' },
396
- { test: (p) => p.startsWith('hooks/'), reason: 'Hook scripts run code; they are not imported.' },
397
- { test: (p) => /^(?:projects|sessions|history|file-history|shell-snapshots|todos|statsig|telemetry|debug|cache|downloads|ide|paste-cache|session-env|backups|state)(?:\/|\.|$)/.test(p), reason: 'Conversation history, caches, and local state are not imported.' },
398
- ];
399
- function normalizePath(path) {
400
- const unified = path.replace(/\\/g, '/').replace(/^\.\//, '');
401
- if (!unified || unified.length > AGENT_PROFILE_LIMITS.maxPathLength)
402
- return null;
403
- if (unified.startsWith('/') || /^[A-Za-z]:/.test(unified) || unified.includes('\0'))
404
- return null;
405
- const segments = unified.split('/');
406
- if (segments.some((segment) => segment === '' || segment === '.' || segment === '..'))
407
- return null;
408
- return segments.join('/');
409
- }
410
- function safeJson(text) {
411
- try {
412
- const parsed = JSON.parse(text);
413
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
414
- }
415
- catch (_error) {
416
- return null;
417
- }
418
- }
419
- function isRecord(value) {
420
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
421
- }
422
- const LOCAL_PATH = /^(?:\/Users\/|\/home\/|~\/|[A-Za-z]:[\\/])/;
423
- class Collector {
424
- files = [];
425
- dropped = [];
426
- redactions = [];
427
- secrets = new Map();
428
- hooks = [];
429
- warnings = [];
430
- mcpServers = {};
431
- drop(path, reason) { this.dropped.push({ path, reason }); }
432
- need(name, usedBy) { if (!this.secrets.has(name))
433
- this.secrets.set(name, { name, usedBy }); }
434
- }
435
- const SETTINGS_DROPPED_KEYS = {
436
- env: 'Environment values can hold credentials.',
437
- apiKeyHelper: 'Runs a command to fetch a credential.',
438
- awsAuthRefresh: 'Runs a command to refresh credentials.',
439
- awsCredentialExport: 'Runs a command to export credentials.',
440
- otelHeadersHelper: 'Runs a command to produce telemetry headers.',
441
- forceLoginMethod: 'Sign-in is set up separately on Overlay.',
442
- forceLoginOrgUUID: 'Sign-in is set up separately on Overlay.',
443
- enabledPlugins: 'Plugins are not imported.',
444
- extraKnownMarketplaces: 'Plugins are not imported.',
445
- skipDangerousModePermissionPrompt: 'Overlay asks for approval itself.',
446
- };
447
- function sanitizeSettings(collector, path, text) {
448
- const parsed = safeJson(text);
449
- if (!parsed) {
450
- collector.drop(path, 'Not valid JSON.');
451
- return null;
452
- }
453
- const settings = { ...parsed };
454
- for (const [key, reason] of Object.entries(SETTINGS_DROPPED_KEYS)) {
455
- if (key in settings) {
456
- delete settings[key];
457
- collector.drop(`${path}: ${key}`, reason);
458
- }
459
- }
460
- // Overlay's approval cards are the permission prompt for a cloud agent. A mode that skips the prompt (bypass,
461
- // accept edits) would sidestep them, and one that denies whatever is not pre-approved (don't ask) would silently
462
- // refuse every tool, so only the modes that ask are imported.
463
- if (isRecord(settings.permissions) && typeof settings.permissions.defaultMode === 'string'
464
- && !['default', 'plan'].includes(settings.permissions.defaultMode)) {
465
- const { defaultMode: _mode, ...rest } = settings.permissions;
466
- settings.permissions = rest;
467
- collector.drop(`${path}: permissions.defaultMode`, 'Overlay asks for approval itself, so a mode that skips or denies the prompt is not imported.');
468
- }
469
- if (isRecord(settings.hooks)) {
470
- for (const [event, groups] of Object.entries(settings.hooks)) {
471
- for (const group of Array.isArray(groups) ? groups : []) {
472
- for (const hook of isRecord(group) && Array.isArray(group.hooks) ? group.hooks : []) {
473
- if (isRecord(hook) && typeof hook.command === 'string')
474
- collector.hooks.push({ kind: 'hook', event, command: hook.command.slice(0, 500) });
475
- }
476
- }
477
- }
478
- delete settings.hooks;
479
- }
480
- if (isRecord(settings.statusLine) && typeof settings.statusLine.command === 'string') {
481
- collector.hooks.push({ kind: 'statusline', event: 'statusLine', command: settings.statusLine.command.slice(0, 500) });
482
- delete settings.statusLine;
483
- }
484
- if (isRecord(settings.mcpServers)) {
485
- absorbMcpServers(collector, settings.mcpServers);
486
- delete settings.mcpServers;
487
- }
488
- // Anything left that is, or contains, a credential goes too.
489
- const scrub = (value, trail) => {
490
- if (typeof value === 'string') {
491
- if (looksLikeSecret(value)) {
492
- collector.drop(`${path}: ${trail}`, 'Looks like a credential.');
493
- return undefined;
494
- }
495
- return value;
496
- }
497
- if (Array.isArray(value))
498
- return value.map((entry, index) => scrub(entry, `${trail}[${index}]`)).filter((entry) => entry !== undefined);
499
- if (isRecord(value)) {
500
- const out = {};
501
- for (const [key, entry] of Object.entries(value)) {
502
- const cleaned = scrub(entry, trail ? `${trail}.${key}` : key);
503
- if (cleaned !== undefined)
504
- out[key] = cleaned;
505
- }
506
- return out;
507
- }
508
- return value;
509
- };
510
- const cleaned = scrub(settings, '');
511
- return { path, content: `${JSON.stringify(cleaned, null, 2)}\n` };
512
- }
513
- function placeholder(name) {
514
- return `\${${name}}`;
515
- }
516
- function absorbMcpServers(collector, servers) {
517
- for (const [name, raw] of Object.entries(servers)) {
518
- if (!isRecord(raw) || !/^[A-Za-z0-9_.-]{1,64}$/.test(name)) {
519
- collector.drop(`MCP server ${name}`, 'Unreadable or unsupported entry.');
520
- continue;
521
- }
522
- const server = { ...raw };
523
- // Keep only fields Claude Code defines for a server; anything else is dropped rather than copied.
524
- for (const key of Object.keys(server)) {
525
- if (!['type', 'command', 'args', 'env', 'url', 'headers'].includes(key))
526
- delete server[key];
527
- }
528
- if (isRecord(server.env)) {
529
- const env = {};
530
- for (const [key, value] of Object.entries(server.env)) {
531
- if (typeof value !== 'string')
532
- continue;
533
- if (SECRET_NAME.test(key) || looksLikeSecret(value)) {
534
- const envName = secretEnvName(key);
535
- env[key] = placeholder(envName);
536
- collector.need(envName, name);
537
- }
538
- else
539
- env[key] = value;
540
- }
541
- server.env = env;
542
- }
543
- if (isRecord(server.headers)) {
544
- const headers = {};
545
- for (const [key, value] of Object.entries(server.headers)) {
546
- if (typeof value !== 'string')
547
- continue;
548
- if (SECRET_NAME.test(key) || looksLikeSecret(value)) {
549
- const envName = secretEnvName(name, key);
550
- const scheme = /^(Bearer|Basic|Token)\s+/i.exec(value);
551
- headers[key] = `${scheme ? `${scheme[1]} ` : ''}${placeholder(envName)}`;
552
- collector.need(envName, name);
553
- }
554
- else
555
- headers[key] = value;
556
- }
557
- server.headers = headers;
558
- }
559
- if (Array.isArray(server.args)) {
560
- server.args = server.args.map((arg, index) => {
561
- if (typeof arg !== 'string')
562
- return arg;
563
- if (looksLikeSecret(arg)) {
564
- const envName = secretEnvName(name, 'ARG', String(index));
565
- collector.need(envName, name);
566
- return placeholder(envName);
567
- }
568
- return arg;
569
- });
570
- }
571
- if (typeof server.url === 'string') {
572
- try {
573
- const url = new URL(server.url);
574
- for (const [key, value] of [...url.searchParams.entries()]) {
575
- if (SECRET_NAME.test(key) || looksLikeSecret(value)) {
576
- const envName = secretEnvName(name, key);
577
- url.searchParams.set(key, placeholder(envName));
578
- collector.need(envName, name);
579
- }
580
- }
581
- // URL.toString percent-encodes the braces of a placeholder; restore them so Claude Code can expand it.
582
- server.url = url.toString().replace(/%24%7B([A-Z0-9_]+)%7D/g, '${$1}');
583
- }
584
- catch (_error) {
585
- collector.drop(`MCP server ${name}`, 'Its URL could not be read.');
586
- continue;
587
- }
588
- }
589
- if (typeof server.command === 'string' && LOCAL_PATH.test(server.command)) {
590
- collector.warnings.push({ path: `MCP server ${name}`, message: 'Its command points at a path on your computer, which will not exist on the agent\'s machine.' });
591
- }
592
- collector.mcpServers[name] = server;
593
- }
594
- }
595
- function sanitizeCodexConfig(collector, path, text) {
596
- const lines = text.split(/\r?\n/);
597
- const out = [];
598
- let table = '';
599
- let skipTable = false;
600
- for (const line of lines) {
601
- const header = /^\s*\[{1,2}\s*([^\]]+?)\s*\]{1,2}\s*$/.exec(line);
602
- if (header) {
603
- table = header[1];
604
- skipTable = /^projects(\.|$)/.test(table);
605
- if (skipTable)
606
- collector.drop(`${path}: [${table}]`, 'Trusted project paths belong to your computer.');
607
- if (!skipTable)
608
- out.push(line);
609
- continue;
610
- }
611
- if (skipTable)
612
- continue;
613
- const entry = /^\s*([A-Za-z0-9_."-]+)\s*=\s*(.*)$/.exec(line);
614
- if (entry) {
615
- const key = entry[1];
616
- const value = entry[2];
617
- if (key === 'notify') {
618
- collector.hooks.push({ kind: 'notify', event: 'notify', command: value.slice(0, 500) });
619
- continue;
620
- }
621
- const isEnvName = /(?:_env|env_key|_env_var|env_vars)$/i.test(key);
622
- const secretKey = SECRET_NAME.test(key) && !isEnvName;
623
- if (secretKey || looksLikeSecret(value.replace(/^["']|["']$/g, ''))) {
624
- collector.drop(`${path}: ${table ? `${table}.` : ''}${key}`, 'Looks like a credential; Codex cannot receive it yet.');
625
- continue;
626
- }
627
- }
628
- out.push(line);
629
- }
630
- return { path, content: `${out.join('\n').replace(/\n{3,}/g, '\n\n').trim()}\n` };
631
- }
632
- /**
633
- * Applies the import rules to a set of files (from a person's `~/.claude` or `~/.codex`): what is allowed in, with
634
- * secrets removed and a record of what was left out and why.
635
- */
636
- export function analyzeAgentProfile(harness, input) {
637
- const collector = new Collector();
638
- const rules = harness === 'claude-code' ? CLAUDE_RULES : CODEX_RULES;
639
- let total = 0;
640
- const seen = new Set();
641
- for (const file of input) {
642
- const path = typeof file?.path === 'string' ? normalizePath(file.path) : null;
643
- if (!path) {
644
- collector.drop(String(file?.path ?? '(no path)').slice(0, 120), 'Not a valid relative path.');
645
- continue;
646
- }
647
- if (seen.has(path)) {
648
- collector.drop(path, 'Listed twice.');
649
- continue;
650
- }
651
- seen.add(path);
652
- const notImported = NOT_IMPORTED.find((entry) => entry.test(path));
653
- if (notImported) {
654
- collector.drop(path, notImported.reason);
655
- continue;
656
- }
657
- const rule = rules.find((candidate) => candidate.test(path));
658
- if (!rule) {
659
- collector.drop(path, 'Not part of what an agent imports.');
660
- continue;
661
- }
662
- if (path.split('/').some((segment) => DENIED_SEGMENT.test(segment))) {
663
- collector.drop(path, 'Looks like a credential or a dependency folder.');
664
- continue;
665
- }
666
- if (typeof file.content !== 'string') {
667
- collector.drop(path, 'Not text.');
668
- continue;
669
- }
670
- if (file.content.includes('\0')) {
671
- collector.drop(path, 'Binary file.');
672
- continue;
673
- }
674
- const bytes = new TextEncoder().encode(file.content).length;
675
- if (bytes > AGENT_PROFILE_LIMITS.maxFileBytes) {
676
- collector.drop(path, `Larger than ${AGENT_PROFILE_LIMITS.maxFileBytes / 1024} KB.`);
677
- continue;
678
- }
679
- if (collector.files.length >= AGENT_PROFILE_LIMITS.maxFiles) {
680
- collector.drop(path, `More than ${AGENT_PROFILE_LIMITS.maxFiles} files.`);
681
- continue;
682
- }
683
- if (total + bytes > AGENT_PROFILE_LIMITS.maxTotalBytes) {
684
- collector.drop(path, 'The import is over its total size limit.');
685
- continue;
686
- }
687
- if (rule.sanitize === 'mcp-source') {
688
- const parsed = safeJson(file.content);
689
- if (!parsed) {
690
- collector.drop(path, 'Not valid JSON.');
691
- continue;
692
- }
693
- if (isRecord(parsed.mcpServers))
694
- absorbMcpServers(collector, parsed.mcpServers);
695
- // The rest of ~/.claude.json is account and project state: never imported.
696
- continue;
697
- }
698
- let cleaned;
699
- if (rule.sanitize === 'settings')
700
- cleaned = sanitizeSettings(collector, path, file.content);
701
- else if (rule.sanitize === 'codex-config')
702
- cleaned = sanitizeCodexConfig(collector, path, file.content);
703
- else {
704
- const redacted = redactSecretText(file.content);
705
- if (redacted.count > 0)
706
- collector.redactions.push({ path, count: redacted.count });
707
- cleaned = { path, content: redacted.text };
708
- }
709
- if (!cleaned)
710
- continue;
711
- total += new TextEncoder().encode(cleaned.content).length;
712
- collector.files.push(cleaned);
713
- }
714
- return {
715
- harness,
716
- files: collector.files,
717
- mcpServers: collector.mcpServers,
718
- hooks: collector.hooks,
719
- secrets: [...collector.secrets.values()],
720
- dropped: collector.dropped,
721
- redactions: collector.redactions,
722
- warnings: collector.warnings,
723
- };
724
- }
725
- export function summarizeAgentProfile(profile) {
726
- const skillNames = new Set();
727
- let skillFiles = 0;
728
- let commands = 0;
729
- let subagents = 0;
730
- let outputStyles = 0;
731
- let prompts = 0;
732
- let bytes = 0;
733
- for (const file of profile.files) {
734
- bytes += new TextEncoder().encode(file.content).length;
735
- if (file.path.startsWith('skills/')) {
736
- skillFiles += 1;
737
- skillNames.add(file.path.split('/')[1] ?? '');
738
- }
739
- else if (file.path.startsWith('commands/'))
740
- commands += 1;
741
- else if (file.path.startsWith('agents/'))
742
- subagents += 1;
743
- else if (file.path.startsWith('output-styles/'))
744
- outputStyles += 1;
745
- else if (file.path.startsWith('prompts/'))
746
- prompts += 1;
747
- }
748
- return {
749
- claudeMd: profile.files.some((file) => file.path === 'CLAUDE.md'),
750
- agentsMd: profile.files.some((file) => file.path === 'AGENTS.md'),
751
- settings: profile.files.some((file) => file.path === 'settings.json' || file.path === 'config.toml'),
752
- skills: skillNames.size, skillFiles, commands, subagents, outputStyles, prompts,
753
- mcpServers: Object.keys(profile.mcpServers).length,
754
- hooks: profile.hooks.length,
755
- secrets: profile.secrets.length,
756
- dropped: profile.dropped.length,
757
- files: profile.files.length,
758
- bytes,
759
- };
760
- }
761
- export function bundleFromAnalysis(profile) {
762
- return { version: 1, harness: profile.harness, files: profile.files, mcpServers: profile.mcpServers, hooks: profile.hooks, secrets: profile.secrets };
763
- }
764
- const SECRET_ENV_NAME = /^[A-Z_][A-Z0-9_]{0,63}$/;
765
- /**
766
- * Runs the import rules over an upload. The receiving side calls this whatever the sender claims to have cleaned:
767
- * files and servers are analyzed again, and the hooks and secret names a host reports are accepted only in a bounded,
768
- * validated form.
769
- */
770
- export function analyzeAgentProfileUpload(upload) {
771
- const input = [...upload.files];
772
- if (upload.harness === 'claude-code' && upload.mcpServers && Object.keys(upload.mcpServers).length > 0) {
773
- input.push({ path: 'claude.json', content: JSON.stringify({ mcpServers: upload.mcpServers }) });
774
- }
775
- const analyzed = analyzeAgentProfile(upload.harness, input);
776
- const hooks = [...analyzed.hooks];
777
- for (const hook of Array.isArray(upload.hooks) ? upload.hooks.slice(0, 100) : []) {
778
- if (hook && ['hook', 'notify', 'statusline'].includes(hook.kind) && typeof hook.command === 'string' && typeof hook.event === 'string') {
779
- hooks.push({ kind: hook.kind, event: hook.event.slice(0, 80), command: hook.command.slice(0, 500) });
780
- }
781
- }
782
- const secrets = new Map(analyzed.secrets.map((secret) => [secret.name, secret]));
783
- for (const secret of Array.isArray(upload.secrets) ? upload.secrets.slice(0, 200) : []) {
784
- if (secret && typeof secret.name === 'string' && SECRET_ENV_NAME.test(secret.name) && !secrets.has(secret.name)) {
785
- secrets.set(secret.name, { name: secret.name, usedBy: typeof secret.usedBy === 'string' ? secret.usedBy.slice(0, 80) : '' });
786
- }
787
- }
788
- return { ...analyzed, hooks, secrets: [...secrets.values()] };
789
- }
790
- /** The folders and files a client may read at the top of a harness's config folder; a browser uses it to skip big folders unread. */
791
- export const AGENT_PROFILE_TOP_LEVEL = {
792
- 'claude-code': ['CLAUDE.md', 'settings.json', 'agents', 'commands', 'skills', 'output-styles'],
793
- codex: ['AGENTS.md', 'config.toml', 'prompts', 'skills'],
794
- };
795
- export { drivePathSegments, portableDrivePathKey } from './drive-path.js';
796
- export { createMcpApprovalBridge, verifyMcpApprovalBridge } from './mcp-approval-bridge.js';
797
87
  //# sourceMappingURL=index.js.map