@ycodium-ai/agent-grok 0.2.5448 → 0.2.5542

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/dist/index.js +382 -63
  3. package/package.json +4 -3
package/README.md CHANGED
@@ -33,6 +33,8 @@ Facts:
33
33
  instance environment table wins over the account-directory setting, and
34
34
  credential reads use the home the subprocess actually sees. An empty
35
35
  account directory means the CLI default `~/.grok` is used without injection.
36
+ - Terminal session import discovers Grok sessions in the selected working directory.
37
+ Reads local transcripts from the selected Grok account directory. Resume uses the existing ACP session ID.
36
38
  - Manifest permission is `{ kind: "executor" }`.
37
39
  - Native in-session model switching is `unsupported` on the card.
38
40
  - Model connection is the instance's own: either `grok login --device-auth`, or
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ var __export = (target, all) => {
8
8
  import { definePlugin } from "@ycodium-ai/plugin-api";
9
9
 
10
10
  // ../../packages/plugin-api/src/version.ts
11
- var PLUGIN_API_VERSION = 171;
11
+ var PLUGIN_API_VERSION = 174;
12
12
 
13
13
  // src/index.ts
14
14
  import {
@@ -468,8 +468,8 @@ var UnboundedEventStream = class {
468
468
  iterators.subscribers.delete(subscriber);
469
469
  return { value: void 0, done: true };
470
470
  }
471
- await new Promise((resolve3) => {
472
- subscriber.wake = resolve3;
471
+ await new Promise((resolve4) => {
472
+ subscriber.wake = resolve4;
473
473
  });
474
474
  }
475
475
  },
@@ -695,8 +695,8 @@ var settledExitCode = async (exited) => {
695
695
  try {
696
696
  return await Promise.race([
697
697
  exited.catch(() => void 0),
698
- new Promise((resolve3) => {
699
- timer = setTimeout(() => resolve3(void 0), AGENT_EXIT_SETTLE_MS);
698
+ new Promise((resolve4) => {
699
+ timer = setTimeout(() => resolve4(void 0), AGENT_EXIT_SETTLE_MS);
700
700
  })
701
701
  ]);
702
702
  } finally {
@@ -1036,15 +1036,15 @@ function boundToolCallRawOutput(rawOutput) {
1036
1036
  return rawOutput;
1037
1037
  }
1038
1038
  let changed = false;
1039
- const bounded = { ...rawOutput };
1039
+ const bounded2 = { ...rawOutput };
1040
1040
  for (const field of RAW_OUTPUT_TEXT_FIELDS) {
1041
1041
  const value = rawOutput[field];
1042
1042
  if (typeof value === "string" && value.length > TOOL_CALL_CONTENT_MAX_CHARS) {
1043
- bounded[field] = boundToolCallOutputText(value);
1043
+ bounded2[field] = boundToolCallOutputText(value);
1044
1044
  changed = true;
1045
1045
  }
1046
1046
  }
1047
- return changed ? bounded : rawOutput;
1047
+ return changed ? bounded2 : rawOutput;
1048
1048
  }
1049
1049
  function toolCallContentText(entry) {
1050
1050
  if (entry.type !== "content" || entry.content?.type !== "text") {
@@ -1071,7 +1071,7 @@ function extractTextContentFromToolCallContent(content) {
1071
1071
  if (joined.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
1072
1072
  return { text: joined, content: typed };
1073
1073
  }
1074
- const bounded = boundToolCallOutputText(joined);
1074
+ const bounded2 = boundToolCallOutputText(joined);
1075
1075
  const lastContributingTextIndex = typed.reduce(
1076
1076
  (lastIndex, entry, index) => toolCallContentText(entry)?.trim() ? index : lastIndex,
1077
1077
  -1
@@ -1083,9 +1083,9 @@ function extractTextContentFromToolCallContent(content) {
1083
1083
  if (index !== lastContributingTextIndex) {
1084
1084
  return [];
1085
1085
  }
1086
- return [{ type: "content", content: { type: "text", text: bounded } }];
1086
+ return [{ type: "content", content: { type: "text", text: bounded2 } }];
1087
1087
  });
1088
- return { text: bounded, content: boundedContent };
1088
+ return { text: bounded2, content: boundedContent };
1089
1089
  }
1090
1090
  function normalizeToolKind(kind) {
1091
1091
  return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : void 0;
@@ -3654,18 +3654,18 @@ var validateAsync = async (schema, value, _ctx) => {
3654
3654
  return result.issues.length === 0;
3655
3655
  };
3656
3656
  var _encode = (_Err) => {
3657
- const parse3 = _parse(_Err);
3657
+ const parse4 = _parse(_Err);
3658
3658
  const fn = (schema, value, _ctx, _params) => {
3659
3659
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
3660
- return parse3(schema, value, ctx, finalizeParams(fn, _params));
3660
+ return parse4(schema, value, ctx, finalizeParams(fn, _params));
3661
3661
  };
3662
3662
  return fn;
3663
3663
  };
3664
3664
  var encode = /* @__PURE__ */ _encode($ZodRealError);
3665
3665
  var _decode = (_Err) => {
3666
- const parse3 = _parse(_Err);
3666
+ const parse4 = _parse(_Err);
3667
3667
  const fn = (schema, value, _ctx, _params) => {
3668
- return parse3(schema, value, _ctx, finalizeParams(fn, _params));
3668
+ return parse4(schema, value, _ctx, finalizeParams(fn, _params));
3669
3669
  };
3670
3670
  return fn;
3671
3671
  };
@@ -6835,7 +6835,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6835
6835
  var NONE = 0;
6836
6836
  var ASSUMED = 1;
6837
6837
  var PROVEN = 2;
6838
- function isRecursive(inst, stack, resolve3) {
6838
+ function isRecursive(inst, stack, resolve4) {
6839
6839
  const cached2 = recursive.get(inst);
6840
6840
  if (cached2 !== void 0)
6841
6841
  return cached2 ? PROVEN : NONE;
@@ -6845,7 +6845,7 @@ function isRecursive(inst, stack, resolve3) {
6845
6845
  let result = NONE;
6846
6846
  const check2 = (child) => {
6847
6847
  if (result !== PROVEN && child?._zod) {
6848
- const answer = isRecursive(child, stack, resolve3);
6848
+ const answer = isRecursive(child, stack, resolve4);
6849
6849
  if (answer > result)
6850
6850
  result = answer;
6851
6851
  }
@@ -6856,7 +6856,7 @@ function isRecursive(inst, stack, resolve3) {
6856
6856
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6857
6857
  if (spread && !desc.enumerable)
6858
6858
  continue;
6859
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve3) : NONE;
6859
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve4) : NONE;
6860
6860
  if (child > answer)
6861
6861
  answer = child;
6862
6862
  }
@@ -6920,7 +6920,7 @@ function isRecursive(inst, stack, resolve3) {
6920
6920
  break;
6921
6921
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6922
6922
  case "lazy": {
6923
- const inner = def._cachedInner ?? (resolve3 ? inst._zod.innerType : void 0);
6923
+ const inner = def._cachedInner ?? (resolve4 ? inst._zod.innerType : void 0);
6924
6924
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6925
6925
  break;
6926
6926
  }
@@ -23584,11 +23584,11 @@ var Connection = class {
23584
23584
  const id = this.nextRequestId++;
23585
23585
  let cancel = () => {
23586
23586
  };
23587
- const response = new Promise((resolve3, reject) => {
23587
+ const response = new Promise((resolve4, reject) => {
23588
23588
  const pendingResponse = {
23589
23589
  resolve: (value) => {
23590
23590
  try {
23591
- resolve3(mapResponse ? mapResponse(value) : value);
23591
+ resolve4(mapResponse ? mapResponse(value) : value);
23592
23592
  } catch (error62) {
23593
23593
  reject(error62);
23594
23594
  }
@@ -23645,8 +23645,8 @@ var Connection = class {
23645
23645
  this.stream = stream;
23646
23646
  this.staticHandlers = handlers;
23647
23647
  this.allowBatches = options?.allowBatches ?? true;
23648
- this.closedPromise = new Promise((resolve3) => {
23649
- this.abortController.signal.addEventListener("abort", () => resolve3());
23648
+ this.closedPromise = new Promise((resolve4) => {
23649
+ this.abortController.signal.addEventListener("abort", () => resolve4());
23650
23650
  });
23651
23651
  void this.receive();
23652
23652
  }
@@ -23937,13 +23937,13 @@ var ConnectionBuilder = class {
23937
23937
  /**
23938
23938
  * Adds a typed request handler for one method.
23939
23939
  */
23940
- onReceiveRequest(method, parse3, handler) {
23940
+ onReceiveRequest(method, parse4, handler) {
23941
23941
  return this.withHandler({
23942
23942
  handleMessage: async (message, cx) => {
23943
23943
  if (message.kind !== "request" || message.method !== method) {
23944
23944
  return Handled.no(message);
23945
23945
  }
23946
- const request = parse3(message.params);
23946
+ const request = parse4(message.params);
23947
23947
  return await handler(request, message.responder, cx) ?? Handled.yes();
23948
23948
  },
23949
23949
  describe: () => `${this.connectionName ?? "request"}:${method}`
@@ -23952,13 +23952,13 @@ var ConnectionBuilder = class {
23952
23952
  /**
23953
23953
  * Adds a typed notification handler for one method.
23954
23954
  */
23955
- onReceiveNotification(method, parse3, handler) {
23955
+ onReceiveNotification(method, parse4, handler) {
23956
23956
  return this.withHandler({
23957
23957
  handleMessage: async (message, cx) => {
23958
23958
  if (message.kind !== "notification" || message.method !== method) {
23959
23959
  return Handled.no(message);
23960
23960
  }
23961
- const notification = parse3(message.params);
23961
+ const notification = parse4(message.params);
23962
23962
  return await handler(notification, cx) ?? Handled.yes();
23963
23963
  },
23964
23964
  describe: () => `${this.connectionName ?? "notification"}:${method}`
@@ -24540,8 +24540,8 @@ var AsyncQueue = class {
24540
24540
  if (this.failed) {
24541
24541
  return Promise.reject(this.failure);
24542
24542
  }
24543
- return new Promise((resolve3, reject) => {
24544
- this.waiters.push({ resolve: resolve3, reject });
24543
+ return new Promise((resolve4, reject) => {
24544
+ this.waiters.push({ resolve: resolve4, reject });
24545
24545
  });
24546
24546
  }
24547
24547
  };
@@ -25588,12 +25588,12 @@ function createAcpConnection(options) {
25588
25588
  failIfClosed();
25589
25589
  const id = nextRequestId;
25590
25590
  nextRequestId += 1;
25591
- const { promise: promise2, resolve: resolve3, reject } = Promise.withResolvers();
25591
+ const { promise: promise2, resolve: resolve4, reject } = Promise.withResolvers();
25592
25592
  pending.set(String(id), {
25593
25593
  method,
25594
25594
  ...promptId === void 0 ? {} : { promptId },
25595
25595
  ...onArrival === void 0 ? {} : { onArrival },
25596
- resolve: resolve3,
25596
+ resolve: resolve4,
25597
25597
  reject
25598
25598
  });
25599
25599
  const message = params === void 0 ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
@@ -25622,8 +25622,8 @@ function createAcpConnection(options) {
25622
25622
  if (inboundBatches === 0) {
25623
25623
  return;
25624
25624
  }
25625
- await new Promise((resolve3) => {
25626
- idleWaiters.push(resolve3);
25625
+ await new Promise((resolve4) => {
25626
+ idleWaiters.push(resolve4);
25627
25627
  if (inboundBatches === 0) {
25628
25628
  releaseIdleWaiters();
25629
25629
  }
@@ -25709,8 +25709,8 @@ var Mutex = class {
25709
25709
  this.locked = true;
25710
25710
  return Promise.resolve();
25711
25711
  }
25712
- return new Promise((resolve3) => {
25713
- this.waiters.push(resolve3);
25712
+ return new Promise((resolve4) => {
25713
+ this.waiters.push(resolve4);
25714
25714
  });
25715
25715
  }
25716
25716
  tryAcquire() {
@@ -25911,9 +25911,9 @@ function createExecutorLifecycle({
25911
25911
  let timer;
25912
25912
  await Promise.race([
25913
25913
  connection.closed.catch(() => void 0),
25914
- new Promise((resolve3) => {
25914
+ new Promise((resolve4) => {
25915
25915
  timer = setTimeout(
25916
- resolve3,
25916
+ resolve4,
25917
25917
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
25918
25918
  );
25919
25919
  })
@@ -26790,12 +26790,12 @@ function createPromptResults({
26790
26790
  }) {
26791
26791
  const prompts = /* @__PURE__ */ new Map();
26792
26792
  const add = (identity, finish) => {
26793
- const { promise: done, resolve: resolve3 } = Promise.withResolvers();
26793
+ const { promise: done, resolve: resolve4 } = Promise.withResolvers();
26794
26794
  const record4 = {
26795
26795
  ...identity,
26796
26796
  finish,
26797
26797
  done,
26798
- resolve: resolve3,
26798
+ resolve: resolve4,
26799
26799
  rejected: false,
26800
26800
  interrupted: false,
26801
26801
  finished: false
@@ -26843,9 +26843,9 @@ function createPromptResults({
26843
26843
  try {
26844
26844
  const drained = await Promise.race([
26845
26845
  Promise.all(claimed.map((record4) => record4.done)).then(() => true),
26846
- new Promise((resolve3) => {
26846
+ new Promise((resolve4) => {
26847
26847
  timer = setTimeout(
26848
- () => resolve3(false),
26848
+ () => resolve4(false),
26849
26849
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
26850
26850
  );
26851
26851
  })
@@ -27044,14 +27044,14 @@ function createExecutorRequests({
27044
27044
  const statement = hooks.permissionStatement?.(permissionContext) ?? defaultPermissionStatement(permissionRequest);
27045
27045
  const fileChanges = hooks.permissionFileChanges?.(permissionContext) ?? fileChangesFromAcpPermission(permissionRequest);
27046
27046
  const requestId = randomId();
27047
- const outcome = await new Promise((resolve3) => {
27047
+ const outcome = await new Promise((resolve4) => {
27048
27048
  const pending = {
27049
27049
  requestId,
27050
27050
  request: params,
27051
27051
  permissionRequest,
27052
27052
  turnId: shared.activeTurnId,
27053
27053
  settled: false,
27054
- resolve: resolve3
27054
+ resolve: resolve4
27055
27055
  };
27056
27056
  approvals.add(pending);
27057
27057
  emit(
@@ -27268,14 +27268,14 @@ function createExecutorRuntime({
27268
27268
  if (!promptMutex.isLocked) {
27269
27269
  return true;
27270
27270
  }
27271
- return await new Promise((resolve3) => {
27271
+ return await new Promise((resolve4) => {
27272
27272
  const timer = setTimeout(() => {
27273
27273
  shared.promptWaiters = shared.promptWaiters.filter((waiter) => waiter !== onSettle);
27274
- resolve3(false);
27274
+ resolve4(false);
27275
27275
  }, timeoutMs);
27276
27276
  const onSettle = () => {
27277
27277
  clearTimeout(timer);
27278
- resolve3(true);
27278
+ resolve4(true);
27279
27279
  };
27280
27280
  shared.promptWaiters.push(onSettle);
27281
27281
  });
@@ -28849,13 +28849,13 @@ function acpNativeSessionProcessMatcher(program, args) {
28849
28849
 
28850
28850
  // ../../packages/ycodium-acp-executor/src/prompt-dispatch.ts
28851
28851
  var dispatchAcpPrompt = (executor, input2) => {
28852
- const { promise: dispatched, resolve: resolve3 } = Promise.withResolvers();
28852
+ const { promise: dispatched, resolve: resolve4 } = Promise.withResolvers();
28853
28853
  let written = false;
28854
28854
  const finished = executor.prompt({
28855
28855
  ...input2,
28856
28856
  onDispatched: (turnId) => {
28857
28857
  written = true;
28858
- resolve3(turnId);
28858
+ resolve4(turnId);
28859
28859
  }
28860
28860
  });
28861
28861
  return Promise.race([
@@ -28870,8 +28870,8 @@ var dispatchAcpPrompt = (executor, input2) => {
28870
28870
  };
28871
28871
 
28872
28872
  // ../../packages/ycodium-acp-executor/src/thread-operations.ts
28873
- var yieldTick = () => new Promise((resolve3) => {
28874
- setImmediate(resolve3);
28873
+ var yieldTick = () => new Promise((resolve4) => {
28874
+ setImmediate(resolve4);
28875
28875
  });
28876
28876
  var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
28877
28877
  function createAcpThreadOperations(options) {
@@ -28985,8 +28985,8 @@ async function raceStartAbort(promise2, signal) {
28985
28985
  }
28986
28986
 
28987
28987
  // ../../packages/ycodium-acp-executor/src/instance-kit.ts
28988
- var yieldTick2 = () => new Promise((resolve3) => {
28989
- setImmediate(resolve3);
28988
+ var yieldTick2 = () => new Promise((resolve4) => {
28989
+ setImmediate(resolve4);
28990
28990
  });
28991
28991
  var nowIso2 = () => (/* @__PURE__ */ new Date()).toISOString();
28992
28992
  function createAcpThreadTable(log, beforeStopAll) {
@@ -29104,7 +29104,7 @@ var acpProbeFailureDetail = (error62) => (error62 instanceof Error ? error62.mes
29104
29104
  // ../../packages/ycodium-acp-executor/src/probe.ts
29105
29105
  function withProbeTimeout(promise2, timeoutMs, what, signal) {
29106
29106
  signal?.throwIfAborted();
29107
- return new Promise((resolve3, reject) => {
29107
+ return new Promise((resolve4, reject) => {
29108
29108
  const onAbort = () => {
29109
29109
  clearTimeout(timer);
29110
29110
  reject(signal?.reason ?? new Error("aborted"));
@@ -29119,7 +29119,7 @@ function withProbeTimeout(promise2, timeoutMs, what, signal) {
29119
29119
  (value) => {
29120
29120
  clearTimeout(timer);
29121
29121
  signal?.removeEventListener("abort", onAbort);
29122
- resolve3(value);
29122
+ resolve4(value);
29123
29123
  },
29124
29124
  (error62) => {
29125
29125
  clearTimeout(timer);
@@ -29223,6 +29223,30 @@ async function collectProbeProcess(child, input2) {
29223
29223
  }
29224
29224
  var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
29225
29225
 
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
+
29226
29250
  // ../../packages/ycodium-instance-config/src/launchArgs.ts
29227
29251
  function tokenizeShellWords(value) {
29228
29252
  const input2 = value.trim();
@@ -29359,13 +29383,13 @@ var hasDeviceCode = (output2) => deviceCodeUrl(output2) !== void 0 && deviceCode
29359
29383
  function readDeviceCodeOutput(stdout, onText) {
29360
29384
  const collected = [];
29361
29385
  let onCodeFound;
29362
- const codeFound = new Promise((resolve3) => {
29363
- onCodeFound = resolve3;
29386
+ const codeFound = new Promise((resolve4) => {
29387
+ onCodeFound = resolve4;
29364
29388
  });
29365
29389
  let quietTimer;
29366
29390
  let onQuiet;
29367
- const outputWentQuiet = new Promise((resolve3) => {
29368
- onQuiet = resolve3;
29391
+ const outputWentQuiet = new Promise((resolve4) => {
29392
+ onQuiet = resolve4;
29369
29393
  });
29370
29394
  const text4 = (async () => {
29371
29395
  const decoder = new TextDecoder();
@@ -29390,8 +29414,8 @@ function readDeviceCodeOutput(stdout, onText) {
29390
29414
  codeFound,
29391
29415
  text4.then(() => void 0),
29392
29416
  outputWentQuiet,
29393
- new Promise((resolve3) => {
29394
- silentCap = setTimeout(resolve3, SILENT_CAP_MS);
29417
+ new Promise((resolve4) => {
29418
+ silentCap = setTimeout(resolve4, SILENT_CAP_MS);
29395
29419
  })
29396
29420
  ]);
29397
29421
  clearTimeout(silentCap);
@@ -29709,11 +29733,11 @@ var createGrokTurnUsageCollector = (base) => {
29709
29733
  const attach = async (event) => {
29710
29734
  if (event.type !== "turn.completed" || !isRecord9(event.payload)) return event;
29711
29735
  if (event.payload["state"] === "completed" && !allAnswered()) {
29712
- await new Promise((resolve3) => {
29713
- const timer = setTimeout(resolve3, USAGE_GRACE_MS);
29736
+ await new Promise((resolve4) => {
29737
+ const timer = setTimeout(resolve4, USAGE_GRACE_MS);
29714
29738
  wake = () => {
29715
29739
  clearTimeout(timer);
29716
- resolve3();
29740
+ resolve4();
29717
29741
  };
29718
29742
  });
29719
29743
  wake = void 0;
@@ -31098,6 +31122,279 @@ var grokPermissionStatement = ({
31098
31122
  };
31099
31123
  };
31100
31124
 
31125
+ // src/nativeSessions.ts
31126
+ import * as NodeFS6 from "node:fs";
31127
+ import * as NodeFSP from "node:fs/promises";
31128
+ import * as NodePath10 from "node:path";
31129
+ import * as NodeReadline from "node:readline";
31130
+ var sessionIdPattern = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/iu;
31131
+ function parseRecord(raw) {
31132
+ try {
31133
+ const value = JSON.parse(raw);
31134
+ return isRecord11(value) ? value : void 0;
31135
+ } catch {
31136
+ return void 0;
31137
+ }
31138
+ }
31139
+ function missingFile(error62) {
31140
+ return error62.code === "ENOENT";
31141
+ }
31142
+ async function directories(path) {
31143
+ try {
31144
+ return (await NodeFSP.readdir(path, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
31145
+ } catch (error62) {
31146
+ if (missingFile(error62)) return [];
31147
+ throw error62;
31148
+ }
31149
+ }
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
+ async function findSessions(home, cwd, signal, nativeSessionId) {
31168
+ signal?.throwIfAborted();
31169
+ const expectedCwd = directoryKey(cwd);
31170
+ const result = [];
31171
+ const root = NodePath10.join(home, "sessions");
31172
+ for (const workspace of await directories(root)) {
31173
+ const workspacePath = NodePath10.join(root, workspace);
31174
+ for (const id of await directories(workspacePath)) {
31175
+ signal?.throwIfAborted();
31176
+ if (!sessionIdPattern.test(id) || nativeSessionId !== void 0 && nativeSessionId !== id)
31177
+ continue;
31178
+ const sessionPath = NodePath10.join(workspacePath, id);
31179
+ const summaryPath = NodePath10.join(sessionPath, "summary.json");
31180
+ try {
31181
+ if (!(await NodeFSP.lstat(summaryPath)).isFile()) continue;
31182
+ const summary = parseRecord(
31183
+ await NodeFSP.readFile(summaryPath, { encoding: "utf8", signal })
31184
+ );
31185
+ const info = summary?.info;
31186
+ if (!summary || !isRecord11(info) || info.id !== id || typeof info.cwd !== "string" || !isAbsoluteDirectory(info.cwd))
31187
+ continue;
31188
+ const relative2 = NodePath10.relative(expectedCwd, directoryKey(info.cwd));
31189
+ if (relative2 !== "" && (nativeSessionId !== void 0 || relative2 === ".." || relative2.startsWith(`..${NodePath10.sep}`) || NodePath10.isAbsolute(relative2)))
31190
+ continue;
31191
+ const updates = NodePath10.join(sessionPath, "updates.jsonl");
31192
+ if (!(await NodeFSP.lstat(updates)).isFile()) continue;
31193
+ const updatedAt = Date.parse(trimmed2(summary.updated_at) ?? "");
31194
+ result.push({
31195
+ id,
31196
+ cwd: info.cwd,
31197
+ title: trimmed2(summary.title) ?? trimmed2(summary.generated_title) ?? null,
31198
+ preview: trimmed2(summary.session_summary) ?? null,
31199
+ model: trimmed2(summary.current_model_id) ?? null,
31200
+ updatedAt: Number.isFinite(updatedAt) ? updatedAt : 0,
31201
+ updates
31202
+ });
31203
+ } catch (error62) {
31204
+ if (!missingFile(error62)) throw error62;
31205
+ }
31206
+ }
31207
+ }
31208
+ signal?.throwIfAborted();
31209
+ return result;
31210
+ }
31211
+ function toolOutput(content) {
31212
+ if (!Array.isArray(content)) return void 0;
31213
+ const output2 = content.flatMap(
31214
+ (entry) => isRecord11(entry) && isRecord11(entry.content) && entry.content.type === "text" && typeof entry.content.text === "string" ? [entry.content.text] : []
31215
+ ).join("\n");
31216
+ return output2.length === 0 ? void 0 : output2;
31217
+ }
31218
+ async function readTranscript(session, signal, summaryOnly = false) {
31219
+ const stream = NodeFS6.createReadStream(session.updates, { signal });
31220
+ const lines = NodeReadline.createInterface({ input: stream, crlfDelay: Infinity });
31221
+ const messages = [];
31222
+ const activities = [];
31223
+ const tools = /* @__PURE__ */ new Map();
31224
+ let turnCount = 0;
31225
+ let hasMessages = false;
31226
+ let preview = null;
31227
+ let nativeTurnId;
31228
+ let model;
31229
+ let sourceOrder = 0;
31230
+ let previous;
31231
+ let firstPrompt = false;
31232
+ try {
31233
+ for await (const line of lines) {
31234
+ signal?.throwIfAborted();
31235
+ sourceOrder += 1;
31236
+ const row = parseRecord(line);
31237
+ if (!row || !isRecord11(row.params) || row.params.sessionId !== session.id) continue;
31238
+ 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;
31242
+ const sourceId = eventId ?? `update:${sourceOrder}`;
31243
+ const timestamp = typeof row.timestamp_us === "number" ? row.timestamp_us / 1e3 : typeof row.timestamp === "number" ? row.timestamp * 1e3 : session.updatedAt;
31244
+ const createdAt = new Date(Math.abs(timestamp) <= 864e13 ? timestamp : 0).toISOString();
31245
+ const type = update.sessionUpdate;
31246
+ const role = type === "user_message_chunk" ? "user" : type === "agent_message_chunk" ? "assistant" : void 0;
31247
+ const promptIndex = updateMetadata?.promptIndex;
31248
+ if (role === "user") {
31249
+ const turnId = typeof promptIndex === "number" ? String(promptIndex) : previous?.role === "user" ? nativeTurnId : sourceId;
31250
+ if (turnId !== nativeTurnId) turnCount += 1;
31251
+ nativeTurnId = turnId;
31252
+ model = trimmed2(updateMetadata?.modelId) ?? model;
31253
+ }
31254
+ const identity = {
31255
+ sourceId,
31256
+ sourceOrder,
31257
+ createdAt,
31258
+ ...nativeTurnId === void 0 ? {} : { nativeTurnId },
31259
+ ...model === void 0 ? {} : { model }
31260
+ };
31261
+ if (role !== void 0) {
31262
+ const content = update.content;
31263
+ if (!isRecord11(content) || content.type !== "text" || typeof content.text !== "string" || content.text.length === 0)
31264
+ continue;
31265
+ hasMessages = true;
31266
+ const continuing = previous?.role === role && previous.nativeTurnId === nativeTurnId;
31267
+ if (!continuing) firstPrompt = role === "user" && preview === null;
31268
+ if (firstPrompt) {
31269
+ const prefix = preview ?? "";
31270
+ preview = prefix + content.text.slice(0, 240 - prefix.length);
31271
+ }
31272
+ previous = { role, nativeTurnId };
31273
+ if (!summaryOnly) {
31274
+ const message = continuing ? messages.at(-1) : void 0;
31275
+ if (message) message.text += content.text;
31276
+ else messages.push({ ...identity, role, text: content.text });
31277
+ }
31278
+ continue;
31279
+ }
31280
+ if (type === "turn_completed") previous = void 0;
31281
+ const toolCallId = trimmed2(update.toolCallId);
31282
+ if (toolCallId === void 0) continue;
31283
+ if (type === "tool_call") previous = void 0;
31284
+ if (summaryOnly) continue;
31285
+ if (type === "tool_call") {
31286
+ 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);
31289
+ const activity = {
31290
+ ...identity,
31291
+ kind: "tool.started",
31292
+ tone: "tool",
31293
+ summary: name,
31294
+ payload: {
31295
+ toolCallId,
31296
+ toolName: name,
31297
+ itemType: tool?.kind === "execute" ? "command_execution" : "dynamic_tool_call",
31298
+ startedAt: createdAt,
31299
+ ...inputPayload(input2)
31300
+ }
31301
+ };
31302
+ activities.push(activity);
31303
+ tools.set(toolCallId, activity);
31304
+ } else if (type === "tool_call_update" && (update.status === "completed" || update.status === "failed")) {
31305
+ const start = tools.get(toolCallId);
31306
+ if (!start) continue;
31307
+ const output2 = toolOutput(update.content);
31308
+ activities.push({
31309
+ ...identity,
31310
+ kind: "tool.completed",
31311
+ tone: update.status === "failed" ? "error" : "tool",
31312
+ summary: start.summary,
31313
+ payload: {
31314
+ ...start.payload,
31315
+ status: update.status,
31316
+ ...outputPayload(output2)
31317
+ }
31318
+ });
31319
+ tools.delete(toolCallId);
31320
+ }
31321
+ }
31322
+ signal?.throwIfAborted();
31323
+ } finally {
31324
+ lines.close();
31325
+ stream.destroy();
31326
+ }
31327
+ return { messages, activities, turnCount, hasMessages, preview };
31328
+ }
31329
+ function createGrokNativeSessions(home, resumeSchemaVersion) {
31330
+ const storageKey = isAbsoluteDirectory(home) ? "grok:" + directoryKey(readableStoragePath(home)) : void 0;
31331
+ const importHome = () => {
31332
+ if (!storageKey)
31333
+ throw new Error("Grok terminal import requires an absolute account directory.");
31334
+ return home;
31335
+ };
31336
+ return {
31337
+ ...storageKey === void 0 ? {} : { storageKey },
31338
+ scan: async ({
31339
+ directory,
31340
+ signal
31341
+ }) => {
31342
+ const sessions = (await findSessions(importHome(), directory, signal)).sort(
31343
+ (left, right) => right.updatedAt - left.updatedAt
31344
+ );
31345
+ const candidates = [];
31346
+ for (const session of sessions) {
31347
+ try {
31348
+ const {
31349
+ hasMessages,
31350
+ preview: prompt,
31351
+ turnCount
31352
+ } = await readTranscript(session, signal, true);
31353
+ if (!hasMessages) continue;
31354
+ candidates.push({
31355
+ nativeSessionId: session.id,
31356
+ cwd: session.cwd,
31357
+ title: session.title ?? prompt?.slice(0, 160) ?? null,
31358
+ preview: session.preview ?? prompt?.slice(0, 240) ?? null,
31359
+ model: session.model,
31360
+ turnCount,
31361
+ updatedAt: session.updatedAt,
31362
+ availability: "importable",
31363
+ openElsewhere: false
31364
+ });
31365
+ } catch (error62) {
31366
+ if (!missingFile(error62)) throw error62;
31367
+ }
31368
+ }
31369
+ return { candidates };
31370
+ },
31371
+ readImport: async ({
31372
+ nativeSessionId,
31373
+ cwd,
31374
+ signal
31375
+ }) => {
31376
+ signal?.throwIfAborted();
31377
+ if (cwd === void 0 || !isAbsoluteDirectory(cwd)) {
31378
+ throw new Error("Grok session import requires an absolute working directory.");
31379
+ }
31380
+ const matches = await findSessions(importHome(), cwd, signal, nativeSessionId);
31381
+ const session = matches[0];
31382
+ if (matches.length !== 1 || session === void 0)
31383
+ throw new Error("Grok session was not found uniquely in the requested working directory.");
31384
+ const { messages, activities } = await readTranscript(session, signal);
31385
+ return {
31386
+ resumeCursor: { schemaVersion: resumeSchemaVersion, sessionId: session.id },
31387
+ title: session.title ?? messages.find((message) => message.role === "user")?.text.slice(0, 160) ?? null,
31388
+ model: session.model,
31389
+ messages,
31390
+ activities,
31391
+ availableMessages: messages.length,
31392
+ availableActivities: activities.length
31393
+ };
31394
+ }
31395
+ };
31396
+ }
31397
+
31101
31398
  // src/grokInstance.ts
31102
31399
  var RESUME_SCHEMA_VERSION = 1;
31103
31400
  function nowIso3() {
@@ -31212,7 +31509,29 @@ var createGrokInstance = (config2, host) => {
31212
31509
  turnSelection: (selection) => readTurnSelection(selection, GROK_REASONING_OPTION_ID),
31213
31510
  log: host.log
31214
31511
  });
31512
+ const sessionHome = (spawnEnv().GROK_HOME ?? process.env.GROK_HOME)?.trim();
31513
+ const sessions = createGrokNativeSessions(
31514
+ sessionHome || resolveGrokHomePath(""),
31515
+ RESUME_SCHEMA_VERSION
31516
+ );
31215
31517
  const instance = {
31518
+ sessions: {
31519
+ ...sessions,
31520
+ 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
+ }
31534
+ },
31216
31535
  probe,
31217
31536
  readCliVersion: (signal) => modelCatalog.readCliVersion(signal),
31218
31537
  refreshModelCatalog: ({ force, signal }) => modelCatalog.refreshModelCatalog({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ycodium-ai/agent-grok",
3
- "version": "0.2.5448",
3
+ "version": "0.2.5542",
4
4
  "description": "Grok executor: grok CLI over Agent Client Protocol stdio.",
5
5
  "keywords": [
6
6
  "ycodium",
@@ -21,10 +21,11 @@
21
21
  "@types/node": "24.12.4",
22
22
  "esbuild": "0.28.1",
23
23
  "vite-plus": "0.2.2",
24
- "@ycodium-ai/plugin-api": "0.2.0",
24
+ "@ycodium-ai/plugin-api": "0.2.5542",
25
+ "ycodium-acp-executor": "0.2.5542",
25
26
  "ycodium-credential-account": "0.0.0",
26
- "ycodium-acp-executor": "0.2.0",
27
27
  "ycodium-executor-testing": "0.0.0",
28
+ "ycodium-jsonl-stream": "0.0.0",
28
29
  "ycodium-instance-config": "0.0.0"
29
30
  },
30
31
  "ycodium": {