aismemory 0.8.8 → 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 (68) 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 +13 -5
  20. package/dist/cli-info.d.ts +1 -0
  21. package/dist/cli-info.js +6 -0
  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 +298 -71
  34. package/dist/mcp/tools.d.ts +5 -0
  35. package/dist/mcp/tools.js +121 -31
  36. package/dist/operating-layer-read.d.ts +38 -0
  37. package/dist/operating-layer-read.js +164 -0
  38. package/dist/pending-device-flow.d.ts +2 -0
  39. package/dist/pending-device-flow.js +1 -0
  40. package/dist/pipeline/bulk-store.d.ts +4 -3
  41. package/dist/pipeline/bulk-store.js +45 -8
  42. package/dist/pipeline/ingestion.d.ts +1 -0
  43. package/dist/pipeline/ingestion.js +6 -1
  44. package/dist/pipeline/types.d.ts +4 -0
  45. package/dist/recall-warning.d.ts +14 -0
  46. package/dist/recall-warning.js +36 -0
  47. package/dist/request-timeout.d.ts +27 -2
  48. package/dist/request-timeout.js +92 -2
  49. package/dist/run-pass-mode.js +34 -16
  50. package/dist/session-identity.js +3 -1
  51. package/dist/session-start.d.ts +13 -3
  52. package/dist/session-start.js +53 -10
  53. package/dist/skill-fetch.d.ts +30 -0
  54. package/dist/skill-fetch.js +88 -0
  55. package/dist/slack-tools.d.ts +44 -0
  56. package/dist/slack-tools.js +156 -0
  57. package/dist/sources/local-claude.js +16 -2
  58. package/dist/sources/types.d.ts +2 -0
  59. package/dist/startup-identity.d.ts +4 -0
  60. package/dist/startup-identity.js +2 -0
  61. package/dist/tool-args.d.ts +12 -1
  62. package/dist/tool-args.js +15 -0
  63. package/dist/tool-scope-filter.d.ts +29 -0
  64. package/dist/tool-scope-filter.js +123 -0
  65. package/dist/version-check.d.ts +30 -3
  66. package/dist/version-check.js +59 -4
  67. package/dist/workspace-key-mode.js +36 -22
  68. package/package.json +4 -3
@@ -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
  }
@@ -27,9 +27,13 @@ export interface ImportProvenance {
27
27
  importedBy: string;
28
28
  sourceScope: SyncScope;
29
29
  sourcePrompt: string;
30
+ /** Canonical Claude project directory this memory was read from. */
31
+ sourceProject?: string;
30
32
  }
31
33
  export interface SyncResult {
34
+ received: number;
32
35
  imported: number;
36
+ deduplicated: number;
33
37
  skippedExactDupes: number;
34
38
  skippedByUser: number;
35
39
  warnings: string[];
@@ -0,0 +1,14 @@
1
+ /**
2
+ * CORBOT-1A5E2E16: when AIS full-text search timed out, recall fused the
3
+ * remaining streams. The REST envelope says so (`data.warnings`, or on older
4
+ * servers `data.queryMetadata.ftsTimedOut`); this puts that warning in front
5
+ * of the agent as the first text item, before the result JSON.
6
+ */
7
+ export declare const FTS_DEGRADED_WARNING: string;
8
+ /** Degraded-search warnings carried by a recall REST envelope. Empty when healthy. */
9
+ export declare function recallWarnings(toolName: string, result: unknown): string[];
10
+ /** Content items for a successful tool call: any recall warning first, then the JSON text. */
11
+ export declare function toolResultContent(toolName: string, result: unknown, text: string): Array<{
12
+ type: 'text';
13
+ text: string;
14
+ }>;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * CORBOT-1A5E2E16: when AIS full-text search timed out, recall fused the
3
+ * remaining streams. The REST envelope says so (`data.warnings`, or on older
4
+ * servers `data.queryMetadata.ftsTimedOut`); this puts that warning in front
5
+ * of the agent as the first text item, before the result JSON.
6
+ */
7
+ export const FTS_DEGRADED_WARNING = 'Search degraded: full-text search timed out; results come from the remaining searches ' +
8
+ 'and may miss exact-word matches. Retry once with a shorter query or a tag filter before ' +
9
+ 'concluding a memory does not exist.';
10
+ // The `in` check proves `key` exists; TS cannot narrow a computed key, hence the cast.
11
+ function field(value, key) {
12
+ return typeof value === 'object' && value !== null && key in value
13
+ ? value[key]
14
+ : undefined;
15
+ }
16
+ /** Degraded-search warnings carried by a recall REST envelope. Empty when healthy. */
17
+ export function recallWarnings(toolName, result) {
18
+ if (toolName !== 'recall')
19
+ return [];
20
+ const data = field(result, 'data');
21
+ const warnings = field(data, 'warnings');
22
+ // Only our own fixed sentence is lifted out in front of the JSON; any other server string
23
+ // stays inside the result JSON, so a future server field cannot open an unfenced channel.
24
+ if (Array.isArray(warnings) && warnings.some((w) => w === FTS_DEGRADED_WARNING)) {
25
+ return [FTS_DEGRADED_WARNING];
26
+ }
27
+ return field(field(data, 'queryMetadata'), 'ftsTimedOut') === true ? [FTS_DEGRADED_WARNING] : [];
28
+ }
29
+ /** Content items for a successful tool call: any recall warning first, then the JSON text. */
30
+ export function toolResultContent(toolName, result, text) {
31
+ return [
32
+ ...recallWarnings(toolName, result).map((warning) => ({ type: 'text', text: warning })),
33
+ { type: 'text', text },
34
+ ];
35
+ }
36
+ //# sourceMappingURL=recall-warning.js.map
@@ -4,8 +4,15 @@
4
4
  * with a clear error instead of hanging the agent process for tens of
5
5
  * minutes — that hang previously froze an entire floor session for 6 hours.
6
6
  */
7
- /** Default timeout for an AIS request, in milliseconds. */
8
- export declare const DEFAULT_AIS_REQUEST_TIMEOUT_MS = 20000;
7
+ /**
8
+ * Default timeout for an AIS request, in milliseconds (CORBOT-E991E195).
9
+ * Measured 2026-11-30 from Railway edge HTTP logs (totalDuration) for
10
+ * successful POST /v1/agents/:id/memory in prod: n=87 over 04:53-05:34Z,
11
+ * p50 1689ms, p95 2269ms, p99 5830ms (also the max). Set to about p99 x 1.5,
12
+ * rounded up. The slowest read in the same window was GET full-context at
13
+ * 2500ms. Report: reports/ais-memory-write-latency/2026-11-30-CORBOT-E991E195.md
14
+ */
15
+ export declare const DEFAULT_AIS_REQUEST_TIMEOUT_MS = 9000;
9
16
  /**
10
17
  * Resolve the AIS request timeout from AIS_MCP_REQUEST_TIMEOUT_MS. Falls back
11
18
  * to the default for anything unset, blank, non-numeric, or non-positive — a
@@ -24,3 +31,21 @@ export declare class AisRequestTimeoutError extends Error {
24
31
  * may-have-landed note. Every other error passes through unchanged.
25
32
  */
26
33
  export declare function toAisRequestError(err: unknown, path: string, timeoutMs: number, method?: string): unknown;
34
+ /** Update diagnostics and refuse to start another stage after the budget expires. */
35
+ export declare function setInboxReadStage(stage: string): void;
36
+ /** Start a fresh request budget after the pass lock. Keep operation deadlines intact. */
37
+ export declare function startAisRequestTimeout(signal?: AbortSignal | null): AbortSignal;
38
+ /** Inbox transports share the operation signal; other tools retain their request timeout. */
39
+ export declare function aisRequestSignal(path: string, timeoutMs: number, method?: string): AbortSignal;
40
+ /**
41
+ * Credential acquisition can start session-owned device polling and renewal.
42
+ * Keep those background tasks outside this call's context; the caller's
43
+ * deadline still bounds its await, and its next stage refuses late results.
44
+ */
45
+ export declare function withoutInboxReadDeadline<T>(operation: () => Promise<T>): Promise<T>;
46
+ /**
47
+ * Nesting (read/ack inside the MCP handler) reuses the same absolute deadline.
48
+ * A single timer also bounds body readers or credential callbacks that ignore
49
+ * abort. The async context keeps concurrent tool calls' budgets independent.
50
+ */
51
+ export declare function withInboxReadDeadline<T>(operation: () => Promise<T>, toolName?: string): Promise<T>;
@@ -4,8 +4,16 @@
4
4
  * with a clear error instead of hanging the agent process for tens of
5
5
  * minutes — that hang previously froze an entire floor session for 6 hours.
6
6
  */
7
- /** Default timeout for an AIS request, in milliseconds. */
8
- export const DEFAULT_AIS_REQUEST_TIMEOUT_MS = 20_000;
7
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
+ /**
9
+ * Default timeout for an AIS request, in milliseconds (CORBOT-E991E195).
10
+ * Measured 2026-11-30 from Railway edge HTTP logs (totalDuration) for
11
+ * successful POST /v1/agents/:id/memory in prod: n=87 over 04:53-05:34Z,
12
+ * p50 1689ms, p95 2269ms, p99 5830ms (also the max). Set to about p99 x 1.5,
13
+ * rounded up. The slowest read in the same window was GET full-context at
14
+ * 2500ms. Report: reports/ais-memory-write-latency/2026-11-30-CORBOT-E991E195.md
15
+ */
16
+ export const DEFAULT_AIS_REQUEST_TIMEOUT_MS = 9_000;
9
17
  const ENV_VAR = 'AIS_MCP_REQUEST_TIMEOUT_MS';
10
18
  /**
11
19
  * Resolve the AIS request timeout from AIS_MCP_REQUEST_TIMEOUT_MS. Falls back
@@ -55,4 +63,86 @@ export function toAisRequestError(err, path, timeoutMs, method = 'GET') {
55
63
  }
56
64
  return err;
57
65
  }
66
+ /** One budget for inbox_read, including credential retries and optional ack. */
67
+ const INBOX_READ_TIMEOUT_MS = 30_000;
68
+ const inboxReadOperation = new AsyncLocalStorage();
69
+ function inboxTimeout(operation) {
70
+ return new AisRequestTimeoutError('inbox_read', INBOX_READ_TIMEOUT_MS, ` during ${operation.stage}${operation.stage.startsWith('POST ') ? WRITE_TIMEOUT_NOTE : ''}`);
71
+ }
72
+ /** Update diagnostics and refuse to start another stage after the budget expires. */
73
+ export function setInboxReadStage(stage) {
74
+ const operation = inboxReadOperation.getStore();
75
+ if (!operation)
76
+ return;
77
+ operation.controller.signal.throwIfAborted();
78
+ if (performance.now() >= operation.deadline) {
79
+ const error = inboxTimeout(operation);
80
+ operation.controller.abort(error);
81
+ throw error;
82
+ }
83
+ operation.stage = stage;
84
+ }
85
+ const requestTimeouts = new WeakMap();
86
+ /** Start a fresh request budget after the pass lock. Keep operation deadlines intact. */
87
+ export function startAisRequestTimeout(signal) {
88
+ if (!signal)
89
+ return AbortSignal.timeout(getAisRequestTimeoutMs());
90
+ const timeoutMs = requestTimeouts.get(signal);
91
+ return timeoutMs === undefined ? signal : AbortSignal.timeout(timeoutMs);
92
+ }
93
+ /** Inbox transports share the operation signal; other tools retain their request timeout. */
94
+ export function aisRequestSignal(path, timeoutMs, method = 'GET') {
95
+ setInboxReadStage(`${method} ${path}: headers`);
96
+ const operation = inboxReadOperation.getStore();
97
+ if (operation)
98
+ return operation.controller.signal;
99
+ const signal = AbortSignal.timeout(timeoutMs);
100
+ requestTimeouts.set(signal, timeoutMs);
101
+ return signal;
102
+ }
103
+ /**
104
+ * Credential acquisition can start session-owned device polling and renewal.
105
+ * Keep those background tasks outside this call's context; the caller's
106
+ * deadline still bounds its await, and its next stage refuses late results.
107
+ */
108
+ export function withoutInboxReadDeadline(operation) {
109
+ return inboxReadOperation.exit(operation);
110
+ }
111
+ /**
112
+ * Nesting (read/ack inside the MCP handler) reuses the same absolute deadline.
113
+ * A single timer also bounds body readers or credential callbacks that ignore
114
+ * abort. The async context keeps concurrent tool calls' budgets independent.
115
+ */
116
+ export async function withInboxReadDeadline(operation, toolName = 'inbox_read') {
117
+ if (toolName !== 'inbox_read')
118
+ return operation();
119
+ const current = inboxReadOperation.getStore();
120
+ if (current) {
121
+ setInboxReadStage(current.stage);
122
+ return operation();
123
+ }
124
+ const context = {
125
+ deadline: performance.now() + INBOX_READ_TIMEOUT_MS,
126
+ stage: 'credentials / identity',
127
+ controller: new AbortController(),
128
+ };
129
+ return inboxReadOperation.run(context, async () => {
130
+ let timer;
131
+ const expired = new Promise((_resolve, reject) => {
132
+ timer = setTimeout(() => {
133
+ const error = inboxTimeout(context);
134
+ reject(error);
135
+ context.controller.abort(error);
136
+ }, Math.max(0, context.deadline - performance.now()));
137
+ });
138
+ try {
139
+ const result = await Promise.race([operation(), expired]);
140
+ setInboxReadStage(context.stage);
141
+ return result;
142
+ }
143
+ finally {
144
+ clearTimeout(timer);
145
+ }
146
+ });
147
+ }
58
148
  //# sourceMappingURL=request-timeout.js.map
@@ -7,16 +7,19 @@
7
7
  */
8
8
  import { constants } from 'node:fs';
9
9
  import { lstat, open } from 'node:fs/promises';
10
+ import { handoffDocFields, withHandoffDocWarning } from './handoff-doc.js';
10
11
  import { AisHttpError, duplicateMemoryResult } from './ais-http-error.js';
11
- import { getAisRequestTimeoutMs, toAisRequestError } from './request-timeout.js';
12
+ import { captureServerVersionHeaders, withAisClientVersion } from './ais-http.js';
13
+ import { aisRequestSignal, getAisRequestTimeoutMs, setInboxReadStage, toAisRequestError } from './request-timeout.js';
12
14
  import { emitTelemetry } from './telemetry.js';
13
15
  import { OutOfScopeToolError } from './agent-key-mode.js';
16
+ import { SKILL_GET_TOOL, SKILL_GET_KEY_MODE_DETAIL } from './operating-layer-read.js';
14
17
  import { OPERATING_LAYER_PUT_TOOL, OPERATING_LAYER_PUT_KEY_MODE_DETAIL } from './operating-layer-write.js';
15
18
  import { readInboxAndMaybeAck } from './inbox-client.js';
16
- import { orient } from './cli/orientation.js';
19
+ import { orientAgainstStoredManifest } from './cli/orientation-load.js';
17
20
  import { AGENT_ARCHIVE_KEY_MODE_DETAIL } from './agent-archive.js';
18
21
  import { fetchCredentialWhoami } from './credential-whoami.js';
19
- import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, parseInboxSendArgs, parseInboxReadArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
22
+ import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseUpdateMemoryArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, parseInboxSendArgs, parseInboxReadArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
20
23
  import { resolveDreamResponse } from './dream-poll.js';
21
24
  import { forgetOwnMemory } from './memory-forget.js';
22
25
  const AGENT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -29,8 +32,11 @@ export class RunPassConfigError extends Error {
29
32
  this.name = 'RunPassConfigError';
30
33
  }
31
34
  }
32
- async function readJson(res) {
33
- return res.json().catch(() => null);
35
+ async function readJson(res, path, method = 'GET') {
36
+ setInboxReadStage(`${method} ${path}: body`);
37
+ const data = await res.json().catch(() => null);
38
+ setInboxReadStage(`${method} ${path}: body`);
39
+ return data;
34
40
  }
35
41
  export function loadRunPassConfig(env = process.env) {
36
42
  const rawPath = env['AIS_RUN_PASS_FILE'];
@@ -101,10 +107,10 @@ export async function readRunPassFile(runPassFile) {
101
107
  }
102
108
  async function runPassHeaders(runPassFile, includeContentType) {
103
109
  const runPass = await readRunPassFile(runPassFile);
104
- return {
110
+ return withAisClientVersion({
105
111
  ...(includeContentType ? { 'Content-Type': 'application/json' } : {}),
106
112
  'x-run-pass': runPass,
107
- };
113
+ });
108
114
  }
109
115
  export async function runPassPost(aisUrl, path, runPassFile, body, fetchImpl = globalThis.fetch) {
110
116
  const headers = await runPassHeaders(runPassFile, true);
@@ -115,7 +121,7 @@ export async function runPassPost(aisUrl, path, runPassFile, body, fetchImpl = g
115
121
  method: 'POST',
116
122
  headers,
117
123
  body: JSON.stringify(body),
118
- signal: AbortSignal.timeout(timeoutMs),
124
+ signal: aisRequestSignal(path, timeoutMs, 'POST'),
119
125
  });
120
126
  }
121
127
  catch (err) {
@@ -123,7 +129,8 @@ export async function runPassPost(aisUrl, path, runPassFile, body, fetchImpl = g
123
129
  emitTelemetry({ event: 'ais.http.failure', path, error: wrapped instanceof Error ? wrapped.message : String(wrapped) });
124
130
  throw wrapped;
125
131
  }
126
- const data = await readJson(res);
132
+ captureServerVersionHeaders(res);
133
+ const data = await readJson(res, path, 'POST');
127
134
  if (!res.ok) {
128
135
  emitTelemetry({ event: 'ais.http.failure', path, httpStatus: res.status, error: `HTTP ${res.status}` });
129
136
  throw new AisHttpError(res.status, path, data);
@@ -137,7 +144,7 @@ export async function runPassGet(aisUrl, path, runPassFile, fetchImpl = globalTh
137
144
  try {
138
145
  res = await fetchImpl(`${aisUrl}${path}`, {
139
146
  headers,
140
- signal: AbortSignal.timeout(timeoutMs),
147
+ signal: aisRequestSignal(path, timeoutMs),
141
148
  });
142
149
  }
143
150
  catch (err) {
@@ -145,7 +152,8 @@ export async function runPassGet(aisUrl, path, runPassFile, fetchImpl = globalTh
145
152
  emitTelemetry({ event: 'ais.http.failure', path, error: wrapped instanceof Error ? wrapped.message : String(wrapped) });
146
153
  throw wrapped;
147
154
  }
148
- const data = await readJson(res);
155
+ captureServerVersionHeaders(res);
156
+ const data = await readJson(res, path);
149
157
  if (!res.ok) {
150
158
  emitTelemetry({ event: 'ais.http.failure', path, httpStatus: res.status, error: `HTTP ${res.status}` });
151
159
  throw new AisHttpError(res.status, path, data);
@@ -161,7 +169,7 @@ export async function runPassPatch(aisUrl, path, runPassFile, body, fetchImpl =
161
169
  method: 'PATCH',
162
170
  headers,
163
171
  body: JSON.stringify(body),
164
- signal: AbortSignal.timeout(timeoutMs),
172
+ signal: aisRequestSignal(path, timeoutMs, 'PATCH'),
165
173
  });
166
174
  }
167
175
  catch (err) {
@@ -169,7 +177,8 @@ export async function runPassPatch(aisUrl, path, runPassFile, body, fetchImpl =
169
177
  emitTelemetry({ event: 'ais.http.failure', path, error: wrapped instanceof Error ? wrapped.message : String(wrapped) });
170
178
  throw wrapped;
171
179
  }
172
- const data = await readJson(res);
180
+ captureServerVersionHeaders(res);
181
+ const data = await readJson(res, path, 'PATCH');
173
182
  if (!res.ok) {
174
183
  emitTelemetry({ event: 'ais.http.failure', path, httpStatus: res.status, error: `HTTP ${res.status}` });
175
184
  throw new AisHttpError(res.status, path, data);
@@ -192,6 +201,10 @@ export async function dispatchToolRunPassMode(aisUrl, config, name, rawArgs, fet
192
201
  throw err;
193
202
  }
194
203
  }
204
+ case 'update_memory': {
205
+ const { memoryId, ...update } = parseUpdateMemoryArgs(rawArgs);
206
+ return runPassPatch(aisUrl, `/v1/agents/${agentId}/memory/${memoryId}`, runPassFile, update, fetchImpl);
207
+ }
195
208
  case 'recall': {
196
209
  const args = parseRecallArgs(rawArgs);
197
210
  const params = new URLSearchParams();
@@ -217,7 +230,7 @@ export async function dispatchToolRunPassMode(aisUrl, config, name, rawArgs, fet
217
230
  case 'full_context': {
218
231
  const fcArgs = parseFullContextArgs(rawArgs);
219
232
  const fcQs = buildFullContextQuery(fcArgs);
220
- return runPassGet(aisUrl, `/v1/agents/${agentId}/full-context${fcQs}`, runPassFile, fetchImpl);
233
+ return withHandoffDocWarning(await runPassGet(aisUrl, `/v1/agents/${agentId}/full-context${fcQs}`, runPassFile, fetchImpl));
221
234
  }
222
235
  case 'dream':
223
236
  parseEmptyToolArgs(rawArgs);
@@ -225,8 +238,11 @@ export async function dispatchToolRunPassMode(aisUrl, config, name, rawArgs, fet
225
238
  case 'whoami':
226
239
  parseEmptyToolArgs(rawArgs);
227
240
  return fetchCredentialWhoami(agentId, 'run-pass', () => runPassGet(aisUrl, `/v1/agents/${agentId}/whoami`, runPassFile, fetchImpl), () => runPassGet(aisUrl, `/v1/agents/${agentId}/memory?limit=1`, runPassFile, fetchImpl));
241
+ case 'environment_manifest_get':
242
+ parseEmptyToolArgs(rawArgs);
243
+ return runPassGet(aisUrl, `/v1/agents/${agentId}/environment-manifest`, runPassFile, fetchImpl);
228
244
  case 'orientation_check':
229
- return orient(rawArgs);
245
+ return orientAgainstStoredManifest(rawArgs, agentId, () => runPassGet(aisUrl, `/v1/agents/${agentId}/environment-manifest`, runPassFile, fetchImpl));
230
246
  case 'agent_load':
231
247
  throw new OutOfScopeToolError(name, 'Run passes are scoped to one agent for one run; start a new run pass for another agent.');
232
248
  case 'goal_create': {
@@ -299,12 +315,14 @@ export async function dispatchToolRunPassMode(aisUrl, config, name, rawArgs, fet
299
315
  return runPassPost(aisUrl, `/v1/agents/${agentId}/handoff`, runPassFile, {
300
316
  ...(args.summary !== undefined ? { summary: args.summary } : {}),
301
317
  ...(args.keyLearnings !== undefined ? { keyLearnings: args.keyLearnings } : {}),
302
- ...(args.docPath !== undefined ? { docPath: args.docPath } : {}),
318
+ ...await handoffDocFields(args.docPath),
303
319
  ...(args.docPrUrl !== undefined ? { docPrUrl: args.docPrUrl } : {}),
304
320
  }, fetchImpl);
305
321
  }
306
322
  case OPERATING_LAYER_PUT_TOOL:
307
323
  throw new OutOfScopeToolError(name, OPERATING_LAYER_PUT_KEY_MODE_DETAIL);
324
+ case SKILL_GET_TOOL:
325
+ throw new OutOfScopeToolError(name, SKILL_GET_KEY_MODE_DETAIL);
308
326
  case 'agent_archive':
309
327
  case 'agent_delete':
310
328
  throw new OutOfScopeToolError(name, AGENT_ARCHIVE_KEY_MODE_DETAIL);
@@ -237,6 +237,7 @@ export function requiresIdentityGate(name, args) {
237
237
  return [
238
238
  'remember',
239
239
  'memory_forget',
240
+ 'update_memory',
240
241
  'handoff',
241
242
  'dream',
242
243
  'inbox_send',
@@ -249,7 +250,8 @@ export function requiresIdentityGate(name, args) {
249
250
  'goal_activate',
250
251
  'goal_complete',
251
252
  'operating_layer_put',
253
+ 'slack_post',
252
254
  ].includes(name) ||
253
- (name === 'inbox_read' && args['ack'] === true);
255
+ ((name === 'inbox_read' || name === 'slack_read') && args['ack'] === true);
254
256
  }
255
257
  //# sourceMappingURL=session-identity.js.map
@@ -9,12 +9,20 @@
9
9
  *
10
10
  * 1. the newest task memory tagged `handoff` (what the last session left),
11
11
  * 2. up to three lessons tagged `when:turn-start` (rules for every turn),
12
- * 3. the open orders and unread-inbox count of the server's bootstrap view.
12
+ * 3. standing lessons, open orders, the unread-inbox count and owner-marked
13
+ * skill bodies from bootstrap.
13
14
  *
14
15
  * Every item carries its memory id and says when it was cut, so the whole text
15
16
  * is one read away. A part that cannot be read is named in `notes`; it never
16
17
  * fails the load and is never dropped silently.
17
18
  */
19
+ import { z } from 'zod';
20
+ declare const hotSkillBodiesSchema: z.ZodArray<z.ZodObject<{
21
+ name: z.ZodString;
22
+ body: z.ZodString;
23
+ }, z.core.$strip>>;
24
+ type HotSkillBody = z.infer<typeof hotSkillBodiesSchema>[number];
25
+ export declare function readHotSkillBodies(raw: unknown): HotSkillBody[];
18
26
  /** Tag an agent puts on the task memory it leaves for its next session. */
19
27
  export declare const SESSION_START_HANDOFF_TAG = "handoff";
20
28
  /** Tag on a lesson that applies at the start of every turn. */
@@ -24,12 +32,12 @@ export declare const SESSION_START_MAX_ORDERS = 5;
24
32
  export declare const SESSION_START_HANDOFF_MAX_CHARS = 3000;
25
33
  export declare const SESSION_START_LESSON_MAX_CHARS = 600;
26
34
  export declare const SESSION_START_ORDER_MAX_CHARS = 300;
27
- /** Upper bound on memory text in one start: about 1,600 tokens. */
35
+ /** Upper bound on memory text in one start, including the server previews. */
28
36
  export declare const SESSION_START_MAX_CHARS: number;
29
37
  /** One time budget for all three start reads together; the load never waits longer. */
30
38
  export declare const SESSION_START_BUDGET_MS = 4000;
31
39
  /** Said by agent_load in a workspace-key session, where the start is not read. */
32
- export declare const SESSION_START_WORKSPACE_KEY_NOTE = "No readable start is included in a workspace-key session. Call full_context with view \"bootstrap\" for the handoff and open orders.";
40
+ export declare const SESSION_START_WORKSPACE_KEY_NOTE = "No readable start is included in a workspace-key session. Call full_context with view \"bootstrap\" for the handoff, lessons and open orders.";
33
41
  export declare const SESSION_START_NOTICE: string;
34
42
  export interface SessionStartItem {
35
43
  /** Memory id; null only for the handoff-package fallback, which is not a memory. */
@@ -55,6 +63,7 @@ export interface SessionStart {
55
63
  lessons: SessionStartItem[];
56
64
  openOrders: SessionStartItem[];
57
65
  unreadInbox: number | null;
66
+ hotSkillBodies?: HotSkillBody[];
58
67
  /** What is missing, cut, or could not be read. Empty when the start is whole. */
59
68
  notes: string[];
60
69
  }
@@ -66,3 +75,4 @@ export type SessionStartGet = (path: string) => Promise<unknown>;
66
75
  * expired memories.
67
76
  */
68
77
  export declare function loadSessionStart(get: SessionStartGet, agentId: string, budgetMs?: number): Promise<SessionStart>;
78
+ export {};