aismemory 0.8.8 → 0.8.9

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/README.md CHANGED
@@ -37,7 +37,7 @@ Add to your IDE's MCP server config:
37
37
  "mcpServers": {
38
38
  "aismemory": {
39
39
  "command": "npx",
40
- "args": ["aismemory@0.8.8"],
40
+ "args": ["aismemory@0.8.9"],
41
41
  "env": {
42
42
  "npm_config_audit": "false",
43
43
  "npm_config_fund": "false"
@@ -325,7 +325,7 @@ mint a new one.
325
325
  "mcpServers": {
326
326
  "aismemory": {
327
327
  "command": "npx",
328
- "args": ["aismemory@0.8.8"],
328
+ "args": ["aismemory@0.8.9"],
329
329
  "env": {
330
330
  "AIS_WORKSPACE_KEY": "ais_wk_...",
331
331
  "AIS_AGENT_ID": "<the agent to start with>",
@@ -131,10 +131,15 @@ async function main() {
131
131
  review,
132
132
  });
133
133
  process.stdout.write(`\n=== Sync complete ===\n`);
134
- process.stdout.write(`imported: ${result.imported}\n`);
134
+ process.stdout.write(`received: ${result.received}\n`);
135
+ process.stdout.write(`stored: ${result.imported}\n`);
136
+ process.stdout.write(`already stored: ${result.deduplicated}\n`);
137
+ process.stdout.write(`rejected: ${result.failed.length}\n`);
138
+ for (const { index, error } of result.failed) {
139
+ process.stdout.write(` - [${index}] ${error}\n`);
140
+ }
135
141
  process.stdout.write(`skippedExactDupes: ${result.skippedExactDupes}\n`);
136
142
  process.stdout.write(`skippedByUser: ${result.skippedByUser}\n`);
137
- process.stdout.write(`failed: ${result.failed.length}\n`);
138
143
  if (result.warnings.length > 0) {
139
144
  process.stdout.write(`\nwarnings:\n`);
140
145
  for (const w of result.warnings)
package/dist/cli-info.js CHANGED
@@ -37,6 +37,7 @@ export const USAGE_TEXT = [
37
37
  '',
38
38
  'Usage:',
39
39
  ' aismemory Start the MCP server on stdio',
40
+ ' aismemory bond Print the bonding link and exit',
40
41
  ' aismemory install --identity <agent-id> Write a pinned MCP config for one agent\'s session',
41
42
  ' aismemory hooks install Add the session-start and pre-compact hook to Claude Code',
42
43
  ' aismemory enable-key-auth Enroll a device key for silent sign-in',
@@ -72,6 +73,9 @@ export function resolveInfoRequest(args, version) {
72
73
  return USAGE_TEXT;
73
74
  if (first === '--version' || first === '-v')
74
75
  return `${version}\n`;
76
+ if (first === 'bond' && (args[1] === '--help' || args[1] === '-h')) {
77
+ return 'Usage: aismemory bond\n\nPrint the bonding link and exit.\n';
78
+ }
75
79
  return null;
76
80
  }
77
81
  //# sourceMappingURL=cli-info.js.map
package/dist/index.js CHANGED
@@ -294,11 +294,11 @@ class BondPendingError extends Error {
294
294
  * Wire the poll loop onto a freshly built flow. Shared by the mint path and
295
295
  * the resume path so a change to the poll/dead bookkeeping lands in one place.
296
296
  */
297
- function attachDeviceFlowPoll(flow, interval) {
297
+ function attachDeviceFlowPoll(flow, interval, reauth) {
298
298
  // flowRef points into the live flow object so auto-restart can update the
299
299
  // surfaced URL without the caller needing to restart the MCP process.
300
300
  const flowRef = flow;
301
- const poll = pollForToken(flow.device_code, interval, flow.agent_id, flow.provisional_tenant_id, flowRef);
301
+ const poll = pollForToken(flow.device_code, interval, flow.agent_id, flow.provisional_tenant_id, reauth, flowRef);
302
302
  flow.poll = poll;
303
303
  // Mark the flow dead as soon as its poll rejects so the next
304
304
  // `ensureCredentials` call starts a fresh flow. The `.catch` here is purely
@@ -342,7 +342,28 @@ function resumeDeviceFlow(saved) {
342
342
  provisional_tenant_id: saved.provisionalTenantId,
343
343
  provisional_token: saved.provisionalToken,
344
344
  dead: false,
345
- }, saved.interval ?? DEFAULT_DEVICE_POLL_INTERVAL_S);
345
+ }, saved.interval ?? DEFAULT_DEVICE_POLL_INTERVAL_S, saved.reauth ?? Boolean(loadAgentPreference()?.agentId));
346
+ }
347
+ /**
348
+ * Body for `/v1/oauth/device/authorize` (CORBOT-542808CE). When this machine
349
+ * has signed in before (a saved agent id on disk) but reached the device flow
350
+ * anyway, the sign-in expired and no device key covers it: ask for a 'reauth'
351
+ * code so approval can sign in as the existing agent instead of adding a
352
+ * duplicate. A true first run sends no mode and keeps the server's
353
+ * 'new_agent' default.
354
+ */
355
+ function deviceAuthorizeBody() {
356
+ const defaultName = `agent-${homedir().split('/').pop() ?? 'user'}`;
357
+ if (loadAgentPreference()?.agentId)
358
+ return { name: defaultName, mode: 'reauth' };
359
+ const requestedName = process.env['AIS_AGENT_NAME']?.trim();
360
+ // Match the name length limit in AIS's /device/authorize route.
361
+ const maxNameLength = 100;
362
+ const tooLong = requestedName !== undefined && requestedName.length > maxNameLength;
363
+ if (tooLong) {
364
+ stderr(`AIS_AGENT_NAME exceeds the ${maxNameLength}-character limit. Using the default agent name.`);
365
+ }
366
+ return { name: requestedName && !tooLong ? requestedName : defaultName };
346
367
  }
347
368
  /** Fallback poll interval when a resumed record predates the stored field. */
348
369
  const DEFAULT_DEVICE_POLL_INTERVAL_S = 5;
@@ -366,7 +387,8 @@ async function startDeviceFlow(priorProvisionalToken) {
366
387
  // before — so this can only reduce the number of agents, never break a
367
388
  // sign-in.
368
389
  const carriedToken = priorProvisionalToken ?? loadPendingDeviceFlow()?.provisionalToken;
369
- const authRes = (await aisPost('/v1/oauth/device/authorize', { name: `agent-${homedir().split('/').pop() ?? 'user'}` }, carriedToken));
390
+ const body = deviceAuthorizeBody();
391
+ const authRes = (await aisPost('/v1/oauth/device/authorize', body, carriedToken));
370
392
  if (!authRes.success || !authRes.data) {
371
393
  throw new Error(`Authentication failed: ${authRes.error?.message ?? 'Unknown error'}`);
372
394
  }
@@ -390,6 +412,7 @@ async function startDeviceFlow(priorProvisionalToken) {
390
412
  userCode: user_code,
391
413
  verificationUriComplete: verification_uri_complete,
392
414
  interval,
415
+ reauth: body.mode === 'reauth',
393
416
  codeExpiresAt: new Date(Date.now() + authRes.data.expires_in * 1000).toISOString(),
394
417
  });
395
418
  return attachDeviceFlowPoll({
@@ -402,9 +425,9 @@ async function startDeviceFlow(priorProvisionalToken) {
402
425
  // poll is assigned by attachDeviceFlowPoll, which captures the live flow
403
426
  // object so pollForToken can update the surfaced URL on auto-restart.
404
427
  dead: false,
405
- }, interval);
428
+ }, interval, body.mode === 'reauth');
406
429
  }
407
- async function pollForToken(device_code, interval, agent_id, provisional_tenant_id,
430
+ async function pollForToken(device_code, interval, agent_id, provisional_tenant_id, reauth,
408
431
  /** Mutable ref so auto-restart can update the surfaced URL and provisional token in ActiveDeviceFlow */
409
432
  flowRef) {
410
433
  const pollIntervalMs = Math.max(interval, 5) * 1000;
@@ -436,7 +459,8 @@ flowRef) {
436
459
  }
437
460
  },
438
461
  startNewFlow: async () => {
439
- const authRes = (await aisPost('/v1/oauth/device/authorize', { name: `agent-${homedir().split('/').pop() ?? 'user'}` }, flowRef?.provisional_token));
462
+ const body = deviceAuthorizeBody();
463
+ const authRes = (await aisPost('/v1/oauth/device/authorize', body, flowRef?.provisional_token));
440
464
  if (!authRes.success || !authRes.data) {
441
465
  throw new Error(`Re-authorization failed: ${authRes.error?.message ?? 'Unknown error'}`);
442
466
  }
@@ -467,6 +491,7 @@ flowRef) {
467
491
  userCode: authRes.data.user_code,
468
492
  verificationUriComplete: authRes.data.verification_uri_complete,
469
493
  interval: authRes.data.interval,
494
+ reauth: body.mode === 'reauth',
470
495
  codeExpiresAt: new Date(Date.now() + authRes.data.expires_in * 1000).toISOString(),
471
496
  });
472
497
  stderr('');
@@ -494,12 +519,16 @@ flowRef) {
494
519
  throw new Error('Poll loop ended without an access token');
495
520
  }
496
521
  const expiresAt = new Date(Date.now() + (pollResp.expires_in ?? 604800) * 1000).toISOString();
497
- // A completed bond names the agent confirmed by this flow, never a
498
- // machine-wide preference or the tenant's first active agent.
499
522
  const bondClaims = decodeJwtClaims(pollResp.access_token);
500
- const { agentId, tenantId } = sessionIdentity || process.env['AIS_AGENT_NAME']
523
+ if (reauth && !bondClaims.agentId) {
524
+ throw new Error('Reauthentication failed: the approved token is missing an agent id');
525
+ }
526
+ // Only the bond token's agent claim confirms an agent; the provisional flow
527
+ // agent never does (CORBOT-F456BD9D).
528
+ const approvedAgentId = bondClaims.agentId;
529
+ const { agentId, tenantId } = sessionIdentity || (!approvedAgentId && process.env['AIS_AGENT_NAME'])
501
530
  ? await resolveAgent(pollResp.access_token, agent_id, provisional_tenant_id)
502
- : { agentId: bondClaims.agentId ?? '', tenantId: bondClaims.tenantId ?? provisional_tenant_id };
531
+ : { agentId: approvedAgentId ?? '', tenantId: bondClaims.tenantId ?? provisional_tenant_id };
503
532
  const creds = {
504
533
  token: pollResp.access_token,
505
534
  agentId,
@@ -1040,6 +1069,20 @@ async function main() {
1040
1069
  return;
1041
1070
  }
1042
1071
  // Subcommand dispatch — CLI entrypoints exit before MCP server startup.
1072
+ if (process.argv[2] === 'bond') {
1073
+ if (process.argv.length > 3)
1074
+ throw new Error('Usage: aismemory bond');
1075
+ if (RUN_PASS_CONFLICTING_KEY_ENV_NAMES.some((name) => process.env[name] !== undefined) ||
1076
+ process.env['AIS_RUN_PASS_FILE'] !== undefined || hasEnrolledKey() ||
1077
+ loadAgentPreference()?.ownerUserId || loadCredentials()) {
1078
+ process.stdout.write('AIS sign-in is already configured.\n');
1079
+ return;
1080
+ }
1081
+ const flow = await startDeviceFlow();
1082
+ // The pending flow is saved. Exit after stdout flushes instead of waiting for approval.
1083
+ process.stdout.write(`${flow.verification_uri_complete}\n`, () => process.exit(0));
1084
+ return;
1085
+ }
1043
1086
  if (process.argv[2] === 'install') {
1044
1087
  (await import('./cli/install.js')).main(process.argv.slice(3));
1045
1088
  return;
@@ -1180,6 +1223,7 @@ async function main() {
1180
1223
  ...(startupPreference?.ownerUserId ? { keychainOwnerSession: true } : {}),
1181
1224
  });
1182
1225
  let activeFlow = null;
1226
+ let startingFlow = null;
1183
1227
  let freshlyBondedAgentId = null;
1184
1228
  let postAuthDone = false;
1185
1229
  let postAuthTask = null;
@@ -1265,6 +1309,17 @@ async function main() {
1265
1309
  ? { ...authenticated, agentId: toolName === 'whoami' ? freshlyBondedAgentId ?? '' : '' }
1266
1310
  : authenticated;
1267
1311
  }
1312
+ async function getDeviceFlow() {
1313
+ if (activeFlow && !activeFlow.dead)
1314
+ return activeFlow;
1315
+ startingFlow ??= startDeviceFlow(activeFlow?.provisional_token)
1316
+ .then((flow) => {
1317
+ activeFlow = flow;
1318
+ return flow;
1319
+ })
1320
+ .finally(() => { startingFlow = null; });
1321
+ return startingFlow;
1322
+ }
1268
1323
  async function acquireCredentials(softTimeoutMs = 7000) {
1269
1324
  // CORBOT-EBCB2D2B: owner terminal sign-in uses the workspace credential
1270
1325
  // in the OS keychain (not the DID key or a stale disk bearer) so
@@ -1324,24 +1379,23 @@ async function main() {
1324
1379
  if (creds && !isCredsStale(creds.expiresAt, Date.now())) {
1325
1380
  return creds;
1326
1381
  }
1327
- if (!activeFlow || activeFlow.dead) {
1328
- try {
1329
- activeFlow = await startDeviceFlow(activeFlow?.provisional_token);
1330
- }
1331
- catch (error) {
1332
- throw new Error(`${MISSING_CREDENTIAL_HELP} AIS sign-in could not start; check AIS_URL and connectivity, then retry.`, { cause: error });
1333
- }
1382
+ let flow;
1383
+ try {
1384
+ flow = await getDeviceFlow();
1385
+ }
1386
+ catch (error) {
1387
+ throw new Error(`${MISSING_CREDENTIAL_HELP} AIS sign-in could not start; check AIS_URL and connectivity, then retry.`, { cause: error });
1334
1388
  }
1335
1389
  const sentinel = Symbol('bond-pending');
1336
1390
  // poll is always set by startDeviceFlow before it returns; this guard
1337
1391
  // satisfies the type checker for the optional field.
1338
- if (!activeFlow.poll) {
1392
+ if (!flow.poll) {
1339
1393
  throw new Error('Invariant violated: activeFlow.poll is unset after startDeviceFlow');
1340
1394
  }
1341
1395
  let got;
1342
1396
  try {
1343
1397
  got = await Promise.race([
1344
- activeFlow.poll,
1398
+ flow.poll,
1345
1399
  new Promise((r) => setTimeout(() => r(sentinel), softTimeoutMs)),
1346
1400
  ]);
1347
1401
  }
@@ -1351,11 +1405,11 @@ async function main() {
1351
1405
  // Always say WHY the old flow died: a silent discard here hid three
1352
1406
  // weeks of broken cold-start bonding (CORBOT-9CE03C6E).
1353
1407
  stderr(`Device flow discarded (${err instanceof Error ? err.message : String(err)}); starting a fresh one.`);
1354
- activeFlow = await startDeviceFlow(activeFlow.provisional_token);
1355
- throw new BondPendingError(activeFlow.verification_uri_complete, activeFlow.user_code);
1408
+ const replacement = await getDeviceFlow();
1409
+ throw new BondPendingError(replacement.verification_uri_complete, replacement.user_code);
1356
1410
  }
1357
1411
  if (got === sentinel) {
1358
- throw new BondPendingError(activeFlow.verification_uri_complete, activeFlow.user_code);
1412
+ throw new BondPendingError(flow.verification_uri_complete, flow.user_code);
1359
1413
  }
1360
1414
  creds = got;
1361
1415
  // Show the agent selected by this bond on whoami in this process only. A bond does
@@ -1462,6 +1516,14 @@ async function main() {
1462
1516
  getAgentContext: () => agentContext,
1463
1517
  setAgentContext: (next) => { agentContext = next; },
1464
1518
  ensureCredentials: (toolName) => ensureCredentials(toolName),
1519
+ ensureFirstBond: async () => {
1520
+ if (creds || hasEnrolledKey())
1521
+ return;
1522
+ const pref = loadAgentPreference();
1523
+ if (pref?.agentId || pref?.ownerUserId)
1524
+ return;
1525
+ await ensureCredentials();
1526
+ },
1465
1527
  invalidateToken: () => { tokenManager.invalidate({ resetBackoff: true }); },
1466
1528
  applyMemoryRefresh,
1467
1529
  resolveAgentForLoad,
@@ -60,6 +60,8 @@ export interface OAuthCallToolContext {
60
60
  getAgentContext(): AgentContext | null;
61
61
  setAgentContext(next: AgentContext | null): void;
62
62
  ensureCredentials(toolName?: string): Promise<OAuthCredentials>;
63
+ /** Surfaces a pending bond link on first use before checking for a session pin. */
64
+ ensureFirstBond?(): Promise<void>;
63
65
  /** Drops the TokenManager's cached token and resets its backoff window. */
64
66
  invalidateToken(): void;
65
67
  applyMemoryRefresh(agentId: string, token: string): void;
package/dist/mcp/tools.js CHANGED
@@ -289,6 +289,8 @@ export function createOAuthCallToolHandler(ctx) {
289
289
  const toolStartedAt = Date.now();
290
290
  try {
291
291
  if (requiresIdentityGate(name, rawArgs)) {
292
+ if (!ctx.getSessionIdentity())
293
+ await ctx.ensureFirstBond?.();
292
294
  assertWriteIdentityConfirmed(ctx.getSessionIdentity());
293
295
  assertPinnedAgent(ctx.getSessionIdentity(), ctx.getSessionIdentity().agentId);
294
296
  }
@@ -47,6 +47,8 @@ export interface PendingDeviceFlow {
47
47
  verificationUriComplete?: string;
48
48
  /** Server-advised poll interval in seconds. */
49
49
  interval?: number;
50
+ /** Whether the saved code was issued for reauth. Older records omit this. */
51
+ reauth?: boolean;
50
52
  /** ISO timestamp at which the device code stops being redeemable. */
51
53
  codeExpiresAt?: string;
52
54
  }
@@ -83,6 +83,7 @@ export function loadPendingDeviceFlow(home = homedir(), now = Date.now()) {
83
83
  ? { verificationUriComplete: parsed.verificationUriComplete }
84
84
  : {}),
85
85
  ...(typeof parsed.interval === 'number' ? { interval: parsed.interval } : {}),
86
+ ...(typeof parsed.reauth === 'boolean' ? { reauth: parsed.reauth } : {}),
86
87
  ...(typeof parsed.codeExpiresAt === 'string' ? { codeExpiresAt: parsed.codeExpiresAt } : {}),
87
88
  };
88
89
  }
@@ -12,11 +12,12 @@ export interface BulkWriteResult {
12
12
  index: number;
13
13
  error: string;
14
14
  }>;
15
+ deduplicated?: number;
15
16
  }
16
17
  /**
17
18
  * POST a single chunk to the AIS bulk endpoint with a hard timeout.
18
- * Throws on HTTP auth errors (401/403) or AbortError; returns a result with
19
- * transient errors mapped to per-item failures for all other HTTP errors.
19
+ * Accepts reconciled HTTP 422 responses for batches with no new writes.
20
+ * Throws on other unsuccessful responses or AbortError.
20
21
  */
21
22
  export declare function postBulkChunk(agentId: string, drafts: AisMemoryDraft[], creds: AisCreds, timeoutMs?: number): Promise<BulkWriteResult>;
22
23
  /**
@@ -29,7 +30,7 @@ export declare function postSingleWrite(agentId: string, draft: AisMemoryDraft,
29
30
  * Recursively write `drafts` mapped to their original `baseIndices`.
30
31
  * On AbortError or 502/503/504, halves the chunk and retries; falls through to
31
32
  * single-write when the chunk reaches size 1.
32
- * Per-item `failed` entries from a successful bulk call are retried individually.
33
+ * Per-item failures are retried individually only for receipt-less servers.
33
34
  */
34
35
  export declare function writeWithRetry(agentId: string, drafts: AisMemoryDraft[], baseIndices: number[], creds: AisCreds, timeoutMs?: number): Promise<BulkWriteResult>;
35
36
  /**
@@ -1,5 +1,12 @@
1
+ import { z } from 'zod';
1
2
  export const BULK_CHUNK_SIZE = 25;
2
3
  export const BULK_TIMEOUT_MS = 20_000;
4
+ const bulkReceiptSchema = z.object({
5
+ received: z.number().int().nonnegative(),
6
+ stored: z.number().int().nonnegative(),
7
+ deduplicated: z.number().int().nonnegative(),
8
+ rejected: z.array(z.object({ index: z.number().int().nonnegative(), reason: z.string() })),
9
+ });
3
10
  function memoryPayload(draft) {
4
11
  return {
5
12
  content: draft.content,
@@ -10,8 +17,8 @@ function memoryPayload(draft) {
10
17
  }
11
18
  /**
12
19
  * POST a single chunk to the AIS bulk endpoint with a hard timeout.
13
- * Throws on HTTP auth errors (401/403) or AbortError; returns a result with
14
- * transient errors mapped to per-item failures for all other HTTP errors.
20
+ * Accepts reconciled HTTP 422 responses for batches with no new writes.
21
+ * Throws on other unsuccessful responses or AbortError.
15
22
  */
16
23
  export async function postBulkChunk(agentId, drafts, creds, timeoutMs = BULK_TIMEOUT_MS) {
17
24
  const controller = new AbortController();
@@ -30,12 +37,35 @@ export async function postBulkChunk(agentId, drafts, creds, timeoutMs = BULK_TIM
30
37
  const text = await res.text().catch(() => '');
31
38
  throw new Error(`AIS bulk store auth error: HTTP ${res.status}${text ? ` — ${text.slice(0, 500)}` : ''}`);
32
39
  }
40
+ // A 422 can be a completed batch or a request error. Keep the body
41
+ // available for the legacy HTTP error if there's no receipt.
42
+ const json = (res.ok ? await res.json() : res.status === 422
43
+ ? await res.clone().json().catch(() => undefined)
44
+ : undefined);
45
+ const data = json?.data;
46
+ const created = data?.created ?? [];
47
+ if (data && typeof data === 'object' &&
48
+ ('received' in data || 'stored' in data || 'deduplicated' in data || 'rejected' in data)) {
49
+ const receipt = bulkReceiptSchema.safeParse(data);
50
+ if (!receipt.success)
51
+ throw new Error('AIS bulk store returned an invalid import receipt');
52
+ const { received, stored, deduplicated, rejected } = receipt.data;
53
+ if (received !== drafts.length || stored !== created.length ||
54
+ received !== stored + deduplicated + rejected.length ||
55
+ rejected.some(({ index }) => index >= received)) {
56
+ throw new Error('AIS bulk store returned an inconsistent import receipt');
57
+ }
58
+ return {
59
+ created,
60
+ failed: rejected.map(({ index, reason }) => ({ index, error: reason })),
61
+ deduplicated,
62
+ };
63
+ }
33
64
  if (!res.ok) {
34
65
  const text = await res.text().catch(() => '');
35
66
  throw new Error(`AIS bulk store failed: HTTP ${res.status} ${res.statusText}${text ? ` — ${text.slice(0, 500)}` : ''}`);
36
67
  }
37
- const json = (await res.json());
38
- return { created: json.data?.created ?? [], failed: json.data?.failed ?? [] };
68
+ return { created, failed: data?.failed ?? [] };
39
69
  }
40
70
  finally {
41
71
  clearTimeout(timer);
@@ -87,7 +117,7 @@ export async function postSingleWrite(agentId, draft, originalIndex, creds, time
87
117
  * Recursively write `drafts` mapped to their original `baseIndices`.
88
118
  * On AbortError or 502/503/504, halves the chunk and retries; falls through to
89
119
  * single-write when the chunk reaches size 1.
90
- * Per-item `failed` entries from a successful bulk call are retried individually.
120
+ * Per-item failures are retried individually only for receipt-less servers.
91
121
  */
92
122
  export async function writeWithRetry(agentId, drafts, baseIndices, creds, timeoutMs = BULK_TIMEOUT_MS) {
93
123
  if (drafts.length === 0)
@@ -100,6 +130,7 @@ export async function writeWithRetry(agentId, drafts, baseIndices, creds, timeou
100
130
  chunkResult = await postBulkChunk(agentId, drafts, creds, timeoutMs);
101
131
  // Re-map chunk-local indices back to global.
102
132
  chunkResult = {
133
+ ...chunkResult,
103
134
  created: chunkResult.created.map((c) => ({ index: baseIndices[c.index], id: c.id })),
104
135
  failed: chunkResult.failed.map((f) => ({ index: baseIndices[f.index], error: f.error })),
105
136
  };
@@ -117,9 +148,13 @@ export async function writeWithRetry(agentId, drafts, baseIndices, creds, timeou
117
148
  writeWithRetry(agentId, drafts.slice(0, half), baseIndices.slice(0, half), creds, timeoutMs),
118
149
  writeWithRetry(agentId, drafts.slice(half), baseIndices.slice(half), creds, timeoutMs),
119
150
  ]);
120
- return { created: [...left.created, ...right.created], failed: [...left.failed, ...right.failed] };
151
+ return {
152
+ created: [...left.created, ...right.created],
153
+ failed: [...left.failed, ...right.failed],
154
+ deduplicated: (left.deduplicated ?? 0) + (right.deduplicated ?? 0),
155
+ };
121
156
  }
122
- if (chunkResult.failed.length === 0)
157
+ if (chunkResult.deduplicated !== undefined || chunkResult.failed.length === 0)
123
158
  return chunkResult;
124
159
  // Retry per-item failures individually.
125
160
  const retried = await Promise.all(chunkResult.failed.map((f) => {
@@ -141,14 +176,16 @@ export async function writeWithRetry(agentId, drafts, baseIndices, creds, timeou
141
176
  export async function bulkStoreViaAis(agentId, drafts, creds) {
142
177
  const allCreated = [];
143
178
  const allFailed = [];
179
+ let deduplicated = 0;
144
180
  for (let start = 0; start < drafts.length; start += BULK_CHUNK_SIZE) {
145
181
  const chunk = drafts.slice(start, start + BULK_CHUNK_SIZE);
146
182
  const baseIndices = Array.from({ length: chunk.length }, (_, i) => start + i);
147
183
  const result = await writeWithRetry(agentId, chunk, baseIndices, creds);
148
184
  allCreated.push(...result.created);
149
185
  allFailed.push(...result.failed);
186
+ deduplicated += result.deduplicated ?? 0;
150
187
  }
151
- return { created: allCreated, failed: allFailed };
188
+ return { created: allCreated, failed: allFailed, deduplicated };
152
189
  }
153
190
  /**
154
191
  * Single-write-only mode: bypasses bulk endpoint entirely.
@@ -12,6 +12,7 @@ export interface BulkStoreResult {
12
12
  index: number;
13
13
  error: string;
14
14
  }>;
15
+ deduplicated?: number;
15
16
  }
16
17
  export type BulkStoreFn = (drafts: AisMemoryDraft[]) => Promise<BulkStoreResult>;
17
18
  export type ReviewFn = (drafts: AisMemoryDraft[]) => Promise<AisMemoryDraft[]>;
@@ -43,7 +43,9 @@ export async function runIngestion(options) {
43
43
  if (approved.length === 0) {
44
44
  ledger.recordSync(agentId, adapter.id, scopeKey);
45
45
  return {
46
+ received: 0,
46
47
  imported: 0,
48
+ deduplicated: 0,
47
49
  skippedExactDupes,
48
50
  skippedByUser,
49
51
  warnings: parsed.warnings,
@@ -53,7 +55,7 @@ export async function runIngestion(options) {
53
55
  }
54
56
  // Split approved drafts into chunks to stay within AIS bulk limit.
55
57
  const storeResult = await chunkedBulkStore(bulkStore, approved);
56
- // Advance trust only on a clean bulk store — partial failures must not
58
+ // Already-stored rows are successful. Partial failures must not
57
59
  // increment syncCount toward auto-commit.
58
60
  if (storeResult.failed.length === 0) {
59
61
  ledger.recordSync(agentId, adapter.id, scopeKey);
@@ -71,7 +73,9 @@ export async function runIngestion(options) {
71
73
  mirrorWarnings.push(`local mirror append failed: ${msg}`);
72
74
  }
73
75
  return {
76
+ received: approved.length,
74
77
  imported: storeResult.created.length,
78
+ deduplicated: storeResult.deduplicated ?? 0,
75
79
  skippedExactDupes,
76
80
  skippedByUser,
77
81
  warnings: [...parsed.warnings, ...mirrorWarnings],
@@ -91,6 +95,7 @@ async function chunkedBulkStore(fn, drafts) {
91
95
  for (let offset = 0; offset < drafts.length; offset += BULK_BATCH_SIZE) {
92
96
  const chunk = drafts.slice(offset, offset + BULK_BATCH_SIZE);
93
97
  const result = await fn(chunk);
98
+ aggregated.deduplicated = (aggregated.deduplicated ?? 0) + (result.deduplicated ?? 0);
94
99
  for (const c of result.created) {
95
100
  aggregated.created.push({ index: c.index + offset, id: c.id });
96
101
  }
@@ -29,7 +29,9 @@ export interface ImportProvenance {
29
29
  sourcePrompt: string;
30
30
  }
31
31
  export interface SyncResult {
32
+ received: number;
32
33
  imported: number;
34
+ deduplicated: number;
33
35
  skippedExactDupes: number;
34
36
  skippedByUser: number;
35
37
  warnings: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aismemory",
3
- "version": "0.8.8",
3
+ "version": "0.8.9",
4
4
  "description": "Persistent memory for AI agents. MCP server that connects to Agent Identity Service.",
5
5
  "mcpName": "ai.agentsandswarms/ais-memory",
6
6
  "type": "module",