@clawos-dev/clawd 0.2.686 → 0.2.689

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/cli.cjs CHANGED
@@ -43380,7 +43380,7 @@ var require_websocket = __commonJS({
43380
43380
  var http2 = require("http");
43381
43381
  var net2 = require("net");
43382
43382
  var tls = require("tls");
43383
- var { randomBytes: randomBytes2, createHash: createHash5 } = require("crypto");
43383
+ var { randomBytes: randomBytes2, createHash: createHash6 } = require("crypto");
43384
43384
  var { Duplex, Readable: Readable4 } = require("stream");
43385
43385
  var { URL: URL2 } = require("url");
43386
43386
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -44040,7 +44040,7 @@ var require_websocket = __commonJS({
44040
44040
  abortHandshake(websocket, socket, "Invalid Upgrade header");
44041
44041
  return;
44042
44042
  }
44043
- const digest = createHash5("sha1").update(key + GUID).digest("base64");
44043
+ const digest = createHash6("sha1").update(key + GUID).digest("base64");
44044
44044
  if (res.headers["sec-websocket-accept"] !== digest) {
44045
44045
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
44046
44046
  return;
@@ -44407,7 +44407,7 @@ var require_websocket_server = __commonJS({
44407
44407
  var EventEmitter2 = require("events");
44408
44408
  var http2 = require("http");
44409
44409
  var { Duplex } = require("stream");
44410
- var { createHash: createHash5 } = require("crypto");
44410
+ var { createHash: createHash6 } = require("crypto");
44411
44411
  var extension2 = require_extension();
44412
44412
  var PerMessageDeflate2 = require_permessage_deflate();
44413
44413
  var subprotocol2 = require_subprotocol();
@@ -44708,7 +44708,7 @@ var require_websocket_server = __commonJS({
44708
44708
  );
44709
44709
  }
44710
44710
  if (this._state > RUNNING) return abortHandshake(socket, 503);
44711
- const digest = createHash5("sha1").update(key + GUID).digest("base64");
44711
+ const digest = createHash6("sha1").update(key + GUID).digest("base64");
44712
44712
  const headers = [
44713
44713
  "HTTP/1.1 101 Switching Protocols",
44714
44714
  "Upgrade: websocket",
@@ -53581,6 +53581,10 @@ async function centralRequest(opts, path111, init) {
53581
53581
  }
53582
53582
  clearTimeout(timer);
53583
53583
  if (res.status === 401) {
53584
+ const detail = await res.json().catch(() => null);
53585
+ if (path111 === "/api/persona-cloud/github/oauth/token" && detail?.errorCode === "GITHUB_REAUTH_REQUIRED") {
53586
+ throw new CentralClientError("API_ERROR", typeof detail.message === "string" ? detail.message : "\u8BF7\u91CD\u65B0\u5173\u8054 GitHub", void 0, 401);
53587
+ }
53584
53588
  throw new CentralClientError("UNAUTHORIZED", "login pass rejected by center");
53585
53589
  }
53586
53590
  if (!res.ok) {
@@ -53759,11 +53763,12 @@ async function centralGithubAuthToken(opts) {
53759
53763
  const body = await centralRequest(opts, "/api/persona-cloud/github/oauth/token", {
53760
53764
  method: "POST",
53761
53765
  bearer: opts.loginPass,
53762
- body: {}
53766
+ body: { ...opts.rejectedToken ? { rejectedToken: opts.rejectedToken } : {} }
53763
53767
  });
53764
53768
  if (body.token === null || body.token === void 0) return void 0;
53765
53769
  if (typeof body.token !== "string" || !body.token) throw new CentralClientError("BAD_RESPONSE", "github/oauth/token: malformed token");
53766
- return { token: body.token, login: typeof body.login === "string" ? body.login : "" };
53770
+ if (body.expiresAt !== void 0 && (typeof body.expiresAt !== "string" || !Number.isFinite(Date.parse(body.expiresAt)))) throw new CentralClientError("BAD_RESPONSE", "github/oauth/token: malformed expiry");
53771
+ return { token: body.token, login: typeof body.login === "string" ? body.login : "", ...typeof body.expiresAt === "string" ? { expiresAt: body.expiresAt } : {} };
53767
53772
  }
53768
53773
  async function centralClaimPublisher(opts) {
53769
53774
  await centralRequest(opts, `/api/persona-cloud/personas/${encodeURIComponent(opts.personaId)}/publisher`, {
@@ -57519,8 +57524,8 @@ function createGhRunner(defaults) {
57519
57524
  const baseTimeoutMs = defaults?.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
57520
57525
  const spawn17 = defaults?.execFile ?? import_node_child_process9.execFile;
57521
57526
  return {
57522
- run(args, opts) {
57523
- const token = defaults?.token?.();
57527
+ async run(args, opts) {
57528
+ const token = await defaults?.token?.();
57524
57529
  return new Promise((resolve9, reject) => {
57525
57530
  spawn17(
57526
57531
  "gh",
@@ -62165,23 +62170,38 @@ function createGithubApi(args) {
62165
62170
  const seal = args.seal ?? sealWithSodium;
62166
62171
  const timeoutMs = args.timeoutMs ?? TIMEOUT_MS;
62167
62172
  const secretsPath = (slug, environment) => `/repos/${slug}/${environment ? `environments/${encodeURIComponent(environment)}` : "actions"}/secrets`;
62168
- async function request(method, path111, body) {
62169
- let res;
62170
- try {
62171
- res = await doFetch(`${API}${path111}`, {
62172
- method,
62173
- headers: {
62174
- Authorization: `Bearer ${args.token}`,
62175
- Accept: "application/vnd.github+json",
62176
- "X-GitHub-Api-Version": "2022-11-28",
62177
- ...body !== void 0 ? { "Content-Type": "application/json" } : {}
62178
- },
62179
- ...body !== void 0 ? { body: JSON.stringify(body) } : {},
62180
- signal: AbortSignal.timeout(timeoutMs)
62181
- });
62182
- } catch (err) {
62183
- throw new GithubApiError(0, `\u8FDE\u4E0D\u4E0A GitHub\uFF1A${err instanceof Error ? err.message : String(err)}`);
62173
+ async function authenticatedFetch(path111, init) {
62174
+ let token = args.identity ? (await args.identity.refresh())?.token : args.token;
62175
+ if (!token) throw new GithubApiError(401, "\u8BF7\u5148\u5173\u8054 GitHub");
62176
+ for (let attempt = 0; ; attempt++) {
62177
+ let res;
62178
+ try {
62179
+ res = await doFetch(API + path111, {
62180
+ ...init,
62181
+ headers: { ...init.headers, Authorization: "Bearer " + token },
62182
+ signal: AbortSignal.timeout(timeoutMs)
62183
+ });
62184
+ } catch (err) {
62185
+ throw new GithubApiError(0, "\u8FDE\u4E0D\u4E0A GitHub\uFF1A" + (err instanceof Error ? err.message : String(err)));
62186
+ }
62187
+ if (res.status !== 401 || attempt !== 0 || !args.identity) return res;
62188
+ const renewed = await args.identity.recover(token);
62189
+ if (!renewed || renewed.token === token) return res;
62190
+ await res.body?.cancel();
62191
+ token = renewed.token;
62184
62192
  }
62193
+ }
62194
+ async function request(method, path111, body) {
62195
+ const res = await authenticatedFetch(path111, {
62196
+ method,
62197
+ redirect: "error",
62198
+ headers: {
62199
+ Accept: "application/vnd.github+json",
62200
+ "X-GitHub-Api-Version": "2022-11-28",
62201
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
62202
+ },
62203
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
62204
+ });
62185
62205
  const text = await res.text();
62186
62206
  let json = void 0;
62187
62207
  if (text) {
@@ -62266,8 +62286,8 @@ function createGithubApi(args) {
62266
62286
  const signal = AbortSignal.timeout(timeoutMs);
62267
62287
  let res;
62268
62288
  try {
62269
- res = await doFetch(`${API}/repos/${slug}/actions/artifacts/${artifactId}/zip`, {
62270
- headers: { Authorization: `Bearer ${args.token}`, Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" },
62289
+ res = await authenticatedFetch(`/repos/${slug}/actions/artifacts/${artifactId}/zip`, {
62290
+ headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" },
62271
62291
  redirect: "manual",
62272
62292
  signal
62273
62293
  });
@@ -62892,7 +62912,8 @@ function networkOptions(auth) {
62892
62912
  return auth?.source === "file" ? { prefix: [...QUIET_GIT_ARGS, "-c", "credential.helper=", "-c", `credential.helper=${INLINE_HELPER}`], env: { ...QUIET_GIT_ENV, CLAWD_GITHUB_TOKEN: auth.token } } : { prefix: [...QUIET_GIT_ARGS], env: QUIET_GIT_ENV };
62893
62913
  }
62894
62914
  async function networkGit(exec, dir, auth, args, what) {
62895
- const opts = networkOptions(auth);
62915
+ const current = typeof auth === "function" ? await auth() : auth;
62916
+ const opts = networkOptions(current);
62896
62917
  return mustGit(exec, dir, [...opts.prefix, ...args], what, { timeoutMs: 12e4, env: opts.env });
62897
62918
  }
62898
62919
  async function gitPush(exec, dir, auth, refspec = "HEAD:refs/heads/integration") {
@@ -63807,7 +63828,11 @@ function buildDeployHandlers(deps) {
63807
63828
  async function requireGithub() {
63808
63829
  const auth = await deps.githubIdentity.refresh();
63809
63830
  if (!auth) throw new ClawdError(ERROR_CODES.INTERNAL, NO_GITHUB_AUTH);
63810
- return { auth, api: deps.githubApi(auth.token) };
63831
+ return { auth: async () => {
63832
+ const current = await deps.githubIdentity.refresh();
63833
+ if (!current) throw new ClawdError(ERROR_CODES.INTERNAL, NO_GITHUB_AUTH);
63834
+ return current;
63835
+ }, api: deps.githubApi(auth.token) };
63811
63836
  }
63812
63837
  function mustPersona(personaId2) {
63813
63838
  if (!deps.hasPersona(personaId2)) {
@@ -65032,13 +65057,82 @@ function createGithubIdentity(deps) {
65032
65057
  let pendingOauth = null;
65033
65058
  let staleCenterToken;
65034
65059
  const listeners = /* @__PURE__ */ new Set();
65035
- async function refresh() {
65036
- const mine = ++seq;
65037
- const resolved = await deps.resolve();
65038
- if (mine === seq) auth = resolved;
65039
- return resolved;
65060
+ let managedToken;
65061
+ const oauthCandidate = (token) => /^gh[ou]_/.test(token);
65062
+ const oauthManaged = (token) => oauthCandidate(token) && (managedToken === token || deps.isManaged?.(token) === true);
65063
+ let acquisition;
65064
+ let centerFlight;
65065
+ let centerCache;
65066
+ let writes = Promise.resolve();
65067
+ function remember(got) {
65068
+ const expiry = got.expiresAt ? Date.parse(got.expiresAt) - 6e4 : Infinity;
65069
+ centerCache = { token: got.token, until: Math.min(deps.now() + 2e4, expiry) };
65070
+ }
65071
+ function persist(token, generation, managed = false) {
65072
+ const write = writes.catch(() => {
65073
+ }).then(async () => {
65074
+ if (generation !== seq) return;
65075
+ const stored = await deps.store(token);
65076
+ if (generation !== seq) return;
65077
+ deps.markManaged?.(managed ? token : void 0);
65078
+ managedToken = managed ? token : void 0;
65079
+ auth = stored;
65080
+ statusCache.clear();
65081
+ pendingOauth = null;
65082
+ for (const cb of listeners) cb();
65083
+ });
65084
+ writes = write;
65085
+ return write;
65086
+ }
65087
+ async function syncCenter(local, rejectedToken) {
65088
+ if (!oauthCandidate(local.token)) return local;
65089
+ const managed = oauthManaged(local.token);
65090
+ if (!rejectedToken && centerCache?.token === local.token && deps.now() < centerCache.until) return local;
65091
+ if (centerFlight) return centerFlight;
65092
+ const generation = seq;
65093
+ const task = (async () => {
65094
+ let got;
65095
+ try {
65096
+ got = await deps.oauth.token(rejectedToken);
65097
+ } catch (err) {
65098
+ if (managed) throw err;
65099
+ return local;
65100
+ }
65101
+ if (generation !== seq) return auth;
65102
+ if (!got || !managed && got.token !== local.token) {
65103
+ remember({ token: local.token });
65104
+ return local;
65105
+ }
65106
+ if (!managed || got.token !== local.token) await persist(got.token, generation, true);
65107
+ if (generation !== seq) return auth;
65108
+ remember(got);
65109
+ return auth ?? local;
65110
+ })().finally(() => {
65111
+ if (centerFlight === task) centerFlight = void 0;
65112
+ });
65113
+ centerFlight = task;
65114
+ return task;
65115
+ }
65116
+ function refresh() {
65117
+ if (acquisition) return acquisition;
65118
+ const generation = seq;
65119
+ const task = (async () => {
65120
+ const resolved = await deps.resolve();
65121
+ if (generation !== seq) return auth;
65122
+ auth = resolved;
65123
+ return resolved ? syncCenter(resolved) : void 0;
65124
+ })().finally(() => {
65125
+ if (acquisition === task) acquisition = void 0;
65126
+ });
65127
+ acquisition = task;
65128
+ return task;
65129
+ }
65130
+ async function recover(rejectedToken) {
65131
+ const current = await refresh();
65132
+ if (!current || current.token !== rejectedToken || !oauthManaged(current.token)) return current;
65133
+ return syncCenter(current, rejectedToken);
65040
65134
  }
65041
- async function whoami(a2) {
65135
+ async function whoami(a2, recovering = false) {
65042
65136
  const hit = statusCache.get(a2.token);
65043
65137
  if (hit && deps.now() - hit.at < cacheMs) return hit.status;
65044
65138
  let status2;
@@ -65046,19 +65140,26 @@ function createGithubIdentity(deps) {
65046
65140
  const { login } = await deps.api(a2.token).whoami();
65047
65141
  status2 = { status: "authorized", login, source: a2.source };
65048
65142
  } catch (err) {
65143
+ if (!recovering && err instanceof GithubApiError && err.status === 401 && oauthManaged(a2.token)) {
65144
+ try {
65145
+ const renewed = await recover(a2.token);
65146
+ if (renewed && renewed.token !== a2.token) return whoami(renewed, true);
65147
+ } catch (recoveryError) {
65148
+ return { status: "invalid", message: recoveryError instanceof Error ? recoveryError.message : String(recoveryError) };
65149
+ }
65150
+ }
65049
65151
  status2 = { status: "invalid", message: err instanceof Error ? err.message : String(err) };
65050
65152
  }
65051
65153
  statusCache.set(a2.token, { at: deps.now(), status: status2 });
65052
65154
  return status2;
65053
65155
  }
65054
65156
  async function adopt(token) {
65055
- auth = await deps.store(token);
65056
- seq++;
65057
- statusCache.clear();
65058
- pendingOauth = null;
65059
- for (const cb of listeners) cb();
65157
+ const generation = ++seq;
65158
+ centerCache = void 0;
65159
+ await persist(token, generation);
65060
65160
  }
65061
65161
  async function claimCenterToken() {
65162
+ const generation = seq;
65062
65163
  let got;
65063
65164
  try {
65064
65165
  got = await deps.oauth.token();
@@ -65072,7 +65173,9 @@ function createGithubIdentity(deps) {
65072
65173
  if (err instanceof GithubApiError && err.status === 401) staleCenterToken = got.token;
65073
65174
  return false;
65074
65175
  }
65075
- await adopt(got.token);
65176
+ if (generation !== seq) return false;
65177
+ await persist(got.token, ++seq, true);
65178
+ remember(got);
65076
65179
  return true;
65077
65180
  }
65078
65181
  async function settlePendingOauth() {
@@ -65090,13 +65193,19 @@ function createGithubIdentity(deps) {
65090
65193
  }
65091
65194
  async function status() {
65092
65195
  await settlePendingOauth();
65093
- const a2 = await refresh();
65196
+ let a2;
65197
+ try {
65198
+ a2 = await refresh();
65199
+ } catch (err) {
65200
+ return { status: "invalid", message: err instanceof Error ? err.message : String(err) };
65201
+ }
65094
65202
  const current = a2 ? await whoami(a2) : { status: "missing" };
65095
65203
  return pendingOauth && current.status !== "authorized" ? { status: "pending", authUrl: pendingOauth.authUrl } : current;
65096
65204
  }
65097
65205
  return {
65098
65206
  cached: () => auth,
65099
65207
  refresh,
65208
+ recover,
65100
65209
  status,
65101
65210
  adopt,
65102
65211
  async authorize(raw) {
@@ -65111,7 +65220,7 @@ function createGithubIdentity(deps) {
65111
65220
  },
65112
65221
  // 已有身份时重新授权;直接返回 pending 链接,不能经 status() 被旧的 authorized 状态遮掉。
65113
65222
  async oauthStart(returnTo) {
65114
- const local = await refresh();
65223
+ const local = await deps.resolve();
65115
65224
  if (!local && await claimCenterToken()) return status();
65116
65225
  try {
65117
65226
  staleCenterToken = (await deps.oauth.token())?.token;
@@ -75363,7 +75472,7 @@ function computeMethodAccess(args) {
75363
75472
  }
75364
75473
 
75365
75474
  // src/version.ts
75366
- var version = "0.2.686".length > 0 ? "0.2.686" : "dev";
75475
+ var version = "0.2.689".length > 0 ? "0.2.689" : "dev";
75367
75476
 
75368
75477
  // src/cli-probe/probe.ts
75369
75478
  var fs86 = __toESM(require("fs"), 1);
@@ -78051,7 +78160,14 @@ async function startDaemon(config) {
78051
78160
  const localSecretsDir = import_node_path89.default.join(config.dataDir, LOCAL_SECRETS_DIRNAME);
78052
78161
  const readSecrets = () => readSecretTable({ bundleRoot: secretsBundleRoot, overrideDir: localSecretsDir, logger });
78053
78162
  const githubTokenFile = import_node_path89.default.join(localSecretsDir, GITHUB_TOKEN_FILE);
78163
+ const managedGithubVar = "CLAWD_GITHUB_MANAGED_TOKEN_SHA256";
78164
+ const githubFingerprint = (token) => (0, import_node_crypto30.createHash)("sha256").update(token).digest("hex");
78054
78165
  const githubIdentity = createGithubIdentity({
78166
+ isManaged: (token) => readEnvFileVar(githubTokenFile, managedGithubVar) === githubFingerprint(token),
78167
+ markManaged: (token) => {
78168
+ if (token) upsertEnvFileVar(githubTokenFile, managedGithubVar, githubFingerprint(token));
78169
+ else removeEnvFileVar(githubTokenFile, managedGithubVar);
78170
+ },
78055
78171
  resolve: () => resolveGithubAuth({ exec: runCommand, fileToken: () => readEnvFileVar(githubTokenFile, GITHUB_TOKEN_VAR) }),
78056
78172
  store: (token) => storeGithubAuth({
78057
78173
  exec: runCommand,
@@ -78073,19 +78189,23 @@ async function startDaemon(config) {
78073
78189
  throw new ClawdError(ERROR_CODES.INTERNAL, `\u5411\u4E2D\u5FC3\u8981 GitHub \u6388\u6743\u94FE\u63A5\u6CA1\u6210\uFF1A${err instanceof Error ? err.message : String(err)}`);
78074
78190
  }
78075
78191
  },
78076
- token: async () => {
78192
+ token: async (rejectedToken) => {
78077
78193
  const r2 = ownerIdentityStore.read();
78078
78194
  if (!r2) return void 0;
78079
- return centralGithubAuthToken({ api: config.clawosApi ?? DEFAULT_CLAWOS_API, loginPass: r2.loginPass });
78195
+ return centralGithubAuthToken({ api: config.clawosApi ?? DEFAULT_CLAWOS_API, loginPass: r2.loginPass, ...rejectedToken ? { rejectedToken } : {} });
78080
78196
  }
78081
78197
  },
78082
78198
  now: () => Date.now(),
78083
78199
  logger
78084
78200
  });
78085
- void githubIdentity.refresh();
78201
+ void githubIdentity.refresh().catch(() => {
78202
+ logger.warn("github.identity.warm-failed");
78203
+ });
78086
78204
  const resolvePersonaMcpConfig = (personaId2) => {
78087
78205
  const secrets = secretsWithGithubIdentity(readSecrets(), githubIdentity.cached());
78088
- void githubIdentity.refresh();
78206
+ void githubIdentity.refresh().catch(() => {
78207
+ logger.warn("github.identity.sync-failed");
78208
+ });
78089
78209
  return renderPersonaMcpSecrets({
78090
78210
  personaId: personaId2,
78091
78211
  personaDir: import_node_path89.default.join(config.dataDir, "personas", personaId2),
@@ -78913,7 +79033,7 @@ async function startDaemon(config) {
78913
79033
  shiftStore,
78914
79034
  shiftOwnerIdProvider: () => ownerPrincipalId,
78915
79035
  // PR 收件箱:github:* handler spawn 本机 gh CLI,凭据是 clawd 的 GitHub 身份(GH_TOKEN),没有才是 gh 自己的登录态
78916
- ghRunner: createGhRunner({ token: () => githubIdentity.cached()?.token }),
79036
+ ghRunner: createGhRunner({ token: async () => (await githubIdentity.refresh())?.token }),
78917
79037
  githubIdentity,
78918
79038
  visitorStore
78919
79039
  })
@@ -79023,7 +79143,7 @@ async function startDaemon(config) {
79023
79143
  fetchArtifact: downloadArtifact(runCommand),
79024
79144
  debianPackage: lookupDebianPackage(),
79025
79145
  githubIdentity,
79026
- githubApi: (token) => createGithubApi({ token }),
79146
+ githubApi: (token) => createGithubApi({ token, identity: githubIdentity }),
79027
79147
  org: PERSONA_REPO_ORG,
79028
79148
  claimPublisher: async (personaId2, environment = "production") => {
79029
79149
  const loginPass = targetLoginPass(environment);