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,50 @@
1
+ function allowedEvidenceUrl(value) {
2
+ const url = URL.canParse(value) ? new URL(value) : undefined;
3
+ if (url?.protocol !== 'https:' || url.username || url.password || url.port)
4
+ return undefined;
5
+ const githubPath = url.pathname.toLowerCase();
6
+ if (url.hostname === 'github.com' &&
7
+ (githubPath === '/rudedoggg/corbot' || githubPath.startsWith('/rudedoggg/corbot/'))) {
8
+ return url.href;
9
+ }
10
+ if (url.hostname === 'claude.ai' && url.pathname.startsWith('/artifact/')) {
11
+ return url.href;
12
+ }
13
+ return undefined;
14
+ }
15
+ function toEvidence(entry) {
16
+ if (typeof entry === 'string') {
17
+ const url = allowedEvidenceUrl(entry);
18
+ return url ? { kind: 'link', ref: entry, url } : { kind: 'reference', ref: entry };
19
+ }
20
+ const { kind, ref } = entry;
21
+ const url = entry.url === undefined ? undefined : allowedEvidenceUrl(entry.url);
22
+ return url ? { kind, ref, url } : { kind, ref };
23
+ }
24
+ /** Adapts a row for display. The record ID provides provenance only. */
25
+ export function toDecisionCard(record) {
26
+ const { cardId, title, askedAt, decidedAt, choice, verbatim, recordId } = record;
27
+ const card = {
28
+ id: cardId,
29
+ title,
30
+ askedAt,
31
+ recordId,
32
+ options: (record.options ?? []).map((option) => typeof option === 'string'
33
+ ? { id: option, label: option }
34
+ : { id: option.id, label: option.label }),
35
+ evidence: (record.evidence ?? []).map(toEvidence),
36
+ };
37
+ if (decidedAt !== undefined) {
38
+ card.decidedAt = decidedAt;
39
+ if (choice !== undefined)
40
+ card.choice = choice;
41
+ if (verbatim !== undefined)
42
+ card.note = verbatim;
43
+ const latest = record.receipts?.find(({ receipt }) => receipt.recordId === recordId);
44
+ if (latest !== undefined) {
45
+ card.executed = { receiptId: latest.id, executedAt: latest.receipt.executedAt, outcome: latest.receipt.outcome };
46
+ }
47
+ }
48
+ return card;
49
+ }
50
+ //# sourceMappingURL=decision-card.js.map
@@ -0,0 +1,24 @@
1
+ import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { z } from 'zod';
3
+ declare const recordSchema: z.ZodObject<{
4
+ cardId: z.ZodString;
5
+ decidedAt: z.ZodISODateTime;
6
+ decidedBy: z.ZodObject<{
7
+ kind: z.ZodEnum<{
8
+ agent: "agent";
9
+ human: "human";
10
+ }>;
11
+ name: z.ZodString;
12
+ }, z.core.$strip>;
13
+ verbatim: z.ZodString;
14
+ options: z.ZodArray<z.ZodString>;
15
+ rationale: z.ZodString;
16
+ evidence: z.ZodArray<z.ZodString>;
17
+ notified: z.ZodArray<z.ZodString>;
18
+ }, z.core.$strip>;
19
+ export type DecisionLedgerRecord = z.infer<typeof recordSchema>;
20
+ export declare function isDecisionLedgerRecord(value: unknown): value is DecisionLedgerRecord;
21
+ export declare function callMemory(client: Pick<Client, 'callTool'>, name: 'recall' | 'remember', args: Record<string, unknown>): Promise<unknown>;
22
+ /** Records provenance for display. A memory receipt cannot establish human approval. */
23
+ export declare function createDecisionLedgerWriter(client: Pick<Client, 'callTool'>): (record: DecisionLedgerRecord) => Promise<string>;
24
+ export {};
@@ -0,0 +1,59 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ const recordSchema = z.object({
4
+ cardId: z.string().regex(/^[a-z0-9._:-]{1,64}$/),
5
+ decidedAt: z.iso.datetime({ offset: true }),
6
+ decidedBy: z.object({ kind: z.enum(['human', 'agent']), name: z.string().min(1) }),
7
+ verbatim: z.string().min(1),
8
+ options: z.array(z.string()),
9
+ rationale: z.string(),
10
+ evidence: z.array(z.string()),
11
+ notified: z.array(z.string()),
12
+ });
13
+ export function isDecisionLedgerRecord(value) {
14
+ return recordSchema.safeParse(value).success;
15
+ }
16
+ const envelope = z.object({ success: z.literal(true), data: z.unknown() });
17
+ const receipt = z.object({ id: z.string().min(1) });
18
+ const matches = z.object({ memories: z.array(receipt) });
19
+ export async function callMemory(client, name, args) {
20
+ const response = await client.callTool({ name, arguments: args });
21
+ const parsed = z.object({
22
+ isError: z.literal(false).optional(),
23
+ content: z.tuple([z.object({ type: z.literal('text'), text: z.string() })]).rest(z.unknown()),
24
+ }).parse(response);
25
+ return envelope.parse(JSON.parse(parsed.content[0].text)).data;
26
+ }
27
+ /** Records provenance for display. A memory receipt cannot establish human approval. */
28
+ export function createDecisionLedgerWriter(client) {
29
+ const inFlight = new Map();
30
+ return async (input) => {
31
+ const record = recordSchema.parse(input);
32
+ const verbatimHash = createHash('sha256').update(record.verbatim).digest('hex');
33
+ const key = createHash('sha256')
34
+ .update(JSON.stringify([record.cardId, record.decidedAt, verbatimHash]))
35
+ .digest('hex');
36
+ const pending = inFlight.get(key);
37
+ if (pending)
38
+ return pending;
39
+ const tags = ['john-word', 'decision-ledger', record.cardId, key];
40
+ const write = (async () => {
41
+ const { memories } = matches.parse(await callMemory(client, 'recall', {
42
+ query: 'decision-ledger', type: 'event', tags, orderBy: 'newest', limit: 1,
43
+ }));
44
+ if (memories[0])
45
+ return memories[0].id;
46
+ return receipt.parse(await callMemory(client, 'remember', {
47
+ content: JSON.stringify(record), type: 'event', tags,
48
+ })).id;
49
+ })();
50
+ inFlight.set(key, write);
51
+ try {
52
+ return await write;
53
+ }
54
+ finally {
55
+ inFlight.delete(key);
56
+ }
57
+ };
58
+ }
59
+ //# sourceMappingURL=decision-ledger.js.map
@@ -0,0 +1,33 @@
1
+ import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { z } from 'zod';
3
+ declare const receiptSchema: z.ZodObject<{
4
+ recordId: z.ZodString;
5
+ executedAt: z.ZodISODateTime;
6
+ executedBy: z.ZodObject<{
7
+ kind: z.ZodEnum<{
8
+ agent: "agent";
9
+ human: "human";
10
+ }>;
11
+ name: z.ZodString;
12
+ }, z.core.$strip>;
13
+ action: z.ZodString;
14
+ outcome: z.ZodEnum<{
15
+ failed: "failed";
16
+ partial: "partial";
17
+ done: "done";
18
+ }>;
19
+ evidence: z.ZodArray<z.ZodString>;
20
+ }, z.core.$strip>;
21
+ export type DecisionReceipt = z.infer<typeof receiptSchema>;
22
+ export interface ListedDecisionReceipt {
23
+ id: string;
24
+ receipt: DecisionReceipt;
25
+ }
26
+ export interface DecisionReceiptLog {
27
+ write: (receipt: DecisionReceipt) => Promise<string>;
28
+ list: (recordId: string, limit?: number) => Promise<ListedDecisionReceipt[]>;
29
+ }
30
+ export declare function isDecisionReceipt(value: unknown): value is DecisionReceipt;
31
+ /** Execution receipts linked to a ledger record id. A receipt reports what was done; it is not approval. */
32
+ export declare function createDecisionReceiptLog(client: Pick<Client, 'callTool'>): DecisionReceiptLog;
33
+ export {};
@@ -0,0 +1,72 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { callMemory } from './decision-ledger.js';
4
+ const RECEIPT_TAG = 'decision-receipt';
5
+ const receiptSchema = z.object({
6
+ /** The memory id the decision ledger writer returned for John's recorded words. */
7
+ recordId: z.string().regex(/^[a-z0-9._:-]{1,64}$/),
8
+ executedAt: z.iso.datetime({ offset: true }),
9
+ executedBy: z.object({ kind: z.enum(['human', 'agent']), name: z.string().min(1) }),
10
+ action: z.string().min(1),
11
+ outcome: z.enum(['done', 'partial', 'failed']),
12
+ evidence: z.array(z.string()),
13
+ });
14
+ export function isDecisionReceipt(value) {
15
+ return receiptSchema.safeParse(value).success;
16
+ }
17
+ const written = z.object({ id: z.string().min(1) });
18
+ const found = z.object({ memories: z.array(z.object({ id: z.string().min(1), content: z.string() })) });
19
+ function parseReceipt(content) {
20
+ try {
21
+ const parsed = receiptSchema.safeParse(JSON.parse(content));
22
+ return parsed.success ? parsed.data : undefined;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ /** Execution receipts linked to a ledger record id. A receipt reports what was done; it is not approval. */
29
+ export function createDecisionReceiptLog(client) {
30
+ const inFlight = new Map();
31
+ const write = async (input) => {
32
+ const receipt = receiptSchema.parse(input);
33
+ const key = createHash('sha256')
34
+ .update(JSON.stringify([receipt.recordId, receipt.executedAt, receipt.action]))
35
+ .digest('hex');
36
+ const pending = inFlight.get(key);
37
+ if (pending)
38
+ return pending;
39
+ const tags = [RECEIPT_TAG, receipt.recordId, key];
40
+ const attempt = (async () => {
41
+ const { memories } = found.parse(await callMemory(client, 'recall', {
42
+ query: RECEIPT_TAG, type: 'event', tags, orderBy: 'newest', limit: 1,
43
+ }));
44
+ if (memories[0])
45
+ return memories[0].id;
46
+ return written.parse(await callMemory(client, 'remember', {
47
+ content: JSON.stringify(receipt), type: 'event', tags,
48
+ })).id;
49
+ })();
50
+ inFlight.set(key, attempt);
51
+ try {
52
+ return await attempt;
53
+ }
54
+ finally {
55
+ inFlight.delete(key);
56
+ }
57
+ };
58
+ const list = async (recordId, limit = 20) => {
59
+ const { memories } = found.parse(await callMemory(client, 'recall', {
60
+ query: RECEIPT_TAG, type: 'event', tags: [RECEIPT_TAG, recordId], orderBy: 'newest', limit,
61
+ }));
62
+ const listed = [];
63
+ for (const memory of memories) {
64
+ const receipt = parseReceipt(memory.content);
65
+ if (receipt?.recordId === recordId)
66
+ listed.push({ id: memory.id, receipt });
67
+ }
68
+ return listed;
69
+ };
70
+ return { write, list };
71
+ }
72
+ //# sourceMappingURL=decision-receipt.js.map
@@ -1,3 +1,5 @@
1
+ import { z } from 'zod';
2
+ import { aisPost } from './ais-http.js';
1
3
  /**
2
4
  * Device-flow poll loop — extracted for testability.
3
5
  *
@@ -18,13 +20,15 @@ export declare class DeviceFlowRestartedError extends Error {
18
20
  readonly isDeviceFlowRestarted = true;
19
21
  constructor(newVerificationUri: string, newUserCode: string);
20
22
  }
21
- export interface PollTokenResponse {
22
- access_token?: string;
23
- refresh_token?: string;
24
- expires_in?: number;
25
- error?: string;
26
- pending_reason?: string;
27
- }
23
+ declare const pollTokenResponse: z.ZodObject<{
24
+ access_token: z.ZodOptional<z.ZodString>;
25
+ refresh_token: z.ZodOptional<z.ZodString>;
26
+ expires_in: z.ZodOptional<z.ZodNumber>;
27
+ error: z.ZodOptional<z.ZodString>;
28
+ pending_reason: z.ZodOptional<z.ZodString>;
29
+ }, z.core.$loose>;
30
+ export type PollTokenResponse = z.infer<typeof pollTokenResponse>;
31
+ export declare const DEVICE_DENIED_MESSAGE = "This bond request was declined. Call any memory tool again to get a new bond link.";
28
32
  export interface DeviceFlowHandle {
29
33
  device_code: string;
30
34
  verification_uri_complete: string;
@@ -33,6 +37,8 @@ export interface DeviceFlowHandle {
33
37
  export interface PollLoopDeps {
34
38
  /** Calls the AIS token endpoint and returns the parsed response. */
35
39
  pollOnce: (deviceCode: string) => Promise<PollTokenResponse>;
40
+ /** Overrides the owner access-token success check for another credential type. */
41
+ accept?: (response: PollTokenResponse) => boolean;
36
42
  /** Initiates a fresh device flow and returns the new handle. */
37
43
  startNewFlow: () => Promise<DeviceFlowHandle>;
38
44
  /** Writes a line to stderr (the existing `stderr` helper in index.ts). */
@@ -50,3 +56,6 @@ export interface PollLoopDeps {
50
56
  * Throws Error on access_denied or hard deadline.
51
57
  */
52
58
  export declare function runPollLoop(handle: DeviceFlowHandle, deps: PollLoopDeps): Promise<PollTokenResponse>;
59
+ /** Normalize OAuth-style HTTP 400 bodies for the shared poll state machine. */
60
+ export declare function pollDeviceGrant(code: string, post?: typeof aisPost): Promise<PollTokenResponse>;
61
+ export {};
@@ -1,3 +1,6 @@
1
+ import { z } from 'zod';
2
+ import { AisHttpError } from './ais-http-error.js';
3
+ import { aisPost } from './ais-http.js';
1
4
  /**
2
5
  * Device-flow poll loop — extracted for testability.
3
6
  *
@@ -25,6 +28,14 @@ export class DeviceFlowRestartedError extends Error {
25
28
  this.name = 'DeviceFlowRestartedError';
26
29
  }
27
30
  }
31
+ const pollTokenResponse = z.looseObject({
32
+ access_token: z.string().optional(),
33
+ refresh_token: z.string().optional(),
34
+ expires_in: z.number().optional(),
35
+ error: z.string().optional(),
36
+ pending_reason: z.string().optional(),
37
+ });
38
+ export const DEVICE_DENIED_MESSAGE = 'This bond request was declined. Call any memory tool again to get a new bond link.';
28
39
  /**
29
40
  * Poll the AIS token endpoint until the device is approved, expired, or denied.
30
41
  *
@@ -33,14 +44,14 @@ export class DeviceFlowRestartedError extends Error {
33
44
  * Throws Error on access_denied or hard deadline.
34
45
  */
35
46
  export async function runPollLoop(handle, deps) {
36
- const { pollOnce, startNewFlow, emitStderr, nowMs = () => Date.now(), pollIntervalMs = 5_000, } = deps;
47
+ const { pollOnce, accept = (response) => Boolean(response.access_token), startNewFlow, emitStderr, nowMs = () => Date.now(), pollIntervalMs = 5_000, } = deps;
37
48
  const deadline = nowMs() + 30 * 60 * 1000; // 30 min
38
49
  let lastHeartbeatAt = 0;
39
50
  const device_code = handle.device_code;
40
51
  while (nowMs() < deadline) {
41
52
  await new Promise((r) => setTimeout(r, pollIntervalMs));
42
53
  const resp = await pollOnce(device_code);
43
- if (resp.access_token) {
54
+ if (accept(resp)) {
44
55
  return resp;
45
56
  }
46
57
  if (resp.error === 'authorization_pending') {
@@ -67,11 +78,28 @@ export async function runPollLoop(handle, deps) {
67
78
  throw new DeviceFlowRestartedError(newFlow.verification_uri_complete, newFlow.user_code);
68
79
  }
69
80
  if (resp.error === 'access_denied') {
70
- throw new Error('Authorization denied by user');
81
+ throw new Error(DEVICE_DENIED_MESSAGE);
71
82
  }
72
83
  // Unknown error — surface it and stop
73
84
  throw new Error(`Unexpected poll response: ${resp.error ?? '(no error field)'}`);
74
85
  }
75
86
  throw new Error('Authentication timed out');
76
87
  }
88
+ /** Normalize OAuth-style HTTP 400 bodies for the shared poll state machine. */
89
+ export async function pollDeviceGrant(code, post = aisPost) {
90
+ try {
91
+ return pollTokenResponse.parse(await post('/v1/oauth/token', {
92
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
93
+ device_code: code,
94
+ }));
95
+ }
96
+ catch (error) {
97
+ if (error instanceof AisHttpError) {
98
+ const parsed = pollTokenResponse.safeParse(error.body);
99
+ if (parsed.success && parsed.data.error !== undefined)
100
+ return parsed.data;
101
+ }
102
+ throw error;
103
+ }
104
+ }
77
105
  //# sourceMappingURL=device-poll.js.map
@@ -0,0 +1,9 @@
1
+ type HandoffDocFields = {
2
+ docPath?: string;
3
+ docBytes?: number;
4
+ docSha256?: string;
5
+ docWarning?: string;
6
+ };
7
+ export declare function handoffDocFields(docPath: string | undefined): Promise<HandoffDocFields>;
8
+ export declare function withHandoffDocWarning(result: unknown): Promise<unknown>;
9
+ export {};
@@ -0,0 +1,53 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { open, stat } from 'node:fs/promises';
4
+ const DOC_WARNING = 'Handoff document is missing or unavailable locally.';
5
+ export async function handoffDocFields(docPath) {
6
+ if (docPath === undefined)
7
+ return {};
8
+ try {
9
+ // Check and read the same open file. Nonblocking open also handles FIFOs.
10
+ const file = await open(docPath, constants.O_RDONLY | constants.O_NONBLOCK);
11
+ try {
12
+ if (!(await file.stat()).isFile())
13
+ return { docWarning: DOC_WARNING };
14
+ const hash = createHash('sha256');
15
+ const buffer = Buffer.alloc(64 * 1024);
16
+ let docBytes = 0;
17
+ for (;;) {
18
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, null);
19
+ if (bytesRead === 0)
20
+ break;
21
+ hash.update(buffer.subarray(0, bytesRead));
22
+ docBytes += bytesRead;
23
+ }
24
+ return { docPath, docBytes, docSha256: hash.digest('hex') };
25
+ }
26
+ finally {
27
+ await file.close();
28
+ }
29
+ }
30
+ catch {
31
+ return { docWarning: DOC_WARNING };
32
+ }
33
+ }
34
+ function isRecord(value) {
35
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
36
+ }
37
+ export async function withHandoffDocWarning(result) {
38
+ if (!isRecord(result) || !isRecord(result.data))
39
+ return result;
40
+ const { lastHandoff } = result.data;
41
+ if (!isRecord(lastHandoff) || typeof lastHandoff.docPath !== 'string')
42
+ return result;
43
+ // Full context only needs to check the path supplied by the server.
44
+ try {
45
+ if ((await stat(lastHandoff.docPath)).isFile())
46
+ return result;
47
+ }
48
+ catch {
49
+ // Keep the historical path and let the caller know it is unavailable here.
50
+ }
51
+ return { ...result, data: { ...result.data, lastHandoff: { ...lastHandoff, docWarning: DOC_WARNING } } };
52
+ }
53
+ //# sourceMappingURL=handoff-doc.js.map
@@ -12,6 +12,7 @@
12
12
  * which AIS entrypoint served it.
13
13
  */
14
14
  import { isAuthErrorResult } from './auth-staleness.js';
15
+ import { setInboxReadStage, withInboxReadDeadline } from './request-timeout.js';
15
16
  /** Mirrors AIS core/inbox/types.ts MAX_ACK_IDS. A page never exceeds it (MAX_PAGE_SIZE === MAX_ACK_IDS), so no chunking is needed. */
16
17
  const MAX_ACK_IDS = 100;
17
18
  function isInboxMessageArray(value) {
@@ -44,31 +45,37 @@ function isAckResponse(value) {
44
45
  * existing re-auth-and-retry loop (`isAuthErrorResult`) still fires.
45
46
  */
46
47
  export async function readInboxAndMaybeAck(args, getPage, ackMessages) {
47
- const page = await getPage();
48
- if (isAuthErrorResult(page))
49
- return page;
50
- if (!isInboxListResponse(page)) {
51
- // AIS's response envelope changed shape underneath us — surface it
52
- // verbatim rather than guessing, same as every other tool's `result`.
53
- return page;
54
- }
55
- const { messages, nextCursor, hasMore } = page.data;
56
- const result = { messages, nextCursor };
57
- if (args.ack && messages.length > 0) {
58
- const ids = messages.slice(0, MAX_ACK_IDS).map((m) => m.messageId);
59
- const ackResult = await ackMessages(ids);
60
- if (isAuthErrorResult(ackResult))
61
- return ackResult;
62
- result.acked = isAckResponse(ackResult) ? ackResult.data.acked : ids;
63
- }
64
- else if (args.ack) {
65
- result.acked = [];
66
- }
67
- // Exact only when this read reached the end of the unread stream — see
68
- // handleInboxRead's identical comment in agent-inbox-handlers.ts.
69
- if (args.unreadOnly && !hasMore) {
70
- result.unreadRemaining = args.ack ? 0 : messages.length;
71
- }
72
- return { success: true, data: result };
48
+ return withInboxReadDeadline(async () => {
49
+ setInboxReadStage('read');
50
+ const page = await getPage();
51
+ setInboxReadStage('read result');
52
+ if (isAuthErrorResult(page))
53
+ return page;
54
+ if (!isInboxListResponse(page)) {
55
+ // AIS's response envelope changed shape underneath us — surface it
56
+ // verbatim rather than guessing, same as every other tool's `result`.
57
+ return page;
58
+ }
59
+ const { messages, nextCursor, hasMore } = page.data;
60
+ const result = { messages, nextCursor };
61
+ if (args.ack && messages.length > 0) {
62
+ const ids = messages.slice(0, MAX_ACK_IDS).map((m) => m.messageId);
63
+ setInboxReadStage('ack');
64
+ const ackResult = await ackMessages(ids);
65
+ setInboxReadStage('ack result');
66
+ if (isAuthErrorResult(ackResult))
67
+ return ackResult;
68
+ result.acked = isAckResponse(ackResult) ? ackResult.data.acked : ids;
69
+ }
70
+ else if (args.ack) {
71
+ result.acked = [];
72
+ }
73
+ // Exact only when this read reached the end of the unread stream — see
74
+ // handleInboxRead's identical comment in agent-inbox-handlers.ts.
75
+ if (args.unreadOnly && !hasMore) {
76
+ result.unreadRemaining = args.ack ? 0 : messages.length;
77
+ }
78
+ return { success: true, data: result };
79
+ });
73
80
  }
74
81
  //# sourceMappingURL=inbox-client.js.map