@ashx-j/lunr 0.2.24 → 0.2.25
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/CHANGELOG.md +9 -1
- package/dist/gateway/adapters/discord.d.ts.map +1 -1
- package/dist/gateway/adapters/discord.js +2 -7
- package/dist/gateway/adapters/discord.js.map +1 -1
- package/dist/gateway/adapters/telegram.d.ts.map +1 -1
- package/dist/gateway/adapters/telegram.js +7 -0
- package/dist/gateway/adapters/telegram.js.map +1 -1
- package/dist/gateway/agent-bridge.d.ts +4 -1
- package/dist/gateway/agent-bridge.d.ts.map +1 -1
- package/dist/gateway/agent-bridge.js +57 -17
- package/dist/gateway/agent-bridge.js.map +1 -1
- package/dist/gateway/buttons.d.ts.map +1 -1
- package/dist/gateway/buttons.js +29 -19
- package/dist/gateway/buttons.js.map +1 -1
- package/dist/gateway/commands.d.ts +2 -0
- package/dist/gateway/commands.d.ts.map +1 -1
- package/dist/gateway/commands.js +39 -18
- package/dist/gateway/commands.js.map +1 -1
- package/dist/gateway/config.d.ts +1 -0
- package/dist/gateway/config.d.ts.map +1 -1
- package/dist/gateway/config.js +2 -0
- package/dist/gateway/config.js.map +1 -1
- package/dist/gateway/cron.d.ts +1 -1
- package/dist/gateway/cron.d.ts.map +1 -1
- package/dist/gateway/cron.js +2 -2
- package/dist/gateway/cron.js.map +1 -1
- package/dist/gateway/index.d.ts.map +1 -1
- package/dist/gateway/index.js +26 -26
- package/dist/gateway/index.js.map +1 -1
- package/dist/gateway/mobile-commands.d.ts.map +1 -1
- package/dist/gateway/mobile-commands.js +3 -3
- package/dist/gateway/mobile-commands.js.map +1 -1
- package/dist/gateway/presenter.d.ts +12 -1
- package/dist/gateway/presenter.d.ts.map +1 -1
- package/dist/gateway/presenter.js +146 -48
- package/dist/gateway/presenter.js.map +1 -1
- package/dist/gateway/router.d.ts +5 -5
- package/dist/gateway/router.d.ts.map +1 -1
- package/dist/gateway/router.js +95 -41
- package/dist/gateway/router.js.map +1 -1
- package/dist/gateway/service.d.ts.map +1 -1
- package/dist/gateway/service.js +13 -4
- package/dist/gateway/service.js.map +1 -1
- package/dist/gateway/setup.d.ts +5 -0
- package/dist/gateway/setup.d.ts.map +1 -1
- package/dist/gateway/setup.js +98 -42
- package/dist/gateway/setup.js.map +1 -1
- package/dist/gateway/stream.d.ts +6 -5
- package/dist/gateway/stream.d.ts.map +1 -1
- package/dist/gateway/stream.js +24 -11
- package/dist/gateway/stream.js.map +1 -1
- package/dist/node-runtime/{agent-session-services-IEF7LQWD.js → agent-session-services-YXXFCP5J.js} +7 -6
- package/dist/node-runtime/{builtin-extensions-EBAWTH4M.js → builtin-extensions-ZLAX7TUH.js} +1 -1
- package/dist/node-runtime/{chunk-OF7PWMG4.js → chunk-2HHLJWGD.js} +3 -87
- package/dist/node-runtime/{chunk-VWCE2HSZ.js → chunk-2HMIRK7W.js} +4 -4
- package/dist/node-runtime/{chunk-K5AGHH57.js → chunk-3XPLBUEM.js} +1 -1
- package/dist/node-runtime/{chunk-RORY2HMJ.js → chunk-6XL67VVY.js} +1 -1
- package/dist/node-runtime/chunk-7S3T6YEA.js +97 -0
- package/dist/node-runtime/{chunk-R3K2F5GI.js → chunk-B4HP6ZWM.js} +2 -0
- package/dist/node-runtime/{chunk-YVI6L6LU.js → chunk-E4D3IGP2.js} +38 -22
- package/dist/node-runtime/{chunk-5Q3EHOHI.js → chunk-IJIFHRTB.js} +14 -12
- package/dist/node-runtime/{chunk-Y73WPE6S.js → chunk-KWIYUUZK.js} +63 -37
- package/dist/node-runtime/{chunk-F4FLTQKV.js → chunk-LQP3RB67.js} +184 -1527
- package/dist/node-runtime/{chunk-FU6OODRZ.js → chunk-NRKGMJYU.js} +1 -1
- package/dist/node-runtime/{chunk-IGV54Q5V.js → chunk-QTU6AKNJ.js} +128 -63
- package/dist/node-runtime/{chunk-L3LX4SNR.js → chunk-RC7DMV45.js} +5 -5
- package/dist/node-runtime/{chunk-UWPJL22I.js → chunk-SLVOAQOY.js} +15 -4
- package/dist/node-runtime/{chunk-WHLRAGUQ.js → chunk-TORR5XBV.js} +6 -6
- package/dist/node-runtime/{chunk-UP2XBVH5.js → chunk-UOEDI7RP.js} +1 -1
- package/dist/node-runtime/{chunk-DE2JB6J5.js → chunk-VQFSUJJG.js} +2 -2
- package/dist/node-runtime/{chunk-QM43FEAE.js → chunk-WF7PGWRZ.js} +3 -3
- package/dist/node-runtime/chunk-YCUZEGJG.js +1361 -0
- package/dist/node-runtime/{command-7BG7VVTS.js → command-6WDOYKS6.js} +5 -5
- package/dist/node-runtime/{commands-QFDKNQTL.js → commands-QC6VUZJQ.js} +5 -5
- package/dist/node-runtime/{config-RORQUQFG.js → config-D4QUPAHX.js} +1 -1
- package/dist/node-runtime/{gateway-TWR3N65G.js → gateway-INAYBF4Q.js} +134 -78
- package/dist/node-runtime/index.js +15 -12
- package/dist/node-runtime/{install-cli-VAP6KBFN.js → install-cli-KL4UDDAD.js} +3 -3
- package/dist/node-runtime/{interactive-mode-6J5VZ2TT.js → interactive-mode-Z5M7WYYZ.js} +8 -7
- package/dist/node-runtime/{lunr-browser-J5ZZYVGM.js → lunr-browser-IR7TL3J7.js} +3 -3
- package/dist/node-runtime/{lunr-cron-CXOL37AL.js → lunr-cron-LWIZJM2N.js} +5 -5
- package/dist/node-runtime/main.js +12 -10
- package/dist/node-runtime/{mobile-commands-VTBM5DSZ.js → mobile-commands-J7OJEKFO.js} +4 -4
- package/dist/node-runtime/{package-manager-cli-ZLW5DZXF.js → package-manager-cli-VYZM5WHN.js} +10 -7
- package/dist/node-runtime/{pi-subagents-XPCLLKIM.js → pi-subagents-DNY7EAIG.js} +6 -6
- package/dist/node-runtime/rpc-entry.js +12 -10
- package/dist/node-runtime/{runtime-bridges-QYXUX2TG.js → runtime-bridges-VRDDR73P.js} +5 -5
- package/dist/node-runtime/{service-ISSP6VHE.js → service-MDQIPQ26.js} +1 -1
- package/dist/node-runtime/{settings-manager-WCQDUVQB.js → settings-manager-J4SPQPDJ.js} +4 -4
- package/dist/node-runtime/setup-CQ2NLVK5.js +214 -0
- package/dist/node-runtime/{subagent-executor-OTNISDQU.js → subagent-executor-KZZQGAKV.js} +5 -5
- package/dist/node-runtime/{update-cli-VBR2777K.js → update-cli-GTFJC7XK.js} +4 -4
- package/docs/features.md +4 -4
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
- package/dist/node-runtime/setup-YRBKH2LD.js +0 -155
package/dist/gateway/config.js
CHANGED
|
@@ -29,6 +29,7 @@ export function defaultGatewayConfig() {
|
|
|
29
29
|
return {
|
|
30
30
|
owners: { telegram: [], discord: [] },
|
|
31
31
|
projectRoots: [],
|
|
32
|
+
defaultProject: undefined,
|
|
32
33
|
telegram: defaultPlatformConfig(false),
|
|
33
34
|
discord: { ...defaultPlatformConfig(true), ignoredChannels: [], autoThread: true },
|
|
34
35
|
groupSessionsPerUser: true,
|
|
@@ -82,6 +83,7 @@ function sanitizeConfig(raw) {
|
|
|
82
83
|
return {
|
|
83
84
|
owners: { telegram: asStringArray(owners.telegram) ?? [], discord: asStringArray(owners.discord) ?? [] },
|
|
84
85
|
projectRoots: asStringArray(r.projectRoots) ?? [],
|
|
86
|
+
defaultProject: typeof r.defaultProject === "string" ? r.defaultProject : undefined,
|
|
85
87
|
telegram: sanitizePlatform(r.telegram, base.telegram),
|
|
86
88
|
discord: sanitizeDiscord(r.discord, base.discord),
|
|
87
89
|
groupSessionsPerUser: asBoolean(r.groupSessionsPerUser) ?? base.groupSessionsPerUser,
|
|
@@ -1 +1 @@
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QAAQ,KAAK,SAAS;QAAE,OAAO,GAAG,CAAC,OAAO,CAAC;IAC/C,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["/**\n * lunR: gateway config (<agentDir>/gateway.json).\n *\n * Follows the pi-ollama-cloud load/save pattern: JSON file under the agent\n * dir (getAgentDir(), honoring PI_CODING_AGENT_DIR), defaults when missing,\n * unknown keys dropped, malformed file tolerated. Writes are atomic\n * (tmp + rename) and the file is created chmod 0600 best-effort — it may\n * hold bot tokens.\n *\n * Token resolution order: LUNR_<PLATFORM>_BOT_TOKEN env →\n * <PLATFORM>_BOT_TOKEN env → file token.\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\n\nexport interface PlatformConfig {\n\tenabled: boolean;\n\ttoken?: string;\n\tallowedUsers: string[];\n\tallowedChats: string[];\n\trequireMention: boolean;\n\tfreeResponseChats: string[];\n\thomeChannel?: string;\n}\n\nexport interface DiscordConfig extends PlatformConfig {\n\tignoredChannels: string[];\n\tautoThread: boolean;\n}\n\nexport interface StreamingConfig {\n\tenabled: boolean;\n\teditIntervalMs: number;\n\tbufferThreshold: number;\n}\n\nexport interface GatewayConfig {\n\towners?: { telegram: string[]; discord: string[] };\n\tprojectRoots?: string[];\n\ttelegram: PlatformConfig;\n\tdiscord: DiscordConfig;\n\t/** Group/channel chats get one session per user when true. */\n\tgroupSessionsPerUser: boolean;\n\t/** What to do with DMs from unauthorized users. */\n\tunauthorizedDmBehavior: \"pair\" | \"ignore\";\n\tstreaming: StreamingConfig;\n}\n\nexport function gatewayConfigPath(): string {\n\treturn join(getAgentDir(), \"gateway.json\");\n}\n\nfunction defaultPlatformConfig(requireMention: boolean): PlatformConfig {\n\treturn {\n\t\tenabled: false,\n\t\tallowedUsers: [],\n\t\tallowedChats: [],\n\t\trequireMention,\n\t\tfreeResponseChats: [],\n\t};\n}\n\nexport function defaultGatewayConfig(): GatewayConfig {\n\treturn {\n\t\towners: { telegram: [], discord: [] },\n\t\tprojectRoots: [],\n\t\ttelegram: defaultPlatformConfig(false),\n\t\tdiscord: { ...defaultPlatformConfig(true), ignoredChannels: [], autoThread: true },\n\t\tgroupSessionsPerUser: true,\n\t\tunauthorizedDmBehavior: \"pair\",\n\t\tstreaming: { enabled: true, editIntervalMs: 800, bufferThreshold: 24 },\n\t};\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\treturn value.every((v) => typeof v === \"string\") ? (value as string[]) : undefined;\n}\n\nfunction asBoolean(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction sanitizePlatform(raw: unknown, base: PlatformConfig): PlatformConfig {\n\tif (raw == null || typeof raw !== \"object\" || Array.isArray(raw)) return base;\n\tconst r = raw as Record<string, unknown>;\n\treturn {\n\t\tenabled: asBoolean(r.enabled) ?? base.enabled,\n\t\ttoken: typeof r.token === \"string\" ? r.token : base.token,\n\t\tallowedUsers: asStringArray(r.allowedUsers) ?? base.allowedUsers,\n\t\tallowedChats: asStringArray(r.allowedChats) ?? base.allowedChats,\n\t\trequireMention: asBoolean(r.requireMention) ?? base.requireMention,\n\t\tfreeResponseChats: asStringArray(r.freeResponseChats) ?? base.freeResponseChats,\n\t\thomeChannel: typeof r.homeChannel === \"string\" ? r.homeChannel : base.homeChannel,\n\t};\n}\n\nfunction sanitizeDiscord(raw: unknown, base: DiscordConfig): DiscordConfig {\n\tconst platform = sanitizePlatform(raw, base);\n\tconst r = raw != null && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};\n\treturn {\n\t\t...platform,\n\t\tignoredChannels: asStringArray(r.ignoredChannels) ?? base.ignoredChannels,\n\t\tautoThread: asBoolean(r.autoThread) ?? base.autoThread,\n\t};\n}\n\nfunction sanitizeConfig(raw: unknown): GatewayConfig {\n\tconst base = defaultGatewayConfig();\n\tif (raw == null || typeof raw !== \"object\" || Array.isArray(raw)) return base;\n\tconst r = raw as Record<string, unknown>;\n\tconst streamingRaw =\n\t\tr.streaming != null && typeof r.streaming === \"object\" && !Array.isArray(r.streaming)\n\t\t\t? (r.streaming as Record<string, unknown>)\n\t\t\t: {};\n\tconst owners = r.owners && typeof r.owners === \"object\" ? (r.owners as Record<string, unknown>) : {};\n\treturn {\n\t\towners: { telegram: asStringArray(owners.telegram) ?? [], discord: asStringArray(owners.discord) ?? [] },\n\t\tprojectRoots: asStringArray(r.projectRoots) ?? [],\n\t\ttelegram: sanitizePlatform(r.telegram, base.telegram),\n\t\tdiscord: sanitizeDiscord(r.discord, base.discord),\n\t\tgroupSessionsPerUser: asBoolean(r.groupSessionsPerUser) ?? base.groupSessionsPerUser,\n\t\tunauthorizedDmBehavior: r.unauthorizedDmBehavior === \"ignore\" ? \"ignore\" : \"pair\",\n\t\tstreaming: {\n\t\t\tenabled: asBoolean(streamingRaw.enabled) ?? base.streaming.enabled,\n\t\t\teditIntervalMs: asNumber(streamingRaw.editIntervalMs) ?? base.streaming.editIntervalMs,\n\t\t\tbufferThreshold: asNumber(streamingRaw.bufferThreshold) ?? base.streaming.bufferThreshold,\n\t\t},\n\t};\n}\n\n/** Load <agentDir>/gateway.json; defaults (both platforms disabled) when missing or malformed. */\nexport function loadGatewayConfig(): GatewayConfig {\n\tconst path = gatewayConfigPath();\n\tif (!existsSync(path)) return defaultGatewayConfig();\n\ttry {\n\t\treturn sanitizeConfig(JSON.parse(readFileSync(path, \"utf-8\")));\n\t} catch (err) {\n\t\tconsole.error(`[gateway] Failed to load config from ${path}: ${err}`);\n\t\treturn defaultGatewayConfig();\n\t}\n}\n\n/** Write the whole config atomically (tmp + rename); chmod 0600 best-effort. */\nexport function saveGatewayConfig(config: GatewayConfig): void {\n\tconst path = gatewayConfigPath();\n\tconst dir = getAgentDir();\n\tif (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\tconst tmp = `${path}.tmp-${process.pid}`;\n\twriteFileSync(tmp, `${JSON.stringify(config, null, 2)}\\n`, \"utf-8\");\n\trenameSync(tmp, path);\n\ttry {\n\t\tchmodSync(path, 0o600);\n\t} catch {\n\t\t// best-effort (Windows ACLs don't map cleanly)\n\t}\n}\n\n/**\n * Resolve a platform's bot token: LUNR_<PLATFORM>_BOT_TOKEN env →\n * <PLATFORM>_BOT_TOKEN env → config file token.\n */\nexport function resolvePlatformToken(platform: string, platformCfg: PlatformConfig): string | undefined {\n\tconst upper = platform.toUpperCase();\n\treturn process.env[`LUNR_${upper}_BOT_TOKEN`] ?? process.env[`${upper}_BOT_TOKEN`] ?? platformCfg.token;\n}\n\n/** Per-platform config lookup; undefined for platforms Phase 2a doesn't model. */\nexport function platformConfigFor(cfg: GatewayConfig, platform: string): PlatformConfig | undefined {\n\tif (platform === \"telegram\") return cfg.telegram;\n\tif (platform === \"discord\") return cfg.discord;\n\treturn undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/gateway/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACpG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAoC3C,MAAM,UAAU,iBAAiB,GAAW;IAC3C,OAAO,IAAI,CAAC,WAAW,EAAE,EAAE,cAAc,CAAC,CAAC;AAAA,CAC3C;AAED,SAAS,qBAAqB,CAAC,cAAuB,EAAkB;IACvE,OAAO;QACN,OAAO,EAAE,KAAK;QACd,YAAY,EAAE,EAAE;QAChB,YAAY,EAAE,EAAE;QAChB,cAAc;QACd,iBAAiB,EAAE,EAAE;KACrB,CAAC;AAAA,C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,OAAO,CAAC,GAAG,EAAE,CAAC;IACzC,aAAa,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACpE,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACtB,IAAI,CAAC;QACJ,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACxB,CAAC;IAAC,MAAM,CAAC;QACR,+CAA+C;IAChD,CAAC;AAAA,CACD;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,QAAgB,EAAE,WAA2B,EAAsB;IACvG,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;IACrC,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,YAAY,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC;AAAA,CACxG;AAED,kFAAkF;AAClF,MAAM,UAAU,iBAAiB,CAAC,GAAkB,EAAE,QAAgB,EAA8B;IACnG,IAAI,QAAQ,KAAK,UAAU;QAAE,OAAO,GAAG,CAAC,QAAQ,CAAC;IACjD,IAAI,QAAQ,KAAK,SAAS;QAAE,OAAO,GAAG,CAAC,OAAO,CAAC;IAC/C,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["/**\n * lunR: gateway config (<agentDir>/gateway.json).\n *\n * Follows the pi-ollama-cloud load/save pattern: JSON file under the agent\n * dir (getAgentDir(), honoring PI_CODING_AGENT_DIR), defaults when missing,\n * unknown keys dropped, malformed file tolerated. Writes are atomic\n * (tmp + rename) and the file is created chmod 0600 best-effort — it may\n * hold bot tokens.\n *\n * Token resolution order: LUNR_<PLATFORM>_BOT_TOKEN env →\n * <PLATFORM>_BOT_TOKEN env → file token.\n */\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getAgentDir } from \"../config.ts\";\n\nexport interface PlatformConfig {\n\tenabled: boolean;\n\ttoken?: string;\n\tallowedUsers: string[];\n\tallowedChats: string[];\n\trequireMention: boolean;\n\tfreeResponseChats: string[];\n\thomeChannel?: string;\n}\n\nexport interface DiscordConfig extends PlatformConfig {\n\tignoredChannels: string[];\n\tautoThread: boolean;\n}\n\nexport interface StreamingConfig {\n\tenabled: boolean;\n\teditIntervalMs: number;\n\tbufferThreshold: number;\n}\n\nexport interface GatewayConfig {\n\towners?: { telegram: string[]; discord: string[] };\n\tprojectRoots?: string[];\n\tdefaultProject?: string;\n\ttelegram: PlatformConfig;\n\tdiscord: DiscordConfig;\n\t/** Group/channel chats get one session per user when true. */\n\tgroupSessionsPerUser: boolean;\n\t/** What to do with DMs from unauthorized users. */\n\tunauthorizedDmBehavior: \"pair\" | \"ignore\";\n\tstreaming: StreamingConfig;\n}\n\nexport function gatewayConfigPath(): string {\n\treturn join(getAgentDir(), \"gateway.json\");\n}\n\nfunction defaultPlatformConfig(requireMention: boolean): PlatformConfig {\n\treturn {\n\t\tenabled: false,\n\t\tallowedUsers: [],\n\t\tallowedChats: [],\n\t\trequireMention,\n\t\tfreeResponseChats: [],\n\t};\n}\n\nexport function defaultGatewayConfig(): GatewayConfig {\n\treturn {\n\t\towners: { telegram: [], discord: [] },\n\t\tprojectRoots: [],\n\t\tdefaultProject: undefined,\n\t\ttelegram: defaultPlatformConfig(false),\n\t\tdiscord: { ...defaultPlatformConfig(true), ignoredChannels: [], autoThread: true },\n\t\tgroupSessionsPerUser: true,\n\t\tunauthorizedDmBehavior: \"pair\",\n\t\tstreaming: { enabled: true, editIntervalMs: 800, bufferThreshold: 24 },\n\t};\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n\tif (!Array.isArray(value)) return undefined;\n\treturn value.every((v) => typeof v === \"string\") ? (value as string[]) : undefined;\n}\n\nfunction asBoolean(value: unknown): boolean | undefined {\n\treturn typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction sanitizePlatform(raw: unknown, base: PlatformConfig): PlatformConfig {\n\tif (raw == null || typeof raw !== \"object\" || Array.isArray(raw)) return base;\n\tconst r = raw as Record<string, unknown>;\n\treturn {\n\t\tenabled: asBoolean(r.enabled) ?? base.enabled,\n\t\ttoken: typeof r.token === \"string\" ? r.token : base.token,\n\t\tallowedUsers: asStringArray(r.allowedUsers) ?? base.allowedUsers,\n\t\tallowedChats: asStringArray(r.allowedChats) ?? base.allowedChats,\n\t\trequireMention: asBoolean(r.requireMention) ?? base.requireMention,\n\t\tfreeResponseChats: asStringArray(r.freeResponseChats) ?? base.freeResponseChats,\n\t\thomeChannel: typeof r.homeChannel === \"string\" ? r.homeChannel : base.homeChannel,\n\t};\n}\n\nfunction sanitizeDiscord(raw: unknown, base: DiscordConfig): DiscordConfig {\n\tconst platform = sanitizePlatform(raw, base);\n\tconst r = raw != null && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};\n\treturn {\n\t\t...platform,\n\t\tignoredChannels: asStringArray(r.ignoredChannels) ?? base.ignoredChannels,\n\t\tautoThread: asBoolean(r.autoThread) ?? base.autoThread,\n\t};\n}\n\nfunction sanitizeConfig(raw: unknown): GatewayConfig {\n\tconst base = defaultGatewayConfig();\n\tif (raw == null || typeof raw !== \"object\" || Array.isArray(raw)) return base;\n\tconst r = raw as Record<string, unknown>;\n\tconst streamingRaw =\n\t\tr.streaming != null && typeof r.streaming === \"object\" && !Array.isArray(r.streaming)\n\t\t\t? (r.streaming as Record<string, unknown>)\n\t\t\t: {};\n\tconst owners = r.owners && typeof r.owners === \"object\" ? (r.owners as Record<string, unknown>) : {};\n\treturn {\n\t\towners: { telegram: asStringArray(owners.telegram) ?? [], discord: asStringArray(owners.discord) ?? [] },\n\t\tprojectRoots: asStringArray(r.projectRoots) ?? [],\n\t\tdefaultProject: typeof r.defaultProject === \"string\" ? r.defaultProject : undefined,\n\t\ttelegram: sanitizePlatform(r.telegram, base.telegram),\n\t\tdiscord: sanitizeDiscord(r.discord, base.discord),\n\t\tgroupSessionsPerUser: asBoolean(r.groupSessionsPerUser) ?? base.groupSessionsPerUser,\n\t\tunauthorizedDmBehavior: r.unauthorizedDmBehavior === \"ignore\" ? \"ignore\" : \"pair\",\n\t\tstreaming: {\n\t\t\tenabled: asBoolean(streamingRaw.enabled) ?? base.streaming.enabled,\n\t\t\teditIntervalMs: asNumber(streamingRaw.editIntervalMs) ?? base.streaming.editIntervalMs,\n\t\t\tbufferThreshold: asNumber(streamingRaw.bufferThreshold) ?? base.streaming.bufferThreshold,\n\t\t},\n\t};\n}\n\n/** Load <agentDir>/gateway.json; defaults (both platforms disabled) when missing or malformed. */\nexport function loadGatewayConfig(): GatewayConfig {\n\tconst path = gatewayConfigPath();\n\tif (!existsSync(path)) return defaultGatewayConfig();\n\ttry {\n\t\treturn sanitizeConfig(JSON.parse(readFileSync(path, \"utf-8\")));\n\t} catch (err) {\n\t\tconsole.error(`[gateway] Failed to load config from ${path}: ${err}`);\n\t\treturn defaultGatewayConfig();\n\t}\n}\n\n/** Write the whole config atomically (tmp + rename); chmod 0600 best-effort. */\nexport function saveGatewayConfig(config: GatewayConfig): void {\n\tconst path = gatewayConfigPath();\n\tconst dir = getAgentDir();\n\tif (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n\tconst tmp = `${path}.tmp-${process.pid}`;\n\twriteFileSync(tmp, `${JSON.stringify(config, null, 2)}\\n`, \"utf-8\");\n\trenameSync(tmp, path);\n\ttry {\n\t\tchmodSync(path, 0o600);\n\t} catch {\n\t\t// best-effort (Windows ACLs don't map cleanly)\n\t}\n}\n\n/**\n * Resolve a platform's bot token: LUNR_<PLATFORM>_BOT_TOKEN env →\n * <PLATFORM>_BOT_TOKEN env → config file token.\n */\nexport function resolvePlatformToken(platform: string, platformCfg: PlatformConfig): string | undefined {\n\tconst upper = platform.toUpperCase();\n\treturn process.env[`LUNR_${upper}_BOT_TOKEN`] ?? process.env[`${upper}_BOT_TOKEN`] ?? platformCfg.token;\n}\n\n/** Per-platform config lookup; undefined for platforms Phase 2a doesn't model. */\nexport function platformConfigFor(cfg: GatewayConfig, platform: string): PlatformConfig | undefined {\n\tif (platform === \"telegram\") return cfg.telegram;\n\tif (platform === \"discord\") return cfg.discord;\n\treturn undefined;\n}\n"]}
|
package/dist/gateway/cron.d.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* "origin" (the chat that created the job, homeChannel fallback), a bare
|
|
17
17
|
* platform name (that platform's homeChannel), or
|
|
18
18
|
* "<platform>:<chatId>[:<threadId>]" (explicit). Content is wrapped as
|
|
19
|
-
* "
|
|
19
|
+
* "Cron: <name>" and split to the adapter's maxMessageLength.
|
|
20
20
|
*
|
|
21
21
|
* The bridge is re-installed after every cron session creation because loading
|
|
22
22
|
* the builtin extensions (lunr-cron) re-registers its local-notify bridge per
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cron.d.ts","sourceRoot":"","sources":["../../src/gateway/cron.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGnE,OAAO,EAAE,KAAK,aAAa,EAAyB,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,KAAK,aAAa,EAAqB,MAAM,aAAa,CAAC;AAEpE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAIlD,KAAK,cAAc,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;AAEhF,qEAAqE;AACrE,MAAM,WAAW,YAAY;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,kBAAkB,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,aAAa,CAAC,CAAC;AAExG,MAAM,WAAW,kBAAkB;IAClC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACvC,GAAG,EAAE,aAAa,CAAC;IACnB,kCAAkC;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iFAAiF;IACjF,cAAc,CAAC,EAAE,kBAAkB,CAAC;IACpC,kHAAkH;IAClH,cAAc,CAAC,EAAE,YAAY,EAAE,CAAC;CAChC;AA+HD,sEAAsE;AACtE,wBAAgB,oBAAoB,CACnC,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,aAAa,GAAG,IAAI,GAC3B,OAAO,CAMT;AAED,wBAAgB,sBAAsB,CACrC,GAAG,EAAE,aAAa,GAChB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,aAAa,GAAG,IAAI,KAAK,MAAM,GAAG,SAAS,CAuBxE;AAED,sDAAsD;AACtD,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAErE;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,EAAE,GAAG,EAAE,aAAa,GAAG,cAAc,CAyClH;AA8CD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,kBAAkB,GAAG;IAAE,IAAI,IAAI,IAAI,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CA0DlG","sourcesContent":["/**\n * lunR: gateway cron runner + delivery (Phase 4 of the cron/gateway roadmap).\n *\n * startGatewayCron() runs the core/cron scheduler inside the `lunr gateway`\n * daemon:\n *\n * - runJob: each fire gets a FRESH headless agent session (createAgentSession\n * with SessionManager.inMemory — cron runs never write session files and\n * never touch the per-chat gateway sessions; the files under\n * <agentDir>/cron/output/ are the audit trail). The shared fire-guard\n * (core/cron/fire-guard) brackets the turn so the `cron` tool refuses to\n * run inside it (jobs cannot schedule jobs).\n * - deliverResult: replaces the `@lunr/cron-delivery` bridge on globalThis\n * with a platform deliverer. Targets come from job.deliver\n * (comma-separated): \"local\" (no-op — the output file is already written),\n * \"origin\" (the chat that created the job, homeChannel fallback), a bare\n * platform name (that platform's homeChannel), or\n * \"<platform>:<chatId>[:<threadId>]\" (explicit). Content is wrapped as\n * \"☾ Cron: <name>\" and split to the adapter's maxMessageLength.\n *\n * The bridge is re-installed after every cron session creation because loading\n * the builtin extensions (lunr-cron) re-registers its local-notify bridge per\n * session; delivery re-reads the bridge on every call, matching lunr-cron.\n *\n * Fallback models (2026-08-02): settings.json `cronFallbackModels`\n * (\"provider/modelId\" entries) are tried IN ORDER when a fire fails — timeout\n * or any error. Each attempt gets a fresh headless session and\n * jobTimeoutMs/candidates of the budget; a successful fallback run prefixes\n * \"[fell back to provider/modelId]\" to the output. TUI fires are unaffected\n * (they use the live session's model).\n */\n\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport { beginCronFire, endCronFire } from \"../core/cron/fire-guard.ts\";\nimport type { CronJob, CronJobOrigin } from \"../core/cron/jobs.ts\";\nimport { setCronDeliverValidator } from \"../core/cron/jobs.ts\";\nimport { startScheduler } from \"../core/cron/scheduler.ts\";\nimport { type BridgeSession, shutdownBridgeSession } from \"./agent-bridge.ts\";\nimport { type GatewayConfig, platformConfigFor } from \"./config.ts\";\nimport { splitMessage } from \"./text.ts\";\nimport type { PlatformAdapter } from \"./types.ts\";\n\nconst DELIVERY_BRIDGE_SYMBOL = Symbol.for(\"@lunr/cron-delivery\");\n\ntype DeliveryBridge = (job: CronJob, content: string) => Promise<string | null>;\n\n/** Test seam / default: one fresh headless session per cron fire. */\nexport interface CronModelRef {\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport type CronSessionFactory = (job: CronJob, modelOverride?: CronModelRef) => Promise<BridgeSession>;\n\nexport interface GatewayCronOptions {\n\tadapters: Map<string, PlatformAdapter>;\n\tcfg: GatewayConfig;\n\t/** Tick interval; default 60s. */\n\tintervalMs?: number;\n\t/** Session factory for cron fires; defaults to a real headless agent session. */\n\tsessionFactory?: CronSessionFactory;\n\t/** Test seam: fallback models. When omitted, read fresh from settings.json `cronFallbackModels` on every fire. */\n\tfallbackModels?: CronModelRef[];\n}\n\nconst KNOWN_PLATFORMS = [\"telegram\", \"discord\"] as const;\n\n/** Default factory: fresh in-memory headless session, mirroring agent-bridge's wiring. */\nasync function defaultCronSessionFactory(job: CronJob, modelOverride?: CronModelRef): Promise<BridgeSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t\t{ bindRuntimeBridges },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t\timport(\"../core/runtime-bridges.ts\"),\n\t]);\n\tconst cwd = job.workdir ?? process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterCustomizeBridge(settingsManager);\n\n\t// In-memory on purpose: cron runs must not persist session files or pollute\n\t// the per-chat gateway sessions — <agentDir>/cron/output/ is the audit trail.\n\tconst sessionManager = SessionManager.inMemory(cwd);\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider.\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\t// Fallback-model attempts pin the session model explicitly; an unresolvable\n\t// or unauthenticated override fails the attempt so the next fallback runs.\n\tlet model: Model<any> | undefined;\n\tif (modelOverride) {\n\t\tconst resolved = services.modelRuntime.getModel(modelOverride.provider, modelOverride.modelId);\n\t\tif (!resolved) throw new Error(`model not found: ${modelOverride.provider}/${modelOverride.modelId}`);\n\t\tif (!services.modelRuntime.hasConfiguredAuth(resolved.provider)) {\n\t\t\tthrow new Error(`no configured auth for provider: ${modelOverride.provider}`);\n\t\t}\n\t\tmodel = resolved;\n\t}\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager, model });\n\tbindRuntimeBridges({ session, services });\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway cron] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as {\n\t\tstopReason?: string;\n\t\terrorMessage?: string;\n\t\tcontent?: Array<{ type: string; text?: string }>;\n\t};\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content ?? []) {\n\t\tif (content.type === \"text\") text += content.text ?? \"\";\n\t}\n\treturn text;\n}\n\ninterface ResolvedTarget {\n\tplatform: string;\n\tchatId: string;\n\tthreadId?: string;\n}\n\nconst EXPLICIT_TARGET_RE = /^([a-z0-9_-]+):([^:]+)(?::([^:]+))?$/i;\n\n/** Resolve one deliver target to a concrete destination. Returns an error string on failure. */\nfunction resolveTarget(target: string, job: CronJob, cfg: GatewayConfig): ResolvedTarget | string {\n\tif (target === \"origin\") {\n\t\tconst origin = job.origin;\n\t\tif (origin?.platform && origin.chatId) {\n\t\t\treturn { platform: origin.platform, chatId: origin.chatId, threadId: origin.threadId };\n\t\t}\n\t\t// Missing/incomplete origin → fall back to a homeChannel: the origin's\n\t\t// platform when known, otherwise the first platform that has one.\n\t\tconst platforms = origin?.platform ? [origin.platform] : KNOWN_PLATFORMS;\n\t\tfor (const platform of platforms) {\n\t\t\tconst home = platformConfigFor(cfg, platform)?.homeChannel;\n\t\t\tif (home) return { platform, chatId: home };\n\t\t}\n\t\treturn `deliver target \"origin\": job has no origin and no homeChannel is configured`;\n\t}\n\n\tconst explicit = EXPLICIT_TARGET_RE.exec(target);\n\tconst platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();\n\tif (platformConfigFor(cfg, platform) === undefined) {\n\t\treturn `unknown platform \"${explicit ? explicit[1] : target}\"`;\n\t}\n\tif (explicit) {\n\t\treturn { platform, chatId: explicit[2], threadId: explicit[3] };\n\t}\n\t// Bare platform name → its homeChannel.\n\tconst home = platformConfigFor(cfg, platform)?.homeChannel;\n\tif (!home) return `no homeChannel configured for ${platform}`;\n\treturn { platform, chatId: home };\n}\n\n/** True when a resolved chat may receive cron output for this job. */\nexport function isAllowedDeliverChat(\n\tcfg: GatewayConfig,\n\tplatform: string,\n\tchatId: string,\n\torigin?: CronJobOrigin | null,\n): boolean {\n\tconst platformCfg = platformConfigFor(cfg, platform);\n\tif (!platformCfg) return false;\n\tif (platformCfg.homeChannel && platformCfg.homeChannel === chatId) return true;\n\tif (platformCfg.allowedChats?.includes(chatId)) return true;\n\treturn origin?.platform === platform && origin.chatId === chatId;\n}\n\nexport function createDeliverValidator(\n\tcfg: GatewayConfig,\n): (deliver: string, origin?: CronJobOrigin | null) => string | undefined {\n\treturn (deliver, origin) => {\n\t\tconst targets = deliver\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\tfor (const target of targets) {\n\t\t\tif (target === \"local\") continue;\n\t\t\tif (target === \"origin\") continue; // delivery time resolves/fails with a sensible error\n\t\t\tconst explicit = EXPLICIT_TARGET_RE.exec(target);\n\t\t\tconst platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();\n\t\t\tconst platformCfg = platformConfigFor(cfg, platform);\n\t\t\tif (!platformCfg) return `unknown platform \"${explicit ? explicit[1] : target}\"`;\n\t\t\tif (explicit) {\n\t\t\t\tif (!isAllowedDeliverChat(cfg, platform, explicit[2], origin)) {\n\t\t\t\t\treturn `deliver target \"${target}\" is not an allowed chat for ${platform}`;\n\t\t\t\t}\n\t\t\t} else if (!platformCfg.homeChannel) {\n\t\t\t\treturn `no homeChannel configured for ${platform}`;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t};\n}\n\n/** Wrap the run output with a compact cron header. */\nexport function wrapCronContent(job: CronJob, content: string): string {\n\treturn `☾ Cron: ${job.name}\\n———\\n${content}`;\n}\n\n/**\n * The platform deliverer installed at the `@lunr/cron-delivery` bridge.\n * Every target is attempted; the first error is returned (null on success).\n */\nexport function createPlatformDeliverer(adapters: Map<string, PlatformAdapter>, cfg: GatewayConfig): DeliveryBridge {\n\treturn async (job, content) => {\n\t\tconst targets = job.deliver\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\tlet firstError: string | null = null;\n\t\tfor (const target of targets) {\n\t\t\tif (target === \"local\") continue; // output file already written by the scheduler\n\t\t\tconst resolved = resolveTarget(target, job, cfg);\n\t\t\tif (typeof resolved === \"string\") {\n\t\t\t\tfirstError ??= resolved;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isAllowedDeliverChat(cfg, resolved.platform, resolved.chatId, job.origin)) {\n\t\t\t\tfirstError ??= `deliver target \"${target}\" is not an allowed chat for ${resolved.platform}`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst adapter = adapters.get(resolved.platform);\n\t\t\tif (!adapter) {\n\t\t\t\tfirstError ??= `no adapter connected for ${resolved.platform}`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst wrapped = wrapCronContent(job, content);\n\t\t\tfor (const chunk of splitMessage(wrapped, adapter.maxMessageLength)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await adapter.send(resolved.chatId, chunk, {\n\t\t\t\t\t\tthreadId: resolved.threadId,\n\t\t\t\t\t});\n\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\tfirstError ??= `${resolved.platform} send failed: ${result.error ?? \"unknown error\"}`;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tfirstError ??= `${resolved.platform} send failed: ${err instanceof Error ? err.message : String(err)}`;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn firstError;\n\t};\n}\n\n/** Race one prompt attempt against its share of the job budget. */\nfunction withAttemptTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n\treturn Promise.race([\n\t\tpromise,\n\t\tnew Promise<never>((_, reject) => {\n\t\t\tconst timer = setTimeout(() => reject(new Error(`attempt timed out after ${ms}ms`)), ms);\n\t\t\t// If the attempt settles first this promise is discarded; the timer must not keep the process alive.\n\t\t\ttimer.unref?.();\n\t\t}),\n\t]);\n}\n\n/**\n * Read settings.json `cronFallbackModels` (\"provider/modelId\" entries).\n * Fresh read per fire so edits apply without a daemon restart; invalid\n * entries are skipped with a log line. Never throws.\n */\nasync function readCronFallbackModels(): Promise<CronModelRef[]> {\n\ttry {\n\t\tconst [{ getAgentDir }, { SettingsManager }] = await Promise.all([\n\t\t\timport(\"../config.ts\"),\n\t\t\timport(\"../core/settings-manager.ts\"),\n\t\t]);\n\t\tconst settingsManager = SettingsManager.create(process.cwd(), getAgentDir(), { projectTrusted: false });\n\t\tconst out: CronModelRef[] = [];\n\t\tfor (const entry of settingsManager.getCronFallbackModels()) {\n\t\t\tconst idx = entry.indexOf(\"/\");\n\t\t\tif (idx <= 0 || idx === entry.length - 1) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[gateway cron] ignoring invalid cronFallbackModels entry \"${entry}\" (want \"provider/modelId\")`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tout.push({ provider: entry.slice(0, idx), modelId: entry.slice(idx + 1) });\n\t\t}\n\t\treturn out;\n\t} catch (err) {\n\t\tconsole.error(\n\t\t\t`[gateway cron] failed to read cronFallbackModels: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t\treturn [];\n\t}\n}\n\n/**\n * Start the cron scheduler inside the gateway daemon. Starts even with zero\n * stored jobs — jobs can be created later from chats. stop() halts the loop.\n */\nexport function startGatewayCron(options: GatewayCronOptions): { stop(): void; intervalMs: number } {\n\tconst { adapters, cfg } = options;\n\tconst sessionFactory = options.sessionFactory ?? defaultCronSessionFactory;\n\tconst platformDeliverer = createPlatformDeliverer(adapters, cfg);\n\n\t// Explicit so runJob can split it into per-attempt budgets that sum to (at\n\t// most) the scheduler's outer race (core/cron/scheduler.ts runSchedulerTick).\n\tconst jobTimeoutMs = 5 * 60 * 1000;\n\n\t// Reject deliver targets that are not local, origin, a configured home channel,\n\t// or an explicit chat in the platform allowlist / the job's origin.\n\tsetCronDeliverValidator(createDeliverValidator(cfg));\n\n\t// Replace the local-notify bridge lunr-cron registered with the platform deliverer.\n\t(globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;\n\n\tconst runJob = async (prompt: string, job: CronJob): Promise<string> => {\n\t\tconst fallbacks = options.fallbackModels ?? (await readCronFallbackModels());\n\t\tconst candidates: Array<CronModelRef | undefined> = [undefined, ...fallbacks];\n\t\tconst attemptTimeoutMs = Math.floor(jobTimeoutMs / candidates.length);\n\t\tconst errors: string[] = [];\n\t\tbeginCronFire();\n\t\ttry {\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tconst label = candidate ? `${candidate.provider}/${candidate.modelId}` : \"default model\";\n\t\t\t\tlet session: BridgeSession | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tsession = await sessionFactory(job, candidate);\n\t\t\t\t\t// Loading the builtin extensions re-registered lunr-cron's local-notify\n\t\t\t\t\t// bridge; restore the platform deliverer before any delivery re-reads it.\n\t\t\t\t\t(globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;\n\t\t\t\t\tawait withAttemptTimeout(session.prompt(prompt, { source: \"extension\" }), attemptTimeoutMs);\n\t\t\t\t\tconst text = extractFinalText(session);\n\t\t\t\t\t// The marker lands in the output file (the audit trail); [SILENT] as\n\t\t\t\t\t// the last line still suppresses delivery (scheduler isSilent check).\n\t\t\t\t\treturn candidate ? `[fell back to ${label}]\\n${text}` : text;\n\t\t\t\t} catch (err) {\n\t\t\t\t\terrors.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t\t} finally {\n\t\t\t\t\tif (session) await shutdownBridgeSession(session, \"quit\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new Error(errors.join(\" | \") || \"no model candidates\");\n\t\t} finally {\n\t\t\tendCronFire();\n\t\t}\n\t};\n\n\tconst deliverResult = async (job: CronJob, content: string): Promise<void> => {\n\t\t// Re-read the bridge on every delivery (same pattern as lunr-cron).\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] as DeliveryBridge | undefined;\n\t\tif (!bridge) throw new Error(\"no cron delivery bridge registered\");\n\t\tconst err = await bridge(job, content);\n\t\tif (err) throw new Error(err);\n\t};\n\n\tconst scheduler = startScheduler({ runJob, deliverResult, intervalMs: options.intervalMs, jobTimeoutMs });\n\treturn { stop: () => scheduler.stop(), intervalMs: options.intervalMs ?? 60_000 };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cron.d.ts","sourceRoot":"","sources":["../../src/gateway/cron.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGnE,OAAO,EAAE,KAAK,aAAa,EAAyB,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAE,KAAK,aAAa,EAAqB,MAAM,aAAa,CAAC;AAEpE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAIlD,KAAK,cAAc,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;AAEhF,qEAAqE;AACrE,MAAM,WAAW,YAAY;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,MAAM,kBAAkB,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,aAAa,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,aAAa,CAAC,CAAC;AAExG,MAAM,WAAW,kBAAkB;IAClC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACvC,GAAG,EAAE,aAAa,CAAC;IACnB,kCAAkC;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iFAAiF;IACjF,cAAc,CAAC,EAAE,kBAAkB,CAAC;IACpC,kHAAkH;IAClH,cAAc,CAAC,EAAE,YAAY,EAAE,CAAC;CAChC;AA+HD,sEAAsE;AACtE,wBAAgB,oBAAoB,CACnC,GAAG,EAAE,aAAa,EAClB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,aAAa,GAAG,IAAI,GAC3B,OAAO,CAMT;AAED,wBAAgB,sBAAsB,CACrC,GAAG,EAAE,aAAa,GAChB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,aAAa,GAAG,IAAI,KAAK,MAAM,GAAG,SAAS,CAuBxE;AAED,sDAAsD;AACtD,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAErE;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,eAAe,CAAC,EAAE,GAAG,EAAE,aAAa,GAAG,cAAc,CAyClH;AA8CD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,kBAAkB,GAAG;IAAE,IAAI,IAAI,IAAI,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CA0DlG","sourcesContent":["/**\n * lunR: gateway cron runner + delivery (Phase 4 of the cron/gateway roadmap).\n *\n * startGatewayCron() runs the core/cron scheduler inside the `lunr gateway`\n * daemon:\n *\n * - runJob: each fire gets a FRESH headless agent session (createAgentSession\n * with SessionManager.inMemory — cron runs never write session files and\n * never touch the per-chat gateway sessions; the files under\n * <agentDir>/cron/output/ are the audit trail). The shared fire-guard\n * (core/cron/fire-guard) brackets the turn so the `cron` tool refuses to\n * run inside it (jobs cannot schedule jobs).\n * - deliverResult: replaces the `@lunr/cron-delivery` bridge on globalThis\n * with a platform deliverer. Targets come from job.deliver\n * (comma-separated): \"local\" (no-op — the output file is already written),\n * \"origin\" (the chat that created the job, homeChannel fallback), a bare\n * platform name (that platform's homeChannel), or\n * \"<platform>:<chatId>[:<threadId>]\" (explicit). Content is wrapped as\n * \"Cron: <name>\" and split to the adapter's maxMessageLength.\n *\n * The bridge is re-installed after every cron session creation because loading\n * the builtin extensions (lunr-cron) re-registers its local-notify bridge per\n * session; delivery re-reads the bridge on every call, matching lunr-cron.\n *\n * Fallback models (2026-08-02): settings.json `cronFallbackModels`\n * (\"provider/modelId\" entries) are tried IN ORDER when a fire fails — timeout\n * or any error. Each attempt gets a fresh headless session and\n * jobTimeoutMs/candidates of the budget; a successful fallback run prefixes\n * \"[fell back to provider/modelId]\" to the output. TUI fires are unaffected\n * (they use the live session's model).\n */\n\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport { beginCronFire, endCronFire } from \"../core/cron/fire-guard.ts\";\nimport type { CronJob, CronJobOrigin } from \"../core/cron/jobs.ts\";\nimport { setCronDeliverValidator } from \"../core/cron/jobs.ts\";\nimport { startScheduler } from \"../core/cron/scheduler.ts\";\nimport { type BridgeSession, shutdownBridgeSession } from \"./agent-bridge.ts\";\nimport { type GatewayConfig, platformConfigFor } from \"./config.ts\";\nimport { splitMessage } from \"./text.ts\";\nimport type { PlatformAdapter } from \"./types.ts\";\n\nconst DELIVERY_BRIDGE_SYMBOL = Symbol.for(\"@lunr/cron-delivery\");\n\ntype DeliveryBridge = (job: CronJob, content: string) => Promise<string | null>;\n\n/** Test seam / default: one fresh headless session per cron fire. */\nexport interface CronModelRef {\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport type CronSessionFactory = (job: CronJob, modelOverride?: CronModelRef) => Promise<BridgeSession>;\n\nexport interface GatewayCronOptions {\n\tadapters: Map<string, PlatformAdapter>;\n\tcfg: GatewayConfig;\n\t/** Tick interval; default 60s. */\n\tintervalMs?: number;\n\t/** Session factory for cron fires; defaults to a real headless agent session. */\n\tsessionFactory?: CronSessionFactory;\n\t/** Test seam: fallback models. When omitted, read fresh from settings.json `cronFallbackModels` on every fire. */\n\tfallbackModels?: CronModelRef[];\n}\n\nconst KNOWN_PLATFORMS = [\"telegram\", \"discord\"] as const;\n\n/** Default factory: fresh in-memory headless session, mirroring agent-bridge's wiring. */\nasync function defaultCronSessionFactory(job: CronJob, modelOverride?: CronModelRef): Promise<BridgeSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t\t{ bindRuntimeBridges },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t\timport(\"../core/runtime-bridges.ts\"),\n\t]);\n\tconst cwd = job.workdir ?? process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterCustomizeBridge(settingsManager);\n\n\t// In-memory on purpose: cron runs must not persist session files or pollute\n\t// the per-chat gateway sessions — <agentDir>/cron/output/ is the audit trail.\n\tconst sessionManager = SessionManager.inMemory(cwd);\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider.\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\t// Fallback-model attempts pin the session model explicitly; an unresolvable\n\t// or unauthenticated override fails the attempt so the next fallback runs.\n\tlet model: Model<any> | undefined;\n\tif (modelOverride) {\n\t\tconst resolved = services.modelRuntime.getModel(modelOverride.provider, modelOverride.modelId);\n\t\tif (!resolved) throw new Error(`model not found: ${modelOverride.provider}/${modelOverride.modelId}`);\n\t\tif (!services.modelRuntime.hasConfiguredAuth(resolved.provider)) {\n\t\t\tthrow new Error(`no configured auth for provider: ${modelOverride.provider}`);\n\t\t}\n\t\tmodel = resolved;\n\t}\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager, model });\n\tbindRuntimeBridges({ session, services });\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway cron] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as {\n\t\tstopReason?: string;\n\t\terrorMessage?: string;\n\t\tcontent?: Array<{ type: string; text?: string }>;\n\t};\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content ?? []) {\n\t\tif (content.type === \"text\") text += content.text ?? \"\";\n\t}\n\treturn text;\n}\n\ninterface ResolvedTarget {\n\tplatform: string;\n\tchatId: string;\n\tthreadId?: string;\n}\n\nconst EXPLICIT_TARGET_RE = /^([a-z0-9_-]+):([^:]+)(?::([^:]+))?$/i;\n\n/** Resolve one deliver target to a concrete destination. Returns an error string on failure. */\nfunction resolveTarget(target: string, job: CronJob, cfg: GatewayConfig): ResolvedTarget | string {\n\tif (target === \"origin\") {\n\t\tconst origin = job.origin;\n\t\tif (origin?.platform && origin.chatId) {\n\t\t\treturn { platform: origin.platform, chatId: origin.chatId, threadId: origin.threadId };\n\t\t}\n\t\t// Missing/incomplete origin → fall back to a homeChannel: the origin's\n\t\t// platform when known, otherwise the first platform that has one.\n\t\tconst platforms = origin?.platform ? [origin.platform] : KNOWN_PLATFORMS;\n\t\tfor (const platform of platforms) {\n\t\t\tconst home = platformConfigFor(cfg, platform)?.homeChannel;\n\t\t\tif (home) return { platform, chatId: home };\n\t\t}\n\t\treturn `deliver target \"origin\": job has no origin and no homeChannel is configured`;\n\t}\n\n\tconst explicit = EXPLICIT_TARGET_RE.exec(target);\n\tconst platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();\n\tif (platformConfigFor(cfg, platform) === undefined) {\n\t\treturn `unknown platform \"${explicit ? explicit[1] : target}\"`;\n\t}\n\tif (explicit) {\n\t\treturn { platform, chatId: explicit[2], threadId: explicit[3] };\n\t}\n\t// Bare platform name → its homeChannel.\n\tconst home = platformConfigFor(cfg, platform)?.homeChannel;\n\tif (!home) return `no homeChannel configured for ${platform}`;\n\treturn { platform, chatId: home };\n}\n\n/** True when a resolved chat may receive cron output for this job. */\nexport function isAllowedDeliverChat(\n\tcfg: GatewayConfig,\n\tplatform: string,\n\tchatId: string,\n\torigin?: CronJobOrigin | null,\n): boolean {\n\tconst platformCfg = platformConfigFor(cfg, platform);\n\tif (!platformCfg) return false;\n\tif (platformCfg.homeChannel && platformCfg.homeChannel === chatId) return true;\n\tif (platformCfg.allowedChats?.includes(chatId)) return true;\n\treturn origin?.platform === platform && origin.chatId === chatId;\n}\n\nexport function createDeliverValidator(\n\tcfg: GatewayConfig,\n): (deliver: string, origin?: CronJobOrigin | null) => string | undefined {\n\treturn (deliver, origin) => {\n\t\tconst targets = deliver\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\tfor (const target of targets) {\n\t\t\tif (target === \"local\") continue;\n\t\t\tif (target === \"origin\") continue; // delivery time resolves/fails with a sensible error\n\t\t\tconst explicit = EXPLICIT_TARGET_RE.exec(target);\n\t\t\tconst platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();\n\t\t\tconst platformCfg = platformConfigFor(cfg, platform);\n\t\t\tif (!platformCfg) return `unknown platform \"${explicit ? explicit[1] : target}\"`;\n\t\t\tif (explicit) {\n\t\t\t\tif (!isAllowedDeliverChat(cfg, platform, explicit[2], origin)) {\n\t\t\t\t\treturn `deliver target \"${target}\" is not an allowed chat for ${platform}`;\n\t\t\t\t}\n\t\t\t} else if (!platformCfg.homeChannel) {\n\t\t\t\treturn `no homeChannel configured for ${platform}`;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t};\n}\n\n/** Wrap the run output with a compact cron header. */\nexport function wrapCronContent(job: CronJob, content: string): string {\n\treturn `Cron: ${job.name}\\n———\\n${content}`;\n}\n\n/**\n * The platform deliverer installed at the `@lunr/cron-delivery` bridge.\n * Every target is attempted; the first error is returned (null on success).\n */\nexport function createPlatformDeliverer(adapters: Map<string, PlatformAdapter>, cfg: GatewayConfig): DeliveryBridge {\n\treturn async (job, content) => {\n\t\tconst targets = job.deliver\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\tlet firstError: string | null = null;\n\t\tfor (const target of targets) {\n\t\t\tif (target === \"local\") continue; // output file already written by the scheduler\n\t\t\tconst resolved = resolveTarget(target, job, cfg);\n\t\t\tif (typeof resolved === \"string\") {\n\t\t\t\tfirstError ??= resolved;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isAllowedDeliverChat(cfg, resolved.platform, resolved.chatId, job.origin)) {\n\t\t\t\tfirstError ??= `deliver target \"${target}\" is not an allowed chat for ${resolved.platform}`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst adapter = adapters.get(resolved.platform);\n\t\t\tif (!adapter) {\n\t\t\t\tfirstError ??= `no adapter connected for ${resolved.platform}`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst wrapped = wrapCronContent(job, content);\n\t\t\tfor (const chunk of splitMessage(wrapped, adapter.maxMessageLength)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await adapter.send(resolved.chatId, chunk, {\n\t\t\t\t\t\tthreadId: resolved.threadId,\n\t\t\t\t\t});\n\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\tfirstError ??= `${resolved.platform} send failed: ${result.error ?? \"unknown error\"}`;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tfirstError ??= `${resolved.platform} send failed: ${err instanceof Error ? err.message : String(err)}`;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn firstError;\n\t};\n}\n\n/** Race one prompt attempt against its share of the job budget. */\nfunction withAttemptTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n\treturn Promise.race([\n\t\tpromise,\n\t\tnew Promise<never>((_, reject) => {\n\t\t\tconst timer = setTimeout(() => reject(new Error(`attempt timed out after ${ms}ms`)), ms);\n\t\t\t// If the attempt settles first this promise is discarded; the timer must not keep the process alive.\n\t\t\ttimer.unref?.();\n\t\t}),\n\t]);\n}\n\n/**\n * Read settings.json `cronFallbackModels` (\"provider/modelId\" entries).\n * Fresh read per fire so edits apply without a daemon restart; invalid\n * entries are skipped with a log line. Never throws.\n */\nasync function readCronFallbackModels(): Promise<CronModelRef[]> {\n\ttry {\n\t\tconst [{ getAgentDir }, { SettingsManager }] = await Promise.all([\n\t\t\timport(\"../config.ts\"),\n\t\t\timport(\"../core/settings-manager.ts\"),\n\t\t]);\n\t\tconst settingsManager = SettingsManager.create(process.cwd(), getAgentDir(), { projectTrusted: false });\n\t\tconst out: CronModelRef[] = [];\n\t\tfor (const entry of settingsManager.getCronFallbackModels()) {\n\t\t\tconst idx = entry.indexOf(\"/\");\n\t\t\tif (idx <= 0 || idx === entry.length - 1) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[gateway cron] ignoring invalid cronFallbackModels entry \"${entry}\" (want \"provider/modelId\")`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tout.push({ provider: entry.slice(0, idx), modelId: entry.slice(idx + 1) });\n\t\t}\n\t\treturn out;\n\t} catch (err) {\n\t\tconsole.error(\n\t\t\t`[gateway cron] failed to read cronFallbackModels: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t\treturn [];\n\t}\n}\n\n/**\n * Start the cron scheduler inside the gateway daemon. Starts even with zero\n * stored jobs — jobs can be created later from chats. stop() halts the loop.\n */\nexport function startGatewayCron(options: GatewayCronOptions): { stop(): void; intervalMs: number } {\n\tconst { adapters, cfg } = options;\n\tconst sessionFactory = options.sessionFactory ?? defaultCronSessionFactory;\n\tconst platformDeliverer = createPlatformDeliverer(adapters, cfg);\n\n\t// Explicit so runJob can split it into per-attempt budgets that sum to (at\n\t// most) the scheduler's outer race (core/cron/scheduler.ts runSchedulerTick).\n\tconst jobTimeoutMs = 5 * 60 * 1000;\n\n\t// Reject deliver targets that are not local, origin, a configured home channel,\n\t// or an explicit chat in the platform allowlist / the job's origin.\n\tsetCronDeliverValidator(createDeliverValidator(cfg));\n\n\t// Replace the local-notify bridge lunr-cron registered with the platform deliverer.\n\t(globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;\n\n\tconst runJob = async (prompt: string, job: CronJob): Promise<string> => {\n\t\tconst fallbacks = options.fallbackModels ?? (await readCronFallbackModels());\n\t\tconst candidates: Array<CronModelRef | undefined> = [undefined, ...fallbacks];\n\t\tconst attemptTimeoutMs = Math.floor(jobTimeoutMs / candidates.length);\n\t\tconst errors: string[] = [];\n\t\tbeginCronFire();\n\t\ttry {\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tconst label = candidate ? `${candidate.provider}/${candidate.modelId}` : \"default model\";\n\t\t\t\tlet session: BridgeSession | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tsession = await sessionFactory(job, candidate);\n\t\t\t\t\t// Loading the builtin extensions re-registered lunr-cron's local-notify\n\t\t\t\t\t// bridge; restore the platform deliverer before any delivery re-reads it.\n\t\t\t\t\t(globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;\n\t\t\t\t\tawait withAttemptTimeout(session.prompt(prompt, { source: \"extension\" }), attemptTimeoutMs);\n\t\t\t\t\tconst text = extractFinalText(session);\n\t\t\t\t\t// The marker lands in the output file (the audit trail); [SILENT] as\n\t\t\t\t\t// the last line still suppresses delivery (scheduler isSilent check).\n\t\t\t\t\treturn candidate ? `[fell back to ${label}]\\n${text}` : text;\n\t\t\t\t} catch (err) {\n\t\t\t\t\terrors.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t\t} finally {\n\t\t\t\t\tif (session) await shutdownBridgeSession(session, \"quit\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new Error(errors.join(\" | \") || \"no model candidates\");\n\t\t} finally {\n\t\t\tendCronFire();\n\t\t}\n\t};\n\n\tconst deliverResult = async (job: CronJob, content: string): Promise<void> => {\n\t\t// Re-read the bridge on every delivery (same pattern as lunr-cron).\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] as DeliveryBridge | undefined;\n\t\tif (!bridge) throw new Error(\"no cron delivery bridge registered\");\n\t\tconst err = await bridge(job, content);\n\t\tif (err) throw new Error(err);\n\t};\n\n\tconst scheduler = startScheduler({ runJob, deliverResult, intervalMs: options.intervalMs, jobTimeoutMs });\n\treturn { stop: () => scheduler.stop(), intervalMs: options.intervalMs ?? 60_000 };\n}\n"]}
|
package/dist/gateway/cron.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* "origin" (the chat that created the job, homeChannel fallback), a bare
|
|
17
17
|
* platform name (that platform's homeChannel), or
|
|
18
18
|
* "<platform>:<chatId>[:<threadId>]" (explicit). Content is wrapped as
|
|
19
|
-
* "
|
|
19
|
+
* "Cron: <name>" and split to the adapter's maxMessageLength.
|
|
20
20
|
*
|
|
21
21
|
* The bridge is re-installed after every cron session creation because loading
|
|
22
22
|
* the builtin extensions (lunr-cron) re-registers its local-notify bridge per
|
|
@@ -179,7 +179,7 @@ export function createDeliverValidator(cfg) {
|
|
|
179
179
|
}
|
|
180
180
|
/** Wrap the run output with a compact cron header. */
|
|
181
181
|
export function wrapCronContent(job, content) {
|
|
182
|
-
return
|
|
182
|
+
return `Cron: ${job.name}\n———\n${content}`;
|
|
183
183
|
}
|
|
184
184
|
/**
|
|
185
185
|
* The platform deliverer installed at the `@lunr/cron-delivery` bridge.
|
package/dist/gateway/cron.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cron.js","sourceRoot":"","sources":["../../src/gateway/cron.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAGH,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAExE,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAsB,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAsB,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAGzC,MAAM,sBAAsB,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAuBjE,MAAM,eAAe,GAAG,CAAC,UAAU,EAAE,SAAS,CAAU,CAAC;AAEzD,0FAA0F;AAC1F,KAAK,UAAU,yBAAyB,CAAC,GAAY,EAAE,aAA4B,EAA0B;IAC5G,MAAM,CACL,EAAE,wBAAwB,EAAE,EAC5B,EAAE,WAAW,EAAE,EACf,EAAE,uBAAuB,EAAE,EAC3B,EAAE,uBAAuB,EAAE,EAC3B,EAAE,uBAAuB,EAAE,EAC3B,EAAE,8BAA8B,EAAE,0BAA0B,EAAE,EAC9D,EAAE,cAAc,EAAE,EAClB,EAAE,eAAe,EAAE,EACnB,EAAE,kBAAkB,EAAE,EACtB,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACrB,MAAM,CAAC,gCAAgC,CAAC;QACxC,MAAM,CAAC,cAAc,CAAC;QACtB,MAAM,CAAC,sBAAsB,CAAC;QAC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AS,CAAC,IAAI,EAAE,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,MAAM,EAAE,CAAC;AAAA,CAClF","sourcesContent":["/**\n * lunR: gateway cron runner + delivery (Phase 4 of the cron/gateway roadmap).\n *\n * startGatewayCron() runs the core/cron scheduler inside the `lunr gateway`\n * daemon:\n *\n * - runJob: each fire gets a FRESH headless agent session (createAgentSession\n * with SessionManager.inMemory — cron runs never write session files and\n * never touch the per-chat gateway sessions; the files under\n * <agentDir>/cron/output/ are the audit trail). The shared fire-guard\n * (core/cron/fire-guard) brackets the turn so the `cron` tool refuses to\n * run inside it (jobs cannot schedule jobs).\n * - deliverResult: replaces the `@lunr/cron-delivery` bridge on globalThis\n * with a platform deliverer. Targets come from job.deliver\n * (comma-separated): \"local\" (no-op — the output file is already written),\n * \"origin\" (the chat that created the job, homeChannel fallback), a bare\n * platform name (that platform's homeChannel), or\n * \"<platform>:<chatId>[:<threadId>]\" (explicit). Content is wrapped as\n * \"☾ Cron: <name>\" and split to the adapter's maxMessageLength.\n *\n * The bridge is re-installed after every cron session creation because loading\n * the builtin extensions (lunr-cron) re-registers its local-notify bridge per\n * session; delivery re-reads the bridge on every call, matching lunr-cron.\n *\n * Fallback models (2026-08-02): settings.json `cronFallbackModels`\n * (\"provider/modelId\" entries) are tried IN ORDER when a fire fails — timeout\n * or any error. Each attempt gets a fresh headless session and\n * jobTimeoutMs/candidates of the budget; a successful fallback run prefixes\n * \"[fell back to provider/modelId]\" to the output. TUI fires are unaffected\n * (they use the live session's model).\n */\n\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport { beginCronFire, endCronFire } from \"../core/cron/fire-guard.ts\";\nimport type { CronJob, CronJobOrigin } from \"../core/cron/jobs.ts\";\nimport { setCronDeliverValidator } from \"../core/cron/jobs.ts\";\nimport { startScheduler } from \"../core/cron/scheduler.ts\";\nimport { type BridgeSession, shutdownBridgeSession } from \"./agent-bridge.ts\";\nimport { type GatewayConfig, platformConfigFor } from \"./config.ts\";\nimport { splitMessage } from \"./text.ts\";\nimport type { PlatformAdapter } from \"./types.ts\";\n\nconst DELIVERY_BRIDGE_SYMBOL = Symbol.for(\"@lunr/cron-delivery\");\n\ntype DeliveryBridge = (job: CronJob, content: string) => Promise<string | null>;\n\n/** Test seam / default: one fresh headless session per cron fire. */\nexport interface CronModelRef {\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport type CronSessionFactory = (job: CronJob, modelOverride?: CronModelRef) => Promise<BridgeSession>;\n\nexport interface GatewayCronOptions {\n\tadapters: Map<string, PlatformAdapter>;\n\tcfg: GatewayConfig;\n\t/** Tick interval; default 60s. */\n\tintervalMs?: number;\n\t/** Session factory for cron fires; defaults to a real headless agent session. */\n\tsessionFactory?: CronSessionFactory;\n\t/** Test seam: fallback models. When omitted, read fresh from settings.json `cronFallbackModels` on every fire. */\n\tfallbackModels?: CronModelRef[];\n}\n\nconst KNOWN_PLATFORMS = [\"telegram\", \"discord\"] as const;\n\n/** Default factory: fresh in-memory headless session, mirroring agent-bridge's wiring. */\nasync function defaultCronSessionFactory(job: CronJob, modelOverride?: CronModelRef): Promise<BridgeSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t\t{ bindRuntimeBridges },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t\timport(\"../core/runtime-bridges.ts\"),\n\t]);\n\tconst cwd = job.workdir ?? process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterCustomizeBridge(settingsManager);\n\n\t// In-memory on purpose: cron runs must not persist session files or pollute\n\t// the per-chat gateway sessions — <agentDir>/cron/output/ is the audit trail.\n\tconst sessionManager = SessionManager.inMemory(cwd);\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider.\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\t// Fallback-model attempts pin the session model explicitly; an unresolvable\n\t// or unauthenticated override fails the attempt so the next fallback runs.\n\tlet model: Model<any> | undefined;\n\tif (modelOverride) {\n\t\tconst resolved = services.modelRuntime.getModel(modelOverride.provider, modelOverride.modelId);\n\t\tif (!resolved) throw new Error(`model not found: ${modelOverride.provider}/${modelOverride.modelId}`);\n\t\tif (!services.modelRuntime.hasConfiguredAuth(resolved.provider)) {\n\t\t\tthrow new Error(`no configured auth for provider: ${modelOverride.provider}`);\n\t\t}\n\t\tmodel = resolved;\n\t}\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager, model });\n\tbindRuntimeBridges({ session, services });\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway cron] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as {\n\t\tstopReason?: string;\n\t\terrorMessage?: string;\n\t\tcontent?: Array<{ type: string; text?: string }>;\n\t};\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content ?? []) {\n\t\tif (content.type === \"text\") text += content.text ?? \"\";\n\t}\n\treturn text;\n}\n\ninterface ResolvedTarget {\n\tplatform: string;\n\tchatId: string;\n\tthreadId?: string;\n}\n\nconst EXPLICIT_TARGET_RE = /^([a-z0-9_-]+):([^:]+)(?::([^:]+))?$/i;\n\n/** Resolve one deliver target to a concrete destination. Returns an error string on failure. */\nfunction resolveTarget(target: string, job: CronJob, cfg: GatewayConfig): ResolvedTarget | string {\n\tif (target === \"origin\") {\n\t\tconst origin = job.origin;\n\t\tif (origin?.platform && origin.chatId) {\n\t\t\treturn { platform: origin.platform, chatId: origin.chatId, threadId: origin.threadId };\n\t\t}\n\t\t// Missing/incomplete origin → fall back to a homeChannel: the origin's\n\t\t// platform when known, otherwise the first platform that has one.\n\t\tconst platforms = origin?.platform ? [origin.platform] : KNOWN_PLATFORMS;\n\t\tfor (const platform of platforms) {\n\t\t\tconst home = platformConfigFor(cfg, platform)?.homeChannel;\n\t\t\tif (home) return { platform, chatId: home };\n\t\t}\n\t\treturn `deliver target \"origin\": job has no origin and no homeChannel is configured`;\n\t}\n\n\tconst explicit = EXPLICIT_TARGET_RE.exec(target);\n\tconst platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();\n\tif (platformConfigFor(cfg, platform) === undefined) {\n\t\treturn `unknown platform \"${explicit ? explicit[1] : target}\"`;\n\t}\n\tif (explicit) {\n\t\treturn { platform, chatId: explicit[2], threadId: explicit[3] };\n\t}\n\t// Bare platform name → its homeChannel.\n\tconst home = platformConfigFor(cfg, platform)?.homeChannel;\n\tif (!home) return `no homeChannel configured for ${platform}`;\n\treturn { platform, chatId: home };\n}\n\n/** True when a resolved chat may receive cron output for this job. */\nexport function isAllowedDeliverChat(\n\tcfg: GatewayConfig,\n\tplatform: string,\n\tchatId: string,\n\torigin?: CronJobOrigin | null,\n): boolean {\n\tconst platformCfg = platformConfigFor(cfg, platform);\n\tif (!platformCfg) return false;\n\tif (platformCfg.homeChannel && platformCfg.homeChannel === chatId) return true;\n\tif (platformCfg.allowedChats?.includes(chatId)) return true;\n\treturn origin?.platform === platform && origin.chatId === chatId;\n}\n\nexport function createDeliverValidator(\n\tcfg: GatewayConfig,\n): (deliver: string, origin?: CronJobOrigin | null) => string | undefined {\n\treturn (deliver, origin) => {\n\t\tconst targets = deliver\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\tfor (const target of targets) {\n\t\t\tif (target === \"local\") continue;\n\t\t\tif (target === \"origin\") continue; // delivery time resolves/fails with a sensible error\n\t\t\tconst explicit = EXPLICIT_TARGET_RE.exec(target);\n\t\t\tconst platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();\n\t\t\tconst platformCfg = platformConfigFor(cfg, platform);\n\t\t\tif (!platformCfg) return `unknown platform \"${explicit ? explicit[1] : target}\"`;\n\t\t\tif (explicit) {\n\t\t\t\tif (!isAllowedDeliverChat(cfg, platform, explicit[2], origin)) {\n\t\t\t\t\treturn `deliver target \"${target}\" is not an allowed chat for ${platform}`;\n\t\t\t\t}\n\t\t\t} else if (!platformCfg.homeChannel) {\n\t\t\t\treturn `no homeChannel configured for ${platform}`;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t};\n}\n\n/** Wrap the run output with a compact cron header. */\nexport function wrapCronContent(job: CronJob, content: string): string {\n\treturn `☾ Cron: ${job.name}\\n———\\n${content}`;\n}\n\n/**\n * The platform deliverer installed at the `@lunr/cron-delivery` bridge.\n * Every target is attempted; the first error is returned (null on success).\n */\nexport function createPlatformDeliverer(adapters: Map<string, PlatformAdapter>, cfg: GatewayConfig): DeliveryBridge {\n\treturn async (job, content) => {\n\t\tconst targets = job.deliver\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\tlet firstError: string | null = null;\n\t\tfor (const target of targets) {\n\t\t\tif (target === \"local\") continue; // output file already written by the scheduler\n\t\t\tconst resolved = resolveTarget(target, job, cfg);\n\t\t\tif (typeof resolved === \"string\") {\n\t\t\t\tfirstError ??= resolved;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isAllowedDeliverChat(cfg, resolved.platform, resolved.chatId, job.origin)) {\n\t\t\t\tfirstError ??= `deliver target \"${target}\" is not an allowed chat for ${resolved.platform}`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst adapter = adapters.get(resolved.platform);\n\t\t\tif (!adapter) {\n\t\t\t\tfirstError ??= `no adapter connected for ${resolved.platform}`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst wrapped = wrapCronContent(job, content);\n\t\t\tfor (const chunk of splitMessage(wrapped, adapter.maxMessageLength)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await adapter.send(resolved.chatId, chunk, {\n\t\t\t\t\t\tthreadId: resolved.threadId,\n\t\t\t\t\t});\n\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\tfirstError ??= `${resolved.platform} send failed: ${result.error ?? \"unknown error\"}`;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tfirstError ??= `${resolved.platform} send failed: ${err instanceof Error ? err.message : String(err)}`;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn firstError;\n\t};\n}\n\n/** Race one prompt attempt against its share of the job budget. */\nfunction withAttemptTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n\treturn Promise.race([\n\t\tpromise,\n\t\tnew Promise<never>((_, reject) => {\n\t\t\tconst timer = setTimeout(() => reject(new Error(`attempt timed out after ${ms}ms`)), ms);\n\t\t\t// If the attempt settles first this promise is discarded; the timer must not keep the process alive.\n\t\t\ttimer.unref?.();\n\t\t}),\n\t]);\n}\n\n/**\n * Read settings.json `cronFallbackModels` (\"provider/modelId\" entries).\n * Fresh read per fire so edits apply without a daemon restart; invalid\n * entries are skipped with a log line. Never throws.\n */\nasync function readCronFallbackModels(): Promise<CronModelRef[]> {\n\ttry {\n\t\tconst [{ getAgentDir }, { SettingsManager }] = await Promise.all([\n\t\t\timport(\"../config.ts\"),\n\t\t\timport(\"../core/settings-manager.ts\"),\n\t\t]);\n\t\tconst settingsManager = SettingsManager.create(process.cwd(), getAgentDir(), { projectTrusted: false });\n\t\tconst out: CronModelRef[] = [];\n\t\tfor (const entry of settingsManager.getCronFallbackModels()) {\n\t\t\tconst idx = entry.indexOf(\"/\");\n\t\t\tif (idx <= 0 || idx === entry.length - 1) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[gateway cron] ignoring invalid cronFallbackModels entry \"${entry}\" (want \"provider/modelId\")`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tout.push({ provider: entry.slice(0, idx), modelId: entry.slice(idx + 1) });\n\t\t}\n\t\treturn out;\n\t} catch (err) {\n\t\tconsole.error(\n\t\t\t`[gateway cron] failed to read cronFallbackModels: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t\treturn [];\n\t}\n}\n\n/**\n * Start the cron scheduler inside the gateway daemon. Starts even with zero\n * stored jobs — jobs can be created later from chats. stop() halts the loop.\n */\nexport function startGatewayCron(options: GatewayCronOptions): { stop(): void; intervalMs: number } {\n\tconst { adapters, cfg } = options;\n\tconst sessionFactory = options.sessionFactory ?? defaultCronSessionFactory;\n\tconst platformDeliverer = createPlatformDeliverer(adapters, cfg);\n\n\t// Explicit so runJob can split it into per-attempt budgets that sum to (at\n\t// most) the scheduler's outer race (core/cron/scheduler.ts runSchedulerTick).\n\tconst jobTimeoutMs = 5 * 60 * 1000;\n\n\t// Reject deliver targets that are not local, origin, a configured home channel,\n\t// or an explicit chat in the platform allowlist / the job's origin.\n\tsetCronDeliverValidator(createDeliverValidator(cfg));\n\n\t// Replace the local-notify bridge lunr-cron registered with the platform deliverer.\n\t(globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;\n\n\tconst runJob = async (prompt: string, job: CronJob): Promise<string> => {\n\t\tconst fallbacks = options.fallbackModels ?? (await readCronFallbackModels());\n\t\tconst candidates: Array<CronModelRef | undefined> = [undefined, ...fallbacks];\n\t\tconst attemptTimeoutMs = Math.floor(jobTimeoutMs / candidates.length);\n\t\tconst errors: string[] = [];\n\t\tbeginCronFire();\n\t\ttry {\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tconst label = candidate ? `${candidate.provider}/${candidate.modelId}` : \"default model\";\n\t\t\t\tlet session: BridgeSession | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tsession = await sessionFactory(job, candidate);\n\t\t\t\t\t// Loading the builtin extensions re-registered lunr-cron's local-notify\n\t\t\t\t\t// bridge; restore the platform deliverer before any delivery re-reads it.\n\t\t\t\t\t(globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;\n\t\t\t\t\tawait withAttemptTimeout(session.prompt(prompt, { source: \"extension\" }), attemptTimeoutMs);\n\t\t\t\t\tconst text = extractFinalText(session);\n\t\t\t\t\t// The marker lands in the output file (the audit trail); [SILENT] as\n\t\t\t\t\t// the last line still suppresses delivery (scheduler isSilent check).\n\t\t\t\t\treturn candidate ? `[fell back to ${label}]\\n${text}` : text;\n\t\t\t\t} catch (err) {\n\t\t\t\t\terrors.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t\t} finally {\n\t\t\t\t\tif (session) await shutdownBridgeSession(session, \"quit\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new Error(errors.join(\" | \") || \"no model candidates\");\n\t\t} finally {\n\t\t\tendCronFire();\n\t\t}\n\t};\n\n\tconst deliverResult = async (job: CronJob, content: string): Promise<void> => {\n\t\t// Re-read the bridge on every delivery (same pattern as lunr-cron).\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] as DeliveryBridge | undefined;\n\t\tif (!bridge) throw new Error(\"no cron delivery bridge registered\");\n\t\tconst err = await bridge(job, content);\n\t\tif (err) throw new Error(err);\n\t};\n\n\tconst scheduler = startScheduler({ runJob, deliverResult, intervalMs: options.intervalMs, jobTimeoutMs });\n\treturn { stop: () => scheduler.stop(), intervalMs: options.intervalMs ?? 60_000 };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cron.js","sourceRoot":"","sources":["../../src/gateway/cron.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAGH,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAExE,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAsB,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAsB,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAGzC,MAAM,sBAAsB,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAuBjE,MAAM,eAAe,GAAG,CAAC,UAAU,EAAE,SAAS,CAAU,CAAC;AAEzD,0FAA0F;AAC1F,KAAK,UAAU,yBAAyB,CAAC,GAAY,EAAE,aAA4B,EAA0B;IAC5G,MAAM,CACL,EAAE,wBAAwB,EAAE,EAC5B,EAAE,WAAW,EAAE,EACf,EAAE,uBAAuB,EAAE,EAC3B,EAAE,uBAAuB,EAAE,EAC3B,EAAE,uBAAuB,EAAE,EAC3B,EAAE,8BAA8B,EAAE,0BAA0B,EAAE,EAC9D,EAAE,cAAc,EAAE,EAClB,EAAE,eAAe,EAAE,EACnB,EAAE,kBAAkB,EAAE,EACtB,GAAG,MA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E,aAAa,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAAC;IAC1G,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,MAAM,EAAE,CAAC;AAAA,CAClF","sourcesContent":["/**\n * lunR: gateway cron runner + delivery (Phase 4 of the cron/gateway roadmap).\n *\n * startGatewayCron() runs the core/cron scheduler inside the `lunr gateway`\n * daemon:\n *\n * - runJob: each fire gets a FRESH headless agent session (createAgentSession\n * with SessionManager.inMemory — cron runs never write session files and\n * never touch the per-chat gateway sessions; the files under\n * <agentDir>/cron/output/ are the audit trail). The shared fire-guard\n * (core/cron/fire-guard) brackets the turn so the `cron` tool refuses to\n * run inside it (jobs cannot schedule jobs).\n * - deliverResult: replaces the `@lunr/cron-delivery` bridge on globalThis\n * with a platform deliverer. Targets come from job.deliver\n * (comma-separated): \"local\" (no-op — the output file is already written),\n * \"origin\" (the chat that created the job, homeChannel fallback), a bare\n * platform name (that platform's homeChannel), or\n * \"<platform>:<chatId>[:<threadId>]\" (explicit). Content is wrapped as\n * \"Cron: <name>\" and split to the adapter's maxMessageLength.\n *\n * The bridge is re-installed after every cron session creation because loading\n * the builtin extensions (lunr-cron) re-registers its local-notify bridge per\n * session; delivery re-reads the bridge on every call, matching lunr-cron.\n *\n * Fallback models (2026-08-02): settings.json `cronFallbackModels`\n * (\"provider/modelId\" entries) are tried IN ORDER when a fire fails — timeout\n * or any error. Each attempt gets a fresh headless session and\n * jobTimeoutMs/candidates of the budget; a successful fallback run prefixes\n * \"[fell back to provider/modelId]\" to the output. TUI fires are unaffected\n * (they use the live session's model).\n */\n\nimport type { Model } from \"@ashx-j/lunr-ai\";\nimport { beginCronFire, endCronFire } from \"../core/cron/fire-guard.ts\";\nimport type { CronJob, CronJobOrigin } from \"../core/cron/jobs.ts\";\nimport { setCronDeliverValidator } from \"../core/cron/jobs.ts\";\nimport { startScheduler } from \"../core/cron/scheduler.ts\";\nimport { type BridgeSession, shutdownBridgeSession } from \"./agent-bridge.ts\";\nimport { type GatewayConfig, platformConfigFor } from \"./config.ts\";\nimport { splitMessage } from \"./text.ts\";\nimport type { PlatformAdapter } from \"./types.ts\";\n\nconst DELIVERY_BRIDGE_SYMBOL = Symbol.for(\"@lunr/cron-delivery\");\n\ntype DeliveryBridge = (job: CronJob, content: string) => Promise<string | null>;\n\n/** Test seam / default: one fresh headless session per cron fire. */\nexport interface CronModelRef {\n\tprovider: string;\n\tmodelId: string;\n}\n\nexport type CronSessionFactory = (job: CronJob, modelOverride?: CronModelRef) => Promise<BridgeSession>;\n\nexport interface GatewayCronOptions {\n\tadapters: Map<string, PlatformAdapter>;\n\tcfg: GatewayConfig;\n\t/** Tick interval; default 60s. */\n\tintervalMs?: number;\n\t/** Session factory for cron fires; defaults to a real headless agent session. */\n\tsessionFactory?: CronSessionFactory;\n\t/** Test seam: fallback models. When omitted, read fresh from settings.json `cronFallbackModels` on every fire. */\n\tfallbackModels?: CronModelRef[];\n}\n\nconst KNOWN_PLATFORMS = [\"telegram\", \"discord\"] as const;\n\n/** Default factory: fresh in-memory headless session, mirroring agent-bridge's wiring. */\nasync function defaultCronSessionFactory(job: CronJob, modelOverride?: CronModelRef): Promise<BridgeSession> {\n\tconst [\n\t\t{ loadAllBuiltinExtensions },\n\t\t{ getAgentDir },\n\t\t{ registerCustomizeBridge },\n\t\t{ registerMemoryCapBridge },\n\t\t{ registerModelTierBridge },\n\t\t{ createAgentSessionFromServices, createAgentSessionServices },\n\t\t{ SessionManager },\n\t\t{ SettingsManager },\n\t\t{ bindRuntimeBridges },\n\t] = await Promise.all([\n\t\timport(\"../builtin-extensions/index.ts\"),\n\t\timport(\"../config.ts\"),\n\t\timport(\"../core/customize.ts\"),\n\t\timport(\"../core/memory-cap.ts\"),\n\t\timport(\"../core/model-tiers.ts\"),\n\t\timport(\"../core/agent-session-services.ts\"),\n\t\timport(\"../core/session-manager.ts\"),\n\t\timport(\"../core/settings-manager.ts\"),\n\t\timport(\"../core/runtime-bridges.ts\"),\n\t]);\n\tconst cwd = job.workdir ?? process.cwd();\n\tconst agentDir = getAgentDir();\n\tconst settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: false });\n\tregisterModelTierBridge(settingsManager);\n\tregisterMemoryCapBridge(settingsManager);\n\tregisterCustomizeBridge(settingsManager);\n\n\t// In-memory on purpose: cron runs must not persist session files or pollute\n\t// the per-chat gateway sessions — <agentDir>/cron/output/ is the audit trail.\n\tconst sessionManager = SessionManager.inMemory(cwd);\n\n\t// Services-first (mirrors main.ts): extension-registered providers (e.g.\n\t// ollama-cloud) must land in the shared ModelRuntime BEFORE session\n\t// creation — otherwise findInitialModel can't resolve the user's default\n\t// model and silently falls back to an arbitrary catalog provider.\n\tconst services = await createAgentSessionServices({\n\t\tcwd,\n\t\tagentDir,\n\t\tsettingsManager,\n\t\tresourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() },\n\t});\n\t// Fallback-model attempts pin the session model explicitly; an unresolvable\n\t// or unauthenticated override fails the attempt so the next fallback runs.\n\tlet model: Model<any> | undefined;\n\tif (modelOverride) {\n\t\tconst resolved = services.modelRuntime.getModel(modelOverride.provider, modelOverride.modelId);\n\t\tif (!resolved) throw new Error(`model not found: ${modelOverride.provider}/${modelOverride.modelId}`);\n\t\tif (!services.modelRuntime.hasConfiguredAuth(resolved.provider)) {\n\t\t\tthrow new Error(`no configured auth for provider: ${modelOverride.provider}`);\n\t\t}\n\t\tmodel = resolved;\n\t}\n\tconst { session } = await createAgentSessionFromServices({ services, sessionManager, model });\n\tbindRuntimeBridges({ session, services });\n\tawait session.bindExtensions({\n\t\tmode: \"print\",\n\t\tonError: (err) => console.error(`[gateway cron] extension error (${err.extensionPath}): ${err.error}`),\n\t});\n\treturn session;\n}\n\n/** Final assistant text, print-mode style; throws on error/aborted stop. */\nfunction extractFinalText(session: BridgeSession): string {\n\tconst messages = session.state.messages;\n\tconst last = messages[messages.length - 1];\n\tif (last?.role !== \"assistant\") return \"\";\n\tconst assistant = last as {\n\t\tstopReason?: string;\n\t\terrorMessage?: string;\n\t\tcontent?: Array<{ type: string; text?: string }>;\n\t};\n\tif (assistant.stopReason === \"error\" || assistant.stopReason === \"aborted\") {\n\t\tthrow new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);\n\t}\n\tlet text = \"\";\n\tfor (const content of assistant.content ?? []) {\n\t\tif (content.type === \"text\") text += content.text ?? \"\";\n\t}\n\treturn text;\n}\n\ninterface ResolvedTarget {\n\tplatform: string;\n\tchatId: string;\n\tthreadId?: string;\n}\n\nconst EXPLICIT_TARGET_RE = /^([a-z0-9_-]+):([^:]+)(?::([^:]+))?$/i;\n\n/** Resolve one deliver target to a concrete destination. Returns an error string on failure. */\nfunction resolveTarget(target: string, job: CronJob, cfg: GatewayConfig): ResolvedTarget | string {\n\tif (target === \"origin\") {\n\t\tconst origin = job.origin;\n\t\tif (origin?.platform && origin.chatId) {\n\t\t\treturn { platform: origin.platform, chatId: origin.chatId, threadId: origin.threadId };\n\t\t}\n\t\t// Missing/incomplete origin → fall back to a homeChannel: the origin's\n\t\t// platform when known, otherwise the first platform that has one.\n\t\tconst platforms = origin?.platform ? [origin.platform] : KNOWN_PLATFORMS;\n\t\tfor (const platform of platforms) {\n\t\t\tconst home = platformConfigFor(cfg, platform)?.homeChannel;\n\t\t\tif (home) return { platform, chatId: home };\n\t\t}\n\t\treturn `deliver target \"origin\": job has no origin and no homeChannel is configured`;\n\t}\n\n\tconst explicit = EXPLICIT_TARGET_RE.exec(target);\n\tconst platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();\n\tif (platformConfigFor(cfg, platform) === undefined) {\n\t\treturn `unknown platform \"${explicit ? explicit[1] : target}\"`;\n\t}\n\tif (explicit) {\n\t\treturn { platform, chatId: explicit[2], threadId: explicit[3] };\n\t}\n\t// Bare platform name → its homeChannel.\n\tconst home = platformConfigFor(cfg, platform)?.homeChannel;\n\tif (!home) return `no homeChannel configured for ${platform}`;\n\treturn { platform, chatId: home };\n}\n\n/** True when a resolved chat may receive cron output for this job. */\nexport function isAllowedDeliverChat(\n\tcfg: GatewayConfig,\n\tplatform: string,\n\tchatId: string,\n\torigin?: CronJobOrigin | null,\n): boolean {\n\tconst platformCfg = platformConfigFor(cfg, platform);\n\tif (!platformCfg) return false;\n\tif (platformCfg.homeChannel && platformCfg.homeChannel === chatId) return true;\n\tif (platformCfg.allowedChats?.includes(chatId)) return true;\n\treturn origin?.platform === platform && origin.chatId === chatId;\n}\n\nexport function createDeliverValidator(\n\tcfg: GatewayConfig,\n): (deliver: string, origin?: CronJobOrigin | null) => string | undefined {\n\treturn (deliver, origin) => {\n\t\tconst targets = deliver\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\tfor (const target of targets) {\n\t\t\tif (target === \"local\") continue;\n\t\t\tif (target === \"origin\") continue; // delivery time resolves/fails with a sensible error\n\t\t\tconst explicit = EXPLICIT_TARGET_RE.exec(target);\n\t\t\tconst platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();\n\t\t\tconst platformCfg = platformConfigFor(cfg, platform);\n\t\t\tif (!platformCfg) return `unknown platform \"${explicit ? explicit[1] : target}\"`;\n\t\t\tif (explicit) {\n\t\t\t\tif (!isAllowedDeliverChat(cfg, platform, explicit[2], origin)) {\n\t\t\t\t\treturn `deliver target \"${target}\" is not an allowed chat for ${platform}`;\n\t\t\t\t}\n\t\t\t} else if (!platformCfg.homeChannel) {\n\t\t\t\treturn `no homeChannel configured for ${platform}`;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t};\n}\n\n/** Wrap the run output with a compact cron header. */\nexport function wrapCronContent(job: CronJob, content: string): string {\n\treturn `Cron: ${job.name}\\n———\\n${content}`;\n}\n\n/**\n * The platform deliverer installed at the `@lunr/cron-delivery` bridge.\n * Every target is attempted; the first error is returned (null on success).\n */\nexport function createPlatformDeliverer(adapters: Map<string, PlatformAdapter>, cfg: GatewayConfig): DeliveryBridge {\n\treturn async (job, content) => {\n\t\tconst targets = job.deliver\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\tlet firstError: string | null = null;\n\t\tfor (const target of targets) {\n\t\t\tif (target === \"local\") continue; // output file already written by the scheduler\n\t\t\tconst resolved = resolveTarget(target, job, cfg);\n\t\t\tif (typeof resolved === \"string\") {\n\t\t\t\tfirstError ??= resolved;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!isAllowedDeliverChat(cfg, resolved.platform, resolved.chatId, job.origin)) {\n\t\t\t\tfirstError ??= `deliver target \"${target}\" is not an allowed chat for ${resolved.platform}`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst adapter = adapters.get(resolved.platform);\n\t\t\tif (!adapter) {\n\t\t\t\tfirstError ??= `no adapter connected for ${resolved.platform}`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst wrapped = wrapCronContent(job, content);\n\t\t\tfor (const chunk of splitMessage(wrapped, adapter.maxMessageLength)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await adapter.send(resolved.chatId, chunk, {\n\t\t\t\t\t\tthreadId: resolved.threadId,\n\t\t\t\t\t});\n\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\tfirstError ??= `${resolved.platform} send failed: ${result.error ?? \"unknown error\"}`;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tfirstError ??= `${resolved.platform} send failed: ${err instanceof Error ? err.message : String(err)}`;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn firstError;\n\t};\n}\n\n/** Race one prompt attempt against its share of the job budget. */\nfunction withAttemptTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n\treturn Promise.race([\n\t\tpromise,\n\t\tnew Promise<never>((_, reject) => {\n\t\t\tconst timer = setTimeout(() => reject(new Error(`attempt timed out after ${ms}ms`)), ms);\n\t\t\t// If the attempt settles first this promise is discarded; the timer must not keep the process alive.\n\t\t\ttimer.unref?.();\n\t\t}),\n\t]);\n}\n\n/**\n * Read settings.json `cronFallbackModels` (\"provider/modelId\" entries).\n * Fresh read per fire so edits apply without a daemon restart; invalid\n * entries are skipped with a log line. Never throws.\n */\nasync function readCronFallbackModels(): Promise<CronModelRef[]> {\n\ttry {\n\t\tconst [{ getAgentDir }, { SettingsManager }] = await Promise.all([\n\t\t\timport(\"../config.ts\"),\n\t\t\timport(\"../core/settings-manager.ts\"),\n\t\t]);\n\t\tconst settingsManager = SettingsManager.create(process.cwd(), getAgentDir(), { projectTrusted: false });\n\t\tconst out: CronModelRef[] = [];\n\t\tfor (const entry of settingsManager.getCronFallbackModels()) {\n\t\t\tconst idx = entry.indexOf(\"/\");\n\t\t\tif (idx <= 0 || idx === entry.length - 1) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[gateway cron] ignoring invalid cronFallbackModels entry \"${entry}\" (want \"provider/modelId\")`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tout.push({ provider: entry.slice(0, idx), modelId: entry.slice(idx + 1) });\n\t\t}\n\t\treturn out;\n\t} catch (err) {\n\t\tconsole.error(\n\t\t\t`[gateway cron] failed to read cronFallbackModels: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t\treturn [];\n\t}\n}\n\n/**\n * Start the cron scheduler inside the gateway daemon. Starts even with zero\n * stored jobs — jobs can be created later from chats. stop() halts the loop.\n */\nexport function startGatewayCron(options: GatewayCronOptions): { stop(): void; intervalMs: number } {\n\tconst { adapters, cfg } = options;\n\tconst sessionFactory = options.sessionFactory ?? defaultCronSessionFactory;\n\tconst platformDeliverer = createPlatformDeliverer(adapters, cfg);\n\n\t// Explicit so runJob can split it into per-attempt budgets that sum to (at\n\t// most) the scheduler's outer race (core/cron/scheduler.ts runSchedulerTick).\n\tconst jobTimeoutMs = 5 * 60 * 1000;\n\n\t// Reject deliver targets that are not local, origin, a configured home channel,\n\t// or an explicit chat in the platform allowlist / the job's origin.\n\tsetCronDeliverValidator(createDeliverValidator(cfg));\n\n\t// Replace the local-notify bridge lunr-cron registered with the platform deliverer.\n\t(globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;\n\n\tconst runJob = async (prompt: string, job: CronJob): Promise<string> => {\n\t\tconst fallbacks = options.fallbackModels ?? (await readCronFallbackModels());\n\t\tconst candidates: Array<CronModelRef | undefined> = [undefined, ...fallbacks];\n\t\tconst attemptTimeoutMs = Math.floor(jobTimeoutMs / candidates.length);\n\t\tconst errors: string[] = [];\n\t\tbeginCronFire();\n\t\ttry {\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tconst label = candidate ? `${candidate.provider}/${candidate.modelId}` : \"default model\";\n\t\t\t\tlet session: BridgeSession | undefined;\n\t\t\t\ttry {\n\t\t\t\t\tsession = await sessionFactory(job, candidate);\n\t\t\t\t\t// Loading the builtin extensions re-registered lunr-cron's local-notify\n\t\t\t\t\t// bridge; restore the platform deliverer before any delivery re-reads it.\n\t\t\t\t\t(globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;\n\t\t\t\t\tawait withAttemptTimeout(session.prompt(prompt, { source: \"extension\" }), attemptTimeoutMs);\n\t\t\t\t\tconst text = extractFinalText(session);\n\t\t\t\t\t// The marker lands in the output file (the audit trail); [SILENT] as\n\t\t\t\t\t// the last line still suppresses delivery (scheduler isSilent check).\n\t\t\t\t\treturn candidate ? `[fell back to ${label}]\\n${text}` : text;\n\t\t\t\t} catch (err) {\n\t\t\t\t\terrors.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t\t} finally {\n\t\t\t\t\tif (session) await shutdownBridgeSession(session, \"quit\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow new Error(errors.join(\" | \") || \"no model candidates\");\n\t\t} finally {\n\t\t\tendCronFire();\n\t\t}\n\t};\n\n\tconst deliverResult = async (job: CronJob, content: string): Promise<void> => {\n\t\t// Re-read the bridge on every delivery (same pattern as lunr-cron).\n\t\tconst bridge = (globalThis as Record<symbol, unknown>)[DELIVERY_BRIDGE_SYMBOL] as DeliveryBridge | undefined;\n\t\tif (!bridge) throw new Error(\"no cron delivery bridge registered\");\n\t\tconst err = await bridge(job, content);\n\t\tif (err) throw new Error(err);\n\t};\n\n\tconst scheduler = startScheduler({ runJob, deliverResult, intervalMs: options.intervalMs, jobTimeoutMs });\n\treturn { stop: () => scheduler.stop(), intervalMs: options.intervalMs ?? 60_000 };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/gateway/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAUH,OAAO,EAGN,KAAK,cAAc,EAGnB,MAAM,aAAa,CAAC;AAQrB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,eAAe,CAGtF,CAAC;AAyOF,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAahE","sourcesContent":["/**\n * lunR: gateway daemon entry (Phase 2a skeleton; Phase 2b registered the\n * Telegram adapter, Phase 3 the Discord adapter — both via ADAPTER_FACTORIES).\n *\n * `lunr gateway` runs the daemon: load gateway.json, instantiate every\n * enabled platform that has a registered adapter factory AND a resolvable\n * token, connect, route messages, and stay alive until SIGINT/SIGTERM.\n * With no runnable adapters it prints per-platform setup instructions and\n * exits 1.\n *\n * Sub-commands:\n * lunr gateway pair approve <platform> <code> approve a pairing code\n * lunr gateway pair list show pending + paired\n * lunr gateway status config/token/session summary\n */\n\nimport { isFeatureEnabled } from \"../core/install-features.ts\";\nimport { DiscordAdapter } from \"./adapters/discord.ts\";\nimport { TelegramAdapter } from \"./adapters/telegram.ts\";\nimport { AgentBridge } from \"./agent-bridge.ts\";\nimport { handleApprovalCallback } from \"./approval.ts\";\nimport { addAllowedUser } from \"./authz.ts\";\nimport { handleCallback, startButtonSweeper, stopButtonSweeper } from \"./buttons.ts\";\nimport { botCommandSpecs } from \"./commands.ts\";\nimport {\n\ttype DiscordConfig,\n\tloadGatewayConfig,\n\ttype PlatformConfig,\n\tplatformConfigFor,\n\tresolvePlatformToken,\n} from \"./config.ts\";\nimport { startGatewayCron } from \"./cron.ts\";\nimport { createPairingStore } from \"./pairing.ts\";\nimport { startGatewayPresenter, stopGatewayPresenter } from \"./presenter.ts\";\nimport { createRouter } from \"./router.ts\";\nimport { claimGateway } from \"./service.ts\";\nimport { buildSessionKey } from \"./session-keys.ts\";\nimport { listSessions } from \"./store.ts\";\nimport type { PlatformAdapter } from \"./types.ts\";\n\n/**\n * Adapter registry — the seam adapters plug into:\n *\n * ADAPTER_FACTORIES.<platform> = (cfg) => new SomeAdapter(cfg);\n *\n * A factory receives the sanitized platform config with the token already\n * resolved into cfg.token (env beats file — see resolvePlatformToken and\n * runDaemon below). The registry type is the PlatformConfig base; adapters\n * with extra fields (Discord) narrow with a cast — the daemon always passes\n * the full sanitized per-platform object.\n */\nexport const ADAPTER_FACTORIES: Record<string, (cfg: PlatformConfig) => PlatformAdapter> = {\n\ttelegram: (cfg) => new TelegramAdapter(cfg),\n\tdiscord: (cfg) => new DiscordAdapter(cfg as DiscordConfig),\n};\n\nconst KNOWN_PLATFORMS = [\"telegram\", \"discord\"] as const;\n\nconst SETUP_INSTRUCTIONS: Record<string, string[]> = {\n\ttelegram: [\n\t\t\"Telegram: talk to @BotFather → /newbot → copy the token into\",\n\t\t\" <agentDir>/gateway.json (telegram.token) or export LUNR_TELEGRAM_BOT_TOKEN,\",\n\t\t\" then set telegram.enabled = true.\",\n\t],\n\tdiscord: [\n\t\t\"Discord: discord.com/developers → New Application → Bot → copy the token into\",\n\t\t\" <agentDir>/gateway.json (discord.token) or export LUNR_DISCORD_BOT_TOKEN,\",\n\t\t\" enable the MESSAGE CONTENT intent, then set discord.enabled = true.\",\n\t],\n};\n\nfunction printSetupInstructions(enabledButUnrunnable: string[]): void {\n\tconsole.log(\"lunR gateway: no runnable platforms configured.\");\n\tfor (const platform of enabledButUnrunnable) {\n\t\tconsole.log(` (platform \"${platform}\" is enabled but has no registered adapter or resolvable token)`);\n\t}\n\tfor (const platform of KNOWN_PLATFORMS) {\n\t\tfor (const line of SETUP_INSTRUCTIONS[platform]) {\n\t\t\tconsole.log(line);\n\t\t}\n\t}\n}\n\nasync function runPairApprove(platform: string, code: string | undefined): Promise<number> {\n\tif (!code) {\n\t\tconsole.error(\"Usage: lunr gateway pair approve <platform> <code>\");\n\t\treturn 1;\n\t}\n\tconst pairing = createPairingStore();\n\tconst userId = pairing.approve(platform, code);\n\tif (userId === null) {\n\t\tconsole.error(`Pairing failed: no valid pending code \"${code}\" for ${platform} (wrong, expired, or locked out).`);\n\t\treturn 1;\n\t}\n\ttry {\n\t\taddAllowedUser(platform, userId);\n\t} catch (err) {\n\t\tconsole.error(`Paired ${platform} user ${userId}, but could not persist allowedUsers: ${err}`);\n\t\treturn 1;\n\t}\n\tconsole.log(`Approved ${platform} user ${userId} (added to ${platform}.allowedUsers in gateway.json).`);\n\treturn 0;\n}\n\nfunction runPairList(): number {\n\tconst pairing = createPairingStore();\n\tconst pending = pairing.listPending();\n\tconst approved = pairing.listApproved();\n\tconsole.log(\"Pending pairing codes:\");\n\tif (pending.length === 0) {\n\t\tconsole.log(\" (none)\");\n\t} else {\n\t\tfor (const p of pending) {\n\t\t\tconsole.log(` ${p.platform} ${p.code} user=${p.userId} expires ${new Date(p.expiresAt).toISOString()}`);\n\t\t}\n\t}\n\tconsole.log(\"Paired users:\");\n\tif (approved.length === 0) {\n\t\tconsole.log(\" (none)\");\n\t} else {\n\t\tfor (const u of approved) {\n\t\t\tconsole.log(` ${u.platform} ${u.userId} approved ${new Date(u.approvedAt).toISOString()}`);\n\t\t}\n\t}\n\treturn 0;\n}\n\nfunction runStatus(): number {\n\tconst cfg = loadGatewayConfig();\n\tconsole.log(\n\t\t`chat-platforms: ${isFeatureEnabled(\"chat-platforms\") ? \"enabled\" : \"disabled\"} (install-features.json)`,\n\t);\n\tconsole.log(\"lunR gateway status:\");\n\tfor (const platform of KNOWN_PLATFORMS) {\n\t\tconst platformCfg = platformConfigFor(cfg, platform);\n\t\tif (!platformCfg) continue;\n\t\tconst token = resolvePlatformToken(platform, platformCfg);\n\t\tconst adapter = ADAPTER_FACTORIES[platform] === undefined ? \"no adapter\" : \"adapter registered\";\n\t\tconsole.log(\n\t\t\t` ${platform}: ${platformCfg.enabled ? \"enabled\" : \"disabled\"} · token ${token ? \"resolved\" : \"missing\"} · ${adapter}`,\n\t\t);\n\t}\n\tconst sessions = listSessions();\n\tconsole.log(` sessions: ${Object.keys(sessions).length} stored`);\n\treturn 0;\n}\n\nasync function runDaemon(): Promise<number> {\n\tif (!isFeatureEnabled(\"chat-platforms\")) {\n\t\tconsole.error(\"lunR gateway: chat platforms are not enabled.\");\n\t\tconsole.error(\"Enable with: lunr features enable chat-platforms\");\n\t\treturn 1;\n\t}\n\tconst cfg = loadGatewayConfig();\n\tconst adapters = new Map<string, PlatformAdapter>();\n\tconst skipped: string[] = [];\n\n\tfor (const platform of KNOWN_PLATFORMS) {\n\t\tconst platformCfg = platformConfigFor(cfg, platform);\n\t\tif (!platformCfg?.enabled) continue;\n\t\tconst factory: ((cfg: PlatformConfig) => PlatformAdapter) | undefined = ADAPTER_FACTORIES[platform];\n\t\tif (factory === undefined) {\n\t\t\tskipped.push(platform);\n\t\t\tcontinue;\n\t\t}\n\t\tconst token = resolvePlatformToken(platform, platformCfg);\n\t\tif (!token) {\n\t\t\tskipped.push(platform);\n\t\t\tcontinue;\n\t\t}\n\t\tadapters.set(platform, factory({ ...platformCfg, token }));\n\t}\n\n\tif (adapters.size === 0) {\n\t\tprintSetupInstructions(skipped);\n\t\treturn 1;\n\t}\n\n\tconst pairing = createPairingStore();\n\tconst bridge = new AgentBridge();\n\tfor (const adapter of adapters.values())\n\t\tadapter.setCommandSuggestions?.(async (source, command) => {\n\t\t\tconst session = bridge.peekSession(buildSessionKey(source, loadGatewayConfig()));\n\t\t\tif (!session) return [];\n\t\t\tif (command === \"thinking\") return session.getAvailableThinkingLevels();\n\t\t\tif (command === \"model\")\n\t\t\t\treturn (await session.modelRuntime.getAvailable()).map((model) => `${model.provider}/${model.id}`);\n\t\t\treturn [];\n\t\t});\n\tconst router = createRouter({ adapters, cfg, pairing, bridge, reloadConfig: true, remoteControls: true });\n\n\tlet finish!: () => void;\n\tconst stopped = new Promise<void>((resolve) => {\n\t\tfinish = resolve;\n\t});\n\tlet stopping = false;\n\tlet cron: ReturnType<typeof startGatewayCron> | undefined;\n\tconst platformStatus: Record<string, string> = {};\n\tconst retries = new Set<ReturnType<typeof setTimeout>>();\n\tconst shutdown = () => {\n\t\tif (stopping) return;\n\t\tstopping = true;\n\t\towner.update(platformStatus, \"stopping\");\n\t\tcron?.stop();\n\t\tfor (const timer of retries) clearTimeout(timer);\n\t\tstopButtonSweeper();\n\t\tvoid (async () => {\n\t\t\tawait bridge.shutdown();\n\t\t\tawait Promise.all([...adapters.values()].map((adapter) => adapter.disconnect().catch(() => {})));\n\t\t\tstopGatewayPresenter();\n\t\t\towner.release();\n\t\t\tprocess.removeListener(\"SIGINT\", shutdown);\n\t\t\tprocess.removeListener(\"SIGTERM\", shutdown);\n\t\t\tfinish();\n\t\t})().catch((error) => {\n\t\t\tconsole.error(\"Gateway shutdown failed:\", error instanceof Error ? error.message : String(error));\n\t\t\tstopping = false;\n\t\t\towner.update(platformStatus, \"ready\");\n\t\t\tstartButtonSweeper();\n\t\t\tcron = startGatewayCron({ adapters, cfg });\n\t\t\tfor (const [platform, adapter] of adapters)\n\t\t\t\tif (platformStatus[platform] !== \"connected\") void connect(platform, adapter);\n\t\t});\n\t};\n\tconst owner = claimGateway(shutdown);\n\tprocess.on(\"SIGINT\", shutdown);\n\tprocess.on(\"SIGTERM\", shutdown);\n\tstartGatewayPresenter(adapters);\n\tconst connected: PlatformAdapter[] = [];\n\tstartButtonSweeper();\n\tconst connect = async (platform: string, adapter: PlatformAdapter): Promise<void> => {\n\t\tif (stopping) return;\n\t\ttry {\n\t\t\tplatformStatus[platform] = \"connecting\";\n\t\t\towner.update(platformStatus, \"starting\");\n\t\t\tconst ok = await adapter.connect();\n\t\t\tif (!ok) {\n\t\t\t\tthrow new Error(\"Connection failed\");\n\t\t\t}\n\t\t\tadapter.onMessage((event) => {\n\t\t\t\tvoid router.handleEvent(event);\n\t\t\t});\n\t\t\tadapter.onCallback(async (event) => {\n\t\t\t\tconst consumed = await handleApprovalCallback(event, adapter);\n\t\t\t\tif (!consumed) {\n\t\t\t\t\tvoid handleCallback(event, { adapters, cfg: loadGatewayConfig(), pairing, bridge, adapter });\n\t\t\t\t}\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tawait adapter.registerCommands?.(botCommandSpecs());\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[gateway] ${platform}: command menu registration failed: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (stopping) {\n\t\t\t\tawait adapter.disconnect();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconnected.push(adapter);\n\t\t\tplatformStatus[platform] = \"connected\";\n\t\t\tconsole.log(`lunR gateway: ${platform} connected`);\n\t\t} catch {\n\t\t\tplatformStatus[platform] = \"disconnected, retrying\";\n\t\t\tawait adapter.disconnect().catch(() => {});\n\t\t\tif (!stopping) {\n\t\t\t\tconst retry = setTimeout(() => {\n\t\t\t\t\tretries.delete(retry);\n\t\t\t\t\tvoid connect(platform, adapter);\n\t\t\t\t}, 5000);\n\t\t\t\tretries.add(retry);\n\t\t\t}\n\t\t}\n\t\tif (!stopping) owner.update(platformStatus);\n\t};\n\tfor (const [platform, adapter] of adapters) void connect(platform, adapter);\n\n\t// Phase 4: cron jobs fire inside the daemon and deliver back to chats.\n\t// Starts even with zero stored jobs — jobs can be created later from chats.\n\tcron = startGatewayCron({ adapters, cfg });\n\tconsole.log(`lunR gateway: cron scheduler started (${cron.intervalMs / 1000}s interval)`);\n\n\towner.update(platformStatus);\n\tawait stopped;\n\treturn 0;\n}\n\nexport async function runGateway(args: string[]): Promise<number> {\n\tconst [sub, ...rest] = args;\n\tif (sub === \"pair\") {\n\t\tconst [action, platform, code] = rest;\n\t\tif (action === \"approve\" && platform) return runPairApprove(platform, code);\n\t\tif (action === \"list\") return runPairList();\n\t\tconsole.error(\"Usage: lunr gateway pair approve <platform> <code> | lunr gateway pair list\");\n\t\treturn 1;\n\t}\n\tif (sub === \"status\") return runStatus();\n\tif (sub === undefined) return runDaemon();\n\tconsole.error(`Unknown gateway sub-command \"${sub}\". Expected: pair approve | pair list | status`);\n\treturn 1;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/gateway/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAUH,OAAO,EAGN,KAAK,cAAc,EAInB,MAAM,aAAa,CAAC;AAQrB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,cAAc,KAAK,eAAe,CAGtF,CAAC;AAyOF,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAchE","sourcesContent":["/**\n * lunR: gateway daemon entry (Phase 2a skeleton; Phase 2b registered the\n * Telegram adapter, Phase 3 the Discord adapter — both via ADAPTER_FACTORIES).\n *\n * `lunr gateway` runs the daemon: load gateway.json, instantiate every\n * enabled platform that has a registered adapter factory AND a resolvable\n * token, connect, route messages, and stay alive until SIGINT/SIGTERM.\n * With no runnable adapters it prints per-platform setup instructions and\n * exits 1.\n *\n * Sub-commands:\n * lunr gateway pair approve <platform> <code> approve a pairing code\n * lunr gateway pair list show pending + paired\n * lunr gateway status config/token/session summary\n */\n\nimport { isFeatureEnabled } from \"../core/install-features.ts\";\nimport { DiscordAdapter } from \"./adapters/discord.ts\";\nimport { TelegramAdapter } from \"./adapters/telegram.ts\";\nimport { AgentBridge } from \"./agent-bridge.ts\";\nimport { handleApprovalCallback } from \"./approval.ts\";\nimport { addAllowedUser } from \"./authz.ts\";\nimport { handleCallback, startButtonSweeper, stopButtonSweeper } from \"./buttons.ts\";\nimport { botCommandSpecs } from \"./commands.ts\";\nimport {\n\ttype DiscordConfig,\n\tloadGatewayConfig,\n\ttype PlatformConfig,\n\tplatformConfigFor,\n\tresolvePlatformToken,\n\tsaveGatewayConfig,\n} from \"./config.ts\";\nimport { startGatewayCron } from \"./cron.ts\";\nimport { createPairingStore } from \"./pairing.ts\";\nimport { startGatewayPresenter, stopGatewayPresenter } from \"./presenter.ts\";\nimport { createRouter } from \"./router.ts\";\nimport { claimGateway } from \"./service.ts\";\nimport { buildSessionKey } from \"./session-keys.ts\";\nimport { listSessions } from \"./store.ts\";\nimport type { PlatformAdapter } from \"./types.ts\";\n\n/**\n * Adapter registry — the seam adapters plug into:\n *\n * ADAPTER_FACTORIES.<platform> = (cfg) => new SomeAdapter(cfg);\n *\n * A factory receives the sanitized platform config with the token already\n * resolved into cfg.token (env beats file — see resolvePlatformToken and\n * runDaemon below). The registry type is the PlatformConfig base; adapters\n * with extra fields (Discord) narrow with a cast — the daemon always passes\n * the full sanitized per-platform object.\n */\nexport const ADAPTER_FACTORIES: Record<string, (cfg: PlatformConfig) => PlatformAdapter> = {\n\ttelegram: (cfg) => new TelegramAdapter(cfg),\n\tdiscord: (cfg) => new DiscordAdapter(cfg as DiscordConfig),\n};\n\nconst KNOWN_PLATFORMS = [\"telegram\", \"discord\"] as const;\n\nconst SETUP_INSTRUCTIONS: Record<string, string[]> = {\n\ttelegram: [\"Telegram: run lunr gateway setup locally to configure the bot token and owner ID.\"],\n\tdiscord: [\"Discord: run lunr gateway setup locally to configure the bot token and owner ID.\"],\n};\n\nfunction printSetupInstructions(enabledButUnrunnable: string[]): void {\n\tconsole.log(\"lunR gateway: no runnable platforms configured.\");\n\tfor (const platform of enabledButUnrunnable) {\n\t\tconsole.log(` (platform \"${platform}\" is enabled but has no registered adapter or resolvable token)`);\n\t}\n\tfor (const platform of KNOWN_PLATFORMS) {\n\t\tfor (const line of SETUP_INSTRUCTIONS[platform]) {\n\t\t\tconsole.log(line);\n\t\t}\n\t}\n}\n\nasync function runPairApprove(platform: string, code: string | undefined, owner = false): Promise<number> {\n\tif (!code) {\n\t\tconsole.error(\"Usage: lunr gateway pair approve <platform> <code> [--owner]\");\n\t\treturn 1;\n\t}\n\tconst pairing = createPairingStore();\n\tconst userId = pairing.approve(platform, code);\n\tif (userId === null) {\n\t\tconsole.error(`Pairing failed: no valid pending code \"${code}\" for ${platform} (wrong, expired, or locked out).`);\n\t\treturn 1;\n\t}\n\ttry {\n\t\tif (owner) {\n\t\t\tconst cfg = loadGatewayConfig();\n\t\t\tif (platform !== \"telegram\" && platform !== \"discord\") throw new Error(\"Unknown platform.\");\n\t\t\tcfg.owners ??= { telegram: [], discord: [] };\n\t\t\tcfg.owners[platform] = [...new Set([...cfg.owners[platform], userId])];\n\t\t\tcfg[platform].allowedUsers = [...new Set([...cfg[platform].allowedUsers, userId])];\n\t\t\tsaveGatewayConfig(cfg);\n\t\t} else addAllowedUser(platform, userId);\n\t} catch (err) {\n\t\tconsole.error(`Paired ${platform} user ${userId}, but could not persist allowedUsers: ${err}`);\n\t\treturn 1;\n\t}\n\tconsole.log(\n\t\t`Approved ${platform} user ${userId}${owner ? \" as owner with local project and TUI access\" : \" for chat only; owner access requires local --owner approval\"}.`,\n\t);\n\treturn 0;\n}\n\nfunction runPairList(): number {\n\tconst pairing = createPairingStore();\n\tconst pending = pairing.listPending();\n\tconst approved = pairing.listApproved();\n\tconsole.log(\"Pending pairing codes:\");\n\tif (pending.length === 0) {\n\t\tconsole.log(\" (none)\");\n\t} else {\n\t\tfor (const p of pending) {\n\t\t\tconsole.log(` ${p.platform} ${p.code} user=${p.userId} expires ${new Date(p.expiresAt).toISOString()}`);\n\t\t}\n\t}\n\tconsole.log(\"Paired users:\");\n\tif (approved.length === 0) {\n\t\tconsole.log(\" (none)\");\n\t} else {\n\t\tfor (const u of approved) {\n\t\t\tconsole.log(` ${u.platform} ${u.userId} approved ${new Date(u.approvedAt).toISOString()}`);\n\t\t}\n\t}\n\treturn 0;\n}\n\nfunction runStatus(): number {\n\tconst cfg = loadGatewayConfig();\n\tconsole.log(\n\t\t`chat-platforms: ${isFeatureEnabled(\"chat-platforms\") ? \"enabled\" : \"disabled\"} (install-features.json)`,\n\t);\n\tconsole.log(\"lunR gateway status:\");\n\tfor (const platform of KNOWN_PLATFORMS) {\n\t\tconst platformCfg = platformConfigFor(cfg, platform);\n\t\tif (!platformCfg) continue;\n\t\tconst token = resolvePlatformToken(platform, platformCfg);\n\t\tconst adapter = ADAPTER_FACTORIES[platform] === undefined ? \"no adapter\" : \"adapter registered\";\n\t\tconsole.log(\n\t\t\t` ${platform}: ${platformCfg.enabled ? \"enabled\" : \"disabled\"} · token ${token ? \"resolved\" : \"missing\"} · ${adapter}`,\n\t\t);\n\t}\n\tconst sessions = listSessions();\n\tconsole.log(` sessions: ${Object.keys(sessions).length} stored`);\n\treturn 0;\n}\n\nasync function runDaemon(): Promise<number> {\n\tif (!isFeatureEnabled(\"chat-platforms\")) {\n\t\tconsole.error(\"lunR gateway: chat platforms are not enabled.\");\n\t\tconsole.error(\"Enable with: lunr features enable chat-platforms\");\n\t\treturn 1;\n\t}\n\tconst cfg = loadGatewayConfig();\n\tconst adapters = new Map<string, PlatformAdapter>();\n\tconst skipped: string[] = [];\n\n\tfor (const platform of KNOWN_PLATFORMS) {\n\t\tconst platformCfg = platformConfigFor(cfg, platform);\n\t\tif (!platformCfg?.enabled) continue;\n\t\tconst factory: ((cfg: PlatformConfig) => PlatformAdapter) | undefined = ADAPTER_FACTORIES[platform];\n\t\tif (factory === undefined) {\n\t\t\tskipped.push(platform);\n\t\t\tcontinue;\n\t\t}\n\t\tconst token = resolvePlatformToken(platform, platformCfg);\n\t\tif (!token) {\n\t\t\tskipped.push(platform);\n\t\t\tcontinue;\n\t\t}\n\t\tadapters.set(platform, factory({ ...platformCfg, token }));\n\t}\n\n\tif (adapters.size === 0) {\n\t\tprintSetupInstructions(skipped);\n\t\treturn 1;\n\t}\n\n\tconst pairing = createPairingStore();\n\tconst bridge = new AgentBridge();\n\tfor (const adapter of adapters.values())\n\t\tadapter.setCommandSuggestions?.(async (source, command) => {\n\t\t\tconst session = bridge.peekSession(buildSessionKey(source, loadGatewayConfig()));\n\t\t\tif (!session) return [];\n\t\t\tif (command === \"thinking\") return session.getAvailableThinkingLevels();\n\t\t\tif (command === \"model\")\n\t\t\t\treturn (await session.modelRuntime.getAvailable()).map((model) => `${model.provider}/${model.id}`);\n\t\t\treturn [];\n\t\t});\n\tconst router = createRouter({ adapters, cfg, pairing, bridge, reloadConfig: true, remoteControls: true });\n\n\tlet finish!: () => void;\n\tconst stopped = new Promise<void>((resolve) => {\n\t\tfinish = resolve;\n\t});\n\tlet stopping = false;\n\tlet cron: ReturnType<typeof startGatewayCron> | undefined;\n\tconst platformStatus: Record<string, string> = {};\n\tconst retries = new Set<ReturnType<typeof setTimeout>>();\n\tconst shutdown = () => {\n\t\tif (stopping) return;\n\t\tstopping = true;\n\t\towner.update(platformStatus, \"stopping\");\n\t\tcron?.stop();\n\t\tfor (const timer of retries) clearTimeout(timer);\n\t\tstopButtonSweeper();\n\t\tvoid (async () => {\n\t\t\tawait bridge.shutdown();\n\t\t\tawait Promise.all([...adapters.values()].map((adapter) => adapter.disconnect().catch(() => {})));\n\t\t\tstopGatewayPresenter();\n\t\t\towner.release();\n\t\t\tprocess.removeListener(\"SIGINT\", shutdown);\n\t\t\tprocess.removeListener(\"SIGTERM\", shutdown);\n\t\t\tfinish();\n\t\t})().catch((error) => {\n\t\t\tconsole.error(\"Gateway shutdown failed:\", error instanceof Error ? error.message : String(error));\n\t\t\tstopping = false;\n\t\t\towner.update(platformStatus, Object.values(platformStatus).includes(\"connected\") ? \"ready\" : \"starting\");\n\t\t\tstartButtonSweeper();\n\t\t\tcron = startGatewayCron({ adapters, cfg });\n\t\t\tfor (const [platform, adapter] of adapters)\n\t\t\t\tif (platformStatus[platform] !== \"connected\") void connect(platform, adapter);\n\t\t});\n\t};\n\tconst owner = claimGateway(shutdown);\n\tprocess.on(\"SIGINT\", shutdown);\n\tprocess.on(\"SIGTERM\", shutdown);\n\tstartGatewayPresenter(adapters);\n\tstartButtonSweeper();\n\tconst connect = async (platform: string, adapter: PlatformAdapter): Promise<void> => {\n\t\tif (stopping) return;\n\t\ttry {\n\t\t\tplatformStatus[platform] = \"connecting\";\n\t\t\towner.update(platformStatus, Object.values(platformStatus).includes(\"connected\") ? \"ready\" : \"starting\");\n\t\t\tconst ok = await adapter.connect();\n\t\t\tif (!ok) {\n\t\t\t\tthrow new Error(\"Connection failed\");\n\t\t\t}\n\t\t\tadapter.onMessage((event) => {\n\t\t\t\tvoid router.handleEvent(event);\n\t\t\t});\n\t\t\tadapter.onCallback(async (event) => {\n\t\t\t\tconst consumed = await handleApprovalCallback(event, adapter);\n\t\t\t\tif (!consumed) {\n\t\t\t\t\tvoid handleCallback(event, { adapters, cfg: loadGatewayConfig(), pairing, bridge, adapter });\n\t\t\t\t}\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tawait adapter.registerCommands?.(botCommandSpecs());\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[gateway] ${platform}: command menu registration failed: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (stopping) {\n\t\t\t\tawait adapter.disconnect();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tplatformStatus[platform] = \"connected\";\n\t\t\tconsole.log(`lunR gateway: ${platform} connected`);\n\t\t} catch {\n\t\t\tplatformStatus[platform] = \"disconnected, retrying (check gateway logs)\";\n\t\t\tawait adapter.disconnect().catch(() => {});\n\t\t\tif (!stopping) {\n\t\t\t\tconst retry = setTimeout(() => {\n\t\t\t\t\tretries.delete(retry);\n\t\t\t\t\tvoid connect(platform, adapter);\n\t\t\t\t}, 5000);\n\t\t\t\tretries.add(retry);\n\t\t\t}\n\t\t}\n\t\tif (!stopping)\n\t\t\towner.update(platformStatus, Object.values(platformStatus).includes(\"connected\") ? \"ready\" : \"starting\");\n\t};\n\tfor (const [platform, adapter] of adapters) void connect(platform, adapter);\n\n\t// Phase 4: cron jobs fire inside the daemon and deliver back to chats.\n\t// Starts even with zero stored jobs — jobs can be created later from chats.\n\tcron = startGatewayCron({ adapters, cfg });\n\tconsole.log(`lunR gateway: cron scheduler started (${cron.intervalMs / 1000}s interval)`);\n\n\towner.update(platformStatus, \"starting\");\n\tawait stopped;\n\treturn 0;\n}\n\nexport async function runGateway(args: string[]): Promise<number> {\n\tconst [sub, ...rest] = args;\n\tif (sub === \"pair\") {\n\t\tconst [action, platform, code, flag] = rest;\n\t\tif (action === \"approve\" && platform && (flag === undefined || flag === \"--owner\"))\n\t\t\treturn runPairApprove(platform, code, flag === \"--owner\");\n\t\tif (action === \"list\") return runPairList();\n\t\tconsole.error(\"Usage: lunr gateway pair approve <platform> <code> [--owner] | lunr gateway pair list\");\n\t\treturn 1;\n\t}\n\tif (sub === \"status\") return runStatus();\n\tif (sub === undefined) return runDaemon();\n\tconsole.error(`Unknown gateway sub-command \"${sub}\". Expected: pair approve | pair list | status`);\n\treturn 1;\n}\n"]}
|
package/dist/gateway/index.js
CHANGED
|
@@ -21,7 +21,7 @@ import { handleApprovalCallback } from "./approval.js";
|
|
|
21
21
|
import { addAllowedUser } from "./authz.js";
|
|
22
22
|
import { handleCallback, startButtonSweeper, stopButtonSweeper } from "./buttons.js";
|
|
23
23
|
import { botCommandSpecs } from "./commands.js";
|
|
24
|
-
import { loadGatewayConfig, platformConfigFor, resolvePlatformToken, } from "./config.js";
|
|
24
|
+
import { loadGatewayConfig, platformConfigFor, resolvePlatformToken, saveGatewayConfig, } from "./config.js";
|
|
25
25
|
import { startGatewayCron } from "./cron.js";
|
|
26
26
|
import { createPairingStore } from "./pairing.js";
|
|
27
27
|
import { startGatewayPresenter, stopGatewayPresenter } from "./presenter.js";
|
|
@@ -46,16 +46,8 @@ export const ADAPTER_FACTORIES = {
|
|
|
46
46
|
};
|
|
47
47
|
const KNOWN_PLATFORMS = ["telegram", "discord"];
|
|
48
48
|
const SETUP_INSTRUCTIONS = {
|
|
49
|
-
telegram: [
|
|
50
|
-
|
|
51
|
-
" <agentDir>/gateway.json (telegram.token) or export LUNR_TELEGRAM_BOT_TOKEN,",
|
|
52
|
-
" then set telegram.enabled = true.",
|
|
53
|
-
],
|
|
54
|
-
discord: [
|
|
55
|
-
"Discord: discord.com/developers → New Application → Bot → copy the token into",
|
|
56
|
-
" <agentDir>/gateway.json (discord.token) or export LUNR_DISCORD_BOT_TOKEN,",
|
|
57
|
-
" enable the MESSAGE CONTENT intent, then set discord.enabled = true.",
|
|
58
|
-
],
|
|
49
|
+
telegram: ["Telegram: run lunr gateway setup locally to configure the bot token and owner ID."],
|
|
50
|
+
discord: ["Discord: run lunr gateway setup locally to configure the bot token and owner ID."],
|
|
59
51
|
};
|
|
60
52
|
function printSetupInstructions(enabledButUnrunnable) {
|
|
61
53
|
console.log("lunR gateway: no runnable platforms configured.");
|
|
@@ -68,9 +60,9 @@ function printSetupInstructions(enabledButUnrunnable) {
|
|
|
68
60
|
}
|
|
69
61
|
}
|
|
70
62
|
}
|
|
71
|
-
async function runPairApprove(platform, code) {
|
|
63
|
+
async function runPairApprove(platform, code, owner = false) {
|
|
72
64
|
if (!code) {
|
|
73
|
-
console.error("Usage: lunr gateway pair approve <platform> <code>");
|
|
65
|
+
console.error("Usage: lunr gateway pair approve <platform> <code> [--owner]");
|
|
74
66
|
return 1;
|
|
75
67
|
}
|
|
76
68
|
const pairing = createPairingStore();
|
|
@@ -80,13 +72,23 @@ async function runPairApprove(platform, code) {
|
|
|
80
72
|
return 1;
|
|
81
73
|
}
|
|
82
74
|
try {
|
|
83
|
-
|
|
75
|
+
if (owner) {
|
|
76
|
+
const cfg = loadGatewayConfig();
|
|
77
|
+
if (platform !== "telegram" && platform !== "discord")
|
|
78
|
+
throw new Error("Unknown platform.");
|
|
79
|
+
cfg.owners ??= { telegram: [], discord: [] };
|
|
80
|
+
cfg.owners[platform] = [...new Set([...cfg.owners[platform], userId])];
|
|
81
|
+
cfg[platform].allowedUsers = [...new Set([...cfg[platform].allowedUsers, userId])];
|
|
82
|
+
saveGatewayConfig(cfg);
|
|
83
|
+
}
|
|
84
|
+
else
|
|
85
|
+
addAllowedUser(platform, userId);
|
|
84
86
|
}
|
|
85
87
|
catch (err) {
|
|
86
88
|
console.error(`Paired ${platform} user ${userId}, but could not persist allowedUsers: ${err}`);
|
|
87
89
|
return 1;
|
|
88
90
|
}
|
|
89
|
-
console.log(`Approved ${platform} user ${userId}
|
|
91
|
+
console.log(`Approved ${platform} user ${userId}${owner ? " as owner with local project and TUI access" : " for chat only; owner access requires local --owner approval"}.`);
|
|
90
92
|
return 0;
|
|
91
93
|
}
|
|
92
94
|
function runPairList() {
|
|
@@ -200,7 +202,7 @@ async function runDaemon() {
|
|
|
200
202
|
})().catch((error) => {
|
|
201
203
|
console.error("Gateway shutdown failed:", error instanceof Error ? error.message : String(error));
|
|
202
204
|
stopping = false;
|
|
203
|
-
owner.update(platformStatus, "ready");
|
|
205
|
+
owner.update(platformStatus, Object.values(platformStatus).includes("connected") ? "ready" : "starting");
|
|
204
206
|
startButtonSweeper();
|
|
205
207
|
cron = startGatewayCron({ adapters, cfg });
|
|
206
208
|
for (const [platform, adapter] of adapters)
|
|
@@ -212,14 +214,13 @@ async function runDaemon() {
|
|
|
212
214
|
process.on("SIGINT", shutdown);
|
|
213
215
|
process.on("SIGTERM", shutdown);
|
|
214
216
|
startGatewayPresenter(adapters);
|
|
215
|
-
const connected = [];
|
|
216
217
|
startButtonSweeper();
|
|
217
218
|
const connect = async (platform, adapter) => {
|
|
218
219
|
if (stopping)
|
|
219
220
|
return;
|
|
220
221
|
try {
|
|
221
222
|
platformStatus[platform] = "connecting";
|
|
222
|
-
owner.update(platformStatus, "starting");
|
|
223
|
+
owner.update(platformStatus, Object.values(platformStatus).includes("connected") ? "ready" : "starting");
|
|
223
224
|
const ok = await adapter.connect();
|
|
224
225
|
if (!ok) {
|
|
225
226
|
throw new Error("Connection failed");
|
|
@@ -243,12 +244,11 @@ async function runDaemon() {
|
|
|
243
244
|
await adapter.disconnect();
|
|
244
245
|
return;
|
|
245
246
|
}
|
|
246
|
-
connected.push(adapter);
|
|
247
247
|
platformStatus[platform] = "connected";
|
|
248
248
|
console.log(`lunR gateway: ${platform} connected`);
|
|
249
249
|
}
|
|
250
250
|
catch {
|
|
251
|
-
platformStatus[platform] = "disconnected, retrying";
|
|
251
|
+
platformStatus[platform] = "disconnected, retrying (check gateway logs)";
|
|
252
252
|
await adapter.disconnect().catch(() => { });
|
|
253
253
|
if (!stopping) {
|
|
254
254
|
const retry = setTimeout(() => {
|
|
@@ -259,7 +259,7 @@ async function runDaemon() {
|
|
|
259
259
|
}
|
|
260
260
|
}
|
|
261
261
|
if (!stopping)
|
|
262
|
-
owner.update(platformStatus);
|
|
262
|
+
owner.update(platformStatus, Object.values(platformStatus).includes("connected") ? "ready" : "starting");
|
|
263
263
|
};
|
|
264
264
|
for (const [platform, adapter] of adapters)
|
|
265
265
|
void connect(platform, adapter);
|
|
@@ -267,19 +267,19 @@ async function runDaemon() {
|
|
|
267
267
|
// Starts even with zero stored jobs — jobs can be created later from chats.
|
|
268
268
|
cron = startGatewayCron({ adapters, cfg });
|
|
269
269
|
console.log(`lunR gateway: cron scheduler started (${cron.intervalMs / 1000}s interval)`);
|
|
270
|
-
owner.update(platformStatus);
|
|
270
|
+
owner.update(platformStatus, "starting");
|
|
271
271
|
await stopped;
|
|
272
272
|
return 0;
|
|
273
273
|
}
|
|
274
274
|
export async function runGateway(args) {
|
|
275
275
|
const [sub, ...rest] = args;
|
|
276
276
|
if (sub === "pair") {
|
|
277
|
-
const [action, platform, code] = rest;
|
|
278
|
-
if (action === "approve" && platform)
|
|
279
|
-
return runPairApprove(platform, code);
|
|
277
|
+
const [action, platform, code, flag] = rest;
|
|
278
|
+
if (action === "approve" && platform && (flag === undefined || flag === "--owner"))
|
|
279
|
+
return runPairApprove(platform, code, flag === "--owner");
|
|
280
280
|
if (action === "list")
|
|
281
281
|
return runPairList();
|
|
282
|
-
console.error("Usage: lunr gateway pair approve <platform> <code> | lunr gateway pair list");
|
|
282
|
+
console.error("Usage: lunr gateway pair approve <platform> <code> [--owner] | lunr gateway pair list");
|
|
283
283
|
return 1;
|
|
284
284
|
}
|
|
285
285
|
if (sub === "status")
|