-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathindex.ts
More file actions
577 lines (555 loc) · 20.4 KB
/
Copy pathindex.ts
File metadata and controls
577 lines (555 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// GRIDA-GG: desktop — the optional `gg` bridge namespace (docs/wg/platform/hosted-ai.md)
// GRIDA-SEC-008 — renderer-safe ChatGPT status/control DTOs only.
/**
* GRIDA-SEC-004 — renderer-visible Desktop bridge protocol.
*
* This package carries only the `window.grida` contract that a URL-loaded
* renderer may compile against. Electron IPC channel names and native
* implementation details stay in the Desktop app; daemon HTTP stays in
* `@grida/daemon/transport` + `@grida/agent/transport`.
*/
import type {
AgentRunOptions,
AgentUIMessageChunk,
ProviderId,
EndpointProviderConfig,
ProbedEndpointModel,
ImageGenerateRequest,
ImageGenerateResult,
VideoGenerateRequest,
VideoGenerateResult,
ThreeDGenerateRequest,
ThreeDGenerateResult,
MusicGenerateRequest,
MusicGenerateResult,
SoundEffectGenerateRequest,
SoundEffectGenerateResult,
TextToSpeechGenerateRequest,
TextToSpeechGenerateResult,
TextToSpeechListVoicesResult,
ChatMessageWithParts,
ChatSessionRow,
ChatGptSubscriptionStatus,
CreateSessionOptions,
PatchSessionOptions,
RewindResult,
SessionListFilter,
SessionListPage,
SessionStatus,
GridaGatewaySession,
GridaGatewaySessionStatus,
DirectoryScopeDescriptor,
} from "@grida/agent";
import type {
DaemonHandshakeResponse,
FileReadResult,
FileWriteResult,
MediaItem,
RecentEntry,
Workspace,
WorkspaceCreateInput,
WorkspaceFsEntry,
WorkspaceReadFileBytesResult,
WorkspaceReadFileResult,
WorkspaceWriteFileResult,
} from "@grida/daemon";
export const DESKTOP_BRIDGE_PROTOCOL = 1 as const;
export type DesktopNativeCapabilities = {
host_apps: boolean;
window: boolean;
dialog: boolean;
shell: boolean;
/**
* Human-interactive terminal (PTY) pane. Added after protocol 1
* shipped — renderers must treat a missing/falsy value as "old
* desktop binary, no terminal" and hide the surface.
*/
terminal: boolean;
/**
* Workspace file-change watcher (issue #805) — `workspaces.subscribe_changes`.
* Added after protocol 1 shipped; treat a missing/falsy value as "old
* desktop binary" and fall back to manual/pull refresh.
*/
workspace_watch: boolean;
};
export type DesktopAgentCapabilities = {
/**
* The host accepts base64 scratch seeds (`{ path, base64 }`) on agent runs.
* Added after protocol 1 shipped; renderers must treat a missing/falsy value
* as an old host that accepts text-only scratch seeds.
*/
scratch_seed_base64?: boolean;
/**
* The host exposes binary-operable tools for scratch-backed files (today,
* the confined `run_command` capability). Omission/false means a path-only
* PDF/archive/etc. would be inert, so renderers must not offer scratch-only
* arbitrary-byte attachments.
*/
scratch_binary_tools?: boolean;
};
export type DesktopCapabilities = {
native: DesktopNativeCapabilities;
/** Optional because protocol-1 hosts shipped before agent capabilities. */
agent?: DesktopAgentCapabilities;
};
export type HandshakeResponse = DaemonHandshakeResponse;
export type {
FileReadResult,
FileWriteResult,
MediaItem,
RecentEntry,
Workspace,
WorkspaceCreateInput,
WorkspaceFsEntry,
WorkspaceReadFileBytesResult,
WorkspaceReadFileResult,
WorkspaceWriteFileResult,
};
export type ConfirmOptions = {
message: string;
detail?: string;
buttons: string[];
default_id?: number;
cancel_id?: number;
};
export type FileFilter = { name: string; extensions: string[] };
export type OpenDialogOptions = {
default_path?: string;
filters?: FileFilter[];
properties?: Array<
"openFile" | "openDirectory" | "multiSelections" | "createDirectory"
>;
};
export type SaveDialogOptions = {
default_path?: string;
filters?: FileFilter[];
};
export type NavigationState = {
can_go_back: boolean;
can_go_forward: boolean;
};
export const DESKTOP_HOST_APP_IDS = [
"finder",
"vscode",
"cursor",
"sublime",
"terminal",
"warp",
"xcode",
] as const;
export type DesktopHostAppId = (typeof DESKTOP_HOST_APP_IDS)[number];
export type DesktopHostAppInfo = {
id: DesktopHostAppId;
label: string;
installed: boolean;
supports: Array<"workspace">;
};
/**
* Result of starting the native ChatGPT sign-in ceremony.
*
* A completed connection preserves the existing secret-free status shape.
* An explicit user cancellation resolves as the closed `cancelled` outcome;
* every other failure still rejects the operation.
*/
export type ChatGptConnectResult =
| (ChatGptSubscriptionStatus &
Readonly<{
outcome?: never;
}>)
| Readonly<{
outcome: "cancelled";
}>;
/**
* A single coalesced external change under a watched workspace root
* (issue #805). `kind` is intentionally coarse — the renderer reacts by
* re-reading the affected path / re-listing its parent, so it doesn't
* need byte-level deltas. A rename surfaces as `deleted` (old path) +
* `added` (new path) in v1.
*/
export type WorkspaceChangeEvent = {
kind: "added" | "changed" | "deleted";
/** Workspace-relative POSIX path of the changed entry. */
rel_path: string;
};
/** Receives coalesced batches of {@link WorkspaceChangeEvent}. */
export type WorkspaceChangeHandler = (events: WorkspaceChangeEvent[]) => void;
export type TerminalCreateOptions = {
/** Workspace whose root becomes the shell's cwd. Resolved host-side
* from the sidecar registry — the renderer never passes a raw path. */
workspace_id: string;
cols: number;
rows: number;
};
export type TerminalHandlers = {
/** Raw PTY output frames, in order. */
on_data: (data: string) => void;
/** Fires once when the shell process exits; no more frames after. */
on_exit: (info: { exit_code: number }) => void;
};
/** Renderer-safe media bytes returned by the native Desktop host. */
export type DesktopMediaReadResult = {
item: MediaItem;
/** Structured-clone byte buffer; avoids a second base64 expansion in IPC. */
bytes: ArrayBuffer;
};
export type DesktopBridge = {
protocol: typeof DESKTOP_BRIDGE_PROTOCOL;
app: { version: string; platform: string };
caps: DesktopCapabilities;
handshake: () => Promise<HandshakeResponse>;
/**
* Grida account lifecycle owned by the native entry controller. Optional
* because older protocol-1 hosts let individual renderer windows sign out
* independently.
*/
account?: {
sign_out: () => Promise<void>;
};
/**
* Purpose-scoped first-run workspace setup owned by Electron main.
*
* This namespace intentionally does not expose the daemon connection tuple
* or a generic filesystem dialog. It is optional because protocol-1 hosts
* shipped before the native onboarding role.
*/
onboarding?: {
get_default_workspace: () => Promise<Workspace | null>;
choose_workspace: () => Promise<Workspace | null>;
};
window: {
set_document_edited: (edited: boolean) => Promise<void>;
set_represented_filename: (filePath: string) => Promise<void>;
close: () => Promise<void>;
/**
* Finish the dedicated onboarding surface and promote the same entry
* BrowserWindow to the regular workstation. Optional because older
* protocol-1 hosts predate the native onboarding route.
*/
complete_onboarding?: (workspaceId?: string) => Promise<void>;
navigation: {
state: () => Promise<NavigationState>;
subscribe: (cb: (state: NavigationState) => void) => () => void;
back: () => Promise<void>;
forward: () => Promise<void>;
};
};
dialog: {
confirm: (opts: ConfirmOptions) => Promise<number>;
open: (opts: OpenDialogOptions) => Promise<string[] | null>;
save_as: (opts: SaveDialogOptions) => Promise<string | null>;
};
shell: {
open_external: (url: string) => Promise<void>;
show_item_in_folder: (filePath: string) => Promise<void>;
get_path_for_file: (file: File) => string;
};
files: {
read: (docId: string) => Promise<FileReadResult>;
write: (docId: string, content: string) => Promise<FileWriteResult>;
};
recent: {
list: () => Promise<RecentEntry[]>;
touch: (path: string) => Promise<void>;
pin: (path: string, pinned: boolean) => Promise<void>;
forget: (path: string) => Promise<void>;
};
/**
* App-managed, durable media library. Optional because protocol-1 Desktop
* builds predate it. Every operation is purpose-scoped: the renderer names
* only an opaque item id and never receives or supplies a native path.
*/
media?: {
list: () => Promise<MediaItem[]>;
read: (id: string) => Promise<DesktopMediaReadResult>;
reveal: (id: string) => Promise<void>;
open_folder: () => Promise<void>;
};
workspaces: {
list: () => Promise<Workspace[]>;
open: (rootPath: string) => Promise<Workspace>;
/**
* Auto-create a fresh project (managed root, seeded `.canvas` board) and
* register it — the desktop home's "auto-create, ask nothing" flow. No OS
* folder dialog. Rejects when the host wired no managed root.
*/
create: (input: WorkspaceCreateInput) => Promise<Workspace>;
pin: (id: string, pinned: boolean) => Promise<void>;
forget: (id: string) => Promise<void>;
readdir: (
workspaceId: string,
relPath?: string
) => Promise<WorkspaceFsEntry[]>;
read_file: (
workspaceId: string,
relPath: string
) => Promise<WorkspaceReadFileResult>;
read_file_bytes: (
workspaceId: string,
relPath: string
) => Promise<WorkspaceReadFileBytesResult>;
/**
* Resolve a streamable media `src` URL for `relPath`, for the read-only
* image/video viewer (#924). Synchronous and pure — it builds a URL the
* host can serve, no I/O. On desktop this is a `grida-workspace://`
* privileged-scheme URL backed by a streamed, Range-capable file route, so
* the viewer is size-independent (no 1 MiB base64 cap) and video seeking
* works.
*
* OPTIONAL: a host that can't serve a streaming scheme (e.g. the
* web-daemon dev bridge running in a plain browser) omits this; the viewer
* falls back to {@link read_file_bytes}. Gate on its presence, not on
* `caps`.
*/
media_url?: (workspaceId: string, relPath: string) => string;
/**
* Write `content` to `relPath`. `expectedMtime` is the optimistic-
* concurrency token (issue #805): the mtime the renderer last
* observed for this file. When supplied and the file on disk has
* advanced past it, the host rejects with a 409 `modified-since`
* error instead of silently clobbering the external change. Omit it
* for force-overwrite / first-time-create / last-writer-wins.
*/
write_file: (
workspaceId: string,
relPath: string,
content: string,
expectedMtime?: number
) => Promise<WorkspaceWriteFileResult>;
/**
* Move a workspace entry (file or folder) to the OS trash
* (recoverable; a folder takes its whole subtree). Unlike the sibling
* fs methods — which route to the agent sidecar — this is a host
* capability: the desktop main process performs the native trash
* after re-validating that `relPath` resolves inside the workspace
* root (and isn't the root itself). Renderers must confirm with the
* user first.
*/
trash_entry: (workspaceId: string, relPath: string) => Promise<void>;
/**
* Subscribe to external file-system changes under the workspace root
* (issue #805). The host watches the real directory tree and pushes
* coalesced batches of {@link WorkspaceChangeEvent} — covering edits
* made outside the editor, including the agent's own writes. Like
* `trash_entry` this is a native host capability (the OS watcher lives
* in the desktop main process), not an agent-sidecar operation.
*
* `subscribe_changes` registers `on_change` before the OS watch
* starts (caller-mints-id, mirroring `terminal.create`) so an early
* event can't race the subscription. Resolves with the id used to
* {@link unsubscribe_changes}. Additive on protocol 1 — gate the UI on
* `caps.native.workspace_watch`; older binaries lack the channel.
*/
subscribe_changes: (
workspaceId: string,
on_change: WorkspaceChangeHandler
) => Promise<{ subscription_id: string }>;
/** Stop a subscription started by {@link subscribe_changes}. */
unsubscribe_changes: (subscriptionId: string) => Promise<void>;
};
/**
* GRIDA-SEC-004 — human-interactive terminal. A real, unsandboxed
* login PTY on the user's own machine (VSCode trust model: the human
* is allowed to run anything as themselves). This is deliberately
* NOT the agent's shell — the agent's `run_command` stays confined
* behind the srt sandbox and is never wired to this surface.
*
* `create` registers `handlers` before the PTY spawns, so no output
* frame is lost. The shell's cwd is the workspace root; the user may
* `cd` freely once open. Killed on window close — no reattach (v1).
*/
terminal: {
create: (
opts: TerminalCreateOptions,
handlers: TerminalHandlers
) => Promise<{ id: string }>;
write: (id: string, data: string) => Promise<void>;
resize: (id: string, cols: number, rows: number) => Promise<void>;
kill: (id: string) => Promise<void>;
};
host_apps: {
resolve_preferred: (opts: {
workspace_id: string;
preferred_apps?: DesktopHostAppId[];
}) => Promise<DesktopHostAppInfo[]>;
open_workspace: (opts: {
workspace_id: string;
app_id: DesktopHostAppId;
}) => Promise<void>;
};
secrets: {
has: (providerId: ProviderId) => Promise<boolean>;
set: (providerId: ProviderId, key: string) => Promise<void>;
delete: (providerId: ProviderId) => Promise<void>;
};
/**
* Endpoint provider config (issue #806) — user-configured OpenAI-
* compatible endpoints (Ollama preset, self-hosted gateways). Plain
* readable config, unlike `secrets`: list returns full configs.
* Optional — older desktop binaries don't carry it; renderers must
* feature-detect and hide the surface when absent.
*/
providers?: {
list_endpoints: () => Promise<EndpointProviderConfig[]>;
set_endpoint: (config: EndpointProviderConfig) => Promise<void>;
delete_endpoint: (id: string) => Promise<void>;
/** Where the endpoint config JSON lives (the hand-editable file). */
info: () => Promise<{ path: string }>;
/** Discover the models an endpoint serves (agent-host-side fetch —
* the renderer's origin can't reach a local Ollama directly). */
probe_endpoint: (baseUrl: string) => Promise<{
source: "ollama" | "openai";
models: ProbedEndpointModel[];
}>;
/** Is the user's `claude` CLI resolvable on the host (issue #813)? Cheap
* filesystem probe, NOT a login check (login surfaces on the first run).
* Optional — older binaries lack it; renderers feature-detect. */
detect_claude?: () => Promise<{ installed: boolean; path?: string }>;
};
/**
* Grida hosted ("included") AI session — GRIDA-SEC-006. Push-only
* custody: the renderer mints the short-lived scoped token from the
* webview session and pushes it to the sidecar; `status` reports
* presence/expiry/org and NEVER the token. Optional — older binaries
* lack it; renderers feature-detect and show no hosted-AI affordances
* when absent.
*/
gg?: {
set_session: (session: GridaGatewaySession) => Promise<void>;
clear_session: () => Promise<void>;
status: () => Promise<GridaGatewaySessionStatus>;
};
/**
* Native ChatGPT-subscription provider control surface. OAuth credentials,
* authorization codes, PKCE material, and provider access tokens stay in
* Electron main + the agent sidecar; only secret-free status crosses into
* the renderer. Optional because protocol-1 Desktop builds predate it.
*/
chatgpt?: {
connect: () => Promise<ChatGptConnectResult>;
cancel: () => Promise<void>;
status: () => Promise<ChatGptSubscriptionStatus>;
sign_out: () => Promise<ChatGptSubscriptionStatus>;
};
/**
* BYOK image generation (#908). Desktop-only: the request resolves the
* user's connected provider key inside the sidecar and returns base64 image
* bytes — never the key. Optional — older binaries lack it; renderers
* feature-detect and hide the surface when absent.
*/
images?: {
generate: (req: ImageGenerateRequest) => Promise<ImageGenerateResult>;
};
/**
* BYOK video generation (#908). Desktop-only; resolves the user's key in the
* sidecar and returns base64 video bytes — never a provider URL or the key.
* Optional — older binaries lack it; renderers feature-detect.
*/
video?: {
generate: (req: VideoGenerateRequest) => Promise<VideoGenerateResult>;
};
/**
* BYOK 3D generation. Optional because protocol-1 Desktop builds predate
* the route; renderer code must feature-detect the namespace.
*/
threeD?: {
generate: (req: ThreeDGenerateRequest) => Promise<ThreeDGenerateResult>;
};
/**
* Audio-output generation taxonomy. Music, sound effects, and text-to-speech
* are independent optional capabilities because their providers,
* availability, and request contracts differ. The parent is optional for
* older Desktop hosts.
*/
audio?: {
music?: {
generate: (req: MusicGenerateRequest) => Promise<MusicGenerateResult>;
};
soundEffects?: {
generate: (
req: SoundEffectGenerateRequest
) => Promise<SoundEffectGenerateResult>;
};
textToSpeech?: {
listVoices: () => Promise<TextToSpeechListVoicesResult>;
generate: (
req: TextToSpeechGenerateRequest
) => Promise<TextToSpeechGenerateResult>;
};
};
agent: {
/**
* Turn an OS-backed directory `File` from a real drop into an opaque,
* read-only agent scope. Optional on protocol 1: older desktop binaries and
* browser hosts omit it. The absolute path is resolved inside Electron's
* preload and never returns to renderer code.
*/
attach_directory?: (file: File) => Promise<DirectoryScopeDescriptor>;
run: (
opts: AgentRunOptions,
onChunk: (chunk: AgentUIMessageChunk) => void
) => Promise<{
stream_id: string;
session_id: string;
done: Promise<void>;
}>;
abort: (sessionId: string) => Promise<void>;
reconnect: (
sessionId: string,
lastEventId: number,
onChunk: (chunk: AgentUIMessageChunk) => void
) => Promise<{
stream_id: string;
session_id: string;
done: Promise<void>;
} | null>;
};
sessions: {
list: (filter?: SessionListFilter) => Promise<SessionListPage>;
get: (id: string) => Promise<ChatSessionRow | null>;
create: (opts: CreateSessionOptions) => Promise<ChatSessionRow>;
patch: (id: string, opts: PatchSessionOptions) => Promise<ChatSessionRow>;
delete: (id: string) => Promise<void>;
list_messages: (id: string) => Promise<ChatMessageWithParts[]>;
/** Soft-truncate to a prior message (`restore: true` un-rewinds). */
rewind: (
id: string,
fromMessageId: string,
opts?: { restore?: boolean }
) => Promise<RewindResult>;
/** Fork the session at a message; resolves to the new forked session. */
fork: (
id: string,
fromMessageId: string,
metadata?: Record<string, unknown>
) => Promise<ChatSessionRow>;
/** User-fired compaction. */
compact: (id: string) => Promise<{
compacted: boolean;
reason?: string;
summary_message_id?: string;
}>;
/** Queued sends: enqueue a pending user message (held out of the model
* view + transcript until it fires). The caller mints the id. */
enqueue: (
id: string,
message: { id?: string; text: string }
) => Promise<ChatMessageWithParts>;
/** The pending queue, FIFO by `queued_at`. */
list_queued: (id: string) => Promise<ChatMessageWithParts[]>;
/** Cancel a queued message before it fires. */
cancel_queued: (id: string, messageId: string) => Promise<void>;
/**
* Subscribe to the session's run-state (RFC `session` §Session status):
* the current status arrives first, then every idle⇄busy⇄waiting⇄error
* transition. Returns a `subscription_id` to later
* {@link unsubscribe_status}, and a `done` that settles when the
* subscription ends.
*/
subscribe_status: (
id: string,
onStatus: (status: SessionStatus) => void
) => Promise<{ subscription_id: string; done: Promise<void> }>;
/** Stop a status subscription started by {@link subscribe_status}. */
unsubscribe_status: (subscriptionId: string) => Promise<void>;
};
};