@one2x/medeo-plugin-sdk 0.0.0-stage → 0.11.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 +27 -2
- package/dist/generated.d.ts +591 -0
- package/dist/generated.js +1 -0
- package/dist/index.d.ts +1320 -0
- package/dist/index.js +541 -0
- package/dist/react.d.ts +46 -0
- package/dist/react.js +44 -0
- package/dist/registry.d.ts +1349 -0
- package/dist/registry.js +203 -0
- package/dist/rpc.d.ts +28 -0
- package/dist/rpc.js +172 -0
- package/dist/testing.d.ts +43 -0
- package/dist/testing.js +190 -0
- package/dist/ui/styles.d.ts +4 -0
- package/dist/ui/styles.js +31 -0
- package/dist/ui.d.ts +50 -0
- package/dist/ui.js +115 -0
- package/package.json +66 -4
- package/src/generated.ts +231 -0
- package/src/index.ts +658 -0
- package/src/react.ts +50 -0
- package/src/registry.ts +204 -0
- package/src/rpc.ts +136 -0
- package/src/testing.ts +169 -0
- package/src/ui/styles.ts +31 -0
- package/src/ui.ts +102 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
import type {JsonValue} from './generated.ts';
|
|
2
|
+
import type {MethodName} from './registry.ts';
|
|
3
|
+
export {METHODS, LIMITS, type MethodName} from './registry.ts';
|
|
4
|
+
/** One SDK for both runtimes: a sandboxed worker/window, and a `runtime: "node"`
|
|
5
|
+
* plugin, whose bootstrap installs the same `medeoPlugin` surface. The SDK itself
|
|
6
|
+
* imports nothing from Node and asserts no identity of its own. */
|
|
7
|
+
export type { Manifest, PluginCommand, Permission, CapabilityDescriptor } from './generated.ts';
|
|
8
|
+
/** The `api_version` this SDK targets; `spec/api-v1.json` carries the same number. */
|
|
9
|
+
export const API_VERSION = 1;
|
|
10
|
+
export interface PluginAPI {
|
|
11
|
+
onLocaleChanged(callback:(state:PluginLocaleState)=>void):()=>void;
|
|
12
|
+
onEvent(callback:(event:PlatformEvent)=>void):()=>void;
|
|
13
|
+
post(message:unknown):Promise<void>;
|
|
14
|
+
onMessage(callback:(message:unknown)=>void):()=>void;
|
|
15
|
+
invoke(method: MethodName, args?: Record<string, unknown>): Promise<unknown>;
|
|
16
|
+
run(command: string, args?: JsonValue): Promise<unknown>;
|
|
17
|
+
/** Medeo Launcher Protocol v1 (Medeo 0.1.33+): answer launcher requests; push views from a launcher-started command. */
|
|
18
|
+
onLauncher?(handler:(request:{op:string;payload:any})=>unknown):()=>void;
|
|
19
|
+
launcher?(op:'update'|'prompt',session:string,view:unknown):Promise<unknown>;
|
|
20
|
+
/** Plugin windows (Medeo 0.1.43+): files dropped on the window as one-use import sources. */
|
|
21
|
+
dropped?(files:ArrayLike<File>):Promise<FileSource[]>;
|
|
22
|
+
}
|
|
23
|
+
declare global { var medeoPlugin: PluginAPI; interface Window { medeoPlugin: PluginAPI } }
|
|
24
|
+
|
|
25
|
+
/** Pushed by the Host: an operation changed status (or streamed progress), or a
|
|
26
|
+
* plugin-owned queue has entries to pull. Events carry no payload data. */
|
|
27
|
+
export type PlatformEvent =
|
|
28
|
+
| {type:'operation';id:string;method:string;status:string;revision?:number}
|
|
29
|
+
| {type:'signal';channel:'files.watch'|'server'|'input_method'|'background'|'permissions'|'config'|'shortcuts'|'tray'|'launcher'};
|
|
30
|
+
/** Messages between this plugin's background worker and its own windows
|
|
31
|
+
* (64 KiB each, JSON). A worker message reaches every open window; a window
|
|
32
|
+
* message reaches the worker. Nothing is persisted or sent elsewhere. */
|
|
33
|
+
export const channel = {
|
|
34
|
+
post:(message:unknown)=>globalThis.medeoPlugin.post(message),
|
|
35
|
+
onMessage:<T=unknown>(callback:(message:T)=>void)=>globalThis.medeoPlugin.onMessage(m=>callback(m as T)),
|
|
36
|
+
};
|
|
37
|
+
export const events = {
|
|
38
|
+
on:(callback:(event:PlatformEvent)=>void)=>globalThis.medeoPlugin.onEvent(callback),
|
|
39
|
+
/** Call `pull` now and again whenever the channel signals new entries. A
|
|
40
|
+
* failed pull (e.g. a permission withdrawn meanwhile) waits for the next signal. */
|
|
41
|
+
onSignal(channel:Extract<PlatformEvent,{type:'signal'}>['channel'],pull:()=>unknown){
|
|
42
|
+
const run=()=>{void Promise.resolve().then(pull).catch(()=>{})};
|
|
43
|
+
const off=globalThis.medeoPlugin.onEvent(event=>{if(event.type==='signal'&&event.channel===channel)run()});
|
|
44
|
+
run();return off;
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
/** Resolves on the next event for `id`, or after `fallbackMs` as a safety net. */
|
|
48
|
+
function nextChange(id:string,fallbackMs:number):{promise:Promise<void>;off:()=>void}{
|
|
49
|
+
let off=()=>{};
|
|
50
|
+
const promise=new Promise<void>(resolve=>{
|
|
51
|
+
const timer=setTimeout(resolve,fallbackMs);
|
|
52
|
+
const stop=globalThis.medeoPlugin.onEvent(event=>{if(event.type==='operation'&&event.id===id){clearTimeout(timer);resolve()}});
|
|
53
|
+
off=()=>{clearTimeout(timer);stop()};
|
|
54
|
+
});
|
|
55
|
+
return {promise,off};
|
|
56
|
+
}
|
|
57
|
+
export const storage = {
|
|
58
|
+
get: <T = unknown>(key: string) => globalThis.medeoPlugin.invoke('storage.get', { key }) as Promise<T | null>,
|
|
59
|
+
remove: (key:string) => globalThis.medeoPlugin.invoke('storage.remove',{key}),
|
|
60
|
+
set: (key: string, value: unknown) => globalThis.medeoPlugin.invoke('storage.set', { key, value }),
|
|
61
|
+
};
|
|
62
|
+
export const creation = { open: () => globalThis.medeoPlugin.invoke('creation.open') };
|
|
63
|
+
export const commands = { run: <T = unknown>(command: string, args?: JsonValue) => globalThis.medeoPlugin.run(command, args) as Promise<T> };
|
|
64
|
+
export interface Disposable { dispose(): unknown }
|
|
65
|
+
/** Passed to `activate` (VS Code style), in both runtimes. */
|
|
66
|
+
export interface PluginContext {
|
|
67
|
+
/** Disposed, in reverse order, when the plugin stops. */
|
|
68
|
+
subscriptions: Disposable[];
|
|
69
|
+
/** Register a handler for each command the manifest declares; all must be registered when `activate` returns. */
|
|
70
|
+
commands: { register(id: string, handler: (args?: JsonValue) => unknown | Promise<unknown>): Disposable };
|
|
71
|
+
/** `runtime: "node"` only: the installed, verified package directory (read-only). */
|
|
72
|
+
extensionPath?: string;
|
|
73
|
+
/** `runtime: "node"` only: a private writable directory that survives updates. */
|
|
74
|
+
storagePath?: string;
|
|
75
|
+
}
|
|
76
|
+
/** A plugin's background entry: export the result, e.g.
|
|
77
|
+
* `export const { activate, deactivate } = definePlugin({ activate(context) { … } })`. */
|
|
78
|
+
export interface PluginDefinition {
|
|
79
|
+
activate(context: PluginContext): unknown | Promise<unknown>;
|
|
80
|
+
deactivate?(): unknown | Promise<unknown>;
|
|
81
|
+
}
|
|
82
|
+
export function definePlugin(definition: PluginDefinition): Required<PluginDefinition> {
|
|
83
|
+
return { deactivate: () => undefined, ...definition };
|
|
84
|
+
}
|
|
85
|
+
/** Settings declared under `contributes.configuration`; the user edits them in the plugin center. */
|
|
86
|
+
export const config = {
|
|
87
|
+
get: <T = unknown>(key: string) => globalThis.medeoPlugin.invoke('config.get', { key }) as Promise<T>,
|
|
88
|
+
all: () => globalThis.medeoPlugin.invoke('config.get') as Promise<Record<string, unknown>>,
|
|
89
|
+
set: (key: string, value: unknown) => globalThis.medeoPlugin.invoke('config.set', { key, value }),
|
|
90
|
+
/** Calls `listener` with all values after each change, from the user or the plugin. */
|
|
91
|
+
onDidChange(listener: (values: Record<string, unknown>) => void): () => void {
|
|
92
|
+
return globalThis.medeoPlugin.onEvent(event => {
|
|
93
|
+
if (event.type === 'signal' && event.channel === 'config') void config.all().then(listener).catch(() => {});
|
|
94
|
+
});
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/** Native providers return quickly; subscribe to progress instead of holding a command open. */
|
|
99
|
+
export interface Provider { id: string; version: number; available: boolean; capabilities: string[] }
|
|
100
|
+
/** `full`: the user approved full access (view and direct Trash) for this directory. */
|
|
101
|
+
export interface Resource { id: string; name: string; available: boolean; full?: boolean }
|
|
102
|
+
/** Ask for full access (requires the `file_full_access` permission). */
|
|
103
|
+
export interface DirectoryAccess { full?: boolean }
|
|
104
|
+
export const providers = {
|
|
105
|
+
list: () => globalThis.medeoPlugin.invoke('providers.list') as Promise<Provider[]>,
|
|
106
|
+
require: async (id: string, version = 1) => {
|
|
107
|
+
const provider = (await providers.list()).find(p => p.id === id && p.version === version && p.available);
|
|
108
|
+
if (!provider) throw new Error('provider_unavailable');
|
|
109
|
+
return provider;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
export const resources = {
|
|
113
|
+
chooseDirectories: (access: DirectoryAccess = {}) => globalThis.medeoPlugin.invoke('resources.choose_directories', access.full ? { full: true } : {}) as Promise<Resource[]>,
|
|
114
|
+
list: () => globalThis.medeoPlugin.invoke('resources.list') as Promise<Resource[]>,
|
|
115
|
+
revoke: (id: string) => globalThis.medeoPlugin.invoke('resources.revoke', { id }) as Promise<Resource[]>,
|
|
116
|
+
requestDirectory: (path: string, reason: string, access: DirectoryAccess = {}) => globalThis.medeoPlugin.invoke('resources.request_directory', { path, reason, ...(access.full ? { full: true } : {}) }) as Promise<Resource[]>,
|
|
117
|
+
};
|
|
118
|
+
/** Medeo Drive (`drive_read`, `drive_manage`; macOS). The sync engine runs in Medeo's tray; no method returns a local path. */
|
|
119
|
+
export interface DriveState { signedIn: boolean; engine: 'ready' | 'connecting' | 'unavailable'; /** Changes whenever the account changes: drop folder ids kept from another generation. */ generation: number; status: { state: string; paused: boolean; totalFiles: number; syncedFiles: number; pendingFiles: number; uploadingFiles: number; errorFiles: number; totalBytes: number; syncedBytes: number } | null }
|
|
120
|
+
export interface DriveFolder { id: string; name: string; state: 'pending' | 'scanning' | 'syncing' | 'synced' | 'paused' | 'error' | 'missing'; files: number; bytes: number; failed: number; progress: number; paused: boolean; cloudOnly: boolean }
|
|
121
|
+
export interface DriveTransfers { uploadBytesPerSec: number; downloadBytesPerSec: number; active: { folder: string; path: string; transferred: number; total: number; direction: 'up' | 'down'; bytesPerSec: number }[]; recent: { folder: string; path: string; finishedAt: number; direction: 'up' | 'down' }[] }
|
|
122
|
+
export interface DriveFile { folder: string; path: string; size: number; status: string; updatedAt: number }
|
|
123
|
+
export interface DriveFailure { folder: string; path: string; reason: string }
|
|
124
|
+
export const drive = {
|
|
125
|
+
state: () => globalThis.medeoPlugin.invoke('drive.state', {}) as Promise<DriveState>,
|
|
126
|
+
folders: () => globalThis.medeoPlugin.invoke('drive.folders', {}) as Promise<DriveFolder[]>,
|
|
127
|
+
transfers: () => globalThis.medeoPlugin.invoke('drive.transfers', {}) as Promise<DriveTransfers>,
|
|
128
|
+
/** Most recently synced files, newest first; `limit` 1–100 (default 20). */
|
|
129
|
+
recent: (limit?: number) => globalThis.medeoPlugin.invoke('drive.recent', limit === undefined ? {} : { limit }) as Promise<DriveFile[]>,
|
|
130
|
+
failed: () => globalThis.medeoPlugin.invoke('drive.failed', {}) as Promise<DriveFailure[]>,
|
|
131
|
+
/** Sync state of up to 500 paths in a folder: `synced`, `pending`, `uploading`/`downloading` (with
|
|
132
|
+
* `progress` 0–1), `failed` (with `reason`), `cloud` (only in the cloud) or `unknown`. */
|
|
133
|
+
fileStates: (folder: string, paths: string[]) => globalThis.medeoPlugin.invoke('drive.fileStates', { folder, paths }) as Promise<Record<string, { state: 'synced' | 'pending' | 'uploading' | 'downloading' | 'failed' | 'cloud' | 'unknown'; progress?: number; reason?: string }>>,
|
|
134
|
+
/** Download a cloud-only file to this computer (`drive_manage`); watch it with `fileStates`. */
|
|
135
|
+
download: (folder: string, path: string) => globalThis.medeoPlugin.invoke('drive.download', { folder, path }) as Promise<null>,
|
|
136
|
+
/** Re-queue a folder's failed files (`drive_manage`). */
|
|
137
|
+
retry: (folder: string) => globalThis.medeoPlugin.invoke('drive.retry', { folder }) as Promise<null>,
|
|
138
|
+
/** From a plugin window, with `file_access` declared: Medeo asks the user (a named `folder`, or a picker
|
|
139
|
+
* opened at the drive) and grants that folder; read and write it with `files.*` (see `resources.list`). */
|
|
140
|
+
requestFolder: (reason: string, folder?: string) => globalThis.medeoPlugin.invoke('drive.requestFolder', folder === undefined ? { reason } : { reason, folder }) as Promise<Resource[]>,
|
|
141
|
+
};
|
|
142
|
+
/** Generic registered-provider entry point; the Host remains the authority. */
|
|
143
|
+
export const capabilities = {
|
|
144
|
+
list: () => globalThis.medeoPlugin.invoke('capabilities.list') as Promise<import('./generated').CapabilityDescriptor[]>,
|
|
145
|
+
labels: () => globalThis.medeoPlugin.invoke('capabilities.labels') as Promise<Record<string,string>>,
|
|
146
|
+
invoke: <T=unknown>(method:string,args:Record<string,unknown>={}) => globalThis.medeoPlugin.invoke(method as MethodName,args) as Promise<T>,
|
|
147
|
+
};
|
|
148
|
+
export const clipboard = {read:()=>globalThis.medeoPlugin.invoke('clipboard.read') as Promise<{text:string}>,write:(text:string)=>globalThis.medeoPlugin.invoke('clipboard.write',{text})};
|
|
149
|
+
/** `running` reports, per rule, whether a matching process exists; it never
|
|
150
|
+
* returns the process list. Rules match an exact executable name or a path fragment. */
|
|
151
|
+
export interface ProcessRule {name?:string;path_contains?:string}
|
|
152
|
+
export interface SystemInfo {platform:string;architecture:string;release:string;locale:string;/** The Medeo running the plugin (0.1.23+; absent on older Medeo). */medeo?:{version:string;channel:'stg'|'prd'};displays:{id:string;bounds:{x:number;y:number;width:number;height:number};scale:number}[]}
|
|
153
|
+
export const system = {info:()=>globalThis.medeoPlugin.invoke('system.info') as Promise<SystemInfo>,running:(rules:ProcessRule[])=>capabilities.invoke<NativeOperation<boolean[]>>('system.running',{rules})};
|
|
154
|
+
/** One outcome per path of `trash`, in the order given. */
|
|
155
|
+
export interface TrashResult {path:string;trashed:boolean;error?:string}
|
|
156
|
+
/** `runtime: "node"` plugins only (the `node` permission): moves up to 256 absolute
|
|
157
|
+
* paths to the OS Trash, the one thing Node cannot do itself. A failure does not stop the rest. */
|
|
158
|
+
export const trash = (paths:string[]) => globalThis.medeoPlugin.invoke('system.trash',{paths}) as Promise<TrashResult[]>;
|
|
159
|
+
export const notifications = {show:(id:string,title:string,body:string)=>globalThis.medeoPlugin.invoke('notifications.show',{id,title,body}),close:(id:string)=>globalThis.medeoPlugin.invoke('notifications.close',{id})};
|
|
160
|
+
export const power = {start:(type:'prevent-app-suspension'|'prevent-display-sleep')=>globalThis.medeoPlugin.invoke('power.start',{type}) as Promise<{id:string}>,stop:(id:string)=>globalThis.medeoPlugin.invoke('power.stop',{id}),state:()=>globalThis.medeoPlugin.invoke('power.state')};
|
|
161
|
+
export const shortcuts = {list:()=>globalThis.medeoPlugin.invoke('shortcuts.list') as Promise<{id:string;accelerator:string;open_ui:boolean}[]>,register:(id:string,accelerator:string,openUI=false)=>globalThis.medeoPlugin.invoke('shortcuts.register',{id,accelerator,open_ui:openUI}),unregister:(id:string)=>globalThis.medeoPlugin.invoke('shortcuts.unregister',{id}),events:()=>globalThis.medeoPlugin.invoke('shortcuts.events')};
|
|
162
|
+
/** `panel: true` (macOS): a frameless window floating over every app and Space that does not
|
|
163
|
+
* activate Medeo — the app the user was in keeps focus — opened at the pointer and hidden (not
|
|
164
|
+
* closed) when it loses focus; opening it again moves it to the pointer. `hide` keeps a window
|
|
165
|
+
* and its page alive for the next `open`/`focus`.
|
|
166
|
+
* `overlay: true` (macOS, needs `window_management` too): a transparent, shadowless panel covering
|
|
167
|
+
* the whole display under the pointer (menu bar included), above full-screen apps — for previews
|
|
168
|
+
* and radial menus. It takes keyboard focus without activating Medeo, hides when it loses focus,
|
|
169
|
+
* and each `open` moves it to the pointer's display; `width`/`height` are ignored. The page's
|
|
170
|
+
* `window.screenX/screenY` is the display's top-left in the same global points as
|
|
171
|
+
* `windowManagement`. `panel` and `overlay` are exclusive. */
|
|
172
|
+
export const appWindows = {open:(options:{id:string;entry:string;title:string;width:number;height:number;panel?:boolean;overlay?:boolean})=>globalThis.medeoPlugin.invoke('windows.open',options),close:(id:string)=>globalThis.medeoPlugin.invoke('windows.close',{id}),focus:(id:string)=>globalThis.medeoPlugin.invoke('windows.focus',{id}),hide:(id:string)=>globalThis.medeoPlugin.invoke('windows.hide',{id}),list:()=>globalThis.medeoPlugin.invoke('windows.list') as Promise<{id:string;title:string;visible:boolean}[]>};
|
|
173
|
+
/** A menu entry, a checkmarked toggle, or a divider. */
|
|
174
|
+
export type TrayItem = {id:string;title:string;checked?:boolean}|{separator:true};
|
|
175
|
+
/** `icon`: a PNG in the package drawn as a menu-bar template (black + alpha, about 36 px tall);
|
|
176
|
+
* `click`: an id reported on a left click, which then leaves the menu to a right click. */
|
|
177
|
+
export interface TrayOptions {icon?:string;click?:string}
|
|
178
|
+
export const tray = {set:(title:string,items:TrayItem[],options:TrayOptions={})=>globalThis.medeoPlugin.invoke('tray.set',{title,items,...options}),remove:()=>globalThis.medeoPlugin.invoke('tray.remove'),events:()=>globalThis.medeoPlugin.invoke('tray.events')};
|
|
179
|
+
export const external = {open:(url:string)=>globalThis.medeoPlugin.invoke('external.open',{url})};
|
|
180
|
+
|
|
181
|
+
/** `scope` says how long an approval lasts: `always` (stored), `run` (until the plugin stops),
|
|
182
|
+
* `never` (refused with "don't ask again"). `remembered`: refused earlier, no dialog was shown. */
|
|
183
|
+
export interface PermissionAnswer { granted: boolean; scope?: 'always' | 'run' | 'never' | 'none'; remembered?: boolean }
|
|
184
|
+
export const permissions = {request:(permission:string,reason:string)=>globalThis.medeoPlugin.invoke('permissions.request',{permission,reason}) as Promise<PermissionAnswer>};
|
|
185
|
+
|
|
186
|
+
/** One of the plugin's own actions for the user to approve (`approvals` permission; `action` must be declared).
|
|
187
|
+
* `rule_key` identifies it (`bash:git status`); `rule_pattern` (a prefix of it ending in `*`) is what
|
|
188
|
+
* "always" remembers instead. Medeo draws the dialog and keeps the rules. In a Node plugin nothing
|
|
189
|
+
* forces you to ask: it is up to the plugin to call this before acting. */
|
|
190
|
+
export interface ApprovalRequest {
|
|
191
|
+
action: string; title: string; detail?: string;
|
|
192
|
+
preview?: { kind: 'text' | 'command' | 'diff'; text: string };
|
|
193
|
+
rule_key: string; rule_pattern?: string;
|
|
194
|
+
}
|
|
195
|
+
/** `scope`: `once`, `run`, `always`, or `rule` when a remembered answer decided without a dialog. */
|
|
196
|
+
export interface ApprovalAnswer { decision: 'allow' | 'deny'; scope: 'once' | 'run' | 'always' | 'rule'; rule?: string }
|
|
197
|
+
export interface ApprovalRule { action: string; pattern: string; allow: boolean; scope: 'run' | 'always' }
|
|
198
|
+
export const approvals = {
|
|
199
|
+
request:(request:ApprovalRequest)=>globalThis.medeoPlugin.invoke('approvals.request',{...request}) as Promise<ApprovalAnswer>,
|
|
200
|
+
rules:()=>globalThis.medeoPlugin.invoke('approvals.rules') as Promise<ApprovalRule[]>,
|
|
201
|
+
forget:(action:string,pattern:string)=>globalThis.medeoPlugin.invoke('approvals.forget',{action,pattern}) as Promise<ApprovalRule[]>,
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
// Text content stays in Host memory. Closing a window does not cancel jobs;
|
|
206
|
+
// state() without an id lists jobs owned by this active plugin instance.
|
|
207
|
+
export interface AgentJob {
|
|
208
|
+
id: string; status: 'running' | 'completed' | 'failed' | 'cancelled';
|
|
209
|
+
text?: string; models?: string[]; error?: string | null;
|
|
210
|
+
}
|
|
211
|
+
export const agent = {
|
|
212
|
+
models: () => capabilities.invoke<AgentJob>('agent.models', {}),
|
|
213
|
+
start: (messages: {role:'system'|'user'|'assistant';content:string}[], model?:string) =>
|
|
214
|
+
capabilities.invoke<AgentJob>('agent.start', {messages, ...(model ? {model} : {})}),
|
|
215
|
+
state: (id:string) => operations.state(id) as Promise<AgentJob>,
|
|
216
|
+
cancel: (id:string) => operations.cancel(id) as Promise<AgentJob>,
|
|
217
|
+
release: (id:string) => operations.release(id),
|
|
218
|
+
/** Calls `onText` as the reply streams in; resolves with the final job. */
|
|
219
|
+
async follow(id:string,onText:(job:AgentJob)=>void):Promise<AgentJob>{
|
|
220
|
+
for(;;){const change=nextChange(id,2000);const job=await agent.state(id);onText(job);if(job.status!=='running'){change.off();return job}await change.promise;change.off()}
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
export interface ApplicationEntry { id:string;title:string;path:string;bundle_id:string }
|
|
225
|
+
export interface ApplicationList { status:string;error:string|null;incomplete:boolean;total:number;entries:ApplicationEntry[] }
|
|
226
|
+
export interface ApplicationState { status:string;error:string|null;launch:{id:string;status:string;error:string|null;pid?:number}|null }
|
|
227
|
+
export const applications = {
|
|
228
|
+
/** The whole inventory; plugins rank and filter it themselves. */
|
|
229
|
+
list: (refresh=false) => capabilities.invoke<ApplicationList>('applications.list',{refresh}),
|
|
230
|
+
launch: (id:string) => capabilities.invoke<{id:string;status:string}>('applications.launch',{id}),
|
|
231
|
+
state: () => capabilities.invoke<ApplicationState>('applications.state',{}),
|
|
232
|
+
/** 64 px PNG `data:` URLs (≤ 24 ids per call; `null` when the app has none). Ids not drawn yet are
|
|
233
|
+
* left out and counted in `pending`; ask again shortly. Medeo 0.1.33+. */
|
|
234
|
+
icons: (ids:string[]) => capabilities.invoke<{icons:Record<string,string|null>;pending:number}>('applications.icons',{ids}),
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
// ------------------------------------------------------------------ Medeo Launcher Protocol v1
|
|
238
|
+
// spec/launcher-v1.md. Plugins describe data; any launcher draws it. Declare what you offer under
|
|
239
|
+
// `contributes.launcher` in the manifest, then use `launcher.provide` (results) and
|
|
240
|
+
// `launcher.session` (views from a command). Medeo trims every value to the protocol's limits.
|
|
241
|
+
export type LauncherDataType = 'text'|'url'|'file'|'image'|'application';
|
|
242
|
+
export type LauncherTone = 'default'|'success'|'warning'|'danger'|'info';
|
|
243
|
+
/** A symbol the launcher draws, an image in your package, a small `data:` URL, or a file whose icon Medeo shows. */
|
|
244
|
+
export type LauncherIcon = {symbol:string}|{path:string}|{data:string}|{file:string};
|
|
245
|
+
export interface LauncherAction { id:string; title:string; shortcut?:string; style?:'default'|'destructive' }
|
|
246
|
+
export interface LauncherItem {
|
|
247
|
+
id:string; title:string; subtitle?:string; icon?:LauncherIcon;
|
|
248
|
+
accessory?:{text:string;tone?:LauncherTone};
|
|
249
|
+
/** With `data`: what the row carries, so the user can send it to plugins that accept the type. */
|
|
250
|
+
type?:LauncherDataType; data?:string; keywords?:string[];
|
|
251
|
+
detail?:{text?:string;image?:LauncherIcon;metadata?:{label:string;value:string}[]};
|
|
252
|
+
/** The first is the primary action (↩); all appear under ⌘K. */
|
|
253
|
+
actions?:LauncherAction[];
|
|
254
|
+
}
|
|
255
|
+
export interface LauncherViewItem { id?:string; title:string; subtitle?:string; accessory?:{text:string;tone?:LauncherTone}; checked?:boolean; state?:'done'|'running'|'pending'|'failed' }
|
|
256
|
+
export type LauncherView =
|
|
257
|
+
| {type:'confirm';title:string;message?:string;items?:LauncherViewItem[];confirm?:string;cancel?:string;style?:'default'|'destructive'}
|
|
258
|
+
| {type:'progress';title:string;message?:string;value?:number;items?:LauncherViewItem[]}
|
|
259
|
+
| {type:'result';tone?:'success'|'info'|'warning'|'error';title:string;message?:string;items?:LauncherItem[]}
|
|
260
|
+
| {type:'list';title?:string;items:LauncherItem[]};
|
|
261
|
+
export interface LauncherActionResult { close?:boolean; toast?:string; view?:LauncherView; refresh?:boolean }
|
|
262
|
+
/** Data another plugin sent to this command (`accepts` in the manifest); `source` is set by Medeo. */
|
|
263
|
+
/** A file or image another plugin sent: a one-use source for `files.import` (Medeo 0.1.45+); never a path you can open. */
|
|
264
|
+
export interface LauncherInputFile { source:string; name:string; size:number }
|
|
265
|
+
export interface LauncherInput { type:LauncherDataType; value:string; title?:string; source:string; file?:LauncherInputFile }
|
|
266
|
+
export interface LauncherProvider {
|
|
267
|
+
/** Results for `query` (≤ `limit`, at most 20). Answer within 1.5 s; slower providers are left out. */
|
|
268
|
+
search(query:string,context:{scoped:boolean;limit:number}):LauncherItem[]|Promise<LauncherItem[]>;
|
|
269
|
+
/** The user picked `action` on result `item` (ids you returned). Within 15 s. */
|
|
270
|
+
action?(item:string,action:string,context:{query:string}):LauncherActionResult|void|Promise<LauncherActionResult|void>;
|
|
271
|
+
}
|
|
272
|
+
/** A command started from a launcher shows its progress there, and asks there. */
|
|
273
|
+
export interface LauncherSession {
|
|
274
|
+
readonly id:string;
|
|
275
|
+
show(view:LauncherView):Promise<void>;
|
|
276
|
+
progress(title:string,options?:{message?:string;value?:number;items?:LauncherViewItem[]}):Promise<void>;
|
|
277
|
+
/** Waits for the user (up to 10 minutes); unanswered or cancelled is `{confirmed:false}`. */
|
|
278
|
+
confirm(view:Omit<Extract<LauncherView,{type:'confirm'}>,'type'>):Promise<{confirmed:boolean;selected?:string[]}>;
|
|
279
|
+
result(view:Omit<Extract<LauncherView,{type:'result'}>,'type'>):Promise<void>;
|
|
280
|
+
}
|
|
281
|
+
export interface LauncherSearchResults { protocol:number; results:{plugin_id:string;items:LauncherItem[];error?:string}[] }
|
|
282
|
+
export type LauncherEvent =
|
|
283
|
+
| {type:'view';session:string;plugin_id:string;view:LauncherView}
|
|
284
|
+
| {type:'prompt';session:string;plugin_id:string;prompt:string;view:LauncherView}
|
|
285
|
+
| {type:'done';session:string;plugin_id:string;ok:boolean;error?:string};
|
|
286
|
+
const bridge=()=>{const api=globalThis.medeoPlugin;if(!api.onLauncher||!api.launcher)throw new Error('launcher_unavailable');return api as Required<PluginAPI>};
|
|
287
|
+
export const launcher = {
|
|
288
|
+
/** Answer launcher searches and actions. Call it in `activate`; needs `contributes.launcher.provider`. */
|
|
289
|
+
provide(provider:LauncherProvider):Disposable{
|
|
290
|
+
// An older Medeo has no launchers to answer: the plugin runs on without being searchable.
|
|
291
|
+
if(!globalThis.medeoPlugin.onLauncher)return {dispose(){}};
|
|
292
|
+
const off=bridge().onLauncher(async({op,payload})=>{
|
|
293
|
+
if(op==='search')return provider.search(String(payload?.query??''),{scoped:payload?.scoped===true,limit:Number(payload?.limit)||20});
|
|
294
|
+
if(op==='action'){if(!provider.action)throw new Error('action_unsupported');return (await provider.action(String(payload?.item),String(payload?.action),{query:String(payload?.query??'')}))??null}
|
|
295
|
+
throw new Error('unknown_launcher_op');
|
|
296
|
+
});
|
|
297
|
+
return {dispose:off};
|
|
298
|
+
},
|
|
299
|
+
/** The session of a command a launcher started, from the command's `args`; null otherwise. */
|
|
300
|
+
session(args:unknown):LauncherSession|null{
|
|
301
|
+
const id=(args as {launcher?:{session?:unknown}}|null)?.launcher?.session;
|
|
302
|
+
if(typeof id!=='string')return null;
|
|
303
|
+
const send=(op:'update'|'prompt',view:LauncherView)=>bridge().launcher(op,id,view);
|
|
304
|
+
return {
|
|
305
|
+
id,
|
|
306
|
+
show:async view=>{await send('update',view)},
|
|
307
|
+
progress:async(title,options={})=>{await send('update',{type:'progress',title,...options})},
|
|
308
|
+
confirm:async view=>await send('prompt',{type:'confirm',...view}) as {confirmed:boolean;selected?:string[]},
|
|
309
|
+
result:async view=>{await send('update',{type:'result',...view})},
|
|
310
|
+
};
|
|
311
|
+
},
|
|
312
|
+
/** Data sent to this command from another plugin's result, if any. */
|
|
313
|
+
input(args:unknown):LauncherInput|null{
|
|
314
|
+
const input=(args as {input?:LauncherInput}|null)?.input;
|
|
315
|
+
return input&&typeof input.value==='string'&&typeof input.type==='string'?input:null;
|
|
316
|
+
},
|
|
317
|
+
// Launchers (`plugin_commands`):
|
|
318
|
+
/** Every provider's results for `query`, or one plugin's with `scope`. */
|
|
319
|
+
search:(query:string,options:{scope?:string;limit?:number}={})=>capabilities.invoke<LauncherSearchResults>('launcher.search',{query,...options}),
|
|
320
|
+
act:(pluginId:string,item:string,action:string,query='')=>capabilities.invoke<LauncherActionResult>('launcher.act',{plugin_id:pluginId,item,action,query}),
|
|
321
|
+
/** Runs a command with a session: its views arrive as `launcher.events()` tagged with `session`. */
|
|
322
|
+
run:<T=unknown>(pluginId:string,command:string,args:JsonValue|undefined,session:string)=>capabilities.invoke<T>('plugins.run',{plugin_id:pluginId,command,session,...(args===undefined?{}:{args})}),
|
|
323
|
+
answer:(prompt:string,value:{confirmed:boolean;selected?:string[]})=>capabilities.invoke<null>('launcher.answer',{prompt,value}),
|
|
324
|
+
/** Drain on the `launcher` signal: `events.onSignal('launcher', …)`. */
|
|
325
|
+
events:()=>capabilities.invoke<LauncherEvent[]>('launcher.events',{}),
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
/** Another installed plugin, as `plugins.commands` reports it (`plugin_commands` permission). */
|
|
329
|
+
export interface LauncherArgumentInfo { name:string; type:'enum'|'string'|'number'|'boolean'; title:string; placeholder:string|null; optional:boolean; options:{value:string;title:string;subtitle:string|null;icon:string|null;keywords:string[]}[] }
|
|
330
|
+
export interface LauncherCommandInfo { command:string; title:string; subtitle:string|null; icon:string|null; keywords:string[]; pinnable:boolean; arguments:LauncherArgumentInfo[]; expand:string|null; accepts:LauncherDataType[] }
|
|
331
|
+
export interface InstalledPluginCommands { id:string;name:string;description:string|null;icon:string|null;has_ui:boolean;commands:{id:string;title:string}[];
|
|
332
|
+
/** Its `contributes.launcher`, localized, images as `data:` URLs. */
|
|
333
|
+
launcher:{keyword:string|null;provider:{types?:LauncherDataType[];scoped?:boolean}|null;commands:LauncherCommandInfo[]}|null }
|
|
334
|
+
/** For launchers: other plugins' commands, run as if the user picked them in the plugin center.
|
|
335
|
+
* Needs the sensitive `plugin_commands` permission and Medeo 0.1.33+. A command started this way
|
|
336
|
+
* cannot call `plugins.run` itself (`recursive_command`). */
|
|
337
|
+
export const plugins = {
|
|
338
|
+
commands: () => capabilities.invoke<InstalledPluginCommands[]>('plugins.commands',{}),
|
|
339
|
+
run: <T = unknown>(pluginId:string, command:string, args?:JsonValue) =>
|
|
340
|
+
capabilities.invoke<T>('plugins.run',{plugin_id:pluginId,command,...(args===undefined?{}:{args})}),
|
|
341
|
+
open: (pluginId:string) => capabilities.invoke<null>('plugins.open',{plugin_id:pluginId}),
|
|
342
|
+
/** Shows the plugin center on its Discover page, where the user installs more plugins. */
|
|
343
|
+
center: () => capabilities.invoke<null>('plugins.center',{}),
|
|
344
|
+
/** Ask the user to install an official plugin this one works with (from a click). Medeo shows its own
|
|
345
|
+
* install confirmation; `installed` when it is there now (already, or just installed / updated). */
|
|
346
|
+
suggestInstall: (pluginId:string) => capabilities.invoke<{state:'installed'|'cancelled'|'unavailable'}>('plugins.suggestInstall',{plugin_id:pluginId}),
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
export interface CaptureSource {id:string;title:string;width:number;height:number}
|
|
350
|
+
export interface CaptureRecord {id:string;source_title:string;status:string;active:boolean;can_stop:boolean;can_recover:boolean;error?:string|null;playable:boolean;duration_ms:number;bytes:number;microphone:boolean;system_audio:boolean;audio_tracks?:number}
|
|
351
|
+
export const capture = {
|
|
352
|
+
status:(refresh=true)=>capabilities.invoke<{status:string;os:Record<string,string>}>('capture.status',{refresh}),
|
|
353
|
+
sources:(refresh=false,requestPermission=false)=>capabilities.invoke<{status:string;error?:string;os:Record<string,string>;sources:CaptureSource[]}>('capture.sources',{refresh,request_permission:requestPermission}),
|
|
354
|
+
start:(source:string,options:{microphone?:boolean;systemAudio?:boolean}={})=>capabilities.invoke<{id?:string;cancelled?:boolean}>('capture.start',{source,microphone:options.microphone??false,system_audio:options.systemAudio??false}),
|
|
355
|
+
state:()=>capabilities.invoke<{records:CaptureRecord[];os:Record<string,string>}>('capture.state',{}),
|
|
356
|
+
stop:(id:string)=>capabilities.invoke('capture.stop',{id}),
|
|
357
|
+
cancel:(id:string)=>capabilities.invoke('capture.cancel',{id}),
|
|
358
|
+
recover:(id:string)=>capabilities.invoke('capture.recover',{id}),
|
|
359
|
+
open:(id:string,mode:'play'|'reveal'='play')=>capabilities.invoke('capture.open',{id,mode}),
|
|
360
|
+
previewURL:(id:string)=>location.origin+'/_capture/'+encodeURIComponent(id)+'.mp4',
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
export interface InputMethodState {enabled:boolean;provider_ready:boolean;configured_name:string;occupied:boolean;system_source:string}
|
|
364
|
+
export interface InputSourceState {status:string;state_key:string;can_setup:boolean;can_remove:boolean;installed?:boolean;registered?:boolean;enabled?:boolean;selected?:boolean;update_available?:boolean;error?:string;last_operation?:{id:string;status:string;error?:string};task?:string}
|
|
365
|
+
export const inputMethod={
|
|
366
|
+
system:(refresh=false)=>capabilities.invoke<InputSourceState>('input_method.system',{refresh}),
|
|
367
|
+
setup:()=>capabilities.invoke<{task?:string;cancelled?:boolean}>('input_method.setup'),
|
|
368
|
+
remove:()=>capabilities.invoke<{task?:string;cancelled?:boolean}>('input_method.remove'),
|
|
369
|
+
settings:()=>capabilities.invoke<{task:string}>('input_method.settings'),
|
|
370
|
+
status:()=>capabilities.invoke<InputMethodState>('input_method.status'),
|
|
371
|
+
configure:(name:string)=>capabilities.invoke('input_method.configure',{name}),
|
|
372
|
+
enable:()=>capabilities.invoke<InputMethodState>('input_method.enable'),
|
|
373
|
+
disable:()=>capabilities.invoke('input_method.disable'),
|
|
374
|
+
events:()=>capabilities.invoke<{id:string;text:string}[]>('input_method.events'),
|
|
375
|
+
respond:(id:string,candidates:string[])=>capabilities.invoke('input_method.respond',{id,candidates}),
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
/** HTTP uses only approved origins; no redirects, browser cookies, or Medeo credentials.
|
|
379
|
+
* Closing UI preserves jobs; disable/revoke cancels. Mutations are never replayed.
|
|
380
|
+
* Release completed results to return the per-instance memory quota.
|
|
381
|
+
*/
|
|
382
|
+
export interface NetworkRequest {url:string;method?:'GET'|'HEAD'|'POST'|'PUT'|'PATCH'|'DELETE'|'OPTIONS';headers?:Record<string,string>;body?:string;body_base64?:string;timeout_ms?:number;stream?:boolean}
|
|
383
|
+
export interface NetworkJob {id:string;status:'running'|'completed'|'failed'|'cancelled';received?:number;http_status?:number|null;headers?:[string,string][];error?:string|null;stream?:boolean}
|
|
384
|
+
export interface NetworkChunk {data_base64:string;next_offset:number;eof:boolean}
|
|
385
|
+
export interface NetworkOrigin {origin:string;declared:boolean;allowed:boolean}
|
|
386
|
+
export interface NetworkServerEvent {data:string;event:string;id:string;retry?:number}
|
|
387
|
+
export const network = {
|
|
388
|
+
origins:()=>capabilities.invoke<NetworkOrigin[]>('network.origins'),
|
|
389
|
+
requestOrigin:(origin:string,reason:string)=>capabilities.invoke<{origin:string;granted:boolean}>('network.request_origin',{origin,reason}),
|
|
390
|
+
revokeOrigin:(origin:string)=>capabilities.invoke<NetworkOrigin[]>('network.revoke_origin',{origin}),
|
|
391
|
+
request:(request:NetworkRequest)=>capabilities.invoke<NetworkJob>('network.request',{...request}),
|
|
392
|
+
state:(id:string)=>operations.state(id) as Promise<NetworkJob>,
|
|
393
|
+
read:(id:string,offset=0,length=32768)=>capabilities.invoke<NetworkChunk>('network.read',{id,offset,length}),
|
|
394
|
+
cancel:(id:string)=>operations.cancel(id) as Promise<NetworkJob>,
|
|
395
|
+
release:(id:string)=>operations.release(id) as Promise<{released:boolean}>,
|
|
396
|
+
/** Resolves once the response has fully arrived; the job stays readable until released. */
|
|
397
|
+
async settled(id:string):Promise<NetworkJob>{for(;;){const change=nextChange(id,2000);const state=await network.state(id);if(state.status!=='running'){change.off();return state}await change.promise;change.off()}},
|
|
398
|
+
/** Single consumer for a stream:true job. Break/throw/abort cancels and releases it. */
|
|
399
|
+
async *bytes(id:string,signal?:AbortSignal):AsyncGenerator<Uint8Array>{
|
|
400
|
+
let offset=0;
|
|
401
|
+
let abortCleanup:Promise<void>|undefined;
|
|
402
|
+
const abort=()=>{abortCleanup=network.dispose(id);void abortCleanup.catch(()=>{})};
|
|
403
|
+
signal?.addEventListener('abort',abort,{once:true});
|
|
404
|
+
try {
|
|
405
|
+
for(;;){
|
|
406
|
+
let wake!:()=>void;
|
|
407
|
+
const changed=new Promise<void>(resolve=>{wake=resolve});
|
|
408
|
+
const off=events.on(event=>{if(event.type==='operation'&&event.id===id)wake()});
|
|
409
|
+
signal?.addEventListener('abort',wake,{once:true});
|
|
410
|
+
try {
|
|
411
|
+
if(signal?.aborted)throw new Error('network_cancelled');
|
|
412
|
+
const state=await network.state(id);
|
|
413
|
+
if(state.status==='failed'||state.status==='cancelled')throw new Error(state.error??state.status);
|
|
414
|
+
const part=await network.read(id,offset);
|
|
415
|
+
offset=part.next_offset;
|
|
416
|
+
if(signal?.aborted)throw new Error('network_cancelled');
|
|
417
|
+
if(part.data_base64)yield Uint8Array.from(atob(part.data_base64),c=>c.charCodeAt(0));
|
|
418
|
+
if(part.eof)return;
|
|
419
|
+
if(!part.data_base64)await changed;
|
|
420
|
+
} finally {off();signal?.removeEventListener('abort',wake)}
|
|
421
|
+
}
|
|
422
|
+
} finally {
|
|
423
|
+
signal?.removeEventListener('abort',abort);
|
|
424
|
+
await (abortCleanup??network.dispose(id));
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
/** Incremental UTF-8 decoder, including code points split across HTTP chunks. */
|
|
428
|
+
async *textStream(id:string,signal?:AbortSignal):AsyncGenerator<string>{
|
|
429
|
+
const decoder=new TextDecoder();
|
|
430
|
+
for await(const bytes of network.bytes(id,signal)){
|
|
431
|
+
const text=decoder.decode(bytes,{stream:true});if(text)yield text;
|
|
432
|
+
}
|
|
433
|
+
const tail=decoder.decode();if(tail)yield tail;
|
|
434
|
+
},
|
|
435
|
+
/** SSE framing only: no automatic reconnect/retry or Last-Event-ID requests. */
|
|
436
|
+
async *sse(id:string,signal?:AbortSignal):AsyncGenerator<NetworkServerEvent>{
|
|
437
|
+
let pending='',data:string[]=[],event='',lastId='',retry:number|undefined,size=0,skipLf=false;
|
|
438
|
+
for await(const text of network.textStream(id,signal)){
|
|
439
|
+
pending+=skipLf&&text.startsWith('\n')?text.slice(1):text;
|
|
440
|
+
skipLf=false;
|
|
441
|
+
for(;;){
|
|
442
|
+
const at=pending.search(/[\r\n]/);
|
|
443
|
+
if(at<0)break;
|
|
444
|
+
skipLf=pending[at]==='\r'&&at===pending.length-1;
|
|
445
|
+
const line=pending.slice(0,at);
|
|
446
|
+
pending=pending.slice(at+(pending[at]==='\r'&&pending[at+1]==='\n'?2:1));
|
|
447
|
+
size+=line.length;
|
|
448
|
+
if(size>262144)throw new Error('network_sse_event_too_large');
|
|
449
|
+
if(!line){
|
|
450
|
+
if(data.length)yield {data:data.join('\n'),event:event||'message',id:lastId,...(retry===undefined?{}:{retry})};
|
|
451
|
+
data=[];event='';size=0;continue;
|
|
452
|
+
}
|
|
453
|
+
if(line.startsWith(':'))continue;
|
|
454
|
+
const colon=line.indexOf(':');
|
|
455
|
+
const field=colon<0?line:line.slice(0,colon);
|
|
456
|
+
let value=colon<0?'':line.slice(colon+1);if(value.startsWith(' '))value=value.slice(1);
|
|
457
|
+
if(field==='data')data.push(value);
|
|
458
|
+
else if(field==='event')event=value;
|
|
459
|
+
else if(field==='id'&&!value.includes('\0'))lastId=value;
|
|
460
|
+
else if(field==='retry'&&/^\d+$/.test(value)&&Number.isSafeInteger(Number(value)))retry=Number(value);
|
|
461
|
+
}
|
|
462
|
+
if(size+pending.length>262144)throw new Error('network_sse_event_too_large');
|
|
463
|
+
}
|
|
464
|
+
// SSE requires a blank line to dispatch; incomplete final events are discarded.
|
|
465
|
+
},
|
|
466
|
+
/** Explicitly dispose a stream that was never iterated (or has another owner). */
|
|
467
|
+
async dispose(id:string):Promise<void>{
|
|
468
|
+
const ignoreMissing=(error:unknown)=>{if(!/^(operation_missing|network_job_missing|permission_denied)$/.test(error instanceof Error?error.message:String(error)))throw error};
|
|
469
|
+
try{await network.cancel(id)}catch(error){ignoreMissing(error)}
|
|
470
|
+
try{await network.release(id)}catch(error){ignoreMissing(error)}
|
|
471
|
+
},
|
|
472
|
+
async text(id:string):Promise<string>{
|
|
473
|
+
const decoder=new TextDecoder();let offset=0,text='';
|
|
474
|
+
for(;;){const part=await network.read(id,offset);const bytes=Uint8Array.from(atob(part.data_base64),c=>c.charCodeAt(0));text+=decoder.decode(bytes,{stream:!part.eof});if(part.eof)return text;offset=part.next_offset;}
|
|
475
|
+
},
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
/** Workspace operations use current directory references and asynchronous jobs. */
|
|
479
|
+
export interface FileRoot {id:string|null;name:string;available:boolean;error?:string}
|
|
480
|
+
export interface FileEntry {path:string;name:string;kind:'file'|'directory'|'blocked';size:number;revision:string;accessible:boolean}
|
|
481
|
+
export interface FileRecord {id:string;operation:string;source:string;destination:string;status:string;has_original:boolean;in_trash?:boolean|null;created_ms:number|null;retention:"workspace"|"trash"|"none"|"unknown"}
|
|
482
|
+
export interface FileJob<T=unknown> {id:string;status:'running'|'completed'|'failed'|'cancelled';result:T|null;error:string|null;method?:string}
|
|
483
|
+
export interface FileWatch {id:string;status:'starting'|'watching'|'stopped'|'failed';cursor?:number;error?:string|null}
|
|
484
|
+
export interface FileWatchEvents extends FileWatch {cursor:number;rescan_required:boolean;events:{cursor:number;kind:'ready'|'created'|'changed'|'removed'|'rescan_required';path:string|null}[]}
|
|
485
|
+
export interface FilePreview {id:string;path:string;bytes:number;count:number;revision:string|null;purpose:string;record:string|null}
|
|
486
|
+
export interface FileHistoryPage {items:FileRecord[];next_cursor:string|null;total:number}
|
|
487
|
+
/** A file the user handed the plugin (picker or drop): import it once with `files.import`. No path. */
|
|
488
|
+
export interface FileSource {source?:string;name:string|null;size?:number;error?:string}
|
|
489
|
+
/** `files.import` while it runs: `progress` appears on `files.state`. */
|
|
490
|
+
export interface FileImportJob extends FileJob<FileEntry> {progress?:{done:number;total:number}}
|
|
491
|
+
export const files = {
|
|
492
|
+
backupPreview:(root:string,record:string)=>capabilities.invoke<FileJob<FilePreview>>('files.backup_preview',{root,record}),
|
|
493
|
+
archiveBackup:(preview:string)=>capabilities.invoke<FileJob<FileRecord>>('files.archive_backup',{preview}),
|
|
494
|
+
forgetPreview:(root:string,record:string)=>capabilities.invoke<FileJob<FilePreview>>('files.forget_preview',{root,record}),
|
|
495
|
+
forgetRecord:(preview:string)=>capabilities.invoke<FileJob<{forgotten:string}>>('files.forget_record',{preview}),
|
|
496
|
+
historyPage:(root:string,cursor?:string,limit=50)=>capabilities.invoke<FileJob<FileHistoryPage>>('files.history_page',{root,...(cursor?{cursor}:{}),limit}),
|
|
497
|
+
trashPreview:(root:string,path:string)=>capabilities.invoke<FileJob<FilePreview>>('files.trash_preview',{root,path}),
|
|
498
|
+
discardPreview:(preview:string)=>capabilities.invoke<{discarded:boolean}>('files.discard_preview',{preview}),
|
|
499
|
+
trash:(preview:string)=>capabilities.invoke<FileJob<FileRecord>>('files.trash',{preview}),
|
|
500
|
+
/** Breadth-first listings of a whole tree in one call. Hidden and `skip`
|
|
501
|
+
* directories are listed by their parent but not entered. */
|
|
502
|
+
listTree:(root:string,path='',options:{depth?:number;skip?:string[];hidden?:boolean;limit?:number}={})=>capabilities.invoke<FileJob<{directories:{path:string;entries?:FileEntry[];error?:string}[];truncated:boolean}>>('files.list_tree',{root,path,...options}),
|
|
503
|
+
/** Full-access roots only: move entries to the Trash without a Host confirmation.
|
|
504
|
+
* `stamp` is what `files.measure` returned; a changed entry is refused, not moved. */
|
|
505
|
+
trashDirect:(items:{root:string;path:string;stamp:{revision:string;digest:string;bytes:number;count:number}}[])=>capabilities.invoke<FileJob<{path:string;record?:FileRecord;error?:string}[]>>('files.trash_direct',{items}),
|
|
506
|
+
watch:(root:string,path='',recursive=false)=>capabilities.invoke<FileWatch>('files.watch',{root,path,recursive}),
|
|
507
|
+
watches:()=>capabilities.invoke<FileWatch[]>('files.watches'),
|
|
508
|
+
events:(id:string,after=0)=>capabilities.invoke<FileWatchEvents>('files.events',{id,after}),
|
|
509
|
+
unwatch:(id:string)=>capabilities.invoke<{stopped:boolean}>('files.unwatch',{id}),
|
|
510
|
+
roots:()=>capabilities.invoke<FileJob<FileRoot[]>>('files.roots'),
|
|
511
|
+
list:(root:string,path='')=>capabilities.invoke<FileJob<FileEntry[]>>('files.list',{root,path}),
|
|
512
|
+
stat:(root:string,path='')=>capabilities.invoke<FileJob<FileEntry>>('files.stat',{root,path}),
|
|
513
|
+
readText:(root:string,path:string,revision?:string)=>capabilities.invoke<FileJob<{text:string;entry:FileEntry}>>('files.read_text',{root,path,...(revision?{revision}:{})}),
|
|
514
|
+
writeText:(root:string,path:string,text:string,revision:string)=>capabilities.invoke<FileJob<{record:FileRecord;entry:FileEntry|null}>>('files.write_text',{root,path,text,revision}),
|
|
515
|
+
mkdir:(root:string,path:string)=>capabilities.invoke<FileJob<FileEntry>>('files.mkdir',{root,path}),
|
|
516
|
+
move:(root:string,path:string,destination:string,revision:string)=>capabilities.invoke<FileJob<FileRecord>>('files.move',{root,path,destination,revision}),
|
|
517
|
+
history:(root:string)=>capabilities.invoke<FileJob<FileRecord[]>>('files.history',{root}),
|
|
518
|
+
restore:(root:string,record:string)=>capabilities.invoke<FileJob<FileRecord>>('files.restore',{root,record}),
|
|
519
|
+
// Medeo 0.1.43+: files in and out of a grant. Bytes and real paths never pass through the plugin.
|
|
520
|
+
/** From a plugin window: the system picker; the chosen files become one-use sources. */
|
|
521
|
+
chooseFiles:()=>capabilities.invoke<FileSource[]>('files.chooseFiles'),
|
|
522
|
+
/** Files dropped on this window (`event.dataTransfer.files` in a `drop` handler) as one-use sources. */
|
|
523
|
+
fromDrop:(files:ArrayLike<File>)=>globalThis.medeoPlugin.dropped?globalThis.medeoPlugin.dropped(Array.from(files)):Promise.reject(new Error('capability_unavailable')), // a FileList does not cross the context bridge; an array of Files does
|
|
524
|
+
/** Copy a source to `path` in `root`; a taken name is `file_exists`, or `name (2).ext` with `keepBoth`. */
|
|
525
|
+
import:(root:string,path:string,source:string,options:{keepBoth?:boolean}={})=>capabilities.invoke<FileImportJob>('files.import',{root,path,source,...(options.keepBoth?{keep_both:true}:{})}),
|
|
526
|
+
/** From a plugin window: copies to where the user picks (save panel for one file, a folder for several). */
|
|
527
|
+
export:(root:string,paths:string[])=>capabilities.invoke<{exported:{name:string;as:string}[];folder:string|null}>('files.export',{root,paths}),
|
|
528
|
+
/** From a plugin window: open with the default app / show in Finder. */
|
|
529
|
+
open:(root:string,path:string)=>capabilities.invoke<null>('files.open',{root,path}),
|
|
530
|
+
reveal:(root:string,path:string)=>capabilities.invoke<null>('files.reveal',{root,path}),
|
|
531
|
+
/** Call in a `dragstart` handler (after `event.preventDefault()`): the system drags these files out. */
|
|
532
|
+
startDrag:(root:string,paths:string[])=>capabilities.invoke<null>('files.startDrag',{root,paths}),
|
|
533
|
+
state:<T=unknown>(id:string)=>operations.state<T>(id) as Promise<FileJob<T>>,
|
|
534
|
+
cancel:(id:string)=>operations.cancel(id),
|
|
535
|
+
release:(id:string)=>operations.release(id),
|
|
536
|
+
result:<T>(job:FileJob<T>):Promise<T>=>operations.wait<T>(job),
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
/** Plugin-owned credentials. Values are returned only to this granted plugin;
|
|
540
|
+
* Agent/Medeo credentials are never part of this vault. No automatic retry. */
|
|
541
|
+
export interface SecretOperation { id:string; status:'running'|'completed'|'failed'; value?:string|null; error?:string }
|
|
542
|
+
async function secretOperation(method:'get'|'set'|'remove',args:Record<string,unknown>):Promise<string|null>{
|
|
543
|
+
const job=await capabilities.invoke<SecretOperation>('secrets.'+method,args);
|
|
544
|
+
const deadline=Date.now()+30000;
|
|
545
|
+
for(;;){
|
|
546
|
+
const change=nextChange(job.id,1000);
|
|
547
|
+
const result=await capabilities.invoke<SecretOperation>('secrets.result',{id:job.id});
|
|
548
|
+
if(result.status!=='running')change.off();
|
|
549
|
+
if(result.status==='completed')return result.value??null;
|
|
550
|
+
if(result.status==='failed')throw Error(result.error??'secrets_storage_failed');
|
|
551
|
+
if(Date.now()>=deadline){change.off();throw Error('secrets_outcome_unknown')}
|
|
552
|
+
await change.promise;change.off();
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
export const secrets={
|
|
556
|
+
get:(key:string)=>secretOperation('get',{key}),
|
|
557
|
+
set:async(key:string,value:string)=>{await secretOperation('set',{key,value})},
|
|
558
|
+
remove:async(key:string)=>{await secretOperation('remove',{key})},
|
|
559
|
+
};
|
|
560
|
+
|
|
561
|
+
export interface LocalServerOptions { port?:number; routes:{method:'GET'|'HEAD'|'POST'|'PUT'|'PATCH'|'DELETE';path:string}[]; origins?:string[]; timeout_ms?:number }
|
|
562
|
+
export interface LocalServerState { id:string; status:'starting'|'running'|'stopping'|'stopped'|'failed'; origin:string|null; error:string|null; pending:number; accepted:number }
|
|
563
|
+
export interface LocalRequest { id:string; method:string; path:string; query:string; headers:Record<string,string>; body_base64:string }
|
|
564
|
+
/** A loopback server is instance-owned and never survives Host restart. Keep the
|
|
565
|
+
* start token in private memory and serve requests in a worker for background use. */
|
|
566
|
+
export const server={
|
|
567
|
+
start:(options:LocalServerOptions)=>capabilities.invoke<{id:string;status:'starting';access_token:string}>('server.start',{...options}),
|
|
568
|
+
state:(id:string)=>capabilities.invoke<LocalServerState>('server.state',{id}),
|
|
569
|
+
list:()=>capabilities.invoke<LocalServerState[]>('server.state'),
|
|
570
|
+
events:(id:string,limit=8)=>capabilities.invoke<{requests:LocalRequest[]}>('server.events',{id,limit}),
|
|
571
|
+
respond:(id:string,request:string,response:{status?:number;body_base64?:string;content_type?:string})=>capabilities.invoke<{responded:boolean}>('server.respond',{id,request,...response}),
|
|
572
|
+
stop:(id:string)=>capabilities.invoke<LocalServerState>('server.stop',{id}),
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
export interface PluginLocaleState {preference:string;locale:string;system_locale:string;direction:'ltr';supported_locales:string[];catalog_locales:string[];catalog_locale:string|null;fallback_locale:string|null;name:string;commands:Record<string,string>}
|
|
577
|
+
/** Text is formatted in Rust from the signed package. Render with textContent,
|
|
578
|
+
* never innerHTML. Register listeners before initial state fetch to avoid races. */
|
|
579
|
+
export const i18n={
|
|
580
|
+
state:()=>capabilities.invoke<PluginLocaleState>('i18n.state'),
|
|
581
|
+
setLocale:(preference:string)=>capabilities.invoke<PluginLocaleState>('i18n.setLocale',{preference}),
|
|
582
|
+
t:(key:string,params:Record<string,string|number>={})=>capabilities.invoke<string>('i18n.t',{key,params}),
|
|
583
|
+
/** Every message of the effective locale (default-locale fallback merged in). */
|
|
584
|
+
catalog:()=>capabilities.invoke<Record<string,string>>('i18n.catalog'),
|
|
585
|
+
onDidChangeLocale:(callback:(state:PluginLocaleState)=>void)=>globalThis.medeoPlugin.onLocaleChanged(callback),
|
|
586
|
+
};
|
|
587
|
+
|
|
588
|
+
/** Every asynchronous call returns an owned operation handle. Status changes
|
|
589
|
+
* are pushed; `wait` resolves on them and releases the result. */
|
|
590
|
+
export interface NativeOperation<T=unknown>{id:string;status:'running'|'completed'|'failed'|'cancelled'|'interrupted';result:T|null;error:string|null}
|
|
591
|
+
export const operations={
|
|
592
|
+
state:<T=unknown>(id:string)=>capabilities.invoke<NativeOperation<T>>('operations.state',{id}),
|
|
593
|
+
list:()=>capabilities.invoke<{id:string;method:string;status:string}[]>('operations.list'),
|
|
594
|
+
cancel:(id:string)=>capabilities.invoke('operations.cancel',{id}),
|
|
595
|
+
release:(id:string)=>capabilities.invoke('operations.release',{id}),
|
|
596
|
+
async wait<T>(operation:{id:string;status:string},signal?:AbortSignal):Promise<T>{
|
|
597
|
+
let value=operation as NativeOperation<T>;
|
|
598
|
+
while(value.status==='running'){
|
|
599
|
+
if(signal?.aborted){await operations.cancel(value.id);throw Error('cancelled')}
|
|
600
|
+
const change=nextChange(value.id,2000);
|
|
601
|
+
value=await operations.state<T>(value.id);
|
|
602
|
+
if(value.status==='running')await change.promise;
|
|
603
|
+
change.off();
|
|
604
|
+
}
|
|
605
|
+
// Quick reads may come back settled and already released by the Host.
|
|
606
|
+
if(!(value as {released?:boolean}).released)await operations.release(value.id);
|
|
607
|
+
if(value.status!=='completed')throw Error(value.error??value.status);
|
|
608
|
+
return value.result as T;
|
|
609
|
+
},
|
|
610
|
+
};
|
|
611
|
+
const nativeCall=<T=unknown>(method:string,args:Record<string,JsonValue>={})=>capabilities.invoke<NativeOperation<T>>(method,args);
|
|
612
|
+
/** A camera / microphone / system audio recording. `waveform` (240 peaks, 0…1) is in `state(id)` once
|
|
613
|
+
* completed; listings carry a 40-point `waveform_preview` instead. Live fields exist only while recording:
|
|
614
|
+
* `levels` holds the latest input levels (0…1, about 20 a second) and `levels_seq` counts every level so far;
|
|
615
|
+
* `frame` is the camera's latest preview as base64 JPEG. "completed" means `previewURL` can play it. */
|
|
616
|
+
export interface MediaRecord {id:string;kind:'camera'|'microphone'|'system_audio';status:'starting'|'recording'|'stopping'|'completed'|'failed'|'interrupted';error?:string|null;created_ms:number;extension:string;duration_ms?:number;bytes?:number;waveform?:number[];waveform_preview?:number[];elapsed_ms?:number;level?:number;peak?:number;levels?:number[];levels_seq?:number;frame?:string}
|
|
617
|
+
function mediaProvider(kind:'camera'|'microphone'|'system_audio'){return{
|
|
618
|
+
status:()=>nativeCall<{authorization:string}>(kind+'.status'),
|
|
619
|
+
start:(maxSeconds=300)=>nativeCall<{id:string;status:string}>(kind+'.start',{max_seconds:maxSeconds}),
|
|
620
|
+
stop:(id:string)=>nativeCall(kind+'.stop',{id}),
|
|
621
|
+
state:(id?:string)=>nativeCall(kind+'.state',id?{id}:{}),
|
|
622
|
+
read:(id:string,offset=0,length=32768)=>nativeCall<NetworkChunk>(kind+'.read',{id,offset,length}),
|
|
623
|
+
/** Same-origin URL for an `<audio>` / `<video>` element; plays once the record is "completed". */
|
|
624
|
+
previewURL:(record:Pick<MediaRecord,'id'|'extension'>)=>location.origin+'/_media/'+encodeURIComponent(record.id)+(record.extension==='m4a'?'.m4a':'.mp4'),
|
|
625
|
+
}}
|
|
626
|
+
export const camera=mediaProvider('camera'),microphone=mediaProvider('microphone'),systemAudio=mediaProvider('system_audio');
|
|
627
|
+
export const accessibility={status:()=>nativeCall('accessibility.status'),request:()=>nativeCall('accessibility.request'),windows:()=>nativeCall<{id:string;title:string;application:string}[]>('accessibility.windows'),focus:(id:string)=>nativeCall('accessibility.focus',{id}),selectedText:(id:string)=>nativeCall<{id:string;text:string}>('accessibility.selected_text',{id}),insertText:(focus:string,text:string)=>nativeCall('accessibility.insert_text',{id:focus,text})};
|
|
628
|
+
/** A rectangle in global points: origin at the top-left of the main display, y grows downwards
|
|
629
|
+
* (displays left of or above the main one have negative coordinates). */
|
|
630
|
+
export interface WindowFrame {x:number;y:number;width:number;height:number}
|
|
631
|
+
/** The frontmost window of another app. `id` stays the same for the same window while it lives. */
|
|
632
|
+
export interface ManagedWindow {id:string;title:string;application:string;bundle_id:string;frame:WindowFrame;resizable:boolean;fullscreen:boolean;minimized:boolean;standard:boolean}
|
|
633
|
+
/** `visible_frame` excludes the menu bar and the Dock. `id` is the display number for this session,
|
|
634
|
+
* `uuid` survives restarts and reconnecting. The first entry is the main display. */
|
|
635
|
+
export interface ManagedScreen {id:string;uuid:string;name:string;primary:boolean;scale:number;frame:WindowFrame;visible_frame:WindowFrame}
|
|
636
|
+
/** Window management (macOS, permission `window_management`, OS Accessibility). All calls are
|
|
637
|
+
* operations: `operations.wait(await windowManagement.focused())`. `request` opens the system
|
|
638
|
+
* prompt and is window-only; the others work in the worker too. `focused` never returns a Medeo window:
|
|
639
|
+
* when Medeo is in front (a plugin's own page) it is the window of the app right behind it, and `null`
|
|
640
|
+
* when there is none or the frontmost app has no window; `set_frame` reports the frame the app
|
|
641
|
+
* actually accepted (apps may clamp sizes) and fails with `resource_missing` once the window is gone. */
|
|
642
|
+
export const windowManagement={
|
|
643
|
+
status:()=>nativeCall<{authorization:'granted'|'denied'}>('window_management.status'),
|
|
644
|
+
request:()=>nativeCall<{authorization:'granted'|'denied'}>('window_management.request'),
|
|
645
|
+
focused:()=>nativeCall<ManagedWindow|null>('window_management.focused'),
|
|
646
|
+
setFrame:(id:string,frame:WindowFrame)=>nativeCall<{frame:WindowFrame;resized:boolean}>('window_management.set_frame',{id,x:frame.x,y:frame.y,width:frame.width,height:frame.height}),
|
|
647
|
+
screens:()=>nativeCall<ManagedScreen[]>('window_management.screens'),
|
|
648
|
+
pointer:()=>nativeCall<{x:number;y:number}>('window_management.pointer'),
|
|
649
|
+
};
|
|
650
|
+
export const browserView={open:(id:string,url:string,width=1000,height=720)=>capabilities.invoke('browser.open',{id,url,width,height}),state:(id:string)=>capabilities.invoke('browser.state',{id}),close:(id:string)=>capabilities.invoke('browser.close',{id})};
|
|
651
|
+
export const printing={print:(text:string)=>capabilities.invoke('printing.print',{text})};
|
|
652
|
+
export const processes={start:(executable:string,args:string[]=[],timeoutMs=60000)=>nativeCall<{id:string;status:string}>('process.start',{executable,arguments:args,timeout_ms:timeoutMs}),state:(id:string)=>nativeCall<{status:string;exit_code:number|null;stdout:string;stderr:string;truncated:boolean}>('process.state',{id}),write:(id:string,text:string)=>nativeCall<{written:number}>('process.write',{id,text}),stop:(id:string)=>nativeCall('process.stop',{id})};
|
|
653
|
+
export interface BackgroundEvent{id:string;schedule:string;due_ms:number;payload:JsonValue}
|
|
654
|
+
export const background={schedule:(id:string,delayMs:number,payload:JsonValue=null,intervalMs=0)=>capabilities.invoke('background.schedule',{id,delay_ms:delayMs,interval_ms:intervalMs,payload}),list:()=>capabilities.invoke('background.list'),cancel:(id:string)=>capabilities.invoke('background.cancel',{id}),events:()=>capabilities.invoke<BackgroundEvent[]>('background.events')};
|
|
655
|
+
export const contacts={status:()=>nativeCall('contacts.status'),request:()=>nativeCall('contacts.request'),list:(query='',limit=50)=>nativeCall('contacts.list',{query,limit}),save:(contact:{given_name:string;family_name:string;email:string;phone:string})=>nativeCall<{id:string;created:boolean}>('contacts.save',contact)};
|
|
656
|
+
export const calendar={status:()=>nativeCall('calendar.status'),request:()=>nativeCall('calendar.request'),list:(startMs:number,endMs:number,limit=50)=>nativeCall('calendar.list',{start_ms:startMs,end_ms:endMs,limit}),save:(event:{title:string;notes:string;start_ms:number;end_ms:number})=>nativeCall<{id:string;created:boolean}>('calendar.save',event)};
|
|
657
|
+
export const deviceLocation={status:()=>nativeCall('location.status'),request:()=>nativeCall('location.request'),current:()=>nativeCall<{latitude:number;longitude:number;accuracy_m:number;timestamp_ms:number}>('location.current')};
|
|
658
|
+
export const devices={choose:(transport:'serial'|'hid'|'ble')=>nativeCall('devices.choose',{transport}),open:(id:string,baudRate=115200)=>nativeCall('devices.open',{id,baud_rate:baudRate}),list:()=>nativeCall('devices.list'),read:(id:string,length=4096)=>nativeCall<{data_base64:string;bytes:number}>('devices.read',{id,length}),write:(id:string,dataBase64:string)=>nativeCall<{written:number}>('devices.write',{id,data_base64:dataBase64}),close:(id:string)=>nativeCall('devices.close',{id})};
|