@lobehub/cli 0.0.92 → 0.0.93

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/dist/index.js CHANGED
@@ -16853,6 +16853,7 @@ const MAX_MISSED_HEARTBEATS$1 = 3;
16853
16853
  */
16854
16854
  const CONNECT_TIMEOUT = 15e3;
16855
16855
  const METRICS_ACK_TIMEOUT_MS = 15e3;
16856
+ const COMPLETION_ACK_TIMEOUT_MS = 3e4;
16856
16857
  /**
16857
16858
  * Close reason the gateway sends when a newer socket with the same
16858
16859
  * `connectionId` takes over. `connectionId` is persisted per install, so this
@@ -16860,6 +16861,7 @@ const METRICS_ACK_TIMEOUT_MS = 15e3;
16860
16861
  * home) shows up.
16861
16862
  */
16862
16863
  const REPLACED_CLOSE_REASON = "Replaced by new connection";
16864
+ const completionAckKey = (operationId, toolCallId) => `${operationId}:${toolCallId}`;
16863
16865
  const noopLogger$1 = {
16864
16866
  debug: () => {},
16865
16867
  error: () => {},
@@ -16876,6 +16878,7 @@ var GatewayClient = class extends EventEmitter {
16876
16878
  missedHeartbeats = 0;
16877
16879
  status = "disconnected";
16878
16880
  pendingMetricAcks = /* @__PURE__ */ new Map();
16881
+ pendingCompletionAcks = /* @__PURE__ */ new Map();
16879
16882
  intentionalDisconnect = false;
16880
16883
  /**
16881
16884
  * When each socket abandoned mid-handshake was abandoned. Only such a socket
@@ -17010,6 +17013,37 @@ var GatewayClient = class extends EventEmitter {
17010
17013
  });
17011
17014
  });
17012
17015
  }
17016
+ /**
17017
+ * Send the late result of a call the device kept watching, and resolve with
17018
+ * the gateway's verdict. Rejects when not connected, when the connection drops
17019
+ * mid-flight, or when no ack arrives in time — the caller keeps the result and
17020
+ * sends it again, which is safe because the server applies it at most once.
17021
+ */
17022
+ reportToolCallCompletion(completion) {
17023
+ if (this.status !== "connected" || this.ws?.readyState !== wrapper_default.OPEN) return Promise.reject(/* @__PURE__ */ new Error("Gateway not connected"));
17024
+ const key = completionAckKey(completion.operationId, completion.toolCallId);
17025
+ this.pendingCompletionAcks.get(key)?.reject(/* @__PURE__ */ new Error("Superseded by a newer send"));
17026
+ return new Promise((resolve, reject) => {
17027
+ const timer = setTimeout(() => {
17028
+ this.pendingCompletionAcks.delete(key);
17029
+ reject(/* @__PURE__ */ new Error("Timed out waiting for tool_call_completion_ack"));
17030
+ }, COMPLETION_ACK_TIMEOUT_MS);
17031
+ this.pendingCompletionAcks.set(key, {
17032
+ reject: (error) => {
17033
+ clearTimeout(timer);
17034
+ reject(error);
17035
+ },
17036
+ resolve: (ack) => {
17037
+ clearTimeout(timer);
17038
+ resolve(ack);
17039
+ }
17040
+ });
17041
+ this.sendMessage({
17042
+ ...completion,
17043
+ type: "tool_call_completion"
17044
+ });
17045
+ });
17046
+ }
17013
17047
  sendSystemInfoResponse(response) {
17014
17048
  this.sendMessage({
17015
17049
  ...response,
@@ -17134,6 +17168,14 @@ var GatewayClient = class extends EventEmitter {
17134
17168
  this.logger.warn("Received auth_expired from gateway");
17135
17169
  this.emit("auth_expired");
17136
17170
  break;
17171
+ case "tool_call_completion_ack": {
17172
+ const { type: _type, ...ack } = message;
17173
+ const key = completionAckKey(ack.operationId, ack.toolCallId);
17174
+ const pending = this.pendingCompletionAcks.get(key);
17175
+ this.pendingCompletionAcks.delete(key);
17176
+ pending?.resolve(ack);
17177
+ break;
17178
+ }
17137
17179
  case "device_metrics_ack": {
17138
17180
  const pending = this.pendingMetricAcks.get(message.batchId);
17139
17181
  this.pendingMetricAcks.delete(message.batchId);
@@ -17272,6 +17314,8 @@ var GatewayClient = class extends EventEmitter {
17272
17314
  rejectPendingMetricAcks() {
17273
17315
  for (const pending of this.pendingMetricAcks.values()) pending.reject(/* @__PURE__ */ new Error("Gateway connection closed"));
17274
17316
  this.pendingMetricAcks.clear();
17317
+ for (const pending of this.pendingCompletionAcks.values()) pending.reject(/* @__PURE__ */ new Error("Gateway connection closed"));
17318
+ this.pendingCompletionAcks.clear();
17275
17319
  }
17276
17320
  closeWebSocket() {
17277
17321
  this.tunnelHost?.closeAll("DEVICE_DISCONNECTED");
@@ -17308,6 +17352,102 @@ var GatewayClient = class extends EventEmitter {
17308
17352
  }
17309
17353
  };
17310
17354
 
17355
+ //#endregion
17356
+ //#region ../../packages/device-gateway-client/src/completionWatch.ts
17357
+ const LOCAL_SYSTEM_IDENTIFIER = "lobe-local-system";
17358
+ /** Longest a device keeps a finished result it could not deliver. */
17359
+ const DEFAULT_COMPLETION_MAX_AGE_MS = 7200 * 1e3;
17360
+ const INITIAL_RETRY_DELAY_MS = 5e3;
17361
+ const MAX_RETRY_DELAY_MS = 6e4;
17362
+ /**
17363
+ * The shell a `runCommand` reply left running, when the server asked for a
17364
+ * late result. Mirrors the server's park predicate: a background spawn or a
17365
+ * foreground call that outlived its wait window, never a command that already
17366
+ * has an exit code or failed to start.
17367
+ */
17368
+ const resolveWatchableShell = (request, result) => {
17369
+ if (!request.completion?.toolCallId || !request.operationId) return void 0;
17370
+ if (request.toolCall.type === "mcp") return void 0;
17371
+ if (request.toolCall.identifier !== LOCAL_SYSTEM_IDENTIFIER) return void 0;
17372
+ if (request.toolCall.apiName !== "runCommand") return void 0;
17373
+ if (result.success === false) return void 0;
17374
+ const state = result.state;
17375
+ if (!state || typeof state !== "object") return void 0;
17376
+ if (typeof state.commandId !== "string" || !state.commandId) return void 0;
17377
+ if (state.error) return void 0;
17378
+ if (state.exitCode !== void 0 && state.exitCode !== null) return void 0;
17379
+ if (state.isBackground === true || state.running === true) return state.commandId;
17380
+ };
17381
+ /** Mark a reply so the server knows a late result will follow and may park. */
17382
+ const withCompletionWatch = (result) => ({
17383
+ ...result,
17384
+ state: {
17385
+ ...result.state,
17386
+ completionWatch: true
17387
+ }
17388
+ });
17389
+ const defaultSleep = (ms, wake) => Promise.race([new Promise((resolve) => setTimeout(resolve, ms)), wake]);
17390
+ /**
17391
+ * Watch a command the device left running and deliver its final result.
17392
+ *
17393
+ * Observation is local (the device waits on its own process), so the wait costs
17394
+ * the server nothing. Delivery retries with backoff — sooner when the gateway
17395
+ * reconnects — until the gateway answers `delivered` or `rejected`, or the
17396
+ * result is older than `maxAgeMs` (the server has timed the call out by then).
17397
+ */
17398
+ const watchToolCallCompletion = async ({ getReporter, logger, maxAgeMs = DEFAULT_COMPLETION_MAX_AGE_MS, observe, operationId, sleep = defaultSleep, toolCallId }) => {
17399
+ const startedAt = Date.now();
17400
+ let result;
17401
+ for (;;) {
17402
+ let observed;
17403
+ try {
17404
+ observed = await observe();
17405
+ } catch (error) {
17406
+ const message = error instanceof Error ? error.message : String(error);
17407
+ observed = {
17408
+ done: true,
17409
+ result: {
17410
+ content: `Failed to observe the command: ${message}`,
17411
+ error: message,
17412
+ success: false
17413
+ }
17414
+ };
17415
+ }
17416
+ if (observed.done) {
17417
+ result = observed.result;
17418
+ break;
17419
+ }
17420
+ if (Date.now() - startedAt > maxAgeMs) return "expired";
17421
+ }
17422
+ let delay = INITIAL_RETRY_DELAY_MS;
17423
+ for (;;) {
17424
+ const reporter = getReporter();
17425
+ if (reporter) try {
17426
+ const ack = await reporter.reportToolCallCompletion({
17427
+ operationId,
17428
+ result,
17429
+ toolCallId
17430
+ });
17431
+ if (ack.status !== "retry") {
17432
+ logger?.info(`Completion for ${toolCallId} ${ack.status}`, ack.reason ?? "");
17433
+ return ack.status;
17434
+ }
17435
+ logger?.warn(`Completion for ${toolCallId} not taken yet`, ack.reason ?? "");
17436
+ } catch (error) {
17437
+ logger?.warn(`Completion for ${toolCallId} not sent`, error instanceof Error ? error.message : String(error));
17438
+ }
17439
+ if (Date.now() - startedAt > maxAgeMs) return "expired";
17440
+ let onConnected;
17441
+ const wake = new Promise((resolve) => {
17442
+ onConnected = resolve;
17443
+ reporter?.on("connected", resolve);
17444
+ });
17445
+ await sleep(delay, wake);
17446
+ if (onConnected) reporter?.off("connected", onConnected);
17447
+ delay = Math.min(delay * 2, MAX_RETRY_DELAY_MS);
17448
+ }
17449
+ };
17450
+
17311
17451
  //#endregion
17312
17452
  //#region ../../packages/const/src/agentDocument.ts
17313
17453
  const MARKDOWN_MIME_TYPES = ["text/markdown", "text/x-markdown"];
@@ -552543,6 +552683,7 @@ var ComputerRuntime = class {
552543
552683
  isBackground: args.background || false,
552544
552684
  output: r.output,
552545
552685
  outputFiles,
552686
+ running: r.running,
552546
552687
  sandboxed: r.sandboxed,
552547
552688
  stderr: r.stderr,
552548
552689
  stdout: r.stdout,
@@ -553661,6 +553802,52 @@ async function executeToolCall(apiName, argsStr, timeout, auth) {
553661
553802
  }
553662
553803
  }
553663
553804
 
553805
+ //#endregion
553806
+ //#region src/commands/connect/completionWatch.ts
553807
+ /** The longest single local wait for a watched command (the shell's own cap). */
553808
+ const COMPLETION_OBSERVATION_TIMEOUT_MS = 6e5;
553809
+ /**
553810
+ * The reply for a finished tool call. When the server asked for a late result
553811
+ * and the command is still running, the reply says this device keeps watching
553812
+ * (`state.completionWatch`) and the final `getCommandOutput` answer is reported
553813
+ * once the process exits — the server parks the run instead of the model
553814
+ * polling.
553815
+ *
553816
+ * The watch runs outside `maintenance.run` on purpose: a command can run for
553817
+ * hours, and a CLI restart must not wait on it. A restart loses the watch; the
553818
+ * server's own deadline then closes the call.
553819
+ */
553820
+ const prepareCompletionReply = (request, result, { getReporter, getToolAuth, logger }) => {
553821
+ const shellId = resolveWatchableShell(request, result);
553822
+ if (!shellId || !request.operationId || !request.completion) return result;
553823
+ watchToolCallCompletion({
553824
+ getReporter,
553825
+ logger,
553826
+ observe: async () => {
553827
+ const output = await executeToolCall("getCommandOutput", JSON.stringify({
553828
+ shell_id: shellId,
553829
+ timeout: COMPLETION_OBSERVATION_TIMEOUT_MS
553830
+ }), COMPLETION_OBSERVATION_TIMEOUT_MS, getToolAuth());
553831
+ const running = output.state?.running === true;
553832
+ const final = {
553833
+ content: output.content,
553834
+ success: output.success
553835
+ };
553836
+ if (output.error !== void 0) final.error = output.error;
553837
+ if (output.state !== void 0) final.state = output.state;
553838
+ return {
553839
+ done: output.success === false || !running,
553840
+ result: final
553841
+ };
553842
+ },
553843
+ operationId: request.operationId,
553844
+ toolCallId: request.completion.toolCallId
553845
+ }).catch((err) => {
553846
+ logger.error(`Completion watch for ${shellId} failed: ${err instanceof Error ? err.message : err}`);
553847
+ });
553848
+ return withCompletionWatch(result);
553849
+ };
553850
+
553664
553851
  //#endregion
553665
553852
  //#region src/commands/connect/handlers.ts
553666
553853
  /**
@@ -553732,15 +553919,24 @@ function bindGatewayClientHandlers(client, ctx, connectionWorkspaceId) {
553732
553919
  const executionTimeMs = Math.round(performance.now() - startedAt);
553733
553920
  if (isDaemonChild) appendLog(`[RESULT] ${result.success ? "OK" : "FAIL"} ${executionTimeMs}ms${operationId ? ` op=${operationId}` : ""} (${requestId})`);
553734
553921
  else log$13.toolResult(requestId, result.success, result.content, operationId);
553922
+ const reply = prepareCompletionReply(request, {
553923
+ content: result.content,
553924
+ error: result.error,
553925
+ executionTimeMs,
553926
+ state: result.state,
553927
+ success: result.success
553928
+ }, {
553929
+ getReporter: () => client,
553930
+ getToolAuth,
553931
+ logger: {
553932
+ error: (...args) => error(args.join(" ")),
553933
+ info: (...args) => isDaemonChild ? appendLog(`[COMPLETION] ${args.join(" ")}`) : info(args.join(" ")),
553934
+ warn: (...args) => error(args.join(" "))
553935
+ }
553936
+ });
553735
553937
  client.sendToolCallResponse({
553736
553938
  requestId,
553737
- result: {
553738
- content: result.content,
553739
- error: result.error,
553740
- executionTimeMs,
553741
- state: result.state,
553742
- success: result.success
553743
- }
553939
+ result: reply
553744
553940
  });
553745
553941
  });
553746
553942
  client.on("rpc_request", async (request) => {
package/man/man1/lh.1 CHANGED
@@ -1,6 +1,6 @@
1
1
  .\" Code generated by `npm run man:generate`; DO NOT EDIT.
2
2
  .\" Manual command details come from the Commander command tree.
3
- .TH LH 1 "" "@lobehub/cli 0.0.92" "User Commands"
3
+ .TH LH 1 "" "@lobehub/cli 0.0.93" "User Commands"
4
4
  .SH NAME
5
5
  lh \- LobeHub CLI \- manage and connect to LobeHub services
6
6
  .SH SYNOPSIS
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lobehub/cli",
3
- "version": "0.0.92",
3
+ "version": "0.0.93",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/lobehub/lobehub",
@@ -83,5 +83,5 @@
83
83
  "access": "public",
84
84
  "registry": "https://registry.npmjs.org"
85
85
  },
86
- "gitHead": "5a04f3b839add50e50a394ecf106713cae7c0707"
86
+ "gitHead": "e0724291bf29d429da630f0505b53b40a5e11b89"
87
87
  }