From 7500d74998a44d4acb57d809d401bd8ef7aff1ad Mon Sep 17 00:00:00 2001 From: Drew Botwinick Date: Fri, 25 Sep 2026 12:11:23 -0500 Subject: [PATCH] Align TypeScript SDK sessions, batch, traversal and threads with the server - touchSession: the server reads extend_seconds from the query string and returns {expires_at}; the SDK sent ttl_seconds in the body (ignored) and returned response.session (always undefined). It now sends the query parameter and returns {expires_at}. The explorer's touch hook read .id from that undefined value; it now refetches the session instead. - BatchOperation/BatchResult: use the server's flat operations discriminated by op, and its {total_operations, successful, failed, results} response. - traverseGraph: send only workspace_id, relationship_types, max_depth, direction and min_strength, which is what the traverse endpoint accepts; unset values use the server defaults (max_depth 2, as in the Python and Go SDKs). relationshipCategories, maxPaths and maxNodes are deprecated. - createThread/listThreads: add ownership, scope, parentThread and idleAction on create (ownership "user" stores the thread under _user_chat, as the Python and Go SDKs do) and scope/ownership/parent/hidden filters on list; stop sending the server-ignored thread_id. --- .../src/hooks/use-sessions.ts | 5 +- memorylayer-sdk-typescript/README.md | 11 +- memorylayer-sdk-typescript/src/client.ts | 46 +++-- memorylayer-sdk-typescript/src/types.ts | 109 ++++++++++-- .../tests/client.test.ts | 163 +++++++++++++++++- 5 files changed, 293 insertions(+), 41 deletions(-) diff --git a/memorylayer-explorer/src/hooks/use-sessions.ts b/memorylayer-explorer/src/hooks/use-sessions.ts index 8a251f3..0508a02 100644 --- a/memorylayer-explorer/src/hooks/use-sessions.ts +++ b/memorylayer-explorer/src/hooks/use-sessions.ts @@ -77,8 +77,9 @@ export function useTouchSession() { }) => { return client.touchSession(sessionId, ttlSeconds); }, - onSuccess: (data) => { - queryClient.setQueryData(['sessions', data.id], data); + onSuccess: (_data, { sessionId }) => { + // The touch endpoint returns only the new expires_at; refetch the session. + queryClient.invalidateQueries({ queryKey: ['sessions', sessionId] }); }, }); } diff --git a/memorylayer-sdk-typescript/README.md b/memorylayer-sdk-typescript/README.md index d8e85e9..b89d58b 100644 --- a/memorylayer-sdk-typescript/README.md +++ b/memorylayer-sdk-typescript/README.md @@ -133,9 +133,10 @@ const trace = await client.traceMemory("mem-123"); ```typescript const result = await client.batchMemories([ - { action: "create", memory: { content: "Memory 1", importance: 0.7 } }, - { action: "create", memory: { content: "Memory 2", importance: 0.8 } }, - { action: "delete", memory_id: "mem-old", hard: false }, + { op: "create", content: "Memory 1", importance: 0.7 }, + { op: "create", content: "Memory 2", importance: 0.8, tags: ["project"] }, + { op: "update", memory_id: "mem-123", tags: ["reviewed"] }, + { op: "delete", memory_id: "mem-old", hard: false }, ]); console.log(`Successful: ${result.successful}, Failed: ${result.failed}`); @@ -223,8 +224,8 @@ await client.setWorkingMemory(session.id, "current_task", { // Retrieve working memory const memory = await client.getWorkingMemory(session.id, "current_task"); -// Extend session TTL -const updated = await client.touchSession(session.id); +// Extend session TTL (server default, or pass seconds to extend by) +const { expires_at } = await client.touchSession(session.id, 7200); // Commit working memory to long-term storage const commitResult = await client.commitSession(session.id, { diff --git a/memorylayer-sdk-typescript/src/client.ts b/memorylayer-sdk-typescript/src/client.ts index fc0cfc8..7d8773a 100644 --- a/memorylayer-sdk-typescript/src/client.ts +++ b/memorylayer-sdk-typescript/src/client.ts @@ -22,8 +22,9 @@ import type { AssociationUpdateOptions, ThreadUpdateOptions, UserThreadListOptions, SessionCheckpoint, ContextPack, ContextDelta, ContextPackOptions, + SessionTouchResult, } from "./types.js"; -import { RelationshipType } from "./types.js"; +import { RelationshipType, USER_CHAT_HOME_WORKSPACE } from "./types.js"; import { MemoryLayerError, AuthenticationError, AuthorizationError, NotFoundError, ValidationError, EnterpriseRequiredError, RateLimitError } from "./errors.js"; import { sleep } from "./utils.js"; import { SkillsNamespace } from "./skills.js"; @@ -644,13 +645,18 @@ export class MemoryLayerClient { ); } - async touchSession(sessionId: string, ttlSeconds?: number): Promise { - const response = await this.request<{ session: Session }>( + /** + * Extend a session's expiration. The server resets `expires_at` to now plus + * `extendSeconds` (or its default TTL when omitted) and returns the new value. + */ + async touchSession(sessionId: string, extendSeconds?: number): Promise { + const query = extendSeconds !== undefined + ? `?${new URLSearchParams({ extend_seconds: String(extendSeconds) }).toString()}` + : ""; + return this.request( "POST", - `/v1/sessions/${sessionId}/touch`, - ttlSeconds ? { ttl_seconds: ttlSeconds } : {} + `/v1/sessions/${sessionId}/touch${query}`, ); - return response.session; } async getBriefing( @@ -897,15 +903,15 @@ export class MemoryLayerClient { } // Graph traversal - uses nested endpoint under memories + // Sends only the fields the traverse endpoint accepts; unset values fall back + // to the server defaults (max_depth 2, direction "both", min_strength 0). async traverseGraph(startMemoryId: string, options: GraphTraverseOptions = {}): Promise { const body = { + workspace_id: options.workspaceId ?? this.workspaceId, relationship_types: options.relationshipTypes, - relationship_categories: options.relationshipCategories, - max_depth: options.maxDepth ?? 3, - direction: options.direction ?? "both", - min_strength: options.minStrength ?? 0.0, - max_paths: options.maxPaths ?? 100, - max_nodes: options.maxNodes ?? 50, + max_depth: options.maxDepth, + direction: options.direction, + min_strength: options.minStrength, }; return this.request("POST", `/v1/memories/${startMemoryId}/traverse`, body); } @@ -1386,9 +1392,13 @@ export class MemoryLayerClient { // ------------------------------------------------------------------ // async createThread(options: ThreadCreateOptions = {}): Promise { + // User-owned threads always live under the _user_chat home (as in the + // Python and Go SDKs); otherwise use the requested or client workspace. + const workspaceId = options.ownership === "user" + ? USER_CHAT_HOME_WORKSPACE + : options.workspaceId ?? this.workspaceId; const body = { - thread_id: options.threadId, - workspace_id: options.workspaceId ?? this.workspaceId, + workspace_id: workspaceId, user_id: options.userId, context_id: options.contextId, observer_id: options.observerId, @@ -1396,6 +1406,10 @@ export class MemoryLayerClient { title: options.title, metadata: options.metadata, expires_at: options.expiresAt, + scope: options.scope, + ownership: options.ownership, + parent_thread: options.parentThread, + idle_action: options.idleAction, }; const response = await this.request<{ thread: ChatThread }>("POST", "/v1/threads", body); return response.thread; @@ -1408,6 +1422,10 @@ export class MemoryLayerClient { if (options.userId) params.set("user_id", options.userId); if (options.limit !== undefined) params.set("limit", String(options.limit)); if (options.offset !== undefined) params.set("offset", String(options.offset)); + if (options.scopeFilter) params.set("scope_filter", options.scopeFilter); + if (options.ownershipFilter) params.set("ownership_filter", options.ownershipFilter); + if (options.parentThread) params.set("parent_thread", options.parentThread); + if (options.includeHidden) params.set("include_hidden", "true"); const query = params.toString(); const response = await this.request<{ threads: ChatThread[]; total_count: number }>( "GET", diff --git a/memorylayer-sdk-typescript/src/types.ts b/memorylayer-sdk-typescript/src/types.ts index 127d1ef..66ea166 100644 --- a/memorylayer-sdk-typescript/src/types.ts +++ b/memorylayer-sdk-typescript/src/types.ts @@ -199,6 +199,12 @@ export interface Association { created_at: string; } +/** Response of `POST /v1/sessions/{id}/touch`. */ +export interface SessionTouchResult { + /** New expiration timestamp (ISO 8601). */ + expires_at: string; +} + export interface Session { id: string; workspace_id: string; @@ -481,13 +487,25 @@ export enum RelationshipCategory { } export interface GraphTraverseOptions { + /** Filter by relationship types (omit or empty = all). */ relationshipTypes?: string[]; + /** + * @deprecated Not accepted by `POST /v1/memories/{id}/traverse`; ignored and + * no longer sent. Filter with `relationshipTypes` instead. + */ relationshipCategories?: RelationshipCategory[]; + /** Maximum traversal depth, 1-5 (server default 2). */ maxDepth?: number; + /** Traversal direction (server default "both"). */ direction?: "outgoing" | "incoming" | "both"; + /** Minimum edge strength, 0-1 (server default 0). */ minStrength?: number; + /** @deprecated Not accepted by the traverse endpoint; ignored and no longer sent. */ maxPaths?: number; + /** @deprecated Not accepted by the traverse endpoint; ignored and no longer sent. */ maxNodes?: number; + /** Override workspace for this traversal (defaults to the client workspace). */ + workspaceId?: string; } export interface GraphPath { @@ -505,21 +523,57 @@ export interface GraphQueryResult { } // Batch operations -export type BatchOperation = - | { op: "create"; memory: RememberOptions & { content: string } } - | { op: "update"; memory_id: string; updates: Partial & { content?: string } } - | { op: "delete"; memory_id: string; hard?: boolean }; +/** Create operation for `POST /v1/memories/batch` (flat, discriminated by `op`). */ +export interface BatchCreateOperation { + op: "create"; + content: string; + type?: MemoryType | string; + subtype?: MemorySubtype | string; + importance?: number; + tags?: string[]; + metadata?: Record; + observer_id?: string; + subject_id?: string; +} + +/** Update operation for `POST /v1/memories/batch`; omitted fields are left unchanged. */ +export interface BatchUpdateOperation { + op: "update"; + memory_id: string; + content?: string; + type?: MemoryType | string; + subtype?: MemorySubtype | string; + importance?: number; + tags?: string[]; + metadata?: Record; + pinned?: boolean; +} + +/** Delete operation for `POST /v1/memories/batch`. */ +export interface BatchDeleteOperation { + op: "delete"; + memory_id: string; + hard?: boolean; +} + +/** A single batch operation, sent to the server as-is. */ +export type BatchOperation = BatchCreateOperation | BatchUpdateOperation | BatchDeleteOperation; + +export interface BatchOperationResult { + index: number; + /** Operation type: "create" | "update" | "delete". */ + type: string; + /** "success" or "error". */ + status: string; + memory_id?: string | null; + error?: string | null; +} export interface BatchResult { - results: Array<{ - index: number; - success: boolean; - memory?: Memory; - error?: string; - }>; - total_processed: number; + total_operations: number; successful: number; failed: number; + results: BatchOperationResult[]; } // Association creation @@ -762,9 +816,21 @@ export interface ChatThread { expires_at?: string; created_at: string; updated_at: string; + /** Surface scope: "web" | "office" (null is equivalent to "web"). */ + scope?: string | null; + /** "user" (stored under the `_user_chat` home) or "workspace". */ + ownership?: string; + /** Parent thread id for sub-threads; null for top-level threads. */ + parent_thread?: string | null; + /** Idle policy: null (never idles out) | "hide" | "delete". */ + idle_action?: string | null; } +/** Storage home of user-owned chat threads (mirrors the server constant). */ +export const USER_CHAT_HOME_WORKSPACE = "_user_chat"; + export interface ThreadCreateOptions { + /** @deprecated Thread ids are server-generated; this value is ignored by the server. */ threadId?: string; workspaceId?: string; userId?: string; @@ -774,6 +840,19 @@ export interface ThreadCreateOptions { title?: string; metadata?: Record; expiresAt?: string; + /** Surface scope: "web" | "office" (omit for the server default). */ + scope?: string; + /** + * Thread ownership. When omitted the server default applies. When set to + * "user", the thread is stored under {@link USER_CHAT_HOME_WORKSPACE} + * (matching the Python and Go SDKs); "workspace" keeps it in the resolved + * workspace. + */ + ownership?: "user" | "workspace"; + /** Create a sub-thread of this thread (inherits its workspace and ownership). */ + parentThread?: string; + /** Idle policy: "hide" | "delete" (omit for never idling out). */ + idleAction?: "hide" | "delete"; } export interface ThreadListOptions { @@ -781,6 +860,14 @@ export interface ThreadListOptions { userId?: string; limit?: number; offset?: number; + /** Scope filter: "web" | "office" (omit for all). */ + scopeFilter?: "web" | "office"; + /** Ownership filter: "user" | "workspace" (omit for all). */ + ownershipFilter?: "user" | "workspace"; + /** List the sub-threads of this thread; omit for top-level threads only. */ + parentThread?: string; + /** Include archived/hidden threads. */ + includeHidden?: boolean; } export interface MessageAppendInput { diff --git a/memorylayer-sdk-typescript/tests/client.test.ts b/memorylayer-sdk-typescript/tests/client.test.ts index c8ce11e..678e797 100644 --- a/memorylayer-sdk-typescript/tests/client.test.ts +++ b/memorylayer-sdk-typescript/tests/client.test.ts @@ -508,19 +508,50 @@ describe("MemoryLayerClient", () => { method: "POST", }) ); + const body = JSON.parse((global.fetch as any).mock.calls[0][1].body); + expect(body).toEqual({ workspace_id: "ws-123", max_depth: 2 }); + }); + + it("should send only fields the traverse endpoint accepts", async () => { + (global.fetch as any).mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ paths: [], total_paths: 0, unique_nodes: [], query_latency_ms: 1 }), + }); + + await client.traverseGraph("mem-1", { + relationshipTypes: ["causes"], + relationshipCategories: ["causal" as any], + maxDepth: 3, + direction: "outgoing", + minStrength: 0.4, + maxPaths: 10, + maxNodes: 20, + workspaceId: "ws-other", + }); + + const body = JSON.parse((global.fetch as any).mock.calls[0][1].body); + expect(body).toEqual({ + workspace_id: "ws-other", + relationship_types: ["causes"], + max_depth: 3, + direction: "outgoing", + min_strength: 0.4, + }); }); }); describe("batch operations", () => { it("should batch memories", async () => { const mockResult = { + total_operations: 3, + successful: 3, + failed: 0, results: [ - { index: 0, success: true, memory: { id: "mem-1" } }, - { index: 1, success: true, memory: { id: "mem-2" } }, + { index: 0, type: "create", status: "success", memory_id: "mem-1", error: null }, + { index: 1, type: "update", status: "success", memory_id: "mem-2", error: null }, + { index: 2, type: "delete", status: "success", memory_id: "mem-3", error: null }, ], - total_processed: 2, - successful: 2, - failed: 0, }; (global.fetch as any).mockResolvedValueOnce({ @@ -529,10 +560,14 @@ describe("MemoryLayerClient", () => { json: async () => mockResult, }); - const result = await client.batchMemories([ - { action: "create", memory: { content: "Test 1" } }, - { action: "create", memory: { content: "Test 2" } }, - ]); + const operations = [ + { op: "create" as const, content: "Test 1", importance: 0.7, tags: ["a"] }, + { op: "update" as const, memory_id: "mem-2", tags: ["reviewed"], pinned: true }, + { op: "delete" as const, memory_id: "mem-3", hard: false }, + ]; + const result = await client.batchMemories(operations); + const body = JSON.parse((global.fetch as any).mock.calls[0][1].body); + expect(body).toEqual({ operations }); expect(result).toEqual(mockResult); expect(global.fetch).toHaveBeenCalledWith( @@ -543,4 +578,114 @@ describe("MemoryLayerClient", () => { ); }); }); + describe("touchSession", () => { + it("returns the new expiration and sends no body by default", async () => { + (global.fetch as any).mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ expires_at: "2026-01-01T01:00:00+00:00" }), + }); + + const result = await client.touchSession("sess-1"); + + expect(result).toEqual({ expires_at: "2026-01-01T01:00:00+00:00" }); + const [url, init] = (global.fetch as any).mock.calls[0]; + expect(url).toBe("http://localhost:61001/v1/sessions/sess-1/touch"); + expect(init.method).toBe("POST"); + expect(init.body).toBeUndefined(); + }); + + it("passes extendSeconds as the extend_seconds query parameter", async () => { + (global.fetch as any).mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ expires_at: "2026-01-01T02:00:00+00:00" }), + }); + + await client.touchSession("sess-1", 7200); + + const [url, init] = (global.fetch as any).mock.calls[0]; + expect(url).toBe("http://localhost:61001/v1/sessions/sess-1/touch?extend_seconds=7200"); + expect(init.body).toBeUndefined(); + }); + }); + + describe("chat threads", () => { + const thread = { + id: "thr-1", + workspace_id: "_user_chat", + tenant_id: "_default", + context_id: "_default", + metadata: {}, + message_count: 0, + last_decomposed_index: 0, + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + ownership: "user", + }; + + it("createThread forwards ownership, scope, parent thread and idle action", async () => { + (global.fetch as any).mockResolvedValueOnce({ ok: true, status: 201, json: async () => ({ thread }) }); + + const result = await client.createThread({ + workspaceId: "ws-app", + title: "Child", + scope: "office", + ownership: "user", + parentThread: "thr-parent", + idleAction: "hide", + }); + + expect(result.id).toBe("thr-1"); + const body = JSON.parse((global.fetch as any).mock.calls[0][1].body); + expect(body).toEqual({ + workspace_id: "_user_chat", + title: "Child", + scope: "office", + ownership: "user", + parent_thread: "thr-parent", + idle_action: "hide", + }); + }); + + it("createThread keeps the workspace for workspace-owned threads and by default", async () => { + (global.fetch as any).mockResolvedValue({ ok: true, status: 201, json: async () => ({ thread }) }); + + await client.createThread({ workspaceId: "ws-app", ownership: "workspace" }); + await client.createThread(); + + const first = JSON.parse((global.fetch as any).mock.calls[0][1].body); + const second = JSON.parse((global.fetch as any).mock.calls[1][1].body); + expect(first).toEqual({ workspace_id: "ws-app", ownership: "workspace" }); + expect(second).toEqual({ workspace_id: "ws-123" }); + }); + + it("listThreads sends scope, ownership, parent and hidden filters", async () => { + (global.fetch as any).mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ threads: [thread], total_count: 1 }), + }); + + const threads = await client.listThreads({ + scopeFilter: "web", + ownershipFilter: "workspace", + parentThread: "thr-parent", + includeHidden: true, + limit: 10, + }); + + expect(threads).toHaveLength(1); + const url = new URL((global.fetch as any).mock.calls[0][0]); + expect(url.pathname).toBe("/v1/threads"); + expect(Object.fromEntries(url.searchParams)).toEqual({ + workspace_id: "ws-123", + limit: "10", + scope_filter: "web", + ownership_filter: "workspace", + parent_thread: "thr-parent", + include_hidden: "true", + }); + }); + }); });