dsh-miloco-bridge 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/push.js CHANGED
@@ -5,17 +5,19 @@
5
5
  * evaluates rules and expires tasks, then asks an Agent to react. This module
6
6
  * is the receiving end of that loop.
7
7
  *
8
- * Delivery target rules (exactly the owner's semantics):
8
+ * Delivery target rules:
9
9
  *
10
- * 1. `target.sessionId` configured (runtime overlay, then static config)
11
- * -> deliver to that conversation.
12
- * 2. Nothing configured -> deliver to **the session that last touched a
13
- * Miloco tool** (state file). If there is none, derive a stable session id
14
- * from Miloco's `sessionKey`.
15
- * 3. Model not configured -> do not touch the session's model at all; it keeps
16
- * following whatever model that conversation already selected.
17
- * 4. Model configured (provider + model) -> select that model for the target
18
- * session before prompting.
10
+ * 1. `target.mode = 'archive'` (the default) -> the dedicated archive session
11
+ * `miloco-archive`, created lazily with the household cwd and preset.
12
+ * 2. `target.mode = 'session'` -> `target.sessionId` (overlay, then config);
13
+ * empty falls back to the session that last touched a Miloco tool, then to
14
+ * an id derived from Miloco's `sessionKey`.
15
+ * 3. Model not configured -> do not touch the session's model.
16
+ * 4. Model configured -> select it before prompting.
17
+ *
18
+ * Every delivery that resolved a target is recorded in the shared push log
19
+ * (`{at, title, summary, sessionId, status, runId}`); a target-resolution
20
+ * failure is not recorded.
19
21
  *
20
22
  * The inbound route authenticates with a bearer token. The effective token is
21
23
  * `overlay.push.token` or `push.token` from static config; when both are empty
@@ -25,18 +27,57 @@
25
27
  */
26
28
 
27
29
  import { randomUUID } from 'node:crypto'
30
+ import { normalizePushTargetMode } from './overlay.js'
28
31
  import {
29
32
  normalizePerceptionLevel,
30
33
  parseUrgency,
31
34
  perceptionAllowed,
32
35
  } from './perception.js'
36
+ import { notePush } from './state.js'
33
37
 
34
38
  /** Default inbound route path. */
35
39
  export const DEFAULT_PUSH_PATH = '/miloco/webhook'
36
40
 
41
+ /** Source kind of a folded Miloco push inside a conversation. */
42
+ export const PUSH_SOURCE_KIND = 'miloco-push'
43
+
44
+ /** The dedicated session inbound pushes land in by default. */
45
+ export const ARCHIVE_SESSION_ID = 'miloco-archive'
46
+
47
+ /** Title of the dedicated archive session. */
48
+ export const ARCHIVE_SESSION_TITLE = 'Miloco 推送归档'
49
+
50
+ /** Maximum length of the one-line summary shown in the folded card. */
51
+ const SUMMARY_MAX_CHARS = 120
52
+
53
+ /** Leading Miloco cron tag: `[cron:<task name>]`. */
54
+ const CRON_TAG = /^\[cron:([^\]]+)\]\s*/i
55
+
37
56
  /** How long a delivered idempotency key / run id is remembered. */
38
57
  const RESULT_TTL_MS = 10 * 60_000
39
58
 
59
+ /**
60
+ * Build the one-line title shown while a push stays folded.
61
+ *
62
+ * A cron push is titled `任务推送-<task name>`; every other push is
63
+ * `事件推送-<title or first body line>`. The cron tag itself is stripped.
64
+ *
65
+ * @param {any} payload - The inbound payload.
66
+ * @param {string} message - The push body.
67
+ * @returns {string} A title of at most 120 characters.
68
+ */
69
+ export function pushDisplayTitle(payload, message) {
70
+ const title = String(payload?.title ?? '').trim()
71
+ const first = String(message ?? '').split('\n').map(line => line.trim()).find(Boolean) ?? ''
72
+ const candidates = [title, first].filter(Boolean)
73
+ const cronSource = candidates.find(text => CRON_TAG.test(text))
74
+ const match = cronSource ? CRON_TAG.exec(cronSource) : null
75
+ const source = cronSource ?? candidates[0] ?? ''
76
+ const name = (match ? match[1] : source).trim() || 'Miloco 推送'
77
+ const text = `${match ? '任务推送' : '事件推送'}-${name}`
78
+ return text.length > SUMMARY_MAX_CHARS ? `${text.slice(0, SUMMARY_MAX_CHARS - 1)}…` : text
79
+ }
80
+
40
81
  /**
41
82
  * Derive a stable DSH session id from a Miloco session key.
42
83
  *
@@ -123,7 +164,7 @@ function bearerOf(req) {
123
164
  /**
124
165
  * Create the push delivery service.
125
166
  *
126
- * @param {{ctx: any, config: any, logger?: any, overlay?: any, activity?: any, agentPreset?: string}} options - Service options.
167
+ * @param {{ctx: any, config: any, logger?: any, overlay?: any, state?: any, activity?: any, agentPreset?: string, home?: any}} options - Service options.
127
168
  * @returns {{register: () => void, deliver: (payload: any, signal?: AbortSignal) => Promise<any>, dispose: () => void, path: string}} The service.
128
169
  */
129
170
  export function createPushService(options) {
@@ -134,7 +175,29 @@ export function createPushService(options) {
134
175
  const staticToken = String(pushConfig.token ?? '')
135
176
  const target = pushConfig.target ?? {}
136
177
  const modelConfig = pushConfig.model ?? {}
137
- const cwd = pushConfig.cwd || config.cwd || ctx.sandboxPolicy?.workspaceRoot || process.cwd()
178
+
179
+ /**
180
+ * Directory a push-created session owns.
181
+ * @returns {string} The effective household directory.
182
+ */
183
+ function homeDir() {
184
+ return options.home?.dir || pushConfig.cwd || config.cwd
185
+ || ctx.sandboxPolicy?.workspaceRoot || process.cwd()
186
+ }
187
+
188
+ /**
189
+ * Read the effective target mode (overlay first, then static config).
190
+ * @returns {Promise<'archive'|'session'>} The mode.
191
+ */
192
+ async function effectiveTargetMode() {
193
+ if (options.overlay) {
194
+ try {
195
+ const value = normalizePushTargetMode((await options.overlay.current())?.push?.target?.mode)
196
+ if (value) return value
197
+ } catch { /* fall through to the static config */ }
198
+ }
199
+ return normalizePushTargetMode(config.push?.target?.mode) || 'archive'
200
+ }
138
201
 
139
202
  /** @type {Map<string, {turn?: number, resolve: (v: any) => void, reject: (e: any) => void, timer: any, replies: string[]}>} */
140
203
  const waiters = new Map()
@@ -205,18 +268,40 @@ export function createPushService(options) {
205
268
  * Resolve the effective target for one inbound push.
206
269
  *
207
270
  * @param {any} payload - The Miloco webhook payload.
208
- * @returns {Promise<{sessionId: string, source: string, explicit: boolean, model?: {provider: string, model: string, reasoningEffort?: string}}>} The target.
271
+ * @returns {Promise<{sessionId: string, source: string, explicit: boolean, mode: 'archive'|'session', model?: {provider: string, model: string, reasoningEffort?: string}}>} The target.
209
272
  */
210
273
  async function resolveTarget(payload) {
211
274
  const overlay = options.overlay ? await options.overlay.current() : null
212
- const overlaySession = (overlay?.push?.target?.sessionId ?? '').trim()
213
275
  const overlayModel = overlay?.push?.model ?? {}
214
-
215
- const staticSession = String(target.sessionId ?? '').trim()
216
276
  const staticProvider = String(modelConfig.provider ?? '').trim()
217
277
  const staticModel = String(modelConfig.model ?? '').trim()
218
278
  const staticEffort = String(modelConfig.reasoningEffort ?? '').trim()
219
279
 
280
+ // Model: configured means "pin this conversation to that model".
281
+ // Empty means "do not call selectModel at all".
282
+ const provider = (overlayModel.provider ?? '').trim() || staticProvider
283
+ const model = (overlayModel.model ?? '').trim() || staticModel
284
+ let modelSelection
285
+ if (provider && model) {
286
+ const reasoningEffort = (overlayModel.reasoningEffort ?? '').trim() || staticEffort
287
+ modelSelection = reasoningEffort
288
+ ? { provider, model, reasoningEffort }
289
+ : { provider, model }
290
+ }
291
+
292
+ const mode = await effectiveTargetMode()
293
+ if (mode === 'archive') {
294
+ return {
295
+ sessionId: ARCHIVE_SESSION_ID,
296
+ source: 'archive',
297
+ explicit: true,
298
+ mode,
299
+ ...(modelSelection ? { model: modelSelection } : {}),
300
+ }
301
+ }
302
+
303
+ const overlaySession = (overlay?.push?.target?.sessionId ?? '').trim()
304
+ const staticSession = String(target.sessionId ?? '').trim()
220
305
  const configuredSession = overlaySession || staticSession
221
306
  let sessionId = configuredSession
222
307
  let source = 'configured'
@@ -230,21 +315,13 @@ export function createPushService(options) {
230
315
  source = 'miloco-session-key'
231
316
  }
232
317
  }
233
-
234
- // Model: configured means "pin this conversation to that model".
235
- // Empty means "do not call selectModel at all".
236
- const provider = (overlayModel.provider ?? '').trim() || staticProvider
237
- const model = (overlayModel.model ?? '').trim() || staticModel
238
- if (provider && model) {
239
- const reasoningEffort = (overlayModel.reasoningEffort ?? '').trim() || staticEffort
240
- return {
241
- sessionId,
242
- source,
243
- explicit: Boolean(configuredSession),
244
- model: reasoningEffort ? { provider, model, reasoningEffort } : { provider, model },
245
- }
318
+ return {
319
+ sessionId,
320
+ source,
321
+ explicit: Boolean(configuredSession),
322
+ mode,
323
+ ...(modelSelection ? { model: modelSelection } : {}),
246
324
  }
247
- return { sessionId, source, explicit: Boolean(configuredSession) }
248
325
  }
249
326
 
250
327
  /**
@@ -283,6 +360,35 @@ export function createPushService(options) {
283
360
  return true
284
361
  }
285
362
 
363
+ /**
364
+ * Attach one session to the household workspace.
365
+ *
366
+ * `sessionController.create({ cwd })` only sets the directory; workspace
367
+ * membership is explicit. Without this the archive session shows up under
368
+ * 「未分组」 in the native sidebar.
369
+ *
370
+ * @param {string} sessionId - Session to attach.
371
+ * @returns {Promise<void>} Resolves once the attempt finished.
372
+ */
373
+ async function attachToHome(sessionId) {
374
+ const workspaceId = String(options.home?.workspaceId ?? '')
375
+ if (!workspaceId) return
376
+ let registry
377
+ try {
378
+ registry = typeof ctx.get === 'function' ? ctx.get('workspaceRegistry') : undefined
379
+ } catch { return }
380
+ const workspace = registry?.get?.(workspaceId)
381
+ if (!workspace || typeof workspace.attachSession !== 'function') return
382
+ if (Array.isArray(workspace.sessionIds) && workspace.sessionIds.includes(sessionId)) return
383
+ try {
384
+ await workspace.attachSession(sessionId)
385
+ } catch (error) {
386
+ log?.warn?.(
387
+ `dsh-miloco-bridge: 把会话挂到家庭工作区失败:${error instanceof Error ? error.message : error}`,
388
+ )
389
+ }
390
+ }
391
+
286
392
  /**
287
393
  * Create a session, falling back to "no preset" if the preset is unknown.
288
394
  * @param {string} sessionId - Desired id.
@@ -290,17 +396,21 @@ export function createPushService(options) {
290
396
  */
291
397
  async function createSession(sessionId) {
292
398
  const agentPreset = String(options.agentPreset ?? '').trim()
399
+ const workspaceId = String(options.home?.workspaceId ?? '')
400
+ // A workspace id both derives the cwd and attaches the session; a host
401
+ // without one falls back to the plain household directory.
402
+ const location = workspaceId ? { workspaceId } : { cwd: homeDir() }
293
403
  try {
294
404
  const created = await ctx.sessionController.create({
295
405
  sessionId,
296
- cwd,
406
+ ...location,
297
407
  ...(agentPreset ? { agentPreset } : {}),
298
408
  })
299
409
  return created?.sessionId ?? sessionId
300
410
  } catch (error) {
301
411
  if (!agentPreset) throw error
302
412
  log?.warn?.(`dsh-miloco-bridge: 创建会话时挂载预设 ${agentPreset} 失败,退回无预设会话:${error instanceof Error ? error.message : error}`)
303
- const created = await ctx.sessionController.create({ sessionId, cwd })
413
+ const created = await ctx.sessionController.create({ sessionId, ...location })
304
414
  return created?.sessionId ?? sessionId
305
415
  }
306
416
  }
@@ -312,14 +422,28 @@ export function createPushService(options) {
312
422
  * turn is not reusable through it. Resolve first (which resumes the persisted
313
423
  * session) and create only when nothing is stored under that id.
314
424
  *
315
- * @param {{sessionId: string, explicit: boolean}} resolvedTarget - Resolved target.
425
+ * @param {{sessionId: string, explicit: boolean, mode: 'archive'|'session'}} resolvedTarget - Resolved target.
316
426
  * @param {any} payload - Inbound payload.
317
427
  * @returns {Promise<string>} The live session id.
318
428
  */
319
429
  async function ensureSession(resolvedTarget, payload) {
320
- const { sessionId, explicit } = resolvedTarget
430
+ const { sessionId, explicit, mode } = resolvedTarget
321
431
  if (await sessionExists(sessionId)) return sessionId
322
432
 
433
+ if (mode === 'archive') {
434
+ // The archive session is created once and then reused forever; only a
435
+ // freshly created session is retitled (a manual rename must survive).
436
+ const created = await createSession(sessionId)
437
+ try {
438
+ await ctx.sessionController.rename({ sessionId: created, title: ARCHIVE_SESSION_TITLE })
439
+ } catch (error) {
440
+ log?.warn?.(
441
+ `dsh-miloco-bridge: 设置归档会话标题失败:${error instanceof Error ? error.message : error}`,
442
+ )
443
+ }
444
+ return created
445
+ }
446
+
323
447
  if (!explicit) {
324
448
  // A remembered "last session" may have been deleted. Fall back to the
325
449
  // stable id derived from Miloco's session key before creating a new one.
@@ -348,6 +472,80 @@ export function createPushService(options) {
348
472
  )
349
473
  }
350
474
 
475
+ /**
476
+ * Read the host Session store, if the deployment provides one.
477
+ * @returns {any} The session store, or undefined.
478
+ */
479
+ function sessionsService() {
480
+ try {
481
+ const found = typeof ctx.get === 'function' ? ctx.get('sessions') : undefined
482
+ if (found) return found
483
+ } catch { /* fall through to the direct property */ }
484
+ return ctx.sessions
485
+ }
486
+
487
+ /**
488
+ * Deliver the push as a folded notification through the agent channel.
489
+ *
490
+ * `sessionController.prompt()` hard-codes `source.kind = 'user'`, so the
491
+ * conversation can only render it as an ordinary user message. A folded
492
+ * notification needs its own source: the client renders
493
+ * `source.kind === 'miloco-push'` as a collapsed card whose summary stays
494
+ * visible and whose body is only shown when the card is expanded.
495
+ *
496
+ * @param {string} sessionId - Target session.
497
+ * @param {string} message - The push body.
498
+ * @param {string} summary - One-line summary shown while folded.
499
+ * @returns {Promise<boolean>} Whether the folded channel handled the push.
500
+ */
501
+ async function deliverFolded(sessionId, message, summary) {
502
+ let agent = null
503
+ try {
504
+ const resolved = await ctx.sessionController.resolveAgent(sessionId)
505
+ if (resolved && typeof resolved === 'object' && resolved.agent) {
506
+ agent = resolved.agent
507
+ } else if (resolved && typeof resolved === 'object' && resolved.error) {
508
+ log?.warn?.(
509
+ `dsh-miloco-bridge: 折叠投递无法解析 Agent,回退到普通提示:${resolved.error instanceof Error ? resolved.error.message : String(resolved.error)}`,
510
+ )
511
+ return false
512
+ }
513
+ } catch (error) {
514
+ log?.warn?.(
515
+ `dsh-miloco-bridge: 折叠投递解析 Agent 失败,回退到普通提示:${error instanceof Error ? error.message : error}`,
516
+ )
517
+ return false
518
+ }
519
+ if (!agent || typeof agent.followup !== 'function') return false
520
+
521
+ const notice = {
522
+ id: randomUUID(),
523
+ role: 'user',
524
+ content: [{ type: 'text', text: message }],
525
+ source: { kind: PUSH_SOURCE_KIND, form: 'notice', summary },
526
+ }
527
+ try {
528
+ agent.followup(notice)
529
+ } catch (error) {
530
+ log?.warn?.(
531
+ `dsh-miloco-bridge: 折叠投递写入 Agent 失败,回退到普通提示:${error instanceof Error ? error.message : error}`,
532
+ )
533
+ return false
534
+ }
535
+
536
+ const sessions = sessionsService()
537
+ if (sessions && typeof sessions.flush === 'function' && agent.session) {
538
+ try {
539
+ await sessions.flush(agent.session)
540
+ } catch (error) {
541
+ log?.warn?.(
542
+ `dsh-miloco-bridge: 折叠投递落盘失败:${error instanceof Error ? error.message : error}`,
543
+ )
544
+ }
545
+ }
546
+ return true
547
+ }
548
+
351
549
  /**
352
550
  * Deliver one Miloco push into DSH.
353
551
  *
@@ -390,9 +588,45 @@ export function createPushService(options) {
390
588
  }
391
589
 
392
590
  const resolved = await resolveTarget(payload)
591
+ // The household workspace must exist before a session claims it as cwd.
592
+ if (typeof options.home?.ensure === 'function') {
593
+ try {
594
+ await options.home.ensure()
595
+ } catch (error) {
596
+ log?.warn?.(
597
+ `dsh-miloco-bridge: 准备家庭助手目录失败:${error instanceof Error ? error.message : error}`,
598
+ )
599
+ }
600
+ }
393
601
  const sessionId = await ensureSession(resolved, payload)
602
+ if (resolved.mode === 'archive') await attachToHome(sessionId)
394
603
  await options.activity?.note?.(sessionId)
395
604
 
605
+ const summary = pushDisplayTitle(payload, message)
606
+ const runId = randomUUID()
607
+ const requestId = randomUUID()
608
+
609
+ /**
610
+ * Append one delivery record to the shared push log.
611
+ * @param {string} status - Delivery status.
612
+ * @returns {Promise<void>} Resolves once the record is attempted.
613
+ */
614
+ async function recordPush(status) {
615
+ if (!options.state) return
616
+ try {
617
+ await notePush(options.state, {
618
+ at: Date.now(),
619
+ title: summary,
620
+ summary,
621
+ sessionId,
622
+ status,
623
+ runId,
624
+ })
625
+ } catch (error) {
626
+ log?.warn?.(`dsh-miloco-bridge: 写入推送记录失败:${error instanceof Error ? error.message : error}`)
627
+ }
628
+ }
629
+
396
630
  if (resolved.model) {
397
631
  await ctx.sessionController.selectModel({
398
632
  sessionId,
@@ -402,16 +636,18 @@ export function createPushService(options) {
402
636
  })
403
637
  }
404
638
 
405
- const runId = randomUUID()
406
- const requestId = randomUUID()
407
639
  const waitMs = Number.isFinite(payload?.timeoutMs) && payload.timeoutMs > 0
408
640
  ? Math.min(payload.timeoutMs, 600_000)
409
641
  : 120_000
410
642
 
411
643
  const waitForTurn = pushConfig.waitForResult !== false
644
+ // Only one delivery may own the session's waiter. A second overlapping
645
+ // push is delivered but not tracked: it must not unregister or resolve the
646
+ // waiter the first push opened.
647
+ const queued = waitForTurn && waiters.has(sessionId)
412
648
  /** @type {PromiseWithResolvers<any> | null} */
413
649
  let completion = null
414
- if (waitForTurn) {
650
+ if (waitForTurn && !queued) {
415
651
  completion = Promise.withResolvers()
416
652
  const timer = setTimeout(() => {
417
653
  waiters.delete(sessionId)
@@ -421,34 +657,67 @@ export function createPushService(options) {
421
657
  waiters.set(sessionId, { resolve: completion.resolve, reject: completion.reject, timer, replies: [], turn: undefined })
422
658
  }
423
659
 
660
+ // 折叠投递优先:走 Agent 通道,消息带 `miloco-push` source,客户端折叠展示。
661
+ // 拿不到 Agent 时回退到普通的 `prompt` 路径(旧行为保持可用)。
662
+ let folded = false
424
663
  try {
425
- await ctx.sessionController.prompt({
426
- requestId,
427
- sessionId,
428
- mode: 'queue',
429
- content: [{ type: 'text', text: message }],
430
- }, signal ?? new AbortController().signal)
664
+ folded = await deliverFolded(sessionId, message, summary)
431
665
  } catch (error) {
432
- const waiter = waiters.get(sessionId)
433
- if (waiter) {
434
- clearTimeout(waiter.timer)
435
- waiters.delete(sessionId)
666
+ if (completion) {
667
+ const waiter = waiters.get(sessionId)
668
+ if (waiter) {
669
+ clearTimeout(waiter.timer)
670
+ waiters.delete(sessionId)
671
+ }
436
672
  }
673
+ await recordPush('error')
437
674
  throw error
438
675
  }
439
676
 
677
+ if (!folded) {
678
+ try {
679
+ await ctx.sessionController.prompt({
680
+ requestId,
681
+ sessionId,
682
+ mode: 'queue',
683
+ content: [{ type: 'text', text: message }],
684
+ }, signal ?? new AbortController().signal)
685
+ } catch (error) {
686
+ if (completion) {
687
+ const waiter = waiters.get(sessionId)
688
+ if (waiter) {
689
+ clearTimeout(waiter.timer)
690
+ waiters.delete(sessionId)
691
+ }
692
+ }
693
+ await recordPush('error')
694
+ throw error
695
+ }
696
+ }
697
+
440
698
  if (!completion) {
441
- const result = { runId, status: 'ok', sessionId, source: resolved.source, async: true }
699
+ await recordPush('ok')
700
+ const result = {
701
+ runId,
702
+ status: 'ok',
703
+ sessionId,
704
+ source: resolved.source,
705
+ folded,
706
+ async: true,
707
+ ...(queued ? { queued: true } : {}),
708
+ }
442
709
  remember(idempotencyKey, result)
443
710
  return result
444
711
  }
445
712
 
446
713
  const settled = await completion.promise
714
+ await recordPush(settled.status)
447
715
  const result = {
448
716
  runId,
449
717
  status: settled.status,
450
718
  sessionId,
451
719
  source: resolved.source,
720
+ folded,
452
721
  ...(settled.reply ? { reply: settled.reply } : {}),
453
722
  ...(settled.status === 'error' ? { error: settled.reason ?? 'turn failed' } : {}),
454
723
  }
@@ -552,6 +821,17 @@ export function createPushService(options) {
552
821
  },
553
822
  })
554
823
  ctx.effect(() => dispose, 'dsh-miloco-bridge: push webhook route')
824
+ // Migrate an archive session created before workspace attachment existed.
825
+ void (async () => {
826
+ try {
827
+ await options.home?.ensure?.()
828
+ if (await sessionExists(ARCHIVE_SESSION_ID)) await attachToHome(ARCHIVE_SESSION_ID)
829
+ } catch (error) {
830
+ log?.warn?.(
831
+ `dsh-miloco-bridge: 归档会话挂载检查失败:${error instanceof Error ? error.message : error}`,
832
+ )
833
+ }
834
+ })()
555
835
  log?.info?.(`dsh-miloco-bridge: push webhook listening on ${path}`)
556
836
  }
557
837