actoviq-agent-sdk 0.2.0 → 0.3.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 (168) hide show
  1. package/README-zh.md +19 -3
  2. package/README.md +19 -3
  3. package/bin/actoviq-interactive-agent.js +5 -0
  4. package/bin/actoviq-link-runtime.js +74 -0
  5. package/bin/actoviq-react.js +5 -0
  6. package/dist/src/cli/actoviq-react.d.ts +3 -0
  7. package/dist/src/cli/actoviq-react.d.ts.map +1 -0
  8. package/dist/src/cli/actoviq-react.js +277 -0
  9. package/dist/src/cli/actoviq-react.js.map +1 -0
  10. package/dist/src/cli/bridge-interactive-agent.d.ts +2 -0
  11. package/dist/src/cli/bridge-interactive-agent.d.ts.map +1 -0
  12. package/dist/src/cli/bridge-interactive-agent.js +147 -0
  13. package/dist/src/cli/bridge-interactive-agent.js.map +1 -0
  14. package/dist/src/config/resolveRuntimeConfig.d.ts.map +1 -1
  15. package/dist/src/config/resolveRuntimeConfig.js +13 -16
  16. package/dist/src/config/resolveRuntimeConfig.js.map +1 -1
  17. package/dist/src/errors.d.ts +9 -0
  18. package/dist/src/errors.d.ts.map +1 -1
  19. package/dist/src/errors.js +9 -0
  20. package/dist/src/errors.js.map +1 -1
  21. package/dist/src/index.d.ts +20 -1
  22. package/dist/src/index.d.ts.map +1 -1
  23. package/dist/src/index.js +18 -1
  24. package/dist/src/index.js.map +1 -1
  25. package/dist/src/parity/actoviqBridgeEvents.d.ts +7 -0
  26. package/dist/src/parity/actoviqBridgeEvents.d.ts.map +1 -0
  27. package/dist/src/parity/actoviqBridgeEvents.js +133 -0
  28. package/dist/src/parity/actoviqBridgeEvents.js.map +1 -0
  29. package/dist/src/parity/actoviqBridgeSdk.d.ts +179 -0
  30. package/dist/src/parity/actoviqBridgeSdk.d.ts.map +1 -0
  31. package/dist/src/parity/actoviqBridgeSdk.js +1267 -0
  32. package/dist/src/parity/actoviqBridgeSdk.js.map +1 -0
  33. package/dist/src/parity/actoviqTranscripts.d.ts +44 -0
  34. package/dist/src/parity/actoviqTranscripts.d.ts.map +1 -0
  35. package/dist/src/parity/actoviqTranscripts.js +282 -0
  36. package/dist/src/parity/actoviqTranscripts.js.map +1 -0
  37. package/dist/src/parity/portableSessions.d.ts +35 -0
  38. package/dist/src/parity/portableSessions.d.ts.map +1 -0
  39. package/dist/src/parity/portableSessions.js +233 -0
  40. package/dist/src/parity/portableSessions.js.map +1 -0
  41. package/dist/src/prompts/systemPrompt.d.ts +15 -0
  42. package/dist/src/prompts/systemPrompt.d.ts.map +1 -0
  43. package/dist/src/prompts/systemPrompt.js +73 -0
  44. package/dist/src/prompts/systemPrompt.js.map +1 -0
  45. package/dist/src/provider/client.d.ts +1 -0
  46. package/dist/src/provider/client.d.ts.map +1 -1
  47. package/dist/src/provider/client.js +6 -5
  48. package/dist/src/provider/client.js.map +1 -1
  49. package/dist/src/provider/json-parse.d.ts +7 -0
  50. package/dist/src/provider/json-parse.d.ts.map +1 -0
  51. package/dist/src/provider/json-parse.js +69 -0
  52. package/dist/src/provider/json-parse.js.map +1 -0
  53. package/dist/src/provider/openai-client.d.ts.map +1 -1
  54. package/dist/src/provider/openai-client.js +2 -1
  55. package/dist/src/provider/openai-client.js.map +1 -1
  56. package/dist/src/provider/openai-model-api.d.ts.map +1 -1
  57. package/dist/src/provider/openai-model-api.js +2 -7
  58. package/dist/src/provider/openai-model-api.js.map +1 -1
  59. package/dist/src/runtime/actoviqApiMicrocompact.d.ts.map +1 -1
  60. package/dist/src/runtime/actoviqApiMicrocompact.js +10 -17
  61. package/dist/src/runtime/actoviqApiMicrocompact.js.map +1 -1
  62. package/dist/src/runtime/actoviqCompact.d.ts.map +1 -1
  63. package/dist/src/runtime/actoviqCompact.js +53 -1
  64. package/dist/src/runtime/actoviqCompact.js.map +1 -1
  65. package/dist/src/runtime/actoviqPermissions.d.ts.map +1 -1
  66. package/dist/src/runtime/actoviqPermissions.js +120 -54
  67. package/dist/src/runtime/actoviqPermissions.js.map +1 -1
  68. package/dist/src/runtime/agentClient.d.ts.map +1 -1
  69. package/dist/src/runtime/agentClient.js +30 -2
  70. package/dist/src/runtime/agentClient.js.map +1 -1
  71. package/dist/src/runtime/conversationEngine.d.ts.map +1 -1
  72. package/dist/src/runtime/conversationEngine.js +95 -3
  73. package/dist/src/runtime/conversationEngine.js.map +1 -1
  74. package/dist/src/runtime/denialTracking.d.ts +10 -0
  75. package/dist/src/runtime/denialTracking.d.ts.map +1 -0
  76. package/dist/src/runtime/denialTracking.js +27 -0
  77. package/dist/src/runtime/denialTracking.js.map +1 -0
  78. package/dist/src/runtime/safetyChecks.d.ts +12 -0
  79. package/dist/src/runtime/safetyChecks.d.ts.map +1 -0
  80. package/dist/src/runtime/safetyChecks.js +62 -0
  81. package/dist/src/runtime/safetyChecks.js.map +1 -0
  82. package/dist/src/runtime/tools.d.ts.map +1 -1
  83. package/dist/src/runtime/tools.js +61 -3
  84. package/dist/src/runtime/tools.js.map +1 -1
  85. package/dist/src/scheduling/cron.d.ts +14 -0
  86. package/dist/src/scheduling/cron.d.ts.map +1 -0
  87. package/dist/src/scheduling/cron.js +157 -0
  88. package/dist/src/scheduling/cron.js.map +1 -0
  89. package/dist/src/scheduling/index.d.ts +3 -0
  90. package/dist/src/scheduling/index.d.ts.map +1 -0
  91. package/dist/src/scheduling/index.js +3 -0
  92. package/dist/src/scheduling/index.js.map +1 -0
  93. package/dist/src/scheduling/scheduler.d.ts +32 -0
  94. package/dist/src/scheduling/scheduler.d.ts.map +1 -0
  95. package/dist/src/scheduling/scheduler.js +196 -0
  96. package/dist/src/scheduling/scheduler.js.map +1 -0
  97. package/dist/src/tools/actoviqCoreTools.d.ts +23 -0
  98. package/dist/src/tools/actoviqCoreTools.d.ts.map +1 -0
  99. package/dist/src/tools/actoviqCoreTools.js +32 -0
  100. package/dist/src/tools/actoviqCoreTools.js.map +1 -0
  101. package/dist/src/tools/actoviqFileTools.d.ts.map +1 -1
  102. package/dist/src/tools/actoviqFileTools.js +338 -373
  103. package/dist/src/tools/actoviqFileTools.js.map +1 -1
  104. package/dist/src/tools/actoviqMiscTools.d.ts +11 -0
  105. package/dist/src/tools/actoviqMiscTools.d.ts.map +1 -0
  106. package/dist/src/tools/actoviqMiscTools.js +89 -0
  107. package/dist/src/tools/actoviqMiscTools.js.map +1 -0
  108. package/dist/src/tools/actoviqNotebookEdit.d.ts +4 -0
  109. package/dist/src/tools/actoviqNotebookEdit.d.ts.map +1 -0
  110. package/dist/src/tools/actoviqNotebookEdit.js +23 -0
  111. package/dist/src/tools/actoviqNotebookEdit.js.map +1 -0
  112. package/dist/src/tools/actoviqShellTools.d.ts +5 -0
  113. package/dist/src/tools/actoviqShellTools.d.ts.map +1 -0
  114. package/dist/src/tools/actoviqShellTools.js +35 -0
  115. package/dist/src/tools/actoviqShellTools.js.map +1 -0
  116. package/dist/src/tools/actoviqTaskTools.d.ts +12 -0
  117. package/dist/src/tools/actoviqTaskTools.d.ts.map +1 -0
  118. package/dist/src/tools/actoviqTaskTools.js +108 -0
  119. package/dist/src/tools/actoviqTaskTools.js.map +1 -0
  120. package/dist/src/tools/actoviqWebTools.d.ts +15 -0
  121. package/dist/src/tools/actoviqWebTools.d.ts.map +1 -0
  122. package/dist/src/tools/actoviqWebTools.js +395 -0
  123. package/dist/src/tools/actoviqWebTools.js.map +1 -0
  124. package/dist/src/tools/askUserQuestion/AskUserQuestionTool.d.ts +6 -0
  125. package/dist/src/tools/askUserQuestion/AskUserQuestionTool.d.ts.map +1 -0
  126. package/dist/src/tools/askUserQuestion/AskUserQuestionTool.js +43 -0
  127. package/dist/src/tools/askUserQuestion/AskUserQuestionTool.js.map +1 -0
  128. package/dist/src/tools/bash/BashTool.d.ts +14 -0
  129. package/dist/src/tools/bash/BashTool.d.ts.map +1 -0
  130. package/dist/src/tools/bash/BashTool.js +60 -0
  131. package/dist/src/tools/bash/BashTool.js.map +1 -0
  132. package/dist/src/tools/bash/prompt.d.ts +3 -0
  133. package/dist/src/tools/bash/prompt.d.ts.map +1 -0
  134. package/dist/src/tools/bash/prompt.js +63 -0
  135. package/dist/src/tools/bash/prompt.js.map +1 -0
  136. package/dist/src/tools/prompts/fileEditPrompt.d.ts +3 -0
  137. package/dist/src/tools/prompts/fileEditPrompt.d.ts.map +1 -0
  138. package/dist/src/tools/prompts/fileEditPrompt.js +14 -0
  139. package/dist/src/tools/prompts/fileEditPrompt.js.map +1 -0
  140. package/dist/src/tools/prompts/fileReadPrompt.d.ts +3 -0
  141. package/dist/src/tools/prompts/fileReadPrompt.d.ts.map +1 -0
  142. package/dist/src/tools/prompts/fileReadPrompt.js +18 -0
  143. package/dist/src/tools/prompts/fileReadPrompt.js.map +1 -0
  144. package/dist/src/tools/prompts/fileSearchPrompt.d.ts +2 -0
  145. package/dist/src/tools/prompts/fileSearchPrompt.d.ts.map +1 -0
  146. package/dist/src/tools/prompts/fileSearchPrompt.js +21 -0
  147. package/dist/src/tools/prompts/fileSearchPrompt.js.map +1 -0
  148. package/dist/src/tools/prompts/fileWritePrompt.d.ts +3 -0
  149. package/dist/src/tools/prompts/fileWritePrompt.d.ts.map +1 -0
  150. package/dist/src/tools/prompts/fileWritePrompt.js +13 -0
  151. package/dist/src/tools/prompts/fileWritePrompt.js.map +1 -0
  152. package/dist/src/tools/prompts/webFetchPrompt.d.ts +3 -0
  153. package/dist/src/tools/prompts/webFetchPrompt.d.ts.map +1 -0
  154. package/dist/src/tools/prompts/webFetchPrompt.js +13 -0
  155. package/dist/src/tools/prompts/webFetchPrompt.js.map +1 -0
  156. package/dist/src/tools/prompts/webSearchPrompt.d.ts +3 -0
  157. package/dist/src/tools/prompts/webSearchPrompt.d.ts.map +1 -0
  158. package/dist/src/tools/prompts/webSearchPrompt.js +17 -0
  159. package/dist/src/tools/prompts/webSearchPrompt.js.map +1 -0
  160. package/dist/src/tools/todo/TodoWriteTool.d.ts +6 -0
  161. package/dist/src/tools/todo/TodoWriteTool.d.ts.map +1 -0
  162. package/dist/src/tools/todo/TodoWriteTool.js +62 -0
  163. package/dist/src/tools/todo/TodoWriteTool.js.map +1 -0
  164. package/dist/src/types.d.ts +309 -2
  165. package/dist/src/types.d.ts.map +1 -1
  166. package/dist/src/types.js.map +1 -1
  167. package/package.json +35 -11
  168. package/vendor/actoviq-runtime/cli.js +54 -0
@@ -0,0 +1,1267 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { constants as fsConstants } from 'node:fs';
4
+ import { access } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import readline from 'node:readline';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { createActoviqBuddyApi } from '../buddy/actoviqBuddy.js';
9
+ import { getLoadedJsonConfig } from '../config/loadJsonConfigFile.js';
10
+ import { ActoviqBridgeProcessError, RunAbortedError } from '../errors.js';
11
+ import { createActoviqMemoryApi } from '../memory/actoviqMemory.js';
12
+ import { AsyncQueue } from '../runtime/asyncQueue.js';
13
+ import { asError, isRecord } from '../runtime/helpers.js';
14
+ import { getActoviqBridgeCompactBoundaries, getActoviqBridgeLatestCompactBoundary, getActoviqBridgeSessionInfo, getActoviqBridgeSessionMessages, listActoviqBridgeSessions, } from './actoviqTranscripts.js';
15
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
16
+ const IS_WINDOWS = process.platform === 'win32';
17
+ function isAbortErrorLike(error) {
18
+ return error instanceof RunAbortedError || (error instanceof Error && error.name === 'AbortError');
19
+ }
20
+ async function pathExists(filePath) {
21
+ try {
22
+ await access(filePath, fsConstants.F_OK);
23
+ return true;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ async function isExecutable(filePath) {
30
+ try {
31
+ await access(filePath, IS_WINDOWS ? fsConstants.F_OK : fsConstants.X_OK);
32
+ return true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ function splitPathEnv(pathValue) {
39
+ if (!pathValue) {
40
+ return [];
41
+ }
42
+ return pathValue.split(path.delimiter).filter(Boolean);
43
+ }
44
+ async function findExecutableOnPath(name) {
45
+ const pathDirectories = splitPathEnv(process.env.PATH);
46
+ const extensions = IS_WINDOWS
47
+ ? (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
48
+ .split(';')
49
+ .filter(Boolean)
50
+ : [''];
51
+ for (const directory of pathDirectories) {
52
+ const directCandidate = path.join(directory, name);
53
+ if (!IS_WINDOWS && (await isExecutable(directCandidate))) {
54
+ return directCandidate;
55
+ }
56
+ for (const extension of extensions) {
57
+ const candidate = directCandidate.endsWith(extension.toLowerCase())
58
+ ? directCandidate
59
+ : `${directCandidate}${extension.toLowerCase()}`;
60
+ if (await isExecutable(candidate)) {
61
+ return candidate;
62
+ }
63
+ }
64
+ }
65
+ return undefined;
66
+ }
67
+ async function findFirstExistingPath(candidates) {
68
+ for (const candidate of candidates) {
69
+ if (!candidate) {
70
+ continue;
71
+ }
72
+ if (await pathExists(candidate)) {
73
+ return candidate;
74
+ }
75
+ }
76
+ return undefined;
77
+ }
78
+ async function resolveBunExecutable(explicitPath) {
79
+ if (explicitPath) {
80
+ if (!(await isExecutable(explicitPath))) {
81
+ throw new ActoviqBridgeProcessError(`The configured executable was not found or is not executable: ${explicitPath}`);
82
+ }
83
+ return explicitPath;
84
+ }
85
+ const localCandidate = await findFirstExistingPath([
86
+ ...(IS_WINDOWS
87
+ ? [
88
+ path.resolve(MODULE_DIR, '..', '..', 'node_modules', 'bun', 'bin', 'bun.exe'),
89
+ path.resolve(MODULE_DIR, '..', '..', '..', 'node_modules', 'bun', 'bin', 'bun.exe'),
90
+ path.resolve(process.cwd(), 'node_modules', 'bun', 'bin', 'bun.exe'),
91
+ ]
92
+ : []),
93
+ path.resolve(MODULE_DIR, '..', '..', 'node_modules', '.bin', `bun${IS_WINDOWS ? '.cmd' : ''}`),
94
+ path.resolve(MODULE_DIR, '..', '..', '..', 'node_modules', '.bin', `bun${IS_WINDOWS ? '.cmd' : ''}`),
95
+ path.resolve(process.cwd(), 'node_modules', '.bin', `bun${IS_WINDOWS ? '.cmd' : ''}`),
96
+ ]);
97
+ if (localCandidate) {
98
+ return localCandidate;
99
+ }
100
+ const pathCandidate = await findExecutableOnPath('bun');
101
+ if (pathCandidate) {
102
+ return pathCandidate;
103
+ }
104
+ throw new ActoviqBridgeProcessError('Bun is required for the Actoviq Runtime bridge, but no bun executable was found. Install Bun or pass { executable }.');
105
+ }
106
+ async function resolveActoviqRuntimeCliPath(explicitPath) {
107
+ if (explicitPath) {
108
+ if (!(await pathExists(explicitPath))) {
109
+ throw new ActoviqBridgeProcessError(`Actoviq Runtime CLI entry was not found: ${explicitPath}`);
110
+ }
111
+ return explicitPath;
112
+ }
113
+ const resolved = await findFirstExistingPath([
114
+ path.resolve(MODULE_DIR, '..', '..', 'vendor', 'actoviq-runtime', 'cli.js'),
115
+ path.resolve(MODULE_DIR, '..', '..', '..', 'vendor', 'actoviq-runtime', 'cli.js'),
116
+ path.resolve(process.cwd(), 'vendor', 'actoviq-runtime', 'cli.js'),
117
+ ]);
118
+ if (!resolved) {
119
+ throw new ActoviqBridgeProcessError('Actoviq Runtime CLI entry was not found. Run npm run sync:actoviq-runtime or pass { cliPath } explicitly.');
120
+ }
121
+ return resolved;
122
+ }
123
+ function stringifyCliValue(value) {
124
+ return typeof value === 'string' ? value : JSON.stringify(value);
125
+ }
126
+ function normalizeToolsArgument(tools) {
127
+ if (tools == null) {
128
+ return undefined;
129
+ }
130
+ if (tools === 'default') {
131
+ return 'default';
132
+ }
133
+ if (tools === 'none') {
134
+ return '';
135
+ }
136
+ return tools.join(',');
137
+ }
138
+ function appendRepeatableArgs(args, flag, values) {
139
+ if (!values?.length) {
140
+ return;
141
+ }
142
+ args.push(flag, ...values);
143
+ }
144
+ function appendOptionalArg(args, flag, value) {
145
+ if (value == null || value === '') {
146
+ return;
147
+ }
148
+ args.push(flag, String(value));
149
+ }
150
+ function getStringValue(event, key) {
151
+ const value = event?.[key];
152
+ return typeof value === 'string' ? value : undefined;
153
+ }
154
+ function getNumberValue(event, key) {
155
+ const value = event?.[key];
156
+ return typeof value === 'number' ? value : undefined;
157
+ }
158
+ function getBooleanValue(event, key) {
159
+ const value = event?.[key];
160
+ return typeof value === 'boolean' ? value : undefined;
161
+ }
162
+ function extractAssistantText(event) {
163
+ const message = event.message;
164
+ if (!isRecord(message)) {
165
+ return '';
166
+ }
167
+ const content = message.content;
168
+ if (!Array.isArray(content)) {
169
+ return '';
170
+ }
171
+ return content
172
+ .map(block => {
173
+ if (!isRecord(block)) {
174
+ return '';
175
+ }
176
+ return block.type === 'text' && typeof block.text === 'string' ? block.text : '';
177
+ })
178
+ .join('');
179
+ }
180
+ function deriveResultText(resultEvent, assistantMessages) {
181
+ const rawResult = resultEvent?.result;
182
+ if (typeof rawResult === 'string') {
183
+ return rawResult;
184
+ }
185
+ for (let index = assistantMessages.length - 1; index >= 0; index -= 1) {
186
+ const text = extractAssistantText(assistantMessages[index]);
187
+ if (text) {
188
+ return text;
189
+ }
190
+ }
191
+ return '';
192
+ }
193
+ function getStringArray(value) {
194
+ if (!Array.isArray(value)) {
195
+ return [];
196
+ }
197
+ return value.filter((entry) => typeof entry === 'string');
198
+ }
199
+ function getObjectArray(value) {
200
+ if (!Array.isArray(value)) {
201
+ return [];
202
+ }
203
+ return value.filter((entry) => isRecord(entry));
204
+ }
205
+ function parseMarkdownTable(markdown, heading) {
206
+ const headingIndex = markdown.indexOf(`### ${heading}`);
207
+ if (headingIndex === -1) {
208
+ return [];
209
+ }
210
+ const afterHeading = markdown.slice(headingIndex).split(/\r?\n/).slice(1);
211
+ const tableLines = [];
212
+ for (const line of afterHeading) {
213
+ if (line.startsWith('### ')) {
214
+ break;
215
+ }
216
+ if (line.trim().startsWith('|')) {
217
+ tableLines.push(line.trim());
218
+ continue;
219
+ }
220
+ if (tableLines.length > 0 && !line.trim()) {
221
+ break;
222
+ }
223
+ }
224
+ if (tableLines.length < 3) {
225
+ return [];
226
+ }
227
+ const headers = tableLines[0]
228
+ .split('|')
229
+ .map(cell => cell.trim())
230
+ .filter(Boolean);
231
+ const rows = tableLines.slice(2);
232
+ return rows.map(row => {
233
+ const cells = row
234
+ .split('|')
235
+ .map(cell => cell.trim())
236
+ .filter(Boolean);
237
+ return Object.fromEntries(headers.map((header, index) => [header, cells[index] ?? '']));
238
+ });
239
+ }
240
+ function parseActoviqContextUsageResult(result) {
241
+ const markdown = result.text;
242
+ const modelMatch = markdown.match(/\*\*Model:\*\*\s+([^\r\n]+)/u);
243
+ const tokensMatch = markdown.match(/\*\*Tokens:\*\*\s+(.+?)\s+\/\s+(.+?)\s+\(([\d.]+)%\)/u);
244
+ return {
245
+ markdown,
246
+ model: modelMatch?.[1]?.trim(),
247
+ tokensUsed: tokensMatch?.[1]?.trim(),
248
+ tokenLimit: tokensMatch?.[2]?.trim(),
249
+ percentage: tokensMatch?.[3] ? Number(tokensMatch[3]) : undefined,
250
+ categories: parseMarkdownTable(markdown, 'Estimated usage by category').map(row => ({
251
+ name: row.Category ?? '',
252
+ tokens: row.Tokens ?? '',
253
+ percentage: row.Percentage ?? '',
254
+ })),
255
+ skills: parseMarkdownTable(markdown, 'Skills').map(row => ({
256
+ name: row.Skill ?? '',
257
+ source: row.Source || undefined,
258
+ tokens: row.Tokens ?? '',
259
+ })),
260
+ agents: parseMarkdownTable(markdown, 'Custom Agents').map(row => ({
261
+ agentType: row['Agent Type'] ?? '',
262
+ source: row.Source || undefined,
263
+ tokens: row.Tokens ?? '',
264
+ })),
265
+ mcpTools: parseMarkdownTable(markdown, 'MCP Tools').map(row => ({
266
+ tool: row.Tool ?? '',
267
+ server: row.Server ?? '',
268
+ tokens: row.Tokens ?? '',
269
+ })),
270
+ rawResult: result,
271
+ };
272
+ }
273
+ function runtimeInfoFromInitEvent(initEvent) {
274
+ return {
275
+ sessionId: getStringValue(initEvent, 'session_id') ?? '',
276
+ cwd: getStringValue(initEvent, 'cwd'),
277
+ model: getStringValue(initEvent, 'model'),
278
+ permissionMode: getStringValue(initEvent, 'permissionMode'),
279
+ tools: getStringArray(initEvent.tools),
280
+ mcpServers: getObjectArray(initEvent.mcp_servers).map(server => ({
281
+ name: typeof server.name === 'string' ? server.name : '',
282
+ status: typeof server.status === 'string' ? server.status : undefined,
283
+ })),
284
+ slashCommands: getStringArray(initEvent.slash_commands),
285
+ agents: getStringArray(initEvent.agents),
286
+ skills: getStringArray(initEvent.skills),
287
+ plugins: getObjectArray(initEvent.plugins).map(plugin => ({
288
+ name: typeof plugin.name === 'string' ? plugin.name : '',
289
+ path: typeof plugin.path === 'string' ? plugin.path : undefined,
290
+ source: typeof plugin.source === 'string' ? plugin.source : undefined,
291
+ })),
292
+ rawInitEvent: structuredClone(initEvent),
293
+ };
294
+ }
295
+ function parseActoviqAgentSummaryOutput(stdout) {
296
+ const agents = [];
297
+ let currentGroup = 'Unknown';
298
+ for (const line of stdout.split(/\r?\n/)) {
299
+ const trimmed = line.trim();
300
+ if (!trimmed) {
301
+ continue;
302
+ }
303
+ if (/^\d+\s+active\s+agents$/u.test(trimmed)) {
304
+ continue;
305
+ }
306
+ if (trimmed.endsWith(':')) {
307
+ currentGroup = trimmed.slice(0, -1);
308
+ continue;
309
+ }
310
+ let active = true;
311
+ let shadowedBy;
312
+ let descriptor = trimmed;
313
+ const shadowedMatch = trimmed.match(/^\(shadowed by ([^)]+)\)\s+(.+)$/u);
314
+ if (shadowedMatch) {
315
+ active = false;
316
+ shadowedBy = shadowedMatch[1]?.trim();
317
+ descriptor = shadowedMatch[2] ?? trimmed;
318
+ }
319
+ const parts = descriptor.split(/\s+·\s+/u).map(part => part.trim()).filter(Boolean);
320
+ const name = parts.shift();
321
+ if (!name) {
322
+ continue;
323
+ }
324
+ let model;
325
+ let memory;
326
+ for (const part of parts) {
327
+ if (part.endsWith(' memory')) {
328
+ memory = part.replace(/ memory$/u, '');
329
+ }
330
+ else if (!model) {
331
+ model = part;
332
+ }
333
+ }
334
+ agents.push({
335
+ name,
336
+ sourceGroup: currentGroup,
337
+ active,
338
+ rawLine: trimmed,
339
+ model,
340
+ memory,
341
+ shadowedBy,
342
+ });
343
+ }
344
+ return agents;
345
+ }
346
+ function formatSlashCommand(commandName, args = '') {
347
+ const normalizedName = commandName.trim().replace(/^\/+/u, '');
348
+ const normalizedArgs = args.trim();
349
+ return normalizedArgs ? `/${normalizedName} ${normalizedArgs}` : `/${normalizedName}`;
350
+ }
351
+ function buildRuntimeCatalog(params) {
352
+ const { runtime, agents, context } = params;
353
+ const contextSkillMap = new Map(context?.skills.map(skill => [skill.name, skill]) ?? []);
354
+ const contextAgentMap = new Map(context?.agents.map(agent => [agent.agentType, agent]) ?? []);
355
+ const contextMcpToolMap = new Map(context?.mcpTools.map(tool => [tool.tool, tool]) ?? []);
356
+ const skillNames = new Set(runtime.skills);
357
+ const tools = runtime.tools.map(name => {
358
+ const contextTool = contextMcpToolMap.get(name);
359
+ return {
360
+ name,
361
+ kind: contextTool ? 'mcp' : 'builtin',
362
+ server: contextTool?.server,
363
+ tokens: contextTool?.tokens,
364
+ };
365
+ });
366
+ const skills = runtime.skills.map(name => {
367
+ const contextSkill = contextSkillMap.get(name);
368
+ return {
369
+ name,
370
+ slashCommand: `/${name}`,
371
+ source: contextSkill?.source,
372
+ tokens: contextSkill?.tokens,
373
+ };
374
+ });
375
+ const slashCommands = runtime.slashCommands.map(name => ({
376
+ name,
377
+ kind: skillNames.has(name) ? 'skill' : 'builtin',
378
+ skillName: skillNames.has(name) ? name : undefined,
379
+ }));
380
+ const enrichedAgents = agents.map(agent => {
381
+ const contextAgent = contextAgentMap.get(agent.name);
382
+ return {
383
+ ...agent,
384
+ contextSource: contextAgent?.source,
385
+ tokens: contextAgent?.tokens,
386
+ };
387
+ });
388
+ return {
389
+ runtime,
390
+ agents: enrichedAgents,
391
+ tools,
392
+ skills,
393
+ slashCommands,
394
+ context,
395
+ };
396
+ }
397
+ function buildCliArgs(prompt, options) {
398
+ const args = [
399
+ '-p',
400
+ prompt,
401
+ '--output-format',
402
+ 'stream-json',
403
+ '--verbose',
404
+ ];
405
+ if (options.includePartialMessages ?? true) {
406
+ args.push('--include-partial-messages');
407
+ }
408
+ if (options.includeHookEvents) {
409
+ args.push('--include-hook-events');
410
+ }
411
+ if (options.bare) {
412
+ args.push('--bare');
413
+ }
414
+ if (options.disableSlashCommands) {
415
+ args.push('--disable-slash-commands');
416
+ }
417
+ if (options.strictMcpConfig) {
418
+ args.push('--strict-mcp-config');
419
+ }
420
+ if (options.continueMostRecent) {
421
+ args.push('--continue');
422
+ }
423
+ if (options.forkSession) {
424
+ args.push('--fork-session');
425
+ }
426
+ const shouldSkipPermissions = options.dangerouslySkipPermissions ??
427
+ (options.permissionMode == null || options.permissionMode === 'bypassPermissions');
428
+ if (shouldSkipPermissions) {
429
+ args.push('--dangerously-skip-permissions');
430
+ }
431
+ appendOptionalArg(args, '--permission-mode', options.permissionMode);
432
+ appendOptionalArg(args, '--model', options.model);
433
+ appendOptionalArg(args, '--fallback-model', options.fallbackModel);
434
+ appendOptionalArg(args, '--effort', options.effort);
435
+ appendOptionalArg(args, '--system-prompt', options.systemPrompt);
436
+ appendOptionalArg(args, '--append-system-prompt', options.appendSystemPrompt);
437
+ appendOptionalArg(args, '--max-turns', options.maxTurns);
438
+ appendOptionalArg(args, '--max-budget-usd', options.maxBudgetUsd);
439
+ appendOptionalArg(args, '--agent', options.agent);
440
+ appendOptionalArg(args, '-n', options.name);
441
+ appendOptionalArg(args, '--setting-sources', options.settingSources);
442
+ if (options.jsonSchema != null) {
443
+ args.push('--json-schema', stringifyCliValue(options.jsonSchema));
444
+ }
445
+ if (options.settings != null) {
446
+ args.push('--settings', stringifyCliValue(options.settings));
447
+ }
448
+ if (options.agents != null) {
449
+ args.push('--agents', JSON.stringify(options.agents));
450
+ }
451
+ const toolsArg = normalizeToolsArgument(options.tools);
452
+ if (toolsArg != null) {
453
+ args.push('--tools', toolsArg);
454
+ }
455
+ if (options.allowedTools?.length) {
456
+ args.push('--allowedTools', options.allowedTools.join(','));
457
+ }
458
+ if (options.disallowedTools?.length) {
459
+ args.push('--disallowedTools', options.disallowedTools.join(','));
460
+ }
461
+ appendRepeatableArgs(args, '--add-dir', options.addDirs);
462
+ appendRepeatableArgs(args, '--plugin-dir', options.pluginDirs);
463
+ appendRepeatableArgs(args, '--file', options.files);
464
+ if (options.mcpConfigs?.length) {
465
+ args.push('--mcp-config', ...options.mcpConfigs.map(config => stringifyCliValue(config)));
466
+ }
467
+ if (typeof options.resume === 'string') {
468
+ args.push('--resume', options.resume);
469
+ }
470
+ else if (options.resume === true) {
471
+ args.push('--resume');
472
+ }
473
+ else if (options.sessionId) {
474
+ args.push('--session-id', options.sessionId);
475
+ }
476
+ if (options.cliArgs?.length) {
477
+ args.push(...options.cliArgs);
478
+ }
479
+ return args;
480
+ }
481
+ function buildChildEnvironment(envOverrides) {
482
+ const loadedConfig = getLoadedJsonConfig();
483
+ const mergedEnv = {
484
+ ...Object.fromEntries(Object.entries(process.env).filter((entry) => typeof entry[1] === 'string')),
485
+ ...(loadedConfig?.env ?? {}),
486
+ ...(envOverrides ?? {}),
487
+ };
488
+ return mergedEnv;
489
+ }
490
+ async function prefersSystemRipgrep(envOverrides) {
491
+ const explicit = envOverrides?.USE_BUILTIN_RIPGREP ?? process.env.USE_BUILTIN_RIPGREP;
492
+ if (explicit != null) {
493
+ return false;
494
+ }
495
+ return Boolean(await findExecutableOnPath('rg'));
496
+ }
497
+ async function parseStdoutEvents(child, onEvent) {
498
+ if (!child.stdout) {
499
+ return;
500
+ }
501
+ const stream = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
502
+ for await (const line of stream) {
503
+ const trimmed = line.trim();
504
+ if (!trimmed) {
505
+ continue;
506
+ }
507
+ let parsed;
508
+ try {
509
+ parsed = JSON.parse(trimmed);
510
+ }
511
+ catch (error) {
512
+ throw new ActoviqBridgeProcessError(`Failed to parse Actoviq Runtime stream line: ${trimmed}`, {
513
+ cause: error,
514
+ });
515
+ }
516
+ if (!isRecord(parsed) || typeof parsed.type !== 'string') {
517
+ throw new ActoviqBridgeProcessError('Actoviq Runtime emitted a malformed stream event.');
518
+ }
519
+ onEvent(parsed);
520
+ }
521
+ }
522
+ async function readStderr(child) {
523
+ if (!child.stderr) {
524
+ return '';
525
+ }
526
+ let stderr = '';
527
+ for await (const chunk of child.stderr) {
528
+ stderr += chunk.toString();
529
+ }
530
+ return stderr;
531
+ }
532
+ async function readStdout(child) {
533
+ if (!child.stdout) {
534
+ return '';
535
+ }
536
+ let stdout = '';
537
+ for await (const chunk of child.stdout) {
538
+ stdout += chunk.toString();
539
+ }
540
+ return stdout;
541
+ }
542
+ export class ActoviqBridgeRunStream {
543
+ queue = new AsyncQueue();
544
+ result;
545
+ constructor(executor) {
546
+ this.result = (async () => {
547
+ try {
548
+ return await executor({
549
+ emit: event => this.queue.push(event),
550
+ fail: error => this.queue.fail(error),
551
+ close: () => this.queue.close(),
552
+ });
553
+ }
554
+ catch (error) {
555
+ this.queue.fail(error);
556
+ throw error;
557
+ }
558
+ finally {
559
+ this.queue.close();
560
+ }
561
+ })();
562
+ }
563
+ [Symbol.asyncIterator]() {
564
+ return this.queue[Symbol.asyncIterator]();
565
+ }
566
+ }
567
+ export class ActoviqBridgeSession {
568
+ client;
569
+ id;
570
+ title;
571
+ defaults;
572
+ started;
573
+ constructor(client, id, title, defaults, started = false) {
574
+ this.client = client;
575
+ this.id = id;
576
+ this.title = title;
577
+ this.defaults = defaults;
578
+ this.started = started;
579
+ }
580
+ async send(prompt, options = {}) {
581
+ const result = await this.client.run(prompt, this.buildRunOptions(options));
582
+ this.started = true;
583
+ return result;
584
+ }
585
+ stream(prompt, options = {}) {
586
+ const runStream = this.client.stream(prompt, this.buildRunOptions(options));
587
+ void runStream.result.then(() => {
588
+ this.started = true;
589
+ }, () => undefined);
590
+ return runStream;
591
+ }
592
+ runSlashCommand(commandName, args = '', options = {}) {
593
+ return this.send(formatSlashCommand(commandName, args), options);
594
+ }
595
+ runSkill(skill, args = '', options = {}) {
596
+ return this.runSlashCommand(skill, args, options);
597
+ }
598
+ streamSlashCommand(commandName, args = '', options = {}) {
599
+ return this.stream(formatSlashCommand(commandName, args), options);
600
+ }
601
+ streamSkill(skill, args = '', options = {}) {
602
+ return this.streamSlashCommand(skill, args, options);
603
+ }
604
+ compact(args = '', options = {}) {
605
+ return this.runSlashCommand('compact', args, options);
606
+ }
607
+ info(options) {
608
+ return getActoviqBridgeSessionInfo(this.id, options);
609
+ }
610
+ messages(options) {
611
+ return getActoviqBridgeSessionMessages(this.id, options);
612
+ }
613
+ compactBoundaries(options) {
614
+ return getActoviqBridgeCompactBoundaries(this.id, options);
615
+ }
616
+ latestCompactBoundary(options) {
617
+ return getActoviqBridgeLatestCompactBoundary(this.id, options);
618
+ }
619
+ compactState(options = {}) {
620
+ return this.client.memory.compactState({
621
+ ...options,
622
+ sessionId: this.id,
623
+ });
624
+ }
625
+ fork(prompt, options = {}) {
626
+ return this.client.run(prompt, {
627
+ ...this.defaults,
628
+ ...options,
629
+ resume: this.id,
630
+ forkSession: true,
631
+ });
632
+ }
633
+ forkStream(prompt, options = {}) {
634
+ return this.client.stream(prompt, {
635
+ ...this.defaults,
636
+ ...options,
637
+ resume: this.id,
638
+ forkSession: true,
639
+ });
640
+ }
641
+ buildRunOptions(options) {
642
+ const merged = {
643
+ ...this.defaults,
644
+ ...options,
645
+ name: options.name ?? this.title,
646
+ };
647
+ if (this.started) {
648
+ merged.resume = this.id;
649
+ }
650
+ else {
651
+ merged.sessionId = this.id;
652
+ }
653
+ return merged;
654
+ }
655
+ }
656
+ export class ActoviqBridgeAgentHandle {
657
+ client;
658
+ agent;
659
+ defaults;
660
+ constructor(client, agent, defaults = {}) {
661
+ this.client = client;
662
+ this.agent = agent;
663
+ this.defaults = defaults;
664
+ }
665
+ run(prompt, options = {}) {
666
+ return this.client.run(prompt, {
667
+ ...this.defaults,
668
+ ...options,
669
+ agent: this.agent,
670
+ });
671
+ }
672
+ stream(prompt, options = {}) {
673
+ return this.client.stream(prompt, {
674
+ ...this.defaults,
675
+ ...options,
676
+ agent: this.agent,
677
+ });
678
+ }
679
+ createSession(options = {}) {
680
+ return this.client.createSession({
681
+ ...this.defaults,
682
+ ...options,
683
+ agent: this.agent,
684
+ });
685
+ }
686
+ }
687
+ export class ActoviqBridgeSkillHandle {
688
+ client;
689
+ skill;
690
+ defaults;
691
+ constructor(client, skill, defaults = {}) {
692
+ this.client = client;
693
+ this.skill = skill;
694
+ this.defaults = defaults;
695
+ }
696
+ run(args = '', options = {}) {
697
+ return this.client.runSlashCommand(this.skill, args, {
698
+ ...this.defaults,
699
+ ...options,
700
+ });
701
+ }
702
+ stream(args = '', options = {}) {
703
+ return this.client.streamSlashCommand(this.skill, args, {
704
+ ...this.defaults,
705
+ ...options,
706
+ });
707
+ }
708
+ async runInSession(session, args = '', options = {}) {
709
+ return session.runSlashCommand(this.skill, args, options);
710
+ }
711
+ streamInSession(session, args = '', options = {}) {
712
+ return session.streamSlashCommand(this.skill, args, options);
713
+ }
714
+ metadata(options) {
715
+ return this.client.getSkillMetadata(this.skill, options);
716
+ }
717
+ }
718
+ export class ActoviqBridgeAgentsApi {
719
+ client;
720
+ constructor(client) {
721
+ this.client = client;
722
+ }
723
+ list(options) {
724
+ return this.client.listAgents(options);
725
+ }
726
+ use(agent, defaults = {}) {
727
+ return new ActoviqBridgeAgentHandle(this.client, agent, defaults);
728
+ }
729
+ run(agent, prompt, options = {}) {
730
+ return this.client.run(prompt, {
731
+ ...options,
732
+ agent,
733
+ });
734
+ }
735
+ stream(agent, prompt, options = {}) {
736
+ return this.client.stream(prompt, {
737
+ ...options,
738
+ agent,
739
+ });
740
+ }
741
+ createSession(agent, options = {}) {
742
+ return this.client.createSession({
743
+ ...options,
744
+ agent,
745
+ });
746
+ }
747
+ }
748
+ export class ActoviqBridgeSkillsApi {
749
+ client;
750
+ constructor(client) {
751
+ this.client = client;
752
+ }
753
+ list(options) {
754
+ return this.client.listSkills(options);
755
+ }
756
+ use(skill, defaults = {}) {
757
+ return new ActoviqBridgeSkillHandle(this.client, skill, defaults);
758
+ }
759
+ run(skill, args = '', options = {}) {
760
+ return this.client.runSlashCommand(skill, args, options);
761
+ }
762
+ stream(skill, args = '', options = {}) {
763
+ return this.client.streamSlashCommand(skill, args, options);
764
+ }
765
+ listMetadata(options) {
766
+ return this.client.listSkillMetadata(options);
767
+ }
768
+ getMetadata(skill, options) {
769
+ return this.client.getSkillMetadata(skill, options);
770
+ }
771
+ }
772
+ export class ActoviqBridgeToolsApi {
773
+ client;
774
+ constructor(client) {
775
+ this.client = client;
776
+ }
777
+ list(options) {
778
+ return this.client.listTools(options);
779
+ }
780
+ listMetadata(options) {
781
+ return this.client.listToolMetadata(options);
782
+ }
783
+ getMetadata(toolName, options) {
784
+ return this.client.getToolMetadata(toolName, options);
785
+ }
786
+ }
787
+ export class ActoviqBridgeSlashCommandsApi {
788
+ client;
789
+ constructor(client) {
790
+ this.client = client;
791
+ }
792
+ list(options) {
793
+ return this.client.listSlashCommands(options);
794
+ }
795
+ listMetadata(options) {
796
+ return this.client.listSlashCommandMetadata(options);
797
+ }
798
+ getMetadata(commandName, options) {
799
+ return this.client.getSlashCommandMetadata(commandName, options);
800
+ }
801
+ run(commandName, args = '', options = {}) {
802
+ return this.client.runSlashCommand(commandName, args, options);
803
+ }
804
+ stream(commandName, args = '', options = {}) {
805
+ return this.client.streamSlashCommand(commandName, args, options);
806
+ }
807
+ }
808
+ export class ActoviqBridgeContextApi {
809
+ client;
810
+ constructor(client) {
811
+ this.client = client;
812
+ }
813
+ usage(options) {
814
+ return this.client.getContextUsage(options);
815
+ }
816
+ compact(args = '', options = {}) {
817
+ return this.client.runSlashCommand('compact', args, options);
818
+ }
819
+ streamCompact(args = '', options = {}) {
820
+ return this.client.streamSlashCommand('compact', args, options);
821
+ }
822
+ compactBoundaries(sessionId, options) {
823
+ return getActoviqBridgeCompactBoundaries(sessionId, options);
824
+ }
825
+ latestCompactBoundary(sessionId, options) {
826
+ return getActoviqBridgeLatestCompactBoundary(sessionId, options);
827
+ }
828
+ compactState(sessionId, options = {}) {
829
+ return this.client.memory.compactState({
830
+ ...options,
831
+ sessionId,
832
+ });
833
+ }
834
+ }
835
+ export class ActoviqBridgeSessionsApi {
836
+ client;
837
+ constructor(client) {
838
+ this.client = client;
839
+ }
840
+ list(options) {
841
+ return listActoviqBridgeSessions(options);
842
+ }
843
+ getInfo(sessionId, options) {
844
+ return getActoviqBridgeSessionInfo(sessionId, options);
845
+ }
846
+ getMessages(sessionId, options) {
847
+ return getActoviqBridgeSessionMessages(sessionId, options);
848
+ }
849
+ getCompactBoundaries(sessionId, options) {
850
+ return getActoviqBridgeCompactBoundaries(sessionId, options);
851
+ }
852
+ getLatestCompactBoundary(sessionId, options) {
853
+ return getActoviqBridgeLatestCompactBoundary(sessionId, options);
854
+ }
855
+ getCompactState(sessionId, options = {}) {
856
+ return this.client.memory.compactState({
857
+ ...options,
858
+ sessionId,
859
+ });
860
+ }
861
+ async resume(sessionId, options = {}) {
862
+ return this.client.resumeSession(sessionId, options);
863
+ }
864
+ continueMostRecent(prompt, options = {}) {
865
+ return this.client.continueMostRecent(prompt, options);
866
+ }
867
+ streamContinueMostRecent(prompt, options = {}) {
868
+ return this.client.streamContinueMostRecent(prompt, options);
869
+ }
870
+ fork(sessionId, prompt, options = {}) {
871
+ return this.client.forkSession(sessionId, prompt, options);
872
+ }
873
+ streamFork(sessionId, prompt, options = {}) {
874
+ return this.client.streamForkSession(sessionId, prompt, options);
875
+ }
876
+ getRuntimeInfo(options) {
877
+ return this.client.getRuntimeInfo(options);
878
+ }
879
+ listAgents(options) {
880
+ return this.client.listAgents(options);
881
+ }
882
+ listSkills(options) {
883
+ return this.client.listSkills(options);
884
+ }
885
+ listSlashCommands(options) {
886
+ return this.client.listSlashCommands(options);
887
+ }
888
+ listTools(options) {
889
+ return this.client.listTools(options);
890
+ }
891
+ getRuntimeCatalog(options) {
892
+ return this.client.getRuntimeCatalog(options);
893
+ }
894
+ listSkillMetadata(options) {
895
+ return this.client.listSkillMetadata(options);
896
+ }
897
+ listSlashCommandMetadata(options) {
898
+ return this.client.listSlashCommandMetadata(options);
899
+ }
900
+ listToolMetadata(options) {
901
+ return this.client.listToolMetadata(options);
902
+ }
903
+ getContextUsage(options) {
904
+ return this.client.getContextUsage(options);
905
+ }
906
+ }
907
+ export class ActoviqBridgeSdkClient {
908
+ executable;
909
+ cliPath;
910
+ defaults;
911
+ sessions;
912
+ agents;
913
+ skills;
914
+ tools;
915
+ slashCommands;
916
+ context;
917
+ buddy;
918
+ memory;
919
+ constructor(executable, cliPath, defaults) {
920
+ this.executable = executable;
921
+ this.cliPath = cliPath;
922
+ this.defaults = defaults;
923
+ this.sessions = new ActoviqBridgeSessionsApi(this);
924
+ this.agents = new ActoviqBridgeAgentsApi(this);
925
+ this.skills = new ActoviqBridgeSkillsApi(this);
926
+ this.tools = new ActoviqBridgeToolsApi(this);
927
+ this.slashCommands = new ActoviqBridgeSlashCommandsApi(this);
928
+ this.context = new ActoviqBridgeContextApi(this);
929
+ this.buddy = createActoviqBuddyApi({
930
+ homeDir: this.defaults.homeDir,
931
+ });
932
+ this.memory = createActoviqMemoryApi({
933
+ homeDir: this.defaults.homeDir,
934
+ projectPath: this.defaults.workDir ?? process.cwd(),
935
+ });
936
+ }
937
+ static async create(options = {}) {
938
+ const executable = await resolveBunExecutable(options.executable);
939
+ const cliPath = await resolveActoviqRuntimeCliPath(options.cliPath);
940
+ return new ActoviqBridgeSdkClient(executable, cliPath, {
941
+ ...options,
942
+ executable: undefined,
943
+ cliPath: undefined,
944
+ });
945
+ }
946
+ async run(prompt, options = {}) {
947
+ const stream = this.stream(prompt, options);
948
+ return stream.result;
949
+ }
950
+ runSlashCommand(commandName, args = '', options = {}) {
951
+ return this.run(formatSlashCommand(commandName, args), options);
952
+ }
953
+ runWithAgent(agent, prompt, options = {}) {
954
+ return this.run(prompt, {
955
+ ...options,
956
+ agent,
957
+ });
958
+ }
959
+ runSkill(skill, args = '', options = {}) {
960
+ return this.runSlashCommand(skill, args, options);
961
+ }
962
+ continueMostRecent(prompt, options = {}) {
963
+ return this.run(prompt, {
964
+ ...options,
965
+ continueMostRecent: true,
966
+ });
967
+ }
968
+ streamContinueMostRecent(prompt, options = {}) {
969
+ return this.stream(prompt, {
970
+ ...options,
971
+ continueMostRecent: true,
972
+ });
973
+ }
974
+ forkSession(sessionId, prompt, options = {}) {
975
+ return this.run(prompt, {
976
+ ...options,
977
+ resume: sessionId,
978
+ forkSession: true,
979
+ });
980
+ }
981
+ streamForkSession(sessionId, prompt, options = {}) {
982
+ return this.stream(prompt, {
983
+ ...options,
984
+ resume: sessionId,
985
+ forkSession: true,
986
+ });
987
+ }
988
+ stream(prompt, options = {}) {
989
+ const mergedOptions = this.mergeOptions(options);
990
+ return new ActoviqBridgeRunStream(async (controller) => {
991
+ return this.execute(prompt, mergedOptions, controller);
992
+ });
993
+ }
994
+ streamSlashCommand(commandName, args = '', options = {}) {
995
+ return this.stream(formatSlashCommand(commandName, args), options);
996
+ }
997
+ streamWithAgent(agent, prompt, options = {}) {
998
+ return this.stream(prompt, {
999
+ ...options,
1000
+ agent,
1001
+ });
1002
+ }
1003
+ streamSkill(skill, args = '', options = {}) {
1004
+ return this.streamSlashCommand(skill, args, options);
1005
+ }
1006
+ async createSession(options = {}) {
1007
+ const sessionId = options.sessionId ?? randomUUID();
1008
+ return new ActoviqBridgeSession(this, sessionId, options.title, this.mergeOptions(options), false);
1009
+ }
1010
+ createAgentSession(agent, options = {}) {
1011
+ return this.createSession({
1012
+ ...options,
1013
+ agent,
1014
+ });
1015
+ }
1016
+ useAgent(agent, defaults = {}) {
1017
+ return this.agents.use(agent, defaults);
1018
+ }
1019
+ useSkill(skill, defaults = {}) {
1020
+ return this.skills.use(skill, defaults);
1021
+ }
1022
+ async resumeSession(sessionId, options = {}) {
1023
+ return new ActoviqBridgeSession(this, sessionId, options.title, this.mergeOptions(options), true);
1024
+ }
1025
+ async close() {
1026
+ return Promise.resolve();
1027
+ }
1028
+ async getRuntimeInfo(options = {}) {
1029
+ const result = await this.run('/cost', {
1030
+ ...options,
1031
+ includePartialMessages: false,
1032
+ maxTurns: options.maxTurns ?? 2,
1033
+ });
1034
+ if (!result.initEvent) {
1035
+ throw new ActoviqBridgeProcessError('Actoviq Runtime did not emit an init event for /cost.');
1036
+ }
1037
+ return runtimeInfoFromInitEvent(result.initEvent);
1038
+ }
1039
+ async listSkills(options = {}) {
1040
+ const info = await this.getRuntimeInfo(options);
1041
+ return [...info.skills];
1042
+ }
1043
+ async listTools(options = {}) {
1044
+ const info = await this.getRuntimeInfo(options);
1045
+ return [...info.tools];
1046
+ }
1047
+ async listSlashCommands(options = {}) {
1048
+ const info = await this.getRuntimeInfo(options);
1049
+ return [...info.slashCommands];
1050
+ }
1051
+ async listAgents(options = {}) {
1052
+ const raw = await this.runRawCliCommand(['agents'], options);
1053
+ return parseActoviqAgentSummaryOutput(raw.stdout);
1054
+ }
1055
+ async getContextUsage(options = {}) {
1056
+ const result = await this.run('/context', {
1057
+ ...options,
1058
+ includePartialMessages: false,
1059
+ maxTurns: options.maxTurns ?? 2,
1060
+ });
1061
+ return parseActoviqContextUsageResult(result);
1062
+ }
1063
+ async getRuntimeCatalog(options = {}) {
1064
+ const runtimeOptions = {
1065
+ ...options,
1066
+ };
1067
+ delete runtimeOptions.includeContext;
1068
+ const [runtime, agents, context] = await Promise.all([
1069
+ this.getRuntimeInfo(runtimeOptions),
1070
+ this.listAgents(runtimeOptions),
1071
+ options.includeContext === false
1072
+ ? Promise.resolve(undefined)
1073
+ : this.getContextUsage(runtimeOptions).catch(() => undefined),
1074
+ ]);
1075
+ return buildRuntimeCatalog({
1076
+ runtime,
1077
+ agents,
1078
+ context,
1079
+ });
1080
+ }
1081
+ async listSkillMetadata(options = {}) {
1082
+ const catalog = await this.getRuntimeCatalog(options);
1083
+ return catalog.skills;
1084
+ }
1085
+ async getSkillMetadata(skillName, options = {}) {
1086
+ const catalog = await this.getRuntimeCatalog(options);
1087
+ return catalog.skills.find(skill => skill.name === skillName);
1088
+ }
1089
+ async listToolMetadata(options = {}) {
1090
+ const catalog = await this.getRuntimeCatalog(options);
1091
+ return catalog.tools;
1092
+ }
1093
+ async getToolMetadata(toolName, options = {}) {
1094
+ const catalog = await this.getRuntimeCatalog(options);
1095
+ return catalog.tools.find(tool => tool.name === toolName);
1096
+ }
1097
+ async listSlashCommandMetadata(options = {}) {
1098
+ const catalog = await this.getRuntimeCatalog(options);
1099
+ return catalog.slashCommands;
1100
+ }
1101
+ async getSlashCommandMetadata(commandName, options = {}) {
1102
+ const normalized = commandName.trim().replace(/^\/+/u, '');
1103
+ const catalog = await this.getRuntimeCatalog(options);
1104
+ return catalog.slashCommands.find(command => command.name === normalized);
1105
+ }
1106
+ compactContext(args = '', options = {}) {
1107
+ return this.runSlashCommand('compact', args, options);
1108
+ }
1109
+ mergeOptions(options) {
1110
+ return {
1111
+ ...this.defaults,
1112
+ ...options,
1113
+ executable: this.executable,
1114
+ cliPath: this.cliPath,
1115
+ workDir: options.workDir ?? this.defaults.workDir ?? process.cwd(),
1116
+ };
1117
+ }
1118
+ async runRawCliCommand(rawArgs, options = {}) {
1119
+ if (options.signal?.aborted) {
1120
+ throw new RunAbortedError('The Actoviq Runtime command was aborted before it started.');
1121
+ }
1122
+ const merged = this.mergeOptions(options);
1123
+ const childEnv = buildChildEnvironment(merged.env);
1124
+ if (await prefersSystemRipgrep(merged.env)) {
1125
+ childEnv.USE_BUILTIN_RIPGREP = '0';
1126
+ }
1127
+ const child = spawn(merged.executable ?? this.executable, [merged.cliPath ?? this.cliPath, ...rawArgs], {
1128
+ cwd: merged.workDir ?? this.defaults.workDir ?? process.cwd(),
1129
+ env: childEnv,
1130
+ stdio: ['ignore', 'pipe', 'pipe'],
1131
+ windowsHide: true,
1132
+ shell: IS_WINDOWS &&
1133
+ /\.(?:cmd|bat)$/i.test(merged.executable ?? this.executable),
1134
+ });
1135
+ let aborted = false;
1136
+ const abort = () => {
1137
+ aborted = true;
1138
+ child.kill('SIGTERM');
1139
+ };
1140
+ options.signal?.addEventListener('abort', abort, { once: true });
1141
+ const stdoutPromise = readStdout(child);
1142
+ const stderrPromise = readStderr(child);
1143
+ const exitCodePromise = new Promise((resolve, reject) => {
1144
+ child.once('error', reject);
1145
+ child.once('close', code => resolve(code));
1146
+ });
1147
+ try {
1148
+ const [stdout, stderr, exitCode] = await Promise.all([
1149
+ stdoutPromise,
1150
+ stderrPromise,
1151
+ exitCodePromise,
1152
+ ]);
1153
+ if (aborted) {
1154
+ throw new RunAbortedError('The Actoviq Runtime command was aborted.');
1155
+ }
1156
+ if (exitCode !== 0) {
1157
+ throw new ActoviqBridgeProcessError(stderr.trim()
1158
+ ? `Actoviq Runtime command failed: ${stderr.trim()}`
1159
+ : `Actoviq Runtime command failed with exit code ${exitCode}.`, { stderr, exitCode });
1160
+ }
1161
+ return { stdout, stderr, exitCode };
1162
+ }
1163
+ catch (error) {
1164
+ const normalized = asError(error);
1165
+ if (aborted || isAbortErrorLike(normalized)) {
1166
+ throw new RunAbortedError('The Actoviq Runtime command was aborted.', { cause: error });
1167
+ }
1168
+ throw new ActoviqBridgeProcessError(normalized.message, { cause: error });
1169
+ }
1170
+ finally {
1171
+ options.signal?.removeEventListener('abort', abort);
1172
+ }
1173
+ }
1174
+ async execute(prompt, options, controller) {
1175
+ if (options.signal?.aborted) {
1176
+ throw new RunAbortedError('The Actoviq Runtime run was aborted before it started.');
1177
+ }
1178
+ const childEnv = buildChildEnvironment(options.env);
1179
+ if (await prefersSystemRipgrep(options.env)) {
1180
+ childEnv.USE_BUILTIN_RIPGREP = '0';
1181
+ }
1182
+ const args = [options.cliPath ?? this.cliPath, ...buildCliArgs(prompt, options)];
1183
+ const child = spawn(options.executable ?? this.executable, args, {
1184
+ cwd: options.workDir ?? this.defaults.workDir ?? process.cwd(),
1185
+ env: childEnv,
1186
+ stdio: ['ignore', 'pipe', 'pipe'],
1187
+ windowsHide: true,
1188
+ shell: IS_WINDOWS &&
1189
+ /\.(?:cmd|bat)$/i.test(options.executable ?? this.executable),
1190
+ });
1191
+ const events = [];
1192
+ const assistantMessages = [];
1193
+ let initEvent;
1194
+ let resultEvent;
1195
+ let aborted = false;
1196
+ const abort = () => {
1197
+ aborted = true;
1198
+ child.kill('SIGTERM');
1199
+ };
1200
+ options.signal?.addEventListener('abort', abort, { once: true });
1201
+ const stdoutPromise = parseStdoutEvents(child, event => {
1202
+ events.push(structuredClone(event));
1203
+ if (event.type === 'system' && event.subtype === 'init') {
1204
+ initEvent = structuredClone(event);
1205
+ }
1206
+ if (event.type === 'assistant') {
1207
+ assistantMessages.push(structuredClone(event));
1208
+ }
1209
+ if (event.type === 'result') {
1210
+ resultEvent = structuredClone(event);
1211
+ }
1212
+ controller.emit(event);
1213
+ });
1214
+ const stderrPromise = readStderr(child);
1215
+ const exitCodePromise = new Promise((resolve, reject) => {
1216
+ child.once('error', reject);
1217
+ child.once('close', code => resolve(code));
1218
+ });
1219
+ let stderr = '';
1220
+ let exitCode = null;
1221
+ try {
1222
+ [stderr, exitCode] = await Promise.all([stderrPromise, exitCodePromise, stdoutPromise]).then(([nextStderr, nextExitCode]) => [nextStderr, nextExitCode]);
1223
+ }
1224
+ catch (error) {
1225
+ const normalized = asError(error);
1226
+ if (aborted || isAbortErrorLike(normalized)) {
1227
+ throw new RunAbortedError('The Actoviq Runtime run was aborted.', { cause: error });
1228
+ }
1229
+ throw new ActoviqBridgeProcessError(normalized.message, { cause: error, stderr, exitCode });
1230
+ }
1231
+ finally {
1232
+ options.signal?.removeEventListener('abort', abort);
1233
+ }
1234
+ if (aborted && !resultEvent) {
1235
+ throw new RunAbortedError('The Actoviq Runtime run was aborted.');
1236
+ }
1237
+ if (!resultEvent) {
1238
+ throw new ActoviqBridgeProcessError(stderr.trim()
1239
+ ? `Actoviq Runtime exited without a result event: ${stderr.trim()}`
1240
+ : 'Actoviq Runtime exited without emitting a result event.', { stderr, exitCode });
1241
+ }
1242
+ const result = {
1243
+ text: deriveResultText(resultEvent, assistantMessages),
1244
+ sessionId: getStringValue(resultEvent, 'session_id') ??
1245
+ getStringValue(initEvent, 'session_id') ??
1246
+ options.sessionId ??
1247
+ (typeof options.resume === 'string' ? options.resume : ''),
1248
+ isError: getBooleanValue(resultEvent, 'is_error') ?? false,
1249
+ subtype: getStringValue(resultEvent, 'subtype'),
1250
+ stopReason: getStringValue(resultEvent, 'stop_reason'),
1251
+ durationMs: getNumberValue(resultEvent, 'duration_ms'),
1252
+ totalCostUsd: getNumberValue(resultEvent, 'total_cost_usd'),
1253
+ numTurns: getNumberValue(resultEvent, 'num_turns'),
1254
+ exitCode,
1255
+ stderr,
1256
+ initEvent,
1257
+ resultEvent,
1258
+ assistantMessages,
1259
+ events,
1260
+ };
1261
+ return result;
1262
+ }
1263
+ }
1264
+ export async function createActoviqBridgeSdk(options = {}) {
1265
+ return ActoviqBridgeSdkClient.create(options);
1266
+ }
1267
+ //# sourceMappingURL=actoviqBridgeSdk.js.map