@cydm/pie 4.3.1 → 4.3.2

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.
@@ -1079,39 +1079,43 @@ function findOwnerInstance(sessionId) {
1079
1079
  } catch {
1080
1080
  return void 0;
1081
1081
  }
1082
+ const candidates = [];
1082
1083
  for (const name of entries.slice(0, 256)) {
1083
1084
  if (!name.endsWith(".json")) continue;
1084
1085
  try {
1085
1086
  const parsed = JSON.parse(fs5.readFileSync(path5.join(discoveryDir(), name), "utf8"));
1086
1087
  if (parsed.instanceId === name.slice(0, -".json".length) && parsed.sessionId === sessionId && parsed.port && typeof parsed.secret === "string" && parsed.protocol === IPC_PROTOCOL_VERSION && pidAlive4(parsed.pid ?? 0)) {
1087
- return parsed;
1088
+ candidates.push({ file: parsed, startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : 0 });
1088
1089
  }
1089
1090
  } catch {
1090
1091
  }
1091
1092
  }
1092
- return void 0;
1093
- }
1094
- function sign(payload) {
1095
- return createHmac("sha256", "").update(JSON.stringify(payload)).digest("hex");
1093
+ if (!candidates.length) return void 0;
1094
+ candidates.sort((a, b) => b.startedAt - a.startedAt);
1095
+ return candidates[0].file;
1096
1096
  }
1097
- function deliverOnce(port, secret, text) {
1097
+ var SYNTHETIC_SENDER = (() => {
1098
+ const hex = randomUUID3().replace(/-/g, "");
1099
+ return `pie-${hex.slice(0, 12)}`;
1100
+ })();
1101
+ function deliverOnce(port, secret, text, targetSessionId, targetInstanceId) {
1098
1102
  return new Promise((resolve4) => {
1099
1103
  const id = randomUUID3();
1100
1104
  const envelope = {
1101
1105
  v: IPC_PROTOCOL_VERSION,
1102
1106
  id,
1103
- from: `pie-${randomUUID3().slice(0, 12)}`,
1104
- to: "unknown",
1107
+ from: SYNTHETIC_SENDER,
1108
+ to: targetInstanceId,
1105
1109
  kind: "message",
1106
1110
  createdAt: Date.now(),
1107
1111
  text,
1108
- sessionId: "",
1112
+ sessionId: targetSessionId,
1109
1113
  waitMs: 0
1110
1114
  };
1111
1115
  const payload = [envelope.v, envelope.id, envelope.from, envelope.to, envelope.kind, envelope.createdAt, envelope.sessionId ?? null, envelope.text ?? null, envelope.replyTo ?? null, envelope.waitMs ?? null, envelope.notifyCompletion ?? null, envelope.control ?? null, envelope.userAssigned ?? null, envelope.subscriberSession ?? null];
1112
1116
  const frame = JSON.stringify({ ...envelope, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") });
1113
- void sign;
1114
1117
  const socket = new net.Socket();
1118
+ let buffer = "";
1115
1119
  let settled = false;
1116
1120
  const finish = (ok) => {
1117
1121
  if (settled) return;
@@ -1122,10 +1126,34 @@ function deliverOnce(port, secret, text) {
1122
1126
  };
1123
1127
  const timer = setTimeout(() => finish(false), 5e3);
1124
1128
  socket.once("error", () => finish(false));
1129
+ socket.once("end", () => finish(false));
1130
+ socket.once("close", (hadError) => {
1131
+ if (!hadError) finish(false);
1132
+ });
1125
1133
  socket.once("connect", () => {
1126
1134
  socket.write(`${frame}
1127
1135
  `);
1128
- socket.setTimeout(250, () => finish(true));
1136
+ });
1137
+ socket.on("data", (chunk) => {
1138
+ buffer += chunk.toString("utf8");
1139
+ let lineEnd = buffer.indexOf("\n");
1140
+ if (lineEnd < 0) return;
1141
+ while (lineEnd >= 0) {
1142
+ const line = buffer.slice(0, lineEnd);
1143
+ buffer = buffer.slice(lineEnd + 1);
1144
+ let reply = null;
1145
+ try {
1146
+ reply = JSON.parse(line);
1147
+ } catch {
1148
+ reply = null;
1149
+ }
1150
+ if (reply && (reply.replyTo === id || reply.id === `${id}:r`) && (reply.kind === "result" || reply.kind === "ack")) {
1151
+ const text2 = typeof reply.text === "string" ? reply.text : "";
1152
+ finish(!/rejected|denied/i.test(text2));
1153
+ return;
1154
+ }
1155
+ lineEnd = buffer.indexOf("\n");
1156
+ }
1129
1157
  });
1130
1158
  try {
1131
1159
  socket.connect(port, "127.0.0.1");
@@ -1137,7 +1165,7 @@ function deliverOnce(port, secret, text) {
1137
1165
  async function dispatchEventToSession(sessionId, eventText) {
1138
1166
  const owner = findOwnerInstance(sessionId);
1139
1167
  if (!owner?.port || !owner.secret) return void 0;
1140
- const ok = await deliverOnce(owner.port, owner.secret, eventText);
1168
+ const ok = await deliverOnce(owner.port, owner.secret, eventText, owner.sessionId ?? "", owner.instanceId);
1141
1169
  return ok ? owner.instanceId : void 0;
1142
1170
  }
1143
1171
 
@@ -1935,18 +1963,24 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
1935
1963
  }
1936
1964
  async function dispatchToOwner(event, meta) {
1937
1965
  let ownerSession;
1966
+ let unknown = false;
1938
1967
  if (meta.threadId) {
1939
- ownerSession = threadOwner({ provider: cfg.provider, threadId: meta.threadId }).sessionId;
1968
+ const t = threadOwner({ provider: cfg.provider, threadId: meta.threadId });
1969
+ if (t.corrupt || t.unavailable) unknown = true;
1970
+ ownerSession = t.sessionId;
1940
1971
  }
1941
- if (!ownerSession && meta.replyTo) {
1972
+ if (!ownerSession && !unknown && meta.replyTo) {
1942
1973
  ownerSession = sessionRootOwner(cfg.provider, meta.replyTo)?.sessionId;
1943
1974
  }
1944
- if (!ownerSession || ownerSession === currentSessionId) return void 0;
1975
+ if (unknown) return { kind: "unknown-owner" };
1976
+ if (!ownerSession) return { kind: "no-owner" };
1977
+ if (ownerSession === currentSessionId) return { kind: "no-owner" };
1945
1978
  const payload = `${DISPATCH_PREFIX} ${JSON.stringify({ v: 1, binding: bindingKey(), event })}`;
1946
1979
  try {
1947
- return await dispatchEventToSession(ownerSession, payload);
1980
+ const delivered = await dispatchEventToSession(ownerSession, payload);
1981
+ return delivered ? { kind: "dispatched", owner: delivered } : { kind: "delivery-failed", owner: ownerSession };
1948
1982
  } catch {
1949
- return void 0;
1983
+ return { kind: "delivery-failed", owner: ownerSession };
1950
1984
  }
1951
1985
  }
1952
1986
  async function handleInboundEventInner(event, retry) {
@@ -2039,9 +2073,38 @@ ${pending.caption || IM_INPUT_FALLBACK_CAPTION}` : pending.caption).trim();
2039
2073
  return;
2040
2074
  }
2041
2075
  if (consumerLock) {
2042
- const dispatched = await dispatchToOwner(event, meta);
2043
- if (dispatched) {
2044
- ctx.log(`im-forward: event ${messageId} dispatched to owner ${dispatched}`);
2076
+ const outcome = await dispatchToOwner(event, meta);
2077
+ if (outcome.kind === "dispatched") {
2078
+ ctx.log(`im-forward: event ${messageId} dispatched to owner ${outcome.owner}`);
2079
+ return;
2080
+ }
2081
+ if (outcome.kind === "delivery-failed") {
2082
+ ctx.log(`im-forward: dispatch to ${outcome.owner} failed for ${messageId}; dropping`);
2083
+ return;
2084
+ }
2085
+ if (outcome.kind === "unknown-owner") {
2086
+ ctx.log(`im-forward: thread ownership unreadable for ${messageId}; dropping (fail closed)`);
2087
+ return;
2088
+ }
2089
+ if (isConcierge && event.chatType === "group" && meta.threadId) {
2090
+ if (!scope.isCurrent()) {
2091
+ releaseInvalidatedEvent();
2092
+ return;
2093
+ }
2094
+ const claim = claimThreadOwnership({ provider: cfg.provider, threadId: meta.threadId }, sessionId);
2095
+ if (!claim.claimed) {
2096
+ ctx.log(`im-forward: unowned-topic takeover lost the claim (${claim.reason}); ${messageId} dropped`);
2097
+ return;
2098
+ }
2099
+ ctx.log(`im-forward: unowned group topic ${meta.threadId} taken by concierge (claimed)`);
2100
+ await acceptRoutedMessage(
2101
+ { messageId: "", threadId: meta.threadId, sessionId, sentAt: Date.now() },
2102
+ event,
2103
+ meta,
2104
+ scope,
2105
+ address,
2106
+ sessionId
2107
+ );
2045
2108
  return;
2046
2109
  }
2047
2110
  }
@@ -2226,6 +2289,7 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2226
2289
  }
2227
2290
  async function resolveRouteByThreadRoot(threadId) {
2228
2291
  const messages = await fetchThreadMessages(threadId);
2292
+ if (messages === "forbidden") return { notOurs: true };
2229
2293
  if (!messages) return { transient: true };
2230
2294
  const rootId = messages[0];
2231
2295
  if (!rootId) return { notOurs: true };
@@ -2252,12 +2316,43 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2252
2316
  });
2253
2317
  }
2254
2318
  let consumerLock;
2319
+ let resolvedBindingKey;
2255
2320
  function bindingKey() {
2256
- return `${cfg.provider}:${cfg.appId ?? cfg.targetId}`;
2321
+ return resolvedBindingKey ?? `${cfg.provider}:${cfg.appId ?? (cfg.profile ? `profile:${cfg.profile}` : cfg.targetId)}`;
2322
+ }
2323
+ function resolveBindingKeySync() {
2324
+ if (resolvedBindingKey) return resolvedBindingKey;
2325
+ if (cfg.appId || !connection.canonicalAppId) {
2326
+ resolvedBindingKey = `${cfg.provider}:${cfg.appId ?? (cfg.profile ? `profile:${cfg.profile}` : cfg.targetId)}`;
2327
+ }
2328
+ return resolvedBindingKey ?? bindingKey();
2257
2329
  }
2258
- function acquireConsumerSlot() {
2330
+ async function resolveBindingKey() {
2331
+ if (resolvedBindingKey) return resolvedBindingKey;
2332
+ if (cfg.appId || !connection.canonicalAppId) return resolveBindingKeySync();
2333
+ const canonical = await connection.canonicalAppId().catch(() => void 0);
2334
+ if (canonical === void 0) return void 0;
2335
+ resolvedBindingKey = `${cfg.provider}:${canonical || (cfg.profile ? `profile:${cfg.profile}` : cfg.targetId)}`;
2336
+ return resolvedBindingKey;
2337
+ }
2338
+ let consumerStartupInFlight = false;
2339
+ function needsCanonicalResolution() {
2340
+ return !resolvedBindingKey && !cfg.appId && !!cfg.profile && connection.canonicalAppId !== void 0;
2341
+ }
2342
+ function acquireConsumerSlotSync() {
2259
2343
  if (consumerLock) return true;
2260
- const claim = tryClaimConsumer(bindingKey(), `pie-${currentSessionId ?? "unknown"}`, () => {
2344
+ if (needsCanonicalResolution()) return false;
2345
+ return acquireClaimedSlot(resolveBindingKeySync());
2346
+ }
2347
+ async function acquireConsumerSlot() {
2348
+ if (consumerLock) return true;
2349
+ if (!needsCanonicalResolution()) return acquireClaimedSlot(resolveBindingKeySync());
2350
+ const resolved = await resolveBindingKey();
2351
+ return acquireClaimedSlot(resolved);
2352
+ }
2353
+ function acquireClaimedSlot(binding) {
2354
+ if (consumerLock) return true;
2355
+ const claim = tryClaimConsumer(binding, `pie-${currentSessionId ?? "unknown"}`, () => {
2261
2356
  ctx.log("im-forward: event-hub slot lost to another consumer; retiring ours");
2262
2357
  consumerLock = void 0;
2263
2358
  if (consumer || consumerRecovering) {
@@ -2276,11 +2371,38 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2276
2371
  consumerLock = claim;
2277
2372
  return true;
2278
2373
  }
2279
- function spawnConsumer() {
2374
+ async function spawnConsumer() {
2280
2375
  restartTimer = void 0;
2281
2376
  restartDueAt = void 0;
2282
2377
  if (terminated || suspended || consumer || consumerRecovering) return;
2283
- if (!acquireConsumerSlot()) return;
2378
+ if (needsCanonicalResolution()) {
2379
+ if (consumerStartupInFlight) return;
2380
+ consumerStartupInFlight = true;
2381
+ let key2;
2382
+ try {
2383
+ key2 = await resolveBindingKey();
2384
+ if (terminated || suspended || consumer || consumerRecovering) return;
2385
+ } finally {
2386
+ consumerStartupInFlight = false;
2387
+ }
2388
+ if (!key2) {
2389
+ restartTimer = setTimeout(spawnConsumer, 15e3);
2390
+ restartTimer.unref?.();
2391
+ restartDueAt = Date.now() + 15e3;
2392
+ return;
2393
+ }
2394
+ if (!acquireClaimedSlot(key2)) {
2395
+ restartTimer = setTimeout(spawnConsumer, 15e3);
2396
+ restartTimer.unref?.();
2397
+ restartDueAt = Date.now() + 15e3;
2398
+ return;
2399
+ }
2400
+ } else if (!acquireClaimedSlot(resolveBindingKeySync())) {
2401
+ restartTimer = setTimeout(spawnConsumer, 15e3);
2402
+ restartTimer.unref?.();
2403
+ restartDueAt = Date.now() + 15e3;
2404
+ return;
2405
+ }
2284
2406
  const gen = {
2285
2407
  handle: null,
2286
2408
  installed: false,
@@ -3460,8 +3582,29 @@ function connect(binary, profile, targetKind = "chat") {
3460
3582
  const result = await native(binary, profile ? [...args, "--profile", profile] : args, 3e4, void 0, { signal: lifetime.signal });
3461
3583
  return result.error ? void 0 : parseLarkCliEnvelope(result.stdout).data;
3462
3584
  };
3585
+ let canonicalAppIdCache = null;
3586
+ let canonicalResolved = false;
3463
3587
  return {
3464
3588
  sourcePrefix: "[Feishu]",
3589
+ async canonicalAppId() {
3590
+ if (canonicalResolved) return canonicalAppIdCache || void 0;
3591
+ if (!profile) {
3592
+ canonicalResolved = true;
3593
+ return void 0;
3594
+ }
3595
+ try {
3596
+ const result = await native(binary, ["profile", "list"], 1e4, void 0, { signal: lifetime.signal });
3597
+ const profiles = result.error ? null : parseProfiles(result.stdout);
3598
+ if (!profiles) return void 0;
3599
+ const appId = profiles.find((item) => item.name === profile)?.appId;
3600
+ if (!appId) return void 0;
3601
+ canonicalAppIdCache = appId;
3602
+ canonicalResolved = true;
3603
+ return canonicalAppIdCache;
3604
+ } catch {
3605
+ return void 0;
3606
+ }
3607
+ },
3465
3608
  async dispose() {
3466
3609
  lifetime.abort();
3467
3610
  await Promise.allSettled([...active]);
@@ -3490,7 +3633,13 @@ function connect(binary, profile, targetKind = "chat") {
3490
3633
  } : null;
3491
3634
  },
3492
3635
  async threadMessages(id) {
3493
- const data = await call(["im", "+threads-messages-list", "--as", "bot", "--thread", id]);
3636
+ const args = ["im", "+threads-messages-list", "--as", "bot", "--thread", id];
3637
+ const result = await native(binary, profile ? [...args, "--profile", profile] : args, 3e4, void 0, { signal: lifetime.signal });
3638
+ if (result.error) {
3639
+ if (/230027|user_unauthorized|authorization/i.test(result.error)) return "forbidden";
3640
+ return null;
3641
+ }
3642
+ const data = parseLarkCliEnvelope(result.stdout).data;
3494
3643
  return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
3495
3644
  },
3496
3645
  async downloadImage(messageId, image, index) {
@@ -3680,7 +3829,7 @@ function initializeImForward(ctx, providers = implementedProviders) {
3680
3829
  return () => {
3681
3830
  };
3682
3831
  };
3683
- createRuntime(bridge, { enabled: config.enabled, provider: config.provider, label: provider.label, targetId: settings.targetId, targetKind: settings.targetKind, allowUsers: settings.allowUsers, retryBackoffMs: config.retryBackoffMs, ...settings.appId ? { appId: settings.appId } : {}, ...settings.groupAccess ? { groupAccess: settings.groupAccess } : {}, ...caps.unattended ? { unattended: true } : {} }, connection, () => liveEnabled(config), (next) => {
3832
+ createRuntime(bridge, { enabled: config.enabled, provider: config.provider, label: provider.label, targetId: settings.targetId, targetKind: settings.targetKind, allowUsers: settings.allowUsers, retryBackoffMs: config.retryBackoffMs, ...settings.appId ? { appId: settings.appId } : {}, ...typeof settings.larkCliProfile === "string" && settings.larkCliProfile.trim() ? { profile: settings.larkCliProfile.trim() } : {}, ...settings.groupAccess ? { groupAccess: settings.groupAccess } : {}, ...caps.unattended ? { unattended: true } : {} }, connection, () => liveEnabled(config), (next) => {
3684
3833
  const latest = readLiveConfig(ctx.cwd, dir);
3685
3834
  if (latest.problems.length || !latest.config || configurationIdentity(latest.config) !== configurationIdentity(config)) throw new Error("Configuration changed; setup required");
3686
3835
  writeConfig(ctx.cwd, dir, { enabled: next });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cydm/pie",
3
- "version": "4.3.1",
3
+ "version": "4.3.2",
4
4
  "description": "Pie AI Agent CLI",
5
5
  "type": "module",
6
6
  "bin": {