@aumos/agent-session-linker 0.1.0

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,100 @@
1
+ /**
2
+ * HTTP client for the agent-session-linker session management API.
3
+ *
4
+ * Uses the Fetch API (available natively in Node 18+, browsers, and Deno).
5
+ * No external dependencies required.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { createAgentSessionLinkerClient } from "@aumos/agent-session-linker";
10
+ *
11
+ * const client = createAgentSessionLinkerClient({ baseUrl: "http://localhost:8091" });
12
+ *
13
+ * const session = await client.createSession({ agent_id: "my-agent" });
14
+ * if (session.ok) {
15
+ * console.log("Session created:", session.data.session_id);
16
+ * }
17
+ * ```
18
+ */
19
+ import type { ApiResult, CreateSessionRequest, ResumptionToken, ResumeSessionRequest, SaveContextRequest, SessionState, SessionStats, SessionSummary } from "./types.js";
20
+ /** Configuration options for the AgentSessionLinkerClient. */
21
+ export interface AgentSessionLinkerClientConfig {
22
+ /** Base URL of the agent-session-linker server (e.g. "http://localhost:8091"). */
23
+ readonly baseUrl: string;
24
+ /** Optional request timeout in milliseconds (default: 30000). */
25
+ readonly timeoutMs?: number;
26
+ /** Optional extra HTTP headers sent with every request. */
27
+ readonly headers?: Readonly<Record<string, string>>;
28
+ }
29
+ /** Typed HTTP client for the agent-session-linker server. */
30
+ export interface AgentSessionLinkerClient {
31
+ /**
32
+ * Create a new agent session.
33
+ *
34
+ * @param request - Optional session creation parameters including agent_id and preferences.
35
+ * @returns The newly created SessionState record.
36
+ */
37
+ createSession(request?: CreateSessionRequest): Promise<ApiResult<SessionState>>;
38
+ /**
39
+ * Retrieve a session by its unique identifier.
40
+ *
41
+ * @param sessionId - The session to retrieve.
42
+ * @returns The full SessionState for the requested session.
43
+ */
44
+ getSession(sessionId: string): Promise<ApiResult<SessionState>>;
45
+ /**
46
+ * Resume a session using a previously issued resumption token.
47
+ *
48
+ * @param request - Contains the opaque resumption token.
49
+ * @returns The deserialised SessionState linked to the token.
50
+ */
51
+ resumeSession(request: ResumeSessionRequest): Promise<ApiResult<SessionState>>;
52
+ /**
53
+ * Save or update the context payload for an existing session.
54
+ *
55
+ * @param request - Contains the session_id and partial context fields to update.
56
+ * @returns The updated SessionState after the save operation.
57
+ */
58
+ saveContext(request: SaveContextRequest): Promise<ApiResult<SessionState>>;
59
+ /**
60
+ * List all sessions, optionally filtered by agent identifier.
61
+ *
62
+ * @param options - Optional filter parameters.
63
+ * @returns Array of SessionSummary records ordered by creation time descending.
64
+ */
65
+ listSessions(options?: {
66
+ readonly agentId?: string;
67
+ readonly limit?: number;
68
+ }): Promise<ApiResult<readonly SessionSummary[]>>;
69
+ /**
70
+ * Delete a session from the session store.
71
+ *
72
+ * @param sessionId - The session to delete.
73
+ * @returns An empty object on successful deletion.
74
+ */
75
+ deleteSession(sessionId: string): Promise<ApiResult<Readonly<Record<string, never>>>>;
76
+ /**
77
+ * Generate a resumption token for a session to enable cross-boundary transfer.
78
+ *
79
+ * @param sessionId - The session for which to generate a token.
80
+ * @param options - Optional token lifetime in seconds (default: 3600).
81
+ * @returns A ResumptionToken that can be serialised and passed to resumeSession().
82
+ */
83
+ getResumptionToken(sessionId: string, options?: {
84
+ readonly ttlSeconds?: number;
85
+ }): Promise<ApiResult<ResumptionToken>>;
86
+ /**
87
+ * Retrieve aggregate statistics across all stored sessions.
88
+ *
89
+ * @returns A SessionStats record with totals and agent breakdown.
90
+ */
91
+ getStats(): Promise<ApiResult<SessionStats>>;
92
+ }
93
+ /**
94
+ * Create a typed HTTP client for the agent-session-linker server.
95
+ *
96
+ * @param config - Client configuration including base URL.
97
+ * @returns An AgentSessionLinkerClient instance.
98
+ */
99
+ export declare function createAgentSessionLinkerClient(config: AgentSessionLinkerClientConfig): AgentSessionLinkerClient;
100
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA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AC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAEtF;;;;;;OAMG;IACH,kBAAkB,CAChB,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,GACzC,OAAO,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC,CAAC;IAEvC;;;;OAIG;IACH,QAAQ,IAAI,OAAO,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC;CAC9C;AAMD;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAC5C,MAAM,EAAE,8BAA8B,GACrC,wBAAwB,CAkH1B"}
package/dist/client.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * HTTP client for the agent-session-linker session management API.
3
+ *
4
+ * Uses the Fetch API (available natively in Node 18+, browsers, and Deno).
5
+ * No external dependencies required.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { createAgentSessionLinkerClient } from "@aumos/agent-session-linker";
10
+ *
11
+ * const client = createAgentSessionLinkerClient({ baseUrl: "http://localhost:8091" });
12
+ *
13
+ * const session = await client.createSession({ agent_id: "my-agent" });
14
+ * if (session.ok) {
15
+ * console.log("Session created:", session.data.session_id);
16
+ * }
17
+ * ```
18
+ */
19
+ // ---------------------------------------------------------------------------
20
+ // Internal helpers
21
+ // ---------------------------------------------------------------------------
22
+ async function fetchJson(url, init, timeoutMs) {
23
+ const controller = new AbortController();
24
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
25
+ try {
26
+ const response = await fetch(url, { ...init, signal: controller.signal });
27
+ clearTimeout(timeoutId);
28
+ const body = await response.json();
29
+ if (!response.ok) {
30
+ const errorBody = body;
31
+ return {
32
+ ok: false,
33
+ error: {
34
+ error: errorBody.error ?? "Unknown error",
35
+ detail: errorBody.detail ?? "",
36
+ },
37
+ status: response.status,
38
+ };
39
+ }
40
+ return { ok: true, data: body };
41
+ }
42
+ catch (err) {
43
+ clearTimeout(timeoutId);
44
+ const message = err instanceof Error ? err.message : String(err);
45
+ return {
46
+ ok: false,
47
+ error: { error: "Network error", detail: message },
48
+ status: 0,
49
+ };
50
+ }
51
+ }
52
+ function buildHeaders(extraHeaders) {
53
+ return {
54
+ "Content-Type": "application/json",
55
+ Accept: "application/json",
56
+ ...extraHeaders,
57
+ };
58
+ }
59
+ // ---------------------------------------------------------------------------
60
+ // Client factory
61
+ // ---------------------------------------------------------------------------
62
+ /**
63
+ * Create a typed HTTP client for the agent-session-linker server.
64
+ *
65
+ * @param config - Client configuration including base URL.
66
+ * @returns An AgentSessionLinkerClient instance.
67
+ */
68
+ export function createAgentSessionLinkerClient(config) {
69
+ const { baseUrl, timeoutMs = 30000, headers: extraHeaders } = config;
70
+ const baseHeaders = buildHeaders(extraHeaders);
71
+ return {
72
+ async createSession(request) {
73
+ return fetchJson(`${baseUrl}/sessions`, {
74
+ method: "POST",
75
+ headers: baseHeaders,
76
+ body: JSON.stringify(request ?? {}),
77
+ }, timeoutMs);
78
+ },
79
+ async getSession(sessionId) {
80
+ return fetchJson(`${baseUrl}/sessions/${encodeURIComponent(sessionId)}`, { method: "GET", headers: baseHeaders }, timeoutMs);
81
+ },
82
+ async resumeSession(request) {
83
+ return fetchJson(`${baseUrl}/sessions/resume`, {
84
+ method: "POST",
85
+ headers: baseHeaders,
86
+ body: JSON.stringify(request),
87
+ }, timeoutMs);
88
+ },
89
+ async saveContext(request) {
90
+ return fetchJson(`${baseUrl}/sessions/${encodeURIComponent(request.session_id)}/context`, {
91
+ method: "PATCH",
92
+ headers: baseHeaders,
93
+ body: JSON.stringify(request.context),
94
+ }, timeoutMs);
95
+ },
96
+ async listSessions(options) {
97
+ const params = new URLSearchParams();
98
+ if (options?.agentId !== undefined) {
99
+ params.set("agent_id", options.agentId);
100
+ }
101
+ if (options?.limit !== undefined) {
102
+ params.set("limit", String(options.limit));
103
+ }
104
+ const queryString = params.toString();
105
+ const url = queryString
106
+ ? `${baseUrl}/sessions?${queryString}`
107
+ : `${baseUrl}/sessions`;
108
+ return fetchJson(url, { method: "GET", headers: baseHeaders }, timeoutMs);
109
+ },
110
+ async deleteSession(sessionId) {
111
+ return fetchJson(`${baseUrl}/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE", headers: baseHeaders }, timeoutMs);
112
+ },
113
+ async getResumptionToken(sessionId, options) {
114
+ const params = new URLSearchParams();
115
+ if (options?.ttlSeconds !== undefined) {
116
+ params.set("ttl_seconds", String(options.ttlSeconds));
117
+ }
118
+ const queryString = params.toString();
119
+ const url = queryString
120
+ ? `${baseUrl}/sessions/${encodeURIComponent(sessionId)}/token?${queryString}`
121
+ : `${baseUrl}/sessions/${encodeURIComponent(sessionId)}/token`;
122
+ return fetchJson(url, { method: "POST", headers: baseHeaders, body: JSON.stringify({}) }, timeoutMs);
123
+ },
124
+ async getStats() {
125
+ return fetchJson(`${baseUrl}/sessions/stats`, { method: "GET", headers: baseHeaders }, timeoutMs);
126
+ },
127
+ };
128
+ }
129
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AA4BH,8EAA8E;AAC9E,mBAAmB;AACnB,8EAA8E;AAE9E,KAAK,UAAU,SAAS,CACtB,GAAW,EACX,IAAiB,EACjB,SAAiB;IAEjB,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,SAAS,CAAC,CAAC;IAElE,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC,CAAC;QAC1E,YAAY,CAAC,SAAS,CAAC,CAAC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AAE,CAAC,EAAE,EAClE,SAAS,CACV,CAAC;QACJ,CAAC;QAED,KAAK,CAAC,QAAQ;YACZ,OAAO,SAAS,CACd,GAAG,OAAO,iBAAiB,EAC3B,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,EACvC,SAAS,CACV,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @aumos/agent-session-linker
3
+ *
4
+ * TypeScript client for the AumOS agent-session-linker library.
5
+ * Provides HTTP client and session type definitions for cross-session
6
+ * context persistence, resumption tokens, and session lifecycle management.
7
+ */
8
+ export type { AgentSessionLinkerClient, AgentSessionLinkerClientConfig } from "./client.js";
9
+ export { createAgentSessionLinkerClient } from "./client.js";
10
+ export type { TaskStatus, ContextSegment, EntityReference, TaskState, ToolContext, SessionState, CreateSessionRequest, ResumeSessionRequest, SaveContextRequest, ResumptionToken, SessionSummary, SessionStats, ApiError, ApiResult, } from "./types.js";
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,YAAY,EAAE,wBAAwB,EAAE,8BAA8B,EAAE,MAAM,aAAa,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,aAAa,CAAC;AAG7D,YAAY,EACV,UAAU,EACV,cAAc,EACd,eAAe,EACf,SAAS,EACT,WAAW,EACX,YAAY,EACZ,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,YAAY,EACZ,QAAQ,EACR,SAAS,GACV,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @aumos/agent-session-linker
3
+ *
4
+ * TypeScript client for the AumOS agent-session-linker library.
5
+ * Provides HTTP client and session type definitions for cross-session
6
+ * context persistence, resumption tokens, and session lifecycle management.
7
+ */
8
+ export { createAgentSessionLinkerClient } from "./client.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,EAAE,8BAA8B,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,227 @@
1
+ /**
2
+ * TypeScript interfaces for the agent-session-linker session management library.
3
+ *
4
+ * Mirrors the Pydantic models defined in:
5
+ * agent_session_linker.session.state
6
+ * agent_session_linker.session.manager
7
+ * agent_session_linker.session.serializer
8
+ *
9
+ * All interfaces use readonly fields to match Python's frozen Pydantic models.
10
+ */
11
+ /**
12
+ * Lifecycle state of a tracked task within a session.
13
+ * Maps to TaskStatus enum in Python.
14
+ */
15
+ export type TaskStatus = "pending" | "in_progress" | "completed" | "failed" | "cancelled";
16
+ /**
17
+ * A discrete unit of context captured from a single conversation turn.
18
+ * Maps to ContextSegment in Python.
19
+ */
20
+ export interface ContextSegment {
21
+ /** Unique identifier for this segment. */
22
+ readonly segment_id: string;
23
+ /** Message role: "user", "assistant", "system", or "tool". */
24
+ readonly role: string;
25
+ /** Raw text content of the segment. */
26
+ readonly content: string;
27
+ /** Estimated token count for this segment. */
28
+ readonly token_count: number;
29
+ /** Categorical label such as "conversation", "reasoning", "code", "plan", "output", or "metadata". */
30
+ readonly segment_type: string;
31
+ /** ISO-8601 UTC timestamp when this segment was captured. */
32
+ readonly timestamp: string;
33
+ /** Zero-based index of the conversation turn this segment belongs to. */
34
+ readonly turn_index: number;
35
+ /** Arbitrary additional key-value data attached to this segment. */
36
+ readonly metadata: Readonly<Record<string, string>>;
37
+ }
38
+ /**
39
+ * A cross-session pointer to a tracked domain entity.
40
+ * Maps to EntityReference in Python.
41
+ */
42
+ export interface EntityReference {
43
+ /** Unique identifier for this entity record. */
44
+ readonly entity_id: string;
45
+ /** Primary normalised name used for matching. */
46
+ readonly canonical_name: string;
47
+ /** Categorical label such as "person", "project", "file", "concept", "tool", or "organisation". */
48
+ readonly entity_type: string;
49
+ /** Alternative names or spellings for this entity. */
50
+ readonly aliases: readonly string[];
51
+ /** Key-value attributes describing the entity. */
52
+ readonly attributes: Readonly<Record<string, string>>;
53
+ /** Session ID where this entity was first observed. */
54
+ readonly first_seen_session: string;
55
+ /** Session ID where this entity was most recently observed. */
56
+ readonly last_seen_session: string;
57
+ /** Match/extraction confidence in the range [0.0, 1.0]. */
58
+ readonly confidence: number;
59
+ }
60
+ /**
61
+ * A tracked task with its current lifecycle status.
62
+ * Maps to TaskState in Python.
63
+ */
64
+ export interface TaskState {
65
+ /** Unique identifier for this task. */
66
+ readonly task_id: string;
67
+ /** Short human-readable title. */
68
+ readonly title: string;
69
+ /** Detailed description of what the task requires. */
70
+ readonly description: string;
71
+ /** Current lifecycle status. */
72
+ readonly status: TaskStatus;
73
+ /** Integer priority where 1 is highest. Range [1, 10]. */
74
+ readonly priority: number;
75
+ /** ISO-8601 UTC timestamp when the task was first recorded. */
76
+ readonly created_at: string;
77
+ /** ISO-8601 UTC timestamp when the task was last modified. */
78
+ readonly updated_at: string;
79
+ /** Optional reference to a parent task for sub-task hierarchies. */
80
+ readonly parent_task_id: string | null;
81
+ /** Free-form labels for categorisation and filtering. */
82
+ readonly tags: readonly string[];
83
+ /** Additional free-text notes about the task. */
84
+ readonly notes: string;
85
+ }
86
+ /**
87
+ * A record of a single tool invocation within a session.
88
+ * Maps to ToolContext in Python.
89
+ */
90
+ export interface ToolContext {
91
+ /** Unique identifier for this invocation. */
92
+ readonly invocation_id: string;
93
+ /** Name of the tool that was called. */
94
+ readonly tool_name: string;
95
+ /** Brief summary of the input arguments (not the full payload). */
96
+ readonly input_summary: string;
97
+ /** Brief summary of the output returned. */
98
+ readonly output_summary: string;
99
+ /** Wall-clock execution time in milliseconds. */
100
+ readonly duration_ms: number;
101
+ /** Whether the invocation completed without error. */
102
+ readonly success: boolean;
103
+ /** Error description when success is false. */
104
+ readonly error_message: string;
105
+ /** ISO-8601 UTC timestamp when the invocation started. */
106
+ readonly timestamp: string;
107
+ /** Tokens consumed by the tool call, if measurable. */
108
+ readonly token_cost: number;
109
+ }
110
+ /**
111
+ * Complete snapshot of an agent session.
112
+ * Maps to SessionState in Python.
113
+ */
114
+ export interface SessionState {
115
+ /** Globally unique session identifier. */
116
+ readonly session_id: string;
117
+ /** Identifier for the agent or agent-type that owns this session. */
118
+ readonly agent_id: string;
119
+ /** Schema version string used for forward/backward compatibility. */
120
+ readonly schema_version: string;
121
+ /** Ordered list of conversation context segments. */
122
+ readonly segments: readonly ContextSegment[];
123
+ /** Named entities tracked within this session. */
124
+ readonly entities: readonly EntityReference[];
125
+ /** Tasks created or referenced during this session. */
126
+ readonly tasks: readonly TaskState[];
127
+ /** Chronological log of tool invocations. */
128
+ readonly tools_used: readonly ToolContext[];
129
+ /** Agent or user preferences captured during the session. */
130
+ readonly preferences: Readonly<Record<string, string>>;
131
+ /** Optional compressed summary of the session's key content. */
132
+ readonly summary: string;
133
+ /** If this is a continuation, the ID of the preceding session. */
134
+ readonly parent_session_id: string | null;
135
+ /** Accumulated LLM API cost in USD for this session. */
136
+ readonly total_cost_usd: number;
137
+ /** ISO-8601 UTC timestamp of session creation. */
138
+ readonly created_at: string;
139
+ /** ISO-8601 UTC timestamp of last modification. */
140
+ readonly updated_at: string;
141
+ /** SHA-256 of the session's canonical JSON (excluding this field). */
142
+ readonly checksum: string;
143
+ }
144
+ /** Configuration for creating a new session. */
145
+ export interface CreateSessionRequest {
146
+ /** Agent identifier that owns this session. */
147
+ readonly agent_id?: string;
148
+ /** Optional parent session to create a continuation from. */
149
+ readonly parent_session_id?: string;
150
+ /** Initial preference key-value pairs. */
151
+ readonly preferences?: Readonly<Record<string, string>>;
152
+ }
153
+ /** Request to resume a session using a resumption token. */
154
+ export interface ResumeSessionRequest {
155
+ /** The opaque resumption token previously issued by the server. */
156
+ readonly resumption_token: string;
157
+ }
158
+ /** Request to save a serialised context payload. */
159
+ export interface SaveContextRequest {
160
+ /** The session ID to update. */
161
+ readonly session_id: string;
162
+ /** Partial or full updated session state fields. */
163
+ readonly context: Partial<Pick<SessionState, "segments" | "entities" | "tasks" | "tools_used" | "preferences" | "summary" | "total_cost_usd">>;
164
+ }
165
+ /**
166
+ * An opaque token that enables resuming a serialised session across boundaries.
167
+ * Maps to the resumption token concept in agent_session_linker.portable.
168
+ */
169
+ export interface ResumptionToken {
170
+ /** The token value to pass to resumeSession(). */
171
+ readonly token: string;
172
+ /** Session ID this token references. */
173
+ readonly session_id: string;
174
+ /** ISO-8601 UTC timestamp after which this token expires. */
175
+ readonly expires_at: string;
176
+ /** Schema version of the serialised payload. */
177
+ readonly schema_version: string;
178
+ }
179
+ /** Summary information returned when listing sessions. */
180
+ export interface SessionSummary {
181
+ /** Unique session identifier. */
182
+ readonly session_id: string;
183
+ /** Agent that owns this session. */
184
+ readonly agent_id: string;
185
+ /** ISO-8601 UTC creation timestamp. */
186
+ readonly created_at: string;
187
+ /** ISO-8601 UTC last-update timestamp. */
188
+ readonly updated_at: string;
189
+ /** Total number of context segments. */
190
+ readonly segment_count: number;
191
+ /** Total number of tracked tasks. */
192
+ readonly task_count: number;
193
+ /** Whether this session has a parent (is a continuation). */
194
+ readonly is_continuation: boolean;
195
+ }
196
+ /** Aggregate statistics across all stored sessions. */
197
+ export interface SessionStats {
198
+ /** Total number of stored sessions. */
199
+ readonly total_sessions: number;
200
+ /** Sum of all segment counts across sessions. */
201
+ readonly total_segments: number;
202
+ /** Sum of all token counts across sessions. */
203
+ readonly total_tokens: number;
204
+ /** Sum of all task counts across sessions. */
205
+ readonly total_tasks: number;
206
+ /** Sum of all entity counts across sessions. */
207
+ readonly total_entities: number;
208
+ /** Summed cost across all sessions in USD. */
209
+ readonly total_cost_usd: number;
210
+ /** List of unique agent IDs that have sessions. */
211
+ readonly agents: readonly string[];
212
+ }
213
+ /** Standard error payload returned by the agent-session-linker API. */
214
+ export interface ApiError {
215
+ readonly error: string;
216
+ readonly detail: string;
217
+ }
218
+ /** Result type for all client operations. */
219
+ export type ApiResult<T> = {
220
+ readonly ok: true;
221
+ readonly data: T;
222
+ } | {
223
+ readonly ok: false;
224
+ readonly error: ApiError;
225
+ readonly status: number;
226
+ };
227
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH;;;GAGG;AACH,MAAM,MAAM,UAAU,GAClB,SAAS,GACT,aAAa,GACb,WAAW,GACX,QAAQ,GACR,WAAW,CAAC;AAMhB;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,0CAA0C;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,8DAA8D;IAC9D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,uCAAuC;IACvC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,8CAA8C;IAC9C,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,sGAAsG;IACtG,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,yEAAyE;IACzE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,oEAAoE;IACpE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACrD;AAMD;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC9B,gDAAgD;IAChD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,iDAAiD;IACjD,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,mGAAmG;IACnG,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,sDAAsD;IACtD,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE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
+ *
4
+ * Mirrors the Pydantic models defined in:
5
+ * agent_session_linker.session.state
6
+ * agent_session_linker.session.manager
7
+ * agent_session_linker.session.serializer
8
+ *
9
+ * All interfaces use readonly fields to match Python's frozen Pydantic models.
10
+ */
11
+ export {};
12
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@aumos/agent-session-linker",
3
+ "version": "0.1.0",
4
+ "description": "TypeScript client for the AumOS agent-session-linker — cross-session context persistence, resumption tokens, and session lifecycle management",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.js",
12
+ "types": "./dist/index.d.ts"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "build": "tsc",
17
+ "typecheck": "tsc --noEmit"
18
+ },
19
+ "devDependencies": {
20
+ "typescript": "^5.3.0"
21
+ },
22
+ "keywords": [
23
+ "aumos",
24
+ "agent-session-linker",
25
+ "session",
26
+ "context",
27
+ "resumption",
28
+ "typescript"
29
+ ],
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/aumos-ai/agent-session-linker"
33
+ }
34
+ }
package/src/client.ts ADDED
@@ -0,0 +1,302 @@
1
+ /**
2
+ * HTTP client for the agent-session-linker session management API.
3
+ *
4
+ * Uses the Fetch API (available natively in Node 18+, browsers, and Deno).
5
+ * No external dependencies required.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { createAgentSessionLinkerClient } from "@aumos/agent-session-linker";
10
+ *
11
+ * const client = createAgentSessionLinkerClient({ baseUrl: "http://localhost:8091" });
12
+ *
13
+ * const session = await client.createSession({ agent_id: "my-agent" });
14
+ * if (session.ok) {
15
+ * console.log("Session created:", session.data.session_id);
16
+ * }
17
+ * ```
18
+ */
19
+
20
+ import type {
21
+ ApiError,
22
+ ApiResult,
23
+ CreateSessionRequest,
24
+ ResumptionToken,
25
+ ResumeSessionRequest,
26
+ SaveContextRequest,
27
+ SessionState,
28
+ SessionStats,
29
+ SessionSummary,
30
+ } from "./types.js";
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Client configuration
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /** Configuration options for the AgentSessionLinkerClient. */
37
+ export interface AgentSessionLinkerClientConfig {
38
+ /** Base URL of the agent-session-linker server (e.g. "http://localhost:8091"). */
39
+ readonly baseUrl: string;
40
+ /** Optional request timeout in milliseconds (default: 30000). */
41
+ readonly timeoutMs?: number;
42
+ /** Optional extra HTTP headers sent with every request. */
43
+ readonly headers?: Readonly<Record<string, string>>;
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // Internal helpers
48
+ // ---------------------------------------------------------------------------
49
+
50
+ async function fetchJson<T>(
51
+ url: string,
52
+ init: RequestInit,
53
+ timeoutMs: number,
54
+ ): Promise<ApiResult<T>> {
55
+ const controller = new AbortController();
56
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
57
+
58
+ try {
59
+ const response = await fetch(url, { ...init, signal: controller.signal });
60
+ clearTimeout(timeoutId);
61
+
62
+ const body = await response.json() as unknown;
63
+
64
+ if (!response.ok) {
65
+ const errorBody = body as Partial<ApiError>;
66
+ return {
67
+ ok: false,
68
+ error: {
69
+ error: errorBody.error ?? "Unknown error",
70
+ detail: errorBody.detail ?? "",
71
+ },
72
+ status: response.status,
73
+ };
74
+ }
75
+
76
+ return { ok: true, data: body as T };
77
+ } catch (err: unknown) {
78
+ clearTimeout(timeoutId);
79
+ const message = err instanceof Error ? err.message : String(err);
80
+ return {
81
+ ok: false,
82
+ error: { error: "Network error", detail: message },
83
+ status: 0,
84
+ };
85
+ }
86
+ }
87
+
88
+ function buildHeaders(
89
+ extraHeaders: Readonly<Record<string, string>> | undefined,
90
+ ): Record<string, string> {
91
+ return {
92
+ "Content-Type": "application/json",
93
+ Accept: "application/json",
94
+ ...extraHeaders,
95
+ };
96
+ }
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // Client interface
100
+ // ---------------------------------------------------------------------------
101
+
102
+ /** Typed HTTP client for the agent-session-linker server. */
103
+ export interface AgentSessionLinkerClient {
104
+ /**
105
+ * Create a new agent session.
106
+ *
107
+ * @param request - Optional session creation parameters including agent_id and preferences.
108
+ * @returns The newly created SessionState record.
109
+ */
110
+ createSession(request?: CreateSessionRequest): Promise<ApiResult<SessionState>>;
111
+
112
+ /**
113
+ * Retrieve a session by its unique identifier.
114
+ *
115
+ * @param sessionId - The session to retrieve.
116
+ * @returns The full SessionState for the requested session.
117
+ */
118
+ getSession(sessionId: string): Promise<ApiResult<SessionState>>;
119
+
120
+ /**
121
+ * Resume a session using a previously issued resumption token.
122
+ *
123
+ * @param request - Contains the opaque resumption token.
124
+ * @returns The deserialised SessionState linked to the token.
125
+ */
126
+ resumeSession(request: ResumeSessionRequest): Promise<ApiResult<SessionState>>;
127
+
128
+ /**
129
+ * Save or update the context payload for an existing session.
130
+ *
131
+ * @param request - Contains the session_id and partial context fields to update.
132
+ * @returns The updated SessionState after the save operation.
133
+ */
134
+ saveContext(request: SaveContextRequest): Promise<ApiResult<SessionState>>;
135
+
136
+ /**
137
+ * List all sessions, optionally filtered by agent identifier.
138
+ *
139
+ * @param options - Optional filter parameters.
140
+ * @returns Array of SessionSummary records ordered by creation time descending.
141
+ */
142
+ listSessions(options?: {
143
+ readonly agentId?: string;
144
+ readonly limit?: number;
145
+ }): Promise<ApiResult<readonly SessionSummary[]>>;
146
+
147
+ /**
148
+ * Delete a session from the session store.
149
+ *
150
+ * @param sessionId - The session to delete.
151
+ * @returns An empty object on successful deletion.
152
+ */
153
+ deleteSession(sessionId: string): Promise<ApiResult<Readonly<Record<string, never>>>>;
154
+
155
+ /**
156
+ * Generate a resumption token for a session to enable cross-boundary transfer.
157
+ *
158
+ * @param sessionId - The session for which to generate a token.
159
+ * @param options - Optional token lifetime in seconds (default: 3600).
160
+ * @returns A ResumptionToken that can be serialised and passed to resumeSession().
161
+ */
162
+ getResumptionToken(
163
+ sessionId: string,
164
+ options?: { readonly ttlSeconds?: number },
165
+ ): Promise<ApiResult<ResumptionToken>>;
166
+
167
+ /**
168
+ * Retrieve aggregate statistics across all stored sessions.
169
+ *
170
+ * @returns A SessionStats record with totals and agent breakdown.
171
+ */
172
+ getStats(): Promise<ApiResult<SessionStats>>;
173
+ }
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // Client factory
177
+ // ---------------------------------------------------------------------------
178
+
179
+ /**
180
+ * Create a typed HTTP client for the agent-session-linker server.
181
+ *
182
+ * @param config - Client configuration including base URL.
183
+ * @returns An AgentSessionLinkerClient instance.
184
+ */
185
+ export function createAgentSessionLinkerClient(
186
+ config: AgentSessionLinkerClientConfig,
187
+ ): AgentSessionLinkerClient {
188
+ const { baseUrl, timeoutMs = 30_000, headers: extraHeaders } = config;
189
+ const baseHeaders = buildHeaders(extraHeaders);
190
+
191
+ return {
192
+ async createSession(
193
+ request?: CreateSessionRequest,
194
+ ): Promise<ApiResult<SessionState>> {
195
+ return fetchJson<SessionState>(
196
+ `${baseUrl}/sessions`,
197
+ {
198
+ method: "POST",
199
+ headers: baseHeaders,
200
+ body: JSON.stringify(request ?? {}),
201
+ },
202
+ timeoutMs,
203
+ );
204
+ },
205
+
206
+ async getSession(sessionId: string): Promise<ApiResult<SessionState>> {
207
+ return fetchJson<SessionState>(
208
+ `${baseUrl}/sessions/${encodeURIComponent(sessionId)}`,
209
+ { method: "GET", headers: baseHeaders },
210
+ timeoutMs,
211
+ );
212
+ },
213
+
214
+ async resumeSession(
215
+ request: ResumeSessionRequest,
216
+ ): Promise<ApiResult<SessionState>> {
217
+ return fetchJson<SessionState>(
218
+ `${baseUrl}/sessions/resume`,
219
+ {
220
+ method: "POST",
221
+ headers: baseHeaders,
222
+ body: JSON.stringify(request),
223
+ },
224
+ timeoutMs,
225
+ );
226
+ },
227
+
228
+ async saveContext(
229
+ request: SaveContextRequest,
230
+ ): Promise<ApiResult<SessionState>> {
231
+ return fetchJson<SessionState>(
232
+ `${baseUrl}/sessions/${encodeURIComponent(request.session_id)}/context`,
233
+ {
234
+ method: "PATCH",
235
+ headers: baseHeaders,
236
+ body: JSON.stringify(request.context),
237
+ },
238
+ timeoutMs,
239
+ );
240
+ },
241
+
242
+ async listSessions(options?: {
243
+ readonly agentId?: string;
244
+ readonly limit?: number;
245
+ }): Promise<ApiResult<readonly SessionSummary[]>> {
246
+ const params = new URLSearchParams();
247
+ if (options?.agentId !== undefined) {
248
+ params.set("agent_id", options.agentId);
249
+ }
250
+ if (options?.limit !== undefined) {
251
+ params.set("limit", String(options.limit));
252
+ }
253
+ const queryString = params.toString();
254
+ const url = queryString
255
+ ? `${baseUrl}/sessions?${queryString}`
256
+ : `${baseUrl}/sessions`;
257
+ return fetchJson<readonly SessionSummary[]>(
258
+ url,
259
+ { method: "GET", headers: baseHeaders },
260
+ timeoutMs,
261
+ );
262
+ },
263
+
264
+ async deleteSession(
265
+ sessionId: string,
266
+ ): Promise<ApiResult<Readonly<Record<string, never>>>> {
267
+ return fetchJson<Readonly<Record<string, never>>>(
268
+ `${baseUrl}/sessions/${encodeURIComponent(sessionId)}`,
269
+ { method: "DELETE", headers: baseHeaders },
270
+ timeoutMs,
271
+ );
272
+ },
273
+
274
+ async getResumptionToken(
275
+ sessionId: string,
276
+ options?: { readonly ttlSeconds?: number },
277
+ ): Promise<ApiResult<ResumptionToken>> {
278
+ const params = new URLSearchParams();
279
+ if (options?.ttlSeconds !== undefined) {
280
+ params.set("ttl_seconds", String(options.ttlSeconds));
281
+ }
282
+ const queryString = params.toString();
283
+ const url = queryString
284
+ ? `${baseUrl}/sessions/${encodeURIComponent(sessionId)}/token?${queryString}`
285
+ : `${baseUrl}/sessions/${encodeURIComponent(sessionId)}/token`;
286
+ return fetchJson<ResumptionToken>(
287
+ url,
288
+ { method: "POST", headers: baseHeaders, body: JSON.stringify({}) },
289
+ timeoutMs,
290
+ );
291
+ },
292
+
293
+ async getStats(): Promise<ApiResult<SessionStats>> {
294
+ return fetchJson<SessionStats>(
295
+ `${baseUrl}/sessions/stats`,
296
+ { method: "GET", headers: baseHeaders },
297
+ timeoutMs,
298
+ );
299
+ },
300
+ };
301
+ }
302
+
package/src/index.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @aumos/agent-session-linker
3
+ *
4
+ * TypeScript client for the AumOS agent-session-linker library.
5
+ * Provides HTTP client and session type definitions for cross-session
6
+ * context persistence, resumption tokens, and session lifecycle management.
7
+ */
8
+
9
+ // Client and configuration
10
+ export type { AgentSessionLinkerClient, AgentSessionLinkerClientConfig } from "./client.js";
11
+ export { createAgentSessionLinkerClient } from "./client.js";
12
+
13
+ // Core types
14
+ export type {
15
+ TaskStatus,
16
+ ContextSegment,
17
+ EntityReference,
18
+ TaskState,
19
+ ToolContext,
20
+ SessionState,
21
+ CreateSessionRequest,
22
+ ResumeSessionRequest,
23
+ SaveContextRequest,
24
+ ResumptionToken,
25
+ SessionSummary,
26
+ SessionStats,
27
+ ApiError,
28
+ ApiResult,
29
+ } from "./types.js";
package/src/types.ts ADDED
@@ -0,0 +1,286 @@
1
+ /**
2
+ * TypeScript interfaces for the agent-session-linker session management library.
3
+ *
4
+ * Mirrors the Pydantic models defined in:
5
+ * agent_session_linker.session.state
6
+ * agent_session_linker.session.manager
7
+ * agent_session_linker.session.serializer
8
+ *
9
+ * All interfaces use readonly fields to match Python's frozen Pydantic models.
10
+ */
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Task lifecycle
14
+ // ---------------------------------------------------------------------------
15
+
16
+ /**
17
+ * Lifecycle state of a tracked task within a session.
18
+ * Maps to TaskStatus enum in Python.
19
+ */
20
+ export type TaskStatus =
21
+ | "pending"
22
+ | "in_progress"
23
+ | "completed"
24
+ | "failed"
25
+ | "cancelled";
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Context segment
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /**
32
+ * A discrete unit of context captured from a single conversation turn.
33
+ * Maps to ContextSegment in Python.
34
+ */
35
+ export interface ContextSegment {
36
+ /** Unique identifier for this segment. */
37
+ readonly segment_id: string;
38
+ /** Message role: "user", "assistant", "system", or "tool". */
39
+ readonly role: string;
40
+ /** Raw text content of the segment. */
41
+ readonly content: string;
42
+ /** Estimated token count for this segment. */
43
+ readonly token_count: number;
44
+ /** Categorical label such as "conversation", "reasoning", "code", "plan", "output", or "metadata". */
45
+ readonly segment_type: string;
46
+ /** ISO-8601 UTC timestamp when this segment was captured. */
47
+ readonly timestamp: string;
48
+ /** Zero-based index of the conversation turn this segment belongs to. */
49
+ readonly turn_index: number;
50
+ /** Arbitrary additional key-value data attached to this segment. */
51
+ readonly metadata: Readonly<Record<string, string>>;
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Entity reference
56
+ // ---------------------------------------------------------------------------
57
+
58
+ /**
59
+ * A cross-session pointer to a tracked domain entity.
60
+ * Maps to EntityReference in Python.
61
+ */
62
+ export interface EntityReference {
63
+ /** Unique identifier for this entity record. */
64
+ readonly entity_id: string;
65
+ /** Primary normalised name used for matching. */
66
+ readonly canonical_name: string;
67
+ /** Categorical label such as "person", "project", "file", "concept", "tool", or "organisation". */
68
+ readonly entity_type: string;
69
+ /** Alternative names or spellings for this entity. */
70
+ readonly aliases: readonly string[];
71
+ /** Key-value attributes describing the entity. */
72
+ readonly attributes: Readonly<Record<string, string>>;
73
+ /** Session ID where this entity was first observed. */
74
+ readonly first_seen_session: string;
75
+ /** Session ID where this entity was most recently observed. */
76
+ readonly last_seen_session: string;
77
+ /** Match/extraction confidence in the range [0.0, 1.0]. */
78
+ readonly confidence: number;
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Task state
83
+ // ---------------------------------------------------------------------------
84
+
85
+ /**
86
+ * A tracked task with its current lifecycle status.
87
+ * Maps to TaskState in Python.
88
+ */
89
+ export interface TaskState {
90
+ /** Unique identifier for this task. */
91
+ readonly task_id: string;
92
+ /** Short human-readable title. */
93
+ readonly title: string;
94
+ /** Detailed description of what the task requires. */
95
+ readonly description: string;
96
+ /** Current lifecycle status. */
97
+ readonly status: TaskStatus;
98
+ /** Integer priority where 1 is highest. Range [1, 10]. */
99
+ readonly priority: number;
100
+ /** ISO-8601 UTC timestamp when the task was first recorded. */
101
+ readonly created_at: string;
102
+ /** ISO-8601 UTC timestamp when the task was last modified. */
103
+ readonly updated_at: string;
104
+ /** Optional reference to a parent task for sub-task hierarchies. */
105
+ readonly parent_task_id: string | null;
106
+ /** Free-form labels for categorisation and filtering. */
107
+ readonly tags: readonly string[];
108
+ /** Additional free-text notes about the task. */
109
+ readonly notes: string;
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // Tool context
114
+ // ---------------------------------------------------------------------------
115
+
116
+ /**
117
+ * A record of a single tool invocation within a session.
118
+ * Maps to ToolContext in Python.
119
+ */
120
+ export interface ToolContext {
121
+ /** Unique identifier for this invocation. */
122
+ readonly invocation_id: string;
123
+ /** Name of the tool that was called. */
124
+ readonly tool_name: string;
125
+ /** Brief summary of the input arguments (not the full payload). */
126
+ readonly input_summary: string;
127
+ /** Brief summary of the output returned. */
128
+ readonly output_summary: string;
129
+ /** Wall-clock execution time in milliseconds. */
130
+ readonly duration_ms: number;
131
+ /** Whether the invocation completed without error. */
132
+ readonly success: boolean;
133
+ /** Error description when success is false. */
134
+ readonly error_message: string;
135
+ /** ISO-8601 UTC timestamp when the invocation started. */
136
+ readonly timestamp: string;
137
+ /** Tokens consumed by the tool call, if measurable. */
138
+ readonly token_cost: number;
139
+ }
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // Session state
143
+ // ---------------------------------------------------------------------------
144
+
145
+ /**
146
+ * Complete snapshot of an agent session.
147
+ * Maps to SessionState in Python.
148
+ */
149
+ export interface SessionState {
150
+ /** Globally unique session identifier. */
151
+ readonly session_id: string;
152
+ /** Identifier for the agent or agent-type that owns this session. */
153
+ readonly agent_id: string;
154
+ /** Schema version string used for forward/backward compatibility. */
155
+ readonly schema_version: string;
156
+ /** Ordered list of conversation context segments. */
157
+ readonly segments: readonly ContextSegment[];
158
+ /** Named entities tracked within this session. */
159
+ readonly entities: readonly EntityReference[];
160
+ /** Tasks created or referenced during this session. */
161
+ readonly tasks: readonly TaskState[];
162
+ /** Chronological log of tool invocations. */
163
+ readonly tools_used: readonly ToolContext[];
164
+ /** Agent or user preferences captured during the session. */
165
+ readonly preferences: Readonly<Record<string, string>>;
166
+ /** Optional compressed summary of the session's key content. */
167
+ readonly summary: string;
168
+ /** If this is a continuation, the ID of the preceding session. */
169
+ readonly parent_session_id: string | null;
170
+ /** Accumulated LLM API cost in USD for this session. */
171
+ readonly total_cost_usd: number;
172
+ /** ISO-8601 UTC timestamp of session creation. */
173
+ readonly created_at: string;
174
+ /** ISO-8601 UTC timestamp of last modification. */
175
+ readonly updated_at: string;
176
+ /** SHA-256 of the session's canonical JSON (excluding this field). */
177
+ readonly checksum: string;
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // API request types
182
+ // ---------------------------------------------------------------------------
183
+
184
+ /** Configuration for creating a new session. */
185
+ export interface CreateSessionRequest {
186
+ /** Agent identifier that owns this session. */
187
+ readonly agent_id?: string;
188
+ /** Optional parent session to create a continuation from. */
189
+ readonly parent_session_id?: string;
190
+ /** Initial preference key-value pairs. */
191
+ readonly preferences?: Readonly<Record<string, string>>;
192
+ }
193
+
194
+ /** Request to resume a session using a resumption token. */
195
+ export interface ResumeSessionRequest {
196
+ /** The opaque resumption token previously issued by the server. */
197
+ readonly resumption_token: string;
198
+ }
199
+
200
+ /** Request to save a serialised context payload. */
201
+ export interface SaveContextRequest {
202
+ /** The session ID to update. */
203
+ readonly session_id: string;
204
+ /** Partial or full updated session state fields. */
205
+ readonly context: Partial<
206
+ Pick<SessionState, "segments" | "entities" | "tasks" | "tools_used" | "preferences" | "summary" | "total_cost_usd">
207
+ >;
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // Resumption token
212
+ // ---------------------------------------------------------------------------
213
+
214
+ /**
215
+ * An opaque token that enables resuming a serialised session across boundaries.
216
+ * Maps to the resumption token concept in agent_session_linker.portable.
217
+ */
218
+ export interface ResumptionToken {
219
+ /** The token value to pass to resumeSession(). */
220
+ readonly token: string;
221
+ /** Session ID this token references. */
222
+ readonly session_id: string;
223
+ /** ISO-8601 UTC timestamp after which this token expires. */
224
+ readonly expires_at: string;
225
+ /** Schema version of the serialised payload. */
226
+ readonly schema_version: string;
227
+ }
228
+
229
+ // ---------------------------------------------------------------------------
230
+ // Session list entry
231
+ // ---------------------------------------------------------------------------
232
+
233
+ /** Summary information returned when listing sessions. */
234
+ export interface SessionSummary {
235
+ /** Unique session identifier. */
236
+ readonly session_id: string;
237
+ /** Agent that owns this session. */
238
+ readonly agent_id: string;
239
+ /** ISO-8601 UTC creation timestamp. */
240
+ readonly created_at: string;
241
+ /** ISO-8601 UTC last-update timestamp. */
242
+ readonly updated_at: string;
243
+ /** Total number of context segments. */
244
+ readonly segment_count: number;
245
+ /** Total number of tracked tasks. */
246
+ readonly task_count: number;
247
+ /** Whether this session has a parent (is a continuation). */
248
+ readonly is_continuation: boolean;
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // Session statistics
253
+ // ---------------------------------------------------------------------------
254
+
255
+ /** Aggregate statistics across all stored sessions. */
256
+ export interface SessionStats {
257
+ /** Total number of stored sessions. */
258
+ readonly total_sessions: number;
259
+ /** Sum of all segment counts across sessions. */
260
+ readonly total_segments: number;
261
+ /** Sum of all token counts across sessions. */
262
+ readonly total_tokens: number;
263
+ /** Sum of all task counts across sessions. */
264
+ readonly total_tasks: number;
265
+ /** Sum of all entity counts across sessions. */
266
+ readonly total_entities: number;
267
+ /** Summed cost across all sessions in USD. */
268
+ readonly total_cost_usd: number;
269
+ /** List of unique agent IDs that have sessions. */
270
+ readonly agents: readonly string[];
271
+ }
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // API result wrapper
275
+ // ---------------------------------------------------------------------------
276
+
277
+ /** Standard error payload returned by the agent-session-linker API. */
278
+ export interface ApiError {
279
+ readonly error: string;
280
+ readonly detail: string;
281
+ }
282
+
283
+ /** Result type for all client operations. */
284
+ export type ApiResult<T> =
285
+ | { readonly ok: true; readonly data: T }
286
+ | { readonly ok: false; readonly error: ApiError; readonly status: number };
package/tsconfig.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2020", "DOM"],
7
+ "outDir": "./dist",
8
+ "rootDir": "./src",
9
+ "declaration": true,
10
+ "declarationMap": true,
11
+ "sourceMap": true,
12
+ "strict": true,
13
+ "noImplicitAny": true,
14
+ "strictNullChecks": true,
15
+ "noUnusedLocals": true,
16
+ "noUnusedParameters": true,
17
+ "noImplicitReturns": true,
18
+ "exactOptionalPropertyTypes": true,
19
+ "forceConsistentCasingInFileNames": true,
20
+ "esModuleInterop": true,
21
+ "skipLibCheck": true
22
+ },
23
+ "include": ["src/**/*"],
24
+ "exclude": ["node_modules", "dist"]
25
+ }