@ap3x/agent-core 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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -0
  3. package/dist/agent-errors.d.ts +54 -0
  4. package/dist/agent-errors.d.ts.map +1 -0
  5. package/dist/agent-loop.d.ts +30 -0
  6. package/dist/agent-loop.d.ts.map +1 -0
  7. package/dist/agent.d.ts +160 -0
  8. package/dist/agent.d.ts.map +1 -0
  9. package/dist/backend.d.ts +67 -0
  10. package/dist/backend.d.ts.map +1 -0
  11. package/dist/compaction.d.ts +147 -0
  12. package/dist/compaction.d.ts.map +1 -0
  13. package/dist/concurrency.d.ts +32 -0
  14. package/dist/concurrency.d.ts.map +1 -0
  15. package/dist/conversation.d.ts +215 -0
  16. package/dist/conversation.d.ts.map +1 -0
  17. package/dist/env.d.ts +125 -0
  18. package/dist/env.d.ts.map +1 -0
  19. package/dist/errors.d.ts +37 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/harness.d.ts +110 -0
  22. package/dist/harness.d.ts.map +1 -0
  23. package/dist/index.d.ts +28 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +4153 -0
  26. package/dist/loader.d.ts +142 -0
  27. package/dist/loader.d.ts.map +1 -0
  28. package/dist/logger.d.ts +36 -0
  29. package/dist/logger.d.ts.map +1 -0
  30. package/dist/output-formatter.d.ts +27 -0
  31. package/dist/output-formatter.d.ts.map +1 -0
  32. package/dist/prompt-templates.d.ts +78 -0
  33. package/dist/prompt-templates.d.ts.map +1 -0
  34. package/dist/result.d.ts +26 -0
  35. package/dist/result.d.ts.map +1 -0
  36. package/dist/serialization.d.ts +75 -0
  37. package/dist/serialization.d.ts.map +1 -0
  38. package/dist/session-repo.d.ts +90 -0
  39. package/dist/session-repo.d.ts.map +1 -0
  40. package/dist/session.d.ts +251 -0
  41. package/dist/session.d.ts.map +1 -0
  42. package/dist/shell-blocklist.d.ts +18 -0
  43. package/dist/shell-blocklist.d.ts.map +1 -0
  44. package/dist/skills.d.ts +95 -0
  45. package/dist/skills.d.ts.map +1 -0
  46. package/dist/system-prompt.d.ts +90 -0
  47. package/dist/system-prompt.d.ts.map +1 -0
  48. package/dist/tools.d.ts +61 -0
  49. package/dist/tools.d.ts.map +1 -0
  50. package/dist/types.d.ts +320 -0
  51. package/dist/types.d.ts.map +1 -0
  52. package/dist/uuid.d.ts +23 -0
  53. package/dist/uuid.d.ts.map +1 -0
  54. package/package.json +33 -0
@@ -0,0 +1,215 @@
1
+ /**
2
+ * `Conversation` — the shared memory substrate for agents and swarms.
3
+ *
4
+ * An append-only, ordered transcript of `{role, content, ...}` messages with a
5
+ * free-form `role` (System / User / agent-name / "Tool Executor" / …). It is
6
+ * the shared memory every swarm orchestrator reads and writes, and the source
7
+ * the {@link import("./output-formatter").historyOutputFormatter} renders from.
8
+ *
9
+ * Beyond add/read/format, it provides:
10
+ * - JSON/YAML persistence (save/load/export/import),
11
+ * - token-budget management (dynamic auto-chunking + tokenizer truncation with
12
+ * a binary-search character cutoff),
13
+ * - MEMORY.md durable persistence (init/preload/append/archive/compact), keyed
14
+ * on the conversation **name** for cross-restart stability.
15
+ *
16
+ * Two invariants worth calling out: the id is generated **per instance** (never once at import
17
+ * time), and the `addMultiple` write order is deterministic — no shared-list race.
18
+ */
19
+ /** Estimate the number of tokens in a piece of text. */
20
+ export type TokenCounter = (text: string, model?: string) => number;
21
+ /** Provider-agnostic token estimate: ~4 characters per token. */
22
+ export declare function estimateTokens(text: string): number;
23
+ /** A single transcript entry. `role` is free-form; `content` is anything. */
24
+ export interface ConversationMessage {
25
+ role: string;
26
+ content: unknown;
27
+ timestamp?: string;
28
+ message_id?: string;
29
+ category?: string;
30
+ token_count?: number;
31
+ [key: string]: unknown;
32
+ }
33
+ /** A `{role, content}` provider-format message. */
34
+ export interface RoleContentMessage {
35
+ role: string;
36
+ content: unknown;
37
+ }
38
+ /** Generate a unique, per-call conversation id. */
39
+ export declare function generateConversationId(): string;
40
+ /** Resolve (and create) the default directory for stored conversations. */
41
+ export declare function getConversationDir(): string;
42
+ /** Constructor options for {@link Conversation}. */
43
+ export interface ConversationOptions {
44
+ id?: string;
45
+ name?: string;
46
+ systemPrompt?: string;
47
+ timeEnabled?: boolean;
48
+ autosave?: boolean;
49
+ saveFilepath?: string;
50
+ loadFilepath?: string;
51
+ contextLength?: number;
52
+ rules?: string;
53
+ customRulesPrompt?: string;
54
+ user?: string;
55
+ saveAsYamlOn?: boolean;
56
+ saveAsJsonBool?: boolean;
57
+ tokenCount?: boolean;
58
+ messageIdOn?: boolean;
59
+ tokenizerModelName?: string;
60
+ conversationsDir?: string;
61
+ exportMethod?: "json" | "yaml";
62
+ dynamicContextWindow?: boolean;
63
+ cacheEnabled?: boolean;
64
+ outputMetadata?: boolean;
65
+ memoryMdPath?: string;
66
+ /** Pluggable token counter (defaults to a chars/4 heuristic). */
67
+ countTokens?: TokenCounter;
68
+ }
69
+ export declare class Conversation {
70
+ readonly id: string;
71
+ name: string;
72
+ systemPrompt?: string;
73
+ timeEnabled: boolean;
74
+ autosave: boolean;
75
+ saveFilepath?: string;
76
+ loadFilepath?: string;
77
+ contextLength: number;
78
+ rules?: string;
79
+ customRulesPrompt?: string;
80
+ user: string;
81
+ saveAsYamlOn: boolean;
82
+ saveAsJsonBool: boolean;
83
+ tokenCount: boolean;
84
+ messageIdOn: boolean;
85
+ tokenizerModelName: string;
86
+ conversationsDir?: string;
87
+ exportMethod: "json" | "yaml";
88
+ dynamicContextWindow: boolean;
89
+ caching: boolean;
90
+ outputMetadata: boolean;
91
+ memoryMdPath?: string;
92
+ conversationHistory: ConversationMessage[];
93
+ private readonly countTokens;
94
+ private strCache;
95
+ private cacheHits;
96
+ private cacheMisses;
97
+ private lastCachedTokens;
98
+ private suppressMemoryMd;
99
+ constructor(options?: ConversationOptions);
100
+ private initializeNewConversation;
101
+ /** Append a message to the in-memory transcript (no MEMORY.md / autosave). */
102
+ addInMemory(role: string, content: unknown, category?: string): ConversationMessage;
103
+ /** Append a message; honors autosave. The primary write entrypoint. */
104
+ add(role: string, content: unknown, _metadata?: Record<string, unknown>, category?: string): ConversationMessage;
105
+ /** Append multiple messages in order (roles and contents must be equal length). */
106
+ addMultiple(roles: string[], contents: unknown[]): ConversationMessage[];
107
+ /** Alias of {@link addMultiple} that also honors autosave once. */
108
+ addMultipleMessages(roles: string[], contents: unknown[]): ConversationMessage[];
109
+ /** Append pre-built message objects directly. */
110
+ batchAdd(messages: ConversationMessage[]): void;
111
+ /** Append a tool's output as a message under `role`. */
112
+ addToolOutputToAgent(role: string, toolOutput: unknown): ConversationMessage;
113
+ /** Delete the message at `index`. */
114
+ delete(index: number): void;
115
+ /** Overwrite the role+content of the message at `index`. */
116
+ update(index: number, role: string, content: unknown): void;
117
+ /** Return the message at `index`, or undefined. */
118
+ query(index: number): ConversationMessage | undefined;
119
+ /** Remove every message. */
120
+ clear(): void;
121
+ /** Alias of {@link clear}. */
122
+ clearMemory(): void;
123
+ /** Return messages whose stringified content contains `keyword`. */
124
+ search(keyword: string): ConversationMessage[];
125
+ /** Alias of {@link search}. */
126
+ searchKeywordInConversation(keyword: string): ConversationMessage[];
127
+ /** Filter messages visible to `agentName` at/before `turn`. */
128
+ getVisibleMessages(agentName: string, turn: number): ConversationMessage[];
129
+ /** Count messages per role. */
130
+ countMessagesByRole(): Record<string, number>;
131
+ /** Return the transcript as a single `role: content` string (with caching). */
132
+ returnHistoryAsString(): string;
133
+ /** Alias of {@link returnHistoryAsString}. */
134
+ getStr(): string;
135
+ private buildHistoryString;
136
+ private historyStringWorker;
137
+ /** Cache stats for {@link returnHistoryAsString}. */
138
+ getCacheStats(): {
139
+ hits: number;
140
+ misses: number;
141
+ cachedTokens: number;
142
+ hitRate: number;
143
+ };
144
+ /** The raw transcript array — the canonical serialized form. */
145
+ toDict(): ConversationMessage[];
146
+ /** The transcript as a list (alias of {@link toDict}). */
147
+ toList(): ConversationMessage[];
148
+ /** The transcript serialized to a JSON string. */
149
+ toJson(): string;
150
+ /** The transcript serialized to a YAML string. */
151
+ toYaml(): string;
152
+ /** Each message as a `role: content` string. */
153
+ returnMessagesAsList(): string[];
154
+ /** Canonical provider format: `[{role, content}]`. */
155
+ returnMessagesAsDictionary(): RoleContentMessage[];
156
+ /** Provider format serialized to a pretty JSON string. */
157
+ returnJson(): string;
158
+ /** The last message as `role: content`, or "". */
159
+ getLastMessageAsString(): string;
160
+ /** The final message as `role: content`, or "". */
161
+ getFinalMessage(): string;
162
+ /** The content of the final message, or "". */
163
+ getFinalMessageContent(): unknown;
164
+ /** Final message content as a `[role, content]` 2-tuple. */
165
+ returnDictFinal(): [unknown, unknown];
166
+ /** Final message content wrapped in a single-element list. */
167
+ returnListFinal(): unknown[];
168
+ /** All messages except the first two (system + first user). */
169
+ returnAllExceptFirst(): ConversationMessage[];
170
+ /** {@link returnAllExceptFirst} rendered as a newline-joined content string. */
171
+ returnAllExceptFirstString(): string;
172
+ /** Save the transcript to `saveFilepath` as JSON. */
173
+ saveAsJson(force?: boolean): void;
174
+ /** Save the transcript to `saveFilepath` as YAML. */
175
+ saveAsYaml(force?: boolean): void;
176
+ /** Save using the configured `exportMethod`. */
177
+ export(force?: boolean): void;
178
+ /** Load the transcript from a JSON file. */
179
+ loadFromJson(filename: string): void;
180
+ /** Load the transcript from a YAML file. */
181
+ loadFromYaml(filename: string): void;
182
+ /** Load the transcript, dispatching on file extension. */
183
+ load(filename: string): void;
184
+ /** Export the transcript to `filename` (JSON for `.json`, plain text otherwise). */
185
+ exportConversation(filename: string): void;
186
+ /** Import a transcript from a JSON file. */
187
+ importConversation(filename: string): void;
188
+ /** Truncate, from the front, the rendered history so it fits `contextLength`. */
189
+ dynamicAutoChunking(): string;
190
+ private dynamicAutoChunkingWorker;
191
+ /** Truncate the transcript message-by-message until it fits `contextLength`. */
192
+ truncateMemoryWithTokenizer(): void;
193
+ /** Binary-search the longest prefix of `text` fitting `targetTokens`. */
194
+ binarySearchTruncate(text: string, targetTokens: number, modelName: string): string;
195
+ /** Sum tokens for messages tagged `category: "input"` / `"output"`. */
196
+ exportAndCountCategories(): {
197
+ inputTokens: number;
198
+ outputTokens: number;
199
+ totalTokens: number;
200
+ };
201
+ private initMemoryMd;
202
+ private preloadMemoryMd;
203
+ private appendToMemoryMd;
204
+ private archiveMemoryMd;
205
+ /**
206
+ * Collapse the interaction history into a single `summary`, preserving the
207
+ * static context (system prompt → rules → custom rules → summary). When
208
+ * MEMORY.md is configured it is archived, wiped, and re-seeded so the on-disk
209
+ * log stops growing across compactions.
210
+ */
211
+ compact(summary: string, summaryRole?: string): void;
212
+ /** Load a conversation by name (or explicit file) from a directory. */
213
+ static loadConversation(name: string, conversationsDir?: string, loadFilepath?: string): Conversation;
214
+ }
215
+ //# sourceMappingURL=conversation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conversation.d.ts","sourceRoot":"","sources":["../src/conversation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAcH,wDAAwD;AACxD,MAAM,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;AAEpE,iEAAiE;AACjE,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGnD;AAED,6EAA6E;AAC7E,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,mDAAmD;AACnD,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,C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ACjF,mBAAmB,IAAI,MAAM;IAQ7B,OAAO,CAAC,yBAAyB;IAuBjC,gFAAgF;IAChF,2BAA2B,IAAI,IAAI;IA4BnC,yEAAyE;IACzE,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM;IA8BnF,uEAAuE;IACvE,wBAAwB,IAAI;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE;IAmB9F,OAAO,CAAC,YAAY;IAcpB,OAAO,CAAC,eAAe;IAiBvB,OAAO,CAAC,gBAAgB;IAexB,OAAO,CAAC,eAAe;IAsBvB;;;;;OAKG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,SAAW,GAAG,IAAI;IAoCtD,uEAAuE;IACvE,MAAM,CAAC,gBAAgB,CACrB,IAAI,EAAE,MAAM,EACZ,gBAAgB,CAAC,EAAE,MAAM,EACzB,YAAY,CAAC,EAAE,MAAM,GACpB,YAAY;CAiBhB"}
package/dist/env.d.ts ADDED
@@ -0,0 +1,125 @@
1
+ import { ExecutionError, FileError } from "./errors";
2
+ import { type Result } from "./result";
3
+ /** Result of running a shell command. */
4
+ export interface ShellResult {
5
+ stdout: string;
6
+ stderr: string;
7
+ exitCode: number;
8
+ }
9
+ /** Options accepted by {@link Shell.exec}. */
10
+ export interface ExecOptions {
11
+ cwd?: string;
12
+ env?: Record<string, string>;
13
+ /** Timeout in milliseconds. The process tree is killed when it elapses. */
14
+ timeoutMs?: number;
15
+ signal?: AbortSignal;
16
+ onStdout?: (chunk: string) => void;
17
+ onStderr?: (chunk: string) => void;
18
+ }
19
+ /** Filesystem operations. Failures are returned as `Result`, never thrown. */
20
+ export interface FileSystem {
21
+ readTextFile(path: string, signal?: AbortSignal): Promise<Result<string, FileError>>;
22
+ /**
23
+ * Read a file as raw bytes (no text decoding). Optional so existing
24
+ * {@link FileSystem}/{@link ExecutionEnv} implementers keep compiling; callers
25
+ * must feature-detect it. Used by the `read` tool to serve images.
26
+ */
27
+ readBinaryFile?(path: string, signal?: AbortSignal): Promise<Result<Uint8Array, FileError>>;
28
+ writeTextFile(path: string, content: string, signal?: AbortSignal): Promise<Result<void, FileError>>;
29
+ appendTextFile(path: string, content: string): Promise<Result<void, FileError>>;
30
+ exists(path: string): Promise<boolean>;
31
+ listDir(path: string): Promise<Result<string[], FileError>>;
32
+ createDir(path: string, options?: {
33
+ recursive?: boolean;
34
+ }): Promise<Result<void, FileError>>;
35
+ remove(path: string, options?: {
36
+ recursive?: boolean;
37
+ force?: boolean;
38
+ }): Promise<Result<void, FileError>>;
39
+ resolvePath(path: string): string;
40
+ }
41
+ /** Shell command execution. */
42
+ export interface Shell {
43
+ exec(command: string, options?: ExecOptions): Promise<Result<ShellResult, ExecutionError>>;
44
+ }
45
+ /** A combined filesystem + shell execution environment. */
46
+ export interface ExecutionEnv extends FileSystem, Shell {
47
+ readonly cwd: string;
48
+ }
49
+ /**
50
+ * Resolve and classify the shell {@link NodeExecutionEnv} will run commands
51
+ * through, so callers (e.g. the CLI) can tell an LLM exactly what shell + OS it
52
+ * is driving. `kind` selects the command syntax family: `bash`/`sh` are POSIX,
53
+ * `cmd` is Windows cmd.exe.
54
+ */
55
+ export declare function detectShell(customShellPath?: string): Promise<{
56
+ shell: string;
57
+ kind: "bash" | "cmd" | "sh";
58
+ }>;
59
+ /** The default Node-backed {@link ExecutionEnv}. */
60
+ export declare class NodeExecutionEnv implements ExecutionEnv {
61
+ readonly cwd: string;
62
+ private readonly shellPath?;
63
+ private readonly shellEnv?;
64
+ /** When true (default), the shell blocklist rejects dangerous commands. */
65
+ readonly enforceBlocklist: boolean;
66
+ /**
67
+ * When true (default false), {@link writeTextFile} and {@link appendTextFile}
68
+ * reject any path that resolves outside {@link workspaceRoot}. Off by default
69
+ * so the write-anywhere behavior is unchanged unless explicitly opted in.
70
+ */
71
+ readonly restrictWritesToWorkspace: boolean;
72
+ /** The boundary used when {@link restrictWritesToWorkspace} is on. */
73
+ readonly workspaceRoot: string;
74
+ constructor(options: {
75
+ cwd: string;
76
+ shellPath?: string;
77
+ shellEnv?: Record<string, string>;
78
+ enforceBlocklist?: boolean;
79
+ restrictWritesToWorkspace?: boolean;
80
+ workspaceRoot?: string;
81
+ });
82
+ resolvePath(path: string): string;
83
+ /**
84
+ * Guard a mutating write when {@link restrictWritesToWorkspace} is on: returns
85
+ * a {@link FileError} when `resolved` falls outside {@link workspaceRoot}, else
86
+ * `undefined`. Inside/outside is computed with `path.relative` (NOT naive
87
+ * string prefixing, which mis-classifies `/work2` against `/work`): a path is
88
+ * inside iff the relative path is empty, is not absolute, and does not begin
89
+ * with a `..` segment. `path.relative` already normalizes separators and
90
+ * Windows drive-letter casing, so a cross-drive or traversal escape resolves
91
+ * to an absolute (or `..`-leading) relative path and is rejected.
92
+ */
93
+ private workspaceWriteError;
94
+ readTextFile(path: string, signal?: AbortSignal): Promise<Result<string, FileError>>;
95
+ readBinaryFile(path: string, signal?: AbortSignal): Promise<Result<Uint8Array, FileError>>;
96
+ writeTextFile(path: string, content: string, signal?: AbortSignal): Promise<Result<void, FileError>>;
97
+ appendTextFile(path: string, content: string): Promise<Result<void, FileError>>;
98
+ exists(path: string): Promise<boolean>;
99
+ listDir(path: string): Promise<Result<string[], FileError>>;
100
+ createDir(path: string, options?: {
101
+ recursive?: boolean;
102
+ }): Promise<Result<void, FileError>>;
103
+ remove(path: string, options?: {
104
+ recursive?: boolean;
105
+ force?: boolean;
106
+ }): Promise<Result<void, FileError>>;
107
+ exec(command: string, options?: ExecOptions): Promise<Result<ShellResult, ExecutionError>>;
108
+ }
109
+ /** A capture-and-truncate wrapper around {@link Shell.exec}. */
110
+ export interface ShellCaptureResult extends ShellResult {
111
+ truncated: boolean;
112
+ }
113
+ /**
114
+ * Run a command and capture its output, truncating each stream to a byte cap
115
+ * (default 50KiB) so a runaway command cannot blow up the transcript. Honors a
116
+ * timeout via an {@link AbortController}.
117
+ */
118
+ export declare function executeShellWithCapture(env: ExecutionEnv, command: string, options?: {
119
+ cwd?: string;
120
+ env?: Record<string, string>;
121
+ timeoutMs?: number;
122
+ maxOutputBytes?: number;
123
+ signal?: AbortSignal;
124
+ }): Promise<Result<ShellCaptureResult, ExecutionError>>;
125
+ //# sourceMappingURL=env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,EAAE,KAAK,MAAM,EAAoB,MAAM,UAAU,CAAC;AAGzD,yCAAyC;AACzC,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,8CAA8C;AAC9C,MAAM,WAAW,WAAW;IAC1B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,2EAA2E;IAC3E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CACpC;AAED,8EAA8E;AAC9E,MAAM,WAAW,UAAU;IACzB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;IACrF;;;;OAIG;IACH,cAAc,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,UAAU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AAE,MAAM,CAAC;IACxB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GACA,OAAO,CAAC,MAAM,CAAC,kBAAkB,EAAE,cAAc,CAAC,CAAC,CA4CrD"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Stable, backend-independent error codes for filesystem operations. These are
3
+ * returned (never thrown) inside a `Result` by the {@link FileSystem} layer.
4
+ */
5
+ export type FileErrorCode = "aborted" | "not_found" | "permission_denied" | "not_directory" | "is_directory" | "invalid" | "not_supported" | "unknown";
6
+ /** Stable error codes for shell command execution. */
7
+ export type ExecutionErrorCode = "aborted" | "timeout" | "blocked" | "shell_unavailable" | "spawn_error" | "callback_error" | "unknown";
8
+ /** Codes that classify a session-storage or session-tree failure. */
9
+ export type SessionErrorCode = "invalid_session" | "invalid_entry" | "not_found" | "io" | "unknown";
10
+ /** Codes for context-compaction failures. */
11
+ export type CompactionErrorCode = "compaction" | "invalid_session" | "aborted" | "summarization_failed" | "auth" | "unknown";
12
+ /** Codes for stateful-agent / harness lifecycle failures. */
13
+ export type AgentHarnessErrorCode = "busy" | "invalid_state" | "invalid_argument" | "auth" | "aborted" | "unknown";
14
+ /** Base class for every AP3X agent-core error. Carries a stable `code`. */
15
+ export declare abstract class Ap3xError<TCode extends string> extends Error {
16
+ readonly code: TCode;
17
+ readonly cause?: unknown;
18
+ constructor(code: TCode, message: string, cause?: unknown);
19
+ }
20
+ /** A filesystem operation failed. */
21
+ export declare class FileError extends Ap3xError<FileErrorCode> {
22
+ readonly path?: string;
23
+ constructor(code: FileErrorCode, message: string, path?: string, cause?: unknown);
24
+ }
25
+ /** A shell command failed, timed out, was aborted, or was blocked. */
26
+ export declare class ExecutionError extends Ap3xError<ExecutionErrorCode> {
27
+ }
28
+ /** A session tree / storage invariant was violated. */
29
+ export declare class SessionError extends Ap3xError<SessionErrorCode> {
30
+ }
31
+ /** Context compaction failed. */
32
+ export declare class CompactionError extends Ap3xError<CompactionErrorCode> {
33
+ }
34
+ /** A stateful `Agent` / harness rejected an operation (e.g. it was busy). */
35
+ export declare class AgentHarnessError extends Ap3xError<AgentHarnessErrorCode> {
36
+ }
37
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,aAAa,GACrB,SAAS,GACT,WAAW,GACX,mBAAmB,GACnB,eAAe,GACf,cAAc,GACd,SAAS,GACT,eAAe,GACf,SAAS,CAAC;AAEd,sDAAsD;AACtD,MAAM,MAAM,kBAAkB,GAC1B,SAAS,GACT,SAAS,GACT,SAAS,GACT,mBAAmB,GACnB,aAAa,GACb,gBAAgB,GAChB,SAAS,CAAC;AAEd,qEAAqE;AACrE,MAAM,MAAM,gBAAgB,GAAG,iBAAiB,GAAG,eAAe,GAAG,WAAW,GAAG,IAAI,GAAG,SAAS,CAAC;AAEpG,6CAA6C;AAC7C,MAAM,MAAM,mBAAmB,GAC3B,YAAY,GACZ,iBAAiB,GACjB,SAAS,GACT,sBAAsB,GACtB,MAAM,GACN,SAAS,CAAC;AAEd,6DAA6D;AAC7D,MAAM,MAAM,qBAAqB,GAC7B,MAAM,GACN,eAAe,GACf,kBAAkB,GAClB,MAAM,GACN,SAAS,GACT,SAAS,CAAC;AAEd,2EAA2E;AAC3E,8BAAsB,SAAS,CAAC,KAAK,SAAS,MAAM,CAAE,SAAQ,KAAK;IACjE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IACrB,SAAkB,KAAK,CAAC,EAAE,OAAO,CAAC;gBAEtB,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAM1D;AAED,qCAAqC;AACrC,qBAAa,SAAU,SAAQ,SAAS,CAAC,aAAa,CAAC;IACrD,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;gBACX,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAIjF;AAED,sEAAsE;AACtE,qBAAa,cAAe,SAAQ,SAAS,CAAC,kBAAkB,CAAC;CAAG;AAEpE,uDAAuD;AACvD,qBAAa,YAAa,SAAQ,SAAS,CAAC,gBAAgB,CAAC;CAAG;AAEhE,iCAAiC;AACjC,qBAAa,eAAgB,SAAQ,SAAS,CAAC,mBAAmB,CAAC;CAAG;AAEtE,6EAA6E;AAC7E,qBAAa,iBAAkB,SAAQ,SAAS,CAAC,qBAAqB,CAAC;CAAG"}
@@ -0,0 +1,110 @@
1
+ import type { AssistantMessage } from "@ap3x/ai";
2
+ import { type AgentOptions } from "./agent";
3
+ import { type CompactionResult, compact } from "./compaction";
4
+ import { type Session } from "./session";
5
+ import type { AgentEvent, AgentMessage } from "./types";
6
+ /**
7
+ * Construction options for the {@link AgentHarness}.
8
+ */
9
+ export interface AgentHarnessOptions extends AgentOptions {
10
+ session: Session;
11
+ }
12
+ /** A harness event subscriber. Mirrors the untyped {@link AgentEvent} stream. */
13
+ type HarnessListener = (event: AgentEvent) => void | Promise<void>;
14
+ /** Narrow an {@link AgentEvent} to a single `type` for the typed {@link AgentHarness.on}. */
15
+ type AgentEventOf<T extends AgentEvent["type"]> = Extract<AgentEvent, {
16
+ type: T;
17
+ }>;
18
+ /**
19
+ * A session-backed host harness over an {@link Agent}. Every prompt and its
20
+ * resulting messages are appended to the session tree, so the conversation can
21
+ * be reconstructed, branched, or compacted later.
22
+ *
23
+ * The harness — not the (rebuildable) inner agent — is the stable event source:
24
+ * subscribers register with the harness and survive an agent rebuild (compaction
25
+ * reseed, branch navigation). Live-run steering (`steer`/`followUp`) delegates to
26
+ * the agent's shared queue; `nextTurn` carries to the *next* prompt instead.
27
+ */
28
+ export declare class AgentHarness {
29
+ readonly session: Session;
30
+ private agent;
31
+ private readonly agentOptions;
32
+ /** Harness-owned subscribers; a single forwarder relays each agent's events. */
33
+ private readonly listeners;
34
+ /** Unsubscribes the forwarder from the current agent (re-wired on rebuild). */
35
+ private agentUnsub?;
36
+ /** Messages queued by {@link nextTurn}, prepended to (and cleared by) the next prompt. */
37
+ private pendingNextTurn;
38
+ /**
39
+ * Summary of an in-memory (unpersistable) compaction — set when {@link compact}
40
+ * finds no session entry to anchor a durable CompactionEntry on (the agent runs
41
+ * on seeded `messages` the session never held). Threads into the NEXT compaction
42
+ * as `previousSummary` so it merges instead of being re-read as conversation
43
+ * text; cleared whenever the agent is reseeded from the session, which replaces
44
+ * the in-memory context this summary describes.
45
+ */
46
+ private unpersistedSummary?;
47
+ private busy;
48
+ constructor(options: AgentHarnessOptions);
49
+ /**
50
+ * Run a single turn and persist all new messages to the session. Only
51
+ * turn-produced messages are appended — seeded {@link AgentOptions.messages}
52
+ * stay context-only and are never persisted (see that option's doc; B21).
53
+ */
54
+ prompt(text: string): Promise<AssistantMessage>;
55
+ /**
56
+ * Inject a steering message into the live run at the next turn boundary (or,
57
+ * while idle, into the next run's first turn). Delegates to the agent's queue.
58
+ */
59
+ steer(message: string | AgentMessage): void;
60
+ /** Queue a follow-up that extends the current run once it would otherwise stop. */
61
+ followUp(message: string | AgentMessage): void;
62
+ /**
63
+ * Carry a message to the NEXT {@link prompt}: it is prepended to that prompt
64
+ * and the queue is cleared. Unlike {@link followUp}, this never extends the
65
+ * currently-running turn — the message is held at the harness (session) layer
66
+ * until the next prompt begins.
67
+ */
68
+ nextTurn(message: string | AgentMessage): void;
69
+ /**
70
+ * Compact the agent's current context: summarize older history, persist a
71
+ * compaction boundary to the session, and reseed the agent from the compacted
72
+ * context so subsequent prompts run against the shortened transcript. Options
73
+ * are forwarded to the P13 {@link compact}. Throws the underlying
74
+ * {@link CompactionError} if summarization fails.
75
+ *
76
+ * When the agent runs on seeded `messages` the session never held (no entry
77
+ * can anchor a durable CompactionEntry), the compaction is applied to the
78
+ * live agent in-memory instead: the returned summary is real and the next
79
+ * provider call sees the compacted context, but no compaction boundary is
80
+ * persisted to the session for that run.
81
+ */
82
+ compact(options?: Parameters<typeof compact>[2]): Promise<CompactionResult>;
83
+ /**
84
+ * Move the session's active branch to `entryId` and reseed the agent from that
85
+ * branch's reconstructed context, so subsequent prompts continue from the
86
+ * navigated-to point (rewind / branch-switch).
87
+ */
88
+ navigateTree(entryId: string): void;
89
+ /** Subscribe to the underlying agent's lifecycle events. */
90
+ subscribe(listener: HarnessListener): () => void;
91
+ /**
92
+ * Typed event subscription: `handler` receives only events of `type`, narrowed
93
+ * to that variant. Returns an unsubscribe function.
94
+ */
95
+ on<T extends AgentEvent["type"]>(type: T, handler: (event: AgentEventOf<T>) => void | Promise<void>): () => void;
96
+ /** Abort the active run. */
97
+ abort(): void;
98
+ /**
99
+ * Rebuild the inner agent over `messages`, re-wiring the event forwarder.
100
+ * When `previous` is given (a rebuild that CONTINUES the same conversation),
101
+ * its pending steer/followUp/nextTurn queue is carried into the new agent.
102
+ */
103
+ private buildAgent;
104
+ /** Reseed the agent from the session's current branch context. */
105
+ private reseedFromSession;
106
+ /** Normalize a string prompt into a user {@link AgentMessage}. */
107
+ private toMessage;
108
+ }
109
+ export {};
110
+ //# sourceMappingURL=harness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"harness.d.ts","sourceRoot":"","sources":["../src/harness.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAS,KAAK,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EACL,KAAK,gBAAgB,EAErB,OAAO,EAER,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,KAAK,OAAO,EAA0B,MAAM,WAAW,CAAC;AACjE,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAExD;;GAEG;AACH,MAAM,WAAW,mBAAoB,SAAQ,YAAY;IACvD,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,iFAAiF;AACjF,KAAK,eAAe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,eAAe,GAAG,MAAM,IAAI;IAOhD;;;OAGG;IACH,EAAE,CAAC,CAAC,SAAS,UAAU,CAAC,MAAM,CAAC,EAC7B,IAAI,EAAE,CAAC,EACP,OAAO,EAAE,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACxD,MAAM,IAAI;IAMb,4BAA4B;IAC5B,KAAK,IAAI,IAAI;IAIb;;;;OAIG;IACH,OAAO,CAAC,UAAU;IASlB,kEAAkE;IAClE,OAAO,CAAC,iBAAiB;IAMzB,kEAAkE;IAClE,OAAO,CAAC,SAAS;CAKlB"}
@@ -0,0 +1,28 @@
1
+ export declare const PACKAGE = "@ap3x/agent-core";
2
+ export declare const VERSION = "0.1.0";
3
+ export { type Result, ok, err, getOrThrow, getOrUndefined, toError } from "./result";
4
+ export { Ap3xError, FileError, ExecutionError, SessionError, CompactionError, AgentHarnessError, type FileErrorCode, type ExecutionErrorCode, type SessionErrorCode, type CompactionErrorCode, type AgentHarnessErrorCode, } from "./errors";
5
+ export { uuidv7, shortId } from "./uuid";
6
+ export { createLimiter, mapLimit, availableParallelism } from "./concurrency";
7
+ export type { AgentMessage, CustomAgentMessages, AgentContext, AgentTool, AnyAgentTool, AgentToolResult, AgentToolUpdate, AgentEvent, AgentEventSink, AgentHooks, AgentLoopConfig, QueueMode, BeforeToolCallContext, AfterToolCallContext, ToolCallGate, ThinkingLevel, StreamFn, } from "./types";
8
+ export { defineTool, executeToolCalls, type ToolBatchResult, type ExecuteToolCallsOptions, type ToolExecutionEvent, } from "./tools";
9
+ export { runAgentLoop, runAgentLoopContinue, agentLoop, agentLoopContinue, DEFAULT_MAX_LOOPS, type AgentEventStream, } from "./agent-loop";
10
+ export { Agent, type AgentOptions, type AgentState, type AgentListener, finalTextOf, lastAssistant, } from "./agent";
11
+ export { type AgentBackend, type AgentRunResult, type AgentRunOptions, type BackendCapability, Ap3xRuntimeBackend, createRuntimeBackend, } from "./backend";
12
+ export { AgentHarness, type AgentHarnessOptions } from "./harness";
13
+ export { assembleSystemPrompt, SystemPromptBuilder, environmentSection, SYSTEM_PROMPT_SECTIONS, type SystemPromptSection, type SystemPromptSectionName, type AssembleSystemPromptOptions, type EnvironmentSectionInput, } from "./system-prompt";
14
+ export { loadPromptTemplate, parseCommandArgs, parsePromptTemplate, renderPromptTemplate, substituteArgs, type PromptTemplate, } from "./prompt-templates";
15
+ export { parseSkill, loadSkill, loadSkills, discoverSkillFiles, discoverSkills, SkillRegistry, formatSkillsForSystemPrompt, type Skill, } from "./skills";
16
+ export { Session, buildSessionContext, producesContextMessage, createSessionId, InMemorySessionStorage, JsonlSessionStorage, StringJsonlFile, type SessionStorage, type SessionEntry, type SessionEntryType, type MessageEntry, type CompactionEntry, type ModelChangeEntry, type LabelEntry, type LeafEntry, type ThinkingLevelChangeEntry, type ActiveToolsChangeEntry, type BranchSummaryEntry, type SessionInfoEntry, type CustomEntry, type CustomMessageEntry, type SessionContext, type SessionMetadata, type JsonlFile, } from "./session";
17
+ export { FileJsonlFile, JsonlSessionRepo, type SessionRepo, type SessionCreateOptions, type SessionForkOptions, type SessionListEntry, } from "./session-repo";
18
+ export { compact, prepareCompaction, shouldCompact, compactionTier, resolveCompactionSettings, resolveAutoCompact, findCutPoint, estimateMessageTokens, estimateContextTokens, DEFAULT_COMPACTION_SETTINGS, SUMMARIZATION_SYSTEM_PROMPT, type CompactionSettings, type CompactionTier, type CompactionResult, type CompactionPreparation, type CutPointResult, } from "./compaction";
19
+ export { NodeExecutionEnv, detectShell, executeShellWithCapture, type ExecutionEnv, type FileSystem, type Shell, type ExecOptions, type ShellResult, type ShellCaptureResult, } from "./env";
20
+ export { matchBlocklist, isBlockedCommand, type BlocklistMatch } from "./shell-blocklist";
21
+ export { logger, setLogLevel, getLogLevel, type LogLevel } from "./logger";
22
+ export { Conversation, generateConversationId, getConversationDir, type ConversationMessage, type ConversationOptions, type RoleContentMessage, } from "./conversation";
23
+ export { historyOutputFormatter, type HistoryOutputType, type OutputType, } from "./output-formatter";
24
+ export { estimateTokens, type TokenCounter } from "./conversation";
25
+ export { AgentLoader, AgentRegistry, AgentConfigSchema, AgentRegistrySchema, AgentSpecSchema, parseYamlFrontmatter, type AgentConfig, type AgentRegistrySnapshot, type AgentSpec, type RegistrableAgent, } from "./loader";
26
+ export { SafeStateManager, SerializableMixin, createStateDict, isClassInstance, isSafeType, preserveInstances, serializeAttr, serializeState, type CallableDescriptor, type HasToDict, } from "./serialization";
27
+ export { AgentError, AgentInitializationError, AgentRunError, AgentLLMError, AgentToolError, AgentMemoryError, AgentMCPConnectionError, AgentMCPToolError, type AgentErrorCode, } from "./agent-errors";
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,OAAO,qBAAqB,CAAC;AAC1C,eAAO,MAAM,OAAO,UAAU,CAAC;AAG/B,OAAO,EAAE,KAAK,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACrF,OAAO,EACL,SAAS,EACT,SAAS,EACT,cAAc,EACd,YAAY,EACZ,eAAe,EACf,iBAAiB,EACjB,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,GAC3B,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAGzC,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAG9E,YAAY,EACV,YAAY,EACZ,mBAAmB,EACnB,YAAY,EACZ,SAAS,EACT,YAAY,EACZ,eAAe,EACf,eAAe,EACf,UAAU,EACV,cAAc,EACd,UAAU,EACV,eAAe,EACf,SAAS,EACT,qBAAq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