@mebular/mcp 0.3.5 → 0.3.7

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.
@@ -409,6 +409,76 @@ function traceProvenanceView(provenance) {
409
409
  };
410
410
  }
411
411
 
412
+ /**
413
+ * 介入决策只透出可解释的枚举/数值/短原因;不返回任何 prompt、正文或 token。
414
+ * 旧 trace 没有 decision → null,读取方按“无策略信息”展示。
415
+ */
416
+ function traceDecisionView(decision) {
417
+ if (!isObject(decision)) return null;
418
+ const action = ['speak', 'defer', 'silent'].includes(decision.action) ? decision.action : null;
419
+ if (!action) return null;
420
+ const depth = ['gist', 'detail', 'quote'].includes(decision.depth) ? decision.depth : null;
421
+ const view = {
422
+ action,
423
+ depth,
424
+ confidence: traceNumber(decision.confidence),
425
+ reason: traceText(decision.reason, 128),
426
+ policyVersion: traceText(decision.policyVersion, 64),
427
+ // 三态:旧 record / shadow 记录可能没有该字段,不把缺失伪造成“未执行”。
428
+ enforced: typeof decision.enforced === 'boolean' ? decision.enforced : null,
429
+ };
430
+ // 可选:部分 runtime 在 decision 上直接标记影子决策。
431
+ if (typeof decision.shadow === 'boolean') view.shadow = decision.shadow;
432
+ return view;
433
+ }
434
+
435
+ /**
436
+ * 只保留 id 型引用;即使未来写成对象数组,也不把正文/token 带到浏览器。
437
+ */
438
+ function traceIdList(value, max = 100) {
439
+ if (!Array.isArray(value)) return null;
440
+ return value.slice(0, max).map((entry) => {
441
+ if (typeof entry === 'string') return traceText(entry, 256);
442
+ if (isObject(entry)) return traceText(entry.fragmentId ?? entry.sourceId ?? entry.id, 256);
443
+ return null;
444
+ }).filter(Boolean);
445
+ }
446
+
447
+ function traceAppliedView(applied) {
448
+ if (!isObject(applied)) return null;
449
+ const action = ['speak', 'defer', 'silent'].includes(applied.action) ? applied.action : null;
450
+ if (!action) return null;
451
+ const depth = ['gist', 'detail', 'quote'].includes(applied.depth) ? applied.depth : null;
452
+ let fragments = null;
453
+ if (typeof applied.fragments === 'number' && Number.isFinite(applied.fragments)) {
454
+ fragments = Math.max(0, Math.trunc(applied.fragments));
455
+ } else if (Array.isArray(applied.fragments)) {
456
+ fragments = traceIdList(applied.fragments);
457
+ }
458
+ const view = { action, depth, fragments };
459
+ // 影子模式的反事实建议:仅枚举/短值,缺失时不输出键,便于上层区分 off baseline。
460
+ if (['speak', 'defer', 'silent'].includes(applied.wouldAction)) view.wouldAction = applied.wouldAction;
461
+ if (['gist', 'detail', 'quote'].includes(applied.wouldDepth)) view.wouldDepth = applied.wouldDepth;
462
+ // runtime 的 suppressed 可能是布尔,也可能是被抑制的 fragmentId 数组;
463
+ // 数组与 fragments 同样只保留 id,不携带正文。shadow 判定不使用该字段。
464
+ if (typeof applied.suppressed === 'boolean') view.suppressed = applied.suppressed;
465
+ else if (Array.isArray(applied.suppressed)) view.suppressed = traceIdList(applied.suppressed);
466
+ return view;
467
+ }
468
+
469
+ function traceOutcomeView(outcome) {
470
+ if (!isObject(outcome)) return null;
471
+ const kind = traceText(outcome.kind, 64);
472
+ if (!kind) return null;
473
+ return {
474
+ kind,
475
+ at: traceNumber(outcome.at),
476
+ source: traceText(outcome.source, 64),
477
+ confidence: traceNumber(outcome.confidence),
478
+ note: traceText(outcome.note, 200),
479
+ };
480
+ }
481
+
412
482
  function traceSummaryView(trace) {
413
483
  const feedback = trace?.feedback;
414
484
  return {
@@ -434,6 +504,9 @@ function traceSummaryView(trace) {
434
504
  injected: traceNumber(trace?.counts?.injected),
435
505
  tokens: traceNumber(trace?.counts?.tokens),
436
506
  },
507
+ decision: traceDecisionView(trace?.decision),
508
+ applied: traceAppliedView(trace?.applied),
509
+ outcome: traceOutcomeView(trace?.outcome),
437
510
  timing: { totalMs: traceNumber(trace?.timing?.totalMs) },
438
511
  model: {
439
512
  query: traceText(trace?.model?.query, 128),
@@ -485,6 +558,9 @@ function traceDetailView(trace) {
485
558
  owner: traceOwnerView(fragment?.owner),
486
559
  provenance: traceProvenanceView(fragment?.provenance),
487
560
  })) : [],
561
+ outcomeHistory: Array.isArray(trace?.outcomeHistory)
562
+ ? trace.outcomeHistory.slice(0, 5).map(traceOutcomeView).filter(Boolean)
563
+ : [],
488
564
  };
489
565
  }
490
566
 
@@ -550,6 +626,7 @@ export class MemoryRuntimeSupervisor {
550
626
 
551
627
  this.child = null;
552
628
  this.childToken = null;
629
+ this.adminToken = null;
553
630
  this.childSecrets = [];
554
631
  this.managedInstance = null;
555
632
  this.dormantLock = null;
@@ -1085,6 +1162,7 @@ export class MemoryRuntimeSupervisor {
1085
1162
  degraded: result.state === 'degraded',
1086
1163
  capability: null,
1087
1164
  model: null,
1165
+ intervention: null,
1088
1166
  };
1089
1167
  }
1090
1168
  const data = result.body?.data ?? result.body ?? {};
@@ -1124,6 +1202,23 @@ export class MemoryRuntimeSupervisor {
1124
1202
  }
1125
1203
  : null,
1126
1204
  model,
1205
+ // 0.4.0 effective intervention:sidecar 已经是唯一推导源,这里只做白名单。
1206
+ intervention: isObject(data.intervention)
1207
+ ? {
1208
+ mode: typeof data.intervention.mode === 'string' ? data.intervention.mode : null,
1209
+ planner: typeof data.intervention.planner === 'string' ? data.intervention.planner : null,
1210
+ source: typeof data.intervention.source === 'string' ? data.intervention.source : null,
1211
+ sourcePresent: data.intervention.sourcePresent === true,
1212
+ derivedMode: typeof data.intervention.derivedMode === 'string' ? data.intervention.derivedMode : null,
1213
+ legacyModePresent: data.intervention.legacyModePresent === true,
1214
+ legacyModeIgnored: data.intervention.legacyModeIgnored === true,
1215
+ legacyModeConflict: data.intervention.legacyModeConflict === true,
1216
+ diagnosticShadow: data.intervention.diagnosticShadow === true,
1217
+ warnings: Array.isArray(data.intervention.warnings)
1218
+ ? data.intervention.warnings.filter((warning) => typeof warning === 'string')
1219
+ : [],
1220
+ }
1221
+ : null,
1127
1222
  };
1128
1223
  }
1129
1224
 
@@ -1439,6 +1534,128 @@ export class MemoryRuntimeSupervisor {
1439
1534
  return { statusCode: 200, body: result.body ?? { ok: true, data } };
1440
1535
  }
1441
1536
 
1537
+ /**
1538
+ * Console 侧 outcome 归因(sidecar `POST /recall/:traceId/outcome`)。
1539
+ *
1540
+ * 只允许 MCP admin 代理:请求必须由 MCP admin 写端点进入,并在此附加
1541
+ * supervisor 持有的独立 admin secret;host token 不能冒充 console。
1542
+ * 不接受 note/raw/bindingToken,source 固定为 console。
1543
+ */
1544
+ async submitRecallOutcome(traceId, outcome) {
1545
+ const id = typeof traceId === 'string' ? traceId.trim() : '';
1546
+ if (!/^tr_[A-Za-z0-9._:-]{1,128}$/.test(id)) {
1547
+ return { statusCode: 400, body: { ok: false, error: 'invalid_trace_id', message: 'trace id 格式非法' } };
1548
+ }
1549
+ if (!isObject(outcome)) {
1550
+ return { statusCode: 400, body: { ok: false, error: 'invalid_outcome', message: 'outcome 必须是对象' } };
1551
+ }
1552
+ const kinds = new Set([
1553
+ 'accepted', 'ignored', 'reasked', 'corrected',
1554
+ 'dismissed', 'missed', 'too_shallow', 'too_deep',
1555
+ ]);
1556
+ const kind = typeof outcome.kind === 'string' ? outcome.kind : '';
1557
+ if (!kinds.has(kind)) {
1558
+ return { statusCode: 400, body: { ok: false, error: 'invalid_outcome', message: 'outcome.kind 非法' } };
1559
+ }
1560
+ const body = { kind, source: 'console' };
1561
+ if (outcome.confidence !== undefined && outcome.confidence !== null) {
1562
+ if (typeof outcome.confidence !== 'number' || !Number.isFinite(outcome.confidence)
1563
+ || outcome.confidence < 0 || outcome.confidence > 1) {
1564
+ return { statusCode: 400, body: { ok: false, error: 'invalid_outcome', message: 'outcome.confidence 必须是 0..1 的数字' } };
1565
+ }
1566
+ body.confidence = outcome.confidence;
1567
+ }
1568
+ // 独立 admin secret 只在 supervisor 启动 managed child 时存在;
1569
+ // attached/external sidecar 或旧 MCP 没有它时明确 fail closed。
1570
+ if (typeof this.adminToken !== 'string' || this.adminToken.length === 0) {
1571
+ return {
1572
+ statusCode: 409,
1573
+ body: {
1574
+ ok: false,
1575
+ error: 'admin_channel_unavailable',
1576
+ message: 'console outcome 通道未启用',
1577
+ },
1578
+ };
1579
+ }
1580
+ const result = await this.#proxyHostApi(`recall/${encodeURIComponent(id)}/outcome`, {
1581
+ method: 'POST',
1582
+ body,
1583
+ admin: true,
1584
+ });
1585
+ if (!result.available) {
1586
+ return {
1587
+ statusCode: result.disabled === true ? 409 : 503,
1588
+ body: {
1589
+ ok: false,
1590
+ error: result.disabled === true ? 'memory_runtime_disabled' : 'sidecar_unavailable',
1591
+ enabled: result.enabled,
1592
+ state: result.state,
1593
+ message: result.disabled === true
1594
+ ? '记忆运行时未启用'
1595
+ : 'Memory Runtime sidecar 未就绪',
1596
+ ...(result.error ? { details: result.error } : {}),
1597
+ },
1598
+ };
1599
+ }
1600
+ const data = result.body?.data ?? result.body ?? null;
1601
+ if (!result.ok) {
1602
+ return {
1603
+ statusCode: result.statusCode ?? 502,
1604
+ body: {
1605
+ ok: false,
1606
+ error: data?.error?.code ?? result.body?.error?.code ?? 'outcome_failed',
1607
+ message: proxyErrorMessage(data, proxyErrorMessage(result.body, '召回结果上报失败')),
1608
+ },
1609
+ };
1610
+ }
1611
+ return { statusCode: 200, body: result.body ?? { ok: true, data } };
1612
+ }
1613
+
1614
+ /**
1615
+ * 重置本机介入策略状态(sidecar `POST /intervention/reset`)。
1616
+ *
1617
+ * 与 feedback 共用 host token 代理;轻量模式/未就绪返回明确 disabled/503,
1618
+ * sidecar 报错或 `ok:false` 原样失败,不伪造成功。
1619
+ */
1620
+ async resetInterventionPolicy() {
1621
+ const result = await this.#proxyHostApi('intervention/reset', {
1622
+ method: 'POST',
1623
+ body: {},
1624
+ timeoutMs: 5000,
1625
+ });
1626
+ if (!result.available) {
1627
+ return {
1628
+ statusCode: result.disabled === true ? 409 : 503,
1629
+ body: {
1630
+ ok: false,
1631
+ error: result.disabled === true ? 'memory_runtime_disabled' : 'sidecar_unavailable',
1632
+ enabled: result.enabled,
1633
+ state: result.state,
1634
+ message: result.disabled === true
1635
+ ? '记忆运行时未启用'
1636
+ : 'Memory Runtime sidecar 未就绪',
1637
+ ...(result.error ? { details: result.error } : {}),
1638
+ },
1639
+ };
1640
+ }
1641
+ const envelope = isObject(result.body) ? result.body : {};
1642
+ const data = envelope.data ?? result.body ?? null;
1643
+ if (!result.ok || envelope.ok === false) {
1644
+ return {
1645
+ statusCode: result.ok ? 502 : (result.statusCode ?? 502),
1646
+ body: {
1647
+ ok: false,
1648
+ error: data?.error?.code ?? envelope.error?.code ?? 'policy_reset_failed',
1649
+ message: proxyErrorMessage(data, proxyErrorMessage(envelope, '介入策略重置失败')),
1650
+ },
1651
+ };
1652
+ }
1653
+ return {
1654
+ statusCode: 200,
1655
+ body: envelope.ok === undefined ? { ok: true, data } : envelope,
1656
+ };
1657
+ }
1658
+
1442
1659
  async #resolveHostToken(discovery) {
1443
1660
  const fromEnv = stringOrNull(this.env?.MEBULAR_MEMORY_RUNTIME_TOKEN);
1444
1661
  if (fromEnv) return { token: fromEnv, source: 'override', refreshable: false };
@@ -1557,7 +1774,12 @@ export class MemoryRuntimeSupervisor {
1557
1774
  return sameDiscoveryInstance(await readDiscovery(this.paths.discoveryPath), discovery);
1558
1775
  }
1559
1776
 
1560
- async #proxyHostApi(pathname, { method = 'GET', body = null, timeoutMs = 2500 } = {}) {
1777
+ async #proxyHostApi(pathname, {
1778
+ method = 'GET',
1779
+ body = null,
1780
+ timeoutMs = 2500,
1781
+ admin = false,
1782
+ } = {}) {
1561
1783
  await this.status().catch(() => undefined);
1562
1784
  if (!this.isEnabled()) {
1563
1785
  return {
@@ -1620,6 +1842,11 @@ export class MemoryRuntimeSupervisor {
1620
1842
  accept: 'application/json',
1621
1843
  authorization: `Bearer ${token}`,
1622
1844
  'x-request-id': requestId,
1845
+ // W4 B1:console outcome 只在 MCP 进程内附加独立 admin secret;
1846
+ // feedback/reset 等普通代理不发送该 header。
1847
+ ...(admin && typeof this.adminToken === 'string' && this.adminToken.length > 0
1848
+ ? { 'x-mebular-admin-token': this.adminToken }
1849
+ : {}),
1623
1850
  };
1624
1851
  const init = { method, headers, signal: controller.signal };
1625
1852
  if (body !== null && body !== undefined) {
@@ -1951,7 +2178,11 @@ export class MemoryRuntimeSupervisor {
1951
2178
 
1952
2179
  const hostToken = stringOrNull(this.env?.MEBULAR_MEMORY_RUNTIME_TOKEN)
1953
2180
  ?? randomBytes(32).toString('base64url');
1954
- this.childSecrets = [token, hostToken];
2181
+ // W4:独立 admin secret 只注入 sidecar child;宿主 adapter 不持有,
2182
+ // discovery/日志/状态都不暴露。console outcome 只走这个通道。
2183
+ const adminToken = randomBytes(32).toString('base64url');
2184
+ this.adminToken = adminToken;
2185
+ this.childSecrets = [token, hostToken, adminToken];
1955
2186
  const spec = commandSpec(resolved.command);
1956
2187
  const args = [
1957
2188
  ...spec.args,
@@ -1965,6 +2196,7 @@ export class MemoryRuntimeSupervisor {
1965
2196
  MEBULAR_MEMORY_RUNTIME_HOME: this.paths.dataDir,
1966
2197
  MEBULAR_CAPABILITY_TOKEN: token,
1967
2198
  MEBULAR_MEMORY_RUNTIME_TOKEN: hostToken,
2199
+ MEBULAR_MEMORY_RUNTIME_ADMIN_TOKEN: adminToken,
1968
2200
  ...(stringOrNull(this.getMcpUrl()) ? { MEBULAR_MCP_URL: stringOrNull(this.getMcpUrl()) } : {}),
1969
2201
  };
1970
2202
 
package/src/provision.mjs CHANGED
@@ -180,7 +180,14 @@ export function normalizeExplicitDeviceId(value) {
180
180
  return /^device-+/i.test(raw) ? deriveDeviceId(raw) : (sanitize(raw) || null);
181
181
  }
182
182
 
183
- export function provisionStatus({ home, mcpPort, phase = 'UNINITIALIZED', provisioned = false } = {}) {
183
+ export function provisionStatus({
184
+ home,
185
+ mcpPort,
186
+ phase = 'UNINITIALIZED',
187
+ provisioned = false,
188
+ firstRun = null,
189
+ firstRunWarning = null,
190
+ } = {}) {
184
191
  const name = defaultDeviceName();
185
192
  const base = {
186
193
  ok: true,
@@ -195,6 +202,9 @@ export function provisionStatus({ home, mcpPort, phase = 'UNINITIALIZED', provis
195
202
  // 兼容旧控制台字段:P1 起初始化不再需要重启。
196
203
  restartRequired: false,
197
204
  restarting: false,
205
+ // 0.4.0 W1b:全新空 home 的一次性首启披露状态;已有用户/完成后为 null。
206
+ ...(firstRun ? { firstRun } : {}),
207
+ ...(firstRunWarning ? { firstRunWarning } : {}),
198
208
  };
199
209
  if (phase === 'INITIALIZING') {
200
210
  return {
package/src/serve.mjs CHANGED
@@ -35,6 +35,7 @@ import {
35
35
  normalizeMemoryRuntimeModelSource,
36
36
  readMemoryRuntimeModelSource,
37
37
  } from './memory-runtime-config.mjs';
38
+ import { resolveMemoryRuntimeEffectiveMode } from './memory-runtime-effective.mjs';
38
39
  import { APP_VERSION } from './version.mjs';
39
40
  import { acquireConfigFileLock } from './config-lock.mjs';
40
41
  import { resolveStaticAssetRoots } from './asset-roots.mjs';
@@ -57,6 +58,13 @@ import {
57
58
  snapshotProvisionState,
58
59
  writeProvisionRecord,
59
60
  } from './provision.mjs';
61
+ import {
62
+ FIRST_RUN_INIT_FAILED,
63
+ firstRunPublicView,
64
+ initializeFirstRunHome,
65
+ markFirstRunAcked,
66
+ readFirstRunMarker,
67
+ } from './first-run.mjs';
60
68
  import {
61
69
  acquireActiveLock,
62
70
  cloudError,
@@ -261,6 +269,7 @@ const CONSOLE_FILES = {
261
269
  'console.js': 'text/javascript; charset=utf-8',
262
270
  'host.js': 'text/javascript; charset=utf-8',
263
271
  'dropdown.mjs': 'text/javascript; charset=utf-8',
272
+ 'first-run-disclosure.js': 'text/javascript; charset=utf-8',
264
273
  'assistants.js': 'text/javascript; charset=utf-8',
265
274
  'assistant-status.js': 'text/javascript; charset=utf-8',
266
275
  'deep-link.js': 'text/javascript; charset=utf-8',
@@ -908,6 +917,8 @@ export async function startHttpServer({
908
917
  afterConfigRename = null,
909
918
  // 引导态(空家目录):只服务 /healthz + /console 引导页 + /app/provision/*;其余 409 provision_required
910
919
  provision: initialProvision = false,
920
+ // 0.4.0 W1b:首启初始化失败时给控制台的稳定 warning(不阻塞 READY)。
921
+ firstRunWarning = null,
911
922
  // P1:同一进程内热初始化。返回新的运行时上下文;成功后本 server 从 UNINITIALIZED → READY。
912
923
  initializeRuntime = null,
913
924
  // 关闭钩子:热初始化后由 server.mjs 关闭 app / join / 广播计时器(HTTP server 本身由本函数关闭)
@@ -1952,6 +1963,28 @@ export async function startHttpServer({
1952
1963
  const detail = memoryRuntimeSupervisor
1953
1964
  ? await memoryRuntimeSupervisor.readStatus().catch(() => null)
1954
1965
  : null;
1966
+ // sidecar 可用时以 sidecar 的 effective 为准;轻量/未就绪时用同一张表纯推导。
1967
+ const fallbackSource = detail?.intervention
1968
+ ? null
1969
+ : await readMemoryRuntimeModelSource({ home }).catch(() => null);
1970
+ const effective = resolveMemoryRuntimeEffectiveMode({
1971
+ config,
1972
+ modelSource: detail?.model?.configured ?? fallbackSource?.source,
1973
+ sourcePresent: fallbackSource?.sourcePresent
1974
+ ?? (detail?.model?.configured !== undefined && detail?.model?.configured !== null),
1975
+ });
1976
+ const intervention = detail?.intervention ?? {
1977
+ mode: effective.effective,
1978
+ planner: effective.planner,
1979
+ source: effective.source,
1980
+ sourcePresent: effective.sourcePresent,
1981
+ derivedMode: effective.derivedMode,
1982
+ legacyModePresent: effective.legacyModePresent,
1983
+ legacyModeIgnored: effective.legacyModeIgnored,
1984
+ legacyModeConflict: effective.legacyModeConflict,
1985
+ diagnosticShadow: effective.diagnosticShadow,
1986
+ warnings: effective.warnings,
1987
+ };
1955
1988
  // 进程、capability 与模型是独立观察;不得用进程存活伪造 capability ready。
1956
1989
  return sendJson(res, 200, {
1957
1990
  ...status,
@@ -1961,6 +1994,7 @@ export async function startHttpServer({
1961
1994
  capability: detail?.capability ?? null,
1962
1995
  capabilityError: detail?.error ?? null,
1963
1996
  model: detail?.model ?? null,
1997
+ intervention,
1964
1998
  });
1965
1999
  }
1966
2000
  if (path === '/admin/api/memory-runtime/model-source') {
@@ -2188,6 +2222,7 @@ export async function startHttpServer({
2188
2222
  /^\/admin\/api\/namespaces\/([^/]+)\/(rejoin|leave)$/,
2189
2223
  /^\/admin\/api\/service\/(install|uninstall)$/,
2190
2224
  /^\/admin\/api\/repair$/,
2225
+ /^\/admin\/api\/adapters\/repair$/,
2191
2226
  /^\/admin\/api\/clients\/([^/]+)\/(connect|rollback|skills|preview|verify|recheck)$/,
2192
2227
  /^\/admin\/api\/assistants$/,
2193
2228
  /^\/admin\/api\/assistants\/([^/]+)$/,
@@ -2196,6 +2231,10 @@ export async function startHttpServer({
2196
2231
  /^\/admin\/api\/(?:models|inference)\/(install|select|download|pause|resume|cancel|import|uninstall|remove|start|stop|test)$/,
2197
2232
  // 0.3 记忆运行时:召回反馈经 MCP 薄代理转发 sidecar;host token 不出服务端。
2198
2233
  /^\/admin\/api\/memory-runtime\/feedback$/,
2234
+ // 0.4 W4:console outcome 经 MCP admin 代理;独立 admin secret 不出服务端。
2235
+ /^\/admin\/api\/memory-runtime\/outcome$/,
2236
+ // 0.4 记忆介入策略:重置本机策略状态;同样经薄代理,sidecar 未启用时明确失败。
2237
+ /^\/admin\/api\/memory-runtime\/policy\/reset$/,
2199
2238
  // 0.3 高级模型来源:经 sidecar `/inference/settings` 或 `/models/:pack/activate`。
2200
2239
  /^\/admin\/api\/memory-runtime\/model-source$/,
2201
2240
  ];
@@ -2731,6 +2770,29 @@ export async function startHttpServer({
2731
2770
  }
2732
2771
  }
2733
2772
 
2773
+ // 内部:App 启动/升级后修复 connected=true 宿主的 Adapter(无 UI)。
2774
+ // 同一 memory.admin + CSRF 门;只报告稳定 code,不回显路径/正文。
2775
+ async function handleAdapterRepair(req, res) {
2776
+ const { listAssistantsAsync, assistantUserHome, daemonMcpUrl } = await import('./clients.mjs');
2777
+ const { ensureAdaptersForConnected } = await import('./adapter-provision.mjs');
2778
+ const mcpUrl = daemonMcpUrl({ host: req.headers?.host, encrypted: Boolean(req.socket?.encrypted) });
2779
+ try {
2780
+ const userHome = assistantUserHome();
2781
+ const list = await listAssistantsAsync({ home, cwd: process.cwd(), userHome, refresh: true, ttlMs: 0, mcpUrl });
2782
+ const connectedHostIds = list.assistants.filter((assistant) => assistant.connected === true).map((assistant) => assistant.id);
2783
+ const result = await ensureAdaptersForConnected({
2784
+ home,
2785
+ cwd: process.cwd(),
2786
+ userHome,
2787
+ connectedHostIds,
2788
+ resourcesPath: process.resourcesPath,
2789
+ });
2790
+ return sendJson(res, 200, result);
2791
+ } catch {
2792
+ return sendJson(res, 500, { ok: false, scope: 'adapter-provisioning', error: 'adapter_repair_failed' });
2793
+ }
2794
+ }
2795
+
2734
2796
  // D2 写端点实现(memory.admin scope + CSRF 已在 handleAdminWrite 校验)
2735
2797
  async function applyAdminWrite(req, res, path, body) {
2736
2798
  if (!app || !service) {
@@ -2748,6 +2810,8 @@ export async function startHttpServer({
2748
2810
 
2749
2811
  // 自动修复:客户端接入修复,**不**经 securityWriteGate(不写记忆/安全状态)。
2750
2812
  if (path === '/admin/api/repair') return handleRepair(req, res);
2813
+ // 内部:App 启动/升级后的 Adapter 修复(仍是 memory.admin + CSRF;无 UI)。
2814
+ if (path === '/admin/api/adapters/repair') return handleAdapterRepair(req, res);
2751
2815
 
2752
2816
  // 0.3 高级模型来源:sidecar 拥有 config.model.source;MCP 只做薄代理。
2753
2817
  // local 必须带 pack 并通过 sidecar activate;不直接写 config.json、不重启 sidecar。
@@ -2782,6 +2846,49 @@ export async function startHttpServer({
2782
2846
  return sendJson(res, result.statusCode, result.body);
2783
2847
  }
2784
2848
 
2849
+ // 0.4 W4 console outcome:同 feedback 的鉴权/CSRF;MCP 只附加独立 admin
2850
+ // secret,host token 不能冒充 console,note/raw 不接受。
2851
+ if (path === '/admin/api/memory-runtime/outcome') {
2852
+ const input = parseJsonBody(body);
2853
+ if (!input) {
2854
+ return sendJson(res, 400, { ok: false, error: 'bad_request', message: '需要 JSON 请求体' });
2855
+ }
2856
+ const traceId = typeof input.traceId === 'string' ? input.traceId : '';
2857
+ const result = memoryRuntimeSupervisor
2858
+ ? await memoryRuntimeSupervisor.submitRecallOutcome(traceId, {
2859
+ kind: input.kind,
2860
+ ...(input.confidence !== undefined ? { confidence: input.confidence } : {}),
2861
+ })
2862
+ : {
2863
+ statusCode: 409,
2864
+ body: {
2865
+ ok: false,
2866
+ error: 'memory_runtime_disabled',
2867
+ enabled: false,
2868
+ state: 'stopped',
2869
+ message: '记忆运行时未启用',
2870
+ },
2871
+ };
2872
+ return sendJson(res, result.statusCode, result.body);
2873
+ }
2874
+
2875
+ // 0.4 记忆介入策略重置:同 feedback 的鉴权/CSRF/writes-enabled;sidecar 未启用返回 409。
2876
+ if (path === '/admin/api/memory-runtime/policy/reset') {
2877
+ const result = memoryRuntimeSupervisor
2878
+ ? await memoryRuntimeSupervisor.resetInterventionPolicy()
2879
+ : {
2880
+ statusCode: 409,
2881
+ body: {
2882
+ ok: false,
2883
+ error: 'memory_runtime_disabled',
2884
+ enabled: false,
2885
+ state: 'stopped',
2886
+ message: '记忆运行时未启用',
2887
+ },
2888
+ };
2889
+ return sendJson(res, result.statusCode, result.body);
2890
+ }
2891
+
2785
2892
  // 0.3 本地模型:只代理 sidecar;不经 securityWriteGate(不写记忆/安全状态)。
2786
2893
  const modelAction = path.match(/^\/admin\/api\/(?:models|inference)\/([^/]+)$/);
2787
2894
  if (modelAction) {
@@ -4244,11 +4351,14 @@ export async function startHttpServer({
4244
4351
  if (done !== false) return done;
4245
4352
  }
4246
4353
  if (path === '/app/provision/status' && req.method === 'GET') {
4354
+ const firstRunMarker = await readFirstRunMarker({ home }).catch(() => null);
4247
4355
  return sendJson(res, 200, provisionStatus({
4248
4356
  home,
4249
4357
  mcpPort: boundPort,
4250
4358
  phase,
4251
4359
  provisioned: !isProvisionHome(home),
4360
+ firstRun: firstRunPublicView(firstRunMarker),
4361
+ firstRunWarning,
4252
4362
  }));
4253
4363
  }
4254
4364
  if (path === '/app/provision/create' || path === '/app/provision/join' || path === '/app/provision/restore') {
@@ -4363,11 +4473,63 @@ export async function startHttpServer({
4363
4473
  }
4364
4474
  })
4365
4475
  .catch((error) => console.error(`CLIENT_ENDPOINT_RECONCILE_FAILED ${error?.code ?? 'ERROR'}`));
4476
+ // 0.4.0 W1b:先确保 provision/应用本身成功,再 ack 披露并初始化 immersive。
4477
+ // 披露成功(Console 显式回传且版本匹配)才写 enabled=true;未回传 / 版本不符 →
4478
+ // marker 保持 pending,不写 enabled=true(fail closed);应用初始化失败时不会 ack。
4479
+ let firstRun = null;
4480
+ if (input.firstRunDisclosure === true) {
4481
+ // 披露版本必须由 Console 显式回传且为整数;缺失/非法一律拒绝 ack。
4482
+ if (!Number.isInteger(input.firstRunDisclosureVersion)) {
4483
+ firstRun = { acknowledged: false };
4484
+ } else {
4485
+ try {
4486
+ const acked = await markFirstRunAcked({
4487
+ home,
4488
+ disclosureVersion: input.firstRunDisclosureVersion,
4489
+ });
4490
+ if (acked) {
4491
+ const initialized = await initializeFirstRunHome({ home, env: process.env });
4492
+ firstRun = {
4493
+ acknowledged: true,
4494
+ initialized: initialized.ok === true && initialized.initialized === true,
4495
+ ...(initialized.ok === true ? {} : { warning: FIRST_RUN_INIT_FAILED }),
4496
+ };
4497
+ if (initialized.ok !== true) {
4498
+ console.error(`FIRST_RUN_INIT_FAILED ${initialized.reason ?? 'unknown'}`);
4499
+ }
4500
+ if (initialized.ok === true && initialized.enabled === true) {
4501
+ // 同步路由可见的配置快照,让 supervisor/capability 看到 enabled=true。
4502
+ config = {
4503
+ ...config,
4504
+ memoryRuntime: { ...(config.memoryRuntime ?? {}), enabled: true },
4505
+ };
4506
+ }
4507
+ } else {
4508
+ firstRun = { acknowledged: false };
4509
+ }
4510
+ } catch (error) {
4511
+ console.error(`FIRST_RUN_INIT_FAILED ${error?.code ?? 'ERROR'}`);
4512
+ firstRun = { acknowledged: false, warning: FIRST_RUN_INIT_FAILED };
4513
+ }
4514
+ }
4515
+ }
4516
+ // 同进程首次启用:准备 capability token 并启动 sidecar(与设置页开启走同一生命周期)。
4517
+ if (firstRun?.initialized === true && isMemoryRuntimeEnabled(config)) {
4518
+ void enqueueMemoryRuntimeLifecycle(async () => {
4519
+ await memoryCapability.prepare().catch(() => undefined);
4520
+ if (memoryRuntimeSupervisor && isMemoryRuntimeEnabled(config)) {
4521
+ await memoryRuntimeSupervisor.start().catch((error) => {
4522
+ console.error(`MEMORY_RUNTIME_START_FAILED ${error?.code ?? 'ERROR'}`);
4523
+ });
4524
+ }
4525
+ }).catch((error) => console.error(`MEMORY_RUNTIME_START_FAILED ${error?.code ?? 'ERROR'}`));
4526
+ }
4366
4527
  return sendJson(res, 200, {
4367
4528
  ok: true,
4368
4529
  ...result,
4369
4530
  initialized: true,
4370
4531
  phase: 'READY',
4532
+ ...(firstRun ? { firstRun } : {}),
4371
4533
  });
4372
4534
  } catch (error) {
4373
4535
  // 回滚本次新建的落盘产物;home 锁仍由当前进程持有(不释放/不重抢)。
package/src/server.mjs CHANGED
@@ -15,6 +15,13 @@ import { createJoinServer } from './jointoken.mjs';
15
15
  import { clearApplyPending, readApplyPending, recoverPendingRollback, writeApplyResult, writeServeReady } from './config-apply.mjs';
16
16
  import { buildSettings } from './admin.mjs';
17
17
  import { isProvisionHome } from './provision.mjs';
18
+ import {
19
+ detectFreshHome,
20
+ FIRST_RUN_INIT_FAILED,
21
+ initializeFirstRunHome,
22
+ markFirstRunPending,
23
+ readFirstRunMarker,
24
+ } from './first-run.mjs';
18
25
  import { acquireActiveLock, profileIdForHome, resolveCloudRoot } from './profiles.mjs';
19
26
  import { advertiseHost, endpointHostname, isLoopbackHost } from './lan-host.mjs';
20
27
 
@@ -147,6 +154,16 @@ export async function startServeServer(options = {}) {
147
154
  // F-NET-1(C):**先取单实例锁,再初始化网络**——第二写者应在绑定监听端口前就得到
148
155
  // 可读的 MCP_STORAGE_LOCKED(此前 createMebular 先启网络 → 抢 4001 → 裸 EADDRINUSE)。
149
156
  let preConfig = provisionStart ? {} : await loadConfigFile(home).catch(() => ({}));
157
+ // 0.4.0 W1b:空 home 判定必须在取 `<home>/lock` 之前——锁文件本身会让目录看起来“非空”。
158
+ // 只写 pending marker,绝不启用;已有 home 不命中。
159
+ let firstRunWarning = null;
160
+ try {
161
+ if (await detectFreshHome({ home, env: process.env })) {
162
+ await markFirstRunPending({ home, env: process.env });
163
+ }
164
+ } catch (error) {
165
+ console.error(`FIRST_RUN_MARKER_FAILED ${error?.code ?? 'ERROR'}`);
166
+ }
150
167
  const { storagePathForHome } = await import('./home-identity.mjs');
151
168
  const preStoragePath = storagePathForHome(home, preConfig, process.env);
152
169
  const lock = await acquireLock(home, preStoragePath);
@@ -164,6 +181,24 @@ export async function startServeServer(options = {}) {
164
181
  provisionStart = isProvisionHome(home, { storagePath: process.env.MEBULAR_STORAGE_PATH });
165
182
  preConfig = provisionStart ? {} : await loadConfigFile(home).catch(() => ({}));
166
183
 
184
+ // 0.4.0 W1b:acked 的首启初始化在正常启动前重试;任一步失败只记录 warning,
185
+ // 不阻塞 serve,也不把失败当成 heuristic 默认启用。
186
+ if (!provisionStart) {
187
+ try {
188
+ const marker = await readFirstRunMarker({ home });
189
+ if (marker?.state === 'acked') {
190
+ const initialized = await initializeFirstRunHome({ home, env: process.env });
191
+ if (initialized.ok !== true) {
192
+ firstRunWarning = FIRST_RUN_INIT_FAILED;
193
+ console.error(`FIRST_RUN_INIT_FAILED ${initialized.reason ?? 'unknown'}`);
194
+ }
195
+ }
196
+ } catch (error) {
197
+ firstRunWarning = FIRST_RUN_INIT_FAILED;
198
+ console.error(`FIRST_RUN_INIT_FAILED ${error?.code ?? 'ERROR'}`);
199
+ }
200
+ }
201
+
167
202
  // 热初始化 / 正常启动共用:app、join 服务、运行时快照与生命周期资源。
168
203
  let current = null;
169
204
  let httpServer = null;
@@ -391,6 +426,7 @@ export async function startServeServer(options = {}) {
391
426
  writesEnabled: options.writesEnabled ?? process.env.MEBULAR_CONSOLE_WRITES !== '0',
392
427
  manageMemoryRuntime: true,
393
428
  provision: provisionStart,
429
+ firstRunWarning,
394
430
  initializeRuntime: async ({ action, result, server }) => {
395
431
  const next = await startRuntime({ action, result, serverContext: server, hot: true });
396
432
  current = next;
package/src/version.mjs CHANGED
@@ -5,4 +5,4 @@
5
5
  // scripts/bump-version.mjs 只改这一处,scripts/verify-release-version.mjs
6
6
  // 校验它等于发布版本;不要在其它文件再写版本字面量。
7
7
 
8
- export const APP_VERSION = '0.3.5';
8
+ export const APP_VERSION = '0.3.7';