@sorbetai/acp 0.0.0-stage → 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 (38) hide show
  1. package/COMPATIBILITY.md +231 -0
  2. package/README.md +270 -2
  3. package/agent.json +15 -0
  4. package/dist/LICENSE.pi +21 -0
  5. package/dist/agent-B7PnGaB0.js +1600 -0
  6. package/dist/agent-B7PnGaB0.js.map +1 -0
  7. package/dist/agent-DfScvNX2.d.ts +43 -0
  8. package/dist/authentication-CraYYCai.js +132 -0
  9. package/dist/authentication-CraYYCai.js.map +1 -0
  10. package/dist/compatibility-B1ZA8Wvn.d.ts +606 -0
  11. package/dist/compatibility-Cmomxq8E.js +728 -0
  12. package/dist/compatibility-Cmomxq8E.js.map +1 -0
  13. package/dist/compatibility.d.ts +2 -0
  14. package/dist/compatibility.js +3 -0
  15. package/dist/experimental-v2-CB_5NMax.d.ts +35 -0
  16. package/dist/experimental-v2-DH1LLn_I.js +1088 -0
  17. package/dist/experimental-v2-DH1LLn_I.js.map +1 -0
  18. package/dist/experimental-v2.d.ts +3 -0
  19. package/dist/experimental-v2.js +4 -0
  20. package/dist/extensions-czICN7yK.js +10 -0
  21. package/dist/extensions-czICN7yK.js.map +1 -0
  22. package/dist/extensions.d.ts +29 -0
  23. package/dist/extensions.js +3 -0
  24. package/dist/filesystem-worker.js +10445 -0
  25. package/dist/filesystem-worker.js.map +1 -0
  26. package/dist/index-BzGG36Gz.d.ts +8248 -0
  27. package/dist/index.d.ts +9 -0
  28. package/dist/index.js +7 -0
  29. package/dist/session-attachments-DXvfzXfV.js +23124 -0
  30. package/dist/session-attachments-DXvfzXfV.js.map +1 -0
  31. package/dist/stdio-Bwi2cEOV.js +38 -0
  32. package/dist/stdio-Bwi2cEOV.js.map +1 -0
  33. package/dist/stdio-cli.d.ts +1 -0
  34. package/dist/stdio-cli.js +91 -0
  35. package/dist/stdio-cli.js.map +1 -0
  36. package/dist/stdio.d.ts +20 -0
  37. package/dist/stdio.js +7 -0
  38. package/package.json +85 -3
@@ -0,0 +1,1600 @@
1
+ import { C as JournalCursorSchema, S as isAuthoritativeSessionTitleSource, _ as NodeAgentError, a as listRefreshedModels, c as connectMcpServers, d as contextUsageUpdate, f as detailedUsageUpdate, h as createV1SessionElicitation, i as toolTitle, m as createV1RequestElicitation, n as lodyTitleSource, o as modelConfigOptions, p as observeSessionUsage, r as sessionRequestError, s as modelsIncludingCurrent, t as AcpSessionAttachments, u as SORBET_ACP_VERSION, v as NodeAgentErrorCode, y as coordinateNodeAgentBehavior } from "./session-attachments-DXvfzXfV.js";
2
+ import { a as SORBET_RUN_INSPECT_METHOD, i as SORBET_REPLAY_METHOD, r as SORBET_EXTENSION_VERSION, t as SESSION_STEERING_METHOD } from "./extensions-czICN7yK.js";
3
+ import { Type } from "typebox";
4
+ import * as acp from "@agentclientprotocol/sdk";
5
+ import { isEqual, isNil, isString } from "es-toolkit";
6
+ import { Check, Parse } from "typebox/schema";
7
+ import { LODY_EXTENSION_METHODS } from "acp-extension-core";
8
+ import { z } from "zod";
9
+
10
+ //#region src/client-tools.ts
11
+ function createAcpClientTools(capabilities, identity, client) {
12
+ const tools = [];
13
+ if (capabilities.fs?.readTextFile === true) tools.push(readTextFileTool(identity, client));
14
+ if (capabilities.fs?.writeTextFile === true) tools.push(writeTextFileTool(identity, client));
15
+ if (capabilities.terminal === true) tools.push(createTerminalTool(identity, client), terminalOutputTool(identity, client), waitForTerminalTool(identity, client), killTerminalTool(identity, client), releaseTerminalTool(identity, client));
16
+ return tools;
17
+ }
18
+ const ReadTextFileParameters = Type.Object({
19
+ path: Type.String({ minLength: 1 }),
20
+ line: Type.Optional(Type.Integer({ minimum: 1 })),
21
+ limit: Type.Optional(Type.Integer({ minimum: 1 }))
22
+ }, { additionalProperties: false });
23
+ function readTextFileTool(identity, client) {
24
+ return {
25
+ name: "acp_fs_read_text_file",
26
+ label: "Read client file",
27
+ description: "Read a text file through the connected ACP Client filesystem capability.",
28
+ parameters: ReadTextFileParameters,
29
+ execute: async (_toolCallId, rawParameters, signal) => {
30
+ const parameters = Parse(ReadTextFileParameters, rawParameters);
31
+ const response = await client.request(acp.methods.client.fs.readTextFile, {
32
+ sessionId: sessionId(identity),
33
+ ...parameters
34
+ }, { cancellationSignal: signal });
35
+ return {
36
+ content: [{
37
+ type: "text",
38
+ text: response.content
39
+ }],
40
+ details: response
41
+ };
42
+ }
43
+ };
44
+ }
45
+ const WriteTextFileParameters = Type.Object({
46
+ path: Type.String({ minLength: 1 }),
47
+ content: Type.String()
48
+ }, { additionalProperties: false });
49
+ function writeTextFileTool(identity, client) {
50
+ return {
51
+ name: "acp_fs_write_text_file",
52
+ label: "Write client file",
53
+ description: "Write a text file through the connected ACP Client filesystem capability.",
54
+ parameters: WriteTextFileParameters,
55
+ execute: async (_toolCallId, rawParameters, signal) => {
56
+ const parameters = Parse(WriteTextFileParameters, rawParameters);
57
+ const response = await client.request(acp.methods.client.fs.writeTextFile, {
58
+ sessionId: sessionId(identity),
59
+ ...parameters
60
+ }, { cancellationSignal: signal });
61
+ return {
62
+ content: [{
63
+ type: "text",
64
+ text: `Wrote ${parameters.path}`
65
+ }],
66
+ details: response
67
+ };
68
+ }
69
+ };
70
+ }
71
+ const CreateTerminalParameters = Type.Object({
72
+ command: Type.String({ minLength: 1 }),
73
+ args: Type.Optional(Type.Array(Type.String())),
74
+ env: Type.Optional(Type.Array(Type.Object({
75
+ name: Type.String({ minLength: 1 }),
76
+ value: Type.String()
77
+ }, { additionalProperties: false }))),
78
+ cwd: Type.Optional(Type.String({ minLength: 1 })),
79
+ outputByteLimit: Type.Optional(Type.Integer({ minimum: 1 }))
80
+ }, { additionalProperties: false });
81
+ function createTerminalTool(identity, client) {
82
+ return {
83
+ name: "acp_terminal_create",
84
+ label: "Start client terminal",
85
+ description: "Start a command in an ACP Client-owned terminal and return its terminal ID.",
86
+ parameters: CreateTerminalParameters,
87
+ execute: async (_toolCallId, rawParameters, signal) => {
88
+ const parameters = Parse(CreateTerminalParameters, rawParameters);
89
+ const response = await client.request(acp.methods.client.terminal.create, {
90
+ sessionId: sessionId(identity),
91
+ ...parameters
92
+ }, { cancellationSignal: signal });
93
+ return {
94
+ content: [{
95
+ type: "text",
96
+ text: `Terminal ${response.terminalId} started`
97
+ }],
98
+ details: response
99
+ };
100
+ }
101
+ };
102
+ }
103
+ const TerminalParameters = Type.Object({ terminalId: Type.String({ minLength: 1 }) }, { additionalProperties: false });
104
+ function terminalOutputTool(identity, client) {
105
+ return terminalTool({
106
+ name: "acp_terminal_output",
107
+ label: "Read client terminal",
108
+ description: "Read retained output and status from an ACP Client-owned terminal.",
109
+ identity,
110
+ request: async (parameters, signal) => {
111
+ const response = await client.request(acp.methods.client.terminal.output, {
112
+ sessionId: sessionId(identity),
113
+ ...parameters
114
+ }, { cancellationSignal: signal });
115
+ return {
116
+ text: response.output,
117
+ details: response
118
+ };
119
+ }
120
+ });
121
+ }
122
+ function waitForTerminalTool(identity, client) {
123
+ return terminalTool({
124
+ name: "acp_terminal_wait",
125
+ label: "Wait for client terminal",
126
+ description: "Wait until an ACP Client-owned terminal exits.",
127
+ identity,
128
+ request: async (parameters, signal) => {
129
+ const response = await client.request(acp.methods.client.terminal.waitForExit, {
130
+ sessionId: sessionId(identity),
131
+ ...parameters
132
+ }, { cancellationSignal: signal });
133
+ return {
134
+ text: JSON.stringify(response),
135
+ details: response
136
+ };
137
+ }
138
+ });
139
+ }
140
+ function killTerminalTool(identity, client) {
141
+ return terminalTool({
142
+ name: "acp_terminal_kill",
143
+ label: "Kill client terminal",
144
+ description: "Kill an ACP Client-owned terminal without releasing it.",
145
+ identity,
146
+ request: async (parameters, signal) => {
147
+ const response = await client.request(acp.methods.client.terminal.kill, {
148
+ sessionId: sessionId(identity),
149
+ ...parameters
150
+ }, { cancellationSignal: signal });
151
+ return {
152
+ text: `Killed terminal ${parameters.terminalId}`,
153
+ details: response
154
+ };
155
+ }
156
+ });
157
+ }
158
+ function releaseTerminalTool(identity, client) {
159
+ return terminalTool({
160
+ name: "acp_terminal_release",
161
+ label: "Release client terminal",
162
+ description: "Release an ACP Client-owned terminal and its retained resources.",
163
+ identity,
164
+ request: async (parameters, signal) => {
165
+ const response = await client.request(acp.methods.client.terminal.release, {
166
+ sessionId: sessionId(identity),
167
+ ...parameters
168
+ }, { cancellationSignal: signal });
169
+ return {
170
+ text: `Released terminal ${parameters.terminalId}`,
171
+ details: response
172
+ };
173
+ }
174
+ });
175
+ }
176
+ function terminalTool(options) {
177
+ return {
178
+ name: options.name,
179
+ label: options.label,
180
+ description: options.description,
181
+ parameters: TerminalParameters,
182
+ execute: async (_toolCallId, rawParameters, signal) => {
183
+ const parameters = Parse(TerminalParameters, rawParameters);
184
+ const result = await options.request(parameters, signal);
185
+ return {
186
+ content: [{
187
+ type: "text",
188
+ text: result.text
189
+ }],
190
+ details: result.details
191
+ };
192
+ }
193
+ };
194
+ }
195
+ function sessionId(identity) {
196
+ if (identity.sessionId === void 0) throw new Error("ACP Session identity is not available");
197
+ return identity.sessionId;
198
+ }
199
+
200
+ //#endregion
201
+ //#region src/prompt.ts
202
+ const textResourceParser = z.looseObject({
203
+ uri: z.string(),
204
+ text: z.string()
205
+ });
206
+ const blobResourceParser = z.looseObject({
207
+ uri: z.string(),
208
+ blob: z.string()
209
+ });
210
+ async function decodePrompt(blocks, audio, signal) {
211
+ const content = [];
212
+ for (const block of blocks) {
213
+ signal.throwIfAborted();
214
+ switch (block.type) {
215
+ case "text":
216
+ content.push({
217
+ type: "text",
218
+ text: block.text
219
+ });
220
+ break;
221
+ case "image":
222
+ content.push({
223
+ type: "image",
224
+ data: block.data,
225
+ mimeType: block.mimeType
226
+ });
227
+ break;
228
+ case "audio":
229
+ if (audio === void 0) throw new TypeError("This Sorbet ACP runtime does not accept audio");
230
+ content.push(...await audio.decode(block, signal));
231
+ break;
232
+ case "resource_link":
233
+ content.push({
234
+ type: "text",
235
+ text: resourceLinkText(block)
236
+ });
237
+ break;
238
+ case "resource":
239
+ {
240
+ const textResource = textResourceParser.safeParse(block.resource);
241
+ if (textResource.success) {
242
+ content.push({
243
+ type: "text",
244
+ text: `<resource uri="${textResource.data.uri}"${mediaTypeAttribute(block.resource.mimeType)}>\n${textResource.data.text}\n</resource>`
245
+ });
246
+ break;
247
+ }
248
+ }
249
+ if (block.resource.mimeType?.startsWith("image/") === true) {
250
+ const blobResource = blobResourceParser.parse(block.resource);
251
+ content.push({
252
+ type: "image",
253
+ data: blobResource.blob,
254
+ mimeType: block.resource.mimeType
255
+ });
256
+ } else content.push({
257
+ type: "text",
258
+ text: `<resource uri="${block.resource.uri}"${mediaTypeAttribute(block.resource.mimeType)}>binary content omitted</resource>`
259
+ });
260
+ break;
261
+ }
262
+ }
263
+ if (content.length === 0) throw new TypeError("ACP prompt must contain content");
264
+ return content;
265
+ }
266
+ function resourceLinkText(link) {
267
+ const description = isNil(link.description) ? "" : ` description="${link.description}"`;
268
+ return `<resource-link uri="${link.uri}" name="${link.name}"${description}${mediaTypeAttribute(link.mimeType)} />`;
269
+ }
270
+ function mediaTypeAttribute(mediaType) {
271
+ return isNil(mediaType) ? "" : ` media-type="${mediaType}"`;
272
+ }
273
+
274
+ //#endregion
275
+ //#region src/projection.ts
276
+ const ToolLocationParametersSchema = Type.Object({ path: Type.String({ minLength: 1 }) }, { additionalProperties: true });
277
+ const ChildSnapshotSchema = Type.Object({
278
+ agentId: Type.String({ minLength: 1 }),
279
+ state: Type.Union([
280
+ Type.Literal("starting"),
281
+ Type.Literal("running"),
282
+ Type.Literal("completed"),
283
+ Type.Literal("failed"),
284
+ Type.Literal("cancelled"),
285
+ Type.Literal("closed")
286
+ ]),
287
+ modelUsage: Type.Object({ totalTokens: Type.Number({ minimum: 0 }) }, { additionalProperties: true }),
288
+ response: Type.Optional(Type.Object({ text: Type.String() }, { additionalProperties: true })),
289
+ outcome: Type.Optional(Type.Object({ kind: Type.String() }, { additionalProperties: true }))
290
+ }, { additionalProperties: true });
291
+ const ChildToolResultSchema = Type.Object({ details: Type.Object({
292
+ action: Type.String(),
293
+ agent: Type.Optional(ChildSnapshotSchema),
294
+ agents: Type.Optional(Type.Array(ChildSnapshotSchema)),
295
+ tasks: Type.Optional(Type.Array(Type.Object({ agent: Type.Optional(ChildSnapshotSchema) }, { additionalProperties: true })))
296
+ }, { additionalProperties: true }) }, { additionalProperties: true });
297
+ const FAILED_CHILD_STATES = new Set(["failed", "cancelled"]);
298
+ async function projectRun(sessionId$1, run, client, tools, supportsPlanUpdates) {
299
+ const events = run.liveEvents();
300
+ let messageSequence = 0;
301
+ let messageId = `${run.receipt.runId}:assistant:0`;
302
+ try {
303
+ for await (const event of events) switch (event.type) {
304
+ case "message_start":
305
+ if (event.message.role === "assistant") {
306
+ messageSequence += 1;
307
+ messageId = `${run.receipt.runId}:assistant:${messageSequence}`;
308
+ }
309
+ break;
310
+ case "message_update":
311
+ await projectAssistantDelta(sessionId$1, messageId, event, client, tools);
312
+ break;
313
+ case "tool_execution_start":
314
+ await update(client, sessionId$1, {
315
+ sessionUpdate: "tool_call_update",
316
+ toolCallId: event.toolCallId,
317
+ title: toolTitle(event.toolName, event.args, tools),
318
+ name: event.toolName,
319
+ kind: toolKind$1(event.toolName),
320
+ status: "in_progress",
321
+ rawInput: event.args,
322
+ locations: locations(event.args)
323
+ });
324
+ break;
325
+ case "tool_execution_update":
326
+ await update(client, sessionId$1, {
327
+ sessionUpdate: "tool_call_update",
328
+ toolCallId: event.toolCallId,
329
+ rawOutput: event.partialResult
330
+ });
331
+ break;
332
+ case "tool_execution_end":
333
+ await update(client, sessionId$1, {
334
+ sessionUpdate: "tool_call_update",
335
+ toolCallId: event.toolCallId,
336
+ status: event.isError ? "failed" : "completed",
337
+ rawOutput: event.result
338
+ });
339
+ await projectChildTasks(sessionId$1, event.toolCallId, event.result, client);
340
+ break;
341
+ case "session.behavior.changed":
342
+ await projectBehaviorSnapshot(sessionId$1, {
343
+ name: event.name,
344
+ view: event.view
345
+ }, client, supportsPlanUpdates);
346
+ break;
347
+ case "auto_retry_start":
348
+ await update(client, sessionId$1, {
349
+ sessionUpdate: "tool_call",
350
+ toolCallId: retryToolCallId(event.logicalModelCallId, event.attempt),
351
+ title: `Retrying model request (${event.attempt}/${event.maxAttempts})`,
352
+ kind: "other",
353
+ status: "in_progress",
354
+ rawInput: {
355
+ attempt: event.attempt,
356
+ maxAttempts: event.maxAttempts,
357
+ delayMs: event.delayMs,
358
+ error: event.errorMessage
359
+ },
360
+ _meta: { lody: { activity: {
361
+ version: 1,
362
+ kind: "retry",
363
+ durationMs: event.delayMs,
364
+ failureReason: event.errorMessage
365
+ } } }
366
+ });
367
+ break;
368
+ case "auto_retry_end":
369
+ await update(client, sessionId$1, {
370
+ sessionUpdate: "tool_call_update",
371
+ toolCallId: retryToolCallId(event.logicalModelCallId, event.attempt),
372
+ status: event.success ? "completed" : "failed",
373
+ ...event.finalError === void 0 ? {} : { rawOutput: event.finalError },
374
+ _meta: { lody: { activity: {
375
+ version: 1,
376
+ kind: "retry",
377
+ ...event.finalError === void 0 ? {} : { failureReason: event.finalError }
378
+ } } }
379
+ });
380
+ break;
381
+ case "agent_start":
382
+ case "agent_end":
383
+ case "turn_start":
384
+ case "turn_end": break;
385
+ }
386
+ } finally {
387
+ events.close();
388
+ }
389
+ }
390
+ function retryToolCallId(logicalModelCallId, attempt) {
391
+ return `sorbet-retry:${logicalModelCallId}:${attempt}`;
392
+ }
393
+ async function projectChildTasks(sessionId$1, parentToolCallId, result, client) {
394
+ if (!Check(ChildToolResultSchema, result) || result.details.action === "list_models") return;
395
+ const snapshots = [
396
+ ...result.details.agent === void 0 ? [] : [result.details.agent],
397
+ ...result.details.agents ?? [],
398
+ ...(result.details.tasks ?? []).flatMap(({ agent }) => agent === void 0 ? [] : [agent])
399
+ ];
400
+ const unique = new Map(snapshots.map((snapshot) => [snapshot.agentId, snapshot]));
401
+ await Promise.all([...unique.values()].map((snapshot) => {
402
+ const status = childTaskStatus(snapshot.state);
403
+ return update(client, sessionId$1, {
404
+ sessionUpdate: "tool_call",
405
+ toolCallId: `sorbet-child:${snapshot.agentId}`,
406
+ title: `Child agent ${snapshot.agentId}`,
407
+ name: "agent",
408
+ kind: "other",
409
+ status,
410
+ _meta: { lody: { task: {
411
+ version: 1,
412
+ taskId: snapshot.agentId,
413
+ kind: "subagent",
414
+ status,
415
+ actor: snapshot.agentId,
416
+ parentToolCallId,
417
+ usage: { totalTokens: snapshot.modelUsage.totalTokens },
418
+ ...snapshot.response === void 0 ? {} : { summary: snapshot.response.text },
419
+ ...FAILED_CHILD_STATES.has(snapshot.state) ? { error: `Child agent ended with state ${snapshot.state}` } : {}
420
+ } } }
421
+ });
422
+ }));
423
+ }
424
+ function childTaskStatus(state) {
425
+ switch (state) {
426
+ case "starting":
427
+ case "running": return "in_progress";
428
+ case "completed":
429
+ case "closed": return "completed";
430
+ case "failed":
431
+ case "cancelled": return "failed";
432
+ }
433
+ }
434
+ async function projectBehaviorSnapshot(sessionId$1, behavior, client, supportsPlanUpdates) {
435
+ const { view, name } = behavior;
436
+ if (view.decision !== void 0 && supportsPlanUpdates) {
437
+ await update(client, sessionId$1, {
438
+ sessionUpdate: "plan_update",
439
+ plan: {
440
+ type: "markdown",
441
+ planId: name,
442
+ content: view.decision.markdown
443
+ }
444
+ });
445
+ return;
446
+ }
447
+ if (view.checklist === void 0) return;
448
+ const entries = view.checklist.map((entry) => ({
449
+ ...entry,
450
+ priority: "medium"
451
+ }));
452
+ if (supportsPlanUpdates) await update(client, sessionId$1, {
453
+ sessionUpdate: "plan_update",
454
+ plan: {
455
+ type: "items",
456
+ planId: name,
457
+ entries
458
+ }
459
+ });
460
+ else await update(client, sessionId$1, {
461
+ sessionUpdate: "plan",
462
+ entries
463
+ });
464
+ }
465
+ async function projectAssistantDelta(sessionId$1, messageId, event, client, tools) {
466
+ switch (event.assistantMessageEvent.type) {
467
+ case "text_delta":
468
+ await update(client, sessionId$1, {
469
+ sessionUpdate: "agent_message_chunk",
470
+ messageId,
471
+ content: {
472
+ type: "text",
473
+ text: event.assistantMessageEvent.delta
474
+ }
475
+ });
476
+ break;
477
+ case "thinking_delta":
478
+ await update(client, sessionId$1, {
479
+ sessionUpdate: "agent_thought_chunk",
480
+ messageId,
481
+ content: {
482
+ type: "text",
483
+ text: event.assistantMessageEvent.delta
484
+ }
485
+ });
486
+ break;
487
+ case "toolcall_end": {
488
+ const call = event.assistantMessageEvent.toolCall;
489
+ await update(client, sessionId$1, {
490
+ sessionUpdate: "tool_call",
491
+ toolCallId: call.id,
492
+ title: toolTitle(call.name, call.arguments, tools),
493
+ name: call.name,
494
+ kind: toolKind$1(call.name),
495
+ status: "pending",
496
+ rawInput: call.arguments,
497
+ locations: locations(call.arguments)
498
+ });
499
+ break;
500
+ }
501
+ case "start":
502
+ case "text_start":
503
+ case "text_end":
504
+ case "thinking_start":
505
+ case "thinking_end":
506
+ case "toolcall_start":
507
+ case "toolcall_delta":
508
+ case "done":
509
+ case "error": break;
510
+ }
511
+ }
512
+ function update(client, sessionId$1, sessionUpdate) {
513
+ return client.notify(acp.methods.client.session.update, {
514
+ sessionId: sessionId$1,
515
+ update: sessionUpdate
516
+ });
517
+ }
518
+ function toolKind$1(name) {
519
+ switch (name) {
520
+ case "read": return "read";
521
+ case "edit":
522
+ case "write": return "edit";
523
+ case "bash": return "execute";
524
+ default: return name.includes("search") ? "search" : "other";
525
+ }
526
+ }
527
+ function locations(parameters) {
528
+ return Check(ToolLocationParametersSchema, parameters) ? [{ path: parameters.path }] : void 0;
529
+ }
530
+
531
+ //#endregion
532
+ //#region src/agent.ts
533
+ const DEFAULT_SESSION_MODE = "default";
534
+ const MODEL_CONFIG_ID = "model";
535
+ const THINKING_LEVEL_CONFIG_ID = "thought_level";
536
+ const PERMISSION_MODE_CONFIG_ID = "permission_mode";
537
+ const SESSION_PAGE_SIZE = 50;
538
+ const ACTIVE_CHILD_STATES = new Set(["starting", "running"]);
539
+ const TERMINAL_CHILD_STATES = new Set([
540
+ "completed",
541
+ "failed",
542
+ "cancelled",
543
+ "closed"
544
+ ]);
545
+ const LODY_EXTENSION_CAPABILITIES = {
546
+ usage: { version: 1 },
547
+ forkAtTurn: { version: 1 },
548
+ steering: {
549
+ version: 1,
550
+ transport: "request",
551
+ upstreamTurn: "same",
552
+ configPolicy: "active"
553
+ },
554
+ goal: {
555
+ version: 1,
556
+ actions: [
557
+ "set",
558
+ "pause",
559
+ "resume",
560
+ "clear"
561
+ ]
562
+ },
563
+ compaction: { version: 1 },
564
+ subagents: {
565
+ version: 1,
566
+ lifecycle: true,
567
+ list: true,
568
+ cancel: true,
569
+ output: true
570
+ },
571
+ sessionHistory: { version: 1 }
572
+ };
573
+ const ProviderParameterErrorCodes = new Set([
574
+ NodeAgentErrorCode.ProviderNotFound,
575
+ NodeAgentErrorCode.ProviderProtocolUnsupported,
576
+ NodeAgentErrorCode.InvalidProviderEndpoint
577
+ ]);
578
+ const contentBlockParser = z.discriminatedUnion("type", [
579
+ z.object({
580
+ type: z.literal("text"),
581
+ text: z.string()
582
+ }).loose(),
583
+ z.object({
584
+ type: z.literal("image"),
585
+ data: z.string(),
586
+ mimeType: z.string()
587
+ }).loose(),
588
+ z.object({
589
+ type: z.literal("audio"),
590
+ data: z.string(),
591
+ mimeType: z.string()
592
+ }).loose(),
593
+ z.object({
594
+ type: z.literal("resource_link"),
595
+ uri: z.string(),
596
+ name: z.string()
597
+ }).loose(),
598
+ z.object({
599
+ type: z.literal("resource"),
600
+ resource: z.union([z.object({
601
+ uri: z.string(),
602
+ text: z.string(),
603
+ mimeType: z.string().nullish()
604
+ }).loose(), z.object({
605
+ uri: z.string(),
606
+ blob: z.string(),
607
+ mimeType: z.string().nullish()
608
+ }).loose()])
609
+ }).loose()
610
+ ]);
611
+ const steeringParser = z.object({
612
+ sessionId: z.string().min(1),
613
+ prompt: z.array(contentBlockParser).min(1)
614
+ });
615
+ const lodySteeringParser = steeringParser.extend({ steerId: z.string().min(1) });
616
+ const lodyGoalParser = z.discriminatedUnion("action", [z.object({
617
+ sessionId: z.string().min(1),
618
+ action: z.literal("set"),
619
+ objective: z.string().min(1).max(2e3)
620
+ }), z.object({
621
+ sessionId: z.string().min(1),
622
+ action: z.enum([
623
+ "pause",
624
+ "resume",
625
+ "clear"
626
+ ])
627
+ })]);
628
+ const lodySessionHistoryParser = z.object({ sessionId: z.string().min(1) });
629
+ const lodySubagentsListParser = z.object({
630
+ sessionId: z.string().min(1),
631
+ activeOnly: z.boolean().optional()
632
+ });
633
+ const lodySubagentCancelParser = z.object({
634
+ sessionId: z.string().min(1),
635
+ taskId: z.string().min(1),
636
+ reason: z.string().min(1).optional()
637
+ });
638
+ const lodySubagentOutputParser = z.object({
639
+ sessionId: z.string().min(1),
640
+ taskId: z.string().min(1),
641
+ tail: z.number().int().min(1).max(1e4).optional()
642
+ });
643
+ const runInspectParser = z.object({
644
+ sessionId: z.string().min(1),
645
+ runId: z.string().min(1)
646
+ });
647
+ const replayParser = z.object({
648
+ sessionId: z.string().min(1),
649
+ after: z.string().min(1).optional()
650
+ });
651
+ const forkAtTurnMetaParser = z.object({ lody: z.object({ forkAtTurn: z.object({
652
+ version: z.literal(1),
653
+ turnId: z.string().min(1).optional()
654
+ }) }).optional() }).loose();
655
+ function createSorbetAcpAgent(options) {
656
+ return { connect: (stream) => {
657
+ const state = {
658
+ capabilities: {},
659
+ sessions: new AcpSessionAttachments(options.agent)
660
+ };
661
+ const connection = buildConnectionApp(options, state).connect(stream);
662
+ const closed = connection.closed.then(() => state.sessions.close(), () => state.sessions.close());
663
+ return {
664
+ client: connection.client,
665
+ signal: connection.signal,
666
+ close: connection.close.bind(connection),
667
+ dispose: () => {
668
+ connection.close();
669
+ return state.sessions.close();
670
+ },
671
+ closed
672
+ };
673
+ } };
674
+ }
675
+ function buildConnectionApp(options, state) {
676
+ return acp.agent({ name: "sorbet-acp" }).onRequest(acp.methods.agent.initialize, async ({ params, signal }) => {
677
+ state.capabilities = params.clientCapabilities ?? {};
678
+ await options.agent.refreshModels({ signal });
679
+ return {
680
+ protocolVersion: acp.PROTOCOL_VERSION,
681
+ agentCapabilities: {
682
+ loadSession: true,
683
+ promptCapabilities: {
684
+ image: true,
685
+ audio: options.audio !== void 0,
686
+ embeddedContext: true
687
+ },
688
+ mcpCapabilities: {
689
+ http: true,
690
+ sse: true
691
+ },
692
+ sessionCapabilities: {
693
+ list: {},
694
+ delete: {},
695
+ additionalDirectories: {},
696
+ resume: {},
697
+ close: {},
698
+ fork: {}
699
+ },
700
+ auth: { logout: {} },
701
+ providers: {},
702
+ _meta: {
703
+ "sorbet.dev": {
704
+ version: SORBET_EXTENSION_VERSION,
705
+ runInspection: true,
706
+ replay: true
707
+ },
708
+ lody: lodyCapabilities(options)
709
+ }
710
+ },
711
+ agentInfo: options.implementation ?? {
712
+ name: "sorbet-acp",
713
+ title: "Sorbet",
714
+ version: SORBET_ACP_VERSION
715
+ },
716
+ authMethods: (await options.authentication?.methods(state.capabilities))?.map(({ method }) => method) ?? [],
717
+ _meta: { steering: { supported: true } }
718
+ };
719
+ }).onRequest(acp.methods.agent.authenticate, async ({ params, client, requestId, signal }) => {
720
+ const selected = (await options.authentication?.methods(state.capabilities) ?? []).find(({ method }) => method.id === params.methodId);
721
+ if (selected === void 0) throw acp.RequestError.invalidParams(params.methodId, "unknown authentication method");
722
+ const elicitation = createV1RequestElicitation(state.capabilities.elicitation, requestId, client);
723
+ if (elicitation === void 0) throw acp.RequestError.invalidRequest(params.methodId, "authentication method requires ACP elicitation support");
724
+ await selected.authenticate({
725
+ elicitation,
726
+ signal
727
+ });
728
+ return {};
729
+ }).onRequest(acp.methods.agent.logout, async ({ signal }) => {
730
+ if (options.authentication !== void 0) await options.authentication.logout(signal);
731
+ else {
732
+ const credentials = await options.agent.listCredentials({ signal });
733
+ await Promise.all(credentials.map(({ providerId }) => options.agent.logout(providerId, { signal })));
734
+ }
735
+ return {};
736
+ }).onRequest(acp.methods.agent.providers.list, async () => ({ providers: (await options.agent.listConfigurableProviders()).map((provider) => ({
737
+ ...provider,
738
+ supported: [...provider.supported]
739
+ })) })).onRequest(acp.methods.agent.providers.set, async ({ params }) => {
740
+ try {
741
+ await options.agent.setProviderEndpoint(params.providerId, {
742
+ apiType: params.apiType,
743
+ baseUrl: params.baseUrl,
744
+ ...params.headers === void 0 ? {} : { headers: params.headers }
745
+ });
746
+ return {};
747
+ } catch (cause) {
748
+ if (cause instanceof NodeAgentError && ProviderParameterErrorCodes.has(cause.code)) throw acp.RequestError.invalidParams(params.providerId, cause.message);
749
+ throw cause;
750
+ }
751
+ }).onRequest(acp.methods.agent.providers.disable, async ({ params }) => {
752
+ await options.agent.disableProviderEndpoint(params.providerId);
753
+ return {};
754
+ }).onRequest(acp.methods.agent.session.new, async ({ params, client, signal }) => state.sessions.run(void 0, async () => {
755
+ const attached = await createSession(options, state, params, client, signal);
756
+ await attached.projection.refresh();
757
+ return sessionResponse(options.agent, attached.session);
758
+ })).onRequest(acp.methods.agent.session.load, async ({ params, client, signal }) => state.sessions.run(params.sessionId, async () => {
759
+ const attached = await loadSession(options, state, params, client, signal);
760
+ await replayConversation(params.sessionId, attached.session, client, attached.bindings.tools, state.capabilities.plan != null);
761
+ await attached.projection.refresh();
762
+ return sessionStateResponse(options.agent, attached.session);
763
+ })).onRequest(acp.methods.agent.session.fork, async ({ params, client, signal }) => state.sessions.run(void 0, async () => {
764
+ const attached = await forkSession(options, state, params, client, signal);
765
+ await attached.projection.refresh();
766
+ return sessionResponse(options.agent, attached.session);
767
+ })).onRequest(acp.methods.agent.session.resume, async ({ params, client, signal }) => state.sessions.run(params.sessionId, async () => {
768
+ const attached = await loadSession(options, state, params, client, signal);
769
+ await attached.projection.refresh();
770
+ return sessionStateResponse(options.agent, attached.session);
771
+ })).onRequest(acp.methods.agent.session.list, async ({ params }) => listSessions(options, params)).onRequest(acp.methods.agent.session.delete, async ({ params }) => state.sessions.run(params.sessionId, async () => {
772
+ await closeAttached(state, params.sessionId);
773
+ await options.agent.deleteSession(params.sessionId);
774
+ return {};
775
+ })).onRequest(acp.methods.agent.session.close, async ({ params }) => state.sessions.run(params.sessionId, async () => {
776
+ await closeAttached(state, params.sessionId);
777
+ return {};
778
+ })).onRequest(acp.methods.agent.session.setMode, async ({ params, client }) => {
779
+ if (params.modeId !== DEFAULT_SESSION_MODE) throw acp.RequestError.invalidParams(params.modeId, "unknown Session mode");
780
+ await update(client, params.sessionId, {
781
+ sessionUpdate: "current_mode_update",
782
+ currentModeId: DEFAULT_SESSION_MODE
783
+ });
784
+ return {};
785
+ }).onRequest(acp.methods.agent.session.setConfigOption, async ({ params, client }) => state.sessions.run(params.sessionId, async () => {
786
+ if (!isString(params.value)) throw acp.RequestError.invalidParams(params.configId, "unknown Session config option");
787
+ const attached = requireAttached(state, params.sessionId);
788
+ if (params.configId === MODEL_CONFIG_ID && params.value === attached.session.modelConfiguration.selector) return sessionConfigStateResponse(options.agent, attached.session);
789
+ if (params.configId === MODEL_CONFIG_ID) {
790
+ const selected = (await listRefreshedModels(options.agent)).find(({ selector }) => selector === params.value);
791
+ if (selected === void 0) throw acp.RequestError.invalidParams(params.value, "unknown model selector");
792
+ const replacement = await options.agent.setSessionModel(params.sessionId, selected.providerId, selected.modelId);
793
+ attached.session = replacement;
794
+ await attached.projection.close();
795
+ attached.projection = startSessionProjection(options.agent, replacement, client);
796
+ } else if (params.configId === THINKING_LEVEL_CONFIG_ID) {
797
+ if (attached.activeRun !== void 0 && params.value !== attached.session.modelConfiguration.thinkingLevel) throw acp.RequestError.invalidRequest(params.sessionId, "Cannot change thinking level while the Session is running");
798
+ const thinkingLevel = attached.session.modelConfiguration.availableThinkingLevels.find((level) => level === params.value);
799
+ if (thinkingLevel === void 0) throw acp.RequestError.invalidParams(params.value, "unsupported thinking level");
800
+ await options.agent.setSessionThinkingLevel(params.sessionId, thinkingLevel);
801
+ } else if (params.configId.startsWith("behavior:")) {
802
+ const name = params.configId.slice(9);
803
+ const entry = (await attached.session.runtime.listBehaviors()).find((item) => item.name === name && item.available);
804
+ if (entry === void 0 || !["on", "off"].includes(Parse(Type.String(), params.value))) throw new Error("Unknown Session behavior setting");
805
+ await attached.session.runtime.commandBehavior(name, {
806
+ name: params.value === "on" ? "enter" : "leave",
807
+ input: null
808
+ }, entry.version);
809
+ } else if (params.configId === PERMISSION_MODE_CONFIG_ID) {
810
+ if (attached.activeRun !== void 0 && params.value !== attached.session.metadata.permissionMode) throw acp.RequestError.invalidRequest(params.sessionId, "Cannot change Permission mode while the Session is running");
811
+ const mode = options.agent.availablePermissionModes.find((candidate) => candidate === params.value);
812
+ if (mode === void 0) throw acp.RequestError.invalidParams(params.value, "unknown Permission mode");
813
+ await options.agent.setSessionPermissionMode(params.sessionId, mode);
814
+ } else throw acp.RequestError.invalidParams(params.configId, "unknown Session config option");
815
+ await attached.projection.refresh();
816
+ const configState = await sessionConfigStateResponse(options.agent, attached.session);
817
+ await update(client, params.sessionId, {
818
+ sessionUpdate: "config_option_update",
819
+ ...configState
820
+ });
821
+ return configState;
822
+ })).onRequest(acp.methods.agent.session.prompt, async ({ params, client, signal }) => {
823
+ const attached = requireAttached(state, params.sessionId);
824
+ if (attached.activeRun !== void 0) throw acp.RequestError.invalidRequest(params.sessionId, "Session already has an active prompt");
825
+ const prompt = await decodePrompt(params.prompt, options.audio, signal);
826
+ const run = await attached.session.start({
827
+ prompt,
828
+ source: {
829
+ kind: "acp.client",
830
+ data: { method: "session/prompt" }
831
+ }
832
+ });
833
+ attached.activeRun = run;
834
+ const work = new AbortController();
835
+ attached.activeWork = work;
836
+ const workSignal = AbortSignal.any([signal, work.signal]);
837
+ let currentRun = run;
838
+ try {
839
+ await publishTurnBoundary(params.sessionId, run.receipt.runId, client);
840
+ const [, outcome] = await Promise.all([projectRun(params.sessionId, run, client, attached.bindings.tools, state.capabilities.plan != null), run.result()]);
841
+ let terminalOutcome = outcome;
842
+ if (outcome.kind === "completed") {
843
+ const implementationRun = await coordinateNodeAgentBehavior({
844
+ session: attached.session,
845
+ requestDecision: (plan, reviewSignal) => requestBehaviorDecision(params.sessionId, plan, client, reviewSignal),
846
+ signal: workSignal
847
+ });
848
+ if (implementationRun !== void 0) {
849
+ currentRun = implementationRun;
850
+ attached.activeRun = implementationRun;
851
+ workSignal.throwIfAborted();
852
+ const configState = await sessionConfigStateResponse(options.agent, attached.session);
853
+ await update(client, params.sessionId, {
854
+ sessionUpdate: "config_option_update",
855
+ ...configState
856
+ });
857
+ const [, implementationOutcome] = await Promise.all([projectRun(params.sessionId, implementationRun, client, attached.bindings.tools, state.capabilities.plan != null), implementationRun.result()]);
858
+ terminalOutcome = implementationOutcome;
859
+ }
860
+ }
861
+ await attached.projection.refresh();
862
+ assertRunSucceeded(terminalOutcome);
863
+ const now = (/* @__PURE__ */ new Date()).toISOString();
864
+ const metadata = await options.agent.updateSession(params.sessionId, {
865
+ updatedAt: now,
866
+ title: attached.session.metadata.title === void 0 ? titleFromPrompt(params.prompt) : void 0,
867
+ titleSource: "fallback"
868
+ });
869
+ await update(client, params.sessionId, {
870
+ sessionUpdate: "session_info_update",
871
+ title: metadata.title ?? null,
872
+ updatedAt: metadata.updatedAt,
873
+ _meta: { lody: { titleSource: lodyTitleSource(metadata) } }
874
+ });
875
+ scheduleSessionTitle(options, attached, client, prompt);
876
+ return { stopReason: await stopReason(attached.session, terminalOutcome.kind) };
877
+ } catch (cause) {
878
+ await currentRun.abort("ACP prompt failed").catch(() => void 0);
879
+ await currentRun.drained();
880
+ throw cause;
881
+ } finally {
882
+ if (attached.activeRun === currentRun) attached.activeRun = void 0;
883
+ if (attached.activeWork === work) attached.activeWork = void 0;
884
+ }
885
+ }).onNotification(acp.methods.agent.session.cancel, async ({ params }) => {
886
+ const attached = state.sessions.get(params.sessionId);
887
+ attached?.activeWork?.abort(/* @__PURE__ */ new Error("ACP Client cancelled the prompt"));
888
+ await attached?.activeRun?.abort("ACP Client cancelled the prompt");
889
+ }).onRequest(SESSION_STEERING_METHOD, steeringParser, async ({ params, client, signal }) => {
890
+ const attached = requireAttached(state, params.sessionId);
891
+ const prompt = await decodePrompt(params.prompt, options.audio, signal);
892
+ const active = attached.activeRun;
893
+ if (active !== void 0) {
894
+ await active.steer(prompt, {
895
+ kind: "acp.client",
896
+ data: { method: "session/steer" }
897
+ });
898
+ return { outcome: "injected" };
899
+ }
900
+ const run = await attached.session.start({
901
+ prompt,
902
+ source: {
903
+ kind: "acp.client",
904
+ data: { method: "session/steer" }
905
+ }
906
+ });
907
+ attached.activeRun = run;
908
+ await publishTurnBoundary(params.sessionId, run.receipt.runId, client);
909
+ Promise.all([projectRun(params.sessionId, run, client, attached.bindings.tools, state.capabilities.plan != null), run.result()]).then(() => {
910
+ scheduleSessionTitle(options, attached, client, prompt);
911
+ }).finally(() => {
912
+ if (attached.activeRun === run) attached.activeRun = void 0;
913
+ });
914
+ return { outcome: "startedNewTurn" };
915
+ }).onRequest(LODY_EXTENSION_METHODS.sessionSteer, lodySteeringParser, async ({ params, client, signal }) => {
916
+ const active = requireAttached(state, params.sessionId).activeRun;
917
+ if (active === void 0) return { outcome: "failed" };
918
+ const prompt = await decodePrompt(params.prompt, options.audio, signal);
919
+ await active.steer(prompt, {
920
+ kind: "acp.client",
921
+ data: {
922
+ method: LODY_EXTENSION_METHODS.sessionSteer,
923
+ steerId: params.steerId
924
+ }
925
+ });
926
+ await client.notify(LODY_EXTENSION_METHODS.sessionSteerApplied, {
927
+ sessionId: params.sessionId,
928
+ steerId: params.steerId
929
+ });
930
+ return { outcome: "injected" };
931
+ }).onRequest(LODY_EXTENSION_METHODS.sessionGoal, lodyGoalParser, async ({ params, client }) => {
932
+ const runtime = requireAttached(state, params.sessionId).session.runtime;
933
+ let goal;
934
+ if (params.action === "set") goal = await runtime.createGoal({ objective: params.objective });
935
+ else if (params.action === "pause") goal = await runtime.pauseGoal();
936
+ else if (params.action === "resume") goal = await runtime.resumeGoal();
937
+ else await runtime.removeGoal();
938
+ const snapshot = lodyGoalSnapshot(goal);
939
+ await update(client, params.sessionId, {
940
+ sessionUpdate: "session_info_update",
941
+ _meta: { lody: { goal: snapshot } }
942
+ });
943
+ return { goal: snapshot };
944
+ }).onRequest(LODY_EXTENSION_METHODS.sessionHistoryRead, lodySessionHistoryParser, async ({ params, client }) => {
945
+ const attached = requireAttached(state, params.sessionId);
946
+ await replayConversation(params.sessionId, attached.session, client, attached.bindings.tools, state.capabilities.plan != null);
947
+ return {};
948
+ }).onRequest(LODY_EXTENSION_METHODS.subagentsList, lodySubagentsListParser, async ({ params }) => {
949
+ requireAttached(state, params.sessionId);
950
+ const [children, sessions] = await Promise.all([options.agent.listChildAgents(params.sessionId, { includeClosed: params.activeOnly !== true }), options.agent.listSessions()]);
951
+ const metadata = new Map(sessions.map((session) => [session.sessionId, session]));
952
+ return { tasks: (params.activeOnly === true ? children.agents.filter(({ state: childState }) => ACTIVE_CHILD_STATES.has(childState)) : children.agents).map((child) => lodySubagentTask(child, metadata.get(child.childSessionId))) };
953
+ }).onRequest(LODY_EXTENSION_METHODS.subagentsCancel, lodySubagentCancelParser, async ({ params, signal }) => {
954
+ requireAttached(state, params.sessionId);
955
+ await options.agent.closeChildAgent(params.sessionId, params.taskId, {
956
+ signal,
957
+ reason: params.reason
958
+ });
959
+ return {};
960
+ }).onRequest(LODY_EXTENSION_METHODS.subagentsOutput, lodySubagentOutputParser, async ({ params }) => {
961
+ requireAttached(state, params.sessionId);
962
+ const child = (await options.agent.listChildAgents(params.sessionId)).agents.find(({ agentId }) => agentId === params.taskId);
963
+ if (child === void 0) throw acp.RequestError.resourceNotFound(params.taskId);
964
+ const output = child.response?.text ?? "";
965
+ return { output: params.tail === void 0 ? output : output.split("\n").slice(-params.tail).join("\n") };
966
+ }).onRequest(SORBET_RUN_INSPECT_METHOD, runInspectParser, async ({ params }) => {
967
+ return {
968
+ version: SORBET_EXTENSION_VERSION,
969
+ run: await requireAttached(state, params.sessionId).session.runtime.snapshot(params.runId)
970
+ };
971
+ }).onRequest(SORBET_REPLAY_METHOD, replayParser, async ({ params }) => {
972
+ const attached = requireAttached(state, params.sessionId);
973
+ const after = params.after === void 0 ? void 0 : Parse(JournalCursorSchema, params.after);
974
+ return {
975
+ version: SORBET_EXTENSION_VERSION,
976
+ facts: (await attached.session.runtime.readFacts({
977
+ limit: 100,
978
+ after
979
+ })).facts.map((fact) => {
980
+ let owner;
981
+ switch (fact.kind) {
982
+ case "session.forked":
983
+ case "model.request.base.committed":
984
+ case "goal.created":
985
+ case "goal.status.changed":
986
+ case "goal.removed":
987
+ case "session.behavior.changed":
988
+ case "permission.grant.revoked":
989
+ case "compaction.requested":
990
+ case "compaction.model.requested":
991
+ case "compaction.model.response.committed":
992
+ case "compaction.model.failed":
993
+ case "compaction.committed":
994
+ case "compaction.failed":
995
+ case "compaction.skipped":
996
+ owner = { operationId: fact.operationId };
997
+ break;
998
+ default: owner = { runId: fact.runId };
999
+ }
1000
+ return {
1001
+ id: fact.id,
1002
+ ...owner,
1003
+ sequence: fact.sequence,
1004
+ cursor: fact.cursor,
1005
+ recordedAt: fact.recordedAt,
1006
+ kind: fact.kind
1007
+ };
1008
+ })
1009
+ };
1010
+ });
1011
+ }
1012
+ async function forkSession(options, state, params, client, signal) {
1013
+ await options.agent.refreshModels({ signal });
1014
+ const mcp = await connectMcpServers(params.mcpServers ?? [], signal);
1015
+ const identity = {};
1016
+ const tools = [...mcp.tools, ...createAcpClientTools(state.capabilities, identity, client)];
1017
+ const elicitation = createV1SessionElicitation(state.capabilities.elicitation, identity, client);
1018
+ const bindings = bindingsFor(options.agent, identity, client, tools, elicitation);
1019
+ try {
1020
+ const session = await options.agent.forkSession(params.sessionId, {
1021
+ workspace: {
1022
+ root: params.cwd,
1023
+ additionalDirectories: params.additionalDirectories
1024
+ },
1025
+ ...forkAtTurnInput(params["_meta"])
1026
+ }, bindings);
1027
+ identity.sessionId = session.metadata.sessionId;
1028
+ const attached = {
1029
+ session,
1030
+ bindings,
1031
+ mcp,
1032
+ projection: startSessionProjection(options.agent, session, client)
1033
+ };
1034
+ state.sessions.attach(attached);
1035
+ for (const warning of mcp.warnings) await update(client, session.metadata.sessionId, warning);
1036
+ return attached;
1037
+ } catch (cause) {
1038
+ if (cause instanceof NodeAgentError) switch (cause.code) {
1039
+ case NodeAgentErrorCode.SessionForkRejected:
1040
+ case NodeAgentErrorCode.SessionNotFound: return state.sessions.rejectOpen(identity.sessionId, mcp, acp.RequestError.invalidRequest(params.sessionId, cause.message));
1041
+ }
1042
+ return state.sessions.rejectOpen(identity.sessionId, mcp, sessionRequestError(cause, identity.sessionId));
1043
+ }
1044
+ }
1045
+ async function createSession(options, state, params, client, signal) {
1046
+ const model = await defaultModel(options);
1047
+ const mcp = await connectMcpServers(params.mcpServers, signal);
1048
+ const identity = {};
1049
+ const tools = [...mcp.tools, ...createAcpClientTools(state.capabilities, identity, client)];
1050
+ const elicitation = createV1SessionElicitation(state.capabilities.elicitation, identity, client);
1051
+ const bindings = bindingsFor(options.agent, identity, client, tools, elicitation);
1052
+ try {
1053
+ const session = await options.agent.createSession({
1054
+ providerId: model.providerId,
1055
+ modelId: model.modelId,
1056
+ workspace: {
1057
+ root: params.cwd,
1058
+ additionalDirectories: params.additionalDirectories
1059
+ }
1060
+ }, bindings);
1061
+ identity.sessionId = session.metadata.sessionId;
1062
+ const attached = {
1063
+ session,
1064
+ bindings,
1065
+ mcp,
1066
+ projection: startSessionProjection(options.agent, session, client)
1067
+ };
1068
+ state.sessions.attach(attached);
1069
+ for (const warning of mcp.warnings) await update(client, session.metadata.sessionId, warning);
1070
+ return attached;
1071
+ } catch (cause) {
1072
+ return state.sessions.rejectOpen(identity.sessionId, mcp, sessionRequestError(cause, identity.sessionId));
1073
+ }
1074
+ }
1075
+ async function loadSession(options, state, params, client, signal) {
1076
+ await closeAttached(state, params.sessionId);
1077
+ await options.agent.refreshModels({ signal });
1078
+ const mcp = await connectMcpServers(params.mcpServers ?? [], signal);
1079
+ const identity = { sessionId: params.sessionId };
1080
+ const tools = [...mcp.tools, ...createAcpClientTools(state.capabilities, identity, client)];
1081
+ const elicitation = createV1SessionElicitation(state.capabilities.elicitation, identity, client);
1082
+ const bindings = bindingsFor(options.agent, identity, client, tools, elicitation);
1083
+ let session;
1084
+ try {
1085
+ session = await options.agent.loadSession(params.sessionId, bindings);
1086
+ const attached = {
1087
+ session,
1088
+ bindings,
1089
+ mcp,
1090
+ projection: startSessionProjection(options.agent, session, client)
1091
+ };
1092
+ state.sessions.attach(attached);
1093
+ const workspace = session.metadata.workspace;
1094
+ if (workspace === void 0 || workspace.root !== params.cwd) throw acp.RequestError.invalidParams(params.cwd, "Session belongs to a different cwd");
1095
+ const requestedAdditional = params.additionalDirectories ?? [];
1096
+ if (!isEqual(workspace.additionalDirectories ?? [], requestedAdditional)) {
1097
+ session = await options.agent.setSessionWorkspace(params.sessionId, {
1098
+ root: params.cwd,
1099
+ additionalDirectories: requestedAdditional
1100
+ });
1101
+ attached.session = session;
1102
+ await attached.projection.close();
1103
+ attached.projection = startSessionProjection(options.agent, session, client);
1104
+ }
1105
+ for (const warning of mcp.warnings) await update(client, session.metadata.sessionId, warning);
1106
+ return attached;
1107
+ } catch (cause) {
1108
+ return state.sessions.rejectOpen(params.sessionId, mcp, sessionRequestError(cause, params.sessionId));
1109
+ }
1110
+ }
1111
+ function bindingsFor(agent, identity, client, tools, elicitation) {
1112
+ return {
1113
+ approvals: { resolve: async (request, signal) => {
1114
+ const sessionId$1 = identity.sessionId;
1115
+ if (sessionId$1 === void 0) throw new Error("ACP Session identity is not available");
1116
+ const response = await client.request(acp.methods.client.session.requestPermission, {
1117
+ sessionId: sessionId$1,
1118
+ toolCall: {
1119
+ toolCallId: request.toolCallId,
1120
+ title: toolTitle(request.toolName, request.parameters, tools),
1121
+ name: request.toolName,
1122
+ kind: toolKind(request.toolName),
1123
+ status: "pending",
1124
+ rawInput: request.parameters
1125
+ },
1126
+ options: [
1127
+ {
1128
+ optionId: "allow_once",
1129
+ name: "Allow once",
1130
+ kind: "allow_once"
1131
+ },
1132
+ {
1133
+ optionId: "allow_always",
1134
+ name: "Allow exact action for Session",
1135
+ kind: "allow_always"
1136
+ },
1137
+ {
1138
+ optionId: "reject_once",
1139
+ name: "Reject",
1140
+ kind: "reject_once"
1141
+ }
1142
+ ]
1143
+ }, { cancellationSignal: signal });
1144
+ if (response.outcome.outcome === "selected") {
1145
+ if (response.outcome.optionId === "allow_once") return { outcome: "allowed-once" };
1146
+ if (response.outcome.optionId === "allow_always") return {
1147
+ outcome: "allowed-once",
1148
+ remember: "session"
1149
+ };
1150
+ }
1151
+ return {
1152
+ outcome: "rejected",
1153
+ reason: "ACP Client denied the Tool call"
1154
+ };
1155
+ } },
1156
+ tools,
1157
+ ...elicitation === void 0 ? {} : { elicitation }
1158
+ };
1159
+ }
1160
+ async function requestBehaviorDecision(sessionId$1, request, client, signal) {
1161
+ const toolCall = {
1162
+ toolCallId: request.id,
1163
+ name: "session_decision",
1164
+ title: request.title,
1165
+ kind: "switch_mode",
1166
+ status: "pending",
1167
+ rawInput: { markdown: request.markdown }
1168
+ };
1169
+ const response = Parse(Type.Object({ outcome: Type.Union([Type.Object({
1170
+ outcome: Type.Literal("selected"),
1171
+ optionId: Type.String()
1172
+ }), Type.Object({ outcome: Type.Literal("cancelled") })]) }), await client.request(acp.methods.client.session.requestPermission, {
1173
+ sessionId: sessionId$1,
1174
+ toolCall,
1175
+ options: request.choices.map((choice) => ({
1176
+ optionId: choice.id,
1177
+ name: choice.title,
1178
+ kind: "allow_once"
1179
+ }))
1180
+ }, { cancellationSignal: signal }));
1181
+ return response.outcome.outcome === "selected" ? response.outcome.optionId : void 0;
1182
+ }
1183
+ async function defaultModel(options) {
1184
+ const models = await listRefreshedModels(options.agent);
1185
+ let selected = models[0];
1186
+ if (options.defaultModel !== void 0) selected = models.find(({ selector }) => selector === options.defaultModel);
1187
+ if (selected === void 0) throw acp.RequestError.authRequired(void 0, "no model is available");
1188
+ return selected;
1189
+ }
1190
+ async function sessionResponse(agent, session) {
1191
+ return {
1192
+ sessionId: session.metadata.sessionId,
1193
+ ...await sessionStateResponse(agent, session)
1194
+ };
1195
+ }
1196
+ async function sessionStateResponse(agent, session) {
1197
+ return {
1198
+ modes: sessionModes(),
1199
+ ...await sessionConfigStateResponse(agent, session)
1200
+ };
1201
+ }
1202
+ async function sessionConfigStateResponse(agent, session) {
1203
+ const models = await listRefreshedModels(agent);
1204
+ const current = session.modelConfiguration;
1205
+ return {
1206
+ configOptions: await sessionConfigOptions(agent, session, current, models),
1207
+ _meta: { lody: { modelConfigOptions: modelConfigOptions(agent, models, current) } }
1208
+ };
1209
+ }
1210
+ function sessionModes() {
1211
+ return {
1212
+ currentModeId: DEFAULT_SESSION_MODE,
1213
+ availableModes: [{
1214
+ id: DEFAULT_SESSION_MODE,
1215
+ name: "Default"
1216
+ }]
1217
+ };
1218
+ }
1219
+ async function sessionConfigOptions(agent, session, current, availableModels) {
1220
+ const selectableModels = modelsIncludingCurrent(availableModels, current);
1221
+ const thinkingLevels = current.availableThinkingLevels;
1222
+ return [
1223
+ ...(await session.runtime.listBehaviors()).filter((entry) => entry.available).map((entry) => ({
1224
+ id: `behavior:${entry.name}`,
1225
+ name: entry.title,
1226
+ type: "select",
1227
+ currentValue: entry.view.active ? "on" : "off",
1228
+ options: [{
1229
+ value: "on",
1230
+ name: "On"
1231
+ }, {
1232
+ value: "off",
1233
+ name: "Off"
1234
+ }]
1235
+ })),
1236
+ {
1237
+ id: MODEL_CONFIG_ID,
1238
+ name: "Model",
1239
+ category: "model",
1240
+ type: "select",
1241
+ currentValue: current.selector,
1242
+ options: selectableModels.map(({ selector, providerId, modelId, displayName }) => ({
1243
+ value: selector,
1244
+ name: `${agent.models.getProvider(providerId)?.name ?? providerId}/${modelId}`,
1245
+ description: displayName
1246
+ }))
1247
+ },
1248
+ ...thinkingLevels.length > 1 ? [{
1249
+ id: THINKING_LEVEL_CONFIG_ID,
1250
+ name: "Thinking level",
1251
+ category: "thought_level",
1252
+ type: "select",
1253
+ currentValue: current.thinkingLevel,
1254
+ options: thinkingLevels.map((level) => ({
1255
+ value: level,
1256
+ name: level
1257
+ }))
1258
+ }] : [],
1259
+ permissionModeConfigOption(agent, session)
1260
+ ];
1261
+ }
1262
+ function permissionModeConfigOption(agent, session) {
1263
+ return {
1264
+ id: PERMISSION_MODE_CONFIG_ID,
1265
+ name: "Permission Mode",
1266
+ category: "_permission",
1267
+ type: "select",
1268
+ currentValue: session.metadata.permissionMode,
1269
+ options: agent.availablePermissionModes.map((value) => ({
1270
+ value,
1271
+ name: permissionModeName(value)
1272
+ }))
1273
+ };
1274
+ }
1275
+ function permissionModeName(mode) {
1276
+ return {
1277
+ ask: "Ask",
1278
+ auto: "Automatic review",
1279
+ yolo: "YOLO",
1280
+ "full-access": "Full access"
1281
+ }[mode];
1282
+ }
1283
+ async function listSessions(options, params) {
1284
+ const pageSize = options.sessionPageSize ?? SESSION_PAGE_SIZE;
1285
+ const offset = decodeCursor(params.cursor);
1286
+ const sessions = (await options.agent.listSessions()).filter(({ depth, workspace }) => depth === 0 && workspace !== void 0).filter(({ workspace }) => isNil(params.cwd) || workspace?.root === params.cwd).sort((left, right) => (right.updatedAt ?? right.createdAt).localeCompare(left.updatedAt ?? left.createdAt));
1287
+ const page = sessions.slice(offset, offset + pageSize);
1288
+ const next = offset + page.length;
1289
+ return {
1290
+ sessions: page.map((session) => ({
1291
+ sessionId: session.sessionId,
1292
+ cwd: session.workspace?.root ?? "",
1293
+ additionalDirectories: session.workspace?.additionalDirectories,
1294
+ title: session.title,
1295
+ updatedAt: session.updatedAt ?? session.createdAt
1296
+ })),
1297
+ ...next < sessions.length ? { nextCursor: Buffer.from(String(next), "utf8").toString("base64url") } : {}
1298
+ };
1299
+ }
1300
+ function decodeCursor(cursor) {
1301
+ if (isNil(cursor)) return 0;
1302
+ try {
1303
+ const decoded = Buffer.from(cursor, "base64url").toString("utf8");
1304
+ const offset = Number.parseInt(decoded, 10);
1305
+ if (!Number.isSafeInteger(offset) || offset < 0 || String(offset) !== decoded) throw new Error();
1306
+ return offset;
1307
+ } catch {
1308
+ throw acp.RequestError.invalidParams(cursor, "invalid Session list cursor");
1309
+ }
1310
+ }
1311
+ async function replayConversation(sessionId$1, session, client, tools, supportsPlanUpdates) {
1312
+ const entries = await session.runtime.conversationEntries();
1313
+ for (const entry of entries) await replayEntry(sessionId$1, entry, client, tools);
1314
+ for (const behavior of await session.runtime.listBehaviors()) await projectBehaviorSnapshot(sessionId$1, behavior, client, supportsPlanUpdates);
1315
+ }
1316
+ async function replayEntry(sessionId$1, entry, client, tools) {
1317
+ const message = entry.message;
1318
+ if (message.role === "user") {
1319
+ const blocks = isString(message.content) ? [{
1320
+ type: "text",
1321
+ text: message.content
1322
+ }] : message.content;
1323
+ for (const content of blocks) await update(client, sessionId$1, {
1324
+ sessionUpdate: "user_message_chunk",
1325
+ messageId: entry.messageId,
1326
+ content
1327
+ });
1328
+ return;
1329
+ }
1330
+ if (message.role === "assistant") {
1331
+ for (const content of message.content) switch (content.type) {
1332
+ case "text":
1333
+ await update(client, sessionId$1, {
1334
+ sessionUpdate: "agent_message_chunk",
1335
+ messageId: entry.messageId,
1336
+ content: {
1337
+ type: "text",
1338
+ text: content.text
1339
+ }
1340
+ });
1341
+ break;
1342
+ case "thinking":
1343
+ await update(client, sessionId$1, {
1344
+ sessionUpdate: "agent_thought_chunk",
1345
+ messageId: entry.messageId,
1346
+ content: {
1347
+ type: "text",
1348
+ text: content.thinking
1349
+ }
1350
+ });
1351
+ break;
1352
+ case "toolCall":
1353
+ await update(client, sessionId$1, {
1354
+ sessionUpdate: "tool_call",
1355
+ toolCallId: content.id,
1356
+ title: toolTitle(content.name, content.arguments, tools),
1357
+ name: content.name,
1358
+ kind: toolKind(content.name),
1359
+ status: "pending",
1360
+ rawInput: content.arguments
1361
+ });
1362
+ break;
1363
+ }
1364
+ return;
1365
+ }
1366
+ await update(client, sessionId$1, {
1367
+ sessionUpdate: "tool_call_update",
1368
+ toolCallId: message.toolCallId,
1369
+ status: message.isError ? "failed" : "completed",
1370
+ content: message.content.map((content) => ({
1371
+ type: "content",
1372
+ content
1373
+ })),
1374
+ rawOutput: message.details
1375
+ });
1376
+ }
1377
+ function startSessionProjection(agent, session, client) {
1378
+ let closed = false;
1379
+ let subscription;
1380
+ const usage = observeSessionUsage(session.runtime, async (snapshot) => {
1381
+ const context = contextUsageUpdate(snapshot);
1382
+ if (context !== void 0) await update(client, session.metadata.sessionId, context);
1383
+ if (snapshot.models.length === 0) return;
1384
+ await client.notify(LODY_EXTENSION_METHODS.sessionUsageUpdate, detailedUsageUpdate(session.metadata.sessionId, snapshot, agent));
1385
+ });
1386
+ const compactionStartedAt = /* @__PURE__ */ new Map();
1387
+ const task = (async () => {
1388
+ const { cursor } = await session.runtime.getUsage();
1389
+ if (closed) return;
1390
+ await publishGoal(session, client);
1391
+ subscription = session.runtime.facts(cursor === void 0 ? {} : { after: cursor });
1392
+ if (closed) {
1393
+ subscription.close();
1394
+ return;
1395
+ }
1396
+ for await (const fact of subscription) {
1397
+ if (closed) return;
1398
+ if (factAffectsGoal(fact)) await publishGoal(session, client);
1399
+ await projectCompaction(session.metadata.sessionId, fact, compactionStartedAt, client);
1400
+ }
1401
+ })().catch(() => void 0);
1402
+ return {
1403
+ refresh: usage.refresh,
1404
+ close: async () => {
1405
+ closed = true;
1406
+ subscription?.close();
1407
+ await Promise.all([task, usage.close()]);
1408
+ }
1409
+ };
1410
+ }
1411
+ function publishTurnBoundary(sessionId$1, runId, client) {
1412
+ return update(client, sessionId$1, {
1413
+ sessionUpdate: "session_info_update",
1414
+ _meta: { lody: { turnId: runId } }
1415
+ });
1416
+ }
1417
+ function forkAtTurnInput(metadata) {
1418
+ const parsed = forkAtTurnMetaParser.safeParse(metadata);
1419
+ const turnId = parsed.success ? parsed.data.lody?.forkAtTurn.turnId : void 0;
1420
+ return turnId === void 0 ? {} : { sourceRunId: turnId };
1421
+ }
1422
+ function lodySubagentTask(child, metadata) {
1423
+ const terminal = TERMINAL_CHILD_STATES.has(child.state);
1424
+ const status = lodySubagentStatus(child.state);
1425
+ const childStopReason = lodySubagentStopReason(child);
1426
+ const startedAt = Date.parse(metadata?.createdAt ?? "");
1427
+ const endedAt = Date.parse(child.outcome?.recordedAt ?? metadata?.updatedAt ?? "");
1428
+ return {
1429
+ taskId: child.agentId,
1430
+ description: metadata?.title ?? `Child agent ${child.agentId}`,
1431
+ status,
1432
+ agentId: child.agentId,
1433
+ ...metadata?.modelId === void 0 ? {} : { modelId: metadata.modelId },
1434
+ ...metadata?.thinkingLevel === void 0 ? {} : { thinkingEffort: metadata.thinkingLevel },
1435
+ startedAtEpochSeconds: Number.isFinite(startedAt) ? startedAt / 1e3 : 0,
1436
+ endedAtEpochSeconds: terminal && Number.isFinite(endedAt) ? endedAt / 1e3 : null,
1437
+ ...childStopReason === void 0 ? {} : { stopReason: childStopReason }
1438
+ };
1439
+ }
1440
+ function lodySubagentStatus(state) {
1441
+ switch (state) {
1442
+ case "starting":
1443
+ case "running": return "running";
1444
+ case "cancelled":
1445
+ case "closed": return "killed";
1446
+ case "completed":
1447
+ case "failed": return state;
1448
+ }
1449
+ }
1450
+ function lodySubagentStopReason(child) {
1451
+ if (child.outcome?.kind === "failed") return child.outcome.error.message;
1452
+ if (child.outcome?.kind === "cancelled") return child.outcome.reason;
1453
+ }
1454
+ function factAffectsGoal(fact) {
1455
+ switch (fact.kind) {
1456
+ case "goal.created":
1457
+ case "goal.status.changed":
1458
+ case "goal.removed":
1459
+ case "model.response.committed": return true;
1460
+ default: return false;
1461
+ }
1462
+ }
1463
+ async function publishGoal(session, client) {
1464
+ const goal = await session.runtime.getGoal();
1465
+ await update(client, session.metadata.sessionId, {
1466
+ sessionUpdate: "session_info_update",
1467
+ _meta: { lody: { goal: lodyGoalSnapshot(goal) } }
1468
+ });
1469
+ }
1470
+ function lodyGoalSnapshot(goal) {
1471
+ if (goal === void 0) return null;
1472
+ return {
1473
+ objective: goal.objective,
1474
+ status: goal.status,
1475
+ tokensUsed: goal.usedTokens,
1476
+ tokenBudget: goal.maxTokenBudget ?? null
1477
+ };
1478
+ }
1479
+ async function projectCompaction(sessionId$1, fact, startedAt, client) {
1480
+ switch (fact.kind) {
1481
+ case "compaction.requested": {
1482
+ startedAt.set(fact.operationId, Date.parse(fact.recordedAt));
1483
+ const activity$1 = {
1484
+ version: 1,
1485
+ kind: "context_compaction",
1486
+ automatic: fact.payload.reason !== "manual",
1487
+ usedTokensBefore: fact.payload.contextTokensBefore
1488
+ };
1489
+ await update(client, sessionId$1, {
1490
+ sessionUpdate: "tool_call",
1491
+ toolCallId: compactionToolCallId(fact.operationId),
1492
+ title: "Context compaction",
1493
+ kind: "other",
1494
+ status: "in_progress",
1495
+ _meta: { lody: { activity: activity$1 } }
1496
+ });
1497
+ return;
1498
+ }
1499
+ case "compaction.committed":
1500
+ case "compaction.failed": break;
1501
+ default: return;
1502
+ }
1503
+ const started = startedAt.get(fact.operationId);
1504
+ startedAt.delete(fact.operationId);
1505
+ const failureReason = fact.kind === "compaction.failed" ? fact.payload.message : void 0;
1506
+ const activity = {
1507
+ version: 1,
1508
+ kind: "context_compaction",
1509
+ ...fact.kind === "compaction.committed" ? {
1510
+ usedTokensBefore: fact.payload.contextTokensBefore,
1511
+ usedTokensAfter: fact.payload.projectedContextTokensAfter
1512
+ } : {},
1513
+ ...started === void 0 ? {} : { durationMs: Math.max(0, Date.parse(fact.recordedAt) - started) },
1514
+ ...failureReason === void 0 ? {} : { failureReason }
1515
+ };
1516
+ await update(client, sessionId$1, {
1517
+ sessionUpdate: "tool_call_update",
1518
+ toolCallId: compactionToolCallId(fact.operationId),
1519
+ status: fact.kind === "compaction.committed" ? "completed" : "failed",
1520
+ _meta: { lody: { activity } }
1521
+ });
1522
+ }
1523
+ function compactionToolCallId(operationId) {
1524
+ return `sorbet-compaction:${operationId}`;
1525
+ }
1526
+ function requireAttached(state, sessionId$1) {
1527
+ const attached = state.sessions.get(sessionId$1);
1528
+ if (attached === void 0) throw acp.RequestError.resourceNotFound(sessionId$1);
1529
+ return attached;
1530
+ }
1531
+ async function closeAttached(state, sessionId$1) {
1532
+ try {
1533
+ await state.sessions.closeSession(sessionId$1);
1534
+ } catch (cause) {
1535
+ throw sessionRequestError(cause, sessionId$1);
1536
+ }
1537
+ }
1538
+ function assertRunSucceeded(outcome) {
1539
+ if (outcome.kind !== "failed") return;
1540
+ throw acp.RequestError.internalError({
1541
+ code: outcome.error.code,
1542
+ message: outcome.error.message
1543
+ }, `Sorbet Run failed with ${outcome.error.code}`);
1544
+ }
1545
+ async function stopReason(session, outcome) {
1546
+ if (outcome === "cancelled") return "cancelled";
1547
+ if (outcome === "failed") return "refusal";
1548
+ const last = (await session.runtime.conversation()).at(-1);
1549
+ return last?.role === "assistant" && last.stopReason === "length" ? "max_tokens" : "end_turn";
1550
+ }
1551
+ function titleFromPrompt(prompt) {
1552
+ const text = prompt.find((block) => block.type === "text");
1553
+ if (text?.type !== "text") return;
1554
+ const normalized = text.text.trim().replaceAll(/\s+/g, " ");
1555
+ return normalized.length === 0 ? void 0 : normalized.slice(0, 80);
1556
+ }
1557
+ function lodyCapabilities(options) {
1558
+ const capabilities = { ...LODY_EXTENSION_CAPABILITIES };
1559
+ if (options.sessionTitle !== false) capabilities.sessionTitle = { version: 1 };
1560
+ return capabilities;
1561
+ }
1562
+ function scheduleSessionTitle(options, attached, client, prompt) {
1563
+ if (options.sessionTitle === false) return;
1564
+ const sessionId$1 = attached.session.metadata.sessionId;
1565
+ if (isAuthoritativeSessionTitleSource(attached.session.metadata.titleSource) || attached.titleAttempted === true || attached.titleTask !== void 0) return;
1566
+ attached.titleAttempted = true;
1567
+ const abort = new AbortController();
1568
+ attached.titleAbort = abort;
1569
+ attached.titleTask = (async () => {
1570
+ try {
1571
+ const metadata = await options.agent.generateSessionTitle(sessionId$1, {
1572
+ prompt,
1573
+ signal: abort.signal
1574
+ });
1575
+ if (metadata === void 0) return;
1576
+ await update(client, sessionId$1, {
1577
+ sessionUpdate: "session_info_update",
1578
+ title: metadata.title ?? null,
1579
+ updatedAt: metadata.updatedAt,
1580
+ _meta: { lody: { titleSource: "generated" } }
1581
+ });
1582
+ } catch {} finally {
1583
+ attached.titleTask = void 0;
1584
+ if (attached.titleAbort === abort) attached.titleAbort = void 0;
1585
+ }
1586
+ })();
1587
+ }
1588
+ function toolKind(name) {
1589
+ switch (name) {
1590
+ case "read": return "read";
1591
+ case "edit":
1592
+ case "write": return "edit";
1593
+ case "bash": return "execute";
1594
+ default: return "other";
1595
+ }
1596
+ }
1597
+
1598
+ //#endregion
1599
+ export { createSorbetAcpAgent as t };
1600
+ //# sourceMappingURL=agent-B7PnGaB0.js.map