aai-lark-bridge 0.2.30 → 0.2.33
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.js +319 -31
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -4,7 +4,7 @@ import { Command } from "commander";
|
|
|
4
4
|
// package.json
|
|
5
5
|
var package_default = {
|
|
6
6
|
name: "aai-lark-bridge",
|
|
7
|
-
version: "0.2.
|
|
7
|
+
version: "0.2.33",
|
|
8
8
|
description: "Lark AI Native Bridge - Lark\u57FA\u7840\u8BBE\u65BD\u5C42\u548CCLI\u96C6\u6210",
|
|
9
9
|
type: "module",
|
|
10
10
|
main: "./dist/index.js",
|
|
@@ -7617,7 +7617,7 @@ async function submitClaudeLogin(cfg, sub, deps = {}) {
|
|
|
7617
7617
|
}
|
|
7618
7618
|
|
|
7619
7619
|
// src/bridge/bot/channel.ts
|
|
7620
|
-
import { dirname as dirname19, join as
|
|
7620
|
+
import { dirname as dirname19, join as join28 } from "path";
|
|
7621
7621
|
|
|
7622
7622
|
// src/bridge/agent/capability.ts
|
|
7623
7623
|
function claudeCapability(profile2) {
|
|
@@ -7874,7 +7874,7 @@ function isDispatchRoot(dir, rootMessageId) {
|
|
|
7874
7874
|
}
|
|
7875
7875
|
function dispatchRoute(dir, m) {
|
|
7876
7876
|
if (m.threadId) return isDispatchRoot(dir, m.rootId) ? "thread" : void 0;
|
|
7877
|
-
return isDispatchMarker(m.content) ? "start" : void 0;
|
|
7877
|
+
return isDispatchMarker(m.content) || isDispatchRoot(dir, m.messageId) ? "start" : void 0;
|
|
7878
7878
|
}
|
|
7879
7879
|
var LOCK_WAIT_MS = 2e3;
|
|
7880
7880
|
var LOCK_STEP_MS = 50;
|
|
@@ -12667,6 +12667,19 @@ async function lookupMessageThreadId(channel, messageId) {
|
|
|
12667
12667
|
return void 0;
|
|
12668
12668
|
}
|
|
12669
12669
|
}
|
|
12670
|
+
async function lookupMessageRoot(channel, messageId) {
|
|
12671
|
+
try {
|
|
12672
|
+
const [item] = await channel.fetchRawMessage(messageId);
|
|
12673
|
+
const raw = item;
|
|
12674
|
+
return { threadId: raw?.thread_id, rootId: raw?.root_id };
|
|
12675
|
+
} catch (err) {
|
|
12676
|
+
log.warn("thread", "root-lookup-failed", {
|
|
12677
|
+
messageId,
|
|
12678
|
+
err: err instanceof Error ? err.message : String(err)
|
|
12679
|
+
});
|
|
12680
|
+
return {};
|
|
12681
|
+
}
|
|
12682
|
+
}
|
|
12670
12683
|
|
|
12671
12684
|
// src/bridge/card/handoff.ts
|
|
12672
12685
|
import { createHash as createHash4 } from "crypto";
|
|
@@ -12734,7 +12747,7 @@ async function handleCardAction(deps) {
|
|
|
12734
12747
|
const chatId = deps.evt.chatId;
|
|
12735
12748
|
const raw = deps.evt.raw;
|
|
12736
12749
|
const formValue = raw?.action?.form_value;
|
|
12737
|
-
const { scope, threadId, mode } = await resolveScope(deps);
|
|
12750
|
+
const { scope, threadId, rootId, mode } = await resolveScope(deps);
|
|
12738
12751
|
const accessDecision = mode === "p2p" ? canUseDm(deps.controls.profileConfig, deps.controls, operatorId) : canUseGroup(deps.controls.profileConfig, deps.controls, chatId, operatorId);
|
|
12739
12752
|
if (!accessDecision.ok) {
|
|
12740
12753
|
log.info("cardAction", "skip-not-allowed-user", {
|
|
@@ -12753,7 +12766,7 @@ async function handleCardAction(deps) {
|
|
|
12753
12766
|
return;
|
|
12754
12767
|
}
|
|
12755
12768
|
log.info("cardAction", "cmd", { cmd, scope });
|
|
12756
|
-
const msg = makeFakeMsg(deps.evt, threadId);
|
|
12769
|
+
const msg = makeFakeMsg(deps.evt, threadId, rootId);
|
|
12757
12770
|
const ctx = {
|
|
12758
12771
|
channel: deps.channel,
|
|
12759
12772
|
msg,
|
|
@@ -12791,7 +12804,7 @@ async function handleCardAction(deps) {
|
|
|
12791
12804
|
}
|
|
12792
12805
|
if (BRIDGE_CALLBACK_MARKER in payload) {
|
|
12793
12806
|
if (!verifyBridgeToken(deps, payload, scope, "agent_callback")) return;
|
|
12794
|
-
forwardToAgent(deps, payload, formValue, scope, threadId, mode);
|
|
12807
|
+
forwardToAgent(deps, payload, formValue, scope, threadId, mode, rootId);
|
|
12795
12808
|
return;
|
|
12796
12809
|
}
|
|
12797
12810
|
return;
|
|
@@ -12821,6 +12834,13 @@ async function resolveScope(deps) {
|
|
|
12821
12834
|
const chatId = deps.evt.chatId;
|
|
12822
12835
|
const mode = await deps.chatModeCache.resolve(deps.channel, chatId);
|
|
12823
12836
|
if (mode !== "topic") {
|
|
12837
|
+
const bindingsDir = deps.controls.profileConfig.preferences.taskBindings?.dir;
|
|
12838
|
+
if (mode === "p2p" && bindingsDir) {
|
|
12839
|
+
const { threadId: threadId2, rootId } = await lookupMessageRoot(deps.channel, deps.evt.messageId);
|
|
12840
|
+
if (rootId && isDispatchRoot(bindingsDir, rootId)) {
|
|
12841
|
+
return { scope: `${chatId}:${rootId}`, threadId: threadId2, rootId, mode };
|
|
12842
|
+
}
|
|
12843
|
+
}
|
|
12824
12844
|
return { scope: chatId, threadId: void 0, mode };
|
|
12825
12845
|
}
|
|
12826
12846
|
const threadId = await lookupMessageThreadId(deps.channel, deps.evt.messageId);
|
|
@@ -12829,7 +12849,7 @@ async function resolveScope(deps) {
|
|
|
12829
12849
|
}
|
|
12830
12850
|
return { scope: `${chatId}:${threadId}`, threadId, mode };
|
|
12831
12851
|
}
|
|
12832
|
-
function forwardToAgent(deps, payload, formValue, scope, threadId, mode) {
|
|
12852
|
+
function forwardToAgent(deps, payload, formValue, scope, threadId, mode, rootId) {
|
|
12833
12853
|
const {
|
|
12834
12854
|
[BRIDGE_CALLBACK_MARKER]: _marker,
|
|
12835
12855
|
bridge_token: _token,
|
|
@@ -12845,6 +12865,7 @@ function forwardToAgent(deps, payload, formValue, scope, threadId, mode) {
|
|
|
12845
12865
|
chatId: deps.evt.chatId,
|
|
12846
12866
|
chatType: mode === "p2p" ? "p2p" : "group",
|
|
12847
12867
|
threadId,
|
|
12868
|
+
...rootId ? { rootId } : {},
|
|
12848
12869
|
senderId: deps.evt.operator.openId,
|
|
12849
12870
|
senderName: deps.evt.operator.name,
|
|
12850
12871
|
content: `[card-click] ${JSON.stringify(merged)}`,
|
|
@@ -12892,12 +12913,13 @@ function composeArgs(sub, payload) {
|
|
|
12892
12913
|
const arg = typeof payload.arg === "string" && payload.arg || typeof payload.name === "string" && payload.name || "";
|
|
12893
12914
|
return arg ? `${sub} ${arg}` : sub;
|
|
12894
12915
|
}
|
|
12895
|
-
function makeFakeMsg(evt, threadId) {
|
|
12916
|
+
function makeFakeMsg(evt, threadId, rootId) {
|
|
12896
12917
|
return {
|
|
12897
12918
|
messageId: evt.messageId,
|
|
12898
12919
|
chatId: evt.chatId,
|
|
12899
12920
|
chatType: "p2p",
|
|
12900
12921
|
threadId,
|
|
12922
|
+
...rootId ? { rootId } : {},
|
|
12901
12923
|
senderId: evt.operator.openId,
|
|
12902
12924
|
senderName: evt.operator.name,
|
|
12903
12925
|
content: "",
|
|
@@ -14736,9 +14758,12 @@ var PendingQueue = class {
|
|
|
14736
14758
|
existing.timer = this.blocked.has(scope) ? void 0 : this.armTimer(scope);
|
|
14737
14759
|
return existing.messages.length;
|
|
14738
14760
|
}
|
|
14761
|
+
const behindRun = this.blocked.has(scope);
|
|
14739
14762
|
this.map.set(scope, {
|
|
14740
14763
|
messages: [msg],
|
|
14741
|
-
timer:
|
|
14764
|
+
timer: behindRun ? void 0 : this.armTimer(scope),
|
|
14765
|
+
firstArrivedAt: Date.now(),
|
|
14766
|
+
behindRun
|
|
14742
14767
|
});
|
|
14743
14768
|
return 1;
|
|
14744
14769
|
}
|
|
@@ -14785,13 +14810,219 @@ var PendingQueue = class {
|
|
|
14785
14810
|
if (!entry) return;
|
|
14786
14811
|
this.map.delete(scope);
|
|
14787
14812
|
try {
|
|
14788
|
-
this.onFlush(scope, entry.messages
|
|
14813
|
+
this.onFlush(scope, entry.messages, {
|
|
14814
|
+
firstArrivedAt: entry.firstArrivedAt,
|
|
14815
|
+
behindRun: entry.behindRun
|
|
14816
|
+
});
|
|
14789
14817
|
} catch (err) {
|
|
14790
14818
|
log.fail("queue", err, { scope, batchSize: entry.messages.length });
|
|
14791
14819
|
}
|
|
14792
14820
|
}
|
|
14793
14821
|
};
|
|
14794
14822
|
|
|
14823
|
+
// src/bridge/bot/scope.ts
|
|
14824
|
+
function dispatchScope(dir, m) {
|
|
14825
|
+
if (!dir) return void 0;
|
|
14826
|
+
const route2 = dispatchRoute(dir, m);
|
|
14827
|
+
if (route2 === "start") return `${m.chatId}:${m.messageId}`;
|
|
14828
|
+
if (route2 === "thread" && m.rootId) return `${m.chatId}:${m.rootId}`;
|
|
14829
|
+
return void 0;
|
|
14830
|
+
}
|
|
14831
|
+
var MAX_DM_WORKERS = 3;
|
|
14832
|
+
function runningWorkers(scopes, chatId) {
|
|
14833
|
+
const prefix = `${chatId}:`;
|
|
14834
|
+
return scopes.filter((s) => s.startsWith(prefix)).length;
|
|
14835
|
+
}
|
|
14836
|
+
|
|
14837
|
+
// src/bridge/bot/spawn-inbox.ts
|
|
14838
|
+
import { existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync3 } from "fs";
|
|
14839
|
+
import { join as join26 } from "path";
|
|
14840
|
+
var SPAWN_DIR = "spawn";
|
|
14841
|
+
var SPAWN_POLL_MS = 1500;
|
|
14842
|
+
var RECENT_TTL_MS = 15 * 6e4;
|
|
14843
|
+
var RECENT_MAX = 200;
|
|
14844
|
+
var STALE_FILE_MS = 10 * 6e4;
|
|
14845
|
+
var RecentMessages = class {
|
|
14846
|
+
constructor(now = Date.now) {
|
|
14847
|
+
this.now = now;
|
|
14848
|
+
}
|
|
14849
|
+
now;
|
|
14850
|
+
map = /* @__PURE__ */ new Map();
|
|
14851
|
+
set(msg) {
|
|
14852
|
+
this.map.delete(msg.messageId);
|
|
14853
|
+
this.map.set(msg.messageId, { msg, at: this.now() });
|
|
14854
|
+
while (this.map.size > RECENT_MAX) this.map.delete(this.map.keys().next().value);
|
|
14855
|
+
}
|
|
14856
|
+
get(chatId, messageId) {
|
|
14857
|
+
const hit = this.map.get(messageId);
|
|
14858
|
+
if (!hit || this.now() - hit.at > RECENT_TTL_MS || hit.msg.chatId !== chatId) return void 0;
|
|
14859
|
+
return hit.msg;
|
|
14860
|
+
}
|
|
14861
|
+
};
|
|
14862
|
+
function processSpawnFiles(o) {
|
|
14863
|
+
const folder = join26(o.dir, SPAWN_DIR);
|
|
14864
|
+
if (!existsSync9(folder)) return [];
|
|
14865
|
+
const now = (o.now ?? Date.now)();
|
|
14866
|
+
const out = [];
|
|
14867
|
+
for (const name of readdirSync2(folder)) {
|
|
14868
|
+
if (!name.endsWith(".json")) continue;
|
|
14869
|
+
const file = join26(folder, name);
|
|
14870
|
+
let req;
|
|
14871
|
+
try {
|
|
14872
|
+
req = JSON.parse(readFileSync5(file, "utf8"));
|
|
14873
|
+
} catch {
|
|
14874
|
+
rmSync3(file, { force: true });
|
|
14875
|
+
out.push("bad-file");
|
|
14876
|
+
continue;
|
|
14877
|
+
}
|
|
14878
|
+
rmSync3(file, { force: true });
|
|
14879
|
+
const chatId = req.chat_id;
|
|
14880
|
+
const messageId = req.message_id;
|
|
14881
|
+
if (!chatId || !messageId || req.at && now - Date.parse(req.at) > STALE_FILE_MS) {
|
|
14882
|
+
out.push("bad-file");
|
|
14883
|
+
continue;
|
|
14884
|
+
}
|
|
14885
|
+
const msg = o.recent.get(chatId, messageId);
|
|
14886
|
+
if (!msg) {
|
|
14887
|
+
log.warn("spawn", "unknown-message", { chatId, messageId });
|
|
14888
|
+
out.push("unknown-message");
|
|
14889
|
+
continue;
|
|
14890
|
+
}
|
|
14891
|
+
const scope = `${chatId}:${messageId}`;
|
|
14892
|
+
if (o.isRoot(messageId) || o.activeScopes().includes(scope)) {
|
|
14893
|
+
out.push("already");
|
|
14894
|
+
continue;
|
|
14895
|
+
}
|
|
14896
|
+
const running = o.activeScopes().filter((s) => s.startsWith(`${chatId}:`)).length;
|
|
14897
|
+
if (running >= o.limit) {
|
|
14898
|
+
log.info("spawn", "worker-limit", { scope, limit: o.limit });
|
|
14899
|
+
o.reject(msg, "limit");
|
|
14900
|
+
out.push("limit");
|
|
14901
|
+
continue;
|
|
14902
|
+
}
|
|
14903
|
+
try {
|
|
14904
|
+
o.register(messageId, chatId);
|
|
14905
|
+
o.push(scope, msg);
|
|
14906
|
+
log.info("spawn", "spawned", { scope });
|
|
14907
|
+
out.push("spawned");
|
|
14908
|
+
} catch (err) {
|
|
14909
|
+
log.fail("spawn", err, { scope });
|
|
14910
|
+
out.push("bad-file");
|
|
14911
|
+
}
|
|
14912
|
+
}
|
|
14913
|
+
return out;
|
|
14914
|
+
}
|
|
14915
|
+
function startSpawnInbox(o, intervalMs = SPAWN_POLL_MS) {
|
|
14916
|
+
mkdirSync6(join26(o.dir, SPAWN_DIR), { recursive: true });
|
|
14917
|
+
const timer = setInterval(() => {
|
|
14918
|
+
try {
|
|
14919
|
+
processSpawnFiles(o);
|
|
14920
|
+
} catch (err) {
|
|
14921
|
+
log.fail("spawn", err);
|
|
14922
|
+
}
|
|
14923
|
+
}, intervalMs);
|
|
14924
|
+
timer.unref?.();
|
|
14925
|
+
return { stop: () => clearInterval(timer) };
|
|
14926
|
+
}
|
|
14927
|
+
|
|
14928
|
+
// src/bridge/bot/worker-report.ts
|
|
14929
|
+
import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync7 } from "fs";
|
|
14930
|
+
import { join as join27 } from "path";
|
|
14931
|
+
var REPORT_MARKER = "[worker-report]";
|
|
14932
|
+
var SUMMARY_LINES = 4;
|
|
14933
|
+
var clip = (s, n) => s.length > n ? `${s.slice(0, n)}\u2026` : s;
|
|
14934
|
+
var oneLine = (s) => s.replace(/\s+/g, " ").trim();
|
|
14935
|
+
function terminalOf(evt) {
|
|
14936
|
+
if (evt.type === "done") {
|
|
14937
|
+
if (evt.terminationReason === "interrupted") return { state: "stopped" };
|
|
14938
|
+
if (evt.terminationReason === "timeout") return { state: "blocked", reason: "\u957F\u65F6\u95F4\u6CA1\u6709\u8FDB\u5C55\uFF0C\u5DF2\u505C\u6B62" };
|
|
14939
|
+
return { state: "ready" };
|
|
14940
|
+
}
|
|
14941
|
+
if (evt.type === "error") {
|
|
14942
|
+
if (evt.terminationReason === "interrupted") return { state: "stopped" };
|
|
14943
|
+
if (evt.terminationReason === "timeout") return { state: "blocked", reason: "\u957F\u65F6\u95F4\u6CA1\u6709\u8FDB\u5C55\uFF0C\u5DF2\u505C\u6B62" };
|
|
14944
|
+
if (evt.budgetHit) return { state: "blocked", reason: "\u649E\u5230\u82B1\u8D39\u4E0A\u9650" };
|
|
14945
|
+
return { state: "failed", reason: evt.message };
|
|
14946
|
+
}
|
|
14947
|
+
return void 0;
|
|
14948
|
+
}
|
|
14949
|
+
function formatReport(r) {
|
|
14950
|
+
const body = (r.summary ? r.summary.split("\n").map((l) => l.trim()).filter(Boolean) : ["\uFF08\u6CA1\u6709\u5185\u5BB9\uFF09"]).slice(0, SUMMARY_LINES - 1);
|
|
14951
|
+
const lines = [
|
|
14952
|
+
`${REPORT_MARKER} ${r.state}\uFF5C\u7528\u6237\u95EE\u7684\uFF1A${clip(oneLine(r.ask), 40)}`,
|
|
14953
|
+
...body.map((l) => clip(l, 120))
|
|
14954
|
+
].slice(0, SUMMARY_LINES);
|
|
14955
|
+
lines.push(`trace: scope=${r.scope} root=${r.rootId} session=${r.sessionId ?? "-"} run=${r.runId} at=${r.at}`);
|
|
14956
|
+
return lines.join("\n");
|
|
14957
|
+
}
|
|
14958
|
+
function reportMessage(r, senderId, senderName) {
|
|
14959
|
+
return {
|
|
14960
|
+
messageId: `worker-report-${r.runId}`,
|
|
14961
|
+
chatId: r.chatId,
|
|
14962
|
+
chatType: "p2p",
|
|
14963
|
+
senderId,
|
|
14964
|
+
...senderName ? { senderName } : {},
|
|
14965
|
+
content: formatReport(r),
|
|
14966
|
+
rawContentType: "worker_report",
|
|
14967
|
+
resources: [],
|
|
14968
|
+
mentions: [],
|
|
14969
|
+
mentionAll: false,
|
|
14970
|
+
mentionedBot: false,
|
|
14971
|
+
createTime: Date.now()
|
|
14972
|
+
};
|
|
14973
|
+
}
|
|
14974
|
+
function appendWorkerLog(dir, r) {
|
|
14975
|
+
if (!/^[A-Za-z0-9_-]+$/.test(r.chatId)) return;
|
|
14976
|
+
const folder = join27(dir, "workers");
|
|
14977
|
+
mkdirSync7(folder, { recursive: true });
|
|
14978
|
+
appendFileSync2(join27(folder, `${r.chatId}.jsonl`), `${JSON.stringify(r)}
|
|
14979
|
+
`);
|
|
14980
|
+
}
|
|
14981
|
+
async function observeWorkerRun(i) {
|
|
14982
|
+
const rootId = i.scope.slice(i.chatId.length + 1);
|
|
14983
|
+
let sessionId;
|
|
14984
|
+
let finalText = "";
|
|
14985
|
+
let streamed = "";
|
|
14986
|
+
let terminal;
|
|
14987
|
+
try {
|
|
14988
|
+
for await (const evt of i.events) {
|
|
14989
|
+
if ((evt.type === "system" || evt.type === "done") && evt.sessionId) sessionId = evt.sessionId;
|
|
14990
|
+
if (evt.type === "final_text") finalText = evt.content;
|
|
14991
|
+
if (evt.type === "text") streamed += evt.delta;
|
|
14992
|
+
const t = terminalOf(evt);
|
|
14993
|
+
if (t) terminal = t;
|
|
14994
|
+
}
|
|
14995
|
+
} catch (err) {
|
|
14996
|
+
i.onError?.("observe", err);
|
|
14997
|
+
terminal ??= { state: "failed", reason: err instanceof Error ? err.message : String(err) };
|
|
14998
|
+
}
|
|
14999
|
+
if (!terminal) return void 0;
|
|
15000
|
+
const report = {
|
|
15001
|
+
state: terminal.state,
|
|
15002
|
+
chatId: i.chatId,
|
|
15003
|
+
scope: i.scope,
|
|
15004
|
+
rootId,
|
|
15005
|
+
runId: i.runId,
|
|
15006
|
+
...sessionId ? { sessionId } : {},
|
|
15007
|
+
ask: i.ask,
|
|
15008
|
+
summary: terminal.reason ?? (finalText || streamed).trim(),
|
|
15009
|
+
at: (i.now?.() ?? /* @__PURE__ */ new Date()).toISOString()
|
|
15010
|
+
};
|
|
15011
|
+
if (i.dir) {
|
|
15012
|
+
try {
|
|
15013
|
+
appendWorkerLog(i.dir, report);
|
|
15014
|
+
} catch (err) {
|
|
15015
|
+
i.onError?.("log", err);
|
|
15016
|
+
}
|
|
15017
|
+
}
|
|
15018
|
+
try {
|
|
15019
|
+
i.push(reportMessage(report, i.senderId, i.senderName));
|
|
15020
|
+
} catch (err) {
|
|
15021
|
+
i.onError?.("push", err);
|
|
15022
|
+
}
|
|
15023
|
+
return report;
|
|
15024
|
+
}
|
|
15025
|
+
|
|
14795
15026
|
// src/bridge/bot/quote.ts
|
|
14796
15027
|
import { normalize } from "@larksuite/channel";
|
|
14797
15028
|
|
|
@@ -15538,7 +15769,7 @@ async function startChannel(deps) {
|
|
|
15538
15769
|
const pool = new ProcessPool(() => getMaxConcurrentRuns(controls.cfg));
|
|
15539
15770
|
const executor = new RunExecutor({ agent, pool, activeRuns });
|
|
15540
15771
|
const appSecret = await resolveAppSecret(cfg, deps.appPaths);
|
|
15541
|
-
const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(
|
|
15772
|
+
const callbackNonceStore = deps.appPaths?.mediaDir ? new CallbackNonceStore(join28(dirname19(deps.appPaths.mediaDir), "callback-nonces.json")) : void 0;
|
|
15542
15773
|
await callbackNonceStore?.load();
|
|
15543
15774
|
const callbackAuth = callbackNonceStore ? new CallbackAuth({
|
|
15544
15775
|
keys: [{ version: 1, secret: appSecret }],
|
|
@@ -15552,6 +15783,7 @@ async function startChannel(deps) {
|
|
|
15552
15783
|
appSecret
|
|
15553
15784
|
});
|
|
15554
15785
|
const threadModeOverrideWarnedChats = /* @__PURE__ */ new Set();
|
|
15786
|
+
const recentDm = new RecentMessages();
|
|
15555
15787
|
const logThreadModeOverride = ({ chatId, resolvedMode, threadId }) => {
|
|
15556
15788
|
const fields = { chatId, cachedMode: resolvedMode, threadId };
|
|
15557
15789
|
if (threadModeOverrideWarnedChats.has(chatId)) {
|
|
@@ -15601,7 +15833,7 @@ async function startChannel(deps) {
|
|
|
15601
15833
|
const channel = createLarkChannel(opts);
|
|
15602
15834
|
installStreamResilience(channel);
|
|
15603
15835
|
const media = new MediaCache(channel, deps.appPaths?.mediaDir);
|
|
15604
|
-
const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch) => {
|
|
15836
|
+
const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch, arrival) => {
|
|
15605
15837
|
const firstMsg = batch[0];
|
|
15606
15838
|
if (!firstMsg) return;
|
|
15607
15839
|
pending.block(scope);
|
|
@@ -15632,6 +15864,10 @@ async function startChannel(deps) {
|
|
|
15632
15864
|
workspaces,
|
|
15633
15865
|
media,
|
|
15634
15866
|
batch,
|
|
15867
|
+
arrival,
|
|
15868
|
+
pushToRouter: (m) => {
|
|
15869
|
+
pending.push(m.chatId, m);
|
|
15870
|
+
},
|
|
15635
15871
|
controls,
|
|
15636
15872
|
cotClient,
|
|
15637
15873
|
callbackAuth,
|
|
@@ -15671,6 +15907,7 @@ async function startChannel(deps) {
|
|
|
15671
15907
|
workspaces,
|
|
15672
15908
|
activeRuns,
|
|
15673
15909
|
pending,
|
|
15910
|
+
recent: recentDm,
|
|
15674
15911
|
msg,
|
|
15675
15912
|
controls,
|
|
15676
15913
|
chatModeCache,
|
|
@@ -15806,6 +16043,22 @@ async function startChannel(deps) {
|
|
|
15806
16043
|
await ownerRefresh.start();
|
|
15807
16044
|
const knownChatsRefresh = startKnownChatsRefreshTimer(channel, controls);
|
|
15808
16045
|
armed.push(() => knownChatsRefresh.stop());
|
|
16046
|
+
const spawnDir = controls.profileConfig.preferences.taskBindings?.dir;
|
|
16047
|
+
const spawnInbox = spawnDir ? startSpawnInbox({
|
|
16048
|
+
dir: spawnDir,
|
|
16049
|
+
recent: recentDm,
|
|
16050
|
+
activeScopes: () => activeRuns.scopes(),
|
|
16051
|
+
limit: MAX_DM_WORKERS,
|
|
16052
|
+
isRoot: (id) => isDispatchRoot(spawnDir, id),
|
|
16053
|
+
register: (id, chatId) => registerDispatchRoot(spawnDir, id, chatId),
|
|
16054
|
+
push: (scope, m) => {
|
|
16055
|
+
pending.push(scope, m);
|
|
16056
|
+
},
|
|
16057
|
+
reject: (m) => {
|
|
16058
|
+
void channel.send(m.chatId, { markdown: `\u4F60\u540C\u65F6\u5728\u8DD1\u7684\u4EFB\u52A1\u5DF2\u7ECF\u6709 ${MAX_DM_WORKERS} \u4E2A\uFF0C\u7B49\u5176\u4E2D\u4E00\u4E2A\u7ED3\u675F\u540E\u518D\u53D1\u8FD9\u6761\u3002` }, { replyTo: m.messageId }).catch((err) => log.warn("spawn", "limit-reply-failed", { err: String(err) }));
|
|
16059
|
+
}
|
|
16060
|
+
}) : void 0;
|
|
16061
|
+
if (spawnInbox) armed.push(() => spawnInbox.stop());
|
|
15809
16062
|
const identity = channel.botIdentity;
|
|
15810
16063
|
if (identity?.openId) {
|
|
15811
16064
|
agent.setBotIdentity?.({
|
|
@@ -15836,6 +16089,7 @@ async function startChannel(deps) {
|
|
|
15836
16089
|
unregisterChannel(controls.profile, channelToken);
|
|
15837
16090
|
ownerRefresh.stop();
|
|
15838
16091
|
knownChatsRefresh.stop();
|
|
16092
|
+
spawnInbox?.stop();
|
|
15839
16093
|
keepalive.stop();
|
|
15840
16094
|
meetingManager?.dispose();
|
|
15841
16095
|
controls.meeting = void 0;
|
|
@@ -15959,6 +16213,7 @@ async function intakeMessage(deps) {
|
|
|
15959
16213
|
}
|
|
15960
16214
|
}
|
|
15961
16215
|
const emsg = threadId === msg.threadId ? msg : { ...msg, threadId };
|
|
16216
|
+
if (msg.chatType === "p2p") deps.recent.set(emsg);
|
|
15962
16217
|
const chatMode = threadId ? "topic" : resolvedMode;
|
|
15963
16218
|
if (threadId && resolvedMode !== "topic") {
|
|
15964
16219
|
chatModeCache.invalidate(msg.chatId);
|
|
@@ -15968,7 +16223,8 @@ async function intakeMessage(deps) {
|
|
|
15968
16223
|
threadId
|
|
15969
16224
|
});
|
|
15970
16225
|
}
|
|
15971
|
-
const
|
|
16226
|
+
const workerScope = msg.chatType === "p2p" ? dispatchScope(controls.profileConfig.preferences.taskBindings?.dir, emsg) : void 0;
|
|
16227
|
+
const scope = workerScope ?? (chatMode === "topic" && threadId ? `${msg.chatId}:${threadId}` : msg.chatId);
|
|
15972
16228
|
log.info("intake", "enter", {
|
|
15973
16229
|
scope,
|
|
15974
16230
|
chatType: msg.chatType,
|
|
@@ -16051,6 +16307,11 @@ async function intakeMessage(deps) {
|
|
|
16051
16307
|
log.info("intake", "command", { scope, droppedPending: dropped.length });
|
|
16052
16308
|
return;
|
|
16053
16309
|
}
|
|
16310
|
+
if (workerScope && !activeRuns.get(scope) && runningWorkers(activeRuns.scopes(), emsg.chatId) >= MAX_DM_WORKERS) {
|
|
16311
|
+
log.info("intake", "worker-limit", { scope, limit: MAX_DM_WORKERS });
|
|
16312
|
+
await channel.send(emsg.chatId, { markdown: `\u4F60\u540C\u65F6\u5728\u8DD1\u7684\u4EFB\u52A1\u5DF2\u7ECF\u6709 ${MAX_DM_WORKERS} \u4E2A\uFF0C\u7B49\u5176\u4E2D\u4E00\u4E2A\u7ED3\u675F\u540E\u518D\u53D1\u8FD9\u6761\u3002` }, { replyTo: emsg.messageId }).catch((err) => log.warn("intake", "worker-limit-reply-failed", { err: String(err) }));
|
|
16313
|
+
return;
|
|
16314
|
+
}
|
|
16054
16315
|
const size = pending.push(scope, emsg);
|
|
16055
16316
|
log.info("intake", "queued", { scope, queueSize: size, debounceMs: DEBOUNCE_MS });
|
|
16056
16317
|
}
|
|
@@ -16152,6 +16413,8 @@ async function runAgentBatchInner(deps) {
|
|
|
16152
16413
|
workspaces,
|
|
16153
16414
|
media,
|
|
16154
16415
|
batch,
|
|
16416
|
+
arrival,
|
|
16417
|
+
pushToRouter,
|
|
16155
16418
|
controls,
|
|
16156
16419
|
cotClient,
|
|
16157
16420
|
callbackAuth,
|
|
@@ -16239,7 +16502,7 @@ async function runAgentBatchInner(deps) {
|
|
|
16239
16502
|
channel.botIdentity,
|
|
16240
16503
|
extraInstructions
|
|
16241
16504
|
);
|
|
16242
|
-
const dispatchStart = firstMsg.chatType === "p2p" && !threadId && Boolean(controls.profileConfig.preferences.taskBindings) && isDispatchMarker(firstMsg.content);
|
|
16505
|
+
const dispatchStart = firstMsg.chatType === "p2p" && !threadId && Boolean(controls.profileConfig.preferences.taskBindings) && (isDispatchMarker(firstMsg.content) || isDispatchRoot(controls.profileConfig.preferences.taskBindings.dir, firstMsg.messageId));
|
|
16243
16506
|
const sendOpts = {
|
|
16244
16507
|
replyTo: dispatchStart ? firstMsg.messageId : lastMsg.messageId,
|
|
16245
16508
|
...mode === "topic" && threadId || dispatchStart ? { replyInThread: true } : {}
|
|
@@ -16286,7 +16549,7 @@ async function runAgentBatchInner(deps) {
|
|
|
16286
16549
|
now: Date.now(),
|
|
16287
16550
|
stopGraceMs: getAgentStopGraceMs(controls.cfg),
|
|
16288
16551
|
...binding && taskPlan?.ok ? { task: { binding, maxBudgetUsd: taskPlan.maxBudgetUsd } } : {},
|
|
16289
|
-
...deps.userRead?.extraEnv || deps.claudeEnv ? { extraEnv: { ...deps.claudeEnv, ...deps.userRead?.extraEnv } } : {},
|
|
16552
|
+
...deps.userRead?.extraEnv || deps.claudeEnv || firstMsg.chatType === "p2p" ? { extraEnv: { ...deps.claudeEnv, ...deps.userRead?.extraEnv, ...firstMsg.chatType === "p2p" ? { SDLC_DM_CHAT: chatId } : {}, ...firstMsg.chatType === "p2p" && scope === chatId ? { SDLC_DM_MSG: lastMsg.messageId } : {} } } : {},
|
|
16290
16553
|
observability: {
|
|
16291
16554
|
profile: controls.profile,
|
|
16292
16555
|
agent: capability.agentId,
|
|
@@ -16312,6 +16575,31 @@ async function runAgentBatchInner(deps) {
|
|
|
16312
16575
|
return;
|
|
16313
16576
|
}
|
|
16314
16577
|
const { execution, cwdRealpath: cwd } = flow;
|
|
16578
|
+
if (firstMsg.chatType === "p2p" && scope.startsWith(`${chatId}:`)) {
|
|
16579
|
+
void observeWorkerRun({
|
|
16580
|
+
events: execution.subscribe(),
|
|
16581
|
+
chatId,
|
|
16582
|
+
scope,
|
|
16583
|
+
runId: execution.runId,
|
|
16584
|
+
ask: lastMsg.content,
|
|
16585
|
+
senderId: firstMsg.senderId,
|
|
16586
|
+
...firstMsg.senderName ? { senderName: firstMsg.senderName } : {},
|
|
16587
|
+
dir: controls.profileConfig.preferences.taskBindings?.dir,
|
|
16588
|
+
push: (m) => {
|
|
16589
|
+
pushToRouter?.(m);
|
|
16590
|
+
},
|
|
16591
|
+
onError: (step, err) => log.fail("worker-report", err, { step, scope })
|
|
16592
|
+
});
|
|
16593
|
+
}
|
|
16594
|
+
if (arrival) {
|
|
16595
|
+
log.info("intake", "arrival-to-start", {
|
|
16596
|
+
scope,
|
|
16597
|
+
mode,
|
|
16598
|
+
batchSize: batch.length,
|
|
16599
|
+
behindRun: arrival.behindRun,
|
|
16600
|
+
arrivalToStartMs: Date.now() - arrival.firstArrivedAt
|
|
16601
|
+
});
|
|
16602
|
+
}
|
|
16315
16603
|
log.info("prompt", "built", {
|
|
16316
16604
|
promptChars: flow.policy.prompt.length,
|
|
16317
16605
|
quotes: quotes.length,
|
|
@@ -19420,8 +19708,8 @@ function openBrowser(url) {
|
|
|
19420
19708
|
|
|
19421
19709
|
// src/bridge/cli/commands/user-gateway.ts
|
|
19422
19710
|
import { spawnSync as spawnSync5 } from "child_process";
|
|
19423
|
-
import { existsSync as
|
|
19424
|
-
import { join as
|
|
19711
|
+
import { existsSync as existsSync11 } from "fs";
|
|
19712
|
+
import { join as join30 } from "path";
|
|
19425
19713
|
|
|
19426
19714
|
// src/bridge/user-gateway/db-query.ts
|
|
19427
19715
|
import { spawn as spawn3 } from "child_process";
|
|
@@ -19479,13 +19767,13 @@ function toResult(r) {
|
|
|
19479
19767
|
|
|
19480
19768
|
// src/bridge/user-gateway/gateway.ts
|
|
19481
19769
|
import { randomBytes as randomBytes10 } from "crypto";
|
|
19482
|
-
import { existsSync as
|
|
19770
|
+
import { existsSync as existsSync10 } from "fs";
|
|
19483
19771
|
import { mkdir as mkdir19, rm as rm14, writeFile as writeFile9 } from "fs/promises";
|
|
19484
|
-
import { join as
|
|
19772
|
+
import { join as join29 } from "path";
|
|
19485
19773
|
|
|
19486
19774
|
// src/bridge/user-gateway/app-token.ts
|
|
19487
19775
|
import { spawn as spawn4 } from "child_process";
|
|
19488
|
-
import { readFileSync as
|
|
19776
|
+
import { readFileSync as readFileSync6 } from "fs";
|
|
19489
19777
|
var APP_TOKEN_REFRESH_BEFORE_MS = 5 * 6e4;
|
|
19490
19778
|
var APP_TOKEN_FAIL_BACKOFF_MS = 6e4;
|
|
19491
19779
|
function createAppTokenCache(fetcher, now = Date.now) {
|
|
@@ -19530,7 +19818,7 @@ function brandOfTenant(tenant) {
|
|
|
19530
19818
|
}
|
|
19531
19819
|
function sourceBrand(sourceConfigFile) {
|
|
19532
19820
|
try {
|
|
19533
|
-
return brandOfTenant(JSON.parse(
|
|
19821
|
+
return brandOfTenant(JSON.parse(readFileSync6(sourceConfigFile, "utf8")).accounts?.app?.tenant);
|
|
19534
19822
|
} catch {
|
|
19535
19823
|
return "lark";
|
|
19536
19824
|
}
|
|
@@ -19567,7 +19855,7 @@ function run(command, args, input, env, timeoutMs) {
|
|
|
19567
19855
|
}
|
|
19568
19856
|
function realAppTokenFetcher(sourceConfigFile) {
|
|
19569
19857
|
return async () => {
|
|
19570
|
-
const cfg = JSON.parse(
|
|
19858
|
+
const cfg = JSON.parse(readFileSync6(sourceConfigFile, "utf8"));
|
|
19571
19859
|
const app = cfg.accounts?.app;
|
|
19572
19860
|
if (!app?.id) throw new Error("source \u914D\u7F6E\u91CC\u6CA1\u6709\u5E94\u7528 id");
|
|
19573
19861
|
let cred;
|
|
@@ -19723,10 +20011,10 @@ function createGateway(opts) {
|
|
|
19723
20011
|
const used = /* @__PURE__ */ new Map();
|
|
19724
20012
|
const inFlight = /* @__PURE__ */ new Set();
|
|
19725
20013
|
const pendingAuth = /* @__PURE__ */ new Map();
|
|
19726
|
-
const tokenRoot =
|
|
19727
|
-
const userDir = (openId) =>
|
|
19728
|
-
const authorizedMark = (openId) =>
|
|
19729
|
-
const isAuthorized = (openId) =>
|
|
20014
|
+
const tokenRoot = join29(opts.stateDir, "user-tokens", opts.appId);
|
|
20015
|
+
const userDir = (openId) => join29(tokenRoot, openId);
|
|
20016
|
+
const authorizedMark = (openId) => join29(userDir(openId), ".authorized");
|
|
20017
|
+
const isAuthorized = (openId) => existsSync10(authorizedMark(openId));
|
|
19730
20018
|
const brand = sourceBrand(opts.larkSourceConfig);
|
|
19731
20019
|
function env(dir) {
|
|
19732
20020
|
return {
|
|
@@ -19737,11 +20025,11 @@ function createGateway(opts) {
|
|
|
19737
20025
|
LARKSUITE_CLI_NO_SKILLS_NOTIFIER: "1"
|
|
19738
20026
|
};
|
|
19739
20027
|
}
|
|
19740
|
-
const appDir =
|
|
20028
|
+
const appDir = join29(opts.stateDir, "app");
|
|
19741
20029
|
const bound2 = /* @__PURE__ */ new Set();
|
|
19742
20030
|
async function ensureBound(dir, identity) {
|
|
19743
20031
|
if (bound2.has(dir)) return;
|
|
19744
|
-
if (!
|
|
20032
|
+
if (!existsSync10(join29(dir, "lark-channel", "config.json"))) {
|
|
19745
20033
|
await mkdir19(dir, { recursive: true, mode: 448 });
|
|
19746
20034
|
const r = await opts.exec(["config", "bind", "--source", "lark-channel", "--identity", identity], env(dir), 3e4);
|
|
19747
20035
|
if (r.code !== 0) throw new Error(`lark-cli \u7ED1\u5B9A\u5931\u8D25\uFF1A${larkError(r).detail}`);
|
|
@@ -20040,7 +20328,7 @@ function createGateway(opts) {
|
|
|
20040
20328
|
if (typeof v === "string") return { status: v };
|
|
20041
20329
|
if (v.text?.trim() !== REVOKE_TEXT2) return { status: "not_revoke" };
|
|
20042
20330
|
for (const [h, x] of handles) if (x.openId === v.openId) handles.delete(h);
|
|
20043
|
-
const had =
|
|
20331
|
+
const had = existsSync10(userDir(v.openId));
|
|
20044
20332
|
await rm14(userDir(v.openId), { recursive: true, force: true });
|
|
20045
20333
|
bound2.delete(userDir(v.openId));
|
|
20046
20334
|
log.info("user-gateway", "auth.revoked", { sender: tail6(v.openId), messageId, had });
|
|
@@ -20287,10 +20575,10 @@ function fetchToken(cmd) {
|
|
|
20287
20575
|
}
|
|
20288
20576
|
async function runUserGateway(opts) {
|
|
20289
20577
|
if (!/^cli_[A-Za-z0-9]+$/.test(opts.appId)) throw new Error("--app-id \u683C\u5F0F\u4E0D\u5BF9");
|
|
20290
|
-
if (!
|
|
20578
|
+
if (!existsSync11(opts.larkSourceConfig)) throw new Error(`\u627E\u4E0D\u5230 lark-cli source \u914D\u7F6E\uFF1A${opts.larkSourceConfig}`);
|
|
20291
20579
|
const port = Number(opts.port ?? 8788);
|
|
20292
20580
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("--port \u4E0D\u5BF9");
|
|
20293
|
-
configureLogger({ logsDir:
|
|
20581
|
+
configureLogger({ logsDir: join30(opts.stateDir, "logs") });
|
|
20294
20582
|
const gateway = createGateway({
|
|
20295
20583
|
appId: opts.appId,
|
|
20296
20584
|
stateDir: opts.stateDir,
|