@eggjs/agent-runtime 3.73.0-beta.0 → 4.0.2-beta.4

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/dist/AgentRuntime.d.ts +46 -0
  3. package/dist/AgentRuntime.js +298 -0
  4. package/dist/AgentStoreUtils.d.ts +7 -0
  5. package/dist/AgentStoreUtils.js +18 -0
  6. package/dist/HttpSSEWriter.d.ts +20 -0
  7. package/dist/HttpSSEWriter.js +49 -0
  8. package/dist/MessageConverter.d.ts +36 -0
  9. package/dist/MessageConverter.js +123 -0
  10. package/dist/OSSAgentStore.d.ts +66 -0
  11. package/dist/OSSAgentStore.js +133 -0
  12. package/dist/OSSObjectStorageClient.d.ts +51 -0
  13. package/dist/OSSObjectStorageClient.js +78 -0
  14. package/dist/RunBuilder.d.ts +47 -0
  15. package/dist/RunBuilder.js +129 -0
  16. package/dist/SSEWriter.d.ts +17 -0
  17. package/dist/SSEWriter.js +1 -0
  18. package/dist/index.d.ts +10 -10
  19. package/dist/index.js +11 -31
  20. package/package.json +35 -25
  21. package/dist/src/AgentRuntime.d.ts +0 -42
  22. package/dist/src/AgentRuntime.js +0 -376
  23. package/dist/src/AgentStore.d.ts +0 -42
  24. package/dist/src/AgentStore.js +0 -3
  25. package/dist/src/AgentStoreUtils.d.ts +0 -4
  26. package/dist/src/AgentStoreUtils.js +0 -23
  27. package/dist/src/FileAgentStore.d.ts +0 -21
  28. package/dist/src/FileAgentStore.js +0 -104
  29. package/dist/src/HttpSSEWriter.d.ts +0 -16
  30. package/dist/src/HttpSSEWriter.js +0 -51
  31. package/dist/src/MessageConverter.d.ts +0 -32
  32. package/dist/src/MessageConverter.js +0 -108
  33. package/dist/src/OSSAgentStore.d.ts +0 -62
  34. package/dist/src/OSSAgentStore.js +0 -165
  35. package/dist/src/OSSObjectStorageClient.d.ts +0 -46
  36. package/dist/src/OSSObjectStorageClient.js +0 -90
  37. package/dist/src/RunBuilder.d.ts +0 -43
  38. package/dist/src/RunBuilder.js +0 -127
  39. package/dist/src/SSEWriter.d.ts +0 -14
  40. package/dist/src/SSEWriter.js +0 -3
  41. package/dist/src/agentDefaults.d.ts +0 -1
  42. package/dist/src/agentDefaults.js +0 -447
  43. package/dist/src/enhanceAgentController.d.ts +0 -2
  44. package/dist/src/enhanceAgentController.js +0 -90
@@ -0,0 +1,133 @@
1
+ import { newRunId, newThreadId, nowUnix } from "./AgentStoreUtils.js";
2
+ import { AgentNotFoundError, AgentObjectType, RunStatus } from "@eggjs/tegg-types/agent-runtime";
3
+
4
+ //#region src/OSSAgentStore.ts
5
+ /**
6
+ * AgentStore implementation backed by an ObjectStorageClient (OSS, S3, etc.).
7
+ *
8
+ * ## Storage layout
9
+ *
10
+ * ```
11
+ * {prefix}threads/{id}/meta.json — Thread metadata (JSON)
12
+ * {prefix}threads/{id}/messages.jsonl — Messages (JSONL, one JSON object per line)
13
+ * {prefix}runs/{id}.json — Run record (JSON)
14
+ * ```
15
+ *
16
+ * ### Why split threads into two keys?
17
+ *
18
+ * Thread messages are append-only: new messages are added at the end but never
19
+ * modified or deleted. Storing them as a JSONL file allows us to leverage the
20
+ * OSS AppendObject API (or similar) to write new messages without reading the
21
+ * entire thread first. This is much more efficient than read-modify-write for
22
+ * long conversations.
23
+ *
24
+ * If the underlying ObjectStorageClient provides an `append()` method, it will
25
+ * be used for O(1) message writes. Otherwise, the store falls back to
26
+ * get-concat-put (which is NOT atomic and may lose data under concurrent
27
+ * writers — acceptable for single-writer scenarios).
28
+ *
29
+ * ### Atomicity note
30
+ *
31
+ * Run updates still use read-modify-write because run fields are mutated
32
+ * (status, timestamps, output, etc.) — they cannot be modelled as append-only.
33
+ * For multi-writer safety, consider a database-backed AgentStore or ETag-based
34
+ * conditional writes with retry.
35
+ */
36
+ var OSSAgentStore = class {
37
+ client;
38
+ prefix;
39
+ constructor(options) {
40
+ this.client = options.client;
41
+ const raw = options.prefix ?? "";
42
+ this.prefix = raw && !raw.endsWith("/") ? raw + "/" : raw;
43
+ }
44
+ /** Key for thread metadata (JSON). */
45
+ threadMetaKey(threadId) {
46
+ return `${this.prefix}threads/${threadId}/meta.json`;
47
+ }
48
+ /** Key for thread messages (JSONL, one message per line). */
49
+ threadMessagesKey(threadId) {
50
+ return `${this.prefix}threads/${threadId}/messages.jsonl`;
51
+ }
52
+ /** Key for run record (JSON). */
53
+ runKey(runId) {
54
+ return `${this.prefix}runs/${runId}.json`;
55
+ }
56
+ async init() {
57
+ await this.client.init?.();
58
+ }
59
+ async destroy() {
60
+ await this.client.destroy?.();
61
+ }
62
+ async createThread(metadata) {
63
+ const threadId = newThreadId();
64
+ const meta = {
65
+ id: threadId,
66
+ object: AgentObjectType.Thread,
67
+ metadata: metadata ?? {},
68
+ createdAt: nowUnix()
69
+ };
70
+ await this.client.put(this.threadMetaKey(threadId), JSON.stringify(meta));
71
+ return {
72
+ ...meta,
73
+ messages: []
74
+ };
75
+ }
76
+ async getThread(threadId) {
77
+ const [metaData, messagesData] = await Promise.all([this.client.get(this.threadMetaKey(threadId)), this.client.get(this.threadMessagesKey(threadId))]);
78
+ if (!metaData) throw new AgentNotFoundError(`Thread ${threadId} not found`);
79
+ const meta = JSON.parse(metaData);
80
+ const messages = messagesData ? messagesData.trim().split("\n").filter((line) => line.length > 0).map((line) => JSON.parse(line)) : [];
81
+ return {
82
+ ...meta,
83
+ messages
84
+ };
85
+ }
86
+ /**
87
+ * Append messages to a thread.
88
+ *
89
+ * Each message is serialized as a single JSON line (JSONL format).
90
+ * When the underlying client supports `append()`, this is a single
91
+ * O(1) write — no need to read the existing messages first.
92
+ */
93
+ async appendMessages(threadId, messages) {
94
+ if (!await this.client.get(this.threadMetaKey(threadId))) throw new AgentNotFoundError(`Thread ${threadId} not found`);
95
+ if (messages.length === 0) return;
96
+ const lines = messages.map((m) => JSON.stringify(m)).join("\n") + "\n";
97
+ const messagesKey = this.threadMessagesKey(threadId);
98
+ if (this.client.append) await this.client.append(messagesKey, lines);
99
+ else {
100
+ const existing = await this.client.get(messagesKey) ?? "";
101
+ await this.client.put(messagesKey, existing + lines);
102
+ }
103
+ }
104
+ async createRun(input, threadId, config, metadata) {
105
+ const runId = newRunId();
106
+ const record = {
107
+ id: runId,
108
+ object: AgentObjectType.ThreadRun,
109
+ threadId,
110
+ status: RunStatus.Queued,
111
+ input,
112
+ config,
113
+ metadata,
114
+ createdAt: nowUnix()
115
+ };
116
+ await this.client.put(this.runKey(runId), JSON.stringify(record));
117
+ return record;
118
+ }
119
+ async getRun(runId) {
120
+ const data = await this.client.get(this.runKey(runId));
121
+ if (!data) throw new AgentNotFoundError(`Run ${runId} not found`);
122
+ return JSON.parse(data);
123
+ }
124
+ async updateRun(runId, updates) {
125
+ const run = await this.getRun(runId);
126
+ const { id: _, object: __, ...safeUpdates } = updates;
127
+ Object.assign(run, safeUpdates);
128
+ await this.client.put(this.runKey(runId), JSON.stringify(run));
129
+ }
130
+ };
131
+
132
+ //#endregion
133
+ export { OSSAgentStore };
@@ -0,0 +1,51 @@
1
+ import { ObjectStorageClient } from "@eggjs/tegg-types/agent-runtime";
2
+ import { OSSObject } from "oss-client";
3
+
4
+ //#region src/OSSObjectStorageClient.d.ts
5
+
6
+ /**
7
+ * ObjectStorageClient backed by Alibaba Cloud OSS (via oss-client).
8
+ *
9
+ * Supports both `put`/`get` for normal objects and `append` for
10
+ * OSS Appendable Objects. The append path uses a local position cache
11
+ * to avoid extra HEAD requests; on position mismatch it falls back to
12
+ * HEAD + retry automatically.
13
+ *
14
+ * The OSSObject instance should be constructed and injected by the caller,
15
+ * following the IoC/DI principle.
16
+ */
17
+ declare class OSSObjectStorageClient implements ObjectStorageClient {
18
+ private readonly client;
19
+ /**
20
+ * In-memory cache of next-append positions.
21
+ *
22
+ * After each successful `append()`, OSS returns `nextAppendPosition`.
23
+ * We cache it here so the next append can skip a HEAD round-trip.
24
+ * If the cached position is stale (e.g., process restarted or another
25
+ * writer appended), the append will fail with PositionNotEqualToLength
26
+ * and we fall back to HEAD + retry.
27
+ */
28
+ private readonly appendPositions;
29
+ constructor(client: OSSObject);
30
+ put(key: string, value: string): Promise<void>;
31
+ get(key: string): Promise<string | null>;
32
+ /**
33
+ * Append data to an OSS Appendable Object.
34
+ *
35
+ * OSS AppendObject requires a `position` parameter that must equal the
36
+ * current object size. We use a three-step strategy:
37
+ *
38
+ * 1. Use the cached position (0 for new objects, or the value from the
39
+ * last successful append).
40
+ * 2. If OSS returns PositionNotEqualToLength (cache is stale), issue a
41
+ * HEAD request to learn the current object size, then retry once.
42
+ * 3. Update the cache with `nextAppendPosition` from the response.
43
+ *
44
+ * This gives us single-round-trip performance in the common case (single
45
+ * writer, no restarts) while still being self-healing when the cache is
46
+ * stale.
47
+ */
48
+ append(key: string, value: string): Promise<void>;
49
+ }
50
+ //#endregion
51
+ export { OSSObjectStorageClient };
@@ -0,0 +1,78 @@
1
+ //#region src/OSSObjectStorageClient.ts
2
+ function isOSSError(err, code) {
3
+ return err != null && typeof err === "object" && "code" in err && err.code === code;
4
+ }
5
+ /**
6
+ * ObjectStorageClient backed by Alibaba Cloud OSS (via oss-client).
7
+ *
8
+ * Supports both `put`/`get` for normal objects and `append` for
9
+ * OSS Appendable Objects. The append path uses a local position cache
10
+ * to avoid extra HEAD requests; on position mismatch it falls back to
11
+ * HEAD + retry automatically.
12
+ *
13
+ * The OSSObject instance should be constructed and injected by the caller,
14
+ * following the IoC/DI principle.
15
+ */
16
+ var OSSObjectStorageClient = class {
17
+ client;
18
+ /**
19
+ * In-memory cache of next-append positions.
20
+ *
21
+ * After each successful `append()`, OSS returns `nextAppendPosition`.
22
+ * We cache it here so the next append can skip a HEAD round-trip.
23
+ * If the cached position is stale (e.g., process restarted or another
24
+ * writer appended), the append will fail with PositionNotEqualToLength
25
+ * and we fall back to HEAD + retry.
26
+ */
27
+ appendPositions = /* @__PURE__ */ new Map();
28
+ constructor(client) {
29
+ this.client = client;
30
+ }
31
+ async put(key, value) {
32
+ await this.client.put(key, Buffer.from(value, "utf-8"));
33
+ }
34
+ async get(key) {
35
+ try {
36
+ const result = await this.client.get(key);
37
+ if (result.content) return Buffer.isBuffer(result.content) ? result.content.toString("utf-8") : String(result.content);
38
+ return null;
39
+ } catch (err) {
40
+ if (isOSSError(err, "NoSuchKey")) return null;
41
+ throw err;
42
+ }
43
+ }
44
+ /**
45
+ * Append data to an OSS Appendable Object.
46
+ *
47
+ * OSS AppendObject requires a `position` parameter that must equal the
48
+ * current object size. We use a three-step strategy:
49
+ *
50
+ * 1. Use the cached position (0 for new objects, or the value from the
51
+ * last successful append).
52
+ * 2. If OSS returns PositionNotEqualToLength (cache is stale), issue a
53
+ * HEAD request to learn the current object size, then retry once.
54
+ * 3. Update the cache with `nextAppendPosition` from the response.
55
+ *
56
+ * This gives us single-round-trip performance in the common case (single
57
+ * writer, no restarts) while still being self-healing when the cache is
58
+ * stale.
59
+ */
60
+ async append(key, value) {
61
+ const buf = Buffer.from(value, "utf-8");
62
+ const position = this.appendPositions.get(key) ?? 0;
63
+ try {
64
+ const result = await this.client.append(key, buf, { position });
65
+ this.appendPositions.set(key, Number(result.nextAppendPosition));
66
+ } catch (err) {
67
+ if (isOSSError(err, "PositionNotEqualToLength")) {
68
+ const head = await this.client.head(key);
69
+ const currentPos = Number(head.res.headers["content-length"] ?? 0);
70
+ const result = await this.client.append(key, buf, { position: currentPos });
71
+ this.appendPositions.set(key, Number(result.nextAppendPosition));
72
+ } else throw err;
73
+ }
74
+ }
75
+ };
76
+
77
+ //#endregion
78
+ export { OSSObjectStorageClient };
@@ -0,0 +1,47 @@
1
+ import { MessageObject, RunObject, RunRecord } from "@eggjs/tegg-types/agent-runtime";
2
+
3
+ //#region src/RunBuilder.d.ts
4
+ /** Accumulated token usage — same shape as non-null RunRecord['usage']. */
5
+ type RunUsage = NonNullable<RunRecord["usage"]>;
6
+ /**
7
+ * Encapsulates run state transitions.
8
+ *
9
+ * Mutation methods (`start`, `complete`, `fail`, `cancel`) update internal
10
+ * state and return `Partial<RunRecord>` for the store.
11
+ *
12
+ * `snapshot()` produces a `RunObject` suitable for API responses and SSE events.
13
+ */
14
+ declare class RunBuilder {
15
+ private readonly id;
16
+ private readonly threadId;
17
+ private readonly createdAt;
18
+ private readonly metadata?;
19
+ private readonly config?;
20
+ private status;
21
+ private startedAt?;
22
+ private completedAt?;
23
+ private cancelledAt?;
24
+ private failedAt?;
25
+ private lastError?;
26
+ private usage?;
27
+ private output?;
28
+ private constructor();
29
+ /** Create a RunBuilder from a store RunRecord, using its own threadId. */
30
+ static fromRecord(run: RunRecord): RunBuilder;
31
+ /** Create a RunBuilder from a store RunRecord, restoring all mutable state. */
32
+ static create(run: RunRecord, threadId: string): RunBuilder;
33
+ /** queued -> in_progress. Returns store update. */
34
+ start(): Partial<RunRecord>;
35
+ /** in_progress -> completed. Returns store update. */
36
+ complete(output: MessageObject[], usage?: RunUsage): Partial<RunRecord>;
37
+ /** queued/in_progress -> failed. Returns store update. */
38
+ fail(error: Error): Partial<RunRecord>;
39
+ /** in_progress/queued -> cancelling (idempotent if already cancelling). Returns store update. */
40
+ cancelling(): Partial<RunRecord>;
41
+ /** cancelling -> cancelled. Returns store update. */
42
+ cancel(): Partial<RunRecord>;
43
+ /** Produce a RunObject snapshot for API / SSE. */
44
+ snapshot(): RunObject;
45
+ }
46
+ //#endregion
47
+ export { RunBuilder, RunUsage };
@@ -0,0 +1,129 @@
1
+ import { nowUnix } from "./AgentStoreUtils.js";
2
+ import { AgentErrorCode, AgentObjectType, InvalidRunStateTransitionError, RunStatus } from "@eggjs/tegg-types/agent-runtime";
3
+
4
+ //#region src/RunBuilder.ts
5
+ /**
6
+ * Encapsulates run state transitions.
7
+ *
8
+ * Mutation methods (`start`, `complete`, `fail`, `cancel`) update internal
9
+ * state and return `Partial<RunRecord>` for the store.
10
+ *
11
+ * `snapshot()` produces a `RunObject` suitable for API responses and SSE events.
12
+ */
13
+ var RunBuilder = class RunBuilder {
14
+ id;
15
+ threadId;
16
+ createdAt;
17
+ metadata;
18
+ config;
19
+ status;
20
+ startedAt;
21
+ completedAt;
22
+ cancelledAt;
23
+ failedAt;
24
+ lastError;
25
+ usage;
26
+ output;
27
+ constructor(id, threadId, createdAt, status, metadata, config) {
28
+ this.id = id;
29
+ this.threadId = threadId;
30
+ this.createdAt = createdAt;
31
+ this.status = status;
32
+ this.metadata = metadata;
33
+ this.config = config;
34
+ }
35
+ /** Create a RunBuilder from a store RunRecord, using its own threadId. */
36
+ static fromRecord(run) {
37
+ return RunBuilder.create(run, run.threadId ?? "");
38
+ }
39
+ /** Create a RunBuilder from a store RunRecord, restoring all mutable state. */
40
+ static create(run, threadId) {
41
+ const rb = new RunBuilder(run.id, threadId, run.createdAt, run.status, run.metadata, run.config);
42
+ rb.startedAt = run.startedAt ?? void 0;
43
+ rb.completedAt = run.completedAt ?? void 0;
44
+ rb.cancelledAt = run.cancelledAt ?? void 0;
45
+ rb.failedAt = run.failedAt ?? void 0;
46
+ rb.lastError = run.lastError ?? void 0;
47
+ rb.output = run.output;
48
+ if (run.usage) rb.usage = { ...run.usage };
49
+ return rb;
50
+ }
51
+ /** queued -> in_progress. Returns store update. */
52
+ start() {
53
+ if (this.status !== RunStatus.Queued) throw new InvalidRunStateTransitionError(this.status, RunStatus.InProgress);
54
+ this.status = RunStatus.InProgress;
55
+ this.startedAt = nowUnix();
56
+ return {
57
+ status: this.status,
58
+ startedAt: this.startedAt
59
+ };
60
+ }
61
+ /** in_progress -> completed. Returns store update. */
62
+ complete(output, usage) {
63
+ if (this.status !== RunStatus.InProgress) throw new InvalidRunStateTransitionError(this.status, RunStatus.Completed);
64
+ this.status = RunStatus.Completed;
65
+ this.completedAt = nowUnix();
66
+ this.output = output;
67
+ this.usage = usage;
68
+ return {
69
+ status: this.status,
70
+ output,
71
+ usage,
72
+ completedAt: this.completedAt
73
+ };
74
+ }
75
+ /** queued/in_progress -> failed. Returns store update. */
76
+ fail(error) {
77
+ if (this.status !== RunStatus.InProgress && this.status !== RunStatus.Queued) throw new InvalidRunStateTransitionError(this.status, RunStatus.Failed);
78
+ this.status = RunStatus.Failed;
79
+ this.failedAt = nowUnix();
80
+ this.lastError = {
81
+ code: AgentErrorCode.ExecError,
82
+ message: error.message
83
+ };
84
+ return {
85
+ status: this.status,
86
+ lastError: this.lastError,
87
+ failedAt: this.failedAt
88
+ };
89
+ }
90
+ /** in_progress/queued -> cancelling (idempotent if already cancelling). Returns store update. */
91
+ cancelling() {
92
+ if (this.status === RunStatus.Cancelling) return { status: this.status };
93
+ if (this.status !== RunStatus.InProgress && this.status !== RunStatus.Queued) throw new InvalidRunStateTransitionError(this.status, RunStatus.Cancelling);
94
+ this.status = RunStatus.Cancelling;
95
+ return { status: this.status };
96
+ }
97
+ /** cancelling -> cancelled. Returns store update. */
98
+ cancel() {
99
+ if (this.status !== RunStatus.Cancelling) throw new InvalidRunStateTransitionError(this.status, RunStatus.Cancelled);
100
+ this.status = RunStatus.Cancelled;
101
+ this.cancelledAt = nowUnix();
102
+ return {
103
+ status: this.status,
104
+ cancelledAt: this.cancelledAt
105
+ };
106
+ }
107
+ /** Produce a RunObject snapshot for API / SSE. */
108
+ snapshot() {
109
+ return {
110
+ id: this.id,
111
+ object: AgentObjectType.ThreadRun,
112
+ createdAt: this.createdAt,
113
+ threadId: this.threadId,
114
+ status: this.status,
115
+ lastError: this.lastError,
116
+ startedAt: this.startedAt ?? null,
117
+ completedAt: this.completedAt ?? null,
118
+ cancelledAt: this.cancelledAt ?? null,
119
+ failedAt: this.failedAt ?? null,
120
+ usage: this.usage ?? null,
121
+ metadata: this.metadata,
122
+ output: this.output,
123
+ config: this.config
124
+ };
125
+ }
126
+ };
127
+
128
+ //#endregion
129
+ export { RunBuilder };
@@ -0,0 +1,17 @@
1
+ //#region src/SSEWriter.d.ts
2
+ /**
3
+ * Abstract interface for writing SSE events.
4
+ * Decouples AgentRuntime from HTTP transport details.
5
+ */
6
+ interface SSEWriter {
7
+ /** Write an SSE event with the given name and JSON-serializable data. */
8
+ writeEvent(event: string, data: unknown): void;
9
+ /** Whether the underlying connection has been closed. */
10
+ readonly closed: boolean;
11
+ /** End the SSE stream. */
12
+ end(): void;
13
+ /** Register a callback for when the client disconnects. */
14
+ onClose(callback: () => void): void;
15
+ }
16
+ //#endregion
17
+ export { SSEWriter };
@@ -0,0 +1 @@
1
+ export { };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- export * from '@eggjs/tegg-types/agent-runtime';
2
- export * from './src/OSSObjectStorageClient';
3
- export * from './src/OSSAgentStore';
4
- export * from './src/AgentStoreUtils';
5
- export * from './src/MessageConverter';
6
- export * from './src/RunBuilder';
7
- export * from './src/SSEWriter';
8
- export * from './src/HttpSSEWriter';
9
- export { AgentRuntime, AGENT_RUNTIME } from './src/AgentRuntime';
10
- export type { AgentExecutor, AgentRuntimeOptions } from './src/AgentRuntime';
1
+ import { SSEWriter } from "./SSEWriter.js";
2
+ import { AGENT_RUNTIME, AgentExecutor, AgentRuntime, AgentRuntimeOptions } from "./AgentRuntime.js";
3
+ import { newMsgId, newRunId, newThreadId, nowUnix } from "./AgentStoreUtils.js";
4
+ import { HttpSSEWriter } from "./HttpSSEWriter.js";
5
+ import { RunBuilder, RunUsage } from "./RunBuilder.js";
6
+ import { MessageConverter } from "./MessageConverter.js";
7
+ import { OSSAgentStore, OSSAgentStoreOptions } from "./OSSAgentStore.js";
8
+ import { OSSObjectStorageClient } from "./OSSObjectStorageClient.js";
9
+ export * from "@eggjs/tegg-types/agent-runtime";
10
+ export { AGENT_RUNTIME, type AgentExecutor, AgentRuntime, type AgentRuntimeOptions, HttpSSEWriter, MessageConverter, OSSAgentStore, OSSAgentStoreOptions, OSSObjectStorageClient, RunBuilder, RunUsage, SSEWriter, newMsgId, newRunId, newThreadId, nowUnix };
package/dist/index.js CHANGED
@@ -1,31 +1,11 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.AGENT_RUNTIME = exports.AgentRuntime = void 0;
18
- // Re-export types from @eggjs/tegg-types (backward compatible)
19
- __exportStar(require("@eggjs/tegg-types/agent-runtime"), exports);
20
- // Implementation code
21
- __exportStar(require("./src/OSSObjectStorageClient"), exports);
22
- __exportStar(require("./src/OSSAgentStore"), exports);
23
- __exportStar(require("./src/AgentStoreUtils"), exports);
24
- __exportStar(require("./src/MessageConverter"), exports);
25
- __exportStar(require("./src/RunBuilder"), exports);
26
- __exportStar(require("./src/SSEWriter"), exports);
27
- __exportStar(require("./src/HttpSSEWriter"), exports);
28
- var AgentRuntime_1 = require("./src/AgentRuntime");
29
- Object.defineProperty(exports, "AgentRuntime", { enumerable: true, get: function () { return AgentRuntime_1.AgentRuntime; } });
30
- Object.defineProperty(exports, "AGENT_RUNTIME", { enumerable: true, get: function () { return AgentRuntime_1.AGENT_RUNTIME; } });
31
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLCtEQUErRDtBQUMvRCxrRUFBZ0Q7QUFDaEQsc0JBQXNCO0FBQ3RCLCtEQUE2QztBQUM3QyxzREFBb0M7QUFDcEMsd0RBQXNDO0FBQ3RDLHlEQUF1QztBQUN2QyxtREFBaUM7QUFDakMsa0RBQWdDO0FBQ2hDLHNEQUFvQztBQUNwQyxtREFBaUU7QUFBeEQsNEdBQUEsWUFBWSxPQUFBO0FBQUUsNkdBQUEsYUFBYSxPQUFBIn0=
1
+ import { newMsgId, newRunId, newThreadId, nowUnix } from "./AgentStoreUtils.js";
2
+ import { MessageConverter } from "./MessageConverter.js";
3
+ import { RunBuilder } from "./RunBuilder.js";
4
+ import { AGENT_RUNTIME, AgentRuntime } from "./AgentRuntime.js";
5
+ import { HttpSSEWriter } from "./HttpSSEWriter.js";
6
+ import { OSSAgentStore } from "./OSSAgentStore.js";
7
+ import { OSSObjectStorageClient } from "./OSSObjectStorageClient.js";
8
+
9
+ export * from "@eggjs/tegg-types/agent-runtime"
10
+
11
+ export { AGENT_RUNTIME, AgentRuntime, HttpSSEWriter, MessageConverter, OSSAgentStore, OSSObjectStorageClient, RunBuilder, newMsgId, newRunId, newThreadId, nowUnix };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eggjs/agent-runtime",
3
- "version": "3.73.0-beta.0",
3
+ "version": "4.0.2-beta.4",
4
4
  "description": "Agent runtime with store abstraction for Egg.js tegg",
5
5
  "keywords": [
6
6
  "agent",
@@ -9,42 +9,52 @@
9
9
  "store",
10
10
  "tegg"
11
11
  ],
12
- "homepage": "https://github.com/eggjs/tegg/tree/master/core/agent-runtime",
12
+ "homepage": "https://github.com/eggjs/egg/tree/next/tegg/core/agent-runtime",
13
13
  "bugs": {
14
- "url": "https://github.com/eggjs/tegg/issues"
14
+ "url": "https://github.com/eggjs/egg/issues"
15
15
  },
16
16
  "license": "MIT",
17
17
  "repository": {
18
18
  "type": "git",
19
- "url": "git+https://github.com/eggjs/tegg.git",
20
- "directory": "core/agent-runtime"
19
+ "url": "git+https://github.com/eggjs/egg.git",
20
+ "directory": "tegg/core/agent-runtime"
21
21
  },
22
22
  "files": [
23
- "dist",
24
- "index.js",
25
- "index.d.ts"
23
+ "dist"
26
24
  ],
27
- "main": "dist/index.js",
28
- "types": "dist/index.d.ts",
29
- "scripts": {
30
- "tsc": "tsc -p tsconfig.json",
31
- "tsc:pub": "tsc -p tsconfig.pub.json",
32
- "prepublishOnly": "npm run tsc:pub",
33
- "test": "mocha"
25
+ "type": "module",
26
+ "main": "./dist/index.js",
27
+ "module": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": "./dist/index.js",
31
+ "./AgentRuntime": "./dist/AgentRuntime.js",
32
+ "./AgentStoreUtils": "./dist/AgentStoreUtils.js",
33
+ "./HttpSSEWriter": "./dist/HttpSSEWriter.js",
34
+ "./MessageConverter": "./dist/MessageConverter.js",
35
+ "./OSSAgentStore": "./dist/OSSAgentStore.js",
36
+ "./OSSObjectStorageClient": "./dist/OSSObjectStorageClient.js",
37
+ "./RunBuilder": "./dist/RunBuilder.js",
38
+ "./SSEWriter": "./dist/SSEWriter.js",
39
+ "./package.json": "./package.json"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
34
43
  },
35
44
  "dependencies": {
36
- "@eggjs/tegg-types": "^3.73.0-beta.0",
37
- "egg-logger": "^3.0.1",
38
- "oss-client": "^2.5.1"
45
+ "egg-logger": "^3.5.0",
46
+ "oss-client": "^2.5.1",
47
+ "@eggjs/tegg-types": "4.0.2-beta.4"
39
48
  },
40
49
  "devDependencies": {
41
- "@types/mocha": "^10.0.0",
42
- "@types/node": "^20.0.0",
43
- "mocha": "^10.0.0",
44
- "typescript": "^5.0.0"
50
+ "@types/node": "^24.10.2",
51
+ "typescript": "^5.9.3"
45
52
  },
46
53
  "engines": {
47
- "node": ">= 16.0.0"
54
+ "node": ">=22.18.0"
48
55
  },
49
- "gitHead": "419d966f3efc649e533f165ba5d15994d7076722"
50
- }
56
+ "scripts": {
57
+ "typecheck": "tsgo --noEmit",
58
+ "test": "vitest run"
59
+ }
60
+ }
@@ -1,42 +0,0 @@
1
- import type { CreateRunInput, ThreadObject, ThreadObjectWithMessages, RunObject, AgentStreamMessage, AgentStore } from '@eggjs/tegg-types/agent-runtime';
2
- import type { EggLogger } from 'egg-logger';
3
- import type { SSEWriter } from './SSEWriter';
4
- export declare const AGENT_RUNTIME: unique symbol;
5
- /**
6
- * The executor interface — only requires execRun so the runtime can delegate
7
- * execution back through the controller's prototype chain (AOP/mock friendly).
8
- */
9
- export interface AgentExecutor {
10
- execRun(input: CreateRunInput, signal?: AbortSignal): AsyncGenerator<AgentStreamMessage>;
11
- }
12
- export interface AgentRuntimeOptions {
13
- executor: AgentExecutor;
14
- store: AgentStore;
15
- logger: EggLogger;
16
- }
17
- export declare class AgentRuntime {
18
- private static readonly TERMINAL_RUN_STATUSES;
19
- private store;
20
- private runningTasks;
21
- private executor;
22
- private logger;
23
- constructor(options: AgentRuntimeOptions);
24
- createThread(): Promise<ThreadObject>;
25
- getThread(threadId: string): Promise<ThreadObjectWithMessages>;
26
- private ensureThread;
27
- syncRun(input: CreateRunInput, signal?: AbortSignal): Promise<RunObject>;
28
- asyncRun(input: CreateRunInput): Promise<RunObject>;
29
- streamRun(input: CreateRunInput, writer: SSEWriter): Promise<void>;
30
- /**
31
- * Consume the execRun async generator, emitting SSE message.delta events
32
- * for each chunk and accumulating content blocks and token usage.
33
- */
34
- private consumeStreamMessages;
35
- getRun(runId: string): Promise<RunObject>;
36
- cancelRun(runId: string): Promise<RunObject>;
37
- /** Wait for all in-flight background tasks to complete naturally (without aborting). */
38
- waitForPendingTasks(): Promise<void>;
39
- destroy(): Promise<void>;
40
- /** Factory method — avoids the spread-arg type issue with dynamic delegation. */
41
- static create(options: AgentRuntimeOptions): AgentRuntime;
42
- }