dsh-monkeyai-sessions 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -39,7 +39,7 @@ All three request `device:connect`, `session:read`, and `session:control` throug
39
39
 
40
40
  ## Sessions
41
41
 
42
- Full conversation history is loaded over the runtime's HTTP read channel (`POST {http_base}/read/session` with `_monkeyai/session/messages`, paginated by cursor) instead of the bounded ACP `session/load` replay, so long sessions show every turn including the latest replies. While a turn is running the composer shows a stop button that sends `session/cancel`; the model switcher uses `_monkeyai/session/model/set` on the live session connection. Assistant messages render lightweight markdown (code blocks, inline code, bold, headings, lists).
42
+ Full conversation history is loaded over the runtime's HTTP read channel (`POST {http_base}/read/session` with `_monkeyai/session/messages`, paginated by cursor) instead of the bounded ACP `session/load` replay, so long sessions show every turn including the latest replies. After mounting the session with the same `historyHTTP` capabilities as the MonkeyAI client, the panel subscribes to ACP live updates: messages and assistant chunks started in the MonkeyAI desktop client appear as they stream, without refreshing. For large replies persisted by the runtime, `history_changed` triggers a cursor-based HTTP delta refresh and replaces any partial snapshot. While a turn is running the composer shows a stop button that sends `session/cancel`; the model switcher uses `_monkeyai/session/model/set` on the live session connection. Assistant messages render lightweight markdown (code blocks, inline code, bold, headings, lists).
43
43
 
44
44
  ## Installation
45
45
 
@@ -61,7 +61,7 @@ From a checkout:
61
61
  npm install
62
62
  npm run build
63
63
  npm pack
64
- dsh plugin --profile web add ./dsh-monkeyai-sessions-0.1.2.tgz
64
+ dsh plugin --profile web add ./dsh-monkeyai-sessions-0.1.3.tgz
65
65
  ```
66
66
 
67
67
  Verified against a real DSH `0.2.2-rc.1` web profile and a live MonkeyAI runtime: authorization, full history loading, prompt delivery, model switching, and turn cancellation all work end to end.
package/README.zh.md CHANGED
@@ -28,7 +28,7 @@ https://artenx.github.io/dsh-monkeyai-sessions/index.json
28
28
  npm install
29
29
  npm run build
30
30
  npm pack
31
- dsh plugin --profile web add ./dsh-monkeyai-sessions-0.1.2.tgz
31
+ dsh plugin --profile web add ./dsh-monkeyai-sessions-0.1.3.tgz
32
32
  ```
33
33
 
34
34
  已在真实的 DSH `0.2.2-rc.1` web profile 与在线 MonkeyAI runtime 上端到端验证:授权、完整历史加载、指令下发、模型切换、回合取消均正常工作。
@@ -45,7 +45,7 @@ dsh plugin --profile web add ./dsh-monkeyai-sessions-0.1.2.tgz
45
45
 
46
46
  ## 会话能力
47
47
 
48
- 完整对话历史通过 runtime 的 HTTP 读取通道加载(`POST {http_base}/read/session`,方法 `_monkeyai/session/messages`,按游标翻页),而不是 ACP `session/load` 的有界回放,因此长会话能看到每一轮内容,包括最新回复。
48
+ 完整对话历史通过 runtime 的 HTTP 读取通道加载(`POST {http_base}/read/session`,方法 `_monkeyai/session/messages`,按游标翻页),而不是 ACP `session/load` 的有界回放,因此长会话能看到每一轮内容,包括最新回复。会话使用与 MonkeyAI 客户端相同的 `historyHTTP` 能力挂载后,面板会订阅 ACP 实时更新:在 MonkeyAI 桌面客户端发起的用户消息和助手回复都会边生成边显示,无需刷新。对于 runtime 先持久化再通知的超大回复,收到 `history_changed` 后会按游标增量读取,并用完整快照补齐部分内容。
49
49
 
50
50
  回合执行期间输入框旁会显示停止按钮,点击发送 `session/cancel`;模型切换在会话自己的连接上调用 `_monkeyai/session/model/set`。助手消息支持轻量 Markdown 渲染(代码块、行内代码、粗体、标题、列表)。
51
51
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-monkeyai-sessions",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "在 DeepSeek Harness 中读取和继续 MonkeyAI 会话:查看完整对话历史、下发新指令,无缝接续之前在 MonkeyAI 客户端上的工作",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -689,6 +689,7 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
689
689
  let reconnectsUsed = 0
690
690
  const MAX_REPLAY_RECONNECTS = 32
691
691
  let ticketValue
692
+ let ticketHttpBase
692
693
  let loadCompleted = false
693
694
  let currentLoadedModel = undefined
694
695
  const aborted = new Promise(resolve => {
@@ -726,10 +727,12 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
726
727
  // for close detection but suppressed from the event stream to avoid
727
728
  // duplicating text the projection already folded in.
728
729
  const httpHistoryMessageIds = new Set()
729
- // When the HTTP channel delivered the full history, the ACP replay adds
730
- // nothing: skip session/load entirely and mount the session live.
730
+ // The full history was loaded over HTTP. Keep the message ids so ACP
731
+ // replay duplicates can be suppressed and history_changed notifications
732
+ // can fetch only newly persisted snapshots.
731
733
  let httpHistoryComplete = false
732
734
  let httpConfigurationRevision
735
+ let historyRefreshPromise = Promise.resolve()
733
736
  // history_loaded can be triggered by both the HTTP history channel and
734
737
  // the ACP load path; the stream must carry it exactly once.
735
738
  let historyLoadedEmitted = false
@@ -738,6 +741,26 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
738
741
  historyLoadedEmitted = true
739
742
  emit({ type: 'history_loaded', sessionId: selectedSession, ...(model === undefined ? {} : { model }) })
740
743
  }
744
+ const refreshPersistedHistory = async changedMessageId => {
745
+ if (!ticketHttpBase || !ticketValue) return
746
+ const delta = await fetchSessionHistoryDelta({
747
+ httpBase: ticketHttpBase,
748
+ ticket: ticketValue,
749
+ sessionId: selectedSession,
750
+ signal,
751
+ knownMessageIds: httpHistoryMessageIds,
752
+ changedMessageId,
753
+ })
754
+ if (Number.isSafeInteger(delta.configurationRevision)) {
755
+ httpConfigurationRevision = delta.configurationRevision
756
+ }
757
+ for (const message of delta.messages) {
758
+ httpHistoryMessageIds.add(message.id)
759
+ for (const frame of historyMessageToFrames(selectedSession, message, delta.toolCalls, { snapshot: true })) {
760
+ await emit(frame)
761
+ }
762
+ }
763
+ }
741
764
 
742
765
  function replayKey(params) {
743
766
  const update = params?.update
@@ -784,6 +807,22 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
784
807
  data: event.params,
785
808
  })
786
809
  } else {
810
+ if (event.method === '_monkeyai/session/history_changed' && httpHistoryComplete && ticketHttpBase) {
811
+ // Large live message bodies are persisted instead of streamed as
812
+ // chunks. Match the desktop client: refresh the newest HTTP pages
813
+ // and merge the resulting message snapshots into the projection.
814
+ historyRefreshPromise = historyRefreshPromise.then(() => refreshPersistedHistory(
815
+ typeof event.params?.messageId === 'string' ? event.params.messageId : undefined,
816
+ )).catch(error => {
817
+ if (!signal.aborted) emit({
818
+ type: 'error',
819
+ sessionId: selectedSession,
820
+ code: 'history_refresh_failed',
821
+ message: error instanceof Error ? error.message : '刷新实时会话内容失败',
822
+ })
823
+ })
824
+ return
825
+ }
787
826
  if (withLoad && !loadCompleted) {
788
827
  const key = replayKey(event.params)
789
828
  if (key !== null) {
@@ -795,7 +834,7 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
795
834
  }
796
835
  // Suppress replayed messages already delivered over HTTP, on every
797
836
  // connection generation (re-mounts replay the same window again).
798
- if (withLoad) {
837
+ if (withLoad && event.params?._meta?.replay === true) {
799
838
  const replayMessageId = (typeof event.params?._meta?.messageId === 'string' && event.params._meta.messageId !== '')
800
839
  ? event.params._meta.messageId
801
840
  : (typeof event.params?.update?.messageId === 'string' ? event.params.update.messageId : '')
@@ -887,7 +926,22 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
887
926
  const initialized = await acp.request('initialize', {
888
927
  protocolVersion: 1,
889
928
  clientInfo: ACP_CLIENT_INFO,
890
- clientCapabilities: {},
929
+ // Match the MonkeyAI desktop client. historyHTTP opts this connection
930
+ // into HTTP-backed snapshots and history_changed notifications;
931
+ // session/load then mounts the live subscription without replaying the
932
+ // oversized history over ACP.
933
+ clientCapabilities: {
934
+ _meta: {
935
+ messageSnapshots: true,
936
+ interactionReplies: true,
937
+ historyHTTP: true,
938
+ queueHTTP: true,
939
+ historyRefresh: true,
940
+ configHTTP: true,
941
+ stateHTTP: true,
942
+ interactionHTTP: true,
943
+ },
944
+ },
891
945
  }, { signal })
892
946
  if (initialized?.agentCapabilities?.loadSession !== true) {
893
947
  throw new Error('MonkeyAI runtime does not advertise ACP session history loading')
@@ -898,14 +952,11 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
898
952
  return
899
953
  }
900
954
  emit({ type: 'ready', sessionId: selectedSession })
901
- if (httpHistoryComplete) {
902
- // History came over HTTP; prompts and model switches work on a plain
903
- // initialized connection. Skip session/load: its bounded replay
904
- // always dies mid-stream and would churn reconnects for nothing.
905
- loadCompleted = true
906
- return
907
- }
908
955
  try {
956
+ // With historyHTTP advertised this mounts the session for live
957
+ // notifications while leaving persisted history reads to the HTTP
958
+ // cursor API above. Older runtimes may still replay a bounded window;
959
+ // the message-id filter suppresses those duplicate snapshots.
909
960
  const loadResult = await acp.request('session/load', {
910
961
  sessionId: selectedSession,
911
962
  cwd,
@@ -914,6 +965,13 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
914
965
  loadCompleted = true
915
966
  currentLoadedModel = typeof loadResult?._meta?.model === 'string' ? loadResult._meta.model : currentLoadedModel
916
967
  emitHistoryLoaded(currentLoadedModel)
968
+ // Close the gap between the initial full-history read and mounting the
969
+ // live subscription. A turn can start during that interval; snapshots
970
+ // replace any partial chunks that arrived before session/load resolved.
971
+ if (httpHistoryComplete) {
972
+ historyRefreshPromise = historyRefreshPromise.then(() => refreshPersistedHistory())
973
+ await historyRefreshPromise
974
+ }
917
975
  } catch (error) {
918
976
  if (signal?.aborted) throw error
919
977
  const message = error instanceof Error ? error.message : String(error)
@@ -958,6 +1016,7 @@ export class MonkeyAIRemoteService extends TypertRemoteService {
958
1016
  const token = await this.refreshAccessToken(accountId, signal)
959
1017
  const ticket = await this.requestConnectionTicket(accountId, grantRef, token, target, { signal })
960
1018
  ticketValue = ticket.ticket
1019
+ ticketHttpBase = ticket.httpBase
961
1020
  if (signal.aborted) throw signal.reason ?? new Error('远程会话已取消')
962
1021
 
963
1022
  // Load the full history over the runtime's HTTP read channel before the
@@ -1312,7 +1371,7 @@ function historyMessageText(parts) {
1312
1371
  // Converts one history message snapshot into the same notification frame
1313
1372
  // shape the ACP replay produces, so the shared projection layer renders both
1314
1373
  // identically. Message ids match ACP replay messageIds (u-turn-N / a-turn-N).
1315
- function historyMessageToFrames(sessionId, message, toolCallsById) {
1374
+ function historyMessageToFrames(sessionId, message, toolCallsById, { snapshot = false } = {}) {
1316
1375
  const frames = []
1317
1376
  const meta = { messageId: message.id, replay: true }
1318
1377
  const emitUpdate = update => {
@@ -1326,16 +1385,47 @@ function historyMessageToFrames(sessionId, message, toolCallsById) {
1326
1385
  const content = fileLinks.length > 0
1327
1386
  ? [...(text === '' ? [] : [{ type: 'text', text }]), ...fileLinks]
1328
1387
  : (text === '' ? undefined : { type: 'text', text })
1329
- if (content !== undefined) emitUpdate({ sessionUpdate: 'user_message_chunk', content })
1388
+ if (content !== undefined) emitUpdate({ sessionUpdate: snapshot ? 'user_message' : 'user_message_chunk', content })
1330
1389
  return frames
1331
1390
  }
1332
- for (const part of Array.isArray(message.parts) ? message.parts : []) {
1391
+ const parts = Array.isArray(message.parts) ? message.parts : []
1392
+ const snapshotThought = snapshot
1393
+ ? parts.filter(part => part?.type === 'thought' && typeof part.text === 'string').map(part => part.text).join('')
1394
+ : ''
1395
+ const snapshotText = snapshot
1396
+ ? parts.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text)
1397
+ .concat(parts.filter(part => part?.type === 'error' && typeof part.reason === 'string').map(part => `[error] ${part.reason}`)).join('')
1398
+ : ''
1399
+ let snapshotThoughtEmitted = false
1400
+ let snapshotTextEmitted = false
1401
+ for (const part of parts) {
1333
1402
  if (part?.type === 'thought' && typeof part.text === 'string' && part.text !== '') {
1334
- emitUpdate({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: part.text } })
1403
+ if (snapshot) {
1404
+ if (!snapshotThoughtEmitted && snapshotThought !== '') {
1405
+ emitUpdate({ sessionUpdate: 'agent_thought', content: { type: 'text', text: snapshotThought } })
1406
+ snapshotThoughtEmitted = true
1407
+ }
1408
+ } else {
1409
+ emitUpdate({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: part.text } })
1410
+ }
1335
1411
  } else if (part?.type === 'text' && typeof part.text === 'string' && part.text !== '') {
1336
- emitUpdate({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: part.text } })
1412
+ if (snapshot) {
1413
+ if (!snapshotTextEmitted && snapshotText !== '') {
1414
+ emitUpdate({ sessionUpdate: 'agent_message', content: { type: 'text', text: snapshotText } })
1415
+ snapshotTextEmitted = true
1416
+ }
1417
+ } else {
1418
+ emitUpdate({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: part.text } })
1419
+ }
1337
1420
  } else if (part?.type === 'error' && typeof part.reason === 'string' && part.reason !== '') {
1338
- emitUpdate({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `[error] ${part.reason}` } })
1421
+ if (snapshot) {
1422
+ if (!snapshotTextEmitted && snapshotText !== '') {
1423
+ emitUpdate({ sessionUpdate: 'agent_message', content: { type: 'text', text: snapshotText } })
1424
+ snapshotTextEmitted = true
1425
+ }
1426
+ } else {
1427
+ emitUpdate({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `[error] ${part.reason}` } })
1428
+ }
1339
1429
  } else if (part?.type === 'file' && typeof part.uri === 'string') {
1340
1430
  emitUpdate({ sessionUpdate: 'agent_message_chunk', content: { type: 'resource_link', name: part.name, uri: part.uri } })
1341
1431
  } else if (part?.type === 'tool_call' && typeof part.toolCallId === 'string') {
@@ -1389,6 +1479,47 @@ async function fetchFullSessionHistory({ httpBase, ticket, sessionId, signal, on
1389
1479
  return { messageIds: [...seenIds], count: seenIds.size, configurationRevision }
1390
1480
  }
1391
1481
 
1482
+ // Refresh only the newest pages after a _monkeyai/session/history_changed
1483
+ // notification. Pages are oldest-to-newest internally and arrive newest-first;
1484
+ // stop once a known boundary is reached, retaining a changed message id even
1485
+ // when it was already present (the runtime may have replaced a partial body).
1486
+ async function fetchSessionHistoryDelta({ httpBase, ticket, sessionId, signal, knownMessageIds, changedMessageId, maxPages = 200 }) {
1487
+ const pages = []
1488
+ const seenIds = new Set()
1489
+ const toolCalls = {}
1490
+ let cursor
1491
+ let configurationRevision
1492
+ let foundBoundary = false
1493
+ let foundChangedMessage = !changedMessageId
1494
+ for (let page = 0; page < maxPages; page += 1) {
1495
+ const timeout = AbortSignal.any([AbortSignal.timeout(30_000), ...(signal ? [signal] : [])])
1496
+ const result = await readSessionHistoryPage({ httpBase, ticket, sessionId, cursor, direction: 'older', signal: timeout })
1497
+ if (Number.isSafeInteger(result.session?.configurationRevision)) configurationRevision = result.session.configurationRevision
1498
+ const pageMessages = []
1499
+ for (const message of result.messages) {
1500
+ if (typeof message?.id !== 'string' || message.id === '') continue
1501
+ const known = knownMessageIds.has(message.id)
1502
+ const changed = message.id === changedMessageId
1503
+ if (changed) foundChangedMessage = true
1504
+ if ((!known || changed) && !seenIds.has(message.id)) {
1505
+ seenIds.add(message.id)
1506
+ pageMessages.push(message)
1507
+ }
1508
+ if (known && !changed) foundBoundary = true
1509
+ }
1510
+ pages.push(pageMessages)
1511
+ Object.assign(toolCalls, result.toolCalls ?? {})
1512
+ if (foundBoundary && foundChangedMessage) break
1513
+ cursor = typeof result.olderCursor === 'string' && result.olderCursor !== '' ? result.olderCursor : undefined
1514
+ if (!cursor || result.messages.length === 0) break
1515
+ }
1516
+ return {
1517
+ messages: pages.reverse().flat(),
1518
+ toolCalls,
1519
+ configurationRevision,
1520
+ }
1521
+ }
1522
+
1392
1523
  function validateResponse(method, params, result) {
1393
1524
  if (!isObject(result)) throw new TypeError('ACP response must be a JSON object')
1394
1525
  if (method === 'session/request_permission') {