moi-computer 0.8.1-next.0 → 0.9.1-next.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.
- package/client/assets/hermes.png +0 -0
- package/client/components/shared/IconGhost.tsx +15 -18
- package/client/components/ui/button.tsx +2 -2
- package/client/components/ui/hover-card.tsx +1 -1
- package/client/components/ui/popover.tsx +3 -1
- package/client/features/chat/ChatEmptyState.tsx +25 -7
- package/client/features/chat/ChatPanel.tsx +70 -28
- package/client/features/chat/ChatPopup.tsx +3 -2
- package/client/features/chat/ChatPromptBubbles.tsx +1 -1
- package/client/features/chat/MarkdownContent.tsx +1 -1
- package/client/features/chat/attachment-staging.ts +153 -0
- package/client/features/chat/chat-send.ts +55 -0
- package/client/features/chat/chat-store.ts +32 -8
- package/client/features/chat/composer/ChatComposer.tsx +190 -77
- package/client/features/chat/{ModelPicker.tsx → composer/ModelPicker.tsx} +29 -25
- package/client/features/chat/composer/banners/ComposerBanner.tsx +1 -1
- package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +4 -13
- package/client/features/chat/{model-order.ts → composer/model-order.ts} +16 -0
- package/client/features/chat/composer/useWorkspaceComposerState.tsx +9 -4
- package/client/features/chat/tool-group/format/claude.ts +48 -0
- package/client/features/chat/tool-group/format/codex.ts +126 -0
- package/client/features/chat/tool-group/format/hermes.ts +68 -0
- package/client/features/chat/tool-group/format/index.ts +34 -0
- package/client/features/chat/tool-group/format/mcp.ts +64 -0
- package/client/features/chat/tool-group/format/openclaw.ts +116 -0
- package/client/features/chat/tool-group/format/shared.ts +49 -0
- package/client/features/chat/useChat.ts +5 -10
- package/client/features/dev/ChatStatesPage.tsx +40 -2
- package/client/features/drawings/DrawingLayer.tsx +49 -0
- package/client/features/drawings/DrawingToolbar.tsx +95 -0
- package/client/features/drawings/annotation-availability.ts +10 -0
- package/client/features/drawings/capture-element.ts +45 -0
- package/client/features/drawings/useChatAnnotation.ts +222 -0
- package/client/features/drawings/useDrawingLayer.ts +758 -0
- package/client/features/drawings/useViewBuilderSketch.ts +151 -0
- package/client/features/home/workspace-presentation.tsx +6 -2
- package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +12 -6
- package/client/features/scratchpad/ScratchpadControls.tsx +19 -5
- package/client/features/views/ViewBuilder.tsx +224 -0
- package/client/features/views/api.ts +1 -0
- package/client/features/views/useViewBuilderActions.ts +24 -3
- package/client/features/views/useViewBuilderDrafts.ts +66 -0
- package/client/features/widgets/Widgets.tsx +23 -39
- package/client/features/workspace/CustomizePanel.tsx +1 -1
- package/client/features/workspace/WorkspaceScreen.tsx +157 -57
- package/client/features/workspace/WorkspaceTabs.tsx +3 -3
- package/client/features/workspace/useFitsSplitLayout.ts +14 -8
- package/client/index.css +8 -0
- package/client/store/ui.ts +19 -0
- package/client/theme.css +33 -8
- package/dist/chunk-3becmq75.js +81 -0
- package/dist/{chunk-kkj86722.js → chunk-6w6j9g4b.js} +78 -78
- package/dist/{chunk-xeyxk7ep.js → chunk-8ew39cvq.js} +4 -4
- package/dist/chunk-c8gtrjwp.js +1 -0
- package/dist/{chunk-2vaafjp4.js → chunk-pp62fnxh.js} +1 -1
- package/dist/{chunk-35fq49qa.js → chunk-sxc24vfp.js} +1 -1
- package/dist/{chunk-xzx7c9hq.js → chunk-v964b5g7.js} +1 -1
- package/dist/chunk-zx33ts9d.css +1 -0
- package/dist/hermes-pznd63x9.png +0 -0
- package/dist/index.html +1 -1
- package/lib/format.ts +21 -7
- package/lib/themes.ts +8 -8
- package/lib/types.ts +8 -1
- package/lib/workspace-types.ts +2 -1
- package/package.json +6 -4
- package/server/api.ts +21 -2
- package/server/bundler/build-applet.ts +35 -44
- package/server/cli-env.ts +2 -2
- package/server/cli.ts +227 -56
- package/server/constants.ts +8 -0
- package/server/control-client.ts +124 -0
- package/server/control.ts +2 -2
- package/server/harness/README.md +74 -23
- package/server/harness/acp/adapter.ts +220 -0
- package/server/harness/acp/archived.ts +88 -0
- package/server/harness/acp/client.ts +328 -0
- package/server/harness/acp/discovery.ts +130 -0
- package/server/harness/acp/run-durations.ts +68 -0
- package/server/harness/acp/session.ts +788 -0
- package/server/harness/acp/wire.ts +132 -0
- package/server/harness/executable.ts +15 -1
- package/server/harness/hermes/NOTES.md +815 -0
- package/server/harness/hermes/discovery.ts +155 -0
- package/server/harness/hermes/index.ts +155 -0
- package/server/harness/hermes/models.ts +79 -0
- package/server/harness/openclaw/NOTES.md +196 -94
- package/server/harness/openclaw/adapter.ts +28 -55
- package/server/harness/openclaw/compat.ts +4 -8
- package/server/harness/openclaw/session.ts +257 -238
- package/server/harness/openclaw/strip.ts +10 -34
- package/server/harness/openclaw/thinking.ts +5 -53
- package/server/harness/registry.ts +3 -1
- package/server/service.ts +2 -2
- package/server/view-builders.ts +4 -2
- package/server/workspace-import.ts +30 -1
- package/workspace/.claude/skills/moi-workspace/SKILL.md +6 -6
- package/client/features/chat/tool-group/format.ts +0 -359
- package/client/features/views/ViewBuilderTab.tsx +0 -152
- package/dist/chunk-gny990qx.css +0 -1
- package/dist/chunk-gt7n06ef.js +0 -1
- package/dist/chunk-n7pga5x3.js +0 -80
- /package/workspace/.claude/skills/moi-workspace/{DESIGN.md → references/DESIGN.md} +0 -0
- /package/workspace/.claude/skills/moi-workspace/{SCRATCHPAD.md → references/SCRATCHPAD.md} +0 -0
package/server/harness/README.md
CHANGED
|
@@ -97,6 +97,36 @@ Current harnesses:
|
|
|
97
97
|
| Claude Code (Agent SDK) | `claude-code/session.ts` | `claude-code/adapter.ts` | shipped, primary |
|
|
98
98
|
| OpenClaw (gateway) | `openclaw/session.ts` | `openclaw/adapter.ts` | shipped, experimental |
|
|
99
99
|
| Codex (app-server) | `codex/session.ts` | `codex/adapter.ts` | shipped, experimental |
|
|
100
|
+
| Hermes (ACP) | `acp/session.ts` | `acp/adapter.ts` | shipped, experimental |
|
|
101
|
+
|
|
102
|
+
`acp/` is the odd one out: it is **not** a harness, it is the shared
|
|
103
|
+
implementation of the Agent Client Protocol (stdio JSON-RPC), and `hermes/`
|
|
104
|
+
is the first provider built on it. Any other ACP-speaking agent (Gemini CLI,
|
|
105
|
+
opencode, Zed's agents) should become another thin folder next to `hermes/`
|
|
106
|
+
rather than a copy of the protocol. The split is:
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
acp/ provider-agnostic protocol
|
|
110
|
+
wire.ts ACP message types (re-exported from the official SDK)
|
|
111
|
+
client.ts spawn + stdio JSON-RPC framing, one process per workspace
|
|
112
|
+
adapter.ts session/update → Turn/ToolCall (+ chunk accumulation)
|
|
113
|
+
session.ts per-session state machine, driven by AcpProviderConfig
|
|
114
|
+
discovery.ts session/list, model catalog, home-card preview
|
|
115
|
+
hermes/ provider specifics only
|
|
116
|
+
discovery.ts profile discovery (the importable "agents")
|
|
117
|
+
index.ts the Harness object + AcpProviderConfig
|
|
118
|
+
NOTES.md protocol research + backend quirks
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
A new ACP provider supplies an `AcpProviderConfig`: an id, the spawn spec
|
|
122
|
+
(binary + args), the no-prompt mode id, and whether images ride inline.
|
|
123
|
+
|
|
124
|
+
`wire.ts` re-exports the schema-generated types from
|
|
125
|
+
`@agentclientprotocol/sdk` — a **types-only, dev-only** dependency, since
|
|
126
|
+
importing values from it would pull zod in at runtime. It adds one labelled
|
|
127
|
+
"pre-1.0 additions" block for the model-selection surface the spec dropped and
|
|
128
|
+
Hermes still implements; delete that block when agents move to
|
|
129
|
+
`session/set_config_option`. See `hermes/NOTES.md` §12.
|
|
100
130
|
|
|
101
131
|
Dev tooling: `/dev/harness` (live wire log + client frames + trigger
|
|
102
132
|
scenarios for any workspace, backed by `GET /api/workspaces/:id/harness/debug`
|
|
@@ -121,15 +151,36 @@ SDK has no live setter for them.
|
|
|
121
151
|
**OpenClaw — shipped.** Chat over the local gateway's WebSocket JSON-RPC
|
|
122
152
|
(wire protocol 4 — the 2026.7.x and 2026.6.x lines; protocol-3 gateways are
|
|
123
153
|
detected and surfaced, see `openclaw/compat.ts`): sessions seeded cold from
|
|
124
|
-
`sessions.get` then updated from live `session.message` frames
|
|
125
|
-
|
|
126
|
-
frames,
|
|
127
|
-
`
|
|
128
|
-
|
|
129
|
-
|
|
154
|
+
`sessions.get` then updated from live `session.message` frames (placed by the
|
|
155
|
+
transcript `seq` they carry, so a late row still renders in order), token-delta
|
|
156
|
+
previews from `chat` frames, live tool state + output from the tool stream
|
|
157
|
+
(`session.tool` and `agent`/tool are one payload split by audience — see
|
|
158
|
+
`openclaw/NOTES.md` §6 — and share one handler), run failures surfaced from the
|
|
159
|
+
frames that carry them, model/effort applied per send via `sessions.patch`,
|
|
160
|
+
abort via `sessions.abort`, per-turn usage (tokens + cost) into `TurnMeta`,
|
|
161
|
+
user-echo rendezvous by `<runId>:user` idempotency key (text fallback), uploads
|
|
162
|
+
materialized to file paths. The frame orders a live gateway produces are
|
|
163
|
+
replayed against the real session code by `openclaw/wire-replay.test.ts`. Known gaps: no rich vision blocks (string-only
|
|
130
164
|
`sessions.send`), and the gateway is the sole source of truth (no local
|
|
131
165
|
persistence; cold restarts re-seed).
|
|
132
166
|
|
|
167
|
+
**Hermes — shipped, experimental.** Chat over `hermes acp` (stdio JSON-RPC,
|
|
168
|
+
one process per workspace so `workspaceEnv` injects at spawn — `acp/client.ts`),
|
|
169
|
+
built on the provider-agnostic `acp/` layer. Session create/resume with temp-id
|
|
170
|
+
rename, `session/load` history replay, interrupt via `session/cancel`, per-turn
|
|
171
|
+
token usage, token streaming for thinking _and_ text, inline base64 images,
|
|
172
|
+
per-chat model switching from the catalog `session/new` returns inline, and
|
|
173
|
+
backend-generated session titles surfaced through `sessions_changed`. Agents are
|
|
174
|
+
Hermes **profiles** — discovered from `$HERMES_HOME`, imported with
|
|
175
|
+
`moi hermes init <profile>`, never created from the UI (OpenClaw's model).
|
|
176
|
+
Sessions run in Hermes's `dont_ask` mode to match moi's bypass-permissions trust
|
|
177
|
+
model. Known gaps: no mid-turn steering (moi queues instead), no subagent lanes,
|
|
178
|
+
no reasoning-effort control, and `session/set_model` drops session-scoped MCP
|
|
179
|
+
servers upstream. Two backend quirks are worked around in `acp/session.ts`:
|
|
180
|
+
tool calls left unsettled at turn end are closed (Hermes never completes file
|
|
181
|
+
read/write calls live), and a completing `tool_call_update` carries no title, so
|
|
182
|
+
the established name is kept. See `hermes/NOTES.md`.
|
|
183
|
+
|
|
133
184
|
**Codex — shipped, experimental.** Chat over `codex app-server` (stdio
|
|
134
185
|
JSON-RPC, one process per workspace so `workspaceEnv` injects at spawn —
|
|
135
186
|
`codex/client.ts`): thread create/resume with temp-id rename, per-turn model +
|
|
@@ -244,23 +295,23 @@ doubles as the evaluation rubric for new harnesses.
|
|
|
244
295
|
|
|
245
296
|
Legend: ✅ supported · ⚠️ partial/workaround · ❌ missing.
|
|
246
297
|
|
|
247
|
-
| Feature | Claude Agent SDK | OpenClaw gateway | Codex app-server |
|
|
248
|
-
| ------------------------ | --------------------------------------------------- | ------------------------- | ------------------------------------- |
|
|
249
|
-
| Long-lived session | ✅ subprocess per session | ✅ gateway-side | ✅ server-side, N threads/process |
|
|
250
|
-
| Queue/steer mid-turn | ⚠️ queued next turn | ⚠️ | ✅ `turn/steer` into live turn |
|
|
251
|
-
| Resume | ✅ | ✅ | ✅ + fork |
|
|
252
|
-
| Interrupt | ✅ `interrupt()` | ✅ | ✅ `turn/interrupt` |
|
|
253
|
-
| List models | ✅ `supportedModels()` | ✅ `models.list` | ✅ `model/list` |
|
|
254
|
-
| Live model switch | ✅ `setModel()` | ✅ `sessions.patch` | ✅ per-turn override |
|
|
255
|
-
| Live effort switch | ❌ rebuild | ✅ `thinkingLevel` patch | ✅ per-turn |
|
|
256
|
-
| Token deltas | ✅ opt-in | ✅ `chat` frames | ✅ `item/*/delta` |
|
|
257
|
-
| Images in input | ✅ base64 blocks | ⚠️ materialize to path | ✅ data URL or path |
|
|
258
|
-
| Interactive approvals | ⚠️ (we bypass) | ✅ | ✅ server→client requests (we bypass) |
|
|
259
|
-
| Session list/history API | ✅ `listSessions()` + jsonl | ✅ `sessions.get` | ✅ `thread/list`/`read` |
|
|
260
|
-
| Home card preview | ✅ session file scan | ✅ cached first message | ⚠️ live app-server only |
|
|
261
|
-
| MCP status | ✅ `mcpServerStatus()` | n/a | ✅ `mcpServerStatus/list` |
|
|
262
|
-
| Usage reporting | ⚠️ cost/duration on `result` (adapter drops tokens) | ✅ tokens + cost per turn | ✅ live + rate limits |
|
|
263
|
-
| Structured output | ❌ | ❌ | ✅ per turn |
|
|
298
|
+
| Feature | Claude Agent SDK | OpenClaw gateway | Codex app-server | Hermes (ACP) |
|
|
299
|
+
| ------------------------ | --------------------------------------------------- | ------------------------- | ------------------------------------- | ------------------------------------ |
|
|
300
|
+
| Long-lived session | ✅ subprocess per session | ✅ gateway-side | ✅ server-side, N threads/process | ✅ process per workspace, N sessions |
|
|
301
|
+
| Queue/steer mid-turn | ⚠️ queued next turn | ⚠️ | ✅ `turn/steer` into live turn | ⚠️ queued (ACP has no steer) |
|
|
302
|
+
| Resume | ✅ | ✅ | ✅ + fork | ✅ `session/load` (+ fork) |
|
|
303
|
+
| Interrupt | ✅ `interrupt()` | ✅ | ✅ `turn/interrupt` | ✅ `session/cancel` → `cancelled` |
|
|
304
|
+
| List models | ✅ `supportedModels()` | ✅ `models.list` | ✅ `model/list` | ✅ inline on `session/new` |
|
|
305
|
+
| Live model switch | ✅ `setModel()` | ✅ `sessions.patch` | ✅ per-turn override | ⚠️ drops session MCP servers |
|
|
306
|
+
| Live effort switch | ❌ rebuild | ✅ `thinkingLevel` patch | ✅ per-turn | ❌ no effort concept in ACP |
|
|
307
|
+
| Token deltas | ✅ opt-in | ✅ `chat` frames | ✅ `item/*/delta` | ✅ always on, thinking + text |
|
|
308
|
+
| Images in input | ✅ base64 blocks | ⚠️ materialize to path | ✅ data URL or path | ✅ base64 blocks |
|
|
309
|
+
| Interactive approvals | ⚠️ (we bypass) | ✅ | ✅ server→client requests (we bypass) | ✅ real, with diffs (we bypass) |
|
|
310
|
+
| Session list/history API | ✅ `listSessions()` + jsonl | ✅ `sessions.get` | ✅ `thread/list`/`read` | ✅ `session/list` (cwd + cursor) |
|
|
311
|
+
| Home card preview | ✅ session file scan | ✅ cached first message | ⚠️ live app-server only | ⚠️ live process only |
|
|
312
|
+
| MCP status | ✅ `mcpServerStatus()` | n/a | ✅ `mcpServerStatus/list` | ⚠️ per-session config, no status RPC |
|
|
313
|
+
| Usage reporting | ⚠️ cost/duration on `result` (adapter drops tokens) | ✅ tokens + cost per turn | ✅ live + rate limits | ✅ tokens per turn |
|
|
314
|
+
| Structured output | ❌ | ❌ | ✅ per turn | ❌ |
|
|
264
315
|
|
|
265
316
|
## Design lessons so far
|
|
266
317
|
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// ACP wire (layer 1) → moi display format (layer 2). Pure mapping, no I/O.
|
|
2
|
+
//
|
|
3
|
+
// ACP streams *chunks*, not discrete messages: assistant text and thinking
|
|
4
|
+
// arrive token-by-token with no message boundary, and tool calls interleave.
|
|
5
|
+
// The shape moi renders is turn-based, so this module owns the accumulation
|
|
6
|
+
// rule: consecutive text/thought chunks build one assistant turn, and a tool
|
|
7
|
+
// call both closes the open assistant turn and becomes a turn of its own —
|
|
8
|
+
// the same item-per-turn model the Codex adapter produces.
|
|
9
|
+
|
|
10
|
+
import { splitAttachmentNote } from '@/lib/attachment-note'
|
|
11
|
+
import type { Part, ToolCall, ToolState, Turn, TurnMeta } from '@/lib/format'
|
|
12
|
+
import { stripMoiContext } from '@/lib/moi-context'
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
type AcpSessionListEntry,
|
|
16
|
+
type ToolCallStatus,
|
|
17
|
+
type ToolCallUpdate,
|
|
18
|
+
type Usage,
|
|
19
|
+
toolContentToText
|
|
20
|
+
} from './wire'
|
|
21
|
+
import type { SessionInfo } from '@/lib/types'
|
|
22
|
+
|
|
23
|
+
export type AcpProviderId = NonNullable<ToolCall['provider']>
|
|
24
|
+
|
|
25
|
+
export function toolStatusToState(status: ToolCallStatus | undefined): ToolState {
|
|
26
|
+
switch (status) {
|
|
27
|
+
case 'completed':
|
|
28
|
+
return 'success'
|
|
29
|
+
case 'failed':
|
|
30
|
+
return 'error'
|
|
31
|
+
case 'in_progress':
|
|
32
|
+
return 'running'
|
|
33
|
+
default:
|
|
34
|
+
// ACP defaults an omitted status to `pending`; moi renders that as a
|
|
35
|
+
// spinner-less card, so treat a started call as running instead.
|
|
36
|
+
return 'running'
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Tool-call turn ids must be stable across the `tool_call` → `tool_call_update`
|
|
41
|
+
// pair (upsert-by-id) and across live-vs-replay, where the backend may hand out
|
|
42
|
+
// different ids for the same call (Hermes does — see ../hermes/NOTES.md §3.4).
|
|
43
|
+
export function toolTurnId(sessionId: string, toolCallId: string): string {
|
|
44
|
+
return `${sessionId}:tool:${toolCallId}`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function assistantTurnId(sessionId: string, runIndex: number): string {
|
|
48
|
+
return `${sessionId}:msg:${runIndex}`
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ACP tool calls carry a semantic `kind` and a human `title` instead of a raw
|
|
52
|
+
// function name. Prefer the title (it is already display-ready, e.g.
|
|
53
|
+
// "terminal: echo hi"); only the opening `tool_call` carries one, so the name
|
|
54
|
+
// already on the card outranks the bare `kind` a `tool_call_update` falls back
|
|
55
|
+
// to — otherwise the label degrades from "terminal: echo hi" to "execute"
|
|
56
|
+
// the moment the call completes.
|
|
57
|
+
export function toolCallName(update: ToolCallUpdate, previousName?: string): string {
|
|
58
|
+
return update.title?.trim() || previousName || update.kind || 'tool'
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function acpToolCallToTurn(input: {
|
|
62
|
+
update: ToolCallUpdate
|
|
63
|
+
sessionId: string
|
|
64
|
+
provider: AcpProviderId
|
|
65
|
+
previous?: Turn
|
|
66
|
+
timestamp?: string
|
|
67
|
+
}): Turn {
|
|
68
|
+
const { update, sessionId, provider, previous } = input
|
|
69
|
+
const prevCall =
|
|
70
|
+
previous?.parts.find((p): p is Extract<Part, { type: 'tool-call' }> => p.type === 'tool-call')
|
|
71
|
+
?.call ?? undefined
|
|
72
|
+
|
|
73
|
+
const text = toolContentToText(update.content)
|
|
74
|
+
const locations = update.locations?.map(l => l.path).filter(Boolean) ?? []
|
|
75
|
+
const call: ToolCall = {
|
|
76
|
+
toolCallId: update.toolCallId,
|
|
77
|
+
name: toolCallName(update, prevCall?.name),
|
|
78
|
+
caller: 'model',
|
|
79
|
+
provider,
|
|
80
|
+
state: update.status ? toolStatusToState(update.status) : (prevCall?.state ?? 'running'),
|
|
81
|
+
input: update.rawInput ?? prevCall?.input ?? (locations.length ? { path: locations[0] } : {}),
|
|
82
|
+
...(locations.length
|
|
83
|
+
? { sidecar: { locations } }
|
|
84
|
+
: prevCall?.sidecar
|
|
85
|
+
? { sidecar: prevCall.sidecar }
|
|
86
|
+
: {})
|
|
87
|
+
}
|
|
88
|
+
// `tool_call` announces with a preview blurb and `tool_call_update` carries
|
|
89
|
+
// the result; keep whichever text we have most recently seen.
|
|
90
|
+
const output = text || (typeof prevCall?.output === 'string' ? prevCall.output : '')
|
|
91
|
+
if (output) call.output = output
|
|
92
|
+
if (call.state === 'error' && output) call.errorText = output
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
id: toolTurnId(sessionId, update.toolCallId),
|
|
96
|
+
role: 'assistant',
|
|
97
|
+
origin: { kind: 'user-input' },
|
|
98
|
+
parts: [{ type: 'tool-call', call }],
|
|
99
|
+
timestamp: previous?.timestamp ?? input.timestamp ?? new Date().toISOString()
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function acpUsageToTurnMeta(usage: Usage | null | undefined): TurnMeta['usage'] | undefined {
|
|
104
|
+
if (!usage) return undefined
|
|
105
|
+
const { inputTokens, outputTokens, totalTokens } = usage
|
|
106
|
+
if (inputTokens === undefined && outputTokens === undefined && totalTokens === undefined) {
|
|
107
|
+
return undefined
|
|
108
|
+
}
|
|
109
|
+
return { inputTokens, outputTokens, totalTokens }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Replayed `user_message_chunk` text is the persisted prompt verbatim: the
|
|
113
|
+
// typed text plus everything the sender appended to it — the attachment note
|
|
114
|
+
// and the `<moi-context>` envelope (see sendAcpMessage in ./session.ts). Fold
|
|
115
|
+
// that machinery back out so a reloaded bubble matches the live one. Envelope
|
|
116
|
+
// first: it is appended after the note, and `splitAttachmentNote` parses the
|
|
117
|
+
// note as the text's tail. An envelope-only block (an attachment-only send
|
|
118
|
+
// carries the envelope as its lone text) folds to no parts — the caller skips
|
|
119
|
+
// the bubble entirely.
|
|
120
|
+
export function replayedUserParts(raw: string): Part[] {
|
|
121
|
+
const split = splitAttachmentNote(stripMoiContext(raw))
|
|
122
|
+
const parts: Part[] = split.files.map(f => ({
|
|
123
|
+
type: 'file',
|
|
124
|
+
mediaType: 'application/octet-stream',
|
|
125
|
+
url: f.path,
|
|
126
|
+
filename: f.filename
|
|
127
|
+
}))
|
|
128
|
+
if (split.text.trim()) parts.push({ type: 'text', text: split.text })
|
|
129
|
+
return parts
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function acpSessionToSessionInfo(entry: AcpSessionListEntry): SessionInfo {
|
|
133
|
+
const updated = entry.updatedAt ? Date.parse(entry.updatedAt) : NaN
|
|
134
|
+
return {
|
|
135
|
+
sessionId: entry.sessionId,
|
|
136
|
+
summary: entry.title?.trim() || 'Untitled session',
|
|
137
|
+
lastModified: Number.isNaN(updated) ? 0 : updated,
|
|
138
|
+
...(entry.cwd ? { cwd: entry.cwd } : {})
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Accumulates chunk streams into assistant turns. One instance per live
|
|
143
|
+
// session (and one per replay pass) — see the module header for the rule.
|
|
144
|
+
export class AssistantTurnAccumulator {
|
|
145
|
+
private text = ''
|
|
146
|
+
private reasoning = ''
|
|
147
|
+
private runIndex = 0
|
|
148
|
+
private startedAt: string | null = null
|
|
149
|
+
|
|
150
|
+
constructor(
|
|
151
|
+
private sessionId: string,
|
|
152
|
+
private model?: string,
|
|
153
|
+
private provider?: string
|
|
154
|
+
) {}
|
|
155
|
+
|
|
156
|
+
setModel(model: string | undefined) {
|
|
157
|
+
this.model = model
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
get isOpen(): boolean {
|
|
161
|
+
return this.text.length > 0 || this.reasoning.length > 0
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// The id the open run will be emitted under. Also used as the preview's
|
|
165
|
+
// `apiMessageId`, so the client clears the preview when the turn lands.
|
|
166
|
+
get currentId(): string {
|
|
167
|
+
return assistantTurnId(this.sessionId, this.runIndex)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
append(kind: 'text' | 'reasoning', delta: string) {
|
|
171
|
+
if (!delta) return
|
|
172
|
+
if (!this.startedAt) this.startedAt = new Date().toISOString()
|
|
173
|
+
if (kind === 'text') this.text += delta
|
|
174
|
+
else this.reasoning += delta
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Snapshot of the open run as preview blocks (cumulative text, never diffs).
|
|
178
|
+
previewBlocks(): { index: number; kind: 'text' | 'reasoning'; text: string }[] {
|
|
179
|
+
const blocks: { index: number; kind: 'text' | 'reasoning'; text: string }[] = []
|
|
180
|
+
if (this.reasoning)
|
|
181
|
+
blocks.push({ index: blocks.length, kind: 'reasoning', text: this.reasoning })
|
|
182
|
+
if (this.text) blocks.push({ index: blocks.length, kind: 'text', text: this.text })
|
|
183
|
+
return blocks
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Close the open run and return its Turn, or null when nothing accumulated.
|
|
187
|
+
// `meta` is folded in so the final turn of a prompt carries usage/stopReason.
|
|
188
|
+
flush(meta?: TurnMeta): Turn | null {
|
|
189
|
+
if (!this.isOpen) return null
|
|
190
|
+
const parts: Part[] = []
|
|
191
|
+
if (this.reasoning) parts.push({ type: 'reasoning', text: this.reasoning })
|
|
192
|
+
if (this.text) parts.push({ type: 'text', text: this.text })
|
|
193
|
+
const turn: Turn = {
|
|
194
|
+
id: this.currentId,
|
|
195
|
+
role: 'assistant',
|
|
196
|
+
origin: { kind: 'user-input' },
|
|
197
|
+
parts,
|
|
198
|
+
timestamp: this.startedAt ?? new Date().toISOString(),
|
|
199
|
+
meta: {
|
|
200
|
+
...(this.model ? { model: this.model } : {}),
|
|
201
|
+
...(this.provider ? { provider: this.provider } : {}),
|
|
202
|
+
apiMessageId: this.currentId,
|
|
203
|
+
...meta
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
this.text = ''
|
|
207
|
+
this.reasoning = ''
|
|
208
|
+
this.startedAt = null
|
|
209
|
+
this.runIndex++
|
|
210
|
+
return turn
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Abandon the open run without emitting (used when a replay pass restarts).
|
|
214
|
+
reset() {
|
|
215
|
+
this.text = ''
|
|
216
|
+
this.reasoning = ''
|
|
217
|
+
this.startedAt = null
|
|
218
|
+
this.runIndex = 0
|
|
219
|
+
}
|
|
220
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Archived-chat bookkeeping for ACP backends.
|
|
2
|
+
//
|
|
3
|
+
// ACP specifies `session/delete`, but agents do not implement it — Hermes 0.20
|
|
4
|
+
// answers it with JSON-RPC -32601 "Method not found", and its per-session
|
|
5
|
+
// archive flag is reachable only through the `hermes serve` HTTP routes, a
|
|
6
|
+
// daemon moi deliberately does not run. So moi hides archived chats on its own
|
|
7
|
+
// side, exactly like the Claude Code harness (which tags a session
|
|
8
|
+
// `moi:archived` and filters the list rather than deleting anything).
|
|
9
|
+
//
|
|
10
|
+
// Nothing is destroyed: the chat stays in the backend's own store and remains
|
|
11
|
+
// visible to that agent's CLI, which is the correct boundary — moi hides a chat
|
|
12
|
+
// from moi, not from the user's agent.
|
|
13
|
+
//
|
|
14
|
+
// Stored OUTSIDE the workspace (no repo churn) in ONE global JSON file in moi's
|
|
15
|
+
// data dir, keyed by workspace path then session id:
|
|
16
|
+
// { "<workspacePath>": ["<sessionId>", …] }
|
|
17
|
+
// Path (not registry id) is the key so the list survives re-registration, the
|
|
18
|
+
// same choice session-config.ts makes.
|
|
19
|
+
import { mkdir, rename } from 'node:fs/promises'
|
|
20
|
+
import { join } from 'node:path'
|
|
21
|
+
|
|
22
|
+
import { DATA_DIR } from '../../data-dir'
|
|
23
|
+
|
|
24
|
+
type Store = Record<string, string[]>
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_ARCHIVED_SESSIONS_PATH = join(DATA_DIR, 'acp-archived-sessions.json')
|
|
27
|
+
|
|
28
|
+
let storePath = DEFAULT_ARCHIVED_SESSIONS_PATH
|
|
29
|
+
|
|
30
|
+
// Test seam: point the store at a scratch file (mirrors setSessionConfigPath).
|
|
31
|
+
export function setArchivedSessionsPath(path: string): void {
|
|
32
|
+
storePath = path
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function readStore(): Promise<Store> {
|
|
36
|
+
try {
|
|
37
|
+
const parsed = JSON.parse(await Bun.file(storePath).text())
|
|
38
|
+
return parsed && typeof parsed === 'object' ? (parsed as Store) : {}
|
|
39
|
+
} catch {
|
|
40
|
+
return {}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function writeStore(store: Store): Promise<void> {
|
|
45
|
+
await mkdir(join(storePath, '..'), { recursive: true })
|
|
46
|
+
const tmp = `${storePath}.${process.pid}.tmp`
|
|
47
|
+
await Bun.write(tmp, JSON.stringify(store, null, 2))
|
|
48
|
+
await rename(tmp, storePath)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Serialize read-modify-write so concurrent archive calls can't clobber the
|
|
52
|
+
// single shared file (last writer would otherwise drop the other's update).
|
|
53
|
+
let writeChain: Promise<unknown> = Promise.resolve()
|
|
54
|
+
function locked<T>(fn: () => Promise<T>): Promise<T> {
|
|
55
|
+
const run = writeChain.then(fn, fn)
|
|
56
|
+
writeChain = run.catch(() => {})
|
|
57
|
+
return run
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function archivedAcpSessions(workspacePath: string): Promise<Set<string>> {
|
|
61
|
+
return locked(async () => new Set((await readStore())[workspacePath] ?? []))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function archiveAcpSession(workspacePath: string, sessionId: string): Promise<void> {
|
|
65
|
+
if (!sessionId) return
|
|
66
|
+
await locked(async () => {
|
|
67
|
+
const store = await readStore()
|
|
68
|
+
const ids = store[workspacePath] ?? []
|
|
69
|
+
if (ids.includes(sessionId)) return
|
|
70
|
+
store[workspacePath] = [...ids, sessionId]
|
|
71
|
+
await writeStore(store)
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Not wired to a route yet — chats are archived, never unarchived, in the UI.
|
|
76
|
+
// Kept because the store is only a hide, so undoing it is a one-liner and the
|
|
77
|
+
// asymmetry would otherwise look like data loss.
|
|
78
|
+
export async function unarchiveAcpSession(workspacePath: string, sessionId: string): Promise<void> {
|
|
79
|
+
await locked(async () => {
|
|
80
|
+
const store = await readStore()
|
|
81
|
+
const ids = store[workspacePath]
|
|
82
|
+
if (!ids?.includes(sessionId)) return
|
|
83
|
+
const next = ids.filter(id => id !== sessionId)
|
|
84
|
+
if (next.length) store[workspacePath] = next
|
|
85
|
+
else delete store[workspacePath]
|
|
86
|
+
await writeStore(store)
|
|
87
|
+
})
|
|
88
|
+
}
|