aismemory 0.8.9 → 0.8.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +38 -7
  2. package/dist/agent-key-mode.d.ts +26 -0
  3. package/dist/agent-key-mode.js +165 -26
  4. package/dist/agent-only-pass.d.ts +41 -0
  5. package/dist/agent-only-pass.js +539 -0
  6. package/dist/ais-http.d.ts +11 -0
  7. package/dist/ais-http.js +31 -17
  8. package/dist/cli/hooks.d.ts +35 -5
  9. package/dist/cli/hooks.js +280 -66
  10. package/dist/cli/install.d.ts +8 -0
  11. package/dist/cli/install.js +15 -0
  12. package/dist/cli/orientation-load.d.ts +18 -0
  13. package/dist/cli/orientation-load.js +50 -0
  14. package/dist/cli/read-claude-memory-tree.d.ts +37 -0
  15. package/dist/cli/read-claude-memory-tree.js +247 -2
  16. package/dist/cli/setup-core.js +7 -3
  17. package/dist/cli/slack.d.ts +2 -0
  18. package/dist/cli/slack.js +263 -0
  19. package/dist/cli/sync-memory.js +6 -3
  20. package/dist/cli-info.d.ts +1 -0
  21. package/dist/cli-info.js +4 -2
  22. package/dist/decision-card.d.ts +42 -0
  23. package/dist/decision-card.js +50 -0
  24. package/dist/decision-ledger.d.ts +24 -0
  25. package/dist/decision-ledger.js +59 -0
  26. package/dist/decision-receipt.d.ts +33 -0
  27. package/dist/decision-receipt.js +72 -0
  28. package/dist/device-poll.d.ts +16 -7
  29. package/dist/device-poll.js +31 -3
  30. package/dist/handoff-doc.d.ts +9 -0
  31. package/dist/handoff-doc.js +53 -0
  32. package/dist/inbox-client.js +33 -26
  33. package/dist/index.js +221 -56
  34. package/dist/mcp/tools.d.ts +3 -0
  35. package/dist/mcp/tools.js +119 -31
  36. package/dist/operating-layer-read.d.ts +38 -0
  37. package/dist/operating-layer-read.js +164 -0
  38. package/dist/pipeline/types.d.ts +2 -0
  39. package/dist/recall-warning.d.ts +14 -0
  40. package/dist/recall-warning.js +36 -0
  41. package/dist/request-timeout.d.ts +27 -2
  42. package/dist/request-timeout.js +92 -2
  43. package/dist/run-pass-mode.js +34 -16
  44. package/dist/session-identity.js +3 -1
  45. package/dist/session-start.d.ts +13 -3
  46. package/dist/session-start.js +53 -10
  47. package/dist/skill-fetch.d.ts +30 -0
  48. package/dist/skill-fetch.js +88 -0
  49. package/dist/slack-tools.d.ts +44 -0
  50. package/dist/slack-tools.js +156 -0
  51. package/dist/sources/local-claude.js +16 -2
  52. package/dist/sources/types.d.ts +2 -0
  53. package/dist/startup-identity.d.ts +4 -0
  54. package/dist/startup-identity.js +2 -0
  55. package/dist/tool-args.d.ts +12 -1
  56. package/dist/tool-args.js +15 -0
  57. package/dist/tool-scope-filter.d.ts +29 -0
  58. package/dist/tool-scope-filter.js +123 -0
  59. package/dist/version-check.d.ts +30 -3
  60. package/dist/version-check.js +59 -4
  61. package/dist/workspace-key-mode.js +36 -22
  62. package/package.json +4 -3
@@ -0,0 +1,539 @@
1
+ /** The portable device credential. Only this module handles the raw pass. */
2
+ import { chmodSync, closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
5
+ import { homedir, hostname } from 'node:os';
6
+ import { dirname, join } from 'node:path';
7
+ import { setTimeout as sleep } from 'node:timers/promises';
8
+ import { z } from 'zod';
9
+ import { AisHttpError } from './ais-http-error.js';
10
+ import { withAisClientVersion } from './ais-http.js';
11
+ import { pollDeviceGrant, runPollLoop } from './device-poll.js';
12
+ import { getAisRequestTimeoutMs, startAisRequestTimeout } from './request-timeout.js';
13
+ const HOUR = 3_600_000;
14
+ const ROTATION_AGE = 12 * HOUR;
15
+ const identifier = z.string().regex(/^[a-zA-Z0-9_-]+$/);
16
+ const key = z.string().regex(/^ais_ak_[a-zA-Z0-9_-]+$/);
17
+ const timestamp = z.string().refine((value) => Number.isFinite(Date.parse(value)));
18
+ const rotation = z.object({ agent_api_key: key, key_id: identifier, expires_at: timestamp });
19
+ const pickup = rotation.extend({ agent_id: identifier, tenant_id: identifier, read_only: z.boolean() });
20
+ const active = pickup.omit({ agent_api_key: true }).extend({
21
+ key, minted_at: timestamp, ais_origin: z.string(), rotate_after_ms: z.number().optional(),
22
+ });
23
+ const ROTATION_BACKOFF = 5_000;
24
+ const ROTATION_RETRY_WINDOW = 10 * 60_000;
25
+ const rotating = active.omit({ key: true, key_id: true }).extend({
26
+ rotating: z.object({
27
+ request_id: z.string().regex(/^[a-zA-Z0-9_-]{43}$/),
28
+ old_key_id: identifier,
29
+ old_key: key,
30
+ started_ms: z.number(),
31
+ retry_after_ms: z.number(),
32
+ retry_sent: z.boolean(),
33
+ successor: rotation.extend({ minted_at: timestamp }).optional(),
34
+ }),
35
+ });
36
+ const ended = z.object({ ended: z.literal(true), agent_id: identifier, ais_origin: z.string() });
37
+ export function agentOnlyPassPath() {
38
+ return join(homedir(), '.aismemory', 'agent-key.json');
39
+ }
40
+ function hasCode(error, code) {
41
+ return error instanceof Error && 'code' in error && error.code === code;
42
+ }
43
+ function ensurePrivateDirectory(file) {
44
+ const directory = dirname(file);
45
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
46
+ const stat = lstatSync(directory);
47
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 0o022) !== 0) {
48
+ throw new Error('The agent pass directory must be owned by the current user and writable only by that user.');
49
+ }
50
+ if ((stat.mode & 0o7777) !== 0o700)
51
+ chmodSync(directory, 0o700);
52
+ }
53
+ function readRecord(file, origin) {
54
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
55
+ try {
56
+ const stat = fstatSync(fd);
57
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0) {
58
+ throw new Error('The agent pass file must be owned by the current user and have private permissions (0600).');
59
+ }
60
+ let raw;
61
+ try {
62
+ raw = JSON.parse(readFileSync(fd, 'utf8'));
63
+ }
64
+ catch {
65
+ throw new Error('The agent pass file is invalid.');
66
+ }
67
+ const parsed = z.union([active, rotating, ended]).safeParse(raw);
68
+ if (!parsed.success)
69
+ throw new Error('The agent pass file is invalid.');
70
+ if (parsed.data.ais_origin !== origin)
71
+ throw new Error('The agent pass is bound to a different AIS origin.');
72
+ return parsed.data;
73
+ }
74
+ finally {
75
+ closeSync(fd);
76
+ }
77
+ }
78
+ class PassEndedError extends Error {
79
+ constructor(agent) {
80
+ super(`This computer's pass for ${agent} ended. Run \`aismemory bond --agent-only\` to sign in again.`);
81
+ }
82
+ }
83
+ function loadUsableRecord(file, origin, now) {
84
+ ensurePrivateDirectory(file);
85
+ let record;
86
+ try {
87
+ record = readRecord(file, origin);
88
+ }
89
+ catch (error) {
90
+ if (hasCode(error, 'ENOENT'))
91
+ throw new Error('No agent pass found. Run `aismemory bond --agent-only` first.');
92
+ throw error;
93
+ }
94
+ if ('ended' in record)
95
+ throw new PassEndedError(record.agent_id);
96
+ const expiresAt = 'rotating' in record ? record.rotating.successor?.expires_at ?? record.expires_at : record.expires_at;
97
+ if (Date.parse(expiresAt) <= now)
98
+ throw new PassEndedError(record.agent_id);
99
+ return record;
100
+ }
101
+ export function loadAgentOnlyPass(file, origin, now = Date.now()) {
102
+ const pass = loadUsableRecord(file, origin, now);
103
+ if ('rotating' in pass)
104
+ throw new Error('Agent pass rotation is pending.');
105
+ return pass;
106
+ }
107
+ function writeTemporary(file, value) {
108
+ const temporary = `${file}.${randomUUID()}.tmp`;
109
+ const fd = openSync(temporary, 'wx', 0o600);
110
+ try {
111
+ try {
112
+ fchmodSync(fd, 0o600);
113
+ writeFileSync(fd, JSON.stringify(value));
114
+ fsyncSync(fd);
115
+ }
116
+ finally {
117
+ closeSync(fd);
118
+ }
119
+ }
120
+ catch (error) {
121
+ unlinkSync(temporary);
122
+ throw error;
123
+ }
124
+ return temporary;
125
+ }
126
+ function replacePass(file, pass) {
127
+ const temporary = writeTemporary(file, pass);
128
+ try {
129
+ renameSync(temporary, file);
130
+ }
131
+ catch (error) {
132
+ unlinkSync(temporary);
133
+ throw error;
134
+ }
135
+ const directory = openSync(dirname(file), 'r');
136
+ try {
137
+ fsyncSync(directory);
138
+ }
139
+ finally {
140
+ closeSync(directory);
141
+ }
142
+ }
143
+ function assertNoActivePass(file, origin) {
144
+ try {
145
+ const previous = readRecord(file, origin);
146
+ if (!('ended' in previous) && Date.parse(previous.expires_at) > Date.now()) {
147
+ throw new Error('An active agent pass already exists.');
148
+ }
149
+ }
150
+ catch (error) {
151
+ if (!hasCode(error, 'ENOENT'))
152
+ throw error;
153
+ }
154
+ }
155
+ const lockOwner = z.object({
156
+ pid: z.number().int().positive().max(2_147_483_647),
157
+ started: z.string().min(1),
158
+ token: z.string().min(1),
159
+ });
160
+ function processStart(pid) {
161
+ try {
162
+ return execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {
163
+ encoding: 'utf8', env: { LC_ALL: 'C', TZ: 'UTC' }, stdio: ['ignore', 'pipe', 'ignore'],
164
+ }).trim() || undefined;
165
+ }
166
+ catch {
167
+ return undefined;
168
+ }
169
+ }
170
+ function readLock(path) {
171
+ try {
172
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
173
+ try {
174
+ const stat = fstatSync(fd);
175
+ if (!stat.isFile() || stat.uid !== process.getuid?.() || stat.size > 1024)
176
+ return undefined;
177
+ const raw = JSON.parse(readFileSync(fd, 'utf8'));
178
+ return lockOwner.safeParse(raw).data;
179
+ }
180
+ finally {
181
+ closeSync(fd);
182
+ }
183
+ }
184
+ catch {
185
+ return undefined;
186
+ }
187
+ }
188
+ function isStale(owner) {
189
+ try {
190
+ process.kill(owner.pid, 0);
191
+ }
192
+ catch (error) {
193
+ if (hasCode(error, 'ESRCH'))
194
+ return true;
195
+ }
196
+ const started = processStart(owner.pid);
197
+ return started !== undefined && started !== owner.started;
198
+ }
199
+ function releaseLock(path, owner) {
200
+ if (readLock(path)?.token === owner.token)
201
+ unlinkSync(path);
202
+ }
203
+ async function acquireLock(path, owner, deadline) {
204
+ for (;;) {
205
+ const temporary = writeTemporary(path, owner);
206
+ try {
207
+ // Publish a complete owner record atomically, including on first acquisition.
208
+ linkSync(temporary, path);
209
+ return;
210
+ }
211
+ catch (error) {
212
+ if (!hasCode(error, 'EEXIST'))
213
+ throw error;
214
+ }
215
+ finally {
216
+ unlinkSync(temporary);
217
+ }
218
+ const previous = readLock(path);
219
+ if (previous && isStale(previous)) {
220
+ // Serialize contenders for this owner. Recheck after acquiring the guard
221
+ // because another process may already have replaced the stale lock.
222
+ const guardName = createHash('sha256').update(path).update(previous.token).digest('hex');
223
+ const guard = join(dirname(path), `.pass-lock-${guardName}`);
224
+ await acquireLock(guard, owner, deadline);
225
+ try {
226
+ if (readLock(path)?.token === previous.token) {
227
+ const replacement = writeTemporary(path, owner);
228
+ try {
229
+ renameSync(replacement, path);
230
+ }
231
+ catch (error) {
232
+ unlinkSync(replacement);
233
+ throw error;
234
+ }
235
+ return;
236
+ }
237
+ }
238
+ finally {
239
+ releaseLock(guard, owner);
240
+ }
241
+ }
242
+ if (Date.now() >= deadline)
243
+ throw new Error('The agent pass is locked. Try again shortly.');
244
+ await sleep(50);
245
+ }
246
+ }
247
+ let ownStart;
248
+ async function lock(file) {
249
+ ensurePrivateDirectory(file);
250
+ ownStart ??= processStart(process.pid);
251
+ if (!ownStart)
252
+ throw new Error('Could not determine the agent pass lock owner.');
253
+ const owner = { pid: process.pid, started: ownStart, token: randomBytes(32).toString('base64url') };
254
+ const path = `${file}.lock`;
255
+ await acquireLock(path, owner, Date.now() + 30_000);
256
+ return () => releaseLock(path, owner);
257
+ }
258
+ async function withPassLock(file, work) {
259
+ const release = await lock(file);
260
+ try {
261
+ return await work();
262
+ }
263
+ finally {
264
+ release();
265
+ }
266
+ }
267
+ const authorization = z.object({
268
+ success: z.literal(true),
269
+ data: z.object({
270
+ device_code: z.string().min(1),
271
+ user_code: z.string().min(1),
272
+ verification_uri_complete: z.url(),
273
+ fingerprint: z.string().regex(/^[A-F0-9]{8}$/),
274
+ interval: z.number().positive().optional(),
275
+ }),
276
+ });
277
+ export async function bondAgentOnly(file, origin, options, post, log) {
278
+ await withPassLock(file, async () => assertNoActivePass(file, origin));
279
+ const auth = await post('/v1/oauth/device/authorize', {
280
+ name: options.name, mode: options.mode, credential: 'agent_key',
281
+ device_label: hostname().trim().slice(0, 64) || 'unknown',
282
+ harness: options.harness.slice(0, 32) || 'aismemory',
283
+ }).catch((error) => {
284
+ if (error instanceof AisHttpError && error.body && typeof error.body === 'object' &&
285
+ 'code' in error.body && error.body.code === 'AGENT_ONLY_DISABLED') {
286
+ throw new Error('Agent-only bonding is disabled on this AIS server.');
287
+ }
288
+ throw new Error('Could not start agent-only bonding.');
289
+ });
290
+ const parsed = authorization.safeParse(auth);
291
+ if (!parsed.success)
292
+ throw new Error('AIS returned an invalid agent-only authorization.');
293
+ const handle = parsed.data.data;
294
+ log(handle.verification_uri_complete);
295
+ log(handle.user_code);
296
+ log(`Check the page shows: ${handle.fingerprint}`);
297
+ await runPollLoop(handle, {
298
+ pollOnce: (code) => withPassLock(file, async () => {
299
+ assertNoActivePass(file, origin);
300
+ const body = await pollDeviceGrant(code, post).catch(() => {
301
+ throw new Error('Could not collect the agent-only pass.');
302
+ });
303
+ const result = pickup.safeParse(body);
304
+ if (result.success) {
305
+ const { agent_api_key, ...metadata } = result.data;
306
+ // Pickup has no mint timestamp. The first pass receives the full 24h TTL.
307
+ const mintedAt = Date.parse(metadata.expires_at) - 24 * HOUR;
308
+ replacePass(file, { ...metadata, key: agent_api_key, ais_origin: origin, minted_at: new Date(mintedAt).toISOString() });
309
+ return { collected: true };
310
+ }
311
+ const error = body?.error;
312
+ if (error && ['authorization_pending', 'slow_down', 'expired_token', 'access_denied', 'already_collected'].includes(error)) {
313
+ return { error, pending_reason: body.pending_reason };
314
+ }
315
+ throw new Error('Could not collect the agent-only pass.');
316
+ }),
317
+ accept: (body) => 'collected' in body && body.collected === true,
318
+ startNewFlow: async () => { throw new Error('Device code expired. Run aismemory bond --agent-only again.'); },
319
+ emitStderr: log,
320
+ pollIntervalMs: (handle.interval ?? 5) * 1_000,
321
+ });
322
+ }
323
+ function connectionFailed(error) {
324
+ // These errors come from connection setup. A socket close or ordinary
325
+ // timeout can also happen after transmission.
326
+ return ['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'UND_ERR_CONNECT_TIMEOUT'].some((code) => hasCode(error, code));
327
+ }
328
+ function rotationNotSent(error) {
329
+ const cause = error instanceof Error ? error.cause : undefined;
330
+ if (connectionFailed(error) || connectionFailed(cause))
331
+ return true;
332
+ const failures = cause instanceof AggregateError ? cause.errors : undefined;
333
+ return Array.isArray(failures) && failures.length > 0 && failures.every(connectionFailed);
334
+ }
335
+ export class AgentOnlyPass {
336
+ file;
337
+ origin;
338
+ log;
339
+ send;
340
+ now;
341
+ queue = Promise.resolve();
342
+ agentId;
343
+ constructor(file, origin, log, send = globalThis.fetch, now = Date.now) {
344
+ this.file = file;
345
+ this.origin = origin;
346
+ this.log = log;
347
+ this.send = send;
348
+ this.now = now;
349
+ }
350
+ async initialize() {
351
+ return withPassLock(this.file, async () => this.currentPass().agent_id);
352
+ }
353
+ startRenewal() {
354
+ const timer = setInterval(() => {
355
+ void this.enqueue(async () => {
356
+ await this.rotateIfDue(this.currentPass());
357
+ }).catch((error) => {
358
+ if (error instanceof PassEndedError)
359
+ clearInterval(timer);
360
+ });
361
+ }, 60_000);
362
+ timer.unref();
363
+ }
364
+ fetch = (input, init) => {
365
+ const url = new URL(input instanceof Request ? input.url : input);
366
+ if (url.origin !== this.origin || !url.pathname.startsWith('/v1/')) {
367
+ return Promise.reject(new Error('The computer pass can only be used with its AIS server.'));
368
+ }
369
+ return this.enqueue(async () => {
370
+ const pass = await this.rotateIfDue(this.currentPass());
371
+ const callerSignal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
372
+ const requestSignal = startAisRequestTimeout(callerSignal);
373
+ requestSignal.throwIfAborted();
374
+ const headers = new Headers(init?.headers);
375
+ headers.set('x-agent-api-key', pass.key);
376
+ let response;
377
+ try {
378
+ response = await this.send(input, { ...init, headers, signal: requestSignal, redirect: 'error' });
379
+ }
380
+ catch {
381
+ requestSignal.throwIfAborted();
382
+ throw new Error('AIS request with the computer pass failed.');
383
+ }
384
+ if (response.status === 401)
385
+ this.end(pass);
386
+ // Key-mode helpers expose server error bodies and version headers.
387
+ const responseHeaders = new Headers(response.headers);
388
+ for (const [name, value] of responseHeaders) {
389
+ if (value.includes(pass.key))
390
+ responseHeaders.set(name, value.replaceAll(pass.key, '[redacted]'));
391
+ }
392
+ const body = response.body ? (await response.text()).replaceAll(pass.key, '[redacted]') : null;
393
+ return new Response(body, { status: response.status, headers: responseHeaders });
394
+ });
395
+ };
396
+ enqueue(work) {
397
+ const pending = this.queue.then(() => withPassLock(this.file, work));
398
+ this.queue = pending.catch(() => { });
399
+ return pending;
400
+ }
401
+ currentPass() {
402
+ const current = loadUsableRecord(this.file, this.origin, this.now());
403
+ this.agentId ??= current.agent_id;
404
+ if (current.agent_id !== this.agentId)
405
+ throw new PassEndedError(this.agentId);
406
+ return current;
407
+ }
408
+ end(pass) {
409
+ replacePass(this.file, { ended: true, agent_id: pass.agent_id, ais_origin: this.origin });
410
+ const error = new PassEndedError(pass.agent_id);
411
+ this.log(error.message);
412
+ throw error;
413
+ }
414
+ deferRotation(pass) {
415
+ if (pass.rotating.retry_sent && !pass.rotating.successor)
416
+ this.end(pass);
417
+ pass.rotating.retry_after_ms = this.now() + ROTATION_BACKOFF;
418
+ replacePass(this.file, pass);
419
+ throw new Error('Agent pass rotation is pending. Try again shortly.');
420
+ }
421
+ async rotateIfDue(pass) {
422
+ const now = this.now();
423
+ const retrying = 'rotating' in pass;
424
+ let pending;
425
+ if (retrying) {
426
+ if (pass.rotating.successor) {
427
+ if (now < pass.rotating.retry_after_ms)
428
+ throw new Error('Agent pass rotation is pending. Try again shortly.');
429
+ return this.confirmSuccessor(pass, pass.rotating.successor);
430
+ }
431
+ if (pass.rotating.retry_sent || now >= pass.rotating.started_ms + ROTATION_RETRY_WINDOW)
432
+ this.end(pass);
433
+ if (now < pass.rotating.retry_after_ms)
434
+ throw new Error('Agent pass rotation is pending. Try again shortly.');
435
+ pending = { ...pass, rotating: { ...pass.rotating, retry_sent: true } };
436
+ }
437
+ else {
438
+ if (now < Math.max(Date.parse(pass.minted_at) + ROTATION_AGE, pass.rotate_after_ms ?? 0))
439
+ return pass;
440
+ const { key: old_key, key_id: old_key_id, ...metadata } = pass;
441
+ pending = {
442
+ ...metadata,
443
+ rotating: {
444
+ old_key, old_key_id, request_id: randomBytes(32).toString('base64url'),
445
+ started_ms: now, retry_after_ms: now + ROTATION_BACKOFF, retry_sent: false,
446
+ },
447
+ };
448
+ }
449
+ replacePass(this.file, pending);
450
+ const { rotating: attempt, ...metadata } = pending;
451
+ const agentPath = `/v1/agents/${pass.agent_id}`;
452
+ let res;
453
+ try {
454
+ res = await this.send(new URL(`${agentPath}/api-keys/rotate`, this.origin), {
455
+ method: 'POST',
456
+ headers: withAisClientVersion({ 'x-agent-api-key': attempt.old_key, 'Idempotency-Key': attempt.request_id }),
457
+ redirect: 'error',
458
+ signal: AbortSignal.timeout(getAisRequestTimeoutMs()),
459
+ });
460
+ }
461
+ catch (error) {
462
+ if (!rotationNotSent(error))
463
+ this.deferRotation(pending);
464
+ if (retrying) {
465
+ attempt.retry_sent = false;
466
+ this.deferRotation(pending);
467
+ }
468
+ replacePass(this.file, pass);
469
+ throw new Error('Agent pass rotation could not connect. Try again shortly.');
470
+ }
471
+ if (res.status === 401)
472
+ this.end(pending);
473
+ let body;
474
+ try {
475
+ body = await res.json();
476
+ }
477
+ catch {
478
+ this.deferRotation(pending);
479
+ }
480
+ const delay = z.object({
481
+ error: z.literal('rotate_too_soon'), retry_after_seconds: z.number().positive(),
482
+ }).safeParse(body);
483
+ if (res.status === 429 && delay.success) {
484
+ const next = {
485
+ ...metadata, key: attempt.old_key, key_id: attempt.old_key_id,
486
+ rotate_after_ms: this.now() + delay.data.retry_after_seconds * 1000,
487
+ };
488
+ replacePass(this.file, next);
489
+ return next;
490
+ }
491
+ const successor = rotation.safeParse(body);
492
+ if (res.status !== 200 || !successor.success || successor.data.agent_api_key === attempt.old_key) {
493
+ this.deferRotation(pending);
494
+ }
495
+ const received = { ...successor.data, minted_at: new Date(this.now()).toISOString() };
496
+ attempt.successor = received;
497
+ replacePass(this.file, pending);
498
+ return this.confirmSuccessor(pending, received);
499
+ }
500
+ async confirmSuccessor(pending, successor) {
501
+ if (Date.parse(successor.expires_at) <= this.now())
502
+ this.end(pending);
503
+ const { rotating: _attempt, ...metadata } = pending;
504
+ const next = {
505
+ ...metadata, key: successor.agent_api_key, key_id: successor.key_id,
506
+ expires_at: successor.expires_at, minted_at: successor.minted_at,
507
+ rotate_after_ms: undefined,
508
+ };
509
+ let confirmation;
510
+ try {
511
+ confirmation = await this.send(new URL(`/v1/agents/${pending.agent_id}/whoami`, this.origin), {
512
+ method: 'GET',
513
+ headers: withAisClientVersion({ 'x-agent-api-key': next.key }),
514
+ redirect: 'error',
515
+ signal: AbortSignal.timeout(getAisRequestTimeoutMs()),
516
+ });
517
+ }
518
+ catch {
519
+ this.deferRotation(pending);
520
+ }
521
+ if (confirmation.status === 401)
522
+ this.end(pending);
523
+ if (!confirmation.ok) {
524
+ void confirmation.body?.cancel().catch(() => { });
525
+ this.deferRotation(pending);
526
+ }
527
+ try {
528
+ await confirmation.json();
529
+ }
530
+ catch {
531
+ this.deferRotation(pending);
532
+ }
533
+ if (Date.parse(next.expires_at) <= this.now())
534
+ this.end(pending);
535
+ replacePass(this.file, next);
536
+ return next;
537
+ }
538
+ }
539
+ //# sourceMappingURL=agent-only-pass.js.map
@@ -6,6 +6,17 @@ export declare const AIS_GET_RETRYABLE_STATUSES: Set<number>;
6
6
  export declare const AIS_GET_RETRY_DELAY_MS = 250;
7
7
  export declare const CLIENT_VERSION_HEADER = "X-AIS-Client-Version";
8
8
  export declare const UPDATE_NOTICE_HEADER = "X-AIS-Update-Notice";
9
+ /** Structured minimum the client compares locally (CORBOT-4142F77E). */
10
+ export declare const MIN_CLIENT_VERSION_HEADER = "X-AIS-Min-Client-Version";
11
+ /** Attach `X-AIS-Client-Version` for every AIS HTTP stack (bearer, agent-key, …). */
12
+ export declare function withAisClientVersion(headers: Record<string, string>): Record<string, string>;
13
+ /**
14
+ * Hand server-sent version signals to the same path whoami / full_context /
15
+ * first-tool reads. Structured minimum (CORBOT-4142F77E) is preferred; the
16
+ * free-text notice covers older servers that only set X-AIS-Update-Notice.
17
+ * Exported so agent-key / workspace-key / run-pass HTTP helpers share one path.
18
+ */
19
+ export declare function captureServerVersionHeaders(res: Response): void;
9
20
  export declare const DEFAULT_AIS_URL = "https://ais.agentsandswarms.ai";
10
21
  /** Refuse plaintext owner credentials except for explicit local development hosts. */
11
22
  export declare function validateAisUrl(aisUrl: string): void;