@lobehub/cli 0.0.215 → 0.0.217

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 (3) hide show
  1. package/dist/index.js +1138 -1199
  2. package/man/man1/lh.1 +1 -1
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import { Buffer as Buffer$1 } from "node:buffer";
15
15
  import * as net$1 from "node:net";
16
16
  import net, { BlockList, connect, createServer, isIP } from "node:net";
17
17
  import { scheduler, setImmediate as setImmediate$1, setTimeout as setTimeout$1 } from "node:timers/promises";
18
- import _w, { cwd, execArgv, execPath, hrtime, platform as platform$1 } from "node:process";
18
+ import process$1, { cwd, execArgv, execPath, hrtime, platform as platform$1 } from "node:process";
19
19
  import { URL as URL$1, fileURLToPath, pathToFileURL } from "node:url";
20
20
  import { finished, pipeline } from "node:stream/promises";
21
21
  import { Duplex, PassThrough, Readable, Transform, Writable, getDefaultHighWaterMark, pipeline as pipeline$1 } from "node:stream";
@@ -24433,7 +24433,7 @@ var require_command = /* @__PURE__ */ __commonJSMin$2(((exports) => {
24433
24433
  const childProcess$2 = __require("node:child_process");
24434
24434
  const path$16 = __require("node:path");
24435
24435
  const fs$17 = __require("node:fs");
24436
- const process$2 = __require("node:process");
24436
+ const process$3 = __require("node:process");
24437
24437
  const { Argument, humanReadableArgName } = require_argument();
24438
24438
  const { CommanderError } = require_error$1();
24439
24439
  const { Help, stripColor } = require_help();
@@ -24485,13 +24485,13 @@ var require_command = /* @__PURE__ */ __commonJSMin$2(((exports) => {
24485
24485
  this._showSuggestionAfterError = true;
24486
24486
  this._savedState = null;
24487
24487
  this._outputConfiguration = {
24488
- writeOut: (str) => process$2.stdout.write(str),
24489
- writeErr: (str) => process$2.stderr.write(str),
24488
+ writeOut: (str) => process$3.stdout.write(str),
24489
+ writeErr: (str) => process$3.stderr.write(str),
24490
24490
  outputError: (str, write) => write(str),
24491
- getOutHelpWidth: () => process$2.stdout.isTTY ? process$2.stdout.columns : void 0,
24492
- getErrHelpWidth: () => process$2.stderr.isTTY ? process$2.stderr.columns : void 0,
24493
- getOutHasColors: () => useColor() ?? (process$2.stdout.isTTY && process$2.stdout.hasColors?.()),
24494
- getErrHasColors: () => useColor() ?? (process$2.stderr.isTTY && process$2.stderr.hasColors?.()),
24491
+ getOutHelpWidth: () => process$3.stdout.isTTY ? process$3.stdout.columns : void 0,
24492
+ getErrHelpWidth: () => process$3.stderr.isTTY ? process$3.stderr.columns : void 0,
24493
+ getOutHasColors: () => useColor() ?? (process$3.stdout.isTTY && process$3.stdout.hasColors?.()),
24494
+ getErrHasColors: () => useColor() ?? (process$3.stderr.isTTY && process$3.stderr.hasColors?.()),
24495
24495
  stripColor: (str) => stripColor(str)
24496
24496
  };
24497
24497
  this._hidden = false;
@@ -24849,7 +24849,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
24849
24849
  */
24850
24850
  _exit(exitCode, code, message) {
24851
24851
  if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
24852
- process$2.exit(exitCode);
24852
+ process$3.exit(exitCode);
24853
24853
  }
24854
24854
  /**
24855
24855
  * Register callback `fn` for the command.
@@ -25188,11 +25188,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
25188
25188
  if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
25189
25189
  parseOptions = parseOptions || {};
25190
25190
  if (argv === void 0 && parseOptions.from === void 0) {
25191
- if (process$2.versions?.electron) parseOptions.from = "electron";
25192
- const execArgv = process$2.execArgv ?? [];
25191
+ if (process$3.versions?.electron) parseOptions.from = "electron";
25192
+ const execArgv = process$3.execArgv ?? [];
25193
25193
  if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
25194
25194
  }
25195
- if (argv === void 0) argv = process$2.argv;
25195
+ if (argv === void 0) argv = process$3.argv;
25196
25196
  this.rawArgs = argv.slice();
25197
25197
  let userArgs;
25198
25198
  switch (parseOptions.from) {
@@ -25202,7 +25202,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
25202
25202
  userArgs = argv.slice(2);
25203
25203
  break;
25204
25204
  case "electron":
25205
- if (process$2.defaultApp) {
25205
+ if (process$3.defaultApp) {
25206
25206
  this._scriptPath = argv[1];
25207
25207
  userArgs = argv.slice(2);
25208
25208
  } else userArgs = argv.slice(1);
@@ -25367,16 +25367,16 @@ Expecting one of '${allowedValues.join("', '")}'`);
25367
25367
  }
25368
25368
  launchWithNode = sourceExt.includes(path$16.extname(executableFile));
25369
25369
  let proc;
25370
- if (process$2.platform !== "win32") if (launchWithNode) {
25370
+ if (process$3.platform !== "win32") if (launchWithNode) {
25371
25371
  args.unshift(executableFile);
25372
- args = incrementNodeInspectorPort(process$2.execArgv).concat(args);
25373
- proc = childProcess$2.spawn(process$2.argv[0], args, { stdio: "inherit" });
25372
+ args = incrementNodeInspectorPort(process$3.execArgv).concat(args);
25373
+ proc = childProcess$2.spawn(process$3.argv[0], args, { stdio: "inherit" });
25374
25374
  } else proc = childProcess$2.spawn(executableFile, args, { stdio: "inherit" });
25375
25375
  else {
25376
25376
  this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
25377
25377
  args.unshift(executableFile);
25378
- args = incrementNodeInspectorPort(process$2.execArgv).concat(args);
25379
- proc = childProcess$2.spawn(process$2.execPath, args, { stdio: "inherit" });
25378
+ args = incrementNodeInspectorPort(process$3.execArgv).concat(args);
25379
+ proc = childProcess$2.spawn(process$3.execPath, args, { stdio: "inherit" });
25380
25380
  }
25381
25381
  if (!proc.killed) [
25382
25382
  "SIGUSR1",
@@ -25385,20 +25385,20 @@ Expecting one of '${allowedValues.join("', '")}'`);
25385
25385
  "SIGINT",
25386
25386
  "SIGHUP"
25387
25387
  ].forEach((signal) => {
25388
- process$2.on(signal, () => {
25388
+ process$3.on(signal, () => {
25389
25389
  if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
25390
25390
  });
25391
25391
  });
25392
25392
  const exitCallback = this._exitCallback;
25393
25393
  proc.on("close", (code) => {
25394
25394
  code = code ?? 1;
25395
- if (!exitCallback) process$2.exit(code);
25395
+ if (!exitCallback) process$3.exit(code);
25396
25396
  else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
25397
25397
  });
25398
25398
  proc.on("error", (err) => {
25399
25399
  if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
25400
25400
  else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
25401
- if (!exitCallback) process$2.exit(1);
25401
+ if (!exitCallback) process$3.exit(1);
25402
25402
  else {
25403
25403
  const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
25404
25404
  wrappedError.nestedError = err;
@@ -25807,13 +25807,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
25807
25807
  */
25808
25808
  _parseOptionsEnv() {
25809
25809
  this.options.forEach((option) => {
25810
- if (option.envVar && option.envVar in process$2.env) {
25810
+ if (option.envVar && option.envVar in process$3.env) {
25811
25811
  const optionKey = option.attributeName();
25812
25812
  if (this.getOptionValue(optionKey) === void 0 || [
25813
25813
  "default",
25814
25814
  "config",
25815
25815
  "env"
25816
- ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$2.env[option.envVar]);
25816
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$3.env[option.envVar]);
25817
25817
  else this.emit(`optionEnv:${option.name()}`);
25818
25818
  }
25819
25819
  });
@@ -26230,7 +26230,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
26230
26230
  */
26231
26231
  help(contextOptions) {
26232
26232
  this.outputHelp(contextOptions);
26233
- let exitCode = Number(process$2.exitCode ?? 0);
26233
+ let exitCode = Number(process$3.exitCode ?? 0);
26234
26234
  if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
26235
26235
  this._exit(exitCode, "commander.help", "(outputHelp)");
26236
26236
  }
@@ -26320,8 +26320,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
26320
26320
  * @package
26321
26321
  */
26322
26322
  function useColor() {
26323
- if (process$2.env.NO_COLOR || process$2.env.FORCE_COLOR === "0" || process$2.env.FORCE_COLOR === "false") return false;
26324
- if (process$2.env.FORCE_COLOR || process$2.env.CLICOLOR_FORCE !== void 0) return true;
26323
+ if (process$3.env.NO_COLOR || process$3.env.FORCE_COLOR === "0" || process$3.env.FORCE_COLOR === "false") return false;
26324
+ if (process$3.env.FORCE_COLOR || process$3.env.CLICOLOR_FORCE !== void 0) return true;
26325
26325
  }
26326
26326
  exports.Command = Command;
26327
26327
  exports.useColor = useColor;
@@ -50500,285 +50500,428 @@ const classifyCliMessageError = ({ agentType, command, detail: rawDetail }) => {
50500
50500
  };
50501
50501
 
50502
50502
  //#endregion
50503
- //#region ../../packages/heterogeneous-agents/src/adapters/antigravity.ts
50503
+ //#region ../../packages/heterogeneous-agents/src/adapters/acpCommon.ts
50504
50504
  init_object$1();
50505
- const IDENTIFIER = "antigravity";
50506
- const tokenCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
50507
- const extractUsage = (raw) => {
50508
- if (!isRecord$8(raw)) return;
50509
- const inputCacheMissTokens = tokenCount(raw.input_tokens);
50510
- const inputCachedTokens = tokenCount(raw.cache_read_tokens);
50511
- const totalOutputTokens = tokenCount(raw.output_tokens);
50512
- const outputReasoningTokens = Math.min(tokenCount(raw.thinking_tokens), totalOutputTokens);
50513
- const totalInputTokens = inputCacheMissTokens + inputCachedTokens;
50514
- return {
50515
- inputCachedTokens,
50516
- inputCacheMissTokens,
50517
- outputReasoningTokens,
50518
- outputTextTokens: totalOutputTokens - outputReasoningTokens,
50519
- totalInputTokens,
50520
- totalOutputTokens,
50521
- totalTokens: totalInputTokens + totalOutputTokens
50522
- };
50523
- };
50524
- const stringifyOutput = (value) => typeof value === "string" ? value : value === void 0 ? "" : JSON.stringify(value);
50525
50505
  /**
50526
- * Native agy NDJSON protocol, not the Gemini/Claude stream-json protocol.
50527
- * https://antigravity.google/docs/cli/headless/
50528
- * Supports both one-shot turns and multi-turn liveInput steering while stdin remains open.
50506
+ * Shared stream/step lifecycle for ACP `sessionUpdate` adapters.
50507
+ *
50508
+ * ACP does not frame model rounds explicitly, so adapters detect step
50509
+ * boundaries themselves (tool completion, response completion, …) and set
50510
+ * {@link pendingStepBoundary}. The next `ensureStream(true)` call consumes the
50511
+ * boundary: it closes the open stream, bumps `stepIndex`, resets the per-step
50512
+ * tool list, and re-opens a stream whose `stream_start` payload comes from the
50513
+ * adapter-provided builder (which appends `newStep` for steps > 0).
50529
50514
  */
50530
- var AntigravityAdapter = class {
50531
- sessionId;
50532
- completedSteps = /* @__PURE__ */ new Set();
50533
- flushed = false;
50534
- hasResponseText = false;
50535
- latestTurnCompleted = false;
50536
- model;
50537
- pendingTools = /* @__PURE__ */ new Map();
50538
- resultReceived = false;
50539
- completionValidated = false;
50540
- responseStep;
50541
- runtimeEndStrategy;
50542
- seenInitialUserInput = false;
50543
- seenUserInputSteps = /* @__PURE__ */ new Set();
50515
+ var AcpStreamLifecycle = class {
50516
+ /** Set by the adapter when the next model round must open a new step. */
50517
+ pendingStepBoundary = false;
50544
50518
  stepIndex = 0;
50519
+ /** Tool calls announced within the current step (reset at each boundary). */
50545
50520
  stepTools = [];
50546
50521
  streamOpen = false;
50547
- takeNextSteerUuid;
50548
- toolSinceResponse = false;
50549
- usageByStep = /* @__PURE__ */ new Map();
50550
- constructor(options = {}) {
50551
- this.runtimeEndStrategy = options.runtimeEndStrategy ?? "on-result";
50552
- this.takeNextSteerUuid = options.takeNextSteerUuid;
50522
+ constructor(buildStreamStartData) {
50523
+ this.buildStreamStartData = buildStreamStartData;
50553
50524
  }
50554
- adapt(raw) {
50555
- if (this.flushed || this.resultReceived || !isRecord$8(raw)) return [];
50556
- if (raw.event === "init") {
50557
- this.latestTurnCompleted = false;
50558
- this.sessionId = pickString$1(raw.conversation_id);
50559
- this.model = pickString$1(toRecord$1(raw.init)?.model);
50560
- return this.openStream();
50561
- }
50562
- if (raw.event === "result" && isRecord$8(raw.result)) return this.handleResult(raw.result);
50563
- if (raw.event !== "step_update" || !isRecord$8(raw.step_update)) return [];
50564
- const step = raw.step_update;
50565
- const index = step.step_index;
50566
- if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return [];
50567
- const conversationId = pickString$1(step.conversation_id);
50568
- if (this.sessionId && conversationId && conversationId !== this.sessionId) return [];
50569
- this.sessionId ??= conversationId;
50570
- if (this.completedSteps.has(index)) return [];
50571
- this.latestTurnCompleted = false;
50525
+ event(type, data) {
50526
+ return {
50527
+ data,
50528
+ stepIndex: this.stepIndex,
50529
+ timestamp: Date.now(),
50530
+ type
50531
+ };
50532
+ }
50533
+ ensureStream(consumeStepBoundary) {
50572
50534
  const events = [];
50573
- if (step.step_type === "user_input") {
50574
- if (!this.seenUserInputSteps.has(index)) {
50575
- this.seenUserInputSteps.add(index);
50576
- if (!this.seenInitialUserInput) this.seenInitialUserInput = true;
50577
- else {
50578
- const uuid = this.takeNextSteerUuid?.();
50579
- if (uuid) {
50580
- events.push(...this.closeStream());
50581
- events.push(this.event("step_complete", {
50582
- phase: "user_message",
50583
- uuid
50584
- }));
50585
- }
50586
- }
50587
- }
50588
- } else if (step.step_type === "agent_response") {
50589
- if (this.toolSinceResponse || this.responseStep !== void 0 && this.responseStep !== index) {
50590
- events.push(...this.closeStream());
50591
- this.stepIndex += 1;
50592
- this.stepTools = [];
50593
- this.hasResponseText = false;
50594
- }
50595
- events.push(...this.openStream());
50596
- this.toolSinceResponse = false;
50597
- this.responseStep = index;
50598
- if (typeof step.text_delta === "string" && step.text_delta) {
50599
- this.hasResponseText = true;
50600
- events.push(this.event("stream_chunk", {
50601
- chunkType: "text",
50602
- content: step.text_delta
50603
- }));
50604
- }
50605
- } else if (step.step_type === "tool" || isRecord$8(step.subagent_info)) events.push(...this.handleTool(index, step));
50606
- if (step.state === "DONE") {
50607
- this.completedSteps.add(index);
50608
- const usage = extractUsage(step.usage);
50609
- if (usage) this.usageByStep.set(index, usage);
50535
+ if (consumeStepBoundary && this.pendingStepBoundary) {
50536
+ events.push(...this.closeStream());
50537
+ this.pendingStepBoundary = false;
50538
+ this.stepIndex += 1;
50539
+ this.stepTools = [];
50610
50540
  }
50541
+ if (this.streamOpen) return events;
50542
+ this.streamOpen = true;
50543
+ events.push(this.event("stream_start", this.buildStreamStartData(this.stepIndex)));
50611
50544
  return events;
50612
50545
  }
50613
- flush() {
50614
- if (this.flushed) return [];
50615
- this.flushed = true;
50616
- return [...this.settlePendingTools("Antigravity ended before this tool returned a result."), ...this.closeStream()];
50546
+ closeStream(data = {}) {
50547
+ if (!this.streamOpen) return [];
50548
+ this.streamOpen = false;
50549
+ return [this.event("stream_end", data)];
50617
50550
  }
50618
- validateCompletion() {
50619
- if (this.resultReceived || this.latestTurnCompleted || this.completionValidated) return [];
50620
- this.completionValidated = true;
50621
- return [this.event("error", {
50622
- agentType: IDENTIFIER,
50623
- code: "incomplete_response",
50624
- message: "Antigravity exited without a final result. Update agy and retry."
50625
- })];
50551
+ };
50552
+ /**
50553
+ * Read the text out of one ACP ContentBlock-ish value: plain strings, `text`
50554
+ * blocks, nested `content` wrappers, and the `diff` / `output` string fields
50555
+ * some agents put on tool-call content.
50556
+ */
50557
+ const acpContentBlockText = (value) => {
50558
+ if (typeof value === "string") return value;
50559
+ if (!isRecord$8(value)) return "";
50560
+ if (value.type === "text" && typeof value.text === "string") return value.text;
50561
+ if (typeof value.content === "string") return value.content;
50562
+ if (isRecord$8(value.content)) return acpContentBlockText(value.content);
50563
+ if (typeof value.diff === "string") return value.diff;
50564
+ if (typeof value.output === "string") return value.output;
50565
+ return "";
50566
+ };
50567
+ /**
50568
+ * ACP extension marker for replayed history: `_meta.isReplay` on either the
50569
+ * notification `params` or the nested `update`.
50570
+ */
50571
+ const isAcpReplayMessage = (raw) => {
50572
+ const params = toRecord$1(toRecord$1(raw)?.params);
50573
+ const update = toRecord$1(params?.update);
50574
+ return toRecord$1(params?._meta)?.isReplay === true || toRecord$1(update?._meta)?.isReplay === true;
50575
+ };
50576
+ /** ACP extension dedup marker: `_meta.eventId` on the notification `params`. */
50577
+ const acpEventIdOf = (raw) => {
50578
+ const meta = toRecord$1(toRecord$1(toRecord$1(raw)?.params)?._meta);
50579
+ return typeof meta?.eventId === "string" ? meta.eventId : void 0;
50580
+ };
50581
+
50582
+ //#endregion
50583
+ //#region ../../packages/heterogeneous-agents/src/adapters/traeAcp.ts
50584
+ init_object$1();
50585
+ const DEFAULT_PROVIDER = "trae";
50586
+ const toFiniteNumber$3 = (value) => {
50587
+ if (typeof value === "number" && Number.isFinite(value)) return value;
50588
+ if (typeof value === "string") {
50589
+ const parsed = Number(value);
50590
+ if (Number.isFinite(parsed)) return parsed;
50626
50591
  }
50627
- openStream() {
50628
- if (this.streamOpen) return [];
50629
- this.streamOpen = true;
50630
- return [this.event("stream_start", {
50631
- model: this.model,
50632
- newStep: this.stepIndex > 0,
50633
- provider: IDENTIFIER,
50634
- sessionId: this.sessionId
50635
- })];
50592
+ };
50593
+ const stringify$1 = (value) => {
50594
+ if (typeof value === "string") return value;
50595
+ if (value === void 0) return "";
50596
+ try {
50597
+ return JSON.stringify(value);
50598
+ } catch {
50599
+ return String(value);
50636
50600
  }
50637
- closeStream() {
50638
- const events = [];
50639
- if (this.usageByStep.size) {
50640
- const usage = [...this.usageByStep.values()].reduce((total, next) => ({
50641
- inputCachedTokens: (total.inputCachedTokens ?? 0) + (next.inputCachedTokens ?? 0),
50642
- inputCacheMissTokens: total.inputCacheMissTokens + next.inputCacheMissTokens,
50643
- outputReasoningTokens: (total.outputReasoningTokens ?? 0) + (next.outputReasoningTokens ?? 0),
50644
- outputTextTokens: (total.outputTextTokens ?? 0) + (next.outputTextTokens ?? 0),
50645
- totalInputTokens: total.totalInputTokens + next.totalInputTokens,
50646
- totalOutputTokens: total.totalOutputTokens + next.totalOutputTokens,
50647
- totalTokens: total.totalTokens + next.totalTokens
50648
- }));
50649
- events.push(this.event("step_complete", {
50650
- model: this.model,
50651
- phase: "turn_metadata",
50652
- provider: IDENTIFIER,
50653
- usage
50654
- }));
50655
- this.usageByStep.clear();
50601
+ };
50602
+ const toolContent = (content, fallback) => {
50603
+ if (!Array.isArray(content)) return stringify$1(content ?? fallback);
50604
+ return content.map((value) => {
50605
+ const block = value;
50606
+ if (block?.type === "content") {
50607
+ const nestedContent = block.content;
50608
+ if (nestedContent?.type === "text") return stringify$1(nestedContent.text);
50609
+ return stringify$1(block.content);
50656
50610
  }
50657
- if (this.streamOpen) {
50658
- events.push(this.event("stream_end", {}));
50659
- this.streamOpen = false;
50611
+ if (block?.type === "diff") return [block.path, block.newText].filter((value) => typeof value === "string").join("\n");
50612
+ if (block?.type === "terminal") return `[Terminal: ${stringify$1(block.terminalId)}]`;
50613
+ return stringify$1(block);
50614
+ }).filter(Boolean).join("\n") || stringify$1(fallback);
50615
+ };
50616
+ /**
50617
+ * Maps the standard ACP `sessionUpdate` vocabulary into the shared event
50618
+ * contract. TRAE is the default provider; other standard-ACP agents reuse it
50619
+ * via {@link AcpSessionAdapterOptions}.
50620
+ */
50621
+ var TraeAcpAdapter = class {
50622
+ sessionId;
50623
+ eventPrefix;
50624
+ provider;
50625
+ completedTools = /* @__PURE__ */ new Set();
50626
+ lastCostUsd;
50627
+ lastUsage;
50628
+ model;
50629
+ pendingTools = /* @__PURE__ */ new Set();
50630
+ snapshotSeq = /* @__PURE__ */ new Map();
50631
+ stream = new AcpStreamLifecycle((stepIndex) => ({
50632
+ ...this.model ? { model: this.model } : {},
50633
+ ...stepIndex > 0 ? { newStep: true } : {},
50634
+ provider: this.provider,
50635
+ sessionId: this.sessionId
50636
+ }));
50637
+ terminal = false;
50638
+ toolResultStateById = /* @__PURE__ */ new Map();
50639
+ constructor(options = {}) {
50640
+ this.provider = options.provider ?? DEFAULT_PROVIDER;
50641
+ this.eventPrefix = options.eventPrefix ?? this.provider;
50642
+ }
50643
+ adapt(value) {
50644
+ if (!value || typeof value !== "object" || this.terminal) return [];
50645
+ const raw = value;
50646
+ if (raw.type === "session_configured") {
50647
+ if (typeof raw.model === "string") this.model = raw.model;
50648
+ return [];
50649
+ }
50650
+ if (raw.type === `${this.eventPrefix}_session`) {
50651
+ if (typeof raw.sessionId === "string") this.sessionId = raw.sessionId;
50652
+ if (typeof raw.model === "string") this.model = raw.model;
50653
+ return [];
50654
+ }
50655
+ if (raw.type === `${this.eventPrefix}_prompt_completed`) {
50656
+ const usage = this.toUsageData(raw.usage) ?? this.lastUsage;
50657
+ const costUsd = this.toCostUsd(raw.cost) ?? this.lastCostUsd;
50658
+ return this.complete(raw.stopReason, usage, costUsd);
50659
+ }
50660
+ if (raw.type === `${this.eventPrefix}_error`) return this.fail(stringify$1(raw.message) || `${this.provider} ACP failed`);
50661
+ switch (raw.sessionUpdate) {
50662
+ case "usage_update": {
50663
+ const usage = this.extractUsageFromUsageUpdate(raw);
50664
+ if (usage) this.lastUsage = usage;
50665
+ const costUsd = this.toCostUsd(raw.cost);
50666
+ if (costUsd !== void 0) this.lastCostUsd = costUsd;
50667
+ return [];
50668
+ }
50669
+ case "agent_message_chunk": {
50670
+ const text = raw.content?.text;
50671
+ return typeof text === "string" && text ? [...this.stream.ensureStream(true), this.stream.event("stream_chunk", {
50672
+ chunkType: "text",
50673
+ content: text
50674
+ })] : [];
50675
+ }
50676
+ case "agent_thought_chunk": {
50677
+ const reasoning = raw.content?.text;
50678
+ return typeof reasoning === "string" && reasoning ? [...this.stream.ensureStream(true), this.stream.event("stream_chunk", {
50679
+ chunkType: "reasoning",
50680
+ reasoning
50681
+ })] : [];
50682
+ }
50683
+ case "tool_call": return this.startTool(raw);
50684
+ case "tool_call_update": return this.updateTool(raw);
50685
+ default: return [];
50660
50686
  }
50661
- return events;
50662
50687
  }
50663
- handleTool(index, step) {
50664
- const info = toRecord$1(step.tool_info);
50665
- const subagents = toRecord$1(step.subagent_info);
50666
- const name = pickString$1(info?.name) ?? pickString$1(step.tool_name);
50667
- let pending = this.pendingTools.get(index);
50668
- if (!pending && !name && !subagents) return [];
50669
- const events = this.openStream();
50670
- this.toolSinceResponse = true;
50671
- const args = JSON.stringify(info?.parameters ?? subagents ?? {});
50672
- if (!pending) {
50673
- pending = {
50674
- payload: {
50675
- apiName: name ?? "subagents",
50676
- arguments: args,
50677
- id: `agy_${this.sessionId ?? "session"}_${index}`,
50678
- identifier: IDENTIFIER,
50679
- type: "default"
50680
- },
50681
- stepIndex: this.stepIndex
50682
- };
50683
- this.pendingTools.set(index, pending);
50684
- } else if (info?.parameters !== void 0) pending.payload.arguments = args;
50685
- if (info?.parameters !== void 0 || step.state === "DONE") events.push(...this.startTool(pending));
50686
- if (step.state === "DONE") {
50687
- const error = toRecord$1(info?.error);
50688
- const content = [stringifyOutput(info?.output ?? subagents), pickString$1(error?.message) ?? stringifyOutput(info?.error)].filter(Boolean).join("\n");
50689
- events.push(...this.toolResult(pending, content, info?.error != null));
50690
- this.pendingTools.delete(index);
50688
+ flush() {
50689
+ if (this.terminal) return [];
50690
+ return this.complete("end_turn", this.lastUsage, this.lastCostUsd);
50691
+ }
50692
+ updateTool(raw) {
50693
+ const id = raw.toolCallId;
50694
+ if (typeof id !== "string" || this.completedTools.has(id)) return [];
50695
+ const startEvents = this.pendingTools.has(id) ? [] : this.startTool(raw);
50696
+ const resultState = this.mergeToolResultState(id, raw);
50697
+ if (raw.status === "running" || raw.status === "in_progress" || raw.status === "pending") {
50698
+ const snapshotSeq = (this.snapshotSeq.get(id) ?? 0) + 1;
50699
+ this.snapshotSeq.set(id, snapshotSeq);
50700
+ return [...startEvents, this.stream.event("stream_chunk", {
50701
+ chunkType: "tool_state",
50702
+ pluginState: { ...raw },
50703
+ snapshotMode: "replace",
50704
+ snapshotSeq,
50705
+ toolCallId: id
50706
+ })];
50691
50707
  }
50708
+ if (raw.status !== "completed" && raw.status !== "failed") return [];
50709
+ this.completedTools.add(id);
50710
+ this.pendingTools.delete(id);
50711
+ const isSuccess = raw.status === "completed";
50712
+ const result = resultState.latest === "content" ? toolContent(resultState.content, resultState.rawOutput ?? resultState.output) : stringify$1(resultState.latest === "rawOutput" ? resultState.rawOutput : resultState.output);
50713
+ const events = [
50714
+ ...startEvents,
50715
+ this.stream.event("tool_result", {
50716
+ content: result,
50717
+ isError: !isSuccess,
50718
+ toolCallId: id
50719
+ }),
50720
+ this.stream.event("tool_end", {
50721
+ isSuccess,
50722
+ toolCallId: id
50723
+ })
50724
+ ];
50725
+ if (this.pendingTools.size === 0) this.stream.pendingStepBoundary = true;
50692
50726
  return events;
50693
50727
  }
50694
- startTool(tool) {
50695
- if (tool.started) return [];
50696
- tool.started = true;
50697
- this.stepTools.push(tool.payload);
50698
- return [this.event("stream_chunk", {
50699
- chunkType: "tools_calling",
50700
- toolsCalling: this.stepTools.map((payload) => ({ ...payload }))
50701
- }, tool.stepIndex), this.event("tool_start", {
50702
- toolCalling: { ...tool.payload },
50703
- toolCallId: tool.payload.id
50704
- }, tool.stepIndex)];
50705
- }
50706
- toolResult(tool, content, isError) {
50728
+ startTool(raw) {
50729
+ const id = raw.toolCallId;
50730
+ if (typeof id !== "string" || this.completedTools.has(id)) return [];
50731
+ this.mergeToolResultState(id, raw);
50732
+ if (this.pendingTools.has(id)) return [];
50733
+ const payload = {
50734
+ apiName: [
50735
+ raw.name,
50736
+ raw.title,
50737
+ raw.kind
50738
+ ].find((value) => typeof value === "string" && value.length > 0) ?? "unknown",
50739
+ arguments: stringify$1(raw.rawInput ?? raw.input ?? raw.parameters ?? {}),
50740
+ id,
50741
+ identifier: typeof raw.identifier === "string" && raw.identifier ? raw.identifier : this.provider,
50742
+ type: "default"
50743
+ };
50744
+ const streamEvents = this.stream.ensureStream(true);
50745
+ this.pendingTools.add(id);
50746
+ this.stream.stepTools.push(payload);
50707
50747
  return [
50708
- ...this.startTool(tool),
50709
- this.event("tool_result", {
50710
- content,
50711
- isError,
50712
- toolCallId: tool.payload.id
50713
- }, tool.stepIndex),
50714
- this.event("tool_end", {
50715
- isSuccess: !isError,
50716
- payload: { toolCalling: tool.payload },
50717
- result: {
50718
- content,
50719
- success: !isError
50720
- },
50721
- toolCallId: tool.payload.id
50722
- }, tool.stepIndex)
50748
+ ...streamEvents,
50749
+ this.stream.event("stream_chunk", {
50750
+ chunkType: "tools_calling",
50751
+ toolsCalling: [...this.stream.stepTools]
50752
+ }),
50753
+ this.stream.event("tool_start", {
50754
+ toolCalling: payload,
50755
+ toolCallId: id
50756
+ })
50723
50757
  ];
50724
50758
  }
50725
- settlePendingTools(message) {
50726
- const events = [...this.pendingTools.values()].flatMap((tool) => this.toolResult(tool, message, true));
50759
+ mergeToolResultState(toolCallId, raw) {
50760
+ const state = this.toolResultStateById.get(toolCallId) ?? {};
50761
+ if (raw.content !== void 0) state.content = raw.content;
50762
+ if (raw.rawOutput !== void 0) state.rawOutput = raw.rawOutput;
50763
+ if (raw.output !== void 0) state.output = raw.output;
50764
+ if (raw.content !== void 0) state.latest = "content";
50765
+ else if (raw.rawOutput !== void 0) state.latest = "rawOutput";
50766
+ else if (raw.output !== void 0) state.latest = "output";
50767
+ this.toolResultStateById.set(toolCallId, state);
50768
+ return state;
50769
+ }
50770
+ closePending() {
50771
+ const events = [...this.pendingTools].map((toolCallId) => this.stream.event("tool_end", {
50772
+ isSuccess: false,
50773
+ toolCallId
50774
+ }));
50727
50775
  this.pendingTools.clear();
50728
50776
  return events;
50729
50777
  }
50730
- handleResult(result) {
50731
- const keepOpenForMoreTurns = this.runtimeEndStrategy === "on-transport-close" && result.status === "SUCCESS";
50732
- if (!keepOpenForMoreTurns) this.resultReceived = true;
50733
- this.latestTurnCompleted = true;
50734
- this.sessionId ??= pickString$1(result.conversation_id);
50735
- const hasPendingTools = this.pendingTools.size > 0;
50736
- const events = this.settlePendingTools("Antigravity ended before this tool returned a result.");
50737
- if (result.status === "SUCCESS") {
50738
- if ((!this.hasResponseText || this.toolSinceResponse) && typeof result.response === "string" && result.response) {
50739
- if (this.toolSinceResponse) {
50740
- events.push(...this.closeStream());
50741
- this.stepIndex += 1;
50742
- }
50743
- events.push(...this.openStream(), this.event("stream_chunk", {
50744
- chunkType: "text",
50745
- content: result.response
50746
- }));
50747
- }
50748
- if (hasPendingTools) events.push(this.event("error", {
50749
- agentType: IDENTIFIER,
50750
- code: "incomplete_tool_result",
50751
- message: "Antigravity completed without returning all tool results."
50752
- }));
50753
- } else {
50754
- const detail = pickString$1(result.error) || `Antigravity ended with status ${String(result.status ?? "unknown")}.`;
50755
- events.push(this.event("error", classifyCliMessageError({
50756
- agentType: IDENTIFIER,
50757
- detail
50758
- }) ?? {
50759
- agentType: IDENTIFIER,
50760
- code: "antigravity_run_error",
50761
- message: detail
50762
- }));
50763
- }
50764
- events.push(...this.closeStream());
50765
- if (keepOpenForMoreTurns) {
50766
- this.hasResponseText = false;
50767
- this.responseStep = void 0;
50768
- this.toolSinceResponse = false;
50769
- this.stepTools = [];
50770
- this.stepIndex += 1;
50778
+ complete(stopReason, usage, costUsd) {
50779
+ if (this.terminal) return [];
50780
+ this.terminal = true;
50781
+ const runtimeEndData = stopReason === "cancelled" ? {
50782
+ reason: "interrupted",
50783
+ stopReason
50784
+ } : { stopReason };
50785
+ const result = [
50786
+ ...this.closePending(),
50787
+ ...this.stream.closeStream({ stopReason }),
50788
+ this.stream.event("visible_output_end", {})
50789
+ ];
50790
+ if (usage) {
50791
+ if (costUsd !== void 0) usage.cost = costUsd;
50792
+ const stepCompleteData = {
50793
+ model: this.model,
50794
+ phase: "turn_metadata",
50795
+ provider: this.provider,
50796
+ usage
50797
+ };
50798
+ result.push(this.stream.event("step_complete", stepCompleteData));
50771
50799
  }
50772
- return events;
50800
+ result.push(this.stream.event("agent_runtime_end", runtimeEndData));
50801
+ return result;
50773
50802
  }
50774
- event(type, data, stepIndex = this.stepIndex) {
50803
+ /**
50804
+ * Convert an ACP experimental `Usage` shape into the shared `UsageData`.
50805
+ * Returns `undefined` when required fields are missing or invalid.
50806
+ */
50807
+ toUsageData(usage) {
50808
+ if (!isRecord$8(usage)) return;
50809
+ const total = toFiniteNumber$3(usage.totalTokens) ?? toFiniteNumber$3(usage.total_tokens);
50810
+ const input = toFiniteNumber$3(usage.inputTokens) ?? toFiniteNumber$3(usage.input_tokens);
50811
+ const output = toFiniteNumber$3(usage.outputTokens) ?? toFiniteNumber$3(usage.output_tokens);
50812
+ if (typeof input !== "number" || typeof output !== "number" || input < 0 || output < 0) return;
50813
+ const cachedRead = toFiniteNumber$3(usage.cachedReadTokens) ?? toFiniteNumber$3(usage.cached_read_tokens) ?? toFiniteNumber$3(usage.cacheReadTokens) ?? toFiniteNumber$3(usage.cache_read_tokens) ?? 0;
50814
+ const cachedWrite = toFiniteNumber$3(usage.cachedWriteTokens) ?? toFiniteNumber$3(usage.cached_write_tokens) ?? toFiniteNumber$3(usage.cacheWriteTokens) ?? toFiniteNumber$3(usage.cache_write_tokens) ?? 0;
50815
+ const thought = toFiniteNumber$3(usage.thoughtTokens) ?? toFiniteNumber$3(usage.thought_tokens) ?? toFiniteNumber$3(usage.reasoningTokens) ?? toFiniteNumber$3(usage.reasoning_tokens) ?? 0;
50816
+ const inputCacheMiss = Math.max(0, input - cachedRead);
50817
+ const outputText = Math.max(0, output - thought);
50818
+ const totalTokens = total ?? input + output + cachedWrite;
50775
50819
  return {
50776
- data,
50777
- stepIndex,
50778
- timestamp: Date.now(),
50779
- type
50820
+ inputCachedTokens: cachedRead || void 0,
50821
+ inputCacheMissTokens: inputCacheMiss,
50822
+ inputWriteCacheTokens: cachedWrite || void 0,
50823
+ outputReasoningTokens: thought || void 0,
50824
+ outputTextTokens: outputText,
50825
+ totalInputTokens: input + cachedWrite,
50826
+ totalOutputTokens: output,
50827
+ totalTokens
50780
50828
  };
50781
50829
  }
50830
+ /**
50831
+ * Extract token usage from a `usage_update` notification.
50832
+ * The ACP spec only requires `used`/`size`/`cost`; per-turn token breakdown
50833
+ * lives in `_meta` as vendor extensions. Subclasses may override this to
50834
+ * parse provider-specific `_meta` keys (e.g. `cognition.ai/*Tokens`).
50835
+ */
50836
+ extractUsageFromUsageUpdate(_raw) {}
50837
+ /** Extract a USD cost amount from an ACP `cost` object. */
50838
+ toCostUsd(cost) {
50839
+ if (!isRecord$8(cost)) return;
50840
+ if (cost.currency !== "USD") return;
50841
+ const amount = toFiniteNumber$3(cost.amount);
50842
+ if (amount === void 0 || amount <= 0) return;
50843
+ return amount;
50844
+ }
50845
+ fail(message) {
50846
+ if (this.terminal) return [];
50847
+ this.terminal = true;
50848
+ return [
50849
+ ...this.closePending(),
50850
+ ...this.stream.closeStream(),
50851
+ this.stream.event("visible_output_end", {}),
50852
+ this.stream.event("error", {
50853
+ agentType: this.provider,
50854
+ error: message,
50855
+ message
50856
+ })
50857
+ ];
50858
+ }
50859
+ };
50860
+
50861
+ //#endregion
50862
+ //#region ../../packages/heterogeneous-agents/src/adapters/antigravityAcp.ts
50863
+ init_object$1();
50864
+ const IDENTIFIER = "antigravity";
50865
+ const tokenCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
50866
+ /**
50867
+ * `agy acp` reports `inputTokens` without cache reads (`totalTokens` is input
50868
+ * + cached reads + output), unlike the ACP usage shape the base adapter
50869
+ * assumes. Our totals include cached input.
50870
+ */
50871
+ const toAntigravityUsage = (raw) => {
50872
+ if (!isRecord$8(raw)) return;
50873
+ const inputCacheMissTokens = tokenCount(raw.inputTokens);
50874
+ const inputCachedTokens = tokenCount(raw.cachedReadTokens);
50875
+ const totalOutputTokens = tokenCount(raw.outputTokens);
50876
+ if (!inputCacheMissTokens && !inputCachedTokens && !totalOutputTokens) return;
50877
+ const outputReasoningTokens = Math.min(tokenCount(raw.thoughtTokens), totalOutputTokens);
50878
+ const totalInputTokens = inputCacheMissTokens + inputCachedTokens;
50879
+ return {
50880
+ inputCachedTokens: inputCachedTokens || void 0,
50881
+ inputCacheMissTokens,
50882
+ outputReasoningTokens: outputReasoningTokens || void 0,
50883
+ outputTextTokens: totalOutputTokens - outputReasoningTokens,
50884
+ totalInputTokens,
50885
+ totalOutputTokens,
50886
+ totalTokens: totalInputTokens + totalOutputTokens
50887
+ };
50888
+ };
50889
+ /**
50890
+ * Maps `agy acp` session updates (the standard ACP vocabulary) into the shared
50891
+ * event contract, plus the steer delivery the session reports as
50892
+ * `antigravity_user_message` once agy took a message into the running turn.
50893
+ */
50894
+ var AntigravityAcpAdapter = class extends TraeAcpAdapter {
50895
+ constructor() {
50896
+ super({
50897
+ eventPrefix: IDENTIFIER,
50898
+ provider: IDENTIFIER
50899
+ });
50900
+ }
50901
+ adapt(value) {
50902
+ if (!isRecord$8(value)) return [];
50903
+ if (value.type === `${IDENTIFIER}_user_message`) {
50904
+ if (typeof value.uuid !== "string" || !value.uuid) return [];
50905
+ this.stream.pendingStepBoundary = true;
50906
+ return [this.stream.event("step_complete", {
50907
+ phase: "user_message",
50908
+ uuid: value.uuid
50909
+ })];
50910
+ }
50911
+ const events = super.adapt(value);
50912
+ if (value.type !== `${IDENTIFIER}_error`) return events;
50913
+ const classified = classifyCliMessageError({
50914
+ agentType: IDENTIFIER,
50915
+ detail: typeof value.message === "string" ? value.message : void 0
50916
+ });
50917
+ return classified ? events.map((event) => event.type === "error" ? {
50918
+ ...event,
50919
+ data: classified
50920
+ } : event) : events;
50921
+ }
50922
+ toUsageData(usage) {
50923
+ return toAntigravityUsage(usage);
50924
+ }
50782
50925
  };
50783
50926
 
50784
50927
  //#endregion
@@ -51370,7 +51513,7 @@ const getPathValue = (raw, path) => {
51370
51513
  }
51371
51514
  return current;
51372
51515
  };
51373
- const toFiniteNumber$3 = (value) => {
51516
+ const toFiniteNumber$2 = (value) => {
51374
51517
  if (typeof value === "number" && Number.isFinite(value)) return value;
51375
51518
  if (typeof value === "string" && value.trim()) {
51376
51519
  const parsed = Number(value);
@@ -51379,7 +51522,7 @@ const toFiniteNumber$3 = (value) => {
51379
51522
  };
51380
51523
  const pickNumber = (raw, paths) => {
51381
51524
  for (const path of paths) {
51382
- const value = toFiniteNumber$3(getPathValue(raw, path));
51525
+ const value = toFiniteNumber$2(getPathValue(raw, path));
51383
51526
  if (value !== void 0) return value;
51384
51527
  }
51385
51528
  };
@@ -54057,7 +54200,7 @@ const CODEX_PROPOSED_PLAN_API_NAME = "proposed_plan";
54057
54200
  //#region ../../packages/heterogeneous-agents/src/adapters/codexAppServer.ts
54058
54201
  const CODEX_IDENTIFIER = "codex";
54059
54202
  const isToolItem = (item) => item.type === "collabAgentToolCall" || item.type === "commandExecution" || item.type === "dynamicToolCall" || item.type === "fileChange" || item.type === "mcpToolCall" || item.type === "webSearch";
54060
- const stringify$1 = (value) => {
54203
+ const stringify = (value) => {
54061
54204
  if (typeof value === "string") return value;
54062
54205
  if (value === null || value === void 0) return "";
54063
54206
  try {
@@ -54113,8 +54256,8 @@ const toMcpContent = (item) => {
54113
54256
  if (!item.result) return "";
54114
54257
  return item.result.content.map((content) => {
54115
54258
  if (typeof content === "string") return content;
54116
- if (content && typeof content === "object" && "text" in content) return typeof content.text === "string" ? content.text : stringify$1(content);
54117
- return stringify$1(content);
54259
+ if (content && typeof content === "object" && "text" in content) return typeof content.text === "string" ? content.text : stringify(content);
54260
+ return stringify(content);
54118
54261
  }).filter(Boolean).join("\n\n");
54119
54262
  };
54120
54263
  const getWebSearchQuery = (item) => {
@@ -54185,7 +54328,7 @@ const toToolResult = (item) => {
54185
54328
  toolCallId: item.id
54186
54329
  };
54187
54330
  case "dynamicToolCall": return {
54188
- content: item.contentItems?.map((entry) => entry.type === "inputText" ? entry.text : stringify$1(entry)).join("\n\n") || `${item.tool} ${success ? "completed" : "failed"}.`,
54331
+ content: item.contentItems?.map((entry) => entry.type === "inputText" ? entry.text : stringify(entry)).join("\n\n") || `${item.tool} ${success ? "completed" : "failed"}.`,
54189
54332
  isError: !success,
54190
54333
  pluginState: {
54191
54334
  arguments: item.arguments,
@@ -54751,365 +54894,6 @@ var CodexAppServerAdapter = class {
54751
54894
  }
54752
54895
  };
54753
54896
 
54754
- //#endregion
54755
- //#region ../../packages/heterogeneous-agents/src/adapters/acpCommon.ts
54756
- init_object$1();
54757
- /**
54758
- * Shared stream/step lifecycle for ACP `sessionUpdate` adapters.
54759
- *
54760
- * ACP does not frame model rounds explicitly, so adapters detect step
54761
- * boundaries themselves (tool completion, response completion, …) and set
54762
- * {@link pendingStepBoundary}. The next `ensureStream(true)` call consumes the
54763
- * boundary: it closes the open stream, bumps `stepIndex`, resets the per-step
54764
- * tool list, and re-opens a stream whose `stream_start` payload comes from the
54765
- * adapter-provided builder (which appends `newStep` for steps > 0).
54766
- */
54767
- var AcpStreamLifecycle = class {
54768
- /** Set by the adapter when the next model round must open a new step. */
54769
- pendingStepBoundary = false;
54770
- stepIndex = 0;
54771
- /** Tool calls announced within the current step (reset at each boundary). */
54772
- stepTools = [];
54773
- streamOpen = false;
54774
- constructor(buildStreamStartData) {
54775
- this.buildStreamStartData = buildStreamStartData;
54776
- }
54777
- event(type, data) {
54778
- return {
54779
- data,
54780
- stepIndex: this.stepIndex,
54781
- timestamp: Date.now(),
54782
- type
54783
- };
54784
- }
54785
- ensureStream(consumeStepBoundary) {
54786
- const events = [];
54787
- if (consumeStepBoundary && this.pendingStepBoundary) {
54788
- events.push(...this.closeStream());
54789
- this.pendingStepBoundary = false;
54790
- this.stepIndex += 1;
54791
- this.stepTools = [];
54792
- }
54793
- if (this.streamOpen) return events;
54794
- this.streamOpen = true;
54795
- events.push(this.event("stream_start", this.buildStreamStartData(this.stepIndex)));
54796
- return events;
54797
- }
54798
- closeStream(data = {}) {
54799
- if (!this.streamOpen) return [];
54800
- this.streamOpen = false;
54801
- return [this.event("stream_end", data)];
54802
- }
54803
- };
54804
- /**
54805
- * Read the text out of one ACP ContentBlock-ish value: plain strings, `text`
54806
- * blocks, nested `content` wrappers, and the `diff` / `output` string fields
54807
- * some agents put on tool-call content.
54808
- */
54809
- const acpContentBlockText = (value) => {
54810
- if (typeof value === "string") return value;
54811
- if (!isRecord$8(value)) return "";
54812
- if (value.type === "text" && typeof value.text === "string") return value.text;
54813
- if (typeof value.content === "string") return value.content;
54814
- if (isRecord$8(value.content)) return acpContentBlockText(value.content);
54815
- if (typeof value.diff === "string") return value.diff;
54816
- if (typeof value.output === "string") return value.output;
54817
- return "";
54818
- };
54819
- /**
54820
- * ACP extension marker for replayed history: `_meta.isReplay` on either the
54821
- * notification `params` or the nested `update`.
54822
- */
54823
- const isAcpReplayMessage = (raw) => {
54824
- const params = toRecord$1(toRecord$1(raw)?.params);
54825
- const update = toRecord$1(params?.update);
54826
- return toRecord$1(params?._meta)?.isReplay === true || toRecord$1(update?._meta)?.isReplay === true;
54827
- };
54828
- /** ACP extension dedup marker: `_meta.eventId` on the notification `params`. */
54829
- const acpEventIdOf = (raw) => {
54830
- const meta = toRecord$1(toRecord$1(toRecord$1(raw)?.params)?._meta);
54831
- return typeof meta?.eventId === "string" ? meta.eventId : void 0;
54832
- };
54833
-
54834
- //#endregion
54835
- //#region ../../packages/heterogeneous-agents/src/adapters/traeAcp.ts
54836
- init_object$1();
54837
- const DEFAULT_PROVIDER = "trae";
54838
- const toFiniteNumber$2 = (value) => {
54839
- if (typeof value === "number" && Number.isFinite(value)) return value;
54840
- if (typeof value === "string") {
54841
- const parsed = Number(value);
54842
- if (Number.isFinite(parsed)) return parsed;
54843
- }
54844
- };
54845
- const stringify = (value) => {
54846
- if (typeof value === "string") return value;
54847
- if (value === void 0) return "";
54848
- try {
54849
- return JSON.stringify(value);
54850
- } catch {
54851
- return String(value);
54852
- }
54853
- };
54854
- const toolContent = (content, fallback) => {
54855
- if (!Array.isArray(content)) return stringify(content ?? fallback);
54856
- return content.map((value) => {
54857
- const block = value;
54858
- if (block?.type === "content") {
54859
- const nestedContent = block.content;
54860
- if (nestedContent?.type === "text") return stringify(nestedContent.text);
54861
- return stringify(block.content);
54862
- }
54863
- if (block?.type === "diff") return [block.path, block.newText].filter((value) => typeof value === "string").join("\n");
54864
- if (block?.type === "terminal") return `[Terminal: ${stringify(block.terminalId)}]`;
54865
- return stringify(block);
54866
- }).filter(Boolean).join("\n") || stringify(fallback);
54867
- };
54868
- /**
54869
- * Maps the standard ACP `sessionUpdate` vocabulary into the shared event
54870
- * contract. TRAE is the default provider; other standard-ACP agents reuse it
54871
- * via {@link AcpSessionAdapterOptions}.
54872
- */
54873
- var TraeAcpAdapter = class {
54874
- sessionId;
54875
- eventPrefix;
54876
- provider;
54877
- completedTools = /* @__PURE__ */ new Set();
54878
- lastCostUsd;
54879
- lastUsage;
54880
- model;
54881
- pendingTools = /* @__PURE__ */ new Set();
54882
- snapshotSeq = /* @__PURE__ */ new Map();
54883
- stream = new AcpStreamLifecycle((stepIndex) => ({
54884
- ...this.model ? { model: this.model } : {},
54885
- ...stepIndex > 0 ? { newStep: true } : {},
54886
- provider: this.provider,
54887
- sessionId: this.sessionId
54888
- }));
54889
- terminal = false;
54890
- toolResultStateById = /* @__PURE__ */ new Map();
54891
- constructor(options = {}) {
54892
- this.provider = options.provider ?? DEFAULT_PROVIDER;
54893
- this.eventPrefix = options.eventPrefix ?? this.provider;
54894
- }
54895
- adapt(value) {
54896
- if (!value || typeof value !== "object" || this.terminal) return [];
54897
- const raw = value;
54898
- if (raw.type === "session_configured") {
54899
- if (typeof raw.model === "string") this.model = raw.model;
54900
- return [];
54901
- }
54902
- if (raw.type === `${this.eventPrefix}_session`) {
54903
- if (typeof raw.sessionId === "string") this.sessionId = raw.sessionId;
54904
- if (typeof raw.model === "string") this.model = raw.model;
54905
- return [];
54906
- }
54907
- if (raw.type === `${this.eventPrefix}_prompt_completed`) {
54908
- const usage = this.toUsageData(raw.usage) ?? this.lastUsage;
54909
- const costUsd = this.toCostUsd(raw.cost) ?? this.lastCostUsd;
54910
- return this.complete(raw.stopReason, usage, costUsd);
54911
- }
54912
- if (raw.type === `${this.eventPrefix}_error`) return this.fail(stringify(raw.message) || `${this.provider} ACP failed`);
54913
- switch (raw.sessionUpdate) {
54914
- case "usage_update": {
54915
- const usage = this.extractUsageFromUsageUpdate(raw);
54916
- if (usage) this.lastUsage = usage;
54917
- const costUsd = this.toCostUsd(raw.cost);
54918
- if (costUsd !== void 0) this.lastCostUsd = costUsd;
54919
- return [];
54920
- }
54921
- case "agent_message_chunk": {
54922
- const text = raw.content?.text;
54923
- return typeof text === "string" && text ? [...this.stream.ensureStream(true), this.stream.event("stream_chunk", {
54924
- chunkType: "text",
54925
- content: text
54926
- })] : [];
54927
- }
54928
- case "agent_thought_chunk": {
54929
- const reasoning = raw.content?.text;
54930
- return typeof reasoning === "string" && reasoning ? [...this.stream.ensureStream(true), this.stream.event("stream_chunk", {
54931
- chunkType: "reasoning",
54932
- reasoning
54933
- })] : [];
54934
- }
54935
- case "tool_call": return this.startTool(raw);
54936
- case "tool_call_update": return this.updateTool(raw);
54937
- default: return [];
54938
- }
54939
- }
54940
- flush() {
54941
- if (this.terminal) return [];
54942
- return this.complete("end_turn", this.lastUsage, this.lastCostUsd);
54943
- }
54944
- updateTool(raw) {
54945
- const id = raw.toolCallId;
54946
- if (typeof id !== "string" || this.completedTools.has(id)) return [];
54947
- const startEvents = this.pendingTools.has(id) ? [] : this.startTool(raw);
54948
- const resultState = this.mergeToolResultState(id, raw);
54949
- if (raw.status === "running" || raw.status === "in_progress" || raw.status === "pending") {
54950
- const snapshotSeq = (this.snapshotSeq.get(id) ?? 0) + 1;
54951
- this.snapshotSeq.set(id, snapshotSeq);
54952
- return [...startEvents, this.stream.event("stream_chunk", {
54953
- chunkType: "tool_state",
54954
- pluginState: { ...raw },
54955
- snapshotMode: "replace",
54956
- snapshotSeq,
54957
- toolCallId: id
54958
- })];
54959
- }
54960
- if (raw.status !== "completed" && raw.status !== "failed") return [];
54961
- this.completedTools.add(id);
54962
- this.pendingTools.delete(id);
54963
- const isSuccess = raw.status === "completed";
54964
- const result = resultState.latest === "content" ? toolContent(resultState.content, resultState.rawOutput ?? resultState.output) : stringify(resultState.latest === "rawOutput" ? resultState.rawOutput : resultState.output);
54965
- const events = [
54966
- ...startEvents,
54967
- this.stream.event("tool_result", {
54968
- content: result,
54969
- isError: !isSuccess,
54970
- toolCallId: id
54971
- }),
54972
- this.stream.event("tool_end", {
54973
- isSuccess,
54974
- toolCallId: id
54975
- })
54976
- ];
54977
- if (this.pendingTools.size === 0) this.stream.pendingStepBoundary = true;
54978
- return events;
54979
- }
54980
- startTool(raw) {
54981
- const id = raw.toolCallId;
54982
- if (typeof id !== "string" || this.completedTools.has(id)) return [];
54983
- this.mergeToolResultState(id, raw);
54984
- if (this.pendingTools.has(id)) return [];
54985
- const payload = {
54986
- apiName: [
54987
- raw.name,
54988
- raw.title,
54989
- raw.kind
54990
- ].find((value) => typeof value === "string" && value.length > 0) ?? "unknown",
54991
- arguments: stringify(raw.rawInput ?? raw.input ?? raw.parameters ?? {}),
54992
- id,
54993
- identifier: typeof raw.identifier === "string" && raw.identifier ? raw.identifier : this.provider,
54994
- type: "default"
54995
- };
54996
- const streamEvents = this.stream.ensureStream(true);
54997
- this.pendingTools.add(id);
54998
- this.stream.stepTools.push(payload);
54999
- return [
55000
- ...streamEvents,
55001
- this.stream.event("stream_chunk", {
55002
- chunkType: "tools_calling",
55003
- toolsCalling: [...this.stream.stepTools]
55004
- }),
55005
- this.stream.event("tool_start", {
55006
- toolCalling: payload,
55007
- toolCallId: id
55008
- })
55009
- ];
55010
- }
55011
- mergeToolResultState(toolCallId, raw) {
55012
- const state = this.toolResultStateById.get(toolCallId) ?? {};
55013
- if (raw.content !== void 0) state.content = raw.content;
55014
- if (raw.rawOutput !== void 0) state.rawOutput = raw.rawOutput;
55015
- if (raw.output !== void 0) state.output = raw.output;
55016
- if (raw.content !== void 0) state.latest = "content";
55017
- else if (raw.rawOutput !== void 0) state.latest = "rawOutput";
55018
- else if (raw.output !== void 0) state.latest = "output";
55019
- this.toolResultStateById.set(toolCallId, state);
55020
- return state;
55021
- }
55022
- closePending() {
55023
- const events = [...this.pendingTools].map((toolCallId) => this.stream.event("tool_end", {
55024
- isSuccess: false,
55025
- toolCallId
55026
- }));
55027
- this.pendingTools.clear();
55028
- return events;
55029
- }
55030
- complete(stopReason, usage, costUsd) {
55031
- if (this.terminal) return [];
55032
- this.terminal = true;
55033
- const runtimeEndData = stopReason === "cancelled" ? {
55034
- reason: "interrupted",
55035
- stopReason
55036
- } : { stopReason };
55037
- const result = [
55038
- ...this.closePending(),
55039
- ...this.stream.closeStream({ stopReason }),
55040
- this.stream.event("visible_output_end", {})
55041
- ];
55042
- if (usage) {
55043
- if (costUsd !== void 0) usage.cost = costUsd;
55044
- const stepCompleteData = {
55045
- model: this.model,
55046
- phase: "turn_metadata",
55047
- provider: this.provider,
55048
- usage
55049
- };
55050
- result.push(this.stream.event("step_complete", stepCompleteData));
55051
- }
55052
- result.push(this.stream.event("agent_runtime_end", runtimeEndData));
55053
- return result;
55054
- }
55055
- /**
55056
- * Convert an ACP experimental `Usage` shape into the shared `UsageData`.
55057
- * Returns `undefined` when required fields are missing or invalid.
55058
- */
55059
- toUsageData(usage) {
55060
- if (!isRecord$8(usage)) return;
55061
- const total = toFiniteNumber$2(usage.totalTokens) ?? toFiniteNumber$2(usage.total_tokens);
55062
- const input = toFiniteNumber$2(usage.inputTokens) ?? toFiniteNumber$2(usage.input_tokens);
55063
- const output = toFiniteNumber$2(usage.outputTokens) ?? toFiniteNumber$2(usage.output_tokens);
55064
- if (typeof input !== "number" || typeof output !== "number" || input < 0 || output < 0) return;
55065
- const cachedRead = toFiniteNumber$2(usage.cachedReadTokens) ?? toFiniteNumber$2(usage.cached_read_tokens) ?? toFiniteNumber$2(usage.cacheReadTokens) ?? toFiniteNumber$2(usage.cache_read_tokens) ?? 0;
55066
- const cachedWrite = toFiniteNumber$2(usage.cachedWriteTokens) ?? toFiniteNumber$2(usage.cached_write_tokens) ?? toFiniteNumber$2(usage.cacheWriteTokens) ?? toFiniteNumber$2(usage.cache_write_tokens) ?? 0;
55067
- const thought = toFiniteNumber$2(usage.thoughtTokens) ?? toFiniteNumber$2(usage.thought_tokens) ?? toFiniteNumber$2(usage.reasoningTokens) ?? toFiniteNumber$2(usage.reasoning_tokens) ?? 0;
55068
- const inputCacheMiss = Math.max(0, input - cachedRead);
55069
- const outputText = Math.max(0, output - thought);
55070
- const totalTokens = total ?? input + output + cachedWrite;
55071
- return {
55072
- inputCachedTokens: cachedRead || void 0,
55073
- inputCacheMissTokens: inputCacheMiss,
55074
- inputWriteCacheTokens: cachedWrite || void 0,
55075
- outputReasoningTokens: thought || void 0,
55076
- outputTextTokens: outputText,
55077
- totalInputTokens: input + cachedWrite,
55078
- totalOutputTokens: output,
55079
- totalTokens
55080
- };
55081
- }
55082
- /**
55083
- * Extract token usage from a `usage_update` notification.
55084
- * The ACP spec only requires `used`/`size`/`cost`; per-turn token breakdown
55085
- * lives in `_meta` as vendor extensions. Subclasses may override this to
55086
- * parse provider-specific `_meta` keys (e.g. `cognition.ai/*Tokens`).
55087
- */
55088
- extractUsageFromUsageUpdate(_raw) {}
55089
- /** Extract a USD cost amount from an ACP `cost` object. */
55090
- toCostUsd(cost) {
55091
- if (!isRecord$8(cost)) return;
55092
- if (cost.currency !== "USD") return;
55093
- const amount = toFiniteNumber$2(cost.amount);
55094
- if (amount === void 0 || amount <= 0) return;
55095
- return amount;
55096
- }
55097
- fail(message) {
55098
- if (this.terminal) return [];
55099
- this.terminal = true;
55100
- return [
55101
- ...this.closePending(),
55102
- ...this.stream.closeStream(),
55103
- this.stream.event("visible_output_end", {}),
55104
- this.stream.event("error", {
55105
- agentType: this.provider,
55106
- error: message,
55107
- message
55108
- })
55109
- ];
55110
- }
55111
- };
55112
-
55113
54897
  //#endregion
55114
54898
  //#region ../../packages/heterogeneous-agents/src/adapters/copilotAcp.ts
55115
54899
  /**
@@ -56669,7 +56453,7 @@ const getHeterogeneousTypeLabel = (type) => {
56669
56453
  * by registering here — no other code changes needed.
56670
56454
  */
56671
56455
  const localAgentRegistry = {
56672
- "antigravity": { createAdapter: () => new AntigravityAdapter() },
56456
+ "antigravity": { createAdapter: () => new AntigravityAcpAdapter() },
56673
56457
  "amp": { createAdapter: () => new AmpAdapter() },
56674
56458
  "claude-code": { createAdapter: () => new ClaudeCodeAdapter() },
56675
56459
  "codebuddy": { createAdapter: () => new CodeBuddyAdapter() },
@@ -56710,7 +56494,7 @@ const createAdapter = (agentType) => {
56710
56494
  };
56711
56495
 
56712
56496
  //#endregion
56713
- //#region node_modules/.pnpm/@lobehub+icons@6.19.0_@lobehub+ui@6.19.1_lucide-react@1.77.0_@types+react@19.2.13_react_8f84f0bc5dacb5092d1bb5a96930f7fd/node_modules/@lobehub/icons/es/features/getLobeIconCDN/index.mjs
56497
+ //#region node_modules/.pnpm/@lobehub+icons@6.20.0_@lobehub+ui@6.19.1_lucide-react@1.77.0_@types+react@19.2.13_react_712a9c1aa2e96b0b3f2c3e4bcad70c75/node_modules/@lobehub/icons/es/features/getLobeIconCDN/index.mjs
56714
56498
  const GITHUB_ICON_CDN = (type) => `https://raw.githubusercontent.com/lobehub/lobe-icons/refs/heads/master/packages/static-${type}`;
56715
56499
  const ALIYUN_ICON_CDN = (type) => `https://registry.npmmirror.com/@lobehub/icons-static-${type}/latest/files`;
56716
56500
  const UNPKG_ICON_CDN = (type) => `https://unpkg.com/@lobehub/icons-static-${type}@latest`;
@@ -70641,14 +70425,6 @@ const QUOTA_SOURCE_LABELS = {
70641
70425
 
70642
70426
  //#endregion
70643
70427
  //#region ../../packages/heterogeneous-agents/src/spawn/antigravity.ts
70644
- /** agy reads a single JSONL user message, then finishes the turn when stdin closes. */
70645
- const ANTIGRAVITY_BASE_ARGS = [
70646
- "--input-format",
70647
- "stream-json",
70648
- "--output-format",
70649
- "stream-json",
70650
- "--dangerously-skip-permissions"
70651
- ];
70652
70428
  /** A Connect service can inherit an old SSH session that makes agy skip the desktop keyring. */
70653
70429
  const getAntigravitySpawnEnv = (env) => {
70654
70430
  if (env.LOBEHUB_CONNECT_SERVICE !== "1") return env;
@@ -70658,39 +70434,53 @@ const getAntigravitySpawnEnv = (env) => {
70658
70434
  delete childEnv.SSH_TTY;
70659
70435
  return childEnv;
70660
70436
  };
70661
- const FULL_ACCESS_SETTINGS = JSON.stringify({
70662
- agentMode: "",
70663
- allowNonWorkspaceAccess: true,
70664
- enableTerminalSandbox: false
70665
- });
70437
+ /**
70438
+ * Flags LobeHub owns: the ACP session carries the prompt, output and
70439
+ * conversation, and `agy acp` has no per-run `--settings`.
70440
+ */
70666
70441
  const MANAGED_FLAGS = new Set([
70667
70442
  "--",
70443
+ "--continue",
70444
+ "--conversation",
70668
70445
  "--input-format",
70669
70446
  "--output-format",
70670
70447
  "--print",
70671
70448
  "--prompt",
70672
70449
  "--prompt-interactive",
70673
70450
  "--remote-control",
70674
- "-i",
70675
- "-p",
70676
- "--continue",
70451
+ "--settings",
70677
70452
  "-c",
70678
- "--conversation"
70453
+ "-i",
70454
+ "-p"
70679
70455
  ]);
70680
- const buildAntigravityArgs = ({ extraArgs = [], resumeSessionId }) => {
70681
- const conflicting = extraArgs.find((arg) => MANAGED_FLAGS.has(arg.split("=")[0]));
70682
- if (conflicting) throw new Error(`LobeHub manages Antigravity's prompt, output and session flags: ${conflicting}`);
70683
- const hasCustomPermissionSettings = extraArgs.some((arg) => [
70684
- "--mode",
70685
- "--sandbox",
70686
- "--settings"
70687
- ].includes(arg.split("=")[0]));
70688
- return [
70689
- ...ANTIGRAVITY_BASE_ARGS,
70690
- ...hasCustomPermissionSettings ? [] : ["--settings", FULL_ACCESS_SETTINGS],
70691
- ...resumeSessionId ? ["--conversation", resumeSessionId] : [],
70692
- ...extraArgs
70693
- ];
70456
+ /** Selector flags applied through ACP `session/set_config_option` instead of argv. */
70457
+ const SESSION_CONFIG_FLAGS = {
70458
+ "--effort": "effort",
70459
+ "--mode": "mode",
70460
+ "--model": "model"
70461
+ };
70462
+ /**
70463
+ * Split user/selector args into the `agy acp` argv and the session options
70464
+ * ACP sets per session (`--model` full ids such as `gemini-4-neon-xhigh`,
70465
+ * `--effort`, `--mode`). Tool permissions are always auto-approved, as the
70466
+ * print-mode runs were.
70467
+ */
70468
+ const buildAntigravityAcpLaunch = (extraArgs = []) => {
70469
+ const launch = { args: ["acp", "--dangerously-skip-permissions"] };
70470
+ for (let index = 0; index < extraArgs.length; index += 1) {
70471
+ const arg = extraArgs[index];
70472
+ const [flag, inlineValue] = arg.split(/=(.*)/s, 2);
70473
+ if (MANAGED_FLAGS.has(flag)) throw new Error(`LobeHub manages Antigravity's prompt, session and settings flags: ${flag}`);
70474
+ const key = SESSION_CONFIG_FLAGS[flag];
70475
+ if (!key) {
70476
+ if (arg !== "--dangerously-skip-permissions") launch.args.push(arg);
70477
+ continue;
70478
+ }
70479
+ const value = inlineValue ?? extraArgs[++index];
70480
+ if (!value?.trim()) throw new Error(`Antigravity flag ${flag} needs a value`);
70481
+ launch[key] = value.trim();
70482
+ }
70483
+ return launch;
70694
70484
  };
70695
70485
 
70696
70486
  //#endregion
@@ -71674,12 +71464,7 @@ var init_resolveCliCommand = __esmMin((() => {
71674
71464
  detectValidatedCommand = async (command, options, probeEnv) => detectValidatedCommandCandidates([command], options, probeEnv);
71675
71465
  HETEROGENEOUS_CLI_AGENT_OPTIONS = {
71676
71466
  "antigravity": {
71677
- validateHelpKeywords: [
71678
- "--input-format",
71679
- "--output-format",
71680
- "--conversation",
71681
- "stream-json"
71682
- ],
71467
+ validateHelpKeywords: ["Agent Client Protocol"],
71683
71468
  validatePattern: /^(?:(?:agy|antigravity(?: cli)?) (?:version )?)?v?\d+\.\d+\.\d+(?:-[\dA-Z.-]+)?(?:\+[\dA-Z.-]+)?$/i
71684
71469
  },
71685
71470
  "amp": {
@@ -73381,7 +73166,6 @@ const buildQoderInput = async (blocks, options) => {
73381
73166
  * extra CLI args required to attach images. The single source of truth for
73382
73167
  * how each external agent CLI receives multimodal input.
73383
73168
  *
73384
- * - `antigravity`: stream-json text on stdin with local paths for the built-in image reader
73385
73169
  * - `amp` / `claude-code` / `codebuddy`: stream-json on stdin with text + base64 image content blocks
73386
73170
  * - `codex`: raw text on stdin + repeatable `--image <path>` flags
73387
73171
  * - `kimi-code`: `--prompt <text>` with materialized image paths referenced in the text
@@ -73395,18 +73179,6 @@ const buildQoderInput = async (blocks, options) => {
73395
73179
  const buildAgentInput = async (agentType, prompt, options = {}) => {
73396
73180
  const blocks = toBlocks$1(prompt);
73397
73181
  switch (agentType) {
73398
- case "antigravity": {
73399
- const imagePaths = await resolvePathInputImagePaths(blocks, options);
73400
- const attachments = imagePaths.length ? ["Use your built-in image-reading tool to inspect the attached images before answering:", ...imagePaths.map((imagePath) => `- ${JSON.stringify(path.resolve(imagePath))}`)].join("\n") : "";
73401
- const content = [collectText(blocks), attachments].filter(Boolean).join("\n\n");
73402
- return {
73403
- args: [],
73404
- stdin: `${JSON.stringify({
73405
- event: "user",
73406
- message: { content }
73407
- })}\n`
73408
- };
73409
- }
73410
73182
  case "amp":
73411
73183
  case "claude-code":
73412
73184
  case "codebuddy": return buildClaudeCompatibleStdin(blocks, options);
@@ -76154,158 +75926,642 @@ var AcpAgentSession = class {
76154
75926
  };
76155
75927
 
76156
75928
  //#endregion
76157
- //#region ../../packages/heterogeneous-agents/src/spawn/antigravityLiveInput.ts
75929
+ //#region ../../packages/heterogeneous-agents/src/spawn/traeAcpSession.ts
75930
+ const NOTIFICATION_DRAIN_QUIET_MS$2 = 250;
75931
+ const NOTIFICATION_DRAIN_TIMEOUT_MS$2 = 2e3;
75932
+ const TRANSPORT$5 = "trae-acp";
75933
+ const sleep$7 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
75934
+ const TRAE_GLOBAL_VALUE_FLAGS = new Set([
75935
+ "--config",
75936
+ "--permission-mode",
75937
+ "--profile",
75938
+ "-c",
75939
+ "-p"
75940
+ ]);
75941
+ const isInlineTraeGlobalArg = (arg) => arg.startsWith("--config=") || arg.startsWith("--permission-mode=") || arg.startsWith("--profile=") || arg.startsWith("-c=") || arg.startsWith("-p=");
76158
75942
  /**
76159
- * How long a live Antigravity session may sit between turns with no stdout
76160
- * before stdin is closed anyway.
75943
+ * TRAE requires configuration flags before `acp serve`, while ACP Server flags
75944
+ * belong after it. Keep unknown/user server flags in their historical position
75945
+ * and move only the documented global flags plus their values.
75946
+ * @see https://docs.trae.cn/cli_agent-client-protocol
76161
75947
  */
76162
- const DEFAULT_IDLE_CLOSE_MS$1 = 1800 * 1e3;
76163
- const readIdleCloseMs$1 = () => {
76164
- const value = Number(process.env.LOBE_ANTIGRAVITY_LIVE_INPUT_IDLE_MS);
76165
- return Number.isFinite(value) && value > 0 ? value : DEFAULT_IDLE_CLOSE_MS$1;
75948
+ const buildTraeAcpArgs = (args = []) => {
75949
+ const globalArgs = [];
75950
+ const serverArgs = [];
75951
+ for (let index = 0; index < args.length; index += 1) {
75952
+ const arg = args[index];
75953
+ if (TRAE_GLOBAL_VALUE_FLAGS.has(arg)) {
75954
+ globalArgs.push(arg);
75955
+ const value = args[index + 1];
75956
+ if (value !== void 0) {
75957
+ globalArgs.push(value);
75958
+ index += 1;
75959
+ }
75960
+ continue;
75961
+ }
75962
+ if (isInlineTraeGlobalArg(arg)) {
75963
+ globalArgs.push(arg);
75964
+ continue;
75965
+ }
75966
+ serverArgs.push(arg);
75967
+ }
75968
+ return [
75969
+ ...globalArgs,
75970
+ "acp",
75971
+ "serve",
75972
+ "--yolo",
75973
+ ...serverArgs
75974
+ ];
75975
+ };
75976
+ const buildTraeAcpPrompt = async (prompt, options = {}) => {
75977
+ const blocks = typeof prompt === "string" ? [{
75978
+ text: prompt,
75979
+ type: "text"
75980
+ }] : prompt;
75981
+ const result = [];
75982
+ for (const block of blocks) if (block.type === "text") result.push({
75983
+ text: block.text,
75984
+ type: "text"
75985
+ });
75986
+ else {
75987
+ const image = await normalizeImage(block.source, options);
75988
+ result.push({
75989
+ data: image.buffer.toString("base64"),
75990
+ mimeType: image.mediaType,
75991
+ type: "image"
75992
+ });
75993
+ }
75994
+ return result;
75995
+ };
75996
+ const toTraeModel = (id, name) => ({
75997
+ id,
75998
+ ...typeof name === "string" && name && name !== id ? { label: name } : {},
75999
+ modelId: id,
76000
+ providerId: "trae"
76001
+ });
76002
+ const parseConfigOptionModels$1 = (options) => {
76003
+ if (!Array.isArray(options)) return [];
76004
+ const values = options.flatMap((value) => {
76005
+ const option = value;
76006
+ return Array.isArray(option?.options) ? option.options : [value];
76007
+ });
76008
+ const seen = /* @__PURE__ */ new Set();
76009
+ const models = [];
76010
+ for (const value of values) {
76011
+ const option = value;
76012
+ if (typeof option?.value !== "string" || !option.value || seen.has(option.value)) continue;
76013
+ seen.add(option.value);
76014
+ models.push(toTraeModel(option.value, option.name));
76015
+ }
76016
+ return models;
76166
76017
  };
76167
76018
  /**
76168
- * The runtime end a live Antigravity session (stdin kept open, see
76169
- * `AntigravityLiveInput`) reports once, at process exit.
76019
+ * Read model selection from the current stable ACP config-options API, with a
76020
+ * compatibility fallback for the never-stabilized dedicated model API still
76021
+ * exposed by older TRAE CLI builds.
76170
76022
  */
76171
- const resolveAntigravityLiveRuntimeEnd = (lastTurn, exit) => {
76172
- if (!lastTurn?.ok || exit.killedByHost || exit.sawError) return;
76173
- if (exit.code !== 0) return;
76023
+ const parseTraeAcpModelCatalog = (result) => {
76024
+ const selectableOptions = (Array.isArray(result?.configOptions) ? result.configOptions.map((value) => value) : []).filter((option) => option?.type === void 0 || option.type === "select");
76025
+ const modelConfig = selectableOptions.find((option) => option?.category === "model") ?? selectableOptions.find((option) => option?.id === "model") ?? selectableOptions.find((option) => typeof option?.name === "string" && option.name.toLowerCase() === "model");
76026
+ if (modelConfig && typeof modelConfig.id === "string" && modelConfig.id) return {
76027
+ configId: modelConfig.id,
76028
+ currentModelId: typeof modelConfig.currentValue === "string" ? modelConfig.currentValue : void 0,
76029
+ models: parseConfigOptionModels$1(modelConfig.options),
76030
+ protocol: "config-option"
76031
+ };
76032
+ if (!Array.isArray(result?.models?.availableModels)) return;
76033
+ const seen = /* @__PURE__ */ new Set();
76034
+ const models = [];
76035
+ for (const value of result.models.availableModels) {
76036
+ const option = value;
76037
+ if (typeof option?.modelId !== "string" || !option.modelId || seen.has(option.modelId)) continue;
76038
+ seen.add(option.modelId);
76039
+ models.push(toTraeModel(option.modelId, option.name));
76040
+ }
76174
76041
  return {
76175
- reason: "complete",
76176
- transport: "cli-live"
76042
+ currentModelId: typeof result.models.currentModelId === "string" ? result.models.currentModelId : void 0,
76043
+ models,
76044
+ protocol: "legacy-model"
76177
76045
  };
76178
76046
  };
76047
+ /** TRAE's ACP v1 lifecycle: model config-options and legacy model API on the shared base. */
76048
+ var TraeAcpSession = class TraeAcpSession extends AcpAgentSession {
76049
+ acceptUpdates = false;
76050
+ lastSessionUpdateAt = 0;
76051
+ modelDiscovery;
76052
+ resolvedPrompt = [];
76053
+ constructor(options) {
76054
+ super(options, {
76055
+ args: buildTraeAcpArgs(options.args),
76056
+ pipeline: { agentType: "trae" },
76057
+ processLabel: "TRAE ACP",
76058
+ transport: TRANSPORT$5
76059
+ });
76060
+ }
76061
+ get nativeSessionId() {
76062
+ return this.acpSessionId;
76063
+ }
76064
+ /** Create a short-lived ACP session and read its agent-provided model selector. */
76065
+ async discoverModels() {
76066
+ return (await this.discoverModelCatalog()).models;
76067
+ }
76068
+ async prepareRun() {
76069
+ this.resolvedPrompt = await this.resolvePrompt();
76070
+ }
76071
+ buildInitializeParams() {
76072
+ return {
76073
+ clientCapabilities: {},
76074
+ clientInfo: {
76075
+ name: "lobehub",
76076
+ title: "LobeHub",
76077
+ version: this.options.clientVersion
76078
+ },
76079
+ protocolVersion: 1
76080
+ };
76081
+ }
76082
+ validateInitialized(initialized) {
76083
+ if (typeof initialized?.protocolVersion === "number" && initialized.protocolVersion !== 1) throw new Error(`TRAE ACP returned unsupported protocol version: ${initialized.protocolVersion}`);
76084
+ }
76085
+ async establishSession(initialized) {
76086
+ if (this.resolvedPrompt.some((block) => block.type === "image") && initialized?.agentCapabilities?.promptCapabilities?.image !== true) throw new Error("TRAE ACP agent does not support image prompt blocks");
76087
+ if (this.options.resumeSessionId && initialized?.agentCapabilities?.loadSession !== true) throw new Error("TRAE ACP agent does not support loading sessions");
76088
+ const sessionResult = await this.client.request(this.options.resumeSessionId ? "session/load" : "session/new", {
76089
+ cwd: this.options.cwd,
76090
+ mcpServers: [],
76091
+ ...this.options.resumeSessionId ? { sessionId: this.options.resumeSessionId } : {}
76092
+ });
76093
+ const sessionId = sessionResult?.sessionId ?? this.options.resumeSessionId;
76094
+ if (!sessionId) throw new Error("TRAE ACP returned no session id");
76095
+ this.acpSessionId = sessionId;
76096
+ this.options.onSessionId(sessionId);
76097
+ const model = await this.applyInitialModel(sessionId, sessionResult);
76098
+ if (model) {
76099
+ this.pipeline.configureSession({ model });
76100
+ this.options.onModel?.(model);
76101
+ }
76102
+ await this.pushToPipeline({
76103
+ model,
76104
+ sessionId,
76105
+ type: "trae_session"
76106
+ });
76107
+ return sessionId;
76108
+ }
76109
+ onBeforePrompt() {
76110
+ this.acceptUpdates = true;
76111
+ }
76112
+ buildPromptParams(sessionId) {
76113
+ return {
76114
+ prompt: this.resolvedPrompt,
76115
+ sessionId
76116
+ };
76117
+ }
76118
+ async settlePrompt(result) {
76119
+ await this.drainNotifications();
76120
+ await this.client.drain();
76121
+ await this.pushToPipeline({
76122
+ stopReason: result?.stopReason,
76123
+ type: "trae_prompt_completed"
76124
+ });
76125
+ }
76126
+ async onRunFailure(error) {
76127
+ await this.pushToPipeline({
76128
+ message: error.message,
76129
+ type: "trae_error"
76130
+ });
76131
+ await this.emitEvents(await this.pipeline.flush());
76132
+ }
76133
+ async onRunCancelled() {
76134
+ await this.pushToPipeline({
76135
+ stopReason: "cancelled",
76136
+ type: "trae_prompt_completed"
76137
+ });
76138
+ }
76139
+ onHostClose() {
76140
+ this.modelDiscovery?.close();
76141
+ }
76142
+ async handleAgentMessage(message) {
76143
+ if (message.method !== "session/update") return;
76144
+ if (!this.acceptUpdates) return;
76145
+ this.lastSessionUpdateAt = Date.now();
76146
+ const update = message.params?.update;
76147
+ if (!update || typeof update !== "object") return;
76148
+ if (update.sessionUpdate === "config_option_update") {
76149
+ const catalog = parseTraeAcpModelCatalog({ configOptions: update.configOptions });
76150
+ if (catalog?.currentModelId) {
76151
+ this.pipeline.configureSession({ model: catalog.currentModelId });
76152
+ this.options.onModel?.(catalog.currentModelId);
76153
+ }
76154
+ }
76155
+ await this.pushToPipeline(update);
76156
+ }
76157
+ handleServerRequest(message) {
76158
+ if (message.method === "session/request_permission") {
76159
+ const optionId = selectAcpPermissionOption(message.params, [
76160
+ (option) => option.optionId === "allow_session" || option.optionId === "approve_for_session",
76161
+ (option) => option.kind === "allow_once",
76162
+ (option) => option.kind === "reject_once"
76163
+ ]);
76164
+ if (optionId) return { outcome: {
76165
+ optionId,
76166
+ outcome: "selected"
76167
+ } };
76168
+ throw new AcpServerRequestError(-32603, "No safe permission option was offered");
76169
+ }
76170
+ throw new AcpServerRequestError(-32601, `Unsupported ACP client request: ${message.method}`);
76171
+ }
76172
+ async discoverModelCatalog() {
76173
+ try {
76174
+ const initialized = await this.initializeConnection();
76175
+ const sessionResult = await this.client.request("session/new", {
76176
+ cwd: this.options.cwd,
76177
+ mcpServers: []
76178
+ });
76179
+ if (!sessionResult?.sessionId) throw new Error("TRAE ACP returned no session id");
76180
+ const catalog = parseTraeAcpModelCatalog(sessionResult);
76181
+ if (!catalog) throw new Error("TRAE ACP did not expose a model configuration option");
76182
+ if (initialized?.agentCapabilities?.sessionCapabilities?.close) await this.client.request("session/close", { sessionId: sessionResult.sessionId });
76183
+ return catalog;
76184
+ } finally {
76185
+ this.client.close();
76186
+ }
76187
+ }
76188
+ async resolvePrompt() {
76189
+ const prompt = this.options.prompt;
76190
+ if (Array.isArray(prompt) && prompt.every((block) => "type" in block && (block.type === "text" || "data" in block && block.type === "image"))) return prompt;
76191
+ return buildTraeAcpPrompt(prompt, this.options.inputOptions);
76192
+ }
76193
+ async applyInitialModel(sessionId, sessionResult) {
76194
+ let catalog = parseTraeAcpModelCatalog(sessionResult);
76195
+ const requestedModel = this.options.initialModel?.trim();
76196
+ if (!requestedModel || requestedModel === "default") return catalog?.currentModelId;
76197
+ if (!catalog && this.options.resumeSessionId) catalog = await this.discoverResumeModelCatalog();
76198
+ if (!catalog) throw new Error("TRAE ACP did not expose a model configuration option");
76199
+ const selected = catalog.models.find((model) => model.id === requestedModel || model.label === requestedModel);
76200
+ if (!selected) throw new Error(`TRAE ACP model is unavailable: ${requestedModel}`);
76201
+ if (catalog.protocol === "config-option") return parseTraeAcpModelCatalog({ configOptions: (await this.client.request("session/set_config_option", {
76202
+ configId: catalog.configId,
76203
+ sessionId,
76204
+ value: selected.id
76205
+ }))?.configOptions })?.currentModelId ?? selected.id;
76206
+ await this.client.request("session/set_model", {
76207
+ modelId: selected.id,
76208
+ sessionId
76209
+ });
76210
+ return selected.id;
76211
+ }
76212
+ async discoverResumeModelCatalog() {
76213
+ const discovery = new TraeAcpSession({
76214
+ ...this.options,
76215
+ initialModel: void 0,
76216
+ onEvents: () => {},
76217
+ onModel: void 0,
76218
+ onRuntimeStatus: () => {},
76219
+ onSessionId: () => {},
76220
+ operationId: `${this.options.operationId}-model-discovery`,
76221
+ prompt: "",
76222
+ resumeSessionId: void 0,
76223
+ sessionId: `${this.options.sessionId}-model-discovery`
76224
+ });
76225
+ this.modelDiscovery = discovery;
76226
+ try {
76227
+ return await discovery.discoverModelCatalog();
76228
+ } finally {
76229
+ discovery.close();
76230
+ if (this.modelDiscovery === discovery) this.modelDiscovery = void 0;
76231
+ }
76232
+ }
76233
+ async drainNotifications() {
76234
+ const deadline = Date.now() + NOTIFICATION_DRAIN_TIMEOUT_MS$2;
76235
+ let quietSince = Date.now();
76236
+ while (Date.now() < deadline) {
76237
+ await sleep$7(Math.min(NOTIFICATION_DRAIN_QUIET_MS$2, deadline - Date.now()));
76238
+ await this.client.drain();
76239
+ if (this.lastSessionUpdateAt > quietSince) {
76240
+ quietSince = this.lastSessionUpdateAt;
76241
+ continue;
76242
+ }
76243
+ if (Date.now() - quietSince >= NOTIFICATION_DRAIN_QUIET_MS$2) return;
76244
+ }
76245
+ }
76246
+ };
76247
+ const listTraeAcpModels = async (options) => new TraeAcpSession({
76248
+ args: options.args ?? [],
76249
+ clientVersion: options.clientVersion ?? "1.0.0",
76250
+ commandPath: options.commandPath,
76251
+ cwd: options.cwd,
76252
+ env: options.env,
76253
+ onEvents: () => {},
76254
+ onRawMessage: () => {},
76255
+ onRuntimeStatus: () => {},
76256
+ onSessionId: () => {},
76257
+ onStderr: () => {},
76258
+ operationId: "trae-model-discovery",
76259
+ prompt: "",
76260
+ requestTimeoutMs: options.timeoutMs,
76261
+ sessionId: "trae-model-discovery"
76262
+ }).discoverModels();
76263
+
76264
+ //#endregion
76265
+ //#region ../../packages/heterogeneous-agents/src/spawn/antigravityAcpSession.ts
76266
+ init_object$1();
76267
+ const TRANSPORT$4 = "antigravity-acp";
76268
+ const USAGE_FIELDS = [
76269
+ "inputTokens",
76270
+ "outputTokens",
76271
+ "cachedReadTokens",
76272
+ "thoughtTokens"
76273
+ ];
76274
+ const findConfigOption = (configOptions, id) => Array.isArray(configOptions) ? configOptions.find((value) => isRecord$8(value) && value.id === id) : void 0;
76275
+ const configValue = (configOptions, id) => {
76276
+ const option = findConfigOption(configOptions, id);
76277
+ return isRecord$8(option) && typeof option.currentValue === "string" ? option.currentValue : void 0;
76278
+ };
76279
+ /** Values of a select option, flattening grouped options. */
76280
+ const configOptionValues = (configOptions, id) => {
76281
+ const option = findConfigOption(configOptions, id);
76282
+ const collect = (entries) => Array.isArray(entries) ? entries.flatMap((entry) => {
76283
+ if (!isRecord$8(entry)) return [];
76284
+ if (Array.isArray(entry.options)) return collect(entry.options);
76285
+ return typeof entry.value === "string" ? [entry.value] : [];
76286
+ }) : [];
76287
+ return isRecord$8(option) ? collect(option.options) : [];
76288
+ };
76289
+ const availableModelIds = (result) => {
76290
+ const models = result.models?.availableModels;
76291
+ return new Set(Array.isArray(models) ? models.flatMap((model) => isRecord$8(model) && typeof model.modelId === "string" ? [model.modelId] : []) : []);
76292
+ };
76179
76293
  /**
76180
- * Keeps an Antigravity (`--input-format stream-json --output-format stream-json`)
76181
- * stdin open while a turn is active or steered follow-ups remain unconsumed,
76182
- * then closes stdin as soon as the session becomes idle so the process exits cleanly.
76294
+ * The `model` value agy takes for a selection. The selector groups `agy models`
76295
+ * slugs into a model and an effort (`gpt-oss-120b` + `medium`), but a model
76296
+ * whose thinking tier is fixed only exists under its full slug
76297
+ * (`gpt-oss-120b-medium`).
76183
76298
  */
76184
- var AntigravityLiveInput = class {
76185
- closed = false;
76186
- idleCloseMs;
76187
- idleTimer;
76188
- initialUserInputSeen = false;
76189
- lastOutcome;
76190
- lineBuffer = "";
76191
- pendingAdapterUuids = [];
76192
- seenUserInputSteps = /* @__PURE__ */ new Set();
76193
- sessionId;
76194
- turnOpen = false;
76195
- unconsumed = [];
76196
- constructor(stdin, options = {}) {
76197
- this.stdin = stdin;
76198
- this.idleCloseMs = options.idleCloseMs ?? readIdleCloseMs$1();
76199
- stdin.on?.("close", () => this.markClosed());
76200
- stdin.on?.("error", () => this.markClosed());
76201
- }
76202
- get isOpen() {
76203
- return !this.closed && !this.stdin.destroyed && !this.stdin.writableEnded;
76299
+ const resolveModelValue = (model, effort, sessionResult) => {
76300
+ const known = new Set([...configOptionValues(sessionResult.configOptions, "model"), ...availableModelIds(sessionResult)]);
76301
+ if (known.size === 0 || known.has(model)) return model;
76302
+ if (effort && known.has(`${model}-${effort}`)) return `${model}-${effort}`;
76303
+ const variants = [...known].filter((id) => id.startsWith(`${model}-`));
76304
+ return variants.length === 1 ? variants[0] : model;
76305
+ };
76306
+ const buildAntigravityAcpPrompt = (prompt, options = {}) => buildTraeAcpPrompt(prompt, options);
76307
+ /** The response to a `session/prompt`: it carries a stop reason, or failed as one. */
76308
+ const isPromptResponse = (message) => {
76309
+ if (message.method !== void 0 || message.id === void 0) return false;
76310
+ if (message.error) return message.requestMethod === "session/prompt";
76311
+ return isRecord$8(message.result) && "stopReason" in message.result;
76312
+ };
76313
+ /**
76314
+ * Antigravity over `agy acp`. One run is one user turn; a message the user
76315
+ * sends while it runs is steered in with another `session/prompt`: agy ends
76316
+ * the pending prompt (`end_turn`) and carries on with the new one inside the
76317
+ * same work. The run ends when the latest prompt settles.
76318
+ */
76319
+ var AntigravityAcpSession = class extends AcpAgentSession {
76320
+ /** Session updates before the prompt (a `session/load` replay) are history, not output. */
76321
+ acceptUpdates = false;
76322
+ /** Read confirmations, chained so each lands before any update that follows it. */
76323
+ confirmations = Promise.resolve();
76324
+ launch;
76325
+ /** Prompt responses handled so far, in stdout order. */
76326
+ promptResponses = 0;
76327
+ /** Steered prompts written to agy, in order, that the run has not settled yet. */
76328
+ steers = [];
76329
+ steerCount = 0;
76330
+ steerable = false;
76331
+ unconfirmedSteers = [];
76332
+ usage = {
76333
+ cachedReadTokens: 0,
76334
+ inputTokens: 0,
76335
+ outputTokens: 0,
76336
+ thoughtTokens: 0
76337
+ };
76338
+ constructor(options) {
76339
+ const launch = buildAntigravityAcpLaunch(options.args);
76340
+ super(options, {
76341
+ args: launch.args,
76342
+ pipeline: {
76343
+ agentType: "antigravity",
76344
+ cwd: options.cwd
76345
+ },
76346
+ processLabel: "Antigravity ACP",
76347
+ transport: TRANSPORT$4
76348
+ });
76349
+ this.launch = launch;
76204
76350
  }
76205
- get lastTurn() {
76206
- return this.lastOutcome;
76351
+ get sessionId() {
76352
+ return this.acpSessionId;
76207
76353
  }
76208
76354
  /**
76209
- * Write one stream-json `user` line into the session. When `uuid` is given
76210
- * (a steered follow-up), stdin stays open across turn boundaries until `agy`
76211
- * picks up that message and finishes its turn.
76355
+ * Write a user message into the running turn. `false` when the run takes no
76356
+ * input now (not prompting yet, interrupted, or settling): nothing was
76357
+ * written, so the message can wait for the next run. agy confirms it read
76358
+ * the message when the prompt it interrupts returns, reported as
76359
+ * `step_complete { phase: 'user_message', uuid }`.
76212
76360
  */
76213
- send(stdinLine, uuid) {
76214
- if (!this.isOpen) return false;
76215
- if (uuid) {
76216
- this.unconsumed.push(uuid);
76217
- this.pendingAdapterUuids.push(uuid);
76218
- }
76219
- this.stdin.write(stdinLine);
76220
- this.clearIdleTimer();
76361
+ steer(prompt, uuid) {
76362
+ const sessionId = this.acpSessionId;
76363
+ if (!this.steerable || !sessionId || this.closedByHost) return false;
76364
+ const result = this.client.request("session/prompt", {
76365
+ prompt,
76366
+ sessionId
76367
+ }, false);
76368
+ result.catch(() => {});
76369
+ this.steers.push(result);
76370
+ const index = ++this.steerCount;
76371
+ if (this.promptResponses >= index) this.confirmSteer(uuid);
76372
+ else this.unconfirmedSteers.push({
76373
+ index,
76374
+ uuid
76375
+ });
76221
76376
  return true;
76222
76377
  }
76223
- /** Pop the next steered message UUID for `AntigravityAdapter` to confirm. */
76224
- takeSteerUuid() {
76225
- return this.pendingAdapterUuids.shift();
76378
+ interrupt() {
76379
+ this.steerable = false;
76380
+ super.interrupt();
76226
76381
  }
76227
- /** Feed raw stdout bytes from the child process. */
76228
- observe(chunk) {
76229
- this.lineBuffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
76230
- for (;;) {
76231
- const newline = this.lineBuffer.indexOf("\n");
76232
- if (newline === -1) break;
76233
- const line = this.lineBuffer.slice(0, newline).trim();
76234
- this.lineBuffer = this.lineBuffer.slice(newline + 1);
76235
- if (!line) continue;
76236
- try {
76237
- this.observeMessage(JSON.parse(line));
76238
- } catch {}
76382
+ buildInitializeParams() {
76383
+ return {
76384
+ clientCapabilities: {
76385
+ fs: {
76386
+ readTextFile: false,
76387
+ writeTextFile: false
76388
+ },
76389
+ terminal: false
76390
+ },
76391
+ clientInfo: {
76392
+ name: "lobehub",
76393
+ title: "LobeHub",
76394
+ version: this.options.clientVersion
76395
+ },
76396
+ protocolVersion: 1
76397
+ };
76398
+ }
76399
+ validateInitialized(initialized) {
76400
+ if (initialized.protocolVersion !== 1 && initialized.protocolVersion !== String(1)) throw new Error(`Antigravity ACP returned unsupported protocol version: ${String(initialized.protocolVersion)}`);
76401
+ if (this.options.prompt.some((block) => block.type === "image") && initialized.agentCapabilities?.promptCapabilities?.image !== true) throw new Error("This Antigravity CLI does not accept images over ACP. Update agy and retry.");
76402
+ }
76403
+ async establishSession(initialized) {
76404
+ const sessionResult = await this.openSession(initialized);
76405
+ const sessionId = sessionResult.sessionId ?? this.options.resumeSessionId;
76406
+ if (!sessionId) throw new Error("Antigravity ACP returned no session id");
76407
+ const model = await this.applySessionConfig(sessionId, sessionResult);
76408
+ if (model) {
76409
+ this.pipeline.configureSession({ model });
76410
+ this.options.onModel?.(model);
76239
76411
  }
76240
- if (this.closed) return;
76241
- if (this.turnOpen) this.clearIdleTimer();
76242
- else this.armIdleTimer();
76412
+ this.options.onSessionId(sessionId);
76413
+ await this.pushToPipeline({
76414
+ model,
76415
+ sessionId,
76416
+ type: "antigravity_session"
76417
+ });
76418
+ return sessionId;
76243
76419
  }
76244
- /** stdout ended: flush any trailing partial line and close stdin. */
76245
- finish() {
76246
- if (this.lineBuffer.trim()) this.observe("\n");
76247
- this.close();
76420
+ onBeforePrompt() {
76421
+ this.acceptUpdates = true;
76422
+ this.steerable = true;
76248
76423
  }
76249
- close() {
76250
- if (this.closed) return;
76251
- this.markClosed();
76252
- this.stdin.end();
76424
+ buildPromptParams(sessionId) {
76425
+ return {
76426
+ prompt: this.options.prompt,
76427
+ sessionId
76428
+ };
76253
76429
  }
76254
- observeMessage(message) {
76255
- if (!message || typeof message !== "object") return;
76256
- if (message.event === "init") {
76257
- if (typeof message.conversation_id === "string" && message.conversation_id) this.sessionId = message.conversation_id;
76258
- this.openTurn();
76259
- return;
76260
- }
76261
- if (message.event === "step_update" && message.step_update && typeof message.step_update === "object") {
76262
- const step = message.step_update;
76263
- const conversationId = typeof step.conversation_id === "string" && step.conversation_id ? step.conversation_id : void 0;
76264
- if (this.sessionId && conversationId && conversationId !== this.sessionId) return;
76265
- this.sessionId ??= conversationId;
76266
- if (step.step_type === "user_input") {
76267
- const index = typeof step.step_index === "number" ? step.step_index : void 0;
76268
- if (index === void 0 || !this.seenUserInputSteps.has(index)) {
76269
- if (index !== void 0) this.seenUserInputSteps.add(index);
76270
- if (this.initialUserInputSeen) this.unconsumed.shift();
76271
- else this.initialUserInputSeen = true;
76272
- }
76430
+ /**
76431
+ * The first prompt settled; settle every message steered in after it, in
76432
+ * order. Each was confirmed as read when the prompt before it returned.
76433
+ */
76434
+ async settlePrompt(result) {
76435
+ let last = isRecord$8(result) ? result : {};
76436
+ this.addUsage(last.usage);
76437
+ for (;;) {
76438
+ await this.client.drain();
76439
+ const next = this.steers.shift();
76440
+ if (!next) break;
76441
+ last = await next;
76442
+ this.addUsage(last.usage);
76443
+ }
76444
+ this.steerable = false;
76445
+ await this.confirmations;
76446
+ const used = Object.values(this.usage).some((value) => value > 0);
76447
+ await this.pushToPipeline({
76448
+ stopReason: last.stopReason,
76449
+ type: "antigravity_prompt_completed",
76450
+ ...used && { usage: { ...this.usage } }
76451
+ });
76452
+ }
76453
+ async onRunFailure(error) {
76454
+ this.steerable = false;
76455
+ await this.pushToPipeline({
76456
+ message: error.message,
76457
+ type: "antigravity_error"
76458
+ });
76459
+ await this.emitEvents(await this.pipeline.flush());
76460
+ }
76461
+ async onRunCancelled() {
76462
+ this.steerable = false;
76463
+ await this.pushToPipeline({
76464
+ stopReason: "cancelled",
76465
+ type: "antigravity_prompt_completed"
76466
+ });
76467
+ }
76468
+ onHostClose() {
76469
+ this.steerable = false;
76470
+ }
76471
+ async handleAgentMessage(message) {
76472
+ await this.confirmations;
76473
+ if (isPromptResponse(message)) {
76474
+ this.promptResponses += 1;
76475
+ const next = this.unconfirmedSteers[0];
76476
+ if (next && next.index <= this.promptResponses) {
76477
+ this.unconfirmedSteers.shift();
76478
+ await this.confirmSteer(next.uuid);
76273
76479
  }
76274
- this.openTurn();
76275
76480
  return;
76276
76481
  }
76277
- if (message.event === "result" && message.result && typeof message.result === "object") {
76278
- this.turnOpen = false;
76279
- const status = typeof message.result.status === "string" ? message.result.status : void 0;
76280
- this.lastOutcome = {
76281
- ok: status === "SUCCESS",
76282
- status
76283
- };
76284
- if (status !== "SUCCESS") this.close();
76285
- else this.closeIfIdle();
76286
- }
76287
- }
76288
- openTurn() {
76289
- this.turnOpen = true;
76290
- this.lastOutcome = void 0;
76482
+ if (!this.acceptUpdates || message.method !== "session/update") return;
76483
+ const params = isRecord$8(message.params) ? message.params : void 0;
76484
+ if (!isRecord$8(params?.update)) return;
76485
+ if (typeof params.sessionId === "string" && params.sessionId !== this.acpSessionId) return;
76486
+ await this.pushToPipeline(params.update);
76291
76487
  }
76292
- closeIfIdle() {
76293
- if (this.turnOpen || this.unconsumed.length > 0) return;
76294
- this.close();
76488
+ /**
76489
+ * `--dangerously-skip-permissions` makes agy approve tools itself; should it
76490
+ * still ask, approve as the print-mode runs did.
76491
+ */
76492
+ handleServerRequest(message) {
76493
+ if (message.method !== "session/request_permission") throw new AcpServerRequestError(-32601, `Unsupported ACP client request: ${message.method}`);
76494
+ const optionId = selectAcpPermissionOption(message.params, [(option) => option.kind === "allow_always", (option) => option.kind === "allow_once"]);
76495
+ return optionId ? { outcome: {
76496
+ optionId,
76497
+ outcome: "selected"
76498
+ } } : { outcome: { outcome: "cancelled" } };
76295
76499
  }
76296
- armIdleTimer() {
76297
- this.clearIdleTimer();
76298
- this.idleTimer = setTimeout(() => this.close(), this.idleCloseMs);
76299
- this.idleTimer.unref?.();
76500
+ /**
76501
+ * Resume without replaying history; agy points sessions it cannot resume to
76502
+ * `session/load`, whose replay arrives before the prompt and is dropped.
76503
+ */
76504
+ async openSession(initialized) {
76505
+ const params = {
76506
+ cwd: this.options.cwd,
76507
+ mcpServers: []
76508
+ };
76509
+ const resumeSessionId = this.options.resumeSessionId;
76510
+ if (!resumeSessionId) return this.client.request("session/new", params);
76511
+ const resumeParams = {
76512
+ ...params,
76513
+ sessionId: resumeSessionId
76514
+ };
76515
+ if (initialized.agentCapabilities?.sessionCapabilities?.resume !== void 0) try {
76516
+ return await this.client.request("session/resume", resumeParams);
76517
+ } catch (error) {
76518
+ if (!(error instanceof AcpRpcResponseError)) throw error;
76519
+ }
76520
+ const loaded = await this.client.request("session/load", resumeParams);
76521
+ await this.client.drain();
76522
+ return loaded;
76300
76523
  }
76301
- clearIdleTimer() {
76302
- if (!this.idleTimer) return;
76303
- clearTimeout(this.idleTimer);
76304
- this.idleTimer = void 0;
76524
+ /**
76525
+ * Apply the selected model (a full id such as `gemini-4-neon-xhigh`, which
76526
+ * agy splits into model and thinking level), effort and mode. Returns the
76527
+ * model the session runs.
76528
+ */
76529
+ async applySessionConfig(sessionId, sessionResult) {
76530
+ let configOptions = sessionResult.configOptions;
76531
+ const set = async (configId, value) => {
76532
+ const result = await this.client.request("session/set_config_option", {
76533
+ configId,
76534
+ sessionId,
76535
+ value
76536
+ });
76537
+ if (result.configOptions !== void 0) configOptions = result.configOptions;
76538
+ };
76539
+ const { effort, mode } = this.launch;
76540
+ const model = this.launch.model && this.launch.model !== "default" ? resolveModelValue(this.launch.model, effort, sessionResult) : void 0;
76541
+ if (model) await set("model", model);
76542
+ if (effort && findConfigOption(configOptions, "thought_level")) await set("thought_level", effort);
76543
+ if (mode) await set("mode", mode);
76544
+ const family = configValue(configOptions, "model");
76545
+ if (!family) return model;
76546
+ const level = configValue(configOptions, "thought_level");
76547
+ const variant = level ? `${family}-${level}` : void 0;
76548
+ return variant && availableModelIds(sessionResult).has(variant) ? variant : family;
76549
+ }
76550
+ confirmSteer(uuid) {
76551
+ const confirmed = this.confirmations.then(() => this.pushToPipeline({
76552
+ type: "antigravity_user_message",
76553
+ uuid
76554
+ }));
76555
+ confirmed.catch(() => {});
76556
+ this.confirmations = confirmed;
76557
+ return confirmed;
76305
76558
  }
76306
- markClosed() {
76307
- this.closed = true;
76308
- this.clearIdleTimer();
76559
+ addUsage(usage) {
76560
+ if (!isRecord$8(usage)) return;
76561
+ for (const field of USAGE_FIELDS) {
76562
+ const value = usage[field];
76563
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) this.usage[field] += value;
76564
+ }
76309
76565
  }
76310
76566
  };
76311
76567
 
@@ -77296,342 +77552,6 @@ const readClaudeCodeSessionCost = async (params) => {
77296
77552
  }
77297
77553
  };
77298
77554
 
77299
- //#endregion
77300
- //#region ../../packages/heterogeneous-agents/src/spawn/traeAcpSession.ts
77301
- const NOTIFICATION_DRAIN_QUIET_MS$2 = 250;
77302
- const NOTIFICATION_DRAIN_TIMEOUT_MS$2 = 2e3;
77303
- const TRANSPORT$4 = "trae-acp";
77304
- const sleep$7 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
77305
- const TRAE_GLOBAL_VALUE_FLAGS = new Set([
77306
- "--config",
77307
- "--permission-mode",
77308
- "--profile",
77309
- "-c",
77310
- "-p"
77311
- ]);
77312
- const isInlineTraeGlobalArg = (arg) => arg.startsWith("--config=") || arg.startsWith("--permission-mode=") || arg.startsWith("--profile=") || arg.startsWith("-c=") || arg.startsWith("-p=");
77313
- /**
77314
- * TRAE requires configuration flags before `acp serve`, while ACP Server flags
77315
- * belong after it. Keep unknown/user server flags in their historical position
77316
- * and move only the documented global flags plus their values.
77317
- * @see https://docs.trae.cn/cli_agent-client-protocol
77318
- */
77319
- const buildTraeAcpArgs = (args = []) => {
77320
- const globalArgs = [];
77321
- const serverArgs = [];
77322
- for (let index = 0; index < args.length; index += 1) {
77323
- const arg = args[index];
77324
- if (TRAE_GLOBAL_VALUE_FLAGS.has(arg)) {
77325
- globalArgs.push(arg);
77326
- const value = args[index + 1];
77327
- if (value !== void 0) {
77328
- globalArgs.push(value);
77329
- index += 1;
77330
- }
77331
- continue;
77332
- }
77333
- if (isInlineTraeGlobalArg(arg)) {
77334
- globalArgs.push(arg);
77335
- continue;
77336
- }
77337
- serverArgs.push(arg);
77338
- }
77339
- return [
77340
- ...globalArgs,
77341
- "acp",
77342
- "serve",
77343
- "--yolo",
77344
- ...serverArgs
77345
- ];
77346
- };
77347
- const buildTraeAcpPrompt = async (prompt, options = {}) => {
77348
- const blocks = typeof prompt === "string" ? [{
77349
- text: prompt,
77350
- type: "text"
77351
- }] : prompt;
77352
- const result = [];
77353
- for (const block of blocks) if (block.type === "text") result.push({
77354
- text: block.text,
77355
- type: "text"
77356
- });
77357
- else {
77358
- const image = await normalizeImage(block.source, options);
77359
- result.push({
77360
- data: image.buffer.toString("base64"),
77361
- mimeType: image.mediaType,
77362
- type: "image"
77363
- });
77364
- }
77365
- return result;
77366
- };
77367
- const toTraeModel = (id, name) => ({
77368
- id,
77369
- ...typeof name === "string" && name && name !== id ? { label: name } : {},
77370
- modelId: id,
77371
- providerId: "trae"
77372
- });
77373
- const parseConfigOptionModels$1 = (options) => {
77374
- if (!Array.isArray(options)) return [];
77375
- const values = options.flatMap((value) => {
77376
- const option = value;
77377
- return Array.isArray(option?.options) ? option.options : [value];
77378
- });
77379
- const seen = /* @__PURE__ */ new Set();
77380
- const models = [];
77381
- for (const value of values) {
77382
- const option = value;
77383
- if (typeof option?.value !== "string" || !option.value || seen.has(option.value)) continue;
77384
- seen.add(option.value);
77385
- models.push(toTraeModel(option.value, option.name));
77386
- }
77387
- return models;
77388
- };
77389
- /**
77390
- * Read model selection from the current stable ACP config-options API, with a
77391
- * compatibility fallback for the never-stabilized dedicated model API still
77392
- * exposed by older TRAE CLI builds.
77393
- */
77394
- const parseTraeAcpModelCatalog = (result) => {
77395
- const selectableOptions = (Array.isArray(result?.configOptions) ? result.configOptions.map((value) => value) : []).filter((option) => option?.type === void 0 || option.type === "select");
77396
- const modelConfig = selectableOptions.find((option) => option?.category === "model") ?? selectableOptions.find((option) => option?.id === "model") ?? selectableOptions.find((option) => typeof option?.name === "string" && option.name.toLowerCase() === "model");
77397
- if (modelConfig && typeof modelConfig.id === "string" && modelConfig.id) return {
77398
- configId: modelConfig.id,
77399
- currentModelId: typeof modelConfig.currentValue === "string" ? modelConfig.currentValue : void 0,
77400
- models: parseConfigOptionModels$1(modelConfig.options),
77401
- protocol: "config-option"
77402
- };
77403
- if (!Array.isArray(result?.models?.availableModels)) return;
77404
- const seen = /* @__PURE__ */ new Set();
77405
- const models = [];
77406
- for (const value of result.models.availableModels) {
77407
- const option = value;
77408
- if (typeof option?.modelId !== "string" || !option.modelId || seen.has(option.modelId)) continue;
77409
- seen.add(option.modelId);
77410
- models.push(toTraeModel(option.modelId, option.name));
77411
- }
77412
- return {
77413
- currentModelId: typeof result.models.currentModelId === "string" ? result.models.currentModelId : void 0,
77414
- models,
77415
- protocol: "legacy-model"
77416
- };
77417
- };
77418
- /** TRAE's ACP v1 lifecycle: model config-options and legacy model API on the shared base. */
77419
- var TraeAcpSession = class TraeAcpSession extends AcpAgentSession {
77420
- acceptUpdates = false;
77421
- lastSessionUpdateAt = 0;
77422
- modelDiscovery;
77423
- resolvedPrompt = [];
77424
- constructor(options) {
77425
- super(options, {
77426
- args: buildTraeAcpArgs(options.args),
77427
- pipeline: { agentType: "trae" },
77428
- processLabel: "TRAE ACP",
77429
- transport: TRANSPORT$4
77430
- });
77431
- }
77432
- get nativeSessionId() {
77433
- return this.acpSessionId;
77434
- }
77435
- /** Create a short-lived ACP session and read its agent-provided model selector. */
77436
- async discoverModels() {
77437
- return (await this.discoverModelCatalog()).models;
77438
- }
77439
- async prepareRun() {
77440
- this.resolvedPrompt = await this.resolvePrompt();
77441
- }
77442
- buildInitializeParams() {
77443
- return {
77444
- clientCapabilities: {},
77445
- clientInfo: {
77446
- name: "lobehub",
77447
- title: "LobeHub",
77448
- version: this.options.clientVersion
77449
- },
77450
- protocolVersion: 1
77451
- };
77452
- }
77453
- validateInitialized(initialized) {
77454
- if (typeof initialized?.protocolVersion === "number" && initialized.protocolVersion !== 1) throw new Error(`TRAE ACP returned unsupported protocol version: ${initialized.protocolVersion}`);
77455
- }
77456
- async establishSession(initialized) {
77457
- if (this.resolvedPrompt.some((block) => block.type === "image") && initialized?.agentCapabilities?.promptCapabilities?.image !== true) throw new Error("TRAE ACP agent does not support image prompt blocks");
77458
- if (this.options.resumeSessionId && initialized?.agentCapabilities?.loadSession !== true) throw new Error("TRAE ACP agent does not support loading sessions");
77459
- const sessionResult = await this.client.request(this.options.resumeSessionId ? "session/load" : "session/new", {
77460
- cwd: this.options.cwd,
77461
- mcpServers: [],
77462
- ...this.options.resumeSessionId ? { sessionId: this.options.resumeSessionId } : {}
77463
- });
77464
- const sessionId = sessionResult?.sessionId ?? this.options.resumeSessionId;
77465
- if (!sessionId) throw new Error("TRAE ACP returned no session id");
77466
- this.acpSessionId = sessionId;
77467
- this.options.onSessionId(sessionId);
77468
- const model = await this.applyInitialModel(sessionId, sessionResult);
77469
- if (model) {
77470
- this.pipeline.configureSession({ model });
77471
- this.options.onModel?.(model);
77472
- }
77473
- await this.pushToPipeline({
77474
- model,
77475
- sessionId,
77476
- type: "trae_session"
77477
- });
77478
- return sessionId;
77479
- }
77480
- onBeforePrompt() {
77481
- this.acceptUpdates = true;
77482
- }
77483
- buildPromptParams(sessionId) {
77484
- return {
77485
- prompt: this.resolvedPrompt,
77486
- sessionId
77487
- };
77488
- }
77489
- async settlePrompt(result) {
77490
- await this.drainNotifications();
77491
- await this.client.drain();
77492
- await this.pushToPipeline({
77493
- stopReason: result?.stopReason,
77494
- type: "trae_prompt_completed"
77495
- });
77496
- }
77497
- async onRunFailure(error) {
77498
- await this.pushToPipeline({
77499
- message: error.message,
77500
- type: "trae_error"
77501
- });
77502
- await this.emitEvents(await this.pipeline.flush());
77503
- }
77504
- async onRunCancelled() {
77505
- await this.pushToPipeline({
77506
- stopReason: "cancelled",
77507
- type: "trae_prompt_completed"
77508
- });
77509
- }
77510
- onHostClose() {
77511
- this.modelDiscovery?.close();
77512
- }
77513
- async handleAgentMessage(message) {
77514
- if (message.method !== "session/update") return;
77515
- if (!this.acceptUpdates) return;
77516
- this.lastSessionUpdateAt = Date.now();
77517
- const update = message.params?.update;
77518
- if (!update || typeof update !== "object") return;
77519
- if (update.sessionUpdate === "config_option_update") {
77520
- const catalog = parseTraeAcpModelCatalog({ configOptions: update.configOptions });
77521
- if (catalog?.currentModelId) {
77522
- this.pipeline.configureSession({ model: catalog.currentModelId });
77523
- this.options.onModel?.(catalog.currentModelId);
77524
- }
77525
- }
77526
- await this.pushToPipeline(update);
77527
- }
77528
- handleServerRequest(message) {
77529
- if (message.method === "session/request_permission") {
77530
- const optionId = selectAcpPermissionOption(message.params, [
77531
- (option) => option.optionId === "allow_session" || option.optionId === "approve_for_session",
77532
- (option) => option.kind === "allow_once",
77533
- (option) => option.kind === "reject_once"
77534
- ]);
77535
- if (optionId) return { outcome: {
77536
- optionId,
77537
- outcome: "selected"
77538
- } };
77539
- throw new AcpServerRequestError(-32603, "No safe permission option was offered");
77540
- }
77541
- throw new AcpServerRequestError(-32601, `Unsupported ACP client request: ${message.method}`);
77542
- }
77543
- async discoverModelCatalog() {
77544
- try {
77545
- const initialized = await this.initializeConnection();
77546
- const sessionResult = await this.client.request("session/new", {
77547
- cwd: this.options.cwd,
77548
- mcpServers: []
77549
- });
77550
- if (!sessionResult?.sessionId) throw new Error("TRAE ACP returned no session id");
77551
- const catalog = parseTraeAcpModelCatalog(sessionResult);
77552
- if (!catalog) throw new Error("TRAE ACP did not expose a model configuration option");
77553
- if (initialized?.agentCapabilities?.sessionCapabilities?.close) await this.client.request("session/close", { sessionId: sessionResult.sessionId });
77554
- return catalog;
77555
- } finally {
77556
- this.client.close();
77557
- }
77558
- }
77559
- async resolvePrompt() {
77560
- const prompt = this.options.prompt;
77561
- if (Array.isArray(prompt) && prompt.every((block) => "type" in block && (block.type === "text" || "data" in block && block.type === "image"))) return prompt;
77562
- return buildTraeAcpPrompt(prompt, this.options.inputOptions);
77563
- }
77564
- async applyInitialModel(sessionId, sessionResult) {
77565
- let catalog = parseTraeAcpModelCatalog(sessionResult);
77566
- const requestedModel = this.options.initialModel?.trim();
77567
- if (!requestedModel || requestedModel === "default") return catalog?.currentModelId;
77568
- if (!catalog && this.options.resumeSessionId) catalog = await this.discoverResumeModelCatalog();
77569
- if (!catalog) throw new Error("TRAE ACP did not expose a model configuration option");
77570
- const selected = catalog.models.find((model) => model.id === requestedModel || model.label === requestedModel);
77571
- if (!selected) throw new Error(`TRAE ACP model is unavailable: ${requestedModel}`);
77572
- if (catalog.protocol === "config-option") return parseTraeAcpModelCatalog({ configOptions: (await this.client.request("session/set_config_option", {
77573
- configId: catalog.configId,
77574
- sessionId,
77575
- value: selected.id
77576
- }))?.configOptions })?.currentModelId ?? selected.id;
77577
- await this.client.request("session/set_model", {
77578
- modelId: selected.id,
77579
- sessionId
77580
- });
77581
- return selected.id;
77582
- }
77583
- async discoverResumeModelCatalog() {
77584
- const discovery = new TraeAcpSession({
77585
- ...this.options,
77586
- initialModel: void 0,
77587
- onEvents: () => {},
77588
- onModel: void 0,
77589
- onRuntimeStatus: () => {},
77590
- onSessionId: () => {},
77591
- operationId: `${this.options.operationId}-model-discovery`,
77592
- prompt: "",
77593
- resumeSessionId: void 0,
77594
- sessionId: `${this.options.sessionId}-model-discovery`
77595
- });
77596
- this.modelDiscovery = discovery;
77597
- try {
77598
- return await discovery.discoverModelCatalog();
77599
- } finally {
77600
- discovery.close();
77601
- if (this.modelDiscovery === discovery) this.modelDiscovery = void 0;
77602
- }
77603
- }
77604
- async drainNotifications() {
77605
- const deadline = Date.now() + NOTIFICATION_DRAIN_TIMEOUT_MS$2;
77606
- let quietSince = Date.now();
77607
- while (Date.now() < deadline) {
77608
- await sleep$7(Math.min(NOTIFICATION_DRAIN_QUIET_MS$2, deadline - Date.now()));
77609
- await this.client.drain();
77610
- if (this.lastSessionUpdateAt > quietSince) {
77611
- quietSince = this.lastSessionUpdateAt;
77612
- continue;
77613
- }
77614
- if (Date.now() - quietSince >= NOTIFICATION_DRAIN_QUIET_MS$2) return;
77615
- }
77616
- }
77617
- };
77618
- const listTraeAcpModels = async (options) => new TraeAcpSession({
77619
- args: options.args ?? [],
77620
- clientVersion: options.clientVersion ?? "1.0.0",
77621
- commandPath: options.commandPath,
77622
- cwd: options.cwd,
77623
- env: options.env,
77624
- onEvents: () => {},
77625
- onRawMessage: () => {},
77626
- onRuntimeStatus: () => {},
77627
- onSessionId: () => {},
77628
- onStderr: () => {},
77629
- operationId: "trae-model-discovery",
77630
- prompt: "",
77631
- requestTimeoutMs: options.timeoutMs,
77632
- sessionId: "trae-model-discovery"
77633
- }).discoverModels();
77634
-
77635
77555
  //#endregion
77636
77556
  //#region ../../packages/heterogeneous-agents/src/spawn/copilotAcpSession.ts
77637
77557
  init_object$1();
@@ -80034,7 +79954,7 @@ const resolveHeteroSpawnCwd = (workDir) => [
80034
79954
  init_config();
80035
79955
  init_cliSpawn();
80036
79956
  /**
80037
- * ACP runtimes (Cursor, Devin, Droid, Grok, TRAE) behind the ordinary
79957
+ * ACP runtimes (Antigravity, Cursor, Devin, Droid, Grok, TRAE) behind the ordinary
80038
79958
  * `SpawnAgentHandle` contract returned by `spawnAgent`.
80039
79959
  */
80040
79960
  /** Guarded raw-stdout tee: diagnostic sink failures must not affect the ACP run. */
@@ -80141,9 +80061,10 @@ const createAcpSpawnBridge = () => {
80141
80061
  stderr
80142
80062
  };
80143
80063
  };
80144
- const createAcpSpawnHandle = (bridge, session, getSessionId = () => session.sessionId) => {
80064
+ const createAcpSpawnHandle = (bridge, session, getSessionId = () => session.sessionId, extra = {}) => {
80145
80065
  const { exit, interrupt, kill } = bridge.attach(session);
80146
80066
  return {
80067
+ ...extra,
80147
80068
  events: bridge.events,
80148
80069
  exit,
80149
80070
  interrupt,
@@ -80157,6 +80078,39 @@ const createAcpSpawnHandle = (bridge, session, getSessionId = () => session.sess
80157
80078
  stderr: bridge.stderr
80158
80079
  };
80159
80080
  };
80081
+ /**
80082
+ * Antigravity (`agy acp`): the handle also takes follow-ups mid-run
80083
+ * (`sendUserMessage`), which the session steers into the running turn.
80084
+ */
80085
+ const spawnAntigravityAcpAgent = async (options, command, cwd) => {
80086
+ const prompt = await buildAntigravityAcpPrompt(options.prompt, options.inputOptions);
80087
+ const bridge = createAcpSpawnBridge();
80088
+ const session = new AntigravityAcpSession({
80089
+ args: options.extraArgs ?? [],
80090
+ clientVersion: "lobehub-cli",
80091
+ commandPath: command,
80092
+ cwd,
80093
+ detached: options.detached,
80094
+ env: getHeterogeneousAgentSpawnEnv("antigravity", options.env, process.env),
80095
+ onEvents: bridge.onEvents,
80096
+ onRawMessage: teeAcpRawStdout(options.onRawStdout),
80097
+ onRuntimeStatus: () => {},
80098
+ onSessionId: () => {},
80099
+ onStderr: bridge.onStderr,
80100
+ operationId: options.operationId,
80101
+ prompt,
80102
+ resumeSessionId: options.resumeSessionId,
80103
+ sessionId: options.operationId
80104
+ });
80105
+ return createAcpSpawnHandle(bridge, session, void 0, {
80106
+ sendUserMessage: async (followUp, sendOptions) => {
80107
+ if (!sendOptions?.uuid) return false;
80108
+ const blocks = await buildAntigravityAcpPrompt(followUp, options.inputOptions);
80109
+ return session.steer(blocks, sendOptions.uuid);
80110
+ },
80111
+ supportsSteerImageAttachments: true
80112
+ });
80113
+ };
80160
80114
  const spawnGrokAcpAgent = async (options, command, cwd) => {
80161
80115
  const prompt = await buildGrokAcpPrompt(options.prompt, options.inputOptions);
80162
80116
  const bridge = createAcpSpawnBridge();
@@ -80502,7 +80456,6 @@ const buildQoderArgs = ({ extraArgs = [], inputArgs = [], resumeSessionId }) =>
80502
80456
  ];
80503
80457
  const buildSpawnArgs = (params) => {
80504
80458
  switch (params.agentType) {
80505
- case "antigravity": return buildAntigravityArgs(params);
80506
80459
  case "amp": return buildAmpArgs(params);
80507
80460
  case "claude-code": return buildClaudeCodeArgs(params);
80508
80461
  case "codebuddy": return buildCodeBuddyArgs(params);
@@ -80550,6 +80503,7 @@ const spawnAgent = async (options) => {
80550
80503
  const command = resolveHeterogeneousAgentCommand(options.agentType, options.command);
80551
80504
  const cwd = options.cwd || process.cwd();
80552
80505
  assertSpawnableWorkingDirectory(cwd);
80506
+ if (options.agentType === "antigravity") return spawnAntigravityAcpAgent(options, command, cwd);
80553
80507
  if (options.agentType === "copilot") return spawnCopilotAcpAgent(options, command, cwd);
80554
80508
  if (options.agentType === "devin") return spawnDevinAcpAgent(options, command, cwd);
80555
80509
  if (options.agentType === "grok-build") return spawnGrokAcpAgent(options, command, cwd);
@@ -80579,7 +80533,6 @@ const spawnAgent = async (options) => {
80579
80533
  /** One-shot JSONL CLI spawn; `spawnAgent` owns the Codex JWT file around it. */
80580
80534
  const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJwtFile) => {
80581
80535
  const claudeLiveInput = options.agentType === "claude-code" && options.liveInput === true;
80582
- const antigravityLiveInput = options.agentType === "antigravity" && options.liveInput === true;
80583
80536
  const permissionMode = options.agentType === "claude-code" ? options.permissionMode : void 0;
80584
80537
  const permissionPrompts = claudeLiveInput && !!options.askUserBridge;
80585
80538
  const args = buildSpawnArgs({
@@ -80618,15 +80571,10 @@ const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJw
80618
80571
  ]
80619
80572
  });
80620
80573
  const claudeLive = claudeLiveInput && proc.stdin ? new ClaudeCodeLiveInput(proc.stdin) : void 0;
80621
- const antigravityLive = antigravityLiveInput && proc.stdin ? new AntigravityLiveInput(proc.stdin) : void 0;
80622
- const live = claudeLive ?? antigravityLive;
80623
80574
  const pipeline = new AgentStreamPipeline({
80624
80575
  adapter: claudeLive ? new ClaudeCodeAdapter({
80625
80576
  runtimeEndStrategy: "on-transport-close",
80626
80577
  signalBackgroundTaskCompletion: true
80627
- }) : antigravityLive ? new AntigravityAdapter({
80628
- runtimeEndStrategy: "on-transport-close",
80629
- takeNextSteerUuid: () => antigravityLive.takeSteerUuid()
80630
80578
  }) : void 0,
80631
80579
  agentType: options.agentType,
80632
80580
  cwd,
@@ -80692,7 +80640,7 @@ const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJw
80692
80640
  wake();
80693
80641
  });
80694
80642
  }
80695
- if (live) live.send(inputPlan.stdin);
80643
+ if (claudeLive) claudeLive.send(inputPlan.stdin);
80696
80644
  else if (proc.stdin) proc.stdin.write(inputPlan.stdin, () => {
80697
80645
  proc.stdin?.end();
80698
80646
  });
@@ -80715,7 +80663,7 @@ const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJw
80715
80663
  pipelineQueue = pipelineQueue.then(async () => {
80716
80664
  try {
80717
80665
  const events = await pipeline.flush();
80718
- live?.finish();
80666
+ claudeLive?.finish();
80719
80667
  const { code, signal } = await exit;
80720
80668
  if (code === 0 && !killedByUs) events.push(...pipeline.validateCompletion());
80721
80669
  sawErrorEvent ||= events.some((event) => event.type === "error");
@@ -80725,11 +80673,6 @@ const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJw
80725
80673
  killedByHost: killedByUs,
80726
80674
  sawError: sawErrorEvent,
80727
80675
  signal
80728
- }) : antigravityLive ? resolveAntigravityLiveRuntimeEnd(antigravityLive.lastTurn, {
80729
- code,
80730
- killedByHost: killedByUs,
80731
- sawError: sawErrorEvent,
80732
- signal
80733
80676
  }) : void 0;
80734
80677
  if (liveEnd) for (const event of pipeline.completeRuntime(liveEnd)) queue.push(event);
80735
80678
  for (const event of await pipeline.collectPostRunUsage({ env: childEnv })) queue.push(event);
@@ -80745,7 +80688,7 @@ const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJw
80745
80688
  if (options.onRawStdout) try {
80746
80689
  options.onRawStdout(chunk);
80747
80690
  } catch {}
80748
- live?.observe(chunk);
80691
+ claudeLive?.observe(chunk);
80749
80692
  enqueuePush(chunk);
80750
80693
  });
80751
80694
  stdout.on("end", enqueueFlush);
@@ -80800,14 +80743,9 @@ const spawnCliAgent = async (options, command, cwd, inputPlan, childEnv, codexJw
80800
80743
  },
80801
80744
  supportsSteerImageAttachments: true
80802
80745
  },
80803
- ...antigravityLive && { sendUserMessage: async (prompt, sendOptions) => {
80804
- if (!antigravityLive.isOpen) return false;
80805
- const plan = await buildAgentInput("antigravity", prompt, options.inputOptions);
80806
- return antigravityLive.send(plan.stdin, sendOptions?.uuid);
80807
- } },
80808
80746
  kill: (signal = "SIGINT") => {
80809
80747
  killedByUs = true;
80810
- live?.close();
80748
+ claudeLive?.close();
80811
80749
  killProcessTree(proc, signal, detached);
80812
80750
  },
80813
80751
  pid: proc.pid,
@@ -338899,7 +338837,7 @@ var stdio_exports = /* @__PURE__ */ __exportAll$2({
338899
338837
  function getDefaultEnvironment() {
338900
338838
  const env = {};
338901
338839
  for (const key of DEFAULT_INHERITED_ENV_VARS) {
338902
- const value = _w.env[key];
338840
+ const value = process$1.env[key];
338903
338841
  if (value === void 0) continue;
338904
338842
  if (value.startsWith("()")) continue;
338905
338843
  env[key] = value;
@@ -338910,7 +338848,7 @@ var import_cross_spawn$1, DEFAULT_INHERITED_ENV_VARS, StdioClientTransport;
338910
338848
  var init_stdio = __esmMin((() => {
338911
338849
  init_src_CeKsbNLO();
338912
338850
  import_cross_spawn$1 = /* @__PURE__ */ __toESM$2(require_cross_spawn(), 1);
338913
- DEFAULT_INHERITED_ENV_VARS = _w.platform === "win32" ? [
338851
+ DEFAULT_INHERITED_ENV_VARS = process$1.platform === "win32" ? [
338914
338852
  "APPDATA",
338915
338853
  "COMSPEC",
338916
338854
  "HOMEDRIVE",
@@ -338967,7 +338905,7 @@ var init_stdio = __esmMin((() => {
338967
338905
  this._serverParams.stderr ?? "inherit"
338968
338906
  ],
338969
338907
  shell: false,
338970
- windowsHide: _w.platform === "win32",
338908
+ windowsHide: process$1.platform === "win32",
338971
338909
  cwd: this._serverParams.cwd
338972
338910
  });
338973
338911
  this._process.on("error", (error) => {
@@ -341018,9 +340956,9 @@ const getSubprocessResult = ({ stdout }) => {
341018
340956
  //#region node_modules/.pnpm/execa@9.6.1/node_modules/execa/lib/utils/standard-stream.js
341019
340957
  const isStandardStream = (stream) => STANDARD_STREAMS.includes(stream);
341020
340958
  const STANDARD_STREAMS = [
341021
- _w.stdin,
341022
- _w.stdout,
341023
- _w.stderr
340959
+ process$1.stdin,
340960
+ process$1.stdout,
340961
+ process$1.stderr
341024
340962
  ];
341025
340963
  const STANDARD_STREAMS_ALIASES = [
341026
340964
  "stdin",
@@ -341145,9 +341083,9 @@ const NO_ESCAPE_REGEXP = /^[\w./-]+$/;
341145
341083
  //#endregion
341146
341084
  //#region node_modules/.pnpm/is-unicode-supported@2.1.0/node_modules/is-unicode-supported/index.js
341147
341085
  function isUnicodeSupported() {
341148
- const { env } = _w;
341086
+ const { env } = process$1;
341149
341087
  const { TERM, TERM_PROGRAM } = env;
341150
- if (_w.platform !== "win32") return TERM !== "linux";
341088
+ if (process$1.platform !== "win32") return TERM !== "linux";
341151
341089
  return Boolean(env.WT_SESSION) || Boolean(env.TERMINUS_SUBLIME) || env.ConEmuTask === "{cmd::Cmder}" || TERM_PROGRAM === "Terminus-Sublime" || TERM_PROGRAM === "vscode" || TERM === "xterm-256color" || TERM === "alacritty" || TERM === "rxvt-unicode" || TERM === "rxvt-unicode-256color" || env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
341152
341090
  }
341153
341091
 
@@ -341682,7 +341620,7 @@ function traversePathUp(startPath) {
341682
341620
 
341683
341621
  //#endregion
341684
341622
  //#region node_modules/.pnpm/npm-run-path@6.0.0/node_modules/npm-run-path/index.js
341685
- const npmRunPath = ({ cwd = _w.cwd(), path: pathOption = _w.env[pathKey()], preferLocal = true, execPath = _w.execPath, addExecPath = true } = {}) => {
341623
+ const npmRunPath = ({ cwd = process$1.cwd(), path: pathOption = process$1.env[pathKey()], preferLocal = true, execPath = process$1.execPath, addExecPath = true } = {}) => {
341686
341624
  const cwdPath = path.resolve(toPath(cwd));
341687
341625
  const result = [];
341688
341626
  const pathParts = pathOption.split(path.delimiter);
@@ -341700,7 +341638,7 @@ const applyExecPath = (result, pathParts, execPath, cwdPath) => {
341700
341638
  const pathPart = path.resolve(cwdPath, toPath(execPath), "..");
341701
341639
  if (!pathParts.includes(pathPart)) result.push(pathPart);
341702
341640
  };
341703
- const npmRunPathEnv = ({ env = _w.env, ...options } = {}) => {
341641
+ const npmRunPathEnv = ({ env = process$1.env, ...options } = {}) => {
341704
341642
  env = { ...env };
341705
341643
  const pathName = pathKey({ env });
341706
341644
  options.path = env[pathName];
@@ -342835,7 +342773,7 @@ const normalizeCwd = (cwd = getDefaultCwd()) => {
342835
342773
  };
342836
342774
  const getDefaultCwd = () => {
342837
342775
  try {
342838
- return _w.cwd();
342776
+ return process$1.cwd();
342839
342777
  } catch (error) {
342840
342778
  error.message = `The current directory does not exist.\n${error.message}`;
342841
342779
  throw error;
@@ -342871,7 +342809,7 @@ const normalizeOptions = (filePath, rawArguments, rawOptions) => {
342871
342809
  options.killSignal = normalizeKillSignal(options.killSignal);
342872
342810
  options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);
342873
342811
  options.lines = options.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options.encoding) && options.buffer[fdNumber]);
342874
- if (_w.platform === "win32" && path.basename(file, ".exe") === "cmd") commandArguments.unshift("/q");
342812
+ if (process$1.platform === "win32" && path.basename(file, ".exe") === "cmd") commandArguments.unshift("/q");
342875
342813
  return {
342876
342814
  file,
342877
342815
  commandArguments,
@@ -342898,7 +342836,7 @@ const addDefaultOptions = ({ extendEnv = true, preferLocal = false, cwd, localDi
342898
342836
  });
342899
342837
  const getEnv = ({ env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath }) => {
342900
342838
  const env = extendEnv ? {
342901
- ..._w.env,
342839
+ ...process$1.env,
342902
342840
  ...envOption
342903
342841
  } : envOption;
342904
342842
  if (preferLocal || node) return npmRunPathEnv({
@@ -343900,12 +343838,12 @@ const guessStreamDirection = {
343900
343838
  }
343901
343839
  };
343902
343840
  const getStandardStreamDirection = (value) => {
343903
- if ([0, _w.stdin].includes(value)) return "input";
343841
+ if ([0, process$1.stdin].includes(value)) return "input";
343904
343842
  if ([
343905
343843
  1,
343906
343844
  2,
343907
- _w.stdout,
343908
- _w.stderr
343845
+ process$1.stdout,
343846
+ process$1.stderr
343909
343847
  ].includes(value)) return "output";
343910
343848
  };
343911
343849
  const DEFAULT_DIRECTION = "output";
@@ -344969,9 +344907,9 @@ const addIpcMethods = (subprocess, { ipc }) => {
344969
344907
  Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));
344970
344908
  };
344971
344909
  const getIpcExport = () => {
344972
- const anyProcess = _w;
344910
+ const anyProcess = process$1;
344973
344911
  const isSubprocess = true;
344974
- const ipc = _w.channel !== void 0;
344912
+ const ipc = process$1.channel !== void 0;
344975
344913
  return {
344976
344914
  ...getIpcMethods(anyProcess, isSubprocess, ipc),
344977
344915
  getCancelSignal: getCancelSignal$1.bind(void 0, {
@@ -345448,7 +345386,7 @@ var SignalExitFallback = class extends SignalExitBase {
345448
345386
  };
345449
345387
  var SignalExit = class extends SignalExitBase {
345450
345388
  /* c8 ignore start */
345451
- #hupSig = process$1.platform === "win32" ? "SIGINT" : "SIGHUP";
345389
+ #hupSig = process$2.platform === "win32" ? "SIGINT" : "SIGHUP";
345452
345390
  /* c8 ignore stop */
345453
345391
  #emitter = new Emitter();
345454
345392
  #process;
@@ -345543,8 +345481,8 @@ var SignalExit = class extends SignalExitBase {
345543
345481
  } else return og.call(this.#process, ev, ...args);
345544
345482
  }
345545
345483
  };
345546
- const process$1 = globalThis.process;
345547
- const { onExit, load: load$1, unload } = signalExitWrap(processOk(process$1) ? new SignalExit(process$1) : new SignalExitFallback());
345484
+ const process$2 = globalThis.process;
345485
+ const { onExit, load: load$1, unload } = signalExitWrap(processOk(process$2) ? new SignalExit(process$2) : new SignalExitFallback());
345548
345486
 
345549
345487
  //#endregion
345550
345488
  //#region node_modules/.pnpm/execa@9.6.1/node_modules/execa/lib/terminate/cleanup.js
@@ -588161,14 +588099,15 @@ const isPermanentRefusal = (error) => {
588161
588099
  const isUserMessageReplay = (event) => event.type === "step_complete" && event.data?.phase === "user_message" && typeof event.data?.uuid === "string";
588162
588100
  const isMainStreamStart = (event) => event.type === "stream_start" && !event.data?.subagent;
588163
588101
  /**
588164
- * Stream a Claude Code or native Codex run's events while typing the
588102
+ * Stream a Claude Code, native Codex or Antigravity run's events while typing the
588165
588103
  * follow-ups the user queues behind it into the live session (steer), instead
588166
588104
  * of leaving them for the next turn.
588167
588105
  *
588168
588106
  * Polls `aiAgent.waitHeteroSteer` for as long as the run streams and its
588169
588107
  * session takes input; a message the session refuses goes back with
588170
588108
  * `aiAgent.returnHeteroSteer`. The agent reports every message it picks up
588171
- * (Claude Code replays it, Codex echoes its client id):
588109
+ * (Claude Code replays it, Codex echoes its client id, Antigravity ends the
588110
+ * prompt it interrupts):
588172
588111
  * the replay of a delivery is forwarded for the server to write the message
588173
588112
  * into the conversation; any other replay (the run's own prompt) is dropped.
588174
588113
  * Once the server answered, the next main `stream_start` carries `liveSteer`
@@ -588237,7 +588176,7 @@ async function* withHeteroSteer(handle, context) {
588237
588176
  const res = await client.aiAgent.waitHeteroSteer.mutate({
588238
588177
  ...acceptsControl && { acceptsControl: true },
588239
588178
  ...handle.supportsSteerImageAttachments && { acceptsImageAttachments: true },
588240
- ...handle.supportsSteerImages !== false && { acceptsImages: true },
588179
+ acceptsImages: true,
588241
588180
  ...!answered && { blockMs: 1 },
588242
588181
  ...waitingForUser() && { holdSteer: true },
588243
588182
  operationId
@@ -589298,7 +589237,7 @@ const exec = async (options) => {
589298
589237
  extraArgs,
589299
589238
  includePartialMessages: options.type === "claude-code",
589300
589239
  initialModel: usesHeterogeneousSessionInitialModel(options.type) ? options.model : void 0,
589301
- liveInput: options.type === "claude-code" || options.type === "antigravity",
589240
+ liveInput: options.type === "claude-code",
589302
589241
  operationId,
589303
589242
  ...dispatchedModeSpawnOptions(options.type, resolved),
589304
589243
  uploadImage