Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions memorylayer-explorer/src/hooks/use-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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] });
},
});
}
Expand Down
11 changes: 6 additions & 5 deletions memorylayer-sdk-typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand Down Expand Up @@ -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, {
Expand Down
46 changes: 32 additions & 14 deletions memorylayer-sdk-typescript/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -644,13 +645,18 @@ export class MemoryLayerClient {
);
}

async touchSession(sessionId: string, ttlSeconds?: number): Promise<Session> {
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<SessionTouchResult> {
const query = extendSeconds !== undefined
? `?${new URLSearchParams({ extend_seconds: String(extendSeconds) }).toString()}`
: "";
return this.request<SessionTouchResult>(
"POST",
`/v1/sessions/${sessionId}/touch`,
ttlSeconds ? { ttl_seconds: ttlSeconds } : {}
`/v1/sessions/${sessionId}/touch${query}`,
);
return response.session;
}

async getBriefing(
Expand Down Expand Up @@ -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<GraphQueryResult> {
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<GraphQueryResult>("POST", `/v1/memories/${startMemoryId}/traverse`, body);
}
Expand Down Expand Up @@ -1386,16 +1392,24 @@ export class MemoryLayerClient {
// ------------------------------------------------------------------ //

async createThread(options: ThreadCreateOptions = {}): Promise<ChatThread> {
// 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,
subject_id: options.subjectId,
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;
Expand All @@ -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",
Expand Down
109 changes: 98 additions & 11 deletions memorylayer-sdk-typescript/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand All @@ -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<RememberOptions> & { 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<string, unknown>;
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<string, unknown>;
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
Expand Down Expand Up @@ -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;
Expand All @@ -774,13 +840,34 @@ export interface ThreadCreateOptions {
title?: string;
metadata?: Record<string, unknown>;
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 {
workspaceId?: string;
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 {
Expand Down
Loading
Loading