@markus-global/cli 0.11.3 → 0.12.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/backend.d.ts.map +1 -1
  2. package/dist/backend.js +5 -1
  3. package/dist/backend.js.map +1 -1
  4. package/dist/commands/approval-card.d.ts +53 -0
  5. package/dist/commands/approval-card.d.ts.map +1 -0
  6. package/dist/commands/approval-card.js +43 -0
  7. package/dist/commands/approval-card.js.map +1 -0
  8. package/dist/commands/auth.d.ts.map +1 -1
  9. package/dist/commands/auth.js +11 -5
  10. package/dist/commands/auth.js.map +1 -1
  11. package/dist/commands/init.d.ts.map +1 -1
  12. package/dist/commands/init.js +7 -5
  13. package/dist/commands/init.js.map +1 -1
  14. package/dist/commands/model.d.ts.map +1 -1
  15. package/dist/commands/model.js +6 -4
  16. package/dist/commands/model.js.map +1 -1
  17. package/dist/commands/outbound.d.ts +76 -0
  18. package/dist/commands/outbound.d.ts.map +1 -0
  19. package/dist/commands/outbound.js +80 -0
  20. package/dist/commands/outbound.js.map +1 -0
  21. package/dist/commands/start.d.ts +124 -2
  22. package/dist/commands/start.d.ts.map +1 -1
  23. package/dist/commands/start.js +718 -82
  24. package/dist/commands/start.js.map +1 -1
  25. package/dist/index.js +5 -20
  26. package/dist/index.js.map +1 -1
  27. package/dist/markus.mjs +112615 -103125
  28. package/dist/web-ui/assets/AsyncState-BebkDWbq.js +1 -0
  29. package/dist/web-ui/assets/{CommentInput-DN3Cichs.js → CommentInput-BRZWIC3U.js} +1 -1
  30. package/dist/web-ui/assets/{ContentRenderer-CjHOyYgJ.js → ContentRenderer-PGP8H_Zz.js} +2 -2
  31. package/dist/web-ui/assets/DeliverableShareModal-CcigVYGz.js +1 -0
  32. package/dist/web-ui/assets/Deliverables-CQwXaCA4.js +3 -0
  33. package/dist/web-ui/assets/{Notifications-CCsdBfdg.js → Notifications-BvHJCIRG.js} +1 -1
  34. package/dist/web-ui/assets/Search-BA-aXh7i.js +1 -0
  35. package/dist/web-ui/assets/SendToChat-CAfyKhpq.js +1 -0
  36. package/dist/web-ui/assets/Settings-icFp6tNI.js +8 -0
  37. package/dist/web-ui/assets/{Store-BWi97VP9.js → Store-DKwOcmMu.js} +1 -1
  38. package/dist/web-ui/assets/Switch-C7lFnHA7.js +1 -0
  39. package/dist/web-ui/assets/Team-DyqXLZ-X.js +84 -0
  40. package/dist/web-ui/assets/Work-BXGrda4S.js +12 -0
  41. package/dist/web-ui/assets/{arc-Cg0-C295.js → arc-Dnk6N-Zc.js} +1 -1
  42. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BctEHNLp.js → architectureDiagram-3BPJPVTR-CV8JIXXD.js} +1 -1
  43. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-hxr2ZwOV.js → blockDiagram-GPEHLZMM-D9pKmrXH.js} +1 -1
  44. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-CfIRo1GE.js → c4Diagram-AAUBKEIU-Q26HvIpY.js} +1 -1
  45. package/dist/web-ui/assets/channel-BZs6ereM.js +1 -0
  46. package/dist/web-ui/assets/{chunk-2J33WTMH-T0bENsqX.js → chunk-2J33WTMH-BSjFVwnx.js} +1 -1
  47. package/dist/web-ui/assets/{chunk-4BX2VUAB-ChLLkyYx.js → chunk-4BX2VUAB-BZXv4MQp.js} +1 -1
  48. package/dist/web-ui/assets/{chunk-55IACEB6-BD3ENYp9.js → chunk-55IACEB6-CeKd3oeJ.js} +1 -1
  49. package/dist/web-ui/assets/{chunk-727SXJPM-BAes4atE.js → chunk-727SXJPM-DP1tSQo5.js} +1 -1
  50. package/dist/web-ui/assets/{chunk-AQP2D5EJ-FymM7gfT.js → chunk-AQP2D5EJ-DqEncn7j.js} +1 -1
  51. package/dist/web-ui/assets/{chunk-FMBD7UC4-N5sRT0m9.js → chunk-FMBD7UC4-tuDUJ9Xx.js} +1 -1
  52. package/dist/web-ui/assets/{chunk-ND2GUHAM-BSjS3JyS.js → chunk-ND2GUHAM-DoC8aLWB.js} +1 -1
  53. package/dist/web-ui/assets/{chunk-QZHKN3VN-Dkwitdbr.js → chunk-QZHKN3VN-74zpvcgs.js} +1 -1
  54. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-C9JIxJeJ.js +1 -0
  55. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-C9JIxJeJ.js +1 -0
  56. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-BLuYATCK.js → cose-bilkent-S5V4N54A-DjYUalC1.js} +1 -1
  57. package/dist/web-ui/assets/{dagre-BM42HDAG-DGLiqiH2.js → dagre-BM42HDAG-oSewacE8.js} +1 -1
  58. package/dist/web-ui/assets/{diagram-2AECGRRQ-Cq_GnNKs.js → diagram-2AECGRRQ-C1fiWe46.js} +1 -1
  59. package/dist/web-ui/assets/{diagram-5GNKFQAL-CHNz-2dA.js → diagram-5GNKFQAL-9G_q6hCa.js} +1 -1
  60. package/dist/web-ui/assets/{diagram-KO2AKTUF-D8eKa7jh.js → diagram-KO2AKTUF-CSm-lJp-.js} +1 -1
  61. package/dist/web-ui/assets/{diagram-LMA3HP47-RkDgQcLr.js → diagram-LMA3HP47-BTAORcHx.js} +1 -1
  62. package/dist/web-ui/assets/{diagram-OG6HWLK6-LqxQrIwa.js → diagram-OG6HWLK6-DbcCkDfo.js} +1 -1
  63. package/dist/web-ui/assets/{docx-preview-Be-Qo_ag.js → docx-preview-DjqdA44x.js} +1 -1
  64. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-BX0zZgYQ.js → erDiagram-TEJ5UH35-DFa-B8-u.js} +1 -1
  65. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-DKnfIFA4.js → flowDiagram-I6XJVG4X-WCTnaK9M.js} +1 -1
  66. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-DjBURmY-.js → ganttDiagram-6RSMTGT7-DbW1CoJJ.js} +1 -1
  67. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-BvSi7SvS.js → gitGraphDiagram-PVQCEYII-1faDfO29.js} +1 -1
  68. package/dist/web-ui/assets/index-B8h1PPzP.js +883 -0
  69. package/dist/web-ui/assets/index-DD3NMntN.css +1 -0
  70. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-CwtIgim2.js → infoDiagram-5YYISTIA-DfXKP4tQ.js} +1 -1
  71. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-CWhXJfSa.js → ishikawaDiagram-YF4QCWOH-D6FOsFQ5.js} +1 -1
  72. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-DN9rorlL.js → journeyDiagram-JHISSGLW-DXpxntIF.js} +1 -1
  73. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-Burf5FE8.js → kanban-definition-UN3LZRKU-Dt7FBCF3.js} +1 -1
  74. package/dist/web-ui/assets/{mermaid.core-Dx4rzlyC.js → mermaid.core-sTcSUoRD.js} +5 -5
  75. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-DqZ21Siw.js → mindmap-definition-RKZ34NQL-CvOU23ga.js} +1 -1
  76. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-C_4ksu-T.js → pieDiagram-4H26LBE5-DUedtXVj.js} +1 -1
  77. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-Dl6Rjg1X.js → quadrantDiagram-W4KKPZXB-CqpHHRca.js} +1 -1
  78. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-CzmWi02d.js → requirementDiagram-4Y6WPE33-CKZYvVDJ.js} +1 -1
  79. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-D8K7e8we.js → sankeyDiagram-5OEKKPKP-gZ0nzDfs.js} +1 -1
  80. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-1z9rqtVx.js → sequenceDiagram-3UESZ5HK-DN3XdBkW.js} +1 -1
  81. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-nneYkkHa.js → stateDiagram-AJRCARHV-BvtafGxO.js} +1 -1
  82. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-B2nWDV5R.js +1 -0
  83. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-D6GmLlRi.js → timeline-definition-PNZ67QCA-BrR919lp.js} +1 -1
  84. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-TVefhiCa.js → vennDiagram-CIIHVFJN-B7CTm4yM.js} +1 -1
  85. package/dist/web-ui/assets/{wardley-L42UT6IY-BgUuAeiM.js → wardley-L42UT6IY-CyqFngx_.js} +1 -1
  86. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-CyJ_l94o.js → wardleyDiagram-YWT4CUSO-BCqEPBJ5.js} +1 -1
  87. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-kajbbx7a.js → xychartDiagram-2RQKCTM6-BmT6Cmz-.js} +1 -1
  88. package/dist/web-ui/index.html +2 -2
  89. package/docs/README.md +1 -0
  90. package/docs/architecture/architecture.md +1 -1
  91. package/docs/architecture/configuration-model.md +156 -0
  92. package/docs/architecture/messaging-gateway.md +1043 -0
  93. package/docs/architecture/notification-delivery.md +273 -0
  94. package/docs/design/remote-access-contract.md +445 -0
  95. package/docs/guides/development.md +1 -1
  96. package/docs/guides/guide.md +4 -2
  97. package/docs/guides/remote-access.md +147 -214
  98. package/docs/handoff/approval-tri-state-handoff.md +69 -0
  99. package/docs/handoff/remote-access-handoff.md +160 -0
  100. package/docs/records/agent-platform-friction-2026-10.md +102 -2
  101. package/package.json +1 -1
  102. package/dist/web-ui/assets/DeliverableShareModal-CBSvxB-X.js +0 -1
  103. package/dist/web-ui/assets/Deliverables-BaAF4-w0.js +0 -3
  104. package/dist/web-ui/assets/Search-BiBdevAU.js +0 -1
  105. package/dist/web-ui/assets/Settings-CawBnWuy.js +0 -8
  106. package/dist/web-ui/assets/Team-CfUDkdc3.js +0 -84
  107. package/dist/web-ui/assets/Work-DrIXOW-P.js +0 -12
  108. package/dist/web-ui/assets/channel-DAQ2Rbxq.js +0 -1
  109. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BZyCVtJb.js +0 -1
  110. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BZyCVtJb.js +0 -1
  111. package/dist/web-ui/assets/index-D8vskks7.js +0 -882
  112. package/dist/web-ui/assets/index-DEN_qReg.css +0 -1
  113. package/dist/web-ui/assets/modelCapabilities-DDtCBZ6o.js +0 -1
  114. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-C-hpzcms.js +0 -1
@@ -3,14 +3,240 @@ import { existsSync, readFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { createRequire } from 'node:module';
5
5
  import { allTemplateDirs, resolveTemplatesDir, resolveWebUiDir } from '../paths.js';
6
- import { loadConfig, saveConfig, getDefaultConfigPath, createLogger, closeRuntimeLogger, checkForUpdate, installCrashGuard, markRunStarted, markCleanShutdown, memoryWatermarkWatchdog, detectUncleanShutdown, APP_VERSION, userId, PROVIDERS, } from '@markus/shared';
7
- import { AgentManager, LLMRouter, LLMLogger, ModelCatalogService, RoleLoader, createDefaultSkillRegistry, ExternalAgentGateway, } from '@markus/core';
8
- import { OrganizationService, TaskService, APIServer, HITLService, BillingService, LicenseService, TelemetryService, AuditService, ProjectService, RequirementService, KnowledgeService, FileKnowledgeStore, DeliverableService, KnowledgeSyncService, ReportService, TrustService, ArchiveService, StaleDetector, ScheduledTaskRunner, initStorage, searchRegistries, installSkill, importSkillFromDirectory, WorkflowService, WorkflowRunner, WorkflowScheduler, } from '@markus/org-manager';
9
- import { MessageRouter, FeishuAdapter, WebUIAdapter } from '@markus/comms';
6
+ import { loadConfig, saveConfig, getDefaultConfigPath, createLogger, closeRuntimeLogger, checkForUpdate, installCrashGuard, markRunStarted, markCleanShutdown, memoryWatermarkWatchdog, detectUncleanShutdown, APP_VERSION, userId, PROVIDERS, resolveJwtSecret, resolveGatewaySecret, pickOrgSecretary, setEnvValue, resolveActionSecret, resolveHostLocale, } from '@markus/shared';
7
+ import { AgentManager, LLMRouter, LLMLogger, ModelCatalogService, RoleLoader, createDefaultSkillRegistry, ExternalAgentGateway, proxyFetch, } from '@markus/core';
8
+ import { OrganizationService, TaskService, APIServer, HITLService, ApprovalApplier, routeRecordedDecision, BillingService, LicenseService, TelemetryService, AuditService, ProjectService, RequirementService, KnowledgeService, FileKnowledgeStore, DeliverableService, KnowledgeSyncService, ReportService, TrustService, ArchiveService, StaleDetector, ScheduledTaskRunner, initStorage, searchRegistries, installSkill, importSkillFromDirectory, WorkflowService, WorkflowRunner, WorkflowScheduler, loadPlatformBindings, readStoredPlatformConfig, recordInstanceVerification, } from '@markus/org-manager';
9
+ import { MessageRouter, PLATFORM_MANIFESTS, setHttpFetch, getManifest, RepoBindingLookup, MAIN_CONVERSATION_KEY, resolveCardActionValue, ConnectionTestRegistry } from '@markus/comms';
10
+ import { setupOutboundDispatch } from './outbound.js';
11
+ import { buildApprovalCardResolution, scheduleCardRewrite } from './approval-card.js';
10
12
  import { initStartupLogger, startupLog, startupBlank, startupSection, closeStartupLogger, getStartupLogFile } from '../utils/logger.js';
11
13
  import { openBrowserAfterHealthCheck } from '../utils/browser.js';
12
14
  import { StartupProgress } from '../utils/startupProgress.js';
13
15
  const log = createLogger('cli');
16
+ /** Env var for a platform field: (feishu, appId) → FEISHU_APP_ID. */
17
+ function manifestEnvKey(platformId, fieldKey) {
18
+ const snake = fieldKey.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase();
19
+ return `${platformId.toUpperCase()}_${snake}`;
20
+ }
21
+ /** Coerce a raw config value to the field's declared type; empty ⇒ undefined. */
22
+ function coerceFieldValue(field, raw) {
23
+ if (raw === undefined || raw === null || raw === '')
24
+ return undefined;
25
+ switch (field.type) {
26
+ case 'number': {
27
+ const n = typeof raw === 'number' ? raw : Number(raw);
28
+ return Number.isFinite(n) ? n : undefined;
29
+ }
30
+ case 'boolean':
31
+ if (typeof raw === 'boolean')
32
+ return raw;
33
+ return ['true', '1', 'yes', 'on'].includes(String(raw).toLowerCase());
34
+ default:
35
+ return typeof raw === 'string' ? raw : String(raw);
36
+ }
37
+ }
38
+ /**
39
+ * Resolve one platform's config from the config file (`integrations[<id>]`) and the
40
+ * environment, then overlay runtime-computed values. Manifest `field.default` is
41
+ * intentionally NOT applied — it is the settings *form* default, while the adapter
42
+ * owns its own runtime defaults (see the design doc §3).
43
+ */
44
+ function resolveManifestConfig(manifest, sections, runtime, stored) {
45
+ const section = sections[manifest.id];
46
+ const fromFile = section && typeof section === 'object' ? section : {};
47
+ const fromStore = stored ?? {};
48
+ const resolved = {};
49
+ for (const field of manifest.fields) {
50
+ const raw = fromStore[field.key] ?? fromFile[field.key] ?? process.env[manifestEnvKey(manifest.id, field.key)];
51
+ const value = coerceFieldValue(field, raw);
52
+ if (value !== undefined)
53
+ resolved[field.key] = value;
54
+ }
55
+ return runtime ? { ...resolved, ...runtime } : resolved;
56
+ }
57
+ /**
58
+ * A platform is on when it is default-on, or it was actually configured: every
59
+ * required field resolved. When a platform declares no required field (all knobs
60
+ * optional) it stays off until at least one value is provided — never silently on.
61
+ *
62
+ * Only fields that are *needed to connect* count. A routing field (`agentId`)
63
+ * cannot be a connection credential, so it must not gate the transport: a bot
64
+ * whose credentials are configured has to connect even if nobody has picked its
65
+ * answering agent yet — otherwise making that field required would silently take
66
+ * an existing install offline.
67
+ */
68
+ function isManifestEnabled(manifest, resolved) {
69
+ if (manifest.defaultEnabled)
70
+ return true;
71
+ const required = manifest.fields.filter((f) => f.required && f.type !== 'agent');
72
+ if (required.length === 0)
73
+ return Object.keys(resolved).length > 0;
74
+ return required.every((f) => resolved[f.key] !== undefined);
75
+ }
76
+ /**
77
+ * Display label for a bot: the manifest name, disambiguated by the instance label
78
+ * when there is one. The implicit legacy bot (`label === 'default'`) keeps the
79
+ * bare manifest name, so pre-G2 logs and progress text are unchanged.
80
+ */
81
+ function botLabel(manifest, instanceLabel) {
82
+ return !instanceLabel || instanceLabel === 'default'
83
+ ? manifest.label
84
+ : `${manifest.label} (${instanceLabel})`;
85
+ }
86
+ /**
87
+ * The one "make this bot match its persisted config" operation.
88
+ *
89
+ * Startup and the Settings API both funnel through here, so a bot that existed
90
+ * at boot and a bot saved afterwards cannot take different code paths — the
91
+ * structural fix for "a newly configured bot needs a restart before it works".
92
+ *
93
+ * Registers the adapter on first use (setup only ever registered at boot, which
94
+ * is why a bot created later had no adapter to connect), then connects it; when
95
+ * the bot is off or unconfigured it is dropped instead, so a disabled or deleted
96
+ * bot cannot keep a live socket.
97
+ */
98
+ async function applyInstanceConfig(router, manifest, instanceId, resolved, enabled) {
99
+ if (!enabled) {
100
+ await router.unregisterInstance(instanceId);
101
+ return false;
102
+ }
103
+ if (!router.hasInstance(instanceId)) {
104
+ router.registerAdapter(manifest.createAdapter(), instanceId);
105
+ }
106
+ return router.connectInstance(instanceId, { platform: manifest.id, ...resolved, instanceId });
107
+ }
108
+ /**
109
+ * Build the runtime reconciler. It reads the same inputs startup does
110
+ * (`sections` = markus.json bootstrap, row config = stored credentials), so the
111
+ * two can never disagree about what a bot's config *is*.
112
+ */
113
+ export function createInstanceReconciler(opts) {
114
+ const { router, instanceRepo, orgId } = opts;
115
+ const sections = opts.sections ?? {};
116
+ // Same resolution order as startup: the injected list first, registry second.
117
+ const manifestIndex = new Map((opts.manifests ?? []).map((manifest) => [manifest.id, manifest]));
118
+ const manifestOf = (platformId) => manifestIndex.get(platformId) ?? getManifest(platformId);
119
+ const configOf = (row) => row?.config && typeof row.config === 'object' ? row.config : {};
120
+ const syncInstance = async (instanceId) => {
121
+ const row = instanceRepo?.findById(instanceId);
122
+ const manifest = row ? manifestOf(row.platform) : undefined;
123
+ // Deleted row or unknown platform ⇒ the live adapter must go too, or a
124
+ // removed bot keeps a socket and a stale entry in `getInstances`.
125
+ if (!row || !manifest) {
126
+ await router.unregisterInstance(instanceId);
127
+ return;
128
+ }
129
+ const resolved = resolveManifestConfig(manifest, sections, undefined, configOf(row));
130
+ const enabled = row.enabled !== false && isManifestEnabled(manifest, resolved);
131
+ await applyInstanceConfig(router, manifest, instanceId, resolved, enabled);
132
+ };
133
+ const syncPlatform = async (platform, overrides) => {
134
+ const rows = instanceRepo?.listByPlatform(orgId, platform) ?? [];
135
+ if (rows.length > 0) {
136
+ // Instances define this platform's connections (design §4.2) — re-derive
137
+ // each one rather than patching a platform-level adapter that no longer
138
+ // owns the connection.
139
+ for (const row of rows)
140
+ await syncInstance(row.id);
141
+ return;
142
+ }
143
+ // Legacy fallback: no instance row ⇒ the implicit bot whose id is the
144
+ // platform id. Freshly saved values ride in as an overlay (they win over the
145
+ // bootstrap file), matching the old reconnect-the-platform behaviour.
146
+ const manifest = manifestOf(platform);
147
+ if (!manifest) {
148
+ await router.unregisterInstance(platform);
149
+ return;
150
+ }
151
+ const stored = opts.storedPlatformValues?.(platform);
152
+ const resolved = resolveManifestConfig(manifest, sections, overrides, stored);
153
+ await applyInstanceConfig(router, manifest, platform, resolved, isManifestEnabled(manifest, resolved));
154
+ };
155
+ return { syncInstance, syncPlatform };
156
+ }
157
+ /**
158
+ * Build, register and connect every enabled bot in `manifests`.
159
+ *
160
+ * A **platform** is a manifest; a **bot** is one instance of it. This walks the
161
+ * persisted instances first — one adapter per row, each on its own credentials —
162
+ * and only falls back to the legacy platform path (the `integrations` row +
163
+ * `markus.json` + env) for a platform that has no instance row. The legacy
164
+ * fallback registers a single implicit instance whose id is the platform id,
165
+ * which is byte-for-byte the pre-instance behaviour (design §4.2, §5.2 step 4).
166
+ *
167
+ * One bot failing never blocks the rest (issue #340 degradation rules).
168
+ */
169
+ export async function connectConfiguredPlatforms(opts) {
170
+ const { router, manifests, config, runtimeConfig, storedConfig, instances } = opts;
171
+ const sections = (config.integrations ?? {});
172
+ const results = [];
173
+ // Persisted instances grouped by platform, so each manifest sees only its own.
174
+ const byPlatform = new Map();
175
+ for (const instance of instances ?? []) {
176
+ const list = byPlatform.get(instance.platform);
177
+ if (list)
178
+ list.push(instance);
179
+ else
180
+ byPlatform.set(instance.platform, [instance]);
181
+ }
182
+ const connectOne = async (manifest, instanceId, label, resolved) => {
183
+ try {
184
+ // `connectOne` is only ever called for a bot that should be up, so the
185
+ // enablement decision is already made by the caller.
186
+ const connected = await applyInstanceConfig(router, manifest, instanceId, resolved, true);
187
+ results.push({ id: instanceId, label, connected });
188
+ }
189
+ catch (error) {
190
+ results.push({ id: instanceId, label, connected: false, error: String(error) });
191
+ }
192
+ };
193
+ for (const manifest of manifests) {
194
+ const rows = byPlatform.get(manifest.id) ?? [];
195
+ if (rows.length > 0) {
196
+ for (const row of rows) {
197
+ const rowConfig = row.config && typeof row.config === 'object' ? row.config : {};
198
+ const resolved = resolveManifestConfig(manifest, sections, runtimeConfig?.[manifest.id], rowConfig);
199
+ // A row switched off, or one whose required fields do not resolve, is
200
+ // skipped — never connected half-configured.
201
+ if (row.enabled === false || !isManifestEnabled(manifest, resolved))
202
+ continue;
203
+ await connectOne(manifest, row.id, botLabel(manifest, row.label), resolved);
204
+ }
205
+ continue;
206
+ }
207
+ // Legacy fallback: no instance row ⇒ the implicit single bot, id = platform id.
208
+ const stored = storedConfig?.(manifest.id);
209
+ const resolved = resolveManifestConfig(manifest, sections, runtimeConfig?.[manifest.id], stored?.values);
210
+ if (!isManifestEnabled(manifest, resolved) || stored?.enabled === false)
211
+ continue;
212
+ await connectOne(manifest, manifest.id, manifest.label, resolved);
213
+ }
214
+ return results;
215
+ }
216
+ /**
217
+ * Apply the persisted platform→agent bindings to the router at startup.
218
+ *
219
+ * Runs right after {@link connectConfiguredPlatforms} so the router is bound in
220
+ * the same window the adapters come up — before the first inbound message can be
221
+ * routed. Returns the number of bindings applied (0 is a valid, quiet outcome:
222
+ * a fresh install binds nothing and inbound stays a loud no-op until configured).
223
+ */
224
+ export function applyPersistedPlatformBindings(opts) {
225
+ const bindings = loadPlatformBindings({
226
+ orgId: opts.orgId,
227
+ repo: opts.repo,
228
+ bootstrap: opts.bootstrap,
229
+ });
230
+ for (const binding of bindings) {
231
+ opts.router.bindPlatformAgent(binding.agentId, binding.platform);
232
+ }
233
+ if (bindings.length > 0) {
234
+ log.info(`Bound ${bindings.length} platform(s) to agents at startup`, {
235
+ bindings: bindings.map((b) => `${b.platform}→${b.agentId}`).join(', '),
236
+ });
237
+ }
238
+ return bindings.length;
239
+ }
14
240
  export function registerStartCommand(program) {
15
241
  program
16
242
  .command('start')
@@ -43,11 +269,13 @@ export async function createServices(config) {
43
269
  const llmStreamTimeoutMs = Number(process.env['LLM_STREAM_TIMEOUT_MS']) || undefined;
44
270
  const providerMeta = new Map(PROVIDERS.map((p) => [p.id, p]));
45
271
  const envPrefix = (id) => id.toUpperCase().replace(/-/g, '_');
46
- // Markus Cloud — OpenRouter member key only (chat + search).
272
+ // Markus Cloud — OpenRouter member key only (chat + search). The key lives in
273
+ // the canonical secret store (~/.markus/.env); config keeps only a reference.
47
274
  const markusCfg = config.llm.providers['markus'] ?? {};
48
- const markusOrKey = markusCfg.apiKey?.startsWith('sk-or-')
275
+ const legacyMarkusKey = markusCfg.apiKey?.startsWith('sk-or-')
49
276
  ? markusCfg.apiKey
50
277
  : (markusCfg.apiKey && !/^markus[_-]/i.test(markusCfg.apiKey) ? markusCfg.apiKey : '');
278
+ const markusOrKey = process.env['MARKUS_OPENROUTER_KEY'] || legacyMarkusKey;
51
279
  if (markusOrKey) {
52
280
  const cfgBaseUrl = markusCfg.baseUrl ?? '';
53
281
  const markusOrBase = (cfgBaseUrl && !/localhost:8787|127\.0\.0\.1:8787|workers\.dev|markus-proxy/i.test(cfgBaseUrl))
@@ -78,15 +306,19 @@ export async function createServices(config) {
78
306
  const prev = markusCfg;
79
307
  const needPersist = (markusModelsUrl && markusModelsUrl !== (prev.modelsUrl ?? ''))
80
308
  || (markusOrBase && markusOrBase !== (prev.baseUrl ?? ''))
81
- || (markusOrKey && markusOrKey !== (prev.apiKey ?? ''))
309
+ || !!prev.apiKey // legacy plaintext on disk → migrate to the store
310
+ || !prev.apiKeyEnv // or the env reference is missing
82
311
  || !!(prev.subscriptionKey || prev.proxyUrl);
83
312
  if (needPersist) {
84
313
  try {
314
+ // Secret → canonical store; config keeps only the reference.
315
+ setEnvValue('MARKUS_OPENROUTER_KEY', markusOrKey);
85
316
  saveConfig({
86
317
  llm: {
87
318
  providers: {
88
319
  markus: {
89
- apiKey: markusOrKey,
320
+ apiKey: null, // never persist plaintext
321
+ apiKeyEnv: 'MARKUS_OPENROUTER_KEY',
90
322
  baseUrl: markusOrBase,
91
323
  ...(markusModelsUrl ? { modelsUrl: markusModelsUrl } : {}),
92
324
  ...(prev.model ? { model: prev.model } : {}),
@@ -167,11 +399,20 @@ export async function createServices(config) {
167
399
  }
168
400
  continue;
169
401
  }
170
- const apiKey = cfg.apiKey
402
+ // Secret precedence — uniform across the platform: an env value (process
403
+ // env, incl. the canonical `~/.markus/.env`) wins, then the config's
404
+ // `apiKeyEnv` indirection, then — LEGACY, read-only — a raw `apiKey` stored
405
+ // in markus.json by older clients. Writes always go to `~/.markus/.env`
406
+ // (referenced by name); plaintext config keys are never written again.
407
+ const apiKey = (cfg.apiKeyEnv ? process.env[cfg.apiKeyEnv] : undefined)
171
408
  ?? (meta ? process.env[meta.envKey] : undefined)
172
- ?? process.env[`${prefix}_API_KEY`];
409
+ ?? process.env[`${prefix}_API_KEY`]
410
+ ?? cfg.apiKey;
173
411
  if (!apiKey)
174
412
  continue;
413
+ if (cfg.apiKey && !cfg.apiKeyEnv) {
414
+ log.warn('Provider apiKey read from markus.json (legacy plaintext). Move it to ~/.markus/.env; the config value is read-only from now on.', { provider: name });
415
+ }
175
416
  const model = cfg.model
176
417
  ?? process.env[`${prefix}_MODEL`]
177
418
  ?? meta?.defaultModel
@@ -190,12 +431,13 @@ export async function createServices(config) {
190
431
  ...(llmStreamTimeoutMs ? { streamTimeoutMs: llmStreamTimeoutMs } : {}),
191
432
  };
192
433
  }
193
- // If the configured default provider has no API key, fall back to the first available one
194
- if (!providerConfigs[defaultProvider]) {
195
- const available = Object.keys(providerConfigs);
196
- if (available.length > 0) {
197
- defaultProvider = available[0];
198
- }
434
+ // Do NOT let a merely env-detected provider hijack the default. The configured
435
+ // default is the user's intent (factory default = markus); when it has no
436
+ // usable config yet the router transparently falls back to any available
437
+ // provider at call time. We only auto-pick when nothing was configured at all,
438
+ // and prefer Markus Cloud over an arbitrary env provider.
439
+ if (!providerConfigs[defaultProvider] && !defaultProvider) {
440
+ defaultProvider = providerConfigs['markus'] ? 'markus' : Object.keys(providerConfigs)[0];
199
441
  }
200
442
  const llmRouter = LLMRouter.createDefault(providerConfigs, defaultProvider);
201
443
  // Apply enabled/disabled state from config
@@ -299,13 +541,23 @@ export async function createServices(config) {
299
541
  }
300
542
  log.info('Feishu MCP server configured', { presets, localBin: !!larkMcpBin });
301
543
  }
544
+ // The Feishu tool's default destination is a *notification-related* field, so
545
+ // it reads the same single source as the outbound dispatcher: the DB
546
+ // `platform_instances.config` that Settings writes. The legacy `markus.json`
547
+ // `integrations.feishu.notifyChatId` / `notifyOpenId` read is gone (R2), so
548
+ // the file no longer shadows the DB for this fact.
549
+ const feishuNotifyConfig = (storage?.platformInstanceRepo?.listByOrg('default') ?? []).find((instance) => instance.platform === 'feishu')?.config;
302
550
  const feishuToolsConfig = (feishuAppId && feishuAppSecret)
303
551
  ? {
304
552
  appId: feishuAppId,
305
553
  appSecret: feishuAppSecret,
306
554
  domain: feishuIntegration?.domain,
307
- defaultChatId: typeof feishuIntegration?.notifyChatId === 'string' ? feishuIntegration.notifyChatId : undefined,
308
- defaultOpenId: typeof feishuIntegration?.notifyOpenId === 'string' ? feishuIntegration.notifyOpenId : undefined,
555
+ defaultChatId: typeof feishuNotifyConfig?.['notifyChatId'] === 'string'
556
+ ? feishuNotifyConfig['notifyChatId']
557
+ : undefined,
558
+ defaultOpenId: typeof feishuNotifyConfig?.['notifyOpenId'] === 'string'
559
+ ? feishuNotifyConfig['notifyOpenId']
560
+ : undefined,
309
561
  }
310
562
  : undefined;
311
563
  const agentManager = new AgentManager({
@@ -321,6 +573,19 @@ export async function createServices(config) {
321
573
  if (config.agent?.maxToolIterations) {
322
574
  agentManager.maxToolIterations = config.agent.maxToolIterations;
323
575
  }
576
+ // 并发处理配置:从 markus.json 读回 → AgentManager 单一事实源。
577
+ // 必须在 orgService.loadFromDB 之前设置:恢复的 agent 会以
578
+ // row.concurrent ?? manager._concurrentConfig 取值(agent-manager L2350),
579
+ // 故此处赋值即可让「重启后仍按设置值并发」成立(修复「改了没用/重启即丢」)。
580
+ if (config.agent?.concurrent) {
581
+ agentManager.concurrentConfig = config.agent.concurrent;
582
+ }
583
+ // 每个 agent 的任务上限(智能体设置 → 任务上限):从 markus.json 读回 →
584
+ // AgentManager 单一事实源。TaskService.checkTaskLimits 读取该值,未设置时回退
585
+ // 治理策略默认值。赋值必须早于任何任务创建;与并发配置同处启动早期。
586
+ if (typeof config.agent?.maxPendingTasksPerAgent === 'number') {
587
+ agentManager.maxPendingTasksPerAgent = config.agent.maxPendingTasksPerAgent;
588
+ }
324
589
  if (config.codingTools) {
325
590
  agentManager.setCodingToolsConfig(config.codingTools);
326
591
  }
@@ -521,6 +786,9 @@ async function startServerCore(config, values, opts) {
521
786
  if (config.security?.adminPassword && !process.env['ADMIN_PASSWORD']) {
522
787
  process.env['ADMIN_PASSWORD'] = config.security.adminPassword;
523
788
  }
789
+ if (config.security?.gatewaySecret && !process.env['GATEWAY_SECRET']) {
790
+ process.env['GATEWAY_SECRET'] = config.security.gatewaySecret;
791
+ }
524
792
  // Propagate markus.json search API keys into env so web_search tool can read them
525
793
  if (config.integrations?.search?.serperApiKey && !process.env['SERPER_API_KEY']) {
526
794
  process.env['SERPER_API_KEY'] = config.integrations.search.serperApiKey;
@@ -640,6 +908,29 @@ async function startServerCore(config, values, opts) {
640
908
  agentManager.setWebUiBaseUrl(`http://localhost:${apiPort}`);
641
909
  requirementService.setAgentManager(agentManager);
642
910
  requirementService.setHITLService(hitlService);
911
+ // ── Approval outcomes: one execution point ──────────────────────────────────
912
+ // Both the `requestApprovalAndWait` callbacks (task/requirement gates) and the
913
+ // HTTP fallback in APIServer route through this applier; its synchronous claim
914
+ // on the approval entity makes the outcome exactly-once across the two.
915
+ const approvalApplier = new ApprovalApplier(hitlService);
916
+ approvalApplier.registerPort(taskService);
917
+ approvalApplier.registerPort(requirementService);
918
+ taskService.setApprovalApplier(approvalApplier);
919
+ requirementService.setApprovalApplier(approvalApplier);
920
+ apiServer.setApprovalApplier(approvalApplier);
921
+ // Recording a decision routes it. The router is the inbound surfaces' common
922
+ // backstop: the `requestApprovalAndWait` callback above is in-memory only and
923
+ // dies with the process, so a card tap on an approval created before the last
924
+ // restart used to record "approved" while nothing moved the task (2026-10-16).
925
+ // Owning the routing here — at the one place a decision is written — means no
926
+ // surface, present or future, has to remember to apply it.
927
+ hitlService.setDecisionRouter(response => {
928
+ routeRecordedDecision(approvalApplier, response.approval, response.decision);
929
+ });
930
+ // A requirement 打回 must stay observable on its own entity, so the decision
931
+ // also lands as a requirement comment — through the existing comment channel
932
+ // (owned by TaskService), never through a new field or table.
933
+ requirementService.setRequirementCommentPoster((requirementId, authorId, authorName, content, mentions, opts) => taskService.postRequirementComment(requirementId, authorId, authorName, content, mentions, undefined, opts));
643
934
  apiServer.setProjectService(projectService);
644
935
  apiServer.setReportService(reportService);
645
936
  apiServer.setKnowledgeService(knowledgeService);
@@ -712,7 +1003,21 @@ async function startServerCore(config, values, opts) {
712
1003
  priority: item.type === 'review_stale' ? 'high' : 'normal',
713
1004
  actionType: item.taskId ? 'navigate' : 'none',
714
1005
  actionTarget: item.taskId ? JSON.stringify({ path: `/work?openTask=${item.taskId}` }) : undefined,
715
- metadata: { taskId: item.taskId, agentId: item.agentId, staleType: item.type },
1006
+ metadata: {
1007
+ taskId: item.taskId,
1008
+ agentId: item.agentId,
1009
+ staleType: item.type,
1010
+ // The title and body as structure: the detector knows *what* to say,
1011
+ // this is the only place that knows the sentence's key.
1012
+ i18n: {
1013
+ titleKey: item.type === 'review_stale'
1014
+ ? 'notifications.titles.staleReview'
1015
+ : item.type === 'stuck_task'
1016
+ ? 'notifications.titles.stuckTask'
1017
+ : 'notifications.titles.unstartedTask',
1018
+ ...(item.i18n ?? {}),
1019
+ },
1020
+ },
716
1021
  });
717
1022
  }
718
1023
  });
@@ -1151,7 +1456,13 @@ async function startServerCore(config, values, opts) {
1151
1456
  priority: 'high',
1152
1457
  actionType: 'open_chat',
1153
1458
  actionTarget: JSON.stringify({ agentId, sessionId: mainSession.id }),
1154
- metadata: { agentId, sessionId: mainSession.id },
1459
+ metadata: {
1460
+ agentId,
1461
+ sessionId: mainSession.id,
1462
+ // The `reason` is the agent's own words — content, passed through
1463
+ // verbatim. Only the platform's own line is ours to translate.
1464
+ i18n: { titleKey: 'notifications.titles.agentNeedsHelp' },
1465
+ },
1155
1466
  });
1156
1467
  auditService.record({
1157
1468
  orgId: 'default', agentId, type: 'error', action: 'escalation', detail: reason, success: false,
@@ -1172,7 +1483,7 @@ async function startServerCore(config, values, opts) {
1172
1483
  }
1173
1484
  // Task resume is triggered after agents finish starting (see below).
1174
1485
  // Wire External Agent Gateway for OpenClaw integration
1175
- const gatewaySecret = config.security?.gatewaySecret ?? process.env['GATEWAY_SECRET'] ?? 'markus-gateway-default-secret-change-me';
1486
+ const gatewaySecret = resolveGatewaySecret();
1176
1487
  const gateway = new ExternalAgentGateway({ signingSecret: gatewaySecret });
1177
1488
  gateway.setAgentCreator(async (opts) => {
1178
1489
  const caps = (opts.capabilities ?? []).map((c) => c.toLowerCase());
@@ -1255,33 +1566,108 @@ async function startServerCore(config, values, opts) {
1255
1566
  }));
1256
1567
  });
1257
1568
  apiServer.setGateway(gateway, gatewaySecret);
1258
- log.info('External Agent Gateway enabled', { secret: gatewaySecret === 'markus-gateway-default-secret-change-me' ? '(default)' : '(custom)' });
1259
- // ── Remote Access (WebRTC P2P via markus-hub + signal server) ─────────
1569
+ log.info('External Agent Gateway enabled', { secret: process.env['GATEWAY_SECRET'] ? '(custom)' : '(auto-generated)' });
1570
+ // ── Remote Access (T8) ─────────────────────────────────────────────────
1571
+ // Prefer the user's OWN tunnel (cloudflared / tailscale) — the data plane
1572
+ // never touches our servers. `config.remote.mode` selects the channel; when it
1573
+ // is unset (or `legacyRelay` is explicitly on) we fall back to the legacy
1574
+ // WebRTC relay so existing installs keep working during the grey release.
1260
1575
  {
1261
- const hubTokenPath = join(homedir(), '.markus', 'hub-token');
1262
- const createRemoteAgent = async () => {
1576
+ const markusConfigPath = values['config'] ?? getDefaultConfigPath();
1577
+ const remoteCfg = config.remote ?? {};
1578
+ const useLegacyRelay = remoteCfg.legacyRelay === true || !remoteCfg.mode;
1579
+ const hubBaseUrl = remoteCfg.hubUrl ?? config.hub?.url ?? 'https://www.markus.global';
1580
+ const instanceName = remoteCfg.instanceName ?? config.org?.name ?? 'My Markus';
1581
+ const localPort = remoteCfg.localPort ?? config.server?.apiPort ?? 8056;
1582
+ // Legacy relay: keep the old WebRTC agent, wrapped so it speaks the same
1583
+ // controller interface as the tunnel path.
1584
+ const createLegacyRemote = async () => {
1585
+ const hubTokenPath = join(homedir(), '.markus', 'hub-token');
1263
1586
  const token = existsSync(hubTokenPath) ? readFileSync(hubTokenPath, 'utf-8').trim() : undefined;
1264
1587
  if (!token)
1265
1588
  return null;
1266
- const { RemoteAccessAgent } = await import('@markus/remote');
1267
- return new RemoteAccessAgent({
1268
- hubUrl: config.remote?.hubUrl ?? config.hub?.url ?? 'https://www.markus.global',
1589
+ const { RemoteAccessAgent, createLegacyController: wrap } = await import('@markus/remote');
1590
+ return wrap(new RemoteAccessAgent({
1591
+ hubUrl: hubBaseUrl,
1269
1592
  hubToken: token,
1270
- instanceName: config.remote?.instanceName ?? config.org?.name ?? 'My Markus',
1271
- localPort: config.server?.apiPort ?? 8056,
1272
- jwtSecret: process.env['JWT_SECRET'],
1593
+ instanceName,
1594
+ localPort,
1595
+ jwtSecret: resolveJwtSecret(),
1596
+ }));
1597
+ };
1598
+ // Tunnel path: TunnelManager (T6) + RegistryClient (T7) behind one controller.
1599
+ // autoInstallConsent is deliberately NOT set — a missing binary refuses to
1600
+ // install and exposes the plan instead (the wizard/Agent path handles consent).
1601
+ const createTunnelRemote = async () => {
1602
+ const { TunnelManager, RegistryClient, createTunnelController: wrap, persistEndpointSecretForTunnel, createLocalVerifyHandler, resolveHubToken, hubUsernameFromToken, buildEntryUrl, } = await import('@markus/remote');
1603
+ const hubToken = resolveHubToken();
1604
+ if (!hubToken)
1605
+ return null; // not signed in to the Hub — can enable later via Settings
1606
+ const registry = new RegistryClient({ hubUrl: hubBaseUrl, hubToken });
1607
+ // The stable shareable entry (`https://{hubUser}.remote.markus.global`),
1608
+ // derived from the signed-in Hub identity. Without this the status payload
1609
+ // reported `entryUrl: null` and the Settings panel had nothing to show.
1610
+ const entryUrl = buildEntryUrl(hubUsernameFromToken(hubToken));
1611
+ const manager = new TunnelManager({
1612
+ kind: remoteCfg.mode,
1613
+ apiPort: localPort,
1614
+ instanceName,
1615
+ ...(remoteCfg.hostname ? { hostname: remoteCfg.hostname } : {}),
1616
+ ...(entryUrl ? { entryUrl } : {}),
1617
+ }, { registry, persistSecret: persistEndpointSecretForTunnel });
1618
+ // Local verify route (T7): read THROUGH the manager — no second cache.
1619
+ apiServer.setRemoteVerifyHandler(createLocalVerifyHandler(() => manager.getVerifyToken()));
1620
+ const controller = wrap(manager);
1621
+ // Persist the endpoint-id POINTER only when it actually changes.
1622
+ let lastEndpointId = remoteCfg.activeEndpointId ?? null;
1623
+ controller.onStatus(() => {
1624
+ const id = controller.getActiveEndpointId();
1625
+ if (id && id !== lastEndpointId) {
1626
+ lastEndpointId = id;
1627
+ try {
1628
+ saveConfig({ remote: { activeEndpointId: id } }, markusConfigPath);
1629
+ }
1630
+ catch { /* non-critical */ }
1631
+ }
1273
1632
  });
1633
+ return controller;
1274
1634
  };
1275
- apiServer.setRemoteAgentFactory(createRemoteAgent);
1276
- if (config.remote?.enabled === true) {
1277
- const remoteAgent = await createRemoteAgent();
1278
- if (remoteAgent) {
1279
- apiServer.setRemoteAgent(remoteAgent);
1280
- if (config.remote?.autoConnect !== false) {
1281
- remoteAgent.start().then(() => {
1282
- const status = remoteAgent.getStatus();
1283
- if (status.remoteUrl) {
1284
- log.info(`Remote access available at ${status.remoteUrl}`);
1635
+ const remoteFactory = useLegacyRelay ? createLegacyRemote : createTunnelRemote;
1636
+ apiServer.setRemoteAgentFactory(remoteFactory);
1637
+ // ── Path B wiring (T10) ───────────────────────────────────────────────
1638
+ // The plan the wizard shows the user is built HERE, from the same provider
1639
+ // knowledge the TunnelManager uses; the browser only renders it. Nothing
1640
+ // installs without the user pressing "hand it to the Agent".
1641
+ {
1642
+ const { execFile } = await import('node:child_process');
1643
+ const probe = (bin) => new Promise((resolve) => {
1644
+ execFile(process.platform === 'win32' ? 'where' : 'which', [bin], (err) => resolve(!err));
1645
+ });
1646
+ apiServer.setRemoteDetectHandler(async () => ({
1647
+ cloudflared: await probe('cloudflared'),
1648
+ tailscale: await probe('tailscale'),
1649
+ }));
1650
+ const { buildAgentSetupPlan } = await import('@markus/remote');
1651
+ apiServer.setRemoteSetupPlanner({
1652
+ plan: (input) => buildAgentSetupPlan({
1653
+ kind: input.kind,
1654
+ platform: input.platform,
1655
+ localPort: input.localPort ?? localPort,
1656
+ hubUrl: input.hubUrl ?? hubBaseUrl,
1657
+ ...(input.instanceName ? { instanceName: input.instanceName } : {}),
1658
+ ...(input.username ? { username: input.username } : {}),
1659
+ }),
1660
+ }, localPort);
1661
+ }
1662
+ if (remoteCfg.enabled === true) {
1663
+ const controller = await remoteFactory();
1664
+ if (controller) {
1665
+ apiServer.setRemoteAgent(controller);
1666
+ if (remoteCfg.autoConnect !== false) {
1667
+ controller.start().then(() => {
1668
+ const status = controller.getRemoteStatus();
1669
+ if (status?.publicUrl) {
1670
+ log.info(`Remote access available at ${status.publicUrl}`);
1285
1671
  }
1286
1672
  }).catch((err) => {
1287
1673
  log.warn('Remote access failed to start', { error: String(err) });
@@ -1289,7 +1675,7 @@ async function startServerCore(config, values, opts) {
1289
1675
  }
1290
1676
  }
1291
1677
  else {
1292
- log.debug('Remote access: no Hub token yet (can enable later via Settings)');
1678
+ log.debug('Remote access: not signed in to the Hub yet (can enable later via Settings)');
1293
1679
  }
1294
1680
  }
1295
1681
  }
@@ -1546,7 +1932,7 @@ async function startServerCore(config, values, opts) {
1546
1932
  log.warn('Failed to update mailbox status', { itemId, error: String(e) });
1547
1933
  }
1548
1934
  },
1549
- markStaleProcessingAsDropped: (aid) => mbRepo.markStaleProcessingAsDropped(aid),
1935
+ markStaleProcessingAsDropped: (aid, nowIso, ownerId) => mbRepo.markStaleProcessingAsDropped(aid, nowIso, ownerId),
1550
1936
  loadQueued: (aid) => {
1551
1937
  const rows = mbRepo.getByAgent(aid, { status: 'queued' });
1552
1938
  return rows.map((r) => ({
@@ -1733,17 +2119,16 @@ async function startServerCore(config, values, opts) {
1733
2119
  const ws = apiServer.getWSBroadcaster();
1734
2120
  ws.broadcast({ type: 'agent:stopped', payload: event, timestamp: new Date().toISOString() });
1735
2121
  });
1736
- // Wire task completion/failure events to WS broadcast
1737
- eventBus.on('task:completed', (event) => {
1738
- const { taskId, agentId } = event;
1739
- const ws = apiServer.getWSBroadcaster();
1740
- ws.broadcastTaskUpdate(taskId, 'completed', { agentId });
1741
- });
1742
- eventBus.on('task:failed', (event) => {
1743
- const { taskId, agentId, error } = event;
1744
- const ws = apiServer.getWSBroadcaster();
1745
- ws.broadcastTaskUpdate(taskId, 'failed', { agentId, error });
1746
- });
2122
+ // NOTE (2026-10-16): `task:completed` / `task:failed` are **agent execution
2123
+ // lifecycle** events — "the runtime finished running". They used to be
2124
+ // re-broadcast here as `task:update`, which was wrong twice over: the payload
2125
+ // carries no title (the UI/OS notification degraded to a bare "Task") and the
2126
+ // status was a lie (a finished execution moves the task to `review`, not
2127
+ // `completed`). The **status machine** (`task-service.broadcastStatusChange`)
2128
+ // is the single writer of a task's user-facing status and already emits
2129
+ // `task:update` with the real status *and* the title on every transition, so
2130
+ // these bridges were pure counterfeit. Removed rather than enriched: one fact,
2131
+ // one writer.
1747
2132
  // Wire system-wide events to WS broadcast
1748
2133
  eventBus.on('system:pause-all', (event) => {
1749
2134
  const ws = apiServer.getWSBroadcaster();
@@ -1782,14 +2167,24 @@ async function startServerCore(config, values, opts) {
1782
2167
  log.info(`Daily token reset scheduled in ${Math.round(msUntilMidnight / 60000)} minutes`);
1783
2168
  };
1784
2169
  scheduleDailyReset();
2170
+ // IM traffic must go through the same proxy the rest of the platform uses.
2171
+ // Bare `fetch` inside the platform clients cannot reach a blocked network
2172
+ // (e.g. Telegram from mainland China), which surfaces as "connection failed"
2173
+ // while the LLM path — already proxy-aware — works fine on the same machine.
2174
+ // One install point; no per-adapter wiring to forget.
2175
+ setHttpFetch(proxyFetch);
1785
2176
  const messageRouter = new MessageRouter();
1786
- const webUIAdapter = new WebUIAdapter();
1787
- messageRouter.registerAdapter(webUIAdapter);
1788
- messageRouter.setAgentHandler(async (agentId, message) => {
2177
+ messageRouter.setAgentHandler(async (target, message) => {
2178
+ const agentId = target.agentId;
1789
2179
  const startTs = Date.now();
1790
2180
  try {
1791
2181
  const agent = agentManager.getAgent(agentId);
1792
- const reply = await agent.sendMessage(message.content.text ?? '', message.senderId);
2182
+ // Session isolation (design §6.2): the resolved conversation key becomes the
2183
+ // agent's `channelKey`, so each group and each external user gets its own
2184
+ // session. A channel designated `main` maps to the agent's own main session
2185
+ // (no per-channel key).
2186
+ const channelKey = target.conversationKey === MAIN_CONVERSATION_KEY ? undefined : target.conversationKey;
2187
+ const reply = await agent.sendMessage(message.content.text ?? '', message.senderId, undefined, { channelKey });
1793
2188
  auditService.record({
1794
2189
  orgId: 'default',
1795
2190
  agentId,
@@ -1815,34 +2210,275 @@ async function startServerCore(config, values, opts) {
1815
2210
  return undefined;
1816
2211
  }
1817
2212
  });
1818
- const commPort = apiPort + 2;
1819
- // ── Step 5: Gateway ───────────────────────────────────────────────────────
2213
+ // ── Platform actions (design §6.5) ────────────────────────────────────────
2214
+ // A card tap is a HITL transition, not a conversation. The action port is the
2215
+ // single inbound side of the approval loop: verify the signed ref the gateway
2216
+ // rendered, then hand the decision to the one HITL service. Without a secret
2217
+ // the ref is a bare approval id (pre-G4 behaviour) — accepted, but warned.
2218
+ messageRouter.setActionHandler(async (action) => {
2219
+ const payload = (action.payload ?? {});
2220
+ const value = payload['action']?.['value'] ?? payload['value'] ?? {};
2221
+ const { approvalId, command, unverified } = resolveCardActionValue(value, resolveActionSecret());
2222
+ if (unverified) {
2223
+ log.warn('MARKUS_ACTION_SECRET not set — accepted an unverified approval action ref');
2224
+ }
2225
+ if (!approvalId || !command) {
2226
+ log.warn('Platform action did not resolve to an approval — ignoring', {
2227
+ platform: action.platform,
2228
+ instanceId: action.instanceId,
2229
+ });
2230
+ return;
2231
+ }
2232
+ // This surface cannot carry free text — `respondToApproval` is called below with
2233
+ // no comment. So a choice that *requires* a written reason must not be accepted
2234
+ // here: recording a request-changes whose reason was never captured sends the
2235
+ // task back with nothing to act on. Cards no longer offer such a choice (the
2236
+ // renderer withholds it and points at Markus); this refuses the taps a card sent
2237
+ // *before* that change can still deliver — fail closed, never a silent mis-apply.
2238
+ const tapped = hitlService.getApproval(approvalId)?.options?.find((o) => o.id === command);
2239
+ if (tapped?.requiresComment) {
2240
+ log.warn('Refused a platform approval action that needs an unwritable comment', {
2241
+ approvalId,
2242
+ command,
2243
+ platform: action.platform,
2244
+ });
2245
+ return;
2246
+ }
2247
+ // Mirror UserInputModal: a named option is affirmative unless it is a reject;
2248
+ // the tapped option id is recorded as `selectedOption` (was silently dropped).
2249
+ const approved = command !== 'reject' && command !== 'request_changes';
2250
+ const resolved = hitlService.respondToApproval(approvalId, approved, action.actorId || 'platform-action', undefined, command);
2251
+ log.info('Platform action resolved', { approvalId, command, platform: action.platform });
2252
+ // Feedback: rewrite the card the tap came from. One invariant, two paths —
2253
+ // *the card must converge to the approval's authoritative state*:
2254
+ // · `resolved` — this tap recorded the decision;
2255
+ // · otherwise — the approval was already terminal (idempotent re-tap):
2256
+ // re-read the record and rewrite anyway, so a stale card (client clobber,
2257
+ // an earlier failed PATCH) self-heals on the next tap.
2258
+ // Timing: Feishu re-renders the tapper's client with the clicked-time card
2259
+ // when the callback responds, so the PATCH must run AFTER the ack — observed
2260
+ // 2026-10-13 as "card flashed resolved, then snapped back to buttons" while
2261
+ // the server kept the resolved card (GET-message probe). Scheduling the
2262
+ // rewrite (not awaiting it inside this handler) makes it the last write the
2263
+ // client applies. Best-effort: failures are logged, never fatal, never roll
2264
+ // the decision back.
2265
+ const approval = resolved?.approval ?? hitlService.getApproval(approvalId);
2266
+ const messageId = action.messageId;
2267
+ if (approval && messageId) {
2268
+ void scheduleCardRewrite(async () => {
2269
+ // Resolve the display name inside the post-ack rewrite: it is a network
2270
+ // round-trip to the contact API, so it must never delay the callback
2271
+ // ack. Best-effort — null keeps the raw id, which is always correct.
2272
+ const actorName = action.actorId
2273
+ ? await messageRouter.resolveActorName(action.platform, action.instanceId, action.actorId)
2274
+ : null;
2275
+ const updated = await messageRouter.updateResolvedCard(action.platform, action.instanceId, messageId, buildApprovalCardResolution(approval, {
2276
+ actorId: action.actorId,
2277
+ actorName: actorName ?? undefined,
2278
+ tappedOption: command,
2279
+ }));
2280
+ if (!updated) {
2281
+ log.info('Card left as-is — platform cannot edit a sent message', {
2282
+ approvalId,
2283
+ platform: action.platform,
2284
+ });
2285
+ }
2286
+ }, (error) => {
2287
+ log.warn('Failed to rewrite the approval card after the decision', {
2288
+ approvalId,
2289
+ platform: action.platform,
2290
+ error: String(error),
2291
+ });
2292
+ });
2293
+ }
2294
+ });
2295
+ // ── Step 5: Gateway (manifest-driven) ─────────────────────────────────────
1820
2296
  progress?.setActive(5);
1821
- await messageRouter.connectAll([{ platform: 'webui', port: commPort }]);
1822
- // Check for Feishu config
1823
- const feishuAppId = config.integrations?.feishu?.appId ?? process.env['FEISHU_APP_ID'];
1824
- const feishuAppSecret = config.integrations?.feishu?.appSecret ?? process.env['FEISHU_APP_SECRET'];
1825
- if (feishuAppId && feishuAppSecret) {
1826
- const feishuAdapter = new FeishuAdapter();
1827
- messageRouter.registerAdapter(feishuAdapter);
1828
- try {
1829
- await messageRouter.connectAll([
1830
- {
1831
- platform: 'feishu',
1832
- appId: feishuAppId,
1833
- appSecret: feishuAppSecret,
1834
- },
1835
- ]);
1836
- startupLog('OK', '飞书适配器已连接');
1837
- progress?.complete(5, 'webhook adapters: WebUI + Feishu');
2297
+ // Platforms configured through the Settings UI live in the `integrations`
2298
+ // table, not `markus.json`; feeding them in here is what makes a UI-configured
2299
+ // platform actually connect on the next start.
2300
+ const integrationRepo = storage?.integrationRepo;
2301
+ // Persisted bot instances (platform_instances). Each row is one bot — a platform
2302
+ // hosting several bots brings several rows, and startup connects them all
2303
+ // (G2, design §4.2). The legacy integrations path below is the fallback for a
2304
+ // platform that has no instance row yet.
2305
+ const persistedInstances = storage?.platformInstanceRepo?.listByOrg('default') ?? [];
2306
+ const platformResults = await connectConfiguredPlatforms({
2307
+ router: messageRouter,
2308
+ manifests: PLATFORM_MANIFESTS,
2309
+ config,
2310
+ instances: persistedInstances,
2311
+ storedConfig: (platformId) => {
2312
+ const manifest = getManifest(platformId);
2313
+ if (!manifest || !integrationRepo)
2314
+ return undefined;
2315
+ return readStoredPlatformConfig({ orgId: 'default', repo: integrationRepo }, manifest);
2316
+ },
2317
+ });
2318
+ for (const result of platformResults) {
2319
+ if (result.connected) {
2320
+ startupLog('OK', `${result.label} 适配器已连接`);
1838
2321
  }
1839
- catch (error) {
1840
- startupLog('WARN', `飞书适配器连接失败,跳过: ${error instanceof Error ? error.message : String(error)}`);
1841
- progress?.complete(5, 'webhook adapter: WebUI only (Feishu failed)');
2322
+ else {
2323
+ startupLog('WARN', `${result.label} 适配器连接失败,跳过${result.error ? `: ${result.error}` : ''}`);
1842
2324
  }
1843
2325
  }
1844
- else {
1845
- progress?.complete(5, 'webhook adapter: WebUI only');
2326
+ // Bind each platform to its configured agent before the first inbound message
2327
+ // can arrive — the same window the adapters just came up in (defect A).
2328
+ applyPersistedPlatformBindings({
2329
+ router: messageRouter,
2330
+ repo: storage?.integrationRepo,
2331
+ orgId: 'default',
2332
+ bootstrap: (platform) => {
2333
+ const section = config.integrations?.[platform];
2334
+ return section && typeof section === 'object' ? section : {};
2335
+ },
2336
+ });
2337
+ // The DB is the single writer for inbound routing (design §2/§6.3); the
2338
+ // in-memory bindings above stay a read-only `markus.json` bootstrap fallback.
2339
+ // Without this lookup an unbound platform would have no global route and the
2340
+ // message would have nowhere to land (defect D6).
2341
+ if (storage?.channelBindingRepo && storage?.platformInstanceRepo) {
2342
+ messageRouter.setBindingLookup(new RepoBindingLookup({
2343
+ bindingRepo: storage.channelBindingRepo,
2344
+ instanceRepo: storage.platformInstanceRepo,
2345
+ orgDefaultAgent: (orgId) => {
2346
+ // Terminal level (design §6.1 level 5): the org Secretary, from the same
2347
+ // shared predicate the migration seeds the `global` binding with.
2348
+ const rows = (storage.agentRepo?.listByOrg?.(orgId) ?? []);
2349
+ return pickOrgSecretary(rows.map((r) => ({
2350
+ id: r.id,
2351
+ name: r.name,
2352
+ role: r.role_name,
2353
+ agentRole: r.agent_role,
2354
+ teamId: r.team_id ?? undefined,
2355
+ })))?.id;
2356
+ },
2357
+ }));
2358
+ }
2359
+ // ── Connection verification (Settings → Integrations "Save & test") ───────
2360
+ // The registry owns the *state* of a pending handshake; the router owns *when*
2361
+ // an inbound message is offered to it. The sender is the only thing the
2362
+ // registry cannot derive itself: it needs a live adapter, so it routes through
2363
+ // the same `sendToChannel` every other outbound message uses.
2364
+ const connectionTests = new ConnectionTestRegistry({
2365
+ sender: {
2366
+ async send(instanceId, channelId, text) {
2367
+ const bot = messageRouter.getInstances().find((b) => b.instanceId === instanceId);
2368
+ const platform = bot?.platform ?? instanceId;
2369
+ const messageId = await messageRouter.sendToChannel(platform, channelId, text, instanceId);
2370
+ // `undefined` is the router's "no adapter, or not connected" signal —
2371
+ // surfacing it as a throw is what keeps the outbound leg honest.
2372
+ if (messageId === undefined) {
2373
+ throw new Error(`bot instance "${instanceId}" is not connected`);
2374
+ }
2375
+ },
2376
+ },
2377
+ // Persist the durable half: the badge says "configured and verified" only
2378
+ // when this succeeded at least once. The promise is *returned* so the
2379
+ // registry can finish writing the fact before it publishes `verified` to
2380
+ // anyone who would then re-read the list; failures are swallowed here
2381
+ // (best-effort) and never surface as a failed verification.
2382
+ onVerified: ({ instanceId, at }) => {
2383
+ const instanceRepo = storage?.platformInstanceRepo;
2384
+ if (!instanceRepo)
2385
+ return;
2386
+ return recordInstanceVerification({ orgId: 'default', instances: instanceRepo }, instanceId, at).catch((error) => {
2387
+ startupLog('WARN', `could not record connection verification for ${instanceId}: ${String(error)}`);
2388
+ });
2389
+ },
2390
+ });
2391
+ messageRouter.setConnectionTestRegistry(connectionTests);
2392
+ // Live connection state + runtime reconfigure come from the gateway (slice G6):
2393
+ // the router's adapters are the single owner of "is this platform connected".
2394
+ //
2395
+ // The reconciler is the runtime half of the startup derivation above: saving a
2396
+ // bot in Settings now re-derives *that* bot (register + connect, or drop it)
2397
+ // instead of asking the user to restart the process.
2398
+ const instanceReconciler = createInstanceReconciler({
2399
+ router: messageRouter,
2400
+ manifests: PLATFORM_MANIFESTS,
2401
+ instanceRepo: storage?.platformInstanceRepo,
2402
+ orgId: 'default',
2403
+ sections: (config.integrations ?? {}),
2404
+ storedPlatformValues: (platformId) => {
2405
+ const manifest = getManifest(platformId);
2406
+ if (!manifest || !integrationRepo)
2407
+ return undefined;
2408
+ return readStoredPlatformConfig({ orgId: 'default', repo: integrationRepo }, manifest)?.values;
2409
+ },
2410
+ });
2411
+ apiServer.setPlatformRuntimeHooks({
2412
+ connected: (platform) => messageRouter.isPlatformConnected(platform),
2413
+ sync: (platform, platformConfig) => instanceReconciler.syncPlatform(platform, platformConfig),
2414
+ syncInstance: (instanceId) => instanceReconciler.syncInstance(instanceId),
2415
+ connectionTest: {
2416
+ begin: (instanceId, platform, target) => connectionTests.begin(instanceId, platform, target),
2417
+ get: (instanceId) => connectionTests.get(instanceId) ?? null,
2418
+ },
2419
+ });
2420
+ const connectedLabels = platformResults.filter((r) => r.connected).map((r) => r.label);
2421
+ const failedLabels = platformResults.filter((r) => !r.connected).map((r) => r.label);
2422
+ const gatewayDetail = connectedLabels.length > 0 ? `webhook adapters: ${connectedLabels.join(' + ')}` : 'webhook adapters: none';
2423
+ progress?.complete(5, failedLabels.length > 0 ? `${gatewayDetail} (${failedLabels.join(', ')} failed)` : gatewayDetail);
2424
+ // ── Outbound dispatch: notification/approval routing (G4, design §7) ───────
2425
+ // Every approval/notification goes through one dispatcher, resolved
2426
+ // `agent → instance(declared) → instance(agent) → global(Secretary)` and
2427
+ // rendered to whatever the target platform can show. This is what makes a
2428
+ // non-Feishu platform a first-class notification destination instead of a
2429
+ // silent dead end (defect D5).
2430
+ //
2431
+ // The destination is read from the DB — `platform_instances.config` plus
2432
+ // `channel_bindings` — the single source Settings writes. The legacy
2433
+ // `markus.json` `integrations.feishu.notifyChatId` read is gone (R2, design §3
2434
+ // "Single source of truth"), so the configured fact and the consumed fact are
2435
+ // the same fact.
2436
+ const outbound = setupOutboundDispatch({
2437
+ router: messageRouter,
2438
+ bindingRepo: storage?.channelBindingRepo,
2439
+ instanceRepo: storage?.platformInstanceRepo,
2440
+ orgSecretaryId: () => orgService.findOrgSecretary()?.id,
2441
+ notificationSource: hitlService,
2442
+ eventBus: agentManager.getEventBus(),
2443
+ orgId: 'default',
2444
+ digestInfo: false,
2445
+ actionSecret: resolveActionSecret(),
2446
+ // Resolve the origin agent's display name so a notification landing in a
2447
+ // shared group says which agent sent it. A lookup failure must never hold
2448
+ // back a delivery — an unknown agent simply goes out unattributed.
2449
+ agentName: (id) => {
2450
+ try {
2451
+ return agentManager.getAgent(id)?.config?.name;
2452
+ }
2453
+ catch {
2454
+ return undefined;
2455
+ }
2456
+ },
2457
+ // …and the team it belongs to, so the notification also says which team it
2458
+ // came from. Same rule: a missing team never holds back the delivery.
2459
+ agentTeamName: (id) => {
2460
+ try {
2461
+ const teamId = agentManager.getAgent(id)?.config?.teamId;
2462
+ return teamId ? orgService.getTeam(teamId)?.name : undefined;
2463
+ }
2464
+ catch {
2465
+ return undefined;
2466
+ }
2467
+ },
2468
+ // …and the language an approval's buttons are written in. The recipient's
2469
+ // own locale wins; the host locale is the fallback. Read lazily so a later
2470
+ // preference change is picked up without a restart.
2471
+ locale: () => {
2472
+ try {
2473
+ return orgService.resolveHumanIdentity(ownerUserId)?.locale ?? resolveHostLocale();
2474
+ }
2475
+ catch {
2476
+ return undefined;
2477
+ }
2478
+ },
2479
+ });
2480
+ if (outbound) {
2481
+ startupLog('OK', '出站通知分发已接线(三级路由:agent → instance → 全局)');
1846
2482
  }
1847
2483
  startupBlank();
1848
2484
  // ── Done — replace console.error spam with progress.finish() ────────────────