moi-computer 0.6.0 → 0.7.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/server/control.ts CHANGED
@@ -6,7 +6,7 @@ import { isParamsRecord } from '@/lib/workspace-tabs'
6
6
 
7
7
  import { clearAppletLog, getAppletLog, getAppletLogCount } from './applet-log'
8
8
  import { serializeWorkspaceBundle } from './bundle-queue'
9
- import { CONTROL_PORT } from './constants'
9
+ import { CONTROL_PORT, PORT } from './constants'
10
10
  import { applyEnvChanged } from './env-apply'
11
11
  import { callFunctionEphemeral, parseFunctionPath } from './functions'
12
12
  import { processIcon } from './icon'
@@ -28,6 +28,7 @@ import {
28
28
  setBuilder
29
29
  } from './view-builders'
30
30
  import { getWorkspaceConfig, setWorkspaceConfig } from './workspace-config'
31
+ import { VERSION } from './version'
31
32
 
32
33
  type ControlSocket = { send(data: string): void }
33
34
 
@@ -86,6 +87,22 @@ export const control = Bun.serve({
86
87
  return
87
88
  }
88
89
 
90
+ // Identity of the running server, for the CLI (`moi status`, `moi
91
+ // update`, `moi service`). VERSION is snapshotted at boot, so this
92
+ // reports the code actually running even after the install tree on
93
+ // disk was replaced by an update.
94
+ if (data.type === 'server:info') {
95
+ ws.send(
96
+ JSON.stringify({
97
+ version: VERSION,
98
+ pid: process.pid,
99
+ port: PORT,
100
+ service: !!process.env.MOI_SERVICE
101
+ })
102
+ )
103
+ return
104
+ }
105
+
89
106
  if (data.type === 'bundle') {
90
107
  // Resolve to the real workspace root (works from `.moi/` or any
91
108
  // subdir; errors when outside every registered workspace) so a bundle
@@ -30,6 +30,17 @@ Rules: **adapters are the only code that sees layer 1** — everything above
30
30
  speaks layers 2/3 only. `lib/format.ts` and `lib/types.ts` never move into
31
31
  this folder: the client imports them; they are the shared contract.
32
32
 
33
+ System machinery that backends leave in user-role text (slash-command
34
+ records, interrupt markers, injected reminder envelopes) is classified by
35
+ the shared rule registry in `lib/system-messages.ts` — provider-agnostic,
36
+ text-level. Adapters call it when building user turns: an all-machinery
37
+ message keeps its raw parts but lands as `origin: synthetic` (hidden by the
38
+ client), embedded envelopes strip out of real text, and notify-classified
39
+ messages (background-task notices) are rewritten to a readable sentence and
40
+ surface as `origin: notification` turns. Add new patterns there, not as
41
+ ad-hoc regexes in an adapter. (Exception: OpenClaw's inbound-meta stripper
42
+ mirrors upstream code verbatim and stays in `openclaw/strip.ts`.)
43
+
33
44
  Socket-protocol notes the layers rely on (all defined in `lib/types.ts`):
34
45
 
35
46
  - **`session_renamed`** — a new thread is created under the client's temporary
@@ -135,13 +135,14 @@ Of these the repo currently handles only `tool_result`.
135
135
 
136
136
  At the SDK wire level, **every tool result and every harness-injected prompt is a `user` message**, because Anthropic's Messages API has no dedicated role for them. Classify by content and flags, in this priority order:
137
137
 
138
- | # | Condition | What it really is | UI behavior |
139
- | --- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- |
140
- | 1 | `isReplay: true` | Replay from a resumed session; not new content | Skip (or render only once from the persisted log) |
141
- | 2 | `content[]` contains a `tool_result` block | Tool return back to the model | Route into the paired tool-use card; may carry extra metadata in top-level `tool_use_result` |
142
- | 3 | `isSynthetic: true` | Harness-injected context (skill body, slash-command expansion, `<system-reminder>`, hook output) | Transcript-only context; hide by default, expose behind a toggle |
143
- | 4 | `parent_tool_use_id !== null` AND first user turn of a subtask | The `Agent` tool's `prompt` argument being replayed as the subtask's opening user turn | Render as the subtask's prompt inside the nested view, not in the main thread |
144
- | 5 | none of the above | Actual user input typed into the chat | Render as the user bubble |
138
+ | # | Condition | What it really is | UI behavior |
139
+ | --- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
140
+ | 1 | `isReplay: true` | Replay from a resumed session; not new content | Skip (or render only once from the persisted log) |
141
+ | 2 | `content[]` contains a `tool_result` block | Tool return back to the model | Route into the paired tool-use card; may carry extra metadata in top-level `tool_use_result` |
142
+ | 3 | `isSynthetic: true` | Harness-injected context (skill body, slash-command expansion, `<system-reminder>`, hook output) | Transcript-only context; hide by default, expose behind a toggle |
143
+ | 4 | Text matches a `lib/system-messages.ts` rule (all blocks) | CLI machinery written **without** flags: slash-command records, `[Request interrupted by user]`, `<local-command-stdout>`, bash-mode I/O, compact continuations, task notifications, … | Hide rules: as #3 — keep raw parts, mark `origin: synthetic`. Notify rules (task notifications): rewrite to readable text, `origin: notification`, shown |
144
+ | 5 | `parent_tool_use_id !== null` AND first user turn of a subtask | The `Agent` tool's `prompt` argument being replayed as the subtask's opening user turn | Render as the subtask's prompt inside the nested view, not in the main thread |
145
+ | 6 | none of the above | Actual user input typed into the chat | Render as the user bubble (embedded `<system-reminder>`/hook envelopes strip out first) |
145
146
 
146
147
  ### On `isSynthetic` specifically — the docs don't say, the source does
147
148
 
@@ -156,6 +157,20 @@ So `isSynthetic = true` means: _this user turn was fabricated by the harness and
156
157
 
157
158
  `isSynthetic` and `parent_tool_use_id` are **orthogonal**. A sub-agent's initial prompt (observed on line 14 of the captured log) has `parent_tool_use_id` set but `isSynthetic` absent — from the subagent's frame, that IS real user input.
158
159
 
160
+ ### Machinery the CLI does NOT flag (row #4)
161
+
162
+ Several user entries the CLI writes for itself carry **no** `isMeta`/`isSynthetic`, so they'd render as user bubbles without text classification. Inventory (verified against the CLI binary's strings and live transcripts; the rules live in `lib/system-messages.ts`):
163
+
164
+ - `<command-name>/<command-message>/<command-args>` (+ legacy `<command-contents>`) — slash-command invocation records
165
+ - `<local-command-stdout>` / `<local-command-stderr>` — local command output
166
+ - `[Request interrupted by user]` / `[Request interrupted by user for tool use]` — abort markers; the tool-use variant rides next to the aborted `tool_result` block
167
+ - `<bash-input>` / `<bash-stdout>` / `<bash-stderr>` — `!command` bash mode
168
+ - `<user-memory-input>` — `#note` memory mode
169
+ - `<task-notification>` (and the cloud `[SYSTEM NOTIFICATION - NOT USER INPUT]` preamble) — background-task notices; these are the one machinery kind that SURFACES: the rule rewrites the block to its `<summary>` text and the turn lands as `origin: notification` (plain text in the flow for now, a dedicated UI block later)
170
+ - `Caveat: The messages below were generated by the user while running local commands.` — `isMeta` in current CLIs, unflagged in older transcripts
171
+ - `This session is being continued from a previous conversation that ran out of context.` — post-compaction continuation summary
172
+ - `<system-reminder>` / `<user-prompt-submit-hook>` — envelopes attached to real messages; stripped from the text rather than hiding the turn
173
+
159
174
  ---
160
175
 
161
176
  ## 5. Sub-agent invocation — the nesting mechanism
@@ -6,6 +6,7 @@ import type {
6
6
  SessionSnapshot,
7
7
  StreamEvent,
8
8
  SubagentRecord,
9
+ SyntheticTurnReason,
9
10
  SystemNotice,
10
11
  ToolCall,
11
12
  ToolCaller,
@@ -16,6 +17,7 @@ import type {
16
17
 
17
18
  import { isAttachmentOnlyPlaceholder, splitAttachmentNote } from '@/lib/attachment-note'
18
19
  import { stripMoiContext } from '@/lib/moi-context'
20
+ import { classifySystemMessage, filterSystemText } from '@/lib/system-messages'
19
21
 
20
22
  // Loose SDK message shape — we don't pull in the full SDK type tree; the
21
23
  // adapter tolerates missing fields. Reference: ./NOTES.md.
@@ -154,9 +156,9 @@ function callerFromBlockType(type: string, name: string): ToolCaller {
154
156
  return 'model'
155
157
  }
156
158
 
157
- function classifySyntheticReason(
158
- firstText: string
159
- ): Exclude<Extract<TurnOrigin, { kind: 'synthetic' }>['reason'], never> {
159
+ function classifySyntheticReason(firstText: string): SyntheticTurnReason {
160
+ const verdict = classifySystemMessage([firstText])
161
+ if (verdict?.kind === 'hide') return verdict.reason
160
162
  if (/<system-reminder>/i.test(firstText)) return 'system-reminder'
161
163
  return 'other'
162
164
  }
@@ -509,19 +511,49 @@ export class ClaudeAdapter {
509
511
  const parts: Part[] = []
510
512
  let firstText = ''
511
513
 
514
+ // A user message whose text is entirely backend machinery (see
515
+ // lib/system-messages.ts). Two fates: hide-classified messages — a
516
+ // slash-command record, an interrupt marker — keep their raw parts but
517
+ // land as synthetic turns, hidden exactly like the SDK's own isSynthetic
518
+ // injections; notify-classified messages (task notifications) surface as
519
+ // readable text below. Computed for isSynthetic entries too — local CC
520
+ // flags task notifications isMeta, and those must still surface. Replays
521
+ // stay untouched so their persisted-log counterpart renders once.
522
+ // Text-only messages qualify; real content (attachments, images) vetoes.
523
+ const systemVerdict =
524
+ msg.type === 'user' && !msg.isReplay && blocks.every(b => b.type === 'text')
525
+ ? classifySystemMessage(blocks.map(b => b.text ?? ''))
526
+ : undefined
527
+
528
+ // A notification renders as plain text in the flow: none of the bubble
529
+ // machinery (attachment notes, echo matching, skill stashing) applies.
530
+ if (systemVerdict?.kind === 'notification') {
531
+ return {
532
+ id: turnId(msg),
533
+ role: 'user',
534
+ origin: { kind: 'notification' },
535
+ parentTaskId: msg.parent_tool_use_id ?? undefined,
536
+ parts: [{ type: 'text', text: systemVerdict.text }],
537
+ timestamp: msg.timestamp
538
+ }
539
+ }
540
+
512
541
  for (const b of blocks) {
513
542
  switch (b.type) {
514
543
  case 'text':
515
544
  if (b.text) {
516
545
  let text = b.text
517
- if (msg.type === 'user' && !msg.isSynthetic) {
546
+ if (msg.type === 'user' && !msg.isSynthetic && !systemVerdict) {
518
547
  // Non-image attachments reach the agent as a temp-path note
519
548
  // appended to the user's text (see lib/attachment-note.ts). The
520
549
  // SDK persists that appended text, so fold the note back into
521
550
  // file chips here — a reloaded bubble matches the live one
522
551
  // instead of leaking temp paths into it.
523
552
  const split = splitAttachmentNote(text)
524
- text = stripMoiContext(split.text)
553
+ // moi's own context envelope strips precisely (marker-guarded);
554
+ // other embedded machinery — system reminders, hook output —
555
+ // strips by the shared rules, keeping the typed text.
556
+ text = filterSystemText(stripMoiContext(split.text)).text
525
557
  for (const f of split.files) {
526
558
  parts.push({
527
559
  type: 'file',
@@ -604,6 +636,8 @@ export class ClaudeAdapter {
604
636
  origin = { kind: 'replay' }
605
637
  } else if (msg.isSynthetic) {
606
638
  origin = { kind: 'synthetic', reason: classifySyntheticReason(firstText) }
639
+ } else if (systemVerdict) {
640
+ origin = { kind: 'synthetic', reason: systemVerdict.reason }
607
641
  } else if (msg.parent_tool_use_id) {
608
642
  origin = { kind: 'subagent-prompt', parentToolCallId: msg.parent_tool_use_id }
609
643
  } else {
@@ -21,6 +21,7 @@ import {
21
21
  import { appendAttachmentNote, attachmentOnlyPlaceholder } from '@/lib/attachment-note'
22
22
  import { buildSessionTitleSource } from '../session-title'
23
23
  import { ClaudeAdapter } from './adapter'
24
+ import { claudeSessionExists } from './sessions'
24
25
  import { generateClaudeSessionTitle, renameClaudeSessionIfUnchanged } from './session-title'
25
26
  import type { Part } from '@/lib/format'
26
27
  import type { SessionActivity } from '@/lib/types'
@@ -624,7 +625,9 @@ function createLiveSession(input: {
624
625
  permissionMode: 'bypassPermissions',
625
626
  allowDangerouslySkipPermissions: true,
626
627
  settingSources: ['user', 'project'],
627
- env: { ...process.env, ...input.workspaceEnv, CLAUDECODE: undefined },
628
+ // MOI_AGENT marks every shell this session spawns as agent-driven (the
629
+ // moi CLI reads it — see agent-caller.ts), surviving the CLAUDECODE strip.
630
+ env: { ...process.env, ...input.workspaceEnv, CLAUDECODE: undefined, MOI_AGENT: '1' },
628
631
  stderr: (data: string) => console.error('[SDK stderr]', data)
629
632
  }
630
633
  if (!input.isNew) options.resume = input.sessionId
@@ -691,12 +694,6 @@ export async function sendCCMessage(input: {
691
694
  ? resolveUploads(input.workspaceId, input.attachments)
692
695
  : []
693
696
  if (!input.content && uploads.length === 0) return
694
- const sessionTitleSource = input.isNew
695
- ? buildSessionTitleSource(
696
- input.content,
697
- uploads.map(upload => upload.filename)
698
- )
699
- : undefined
700
697
  const { content: userContent, parts } = buildUserMessage(input.content, uploads)
701
698
  // The envelope goes in as its OWN leading text block, never merged into the
702
699
  // user's string: the SDK's first-prompt extraction (session titles,
@@ -758,18 +755,37 @@ export async function sendCCMessage(input: {
758
755
  }
759
756
  }
760
757
  if (!s) {
758
+ // The agent only sees secrets scoped to the 'agent' sink (plus .env).
759
+ // Resolved before the probe below so both see the same env.
760
+ const workspaceEnv = await resolveWorkspaceEnv(input.workspacePath)
761
+ // Resuming a session with no file on disk hard-fails the CLI with "No
762
+ // conversation found" — and a dangling id can be selected forever (a
763
+ // brand-new chat whose first turn died before init persisted anything,
764
+ // or session files cleaned up externally), wedging the chat. Start fresh
765
+ // instead: the init rename then migrates this id to the real one
766
+ // everywhere (selected session, session config, view builders, client).
767
+ const isNew =
768
+ input.isNew ||
769
+ !(await claudeSessionExists(input.sessionId, input.workspacePath, workspaceEnv))
770
+ if (isNew !== input.isNew) {
771
+ debug(`cc resume-missing ws=${input.workspaceId} session=${input.sessionId} — starting fresh`)
772
+ }
761
773
  s = createLiveSession({
762
774
  workspaceId: input.workspaceId,
763
775
  workspacePath: input.workspacePath,
764
776
  sessionId: input.sessionId,
765
- isNew: input.isNew,
777
+ isNew,
766
778
  model: input.model,
767
779
  effort: input.effort,
768
780
  fastMode: input.fastMode,
769
781
  stream: wantStream,
770
- sessionTitleSource,
771
- // The agent only sees secrets scoped to the 'agent' sink (plus .env).
772
- workspaceEnv: await resolveWorkspaceEnv(input.workspacePath)
782
+ sessionTitleSource: isNew
783
+ ? buildSessionTitleSource(
784
+ input.content,
785
+ uploads.map(upload => upload.filename)
786
+ )
787
+ : undefined,
788
+ workspaceEnv
773
789
  })
774
790
  }
775
791
  // Streaming-input mode does NOT echo the pushed user message back in the
@@ -1,6 +1,11 @@
1
1
  // Session discovery + history replay for Claude Code workspaces, backed by
2
2
  // the Agent SDK's persisted `.jsonl` session files.
3
- import { getSessionMessages, listSessions, tagSession } from '@anthropic-ai/claude-agent-sdk'
3
+ import {
4
+ getSessionInfo,
5
+ getSessionMessages,
6
+ listSessions,
7
+ tagSession
8
+ } from '@anthropic-ai/claude-agent-sdk'
4
9
  import type { SDKSessionInfo } from '@anthropic-ai/claude-agent-sdk'
5
10
 
6
11
  import {
@@ -91,6 +96,29 @@ export async function getSessionWorkspacePreview(
91
96
  }
92
97
  }
93
98
 
99
+ // Whether the session's file exists on disk in this workspace's project dir —
100
+ // i.e. whether `resume` can possibly succeed. Reads only that session's file
101
+ // (unlike listSessions). Fails open — a probe that can't answer reliably
102
+ // counts as existing, so the resume is still attempted instead of silently
103
+ // forking a new chat:
104
+ // - a transient fs error, and
105
+ // - a workspace env that redirects CLAUDE_CONFIG_DIR: the CLI subprocess gets
106
+ // workspaceEnv on top of process.env, so its session store is somewhere
107
+ // this process (and the SDK's ambient-env resolution) can't see.
108
+ export async function claudeSessionExists(
109
+ sessionId: string,
110
+ workspacePath: string,
111
+ workspaceEnv: Record<string, string> = {}
112
+ ): Promise<boolean> {
113
+ const override = workspaceEnv.CLAUDE_CONFIG_DIR
114
+ if (override && override !== process.env.CLAUDE_CONFIG_DIR) return true
115
+ try {
116
+ return (await getSessionInfo(sessionId, { dir: workspacePath })) !== undefined
117
+ } catch {
118
+ return true
119
+ }
120
+ }
121
+
94
122
  export async function archiveClaudeSession(
95
123
  sessionId: string,
96
124
  workspacePath: string
@@ -97,7 +97,9 @@ async function startClient(workspacePath: string): Promise<ClientRecord> {
97
97
  stdin: 'pipe',
98
98
  stdout: 'pipe',
99
99
  stderr: 'pipe',
100
- env: { ...process.env, ...workspaceEnv }
100
+ // MOI_AGENT marks the agent's shells as agent-driven for the moi CLI
101
+ // (see agent-caller.ts).
102
+ env: { ...process.env, ...workspaceEnv, MOI_AGENT: '1' }
101
103
  })
102
104
 
103
105
  let alive = true
@@ -76,6 +76,26 @@ function styleProps(style: ScratchStyle): Record<string, unknown> {
76
76
  }
77
77
  }
78
78
 
79
+ // Run a synchronous load with tldraw's own logging held back. On a failed
80
+ // migration `StoreSchema` prints `Error migrating store Incompatible schema?`
81
+ // itself, which reaches the `moi scratch` caller ahead of — and contradicting —
82
+ // the actionable error we throw below ("the file is intact"). Whatever it says
83
+ // is replayed if the load actually succeeds, so only the swallowed-by-a-throw
84
+ // case is lost. Safe to swap `console.error` around: `loadSnapshot` is sync.
85
+ function loadQuietly(load: () => void): void {
86
+ const original = console.error
87
+ const held: unknown[][] = []
88
+ console.error = (...args: unknown[]) => {
89
+ held.push(args)
90
+ }
91
+ try {
92
+ load()
93
+ } finally {
94
+ console.error = original
95
+ }
96
+ for (const args of held) original(...args)
97
+ }
98
+
79
99
  // A fresh headless store hydrated from the saved snapshot (or empty). The
80
100
  // snapshot shape (`{ document }`) matches what the browser PUTs and loads.
81
101
  // A failed load is inspected for version skew: tldraw has no down-migrations,
@@ -86,7 +106,9 @@ function buildStore(doc: ScratchpadDoc | null, writer: ScratchpadWriter | undefi
86
106
  const store = createTLStore({ shapeUtils: defaultShapeUtils, bindingUtils: defaultBindingUtils })
87
107
  if (doc?.store) {
88
108
  try {
89
- loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
109
+ loadQuietly(() =>
110
+ loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
111
+ )
90
112
  } catch (err) {
91
113
  const ahead = sequencesAhead(doc.schema, store.schema.serialize().sequences)
92
114
  if (ahead.length > 0) {