@nowcrew/daemon 0.6.95 → 0.6.97-beta.1

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.
File without changes
@@ -33,6 +33,7 @@ export const SELF_TRAINING_EXECUTION_CAPABILITY = "self_training_execution_v1";
33
33
  export const EXECUTION_LARGE_ATTACHMENTS_CAPABILITY = "execution_attachments_300m_v1";
34
34
  export const PROJECT_SKILL_PROJECTION_CAPABILITY = "project_skill_projection_v2";
35
35
  export const MACHINE_ENVIRONMENT_CAPABILITY = "machine_environment_v1";
36
+ export const MACHINE_HELLO_ACK_CAPABILITY = "machine_hello_ack_v1";
36
37
  export const NATIVE_PROJECT_WORKSPACE_READINESS = Object.freeze({
37
38
  resolverReady: true,
38
39
  nativeRuntimeAdaptersReady: true,
@@ -62,6 +63,7 @@ export const DAEMON_CAPABILITIES = Object.freeze([
62
63
  "agent_ability_runtime_assets_v1",
63
64
  "agent_environments_v1",
64
65
  MACHINE_ENVIRONMENT_CAPABILITY,
66
+ MACHINE_HELLO_ACK_CAPABILITY,
65
67
  ]);
66
68
  /** 能力只按平台过滤,进程存活期间静态(CLAUDE.md 红线)。Windows 在 junction/copy 真机 smoke 通过前不宣告 Project Skills。 */
67
69
  export const daemonCapabilities = (runtimePlatform = process.platform, readiness = NATIVE_PROJECT_WORKSPACE_READINESS) => {
package/dist/main.js CHANGED
File without changes
@@ -1,20 +1,109 @@
1
1
  import { WebSocket } from "ws";
2
+ const HELLO_RETRY_DELAYS_MS = [1_000, 2_000, 4_000];
2
3
  /** 记住最近一次 hello 与 socket,便于存储身份变化后重发;Project Skills 状态恒为 ready。 */
3
4
  export function createMachineHelloPublisher(input) {
4
5
  let latest = null;
5
6
  let latestSocket = null;
6
- const republish = () => {
7
- if (latest === null || latestSocket?.readyState !== WebSocket.OPEN)
7
+ let acknowledged = false;
8
+ let attempts = 0;
9
+ // 发送代次:每开一轮新发送(attach/publish/republish)自增,随帧发出并要求 ack 回显。
10
+ let generation = 0;
11
+ let retryTimer;
12
+ const clearRetry = () => {
13
+ if (retryTimer !== undefined) {
14
+ clearTimeout(retryTimer);
15
+ retryTimer = undefined;
16
+ }
17
+ };
18
+ const scheduleRetry = () => {
19
+ clearRetry();
20
+ if (acknowledged || latest === null || latestSocket?.readyState !== WebSocket.OPEN)
21
+ return;
22
+ // 当前 server 不支持 ack → 不排重试(否则永远等不到确认,白跑满退避)。
23
+ if (input.ackSupported && !input.ackSupported())
24
+ return;
25
+ const delay = HELLO_RETRY_DELAYS_MS[attempts - 1];
26
+ if (delay === undefined) {
27
+ // 退避跑满仍未 ack:期待 ack(ackSupported 已声明支持)才升级为断连重连,避免旧行为下反复重连。
28
+ if (input.ackSupported !== undefined && latestSocket !== null)
29
+ input.onExhausted?.(latestSocket);
8
30
  return;
9
- const hello = input.effective({ ...latest, projectSkillsStatus: "ready" });
31
+ }
32
+ retryTimer = setTimeout(() => {
33
+ retryTimer = undefined;
34
+ sendCurrent();
35
+ }, delay);
36
+ };
37
+ function sendCurrent() {
38
+ if (latest === null || latestSocket?.readyState !== WebSocket.OPEN || acknowledged)
39
+ return;
40
+ // helloSeq 随帧发出;同一代次的多次重试复用同一 seq,ack 回显该 seq 即视为确认。
41
+ const hello = input.effective({ ...latest, projectSkillsStatus: "ready", helloSeq: generation });
42
+ const attempt = attempts + 1;
43
+ attempts = attempt;
10
44
  try {
11
45
  latestSocket.send(JSON.stringify(hello));
12
- input.onSent(hello);
46
+ input.onSent(hello, attempt);
47
+ }
48
+ catch (error) {
49
+ input.onSendFailed?.(hello, attempt, error);
13
50
  }
14
- catch { /* 非 OPEN,忽略 */ }
51
+ scheduleRetry();
52
+ }
53
+ const attach = (socket) => {
54
+ clearRetry();
55
+ latestSocket = socket;
56
+ acknowledged = false;
57
+ attempts = 0;
58
+ generation += 1;
59
+ sendCurrent();
60
+ };
61
+ const detach = (socket) => {
62
+ if (latestSocket !== socket)
63
+ return;
64
+ clearRetry();
65
+ latestSocket = null;
66
+ acknowledged = false;
67
+ attempts = 0;
68
+ };
69
+ const republish = () => {
70
+ if (latest === null || latestSocket === null)
71
+ return;
72
+ clearRetry();
73
+ acknowledged = false;
74
+ attempts = 0;
75
+ generation += 1;
76
+ sendCurrent();
77
+ };
78
+ const acknowledge = (socket, seq) => {
79
+ // 非当前 socket / 已确认 / 该 socket 已在关闭(close 后迟到的 ack)一律忽略:
80
+ // 后者会错误触发 onAck→清零强制重连计数,削弱重连上限。
81
+ if (latestSocket !== socket || latest === null || acknowledged || socket.readyState !== WebSocket.OPEN)
82
+ return;
83
+ // 代次校验:只接受回显当前代次的 ack,忽略上一代次迟到的 ack(否则会误停新代次的重试)。
84
+ // seq 缺省(老 server 不回显)时退回仅按 socket 匹配,保持兼容。
85
+ if (seq !== undefined && seq !== generation)
86
+ return;
87
+ acknowledged = true;
88
+ clearRetry();
89
+ input.onAck?.(input.effective({ ...latest, projectSkillsStatus: "ready" }));
15
90
  };
16
91
  return Object.freeze({
17
- publish: (hello, socket) => { latest = hello; latestSocket = socket; republish(); },
92
+ publish: (hello, socket) => {
93
+ latest = hello;
94
+ if (latestSocket !== socket) {
95
+ attach(socket);
96
+ return;
97
+ }
98
+ acknowledged = false;
99
+ attempts = 0;
100
+ generation += 1;
101
+ clearRetry();
102
+ sendCurrent();
103
+ },
104
+ attach,
105
+ detach,
18
106
  republish,
107
+ acknowledge,
19
108
  });
20
109
  }
package/dist/serve.js CHANGED
@@ -9,7 +9,7 @@ import { randomUUID } from "node:crypto";
9
9
  import { dslog, setSlogDefaults, drainSpool, flushSlog } from "./slog.js";
10
10
  import { mergeRunAgentResults, reportScheduledStartFailure, runAgent } from "./runner.js";
11
11
  import { buildOriginDecisionRetryPrompt, buildScheduledPrompt } from "./prompt.js";
12
- import { daemonCapabilities, daemonCapabilityBindings, } from "./machine-info.js";
12
+ import { daemonCapabilities, daemonCapabilityBindings, MACHINE_HELLO_ACK_CAPABILITY, } from "./machine-info.js";
13
13
  import { reconcileExecutionJournal } from "./execution-recovery.js";
14
14
  import { initReleaseSlog, reportDaemonConnectionClose, reportReleaseError } from "./release-channel-guard.js";
15
15
  import { handleWorkspaceControlRequest } from "./workspace-control-handler.js";
@@ -65,6 +65,10 @@ export function serve(config, opts = {}) {
65
65
  let serverCapabilities = new Set();
66
66
  let backoff = 1000;
67
67
  const maxBackoff = opts.maxBackoffMs ?? 30_000;
68
+ // hello 重试跑满仍未 ack 时主动断连重连(破 server 侧连接归属/fence 死锁)。收到 ack 清零;
69
+ // 连续多次仍拿不到 ack 则停手,退回 connected-offline,避免事故期把控制面打成重连风暴。
70
+ const maxUnackedHelloReconnects = 3;
71
+ let unackedHelloReconnects = 0;
68
72
  const testShutdown = readTestShutdownConfiguration(process.env);
69
73
  const shutdownTimeoutMs = opts.shutdownTimeoutMs ?? testShutdown.timeoutMs ?? 30_000;
70
74
  const createWebSocket = opts.createWebSocket ?? ((url) => new WebSocket(url));
@@ -160,7 +164,41 @@ export function serve(config, opts = {}) {
160
164
  : configuredIdentity;
161
165
  return currentIdentity === undefined ? hello : { ...hello, ...currentIdentity };
162
166
  },
163
- onSent: (hello) => log(`📤 已上报机器信息: ${hello.hostname} · ${hello.os} · installed=[${hello.runtimes.join(",")}] · executable=[${hello.executionRuntimes.join(",")}] · agents=[${hello.agentHandles.join(",")}]`),
167
+ onSent: (hello, attempt) => dslog("daemon.machine_hello_send_queued", "机器 hello 已进入发送队列", {
168
+ attempt, hostname: hello.hostname, daemon_version: hello.daemonVersion,
169
+ }),
170
+ onSendFailed: (hello, attempt, error) => dslog("daemon.machine_hello_send_failed", "机器 hello 发送失败", {
171
+ level: "WARN", attempt, hostname: hello.hostname, daemon_version: hello.daemonVersion,
172
+ error_message: error instanceof Error ? error.message : String(error),
173
+ }),
174
+ onAck: (hello) => {
175
+ unackedHelloReconnects = 0; // 拿到确认 = 本连接登记成功,清零强制重连计数。
176
+ dslog("daemon.machine_hello_ack_received", "机器 hello 已收到控制面确认", {
177
+ hostname: hello.hostname, daemon_version: hello.daemonVersion,
178
+ });
179
+ },
180
+ // 仅当当前 server 声明支持 ack 才重试;老 server 收不到 ack,重试无意义(退回单次上报)。
181
+ ackSupported: () => serverCapabilities.has(MACHINE_HELLO_ACK_CAPABILITY),
182
+ // 重试跑满仍未 ack → 断开当前连接,靠重连换新连接(新 epoch/token)破 server 侧 fence 死锁。
183
+ onExhausted: (socket) => {
184
+ if (stopped || ws !== socket || socket.readyState !== WebSocket.OPEN)
185
+ return;
186
+ if (unackedHelloReconnects >= maxUnackedHelloReconnects) {
187
+ dslog("daemon.machine_hello_unacked_giveup", "机器 hello 连续多次重连仍未确认,停止强制重连(保持连接,等待下次事件或人工介入)", {
188
+ level: "ERROR", reconnects: unackedHelloReconnects,
189
+ });
190
+ return;
191
+ }
192
+ unackedHelloReconnects += 1;
193
+ // 抖动重连间隔:控制面回滚时多台 daemon 会同时耗尽重试,固定间隔会同步重连造成羊群。
194
+ // close handler 用当前 backoff 排重连,这里注入 1~4s 随机值把各机错峰(open 会再把它复位)。
195
+ const jitteredBackoff = 1_000 + Math.floor(Math.random() * 3_000);
196
+ backoff = Math.min(jitteredBackoff, maxBackoff);
197
+ dslog("daemon.machine_hello_unacked_reconnect", "机器 hello 重试跑满仍未确认,断开重连换新连接", {
198
+ level: "WARN", reconnects: unackedHelloReconnects, backoff_ms: backoff,
199
+ });
200
+ socket.close(1011, "machine hello unacknowledged");
201
+ },
164
202
  });
165
203
  const machineRuntime = createMachineRuntimeEnvironment({
166
204
  config,
@@ -310,6 +348,7 @@ export function serve(config, opts = {}) {
310
348
  // 连上了才有机会把离线期间(断连原因/退出前)落盘的日志补传上去
311
349
  void drainSpool();
312
350
  // 上报本机信息 (hostname/os/daemon 版本/已装 runtimes)
351
+ machineHelloPublisher.attach(openedSocket);
313
352
  machineRuntime.open(openedSocket, { capabilities: capabilities.machineHello, beforePublish: Promise.resolve(), connectionId });
314
353
  opts.onOpen?.(ws);
315
354
  void sendSnapshot(`reconnect-${randomUUID()}`);
@@ -352,6 +391,11 @@ export function serve(config, opts = {}) {
352
391
  if (typeof decoded !== "object" || decoded === null)
353
392
  return;
354
393
  const rawType = "type" in decoded && typeof decoded.type === "string" ? decoded.type : "";
394
+ if (rawType === "machine:hello_ack") {
395
+ const ackSeq = "helloSeq" in decoded && typeof decoded.helloSeq === "number" ? decoded.helloSeq : undefined;
396
+ machineHelloPublisher.acknowledge(connectionSocket, ackSeq);
397
+ return;
398
+ }
355
399
  if (rawType === "machine:environment:get" || rawType === "machine:environment:refresh") {
356
400
  await handleMachineEnvironmentFrame(decoded, machineRuntime.provider, sendToConnection);
357
401
  return;
@@ -735,6 +779,11 @@ export function serve(config, opts = {}) {
735
779
  // ready 帧带 server 视角的 machineId/workspaceId → 作为后续所有日志的默认关联键
736
780
  const r = msg;
737
781
  setSlogDefaults({ machine_id: r.machineId, workspace_id: r.workspaceId });
782
+ // 旧 server 无此字段 → 空集合(daemon 保持全部旧行为)。ackSupported() 依赖它判断是否重试,
783
+ // 必须在任何 republish() 之前就位;否则本轮 republish 看到空集合→不排重试→整套 ack/重连机制哑火。
784
+ serverCapabilities = new Set(Array.isArray(r.serverCapabilities)
785
+ ? r.serverCapabilities.filter((c) => typeof c === "string")
786
+ : []);
738
787
  if (opts.storageRuntime !== undefined && typeof r.workspaceId === "string" && typeof r.machineId === "string") {
739
788
  const bindingSocket = ws;
740
789
  bindStorageServerIdentity(opts.storageRuntime, { workspaceId: r.workspaceId, machineId: r.machineId }, {
@@ -751,10 +800,7 @@ export function serve(config, opts = {}) {
751
800
  },
752
801
  });
753
802
  }
754
- // 旧 server 无此字段 → 空集合(daemon 保持全部旧行为)。
755
- serverCapabilities = new Set(Array.isArray(r.serverCapabilities)
756
- ? r.serverCapabilities.filter((c) => typeof c === "string")
757
- : []);
803
+ machineHelloPublisher.republish();
758
804
  if (serverCapabilities.has(PROJECT_SKILLS_CAPABILITY)) {
759
805
  void projectSkillsController.initialize()
760
806
  .then(() => projectSkillsController.publishCurrent())
@@ -1203,6 +1249,7 @@ export function serve(config, opts = {}) {
1203
1249
  });
1204
1250
  connectionSocket.on("close", (code) => {
1205
1251
  machineRuntime.close(connectionSocket);
1252
+ machineHelloPublisher.detach(connectionSocket);
1206
1253
  if (stopped || ws !== connectionSocket)
1207
1254
  return;
1208
1255
  // server 能力随连接失效;下个连接的 ready 帧重新声明(防降级重连后沿用过期能力)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nowcrew/daemon",
3
- "version": "0.6.95",
3
+ "version": "0.6.97-beta.1",
4
4
  "type": "module",
5
5
  "description": "crew daemon — 运行在用户机器:拉起/管理 agent 进程,注入 crew CLI,归一化 runtime 事件",
6
6
  "license": "Apache-2.0",
@@ -18,13 +18,6 @@
18
18
  "publishConfig": {
19
19
  "access": "public"
20
20
  },
21
- "scripts": {
22
- "daemon": "pnpm --filter @nowcrew/cli build && tsx src/main.ts",
23
- "build": "tsc -p tsconfig.json",
24
- "prepublishOnly": "pnpm build && node ../scripts/daemon-release-artifact.mjs --strict-registry",
25
- "test": "vitest run",
26
- "typecheck": "tsc --noEmit"
27
- },
28
21
  "dependencies": {
29
22
  "@agentclientprotocol/sdk": "1.2.1",
30
23
  "@nowcrew/cli": "0.4.17",
@@ -46,5 +39,11 @@
46
39
  "tsx": "^4.19.0",
47
40
  "typescript": "^5.6.0",
48
41
  "vitest": "^2.1.0"
42
+ },
43
+ "scripts": {
44
+ "daemon": "pnpm --filter @nowcrew/cli build && tsx src/main.ts",
45
+ "build": "tsc -p tsconfig.json",
46
+ "test": "vitest run",
47
+ "typecheck": "tsc --noEmit"
49
48
  }
50
- }
49
+ }