@senselab-ai/amfs 0.3.1 → 0.4.5

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.
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Shared machinery for the provider instrumentations.
3
+ *
4
+ * Each `instrument*` function replaces a client method on the *instance* with a
5
+ * wrapper that times the call, reads token usage off the response (or, for a
6
+ * stream, accumulates it while the caller iterates and records when the stream
7
+ * ends) and hands the result to `memory.recordLlmCall`. The wrapped call is
8
+ * never altered: an instrumentation failure is logged and swallowed, an error
9
+ * from the provider is recorded as a failed call and re-thrown unchanged.
10
+ *
11
+ * Responses are read by duck typing, so neither `openai` nor `@anthropic-ai/sdk`
12
+ * is imported — they are optional peers — and tests drive the wrappers with
13
+ * plain objects.
14
+ */
15
+ const FLAG = "__amfsInstrumented";
16
+ export function isInstrumented(target) {
17
+ return Boolean(target?.[FLAG]);
18
+ }
19
+ export function markInstrumented(target) {
20
+ try {
21
+ Object.defineProperty(target, FLAG, { value: true, enumerable: false, configurable: true });
22
+ }
23
+ catch {
24
+ // frozen or proxy — nothing to do
25
+ }
26
+ }
27
+ export function get(obj, key) {
28
+ if (obj === null || obj === undefined)
29
+ return undefined;
30
+ return obj[key];
31
+ }
32
+ export function asInt(value) {
33
+ if (typeof value !== "number" || !Number.isFinite(value))
34
+ return undefined;
35
+ return Math.trunc(value);
36
+ }
37
+ export function resolve(target, path) {
38
+ let obj = target;
39
+ for (const hop of path) {
40
+ obj = get(obj, hop);
41
+ if (obj === null || obj === undefined)
42
+ return undefined;
43
+ }
44
+ return obj;
45
+ }
46
+ function isAsyncIterable(value) {
47
+ return (value !== null &&
48
+ typeof value === "object" &&
49
+ typeof value[Symbol.asyncIterator] === "function");
50
+ }
51
+ function warn(message, err) {
52
+ try {
53
+ console.warn(`[amfs] ${message}`, err);
54
+ }
55
+ catch {
56
+ // no console — stay silent
57
+ }
58
+ }
59
+ class Call {
60
+ sink;
61
+ provider;
62
+ requestedModel;
63
+ startedAt = new Date();
64
+ t0 = performance.now();
65
+ done = false;
66
+ constructor(sink, provider, requestedModel) {
67
+ this.sink = sink;
68
+ this.provider = provider;
69
+ this.requestedModel = requestedModel;
70
+ }
71
+ record(usage, error) {
72
+ if (this.done)
73
+ return;
74
+ this.done = true;
75
+ const latencyMs = performance.now() - this.t0;
76
+ try {
77
+ const model = usage.model || this.requestedModel || "";
78
+ if (!model)
79
+ return; // nothing to attribute the call to
80
+ this.sink.recordLlmCall({
81
+ model,
82
+ provider: this.provider,
83
+ inputTokens: usage.inputTokens ?? 0,
84
+ outputTokens: usage.outputTokens ?? 0,
85
+ latencyMs,
86
+ ...(error !== undefined ? { error: String(error) } : {}),
87
+ }, this.startedAt);
88
+ }
89
+ catch (err) {
90
+ warn(`${this.provider} instrumentation: could not record call`, err);
91
+ }
92
+ }
93
+ }
94
+ /**
95
+ * Wrap an async iterable so its chunks are observed and the call is recorded
96
+ * once the stream is exhausted, breaks, or is returned early. Every other
97
+ * property (e.g. `controller`, `finalMessage()`) is forwarded to the original.
98
+ */
99
+ function proxyStream(inner, call, onChunk) {
100
+ const usage = {};
101
+ const iterate = async function* () {
102
+ try {
103
+ for await (const chunk of inner) {
104
+ try {
105
+ onChunk(chunk, usage);
106
+ }
107
+ catch (err) {
108
+ warn("stream chunk extraction failed", err);
109
+ }
110
+ yield chunk;
111
+ }
112
+ call.record(usage);
113
+ }
114
+ catch (err) {
115
+ call.record(usage, err);
116
+ throw err;
117
+ }
118
+ finally {
119
+ call.record(usage); // early `return()` / `break` lands here
120
+ }
121
+ };
122
+ return new Proxy(inner, {
123
+ get(target, prop, receiver) {
124
+ if (prop === Symbol.asyncIterator)
125
+ return () => iterate();
126
+ const value = Reflect.get(target, prop, receiver);
127
+ return typeof value === "function" ? value.bind(target) : value;
128
+ },
129
+ });
130
+ }
131
+ /**
132
+ * Replace `owner[method]` with an instrumented wrapper. Returns whether anything
133
+ * was patched (`false` when the method is missing or already wrapped).
134
+ *
135
+ * The provider SDKs return a promise-like (`APIPromise`) from `create`; the
136
+ * wrapper awaits it, so callers always get a plain `Promise`. `stream: true`
137
+ * calls resolve to an async iterable, which is proxied.
138
+ */
139
+ export function patchMethod(owner, method, options) {
140
+ if (owner === null || typeof owner !== "object")
141
+ return false;
142
+ const holder = owner;
143
+ const original = holder[method];
144
+ if (typeof original !== "function" || isInstrumented(original))
145
+ return false;
146
+ const wrapper = async function (...args) {
147
+ const params = (args[0] ?? {});
148
+ const call = new Call(options.sink, options.provider, typeof params.model === "string" ? params.model : undefined);
149
+ let result;
150
+ try {
151
+ result = await original.apply(this ?? owner, args);
152
+ }
153
+ catch (err) {
154
+ call.record({}, err);
155
+ throw err;
156
+ }
157
+ try {
158
+ if (params.stream === true && isAsyncIterable(result)) {
159
+ return proxyStream(result, call, options.onChunk);
160
+ }
161
+ const usage = {};
162
+ options.extract(result, usage);
163
+ call.record(usage);
164
+ }
165
+ catch (err) {
166
+ warn(`${options.provider} instrumentation failed; call unaffected`, err);
167
+ }
168
+ return result;
169
+ };
170
+ markInstrumented(wrapper);
171
+ try {
172
+ holder[method] = wrapper;
173
+ }
174
+ catch (err) {
175
+ warn(`${options.provider} instrumentation: cannot patch ${method}`, err);
176
+ return false;
177
+ }
178
+ return true;
179
+ }
@@ -0,0 +1,3 @@
1
+ export { instrumentOpenAI } from "./openai.js";
2
+ export { instrumentAnthropic } from "./anthropic.js";
3
+ export type { LlmCallSink } from "./common.js";
@@ -0,0 +1,2 @@
1
+ export { instrumentOpenAI } from "./openai.js";
2
+ export { instrumentAnthropic } from "./anthropic.js";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * `instrumentOpenAI(client, memory)` — every `chat.completions.create` and
3
+ * `responses.create` on the `openai` package's client is recorded with
4
+ * `memory.recordLlmCall` (model, tokens, latency, provider).
5
+ *
6
+ * Streaming calls (`stream: true`) are recorded when the stream ends; the Chat
7
+ * Completions API only sends token counts on the final chunk when the request
8
+ * has `stream_options: { include_usage: true }` — without it the call is still
9
+ * recorded, with a model and latency but zero tokens. `openai` is an optional
10
+ * peer and is not imported here.
11
+ */
12
+ import type { Extractor, LlmCallSink } from "./common.js";
13
+ export declare const extractChatCompletion: Extractor;
14
+ export declare const extractResponse: Extractor;
15
+ /** Responses API stream: the terminal event carries the whole response. */
16
+ export declare const extractResponseEvent: Extractor;
17
+ /**
18
+ * Instrument an OpenAI (or AzureOpenAI) client in place and return it. Every
19
+ * call made through it is recorded on `memory` until the next
20
+ * `commitOutcomeAsync`, which ships the calls with the outcome. Idempotent.
21
+ *
22
+ * ```ts
23
+ * const openai = instrumentOpenAI(new OpenAI(), memory);
24
+ * const r = await openai.chat.completions.create({ model: "gpt-4o-mini", messages });
25
+ * await memory.commitOutcomeAsync("deploy-42", OutcomeType.SUCCESS);
26
+ * ```
27
+ */
28
+ export declare function instrumentOpenAI<C>(client: C, memory: LlmCallSink): C;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * `instrumentOpenAI(client, memory)` — every `chat.completions.create` and
3
+ * `responses.create` on the `openai` package's client is recorded with
4
+ * `memory.recordLlmCall` (model, tokens, latency, provider).
5
+ *
6
+ * Streaming calls (`stream: true`) are recorded when the stream ends; the Chat
7
+ * Completions API only sends token counts on the final chunk when the request
8
+ * has `stream_options: { include_usage: true }` — without it the call is still
9
+ * recorded, with a model and latency but zero tokens. `openai` is an optional
10
+ * peer and is not imported here.
11
+ */
12
+ import { asInt, get, isInstrumented, markInstrumented, patchMethod, resolve } from "./common.js";
13
+ const PROVIDER = "openai";
14
+ export const extractChatCompletion = (response, usage) => {
15
+ const model = get(response, "model");
16
+ if (typeof model === "string" && model)
17
+ usage.model = model;
18
+ const u = get(response, "usage");
19
+ if (u) {
20
+ const inTok = asInt(get(u, "prompt_tokens"));
21
+ const outTok = asInt(get(u, "completion_tokens"));
22
+ if (inTok !== undefined)
23
+ usage.inputTokens = inTok;
24
+ if (outTok !== undefined)
25
+ usage.outputTokens = outTok;
26
+ }
27
+ };
28
+ export const extractResponse = (response, usage) => {
29
+ const model = get(response, "model");
30
+ if (typeof model === "string" && model)
31
+ usage.model = model;
32
+ const u = get(response, "usage");
33
+ if (u) {
34
+ const inTok = asInt(get(u, "input_tokens"));
35
+ const outTok = asInt(get(u, "output_tokens"));
36
+ if (inTok !== undefined)
37
+ usage.inputTokens = inTok;
38
+ if (outTok !== undefined)
39
+ usage.outputTokens = outTok;
40
+ }
41
+ };
42
+ /** Responses API stream: the terminal event carries the whole response. */
43
+ export const extractResponseEvent = (event, usage) => {
44
+ const type = String(get(event, "type") ?? "");
45
+ if (type === "response.completed" || type === "response.incomplete" || type === "response.failed") {
46
+ extractResponse(get(event, "response"), usage);
47
+ }
48
+ else if (type === "response.created") {
49
+ const model = get(get(event, "response"), "model");
50
+ if (typeof model === "string" && model)
51
+ usage.model = model;
52
+ }
53
+ };
54
+ /**
55
+ * Instrument an OpenAI (or AzureOpenAI) client in place and return it. Every
56
+ * call made through it is recorded on `memory` until the next
57
+ * `commitOutcomeAsync`, which ships the calls with the outcome. Idempotent.
58
+ *
59
+ * ```ts
60
+ * const openai = instrumentOpenAI(new OpenAI(), memory);
61
+ * const r = await openai.chat.completions.create({ model: "gpt-4o-mini", messages });
62
+ * await memory.commitOutcomeAsync("deploy-42", OutcomeType.SUCCESS);
63
+ * ```
64
+ */
65
+ export function instrumentOpenAI(client, memory) {
66
+ if (isInstrumented(client))
67
+ return client;
68
+ const completions = resolve(client, ["chat", "completions"]);
69
+ if (completions) {
70
+ patchMethod(completions, "create", {
71
+ provider: PROVIDER,
72
+ sink: memory,
73
+ extract: extractChatCompletion,
74
+ onChunk: extractChatCompletion,
75
+ });
76
+ }
77
+ const responses = resolve(client, ["responses"]);
78
+ if (responses) {
79
+ patchMethod(responses, "create", {
80
+ provider: PROVIDER,
81
+ sink: memory,
82
+ extract: extractResponse,
83
+ onChunk: extractResponseEvent,
84
+ });
85
+ }
86
+ markInstrumented(client);
87
+ return client;
88
+ }
package/dist/memory.d.ts CHANGED
@@ -2,14 +2,40 @@
2
2
  * AgentMemory — the main SDK entry point for TypeScript agents.
3
3
  */
4
4
  import type { AmfsAdapter, WatchHandle } from "./adapter.js";
5
+ import type { DecisionTrace, DecisionTracePage, DecisionTraceSummary, ListTracesOptions } from "./adapters/http.js";
5
6
  import type { AMFSConfig, Commit, MemoryEntry, RecallConfig, ScopeInfo, ScoredEntry } from "./models.js";
6
7
  import { OutcomeType } from "./models.js";
8
+ import type { LlmCallRecord, RecordLlmCallInput, SessionAttributes } from "./session.js";
7
9
  import { ReadTracker } from "./tracker.js";
8
10
  export interface AgentMemoryOptions {
9
11
  sessionId?: string;
10
12
  adapter?: AmfsAdapter;
11
13
  config?: AMFSConfig;
14
+ /**
15
+ * The memory branch every remote read and write goes to unless the call
16
+ * names one. Defaults to `AMFS_BRANCH` from the environment, then `main` —
17
+ * how a process is pointed at a repair branch or a canary without a code
18
+ * change. See {@link AgentMemory.checkout}.
19
+ */
20
+ branch?: string;
12
21
  }
22
+ /** Environment variable naming the branch an `AgentMemory` starts on. */
23
+ export declare const BRANCH_ENV = "AMFS_BRANCH";
24
+ /**
25
+ * The session attribute a committed outcome carries when the memory was on a
26
+ * branch other than `main`: the trace says which memory it read. A canary and
27
+ * a customer replay are graded through it — a run of the same prompt on
28
+ * `main` never read the fix and does not count — so the SDK stamps it rather
29
+ * than leaving it to every caller to remember.
30
+ */
31
+ export declare const MEMORY_BRANCH_ATTRIBUTE = "memory_branch";
32
+ /**
33
+ * The hosted connection, as the MCP server reads it. The constructor does not
34
+ * read these — a memory built without an adapter is in-memory whatever the
35
+ * environment says. {@link AgentMemory.fromEnv} is the explicit way to use them.
36
+ */
37
+ export declare const HTTP_URL_ENV = "AMFS_HTTP_URL";
38
+ export declare const API_KEY_ENV = "AMFS_API_KEY";
13
39
  export interface SearchOptions {
14
40
  query?: string;
15
41
  entityPath?: string;
@@ -20,8 +46,10 @@ export interface SearchOptions {
20
46
  since?: string;
21
47
  patternRef?: string;
22
48
  limit?: number;
23
- sortBy?: "confidence" | "recency" | "version";
49
+ sortBy?: "confidence" | "recency" | "version" | "priority";
24
50
  recallConfig?: RecallConfig;
51
+ /** Memory branch to search; defaults to the memory's branch. */
52
+ branch?: string;
25
53
  }
26
54
  export interface MemoryStats {
27
55
  totalEntries: number;
@@ -40,7 +68,36 @@ export declare class AgentMemory {
40
68
  readonly readTracker: ReadTracker;
41
69
  private engine;
42
70
  private propagator;
71
+ /** Cleared when an outcome is committed; see {@link setSessionAttributes}. */
72
+ private _sessionAttributes;
73
+ private _sessionLlmCalls;
74
+ private _branch;
43
75
  constructor(agentId: string, options?: AgentMemoryOptions);
76
+ /**
77
+ * A memory connected to hosted SenseLab, from `AMFS_HTTP_URL` and
78
+ * `AMFS_API_KEY`.
79
+ *
80
+ * The constructor never reads those variables, so this is the one-line way
81
+ * to use them. `url` and `apiKey` override the environment — a second key
82
+ * for a second agent, say. It never falls back to the in-memory adapter: a
83
+ * missing URL or key throws, naming what to set.
84
+ */
85
+ static fromEnv(agentId: string, options?: Omit<AgentMemoryOptions, "adapter"> & {
86
+ url?: string;
87
+ apiKey?: string;
88
+ }): AgentMemory;
89
+ /** The branch remote reads and writes go to unless a call names another. */
90
+ get branch(): string;
91
+ /**
92
+ * Point this memory at `branch` for every later remote read and write that
93
+ * does not name one; `null` or `""` means `main`. Returns the branch now
94
+ * active. The same thing `options.branch` does at construction, for a
95
+ * memory that outlives the choice — onto a repair branch while a replay
96
+ * runs and back to `main` when it ends.
97
+ */
98
+ checkout(branch: string | null | undefined): string;
99
+ /** The branch a remote call goes to: the call's own, else the memory's. */
100
+ private branchFor;
44
101
  read(entityPath: string, key: string, options?: {
45
102
  minConfidence?: number;
46
103
  }): MemoryEntry | null;
@@ -107,7 +164,45 @@ export declare class AgentMemory {
107
164
  */
108
165
  commitOutcome(outcomeRef: string, outcomeType: OutcomeType, causalEntryKeys?: string[], options?: {
109
166
  causalConfidence?: number;
167
+ attributes?: SessionAttributes;
110
168
  }): MemoryEntry[];
169
+ /**
170
+ * Merge `attributes` into the bag the next committed outcome stamps on its
171
+ * trace (`session_metadata.attributes`); returns the bag as it now stands.
172
+ *
173
+ * Attributes are the dimensions a run is later filtered and grouped by —
174
+ * `customer`, `task_type`, `environment`. Scalars only (string, number,
175
+ * boolean), at most 20 keys of up to 64 characters, string values up to 256
176
+ * characters; anything else throws. Keys are lowercased. Cleared when the
177
+ * outcome is committed.
178
+ *
179
+ * The key cap applies to the bag as merged, not to each call: a merge that
180
+ * would take it past 20 keys throws a `RangeError` and leaves the bag as it
181
+ * was.
182
+ */
183
+ setSessionAttributes(attributes: SessionAttributes): SessionAttributes;
184
+ /** The attribute bag waiting for the next commit. */
185
+ get sessionAttributes(): SessionAttributes;
186
+ /**
187
+ * Drop the attribute bag waiting for the next commit, as the commit itself
188
+ * does afterwards. For a caller that must fit its own keys under the cap
189
+ * ahead of what a run set — the replay receiver's grader keys, say.
190
+ */
191
+ clearSessionAttributes(): void;
192
+ /**
193
+ * Record one LLM call for the trace the next committed outcome builds.
194
+ *
195
+ * Token counts and cost are only ever known if the agent reports them, so
196
+ * this is what makes a trace's token and cost figures real rather than
197
+ * blank. `instrumentOpenAI` / `instrumentAnthropic` call this for you.
198
+ * Stored in `session_metadata.llm_calls` as
199
+ * `{call_id, model, provider, input_tokens, output_tokens, cost_usd, latency_ms, started_at}`.
200
+ * Returns the record as stored. Cleared when the outcome is committed.
201
+ */
202
+ recordLlmCall(call: RecordLlmCallInput, startedAt?: Date): LlmCallRecord;
203
+ /** The LLM calls waiting for the next commit. */
204
+ get sessionLlmCalls(): LlmCallRecord[];
205
+ private resetSessionMetadata;
111
206
  /**
112
207
  * Recall this agent's own memory for a key.
113
208
  * Unlike read(), returns only entries written by this agent.
@@ -134,6 +229,148 @@ export declare class AgentMemory {
134
229
  tree(maxDepth?: number): string;
135
230
  /** Reset the session read log. */
136
231
  clearReadLog(): void;
232
+ private requireHttp;
233
+ /** Read a single entry from the remote server. Records it for causal tracing. */
234
+ readAsync(entityPath: string, key: string, options?: {
235
+ branch?: string;
236
+ }): Promise<MemoryEntry | null>;
237
+ /** Write an entry to the remote server. */
238
+ writeAsync(entityPath: string, key: string, value: unknown, options?: {
239
+ confidence?: number;
240
+ memoryType?: string;
241
+ shared?: boolean;
242
+ patternRefs?: string[];
243
+ branch?: string;
244
+ }): Promise<MemoryEntry>;
245
+ /** List entries under an entity path from the remote server. */
246
+ listAsync(entityPath?: string, options?: {
247
+ includeSuperseded?: boolean;
248
+ branch?: string;
249
+ }): Promise<MemoryEntry[]>;
250
+ /** Filtered/keyword search on the remote server. */
251
+ searchAsync(options?: SearchOptions): Promise<MemoryEntry[]>;
252
+ /** Semantic retrieval by meaning (server-side embedding + blend). */
253
+ retrieveAsync(query: string, options?: {
254
+ entityPath?: string;
255
+ minConfidence?: number;
256
+ limit?: number;
257
+ includeArtifacts?: boolean;
258
+ /** Memory branch to retrieve from; defaults to the memory's branch. */
259
+ branch?: string;
260
+ }): Promise<Array<{
261
+ entry: MemoryEntry;
262
+ score: number;
263
+ }>>;
264
+ /**
265
+ * Compiled Cortex briefing for an entity — the start-of-session context load.
266
+ *
267
+ * `compact` returns the lead digest with its evidence sections (`validated`,
268
+ * `discredited`, `procedures`, `regime_shift`); `since` trims those to what
269
+ * changed after that moment; `branch` briefs from a branch other than `main`.
270
+ */
271
+ briefingAsync(options?: {
272
+ entityPath?: string;
273
+ agentId?: string;
274
+ limit?: number;
275
+ compact?: boolean;
276
+ since?: string;
277
+ branch?: string;
278
+ }): Promise<unknown>;
279
+ /**
280
+ * Commit an outcome remotely, snapshotting the session's causal chain.
281
+ *
282
+ * The session's attributes (from {@link setSessionAttributes} and
283
+ * `options.attributes`) and recorded LLM calls travel as `session_metadata`
284
+ * and are cleared once the server has accepted them, so each commit
285
+ * describes one run. A refused commit — a 422 for a bad bag, a 5xx — leaves
286
+ * them in place: the run still happened, and a retry should carry them.
287
+ */
288
+ commitOutcomeAsync(outcomeRef: string, outcomeType: OutcomeType, options?: {
289
+ entityPath?: string;
290
+ causalEntryKeys?: string[];
291
+ causalConfidence?: number;
292
+ attributes?: SessionAttributes;
293
+ /** The request the run answered; sealed on the trace for judges and training. */
294
+ taskInput?: string | null;
295
+ /** The agent's answer, in full. */
296
+ responseText?: string | null;
297
+ /** The actions taken, as `{tool_name, arguments}` rows. */
298
+ toolCalls?: Array<Record<string, unknown>>;
299
+ }): Promise<unknown>;
300
+ /** Version history of a key from the remote server. */
301
+ historyAsync(entityPath: string, key: string, options?: {
302
+ since?: string;
303
+ until?: string;
304
+ }): Promise<MemoryEntry[]>;
305
+ /** Recent timeline events for this agent (writes, outcomes, cross-agent reads). */
306
+ timelineAsync(options?: {
307
+ eventType?: string;
308
+ since?: string;
309
+ limit?: number;
310
+ branch?: string;
311
+ }): Promise<unknown[]>;
312
+ /** Related entities in the knowledge graph (Pro). */
313
+ graphNeighborsAsync(options: {
314
+ entity: string;
315
+ relation?: string;
316
+ direction?: string;
317
+ minConfidence?: number;
318
+ depth?: number;
319
+ limit?: number;
320
+ }): Promise<unknown[]>;
321
+ /**
322
+ * Browse persisted decision traces from past sessions, newest first.
323
+ *
324
+ * Returns one page as a flat array. Pass `cursor` (from
325
+ * {@link listTracesPageAsync}) to continue, or `since` / `until` to bound by
326
+ * creation time.
327
+ */
328
+ listTracesAsync(options?: ListTracesOptions): Promise<DecisionTraceSummary[]>;
329
+ /**
330
+ * One page of decision traces with paging metadata:
331
+ * `{ traces, nextCursor, hasMore }`. Follow `nextCursor` while `hasMore`.
332
+ */
333
+ listTracesPageAsync(options?: ListTracesOptions): Promise<DecisionTracePage>;
334
+ /** Retrieve a full decision trace by ID, or null if not found. */
335
+ getTraceAsync(traceId: string): Promise<DecisionTrace | null>;
336
+ /** Aggregate memory statistics from the remote server. */
337
+ statsAsync(): Promise<Record<string, unknown>>;
338
+ /**
339
+ * Open a room over one or more topics (entity paths) this account owns.
340
+ *
341
+ * Everyone admitted to the room reads and writes those exact paths — a
342
+ * sub-path of a topic is not part of the room. This agent is joined as the
343
+ * room's creator. Returns the room, including its `id`.
344
+ */
345
+ roomCreate(topics: string | string[], options?: {
346
+ name?: string;
347
+ description?: string;
348
+ discussions?: boolean;
349
+ }): Promise<Record<string, unknown>>;
350
+ /**
351
+ * Mint a join link for a room. Owner only.
352
+ *
353
+ * The response carries the raw `token`, and this is the only time it is
354
+ * returned; whoever should join spends it with {@link roomRedeem}.
355
+ * `clampToPlan` (default true) lowers `maxUses` to the plan's per-room
356
+ * ceiling rather than refusing with 402; the response then carries
357
+ * `max_uses_clamped`.
358
+ */
359
+ roomShare(roomId: string, options?: {
360
+ expiresInDays?: number;
361
+ maxUses?: number;
362
+ role?: "collaborator" | "viewer";
363
+ clampToPlan?: boolean;
364
+ }): Promise<Record<string, unknown>>;
365
+ /**
366
+ * Spend a join link: admit this API key's user to the room it opens.
367
+ *
368
+ * Accepts the bare token or the whole link URL. The one room call that
369
+ * works before the caller has any access to the room. It admits the *user*;
370
+ * call {@link roomJoin} afterwards to place this agent in the room and
371
+ * receive its briefing. Returns the `room_id`.
372
+ */
373
+ roomRedeem(token: string): Promise<Record<string, unknown>>;
137
374
  /** Join a room. The user owning this agent must have an accepted invite. */
138
375
  roomJoin(roomId: string): Promise<Record<string, unknown>>;
139
376
  /** Leave a room. Knowledge snapshots are preserved in private memory. */
@@ -142,17 +379,34 @@ export declare class AgentMemory {
142
379
  myRooms(): Promise<Record<string, unknown>[]>;
143
380
  /** Get room details including members, settings, and discussion status. */
144
381
  roomInfo(roomId: string): Promise<Record<string, unknown>>;
382
+ /**
383
+ * (Re)deliver the room's shared knowledge to this agent, without a rejoin.
384
+ * The briefing text comes back under `briefing`.
385
+ */
386
+ roomBriefing(roomId: string): Promise<Record<string, unknown>>;
145
387
  /** Get recent room activity (writes, joins, discussions, negotiations). */
146
388
  roomUpdates(roomId: string, options?: {
147
389
  since?: string;
148
390
  }): Promise<Record<string, unknown>>;
391
+ /**
392
+ * Close a room. Owner only. It stops accepting joins and writes; the shared
393
+ * topics and the memories in them stay where they are.
394
+ */
395
+ roomClose(roomId: string): Promise<Record<string, unknown>>;
396
+ /**
397
+ * Delete a room. Owner only. The room, its membership and its activity
398
+ * history go away; the shared topics and every memory in them survive.
399
+ */
400
+ roomDelete(roomId: string): Promise<Record<string, unknown>>;
149
401
  roomDiscuss(roomId: string, content: string, options?: {
150
402
  messageType?: string;
151
403
  addressedTo?: string;
404
+ replyTo?: string;
152
405
  }): Promise<Record<string, unknown>>;
153
406
  roomDiscussions(roomId: string, options?: {
154
407
  limit?: number;
155
408
  since?: string;
409
+ addressedTo?: string;
156
410
  }): Promise<Record<string, unknown>>;
157
411
  negotiateCreate(roomId: string, title: string, options?: {
158
412
  description?: string;
@@ -167,6 +421,15 @@ export declare class AgentMemory {
167
421
  rationale?: string;
168
422
  }): Promise<Record<string, unknown>>;
169
423
  negotiateStatus(roomId: string, sessionId: string): Promise<Record<string, unknown>>;
424
+ /**
425
+ * Send a request to the rooms API over the HTTP adapter's own transport.
426
+ *
427
+ * This used to build its own `fetch` from `adapter.apiKey`, a property
428
+ * `HttpAdapter` does not have, so every room call went out with no API key
429
+ * and no agent or session header and was refused with 401. Through
430
+ * `requestRaw` it is the adapter's request: same key, same identity, and an
431
+ * error whose message carries the server's response body.
432
+ */
170
433
  private _roomRequest;
171
434
  }
172
435
  /**