@webskill/polyfill 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chunhui Mo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,170 @@
1
- # Temporary Holding Version
1
+ # @webskill/polyfill
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@webskill/polyfill` installs the WebSkill facade on `navigator.webskill` when a browser does not provide it. It reuses `@webskill/sdk` for discovery, validation, local script execution, installation, and run management; it does not contain a second runtime.
4
+
5
+ The package is **experimental**. Its installation API and compatibility matrix may change before `0.1.0`.
6
+
7
+ ## Relationship to the proposed API
8
+
9
+ The native browser API and its vocabulary are defined by the
10
+ [WebSkill explainer](https://github.com/kevinmoch/web-skill/blob/main/EXPLAINER.md)
11
+ ([简体中文](https://github.com/kevinmoch/web-skill/blob/main/EXPLAINER.zh-CN.md)).
12
+ That document describes `navigator.webskill` and the six-method facade; this package is a
13
+ JavaScript compatibility layer that installs the same facade where the browser does not provide it.
14
+
15
+ `installWebSkillPolyfill` and `createLlmClient` are **polyfill/SDK installation helpers**, not
16
+ additional methods in the proposed native API. The canonical handle in examples is:
17
+
18
+ ```js
19
+ const ws = navigator.webskill;
20
+ ```
21
+
22
+ When the browser has no native implementation, the polyfill is installed first and the same
23
+ `navigator.webskill` handle is used afterwards.
24
+
25
+ ## Requirements
26
+
27
+ - A secure browser Window (HTTPS or localhost)
28
+ - OPFS (`navigator.storage.getDirectory`) unless a custom `FileSystemProvider` is supplied
29
+ - Web Workers and ES modules
30
+ - An `LlmClient` supplied by the host
31
+ - `@webskill/sdk` `^0.27.0` as a shared peer dependency (WebKit ESM needs the OPFS move fix)
32
+
33
+ The initial release does not install into Workers, frames, or non-browser runtimes.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ npm install @webskill/polyfill @webskill/sdk
39
+ ```
40
+
41
+ A complete local-script example is available in
42
+ [`examples/quickstart-polyfill`](../../examples/quickstart-polyfill).
43
+
44
+ ## ESM usage
45
+
46
+ ```js
47
+ import { createLlmClient, installWebSkillPolyfill } from '@webskill/polyfill';
48
+
49
+ const llm = createLlmClient({
50
+ provider: 'openai-compatible',
51
+ baseUrl: 'https://your-llm-endpoint/v1',
52
+ apiKey: 'provided-by-the-host',
53
+ model: 'your-model'
54
+ });
55
+
56
+ // Native first: install only when navigator.webskill is absent.
57
+ const ws =
58
+ navigator.webskill ??
59
+ installWebSkillPolyfill({
60
+ roots: ['/skills'],
61
+ llm
62
+ });
63
+
64
+ if (!ws) {
65
+ // Keep the application's existing non-WebSkill fallback.
66
+ } else {
67
+ const catalog = await ws.discover('/skills');
68
+ const doc = await ws.read('sales');
69
+ const report = await ws.validate('/skills');
70
+ const run = await ws.run('Use the sales skill to total 12.5, 7.5, and 20.');
71
+
72
+ console.log(catalog.entries, doc.metadata.description, report.ok);
73
+ console.log(run.status, run.activeSkillNames, run.trace, run.artifacts);
74
+ }
75
+ ```
76
+
77
+ The six facade methods and their result shapes are the same as the SDK and the explainer:
78
+
79
+ | Method | Result |
80
+ | ----------------- | ------------------------ |
81
+ | `discover(path)` | `SkillCatalog` |
82
+ | `read(name)` | `SkillDocument` |
83
+ | `validate(path)` | `ValidationReport` |
84
+ | `run(prompt)` | `RuntimeRun` |
85
+ | `install(url)` | `InstalledSkillManifest` |
86
+ | `uninstall(name)` | `void` |
87
+
88
+ Local scripts execute without MCP or WebMCP. Those protocols remain optional integrations, not
89
+ requirements for running a skill.
90
+
91
+ ## Local script contract
92
+
93
+ A script in a skill's `scripts/` directory exports `description`, `inputSchema`, and
94
+ `run(input, context)`. The `context` exposes narrow host capabilities such as
95
+ `writeArtifact` and `confirm`; it is not an arbitrary host object.
96
+
97
+ ```js
98
+ export const description = 'Greet someone by name.';
99
+ export const inputSchema = {
100
+ type: 'object',
101
+ properties: { text: { type: 'string' } },
102
+ required: ['text']
103
+ };
104
+
105
+ export async function run(input, context) {
106
+ const message = 'Hello, ' + input.text + '!';
107
+ await context.writeArtifact('greeting.json', JSON.stringify({ message }), {
108
+ mimeType: 'application/json'
109
+ });
110
+ return [{ type: 'text', text: message }];
111
+ }
112
+ ```
113
+
114
+ This follows [§8.8](https://github.com/kevinmoch/web-skill/blob/main/EXPLAINER.md#88-script-module-contract)
115
+ and [§9.3](https://github.com/kevinmoch/web-skill/blob/main/EXPLAINER.md#93-run-a-self-contained-script-backed-skill)
116
+ of the explainer.
117
+
118
+ ## Standalone script
119
+
120
+ Serve `dist/polyfill.js` before the application. Loading the file only defines `globalThis.WebSkillPolyfill`; it does not install the facade or select a model.
121
+
122
+ ```html
123
+ <script src="/assets/polyfill.js"></script>
124
+ <script>
125
+ const llm = WebSkillPolyfill.createLlmClient(config);
126
+ const ws = navigator.webskill ?? WebSkillPolyfill.install({ roots: ['/skills'], llm });
127
+
128
+ if (ws) {
129
+ ws.discover('/skills').then((catalog) => console.log(catalog.entries));
130
+ }
131
+ </script>
132
+ ```
133
+
134
+ The standalone build contains the SDK runtime. The ESM build keeps `@webskill/sdk` external so an application shares one SDK instance.
135
+
136
+ ## Installation semantics
137
+
138
+ - **Native first.** Any existing `navigator.webskill` — object, function, accessor, or read-only/non-configurable descriptor — is returned unchanged, without requiring an LLM. An accessor that returns `undefined` stays untouched.
139
+ - **Validate only on install.** `llm` is checked only when the polyfill actually has to assemble the SDK. Native, already-installed, and unsupported environments return without throwing `LLM_UNAVAILABLE`.
140
+ - **Idempotent.** Repeated calls return the same facade even if the second call has a different or missing `llm`/`fs`. The first successful configuration wins; changing configuration later requires a page reload.
141
+ - **No half-install.** The SDK is assembled against a local staging object first. If the real navigator cannot receive the getter, the call returns `undefined` and leaves it untouched — no writable `webskill` property is left behind.
142
+ - **Read-only facade.** Installation exposes `webskill` through a getter rather than a writable assignment.
143
+ - **SSR-safe import.** Importing the package does not touch browser globals. Calling install in an unsupported environment returns `undefined` instead of creating a partial global facade.
144
+ - **No silent storage fallback.** OPFS is required unless the host explicitly supplies another filesystem. MemoryFS and localStorage are not automatic substitutes.
145
+ - **`target` is an injection seam.** Passing `target` replaces only the object that receives `webskill` and intentionally bypasses the Window/secure-context/Worker/OPFS checks. It is for tests and host-controlled embedding; it is **not** a promise of Worker, cross-frame, or non-browser support. Omit it in production.
146
+
147
+ There is no `auto` entry point. Model, filesystem, and execution policy must be chosen explicitly.
148
+
149
+ ## Install sources and execution boundaries
150
+
151
+ Browser installation supports HTTP(S) ZIP archives and `ArrayBuffer` archives through the SDK's browser manager. Git and npm sources remain unsupported and return `TOOL_UNSUPPORTED`.
152
+
153
+ `run()` returns the current `RuntimeRun` shape. The polyfill does not add streaming output, new run options, or browser-native model management.
154
+
155
+ The default Window execution path uses the SDK's opaque-origin iframe sandbox. This is not a claim that every Worker or every script is equally safe. Network policy, capability approval, and script isolation remain the SDK's responsibility and must not be weakened by the host.
156
+
157
+ ## Security and privacy
158
+
159
+ - Do not embed production API keys in a public browser bundle. Use an on-device model or a host-controlled server/proxy where appropriate.
160
+ - The polyfill cannot create a browser-native permission prompt, browser agent, or native trust decision.
161
+ - OPFS provides origin-private storage, not confidentiality from every script or service authorized by the same origin.
162
+ - Polyfilled APIs are not evidence of native browser support or full standards conformance.
163
+
164
+ ## Package validation
165
+
166
+ The repository checks ESM and IIFE behavior, native preservation, repeated installation, SSR imports, public types, package contents, and real browser execution. Current results, commands, support boundaries, and any unverified browser environments are recorded in [TESTING.md](TESTING.md).
167
+
168
+ ## License
169
+
170
+ MIT
package/TESTING.md ADDED
@@ -0,0 +1,81 @@
1
+ # Testing
2
+
3
+ The public facade vocabulary (`navigator.webskill`, `ws`, six methods, `run(input, context)`)
4
+ follows the [WebSkill explainer](https://github.com/kevinmoch/web-skill/blob/main/EXPLAINER.md).
5
+ This file only records how the polyfill installation and compatibility path is verified.
6
+
7
+ ## Current validation results
8
+
9
+ The polyfill behavior and package checks pass in the current checkout:
10
+
11
+ - 17 installation and lifecycle tests (`--project polyfill`)
12
+ - 6 OPFS native-rename compatibility tests (`OpfsProvider.rename`): one/two-arg, `.length==0` retry, both-fail, and copy+remove fallback
13
+ - Public API snapshot, dist smoke, release workflow, and package smoke checks
14
+ - ESM and standalone IIFE SSR imports and public TypeScript declarations
15
+ - **Chromium:** full local-script, artifact, ZIP install/uninstall, idempotency, and native-preservation flow passed
16
+ - **WebKit:** the same flow passed locally with a persistent browser context and SDK ≥ 0.27.0. GitHub’s Linux WebKit build does not expose OPFS, so the Playwright case explicitly skips there instead of failing; the lifecycle remains covered on macOS WebKit and Chromium.
17
+ - **Firefox:** the same flow passed in a real Firefox 158 window via the manual autorun flow below (20/20 assertions, ESM and standalone IIFE)
18
+
19
+ **Firefox is verified manually, not through Playwright.** Playwright-managed Firefox Nightly still fails during browser launch before any application code runs in this macOS environment. The reported errors include `RenderCompositorSWGL failed mapping default framebuffer` and a plugin-container sandbox error; headless, headed, sandbox-disabled, and WebRender-disabled attempts did not resolve the launch failure. The lifecycle is therefore verified in a real Firefox window: the autorun page evaluates the same 20 assertions as the Playwright test, renders PASS/FAIL in-page, and POSTs the report to a local collector. Playwright Firefox automation remains blocked by that environment limitation; the manual result above is the current Firefox evidence.
20
+
21
+ WebKit ESM requires `@webskill/sdk` ≥ 0.27.0; older peers may install a `move()` implementation that only supports the one-argument signature. WebKit's OPFS implementation also requires a persistent context in this test setup. See [microsoft/playwright#18235](https://github.com/microsoft/playwright/issues/18235) for the ephemeral-context limitation. The WebKit test also covers the two native `FileSystemHandle.move()` signatures: Chromium's `move(name)` and WebKit's `move(destinationDirectory, name)`.
22
+
23
+ ## Commands
24
+
25
+ ```bash
26
+ # Unit and behavior tests
27
+ pnpm exec vitest run --project polyfill
28
+ pnpm exec vitest run --project browser packages/browser/test/opfsRename.test.ts
29
+
30
+ # API, package, and consumer checks
31
+ node scripts/apiSnapshot.mjs --check --dist-dir packages/polyfill/dist --snap-dir api-snapshots/polyfill --entries index
32
+ node scripts/polyfillPackageSmoke.mjs
33
+ pnpm test:install-smoke
34
+
35
+ # Real browsers (Chromium and WebKit)
36
+ pnpm exec playwright test --config playwright.polyfill.config.ts --project=chromium --project=webkit
37
+
38
+ # Chromium + WebKit (Firefox is manual; the headless launcher is broken here)
39
+ pnpm test:e2e:polyfill
40
+
41
+ # Manual Firefox verification (real browser, no automation driver)
42
+ pnpm -C packages/sdk build && pnpm -C packages/polyfill build
43
+ POLYFILL_E2E_PACKAGE_ROOT="$(node scripts/preparePolyfillE2E.mjs)" pnpm exec vite build test/polyfill-app
44
+ node scripts/preparePolyfillQuickstart.mjs
45
+ pnpm exec vite preview test/polyfill-app --host 127.0.0.1 --port 5212 --strictPort &
46
+ node scripts/collectPolyfillReport.mjs &
47
+ open -a Firefox "http://127.0.0.1:5212/?autorun=1" # or paste the URL into any browser
48
+ # The page renders PASS/FAIL and POSTs the report to /tmp/polyfill-e2e-report.json
49
+ ```
50
+
51
+ ## Support matrix
52
+
53
+ | Environment | ESM polyfill | Standalone IIFE | Notes |
54
+ | ---------------------------------- | ----------------- | ----------------- | ---------------------------------------------------------------------------------------------- |
55
+ | Chromium (Window) | Verified | Verified | Full lifecycle, OPFS, Worker sandbox |
56
+ | WebKit (Window) | Verified | Verified | Requires a persistent context for OPFS; SDK ≥ 0.27.0 |
57
+ | Firefox (Window) | Verified (manual) | Verified (manual) | Real Firefox 158 window via the autorun flow; Playwright-managed Firefox still fails to launch |
58
+ | Worker / cross-frame / non-browser | Not supported | Not supported | `target` is a test/host seam, not support |
59
+
60
+ ## Supported behavior
61
+
62
+ - Explicit installation in a secure browser Window
63
+ - Native and partial-native preservation
64
+ - Idempotent installation with first-configuration-wins semantics
65
+ - `discover` / `read` / `validate` / `run` / `install` / `uninstall`
66
+ - Local scripts without MCP or WebMCP
67
+ - OPFS persistence, opaque-origin iframe script execution, and HTTP(S) ZIP installation
68
+ - ESM and standalone IIFE distributions, including global TypeScript declarations
69
+
70
+ ## Limitations
71
+
72
+ - No `auto` entry point and no default model configuration
73
+ - No Worker, cross-frame, or cross-origin installation
74
+ - No automatic MemoryFS/localStorage fallback when OPFS is unavailable
75
+ - No Git/npm installation sources in the browser
76
+ - No browser-native permission UI, browser agent, or native trust decision
77
+ - No claim of full standards conformance or native browser availability
78
+
79
+ ## Package and repository checks
80
+
81
+ `pnpm typecheck`, `pnpm build`, `pnpm api:check`, `pnpm lint`, and `pnpm test:install-smoke` also cover this package. The full repository's env-gated real-model integration tests depend on external providers and are outside this package's deterministic validation scope.
@@ -0,0 +1,11 @@
1
+ import type { WebSkillApi, WebSkillPolyfillConfig } from './index.js';
2
+ import type { ConfiguredLlmClient, LlmEntryConfig } from '@webskill/sdk/browser';
3
+
4
+ export interface WebSkillPolyfillGlobal {
5
+ install(config: WebSkillPolyfillConfig): WebSkillApi | undefined;
6
+ createLlmClient(config: LlmEntryConfig): ConfiguredLlmClient;
7
+ }
8
+
9
+ declare global {
10
+ const WebSkillPolyfill: WebSkillPolyfillGlobal;
11
+ }
@@ -0,0 +1,23 @@
1
+ import { LlmClient, WebSkillApi, WebSkillApi as WebSkillApi$1 } from "@webskill/sdk";
2
+ import { ConfiguredLlmClient, LlmEntryConfig, TypeScriptSupportOptions, createLlmClient, installWebSkillNavigator } from "@webskill/sdk/browser";
3
+ //#region src/install.d.ts
4
+ interface WebSkillNavigatorTarget {
5
+ navigator?: Record<string, unknown>;
6
+ }
7
+ interface WebSkillPolyfillConfig {
8
+ roots?: string[];
9
+ /** Native/installed/unsupported paths do not need it; required only for a real install. */
10
+ llm?: LlmClient;
11
+ typescript?: TypeScriptSupportOptions;
12
+ fs?: Parameters<typeof installWebSkillNavigator>[0]['fs'];
13
+ managedRoot?: string;
14
+ target?: WebSkillNavigatorTarget;
15
+ }
16
+ /**
17
+ * Install the WebSkill facade without replacing an existing native implementation.
18
+ * The first successful configuration wins for the lifetime of the navigator object.
19
+ * @experimental
20
+ */
21
+ declare function installWebSkillPolyfill(config: WebSkillPolyfillConfig): WebSkillApi$1 | undefined;
22
+ //#endregion
23
+ export { type ConfiguredLlmClient, type LlmEntryConfig, type WebSkillApi, type WebSkillNavigatorTarget, type WebSkillPolyfillConfig, createLlmClient, installWebSkillPolyfill };
package/dist/index.js ADDED
@@ -0,0 +1,67 @@
1
+ import { WebSkillError } from "@webskill/sdk";
2
+ import { createLlmClient, installWebSkillNavigator } from "@webskill/sdk/browser";
3
+
4
+ //#region src/install.ts
5
+ const installations = /* @__PURE__ */ new WeakMap();
6
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7
+ const invalidTarget = () => new WebSkillError("VALIDATION_FAILED", "target must be an object; target.navigator, when present, must be a non-null object");
8
+ function expose(nav, api) {
9
+ Object.defineProperty(nav, "webskill", {
10
+ configurable: true,
11
+ enumerable: true,
12
+ get: () => api
13
+ });
14
+ }
15
+ /**
16
+ * Install the WebSkill facade without replacing an existing native implementation.
17
+ * The first successful configuration wins for the lifetime of the navigator object.
18
+ * @experimental
19
+ */
20
+ function installWebSkillPolyfill(config) {
21
+ if (config.target !== void 0 && !isObject(config.target)) throw invalidTarget();
22
+ let nav;
23
+ if (config.target !== void 0) {
24
+ const target = config.target;
25
+ if (target.navigator !== void 0 && !isObject(target.navigator)) throw invalidTarget();
26
+ if (target.navigator !== void 0) nav = target.navigator;
27
+ else try {
28
+ nav = {};
29
+ target.navigator = nav;
30
+ } catch {
31
+ throw invalidTarget();
32
+ }
33
+ } else if (typeof navigator !== "undefined") nav = navigator;
34
+ if (nav === void 0) return void 0;
35
+ if ("webskill" in nav) return nav["webskill"];
36
+ const installed = installations.get(nav);
37
+ if (installed !== void 0) {
38
+ expose(nav, installed);
39
+ return installed;
40
+ }
41
+ if (config.target === void 0) {
42
+ if (typeof window === "undefined" || typeof document === "undefined") return void 0;
43
+ if (globalThis.isSecureContext !== true) return void 0;
44
+ if (typeof Worker !== "function") return void 0;
45
+ if (!config.fs && typeof navigator.storage?.getDirectory !== "function") return void 0;
46
+ }
47
+ const llm = config.llm;
48
+ if (typeof llm?.complete !== "function") throw new WebSkillError("LLM_UNAVAILABLE", "installWebSkillPolyfill requires an LlmClient with a complete() method");
49
+ const api = installWebSkillNavigator({
50
+ roots: config.roots,
51
+ llm,
52
+ typescript: config.typescript,
53
+ fs: config.fs,
54
+ managedRoot: config.managedRoot,
55
+ target: { navigator: {} }
56
+ });
57
+ try {
58
+ expose(nav, api);
59
+ } catch {
60
+ return;
61
+ }
62
+ installations.set(nav, api);
63
+ return api;
64
+ }
65
+
66
+ //#endregion
67
+ export { createLlmClient, installWebSkillPolyfill };