dsh-agent-enhancer 0.4.1 → 0.5.0
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/README.md +4 -3
- package/lib/client/dsh/settings-catalog.d.ts +3 -3
- package/lib/client/dsh/settings-catalog.d.ts.map +1 -1
- package/lib/client/dsh/settings-features.d.ts +2 -0
- package/lib/client/dsh/settings-features.d.ts.map +1 -1
- package/lib/client/dsh/settings.d.ts.map +1 -1
- package/lib/client/locales.d.ts +171 -1
- package/lib/client/locales.d.ts.map +1 -1
- package/lib/client/remote/panel.d.ts +19 -0
- package/lib/client/remote/panel.d.ts.map +1 -0
- package/lib/client/remote/qr-code.d.ts +13 -0
- package/lib/client/remote/qr-code.d.ts.map +1 -0
- package/lib/client/remote/qr.d.ts +27 -0
- package/lib/client/remote/qr.d.ts.map +1 -0
- package/lib/client/remote.d.ts +36 -1
- package/lib/client/remote.d.ts.map +1 -1
- package/lib/client/soft-pause/action.d.ts.map +1 -1
- package/lib/client/soft-pause/controller.d.ts +8 -8
- package/lib/client/soft-pause/controller.d.ts.map +1 -1
- package/lib/client/soft-pause/visibility.d.ts +7 -1
- package/lib/client/soft-pause/visibility.d.ts.map +1 -1
- package/lib/client.js +2786 -1096
- package/lib/client.js.map +1 -1
- package/lib/config.d.ts +1 -1
- package/lib/config.d.ts.map +1 -1
- package/lib/host/index.d.ts +40 -2
- package/lib/host/index.d.ts.map +1 -1
- package/lib/host/remote/approval-router.d.ts +35 -0
- package/lib/host/remote/approval-router.d.ts.map +1 -0
- package/lib/host/remote/bindings.d.ts +56 -0
- package/lib/host/remote/bindings.d.ts.map +1 -0
- package/lib/host/remote/channels/cursor.d.ts +18 -0
- package/lib/host/remote/channels/cursor.d.ts.map +1 -0
- package/lib/host/remote/channels/poller.d.ts +57 -0
- package/lib/host/remote/channels/poller.d.ts.map +1 -0
- package/lib/host/remote/channels/status.d.ts +31 -0
- package/lib/host/remote/channels/status.d.ts.map +1 -0
- package/lib/host/remote/channels/types.d.ts +57 -0
- package/lib/host/remote/channels/types.d.ts.map +1 -0
- package/lib/host/remote/commands.d.ts +39 -0
- package/lib/host/remote/commands.d.ts.map +1 -0
- package/lib/host/remote/controller.d.ts +107 -0
- package/lib/host/remote/controller.d.ts.map +1 -0
- package/lib/host/remote/feishu/adapter.d.ts +28 -0
- package/lib/host/remote/feishu/adapter.d.ts.map +1 -0
- package/lib/host/remote/feishu/channel.d.ts +47 -0
- package/lib/host/remote/feishu/channel.d.ts.map +1 -0
- package/lib/host/remote/feishu/credentials.d.ts +10 -0
- package/lib/host/remote/feishu/credentials.d.ts.map +1 -0
- package/lib/host/remote/feishu/transport.d.ts +109 -0
- package/lib/host/remote/feishu/transport.d.ts.map +1 -0
- package/lib/host/remote/host-bridge.d.ts +64 -0
- package/lib/host/remote/host-bridge.d.ts.map +1 -0
- package/lib/host/remote/hub.d.ts +101 -0
- package/lib/host/remote/hub.d.ts.map +1 -0
- package/lib/host/remote/ports.d.ts +7 -0
- package/lib/host/remote/ports.d.ts.map +1 -0
- package/lib/host/remote/render.d.ts +33 -0
- package/lib/host/remote/render.d.ts.map +1 -0
- package/lib/host/remote/task-board.d.ts +44 -0
- package/lib/host/remote/task-board.d.ts.map +1 -0
- package/lib/host/remote/telegram/adapter.d.ts +29 -0
- package/lib/host/remote/telegram/adapter.d.ts.map +1 -0
- package/lib/host/remote/telegram/channel.d.ts +49 -0
- package/lib/host/remote/telegram/channel.d.ts.map +1 -0
- package/lib/host/remote/telegram/credentials.d.ts +10 -0
- package/lib/host/remote/telegram/credentials.d.ts.map +1 -0
- package/lib/host/remote/telegram/transport.d.ts +54 -0
- package/lib/host/remote/telegram/transport.d.ts.map +1 -0
- package/lib/host/remote/types.d.ts +60 -0
- package/lib/host/remote/types.d.ts.map +1 -0
- package/lib/host/remote/weixin/adapter.d.ts +39 -0
- package/lib/host/remote/weixin/adapter.d.ts.map +1 -0
- package/lib/host/remote/weixin/capabilities.d.ts +4 -0
- package/lib/host/remote/weixin/capabilities.d.ts.map +1 -0
- package/lib/host/remote/weixin/channel.d.ts +52 -0
- package/lib/host/remote/weixin/channel.d.ts.map +1 -0
- package/lib/host/remote/weixin/credentials.d.ts +17 -0
- package/lib/host/remote/weixin/credentials.d.ts.map +1 -0
- package/lib/host/remote/weixin/cursor.d.ts +2 -0
- package/lib/host/remote/weixin/cursor.d.ts.map +1 -0
- package/lib/host/remote/weixin/login.d.ts +47 -0
- package/lib/host/remote/weixin/login.d.ts.map +1 -0
- package/lib/host/remote/weixin/transport.d.ts +74 -0
- package/lib/host/remote/weixin/transport.d.ts.map +1 -0
- package/lib/host/rpc.d.ts +167 -0
- package/lib/host/rpc.d.ts.map +1 -1
- package/lib/host/soft-pause/gate.d.ts +13 -0
- package/lib/host/soft-pause/gate.d.ts.map +1 -1
- package/lib/host/soft-pause/lineage.d.ts +42 -0
- package/lib/host/soft-pause/lineage.d.ts.map +1 -0
- package/lib/host/soft-pause/live.d.ts.map +1 -1
- package/lib/index.js +4052 -188
- package/lib/index.js.map +4 -4
- package/package.json +3 -2
package/lib/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/host/index.ts
|
|
2
|
-
import { existsSync as existsSync20, mkdirSync as
|
|
2
|
+
import { existsSync as existsSync20, mkdirSync as mkdirSync15, readdirSync as readdirSync7, renameSync as renameSync11, rmdirSync } from "node:fs";
|
|
3
3
|
import { homedir as homedir5 } from "node:os";
|
|
4
|
-
import { join as
|
|
4
|
+
import { join as join33 } from "node:path";
|
|
5
5
|
import z5 from "@deepseek-ai/schemastery";
|
|
6
6
|
import { RemoteError as RemoteError2, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
7
7
|
|
|
@@ -116,6 +116,7 @@ var DEFAULT_SETTINGS = {
|
|
|
116
116
|
webChatBridgeEnabled: true,
|
|
117
117
|
instructionsSkillsEnabled: true,
|
|
118
118
|
mcpConnectorsEnabled: true,
|
|
119
|
+
remoteControlEnabled: true,
|
|
119
120
|
optimizeProvider: "",
|
|
120
121
|
optimizeModel: "",
|
|
121
122
|
optimizeReasoningEffort: "",
|
|
@@ -166,6 +167,7 @@ function resolveSettings(value) {
|
|
|
166
167
|
webChatBridgeEnabled: value?.webChatBridgeEnabled ?? true,
|
|
167
168
|
instructionsSkillsEnabled: value?.instructionsSkillsEnabled ?? true,
|
|
168
169
|
mcpConnectorsEnabled: value?.mcpConnectorsEnabled ?? true,
|
|
170
|
+
remoteControlEnabled: value?.remoteControlEnabled ?? true,
|
|
169
171
|
optimizeProvider: text(value?.optimizeProvider),
|
|
170
172
|
optimizeModel: text(value?.optimizeModel),
|
|
171
173
|
optimizeReasoningEffort: text(value?.optimizeReasoningEffort),
|
|
@@ -2236,10 +2238,10 @@ var PlaywrightDriver = class {
|
|
|
2236
2238
|
const box = await locator.boundingBox().catch(() => null);
|
|
2237
2239
|
if (box === null) return null;
|
|
2238
2240
|
const viewport = page.viewportSize() ?? { width: 1280, height: 800 };
|
|
2239
|
-
const
|
|
2240
|
-
if (
|
|
2241
|
+
const clip3 = clampThumbnailClip(box, viewport);
|
|
2242
|
+
if (clip3 === null) return null;
|
|
2241
2243
|
const buffer = await page.screenshot({
|
|
2242
|
-
clip:
|
|
2244
|
+
clip: clip3,
|
|
2243
2245
|
type: "jpeg",
|
|
2244
2246
|
quality: 60,
|
|
2245
2247
|
scale: "css",
|
|
@@ -6377,11 +6379,11 @@ function escapeRegExp(value) {
|
|
|
6377
6379
|
async function buildAuxiliaryModelCatalog(ctx) {
|
|
6378
6380
|
const selection = ctx.agentDefaultModel.currentSelection();
|
|
6379
6381
|
const providers = ctx.llm.listProviders();
|
|
6380
|
-
const catalog = await Promise.all(providers.map(async (
|
|
6382
|
+
const catalog = await Promise.all(providers.map(async (provider4) => {
|
|
6381
6383
|
try {
|
|
6382
|
-
const models = await ctx.llm.listModels(
|
|
6384
|
+
const models = await ctx.llm.listModels(provider4.id);
|
|
6383
6385
|
const entries = await Promise.all(models.map(async (model) => {
|
|
6384
|
-
const resolved = await ctx.llm.resolveModelInfo(
|
|
6386
|
+
const resolved = await ctx.llm.resolveModelInfo(provider4.id, model.id);
|
|
6385
6387
|
const reasoning = resolved.reasoning === void 0 ? void 0 : {
|
|
6386
6388
|
efforts: resolved.reasoning.efforts.map((effort) => ({
|
|
6387
6389
|
id: String(effort.id),
|
|
@@ -6399,14 +6401,14 @@ async function buildAuxiliaryModelCatalog(ctx) {
|
|
|
6399
6401
|
}));
|
|
6400
6402
|
return {
|
|
6401
6403
|
kind: "group",
|
|
6402
|
-
group: { id:
|
|
6404
|
+
group: { id: provider4.id, name: provider4.name, models: entries }
|
|
6403
6405
|
};
|
|
6404
6406
|
} catch (error) {
|
|
6405
6407
|
return {
|
|
6406
6408
|
kind: "failure",
|
|
6407
6409
|
failure: {
|
|
6408
|
-
id:
|
|
6409
|
-
name:
|
|
6410
|
+
id: provider4.id,
|
|
6411
|
+
name: provider4.name,
|
|
6410
6412
|
message: error instanceof Error ? error.message : String(error)
|
|
6411
6413
|
}
|
|
6412
6414
|
};
|
|
@@ -15963,20 +15965,20 @@ import { ReasoningEffortId } from "@deepseek-ai/dsh-llm/brand";
|
|
|
15963
15965
|
var AUTO_CATALOG_NAME = "Auto";
|
|
15964
15966
|
var AUTO_CONTEXT_WINDOW = 524288;
|
|
15965
15967
|
var AutoCatalogAdapter = class extends LlmAdapter {
|
|
15966
|
-
providerInfo(
|
|
15967
|
-
return { id:
|
|
15968
|
+
providerInfo(provider4) {
|
|
15969
|
+
return { id: provider4, name: AUTO_CATALOG_NAME };
|
|
15968
15970
|
}
|
|
15969
|
-
listModels(
|
|
15971
|
+
listModels(provider4) {
|
|
15970
15972
|
return Promise.resolve([{
|
|
15971
|
-
provider,
|
|
15973
|
+
provider: provider4,
|
|
15972
15974
|
id: AUTO_MODEL,
|
|
15973
15975
|
name: AUTO_CATALOG_NAME,
|
|
15974
15976
|
inputModalities: ["text"]
|
|
15975
15977
|
}]);
|
|
15976
15978
|
}
|
|
15977
|
-
resolveModel(
|
|
15979
|
+
resolveModel(provider4, model) {
|
|
15978
15980
|
return Promise.resolve({
|
|
15979
|
-
provider,
|
|
15981
|
+
provider: provider4,
|
|
15980
15982
|
id: model,
|
|
15981
15983
|
name: AUTO_CATALOG_NAME,
|
|
15982
15984
|
inputModalities: ["text"],
|
|
@@ -16095,7 +16097,7 @@ function routeConfig(config, mapped) {
|
|
|
16095
16097
|
function installAutoCatalogModel(ctx) {
|
|
16096
16098
|
const llm = ctx.llm;
|
|
16097
16099
|
if (typeof llm.registerAdapter !== "function" || typeof llm.listProviders !== "function") return;
|
|
16098
|
-
if (llm.listProviders().some((
|
|
16100
|
+
if (llm.listProviders().some((provider4) => provider4.id === AUTO_PROVIDER)) {
|
|
16099
16101
|
ctx.logger.warn("agent-enhancer: Auto was not added to the model catalog because that provider id is already registered");
|
|
16100
16102
|
return;
|
|
16101
16103
|
}
|
|
@@ -16153,7 +16155,7 @@ function installAutoSessionRoute(ctx, options) {
|
|
|
16153
16155
|
map,
|
|
16154
16156
|
classifierEnabled: settings.autoClassifierEnabled,
|
|
16155
16157
|
classify: classify2,
|
|
16156
|
-
isAvailable: (
|
|
16158
|
+
isAvailable: (provider4, model) => provider4 !== "" && model !== "" && !isAutoModel({ provider: provider4, model }),
|
|
16157
16159
|
signal,
|
|
16158
16160
|
fallback: fallbackRoute(ctx, asAgent(agent))
|
|
16159
16161
|
});
|
|
@@ -16242,43 +16244,67 @@ var SoftPauseGate = class {
|
|
|
16242
16244
|
* callers can check `signal.aborted` and return `{ kind: 'reject' }`.
|
|
16243
16245
|
*/
|
|
16244
16246
|
async waitIfEngaged(sessionId, signal) {
|
|
16245
|
-
|
|
16247
|
+
await this.waitWhileEngaged([sessionId], signal, { clearOnAbort: sessionId });
|
|
16248
|
+
}
|
|
16249
|
+
/**
|
|
16250
|
+
* Wait while ANY of `sessionIds` is engaged, settling only when none is.
|
|
16251
|
+
* A subagent step passes its own id plus its engaged subagent ancestors, so
|
|
16252
|
+
* releasing one of them cannot let the step through while another holds it.
|
|
16253
|
+
*/
|
|
16254
|
+
async waitWhileEngaged(sessionIds, signal, options = {}) {
|
|
16255
|
+
const owners = [...new Set(sessionIds)];
|
|
16256
|
+
if (!owners.some((id) => this.engaged.has(id))) return;
|
|
16246
16257
|
if (signal.aborted) {
|
|
16247
|
-
this.clear(
|
|
16258
|
+
if (options.clearOnAbort !== void 0) this.clear(options.clearOnAbort);
|
|
16248
16259
|
return;
|
|
16249
16260
|
}
|
|
16250
16261
|
await new Promise((resolve17) => {
|
|
16251
16262
|
let settled = false;
|
|
16263
|
+
let registered = [];
|
|
16264
|
+
let waiter;
|
|
16265
|
+
const detach = () => {
|
|
16266
|
+
signal.removeEventListener("abort", onAbort);
|
|
16267
|
+
};
|
|
16252
16268
|
const settle = () => {
|
|
16253
16269
|
if (settled) return;
|
|
16254
16270
|
settled = true;
|
|
16255
|
-
|
|
16256
|
-
const
|
|
16257
|
-
|
|
16258
|
-
|
|
16259
|
-
|
|
16271
|
+
detach();
|
|
16272
|
+
for (const id of registered) {
|
|
16273
|
+
const bucket = this.waiters.get(id);
|
|
16274
|
+
if (bucket === void 0) continue;
|
|
16275
|
+
bucket.delete(waiter);
|
|
16276
|
+
if (bucket.size === 0) this.waiters.delete(id);
|
|
16260
16277
|
}
|
|
16278
|
+
registered = [];
|
|
16261
16279
|
resolve17();
|
|
16262
16280
|
};
|
|
16281
|
+
const register = () => {
|
|
16282
|
+
registered = [];
|
|
16283
|
+
for (const id of owners) {
|
|
16284
|
+
if (!this.engaged.has(id)) continue;
|
|
16285
|
+
let bucket = this.waiters.get(id);
|
|
16286
|
+
if (bucket === void 0) {
|
|
16287
|
+
bucket = /* @__PURE__ */ new Set();
|
|
16288
|
+
this.waiters.set(id, bucket);
|
|
16289
|
+
}
|
|
16290
|
+
bucket.add(waiter);
|
|
16291
|
+
registered.push(id);
|
|
16292
|
+
}
|
|
16293
|
+
};
|
|
16263
16294
|
const onAbort = () => {
|
|
16264
|
-
this.
|
|
16265
|
-
|
|
16295
|
+
if (options.clearOnAbort !== void 0) this.clear(options.clearOnAbort);
|
|
16296
|
+
settle();
|
|
16266
16297
|
};
|
|
16267
|
-
const
|
|
16268
|
-
|
|
16298
|
+
const wake = () => {
|
|
16299
|
+
if (settled) return;
|
|
16300
|
+
if (owners.some((id) => this.engaged.has(id))) register();
|
|
16301
|
+
else settle();
|
|
16269
16302
|
};
|
|
16270
|
-
|
|
16271
|
-
|
|
16272
|
-
if (bucket === void 0) {
|
|
16273
|
-
bucket = /* @__PURE__ */ new Set();
|
|
16274
|
-
this.waiters.set(sessionId, bucket);
|
|
16275
|
-
}
|
|
16276
|
-
bucket.add(waiter);
|
|
16303
|
+
waiter = { wake };
|
|
16304
|
+
register();
|
|
16277
16305
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
16278
|
-
if (
|
|
16279
|
-
|
|
16280
|
-
settle();
|
|
16281
|
-
}
|
|
16306
|
+
if (signal.aborted) onAbort();
|
|
16307
|
+
else if (!owners.some((id) => this.engaged.has(id))) settle();
|
|
16282
16308
|
});
|
|
16283
16309
|
}
|
|
16284
16310
|
/** Drop engaged + waiters without distinguishing resume vs abort. */
|
|
@@ -16290,19 +16316,62 @@ var SoftPauseGate = class {
|
|
|
16290
16316
|
const bucket = this.waiters.get(sessionId);
|
|
16291
16317
|
if (bucket === void 0) return;
|
|
16292
16318
|
this.waiters.delete(sessionId);
|
|
16293
|
-
for (const waiter of bucket)
|
|
16294
|
-
waiter.detachAbort();
|
|
16295
|
-
waiter.settle();
|
|
16296
|
-
}
|
|
16319
|
+
for (const waiter of bucket) waiter.wake();
|
|
16297
16320
|
}
|
|
16298
16321
|
};
|
|
16299
16322
|
|
|
16323
|
+
// src/host/soft-pause/lineage.ts
|
|
16324
|
+
function sessionLineage(session, sessions) {
|
|
16325
|
+
const ids = [];
|
|
16326
|
+
const visited = /* @__PURE__ */ new Set();
|
|
16327
|
+
let id = session.header?.id ?? session.id;
|
|
16328
|
+
let header = session.header;
|
|
16329
|
+
while (id !== void 0 && !visited.has(id)) {
|
|
16330
|
+
visited.add(id);
|
|
16331
|
+
ids.push(id);
|
|
16332
|
+
if (header === void 0) break;
|
|
16333
|
+
if (header.origin !== "subagent" || header.parentSession === void 0) break;
|
|
16334
|
+
id = header.parentSession;
|
|
16335
|
+
header = parentHeader(sessions, id);
|
|
16336
|
+
}
|
|
16337
|
+
return ids;
|
|
16338
|
+
}
|
|
16339
|
+
function parentHeader(sessions, id) {
|
|
16340
|
+
try {
|
|
16341
|
+
return sessions?.get(id)?.header;
|
|
16342
|
+
} catch {
|
|
16343
|
+
return void 0;
|
|
16344
|
+
}
|
|
16345
|
+
}
|
|
16346
|
+
function isTreeRunning(rootSessionId, agents, sessions) {
|
|
16347
|
+
for (const agent of agents) {
|
|
16348
|
+
if (agent.status !== "running") continue;
|
|
16349
|
+
if (agent.session === void 0) continue;
|
|
16350
|
+
if (sessionLineage(agent.session, sessions).includes(rootSessionId)) return true;
|
|
16351
|
+
}
|
|
16352
|
+
return false;
|
|
16353
|
+
}
|
|
16354
|
+
function sessionStore(ctx) {
|
|
16355
|
+
try {
|
|
16356
|
+
return ctx.get("sessions");
|
|
16357
|
+
} catch {
|
|
16358
|
+
return void 0;
|
|
16359
|
+
}
|
|
16360
|
+
}
|
|
16361
|
+
|
|
16300
16362
|
// src/host/soft-pause/live.ts
|
|
16301
16363
|
function installSoftPause(ctx, options) {
|
|
16302
16364
|
ctx.on("agent/pre-step", async (payload, next) => {
|
|
16303
16365
|
if (!options.enabled()) return await next();
|
|
16304
|
-
const
|
|
16305
|
-
|
|
16366
|
+
const session = payload.agent.session;
|
|
16367
|
+
const own = session.header?.id ?? session.id;
|
|
16368
|
+
const owners = sessionLineage(session, sessionStore(ctx)).filter((id) => options.gate.isEngaged(id));
|
|
16369
|
+
if (owners.length === 0) return await next();
|
|
16370
|
+
await options.gate.waitWhileEngaged(
|
|
16371
|
+
owners,
|
|
16372
|
+
payload.signal,
|
|
16373
|
+
own !== void 0 && owners.includes(own) ? { clearOnAbort: own } : {}
|
|
16374
|
+
);
|
|
16306
16375
|
if (payload.signal.aborted) return { kind: "reject" };
|
|
16307
16376
|
return await next();
|
|
16308
16377
|
});
|
|
@@ -16510,8 +16579,8 @@ var AuxiliaryModels = class {
|
|
|
16510
16579
|
featureSettings(feature) {
|
|
16511
16580
|
return auxiliaryModelOf(this.enhancerSettings(), feature);
|
|
16512
16581
|
}
|
|
16513
|
-
modelExists(
|
|
16514
|
-
return
|
|
16582
|
+
modelExists(provider4, model) {
|
|
16583
|
+
return provider4 !== "" && model !== "";
|
|
16515
16584
|
}
|
|
16516
16585
|
sessionModelSelection(session) {
|
|
16517
16586
|
return projectedSessionModel(this.ctx, session);
|
|
@@ -16554,7 +16623,7 @@ var AuxiliaryModels = class {
|
|
|
16554
16623
|
map,
|
|
16555
16624
|
classifierEnabled: settings.autoClassifierEnabled,
|
|
16556
16625
|
classify: classify2,
|
|
16557
|
-
isAvailable: (
|
|
16626
|
+
isAvailable: (provider4, model) => this.modelExists(provider4, model),
|
|
16558
16627
|
fallback: this.fallbackFromSession(session, override)
|
|
16559
16628
|
});
|
|
16560
16629
|
} catch (error) {
|
|
@@ -17113,7 +17182,7 @@ function normalizeReasoningEffort(value) {
|
|
|
17113
17182
|
if (typeof value !== "string") return "";
|
|
17114
17183
|
return value.trim();
|
|
17115
17184
|
}
|
|
17116
|
-
function usageCallFromReport(source,
|
|
17185
|
+
function usageCallFromReport(source, provider4, model, usage, at, reasoningEffort = "") {
|
|
17117
17186
|
if (!Number.isSafeInteger(at) || at < 0) return void 0;
|
|
17118
17187
|
if (!USAGE_SOURCES.includes(source)) return void 0;
|
|
17119
17188
|
const inputTokens = tokenCount(usage.inputTokens);
|
|
@@ -17122,7 +17191,7 @@ function usageCallFromReport(source, provider, model, usage, at, reasoningEffort
|
|
|
17122
17191
|
const cacheWriteTokens = tokenCount(usage.cacheWriteTokens);
|
|
17123
17192
|
const reasoningTokens = tokenCount(usage.reasoningTokens);
|
|
17124
17193
|
if (inputTokens === void 0 || outputTokens === void 0 || cacheReadTokens === void 0 || cacheWriteTokens === void 0 || reasoningTokens === void 0) return void 0;
|
|
17125
|
-
const routeProvider =
|
|
17194
|
+
const routeProvider = provider4.trim();
|
|
17126
17195
|
const routeModel = model.trim();
|
|
17127
17196
|
if (routeProvider === "" || routeModel === "") return void 0;
|
|
17128
17197
|
return {
|
|
@@ -17265,8 +17334,8 @@ function sourceLine(source, calls) {
|
|
|
17265
17334
|
const modelLines = [...models.values()].sort((left, right) => {
|
|
17266
17335
|
const delta = volume(right) - volume(left);
|
|
17267
17336
|
if (delta !== 0) return delta;
|
|
17268
|
-
const
|
|
17269
|
-
if (
|
|
17337
|
+
const provider4 = left.provider.localeCompare(right.provider);
|
|
17338
|
+
if (provider4 !== 0) return provider4;
|
|
17270
17339
|
const model = left.model.localeCompare(right.model);
|
|
17271
17340
|
if (model !== 0) return model;
|
|
17272
17341
|
return left.reasoningEffort.localeCompare(right.reasoningEffort);
|
|
@@ -17312,8 +17381,8 @@ function record(value) {
|
|
|
17312
17381
|
function text2(value) {
|
|
17313
17382
|
return typeof value === "string" ? value : void 0;
|
|
17314
17383
|
}
|
|
17315
|
-
function routeOf(
|
|
17316
|
-
const nextProvider = text2(
|
|
17384
|
+
function routeOf(provider4, model, reasoningEffort = "") {
|
|
17385
|
+
const nextProvider = text2(provider4)?.trim() ?? "";
|
|
17317
17386
|
const nextModel = text2(model)?.trim() ?? "";
|
|
17318
17387
|
if (nextProvider === "" || nextModel === "") return void 0;
|
|
17319
17388
|
return {
|
|
@@ -18220,7 +18289,9 @@ var softPauseSetRequestSchema = z4.strictObject({
|
|
|
18220
18289
|
});
|
|
18221
18290
|
var softPauseStateSchema = z4.strictObject({
|
|
18222
18291
|
sessionId: sessionIdSchema3,
|
|
18223
|
-
engaged: z4.boolean()
|
|
18292
|
+
engaged: z4.boolean(),
|
|
18293
|
+
/** Live work anywhere in this session's tree — a subagent can outlive the turn. */
|
|
18294
|
+
treeRunning: z4.boolean()
|
|
18224
18295
|
});
|
|
18225
18296
|
var softPauseSnapshotRequestCodec = codec(
|
|
18226
18297
|
"dsh-agent-enhancer#SoftPauseSnapshotRequest",
|
|
@@ -18231,6 +18302,120 @@ var softPauseSetRequestCodec = codec(
|
|
|
18231
18302
|
softPauseSetRequestSchema
|
|
18232
18303
|
);
|
|
18233
18304
|
var softPauseStateCodec = codec("dsh-agent-enhancer#SoftPauseState", softPauseStateSchema);
|
|
18305
|
+
var remoteChannelIdSchema = z4.enum(["weixin", "telegram", "feishu"]);
|
|
18306
|
+
var remoteChannelDeviceSchema = z4.strictObject({
|
|
18307
|
+
chatId: z4.string().min(1),
|
|
18308
|
+
boundAt: z4.number()
|
|
18309
|
+
});
|
|
18310
|
+
var remoteChannelLoginSchema = z4.strictObject({
|
|
18311
|
+
phase: z4.enum(["idle", "waiting", "connected", "failed"]),
|
|
18312
|
+
/** Raw host status token; unknown values are passed through, never guessed. */
|
|
18313
|
+
status: z4.string(),
|
|
18314
|
+
qrUrl: z4.string().optional(),
|
|
18315
|
+
error: z4.string().optional()
|
|
18316
|
+
});
|
|
18317
|
+
var remoteChannelStatusSchema = z4.strictObject({
|
|
18318
|
+
id: remoteChannelIdSchema,
|
|
18319
|
+
phase: z4.enum(["off", "unbound", "running", "failed"]),
|
|
18320
|
+
login: remoteChannelLoginSchema,
|
|
18321
|
+
devices: z4.array(remoteChannelDeviceSchema),
|
|
18322
|
+
handle: z4.string().optional(),
|
|
18323
|
+
error: z4.string().optional()
|
|
18324
|
+
});
|
|
18325
|
+
var remoteStatusSchema = z4.strictObject({
|
|
18326
|
+
phase: z4.enum(["stopped", "unbound", "running", "failed"]),
|
|
18327
|
+
channels: z4.array(remoteChannelStatusSchema),
|
|
18328
|
+
/** Sessions on the remote board; zero is valid. */
|
|
18329
|
+
tasks: z4.number().int().nonnegative(),
|
|
18330
|
+
error: z4.string().optional()
|
|
18331
|
+
});
|
|
18332
|
+
var remoteStatusRequestSchema = z4.strictObject({});
|
|
18333
|
+
var remoteLoginBeginRequestSchema = z4.strictObject({});
|
|
18334
|
+
var remoteLoginBeginResultSchema = z4.strictObject({
|
|
18335
|
+
ok: z4.boolean(),
|
|
18336
|
+
ticket: z4.string().optional(),
|
|
18337
|
+
/** Encode this URL into a QR code; opening it and scanning the page fails. */
|
|
18338
|
+
qrUrl: z4.string().optional(),
|
|
18339
|
+
error: z4.string().optional()
|
|
18340
|
+
});
|
|
18341
|
+
var remoteLoginCancelRequestSchema = z4.strictObject({});
|
|
18342
|
+
var remoteBindCodeRequestSchema = z4.strictObject({
|
|
18343
|
+
channel: remoteChannelIdSchema
|
|
18344
|
+
});
|
|
18345
|
+
var remoteBindCodeResultSchema = z4.strictObject({
|
|
18346
|
+
ok: z4.boolean(),
|
|
18347
|
+
code: z4.string().regex(/^\d{6}$/).optional(),
|
|
18348
|
+
expiresAt: z4.number().optional(),
|
|
18349
|
+
error: z4.string().optional()
|
|
18350
|
+
});
|
|
18351
|
+
var remoteRevokeRequestSchema = z4.strictObject({
|
|
18352
|
+
channel: remoteChannelIdSchema.optional(),
|
|
18353
|
+
chatId: z4.string().min(1).optional()
|
|
18354
|
+
});
|
|
18355
|
+
var remoteRevokeResultSchema = z4.strictObject({
|
|
18356
|
+
ok: z4.boolean(),
|
|
18357
|
+
revoked: z4.number().int().nonnegative(),
|
|
18358
|
+
error: z4.string().optional()
|
|
18359
|
+
});
|
|
18360
|
+
var remoteLogoutRequestSchema = z4.strictObject({
|
|
18361
|
+
channel: remoteChannelIdSchema.optional()
|
|
18362
|
+
});
|
|
18363
|
+
var remoteTelegramConnectRequestSchema = z4.strictObject({
|
|
18364
|
+
token: z4.string().min(1).max(200)
|
|
18365
|
+
});
|
|
18366
|
+
var remoteTelegramConnectResultSchema = z4.strictObject({
|
|
18367
|
+
ok: z4.boolean(),
|
|
18368
|
+
username: z4.string().optional(),
|
|
18369
|
+
error: z4.string().optional()
|
|
18370
|
+
});
|
|
18371
|
+
var remoteFeishuConnectRequestSchema = z4.strictObject({
|
|
18372
|
+
appId: z4.string().min(1).max(100),
|
|
18373
|
+
appSecret: z4.string().min(1).max(200)
|
|
18374
|
+
});
|
|
18375
|
+
var remoteFeishuConnectResultSchema = z4.strictObject({
|
|
18376
|
+
ok: z4.boolean(),
|
|
18377
|
+
name: z4.string().optional(),
|
|
18378
|
+
error: z4.string().optional()
|
|
18379
|
+
});
|
|
18380
|
+
var remoteOkResultSchema = z4.strictObject({
|
|
18381
|
+
ok: z4.literal(true)
|
|
18382
|
+
});
|
|
18383
|
+
var remoteStatusRequestCodec = codec("dsh-agent-enhancer#RemoteStatusRequest", remoteStatusRequestSchema);
|
|
18384
|
+
var remoteStatusResultCodec = codec("dsh-agent-enhancer#RemoteStatusResult", remoteStatusSchema);
|
|
18385
|
+
var remoteLoginBeginRequestCodec = codec(
|
|
18386
|
+
"dsh-agent-enhancer#RemoteLoginBeginRequest",
|
|
18387
|
+
remoteLoginBeginRequestSchema
|
|
18388
|
+
);
|
|
18389
|
+
var remoteLoginBeginResultCodec = codec(
|
|
18390
|
+
"dsh-agent-enhancer#RemoteLoginBeginResult",
|
|
18391
|
+
remoteLoginBeginResultSchema
|
|
18392
|
+
);
|
|
18393
|
+
var remoteLoginCancelRequestCodec = codec(
|
|
18394
|
+
"dsh-agent-enhancer#RemoteLoginCancelRequest",
|
|
18395
|
+
remoteLoginCancelRequestSchema
|
|
18396
|
+
);
|
|
18397
|
+
var remoteBindCodeRequestCodec = codec("dsh-agent-enhancer#RemoteBindCodeRequest", remoteBindCodeRequestSchema);
|
|
18398
|
+
var remoteBindCodeResultCodec = codec("dsh-agent-enhancer#RemoteBindCodeResult", remoteBindCodeResultSchema);
|
|
18399
|
+
var remoteRevokeRequestCodec = codec("dsh-agent-enhancer#RemoteRevokeRequest", remoteRevokeRequestSchema);
|
|
18400
|
+
var remoteRevokeResultCodec = codec("dsh-agent-enhancer#RemoteRevokeResult", remoteRevokeResultSchema);
|
|
18401
|
+
var remoteLogoutRequestCodec = codec("dsh-agent-enhancer#RemoteLogoutRequest", remoteLogoutRequestSchema);
|
|
18402
|
+
var remoteTelegramConnectRequestCodec = codec(
|
|
18403
|
+
"dsh-agent-enhancer#RemoteTelegramConnectRequest",
|
|
18404
|
+
remoteTelegramConnectRequestSchema
|
|
18405
|
+
);
|
|
18406
|
+
var remoteTelegramConnectResultCodec = codec(
|
|
18407
|
+
"dsh-agent-enhancer#RemoteTelegramConnectResult",
|
|
18408
|
+
remoteTelegramConnectResultSchema
|
|
18409
|
+
);
|
|
18410
|
+
var remoteFeishuConnectRequestCodec = codec(
|
|
18411
|
+
"dsh-agent-enhancer#RemoteFeishuConnectRequest",
|
|
18412
|
+
remoteFeishuConnectRequestSchema
|
|
18413
|
+
);
|
|
18414
|
+
var remoteFeishuConnectResultCodec = codec(
|
|
18415
|
+
"dsh-agent-enhancer#RemoteFeishuConnectResult",
|
|
18416
|
+
remoteFeishuConnectResultSchema
|
|
18417
|
+
);
|
|
18418
|
+
var remoteOkResultCodec = codec("dsh-agent-enhancer#RemoteOkResult", remoteOkResultSchema);
|
|
18234
18419
|
var showOsNotificationRequestSchema = z4.strictObject({
|
|
18235
18420
|
title: z4.string().min(1).max(120),
|
|
18236
18421
|
body: z4.string().min(1).max(240),
|
|
@@ -19274,6 +19459,102 @@ var remoteInfo = createTypertRemoteInfo({
|
|
|
19274
19459
|
}],
|
|
19275
19460
|
result: softPauseStateCodec
|
|
19276
19461
|
},
|
|
19462
|
+
"agentEnhancer/remoteStatus": {
|
|
19463
|
+
service: "agentEnhancer",
|
|
19464
|
+
implementation: "remoteStatus",
|
|
19465
|
+
invocation: { kind: "direct" },
|
|
19466
|
+
parameters: [{
|
|
19467
|
+
name: "request",
|
|
19468
|
+
source: "json",
|
|
19469
|
+
codec: remoteStatusRequestCodec,
|
|
19470
|
+
strictCodec: remoteStatusRequestCodec
|
|
19471
|
+
}],
|
|
19472
|
+
result: remoteStatusResultCodec
|
|
19473
|
+
},
|
|
19474
|
+
"agentEnhancer/remoteLoginBegin": {
|
|
19475
|
+
service: "agentEnhancer",
|
|
19476
|
+
implementation: "remoteLoginBegin",
|
|
19477
|
+
invocation: { kind: "direct" },
|
|
19478
|
+
parameters: [{
|
|
19479
|
+
name: "request",
|
|
19480
|
+
source: "json",
|
|
19481
|
+
codec: remoteLoginBeginRequestCodec,
|
|
19482
|
+
strictCodec: remoteLoginBeginRequestCodec
|
|
19483
|
+
}],
|
|
19484
|
+
result: remoteLoginBeginResultCodec
|
|
19485
|
+
},
|
|
19486
|
+
"agentEnhancer/remoteLoginCancel": {
|
|
19487
|
+
service: "agentEnhancer",
|
|
19488
|
+
implementation: "remoteLoginCancel",
|
|
19489
|
+
invocation: { kind: "direct" },
|
|
19490
|
+
parameters: [{
|
|
19491
|
+
name: "request",
|
|
19492
|
+
source: "json",
|
|
19493
|
+
codec: remoteLoginCancelRequestCodec,
|
|
19494
|
+
strictCodec: remoteLoginCancelRequestCodec
|
|
19495
|
+
}],
|
|
19496
|
+
result: remoteOkResultCodec
|
|
19497
|
+
},
|
|
19498
|
+
"agentEnhancer/remoteBindCode": {
|
|
19499
|
+
service: "agentEnhancer",
|
|
19500
|
+
implementation: "remoteBindCode",
|
|
19501
|
+
invocation: { kind: "direct" },
|
|
19502
|
+
parameters: [{
|
|
19503
|
+
name: "request",
|
|
19504
|
+
source: "json",
|
|
19505
|
+
codec: remoteBindCodeRequestCodec,
|
|
19506
|
+
strictCodec: remoteBindCodeRequestCodec
|
|
19507
|
+
}],
|
|
19508
|
+
result: remoteBindCodeResultCodec
|
|
19509
|
+
},
|
|
19510
|
+
"agentEnhancer/remoteRevoke": {
|
|
19511
|
+
service: "agentEnhancer",
|
|
19512
|
+
implementation: "remoteRevoke",
|
|
19513
|
+
invocation: { kind: "direct" },
|
|
19514
|
+
parameters: [{
|
|
19515
|
+
name: "request",
|
|
19516
|
+
source: "json",
|
|
19517
|
+
codec: remoteRevokeRequestCodec,
|
|
19518
|
+
strictCodec: remoteRevokeRequestCodec
|
|
19519
|
+
}],
|
|
19520
|
+
result: remoteRevokeResultCodec
|
|
19521
|
+
},
|
|
19522
|
+
"agentEnhancer/remoteLogout": {
|
|
19523
|
+
service: "agentEnhancer",
|
|
19524
|
+
implementation: "remoteLogout",
|
|
19525
|
+
invocation: { kind: "direct" },
|
|
19526
|
+
parameters: [{
|
|
19527
|
+
name: "request",
|
|
19528
|
+
source: "json",
|
|
19529
|
+
codec: remoteLogoutRequestCodec,
|
|
19530
|
+
strictCodec: remoteLogoutRequestCodec
|
|
19531
|
+
}],
|
|
19532
|
+
result: remoteOkResultCodec
|
|
19533
|
+
},
|
|
19534
|
+
"agentEnhancer/remoteTelegramConnect": {
|
|
19535
|
+
service: "agentEnhancer",
|
|
19536
|
+
implementation: "remoteTelegramConnect",
|
|
19537
|
+
invocation: { kind: "direct" },
|
|
19538
|
+
parameters: [{
|
|
19539
|
+
name: "request",
|
|
19540
|
+
source: "json",
|
|
19541
|
+
codec: remoteTelegramConnectRequestCodec,
|
|
19542
|
+
strictCodec: remoteTelegramConnectRequestCodec
|
|
19543
|
+
}],
|
|
19544
|
+
result: remoteTelegramConnectResultCodec
|
|
19545
|
+
},
|
|
19546
|
+
"agentEnhancer/remoteFeishuConnect": {
|
|
19547
|
+
service: "agentEnhancer",
|
|
19548
|
+
implementation: "remoteFeishuConnect",
|
|
19549
|
+
invocation: { kind: "direct" },
|
|
19550
|
+
parameters: [{
|
|
19551
|
+
name: "request",
|
|
19552
|
+
source: "json",
|
|
19553
|
+
codec: remoteFeishuConnectRequestCodec,
|
|
19554
|
+
strictCodec: remoteFeishuConnectRequestCodec
|
|
19555
|
+
}],
|
|
19556
|
+
result: remoteFeishuConnectResultCodec
|
|
19557
|
+
},
|
|
19277
19558
|
"agentEnhancer/showOsNotification": {
|
|
19278
19559
|
service: "agentEnhancer",
|
|
19279
19560
|
implementation: "showOsNotification",
|
|
@@ -20070,119 +20351,3562 @@ async function showOsNotificationNow(input) {
|
|
|
20070
20351
|
return { shown: false, channel: "none" };
|
|
20071
20352
|
}
|
|
20072
20353
|
|
|
20073
|
-
// src/host/
|
|
20074
|
-
|
|
20075
|
-
|
|
20076
|
-
|
|
20077
|
-
|
|
20078
|
-
|
|
20079
|
-
|
|
20080
|
-
|
|
20081
|
-
|
|
20082
|
-
|
|
20083
|
-
|
|
20084
|
-
|
|
20085
|
-
|
|
20086
|
-
|
|
20087
|
-
|
|
20088
|
-
|
|
20089
|
-
|
|
20090
|
-
|
|
20091
|
-
|
|
20092
|
-
|
|
20093
|
-
|
|
20094
|
-
|
|
20095
|
-
|
|
20096
|
-
|
|
20097
|
-
|
|
20098
|
-
|
|
20099
|
-
|
|
20100
|
-
|
|
20101
|
-
|
|
20102
|
-
|
|
20103
|
-
|
|
20104
|
-
|
|
20105
|
-
|
|
20106
|
-
|
|
20107
|
-
|
|
20108
|
-
|
|
20109
|
-
|
|
20110
|
-
|
|
20111
|
-
|
|
20112
|
-
|
|
20113
|
-
|
|
20114
|
-
|
|
20115
|
-
|
|
20116
|
-
|
|
20117
|
-
|
|
20118
|
-
|
|
20119
|
-
|
|
20120
|
-
|
|
20121
|
-
|
|
20122
|
-
|
|
20123
|
-
|
|
20124
|
-
|
|
20125
|
-
|
|
20126
|
-
|
|
20127
|
-
|
|
20128
|
-
|
|
20129
|
-
|
|
20130
|
-
|
|
20131
|
-
|
|
20132
|
-
|
|
20133
|
-
|
|
20134
|
-
|
|
20135
|
-
|
|
20136
|
-
|
|
20137
|
-
|
|
20138
|
-
|
|
20139
|
-
|
|
20140
|
-
|
|
20141
|
-
|
|
20142
|
-
|
|
20143
|
-
|
|
20144
|
-
|
|
20145
|
-
|
|
20146
|
-
|
|
20147
|
-
|
|
20148
|
-
|
|
20149
|
-
|
|
20150
|
-
|
|
20151
|
-
|
|
20152
|
-
|
|
20153
|
-
|
|
20154
|
-
|
|
20155
|
-
|
|
20156
|
-
|
|
20157
|
-
|
|
20158
|
-
|
|
20159
|
-
|
|
20160
|
-
|
|
20161
|
-
|
|
20162
|
-
|
|
20163
|
-
|
|
20354
|
+
// src/host/remote/hub.ts
|
|
20355
|
+
import { join as join32 } from "node:path";
|
|
20356
|
+
|
|
20357
|
+
// src/host/remote/bindings.ts
|
|
20358
|
+
import { mkdirSync as mkdirSync13, readFileSync as readFileSync11, renameSync as renameSync9, writeFileSync as writeFileSync7 } from "node:fs";
|
|
20359
|
+
import { dirname as dirname13 } from "node:path";
|
|
20360
|
+
var REMOTE_CHANNELS = ["weixin", "telegram", "feishu"];
|
|
20361
|
+
function isRemoteChannel(value) {
|
|
20362
|
+
return typeof value === "string" && REMOTE_CHANNELS.includes(value);
|
|
20363
|
+
}
|
|
20364
|
+
var DEFAULT_CODE_TTL_MS = 10 * 6e4;
|
|
20365
|
+
var FILE_VERSION2 = 1;
|
|
20366
|
+
function numericCode() {
|
|
20367
|
+
return String(1e5 + Math.floor(Math.random() * 9e5));
|
|
20368
|
+
}
|
|
20369
|
+
var BindingStore = class {
|
|
20370
|
+
constructor(options) {
|
|
20371
|
+
this.options = options;
|
|
20372
|
+
this.now = options.now ?? Date.now;
|
|
20373
|
+
this.code = options.code ?? numericCode;
|
|
20374
|
+
this.codeTtlMs = options.codeTtlMs ?? DEFAULT_CODE_TTL_MS;
|
|
20375
|
+
this.load();
|
|
20376
|
+
}
|
|
20377
|
+
options;
|
|
20378
|
+
chats = /* @__PURE__ */ new Map();
|
|
20379
|
+
codes = /* @__PURE__ */ new Map();
|
|
20380
|
+
now;
|
|
20381
|
+
code;
|
|
20382
|
+
codeTtlMs;
|
|
20383
|
+
isBound(chatId) {
|
|
20384
|
+
return this.chats.has(chatId);
|
|
20385
|
+
}
|
|
20386
|
+
binding(chatId) {
|
|
20387
|
+
return this.chats.get(chatId);
|
|
20388
|
+
}
|
|
20389
|
+
list() {
|
|
20390
|
+
return [...this.chats.values()];
|
|
20391
|
+
}
|
|
20392
|
+
bind(chatId, channel, at = this.now()) {
|
|
20393
|
+
const existing = this.chats.get(chatId);
|
|
20394
|
+
if (existing !== void 0) return existing;
|
|
20395
|
+
const binding = { chatId, channel, boundAt: at };
|
|
20396
|
+
this.chats.set(chatId, binding);
|
|
20397
|
+
this.save();
|
|
20398
|
+
return binding;
|
|
20399
|
+
}
|
|
20400
|
+
unbind(chatId) {
|
|
20401
|
+
const removed = this.chats.delete(chatId);
|
|
20402
|
+
if (removed) this.save();
|
|
20403
|
+
return removed;
|
|
20404
|
+
}
|
|
20405
|
+
unbindAll() {
|
|
20406
|
+
if (this.chats.size === 0) return;
|
|
20407
|
+
this.chats.clear();
|
|
20408
|
+
this.save();
|
|
20409
|
+
}
|
|
20410
|
+
/** Remember (or clear) the task this chat is following. */
|
|
20411
|
+
setFocus(chatId, focusSessionId) {
|
|
20412
|
+
const existing = this.chats.get(chatId);
|
|
20413
|
+
if (existing === void 0) return;
|
|
20414
|
+
if (existing.focusSessionId === focusSessionId) return;
|
|
20415
|
+
const { focusSessionId: _previous, ...rest } = existing;
|
|
20416
|
+
const next = focusSessionId === void 0 ? rest : { ...rest, focusSessionId };
|
|
20417
|
+
this.chats.set(chatId, next);
|
|
20418
|
+
this.save();
|
|
20419
|
+
}
|
|
20420
|
+
/** Issue a one-shot pairing code. Codes are unique among live ones. */
|
|
20421
|
+
issueCode(ttlMs = this.codeTtlMs, channel = "weixin") {
|
|
20422
|
+
this.pruneCodes();
|
|
20423
|
+
let code = this.code();
|
|
20424
|
+
for (let attempt = 0; this.codes.has(code) && attempt < 20; attempt += 1) code = this.code();
|
|
20425
|
+
const expiresAt = this.now() + ttlMs;
|
|
20426
|
+
this.codes.set(code, { expiresAt, channel });
|
|
20427
|
+
return { code, expiresAt };
|
|
20428
|
+
}
|
|
20429
|
+
/** One-shot redemption; expired, unknown or foreign-channel codes fail. */
|
|
20430
|
+
redeem(code, chatId, channel, at = this.now()) {
|
|
20431
|
+
this.pruneCodes(at);
|
|
20432
|
+
const entry = this.codes.get(code);
|
|
20433
|
+
if (entry === void 0) return false;
|
|
20434
|
+
if (entry.channel !== channel) return false;
|
|
20435
|
+
this.codes.delete(code);
|
|
20436
|
+
this.bind(chatId, channel, at);
|
|
20437
|
+
return true;
|
|
20438
|
+
}
|
|
20439
|
+
/** Drop expired pairing codes and return how many were removed. */
|
|
20440
|
+
pruneCodes(at = this.now()) {
|
|
20441
|
+
let removed = 0;
|
|
20442
|
+
for (const [code, entry] of this.codes) {
|
|
20443
|
+
if (entry.expiresAt > at) continue;
|
|
20444
|
+
this.codes.delete(code);
|
|
20445
|
+
removed += 1;
|
|
20164
20446
|
}
|
|
20165
|
-
|
|
20166
|
-
|
|
20167
|
-
|
|
20168
|
-
|
|
20169
|
-
|
|
20170
|
-
|
|
20447
|
+
return removed;
|
|
20448
|
+
}
|
|
20449
|
+
load() {
|
|
20450
|
+
const path = this.options.filePath;
|
|
20451
|
+
if (path === null) return;
|
|
20452
|
+
let parsed;
|
|
20453
|
+
try {
|
|
20454
|
+
parsed = JSON.parse(readFileSync11(path, "utf8"));
|
|
20455
|
+
} catch {
|
|
20456
|
+
return;
|
|
20171
20457
|
}
|
|
20172
|
-
|
|
20173
|
-
|
|
20174
|
-
|
|
20175
|
-
|
|
20176
|
-
|
|
20177
|
-
|
|
20178
|
-
|
|
20179
|
-
|
|
20180
|
-
|
|
20181
|
-
|
|
20182
|
-
|
|
20183
|
-
|
|
20184
|
-
|
|
20185
|
-
|
|
20458
|
+
if (parsed === null || typeof parsed !== "object") return;
|
|
20459
|
+
const shape = parsed;
|
|
20460
|
+
if (shape.version !== FILE_VERSION2 || shape.chats === null || typeof shape.chats !== "object") return;
|
|
20461
|
+
for (const [chatId, value] of Object.entries(shape.chats)) {
|
|
20462
|
+
if (value === null || typeof value !== "object") continue;
|
|
20463
|
+
const channel = value.channel;
|
|
20464
|
+
const boundAt = value.boundAt;
|
|
20465
|
+
const focus = value.focusSessionId;
|
|
20466
|
+
if (!isRemoteChannel(channel)) continue;
|
|
20467
|
+
this.chats.set(chatId, {
|
|
20468
|
+
chatId,
|
|
20469
|
+
channel,
|
|
20470
|
+
boundAt: typeof boundAt === "number" ? boundAt : 0,
|
|
20471
|
+
...typeof focus === "string" && focus !== "" ? { focusSessionId: focus } : {}
|
|
20472
|
+
});
|
|
20473
|
+
}
|
|
20474
|
+
}
|
|
20475
|
+
save() {
|
|
20476
|
+
const path = this.options.filePath;
|
|
20477
|
+
if (path === null) return;
|
|
20478
|
+
const shape = {
|
|
20479
|
+
version: FILE_VERSION2,
|
|
20480
|
+
chats: Object.fromEntries([...this.chats].map(([chatId, binding]) => [
|
|
20481
|
+
chatId,
|
|
20482
|
+
{
|
|
20483
|
+
channel: binding.channel,
|
|
20484
|
+
boundAt: binding.boundAt,
|
|
20485
|
+
...binding.focusSessionId === void 0 ? {} : { focusSessionId: binding.focusSessionId }
|
|
20486
|
+
}
|
|
20487
|
+
]))
|
|
20488
|
+
};
|
|
20489
|
+
try {
|
|
20490
|
+
mkdirSync13(dirname13(path), { recursive: true });
|
|
20491
|
+
const tmp = `${path}.tmp`;
|
|
20492
|
+
writeFileSync7(tmp, JSON.stringify(shape, null, 2));
|
|
20493
|
+
renameSync9(tmp, path);
|
|
20494
|
+
} catch {
|
|
20495
|
+
}
|
|
20496
|
+
}
|
|
20497
|
+
};
|
|
20498
|
+
|
|
20499
|
+
// src/host/remote/types.ts
|
|
20500
|
+
var CODE_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
|
|
20501
|
+
var CODE_LENGTH = 4;
|
|
20502
|
+
var DEFAULT_PENDING_TTL_MS = 24e4;
|
|
20503
|
+
function isCode(value) {
|
|
20504
|
+
if (value.length !== CODE_LENGTH) return false;
|
|
20505
|
+
for (const char of value) {
|
|
20506
|
+
if (!CODE_ALPHABET.includes(char)) return false;
|
|
20507
|
+
}
|
|
20508
|
+
return true;
|
|
20509
|
+
}
|
|
20510
|
+
function createCode(random = (max) => Math.floor(Math.random() * max)) {
|
|
20511
|
+
let code = "";
|
|
20512
|
+
for (let index = 0; index < CODE_LENGTH; index += 1) {
|
|
20513
|
+
code += CODE_ALPHABET.charAt(random(CODE_ALPHABET.length));
|
|
20514
|
+
}
|
|
20515
|
+
return code;
|
|
20516
|
+
}
|
|
20517
|
+
function createPending(input, now) {
|
|
20518
|
+
return {
|
|
20519
|
+
kind: input.kind,
|
|
20520
|
+
code: input.code ?? createCode(),
|
|
20521
|
+
prompt: input.prompt,
|
|
20522
|
+
...input.options === void 0 ? {} : { options: input.options },
|
|
20523
|
+
...input.risk === void 0 ? {} : { risk: input.risk },
|
|
20524
|
+
sessionId: input.sessionId,
|
|
20525
|
+
createdAt: now,
|
|
20526
|
+
expiresAt: now + (input.ttlMs ?? DEFAULT_PENDING_TTL_MS)
|
|
20527
|
+
};
|
|
20528
|
+
}
|
|
20529
|
+
function isExpired(pending, now) {
|
|
20530
|
+
return now >= pending.expiresAt;
|
|
20531
|
+
}
|
|
20532
|
+
|
|
20533
|
+
// src/host/remote/approval-router.ts
|
|
20534
|
+
function withKind(task, kind) {
|
|
20535
|
+
return task.pending !== void 0 && task.pending.kind === kind;
|
|
20536
|
+
}
|
|
20537
|
+
function activeCodes(tasks, now) {
|
|
20538
|
+
return tasks.filter((task) => !isExpired(task.pending, now)).map((task) => task.pending.code);
|
|
20539
|
+
}
|
|
20540
|
+
function routeDecision(tasks, command, now) {
|
|
20541
|
+
if (command.kind !== "approve" && command.kind !== "reject") {
|
|
20542
|
+
return { ok: false, reason: "not-a-decision" };
|
|
20543
|
+
}
|
|
20544
|
+
const decision = command.kind === "approve" ? "approve" : "reject";
|
|
20545
|
+
const approvals = tasks.filter((task) => withKind(task, "approval"));
|
|
20546
|
+
const codes = activeCodes(approvals, now);
|
|
20547
|
+
if (command.code !== void 0) {
|
|
20548
|
+
const hit = approvals.find((task) => task.pending.code === command.code);
|
|
20549
|
+
if (hit === void 0) return { ok: false, reason: "unknown-code", codes };
|
|
20550
|
+
if (isExpired(hit.pending, now)) return { ok: false, reason: "expired", codes };
|
|
20551
|
+
return { ok: true, taskId: hit.id, pending: hit.pending, decision };
|
|
20552
|
+
}
|
|
20553
|
+
const live = approvals.filter((task) => !isExpired(task.pending, now));
|
|
20554
|
+
if (live.length === 0) {
|
|
20555
|
+
return { ok: false, reason: approvals.length > 0 ? "expired" : "no-pending" };
|
|
20556
|
+
}
|
|
20557
|
+
const only = live[0];
|
|
20558
|
+
if (only === void 0) return { ok: false, reason: "no-pending" };
|
|
20559
|
+
if (live.length > 1) return { ok: false, reason: "ambiguous", codes: live.map((task) => task.pending.code) };
|
|
20560
|
+
return { ok: true, taskId: only.id, pending: only.pending, decision };
|
|
20561
|
+
}
|
|
20562
|
+
function routeAnswer(tasks, command, now) {
|
|
20563
|
+
if (command.kind !== "answer") return { ok: false, reason: "not-an-answer" };
|
|
20564
|
+
const questions = tasks.filter((task) => withKind(task, "question"));
|
|
20565
|
+
const codes = activeCodes(questions, now);
|
|
20566
|
+
if (command.code !== void 0) {
|
|
20567
|
+
const hit = questions.find((task) => task.pending.code === command.code);
|
|
20568
|
+
if (hit === void 0) return { ok: false, reason: "unknown-code", codes };
|
|
20569
|
+
if (isExpired(hit.pending, now)) return { ok: false, reason: "expired", codes };
|
|
20570
|
+
return { ok: true, taskId: hit.id, pending: hit.pending, text: command.text };
|
|
20571
|
+
}
|
|
20572
|
+
const live = questions.filter((task) => !isExpired(task.pending, now));
|
|
20573
|
+
if (live.length === 0) {
|
|
20574
|
+
return { ok: false, reason: questions.length > 0 ? "expired" : "no-pending" };
|
|
20575
|
+
}
|
|
20576
|
+
const only = live[0];
|
|
20577
|
+
if (only === void 0) return { ok: false, reason: "no-pending" };
|
|
20578
|
+
if (live.length > 1) return { ok: false, reason: "ambiguous", codes: live.map((task) => task.pending.code) };
|
|
20579
|
+
return { ok: true, taskId: only.id, pending: only.pending, text: command.text };
|
|
20580
|
+
}
|
|
20581
|
+
|
|
20582
|
+
// src/host/remote/commands.ts
|
|
20583
|
+
var WORDS = [
|
|
20584
|
+
{ kind: "tasks", aliases: ["\u4EFB\u52A1", "\u4EFB\u52A1\u5217\u8868", "\u5217\u8868", "tasks", "task", "list"] },
|
|
20585
|
+
{ kind: "switch", aliases: ["\u5207", "\u5207\u6362", "\u9009", "switch", "sw"] },
|
|
20586
|
+
{ kind: "approve", aliases: ["\u6279\u51C6", "\u540C\u610F", "approve", "ok"] },
|
|
20587
|
+
{ kind: "reject", aliases: ["\u62D2\u7EDD", "\u5426\u51B3", "reject", "deny", "no"] },
|
|
20588
|
+
{ kind: "answer", aliases: ["\u56DE\u7B54", "answer"] },
|
|
20589
|
+
{ kind: "detail", aliases: ["\u8BE6\u60C5", "\u67E5\u770B", "detail", "details"] },
|
|
20590
|
+
{ kind: "pause", aliases: ["\u6682\u505C", "pause"] },
|
|
20591
|
+
{ kind: "resume", aliases: ["\u7EE7\u7EED", "\u6062\u590D", "resume", "continue"] }
|
|
20592
|
+
];
|
|
20593
|
+
var BY_ALIAS = /* @__PURE__ */ new Map();
|
|
20594
|
+
for (const entry of WORDS) {
|
|
20595
|
+
for (const alias of entry.aliases) BY_ALIAS.set(alias, entry.kind);
|
|
20596
|
+
}
|
|
20597
|
+
var ESCAPES = ["\u6D88\u606F", "message"];
|
|
20598
|
+
function positiveInt(value) {
|
|
20599
|
+
if (!/^[1-9][0-9]{0,3}$/.test(value)) return void 0;
|
|
20600
|
+
return Number(value);
|
|
20601
|
+
}
|
|
20602
|
+
var NUMBER_WORDS = /* @__PURE__ */ new Set(["switch", "detail"]);
|
|
20603
|
+
var CODE_WORDS = /* @__PURE__ */ new Set(["approve", "reject"]);
|
|
20604
|
+
function gluedWord(lower, text3) {
|
|
20605
|
+
const aliases = [...BY_ALIAS.entries()].sort((left, right) => right[0].length - left[0].length);
|
|
20606
|
+
for (const [alias, kind] of aliases) {
|
|
20607
|
+
if (!lower.startsWith(alias) || lower.length === alias.length) continue;
|
|
20608
|
+
const rest = text3.slice(alias.length).trim();
|
|
20609
|
+
if (rest === "") continue;
|
|
20610
|
+
if (NUMBER_WORDS.has(kind) && positiveInt(rest) !== void 0) return { kind, rest };
|
|
20611
|
+
if (CODE_WORDS.has(kind) && isCode(rest.toLowerCase())) return { kind, rest };
|
|
20612
|
+
}
|
|
20613
|
+
return void 0;
|
|
20614
|
+
}
|
|
20615
|
+
function parseCommand(input) {
|
|
20616
|
+
const text3 = input.trim();
|
|
20617
|
+
if (text3 === "") return { kind: "invalid", reason: "empty" };
|
|
20618
|
+
const lower = text3.toLowerCase();
|
|
20619
|
+
for (const escape of ESCAPES) {
|
|
20620
|
+
if (!lower.startsWith(`${escape} `)) continue;
|
|
20621
|
+
const payload = text3.slice(escape.length).trim();
|
|
20622
|
+
if (payload === "") return { kind: "invalid", reason: "empty-message" };
|
|
20623
|
+
return { kind: "message", text: payload };
|
|
20624
|
+
}
|
|
20625
|
+
if (positiveInt(text3) !== void 0) return { kind: "switch", number: Number(text3) };
|
|
20626
|
+
const space = text3.search(/\s/);
|
|
20627
|
+
const head = (space === -1 ? text3 : text3.slice(0, space)).toLowerCase();
|
|
20628
|
+
let rest = space === -1 ? "" : text3.slice(space).trim();
|
|
20629
|
+
let kind = BY_ALIAS.get(head);
|
|
20630
|
+
if (kind === void 0) {
|
|
20631
|
+
const glued = gluedWord(lower, text3);
|
|
20632
|
+
if (glued === void 0) return { kind: "message", text: text3 };
|
|
20633
|
+
kind = glued.kind;
|
|
20634
|
+
rest = glued.rest;
|
|
20635
|
+
}
|
|
20636
|
+
switch (kind) {
|
|
20637
|
+
case "tasks":
|
|
20638
|
+
return rest === "" ? { kind } : { kind: "invalid", reason: "unexpected-argument" };
|
|
20639
|
+
case "pause":
|
|
20640
|
+
return rest === "" ? { kind } : { kind: "invalid", reason: "unexpected-argument" };
|
|
20641
|
+
case "resume":
|
|
20642
|
+
return rest === "" ? { kind } : { kind: "invalid", reason: "unexpected-argument" };
|
|
20643
|
+
case "switch": {
|
|
20644
|
+
const number = positiveInt(rest);
|
|
20645
|
+
return number === void 0 ? { kind: "invalid", reason: "bad-task-number" } : { kind: "switch", number };
|
|
20646
|
+
}
|
|
20647
|
+
case "detail": {
|
|
20648
|
+
if (rest === "") return { kind: "detail" };
|
|
20649
|
+
const number = positiveInt(rest);
|
|
20650
|
+
return number === void 0 ? { kind: "invalid", reason: "bad-task-number" } : { kind: "detail", number };
|
|
20651
|
+
}
|
|
20652
|
+
case "approve":
|
|
20653
|
+
case "reject": {
|
|
20654
|
+
if (rest === "") return { kind };
|
|
20655
|
+
const code = rest.toLowerCase();
|
|
20656
|
+
if (!isCode(code)) return { kind: "invalid", reason: "bad-code" };
|
|
20657
|
+
return { kind, code };
|
|
20658
|
+
}
|
|
20659
|
+
case "answer": {
|
|
20660
|
+
if (rest === "") return { kind: "invalid", reason: "answer-empty" };
|
|
20661
|
+
const withCode = new RegExp(`^([a-z0-9]{${CODE_LENGTH}})\\s+(.+)$`, "is").exec(rest);
|
|
20662
|
+
const code = withCode?.[1]?.toLowerCase();
|
|
20663
|
+
if (code !== void 0 && isCode(code)) {
|
|
20664
|
+
const body = (withCode?.[2] ?? "").trim();
|
|
20665
|
+
if (body === "") return { kind: "invalid", reason: "answer-empty" };
|
|
20666
|
+
return { kind: "answer", code, text: body };
|
|
20667
|
+
}
|
|
20668
|
+
return { kind: "answer", text: rest };
|
|
20669
|
+
}
|
|
20670
|
+
}
|
|
20671
|
+
}
|
|
20672
|
+
|
|
20673
|
+
// src/host/remote/render.ts
|
|
20674
|
+
var STATE_LABEL = {
|
|
20675
|
+
running: "\u8FD0\u884C\u4E2D",
|
|
20676
|
+
waiting: "\u5F85\u51B3\u5B9A",
|
|
20677
|
+
paused: "\u5DF2\u6682\u505C",
|
|
20678
|
+
done: "\u5DF2\u5B8C\u6210",
|
|
20679
|
+
failed: "\u5931\u8D25",
|
|
20680
|
+
stopped: "\u5DF2\u505C\u6B62",
|
|
20681
|
+
offline: "\u79BB\u7EBF"
|
|
20682
|
+
};
|
|
20683
|
+
function clipLabel(value, max = 22) {
|
|
20684
|
+
const text3 = value.trim();
|
|
20685
|
+
return text3.length <= max ? text3 : `${text3.slice(0, max - 1)}\u2026`;
|
|
20686
|
+
}
|
|
20687
|
+
function taskActionButtons(task) {
|
|
20688
|
+
if (task.pending !== void 0) {
|
|
20689
|
+
const code = task.pending.code;
|
|
20690
|
+
if (task.pending.kind === "approval") {
|
|
20691
|
+
return [
|
|
20692
|
+
{ label: "\u6279\u51C6", command: `\u6279\u51C6 ${code}` },
|
|
20693
|
+
{ label: "\u62D2\u7EDD", command: `\u62D2\u7EDD ${code}` },
|
|
20694
|
+
{ label: "\u8BE6\u60C5", command: "\u8BE6\u60C5" }
|
|
20695
|
+
];
|
|
20696
|
+
}
|
|
20697
|
+
const options = (task.pending.options ?? []).slice(0, 6).map((option) => ({
|
|
20698
|
+
label: clipLabel(option),
|
|
20699
|
+
command: `\u56DE\u7B54 ${code} ${option}`
|
|
20700
|
+
}));
|
|
20701
|
+
return [...options, { label: "\u8BE6\u60C5", command: "\u8BE6\u60C5" }];
|
|
20702
|
+
}
|
|
20703
|
+
const actions = [];
|
|
20704
|
+
if (task.state === "running" || task.state === "waiting") {
|
|
20705
|
+
actions.push({ label: "\u6682\u505C", command: "\u6682\u505C" });
|
|
20706
|
+
} else if (task.state === "paused") {
|
|
20707
|
+
actions.push({ label: "\u7EE7\u7EED", command: "\u7EE7\u7EED" });
|
|
20708
|
+
}
|
|
20709
|
+
actions.push({ label: "\u8BE6\u60C5", command: "\u8BE6\u60C5" });
|
|
20710
|
+
return actions;
|
|
20711
|
+
}
|
|
20712
|
+
function listActionButtons(tasks, numbers) {
|
|
20713
|
+
const active = tasks.filter((task) => task.state === "running" || task.state === "waiting" || task.state === "paused");
|
|
20714
|
+
const rest = tasks.filter((task) => !active.includes(task)).sort((left, right) => right.lastActivityAt - left.lastActivityAt);
|
|
20715
|
+
const chosen = [...active, ...rest].slice(0, 8);
|
|
20716
|
+
return chosen.map((task) => {
|
|
20717
|
+
const number = numbers.get(task.id) ?? 0;
|
|
20718
|
+
return {
|
|
20719
|
+
label: clipLabel(`${number} ${task.title}`),
|
|
20720
|
+
command: `\u5207 ${number}`
|
|
20721
|
+
};
|
|
20722
|
+
});
|
|
20723
|
+
}
|
|
20724
|
+
function decisionHint(pending, capabilities) {
|
|
20725
|
+
if (pending.kind === "question") {
|
|
20726
|
+
return `\u56DE\u590D\u300C\u56DE\u7B54 ${pending.code} \u4F60\u7684\u7B54\u6848\u300D`;
|
|
20727
|
+
}
|
|
20728
|
+
if (capabilities.buttons) {
|
|
20729
|
+
return `\u70B9\u4E0B\u65B9\u6309\u94AE\uFF0C\u6216\u56DE\u590D\u300C\u6279\u51C6 ${pending.code}\u300D/\u300C\u62D2\u7EDD ${pending.code}\u300D`;
|
|
20730
|
+
}
|
|
20731
|
+
return `\u56DE\u590D\u300C\u6279\u51C6 ${pending.code}\u300D\u6216\u300C\u62D2\u7EDD ${pending.code}\u300D`;
|
|
20732
|
+
}
|
|
20733
|
+
function pendingBody(pending) {
|
|
20734
|
+
const lines = [pending.prompt];
|
|
20735
|
+
if (pending.options !== void 0 && pending.options.length > 0) {
|
|
20736
|
+
const options = pending.options.map((option, index) => `${index + 1}) ${option}`).join(" ");
|
|
20737
|
+
lines.push(`\u9009\u9879\uFF1A${options}`);
|
|
20738
|
+
}
|
|
20739
|
+
return lines;
|
|
20740
|
+
}
|
|
20741
|
+
function renderTaskCard(task, number, capabilities, presented = task.state) {
|
|
20742
|
+
const head = `\u3010${number}\u3011${task.title} \xB7 ${STATE_LABEL[presented]}`;
|
|
20743
|
+
if (task.pending !== void 0 && presented !== "offline") {
|
|
20744
|
+
return [head, ...pendingBody(task.pending), decisionHint(task.pending, capabilities)].join("\n");
|
|
20745
|
+
}
|
|
20746
|
+
if (presented === "running" && task.lastLine !== void 0) {
|
|
20747
|
+
return [head, `\u6700\u8FD1\uFF1A${task.lastLine}`].join("\n");
|
|
20748
|
+
}
|
|
20749
|
+
return head;
|
|
20750
|
+
}
|
|
20751
|
+
function renderTaskList(tasks, numbers, capabilities) {
|
|
20752
|
+
if (tasks.length === 0) return "\u5F53\u524D\u6CA1\u6709\u4EFB\u52A1\u3002\u5728\u7535\u8111\u4E0A\u5F00\u59CB\u4E00\u4E2A\u4EFB\u52A1\u540E\uFF0C\u8FD9\u91CC\u4F1A\u51FA\u73B0\u3002";
|
|
20753
|
+
const lines = tasks.map((task) => {
|
|
20754
|
+
const number = numbers.get(task.id) ?? 0;
|
|
20755
|
+
const marker = task.pending !== void 0 ? " \u2190 \u9700\u8981\u4F60" : "";
|
|
20756
|
+
return `${number} ${task.title} ${STATE_LABEL[task.state]}${marker}`;
|
|
20757
|
+
});
|
|
20758
|
+
const pending = tasks.find((task) => task.pending !== void 0);
|
|
20759
|
+
const hint = capabilities.buttons ? pending === void 0 ? "\u70B9\u4E0B\u65B9\u4EFB\u52A1\u6309\u94AE\u5207\u6362\uFF0C\u6216\u56DE\u590D\u300C\u5207 2\u300D" : "\u70B9\u6D88\u606F\u91CC\u7684\u6309\u94AE\u5904\u7406\u5F85\u529E\uFF0C\u6216\u70B9\u4EFB\u52A1\u6309\u94AE\u5207\u6362" : pending === void 0 ? "\u56DE\u590D\u300C\u5207 2\u300D\u5207\u6362\u4EFB\u52A1" : "\u56DE\u590D\u300C\u6279\u51C6 <\u7F16\u53F7>\u300D\u5904\u7406\u5F85\u529E\uFF0C\u6216\u56DE\u590D\u300C\u5207 2\u300D\u5207\u6362\u4EFB\u52A1";
|
|
20760
|
+
return [...lines, "", hint].join("\n");
|
|
20761
|
+
}
|
|
20762
|
+
function splitForChannel(text3, maxChars) {
|
|
20763
|
+
const limit = Math.max(1, Math.floor(maxChars));
|
|
20764
|
+
if (text3.length <= limit) return [text3];
|
|
20765
|
+
const bodyLimit = Math.max(1, limit - 12);
|
|
20766
|
+
const chunks = [];
|
|
20767
|
+
let rest = text3;
|
|
20768
|
+
while (rest.length > bodyLimit) {
|
|
20769
|
+
let cut = rest.lastIndexOf("\n", bodyLimit);
|
|
20770
|
+
if (cut < Math.floor(bodyLimit / 2)) cut = bodyLimit;
|
|
20771
|
+
chunks.push(rest.slice(0, cut));
|
|
20772
|
+
rest = rest.slice(cut).replace(/^\n+/, "");
|
|
20773
|
+
}
|
|
20774
|
+
if (rest !== "") chunks.push(rest);
|
|
20775
|
+
return chunks.map((chunk, index) => `${chunk}
|
|
20776
|
+
(${index + 1}/${chunks.length})`);
|
|
20777
|
+
}
|
|
20778
|
+
|
|
20779
|
+
// src/host/remote/task-board.ts
|
|
20780
|
+
var TERMINAL = {
|
|
20781
|
+
ok: "done",
|
|
20782
|
+
error: "failed",
|
|
20783
|
+
aborted: "stopped",
|
|
20784
|
+
stopped: "stopped"
|
|
20785
|
+
};
|
|
20786
|
+
var TaskBoard = class {
|
|
20787
|
+
tasks = /* @__PURE__ */ new Map();
|
|
20788
|
+
get(id) {
|
|
20789
|
+
return this.tasks.get(id);
|
|
20790
|
+
}
|
|
20791
|
+
list() {
|
|
20792
|
+
return [...this.tasks.values()];
|
|
20793
|
+
}
|
|
20794
|
+
size() {
|
|
20795
|
+
return this.tasks.size;
|
|
20796
|
+
}
|
|
20797
|
+
/** Create or refresh a task from a session row. */
|
|
20798
|
+
register(id, title, state, at) {
|
|
20799
|
+
const existing = this.tasks.get(id);
|
|
20800
|
+
if (existing !== void 0) {
|
|
20801
|
+
const next = {
|
|
20802
|
+
...existing,
|
|
20803
|
+
title,
|
|
20804
|
+
// Do not overwrite a live state (waiting/paused) from a passive list read.
|
|
20805
|
+
state: existing.state === "waiting" || existing.state === "paused" ? existing.state : state,
|
|
20806
|
+
lastActivityAt: Math.max(existing.lastActivityAt, at)
|
|
20807
|
+
};
|
|
20808
|
+
this.tasks.set(id, next);
|
|
20809
|
+
return next;
|
|
20810
|
+
}
|
|
20811
|
+
const created = { id, title, state, lastActivityAt: at };
|
|
20812
|
+
this.tasks.set(id, created);
|
|
20813
|
+
return created;
|
|
20814
|
+
}
|
|
20815
|
+
rename(id, title) {
|
|
20816
|
+
return this.replace(id, (task) => ({ ...task, title }));
|
|
20817
|
+
}
|
|
20818
|
+
/** Newest step summary, used by the card body. */
|
|
20819
|
+
note(id, line, at) {
|
|
20820
|
+
return this.replace(id, (task) => ({
|
|
20821
|
+
...task,
|
|
20822
|
+
lastLine: line,
|
|
20823
|
+
lastActivityAt: Math.max(task.lastActivityAt, at)
|
|
20824
|
+
}));
|
|
20825
|
+
}
|
|
20826
|
+
turnStart(id, at) {
|
|
20827
|
+
return this.replace(id, (task) => ({
|
|
20828
|
+
...task,
|
|
20829
|
+
state: "running",
|
|
20830
|
+
pending: void 0,
|
|
20831
|
+
resumeTo: void 0,
|
|
20832
|
+
lastAnswer: void 0,
|
|
20833
|
+
lastActivityAt: Math.max(task.lastActivityAt, at)
|
|
20834
|
+
}));
|
|
20835
|
+
}
|
|
20836
|
+
/** Store the model's final text for this turn (the remote answer). */
|
|
20837
|
+
answer(id, text3, at) {
|
|
20838
|
+
return this.replace(id, (task) => ({
|
|
20839
|
+
...task,
|
|
20840
|
+
lastAnswer: text3,
|
|
20841
|
+
lastActivityAt: Math.max(task.lastActivityAt, at)
|
|
20842
|
+
}));
|
|
20843
|
+
}
|
|
20844
|
+
turnEnd(id, reason, at, error) {
|
|
20845
|
+
return this.replace(id, (task) => ({
|
|
20846
|
+
...task,
|
|
20847
|
+
state: TERMINAL[reason],
|
|
20848
|
+
pending: void 0,
|
|
20849
|
+
resumeTo: void 0,
|
|
20850
|
+
lastActivityAt: Math.max(task.lastActivityAt, at),
|
|
20851
|
+
...reason === "error" && error !== void 0 ? { lastLine: error } : {}
|
|
20852
|
+
}));
|
|
20853
|
+
}
|
|
20854
|
+
/**
|
|
20855
|
+
* Record a pending approval/question. Waits are created while the turn runs;
|
|
20856
|
+
* an existing pending is a bug (the host would have had to resolve it first).
|
|
20857
|
+
*/
|
|
20858
|
+
ask(id, pending, at) {
|
|
20859
|
+
const task = this.tasks.get(id);
|
|
20860
|
+
if (task === void 0) return void 0;
|
|
20861
|
+
if (task.pending !== void 0) throw new Error(`task ${id} already has a pending decision`);
|
|
20862
|
+
if (task.state === "paused") throw new Error(`task ${id} is paused; a decision cannot arrive now`);
|
|
20863
|
+
return this.replace(id, (current) => ({
|
|
20864
|
+
...current,
|
|
20865
|
+
state: "waiting",
|
|
20866
|
+
pending,
|
|
20867
|
+
lastActivityAt: Math.max(current.lastActivityAt, at)
|
|
20868
|
+
}));
|
|
20869
|
+
}
|
|
20870
|
+
/** Resolve the pending decision with a matching one-shot code. */
|
|
20871
|
+
decide(id, code, now) {
|
|
20872
|
+
const task = this.tasks.get(id);
|
|
20873
|
+
if (task?.pending === void 0) return "no-pending";
|
|
20874
|
+
if (task.pending.code !== code) return "code-mismatch";
|
|
20875
|
+
if (isExpired(task.pending, now)) {
|
|
20876
|
+
this.replace(id, (current) => ({ ...current, pending: void 0, state: "running" }));
|
|
20877
|
+
return "expired";
|
|
20878
|
+
}
|
|
20879
|
+
this.replace(id, (current) => ({
|
|
20880
|
+
...current,
|
|
20881
|
+
pending: void 0,
|
|
20882
|
+
state: "running",
|
|
20883
|
+
lastActivityAt: Math.max(current.lastActivityAt, now)
|
|
20884
|
+
}));
|
|
20885
|
+
return "ok";
|
|
20886
|
+
}
|
|
20887
|
+
/** Drop expired pendings and let their tasks resume running. Returns the dropped codes. */
|
|
20888
|
+
expire(now) {
|
|
20889
|
+
const dropped = [];
|
|
20890
|
+
for (const [id, task] of this.tasks) {
|
|
20891
|
+
if (task.pending === void 0) continue;
|
|
20892
|
+
if (!isExpired(task.pending, now)) continue;
|
|
20893
|
+
dropped.push(task.pending.code);
|
|
20894
|
+
this.tasks.set(id, { ...task, pending: void 0, state: "running" });
|
|
20895
|
+
}
|
|
20896
|
+
return dropped;
|
|
20897
|
+
}
|
|
20898
|
+
/** Drop a pending without deciding it (another client already handled the request). */
|
|
20899
|
+
clearPending(id) {
|
|
20900
|
+
const task = this.tasks.get(id);
|
|
20901
|
+
if (task?.pending === void 0) return void 0;
|
|
20902
|
+
const pending = task.pending;
|
|
20903
|
+
const paused = task.state === "paused";
|
|
20904
|
+
this.tasks.set(id, {
|
|
20905
|
+
...task,
|
|
20906
|
+
pending: void 0,
|
|
20907
|
+
state: paused ? "paused" : "running",
|
|
20908
|
+
resumeTo: paused && task.resumeTo === "waiting" ? "running" : task.resumeTo
|
|
20909
|
+
});
|
|
20910
|
+
return pending;
|
|
20911
|
+
}
|
|
20912
|
+
/** Soft pause: remember what to return to. No-op when already paused. */
|
|
20913
|
+
pause(id) {
|
|
20914
|
+
const task = this.tasks.get(id);
|
|
20915
|
+
if (task === void 0 || task.state === "paused") return task;
|
|
20916
|
+
if (task.state !== "running" && task.state !== "waiting") return task;
|
|
20917
|
+
return this.replace(id, (current) => ({
|
|
20918
|
+
...current,
|
|
20919
|
+
state: "paused",
|
|
20920
|
+
resumeTo: current.state === "waiting" ? "waiting" : "running"
|
|
20921
|
+
}));
|
|
20922
|
+
}
|
|
20923
|
+
resume(id, now) {
|
|
20924
|
+
const task = this.tasks.get(id);
|
|
20925
|
+
if (task === void 0 || task.state !== "paused") return task;
|
|
20926
|
+
const resumeTo = task.resumeTo ?? "running";
|
|
20927
|
+
const pending = task.pending !== void 0 && isExpired(task.pending, now) ? void 0 : task.pending;
|
|
20928
|
+
const state = pending === void 0 ? "running" : resumeTo;
|
|
20929
|
+
return this.replace(id, (current) => ({
|
|
20930
|
+
...current,
|
|
20931
|
+
state,
|
|
20932
|
+
pending,
|
|
20933
|
+
resumeTo: void 0,
|
|
20934
|
+
lastActivityAt: Math.max(current.lastActivityAt, now)
|
|
20935
|
+
}));
|
|
20936
|
+
}
|
|
20937
|
+
remove(id) {
|
|
20938
|
+
return this.tasks.delete(id);
|
|
20939
|
+
}
|
|
20940
|
+
/** Offline is a presentation fact, not a stored state. */
|
|
20941
|
+
presented(id, hostOnline) {
|
|
20942
|
+
const task = this.tasks.get(id);
|
|
20943
|
+
if (task === void 0) return void 0;
|
|
20944
|
+
return hostOnline ? task.state : "offline";
|
|
20945
|
+
}
|
|
20946
|
+
replace(id, update) {
|
|
20947
|
+
const task = this.tasks.get(id);
|
|
20948
|
+
if (task === void 0) return void 0;
|
|
20949
|
+
const next = update(task);
|
|
20950
|
+
this.tasks.set(id, next);
|
|
20951
|
+
return next;
|
|
20952
|
+
}
|
|
20953
|
+
};
|
|
20954
|
+
|
|
20955
|
+
// src/host/remote/controller.ts
|
|
20956
|
+
var RemoteController = class {
|
|
20957
|
+
constructor(options) {
|
|
20958
|
+
this.options = options;
|
|
20959
|
+
}
|
|
20960
|
+
options;
|
|
20961
|
+
board = new TaskBoard();
|
|
20962
|
+
numbers = /* @__PURE__ */ new Map();
|
|
20963
|
+
focusByChat = /* @__PURE__ */ new Map();
|
|
20964
|
+
approvalWaiters = /* @__PURE__ */ new Map();
|
|
20965
|
+
questionWaiters = /* @__PURE__ */ new Map();
|
|
20966
|
+
codeByApprovalId = /* @__PURE__ */ new Map();
|
|
20967
|
+
counter = 0;
|
|
20968
|
+
now() {
|
|
20969
|
+
return this.options.now?.() ?? Date.now();
|
|
20970
|
+
}
|
|
20971
|
+
nextCode() {
|
|
20972
|
+
return this.options.code?.() ?? createCode();
|
|
20973
|
+
}
|
|
20974
|
+
track(row, at = this.now()) {
|
|
20975
|
+
const existing = this.numbers.get(row.id);
|
|
20976
|
+
if (existing === void 0) {
|
|
20977
|
+
this.counter += 1;
|
|
20978
|
+
this.numbers.set(row.id, this.counter);
|
|
20979
|
+
}
|
|
20980
|
+
this.board.register(row.id, row.title, row.running ? "running" : "done", at);
|
|
20981
|
+
}
|
|
20982
|
+
untrack(id) {
|
|
20983
|
+
this.board.remove(id);
|
|
20984
|
+
this.numbers.delete(id);
|
|
20985
|
+
for (const [chat, focused] of this.focusByChat) {
|
|
20986
|
+
if (focused === id) this.focusByChat.delete(chat);
|
|
20987
|
+
}
|
|
20988
|
+
}
|
|
20989
|
+
numberOf(id) {
|
|
20990
|
+
return this.numbers.get(id);
|
|
20991
|
+
}
|
|
20992
|
+
tasks() {
|
|
20993
|
+
const list = this.board.list();
|
|
20994
|
+
return [...list].sort((left, right) => (this.numbers.get(left.id) ?? 0) - (this.numbers.get(right.id) ?? 0));
|
|
20995
|
+
}
|
|
20996
|
+
onTurnStart(id, at = this.now()) {
|
|
20997
|
+
this.board.turnStart(id, at);
|
|
20998
|
+
}
|
|
20999
|
+
onTurnEnd(id, reason, error, at = this.now()) {
|
|
21000
|
+
this.board.turnEnd(id, reason, at, error);
|
|
21001
|
+
}
|
|
21002
|
+
onTitle(id, title) {
|
|
21003
|
+
this.board.rename(id, title);
|
|
21004
|
+
}
|
|
21005
|
+
/** Record the model's final text so `详情` can show the actual answer. */
|
|
21006
|
+
onAnswer(id, text3, at = this.now()) {
|
|
21007
|
+
const trimmed = text3.trim();
|
|
21008
|
+
if (trimmed === "") return;
|
|
21009
|
+
this.board.answer(id, trimmed.length > 8e3 ? `${trimmed.slice(0, 7999)}\u2026` : trimmed, at);
|
|
21010
|
+
}
|
|
21011
|
+
onNote(id, line, at = this.now()) {
|
|
21012
|
+
this.board.note(id, line, at);
|
|
21013
|
+
}
|
|
21014
|
+
/** Hold an approval request; resolves with the remote decision, or never if dismissed. */
|
|
21015
|
+
askApproval(id, ask, at = this.now()) {
|
|
21016
|
+
const pending = createPending({
|
|
21017
|
+
kind: "approval",
|
|
21018
|
+
sessionId: id,
|
|
21019
|
+
prompt: ask.prompt,
|
|
21020
|
+
...ask.risk === void 0 ? {} : { risk: ask.risk },
|
|
21021
|
+
code: this.nextCode(),
|
|
21022
|
+
...this.options.ttlMs === void 0 ? {} : { ttlMs: this.options.ttlMs }
|
|
21023
|
+
}, at);
|
|
21024
|
+
this.board.ask(id, pending, at);
|
|
21025
|
+
if (ask.approvalId !== void 0) this.codeByApprovalId.set(ask.approvalId, pending.code);
|
|
21026
|
+
const wait = new Promise((resolve17) => {
|
|
21027
|
+
this.approvalWaiters.set(pending.code, resolve17);
|
|
21028
|
+
});
|
|
21029
|
+
return { code: pending.code, wait };
|
|
21030
|
+
}
|
|
21031
|
+
askQuestion(id, ask, at = this.now()) {
|
|
21032
|
+
const pending = createPending({
|
|
21033
|
+
kind: "question",
|
|
21034
|
+
sessionId: id,
|
|
21035
|
+
prompt: ask.prompt,
|
|
21036
|
+
...ask.options === void 0 ? {} : { options: ask.options },
|
|
21037
|
+
code: this.nextCode(),
|
|
21038
|
+
...this.options.ttlMs === void 0 ? {} : { ttlMs: this.options.ttlMs }
|
|
21039
|
+
}, at);
|
|
21040
|
+
this.board.ask(id, pending, at);
|
|
21041
|
+
const wait = new Promise((resolve17) => {
|
|
21042
|
+
this.questionWaiters.set(pending.code, resolve17);
|
|
21043
|
+
});
|
|
21044
|
+
return { code: pending.code, wait };
|
|
21045
|
+
}
|
|
21046
|
+
/** Another client (e.g. the desktop) resolved this approval: drop the remote card. */
|
|
21047
|
+
dismissApproval(approvalId, at = this.now()) {
|
|
21048
|
+
const code = this.codeByApprovalId.get(approvalId);
|
|
21049
|
+
if (code === void 0) return false;
|
|
21050
|
+
this.codeByApprovalId.delete(approvalId);
|
|
21051
|
+
this.approvalWaiters.delete(code);
|
|
21052
|
+
const task = this.board.list().find((entry) => entry.pending?.code === code);
|
|
21053
|
+
if (task !== void 0) {
|
|
21054
|
+
this.board.clearPending(task.id);
|
|
21055
|
+
return true;
|
|
21056
|
+
}
|
|
21057
|
+
return false;
|
|
21058
|
+
}
|
|
21059
|
+
/** Drop expired codes so the board does not keep stale cards. */
|
|
21060
|
+
expire(at = this.now()) {
|
|
21061
|
+
const dropped = this.board.expire(at);
|
|
21062
|
+
for (const code of dropped) {
|
|
21063
|
+
this.approvalWaiters.delete(code);
|
|
21064
|
+
this.questionWaiters.delete(code);
|
|
21065
|
+
}
|
|
21066
|
+
return dropped;
|
|
21067
|
+
}
|
|
21068
|
+
/**
|
|
21069
|
+
* Resolve every held ask so tearing the channel down cannot leave a tool
|
|
21070
|
+
* waiting forever. An approval becomes a rejection (the desktop had already
|
|
21071
|
+
* been bypassed by this hook); a question becomes an empty answer.
|
|
21072
|
+
*/
|
|
21073
|
+
releasePending() {
|
|
21074
|
+
for (const resolve17 of this.approvalWaiters.values()) resolve17("reject");
|
|
21075
|
+
this.approvalWaiters.clear();
|
|
21076
|
+
for (const resolve17 of this.questionWaiters.values()) resolve17("");
|
|
21077
|
+
this.questionWaiters.clear();
|
|
21078
|
+
for (const task of this.board.list()) {
|
|
21079
|
+
if (task.pending !== void 0) this.board.clearPending(task.id);
|
|
21080
|
+
}
|
|
21081
|
+
}
|
|
21082
|
+
renderCard(id, capabilities, hostOnline = true) {
|
|
21083
|
+
const task = this.board.get(id);
|
|
21084
|
+
if (task === void 0) return void 0;
|
|
21085
|
+
const number = this.numbers.get(id) ?? 0;
|
|
21086
|
+
return renderTaskCard(task, number, capabilities, this.board.presented(id, hostOnline) ?? task.state);
|
|
21087
|
+
}
|
|
21088
|
+
renderList(capabilities) {
|
|
21089
|
+
return renderTaskList(this.tasks(), this.numbers, capabilities);
|
|
21090
|
+
}
|
|
21091
|
+
focus(chatId) {
|
|
21092
|
+
return this.focusByChat.get(chatId);
|
|
21093
|
+
}
|
|
21094
|
+
/** Restore a persisted focus; ignore ids the board no longer has. */
|
|
21095
|
+
setFocus(chatId, id) {
|
|
21096
|
+
if (this.board.get(id) === void 0) return;
|
|
21097
|
+
this.focusByChat.set(chatId, id);
|
|
21098
|
+
}
|
|
21099
|
+
/** Handle one inbound message for a chat. Returns the reply text. */
|
|
21100
|
+
async execute(chatId, input, capabilities, at = this.now()) {
|
|
21101
|
+
const command = parseCommand(input);
|
|
21102
|
+
if (command.kind === "invalid") return { text: this.invalidText(command.reason) };
|
|
21103
|
+
if (command.kind === "tasks") {
|
|
21104
|
+
const text3 = this.renderList(capabilities);
|
|
21105
|
+
if (!capabilities.buttons) return { text: text3 };
|
|
21106
|
+
const buttons = listActionButtons(this.tasks(), this.numbers);
|
|
21107
|
+
return buttons.length === 0 ? { text: text3 } : { text: text3, buttons };
|
|
21108
|
+
}
|
|
21109
|
+
if (command.kind === "switch") {
|
|
21110
|
+
const target2 = this.byNumber(command.number);
|
|
21111
|
+
if (target2 === void 0) return { text: `\u6CA1\u6709\u7F16\u53F7 ${command.number} \u7684\u4EFB\u52A1\u3002\u56DE\u300C\u4EFB\u52A1\u300D\u770B\u5217\u8868\u3002` };
|
|
21112
|
+
this.focusByChat.set(chatId, target2.id);
|
|
21113
|
+
const task = this.board.get(target2.id);
|
|
21114
|
+
return task === void 0 ? { text: "\u4EFB\u52A1\u5DF2\u4E0D\u5B58\u5728\u3002\u56DE\u300C\u4EFB\u52A1\u300D\u770B\u5217\u8868\u3002" } : this.focusedReply(task, capabilities, at);
|
|
21115
|
+
}
|
|
21116
|
+
if (command.kind === "detail") {
|
|
21117
|
+
const pending = this.tasks().filter((task2) => task2.pending !== void 0);
|
|
21118
|
+
const target2 = command.number === void 0 ? pending.length === 1 ? pending[0] : this.taskFor(chatId) : this.byNumber(command.number);
|
|
21119
|
+
if (target2 === void 0) return { text: "\u6CA1\u6709\u53EF\u663E\u793A\u7684\u4EFB\u52A1\u3002\u56DE\u300C\u4EFB\u52A1\u300D\u770B\u5217\u8868\u3002" };
|
|
21120
|
+
this.focusByChat.set(chatId, target2.id);
|
|
21121
|
+
const task = this.board.get(target2.id);
|
|
21122
|
+
return task === void 0 ? { text: "\u4EFB\u52A1\u5DF2\u4E0D\u5B58\u5728\u3002\u56DE\u300C\u4EFB\u52A1\u300D\u770B\u5217\u8868\u3002" } : this.focusedReply(task, capabilities, at);
|
|
21123
|
+
}
|
|
21124
|
+
if (command.kind === "approve" || command.kind === "reject") {
|
|
21125
|
+
return this.decide(command.kind, command.code, at);
|
|
21126
|
+
}
|
|
21127
|
+
if (command.kind === "answer") {
|
|
21128
|
+
const route = routeAnswer(this.board.list(), command, at);
|
|
21129
|
+
if (!route.ok) return { text: this.routeFailureText(route.reason, route.codes) };
|
|
21130
|
+
const result = this.board.decide(route.taskId, route.pending.code, at);
|
|
21131
|
+
if (result !== "ok") return { text: this.routeFailureText(result === "expired" ? "expired" : "unknown-code") };
|
|
21132
|
+
const waiter = this.questionWaiters.get(route.pending.code);
|
|
21133
|
+
this.questionWaiters.delete(route.pending.code);
|
|
21134
|
+
waiter?.(route.text);
|
|
21135
|
+
return { text: `\u5DF2\u56DE\u590D\u3010${this.numbers.get(route.taskId) ?? 0}\u3011${this.taskTitle(route.taskId)}` };
|
|
21136
|
+
}
|
|
21137
|
+
if (command.kind === "pause" || command.kind === "resume") {
|
|
21138
|
+
const target2 = this.taskFor(chatId);
|
|
21139
|
+
if (target2 === void 0) return { text: "\u5148\u56DE\u300C\u4EFB\u52A1\u300D\u9009\u4E00\u4E2A\u4EFB\u52A1\u3002" };
|
|
21140
|
+
const paused = command.kind === "pause";
|
|
21141
|
+
try {
|
|
21142
|
+
await this.options.actions.setPaused(target2.id, paused);
|
|
21143
|
+
} catch (error) {
|
|
21144
|
+
return { text: `\u64CD\u4F5C\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}` };
|
|
21145
|
+
}
|
|
21146
|
+
if (paused) this.board.pause(target2.id);
|
|
21147
|
+
else this.board.resume(target2.id, at);
|
|
21148
|
+
const text3 = paused ? `\u5DF2\u6682\u505C\u3010${this.numbers.get(target2.id) ?? 0}\u3011${target2.title}` : `\u5DF2\u7EE7\u7EED\u3010${this.numbers.get(target2.id) ?? 0}\u3011${target2.title}`;
|
|
21149
|
+
return this.withTaskButtons(text3, target2.id, capabilities);
|
|
21150
|
+
}
|
|
21151
|
+
const target = this.taskFor(chatId);
|
|
21152
|
+
if (target === void 0) {
|
|
21153
|
+
return { text: this.tasks().length === 0 ? "\u5F53\u524D\u6CA1\u6709\u4EFB\u52A1\u3002" : "\u5148\u56DE\u300C\u4EFB\u52A1\u300D\u9009\u4E00\u4E2A\u4EFB\u52A1\uFF0C\u518D\u53D1\u6D88\u606F\u3002" };
|
|
21154
|
+
}
|
|
21155
|
+
try {
|
|
21156
|
+
await this.options.actions.sendPrompt(target.id, command.text);
|
|
21157
|
+
} catch (error) {
|
|
21158
|
+
return { text: `\u53D1\u9001\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}` };
|
|
21159
|
+
}
|
|
21160
|
+
return this.withTaskButtons(
|
|
21161
|
+
`\u5DF2\u53D1\u7ED9\u3010${this.numbers.get(target.id) ?? 0}\u3011${target.title}`,
|
|
21162
|
+
target.id,
|
|
21163
|
+
capabilities
|
|
21164
|
+
);
|
|
21165
|
+
}
|
|
21166
|
+
/** Attach a task's actions when the channel can render buttons. */
|
|
21167
|
+
/**
|
|
21168
|
+
* One task, in full: status, pending decision and the latest answer.
|
|
21169
|
+
* Switching and 详情 land here, so the chat watches a task instead of
|
|
21170
|
+
* bouncing back into the picker.
|
|
21171
|
+
*/
|
|
21172
|
+
async focusedReply(task, capabilities, at) {
|
|
21173
|
+
const card = this.renderCard(task.id, capabilities);
|
|
21174
|
+
let answer = this.board.get(task.id)?.lastAnswer;
|
|
21175
|
+
if (answer === void 0 && this.options.readAnswer !== void 0) {
|
|
21176
|
+
answer = await this.options.readAnswer(task.id).catch(() => void 0);
|
|
21177
|
+
if (answer !== void 0 && answer.trim() !== "") {
|
|
21178
|
+
this.board.answer(task.id, answer.trim().slice(0, 8e3), at);
|
|
21179
|
+
} else {
|
|
21180
|
+
answer = void 0;
|
|
21181
|
+
}
|
|
21182
|
+
}
|
|
21183
|
+
const text3 = card === void 0 ? "\u4EFB\u52A1\u5DF2\u4E0D\u5B58\u5728\u3002" : answer === void 0 || answer === "" ? card : `${card}
|
|
21184
|
+
|
|
21185
|
+
\u56DE\u7B54\uFF1A${answer}`;
|
|
21186
|
+
return this.withTaskButtons(text3, task.id, capabilities);
|
|
21187
|
+
}
|
|
21188
|
+
withTaskButtons(text3, id, capabilities) {
|
|
21189
|
+
if (!capabilities.buttons) return { text: text3 };
|
|
21190
|
+
const task = this.board.get(id);
|
|
21191
|
+
if (task === void 0) return { text: text3 };
|
|
21192
|
+
const buttons = taskActionButtons(task);
|
|
21193
|
+
return buttons.length === 0 ? { text: text3 } : { text: text3, buttons };
|
|
21194
|
+
}
|
|
21195
|
+
decide(kind, code, at) {
|
|
21196
|
+
const tasks = this.board.list();
|
|
21197
|
+
const route = kind === "approve" ? routeDecision(tasks, code === void 0 ? { kind: "approve" } : { kind: "approve", code }, at) : routeDecision(tasks, code === void 0 ? { kind: "reject" } : { kind: "reject", code }, at);
|
|
21198
|
+
if (!route.ok) return { text: this.routeFailureText(route.reason, route.codes) };
|
|
21199
|
+
const result = this.board.decide(route.taskId, route.pending.code, at);
|
|
21200
|
+
if (result !== "ok") return { text: this.routeFailureText(result === "expired" ? "expired" : "unknown-code") };
|
|
21201
|
+
const waiter = this.approvalWaiters.get(route.pending.code);
|
|
21202
|
+
this.approvalWaiters.delete(route.pending.code);
|
|
21203
|
+
if (route.pending.kind === "approval") waiter?.(route.decision);
|
|
21204
|
+
const label = route.decision === "approve" ? "\u5DF2\u6279\u51C6" : "\u5DF2\u62D2\u7EDD";
|
|
21205
|
+
return { text: `${label}\u3010${this.numbers.get(route.taskId) ?? 0}\u3011${this.taskTitle(route.taskId)}` };
|
|
21206
|
+
}
|
|
21207
|
+
routeFailureText(reason, codes) {
|
|
21208
|
+
switch (reason) {
|
|
21209
|
+
case "no-pending":
|
|
21210
|
+
return "\u5F53\u524D\u6CA1\u6709\u5F85\u5904\u7406\u7684\u51B3\u5B9A\u3002";
|
|
21211
|
+
case "ambiguous":
|
|
21212
|
+
return `\u6709\u591A\u4E2A\u5F85\u5904\u7406\uFF0C\u8BF7\u5E26\u7F16\u53F7\uFF1A${(codes ?? []).join(" / ")}`;
|
|
21213
|
+
case "unknown-code":
|
|
21214
|
+
return (codes ?? []).length > 0 ? `\u6CA1\u6709\u8FD9\u4E2A\u7F16\u53F7\uFF0C\u5F53\u524D\u53EF\u7528\uFF1A${(codes ?? []).join(" / ")}` : "\u6CA1\u6709\u8FD9\u4E2A\u7F16\u53F7\uFF0C\u5F53\u524D\u6CA1\u6709\u5F85\u5904\u7406\u3002";
|
|
21215
|
+
case "expired":
|
|
21216
|
+
return "\u8FD9\u6761\u5DF2\u7ECF\u8FC7\u671F\uFF0C\u7B49\u7535\u8111\u4E0A\u91CD\u65B0\u53D1\u8D77\u3002";
|
|
21217
|
+
case "not-a-decision":
|
|
21218
|
+
case "not-an-answer":
|
|
21219
|
+
return "\u8FD9\u4E0D\u662F\u4E00\u4E2A\u51B3\u5B9A\u3002";
|
|
21220
|
+
default:
|
|
21221
|
+
return "\u5904\u7406\u5931\u8D25\u3002";
|
|
21222
|
+
}
|
|
21223
|
+
}
|
|
21224
|
+
invalidText(reason) {
|
|
21225
|
+
switch (reason) {
|
|
21226
|
+
case "empty":
|
|
21227
|
+
return "\u8BF4\u70B9\u4EC0\u4E48\uFF0C\u6216\u8005\u56DE\u300C\u4EFB\u52A1\u300D\u3002";
|
|
21228
|
+
case "bad-code":
|
|
21229
|
+
return "\u7F16\u53F7\u662F 4 \u4F4D\u5C0F\u5199\u5B57\u6BCD\u6570\u5B57\uFF0C\u4F8B\u5982 a3f9\u3002";
|
|
21230
|
+
case "bad-task-number":
|
|
21231
|
+
return "\u4EFB\u52A1\u7F16\u53F7\u662F\u6B63\u6574\u6570\uFF0C\u4F8B\u5982\u300C\u5207 2\u300D\u3002";
|
|
21232
|
+
case "unexpected-argument":
|
|
21233
|
+
return "\u8FD9\u4E2A\u8BCD\u540E\u9762\u4E0D\u9700\u8981\u53C2\u6570\u3002";
|
|
21234
|
+
case "answer-empty":
|
|
21235
|
+
return "\u56DE\u7B54\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A\u3002";
|
|
21236
|
+
case "empty-message":
|
|
21237
|
+
return "\u8981\u53D1\u7ED9\u4EFB\u52A1\u7684\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A\u3002";
|
|
21238
|
+
default:
|
|
21239
|
+
return "\u6CA1\u770B\u61C2\uFF0C\u56DE\u300C\u4EFB\u52A1\u300D\u770B\u53EF\u9009\u64CD\u4F5C\u3002";
|
|
21240
|
+
}
|
|
21241
|
+
}
|
|
21242
|
+
byNumber(number) {
|
|
21243
|
+
for (const task of this.tasks()) {
|
|
21244
|
+
if (this.numbers.get(task.id) === number) return { id: task.id, title: task.title };
|
|
21245
|
+
}
|
|
21246
|
+
return void 0;
|
|
21247
|
+
}
|
|
21248
|
+
taskFor(chatId) {
|
|
21249
|
+
const focused = this.focusByChat.get(chatId);
|
|
21250
|
+
if (focused !== void 0) {
|
|
21251
|
+
const task = this.board.get(focused);
|
|
21252
|
+
if (task !== void 0) return { id: task.id, title: task.title };
|
|
21253
|
+
this.focusByChat.delete(chatId);
|
|
21254
|
+
}
|
|
21255
|
+
const waiting = this.tasks().filter((task) => task.pending !== void 0);
|
|
21256
|
+
if (waiting.length === 1) {
|
|
21257
|
+
const only2 = waiting[0];
|
|
21258
|
+
if (only2 === void 0) return void 0;
|
|
21259
|
+
this.focusByChat.set(chatId, only2.id);
|
|
21260
|
+
return { id: only2.id, title: only2.title };
|
|
21261
|
+
}
|
|
21262
|
+
const all = this.tasks();
|
|
21263
|
+
if (all.length !== 1) return void 0;
|
|
21264
|
+
const only = all[0];
|
|
21265
|
+
if (only === void 0) return void 0;
|
|
21266
|
+
this.focusByChat.set(chatId, only.id);
|
|
21267
|
+
return { id: only.id, title: only.title };
|
|
21268
|
+
}
|
|
21269
|
+
taskTitle(id) {
|
|
21270
|
+
return this.board.get(id)?.title ?? id;
|
|
21271
|
+
}
|
|
21272
|
+
};
|
|
21273
|
+
|
|
21274
|
+
// src/host/remote/host-bridge.ts
|
|
21275
|
+
function sessionIdOf2(agent) {
|
|
21276
|
+
const id = agent?.session?.id;
|
|
21277
|
+
return typeof id === "string" && id !== "" ? id : void 0;
|
|
21278
|
+
}
|
|
21279
|
+
function turnEndKind(reason) {
|
|
21280
|
+
const kind = reason !== null && typeof reason === "object" && "kind" in reason ? String(reason.kind) : "";
|
|
21281
|
+
switch (kind) {
|
|
21282
|
+
case "completed":
|
|
21283
|
+
return "ok";
|
|
21284
|
+
case "aborted":
|
|
21285
|
+
case "interrupted":
|
|
21286
|
+
return "aborted";
|
|
21287
|
+
case "blocked":
|
|
21288
|
+
case "forked":
|
|
21289
|
+
return "stopped";
|
|
21290
|
+
default:
|
|
21291
|
+
return "error";
|
|
21292
|
+
}
|
|
21293
|
+
}
|
|
21294
|
+
function turnEndError(reason) {
|
|
21295
|
+
if (reason === null || typeof reason !== "object") return void 0;
|
|
21296
|
+
const error = reason.error;
|
|
21297
|
+
return typeof error?.message === "string" ? error.message : void 0;
|
|
21298
|
+
}
|
|
21299
|
+
function describeApproval(request) {
|
|
21300
|
+
const tool = typeof request.toolName === "string" && request.toolName !== "" ? request.toolName : "\u5DE5\u5177";
|
|
21301
|
+
return typeof request.reason === "string" && request.reason !== "" ? `${tool} \u8BF7\u6C42\u6267\u884C\uFF1A${request.reason}` : `${tool} \u8BF7\u6C42\u6267\u884C`;
|
|
21302
|
+
}
|
|
21303
|
+
function assistantText(data) {
|
|
21304
|
+
const message = data.message;
|
|
21305
|
+
if (message === null || typeof message !== "object") return void 0;
|
|
21306
|
+
const content = message.content;
|
|
21307
|
+
if (!Array.isArray(content)) return void 0;
|
|
21308
|
+
const parts = [];
|
|
21309
|
+
for (const block of content) {
|
|
21310
|
+
if (block === null || typeof block !== "object") continue;
|
|
21311
|
+
const record2 = block;
|
|
21312
|
+
if (record2.type === "text" && typeof record2.text === "string" && record2.text.trim() !== "") {
|
|
21313
|
+
parts.push(record2.text.trim());
|
|
21314
|
+
}
|
|
21315
|
+
}
|
|
21316
|
+
return parts.length === 0 ? void 0 : parts.join("\n");
|
|
21317
|
+
}
|
|
21318
|
+
function questionLabels(question) {
|
|
21319
|
+
if (!Array.isArray(question.options)) return [];
|
|
21320
|
+
return question.options.map((option) => typeof option?.label === "string" ? option.label : "").filter((label) => label !== "");
|
|
21321
|
+
}
|
|
21322
|
+
function pickAnswer(labels, text3) {
|
|
21323
|
+
const match = labels.find((label) => label.trim() === text3.trim());
|
|
21324
|
+
return match === void 0 ? { selected: [], custom: text3 } : { selected: [match] };
|
|
21325
|
+
}
|
|
21326
|
+
function installRemoteHostBridge(ctx, options) {
|
|
21327
|
+
const controller = new RemoteController({
|
|
21328
|
+
actions: {
|
|
21329
|
+
sendPrompt: (sessionId, text3) => options.ports.prompt(sessionId, text3, "queue"),
|
|
21330
|
+
setPaused: (sessionId, paused) => options.ports.setPaused(sessionId, paused),
|
|
21331
|
+
stop: (sessionId) => options.ports.cancel(sessionId)
|
|
21332
|
+
},
|
|
21333
|
+
...options.ports.readAnswer === void 0 ? {} : { readAnswer: options.ports.readAnswer },
|
|
21334
|
+
...options.now === void 0 ? {} : { now: options.now },
|
|
21335
|
+
...options.ttlMs === void 0 ? {} : { ttlMs: options.ttlMs }
|
|
21336
|
+
});
|
|
21337
|
+
const known = (sessionId) => controller.tasks().some((task) => task.id === sessionId);
|
|
21338
|
+
const lastAssistant = /* @__PURE__ */ new Map();
|
|
21339
|
+
const notify = (notice) => {
|
|
21340
|
+
try {
|
|
21341
|
+
options.ports.notify?.(notice);
|
|
21342
|
+
} catch {
|
|
21343
|
+
}
|
|
21344
|
+
};
|
|
21345
|
+
let refreshing;
|
|
21346
|
+
let lastEventRefresh = 0;
|
|
21347
|
+
const refreshSessions = async () => {
|
|
21348
|
+
if (refreshing !== void 0) return refreshing;
|
|
21349
|
+
refreshing = (async () => {
|
|
21350
|
+
const rows = await options.ports.listSessions();
|
|
21351
|
+
for (const row of rows) controller.track(row);
|
|
21352
|
+
return rows.length;
|
|
21353
|
+
})();
|
|
21354
|
+
try {
|
|
21355
|
+
return await refreshing;
|
|
21356
|
+
} finally {
|
|
21357
|
+
refreshing = void 0;
|
|
21358
|
+
}
|
|
21359
|
+
};
|
|
21360
|
+
const refreshForUnknown = (at) => {
|
|
21361
|
+
if (at - lastEventRefresh < 2e3) return;
|
|
21362
|
+
lastEventRefresh = at;
|
|
21363
|
+
void refreshSessions().catch(() => {
|
|
21364
|
+
});
|
|
21365
|
+
};
|
|
21366
|
+
const onSessionEvent = (session, event) => {
|
|
21367
|
+
const sessionId = typeof session?.id === "string" ? session.id : void 0;
|
|
21368
|
+
if (sessionId === void 0 || sessionId === "") return;
|
|
21369
|
+
const data = event?.data ?? {};
|
|
21370
|
+
const at = typeof event.time === "number" ? event.time : options.now?.() ?? Date.now();
|
|
21371
|
+
if (!known(sessionId)) refreshForUnknown(at);
|
|
21372
|
+
switch (event.type) {
|
|
21373
|
+
case "turn/start":
|
|
21374
|
+
lastAssistant.delete(sessionId);
|
|
21375
|
+
controller.onTurnStart(sessionId, at);
|
|
21376
|
+
break;
|
|
21377
|
+
case "turn/end": {
|
|
21378
|
+
const reason = turnEndKind(data.reason);
|
|
21379
|
+
controller.onTurnEnd(sessionId, reason, turnEndError(data.reason), at);
|
|
21380
|
+
if (!known(sessionId)) break;
|
|
21381
|
+
if (reason === "error") {
|
|
21382
|
+
notify({ kind: "failed", sessionId, ...turnEndError(data.reason) === void 0 ? {} : { error: turnEndError(data.reason) } });
|
|
21383
|
+
break;
|
|
21384
|
+
}
|
|
21385
|
+
if (reason === "ok") {
|
|
21386
|
+
const answer = lastAssistant.get(sessionId);
|
|
21387
|
+
lastAssistant.delete(sessionId);
|
|
21388
|
+
if (answer !== void 0) {
|
|
21389
|
+
notify({ kind: "done", sessionId, answer });
|
|
21390
|
+
} else if (options.ports.readAnswer !== void 0) {
|
|
21391
|
+
void options.ports.readAnswer(sessionId).then((text3) => notify({
|
|
21392
|
+
kind: "done",
|
|
21393
|
+
sessionId,
|
|
21394
|
+
...text3 === void 0 || text3.trim() === "" ? {} : { answer: text3 }
|
|
21395
|
+
})).catch(() => {
|
|
21396
|
+
notify({ kind: "done", sessionId });
|
|
21397
|
+
});
|
|
21398
|
+
} else {
|
|
21399
|
+
notify({ kind: "done", sessionId });
|
|
21400
|
+
}
|
|
21401
|
+
}
|
|
21402
|
+
break;
|
|
21403
|
+
}
|
|
21404
|
+
case "assistant/message": {
|
|
21405
|
+
const text3 = assistantText(data);
|
|
21406
|
+
if (text3 !== void 0) {
|
|
21407
|
+
const stored = text3.length > 8e3 ? `${text3.slice(0, 7999)}\u2026` : text3;
|
|
21408
|
+
lastAssistant.set(sessionId, stored);
|
|
21409
|
+
controller.onAnswer(sessionId, stored, at);
|
|
21410
|
+
}
|
|
21411
|
+
break;
|
|
21412
|
+
}
|
|
21413
|
+
case "session/title":
|
|
21414
|
+
if (typeof data.title === "string" && data.title !== "") controller.onTitle(sessionId, data.title);
|
|
21415
|
+
break;
|
|
21416
|
+
case "tool/result":
|
|
21417
|
+
controller.onNote(sessionId, data.error === void 0 ? "\u5DE5\u5177\u6267\u884C\u5B8C\u6210" : "\u5DE5\u5177\u6267\u884C\u5931\u8D25", at);
|
|
21418
|
+
break;
|
|
21419
|
+
case "approval/decided":
|
|
21420
|
+
if (typeof data.id === "string") controller.dismissApproval(data.id, at);
|
|
21421
|
+
break;
|
|
21422
|
+
}
|
|
21423
|
+
};
|
|
21424
|
+
const canAnswer = () => options.shouldHold?.() !== false;
|
|
21425
|
+
const onApprovalRequest = (request, next) => {
|
|
21426
|
+
if (!canAnswer()) return next();
|
|
21427
|
+
const sessionId = sessionIdOf2(request?.agent);
|
|
21428
|
+
if (sessionId === void 0 || !known(sessionId)) return next();
|
|
21429
|
+
try {
|
|
21430
|
+
const handle = controller.askApproval(sessionId, {
|
|
21431
|
+
prompt: describeApproval(request),
|
|
21432
|
+
...typeof request.approvalId === "string" ? { approvalId: request.approvalId } : {},
|
|
21433
|
+
risk: "other"
|
|
21434
|
+
});
|
|
21435
|
+
notify({ kind: "approval", sessionId, code: handle.code });
|
|
21436
|
+
return handle.wait;
|
|
21437
|
+
} catch {
|
|
21438
|
+
return next();
|
|
21439
|
+
}
|
|
21440
|
+
};
|
|
21441
|
+
const onQuestionRequest = (request, next) => {
|
|
21442
|
+
if (!canAnswer()) return next();
|
|
21443
|
+
const sessionId = sessionIdOf2(request?.agent) ?? (typeof request?.sessionId === "string" ? request.sessionId : void 0);
|
|
21444
|
+
if (sessionId === void 0 || !known(sessionId)) return next();
|
|
21445
|
+
const questions = Array.isArray(request.questions) ? request.questions : [];
|
|
21446
|
+
if (questions.length !== 1) return next();
|
|
21447
|
+
const question = questions[0];
|
|
21448
|
+
if (question === void 0) return next();
|
|
21449
|
+
const questionId = typeof question.id === "string" ? question.id : void 0;
|
|
21450
|
+
if (questionId === void 0) return next();
|
|
21451
|
+
const labels = questionLabels(question);
|
|
21452
|
+
const prompt = typeof question.header === "string" && question.header !== "" ? question.header : typeof question.detail === "string" && question.detail !== "" ? question.detail : "\u9700\u8981\u4F60\u56DE\u7B54";
|
|
21453
|
+
try {
|
|
21454
|
+
const handle = controller.askQuestion(sessionId, {
|
|
21455
|
+
prompt,
|
|
21456
|
+
...labels.length === 0 ? {} : { options: labels }
|
|
21457
|
+
});
|
|
21458
|
+
notify({ kind: "question", sessionId, code: handle.code });
|
|
21459
|
+
return handle.wait.then((text3) => ({
|
|
21460
|
+
answers: [{ id: questionId, ...pickAnswer(labels, text3) }]
|
|
21461
|
+
}));
|
|
21462
|
+
} catch {
|
|
21463
|
+
return next();
|
|
21464
|
+
}
|
|
21465
|
+
};
|
|
21466
|
+
const loose = ctx;
|
|
21467
|
+
const disposers = [
|
|
21468
|
+
loose.on("session/event", onSessionEvent, { global: true }),
|
|
21469
|
+
loose.on("approval/request", onApprovalRequest, { prepend: true, global: true }),
|
|
21470
|
+
loose.on("user-questions/request", onQuestionRequest, { prepend: true, global: true })
|
|
21471
|
+
];
|
|
21472
|
+
return {
|
|
21473
|
+
controller,
|
|
21474
|
+
refreshSessions,
|
|
21475
|
+
dispose() {
|
|
21476
|
+
for (const dispose of disposers) {
|
|
21477
|
+
try {
|
|
21478
|
+
dispose();
|
|
21479
|
+
} catch {
|
|
21480
|
+
}
|
|
21481
|
+
}
|
|
21482
|
+
}
|
|
21483
|
+
};
|
|
21484
|
+
}
|
|
21485
|
+
|
|
21486
|
+
// src/host/remote/ports.ts
|
|
21487
|
+
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
21488
|
+
function titleOf2(item, sessionId) {
|
|
21489
|
+
const projections = item.projections;
|
|
21490
|
+
if (projections !== null && typeof projections === "object") {
|
|
21491
|
+
const values = projections.values;
|
|
21492
|
+
if (values !== null && typeof values === "object") {
|
|
21493
|
+
const title = values.title;
|
|
21494
|
+
if (typeof title === "string" && title.trim() !== "") return title;
|
|
21495
|
+
}
|
|
21496
|
+
}
|
|
21497
|
+
return sessionId.slice(0, 8);
|
|
21498
|
+
}
|
|
21499
|
+
function toRow(item) {
|
|
21500
|
+
if (item === null || typeof item !== "object") return void 0;
|
|
21501
|
+
const record2 = item;
|
|
21502
|
+
const sessionId = typeof record2.sessionId === "string" ? record2.sessionId : void 0;
|
|
21503
|
+
if (sessionId === void 0 || sessionId === "") return void 0;
|
|
21504
|
+
if (record2.origin === "subagent") return void 0;
|
|
21505
|
+
return {
|
|
21506
|
+
id: sessionId,
|
|
21507
|
+
title: titleOf2(record2, sessionId),
|
|
21508
|
+
running: record2.running === true
|
|
21509
|
+
};
|
|
21510
|
+
}
|
|
21511
|
+
function controllerOf(ctx) {
|
|
21512
|
+
let service;
|
|
21513
|
+
try {
|
|
21514
|
+
service = ctx.get("sessionController");
|
|
21515
|
+
} catch {
|
|
21516
|
+
service = void 0;
|
|
21517
|
+
}
|
|
21518
|
+
if (service === null || service === void 0 || typeof service !== "object" || typeof service.list !== "function") {
|
|
21519
|
+
throw new Error("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B sessionController\uFF0C\u8FDC\u7A0B\u63A7\u5236\u65E0\u6CD5\u5DE5\u4F5C");
|
|
21520
|
+
}
|
|
21521
|
+
return service;
|
|
21522
|
+
}
|
|
21523
|
+
function createHostPorts(ctx, options) {
|
|
21524
|
+
return {
|
|
21525
|
+
async listSessions() {
|
|
21526
|
+
const signal = new AbortController().signal;
|
|
21527
|
+
const value = await controllerOf(ctx).list({}, signal);
|
|
21528
|
+
const items = value !== null && typeof value === "object" ? value.items : void 0;
|
|
21529
|
+
if (!Array.isArray(items)) return [];
|
|
21530
|
+
const rows = [];
|
|
21531
|
+
for (const item of items) {
|
|
21532
|
+
const row = toRow(item);
|
|
21533
|
+
if (row !== void 0) rows.push(row);
|
|
21534
|
+
}
|
|
21535
|
+
return rows;
|
|
21536
|
+
},
|
|
21537
|
+
async prompt(sessionId, text3, mode) {
|
|
21538
|
+
const request = {
|
|
21539
|
+
requestId: randomUUID9(),
|
|
21540
|
+
sessionId,
|
|
21541
|
+
mode,
|
|
21542
|
+
content: [{ type: "text", text: text3 }]
|
|
21543
|
+
};
|
|
21544
|
+
await controllerOf(ctx).prompt(request, new AbortController().signal);
|
|
21545
|
+
},
|
|
21546
|
+
async cancel(sessionId) {
|
|
21547
|
+
const request = { sessionId };
|
|
21548
|
+
await controllerOf(ctx).cancel(request);
|
|
21549
|
+
},
|
|
21550
|
+
async setPaused(sessionId, paused) {
|
|
21551
|
+
await options.setPaused(sessionId, paused);
|
|
21552
|
+
},
|
|
21553
|
+
async readAnswer(sessionId) {
|
|
21554
|
+
const controller = controllerOf(ctx);
|
|
21555
|
+
const page = await controller.events({
|
|
21556
|
+
address: { kind: "session", sessionId },
|
|
21557
|
+
maxMessages: 50
|
|
21558
|
+
}, new AbortController().signal);
|
|
21559
|
+
const records = page?.records ?? [];
|
|
21560
|
+
for (let index = records.length - 1; index >= 0; index -= 1) {
|
|
21561
|
+
const entry = records[index];
|
|
21562
|
+
if (entry?.type !== "event" || entry.event?.type !== "assistant/message") continue;
|
|
21563
|
+
const text3 = assistantText(entry.event.data);
|
|
21564
|
+
if (text3 !== void 0 && text3.trim() !== "") return text3;
|
|
21565
|
+
}
|
|
21566
|
+
return void 0;
|
|
21567
|
+
},
|
|
21568
|
+
notify(notice) {
|
|
21569
|
+
options.notify?.(notice);
|
|
21570
|
+
}
|
|
21571
|
+
};
|
|
21572
|
+
}
|
|
21573
|
+
|
|
21574
|
+
// src/host/remote/telegram/channel.ts
|
|
21575
|
+
import { join as join30 } from "node:path";
|
|
21576
|
+
|
|
21577
|
+
// src/host/remote/channels/cursor.ts
|
|
21578
|
+
import { mkdirSync as mkdirSync14, readFileSync as readFileSync12, renameSync as renameSync10, writeFileSync as writeFileSync8 } from "node:fs";
|
|
21579
|
+
import { dirname as dirname14 } from "node:path";
|
|
21580
|
+
function load(filePath, fallback) {
|
|
21581
|
+
try {
|
|
21582
|
+
const parsed = JSON.parse(readFileSync12(filePath, "utf8"));
|
|
21583
|
+
return parsed.version === 1 && typeof parsed.cursor === "string" ? parsed.cursor : fallback;
|
|
21584
|
+
} catch {
|
|
21585
|
+
return fallback;
|
|
21586
|
+
}
|
|
21587
|
+
}
|
|
21588
|
+
function createCursorStore(options) {
|
|
21589
|
+
const fallback = options.initial ?? "";
|
|
21590
|
+
let current = options.filePath === null ? fallback : load(options.filePath, fallback);
|
|
21591
|
+
return {
|
|
21592
|
+
get: () => current,
|
|
21593
|
+
set(next) {
|
|
21594
|
+
current = next;
|
|
21595
|
+
if (options.filePath === null) return;
|
|
21596
|
+
try {
|
|
21597
|
+
const shape = { version: 1, cursor: next };
|
|
21598
|
+
mkdirSync14(dirname14(options.filePath), { recursive: true });
|
|
21599
|
+
const tmp = `${options.filePath}.tmp`;
|
|
21600
|
+
writeFileSync8(tmp, JSON.stringify(shape));
|
|
21601
|
+
renameSync10(tmp, options.filePath);
|
|
21602
|
+
} catch {
|
|
21603
|
+
}
|
|
21604
|
+
}
|
|
21605
|
+
};
|
|
21606
|
+
}
|
|
21607
|
+
|
|
21608
|
+
// src/host/remote/channels/types.ts
|
|
21609
|
+
var ChannelAuthError = class extends Error {
|
|
21610
|
+
constructor(code, message) {
|
|
21611
|
+
super(message);
|
|
21612
|
+
this.code = code;
|
|
21613
|
+
this.name = "ChannelAuthError";
|
|
21614
|
+
}
|
|
21615
|
+
code;
|
|
21616
|
+
};
|
|
21617
|
+
|
|
21618
|
+
// src/host/remote/channels/poller.ts
|
|
21619
|
+
var RETRY_DELAYS_MS = [250, 1e3, 3e3, 5e3, 1e4, 3e4];
|
|
21620
|
+
var DEFAULT_SLEEP = (ms) => new Promise((resolve17) => setTimeout(resolve17, ms));
|
|
21621
|
+
var DEFAULT_HINTS = {
|
|
21622
|
+
unbound: "\u8FD9\u53F0\u804A\u5929\u8FD8\u6CA1\u7ED1\u5B9A\u3002\u8BF7\u5728\u7535\u8111\u4E0A\u6253\u5F00\u300C\u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u8FDC\u7A0B\u8FDE\u63A5\u300D\u751F\u6210\u7ED1\u5B9A\u7801\uFF0C\u7136\u540E\u628A 6 \u4F4D\u6570\u5B57\u53D1\u7ED9\u6211\u3002",
|
|
21623
|
+
badCode: "\u7ED1\u5B9A\u7801\u65E0\u6548\u3001\u5DF2\u8FC7\u671F\uFF0C\u6216\u4E0D\u5C5E\u4E8E\u8FD9\u4E2A\u5E73\u53F0\u3002\u8BF7\u5728\u7535\u8111\u4E0A\u91CD\u65B0\u751F\u6210\u4E00\u4E2A\u3002",
|
|
21624
|
+
unsupported: "\u76EE\u524D\u53EA\u652F\u6301\u6587\u5B57\u548C\u8BED\u97F3\u3002\u56FE\u7247\u548C\u6587\u4EF6\u8BF7\u5728\u7535\u8111\u4E0A\u67E5\u770B\u3002",
|
|
21625
|
+
bound: "\u5DF2\u7ED1\u5B9A\u3002\u56DE\u300C\u4EFB\u52A1\u300D\u67E5\u770B\u5F53\u524D\u4EFB\u52A1\u3002"
|
|
21626
|
+
};
|
|
21627
|
+
function messageText2(message) {
|
|
21628
|
+
for (const item of message.items) {
|
|
21629
|
+
if (item.kind === "text" && item.text.trim() !== "") return item.text;
|
|
21630
|
+
}
|
|
21631
|
+
for (const item of message.items) {
|
|
21632
|
+
if (item.kind === "voice" && item.text !== void 0 && item.text.trim() !== "") return item.text;
|
|
21633
|
+
}
|
|
21634
|
+
return void 0;
|
|
21635
|
+
}
|
|
21636
|
+
var ChannelPoller = class {
|
|
21637
|
+
constructor(options) {
|
|
21638
|
+
this.options = options;
|
|
21639
|
+
this.sleep = options.sleep ?? DEFAULT_SLEEP;
|
|
21640
|
+
this.hints = { ...DEFAULT_HINTS, ...options.hints };
|
|
21641
|
+
let current = "";
|
|
21642
|
+
this.cursor = options.cursor ?? {
|
|
21643
|
+
get: () => current,
|
|
21644
|
+
set: (next) => {
|
|
21645
|
+
current = next;
|
|
21646
|
+
}
|
|
21647
|
+
};
|
|
21648
|
+
}
|
|
21649
|
+
options;
|
|
21650
|
+
stopped = false;
|
|
21651
|
+
contexts = /* @__PURE__ */ new Map();
|
|
21652
|
+
sleep;
|
|
21653
|
+
cursor;
|
|
21654
|
+
hints;
|
|
21655
|
+
stop() {
|
|
21656
|
+
this.stopped = true;
|
|
21657
|
+
}
|
|
21658
|
+
get running() {
|
|
21659
|
+
return !this.stopped;
|
|
21660
|
+
}
|
|
21661
|
+
/** Latest inbound context token, so a push can answer in the same thread. */
|
|
21662
|
+
contextFor(chatId) {
|
|
21663
|
+
return this.contexts.get(chatId);
|
|
21664
|
+
}
|
|
21665
|
+
async run() {
|
|
21666
|
+
let failures = 0;
|
|
21667
|
+
while (!this.stopped) {
|
|
21668
|
+
let page;
|
|
21669
|
+
try {
|
|
21670
|
+
page = await this.options.transport.getUpdates(this.cursor.get());
|
|
21671
|
+
} catch (error) {
|
|
21672
|
+
if (this.options.isFatal?.(error) === true || error instanceof ChannelAuthError) {
|
|
21673
|
+
this.stopped = true;
|
|
21674
|
+
this.options.onFatal?.(error);
|
|
21675
|
+
return;
|
|
21676
|
+
}
|
|
21677
|
+
this.options.onError?.(error);
|
|
21678
|
+
const retryAfter = error.retryAfterMs;
|
|
21679
|
+
const delay = typeof retryAfter === "number" && retryAfter > 0 ? retryAfter : RETRY_DELAYS_MS[Math.min(failures, RETRY_DELAYS_MS.length - 1)] ?? 3e4;
|
|
21680
|
+
failures += 1;
|
|
21681
|
+
await this.sleep(delay);
|
|
21682
|
+
continue;
|
|
21683
|
+
}
|
|
21684
|
+
failures = 0;
|
|
21685
|
+
this.cursor.set(page.cursor);
|
|
21686
|
+
for (const message of page.messages) {
|
|
21687
|
+
if (this.stopped) break;
|
|
21688
|
+
try {
|
|
21689
|
+
await this.handle(message);
|
|
21690
|
+
} catch (error) {
|
|
21691
|
+
this.options.onError?.(error);
|
|
21692
|
+
} finally {
|
|
21693
|
+
if (message.callbackQueryId !== void 0) {
|
|
21694
|
+
try {
|
|
21695
|
+
await this.options.transport.acknowledge?.(message.callbackQueryId);
|
|
21696
|
+
} catch (error) {
|
|
21697
|
+
this.options.onError?.(error);
|
|
21698
|
+
}
|
|
21699
|
+
}
|
|
21700
|
+
}
|
|
21701
|
+
}
|
|
21702
|
+
if (page.messages.length === 0 && !this.stopped) {
|
|
21703
|
+
await this.sleep(this.options.emptyPageDelayMs ?? 1e3);
|
|
21704
|
+
}
|
|
21705
|
+
}
|
|
21706
|
+
}
|
|
21707
|
+
async handle(message) {
|
|
21708
|
+
const chatId = message.fromUserId;
|
|
21709
|
+
if (message.contextToken !== void 0 && message.contextToken !== "") {
|
|
21710
|
+
this.contexts.set(chatId, message.contextToken);
|
|
21711
|
+
}
|
|
21712
|
+
const text3 = messageText2(message);
|
|
21713
|
+
if (text3 === void 0) {
|
|
21714
|
+
await this.reply(chatId, this.hints.unsupported, message.contextToken);
|
|
21715
|
+
return;
|
|
21716
|
+
}
|
|
21717
|
+
if (!this.options.bindings.isBound(chatId)) {
|
|
21718
|
+
const candidate = text3.trim();
|
|
21719
|
+
if (/^\d{6}$/.test(candidate)) {
|
|
21720
|
+
const bound = this.options.bindings.redeem(candidate, chatId, this.options.channel);
|
|
21721
|
+
await this.reply(chatId, bound ? this.hints.bound : this.hints.badCode, message.contextToken);
|
|
21722
|
+
return;
|
|
21723
|
+
}
|
|
21724
|
+
await this.reply(chatId, this.hints.unbound, message.contextToken);
|
|
21725
|
+
return;
|
|
21726
|
+
}
|
|
21727
|
+
try {
|
|
21728
|
+
await this.options.refresh?.();
|
|
21729
|
+
} catch (error) {
|
|
21730
|
+
this.options.onError?.(error);
|
|
21731
|
+
}
|
|
21732
|
+
const reply = await this.options.controller.execute(chatId, text3, this.options.capabilities);
|
|
21733
|
+
this.options.bindings.setFocus(chatId, this.options.controller.focus(chatId));
|
|
21734
|
+
await this.reply(chatId, reply.text, message.contextToken, reply.buttons);
|
|
21735
|
+
}
|
|
21736
|
+
async reply(chatId, text3, contextToken, buttons) {
|
|
21737
|
+
const chunks = splitForChannel(text3, this.options.capabilities.maxChars);
|
|
21738
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
21739
|
+
await this.options.transport.sendText(
|
|
21740
|
+
chatId,
|
|
21741
|
+
chunk,
|
|
21742
|
+
{
|
|
21743
|
+
...contextToken === void 0 ? {} : { contextToken },
|
|
21744
|
+
...index === chunks.length - 1 && buttons !== void 0 && buttons.length > 0 ? { buttons } : {}
|
|
21745
|
+
}
|
|
21746
|
+
);
|
|
21747
|
+
}
|
|
21748
|
+
}
|
|
21749
|
+
};
|
|
21750
|
+
|
|
21751
|
+
// src/host/remote/telegram/adapter.ts
|
|
21752
|
+
var TELEGRAM_HINTS = {
|
|
21753
|
+
unbound: "\u8FD9\u4E2A Telegram \u804A\u5929\u8FD8\u6CA1\u7ED1\u5B9A\u3002\u8BF7\u5728\u7535\u8111\u4E0A\u6253\u5F00\u300C\u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u8FDC\u7A0B\u8FDE\u63A5\u300D\u7684 Telegram \u6E20\u9053\u751F\u6210\u7ED1\u5B9A\u7801\uFF0C\u7136\u540E\u628A 6 \u4F4D\u6570\u5B57\u53D1\u7ED9\u6211\u3002",
|
|
21754
|
+
badCode: "\u7ED1\u5B9A\u7801\u65E0\u6548\u3001\u5DF2\u8FC7\u671F\uFF0C\u6216\u4E0D\u662F Telegram \u6E20\u9053\u7684\u3002\u8BF7\u91CD\u65B0\u751F\u6210\u4E00\u4E2A\u3002",
|
|
21755
|
+
unsupported: "\u76EE\u524D\u53EA\u652F\u6301\u6587\u5B57\u3002\u8BED\u97F3\u3001\u56FE\u7247\u548C\u6587\u4EF6\u8BF7\u5728\u7535\u8111\u4E0A\u67E5\u770B\u3002",
|
|
21756
|
+
bound: "\u5DF2\u7ED1\u5B9A\u3002\u56DE\u300C\u4EFB\u52A1\u300D\u67E5\u770B\u5F53\u524D\u4EFB\u52A1\u3002"
|
|
21757
|
+
};
|
|
21758
|
+
var TelegramAdapter = class {
|
|
21759
|
+
poller;
|
|
21760
|
+
constructor(options) {
|
|
21761
|
+
this.poller = new ChannelPoller({
|
|
21762
|
+
channel: "telegram",
|
|
21763
|
+
transport: {
|
|
21764
|
+
getUpdates: (cursor) => options.transport.getUpdates(options.credentials, cursor),
|
|
21765
|
+
sendText: (chatId, text3, sendOptions) => options.transport.sendText(
|
|
21766
|
+
options.credentials,
|
|
21767
|
+
chatId,
|
|
21768
|
+
text3,
|
|
21769
|
+
sendOptions
|
|
21770
|
+
),
|
|
21771
|
+
acknowledge: (callbackQueryId) => options.transport.answerCallbackQuery(
|
|
21772
|
+
options.credentials,
|
|
21773
|
+
callbackQueryId
|
|
21774
|
+
)
|
|
21775
|
+
},
|
|
21776
|
+
controller: options.controller,
|
|
21777
|
+
bindings: options.bindings,
|
|
21778
|
+
capabilities: options.capabilities,
|
|
21779
|
+
...options.cursor === void 0 ? {} : { cursor: options.cursor },
|
|
21780
|
+
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
21781
|
+
...options.onFatal === void 0 ? {} : { onFatal: options.onFatal },
|
|
21782
|
+
...options.onError === void 0 ? {} : { onError: options.onError },
|
|
21783
|
+
...options.refresh === void 0 ? {} : { refresh: options.refresh },
|
|
21784
|
+
...options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: options.emptyPageDelayMs },
|
|
21785
|
+
hints: TELEGRAM_HINTS
|
|
21786
|
+
});
|
|
21787
|
+
}
|
|
21788
|
+
stop() {
|
|
21789
|
+
this.poller.stop();
|
|
21790
|
+
}
|
|
21791
|
+
get running() {
|
|
21792
|
+
return this.poller.running;
|
|
21793
|
+
}
|
|
21794
|
+
contextFor(chatId) {
|
|
21795
|
+
return this.poller.contextFor(chatId);
|
|
21796
|
+
}
|
|
21797
|
+
run() {
|
|
21798
|
+
return this.poller.run();
|
|
21799
|
+
}
|
|
21800
|
+
};
|
|
21801
|
+
|
|
21802
|
+
// src/host/remote/telegram/transport.ts
|
|
21803
|
+
var TelegramTransportError = class extends Error {
|
|
21804
|
+
constructor(code, message, detail = {}) {
|
|
21805
|
+
super(message);
|
|
21806
|
+
this.code = code;
|
|
21807
|
+
this.detail = detail;
|
|
21808
|
+
this.name = "TelegramTransportError";
|
|
21809
|
+
}
|
|
21810
|
+
code;
|
|
21811
|
+
detail;
|
|
21812
|
+
};
|
|
21813
|
+
var DEFAULT_API_BASE = "https://api.telegram.org";
|
|
21814
|
+
var DEFAULT_POLL_TIMEOUT_MS = 35e3;
|
|
21815
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 15e3;
|
|
21816
|
+
var LONG_POLL_SECONDS = 25;
|
|
21817
|
+
var CALLBACK_DATA_MAX_BYTES = 64;
|
|
21818
|
+
function tokenIsWellFormed(token) {
|
|
21819
|
+
return token.length > 0 && !/\s/.test(token) && !token.includes("/");
|
|
21820
|
+
}
|
|
21821
|
+
function textOf3(message) {
|
|
21822
|
+
const text3 = message.text;
|
|
21823
|
+
return typeof text3 === "string" && text3.trim() !== "" ? text3 : void 0;
|
|
21824
|
+
}
|
|
21825
|
+
function itemsOf(message) {
|
|
21826
|
+
const text3 = textOf3(message);
|
|
21827
|
+
if (text3 !== void 0) return [{ kind: "text", text: text3 }];
|
|
21828
|
+
if (message.voice !== void 0) return [{ kind: "voice" }];
|
|
21829
|
+
if (message.photo !== void 0) return [{ kind: "image" }];
|
|
21830
|
+
if (message.document !== void 0) return [{ kind: "file" }];
|
|
21831
|
+
return [{ kind: "other" }];
|
|
21832
|
+
}
|
|
21833
|
+
function privateChatId(chat) {
|
|
21834
|
+
if (chat === null || typeof chat !== "object") return void 0;
|
|
21835
|
+
const record2 = chat;
|
|
21836
|
+
if (record2.type !== "private") return void 0;
|
|
21837
|
+
return typeof record2.id === "number" ? String(record2.id) : void 0;
|
|
21838
|
+
}
|
|
21839
|
+
function parseCallback(update) {
|
|
21840
|
+
const query = update.callback_query;
|
|
21841
|
+
if (query === null || typeof query !== "object") return void 0;
|
|
21842
|
+
const record2 = query;
|
|
21843
|
+
const id = typeof record2.id === "string" ? record2.id : void 0;
|
|
21844
|
+
const data = typeof record2.data === "string" ? record2.data : void 0;
|
|
21845
|
+
const message = record2.message;
|
|
21846
|
+
if (id === void 0 || data === void 0 || message === null || typeof message !== "object") {
|
|
21847
|
+
return void 0;
|
|
21848
|
+
}
|
|
21849
|
+
const messageRecord = message;
|
|
21850
|
+
const chatId = privateChatId(messageRecord.chat);
|
|
21851
|
+
if (chatId === void 0) return void 0;
|
|
21852
|
+
const from = record2.from;
|
|
21853
|
+
const fromRecord = from !== null && typeof from === "object" ? from : {};
|
|
21854
|
+
return {
|
|
21855
|
+
seq: typeof messageRecord.message_id === "number" ? messageRecord.message_id : 0,
|
|
21856
|
+
messageId: typeof messageRecord.message_id === "number" ? messageRecord.message_id : 0,
|
|
21857
|
+
fromUserId: chatId,
|
|
21858
|
+
toUserId: typeof fromRecord.id === "number" ? String(fromRecord.id) : chatId,
|
|
21859
|
+
createdAt: typeof messageRecord.date === "number" ? messageRecord.date * 1e3 : 0,
|
|
21860
|
+
items: [{ kind: "text", text: data }],
|
|
21861
|
+
callbackQueryId: id
|
|
21862
|
+
};
|
|
21863
|
+
}
|
|
21864
|
+
function parseUpdate(update) {
|
|
21865
|
+
if (update === null || typeof update !== "object") return { cursorId: 0 };
|
|
21866
|
+
const record2 = update;
|
|
21867
|
+
const updateId = typeof record2.update_id === "number" ? record2.update_id : 0;
|
|
21868
|
+
const callback = parseCallback(record2);
|
|
21869
|
+
if (callback !== void 0) return { cursorId: updateId, message: callback };
|
|
21870
|
+
const message = record2.message;
|
|
21871
|
+
if (message === null || typeof message !== "object") return { cursorId: updateId };
|
|
21872
|
+
const item = message;
|
|
21873
|
+
const chatId = privateChatId(item.chat);
|
|
21874
|
+
if (chatId === void 0) return { cursorId: updateId };
|
|
21875
|
+
const from = item.from;
|
|
21876
|
+
const fromRecord = from !== null && typeof from === "object" ? from : {};
|
|
21877
|
+
const fromId = typeof fromRecord.id === "number" ? String(fromRecord.id) : chatId;
|
|
21878
|
+
return {
|
|
21879
|
+
cursorId: updateId,
|
|
21880
|
+
message: {
|
|
21881
|
+
seq: typeof item.message_id === "number" ? item.message_id : 0,
|
|
21882
|
+
messageId: typeof item.message_id === "number" ? item.message_id : 0,
|
|
21883
|
+
fromUserId: chatId,
|
|
21884
|
+
toUserId: fromId,
|
|
21885
|
+
createdAt: typeof item.date === "number" ? item.date * 1e3 : 0,
|
|
21886
|
+
items: itemsOf(item)
|
|
21887
|
+
}
|
|
21888
|
+
};
|
|
21889
|
+
}
|
|
21890
|
+
var TelegramTransport = class {
|
|
21891
|
+
fetchImpl;
|
|
21892
|
+
apiBase;
|
|
21893
|
+
pollTimeoutMs;
|
|
21894
|
+
requestTimeoutMs;
|
|
21895
|
+
constructor(options = {}) {
|
|
21896
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
21897
|
+
this.apiBase = (options.apiBase ?? DEFAULT_API_BASE).replace(/\/$/, "");
|
|
21898
|
+
this.pollTimeoutMs = options.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
|
|
21899
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
21900
|
+
}
|
|
21901
|
+
async call(token, method, body, timeoutMs) {
|
|
21902
|
+
if (!tokenIsWellFormed(token)) {
|
|
21903
|
+
throw new ChannelAuthError("invalid-token", "Bot Token \u683C\u5F0F\u4E0D\u6B63\u786E");
|
|
21904
|
+
}
|
|
21905
|
+
const controller = new AbortController();
|
|
21906
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
21907
|
+
let response;
|
|
21908
|
+
try {
|
|
21909
|
+
response = await this.fetchImpl(`${this.apiBase}/bot${token}/${method}`, {
|
|
21910
|
+
method: "POST",
|
|
21911
|
+
headers: { "content-type": "application/json" },
|
|
21912
|
+
body: JSON.stringify(body),
|
|
21913
|
+
signal: controller.signal
|
|
21914
|
+
});
|
|
21915
|
+
} catch (error) {
|
|
21916
|
+
if (controller.signal.aborted) throw new TelegramTransportError("timeout", "Telegram \u8BF7\u6C42\u8D85\u65F6");
|
|
21917
|
+
throw new TelegramTransportError("network-error", "\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE Telegram");
|
|
21918
|
+
} finally {
|
|
21919
|
+
clearTimeout(timer);
|
|
21920
|
+
}
|
|
21921
|
+
const text3 = await response.text();
|
|
21922
|
+
let parsed;
|
|
21923
|
+
try {
|
|
21924
|
+
parsed = JSON.parse(text3);
|
|
21925
|
+
} catch {
|
|
21926
|
+
throw new TelegramTransportError("invalid-response", "Telegram \u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94", {
|
|
21927
|
+
status: response.status
|
|
21928
|
+
});
|
|
21929
|
+
}
|
|
21930
|
+
if (parsed.ok === true) return parsed.result;
|
|
21931
|
+
const status = parsed.error_code ?? response.status;
|
|
21932
|
+
const retryAfter = parsed.parameters?.retry_after;
|
|
21933
|
+
if (status === 401 || status === 403) {
|
|
21934
|
+
throw new ChannelAuthError("unauthorized", "Bot Token \u65E0\u6548\u6216\u5DF2\u88AB\u64A4\u9500\uFF0C\u8BF7\u91CD\u65B0\u586B\u5199");
|
|
21935
|
+
}
|
|
21936
|
+
if (status === 409) {
|
|
21937
|
+
throw new ChannelAuthError("conflict", "\u8FD9\u4E2A Bot \u5DF2\u5728\u522B\u5904\u8F6E\u8BE2\uFF0C\u8BF7\u5148\u505C\u6389\u53E6\u4E00\u4E2A\u5B9E\u4F8B");
|
|
21938
|
+
}
|
|
21939
|
+
if (status === 429) {
|
|
21940
|
+
throw new TelegramTransportError("rate-limited", "Telegram \u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41", {
|
|
21941
|
+
status,
|
|
21942
|
+
...typeof retryAfter === "number" ? { retryAfterMs: retryAfter * 1e3 } : {}
|
|
21943
|
+
});
|
|
21944
|
+
}
|
|
21945
|
+
throw new TelegramTransportError("rejected", parsed.description ?? "Telegram \u62D2\u7EDD\u4E86\u8BF7\u6C42", { status });
|
|
21946
|
+
}
|
|
21947
|
+
/** Confirm the token and learn the bot identity. */
|
|
21948
|
+
async validate(credentials) {
|
|
21949
|
+
const result = await this.call(credentials.token, "getMe", {}, this.requestTimeoutMs);
|
|
21950
|
+
const record2 = result !== null && typeof result === "object" ? result : {};
|
|
21951
|
+
const id = typeof record2.id === "number" ? String(record2.id) : void 0;
|
|
21952
|
+
if (id === void 0) throw new TelegramTransportError("invalid-response", "Telegram \u6CA1\u6709\u8FD4\u56DE Bot \u8EAB\u4EFD");
|
|
21953
|
+
return {
|
|
21954
|
+
id,
|
|
21955
|
+
...typeof record2.username === "string" && record2.username !== "" ? { username: record2.username } : {}
|
|
21956
|
+
};
|
|
21957
|
+
}
|
|
21958
|
+
/** Long poll. The cursor is the next update_offset; empty starts from now. */
|
|
21959
|
+
async getUpdates(credentials, cursor = "") {
|
|
21960
|
+
const body = {
|
|
21961
|
+
timeout: LONG_POLL_SECONDS,
|
|
21962
|
+
allowed_updates: ["message", "callback_query"]
|
|
21963
|
+
};
|
|
21964
|
+
if (cursor !== "") body.offset = Number(cursor);
|
|
21965
|
+
const result = await this.call(credentials.token, "getUpdates", body, this.pollTimeoutMs);
|
|
21966
|
+
const updates = Array.isArray(result) ? result : [];
|
|
21967
|
+
const messages = [];
|
|
21968
|
+
let next = cursor === "" ? 0 : Number(cursor);
|
|
21969
|
+
for (const update of updates) {
|
|
21970
|
+
const parsed = parseUpdate(update);
|
|
21971
|
+
next = Math.max(next, parsed.cursorId + 1);
|
|
21972
|
+
if (parsed.message !== void 0) messages.push(parsed.message);
|
|
21973
|
+
}
|
|
21974
|
+
return { cursor: next === 0 ? cursor : String(next), messages };
|
|
21975
|
+
}
|
|
21976
|
+
async sendText(credentials, chatId, text3, options = {}) {
|
|
21977
|
+
if (chatId === "") throw new TelegramTransportError("invalid-recipient", "\u7F3A\u5C11\u63A5\u6536\u8005");
|
|
21978
|
+
if (text3.trim() === "") throw new TelegramTransportError("empty-text", "\u8981\u53D1\u9001\u7684\u6587\u672C\u4E3A\u7A7A");
|
|
21979
|
+
const body = {
|
|
21980
|
+
chat_id: chatId,
|
|
21981
|
+
text: text3,
|
|
21982
|
+
disable_web_page_preview: true
|
|
21983
|
+
};
|
|
21984
|
+
const buttons = (options.buttons ?? []).filter((button) => Buffer.byteLength(button.command, "utf8") <= CALLBACK_DATA_MAX_BYTES);
|
|
21985
|
+
if (buttons.length > 0) {
|
|
21986
|
+
const rows = [];
|
|
21987
|
+
for (let index = 0; index < buttons.length; index += 2) {
|
|
21988
|
+
rows.push(buttons.slice(index, index + 2).map((button) => ({
|
|
21989
|
+
text: button.label,
|
|
21990
|
+
callback_data: button.command
|
|
21991
|
+
})));
|
|
21992
|
+
}
|
|
21993
|
+
body.reply_markup = { inline_keyboard: rows };
|
|
21994
|
+
}
|
|
21995
|
+
const result = await this.call(credentials.token, "sendMessage", body, this.requestTimeoutMs);
|
|
21996
|
+
const record2 = result !== null && typeof result === "object" ? result : {};
|
|
21997
|
+
return typeof record2.message_id === "number" ? record2.message_id : 0;
|
|
21998
|
+
}
|
|
21999
|
+
/** Stop the spinner on a tapped inline button. */
|
|
22000
|
+
async answerCallbackQuery(credentials, callbackQueryId) {
|
|
22001
|
+
await this.call(
|
|
22002
|
+
credentials.token,
|
|
22003
|
+
"answerCallbackQuery",
|
|
22004
|
+
{ callback_query_id: callbackQueryId },
|
|
22005
|
+
this.requestTimeoutMs
|
|
22006
|
+
);
|
|
22007
|
+
}
|
|
22008
|
+
};
|
|
22009
|
+
|
|
22010
|
+
// src/host/remote/telegram/channel.ts
|
|
22011
|
+
function messageOf(error) {
|
|
22012
|
+
return error instanceof Error ? error.message : String(error);
|
|
22013
|
+
}
|
|
22014
|
+
var TelegramChannel = class {
|
|
22015
|
+
constructor(options) {
|
|
22016
|
+
this.options = options;
|
|
22017
|
+
this.transport = options.createTransport?.() ?? new TelegramTransport();
|
|
22018
|
+
}
|
|
22019
|
+
options;
|
|
22020
|
+
id = "telegram";
|
|
22021
|
+
transport;
|
|
22022
|
+
adapter;
|
|
22023
|
+
cursor;
|
|
22024
|
+
credentialsValue;
|
|
22025
|
+
phaseValue = "off";
|
|
22026
|
+
errorValue;
|
|
22027
|
+
generation = 0;
|
|
22028
|
+
get running() {
|
|
22029
|
+
return this.phaseValue === "running";
|
|
22030
|
+
}
|
|
22031
|
+
status() {
|
|
22032
|
+
const devices = this.options.bindings.list().filter((binding) => binding.channel === this.id).map((binding) => ({ chatId: binding.chatId, boundAt: binding.boundAt }));
|
|
22033
|
+
const connected = this.phaseValue === "running";
|
|
22034
|
+
const failed = this.phaseValue === "failed";
|
|
22035
|
+
return {
|
|
22036
|
+
id: this.id,
|
|
22037
|
+
phase: this.phaseValue,
|
|
22038
|
+
login: {
|
|
22039
|
+
phase: connected ? "connected" : failed ? "failed" : "idle",
|
|
22040
|
+
status: connected ? "connected" : failed ? "failed" : "idle",
|
|
22041
|
+
...this.errorValue === void 0 ? {} : { error: this.errorValue }
|
|
22042
|
+
},
|
|
22043
|
+
devices,
|
|
22044
|
+
...this.credentialsValue?.username === void 0 ? this.credentialsValue?.botId === void 0 ? {} : { handle: this.credentialsValue.botId } : { handle: `@${this.credentialsValue.username}` },
|
|
22045
|
+
...this.errorValue === void 0 ? {} : { error: this.errorValue }
|
|
22046
|
+
};
|
|
22047
|
+
}
|
|
22048
|
+
async start() {
|
|
22049
|
+
if (this.phaseValue === "running" || this.phaseValue === "unbound") return;
|
|
22050
|
+
const stored = await this.options.credentials.load().catch(() => void 0);
|
|
22051
|
+
if (stored === void 0) {
|
|
22052
|
+
this.phaseValue = "unbound";
|
|
22053
|
+
return;
|
|
22054
|
+
}
|
|
22055
|
+
this.connectStored(stored);
|
|
22056
|
+
}
|
|
22057
|
+
/** Validate and switch to a new bot token. */
|
|
22058
|
+
async connect(token) {
|
|
22059
|
+
const trimmed = token.trim();
|
|
22060
|
+
if (trimmed === "") return { ok: false, error: "\u8BF7\u586B\u5199 Bot Token" };
|
|
22061
|
+
const generation = this.generation;
|
|
22062
|
+
let identity;
|
|
22063
|
+
try {
|
|
22064
|
+
identity = await this.transport.validate({ token: trimmed });
|
|
22065
|
+
} catch (error) {
|
|
22066
|
+
return { ok: false, error: messageOf(error) };
|
|
22067
|
+
}
|
|
22068
|
+
if (this.generation !== generation) return { ok: false, error: "\u8FDE\u63A5\u5DF2\u53D6\u6D88" };
|
|
22069
|
+
const credentials = {
|
|
22070
|
+
token: trimmed,
|
|
22071
|
+
botId: identity.id,
|
|
22072
|
+
...identity.username === void 0 ? {} : { username: identity.username }
|
|
22073
|
+
};
|
|
22074
|
+
try {
|
|
22075
|
+
await this.options.credentials.save(credentials);
|
|
22076
|
+
} catch (error) {
|
|
22077
|
+
return { ok: false, error: messageOf(error) };
|
|
22078
|
+
}
|
|
22079
|
+
if (this.generation !== generation) return { ok: false, error: "\u8FDE\u63A5\u5DF2\u53D6\u6D88" };
|
|
22080
|
+
this.connectStored(credentials);
|
|
22081
|
+
return { ok: true, ...identity.username === void 0 ? {} : { username: identity.username } };
|
|
22082
|
+
}
|
|
22083
|
+
async logout() {
|
|
22084
|
+
this.generation += 1;
|
|
22085
|
+
this.adapter?.stop();
|
|
22086
|
+
this.adapter = void 0;
|
|
22087
|
+
this.credentialsValue = void 0;
|
|
22088
|
+
this.errorValue = void 0;
|
|
22089
|
+
await this.options.credentials.clear().catch((error) => {
|
|
22090
|
+
this.options.onError?.(error);
|
|
22091
|
+
});
|
|
22092
|
+
if (this.phaseValue !== "off") this.phaseValue = "unbound";
|
|
22093
|
+
}
|
|
22094
|
+
stop() {
|
|
22095
|
+
this.generation += 1;
|
|
22096
|
+
this.adapter?.stop();
|
|
22097
|
+
this.adapter = void 0;
|
|
22098
|
+
this.cursor = void 0;
|
|
22099
|
+
this.credentialsValue = void 0;
|
|
22100
|
+
this.phaseValue = "off";
|
|
22101
|
+
}
|
|
22102
|
+
async send(chatId, text3, buttons) {
|
|
22103
|
+
const credentials = this.credentialsValue;
|
|
22104
|
+
if (this.phaseValue !== "running" || credentials === void 0) return;
|
|
22105
|
+
const chunks = splitForChannel(text3, this.options.capabilities.maxChars);
|
|
22106
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
22107
|
+
await this.transport.sendText(
|
|
22108
|
+
credentials,
|
|
22109
|
+
chatId,
|
|
22110
|
+
chunk,
|
|
22111
|
+
index === chunks.length - 1 && buttons !== void 0 && buttons.length > 0 ? { buttons } : {}
|
|
22112
|
+
);
|
|
22113
|
+
}
|
|
22114
|
+
}
|
|
22115
|
+
contextFor(_chatId) {
|
|
22116
|
+
return void 0;
|
|
22117
|
+
}
|
|
22118
|
+
connectStored(credentials) {
|
|
22119
|
+
this.cursor ??= createCursorStore({ filePath: join30(this.options.rootDir, "telegram-cursor.json") });
|
|
22120
|
+
this.credentialsValue = credentials;
|
|
22121
|
+
this.errorValue = void 0;
|
|
22122
|
+
this.adapter?.stop();
|
|
22123
|
+
const adapter = new TelegramAdapter({
|
|
22124
|
+
transport: this.transport,
|
|
22125
|
+
credentials,
|
|
22126
|
+
controller: this.options.controller,
|
|
22127
|
+
bindings: this.options.bindings,
|
|
22128
|
+
capabilities: this.options.capabilities,
|
|
22129
|
+
cursor: this.cursor,
|
|
22130
|
+
refresh: this.options.refresh,
|
|
22131
|
+
...this.options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: this.options.emptyPageDelayMs },
|
|
22132
|
+
onError: (error) => this.options.onError?.(error),
|
|
22133
|
+
onFatal: (error) => {
|
|
22134
|
+
this.phaseValue = "failed";
|
|
22135
|
+
this.errorValue = messageOf(error);
|
|
22136
|
+
}
|
|
22137
|
+
});
|
|
22138
|
+
this.adapter = adapter;
|
|
22139
|
+
this.phaseValue = "running";
|
|
22140
|
+
void adapter.run();
|
|
22141
|
+
}
|
|
22142
|
+
};
|
|
22143
|
+
|
|
22144
|
+
// src/host/remote/telegram/credentials.ts
|
|
22145
|
+
var CREDENTIAL_REF = "DSH_AGENT_ENHANCER_TELEGRAM";
|
|
22146
|
+
function parse(value) {
|
|
22147
|
+
let parsed;
|
|
22148
|
+
try {
|
|
22149
|
+
parsed = JSON.parse(value);
|
|
22150
|
+
} catch {
|
|
22151
|
+
return void 0;
|
|
22152
|
+
}
|
|
22153
|
+
if (parsed === null || typeof parsed !== "object") return void 0;
|
|
22154
|
+
const record2 = parsed;
|
|
22155
|
+
if (typeof record2.token !== "string" || record2.token.trim() === "") return void 0;
|
|
22156
|
+
return {
|
|
22157
|
+
token: record2.token,
|
|
22158
|
+
...typeof record2.botId === "string" && record2.botId !== "" ? { botId: record2.botId } : {},
|
|
22159
|
+
...typeof record2.username === "string" && record2.username !== "" ? { username: record2.username } : {}
|
|
22160
|
+
};
|
|
22161
|
+
}
|
|
22162
|
+
function provider(ctx) {
|
|
22163
|
+
let service;
|
|
22164
|
+
try {
|
|
22165
|
+
service = ctx.get("credentials");
|
|
22166
|
+
} catch {
|
|
22167
|
+
return void 0;
|
|
22168
|
+
}
|
|
22169
|
+
if (service === void 0 || service === null || typeof service !== "object") return void 0;
|
|
22170
|
+
const candidate = service;
|
|
22171
|
+
if (typeof candidate.resolve !== "function" || typeof candidate.set !== "function") return void 0;
|
|
22172
|
+
return service;
|
|
22173
|
+
}
|
|
22174
|
+
function createTelegramCredentialStore(ctx) {
|
|
22175
|
+
if (provider(ctx) === void 0) {
|
|
22176
|
+
return {
|
|
22177
|
+
async load() {
|
|
22178
|
+
return void 0;
|
|
22179
|
+
},
|
|
22180
|
+
async save() {
|
|
22181
|
+
throw new Error("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B\u51ED\u636E\u670D\u52A1\uFF0C\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58 Telegram Bot Token");
|
|
22182
|
+
},
|
|
22183
|
+
async clear() {
|
|
22184
|
+
}
|
|
22185
|
+
};
|
|
22186
|
+
}
|
|
22187
|
+
return {
|
|
22188
|
+
async load() {
|
|
22189
|
+
const resolved = await provider(ctx)?.resolve(CREDENTIAL_REF);
|
|
22190
|
+
if (resolved === void 0) return void 0;
|
|
22191
|
+
return parse(resolved.value);
|
|
22192
|
+
},
|
|
22193
|
+
async save(credentials) {
|
|
22194
|
+
const service = provider(ctx);
|
|
22195
|
+
if (service === void 0) throw new Error("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B\u51ED\u636E\u670D\u52A1");
|
|
22196
|
+
const payload = { token: credentials.token };
|
|
22197
|
+
if (credentials.botId !== void 0) payload.botId = credentials.botId;
|
|
22198
|
+
if (credentials.username !== void 0) payload.username = credentials.username;
|
|
22199
|
+
await service.set(CREDENTIAL_REF, JSON.stringify(payload));
|
|
22200
|
+
},
|
|
22201
|
+
async clear() {
|
|
22202
|
+
await provider(ctx)?.unset(CREDENTIAL_REF);
|
|
22203
|
+
}
|
|
22204
|
+
};
|
|
22205
|
+
}
|
|
22206
|
+
|
|
22207
|
+
// src/host/remote/feishu/adapter.ts
|
|
22208
|
+
var FEISHU_HINTS = {
|
|
22209
|
+
unbound: "\u8FD9\u4E2A\u98DE\u4E66\u804A\u5929\u8FD8\u6CA1\u7ED1\u5B9A\u3002\u8BF7\u5728\u7535\u8111\u4E0A\u6253\u5F00\u300C\u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u8FDC\u7A0B\u8FDE\u63A5\u300D\u7684\u98DE\u4E66\u6E20\u9053\u751F\u6210\u7ED1\u5B9A\u7801\uFF0C\u7136\u540E\u628A 6 \u4F4D\u6570\u5B57\u53D1\u7ED9\u6211\u3002",
|
|
22210
|
+
badCode: "\u7ED1\u5B9A\u7801\u65E0\u6548\u3001\u5DF2\u8FC7\u671F\uFF0C\u6216\u4E0D\u662F\u98DE\u4E66\u6E20\u9053\u7684\u3002\u8BF7\u91CD\u65B0\u751F\u6210\u4E00\u4E2A\u3002",
|
|
22211
|
+
unsupported: "\u76EE\u524D\u53EA\u652F\u6301\u6587\u5B57\u3002\u8BED\u97F3\u3001\u56FE\u7247\u548C\u6587\u4EF6\u8BF7\u5728\u7535\u8111\u4E0A\u67E5\u770B\u3002",
|
|
22212
|
+
bound: "\u5DF2\u7ED1\u5B9A\u3002\u56DE\u300C\u4EFB\u52A1\u300D\u67E5\u770B\u5F53\u524D\u4EFB\u52A1\u3002"
|
|
22213
|
+
};
|
|
22214
|
+
var FeishuAdapter = class {
|
|
22215
|
+
poller;
|
|
22216
|
+
constructor(options) {
|
|
22217
|
+
this.poller = new ChannelPoller({
|
|
22218
|
+
channel: "feishu",
|
|
22219
|
+
transport: {
|
|
22220
|
+
getUpdates: (cursor) => options.transport.getUpdates(cursor),
|
|
22221
|
+
sendText: (chatId, text3, sendOptions) => options.transport.sendText(
|
|
22222
|
+
options.credentials,
|
|
22223
|
+
chatId,
|
|
22224
|
+
text3,
|
|
22225
|
+
sendOptions
|
|
22226
|
+
)
|
|
22227
|
+
},
|
|
22228
|
+
controller: options.controller,
|
|
22229
|
+
bindings: options.bindings,
|
|
22230
|
+
capabilities: options.capabilities,
|
|
22231
|
+
...options.cursor === void 0 ? {} : { cursor: options.cursor },
|
|
22232
|
+
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
22233
|
+
...options.onFatal === void 0 ? {} : { onFatal: options.onFatal },
|
|
22234
|
+
...options.onError === void 0 ? {} : { onError: options.onError },
|
|
22235
|
+
...options.refresh === void 0 ? {} : { refresh: options.refresh },
|
|
22236
|
+
...options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: options.emptyPageDelayMs },
|
|
22237
|
+
hints: FEISHU_HINTS
|
|
22238
|
+
});
|
|
22239
|
+
}
|
|
22240
|
+
stop() {
|
|
22241
|
+
this.poller.stop();
|
|
22242
|
+
}
|
|
22243
|
+
get running() {
|
|
22244
|
+
return this.poller.running;
|
|
22245
|
+
}
|
|
22246
|
+
run() {
|
|
22247
|
+
return this.poller.run();
|
|
22248
|
+
}
|
|
22249
|
+
};
|
|
22250
|
+
|
|
22251
|
+
// src/host/remote/feishu/transport.ts
|
|
22252
|
+
var FeishuTransportError = class extends Error {
|
|
22253
|
+
constructor(code, message, detail = {}) {
|
|
22254
|
+
super(message);
|
|
22255
|
+
this.code = code;
|
|
22256
|
+
this.detail = detail;
|
|
22257
|
+
this.name = "FeishuTransportError";
|
|
22258
|
+
}
|
|
22259
|
+
code;
|
|
22260
|
+
detail;
|
|
22261
|
+
};
|
|
22262
|
+
var DEFAULT_API_BASE2 = "https://open.feishu.cn";
|
|
22263
|
+
var DEFAULT_REQUEST_TIMEOUT_MS2 = 15e3;
|
|
22264
|
+
var DEFAULT_WAIT_TIMEOUT_MS = 2e4;
|
|
22265
|
+
var SEEN_LIMIT = 200;
|
|
22266
|
+
var AUTH_CODES = /* @__PURE__ */ new Set([99991661, 99991663, 99991668, 10003, 10014]);
|
|
22267
|
+
function sdkLoader() {
|
|
22268
|
+
return import("@larksuiteoapi/node-sdk").then((module) => module);
|
|
22269
|
+
}
|
|
22270
|
+
function textOf4(value) {
|
|
22271
|
+
return typeof value === "string" && value.trim() !== "" ? value : void 0;
|
|
22272
|
+
}
|
|
22273
|
+
function textItems(messageType, content) {
|
|
22274
|
+
let parsed;
|
|
22275
|
+
try {
|
|
22276
|
+
parsed = JSON.parse(content);
|
|
22277
|
+
} catch {
|
|
22278
|
+
return [{ kind: "other" }];
|
|
22279
|
+
}
|
|
22280
|
+
if (parsed === null || typeof parsed !== "object") return [{ kind: "other" }];
|
|
22281
|
+
if (messageType === "text") {
|
|
22282
|
+
const text3 = textOf4(parsed.text);
|
|
22283
|
+
return text3 === void 0 ? [{ kind: "other" }] : [{ kind: "text", text: text3 }];
|
|
22284
|
+
}
|
|
22285
|
+
if (messageType === "post") {
|
|
22286
|
+
const record2 = parsed;
|
|
22287
|
+
const lines = [];
|
|
22288
|
+
const title = textOf4(record2.title);
|
|
22289
|
+
if (title !== void 0) lines.push(title);
|
|
22290
|
+
if (Array.isArray(record2.content)) {
|
|
22291
|
+
for (const paragraph of record2.content) {
|
|
22292
|
+
if (!Array.isArray(paragraph)) continue;
|
|
22293
|
+
const pieces = [];
|
|
22294
|
+
for (const element of paragraph) {
|
|
22295
|
+
if (element === null || typeof element !== "object") continue;
|
|
22296
|
+
const text4 = textOf4(element.text);
|
|
22297
|
+
if (text4 !== void 0) pieces.push(text4);
|
|
22298
|
+
}
|
|
22299
|
+
if (pieces.length > 0) lines.push(pieces.join(""));
|
|
22300
|
+
}
|
|
22301
|
+
}
|
|
22302
|
+
const text3 = lines.join("\n").trim();
|
|
22303
|
+
return text3 === "" ? [{ kind: "other" }] : [{ kind: "text", text: text3 }];
|
|
22304
|
+
}
|
|
22305
|
+
if (messageType === "audio") return [{ kind: "voice" }];
|
|
22306
|
+
if (messageType === "image") return [{ kind: "image" }];
|
|
22307
|
+
if (messageType === "file" || messageType === "media") return [{ kind: "file" }];
|
|
22308
|
+
return [{ kind: "other" }];
|
|
22309
|
+
}
|
|
22310
|
+
function recordOf(value) {
|
|
22311
|
+
return value !== null && typeof value === "object" ? value : void 0;
|
|
22312
|
+
}
|
|
22313
|
+
function parseMessageEvent(data) {
|
|
22314
|
+
const root = recordOf(data);
|
|
22315
|
+
if (root === void 0) return void 0;
|
|
22316
|
+
const sender = recordOf(root.sender);
|
|
22317
|
+
if (sender?.sender_type === "app") return void 0;
|
|
22318
|
+
const message = recordOf(root.message);
|
|
22319
|
+
if (message === void 0) return void 0;
|
|
22320
|
+
if (message.chat_type !== "p2p") return void 0;
|
|
22321
|
+
const chatId = textOf4(message.chat_id);
|
|
22322
|
+
const messageId = textOf4(message.message_id);
|
|
22323
|
+
if (chatId === void 0) return void 0;
|
|
22324
|
+
const messageType = typeof message.message_type === "string" ? message.message_type : "unknown";
|
|
22325
|
+
const content = typeof message.content === "string" ? message.content : "";
|
|
22326
|
+
const senderId = recordOf(sender?.sender_id);
|
|
22327
|
+
const created = Number(message.create_time);
|
|
22328
|
+
return {
|
|
22329
|
+
seq: 0,
|
|
22330
|
+
messageId: 0,
|
|
22331
|
+
fromUserId: chatId,
|
|
22332
|
+
toUserId: textOf4(senderId?.open_id) ?? "",
|
|
22333
|
+
createdAt: Number.isFinite(created) && created > 0 ? created : Date.now(),
|
|
22334
|
+
items: textItems(messageType, content),
|
|
22335
|
+
...messageId === void 0 ? {} : { contextToken: messageId }
|
|
22336
|
+
};
|
|
22337
|
+
}
|
|
22338
|
+
function parseCardAction(data) {
|
|
22339
|
+
const root = recordOf(data);
|
|
22340
|
+
if (root === void 0) return void 0;
|
|
22341
|
+
const context = recordOf(root.context);
|
|
22342
|
+
const chatId = textOf4(context?.open_chat_id) ?? textOf4(root.open_chat_id);
|
|
22343
|
+
const action = recordOf(root.action);
|
|
22344
|
+
const value = recordOf(action?.value);
|
|
22345
|
+
const command = textOf4(value?.command);
|
|
22346
|
+
if (chatId === void 0 || command === void 0) return void 0;
|
|
22347
|
+
const operator = recordOf(root.operator);
|
|
22348
|
+
return {
|
|
22349
|
+
seq: 0,
|
|
22350
|
+
messageId: 0,
|
|
22351
|
+
fromUserId: chatId,
|
|
22352
|
+
toUserId: textOf4(operator?.open_id) ?? "",
|
|
22353
|
+
createdAt: Date.now(),
|
|
22354
|
+
items: [{ kind: "text", text: command }]
|
|
22355
|
+
};
|
|
22356
|
+
}
|
|
22357
|
+
var FeishuTransport = class {
|
|
22358
|
+
fetchImpl;
|
|
22359
|
+
apiBase;
|
|
22360
|
+
requestTimeoutMs;
|
|
22361
|
+
waitTimeoutMs;
|
|
22362
|
+
loadSdk;
|
|
22363
|
+
tokens = /* @__PURE__ */ new Map();
|
|
22364
|
+
queue = [];
|
|
22365
|
+
seen = /* @__PURE__ */ new Set();
|
|
22366
|
+
socket;
|
|
22367
|
+
socketError;
|
|
22368
|
+
waiter;
|
|
22369
|
+
constructor(options = {}) {
|
|
22370
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
22371
|
+
this.apiBase = (options.apiBase ?? DEFAULT_API_BASE2).replace(/\/$/, "");
|
|
22372
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS2;
|
|
22373
|
+
this.waitTimeoutMs = options.waitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
22374
|
+
this.loadSdk = options.loadSdk ?? sdkLoader;
|
|
22375
|
+
}
|
|
22376
|
+
get lastSocketError() {
|
|
22377
|
+
return this.socketError;
|
|
22378
|
+
}
|
|
22379
|
+
async call(path, init) {
|
|
22380
|
+
const controller = new AbortController();
|
|
22381
|
+
const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs);
|
|
22382
|
+
let response;
|
|
22383
|
+
try {
|
|
22384
|
+
response = await this.fetchImpl(`${this.apiBase}${path}`, {
|
|
22385
|
+
method: init.method,
|
|
22386
|
+
headers: {
|
|
22387
|
+
"content-type": "application/json",
|
|
22388
|
+
...init.token === void 0 ? {} : { authorization: `Bearer ${init.token}` }
|
|
22389
|
+
},
|
|
22390
|
+
...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
|
|
22391
|
+
signal: controller.signal
|
|
22392
|
+
});
|
|
22393
|
+
} catch {
|
|
22394
|
+
if (controller.signal.aborted) throw new FeishuTransportError("timeout", "\u98DE\u4E66\u8BF7\u6C42\u8D85\u65F6");
|
|
22395
|
+
throw new FeishuTransportError("network-error", "\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u98DE\u4E66");
|
|
22396
|
+
} finally {
|
|
22397
|
+
clearTimeout(timer);
|
|
22398
|
+
}
|
|
22399
|
+
const text3 = await response.text();
|
|
22400
|
+
let parsed;
|
|
22401
|
+
try {
|
|
22402
|
+
parsed = JSON.parse(text3);
|
|
22403
|
+
} catch {
|
|
22404
|
+
throw new FeishuTransportError("invalid-response", "\u98DE\u4E66\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94", {
|
|
22405
|
+
status: response.status
|
|
22406
|
+
});
|
|
22407
|
+
}
|
|
22408
|
+
if (response.status === 401 || typeof parsed.code === "number" && AUTH_CODES.has(parsed.code)) {
|
|
22409
|
+
throw new ChannelAuthError("unauthorized", "\u98DE\u4E66 App ID \u6216 App Secret \u65E0\u6548\uFF0C\u6216\u5E94\u7528\u5DF2\u505C\u7528");
|
|
22410
|
+
}
|
|
22411
|
+
if (response.status === 429 || parsed.code === 99991400) {
|
|
22412
|
+
throw new FeishuTransportError("rate-limited", "\u98DE\u4E66\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41", {
|
|
22413
|
+
status: response.status,
|
|
22414
|
+
retryAfterMs: 2e3
|
|
22415
|
+
});
|
|
22416
|
+
}
|
|
22417
|
+
if (parsed.code !== void 0 && parsed.code !== 0) {
|
|
22418
|
+
throw new FeishuTransportError(
|
|
22419
|
+
"rejected",
|
|
22420
|
+
parsed.msg === void 0 || parsed.msg === "" ? `\u98DE\u4E66\u62D2\u7EDD\u4E86\u8BF7\u6C42\uFF08${parsed.code}\uFF09` : parsed.msg,
|
|
22421
|
+
{ status: response.status }
|
|
22422
|
+
);
|
|
22423
|
+
}
|
|
22424
|
+
if (!response.ok) {
|
|
22425
|
+
throw new FeishuTransportError("rejected", `\u98DE\u4E66\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${response.status}\uFF09`, {
|
|
22426
|
+
status: response.status
|
|
22427
|
+
});
|
|
22428
|
+
}
|
|
22429
|
+
return parsed;
|
|
22430
|
+
}
|
|
22431
|
+
async tenantToken(credentials) {
|
|
22432
|
+
const key = `${credentials.appId}
|
|
22433
|
+
${credentials.appSecret}`;
|
|
22434
|
+
const cached = this.tokens.get(key);
|
|
22435
|
+
if (cached !== void 0 && cached.expiresAt > Date.now() + 6e4) return cached.token;
|
|
22436
|
+
const response = await this.call("/open-apis/auth/v3/tenant_access_token/internal", {
|
|
22437
|
+
method: "POST",
|
|
22438
|
+
body: { app_id: credentials.appId, app_secret: credentials.appSecret }
|
|
22439
|
+
});
|
|
22440
|
+
const token = response.tenant_access_token;
|
|
22441
|
+
if (token === void 0 || token === "") {
|
|
22442
|
+
throw new FeishuTransportError("invalid-response", "\u98DE\u4E66\u6CA1\u6709\u8FD4\u56DE tenant_access_token");
|
|
22443
|
+
}
|
|
22444
|
+
const expire = typeof response.expire === "number" && response.expire > 0 ? response.expire : 7200;
|
|
22445
|
+
this.tokens.set(key, { token, expiresAt: Date.now() + expire * 1e3 });
|
|
22446
|
+
return token;
|
|
22447
|
+
}
|
|
22448
|
+
/** Confirm the credentials and learn the bot name. */
|
|
22449
|
+
async validate(credentials) {
|
|
22450
|
+
const token = await this.tenantToken(credentials);
|
|
22451
|
+
const info = await this.call("/open-apis/bot/v3/info", { method: "GET", token });
|
|
22452
|
+
const name2 = textOf4(info.bot?.app_name);
|
|
22453
|
+
return name2 === void 0 ? {} : { name: name2 };
|
|
22454
|
+
}
|
|
22455
|
+
/**
|
|
22456
|
+
* Open the long connection. Events arrive on the SDK's socket and wait in the
|
|
22457
|
+
* queue for `getUpdates`.
|
|
22458
|
+
*/
|
|
22459
|
+
async start(credentials) {
|
|
22460
|
+
if (this.socket !== void 0) return;
|
|
22461
|
+
const sdk = await this.loadSdk();
|
|
22462
|
+
const loggerLevel = sdk.LoggerLevel?.error;
|
|
22463
|
+
const dispatcher = new sdk.EventDispatcher(
|
|
22464
|
+
loggerLevel === void 0 ? {} : { loggerLevel }
|
|
22465
|
+
);
|
|
22466
|
+
dispatcher.register({
|
|
22467
|
+
"im.message.receive_v1": (data) => {
|
|
22468
|
+
const message = parseMessageEvent(data);
|
|
22469
|
+
if (message !== void 0) this.push(message);
|
|
22470
|
+
return void 0;
|
|
22471
|
+
},
|
|
22472
|
+
"card.action.trigger": (data) => {
|
|
22473
|
+
const message = parseCardAction(data);
|
|
22474
|
+
if (message !== void 0) this.push(message);
|
|
22475
|
+
return { toast: { type: "info", content: "\u5DF2\u6536\u5230" } };
|
|
22476
|
+
}
|
|
22477
|
+
});
|
|
22478
|
+
const socket = new sdk.WSClient({
|
|
22479
|
+
appId: credentials.appId,
|
|
22480
|
+
appSecret: credentials.appSecret,
|
|
22481
|
+
autoReconnect: true,
|
|
22482
|
+
...loggerLevel === void 0 ? {} : { loggerLevel },
|
|
22483
|
+
onReady: () => {
|
|
22484
|
+
this.socketError = void 0;
|
|
22485
|
+
},
|
|
22486
|
+
onError: (error) => {
|
|
22487
|
+
this.socketError = error.message;
|
|
22488
|
+
}
|
|
22489
|
+
});
|
|
22490
|
+
this.socket = socket;
|
|
22491
|
+
try {
|
|
22492
|
+
await socket.start({ eventDispatcher: dispatcher });
|
|
22493
|
+
} catch (error) {
|
|
22494
|
+
if (this.socket === socket) this.socket = void 0;
|
|
22495
|
+
socket.close({ force: true });
|
|
22496
|
+
throw error;
|
|
22497
|
+
}
|
|
22498
|
+
}
|
|
22499
|
+
stop() {
|
|
22500
|
+
const socket = this.socket;
|
|
22501
|
+
this.socket = void 0;
|
|
22502
|
+
this.queue.length = 0;
|
|
22503
|
+
this.wake();
|
|
22504
|
+
if (socket !== void 0) {
|
|
22505
|
+
try {
|
|
22506
|
+
socket.close({ force: true });
|
|
22507
|
+
} catch {
|
|
22508
|
+
}
|
|
22509
|
+
}
|
|
22510
|
+
}
|
|
22511
|
+
push(message) {
|
|
22512
|
+
const key = message.contextToken;
|
|
22513
|
+
if (key !== void 0) {
|
|
22514
|
+
if (this.seen.has(key)) return;
|
|
22515
|
+
this.seen.add(key);
|
|
22516
|
+
if (this.seen.size > SEEN_LIMIT) {
|
|
22517
|
+
const oldest = this.seen.values().next().value;
|
|
22518
|
+
if (oldest !== void 0) this.seen.delete(oldest);
|
|
22519
|
+
}
|
|
22520
|
+
}
|
|
22521
|
+
this.queue.push(message);
|
|
22522
|
+
this.wake();
|
|
22523
|
+
}
|
|
22524
|
+
wake() {
|
|
22525
|
+
const waiter = this.waiter;
|
|
22526
|
+
this.waiter = void 0;
|
|
22527
|
+
waiter?.();
|
|
22528
|
+
}
|
|
22529
|
+
wait(ms) {
|
|
22530
|
+
return new Promise((resolve17) => {
|
|
22531
|
+
const timer = setTimeout(() => {
|
|
22532
|
+
if (this.waiter === wake) this.waiter = void 0;
|
|
22533
|
+
resolve17();
|
|
22534
|
+
}, ms);
|
|
22535
|
+
const wake = () => {
|
|
22536
|
+
clearTimeout(timer);
|
|
22537
|
+
resolve17();
|
|
22538
|
+
};
|
|
22539
|
+
this.waiter = wake;
|
|
22540
|
+
});
|
|
22541
|
+
}
|
|
22542
|
+
/** Push channels have no cursor; keep the empty string so the poller is happy. */
|
|
22543
|
+
async getUpdates(cursor = "") {
|
|
22544
|
+
if (this.queue.length === 0) await this.wait(this.waitTimeoutMs);
|
|
22545
|
+
if (this.queue.length === 0) return { cursor, messages: [] };
|
|
22546
|
+
return { cursor, messages: this.queue.splice(0, this.queue.length) };
|
|
22547
|
+
}
|
|
22548
|
+
async sendText(credentials, chatId, text3, options = {}) {
|
|
22549
|
+
if (chatId === "") throw new FeishuTransportError("invalid-recipient", "\u7F3A\u5C11\u63A5\u6536\u8005");
|
|
22550
|
+
if (text3.trim() === "") throw new FeishuTransportError("empty-text", "\u8981\u53D1\u9001\u7684\u6587\u672C\u4E3A\u7A7A");
|
|
22551
|
+
const buttons = options.buttons ?? [];
|
|
22552
|
+
const token = await this.tenantToken(credentials);
|
|
22553
|
+
let msgType = "text";
|
|
22554
|
+
let content = JSON.stringify({ text: text3 });
|
|
22555
|
+
if (buttons.length > 0) {
|
|
22556
|
+
msgType = "interactive";
|
|
22557
|
+
content = JSON.stringify({
|
|
22558
|
+
config: { wide_screen_mode: true },
|
|
22559
|
+
elements: [
|
|
22560
|
+
{ tag: "div", text: { tag: "plain_text", content: text3 } },
|
|
22561
|
+
{
|
|
22562
|
+
tag: "action",
|
|
22563
|
+
actions: buttons.map((button) => ({
|
|
22564
|
+
tag: "button",
|
|
22565
|
+
text: { tag: "plain_text", content: button.label },
|
|
22566
|
+
type: "default",
|
|
22567
|
+
value: { command: button.command }
|
|
22568
|
+
}))
|
|
22569
|
+
}
|
|
22570
|
+
]
|
|
22571
|
+
});
|
|
22572
|
+
}
|
|
22573
|
+
const response = await this.call(
|
|
22574
|
+
`/open-apis/im/v1/messages?receive_id_type=chat_id`,
|
|
22575
|
+
{
|
|
22576
|
+
method: "POST",
|
|
22577
|
+
token,
|
|
22578
|
+
body: { receive_id: chatId, msg_type: msgType, content }
|
|
22579
|
+
}
|
|
22580
|
+
);
|
|
22581
|
+
return response.data?.message_id ?? "";
|
|
22582
|
+
}
|
|
22583
|
+
};
|
|
22584
|
+
|
|
22585
|
+
// src/host/remote/feishu/channel.ts
|
|
22586
|
+
function messageOf2(error) {
|
|
22587
|
+
return error instanceof Error ? error.message : String(error);
|
|
22588
|
+
}
|
|
22589
|
+
var FeishuChannel = class {
|
|
22590
|
+
constructor(options) {
|
|
22591
|
+
this.options = options;
|
|
22592
|
+
this.transport = options.createTransport?.() ?? new FeishuTransport();
|
|
22593
|
+
}
|
|
22594
|
+
options;
|
|
22595
|
+
id = "feishu";
|
|
22596
|
+
transport;
|
|
22597
|
+
adapter;
|
|
22598
|
+
credentialsValue;
|
|
22599
|
+
phaseValue = "off";
|
|
22600
|
+
errorValue;
|
|
22601
|
+
generation = 0;
|
|
22602
|
+
get running() {
|
|
22603
|
+
return this.phaseValue === "running";
|
|
22604
|
+
}
|
|
22605
|
+
status() {
|
|
22606
|
+
const devices = this.options.bindings.list().filter((binding) => binding.channel === this.id).map((binding) => ({ chatId: binding.chatId, boundAt: binding.boundAt }));
|
|
22607
|
+
const connected = this.phaseValue === "running";
|
|
22608
|
+
const failed = this.phaseValue === "failed";
|
|
22609
|
+
return {
|
|
22610
|
+
id: this.id,
|
|
22611
|
+
phase: this.phaseValue,
|
|
22612
|
+
login: {
|
|
22613
|
+
phase: connected ? "connected" : failed ? "failed" : "idle",
|
|
22614
|
+
status: connected ? "connected" : failed ? "failed" : "idle",
|
|
22615
|
+
...this.errorValue === void 0 ? {} : { error: this.errorValue }
|
|
22616
|
+
},
|
|
22617
|
+
devices,
|
|
22618
|
+
...this.credentialsValue?.name === void 0 ? {} : { handle: this.credentialsValue.name },
|
|
22619
|
+
...this.errorValue === void 0 ? {} : { error: this.errorValue }
|
|
22620
|
+
};
|
|
22621
|
+
}
|
|
22622
|
+
async start() {
|
|
22623
|
+
if (this.phaseValue === "running" || this.phaseValue === "unbound") return;
|
|
22624
|
+
const stored = await this.options.credentials.load().catch(() => void 0);
|
|
22625
|
+
if (stored === void 0) {
|
|
22626
|
+
this.phaseValue = "unbound";
|
|
22627
|
+
return;
|
|
22628
|
+
}
|
|
22629
|
+
this.connectStored(stored);
|
|
22630
|
+
}
|
|
22631
|
+
/** Validate the app credentials, then keep the long connection open. */
|
|
22632
|
+
async connect(appId, appSecret) {
|
|
22633
|
+
const id = appId.trim();
|
|
22634
|
+
const secret = appSecret.trim();
|
|
22635
|
+
if (id === "" || secret === "") return { ok: false, error: "\u8BF7\u586B\u5199 App ID \u548C App Secret" };
|
|
22636
|
+
const generation = this.generation;
|
|
22637
|
+
let identity;
|
|
22638
|
+
try {
|
|
22639
|
+
identity = await this.transport.validate({ appId: id, appSecret: secret });
|
|
22640
|
+
} catch (error) {
|
|
22641
|
+
return { ok: false, error: messageOf2(error) };
|
|
22642
|
+
}
|
|
22643
|
+
if (this.generation !== generation) return { ok: false, error: "\u8FDE\u63A5\u5DF2\u53D6\u6D88" };
|
|
22644
|
+
const credentials = {
|
|
22645
|
+
appId: id,
|
|
22646
|
+
appSecret: secret,
|
|
22647
|
+
...identity.name === void 0 ? {} : { name: identity.name }
|
|
22648
|
+
};
|
|
22649
|
+
try {
|
|
22650
|
+
await this.options.credentials.save(credentials);
|
|
22651
|
+
} catch (error) {
|
|
22652
|
+
return { ok: false, error: messageOf2(error) };
|
|
22653
|
+
}
|
|
22654
|
+
if (this.generation !== generation) return { ok: false, error: "\u8FDE\u63A5\u5DF2\u53D6\u6D88" };
|
|
22655
|
+
this.connectStored(credentials);
|
|
22656
|
+
return { ok: true, ...identity.name === void 0 ? {} : { name: identity.name } };
|
|
22657
|
+
}
|
|
22658
|
+
async logout() {
|
|
22659
|
+
this.generation += 1;
|
|
22660
|
+
this.adapter?.stop();
|
|
22661
|
+
this.adapter = void 0;
|
|
22662
|
+
this.transport.stop();
|
|
22663
|
+
this.credentialsValue = void 0;
|
|
22664
|
+
this.errorValue = void 0;
|
|
22665
|
+
await this.options.credentials.clear().catch((error) => {
|
|
22666
|
+
this.options.onError?.(error);
|
|
22667
|
+
});
|
|
22668
|
+
if (this.phaseValue !== "off") this.phaseValue = "unbound";
|
|
22669
|
+
}
|
|
22670
|
+
stop() {
|
|
22671
|
+
this.generation += 1;
|
|
22672
|
+
this.adapter?.stop();
|
|
22673
|
+
this.adapter = void 0;
|
|
22674
|
+
this.transport.stop();
|
|
22675
|
+
this.credentialsValue = void 0;
|
|
22676
|
+
this.phaseValue = "off";
|
|
22677
|
+
}
|
|
22678
|
+
async send(chatId, text3, buttons) {
|
|
22679
|
+
const credentials = this.credentialsValue;
|
|
22680
|
+
if (this.phaseValue !== "running" || credentials === void 0) return;
|
|
22681
|
+
const chunks = splitForChannel(text3, this.options.capabilities.maxChars);
|
|
22682
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
22683
|
+
await this.transport.sendText(
|
|
22684
|
+
credentials,
|
|
22685
|
+
chatId,
|
|
22686
|
+
chunk,
|
|
22687
|
+
index === chunks.length - 1 && buttons !== void 0 && buttons.length > 0 ? { buttons } : {}
|
|
22688
|
+
);
|
|
22689
|
+
}
|
|
22690
|
+
}
|
|
22691
|
+
contextFor(_chatId) {
|
|
22692
|
+
return void 0;
|
|
22693
|
+
}
|
|
22694
|
+
connectStored(credentials) {
|
|
22695
|
+
this.credentialsValue = credentials;
|
|
22696
|
+
this.errorValue = void 0;
|
|
22697
|
+
this.adapter?.stop();
|
|
22698
|
+
const generation = this.generation;
|
|
22699
|
+
const adapter = new FeishuAdapter({
|
|
22700
|
+
transport: this.transport,
|
|
22701
|
+
credentials,
|
|
22702
|
+
controller: this.options.controller,
|
|
22703
|
+
bindings: this.options.bindings,
|
|
22704
|
+
capabilities: this.options.capabilities,
|
|
22705
|
+
refresh: this.options.refresh,
|
|
22706
|
+
...this.options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: this.options.emptyPageDelayMs },
|
|
22707
|
+
onError: (error) => this.options.onError?.(error),
|
|
22708
|
+
onFatal: (error) => {
|
|
22709
|
+
this.phaseValue = "failed";
|
|
22710
|
+
this.errorValue = messageOf2(error);
|
|
22711
|
+
}
|
|
22712
|
+
});
|
|
22713
|
+
this.adapter = adapter;
|
|
22714
|
+
this.phaseValue = "off";
|
|
22715
|
+
void this.transport.start(credentials).then(() => {
|
|
22716
|
+
if (this.generation !== generation) return;
|
|
22717
|
+
this.phaseValue = "running";
|
|
22718
|
+
this.errorValue = void 0;
|
|
22719
|
+
void adapter.run();
|
|
22720
|
+
}).catch((error) => {
|
|
22721
|
+
if (this.generation !== generation) return;
|
|
22722
|
+
this.adapter = void 0;
|
|
22723
|
+
adapter.stop();
|
|
22724
|
+
this.phaseValue = "failed";
|
|
22725
|
+
this.errorValue = `\u98DE\u4E66\u957F\u8FDE\u63A5\u6CA1\u6709\u5EFA\u7ACB\uFF1A${messageOf2(error)}`;
|
|
22726
|
+
});
|
|
22727
|
+
}
|
|
22728
|
+
};
|
|
22729
|
+
|
|
22730
|
+
// src/host/remote/feishu/credentials.ts
|
|
22731
|
+
var CREDENTIAL_REF2 = "DSH_AGENT_ENHANCER_FEISHU";
|
|
22732
|
+
function parse2(value) {
|
|
22733
|
+
let parsed;
|
|
22734
|
+
try {
|
|
22735
|
+
parsed = JSON.parse(value);
|
|
22736
|
+
} catch {
|
|
22737
|
+
return void 0;
|
|
22738
|
+
}
|
|
22739
|
+
if (parsed === null || typeof parsed !== "object") return void 0;
|
|
22740
|
+
const record2 = parsed;
|
|
22741
|
+
if (typeof record2.appId !== "string" || record2.appId.trim() === "") return void 0;
|
|
22742
|
+
if (typeof record2.appSecret !== "string" || record2.appSecret.trim() === "") return void 0;
|
|
22743
|
+
return {
|
|
22744
|
+
appId: record2.appId,
|
|
22745
|
+
appSecret: record2.appSecret,
|
|
22746
|
+
...typeof record2.name === "string" && record2.name !== "" ? { name: record2.name } : {}
|
|
22747
|
+
};
|
|
22748
|
+
}
|
|
22749
|
+
function provider2(ctx) {
|
|
22750
|
+
let service;
|
|
22751
|
+
try {
|
|
22752
|
+
service = ctx.get("credentials");
|
|
22753
|
+
} catch {
|
|
22754
|
+
return void 0;
|
|
22755
|
+
}
|
|
22756
|
+
if (service === void 0 || service === null || typeof service !== "object") return void 0;
|
|
22757
|
+
const candidate = service;
|
|
22758
|
+
if (typeof candidate.resolve !== "function" || typeof candidate.set !== "function") return void 0;
|
|
22759
|
+
return service;
|
|
22760
|
+
}
|
|
22761
|
+
function createFeishuCredentialStore(ctx) {
|
|
22762
|
+
if (provider2(ctx) === void 0) {
|
|
22763
|
+
return {
|
|
22764
|
+
async load() {
|
|
22765
|
+
return void 0;
|
|
22766
|
+
},
|
|
22767
|
+
async save() {
|
|
22768
|
+
throw new Error("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B\u51ED\u636E\u670D\u52A1\uFF0C\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u98DE\u4E66 App Secret");
|
|
22769
|
+
},
|
|
22770
|
+
async clear() {
|
|
22771
|
+
}
|
|
22772
|
+
};
|
|
22773
|
+
}
|
|
22774
|
+
return {
|
|
22775
|
+
async load() {
|
|
22776
|
+
const resolved = await provider2(ctx)?.resolve(CREDENTIAL_REF2);
|
|
22777
|
+
if (resolved === void 0) return void 0;
|
|
22778
|
+
return parse2(resolved.value);
|
|
22779
|
+
},
|
|
22780
|
+
async save(credentials) {
|
|
22781
|
+
const service = provider2(ctx);
|
|
22782
|
+
if (service === void 0) throw new Error("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B\u51ED\u636E\u670D\u52A1");
|
|
22783
|
+
const payload = {
|
|
22784
|
+
appId: credentials.appId,
|
|
22785
|
+
appSecret: credentials.appSecret
|
|
22786
|
+
};
|
|
22787
|
+
if (credentials.name !== void 0) payload.name = credentials.name;
|
|
22788
|
+
await service.set(CREDENTIAL_REF2, JSON.stringify(payload));
|
|
22789
|
+
},
|
|
22790
|
+
async clear() {
|
|
22791
|
+
await provider2(ctx)?.unset(CREDENTIAL_REF2);
|
|
22792
|
+
}
|
|
22793
|
+
};
|
|
22794
|
+
}
|
|
22795
|
+
|
|
22796
|
+
// src/host/remote/weixin/capabilities.ts
|
|
22797
|
+
var WEIXIN_CAPABILITIES = {
|
|
22798
|
+
buttons: false,
|
|
22799
|
+
editMessage: false,
|
|
22800
|
+
threads: false,
|
|
22801
|
+
media: "file",
|
|
22802
|
+
markdown: false,
|
|
22803
|
+
maxChars: 1800,
|
|
22804
|
+
privateOnly: true
|
|
22805
|
+
};
|
|
22806
|
+
|
|
22807
|
+
// src/host/remote/weixin/channel.ts
|
|
22808
|
+
import { join as join31 } from "node:path";
|
|
22809
|
+
|
|
22810
|
+
// src/host/remote/weixin/transport.ts
|
|
22811
|
+
import { randomBytes, randomUUID as randomUUID10 } from "node:crypto";
|
|
22812
|
+
var WeixinTransportError = class extends Error {
|
|
22813
|
+
constructor(code, message, detail = {}) {
|
|
22814
|
+
super(message);
|
|
22815
|
+
this.code = code;
|
|
22816
|
+
this.detail = detail;
|
|
22817
|
+
this.name = "WeixinTransportError";
|
|
22818
|
+
}
|
|
22819
|
+
code;
|
|
22820
|
+
detail;
|
|
22821
|
+
};
|
|
22822
|
+
var DEFAULT_LOGIN_BASE_URL = "https://ilinkai.weixin.qq.com/";
|
|
22823
|
+
var PROTOCOL_VERSION = "2.4.6";
|
|
22824
|
+
var BOT_TYPE = "3";
|
|
22825
|
+
var APP_ID = "bot";
|
|
22826
|
+
var CLIENT_VERSION = String(2 << 16 | 4 << 8 | 6);
|
|
22827
|
+
var DEFAULT_POLL_TIMEOUT_MS2 = 35e3;
|
|
22828
|
+
var DEFAULT_REQUEST_TIMEOUT_MS3 = 15e3;
|
|
22829
|
+
function isWeixinHost(hostname) {
|
|
22830
|
+
const host = hostname.toLowerCase().replace(/\.$/, "");
|
|
22831
|
+
return host === "weixin.qq.com" || host.endsWith(".weixin.qq.com") || host === "wechat.com" || host.endsWith(".wechat.com");
|
|
22832
|
+
}
|
|
22833
|
+
function normalizeBaseUrl(value) {
|
|
22834
|
+
let url;
|
|
22835
|
+
try {
|
|
22836
|
+
url = new URL(value);
|
|
22837
|
+
} catch {
|
|
22838
|
+
throw new WeixinTransportError("invalid-base-url", "\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u8FDE\u63A5\u5730\u5740");
|
|
22839
|
+
}
|
|
22840
|
+
if (url.protocol !== "https:" || !isWeixinHost(url.hostname) || url.port !== "" && url.port !== "443") {
|
|
22841
|
+
throw new WeixinTransportError("untrusted-base-url", "\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u8FDE\u63A5\u5730\u5740");
|
|
22842
|
+
}
|
|
22843
|
+
url.username = "";
|
|
22844
|
+
url.password = "";
|
|
22845
|
+
url.search = "";
|
|
22846
|
+
url.hash = "";
|
|
22847
|
+
if (!url.pathname.endsWith("/")) url.pathname += "/";
|
|
22848
|
+
return url.toString();
|
|
22849
|
+
}
|
|
22850
|
+
function normalizeQrUrl(value) {
|
|
22851
|
+
let url;
|
|
22852
|
+
try {
|
|
22853
|
+
url = new URL(value);
|
|
22854
|
+
} catch {
|
|
22855
|
+
throw new WeixinTransportError("invalid-qr", "\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u626B\u7801\u5730\u5740");
|
|
22856
|
+
}
|
|
22857
|
+
if (url.protocol !== "https:" || !isWeixinHost(url.hostname)) {
|
|
22858
|
+
throw new WeixinTransportError("untrusted-qr", "\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u4E0D\u53D7\u4FE1\u4EFB\u7684\u626B\u7801\u5730\u5740");
|
|
22859
|
+
}
|
|
22860
|
+
return url.toString();
|
|
22861
|
+
}
|
|
22862
|
+
function providerCodeOf(value) {
|
|
22863
|
+
if (value === null || typeof value !== "object") return void 0;
|
|
22864
|
+
for (const key of ["ret", "errcode"]) {
|
|
22865
|
+
const raw = value[key];
|
|
22866
|
+
if (typeof raw === "number" && raw !== 0) return String(raw);
|
|
22867
|
+
if (typeof raw === "string" && raw !== "" && raw !== "0") return raw;
|
|
22868
|
+
}
|
|
22869
|
+
return void 0;
|
|
22870
|
+
}
|
|
22871
|
+
function nonEmptyString2(value) {
|
|
22872
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
22873
|
+
}
|
|
22874
|
+
function textOfItem(item) {
|
|
22875
|
+
const textItem = item.text_item;
|
|
22876
|
+
if (textItem === null || typeof textItem !== "object") return void 0;
|
|
22877
|
+
return nonEmptyString2(textItem.text) ?? "";
|
|
22878
|
+
}
|
|
22879
|
+
function voiceTextOfItem(item) {
|
|
22880
|
+
const voiceItem = item.voice_item;
|
|
22881
|
+
if (voiceItem === null || typeof voiceItem !== "object") return void 0;
|
|
22882
|
+
return nonEmptyString2(voiceItem.text);
|
|
22883
|
+
}
|
|
22884
|
+
function parseItems(raw) {
|
|
22885
|
+
if (!Array.isArray(raw)) return [];
|
|
22886
|
+
const items = [];
|
|
22887
|
+
for (const entry of raw) {
|
|
22888
|
+
if (entry === null || typeof entry !== "object") continue;
|
|
22889
|
+
const item = entry;
|
|
22890
|
+
switch (item.type) {
|
|
22891
|
+
case 1: {
|
|
22892
|
+
const text3 = textOfItem(item);
|
|
22893
|
+
items.push(text3 === void 0 ? { kind: "other" } : { kind: "text", text: text3 });
|
|
22894
|
+
break;
|
|
22895
|
+
}
|
|
22896
|
+
case 3: {
|
|
22897
|
+
const text3 = voiceTextOfItem(item);
|
|
22898
|
+
items.push(text3 === void 0 ? { kind: "voice" } : { kind: "voice", text: text3 });
|
|
22899
|
+
break;
|
|
22900
|
+
}
|
|
22901
|
+
case 2:
|
|
22902
|
+
items.push({ kind: "image" });
|
|
22903
|
+
break;
|
|
22904
|
+
case 4:
|
|
22905
|
+
items.push({ kind: "file" });
|
|
22906
|
+
break;
|
|
22907
|
+
default:
|
|
22908
|
+
items.push({ kind: "other" });
|
|
22909
|
+
}
|
|
22910
|
+
}
|
|
22911
|
+
return items;
|
|
22912
|
+
}
|
|
22913
|
+
function parseMessage(raw) {
|
|
22914
|
+
if (raw === null || typeof raw !== "object") return void 0;
|
|
22915
|
+
const record2 = raw;
|
|
22916
|
+
const fromUserId = nonEmptyString2(record2.from_user_id);
|
|
22917
|
+
if (fromUserId === void 0) return void 0;
|
|
22918
|
+
const messageId = typeof record2.message_id === "number" ? record2.message_id : 0;
|
|
22919
|
+
const seq = typeof record2.seq === "number" ? record2.seq : 0;
|
|
22920
|
+
const createdAt = typeof record2.create_time_ms === "number" ? record2.create_time_ms : 0;
|
|
22921
|
+
const contextToken = nonEmptyString2(record2.context_token);
|
|
22922
|
+
return {
|
|
22923
|
+
seq,
|
|
22924
|
+
messageId,
|
|
22925
|
+
fromUserId,
|
|
22926
|
+
toUserId: nonEmptyString2(record2.to_user_id) ?? "",
|
|
22927
|
+
createdAt,
|
|
22928
|
+
items: parseItems(record2.item_list),
|
|
22929
|
+
...contextToken === void 0 ? {} : { contextToken }
|
|
22930
|
+
};
|
|
22931
|
+
}
|
|
22932
|
+
var WeixinTransport = class {
|
|
22933
|
+
fetchImpl;
|
|
22934
|
+
loginBaseUrl;
|
|
22935
|
+
pollTimeoutMs;
|
|
22936
|
+
requestTimeoutMs;
|
|
22937
|
+
channelVersion;
|
|
22938
|
+
botAgent;
|
|
22939
|
+
constructor(options = {}) {
|
|
22940
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
22941
|
+
this.loginBaseUrl = normalizeBaseUrl(options.loginBaseUrl ?? DEFAULT_LOGIN_BASE_URL);
|
|
22942
|
+
this.pollTimeoutMs = options.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS2;
|
|
22943
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS3;
|
|
22944
|
+
this.channelVersion = options.channelVersion ?? PROTOCOL_VERSION;
|
|
22945
|
+
this.botAgent = options.botAgent ?? "dsh-agent-enhancer";
|
|
22946
|
+
}
|
|
22947
|
+
baseInfo() {
|
|
22948
|
+
return { channel_version: this.channelVersion, bot_agent: this.botAgent };
|
|
22949
|
+
}
|
|
22950
|
+
headers(token) {
|
|
22951
|
+
const headers = {
|
|
22952
|
+
"content-type": "application/json",
|
|
22953
|
+
"iLink-App-Id": APP_ID,
|
|
22954
|
+
"iLink-App-ClientVersion": CLIENT_VERSION
|
|
22955
|
+
};
|
|
22956
|
+
if (token === void 0) return headers;
|
|
22957
|
+
const uin = randomBytes(4).readUInt32BE(0);
|
|
22958
|
+
return {
|
|
22959
|
+
...headers,
|
|
22960
|
+
AuthorizationType: "ilink_bot_token",
|
|
22961
|
+
Authorization: `Bearer ${token}`,
|
|
22962
|
+
"X-WECHAT-UIN": Buffer.from(String(uin), "utf8").toString("base64")
|
|
22963
|
+
};
|
|
22964
|
+
}
|
|
22965
|
+
async request(method, baseUrl, endpoint, options) {
|
|
22966
|
+
const base = normalizeBaseUrl(baseUrl);
|
|
22967
|
+
const url = new URL(endpoint, base);
|
|
22968
|
+
if (url.protocol !== "https:" || !isWeixinHost(url.hostname)) {
|
|
22969
|
+
throw new WeixinTransportError("untrusted-endpoint", "\u62D2\u7EDD\u8BBF\u95EE\u4E0D\u53D7\u4FE1\u4EFB\u7684\u5FAE\u4FE1\u5730\u5740");
|
|
22970
|
+
}
|
|
22971
|
+
const controller = new AbortController();
|
|
22972
|
+
const timer = setTimeout(() => controller.abort(), options.timeoutMs);
|
|
22973
|
+
try {
|
|
22974
|
+
const response = await this.fetchImpl(url, {
|
|
22975
|
+
method,
|
|
22976
|
+
headers: this.headers(options.token),
|
|
22977
|
+
...options.body === void 0 ? {} : { body: JSON.stringify(options.body) },
|
|
22978
|
+
signal: controller.signal
|
|
22979
|
+
});
|
|
22980
|
+
const text3 = await response.text();
|
|
22981
|
+
if (!response.ok) {
|
|
22982
|
+
throw new WeixinTransportError("http-error", `\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${response.status}\uFF09`, { status: response.status });
|
|
22983
|
+
}
|
|
22984
|
+
try {
|
|
22985
|
+
return JSON.parse(text3);
|
|
22986
|
+
} catch {
|
|
22987
|
+
throw new WeixinTransportError("invalid-response", "\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94");
|
|
22988
|
+
}
|
|
22989
|
+
} catch (error) {
|
|
22990
|
+
if (error instanceof WeixinTransportError) throw error;
|
|
22991
|
+
if (controller.signal.aborted) throw new WeixinTransportError("timeout", "\u5FAE\u4FE1\u670D\u52A1\u8BF7\u6C42\u8D85\u65F6");
|
|
22992
|
+
throw new WeixinTransportError("network-error", "\u6682\u65F6\u65E0\u6CD5\u8BBF\u95EE\u5FAE\u4FE1\u670D\u52A1");
|
|
22993
|
+
} finally {
|
|
22994
|
+
clearTimeout(timer);
|
|
22995
|
+
}
|
|
22996
|
+
}
|
|
22997
|
+
/** Fresh login QR. The caller renders `qrUrl` as a QR code; the ticket polls status. */
|
|
22998
|
+
async beginLogin(localTokens = []) {
|
|
22999
|
+
const response = await this.request("POST", this.loginBaseUrl, `ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(BOT_TYPE)}`, {
|
|
23000
|
+
body: { local_token_list: localTokens.slice(-10) },
|
|
23001
|
+
timeoutMs: this.requestTimeoutMs
|
|
23002
|
+
});
|
|
23003
|
+
const record2 = response !== null && typeof response === "object" ? response : {};
|
|
23004
|
+
const providerCode = providerCodeOf(record2);
|
|
23005
|
+
if (providerCode !== void 0) {
|
|
23006
|
+
throw new WeixinTransportError("qr-rejected", "\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u4E8C\u7EF4\u7801\u7533\u8BF7", { providerCode });
|
|
23007
|
+
}
|
|
23008
|
+
const ticket = nonEmptyString2(record2.qrcode);
|
|
23009
|
+
const qrUrl = nonEmptyString2(record2.qrcode_img_content);
|
|
23010
|
+
if (ticket === void 0 || qrUrl === void 0) {
|
|
23011
|
+
throw new WeixinTransportError("invalid-qr", "\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u4E8C\u7EF4\u7801");
|
|
23012
|
+
}
|
|
23013
|
+
return { ticket, qrUrl: normalizeQrUrl(qrUrl) };
|
|
23014
|
+
}
|
|
23015
|
+
async pollLogin(ticket, verifyCode) {
|
|
23016
|
+
const query = new URLSearchParams({ qrcode: ticket });
|
|
23017
|
+
if (verifyCode !== void 0 && verifyCode !== "") query.set("verify_code", verifyCode);
|
|
23018
|
+
const response = await this.request("GET", this.loginBaseUrl, `ilink/bot/get_qrcode_status?${query.toString()}`, {
|
|
23019
|
+
timeoutMs: this.pollTimeoutMs
|
|
23020
|
+
});
|
|
23021
|
+
const record2 = response !== null && typeof response === "object" ? response : {};
|
|
23022
|
+
const status = nonEmptyString2(record2.status);
|
|
23023
|
+
if (status === void 0) {
|
|
23024
|
+
throw new WeixinTransportError("invalid-login-status", "\u5FAE\u4FE1\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u8BC6\u522B\u7684\u626B\u7801\u72B6\u6001");
|
|
23025
|
+
}
|
|
23026
|
+
if (status !== "confirmed") return { status };
|
|
23027
|
+
const baseUrl = nonEmptyString2(record2.baseurl);
|
|
23028
|
+
const token = nonEmptyString2(record2.bot_token);
|
|
23029
|
+
if (baseUrl === void 0 || token === void 0) {
|
|
23030
|
+
throw new WeixinTransportError("invalid-credentials", "\u5FAE\u4FE1\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u767B\u5F55\u51ED\u636E");
|
|
23031
|
+
}
|
|
23032
|
+
return {
|
|
23033
|
+
status,
|
|
23034
|
+
credentials: {
|
|
23035
|
+
baseUrl: normalizeBaseUrl(baseUrl),
|
|
23036
|
+
token,
|
|
23037
|
+
...nonEmptyString2(record2.ilink_bot_id) === void 0 ? {} : { botId: nonEmptyString2(record2.ilink_bot_id) },
|
|
23038
|
+
...nonEmptyString2(record2.ilink_user_id) === void 0 ? {} : { userId: nonEmptyString2(record2.ilink_user_id) }
|
|
23039
|
+
}
|
|
23040
|
+
};
|
|
23041
|
+
}
|
|
23042
|
+
/**
|
|
23043
|
+
* Long poll. A client-side timeout is normal: it returns no messages and the
|
|
23044
|
+
* same cursor so the next round can continue.
|
|
23045
|
+
*/
|
|
23046
|
+
async getUpdates(credentials, cursor = "") {
|
|
23047
|
+
let response;
|
|
23048
|
+
try {
|
|
23049
|
+
response = await this.request("POST", credentials.baseUrl, "ilink/bot/getupdates", {
|
|
23050
|
+
body: { get_updates_buf: cursor, base_info: this.baseInfo() },
|
|
23051
|
+
token: credentials.token,
|
|
23052
|
+
timeoutMs: this.pollTimeoutMs
|
|
23053
|
+
});
|
|
23054
|
+
} catch (error) {
|
|
23055
|
+
if (error instanceof WeixinTransportError && error.code === "timeout") {
|
|
23056
|
+
return { cursor, messages: [] };
|
|
23057
|
+
}
|
|
23058
|
+
throw error;
|
|
23059
|
+
}
|
|
23060
|
+
const record2 = response !== null && typeof response === "object" ? response : {};
|
|
23061
|
+
const providerCode = providerCodeOf(record2);
|
|
23062
|
+
if (providerCode !== void 0) {
|
|
23063
|
+
throw new WeixinTransportError(providerCode === "-14" ? "stale-token" : "updates-rejected", "\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u6D88\u606F\u62C9\u53D6", { providerCode });
|
|
23064
|
+
}
|
|
23065
|
+
const messages = [];
|
|
23066
|
+
if (Array.isArray(record2.msgs)) {
|
|
23067
|
+
for (const raw of record2.msgs) {
|
|
23068
|
+
const message = parseMessage(raw);
|
|
23069
|
+
if (message !== void 0) messages.push(message);
|
|
23070
|
+
}
|
|
23071
|
+
}
|
|
23072
|
+
const next = nonEmptyString2(record2.get_updates_buf) ?? cursor;
|
|
23073
|
+
return { cursor: next, messages };
|
|
23074
|
+
}
|
|
23075
|
+
/** Send one text message. Chunking belongs to the caller (it is a UI budget, not a protocol limit). */
|
|
23076
|
+
async sendText(credentials, toUserId, text3, options = {}) {
|
|
23077
|
+
if (toUserId === "") throw new WeixinTransportError("invalid-recipient", "\u7F3A\u5C11\u63A5\u6536\u8005");
|
|
23078
|
+
if (text3.trim() === "") throw new WeixinTransportError("empty-text", "\u8981\u53D1\u9001\u7684\u6587\u672C\u4E3A\u7A7A");
|
|
23079
|
+
const payload = {
|
|
23080
|
+
msg: {
|
|
23081
|
+
from_user_id: "",
|
|
23082
|
+
to_user_id: toUserId,
|
|
23083
|
+
client_id: options.clientId ?? `dsh-enhancer-${randomUUID10()}`,
|
|
23084
|
+
message_type: 2,
|
|
23085
|
+
message_state: 2,
|
|
23086
|
+
item_list: [{ type: 1, text_item: { text: text3 } }],
|
|
23087
|
+
...options.contextToken === void 0 ? {} : { context_token: options.contextToken },
|
|
23088
|
+
...options.runId === void 0 ? {} : { run_id: options.runId }
|
|
23089
|
+
},
|
|
23090
|
+
base_info: this.baseInfo()
|
|
23091
|
+
};
|
|
23092
|
+
const response = await this.request("POST", credentials.baseUrl, "ilink/bot/sendmessage", {
|
|
23093
|
+
body: payload,
|
|
23094
|
+
token: credentials.token,
|
|
23095
|
+
timeoutMs: this.requestTimeoutMs
|
|
23096
|
+
});
|
|
23097
|
+
const record2 = response !== null && typeof response === "object" ? response : {};
|
|
23098
|
+
const providerCode = providerCodeOf(record2);
|
|
23099
|
+
if (providerCode !== void 0) {
|
|
23100
|
+
throw new WeixinTransportError("send-rejected", "\u5FAE\u4FE1\u670D\u52A1\u62D2\u7EDD\u4E86\u8FD9\u6761\u6D88\u606F", { providerCode });
|
|
23101
|
+
}
|
|
23102
|
+
return typeof record2.message_id === "number" ? record2.message_id : 0;
|
|
23103
|
+
}
|
|
23104
|
+
};
|
|
23105
|
+
|
|
23106
|
+
// src/host/remote/weixin/adapter.ts
|
|
23107
|
+
var WEIXIN_HINTS = {
|
|
23108
|
+
unbound: "\u8FD9\u53F0\u804A\u5929\u8FD8\u6CA1\u7ED1\u5B9A\u3002\u8BF7\u5728\u7535\u8111\u4E0A\u6253\u5F00\u300C\u8BBE\u7F6E \u2192 \u8FDC\u7A0B\u8FDE\u63A5\u300D\u751F\u6210\u7ED1\u5B9A\u7801\uFF0C\u7136\u540E\u628A 6 \u4F4D\u6570\u5B57\u53D1\u7ED9\u6211\u3002",
|
|
23109
|
+
badCode: "\u7ED1\u5B9A\u7801\u65E0\u6548\u6216\u5DF2\u8FC7\u671F\u3002\u8BF7\u5728\u7535\u8111\u4E0A\u91CD\u65B0\u751F\u6210\u4E00\u4E2A\u3002",
|
|
23110
|
+
unsupported: "\u76EE\u524D\u53EA\u652F\u6301\u6587\u5B57\u548C\u8BED\u97F3\u3002\u56FE\u7247\u548C\u6587\u4EF6\u8BF7\u5728\u7535\u8111\u4E0A\u67E5\u770B\u3002",
|
|
23111
|
+
bound: "\u5DF2\u7ED1\u5B9A\u3002\u56DE\u300C\u4EFB\u52A1\u300D\u67E5\u770B\u5F53\u524D\u4EFB\u52A1\u3002"
|
|
23112
|
+
};
|
|
23113
|
+
var WeixinAdapter = class {
|
|
23114
|
+
poller;
|
|
23115
|
+
constructor(options) {
|
|
23116
|
+
this.poller = new ChannelPoller({
|
|
23117
|
+
channel: options.channel ?? "weixin",
|
|
23118
|
+
transport: {
|
|
23119
|
+
getUpdates: (cursor) => options.transport.getUpdates(options.credentials, cursor),
|
|
23120
|
+
sendText: (chatId, text3, sendOptions) => options.transport.sendText(
|
|
23121
|
+
options.credentials,
|
|
23122
|
+
chatId,
|
|
23123
|
+
text3,
|
|
23124
|
+
sendOptions
|
|
23125
|
+
)
|
|
23126
|
+
},
|
|
23127
|
+
controller: options.controller,
|
|
23128
|
+
bindings: options.bindings,
|
|
23129
|
+
capabilities: options.capabilities,
|
|
23130
|
+
...options.cursor === void 0 ? {} : { cursor: options.cursor },
|
|
23131
|
+
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
23132
|
+
...options.onFatal === void 0 ? {} : { onFatal: options.onFatal },
|
|
23133
|
+
...options.onError === void 0 ? {} : { onError: options.onError },
|
|
23134
|
+
...options.refresh === void 0 ? {} : { refresh: options.refresh },
|
|
23135
|
+
...options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: options.emptyPageDelayMs },
|
|
23136
|
+
isFatal: (error) => error instanceof WeixinTransportError && error.code === "stale-token",
|
|
23137
|
+
hints: WEIXIN_HINTS
|
|
23138
|
+
});
|
|
23139
|
+
}
|
|
23140
|
+
stop() {
|
|
23141
|
+
this.poller.stop();
|
|
23142
|
+
}
|
|
23143
|
+
get running() {
|
|
23144
|
+
return this.poller.running;
|
|
23145
|
+
}
|
|
23146
|
+
contextFor(chatId) {
|
|
23147
|
+
return this.poller.contextFor(chatId);
|
|
23148
|
+
}
|
|
23149
|
+
run() {
|
|
23150
|
+
return this.poller.run();
|
|
23151
|
+
}
|
|
23152
|
+
};
|
|
23153
|
+
|
|
23154
|
+
// src/host/remote/weixin/login.ts
|
|
23155
|
+
var DEFAULT_POLL_INTERVAL_MS = 1200;
|
|
23156
|
+
var DEFAULT_SLEEP2 = (ms) => new Promise((resolve17) => setTimeout(resolve17, ms));
|
|
23157
|
+
var WeixinLogin = class {
|
|
23158
|
+
constructor(options) {
|
|
23159
|
+
this.options = options;
|
|
23160
|
+
this.sleep = options.sleep ?? DEFAULT_SLEEP2;
|
|
23161
|
+
}
|
|
23162
|
+
options;
|
|
23163
|
+
snapshotValue = { phase: "idle", status: "idle" };
|
|
23164
|
+
ticket;
|
|
23165
|
+
credentialsValue;
|
|
23166
|
+
stopped = true;
|
|
23167
|
+
settled = true;
|
|
23168
|
+
waiters = [];
|
|
23169
|
+
sleep;
|
|
23170
|
+
snapshot() {
|
|
23171
|
+
return this.snapshotValue;
|
|
23172
|
+
}
|
|
23173
|
+
credentials() {
|
|
23174
|
+
return this.credentialsValue;
|
|
23175
|
+
}
|
|
23176
|
+
async begin() {
|
|
23177
|
+
this.cancel();
|
|
23178
|
+
this.stopped = false;
|
|
23179
|
+
this.settled = false;
|
|
23180
|
+
this.credentialsValue = void 0;
|
|
23181
|
+
const ticket = await this.options.transport.beginLogin();
|
|
23182
|
+
this.ticket = ticket.ticket;
|
|
23183
|
+
this.update({ phase: "waiting", status: "wait", qrUrl: ticket.qrUrl });
|
|
23184
|
+
void this.run(ticket.ticket);
|
|
23185
|
+
return ticket;
|
|
23186
|
+
}
|
|
23187
|
+
wait() {
|
|
23188
|
+
if (this.credentialsValue !== void 0) return Promise.resolve(this.credentialsValue);
|
|
23189
|
+
if (this.settled) return Promise.resolve(void 0);
|
|
23190
|
+
return new Promise((resolve17) => {
|
|
23191
|
+
this.waiters.push(resolve17);
|
|
23192
|
+
});
|
|
23193
|
+
}
|
|
23194
|
+
cancel() {
|
|
23195
|
+
this.stopped = true;
|
|
23196
|
+
this.ticket = void 0;
|
|
23197
|
+
this.settle(void 0, { phase: "idle", status: "idle" });
|
|
23198
|
+
}
|
|
23199
|
+
async run(ticket) {
|
|
23200
|
+
const interval = this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
23201
|
+
while (!this.stopped && this.ticket === ticket) {
|
|
23202
|
+
let poll;
|
|
23203
|
+
try {
|
|
23204
|
+
poll = await this.options.transport.pollLogin(ticket);
|
|
23205
|
+
} catch (error) {
|
|
23206
|
+
if (this.stopped) return;
|
|
23207
|
+
this.settle(void 0, {
|
|
23208
|
+
phase: "failed",
|
|
23209
|
+
status: this.snapshotValue.status,
|
|
23210
|
+
...this.snapshotValue.qrUrl === void 0 ? {} : { qrUrl: this.snapshotValue.qrUrl },
|
|
23211
|
+
error: error instanceof Error ? error.message : String(error)
|
|
23212
|
+
});
|
|
23213
|
+
return;
|
|
23214
|
+
}
|
|
23215
|
+
if (this.stopped || this.ticket !== ticket) return;
|
|
23216
|
+
const status = poll.status;
|
|
23217
|
+
if (status === "confirmed") {
|
|
23218
|
+
if (poll.credentials === void 0) {
|
|
23219
|
+
this.settle(void 0, {
|
|
23220
|
+
phase: "failed",
|
|
23221
|
+
status,
|
|
23222
|
+
...this.snapshotValue.qrUrl === void 0 ? {} : { qrUrl: this.snapshotValue.qrUrl },
|
|
23223
|
+
error: "\u767B\u5F55\u5DF2\u786E\u8BA4\uFF0C\u4F46\u670D\u52A1\u6CA1\u6709\u8FD4\u56DE\u51ED\u636E"
|
|
23224
|
+
});
|
|
23225
|
+
return;
|
|
23226
|
+
}
|
|
23227
|
+
this.settle(poll.credentials, {
|
|
23228
|
+
phase: "connected",
|
|
23229
|
+
status,
|
|
23230
|
+
...this.snapshotValue.qrUrl === void 0 ? {} : { qrUrl: this.snapshotValue.qrUrl }
|
|
23231
|
+
});
|
|
23232
|
+
return;
|
|
23233
|
+
}
|
|
23234
|
+
if (status === "expired" || status === "scaned_but_redirect" || status === "binded_redirect" || status === "need_verifycode" || status === "verify_code_blocked") {
|
|
23235
|
+
this.settle(void 0, {
|
|
23236
|
+
phase: "failed",
|
|
23237
|
+
status,
|
|
23238
|
+
...this.snapshotValue.qrUrl === void 0 ? {} : { qrUrl: this.snapshotValue.qrUrl }
|
|
23239
|
+
});
|
|
23240
|
+
return;
|
|
23241
|
+
}
|
|
23242
|
+
this.update({
|
|
23243
|
+
phase: "waiting",
|
|
23244
|
+
status,
|
|
23245
|
+
...this.snapshotValue.qrUrl === void 0 ? {} : { qrUrl: this.snapshotValue.qrUrl }
|
|
23246
|
+
});
|
|
23247
|
+
await this.sleep(interval);
|
|
23248
|
+
}
|
|
23249
|
+
}
|
|
23250
|
+
settle(credentials, snapshot) {
|
|
23251
|
+
this.credentialsValue = credentials;
|
|
23252
|
+
this.settled = true;
|
|
23253
|
+
this.update(snapshot);
|
|
23254
|
+
const waiters = this.waiters;
|
|
23255
|
+
this.waiters = [];
|
|
23256
|
+
for (const waiter of waiters) waiter(credentials);
|
|
23257
|
+
}
|
|
23258
|
+
update(snapshot) {
|
|
23259
|
+
this.snapshotValue = snapshot;
|
|
23260
|
+
try {
|
|
23261
|
+
this.options.onChange?.(snapshot);
|
|
23262
|
+
} catch {
|
|
23263
|
+
}
|
|
23264
|
+
}
|
|
23265
|
+
};
|
|
23266
|
+
|
|
23267
|
+
// src/host/remote/weixin/channel.ts
|
|
23268
|
+
function messageOf3(error) {
|
|
23269
|
+
return error instanceof Error ? error.message : String(error);
|
|
23270
|
+
}
|
|
23271
|
+
var WeixinChannel = class {
|
|
23272
|
+
constructor(options) {
|
|
23273
|
+
this.options = options;
|
|
23274
|
+
this.transport = options.createTransport?.() ?? new WeixinTransport();
|
|
23275
|
+
this.login = new WeixinLogin({ transport: this.transport });
|
|
23276
|
+
}
|
|
23277
|
+
options;
|
|
23278
|
+
id = "weixin";
|
|
23279
|
+
transport;
|
|
23280
|
+
login;
|
|
23281
|
+
adapter;
|
|
23282
|
+
cursor;
|
|
23283
|
+
credentialsValue;
|
|
23284
|
+
phaseValue = "off";
|
|
23285
|
+
errorValue;
|
|
23286
|
+
/** Bumped by stop/logout so an in-flight scan result cannot reconnect. */
|
|
23287
|
+
generation = 0;
|
|
23288
|
+
get running() {
|
|
23289
|
+
return this.phaseValue === "running";
|
|
23290
|
+
}
|
|
23291
|
+
status() {
|
|
23292
|
+
const devices = this.options.bindings.list().filter((binding) => binding.channel === this.id).map((binding) => ({ chatId: binding.chatId, boundAt: binding.boundAt }));
|
|
23293
|
+
return {
|
|
23294
|
+
id: this.id,
|
|
23295
|
+
phase: this.phaseValue,
|
|
23296
|
+
login: this.login.snapshot(),
|
|
23297
|
+
devices,
|
|
23298
|
+
...this.credentialsValue?.botId === void 0 ? {} : { handle: this.credentialsValue.botId },
|
|
23299
|
+
...this.errorValue === void 0 ? {} : { error: this.errorValue }
|
|
23300
|
+
};
|
|
23301
|
+
}
|
|
23302
|
+
async start() {
|
|
23303
|
+
if (this.phaseValue === "running" || this.phaseValue === "unbound") return;
|
|
23304
|
+
this.cursor = createCursorStore({ filePath: join31(this.options.rootDir, "cursor.json") });
|
|
23305
|
+
const stored = await this.options.credentials.load().catch(() => void 0);
|
|
23306
|
+
if (stored === void 0) {
|
|
23307
|
+
this.phaseValue = "unbound";
|
|
23308
|
+
return;
|
|
23309
|
+
}
|
|
23310
|
+
await this.connect(stored);
|
|
23311
|
+
}
|
|
23312
|
+
/** Start a fresh QR login; connecting happens when the scan is confirmed. */
|
|
23313
|
+
async beginLogin() {
|
|
23314
|
+
if (this.phaseValue === "off" || this.phaseValue === "failed") await this.start();
|
|
23315
|
+
const generation = this.generation;
|
|
23316
|
+
const ticket = await this.login.begin();
|
|
23317
|
+
void this.login.wait().then((credentials) => {
|
|
23318
|
+
if (credentials !== void 0 && this.generation === generation) void this.connect(credentials);
|
|
23319
|
+
});
|
|
23320
|
+
return ticket;
|
|
23321
|
+
}
|
|
23322
|
+
cancelLogin() {
|
|
23323
|
+
this.login.cancel();
|
|
23324
|
+
if (this.phaseValue === "unbound" || this.phaseValue === "failed") {
|
|
23325
|
+
this.errorValue = void 0;
|
|
23326
|
+
this.phaseValue = "unbound";
|
|
23327
|
+
}
|
|
23328
|
+
}
|
|
23329
|
+
async logout() {
|
|
23330
|
+
this.generation += 1;
|
|
23331
|
+
this.adapter?.stop();
|
|
23332
|
+
this.adapter = void 0;
|
|
23333
|
+
this.login.cancel();
|
|
23334
|
+
this.credentialsValue = void 0;
|
|
23335
|
+
this.errorValue = void 0;
|
|
23336
|
+
await this.options.credentials.clear().catch((error) => {
|
|
23337
|
+
this.options.onError?.(error);
|
|
23338
|
+
});
|
|
23339
|
+
if (this.phaseValue !== "off") this.phaseValue = "unbound";
|
|
23340
|
+
}
|
|
23341
|
+
stop() {
|
|
23342
|
+
this.generation += 1;
|
|
23343
|
+
this.adapter?.stop();
|
|
23344
|
+
this.login.cancel();
|
|
23345
|
+
this.adapter = void 0;
|
|
23346
|
+
this.cursor = void 0;
|
|
23347
|
+
this.credentialsValue = void 0;
|
|
23348
|
+
this.phaseValue = "off";
|
|
23349
|
+
}
|
|
23350
|
+
/** Push a ready-made text; used for notices, not command replies. */
|
|
23351
|
+
async send(chatId, text3, _buttons) {
|
|
23352
|
+
const credentials = this.credentialsValue;
|
|
23353
|
+
const adapter = this.adapter;
|
|
23354
|
+
if (this.phaseValue !== "running" || credentials === void 0 || adapter === void 0) return;
|
|
23355
|
+
const chunks = splitForChannel(text3, this.options.capabilities.maxChars);
|
|
23356
|
+
for (const chunk of chunks) {
|
|
23357
|
+
const contextToken = adapter.contextFor(chatId);
|
|
23358
|
+
await this.transport.sendText(
|
|
23359
|
+
credentials,
|
|
23360
|
+
chatId,
|
|
23361
|
+
chunk,
|
|
23362
|
+
contextToken === void 0 ? {} : { contextToken }
|
|
23363
|
+
);
|
|
23364
|
+
}
|
|
23365
|
+
}
|
|
23366
|
+
contextFor(chatId) {
|
|
23367
|
+
return this.adapter?.contextFor(chatId);
|
|
23368
|
+
}
|
|
23369
|
+
async connect(credentials) {
|
|
23370
|
+
const generation = this.generation;
|
|
23371
|
+
this.credentialsValue = credentials;
|
|
23372
|
+
try {
|
|
23373
|
+
await this.options.credentials.save(credentials);
|
|
23374
|
+
} catch (error) {
|
|
23375
|
+
this.options.onError?.(error);
|
|
23376
|
+
}
|
|
23377
|
+
if (this.generation !== generation) return;
|
|
23378
|
+
const cursor = this.cursor;
|
|
23379
|
+
if (cursor === void 0) return;
|
|
23380
|
+
this.adapter?.stop();
|
|
23381
|
+
const adapter = new WeixinAdapter({
|
|
23382
|
+
transport: this.transport,
|
|
23383
|
+
controller: this.options.controller,
|
|
23384
|
+
bindings: this.options.bindings,
|
|
23385
|
+
credentials,
|
|
23386
|
+
capabilities: this.options.capabilities,
|
|
23387
|
+
cursor,
|
|
23388
|
+
refresh: this.options.refresh,
|
|
23389
|
+
...this.options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: this.options.emptyPageDelayMs },
|
|
23390
|
+
onError: (error) => this.options.onError?.(error),
|
|
23391
|
+
onFatal: (error) => {
|
|
23392
|
+
this.phaseValue = "failed";
|
|
23393
|
+
this.errorValue = messageOf3(error);
|
|
23394
|
+
}
|
|
23395
|
+
});
|
|
23396
|
+
this.adapter = adapter;
|
|
23397
|
+
this.phaseValue = "running";
|
|
23398
|
+
void adapter.run();
|
|
23399
|
+
}
|
|
23400
|
+
};
|
|
23401
|
+
|
|
23402
|
+
// src/host/remote/weixin/credentials.ts
|
|
23403
|
+
var CREDENTIAL_REF3 = "DSH_AGENT_ENHANCER_WEIXIN";
|
|
23404
|
+
function parse3(value) {
|
|
23405
|
+
let parsed;
|
|
23406
|
+
try {
|
|
23407
|
+
parsed = JSON.parse(value);
|
|
23408
|
+
} catch {
|
|
23409
|
+
return void 0;
|
|
23410
|
+
}
|
|
23411
|
+
if (parsed === null || typeof parsed !== "object") return void 0;
|
|
23412
|
+
const record2 = parsed;
|
|
23413
|
+
if (typeof record2.baseUrl !== "string" || typeof record2.token !== "string") return void 0;
|
|
23414
|
+
if (record2.baseUrl === "" || record2.token === "") return void 0;
|
|
23415
|
+
return {
|
|
23416
|
+
baseUrl: record2.baseUrl,
|
|
23417
|
+
token: record2.token,
|
|
23418
|
+
...typeof record2.botId === "string" ? { botId: record2.botId } : {},
|
|
23419
|
+
...typeof record2.userId === "string" ? { userId: record2.userId } : {}
|
|
23420
|
+
};
|
|
23421
|
+
}
|
|
23422
|
+
function provider3(ctx) {
|
|
23423
|
+
let service;
|
|
23424
|
+
try {
|
|
23425
|
+
service = ctx.get("credentials");
|
|
23426
|
+
} catch {
|
|
23427
|
+
return void 0;
|
|
23428
|
+
}
|
|
23429
|
+
if (service === void 0 || service === null || typeof service !== "object") return void 0;
|
|
23430
|
+
const candidate = service;
|
|
23431
|
+
if (typeof candidate.resolve !== "function" || typeof candidate.set !== "function") return void 0;
|
|
23432
|
+
return service;
|
|
23433
|
+
}
|
|
23434
|
+
function createWeixinCredentialStore(ctx) {
|
|
23435
|
+
if (provider3(ctx) === void 0) {
|
|
23436
|
+
return {
|
|
23437
|
+
async load() {
|
|
23438
|
+
return void 0;
|
|
23439
|
+
},
|
|
23440
|
+
async save() {
|
|
23441
|
+
throw new Error("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B\u51ED\u636E\u670D\u52A1\uFF0C\u65E0\u6CD5\u5B89\u5168\u4FDD\u5B58\u5FAE\u4FE1\u767B\u5F55");
|
|
23442
|
+
},
|
|
23443
|
+
async clear() {
|
|
23444
|
+
}
|
|
23445
|
+
};
|
|
23446
|
+
}
|
|
23447
|
+
return {
|
|
23448
|
+
async load() {
|
|
23449
|
+
const service = provider3(ctx);
|
|
23450
|
+
const resolved = await service?.resolve(CREDENTIAL_REF3);
|
|
23451
|
+
if (resolved === void 0) return void 0;
|
|
23452
|
+
return parse3(resolved.value);
|
|
23453
|
+
},
|
|
23454
|
+
async save(credentials) {
|
|
23455
|
+
const service = provider3(ctx);
|
|
23456
|
+
if (service === void 0) throw new Error("\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B\u51ED\u636E\u670D\u52A1");
|
|
23457
|
+
const payload = { baseUrl: credentials.baseUrl, token: credentials.token };
|
|
23458
|
+
if (credentials.botId !== void 0) payload.botId = credentials.botId;
|
|
23459
|
+
if (credentials.userId !== void 0) payload.userId = credentials.userId;
|
|
23460
|
+
await service.set(CREDENTIAL_REF3, JSON.stringify(payload));
|
|
23461
|
+
},
|
|
23462
|
+
async clear() {
|
|
23463
|
+
const service = provider3(ctx);
|
|
23464
|
+
await service?.unset(CREDENTIAL_REF3);
|
|
23465
|
+
}
|
|
23466
|
+
};
|
|
23467
|
+
}
|
|
23468
|
+
|
|
23469
|
+
// src/host/remote/hub.ts
|
|
23470
|
+
var TELEGRAM_CAPABILITIES = {
|
|
23471
|
+
buttons: true,
|
|
23472
|
+
editMessage: false,
|
|
23473
|
+
threads: false,
|
|
23474
|
+
media: "none",
|
|
23475
|
+
markdown: false,
|
|
23476
|
+
maxChars: 4e3,
|
|
23477
|
+
privateOnly: true
|
|
23478
|
+
};
|
|
23479
|
+
var FEISHU_CAPABILITIES = {
|
|
23480
|
+
buttons: true,
|
|
23481
|
+
editMessage: false,
|
|
23482
|
+
threads: false,
|
|
23483
|
+
media: "none",
|
|
23484
|
+
markdown: false,
|
|
23485
|
+
maxChars: 3e3,
|
|
23486
|
+
privateOnly: true
|
|
23487
|
+
};
|
|
23488
|
+
var RETRY_DELAY_MS = 5e3;
|
|
23489
|
+
var MAX_RETRIES = 12;
|
|
23490
|
+
function offStatus(id) {
|
|
23491
|
+
return { id, phase: "off", login: { phase: "idle", status: "idle" }, devices: [] };
|
|
23492
|
+
}
|
|
23493
|
+
function messageOf4(error) {
|
|
23494
|
+
return error instanceof Error ? error.message : String(error);
|
|
23495
|
+
}
|
|
23496
|
+
function clip2(value, max) {
|
|
23497
|
+
const text3 = value.trim();
|
|
23498
|
+
return text3.length <= max ? text3 : `${text3.slice(0, max - 1)}\u2026`;
|
|
23499
|
+
}
|
|
23500
|
+
var RemoteHub = class {
|
|
23501
|
+
constructor(options) {
|
|
23502
|
+
this.options = options;
|
|
23503
|
+
this.weixinCapabilities = options.weixinCapabilities ?? WEIXIN_CAPABILITIES;
|
|
23504
|
+
this.telegramCapabilities = options.telegramCapabilities ?? TELEGRAM_CAPABILITIES;
|
|
23505
|
+
this.feishuCapabilities = options.feishuCapabilities ?? FEISHU_CAPABILITIES;
|
|
23506
|
+
this.weixinCredentials = options.weixinCredentials ?? createWeixinCredentialStore(options.ctx);
|
|
23507
|
+
this.telegramCredentials = options.telegramCredentials ?? createTelegramCredentialStore(options.ctx);
|
|
23508
|
+
this.feishuCredentials = options.feishuCredentials ?? createFeishuCredentialStore(options.ctx);
|
|
23509
|
+
}
|
|
23510
|
+
options;
|
|
23511
|
+
bindings;
|
|
23512
|
+
controller;
|
|
23513
|
+
bridge;
|
|
23514
|
+
weixin;
|
|
23515
|
+
telegram;
|
|
23516
|
+
feishu;
|
|
23517
|
+
phaseValue = "stopped";
|
|
23518
|
+
errorValue;
|
|
23519
|
+
startingPromise;
|
|
23520
|
+
recoverable = false;
|
|
23521
|
+
retryTimer;
|
|
23522
|
+
retries = 0;
|
|
23523
|
+
generation = 0;
|
|
23524
|
+
weixinCapabilities;
|
|
23525
|
+
telegramCapabilities;
|
|
23526
|
+
feishuCapabilities;
|
|
23527
|
+
weixinCredentials;
|
|
23528
|
+
telegramCredentials;
|
|
23529
|
+
feishuCredentials;
|
|
23530
|
+
get running() {
|
|
23531
|
+
return this.anyRunning();
|
|
23532
|
+
}
|
|
23533
|
+
anyRunning() {
|
|
23534
|
+
return this.weixin?.running === true || this.telegram?.running === true || this.feishu?.running === true;
|
|
23535
|
+
}
|
|
23536
|
+
status() {
|
|
23537
|
+
const weixin = this.weixin;
|
|
23538
|
+
const telegram = this.telegram;
|
|
23539
|
+
const feishu = this.feishu;
|
|
23540
|
+
const started = weixin !== void 0 && telegram !== void 0 && feishu !== void 0;
|
|
23541
|
+
const channels = started ? [weixin.status(), telegram.status(), feishu.status()] : [offStatus("weixin"), offStatus("telegram"), offStatus("feishu")];
|
|
23542
|
+
let phase;
|
|
23543
|
+
if (!started) {
|
|
23544
|
+
phase = this.phaseValue === "failed" ? "failed" : this.phaseValue;
|
|
23545
|
+
} else if (channels.some((channel) => channel.phase === "running")) {
|
|
23546
|
+
phase = "running";
|
|
23547
|
+
} else if (channels.every((channel) => channel.phase === "failed")) {
|
|
23548
|
+
phase = "failed";
|
|
23549
|
+
} else {
|
|
23550
|
+
phase = "unbound";
|
|
23551
|
+
}
|
|
23552
|
+
return {
|
|
23553
|
+
phase,
|
|
23554
|
+
channels,
|
|
23555
|
+
tasks: this.controller?.tasks().length ?? 0,
|
|
23556
|
+
...this.errorValue === void 0 ? {} : { error: this.errorValue }
|
|
23557
|
+
};
|
|
23558
|
+
}
|
|
23559
|
+
async start() {
|
|
23560
|
+
if (this.startingPromise !== void 0) return this.startingPromise;
|
|
23561
|
+
const retryable = this.phaseValue === "failed" && this.recoverable;
|
|
23562
|
+
if (this.phaseValue !== "stopped" && !retryable) return this.status();
|
|
23563
|
+
this.startingPromise = this.startInternal().finally(() => {
|
|
23564
|
+
this.startingPromise = void 0;
|
|
23565
|
+
});
|
|
23566
|
+
return this.startingPromise;
|
|
23567
|
+
}
|
|
23568
|
+
async startInternal() {
|
|
23569
|
+
const generation = this.generation;
|
|
23570
|
+
this.recoverable = false;
|
|
23571
|
+
this.disposeChannels();
|
|
23572
|
+
this.bridge?.dispose();
|
|
23573
|
+
this.controller?.releasePending();
|
|
23574
|
+
this.bridge = void 0;
|
|
23575
|
+
this.controller = void 0;
|
|
23576
|
+
const bindings = this.bindings ?? new BindingStore({
|
|
23577
|
+
filePath: join32(this.options.rootDir, "bindings.json")
|
|
23578
|
+
});
|
|
23579
|
+
this.bindings = bindings;
|
|
23580
|
+
const ports = createHostPorts(this.options.ctx, {
|
|
23581
|
+
setPaused: this.options.setPaused,
|
|
23582
|
+
notify: (notice) => this.pushNotice(notice)
|
|
23583
|
+
});
|
|
23584
|
+
this.bridge = installRemoteHostBridge(this.options.ctx, {
|
|
23585
|
+
ports,
|
|
23586
|
+
capabilities: this.weixinCapabilities,
|
|
23587
|
+
shouldHold: () => bindings.list().length > 0 && this.anyRunning()
|
|
23588
|
+
});
|
|
23589
|
+
this.controller = this.bridge.controller;
|
|
23590
|
+
try {
|
|
23591
|
+
await this.bridge.refreshSessions();
|
|
23592
|
+
} catch (error) {
|
|
23593
|
+
this.phaseValue = "failed";
|
|
23594
|
+
this.errorValue = messageOf4(error);
|
|
23595
|
+
this.recoverable = true;
|
|
23596
|
+
this.scheduleRetry();
|
|
23597
|
+
return this.status();
|
|
23598
|
+
}
|
|
23599
|
+
if (this.generation !== generation) return this.status();
|
|
23600
|
+
this.errorValue = void 0;
|
|
23601
|
+
this.retries = 0;
|
|
23602
|
+
this.clearRetry();
|
|
23603
|
+
for (const binding of bindings.list()) {
|
|
23604
|
+
if (binding.focusSessionId !== void 0) {
|
|
23605
|
+
this.controller.setFocus(binding.chatId, binding.focusSessionId);
|
|
23606
|
+
}
|
|
23607
|
+
}
|
|
23608
|
+
this.weixin = new WeixinChannel({
|
|
23609
|
+
ctx: this.options.ctx,
|
|
23610
|
+
rootDir: this.options.rootDir,
|
|
23611
|
+
capabilities: this.weixinCapabilities,
|
|
23612
|
+
credentials: this.weixinCredentials,
|
|
23613
|
+
bindings,
|
|
23614
|
+
controller: this.controller,
|
|
23615
|
+
refresh: () => this.bridge?.refreshSessions() ?? Promise.resolve(0),
|
|
23616
|
+
...this.options.createWeixinTransport === void 0 ? {} : { createTransport: this.options.createWeixinTransport },
|
|
23617
|
+
...this.options.onError === void 0 ? {} : { onError: this.options.onError },
|
|
23618
|
+
...this.options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: this.options.emptyPageDelayMs }
|
|
23619
|
+
});
|
|
23620
|
+
this.telegram = new TelegramChannel({
|
|
23621
|
+
rootDir: this.options.rootDir,
|
|
23622
|
+
capabilities: this.telegramCapabilities,
|
|
23623
|
+
credentials: this.telegramCredentials,
|
|
23624
|
+
bindings,
|
|
23625
|
+
controller: this.controller,
|
|
23626
|
+
refresh: () => this.bridge?.refreshSessions() ?? Promise.resolve(0),
|
|
23627
|
+
...this.options.createTelegramTransport === void 0 ? {} : { createTransport: this.options.createTelegramTransport },
|
|
23628
|
+
...this.options.onError === void 0 ? {} : { onError: this.options.onError },
|
|
23629
|
+
...this.options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: this.options.emptyPageDelayMs }
|
|
23630
|
+
});
|
|
23631
|
+
this.feishu = new FeishuChannel({
|
|
23632
|
+
capabilities: this.feishuCapabilities,
|
|
23633
|
+
credentials: this.feishuCredentials,
|
|
23634
|
+
bindings,
|
|
23635
|
+
controller: this.controller,
|
|
23636
|
+
refresh: () => this.bridge?.refreshSessions() ?? Promise.resolve(0),
|
|
23637
|
+
...this.options.createFeishuTransport === void 0 ? {} : { createTransport: this.options.createFeishuTransport },
|
|
23638
|
+
...this.options.onError === void 0 ? {} : { onError: this.options.onError },
|
|
23639
|
+
...this.options.emptyPageDelayMs === void 0 ? {} : { emptyPageDelayMs: this.options.emptyPageDelayMs }
|
|
23640
|
+
});
|
|
23641
|
+
await Promise.all([this.weixin.start(), this.telegram.start(), this.feishu.start()]);
|
|
23642
|
+
this.refreshPhase();
|
|
23643
|
+
return this.status();
|
|
23644
|
+
}
|
|
23645
|
+
/** QR login for WeChat; connects when the scan is confirmed. */
|
|
23646
|
+
async beginWeixinLogin() {
|
|
23647
|
+
await this.start();
|
|
23648
|
+
if (this.weixin === void 0) throw new Error("\u8FDC\u7A0B\u63A7\u5236\u8FD8\u6CA1\u6709\u542F\u52A8");
|
|
23649
|
+
return this.weixin.beginLogin();
|
|
23650
|
+
}
|
|
23651
|
+
cancelWeixinLogin() {
|
|
23652
|
+
this.weixin?.cancelLogin();
|
|
23653
|
+
}
|
|
23654
|
+
/** Validate and connect the Telegram bot. */
|
|
23655
|
+
async connectTelegram(token) {
|
|
23656
|
+
await this.start();
|
|
23657
|
+
if (this.telegram === void 0) return { ok: false, error: "\u8FDC\u7A0B\u63A7\u5236\u8FD8\u6CA1\u6709\u542F\u52A8" };
|
|
23658
|
+
const result = await this.telegram.connect(token);
|
|
23659
|
+
this.refreshPhase();
|
|
23660
|
+
return result;
|
|
23661
|
+
}
|
|
23662
|
+
/** Validate the Feishu app credentials and open the long connection. */
|
|
23663
|
+
async connectFeishu(appId, appSecret) {
|
|
23664
|
+
await this.start();
|
|
23665
|
+
if (this.feishu === void 0) return { ok: false, error: "\u8FDC\u7A0B\u63A7\u5236\u8FD8\u6CA1\u6709\u542F\u52A8" };
|
|
23666
|
+
const result = await this.feishu.connect(appId, appSecret);
|
|
23667
|
+
this.refreshPhase();
|
|
23668
|
+
return result;
|
|
23669
|
+
}
|
|
23670
|
+
/** One-shot pairing code for the given channel. */
|
|
23671
|
+
issueBindCode(channel) {
|
|
23672
|
+
if (this.bindings === void 0) throw new Error("\u8FDC\u7A0B\u63A7\u5236\u8FD8\u6CA1\u6709\u542F\u52A8");
|
|
23673
|
+
return this.bindings.issueCode(void 0, channel);
|
|
23674
|
+
}
|
|
23675
|
+
devices(channel) {
|
|
23676
|
+
return (this.bindings?.list() ?? []).filter((binding) => channel === void 0 || binding.channel === channel).map((binding) => ({ chatId: binding.chatId, boundAt: binding.boundAt, channel: binding.channel }));
|
|
23677
|
+
}
|
|
23678
|
+
revoke(channel, chatId) {
|
|
23679
|
+
if (this.bindings === void 0) return 0;
|
|
23680
|
+
if (chatId !== void 0) {
|
|
23681
|
+
return this.bindings.unbind(chatId) ? 1 : 0;
|
|
23682
|
+
}
|
|
23683
|
+
const targets = this.bindings.list().filter((binding) => channel === void 0 || binding.channel === channel);
|
|
23684
|
+
for (const binding of targets) this.bindings.unbind(binding.chatId);
|
|
23685
|
+
return targets.length;
|
|
23686
|
+
}
|
|
23687
|
+
async logout(channel) {
|
|
23688
|
+
if (channel === void 0 || channel === "weixin") await this.weixin?.logout();
|
|
23689
|
+
if (channel === void 0 || channel === "telegram") await this.telegram?.logout();
|
|
23690
|
+
if (channel === void 0 || channel === "feishu") await this.feishu?.logout();
|
|
23691
|
+
if (!this.anyRunning()) this.controller?.releasePending();
|
|
23692
|
+
this.refreshPhase();
|
|
23693
|
+
}
|
|
23694
|
+
/** Session deleted: drop it from the board and clear any chat that followed it. */
|
|
23695
|
+
forgetSession(sessionId) {
|
|
23696
|
+
this.controller?.untrack(sessionId);
|
|
23697
|
+
for (const binding of this.bindings?.list() ?? []) {
|
|
23698
|
+
if (binding.focusSessionId === sessionId) this.bindings?.setFocus(binding.chatId, void 0);
|
|
23699
|
+
}
|
|
23700
|
+
}
|
|
23701
|
+
stop() {
|
|
23702
|
+
this.generation += 1;
|
|
23703
|
+
this.clearRetry();
|
|
23704
|
+
this.retries = 0;
|
|
23705
|
+
this.controller?.releasePending();
|
|
23706
|
+
this.disposeChannels();
|
|
23707
|
+
this.bridge?.dispose();
|
|
23708
|
+
this.bridge = void 0;
|
|
23709
|
+
this.controller = void 0;
|
|
23710
|
+
this.bindings = void 0;
|
|
23711
|
+
this.phaseValue = "stopped";
|
|
23712
|
+
this.errorValue = void 0;
|
|
23713
|
+
}
|
|
23714
|
+
disposeChannels() {
|
|
23715
|
+
this.weixin?.stop();
|
|
23716
|
+
this.telegram?.stop();
|
|
23717
|
+
this.feishu?.stop();
|
|
23718
|
+
this.weixin = void 0;
|
|
23719
|
+
this.telegram = void 0;
|
|
23720
|
+
this.feishu = void 0;
|
|
23721
|
+
}
|
|
23722
|
+
refreshPhase() {
|
|
23723
|
+
const channels = [this.weixin, this.telegram, this.feishu].filter((channel) => channel !== void 0);
|
|
23724
|
+
if (channels.some((channel) => channel.running)) {
|
|
23725
|
+
this.phaseValue = "running";
|
|
23726
|
+
this.errorValue = void 0;
|
|
23727
|
+
return;
|
|
23728
|
+
}
|
|
23729
|
+
this.phaseValue = channels.length > 0 && channels.every((channel) => channel.status().phase === "failed") ? "failed" : "unbound";
|
|
23730
|
+
}
|
|
23731
|
+
/** Send one notice to every paired chat on a channel that can answer. */
|
|
23732
|
+
pushNotice(notice) {
|
|
23733
|
+
const controller = this.controller;
|
|
23734
|
+
if (controller === void 0 || this.bindings === void 0) return;
|
|
23735
|
+
for (const binding of this.bindings.list()) {
|
|
23736
|
+
const channel = binding.channel === "weixin" ? this.weixin : binding.channel === "telegram" ? this.telegram : this.feishu;
|
|
23737
|
+
if (channel === void 0 || !channel.running) continue;
|
|
23738
|
+
const capabilities = binding.channel === "weixin" ? this.weixinCapabilities : binding.channel === "telegram" ? this.telegramCapabilities : this.feishuCapabilities;
|
|
23739
|
+
let text3 = controller.renderCard(notice.sessionId, capabilities);
|
|
23740
|
+
if (text3 === void 0) continue;
|
|
23741
|
+
if (notice.kind === "failed" && notice.error !== void 0) {
|
|
23742
|
+
text3 += `
|
|
23743
|
+
${clip2(notice.error, 300)}`;
|
|
23744
|
+
}
|
|
23745
|
+
if (notice.kind === "done" && notice.answer !== void 0) {
|
|
23746
|
+
const answer = clip2(notice.answer, 6e3);
|
|
23747
|
+
if (answer !== "") text3 += `
|
|
23748
|
+
|
|
23749
|
+
${answer}`;
|
|
23750
|
+
}
|
|
23751
|
+
const task = controller.tasks().find((entry) => entry.id === notice.sessionId);
|
|
23752
|
+
const pending = task?.pending;
|
|
23753
|
+
let buttons;
|
|
23754
|
+
if (capabilities.buttons) {
|
|
23755
|
+
const number = controller.numberOf(notice.sessionId);
|
|
23756
|
+
if (pending !== void 0) {
|
|
23757
|
+
if (pending.kind === "approval") {
|
|
23758
|
+
buttons = [
|
|
23759
|
+
{ label: "\u6279\u51C6", command: `\u6279\u51C6 ${pending.code}` },
|
|
23760
|
+
{ label: "\u62D2\u7EDD", command: `\u62D2\u7EDD ${pending.code}` },
|
|
23761
|
+
{ label: "\u8BE6\u60C5", command: number === void 0 ? "\u8BE6\u60C5" : `\u8BE6\u60C5 ${number}` }
|
|
23762
|
+
];
|
|
23763
|
+
} else if (pending.options !== void 0 && pending.options.length > 0) {
|
|
23764
|
+
buttons = pending.options.map((option) => ({
|
|
23765
|
+
label: option,
|
|
23766
|
+
command: `\u56DE\u7B54 ${pending.code} ${option}`
|
|
23767
|
+
}));
|
|
23768
|
+
}
|
|
23769
|
+
} else if (notice.kind === "done" || notice.kind === "failed") {
|
|
23770
|
+
buttons = [{ label: "\u8BE6\u60C5", command: number === void 0 ? "\u8BE6\u60C5" : `\u8BE6\u60C5 ${number}` }];
|
|
23771
|
+
}
|
|
23772
|
+
}
|
|
23773
|
+
void channel.send(binding.chatId, text3, buttons).catch((error) => this.options.onError?.(error));
|
|
23774
|
+
}
|
|
23775
|
+
}
|
|
23776
|
+
scheduleRetry() {
|
|
23777
|
+
if (this.retryTimer !== void 0 || !this.recoverable || this.retries >= MAX_RETRIES) return;
|
|
23778
|
+
this.retries += 1;
|
|
23779
|
+
const timer = setTimeout(() => {
|
|
23780
|
+
this.retryTimer = void 0;
|
|
23781
|
+
if (!this.recoverable || this.phaseValue === "stopped") return;
|
|
23782
|
+
void this.start().catch(() => {
|
|
23783
|
+
});
|
|
23784
|
+
}, RETRY_DELAY_MS);
|
|
23785
|
+
timer.unref?.();
|
|
23786
|
+
this.retryTimer = timer;
|
|
23787
|
+
}
|
|
23788
|
+
clearRetry() {
|
|
23789
|
+
if (this.retryTimer === void 0) return;
|
|
23790
|
+
clearTimeout(this.retryTimer);
|
|
23791
|
+
this.retryTimer = void 0;
|
|
23792
|
+
}
|
|
23793
|
+
};
|
|
23794
|
+
|
|
23795
|
+
// src/host/index.ts
|
|
23796
|
+
function hostBrowserPreference(value) {
|
|
23797
|
+
return coerceBrowserAgentBrowserForPlatform(
|
|
23798
|
+
resolveBrowserAgentBrowser(value),
|
|
23799
|
+
process.platform
|
|
23800
|
+
);
|
|
23801
|
+
}
|
|
23802
|
+
var name = PLUGIN_ID;
|
|
23803
|
+
var inject = [
|
|
23804
|
+
"llm",
|
|
23805
|
+
"sessions",
|
|
23806
|
+
"agents",
|
|
23807
|
+
"sessionProjections",
|
|
23808
|
+
"agentDefaultModel",
|
|
23809
|
+
"fs",
|
|
23810
|
+
"tools",
|
|
23811
|
+
"tokenMeter",
|
|
23812
|
+
"typert",
|
|
23813
|
+
"typertGateway",
|
|
23814
|
+
// Chat `/compact` → compaction.compactNow; commands kept as fallback.
|
|
23815
|
+
"commands",
|
|
23816
|
+
// Session delete: registry detach + durable workspace/global domain writes.
|
|
23817
|
+
"workspaceRegistry",
|
|
23818
|
+
"storageDomain"
|
|
23819
|
+
];
|
|
23820
|
+
var Config = z5.object({
|
|
23821
|
+
historyEnabled: z5.boolean().default(true).volatile(),
|
|
23822
|
+
optimizeEnabled: z5.boolean().default(true).volatile(),
|
|
23823
|
+
predictEnabled: z5.boolean().default(true).volatile(),
|
|
23824
|
+
quoteEnabled: z5.boolean().default(true).volatile(),
|
|
23825
|
+
rollbackEnabled: z5.boolean().default(true).volatile(),
|
|
23826
|
+
contextInspectEnabled: z5.boolean().default(true).volatile(),
|
|
23827
|
+
usageEnabled: z5.boolean().default(true).volatile(),
|
|
23828
|
+
sessionDeleteEnabled: z5.boolean().default(true).volatile(),
|
|
23829
|
+
fileEditEnabled: z5.boolean().default(true).volatile(),
|
|
23830
|
+
softPauseEnabled: z5.boolean().default(true).volatile(),
|
|
23831
|
+
runAlertsEnabled: z5.boolean().default(true).volatile(),
|
|
23832
|
+
/** Coerced via resolveRunAlertsLevel in readSettings (`hidden` | `unfocused` | `always`). */
|
|
23833
|
+
runAlertsLevel: z5.string().default("unfocused").volatile(),
|
|
23834
|
+
/** High-risk; default off. */
|
|
23835
|
+
browserAgentEnabled: z5.boolean().default(false).volatile(),
|
|
23836
|
+
browserAgentBrowser: z5.string().default("auto").volatile(),
|
|
23837
|
+
/** Debug tools (network / console / emulate); default off, gated per tool. */
|
|
23838
|
+
browserAgentDebugTools: z5.boolean().default(false).volatile(),
|
|
23839
|
+
/** "Show me" recorder; observes user actions in the bound tab, default off. */
|
|
23840
|
+
browserAgentDemonstrate: z5.boolean().default(false).volatile(),
|
|
23841
|
+
/** Close idle agent tabs after ~10 min; coerced via resolveBrowserAgentIdleClose. */
|
|
23842
|
+
browserAgentIdleClose: z5.union([z5.boolean(), z5.string()]).default("10m").volatile(),
|
|
23843
|
+
/** Unattended-run grant: bounded minutes (default 20). */
|
|
23844
|
+
browserAgentUnattendedMinutes: z5.number().default(BROWSER_AGENT_UNATTENDED.minutes.default).volatile(),
|
|
23845
|
+
/** Unattended-run grant: bounded action budget (default 30). */
|
|
23846
|
+
browserAgentUnattendedActions: z5.number().default(BROWSER_AGENT_UNATTENDED.actions.default).volatile(),
|
|
23847
|
+
/** Default off; embeds official web chat + import to work. */
|
|
23848
|
+
webChatBridgeEnabled: z5.boolean().default(true).volatile(),
|
|
23849
|
+
/** WeChat + Telegram remote control; on by default, inert until a chat is paired. */
|
|
23850
|
+
remoteControlEnabled: z5.boolean().default(true).volatile(),
|
|
23851
|
+
instructionsSkillsEnabled: z5.boolean().default(true).volatile(),
|
|
23852
|
+
mcpConnectorsEnabled: z5.boolean().default(true).volatile(),
|
|
23853
|
+
// Empty provider/model = follow the current Desktop session model.
|
|
23854
|
+
optimizeProvider: z5.string().default("").volatile(),
|
|
23855
|
+
optimizeModel: z5.string().default("").volatile(),
|
|
23856
|
+
optimizeReasoningEffort: z5.string().default("").volatile(),
|
|
23857
|
+
predictProvider: z5.string().default("").volatile(),
|
|
23858
|
+
predictModel: z5.string().default("").volatile(),
|
|
23859
|
+
predictReasoningEffort: z5.string().default("").volatile(),
|
|
23860
|
+
compactProvider: z5.string().default("").volatile(),
|
|
23861
|
+
compactModel: z5.string().default("").volatile(),
|
|
23862
|
+
compactReasoningEffort: z5.string().default("").volatile(),
|
|
23863
|
+
autoClassifierEnabled: z5.boolean().default(false).volatile(),
|
|
23864
|
+
autoInstantProvider: z5.string().default("").volatile(),
|
|
23865
|
+
autoInstantModel: z5.string().default("").volatile(),
|
|
23866
|
+
autoInstantReasoningEffort: z5.string().default("").volatile(),
|
|
23867
|
+
autoThinkingProvider: z5.string().default("").volatile(),
|
|
23868
|
+
autoThinkingModel: z5.string().default("").volatile(),
|
|
23869
|
+
autoThinkingReasoningEffort: z5.string().default("").volatile(),
|
|
23870
|
+
autoProProvider: z5.string().default("").volatile(),
|
|
23871
|
+
autoProModel: z5.string().default("").volatile(),
|
|
23872
|
+
autoProReasoningEffort: z5.string().default("").volatile(),
|
|
23873
|
+
autoClassifierProvider: z5.string().default("").volatile(),
|
|
23874
|
+
autoClassifierModel: z5.string().default("").volatile(),
|
|
23875
|
+
autoClassifierReasoningEffort: z5.string().default("").volatile()
|
|
23876
|
+
});
|
|
23877
|
+
var hostContribution = {
|
|
23878
|
+
package: PACKAGE_NAME,
|
|
23879
|
+
face: "host",
|
|
23880
|
+
schemas: [],
|
|
23881
|
+
model: { services: [], events: [], objects: [] },
|
|
23882
|
+
invocations: [...remoteInfo.descriptors, ...checkpointRemoteInfo.descriptors]
|
|
23883
|
+
};
|
|
23884
|
+
var AgentEnhancerService = class extends TypertRemoteService {
|
|
23885
|
+
constructor(ctx, models, usage = {
|
|
23886
|
+
async summarize(range) {
|
|
23887
|
+
return summarizeUsage([], range, Date.now());
|
|
23888
|
+
}
|
|
23889
|
+
}, balances = {
|
|
23890
|
+
async get() {
|
|
23891
|
+
return {
|
|
23892
|
+
account: { source: "account", status: "signed-out" },
|
|
23893
|
+
apiKey: { source: "api-key", status: "no-key" }
|
|
23894
|
+
};
|
|
23895
|
+
}
|
|
23896
|
+
}, sessionCleanup = new SessionCleanupRegistry(), extraFolders = createExtraFoldersStore(
|
|
23897
|
+
join33(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
|
|
23898
|
+
), softPause = new SoftPauseGate(), softPauseEnabled = () => true, installLedgerRoot = void 0, mcpHost = null, browserAgent = null, browserAgentSettings = () => ({
|
|
23899
|
+
enabled: false,
|
|
23900
|
+
browser: "auto",
|
|
23901
|
+
demonstrate: false
|
|
23902
|
+
}), setBrowserAgentBrowser = () => void 0, browserAgentProfileDir = defaultBrowserAgentProfileDir(
|
|
23903
|
+
join33(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
|
|
23904
|
+
), remoteControl = () => null) {
|
|
23905
|
+
super(ctx, "agentEnhancer");
|
|
23906
|
+
this.models = models;
|
|
23907
|
+
this.usage = usage;
|
|
23908
|
+
this.balances = balances;
|
|
23909
|
+
this.sessionCleanup = sessionCleanup;
|
|
20186
23910
|
this.extraFolders = extraFolders;
|
|
20187
23911
|
this.softPause = softPause;
|
|
20188
23912
|
this.softPauseEnabled = softPauseEnabled;
|
|
@@ -20192,6 +23916,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
20192
23916
|
this.browserAgentSettings = browserAgentSettings;
|
|
20193
23917
|
this.setBrowserAgentBrowser = setBrowserAgentBrowser;
|
|
20194
23918
|
this.browserAgentProfileDir = browserAgentProfileDir;
|
|
23919
|
+
this.remoteControl = remoteControl;
|
|
20195
23920
|
}
|
|
20196
23921
|
models;
|
|
20197
23922
|
usage;
|
|
@@ -20206,6 +23931,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
20206
23931
|
browserAgentSettings;
|
|
20207
23932
|
setBrowserAgentBrowser;
|
|
20208
23933
|
browserAgentProfileDir;
|
|
23934
|
+
remoteControl;
|
|
20209
23935
|
async browserSnapshotNow() {
|
|
20210
23936
|
const settings = this.browserAgentSettings();
|
|
20211
23937
|
const driverStatus = this.browserAgent?.driverStatus();
|
|
@@ -20440,7 +24166,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
20440
24166
|
}
|
|
20441
24167
|
}
|
|
20442
24168
|
webChatPluginDataRoot() {
|
|
20443
|
-
return this.installLedgerRoot ??
|
|
24169
|
+
return this.installLedgerRoot ?? join33(homedir5(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
|
|
20444
24170
|
}
|
|
20445
24171
|
/** User-level web chat guest login snapshot (non-HttpOnly storage only). */
|
|
20446
24172
|
async loadWebChatLoginSnapshot(_request, signal) {
|
|
@@ -20843,20 +24569,118 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
20843
24569
|
this.assertOwner();
|
|
20844
24570
|
if (!this.softPauseEnabled()) {
|
|
20845
24571
|
if (this.softPause.isEngaged(request.sessionId)) this.softPause.release(request.sessionId);
|
|
20846
|
-
return { sessionId: request.sessionId, engaged: false };
|
|
24572
|
+
return { sessionId: request.sessionId, engaged: false, treeRunning: false };
|
|
20847
24573
|
}
|
|
20848
|
-
return {
|
|
24574
|
+
return {
|
|
24575
|
+
sessionId: request.sessionId,
|
|
24576
|
+
engaged: this.softPause.isEngaged(request.sessionId),
|
|
24577
|
+
treeRunning: this.softPauseTreeRunning(request.sessionId)
|
|
24578
|
+
};
|
|
20849
24579
|
}
|
|
20850
24580
|
/** Engage or release the soft-pause gate (no new user turn on resume). */
|
|
20851
24581
|
async softPauseSet(request) {
|
|
20852
24582
|
this.assertOwner();
|
|
20853
24583
|
if (!this.softPauseEnabled()) {
|
|
20854
24584
|
this.softPause.release(request.sessionId);
|
|
20855
|
-
return { sessionId: request.sessionId, engaged: false };
|
|
24585
|
+
return { sessionId: request.sessionId, engaged: false, treeRunning: false };
|
|
20856
24586
|
}
|
|
20857
24587
|
if (request.engaged) this.softPause.engage(request.sessionId);
|
|
20858
24588
|
else this.softPause.release(request.sessionId);
|
|
20859
|
-
return {
|
|
24589
|
+
return {
|
|
24590
|
+
sessionId: request.sessionId,
|
|
24591
|
+
engaged: this.softPause.isEngaged(request.sessionId),
|
|
24592
|
+
treeRunning: this.softPauseTreeRunning(request.sessionId)
|
|
24593
|
+
};
|
|
24594
|
+
}
|
|
24595
|
+
requireRemoteControl() {
|
|
24596
|
+
const remote = this.remoteControl();
|
|
24597
|
+
if (remote === null) {
|
|
24598
|
+
throw new RemoteError2("agent-enhancer/failed", "\u8FDC\u7A0B\u63A7\u5236\u672A\u542F\u7528\uFF0C\u8BF7\u5148\u5728\u8BBE\u7F6E\u91CC\u5F00\u542F", {
|
|
24599
|
+
code: "FILE_EDIT_FAILED"
|
|
24600
|
+
});
|
|
24601
|
+
}
|
|
24602
|
+
return remote;
|
|
24603
|
+
}
|
|
24604
|
+
/** Channel status, pairing and devices. Never returns a bot token. */
|
|
24605
|
+
async remoteStatus(_request) {
|
|
24606
|
+
this.assertOwner();
|
|
24607
|
+
const remote = this.requireRemoteControl();
|
|
24608
|
+
void remote.start().catch(() => {
|
|
24609
|
+
});
|
|
24610
|
+
const status = remote.status();
|
|
24611
|
+
return { ...status, channels: status.channels.map((channel) => ({ ...channel, devices: [...channel.devices] })) };
|
|
24612
|
+
}
|
|
24613
|
+
/** Show a fresh WeChat QR. Connecting happens on confirmation, not here. */
|
|
24614
|
+
async remoteLoginBegin(_request) {
|
|
24615
|
+
this.assertOwner();
|
|
24616
|
+
try {
|
|
24617
|
+
const ticket = await this.requireRemoteControl().beginWeixinLogin();
|
|
24618
|
+
return { ok: true, ticket: ticket.ticket, qrUrl: ticket.qrUrl };
|
|
24619
|
+
} catch (error) {
|
|
24620
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
24621
|
+
}
|
|
24622
|
+
}
|
|
24623
|
+
async remoteLoginCancel(_request) {
|
|
24624
|
+
this.assertOwner();
|
|
24625
|
+
this.requireRemoteControl().cancelWeixinLogin();
|
|
24626
|
+
return { ok: true };
|
|
24627
|
+
}
|
|
24628
|
+
/** One-shot code a chat types once to become a control device. */
|
|
24629
|
+
async remoteBindCode(request) {
|
|
24630
|
+
this.assertOwner();
|
|
24631
|
+
try {
|
|
24632
|
+
const issued = this.requireRemoteControl().issueBindCode(request.channel);
|
|
24633
|
+
return { ok: true, code: issued.code, expiresAt: issued.expiresAt };
|
|
24634
|
+
} catch (error) {
|
|
24635
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
24636
|
+
}
|
|
24637
|
+
}
|
|
24638
|
+
async remoteRevoke(request) {
|
|
24639
|
+
this.assertOwner();
|
|
24640
|
+
try {
|
|
24641
|
+
const revoked = this.requireRemoteControl().revoke(request.channel, request.chatId);
|
|
24642
|
+
return { ok: true, revoked };
|
|
24643
|
+
} catch (error) {
|
|
24644
|
+
return { ok: false, revoked: 0, error: error instanceof Error ? error.message : String(error) };
|
|
24645
|
+
}
|
|
24646
|
+
}
|
|
24647
|
+
/** Forget a bot login; bound chats stay remembered. */
|
|
24648
|
+
async remoteLogout(request) {
|
|
24649
|
+
this.assertOwner();
|
|
24650
|
+
await this.requireRemoteControl().logout(request.channel);
|
|
24651
|
+
return { ok: true };
|
|
24652
|
+
}
|
|
24653
|
+
/** Validate and connect a Telegram bot token. */
|
|
24654
|
+
async remoteTelegramConnect(request) {
|
|
24655
|
+
this.assertOwner();
|
|
24656
|
+
try {
|
|
24657
|
+
return await this.requireRemoteControl().connectTelegram(request.token);
|
|
24658
|
+
} catch (error) {
|
|
24659
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
24660
|
+
}
|
|
24661
|
+
}
|
|
24662
|
+
/** Validate Feishu app credentials and open the long connection. */
|
|
24663
|
+
async remoteFeishuConnect(request) {
|
|
24664
|
+
this.assertOwner();
|
|
24665
|
+
try {
|
|
24666
|
+
return await this.requireRemoteControl().connectFeishu(request.appId, request.appSecret);
|
|
24667
|
+
} catch (error) {
|
|
24668
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
24669
|
+
}
|
|
24670
|
+
}
|
|
24671
|
+
/**
|
|
24672
|
+
* Whether a live agent in this session's subagent tree is still running.
|
|
24673
|
+
* The control has to stay reachable after the parent's turn ends: the child
|
|
24674
|
+
* it spawned keeps working, and that is exactly what a pause should stop.
|
|
24675
|
+
*/
|
|
24676
|
+
softPauseTreeRunning(sessionId) {
|
|
24677
|
+
const agents = this.ctx.agents;
|
|
24678
|
+
if (typeof agents?.list !== "function") return false;
|
|
24679
|
+
try {
|
|
24680
|
+
return isTreeRunning(sessionId, agents.list(), sessionStore(this.ctx));
|
|
24681
|
+
} catch {
|
|
24682
|
+
return false;
|
|
24683
|
+
}
|
|
20860
24684
|
}
|
|
20861
24685
|
/** Desktop OS notification for run alerts (Electron / Windows Action Center). */
|
|
20862
24686
|
async showOsNotification(request) {
|
|
@@ -21056,14 +24880,14 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
21056
24880
|
}
|
|
21057
24881
|
};
|
|
21058
24882
|
function resolveCheckpointRoot(dshHome2) {
|
|
21059
|
-
const base =
|
|
21060
|
-
const nextPkg =
|
|
21061
|
-
const next =
|
|
21062
|
-
const prev =
|
|
24883
|
+
const base = join33(dshHome2, "profiles", "desktop", "plugin-data");
|
|
24884
|
+
const nextPkg = join33(base, PACKAGE_NAME);
|
|
24885
|
+
const next = join33(nextPkg, "checkpoint");
|
|
24886
|
+
const prev = join33(base, LEGACY_PACKAGE_NAME, "checkpoint");
|
|
21063
24887
|
if (!existsSync20(next) && existsSync20(prev)) {
|
|
21064
|
-
|
|
21065
|
-
|
|
21066
|
-
const prevPkg =
|
|
24888
|
+
mkdirSync15(nextPkg, { recursive: true });
|
|
24889
|
+
renameSync11(prev, next);
|
|
24890
|
+
const prevPkg = join33(base, LEGACY_PACKAGE_NAME);
|
|
21067
24891
|
try {
|
|
21068
24892
|
if (existsSync20(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
|
|
21069
24893
|
} catch {
|
|
@@ -21143,6 +24967,7 @@ function readSettings(config) {
|
|
|
21143
24967
|
browserAgentUnattendedMinutes: config.browserAgentUnattendedMinutes.get(),
|
|
21144
24968
|
browserAgentUnattendedActions: config.browserAgentUnattendedActions.get(),
|
|
21145
24969
|
webChatBridgeEnabled: config.webChatBridgeEnabled.get(),
|
|
24970
|
+
remoteControlEnabled: config.remoteControlEnabled.get(),
|
|
21146
24971
|
instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
|
|
21147
24972
|
mcpConnectorsEnabled: config.mcpConnectorsEnabled.get(),
|
|
21148
24973
|
optimizeProvider: config.optimizeProvider.get(),
|
|
@@ -21173,9 +24998,9 @@ function apply(ctx, config) {
|
|
|
21173
24998
|
const settings = () => readSettings(config);
|
|
21174
24999
|
const models = new AuxiliaryModels(ctx, settings);
|
|
21175
25000
|
installAutoSessionRoute(ctx, { settings });
|
|
21176
|
-
const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ??
|
|
21177
|
-
const pluginDataPackageRoot =
|
|
21178
|
-
const usage = new UsageLedger(
|
|
25001
|
+
const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join33(homedir5(), ".dsh"));
|
|
25002
|
+
const pluginDataPackageRoot = join33(storageRoot, "..");
|
|
25003
|
+
const usage = new UsageLedger(join33(storageRoot, "..", "usage"), (message) => {
|
|
21179
25004
|
ctx.logger.warn(message);
|
|
21180
25005
|
});
|
|
21181
25006
|
const balancesFacade = (() => {
|
|
@@ -21205,12 +25030,12 @@ function apply(ctx, config) {
|
|
|
21205
25030
|
})();
|
|
21206
25031
|
installUsageObserver(ctx, usage);
|
|
21207
25032
|
const store = new CheckpointStore(storageRoot);
|
|
21208
|
-
const cutStore = new SessionCutStore(
|
|
25033
|
+
const cutStore = new SessionCutStore(join33(storageRoot, "cuts"));
|
|
21209
25034
|
const cutCache = /* @__PURE__ */ new Map();
|
|
21210
25035
|
const sessionCleanup = new SessionCleanupRegistry();
|
|
21211
25036
|
sessionCleanup.register(createCheckpointCleaner({ store, cutStore, storageRoot }));
|
|
21212
|
-
sessionCleanup.register(createContextExcludeCleaner(
|
|
21213
|
-
const extraFoldersStore = createExtraFoldersStore(
|
|
25037
|
+
sessionCleanup.register(createContextExcludeCleaner(join33(storageRoot, "..")));
|
|
25038
|
+
const extraFoldersStore = createExtraFoldersStore(join33(storageRoot, "..", "extra-folders"));
|
|
21214
25039
|
const softPauseGate = new SoftPauseGate();
|
|
21215
25040
|
const mcpStore = createMcpConnectorsStore(mcpConnectorsRoot(pluginDataPackageRoot));
|
|
21216
25041
|
const mcpRuntime = new McpConnectorRuntime(ctx, mcpStore);
|
|
@@ -21236,7 +25061,7 @@ function apply(ctx, config) {
|
|
|
21236
25061
|
minutes: settings().browserAgentUnattendedMinutes,
|
|
21237
25062
|
actions: settings().browserAgentUnattendedActions
|
|
21238
25063
|
}),
|
|
21239
|
-
recipes: new DemoRecipeStore(
|
|
25064
|
+
recipes: new DemoRecipeStore(join33(pluginDataPackageRoot, "demo-recipes.json")),
|
|
21240
25065
|
profileRoot: pluginDataPackageRoot,
|
|
21241
25066
|
softPause: softPauseGate,
|
|
21242
25067
|
softPauseEnabled: () => settings().softPauseEnabled,
|
|
@@ -21257,6 +25082,42 @@ function apply(ctx, config) {
|
|
|
21257
25082
|
softPauseGate.release(sessionId);
|
|
21258
25083
|
}
|
|
21259
25084
|
});
|
|
25085
|
+
const remoteControlLive = { enabled: settings().remoteControlEnabled };
|
|
25086
|
+
const remoteHub = new RemoteHub({
|
|
25087
|
+
ctx,
|
|
25088
|
+
rootDir: join33(pluginDataPackageRoot, "remote"),
|
|
25089
|
+
// Same pause as the desktop control: hold the next model call, let tools finish.
|
|
25090
|
+
setPaused: async (sessionId, paused) => {
|
|
25091
|
+
if (!settings().softPauseEnabled) return;
|
|
25092
|
+
if (paused) softPauseGate.engage(sessionId);
|
|
25093
|
+
else softPauseGate.release(sessionId);
|
|
25094
|
+
},
|
|
25095
|
+
onError: (error) => {
|
|
25096
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
25097
|
+
ctx.logger.warn(`agent-enhancer: remote control: ${detail}`);
|
|
25098
|
+
}
|
|
25099
|
+
});
|
|
25100
|
+
let remoteRunning = false;
|
|
25101
|
+
const syncRemoteControl = async (enabled) => {
|
|
25102
|
+
remoteControlLive.enabled = enabled;
|
|
25103
|
+
if (enabled === remoteRunning) return;
|
|
25104
|
+
remoteRunning = enabled;
|
|
25105
|
+
try {
|
|
25106
|
+
if (enabled) await remoteHub.start();
|
|
25107
|
+
else remoteHub.stop();
|
|
25108
|
+
} catch (error) {
|
|
25109
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
25110
|
+
ctx.logger.warn(`agent-enhancer: remote control start failed: ${detail}`);
|
|
25111
|
+
}
|
|
25112
|
+
};
|
|
25113
|
+
void syncRemoteControl(settings().remoteControlEnabled);
|
|
25114
|
+
sessionCleanup.register({
|
|
25115
|
+
id: "remote-control",
|
|
25116
|
+
label: "Remote control focus",
|
|
25117
|
+
async purge(sessionId) {
|
|
25118
|
+
remoteHub.forgetSession(sessionId);
|
|
25119
|
+
}
|
|
25120
|
+
});
|
|
21260
25121
|
new AgentEnhancerService(
|
|
21261
25122
|
ctx,
|
|
21262
25123
|
models,
|
|
@@ -21289,7 +25150,8 @@ function apply(ctx, config) {
|
|
|
21289
25150
|
(browser) => {
|
|
21290
25151
|
browserAgentLive.browser = hostBrowserPreference(browser);
|
|
21291
25152
|
},
|
|
21292
|
-
browserAgentProfileDir
|
|
25153
|
+
browserAgentProfileDir,
|
|
25154
|
+
() => remoteControlLive.enabled ? remoteHub : null
|
|
21293
25155
|
);
|
|
21294
25156
|
ctx.effect(() => {
|
|
21295
25157
|
const unsubscribe = ctx.on("internal/update", (resolvedConfig, next) => {
|
|
@@ -21304,6 +25166,7 @@ function apply(ctx, config) {
|
|
|
21304
25166
|
browserAgentLive.enabled = cfg.browserAgentEnabled.get();
|
|
21305
25167
|
browserAgentLive.browser = hostBrowserPreference(cfg.browserAgentBrowser.get());
|
|
21306
25168
|
browserAgentLive.demonstrate = cfg.browserAgentDemonstrate.get();
|
|
25169
|
+
void syncRemoteControl(cfg.remoteControlEnabled.get());
|
|
21307
25170
|
browserAgent.refresh();
|
|
21308
25171
|
if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
|
|
21309
25172
|
void browserAgent.alignToPreference().catch((error) => {
|
|
@@ -21317,6 +25180,7 @@ function apply(ctx, config) {
|
|
|
21317
25180
|
unsubscribe();
|
|
21318
25181
|
await mcpRuntime.disposeAll();
|
|
21319
25182
|
await browserAgent.dispose();
|
|
25183
|
+
remoteHub.stop();
|
|
21320
25184
|
};
|
|
21321
25185
|
});
|
|
21322
25186
|
installSoftPause(ctx, {
|