@xopcai/xopc 0.0.464 → 0.0.465

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.
Files changed (119) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/feishu/src/adapters/cli-login.js +23 -49
  3. package/dist/extensions/feishu/src/adapters/gateway-setup.d.ts +3 -0
  4. package/dist/extensions/feishu/src/adapters/gateway-setup.js +180 -128
  5. package/dist/extensions/feishu/src/adapters/onboard-cli.d.ts +1 -1
  6. package/dist/extensions/feishu/src/adapters/onboard-cli.js +27 -15
  7. package/dist/extensions/feishu/src/auth/app-registration.d.ts +1 -0
  8. package/dist/extensions/feishu/src/auth/app-registration.js +12 -9
  9. package/dist/extensions/feishu/src/outbound/outbound-adapter.js +40 -16
  10. package/dist/extensions/feishu/src/plugin.d.ts +2 -0
  11. package/dist/extensions/feishu/src/plugin.js +37 -23
  12. package/dist/extensions/feishu/src/status/status-adapter.d.ts +1 -1
  13. package/dist/extensions/feishu/src/status/status-adapter.js +8 -5
  14. package/dist/extensions/feishu/src/streaming/streaming-adapter.js +97 -69
  15. package/dist/extensions/feishu/src/transport/client/bot-info.d.ts +10 -0
  16. package/dist/extensions/feishu/src/transport/client/bot-info.js +34 -0
  17. package/dist/extensions/feishu/src/transport/client/client.d.ts +7 -1
  18. package/dist/extensions/feishu/src/transport/client/client.js +6 -5
  19. package/dist/extensions/feishu/src/transport/client/install-sdk.d.ts +2 -0
  20. package/dist/extensions/feishu/src/transport/client/install-sdk.js +77 -0
  21. package/dist/extensions/feishu/src/transport/client/lark-sdk.d.ts +2 -0
  22. package/dist/extensions/feishu/src/transport/client/lark-sdk.js +27 -3
  23. package/dist/extensions/feishu/src/transport/client/sdk-catalog.d.ts +1 -0
  24. package/dist/extensions/feishu/src/transport/client/sdk-catalog.js +317 -0
  25. package/dist/extensions/feishu/src/transport/reliability/inbound-pipeline.d.ts +1 -1
  26. package/dist/extensions/feishu/src/transport/reliability/inbound-pipeline.js +13 -5
  27. package/dist/extensions/feishu/src/transport/reliability/message-ingress.d.ts +21 -0
  28. package/dist/extensions/feishu/src/transport/reliability/message-ingress.js +313 -0
  29. package/dist/extensions/feishu/src/transport/socket-mode/monitor.d.ts +1 -0
  30. package/dist/extensions/feishu/src/transport/socket-mode/monitor.js +56 -171
  31. package/dist/extensions/feishu/src/transport/webhook/monitor.d.ts +1 -0
  32. package/dist/extensions/feishu/src/transport/webhook/monitor.js +10 -102
  33. package/dist/extensions/telegram/src/account-manager.d.ts +1 -0
  34. package/dist/extensions/telegram/src/account-manager.js +3 -0
  35. package/dist/extensions/telegram/src/adapters/debounce-keys.js +7 -2
  36. package/dist/extensions/telegram/src/adapters/gateway-setup.js +113 -63
  37. package/dist/extensions/telegram/src/adapters/streaming-adapter.js +8 -4
  38. package/dist/extensions/telegram/src/doctor.js +1 -1
  39. package/dist/extensions/telegram/src/inbound-coalescer.d.ts +8 -6
  40. package/dist/extensions/telegram/src/inbound-coalescer.js +47 -88
  41. package/dist/extensions/telegram/src/inbound-processor.js +5 -1
  42. package/dist/extensions/telegram/src/outbound-sender.js +16 -23
  43. package/dist/extensions/telegram/src/plugin.js +80 -57
  44. package/dist/extensions/telegram/src/polling-session.d.ts +3 -6
  45. package/dist/extensions/telegram/src/polling-session.js +107 -94
  46. package/dist/extensions/telegram/src/rich-message.d.ts +4 -0
  47. package/dist/extensions/telegram/src/rich-message.js +23 -0
  48. package/dist/extensions/telegram/src/timeout-abort.d.ts +1 -1
  49. package/dist/extensions/telegram/src/timeout-abort.js +9 -3
  50. package/dist/extensions/telegram/src/update-offset-store.d.ts +1 -0
  51. package/dist/extensions/telegram/src/update-offset-store.js +6 -1
  52. package/dist/extensions/telegram/xopc.extension.json +1 -1
  53. package/dist/extensions/weixin/src/api/api.d.ts +1 -0
  54. package/dist/extensions/weixin/src/api/api.js +12 -6
  55. package/dist/extensions/weixin/src/api/types.d.ts +5 -2
  56. package/dist/extensions/weixin/src/auth/login-qr.d.ts +7 -1
  57. package/dist/extensions/weixin/src/auth/login-qr.js +48 -13
  58. package/dist/extensions/weixin/src/cdn/pic-decrypt.d.ts +2 -2
  59. package/dist/extensions/weixin/src/cdn/pic-decrypt.js +37 -25
  60. package/dist/extensions/weixin/src/cli/gateway-qr-login.d.ts +8 -0
  61. package/dist/extensions/weixin/src/cli/gateway-qr-login.js +45 -6
  62. package/dist/extensions/weixin/src/cli/qr-login.d.ts +1 -1
  63. package/dist/extensions/weixin/src/cli/qr-login.js +9 -3
  64. package/dist/extensions/weixin/src/media/media-download.d.ts +1 -0
  65. package/dist/extensions/weixin/src/media/media-download.js +4 -5
  66. package/dist/extensions/weixin/src/messaging/process-message.d.ts +2 -0
  67. package/dist/extensions/weixin/src/messaging/process-message.js +90 -65
  68. package/dist/extensions/weixin/src/messaging/quote-cache.d.ts +10 -0
  69. package/dist/extensions/weixin/src/messaging/quote-cache.js +46 -0
  70. package/dist/extensions/weixin/src/monitor/monitor.d.ts +3 -3
  71. package/dist/extensions/weixin/src/monitor/monitor.js +108 -104
  72. package/dist/extensions/weixin/src/plugin.d.ts +5 -1
  73. package/dist/extensions/weixin/src/plugin.js +138 -42
  74. package/dist/gateway/static/root/assets/{capabilities-page-rTjkjo71.js → capabilities-page-U_hQx5ou.js} +2 -2
  75. package/dist/gateway/static/root/assets/channels-BUzno8Pi.js +1 -0
  76. package/dist/gateway/static/root/assets/extension-settings-page-BvUtZGLT.js +1 -0
  77. package/dist/gateway/static/root/assets/index-Cdo4_zon.js +11 -0
  78. package/dist/gateway/static/root/assets/index-DYTktubl.css +1 -0
  79. package/dist/gateway/static/root/assets/{route-preload-5iwjWERk.js → route-preload-ClsAFFQc.js} +2 -2
  80. package/dist/gateway/static/root/assets/schema-form-BxBDgLrg.js +1 -0
  81. package/dist/gateway/static/root/assets/{settings-page-DNiRlM5x.js → settings-page-M6XwzIyu.js} +1 -1
  82. package/dist/gateway/static/root/assets/understanding-refresh-store-CM6bUcaJ.js +1 -0
  83. package/dist/gateway/static/root/assets/user-model-page-CBcGMhrR.js +2 -0
  84. package/dist/gateway/static/root/index.html +4 -4
  85. package/dist/package.js +1 -1
  86. package/dist/src/agent/inbound/inbound-loop.js +14 -0
  87. package/dist/src/agent/messaging/outbound-coordinator.js +1 -1
  88. package/dist/src/channels/connection-probe.d.ts +23 -0
  89. package/dist/src/channels/connection-probe.js +98 -0
  90. package/dist/src/channels/manager.d.ts +2 -0
  91. package/dist/src/channels/manager.js +5 -0
  92. package/dist/src/channels/message-journal.d.ts +25 -0
  93. package/dist/src/channels/message-journal.js +79 -0
  94. package/dist/src/channels/outbound-sender.d.ts +8 -0
  95. package/dist/src/channels/outbound-sender.js +60 -1
  96. package/dist/src/channels/plugins/types.adapters.d.ts +4 -0
  97. package/dist/src/channels/verified-inbound.js +20 -14
  98. package/dist/src/gateway/hono/routes/channels.js +23 -10
  99. package/dist/src/gateway/hono/routes/home.js +1 -1
  100. package/dist/src/gateway/hono/routes/user-model.js +48 -20
  101. package/dist/src/gateway/service.js +5 -5
  102. package/dist/src/home-intelligence/host.js +5 -5
  103. package/dist/src/infra/bus/index.d.ts +1 -1
  104. package/dist/src/infra/bus/queue.d.ts +16 -3
  105. package/dist/src/infra/bus/queue.js +74 -3
  106. package/dist/src/infra/debounce.d.ts +1 -0
  107. package/dist/src/infra/debounce.js +40 -35
  108. package/dist/src/knowledge-memory/index.js +2 -2
  109. package/dist/src/knowledge-memory/repository.d.ts +9 -0
  110. package/dist/src/knowledge-memory/repository.js +12 -2
  111. package/dist/src/runtime-tools/types.d.ts +1 -1
  112. package/package.json +5 -6
  113. package/dist/gateway/static/root/assets/channels-DvB2fwPI.js +0 -1
  114. package/dist/gateway/static/root/assets/extension-settings-page-DKAJE4h9.js +0 -1
  115. package/dist/gateway/static/root/assets/index-BGA-G-Bp.css +0 -1
  116. package/dist/gateway/static/root/assets/index-pmlYYCCU.js +0 -11
  117. package/dist/gateway/static/root/assets/schema-form-C9TYGa0_.js +0 -1
  118. package/dist/gateway/static/root/assets/understanding-refresh-store-Cf0DUO_C.js +0 -1
  119. package/dist/gateway/static/root/assets/user-model-page-CdB9qH57.js +0 -2
@@ -0,0 +1,98 @@
1
+ import { randomUUID } from "node:crypto";
2
+ //#region src/channels/connection-probe.ts
3
+ const LIFETIME_MS = 5 * 6e4;
4
+ const probes = /* @__PURE__ */ new Map();
5
+ const probeKey = (channel, accountId) => JSON.stringify([channel, accountId]);
6
+ function startChannelConnectionProbe(params) {
7
+ const { channel, accountId, ownerId, identity, botUsername, zh } = params;
8
+ const id = randomUUID();
9
+ const code = `xopc_${randomUUID().replaceAll("-", "")}`;
10
+ const key = probeKey(channel, accountId);
11
+ const probe = {
12
+ id,
13
+ code,
14
+ expiresAt: Date.now() + LIFETIME_MS,
15
+ ownerId,
16
+ identity,
17
+ confirmOwner: params.confirmOwner ?? false,
18
+ sending: false,
19
+ verified: false
20
+ };
21
+ probes.set(key, probe);
22
+ setTimeout(() => {
23
+ if (probes.get(key) === probe) probes.delete(key);
24
+ }, LIFETIME_MS).unref();
25
+ const link = botUsername ? `https://t.me/${encodeURIComponent(botUsername)}?start=${code}` : void 0;
26
+ return {
27
+ type: "qr",
28
+ conversationId: id,
29
+ accountId,
30
+ ...link ? { qrPayload: link } : { verificationCode: code },
31
+ statusAction: "setup.verify.status",
32
+ cancelAction: "setup.verify.cancel",
33
+ pollIntervalMs: 1500,
34
+ expiresInSec: LIFETIME_MS / 1e3,
35
+ configChanged: params.configChanged,
36
+ message: link ? zh ? "凭据已验证。在 Telegram 打开机器人并点击开始。" : "Credentials verified. Open the bot in Telegram and tap Start." : zh ? "已授权。请在机器人私聊中发送下方验证码。" : "Authorized. Send the code below in a private chat with the bot."
37
+ };
38
+ }
39
+ function getChannelConnectionProbe(channel, accountId, id, zh) {
40
+ const probe = findProbe(channel, accountId, id);
41
+ if (!probe) return {
42
+ type: "poll",
43
+ phase: "unknown",
44
+ ok: false,
45
+ message: zh ? "验证已结束,请重新连接。" : "Verification ended. Connect again to retry."
46
+ };
47
+ if (probe.verified) return {
48
+ type: "poll",
49
+ phase: "done",
50
+ ok: true,
51
+ message: zh ? "已连接,双向收发已验证。" : "Connected. Message delivery verified in both directions."
52
+ };
53
+ if (probe.claimant && probe.confirmOwner) return {
54
+ type: "poll",
55
+ phase: "done",
56
+ confirmAction: "setup.verify.confirm",
57
+ conversationId: id,
58
+ accountId,
59
+ message: zh ? `Telegram 已收到验证回复。请确认用户 ${probe.claimant}。` : `Telegram received the test reply. Confirm user ${probe.claimant}.`
60
+ };
61
+ return {
62
+ type: "poll",
63
+ phase: "pending",
64
+ message: zh ? "等待机器人收到验证消息并回复。" : "Waiting for the bot to receive the test message and reply."
65
+ };
66
+ }
67
+ function findProbe(channel, accountId, id) {
68
+ const probe = probes.get(probeKey(channel, accountId));
69
+ if (probe?.id === id && probe.expiresAt > Date.now()) return probe;
70
+ }
71
+ function cancelChannelConnectionProbe(channel, accountId, id) {
72
+ if (findProbe(channel, accountId, id)) probes.delete(probeKey(channel, accountId));
73
+ }
74
+ function getChannelConnectionClaimant(channel, accountId, id, identity) {
75
+ const probe = findProbe(channel, accountId, id);
76
+ if (probe?.confirmOwner && probe.identity === identity) return probe.claimant;
77
+ }
78
+ function confirmChannelConnectionProbe(channel, accountId, id) {
79
+ const probe = findProbe(channel, accountId, id);
80
+ if (probe?.claimant) probe.verified = true;
81
+ }
82
+ async function handleChannelConnectionProbe(params) {
83
+ const probe = probes.get(probeKey(params.channel, params.accountId));
84
+ const code = params.text.trim().replace(/^\/start(?:@[\w_]+)?\s+/, "");
85
+ if (!/^xopc_[a-f0-9]{32}$/.test(code)) return false;
86
+ if (!probe || probe.code !== code || probe.expiresAt <= Date.now() || probe.identity && params.identity !== probe.identity || probe.ownerId && params.senderId !== probe.ownerId || probe.sending || probe.claimant || probe.verified) return true;
87
+ probe.sending = true;
88
+ try {
89
+ await params.reply("xopc ✓");
90
+ probe.claimant = params.senderId;
91
+ probe.verified = !probe.confirmOwner;
92
+ } finally {
93
+ probe.sending = false;
94
+ }
95
+ return true;
96
+ }
97
+ //#endregion
98
+ export { cancelChannelConnectionProbe, confirmChannelConnectionProbe, getChannelConnectionClaimant, getChannelConnectionProbe, handleChannelConnectionProbe, startChannelConnectionProbe };
@@ -21,6 +21,7 @@ import { ChannelHealthMonitor, type ChannelHealthState } from './health-monitor.
21
21
  import { type OutboundChannelHooks } from './outbound-sender.js';
22
22
  export type { OutboundChannelHooks } from './outbound-sender.js';
23
23
  export declare class ChannelManager {
24
+ private readonly bus;
24
25
  private config;
25
26
  private readonly registry;
26
27
  private readonly healthMonitor;
@@ -52,6 +53,7 @@ export declare class ChannelManager {
52
53
  skipPersist?: boolean;
53
54
  requireDelivery?: boolean;
54
55
  }): Promise<void>;
56
+ sendQueuedOutboundMessage(message: OutboundMessage): Promise<void>;
55
57
  replayPendingOutboundMessages(): Promise<void>;
56
58
  startStream(channel: string, chatId: string, accountId?: string, opts?: {
57
59
  threadId?: string;
@@ -17,6 +17,7 @@ var ChannelManager = class {
17
17
  outbound;
18
18
  sessionModelHooks;
19
19
  constructor(config, bus) {
20
+ this.bus = bus;
20
21
  this.config = config;
21
22
  this.heartbeat = new ChannelHeartbeatScheduler({
22
23
  getConfig: () => this.config,
@@ -47,6 +48,7 @@ var ChannelManager = class {
47
48
  }
48
49
  enableOutboundPersistence(agentId) {
49
50
  this.outbound.enablePersistence(agentId);
51
+ this.bus.setOutboundReplyPersistence?.((message, delivery) => this.outbound.persistReply(message, delivery));
50
52
  }
51
53
  registerPlugin(plugin) {
52
54
  this.registry.register(plugin);
@@ -89,6 +91,9 @@ var ChannelManager = class {
89
91
  send(msg, options) {
90
92
  return this.outbound.send(msg, options);
91
93
  }
94
+ sendQueuedOutboundMessage(message) {
95
+ return this.outbound.sendQueued(message);
96
+ }
92
97
  replayPendingOutboundMessages() {
93
98
  return this.outbound.replayPending();
94
99
  }
@@ -0,0 +1,25 @@
1
+ type JournalEntry<T> = {
2
+ id: string;
3
+ payload: T;
4
+ };
5
+ /** Persists channel messages, their dispatch receipts, and optional platform cursors. */
6
+ export declare class ChannelMessageJournal<T, Cursor> {
7
+ private readonly scope;
8
+ private readonly cursors;
9
+ private readonly queue;
10
+ private lastPrunedAt;
11
+ constructor(channel: string, scope: string);
12
+ cursor(): Cursor | undefined;
13
+ accept(entries: JournalEntry<T>[], cursor?: Cursor): string[];
14
+ pending(limit?: number): Array<JournalEntry<T> & {
15
+ enqueuedAt: number;
16
+ }>;
17
+ begin(id: string, replayable?: boolean): boolean;
18
+ finish(id: string, outcome: 'completed' | 'interrupted'): void;
19
+ finishBatch(entries: ReadonlyArray<{
20
+ id: string;
21
+ outcome: 'completed' | 'interrupted';
22
+ }>): void;
23
+ recoverInterrupted(): number;
24
+ }
25
+ export {};
@@ -0,0 +1,79 @@
1
+ import { init_connection, requireXopcDatabase } from "../storage/sqlite/connection.js";
2
+ import { init_transaction, runSqliteWriteTransaction } from "../storage/sqlite/transaction.js";
3
+ import { DurableState } from "../storage/sqlite/durable-state.js";
4
+ //#region src/channels/message-journal.ts
5
+ init_connection();
6
+ init_transaction();
7
+ const MAX_PENDING = 500;
8
+ const MAX_PENDING_BYTES = 16 * 1024 * 1024;
9
+ const RECEIPT_RETENTION_MS = 10080 * 6e4;
10
+ /** Persists channel messages, their dispatch receipts, and optional platform cursors. */
11
+ var ChannelMessageJournal = class {
12
+ cursors;
13
+ queue;
14
+ lastPrunedAt = 0;
15
+ constructor(channel, scope) {
16
+ this.scope = scope;
17
+ this.queue = `channel-journal:${channel}`;
18
+ this.cursors = new DurableState(this.queue);
19
+ }
20
+ cursor() {
21
+ return this.cursors.get(this.scope);
22
+ }
23
+ accept(entries, cursor) {
24
+ requireXopcDatabase();
25
+ return runSqliteWriteTransaction((db) => {
26
+ const insert = db.prepare(`INSERT INTO durable_messages(queue, scope, id, payload, enqueued_at)
27
+ VALUES (?, ?, ?, ?, ?) ON CONFLICT(queue, scope, id) DO NOTHING`);
28
+ const now = Date.now();
29
+ if (now - this.lastPrunedAt > 60 * 6e4) {
30
+ db.prepare(`DELETE FROM durable_messages WHERE queue = ? AND scope = ? AND processed_at <= ?`).run(this.queue, this.scope, now - RECEIPT_RETENTION_MS);
31
+ this.lastPrunedAt = now;
32
+ }
33
+ const inserted = [];
34
+ for (const entry of entries) if (insert.run(this.queue, this.scope, entry.id, JSON.stringify(entry.payload), now).changes > 0) inserted.push(entry.id);
35
+ if (entries.length) {
36
+ const pending = db.prepare(`SELECT count(*) AS count, coalesce(sum(length(CAST(payload AS BLOB))), 0) AS bytes
37
+ FROM durable_messages WHERE queue = ? AND scope = ? AND processed_at IS NULL`).get(this.queue, this.scope);
38
+ if (pending.count > MAX_PENDING || pending.bytes > MAX_PENDING_BYTES) throw new Error("Channel inbox capacity exceeded");
39
+ }
40
+ if (cursor !== void 0) this.cursors.set(this.scope, cursor);
41
+ return inserted;
42
+ });
43
+ }
44
+ pending(limit = 100) {
45
+ return requireXopcDatabase().db.prepare(`SELECT id, payload, enqueued_at FROM durable_messages
46
+ WHERE queue = ? AND scope = ? AND processed_at IS NULL AND lease_token IS NULL
47
+ ORDER BY sequence LIMIT ?`).all(this.queue, this.scope, limit).map((row) => ({
48
+ id: row.id,
49
+ payload: JSON.parse(row.payload),
50
+ enqueuedAt: row.enqueued_at
51
+ }));
52
+ }
53
+ begin(id, replayable = false) {
54
+ return requireXopcDatabase().db.prepare(`UPDATE durable_messages SET lease_token = ?
55
+ WHERE queue = ? AND scope = ? AND id = ? AND processed_at IS NULL AND lease_token IS NULL`).run(replayable ? "preparing" : "dispatching", this.queue, this.scope, id).changes > 0;
56
+ }
57
+ finish(id, outcome) {
58
+ requireXopcDatabase().db.prepare(`UPDATE durable_messages
59
+ SET processed_at = ?, lease_token = ?, payload = '{}'
60
+ WHERE queue = ? AND scope = ? AND id = ? AND processed_at IS NULL AND lease_token IN ('dispatching', 'preparing')`).run(Date.now(), outcome, this.queue, this.scope, id);
61
+ }
62
+ finishBatch(entries) {
63
+ if (!entries.length) return;
64
+ runSqliteWriteTransaction(() => {
65
+ for (const { id, outcome } of entries) this.finish(id, outcome);
66
+ });
67
+ }
68
+ recoverInterrupted() {
69
+ const db = requireXopcDatabase().db;
70
+ db.prepare(`UPDATE durable_messages SET lease_token = NULL
71
+ WHERE queue = ? AND scope = ? AND processed_at IS NULL AND lease_token = 'preparing'`).run(this.queue, this.scope);
72
+ const count = db.prepare(`UPDATE durable_messages SET processed_at = ?, lease_token = 'interrupted', payload = '{}'
73
+ WHERE queue = ? AND scope = ? AND processed_at IS NULL AND lease_token = 'dispatching'`).run(Date.now(), this.queue, this.scope).changes;
74
+ db.prepare(`DELETE FROM durable_messages WHERE queue = ? AND scope = ? AND processed_at <= ?`).run(this.queue, this.scope, Date.now() - RECEIPT_RETENTION_MS);
75
+ return Number(count);
76
+ }
77
+ };
78
+ //#endregion
79
+ export { ChannelMessageJournal };
@@ -14,6 +14,7 @@
14
14
  * the highest-traffic path in the channel layer; centralising it makes its
15
15
  * error semantics easier to reason about.
16
16
  */
17
+ import type { InboundDelivery } from '../infra/bus/index.js';
17
18
  import type { Config } from '../config/schema.js';
18
19
  import type { OutboundMessage } from './transport-types.js';
19
20
  import type { ChannelPluginRegistry } from './plugin-registry.js';
@@ -35,9 +36,16 @@ export declare class ChannelOutboundSender {
35
36
  private readonly opts;
36
37
  private hooks?;
37
38
  private persistStore?;
39
+ private replyJournal?;
40
+ private replyRecoveryDone;
41
+ private readonly replyReceipts;
38
42
  constructor(opts: ChannelOutboundSenderOptions);
39
43
  setHooks(hooks: OutboundChannelHooks): void;
40
44
  enablePersistence(agentId: string): void;
45
+ persistReply(message: OutboundMessage, delivery: InboundDelivery): boolean;
46
+ sendQueued(message: OutboundMessage): Promise<void>;
47
+ private dispatchReply;
48
+ private recoverInterruptedReplies;
41
49
  /**
42
50
  * Redeliver every queued outbound item (called after channels are started).
43
51
  * Best-effort — may duplicate if the prior send succeeded but ack did not
@@ -2,6 +2,7 @@ import { createLogger } from "../utils/logger/index.js";
2
2
  import { init_logger } from "../utils/logger.js";
3
3
  import { mergeTtsConfigFromAppConfig } from "../voice/tts/merge-config.js";
4
4
  import { maybeApplyTtsToPayload } from "../voice/tts/payload.js";
5
+ import { ChannelMessageJournal } from "./message-journal.js";
5
6
  import "./internal-outbound.js";
6
7
  import { deliverOutboundMessage } from "./outbound/deliver.js";
7
8
  import { OutboundPersistStore } from "./outbound/persist-store.js";
@@ -12,6 +13,9 @@ var ChannelOutboundSender = class {
12
13
  opts;
13
14
  hooks;
14
15
  persistStore;
16
+ replyJournal;
17
+ replyRecoveryDone = false;
18
+ replyReceipts = /* @__PURE__ */ new WeakMap();
15
19
  constructor(opts) {
16
20
  this.opts = opts;
17
21
  }
@@ -20,6 +24,56 @@ var ChannelOutboundSender = class {
20
24
  }
21
25
  enablePersistence(agentId) {
22
26
  this.persistStore = new OutboundPersistStore(agentId);
27
+ this.replyJournal = new ChannelMessageJournal("agent-reply", agentId);
28
+ this.replyRecoveryDone = false;
29
+ }
30
+ persistReply(message, delivery) {
31
+ if (!this.replyJournal) return true;
32
+ this.recoverInterruptedReplies();
33
+ const id = JSON.stringify([
34
+ message.channel,
35
+ delivery.scope,
36
+ delivery.id
37
+ ]);
38
+ const accepted = this.replyJournal.accept([{
39
+ id,
40
+ payload: message
41
+ }]).length > 0;
42
+ if (accepted) this.replyReceipts.set(message, id);
43
+ return accepted;
44
+ }
45
+ async sendQueued(message) {
46
+ const id = this.replyReceipts.get(message);
47
+ if (!id || !this.replyJournal) {
48
+ await this.send(message);
49
+ return;
50
+ }
51
+ this.replyReceipts.delete(message);
52
+ await this.dispatchReply(id, message);
53
+ }
54
+ async dispatchReply(id, message) {
55
+ const journal = this.replyJournal;
56
+ if (!journal?.begin(id)) return;
57
+ try {
58
+ await this.send(message, {
59
+ skipPersist: true,
60
+ requireDelivery: true
61
+ });
62
+ } catch {
63
+ journal.finish(id, "interrupted");
64
+ log.warn({
65
+ channel: message.channel,
66
+ deliveryId: id
67
+ }, "Channel reply delivery could not be confirmed");
68
+ return;
69
+ }
70
+ journal.finish(id, "completed");
71
+ }
72
+ recoverInterruptedReplies() {
73
+ if (!this.replyJournal || this.replyRecoveryDone) return;
74
+ const interrupted = this.replyJournal.recoverInterrupted();
75
+ this.replyRecoveryDone = true;
76
+ if (interrupted) log.warn({ interrupted }, "Channel replies interrupted during delivery");
23
77
  }
24
78
  /**
25
79
  * Redeliver every queued outbound item (called after channels are started).
@@ -27,6 +81,11 @@ var ChannelOutboundSender = class {
27
81
  * land on disk.
28
82
  */
29
83
  async replayPending() {
84
+ const journal = this.replyJournal;
85
+ if (journal) {
86
+ this.recoverInterruptedReplies();
87
+ for (const { id, payload } of journal.pending(500)) await this.dispatchReply(id, payload);
88
+ }
30
89
  if (!this.persistStore) return;
31
90
  const pending = [...this.persistStore.peek()];
32
91
  for (const p of pending) try {
@@ -103,7 +162,7 @@ var ChannelOutboundSender = class {
103
162
  chatId: processedMsg.chat_id,
104
163
  err
105
164
  }, "Outbound send threw");
106
- if (!queueId) throw err;
165
+ if (!queueId || options?.requireDelivery) throw err;
107
166
  }
108
167
  }
109
168
  async applyTtsIfNeeded(msg) {
@@ -178,6 +178,10 @@ export interface ChannelRuntimeActionResult {
178
178
  message?: string;
179
179
  /** Internal gateway-side config replacement; never returned to the browser. */
180
180
  nextConfig?: Config;
181
+ /** Called by the gateway only after the proposed config is saved. */
182
+ onConfigSaved?: () => ChannelRuntimeActionPayload | void | Promise<ChannelRuntimeActionPayload | void>;
183
+ /** Persist channel-owned credentials after the config compare-and-swap check. */
184
+ beforeConfigSaved?: () => void;
181
185
  }
182
186
  /** Gateway/CLI control-plane actions declared by extension manifests. */
183
187
  export interface ChannelRuntimeActionAdapter {
@@ -2,21 +2,27 @@
2
2
  const verified = /* @__PURE__ */ new WeakMap();
3
3
  /** Only channel lifecycle code gives a plugin access to this ingress. Ordinary bus publishers cannot mark a message. */
4
4
  function verifiedChannelBus(bus, channel) {
5
+ function verify(message, acceptedAt = Date.now()) {
6
+ const meta = message.metadata;
7
+ if (message.channel === channel && channel !== "system" && channel !== "webchat" && channel !== "cli" && typeof meta?.accountId === "string" && typeof meta.messageId === "string" && meta.messageId.length > 0 && typeof meta.isGroup === "boolean" && !meta.isCommand && !meta.isReaction && message.chat_id && message.sender_id) verified.set(message, {
8
+ subject: {
9
+ kind: "channel",
10
+ channel,
11
+ accountId: meta.accountId,
12
+ chatId: message.chat_id,
13
+ senderId: message.sender_id,
14
+ ...typeof meta.threadId === "string" && meta.threadId ? { threadId: meta.threadId } : {}
15
+ },
16
+ acceptedAt
17
+ });
18
+ }
5
19
  return new Proxy(bus, { get(target, property) {
6
- if (property === "publishInbound") return (message) => {
7
- const meta = message.metadata;
8
- if (message.channel === channel && channel !== "system" && channel !== "webchat" && channel !== "cli" && typeof meta?.accountId === "string" && typeof meta.messageId === "string" && meta.messageId.length > 0 && typeof meta.isGroup === "boolean" && !meta.isCommand && !meta.isReaction && message.chat_id && message.sender_id) verified.set(message, {
9
- subject: {
10
- kind: "channel",
11
- channel,
12
- accountId: meta.accountId,
13
- chatId: message.chat_id,
14
- senderId: message.sender_id,
15
- ...typeof meta.threadId === "string" && meta.threadId ? { threadId: meta.threadId } : {}
16
- },
17
- acceptedAt: Date.now()
18
- });
19
- return target.publishInbound(message);
20
+ if (property === "publishInbound") return (message, delivery) => {
21
+ verify(message);
22
+ return target.publishInbound(message, message.channel === channel ? delivery : void 0, verify);
23
+ };
24
+ if (property === "restoreDurableInbound") return (requestedChannel, scope) => {
25
+ if (requestedChannel === channel) target.restoreDurableInbound(channel, scope, verify);
20
26
  };
21
27
  const value = Reflect.get(target, property, target);
22
28
  return typeof value === "function" ? value.bind(target) : value;
@@ -99,8 +99,9 @@ function registerChannelRoutes(authenticated, deps) {
99
99
  });
100
100
  }
101
101
  if (plugin.runtimeActions) {
102
+ const currentConfig = service.currentConfig;
102
103
  const result = await plugin.runtimeActions.runAction({
103
- cfg: service.currentConfig,
104
+ cfg: currentConfig,
104
105
  locale: localeFromRequest(c),
105
106
  actionId: action,
106
107
  accountId,
@@ -113,19 +114,31 @@ function registerChannelRoutes(authenticated, deps) {
113
114
  message: result.message ?? "Channel action failed"
114
115
  }
115
116
  }, 400);
117
+ let payload = result.payload;
116
118
  if (result.nextConfig) {
117
- const saved = await service.saveConfig(result.nextConfig);
118
- if (!saved.saved) return c.json({
119
- ok: false,
120
- error: {
121
- code: "CHANNEL_ACTION_FAILED",
122
- message: saved.error ?? "Failed to save channel config"
123
- }
124
- }, 500);
119
+ const saved = await service.saveConfig(result.nextConfig, currentConfig, result.beforeConfigSaved);
120
+ if (!saved.saved) {
121
+ if (saved.conflict) return c.json({
122
+ ok: false,
123
+ error: {
124
+ code: "CHANNEL_CONFIG_CHANGED",
125
+ message: "Channel settings changed. Reload and retry."
126
+ }
127
+ }, 409);
128
+ return c.json({
129
+ ok: false,
130
+ error: {
131
+ code: "CHANNEL_ACTION_FAILED",
132
+ message: saved.error ?? "Failed to save channel config"
133
+ }
134
+ }, 500);
135
+ }
136
+ const afterSave = await result.onConfigSaved?.();
137
+ if (afterSave) payload = afterSave;
125
138
  } else if (actionPayloadChangedConfig(result.payload)) await service.reloadConfig();
126
139
  return c.json({
127
140
  ok: true,
128
- payload: result.payload ?? {}
141
+ payload: payload ?? {}
129
142
  });
130
143
  }
131
144
  return c.json({
@@ -8,8 +8,8 @@ import { acknowledgeHomeAttention } from "../../../storage/sqlite/home-attention
8
8
  import "../../../storage/sqlite/index.js";
9
9
  import { HomeQueryService, buildHomeWorkbench, decisionFromTask } from "../../../tasks/home-query-service.js";
10
10
  import { resumeApprovedConnectorAction } from "../../../connectors/approval-resume.js";
11
- import { ObservationConflictError } from "../../../home-intelligence/observation.js";
12
11
  import { HomeOpportunityActionError, HomeOpportunityNotFoundError } from "../../../home-intelligence/application-service.js";
12
+ import { ObservationConflictError } from "../../../home-intelligence/observation.js";
13
13
  //#region src/gateway/hono/routes/home.ts
14
14
  init_src();
15
15
  /** Register the unified work-home read model and its decision actions. */
@@ -1,7 +1,7 @@
1
1
  import { init_transaction, runSqliteWriteTransaction } from "../../../storage/sqlite/transaction.js";
2
2
  import { createCollaborationRule, getCollaborationRule, listCollaborationRules, setCollaborationRuleStatus } from "../../../storage/sqlite/collaboration-rule-repository.js";
3
3
  import { getActiveUnderstandingConsent } from "../../../user-context/sources/consent-repository.js";
4
- import { KnowledgeReviewConflictError, deleteKnowledgeItem, getKnowledgeItem, listKnowledgeItems, reviewKnowledgeItem, searchKnowledgeItems, setKnowledgeScope } from "../../../knowledge-memory/repository.js";
4
+ import { KnowledgeReviewConflictError, deleteKnowledgeItem, getKnowledgeItem, listKnowledgeItems, listManagedWorkMemory, reviewKnowledgeItem, searchKnowledgeItems, setKnowledgeScope } from "../../../knowledge-memory/repository.js";
5
5
  import "../../../knowledge-memory/index.js";
6
6
  import { listUserAssertionEdges, listUserModelObservations } from "../../../user-model/observation-repository.js";
7
7
  import { createPriorityWindow, createUserGoal, listPriorityWindows, listUserGoals, setUserGoalStatus, updatePriorityWindow, updateUserGoal } from "../../../user-model/goals.js";
@@ -201,14 +201,14 @@ function matchesMobileSearch(item, query) {
201
201
  ])
202
202
  ].join(" ")).includes(query);
203
203
  }
204
- function encodeMobileCursor(item) {
205
- return Buffer.from(JSON.stringify([item.recordedAt, item.id])).toString("base64url");
204
+ function encodeTimeCursor(timestamp, id) {
205
+ return Buffer.from(JSON.stringify([timestamp, id])).toString("base64url");
206
206
  }
207
- function decodeMobileCursor(value) {
207
+ function decodeTimeCursor(value) {
208
208
  if (!value) return void 0;
209
209
  try {
210
210
  const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
211
- return Array.isArray(parsed) && typeof parsed[0] === "number" && typeof parsed[1] === "string" ? [parsed[0], parsed[1]] : void 0;
211
+ return Array.isArray(parsed) && typeof parsed[0] === "number" && Number.isSafeInteger(parsed[0]) && typeof parsed[1] === "string" ? [parsed[0], parsed[1]] : void 0;
212
212
  } catch {
213
213
  return;
214
214
  }
@@ -225,7 +225,7 @@ function registerUserModelRoutes(authenticated, deps) {
225
225
  sensitiveWritePolicy: userContext.userModel.sensitiveWritePolicy
226
226
  };
227
227
  };
228
- const snapshot = () => {
228
+ const snapshot = (aboutOnly = false) => {
229
229
  const rawAssertions = listUserAssertions({
230
230
  statuses: [
231
231
  "active",
@@ -240,10 +240,6 @@ function registerUserModelRoutes(authenticated, deps) {
240
240
  const assertions = rawAssertions.map((item) => assertionView(item, assertionSources.get(item.id) ?? []));
241
241
  const goals = listUserGoals();
242
242
  const priorities = listPriorityWindows();
243
- const knowledge = listKnowledgeItems({
244
- recordClass: "memory",
245
- limit: 1e3
246
- });
247
243
  const profile = getUserProfileSnapshot();
248
244
  const sources = listUnderstandingSourceGrants().map((source) => ({
249
245
  id: source.id,
@@ -254,23 +250,31 @@ function registerUserModelRoutes(authenticated, deps) {
254
250
  ...source.lastCollectedAt ? { lastCollectedAt: source.lastCollectedAt } : {},
255
251
  consent: getActiveUnderstandingConsent(source.id)
256
252
  }));
257
- return {
253
+ const about = {
258
254
  assertions,
259
- assertionEdges: listUserAssertionEdges(assertions.map((item) => item.id)),
260
- observations: listUserModelObservations({ limit: 500 }),
261
255
  goals,
262
256
  priorities,
263
257
  rules: listCollaborationRules(),
264
258
  ruleSuggestions: listActionRuleSuggestions(),
259
+ profile,
260
+ sources,
261
+ suggestedCallName: profile.callName || machineCallName(),
262
+ settings: memorySettings()
263
+ };
264
+ if (aboutOnly) return about;
265
+ const knowledge = listKnowledgeItems({
266
+ recordClass: "memory",
267
+ limit: 1e3
268
+ });
269
+ return {
270
+ ...about,
271
+ assertionEdges: listUserAssertionEdges(assertions.map((item) => item.id)),
272
+ observations: listUserModelObservations({ limit: 500 }),
265
273
  knowledge: knowledge.map((item) => ({
266
274
  ...item,
267
275
  version: memoryVersion(item)
268
276
  })),
269
277
  maintenance: { lastRun: listMemoryMaintenanceRuns(1)[0] ?? null },
270
- profile,
271
- sources,
272
- suggestedCallName: profile.callName || machineCallName(),
273
- settings: memorySettings(),
274
278
  counts: {
275
279
  activeAssertions: assertions.filter((item) => item.status === "active").length,
276
280
  reviewAssertions: assertions.filter((item) => item.status === "needs_review" || item.status === "conflicted").length,
@@ -280,7 +284,7 @@ function registerUserModelRoutes(authenticated, deps) {
280
284
  }
281
285
  };
282
286
  };
283
- authenticated.get("/api/user-model", (c) => c.json(snapshot()));
287
+ authenticated.get("/api/user-model", (c) => c.json(snapshot(c.req.query("view") === "about")));
284
288
  authenticated.patch("/api/user-model/settings", write, async (c) => {
285
289
  const input = await body(c);
286
290
  const memoryEnabled = input?.memoryEnabled;
@@ -433,7 +437,7 @@ function registerUserModelRoutes(authenticated, deps) {
433
437
  const limit = Number.isFinite(requestedLimit) ? Math.max(1, Math.min(50, Math.trunc(requestedLimit))) : 20;
434
438
  const query = normalizeMobileSearch(c.req.query("q"), 100);
435
439
  const cursorValue = c.req.query("cursor");
436
- const cursor = decodeMobileCursor(cursorValue);
440
+ const cursor = decodeTimeCursor(cursorValue);
437
441
  if (cursorValue && !cursor) return c.json({ error: "Invalid cursor" }, 400);
438
442
  const assertions = listUserAssertions({
439
443
  statuses: [
@@ -450,7 +454,7 @@ function registerUserModelRoutes(authenticated, deps) {
450
454
  const items = filtered.slice(0, limit);
451
455
  const result = {
452
456
  items,
453
- ...filtered.length > limit && items.length ? { nextCursor: encodeMobileCursor(items[items.length - 1]) } : {}
457
+ ...filtered.length > limit && items.length ? { nextCursor: encodeTimeCursor(items[items.length - 1].recordedAt, items[items.length - 1].id) } : {}
454
458
  };
455
459
  return c.json(result);
456
460
  }
@@ -736,6 +740,30 @@ function registerUserModelRoutes(authenticated, deps) {
736
740
  });
737
741
  authenticated.get("/api/knowledge-memory", (c) => {
738
742
  const query = c.req.query("q")?.trim();
743
+ if (c.req.query("view") === "manage") {
744
+ const cursor = c.req.query("cursor");
745
+ const before = cursor ? decodeTimeCursor(cursor) : void 0;
746
+ if (cursor && !before) return c.json({ error: "Invalid memory cursor" }, 400);
747
+ const limit = 24;
748
+ const records = listManagedWorkMemory({
749
+ query: query ?? "",
750
+ kind: c.req.query("kind"),
751
+ before: before && {
752
+ updatedAt: before[0],
753
+ id: before[1]
754
+ },
755
+ limit: limit + 1
756
+ });
757
+ const items = records.slice(0, limit);
758
+ const last = items.at(-1);
759
+ return c.json({
760
+ items: items.map((item) => ({
761
+ ...item,
762
+ version: memoryVersion(item)
763
+ })),
764
+ ...last && records.length > limit ? { nextCursor: encodeTimeCursor(last.updatedAt, last.id) } : {}
765
+ });
766
+ }
739
767
  if (!query) return c.json({ items: listKnowledgeItems({
740
768
  recordClass: "memory",
741
769
  limit: 500
@@ -107,6 +107,10 @@ import { DiscussionSealer } from "../discussions/sealer.js";
107
107
  import "../discussions/index.js";
108
108
  import { EndpointToolRuntime } from "../endpoint-tools/runtime.js";
109
109
  import "../endpoint-tools/index.js";
110
+ import { HomeCapabilityPreflightService } from "../home-intelligence/capability-preflight.js";
111
+ import { HomeAdviceGenerator } from "../home-intelligence/generator.js";
112
+ import { HomeIntelligenceHost } from "../home-intelligence/host.js";
113
+ import { HomeSnapshotBuilder } from "../home-intelligence/snapshot.js";
110
114
  import { assertGatewayAuthConfigured, extractToken, resolveGatewayAuth, validateToken } from "./auth.js";
111
115
  import { prepareAutomationAgentSession } from "./automation-agent-session.js";
112
116
  import { deliverAutomationCompletion } from "./automation-completion-delivery.js";
@@ -170,10 +174,6 @@ import { TaskMainUpdateDecisionService } from "../tasks/task-main-update-decisio
170
174
  import { selectTaskMainUpdateAttempt, submitAndConfirmTaskMainUpdate } from "../tasks/task-main-update-input.js";
171
175
  import { checkAppContextAccess, prepareAppContext } from "./service/app-context-access.js";
172
176
  import { applyAutomaticVoiceLanguage, inferProductLanguageFromEnvironment, initializeVoiceDefaults } from "../voice/language-profile.js";
173
- import { HomeAdviceGenerator } from "../home-intelligence/generator.js";
174
- import { HomeIntelligenceHost } from "../home-intelligence/host.js";
175
- import { HomeSnapshotBuilder } from "../home-intelligence/snapshot.js";
176
- import { HomeCapabilityPreflightService } from "../home-intelligence/capability-preflight.js";
177
177
  import crypto from "node:crypto";
178
178
  //#region src/gateway/service.ts
179
179
  init_session_repository();
@@ -1803,7 +1803,7 @@ var GatewayService = class {
1803
1803
  log.debug("Starting outbound message processor");
1804
1804
  while (this.running) try {
1805
1805
  const msg = await this.bus.consumeOutbound();
1806
- await this.channelManager.send(msg);
1806
+ await this.channelManager.sendQueuedOutboundMessage(msg);
1807
1807
  } catch (error) {
1808
1808
  if (error instanceof MessageBusShutdownError) break;
1809
1809
  const em = error instanceof Error ? error.message : String(error);