@ycodium-ai/agent-grok 0.2.5029 → 0.2.5093

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 (2) hide show
  1. package/dist/index.js +809 -635
  2. package/package.json +6 -4
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ var __export = (target, all) => {
8
8
  import { definePlugin } from "@ycodium-ai/plugin-api";
9
9
 
10
10
  // ../../packages/plugin-api/src/version.ts
11
- var PLUGIN_API_VERSION = 143;
11
+ var PLUGIN_API_VERSION = 147;
12
12
 
13
13
  // src/index.ts
14
14
  import {
@@ -17,6 +17,39 @@ import {
17
17
  readExecutorEffectiveRequest
18
18
  } from "@ycodium-ai/plugin-api/executor";
19
19
 
20
+ // ../../packages/ycodium-instance-config/src/programHomeSchema.ts
21
+ function programAndHomeConfigSchema(binaryPath) {
22
+ const binaryForm = {
23
+ titleKey: "form.binaryPath.title",
24
+ descriptionKey: "form.binaryPath.description",
25
+ placeholderKey: "form.binaryPath.placeholder",
26
+ control: binaryPath.control
27
+ };
28
+ if (binaryPath.machineLocal === true) binaryForm["machineLocal"] = true;
29
+ return {
30
+ type: "object",
31
+ "x-ycodium-form-order": ["binaryPath", "homePath"],
32
+ properties: {
33
+ binaryPath: { type: "string", "x-ycodium-form": binaryForm },
34
+ homePath: {
35
+ type: "string",
36
+ "x-ycodium-form": {
37
+ titleKey: "form.homePath.title",
38
+ machineLocal: true,
39
+ descriptionKey: "form.homePath.description",
40
+ placeholderKey: "form.homePath.placeholder"
41
+ }
42
+ },
43
+ enabled: { type: "boolean" },
44
+ customModels: { type: "array" },
45
+ driver: { type: "string" },
46
+ config: { type: "object" },
47
+ environment: { type: "array" }
48
+ },
49
+ additionalProperties: true
50
+ };
51
+ }
52
+
20
53
  // src/card.ts
21
54
  var GROK_DRIVER_KIND = "grok";
22
55
  var GROK_CLIENT_INFO = { name: "ycodium-agent-grok", version: "0.1.0" };
@@ -110,38 +143,7 @@ var GROK_CARD = {
110
143
  }
111
144
  ],
112
145
  diagnostics: [],
113
- // 设置表单照这份画:带 x-ycodium-form 的属性才进表单(enabled、customModels 等另有入口,不在此列),
114
- // 顺序看 x-ycodium-form-order;文案键在本插件 locales/<locale>.json 里解析,宿主不兜底。
115
- configSchema: {
116
- type: "object",
117
- "x-ycodium-form-order": ["binaryPath", "homePath"],
118
- properties: {
119
- binaryPath: {
120
- type: "string",
121
- "x-ycodium-form": {
122
- titleKey: "form.binaryPath.title",
123
- descriptionKey: "form.binaryPath.description",
124
- placeholderKey: "form.binaryPath.placeholder",
125
- control: "executable-path"
126
- }
127
- },
128
- homePath: {
129
- type: "string",
130
- "x-ycodium-form": {
131
- titleKey: "form.homePath.title",
132
- machineLocal: true,
133
- descriptionKey: "form.homePath.description",
134
- placeholderKey: "form.homePath.placeholder"
135
- }
136
- },
137
- enabled: { type: "boolean" },
138
- customModels: { type: "array" },
139
- driver: { type: "string" },
140
- config: { type: "object" },
141
- environment: { type: "array" }
142
- },
143
- additionalProperties: true
144
- },
146
+ configSchema: programAndHomeConfigSchema({ control: "executable-path" }),
145
147
  modelConnectivity: {
146
148
  // 只报 `GROK_MODELS_BASE_URL` 下主请求说的那一种:后缀是 `/chat/completions`。CLI 换了
147
149
  // 配置(`api_backend`)能说 messages / responses 不算。它另有一笔标题请求走
@@ -182,16 +184,29 @@ var GROK_CARD = {
182
184
 
183
185
  // src/grokHome.ts
184
186
  import * as NodeCrypto from "node:crypto";
187
+ import * as NodeOS2 from "node:os";
188
+ import * as NodePath3 from "node:path";
189
+ import { mergeLaunchEnv as mergeLaunchEnv2 } from "@ycodium-ai/plugin-api/executor";
190
+
191
+ // ../../packages/ycodium-instance-config/src/homePath.ts
185
192
  import * as NodeOS from "node:os";
186
- import * as NodePath2 from "node:path";
193
+ import * as NodePath from "node:path";
187
194
  import { mergeLaunchEnv } from "@ycodium-ai/plugin-api/executor";
195
+ function expandHomePath(value) {
196
+ if (value === "~") return NodeOS.homedir();
197
+ if (value.startsWith("~/") || value.startsWith("~\\")) {
198
+ return NodePath.join(NodeOS.homedir(), value.slice(2));
199
+ }
200
+ return value;
201
+ }
188
202
 
189
203
  // src/grokAccount.ts
204
+ import * as NodePath2 from "node:path";
205
+
206
+ // ../../packages/ycodium-credential-account/src/credentialAccount.ts
190
207
  import * as NodeFS from "node:fs";
191
- import * as NodePath from "node:path";
192
- var AUTH_FILE_NAME = "auth.json";
193
208
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
194
- var readString = (record4, key) => {
209
+ var readTrimmedString = (record4, key) => {
195
210
  const value = record4[key];
196
211
  if (typeof value !== "string") return void 0;
197
212
  const trimmed3 = value.trim();
@@ -220,30 +235,26 @@ var readCredentialFile = (path) => {
220
235
  return void 0;
221
236
  }
222
237
  };
223
- var signedOutProbe = (exists) => ({
224
- state: "signed-out",
225
- directoryExists: exists,
226
- email: void 0,
227
- name: void 0,
228
- expiresAt: void 0
229
- });
230
- var unreadableProbe = (exists) => ({
231
- state: "unreadable",
238
+ var accountWithoutIdentity = (state, exists) => ({
239
+ state,
232
240
  directoryExists: exists,
233
241
  email: void 0,
234
242
  name: void 0,
235
243
  expiresAt: void 0
236
244
  });
245
+
246
+ // src/grokAccount.ts
247
+ var AUTH_FILE_NAME = "auth.json";
237
248
  var joinName = (record4) => {
238
- const first = readString(record4, "first_name");
239
- const last = readString(record4, "last_name");
249
+ const first = readTrimmedString(record4, "first_name");
250
+ const last = readTrimmedString(record4, "last_name");
240
251
  const joined = [first, last].filter((part) => part !== void 0).join(" ");
241
252
  return joined.length > 0 ? joined : void 0;
242
253
  };
243
254
  var findIdentityEntry = (parsed) => {
244
255
  for (const value of Object.values(parsed)) {
245
256
  if (!isRecord(value)) continue;
246
- if (readString(value, "email") !== void 0 || readString(value, "user_id") !== void 0) {
257
+ if (readTrimmedString(value, "email") !== void 0 || readTrimmedString(value, "user_id") !== void 0) {
247
258
  return value;
248
259
  }
249
260
  }
@@ -256,33 +267,26 @@ var isExpired = (expiresAt, nowMs) => {
256
267
  };
257
268
  var readGrokAccount = (homePath) => {
258
269
  const exists = directoryExists(homePath);
259
- const raw = readCredentialFile(NodePath.join(homePath, AUTH_FILE_NAME));
260
- if (raw === void 0) return signedOutProbe(exists);
270
+ const raw = readCredentialFile(NodePath2.join(homePath, AUTH_FILE_NAME));
271
+ if (raw === void 0) return accountWithoutIdentity("signed-out", exists);
261
272
  const parsed = parseJsonRecord(raw);
262
273
  const identity = parsed === void 0 ? void 0 : findIdentityEntry(parsed);
263
- if (identity === void 0) return unreadableProbe(exists);
264
- const expiresAt = readString(identity, "expires_at");
274
+ if (identity === void 0) return accountWithoutIdentity("unreadable", exists);
275
+ const expiresAt = readTrimmedString(identity, "expires_at");
265
276
  return {
266
277
  state: isExpired(expiresAt, Date.now()) ? "expired" : "signed-in",
267
278
  directoryExists: exists,
268
- email: readString(identity, "email"),
279
+ email: readTrimmedString(identity, "email"),
269
280
  name: joinName(identity),
270
281
  expiresAt
271
282
  };
272
283
  };
273
284
 
274
285
  // src/grokHome.ts
275
- function expandHomePath(value) {
276
- if (value === "~") return NodeOS.homedir();
277
- if (value.startsWith("~/") || value.startsWith("~\\")) {
278
- return NodePath2.join(NodeOS.homedir(), value.slice(2));
279
- }
280
- return value;
281
- }
282
286
  function resolveGrokHomePath(value) {
283
287
  const trimmed3 = value.trim();
284
- if (trimmed3.length === 0) return NodePath2.join(NodeOS.homedir(), ".grok");
285
- return NodePath2.resolve(expandHomePath(trimmed3));
288
+ if (trimmed3.length === 0) return NodePath3.join(NodeOS2.homedir(), ".grok");
289
+ return NodePath3.resolve(expandHomePath(trimmed3));
286
290
  }
287
291
  function probeGrokAccount(accountPath) {
288
292
  const resolved = resolveGrokHomePath(accountPath);
@@ -301,13 +305,13 @@ function grokContinuationKey(recipe) {
301
305
  function resolveAccountHomePath(recipe, configuredHome) {
302
306
  const fromEnvironment = recipe.environment["GROK_HOME"]?.trim();
303
307
  if (fromEnvironment !== void 0 && fromEnvironment.length > 0) {
304
- return NodePath2.resolve(expandHomePath(fromEnvironment));
308
+ return NodePath3.resolve(expandHomePath(fromEnvironment));
305
309
  }
306
310
  return resolveGrokHomePath(configuredHome);
307
311
  }
308
312
  function absentPath() {
309
- return NodePath2.join(
310
- NodeOS.tmpdir(),
313
+ return NodePath3.join(
314
+ NodeOS2.tmpdir(),
311
315
  `ycodium-grok-no-auth-${NodeCrypto.randomUUID()}`,
312
316
  "auth.json"
313
317
  );
@@ -325,7 +329,7 @@ function ownEndpointAuthGuard(recipe) {
325
329
  function buildSignInEnv(recipe) {
326
330
  const configuredHome = recipe.homePath;
327
331
  const homeInjection = configuredHome.trim().length > 0 ? { [GROK_CARD.homeEnvVar]: resolveGrokHomePath(configuredHome) } : {};
328
- return mergeLaunchEnv({
332
+ return mergeLaunchEnv2({
329
333
  accountHome: homeInjection,
330
334
  instanceTable: recipe.environment,
331
335
  handOverrides: { GROK_OAUTH2_REFERRER: "ycodium" }
@@ -333,7 +337,7 @@ function buildSignInEnv(recipe) {
333
337
  }
334
338
  function buildSpawnEnv(recipe, resolvedHomePath, homeConfigured) {
335
339
  const homeInjection = homeConfigured ? { [GROK_CARD.homeEnvVar]: resolvedHomePath } : {};
336
- return mergeLaunchEnv({
340
+ return mergeLaunchEnv2({
337
341
  accountHome: { ...homeInjection, ...ownEndpointAuthGuard(recipe) },
338
342
  instanceTable: recipe.environment,
339
343
  handOverrides: { GROK_OAUTH2_REFERRER: "ycodium" }
@@ -343,9 +347,9 @@ function buildSpawnEnv(recipe, resolvedHomePath, homeConfigured) {
343
347
  // src/grokInstance.ts
344
348
  import * as NodeCrypto3 from "node:crypto";
345
349
  import {
346
- raceAbort as raceAbort3
350
+ raceAbort as raceAbort4
347
351
  } from "@ycodium-ai/plugin-api/executor";
348
- import { nodeStreamsFromHandle as nodeStreamsFromHandle2 } from "@ycodium-ai/plugin-api/process-stdin";
352
+ import { nodeStreamsFromHandle as nodeStreamsFromHandle3 } from "@ycodium-ai/plugin-api/process-stdin";
349
353
 
350
354
  // ../../packages/ycodium-acp-executor/src/executor.ts
351
355
  import * as NodeCrypto2 from "node:crypto";
@@ -407,6 +411,24 @@ function approvalOutcomeForDecision(decision, optionId) {
407
411
  return decision !== "cancel" && optionId !== void 0 ? { outcome: "selected", optionId } : { outcome: "cancelled" };
408
412
  }
409
413
 
414
+ // ../../packages/ycodium-executor-common/src/stderrTail.ts
415
+ var REDACTION_MARKERS = ["[redacted]", "[pairing-url]"];
416
+ function lastStderrTail(text4, maxChars) {
417
+ if (text4.length <= maxChars) return text4;
418
+ let start = text4.length - maxChars;
419
+ if (text4[start - 1] !== "\n") {
420
+ const lineEnd = text4.indexOf("\n", start);
421
+ if (lineEnd !== -1 && lineEnd < text4.length - 1) return text4.slice(lineEnd + 1);
422
+ const code = text4.charCodeAt(start);
423
+ if (code >= 56320 && code <= 57343) start += 1;
424
+ for (const marker of REDACTION_MARKERS) {
425
+ const at = text4.lastIndexOf(marker, start);
426
+ if (at !== -1 && at < start && start < at + marker.length) start = at + marker.length;
427
+ }
428
+ }
429
+ return text4.slice(start);
430
+ }
431
+
410
432
  // ../../packages/ycodium-acp-executor/src/errors.ts
411
433
  var AcpExecutorError = class extends Error {
412
434
  code;
@@ -511,30 +533,14 @@ var AcpAgentExitedError = class extends AcpConnectionClosedError {
511
533
  this.exitCode = exitCode;
512
534
  }
513
535
  };
514
- var REDACTION_MARKERS = ["[redacted]", "[pairing-url]"];
515
- var lastLines = (text4, maxChars) => {
516
- if (text4.length <= maxChars) return text4;
517
- let start = text4.length - maxChars;
518
- if (text4[start - 1] !== "\n") {
519
- const lineEnd = text4.indexOf("\n", start);
520
- if (lineEnd !== -1 && lineEnd < text4.length - 1) return text4.slice(lineEnd + 1);
521
- const code = text4.charCodeAt(start);
522
- if (code >= 56320 && code <= 57343) start += 1;
523
- for (const marker of REDACTION_MARKERS) {
524
- const at = text4.lastIndexOf(marker, start);
525
- if (at !== -1 && at < start && start < at + marker.length) start = at + marker.length;
526
- }
527
- }
528
- return text4.slice(start);
529
- };
530
536
  var settledExitCode = async (exited) => {
531
537
  if (exited === void 0) return void 0;
532
538
  let timer;
533
539
  try {
534
540
  return await Promise.race([
535
541
  exited.catch(() => void 0),
536
- new Promise((resolve2) => {
537
- timer = setTimeout(() => resolve2(void 0), AGENT_EXIT_SETTLE_MS);
542
+ new Promise((resolve3) => {
543
+ timer = setTimeout(() => resolve3(void 0), AGENT_EXIT_SETTLE_MS);
538
544
  })
539
545
  ]);
540
546
  } finally {
@@ -547,7 +553,7 @@ async function describeAgentExit(input2) {
547
553
  input2.stderrTail === void 0 ? "" : Promise.resolve().then(input2.stderrTail).catch(() => "")
548
554
  ]);
549
555
  const head = exitCode === void 0 ? "The agent closed its connection." : exitCode === null ? "The agent process exited without an exit code." : `The agent process exited with code ${exitCode}.`;
550
- const excerpt = lastLines(tail.trim(), AGENT_EXIT_STDERR_MAX_CHARS);
556
+ const excerpt = lastStderrTail(tail.trim(), AGENT_EXIT_STDERR_MAX_CHARS);
551
557
  return new AcpAgentExitedError(
552
558
  excerpt.length === 0 ? head : `${head}
553
559
  Agent stderr (last lines):
@@ -612,8 +618,8 @@ var UnboundedEventStream = class {
612
618
  iterators.subscribers.delete(subscriber);
613
619
  return { value: void 0, done: true };
614
620
  }
615
- await new Promise((resolve2) => {
616
- subscriber.wake = resolve2;
621
+ await new Promise((resolve3) => {
622
+ subscriber.wake = resolve3;
617
623
  });
618
624
  }
619
625
  },
@@ -732,9 +738,17 @@ var selectPromptTurnId = (input2, activeTurnId, freshTurnId) => {
732
738
  return target;
733
739
  };
734
740
 
735
- // ../../packages/ycodium-acp-executor/src/tool-presentation.ts
741
+ // ../../packages/ycodium-executor-common/src/toolPresentation.ts
742
+ function isRecord4(value) {
743
+ return typeof value === "object" && value !== null && !Array.isArray(value);
744
+ }
745
+ function asTrimmedString2(value) {
746
+ if (typeof value !== "string") return void 0;
747
+ const trimmed3 = value.trim();
748
+ return trimmed3.length > 0 ? trimmed3 : void 0;
749
+ }
736
750
  function normalizeCommandValue(value) {
737
- const direct = asTrimmedString(value);
751
+ const direct = asTrimmedString2(value);
738
752
  if (direct) {
739
753
  return direct;
740
754
  }
@@ -743,7 +757,7 @@ function normalizeCommandValue(value) {
743
757
  }
744
758
  const parts = [];
745
759
  for (const entry of value) {
746
- const part = asTrimmedString(entry);
760
+ const part = asTrimmedString2(entry);
747
761
  if (part !== void 0) {
748
762
  parts.push(part);
749
763
  }
@@ -767,11 +781,11 @@ function extractCommandFromTitle(title) {
767
781
  return backtickMatch?.[1]?.trim() || void 0;
768
782
  }
769
783
  function extractToolCommand(data, title) {
770
- const item = isRecord3(data?.["item"]) ? data["item"] : void 0;
771
- const itemInput = item && isRecord3(item["input"]) ? item["input"] : void 0;
772
- const itemResult = item && isRecord3(item["result"]) ? item["result"] : void 0;
773
- const rawInput = isRecord3(data?.["rawInput"]) ? data["rawInput"] : void 0;
774
- const dataInput = isRecord3(data?.["input"]) ? data["input"] : void 0;
784
+ const item = isRecord4(data?.["item"]) ? data["item"] : void 0;
785
+ const itemInput = item && isRecord4(item["input"]) ? item["input"] : void 0;
786
+ const itemResult = item && isRecord4(item["result"]) ? item["result"] : void 0;
787
+ const rawInput = isRecord4(data?.["rawInput"]) ? data["rawInput"] : void 0;
788
+ const dataInput = isRecord4(data?.["input"]) ? data["input"] : void 0;
775
789
  const candidates = [
776
790
  normalizeCommandValue(item?.["command"]),
777
791
  normalizeCommandValue(itemInput?.["command"]),
@@ -784,7 +798,7 @@ function extractToolCommand(data, title) {
784
798
  if (direct) {
785
799
  return direct;
786
800
  }
787
- const executable = asTrimmedString(rawInput?.["executable"]);
801
+ const executable = asTrimmedString2(rawInput?.["executable"]);
788
802
  const args = normalizeCommandValue(rawInput?.["args"]);
789
803
  if (executable && args) {
790
804
  return `${executable} ${args}`;
@@ -816,11 +830,11 @@ function collectPaths(value, paths, seen, depth) {
816
830
  }
817
831
  return;
818
832
  }
819
- if (!isRecord3(value)) {
833
+ if (!isRecord4(value)) {
820
834
  return;
821
835
  }
822
836
  for (const key of ["path", "filePath", "relativePath", "filename", "newPath", "oldPath"]) {
823
- const candidate = maybePathLike(asTrimmedString(value[key]));
837
+ const candidate = maybePathLike(asTrimmedString2(value[key]));
824
838
  if (!candidate || seen.has(candidate)) {
825
839
  continue;
826
840
  }
@@ -846,7 +860,7 @@ function extractPrimaryPath(data) {
846
860
  return paths[0];
847
861
  }
848
862
  function normalizeEquivalentValue(value) {
849
- const trimmed3 = asTrimmedString(value);
863
+ const trimmed3 = asTrimmedString2(value);
850
864
  if (!trimmed3) {
851
865
  return void 0;
852
866
  }
@@ -859,8 +873,8 @@ function isEquivalent(left, right) {
859
873
  }
860
874
  function classifyToolAction(input2) {
861
875
  const itemType = input2.itemType ?? void 0;
862
- const kind = asTrimmedString(input2.data?.["kind"])?.toLowerCase();
863
- const title = asTrimmedString(input2.title)?.toLowerCase();
876
+ const kind = asTrimmedString2(input2.data?.["kind"])?.toLowerCase();
877
+ const title = asTrimmedString2(input2.title)?.toLowerCase();
864
878
  if (itemType === "command_execution" || kind === "execute" || title === "terminal") {
865
879
  return "command";
866
880
  }
@@ -875,26 +889,11 @@ function classifyToolAction(input2) {
875
889
  }
876
890
  return "other";
877
891
  }
878
- function canonicalItemTypeFromAcpToolKind(kind) {
879
- switch (kind) {
880
- case "execute":
881
- return "command_execution";
882
- case "edit":
883
- case "delete":
884
- case "move":
885
- return "file_change";
886
- case "search":
887
- case "fetch":
888
- return "web_search";
889
- default:
890
- return "dynamic_tool_call";
891
- }
892
- }
893
892
  function deriveToolActivityPresentation(input2) {
894
- const title = asTrimmedString(input2.title);
895
- const detail = stripTrailingExitCode(asTrimmedString(input2.detail));
896
- const fallbackSummary = asTrimmedString(input2.fallbackSummary) ?? "Tool";
897
- const data = isRecord3(input2.data) ? input2.data : void 0;
893
+ const title = asTrimmedString2(input2.title);
894
+ const detail = stripTrailingExitCode(asTrimmedString2(input2.detail));
895
+ const fallbackSummary = asTrimmedString2(input2.fallbackSummary) ?? "Tool";
896
+ const data = isRecord4(input2.data) ? input2.data : void 0;
898
897
  const command = extractToolCommand(data, title);
899
898
  const primaryPath = extractPrimaryPath(data);
900
899
  const action = classifyToolAction({
@@ -926,8 +925,8 @@ function deriveToolActivityPresentation(input2) {
926
925
  };
927
926
  }
928
927
  if (action === "search") {
929
- const rawInput = isRecord3(data?.["rawInput"]) ? data["rawInput"] : void 0;
930
- const query = asTrimmedString(rawInput?.["query"]) ?? asTrimmedString(rawInput?.["pattern"]) ?? asTrimmedString(rawInput?.["searchTerm"]);
928
+ const rawInput = isRecord4(data?.["rawInput"]) ? data["rawInput"] : void 0;
929
+ const query = asTrimmedString2(rawInput?.["query"]) ?? asTrimmedString2(rawInput?.["pattern"]) ?? asTrimmedString2(rawInput?.["searchTerm"]);
931
930
  return {
932
931
  summary: "Searched files",
933
932
  ...query ? { detail: query } : {}
@@ -944,6 +943,23 @@ function deriveToolActivityPresentation(input2) {
944
943
  };
945
944
  }
946
945
 
946
+ // ../../packages/ycodium-acp-executor/src/tool-presentation.ts
947
+ function canonicalItemTypeFromAcpToolKind(kind) {
948
+ switch (kind) {
949
+ case "execute":
950
+ return "command_execution";
951
+ case "edit":
952
+ case "delete":
953
+ case "move":
954
+ return "file_change";
955
+ case "search":
956
+ case "fetch":
957
+ return "web_search";
958
+ default:
959
+ return "dynamic_tool_call";
960
+ }
961
+ }
962
+
947
963
  // ../../packages/ycodium-acp-executor/src/tool-call-state.ts
948
964
  function normalizeToolCallStatus(raw, fallback) {
949
965
  switch (raw) {
@@ -1172,6 +1188,30 @@ function decideToolCallUpdateEmission(input2) {
1172
1188
  return { emit: false, skippedSinceEmit: skippedSinceEmit + 1 };
1173
1189
  }
1174
1190
 
1191
+ // ../../packages/ycodium-executor-common/src/catalogModel.ts
1192
+ function catalogModelLastSegment(value) {
1193
+ if (value.startsWith("[")) {
1194
+ let parsed;
1195
+ try {
1196
+ parsed = JSON.parse(value);
1197
+ } catch {
1198
+ return void 0;
1199
+ }
1200
+ if (!Array.isArray(parsed) || parsed.length < 2) return void 0;
1201
+ const last = parsed[parsed.length - 1];
1202
+ return typeof last === "string" ? last : void 0;
1203
+ }
1204
+ const separator = value.indexOf("/");
1205
+ return separator > 0 && separator < value.length - 1 ? value.slice(separator + 1) : void 0;
1206
+ }
1207
+ function matchCatalogModel(requested, catalog) {
1208
+ const wanted = requested?.trim();
1209
+ if (!wanted) return void 0;
1210
+ if (catalog.includes(wanted)) return wanted;
1211
+ const byLastSegment = catalog.filter((value) => catalogModelLastSegment(value) === wanted);
1212
+ return byLastSegment.length === 1 ? byLastSegment[0] : void 0;
1213
+ }
1214
+
1175
1215
  // ../../packages/ycodium-acp-executor/src/runtime-model.ts
1176
1216
  function normalizePlanStepStatus(raw) {
1177
1217
  switch (raw) {
@@ -1213,30 +1253,6 @@ function collectSessionModelIds(models) {
1213
1253
  (model) => isRecord3(model) && typeof model["modelId"] === "string" ? [model["modelId"]] : []
1214
1254
  );
1215
1255
  }
1216
- function catalogModelLastSegment(value) {
1217
- if (value.startsWith("[")) {
1218
- let parsed;
1219
- try {
1220
- parsed = JSON.parse(value);
1221
- } catch {
1222
- return void 0;
1223
- }
1224
- if (!Array.isArray(parsed) || parsed.length < 2) return void 0;
1225
- const last = parsed[parsed.length - 1];
1226
- return typeof last === "string" ? last : void 0;
1227
- }
1228
- const separator = value.indexOf("/");
1229
- return separator > 0 && separator < value.length - 1 ? value.slice(separator + 1) : void 0;
1230
- }
1231
- function matchAdvertisedModelValue(requestedModelId, advertisedValues) {
1232
- const wanted = requestedModelId.trim();
1233
- if (!wanted) return void 0;
1234
- if (advertisedValues.includes(wanted)) return wanted;
1235
- const byLastSegment = advertisedValues.filter(
1236
- (value) => catalogModelLastSegment(value) === wanted
1237
- );
1238
- return byLastSegment.length === 1 ? byLastSegment[0] : void 0;
1239
- }
1240
1256
  function parseSessionModeState(sessionResponse) {
1241
1257
  const modes = sessionResponse.modes;
1242
1258
  if (!modes) return void 0;
@@ -6817,7 +6833,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6817
6833
  var NONE = 0;
6818
6834
  var ASSUMED = 1;
6819
6835
  var PROVEN = 2;
6820
- function isRecursive(inst, stack, resolve2) {
6836
+ function isRecursive(inst, stack, resolve3) {
6821
6837
  const cached2 = recursive.get(inst);
6822
6838
  if (cached2 !== void 0)
6823
6839
  return cached2 ? PROVEN : NONE;
@@ -6827,7 +6843,7 @@ function isRecursive(inst, stack, resolve2) {
6827
6843
  let result = NONE;
6828
6844
  const check2 = (child) => {
6829
6845
  if (result !== PROVEN && child?._zod) {
6830
- const answer = isRecursive(child, stack, resolve2);
6846
+ const answer = isRecursive(child, stack, resolve3);
6831
6847
  if (answer > result)
6832
6848
  result = answer;
6833
6849
  }
@@ -6838,7 +6854,7 @@ function isRecursive(inst, stack, resolve2) {
6838
6854
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6839
6855
  if (spread && !desc.enumerable)
6840
6856
  continue;
6841
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
6857
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6842
6858
  if (child > answer)
6843
6859
  answer = child;
6844
6860
  }
@@ -6902,7 +6918,7 @@ function isRecursive(inst, stack, resolve2) {
6902
6918
  break;
6903
6919
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6904
6920
  case "lazy": {
6905
- const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
6921
+ const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6906
6922
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6907
6923
  break;
6908
6924
  }
@@ -23152,17 +23168,17 @@ function isResponseMessage(value) {
23152
23168
  function isNotificationMessage(value) {
23153
23169
  return isJsonRpcEnvelope(value) && !("id" in value) && typeof value["method"] === "string";
23154
23170
  }
23155
- function isRecord4(value) {
23171
+ function isRecord5(value) {
23156
23172
  return typeof value === "object" && value !== null;
23157
23173
  }
23158
23174
  function isJsonRpcEnvelope(value) {
23159
- return isRecord4(value) && value["jsonrpc"] === "2.0";
23175
+ return isRecord5(value) && value["jsonrpc"] === "2.0";
23160
23176
  }
23161
23177
  function isJsonRpcId(value) {
23162
23178
  return value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
23163
23179
  }
23164
23180
  function isResponseShapedMessage(value) {
23165
- return isRecord4(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
23181
+ return isRecord5(value) && !("method" in value) && ("id" in value || "result" in value || "error" in value);
23166
23182
  }
23167
23183
  function isResponseBatch(batch) {
23168
23184
  let hasValidCall = false;
@@ -23172,7 +23188,7 @@ function isResponseBatch(batch) {
23172
23188
  for (const entry of batch) {
23173
23189
  hasValidCall ||= isRequestMessage(entry) || isNotificationMessage(entry);
23174
23190
  hasValidResponse ||= isResponseMessage(entry);
23175
- if (!isRecord4(entry)) {
23191
+ if (!isRecord5(entry)) {
23176
23192
  continue;
23177
23193
  }
23178
23194
  hasCallShape ||= "method" in entry;
@@ -23187,13 +23203,13 @@ function isResponseBatch(batch) {
23187
23203
  return hasResponseShape && !hasCallShape;
23188
23204
  }
23189
23205
  function cancelRequestId(params) {
23190
- if (!isRecord4(params) || !isJsonRpcId(params["requestId"])) {
23206
+ if (!isRecord5(params) || !isJsonRpcId(params["requestId"])) {
23191
23207
  return void 0;
23192
23208
  }
23193
23209
  return params["requestId"];
23194
23210
  }
23195
23211
  function isErrorResponse(value) {
23196
- return isRecord4(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
23212
+ return isRecord5(value) && typeof value["code"] === "number" && Number.isInteger(value["code"]) && typeof value["message"] === "string";
23197
23213
  }
23198
23214
  var Handled = {
23199
23215
  /**
@@ -23566,11 +23582,11 @@ var Connection = class {
23566
23582
  const id = this.nextRequestId++;
23567
23583
  let cancel = () => {
23568
23584
  };
23569
- const response = new Promise((resolve2, reject) => {
23585
+ const response = new Promise((resolve3, reject) => {
23570
23586
  const pendingResponse = {
23571
23587
  resolve: (value) => {
23572
23588
  try {
23573
- resolve2(mapResponse ? mapResponse(value) : value);
23589
+ resolve3(mapResponse ? mapResponse(value) : value);
23574
23590
  } catch (error62) {
23575
23591
  reject(error62);
23576
23592
  }
@@ -23627,8 +23643,8 @@ var Connection = class {
23627
23643
  this.stream = stream;
23628
23644
  this.staticHandlers = handlers;
23629
23645
  this.allowBatches = options?.allowBatches ?? true;
23630
- this.closedPromise = new Promise((resolve2) => {
23631
- this.abortController.signal.addEventListener("abort", () => resolve2());
23646
+ this.closedPromise = new Promise((resolve3) => {
23647
+ this.abortController.signal.addEventListener("abort", () => resolve3());
23632
23648
  });
23633
23649
  void this.receive();
23634
23650
  }
@@ -23738,7 +23754,7 @@ var Connection = class {
23738
23754
  if (this.abortController.signal.aborted) {
23739
23755
  return Promise.resolve();
23740
23756
  }
23741
- if (!isRecord4(message)) {
23757
+ if (!isRecord5(message)) {
23742
23758
  console.error("Invalid message", { message });
23743
23759
  return Promise.resolve();
23744
23760
  }
@@ -24141,7 +24157,7 @@ function ndJsonStream(output2, input2) {
24141
24157
  await writeJson(protocolErrorResponse(RequestError.parseError()));
24142
24158
  return;
24143
24159
  }
24144
- if (isRecord4(message) || Array.isArray(message)) {
24160
+ if (isRecord5(message) || Array.isArray(message)) {
24145
24161
  controller.enqueue(message);
24146
24162
  } else {
24147
24163
  await writeJson(protocolErrorResponse(RequestError.invalidRequest(message)));
@@ -24522,8 +24538,8 @@ var AsyncQueue = class {
24522
24538
  if (this.failed) {
24523
24539
  return Promise.reject(this.failure);
24524
24540
  }
24525
- return new Promise((resolve2, reject) => {
24526
- this.waiters.push({ resolve: resolve2, reject });
24541
+ return new Promise((resolve3, reject) => {
24542
+ this.waiters.push({ resolve: resolve3, reject });
24527
24543
  });
24528
24544
  }
24529
24545
  };
@@ -25128,14 +25144,14 @@ var legacyClientNotificationMethods = /* @__PURE__ */ new Set([
25128
25144
  import * as NodeStream from "node:stream";
25129
25145
 
25130
25146
  // ../../packages/ycodium-acp-executor/src/jsonrpc.ts
25131
- function isRecord5(value) {
25147
+ function isRecord6(value) {
25132
25148
  return typeof value === "object" && value !== null;
25133
25149
  }
25134
25150
  function isJsonRpcId2(value) {
25135
25151
  return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
25136
25152
  }
25137
25153
  function isJsonRpcEnvelope2(value) {
25138
- return isRecord5(value) && value["jsonrpc"] === "2.0";
25154
+ return isRecord6(value) && value["jsonrpc"] === "2.0";
25139
25155
  }
25140
25156
  function isRequestMessage2(value) {
25141
25157
  return isJsonRpcEnvelope2(value) && "id" in value && typeof value["method"] === "string" && isJsonRpcId2(value["id"]);
@@ -25155,7 +25171,7 @@ function isNotificationMessage2(value) {
25155
25171
  return isJsonRpcEnvelope2(value) && !("id" in value) && typeof value["method"] === "string";
25156
25172
  }
25157
25173
  function readJsonRpcError(value) {
25158
- if (!isRecord5(value) || typeof value["code"] !== "number" || typeof value["message"] !== "string") {
25174
+ if (!isRecord6(value) || typeof value["code"] !== "number" || typeof value["message"] !== "string") {
25159
25175
  return void 0;
25160
25176
  }
25161
25177
  return {
@@ -25228,11 +25244,11 @@ var KNOWN_SESSION_UPDATES = /* @__PURE__ */ new Set([
25228
25244
  "compaction_summary_chunk"
25229
25245
  ]);
25230
25246
  function isSessionUpdateEnvelope(payload) {
25231
- if (!isRecord5(payload) || typeof payload["sessionId"] !== "string") {
25247
+ if (!isRecord6(payload) || typeof payload["sessionId"] !== "string") {
25232
25248
  return false;
25233
25249
  }
25234
25250
  const update = payload["update"];
25235
- return isRecord5(update) && typeof update["sessionUpdate"] === "string";
25251
+ return isRecord6(update) && typeof update["sessionUpdate"] === "string";
25236
25252
  }
25237
25253
  function hasKnownVariantShape(update) {
25238
25254
  const kind = update["sessionUpdate"];
@@ -25240,7 +25256,7 @@ function hasKnownVariantShape(update) {
25240
25256
  return false;
25241
25257
  }
25242
25258
  if (kind === "user_message_chunk" || kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
25243
- return isRecord5(update["content"]);
25259
+ return isRecord6(update["content"]);
25244
25260
  }
25245
25261
  return true;
25246
25262
  }
@@ -25570,12 +25586,12 @@ function createAcpConnection(options) {
25570
25586
  failIfClosed();
25571
25587
  const id = nextRequestId;
25572
25588
  nextRequestId += 1;
25573
- const { promise: promise2, resolve: resolve2, reject } = Promise.withResolvers();
25589
+ const { promise: promise2, resolve: resolve3, reject } = Promise.withResolvers();
25574
25590
  pending.set(String(id), {
25575
25591
  method,
25576
25592
  ...promptId === void 0 ? {} : { promptId },
25577
25593
  ...onArrival === void 0 ? {} : { onArrival },
25578
- resolve: resolve2,
25594
+ resolve: resolve3,
25579
25595
  reject
25580
25596
  });
25581
25597
  const message = params === void 0 ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
@@ -25604,8 +25620,8 @@ function createAcpConnection(options) {
25604
25620
  if (inboundBatches === 0) {
25605
25621
  return;
25606
25622
  }
25607
- await new Promise((resolve2) => {
25608
- idleWaiters.push(resolve2);
25623
+ await new Promise((resolve3) => {
25624
+ idleWaiters.push(resolve3);
25609
25625
  if (inboundBatches === 0) {
25610
25626
  releaseIdleWaiters();
25611
25627
  }
@@ -25691,8 +25707,8 @@ var Mutex = class {
25691
25707
  this.locked = true;
25692
25708
  return Promise.resolve();
25693
25709
  }
25694
- return new Promise((resolve2) => {
25695
- this.waiters.push(resolve2);
25710
+ return new Promise((resolve3) => {
25711
+ this.waiters.push(resolve3);
25696
25712
  });
25697
25713
  }
25698
25714
  tryAcquire() {
@@ -25892,9 +25908,9 @@ function createExecutorLifecycle({
25892
25908
  let timer;
25893
25909
  await Promise.race([
25894
25910
  connection.closed.catch(() => void 0),
25895
- new Promise((resolve2) => {
25911
+ new Promise((resolve3) => {
25896
25912
  timer = setTimeout(
25897
- resolve2,
25913
+ resolve3,
25898
25914
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
25899
25915
  );
25900
25916
  })
@@ -26008,7 +26024,7 @@ var alignRequestedEffort = async (input2) => {
26008
26024
  return { configOptions, unsupportedEffort, ...confirmed ? { appliedEffort: fallback } : {} };
26009
26025
  };
26010
26026
 
26011
- // ../../packages/ycodium-acp-executor/src/reasoning-level-fallback.ts
26027
+ // ../../packages/ycodium-executor-common/src/reasoningLevelFallback.ts
26012
26028
  var REASONING_LEVEL_FALLBACK_CODE = "reasoning-level-fallback";
26013
26029
  function reasoningLevelFallbackWarning(input2) {
26014
26030
  const model = input2.model ?? "This model";
@@ -26760,12 +26776,12 @@ function createPromptResults({
26760
26776
  }) {
26761
26777
  const prompts = /* @__PURE__ */ new Map();
26762
26778
  const add = (identity, finish) => {
26763
- const { promise: done, resolve: resolve2 } = Promise.withResolvers();
26779
+ const { promise: done, resolve: resolve3 } = Promise.withResolvers();
26764
26780
  const record4 = {
26765
26781
  ...identity,
26766
26782
  finish,
26767
26783
  done,
26768
- resolve: resolve2,
26784
+ resolve: resolve3,
26769
26785
  rejected: false,
26770
26786
  interrupted: false,
26771
26787
  finished: false
@@ -26813,9 +26829,9 @@ function createPromptResults({
26813
26829
  try {
26814
26830
  const drained = await Promise.race([
26815
26831
  Promise.all(claimed.map((record4) => record4.done)).then(() => true),
26816
- new Promise((resolve2) => {
26832
+ new Promise((resolve3) => {
26817
26833
  timer = setTimeout(
26818
- () => resolve2(false),
26834
+ () => resolve3(false),
26819
26835
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
26820
26836
  );
26821
26837
  })
@@ -27014,14 +27030,14 @@ function createExecutorRequests({
27014
27030
  const statement = hooks.permissionStatement?.(permissionContext) ?? defaultPermissionStatement(permissionRequest);
27015
27031
  const fileChanges = hooks.permissionFileChanges?.(permissionContext) ?? fileChangesFromAcpPermission(permissionRequest);
27016
27032
  const requestId = randomId();
27017
- const outcome = await new Promise((resolve2) => {
27033
+ const outcome = await new Promise((resolve3) => {
27018
27034
  const pending = {
27019
27035
  requestId,
27020
27036
  request: params,
27021
27037
  permissionRequest,
27022
27038
  turnId: shared.activeTurnId,
27023
27039
  settled: false,
27024
- resolve: resolve2
27040
+ resolve: resolve3
27025
27041
  };
27026
27042
  approvals.add(pending);
27027
27043
  emit(
@@ -27104,7 +27120,7 @@ function createExecutorRequests({
27104
27120
  }
27105
27121
 
27106
27122
  // ../../packages/ycodium-acp-executor/src/artifacts.ts
27107
- import * as NodePath3 from "node:path";
27123
+ import * as NodePath4 from "node:path";
27108
27124
  import * as NodeURL from "node:url";
27109
27125
  function resourceLinkArtifacts(content) {
27110
27126
  if (content["type"] !== "resource_link" || typeof content["uri"] !== "string") return [];
@@ -27115,7 +27131,7 @@ function resourceLinkArtifacts(content) {
27115
27131
  } catch {
27116
27132
  return [];
27117
27133
  }
27118
- if (!NodePath3.isAbsolute(path)) return [];
27134
+ if (!NodePath4.isAbsolute(path)) return [];
27119
27135
  const name = typeof content["name"] === "string" ? content["name"].trim() : "";
27120
27136
  const mimeType = typeof content["mimeType"] === "string" ? content["mimeType"].trim() : "";
27121
27137
  return [
@@ -27160,7 +27176,7 @@ function makeArtifactEmitter(input2) {
27160
27176
  // ../../packages/ycodium-acp-executor/src/executor/runtime.ts
27161
27177
  function createExecutorRuntime({
27162
27178
  randomId,
27163
- nowIso: nowIso2,
27179
+ nowIso: nowIso4,
27164
27180
  eventStream,
27165
27181
  options,
27166
27182
  assistantItemRuntimeId,
@@ -27169,7 +27185,7 @@ function createExecutorRuntime({
27169
27185
  }) {
27170
27186
  const stamp = () => ({
27171
27187
  eventId: randomId(),
27172
- createdAt: nowIso2()
27188
+ createdAt: nowIso4()
27173
27189
  });
27174
27190
  const isLive = (expectedGeneration) => !shared.disposed && shared.generation === expectedGeneration;
27175
27191
  const publish = (event) => {
@@ -27238,14 +27254,14 @@ function createExecutorRuntime({
27238
27254
  if (!promptMutex.isLocked) {
27239
27255
  return true;
27240
27256
  }
27241
- return await new Promise((resolve2) => {
27257
+ return await new Promise((resolve3) => {
27242
27258
  const timer = setTimeout(() => {
27243
27259
  shared.promptWaiters = shared.promptWaiters.filter((waiter) => waiter !== onSettle);
27244
- resolve2(false);
27260
+ resolve3(false);
27245
27261
  }, timeoutMs);
27246
27262
  const onSettle = () => {
27247
27263
  clearTimeout(timer);
27248
- resolve2(true);
27264
+ resolve3(true);
27249
27265
  };
27250
27266
  shared.promptWaiters.push(onSettle);
27251
27267
  });
@@ -27347,7 +27363,7 @@ function judgeRequestedModel(input2) {
27347
27363
  const hasCurrent = current !== void 0;
27348
27364
  if (!hasCatalog && !hasCurrent && input2.state.modelUnconfirmed !== true) return { kind: "keep" };
27349
27365
  const canSwitch = canSwitchModel(input2.state);
27350
- const value = hasCatalog ? matchAdvertisedModelValue(requested, input2.state.advertisedModelValues) : void 0;
27366
+ const value = hasCatalog ? matchCatalogModel(requested, input2.state.advertisedModelValues) : void 0;
27351
27367
  if (value !== void 0 && value === current) return { kind: "keep" };
27352
27368
  if (value !== void 0 && canSwitch) return { kind: "switch", value };
27353
27369
  return { kind: "refresh" };
@@ -27387,18 +27403,18 @@ function modelRefreshFailedError(requestedModelId, error62) {
27387
27403
  }
27388
27404
 
27389
27405
  // ../../packages/ycodium-acp-executor/src/runtime-mode.ts
27390
- function isRecord6(value) {
27406
+ function isRecord7(value) {
27391
27407
  return typeof value === "object" && value !== null && !Array.isArray(value);
27392
27408
  }
27393
27409
  function asString2(value) {
27394
27410
  return typeof value === "string" ? value : void 0;
27395
27411
  }
27396
27412
  function acpModeConfigId(setup) {
27397
- if (!isRecord6(setup)) return void 0;
27413
+ if (!isRecord7(setup)) return void 0;
27398
27414
  const configOptions = setup["configOptions"];
27399
27415
  if (!Array.isArray(configOptions)) return void 0;
27400
27416
  for (const option of configOptions) {
27401
- if (!isRecord6(option)) continue;
27417
+ if (!isRecord7(option)) continue;
27402
27418
  if (asString2(option["category"])?.trim().toLowerCase() !== "mode") continue;
27403
27419
  const id = asString2(option["id"])?.trim();
27404
27420
  if (id) return id;
@@ -28311,8 +28327,8 @@ function readOpenToolCalls(toolCalls, turnId) {
28311
28327
 
28312
28328
  // ../../packages/ycodium-acp-executor/src/protocol-log.ts
28313
28329
  import * as NodeFS2 from "node:fs";
28314
- import * as NodeOS2 from "node:os";
28315
- import * as NodePath4 from "node:path";
28330
+ import * as NodeOS3 from "node:os";
28331
+ import * as NodePath5 from "node:path";
28316
28332
  var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
28317
28333
  var UNSAFE_FILE_CHARS = /[^A-Za-z0-9._-]+/gu;
28318
28334
  function safeFileName(value) {
@@ -28321,7 +28337,7 @@ function safeFileName(value) {
28321
28337
  function createAcpProtocolLogFile(input2) {
28322
28338
  const maxBytes = input2.maxBytes ?? DEFAULT_MAX_BYTES;
28323
28339
  NodeFS2.mkdirSync(input2.directory, { recursive: true });
28324
- const filePath = NodePath4.join(
28340
+ const filePath = NodePath5.join(
28325
28341
  input2.directory,
28326
28342
  `${safeFileName(input2.provider)}-${safeFileName(input2.threadId)}-${Date.now().toString(36)}.ndjson`
28327
28343
  );
@@ -28377,7 +28393,7 @@ function createAcpProtocolLogFromEnv(input2) {
28377
28393
  const flag = process.env.YCODIUM_ACP_PROTOCOL_LOG;
28378
28394
  if (flag !== "1" && flag?.toLowerCase() !== "true") return void 0;
28379
28395
  const configured = process.env.YCODIUM_ACP_PROTOCOL_LOG_DIR?.trim();
28380
- const directory = configured && configured.length > 0 ? configured : NodePath4.join(NodeOS2.tmpdir(), "ycodium-acp-protocol");
28396
+ const directory = configured && configured.length > 0 ? configured : NodePath5.join(NodeOS3.tmpdir(), "ycodium-acp-protocol");
28381
28397
  try {
28382
28398
  const sink = createAcpProtocolLogFile({
28383
28399
  directory,
@@ -28406,7 +28422,7 @@ function defaultRandomId() {
28406
28422
  function createAcpExecutor(options) {
28407
28423
  const hooks = { ...defaultVendorHooks, ...options.hooks };
28408
28424
  const cancelGraceMs = options.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS;
28409
- const nowIso2 = options.nowIso ?? defaultNowIso;
28425
+ const nowIso4 = options.nowIso ?? defaultNowIso;
28410
28426
  const randomId = options.randomId ?? defaultRandomId;
28411
28427
  const eventStream = new UnboundedEventStream();
28412
28428
  const threadMutex = new Mutex();
@@ -28467,7 +28483,7 @@ function createAcpExecutor(options) {
28467
28483
  waitForPromptIdle
28468
28484
  } = createExecutorRuntime({
28469
28485
  randomId,
28470
- nowIso: nowIso2,
28486
+ nowIso: nowIso4,
28471
28487
  eventStream,
28472
28488
  options,
28473
28489
  assistantItemRuntimeId,
@@ -28711,7 +28727,7 @@ function createAcpExecutor(options) {
28711
28727
  }
28712
28728
 
28713
28729
  // ../../packages/ycodium-acp-executor/src/session-registry.ts
28714
- function createAcpSessionRegistry(threads, stopBooked2, log) {
28730
+ function createAcpSessionRegistry(threads, stopBooked, log) {
28715
28731
  const exits = /* @__PURE__ */ new WeakMap();
28716
28732
  const requireThread = (threadId) => {
28717
28733
  const booked = threads.get(threadId);
@@ -28722,7 +28738,7 @@ function createAcpSessionRegistry(threads, stopBooked2, log) {
28722
28738
  const stopSession = (threadId, booked = threads.get(threadId)) => {
28723
28739
  if (!booked) return Promise.resolve();
28724
28740
  const close = { exitCode: exits.get(booked), hasExited: () => exits.has(booked) };
28725
- booked.closing ??= Promise.resolve().then(() => stopBooked2(booked, close)).then(() => {
28741
+ booked.closing ??= Promise.resolve().then(() => stopBooked(booked, close)).then(() => {
28726
28742
  if (threads.get(threadId) === booked) threads.delete(threadId);
28727
28743
  }).catch((cause) => {
28728
28744
  if (threads.get(threadId) === booked) delete booked.closing;
@@ -28819,13 +28835,13 @@ function acpNativeSessionProcessMatcher(program, args) {
28819
28835
 
28820
28836
  // ../../packages/ycodium-acp-executor/src/prompt-dispatch.ts
28821
28837
  var dispatchAcpPrompt = (executor, input2) => {
28822
- const { promise: dispatched, resolve: resolve2 } = Promise.withResolvers();
28838
+ const { promise: dispatched, resolve: resolve3 } = Promise.withResolvers();
28823
28839
  let written = false;
28824
28840
  const finished = executor.prompt({
28825
28841
  ...input2,
28826
28842
  onDispatched: (turnId) => {
28827
28843
  written = true;
28828
- resolve2(turnId);
28844
+ resolve3(turnId);
28829
28845
  }
28830
28846
  });
28831
28847
  return Promise.race([
@@ -28839,63 +28855,257 @@ var dispatchAcpPrompt = (executor, input2) => {
28839
28855
  ]);
28840
28856
  };
28841
28857
 
28842
- // ../../packages/ycodium-acp-executor/src/start-abort.ts
28843
- function throwIfStartAborted(signal) {
28844
- if (signal?.aborted) throw new Error("aborted");
28845
- }
28846
- async function raceStartAbort(promise2, signal) {
28847
- void promise2.catch(() => void 0);
28848
- throwIfStartAborted(signal);
28849
- if (signal === void 0) return promise2;
28850
- const aborted2 = Promise.withResolvers();
28851
- const onAbort = () => aborted2.reject(new Error("aborted"));
28852
- signal.addEventListener("abort", onAbort, { once: true });
28853
- try {
28854
- return await Promise.race([promise2, aborted2.promise]);
28855
- } finally {
28856
- signal.removeEventListener("abort", onAbort);
28857
- }
28858
- }
28859
-
28860
- // ../../packages/ycodium-acp-executor/src/mcp-servers.ts
28861
- function toAcpMcpServers(entries) {
28862
- return (entries ?? []).map(
28863
- (entry) => entry.transport.type === "stdio" ? {
28864
- name: entry.name,
28865
- command: entry.transport.command,
28866
- args: [...entry.transport.args ?? []],
28867
- env: Object.entries(entry.transport.env ?? {}).map(([name, value]) => ({ name, value }))
28868
- } : {
28869
- type: entry.transport.type,
28870
- name: entry.name,
28871
- url: entry.transport.url,
28872
- headers: Object.entries(entry.transport.headers ?? {}).map(([name, value]) => ({
28873
- name,
28874
- value
28875
- }))
28876
- }
28877
- );
28878
- }
28879
-
28880
- // ../../packages/ycodium-acp-executor/src/probe.ts
28881
- function withProbeTimeout(promise2, timeoutMs, what, signal) {
28882
- signal?.throwIfAborted();
28883
- return new Promise((resolve2, reject) => {
28884
- const onAbort = () => {
28885
- clearTimeout(timer);
28886
- reject(signal?.reason ?? new Error("aborted"));
28887
- };
28888
- const timer = setTimeout(() => {
28889
- signal?.removeEventListener("abort", onAbort);
28890
- reject(new Error(`${what} timed out after ${timeoutMs}ms`));
28891
- }, timeoutMs);
28892
- timer.unref?.();
28893
- signal?.addEventListener("abort", onAbort, { once: true });
28894
- promise2.then(
28895
- (value) => {
28896
- clearTimeout(timer);
28897
- signal?.removeEventListener("abort", onAbort);
28898
- resolve2(value);
28858
+ // ../../packages/ycodium-acp-executor/src/thread-operations.ts
28859
+ var yieldTick = () => new Promise((resolve3) => {
28860
+ setImmediate(resolve3);
28861
+ });
28862
+ var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
28863
+ function createAcpThreadOperations(options) {
28864
+ const { threads, requireThread } = options;
28865
+ return {
28866
+ sendTurn: async (input2, signal) => {
28867
+ if (options.isDisposed()) throw new Error("instance disposed");
28868
+ const booked = requireThread(input2.threadId);
28869
+ if (signal?.aborted) throw new Error("aborted");
28870
+ options.beforeSendTurn?.(booked);
28871
+ const onAbort = () => {
28872
+ void booked.executor.cancel(input2.expectedTurnId).catch(() => void 0);
28873
+ };
28874
+ signal?.addEventListener("abort", onAbort);
28875
+ try {
28876
+ const { requestedModelId, requestedEffort } = options.turnSelection?.(input2.modelSelection) ?? {};
28877
+ const turn = await dispatchAcpPrompt(booked.executor, {
28878
+ text: input2.input ?? "",
28879
+ expectedActiveTurnId: input2.expectedTurnId,
28880
+ ...requestedModelId === void 0 ? {} : { requestedModelId },
28881
+ ...requestedEffort === void 0 ? {} : { requestedEffort }
28882
+ });
28883
+ booked.turns.push({ id: turn.turnId, items: [] });
28884
+ return {
28885
+ threadId: input2.threadId,
28886
+ turnId: turn.turnId,
28887
+ ...booked.session.resumeCursor === void 0 ? {} : { resumeCursor: booked.session.resumeCursor }
28888
+ };
28889
+ } finally {
28890
+ signal?.removeEventListener("abort", onAbort);
28891
+ }
28892
+ },
28893
+ interruptTurn: async (threadId, turnId) => {
28894
+ const booked = threads.get(threadId);
28895
+ if (booked === void 0 || booked.closing) return;
28896
+ options.log.info("interrupt turn", { threadId, turnId });
28897
+ await booked.executor.cancel(turnId);
28898
+ await yieldTick();
28899
+ },
28900
+ respondToRequest: async (threadId, requestId, decision, reason) => {
28901
+ const booked = requireThread(threadId);
28902
+ await booked.executor.respondToRequest(
28903
+ requestId,
28904
+ decision === "allow" ? "accept" : "decline",
28905
+ reason
28906
+ );
28907
+ },
28908
+ respondToUserInput: async (threadId, requestId, answers) => {
28909
+ const booked = requireThread(threadId);
28910
+ await booked.executor.respondToUserInput(requestId, answers);
28911
+ },
28912
+ /**
28913
+ * 切这只手自报的审批档。`nativeModeId` 是它自己报的 id(探测时原样上报的那些),
28914
+ * 一路不翻译成宿主四档。
28915
+ *
28916
+ * 这是 `setRuntimeMode` 做不到的那一半:那个只改插件自己的会话记录,CLI 收不到
28917
+ * (`runtime-mode-never-reaches-cli` 记的那族缺陷)。
28918
+ */
28919
+ setNativeMode: async (threadId, nativeModeId) => {
28920
+ const booked = requireThread(threadId);
28921
+ await booked.executor.setNativeMode(nativeModeId);
28922
+ booked.session = { ...booked.session, nativeModeId, updatedAt: nowIso() };
28923
+ },
28924
+ setRuntimeMode: async (threadId, runtimeMode) => {
28925
+ const booked = requireThread(threadId);
28926
+ booked.session = { ...booked.session, runtimeMode, updatedAt: nowIso() };
28927
+ },
28928
+ readThread: async (threadId) => {
28929
+ const booked = requireThread(threadId);
28930
+ return { threadId, turns: booked.turns };
28931
+ }
28932
+ };
28933
+ }
28934
+
28935
+ // ../../packages/ycodium-acp-executor/src/mcp-servers.ts
28936
+ function toAcpMcpServers(entries) {
28937
+ return (entries ?? []).map(
28938
+ (entry) => entry.transport.type === "stdio" ? {
28939
+ name: entry.name,
28940
+ command: entry.transport.command,
28941
+ args: [...entry.transport.args ?? []],
28942
+ env: Object.entries(entry.transport.env ?? {}).map(([name, value]) => ({ name, value }))
28943
+ } : {
28944
+ type: entry.transport.type,
28945
+ name: entry.name,
28946
+ url: entry.transport.url,
28947
+ headers: Object.entries(entry.transport.headers ?? {}).map(([name, value]) => ({
28948
+ name,
28949
+ value
28950
+ }))
28951
+ }
28952
+ );
28953
+ }
28954
+
28955
+ // ../../packages/ycodium-acp-executor/src/start-abort.ts
28956
+ function throwIfStartAborted(signal) {
28957
+ if (signal?.aborted) throw new Error("aborted");
28958
+ }
28959
+ async function raceStartAbort(promise2, signal) {
28960
+ void promise2.catch(() => void 0);
28961
+ throwIfStartAborted(signal);
28962
+ if (signal === void 0) return promise2;
28963
+ const aborted2 = Promise.withResolvers();
28964
+ const onAbort = () => aborted2.reject(new Error("aborted"));
28965
+ signal.addEventListener("abort", onAbort, { once: true });
28966
+ try {
28967
+ return await Promise.race([promise2, aborted2.promise]);
28968
+ } finally {
28969
+ signal.removeEventListener("abort", onAbort);
28970
+ }
28971
+ }
28972
+
28973
+ // ../../packages/ycodium-acp-executor/src/instance-kit.ts
28974
+ var yieldTick2 = () => new Promise((resolve3) => {
28975
+ setImmediate(resolve3);
28976
+ });
28977
+ var nowIso2 = () => (/* @__PURE__ */ new Date()).toISOString();
28978
+ function createAcpThreadTable(log, beforeStopAll) {
28979
+ const threads = /* @__PURE__ */ new Map();
28980
+ const registry2 = createAcpSessionRegistry(
28981
+ threads,
28982
+ (booked, processExit) => cleanupAcpSession({
28983
+ executor: booked.executor,
28984
+ stopProcess: () => booked.handle.kill("SIGTERM"),
28985
+ forwarding: booked.forwarding,
28986
+ processExit
28987
+ }),
28988
+ log
28989
+ );
28990
+ const disposeOnce = createRetryableClose(async () => {
28991
+ await beforeStopAll?.();
28992
+ await registry2.stopAll();
28993
+ });
28994
+ return { threads, ...registry2, disposeOnce };
28995
+ }
28996
+ async function stopExistingAcpThread(table, threadId, isDisposed, signal) {
28997
+ const existing = table.threads.get(threadId);
28998
+ if (existing === void 0) return;
28999
+ await table.stopSession(threadId, existing);
29000
+ if (isDisposed()) throw new Error("instance disposed");
29001
+ throwIfStartAborted(signal);
29002
+ }
29003
+ function acpResumeFrom(input2, schemaVersion) {
29004
+ return input2.discardResumeCursor === true ? void 0 : parseAcpResumeCursor(input2.resumeCursor, schemaVersion);
29005
+ }
29006
+ function acpStartedSession(input2, started) {
29007
+ const createdAt = nowIso2();
29008
+ return {
29009
+ provider: input2.provider,
29010
+ providerInstanceId: input2.providerInstanceId,
29011
+ status: "idle",
29012
+ runtimeMode: input2.runtimeMode,
29013
+ ...input2.nativeModeId === void 0 ? {} : { nativeModeId: input2.nativeModeId },
29014
+ cwd: input2.cwd,
29015
+ threadId: input2.threadId,
29016
+ createdAt,
29017
+ updatedAt: createdAt,
29018
+ resumeCursor: { schemaVersion: input2.resumeSchemaVersion, sessionId: started.sessionId },
29019
+ ...started.modelId === void 0 ? {} : {
29020
+ model: started.modelId,
29021
+ // agent 在握手里报的才是读回的;切型号走 session/set_model 时回包不带型号,那只是请求值。
29022
+ modelSource: started.modelReported ? "reported" : "echo"
29023
+ },
29024
+ ...input2.bindingGeneration === void 0 ? {} : { bindingGeneration: input2.bindingGeneration }
29025
+ };
29026
+ }
29027
+ async function openAcpThread(input2) {
29028
+ const { executor, handle, signal, threadId } = input2;
29029
+ const forwarding = (async () => {
29030
+ for await (const event of executor.events) {
29031
+ const forwarded = input2.forward(event);
29032
+ if (forwarded !== void 0) await forwarded;
29033
+ }
29034
+ })();
29035
+ try {
29036
+ throwIfStartAborted(signal);
29037
+ const started = await raceStartAbort(executor.start(), signal);
29038
+ const after = input2.afterStart?.(started);
29039
+ if (after !== void 0) await after;
29040
+ await yieldTick2();
29041
+ throwIfStartAborted(signal);
29042
+ const session = input2.session(started);
29043
+ input2.registerSession(
29044
+ threadId,
29045
+ input2.booked({ session, turns: [], executor, handle, forwarding })
29046
+ );
29047
+ input2.log.info("session started", { threadId, sessionId: started.sessionId });
29048
+ input2.afterRegister?.();
29049
+ return session;
29050
+ } catch (error62) {
29051
+ await cleanupAcpStartup({
29052
+ executor,
29053
+ stopProcess: () => handle.kill("SIGTERM"),
29054
+ forwarding,
29055
+ log: input2.log,
29056
+ threadId
29057
+ });
29058
+ throw error62;
29059
+ }
29060
+ }
29061
+ function acpLaunchMcpFields(input2) {
29062
+ const omit2 = input2.omitWhenEmpty === true && (input2.mcpServers === void 0 || input2.mcpServers.length === 0);
29063
+ return {
29064
+ ...omit2 ? {} : { mcpServers: toAcpMcpServers(input2.mcpServers) },
29065
+ ...input2.resumeSessionId === void 0 ? {} : { resumeSessionId: input2.resumeSessionId }
29066
+ };
29067
+ }
29068
+ function openAcpThreadSession(input2) {
29069
+ return openAcpThread({
29070
+ registerSession: input2.registerSession,
29071
+ threadId: input2.threadId,
29072
+ executor: input2.executor,
29073
+ handle: input2.handle,
29074
+ ...input2.signal === void 0 ? {} : { signal: input2.signal },
29075
+ log: input2.log,
29076
+ forward: input2.emit,
29077
+ ...input2.afterStart === void 0 ? {} : { afterStart: input2.afterStart },
29078
+ session: (started) => {
29079
+ input2.beforeSession?.(started);
29080
+ return acpStartedSession({ ...input2.session, threadId: input2.threadId }, started);
29081
+ },
29082
+ booked: input2.booked,
29083
+ ...input2.afterRegister === void 0 ? {} : { afterRegister: input2.afterRegister }
29084
+ });
29085
+ }
29086
+
29087
+ // ../../packages/ycodium-acp-executor/src/probe-session.ts
29088
+ var acpProbeFailureDetail = (error62) => (error62 instanceof Error ? error62.message : String(error62)).trim() || void 0;
29089
+
29090
+ // ../../packages/ycodium-acp-executor/src/probe.ts
29091
+ function withProbeTimeout(promise2, timeoutMs, what, signal) {
29092
+ signal?.throwIfAborted();
29093
+ return new Promise((resolve3, reject) => {
29094
+ const onAbort = () => {
29095
+ clearTimeout(timer);
29096
+ reject(signal?.reason ?? new Error("aborted"));
29097
+ };
29098
+ const timer = setTimeout(() => {
29099
+ signal?.removeEventListener("abort", onAbort);
29100
+ reject(new Error(`${what} timed out after ${timeoutMs}ms`));
29101
+ }, timeoutMs);
29102
+ timer.unref?.();
29103
+ signal?.addEventListener("abort", onAbort, { once: true });
29104
+ promise2.then(
29105
+ (value) => {
29106
+ clearTimeout(timer);
29107
+ signal?.removeEventListener("abort", onAbort);
29108
+ resolve3(value);
28899
29109
  },
28900
29110
  (error62) => {
28901
29111
  clearTimeout(timer);
@@ -28999,51 +29209,8 @@ async function collectProbeProcess(child, input2) {
28999
29209
  }
29000
29210
  var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
29001
29211
 
29002
- // src/config.ts
29003
- var GROK_DEFAULT_LAUNCH_ARGS = "agent stdio";
29004
- function isRecord7(value) {
29005
- return typeof value === "object" && value !== null && !Array.isArray(value);
29006
- }
29007
- function readString2(value) {
29008
- return typeof value === "string" ? value : "";
29009
- }
29010
- function readTrimmed(value) {
29011
- return readString2(value).trim();
29012
- }
29013
- function readEnvironment(value) {
29014
- if (!Array.isArray(value)) return {};
29015
- const env = {};
29016
- for (const entry of value) {
29017
- if (!isRecord7(entry)) continue;
29018
- const name = readTrimmed(entry["name"]);
29019
- if (name.length === 0) continue;
29020
- env[name] = readString2(entry["value"]);
29021
- }
29022
- return env;
29023
- }
29024
- function parseGrokInstanceConfig(config2) {
29025
- if (!isRecord7(config2)) {
29026
- return {
29027
- binaryPath: "",
29028
- launchArgs: GROK_DEFAULT_LAUNCH_ARGS,
29029
- homePath: "",
29030
- homeEnvVar: "",
29031
- environment: {},
29032
- envelopeDriver: void 0
29033
- };
29034
- }
29035
- const nested = isRecord7(config2["config"]) ? config2["config"] : void 0;
29036
- const settings = nested ?? config2;
29037
- return {
29038
- binaryPath: readTrimmed(settings["binaryPath"]),
29039
- launchArgs: readString2(settings["launchArgs"]) || GROK_DEFAULT_LAUNCH_ARGS,
29040
- homePath: readTrimmed(settings["homePath"]) || readTrimmed(config2["homePath"]),
29041
- homeEnvVar: readTrimmed(settings["homeEnvVar"]) || readTrimmed(config2["homeEnvVar"]),
29042
- environment: readEnvironment(config2["environment"]),
29043
- envelopeDriver: readTrimmed(config2["driver"]) || void 0
29044
- };
29045
- }
29046
- function tokenizeLaunchArgs(value) {
29212
+ // ../../packages/ycodium-instance-config/src/launchArgs.ts
29213
+ function tokenizeShellWords(value) {
29047
29214
  const input2 = value.trim();
29048
29215
  if (!input2) return [];
29049
29216
  const tokens = [];
@@ -29095,9 +29262,76 @@ function tokenizeLaunchArgs(value) {
29095
29262
  return tokens;
29096
29263
  }
29097
29264
 
29265
+ // ../../packages/ycodium-instance-config/src/instanceConfig.ts
29266
+ import { modelSelectionStringOption as modelSelectionStringOption2 } from "@ycodium-ai/plugin-api/executor";
29267
+ function isRecord8(value) {
29268
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29269
+ }
29270
+ function readString(value) {
29271
+ return typeof value === "string" ? value : "";
29272
+ }
29273
+ function readTrimmed(value) {
29274
+ return readString(value).trim();
29275
+ }
29276
+ function modelIdFromSelection(selection) {
29277
+ if (!isRecord8(selection)) return void 0;
29278
+ const model = selection["model"];
29279
+ return typeof model === "string" ? model.trim() || void 0 : void 0;
29280
+ }
29281
+ function readTurnSelection(selection, effortOptionId) {
29282
+ const requestedModelId = modelIdFromSelection(selection);
29283
+ const requestedEffort = modelSelectionStringOption2(selection, effortOptionId);
29284
+ return {
29285
+ ...requestedModelId === void 0 ? {} : { requestedModelId },
29286
+ ...requestedEffort === void 0 ? {} : { requestedEffort }
29287
+ };
29288
+ }
29289
+ function readEnvironment(value) {
29290
+ if (!Array.isArray(value)) return {};
29291
+ const env = {};
29292
+ for (const entry of value) {
29293
+ if (!isRecord8(entry)) continue;
29294
+ const name = readTrimmed(entry["name"]);
29295
+ if (name.length === 0) continue;
29296
+ env[name] = readString(entry["value"]);
29297
+ }
29298
+ return env;
29299
+ }
29300
+ function instanceSettings(config2) {
29301
+ if (!isRecord8(config2)) return {};
29302
+ return isRecord8(config2["config"]) ? config2["config"] : config2;
29303
+ }
29304
+ function readInstanceEnvelope(config2) {
29305
+ const envelope = isRecord8(config2) ? config2 : {};
29306
+ const settings = instanceSettings(config2);
29307
+ return {
29308
+ settings,
29309
+ settingOrEnvelope: (key) => readTrimmed(settings[key]) || readTrimmed(envelope[key]),
29310
+ environment: readEnvironment(envelope["environment"]),
29311
+ envelopeDriver: readTrimmed(envelope["driver"]) || void 0
29312
+ };
29313
+ }
29314
+ function readLaunchInstanceRecipe(config2, defaultLaunchArgs = "") {
29315
+ const envelope = readInstanceEnvelope(config2);
29316
+ return {
29317
+ binaryPath: readTrimmed(envelope.settings["binaryPath"]),
29318
+ launchArgs: readString(envelope.settings["launchArgs"]) || defaultLaunchArgs,
29319
+ homePath: envelope.settingOrEnvelope("homePath"),
29320
+ homeEnvVar: envelope.settingOrEnvelope("homeEnvVar"),
29321
+ environment: envelope.environment,
29322
+ envelopeDriver: envelope.envelopeDriver
29323
+ };
29324
+ }
29325
+
29326
+ // src/config.ts
29327
+ var GROK_DEFAULT_LAUNCH_ARGS = "agent stdio";
29328
+ function parseGrokInstanceConfig(config2) {
29329
+ return readLaunchInstanceRecipe(config2, GROK_DEFAULT_LAUNCH_ARGS);
29330
+ }
29331
+
29098
29332
  // src/grokSignIn.ts
29099
29333
  import {
29100
- raceAbort
29334
+ raceAbort as raceAbort2
29101
29335
  } from "@ycodium-ai/plugin-api/executor";
29102
29336
 
29103
29337
  // src/deviceCodeOutput.ts
@@ -29111,13 +29345,13 @@ var hasDeviceCode = (output2) => deviceCodeUrl(output2) !== void 0 && deviceCode
29111
29345
  function readDeviceCodeOutput(stdout, onText) {
29112
29346
  const collected = [];
29113
29347
  let onCodeFound;
29114
- const codeFound = new Promise((resolve2) => {
29115
- onCodeFound = resolve2;
29348
+ const codeFound = new Promise((resolve3) => {
29349
+ onCodeFound = resolve3;
29116
29350
  });
29117
29351
  let quietTimer;
29118
29352
  let onQuiet;
29119
- const outputWentQuiet = new Promise((resolve2) => {
29120
- onQuiet = resolve2;
29353
+ const outputWentQuiet = new Promise((resolve3) => {
29354
+ onQuiet = resolve3;
29121
29355
  });
29122
29356
  const text4 = (async () => {
29123
29357
  const decoder = new TextDecoder();
@@ -29142,8 +29376,8 @@ function readDeviceCodeOutput(stdout, onText) {
29142
29376
  codeFound,
29143
29377
  text4.then(() => void 0),
29144
29378
  outputWentQuiet,
29145
- new Promise((resolve2) => {
29146
- silentCap = setTimeout(resolve2, SILENT_CAP_MS);
29379
+ new Promise((resolve3) => {
29380
+ silentCap = setTimeout(resolve3, SILENT_CAP_MS);
29147
29381
  })
29148
29382
  ]);
29149
29383
  clearTimeout(silentCap);
@@ -29192,7 +29426,7 @@ function makeGrokSignIn(input2) {
29192
29426
  };
29193
29427
  operations.set(operationId, operation);
29194
29428
  try {
29195
- const code = await raceAbort(output2.code, signal);
29429
+ const code = await raceAbort2(output2.code, signal);
29196
29430
  if (signal?.aborted || input2.isDisposed()) throw new Error("Grok sign-in cancelled");
29197
29431
  return { operationId, ...code };
29198
29432
  } catch (error62) {
@@ -29207,7 +29441,7 @@ function makeGrokSignIn(input2) {
29207
29441
  const active2 = [...operations.values()];
29208
29442
  try {
29209
29443
  for (const operation of active2) {
29210
- const code = await raceAbort(operation.handle.exited, signal);
29444
+ const code = await raceAbort2(operation.handle.exited, signal);
29211
29445
  if (code !== 0) throw new Error(`Grok sign-in exited with code ${String(code)}`);
29212
29446
  }
29213
29447
  return await input2.probe(signal);
@@ -29226,14 +29460,47 @@ function makeGrokSignIn(input2) {
29226
29460
 
29227
29461
  // src/grokQuota.ts
29228
29462
  import * as NodeFS3 from "node:fs";
29229
- import * as NodePath5 from "node:path";
29230
- import {
29231
- parseRetryAfterMs
29232
- } from "@ycodium-ai/plugin-api/usage";
29233
- var GROK_USAGE_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
29234
- var GROK_ISSUER_PREFIX = "https://auth.x.ai::";
29235
- var AUTH_FILE_NAME2 = "auth.json";
29236
- var QUOTA_TIMEOUT_MS = 1e4;
29463
+ import * as NodePath6 from "node:path";
29464
+ import "@ycodium-ai/plugin-api/usage";
29465
+
29466
+ // ../../packages/ycodium-credential-account/src/quotaRequest.ts
29467
+ import { parseRetryAfterMs } from "@ycodium-ai/plugin-api/usage";
29468
+ async function requestQuotaJson(input2) {
29469
+ let response;
29470
+ try {
29471
+ response = await input2.fetch(input2.url, {
29472
+ headers: input2.headers,
29473
+ signal: AbortSignal.any([
29474
+ ...input2.signal === void 0 ? [] : [input2.signal],
29475
+ AbortSignal.timeout(input2.timeoutMs)
29476
+ ])
29477
+ });
29478
+ } catch {
29479
+ return { status: "unavailable", reason: "unreachable" };
29480
+ }
29481
+ if (response.status === 401 || response.status === 403) {
29482
+ return { status: "unavailable", reason: "authRejected" };
29483
+ }
29484
+ if (response.status === 429) {
29485
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), input2.now());
29486
+ return {
29487
+ status: "unavailable",
29488
+ reason: "rateLimited",
29489
+ ...retryAfterMs === null ? {} : { retryAfterMs }
29490
+ };
29491
+ }
29492
+ if (!response.ok) return { status: "unavailable", reason: "unreachable" };
29493
+ let body;
29494
+ try {
29495
+ body = JSON.parse(await response.text());
29496
+ } catch {
29497
+ return { status: "unavailable", reason: "unreachable" };
29498
+ }
29499
+ if (!isRecord(body)) return { status: "unavailable", reason: "unreachable" };
29500
+ return { body };
29501
+ }
29502
+
29503
+ // ../../packages/ycodium-credential-account/src/quotaJson.ts
29237
29504
  var asObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
29238
29505
  var asString3 = (value) => typeof value === "string" && value.length > 0 ? value : null;
29239
29506
  var asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
@@ -29244,6 +29511,12 @@ var parseJson = (raw) => {
29244
29511
  return null;
29245
29512
  }
29246
29513
  };
29514
+
29515
+ // src/grokQuota.ts
29516
+ var GROK_USAGE_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
29517
+ var GROK_ISSUER_PREFIX = "https://auth.x.ai::";
29518
+ var AUTH_FILE_NAME2 = "auth.json";
29519
+ var QUOTA_TIMEOUT_MS = 1e4;
29247
29520
  var extractGrokToken = (auth) => {
29248
29521
  const record4 = asObject(auth);
29249
29522
  if (record4 === null) return null;
@@ -29273,7 +29546,7 @@ var grokQuotaWindows = (body) => {
29273
29546
  };
29274
29547
  var createGrokUsage = (input2) => {
29275
29548
  const now = input2.now ?? Date.now;
29276
- const authPath = NodePath5.join(input2.homePath, AUTH_FILE_NAME2);
29549
+ const authPath = NodePath6.join(input2.homePath, AUTH_FILE_NAME2);
29277
29550
  const readQuota = async (request) => {
29278
29551
  const baseUrlKey = GROK_CARD.modelConnectivity.baseUrlEnvKey;
29279
29552
  if (baseUrlKey !== void 0 && (input2.environment[baseUrlKey]?.trim() ?? "") !== "") {
@@ -29292,41 +29565,20 @@ var createGrokUsage = (input2) => {
29292
29565
  reason: apiKey.length > 0 ? "unsupportedLogin" : "missingCredentials"
29293
29566
  };
29294
29567
  }
29295
- let response;
29296
- try {
29297
- response = await input2.fetch(GROK_USAGE_URL, {
29298
- headers: {
29299
- Authorization: `Bearer ${token}`,
29300
- Accept: "application/json",
29301
- "X-XAI-Token-Auth": "xai-grok-cli"
29302
- },
29303
- signal: AbortSignal.any([
29304
- ...request.signal === void 0 ? [] : [request.signal],
29305
- AbortSignal.timeout(QUOTA_TIMEOUT_MS)
29306
- ])
29307
- });
29308
- } catch {
29309
- return { status: "unavailable", reason: "unreachable" };
29310
- }
29311
- if (response.status === 401 || response.status === 403) {
29312
- return { status: "unavailable", reason: "authRejected" };
29313
- }
29314
- if (response.status === 429) {
29315
- const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), now());
29316
- return {
29317
- status: "unavailable",
29318
- reason: "rateLimited",
29319
- ...retryAfterMs === null ? {} : { retryAfterMs }
29320
- };
29321
- }
29322
- if (!response.ok) return { status: "unavailable", reason: "unreachable" };
29323
- let body;
29324
- try {
29325
- body = parseJson(await response.text());
29326
- } catch {
29327
- return { status: "unavailable", reason: "unreachable" };
29328
- }
29329
- if (asObject(body) === null) return { status: "unavailable", reason: "unreachable" };
29568
+ const answer = await requestQuotaJson({
29569
+ fetch: input2.fetch,
29570
+ url: GROK_USAGE_URL,
29571
+ headers: {
29572
+ Authorization: `Bearer ${token}`,
29573
+ Accept: "application/json",
29574
+ "X-XAI-Token-Auth": "xai-grok-cli"
29575
+ },
29576
+ ...request.signal === void 0 ? {} : { signal: request.signal },
29577
+ timeoutMs: QUOTA_TIMEOUT_MS,
29578
+ now
29579
+ });
29580
+ if (!("body" in answer)) return answer;
29581
+ const { body } = answer;
29330
29582
  return {
29331
29583
  status: "available",
29332
29584
  windows: grokQuotaWindows(body),
@@ -29339,11 +29591,11 @@ var createGrokUsage = (input2) => {
29339
29591
 
29340
29592
  // src/grokTurnUsage.ts
29341
29593
  var USAGE_GRACE_MS = 300;
29342
- var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29594
+ var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29343
29595
  var count = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
29344
29596
  var text = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
29345
29597
  var readModelTotals = (entry) => {
29346
- if (!isRecord8(entry)) return void 0;
29598
+ if (!isRecord9(entry)) return void 0;
29347
29599
  const input2 = count(entry["inputTokens"]);
29348
29600
  const cachedInputTokens = count(entry["cachedReadTokens"]);
29349
29601
  const cacheCreationTokens = count(entry["cacheCreationTokens"]);
@@ -29358,12 +29610,12 @@ var readModelTotals = (entry) => {
29358
29610
  };
29359
29611
  var sumOf = (totals) => totals.uncachedInputTokens + totals.cachedInputTokens + totals.cacheCreationTokens + totals.outputTokens;
29360
29612
  var grokTurnUsageReport = (promptResponse) => {
29361
- const meta3 = isRecord8(promptResponse) ? promptResponse["_meta"] : void 0;
29362
- const usage = isRecord8(meta3) ? meta3["usage"] : void 0;
29363
- if (!isRecord8(meta3) || !isRecord8(usage)) return void 0;
29613
+ const meta3 = isRecord9(promptResponse) ? promptResponse["_meta"] : void 0;
29614
+ const usage = isRecord9(meta3) ? meta3["usage"] : void 0;
29615
+ if (!isRecord9(meta3) || !isRecord9(usage)) return void 0;
29364
29616
  const perModel = /* @__PURE__ */ new Map();
29365
29617
  const modelUsage = usage["modelUsage"];
29366
- if (isRecord8(modelUsage)) {
29618
+ if (isRecord9(modelUsage)) {
29367
29619
  for (const [model, entry] of Object.entries(modelUsage)) {
29368
29620
  const totals = readModelTotals(entry);
29369
29621
  if (totals !== void 0 && model.trim().length > 0) perModel.set(model.trim(), totals);
@@ -29441,13 +29693,13 @@ var createGrokTurnUsageCollector = (base) => {
29441
29693
  }
29442
29694
  };
29443
29695
  const attach = async (event) => {
29444
- if (event.type !== "turn.completed" || !isRecord8(event.payload)) return event;
29696
+ if (event.type !== "turn.completed" || !isRecord9(event.payload)) return event;
29445
29697
  if (event.payload["state"] === "completed" && !allAnswered()) {
29446
- await new Promise((resolve2) => {
29447
- const timer = setTimeout(resolve2, USAGE_GRACE_MS);
29698
+ await new Promise((resolve3) => {
29699
+ const timer = setTimeout(resolve3, USAGE_GRACE_MS);
29448
29700
  wake = () => {
29449
29701
  clearTimeout(timer);
29450
- resolve2();
29702
+ resolve3();
29451
29703
  };
29452
29704
  });
29453
29705
  wake = void 0;
@@ -29471,16 +29723,16 @@ var XAI_EXIT_PLAN_MODE_METHODS = [
29471
29723
  var GROK_PLAN_APPROVE_OPTION_ID = "approved";
29472
29724
  var GROK_PLAN_ABANDON_OPTION_ID = "abandoned";
29473
29725
  var GROK_EMPTY_PLAN_TEXT = "The agent exited plan mode without writing a plan.";
29474
- var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29726
+ var isRecord10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29475
29727
  var trimmed = (value) => {
29476
29728
  if (typeof value !== "string") return void 0;
29477
29729
  const text4 = value.trim();
29478
29730
  return text4.length > 0 ? text4 : void 0;
29479
29731
  };
29480
29732
  function parseXAiExitPlanModeParams(params) {
29481
- const candidates = [params, ...isRecord9(params) ? [params["params"]] : []];
29733
+ const candidates = [params, ...isRecord10(params) ? [params["params"]] : []];
29482
29734
  for (const candidate of candidates) {
29483
- if (!isRecord9(candidate)) continue;
29735
+ if (!isRecord10(candidate)) continue;
29484
29736
  const toolCallId = trimmed(candidate["toolCallId"]);
29485
29737
  if (toolCallId === void 0) continue;
29486
29738
  return { toolCallId, planContent: trimmed(candidate["planContent"]) };
@@ -29532,7 +29784,7 @@ function makeXAiExitPlanModeResponse(params, resolution) {
29532
29784
  import { REASONING_OPTION_LABEL, reasoningEffortShortLabel } from "@ycodium-ai/plugin-api/executor";
29533
29785
 
29534
29786
  // src/grokJson.ts
29535
- var isRecord10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29787
+ var isRecord11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29536
29788
  var trimmed2 = (value) => {
29537
29789
  if (typeof value !== "string") return void 0;
29538
29790
  const text4 = value.trim();
@@ -29542,11 +29794,11 @@ var trimmed2 = (value) => {
29542
29794
  // src/grokReasoningEffort.ts
29543
29795
  var GROK_REASONING_OPTION_ID = "reasoningEffort";
29544
29796
  function grokReasoningEffortDescriptor(modelMeta) {
29545
- if (!isRecord10(modelMeta) || modelMeta["supportsReasoningEffort"] !== true) return void 0;
29797
+ if (!isRecord11(modelMeta) || modelMeta["supportsReasoningEffort"] !== true) return void 0;
29546
29798
  const table = modelMeta["reasoningEfforts"];
29547
29799
  if (!Array.isArray(table)) return void 0;
29548
29800
  const options = table.flatMap((entry) => {
29549
- if (!isRecord10(entry)) return [];
29801
+ if (!isRecord11(entry)) return [];
29550
29802
  const value = trimmed2(entry["value"]) ?? trimmed2(entry["id"]);
29551
29803
  if (value === void 0) return [];
29552
29804
  const description = trimmed2(entry["description"]);
@@ -29571,23 +29823,23 @@ function grokReasoningEffortDescriptor(modelMeta) {
29571
29823
  };
29572
29824
  }
29573
29825
  function grokReasoningEffortKnown(modelMeta) {
29574
- if (!isRecord10(modelMeta)) return "unknown";
29826
+ if (!isRecord11(modelMeta)) return "unknown";
29575
29827
  if (modelMeta["supportsReasoningEffort"] === false) return "none";
29576
29828
  if (modelMeta["supportsReasoningEffort"] !== true) return "unknown";
29577
29829
  const table = modelMeta["reasoningEfforts"];
29578
29830
  if (!Array.isArray(table)) return "unknown";
29579
29831
  const readable = table.every(
29580
- (entry) => isRecord10(entry) && (trimmed2(entry["value"]) ?? trimmed2(entry["id"])) !== void 0
29832
+ (entry) => isRecord11(entry) && (trimmed2(entry["value"]) ?? trimmed2(entry["id"])) !== void 0
29581
29833
  );
29582
29834
  if (!readable) return "unknown";
29583
29835
  return table.length === 0 ? "none" : "listed";
29584
29836
  }
29585
29837
  function grokModelDefaultEffort(input2) {
29586
- const models = isRecord10(input2.setup) ? input2.setup["models"] : void 0;
29587
- const available = isRecord10(models) ? models["availableModels"] : void 0;
29838
+ const models = isRecord11(input2.setup) ? input2.setup["models"] : void 0;
29839
+ const available = isRecord11(models) ? models["availableModels"] : void 0;
29588
29840
  if (!Array.isArray(available)) return void 0;
29589
- const model = available.find((entry) => isRecord10(entry) && entry["modelId"] === input2.modelId);
29590
- const current = isRecord10(model) ? grokReasoningEffortDescriptor(model["_meta"])?.currentValue : void 0;
29841
+ const model = available.find((entry) => isRecord11(entry) && entry["modelId"] === input2.modelId);
29842
+ const current = isRecord11(model) ? grokReasoningEffortDescriptor(model["_meta"])?.currentValue : void 0;
29591
29843
  return typeof current === "string" ? current : void 0;
29592
29844
  }
29593
29845
  function grokReasoningEffortArgs(effort) {
@@ -29746,7 +29998,7 @@ var NOTIFICATION_METHODS = /* @__PURE__ */ new Set([
29746
29998
  "x.ai/session/update"
29747
29999
  ]);
29748
30000
  var isGrokSessionNotification = (method) => NOTIFICATION_METHODS.has(method.startsWith("_") ? method.slice(1) : method);
29749
- var record3 = (value) => isRecord10(value) ? value : {};
30001
+ var record3 = (value) => isRecord11(value) ? value : {};
29750
30002
  var text3 = trimmed2;
29751
30003
  var count2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
29752
30004
  var replyText = (value) => {
@@ -30034,7 +30286,7 @@ function createGrokRetryNotices() {
30034
30286
  let phase;
30035
30287
  return {
30036
30288
  observe: (envelope, ctx) => {
30037
- if (!isRecord10(envelope) || !isRecord10(envelope["update"])) return [];
30289
+ if (!isRecord11(envelope) || !isRecord11(envelope["update"])) return [];
30038
30290
  if (ctx.sessionId === void 0 || envelope["sessionId"] !== ctx.sessionId) return [];
30039
30291
  const update = envelope["update"];
30040
30292
  if (update["sessionUpdate"] !== "retry_state") {
@@ -30045,7 +30297,7 @@ function createGrokRetryNotices() {
30045
30297
  phase = void 0;
30046
30298
  return [];
30047
30299
  }
30048
- const meta3 = isRecord10(envelope["_meta"]) ? envelope["_meta"] : {};
30300
+ const meta3 = isRecord11(envelope["_meta"]) ? envelope["_meta"] : {};
30049
30301
  if (meta3["isReplay"] === true) return [];
30050
30302
  const turnId = ctx.turnId;
30051
30303
  if (turnId === void 0) return [];
@@ -30084,7 +30336,7 @@ function createGrokRetryNotices() {
30084
30336
  }
30085
30337
 
30086
30338
  // src/grokSupport.ts
30087
- import { modelSelectionStringOption } from "@ycodium-ai/plugin-api/executor";
30339
+ import { modelSelectionStringOption as modelSelectionStringOption3 } from "@ycodium-ai/plugin-api/executor";
30088
30340
  var GROK_NATIVE_MODE_BY_RUNTIME_MODE = {
30089
30341
  "approval-required": "default",
30090
30342
  "auto-accept-edits": "auto",
@@ -30189,28 +30441,28 @@ function grokRuntimeModeCaveat(nativeModeId) {
30189
30441
  };
30190
30442
  }
30191
30443
  function resolveGrokAuthMethodId(initializeResult) {
30192
- const authMethods = isRecord10(initializeResult) ? initializeResult["authMethods"] : void 0;
30444
+ const authMethods = isRecord11(initializeResult) ? initializeResult["authMethods"] : void 0;
30193
30445
  if (!Array.isArray(authMethods)) return void 0;
30194
30446
  for (const method of authMethods) {
30195
- if (isRecord10(method) && method["id"] === "cached_token") return "cached_token";
30447
+ if (isRecord11(method) && method["id"] === "cached_token") return "cached_token";
30196
30448
  }
30197
30449
  return void 0;
30198
30450
  }
30199
30451
  var positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : void 0;
30200
30452
  function grokPromptUsage(promptResponse) {
30201
- if (!isRecord10(promptResponse)) return void 0;
30453
+ if (!isRecord11(promptResponse)) return void 0;
30202
30454
  const meta3 = promptResponse["_meta"];
30203
- if (!isRecord10(meta3)) return void 0;
30455
+ if (!isRecord11(meta3)) return void 0;
30204
30456
  const usedTokens = positive(meta3["totalTokens"]);
30205
30457
  if (usedTokens === void 0) return void 0;
30206
30458
  return { usedTokens, modelId: trimmed2(meta3["modelId"]) };
30207
30459
  }
30208
30460
  function grokModelState(initializeResult) {
30209
- if (!isRecord10(initializeResult)) return void 0;
30461
+ if (!isRecord11(initializeResult)) return void 0;
30210
30462
  const meta3 = initializeResult["_meta"];
30211
- if (!isRecord10(meta3)) return void 0;
30463
+ if (!isRecord11(meta3)) return void 0;
30212
30464
  const modelState = meta3["modelState"];
30213
- if (!isRecord10(modelState)) return void 0;
30465
+ if (!isRecord11(modelState)) return void 0;
30214
30466
  const availableModels = modelState["availableModels"];
30215
30467
  if (!Array.isArray(availableModels)) return void 0;
30216
30468
  return { currentModelId: trimmed2(modelState["currentModelId"]), availableModels };
@@ -30220,11 +30472,11 @@ function grokAdvertisedModels(initializeResult) {
30220
30472
  if (state === void 0) return [];
30221
30473
  const models = [];
30222
30474
  for (const entry of state.availableModels) {
30223
- if (!isRecord10(entry)) continue;
30475
+ if (!isRecord11(entry)) continue;
30224
30476
  const modelId = trimmed2(entry["modelId"]);
30225
30477
  if (modelId === void 0) continue;
30226
30478
  const modelMeta = entry["_meta"];
30227
- const contextWindow = isRecord10(modelMeta) ? positive(modelMeta["totalContextTokens"]) : void 0;
30479
+ const contextWindow = isRecord11(modelMeta) ? positive(modelMeta["totalContextTokens"]) : void 0;
30228
30480
  models.push({
30229
30481
  modelId,
30230
30482
  name: trimmed2(entry["name"]),
@@ -30241,7 +30493,7 @@ var XAI_ASK_USER_QUESTION_METHODS = [
30241
30493
  "x.ai/ask_user_question"
30242
30494
  ];
30243
30495
  var readOption = (value) => {
30244
- if (!isRecord10(value)) return void 0;
30496
+ if (!isRecord11(value)) return void 0;
30245
30497
  const label = typeof value["label"] === "string" ? value["label"] : void 0;
30246
30498
  if (label === void 0) return void 0;
30247
30499
  return {
@@ -30252,7 +30504,7 @@ var readOption = (value) => {
30252
30504
  };
30253
30505
  };
30254
30506
  var readQuestion = (value) => {
30255
- if (!isRecord10(value)) return void 0;
30507
+ if (!isRecord11(value)) return void 0;
30256
30508
  const question = typeof value["question"] === "string" ? value["question"] : void 0;
30257
30509
  if (question === void 0) return void 0;
30258
30510
  const optionsRaw = value["options"];
@@ -30268,9 +30520,9 @@ var readQuestion = (value) => {
30268
30520
  };
30269
30521
  };
30270
30522
  function parseXAiAskUserQuestionParams(params) {
30271
- const candidates = [params, ...isRecord10(params) ? [params["params"]] : []];
30523
+ const candidates = [params, ...isRecord11(params) ? [params["params"]] : []];
30272
30524
  for (const candidate of candidates) {
30273
- if (!isRecord10(candidate)) continue;
30525
+ if (!isRecord11(candidate)) continue;
30274
30526
  const questionsRaw = candidate["questions"];
30275
30527
  if (!Array.isArray(questionsRaw)) continue;
30276
30528
  const questions = questionsRaw.flatMap((entry) => {
@@ -30345,21 +30597,21 @@ var XAI_PROMPT_COMPLETE_METHOD = "_x.ai/session/prompt_complete";
30345
30597
  var GROK_RATE_LIMIT_MESSAGE = "Grok usage limit reached or rate limited. Try again later.";
30346
30598
  var grokAgentResultMessage = (value) => {
30347
30599
  if (typeof value === "string") return trimmed2(value);
30348
- return isRecord10(value) ? trimmed2(value["message"]) : void 0;
30600
+ return isRecord11(value) ? trimmed2(value["message"]) : void 0;
30349
30601
  };
30350
30602
  var grokPromptSettlement = {
30351
30603
  // 关联 id 双写 promptId 与 requestId(宿主 XAiAcpExtension 同款):
30352
30604
  // agent 认回哪个键是它的事,两个都给才不猜版本。
30353
30605
  requestFields: (promptKey) => ({ _meta: { promptId: promptKey, requestId: promptKey } }),
30354
30606
  responseKey: (response) => {
30355
- if (!isRecord10(response)) return void 0;
30607
+ if (!isRecord11(response)) return void 0;
30356
30608
  const meta3 = response["_meta"];
30357
- if (!isRecord10(meta3)) return void 0;
30609
+ if (!isRecord11(meta3)) return void 0;
30358
30610
  return trimmed2(meta3["promptId"]) ?? trimmed2(meta3["requestId"]);
30359
30611
  },
30360
30612
  fromNotification: (method, params) => {
30361
30613
  if (method !== XAI_PROMPT_COMPLETE_METHOD) return void 0;
30362
- if (!isRecord10(params)) return void 0;
30614
+ if (!isRecord11(params)) return void 0;
30363
30615
  const sessionId = params["sessionId"];
30364
30616
  if (typeof sessionId !== "string") return void 0;
30365
30617
  const stopReason = trimmed2(params["stopReason"]);
@@ -30378,12 +30630,12 @@ var grokPromptSettlement = {
30378
30630
  };
30379
30631
 
30380
30632
  // src/grokSkills.ts
30381
- import * as NodeOS3 from "node:os";
30382
- import * as NodePath6 from "node:path";
30633
+ import * as NodeOS4 from "node:os";
30634
+ import * as NodePath7 from "node:path";
30383
30635
  var INSPECT_TIMEOUT_MS = 15e3;
30384
30636
  var MAX_INSPECT_OUTPUT_BYTES = 4 * 1024 * 1024;
30385
30637
  var GROK_INSPECT_ARGS = ["inspect", "--json"];
30386
- var isRecord11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30638
+ var isRecord12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30387
30639
  var trimmedString = (value) => typeof value === "string" ? value.trim() : "";
30388
30640
  function parseGrokInspectSkills(stdout) {
30389
30641
  let parsed;
@@ -30392,13 +30644,13 @@ function parseGrokInspectSkills(stdout) {
30392
30644
  } catch {
30393
30645
  return [];
30394
30646
  }
30395
- const entries = isRecord11(parsed) ? parsed["skills"] : void 0;
30647
+ const entries = isRecord12(parsed) ? parsed["skills"] : void 0;
30396
30648
  if (!Array.isArray(entries)) return [];
30397
30649
  const byName = /* @__PURE__ */ new Map();
30398
30650
  for (const entry of entries) {
30399
- if (!isRecord11(entry)) continue;
30651
+ if (!isRecord12(entry)) continue;
30400
30652
  const name = trimmedString(entry["name"]);
30401
- const source = isRecord11(entry["source"]) ? entry["source"] : void 0;
30653
+ const source = isRecord12(entry["source"]) ? entry["source"] : void 0;
30402
30654
  const path = trimmedString(source?.["path"]);
30403
30655
  if (name.length === 0 || path.length === 0) continue;
30404
30656
  const scope = trimmedString(source?.["type"]);
@@ -30432,14 +30684,14 @@ var runGrokInspect = async (input2) => {
30432
30684
  throw new Error(`grok inspect exited with ${String(run.exitCode)}`);
30433
30685
  }
30434
30686
  const parsed = JSON.parse(run.stdout);
30435
- if (!isRecord11(parsed) || !Array.isArray(parsed["skills"])) {
30687
+ if (!isRecord12(parsed) || !Array.isArray(parsed["skills"])) {
30436
30688
  throw new Error("grok inspect output has no skills list");
30437
30689
  }
30438
30690
  return parseGrokInspectSkills(run.stdout);
30439
30691
  };
30440
30692
  async function probeGrokSkills(input2) {
30441
30693
  try {
30442
- return await runGrokInspect({ ...input2, cwd: NodeOS3.homedir() });
30694
+ return await runGrokInspect({ ...input2, cwd: NodeOS4.homedir() });
30443
30695
  } catch {
30444
30696
  return [];
30445
30697
  }
@@ -30448,14 +30700,14 @@ async function inspectGrokWorkspace(input2) {
30448
30700
  const skills = await runGrokInspect(input2);
30449
30701
  const watched = /* @__PURE__ */ new Set([
30450
30702
  // 项目技能目录的位置没有实测,这两处只是触发重查的提示,不影响答案本身。
30451
- NodePath6.join(input2.cwd, ".grok", "skills"),
30452
- NodePath6.join(input2.cwd, ".agents", "skills")
30703
+ NodePath7.join(input2.cwd, ".grok", "skills"),
30704
+ NodePath7.join(input2.cwd, ".agents", "skills")
30453
30705
  ]);
30454
30706
  for (const skill of skills) {
30455
30707
  watched.add(skill.path);
30456
- const skillDirectory = NodePath6.dirname(skill.path);
30708
+ const skillDirectory = NodePath7.dirname(skill.path);
30457
30709
  watched.add(skillDirectory);
30458
- watched.add(NodePath6.dirname(skillDirectory));
30710
+ watched.add(NodePath7.dirname(skillDirectory));
30459
30711
  }
30460
30712
  return { skills, watchPaths: [...watched] };
30461
30713
  }
@@ -30513,7 +30765,7 @@ import {
30513
30765
  OperationCleanupError as OperationCleanupError2
30514
30766
  } from "@ycodium-ai/plugin-api/process-operation";
30515
30767
  import * as NodeFS4 from "node:fs";
30516
- import * as NodePath7 from "node:path";
30768
+ import * as NodePath8 from "node:path";
30517
30769
  import {
30518
30770
  ExecutorSpawnAbortedError as ExecutorSpawnAbortedError2,
30519
30771
  ExecutorSpawnRefusedError as ExecutorSpawnRefusedError2,
@@ -30522,16 +30774,58 @@ import {
30522
30774
 
30523
30775
  // src/probeModels.ts
30524
30776
  import {
30525
- runProcessOperation,
30526
- OperationCleanupError
30527
- } from "@ycodium-ai/plugin-api/process-operation";
30777
+ raceAbort as raceAbort3
30778
+ } from "@ycodium-ai/plugin-api/executor";
30779
+ import { nodeStreamsFromHandle as nodeStreamsFromHandle2 } from "@ycodium-ai/plugin-api/process-stdin";
30780
+
30781
+ // ../../packages/ycodium-instance-config/src/probeProcess.ts
30528
30782
  import {
30529
30783
  describeExecutorSpawnFailure,
30530
30784
  ExecutorSpawnAbortedError,
30531
- ExecutorSpawnRefusedError,
30532
- raceAbort as raceAbort2
30785
+ ExecutorSpawnRefusedError
30533
30786
  } from "@ycodium-ai/plugin-api/executor";
30534
- import { nodeStreamsFromHandle } from "@ycodium-ai/plugin-api/process-stdin";
30787
+ import {
30788
+ OperationCleanupError,
30789
+ runProcessOperation
30790
+ } from "@ycodium-ai/plugin-api/process-operation";
30791
+ async function spawnProbeProcess(host, launch) {
30792
+ try {
30793
+ const handle = await host.process.spawn({
30794
+ program: launch.program,
30795
+ args: launch.args,
30796
+ cwd: launch.cwd,
30797
+ owner: { bindingId: host.bindingId },
30798
+ ...Object.keys(launch.env).length > 0 ? { env: launch.env } : {},
30799
+ ...launch.signal === void 0 ? {} : { signal: launch.signal }
30800
+ });
30801
+ return { kind: "spawned", handle };
30802
+ } catch (error62) {
30803
+ if (error62 instanceof ExecutorSpawnRefusedError || error62 instanceof ExecutorSpawnAbortedError) {
30804
+ throw error62;
30805
+ }
30806
+ return { kind: "not-started", ...describeExecutorSpawnFailure(error62) };
30807
+ }
30808
+ }
30809
+ async function readCliVersionCommand(host, input2) {
30810
+ try {
30811
+ const run = await runProcessOperation(host, {
30812
+ program: input2.program,
30813
+ args: ["--version"],
30814
+ owner: { bindingId: host.bindingId },
30815
+ ...Object.keys(input2.env).length > 0 ? { env: input2.env } : {},
30816
+ signal: input2.signal,
30817
+ timeoutMs: input2.timeoutMs,
30818
+ maxOutputBytes: 64 * 1024
30819
+ });
30820
+ if (run.exitCode !== 0) return null;
30821
+ return input2.parse(run.stdout) ?? input2.parse(run.stderr);
30822
+ } catch (error62) {
30823
+ if (error62 instanceof OperationCleanupError || input2.signal?.aborted) throw error62;
30824
+ return null;
30825
+ }
30826
+ }
30827
+
30828
+ // src/probeModels.ts
30535
30829
  var PROBE_REQUEST_TIMEOUT_MS = 2e4;
30536
30830
  function grokProbeModels(initializeResult) {
30537
30831
  if (grokModelState(initializeResult) === void 0) return void 0;
@@ -30547,29 +30841,21 @@ function grokProbeModels(initializeResult) {
30547
30841
  }
30548
30842
  }));
30549
30843
  }
30550
- var failureDetail = (error62) => (error62 instanceof Error ? error62.message : String(error62)).trim() || void 0;
30551
30844
  async function probeGrokModels(input2) {
30552
30845
  const { recipe, host, env } = input2;
30553
- let handle;
30554
- try {
30555
- handle = await host.process.spawn({
30556
- program: recipe.binaryPath,
30557
- args: tokenizeLaunchArgs(recipe.launchArgs),
30558
- cwd: process.cwd(),
30559
- owner: { bindingId: host.bindingId },
30560
- ...Object.keys(env).length > 0 ? { env } : {},
30561
- ...input2.signal === void 0 ? {} : { signal: input2.signal }
30562
- });
30563
- } catch (error62) {
30564
- if (error62 instanceof ExecutorSpawnRefusedError || error62 instanceof ExecutorSpawnAbortedError) {
30565
- throw error62;
30566
- }
30567
- return { kind: "not-started", ...describeExecutorSpawnFailure(error62) };
30568
- }
30846
+ const spawned = await spawnProbeProcess(host, {
30847
+ program: recipe.binaryPath,
30848
+ args: tokenizeShellWords(recipe.launchArgs),
30849
+ cwd: process.cwd(),
30850
+ env,
30851
+ ...input2.signal === void 0 ? {} : { signal: input2.signal }
30852
+ });
30853
+ if (spawned.kind === "not-started") return spawned;
30854
+ const { handle } = spawned;
30569
30855
  let handshake;
30570
30856
  try {
30571
- const { readable, writable } = nodeStreamsFromHandle(handle);
30572
- handshake = await raceAbort2(
30857
+ const { readable, writable } = nodeStreamsFromHandle2(handle);
30858
+ handshake = await raceAbort3(
30573
30859
  openAcpProbeHandshake({
30574
30860
  readable,
30575
30861
  writable,
@@ -30580,7 +30866,7 @@ async function probeGrokModels(input2) {
30580
30866
  );
30581
30867
  return { kind: "answered", models: grokProbeModels(handshake.initializeResult) };
30582
30868
  } catch (error62) {
30583
- return { kind: "failed", detail: failureDetail(error62) };
30869
+ return { kind: "failed", detail: acpProbeFailureDetail(error62) };
30584
30870
  } finally {
30585
30871
  await handshake?.close().catch(() => void 0);
30586
30872
  await handle.kill("SIGTERM").catch(() => void 0);
@@ -30588,22 +30874,13 @@ async function probeGrokModels(input2) {
30588
30874
  }
30589
30875
  async function probeGrokVersion(input2) {
30590
30876
  const { recipe, host, env, signal } = input2;
30591
- try {
30592
- const run = await runProcessOperation(host, {
30593
- program: recipe.binaryPath,
30594
- args: ["--version"],
30595
- owner: { bindingId: host.bindingId },
30596
- ...Object.keys(env).length > 0 ? { env } : {},
30597
- signal,
30598
- timeoutMs: PROBE_REQUEST_TIMEOUT_MS,
30599
- maxOutputBytes: 64 * 1024
30600
- });
30601
- if (run.exitCode !== 0) return null;
30602
- return parseCliVersion(run.stdout) ?? parseCliVersion(run.stderr);
30603
- } catch (error62) {
30604
- if (error62 instanceof OperationCleanupError || signal?.aborted) throw error62;
30605
- return null;
30606
- }
30877
+ return readCliVersionCommand(host, {
30878
+ program: recipe.binaryPath,
30879
+ env,
30880
+ signal,
30881
+ timeoutMs: PROBE_REQUEST_TIMEOUT_MS,
30882
+ parse: parseCliVersion
30883
+ });
30607
30884
  }
30608
30885
 
30609
30886
  // src/modelCacheRefresh.ts
@@ -30611,7 +30888,7 @@ var GROK_MODEL_CACHE_FILE = "models_cache.json";
30611
30888
  var GROK_MODEL_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
30612
30889
  var GROK_MODELS_COMMAND_TIMEOUT_MS = 6e4;
30613
30890
  function grokModelCachePath(accountHome) {
30614
- return NodePath7.join(accountHome, GROK_MODEL_CACHE_FILE);
30891
+ return NodePath8.join(accountHome, GROK_MODEL_CACHE_FILE);
30615
30892
  }
30616
30893
  function readGrokModelCacheMtimeMs(accountHome) {
30617
30894
  try {
@@ -30744,7 +31021,7 @@ function createGrokModelCatalog(input2) {
30744
31021
 
30745
31022
  // src/grokFollowUpSteer.ts
30746
31023
  import * as NodeFS5 from "node:fs";
30747
- import * as NodePath8 from "node:path";
31024
+ import * as NodePath9 from "node:path";
30748
31025
  var SETTING = 'follow_up_behavior = "steer"';
30749
31026
  function grokFollowUpSteerIsOn(text4) {
30750
31027
  const lines = text4.split(/\r?\n/).map((line) => line.trim());
@@ -30758,7 +31035,7 @@ function grokFollowUpSteerIsOn(text4) {
30758
31035
  return false;
30759
31036
  }
30760
31037
  function ensureGrokFollowUpSteer(homePath) {
30761
- const path = NodePath8.join(homePath, "config.toml");
31038
+ const path = NodePath9.join(homePath, "config.toml");
30762
31039
  try {
30763
31040
  return grokFollowUpSteerIsOn(NodeFS5.readFileSync(path, "utf8")) ? "on" : "off";
30764
31041
  } catch (error62) {
@@ -30809,40 +31086,14 @@ var grokPermissionStatement = ({
30809
31086
 
30810
31087
  // src/grokInstance.ts
30811
31088
  var RESUME_SCHEMA_VERSION = 1;
30812
- var yieldTick = () => new Promise((resolve2) => {
30813
- setImmediate(resolve2);
30814
- });
30815
- function nowIso() {
31089
+ function nowIso3() {
30816
31090
  return (/* @__PURE__ */ new Date()).toISOString();
30817
31091
  }
30818
- async function stopBooked(booked, processExit) {
30819
- await cleanupAcpSession({
30820
- executor: booked.executor,
30821
- stopProcess: () => booked.handle.kill("SIGTERM"),
30822
- forwarding: booked.forwarding,
30823
- processExit
30824
- });
30825
- }
30826
- function modelIdFromSelection(selection) {
30827
- if (typeof selection !== "object" || selection === null || Array.isArray(selection)) {
30828
- return void 0;
30829
- }
30830
- const model = selection["model"];
30831
- return typeof model === "string" ? model.trim() || void 0 : void 0;
30832
- }
30833
31092
  var createGrokInstance = (config2, host) => {
30834
31093
  const recipe = parseGrokInstanceConfig(config2);
30835
- const threads = /* @__PURE__ */ new Map();
30836
31094
  let disposed = false;
30837
- const { requireThread, registerSession, stopSession, stopAll } = createAcpSessionRegistry(
30838
- threads,
30839
- stopBooked,
30840
- host.log
30841
- );
30842
- const disposeOnce = createRetryableClose(async () => {
30843
- await signIn.close();
30844
- await stopAll();
30845
- });
31095
+ const table = createAcpThreadTable(host.log, () => signIn.close());
31096
+ const { threads, requireThread, registerSession, stopSession, disposeOnce } = table;
30846
31097
  const probeAuth = () => {
30847
31098
  if ((recipe.environment["XAI_API_KEY"] ?? "").trim().length > 0) {
30848
31099
  return { status: "authenticated", type: "api-key", label: "XAI_API_KEY" };
@@ -30889,9 +31140,9 @@ var createGrokInstance = (config2, host) => {
30889
31140
  }
30890
31141
  prepareGrokFollowUpSteer(resolveAccountHomePath(recipe, recipe.homePath), host.log);
30891
31142
  const env = spawnEnv();
30892
- const version2 = await raceAbort3(modelCatalog.readCliVersion(signal), signal);
31143
+ const version2 = await raceAbort4(modelCatalog.readCliVersion(signal), signal);
30893
31144
  if (signal?.aborted) throw new Error("aborted");
30894
- await raceAbort3(
31145
+ await raceAbort4(
30895
31146
  modelCatalog.refreshModelCatalog({
30896
31147
  force: false,
30897
31148
  cliVersion: version2,
@@ -30900,7 +31151,7 @@ var createGrokInstance = (config2, host) => {
30900
31151
  signal
30901
31152
  );
30902
31153
  if (signal?.aborted) throw new Error("aborted");
30903
- const [outcome, skills] = await raceAbort3(
31154
+ const [outcome, skills] = await raceAbort4(
30904
31155
  Promise.all([
30905
31156
  probeGrokModels({
30906
31157
  recipe,
@@ -30940,6 +31191,13 @@ var createGrokInstance = (config2, host) => {
30940
31191
  };
30941
31192
  };
30942
31193
  const signIn = makeGrokSignIn({ host, recipe, probe, isDisposed: () => disposed });
31194
+ const threadOps = createAcpThreadOperations({
31195
+ threads,
31196
+ requireThread,
31197
+ isDisposed: () => disposed,
31198
+ turnSelection: (selection) => readTurnSelection(selection, GROK_REASONING_OPTION_ID),
31199
+ log: host.log
31200
+ });
30943
31201
  const instance = {
30944
31202
  probe,
30945
31203
  readCliVersion: (signal) => modelCatalog.readCliVersion(signal),
@@ -30970,20 +31228,15 @@ var createGrokInstance = (config2, host) => {
30970
31228
  }
30971
31229
  const cwd = input2.cwd ?? host.workspacePath(input2.threadId);
30972
31230
  if (cwd.trim() === "") throw new Error("workspace path missing");
30973
- const existing = threads.get(input2.threadId);
30974
- if (existing !== void 0) {
30975
- await stopSession(input2.threadId, existing);
30976
- if (disposed) throw new Error("instance disposed");
30977
- throwIfStartAborted(signal);
30978
- }
31231
+ await stopExistingAcpThread(table, input2.threadId, () => disposed, signal);
30979
31232
  prepareGrokFollowUpSteer(
30980
31233
  resolveAccountHomePath(recipe, recipe.homePath),
30981
31234
  host.log,
30982
31235
  input2.threadId
30983
31236
  );
30984
31237
  const env = spawnEnv();
30985
- const effort = modelSelectionStringOption(input2.modelSelection, GROK_REASONING_OPTION_ID);
30986
- const baseArgs = tokenizeLaunchArgs(recipe.launchArgs);
31238
+ const effort = modelSelectionStringOption3(input2.modelSelection, GROK_REASONING_OPTION_ID);
31239
+ const baseArgs = tokenizeShellWords(recipe.launchArgs);
30987
31240
  const insertAt = baseArgs.length <= 1 ? baseArgs.length : baseArgs.length - 1;
30988
31241
  const permissionMode = grokPermissionModeFor(input2.runtimeMode, input2.nativeModeId);
30989
31242
  const args = [
@@ -31000,8 +31253,8 @@ var createGrokInstance = (config2, host) => {
31000
31253
  owner: { bindingId: host.bindingId },
31001
31254
  ...Object.keys(env).length > 0 ? { env } : {}
31002
31255
  });
31003
- const { readable, writable, stderrTail } = nodeStreamsFromHandle2(handle);
31004
- const resume = input2.discardResumeCursor === true ? void 0 : parseAcpResumeCursor(input2.resumeCursor, RESUME_SCHEMA_VERSION);
31256
+ const { readable, writable, stderrTail } = nodeStreamsFromHandle3(handle);
31257
+ const resume = acpResumeFrom(input2, RESUME_SCHEMA_VERSION);
31005
31258
  const requestedModelId = modelIdFromSelection(input2.modelSelection);
31006
31259
  let initializeResult;
31007
31260
  const backgroundTasks = /* @__PURE__ */ new Map();
@@ -31085,126 +31338,60 @@ var createGrokInstance = (config2, host) => {
31085
31338
  refreshCatalogForSend: () => modelCatalog.refreshForSend(),
31086
31339
  // 内置编排那一条排第一,后面跟用户在插件中心配的;缺了这一栏,
31087
31340
  // `mcp__ycodium__*` 整套工具(浏览器等)在这只手的会话里都不存在。
31088
- // http / sse 由执行器按握手里的 `mcpCapabilities` 再筛。
31089
- mcpServers: toAcpMcpServers(input2.mcpServers),
31090
- ...resume === void 0 ? {} : { resumeSessionId: resume.sessionId }
31341
+ // http / sse 由执行器按握手里的 `mcpCapabilities` 再筛。空数组也传。
31342
+ ...acpLaunchMcpFields({
31343
+ mcpServers: input2.mcpServers,
31344
+ resumeSessionId: resume?.sessionId
31345
+ })
31091
31346
  });
31092
- const forwarding = (async () => {
31093
- for await (const event of executor.events) {
31094
- input2.events.emit(await turnUsage.attach(event));
31095
- }
31096
- })();
31097
- try {
31098
- throwIfStartAborted(signal);
31099
- const started = await raceStartAbort(executor.start(), signal);
31100
- initializeResult = started.initializeResult;
31101
- await yieldTick();
31102
- throwIfStartAborted(signal);
31103
- const createdAt = nowIso();
31104
- const resumeCursor = {
31105
- schemaVersion: RESUME_SCHEMA_VERSION,
31106
- sessionId: started.sessionId
31107
- };
31108
- const session = {
31347
+ return openAcpThreadSession({
31348
+ registerSession,
31349
+ threadId: input2.threadId,
31350
+ executor,
31351
+ handle,
31352
+ signal,
31353
+ log: host.log,
31354
+ emit: async (event) => input2.events.emit(await turnUsage.attach(event)),
31355
+ afterStart: (started) => {
31356
+ initializeResult = started.initializeResult;
31357
+ },
31358
+ session: {
31109
31359
  provider: GROK_DRIVER_KIND,
31110
31360
  providerInstanceId: host.instanceId,
31111
- status: "idle",
31112
31361
  runtimeMode: input2.runtimeMode,
31113
31362
  nativeModeId: permissionMode,
31114
31363
  cwd,
31115
- threadId: input2.threadId,
31116
- createdAt,
31117
- updatedAt: createdAt,
31118
- resumeCursor,
31119
- ...started.modelId === void 0 ? {} : {
31120
- model: started.modelId,
31121
- // agent 在握手里报的才是读回的;切型号走 session/set_model 时回包不带型号,那只是请求值。
31122
- modelSource: started.modelReported ? "reported" : "echo"
31123
- },
31124
- ...input2.bindingGeneration === void 0 ? {} : { bindingGeneration: input2.bindingGeneration }
31125
- };
31126
- registerSession(input2.threadId, {
31127
- session,
31128
- turns: [],
31129
- executor,
31130
- handle,
31131
- forwarding,
31132
- spawned
31133
- });
31134
- host.log.info("session started", {
31135
- threadId: input2.threadId,
31136
- sessionId: started.sessionId
31137
- });
31138
- const caveat = grokRuntimeModeCaveat(permissionMode);
31139
- if (caveat !== void 0) {
31140
- input2.events.emit({
31141
- type: "runtime.warning",
31142
- eventId: NodeCrypto3.randomUUID(),
31143
- provider: GROK_DRIVER_KIND,
31144
- providerInstanceId: host.instanceId,
31145
- threadId: input2.threadId,
31146
- createdAt: nowIso(),
31147
- payload: {
31148
- message: caveat.message,
31149
- detail: {
31150
- code: caveat.code,
31151
- nativeModeId: caveat.nativeModeId,
31152
- asked: caveat.asked,
31153
- unasked: caveat.unasked,
31154
- externalRulesPaths: caveat.externalRulesPaths
31364
+ bindingGeneration: input2.bindingGeneration,
31365
+ resumeSchemaVersion: RESUME_SCHEMA_VERSION
31366
+ },
31367
+ booked: (base) => ({ ...base, spawned }),
31368
+ afterRegister: () => {
31369
+ const caveat = grokRuntimeModeCaveat(permissionMode);
31370
+ if (caveat !== void 0) {
31371
+ input2.events.emit({
31372
+ type: "runtime.warning",
31373
+ eventId: NodeCrypto3.randomUUID(),
31374
+ provider: GROK_DRIVER_KIND,
31375
+ providerInstanceId: host.instanceId,
31376
+ threadId: input2.threadId,
31377
+ createdAt: nowIso3(),
31378
+ payload: {
31379
+ message: caveat.message,
31380
+ detail: {
31381
+ code: caveat.code,
31382
+ nativeModeId: caveat.nativeModeId,
31383
+ asked: caveat.asked,
31384
+ unasked: caveat.unasked,
31385
+ externalRulesPaths: caveat.externalRulesPaths
31386
+ }
31155
31387
  }
31156
- }
31157
- });
31388
+ });
31389
+ }
31158
31390
  }
31159
- return session;
31160
- } catch (error62) {
31161
- await cleanupAcpStartup({
31162
- executor,
31163
- stopProcess: () => handle.kill("SIGTERM"),
31164
- forwarding,
31165
- log: host.log,
31166
- threadId: input2.threadId
31167
- });
31168
- throw error62;
31169
- }
31170
- },
31171
- sendTurn: async (input2, signal) => {
31172
- if (disposed) throw new Error("instance disposed");
31173
- const booked = requireThread(input2.threadId);
31174
- if (signal?.aborted) throw new Error("aborted");
31175
- const onAbort = () => {
31176
- void booked.executor.cancel(input2.expectedTurnId).catch(() => void 0);
31177
- };
31178
- signal?.addEventListener("abort", onAbort);
31179
- try {
31180
- const requestedModelId = modelIdFromSelection(input2.modelSelection);
31181
- const requestedEffort = modelSelectionStringOption(
31182
- input2.modelSelection,
31183
- GROK_REASONING_OPTION_ID
31184
- );
31185
- const turn = await dispatchAcpPrompt(booked.executor, {
31186
- text: input2.input ?? "",
31187
- expectedActiveTurnId: input2.expectedTurnId,
31188
- ...requestedModelId === void 0 ? {} : { requestedModelId },
31189
- ...requestedEffort === void 0 ? {} : { requestedEffort }
31190
- });
31191
- booked.turns.push({ id: turn.turnId, items: [] });
31192
- return {
31193
- threadId: input2.threadId,
31194
- turnId: turn.turnId,
31195
- ...booked.session.resumeCursor === void 0 ? {} : { resumeCursor: booked.session.resumeCursor }
31196
- };
31197
- } finally {
31198
- signal?.removeEventListener("abort", onAbort);
31199
- }
31200
- },
31201
- interruptTurn: async (threadId, turnId) => {
31202
- const booked = threads.get(threadId);
31203
- if (booked === void 0 || booked.closing) return;
31204
- host.log.info("interrupt turn", { threadId, turnId });
31205
- await booked.executor.cancel(turnId);
31206
- await yieldTick();
31391
+ });
31207
31392
  },
31393
+ sendTurn: threadOps.sendTurn,
31394
+ interruptTurn: threadOps.interruptTurn,
31208
31395
  openCommandProcesses: async (threadId) => {
31209
31396
  const booked = threads.get(threadId);
31210
31397
  if (booked === void 0) return void 0;
@@ -31214,18 +31401,8 @@ var createGrokInstance = (config2, host) => {
31214
31401
  openToolCalls: booked.executor.openToolCalls()
31215
31402
  });
31216
31403
  },
31217
- respondToRequest: async (threadId, requestId, decision, reason) => {
31218
- const booked = requireThread(threadId);
31219
- await booked.executor.respondToRequest(
31220
- requestId,
31221
- decision === "allow" ? "accept" : "decline",
31222
- reason
31223
- );
31224
- },
31225
- respondToUserInput: async (threadId, requestId, answers) => {
31226
- const booked = requireThread(threadId);
31227
- await booked.executor.respondToUserInput(requestId, answers);
31228
- },
31404
+ respondToRequest: threadOps.respondToRequest,
31405
+ respondToUserInput: threadOps.respondToUserInput,
31229
31406
  // 原生压缩:让 CLI 执行它自己宣告的 `/compact`。这不是用户消息——执行器不开轮次、
31230
31407
  // 不把命令吐的文本放进时间线,进度与结果只走压缩生命周期事件。
31231
31408
  compactContext: async (threadId) => {
@@ -31236,10 +31413,7 @@ var createGrokInstance = (config2, host) => {
31236
31413
  await booked.executor.compact({ commandName: "compact" });
31237
31414
  },
31238
31415
  stopSession: (threadId) => stopSession(threadId),
31239
- readThread: async (threadId) => {
31240
- const booked = requireThread(threadId);
31241
- return { threadId, turns: booked.turns };
31242
- },
31416
+ readThread: threadOps.readThread,
31243
31417
  // 额度读实例自己的账号目录与连接(与它的 CLI 同源);token 走编排账本,见 grokTurnUsage.ts。
31244
31418
  usage: createGrokUsage({
31245
31419
  homePath: resolveAccountHomePath(recipe, recipe.homePath),