@acontext/acontext 0.0.11 → 0.0.13

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/README.md CHANGED
@@ -8,295 +8,6 @@ TypeScript SDK for interacting with the Acontext REST API.
8
8
  npm install @acontext/acontext
9
9
  ```
10
10
 
11
- ## Quickstart
12
-
13
- ```typescript
14
- import { AcontextClient, MessagePart } from '@acontext/acontext';
15
-
16
- const client = new AcontextClient({ apiKey: 'sk-ac-your-root-api-bearer-token' });
17
-
18
- // List spaces for the authenticated project
19
- const spaces = await client.spaces.list();
20
-
21
- // Create a session bound to the first space
22
- const session = await client.sessions.create({ spaceId: spaces.items[0].id });
23
-
24
- // Send a text message to the session
25
- await client.sessions.sendMessage(
26
- session.id,
27
- {
28
- role: 'user',
29
- parts: [MessagePart.textPart('Hello from TypeScript!')],
30
- },
31
- { format: 'acontext' }
32
- );
33
-
34
- // Flush session buffer when needed
35
- await client.sessions.flush(session.id);
36
- ```
37
-
38
- See the inline documentation for the full list of helpers covering sessions, spaces, disks, and artifact uploads.
39
-
40
- ## Health Check
41
-
42
- Test connectivity to the Acontext API server:
43
-
44
- ```typescript
45
- import { AcontextClient } from '@acontext/acontext';
46
-
47
- const client = new AcontextClient({ apiKey: 'sk-ac-your-root-api-bearer-token' });
48
-
49
- // Ping the server
50
- const pong = await client.ping();
51
- console.log(`Server responded: ${pong}`); // Output: Server responded: pong
52
- ```
53
-
54
- This is useful for:
55
- - Verifying API connectivity before performing operations
56
- - Health checks in monitoring systems
57
- - Debugging connection issues
58
-
59
- ## Managing disks and artifacts
60
-
61
- Artifacts now live under project disks. Create a disk first, then upload files through the disk-scoped helper:
62
-
63
- ```typescript
64
- import { AcontextClient, FileUpload } from '@acontext/acontext';
65
-
66
- const client = new AcontextClient({ apiKey: 'sk-ac-your-root-api-bearer-token' });
67
-
68
- const disk = await client.disks.create();
69
- await client.disks.artifacts.upsert(
70
- disk.id,
71
- {
72
- file: new FileUpload({
73
- filename: 'retro_notes.md',
74
- content: Buffer.from('# Retro Notes\nWe shipped file uploads successfully!\n'),
75
- contentType: 'text/markdown',
76
- }),
77
- filePath: '/notes/',
78
- meta: { source: 'readme-demo' },
79
- }
80
- );
81
- ```
82
-
83
- ## Working with blocks
84
-
85
- ```typescript
86
- import { AcontextClient } from '@acontext/acontext';
87
-
88
- const client = new AcontextClient({ apiKey: 'sk-ac-your-root-api-bearer-token' });
89
-
90
- const space = await client.spaces.create();
91
- const page = await client.blocks.create(space.id, {
92
- blockType: 'page',
93
- title: 'Kick-off Notes',
94
- });
95
- await client.blocks.create(space.id, {
96
- parentId: page.id,
97
- blockType: 'text',
98
- title: 'First block',
99
- props: { text: 'Plan the sprint goals' },
100
- });
101
- ```
102
-
103
- ## Managing sessions
104
-
105
- ### Flush session buffer
106
-
107
- The `flush` method clears the session buffer, useful for managing session state:
108
-
109
- ```typescript
110
- const result = await client.sessions.flush('session-uuid');
111
- console.log(result); // { status: 0, errmsg: '' }
112
- ```
113
-
114
- ## Working with tools
115
-
116
- The SDK provides APIs to manage tool names within your project:
117
-
118
- ### Get tool names
119
-
120
- ```typescript
121
- const tools = await client.tools.getToolName();
122
- for (const tool of tools) {
123
- console.log(`${tool.name} (used in ${tool.sop_count} SOPs)`);
124
- }
125
- ```
126
-
127
- ### Rename tool names
128
-
129
- ```typescript
130
- const result = await client.tools.renameToolName({
131
- rename: [
132
- { oldName: 'calculate', newName: 'calculate_math' },
133
- { oldName: 'search', newName: 'search_web' },
134
- ],
135
- });
136
- console.log(result); // { status: 0, errmsg: '' }
137
- ```
138
-
139
- ## Agent Tools
140
-
141
- The SDK provides agent tools that allow LLMs (OpenAI, Anthropic) to interact with Acontext disks through function calling. These tools can be converted to OpenAI or Anthropic tool schemas and executed when the LLM calls them.
142
-
143
- ### Pre-configured Disk Tools
144
-
145
- The SDK includes a pre-configured `DISK_TOOLS` pool with four disk operation tools:
146
-
147
- - **`write_file`**: Write text content to a file
148
- - **`read_file`**: Read a text file with optional line offset and limit
149
- - **`replace_string`**: Replace strings in a file
150
- - **`list_artifacts`**: List files and directories in a path
151
-
152
- ### Getting Tool Schemas for LLM APIs
153
-
154
- Convert tools to the appropriate format for your LLM provider:
155
-
156
- ```typescript
157
- import { AcontextClient, DISK_TOOLS } from '@acontext/acontext';
158
-
159
- const client = new AcontextClient({ apiKey: 'sk-ac-your-root-api-bearer-token' });
160
-
161
- // Get OpenAI-compatible tool schemas
162
- const openaiTools = DISK_TOOLS.toOpenAIToolSchema();
163
-
164
- // Get Anthropic-compatible tool schemas
165
- const anthropicTools = DISK_TOOLS.toAnthropicToolSchema();
166
-
167
- // Use with OpenAI API
168
- import OpenAI from 'openai';
169
- const openai = new OpenAI({ apiKey: 'your-openai-key' });
170
- const completion = await openai.chat.completions.create({
171
- model: 'gpt-4',
172
- messages: [{ role: 'user', content: 'Write a file called hello.txt with "Hello, World!"' }],
173
- tools: openaiTools,
174
- });
175
- ```
176
-
177
- ### Executing Tools
178
-
179
- When an LLM calls a tool, execute it using the tool pool:
180
-
181
- ```typescript
182
- import { AcontextClient, DISK_TOOLS } from '@acontext/acontext';
183
-
184
- const client = new AcontextClient({ apiKey: 'sk-ac-your-root-api-bearer-token' });
185
-
186
- // Create a disk for the tools to operate on
187
- const disk = await client.disks.create();
188
-
189
- // Create a context for the tools
190
- const ctx = DISK_TOOLS.formatContext(client, disk.id);
191
-
192
- // Execute a tool (e.g., after LLM returns a tool call)
193
- const result = await DISK_TOOLS.executeTool(ctx, 'write_file', {
194
- filename: 'hello.txt',
195
- file_path: '/notes/',
196
- content: 'Hello, World!',
197
- });
198
- console.log(result); // File 'hello.txt' written successfully to '/notes/hello.txt'
199
-
200
- // Read the file
201
- const readResult = await DISK_TOOLS.executeTool(ctx, 'read_file', {
202
- filename: 'hello.txt',
203
- file_path: '/notes/',
204
- });
205
- console.log(readResult);
206
-
207
- // List files in a directory
208
- const listResult = await DISK_TOOLS.executeTool(ctx, 'list_artifacts', {
209
- file_path: '/notes/',
210
- });
211
- console.log(listResult);
212
-
213
- // Replace a string in a file
214
- const replaceResult = await DISK_TOOLS.executeTool(ctx, 'replace_string', {
215
- filename: 'hello.txt',
216
- file_path: '/notes/',
217
- old_string: 'Hello',
218
- new_string: 'Hi',
219
- });
220
- console.log(replaceResult);
221
- ```
222
-
223
- ### Creating Custom Tools
224
-
225
- You can create custom tools by extending `AbstractBaseTool`:
226
-
227
- ```typescript
228
- import { AbstractBaseTool, BaseContext, BaseToolPool } from '@acontext/acontext';
229
-
230
- interface MyContext extends BaseContext {
231
- // Your context properties
232
- }
233
-
234
- class MyCustomTool extends AbstractBaseTool {
235
- readonly name = 'my_custom_tool';
236
- readonly description = 'A custom tool that does something';
237
- readonly arguments = {
238
- param1: {
239
- type: 'string',
240
- description: 'First parameter',
241
- },
242
- };
243
- readonly requiredArguments = ['param1'];
244
-
245
- async execute(ctx: MyContext, llmArguments: Record<string, unknown>): Promise<string> {
246
- const param1 = llmArguments.param1 as string;
247
- // Your custom logic here
248
- return `Result: ${param1}`;
249
- }
250
- }
251
-
252
- // Create a custom tool pool
253
- class MyToolPool extends BaseToolPool {
254
- formatContext(...args: unknown[]): MyContext {
255
- // Create and return your context
256
- return {};
257
- }
258
- }
259
-
260
- const myPool = new MyToolPool();
261
- myPool.addTool(new MyCustomTool());
262
- ```
263
-
264
- ## Semantic search within spaces
265
-
266
- The SDK provides a powerful semantic search API for finding content within your spaces:
267
-
268
- ### 1. Experience Search (Advanced AI-powered search)
269
-
270
- The most sophisticated search that can operate in two modes: **fast** (quick semantic search) or **agentic** (AI-powered iterative refinement).
271
-
272
- ```typescript
273
- import { AcontextClient } from '@acontext/acontext';
274
-
275
- const client = new AcontextClient({ apiKey: 'sk_project_token' });
276
-
277
- // Fast mode - quick semantic search
278
- const result = await client.spaces.experienceSearch('space-uuid', {
279
- query: 'How to implement authentication?',
280
- limit: 10,
281
- mode: 'fast',
282
- semanticThreshold: 0.8,
283
- });
284
-
285
- // Agentic mode - AI-powered iterative search
286
- const agenticResult = await client.spaces.experienceSearch('space-uuid', {
287
- query: 'What are the best practices for API security?',
288
- limit: 10,
289
- mode: 'agentic',
290
- maxIterations: 20,
291
- });
292
-
293
- // Access results
294
- for (const block of result.cited_blocks) {
295
- console.log(`${block.title} (distance: ${block.distance})`);
296
- }
297
-
298
- if (result.final_answer) {
299
- console.log(`AI Answer: ${result.final_answer}`);
300
- }
301
- ```
11
+ # 🔍 Document
302
12
 
13
+ To understand more about this SDK, please view [our docs](https://docs.acontext.io/) and [api references](https://docs.acontext.io/api-reference/introduction)
@@ -4,7 +4,7 @@
4
4
  import { RequesterProtocol } from '../client-types';
5
5
  import { AcontextMessage } from '../messages';
6
6
  import { FileUpload } from '../uploads';
7
- import { EditStrategy, GetMessagesOutput, GetTasksOutput, LearningStatus, ListSessionsOutput, Message, Session, TokenCounts } from '../types';
7
+ import { EditStrategy, GetMessagesOutput, GetTasksOutput, LearningStatus, ListSessionsOutput, Message, MessageObservingStatus, Session, TokenCounts } from '../types';
8
8
  export type MessageBlob = AcontextMessage | Record<string, unknown>;
9
9
  export declare class SessionsAPI {
10
10
  private requester;
@@ -34,7 +34,7 @@ export declare class SessionsAPI {
34
34
  cursor?: string | null;
35
35
  timeDesc?: boolean | null;
36
36
  }): Promise<GetTasksOutput>;
37
- sendMessage(sessionId: string, blob: MessageBlob, options?: {
37
+ storeMessage(sessionId: string, blob: MessageBlob, options?: {
38
38
  format?: 'acontext' | 'openai' | 'anthropic';
39
39
  fileField?: string | null;
40
40
  file?: FileUpload | null;
@@ -84,4 +84,15 @@ export declare class SessionsAPI {
84
84
  * @returns TokenCounts object containing total_tokens.
85
85
  */
86
86
  getTokenCounts(sessionId: string): Promise<TokenCounts>;
87
+ /**
88
+ * Get message observing status counts for a session.
89
+ *
90
+ * Returns the count of messages by their observing status:
91
+ * observed, in_process, and pending.
92
+ *
93
+ * @param sessionId - The UUID of the session.
94
+ * @returns MessageObservingStatus object containing observed, in_process,
95
+ * pending counts and updated_at timestamp.
96
+ */
97
+ messagesObservingStatus(sessionId: string): Promise<MessageObservingStatus>;
87
98
  }
@@ -73,7 +73,7 @@ class SessionsAPI {
73
73
  });
74
74
  return types_1.GetTasksOutputSchema.parse(data);
75
75
  }
76
- async sendMessage(sessionId, blob, options) {
76
+ async storeMessage(sessionId, blob, options) {
77
77
  const format = options?.format ?? 'openai';
78
78
  if (!['acontext', 'openai', 'anthropic'].includes(format)) {
79
79
  throw new Error("format must be one of {'acontext', 'openai', 'anthropic'}");
@@ -180,5 +180,19 @@ class SessionsAPI {
180
180
  const data = await this.requester.request('GET', `/session/${sessionId}/token_counts`);
181
181
  return types_1.TokenCountsSchema.parse(data);
182
182
  }
183
+ /**
184
+ * Get message observing status counts for a session.
185
+ *
186
+ * Returns the count of messages by their observing status:
187
+ * observed, in_process, and pending.
188
+ *
189
+ * @param sessionId - The UUID of the session.
190
+ * @returns MessageObservingStatus object containing observed, in_process,
191
+ * pending counts and updated_at timestamp.
192
+ */
193
+ async messagesObservingStatus(sessionId) {
194
+ const data = await this.requester.request('GET', `/session/${sessionId}/observing_status`);
195
+ return types_1.MessageObservingStatusSchema.parse(data);
196
+ }
183
197
  }
184
198
  exports.SessionsAPI = SessionsAPI;
@@ -113,6 +113,7 @@ export declare const PublicURLSchema: z.ZodObject<{
113
113
  export type PublicURL = z.infer<typeof PublicURLSchema>;
114
114
  export declare const GetMessagesOutputSchema: z.ZodObject<{
115
115
  items: z.ZodArray<z.ZodUnknown>;
116
+ ids: z.ZodArray<z.ZodString>;
116
117
  next_cursor: z.ZodOptional<z.ZodNullable<z.ZodString>>;
117
118
  has_more: z.ZodBoolean;
118
119
  public_urls: z.ZodOptional<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodObject<{
@@ -152,6 +153,13 @@ export declare const TokenCountsSchema: z.ZodObject<{
152
153
  total_tokens: z.ZodNumber;
153
154
  }, z.core.$strip>;
154
155
  export type TokenCounts = z.infer<typeof TokenCountsSchema>;
156
+ export declare const MessageObservingStatusSchema: z.ZodObject<{
157
+ observed: z.ZodNumber;
158
+ in_process: z.ZodNumber;
159
+ pending: z.ZodNumber;
160
+ updated_at: z.ZodString;
161
+ }, z.core.$strip>;
162
+ export type MessageObservingStatus = z.infer<typeof MessageObservingStatusSchema>;
155
163
  /**
156
164
  * Parameters for the remove_tool_result edit strategy.
157
165
  */
@@ -160,6 +168,29 @@ export declare const RemoveToolResultParamsSchema: z.ZodObject<{
160
168
  tool_result_placeholder: z.ZodOptional<z.ZodString>;
161
169
  }, z.core.$strip>;
162
170
  export type RemoveToolResultParams = z.infer<typeof RemoveToolResultParamsSchema>;
171
+ /**
172
+ * Parameters for the remove_tool_call_params edit strategy.
173
+ */
174
+ export declare const RemoveToolCallParamsParamsSchema: z.ZodObject<{
175
+ keep_recent_n_tool_calls: z.ZodOptional<z.ZodNumber>;
176
+ }, z.core.$strip>;
177
+ export type RemoveToolCallParamsParams = z.infer<typeof RemoveToolCallParamsParamsSchema>;
178
+ /**
179
+ * Edit strategy to remove parameters from old tool-call parts.
180
+ *
181
+ * Keeps the most recent N tool calls with full parameters, replacing older
182
+ * tool call arguments with empty JSON "{}". The tool call ID and name remain
183
+ * intact so tool-results can still reference them.
184
+ *
185
+ * Example: { type: 'remove_tool_call_params', params: { keep_recent_n_tool_calls: 5 } }
186
+ */
187
+ export declare const RemoveToolCallParamsStrategySchema: z.ZodObject<{
188
+ type: z.ZodLiteral<"remove_tool_call_params">;
189
+ params: z.ZodObject<{
190
+ keep_recent_n_tool_calls: z.ZodOptional<z.ZodNumber>;
191
+ }, z.core.$strip>;
192
+ }, z.core.$strip>;
193
+ export type RemoveToolCallParamsStrategy = z.infer<typeof RemoveToolCallParamsStrategySchema>;
163
194
  /**
164
195
  * Edit strategy to replace old tool results with placeholder text.
165
196
  *
@@ -206,6 +237,11 @@ export declare const EditStrategySchema: z.ZodUnion<readonly [z.ZodObject<{
206
237
  keep_recent_n_tool_results: z.ZodOptional<z.ZodNumber>;
207
238
  tool_result_placeholder: z.ZodOptional<z.ZodString>;
208
239
  }, z.core.$strip>;
240
+ }, z.core.$strip>, z.ZodObject<{
241
+ type: z.ZodLiteral<"remove_tool_call_params">;
242
+ params: z.ZodObject<{
243
+ keep_recent_n_tool_calls: z.ZodOptional<z.ZodNumber>;
244
+ }, z.core.$strip>;
209
245
  }, z.core.$strip>, z.ZodObject<{
210
246
  type: z.ZodLiteral<"token_limit">;
211
247
  params: z.ZodObject<{
@@ -3,7 +3,7 @@
3
3
  * Type definitions for session, message, and task resources.
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.EditStrategySchema = exports.TokenLimitStrategySchema = exports.TokenLimitParamsSchema = exports.RemoveToolResultStrategySchema = exports.RemoveToolResultParamsSchema = exports.TokenCountsSchema = exports.LearningStatusSchema = exports.GetTasksOutputSchema = exports.GetMessagesOutputSchema = exports.PublicURLSchema = exports.ListSessionsOutputSchema = exports.TaskSchema = exports.TaskDataSchema = exports.SessionSchema = exports.MessageSchema = exports.PartSchema = exports.AssetSchema = void 0;
6
+ exports.EditStrategySchema = exports.TokenLimitStrategySchema = exports.TokenLimitParamsSchema = exports.RemoveToolResultStrategySchema = exports.RemoveToolCallParamsStrategySchema = exports.RemoveToolCallParamsParamsSchema = exports.RemoveToolResultParamsSchema = exports.MessageObservingStatusSchema = exports.TokenCountsSchema = exports.LearningStatusSchema = exports.GetTasksOutputSchema = exports.GetMessagesOutputSchema = exports.PublicURLSchema = exports.ListSessionsOutputSchema = exports.TaskSchema = exports.TaskDataSchema = exports.SessionSchema = exports.MessageSchema = exports.PartSchema = exports.AssetSchema = void 0;
7
7
  const zod_1 = require("zod");
8
8
  exports.AssetSchema = zod_1.z.object({
9
9
  bucket: zod_1.z.string(),
@@ -75,6 +75,7 @@ exports.PublicURLSchema = zod_1.z.object({
75
75
  });
76
76
  exports.GetMessagesOutputSchema = zod_1.z.object({
77
77
  items: zod_1.z.array(zod_1.z.unknown()),
78
+ ids: zod_1.z.array(zod_1.z.string()),
78
79
  next_cursor: zod_1.z.string().nullable().optional(),
79
80
  has_more: zod_1.z.boolean(),
80
81
  public_urls: zod_1.z.record(zod_1.z.string(), exports.PublicURLSchema).nullable().optional(),
@@ -91,6 +92,12 @@ exports.LearningStatusSchema = zod_1.z.object({
91
92
  exports.TokenCountsSchema = zod_1.z.object({
92
93
  total_tokens: zod_1.z.number(),
93
94
  });
95
+ exports.MessageObservingStatusSchema = zod_1.z.object({
96
+ observed: zod_1.z.number(),
97
+ in_process: zod_1.z.number(),
98
+ pending: zod_1.z.number(),
99
+ updated_at: zod_1.z.string(),
100
+ });
94
101
  /**
95
102
  * Parameters for the remove_tool_result edit strategy.
96
103
  */
@@ -106,6 +113,29 @@ exports.RemoveToolResultParamsSchema = zod_1.z.object({
106
113
  */
107
114
  tool_result_placeholder: zod_1.z.string().optional(),
108
115
  });
116
+ /**
117
+ * Parameters for the remove_tool_call_params edit strategy.
118
+ */
119
+ exports.RemoveToolCallParamsParamsSchema = zod_1.z.object({
120
+ /**
121
+ * Number of most recent tool calls to keep with full parameters.
122
+ * @default 3
123
+ */
124
+ keep_recent_n_tool_calls: zod_1.z.number().optional(),
125
+ });
126
+ /**
127
+ * Edit strategy to remove parameters from old tool-call parts.
128
+ *
129
+ * Keeps the most recent N tool calls with full parameters, replacing older
130
+ * tool call arguments with empty JSON "{}". The tool call ID and name remain
131
+ * intact so tool-results can still reference them.
132
+ *
133
+ * Example: { type: 'remove_tool_call_params', params: { keep_recent_n_tool_calls: 5 } }
134
+ */
135
+ exports.RemoveToolCallParamsStrategySchema = zod_1.z.object({
136
+ type: zod_1.z.literal('remove_tool_call_params'),
137
+ params: exports.RemoveToolCallParamsParamsSchema,
138
+ });
109
139
  /**
110
140
  * Edit strategy to replace old tool results with placeholder text.
111
141
  *
@@ -145,5 +175,6 @@ exports.TokenLimitStrategySchema = zod_1.z.object({
145
175
  */
146
176
  exports.EditStrategySchema = zod_1.z.union([
147
177
  exports.RemoveToolResultStrategySchema,
178
+ exports.RemoveToolCallParamsStrategySchema,
148
179
  exports.TokenLimitStrategySchema,
149
180
  ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acontext/acontext",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
4
  "description": "TypeScript SDK for the Acontext API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",