@tyvm/knowhow-app-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -2
- package/dist/index.cjs +1141 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +528 -0
- package/dist/index.d.ts +528 -0
- package/dist/index.js +1101 -0
- package/dist/index.js.map +1 -0
- package/dist/knowhow-sdk.iife.js +1 -0
- package/package.json +37 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1101 @@
|
|
|
1
|
+
// ../app-protocol/dist/chunk-RLOKSSFV.js
|
|
2
|
+
var PROTOCOL_VERSION = 1;
|
|
3
|
+
var Methods = {
|
|
4
|
+
Protocol: "kh_protocol",
|
|
5
|
+
Connect: "kh_connect",
|
|
6
|
+
Session: "kh_session",
|
|
7
|
+
Disconnect: "kh_disconnect",
|
|
8
|
+
DbQuery: "kh_db_query",
|
|
9
|
+
DbExec: "kh_db_exec",
|
|
10
|
+
DbBatch: "kh_db_batch",
|
|
11
|
+
KvGet: "kh_kv_get",
|
|
12
|
+
KvSet: "kh_kv_set",
|
|
13
|
+
KvDelete: "kh_kv_delete",
|
|
14
|
+
FilesList: "kh_files_list",
|
|
15
|
+
FilesRead: "kh_files_read",
|
|
16
|
+
FilesWrite: "kh_files_write",
|
|
17
|
+
FilesStat: "kh_files_stat",
|
|
18
|
+
FilesDelete: "kh_files_delete",
|
|
19
|
+
FilesUploadStart: "kh_files_upload_start",
|
|
20
|
+
FilesUploadComplete: "kh_files_upload_complete",
|
|
21
|
+
FilesDownloadUrl: "kh_files_download_url",
|
|
22
|
+
AiComplete: "kh_ai_complete",
|
|
23
|
+
AiTranscribe: "kh_ai_transcribe",
|
|
24
|
+
AiImage: "kh_ai_image",
|
|
25
|
+
SpendGet: "kh_spend_get",
|
|
26
|
+
AppEnv: "kh_app_env",
|
|
27
|
+
ToolsRegister: "kh_tools_register",
|
|
28
|
+
ToolsResult: "kh_tools_result",
|
|
29
|
+
UiNotify: "kh_ui_notify"
|
|
30
|
+
};
|
|
31
|
+
var HOST_LOCAL_METHODS = [
|
|
32
|
+
Methods.Protocol,
|
|
33
|
+
Methods.Connect,
|
|
34
|
+
Methods.Session,
|
|
35
|
+
Methods.Disconnect,
|
|
36
|
+
Methods.ToolsRegister,
|
|
37
|
+
Methods.ToolsResult,
|
|
38
|
+
Methods.UiNotify
|
|
39
|
+
];
|
|
40
|
+
var Events = {
|
|
41
|
+
Connect: "connect",
|
|
42
|
+
Disconnect: "disconnect",
|
|
43
|
+
SessionChanged: "sessionChanged",
|
|
44
|
+
ToolCall: "toolCall",
|
|
45
|
+
Message: "message"
|
|
46
|
+
};
|
|
47
|
+
var AI_TRANSCRIBE_MAX_AUDIO_BYTES = 25 * 1024 * 1024;
|
|
48
|
+
var AI_IMAGE_MAX_N = 4;
|
|
49
|
+
var AI_IMAGE_MAX_INPUTS = 4;
|
|
50
|
+
var ALL_METHODS = Object.values(Methods);
|
|
51
|
+
var HELLO_TYPE = "kh:hello";
|
|
52
|
+
var PORT_TYPE = "kh:port";
|
|
53
|
+
var INIT_TYPE = "kh:init";
|
|
54
|
+
var CAPABILITIES = [
|
|
55
|
+
"db:app",
|
|
56
|
+
"files:app",
|
|
57
|
+
"ai:complete",
|
|
58
|
+
"ai:transcribe",
|
|
59
|
+
"ai:image",
|
|
60
|
+
"tools:expose"
|
|
61
|
+
];
|
|
62
|
+
var METHOD_CAPABILITY = {
|
|
63
|
+
[Methods.Protocol]: null,
|
|
64
|
+
[Methods.Connect]: null,
|
|
65
|
+
[Methods.Session]: null,
|
|
66
|
+
[Methods.Disconnect]: null,
|
|
67
|
+
[Methods.DbQuery]: "db:app",
|
|
68
|
+
[Methods.DbExec]: "db:app",
|
|
69
|
+
[Methods.DbBatch]: "db:app",
|
|
70
|
+
[Methods.KvGet]: "db:app",
|
|
71
|
+
[Methods.KvSet]: "db:app",
|
|
72
|
+
[Methods.KvDelete]: "db:app",
|
|
73
|
+
[Methods.FilesList]: "files:app",
|
|
74
|
+
[Methods.FilesRead]: "files:app",
|
|
75
|
+
[Methods.FilesWrite]: "files:app",
|
|
76
|
+
[Methods.FilesStat]: "files:app",
|
|
77
|
+
[Methods.FilesDelete]: "files:app",
|
|
78
|
+
[Methods.FilesUploadStart]: "files:app",
|
|
79
|
+
[Methods.FilesUploadComplete]: "files:app",
|
|
80
|
+
[Methods.FilesDownloadUrl]: "files:app",
|
|
81
|
+
[Methods.AiComplete]: "ai:complete",
|
|
82
|
+
[Methods.AiTranscribe]: "ai:transcribe",
|
|
83
|
+
[Methods.AiImage]: "ai:image",
|
|
84
|
+
[Methods.SpendGet]: null,
|
|
85
|
+
[Methods.AppEnv]: null,
|
|
86
|
+
[Methods.ToolsRegister]: "tools:expose",
|
|
87
|
+
[Methods.ToolsResult]: null,
|
|
88
|
+
[Methods.UiNotify]: null
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// ../app-protocol/dist/index.js
|
|
92
|
+
var ErrorCodes = {
|
|
93
|
+
USER_REJECTED: 4001,
|
|
94
|
+
UNAUTHORIZED: 4100,
|
|
95
|
+
UNSUPPORTED_METHOD: 4200,
|
|
96
|
+
RATE_LIMITED: 4290,
|
|
97
|
+
/** The app/site hit its USD AI spend limit. `data`: SpendLimitReachedData. */
|
|
98
|
+
SPEND_LIMIT_REACHED: 4291,
|
|
99
|
+
DISCONNECTED: 4900,
|
|
100
|
+
INVALID_PARAMS: -32602,
|
|
101
|
+
INTERNAL: -32603
|
|
102
|
+
};
|
|
103
|
+
var ProviderRpcError = class _ProviderRpcError extends Error {
|
|
104
|
+
constructor(code, message, data) {
|
|
105
|
+
super(message);
|
|
106
|
+
this.name = "ProviderRpcError";
|
|
107
|
+
this.code = code;
|
|
108
|
+
this.data = data;
|
|
109
|
+
Object.setPrototypeOf(this, _ProviderRpcError.prototype);
|
|
110
|
+
}
|
|
111
|
+
toJSON() {
|
|
112
|
+
const out = { code: this.code, message: this.message };
|
|
113
|
+
if (this.data !== void 0) out.data = this.data;
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
static fromPayload(payload) {
|
|
117
|
+
return new _ProviderRpcError(payload.code, payload.message, payload.data);
|
|
118
|
+
}
|
|
119
|
+
/** Normalize anything thrown into a payload suitable for the wire. */
|
|
120
|
+
static toPayload(err) {
|
|
121
|
+
if (err instanceof _ProviderRpcError) return err.toJSON();
|
|
122
|
+
if (isErrorPayload(err)) return { code: err.code, message: err.message, data: err.data };
|
|
123
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
124
|
+
return { code: ErrorCodes.INTERNAL, message };
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
function isErrorPayload(v) {
|
|
128
|
+
if (typeof v !== "object" || v === null) return false;
|
|
129
|
+
const o = v;
|
|
130
|
+
return typeof o.code === "number" && typeof o.message === "string";
|
|
131
|
+
}
|
|
132
|
+
var ANNOUNCE_EVENT = "knowhow:announceProvider";
|
|
133
|
+
var REQUEST_EVENT = "knowhow:requestProvider";
|
|
134
|
+
function defaultTarget() {
|
|
135
|
+
if (typeof window !== "undefined") return window;
|
|
136
|
+
throw new Error("No event target available; pass one explicitly");
|
|
137
|
+
}
|
|
138
|
+
function requestProviders(handler, target = defaultTarget()) {
|
|
139
|
+
const listener = (ev) => {
|
|
140
|
+
const detail = ev.detail;
|
|
141
|
+
if (detail && detail.info && detail.provider && detail.info.protocol === PROTOCOL_VERSION) handler(detail);
|
|
142
|
+
};
|
|
143
|
+
target.addEventListener(ANNOUNCE_EVENT, listener);
|
|
144
|
+
target.dispatchEvent(new Event(REQUEST_EVENT));
|
|
145
|
+
return () => target.removeEventListener(ANNOUNCE_EVENT, listener);
|
|
146
|
+
}
|
|
147
|
+
var INTERACTIVE_METHODS = /* @__PURE__ */ new Set(["kh_connect"]);
|
|
148
|
+
function createProviderFromEndpoint(endpoint) {
|
|
149
|
+
const subs = /* @__PURE__ */ new Map();
|
|
150
|
+
return {
|
|
151
|
+
endpoint,
|
|
152
|
+
request: (args) => endpoint.request(args.method, args.params, INTERACTIVE_METHODS.has(args.method) ? 0 : void 0),
|
|
153
|
+
on(event, listener) {
|
|
154
|
+
const off = endpoint.on(event, (data) => listener(data));
|
|
155
|
+
subs.set(listener, off);
|
|
156
|
+
},
|
|
157
|
+
removeListener(_event, listener) {
|
|
158
|
+
subs.get(listener)?.();
|
|
159
|
+
subs.delete(listener);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function isObj(v) {
|
|
164
|
+
return typeof v === "object" && v !== null;
|
|
165
|
+
}
|
|
166
|
+
var isId = (v) => typeof v === "number" || typeof v === "string";
|
|
167
|
+
function isRequestFrame(v) {
|
|
168
|
+
return isObj(v) && isId(v.id) && typeof v.method === "string";
|
|
169
|
+
}
|
|
170
|
+
function isResponseFrame(v) {
|
|
171
|
+
return isObj(v) && isId(v.id) && typeof v.method !== "string" && ("result" in v || "error" in v);
|
|
172
|
+
}
|
|
173
|
+
function isEventFrame(v) {
|
|
174
|
+
return isObj(v) && typeof v.event === "string" && !("id" in v);
|
|
175
|
+
}
|
|
176
|
+
var RpcEndpoint = class {
|
|
177
|
+
constructor(transport, opts = {}) {
|
|
178
|
+
this.transport = transport;
|
|
179
|
+
this.nextId = 1;
|
|
180
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
181
|
+
this.listeners = /* @__PURE__ */ new Map();
|
|
182
|
+
this.closed = false;
|
|
183
|
+
this.timeoutMs = opts.timeoutMs ?? 3e4;
|
|
184
|
+
this.onRequest = opts.onRequest;
|
|
185
|
+
this.nonce = opts.nonce;
|
|
186
|
+
const filter = opts.filter;
|
|
187
|
+
this.handleMessage = (ev) => {
|
|
188
|
+
if (this.closed) return;
|
|
189
|
+
if (filter && !filter(ev)) return;
|
|
190
|
+
if (this.nonce !== void 0) {
|
|
191
|
+
const n = ev.data?.nonce;
|
|
192
|
+
if (typeof n !== "string" || n !== this.nonce) return;
|
|
193
|
+
}
|
|
194
|
+
this.dispatch(ev.data);
|
|
195
|
+
};
|
|
196
|
+
transport.addEventListener("message", this.handleMessage);
|
|
197
|
+
transport.start?.();
|
|
198
|
+
}
|
|
199
|
+
setRequestHandler(handler) {
|
|
200
|
+
this.onRequest = handler;
|
|
201
|
+
}
|
|
202
|
+
request(method, params, timeoutMs) {
|
|
203
|
+
if (this.closed) {
|
|
204
|
+
return Promise.reject(new ProviderRpcError(ErrorCodes.DISCONNECTED, "Endpoint closed"));
|
|
205
|
+
}
|
|
206
|
+
const id = this.nextId++;
|
|
207
|
+
const ms = timeoutMs ?? this.timeoutMs;
|
|
208
|
+
return new Promise((resolve, reject) => {
|
|
209
|
+
const entry = { resolve, reject };
|
|
210
|
+
if (ms > 0) {
|
|
211
|
+
entry.timer = setTimeout(() => {
|
|
212
|
+
this.pending.delete(id);
|
|
213
|
+
reject(new ProviderRpcError(ErrorCodes.INTERNAL, `Request timed out: ${method}`));
|
|
214
|
+
}, ms);
|
|
215
|
+
}
|
|
216
|
+
this.pending.set(id, entry);
|
|
217
|
+
const frame = this.stamp(params === void 0 ? { id, method } : { id, method, params });
|
|
218
|
+
try {
|
|
219
|
+
this.transport.postMessage(frame);
|
|
220
|
+
} catch (e) {
|
|
221
|
+
this.settle(id);
|
|
222
|
+
reject(e);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
emit(event, data) {
|
|
227
|
+
if (this.closed) return;
|
|
228
|
+
const frame = this.stamp(data === void 0 ? { event } : { event, data });
|
|
229
|
+
this.transport.postMessage(frame);
|
|
230
|
+
}
|
|
231
|
+
on(event, cb) {
|
|
232
|
+
let set = this.listeners.get(event);
|
|
233
|
+
if (!set) this.listeners.set(event, set = /* @__PURE__ */ new Set());
|
|
234
|
+
set.add(cb);
|
|
235
|
+
return () => this.off(event, cb);
|
|
236
|
+
}
|
|
237
|
+
off(event, cb) {
|
|
238
|
+
this.listeners.get(event)?.delete(cb);
|
|
239
|
+
}
|
|
240
|
+
close() {
|
|
241
|
+
if (this.closed) return;
|
|
242
|
+
this.closed = true;
|
|
243
|
+
this.transport.removeEventListener?.("message", this.handleMessage);
|
|
244
|
+
for (const [id] of this.pending) {
|
|
245
|
+
const p = this.settle(id);
|
|
246
|
+
p?.reject(new ProviderRpcError(ErrorCodes.DISCONNECTED, "Endpoint closed"));
|
|
247
|
+
}
|
|
248
|
+
this.transport.close?.();
|
|
249
|
+
this.dispatchLocal("close", void 0);
|
|
250
|
+
}
|
|
251
|
+
get isClosed() {
|
|
252
|
+
return this.closed;
|
|
253
|
+
}
|
|
254
|
+
stamp(frame) {
|
|
255
|
+
return this.nonce === void 0 ? frame : { ...frame, nonce: this.nonce };
|
|
256
|
+
}
|
|
257
|
+
settle(id) {
|
|
258
|
+
const p = this.pending.get(id);
|
|
259
|
+
if (p) {
|
|
260
|
+
if (p.timer) clearTimeout(p.timer);
|
|
261
|
+
this.pending.delete(id);
|
|
262
|
+
}
|
|
263
|
+
return p;
|
|
264
|
+
}
|
|
265
|
+
dispatchLocal(event, data) {
|
|
266
|
+
for (const cb of Array.from(this.listeners.get(event) ?? [])) {
|
|
267
|
+
try {
|
|
268
|
+
cb(data);
|
|
269
|
+
} catch {
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
dispatch(msg) {
|
|
274
|
+
if (isRequestFrame(msg)) {
|
|
275
|
+
void this.handleRequest(msg);
|
|
276
|
+
} else if (isResponseFrame(msg)) {
|
|
277
|
+
const p = this.settle(msg.id);
|
|
278
|
+
if (!p) return;
|
|
279
|
+
if (msg.error && isErrorPayload(msg.error)) p.reject(ProviderRpcError.fromPayload(msg.error));
|
|
280
|
+
else p.resolve(msg.result);
|
|
281
|
+
} else if (isEventFrame(msg)) {
|
|
282
|
+
this.dispatchLocal(msg.event, msg.data);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
async handleRequest(req) {
|
|
286
|
+
let response;
|
|
287
|
+
if (!this.onRequest) {
|
|
288
|
+
response = {
|
|
289
|
+
id: req.id,
|
|
290
|
+
error: { code: ErrorCodes.UNSUPPORTED_METHOD, message: `Unsupported method: ${req.method}` }
|
|
291
|
+
};
|
|
292
|
+
} else {
|
|
293
|
+
try {
|
|
294
|
+
const result = await this.onRequest(req.method, req.params);
|
|
295
|
+
response = { id: req.id, result: result === void 0 ? null : result };
|
|
296
|
+
} catch (e) {
|
|
297
|
+
response = { id: req.id, error: ProviderRpcError.toPayload(e) };
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (this.closed) return;
|
|
301
|
+
try {
|
|
302
|
+
this.transport.postMessage(this.stamp(response));
|
|
303
|
+
} catch {
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
// src/provider.ts
|
|
309
|
+
var SDK_VERSION = "0.1.0";
|
|
310
|
+
function discoverAnnounced(win) {
|
|
311
|
+
let found = null;
|
|
312
|
+
const stop = requestProviders((d) => {
|
|
313
|
+
if (!found) found = { provider: d.provider, name: d.info?.name || "Knowhow" };
|
|
314
|
+
}, win);
|
|
315
|
+
stop();
|
|
316
|
+
return found;
|
|
317
|
+
}
|
|
318
|
+
var initByWindow = /* @__PURE__ */ new WeakMap();
|
|
319
|
+
var watchedWindows = /* @__PURE__ */ new WeakSet();
|
|
320
|
+
function originOf(url) {
|
|
321
|
+
try {
|
|
322
|
+
const o = new URL(url).origin;
|
|
323
|
+
return o && o !== "null" ? o : void 0;
|
|
324
|
+
} catch {
|
|
325
|
+
return void 0;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
function isTrustedParentOrigin(win, origin) {
|
|
329
|
+
if (!origin || origin === "null") return false;
|
|
330
|
+
try {
|
|
331
|
+
const ancestors = win.location?.ancestorOrigins;
|
|
332
|
+
if (ancestors && ancestors.length > 0) return ancestors[0] === origin;
|
|
333
|
+
} catch {
|
|
334
|
+
}
|
|
335
|
+
try {
|
|
336
|
+
const ref = win.document?.referrer ? originOf(win.document.referrer) : void 0;
|
|
337
|
+
const own = originOf(win.location?.href ?? "");
|
|
338
|
+
if (ref && ref !== own) return ref === origin;
|
|
339
|
+
} catch {
|
|
340
|
+
}
|
|
341
|
+
return true;
|
|
342
|
+
}
|
|
343
|
+
function readInit(win, ev) {
|
|
344
|
+
if (ev.source !== win.parent) return null;
|
|
345
|
+
const data = ev.data;
|
|
346
|
+
if (typeof data !== "object" || data === null) return null;
|
|
347
|
+
const d = data;
|
|
348
|
+
if (d.type !== INIT_TYPE || d.protocol !== PROTOCOL_VERSION) return null;
|
|
349
|
+
if (typeof d.nonce !== "string" || d.nonce.length < 8) return null;
|
|
350
|
+
if (!isTrustedParentOrigin(win, ev.origin)) return null;
|
|
351
|
+
return { origin: ev.origin, nonce: d.nonce };
|
|
352
|
+
}
|
|
353
|
+
function watchParentInit(win) {
|
|
354
|
+
if (!win.parent || win.parent === win || watchedWindows.has(win)) return;
|
|
355
|
+
watchedWindows.add(win);
|
|
356
|
+
win.addEventListener("message", (ev) => {
|
|
357
|
+
const init = readInit(win, ev);
|
|
358
|
+
if (init) initByWindow.set(win, init);
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
function handshakeWithParent(win, opts) {
|
|
362
|
+
const timeoutMs = opts.handshakeTimeoutMs ?? 5e3;
|
|
363
|
+
const intervalMs = opts.helloIntervalMs ?? 250;
|
|
364
|
+
const parent = win.parent;
|
|
365
|
+
watchParentInit(win);
|
|
366
|
+
return new Promise((resolve, reject) => {
|
|
367
|
+
let interval;
|
|
368
|
+
let timer;
|
|
369
|
+
let init = initByWindow.get(win);
|
|
370
|
+
const cleanup = () => {
|
|
371
|
+
win.removeEventListener("message", onMessage);
|
|
372
|
+
if (interval) clearInterval(interval);
|
|
373
|
+
if (timer) clearTimeout(timer);
|
|
374
|
+
};
|
|
375
|
+
const send = () => {
|
|
376
|
+
if (!init) return;
|
|
377
|
+
const hello = {
|
|
378
|
+
type: HELLO_TYPE,
|
|
379
|
+
protocol: PROTOCOL_VERSION,
|
|
380
|
+
sdkVersion: SDK_VERSION,
|
|
381
|
+
nonce: init.nonce
|
|
382
|
+
};
|
|
383
|
+
parent.postMessage(hello, init.origin);
|
|
384
|
+
};
|
|
385
|
+
const onMessage = (ev) => {
|
|
386
|
+
const fresh = readInit(win, ev);
|
|
387
|
+
if (fresh) {
|
|
388
|
+
const changed = !init || init.nonce !== fresh.nonce || init.origin !== fresh.origin;
|
|
389
|
+
init = fresh;
|
|
390
|
+
initByWindow.set(win, fresh);
|
|
391
|
+
if (changed) send();
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (!init || ev.source !== parent || ev.origin !== init.origin) return;
|
|
395
|
+
const data = ev.data;
|
|
396
|
+
if (typeof data !== "object" || data === null) return;
|
|
397
|
+
const d = data;
|
|
398
|
+
if (d.type !== PORT_TYPE || d.nonce !== init.nonce) return;
|
|
399
|
+
const port = ev.ports && ev.ports[0];
|
|
400
|
+
if (!port) return;
|
|
401
|
+
cleanup();
|
|
402
|
+
const endpoint = new RpcEndpoint(port, { nonce: init.nonce });
|
|
403
|
+
resolve(createProviderFromEndpoint(endpoint));
|
|
404
|
+
};
|
|
405
|
+
win.addEventListener("message", onMessage);
|
|
406
|
+
send();
|
|
407
|
+
interval = setInterval(send, intervalMs);
|
|
408
|
+
timer = setTimeout(() => {
|
|
409
|
+
cleanup();
|
|
410
|
+
reject(new ProviderRpcError(ErrorCodes.DISCONNECTED, "Knowhow host did not respond to kh:hello"));
|
|
411
|
+
}, timeoutMs);
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
async function discoverProvider(opts = {}) {
|
|
415
|
+
const win = opts.window ?? (typeof window !== "undefined" ? window : void 0);
|
|
416
|
+
if (!win) throw new ProviderRpcError(ErrorCodes.DISCONNECTED, "No window: Knowhow provider unavailable");
|
|
417
|
+
const framed = !!win.parent && win.parent !== win;
|
|
418
|
+
const announced = discoverAnnounced(win);
|
|
419
|
+
const injected = (a) => ({
|
|
420
|
+
provider: a.provider,
|
|
421
|
+
kind: "injected",
|
|
422
|
+
providerName: a.name
|
|
423
|
+
});
|
|
424
|
+
if (announced && (opts.prefer === "injected" || !framed)) return injected(announced);
|
|
425
|
+
if (framed) {
|
|
426
|
+
const timeoutMs = announced ? opts.parentProbeMs ?? 1500 : opts.handshakeTimeoutMs;
|
|
427
|
+
try {
|
|
428
|
+
const provider = await handshakeWithParent(win, { ...opts, handshakeTimeoutMs: timeoutMs });
|
|
429
|
+
return { provider, kind: "embedded" };
|
|
430
|
+
} catch (e) {
|
|
431
|
+
if (announced) return injected(announced);
|
|
432
|
+
throw e;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
throw new ProviderRpcError(
|
|
436
|
+
ErrorCodes.DISCONNECTED,
|
|
437
|
+
"No Knowhow provider found (not embedded in Knowhow and no extension installed). Call knowhow.mock() for local development."
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
async function getProvider(opts = {}) {
|
|
441
|
+
return (await discoverProvider(opts)).provider;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// src/files.ts
|
|
445
|
+
var mockBlobStore = /* @__PURE__ */ new Map();
|
|
446
|
+
var MOCK_URL_PREFIX = "mock-blob:";
|
|
447
|
+
function toBlob(data, contentType) {
|
|
448
|
+
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
449
|
+
return contentType && !data.type ? data.slice(0, data.size, contentType) : data;
|
|
450
|
+
}
|
|
451
|
+
const part = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
|
|
452
|
+
return new Blob([part], contentType ? { type: contentType } : void 0);
|
|
453
|
+
}
|
|
454
|
+
function abortError() {
|
|
455
|
+
const e = new Error("Aborted");
|
|
456
|
+
e.name = "AbortError";
|
|
457
|
+
return e;
|
|
458
|
+
}
|
|
459
|
+
async function putBlob(url, blob, opts) {
|
|
460
|
+
if (url.startsWith(MOCK_URL_PREFIX)) {
|
|
461
|
+
mockBlobStore.set(url, blob);
|
|
462
|
+
opts.onProgress?.(blob.size, blob.size);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
const headers = {};
|
|
466
|
+
if (blob.type) headers["Content-Type"] = blob.type;
|
|
467
|
+
if (typeof XMLHttpRequest !== "undefined" && opts.onProgress) {
|
|
468
|
+
await new Promise((resolve, reject) => {
|
|
469
|
+
const xhr = new XMLHttpRequest();
|
|
470
|
+
xhr.open("PUT", url);
|
|
471
|
+
for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);
|
|
472
|
+
xhr.upload.onprogress = (ev) => {
|
|
473
|
+
if (ev.lengthComputable) opts.onProgress?.(ev.loaded, ev.total);
|
|
474
|
+
};
|
|
475
|
+
xhr.onload = () => xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (${xhr.status})`));
|
|
476
|
+
xhr.onerror = () => reject(new Error("Upload failed (network error)"));
|
|
477
|
+
xhr.onabort = () => reject(abortError());
|
|
478
|
+
if (opts.signal) {
|
|
479
|
+
if (opts.signal.aborted) return reject(abortError());
|
|
480
|
+
opts.signal.addEventListener("abort", () => xhr.abort(), { once: true });
|
|
481
|
+
}
|
|
482
|
+
xhr.send(blob);
|
|
483
|
+
});
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
const res = await fetch(url, { method: "PUT", body: blob, headers, signal: opts.signal });
|
|
487
|
+
if (!res.ok) throw new Error(`Upload failed (${res.status})`);
|
|
488
|
+
opts.onProgress?.(blob.size, blob.size);
|
|
489
|
+
}
|
|
490
|
+
async function getBlob(url, opts) {
|
|
491
|
+
if (url.startsWith(MOCK_URL_PREFIX)) {
|
|
492
|
+
const b = mockBlobStore.get(url);
|
|
493
|
+
if (!b) throw new Error("Download failed (404)");
|
|
494
|
+
const out = opts.range ? b.slice(opts.range.start, (opts.range.end ?? b.size - 1) + 1) : b;
|
|
495
|
+
opts.onProgress?.(out.size, out.size);
|
|
496
|
+
return out;
|
|
497
|
+
}
|
|
498
|
+
const headers = {};
|
|
499
|
+
if (opts.range) headers.Range = `bytes=${opts.range.start}-${opts.range.end ?? ""}`;
|
|
500
|
+
const res = await fetch(url, { headers, signal: opts.signal });
|
|
501
|
+
if (!res.ok) throw new Error(`Download failed (${res.status})`);
|
|
502
|
+
const total = Number(res.headers.get("content-length")) || 0;
|
|
503
|
+
const type = res.headers.get("content-type") ?? "";
|
|
504
|
+
if (!opts.onProgress || !res.body) return res.blob();
|
|
505
|
+
const reader = res.body.getReader();
|
|
506
|
+
const chunks = [];
|
|
507
|
+
let loaded = 0;
|
|
508
|
+
for (; ; ) {
|
|
509
|
+
const { done, value } = await reader.read();
|
|
510
|
+
if (done) break;
|
|
511
|
+
chunks.push(value);
|
|
512
|
+
loaded += value.byteLength;
|
|
513
|
+
opts.onProgress(loaded, total || loaded);
|
|
514
|
+
}
|
|
515
|
+
return new Blob(chunks, type ? { type } : void 0);
|
|
516
|
+
}
|
|
517
|
+
function createFilesApi(call) {
|
|
518
|
+
const scoped = (o) => ({ scope: o?.scope ?? "user" });
|
|
519
|
+
return {
|
|
520
|
+
/** Folder listing (≤ 1000 entries) of the scoped storage; `prefix` is a folder relative to the root. */
|
|
521
|
+
async listScoped(prefix, opts) {
|
|
522
|
+
const r = await call(Methods.FilesList, { ...prefix ? { path: prefix } : {}, ...scoped(opts) });
|
|
523
|
+
return r.files;
|
|
524
|
+
},
|
|
525
|
+
async stat(path, opts) {
|
|
526
|
+
const r = await call(Methods.FilesStat, { path, ...scoped(opts) });
|
|
527
|
+
return r.file;
|
|
528
|
+
},
|
|
529
|
+
async delete(path, opts) {
|
|
530
|
+
const r = await call(Methods.FilesDelete, { path, ...scoped(opts) });
|
|
531
|
+
return r.deleted;
|
|
532
|
+
},
|
|
533
|
+
/** Short-lived presigned download URL (usable as `<video src>`; S3 serves Range requests). */
|
|
534
|
+
async url(path, opts) {
|
|
535
|
+
const r = await call(Methods.FilesDownloadUrl, { path, ...scoped(opts) });
|
|
536
|
+
return r.url;
|
|
537
|
+
},
|
|
538
|
+
/** Download to a Blob (optionally a byte range) with progress. */
|
|
539
|
+
async get(path, opts = {}) {
|
|
540
|
+
const r = await call(Methods.FilesDownloadUrl, { path, ...scoped(opts) });
|
|
541
|
+
return getBlob(r.url, opts);
|
|
542
|
+
},
|
|
543
|
+
/**
|
|
544
|
+
* Upload (any size up to 2 GiB - 1 byte): asks the host for a presigned URL, PUTs the bytes straight to
|
|
545
|
+
* storage (they never pass through the provider), then verifies the upload.
|
|
546
|
+
*/
|
|
547
|
+
async put(path, data, opts = {}) {
|
|
548
|
+
const blob = toBlob(data, opts.contentType);
|
|
549
|
+
const start = await call(Methods.FilesUploadStart, {
|
|
550
|
+
path,
|
|
551
|
+
size: blob.size,
|
|
552
|
+
contentType: opts.contentType || blob.type || void 0,
|
|
553
|
+
...scoped(opts)
|
|
554
|
+
});
|
|
555
|
+
await putBlob(start.uploadUrl, blob, opts);
|
|
556
|
+
const done = await call(Methods.FilesUploadComplete, { id: start.id, ...scoped(opts) });
|
|
557
|
+
return done.file;
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// src/mock.ts
|
|
563
|
+
var MOCK_PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
|
|
564
|
+
var MOCK_TRANSCRIPT_WORDS = ["This", "is", "a", "mock", "transcript", "from", "the", "Knowhow", "app", "SDK."];
|
|
565
|
+
var MOCK_WORD_SECONDS = 0.5;
|
|
566
|
+
function decodedBase64Bytes(audio) {
|
|
567
|
+
const comma = audio.startsWith("data:") ? audio.indexOf(",") : -1;
|
|
568
|
+
const b64 = (comma >= 0 ? audio.slice(comma + 1) : audio).replace(/\s+/g, "");
|
|
569
|
+
const padding = b64.endsWith("==") ? 2 : b64.endsWith("=") ? 1 : 0;
|
|
570
|
+
return Math.floor(b64.length * 3 / 4) - padding;
|
|
571
|
+
}
|
|
572
|
+
function mockTranscribe(params) {
|
|
573
|
+
if (typeof params.audio !== "string" || !params.audio) {
|
|
574
|
+
throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, "audio is required");
|
|
575
|
+
}
|
|
576
|
+
if (decodedBase64Bytes(params.audio) > AI_TRANSCRIBE_MAX_AUDIO_BYTES) {
|
|
577
|
+
throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, "audio exceeds 25 MB");
|
|
578
|
+
}
|
|
579
|
+
const timestamps = params.timestamps ?? ["word", "segment"];
|
|
580
|
+
const words = MOCK_TRANSCRIPT_WORDS.map((word, i) => ({
|
|
581
|
+
start: i * MOCK_WORD_SECONDS,
|
|
582
|
+
end: (i + 1) * MOCK_WORD_SECONDS,
|
|
583
|
+
word
|
|
584
|
+
}));
|
|
585
|
+
const duration = words.length * MOCK_WORD_SECONDS;
|
|
586
|
+
const text = MOCK_TRANSCRIPT_WORDS.join(" ");
|
|
587
|
+
return {
|
|
588
|
+
text,
|
|
589
|
+
language: params.language ?? "en",
|
|
590
|
+
duration,
|
|
591
|
+
model: params.model ?? "mock",
|
|
592
|
+
segments: timestamps.includes("segment") ? [{ start: 0, end: duration, text }] : [],
|
|
593
|
+
words: timestamps.includes("word") ? words : []
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
function mockImage(params) {
|
|
597
|
+
if (typeof params.prompt !== "string" || !params.prompt.trim()) {
|
|
598
|
+
throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, "prompt is required");
|
|
599
|
+
}
|
|
600
|
+
if (params.images !== void 0 && (!Array.isArray(params.images) || params.images.length < 1 || params.images.length > AI_IMAGE_MAX_INPUTS)) {
|
|
601
|
+
throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, `images must be an array of 1..${AI_IMAGE_MAX_INPUTS} image data URLs`);
|
|
602
|
+
}
|
|
603
|
+
const n = params.n ?? 1;
|
|
604
|
+
if (!Number.isInteger(n) || n < 1 || n > AI_IMAGE_MAX_N) {
|
|
605
|
+
throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, `n must be an integer between 1 and ${AI_IMAGE_MAX_N}`);
|
|
606
|
+
}
|
|
607
|
+
return {
|
|
608
|
+
model: params.model ?? "mock",
|
|
609
|
+
images: Array.from({ length: n }, () => ({
|
|
610
|
+
dataUrl: `data:image/png;base64,${MOCK_PNG_BASE64}`,
|
|
611
|
+
revisedPrompt: `[mock] ${params.prompt}`
|
|
612
|
+
}))
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
function createMockProvider(opts = {}) {
|
|
616
|
+
const kv = /* @__PURE__ */ new Map();
|
|
617
|
+
const files = /* @__PURE__ */ new Map();
|
|
618
|
+
const scoped = /* @__PURE__ */ new Map();
|
|
619
|
+
const scopedOf = (p) => p.scope === "org" ? "org" : "user";
|
|
620
|
+
const scopedKey = (p) => {
|
|
621
|
+
const path = String(p.path ?? "");
|
|
622
|
+
if (!path || path.startsWith("/") || path.split("/").some((s) => s === "..") || path.includes("\\")) {
|
|
623
|
+
throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, "Invalid path");
|
|
624
|
+
}
|
|
625
|
+
return `${scopedOf(p)}:${path.split("/").filter((s) => s && s !== ".").join("/")}`;
|
|
626
|
+
};
|
|
627
|
+
const scopedView = (key) => {
|
|
628
|
+
const m = scoped.get(key);
|
|
629
|
+
const [scope, ...rest] = key.split(":");
|
|
630
|
+
const path = rest.join(":");
|
|
631
|
+
return { id: m.id, name: path.split("/").pop() ?? path, path, size: m.size, mime: m.mime, updatedAt: m.updatedAt, scope };
|
|
632
|
+
};
|
|
633
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
634
|
+
const pendingTools = /* @__PURE__ */ new Map();
|
|
635
|
+
let session = null;
|
|
636
|
+
let callSeq = 0;
|
|
637
|
+
const emit = (event, data) => {
|
|
638
|
+
for (const l of Array.from(listeners.get(event) ?? [])) l(data);
|
|
639
|
+
};
|
|
640
|
+
const dbMethods = [Methods.DbQuery, Methods.DbExec, Methods.DbBatch];
|
|
641
|
+
const methods = Object.values(Methods);
|
|
642
|
+
async function request(method, params) {
|
|
643
|
+
const p = params ?? {};
|
|
644
|
+
switch (method) {
|
|
645
|
+
case Methods.Protocol:
|
|
646
|
+
return { protocol: PROTOCOL_VERSION, methods, host: { kind: "web", version: "mock" } };
|
|
647
|
+
case Methods.Connect: {
|
|
648
|
+
session = {
|
|
649
|
+
appId: p.appId ?? "mock-app",
|
|
650
|
+
user: opts.user ?? { displayName: "Mock User" },
|
|
651
|
+
capabilities: [...CAPABILITIES]
|
|
652
|
+
};
|
|
653
|
+
emit("connect", session);
|
|
654
|
+
emit("sessionChanged", session);
|
|
655
|
+
return session;
|
|
656
|
+
}
|
|
657
|
+
case Methods.Session:
|
|
658
|
+
return session;
|
|
659
|
+
case Methods.Disconnect:
|
|
660
|
+
session = null;
|
|
661
|
+
emit("disconnect");
|
|
662
|
+
return true;
|
|
663
|
+
}
|
|
664
|
+
if (!session) throw new ProviderRpcError(ErrorCodes.UNAUTHORIZED, "Not connected");
|
|
665
|
+
if (dbMethods.includes(method)) {
|
|
666
|
+
if (!opts.db) throw new ProviderRpcError(ErrorCodes.INTERNAL, "db not available in mock");
|
|
667
|
+
return opts.db(method, params);
|
|
668
|
+
}
|
|
669
|
+
switch (method) {
|
|
670
|
+
case Methods.KvGet:
|
|
671
|
+
return { value: kv.has(String(p.key)) ? kv.get(String(p.key)) : null };
|
|
672
|
+
case Methods.KvSet:
|
|
673
|
+
kv.set(String(p.key), p.value);
|
|
674
|
+
return true;
|
|
675
|
+
case Methods.KvDelete:
|
|
676
|
+
kv.delete(String(p.key));
|
|
677
|
+
return true;
|
|
678
|
+
case Methods.FilesStat: {
|
|
679
|
+
const key = scopedKey(p);
|
|
680
|
+
return { file: scoped.get(key)?.done ? scopedView(key) : null };
|
|
681
|
+
}
|
|
682
|
+
case Methods.FilesDelete: {
|
|
683
|
+
const key = scopedKey(p);
|
|
684
|
+
const m = scoped.get(key);
|
|
685
|
+
if (m) mockBlobStore.delete(`${MOCK_URL_PREFIX}${m.id}`);
|
|
686
|
+
return { deleted: scoped.delete(key) };
|
|
687
|
+
}
|
|
688
|
+
case Methods.FilesUploadStart: {
|
|
689
|
+
const key = scopedKey(p);
|
|
690
|
+
const id = `mock-file-${scoped.size + 1}-${key}`;
|
|
691
|
+
scoped.set(key, {
|
|
692
|
+
id,
|
|
693
|
+
size: Number(p.size) || 0,
|
|
694
|
+
mime: typeof p.contentType === "string" ? p.contentType : "application/octet-stream",
|
|
695
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
696
|
+
done: false
|
|
697
|
+
});
|
|
698
|
+
return { id, uploadUrl: `${MOCK_URL_PREFIX}${id}`, method: "PUT", maxBytes: Number(p.size) || 0 };
|
|
699
|
+
}
|
|
700
|
+
case Methods.FilesUploadComplete: {
|
|
701
|
+
const entry = Array.from(scoped.entries()).find(([, m]) => m.id === p.id);
|
|
702
|
+
if (!entry) throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, "File not found");
|
|
703
|
+
const blob = mockBlobStore.get(`${MOCK_URL_PREFIX}${entry[1].id}`);
|
|
704
|
+
entry[1].size = blob?.size ?? entry[1].size;
|
|
705
|
+
entry[1].done = true;
|
|
706
|
+
return { file: scopedView(entry[0]) };
|
|
707
|
+
}
|
|
708
|
+
case Methods.FilesDownloadUrl: {
|
|
709
|
+
const key = scopedKey(p);
|
|
710
|
+
const m = scoped.get(key);
|
|
711
|
+
if (!m?.done) throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, "File not found");
|
|
712
|
+
return { url: `${MOCK_URL_PREFIX}${m.id}`, file: scopedView(key) };
|
|
713
|
+
}
|
|
714
|
+
case Methods.FilesList:
|
|
715
|
+
if (p.scope !== void 0) {
|
|
716
|
+
const scope = scopedOf(p);
|
|
717
|
+
const prefix = typeof p.path === "string" && p.path ? `${scope}:${p.path.replace(/\/+$/, "")}/` : `${scope}:`;
|
|
718
|
+
return {
|
|
719
|
+
files: Array.from(scoped.keys()).filter((k) => k.startsWith(prefix) && scoped.get(k).done).map(scopedView)
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
return {
|
|
723
|
+
files: Array.from(files.entries()).map(([path, text]) => ({
|
|
724
|
+
id: path,
|
|
725
|
+
name: path.split("/").pop() ?? path,
|
|
726
|
+
path,
|
|
727
|
+
size: text.length,
|
|
728
|
+
mime: "text/plain",
|
|
729
|
+
updatedAt: (/* @__PURE__ */ new Date(0)).toISOString()
|
|
730
|
+
}))
|
|
731
|
+
};
|
|
732
|
+
case Methods.FilesRead: {
|
|
733
|
+
const text = files.get(String(p.path));
|
|
734
|
+
if (text === void 0) throw new ProviderRpcError(ErrorCodes.INVALID_PARAMS, "File not found");
|
|
735
|
+
return { text };
|
|
736
|
+
}
|
|
737
|
+
case Methods.FilesWrite:
|
|
738
|
+
files.set(String(p.path), String(p.text));
|
|
739
|
+
return { id: String(p.path) };
|
|
740
|
+
case Methods.AiComplete: {
|
|
741
|
+
const msgs = p.messages ?? [];
|
|
742
|
+
const last = msgs[msgs.length - 1];
|
|
743
|
+
return { content: `[mock] ${last ? last.content : ""}`, model: "mock" };
|
|
744
|
+
}
|
|
745
|
+
case Methods.AiTranscribe:
|
|
746
|
+
return mockTranscribe(p);
|
|
747
|
+
case Methods.AiImage:
|
|
748
|
+
return mockImage(p);
|
|
749
|
+
case Methods.AppEnv:
|
|
750
|
+
return { name: opts.env?.name ?? "dev", vars: { ...opts.env?.vars ?? {} } };
|
|
751
|
+
case Methods.SpendGet:
|
|
752
|
+
return {
|
|
753
|
+
spendLimitUsd: 5,
|
|
754
|
+
spendPeriod: "month",
|
|
755
|
+
spentUsd: 0,
|
|
756
|
+
spentUsdTotal: 0,
|
|
757
|
+
periodResetsAt: null,
|
|
758
|
+
aiRequestsTotal: 0
|
|
759
|
+
};
|
|
760
|
+
case Methods.ToolsRegister:
|
|
761
|
+
return true;
|
|
762
|
+
case Methods.ToolsResult: {
|
|
763
|
+
const entry = pendingTools.get(String(p.callId));
|
|
764
|
+
if (entry) {
|
|
765
|
+
pendingTools.delete(String(p.callId));
|
|
766
|
+
if (p.error) entry.reject(new Error(String(p.error)));
|
|
767
|
+
else entry.resolve(p.result);
|
|
768
|
+
}
|
|
769
|
+
return true;
|
|
770
|
+
}
|
|
771
|
+
case Methods.UiNotify:
|
|
772
|
+
console.info("[knowhow mock] notify:", p.message);
|
|
773
|
+
return true;
|
|
774
|
+
default:
|
|
775
|
+
throw new ProviderRpcError(ErrorCodes.UNSUPPORTED_METHOD, `Unsupported method: ${method}`);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
return {
|
|
779
|
+
request: (args) => request(args.method, args.params),
|
|
780
|
+
on(event, listener) {
|
|
781
|
+
let set = listeners.get(event);
|
|
782
|
+
if (!set) listeners.set(event, set = /* @__PURE__ */ new Set());
|
|
783
|
+
set.add(listener);
|
|
784
|
+
},
|
|
785
|
+
removeListener(event, listener) {
|
|
786
|
+
listeners.get(event)?.delete(listener);
|
|
787
|
+
},
|
|
788
|
+
callTool(name, args = {}) {
|
|
789
|
+
const callId = `mock-${++callSeq}`;
|
|
790
|
+
return new Promise((resolve, reject) => {
|
|
791
|
+
pendingTools.set(callId, { resolve, reject });
|
|
792
|
+
emit("toolCall", { callId, name, args });
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// src/sdk.ts
|
|
799
|
+
function readMetaAppId(win) {
|
|
800
|
+
try {
|
|
801
|
+
const el = win?.document?.querySelector('meta[name="knowhow-app-id"]');
|
|
802
|
+
const v = el?.getAttribute("content")?.trim();
|
|
803
|
+
return v || void 0;
|
|
804
|
+
} catch {
|
|
805
|
+
return void 0;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
var FORWARDED_EVENTS = [Events.Connect, Events.Disconnect, Events.SessionChanged, Events.Message];
|
|
809
|
+
function createKnowhow(options = {}) {
|
|
810
|
+
let mocked = false;
|
|
811
|
+
let mockOptions;
|
|
812
|
+
let providerPromise = null;
|
|
813
|
+
let discovery = null;
|
|
814
|
+
let hostKind = null;
|
|
815
|
+
let hostName;
|
|
816
|
+
let prefer = options.prefer;
|
|
817
|
+
let protocol = null;
|
|
818
|
+
let session = null;
|
|
819
|
+
let configuredAppId = options.appId;
|
|
820
|
+
const getWin = () => options.window ?? (typeof window !== "undefined" ? window : void 0);
|
|
821
|
+
{
|
|
822
|
+
const w = getWin();
|
|
823
|
+
if (w && !options.getProvider) watchParentInit(w);
|
|
824
|
+
}
|
|
825
|
+
const resolveAppId = (override) => override ?? configuredAppId ?? readMetaAppId(getWin());
|
|
826
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
827
|
+
const toolHandlers = /* @__PURE__ */ new Map();
|
|
828
|
+
const emitLocal = (event, data) => {
|
|
829
|
+
for (const cb of Array.from(listeners.get(event) ?? [])) cb(data);
|
|
830
|
+
};
|
|
831
|
+
async function runToolCall(provider, call2) {
|
|
832
|
+
const tool = toolHandlers.get(call2.name);
|
|
833
|
+
try {
|
|
834
|
+
if (!tool) throw new Error(`Unknown tool: ${call2.name}`);
|
|
835
|
+
const out = await tool.handler(call2.args ?? {});
|
|
836
|
+
await provider.request({
|
|
837
|
+
method: Methods.ToolsResult,
|
|
838
|
+
params: { callId: call2.callId, result: out === void 0 ? null : out }
|
|
839
|
+
});
|
|
840
|
+
} catch (e) {
|
|
841
|
+
await provider.request({
|
|
842
|
+
method: Methods.ToolsResult,
|
|
843
|
+
params: { callId: call2.callId, error: e instanceof Error ? e.message : String(e) }
|
|
844
|
+
}).catch(() => void 0);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
function discover() {
|
|
848
|
+
if (!discovery) {
|
|
849
|
+
discovery = (options.getProvider ? options.getProvider().then((provider) => ({ provider, kind: "embedded" })) : discoverProvider({ ...options, prefer })).then((d) => {
|
|
850
|
+
hostKind = d.kind;
|
|
851
|
+
hostName = d.providerName;
|
|
852
|
+
return d;
|
|
853
|
+
});
|
|
854
|
+
discovery.catch(() => {
|
|
855
|
+
discovery = null;
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
return discovery;
|
|
859
|
+
}
|
|
860
|
+
function loadProvider() {
|
|
861
|
+
if (!providerPromise) {
|
|
862
|
+
const make = mocked ? async () => createMockProvider(mockOptions) : async () => (await discover()).provider;
|
|
863
|
+
providerPromise = make().then(async (provider) => {
|
|
864
|
+
for (const ev of FORWARDED_EVENTS) {
|
|
865
|
+
provider.on(ev, (data) => {
|
|
866
|
+
if (ev === Events.SessionChanged) session = data ?? null;
|
|
867
|
+
if (ev === Events.Disconnect) session = null;
|
|
868
|
+
emitLocal(ev, data);
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
provider.on(Events.ToolCall, (data) => void runToolCall(provider, data));
|
|
872
|
+
protocol = await provider.request({ method: Methods.Protocol });
|
|
873
|
+
return provider;
|
|
874
|
+
});
|
|
875
|
+
providerPromise.catch(() => {
|
|
876
|
+
providerPromise = null;
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
return providerPromise;
|
|
880
|
+
}
|
|
881
|
+
async function connectInternal(capabilities, opts = {}) {
|
|
882
|
+
const provider = await loadProvider();
|
|
883
|
+
const params = capabilities ? { capabilities } : {};
|
|
884
|
+
const appId = resolveAppId(opts.appId);
|
|
885
|
+
if (appId) params.appId = appId;
|
|
886
|
+
session = await provider.request({ method: Methods.Connect, params });
|
|
887
|
+
return session;
|
|
888
|
+
}
|
|
889
|
+
async function call(method, params) {
|
|
890
|
+
const provider = await loadProvider();
|
|
891
|
+
if (protocol && !protocol.methods.includes(method)) {
|
|
892
|
+
throw new ProviderRpcError(ErrorCodes.UNSUPPORTED_METHOD, `Host does not support ${method}`);
|
|
893
|
+
}
|
|
894
|
+
if (!session) {
|
|
895
|
+
const existing = await provider.request({ method: Methods.Session });
|
|
896
|
+
session = existing;
|
|
897
|
+
if (!session) await connectInternal();
|
|
898
|
+
}
|
|
899
|
+
return provider.request({ method, params });
|
|
900
|
+
}
|
|
901
|
+
const pushTools = async () => {
|
|
902
|
+
const tools = Array.from(toolHandlers.values()).map((t) => ({
|
|
903
|
+
name: t.name,
|
|
904
|
+
description: t.description,
|
|
905
|
+
parameters: t.parameters,
|
|
906
|
+
...t.readOnly === void 0 ? {} : { readOnly: t.readOnly }
|
|
907
|
+
}));
|
|
908
|
+
await call(Methods.ToolsRegister, { tools });
|
|
909
|
+
};
|
|
910
|
+
const filesApi = createFilesApi(call);
|
|
911
|
+
return {
|
|
912
|
+
/** Resolve the provider and fetch protocol info. */
|
|
913
|
+
async ready() {
|
|
914
|
+
await loadProvider();
|
|
915
|
+
return protocol;
|
|
916
|
+
},
|
|
917
|
+
get session() {
|
|
918
|
+
return session;
|
|
919
|
+
},
|
|
920
|
+
/** True if the connected host supports `method` (after ready()). */
|
|
921
|
+
supports(method) {
|
|
922
|
+
return !!protocol && protocol.methods.includes(method);
|
|
923
|
+
},
|
|
924
|
+
/**
|
|
925
|
+
* Ask the host for a session. Iframe hosts know the app already. Injected hosts (extension, desktop)
|
|
926
|
+
* resolve a registered app from an app id or alias — pass `{ appId }`, call `configure({ appId })`, or add
|
|
927
|
+
* the meta tag. With NO app id the extension opens a *self-hosted site* session instead: bound to the page's
|
|
928
|
+
* real origin, limited to ai:* / db:app, billed to the visitor (`session.site.origin` is set).
|
|
929
|
+
*/
|
|
930
|
+
connect: (capabilities, opts) => connectInternal(capabilities, opts),
|
|
931
|
+
/**
|
|
932
|
+
* Set defaults before connecting. `prefer` picks the host when an app is framed by Knowhow AND an
|
|
933
|
+
* extension/desktop provider is injected: "host" (default) or "injected". Must be set before the
|
|
934
|
+
* provider is first resolved.
|
|
935
|
+
*/
|
|
936
|
+
configure(opts) {
|
|
937
|
+
if ("appId" in opts) configuredAppId = opts.appId;
|
|
938
|
+
if ("prefer" in opts) prefer = opts.prefer;
|
|
939
|
+
},
|
|
940
|
+
/** Which host the SDK actually connected through (after ready()/detect()), or null if unresolved. */
|
|
941
|
+
get host() {
|
|
942
|
+
if (mocked) return { kind: "mock" };
|
|
943
|
+
return hostKind ? { kind: hostKind, ...hostName ? { providerName: hostName } : {} } : null;
|
|
944
|
+
},
|
|
945
|
+
/** The app id/alias that will be claimed on connect (config → meta tag), if any. */
|
|
946
|
+
get appId() {
|
|
947
|
+
return resolveAppId();
|
|
948
|
+
},
|
|
949
|
+
/**
|
|
950
|
+
* Non-throwing host detection for building a connect screen. Never prompts the user:
|
|
951
|
+
* "embedded" = inside a Knowhow iframe host, "injected" = an extension/desktop provider announced
|
|
952
|
+
* itself, "none" = standalone (offer install / open-in-Knowhow / mock). When framed this performs the
|
|
953
|
+
* (shared, non-prompting) parent handshake so it reports the host that will actually be used.
|
|
954
|
+
*/
|
|
955
|
+
async detect(opts = {}) {
|
|
956
|
+
if (mocked) return { kind: "mock" };
|
|
957
|
+
const win = getWin();
|
|
958
|
+
if (!win) return { kind: "none" };
|
|
959
|
+
if (win.parent && win.parent !== win) {
|
|
960
|
+
try {
|
|
961
|
+
const d = await discover();
|
|
962
|
+
return { kind: d.kind, ...d.providerName ? { providerName: d.providerName } : {} };
|
|
963
|
+
} catch {
|
|
964
|
+
return { kind: "none" };
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
const name = await new Promise((resolve) => {
|
|
968
|
+
let done = false;
|
|
969
|
+
let timer;
|
|
970
|
+
let stop = () => void 0;
|
|
971
|
+
const finish = (v) => {
|
|
972
|
+
if (done) return;
|
|
973
|
+
done = true;
|
|
974
|
+
if (timer) clearTimeout(timer);
|
|
975
|
+
stop();
|
|
976
|
+
resolve(v);
|
|
977
|
+
};
|
|
978
|
+
stop = requestProviders((d) => finish(d.info.name || "Knowhow"), win);
|
|
979
|
+
if (done) stop();
|
|
980
|
+
else timer = setTimeout(() => finish(null), opts.timeoutMs ?? 300);
|
|
981
|
+
});
|
|
982
|
+
if (name) return { kind: "injected", providerName: name };
|
|
983
|
+
return { kind: "none" };
|
|
984
|
+
},
|
|
985
|
+
async disconnect() {
|
|
986
|
+
const provider = await loadProvider();
|
|
987
|
+
await provider.request({ method: Methods.Disconnect });
|
|
988
|
+
session = null;
|
|
989
|
+
},
|
|
990
|
+
db: {
|
|
991
|
+
query: (sql, params) => call(Methods.DbQuery, params ? { sql, params } : { sql }),
|
|
992
|
+
exec: (sql, params) => call(Methods.DbExec, params ? { sql, params } : { sql }),
|
|
993
|
+
batch: (statements) => call(Methods.DbBatch, { statements })
|
|
994
|
+
},
|
|
995
|
+
kv: {
|
|
996
|
+
async get(key) {
|
|
997
|
+
const r = await call(Methods.KvGet, { key });
|
|
998
|
+
return r.value;
|
|
999
|
+
},
|
|
1000
|
+
async set(key, value) {
|
|
1001
|
+
await call(Methods.KvSet, { key, value });
|
|
1002
|
+
},
|
|
1003
|
+
async delete(key) {
|
|
1004
|
+
await call(Methods.KvDelete, { key });
|
|
1005
|
+
}
|
|
1006
|
+
},
|
|
1007
|
+
files: {
|
|
1008
|
+
/**
|
|
1009
|
+
* `list(prefix, { scope })` lists the scoped app storage (works for websites too).
|
|
1010
|
+
* `list(path)` WITHOUT options is the legacy listing of a registered app's `data` folder.
|
|
1011
|
+
*/
|
|
1012
|
+
async list(path, opts) {
|
|
1013
|
+
if (opts) return filesApi.listScoped(path, opts);
|
|
1014
|
+
const r = await call(Methods.FilesList, path ? { path } : {});
|
|
1015
|
+
return r.files;
|
|
1016
|
+
},
|
|
1017
|
+
read: (path) => call(Methods.FilesRead, { path }),
|
|
1018
|
+
async write(path, text) {
|
|
1019
|
+
return call(Methods.FilesWrite, { path, text });
|
|
1020
|
+
},
|
|
1021
|
+
stat: filesApi.stat,
|
|
1022
|
+
delete: filesApi.delete,
|
|
1023
|
+
url: filesApi.url,
|
|
1024
|
+
get: filesApi.get,
|
|
1025
|
+
put: filesApi.put
|
|
1026
|
+
},
|
|
1027
|
+
ai: {
|
|
1028
|
+
complete: (params) => call(Methods.AiComplete, params),
|
|
1029
|
+
/** Speech-to-text (capability "ai:transcribe"). Audio ≤ 25 MB decoded; billed to the user's org. */
|
|
1030
|
+
transcribe: (params) => call(Methods.AiTranscribe, params),
|
|
1031
|
+
/** Image generation (capability "ai:image"); `n` ≤ 4. Billed to the user's org. */
|
|
1032
|
+
image: (params) => call(Methods.AiImage, params)
|
|
1033
|
+
},
|
|
1034
|
+
app: {
|
|
1035
|
+
/**
|
|
1036
|
+
* The environment this app runs in: `{name, vars}` ("prod" | "dev" | ...). Variables are the
|
|
1037
|
+
* environment's non-secret config, read at runtime; no capability needed.
|
|
1038
|
+
*/
|
|
1039
|
+
env: () => call(Methods.AppEnv, {})
|
|
1040
|
+
},
|
|
1041
|
+
spend: {
|
|
1042
|
+
/** This app's AI spend limit + usage for the signed-in user (no capability needed). */
|
|
1043
|
+
get: () => call(Methods.SpendGet, {})
|
|
1044
|
+
},
|
|
1045
|
+
tools: {
|
|
1046
|
+
/** Register (or replace) a tool whose handler runs in this app. */
|
|
1047
|
+
async register(tool) {
|
|
1048
|
+
toolHandlers.set(tool.name, tool);
|
|
1049
|
+
await pushTools();
|
|
1050
|
+
},
|
|
1051
|
+
async unregister(name) {
|
|
1052
|
+
toolHandlers.delete(name);
|
|
1053
|
+
await pushTools();
|
|
1054
|
+
}
|
|
1055
|
+
},
|
|
1056
|
+
ui: {
|
|
1057
|
+
async notify(message, level) {
|
|
1058
|
+
await call(Methods.UiNotify, level ? { message, level } : { message });
|
|
1059
|
+
}
|
|
1060
|
+
},
|
|
1061
|
+
/** Subscribe to provider events (connect, disconnect, sessionChanged, message). Returns unsubscribe. */
|
|
1062
|
+
on(event, cb) {
|
|
1063
|
+
let set = listeners.get(event);
|
|
1064
|
+
if (!set) listeners.set(event, set = /* @__PURE__ */ new Set());
|
|
1065
|
+
set.add(cb);
|
|
1066
|
+
return () => set?.delete(cb);
|
|
1067
|
+
},
|
|
1068
|
+
/** Mock mode only: simulate the host invoking one of this app's registered tools. */
|
|
1069
|
+
async mockCallTool(name, args = {}) {
|
|
1070
|
+
const provider = await loadProvider();
|
|
1071
|
+
if (!mocked) throw new Error("mockCallTool is only available after knowhow.mock()");
|
|
1072
|
+
return provider.callTool(name, args);
|
|
1073
|
+
},
|
|
1074
|
+
/** Switch to the in-memory mock provider (call before any other API). */
|
|
1075
|
+
mock(opts) {
|
|
1076
|
+
mocked = true;
|
|
1077
|
+
mockOptions = opts;
|
|
1078
|
+
providerPromise = null;
|
|
1079
|
+
protocol = null;
|
|
1080
|
+
session = null;
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
var knowhow = createKnowhow();
|
|
1085
|
+
export {
|
|
1086
|
+
CAPABILITIES,
|
|
1087
|
+
ErrorCodes,
|
|
1088
|
+
Events,
|
|
1089
|
+
Methods,
|
|
1090
|
+
ProviderRpcError,
|
|
1091
|
+
SDK_VERSION,
|
|
1092
|
+
createFilesApi,
|
|
1093
|
+
createKnowhow,
|
|
1094
|
+
createMockProvider,
|
|
1095
|
+
discoverProvider,
|
|
1096
|
+
getProvider,
|
|
1097
|
+
isTrustedParentOrigin,
|
|
1098
|
+
knowhow,
|
|
1099
|
+
watchParentInit
|
|
1100
|
+
};
|
|
1101
|
+
//# sourceMappingURL=index.js.map
|