@artinet/sdk 0.2.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.
Files changed (120) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/LICENSE +21 -0
  3. package/README.md +618 -0
  4. package/dist/client/a2a-client.d.ts +99 -0
  5. package/dist/client/a2a-client.d.ts.map +1 -0
  6. package/dist/client/a2a-client.js +171 -0
  7. package/dist/client/a2a-client.js.map +1 -0
  8. package/dist/client/index.d.ts +3 -0
  9. package/dist/client/index.d.ts.map +1 -0
  10. package/dist/client/index.js +3 -0
  11. package/dist/client/index.js.map +1 -0
  12. package/dist/client/interfaces/client.d.ts +19 -0
  13. package/dist/client/interfaces/client.d.ts.map +1 -0
  14. package/dist/client/interfaces/client.js +2 -0
  15. package/dist/client/interfaces/client.js.map +1 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +6 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/server/a2a-server.d.ts +144 -0
  21. package/dist/server/a2a-server.d.ts.map +1 -0
  22. package/dist/server/a2a-server.js +384 -0
  23. package/dist/server/a2a-server.js.map +1 -0
  24. package/dist/server/index.d.ts +9 -0
  25. package/dist/server/index.d.ts.map +1 -0
  26. package/dist/server/index.js +9 -0
  27. package/dist/server/index.js.map +1 -0
  28. package/dist/server/interfaces/context.d.ts +41 -0
  29. package/dist/server/interfaces/context.d.ts.map +1 -0
  30. package/dist/server/interfaces/context.js +2 -0
  31. package/dist/server/interfaces/context.js.map +1 -0
  32. package/dist/server/interfaces/params.d.ts +72 -0
  33. package/dist/server/interfaces/params.d.ts.map +1 -0
  34. package/dist/server/interfaces/params.js +3 -0
  35. package/dist/server/interfaces/params.js.map +1 -0
  36. package/dist/server/interfaces/server.d.ts +34 -0
  37. package/dist/server/interfaces/server.d.ts.map +1 -0
  38. package/dist/server/interfaces/server.js +2 -0
  39. package/dist/server/interfaces/server.js.map +1 -0
  40. package/dist/server/interfaces/store.d.ts +30 -0
  41. package/dist/server/interfaces/store.d.ts.map +1 -0
  42. package/dist/server/interfaces/store.js +2 -0
  43. package/dist/server/interfaces/store.js.map +1 -0
  44. package/dist/server/lib/express-server.d.ts +13 -0
  45. package/dist/server/lib/express-server.d.ts.map +1 -0
  46. package/dist/server/lib/express-server.js +51 -0
  47. package/dist/server/lib/express-server.js.map +1 -0
  48. package/dist/server/lib/json-middleware.d.ts +19 -0
  49. package/dist/server/lib/json-middleware.d.ts.map +1 -0
  50. package/dist/server/lib/json-middleware.js +180 -0
  51. package/dist/server/lib/json-middleware.js.map +1 -0
  52. package/dist/server/lib/state.d.ts +28 -0
  53. package/dist/server/lib/state.d.ts.map +1 -0
  54. package/dist/server/lib/state.js +108 -0
  55. package/dist/server/lib/state.js.map +1 -0
  56. package/dist/server/lib/storage/file.d.ts +62 -0
  57. package/dist/server/lib/storage/file.d.ts.map +1 -0
  58. package/dist/server/lib/storage/file.js +148 -0
  59. package/dist/server/lib/storage/file.js.map +1 -0
  60. package/dist/server/lib/storage/memory.d.ts +21 -0
  61. package/dist/server/lib/storage/memory.d.ts.map +1 -0
  62. package/dist/server/lib/storage/memory.js +40 -0
  63. package/dist/server/lib/storage/memory.js.map +1 -0
  64. package/dist/transport/index.d.ts +5 -0
  65. package/dist/transport/index.d.ts.map +1 -0
  66. package/dist/transport/index.js +5 -0
  67. package/dist/transport/index.js.map +1 -0
  68. package/dist/transport/rpc/parser.d.ts +12 -0
  69. package/dist/transport/rpc/parser.d.ts.map +1 -0
  70. package/dist/transport/rpc/parser.js +37 -0
  71. package/dist/transport/rpc/parser.js.map +1 -0
  72. package/dist/transport/rpc/rpc-client.d.ts +77 -0
  73. package/dist/transport/rpc/rpc-client.d.ts.map +1 -0
  74. package/dist/transport/rpc/rpc-client.js +182 -0
  75. package/dist/transport/rpc/rpc-client.js.map +1 -0
  76. package/dist/transport/streaming/event-stream.d.ts +22 -0
  77. package/dist/transport/streaming/event-stream.d.ts.map +1 -0
  78. package/dist/transport/streaming/event-stream.js +79 -0
  79. package/dist/transport/streaming/event-stream.js.map +1 -0
  80. package/dist/transport/streaming/stream.d.ts +42 -0
  81. package/dist/transport/streaming/stream.d.ts.map +1 -0
  82. package/dist/transport/streaming/stream.js +128 -0
  83. package/dist/transport/streaming/stream.js.map +1 -0
  84. package/dist/types/extended-schema.d.ts +52 -0
  85. package/dist/types/extended-schema.d.ts.map +1 -0
  86. package/dist/types/extended-schema.js +7 -0
  87. package/dist/types/extended-schema.js.map +1 -0
  88. package/dist/types/index.d.ts +2 -0
  89. package/dist/types/index.d.ts.map +1 -0
  90. package/dist/types/index.js +2 -0
  91. package/dist/types/index.js.map +1 -0
  92. package/dist/types/schema.d.ts +729 -0
  93. package/dist/types/schema.d.ts.map +1 -0
  94. package/dist/types/schema.js +23 -0
  95. package/dist/types/schema.js.map +1 -0
  96. package/dist/utils/common/constants.d.ts +6 -0
  97. package/dist/utils/common/constants.d.ts.map +1 -0
  98. package/dist/utils/common/constants.js +28 -0
  99. package/dist/utils/common/constants.js.map +1 -0
  100. package/dist/utils/common/errors.d.ts +26 -0
  101. package/dist/utils/common/errors.d.ts.map +1 -0
  102. package/dist/utils/common/errors.js +59 -0
  103. package/dist/utils/common/errors.js.map +1 -0
  104. package/dist/utils/common/utils.d.ts +30 -0
  105. package/dist/utils/common/utils.d.ts.map +1 -0
  106. package/dist/utils/common/utils.js +67 -0
  107. package/dist/utils/common/utils.js.map +1 -0
  108. package/dist/utils/index.d.ts +6 -0
  109. package/dist/utils/index.d.ts.map +1 -0
  110. package/dist/utils/index.js +6 -0
  111. package/dist/utils/index.js.map +1 -0
  112. package/dist/utils/logging/log.d.ts +30 -0
  113. package/dist/utils/logging/log.d.ts.map +1 -0
  114. package/dist/utils/logging/log.js +58 -0
  115. package/dist/utils/logging/log.js.map +1 -0
  116. package/dist/utils/logging/logger.d.ts +16 -0
  117. package/dist/utils/logging/logger.d.ts.map +1 -0
  118. package/dist/utils/logging/logger.js +38 -0
  119. package/dist/utils/logging/logger.js.map +1 -0
  120. package/package.json +83 -0
@@ -0,0 +1,13 @@
1
+ import express from "express";
2
+ import http from "http";
3
+ import { CreateExpressServerParams } from "../interfaces/params.js";
4
+ /**
5
+ * Creates an Express server for the A2A protocol.
6
+ * Handles task creation, streaming, cancellation and more.
7
+ * Uses Jayson for JSON-RPC handling.
8
+ */
9
+ export declare function createExpressServer(params: CreateExpressServerParams): {
10
+ app: express.Express;
11
+ server: http.Server;
12
+ };
13
+ //# sourceMappingURL=express-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"express-server.d.ts","sourceRoot":"","sources":["../../../src/server/lib/express-server.ts"],"names":[],"mappings":"AACA,OAAO,OAA4C,MAAM,SAAS,CAAC;AAEnE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAEpE;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,yBAAyB,GAAG;IACtE,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC;IACrB,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC;CACrB,CA4DA"}
@@ -0,0 +1,51 @@
1
+ import cors from "cors";
2
+ import express from "express";
3
+ import { logInfo } from "../../utils/logging/log.js";
4
+ /**
5
+ * Creates an Express server for the A2A protocol.
6
+ * Handles task creation, streaming, cancellation and more.
7
+ * Uses Jayson for JSON-RPC handling.
8
+ */
9
+ export function createExpressServer(params) {
10
+ const { card, corsOptions, basePath, port, rpcServer, errorHandler, onTaskSendSubscribe, onTaskResubscribe, } = params;
11
+ const app = express();
12
+ app.use(cors(corsOptions));
13
+ app.use(express.json());
14
+ app.get("/.well-known/agent.json", (_, res) => {
15
+ res.json(card);
16
+ });
17
+ app.get("/agent-card", (_, res) => {
18
+ res.json(card);
19
+ });
20
+ //SSE Paths
21
+ app.post(basePath, async (req, res, next) => {
22
+ try {
23
+ const body = req.body;
24
+ if (body && body.method) {
25
+ if (body.method === "tasks/sendSubscribe") {
26
+ return await onTaskSendSubscribe(body, res);
27
+ }
28
+ else if (body.method === "tasks/resubscribe") {
29
+ return await onTaskResubscribe(body, res);
30
+ }
31
+ }
32
+ next();
33
+ }
34
+ catch (error) {
35
+ next(error);
36
+ }
37
+ });
38
+ //RPC server
39
+ app.post(basePath, rpcServer.middleware());
40
+ // Fallback error handler
41
+ app.use(errorHandler);
42
+ // Start listening
43
+ const server = app.listen(port, () => {
44
+ logInfo("A2AServer", `A2A Server started and listening`, {
45
+ port,
46
+ path: basePath,
47
+ });
48
+ });
49
+ return { app, server };
50
+ }
51
+ //# sourceMappingURL=express-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"express-server.js","sourceRoot":"","sources":["../../../src/server/lib/express-server.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,OAA4C,MAAM,SAAS,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAIrD;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAiC;IAInE,MAAM,EACJ,IAAI,EACJ,WAAW,EACX,QAAQ,EACR,IAAI,EACJ,SAAS,EACT,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,GAClB,GAAG,MAAM,CAAC;IACX,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;IAEtB,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IAE3B,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IAExB,GAAG,CAAC,GAAG,CAAC,yBAAyB,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE;QAC5C,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC,CAAC,CAAC;IAEH,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE;QACh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JSONRPCServer
4
+ * This implementation is used by the Artinet API server
5
+ * It provides a basic JSON-RPC server with methods for task creation, retrieval, and cancellation
6
+ * Creates and initializes a Jayson server with A2A methods
7
+ * @param params Object containing all required parameters for server initialization
8
+ * @returns A configured Jayson server instance
9
+ */
10
+ /**
11
+ * Default implementation of createJSONRPCServer
12
+ * This implementation is used by the Artinet API server
13
+ * It provides a basic JSON-RPC server with methods for task creation, retrieval, and cancellation
14
+ * Creates and initializes a Jayson server with A2A methods
15
+ * @param params Object containing all required parameters for server initialization
16
+ * @returns A configured Jayson server instance
17
+ */
18
+ export declare function defaultCreateJSONRPCServer(params: CreateJSONRPCServerParams): JSONRPCServerType;
19
+ //# sourceMappingURL=json-middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-middleware.d.ts","sourceRoot":"","sources":["../../../src/server/lib/json-middleware.ts"],"names":[],"mappings":"AAeA,OAAO,EACL,yBAAyB,EAEzB,iBAAiB,EAElB,MAAM,yBAAyB,CAAC;AAWjC;;;;;;;GAOG;AAEH;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,yBAAyB,GAChC,iBAAiB,CAkNnB"}
@@ -0,0 +1,180 @@
1
+ import { getCurrentTimestamp } from "../../utils/common/utils.js";
2
+ import { logError, logWarn } from "../../utils/logging/log.js";
3
+ import { loadState, updateState } from "../lib/state.js";
4
+ import { INTERNAL_ERROR, INVALID_PARAMS, METHOD_NOT_FOUND, PUSH_NOTIFICATION_NOT_SUPPORTED, TASK_NOT_CANCELABLE, TASK_NOT_FOUND, FAILED_UPDATE, } from "../../utils/common/errors.js";
5
+ import { JSONRPCServer, } from "../interfaces/params.js";
6
+ function toJaysonError(error) {
7
+ return {
8
+ code: error.code,
9
+ message: error.message,
10
+ data: error.data,
11
+ };
12
+ }
13
+ /**
14
+ * Default implementation of createJSONRPCServer
15
+ * This implementation is used by the Artinet API server
16
+ * It provides a basic JSON-RPC server with methods for task creation, retrieval, and cancellation
17
+ * Creates and initializes a Jayson server with A2A methods
18
+ * @param params Object containing all required parameters for server initialization
19
+ * @returns A configured Jayson server instance
20
+ */
21
+ /**
22
+ * Default implementation of createJSONRPCServer
23
+ * This implementation is used by the Artinet API server
24
+ * It provides a basic JSON-RPC server with methods for task creation, retrieval, and cancellation
25
+ * Creates and initializes a Jayson server with A2A methods
26
+ * @param params Object containing all required parameters for server initialization
27
+ * @returns A configured Jayson server instance
28
+ */
29
+ export function defaultCreateJSONRPCServer(params) {
30
+ const { taskStore, card, taskHandler, activeCancellations, createTaskContext, closeStreamsForTask, } = params;
31
+ return new JSONRPCServer({
32
+ "tasks/send": async (params, callback) => {
33
+ try {
34
+ // Validate params
35
+ if (!params || !params.id || !params.message) {
36
+ return callback(toJaysonError(INVALID_PARAMS()));
37
+ }
38
+ const { id: taskId, message, sessionId, metadata } = params;
39
+ // Load or create task
40
+ let currentData = await loadState(taskStore, taskId, message, sessionId, metadata);
41
+ // Create task context
42
+ const context = createTaskContext(currentData.task, message, currentData.history);
43
+ const generator = taskHandler(context);
44
+ try {
45
+ for await (const update of generator) {
46
+ currentData = await updateState(taskStore, currentData, update);
47
+ }
48
+ return callback(null, currentData.task);
49
+ }
50
+ catch (error) {
51
+ const failedUpdate = FAILED_UPDATE(`Task processing failed: ${error instanceof Error ? error.message : String(error)}`);
52
+ currentData = await updateState(taskStore, currentData, failedUpdate);
53
+ return callback(toJaysonError(INTERNAL_ERROR(error)));
54
+ }
55
+ }
56
+ catch (error) {
57
+ logError("tasks/send", "Error in tasks/send", error);
58
+ return callback(toJaysonError(INTERNAL_ERROR(error)));
59
+ }
60
+ },
61
+ "tasks/get": async (params, callback) => {
62
+ try {
63
+ const { id: taskId } = params;
64
+ if (!taskId) {
65
+ return callback(toJaysonError(INVALID_PARAMS()));
66
+ }
67
+ // Load the task
68
+ const data = await taskStore.load(taskId);
69
+ if (!data) {
70
+ return callback(toJaysonError(TASK_NOT_FOUND()));
71
+ }
72
+ return callback(null, data.task);
73
+ }
74
+ catch (error) {
75
+ logError("tasks/get", "Error in tasks/get", error);
76
+ return callback(toJaysonError(INTERNAL_ERROR(error)));
77
+ }
78
+ },
79
+ "tasks/cancel": async (params, callback) => {
80
+ try {
81
+ const { id: taskId } = params;
82
+ if (!taskId) {
83
+ return callback(toJaysonError(INVALID_PARAMS()));
84
+ }
85
+ // Load the task
86
+ const data = await taskStore.load(taskId);
87
+ if (!data) {
88
+ return callback(toJaysonError(TASK_NOT_FOUND()));
89
+ }
90
+ // Check if task is already in a final state
91
+ const finalStates = ["completed", "failed", "canceled"];
92
+ if (finalStates.includes(data.task.status.state)) {
93
+ return callback(toJaysonError(TASK_NOT_CANCELABLE()));
94
+ }
95
+ // Mark as cancelled
96
+ activeCancellations.add(taskId);
97
+ // Create updated task with canceled status
98
+ const canceledTask = {
99
+ ...data.task,
100
+ status: {
101
+ state: "canceled",
102
+ timestamp: getCurrentTimestamp(),
103
+ message: {
104
+ role: "agent",
105
+ parts: [{ type: "text", text: "Task was canceled." }],
106
+ },
107
+ },
108
+ };
109
+ const updatedData = {
110
+ task: canceledTask,
111
+ history: data.history,
112
+ };
113
+ await taskStore.save(updatedData);
114
+ closeStreamsForTask(taskId);
115
+ return callback(null, canceledTask);
116
+ }
117
+ catch (error) {
118
+ logError("tasks/cancel", "Error in tasks/cancel", error);
119
+ callback(toJaysonError(INTERNAL_ERROR(error)));
120
+ }
121
+ },
122
+ "tasks/pushNotification/set": async (params, callback) => {
123
+ try {
124
+ logWarn("tasks/pushNotification/set", "Push notifications are not fully implemented.");
125
+ if (!card.capabilities?.pushNotifications) {
126
+ return callback(toJaysonError(METHOD_NOT_FOUND()));
127
+ }
128
+ const config = params;
129
+ // Basic validation
130
+ if (!config.id) {
131
+ return callback(toJaysonError(INVALID_PARAMS()));
132
+ }
133
+ if (!config.pushNotificationConfig?.url) {
134
+ return callback(toJaysonError(INVALID_PARAMS()));
135
+ }
136
+ // Verify the task exists
137
+ const data = await taskStore.load(config.id);
138
+ if (!data) {
139
+ return callback(toJaysonError(TASK_NOT_FOUND()));
140
+ }
141
+ // In a real implementation, we'd store this config
142
+ // For now, we'll just return it
143
+ return callback(null, config);
144
+ }
145
+ catch (error) {
146
+ logError("tasks/pushNotification/set", "Error in tasks/pushNotification/set", error);
147
+ return callback(toJaysonError(INTERNAL_ERROR(error)));
148
+ }
149
+ },
150
+ "tasks/pushNotification/get": async (params, callback) => {
151
+ try {
152
+ logWarn("tasks/pushNotification/get", "Push notifications are not fully implemented.");
153
+ if (!card.capabilities?.pushNotifications) {
154
+ return callback(toJaysonError(PUSH_NOTIFICATION_NOT_SUPPORTED()));
155
+ }
156
+ const { id: taskId } = params;
157
+ if (!taskId) {
158
+ return callback(toJaysonError(INVALID_PARAMS()));
159
+ }
160
+ // Verify the task exists
161
+ const data = await taskStore.load(taskId);
162
+ if (!data) {
163
+ return callback(toJaysonError(TASK_NOT_FOUND()));
164
+ }
165
+ // In a real implementation, we'd retrieve a stored config
166
+ // For now, return null (no push notification config)
167
+ return callback(null, null);
168
+ }
169
+ catch (error) {
170
+ logError("tasks/pushNotification/get", "Error in tasks/pushNotification/get", error);
171
+ return callback(toJaysonError(INTERNAL_ERROR(error)));
172
+ }
173
+ },
174
+ }, {
175
+ //server options
176
+ reviver: undefined,
177
+ replacer: undefined,
178
+ });
179
+ }
180
+ //# sourceMappingURL=json-middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-middleware.js","sourceRoot":"","sources":["../../../src/server/lib/json-middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EACL,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,+BAA+B,EAC/B,mBAAmB,EACnB,cAAc,EACd,aAAa,GAEd,MAAM,8BAA8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OAAO,KAAK,EAAE,CAAC;gBACf,QAAQ,CACN,4BAA4B,EAC5B,qCAAqC,EACrC,KAAK,CACN,CAAC;gBACF,OAAO,QAAQ,CAAC,aAAa,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACxD,CAAC;QACH,CAAC;KACF,EACD;QACE,gBAAgB;QAChB,OAAO,EAAE,SAAS;QAClB,QAAQ,EAAE,SAAS;KACpB,CACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,28 @@
1
+ import { Task, TaskStatus, Artifact, Message, TaskYieldUpdate } from "../../types/extended-schema.js";
2
+ import { TaskAndHistory } from "../interfaces/store.js";
3
+ import { TaskStore } from "../interfaces/store.js";
4
+ export declare function updateTaskStatus(task: Task, update: TaskYieldUpdate): TaskStatus;
5
+ export declare function checkBounds(index: number, length: number): boolean;
6
+ export declare function updateByIndex(artifacts: Artifact[], index: number, update: Artifact): {
7
+ artifacts: Artifact[];
8
+ replaced: boolean;
9
+ };
10
+ export declare function updateByName(artifacts: Artifact[], update: Artifact): {
11
+ artifacts: Artifact[];
12
+ replaced: boolean;
13
+ };
14
+ export declare function processArtifactUpdate(artifacts: Artifact[], update: Artifact): {
15
+ artifacts: Artifact[];
16
+ replaced: boolean;
17
+ };
18
+ export declare function updateState(taskStore: TaskStore, current: TaskAndHistory, update: TaskYieldUpdate): Promise<TaskAndHistory>;
19
+ /**
20
+ * Loads or creates a task and its history.
21
+ * @param taskId The task ID
22
+ * @param message The message to process
23
+ * @param sessionId Optional session ID
24
+ * @param metadata Optional metadata
25
+ * @returns The task and history
26
+ */
27
+ export declare function loadState(taskStore: TaskStore, taskId: string, message: Message, sessionId?: string, metadata?: Record<string, unknown> | null): Promise<TaskAndHistory>;
28
+ //# sourceMappingURL=state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../../../src/server/lib/state.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,IAAI,EACJ,UAAU,EACV,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"}
@@ -0,0 +1,108 @@
1
+ import { getCurrentTimestamp, isArtifactUpdate, isTaskStatusUpdate, } from "../../utils/common/utils.js";
2
+ import { INVALID_REQUEST } from "../../utils/common/errors.js";
3
+ export function updateTaskStatus(task, update) {
4
+ return { ...task.status, ...update, timestamp: getCurrentTimestamp() };
5
+ }
6
+ export function checkBounds(index, length) {
7
+ return index >= 0 && index < length;
8
+ }
9
+ export function updateByIndex(artifacts, index, update) {
10
+ const existingArtifact = artifacts[index];
11
+ if (update.append) {
12
+ //deep copy to avoid mutating original
13
+ const appendedArtifact = JSON.parse(JSON.stringify(existingArtifact));
14
+ appendedArtifact.parts.push(...update.parts);
15
+ if (update.metadata) {
16
+ appendedArtifact.metadata = {
17
+ ...(appendedArtifact.metadata || {}),
18
+ ...update.metadata,
19
+ };
20
+ }
21
+ if (update.lastChunk !== undefined) {
22
+ appendedArtifact.lastChunk = update.lastChunk;
23
+ }
24
+ if (update.description) {
25
+ appendedArtifact.description = update.description;
26
+ }
27
+ artifacts[index] = appendedArtifact;
28
+ }
29
+ else {
30
+ artifacts[index] = { ...update };
31
+ }
32
+ return { artifacts, replaced: true };
33
+ }
34
+ export function updateByName(artifacts, update) {
35
+ const namedIndex = artifacts.findIndex((a) => a.name === update.name);
36
+ if (namedIndex >= 0) {
37
+ artifacts[namedIndex] = { ...update };
38
+ return { artifacts, replaced: true };
39
+ }
40
+ return { artifacts: artifacts, replaced: false };
41
+ }
42
+ export function processArtifactUpdate(artifacts, update) {
43
+ const existingIndex = update.index ?? -1;
44
+ let replaced = false;
45
+ let newArtifacts = artifacts;
46
+ if (checkBounds(existingIndex, artifacts.length)) {
47
+ ({ artifacts: newArtifacts, replaced } = updateByIndex(artifacts, existingIndex, update));
48
+ }
49
+ else if (update.name) {
50
+ ({ artifacts: newArtifacts, replaced } = updateByName(artifacts, update));
51
+ }
52
+ if (!replaced) {
53
+ newArtifacts.push({ ...update });
54
+ if (newArtifacts.some((a) => a.index !== undefined)) {
55
+ newArtifacts.sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
56
+ }
57
+ replaced = true;
58
+ }
59
+ return { artifacts: newArtifacts, replaced };
60
+ }
61
+ export async function updateState(taskStore, current, update) {
62
+ const newTask = { ...current.task };
63
+ const newHistory = [...current.history];
64
+ if (isTaskStatusUpdate(update)) {
65
+ newTask.status = updateTaskStatus(newTask, update);
66
+ if (update.message?.role === "agent") {
67
+ newHistory.push(update.message);
68
+ }
69
+ }
70
+ else if (isArtifactUpdate(update)) {
71
+ const artifacts = !newTask.artifacts ? [] : [...newTask.artifacts];
72
+ const { artifacts: newArtifacts, replaced } = processArtifactUpdate(artifacts, update);
73
+ if (!replaced) {
74
+ throw INVALID_REQUEST();
75
+ }
76
+ newTask.artifacts = newArtifacts;
77
+ }
78
+ const currentData = { task: newTask, history: newHistory };
79
+ await taskStore.save(currentData);
80
+ return currentData;
81
+ }
82
+ /**
83
+ * Loads or creates a task and its history.
84
+ * @param taskId The task ID
85
+ * @param message The message to process
86
+ * @param sessionId Optional session ID
87
+ * @param metadata Optional metadata
88
+ * @returns The task and history
89
+ */
90
+ export async function loadState(taskStore, taskId, message, sessionId, metadata) {
91
+ const existingData = await taskStore.load(taskId);
92
+ if (existingData) {
93
+ return existingData;
94
+ }
95
+ const timestamp = getCurrentTimestamp();
96
+ const newTask = {
97
+ id: taskId,
98
+ sessionId: sessionId || null,
99
+ status: {
100
+ state: "submitted",
101
+ timestamp,
102
+ },
103
+ metadata: metadata || null,
104
+ };
105
+ const newHistory = [message];
106
+ return { task: newTask, history: newHistory };
107
+ }
108
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../../../src/server/lib/state.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AASrC,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAG/D,MAAM,UAAU,gBA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,CAAC;IAED,MAAM,WAAW,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC;IAC3D,MAAM,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IAElC,OAAO,WAAW,CAAC;AACrB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,SAAoB,EACpB,MAAc,EACd,OAAgB,EAChB,SAAkB,EAClB,QAAyC;IAEzC,MAAM,YAAY,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAClD,IAAI,YAAY,EAAE,CAAC;QACjB,OAAO,YAAY,CAAC;IACtB,CAAC;IACD,MAAM,SAAS,GAAG,mBAAmB,EAAE,CAAC;IACxC,MAAM,OAAO,GAAS;QACpB,EAAE,EAAE,MAAM;QACV,SAAS,EAAE,SAAS,IAAI,IAAI;QAC5B,MAAM,EAAE;YACN,KAAK,EAAE,WAAW;YAClB,SAAS;SACV;QACD,QAAQ,EAAE,QAAQ,IAAI,IAAI;KAC3B,CAAC;IACF,MAAM,UAAU,GAAc,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC;AAChD,CAAC"}
@@ -0,0 +1,62 @@
1
+ import { TaskAndHistory, TaskStore } from "../../interfaces/store.js";
2
+ /**
3
+ * File-based implementation of the TaskStore interface.
4
+ * Stores tasks and their history as JSON files on disk.
5
+ */
6
+ export declare class FileStore implements TaskStore {
7
+ private baseDir;
8
+ /**
9
+ * Creates a new FileStore.
10
+ * @param baseDir The base directory to store task files in.
11
+ */
12
+ constructor(baseDir: string);
13
+ /**
14
+ * Constructs the file path for a task.
15
+ * @param taskId The task ID
16
+ * @returns The full file path for the task JSON file
17
+ */
18
+ private getTaskFilePath;
19
+ /**
20
+ * Constructs the file path for a task's history.
21
+ * @param taskId The task ID
22
+ * @returns The full file path for the history JSON file
23
+ */
24
+ private getHistoryFilePath;
25
+ /**
26
+ * Ensures the base directory exists.
27
+ * @returns A promise that resolves when the directory exists.
28
+ */
29
+ private ensureBaseDir;
30
+ /**
31
+ * Writes data to a JSON file.
32
+ * @param filePath The path to write to
33
+ * @param data The data to write
34
+ * @returns A promise that resolves when the write is complete
35
+ */
36
+ private writeJsonFile;
37
+ /**
38
+ * Reads data from a JSON file.
39
+ * @param filePath The path to read from
40
+ * @returns A promise resolving to the parsed data, or null if the file doesn't exist
41
+ */
42
+ private readJsonFile;
43
+ /**
44
+ * Type guard to validate the structure of history file content.
45
+ * @param content The content to check
46
+ * @returns True if the content is a valid history file content
47
+ */
48
+ private isHistoryFileContent;
49
+ /**
50
+ * Loads a task and its history by task ID.
51
+ * @param taskId The ID of the task to load.
52
+ * @returns A promise resolving to the task and history, or null if not found.
53
+ */
54
+ load(taskId: string): Promise<TaskAndHistory | null>;
55
+ /**
56
+ * Saves a task and its history.
57
+ * @param data The task and history to save.
58
+ * @returns A promise that resolves when the save is complete.
59
+ */
60
+ save(data: TaskAndHistory): Promise<void>;
61
+ }
62
+ //# sourceMappingURL=file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file.d.ts","sourceRoot":"","sources":["../../../../src/server/lib/storage/file.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAMtE;;;GAGG;AACH,qBAAa,SAAU,YAAW,SAAS;IACzC,OAAO,CAAC,OAAO,CAAS;IAExB;;;OAGG;gBACS,OAAO,EAAE,MAAM;IAI3B;;;;OAIG;IACH,OAAO,CAAC,eAAe;IAIvB;;;;OAIG;IACH,OAAO,CAAC,kBAAkB;IAI1B;;;OAGG;YACW,aAAa;IAa3B;;;;;OAKG;YACW,aAAa;IAY3B;;;;OAIG;YACW,YAAY;IAc1B;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAW5B;;;;OAIG;IACG,IAAI,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;IA4C1D;;;;OAIG;IACG,IAAI,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAgBhD"}
@@ -0,0 +1,148 @@
1
+ import { logError, logDebug } from "../../../utils/logging/log.js";
2
+ import fs from "fs/promises";
3
+ import path from "path";
4
+ /**
5
+ * File-based implementation of the TaskStore interface.
6
+ * Stores tasks and their history as JSON files on disk.
7
+ */
8
+ export class FileStore {
9
+ /**
10
+ * Creates a new FileStore.
11
+ * @param baseDir The base directory to store task files in.
12
+ */
13
+ constructor(baseDir) {
14
+ this.baseDir = baseDir;
15
+ }
16
+ /**
17
+ * Constructs the file path for a task.
18
+ * @param taskId The task ID
19
+ * @returns The full file path for the task JSON file
20
+ */
21
+ getTaskFilePath(taskId) {
22
+ return path.join(this.baseDir, `${taskId}.task.json`);
23
+ }
24
+ /**
25
+ * Constructs the file path for a task's history.
26
+ * @param taskId The task ID
27
+ * @returns The full file path for the history JSON file
28
+ */
29
+ getHistoryFilePath(taskId) {
30
+ return path.join(this.baseDir, `${taskId}.history.json`);
31
+ }
32
+ /**
33
+ * Ensures the base directory exists.
34
+ * @returns A promise that resolves when the directory exists.
35
+ */
36
+ async ensureBaseDir() {
37
+ try {
38
+ await fs.mkdir(this.baseDir, { recursive: true });
39
+ }
40
+ catch (error) {
41
+ logError("FileStore", `Failed to create directory: ${this.baseDir}`, error);
42
+ throw error;
43
+ }
44
+ }
45
+ /**
46
+ * Writes data to a JSON file.
47
+ * @param filePath The path to write to
48
+ * @param data The data to write
49
+ * @returns A promise that resolves when the write is complete
50
+ */
51
+ async writeJsonFile(filePath, data) {
52
+ try {
53
+ await this.ensureBaseDir();
54
+ await fs.writeFile(filePath, JSON.stringify(data, null, 2), {
55
+ encoding: "utf8",
56
+ });
57
+ }
58
+ catch (error) {
59
+ logError("FileStore", `Failed to write file: ${filePath}`, error);
60
+ throw error;
61
+ }
62
+ }
63
+ /**
64
+ * Reads data from a JSON file.
65
+ * @param filePath The path to read from
66
+ * @returns A promise resolving to the parsed data, or null if the file doesn't exist
67
+ */
68
+ async readJsonFile(filePath) {
69
+ try {
70
+ const content = await fs.readFile(filePath, { encoding: "utf8" });
71
+ return JSON.parse(content);
72
+ }
73
+ catch (error) {
74
+ if (error.code === "ENOENT") {
75
+ // File not found - return null rather than throwing
76
+ return null;
77
+ }
78
+ logError("FileStore", `Failed to read file: ${filePath}`, error);
79
+ throw error;
80
+ }
81
+ }
82
+ /**
83
+ * Type guard to validate the structure of history file content.
84
+ * @param content The content to check
85
+ * @returns True if the content is a valid history file content
86
+ */
87
+ isHistoryFileContent(content) {
88
+ return (typeof content === "object" &&
89
+ content !== null &&
90
+ "messageHistory" in content &&
91
+ Array.isArray(content.messageHistory));
92
+ }
93
+ /**
94
+ * Loads a task and its history by task ID.
95
+ * @param taskId The ID of the task to load.
96
+ * @returns A promise resolving to the task and history, or null if not found.
97
+ */
98
+ async load(taskId) {
99
+ logDebug("FileStore", `Loading task: ${taskId}`);
100
+ const taskFilePath = this.getTaskFilePath(taskId);
101
+ const historyFilePath = this.getHistoryFilePath(taskId);
102
+ // Read task file first - if it doesn't exist, the task doesn't exist.
103
+ const task = await this.readJsonFile(taskFilePath);
104
+ if (!task) {
105
+ return null; // Task not found
106
+ }
107
+ // Task exists, now try to read history. It might not exist yet.
108
+ let history = [];
109
+ try {
110
+ const historyContent = await this.readJsonFile(historyFilePath);
111
+ // Validate the structure
112
+ if (this.isHistoryFileContent(historyContent)) {
113
+ history = historyContent.messageHistory;
114
+ }
115
+ else if (historyContent !== null) {
116
+ // Log a warning if the history file exists but is malformed
117
+ logError("FileStore", `Malformed history file found for task ${taskId}`, new Error("Invalid history file format"), { path: historyFilePath });
118
+ // Proceed with empty history
119
+ }
120
+ // If historyContent is null (file not found), history remains []
121
+ }
122
+ catch (error) {
123
+ // Log error reading history but proceed with empty history
124
+ logError("FileStore", `Error reading history file for task ${taskId}`, error, { path: historyFilePath });
125
+ // Proceed with empty history
126
+ }
127
+ return { task, history };
128
+ }
129
+ /**
130
+ * Saves a task and its history.
131
+ * @param data The task and history to save.
132
+ * @returns A promise that resolves when the save is complete.
133
+ */
134
+ async save(data) {
135
+ logDebug("FileStore", `Saving task: ${data.task.id}`);
136
+ const taskFilePath = this.getTaskFilePath(data.task.id);
137
+ const historyFilePath = this.getHistoryFilePath(data.task.id);
138
+ // For simplicity and atomicity, we'll write each file individually
139
+ // First, write the task file
140
+ await this.writeJsonFile(taskFilePath, data.task);
141
+ // Then, write the history file
142
+ // We'll wrap it in an object to allow for future extensibility
143
+ await this.writeJsonFile(historyFilePath, {
144
+ messageHistory: data.history,
145
+ });
146
+ }
147
+ }
148
+ //# sourceMappingURL=file.js.map