moi-computer 0.0.3 → 0.1.1
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 +2 -2
- package/bunfig.toml +4 -0
- package/client/api/workspaces.ts +277 -6
- package/client/assets/mcp/agentation.png +0 -0
- package/client/assets/mcp/airtable.png +0 -0
- package/client/assets/mcp/apollo.png +0 -0
- package/client/assets/mcp/asana.png +0 -0
- package/client/assets/mcp/box.png +0 -0
- package/client/assets/mcp/chrome.svg +33 -0
- package/client/assets/mcp/clickup.png +0 -0
- package/client/assets/mcp/cloudflare.png +0 -0
- package/client/assets/mcp/context7.png +0 -0
- package/client/assets/mcp/datadog.png +0 -0
- package/client/assets/mcp/dropbox.png +0 -0
- package/client/assets/mcp/elevenlabs.png +0 -0
- package/client/assets/mcp/exa.png +0 -0
- package/client/assets/mcp/firecrawl.png +0 -0
- package/client/assets/mcp/gmail.png +0 -0
- package/client/assets/mcp/googlecalendar.png +0 -0
- package/client/assets/mcp/googledrive.png +0 -0
- package/client/assets/mcp/grafana.png +0 -0
- package/client/assets/mcp/huggingface.png +0 -0
- package/client/assets/mcp/intercom.png +0 -0
- package/client/assets/mcp/monday.png +0 -0
- package/client/assets/mcp/mongodb.png +0 -0
- package/client/assets/mcp/paper.png +0 -0
- package/client/assets/mcp/paypal.png +0 -0
- package/client/assets/mcp/perplexity.png +0 -0
- package/client/assets/mcp/postgresql.png +0 -0
- package/client/assets/mcp/posthog.png +0 -0
- package/client/assets/mcp/puppeteer.png +0 -0
- package/client/assets/mcp/railway.png +0 -0
- package/client/assets/mcp/redis.png +0 -0
- package/client/assets/mcp/salesforce.png +0 -0
- package/client/assets/mcp/shopify.png +0 -0
- package/client/assets/mcp/snowflake.png +0 -0
- package/client/assets/mcp/telegram.png +0 -0
- package/client/assets/mcp/twilio.png +0 -0
- package/client/assets/mcp/zapier.png +0 -0
- package/client/components/App.tsx +7 -1
- package/client/components/ChatInput.tsx +194 -13
- package/client/components/ChatPanel.tsx +116 -47
- package/client/components/ChatPopup.tsx +1 -1
- package/client/components/IconMcp.tsx +21 -0
- package/client/components/McpMenu.tsx +125 -0
- package/client/components/ModelPicker.tsx +147 -0
- package/client/components/Scratchpad.tsx +775 -0
- package/client/components/ShimmerText.tsx +20 -0
- package/client/components/ThreadSelector.tsx +2 -2
- package/client/components/TurnView.tsx +111 -531
- package/client/components/WidgetShell.tsx +1 -1
- package/client/components/WorkspacesPage.tsx +12 -4
- package/client/components/layout/SidebarLayout.tsx +18 -9
- package/client/components/playground/ToolCallsPage.tsx +81 -0
- package/client/components/routes/workspace/[id].tsx +534 -141
- package/client/components/routes/workspace/create.tsx +155 -0
- package/client/components/settings/IconPicker.tsx +590 -0
- package/client/components/settings/SettingsPages.tsx +307 -0
- package/client/components/settings/WorkspaceSettings.tsx +92 -0
- package/client/components/tool-group/CodeBlock.tsx +41 -0
- package/client/components/tool-group/Collapse.tsx +28 -0
- package/client/components/tool-group/ReadImagePreview.tsx +46 -0
- package/client/components/tool-group/SubagentCard.tsx +135 -0
- package/client/components/tool-group/TimelineRow.tsx +147 -0
- package/client/components/tool-group/ToolCallGroup.tsx +231 -0
- package/client/components/tool-group/ToolOutput.tsx +139 -0
- package/client/components/tool-group/detect.ts +93 -0
- package/client/components/tool-group/fixtures.ts +315 -0
- package/client/components/tool-group/format.ts +211 -0
- package/client/components/tool-group/index.ts +9 -0
- package/client/components/ui/dialog.tsx +58 -0
- package/client/components/ui/hover-card.tsx +44 -0
- package/client/components/ui/switch.tsx +23 -0
- package/client/components/ui/tooltip.tsx +54 -0
- package/client/externalize-react.ts +6 -0
- package/client/hooks/useApplet.ts +117 -0
- package/client/hooks/useChat.ts +162 -62
- package/client/hooks/useMeiEvents.ts +9 -2
- package/client/hooks/useStickToBottom.ts +86 -0
- package/client/hooks/useWorkspaceTheme.ts +8 -2
- package/client/index.css +48 -2
- package/client/index.html +9 -5
- package/client/index.tsx +29 -2
- package/client/lib/WorkspaceContext.tsx +5 -8
- package/client/lib/WorkspaceLayoutContext.tsx +30 -10
- package/client/lib/applet-cache.ts +54 -0
- package/client/lib/connection.ts +237 -0
- package/client/lib/flags.ts +10 -0
- package/client/lib/mcp-icons.ts +142 -10
- package/client/lib/preview-turn.ts +37 -0
- package/client/lib/render-icon.ts +173 -0
- package/client/lib/scratch-executor.ts +20 -0
- package/client/lib/uploads.ts +18 -0
- package/client/main.tsx +5 -0
- package/client/store/live.ts +282 -0
- package/client/structured-clone-shim.ts +14 -0
- package/client/theme.css +2 -2
- package/client/vendor/emojibase/en/data.json +1 -0
- package/client/vendor/emojibase/en/messages.json +1 -0
- package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
- package/client/vendor/react/development/_impl/react-dom.js +223 -0
- package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
- package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
- package/client/vendor/react/development/_impl/react.js +863 -0
- package/client/vendor/react/development/react-dom-client.js +6 -0
- package/client/vendor/react/development/react-dom.js +17 -0
- package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
- package/client/vendor/react/development/react-jsx-runtime.js +6 -0
- package/client/vendor/react/development/react.js +47 -0
- package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
- package/client/vendor/react/production/_impl/react-dom.js +184 -0
- package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
- package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
- package/client/vendor/react/production/_impl/react.js +428 -0
- package/client/vendor/react/production/react-dom-client.js +6 -0
- package/client/vendor/react/production/react-dom.js +17 -0
- package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
- package/client/vendor/react/production/react-jsx-runtime.js +6 -0
- package/client/vendor/react/production/react.js +47 -0
- package/dist/agentation-4s0nn45p.png +0 -0
- package/dist/airtable-hsa66v6q.png +0 -0
- package/dist/apollo-2ed5dy2d.png +0 -0
- package/dist/asana-tvgtwbx2.png +0 -0
- package/dist/box-w3n36t5g.png +0 -0
- package/dist/chrome-tspm94rw.svg +33 -0
- package/dist/chunk-kc6e9nd4.css +1 -0
- package/dist/chunk-yf3p7qg7.js +673 -0
- package/dist/clickup-qqrqqvqb.png +0 -0
- package/dist/cloudflare-j9p931v6.png +0 -0
- package/dist/context7-8ht0xjfy.png +0 -0
- package/dist/datadog-70ne3yzt.png +0 -0
- package/dist/dropbox-4m5s9mgr.png +0 -0
- package/dist/elevenlabs-2nzzej1t.png +0 -0
- package/dist/exa-qqj3vr0x.png +0 -0
- package/dist/firecrawl-w2t8nehx.png +0 -0
- package/dist/gmail-sg6a5v3x.png +0 -0
- package/dist/googlecalendar-nqhh2v7r.png +0 -0
- package/dist/googledrive-6s8xyab7.png +0 -0
- package/dist/grafana-1yfsnwr6.png +0 -0
- package/dist/huggingface-kxzaxj83.png +0 -0
- package/dist/index.html +10 -6
- package/dist/intercom-td763jt8.png +0 -0
- package/dist/monday-jdbs4wwf.png +0 -0
- package/dist/mongodb-emzxvhd5.png +0 -0
- package/dist/paper-zbt34fab.png +0 -0
- package/dist/paypal-kwwf7xsc.png +0 -0
- package/dist/perplexity-4y63rxvj.png +0 -0
- package/dist/postgresql-qsspbsr1.png +0 -0
- package/dist/posthog-sphppc4w.png +0 -0
- package/dist/puppeteer-2xjt1a9b.png +0 -0
- package/dist/railway-834de8d2.png +0 -0
- package/dist/redis-spm6w2m1.png +0 -0
- package/dist/salesforce-1mk56v4z.png +0 -0
- package/dist/shopify-90dadaav.png +0 -0
- package/dist/snowflake-hfpykpgy.png +0 -0
- package/dist/telegram-v6tjyrs7.png +0 -0
- package/dist/twilio-dpyjdwpj.png +0 -0
- package/dist/zapier-p67qfch0.png +0 -0
- package/lib/attachment-note.ts +48 -0
- package/lib/claude-adapter.ts +219 -29
- package/lib/format.ts +32 -0
- package/lib/types.ts +314 -6
- package/package.json +11 -5
- package/server/CLAUDE.md +4 -1
- package/server/agent.ts +25 -118
- package/server/api.ts +593 -0
- package/server/applets.ts +396 -0
- package/server/build-applet.ts +580 -0
- package/server/cc-session.ts +611 -0
- package/server/cli-colors.ts +17 -0
- package/server/cli-ui.ts +52 -0
- package/server/cli.ts +965 -73
- package/server/constants.ts +1 -1
- package/server/control.ts +166 -19
- package/server/debug.ts +10 -0
- package/server/events.ts +24 -0
- package/server/functions-worker.ts +18 -2
- package/server/functions.ts +59 -12
- package/server/icon.ts +13 -0
- package/server/layout.ts +25 -3
- package/server/mcp.ts +125 -0
- package/server/moi-scaffold.ts +85 -0
- package/server/openclaw-session.ts +41 -10
- package/server/openclaw.ts +22 -0
- package/server/preview.ts +70 -0
- package/server/registry.ts +32 -2
- package/server/scratchpad-executor.ts +380 -0
- package/server/scratchpad-relay.ts +45 -0
- package/server/scratchpad.ts +171 -0
- package/server/skill-version.ts +146 -0
- package/server/skills-template.ts +6 -1
- package/server/state.ts +22 -36
- package/server/static.ts +23 -0
- package/server/status.ts +94 -0
- package/server/thread-config.ts +125 -0
- package/server/uploads.ts +0 -0
- package/server/vendor.ts +63 -0
- package/server/views.ts +0 -0
- package/server/web.ts +108 -253
- package/server/widgets.ts +52 -142
- package/server/workspace-config.ts +37 -0
- package/server/workspace-env.ts +407 -0
- package/server/workspace-init.ts +66 -0
- package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
- package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
- package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
- package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
- package/client/hooks/useWidget.ts +0 -72
- package/client/hooks/useWidgetList.ts +0 -30
- package/client/lib/ws.ts +0 -129
- package/client/store/chat.tsx +0 -162
- package/dist/chunk-4615fa69.js +0 -67
- package/dist/chunk-582xmy05.css +0 -1
- package/server/build-widget.ts +0 -343
- package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
- package/workspace/.claude/skills/widgets/SKILL.md +0 -176
|
@@ -0,0 +1,611 @@
|
|
|
1
|
+
// Live Claude Code sessions held open in the server process.
|
|
2
|
+
//
|
|
3
|
+
// Each (workspaceId, sessionId) gets ONE long-lived `query()` running in
|
|
4
|
+
// streaming-input mode: a single agent session that consumes user messages from
|
|
5
|
+
// an in-memory queue and streams output to all connected clients. Follow-up
|
|
6
|
+
// messages (and messages from multiple browser tabs) are pushed into the same
|
|
7
|
+
// queue — so they're *queued* instead of rejected, and there's no cold `resume`
|
|
8
|
+
// between turns.
|
|
9
|
+
//
|
|
10
|
+
// Disk stays the source of truth: the SDK persists each block to the session
|
|
11
|
+
// `.jsonl` incrementally, so a (re)connecting client reads /events then folds
|
|
12
|
+
// live deltas. If a session is idle-evicted (or lost on a server restart), the
|
|
13
|
+
// next message recreates it with `resume` — transparently.
|
|
14
|
+
import {
|
|
15
|
+
type Options,
|
|
16
|
+
type Query,
|
|
17
|
+
type SDKUserMessage,
|
|
18
|
+
query
|
|
19
|
+
} from '@anthropic-ai/claude-agent-sdk'
|
|
20
|
+
|
|
21
|
+
import { ATTACHMENT_ONLY_PLACEHOLDER, appendAttachmentNote } from '@/lib/attachment-note'
|
|
22
|
+
import { ClaudeAdapter } from '@/lib/claude-adapter'
|
|
23
|
+
import type { Part } from '@/lib/format'
|
|
24
|
+
|
|
25
|
+
import { debug } from './debug'
|
|
26
|
+
import { broadcast } from './state'
|
|
27
|
+
import { hasThreadConfig, renameThreadConfig, saveThreadConfig } from './thread-config'
|
|
28
|
+
import { type StoredUpload, resolveUploads, uploadToDisplayPart } from './uploads'
|
|
29
|
+
import { resolveWorkspaceEnv } from './workspace-env'
|
|
30
|
+
|
|
31
|
+
// Media types Claude vision accepts; uploads.ts guarantees every image upload is
|
|
32
|
+
// normalized to one of these, so the cast on `media_type` below is sound.
|
|
33
|
+
type ImageMediaType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp'
|
|
34
|
+
|
|
35
|
+
// What the SDK's streaming-input prompt accepts for one message's content:
|
|
36
|
+
// a plain string or an array of Anthropic content blocks (text/image/…).
|
|
37
|
+
type MessageContent = SDKUserMessage['message']['content']
|
|
38
|
+
|
|
39
|
+
// Turn a typed text + resolved uploads into (a) the content the agent receives
|
|
40
|
+
// and (b) the display parts we broadcast for the user's bubble. Images become
|
|
41
|
+
// base64 vision blocks; other files are referenced by their temp path so the
|
|
42
|
+
// agent can Read them. Display text stays the user's text (no path note).
|
|
43
|
+
// Exported for unit tests.
|
|
44
|
+
export function buildUserMessage(
|
|
45
|
+
text: string,
|
|
46
|
+
uploads: StoredUpload[]
|
|
47
|
+
): { content: MessageContent; parts: Part[] } {
|
|
48
|
+
const parts: Part[] = []
|
|
49
|
+
for (const u of uploads) {
|
|
50
|
+
const part = uploadToDisplayPart(u)
|
|
51
|
+
if (part) parts.push(part)
|
|
52
|
+
}
|
|
53
|
+
if (text) parts.push({ type: 'text', text })
|
|
54
|
+
|
|
55
|
+
if (uploads.length === 0) return { content: text, parts }
|
|
56
|
+
|
|
57
|
+
const blocks: Exclude<MessageContent, string> = []
|
|
58
|
+
for (const u of uploads) {
|
|
59
|
+
if (u.kind === 'image' && u.data) {
|
|
60
|
+
blocks.push({
|
|
61
|
+
type: 'image',
|
|
62
|
+
source: {
|
|
63
|
+
type: 'base64',
|
|
64
|
+
media_type: u.mediaType as ImageMediaType,
|
|
65
|
+
data: u.data.toString('base64')
|
|
66
|
+
}
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const files = uploads.filter(u => u.kind === 'file' && u.path)
|
|
72
|
+
const agentText = appendAttachmentNote(
|
|
73
|
+
text,
|
|
74
|
+
files.map(f => ({ filename: f.filename, path: f.path! }))
|
|
75
|
+
)
|
|
76
|
+
// Always end with a text block so an image-only message still has a prompt.
|
|
77
|
+
blocks.push({ type: 'text', text: agentText || ATTACHMENT_ONLY_PLACEHOLDER })
|
|
78
|
+
return { content: blocks, parts }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Cap on concurrently-held live sessions (each = one claude subprocess). When
|
|
82
|
+
// exceeded, the least-recently-active IDLE session is closed; a busy session is
|
|
83
|
+
// never evicted. Idle sessions are also closed after this TTL.
|
|
84
|
+
const MAX_LIVE_SESSIONS = 8
|
|
85
|
+
const IDLE_TTL_MS = 5 * 60_000
|
|
86
|
+
|
|
87
|
+
const ALLOWED_TOOLS = [
|
|
88
|
+
'Bash',
|
|
89
|
+
'Read',
|
|
90
|
+
'Write',
|
|
91
|
+
'Edit',
|
|
92
|
+
'MultiEdit',
|
|
93
|
+
'Glob',
|
|
94
|
+
'Grep',
|
|
95
|
+
'WebSearch',
|
|
96
|
+
'WebFetch'
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
type InputQueue = {
|
|
100
|
+
iterator: AsyncGenerator<SDKUserMessage>
|
|
101
|
+
push: (content: MessageContent) => void
|
|
102
|
+
clear: () => void
|
|
103
|
+
close: () => void
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
type LiveSession = {
|
|
107
|
+
workspaceId: string
|
|
108
|
+
workspacePath: string
|
|
109
|
+
sessionId: string // current real id (rekeyed on rename)
|
|
110
|
+
q: Query
|
|
111
|
+
adapter: ClaudeAdapter
|
|
112
|
+
input: InputQueue
|
|
113
|
+
abort: AbortController
|
|
114
|
+
// User messages enqueued but not yet completed. A turn ends on a `result`
|
|
115
|
+
// message; processing = pendingTurns > 0.
|
|
116
|
+
pendingTurns: number
|
|
117
|
+
model: string | undefined
|
|
118
|
+
// Reasoning effort the query was created with. The SDK has no live setter for
|
|
119
|
+
// it (unlike setModel), so a change tears the session down and resumes.
|
|
120
|
+
effort: string | undefined
|
|
121
|
+
// Effort the latest message asked for. When it diverges from `effort` while a
|
|
122
|
+
// turn is in flight (can't rebuild mid-turn), the session is torn down once it
|
|
123
|
+
// drains so the next message resumes with the requested effort.
|
|
124
|
+
desiredEffort: string | undefined
|
|
125
|
+
// Whether this query was built with `includePartialMessages` (live token
|
|
126
|
+
// streaming). Like effort, it's a construct-time option with no live setter,
|
|
127
|
+
// so a change tears the session down and resumes.
|
|
128
|
+
stream: boolean
|
|
129
|
+
// Streaming mode the latest message asked for; drives the same drain-then-
|
|
130
|
+
// rebuild path as `desiredEffort` when it diverges mid-turn.
|
|
131
|
+
desiredStream: boolean
|
|
132
|
+
idleTimer: ReturnType<typeof setTimeout> | null
|
|
133
|
+
closed: boolean
|
|
134
|
+
// Introspection only (surfaced by /status) — not load-bearing.
|
|
135
|
+
createdAt: number
|
|
136
|
+
lastActivityAt: number
|
|
137
|
+
lastUserText: string | undefined
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const sessions = new Map<string, LiveSession>()
|
|
141
|
+
// `${workspaceId}:${tempId}` -> real session id. A new thread is created under
|
|
142
|
+
// the client's temporary id, then renamed to the SDK's real id on init. A
|
|
143
|
+
// follow-up queued in the window before the client learns the new id still
|
|
144
|
+
// carries the temp id; this alias re-routes it to the live session instead of
|
|
145
|
+
// spawning a duplicate. Temp ids are UUIDs, so stale entries never collide.
|
|
146
|
+
const aliases = new Map<string, string>()
|
|
147
|
+
|
|
148
|
+
function recKey(workspaceId: string, sessionId: string): string {
|
|
149
|
+
return `${workspaceId}:${sessionId}`
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Resolve the live-session key for a (workspaceId, sessionId), following a
|
|
153
|
+
// temp->real alias when the direct key isn't live.
|
|
154
|
+
function liveKey(workspaceId: string, sessionId: string): string {
|
|
155
|
+
const direct = recKey(workspaceId, sessionId)
|
|
156
|
+
if (sessions.has(direct)) return direct
|
|
157
|
+
const real = aliases.get(direct)
|
|
158
|
+
return real ? recKey(workspaceId, real) : direct
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Running sessions across all workspaces, for the connect-time status snapshot.
|
|
162
|
+
export function getCCRunningSessions(): { workspaceId: string; sessionId: string }[] {
|
|
163
|
+
const out: { workspaceId: string; sessionId: string }[] = []
|
|
164
|
+
for (const s of sessions.values()) {
|
|
165
|
+
if (s.pendingTurns > 0) out.push({ workspaceId: s.workspaceId, sessionId: s.sessionId })
|
|
166
|
+
}
|
|
167
|
+
return out
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Caps surfaced in /status so the numbers there are self-explanatory.
|
|
171
|
+
export const SESSION_LIMITS = { maxLive: MAX_LIVE_SESSIONS, idleTtlMs: IDLE_TTL_MS }
|
|
172
|
+
|
|
173
|
+
export type CCDebugSession = {
|
|
174
|
+
workspaceId: string
|
|
175
|
+
sessionId: string
|
|
176
|
+
model: string | undefined
|
|
177
|
+
effort: string | undefined
|
|
178
|
+
desiredEffort: string | undefined
|
|
179
|
+
stream: boolean
|
|
180
|
+
desiredStream: boolean
|
|
181
|
+
pendingTurns: number
|
|
182
|
+
busy: boolean
|
|
183
|
+
closed: boolean
|
|
184
|
+
hasIdleTimer: boolean
|
|
185
|
+
createdAt: number
|
|
186
|
+
lastActivityAt: number
|
|
187
|
+
lastUserText: string | undefined
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// A full snapshot of the in-memory live-session registry, for the /status page.
|
|
191
|
+
// Read-only — never mutate the returned objects.
|
|
192
|
+
export function getCCDebugSnapshot(): { sessions: CCDebugSession[]; aliases: number } {
|
|
193
|
+
return {
|
|
194
|
+
sessions: [...sessions.values()].map(s => ({
|
|
195
|
+
workspaceId: s.workspaceId,
|
|
196
|
+
sessionId: s.sessionId,
|
|
197
|
+
model: s.model,
|
|
198
|
+
effort: s.effort,
|
|
199
|
+
desiredEffort: s.desiredEffort,
|
|
200
|
+
stream: s.stream,
|
|
201
|
+
desiredStream: s.desiredStream,
|
|
202
|
+
pendingTurns: s.pendingTurns,
|
|
203
|
+
busy: s.pendingTurns > 0,
|
|
204
|
+
closed: s.closed,
|
|
205
|
+
hasIdleTimer: s.idleTimer !== null,
|
|
206
|
+
createdAt: s.createdAt,
|
|
207
|
+
lastActivityAt: s.lastActivityAt,
|
|
208
|
+
lastUserText: s.lastUserText
|
|
209
|
+
})),
|
|
210
|
+
aliases: aliases.size
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// A push-able async generator used as the streaming-input prompt: it yields
|
|
215
|
+
// queued user messages and awaits when empty, so the session stays open between
|
|
216
|
+
// turns instead of ending when the current input is consumed.
|
|
217
|
+
function createInputQueue(): InputQueue {
|
|
218
|
+
const buffer: SDKUserMessage[] = []
|
|
219
|
+
let wake: (() => void) | null = null
|
|
220
|
+
let closed = false
|
|
221
|
+
|
|
222
|
+
async function* gen(): AsyncGenerator<SDKUserMessage> {
|
|
223
|
+
while (true) {
|
|
224
|
+
if (buffer.length === 0) {
|
|
225
|
+
if (closed) return
|
|
226
|
+
await new Promise<void>(resolve => {
|
|
227
|
+
wake = resolve
|
|
228
|
+
})
|
|
229
|
+
if (closed && buffer.length === 0) return
|
|
230
|
+
}
|
|
231
|
+
while (buffer.length) yield buffer.shift()!
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
iterator: gen(),
|
|
237
|
+
push(content: MessageContent) {
|
|
238
|
+
buffer.push({
|
|
239
|
+
type: 'user',
|
|
240
|
+
message: { role: 'user', content },
|
|
241
|
+
parent_tool_use_id: null
|
|
242
|
+
})
|
|
243
|
+
wake?.()
|
|
244
|
+
wake = null
|
|
245
|
+
},
|
|
246
|
+
clear() {
|
|
247
|
+
buffer.length = 0
|
|
248
|
+
},
|
|
249
|
+
close() {
|
|
250
|
+
closed = true
|
|
251
|
+
wake?.()
|
|
252
|
+
wake = null
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function broadcastProcessing(s: LiveSession, processing: boolean) {
|
|
258
|
+
broadcast(s.workspaceId, { type: 'status', sessionId: s.sessionId, processing })
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function clearIdle(s: LiveSession) {
|
|
262
|
+
if (s.idleTimer) {
|
|
263
|
+
clearTimeout(s.idleTimer)
|
|
264
|
+
s.idleTimer = null
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function armIdle(s: LiveSession) {
|
|
269
|
+
clearIdle(s)
|
|
270
|
+
s.idleTimer = setTimeout(() => {
|
|
271
|
+
if (s.pendingTurns === 0) teardown(s)
|
|
272
|
+
}, IDLE_TTL_MS)
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function teardown(s: LiveSession) {
|
|
276
|
+
if (s.closed) return
|
|
277
|
+
debug(`cc teardown ws=${s.workspaceId} session=${s.sessionId} pendingTurns=${s.pendingTurns}`)
|
|
278
|
+
s.closed = true
|
|
279
|
+
clearIdle(s)
|
|
280
|
+
s.input.close()
|
|
281
|
+
try {
|
|
282
|
+
s.q.close?.()
|
|
283
|
+
} catch {}
|
|
284
|
+
try {
|
|
285
|
+
s.abort.abort()
|
|
286
|
+
} catch {}
|
|
287
|
+
if (sessions.get(recKey(s.workspaceId, s.sessionId)) === s) {
|
|
288
|
+
sessions.delete(recKey(s.workspaceId, s.sessionId))
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// On `system/init` the SDK reports the real session id. For a brand-new session
|
|
293
|
+
// that differs from the client's temporary id, so we rekey the registry and
|
|
294
|
+
// tell the client to move its optimistic state. Subsequent inits report the
|
|
295
|
+
// same id and no-op.
|
|
296
|
+
function renameSession(s: LiveSession, realId: string) {
|
|
297
|
+
const from = s.sessionId
|
|
298
|
+
sessions.delete(recKey(s.workspaceId, from))
|
|
299
|
+
s.sessionId = realId
|
|
300
|
+
sessions.set(recKey(s.workspaceId, realId), s)
|
|
301
|
+
aliases.set(recKey(s.workspaceId, from), realId)
|
|
302
|
+
broadcast(s.workspaceId, { type: 'session_renamed', from, to: realId })
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async function consume(s: LiveSession) {
|
|
306
|
+
try {
|
|
307
|
+
for await (const msg of s.q) {
|
|
308
|
+
if (msg.type === 'system' && msg.subtype === 'init') {
|
|
309
|
+
const realId = msg.session_id
|
|
310
|
+
if (realId && realId !== s.sessionId) {
|
|
311
|
+
const from = s.sessionId
|
|
312
|
+
renameSession(s, realId)
|
|
313
|
+
// Carry any config the picker wrote under the temp id to the real id.
|
|
314
|
+
await renameThreadConfig(s.workspacePath, from, s.sessionId)
|
|
315
|
+
}
|
|
316
|
+
// Seed the thread's config from what it actually ran with — but only if
|
|
317
|
+
// it has none yet, so an explicit user PUT (or a migrated temp-id edit)
|
|
318
|
+
// always wins. A default run (no model/effort) leaves no file and falls
|
|
319
|
+
// back to the workspace defaults.
|
|
320
|
+
if ((s.model || s.effort) && !(await hasThreadConfig(s.workspacePath, s.sessionId))) {
|
|
321
|
+
await saveThreadConfig(s.workspacePath, s.sessionId, {
|
|
322
|
+
model: s.model,
|
|
323
|
+
effort: s.effort
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
for (const ev of s.adapter.ingest(msg)) {
|
|
328
|
+
if (ev.kind === 'preview') {
|
|
329
|
+
// Live-only token preview — a sibling frame, never a StreamEvent, so
|
|
330
|
+
// it never enters the persisted/replayable transcript path.
|
|
331
|
+
broadcast(s.workspaceId, {
|
|
332
|
+
type: 'preview',
|
|
333
|
+
sessionId: s.sessionId,
|
|
334
|
+
messageId: ev.preview.messageId,
|
|
335
|
+
parentToolUseId: ev.preview.parentToolUseId,
|
|
336
|
+
blocks: ev.preview.blocks
|
|
337
|
+
})
|
|
338
|
+
} else {
|
|
339
|
+
broadcast(s.workspaceId, { ...ev, sessionId: s.sessionId })
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (msg.type === 'system' && msg.subtype === 'init') {
|
|
343
|
+
debug(`cc init ws=${s.workspaceId} session=${s.sessionId}`)
|
|
344
|
+
}
|
|
345
|
+
if (msg.type === 'result') {
|
|
346
|
+
s.lastActivityAt = Date.now()
|
|
347
|
+
s.pendingTurns = Math.max(0, s.pendingTurns - 1)
|
|
348
|
+
debug(`cc result ws=${s.workspaceId} session=${s.sessionId} pendingTurns=${s.pendingTurns}`)
|
|
349
|
+
if (s.pendingTurns === 0) {
|
|
350
|
+
broadcastProcessing(s, false)
|
|
351
|
+
// A mid-turn effort/streaming change couldn't be applied live; now
|
|
352
|
+
// that the queue has drained, tear down so the next message resumes
|
|
353
|
+
// with it.
|
|
354
|
+
if (s.desiredEffort !== s.effort || s.desiredStream !== s.stream) teardown(s)
|
|
355
|
+
else armIdle(s)
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
} catch (err) {
|
|
360
|
+
debug(
|
|
361
|
+
`cc consume error ws=${s.workspaceId} session=${s.sessionId}: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`
|
|
362
|
+
)
|
|
363
|
+
if (!(err instanceof Error && err.name === 'AbortError')) {
|
|
364
|
+
broadcast(s.workspaceId, {
|
|
365
|
+
kind: 'error',
|
|
366
|
+
sessionId: s.sessionId,
|
|
367
|
+
content: err instanceof Error ? err.message : 'Unknown error'
|
|
368
|
+
})
|
|
369
|
+
}
|
|
370
|
+
} finally {
|
|
371
|
+
if (s.pendingTurns > 0) {
|
|
372
|
+
s.pendingTurns = 0
|
|
373
|
+
broadcastProcessing(s, false)
|
|
374
|
+
}
|
|
375
|
+
teardown(s)
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Close one idle session to stay under the cap. A busy session is never evicted;
|
|
380
|
+
// if everything is busy we allow a temporary overflow rather than killing a run.
|
|
381
|
+
function evictIfNeeded() {
|
|
382
|
+
if (sessions.size < MAX_LIVE_SESSIONS) return
|
|
383
|
+
for (const s of sessions.values()) {
|
|
384
|
+
if (s.pendingTurns === 0) {
|
|
385
|
+
teardown(s)
|
|
386
|
+
return
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function createLiveSession(input: {
|
|
392
|
+
workspaceId: string
|
|
393
|
+
workspacePath: string
|
|
394
|
+
sessionId: string
|
|
395
|
+
isNew: boolean
|
|
396
|
+
model: string | undefined
|
|
397
|
+
effort: string | undefined
|
|
398
|
+
// Live token streaming (`includePartialMessages`). Only enabled when the
|
|
399
|
+
// client opts in; off leaves the query byte-for-byte as before.
|
|
400
|
+
stream: boolean
|
|
401
|
+
// Resolved workspace env (.env + UI custom overrides), injected so the agent's
|
|
402
|
+
// Bash tool can use workspace secrets. Frozen at spawn — see restartWorkspaceSessions.
|
|
403
|
+
workspaceEnv: Record<string, string>
|
|
404
|
+
}): LiveSession {
|
|
405
|
+
evictIfNeeded()
|
|
406
|
+
|
|
407
|
+
const queue = createInputQueue()
|
|
408
|
+
const abort = new AbortController()
|
|
409
|
+
const options: Options = {
|
|
410
|
+
abortController: abort,
|
|
411
|
+
// Generous: one query() spans the whole live session (many turns). On end
|
|
412
|
+
// (limit hit / closed / error) the session is torn down and the next
|
|
413
|
+
// message recreates it via resume.
|
|
414
|
+
maxTurns: 1000,
|
|
415
|
+
cwd: input.workspacePath,
|
|
416
|
+
// Current-gen models (Sonnet 5, Opus 4.7/4.8, Fable 5) default thinking
|
|
417
|
+
// display to 'omitted' — the API still emits a `thinking` block but with
|
|
418
|
+
// empty text, which the adapter drops (`if (b.thinking)`), so no
|
|
419
|
+
// "Thinking" row ever reaches the timeline. Request the summary
|
|
420
|
+
// explicitly so reasoning stays visible.
|
|
421
|
+
thinking: { type: 'adaptive', display: 'summarized' },
|
|
422
|
+
...(input.model ? { model: input.model } : {}),
|
|
423
|
+
// The picker only offers a model's own `supportedEffortLevels`, so the value
|
|
424
|
+
// is valid for the model; the SDK silently downgrades otherwise. Cast because
|
|
425
|
+
// the SDK under-types the union (no 'xhigh') vs our pass-through string.
|
|
426
|
+
...(input.effort ? { effort: input.effort as Options['effort'] } : {}),
|
|
427
|
+
// Emit `stream_event` partial-message frames so the adapter can surface a
|
|
428
|
+
// live token-by-token preview. Off = unchanged behavior (whole blocks only).
|
|
429
|
+
includePartialMessages: input.stream,
|
|
430
|
+
allowedTools: ALLOWED_TOOLS,
|
|
431
|
+
permissionMode: 'bypassPermissions',
|
|
432
|
+
allowDangerouslySkipPermissions: true,
|
|
433
|
+
settingSources: ['user', 'project'],
|
|
434
|
+
env: { ...process.env, ...input.workspaceEnv, CLAUDECODE: undefined },
|
|
435
|
+
stderr: (data: string) => console.error('[SDK stderr]', data)
|
|
436
|
+
}
|
|
437
|
+
if (!input.isNew) options.resume = input.sessionId
|
|
438
|
+
|
|
439
|
+
const session: LiveSession = {
|
|
440
|
+
workspaceId: input.workspaceId,
|
|
441
|
+
workspacePath: input.workspacePath,
|
|
442
|
+
sessionId: input.sessionId,
|
|
443
|
+
q: query({ prompt: queue.iterator, options }),
|
|
444
|
+
adapter: new ClaudeAdapter(),
|
|
445
|
+
input: queue,
|
|
446
|
+
abort,
|
|
447
|
+
pendingTurns: 0,
|
|
448
|
+
model: input.model,
|
|
449
|
+
effort: input.effort,
|
|
450
|
+
desiredEffort: input.effort,
|
|
451
|
+
stream: input.stream,
|
|
452
|
+
desiredStream: input.stream,
|
|
453
|
+
idleTimer: null,
|
|
454
|
+
closed: false,
|
|
455
|
+
createdAt: Date.now(),
|
|
456
|
+
lastActivityAt: Date.now(),
|
|
457
|
+
lastUserText: undefined
|
|
458
|
+
}
|
|
459
|
+
sessions.set(recKey(session.workspaceId, session.sessionId), session)
|
|
460
|
+
debug(
|
|
461
|
+
`cc create ${input.isNew ? 'new' : 'resume'} ws=${input.workspaceId} session=${input.sessionId} model=${input.model ?? 'default'} effort=${input.effort ?? 'default'} live=${sessions.size}`
|
|
462
|
+
)
|
|
463
|
+
void consume(session)
|
|
464
|
+
return session
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Enqueue a user message into the thread's live session, creating it on first
|
|
468
|
+
// use. Safe to call while a turn is in flight — the message is queued.
|
|
469
|
+
export async function sendCCMessage(input: {
|
|
470
|
+
workspaceId: string
|
|
471
|
+
workspacePath: string
|
|
472
|
+
sessionId: string
|
|
473
|
+
isNew: boolean
|
|
474
|
+
content: string
|
|
475
|
+
// Upload ids attached to this turn (resolved from the upload store here).
|
|
476
|
+
attachments?: string[]
|
|
477
|
+
optimisticId?: string
|
|
478
|
+
model?: string
|
|
479
|
+
effort?: string
|
|
480
|
+
stream?: boolean
|
|
481
|
+
}): Promise<void> {
|
|
482
|
+
// Resolve any attachments into agent content blocks + display parts. Unknown
|
|
483
|
+
// or expired ids are silently dropped (resolveUploads filters them) — if that
|
|
484
|
+
// leaves nothing to say at all, don't spin up a session for an empty turn.
|
|
485
|
+
const uploads = input.attachments?.length
|
|
486
|
+
? resolveUploads(input.workspaceId, input.attachments)
|
|
487
|
+
: []
|
|
488
|
+
if (!input.content && uploads.length === 0) return
|
|
489
|
+
const { content, parts } = buildUserMessage(input.content, uploads)
|
|
490
|
+
|
|
491
|
+
const wantStream = input.stream === true
|
|
492
|
+
let s = sessions.get(liveKey(input.workspaceId, input.sessionId))
|
|
493
|
+
// Neither effort nor streaming can be changed on a running query (both are
|
|
494
|
+
// construct-time, no SDK setter), so when either differs we tear the idle
|
|
495
|
+
// session down and recreate it via resume — the change lands on this very
|
|
496
|
+
// turn. A busy session keeps its settings until the in-flight turn ends.
|
|
497
|
+
if (s && (input.effort !== s.effort || wantStream !== s.stream) && s.pendingTurns === 0) {
|
|
498
|
+
teardown(s)
|
|
499
|
+
s = undefined
|
|
500
|
+
}
|
|
501
|
+
if (s) {
|
|
502
|
+
clearIdle(s)
|
|
503
|
+
if (input.model !== s.model) {
|
|
504
|
+
try {
|
|
505
|
+
await s.q.setModel(input.model)
|
|
506
|
+
s.model = input.model
|
|
507
|
+
} catch (err) {
|
|
508
|
+
console.error('[cc-session] setModel failed', err)
|
|
509
|
+
}
|
|
510
|
+
// setModel is a control round-trip to the subprocess. During that await a
|
|
511
|
+
// concurrent turn `result` can drain this session to idle and — if effort
|
|
512
|
+
// or streaming diverged — tear it down (see the `result` handler). If that
|
|
513
|
+
// happened, drop the dead handle and fall through to recreate a fresh
|
|
514
|
+
// session below, rather than enqueue onto a closed input queue (which would
|
|
515
|
+
// silently lose the message and hang the spinner).
|
|
516
|
+
if (s.closed) s = undefined
|
|
517
|
+
}
|
|
518
|
+
if (s) {
|
|
519
|
+
// Effort/streaming can't change on a running query; record the request so
|
|
520
|
+
// the session rebuilds once its turns drain (see the `result` handler).
|
|
521
|
+
// Reaching here with a divergent value means the session is busy — an idle
|
|
522
|
+
// one was torn down above.
|
|
523
|
+
s.desiredEffort = input.effort
|
|
524
|
+
s.desiredStream = wantStream
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (!s) {
|
|
528
|
+
s = createLiveSession({
|
|
529
|
+
workspaceId: input.workspaceId,
|
|
530
|
+
workspacePath: input.workspacePath,
|
|
531
|
+
sessionId: input.sessionId,
|
|
532
|
+
isNew: input.isNew,
|
|
533
|
+
model: input.model,
|
|
534
|
+
effort: input.effort,
|
|
535
|
+
stream: wantStream,
|
|
536
|
+
// The agent only sees secrets scoped to the 'agent' sink (plus .env).
|
|
537
|
+
workspaceEnv: await resolveWorkspaceEnv(input.workspacePath, 'agent')
|
|
538
|
+
})
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// Streaming-input mode does NOT echo the pushed user message back in the
|
|
542
|
+
// output stream (string-prompt mode did — that's what expectUserEcho was
|
|
543
|
+
// for), so the adapter never emits a user turn. Synthesize and broadcast it
|
|
544
|
+
// ourselves so EVERY connected tab shows the user's bubble — not just the
|
|
545
|
+
// sender (which inserts it optimistically). Keyed by optimisticId, so the
|
|
546
|
+
// sender's optimistic turn upserts in place rather than duplicating.
|
|
547
|
+
const turnId = input.optimisticId ?? crypto.randomUUID()
|
|
548
|
+
broadcast(s.workspaceId, {
|
|
549
|
+
kind: 'turn',
|
|
550
|
+
sessionId: s.sessionId,
|
|
551
|
+
turn: {
|
|
552
|
+
id: turnId,
|
|
553
|
+
role: 'user',
|
|
554
|
+
origin: { kind: 'user-input' },
|
|
555
|
+
parts,
|
|
556
|
+
timestamp: new Date().toISOString()
|
|
557
|
+
}
|
|
558
|
+
})
|
|
559
|
+
// Safety net: if a future SDK does echo the user message, the adapter re-ids
|
|
560
|
+
// that echo to the same optimisticId so it collapses onto the turn above
|
|
561
|
+
// instead of duplicating.
|
|
562
|
+
if (input.optimisticId) s.adapter.expectUserEcho(input.optimisticId, input.content)
|
|
563
|
+
|
|
564
|
+
s.lastActivityAt = Date.now()
|
|
565
|
+
// For an attachment-only message, fall back to the filenames so the thread
|
|
566
|
+
// list / status view don't show a blank label.
|
|
567
|
+
const label = input.content || uploads.map(u => u.filename).join(', ')
|
|
568
|
+
s.lastUserText = label.replace(/\s+/g, ' ').slice(0, 120)
|
|
569
|
+
|
|
570
|
+
const wasIdle = s.pendingTurns === 0
|
|
571
|
+
s.pendingTurns++
|
|
572
|
+
if (wasIdle) broadcastProcessing(s, true)
|
|
573
|
+
s.input.push(content)
|
|
574
|
+
debug(
|
|
575
|
+
`cc enqueue ws=${s.workspaceId} session=${s.sessionId} pendingTurns=${s.pendingTurns} text=${JSON.stringify(s.lastUserText)}`
|
|
576
|
+
)
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// Interrupt the current turn and drop any queued messages, but keep the session
|
|
580
|
+
// alive for the next message.
|
|
581
|
+
export async function interruptCCSession(workspaceId: string, sessionId: string): Promise<void> {
|
|
582
|
+
const s = sessions.get(liveKey(workspaceId, sessionId))
|
|
583
|
+
if (!s) return
|
|
584
|
+
debug(`cc interrupt ws=${workspaceId} session=${sessionId} pendingTurns=${s.pendingTurns}`)
|
|
585
|
+
s.input.clear()
|
|
586
|
+
try {
|
|
587
|
+
await s.q.interrupt()
|
|
588
|
+
} catch (err) {
|
|
589
|
+
console.error('[cc-session] interrupt failed', err)
|
|
590
|
+
}
|
|
591
|
+
s.pendingTurns = 0
|
|
592
|
+
broadcast(s.workspaceId, { kind: 'stopped', sessionId: s.sessionId })
|
|
593
|
+
broadcastProcessing(s, false)
|
|
594
|
+
armIdle(s)
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// Tear down a workspace's IDLE sessions so the next message respawns the agent
|
|
598
|
+
// with fresh env. A running claude subprocess can't pick up new env vars, and
|
|
599
|
+
// mid-turn reload isn't supported — busy sessions keep their snapshot until the
|
|
600
|
+
// turn ends (then idle-evict or get recreated on the next message via resume).
|
|
601
|
+
export function restartWorkspaceSessions(workspacePath: string): void {
|
|
602
|
+
for (const s of [...sessions.values()]) {
|
|
603
|
+
if (s.workspacePath === workspacePath && s.pendingTurns === 0) teardown(s)
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// Close every live session — called on server shutdown so no claude subprocess
|
|
608
|
+
// is orphaned.
|
|
609
|
+
export function killAllCCSessions(): void {
|
|
610
|
+
for (const s of [...sessions.values()]) teardown(s)
|
|
611
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Disable ANSI color when stdout is not a TTY — e.g. an agent capturing
|
|
2
|
+
// `moi scratch --help` through a pipe.
|
|
3
|
+
//
|
|
4
|
+
// citty colors its usage and error output *unconditionally*: its color helper
|
|
5
|
+
// keys off env vars (`NO_COLOR`/`TERM`/`CI`/`TEST`) and never checks `isTTY`, so
|
|
6
|
+
// without this an agent sees literal `[36m`/`[1m` escape noise instead of
|
|
7
|
+
// readable help. We set `NO_COLOR` here so citty's color helpers no-op. This
|
|
8
|
+
// module is imported *first* in `cli.ts` so it runs before citty's module is
|
|
9
|
+
// evaluated (citty computes its `noColor` flag once, at import time).
|
|
10
|
+
//
|
|
11
|
+
// picocolors (our own coloring) already auto-detects `isTTY`, so this only
|
|
12
|
+
// closes citty's gap. `FORCE_COLOR` and an explicit `NO_COLOR` are honored: if
|
|
13
|
+
// the user opted in or out of color, we leave their choice untouched.
|
|
14
|
+
|
|
15
|
+
if (!process.stdout.isTTY && !process.env.FORCE_COLOR && process.env.NO_COLOR == null) {
|
|
16
|
+
process.env.NO_COLOR = '1'
|
|
17
|
+
}
|
package/server/cli-ui.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Plain-text CLI formatting — borderless, alignment-only, no unconditional ANSI.
|
|
2
|
+
//
|
|
3
|
+
// moi's commands are run by an agent at least as often as by a human. cli-table3
|
|
4
|
+
// (the previous renderer) colored its borders and header cells *unconditionally*
|
|
5
|
+
// — even into a pipe — so an agent capturing `moi bundle 2>&1` got literal
|
|
6
|
+
// `[90m`/`[31m` escape noise instead of a readable table. These helpers render
|
|
7
|
+
// aligned columns/rows identically whether stdout is a TTY or a pipe.
|
|
8
|
+
//
|
|
9
|
+
// Cells stay color-agnostic: a caller may wrap a cell in picocolors (which
|
|
10
|
+
// no-ops when stdout isn't a TTY, so it never reaches the agent as noise) and
|
|
11
|
+
// alignment still holds — widths are measured on the *visible* text, with ANSI
|
|
12
|
+
// escapes stripped.
|
|
13
|
+
|
|
14
|
+
// eslint-disable-next-line no-control-regex
|
|
15
|
+
const ANSI_RE = /\x1b\[[0-9;]*m/g
|
|
16
|
+
|
|
17
|
+
function visibleWidth(s: string): number {
|
|
18
|
+
return s.replace(ANSI_RE, '').length
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function padEndVisible(s: string, width: number): string {
|
|
22
|
+
return s + ' '.repeat(Math.max(0, width - visibleWidth(s)))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// A borderless table: a header row plus body rows. Each cell is left-aligned to
|
|
26
|
+
// its column's widest value, columns separated by two spaces, every line
|
|
27
|
+
// indented. The last column is never padded (no trailing whitespace). Mirrors
|
|
28
|
+
// the `moi config` look.
|
|
29
|
+
export function columns(headers: string[], rows: string[][], indent = ' '): string {
|
|
30
|
+
const ncols = headers.length
|
|
31
|
+
const all = [headers, ...rows]
|
|
32
|
+
const widths = Array.from({ length: ncols }, (_, i) =>
|
|
33
|
+
Math.max(0, ...all.map(r => visibleWidth(r[i] ?? '')))
|
|
34
|
+
)
|
|
35
|
+
const renderRow = (cells: string[]): string => {
|
|
36
|
+
const out = Array.from({ length: ncols }, (_, i) => {
|
|
37
|
+
const cell = cells[i] ?? ''
|
|
38
|
+
return i === ncols - 1 ? cell : padEndVisible(cell, widths[i])
|
|
39
|
+
})
|
|
40
|
+
return (indent + out.join(' ')).replace(/\s+$/, '')
|
|
41
|
+
}
|
|
42
|
+
return [renderRow(headers), ...rows.map(renderRow)].join('\n')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Aligned key/value rows, like `moi config`'s identity block: keys padded to the
|
|
46
|
+
// widest key, two spaces between key and value, indented.
|
|
47
|
+
export function keyValue(rows: [string, string][], indent = ' '): string {
|
|
48
|
+
const keyWidth = Math.max(0, ...rows.map(([k]) => visibleWidth(k)))
|
|
49
|
+
return rows
|
|
50
|
+
.map(([k, v]) => (indent + padEndVisible(k, keyWidth) + ' ' + v).replace(/\s+$/, ''))
|
|
51
|
+
.join('\n')
|
|
52
|
+
}
|