@ycodium-ai/agent-grok 0.2.5557 → 0.2.5751

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 +476 -712
  2. package/package.json +4 -6
package/dist/index.js CHANGED
@@ -8,49 +8,13 @@ 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 = 175;
11
+ var PLUGIN_API_VERSION = 180;
12
12
 
13
13
  // src/index.ts
14
- import {
15
- EXECUTOR_EFFECTIVE_PAYLOAD_SCHEMA,
16
- executorHomeEffectiveValue,
17
- readExecutorEffectiveRequest
18
- } from "@ycodium-ai/plugin-api/executor";
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
- }
14
+ import { registerEffectiveHomeCommand } from "@ycodium-ai/plugin-api/instance-config";
52
15
 
53
16
  // src/card.ts
17
+ import { programAndHomeConfigSchema } from "@ycodium-ai/plugin-api/instance-config";
54
18
  var GROK_DRIVER_KIND = "grok";
55
19
  var GROK_CLIENT_INFO = { name: "ycodium-agent-grok", version: "0.1.0" };
56
20
  var GROK_CARD = {
@@ -186,77 +150,32 @@ var GROK_CARD = {
186
150
 
187
151
  // src/grokHome.ts
188
152
  import * as NodeCrypto from "node:crypto";
189
- import * as NodeOS2 from "node:os";
190
- import * as NodePath3 from "node:path";
191
- import { mergeLaunchEnv as mergeLaunchEnv2 } from "@ycodium-ai/plugin-api/executor";
192
-
193
- // ../../packages/ycodium-instance-config/src/homePath.ts
194
153
  import * as NodeOS from "node:os";
195
- import * as NodePath from "node:path";
196
- import { mergeLaunchEnv } from "@ycodium-ai/plugin-api/executor";
197
- function expandHomePath(value) {
198
- if (value === "~") return NodeOS.homedir();
199
- if (value.startsWith("~/") || value.startsWith("~\\")) {
200
- return NodePath.join(NodeOS.homedir(), value.slice(2));
201
- }
202
- return value;
203
- }
204
-
205
- // src/grokAccount.ts
206
154
  import * as NodePath2 from "node:path";
207
-
208
- // ../../packages/ycodium-credential-account/src/credentialAccount.ts
209
- import * as NodeFS from "node:fs";
210
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
211
- var readTrimmedString = (record4, key) => {
212
- const value = record4[key];
213
- if (typeof value !== "string") return void 0;
214
- const trimmed3 = value.trim();
215
- return trimmed3.length > 0 ? trimmed3 : void 0;
216
- };
217
- var parseJsonRecord = (raw) => {
218
- let parsed;
219
- try {
220
- parsed = JSON.parse(raw);
221
- } catch {
222
- return void 0;
223
- }
224
- return isRecord(parsed) ? parsed : void 0;
225
- };
226
- var directoryExists = (homePath) => {
227
- try {
228
- return NodeFS.statSync(homePath).isDirectory();
229
- } catch {
230
- return false;
231
- }
232
- };
233
- var readCredentialFile = (path) => {
234
- try {
235
- return NodeFS.readFileSync(path, "utf8");
236
- } catch {
237
- return void 0;
238
- }
239
- };
240
- var accountWithoutIdentity = (state, exists) => ({
241
- state,
242
- directoryExists: exists,
243
- email: void 0,
244
- name: void 0,
245
- expiresAt: void 0
246
- });
155
+ import { mergeLaunchEnv } from "@ycodium-ai/plugin-api/executor";
156
+ import { expandHomePath } from "@ycodium-ai/plugin-api/instance-config";
247
157
 
248
158
  // src/grokAccount.ts
159
+ import * as NodePath from "node:path";
160
+ import {
161
+ accountWithoutIdentity,
162
+ directoryExists,
163
+ isRecord,
164
+ parseJsonRecord,
165
+ readCredentialFile,
166
+ readTrimmedString as readString
167
+ } from "@ycodium-ai/plugin-api/credential-account";
249
168
  var AUTH_FILE_NAME = "auth.json";
250
169
  var joinName = (record4) => {
251
- const first = readTrimmedString(record4, "first_name");
252
- const last = readTrimmedString(record4, "last_name");
170
+ const first = readString(record4, "first_name");
171
+ const last = readString(record4, "last_name");
253
172
  const joined = [first, last].filter((part) => part !== void 0).join(" ");
254
173
  return joined.length > 0 ? joined : void 0;
255
174
  };
256
175
  var findIdentityEntry = (parsed) => {
257
176
  for (const value of Object.values(parsed)) {
258
177
  if (!isRecord(value)) continue;
259
- if (readTrimmedString(value, "email") !== void 0 || readTrimmedString(value, "user_id") !== void 0) {
178
+ if (readString(value, "email") !== void 0 || readString(value, "user_id") !== void 0) {
260
179
  return value;
261
180
  }
262
181
  }
@@ -269,16 +188,16 @@ var isExpired = (expiresAt, nowMs) => {
269
188
  };
270
189
  var readGrokAccount = (homePath) => {
271
190
  const exists = directoryExists(homePath);
272
- const raw = readCredentialFile(NodePath2.join(homePath, AUTH_FILE_NAME));
191
+ const raw = readCredentialFile(NodePath.join(homePath, AUTH_FILE_NAME));
273
192
  if (raw === void 0) return accountWithoutIdentity("signed-out", exists);
274
193
  const parsed = parseJsonRecord(raw);
275
194
  const identity = parsed === void 0 ? void 0 : findIdentityEntry(parsed);
276
195
  if (identity === void 0) return accountWithoutIdentity("unreadable", exists);
277
- const expiresAt = readTrimmedString(identity, "expires_at");
196
+ const expiresAt = readString(identity, "expires_at");
278
197
  return {
279
198
  state: isExpired(expiresAt, Date.now()) ? "expired" : "signed-in",
280
199
  directoryExists: exists,
281
- email: readTrimmedString(identity, "email"),
200
+ email: readString(identity, "email"),
282
201
  name: joinName(identity),
283
202
  expiresAt
284
203
  };
@@ -287,8 +206,8 @@ var readGrokAccount = (homePath) => {
287
206
  // src/grokHome.ts
288
207
  function resolveGrokHomePath(value) {
289
208
  const trimmed3 = value.trim();
290
- if (trimmed3.length === 0) return NodePath3.join(NodeOS2.homedir(), ".grok");
291
- return NodePath3.resolve(expandHomePath(trimmed3));
209
+ if (trimmed3.length === 0) return NodePath2.join(NodeOS.homedir(), ".grok");
210
+ return NodePath2.resolve(expandHomePath(trimmed3));
292
211
  }
293
212
  function probeGrokAccount(accountPath) {
294
213
  const resolved = resolveGrokHomePath(accountPath);
@@ -307,13 +226,13 @@ function grokContinuationKey(recipe) {
307
226
  function resolveAccountHomePath(recipe, configuredHome) {
308
227
  const fromEnvironment = recipe.environment["GROK_HOME"]?.trim();
309
228
  if (fromEnvironment !== void 0 && fromEnvironment.length > 0) {
310
- return NodePath3.resolve(expandHomePath(fromEnvironment));
229
+ return NodePath2.resolve(expandHomePath(fromEnvironment));
311
230
  }
312
231
  return resolveGrokHomePath(configuredHome);
313
232
  }
314
233
  function absentPath() {
315
- return NodePath3.join(
316
- NodeOS2.tmpdir(),
234
+ return NodePath2.join(
235
+ NodeOS.tmpdir(),
317
236
  `ycodium-grok-no-auth-${NodeCrypto.randomUUID()}`,
318
237
  "auth.json"
319
238
  );
@@ -331,7 +250,7 @@ function ownEndpointAuthGuard(recipe) {
331
250
  function buildSignInEnv(recipe) {
332
251
  const configuredHome = recipe.homePath;
333
252
  const homeInjection = configuredHome.trim().length > 0 ? { [GROK_CARD.homeEnvVar]: resolveGrokHomePath(configuredHome) } : {};
334
- return mergeLaunchEnv2({
253
+ return mergeLaunchEnv({
335
254
  accountHome: homeInjection,
336
255
  instanceTable: recipe.environment,
337
256
  handOverrides: { GROK_OAUTH2_REFERRER: "ycodium" }
@@ -339,7 +258,7 @@ function buildSignInEnv(recipe) {
339
258
  }
340
259
  function buildSpawnEnv(recipe, resolvedHomePath, homeConfigured) {
341
260
  const homeInjection = homeConfigured ? { [GROK_CARD.homeEnvVar]: resolvedHomePath } : {};
342
- return mergeLaunchEnv2({
261
+ return mergeLaunchEnv({
343
262
  accountHome: { ...homeInjection, ...ownEndpointAuthGuard(recipe) },
344
263
  instanceTable: recipe.environment,
345
264
  handOverrides: { GROK_OAUTH2_REFERRER: "ycodium" }
@@ -347,11 +266,12 @@ function buildSpawnEnv(recipe, resolvedHomePath, homeConfigured) {
347
266
  }
348
267
 
349
268
  // src/grokInstance.ts
269
+ import { sessionReadFromImport } from "@ycodium-ai/plugin-api/session-history";
350
270
  import * as NodeCrypto3 from "node:crypto";
351
271
  import {
352
- raceAbort as raceAbort4
272
+ raceAbort as raceAbort2
353
273
  } from "@ycodium-ai/plugin-api/executor";
354
- import { nodeStreamsFromHandle as nodeStreamsFromHandle3 } from "@ycodium-ai/plugin-api/process-stdin";
274
+ import { nodeStreamsFromHandle as nodeStreamsFromHandle2 } from "@ycodium-ai/plugin-api/process-stdin";
355
275
 
356
276
  // ../../packages/ycodium-acp-executor/src/executor.ts
357
277
  import * as NodeCrypto2 from "node:crypto";
@@ -468,8 +388,8 @@ var UnboundedEventStream = class {
468
388
  iterators.subscribers.delete(subscriber);
469
389
  return { value: void 0, done: true };
470
390
  }
471
- await new Promise((resolve4) => {
472
- subscriber.wake = resolve4;
391
+ await new Promise((resolve2) => {
392
+ subscriber.wake = resolve2;
473
393
  });
474
394
  }
475
395
  },
@@ -695,8 +615,8 @@ var settledExitCode = async (exited) => {
695
615
  try {
696
616
  return await Promise.race([
697
617
  exited.catch(() => void 0),
698
- new Promise((resolve4) => {
699
- timer = setTimeout(() => resolve4(void 0), AGENT_EXIT_SETTLE_MS);
618
+ new Promise((resolve2) => {
619
+ timer = setTimeout(() => resolve2(void 0), AGENT_EXIT_SETTLE_MS);
700
620
  })
701
621
  ]);
702
622
  } finally {
@@ -1036,15 +956,15 @@ function boundToolCallRawOutput(rawOutput) {
1036
956
  return rawOutput;
1037
957
  }
1038
958
  let changed = false;
1039
- const bounded2 = { ...rawOutput };
959
+ const bounded = { ...rawOutput };
1040
960
  for (const field of RAW_OUTPUT_TEXT_FIELDS) {
1041
961
  const value = rawOutput[field];
1042
962
  if (typeof value === "string" && value.length > TOOL_CALL_CONTENT_MAX_CHARS) {
1043
- bounded2[field] = boundToolCallOutputText(value);
963
+ bounded[field] = boundToolCallOutputText(value);
1044
964
  changed = true;
1045
965
  }
1046
966
  }
1047
- return changed ? bounded2 : rawOutput;
967
+ return changed ? bounded : rawOutput;
1048
968
  }
1049
969
  function toolCallContentText(entry) {
1050
970
  if (entry.type !== "content" || entry.content?.type !== "text") {
@@ -1071,7 +991,7 @@ function extractTextContentFromToolCallContent(content) {
1071
991
  if (joined.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
1072
992
  return { text: joined, content: typed };
1073
993
  }
1074
- const bounded2 = boundToolCallOutputText(joined);
994
+ const bounded = boundToolCallOutputText(joined);
1075
995
  const lastContributingTextIndex = typed.reduce(
1076
996
  (lastIndex, entry, index) => toolCallContentText(entry)?.trim() ? index : lastIndex,
1077
997
  -1
@@ -1083,9 +1003,9 @@ function extractTextContentFromToolCallContent(content) {
1083
1003
  if (index !== lastContributingTextIndex) {
1084
1004
  return [];
1085
1005
  }
1086
- return [{ type: "content", content: { type: "text", text: bounded2 } }];
1006
+ return [{ type: "content", content: { type: "text", text: bounded } }];
1087
1007
  });
1088
- return { text: bounded2, content: boundedContent };
1008
+ return { text: bounded, content: boundedContent };
1089
1009
  }
1090
1010
  function normalizeToolKind(kind) {
1091
1011
  return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : void 0;
@@ -1459,6 +1379,14 @@ function parseSessionUpdateEvent(params) {
1459
1379
  }
1460
1380
  break;
1461
1381
  }
1382
+ case "usage_update": {
1383
+ const used = upd["used"];
1384
+ const size = upd["size"];
1385
+ if (typeof used === "number" && Number.isSafeInteger(used) && used >= 0 && typeof size === "number" && Number.isSafeInteger(size) && size > 0) {
1386
+ events.push({ _tag: "ContextWindowUpdated", usedTokens: used, maxTokens: size });
1387
+ }
1388
+ break;
1389
+ }
1462
1390
  case "compaction_update": {
1463
1391
  const compactionId = readAcpText(upd, "compactionId");
1464
1392
  const status = readAcpText(upd, "status");
@@ -3654,18 +3582,18 @@ var validateAsync = async (schema, value, _ctx) => {
3654
3582
  return result.issues.length === 0;
3655
3583
  };
3656
3584
  var _encode = (_Err) => {
3657
- const parse4 = _parse(_Err);
3585
+ const parse3 = _parse(_Err);
3658
3586
  const fn = (schema, value, _ctx, _params) => {
3659
3587
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
3660
- return parse4(schema, value, ctx, finalizeParams(fn, _params));
3588
+ return parse3(schema, value, ctx, finalizeParams(fn, _params));
3661
3589
  };
3662
3590
  return fn;
3663
3591
  };
3664
3592
  var encode = /* @__PURE__ */ _encode($ZodRealError);
3665
3593
  var _decode = (_Err) => {
3666
- const parse4 = _parse(_Err);
3594
+ const parse3 = _parse(_Err);
3667
3595
  const fn = (schema, value, _ctx, _params) => {
3668
- return parse4(schema, value, _ctx, finalizeParams(fn, _params));
3596
+ return parse3(schema, value, _ctx, finalizeParams(fn, _params));
3669
3597
  };
3670
3598
  return fn;
3671
3599
  };
@@ -6835,7 +6763,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6835
6763
  var NONE = 0;
6836
6764
  var ASSUMED = 1;
6837
6765
  var PROVEN = 2;
6838
- function isRecursive(inst, stack, resolve4) {
6766
+ function isRecursive(inst, stack, resolve2) {
6839
6767
  const cached2 = recursive.get(inst);
6840
6768
  if (cached2 !== void 0)
6841
6769
  return cached2 ? PROVEN : NONE;
@@ -6845,7 +6773,7 @@ function isRecursive(inst, stack, resolve4) {
6845
6773
  let result = NONE;
6846
6774
  const check2 = (child) => {
6847
6775
  if (result !== PROVEN && child?._zod) {
6848
- const answer = isRecursive(child, stack, resolve4);
6776
+ const answer = isRecursive(child, stack, resolve2);
6849
6777
  if (answer > result)
6850
6778
  result = answer;
6851
6779
  }
@@ -6856,7 +6784,7 @@ function isRecursive(inst, stack, resolve4) {
6856
6784
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6857
6785
  if (spread && !desc.enumerable)
6858
6786
  continue;
6859
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve4) : NONE;
6787
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve2) : NONE;
6860
6788
  if (child > answer)
6861
6789
  answer = child;
6862
6790
  }
@@ -6920,7 +6848,7 @@ function isRecursive(inst, stack, resolve4) {
6920
6848
  break;
6921
6849
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6922
6850
  case "lazy": {
6923
- const inner = def._cachedInner ?? (resolve4 ? inst._zod.innerType : void 0);
6851
+ const inner = def._cachedInner ?? (resolve2 ? inst._zod.innerType : void 0);
6924
6852
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6925
6853
  break;
6926
6854
  }
@@ -23584,11 +23512,11 @@ var Connection = class {
23584
23512
  const id = this.nextRequestId++;
23585
23513
  let cancel = () => {
23586
23514
  };
23587
- const response = new Promise((resolve4, reject) => {
23515
+ const response = new Promise((resolve2, reject) => {
23588
23516
  const pendingResponse = {
23589
23517
  resolve: (value) => {
23590
23518
  try {
23591
- resolve4(mapResponse ? mapResponse(value) : value);
23519
+ resolve2(mapResponse ? mapResponse(value) : value);
23592
23520
  } catch (error62) {
23593
23521
  reject(error62);
23594
23522
  }
@@ -23645,8 +23573,8 @@ var Connection = class {
23645
23573
  this.stream = stream;
23646
23574
  this.staticHandlers = handlers;
23647
23575
  this.allowBatches = options?.allowBatches ?? true;
23648
- this.closedPromise = new Promise((resolve4) => {
23649
- this.abortController.signal.addEventListener("abort", () => resolve4());
23576
+ this.closedPromise = new Promise((resolve2) => {
23577
+ this.abortController.signal.addEventListener("abort", () => resolve2());
23650
23578
  });
23651
23579
  void this.receive();
23652
23580
  }
@@ -23937,13 +23865,13 @@ var ConnectionBuilder = class {
23937
23865
  /**
23938
23866
  * Adds a typed request handler for one method.
23939
23867
  */
23940
- onReceiveRequest(method, parse4, handler) {
23868
+ onReceiveRequest(method, parse3, handler) {
23941
23869
  return this.withHandler({
23942
23870
  handleMessage: async (message, cx) => {
23943
23871
  if (message.kind !== "request" || message.method !== method) {
23944
23872
  return Handled.no(message);
23945
23873
  }
23946
- const request = parse4(message.params);
23874
+ const request = parse3(message.params);
23947
23875
  return await handler(request, message.responder, cx) ?? Handled.yes();
23948
23876
  },
23949
23877
  describe: () => `${this.connectionName ?? "request"}:${method}`
@@ -23952,13 +23880,13 @@ var ConnectionBuilder = class {
23952
23880
  /**
23953
23881
  * Adds a typed notification handler for one method.
23954
23882
  */
23955
- onReceiveNotification(method, parse4, handler) {
23883
+ onReceiveNotification(method, parse3, handler) {
23956
23884
  return this.withHandler({
23957
23885
  handleMessage: async (message, cx) => {
23958
23886
  if (message.kind !== "notification" || message.method !== method) {
23959
23887
  return Handled.no(message);
23960
23888
  }
23961
- const notification = parse4(message.params);
23889
+ const notification = parse3(message.params);
23962
23890
  return await handler(notification, cx) ?? Handled.yes();
23963
23891
  },
23964
23892
  describe: () => `${this.connectionName ?? "notification"}:${method}`
@@ -24540,8 +24468,8 @@ var AsyncQueue = class {
24540
24468
  if (this.failed) {
24541
24469
  return Promise.reject(this.failure);
24542
24470
  }
24543
- return new Promise((resolve4, reject) => {
24544
- this.waiters.push({ resolve: resolve4, reject });
24471
+ return new Promise((resolve2, reject) => {
24472
+ this.waiters.push({ resolve: resolve2, reject });
24545
24473
  });
24546
24474
  }
24547
24475
  };
@@ -25588,12 +25516,12 @@ function createAcpConnection(options) {
25588
25516
  failIfClosed();
25589
25517
  const id = nextRequestId;
25590
25518
  nextRequestId += 1;
25591
- const { promise: promise2, resolve: resolve4, reject } = Promise.withResolvers();
25519
+ const { promise: promise2, resolve: resolve2, reject } = Promise.withResolvers();
25592
25520
  pending.set(String(id), {
25593
25521
  method,
25594
25522
  ...promptId === void 0 ? {} : { promptId },
25595
25523
  ...onArrival === void 0 ? {} : { onArrival },
25596
- resolve: resolve4,
25524
+ resolve: resolve2,
25597
25525
  reject
25598
25526
  });
25599
25527
  const message = params === void 0 ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
@@ -25622,8 +25550,8 @@ function createAcpConnection(options) {
25622
25550
  if (inboundBatches === 0) {
25623
25551
  return;
25624
25552
  }
25625
- await new Promise((resolve4) => {
25626
- idleWaiters.push(resolve4);
25553
+ await new Promise((resolve2) => {
25554
+ idleWaiters.push(resolve2);
25627
25555
  if (inboundBatches === 0) {
25628
25556
  releaseIdleWaiters();
25629
25557
  }
@@ -25709,8 +25637,8 @@ var Mutex = class {
25709
25637
  this.locked = true;
25710
25638
  return Promise.resolve();
25711
25639
  }
25712
- return new Promise((resolve4) => {
25713
- this.waiters.push(resolve4);
25640
+ return new Promise((resolve2) => {
25641
+ this.waiters.push(resolve2);
25714
25642
  });
25715
25643
  }
25716
25644
  tryAcquire() {
@@ -25911,9 +25839,9 @@ function createExecutorLifecycle({
25911
25839
  let timer;
25912
25840
  await Promise.race([
25913
25841
  connection.closed.catch(() => void 0),
25914
- new Promise((resolve4) => {
25842
+ new Promise((resolve2) => {
25915
25843
  timer = setTimeout(
25916
- resolve4,
25844
+ resolve2,
25917
25845
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
25918
25846
  );
25919
25847
  })
@@ -26086,7 +26014,7 @@ function toolSubagentSettlementOfTurn(state, failureCategory) {
26086
26014
  if (state === "cancelled") return "turn-interrupted";
26087
26015
  return state === "failed" && failureCategory === "process-exit" ? "session-ended" : "turn-ended";
26088
26016
  }
26089
- var sameFacts = (a, b) => a.title === b.title && a.description === b.description && a.summary === b.summary && a.role === b.role && a.model === b.model && a.effort === b.effort && a.rosterKind === b.rosterKind;
26017
+ var sameFacts = (a, b) => a.title === b.title && a.description === b.description && a.summary === b.summary && a.role === b.role && a.model === b.model && a.effort === b.effort && a.nativeSessionId === b.nativeSessionId && a.rosterKind === b.rosterKind;
26090
26018
  function linkage(taskId, toolCallId, facts) {
26091
26019
  return {
26092
26020
  taskId,
@@ -26096,6 +26024,7 @@ function linkage(taskId, toolCallId, facts) {
26096
26024
  ...facts.role === void 0 ? {} : { role: facts.role },
26097
26025
  ...facts.model === void 0 ? {} : { model: facts.model },
26098
26026
  ...facts.effort === void 0 ? {} : { effort: facts.effort },
26027
+ ...facts.nativeSessionId === void 0 ? {} : { nativeSessionId: facts.nativeSessionId },
26099
26028
  ...facts.rosterKind === void 0 ? {} : { rosterKind: facts.rosterKind }
26100
26029
  };
26101
26030
  }
@@ -26790,12 +26719,12 @@ function createPromptResults({
26790
26719
  }) {
26791
26720
  const prompts = /* @__PURE__ */ new Map();
26792
26721
  const add = (identity, finish) => {
26793
- const { promise: done, resolve: resolve4 } = Promise.withResolvers();
26722
+ const { promise: done, resolve: resolve2 } = Promise.withResolvers();
26794
26723
  const record4 = {
26795
26724
  ...identity,
26796
26725
  finish,
26797
26726
  done,
26798
- resolve: resolve4,
26727
+ resolve: resolve2,
26799
26728
  rejected: false,
26800
26729
  interrupted: false,
26801
26730
  finished: false
@@ -26843,9 +26772,9 @@ function createPromptResults({
26843
26772
  try {
26844
26773
  const drained = await Promise.race([
26845
26774
  Promise.all(claimed.map((record4) => record4.done)).then(() => true),
26846
- new Promise((resolve4) => {
26775
+ new Promise((resolve2) => {
26847
26776
  timer = setTimeout(
26848
- () => resolve4(false),
26777
+ () => resolve2(false),
26849
26778
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
26850
26779
  );
26851
26780
  })
@@ -27044,14 +26973,14 @@ function createExecutorRequests({
27044
26973
  const statement = hooks.permissionStatement?.(permissionContext) ?? defaultPermissionStatement(permissionRequest);
27045
26974
  const fileChanges = hooks.permissionFileChanges?.(permissionContext) ?? fileChangesFromAcpPermission(permissionRequest);
27046
26975
  const requestId = randomId();
27047
- const outcome = await new Promise((resolve4) => {
26976
+ const outcome = await new Promise((resolve2) => {
27048
26977
  const pending = {
27049
26978
  requestId,
27050
26979
  request: params,
27051
26980
  permissionRequest,
27052
26981
  turnId: shared.activeTurnId,
27053
26982
  settled: false,
27054
- resolve: resolve4
26983
+ resolve: resolve2
27055
26984
  };
27056
26985
  approvals.add(pending);
27057
26986
  emit(
@@ -27134,7 +27063,7 @@ function createExecutorRequests({
27134
27063
  }
27135
27064
 
27136
27065
  // ../../packages/ycodium-acp-executor/src/artifacts.ts
27137
- import * as NodePath4 from "node:path";
27066
+ import * as NodePath3 from "node:path";
27138
27067
  import * as NodeURL from "node:url";
27139
27068
  function resourceLinkArtifacts(content) {
27140
27069
  if (content["type"] !== "resource_link" || typeof content["uri"] !== "string") return [];
@@ -27145,7 +27074,7 @@ function resourceLinkArtifacts(content) {
27145
27074
  } catch {
27146
27075
  return [];
27147
27076
  }
27148
- if (!NodePath4.isAbsolute(path)) return [];
27077
+ if (!NodePath3.isAbsolute(path)) return [];
27149
27078
  const name = typeof content["name"] === "string" ? content["name"].trim() : "";
27150
27079
  const mimeType = typeof content["mimeType"] === "string" ? content["mimeType"].trim() : "";
27151
27080
  return [
@@ -27268,14 +27197,14 @@ function createExecutorRuntime({
27268
27197
  if (!promptMutex.isLocked) {
27269
27198
  return true;
27270
27199
  }
27271
- return await new Promise((resolve4) => {
27200
+ return await new Promise((resolve2) => {
27272
27201
  const timer = setTimeout(() => {
27273
27202
  shared.promptWaiters = shared.promptWaiters.filter((waiter) => waiter !== onSettle);
27274
- resolve4(false);
27203
+ resolve2(false);
27275
27204
  }, timeoutMs);
27276
27205
  const onSettle = () => {
27277
27206
  clearTimeout(timer);
27278
- resolve4(true);
27207
+ resolve2(true);
27279
27208
  };
27280
27209
  shared.promptWaiters.push(onSettle);
27281
27210
  });
@@ -27626,10 +27555,27 @@ function createExecutorSession({
27626
27555
  throw new AcpExecutorDisposedError();
27627
27556
  }
27628
27557
  }
27558
+ const mcpCapabilities = initialized.agentCapabilities?.mcpCapabilities ?? hooks.mcpCapabilities;
27559
+ const requestedMcpServers = options.mcpServers ?? [];
27629
27560
  const mcpServers = filterMcpServersByAgentCapabilities(
27630
- options.mcpServers ?? [],
27631
- initialized.agentCapabilities
27561
+ requestedMcpServers,
27562
+ mcpCapabilities === void 0 ? initialized.agentCapabilities : { mcpCapabilities }
27632
27563
  );
27564
+ if (mcpServers.length < requestedMcpServers.length) {
27565
+ const kept = new Set(mcpServers);
27566
+ const dropped = requestedMcpServers.filter((server) => !kept.has(server)).map((server) => ({
27567
+ ...typeof server["name"] === "string" ? { name: server["name"] } : {},
27568
+ ...typeof server.type === "string" ? { type: server.type } : {}
27569
+ }));
27570
+ options.log?.warn?.(
27571
+ "acp session dropped MCP servers whose transport was not advertised in initialize.agentCapabilities.mcpCapabilities; set hooks.mcpCapabilities if the agent supports the transport without reporting it",
27572
+ {
27573
+ threadId: options.threadId,
27574
+ dropped,
27575
+ advertisedMcpCapabilities: initialized.agentCapabilities?.mcpCapabilities ?? null
27576
+ }
27577
+ );
27578
+ }
27633
27579
  const additionalDirectories = options.additionalDirectories !== void 0 && options.additionalDirectories.length > 0 ? { additionalDirectories: options.additionalDirectories } : {};
27634
27580
  let setup;
27635
27581
  let nextSessionId;
@@ -28224,6 +28170,17 @@ function createExecutorUpdates({
28224
28170
  emitArtifacts(resourceLinkArtifacts(event.content));
28225
28171
  continue;
28226
28172
  }
28173
+ if (event._tag === "ContextWindowUpdated") {
28174
+ emit({
28175
+ type: "thread.token-usage.updated",
28176
+ ...stamp(),
28177
+ provider: options.provider,
28178
+ threadId: options.threadId,
28179
+ ...shared.activeTurnId === void 0 ? {} : { turnId: shared.activeTurnId },
28180
+ payload: { usage: { usedTokens: event.usedTokens, maxTokens: event.maxTokens } }
28181
+ });
28182
+ continue;
28183
+ }
28227
28184
  if (event._tag === "CompactionUpdated") {
28228
28185
  applyCompactionUpdate(event);
28229
28186
  continue;
@@ -28340,9 +28297,9 @@ function readOpenToolCalls(toolCalls, turnId) {
28340
28297
  }
28341
28298
 
28342
28299
  // ../../packages/ycodium-acp-executor/src/protocol-log.ts
28343
- import * as NodeFS2 from "node:fs";
28344
- import * as NodeOS3 from "node:os";
28345
- import * as NodePath5 from "node:path";
28300
+ import * as NodeFS from "node:fs";
28301
+ import * as NodeOS2 from "node:os";
28302
+ import * as NodePath4 from "node:path";
28346
28303
  var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
28347
28304
  var UNSAFE_FILE_CHARS = /[^A-Za-z0-9._-]+/gu;
28348
28305
  function safeFileName(value) {
@@ -28350,12 +28307,12 @@ function safeFileName(value) {
28350
28307
  }
28351
28308
  function createAcpProtocolLogFile(input2) {
28352
28309
  const maxBytes = input2.maxBytes ?? DEFAULT_MAX_BYTES;
28353
- NodeFS2.mkdirSync(input2.directory, { recursive: true });
28354
- const filePath = NodePath5.join(
28310
+ NodeFS.mkdirSync(input2.directory, { recursive: true });
28311
+ const filePath = NodePath4.join(
28355
28312
  input2.directory,
28356
28313
  `${safeFileName(input2.provider)}-${safeFileName(input2.threadId)}-${Date.now().toString(36)}.ndjson`
28357
28314
  );
28358
- const stream = (input2.openStream ?? ((path) => NodeFS2.createWriteStream(path, { flags: "a" })))(
28315
+ const stream = (input2.openStream ?? ((path) => NodeFS.createWriteStream(path, { flags: "a" })))(
28359
28316
  filePath
28360
28317
  );
28361
28318
  let bytes = 0;
@@ -28407,7 +28364,7 @@ function createAcpProtocolLogFromEnv(input2) {
28407
28364
  const flag = process.env.YCODIUM_ACP_PROTOCOL_LOG;
28408
28365
  if (flag !== "1" && flag?.toLowerCase() !== "true") return void 0;
28409
28366
  const configured = process.env.YCODIUM_ACP_PROTOCOL_LOG_DIR?.trim();
28410
- const directory = configured && configured.length > 0 ? configured : NodePath5.join(NodeOS3.tmpdir(), "ycodium-acp-protocol");
28367
+ const directory = configured && configured.length > 0 ? configured : NodePath4.join(NodeOS2.tmpdir(), "ycodium-acp-protocol");
28411
28368
  try {
28412
28369
  const sink = createAcpProtocolLogFile({
28413
28370
  directory,
@@ -28849,13 +28806,13 @@ function acpNativeSessionProcessMatcher(program, args) {
28849
28806
 
28850
28807
  // ../../packages/ycodium-acp-executor/src/prompt-dispatch.ts
28851
28808
  var dispatchAcpPrompt = (executor, input2) => {
28852
- const { promise: dispatched, resolve: resolve4 } = Promise.withResolvers();
28809
+ const { promise: dispatched, resolve: resolve2 } = Promise.withResolvers();
28853
28810
  let written = false;
28854
28811
  const finished = executor.prompt({
28855
28812
  ...input2,
28856
28813
  onDispatched: (turnId) => {
28857
28814
  written = true;
28858
- resolve4(turnId);
28815
+ resolve2(turnId);
28859
28816
  }
28860
28817
  });
28861
28818
  return Promise.race([
@@ -28870,8 +28827,8 @@ var dispatchAcpPrompt = (executor, input2) => {
28870
28827
  };
28871
28828
 
28872
28829
  // ../../packages/ycodium-acp-executor/src/thread-operations.ts
28873
- var yieldTick = () => new Promise((resolve4) => {
28874
- setImmediate(resolve4);
28830
+ var yieldTick = () => new Promise((resolve2) => {
28831
+ setImmediate(resolve2);
28875
28832
  });
28876
28833
  var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
28877
28834
  function createAcpThreadOperations(options) {
@@ -28946,6 +28903,133 @@ function createAcpThreadOperations(options) {
28946
28903
  };
28947
28904
  }
28948
28905
 
28906
+ // ../../packages/ycodium-executor-common/src/nodeStreams.ts
28907
+ import * as NodeOS3 from "node:os";
28908
+ import * as NodeStream2 from "node:stream";
28909
+ var PEER_CLOSED_STDIN_CODES = /* @__PURE__ */ new Set([
28910
+ "EPIPE",
28911
+ "ECONNRESET",
28912
+ "EOF",
28913
+ "ERR_STREAM_DESTROYED",
28914
+ "ERR_STREAM_WRITE_AFTER_END",
28915
+ "ERR_STREAM_ALREADY_FINISHED"
28916
+ ]);
28917
+ function errorCode(value) {
28918
+ if (typeof value !== "object" || value === null) return void 0;
28919
+ const code = value.code;
28920
+ return typeof code === "string" ? code : void 0;
28921
+ }
28922
+ function asError(value) {
28923
+ return value instanceof Error ? value : new Error(String(value));
28924
+ }
28925
+ function isPeerClosedStdinError(error62) {
28926
+ const code = errorCode(error62);
28927
+ return code !== void 0 && PEER_CLOSED_STDIN_CODES.has(code);
28928
+ }
28929
+ var PeerClosedStdinError = class extends Error {
28930
+ name = "PeerClosedStdinError";
28931
+ code;
28932
+ constructor(operation, cause) {
28933
+ super(
28934
+ `Child process stdin is closed; the ${operation} did not reach the peer.`,
28935
+ cause === void 0 ? void 0 : { cause }
28936
+ );
28937
+ this.code = errorCode(cause) ?? "ERR_STREAM_DESTROYED";
28938
+ }
28939
+ };
28940
+ var ownErrors = {
28941
+ isPeerClosed: isPeerClosedStdinError,
28942
+ peerClosed: (operation, cause) => new PeerClosedStdinError(operation, cause)
28943
+ };
28944
+ function toStreamError(errors, operation, error62) {
28945
+ if (errors.isPeerClosed(error62)) return errors.peerClosed(operation, error62);
28946
+ return asError(error62);
28947
+ }
28948
+ function nodeWritableFromHandle(handle, errors = ownErrors) {
28949
+ return new NodeStream2.Writable({
28950
+ write(chunk, _encoding, callback) {
28951
+ const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
28952
+ handle.writeStdin(bytes).then(
28953
+ () => callback(),
28954
+ (error62) => callback(toStreamError(errors, "write", error62))
28955
+ );
28956
+ },
28957
+ final(callback) {
28958
+ handle.closeStdin().then(
28959
+ () => callback(),
28960
+ // 关一条对端已经没了的流是正常收尾,不是失败;真异常照旧交出去。
28961
+ (error62) => callback(errors.isPeerClosed(error62) ? void 0 : toStreamError(errors, "close", error62))
28962
+ );
28963
+ }
28964
+ });
28965
+ }
28966
+ var STDERR_TAIL_MAX_CHARS = 4096;
28967
+ var STDERR_SETTLE_MS = 500;
28968
+ var PAIRING_URL_PATTERN = /https?:\/\/[^\s]*\/pair#[^\s]*/gi;
28969
+ var BEARER_TOKEN_PATTERN = /\bBearer\s+[A-Za-z0-9._\-+=/]+/gi;
28970
+ var BASIC_AUTH_PATTERN = /\bAuthorization:\s*Basic\s+\S+/gi;
28971
+ var API_KEY_HEADER_PATTERN = /\bx-api-key:\s*\S+/gi;
28972
+ var SECRET_TOKEN_PATTERN = /\b(?:sk-[A-Za-z0-9][A-Za-z0-9-]{7,}|ghp_[A-Za-z0-9]+|xox[a-zA-Z]-[A-Za-z0-9-]+)\b/g;
28973
+ function redactStderrExcerpt(text4, environment = process.env) {
28974
+ let result = text4.replaceAll("\0", "");
28975
+ const homes = [environment["HOME"], environment["USERPROFILE"], NodeOS3.homedir()].filter(
28976
+ (value) => typeof value === "string" && value.length > 1
28977
+ );
28978
+ for (const home of new Set(homes)) {
28979
+ result = result.split(home).join("~");
28980
+ }
28981
+ return result.replace(PAIRING_URL_PATTERN, "[pairing-url]").replace(BEARER_TOKEN_PATTERN, "Bearer [redacted]").replace(BASIC_AUTH_PATTERN, "Authorization: Basic [redacted]").replace(API_KEY_HEADER_PATTERN, "x-api-key: [redacted]").replace(SECRET_TOKEN_PATTERN, "[redacted]").trim();
28982
+ }
28983
+ function drainStderrTail(stderr) {
28984
+ let tail = "";
28985
+ const decoder = new TextDecoder();
28986
+ const drained = (async () => {
28987
+ for await (const chunk of stderr) {
28988
+ const next = tail + decoder.decode(chunk, { stream: true });
28989
+ tail = next.length <= STDERR_TAIL_MAX_CHARS ? next : next.slice(-STDERR_TAIL_MAX_CHARS);
28990
+ }
28991
+ })().catch(() => void 0);
28992
+ return async () => {
28993
+ let timer;
28994
+ await Promise.race([
28995
+ drained,
28996
+ new Promise((resolve2) => {
28997
+ timer = setTimeout(resolve2, STDERR_SETTLE_MS);
28998
+ })
28999
+ ]);
29000
+ clearTimeout(timer);
29001
+ return redactStderrExcerpt(tail);
29002
+ };
29003
+ }
29004
+ function nodeStreamsFromHandle(handle, errors = ownErrors) {
29005
+ const readable = new NodeStream2.PassThrough();
29006
+ void (async () => {
29007
+ try {
29008
+ for await (const chunk of handle.stdout) {
29009
+ if (!readable.writable) return;
29010
+ if (!readable.write(chunk)) {
29011
+ await new Promise((resolve2) => {
29012
+ const onDone = () => {
29013
+ readable.off("drain", onDone);
29014
+ readable.off("close", onDone);
29015
+ resolve2();
29016
+ };
29017
+ readable.once("drain", onDone);
29018
+ readable.once("close", onDone);
29019
+ });
29020
+ }
29021
+ }
29022
+ } catch (error62) {
29023
+ readable.destroy(asError(error62));
29024
+ return;
29025
+ }
29026
+ if (readable.writable) readable.end();
29027
+ })();
29028
+ const settledStderrTail = drainStderrTail(handle.stderr);
29029
+ const writable = nodeWritableFromHandle(handle, errors);
29030
+ return { readable, writable, stderrTail: settledStderrTail };
29031
+ }
29032
+
28949
29033
  // ../../packages/ycodium-acp-executor/src/mcp-servers.ts
28950
29034
  function toAcpMcpServers(entries) {
28951
29035
  return (entries ?? []).map(
@@ -28985,8 +29069,8 @@ async function raceStartAbort(promise2, signal) {
28985
29069
  }
28986
29070
 
28987
29071
  // ../../packages/ycodium-acp-executor/src/instance-kit.ts
28988
- var yieldTick2 = () => new Promise((resolve4) => {
28989
- setImmediate(resolve4);
29072
+ var yieldTick2 = () => new Promise((resolve2) => {
29073
+ setImmediate(resolve2);
28990
29074
  });
28991
29075
  var nowIso2 = () => (/* @__PURE__ */ new Date()).toISOString();
28992
29076
  function createAcpThreadTable(log, beforeStopAll) {
@@ -29104,7 +29188,7 @@ var acpProbeFailureDetail = (error62) => (error62 instanceof Error ? error62.mes
29104
29188
  // ../../packages/ycodium-acp-executor/src/probe.ts
29105
29189
  function withProbeTimeout(promise2, timeoutMs, what, signal) {
29106
29190
  signal?.throwIfAborted();
29107
- return new Promise((resolve4, reject) => {
29191
+ return new Promise((resolve2, reject) => {
29108
29192
  const onAbort = () => {
29109
29193
  clearTimeout(timer);
29110
29194
  reject(signal?.reason ?? new Error("aborted"));
@@ -29119,7 +29203,7 @@ function withProbeTimeout(promise2, timeoutMs, what, signal) {
29119
29203
  (value) => {
29120
29204
  clearTimeout(timer);
29121
29205
  signal?.removeEventListener("abort", onAbort);
29122
- resolve4(value);
29206
+ resolve2(value);
29123
29207
  },
29124
29208
  (error62) => {
29125
29209
  clearTimeout(timer);
@@ -29223,334 +29307,101 @@ async function collectProbeProcess(child, input2) {
29223
29307
  }
29224
29308
  var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
29225
29309
 
29226
- // ../../packages/ycodium-jsonl-stream/src/sessionTranscript.ts
29227
- var SESSION_IMPORT_ACTIVITY_TEXT_LIMIT = 32e3;
29228
- function bounded(value, tail = false) {
29229
- if (value.length <= SESSION_IMPORT_ACTIVITY_TEXT_LIMIT) return { text: value, truncated: false };
29230
- const offset = tail ? value.length - SESSION_IMPORT_ACTIVITY_TEXT_LIMIT : SESSION_IMPORT_ACTIVITY_TEXT_LIMIT;
29231
- const character = value.charCodeAt(offset);
29232
- const previous = value.charCodeAt(offset - 1);
29233
- const splitPair = character >= 56320 && character <= 57343 && previous >= 55296 && previous <= 56319;
29234
- return {
29235
- text: tail ? value.slice(offset + (splitPair ? 1 : 0)) : value.slice(0, offset - (splitPair ? 1 : 0)),
29236
- truncated: true
29237
- };
29238
- }
29239
- function inputPayload(input2) {
29240
- if (input2 === void 0) return {};
29241
- const result = bounded(input2);
29242
- return { input: result.text, ...result.truncated ? { inputTruncated: true } : {} };
29243
- }
29244
- function outputPayload(output2) {
29245
- if (output2 === void 0) return {};
29246
- const result = bounded(output2, true);
29247
- return { output: result.text, ...result.truncated ? { outputTruncated: true } : {} };
29248
- }
29249
-
29250
- // ../../packages/ycodium-instance-config/src/launchArgs.ts
29251
- function tokenizeShellWords(value) {
29252
- const input2 = value.trim();
29253
- if (!input2) return [];
29254
- const tokens = [];
29255
- let current = "";
29256
- let quote;
29257
- let quoted = false;
29258
- for (let index = 0; index < input2.length; index++) {
29259
- const char = input2[index];
29260
- if (char === void 0) continue;
29261
- if (quote) {
29262
- if (char === quote) {
29263
- quote = void 0;
29264
- quoted = true;
29265
- } else if (char === "\\" && quote === '"') {
29266
- const next = input2[index + 1];
29267
- if (next !== void 0 && ['"', "\\", "$", "`"].includes(next)) {
29268
- current += next;
29269
- index++;
29270
- } else {
29271
- current += char;
29272
- }
29273
- } else {
29274
- current += char;
29275
- }
29276
- continue;
29277
- }
29278
- if (char === "'" || char === '"') {
29279
- quote = char;
29280
- quoted = true;
29281
- } else if (/\s/.test(char)) {
29282
- if (current || quoted) {
29283
- tokens.push(current);
29284
- current = "";
29285
- quoted = false;
29286
- }
29287
- } else if (char === "\\") {
29288
- const next = input2[index + 1];
29289
- if (next !== void 0 && /\s/.test(next)) {
29290
- current += next;
29291
- index++;
29292
- } else {
29293
- current += char;
29294
- }
29295
- } else {
29296
- current += char;
29297
- }
29310
+ // ../../packages/ycodium-executor-common/src/raceAbort.ts
29311
+ async function raceAbort(pending, signal) {
29312
+ if (signal === void 0) return pending;
29313
+ void pending.catch(() => void 0);
29314
+ if (signal.aborted) throw new Error("aborted");
29315
+ let onAbort;
29316
+ const aborted2 = new Promise((_resolve, reject) => {
29317
+ onAbort = () => reject(new Error("aborted"));
29318
+ signal.addEventListener("abort", onAbort, { once: true });
29319
+ });
29320
+ try {
29321
+ return await Promise.race([pending, aborted2]);
29322
+ } finally {
29323
+ signal.removeEventListener("abort", onAbort);
29298
29324
  }
29299
- if (current || quoted) tokens.push(current);
29300
- return tokens;
29301
29325
  }
29302
29326
 
29303
- // ../../packages/ycodium-instance-config/src/instanceConfig.ts
29304
- import { modelSelectionStringOption as modelSelectionStringOption2 } from "@ycodium-ai/plugin-api/executor";
29305
- function isRecord8(value) {
29306
- return typeof value === "object" && value !== null && !Array.isArray(value);
29307
- }
29308
- function readString(value) {
29309
- return typeof value === "string" ? value : "";
29310
- }
29311
- function readTrimmed(value) {
29312
- return readString(value).trim();
29313
- }
29314
- function modelIdFromSelection(selection) {
29315
- if (!isRecord8(selection)) return void 0;
29316
- const model = selection["model"];
29317
- return typeof model === "string" ? model.trim() || void 0 : void 0;
29318
- }
29319
- function readTurnSelection(selection, effortOptionId) {
29320
- const requestedModelId = modelIdFromSelection(selection);
29321
- const requestedEffort = modelSelectionStringOption2(selection, effortOptionId);
29322
- return {
29323
- ...requestedModelId === void 0 ? {} : { requestedModelId },
29324
- ...requestedEffort === void 0 ? {} : { requestedEffort }
29325
- };
29326
- }
29327
- function readEnvironment(value) {
29328
- if (!Array.isArray(value)) return {};
29329
- const env = {};
29330
- for (const entry of value) {
29331
- if (!isRecord8(entry)) continue;
29332
- const name = readTrimmed(entry["name"]);
29333
- if (name.length === 0) continue;
29334
- env[name] = readString(entry["value"]);
29327
+ // ../../packages/ycodium-acp-executor/src/probe-process.ts
29328
+ async function runAcpProbeProcess(input2) {
29329
+ const spawned = await input2.spawn(input2.cwd);
29330
+ if (spawned.kind !== "spawned") return spawned;
29331
+ const handle = spawned.handle;
29332
+ let handshake;
29333
+ try {
29334
+ const streams = nodeStreamsFromHandle(handle);
29335
+ handshake = await raceAbort(
29336
+ openAcpProbeHandshake({
29337
+ readable: streams.readable,
29338
+ writable: streams.writable,
29339
+ clientInfo: input2.clientInfo,
29340
+ requestTimeoutMs: input2.requestTimeoutMs,
29341
+ ...input2.subagentSessions === void 0 ? {} : { subagentSessions: input2.subagentSessions }
29342
+ }),
29343
+ input2.signal
29344
+ );
29345
+ return { kind: "ok", value: await input2.run(handshake) };
29346
+ } catch (error62) {
29347
+ return {
29348
+ kind: "threw",
29349
+ error: error62,
29350
+ handshakeOpened: handshake !== void 0,
29351
+ initializeResult: handshake?.initializeResult
29352
+ };
29353
+ } finally {
29354
+ await handshake?.close().catch(() => void 0);
29355
+ await handle.kill("SIGTERM").catch(() => void 0);
29335
29356
  }
29336
- return env;
29337
- }
29338
- function instanceSettings(config2) {
29339
- if (!isRecord8(config2)) return {};
29340
- return isRecord8(config2["config"]) ? config2["config"] : config2;
29341
- }
29342
- function readInstanceEnvelope(config2) {
29343
- const envelope = isRecord8(config2) ? config2 : {};
29344
- const settings = instanceSettings(config2);
29345
- return {
29346
- settings,
29347
- settingOrEnvelope: (key) => readTrimmed(settings[key]) || readTrimmed(envelope[key]),
29348
- environment: readEnvironment(envelope["environment"]),
29349
- envelopeDriver: readTrimmed(envelope["driver"]) || void 0
29350
- };
29351
- }
29352
- function readLaunchInstanceRecipe(config2, defaultLaunchArgs = "") {
29353
- const envelope = readInstanceEnvelope(config2);
29354
- return {
29355
- binaryPath: readTrimmed(envelope.settings["binaryPath"]),
29356
- launchArgs: readString(envelope.settings["launchArgs"]) || defaultLaunchArgs,
29357
- homePath: envelope.settingOrEnvelope("homePath"),
29358
- homeEnvVar: envelope.settingOrEnvelope("homeEnvVar"),
29359
- environment: envelope.environment,
29360
- envelopeDriver: envelope.envelopeDriver
29361
- };
29362
29357
  }
29363
29358
 
29359
+ // src/grokInstance.ts
29360
+ import {
29361
+ tokenizeShellWords as tokenizeShellWords2,
29362
+ modelIdFromSelection,
29363
+ readTurnSelection
29364
+ } from "@ycodium-ai/plugin-api/instance-config";
29365
+
29364
29366
  // src/config.ts
29367
+ import {
29368
+ readLaunchInstanceRecipe
29369
+ } from "@ycodium-ai/plugin-api/instance-config";
29365
29370
  var GROK_DEFAULT_LAUNCH_ARGS = "agent stdio";
29366
29371
  function parseGrokInstanceConfig(config2) {
29367
29372
  return readLaunchInstanceRecipe(config2, GROK_DEFAULT_LAUNCH_ARGS);
29368
29373
  }
29369
29374
 
29370
29375
  // src/grokSignIn.ts
29371
- import {
29372
- raceAbort as raceAbort2
29373
- } from "@ycodium-ai/plugin-api/executor";
29374
-
29375
- // src/deviceCodeOutput.ts
29376
- var OUTPUT_QUIET_MS = 3e3;
29377
- var SILENT_CAP_MS = 3e4;
29378
- var DEVICE_CODE_URL = /https?:\/\/\S+/;
29379
- var DEVICE_CODE_VALUE = /\b([A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+)\b/;
29380
- var deviceCodeUrl = (output2) => DEVICE_CODE_URL.exec(output2)?.[0];
29381
- var deviceCodeValue = (output2) => DEVICE_CODE_VALUE.exec(output2)?.[1];
29382
- var hasDeviceCode = (output2) => deviceCodeUrl(output2) !== void 0 && deviceCodeValue(output2) !== void 0;
29383
- function readDeviceCodeOutput(stdout, onText) {
29384
- const collected = [];
29385
- let onCodeFound;
29386
- const codeFound = new Promise((resolve4) => {
29387
- onCodeFound = resolve4;
29388
- });
29389
- let quietTimer;
29390
- let onQuiet;
29391
- const outputWentQuiet = new Promise((resolve4) => {
29392
- onQuiet = resolve4;
29393
- });
29394
- const text4 = (async () => {
29395
- const decoder = new TextDecoder();
29396
- for await (const chunk of stdout) {
29397
- const piece = decoder.decode(chunk, { stream: true });
29398
- collected.push(piece);
29399
- onText(piece);
29400
- if (onCodeFound !== void 0 && hasDeviceCode(collected.join(""))) {
29401
- onCodeFound();
29402
- onCodeFound = void 0;
29403
- }
29404
- if (onQuiet !== void 0) {
29405
- clearTimeout(quietTimer);
29406
- quietTimer = setTimeout(() => onQuiet?.(), OUTPUT_QUIET_MS);
29407
- }
29408
- }
29409
- return collected.join("");
29410
- })();
29411
- const code = (async () => {
29412
- let silentCap;
29413
- await Promise.race([
29414
- codeFound,
29415
- text4.then(() => void 0),
29416
- outputWentQuiet,
29417
- new Promise((resolve4) => {
29418
- silentCap = setTimeout(resolve4, SILENT_CAP_MS);
29419
- })
29420
- ]);
29421
- clearTimeout(silentCap);
29422
- clearTimeout(quietTimer);
29423
- onQuiet = void 0;
29424
- const output2 = collected.join("");
29425
- const verificationUrl = deviceCodeUrl(output2);
29426
- const userCode = deviceCodeValue(output2);
29427
- return {
29428
- ...userCode === void 0 ? {} : { userCode },
29429
- ...verificationUrl === void 0 ? {} : { verificationUrl }
29430
- };
29431
- })();
29432
- return { text: text4, code };
29433
- }
29434
-
29435
- // src/grokSignIn.ts
29376
+ import { createCliDeviceSignIn } from "@ycodium-ai/plugin-api/runtime-maintenance";
29436
29377
  function makeGrokSignIn(input2) {
29437
- const { host, recipe } = input2;
29438
- const operations = /* @__PURE__ */ new Map();
29439
- const signIn = {
29440
- start: async (signal) => {
29441
- if (recipe.binaryPath.length === 0) throw new Error("Grok program path is not configured");
29442
- const env = buildSignInEnv(recipe);
29443
- const handle = await host.process.spawn({
29444
- program: recipe.binaryPath,
29445
- args: [...GROK_CARD.deviceCodeSignInArgs],
29446
- owner: { bindingId: host.bindingId },
29447
- ...Object.keys(env).length > 0 ? { env } : {},
29448
- ...signal === void 0 ? {} : { signal }
29449
- });
29450
- const output2 = readDeviceCodeOutput(
29451
- handle.stdout,
29452
- (text4) => host.log.info("sign-in output", { text: text4 })
29453
- );
29454
- const operationId = `grok-sign-in-${Date.now().toString(36)}-${operations.size}`;
29455
- let closing;
29456
- const operation = {
29457
- handle,
29458
- close: () => closing ??= Promise.resolve().then(async () => {
29459
- await handle.kill("SIGTERM").catch(() => void 0);
29460
- await Promise.allSettled([handle.exited, output2.text]);
29461
- }).finally(() => {
29462
- if (operations.get(operationId) === operation) operations.delete(operationId);
29463
- })
29464
- };
29465
- operations.set(operationId, operation);
29466
- try {
29467
- const code = await raceAbort2(output2.code, signal);
29468
- if (signal?.aborted || input2.isDisposed()) throw new Error("Grok sign-in cancelled");
29469
- return { operationId, ...code };
29470
- } catch (error62) {
29471
- await operation.close();
29472
- throw error62;
29473
- }
29474
- },
29475
- cancel: async (operationId) => {
29476
- await operations.get(operationId)?.close();
29477
- },
29478
- verify: async (signal) => {
29479
- const active2 = [...operations.values()];
29480
- try {
29481
- for (const operation of active2) {
29482
- const code = await raceAbort2(operation.handle.exited, signal);
29483
- if (code !== 0) throw new Error(`Grok sign-in exited with code ${String(code)}`);
29484
- }
29485
- return await input2.probe(signal);
29486
- } finally {
29487
- await Promise.all(active2.map((operation) => operation.close()));
29488
- }
29489
- }
29490
- };
29491
- return {
29492
- signIn,
29493
- close: async () => {
29494
- await Promise.all([...operations.values()].map((operation) => operation.close()));
29378
+ return createCliDeviceSignIn({
29379
+ ...input2,
29380
+ name: "Grok",
29381
+ program: input2.recipe.binaryPath,
29382
+ args: GROK_CARD.deviceCodeSignInArgs,
29383
+ env: buildSignInEnv(input2.recipe),
29384
+ stream: "stdout",
29385
+ parse: (text4) => {
29386
+ const verificationUrl = /https?:\/\/\S+/.exec(text4)?.[0];
29387
+ const userCode = /\b([A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+)\b/.exec(text4)?.[1];
29388
+ return verificationUrl && userCode ? { verificationUrl, userCode } : void 0;
29495
29389
  }
29496
- };
29390
+ });
29497
29391
  }
29498
29392
 
29499
29393
  // src/grokQuota.ts
29500
- import * as NodeFS3 from "node:fs";
29501
- import * as NodePath6 from "node:path";
29394
+ import * as NodeFS2 from "node:fs";
29395
+ import * as NodePath5 from "node:path";
29502
29396
  import "@ycodium-ai/plugin-api/usage";
29503
-
29504
- // ../../packages/ycodium-credential-account/src/quotaRequest.ts
29505
- import { parseRetryAfterMs } from "@ycodium-ai/plugin-api/usage";
29506
- async function requestQuotaJson(input2) {
29507
- let response;
29508
- try {
29509
- response = await input2.fetch(input2.url, {
29510
- headers: input2.headers,
29511
- signal: AbortSignal.any([
29512
- ...input2.signal === void 0 ? [] : [input2.signal],
29513
- AbortSignal.timeout(input2.timeoutMs)
29514
- ])
29515
- });
29516
- } catch {
29517
- return { status: "unavailable", reason: "unreachable" };
29518
- }
29519
- if (response.status === 401 || response.status === 403) {
29520
- return { status: "unavailable", reason: "authRejected" };
29521
- }
29522
- if (response.status === 429) {
29523
- const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"), input2.now());
29524
- return {
29525
- status: "unavailable",
29526
- reason: "rateLimited",
29527
- ...retryAfterMs === null ? {} : { retryAfterMs }
29528
- };
29529
- }
29530
- if (!response.ok) return { status: "unavailable", reason: "unreachable" };
29531
- let body;
29532
- try {
29533
- body = JSON.parse(await response.text());
29534
- } catch {
29535
- return { status: "unavailable", reason: "unreachable" };
29536
- }
29537
- if (!isRecord(body)) return { status: "unavailable", reason: "unreachable" };
29538
- return { body };
29539
- }
29540
-
29541
- // ../../packages/ycodium-credential-account/src/quotaJson.ts
29542
- var asObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
29543
- var asString3 = (value) => typeof value === "string" && value.length > 0 ? value : null;
29544
- var asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
29545
- var parseJson = (raw) => {
29546
- try {
29547
- return JSON.parse(raw);
29548
- } catch {
29549
- return null;
29550
- }
29551
- };
29552
-
29553
- // src/grokQuota.ts
29397
+ import {
29398
+ requestQuotaJson,
29399
+ clampPercent,
29400
+ asNumber,
29401
+ asObject,
29402
+ asString as asString3,
29403
+ parseJson
29404
+ } from "@ycodium-ai/plugin-api/credential-account";
29554
29405
  var GROK_USAGE_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
29555
29406
  var GROK_ISSUER_PREFIX = "https://auth.x.ai::";
29556
29407
  var AUTH_FILE_NAME2 = "auth.json";
@@ -29565,7 +29416,6 @@ var extractGrokToken = (auth) => {
29565
29416
  }
29566
29417
  return null;
29567
29418
  };
29568
- var clampPercent = (value) => Math.min(100, Math.max(0, value));
29569
29419
  var grokQuotaWindows = (body) => {
29570
29420
  const config2 = asObject(asObject(body)?.["config"]);
29571
29421
  const productUsage = config2?.["productUsage"];
@@ -29584,7 +29434,7 @@ var grokQuotaWindows = (body) => {
29584
29434
  };
29585
29435
  var createGrokUsage = (input2) => {
29586
29436
  const now = input2.now ?? Date.now;
29587
- const authPath = NodePath6.join(input2.homePath, AUTH_FILE_NAME2);
29437
+ const authPath = NodePath5.join(input2.homePath, AUTH_FILE_NAME2);
29588
29438
  const readQuota = async (request) => {
29589
29439
  const baseUrlKey = GROK_CARD.modelConnectivity.baseUrlEnvKey;
29590
29440
  if (baseUrlKey !== void 0 && (input2.environment[baseUrlKey]?.trim() ?? "") !== "") {
@@ -29592,7 +29442,7 @@ var createGrokUsage = (input2) => {
29592
29442
  }
29593
29443
  let token = null;
29594
29444
  try {
29595
- token = extractGrokToken(parseJson(NodeFS3.readFileSync(authPath, "utf8")));
29445
+ token = extractGrokToken(parseJson(NodeFS2.readFileSync(authPath, "utf8")));
29596
29446
  } catch {
29597
29447
  token = null;
29598
29448
  }
@@ -29629,11 +29479,11 @@ var createGrokUsage = (input2) => {
29629
29479
 
29630
29480
  // src/grokTurnUsage.ts
29631
29481
  var USAGE_GRACE_MS = 300;
29632
- var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29482
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29633
29483
  var count = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
29634
29484
  var text = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
29635
29485
  var readModelTotals = (entry) => {
29636
- if (!isRecord9(entry)) return void 0;
29486
+ if (!isRecord8(entry)) return void 0;
29637
29487
  const input2 = count(entry["inputTokens"]);
29638
29488
  const cachedInputTokens = count(entry["cachedReadTokens"]);
29639
29489
  const cacheCreationTokens = count(entry["cacheCreationTokens"]);
@@ -29648,12 +29498,12 @@ var readModelTotals = (entry) => {
29648
29498
  };
29649
29499
  var sumOf = (totals) => totals.uncachedInputTokens + totals.cachedInputTokens + totals.cacheCreationTokens + totals.outputTokens;
29650
29500
  var grokTurnUsageReport = (promptResponse) => {
29651
- const meta3 = isRecord9(promptResponse) ? promptResponse["_meta"] : void 0;
29652
- const usage = isRecord9(meta3) ? meta3["usage"] : void 0;
29653
- if (!isRecord9(meta3) || !isRecord9(usage)) return void 0;
29501
+ const meta3 = isRecord8(promptResponse) ? promptResponse["_meta"] : void 0;
29502
+ const usage = isRecord8(meta3) ? meta3["usage"] : void 0;
29503
+ if (!isRecord8(meta3) || !isRecord8(usage)) return void 0;
29654
29504
  const perModel = /* @__PURE__ */ new Map();
29655
29505
  const modelUsage = usage["modelUsage"];
29656
- if (isRecord9(modelUsage)) {
29506
+ if (isRecord8(modelUsage)) {
29657
29507
  for (const [model, entry] of Object.entries(modelUsage)) {
29658
29508
  const totals = readModelTotals(entry);
29659
29509
  if (totals !== void 0 && model.trim().length > 0) perModel.set(model.trim(), totals);
@@ -29731,13 +29581,13 @@ var createGrokTurnUsageCollector = (base) => {
29731
29581
  }
29732
29582
  };
29733
29583
  const attach = async (event) => {
29734
- if (event.type !== "turn.completed" || !isRecord9(event.payload)) return event;
29584
+ if (event.type !== "turn.completed" || !isRecord8(event.payload)) return event;
29735
29585
  if (event.payload["state"] === "completed" && !allAnswered()) {
29736
- await new Promise((resolve4) => {
29737
- const timer = setTimeout(resolve4, USAGE_GRACE_MS);
29586
+ await new Promise((resolve2) => {
29587
+ const timer = setTimeout(resolve2, USAGE_GRACE_MS);
29738
29588
  wake = () => {
29739
29589
  clearTimeout(timer);
29740
- resolve4();
29590
+ resolve2();
29741
29591
  };
29742
29592
  });
29743
29593
  wake = void 0;
@@ -29761,16 +29611,16 @@ var XAI_EXIT_PLAN_MODE_METHODS = [
29761
29611
  var GROK_PLAN_APPROVE_OPTION_ID = "approved";
29762
29612
  var GROK_PLAN_ABANDON_OPTION_ID = "abandoned";
29763
29613
  var GROK_EMPTY_PLAN_TEXT = "The agent exited plan mode without writing a plan.";
29764
- var isRecord10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29614
+ var isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29765
29615
  var trimmed = (value) => {
29766
29616
  if (typeof value !== "string") return void 0;
29767
29617
  const text4 = value.trim();
29768
29618
  return text4.length > 0 ? text4 : void 0;
29769
29619
  };
29770
29620
  function parseXAiExitPlanModeParams(params) {
29771
- const candidates = [params, ...isRecord10(params) ? [params["params"]] : []];
29621
+ const candidates = [params, ...isRecord9(params) ? [params["params"]] : []];
29772
29622
  for (const candidate of candidates) {
29773
- if (!isRecord10(candidate)) continue;
29623
+ if (!isRecord9(candidate)) continue;
29774
29624
  const toolCallId = trimmed(candidate["toolCallId"]);
29775
29625
  if (toolCallId === void 0) continue;
29776
29626
  return { toolCallId, planContent: trimmed(candidate["planContent"]) };
@@ -29822,7 +29672,7 @@ function makeXAiExitPlanModeResponse(params, resolution) {
29822
29672
  import { REASONING_OPTION_LABEL, reasoningEffortShortLabel } from "@ycodium-ai/plugin-api/executor";
29823
29673
 
29824
29674
  // src/grokJson.ts
29825
- var isRecord11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29675
+ var isRecord10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29826
29676
  var trimmed2 = (value) => {
29827
29677
  if (typeof value !== "string") return void 0;
29828
29678
  const text4 = value.trim();
@@ -29832,11 +29682,11 @@ var trimmed2 = (value) => {
29832
29682
  // src/grokReasoningEffort.ts
29833
29683
  var GROK_REASONING_OPTION_ID = "reasoningEffort";
29834
29684
  function grokReasoningEffortDescriptor(modelMeta) {
29835
- if (!isRecord11(modelMeta) || modelMeta["supportsReasoningEffort"] !== true) return void 0;
29685
+ if (!isRecord10(modelMeta) || modelMeta["supportsReasoningEffort"] !== true) return void 0;
29836
29686
  const table = modelMeta["reasoningEfforts"];
29837
29687
  if (!Array.isArray(table)) return void 0;
29838
29688
  const options = table.flatMap((entry) => {
29839
- if (!isRecord11(entry)) return [];
29689
+ if (!isRecord10(entry)) return [];
29840
29690
  const value = trimmed2(entry["value"]) ?? trimmed2(entry["id"]);
29841
29691
  if (value === void 0) return [];
29842
29692
  const description = trimmed2(entry["description"]);
@@ -29861,23 +29711,23 @@ function grokReasoningEffortDescriptor(modelMeta) {
29861
29711
  };
29862
29712
  }
29863
29713
  function grokReasoningEffortKnown(modelMeta) {
29864
- if (!isRecord11(modelMeta)) return "unknown";
29714
+ if (!isRecord10(modelMeta)) return "unknown";
29865
29715
  if (modelMeta["supportsReasoningEffort"] === false) return "none";
29866
29716
  if (modelMeta["supportsReasoningEffort"] !== true) return "unknown";
29867
29717
  const table = modelMeta["reasoningEfforts"];
29868
29718
  if (!Array.isArray(table)) return "unknown";
29869
29719
  const readable = table.every(
29870
- (entry) => isRecord11(entry) && (trimmed2(entry["value"]) ?? trimmed2(entry["id"])) !== void 0
29720
+ (entry) => isRecord10(entry) && (trimmed2(entry["value"]) ?? trimmed2(entry["id"])) !== void 0
29871
29721
  );
29872
29722
  if (!readable) return "unknown";
29873
29723
  return table.length === 0 ? "none" : "listed";
29874
29724
  }
29875
29725
  function grokModelDefaultEffort(input2) {
29876
- const models = isRecord11(input2.setup) ? input2.setup["models"] : void 0;
29877
- const available = isRecord11(models) ? models["availableModels"] : void 0;
29726
+ const models = isRecord10(input2.setup) ? input2.setup["models"] : void 0;
29727
+ const available = isRecord10(models) ? models["availableModels"] : void 0;
29878
29728
  if (!Array.isArray(available)) return void 0;
29879
- const model = available.find((entry) => isRecord11(entry) && entry["modelId"] === input2.modelId);
29880
- const current = isRecord11(model) ? grokReasoningEffortDescriptor(model["_meta"])?.currentValue : void 0;
29729
+ const model = available.find((entry) => isRecord10(entry) && entry["modelId"] === input2.modelId);
29730
+ const current = isRecord10(model) ? grokReasoningEffortDescriptor(model["_meta"])?.currentValue : void 0;
29881
29731
  return typeof current === "string" ? current : void 0;
29882
29732
  }
29883
29733
  function grokReasoningEffortArgs(effort) {
@@ -30036,7 +29886,7 @@ var NOTIFICATION_METHODS = /* @__PURE__ */ new Set([
30036
29886
  "x.ai/session/update"
30037
29887
  ]);
30038
29888
  var isGrokSessionNotification = (method) => NOTIFICATION_METHODS.has(method.startsWith("_") ? method.slice(1) : method);
30039
- var record3 = (value) => isRecord11(value) ? value : {};
29889
+ var record3 = (value) => isRecord10(value) ? value : {};
30040
29890
  var text3 = trimmed2;
30041
29891
  var count2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
30042
29892
  var replyText = (value) => {
@@ -30324,7 +30174,7 @@ function createGrokRetryNotices() {
30324
30174
  let phase;
30325
30175
  return {
30326
30176
  observe: (envelope, ctx) => {
30327
- if (!isRecord11(envelope) || !isRecord11(envelope["update"])) return [];
30177
+ if (!isRecord10(envelope) || !isRecord10(envelope["update"])) return [];
30328
30178
  if (ctx.sessionId === void 0 || envelope["sessionId"] !== ctx.sessionId) return [];
30329
30179
  const update = envelope["update"];
30330
30180
  if (update["sessionUpdate"] !== "retry_state") {
@@ -30335,7 +30185,7 @@ function createGrokRetryNotices() {
30335
30185
  phase = void 0;
30336
30186
  return [];
30337
30187
  }
30338
- const meta3 = isRecord11(envelope["_meta"]) ? envelope["_meta"] : {};
30188
+ const meta3 = isRecord10(envelope["_meta"]) ? envelope["_meta"] : {};
30339
30189
  if (meta3["isReplay"] === true) return [];
30340
30190
  const turnId = ctx.turnId;
30341
30191
  if (turnId === void 0) return [];
@@ -30374,7 +30224,7 @@ function createGrokRetryNotices() {
30374
30224
  }
30375
30225
 
30376
30226
  // src/grokSupport.ts
30377
- import { modelSelectionStringOption as modelSelectionStringOption3 } from "@ycodium-ai/plugin-api/executor";
30227
+ import { modelSelectionStringOption as modelSelectionStringOption2 } from "@ycodium-ai/plugin-api/executor";
30378
30228
  var GROK_NATIVE_MODE_BY_RUNTIME_MODE = {
30379
30229
  "approval-required": "default",
30380
30230
  "auto-accept-edits": "auto",
@@ -30479,28 +30329,28 @@ function grokRuntimeModeCaveat(nativeModeId) {
30479
30329
  };
30480
30330
  }
30481
30331
  function resolveGrokAuthMethodId(initializeResult) {
30482
- const authMethods = isRecord11(initializeResult) ? initializeResult["authMethods"] : void 0;
30332
+ const authMethods = isRecord10(initializeResult) ? initializeResult["authMethods"] : void 0;
30483
30333
  if (!Array.isArray(authMethods)) return void 0;
30484
30334
  for (const method of authMethods) {
30485
- if (isRecord11(method) && method["id"] === "cached_token") return "cached_token";
30335
+ if (isRecord10(method) && method["id"] === "cached_token") return "cached_token";
30486
30336
  }
30487
30337
  return void 0;
30488
30338
  }
30489
30339
  var positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : void 0;
30490
30340
  function grokPromptUsage(promptResponse) {
30491
- if (!isRecord11(promptResponse)) return void 0;
30341
+ if (!isRecord10(promptResponse)) return void 0;
30492
30342
  const meta3 = promptResponse["_meta"];
30493
- if (!isRecord11(meta3)) return void 0;
30343
+ if (!isRecord10(meta3)) return void 0;
30494
30344
  const usedTokens = positive(meta3["totalTokens"]);
30495
30345
  if (usedTokens === void 0) return void 0;
30496
30346
  return { usedTokens, modelId: trimmed2(meta3["modelId"]) };
30497
30347
  }
30498
30348
  function grokModelState(initializeResult) {
30499
- if (!isRecord11(initializeResult)) return void 0;
30349
+ if (!isRecord10(initializeResult)) return void 0;
30500
30350
  const meta3 = initializeResult["_meta"];
30501
- if (!isRecord11(meta3)) return void 0;
30351
+ if (!isRecord10(meta3)) return void 0;
30502
30352
  const modelState = meta3["modelState"];
30503
- if (!isRecord11(modelState)) return void 0;
30353
+ if (!isRecord10(modelState)) return void 0;
30504
30354
  const availableModels = modelState["availableModels"];
30505
30355
  if (!Array.isArray(availableModels)) return void 0;
30506
30356
  return { currentModelId: trimmed2(modelState["currentModelId"]), availableModels };
@@ -30510,11 +30360,11 @@ function grokAdvertisedModels(initializeResult) {
30510
30360
  if (state === void 0) return [];
30511
30361
  const models = [];
30512
30362
  for (const entry of state.availableModels) {
30513
- if (!isRecord11(entry)) continue;
30363
+ if (!isRecord10(entry)) continue;
30514
30364
  const modelId = trimmed2(entry["modelId"]);
30515
30365
  if (modelId === void 0) continue;
30516
30366
  const modelMeta = entry["_meta"];
30517
- const contextWindow = isRecord11(modelMeta) ? positive(modelMeta["totalContextTokens"]) : void 0;
30367
+ const contextWindow = isRecord10(modelMeta) ? positive(modelMeta["totalContextTokens"]) : void 0;
30518
30368
  models.push({
30519
30369
  modelId,
30520
30370
  name: trimmed2(entry["name"]),
@@ -30531,7 +30381,7 @@ var XAI_ASK_USER_QUESTION_METHODS = [
30531
30381
  "x.ai/ask_user_question"
30532
30382
  ];
30533
30383
  var readOption = (value) => {
30534
- if (!isRecord11(value)) return void 0;
30384
+ if (!isRecord10(value)) return void 0;
30535
30385
  const label = typeof value["label"] === "string" ? value["label"] : void 0;
30536
30386
  if (label === void 0) return void 0;
30537
30387
  return {
@@ -30542,7 +30392,7 @@ var readOption = (value) => {
30542
30392
  };
30543
30393
  };
30544
30394
  var readQuestion = (value) => {
30545
- if (!isRecord11(value)) return void 0;
30395
+ if (!isRecord10(value)) return void 0;
30546
30396
  const question = typeof value["question"] === "string" ? value["question"] : void 0;
30547
30397
  if (question === void 0) return void 0;
30548
30398
  const optionsRaw = value["options"];
@@ -30558,9 +30408,9 @@ var readQuestion = (value) => {
30558
30408
  };
30559
30409
  };
30560
30410
  function parseXAiAskUserQuestionParams(params) {
30561
- const candidates = [params, ...isRecord11(params) ? [params["params"]] : []];
30411
+ const candidates = [params, ...isRecord10(params) ? [params["params"]] : []];
30562
30412
  for (const candidate of candidates) {
30563
- if (!isRecord11(candidate)) continue;
30413
+ if (!isRecord10(candidate)) continue;
30564
30414
  const questionsRaw = candidate["questions"];
30565
30415
  if (!Array.isArray(questionsRaw)) continue;
30566
30416
  const questions = questionsRaw.flatMap((entry) => {
@@ -30635,21 +30485,21 @@ var XAI_PROMPT_COMPLETE_METHOD = "_x.ai/session/prompt_complete";
30635
30485
  var GROK_RATE_LIMIT_MESSAGE = "Grok usage limit reached or rate limited. Try again later.";
30636
30486
  var grokAgentResultMessage = (value) => {
30637
30487
  if (typeof value === "string") return trimmed2(value);
30638
- return isRecord11(value) ? trimmed2(value["message"]) : void 0;
30488
+ return isRecord10(value) ? trimmed2(value["message"]) : void 0;
30639
30489
  };
30640
30490
  var grokPromptSettlement = {
30641
30491
  // 关联 id 双写 promptId 与 requestId(宿主 XAiAcpExtension 同款):
30642
30492
  // agent 认回哪个键是它的事,两个都给才不猜版本。
30643
30493
  requestFields: (promptKey) => ({ _meta: { promptId: promptKey, requestId: promptKey } }),
30644
30494
  responseKey: (response) => {
30645
- if (!isRecord11(response)) return void 0;
30495
+ if (!isRecord10(response)) return void 0;
30646
30496
  const meta3 = response["_meta"];
30647
- if (!isRecord11(meta3)) return void 0;
30497
+ if (!isRecord10(meta3)) return void 0;
30648
30498
  return trimmed2(meta3["promptId"]) ?? trimmed2(meta3["requestId"]);
30649
30499
  },
30650
30500
  fromNotification: (method, params) => {
30651
30501
  if (method !== XAI_PROMPT_COMPLETE_METHOD) return void 0;
30652
- if (!isRecord11(params)) return void 0;
30502
+ if (!isRecord10(params)) return void 0;
30653
30503
  const sessionId = params["sessionId"];
30654
30504
  if (typeof sessionId !== "string") return void 0;
30655
30505
  const stopReason = trimmed2(params["stopReason"]);
@@ -30669,11 +30519,11 @@ var grokPromptSettlement = {
30669
30519
 
30670
30520
  // src/grokSkills.ts
30671
30521
  import * as NodeOS4 from "node:os";
30672
- import * as NodePath7 from "node:path";
30522
+ import * as NodePath6 from "node:path";
30673
30523
  var INSPECT_TIMEOUT_MS = 15e3;
30674
30524
  var MAX_INSPECT_OUTPUT_BYTES = 4 * 1024 * 1024;
30675
30525
  var GROK_INSPECT_ARGS = ["inspect", "--json"];
30676
- var isRecord12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30526
+ var isRecord11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30677
30527
  var trimmedString = (value) => typeof value === "string" ? value.trim() : "";
30678
30528
  function parseGrokInspectSkills(stdout) {
30679
30529
  let parsed;
@@ -30682,13 +30532,13 @@ function parseGrokInspectSkills(stdout) {
30682
30532
  } catch {
30683
30533
  return [];
30684
30534
  }
30685
- const entries = isRecord12(parsed) ? parsed["skills"] : void 0;
30535
+ const entries = isRecord11(parsed) ? parsed["skills"] : void 0;
30686
30536
  if (!Array.isArray(entries)) return [];
30687
30537
  const byName = /* @__PURE__ */ new Map();
30688
30538
  for (const entry of entries) {
30689
- if (!isRecord12(entry)) continue;
30539
+ if (!isRecord11(entry)) continue;
30690
30540
  const name = trimmedString(entry["name"]);
30691
- const source = isRecord12(entry["source"]) ? entry["source"] : void 0;
30541
+ const source = isRecord11(entry["source"]) ? entry["source"] : void 0;
30692
30542
  const path = trimmedString(source?.["path"]);
30693
30543
  if (name.length === 0 || path.length === 0) continue;
30694
30544
  const scope = trimmedString(source?.["type"]);
@@ -30722,7 +30572,7 @@ var runGrokInspect = async (input2) => {
30722
30572
  throw new Error(`grok inspect exited with ${String(run.exitCode)}`);
30723
30573
  }
30724
30574
  const parsed = JSON.parse(run.stdout);
30725
- if (!isRecord12(parsed) || !Array.isArray(parsed["skills"])) {
30575
+ if (!isRecord11(parsed) || !Array.isArray(parsed["skills"])) {
30726
30576
  throw new Error("grok inspect output has no skills list");
30727
30577
  }
30728
30578
  return parseGrokInspectSkills(run.stdout);
@@ -30738,14 +30588,14 @@ async function inspectGrokWorkspace(input2) {
30738
30588
  const skills = await runGrokInspect(input2);
30739
30589
  const watched = /* @__PURE__ */ new Set([
30740
30590
  // 项目技能目录的位置没有实测,这两处只是触发重查的提示,不影响答案本身。
30741
- NodePath7.join(input2.cwd, ".grok", "skills"),
30742
- NodePath7.join(input2.cwd, ".agents", "skills")
30591
+ NodePath6.join(input2.cwd, ".grok", "skills"),
30592
+ NodePath6.join(input2.cwd, ".agents", "skills")
30743
30593
  ]);
30744
30594
  for (const skill of skills) {
30745
30595
  watched.add(skill.path);
30746
- const skillDirectory = NodePath7.dirname(skill.path);
30596
+ const skillDirectory = NodePath6.dirname(skill.path);
30747
30597
  watched.add(skillDirectory);
30748
- watched.add(NodePath7.dirname(skillDirectory));
30598
+ watched.add(NodePath6.dirname(skillDirectory));
30749
30599
  }
30750
30600
  return { skills, watchPaths: [...watched] };
30751
30601
  }
@@ -30799,71 +30649,23 @@ function grokOpenCommands(session) {
30799
30649
 
30800
30650
  // src/modelCacheRefresh.ts
30801
30651
  import {
30802
- runProcessOperation as runProcessOperation2,
30803
- OperationCleanupError as OperationCleanupError2
30652
+ runProcessOperation,
30653
+ isOperationCleanupError
30804
30654
  } from "@ycodium-ai/plugin-api/process-operation";
30805
- import * as NodeFS4 from "node:fs";
30806
- import * as NodePath8 from "node:path";
30655
+ import * as NodeFS3 from "node:fs";
30656
+ import * as NodePath7 from "node:path";
30807
30657
  import {
30808
- ExecutorSpawnAbortedError as ExecutorSpawnAbortedError2,
30809
- ExecutorSpawnRefusedError as ExecutorSpawnRefusedError2,
30658
+ ExecutorSpawnAbortedError,
30659
+ ExecutorSpawnRefusedError,
30810
30660
  throwIfExecutorSpawnAborted
30811
30661
  } from "@ycodium-ai/plugin-api/executor";
30812
30662
 
30813
30663
  // src/probeModels.ts
30814
30664
  import {
30815
- raceAbort as raceAbort3
30816
- } from "@ycodium-ai/plugin-api/executor";
30817
- import { nodeStreamsFromHandle as nodeStreamsFromHandle2 } from "@ycodium-ai/plugin-api/process-stdin";
30818
-
30819
- // ../../packages/ycodium-instance-config/src/probeProcess.ts
30820
- import {
30821
- describeExecutorSpawnFailure,
30822
- ExecutorSpawnAbortedError,
30823
- ExecutorSpawnRefusedError
30824
- } from "@ycodium-ai/plugin-api/executor";
30825
- import {
30826
- OperationCleanupError,
30827
- runProcessOperation
30828
- } from "@ycodium-ai/plugin-api/process-operation";
30829
- async function spawnProbeProcess(host, launch) {
30830
- try {
30831
- const handle = await host.process.spawn({
30832
- program: launch.program,
30833
- args: launch.args,
30834
- cwd: launch.cwd,
30835
- owner: { bindingId: host.bindingId },
30836
- ...Object.keys(launch.env).length > 0 ? { env: launch.env } : {},
30837
- ...launch.signal === void 0 ? {} : { signal: launch.signal }
30838
- });
30839
- return { kind: "spawned", handle };
30840
- } catch (error62) {
30841
- if (error62 instanceof ExecutorSpawnRefusedError || error62 instanceof ExecutorSpawnAbortedError) {
30842
- throw error62;
30843
- }
30844
- return { kind: "not-started", ...describeExecutorSpawnFailure(error62) };
30845
- }
30846
- }
30847
- async function readCliVersionCommand(host, input2) {
30848
- try {
30849
- const run = await runProcessOperation(host, {
30850
- program: input2.program,
30851
- args: ["--version"],
30852
- owner: { bindingId: host.bindingId },
30853
- ...Object.keys(input2.env).length > 0 ? { env: input2.env } : {},
30854
- signal: input2.signal,
30855
- timeoutMs: input2.timeoutMs,
30856
- maxOutputBytes: 64 * 1024
30857
- });
30858
- if (run.exitCode !== 0) return null;
30859
- return input2.parse(run.stdout) ?? input2.parse(run.stderr);
30860
- } catch (error62) {
30861
- if (error62 instanceof OperationCleanupError || input2.signal?.aborted) throw error62;
30862
- return null;
30863
- }
30864
- }
30865
-
30866
- // src/probeModels.ts
30665
+ tokenizeShellWords,
30666
+ readCliVersionCommand,
30667
+ spawnProbeProcess
30668
+ } from "@ycodium-ai/plugin-api/instance-config";
30867
30669
  var PROBE_REQUEST_TIMEOUT_MS = 2e4;
30868
30670
  function grokProbeModels(initializeResult) {
30869
30671
  if (grokModelState(initializeResult) === void 0) return void 0;
@@ -30881,34 +30683,24 @@ function grokProbeModels(initializeResult) {
30881
30683
  }
30882
30684
  async function probeGrokModels(input2) {
30883
30685
  const { recipe, host, env } = input2;
30884
- const spawned = await spawnProbeProcess(host, {
30885
- program: recipe.binaryPath,
30886
- args: tokenizeShellWords(recipe.launchArgs),
30686
+ const attempt = await runAcpProbeProcess({
30887
30687
  cwd: process.cwd(),
30888
- env,
30889
- ...input2.signal === void 0 ? {} : { signal: input2.signal }
30688
+ signal: input2.signal,
30689
+ clientInfo: GROK_CLIENT_INFO,
30690
+ requestTimeoutMs: PROBE_REQUEST_TIMEOUT_MS,
30691
+ spawn: (cwd) => spawnProbeProcess(host, {
30692
+ program: recipe.binaryPath,
30693
+ args: tokenizeShellWords(recipe.launchArgs),
30694
+ cwd,
30695
+ env,
30696
+ ...input2.signal === void 0 ? {} : { signal: input2.signal }
30697
+ }),
30698
+ run: async (handshake) => grokProbeModels(handshake.initializeResult)
30890
30699
  });
30891
- if (spawned.kind === "not-started") return spawned;
30892
- const { handle } = spawned;
30893
- let handshake;
30894
- try {
30895
- const { readable, writable } = nodeStreamsFromHandle2(handle);
30896
- handshake = await raceAbort3(
30897
- openAcpProbeHandshake({
30898
- readable,
30899
- writable,
30900
- clientInfo: GROK_CLIENT_INFO,
30901
- requestTimeoutMs: PROBE_REQUEST_TIMEOUT_MS
30902
- }),
30903
- input2.signal
30904
- );
30905
- return { kind: "answered", models: grokProbeModels(handshake.initializeResult) };
30906
- } catch (error62) {
30907
- return { kind: "failed", detail: acpProbeFailureDetail(error62) };
30908
- } finally {
30909
- await handshake?.close().catch(() => void 0);
30910
- await handle.kill("SIGTERM").catch(() => void 0);
30911
- }
30700
+ if (attempt.kind === "not-started") return attempt;
30701
+ if (attempt.kind === "threw")
30702
+ return { kind: "failed", detail: acpProbeFailureDetail(attempt.error) };
30703
+ return { kind: "answered", models: attempt.value };
30912
30704
  }
30913
30705
  async function probeGrokVersion(input2) {
30914
30706
  const { recipe, host, env, signal } = input2;
@@ -30926,11 +30718,11 @@ var GROK_MODEL_CACHE_FILE = "models_cache.json";
30926
30718
  var GROK_MODEL_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
30927
30719
  var GROK_MODELS_COMMAND_TIMEOUT_MS = 6e4;
30928
30720
  function grokModelCachePath(accountHome) {
30929
- return NodePath8.join(accountHome, GROK_MODEL_CACHE_FILE);
30721
+ return NodePath7.join(accountHome, GROK_MODEL_CACHE_FILE);
30930
30722
  }
30931
30723
  function readGrokModelCacheMtimeMs(accountHome) {
30932
30724
  try {
30933
- return NodeFS4.statSync(grokModelCachePath(accountHome)).mtimeMs;
30725
+ return NodeFS3.statSync(grokModelCachePath(accountHome)).mtimeMs;
30934
30726
  } catch {
30935
30727
  return null;
30936
30728
  }
@@ -30945,7 +30737,7 @@ async function runGrokModelsCommand(input2) {
30945
30737
  const { recipe, host, env } = input2;
30946
30738
  throwIfExecutorSpawnAborted(input2.signal);
30947
30739
  try {
30948
- const run = await runProcessOperation2(host, {
30740
+ const run = await runProcessOperation(host, {
30949
30741
  program: recipe.binaryPath,
30950
30742
  args: ["models"],
30951
30743
  cwd: process.cwd(),
@@ -30962,10 +30754,10 @@ async function runGrokModelsCommand(input2) {
30962
30754
  }
30963
30755
  return true;
30964
30756
  } catch (error62) {
30965
- if (error62 instanceof ExecutorSpawnAbortedError2 || error62 instanceof OperationCleanupError2 || input2.signal?.aborted)
30757
+ if (error62 instanceof ExecutorSpawnAbortedError || isOperationCleanupError(error62) || input2.signal?.aborted)
30966
30758
  throw error62;
30967
30759
  host.log.warn("grok models failed; keeping the previous model list", {
30968
- detail: error62 instanceof ExecutorSpawnRefusedError2 ? "process limit" : String(error62)
30760
+ detail: error62 instanceof ExecutorSpawnRefusedError ? "process limit" : String(error62)
30969
30761
  });
30970
30762
  return false;
30971
30763
  }
@@ -30984,6 +30776,7 @@ function runCoalescedModelsCommand(cachePath, force, run) {
30984
30776
  if (modelsCommandSlots.get(cachePath)?.followUp === followUp) {
30985
30777
  modelsCommandSlots.delete(cachePath);
30986
30778
  }
30779
+ }).catch(() => {
30987
30780
  });
30988
30781
  return followUp;
30989
30782
  }
@@ -30995,6 +30788,7 @@ function runCoalescedModelsCommand(cachePath, force, run) {
30995
30788
  void current.finally(() => {
30996
30789
  if (slot.followUp !== void 0) return;
30997
30790
  if (modelsCommandSlots.get(cachePath) === slot) modelsCommandSlots.delete(cachePath);
30791
+ }).catch(() => {
30998
30792
  });
30999
30793
  return current;
31000
30794
  }
@@ -31045,7 +30839,7 @@ function createGrokModelCatalog(input2) {
31045
30839
  throw new Error("grok models failed");
31046
30840
  }
31047
30841
  } catch (error62) {
31048
- if (error62 instanceof ExecutorSpawnAbortedError2 || error62 instanceof OperationCleanupError2 || request.signal?.aborted)
30842
+ if (error62 instanceof ExecutorSpawnAbortedError || isOperationCleanupError(error62) || request.signal?.aborted)
31049
30843
  throw error62;
31050
30844
  if (request.surfaceErrors === true) throw error62;
31051
30845
  input2.host.log.warn("grok model cache refresh failed; keeping the previous model list", {
@@ -31058,8 +30852,8 @@ function createGrokModelCatalog(input2) {
31058
30852
  }
31059
30853
 
31060
30854
  // src/grokFollowUpSteer.ts
31061
- import * as NodeFS5 from "node:fs";
31062
- import * as NodePath9 from "node:path";
30855
+ import * as NodeFS4 from "node:fs";
30856
+ import * as NodePath8 from "node:path";
31063
30857
  var SETTING = 'follow_up_behavior = "steer"';
31064
30858
  function grokFollowUpSteerIsOn(text4) {
31065
30859
  const lines = text4.split(/\r?\n/).map((line) => line.trim());
@@ -31073,21 +30867,21 @@ function grokFollowUpSteerIsOn(text4) {
31073
30867
  return false;
31074
30868
  }
31075
30869
  function ensureGrokFollowUpSteer(homePath) {
31076
- const path = NodePath9.join(homePath, "config.toml");
30870
+ const path = NodePath8.join(homePath, "config.toml");
31077
30871
  try {
31078
- return grokFollowUpSteerIsOn(NodeFS5.readFileSync(path, "utf8")) ? "on" : "off";
30872
+ return grokFollowUpSteerIsOn(NodeFS4.readFileSync(path, "utf8")) ? "on" : "off";
31079
30873
  } catch (error62) {
31080
30874
  if (error62.code !== "ENOENT") throw error62;
31081
30875
  }
31082
- NodeFS5.mkdirSync(homePath, { recursive: true });
30876
+ NodeFS4.mkdirSync(homePath, { recursive: true });
31083
30877
  try {
31084
- NodeFS5.writeFileSync(path, `[ui]
30878
+ NodeFS4.writeFileSync(path, `[ui]
31085
30879
  ${SETTING}
31086
30880
  `, { encoding: "utf8", flag: "wx" });
31087
30881
  return "created";
31088
30882
  } catch (error62) {
31089
30883
  if (error62.code !== "EEXIST") throw error62;
31090
- return grokFollowUpSteerIsOn(NodeFS5.readFileSync(path, "utf8")) ? "on" : "off";
30884
+ return grokFollowUpSteerIsOn(NodeFS4.readFileSync(path, "utf8")) ? "on" : "off";
31091
30885
  }
31092
30886
  }
31093
30887
  function prepareGrokFollowUpSteer(homePath, log, threadId) {
@@ -31123,15 +30917,23 @@ var grokPermissionStatement = ({
31123
30917
  };
31124
30918
 
31125
30919
  // src/nativeSessions.ts
31126
- import * as NodeFS6 from "node:fs";
30920
+ import * as NodeFS5 from "node:fs";
31127
30921
  import * as NodeFSP from "node:fs/promises";
31128
- import * as NodePath10 from "node:path";
30922
+ import * as NodePath9 from "node:path";
31129
30923
  import * as NodeReadline from "node:readline";
30924
+ import {
30925
+ directoryKey,
30926
+ isAbsoluteDirectory,
30927
+ matchesSessionDirectory,
30928
+ readableStoragePath,
30929
+ inputPayload as inputPayload2,
30930
+ outputPayload as outputPayload2
30931
+ } from "@ycodium-ai/plugin-api/session-history";
31130
30932
  var sessionIdPattern = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/iu;
31131
30933
  function parseRecord(raw) {
31132
30934
  try {
31133
30935
  const value = JSON.parse(raw);
31134
- return isRecord11(value) ? value : void 0;
30936
+ return isRecord10(value) ? value : void 0;
31135
30937
  } catch {
31136
30938
  return void 0;
31137
30939
  }
@@ -31147,48 +30949,34 @@ async function directories(path) {
31147
30949
  throw error62;
31148
30950
  }
31149
30951
  }
31150
- function readableStoragePath(home) {
31151
- try {
31152
- return NodeFS6.realpathSync.native(home);
31153
- } catch {
31154
- return home;
31155
- }
31156
- }
31157
- function isAbsoluteDirectory(path) {
31158
- if (!NodePath10.isAbsolute(path)) return false;
31159
- if (NodePath10.sep !== "\\") return true;
31160
- const { root } = NodePath10.parse(path);
31161
- return root.length > 1;
31162
- }
31163
- var directoryKey = (directory) => {
31164
- const resolved = NodePath10.resolve(directory);
31165
- return NodePath10.sep === "\\" ? resolved.toLowerCase() : resolved;
31166
- };
31167
30952
  async function findSessions(home, cwd, signal, nativeSessionId) {
31168
30953
  signal?.throwIfAborted();
31169
30954
  const expectedCwd = directoryKey(cwd);
31170
30955
  const result = [];
31171
- const root = NodePath10.join(home, "sessions");
30956
+ const root = NodePath9.join(home, "sessions");
31172
30957
  for (const workspace of await directories(root)) {
31173
- const workspacePath = NodePath10.join(root, workspace);
30958
+ const workspacePath = NodePath9.join(root, workspace);
31174
30959
  for (const id of await directories(workspacePath)) {
31175
30960
  signal?.throwIfAborted();
31176
30961
  if (!sessionIdPattern.test(id) || nativeSessionId !== void 0 && nativeSessionId !== id)
31177
30962
  continue;
31178
- const sessionPath = NodePath10.join(workspacePath, id);
31179
- const summaryPath = NodePath10.join(sessionPath, "summary.json");
30963
+ const sessionPath = NodePath9.join(workspacePath, id);
30964
+ const summaryPath = NodePath9.join(sessionPath, "summary.json");
31180
30965
  try {
31181
30966
  if (!(await NodeFSP.lstat(summaryPath)).isFile()) continue;
31182
30967
  const summary = parseRecord(
31183
30968
  await NodeFSP.readFile(summaryPath, { encoding: "utf8", signal })
31184
30969
  );
31185
30970
  const info = summary?.info;
31186
- if (!summary || !isRecord11(info) || info.id !== id || typeof info.cwd !== "string" || !isAbsoluteDirectory(info.cwd))
30971
+ if (!summary || !isRecord10(info) || info.id !== id || typeof info.cwd !== "string" || !isAbsoluteDirectory(info.cwd))
31187
30972
  continue;
31188
- const relative2 = NodePath10.relative(expectedCwd, directoryKey(info.cwd));
31189
- if (relative2 !== "" && (nativeSessionId !== void 0 || relative2 === ".." || relative2.startsWith(`..${NodePath10.sep}`) || NodePath10.isAbsolute(relative2)))
30973
+ if (!matchesSessionDirectory(
30974
+ expectedCwd,
30975
+ info.cwd,
30976
+ nativeSessionId === void 0 ? "scan" : "read"
30977
+ ))
31190
30978
  continue;
31191
- const updates = NodePath10.join(sessionPath, "updates.jsonl");
30979
+ const updates = NodePath9.join(sessionPath, "updates.jsonl");
31192
30980
  if (!(await NodeFSP.lstat(updates)).isFile()) continue;
31193
30981
  const updatedAt = Date.parse(trimmed2(summary.updated_at) ?? "");
31194
30982
  result.push({
@@ -31211,12 +30999,12 @@ async function findSessions(home, cwd, signal, nativeSessionId) {
31211
30999
  function toolOutput(content) {
31212
31000
  if (!Array.isArray(content)) return void 0;
31213
31001
  const output2 = content.flatMap(
31214
- (entry) => isRecord11(entry) && isRecord11(entry.content) && entry.content.type === "text" && typeof entry.content.text === "string" ? [entry.content.text] : []
31002
+ (entry) => isRecord10(entry) && isRecord10(entry.content) && entry.content.type === "text" && typeof entry.content.text === "string" ? [entry.content.text] : []
31215
31003
  ).join("\n");
31216
31004
  return output2.length === 0 ? void 0 : output2;
31217
31005
  }
31218
31006
  async function readTranscript(session, signal, summaryOnly = false) {
31219
- const stream = NodeFS6.createReadStream(session.updates, { signal });
31007
+ const stream = NodeFS5.createReadStream(session.updates, { signal });
31220
31008
  const lines = NodeReadline.createInterface({ input: stream, crlfDelay: Infinity });
31221
31009
  const messages = [];
31222
31010
  const activities = [];
@@ -31234,11 +31022,11 @@ async function readTranscript(session, signal, summaryOnly = false) {
31234
31022
  signal?.throwIfAborted();
31235
31023
  sourceOrder += 1;
31236
31024
  const row = parseRecord(line);
31237
- if (!row || !isRecord11(row.params) || row.params.sessionId !== session.id) continue;
31025
+ if (!row || !isRecord10(row.params) || row.params.sessionId !== session.id) continue;
31238
31026
  const { update, _meta: metadata } = row.params;
31239
- if (!isRecord11(update)) continue;
31240
- const updateMetadata = isRecord11(update._meta) ? update._meta : void 0;
31241
- const eventId = isRecord11(metadata) ? trimmed2(metadata.eventId) : void 0;
31027
+ if (!isRecord10(update)) continue;
31028
+ const updateMetadata = isRecord10(update._meta) ? update._meta : void 0;
31029
+ const eventId = isRecord10(metadata) ? trimmed2(metadata.eventId) : void 0;
31242
31030
  const sourceId = eventId ?? `update:${sourceOrder}`;
31243
31031
  const timestamp = typeof row.timestamp_us === "number" ? row.timestamp_us / 1e3 : typeof row.timestamp === "number" ? row.timestamp * 1e3 : session.updatedAt;
31244
31032
  const createdAt = new Date(Math.abs(timestamp) <= 864e13 ? timestamp : 0).toISOString();
@@ -31260,7 +31048,7 @@ async function readTranscript(session, signal, summaryOnly = false) {
31260
31048
  };
31261
31049
  if (role !== void 0) {
31262
31050
  const content = update.content;
31263
- if (!isRecord11(content) || content.type !== "text" || typeof content.text !== "string" || content.text.length === 0)
31051
+ if (!isRecord10(content) || content.type !== "text" || typeof content.text !== "string" || content.text.length === 0)
31264
31052
  continue;
31265
31053
  hasMessages = true;
31266
31054
  const continuing = previous?.role === role && previous.nativeTurnId === nativeTurnId;
@@ -31284,8 +31072,8 @@ async function readTranscript(session, signal, summaryOnly = false) {
31284
31072
  if (summaryOnly) continue;
31285
31073
  if (type === "tool_call") {
31286
31074
  const name = trimmed2(update.title) ?? "Tool";
31287
- const tool = isRecord11(updateMetadata?.["x.ai/tool"]) ? updateMetadata["x.ai/tool"] : void 0;
31288
- const input2 = isRecord11(update.rawInput) && typeof update.rawInput.command === "string" ? update.rawInput.command : update.rawInput === void 0 ? void 0 : JSON.stringify(update.rawInput);
31075
+ const tool = isRecord10(updateMetadata?.["x.ai/tool"]) ? updateMetadata["x.ai/tool"] : void 0;
31076
+ const input2 = isRecord10(update.rawInput) && typeof update.rawInput.command === "string" ? update.rawInput.command : update.rawInput === void 0 ? void 0 : JSON.stringify(update.rawInput);
31289
31077
  const activity = {
31290
31078
  ...identity,
31291
31079
  kind: "tool.started",
@@ -31296,7 +31084,7 @@ async function readTranscript(session, signal, summaryOnly = false) {
31296
31084
  toolName: name,
31297
31085
  itemType: tool?.kind === "execute" ? "command_execution" : "dynamic_tool_call",
31298
31086
  startedAt: createdAt,
31299
- ...inputPayload(input2)
31087
+ ...inputPayload2(input2)
31300
31088
  }
31301
31089
  };
31302
31090
  activities.push(activity);
@@ -31313,7 +31101,7 @@ async function readTranscript(session, signal, summaryOnly = false) {
31313
31101
  payload: {
31314
31102
  ...start.payload,
31315
31103
  status: update.status,
31316
- ...outputPayload(output2)
31104
+ ...outputPayload2(output2)
31317
31105
  }
31318
31106
  });
31319
31107
  tools.delete(toolCallId);
@@ -31451,9 +31239,9 @@ var createGrokInstance = (config2, host) => {
31451
31239
  }
31452
31240
  prepareGrokFollowUpSteer(resolveAccountHomePath(recipe, recipe.homePath), host.log);
31453
31241
  const env = spawnEnv();
31454
- const version2 = await raceAbort4(modelCatalog.readCliVersion(signal), signal);
31242
+ const version2 = await raceAbort2(modelCatalog.readCliVersion(signal), signal);
31455
31243
  if (signal?.aborted) throw new Error("aborted");
31456
- await raceAbort4(
31244
+ await raceAbort2(
31457
31245
  modelCatalog.refreshModelCatalog({
31458
31246
  force: false,
31459
31247
  cliVersion: version2,
@@ -31462,7 +31250,7 @@ var createGrokInstance = (config2, host) => {
31462
31250
  signal
31463
31251
  );
31464
31252
  if (signal?.aborted) throw new Error("aborted");
31465
- const [outcome, skills] = await raceAbort4(
31253
+ const [outcome, skills] = await raceAbort2(
31466
31254
  Promise.all([
31467
31255
  probeGrokModels({
31468
31256
  recipe,
@@ -31518,19 +31306,7 @@ var createGrokInstance = (config2, host) => {
31518
31306
  sessions: {
31519
31307
  ...sessions,
31520
31308
  scan: ({ projectId, directory, signal }) => sessions.scan({ directory: directory ?? host.workspacePath(projectId), signal }),
31521
- read: async (input2) => {
31522
- const imported = await sessions.readImport(input2);
31523
- return {
31524
- nativeSessionId: input2.nativeSessionId,
31525
- model: imported.model,
31526
- resumeCursor: imported.resumeCursor,
31527
- messages: imported.messages.map(({ role, text: text4, createdAt }) => ({
31528
- role,
31529
- text: text4,
31530
- createdAt: Date.parse(createdAt)
31531
- }))
31532
- };
31533
- }
31309
+ read: async (input2) => sessionReadFromImport(input2.nativeSessionId, await sessions.readImport(input2))
31534
31310
  },
31535
31311
  probe,
31536
31312
  readCliVersion: (signal) => modelCatalog.readCliVersion(signal),
@@ -31568,8 +31344,8 @@ var createGrokInstance = (config2, host) => {
31568
31344
  input2.threadId
31569
31345
  );
31570
31346
  const env = spawnEnv();
31571
- const effort = modelSelectionStringOption3(input2.modelSelection, GROK_REASONING_OPTION_ID);
31572
- const baseArgs = tokenizeShellWords(recipe.launchArgs);
31347
+ const effort = modelSelectionStringOption2(input2.modelSelection, GROK_REASONING_OPTION_ID);
31348
+ const baseArgs = tokenizeShellWords2(recipe.launchArgs);
31573
31349
  const insertAt = baseArgs.length <= 1 ? baseArgs.length : baseArgs.length - 1;
31574
31350
  const permissionMode = grokPermissionModeFor(input2.runtimeMode, input2.nativeModeId);
31575
31351
  const args = [
@@ -31586,7 +31362,7 @@ var createGrokInstance = (config2, host) => {
31586
31362
  owner: { bindingId: host.bindingId },
31587
31363
  ...Object.keys(env).length > 0 ? { env } : {}
31588
31364
  });
31589
- const { readable, writable, stderrTail } = nodeStreamsFromHandle3(handle);
31365
+ const { readable, writable, stderrTail } = nodeStreamsFromHandle2(handle);
31590
31366
  const resume = acpResumeFrom(input2, RESUME_SCHEMA_VERSION);
31591
31367
  const requestedModelId = modelIdFromSelection(input2.modelSelection);
31592
31368
  let initializeResult;
@@ -31780,23 +31556,11 @@ var index_default = definePlugin({
31780
31556
  apiVersion: PLUGIN_API_VERSION,
31781
31557
  executors,
31782
31558
  activate(ctx) {
31783
- ctx.command({
31784
- name: "effectiveConfig",
31785
- description: "Settings form: the account directory an empty path resolves to on this machine.",
31786
- scope: "read",
31787
- payloadSchema: EXECUTOR_EFFECTIVE_PAYLOAD_SCHEMA,
31788
- handle: async (payload) => {
31789
- const request = readExecutorEffectiveRequest(payload);
31790
- return {
31791
- homePath: executorHomeEffectiveValue(
31792
- "GROK_HOME",
31793
- request,
31794
- process.env,
31795
- (value) => resolveGrokHomePath(value ?? "")
31796
- )
31797
- };
31798
- }
31799
- });
31559
+ registerEffectiveHomeCommand(
31560
+ ctx,
31561
+ GROK_CARD.homeEnvVar,
31562
+ (value) => resolveGrokHomePath(value ?? "")
31563
+ );
31800
31564
  ctx.log.info("grok executor ready");
31801
31565
  }
31802
31566
  });