alink-cli 0.11.8 → 0.11.9

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.
package/bin/agentlink.js CHANGED
@@ -137,15 +137,20 @@ async function createSingleCredential(hub) {
137
137
  const enckey = randomBytes(32).toString("base64url");
138
138
  const credential = `als1.${token}.${enckey}`;
139
139
  saveCredential(credential, hub);
140
+ await printSingleCredential(credential, hub, true);
141
+ return credential;
142
+ }
143
+
144
+ async function printSingleCredential(credential, hub, qr = false) {
145
+ const { machineToken: token, enckey } = parseCredential(credential);
140
146
  const url = new URL("/pair", hub);
141
147
  if (url.protocol === "ws:") url.protocol = "http:";
142
148
  if (url.protocol === "wss:") url.protocol = "https:";
143
149
  url.searchParams.set("token", token);
144
150
  url.hash = new URLSearchParams({ enckey }).toString();
145
- console.log("\n在 AgentLink 网页扫码,或打开下面的链接:\n");
146
- await printQr(credential);
151
+ console.log("\n在 AgentLink 网页打开下面的本机配对链接:\n");
152
+ if (qr) await printQr(credential);
147
153
  console.log(`\n${url}\n`);
148
- return credential;
149
154
  }
150
155
 
151
156
  async function loginAndCreateCredential(hub, config) {
@@ -187,7 +192,9 @@ async function browserLogin(hub) {
187
192
  res.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" }).end("登录请求无效。");
188
193
  return;
189
194
  }
190
- res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }).end("登录成功,可以关闭此页面。");
195
+ res
196
+ .writeHead(200, { "Content-Type": "text/plain; charset=utf-8" })
197
+ .end("登录成功,可以关闭此页面。");
191
198
  clearTimeout(timer);
192
199
  server.close();
193
200
  resolve(jwt);
@@ -209,8 +216,10 @@ async function browserLogin(hub) {
209
216
  url.searchParams.set("cli_callback", `http://127.0.0.1:${address.port}/callback`);
210
217
  url.searchParams.set("cli_state", state);
211
218
  console.log(`\n请在浏览器完成 AgentLink 账号验证:\n${url}\n`);
212
- const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
213
- const commandArgs = process.platform === "win32" ? ["/c", "start", "", url.toString()] : [url.toString()];
219
+ const command =
220
+ process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
221
+ const commandArgs =
222
+ process.platform === "win32" ? ["/c", "start", "", url.toString()] : [url.toString()];
214
223
  const opener = spawn(command, commandArgs, { detached: true, stdio: "ignore" });
215
224
  opener.on("error", () => undefined);
216
225
  opener.unref();
@@ -306,11 +315,8 @@ async function showStatus() {
306
315
  }
307
316
  const statusMatchesHub =
308
317
  typeof status.hub !== "string" || normalizeHub(status.hub) === normalizeHub(hub);
309
- const hubStatus = !running || !statusMatchesHub
310
- ? "未连接"
311
- : status.hubConnected
312
- ? "已连接"
313
- : "连接中";
318
+ const hubStatus =
319
+ !running || !statusMatchesHub ? "未连接" : status.hubConnected ? "已连接" : "连接中";
314
320
  console.log(`[agentlink] 登录状态:${savedCredential(hub) ? "已登录" : "未登录"}`);
315
321
  console.log(`[agentlink] 本机服务:${running ? "运行中" : "已停止"}`);
316
322
  console.log(`[agentlink] Hub 连接:${hubStatus}`);
@@ -351,7 +357,9 @@ async function ensureSessionJwt(hub, config) {
351
357
  const login = await loginResponse.json().catch(() => ({}));
352
358
  if (!loginResponse.ok || typeof login.jwt !== "string" || !login.jwt) {
353
359
  throw new Error(
354
- login.error === "invalid_account_credentials" ? "账号或密码错误。" : login.error || "账号登录失败。",
360
+ login.error === "invalid_account_credentials"
361
+ ? "账号或密码错误。"
362
+ : login.error || "账号登录失败。",
355
363
  );
356
364
  }
357
365
  saveSessionJwt(login.jwt, hub);
@@ -392,18 +400,18 @@ async function doLegacy() {
392
400
  async function doNoTuiStart() {
393
401
  const hub = value("hub") || OFFICIAL_HUB;
394
402
  const explicit = value("token") || process.env.AGENTLINK_TOKEN;
403
+ const stored = !args.includes("--pair") ? savedCredential(hub) : undefined;
395
404
  const config =
396
- explicit || savedCredential(hub) || args.includes("--pair")
397
- ? null
398
- : await loadAgentLinkAccountConfig(hub);
405
+ explicit || stored || args.includes("--pair") ? null : await loadAgentLinkAccountConfig(hub);
399
406
  const credential =
400
407
  explicit ||
401
- (!args.includes("--pair") && savedCredential(hub)) ||
408
+ stored ||
402
409
  (args.includes("--pair")
403
410
  ? await pair(hub)
404
411
  : config?.mode === "multi"
405
412
  ? await loginAndCreateCredential(hub, config)
406
413
  : await createSingleCredential(hub));
414
+ if (!explicit && stored?.startsWith("als1.")) await printSingleCredential(stored, hub);
407
415
  if (explicit && explicit !== savedCredential(hub)) saveCredential(explicit, hub);
408
416
  if (!explicit && !args.includes("--pair")) console.log("[agentlink] 正在让这台电脑上线。");
409
417
  const { machineToken, enckey } = parseCredential(credential);
@@ -478,7 +486,8 @@ async function main() {
478
486
  if (command === "path") console.log(CREDENTIAL_FILE);
479
487
  else if (command === "status") console.log(savedCredential(hub) ? "已保存凭证" : "未保存凭证");
480
488
  else if (command === "show") console.log(savedCredential(hub) || "");
481
- else if (command === "set" && publicArgs[2] && !/\s/.test(publicArgs[2])) saveCredential(publicArgs[2], hub);
489
+ else if (command === "set" && publicArgs[2] && !/\s/.test(publicArgs[2]))
490
+ saveCredential(publicArgs[2], hub);
482
491
  else if (command === "clear") rmSync(CREDENTIAL_FILE, { force: true });
483
492
  else throw new Error("用法: alink-cli credential status|path|show|set <credential>|clear");
484
493
  return;
@@ -486,7 +495,9 @@ async function main() {
486
495
 
487
496
  if (publicArgs[0] === "qr" && legacyCredentialCommands) {
488
497
  const credential =
489
- value("token") || process.env.AGENTLINK_TOKEN || savedCredential(value("hub") || OFFICIAL_HUB);
498
+ value("token") ||
499
+ process.env.AGENTLINK_TOKEN ||
500
+ savedCredential(value("hub") || OFFICIAL_HUB);
490
501
  if (!credential) throw new Error("这台电脑还没有凭证,请先运行 npx alink-cli 完成配对。");
491
502
  await printQr(credential);
492
503
  return;
package/dist/bin.mjs CHANGED
@@ -50725,7 +50725,7 @@ const layer$12 = effect(ProviderMaintenanceRunner, fn("ProviderMaintenanceRunner
50725
50725
  })());
50726
50726
  //#endregion
50727
50727
  //#region src/orchestration/ActivityPayloadProjection.ts
50728
- function asRecord$1(value) {
50728
+ function asRecord$2(value) {
50729
50729
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
50730
50730
  }
50731
50731
  function asTrimmedString$1(value) {
@@ -50748,7 +50748,7 @@ function collectChangedFiles(value, target, seen, depth) {
50748
50748
  }
50749
50749
  return;
50750
50750
  }
50751
- const record = asRecord$1(value);
50751
+ const record = asRecord$2(value);
50752
50752
  if (!record) return;
50753
50753
  pushChangedFile(target, seen, record.path);
50754
50754
  pushChangedFile(target, seen, record.filePath);
@@ -50774,13 +50774,13 @@ function collectChangedFiles(value, target, seen, depth) {
50774
50774
  }
50775
50775
  }
50776
50776
  function projectCommandData(data) {
50777
- const item = asRecord$1(data.item);
50777
+ const item = asRecord$2(data.item);
50778
50778
  if (!item) return;
50779
50779
  const projectedItem = {};
50780
50780
  if ("command" in item) projectedItem.command = item.command;
50781
- const input = asRecord$1(item.input);
50781
+ const input = asRecord$2(item.input);
50782
50782
  if (input && "command" in input) projectedItem.input = { command: input.command };
50783
- const result = asRecord$1(item.result);
50783
+ const result = asRecord$2(item.result);
50784
50784
  if (result && "command" in result) projectedItem.result = { command: result.command };
50785
50785
  return Object.keys(projectedItem).length > 0 ? projectedItem : void 0;
50786
50786
  }
@@ -50796,7 +50796,7 @@ function summarizeToolTextOutput(value) {
50796
50796
  return null;
50797
50797
  }
50798
50798
  function projectRawOutput(value) {
50799
- const rawOutput = asRecord$1(value);
50799
+ const rawOutput = asRecord$2(value);
50800
50800
  if (!rawOutput) return;
50801
50801
  if (typeof rawOutput.totalFiles === "number" && Number.isFinite(rawOutput.totalFiles)) return {
50802
50802
  totalFiles: rawOutput.totalFiles,
@@ -50818,8 +50818,8 @@ function projectRawOutput(value) {
50818
50818
  * the full payload in persistence and the event store.
50819
50819
  */
50820
50820
  function projectActivityPayload(activity) {
50821
- const payload = asRecord$1(activity.payload);
50822
- const data = asRecord$1(payload?.data);
50821
+ const payload = asRecord$2(activity.payload);
50822
+ const data = asRecord$2(payload?.data);
50823
50823
  if (!payload || !data || payload.itemType === "mcp_tool_call") return activity;
50824
50824
  const projectedData = {};
50825
50825
  const item = projectCommandData(data);
@@ -50848,7 +50848,7 @@ function projectActivityPayload(activity) {
50848
50848
  */
50849
50849
  function isResolvableContextWindowActivity(activity) {
50850
50850
  if (activity.kind !== "context-window.updated") return false;
50851
- const usedTokens = asRecord$1(activity.payload)?.usedTokens;
50851
+ const usedTokens = asRecord$2(activity.payload)?.usedTokens;
50852
50852
  return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
50853
50853
  }
50854
50854
  /**
@@ -60178,7 +60178,7 @@ const CodexAppServerSchemaIssueKind = Literals([
60178
60178
  "Forbidden",
60179
60179
  "OneOf"
60180
60180
  ]);
60181
- const schemaIssueDiagnostics$1 = (root) => {
60181
+ const schemaIssueDiagnostics$2 = (root) => {
60182
60182
  let issueCount = 0;
60183
60183
  let maximumPathDepth = 0;
60184
60184
  const issueKinds = /* @__PURE__ */ new Set();
@@ -60283,7 +60283,7 @@ var CodexAppServerProtocolParseError = class CodexAppServerProtocolParseError ex
60283
60283
  return new CodexAppServerProtocolParseError({
60284
60284
  operation,
60285
60285
  ...context,
60286
- ...schemaIssueDiagnostics$1(cause.issue),
60286
+ ...schemaIssueDiagnostics$2(cause.issue),
60287
60287
  cause
60288
60288
  });
60289
60289
  }
@@ -60401,7 +60401,7 @@ var CodexAppServerRequestError = class CodexAppServerRequestError extends Tagged
60401
60401
  });
60402
60402
  }
60403
60403
  static invalidPayload(method, operation, cause) {
60404
- const diagnostics = schemaIssueDiagnostics$1(cause.issue);
60404
+ const diagnostics = schemaIssueDiagnostics$2(cause.issue);
60405
60405
  return new CodexAppServerRequestError({
60406
60406
  code: -32602,
60407
60407
  errorMessage: `Invalid payload for method '${method}' during '${operation}'`,
@@ -84374,7 +84374,7 @@ const AcpSchemaIssueKind = Literals([
84374
84374
  "Forbidden",
84375
84375
  "OneOf"
84376
84376
  ]);
84377
- const schemaIssueDiagnostics = (root) => {
84377
+ const schemaIssueDiagnostics$1 = (root) => {
84378
84378
  let issueCount = 0;
84379
84379
  let maximumPathDepth = 0;
84380
84380
  const issueKinds = /* @__PURE__ */ new Set();
@@ -84423,7 +84423,8 @@ var AcpProcessExitedError = class extends TaggedErrorClass()("AcpProcessExitedEr
84423
84423
  const AcpProtocolParseOperation = Literals([
84424
84424
  "encode-message",
84425
84425
  "decode-wire-message",
84426
- "decode-notification-payload"
84426
+ "decode-notification-payload",
84427
+ "decode-rpc-result"
84427
84428
  ]);
84428
84429
  var AcpProtocolParseError = class AcpProtocolParseError extends TaggedErrorClass()("AcpProtocolParseError", {
84429
84430
  operation: AcpProtocolParseOperation,
@@ -84442,7 +84443,7 @@ var AcpProtocolParseError = class AcpProtocolParseError extends TaggedErrorClass
84442
84443
  return new AcpProtocolParseError({
84443
84444
  operation,
84444
84445
  method,
84445
- ...schemaIssueDiagnostics(cause.issue),
84446
+ ...schemaIssueDiagnostics$1(cause.issue),
84446
84447
  cause
84447
84448
  });
84448
84449
  }
@@ -84569,7 +84570,7 @@ var AcpRequestError = class AcpRequestError extends TaggedErrorClass()("AcpReque
84569
84570
  });
84570
84571
  }
84571
84572
  static invalidExtensionPayload(method, cause) {
84572
- const diagnostics = schemaIssueDiagnostics(cause.issue);
84573
+ const diagnostics = schemaIssueDiagnostics$1(cause.issue);
84573
84574
  return new AcpRequestError({
84574
84575
  code: -32602,
84575
84576
  errorMessage: `Invalid payload for ACP extension method '${method}'.`,
@@ -84655,6 +84656,65 @@ const isAcpError = is(AcpError);
84655
84656
  const decodeSessionUpdate = decodeUnknownEffect(SessionNotification);
84656
84657
  const decodeElicitationComplete = decodeUnknownEffect(ElicitationCompleteNotification);
84657
84658
  const parserFactory = ndJsonRpc();
84659
+ const canonicalStopReasons$1 = /* @__PURE__ */ new Set([
84660
+ "end_turn",
84661
+ "max_tokens",
84662
+ "max_turn_requests",
84663
+ "refusal",
84664
+ "cancelled"
84665
+ ]);
84666
+ const structuralName = (value) => value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";
84667
+ const valueType = (value) => value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
84668
+ const boundedFieldNames = (value) => Object.keys(value).slice(0, 16).map(structuralName);
84669
+ const safeWireDiagnostics = (data) => {
84670
+ const lines = (typeof data === "string" ? data : new TextDecoder().decode(data)).split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
84671
+ if (lines.length === 0 || lines.length > 16) return { jsonSyntaxValid: false };
84672
+ let decoded;
84673
+ try {
84674
+ decoded = lines.map((line) => JSON.parse(line));
84675
+ } catch {
84676
+ return { jsonSyntaxValid: false };
84677
+ }
84678
+ const candidate = decoded.at(-1);
84679
+ if (candidate === null || typeof candidate !== "object" || Array.isArray(candidate)) return {
84680
+ jsonSyntaxValid: true,
84681
+ frameCount: decoded.length,
84682
+ topLevelType: valueType(candidate)
84683
+ };
84684
+ const frame = candidate;
84685
+ const result = frame.result !== null && typeof frame.result === "object" && !Array.isArray(frame.result) ? frame.result : void 0;
84686
+ const stopReason = result?.stopReason;
84687
+ return {
84688
+ jsonSyntaxValid: true,
84689
+ frameCount: decoded.length,
84690
+ topLevelFields: boundedFieldNames(frame),
84691
+ ...Object.hasOwn(frame, "jsonrpc") ? { jsonrpcType: valueType(frame.jsonrpc) } : {},
84692
+ ...Object.hasOwn(frame, "id") ? { idType: valueType(frame.id) } : {},
84693
+ ...typeof frame.method === "string" ? { method: structuralName(frame.method) } : {},
84694
+ ...result ? { resultFields: boundedFieldNames(result) } : {},
84695
+ ...result && Object.hasOwn(result, "stopReason") ? {
84696
+ stopReasonType: valueType(stopReason),
84697
+ ...typeof stopReason === "string" && canonicalStopReasons$1.has(stopReason) ? { canonicalStopReason: stopReason } : {}
84698
+ } : {}
84699
+ };
84700
+ };
84701
+ const safeTerminationDiagnostics = (error) => {
84702
+ const record = error;
84703
+ return {
84704
+ errorTag: error._tag,
84705
+ ...typeof record.operation === "string" ? { operation: structuralName(record.operation) } : {},
84706
+ ...typeof record.method === "string" ? { method: structuralName(record.method) } : {},
84707
+ ...Object.hasOwn(record, "requestId") ? {
84708
+ requestIdType: valueType(record.requestId),
84709
+ requestId: "redacted"
84710
+ } : {},
84711
+ ...typeof record.issueCount === "number" ? { issueCount: Math.min(Math.max(0, record.issueCount), 1e4) } : {},
84712
+ ...Array.isArray(record.issueKinds) ? { issueKinds: record.issueKinds.slice(0, 16).map((kind) => structuralName(String(kind))) } : {},
84713
+ ...typeof record.maximumPathDepth === "number" ? { maximumPathDepth: Math.min(Math.max(0, record.maximumPathDepth), 1e3) } : {},
84714
+ ...typeof record.pid === "number" ? { pid: record.pid } : {},
84715
+ ...typeof record.code === "number" ? { exitCode: record.code } : {}
84716
+ };
84717
+ };
84658
84718
  const makeAcpPatchedProtocol = fn("makeAcpPatchedProtocol")(function* (options) {
84659
84719
  const parser = parserFactory.makeUnsafe();
84660
84720
  const serverQueue = yield* unbounded$2();
@@ -84724,6 +84784,11 @@ const makeAcpPatchedProtocol = fn("makeAcpPatchedProtocol")(function* (options)
84724
84784
  yield* offer$1(disconnects, 0);
84725
84785
  const error = yield* classify();
84726
84786
  if (!error) return;
84787
+ yield* logProtocol({
84788
+ direction: "incoming",
84789
+ stage: "terminated",
84790
+ payload: safeTerminationDiagnostics(error)
84791
+ });
84727
84792
  yield* failAllExtPending(error);
84728
84793
  yield* emitClientProtocolError(error);
84729
84794
  if (options.onTermination) yield* options.onTermination(error);
@@ -84823,18 +84888,22 @@ const makeAcpPatchedProtocol = fn("makeAcpPatchedProtocol")(function* (options)
84823
84888
  direction: "incoming",
84824
84889
  stage: "decoded",
84825
84890
  payload: messages
84826
- })), tapErrorTag("AcpProtocolParseError", (error) => logProtocol({
84891
+ })), flatMap$1((messages) => forEach(messages, routeDecodedMessage, { discard: true })), tapErrorTag("AcpProtocolParseError", (error) => logProtocol({
84827
84892
  direction: "incoming",
84828
84893
  stage: "decode_failed",
84829
84894
  payload: {
84830
84895
  operation: error.operation,
84896
+ ...error.operation === "decode-wire-message" ? safeWireDiagnostics(data) : {},
84831
84897
  ...error.method === void 0 ? {} : { method: error.method },
84832
- ...error.requestId === void 0 ? {} : { requestId: error.requestId },
84898
+ ...error.requestId === void 0 ? {} : {
84899
+ requestIdType: valueType(error.requestId),
84900
+ requestId: "redacted"
84901
+ },
84833
84902
  ...error.issueCount === void 0 ? {} : { issueCount: error.issueCount },
84834
84903
  ...error.issueKinds === void 0 ? {} : { issueKinds: error.issueKinds },
84835
84904
  ...error.maximumPathDepth === void 0 ? {} : { maximumPathDepth: error.maximumPathDepth }
84836
84905
  }
84837
- })), flatMap$1((messages) => forEach(messages, routeDecodedMessage, { discard: true })))), matchEffect({
84906
+ })))), matchEffect({
84838
84907
  onFailure: (error) => {
84839
84908
  const normalized = isAcpError(error) ? error : new AcpTransportError({
84840
84909
  operation: "read-input-stream",
@@ -85028,7 +85097,7 @@ const ClientRpcs = make$51(ReadTextFileRpc, WriteTextFileRpc, RequestPermissionR
85028
85097
  //#endregion
85029
85098
  //#region ../effect-acp/src/_internal/shared.ts
85030
85099
  const isError = is(Error$1);
85031
- const callRpc = (method, effect) => effect.pipe(catchIf(isError, (error) => fail(AcpRequestError.fromProtocolError(error, { method }))), catchTags({ RpcClientError: (cause) => fail(new AcpTransportError({
85100
+ const callRpc = (method, effect) => effect.pipe(catchDefect((defect) => isSchemaError(defect) ? fail(AcpProtocolParseError.fromSchemaError("decode-rpc-result", method, defect)) : die(defect)), catchIf(isError, (error) => fail(AcpRequestError.fromProtocolError(error, { method }))), catchTags({ RpcClientError: (cause) => fail(new AcpTransportError({
85032
85101
  operation: "call-rpc",
85033
85102
  method,
85034
85103
  cause
@@ -85388,7 +85457,7 @@ const registerLocalToolHandlers = (input) => gen(function* () {
85388
85457
  });
85389
85458
  //#endregion
85390
85459
  //#region ../t3-shared/src/toolActivity.ts
85391
- function asRecord(value) {
85460
+ function asRecord$1(value) {
85392
85461
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
85393
85462
  }
85394
85463
  function asTrimmedString(value) {
@@ -85418,10 +85487,10 @@ function extractCommandFromTitle$1(title) {
85418
85487
  return /`([^`]+)`/u.exec(title)?.[1]?.trim() || void 0;
85419
85488
  }
85420
85489
  function extractToolCommand(data, title) {
85421
- const item = asRecord(data?.item);
85422
- const itemInput = asRecord(item?.input);
85423
- const itemResult = asRecord(item?.result);
85424
- const rawInput = asRecord(data?.rawInput);
85490
+ const item = asRecord$1(data?.item);
85491
+ const itemInput = asRecord$1(item?.input);
85492
+ const itemResult = asRecord$1(item?.result);
85493
+ const rawInput = asRecord$1(data?.rawInput);
85425
85494
  const direct = [
85426
85495
  normalizeCommandValue$1(item?.command),
85427
85496
  normalizeCommandValue$1(itemInput?.command),
@@ -85449,7 +85518,7 @@ function collectPaths(value, paths, seen, depth) {
85449
85518
  }
85450
85519
  return;
85451
85520
  }
85452
- const record = asRecord(value);
85521
+ const record = asRecord$1(value);
85453
85522
  if (!record) return;
85454
85523
  for (const key of [
85455
85524
  "path",
@@ -85508,7 +85577,7 @@ function deriveToolActivityPresentation(input) {
85508
85577
  const title = asTrimmedString(input.title);
85509
85578
  const detail = stripTrailingExitCode(asTrimmedString(input.detail));
85510
85579
  const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? "Tool";
85511
- const data = asRecord(input.data);
85580
+ const data = asRecord$1(input.data);
85512
85581
  const command = extractToolCommand(data, title);
85513
85582
  const primaryPath = extractPrimaryPath(data);
85514
85583
  const action = classifyToolAction({
@@ -85532,7 +85601,7 @@ function deriveToolActivityPresentation(input) {
85532
85601
  ...primaryPath ? { detail: primaryPath } : {}
85533
85602
  };
85534
85603
  if (action === "search") {
85535
- const query = asTrimmedString(asRecord(data?.rawInput)?.query) ?? asTrimmedString(asRecord(data?.rawInput)?.pattern) ?? asTrimmedString(asRecord(data?.rawInput)?.searchTerm);
85604
+ const query = asTrimmedString(asRecord$1(data?.rawInput)?.query) ?? asTrimmedString(asRecord$1(data?.rawInput)?.pattern) ?? asTrimmedString(asRecord$1(data?.rawInput)?.searchTerm);
85536
85605
  return {
85537
85606
  summary: "Searched files",
85538
85607
  ...query ? { detail: query } : {}
@@ -85841,6 +85910,20 @@ function parseSessionUpdateEvent(params) {
85841
85910
  function formatConfigOptionValue(value) {
85842
85911
  return JSON.stringify(value);
85843
85912
  }
85913
+ function safeProcessCommand(command) {
85914
+ const basename = command.split(/[\\/]/).at(-1) ?? "unknown";
85915
+ return basename.length <= 128 && /^[A-Za-z0-9._-]+$/.test(basename) ? basename : "unknown";
85916
+ }
85917
+ function safeArgumentKind(argument) {
85918
+ return argument.startsWith("-") ? "flag" : "positional";
85919
+ }
85920
+ function safeErrorTag(error) {
85921
+ if (error !== null && typeof error === "object" && "_tag" in error) {
85922
+ const tag = error._tag;
85923
+ if (typeof tag === "string" && /^[A-Za-z][A-Za-z0-9._-]*$/.test(tag)) return tag;
85924
+ }
85925
+ return "unknown";
85926
+ }
85844
85927
  const defaultSessionLoadTimeout = seconds(90);
85845
85928
  const defaultSessionLoadReplayIdleGap = seconds(2);
85846
85929
  var AcpSessionRuntime = class extends Service$2()("t3/provider/acp/AcpSessionRuntime") {};
@@ -85892,6 +85975,38 @@ const make$4 = (options) => gen(function* () {
85892
85975
  command: options.spawn.command,
85893
85976
  cause
85894
85977
  })));
85978
+ const logProcessEvent = (stage, payload) => options.protocolLogging?.logger?.({
85979
+ direction: "incoming",
85980
+ stage,
85981
+ payload
85982
+ }) ?? void_$1;
85983
+ yield* logProcessEvent("process_spawned", {
85984
+ command: safeProcessCommand(spawnCommand.command),
85985
+ argumentCount: Math.min(spawnCommand.args.length, 1e3),
85986
+ argumentKinds: spawnCommand.args.slice(0, 32).map(safeArgumentKind),
85987
+ pid: child.pid
85988
+ });
85989
+ yield* child.stderr.pipe(runForEach((chunk) => {
85990
+ const text = new TextDecoder().decode(chunk);
85991
+ return logProcessEvent("process_stderr", {
85992
+ pid: child.pid,
85993
+ byteLength: chunk.byteLength,
85994
+ lineBreakCount: Math.min(text.match(/\n/g)?.length ?? 0, 1e4)
85995
+ });
85996
+ }), catch_((error) => logProcessEvent("process_stderr", {
85997
+ pid: child.pid,
85998
+ errorTag: safeErrorTag(error)
85999
+ })), forkIn(runtimeScope));
86000
+ yield* child.exitCode.pipe(matchEffect({
86001
+ onFailure: (error) => logProcessEvent("process_exited", {
86002
+ pid: child.pid,
86003
+ errorTag: safeErrorTag(error)
86004
+ }),
86005
+ onSuccess: (exitCode) => logProcessEvent("process_exited", {
86006
+ pid: child.pid,
86007
+ exitCode
86008
+ })
86009
+ }), forkIn(runtimeScope));
85895
86010
  const acpContext = yield* build(layerChildProcess(child, {
85896
86011
  ...options.protocolLogging?.logIncoming !== void 0 ? { logIncoming: options.protocolLogging.logIncoming } : {},
85897
86012
  ...options.protocolLogging?.logOutgoing !== void 0 ? { logOutgoing: options.protocolLogging.logOutgoing } : {},
@@ -86642,6 +86757,13 @@ function makeAcpContentDeltaEvent(input) {
86642
86757
  }
86643
86758
  //#endregion
86644
86759
  //#region src/provider/acp/AcpNativeLogging.ts
86760
+ const canonicalStopReasons = /* @__PURE__ */ new Set([
86761
+ "end_turn",
86762
+ "max_tokens",
86763
+ "max_turn_requests",
86764
+ "refusal",
86765
+ "cancelled"
86766
+ ]);
86645
86767
  function structuralMethod(value) {
86646
86768
  return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";
86647
86769
  }
@@ -86672,7 +86794,127 @@ function summarizePayload(payload) {
86672
86794
  return { valueType: "object" };
86673
86795
  }
86674
86796
  }
86797
+ function boundedNumber(value, maximum) {
86798
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(Math.max(0, value), maximum) : void 0;
86799
+ }
86800
+ function structuralNames(value) {
86801
+ return Array.isArray(value) ? value.slice(0, 16).map((item) => typeof item === "string" ? structuralMethod(item) : "unknown") : void 0;
86802
+ }
86803
+ function schemaIssueDiagnostics(root) {
86804
+ let issueCount = 0;
86805
+ let maximumPathDepth = 0;
86806
+ const issueKinds = /* @__PURE__ */ new Set();
86807
+ const visit = (issue, pathDepth) => {
86808
+ if (issueCount >= 1e4) return;
86809
+ issueCount += 1;
86810
+ issueKinds.add(structuralMethod(issue._tag));
86811
+ maximumPathDepth = Math.max(maximumPathDepth, pathDepth);
86812
+ switch (issue._tag) {
86813
+ case "Filter":
86814
+ case "Encoding":
86815
+ visit(issue.issue, pathDepth);
86816
+ break;
86817
+ case "Pointer":
86818
+ visit(issue.issue, Math.min(pathDepth + issue.path.length, 1e3));
86819
+ break;
86820
+ case "Composite":
86821
+ case "AnyOf":
86822
+ for (const child of issue.issues.slice(0, 1e3)) visit(child, pathDepth);
86823
+ break;
86824
+ }
86825
+ };
86826
+ visit(root, 0);
86827
+ return {
86828
+ issueCount,
86829
+ issueKinds: [...issueKinds].slice(0, 16),
86830
+ maximumPathDepth
86831
+ };
86832
+ }
86833
+ function asRecord(value) {
86834
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
86835
+ }
86836
+ function summarizeRequestCause(cause) {
86837
+ for (const reason of cause.reasons) {
86838
+ if (reason._tag !== "Fail") continue;
86839
+ const failure = asRecord(reason.error);
86840
+ if (failure?._tag === "AcpProtocolParseError" && failure.operation === "decode-rpc-result") {
86841
+ const issueCount = boundedNumber(failure.issueCount, 1e4);
86842
+ const issueKinds = structuralNames(failure.issueKinds);
86843
+ const maximumPathDepth = boundedNumber(failure.maximumPathDepth, 1e3);
86844
+ return {
86845
+ failureKind: "rpc-result-decode",
86846
+ causeTags: ["AcpProtocolParseError", "SchemaError"],
86847
+ ...issueCount === void 0 ? {} : { issueCount },
86848
+ ...issueKinds ? { issueKinds } : {},
86849
+ ...maximumPathDepth === void 0 ? {} : { maximumPathDepth }
86850
+ };
86851
+ }
86852
+ const transport = failure;
86853
+ if (transport?._tag !== "AcpTransportError" || transport.operation !== "call-rpc") continue;
86854
+ const rpcClient = asRecord(transport.cause);
86855
+ if (rpcClient?._tag !== "RpcClientError") continue;
86856
+ const rpcDefect = asRecord(rpcClient.reason);
86857
+ if (rpcDefect?._tag !== "RpcClientDefect" || !isSchemaError(rpcDefect.cause)) continue;
86858
+ return {
86859
+ failureKind: "rpc-result-decode",
86860
+ causeTags: [
86861
+ "AcpTransportError",
86862
+ "RpcClientError",
86863
+ "RpcClientDefect",
86864
+ "SchemaError"
86865
+ ],
86866
+ ...schemaIssueDiagnostics(rpcDefect.cause.issue)
86867
+ };
86868
+ }
86869
+ }
86870
+ function summarizeProtocolDiagnostics(payload) {
86871
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return summarizePayload(payload);
86872
+ const record = payload;
86873
+ const requestIdType = typeof record.requestIdType === "string" ? structuralMethod(record.requestIdType) : Object.hasOwn(record, "requestId") ? record.requestId === null ? "null" : Array.isArray(record.requestId) ? "array" : typeof record.requestId : void 0;
86874
+ const issueCount = boundedNumber(record.issueCount, 1e4);
86875
+ const maximumPathDepth = boundedNumber(record.maximumPathDepth, 1e3);
86876
+ const frameCount = boundedNumber(record.frameCount, 16);
86877
+ const pid = boundedNumber(record.pid, Number.MAX_SAFE_INTEGER);
86878
+ const exitCode = boundedNumber(record.exitCode, 255);
86879
+ const byteLength = boundedNumber(record.byteLength, Number.MAX_SAFE_INTEGER);
86880
+ const lineBreakCount = boundedNumber(record.lineBreakCount, 1e4);
86881
+ const argumentCount = boundedNumber(record.argumentCount, 1e3);
86882
+ const argumentKinds = structuralNames(record.argumentKinds);
86883
+ const issueKinds = structuralNames(record.issueKinds);
86884
+ const topLevelFields = structuralNames(record.topLevelFields);
86885
+ const resultFields = structuralNames(record.resultFields);
86886
+ return {
86887
+ valueType: "object",
86888
+ ...typeof record.errorTag === "string" ? { errorTag: structuralMethod(record.errorTag) } : {},
86889
+ ...typeof record.command === "string" ? { command: structuralMethod(record.command) } : {},
86890
+ ...argumentCount === void 0 ? {} : { argumentCount },
86891
+ ...argumentKinds ? { argumentKinds } : {},
86892
+ ...typeof record.operation === "string" ? { operation: structuralMethod(record.operation) } : {},
86893
+ ...typeof record.method === "string" ? { method: structuralMethod(record.method) } : {},
86894
+ ...requestIdType ? {
86895
+ requestIdType,
86896
+ requestId: "redacted"
86897
+ } : {},
86898
+ ...issueCount === void 0 ? {} : { issueCount },
86899
+ ...issueKinds ? { issueKinds } : {},
86900
+ ...maximumPathDepth === void 0 ? {} : { maximumPathDepth },
86901
+ ...typeof record.jsonSyntaxValid === "boolean" ? { jsonSyntaxValid: record.jsonSyntaxValid } : {},
86902
+ ...frameCount === void 0 ? {} : { frameCount },
86903
+ ...typeof record.topLevelType === "string" ? { topLevelType: structuralMethod(record.topLevelType) } : {},
86904
+ ...topLevelFields ? { topLevelFields } : {},
86905
+ ...typeof record.jsonrpcType === "string" ? { jsonrpcType: structuralMethod(record.jsonrpcType) } : {},
86906
+ ...typeof record.idType === "string" ? { idType: structuralMethod(record.idType) } : {},
86907
+ ...resultFields ? { resultFields } : {},
86908
+ ...typeof record.stopReasonType === "string" ? { stopReasonType: structuralMethod(record.stopReasonType) } : {},
86909
+ ...typeof record.canonicalStopReason === "string" && canonicalStopReasons.has(record.canonicalStopReason) ? { canonicalStopReason: record.canonicalStopReason } : {},
86910
+ ...pid === void 0 ? {} : { pid },
86911
+ ...exitCode === void 0 ? {} : { exitCode },
86912
+ ...byteLength === void 0 ? {} : { byteLength },
86913
+ ...lineBreakCount === void 0 ? {} : { lineBreakCount }
86914
+ };
86915
+ }
86675
86916
  function formatRequestLogPayload(event) {
86917
+ const causeDiagnostics = event.cause ? summarizeRequestCause(event.cause) : void 0;
86676
86918
  return {
86677
86919
  method: structuralMethod(event.method),
86678
86920
  status: event.status,
@@ -86680,7 +86922,8 @@ function formatRequestLogPayload(event) {
86680
86922
  ...event.result !== void 0 ? { result: summarizePayload(event.result) } : {},
86681
86923
  ...event.cause !== void 0 ? {
86682
86924
  errorTag: causeErrorTag(event.cause),
86683
- reasonCount: event.cause.reasons.length
86925
+ reasonCount: event.cause.reasons.length,
86926
+ ...causeDiagnostics ?? {}
86684
86927
  } : {}
86685
86928
  };
86686
86929
  }
@@ -86688,7 +86931,7 @@ function formatProtocolLogPayload(event) {
86688
86931
  return {
86689
86932
  direction: event.direction,
86690
86933
  stage: event.stage,
86691
- payload: summarizePayload(event.payload)
86934
+ payload: event.stage === "decode_failed" || event.stage === "terminated" || event.stage === "process_spawned" || event.stage === "process_stderr" || event.stage === "process_exited" ? summarizeProtocolDiagnostics(event.payload) : summarizePayload(event.payload)
86692
86935
  };
86693
86936
  }
86694
86937
  const makeAcpNativeLoggerFactory = fn("makeAcpNativeLoggerFactory")(function* () {