@ycodium-ai/agent-grok 0.2.5407 → 0.2.5503

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 +400 -69
  3. package/package.json +6 -5
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 = 170;
11
+ var PLUGIN_API_VERSION = 173;
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() {
@@ -25791,9 +25791,9 @@ function createExecutorLifecycle({
25791
25791
  if (targetTurnId !== void 0) {
25792
25792
  interruptedTurnIds.add(targetTurnId);
25793
25793
  }
25794
- const optionWrites = shared.optionWriteStop;
25795
- if (optionWrites !== void 0 && (targetTurnId === void 0 || optionWrites.turnId === targetTurnId)) {
25796
- optionWrites.stop();
25794
+ const waiting = shared.localPromptWait;
25795
+ if (waiting !== void 0 && (targetTurnId === void 0 || waiting.turnId === targetTurnId)) {
25796
+ waiting.stop();
25797
25797
  }
25798
25798
  settleAllApprovals("cancel");
25799
25799
  settleAllUserInputs();
@@ -25906,13 +25906,14 @@ function createExecutorLifecycle({
25906
25906
  if (disposing) return disposing;
25907
25907
  shared.disposing = true;
25908
25908
  disposing = (async () => {
25909
+ shared.localPromptWait?.stop();
25909
25910
  if (exitCode !== void 0) {
25910
25911
  let timer;
25911
25912
  await Promise.race([
25912
25913
  connection.closed.catch(() => void 0),
25913
- new Promise((resolve3) => {
25914
+ new Promise((resolve4) => {
25914
25915
  timer = setTimeout(
25915
- resolve3,
25916
+ resolve4,
25916
25917
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
25917
25918
  );
25918
25919
  })
@@ -26655,7 +26656,7 @@ function createExecutorPrompt({
26655
26656
  const isStale = () => interruptedTurnIds.has(queuedTurnId) || input2.expectedActiveTurnId !== void 0 && shared.activeTurnId !== queuedTurnId;
26656
26657
  if (!isStale() && input2.expectedActiveTurnId === void 0) {
26657
26658
  const optionWrites = new AbortController();
26658
- shared.optionWriteStop = { turnId, stop: () => optionWrites.abort() };
26659
+ shared.localPromptWait = { turnId, stop: () => optionWrites.abort() };
26659
26660
  try {
26660
26661
  await alignTurnOptions(
26661
26662
  input2,
@@ -26680,7 +26681,7 @@ function createExecutorPrompt({
26680
26681
  });
26681
26682
  throw error62 instanceof Error ? withFailureCategory(error62, failureCategory) : error62;
26682
26683
  } finally {
26683
- shared.optionWriteStop = void 0;
26684
+ shared.localPromptWait = void 0;
26684
26685
  }
26685
26686
  }
26686
26687
  failIfDisposed();
@@ -26691,6 +26692,7 @@ function createExecutorPrompt({
26691
26692
  closeActiveAssistantSegment(turnId);
26692
26693
  let written = false;
26693
26694
  try {
26695
+ const readFailure = hooks.observePromptFailure?.(sessionId);
26694
26696
  response = await sendPromptRpc(
26695
26697
  sessionId,
26696
26698
  promptParts,
@@ -26700,6 +26702,16 @@ function createExecutorPrompt({
26700
26702
  },
26701
26703
  record4
26702
26704
  );
26705
+ if (readFailure && response.stopReason === "end_turn" && isLive(started.generation) && !isStale()) {
26706
+ const controller = new AbortController();
26707
+ shared.localPromptWait = { turnId, stop: () => controller.abort() };
26708
+ try {
26709
+ const failure2 = await readFailure(controller.signal);
26710
+ if (failure2 && !isStale() && !controller.signal.aborted) throw failure2;
26711
+ } finally {
26712
+ shared.localPromptWait = void 0;
26713
+ }
26714
+ }
26703
26715
  } catch (caught) {
26704
26716
  if (shared.disposed) {
26705
26717
  throw new AcpExecutorDisposedError();
@@ -26778,12 +26790,12 @@ function createPromptResults({
26778
26790
  }) {
26779
26791
  const prompts = /* @__PURE__ */ new Map();
26780
26792
  const add = (identity, finish) => {
26781
- const { promise: done, resolve: resolve3 } = Promise.withResolvers();
26793
+ const { promise: done, resolve: resolve4 } = Promise.withResolvers();
26782
26794
  const record4 = {
26783
26795
  ...identity,
26784
26796
  finish,
26785
26797
  done,
26786
- resolve: resolve3,
26798
+ resolve: resolve4,
26787
26799
  rejected: false,
26788
26800
  interrupted: false,
26789
26801
  finished: false
@@ -26831,9 +26843,9 @@ function createPromptResults({
26831
26843
  try {
26832
26844
  const drained = await Promise.race([
26833
26845
  Promise.all(claimed.map((record4) => record4.done)).then(() => true),
26834
- new Promise((resolve3) => {
26846
+ new Promise((resolve4) => {
26835
26847
  timer = setTimeout(
26836
- () => resolve3(false),
26848
+ () => resolve4(false),
26837
26849
  options.resultDrainTimeoutMs ?? DEFAULT_RESULT_DRAIN_TIMEOUT_MS
26838
26850
  );
26839
26851
  })
@@ -27032,14 +27044,14 @@ function createExecutorRequests({
27032
27044
  const statement = hooks.permissionStatement?.(permissionContext) ?? defaultPermissionStatement(permissionRequest);
27033
27045
  const fileChanges = hooks.permissionFileChanges?.(permissionContext) ?? fileChangesFromAcpPermission(permissionRequest);
27034
27046
  const requestId = randomId();
27035
- const outcome = await new Promise((resolve3) => {
27047
+ const outcome = await new Promise((resolve4) => {
27036
27048
  const pending = {
27037
27049
  requestId,
27038
27050
  request: params,
27039
27051
  permissionRequest,
27040
27052
  turnId: shared.activeTurnId,
27041
27053
  settled: false,
27042
- resolve: resolve3
27054
+ resolve: resolve4
27043
27055
  };
27044
27056
  approvals.add(pending);
27045
27057
  emit(
@@ -27256,14 +27268,14 @@ function createExecutorRuntime({
27256
27268
  if (!promptMutex.isLocked) {
27257
27269
  return true;
27258
27270
  }
27259
- return await new Promise((resolve3) => {
27271
+ return await new Promise((resolve4) => {
27260
27272
  const timer = setTimeout(() => {
27261
27273
  shared.promptWaiters = shared.promptWaiters.filter((waiter) => waiter !== onSettle);
27262
- resolve3(false);
27274
+ resolve4(false);
27263
27275
  }, timeoutMs);
27264
27276
  const onSettle = () => {
27265
27277
  clearTimeout(timer);
27266
- resolve3(true);
27278
+ resolve4(true);
27267
27279
  };
27268
27280
  shared.promptWaiters.push(onSettle);
27269
27281
  });
@@ -28461,7 +28473,7 @@ function createAcpExecutor(options) {
28461
28473
  childSessions: createChildSessionRegistry(),
28462
28474
  sessionOpensInFlight: 0,
28463
28475
  configOptionUpdates: /* @__PURE__ */ new Map(),
28464
- optionWriteStop: void 0,
28476
+ localPromptWait: void 0,
28465
28477
  configUpdateSeq: 0
28466
28478
  };
28467
28479
  const interruptedTurnIds = /* @__PURE__ */ new Set();
@@ -28837,13 +28849,13 @@ function acpNativeSessionProcessMatcher(program, args) {
28837
28849
 
28838
28850
  // ../../packages/ycodium-acp-executor/src/prompt-dispatch.ts
28839
28851
  var dispatchAcpPrompt = (executor, input2) => {
28840
- const { promise: dispatched, resolve: resolve3 } = Promise.withResolvers();
28852
+ const { promise: dispatched, resolve: resolve4 } = Promise.withResolvers();
28841
28853
  let written = false;
28842
28854
  const finished = executor.prompt({
28843
28855
  ...input2,
28844
28856
  onDispatched: (turnId) => {
28845
28857
  written = true;
28846
- resolve3(turnId);
28858
+ resolve4(turnId);
28847
28859
  }
28848
28860
  });
28849
28861
  return Promise.race([
@@ -28858,8 +28870,8 @@ var dispatchAcpPrompt = (executor, input2) => {
28858
28870
  };
28859
28871
 
28860
28872
  // ../../packages/ycodium-acp-executor/src/thread-operations.ts
28861
- var yieldTick = () => new Promise((resolve3) => {
28862
- setImmediate(resolve3);
28873
+ var yieldTick = () => new Promise((resolve4) => {
28874
+ setImmediate(resolve4);
28863
28875
  });
28864
28876
  var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
28865
28877
  function createAcpThreadOperations(options) {
@@ -28973,8 +28985,8 @@ async function raceStartAbort(promise2, signal) {
28973
28985
  }
28974
28986
 
28975
28987
  // ../../packages/ycodium-acp-executor/src/instance-kit.ts
28976
- var yieldTick2 = () => new Promise((resolve3) => {
28977
- setImmediate(resolve3);
28988
+ var yieldTick2 = () => new Promise((resolve4) => {
28989
+ setImmediate(resolve4);
28978
28990
  });
28979
28991
  var nowIso2 = () => (/* @__PURE__ */ new Date()).toISOString();
28980
28992
  function createAcpThreadTable(log, beforeStopAll) {
@@ -29092,7 +29104,7 @@ var acpProbeFailureDetail = (error62) => (error62 instanceof Error ? error62.mes
29092
29104
  // ../../packages/ycodium-acp-executor/src/probe.ts
29093
29105
  function withProbeTimeout(promise2, timeoutMs, what, signal) {
29094
29106
  signal?.throwIfAborted();
29095
- return new Promise((resolve3, reject) => {
29107
+ return new Promise((resolve4, reject) => {
29096
29108
  const onAbort = () => {
29097
29109
  clearTimeout(timer);
29098
29110
  reject(signal?.reason ?? new Error("aborted"));
@@ -29107,7 +29119,7 @@ function withProbeTimeout(promise2, timeoutMs, what, signal) {
29107
29119
  (value) => {
29108
29120
  clearTimeout(timer);
29109
29121
  signal?.removeEventListener("abort", onAbort);
29110
- resolve3(value);
29122
+ resolve4(value);
29111
29123
  },
29112
29124
  (error62) => {
29113
29125
  clearTimeout(timer);
@@ -29211,6 +29223,30 @@ async function collectProbeProcess(child, input2) {
29211
29223
  }
29212
29224
  var MAX_VERSION_OUTPUT_BYTES = 64 * 1024;
29213
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
+
29214
29250
  // ../../packages/ycodium-instance-config/src/launchArgs.ts
29215
29251
  function tokenizeShellWords(value) {
29216
29252
  const input2 = value.trim();
@@ -29347,13 +29383,13 @@ var hasDeviceCode = (output2) => deviceCodeUrl(output2) !== void 0 && deviceCode
29347
29383
  function readDeviceCodeOutput(stdout, onText) {
29348
29384
  const collected = [];
29349
29385
  let onCodeFound;
29350
- const codeFound = new Promise((resolve3) => {
29351
- onCodeFound = resolve3;
29386
+ const codeFound = new Promise((resolve4) => {
29387
+ onCodeFound = resolve4;
29352
29388
  });
29353
29389
  let quietTimer;
29354
29390
  let onQuiet;
29355
- const outputWentQuiet = new Promise((resolve3) => {
29356
- onQuiet = resolve3;
29391
+ const outputWentQuiet = new Promise((resolve4) => {
29392
+ onQuiet = resolve4;
29357
29393
  });
29358
29394
  const text4 = (async () => {
29359
29395
  const decoder = new TextDecoder();
@@ -29378,8 +29414,8 @@ function readDeviceCodeOutput(stdout, onText) {
29378
29414
  codeFound,
29379
29415
  text4.then(() => void 0),
29380
29416
  outputWentQuiet,
29381
- new Promise((resolve3) => {
29382
- silentCap = setTimeout(resolve3, SILENT_CAP_MS);
29417
+ new Promise((resolve4) => {
29418
+ silentCap = setTimeout(resolve4, SILENT_CAP_MS);
29383
29419
  })
29384
29420
  ]);
29385
29421
  clearTimeout(silentCap);
@@ -29697,11 +29733,11 @@ var createGrokTurnUsageCollector = (base) => {
29697
29733
  const attach = async (event) => {
29698
29734
  if (event.type !== "turn.completed" || !isRecord9(event.payload)) return event;
29699
29735
  if (event.payload["state"] === "completed" && !allAnswered()) {
29700
- await new Promise((resolve3) => {
29701
- const timer = setTimeout(resolve3, USAGE_GRACE_MS);
29736
+ await new Promise((resolve4) => {
29737
+ const timer = setTimeout(resolve4, USAGE_GRACE_MS);
29702
29738
  wake = () => {
29703
29739
  clearTimeout(timer);
29704
- resolve3();
29740
+ resolve4();
29705
29741
  };
29706
29742
  });
29707
29743
  wake = void 0;
@@ -31086,6 +31122,279 @@ var grokPermissionStatement = ({
31086
31122
  };
31087
31123
  };
31088
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
+
31089
31398
  // src/grokInstance.ts
31090
31399
  var RESUME_SCHEMA_VERSION = 1;
31091
31400
  function nowIso3() {
@@ -31200,7 +31509,29 @@ var createGrokInstance = (config2, host) => {
31200
31509
  turnSelection: (selection) => readTurnSelection(selection, GROK_REASONING_OPTION_ID),
31201
31510
  log: host.log
31202
31511
  });
31512
+ const sessionHome = (spawnEnv().GROK_HOME ?? process.env.GROK_HOME)?.trim();
31513
+ const sessions = createGrokNativeSessions(
31514
+ sessionHome || resolveGrokHomePath(""),
31515
+ RESUME_SCHEMA_VERSION
31516
+ );
31203
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
+ },
31204
31535
  probe,
31205
31536
  readCliVersion: (signal) => modelCatalog.readCliVersion(signal),
31206
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.5407",
3
+ "version": "0.2.5503",
4
4
  "description": "Grok executor: grok CLI over Agent Client Protocol stdio.",
5
5
  "keywords": [
6
6
  "ycodium",
@@ -21,11 +21,12 @@
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",
25
- "ycodium-acp-executor": "0.2.0",
24
+ "@ycodium-ai/plugin-api": "0.2.5503",
26
25
  "ycodium-credential-account": "0.0.0",
27
- "ycodium-instance-config": "0.0.0",
28
- "ycodium-executor-testing": "0.0.0"
26
+ "ycodium-acp-executor": "0.2.5503",
27
+ "ycodium-executor-testing": "0.0.0",
28
+ "ycodium-jsonl-stream": "0.0.0",
29
+ "ycodium-instance-config": "0.0.0"
29
30
  },
30
31
  "ycodium": {
31
32
  "plugin": "./dist/index.js",