@senselab-ai/amfs 0.3.2 → 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.
package/dist/memory.js CHANGED
@@ -1,11 +1,90 @@
1
1
  /**
2
2
  * AgentMemory — the main SDK entry point for TypeScript agents.
3
3
  */
4
+ import { HttpAdapter } from "./adapters/http.js";
4
5
  import { InMemoryAdapter } from "./adapters/filesystem.js";
5
6
  import { defaultConfig } from "./config.js";
6
7
  import { CausalTagger, CoWEngine } from "./engine.js";
7
8
  import { OutcomeBackPropagator } from "./outcome.js";
9
+ import { buildSessionMetadata, SESSION_ATTRIBUTES_MAX_KEYS, countedAttributeKeys, toLlmCallRecord, validateSessionAttributes, } from "./session.js";
8
10
  import { ReadTracker } from "./tracker.js";
11
+ /** Environment variable naming the branch an `AgentMemory` starts on. */
12
+ export const BRANCH_ENV = "AMFS_BRANCH";
13
+ /**
14
+ * The session attribute a committed outcome carries when the memory was on a
15
+ * branch other than `main`: the trace says which memory it read. A canary and
16
+ * a customer replay are graded through it — a run of the same prompt on
17
+ * `main` never read the fix and does not count — so the SDK stamps it rather
18
+ * than leaving it to every caller to remember.
19
+ */
20
+ export const MEMORY_BRANCH_ATTRIBUTE = "memory_branch";
21
+ /**
22
+ * The hosted connection, as the MCP server reads it. The constructor does not
23
+ * read these — a memory built without an adapter is in-memory whatever the
24
+ * environment says. {@link AgentMemory.fromEnv} is the explicit way to use them.
25
+ */
26
+ export const HTTP_URL_ENV = "AMFS_HTTP_URL";
27
+ export const API_KEY_ENV = "AMFS_API_KEY";
28
+ function fromProcessEnv(name) {
29
+ const env = globalThis.process?.env;
30
+ return env?.[name];
31
+ }
32
+ function branchFromEnv() {
33
+ return fromProcessEnv(BRANCH_ENV);
34
+ }
35
+ /**
36
+ * What a pasted join link arrives wrapped in, besides whitespace: brackets,
37
+ * straight and curly quotes, the punctuation of the sentence around it, and
38
+ * the zero-width characters a copy out of an email or a document carries.
39
+ * None of it can be part of a token, which is URL-safe base64.
40
+ */
41
+ const LINK_WRAPPING = "<>()[]\"'`.,;:!\u201c\u201d\u2018\u2019\u200b\u200c\u200d\u2060\ufeff";
42
+ /** Whitespace as `String.prototype.trim` sees it, so a non-breaking space counts. */
43
+ function isLinkWrapping(ch) {
44
+ return ch.trim() === "" || LINK_WRAPPING.includes(ch);
45
+ }
46
+ /**
47
+ * `text` without link wrapping or whitespace at either end. One pass over one
48
+ * set, in any order, and not a bracket pass followed by a punctuation pass:
49
+ * `<https://.../join/tok>.` ends in a full stop with the bracket behind it,
50
+ * and two passes leave the `>` on the token. Index scans, not regexes: an
51
+ * anchored `[...]+$` backtracks quadratically on a long run of the character
52
+ * that is then followed by something else.
53
+ */
54
+ function unwrapLink(text) {
55
+ let start = 0;
56
+ let end = text.length;
57
+ while (start < end && isLinkWrapping(text[start]))
58
+ start++;
59
+ while (end > start && isLinkWrapping(text[end - 1]))
60
+ end--;
61
+ return text.slice(start, end);
62
+ }
63
+ /**
64
+ * The token out of whatever a room join link looks like when pasted: the bare
65
+ * token, or the whole URL with the brackets, trailing punctuation and query
66
+ * string it tends to arrive wrapped in.
67
+ */
68
+ function joinToken(value) {
69
+ let text = unwrapLink(value ?? "");
70
+ for (const marker of ["/join/", "/j/"]) {
71
+ const at = text.lastIndexOf(marker);
72
+ if (at !== -1) {
73
+ text = text.slice(at + marker.length);
74
+ break;
75
+ }
76
+ }
77
+ for (const cut of ["?", "#", "/"]) {
78
+ const at = text.indexOf(cut);
79
+ if (at !== -1)
80
+ text = text.slice(0, at);
81
+ }
82
+ return unwrapLink(text);
83
+ }
84
+ function normalizeBranch(branch) {
85
+ const trimmed = (branch ?? "").trim();
86
+ return trimmed || "main";
87
+ }
9
88
  export class AgentMemory {
10
89
  agentId;
11
90
  sessionId;
@@ -14,17 +93,74 @@ export class AgentMemory {
14
93
  readTracker;
15
94
  engine;
16
95
  propagator;
96
+ /** Cleared when an outcome is committed; see {@link setSessionAttributes}. */
97
+ _sessionAttributes = {};
98
+ _sessionLlmCalls = [];
99
+ _branch;
17
100
  constructor(agentId, options) {
18
101
  const config = options?.config ?? defaultConfig();
19
102
  this.agentId = agentId;
20
103
  this.adapter = options?.adapter ?? new InMemoryAdapter();
21
104
  this.namespace = config.namespace;
22
105
  this.readTracker = new ReadTracker();
106
+ // `branch` wins, then AMFS_BRANCH, then main — the Python SDK's order.
107
+ this._branch = normalizeBranch(options?.branch ?? branchFromEnv());
23
108
  const tagger = new CausalTagger(agentId, options?.sessionId);
24
109
  this.sessionId = tagger.sessionId;
110
+ // An adapter that talks to a server identifies this memory's agent and
111
+ // session on every request, so a hosted server can attribute reads and
112
+ // keep the whole session on one arm of a live repair canary. Duck-typed:
113
+ // the in-memory adapter has no identity to declare.
114
+ const bind = this.adapter.bind;
115
+ if (typeof bind === "function") {
116
+ this.adapter = bind.call(this.adapter, agentId, tagger.sessionId);
117
+ }
25
118
  this.engine = new CoWEngine(this.adapter, tagger, this.readTracker);
26
119
  this.propagator = new OutcomeBackPropagator(this.adapter);
27
120
  }
121
+ /**
122
+ * A memory connected to hosted SenseLab, from `AMFS_HTTP_URL` and
123
+ * `AMFS_API_KEY`.
124
+ *
125
+ * The constructor never reads those variables, so this is the one-line way
126
+ * to use them. `url` and `apiKey` override the environment — a second key
127
+ * for a second agent, say. It never falls back to the in-memory adapter: a
128
+ * missing URL or key throws, naming what to set.
129
+ */
130
+ static fromEnv(agentId, options) {
131
+ const { url: urlOption, apiKey: apiKeyOption, ...rest } = options ?? {};
132
+ const url = (urlOption ?? fromProcessEnv(HTTP_URL_ENV) ?? "").trim();
133
+ const apiKey = (apiKeyOption ?? fromProcessEnv(API_KEY_ENV) ?? "").trim();
134
+ const missing = [
135
+ ...(url ? [] : [HTTP_URL_ENV]),
136
+ ...(apiKey ? [] : [API_KEY_ENV]),
137
+ ];
138
+ if (missing.length > 0) {
139
+ throw new Error(`AgentMemory.fromEnv() needs ${missing.join(" and ")}: set ` +
140
+ `${missing.length === 1 ? "it" : "them"} in the environment, or pass url / apiKey.`);
141
+ }
142
+ return new AgentMemory(agentId, { ...rest, adapter: new HttpAdapter({ url, apiKey }) });
143
+ }
144
+ /** The branch remote reads and writes go to unless a call names another. */
145
+ get branch() {
146
+ return this._branch;
147
+ }
148
+ /**
149
+ * Point this memory at `branch` for every later remote read and write that
150
+ * does not name one; `null` or `""` means `main`. Returns the branch now
151
+ * active. The same thing `options.branch` does at construction, for a
152
+ * memory that outlives the choice — onto a repair branch while a replay
153
+ * runs and back to `main` when it ends.
154
+ */
155
+ checkout(branch) {
156
+ this._branch = normalizeBranch(branch);
157
+ return this._branch;
158
+ }
159
+ /** The branch a remote call goes to: the call's own, else the memory's. */
160
+ branchFor(branch) {
161
+ const effective = branch ?? this._branch;
162
+ return effective === "main" ? undefined : effective;
163
+ }
28
164
  read(entityPath, key, options) {
29
165
  const entry = this.engine.read(entityPath, key, options);
30
166
  if (entry && !entry.shared && entry.provenance.agentId !== this.agentId) {
@@ -274,9 +410,76 @@ export class AgentMemory {
274
410
  commitOutcome(outcomeRef, outcomeType, causalEntryKeys, options) {
275
411
  const keys = causalEntryKeys ?? this.readTracker.causalKeys;
276
412
  const record = OutcomeBackPropagator.makeRecord(outcomeRef, outcomeType, keys, this.agentId, { causalConfidence: options?.causalConfidence });
413
+ // Local adapters propagate confidence but build no trace, so the session
414
+ // bag has nowhere to go here; it is still validated and consumed so the
415
+ // next run starts clean, as on the HTTP path.
416
+ if (options?.attributes)
417
+ this.setSessionAttributes(options.attributes);
418
+ this.resetSessionMetadata();
277
419
  return this.propagator.propagate(record);
278
420
  }
279
421
  // ------------------------------------------------------------------
422
+ // Session metadata — attributes and LLM calls for the next trace
423
+ // ------------------------------------------------------------------
424
+ /**
425
+ * Merge `attributes` into the bag the next committed outcome stamps on its
426
+ * trace (`session_metadata.attributes`); returns the bag as it now stands.
427
+ *
428
+ * Attributes are the dimensions a run is later filtered and grouped by —
429
+ * `customer`, `task_type`, `environment`. Scalars only (string, number,
430
+ * boolean), at most 20 keys of up to 64 characters, string values up to 256
431
+ * characters; anything else throws. Keys are lowercased. Cleared when the
432
+ * outcome is committed.
433
+ *
434
+ * The key cap applies to the bag as merged, not to each call: a merge that
435
+ * would take it past 20 keys throws a `RangeError` and leaves the bag as it
436
+ * was.
437
+ */
438
+ setSessionAttributes(attributes) {
439
+ const merged = { ...this._sessionAttributes, ...validateSessionAttributes(attributes) };
440
+ const size = countedAttributeKeys(Object.keys(merged));
441
+ if (size > SESSION_ATTRIBUTES_MAX_KEYS) {
442
+ throw new RangeError(`at most ${SESSION_ATTRIBUTES_MAX_KEYS} session attributes are allowed (the bag would hold ${size})`);
443
+ }
444
+ this._sessionAttributes = merged;
445
+ return { ...this._sessionAttributes };
446
+ }
447
+ /** The attribute bag waiting for the next commit. */
448
+ get sessionAttributes() {
449
+ return { ...this._sessionAttributes };
450
+ }
451
+ /**
452
+ * Drop the attribute bag waiting for the next commit, as the commit itself
453
+ * does afterwards. For a caller that must fit its own keys under the cap
454
+ * ahead of what a run set — the replay receiver's grader keys, say.
455
+ */
456
+ clearSessionAttributes() {
457
+ this._sessionAttributes = {};
458
+ }
459
+ /**
460
+ * Record one LLM call for the trace the next committed outcome builds.
461
+ *
462
+ * Token counts and cost are only ever known if the agent reports them, so
463
+ * this is what makes a trace's token and cost figures real rather than
464
+ * blank. `instrumentOpenAI` / `instrumentAnthropic` call this for you.
465
+ * Stored in `session_metadata.llm_calls` as
466
+ * `{call_id, model, provider, input_tokens, output_tokens, cost_usd, latency_ms, started_at}`.
467
+ * Returns the record as stored. Cleared when the outcome is committed.
468
+ */
469
+ recordLlmCall(call, startedAt) {
470
+ const record = toLlmCallRecord(call, startedAt);
471
+ this._sessionLlmCalls.push(record);
472
+ return { ...record };
473
+ }
474
+ /** The LLM calls waiting for the next commit. */
475
+ get sessionLlmCalls() {
476
+ return this._sessionLlmCalls.map((c) => ({ ...c }));
477
+ }
478
+ resetSessionMetadata() {
479
+ this._sessionAttributes = {};
480
+ this._sessionLlmCalls = [];
481
+ }
482
+ // ------------------------------------------------------------------
280
483
  // Agent brain — scoped recall & cross-agent reads
281
484
  // ------------------------------------------------------------------
282
485
  /**
@@ -379,7 +582,216 @@ export class AgentMemory {
379
582
  clearReadLog() {
380
583
  this.readTracker.clear();
381
584
  }
382
- // ── Room operations (Pro — requires HTTP adapter with rooms backend) ──
585
+ // ------------------------------------------------------------------
586
+ // Async remote API (HTTP adapter)
587
+ //
588
+ // The synchronous methods above operate on an in-process adapter. When the
589
+ // memory is backed by a remote AMFS server — the common case for an
590
+ // orchestrator or a disposable sandbox pointing at hosted SenseLab — every
591
+ // operation is a network round-trip, so these `*Async` variants delegate to
592
+ // the HttpAdapter and return promises. They also feed the local read/commit
593
+ // trackers, so decision traces stay complete over HTTP.
594
+ // ------------------------------------------------------------------
595
+ requireHttp(method) {
596
+ const a = this.adapter;
597
+ if (typeof a[method] !== "function") {
598
+ throw new Error(`${method}() requires a remote HTTP adapter — construct AgentMemory ` +
599
+ `with an HttpAdapter (AMFS_HTTP_URL + AMFS_API_KEY). The local ` +
600
+ `in-memory adapter supports only the synchronous API.`);
601
+ }
602
+ return this.adapter;
603
+ }
604
+ /** Read a single entry from the remote server. Records it for causal tracing. */
605
+ async readAsync(entityPath, key, options) {
606
+ const entry = await this.requireHttp("readAsync").readAsync(entityPath, key, {
607
+ branch: this.branchFor(options?.branch),
608
+ });
609
+ if (entry)
610
+ this.readTracker.record(entry);
611
+ return entry;
612
+ }
613
+ /** Write an entry to the remote server. */
614
+ async writeAsync(entityPath, key, value, options) {
615
+ return this.requireHttp("writeAsync").writeAsync({
616
+ entityPath,
617
+ key,
618
+ value,
619
+ agentId: this.agentId,
620
+ ...options,
621
+ branch: this.branchFor(options?.branch),
622
+ });
623
+ }
624
+ /** List entries under an entity path from the remote server. */
625
+ async listAsync(entityPath, options) {
626
+ return this.requireHttp("listAsync").listAsync(entityPath, {
627
+ ...options,
628
+ branch: this.branchFor(options?.branch),
629
+ });
630
+ }
631
+ /** Filtered/keyword search on the remote server. */
632
+ async searchAsync(options) {
633
+ return this.requireHttp("searchAsync").searchAsync({
634
+ query: options?.query,
635
+ entityPath: options?.entityPath,
636
+ minConfidence: options?.minConfidence,
637
+ maxConfidence: options?.maxConfidence,
638
+ agentId: options?.agentId,
639
+ since: options?.since,
640
+ patternRef: options?.patternRef,
641
+ sortBy: options?.sortBy,
642
+ limit: options?.limit,
643
+ branch: this.branchFor(options?.branch),
644
+ });
645
+ }
646
+ /** Semantic retrieval by meaning (server-side embedding + blend). */
647
+ async retrieveAsync(query, options) {
648
+ return this.requireHttp("retrieveAsync").retrieveAsync(query, {
649
+ ...options,
650
+ branch: this.branchFor(options?.branch),
651
+ });
652
+ }
653
+ /**
654
+ * Compiled Cortex briefing for an entity — the start-of-session context load.
655
+ *
656
+ * `compact` returns the lead digest with its evidence sections (`validated`,
657
+ * `discredited`, `procedures`, `regime_shift`); `since` trims those to what
658
+ * changed after that moment; `branch` briefs from a branch other than `main`.
659
+ */
660
+ async briefingAsync(options) {
661
+ return this.requireHttp("briefingAsync").briefingAsync({
662
+ ...options,
663
+ branch: this.branchFor(options?.branch),
664
+ });
665
+ }
666
+ /**
667
+ * Commit an outcome remotely, snapshotting the session's causal chain.
668
+ *
669
+ * The session's attributes (from {@link setSessionAttributes} and
670
+ * `options.attributes`) and recorded LLM calls travel as `session_metadata`
671
+ * and are cleared once the server has accepted them, so each commit
672
+ * describes one run. A refused commit — a 422 for a bad bag, a 5xx — leaves
673
+ * them in place: the run still happened, and a retry should carry them.
674
+ */
675
+ async commitOutcomeAsync(outcomeRef, outcomeType, options) {
676
+ const keys = options?.causalEntryKeys ?? this.readTracker.causalKeys;
677
+ if (options?.attributes)
678
+ this.setSessionAttributes(options.attributes);
679
+ // The branch stamp: on a branch other than main the trace says so, unless
680
+ // the caller set the attribute themselves. Added after the bag was
681
+ // validated so a bag at the key cap is not refused for the branch it ran on.
682
+ const attributes = this._branch !== "main" && !(MEMORY_BRANCH_ATTRIBUTE in this._sessionAttributes)
683
+ ? { ...this._sessionAttributes, [MEMORY_BRANCH_ATTRIBUTE]: this._branch }
684
+ : this._sessionAttributes;
685
+ const sessionMetadata = buildSessionMetadata(attributes, this._sessionLlmCalls);
686
+ const result = await this.requireHttp("commitOutcomeAsync").commitOutcomeAsync({
687
+ outcomeRef,
688
+ outcomeType: String(outcomeType),
689
+ entityPath: options?.entityPath,
690
+ causalEntryKeys: keys,
691
+ causalConfidence: options?.causalConfidence,
692
+ agentId: this.agentId,
693
+ sessionMetadata,
694
+ taskInput: options?.taskInput,
695
+ responseText: options?.responseText,
696
+ toolCalls: options?.toolCalls,
697
+ });
698
+ this.resetSessionMetadata();
699
+ return result;
700
+ }
701
+ /** Version history of a key from the remote server. */
702
+ async historyAsync(entityPath, key, options) {
703
+ return this.requireHttp("historyAsync").historyAsync(entityPath, key, options);
704
+ }
705
+ /** Recent timeline events for this agent (writes, outcomes, cross-agent reads). */
706
+ async timelineAsync(options) {
707
+ return this.requireHttp("timelineAsync").timelineAsync(this.agentId, options);
708
+ }
709
+ /** Related entities in the knowledge graph (Pro). */
710
+ async graphNeighborsAsync(options) {
711
+ return this.requireHttp("graphNeighborsAsync").graphNeighborsAsync(options);
712
+ }
713
+ /**
714
+ * Browse persisted decision traces from past sessions, newest first.
715
+ *
716
+ * Returns one page as a flat array. Pass `cursor` (from
717
+ * {@link listTracesPageAsync}) to continue, or `since` / `until` to bound by
718
+ * creation time.
719
+ */
720
+ async listTracesAsync(options) {
721
+ return this.requireHttp("listTracesAsync").listTracesAsync(options);
722
+ }
723
+ /**
724
+ * One page of decision traces with paging metadata:
725
+ * `{ traces, nextCursor, hasMore }`. Follow `nextCursor` while `hasMore`.
726
+ */
727
+ async listTracesPageAsync(options) {
728
+ return this.requireHttp("listTracesPageAsync").listTracesPageAsync(options);
729
+ }
730
+ /** Retrieve a full decision trace by ID, or null if not found. */
731
+ async getTraceAsync(traceId) {
732
+ return this.requireHttp("getTraceAsync").getTraceAsync(traceId);
733
+ }
734
+ /** Aggregate memory statistics from the remote server. */
735
+ async statsAsync() {
736
+ return this.requireHttp("statsAsync").statsAsync();
737
+ }
738
+ // ── Room operations (hosted — requires the HTTP adapter) ──
739
+ //
740
+ // These return the server's JSON as it arrived (snake_case keys), unlike the
741
+ // entry methods above, which convert to camelCase: a room response is read by
742
+ // the same names the REST API and the Python SDK use.
743
+ /**
744
+ * Open a room over one or more topics (entity paths) this account owns.
745
+ *
746
+ * Everyone admitted to the room reads and writes those exact paths — a
747
+ * sub-path of a topic is not part of the room. This agent is joined as the
748
+ * room's creator. Returns the room, including its `id`.
749
+ */
750
+ async roomCreate(topics, options) {
751
+ const paths = (Array.isArray(topics) ? topics : [topics]).filter((p) => (p ?? "").trim());
752
+ if (paths.length === 0) {
753
+ throw new Error("roomCreate() needs at least one topic (entity path)");
754
+ }
755
+ return this._roomRequest("POST", "/api/v1/rooms", {
756
+ entity_paths: paths,
757
+ display_name: options?.name ?? null,
758
+ description: options?.description ?? null,
759
+ discussions_enabled: options?.discussions ?? true,
760
+ agent_id: this.agentId,
761
+ });
762
+ }
763
+ /**
764
+ * Mint a join link for a room. Owner only.
765
+ *
766
+ * The response carries the raw `token`, and this is the only time it is
767
+ * returned; whoever should join spends it with {@link roomRedeem}.
768
+ * `clampToPlan` (default true) lowers `maxUses` to the plan's per-room
769
+ * ceiling rather than refusing with 402; the response then carries
770
+ * `max_uses_clamped`.
771
+ */
772
+ async roomShare(roomId, options) {
773
+ return this._roomRequest("POST", `/api/v1/rooms/${roomId}/join-links`, {
774
+ expires_in_days: options?.expiresInDays ?? null,
775
+ max_uses: options?.maxUses ?? null,
776
+ role: options?.role ?? "collaborator",
777
+ clamp_max_uses_to_plan: options?.clampToPlan ?? true,
778
+ });
779
+ }
780
+ /**
781
+ * Spend a join link: admit this API key's user to the room it opens.
782
+ *
783
+ * Accepts the bare token or the whole link URL. The one room call that
784
+ * works before the caller has any access to the room. It admits the *user*;
785
+ * call {@link roomJoin} afterwards to place this agent in the room and
786
+ * receive its briefing. Returns the `room_id`.
787
+ */
788
+ async roomRedeem(token) {
789
+ const cleaned = joinToken(token);
790
+ if (!cleaned) {
791
+ throw new Error("roomRedeem() needs a join token or a join link URL");
792
+ }
793
+ return this._roomRequest("POST", `/api/v1/room-join/${encodeURIComponent(cleaned)}`, {});
794
+ }
383
795
  /** Join a room. The user owning this agent must have an accepted invite. */
384
796
  async roomJoin(roomId) {
385
797
  return this._roomRequest("POST", `/api/v1/rooms/${roomId}/agents`, {
@@ -388,21 +800,47 @@ export class AgentMemory {
388
800
  }
389
801
  /** Leave a room. Knowledge snapshots are preserved in private memory. */
390
802
  async roomLeave(roomId) {
391
- return this._roomRequest("DELETE", `/api/v1/rooms/${roomId}/agents/${this.agentId}`);
803
+ return this._roomRequest("DELETE", `/api/v1/rooms/${roomId}/agents/${encodeURIComponent(this.agentId)}`);
392
804
  }
393
805
  /** List rooms this agent's user owns or is invited to. */
394
806
  async myRooms() {
395
- const result = await this._roomRequest("GET", "/api/v1/rooms");
396
- return Array.isArray(result) ? result : result.rooms ?? [];
807
+ const result = (await this._roomRequest("GET", "/api/v1/rooms"));
808
+ if (Array.isArray(result))
809
+ return result;
810
+ return result?.rooms ?? [];
397
811
  }
398
812
  /** Get room details including members, settings, and discussion status. */
399
813
  async roomInfo(roomId) {
400
814
  return this._roomRequest("GET", `/api/v1/rooms/${roomId}`);
401
815
  }
816
+ /**
817
+ * (Re)deliver the room's shared knowledge to this agent, without a rejoin.
818
+ * The briefing text comes back under `briefing`.
819
+ */
820
+ async roomBriefing(roomId) {
821
+ return this._roomRequest("POST", `/api/v1/rooms/${roomId}/briefing`, {
822
+ agent_id: this.agentId,
823
+ });
824
+ }
402
825
  /** Get recent room activity (writes, joins, discussions, negotiations). */
403
826
  async roomUpdates(roomId, options) {
404
- const params = options?.since ? `?since=${options.since}` : "";
405
- return this._roomRequest("GET", `/api/v1/rooms/${roomId}/activity${params}`);
827
+ return this._roomRequest("GET", `/api/v1/rooms/${roomId}/activity`, undefined, {
828
+ since: options?.since,
829
+ });
830
+ }
831
+ /**
832
+ * Close a room. Owner only. It stops accepting joins and writes; the shared
833
+ * topics and the memories in them stay where they are.
834
+ */
835
+ async roomClose(roomId) {
836
+ return this._roomRequest("POST", `/api/v1/rooms/${roomId}/close`, {});
837
+ }
838
+ /**
839
+ * Delete a room. Owner only. The room, its membership and its activity
840
+ * history go away; the shared topics and every memory in them survive.
841
+ */
842
+ async roomDelete(roomId) {
843
+ return this._roomRequest("DELETE", `/api/v1/rooms/${roomId}`);
406
844
  }
407
845
  // -- Discussions --
408
846
  async roomDiscuss(roomId, content, options) {
@@ -411,16 +849,15 @@ export class AgentMemory {
411
849
  content,
412
850
  message_type: options?.messageType ?? "message",
413
851
  addressed_to: options?.addressedTo ?? null,
852
+ ...(options?.replyTo ? { reply_to: options.replyTo } : {}),
414
853
  });
415
854
  }
416
855
  async roomDiscussions(roomId, options) {
417
- const params = new URLSearchParams();
418
- if (options?.limit)
419
- params.set("limit", String(options.limit));
420
- if (options?.since)
421
- params.set("since", options.since);
422
- const qs = params.toString();
423
- return this._roomRequest("GET", `/api/v1/rooms/${roomId}/discussions${qs ? `?${qs}` : ""}`);
856
+ return this._roomRequest("GET", `/api/v1/rooms/${roomId}/discussions`, undefined, {
857
+ limit: options?.limit || undefined,
858
+ since: options?.since,
859
+ addressed_to: options?.addressedTo,
860
+ });
424
861
  }
425
862
  // -- Negotiations --
426
863
  async negotiateCreate(roomId, title, options) {
@@ -448,27 +885,26 @@ export class AgentMemory {
448
885
  async negotiateStatus(roomId, sessionId) {
449
886
  return this._roomRequest("GET", `/api/v1/rooms/${roomId}/negotiations/${sessionId}`);
450
887
  }
451
- async _roomRequest(method, path, body) {
888
+ /**
889
+ * Send a request to the rooms API over the HTTP adapter's own transport.
890
+ *
891
+ * This used to build its own `fetch` from `adapter.apiKey`, a property
892
+ * `HttpAdapter` does not have, so every room call went out with no API key
893
+ * and no agent or session header and was refused with 401. Through
894
+ * `requestRaw` it is the adapter's request: same key, same identity, and an
895
+ * error whose message carries the server's response body.
896
+ */
897
+ async _roomRequest(method, path, body, query) {
452
898
  const adapter = this.adapter;
453
- const baseUrl = adapter._baseUrl ?? adapter.baseUrl;
454
- if (typeof baseUrl !== "string") {
455
- throw new Error("Room operations require the HTTP adapter (set AMFS_HTTP_URL)");
456
- }
457
- const url = `${baseUrl.replace(/\/$/, "")}${path}`;
458
- const headers = { "Content-Type": "application/json" };
459
- const apiKey = adapter._apiKey ?? adapter.apiKey;
460
- if (typeof apiKey === "string") {
461
- headers["Authorization"] = `Bearer ${apiKey}`;
462
- }
463
- const resp = await fetch(url, {
464
- method,
465
- headers,
466
- body: body ? JSON.stringify(body) : undefined,
467
- });
468
- if (!resp.ok) {
469
- throw new Error(`Room API error: ${resp.status} ${resp.statusText}`);
899
+ if (typeof adapter.requestRaw !== "function") {
900
+ throw new Error("Room operations need the hosted API: build the memory with " +
901
+ "AgentMemory.fromEnv(agentId) or an HttpAdapter ({ url, apiKey }). " +
902
+ "The in-memory adapter has no rooms.");
470
903
  }
471
- return resp.json();
904
+ return (await this.adapter.requestRaw(method, path, {
905
+ body,
906
+ query,
907
+ }));
472
908
  }
473
909
  }
474
910
  /**
package/dist/models.d.ts CHANGED
@@ -11,6 +11,20 @@ export declare enum OutcomeType {
11
11
  /** @deprecated Use FAILURE */ P2_INCIDENT = "p2_incident",
12
12
  /** @deprecated Use CRITICAL_FAILURE */ P1_INCIDENT = "p1_incident"
13
13
  }
14
+ /**
15
+ * Classification of a memory entry, mirroring `amfs_core.models.MemoryType`.
16
+ *
17
+ * `fact` is stable knowledge; `belief` a hypothesis that decays faster;
18
+ * `experience` a record of an action taken, decaying slower; `procedure` is
19
+ * how to do a task — a goal, ordered steps and what to do when one fails —
20
+ * decaying slowest and listed by the briefing in its own `procedures` section.
21
+ */
22
+ export declare enum MemoryType {
23
+ FACT = "fact",
24
+ BELIEF = "belief",
25
+ EXPERIENCE = "experience",
26
+ PROCEDURE = "procedure"
27
+ }
14
28
  export declare const OUTCOME_MULTIPLIERS: Record<string, number>;
15
29
  export interface Provenance {
16
30
  agentId: string;
package/dist/models.js CHANGED
@@ -12,6 +12,21 @@ export var OutcomeType;
12
12
  /** @deprecated Use FAILURE */ OutcomeType["P2_INCIDENT"] = "p2_incident";
13
13
  /** @deprecated Use CRITICAL_FAILURE */ OutcomeType["P1_INCIDENT"] = "p1_incident";
14
14
  })(OutcomeType || (OutcomeType = {}));
15
+ /**
16
+ * Classification of a memory entry, mirroring `amfs_core.models.MemoryType`.
17
+ *
18
+ * `fact` is stable knowledge; `belief` a hypothesis that decays faster;
19
+ * `experience` a record of an action taken, decaying slower; `procedure` is
20
+ * how to do a task — a goal, ordered steps and what to do when one fails —
21
+ * decaying slowest and listed by the briefing in its own `procedures` section.
22
+ */
23
+ export var MemoryType;
24
+ (function (MemoryType) {
25
+ MemoryType["FACT"] = "fact";
26
+ MemoryType["BELIEF"] = "belief";
27
+ MemoryType["EXPERIENCE"] = "experience";
28
+ MemoryType["PROCEDURE"] = "procedure";
29
+ })(MemoryType || (MemoryType = {}));
15
30
  export const OUTCOME_MULTIPLIERS = {
16
31
  [OutcomeType.CRITICAL_FAILURE]: 1.15,
17
32
  [OutcomeType.FAILURE]: 1.1,