@immediately-run/sdk 0.83.0 → 0.85.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/dist/catalog.cjs +2 -0
- package/dist/catalog.cjs.map +1 -1
- package/dist/catalog.js +2 -0
- package/dist/catalog.js.map +1 -1
- package/dist/contribute.cjs.map +1 -1
- package/dist/contribute.d.cts +39 -1
- package/dist/contribute.d.ts +39 -1
- package/dist/contribute.js.map +1 -1
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/openBundle.cjs +44 -0
- package/dist/openBundle.cjs.map +1 -0
- package/dist/openBundle.d.cts +53 -0
- package/dist/openBundle.d.ts +53 -0
- package/dist/openBundle.js +20 -0
- package/dist/openBundle.js.map +1 -0
- package/dist/openRepository.cjs +4 -4
- package/dist/openRepository.cjs.map +1 -1
- package/dist/openRepository.d.cts +12 -2
- package/dist/openRepository.d.ts +12 -2
- package/dist/openRepository.js +4 -4
- package/dist/openRepository.js.map +1 -1
- package/dist/protocolDeadline.cjs +15 -0
- package/dist/protocolDeadline.cjs.map +1 -1
- package/dist/protocolDeadline.js +15 -0
- package/dist/protocolDeadline.js.map +1 -1
- package/dist/protocolRefusal.cjs.map +1 -1
- package/dist/protocolRefusal.d.cts +1 -1
- package/dist/protocolRefusal.d.ts +1 -1
- package/dist/protocolRefusal.js.map +1 -1
- package/dist/protocolSchemes.cjs +1 -0
- package/dist/protocolSchemes.cjs.map +1 -1
- package/dist/protocolSchemes.d.cts +1 -0
- package/dist/protocolSchemes.d.ts +1 -0
- package/dist/protocolSchemes.js +2 -0
- package/dist/protocolSchemes.js.map +1 -1
- package/dist/vcs.cjs +106 -1
- package/dist/vcs.cjs.map +1 -1
- package/dist/vcs.d.cts +104 -1
- package/dist/vcs.d.ts +104 -1
- package/dist/vcs.js +99 -1
- package/dist/vcs.js.map +1 -1
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import "./chunk-VHAA22YE.js";
|
|
2
|
+
import { protocolRequest } from "./sandboxUtils.js";
|
|
3
|
+
import { throwOnRefusal } from "./protocolRefusal.js";
|
|
4
|
+
import { PROTOCOL_OPENBUNDLE } from "./generated/protocol.js";
|
|
5
|
+
import { SCHEMES } from "./protocolSchemes.js";
|
|
6
|
+
const OPEN_BUNDLE_REPLY_TIMEOUT_MS = 2e3;
|
|
7
|
+
async function openBundle(target) {
|
|
8
|
+
const { $cap, mountId, relPath, mode } = target?.dir ?? {};
|
|
9
|
+
const params = { dir: { $cap, mountId, relPath, mode } };
|
|
10
|
+
if (target?.view !== void 0) params.view = target.view;
|
|
11
|
+
const res = await protocolRequest(SCHEMES[PROTOCOL_OPENBUNDLE], "open", [params], {
|
|
12
|
+
timeoutMs: OPEN_BUNDLE_REPLY_TIMEOUT_MS
|
|
13
|
+
});
|
|
14
|
+
throwOnRefusal(res, "bundle open refused");
|
|
15
|
+
}
|
|
16
|
+
export {
|
|
17
|
+
OPEN_BUNDLE_REPLY_TIMEOUT_MS,
|
|
18
|
+
openBundle
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=openBundle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/openBundle.ts"],"sourcesContent":["// Host-mediated \"open this bundle in its own tab\" (BUNDLE_EMBEDDING_SPEC §4b.9).\n//\n// Opening a bundle is not a for-result task: the reader stays, the view wants the whole\n// screen, and the bundle's files are what they work on next. So a file manager's\n// \"Open as …\" asks the host for a new tab — an ordinary session of the opener over the\n// bundle — instead of the task overlay. The tab starts in present mode, except for a local\n// dev-server source, whose tab is its editing session.\n//\n// The app names the DIRECTORY it already holds, as the same capability it would hand a\n// task, and optionally a declared view by NAME. It cannot pass a URL, a route or an app:\n// the host maps the capability to a location it can address, builds the destination from\n// its own route grammar, and the opened tab re-reads the bundle's marker and resolves the\n// opener itself. The link grants nothing.\n//\n// Not every directory has an address. A folder in a space, or on a session mount, cannot\n// be named by a URL today; the host refuses those with `unaddressable`, and the caller\n// keeps its overlay open (`invokeTask`) as the fallback.\n//\n// A host that predates this call does not refuse it — it does not answer at all, because\n// it has never heard of the request. A host that knows the request answers on the turn it\n// arrives, so the wait is bounded tightly here and its expiry (`timeout`) is the third\n// reason to fall back.\n//\n// As with `openRepository`, the open needs the HOST document's live transient user\n// activation, which the host samples rather than believes.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENBUNDLE } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\nimport type { DirCap } from './tasks';\n\n/** What to open: a bundle directory the app holds, and optionally one of its declared views. */\nexport interface OpenBundleTarget {\n /** The bundle's directory, as the capability the app holds on it (`capDir(...)`). */\n dir: DirCap;\n /** A view the bundle's marker declares, by name. The host resolves which app shows it. */\n view?: string;\n}\n\n/** Why a bundle did not open in a tab.\n *\n * - `invalid-params` — `dir` is not a directory capability, or `view` is not a string.\n * - `invalid` — `view` is not a view name.\n * - `unaddressable` — the directory is real and the app holds it, but the host has no URL\n * for it (a space folder, a session mount). Fall back to the overlay open.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler, with no `await` before it.\n * - `forbidden` — the app may not open tabs, or does not hold the directory it named.\n * - `unsupported` — this host knows the request but has no bundle-open surface wired.\n * Fall back to the overlay open.\n * - `timeout` — the host did not answer within {@link OPEN_BUNDLE_REPLY_TIMEOUT_MS}. That\n * is what a host that predates this call does. Fall back to the overlay open.\n * - `unknown` — the host refused without naming a code.\n *\n * The SDK throws a plain `Error` with `.code` assigned; `.code` is whatever string the\n * host sent, so treat an unlisted code as possible. */\nexport type OpenBundleErrorCode =\n | 'invalid-params'\n | 'invalid'\n | 'unaddressable'\n | 'no-activation'\n | 'forbidden'\n | 'unsupported'\n | 'timeout'\n | 'unknown';\n\n/**\n * How long `openBundle` waits for the host's answer, in ms. A host that knows the request\n * decides it synchronously — nothing is fetched and nobody is asked — so the answer is one\n * message round trip away. A host that does not know it never answers, and a click that\n * does nothing for the default thirty seconds before falling back would read as broken.\n */\nexport const OPEN_BUNDLE_REPLY_TIMEOUT_MS = 2000;\n\nexport interface OpenBundleError extends Error {\n code: OpenBundleErrorCode;\n}\n\n/** The wire params: the capability and the view name, and nothing else. */\ninterface OpenBundleParams {\n dir: DirCap;\n view?: string;\n}\n\n/** The host's reply: a refusal is a resolved `{ ok: false }`, not a transport rejection. */\ntype OpenBundleReply = { ok: true } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a bundle in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with an {@link OpenBundleError} carrying `code` otherwise.\n * On `unaddressable`, `unsupported` or `timeout`, open the bundle the way you did before\n * this call existed: the `invokeTask` you used (`open-declared` for an app-form marker or a\n * declared view, the marker's own contract for a task-form one).\n *\n * Call it directly from a user gesture: the host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture is refused\n * `no-activation`.\n */\nexport async function openBundle(target: OpenBundleTarget): Promise<void> {\n // Whatever was passed as `dir` is narrowed to the capability's four fields and sent: a\n // value that is not a capability is the host's to refuse (`invalid-params`), with a code.\n const { $cap, mountId, relPath, mode } = (target?.dir ?? {}) as DirCap;\n const params: OpenBundleParams = { dir: { $cap, mountId, relPath, mode } };\n if (target?.view !== undefined) params.view = target.view;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENBUNDLE], 'open', [params], {\n timeoutMs: OPEN_BUNDLE_REPLY_TIMEOUT_MS,\n })) as OpenBundleReply;\n throwOnRefusal(res, 'bundle open refused');\n}\n"],"mappings":";AAyBA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,2BAA2B;AACpC,SAAS,eAAe;AA4CjB,MAAM,+BAA+B;AA4B5C,eAAsB,WAAW,QAAyC;AAGxE,QAAM,EAAE,MAAM,SAAS,SAAS,KAAK,IAAK,QAAQ,OAAO,CAAC;AAC1D,QAAM,SAA2B,EAAE,KAAK,EAAE,MAAM,SAAS,SAAS,KAAK,EAAE;AACzE,MAAI,QAAQ,SAAS,OAAW,QAAO,OAAO,OAAO;AACrD,QAAM,MAAO,MAAM,gBAAgB,QAAQ,mBAAmB,GAAG,QAAQ,CAAC,MAAM,GAAG;AAAA,IACjF,WAAW;AAAA,EACb,CAAC;AACD,iBAAe,KAAK,qBAAqB;AAC3C;","names":[]}
|
package/dist/openRepository.cjs
CHANGED
|
@@ -25,11 +25,11 @@ var import_sandboxUtils = require("./sandboxUtils");
|
|
|
25
25
|
var import_protocolRefusal = require("./protocolRefusal");
|
|
26
26
|
var import_protocol = require("./generated/protocol");
|
|
27
27
|
var import_protocolSchemes = require("./protocolSchemes");
|
|
28
|
-
async function openRepository(coordinates) {
|
|
28
|
+
async function openRepository(coordinates, reveal) {
|
|
29
29
|
const { provider, namespace, repository } = coordinates;
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
]);
|
|
30
|
+
const params = { provider, namespace, repository };
|
|
31
|
+
if (reveal !== void 0) params.reveal = reveal;
|
|
32
|
+
const res = await (0, import_sandboxUtils.protocolRequest)(import_protocolSchemes.SCHEMES[import_protocol.PROTOCOL_OPENREPO], "open", [params]);
|
|
33
33
|
(0, import_protocolRefusal.throwOnRefusal)(res, "repository open refused");
|
|
34
34
|
}
|
|
35
35
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends. Nothing enforces the union at runtime — `.code` is\n * whatever string arrived — so treat an unlisted code as possible and `instanceof Error`\n * as the only reliable test.\n *\n * (This note is on the code alias rather than on the interface because the alias is where\n * the codes are documented. Every doclink in this file names the INTERFACE, so a reader\n * following one lands a hop away from this — a wart, not a plan. Stated without a\n * direction on purpose: two earlier revisions of this sentence asserted a positional\n * claim, and both were wrong.) */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n
|
|
1
|
+
{"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// R3-1033: an optional REVEAL rides the open — a closed chrome enum, never a destination.\n// The app still cannot pass a URL, a route prefix or a path; the host decides what the\n// reveal means (which surface of ITS chrome opens) and builds every URL itself. A future\n// panel joins the `RepositoryReveal` union deliberately, never by a free string.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** A chrome reveal that may ride an open (R3-1033) — the host's own surface to open at the\n * destination, never a destination the app names. `'agent'` is the conversations panel;\n * the value set is closed on purpose (see the header). */\nexport interface RepositoryReveal {\n panel: 'agent';\n}\n\n/** The `open` wire params — the coordinates plus the optional reveal. Typed as a named\n * interface (not an inline literal) so the protocol-snapshot extractor resolves the wire\n * shape from the type; see `openRepository` below. */\ninterface OpenRepositoryOpenParams extends RepositoryCoordinates {\n reveal?: RepositoryReveal;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends. Nothing enforces the union at runtime — `.code` is\n * whatever string arrived — so treat an unlisted code as possible and `instanceof Error`\n * as the only reliable test.\n *\n * (This note is on the code alias rather than on the interface because the alias is where\n * the codes are documented. Every doclink in this file names the INTERFACE, so a reader\n * following one lands a hop away from this — a wart, not a plan. Stated without a\n * direction on purpose: two earlier revisions of this sentence asserted a positional\n * claim, and both were wrong.) */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * `reveal` (R3-1033) optionally asks the host to open one of its own chrome surfaces at\n * the destination — a closed enum (`RepositoryReveal`), never a destination. Omitted,\n * the open lands exactly as before.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates, reveal?: RepositoryReveal): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n // The reveal rides the one wire arg when the caller asked for it; a caller omitting it\n // sends no field at all (never `undefined` on the wire — the host validates what arrives).\n // Typed as OpenRepositoryOpenParams (the named interface) so the protocol-snapshot\n // extractor resolves the wire shape from the type — an intersection or a bare Record\n // would read shapeless and the check would flag a reshape that is not one.\n const params: OpenRepositoryOpenParams = { provider, namespace, repository };\n if (reveal !== undefined) params.reveal = reveal;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [params])) as OpenRepositoryReply;\n throwOnRefusal(res, 'repository open refused');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,0BAAgC;AAChC,6BAA+B;AAC/B,sBAAkC;AAClC,6BAAwB;AAwExB,eAAsB,eAAe,aAAoC,QAA0C;AACjH,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAM5C,QAAM,SAAmC,EAAE,UAAU,WAAW,WAAW;AAC3E,MAAI,WAAW,OAAW,QAAO,SAAS;AAC1C,QAAM,MAAO,UAAM,qCAAgB,+BAAQ,iCAAiB,GAAG,QAAQ,CAAC,MAAM,CAAC;AAC/E,6CAAe,KAAK,yBAAyB;AAC/C;","names":[]}
|
|
@@ -5,6 +5,12 @@ interface RepositoryCoordinates {
|
|
|
5
5
|
namespace: string;
|
|
6
6
|
repository: string;
|
|
7
7
|
}
|
|
8
|
+
/** A chrome reveal that may ride an open (R3-1033) — the host's own surface to open at the
|
|
9
|
+
* destination, never a destination the app names. `'agent'` is the conversations panel;
|
|
10
|
+
* the value set is closed on purpose (see the header). */
|
|
11
|
+
interface RepositoryReveal {
|
|
12
|
+
panel: 'agent';
|
|
13
|
+
}
|
|
8
14
|
/** Why the host refused to open a tab.
|
|
9
15
|
*
|
|
10
16
|
* - `invalid` — the coordinates are not three clean path segments.
|
|
@@ -34,6 +40,10 @@ interface OpenRepositoryError extends Error {
|
|
|
34
40
|
/**
|
|
35
41
|
* Ask the host to open a repository in a new browser tab.
|
|
36
42
|
*
|
|
43
|
+
* `reveal` (R3-1033) optionally asks the host to open one of its own chrome surfaces at
|
|
44
|
+
* the destination — a closed enum (`RepositoryReveal`), never a destination. Omitted,
|
|
45
|
+
* the open lands exactly as before.
|
|
46
|
+
*
|
|
37
47
|
* Resolves once the host has performed the open; it does not wait for — and cannot observe —
|
|
38
48
|
* the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`
|
|
39
49
|
* when the host refuses.
|
|
@@ -43,6 +53,6 @@ interface OpenRepositoryError extends Error {
|
|
|
43
53
|
* it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
|
|
44
54
|
* worth retrying: each names a condition a retry cannot change.
|
|
45
55
|
*/
|
|
46
|
-
declare function openRepository(coordinates: RepositoryCoordinates): Promise<void>;
|
|
56
|
+
declare function openRepository(coordinates: RepositoryCoordinates, reveal?: RepositoryReveal): Promise<void>;
|
|
47
57
|
|
|
48
|
-
export { type OpenRepositoryError, type OpenRepositoryErrorCode, type RepositoryCoordinates, openRepository };
|
|
58
|
+
export { type OpenRepositoryError, type OpenRepositoryErrorCode, type RepositoryCoordinates, type RepositoryReveal, openRepository };
|
package/dist/openRepository.d.ts
CHANGED
|
@@ -5,6 +5,12 @@ interface RepositoryCoordinates {
|
|
|
5
5
|
namespace: string;
|
|
6
6
|
repository: string;
|
|
7
7
|
}
|
|
8
|
+
/** A chrome reveal that may ride an open (R3-1033) — the host's own surface to open at the
|
|
9
|
+
* destination, never a destination the app names. `'agent'` is the conversations panel;
|
|
10
|
+
* the value set is closed on purpose (see the header). */
|
|
11
|
+
interface RepositoryReveal {
|
|
12
|
+
panel: 'agent';
|
|
13
|
+
}
|
|
8
14
|
/** Why the host refused to open a tab.
|
|
9
15
|
*
|
|
10
16
|
* - `invalid` — the coordinates are not three clean path segments.
|
|
@@ -34,6 +40,10 @@ interface OpenRepositoryError extends Error {
|
|
|
34
40
|
/**
|
|
35
41
|
* Ask the host to open a repository in a new browser tab.
|
|
36
42
|
*
|
|
43
|
+
* `reveal` (R3-1033) optionally asks the host to open one of its own chrome surfaces at
|
|
44
|
+
* the destination — a closed enum (`RepositoryReveal`), never a destination. Omitted,
|
|
45
|
+
* the open lands exactly as before.
|
|
46
|
+
*
|
|
37
47
|
* Resolves once the host has performed the open; it does not wait for — and cannot observe —
|
|
38
48
|
* the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`
|
|
39
49
|
* when the host refuses.
|
|
@@ -43,6 +53,6 @@ interface OpenRepositoryError extends Error {
|
|
|
43
53
|
* it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are
|
|
44
54
|
* worth retrying: each names a condition a retry cannot change.
|
|
45
55
|
*/
|
|
46
|
-
declare function openRepository(coordinates: RepositoryCoordinates): Promise<void>;
|
|
56
|
+
declare function openRepository(coordinates: RepositoryCoordinates, reveal?: RepositoryReveal): Promise<void>;
|
|
47
57
|
|
|
48
|
-
export { type OpenRepositoryError, type OpenRepositoryErrorCode, type RepositoryCoordinates, openRepository };
|
|
58
|
+
export { type OpenRepositoryError, type OpenRepositoryErrorCode, type RepositoryCoordinates, type RepositoryReveal, openRepository };
|
package/dist/openRepository.js
CHANGED
|
@@ -3,11 +3,11 @@ import { protocolRequest } from "./sandboxUtils.js";
|
|
|
3
3
|
import { throwOnRefusal } from "./protocolRefusal.js";
|
|
4
4
|
import { PROTOCOL_OPENREPO } from "./generated/protocol.js";
|
|
5
5
|
import { SCHEMES } from "./protocolSchemes.js";
|
|
6
|
-
async function openRepository(coordinates) {
|
|
6
|
+
async function openRepository(coordinates, reveal) {
|
|
7
7
|
const { provider, namespace, repository } = coordinates;
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
]);
|
|
8
|
+
const params = { provider, namespace, repository };
|
|
9
|
+
if (reveal !== void 0) params.reveal = reveal;
|
|
10
|
+
const res = await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], "open", [params]);
|
|
11
11
|
throwOnRefusal(res, "repository open refused");
|
|
12
12
|
}
|
|
13
13
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends. Nothing enforces the union at runtime — `.code` is\n * whatever string arrived — so treat an unlisted code as possible and `instanceof Error`\n * as the only reliable test.\n *\n * (This note is on the code alias rather than on the interface because the alias is where\n * the codes are documented. Every doclink in this file names the INTERFACE, so a reader\n * following one lands a hop away from this — a wart, not a plan. Stated without a\n * direction on purpose: two earlier revisions of this sentence asserted a positional\n * claim, and both were wrong.) */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n
|
|
1
|
+
{"version":3,"sources":["../src/openRepository.ts"],"sourcesContent":["// Host-mediated \"open this repository in a new tab\" (R3-476).\n//\n// An app frame cannot open a first-party tab itself. A `window.open` from inside the\n// sandboxed frame inherits the sandbox — the opened tab runs at the same opaque origin and\n// cannot load the host — and `target=\"_top\"` would replace the app's own frame rather than\n// open a tab. So the app asks the host, and the host performs the open from its own context.\n//\n// The app names COORDINATES and nothing else. It cannot pass a URL, a route prefix or a\n// path: the host builds the destination from its own route grammar, so this call can only\n// ever reach one of the platform's own repository routes. That is the point of the shape —\n// an app that could spell the destination could open anything.\n//\n// R3-1033: an optional REVEAL rides the open — a closed chrome enum, never a destination.\n// The app still cannot pass a URL, a route prefix or a path; the host decides what the\n// reveal means (which surface of ITS chrome opens) and builds every URL itself. A future\n// panel joins the `RepositoryReveal` union deliberately, never by a free string.\n//\n// Two more conditions hold on the host side, and neither is something this call can assert\n// for itself: the open needs the HOST document's live transient user activation (a real\n// click, which the host samples rather than believes), and one gesture opens exactly one\n// tab. Both surface here as ordinary coded refusals.\nimport { protocolRequest } from './sandboxUtils';\nimport { throwOnRefusal } from './protocolRefusal';\nimport { PROTOCOL_OPENREPO } from './generated/protocol';\nimport { SCHEMES } from './protocolSchemes';\n\n/** Where a repository lives. The same three fields a `RecentProject` carries — this is a\n * location the user may already have navigated to under their own authority. */\nexport interface RepositoryCoordinates {\n provider: string;\n namespace: string;\n repository: string;\n}\n\n/** A chrome reveal that may ride an open (R3-1033) — the host's own surface to open at the\n * destination, never a destination the app names. `'agent'` is the conversations panel;\n * the value set is closed on purpose (see the header). */\nexport interface RepositoryReveal {\n panel: 'agent';\n}\n\n/** The `open` wire params — the coordinates plus the optional reveal. Typed as a named\n * interface (not an inline literal) so the protocol-snapshot extractor resolves the wire\n * shape from the type; see `openRepository` below. */\ninterface OpenRepositoryOpenParams extends RepositoryCoordinates {\n reveal?: RepositoryReveal;\n}\n\n/** Why the host refused to open a tab.\n *\n * - `invalid` — the coordinates are not three clean path segments.\n * - `no-activation` — no live user gesture on the host document. Call this from a click\n * handler; a timer or a boot path will always get this. A SECOND call inside one gesture\n * also lands here: `window.open` consumes the host's transient activation, so one click\n * buys exactly one tab and the next needs a real second click.\n * - `forbidden` — the app does not hold the baseline `route:read` capability.\n * - `unsupported` — this host has no repository-open surface wired.\n * - `unknown` — the host refused without naming a code.\n *\n * **What you actually catch.** The SDK throws a plain `Error` with `.code` assigned — a\n * `CodedRefusalError` from `protocolRefusal.ts` — never a distinct class. These are the\n * `.code` VALUES the host sends. Nothing enforces the union at runtime — `.code` is\n * whatever string arrived — so treat an unlisted code as possible and `instanceof Error`\n * as the only reliable test.\n *\n * (This note is on the code alias rather than on the interface because the alias is where\n * the codes are documented. Every doclink in this file names the INTERFACE, so a reader\n * following one lands a hop away from this — a wart, not a plan. Stated without a\n * direction on purpose: two earlier revisions of this sentence asserted a positional\n * claim, and both were wrong.) */\nexport type OpenRepositoryErrorCode = 'invalid' | 'no-activation' | 'forbidden' | 'unsupported' | 'unknown';\n\nexport interface OpenRepositoryError extends Error {\n code: OpenRepositoryErrorCode;\n}\n\n/** The host's reply: the envelope resolves INSIDE the promise, so a refusal is a resolved\n * `{ ok: false }` rather than a rejection at the transport layer. */\ntype OpenRepositoryReply = { ok: true; url?: string } | { ok: false; code?: string; message?: string };\n\n/**\n * Ask the host to open a repository in a new browser tab.\n *\n * `reveal` (R3-1033) optionally asks the host to open one of its own chrome surfaces at\n * the destination — a closed enum (`RepositoryReveal`), never a destination. Omitted,\n * the open lands exactly as before.\n *\n * Resolves once the host has performed the open; it does not wait for — and cannot observe —\n * the opened tab loading. Rejects with a typed {@link OpenRepositoryError} carrying `code`\n * when the host refuses.\n *\n * Call it directly from a user gesture. The host samples its own transient activation when\n * the request arrives, so anything that defers the call past the gesture (an `await` before\n * it, a `setTimeout`, a retry) will be refused `no-activation`. None of the refusals are\n * worth retrying: each names a condition a retry cannot change.\n */\nexport async function openRepository(coordinates: RepositoryCoordinates, reveal?: RepositoryReveal): Promise<void> {\n const { provider, namespace, repository } = coordinates;\n // The reveal rides the one wire arg when the caller asked for it; a caller omitting it\n // sends no field at all (never `undefined` on the wire — the host validates what arrives).\n // Typed as OpenRepositoryOpenParams (the named interface) so the protocol-snapshot\n // extractor resolves the wire shape from the type — an intersection or a bare Record\n // would read shapeless and the check would flag a reshape that is not one.\n const params: OpenRepositoryOpenParams = { provider, namespace, repository };\n if (reveal !== undefined) params.reveal = reveal;\n const res = (await protocolRequest(SCHEMES[PROTOCOL_OPENREPO], 'open', [params])) as OpenRepositoryReply;\n throwOnRefusal(res, 'repository open refused');\n}\n"],"mappings":";AAqBA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,eAAe;AAwExB,eAAsB,eAAe,aAAoC,QAA0C;AACjH,QAAM,EAAE,UAAU,WAAW,WAAW,IAAI;AAM5C,QAAM,SAAmC,EAAE,UAAU,WAAW,WAAW;AAC3E,MAAI,WAAW,OAAW,QAAO,SAAS;AAC1C,QAAM,MAAO,MAAM,gBAAgB,QAAQ,iBAAiB,GAAG,QAAQ,CAAC,MAAM,CAAC;AAC/E,iBAAe,KAAK,yBAAyB;AAC/C;","names":[]}
|
|
@@ -62,6 +62,21 @@ const ATTENDED = {
|
|
|
62
62
|
reason: "settings verbs reach the same consent and picker surfaces as spaces",
|
|
63
63
|
idleMs: UNATTENDED_TIMEOUT_MS
|
|
64
64
|
},
|
|
65
|
+
// R3-1011 — `recents:list` can raise the R3-786 lazy `recents:read` consent INSIDE the
|
|
66
|
+
// request, through `presentCapabilityConsent` — a presenter site-main's SandboxListener
|
|
67
|
+
// wraps (announcingPresenters, kind 'consent'), so the idle bound is safe to shorten.
|
|
68
|
+
// Until this entry the call was classified unattended: a user who took longer than 30 s
|
|
69
|
+
// to answer the dialog got `timeout` while it was still on screen, and a later Allow
|
|
70
|
+
// replied to a call the SDK had already abandoned.
|
|
71
|
+
recents: {
|
|
72
|
+
reason: "the lazy recents:read consent (R3-786) is drawn inside the request, via presentCapabilityConsent",
|
|
73
|
+
idleMs: UNATTENDED_TIMEOUT_MS
|
|
74
|
+
},
|
|
75
|
+
// R3-1011's table survey found two more HOST schemes that can raise the lazy offer
|
|
76
|
+
// (device:geolocation, diagnostics:read) — but this package emits no
|
|
77
|
+
// protocol-device/protocol-diagnostics call (the wire vocabulary has neither, and
|
|
78
|
+
// diagnostics reads ride the push channel), so an entry here would classify a call
|
|
79
|
+
// nothing makes. It lands with the wrapper that adds one.
|
|
65
80
|
// The contribute flow shows the full diff for approval before anything is written
|
|
66
81
|
// (TRUST_AND_SAFETY TS-19b: the approval MUST show the real diff, so a human reads it).
|
|
67
82
|
// NOT a wrapped presenter — no `idleMs`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocolDeadline.ts"],"sourcesContent":["// Deadlines for host protocol calls (R3-298) — so no platform request can hang forever.\n//\n// THE FAILURE THIS FIXES. `protocolRequest` and `hostFetch` carried no timeout, so a host\n// operation that never resolved presented as an indefinite \"Running…\" with no error, no\n// cancel, and nothing in the console. The GLM dogfood run hit exactly this: the first\n// `chat()` of a session parks on a WebAuthn unseal that never completes, and the surface\n// simply waits. A first-run user inside the setup wizard (R3-299) would be stranded on\n// \"Testing…\" — at the worst possible moment, on the screen whose whole purpose is to prove\n// setup worked.\n//\n// WHY A SINGLE CONSTANT IS THE WRONG ANSWER, AND WHAT IS DONE INSTEAD. A blanket timeout\n// was deferred once as risky, correctly: some host operations legitimately await a HUMAN —\n// a passkey tap, a consent decision, a file picker — and a flat deadline aborts those. So\n// calls are classified, and the two classes get very different bounds:\n//\n// unattended — a network call or a channel round-trip. Nobody is being asked anything, so\n// a reply that has not arrived in tens of seconds is a fault. Short bound.\n// attended — the host may draw chrome and wait for the user. The bound exists only to\n// stop an ABANDONED prompt from pinning the caller forever, so it is set far\n// beyond human reaction time.\n//\n// NOTHING IS UNBOUNDED. \"A long or absent deadline\" was the licence; absent is declined,\n// because absent is the bug. An attended bound of minutes never aborts a person who is\n// actually deciding, and does release a caller whose user walked away — which is the\n// difference between a slow flow and a wedged one.\n//\n// THE IMPRECISION, AND HOW R3-307 REMOVED IT. Attendedness is classified per\n// (scheme, method), but it is really a property of a MOMENT: `spaces:mount` is unattended\n// when the grant is already held and attended on first use, because the host raises consent\n// inside the request (`spaceHandler` `presentMountConsent`). A per-method table cannot see\n// that, so R3-298 classified any method that MAY prompt as `attended` and gave it the long\n// bound — which meant the common grant-held path also waited ten minutes before reporting a\n// fault.\n//\n// R3-307 added the host-attention channel (`hostAttention.ts`), on which the host says\n// whether a person is being asked something RIGHT NOW. So a call now carries TWO bounds:\n//\n// idle — in force while the host is not prompting. A may-prompt call runs on this,\n// which is a real correctness gain: the grant-held `spaces:mount` faults in\n// seconds, as it always should have.\n// ceiling — absolute, from call start, NEVER suspended. An abandoned prompt still\n// releases the caller. The signal may EXTEND a deadline, never remove it.\n//\n// AND THE SHORTENING IS OPT-IN PER ENTRY, which is the part worth not losing. A scheme\n// drops to the short idle bound only when EVERY prompt it can raise is one the host\n// actually announces on that channel (the powerbox, the add-secret modal, the passkey\n// unlock, and the spaceHandler consent surfaces — the presenters site-main wraps). A task\n// app's interaction and the contribute diff-approval are human-paced but are NOT host\n// prompts, so no signal would ever fire for them and they keep the full attended bound. A\n// signal that cannot fire must never be allowed to shorten a deadline.\n\nimport type { HostAttentionKind } from './hostAttention';\n\n/** Whether a call may block on a human being asked something. */\nexport type Attendance = 'unattended' | 'attended';\n\n/** Milliseconds. Exported so callers can reason about the defaults they are overriding. */\nexport const UNATTENDED_TIMEOUT_MS = 30_000;\n/** Network calls reach arbitrary upstreams; the host bounds the fetch itself, so this is a\n * backstop against the host never replying, not a request budget. */\nexport const NETWORK_TIMEOUT_MS = 120_000;\n/** Far beyond human reaction time — this exists only so an ABANDONED prompt releases the\n * caller. It must never be short enough to abort someone who is deciding. */\nexport const ATTENDED_TIMEOUT_MS = 600_000;\n/** A stream's first frame may be behind an unseal, so it gets an attended-scale bound of\n * its own. See `firstFrameTimeoutFor`. */\nexport const ATTENDED_FIRST_FRAME_MS = 300_000;\n/** After the first frame, silence this long means the stream is wedged: the host is no\n * longer producing and no human is being asked. */\nexport const STREAM_IDLE_TIMEOUT_MS = 120_000;\n/** When a call passes this, `onPending` fires so a caller can render a waiting state\n * instead of an unexplained stall. */\nexport const PENDING_NOTICE_MS = 3_000;\n\n/**\n * Methods that may draw host chrome and wait for the user.\n *\n * Each entry is a `scheme:method` or a bare `scheme` (matching every method of it). The\n * REASON is recorded per entry, because this table is the item's actual content — a future\n * reader must be able to see why a method is on the long bound without re-deriving it from\n * the host source.\n */\ninterface AttendedEntry {\n /** Why this call may block on a human. */\n reason: string;\n /**\n * The bound this call runs on while the host reports NOBODY is being asked (R3-307).\n *\n * Set it ONLY when every prompt this entry can raise is one the host announces on the\n * host-attention channel — i.e. a presenter site-main wraps (`hostAttention.ts` in that\n * repo). Omitted ⇒ the call keeps the full attended bound at all times, because a signal\n * that never fires must not be allowed to shorten a deadline.\n */\n idleMs?: number;\n}\n\nconst ATTENDED: Record<string, AttendedEntry> = {\n // The powerbox and the add-secret modal are host-drawn and wait for the user to type or\n // pick; the first use of any stored secret additionally raises a WebAuthn assertion\n // (SECRETS_SPEC §3 — one unlock per session, from a live gesture). All three are wrapped\n // presenters, so the signal covers this scheme completely.\n secrets: {\n reason: 'host-drawn key entry / picker, and the per-session passkey unlock',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // Consent is raised INSIDE the request: presentMountConsent, presentGrantPicker,\n // presentCreateConsent, presentShareDisclosure, presentReferenceConsent — every one of\n // them a wrapped presenter. Unattended once the grant is held, attended on first use, and\n // since R3-307 the host says which of those is happening.\n spaces: {\n reason: 'first-use mount/share/create consent is drawn inside the request',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n settings: {\n reason: 'settings verbs reach the same consent and picker surfaces as spaces',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // The contribute flow shows the full diff for approval before anything is written\n // (TRUST_AND_SAFETY TS-19b: the approval MUST show the real diff, so a human reads it).\n // NOT a wrapped presenter — no `idleMs`.\n contribute: { reason: 'the diff-approval step is a human read of the whole change' },\n // A task is an app bound to a transient slot that the user interacts with; it returns\n // when they finish, which is human-paced by construction. That is an APP's interaction,\n // not a host prompt, so the attention channel never fires for it — no `idleMs`.\n task: { reason: 'a task app runs an interaction and returns when the user finishes' },\n // Launching a target can raise consent for a not-yet-granted app — through the launch\n // flow's own surface, not one of the wrapped presenters. No `idleMs`.\n launch: { reason: 'may raise first-use consent for the launched target' },\n // A drag is a gesture in progress — its duration is the user's hand, and no host prompt\n // is up while it happens. No `idleMs`.\n dnd: { reason: 'a drag is a human gesture in flight' },\n // The chat stream's FIRST frame sits behind the session's first passkey unseal — the\n // exact hang the dogfood run found — and that unseal IS a wrapped presenter. But the idle\n // bound here is the NETWORK one, not the channel one: with no prompt up, this call is\n // waiting on an arbitrary upstream model, and thirty seconds is a normal generation.\n llm: {\n reason: 'the first frame can sit behind the session passkey unseal',\n idleMs: NETWORK_TIMEOUT_MS,\n },\n};\n\n/** Look up a scheme/method in the attended table, preferring the exact method entry. */\nfunction attendedEntry(scheme: string, method: string): AttendedEntry | undefined {\n return ATTENDED[`${scheme}:${method}`] ?? ATTENDED[scheme];\n}\n\n/** Look up a scheme/method in the attended table, preferring the exact method entry. */\nfunction attendedReason(scheme: string, method: string): string | undefined {\n return attendedEntry(scheme, method)?.reason;\n}\n\n/** Whether a call may block on a human. Exported for the classification test + tooling. */\nexport function attendanceOf(scheme: string, method: string): Attendance {\n return attendedReason(scheme, method) ? 'attended' : 'unattended';\n}\n\n/** Why a call is classified attended, or `undefined` when it is not. Exported so the\n * classification is legible from a test failure rather than only from this source. */\nexport function attendanceReason(scheme: string, method: string): string | undefined {\n return attendedReason(scheme, method);\n}\n\n/** The default deadline for a one-shot `protocolRequest`. */\nexport function timeoutFor(scheme: string, method: string): number {\n if (attendanceOf(scheme, method) === 'attended') return ATTENDED_TIMEOUT_MS;\n // `fetch` reaches an arbitrary upstream, so it gets the network bound rather than the\n // channel-round-trip one.\n if (scheme === 'fetch') return NETWORK_TIMEOUT_MS;\n return UNATTENDED_TIMEOUT_MS;\n}\n\n/**\n * The default TIME-TO-FIRST-FRAME bound for a stream.\n *\n * Deliberately not a total-duration bound: a long generation that is streaming normally is\n * healthy, and killing it would be a worse bug than the one being fixed. The hang has a\n * distinct shape — NO frames at all — so that is what is bounded, plus an idle gap between\n * frames once flowing. Together they fire exactly on a wedged stream and never on a slow\n * one.\n */\nexport function firstFrameTimeoutFor(scheme: string, method: string): number {\n return attendanceOf(scheme, method) === 'attended' ? ATTENDED_FIRST_FRAME_MS : NETWORK_TIMEOUT_MS;\n}\n\n/**\n * The two bounds a call runs under (R3-307).\n *\n * `idleMs` is in force while the host reports nobody is being asked; it is cleared while a\n * host prompt is up and restarted, in full, when the prompt goes away. `ceilingMs` runs from\n * call start and is NEVER suspended — it is what releases a caller whose user walked away.\n */\nexport interface CallBounds {\n /** The bound in force while the host is not waiting on a person. */\n idleMs: number;\n /** The absolute bound from call start. Never suspended. */\n ceilingMs: number;\n}\n\n/** Which of a call's two bounds elapsed. `idle` means the host was NOT prompting — nobody\n * was being asked anything, so this is a fault. `ceiling` means the absolute bound ran out,\n * which for an attended call is an abandoned prompt. */\nexport type DeadlineBound = 'idle' | 'ceiling';\n\n/** The bounds for a one-shot `protocolRequest`. */\nexport function boundsFor(scheme: string, method: string): CallBounds {\n const ceilingMs = timeoutFor(scheme, method);\n const idleMs = attendedEntry(scheme, method)?.idleMs;\n // `Math.min` so an `idleMs` can only ever tighten: an entry that named a bound longer than\n // its own ceiling would otherwise silently disable the idle leg.\n return { idleMs: idleMs === undefined ? ceilingMs : Math.min(idleMs, ceilingMs), ceilingMs };\n}\n\n/** The bounds for a stream's time-to-first-frame. */\nexport function firstFrameBoundsFor(scheme: string, method: string): CallBounds {\n const ceilingMs = firstFrameTimeoutFor(scheme, method);\n const idleMs = attendedEntry(scheme, method)?.idleMs;\n return { idleMs: idleMs === undefined ? ceilingMs : Math.min(idleMs, ceilingMs), ceilingMs };\n}\n\n/** A live deadline that the host-attention signal can suspend. */\nexport interface SuspendableDeadline {\n /** Tell the deadline whether the host is waiting on a person right now. */\n setAwaiting(awaiting: boolean): void;\n /** Clear every timer. Idempotent — safe to call from a `finally`. */\n dispose(): void;\n}\n\n/**\n * A deadline with a suspendable idle leg and an unsuspendable ceiling.\n *\n * Pure and injectable (`setTimer`/`clearTimer`) so the suspension rules are unit-testable\n * against a fake clock rather than by waiting minutes for real ones.\n *\n * The idle leg RESTARTS in full when a prompt clears rather than resuming where it left off.\n * That is deliberate: after the user dismisses a prompt the host begins fresh work, and the\n * seconds that elapsed before the prompt say nothing about how long that work should take.\n * The ceiling is what stops a repeatedly-prompting call from running forever.\n */\nexport function createSuspendableDeadline(opts: {\n bounds: CallBounds;\n /** Called once, with the bound that elapsed and its length in ms. */\n onExpire: (bound: DeadlineBound, boundMs: number) => void;\n setTimer?: (fn: () => void, ms: number) => unknown;\n clearTimer?: (handle: unknown) => void;\n}): SuspendableDeadline {\n const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));\n const clearTimer = opts.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>));\n const { idleMs, ceilingMs } = opts.bounds;\n // An idle leg at or above the ceiling can never fire first, so don't arm one — that keeps\n // the common unattended case (idle === ceiling) on exactly one timer, as before R3-307.\n const hasIdleLeg = Number.isFinite(idleMs) && idleMs < ceilingMs;\n\n let done = false;\n let idle: unknown;\n let ceiling: unknown;\n\n const expire = (bound: DeadlineBound, boundMs: number) => {\n if (done) return;\n done = true;\n opts.onExpire(bound, boundMs);\n };\n\n const armIdle = () => {\n if (done || !hasIdleLeg || idle !== undefined) return;\n idle = setTimer(() => {\n idle = undefined;\n expire('idle', idleMs);\n }, idleMs);\n };\n const disarmIdle = () => {\n if (idle !== undefined) {\n clearTimer(idle);\n idle = undefined;\n }\n };\n\n if (Number.isFinite(ceilingMs)) {\n ceiling = setTimer(() => {\n ceiling = undefined;\n expire('ceiling', ceilingMs);\n }, ceilingMs);\n }\n armIdle();\n\n return {\n setAwaiting(awaiting: boolean) {\n if (done) return;\n if (awaiting) disarmIdle();\n else armIdle();\n },\n dispose() {\n done = true;\n disarmIdle();\n if (ceiling !== undefined) {\n clearTimer(ceiling);\n ceiling = undefined;\n }\n },\n };\n}\n\n/** The error a bounded call rejects with. `code` is `'timeout'` — the code R3-303's typed\n * provider-error taxonomy adopts, so apps see one vocabulary. */\nexport class ProtocolTimeoutError extends Error {\n readonly code = 'timeout';\n /** `scheme:method` of the call that timed out. */\n readonly call: string;\n /** The bound that elapsed, in ms. */\n readonly timeoutMs: number;\n /** Whether the call was on the attended or unattended bound — the first thing anyone\n * debugging a timeout needs, and otherwise invisible. */\n readonly attendance: Attendance;\n /** WHICH bound elapsed (R3-307). An attended call that faults on its `idle` bound was not\n * waiting on anyone — the host said so — and that is a genuinely different diagnosis from\n * an abandoned prompt hitting the `ceiling`. */\n readonly bound: DeadlineBound;\n constructor(\n call: string,\n timeoutMs: number,\n attendance: Attendance,\n bound: DeadlineBound = attendance === 'attended' ? 'ceiling' : 'idle',\n ) {\n super(\n attendance === 'attended' && bound === 'ceiling'\n ? `immediately.run: ${call} was abandoned after ${Math.round(timeoutMs / 1000)}s waiting for you`\n : `immediately.run: ${call} did not respond within ${Math.round(timeoutMs / 1000)}s`,\n );\n this.name = 'ProtocolTimeoutError';\n this.call = call;\n this.timeoutMs = timeoutMs;\n this.attendance = attendance;\n this.bound = bound;\n }\n}\n\n/** The error a cancelled call rejects with. */\nexport class ProtocolCancelledError extends Error {\n readonly code = 'cancelled';\n constructor(call: string) {\n super(`immediately.run: ${call} was cancelled`);\n this.name = 'ProtocolCancelledError';\n }\n}\n\n/** What the host is waiting for at this moment, as reported on the host-attention channel\n * (R3-307). Present on a {@link PendingState} only while the host IS prompting. */\nexport interface PendingAttention {\n /** The kind of prompt on screen, or `null` when the host reports a wait it cannot name. */\n kind: HostAttentionKind | null;\n /** `Date.now()` when the wait began, or `null`. */\n since: number | null;\n}\n\n/** What `onPending` is told when a call is taking a while. */\nexport interface PendingState {\n call: string;\n attendance: Attendance;\n elapsedMs: number;\n /** Why this call *may* be waiting on a person — present only when attended. It comes from\n * the classification table, so it is a standing possibility, not a live fact. */\n reason?: string;\n /**\n * What the host is waiting for RIGHT NOW (R3-307) — present only while a host prompt is\n * actually up. Prefer it over {@link reason} when rendering: \"tap your passkey\" is a\n * sentence the user can act on; \"this may need you\" is not.\n */\n awaiting?: PendingAttention;\n}\n\n/** Options accepted by every bounded host call. */\nexport interface BoundedCallOptions {\n /** Override the classified default. `Infinity` disables the bound — an escape hatch for a\n * caller that genuinely owns the wait (it must then provide its own way out).\n *\n * An explicit value is the WHOLE bound: it is never suspended by the host-attention\n * signal, because a caller that named a number owns the wait. */\n timeoutMs?: number;\n /** Abort the wait. The SDK stops waiting and rejects with `code: 'cancelled'`. */\n signal?: AbortSignal;\n /** Fired when the call passes `PENDING_NOTICE_MS`, so a caller can render a waiting state\n * rather than an unexplained pause — and again, after that, whenever the host starts or\n * stops waiting on the user, so the waiting state can name what is on screen now. */\n onPending?: (state: PendingState) => void;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyDO,MAAM,wBAAwB;AAG9B,MAAM,qBAAqB;AAG3B,MAAM,sBAAsB;AAG5B,MAAM,0BAA0B;AAGhC,MAAM,yBAAyB;AAG/B,MAAM,oBAAoB;AAwBjC,MAAM,WAA0C;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9C,SAAS;AAAA,IACP,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,QAAQ;AAAA,IAC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M;AAAA,EAa9C,YACE,MACA,WACA,YACA,QAAuB,eAAe,aAAa,YAAY,QAC/D;AACA;AAAA,MACE,eAAe,cAAc,UAAU,YACnC,oBAAoB,IAAI,wBAAwB,KAAK,MAAM,YAAY,GAAI,CAAC,sBAC5E,oBAAoB,IAAI,2BAA2B,KAAK,MAAM,YAAY,GAAI,CAAC;AAAA,IACrF;AAtBF,SAAS,OAAO;AAuBd,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,YAAY;AACjB,SAAK,aAAa;AAClB,SAAK,QAAQ;AAAA,EACf;AACF;AAGO,MAAM,+BAA+B,MAAM;AAAA,EAEhD,YAAY,MAAc;AACxB,UAAM,oBAAoB,IAAI,gBAAgB;AAFhD,SAAS,OAAO;AAGd,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/protocolDeadline.ts"],"sourcesContent":["// Deadlines for host protocol calls (R3-298) — so no platform request can hang forever.\n//\n// THE FAILURE THIS FIXES. `protocolRequest` and `hostFetch` carried no timeout, so a host\n// operation that never resolved presented as an indefinite \"Running…\" with no error, no\n// cancel, and nothing in the console. The GLM dogfood run hit exactly this: the first\n// `chat()` of a session parks on a WebAuthn unseal that never completes, and the surface\n// simply waits. A first-run user inside the setup wizard (R3-299) would be stranded on\n// \"Testing…\" — at the worst possible moment, on the screen whose whole purpose is to prove\n// setup worked.\n//\n// WHY A SINGLE CONSTANT IS THE WRONG ANSWER, AND WHAT IS DONE INSTEAD. A blanket timeout\n// was deferred once as risky, correctly: some host operations legitimately await a HUMAN —\n// a passkey tap, a consent decision, a file picker — and a flat deadline aborts those. So\n// calls are classified, and the two classes get very different bounds:\n//\n// unattended — a network call or a channel round-trip. Nobody is being asked anything, so\n// a reply that has not arrived in tens of seconds is a fault. Short bound.\n// attended — the host may draw chrome and wait for the user. The bound exists only to\n// stop an ABANDONED prompt from pinning the caller forever, so it is set far\n// beyond human reaction time.\n//\n// NOTHING IS UNBOUNDED. \"A long or absent deadline\" was the licence; absent is declined,\n// because absent is the bug. An attended bound of minutes never aborts a person who is\n// actually deciding, and does release a caller whose user walked away — which is the\n// difference between a slow flow and a wedged one.\n//\n// THE IMPRECISION, AND HOW R3-307 REMOVED IT. Attendedness is classified per\n// (scheme, method), but it is really a property of a MOMENT: `spaces:mount` is unattended\n// when the grant is already held and attended on first use, because the host raises consent\n// inside the request (`spaceHandler` `presentMountConsent`). A per-method table cannot see\n// that, so R3-298 classified any method that MAY prompt as `attended` and gave it the long\n// bound — which meant the common grant-held path also waited ten minutes before reporting a\n// fault.\n//\n// R3-307 added the host-attention channel (`hostAttention.ts`), on which the host says\n// whether a person is being asked something RIGHT NOW. So a call now carries TWO bounds:\n//\n// idle — in force while the host is not prompting. A may-prompt call runs on this,\n// which is a real correctness gain: the grant-held `spaces:mount` faults in\n// seconds, as it always should have.\n// ceiling — absolute, from call start, NEVER suspended. An abandoned prompt still\n// releases the caller. The signal may EXTEND a deadline, never remove it.\n//\n// AND THE SHORTENING IS OPT-IN PER ENTRY, which is the part worth not losing. A scheme\n// drops to the short idle bound only when EVERY prompt it can raise is one the host\n// actually announces on that channel (the powerbox, the add-secret modal, the passkey\n// unlock, and the spaceHandler consent surfaces — the presenters site-main wraps). A task\n// app's interaction and the contribute diff-approval are human-paced but are NOT host\n// prompts, so no signal would ever fire for them and they keep the full attended bound. A\n// signal that cannot fire must never be allowed to shorten a deadline.\n\nimport type { HostAttentionKind } from './hostAttention';\n\n/** Whether a call may block on a human being asked something. */\nexport type Attendance = 'unattended' | 'attended';\n\n/** Milliseconds. Exported so callers can reason about the defaults they are overriding. */\nexport const UNATTENDED_TIMEOUT_MS = 30_000;\n/** Network calls reach arbitrary upstreams; the host bounds the fetch itself, so this is a\n * backstop against the host never replying, not a request budget. */\nexport const NETWORK_TIMEOUT_MS = 120_000;\n/** Far beyond human reaction time — this exists only so an ABANDONED prompt releases the\n * caller. It must never be short enough to abort someone who is deciding. */\nexport const ATTENDED_TIMEOUT_MS = 600_000;\n/** A stream's first frame may be behind an unseal, so it gets an attended-scale bound of\n * its own. See `firstFrameTimeoutFor`. */\nexport const ATTENDED_FIRST_FRAME_MS = 300_000;\n/** After the first frame, silence this long means the stream is wedged: the host is no\n * longer producing and no human is being asked. */\nexport const STREAM_IDLE_TIMEOUT_MS = 120_000;\n/** When a call passes this, `onPending` fires so a caller can render a waiting state\n * instead of an unexplained stall. */\nexport const PENDING_NOTICE_MS = 3_000;\n\n/**\n * Methods that may draw host chrome and wait for the user.\n *\n * Each entry is a `scheme:method` or a bare `scheme` (matching every method of it). The\n * REASON is recorded per entry, because this table is the item's actual content — a future\n * reader must be able to see why a method is on the long bound without re-deriving it from\n * the host source.\n */\ninterface AttendedEntry {\n /** Why this call may block on a human. */\n reason: string;\n /**\n * The bound this call runs on while the host reports NOBODY is being asked (R3-307).\n *\n * Set it ONLY when every prompt this entry can raise is one the host announces on the\n * host-attention channel — i.e. a presenter site-main wraps (`hostAttention.ts` in that\n * repo). Omitted ⇒ the call keeps the full attended bound at all times, because a signal\n * that never fires must not be allowed to shorten a deadline.\n */\n idleMs?: number;\n}\n\nconst ATTENDED: Record<string, AttendedEntry> = {\n // The powerbox and the add-secret modal are host-drawn and wait for the user to type or\n // pick; the first use of any stored secret additionally raises a WebAuthn assertion\n // (SECRETS_SPEC §3 — one unlock per session, from a live gesture). All three are wrapped\n // presenters, so the signal covers this scheme completely.\n secrets: {\n reason: 'host-drawn key entry / picker, and the per-session passkey unlock',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // Consent is raised INSIDE the request: presentMountConsent, presentGrantPicker,\n // presentCreateConsent, presentShareDisclosure, presentReferenceConsent — every one of\n // them a wrapped presenter. Unattended once the grant is held, attended on first use, and\n // since R3-307 the host says which of those is happening.\n spaces: {\n reason: 'first-use mount/share/create consent is drawn inside the request',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n settings: {\n reason: 'settings verbs reach the same consent and picker surfaces as spaces',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // R3-1011 — `recents:list` can raise the R3-786 lazy `recents:read` consent INSIDE the\n // request, through `presentCapabilityConsent` — a presenter site-main's SandboxListener\n // wraps (announcingPresenters, kind 'consent'), so the idle bound is safe to shorten.\n // Until this entry the call was classified unattended: a user who took longer than 30 s\n // to answer the dialog got `timeout` while it was still on screen, and a later Allow\n // replied to a call the SDK had already abandoned.\n recents: {\n reason: 'the lazy recents:read consent (R3-786) is drawn inside the request, via presentCapabilityConsent',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // R3-1011's table survey found two more HOST schemes that can raise the lazy offer\n // (device:geolocation, diagnostics:read) — but this package emits no\n // protocol-device/protocol-diagnostics call (the wire vocabulary has neither, and\n // diagnostics reads ride the push channel), so an entry here would classify a call\n // nothing makes. It lands with the wrapper that adds one.\n // The contribute flow shows the full diff for approval before anything is written\n // (TRUST_AND_SAFETY TS-19b: the approval MUST show the real diff, so a human reads it).\n // NOT a wrapped presenter — no `idleMs`.\n contribute: { reason: 'the diff-approval step is a human read of the whole change' },\n // A task is an app bound to a transient slot that the user interacts with; it returns\n // when they finish, which is human-paced by construction. That is an APP's interaction,\n // not a host prompt, so the attention channel never fires for it — no `idleMs`.\n task: { reason: 'a task app runs an interaction and returns when the user finishes' },\n // Launching a target can raise consent for a not-yet-granted app — through the launch\n // flow's own surface, not one of the wrapped presenters. No `idleMs`.\n launch: { reason: 'may raise first-use consent for the launched target' },\n // A drag is a gesture in progress — its duration is the user's hand, and no host prompt\n // is up while it happens. No `idleMs`.\n dnd: { reason: 'a drag is a human gesture in flight' },\n // The chat stream's FIRST frame sits behind the session's first passkey unseal — the\n // exact hang the dogfood run found — and that unseal IS a wrapped presenter. But the idle\n // bound here is the NETWORK one, not the channel one: with no prompt up, this call is\n // waiting on an arbitrary upstream model, and thirty seconds is a normal generation.\n llm: {\n reason: 'the first frame can sit behind the session passkey unseal',\n idleMs: NETWORK_TIMEOUT_MS,\n },\n};\n\n/** Look up a scheme/method in the attended table, preferring the exact method entry. */\nfunction attendedEntry(scheme: string, method: string): AttendedEntry | undefined {\n return ATTENDED[`${scheme}:${method}`] ?? ATTENDED[scheme];\n}\n\n/** Look up a scheme/method in the attended table, preferring the exact method entry. */\nfunction attendedReason(scheme: string, method: string): string | undefined {\n return attendedEntry(scheme, method)?.reason;\n}\n\n/** Whether a call may block on a human. Exported for the classification test + tooling. */\nexport function attendanceOf(scheme: string, method: string): Attendance {\n return attendedReason(scheme, method) ? 'attended' : 'unattended';\n}\n\n/** Why a call is classified attended, or `undefined` when it is not. Exported so the\n * classification is legible from a test failure rather than only from this source. */\nexport function attendanceReason(scheme: string, method: string): string | undefined {\n return attendedReason(scheme, method);\n}\n\n/** The default deadline for a one-shot `protocolRequest`. */\nexport function timeoutFor(scheme: string, method: string): number {\n if (attendanceOf(scheme, method) === 'attended') return ATTENDED_TIMEOUT_MS;\n // `fetch` reaches an arbitrary upstream, so it gets the network bound rather than the\n // channel-round-trip one.\n if (scheme === 'fetch') return NETWORK_TIMEOUT_MS;\n return UNATTENDED_TIMEOUT_MS;\n}\n\n/**\n * The default TIME-TO-FIRST-FRAME bound for a stream.\n *\n * Deliberately not a total-duration bound: a long generation that is streaming normally is\n * healthy, and killing it would be a worse bug than the one being fixed. The hang has a\n * distinct shape — NO frames at all — so that is what is bounded, plus an idle gap between\n * frames once flowing. Together they fire exactly on a wedged stream and never on a slow\n * one.\n */\nexport function firstFrameTimeoutFor(scheme: string, method: string): number {\n return attendanceOf(scheme, method) === 'attended' ? ATTENDED_FIRST_FRAME_MS : NETWORK_TIMEOUT_MS;\n}\n\n/**\n * The two bounds a call runs under (R3-307).\n *\n * `idleMs` is in force while the host reports nobody is being asked; it is cleared while a\n * host prompt is up and restarted, in full, when the prompt goes away. `ceilingMs` runs from\n * call start and is NEVER suspended — it is what releases a caller whose user walked away.\n */\nexport interface CallBounds {\n /** The bound in force while the host is not waiting on a person. */\n idleMs: number;\n /** The absolute bound from call start. Never suspended. */\n ceilingMs: number;\n}\n\n/** Which of a call's two bounds elapsed. `idle` means the host was NOT prompting — nobody\n * was being asked anything, so this is a fault. `ceiling` means the absolute bound ran out,\n * which for an attended call is an abandoned prompt. */\nexport type DeadlineBound = 'idle' | 'ceiling';\n\n/** The bounds for a one-shot `protocolRequest`. */\nexport function boundsFor(scheme: string, method: string): CallBounds {\n const ceilingMs = timeoutFor(scheme, method);\n const idleMs = attendedEntry(scheme, method)?.idleMs;\n // `Math.min` so an `idleMs` can only ever tighten: an entry that named a bound longer than\n // its own ceiling would otherwise silently disable the idle leg.\n return { idleMs: idleMs === undefined ? ceilingMs : Math.min(idleMs, ceilingMs), ceilingMs };\n}\n\n/** The bounds for a stream's time-to-first-frame. */\nexport function firstFrameBoundsFor(scheme: string, method: string): CallBounds {\n const ceilingMs = firstFrameTimeoutFor(scheme, method);\n const idleMs = attendedEntry(scheme, method)?.idleMs;\n return { idleMs: idleMs === undefined ? ceilingMs : Math.min(idleMs, ceilingMs), ceilingMs };\n}\n\n/** A live deadline that the host-attention signal can suspend. */\nexport interface SuspendableDeadline {\n /** Tell the deadline whether the host is waiting on a person right now. */\n setAwaiting(awaiting: boolean): void;\n /** Clear every timer. Idempotent — safe to call from a `finally`. */\n dispose(): void;\n}\n\n/**\n * A deadline with a suspendable idle leg and an unsuspendable ceiling.\n *\n * Pure and injectable (`setTimer`/`clearTimer`) so the suspension rules are unit-testable\n * against a fake clock rather than by waiting minutes for real ones.\n *\n * The idle leg RESTARTS in full when a prompt clears rather than resuming where it left off.\n * That is deliberate: after the user dismisses a prompt the host begins fresh work, and the\n * seconds that elapsed before the prompt say nothing about how long that work should take.\n * The ceiling is what stops a repeatedly-prompting call from running forever.\n */\nexport function createSuspendableDeadline(opts: {\n bounds: CallBounds;\n /** Called once, with the bound that elapsed and its length in ms. */\n onExpire: (bound: DeadlineBound, boundMs: number) => void;\n setTimer?: (fn: () => void, ms: number) => unknown;\n clearTimer?: (handle: unknown) => void;\n}): SuspendableDeadline {\n const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));\n const clearTimer = opts.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>));\n const { idleMs, ceilingMs } = opts.bounds;\n // An idle leg at or above the ceiling can never fire first, so don't arm one — that keeps\n // the common unattended case (idle === ceiling) on exactly one timer, as before R3-307.\n const hasIdleLeg = Number.isFinite(idleMs) && idleMs < ceilingMs;\n\n let done = false;\n let idle: unknown;\n let ceiling: unknown;\n\n const expire = (bound: DeadlineBound, boundMs: number) => {\n if (done) return;\n done = true;\n opts.onExpire(bound, boundMs);\n };\n\n const armIdle = () => {\n if (done || !hasIdleLeg || idle !== undefined) return;\n idle = setTimer(() => {\n idle = undefined;\n expire('idle', idleMs);\n }, idleMs);\n };\n const disarmIdle = () => {\n if (idle !== undefined) {\n clearTimer(idle);\n idle = undefined;\n }\n };\n\n if (Number.isFinite(ceilingMs)) {\n ceiling = setTimer(() => {\n ceiling = undefined;\n expire('ceiling', ceilingMs);\n }, ceilingMs);\n }\n armIdle();\n\n return {\n setAwaiting(awaiting: boolean) {\n if (done) return;\n if (awaiting) disarmIdle();\n else armIdle();\n },\n dispose() {\n done = true;\n disarmIdle();\n if (ceiling !== undefined) {\n clearTimer(ceiling);\n ceiling = undefined;\n }\n },\n };\n}\n\n/** The error a bounded call rejects with. `code` is `'timeout'` — the code R3-303's typed\n * provider-error taxonomy adopts, so apps see one vocabulary. */\nexport class ProtocolTimeoutError extends Error {\n readonly code = 'timeout';\n /** `scheme:method` of the call that timed out. */\n readonly call: string;\n /** The bound that elapsed, in ms. */\n readonly timeoutMs: number;\n /** Whether the call was on the attended or unattended bound — the first thing anyone\n * debugging a timeout needs, and otherwise invisible. */\n readonly attendance: Attendance;\n /** WHICH bound elapsed (R3-307). An attended call that faults on its `idle` bound was not\n * waiting on anyone — the host said so — and that is a genuinely different diagnosis from\n * an abandoned prompt hitting the `ceiling`. */\n readonly bound: DeadlineBound;\n constructor(\n call: string,\n timeoutMs: number,\n attendance: Attendance,\n bound: DeadlineBound = attendance === 'attended' ? 'ceiling' : 'idle',\n ) {\n super(\n attendance === 'attended' && bound === 'ceiling'\n ? `immediately.run: ${call} was abandoned after ${Math.round(timeoutMs / 1000)}s waiting for you`\n : `immediately.run: ${call} did not respond within ${Math.round(timeoutMs / 1000)}s`,\n );\n this.name = 'ProtocolTimeoutError';\n this.call = call;\n this.timeoutMs = timeoutMs;\n this.attendance = attendance;\n this.bound = bound;\n }\n}\n\n/** The error a cancelled call rejects with. */\nexport class ProtocolCancelledError extends Error {\n readonly code = 'cancelled';\n constructor(call: string) {\n super(`immediately.run: ${call} was cancelled`);\n this.name = 'ProtocolCancelledError';\n }\n}\n\n/** What the host is waiting for at this moment, as reported on the host-attention channel\n * (R3-307). Present on a {@link PendingState} only while the host IS prompting. */\nexport interface PendingAttention {\n /** The kind of prompt on screen, or `null` when the host reports a wait it cannot name. */\n kind: HostAttentionKind | null;\n /** `Date.now()` when the wait began, or `null`. */\n since: number | null;\n}\n\n/** What `onPending` is told when a call is taking a while. */\nexport interface PendingState {\n call: string;\n attendance: Attendance;\n elapsedMs: number;\n /** Why this call *may* be waiting on a person — present only when attended. It comes from\n * the classification table, so it is a standing possibility, not a live fact. */\n reason?: string;\n /**\n * What the host is waiting for RIGHT NOW (R3-307) — present only while a host prompt is\n * actually up. Prefer it over {@link reason} when rendering: \"tap your passkey\" is a\n * sentence the user can act on; \"this may need you\" is not.\n */\n awaiting?: PendingAttention;\n}\n\n/** Options accepted by every bounded host call. */\nexport interface BoundedCallOptions {\n /** Override the classified default. `Infinity` disables the bound — an escape hatch for a\n * caller that genuinely owns the wait (it must then provide its own way out).\n *\n * An explicit value is the WHOLE bound: it is never suspended by the host-attention\n * signal, because a caller that named a number owns the wait. */\n timeoutMs?: number;\n /** Abort the wait. The SDK stops waiting and rejects with `code: 'cancelled'`. */\n signal?: AbortSignal;\n /** Fired when the call passes `PENDING_NOTICE_MS`, so a caller can render a waiting state\n * rather than an unexplained pause — and again, after that, whenever the host starts or\n * stops wa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AAc,SAAS,OAAW;AAC/C,WAAO,SAAS,MAAM;AACpB,aAAO;AACP,aAAO,QAAQ,MAAM;AAAA,IACvB,GAAG,MAAM;AAAA,EACX;AACA,QAAM,aAAa,MAAM;AACvB,QAAI,SAAS,QAAW;AACtB,iBAAW,IAAI;AACf,aAAO;AAAA,IACT;AAAA,EACF;AAEA,MAAI,OAAO,SAAS,SAAS,GAAG;AAC9B,cAAU,SAAS,MAAM;AACvB,gBAAU;AACV,aAAO,WAAW,SAAS;AAAA,IAC7B,GAAG,SAAS;AAAA,EACd;AACA,UAAQ;AAER,SAAO;AAAA,IACL,YAAY,UAAmB;AAC7B,UAAI,KAAM;AACV,UAAI,SAAU,YAAW;AAAA,UACpB,SAAQ;AAAA,IACf;AAAA,IACA,UAAU;AACR,aAAO;AACP,iBAAW;AACX,UAAI,YAAY,QAAW;AACzB,mBAAW,OAAO;AAClB,kBAAU;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AAIO,MAAM,6BAA6B,MAAM;AAAA,EAa9C,YACE,MACA,WACA,YACA,QAAuB,eAAe,aAAa,YAAY,QAC/D;AACA;AAAA,MACE,eAAe,cAAc,UAAU,YACnC,oBAAoB,IAAI,wBAAwB,KAAK,MAAM,YAAY,GAAI,CAAC,sBAC5E,oBAAoB,IAAI,2BAA2B,KAAK,MAAM,YAAY,GAAI,CAAC;AAAA,IACrF;AAtBF,SAAS,OAAO;AAuBd,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,YAAY;AACjB,SAAK,aAAa;AAClB,SAAK,QAAQ;AAAA,EACf;AACF;AAGO,MAAM,+BAA+B,MAAM;AAAA,EAEhD,YAAY,MAAc;AACxB,UAAM,oBAAoB,IAAI,gBAAgB;AAFhD,SAAS,OAAO;AAGd,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
|
package/dist/protocolDeadline.js
CHANGED
|
@@ -26,6 +26,21 @@ const ATTENDED = {
|
|
|
26
26
|
reason: "settings verbs reach the same consent and picker surfaces as spaces",
|
|
27
27
|
idleMs: UNATTENDED_TIMEOUT_MS
|
|
28
28
|
},
|
|
29
|
+
// R3-1011 — `recents:list` can raise the R3-786 lazy `recents:read` consent INSIDE the
|
|
30
|
+
// request, through `presentCapabilityConsent` — a presenter site-main's SandboxListener
|
|
31
|
+
// wraps (announcingPresenters, kind 'consent'), so the idle bound is safe to shorten.
|
|
32
|
+
// Until this entry the call was classified unattended: a user who took longer than 30 s
|
|
33
|
+
// to answer the dialog got `timeout` while it was still on screen, and a later Allow
|
|
34
|
+
// replied to a call the SDK had already abandoned.
|
|
35
|
+
recents: {
|
|
36
|
+
reason: "the lazy recents:read consent (R3-786) is drawn inside the request, via presentCapabilityConsent",
|
|
37
|
+
idleMs: UNATTENDED_TIMEOUT_MS
|
|
38
|
+
},
|
|
39
|
+
// R3-1011's table survey found two more HOST schemes that can raise the lazy offer
|
|
40
|
+
// (device:geolocation, diagnostics:read) — but this package emits no
|
|
41
|
+
// protocol-device/protocol-diagnostics call (the wire vocabulary has neither, and
|
|
42
|
+
// diagnostics reads ride the push channel), so an entry here would classify a call
|
|
43
|
+
// nothing makes. It lands with the wrapper that adds one.
|
|
29
44
|
// The contribute flow shows the full diff for approval before anything is written
|
|
30
45
|
// (TRUST_AND_SAFETY TS-19b: the approval MUST show the real diff, so a human reads it).
|
|
31
46
|
// NOT a wrapped presenter — no `idleMs`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocolDeadline.ts"],"sourcesContent":["// Deadlines for host protocol calls (R3-298) — so no platform request can hang forever.\n//\n// THE FAILURE THIS FIXES. `protocolRequest` and `hostFetch` carried no timeout, so a host\n// operation that never resolved presented as an indefinite \"Running…\" with no error, no\n// cancel, and nothing in the console. The GLM dogfood run hit exactly this: the first\n// `chat()` of a session parks on a WebAuthn unseal that never completes, and the surface\n// simply waits. A first-run user inside the setup wizard (R3-299) would be stranded on\n// \"Testing…\" — at the worst possible moment, on the screen whose whole purpose is to prove\n// setup worked.\n//\n// WHY A SINGLE CONSTANT IS THE WRONG ANSWER, AND WHAT IS DONE INSTEAD. A blanket timeout\n// was deferred once as risky, correctly: some host operations legitimately await a HUMAN —\n// a passkey tap, a consent decision, a file picker — and a flat deadline aborts those. So\n// calls are classified, and the two classes get very different bounds:\n//\n// unattended — a network call or a channel round-trip. Nobody is being asked anything, so\n// a reply that has not arrived in tens of seconds is a fault. Short bound.\n// attended — the host may draw chrome and wait for the user. The bound exists only to\n// stop an ABANDONED prompt from pinning the caller forever, so it is set far\n// beyond human reaction time.\n//\n// NOTHING IS UNBOUNDED. \"A long or absent deadline\" was the licence; absent is declined,\n// because absent is the bug. An attended bound of minutes never aborts a person who is\n// actually deciding, and does release a caller whose user walked away — which is the\n// difference between a slow flow and a wedged one.\n//\n// THE IMPRECISION, AND HOW R3-307 REMOVED IT. Attendedness is classified per\n// (scheme, method), but it is really a property of a MOMENT: `spaces:mount` is unattended\n// when the grant is already held and attended on first use, because the host raises consent\n// inside the request (`spaceHandler` `presentMountConsent`). A per-method table cannot see\n// that, so R3-298 classified any method that MAY prompt as `attended` and gave it the long\n// bound — which meant the common grant-held path also waited ten minutes before reporting a\n// fault.\n//\n// R3-307 added the host-attention channel (`hostAttention.ts`), on which the host says\n// whether a person is being asked something RIGHT NOW. So a call now carries TWO bounds:\n//\n// idle — in force while the host is not prompting. A may-prompt call runs on this,\n// which is a real correctness gain: the grant-held `spaces:mount` faults in\n// seconds, as it always should have.\n// ceiling — absolute, from call start, NEVER suspended. An abandoned prompt still\n// releases the caller. The signal may EXTEND a deadline, never remove it.\n//\n// AND THE SHORTENING IS OPT-IN PER ENTRY, which is the part worth not losing. A scheme\n// drops to the short idle bound only when EVERY prompt it can raise is one the host\n// actually announces on that channel (the powerbox, the add-secret modal, the passkey\n// unlock, and the spaceHandler consent surfaces — the presenters site-main wraps). A task\n// app's interaction and the contribute diff-approval are human-paced but are NOT host\n// prompts, so no signal would ever fire for them and they keep the full attended bound. A\n// signal that cannot fire must never be allowed to shorten a deadline.\n\nimport type { HostAttentionKind } from './hostAttention';\n\n/** Whether a call may block on a human being asked something. */\nexport type Attendance = 'unattended' | 'attended';\n\n/** Milliseconds. Exported so callers can reason about the defaults they are overriding. */\nexport const UNATTENDED_TIMEOUT_MS = 30_000;\n/** Network calls reach arbitrary upstreams; the host bounds the fetch itself, so this is a\n * backstop against the host never replying, not a request budget. */\nexport const NETWORK_TIMEOUT_MS = 120_000;\n/** Far beyond human reaction time — this exists only so an ABANDONED prompt releases the\n * caller. It must never be short enough to abort someone who is deciding. */\nexport const ATTENDED_TIMEOUT_MS = 600_000;\n/** A stream's first frame may be behind an unseal, so it gets an attended-scale bound of\n * its own. See `firstFrameTimeoutFor`. */\nexport const ATTENDED_FIRST_FRAME_MS = 300_000;\n/** After the first frame, silence this long means the stream is wedged: the host is no\n * longer producing and no human is being asked. */\nexport const STREAM_IDLE_TIMEOUT_MS = 120_000;\n/** When a call passes this, `onPending` fires so a caller can render a waiting state\n * instead of an unexplained stall. */\nexport const PENDING_NOTICE_MS = 3_000;\n\n/**\n * Methods that may draw host chrome and wait for the user.\n *\n * Each entry is a `scheme:method` or a bare `scheme` (matching every method of it). The\n * REASON is recorded per entry, because this table is the item's actual content — a future\n * reader must be able to see why a method is on the long bound without re-deriving it from\n * the host source.\n */\ninterface AttendedEntry {\n /** Why this call may block on a human. */\n reason: string;\n /**\n * The bound this call runs on while the host reports NOBODY is being asked (R3-307).\n *\n * Set it ONLY when every prompt this entry can raise is one the host announces on the\n * host-attention channel — i.e. a presenter site-main wraps (`hostAttention.ts` in that\n * repo). Omitted ⇒ the call keeps the full attended bound at all times, because a signal\n * that never fires must not be allowed to shorten a deadline.\n */\n idleMs?: number;\n}\n\nconst ATTENDED: Record<string, AttendedEntry> = {\n // The powerbox and the add-secret modal are host-drawn and wait for the user to type or\n // pick; the first use of any stored secret additionally raises a WebAuthn assertion\n // (SECRETS_SPEC §3 — one unlock per session, from a live gesture). All three are wrapped\n // presenters, so the signal covers this scheme completely.\n secrets: {\n reason: 'host-drawn key entry / picker, and the per-session passkey unlock',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // Consent is raised INSIDE the request: presentMountConsent, presentGrantPicker,\n // presentCreateConsent, presentShareDisclosure, presentReferenceConsent — every one of\n // them a wrapped presenter. Unattended once the grant is held, attended on first use, and\n // since R3-307 the host says which of those is happening.\n spaces: {\n reason: 'first-use mount/share/create consent is drawn inside the request',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n settings: {\n reason: 'settings verbs reach the same consent and picker surfaces as spaces',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // The contribute flow shows the full diff for approval before anything is written\n // (TRUST_AND_SAFETY TS-19b: the approval MUST show the real diff, so a human reads it).\n // NOT a wrapped presenter — no `idleMs`.\n contribute: { reason: 'the diff-approval step is a human read of the whole change' },\n // A task is an app bound to a transient slot that the user interacts with; it returns\n // when they finish, which is human-paced by construction. That is an APP's interaction,\n // not a host prompt, so the attention channel never fires for it — no `idleMs`.\n task: { reason: 'a task app runs an interaction and returns when the user finishes' },\n // Launching a target can raise consent for a not-yet-granted app — through the launch\n // flow's own surface, not one of the wrapped presenters. No `idleMs`.\n launch: { reason: 'may raise first-use consent for the launched target' },\n // A drag is a gesture in progress — its duration is the user's hand, and no host prompt\n // is up while it happens. No `idleMs`.\n dnd: { reason: 'a drag is a human gesture in flight' },\n // The chat stream's FIRST frame sits behind the session's first passkey unseal — the\n // exact hang the dogfood run found — and that unseal IS a wrapped presenter. But the idle\n // bound here is the NETWORK one, not the channel one: with no prompt up, this call is\n // waiting on an arbitrary upstream model, and thirty seconds is a normal generation.\n llm: {\n reason: 'the first frame can sit behind the session passkey unseal',\n idleMs: NETWORK_TIMEOUT_MS,\n },\n};\n\n/** Look up a scheme/method in the attended table, preferring the exact method entry. */\nfunction attendedEntry(scheme: string, method: string): AttendedEntry | undefined {\n return ATTENDED[`${scheme}:${method}`] ?? ATTENDED[scheme];\n}\n\n/** Look up a scheme/method in the attended table, preferring the exact method entry. */\nfunction attendedReason(scheme: string, method: string): string | undefined {\n return attendedEntry(scheme, method)?.reason;\n}\n\n/** Whether a call may block on a human. Exported for the classification test + tooling. */\nexport function attendanceOf(scheme: string, method: string): Attendance {\n return attendedReason(scheme, method) ? 'attended' : 'unattended';\n}\n\n/** Why a call is classified attended, or `undefined` when it is not. Exported so the\n * classification is legible from a test failure rather than only from this source. */\nexport function attendanceReason(scheme: string, method: string): string | undefined {\n return attendedReason(scheme, method);\n}\n\n/** The default deadline for a one-shot `protocolRequest`. */\nexport function timeoutFor(scheme: string, method: string): number {\n if (attendanceOf(scheme, method) === 'attended') return ATTENDED_TIMEOUT_MS;\n // `fetch` reaches an arbitrary upstream, so it gets the network bound rather than the\n // channel-round-trip one.\n if (scheme === 'fetch') return NETWORK_TIMEOUT_MS;\n return UNATTENDED_TIMEOUT_MS;\n}\n\n/**\n * The default TIME-TO-FIRST-FRAME bound for a stream.\n *\n * Deliberately not a total-duration bound: a long generation that is streaming normally is\n * healthy, and killing it would be a worse bug than the one being fixed. The hang has a\n * distinct shape — NO frames at all — so that is what is bounded, plus an idle gap between\n * frames once flowing. Together they fire exactly on a wedged stream and never on a slow\n * one.\n */\nexport function firstFrameTimeoutFor(scheme: string, method: string): number {\n return attendanceOf(scheme, method) === 'attended' ? ATTENDED_FIRST_FRAME_MS : NETWORK_TIMEOUT_MS;\n}\n\n/**\n * The two bounds a call runs under (R3-307).\n *\n * `idleMs` is in force while the host reports nobody is being asked; it is cleared while a\n * host prompt is up and restarted, in full, when the prompt goes away. `ceilingMs` runs from\n * call start and is NEVER suspended — it is what releases a caller whose user walked away.\n */\nexport interface CallBounds {\n /** The bound in force while the host is not waiting on a person. */\n idleMs: number;\n /** The absolute bound from call start. Never suspended. */\n ceilingMs: number;\n}\n\n/** Which of a call's two bounds elapsed. `idle` means the host was NOT prompting — nobody\n * was being asked anything, so this is a fault. `ceiling` means the absolute bound ran out,\n * which for an attended call is an abandoned prompt. */\nexport type DeadlineBound = 'idle' | 'ceiling';\n\n/** The bounds for a one-shot `protocolRequest`. */\nexport function boundsFor(scheme: string, method: string): CallBounds {\n const ceilingMs = timeoutFor(scheme, method);\n const idleMs = attendedEntry(scheme, method)?.idleMs;\n // `Math.min` so an `idleMs` can only ever tighten: an entry that named a bound longer than\n // its own ceiling would otherwise silently disable the idle leg.\n return { idleMs: idleMs === undefined ? ceilingMs : Math.min(idleMs, ceilingMs), ceilingMs };\n}\n\n/** The bounds for a stream's time-to-first-frame. */\nexport function firstFrameBoundsFor(scheme: string, method: string): CallBounds {\n const ceilingMs = firstFrameTimeoutFor(scheme, method);\n const idleMs = attendedEntry(scheme, method)?.idleMs;\n return { idleMs: idleMs === undefined ? ceilingMs : Math.min(idleMs, ceilingMs), ceilingMs };\n}\n\n/** A live deadline that the host-attention signal can suspend. */\nexport interface SuspendableDeadline {\n /** Tell the deadline whether the host is waiting on a person right now. */\n setAwaiting(awaiting: boolean): void;\n /** Clear every timer. Idempotent — safe to call from a `finally`. */\n dispose(): void;\n}\n\n/**\n * A deadline with a suspendable idle leg and an unsuspendable ceiling.\n *\n * Pure and injectable (`setTimer`/`clearTimer`) so the suspension rules are unit-testable\n * against a fake clock rather than by waiting minutes for real ones.\n *\n * The idle leg RESTARTS in full when a prompt clears rather than resuming where it left off.\n * That is deliberate: after the user dismisses a prompt the host begins fresh work, and the\n * seconds that elapsed before the prompt say nothing about how long that work should take.\n * The ceiling is what stops a repeatedly-prompting call from running forever.\n */\nexport function createSuspendableDeadline(opts: {\n bounds: CallBounds;\n /** Called once, with the bound that elapsed and its length in ms. */\n onExpire: (bound: DeadlineBound, boundMs: number) => void;\n setTimer?: (fn: () => void, ms: number) => unknown;\n clearTimer?: (handle: unknown) => void;\n}): SuspendableDeadline {\n const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));\n const clearTimer = opts.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>));\n const { idleMs, ceilingMs } = opts.bounds;\n // An idle leg at or above the ceiling can never fire first, so don't arm one — that keeps\n // the common unattended case (idle === ceiling) on exactly one timer, as before R3-307.\n const hasIdleLeg = Number.isFinite(idleMs) && idleMs < ceilingMs;\n\n let done = false;\n let idle: unknown;\n let ceiling: unknown;\n\n const expire = (bound: DeadlineBound, boundMs: number) => {\n if (done) return;\n done = true;\n opts.onExpire(bound, boundMs);\n };\n\n const armIdle = () => {\n if (done || !hasIdleLeg || idle !== undefined) return;\n idle = setTimer(() => {\n idle = undefined;\n expire('idle', idleMs);\n }, idleMs);\n };\n const disarmIdle = () => {\n if (idle !== undefined) {\n clearTimer(idle);\n idle = undefined;\n }\n };\n\n if (Number.isFinite(ceilingMs)) {\n ceiling = setTimer(() => {\n ceiling = undefined;\n expire('ceiling', ceilingMs);\n }, ceilingMs);\n }\n armIdle();\n\n return {\n setAwaiting(awaiting: boolean) {\n if (done) return;\n if (awaiting) disarmIdle();\n else armIdle();\n },\n dispose() {\n done = true;\n disarmIdle();\n if (ceiling !== undefined) {\n clearTimer(ceiling);\n ceiling = undefined;\n }\n },\n };\n}\n\n/** The error a bounded call rejects with. `code` is `'timeout'` — the code R3-303's typed\n * provider-error taxonomy adopts, so apps see one vocabulary. */\nexport class ProtocolTimeoutError extends Error {\n readonly code = 'timeout';\n /** `scheme:method` of the call that timed out. */\n readonly call: string;\n /** The bound that elapsed, in ms. */\n readonly timeoutMs: number;\n /** Whether the call was on the attended or unattended bound — the first thing anyone\n * debugging a timeout needs, and otherwise invisible. */\n readonly attendance: Attendance;\n /** WHICH bound elapsed (R3-307). An attended call that faults on its `idle` bound was not\n * waiting on anyone — the host said so — and that is a genuinely different diagnosis from\n * an abandoned prompt hitting the `ceiling`. */\n readonly bound: DeadlineBound;\n constructor(\n call: string,\n timeoutMs: number,\n attendance: Attendance,\n bound: DeadlineBound = attendance === 'attended' ? 'ceiling' : 'idle',\n ) {\n super(\n attendance === 'attended' && bound === 'ceiling'\n ? `immediately.run: ${call} was abandoned after ${Math.round(timeoutMs / 1000)}s waiting for you`\n : `immediately.run: ${call} did not respond within ${Math.round(timeoutMs / 1000)}s`,\n );\n this.name = 'ProtocolTimeoutError';\n this.call = call;\n this.timeoutMs = timeoutMs;\n this.attendance = attendance;\n this.bound = bound;\n }\n}\n\n/** The error a cancelled call rejects with. */\nexport class ProtocolCancelledError extends Error {\n readonly code = 'cancelled';\n constructor(call: string) {\n super(`immediately.run: ${call} was cancelled`);\n this.name = 'ProtocolCancelledError';\n }\n}\n\n/** What the host is waiting for at this moment, as reported on the host-attention channel\n * (R3-307). Present on a {@link PendingState} only while the host IS prompting. */\nexport interface PendingAttention {\n /** The kind of prompt on screen, or `null` when the host reports a wait it cannot name. */\n kind: HostAttentionKind | null;\n /** `Date.now()` when the wait began, or `null`. */\n since: number | null;\n}\n\n/** What `onPending` is told when a call is taking a while. */\nexport interface PendingState {\n call: string;\n attendance: Attendance;\n elapsedMs: number;\n /** Why this call *may* be waiting on a person — present only when attended. It comes from\n * the classification table, so it is a standing possibility, not a live fact. */\n reason?: string;\n /**\n * What the host is waiting for RIGHT NOW (R3-307) — present only while a host prompt is\n * actually up. Prefer it over {@link reason} when rendering: \"tap your passkey\" is a\n * sentence the user can act on; \"this may need you\" is not.\n */\n awaiting?: PendingAttention;\n}\n\n/** Options accepted by every bounded host call. */\nexport interface BoundedCallOptions {\n /** Override the classified default. `Infinity` disables the bound — an escape hatch for a\n * caller that genuinely owns the wait (it must then provide its own way out).\n *\n * An explicit value is the WHOLE bound: it is never suspended by the host-attention\n * signal, because a caller that named a number owns the wait. */\n timeoutMs?: number;\n /** Abort the wait. The SDK stops waiting and rejects with `code: 'cancelled'`. */\n signal?: AbortSignal;\n /** Fired when the call passes `PENDING_NOTICE_MS`, so a caller can render a waiting state\n * rather than an unexplained pause — and again, after that, whenever the host starts or\n * stops waiting on the user, so the waiting state can name what is on screen now. */\n onPending?: (state: PendingState) => void;\n}\n"],"mappings":";AAyDO,MAAM,wBAAwB;AAG9B,MAAM,qBAAqB;AAG3B,MAAM,sBAA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B;AAC7B,UAAI,KAAM;AACV,UAAI,SAAU,YAAW;AAAA,UACpB,SAAQ;AAAA,IACf;AAAA,IACA,UAAU;AACR,aAAO;AACP,iBAAW;AACX,UAAI,YAAY,QAAW;AACzB,mBAAW,OAAO;AAClB,kBAAU;AAAA,MACZ;AAAA,IACF;AAAA,EACF;AACF;AAIO,MAAM,6BAA6B,MAAM;AAAA,EAa9C,YACE,MACA,WACA,YACA,QAAuB,eAAe,aAAa,YAAY,QAC/D;AACA;AAAA,MACE,eAAe,cAAc,UAAU,YACnC,oBAAoB,IAAI,wBAAwB,KAAK,MAAM,YAAY,GAAI,CAAC,sBAC5E,oBAAoB,IAAI,2BAA2B,KAAK,MAAM,YAAY,GAAI,CAAC;AAAA,IACrF;AAtBF,SAAS,OAAO;AAuBd,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,YAAY;AACjB,SAAK,aAAa;AAClB,SAAK,QAAQ;AAAA,EACf;AACF;AAGO,MAAM,+BAA+B,MAAM;AAAA,EAEhD,YAAY,MAAc;AACxB,UAAM,oBAAoB,IAAI,gBAAgB;AAFhD,SAAS,OAAO;AAGd,SAAK,OAAO;AAAA,EACd;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/protocolDeadline.ts"],"sourcesContent":["// Deadlines for host protocol calls (R3-298) — so no platform request can hang forever.\n//\n// THE FAILURE THIS FIXES. `protocolRequest` and `hostFetch` carried no timeout, so a host\n// operation that never resolved presented as an indefinite \"Running…\" with no error, no\n// cancel, and nothing in the console. The GLM dogfood run hit exactly this: the first\n// `chat()` of a session parks on a WebAuthn unseal that never completes, and the surface\n// simply waits. A first-run user inside the setup wizard (R3-299) would be stranded on\n// \"Testing…\" — at the worst possible moment, on the screen whose whole purpose is to prove\n// setup worked.\n//\n// WHY A SINGLE CONSTANT IS THE WRONG ANSWER, AND WHAT IS DONE INSTEAD. A blanket timeout\n// was deferred once as risky, correctly: some host operations legitimately await a HUMAN —\n// a passkey tap, a consent decision, a file picker — and a flat deadline aborts those. So\n// calls are classified, and the two classes get very different bounds:\n//\n// unattended — a network call or a channel round-trip. Nobody is being asked anything, so\n// a reply that has not arrived in tens of seconds is a fault. Short bound.\n// attended — the host may draw chrome and wait for the user. The bound exists only to\n// stop an ABANDONED prompt from pinning the caller forever, so it is set far\n// beyond human reaction time.\n//\n// NOTHING IS UNBOUNDED. \"A long or absent deadline\" was the licence; absent is declined,\n// because absent is the bug. An attended bound of minutes never aborts a person who is\n// actually deciding, and does release a caller whose user walked away — which is the\n// difference between a slow flow and a wedged one.\n//\n// THE IMPRECISION, AND HOW R3-307 REMOVED IT. Attendedness is classified per\n// (scheme, method), but it is really a property of a MOMENT: `spaces:mount` is unattended\n// when the grant is already held and attended on first use, because the host raises consent\n// inside the request (`spaceHandler` `presentMountConsent`). A per-method table cannot see\n// that, so R3-298 classified any method that MAY prompt as `attended` and gave it the long\n// bound — which meant the common grant-held path also waited ten minutes before reporting a\n// fault.\n//\n// R3-307 added the host-attention channel (`hostAttention.ts`), on which the host says\n// whether a person is being asked something RIGHT NOW. So a call now carries TWO bounds:\n//\n// idle — in force while the host is not prompting. A may-prompt call runs on this,\n// which is a real correctness gain: the grant-held `spaces:mount` faults in\n// seconds, as it always should have.\n// ceiling — absolute, from call start, NEVER suspended. An abandoned prompt still\n// releases the caller. The signal may EXTEND a deadline, never remove it.\n//\n// AND THE SHORTENING IS OPT-IN PER ENTRY, which is the part worth not losing. A scheme\n// drops to the short idle bound only when EVERY prompt it can raise is one the host\n// actually announces on that channel (the powerbox, the add-secret modal, the passkey\n// unlock, and the spaceHandler consent surfaces — the presenters site-main wraps). A task\n// app's interaction and the contribute diff-approval are human-paced but are NOT host\n// prompts, so no signal would ever fire for them and they keep the full attended bound. A\n// signal that cannot fire must never be allowed to shorten a deadline.\n\nimport type { HostAttentionKind } from './hostAttention';\n\n/** Whether a call may block on a human being asked something. */\nexport type Attendance = 'unattended' | 'attended';\n\n/** Milliseconds. Exported so callers can reason about the defaults they are overriding. */\nexport const UNATTENDED_TIMEOUT_MS = 30_000;\n/** Network calls reach arbitrary upstreams; the host bounds the fetch itself, so this is a\n * backstop against the host never replying, not a request budget. */\nexport const NETWORK_TIMEOUT_MS = 120_000;\n/** Far beyond human reaction time — this exists only so an ABANDONED prompt releases the\n * caller. It must never be short enough to abort someone who is deciding. */\nexport const ATTENDED_TIMEOUT_MS = 600_000;\n/** A stream's first frame may be behind an unseal, so it gets an attended-scale bound of\n * its own. See `firstFrameTimeoutFor`. */\nexport const ATTENDED_FIRST_FRAME_MS = 300_000;\n/** After the first frame, silence this long means the stream is wedged: the host is no\n * longer producing and no human is being asked. */\nexport const STREAM_IDLE_TIMEOUT_MS = 120_000;\n/** When a call passes this, `onPending` fires so a caller can render a waiting state\n * instead of an unexplained stall. */\nexport const PENDING_NOTICE_MS = 3_000;\n\n/**\n * Methods that may draw host chrome and wait for the user.\n *\n * Each entry is a `scheme:method` or a bare `scheme` (matching every method of it). The\n * REASON is recorded per entry, because this table is the item's actual content — a future\n * reader must be able to see why a method is on the long bound without re-deriving it from\n * the host source.\n */\ninterface AttendedEntry {\n /** Why this call may block on a human. */\n reason: string;\n /**\n * The bound this call runs on while the host reports NOBODY is being asked (R3-307).\n *\n * Set it ONLY when every prompt this entry can raise is one the host announces on the\n * host-attention channel — i.e. a presenter site-main wraps (`hostAttention.ts` in that\n * repo). Omitted ⇒ the call keeps the full attended bound at all times, because a signal\n * that never fires must not be allowed to shorten a deadline.\n */\n idleMs?: number;\n}\n\nconst ATTENDED: Record<string, AttendedEntry> = {\n // The powerbox and the add-secret modal are host-drawn and wait for the user to type or\n // pick; the first use of any stored secret additionally raises a WebAuthn assertion\n // (SECRETS_SPEC §3 — one unlock per session, from a live gesture). All three are wrapped\n // presenters, so the signal covers this scheme completely.\n secrets: {\n reason: 'host-drawn key entry / picker, and the per-session passkey unlock',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // Consent is raised INSIDE the request: presentMountConsent, presentGrantPicker,\n // presentCreateConsent, presentShareDisclosure, presentReferenceConsent — every one of\n // them a wrapped presenter. Unattended once the grant is held, attended on first use, and\n // since R3-307 the host says which of those is happening.\n spaces: {\n reason: 'first-use mount/share/create consent is drawn inside the request',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n settings: {\n reason: 'settings verbs reach the same consent and picker surfaces as spaces',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // R3-1011 — `recents:list` can raise the R3-786 lazy `recents:read` consent INSIDE the\n // request, through `presentCapabilityConsent` — a presenter site-main's SandboxListener\n // wraps (announcingPresenters, kind 'consent'), so the idle bound is safe to shorten.\n // Until this entry the call was classified unattended: a user who took longer than 30 s\n // to answer the dialog got `timeout` while it was still on screen, and a later Allow\n // replied to a call the SDK had already abandoned.\n recents: {\n reason: 'the lazy recents:read consent (R3-786) is drawn inside the request, via presentCapabilityConsent',\n idleMs: UNATTENDED_TIMEOUT_MS,\n },\n // R3-1011's table survey found two more HOST schemes that can raise the lazy offer\n // (device:geolocation, diagnostics:read) — but this package emits no\n // protocol-device/protocol-diagnostics call (the wire vocabulary has neither, and\n // diagnostics reads ride the push channel), so an entry here would classify a call\n // nothing makes. It lands with the wrapper that adds one.\n // The contribute flow shows the full diff for approval before anything is written\n // (TRUST_AND_SAFETY TS-19b: the approval MUST show the real diff, so a human reads it).\n // NOT a wrapped presenter — no `idleMs`.\n contribute: { reason: 'the diff-approval step is a human read of the whole change' },\n // A task is an app bound to a transient slot that the user interacts with; it returns\n // when they finish, which is human-paced by construction. That is an APP's interaction,\n // not a host prompt, so the attention channel never fires for it — no `idleMs`.\n task: { reason: 'a task app runs an interaction and returns when the user finishes' },\n // Launching a target can raise consent for a not-yet-granted app — through the launch\n // flow's own surface, not one of the wrapped presenters. No `idleMs`.\n launch: { reason: 'may raise first-use consent for the launched target' },\n // A drag is a gesture in progress — its duration is the user's hand, and no host prompt\n // is up while it happens. No `idleMs`.\n dnd: { reason: 'a drag is a human gesture in flight' },\n // The chat stream's FIRST frame sits behind the session's first passkey unseal — the\n // exact hang the dogfood run found — and that unseal IS a wrapped presenter. But the idle\n // bound here is the NETWORK one, not the channel one: with no prompt up, this call is\n // waiting on an arbitrary upstream model, and thirty seconds is a normal generation.\n llm: {\n reason: 'the first frame can sit behind the session passkey unseal',\n idleMs: NETWORK_TIMEOUT_MS,\n },\n};\n\n/** Look up a scheme/method in the attended table, preferring the exact method entry. */\nfunction attendedEntry(scheme: string, method: string): AttendedEntry | undefined {\n return ATTENDED[`${scheme}:${method}`] ?? ATTENDED[scheme];\n}\n\n/** Look up a scheme/method in the attended table, preferring the exact method entry. */\nfunction attendedReason(scheme: string, method: string): string | undefined {\n return attendedEntry(scheme, method)?.reason;\n}\n\n/** Whether a call may block on a human. Exported for the classification test + tooling. */\nexport function attendanceOf(scheme: string, method: string): Attendance {\n return attendedReason(scheme, method) ? 'attended' : 'unattended';\n}\n\n/** Why a call is classified attended, or `undefined` when it is not. Exported so the\n * classification is legible from a test failure rather than only from this source. */\nexport function attendanceReason(scheme: string, method: string): string | undefined {\n return attendedReason(scheme, method);\n}\n\n/** The default deadline for a one-shot `protocolRequest`. */\nexport function timeoutFor(scheme: string, method: string): number {\n if (attendanceOf(scheme, method) === 'attended') return ATTENDED_TIMEOUT_MS;\n // `fetch` reaches an arbitrary upstream, so it gets the network bound rather than the\n // channel-round-trip one.\n if (scheme === 'fetch') return NETWORK_TIMEOUT_MS;\n return UNATTENDED_TIMEOUT_MS;\n}\n\n/**\n * The default TIME-TO-FIRST-FRAME bound for a stream.\n *\n * Deliberately not a total-duration bound: a long generation that is streaming normally is\n * healthy, and killing it would be a worse bug than the one being fixed. The hang has a\n * distinct shape — NO frames at all — so that is what is bounded, plus an idle gap between\n * frames once flowing. Together they fire exactly on a wedged stream and never on a slow\n * one.\n */\nexport function firstFrameTimeoutFor(scheme: string, method: string): number {\n return attendanceOf(scheme, method) === 'attended' ? ATTENDED_FIRST_FRAME_MS : NETWORK_TIMEOUT_MS;\n}\n\n/**\n * The two bounds a call runs under (R3-307).\n *\n * `idleMs` is in force while the host reports nobody is being asked; it is cleared while a\n * host prompt is up and restarted, in full, when the prompt goes away. `ceilingMs` runs from\n * call start and is NEVER suspended — it is what releases a caller whose user walked away.\n */\nexport interface CallBounds {\n /** The bound in force while the host is not waiting on a person. */\n idleMs: number;\n /** The absolute bound from call start. Never suspended. */\n ceilingMs: number;\n}\n\n/** Which of a call's two bounds elapsed. `idle` means the host was NOT prompting — nobody\n * was being asked anything, so this is a fault. `ceiling` means the absolute bound ran out,\n * which for an attended call is an abandoned prompt. */\nexport type DeadlineBound = 'idle' | 'ceiling';\n\n/** The bounds for a one-shot `protocolRequest`. */\nexport function boundsFor(scheme: string, method: string): CallBounds {\n const ceilingMs = timeoutFor(scheme, method);\n const idleMs = attendedEntry(scheme, method)?.idleMs;\n // `Math.min` so an `idleMs` can only ever tighten: an entry that named a bound longer than\n // its own ceiling would otherwise silently disable the idle leg.\n return { idleMs: idleMs === undefined ? ceilingMs : Math.min(idleMs, ceilingMs), ceilingMs };\n}\n\n/** The bounds for a stream's time-to-first-frame. */\nexport function firstFrameBoundsFor(scheme: string, method: string): CallBounds {\n const ceilingMs = firstFrameTimeoutFor(scheme, method);\n const idleMs = attendedEntry(scheme, method)?.idleMs;\n return { idleMs: idleMs === undefined ? ceilingMs : Math.min(idleMs, ceilingMs), ceilingMs };\n}\n\n/** A live deadline that the host-attention signal can suspend. */\nexport interface SuspendableDeadline {\n /** Tell the deadline whether the host is waiting on a person right now. */\n setAwaiting(awaiting: boolean): void;\n /** Clear every timer. Idempotent — safe to call from a `finally`. */\n dispose(): void;\n}\n\n/**\n * A deadline with a suspendable idle leg and an unsuspendable ceiling.\n *\n * Pure and injectable (`setTimer`/`clearTimer`) so the suspension rules are unit-testable\n * against a fake clock rather than by waiting minutes for real ones.\n *\n * The idle leg RESTARTS in full when a prompt clears rather than resuming where it left off.\n * That is deliberate: after the user dismisses a prompt the host begins fresh work, and the\n * seconds that elapsed before the prompt say nothing about how long that work should take.\n * The ceiling is what stops a repeatedly-prompting call from running forever.\n */\nexport function createSuspendableDeadline(opts: {\n bounds: CallBounds;\n /** Called once, with the bound that elapsed and its length in ms. */\n onExpire: (bound: DeadlineBound, boundMs: number) => void;\n setTimer?: (fn: () => void, ms: number) => unknown;\n clearTimer?: (handle: unknown) => void;\n}): SuspendableDeadline {\n const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));\n const clearTimer = opts.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>));\n const { idleMs, ceilingMs } = opts.bounds;\n // An idle leg at or above the ceiling can never fire first, so don't arm one — that keeps\n // the common unattended case (idle === ceiling) on exactly one timer, as before R3-307.\n const hasIdleLeg = Number.isFinite(idleMs) && idleMs < ceilingMs;\n\n let done = false;\n let idle: unknown;\n let ceiling: unknown;\n\n const expire = (bound: DeadlineBound, boundMs: number) => {\n if (done) return;\n done = true;\n opts.onExpire(bound, boundMs);\n };\n\n const armIdle = () => {\n if (done || !hasIdleLeg || idle !== undefined) return;\n idle = setTimer(() => {\n idle = undefined;\n expire('idle', idleMs);\n }, idleMs);\n };\n const disarmIdle = () => {\n if (idle !== undefined) {\n clearTimer(idle);\n idle = undefined;\n }\n };\n\n if (Number.isFinite(ceilingMs)) {\n ceiling = setTimer(() => {\n ceiling = undefined;\n expire('ceiling', ceilingMs);\n }, ceilingMs);\n }\n armIdle();\n\n return {\n setAwaiting(awaiting: boolean) {\n if (done) return;\n if (awaiting) disarmIdle();\n else armIdle();\n },\n dispose() {\n done = true;\n disarmIdle();\n if (ceiling !== undefined) {\n clearTimer(ceiling);\n ceiling = undefined;\n }\n },\n };\n}\n\n/** The error a bounded call rejects with. `code` is `'timeout'` — the code R3-303's typed\n * provider-error taxonomy adopts, so apps see one vocabulary. */\nexport class ProtocolTimeoutError extends Error {\n readonly code = 'timeout';\n /** `scheme:method` of the call that timed out. */\n readonly call: string;\n /** The bound that elapsed, in ms. */\n readonly timeoutMs: number;\n /** Whether the call was on the attended or unattended bound — the first thing anyone\n * debugging a timeout needs, and otherwise invisible. */\n readonly attendance: Attendance;\n /** WHICH bound elapsed (R3-307). An attended call that faults on its `idle` bound was not\n * waiting on anyone — the host said so — and that is a genuinely different diagnosis from\n * an abandoned prompt hitting the `ceiling`. */\n readonly bound: DeadlineBound;\n constructor(\n call: string,\n timeoutMs: number,\n attendance: Attendance,\n bound: DeadlineBound = attendance === 'attended' ? 'ceiling' : 'idle',\n ) {\n super(\n attendance === 'attended' && bound === 'ceiling'\n ? `immediately.run: ${call} was abandoned after ${Math.round(timeoutMs / 1000)}s waiting for you`\n : `immediately.run: ${call} did not respond within ${Math.round(timeoutMs / 1000)}s`,\n );\n this.name = 'ProtocolTimeoutError';\n this.call = call;\n this.timeoutMs = timeoutMs;\n this.attendance = attendance;\n this.bound = bound;\n }\n}\n\n/** The error a cancelled call rejects with. */\nexport class ProtocolCancelledError extends Error {\n readonly code = 'cancelled';\n constructor(call: string) {\n super(`immediately.run: ${call} was cancelled`);\n this.name = 'ProtocolCancelledError';\n }\n}\n\n/** What the host is waiting for at this moment, as reported on the host-attention channel\n * (R3-307). Present on a {@link PendingState} only while the host IS prompting. */\nexport interface PendingAttention {\n /** The kind of prompt on screen, or `null` when the host reports a wait it cannot name. */\n kind: HostAttentionKind | null;\n /** `Date.now()` when the wait began, or `null`. */\n since: number | null;\n}\n\n/** What `onPending` is told when a call is taking a while. */\nexport interface PendingState {\n call: string;\n attendance: Attendance;\n elapsedMs: number;\n /** Why this call *may* be waiting on a person — present only when attended. It comes from\n * the classification table, so it is a standing possibility, not a live fact. */\n reason?: string;\n /**\n * What the host is waiting for RIGHT NOW (R3-307) — present only while a host prompt is\n * actually up. Prefer it over {@link reason} when rendering: \"tap your passkey\" is a\n * sentence the user can act on; \"this may need you\" is not.\n */\n awaiting?: PendingAttention;\n}\n\n/** Options accepted by every bounded host call. */\nexport interface BoundedCallOptions {\n /** Override the classified default. `Infinity` disables the bound — an escape hatch for a\n * caller that genuinely owns the wait (it must then provide its own way out).\n *\n * An explicit value is the WHOLE bound: it is never suspended by the host-attention\n * signal, because a caller that named a number owns the wait. */\n timeoutMs?: number;\n /** Abort the wait. The SDK stops waiting and rejects with `code: 'cancelled'`. */\n signal?: AbortSignal;\n /** Fired when the call passes `PENDING_NOTICE_MS`, so a caller can render a waiting state\n * rather than an unexplained pause — and again, after that, whenever the host starts or\n * stops waiting on the user, so the waiting state can name what is on screen now. */\n onPending?: (state: PendingState) => void;\n}\n"],"mappings":";AAyDO,MAAM,wBAAwB;AAG9B,MAAM,qBAAqB;AAG3B,MAAM,sBAAsB;AAG5B,MAAM,0BAA0B;AAGhC,MAAM,yBAAyB;AAG/B,MAAM,oBAAoB;AAwBjC,MAAM,WAA0C;AAAA;AAAA;AAAA;AAAA;AAAA,EAK9C,SAAS;AAAA,IACP,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AAAA,EACA,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,SAAS;AAAA,IACP,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,YAAY,EAAE,QAAQ,6DAA6D;AAAA;AAAA;AAAA;AAAA,EAInF,MAAM,EAAE,QAAQ,oEAAoE;AAAA;AAAA;AAAA,EAGpF,QAAQ,EAAE,QAAQ,sDAAsD;AAAA;AAAA;AAAA,EAGxE,KAAK,EAAE,QAAQ,sCAAsC;AAAA;AAAA;AAAA;AAAA;AAAA,EAKrD,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV;AACF;AAGA,SAAS,cAAc,QAAgB,QAA2C;AAChF,SAAO,SAAS,GAAG,MAAM,IAAI,MAAM,EAAE,KAAK,SAAS,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
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. The count is:\n//\n// **seventeen CALL SITES across twelve FILES** — `grep -n 'throwOnRefusal(' src/*.ts`,\n// minus the declaration here and minus `*.test.*`:\n//\n// dnd.ts · editor.ts · feed.ts · ipc.ts (×2) · mounts.ts (×3) · netFetch.ts ·\n// openExternal.ts · openRepository.ts · secrets.ts · spacesMode.ts · theme.ts (×3) ·\n// vcs.ts\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// Not folded, deliberately, and the reason is NOT that they are all unalike — that was the\n// previous excuse and it was false for three of them:\n//\n// · `catalog.ts`, `recents.ts`, `tasks.ts` are pure copies of the shape `ipc.ts` had\n// until R3-780 folded it — untyped `Error & { code?: string }`, `res?.code ??\n// 'unknown'`. (`recents.ts` casts `code` as required rather than optional; immaterial,\n// the cast erases.) They are foldable and nothing here argues otherwise;\n// · `feed.ts`, `netFetch.ts` and `theme.ts` (×3) read `res && 'code' in res`, which\n// THREW `TypeError: Cannot use 'in' operator` on a string reply — FOLDED in R3-817\n// (0.74.3), a behaviour change reviewed as its own item, exactly as this bullet\n// prescribed;\n// · `launch.ts` folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// So the remaining work is two items, not one, and they are not the same size.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL SEVENTEEN SITES\n// ---------------------------------------------------------------------------\n//\n// Measured: changing the guard to `r.ok !== false` compiles clean and leaves **ten of the\n// seventeen SITES** green — seven of the twelve files: `dnd`, `editor`, `ipc`, `mounts`,\n// `secrets`, `spacesMode` and `vcs`. Every one of them stubs an explicit `{ ok: false }`,\n// so they pin \"throws on a refusal envelope\" and nothing about a malformed or absent\n// reply. The catchers: `openExternal`, `openRepository`, the five R3-817 sites (whose\n// string-reply tests reject on a non-envelope — the mutation never throws), plus\n// `protocolRefusal.test.ts`. (Re-run 2026-09-30 on the post-fold tree: suites red —\n// feed, netFetch, theme, openExternal, openRepository, protocolRefusal; the seven\n// families green.)\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and seventeen near-duplicate malformed\n// -reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Seventeen sites call this;\n * **sixteen** had an inline copy it replaced (`spacesMode.ts` was written against the\n * helper in R3-708 and replaced nothing). All sixteen tested for PRESENCE, in **three**\n * shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **seven** used the `in` operator — `openExternal`, `openRepository` (with the cast;\n * folded in R3-708) and `feed`, `netFetch`, `theme` ×3 (without it; folded in R3-817,\n * the TypeError fix disclosed above);\n * - **two** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc.ts`.\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply.\n *\n * ONE revision of this paragraph got that backwards, and this is the fourth attempt to\n * describe it accurately. The original text was right FOR ITS REFERENT — it named\n * `'code' in res` as a shape replaced, without saying which sites, and at the time the\n * sites it referred to were R3-708's four, two of which used that form. R3-780 then folded\n * five DIFFERENT files and inherited the sentence unchanged, so it became false in place\n * without anyone editing it. That silent shift is the likeliest reason the next revision\n * \"corrected\" it to say NO replaced site used it — which is false the other way:\n * `openExternal` and `openRepository` did.\n *\n * The mechanism is worth more than the correction, because it is repeatable. `'code' in\n * res` is **gone from `main`** since R3-817 (0.74.3) folded the last five — a reviewer who\n * greps `main` finds nothing, and this paragraph is the record of where it lived and why\n * it misread twice before. What a grep of `main` cannot show is that the\n * form was ALSO at two sites R3-708 folded. The tree that answers the question is the one\n * before the fold, `d4b07cc1^`. Read that before rewriting this paragraph again.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n *\n * R3-817 (0.74.3): the five remaining inline copies (`feed.ts`, `netFetch.ts`,\n * `theme.ts` ×3) folded onto this — removing a latent defect with them: their\n * `res && 'code' in res` guard threw `TypeError: Cannot use 'in' operator` on a\n * bare-STRING reply (a proxy error page, a relay), escaping past every `err.code`\n * branch an app wrote. This function reads `typeof r?.code === 'string'` and\n * cannot throw on any input; the TypeError path no longer exists.\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgLO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/protocolRefusal.ts"],"sourcesContent":["// The one place the SDK turns a host reply envelope into a typed, coded rejection (R6).\n//\n// ---------------------------------------------------------------------------\n// THE CENSUS — miscounted four times. COUNT THE GREP, and say which unit.\n// ---------------------------------------------------------------------------\n//\n// R3-708's review said three copies, then five, then \"ten across eight files\". This file\n// then said ten while the list beneath it summed to twelve, and a fourth reviewer caught\n// that. The count is:\n//\n// **eighteen CALL SITES across thirteen FILES** — `grep -n 'throwOnRefusal(' src/*.ts`,\n// minus the declaration here and minus `*.test.*`:\n//\n// dnd.ts · editor.ts · feed.ts · ipc.ts (×2) · mounts.ts (×3) · netFetch.ts ·\n// openBundle.ts · openExternal.ts · openRepository.ts · secrets.ts · spacesMode.ts · theme.ts (×3) ·\n// vcs.ts\n//\n// Every miscount came from the same two mistakes: reading files instead of counting the\n// grep, and never saying which unit was being counted. `mounts.ts` has three separate\n// request helpers, each with its own copy; R3-780 touched five FILES and seven SITES.\n// \"Ten\" was neither.\n//\n// Not folded, deliberately, and the reason is NOT that they are all unalike — that was the\n// previous excuse and it was false for three of them:\n//\n// · `catalog.ts`, `recents.ts`, `tasks.ts` are pure copies of the shape `ipc.ts` had\n// until R3-780 folded it — untyped `Error & { code?: string }`, `res?.code ??\n// 'unknown'`. (`recents.ts` casts `code` as required rather than optional; immaterial,\n// the cast erases.) They are foldable and nothing here argues otherwise;\n// · `feed.ts`, `netFetch.ts` and `theme.ts` (×3) read `res && 'code' in res`, which\n// THREW `TypeError: Cannot use 'in' operator` on a string reply — FOLDED in R3-817\n// (0.74.3), a behaviour change reviewed as its own item, exactly as this bullet\n// prescribed;\n// · `launch.ts` folds `!res.data?.launchId` into the same condition and RETURNS\n// `{ ok: false, code }` instead of throwing. Different control flow entirely.\n//\n// So the remaining work is two items, not one, and they are not the same size.\n//\n// `check:clones` cannot help with any of this: minLines 6, minTokens 50, and no identifier\n// normalisation, so blocks differing only in type names read as distinct.\n//\n// ---------------------------------------------------------------------------\n// THIS FILE'S OWN TEST IS LOAD-BEARING FOR ALL EIGHTEEN SITES\n// ---------------------------------------------------------------------------\n//\n// Measured: changing the guard to `r.ok !== false` compiles clean and leaves **ten of the\n// eighteen SITES** green — seven of the thirteen files: `dnd`, `editor`, `ipc`, `mounts`,\n// `secrets`, `spacesMode` and `vcs`. Every one of them stubs an explicit `{ ok: false }`,\n// so they pin \"throws on a refusal envelope\" and nothing about a malformed or absent\n// reply. The catchers: `openBundle`, `openExternal`, `openRepository`, the five R3-817 sites (whose\n// string-reply tests reject on a non-envelope — the mutation never throws), plus\n// `protocolRefusal.test.ts`. (Re-run 2026-09-30 on the post-fold tree: suites red —\n// feed, netFetch, theme, openExternal, openRepository, protocolRefusal; the seven\n// families green. `openBundle`, the eighteenth site, was added 2026-10-05 and re-run alone\n// under the same mutation: red.)\n//\n// (An earlier version of this paragraph said \"nine of the twelve sites' suites\", which\n// mixes sites with suites — the exact mistake the census block above is headed about —\n// and omitted `secrets` and `spacesMode` from the green list.)\n//\n// Each inline form this replaced carried its own `!res ||` guard, visible at the call site.\n// That guarantee now lives here alone. Do not weaken `protocolRefusal.test.ts` on the\n// grounds that \"the consumers cover it\" — they do not, and eighteen near-duplicate malformed\n// -reply tests would be the duplication this extraction exists to remove.\n//\n// ---------------------------------------------------------------------------\n// WHICH `ok` THIS READS, AND WHY IT MATTERS\n// ---------------------------------------------------------------------------\n//\n// It reads the DISPATCHER ENVELOPE's `ok` — the host's answer to \"did this call\n// succeed\", not a handler's own return value. site-main declares that envelope\n// (`src/editor/requestDispatcher.ts`):\n//\n// type SpaceResult =\n// | { ok: true; data: unknown }\n// | { ok: false; code: string; message: string };\n//\n// and the sandbox resolves it to the SDK unmodified (`src/protocol/iframe.ts`,\n// `resolve(msg.result)`). So a refusal reaches us as `{ok:false, code, message}` — which\n// is exactly what this function unwraps — and the host produces that frame by THROWING\n// `spaceError(code, message)`. The dispatcher's `.catch` turns the throw into the frame.\n//\n// **A handler that RETURNS `{ok:false, code}` instead of throwing does not produce a\n// refusal.** The dispatcher wraps a return value as `result: {ok: true, data: <return>}`,\n// so the envelope says the call succeeded and the refusal is buried one level down, where\n// nothing looks. Two shipped handlers did this until R3-778 closed it (site-main; audited sdk#184 round 2, 2026-09-25; fixed 2026-09-28 — both now throw, and a dispatcher assertion reddens on the shape):\n//\n// `handleOpenRepository` returns `invalid`, `no-activation`\n// `handleOpenLink` returns `invalid`, `no-activation`, **`declined`**\n//\n// `declined` is the user pressing \"no\" on the host's confirmation dialog, and\n// `openExternal()` reported that to the app as a successful open, until R3-778 closed it. Driven against the built\n// SDK with each reply shape:\n//\n// thrown -> threw, code=no-activation\n// returned -> RESOLVED (the app believes the tab opened)\n//\n// That was a live defect in site-main's handlers until R3-778 closed it (2026-09-28), not here — the envelope is the contract\n// and this reads the contract. Filed as R3-778. It is written down here because this is\n// the file a host author will be pointed at when they ask what shape to reply with, and\n// the answer is: **throw `spaceError`; never return `{ok:false}`.**\n//\n// Deliberately NOT done: sniffing `res.data?.ok === false` as a second refusal shape. On a\n// SUCCESS, `data` is whatever the handler returned — so a handler whose legitimate payload\n// happens to carry `ok: false` would be turned into a refusal. It would bless the broken\n// shape and create a second contract where the spec names one.\n\n/** An error carrying a stable, host-supplied `code` the app can branch on. */\nexport interface CodedRefusalError<C extends string = string> extends Error {\n code: C;\n}\n\n/**\n * Throw a typed, coded error unless the host's reply envelope says the call succeeded.\n *\n * `fallbackMessage` is used when the host refused without a message, and `'unknown'` is\n * the code when it refused without one — a refusal is never reported as a success just\n * because it arrived under-specified.\n *\n * `code` and `message` must be STRINGS to be used. Eighteen sites call this;\n * **sixteen** had an inline copy it replaced (`spacesMode.ts` was written against the\n * helper in R3-708 and replaced nothing). All sixteen tested for PRESENCE, in **three**\n * shapes:\n *\n * - **seven** cast the value: `(res?.code as SomeError['code']) ?? 'unknown'` —\n * `dnd`, `editor`, `vcs`, `mounts` (×3), `secrets`;\n * - **seven** used the `in` operator — `openExternal`, `openRepository` (with the cast;\n * folded in R3-708) and `feed`, `netFetch`, `theme` ×3 (without it; folded in R3-817,\n * the TypeError fix disclosed above);\n * - **two** used a bare `res?.code ?? 'unknown'` onto `Error & { code?: string }` —\n * `ipc.ts`.\n *\n * Every one of them let a host sending `code: 42` surface `err.code === 42` on a field\n * declared `string`, and turned `message: 42` into the string `\"42\"`. Both now fall back,\n * to `'unknown'` and `fallbackMessage`. A deliberate tightening, pinned by\n * `protocolRefusal.test.ts` — and since this package ships no changelog, this paragraph is\n * where a consumer learns of it.\n *\n * The `ipc.ts` pair changed one more thing: their anonymous type declared `code` OPTIONAL\n * and `CodedRefusalError` requires it. No runtime difference for a missing code — the old\n * code assigned `'unknown'` exactly when the new one does (a non-string `code` falls back\n * too, as the paragraph above discloses) — but a consumer narrowing on `'code' in err`\n * can stop.\n *\n * Folding the two `in`-operator sites also removed a latent `TypeError`: `'code' in res`\n * throws on a string reply.\n *\n * ONE revision of this paragraph got that backwards, and this is the fourth attempt to\n * describe it accurately. The original text was right FOR ITS REFERENT — it named\n * `'code' in res` as a shape replaced, without saying which sites, and at the time the\n * sites it referred to were R3-708's four, two of which used that form. R3-780 then folded\n * five DIFFERENT files and inherited the sentence unchanged, so it became false in place\n * without anyone editing it. That silent shift is the likeliest reason the next revision\n * \"corrected\" it to say NO replaced site used it — which is false the other way:\n * `openExternal` and `openRepository` did.\n *\n * The mechanism is worth more than the correction, because it is repeatable. `'code' in\n * res` is **gone from `main`** since R3-817 (0.74.3) folded the last five — a reviewer who\n * greps `main` finds nothing, and this paragraph is the record of where it lived and why\n * it misread twice before. What a grep of `main` cannot show is that the\n * form was ALSO at two sites R3-708 folded. The tree that answers the question is the one\n * before the fold, `d4b07cc1^`. Read that before rewriting this paragraph again.\n *\n * It is an ASSERTION function, not a `void` one, because the inline form it replaced\n * narrowed `res` as a side effect of its `if`/`throw`: `secrets.ts` and `mounts.ts` read\n * `res.data` on the next line and stopped compiling without it. A caller that only needs\n * the throw can ignore the narrowing; one that reads the payload gets it for free. (TS\n * requires the call target to be an explicitly-typed declared name — this is why it is a\n * `function` declaration and not an arrow const.)\n *\n * R3-817 (0.74.3): the five remaining inline copies (`feed.ts`, `netFetch.ts`,\n * `theme.ts` ×3) folded onto this — removing a latent defect with them: their\n * `res && 'code' in res` guard threw `TypeError: Cannot use 'in' operator` on a\n * bare-STRING reply (a proxy error page, a relay), escaping past every `err.code`\n * branch an app wrote. This function reads `typeof r?.code === 'string'` and\n * cannot throw on any input; the TypeError path no longer exists.\n */\nexport function throwOnRefusal(res: unknown, fallbackMessage: string): asserts res is { ok: true; data?: unknown } {\n const r = res as { ok?: unknown; code?: unknown; message?: unknown } | null | undefined;\n if (r && r.ok === true) return;\n const err = new Error(typeof r?.message === 'string' ? r.message : fallbackMessage) as CodedRefusalError;\n err.code = typeof r?.code === 'string' ? r.code : 'unknown';\n throw err;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiLO,SAAS,eAAe,KAAc,iBAAsE;AACjH,QAAM,IAAI;AACV,MAAI,KAAK,EAAE,OAAO,KAAM;AACxB,QAAM,MAAM,IAAI,MAAM,OAAO,GAAG,YAAY,WAAW,EAAE,UAAU,eAAe;AAClF,MAAI,OAAO,OAAO,GAAG,SAAS,WAAW,EAAE,OAAO;AAClD,QAAM;AACR;","names":[]}
|
|
@@ -9,7 +9,7 @@ interface CodedRefusalError<C extends string = string> extends Error {
|
|
|
9
9
|
* the code when it refused without one — a refusal is never reported as a success just
|
|
10
10
|
* because it arrived under-specified.
|
|
11
11
|
*
|
|
12
|
-
* `code` and `message` must be STRINGS to be used.
|
|
12
|
+
* `code` and `message` must be STRINGS to be used. Eighteen sites call this;
|
|
13
13
|
* **sixteen** had an inline copy it replaced (`spacesMode.ts` was written against the
|
|
14
14
|
* helper in R3-708 and replaced nothing). All sixteen tested for PRESENCE, in **three**
|
|
15
15
|
* shapes:
|
|
@@ -9,7 +9,7 @@ interface CodedRefusalError<C extends string = string> extends Error {
|
|
|
9
9
|
* the code when it refused without one — a refusal is never reported as a success just
|
|
10
10
|
* because it arrived under-specified.
|
|
11
11
|
*
|
|
12
|
-
* `code` and `message` must be STRINGS to be used.
|
|
12
|
+
* `code` and `message` must be STRINGS to be used. Eighteen sites call this;
|
|
13
13
|
* **sixteen** had an inline copy it replaced (`spacesMode.ts` was written against the
|
|
14
14
|
* helper in R3-708 and replaced nothing). All sixteen tested for PRESENCE, in **three**
|
|
15
15
|
* shapes:
|