@kaoruisaac/pedelec 0.1.0 → 0.1.3

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 CHANGED
@@ -1,9 +1,601 @@
1
1
  # Pedelec SDK
2
+
2
3
  [![npm version](https://img.shields.io/npm/v/@kaoruisaac/pedelec.svg)](https://www.npmjs.com/package/@kaoruisaac/pedelec)
4
+
3
5
  Browser SDK for connecting a web app to the Pedelec Chrome Extension and Desktop Runtime.
4
6
 
7
+ The SDK lets a browser page create local agent sessions, send user text, receive streamed assistant output, handle tool calls in the web app, and resume or end sessions.
8
+
9
+ ## Requirements
10
+
11
+ Pedelec SDK runs in a browser page context. It is not intended for Node.js, SSR server code, or background workers.
12
+
13
+ Before using it, the user needs:
14
+
15
+ - Pedelec Chrome Extension installed.
16
+ - Pedelec Desktop App running.
17
+ - Chrome Native Messaging host registered by the Desktop App.
18
+ - The target provider available locally. CLI-backed providers use commands such as `codex`, `gemini`, `opencode`, `cursor`, or `claude`; the Ollama provider uses Pedelec's bundled `pedelec-agent`.
19
+
20
+ ## Installation
21
+
22
+ Install from npm:
23
+
24
+ ```bash
25
+ npm install @kaoruisaac/pedelec
26
+ ```
27
+
28
+ Import the SDK in browser-side TypeScript:
29
+
30
+ ```ts
31
+ import { Pedelec, defineTool } from "@kaoruisaac/pedelec";
32
+ ```
33
+
34
+ For local development before publishing:
35
+
36
+ ```bash
37
+ npm install ../path/to/pedelec/sdk
38
+ ```
39
+
40
+ To build the SDK from this repository:
41
+
42
+ ```bash
43
+ cd sdk
44
+ npm install
45
+ npm run build
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ```ts
51
+ import { Pedelec, defineTool } from "@kaoruisaac/pedelec";
52
+
53
+ const pedelec = new Pedelec();
54
+
55
+ const session = await pedelec.createSession({
56
+ provider: "codex",
57
+ model: "gpt-5",
58
+ skills: {
59
+ guidance: "Use get_current_page when you need browser page context.",
60
+ tools: [
61
+ defineTool({
62
+ name: "get_current_page",
63
+ description: "Read the current browser page title and URL.",
64
+ argsSchema: {
65
+ type: "object",
66
+ properties: {},
67
+ required: [],
68
+ },
69
+ handler: (_args, ctx) => ({
70
+ url: location.href,
71
+ title: document.title,
72
+ turnId: ctx.turnId,
73
+ }),
74
+ }),
75
+ ],
76
+ },
77
+ });
78
+
79
+ session.onChat((text, ctx) => {
80
+ console.log(ctx.turnId, text);
81
+ });
82
+
83
+ session.onStatus((status, ctx) => {
84
+ console.log("status", status, "previous", ctx.previousStatus);
85
+ });
86
+
87
+ session.onError((error, ctx) => {
88
+ console.error(ctx.type, error.code, error.message, error.details);
89
+ });
90
+
91
+ await session.sendText("Analyze the current page state.");
92
+ ```
93
+
94
+ `sendText()` resolves after the current agent turn is done. If the same session is already running a prompt, another `sendText()` rejects with `SESSION_BUSY`.
95
+
96
+ ## Create a Client
97
+
98
+ ```ts
99
+ const pedelec = new Pedelec({
100
+ bridgeTimeoutMs: 30_000,
101
+ });
102
+ ```
103
+
104
+ `bridgeTimeoutMs` controls how long SDK requests wait for an extension response. The default is 30 seconds. Values below 1 ms are clamped to 1 ms.
105
+
106
+ ## Check Approval Status
107
+
108
+ The extension may ask the user to approve the current origin before a page can create or resume sessions. You can check status before showing a connect button.
109
+
110
+ ```ts
111
+ const status = await pedelec.getApprovalStatus();
112
+
113
+ if (!status.installed) {
114
+ console.log("Pedelec extension is not available.");
115
+ } else if (!status.approved) {
116
+ console.log(`${status.origin} still needs approval.`);
117
+ }
118
+ ```
119
+
120
+ Return shape:
121
+
122
+ ```ts
123
+ type ApprovalStatus = {
124
+ installed: boolean;
125
+ approved: boolean;
126
+ origin: string | null;
127
+ };
128
+ ```
129
+
130
+ If the extension cannot be reached, `getApprovalStatus()` returns `{ installed: false, approved: false, origin }` instead of throwing for extension unavailable cases.
131
+
132
+ ## Providers
133
+
134
+ List available providers on the user's machine:
135
+
136
+ ```ts
137
+ const providers = await pedelec.listProviders();
138
+
139
+ for (const provider of providers) {
140
+ console.log(provider.code, provider.available, provider.path, provider.error);
141
+ }
142
+ ```
143
+
144
+ ```ts
145
+ type ProviderCode = "codex" | "gemini" | "opencode" | "cursor" | "claude" | "ollama";
146
+
147
+ type ProviderInfo = {
148
+ name: string;
149
+ code: ProviderCode;
150
+ path: string | null;
151
+ available: boolean;
152
+ error: string | null;
153
+ };
154
+ ```
155
+
156
+ Supported provider codes:
157
+
158
+ | Provider | Code | Example model |
159
+ | --- | --- | --- |
160
+ | Codex | `codex` | `gpt-5` |
161
+ | Gemini | `gemini` | provider-supported model id |
162
+ | OpenCode | `opencode` | `ollama/qwen2.5-coder:14b` |
163
+ | Cursor | `cursor` | `gpt-5` |
164
+ | Claude Code | `claude` | `sonnet` |
165
+ | Ollama | `ollama` | `qwen3-14b-32k:latest` |
166
+
167
+ `available: false` usually means the provider CLI is not installed or is not available in `PATH`.
168
+ For Ollama, `available: true` only means Pedelec can find `pedelec-agent`; it does not mean the Ollama server is running or the selected model is installed.
169
+
170
+ ## Settings
171
+
172
+ Read the Desktop App default provider and per-provider models:
173
+
174
+ ```ts
175
+ const settings = await pedelec.getSettings();
176
+
177
+ console.log(settings.defaultProvider);
178
+ console.log(settings.defaultModels.codex);
179
+ console.log(settings.defaultModels.gemini);
180
+ console.log(settings.defaultModels.ollama);
181
+ ```
182
+
183
+ ```ts
184
+ type PedelecSettings = {
185
+ defaultProvider: ProviderCode | null;
186
+ defaultModels: Partial<Record<ProviderCode, string>>;
187
+ };
188
+ ```
189
+
190
+ ## Create Sessions
191
+
192
+ Use the Desktop App default provider:
193
+
194
+ ```ts
195
+ const session = await pedelec.createSession();
196
+ ```
197
+
198
+ Use default provider with skills:
199
+
200
+ ```ts
201
+ const session = await pedelec.createSession({
202
+ skills: {
203
+ guidance: "Use update_counter when the user asks to change the counter.",
204
+ tools: [
205
+ defineTool({
206
+ name: "update_counter",
207
+ description: "Update the visible counter by delta.",
208
+ argsSchema: {
209
+ type: "object",
210
+ required: ["delta"],
211
+ properties: {
212
+ delta: {
213
+ type: "number",
214
+ description: "Counter delta.",
215
+ },
216
+ },
217
+ },
218
+ }),
219
+ ],
220
+ },
221
+ });
222
+ ```
223
+
224
+ If no default provider is configured, this rejects with `DEFAULT_PROVIDER_NOT_SET`. If the default provider is configured but unavailable, it rejects with `DEFAULT_PROVIDER_UNAVAILABLE`. If the default provider has its own default model, the SDK sends that model with the session request.
225
+
226
+ Use an explicit provider:
227
+
228
+ ```ts
229
+ const session = await pedelec.createSession({
230
+ provider: "codex",
231
+ });
232
+ ```
233
+
234
+ When only `provider` is passed, the SDK uses that provider's own Desktop App default model if one is configured. Otherwise, it sends the provider without a model and lets the provider CLI use its own default behavior.
235
+ Ollama is the exception: it requires a model, so provider-only Ollama sessions need `defaultModels.ollama` or they fail with `MODEL_REQUIRED`.
236
+
237
+ Use an explicit provider and model:
238
+
239
+ ```ts
240
+ const session = await pedelec.createSession({
241
+ provider: "ollama",
242
+ model: "qwen3-14b-32k:latest",
243
+ });
244
+ ```
245
+
246
+ Ollama sessions are executed by the `pedelec-agent` binary bundled with the Desktop App, not by the `ollama` CLI. You still need to start the local Ollama server yourself. Ollama requires a model from the session input or `defaultModels.ollama`; otherwise the CoreRuntime returns `MODEL_REQUIRED`.
247
+
248
+ By default, SDK-created sessions are page-scoped. `autoEndOnDisconnect` defaults to `true`, so the Desktop thread is ended when the last SDK connection for that session disconnects, such as on page refresh or tab close. Keep the default for demo and page-scoped apps. Set `autoEndOnDisconnect: false` when you need to resume the same session after navigation or share it across pages:
249
+
250
+ ```ts
251
+ const session = await pedelec.createSession({
252
+ provider: "codex",
253
+ autoEndOnDisconnect: false,
254
+ });
255
+ ```
256
+
257
+ `model` cannot be provided without `provider`.
258
+
5
259
  ```ts
6
- import { Pedelec } from "@kaoruisaac/pedelec";
260
+ type CreateSessionInput =
261
+ | {
262
+ provider: ProviderCode;
263
+ model?: string;
264
+ skills?: SkillsInput;
265
+ autoEndOnDisconnect?: boolean;
266
+ }
267
+ | {
268
+ provider?: undefined;
269
+ skills?: SkillsInput;
270
+ autoEndOnDisconnect?: boolean;
271
+ };
7
272
  ```
8
273
 
9
- See the repository README for full setup and usage documentation.
274
+ ## Stream Responses
275
+
276
+ `onChat()` receives text deltas. A delta is not guaranteed to be a sentence or paragraph, so UI code should append chunks.
277
+
278
+ ```ts
279
+ let assistantText = "";
280
+
281
+ session.onChat((text, ctx) => {
282
+ console.debug("chat delta for turn", ctx.turnId, ctx.eventReceivedAt);
283
+ assistantText += text;
284
+ renderAssistantMessage(assistantText);
285
+ });
286
+ ```
287
+
288
+ The returned function unsubscribes the handler:
289
+
290
+ ```ts
291
+ const unsubscribe = session.onChat((text, ctx) => {
292
+ console.log(ctx.turnId, text);
293
+ });
294
+
295
+ unsubscribe();
296
+ ```
297
+
298
+ ## Send Text
299
+
300
+ ```ts
301
+ try {
302
+ await session.sendText("Summarize this workspace.");
303
+ } catch (error) {
304
+ console.error("send failed", error);
305
+ }
306
+ ```
307
+
308
+ `sendText(text)` sets the session status to `running`, sends the prompt to the runtime, and resolves after a `done` or idle status event. It rejects if the session ends, errors, disconnects, or is already busy.
309
+
310
+ ## Session Status
311
+
312
+ ```ts
313
+ session.onStatus((status, ctx) => {
314
+ console.debug("status changed from", ctx.previousStatus, "to", ctx.status);
315
+ switch (status) {
316
+ case "idle":
317
+ break;
318
+ case "running":
319
+ break;
320
+ case "waiting_tool_result":
321
+ break;
322
+ case "ended":
323
+ break;
324
+ case "error":
325
+ break;
326
+ }
327
+ });
328
+
329
+ console.log(session.getStatus());
330
+ ```
331
+
332
+ ```ts
333
+ type PedelecSessionStatus =
334
+ | "idle"
335
+ | "running"
336
+ | "waiting_tool_result"
337
+ | "ended"
338
+ | "error";
339
+ ```
340
+
341
+ | Status | Meaning |
342
+ | --- | --- |
343
+ | `idle` | The session can accept another prompt. |
344
+ | `running` | The agent is processing user text. |
345
+ | `waiting_tool_result` | The agent requested a tool result from the web app. |
346
+ | `ended` | The session has ended and cannot receive more text. |
347
+ | `error` | The session entered an error state. |
348
+
349
+ ## Tool Calling
350
+
351
+ Use `skills` to tell the agent what tools your web app can handle. `guidance` is high-level instruction for the agent, and `tools` is the typed list of callable frontend capabilities. Core automatically generates `tools.md` and per-tool spec artifacts inside the sandbox; SDK users do not write or host those files.
352
+
353
+ Inline handlers are registered locally and are not sent to Core:
354
+
355
+ ```ts
356
+ const session = await pedelec.createSession({
357
+ provider: "codex",
358
+ skills: {
359
+ guidance: "Use get_current_page for browser context.",
360
+ tools: [
361
+ defineTool({
362
+ name: "get_current_page",
363
+ description: "Read the current browser page title and URL.",
364
+ argsSchema: {
365
+ type: "object",
366
+ properties: {},
367
+ required: [],
368
+ },
369
+ handler: (_args, ctx) => ({
370
+ url: location.href,
371
+ title: document.title,
372
+ selectedText: window.getSelection()?.toString() ?? "",
373
+ turnId: ctx.turnId,
374
+ }),
375
+ }),
376
+ ],
377
+ },
378
+ });
379
+ ```
380
+
381
+ You can also register handlers after session creation. A named `onTool(name, handler)` handler overrides an inline handler for the same tool:
382
+
383
+ ```ts
384
+ const session = await pedelec.createSession({
385
+ provider: "codex",
386
+ skills: {
387
+ guidance: "Use update_counter when the user asks to change the counter.",
388
+ tools: [
389
+ defineTool({
390
+ name: "update_counter",
391
+ description: "Update the visible counter by delta.",
392
+ argsSchema: {
393
+ type: "object",
394
+ required: ["delta"],
395
+ properties: {
396
+ delta: {
397
+ type: "number",
398
+ description: "Counter delta.",
399
+ },
400
+ },
401
+ },
402
+ }),
403
+ ],
404
+ },
405
+ });
406
+
407
+ session.onTool("update_counter", async (args, ctx) => {
408
+ const { delta } = args as { delta: number };
409
+ console.debug("tool call", ctx.toolRequestId, ctx.turnId);
410
+ counter.value += delta;
411
+ return {
412
+ counter: counter.value,
413
+ delta,
414
+ };
415
+ });
416
+ ```
417
+
418
+ Tool results must be JSON-serializable. If no handler is registered, the SDK returns a `TOOL_HANDLER_NOT_FOUND` error result. If the handler throws, the SDK returns a `TOOL_HANDLER_ERROR` error result.
419
+
420
+ The generic form `session.onTool((tool, args, ctx) => ...)` remains available as a fallback handler.
421
+
422
+ ### Event Context and UI Lifecycles
423
+
424
+ All user-facing event callbacks receive context metadata. The SDK provides `ctx.sessionId`, `ctx.provider`, `ctx.model`, `ctx.turnId`, `ctx.turnStartedAt`, `ctx.eventReceivedAt`, `ctx.eventEmittedAt`, and `ctx.source` where they apply. `turnId` is SDK-local metadata for one accepted `sendText()` turn; it is not sent to Core and should not be parsed.
425
+
426
+ Apps should still use their own UI lifecycle state to decide whether a late callback is stale:
427
+
428
+ ```ts
429
+ let lifecycleId = 0;
430
+
431
+ function createWorldSession(session: PedelecSession) {
432
+ const generation = ++lifecycleId;
433
+
434
+ session.onTool("spawn_basic_shapes", async (args, ctx) => {
435
+ if (generation !== lifecycleId) {
436
+ return {
437
+ error: {
438
+ code: "STALE_TOOL_CALL",
439
+ message: "This tool call belongs to an older UI lifecycle.",
440
+ },
441
+ };
442
+ }
443
+
444
+ console.debug("handling tool", ctx.toolRequestId, ctx.turnId, ctx.turnStartedAt);
445
+ return spawnBasicShapes(args);
446
+ });
447
+ }
448
+ ```
449
+
450
+ The SDK context helps you inspect which session and turn produced an event. It does not automatically know whether your current canvas, page, render mode, or world instance is still valid.
451
+
452
+ ### Tool Args Schema
453
+
454
+ `defineTool` uses `argsSchema` to describe the tool arguments sent to the provider and agent. The root schema must be an object:
455
+
456
+ ```ts
457
+ defineTool({
458
+ name: "update_counter",
459
+ description: "Update the visible counter by delta.",
460
+ argsSchema: {
461
+ type: "object",
462
+ required: ["delta"],
463
+ properties: {
464
+ delta: {
465
+ type: "number",
466
+ description: "Counter delta.",
467
+ },
468
+ },
469
+ },
470
+ });
471
+ ```
472
+
473
+ `argsSchema` is the Pedelec Tool Args Schema subset, not full JSON Schema. It supports common `string`, `number`, `integer`, `boolean`, `array`, `object`, and `oneOf` nodes with fields such as `description`, `default`, `examples`, `enum`, `minimum`, `maximum`, `minItems`, `maxItems`, and `required`.
474
+
475
+ `default` is guidance for the agent; the SDK does not automatically fill missing argument values. Shorthand schemas such as `input: { delta: "number" }` are no longer supported.
476
+
477
+ The first version does not support `$defs`, `$ref`, `additionalProperties`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, or `format`. Reuse schema fragments with TypeScript constants instead of JSON Schema references.
478
+
479
+ ## Resume Sessions
480
+
481
+ If you have saved a `sessionId`, resume it later:
482
+
483
+ ```ts
484
+ const session = await pedelec.resumeSession("thread_abc123");
485
+
486
+ session.onChat((text, ctx) => {
487
+ console.log(ctx.turnId, text);
488
+ });
489
+
490
+ await session.sendText("Continue the previous task.");
491
+ ```
492
+
493
+ `resumeSession(sessionId)` rejects with `INVALID_INPUT` when `sessionId` is empty.
494
+
495
+ ## End Sessions
496
+
497
+ ```ts
498
+ await session.end();
499
+ ```
500
+
501
+ After a session ends, future `sendText()` calls reject with `SESSION_ENDED`.
502
+
503
+ Listen for runtime-ended sessions:
504
+
505
+ ```ts
506
+ session.onEnded((ctx) => {
507
+ console.log("session ended", ctx.source);
508
+ });
509
+ ```
510
+
511
+ ## Low-Level Requests
512
+
513
+ Most apps should use the typed methods above. `request<T>(type, payload)` is exposed for advanced integrations that need to call bridge operations directly.
514
+
515
+ ```ts
516
+ const result = await pedelec.request<{ sessionId: string }>("create_session", {
517
+ input: {
518
+ provider: "codex",
519
+ skills: undefined,
520
+ autoEndOnDisconnect: true,
521
+ },
522
+ });
523
+ ```
524
+
525
+ Low-level requests still use the SDK bridge timeout and reject with `PedelecError` objects.
526
+
527
+ ## Error Handling
528
+
529
+ Register `onError()` for session-level errors and use `try/catch` around async SDK calls.
530
+
531
+ ```ts
532
+ session.onError((error, ctx) => {
533
+ console.error("session error", ctx.type, error.code, error.message, error.details);
534
+ });
535
+
536
+ try {
537
+ await session.sendText("Update the selected content.");
538
+ } catch (error) {
539
+ console.error("request failed", error);
540
+ }
541
+ ```
542
+
543
+ ```ts
544
+ type PedelecError = {
545
+ code: string;
546
+ message: string;
547
+ details?: unknown;
548
+ };
549
+ ```
550
+
551
+ Common error codes:
552
+
553
+ | Code | Meaning |
554
+ | --- | --- |
555
+ | `EXTENSION_UNAVAILABLE` | The SDK is not running in a supported browser page, or the extension cannot be reached. |
556
+ | `EXTENSION_DISCONNECTED` | The extension connection was interrupted. |
557
+ | `SDK_BRIDGE_TIMEOUT` | The extension did not respond before `bridgeTimeoutMs`. |
558
+ | `SDK_PROTOCOL_ERROR` | The extension response did not match the SDK protocol. |
559
+ | `SDK_TRANSPORT_ERROR` | A bridge request failed at the transport layer. |
560
+ | `APPROVAL_REJECTED` | The user rejected approval for the current origin. |
561
+ | `APPROVAL_TIMEOUT` | The user did not complete origin approval in time. |
562
+ | `OPEN_POPUP_FAILED` | The extension could not open the approval popup. |
563
+ | `NATIVE_HOST_UNAVAILABLE` | Chrome Native Messaging host cannot be reached. |
564
+ | `DEFAULT_PROVIDER_NOT_SET` | The Desktop App has no default provider configured. |
565
+ | `DEFAULT_PROVIDER_UNAVAILABLE` | The configured default provider is not currently available. |
566
+ | `INVALID_INPUT` | The request input is invalid, such as model without provider or empty session id. |
567
+ | `SESSION_BUSY` | The session already has a prompt in progress. |
568
+ | `SESSION_ENDED` | The session has ended. |
569
+ | `SESSION_ERROR` | The runtime reported a session error. |
570
+ | `TOOL_HANDLER_NOT_FOUND` | The agent called a tool but no web app handler is registered. |
571
+ | `TOOL_HANDLER_ERROR` | The web app tool handler threw an error. |
572
+ | `SUBMIT_TOOL_RESULT_FAILED` | The SDK could not submit a tool result back to the runtime. |
573
+
574
+ ## Public API Summary
575
+
576
+ ```ts
577
+ class Pedelec {
578
+ constructor(options?: { bridgeTimeoutMs?: number });
579
+ createSession(input?: CreateSessionInput): Promise<PedelecSession>;
580
+ listProviders(): Promise<ProviderInfo[]>;
581
+ getSettings(): Promise<PedelecSettings>;
582
+ getApprovalStatus(): Promise<ApprovalStatus>;
583
+ resumeSession(sessionId: string): Promise<PedelecSession>;
584
+ request<T>(type: string, payload?: Record<string, unknown>): Promise<T>;
585
+ }
586
+
587
+ class PedelecSession {
588
+ readonly sessionId: string;
589
+ readonly provider: string;
590
+ readonly model?: string;
591
+
592
+ sendText(text: string): Promise<void>;
593
+ onChat(handler: (text: string, ctx: ChatEventContext) => void): () => void;
594
+ onTool(handler: (tool: string, args: unknown, ctx: ToolCallContext) => unknown | Promise<unknown>): () => void;
595
+ onError(handler: (error: PedelecError, ctx: ErrorEventContext) => void): () => void;
596
+ onStatus(handler: (status: PedelecSessionStatus, ctx: StatusEventContext) => void): () => void;
597
+ onEnded(handler: (ctx: EndedEventContext) => void): () => void;
598
+ getStatus(): PedelecSessionStatus;
599
+ end(): Promise<void>;
600
+ }
601
+ ```