@xynolog/core 0.8.0 → 0.8.2

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/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { BUS_OPERATIONS, isObject, isString, isAnnotationId, XynologError, HTTP_REQUEST_TIMEOUT_MS, annotationId, uuidV4, byCodePoint } from './chunk-VWT5CTL7.js';
2
- export { ANCHORED_TEXT_REASK_MS, BRIDGED_CHANNELS, BUS_OPERATIONS, BUS_REQUEST_TIMEOUT_MS, Bus, BusRequestError, CHANNEL_SCHEMAS, CHECKS_AT_ONCE_COUNT, DEGRADED_THRESHOLD_MS, DELEGATE_SILENCE_MS, DEVICE_POLL_FLOOR_MS, DEVICE_POLL_MS, DEVICE_SLOW_DOWN_MS, DISCOVERY_INTERVAL_MS, EMIT_RETRY, EMIT_TIMEOUT_MS, ENRICHED_EVENT_TYPES, ERRORS_KEPT_FOR_FIRST_READER_COUNT, EventBus, FrameRefusal, GENERATED_TEXT_ASKS_COUNT, GENERATION_STALL_ASSUMED_TOKENS_COUNT, GENERATION_STALL_FLOOR_MS, GENERATION_STALL_PER_TOKEN_MS, HELD_JOB_STALL_CHECK_MS, HELD_JOB_STALL_MS, HOVER_DELAY_MS, HTTP_REQUEST_TIMEOUT_MS, INVALIDATION_WINDOW_MS, JOB_CLAIM_TIMEOUT_MS, JOB_POLL_MS, JOB_POLL_TIMEOUT_MS, JOB_SILENCE_MS, JOB_STATUS_POLL_MS, KeptForFirstReader, LAZY_REMOVE_MS, LINGER_MS, MARK_COMMIT_TIMEOUT_MS, MAX_RECONNECT_MS, MAX_STORED_BYTES_COUNT, MIN_REFRESH_DELAY_MS, RECONNECT_DEBOUNCE_MS, RECONNECT_MS, REFRESH_BEFORE_EXP_MS, REFRESH_RETRY, REQUEST_RETRY_PAUSE_MS, RESOURCE_SCOPED_CHANNELS, SAVE_DEBOUNCE_MS, SEARCH_DEBOUNCE_MS, SEEN_EVENT_IDS_COUNT, STREAM_OPEN_TIMEOUT_MS, ScopedEventBus, TRACE_FIELD, XynologError, accessToken, annotationId, asDeclared, baseUrl, busLog, busLogEnabled, entityType, faultOf, isAnnotationId, isArray, isJobId, isMarkJobResult, isNumber, isObject, isReportedJobResult, isResourceId, isResourceScopedChannel, isSchemaName, isString, isUserId, isYieldJobResult, jobId, relayFrames, replyChannelsFor, resourceId, said, setBusLogTraceIdProvider, transportErrorCodeForStatus, userId, uuidV4 } from './chunk-VWT5CTL7.js';
1
+ import { HttpStatus, BUS_OPERATIONS, isObject, isString, isAnnotationId, XynologError, TransportError, MIN_REFRESH_DELAY_MS, REFRESH_BEFORE_EXP_MS, annotationId, uuidV4, byCodePoint } from './chunk-NZ7SRPXU.js';
2
+ export { ANCHORED_TEXT_REASK_MS, ARCHIVIST_DEFAULT_ENTITY_TYPES, ARCHIVIST_LAYOUT, ARCHIVIST_MESSAGES, AccessToken, BRIDGED_CHANNELS, BUS_OPERATIONS, BUS_REPLY_BOUNDS, Binary, Bus, BusRequestError, CHANNEL_SCHEMAS, CHECKS_AT_ONCE_COUNT, ContentFormat, CursorsPath, DEFAULT_CLIENT_TIMING, DEFAULT_TRANSPORT_TIMING, DEGRADED_THRESHOLD_MS, DELEGATE_SILENCE_MS, DEVICE_POLL_FLOOR_MS, DEVICE_POLL_MS, DEVICE_SLOW_DOWN_MS, DISCOVERY_INTERVAL_MS, DISPATCHER_MESSAGES, EMBEDDING_REQUESTS, EMIT_TIMEOUT_MS, ENRICHED_EVENT_TYPES, ERRORS_KEPT_FOR_FIRST_READER_COUNT, EnginesWithLimits, EphemeralEventId, EventBus, GATEWAY_MEDIA_TOKEN, GATEWAY_MESSAGES, GATEWAY_RESPONSE_HEADERS, GENERATED_TEXT_ASKS_COUNT, GENERATION_STALL_ASSUMED_TOKENS_COUNT, GENERATION_STALL_FLOOR_MS, GENERATION_STALL_PER_TOKEN_MS, GRAPH_SCHEMA, HELD_JOB_STALL_CHECK_MS, HELD_JOB_STALL_MS, HOVER_DELAY_MS, HttpStatus, Image, JOBS_BUDGETS, JOBS_STORAGE, JOB_CLAIM_TIMEOUT_MS, JOB_POLL_MS, JOB_POLL_TIMEOUT_MS, KbDid, KeptForFirstReader, LIBRARIAN_ANSWER_FORMATS, LIBRARIAN_FOLLOWED, LastEventIds, MARK_COMMIT_TIMEOUT_MS, MAX_RECONNECT_MS, MAX_STORED_BYTES_COUNT, MIN_REFRESH_DELAY_MS, PersistedEventId, RECONNECT_DEBOUNCE_MS, REFRESH_BEFORE_EXP_MS, REFRESH_RETRY, REQUEST_RETRY_PAUSE_MS, RESOURCE_SCOPED_CHANNELS, Refused, ReplyEventId, RunInstance, SAVE_DEBOUNCE_MS, SEARCH_DEBOUNCE_MS, SERVICE_ENVIRONMENT_BOOT_REFUSALS, SERVICE_ENVIRONMENT_VARIABLES, SERVICE_TABLES, SERVICE_TELEMETRY_LOG_LINES, SERVICE_TELEMETRY_MESSAGES, SERVICE_TELEMETRY_TELEMETRY, SMELTER_APPLIED, SMELTER_MESSAGES, ScopedEventBus, ServiceEnvironmentVariable, TRACE_FIELD, TransportError, WEAVER_FOLDED, WORKER_ANSWER_FORMATS, WORKER_MESSAGES, XynologError, annotationId, asDeclared, baseUrl, busLog, busLogEnabled, busLogLinger, busLogTagOf, codeVocabularies, controlErrorCodeAnswers, controlRpcCodes, entityType, errorCodeOf, faultOf, heard, isAnnotationId, isArray, isJobId, isMarkJobResult, isNumber, isObject, isPlace, isReportedJobResult, isResourceId, isResourceScopedChannel, isSchemaName, isString, isUserId, isYieldJobResult, jobId, limitRefusalTransportCodes, membersOf, readOfShape, relayFrames, replyChannelsFor, requestFailureCode, resourceId, said, setActiveTraceProvider, setArrivalMarker, setTraceContinuation, transportErrorCodeForStatus, userId, uuidV4 } from './chunk-NZ7SRPXU.js';
3
3
 
4
4
  // src/job-filter.ts
5
5
  function states(stated, actual) {
@@ -31,6 +31,28 @@ function jobSubject(type) {
31
31
  }
32
32
 
33
33
  // src/persisted-events.ts
34
+ var PERSISTED_EVENT_PAYLOADS = {
35
+ "yield:created": "ResourceCreatedPayload",
36
+ "yield:cloned": "ResourceClonedPayload",
37
+ "yield:updated": "ResourceUpdatedPayload",
38
+ "yield:moved": "ResourceMovedPayload",
39
+ "yield:representation-added": "RepresentationAddedPayload",
40
+ "yield:representation-removed": "RepresentationRemovedPayload",
41
+ "mark:added": "AnnotationAddedPayload",
42
+ "mark:removed": "AnnotationRemovedPayload",
43
+ "mark:body-updated": "AnnotationBodyUpdatedPayload",
44
+ "mark:entity-tag-added": "EntityTagChangedPayload",
45
+ "mark:entity-tag-removed": "EntityTagChangedPayload",
46
+ "mark:archived": "ResourceArchivedPayload",
47
+ "mark:unarchived": "ResourceUnarchivedPayload",
48
+ "frame:entity-type-added": "EntityTypeAddedPayload",
49
+ "frame:tag-schema-added": "TagSchemaAddedPayload",
50
+ "principal:profiled": "PrincipalProfiledPayload",
51
+ "job:started": "JobStartedPayload",
52
+ "job:assigned": "JobAssignedPayload",
53
+ "job:completed": "JobCompletedPayload",
54
+ "job:failed": "JobFailedPayload"
55
+ };
34
56
  var PERSISTED_EVENT_TYPES = [
35
57
  "yield:created",
36
58
  "yield:cloned",
@@ -66,44 +88,83 @@ function getAnnotationIdFromEvent(event) {
66
88
  return isString(id) && isAnnotationId(id) ? id : null;
67
89
  }
68
90
 
91
+ // src/retry-sets.ts
92
+ var RETRY_RULES = {
93
+ boot: {
94
+ statuses: [HttpStatus(429), HttpStatus(503), HttpStatus(504)]
95
+ },
96
+ job: {
97
+ statuses: [HttpStatus(408), HttpStatus(429)],
98
+ statusFrom: HttpStatus(500)
99
+ },
100
+ transport: {
101
+ statuses: [
102
+ HttpStatus(408),
103
+ HttpStatus(413),
104
+ HttpStatus(429),
105
+ HttpStatus(500),
106
+ HttpStatus(502),
107
+ HttpStatus(503),
108
+ HttpStatus(504)
109
+ ],
110
+ idempotentMethods: ["GET", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE"]
111
+ },
112
+ refresh: {
113
+ statuses: [HttpStatus(408), HttpStatus(429)],
114
+ statusFrom: HttpStatus(500),
115
+ noResponse: true
116
+ },
117
+ follow: {
118
+ codes: [
119
+ "bus.timeout",
120
+ "bus.peer-unavailable",
121
+ "rate-limited",
122
+ "unavailable"
123
+ ]
124
+ }
125
+ };
126
+
69
127
  // src/retry-rules.ts
70
- var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
71
- "GET",
72
- "HEAD",
73
- "PUT",
74
- "DELETE",
75
- "OPTIONS",
76
- "TRACE"
77
- ]);
128
+ var listed = (statuses, status) => statuses.includes(status);
78
129
  var boot = {
79
130
  name: "boot",
80
131
  rationale: 'A boot pass or a bus request, where the peer is usually seconds from being ready. 429/503/504 are the server saying "up, but not now" \u2014 retrying is compliance with its own instruction. 500 is excluded on the record: 503 and 504 are promises to recover, an unclassified server fault is not, and replaying it inside a boot pass re-runs whatever broke it. Auth and validation failures stay out for the same reason a 401 does \u2014 the gateway is up and rejected us.',
81
- retryable: ({ status }) => status === 429 || status === 503 || status === 504
132
+ retryable: ({ status }) => status !== void 0 && listed(RETRY_RULES.boot.statuses, status)
82
133
  };
83
134
  var job = {
84
135
  name: "job",
85
136
  rationale: 'A job retry budget, where the cost of NOT retrying is a discarded long-running attempt. 5xx is included where the boot rule excludes it, because the alternative is throwing away paid work over one unclassified fault. 408 joins as an explicit timeout. The price of a wrong "transient" is a re-pay, not a corrupted write \u2014 which is what makes the wider answer affordable here and not at boot. Two facts, both settled 2026-09-12, say how affordable: a 5xx arriving at a job has ALREADY failed three times at the call (the inference client retries twice, a count chosen explicitly rather than inherited from the vendor SDK), so this is a considered second chance rather than a hair-trigger; and since a retried job resumes mid-unit from its checkpointed cursor, the re-pay is about ONE CHUNK, not the whole prefix it used to be (~26 min on the 1958 document). Both push the same way. If either changes \u2014 the client stops retrying, or resume stops working \u2014 this rule is the line to revisit.',
86
- retryable: ({ status }) => status === 408 || status === 429 || status !== void 0 && status >= 500
137
+ retryable: ({ status }) => status !== void 0 && (listed(RETRY_RULES.job.statuses, status) || status >= RETRY_RULES.job.statusFrom)
87
138
  };
88
139
  var transport = {
89
140
  name: "transport",
90
141
  rationale: "An HTTP client's request. A retryable status applies only where a repeat cannot cause a second effect: on an idempotent method, or on a request that carries an Idempotency-Key, whose repeat the server answers as it answered the first. A POST with no key that got a 502 may already have been processed, so a repeat could do it twice. The method and the key are enough: no per-endpoint registry. A key makes a repeat harmless, not a refused request acceptable, so a 400 or 422 stays final. A 401 is not retried: a refused credential is renewed before any rule is asked, and the same token gets the same answer.",
91
142
  retryable: ({ status, method, keyed }) => {
92
143
  if (status === void 0) return false;
93
- const repeatable = keyed === true || method !== void 0 && IDEMPOTENT_METHODS.has(method.toUpperCase());
94
- if (!repeatable) return false;
95
- return status === 408 || status === 413 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
144
+ const repeatable = keyed === true || method !== void 0 && RETRY_RULES.transport.idempotentMethods.includes(method.toUpperCase());
145
+ return repeatable && listed(RETRY_RULES.transport.statuses, status);
96
146
  }
97
147
  };
98
148
  var refresh = {
99
149
  name: "refresh",
100
150
  rationale: 'Exchanging a refresh token at its issuer. The issuer\'s answer is the verdict and its absence never is: a refused grant (RFC 6749 \xA75.2 returns 400 `invalid_grant` for a revoked, expired or already-rotated token) is terminal on the first answer, because retrying cannot change it and only delays a re-login the user must perform anyway. No response at all, or one saying "not now" (408, 429, 5xx), is transient \u2014 the session survives a lost packet. 5xx is included where the boot rule excludes it, and the two are not in conflict: a boot pass replays whatever broke it, while this is a single idempotent exchange with no side effect to replay. Unclassified faults are TERMINAL, which inverts the usual instinct deliberately \u2014 a 404 on the token endpoint is a misconfiguration, not a promise to recover, and over-retrying here shows the user a hung app instead of the honest re-login.',
101
151
  retryable: ({ status }) => {
102
- if (status === void 0) return true;
103
- return status === 408 || status === 429 || status >= 500;
152
+ if (status === void 0) return RETRY_RULES.refresh.noResponse;
153
+ return listed(RETRY_RULES.refresh.statuses, status) || status >= RETRY_RULES.refresh.statusFrom;
104
154
  }
105
155
  };
106
- var RETRY_RULES = Object.freeze({ boot, job, refresh, transport });
156
+ var follow = {
157
+ name: "follow",
158
+ rationale: "A job's follower's ask for the job's status, asked about the code the ask failed with. Asking again is how a follower that heard nothing learns how its job ended, so a failure that may pass is asked again at the next poll: a reply that did not come in time, an answering service not yet connected, a limit, a gateway that could not be reached. Any other ends the follower with its code, never the job: asking again cannot mend it, and a follower that asked forever would never say so.",
159
+ retryable: ({ code }) => RETRY_RULES.follow.codes.some((asked) => asked === code)
160
+ };
161
+ var RETRY_RULES2 = Object.freeze({
162
+ boot,
163
+ follow,
164
+ job,
165
+ refresh,
166
+ transport
167
+ });
107
168
 
108
169
  // src/base64url.ts
109
170
  function base64url(bytes) {
@@ -112,6 +173,15 @@ function base64url(bytes) {
112
173
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
113
174
  }
114
175
 
176
+ // src/refuse-non-finite.ts
177
+ function refuseNonFinite(key, value) {
178
+ if (typeof value === "number" && !Number.isFinite(value))
179
+ throw new TypeError(
180
+ `${key === "" ? "The value" : `The member ${key}`} is ${String(value)}, which is no number JSON writes`
181
+ );
182
+ return value;
183
+ }
184
+
115
185
  // src/sha256.ts
116
186
  var K = new Uint32Array([
117
187
  1116352408,
@@ -243,7 +313,7 @@ function sha256(message) {
243
313
  // src/annotation-id.ts
244
314
  function canonical(value) {
245
315
  if (value === null || typeof value !== "object")
246
- return JSON.stringify(value) ?? "null";
316
+ return JSON.stringify(value, refuseNonFinite) ?? "null";
247
317
  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
248
318
  const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => byCodePoint(a, b));
249
319
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
@@ -577,7 +647,7 @@ function parseFragmentSelector(fragment) {
577
647
  // src/text-context.ts
578
648
  var CONTEXT_LENGTH = 64;
579
649
  var MAX_EXTENSION = 32;
580
- var BOUNDARY = /[\s.,;:!?'"()\[\]{}<>\/\\]/;
650
+ var BOUNDARY = /[\s.,;:!?'"()[\]{}<>/\\]/;
581
651
  function extractContext(content, start, end) {
582
652
  return contextOf(content, textOffsets(content), start, end);
583
653
  }
@@ -611,9 +681,11 @@ function contextOf(content, offsets, start, end) {
611
681
  // src/annotation-builders.ts
612
682
  var SpanRefusedError = class extends XynologError {
613
683
  constructor(message, code) {
614
- super(message, code);
684
+ super(message);
685
+ this.code = code;
615
686
  this.name = "SpanRefusedError";
616
687
  }
688
+ code;
617
689
  };
618
690
  var DISAMBIGUATION_MIN_WINDOW = 32;
619
691
  function reconcile(text, quoted) {
@@ -1754,7 +1826,7 @@ function extractCharset(mediaType) {
1754
1826
  );
1755
1827
  }
1756
1828
  function undecoded(label) {
1757
- return new XynologError(
1829
+ return new TransportError(
1758
1830
  `The resource's text is ${label}, which is no charset this reader decodes: read its bytes instead`,
1759
1831
  "error"
1760
1832
  );
@@ -1796,7 +1868,7 @@ function getPrimaryRepresentation(resource) {
1796
1868
  const stated = resource.representations;
1797
1869
  if (isRepresentation(stated)) return stated;
1798
1870
  if (Array.isArray(stated) && stated.every(isRepresentation)) return stated[0];
1799
- throw new XynologError(
1871
+ throw new TransportError(
1800
1872
  `The resource ${resource["@id"]} is no ResourceDescriptor: its representations are ${stated === void 0 ? "not stated" : "neither one representation nor a list of them"}`,
1801
1873
  "error"
1802
1874
  );
@@ -1822,7 +1894,7 @@ function isDraft(resource) {
1822
1894
  function decodeRepresentation(buffer, mediaType) {
1823
1895
  const source = textSourceOf(mediaType);
1824
1896
  if (derivesTextOf(mediaType) || source === "none") {
1825
- throw new XynologError(
1897
+ throw new TransportError(
1826
1898
  `decodeRepresentation refused ${mediaType}: its text source is '${source}' \u2014 derived text comes from the anchored-text read, never from decoding bytes`,
1827
1899
  "error"
1828
1900
  );
@@ -1830,6 +1902,87 @@ function decodeRepresentation(buffer, mediaType) {
1830
1902
  return decodeWithCharset(buffer, mediaType);
1831
1903
  }
1832
1904
 
1905
+ // src/byte-source.ts
1906
+ function byteSourceOf(bytes) {
1907
+ return {
1908
+ open: () => new ReadableStream({
1909
+ start(controller) {
1910
+ controller.enqueue(bytes);
1911
+ controller.close();
1912
+ }
1913
+ }),
1914
+ length: bytes.byteLength
1915
+ };
1916
+ }
1917
+ function lengthOf(source) {
1918
+ return source instanceof Blob ? source.size : source.length;
1919
+ }
1920
+ function openSource(source) {
1921
+ return source instanceof Blob ? source.stream() : source.open();
1922
+ }
1923
+ function sourceFailure(cause) {
1924
+ return new TransportError(
1925
+ `the upload's source could not be read: ${cause instanceof Error ? cause.message : String(cause)}`,
1926
+ "error",
1927
+ void 0,
1928
+ { cause }
1929
+ );
1930
+ }
1931
+ function releaseFailure(cause) {
1932
+ return new TransportError(
1933
+ `the upload's source could not be released: ${cause instanceof Error ? cause.message : String(cause)}`,
1934
+ "error",
1935
+ void 0,
1936
+ { cause }
1937
+ );
1938
+ }
1939
+ async function heldOf(source, signal, onReleaseFailure) {
1940
+ if (signal?.aborted) throw signal.reason;
1941
+ const { length } = source;
1942
+ let reader;
1943
+ try {
1944
+ reader = source.open().getReader();
1945
+ } catch (error) {
1946
+ throw sourceFailure(error);
1947
+ }
1948
+ let released;
1949
+ const release = (reason) => released ??= reader.cancel(reason).catch((error) => {
1950
+ onReleaseFailure(releaseFailure(error));
1951
+ });
1952
+ const cancelled = () => void release(signal?.reason);
1953
+ signal?.addEventListener("abort", cancelled, { once: true });
1954
+ const pieces = [];
1955
+ let given = 0;
1956
+ try {
1957
+ for (; ; ) {
1958
+ const read = await reader.read().catch((error) => {
1959
+ released ??= Promise.resolve();
1960
+ throw signal?.aborted ? signal.reason : sourceFailure(error);
1961
+ });
1962
+ if (signal?.aborted) throw signal.reason;
1963
+ if (read.done) {
1964
+ const file = new Blob(pieces);
1965
+ if (length !== void 0 && file.size !== length)
1966
+ throw sourceFailure(
1967
+ new Error(`it gave ${file.size} bytes, and states ${length}`)
1968
+ );
1969
+ return file;
1970
+ }
1971
+ given += read.value.byteLength;
1972
+ if (length !== void 0 && given > length)
1973
+ throw sourceFailure(
1974
+ new Error(`it gave more bytes than the ${length} it states`)
1975
+ );
1976
+ pieces.push(new Uint8Array(read.value));
1977
+ }
1978
+ } catch (error) {
1979
+ await release(error);
1980
+ throw error;
1981
+ } finally {
1982
+ signal?.removeEventListener("abort", cancelled);
1983
+ }
1984
+ }
1985
+
1833
1986
  // src/cache-refresh.ts
1834
1987
  var CACHE_QUERIES = [
1835
1988
  "resource",
@@ -2113,11 +2266,221 @@ var CACHE_REFRESH_CHANNELS = [
2113
2266
  "frame:tag-schema-added"
2114
2267
  ];
2115
2268
 
2269
+ // src/control-methods.ts
2270
+ var CONTROL_API_VERSION = "control.xynolog.org/v1alpha1";
2271
+ var CONTROL_NOTIFICATIONS = {
2272
+ /** A line of what a request is doing. */
2273
+ "notifications/progress": { from: "launcher", params: "Progress" },
2274
+ /** A sign-in waits for a person to enter a code. */
2275
+ "notifications/userAction": { from: "launcher", params: "UserAction" },
2276
+ /** A line a followed service wrote. */
2277
+ "notifications/log": { from: "launcher", params: "LogRecord" },
2278
+ /** A run's instance is running. */
2279
+ "notifications/serviceStarted": {
2280
+ from: "launcher",
2281
+ params: "ServiceStarted"
2282
+ },
2283
+ /** A line a run's instance wrote. */
2284
+ "notifications/serviceOutput": { from: "launcher", params: "ServiceOutput" },
2285
+ /** The client gives up on a request. */
2286
+ "notifications/cancelled": { from: "client", params: "Cancelled" }
2287
+ };
2288
+ var CONTROL_METHODS = {
2289
+ /**
2290
+ * What the launcher is: its version, the API versions it speaks, the runtimes
2291
+ * it detects. It reads none of the machine's state.
2292
+ */
2293
+ "launcher.about": {
2294
+ params: "AboutParams",
2295
+ result: "AboutResult",
2296
+ exclusive: false,
2297
+ sends: []
2298
+ },
2299
+ /** Every knowledge base this machine knows: xynolog roots. */
2300
+ "roots.list": {
2301
+ params: "RootsListParams",
2302
+ result: "RootsListResult",
2303
+ exclusive: true,
2304
+ sends: []
2305
+ },
2306
+ /** Create and register a new local knowledge base: xynolog init. */
2307
+ "roots.init": {
2308
+ params: "RootsInitParams",
2309
+ result: "RootsInitResult",
2310
+ exclusive: true,
2311
+ sends: ["notifications/progress"]
2312
+ },
2313
+ /** Remove one registry row, and no file: xynolog forget. */
2314
+ "roots.forget": {
2315
+ params: "RootsForgetParams",
2316
+ result: "RootsForgetResult",
2317
+ exclusive: true,
2318
+ sends: []
2319
+ },
2320
+ /**
2321
+ * Each knowledge base's stack, and the services they share: xynolog status.
2322
+ */
2323
+ "status.snapshot": {
2324
+ params: "StatusSnapshotParams",
2325
+ result: "StatusSnapshotResult",
2326
+ exclusive: true,
2327
+ sends: []
2328
+ },
2329
+ /** Start a stack, or some of its services: xynolog start. */
2330
+ "stack.start": {
2331
+ params: "StackStartParams",
2332
+ result: "StackStartResult",
2333
+ exclusive: true,
2334
+ sends: []
2335
+ },
2336
+ /** Stop a stack, or some of its services: xynolog stop. */
2337
+ "stack.stop": {
2338
+ params: "StackStopParams",
2339
+ result: "StackStopResult",
2340
+ exclusive: true,
2341
+ sends: []
2342
+ },
2343
+ /**
2344
+ * Sign in at the issuer a stack's knowledge base trusts, by the device grant,
2345
+ * and keep the session in the launcher's store: xynolog login. Exclusive
2346
+ * while it finds the stack; the wait for the person is not.
2347
+ */
2348
+ "auth.login": {
2349
+ params: "AuthLoginParams",
2350
+ result: "AuthLoginResult",
2351
+ exclusive: true,
2352
+ sends: ["notifications/userAction"]
2353
+ },
2354
+ /** End the launcher's session for a stack: xynolog logout. */
2355
+ "auth.logout": {
2356
+ params: "AuthLogoutParams",
2357
+ result: "AuthLogoutResult",
2358
+ exclusive: true,
2359
+ sends: []
2360
+ },
2361
+ /**
2362
+ * Create an account in a local knowledge base's launcher-managed Keycloak
2363
+ * realm: xynolog useradd. A supplied password is secret request data and is
2364
+ * never narrated or persisted; a generated password is returned once in the
2365
+ * result.
2366
+ */
2367
+ "identity.useradd": {
2368
+ params: "IdentityUseraddParams",
2369
+ result: "IdentityUseraddResult",
2370
+ exclusive: true,
2371
+ sends: []
2372
+ },
2373
+ /**
2374
+ * List accounts in one local knowledge base's launcher-managed Keycloak
2375
+ * realm. Passwords and tokens are never returned.
2376
+ */
2377
+ "identity.users.list": {
2378
+ params: "IdentityUsersListParams",
2379
+ result: "IdentityUsersListResult",
2380
+ exclusive: true,
2381
+ sends: []
2382
+ },
2383
+ /**
2384
+ * Follow a stack's service logs until the client cancels or every source
2385
+ * ends: xynolog logs. Exclusive while it finds the containers; the follow is
2386
+ * not.
2387
+ */
2388
+ "logs.follow": {
2389
+ params: "LogsFollowParams",
2390
+ result: "LogsFollowResult",
2391
+ exclusive: true,
2392
+ sends: ["notifications/log"]
2393
+ },
2394
+ /** Every setting the launcher keeps: xynolog settings. */
2395
+ "settings.list": {
2396
+ params: "SettingsListParams",
2397
+ result: "SettingsListResult",
2398
+ exclusive: true,
2399
+ sends: []
2400
+ },
2401
+ /** One setting: xynolog settings <name>. */
2402
+ "settings.get": {
2403
+ params: "SettingsGetParams",
2404
+ result: "Setting",
2405
+ exclusive: true,
2406
+ sends: []
2407
+ },
2408
+ /**
2409
+ * Set a setting, checked as a start would check it: xynolog settings <name>
2410
+ * <value>.
2411
+ */
2412
+ "settings.set": {
2413
+ params: "SettingsSetParams",
2414
+ result: "Setting",
2415
+ exclusive: true,
2416
+ sends: []
2417
+ },
2418
+ /** Return a setting to its default: xynolog settings <name> --unset. */
2419
+ "settings.unset": {
2420
+ params: "SettingsUnsetParams",
2421
+ result: "Setting",
2422
+ exclusive: true,
2423
+ sends: []
2424
+ },
2425
+ /** Where a machine document is: xynolog settings <document> --path. */
2426
+ "settings.path": {
2427
+ params: "SettingsPathParams",
2428
+ result: "SettingsPathResult",
2429
+ exclusive: true,
2430
+ sends: []
2431
+ },
2432
+ /**
2433
+ * Where this machine and a run's instance meet under a runtime: the host
2434
+ * address an instance's ports are published on and its dials of this machine
2435
+ * go to. A caller asks it before it writes an instance's document.
2436
+ */
2437
+ "service.host": {
2438
+ params: "ServiceHostParams",
2439
+ result: "ServiceHostResult",
2440
+ exclusive: false,
2441
+ sends: []
2442
+ },
2443
+ /**
2444
+ * Run one instance of a knowledge base's own service once, from the image its
2445
+ * stack documents name, unsupervised, on the caller's document, arguments,
2446
+ * environment and mounts, and answer when it exits: xynolog run. Exclusive
2447
+ * until its container runs; the wait for its exit is not.
2448
+ */
2449
+ "service.run": {
2450
+ params: "ServiceRunParams",
2451
+ result: "ServiceRunResult",
2452
+ exclusive: true,
2453
+ sends: ["notifications/serviceStarted", "notifications/serviceOutput"]
2454
+ },
2455
+ /**
2456
+ * Send a run's instance SIGTERM, then SIGKILL if it outlives 15 seconds, or
2457
+ * SIGKILL at once: xynolog signal.
2458
+ */
2459
+ "service.signal": {
2460
+ params: "ServiceSignalParams",
2461
+ result: "ServiceSignalResult",
2462
+ exclusive: false,
2463
+ sends: []
2464
+ }
2465
+ };
2466
+
2116
2467
  // src/oauth-clients.ts
2117
2468
  var BROWSER_CLIENT_ID = "xynolog-browser";
2118
2469
  var SCRIPT_CLIENT_ID = "xynolog-cli";
2119
2470
  var SIGN_IN_SCOPE = "openid email profile offline_access";
2120
2471
 
2472
+ // src/stored.ts
2473
+ var STORAGE_KEY = "xynolog.knowledgeBases";
2474
+ var ACTIVE_KEY = "xynolog.activeKnowledgeBaseId";
2475
+ var OPEN_RESOURCES_BY_KB_KEY = "xynolog.openResourcesByKb";
2476
+ var LAST_VIEWED_RESOURCE_BY_KB_KEY = "xynolog.lastViewedResourceByKb";
2477
+ var PENDING_AUTHORIZATION_KEY = "xynolog.pendingAuthorization";
2478
+ var SESSION_KEY_PREFIX = "xynolog.session.";
2479
+ var LAST_EVENT_ID_KEY_PREFIX = "xynolog.lastEventId.";
2480
+ var CACHE_KEY_PREFIX = "xynolog.cache.";
2481
+ var WHOLE_KEY = "_";
2482
+ var CACHE_DOCUMENT_VERSION = 1;
2483
+
2121
2484
  // src/gateway-http.ts
2122
2485
  var gatewayRoutes = {
2123
2486
  getHealth: {
@@ -2196,9 +2559,13 @@ var gatewayRoutes = {
2196
2559
  answers: "*/*"
2197
2560
  }
2198
2561
  };
2199
- var gatewayHeaders = {
2200
- cacheControl: "Cache-Control",
2562
+ var gatewayRequestHeaders = {
2201
2563
  idempotencyKey: "Idempotency-Key",
2564
+ traceparent: "traceparent",
2565
+ tracestate: "tracestate"
2566
+ };
2567
+ var gatewayResponseHeaders = {
2568
+ cacheControl: "Cache-Control",
2202
2569
  link: "Link",
2203
2570
  retryAfter: "Retry-After",
2204
2571
  wwwAuthenticate: "WWW-Authenticate"
@@ -2207,10 +2574,537 @@ var gatewayApiKeys = {
2207
2574
  mediaToken: { in: "query", name: "token" }
2208
2575
  };
2209
2576
 
2210
- // src/sign-in.ts
2211
- function isSignIn(value) {
2212
- return isObject(value) && isString(value["token"]) && (value["refreshToken"] === void 0 || isString(value["refreshToken"])) && (value["email"] === void 0 || isString(value["email"])) && isString(value["obtainedAt"]) && (value["expiresAt"] === void 0 || isString(value["expiresAt"])) && isString(value["issuer"]) && isString(value["tokenEndpoint"]) && (value["revocationEndpoint"] === void 0 || isString(value["revocationEndpoint"]));
2577
+ // src/archivist-http.ts
2578
+ var archivistRoutes = {
2579
+ getHealth: { method: "GET", path: "/health" },
2580
+ listStreams: { method: "GET", path: "/events" },
2581
+ getResourceEvents: { method: "GET", path: "/events/{resourceId}" },
2582
+ storeResource: { method: "POST", path: "/resources" },
2583
+ getResourceContent: { method: "GET", path: "/resources/{id}/content" },
2584
+ getResourceJsonLd: { method: "GET", path: "/resources/{id}/jsonld" },
2585
+ getResourceAnnotations: {
2586
+ method: "GET",
2587
+ path: "/resources/{id}/annotations"
2588
+ },
2589
+ getResourceAnchoredText: {
2590
+ method: "GET",
2591
+ path: "/resources/{id}/anchored-text"
2592
+ },
2593
+ putResourceAnchoredText: {
2594
+ method: "PUT",
2595
+ path: "/resources/{id}/anchored-text"
2596
+ },
2597
+ listAnchoredTextEntries: { method: "GET", path: "/anchored-text/entries" },
2598
+ getStoredResourceAnchoredText: {
2599
+ method: "GET",
2600
+ path: "/resources/{id}/anchored-text/stored"
2601
+ },
2602
+ putAnchoredTextStamp: { method: "PUT", path: "/anchored-text/stamp" }
2603
+ };
2604
+
2605
+ // src/service-groups.ts
2606
+ var CONTROL_SERVICE_GROUPS = {
2607
+ $comment: "AUTHORITY for the group each service role is in (ServiceRole, ServiceGroup): what xynolog status shows together, and what --group starts or stops. Each group once, in ServiceGroup's order, and each role in exactly one group, in the order status reads them; read in order, the roles are ServiceRole's. A knowledge base is its record and its index. The issuer signs every knowledge base's accounts in. The knowledge workers are where people and agents work on it. The providers serve its models, and the telemetry watches them all.",
2608
+ groups: [
2609
+ {
2610
+ group: "record",
2611
+ roles: ["gateway", "archivist", "dispatcher", "messaging"]
2612
+ },
2613
+ {
2614
+ group: "index",
2615
+ roles: ["librarian", "smelter", "weaver", "graph", "vectors"]
2616
+ },
2617
+ {
2618
+ group: "issuer",
2619
+ roles: ["identity", "identity-store"]
2620
+ },
2621
+ {
2622
+ group: "knowledge-workers",
2623
+ roles: ["browser", "worker"]
2624
+ },
2625
+ {
2626
+ group: "providers",
2627
+ roles: ["inference", "embedding"]
2628
+ },
2629
+ {
2630
+ group: "telemetry",
2631
+ roles: ["collector", "traces", "metrics"]
2632
+ }
2633
+ ]
2634
+ };
2635
+
2636
+ // src/service-texts.ts
2637
+ function archivistLayoutEventStreamPath(placeholders) {
2638
+ return `.xynolog/events/${placeholders.shard}/${placeholders.resourceId}`;
2639
+ }
2640
+ function archivistLayoutEventFileName(placeholders) {
2641
+ return `events-${String(placeholders.number).padStart(6, "0")}.jsonl`;
2642
+ }
2643
+ function archivistLayoutViewPath(placeholders) {
2644
+ return `resources/${placeholders.shard}/${placeholders.resourceId}.json`;
2645
+ }
2646
+ function archivistLayoutStorageUriIndexPath(placeholders) {
2647
+ return `projections/storage-uri/${placeholders.shard}/${placeholders.uriHash}.json`;
2648
+ }
2649
+ function archivistLayoutAnchoredTextEntryPath(placeholders) {
2650
+ return `${placeholders.shard}/${placeholders.contentChecksum}.json`;
2651
+ }
2652
+ function archivistMessagesBootNoProjectFile() {
2653
+ return "The knowledge base commits no .xynolog/config.yaml, so declares no site.domain: it is the identity this knowledge base acts under, and the audience it accepts tokens for";
2654
+ }
2655
+ function archivistMessagesBootNotACheckout(placeholders) {
2656
+ return `The knowledge base's project file says git.sync is true, and ${placeholders.root} is not a git checkout (${placeholders.why}). Make it one (git init), or set git.sync to false.`;
2657
+ }
2658
+ function archivistMessagesBootGatewaySilent(placeholders) {
2659
+ return `The gateway at ${placeholders.gateway} did not say which knowledge base it serves (/.well-known/oauth-protected-resource): ${placeholders.reason}`;
2660
+ }
2661
+ function archivistMessagesBootGatewayElsewhere(placeholders) {
2662
+ return `The gateway at ${placeholders.gateway} serves ${placeholders.served}, and the tree at ${placeholders.root} is ${placeholders.tree} (${placeholders.did})`;
2663
+ }
2664
+ function archivistMessagesUnsentTooLarge(placeholders) {
2665
+ return `The answer could not be sent: it is ${placeholders.bytes} bytes, and a bus message may be ${placeholders.maxBodyBytes}`;
2666
+ }
2667
+ function archivistMessagesUnsentNotSent(placeholders) {
2668
+ return `The answer could not be sent: ${placeholders.why}`;
2669
+ }
2670
+ function archivistMessagesRefusalsUncitedWorker(placeholders) {
2671
+ return `${placeholders.channel} refused: a worker-role emitter must cite the job it fulfils in \`jobId\``;
2672
+ }
2673
+ function archivistMessagesRefusalsUnassignedJob(placeholders) {
2674
+ return `${placeholders.channel} refused: cites job ${placeholders.jobId}, but the log of ${placeholders.resourceId} holds no assignment of it, and the job did not make it`;
2675
+ }
2676
+ function archivistMessagesRefusalsNotTheHolder(placeholders) {
2677
+ return `${placeholders.channel} refused: job ${placeholders.jobId}'s recorded holder is ${placeholders.holder}, not the writer ${placeholders.writer}`;
2678
+ }
2679
+ function archivistMessagesRefusalsSourcelessCreate() {
2680
+ return "yield:create refused: a create citing a job must name the source resource its job was assigned on (generatedFrom.resourceId)";
2681
+ }
2682
+ function archivistMessagesRefusalsMultiAgentCreate() {
2683
+ return "yield:create refused: a multi-agent generator is not supported; derivation binds one generator to the executor";
2684
+ }
2685
+ function archivistMessagesRefusalsGeneratorNotExecutor(placeholders) {
2686
+ return `${placeholders.channel} refused: generator ${placeholders.generator} is not the executor ${placeholders.executor}`;
2687
+ }
2688
+ function archivistMessagesRefusalsExecutorNotSoftware(placeholders) {
2689
+ return `${placeholders.channel} refused: a generator was supplied, but the executor ${placeholders.executor} is not software`;
2690
+ }
2691
+ function archivistMessagesRefusalsAnnotationWithCreator(placeholders) {
2692
+ return `${placeholders.channel} refused: \`creator\` on annotation ${placeholders.annotationId} is derived by the knowledge base, never sent`;
2693
+ }
2694
+ function archivistMessagesRefusalsMultiAgentAnnotation(placeholders) {
2695
+ return `${placeholders.channel} refused: annotation ${placeholders.annotationId} carries a multi-agent generator; derivation binds one generator to the executor`;
2696
+ }
2697
+ function archivistMessagesRefusalsNotAnnotatable(placeholders) {
2698
+ return `"${placeholders.mediaType}" cannot be annotated`;
2699
+ }
2700
+ function archivistMessagesRefusalsStorageUriScheme(placeholders) {
2701
+ return `Invalid storage URI (must start with file://): ${placeholders.uri}`;
2702
+ }
2703
+ function archivistMessagesRefusalsStorageUriOutside(placeholders) {
2704
+ return `Invalid storage URI (must name a file inside the working tree): ${placeholders.uri}`;
2705
+ }
2706
+ function archivistMessagesRefusalsChecksumMismatch(placeholders) {
2707
+ return `Checksum mismatch for ${placeholders.uri}: expected ${placeholders.expected}... but got ${placeholders.actual}...
2708
+ The file on disk differs from the recorded checksum. Has it been modified since staging?`;
2709
+ }
2710
+ function archivistMessagesRefusalsUnarchiveWithoutFile(placeholders) {
2711
+ return `Cannot unarchive: file not found at ${placeholders.uri}`;
2712
+ }
2713
+ function archivistMessagesRefusalsEntityTypeNotRegistered(placeholders) {
2714
+ return `Entity type not registered: ${placeholders.types}`;
2715
+ }
2716
+ function archivistMessagesRefusalsResourceNotFound() {
2717
+ return "Resource not found";
2718
+ }
2719
+ function archivistMessagesRefusalsAnnotationNotFound() {
2720
+ return "Annotation not found";
2721
+ }
2722
+ function archivistMessagesRefusalsPathEscapes() {
2723
+ return "path escapes project root";
2724
+ }
2725
+ function archivistMessagesRefusalsPathNotFound() {
2726
+ return "path not found";
2727
+ }
2728
+ function archivistMessagesRefusalsCloneSourceNotFound() {
2729
+ return "Resource not found";
2730
+ }
2731
+ function archivistMessagesRefusalsCloneContentNotFound() {
2732
+ return "Resource content not found";
2733
+ }
2734
+ function archivistMessagesRefusalsInvalidToken() {
2735
+ return "Invalid or expired token";
2736
+ }
2737
+ function archivistMessagesRefusalsTokenExpired() {
2738
+ return "Token expired";
2739
+ }
2740
+ function archivistMessagesRefusalsTokenSourceNotFound() {
2741
+ return "Source resource not found";
2742
+ }
2743
+ function archivistMessagesHttpStreamListingFailed() {
2744
+ return "stream listing failed";
2745
+ }
2746
+ function archivistMessagesHttpEventsBadRequest() {
2747
+ return "resourceId path segment and integer fromSequence >= 1 are required";
2748
+ }
2749
+ function archivistMessagesHttpEventReadFailed() {
2750
+ return "event read failed";
2751
+ }
2752
+ function archivistMessagesHttpContentReadFailed() {
2753
+ return "content read failed";
2754
+ }
2755
+ function archivistMessagesHttpContentNoResource(placeholders) {
2756
+ return `Resource not found: ${placeholders.id}`;
2213
2757
  }
2758
+ function archivistMessagesHttpContentNoRepresentation(placeholders) {
2759
+ return `Resource representation not found: no storageUri for ${placeholders.id}`;
2760
+ }
2761
+ function archivistMessagesHttpJsonldNotFound() {
2762
+ return "Resource not found";
2763
+ }
2764
+ function archivistMessagesHttpAnnotationsNotFound() {
2765
+ return "Resource not found";
2766
+ }
2767
+ function archivistMessagesHttpAnchoredTextReadFailed() {
2768
+ return "anchored-text read failed";
2769
+ }
2770
+ function archivistMessagesHttpAnchoredTextNotAWrite(placeholders) {
2771
+ return `The body is no AnchoredTextWrite: ${placeholders.why}`;
2772
+ }
2773
+ function archivistMessagesHttpAnchoredTextWriteNotFound() {
2774
+ return "Resource not found";
2775
+ }
2776
+ function archivistMessagesHttpAnchoredTextStoredNotFound() {
2777
+ return "Resource not found";
2778
+ }
2779
+ function archivistMessagesHttpAnchoredTextNoEntry() {
2780
+ return "No entry is stored for this content";
2781
+ }
2782
+ function archivistMessagesHttpUploadUnattributed() {
2783
+ return "Xynolog-Principal is required: the record attributes every resource to someone";
2784
+ }
2785
+ function archivistMessagesHttpUploadNotMultipart() {
2786
+ return "The body is not multipart/form-data";
2787
+ }
2788
+ function archivistMessagesHttpUploadUnsupportedMedia(placeholders) {
2789
+ return `Unsupported media type: ${placeholders.type}`;
2790
+ }
2791
+ function archivistMessagesHttpUploadKeyReused() {
2792
+ return "This Idempotency-Key names a resource recorded from other fields or other bytes";
2793
+ }
2794
+ function archivistMessagesHttpUploadRefused(placeholders) {
2795
+ return `${placeholders.refusal}`;
2796
+ }
2797
+ function archivistMessagesLoggedNotAnEventFieldsWhat(placeholders) {
2798
+ return `${placeholders.path} line ${placeholders.line} is not an event`;
2799
+ }
2800
+ function dispatcherMessagesRefusalsCreateWithoutUser() {
2801
+ return "_userId is required (injected by bus gateway)";
2802
+ }
2803
+ function dispatcherMessagesRefusalsEntityTypeNotRegistered(placeholders) {
2804
+ return `Entity type not registered: ${placeholders.types}`;
2805
+ }
2806
+ function dispatcherMessagesRefusalsTagSchemaNotRegistered(placeholders) {
2807
+ return `Tag schema not registered: ${placeholders.schemaId}`;
2808
+ }
2809
+ function dispatcherMessagesRefusalsYieldParameter(placeholders) {
2810
+ return `a yield job takes no parameter ${placeholders.params}`;
2811
+ }
2812
+ function dispatcherMessagesRefusalsNotAWorker() {
2813
+ return "job:claim refused: the caller is not a worker for this knowledge base";
2814
+ }
2815
+ function dispatcherMessagesRefusalsNonePending() {
2816
+ return "No pending job matches the claim";
2817
+ }
2818
+ function dispatcherMessagesRefusalsClaimWithoutUser() {
2819
+ return "job:claim missing _userId (gateway injection)";
2820
+ }
2821
+ function dispatcherMessagesRefusalsJobNotFound() {
2822
+ return "Job not found";
2823
+ }
2824
+ function dispatcherMessagesErrorsPresumedDead(placeholders) {
2825
+ return `worker presumed dead \u2014 no progress within ${placeholders.minutes} minutes`;
2826
+ }
2827
+ function gatewayMediaTokenClaimsIss(placeholders) {
2828
+ return `${placeholders.domain}`;
2829
+ }
2830
+ function gatewayMediaTokenClaimsSub(placeholders) {
2831
+ return `${placeholders.resourceId}`;
2832
+ }
2833
+ function gatewayMessagesMessagesNoCredential() {
2834
+ return "Unauthorized";
2835
+ }
2836
+ function gatewayMessagesMessagesRefusedToken() {
2837
+ return "Invalid token";
2838
+ }
2839
+ function gatewayMessagesMessagesRefusedMediaToken() {
2840
+ return "Invalid media token";
2841
+ }
2842
+ function gatewayMessagesMessagesRefusalRate() {
2843
+ return "The credential was refused, and its holder's refused requests have used their allowance";
2844
+ }
2845
+ function gatewayMessagesMessagesNotJson() {
2846
+ return "The body is not JSON";
2847
+ }
2848
+ function gatewayMessagesMessagesNoIdempotencyKey() {
2849
+ return "The request carries no Idempotency-Key";
2850
+ }
2851
+ function gatewayMessagesMessagesIdempotencyKeyNotText() {
2852
+ return "The Idempotency-Key is not text: only visible ASCII characters";
2853
+ }
2854
+ function gatewayMessagesMessagesIdempotencyKeyLength(placeholders) {
2855
+ return `The Idempotency-Key must be ${placeholders.minLength} to ${placeholders.maxLength} characters`;
2856
+ }
2857
+ function gatewayMessagesMessagesUnknownChannel(placeholders) {
2858
+ return `Unknown channel: ${placeholders.channel}`;
2859
+ }
2860
+ function gatewayMessagesMessagesInvalidPayload(placeholders) {
2861
+ return `Invalid payload for ${placeholders.channel}: ${placeholders.problems}`;
2862
+ }
2863
+ function gatewayMessagesMessagesCorrelationWithoutClient(placeholders) {
2864
+ return `clientId is required to emit ${placeholders.channel} with a correlationId`;
2865
+ }
2866
+ function gatewayMessagesMessagesNoSubscription() {
2867
+ return "At least one global channel or scoped entry is required";
2868
+ }
2869
+ function gatewayMessagesMessagesDuplicateScope(placeholders) {
2870
+ return `duplicate scope "${placeholders.scope}" in matrix`;
2871
+ }
2872
+ function gatewayMessagesMessagesNotFound() {
2873
+ return "Not found";
2874
+ }
2875
+ function gatewayMessagesMessagesResourceNotFound() {
2876
+ return "Resource not found";
2877
+ }
2878
+ function gatewayMessagesMessagesRepresentationNotFound() {
2879
+ return "Resource representation not found";
2880
+ }
2881
+ function gatewayMessagesMessagesCorrelationClaimed(placeholders) {
2882
+ return `correlationId ${placeholders.correlationId} is already claimed`;
2883
+ }
2884
+ function gatewayMessagesMessagesTooLarge(placeholders) {
2885
+ return `The body is larger than ${placeholders.maxBodyBytes} bytes, this operation's maxBodyBytes`;
2886
+ }
2887
+ function gatewayMessagesMessagesIdempotencyKeyReused() {
2888
+ return "This Idempotency-Key was first sent with another body";
2889
+ }
2890
+ function gatewayMessagesMessagesEmitRate() {
2891
+ return "This principal's emits have used its bucket";
2892
+ }
2893
+ function gatewayMessagesMessagesUnansweredRequests(placeholders) {
2894
+ return `client has ${placeholders.max} unanswered requests; retry when one settles`;
2895
+ }
2896
+ function gatewayMessagesMessagesStreams() {
2897
+ return "This principal holds as many streams as it may";
2898
+ }
2899
+ function gatewayMessagesMessagesInternal() {
2900
+ return "Internal server error";
2901
+ }
2902
+ function gatewayMessagesMessagesContentStoreUnavailable() {
2903
+ return "Content store unavailable";
2904
+ }
2905
+ function gatewayMessagesMessagesPlaneUnavailable() {
2906
+ return "The signal plane is unavailable: its broker is not connected";
2907
+ }
2908
+ function gatewayMessagesMessagesCapacity() {
2909
+ return "The gateway holds as many queued bytes as it can";
2910
+ }
2911
+ function gatewayMessagesFailuresPeerUnavailable(placeholders) {
2912
+ return `No subscriber for ${placeholders.channel}: the service that answers it is not connected`;
2913
+ }
2914
+ function gatewayMessagesChallengesNoCredential(placeholders) {
2915
+ return `Bearer resource_metadata="${placeholders.origin}/.well-known/oauth-protected-resource"`;
2916
+ }
2917
+ function gatewayMessagesChallengesRefused(placeholders) {
2918
+ return `Bearer error="invalid_token", resource_metadata="${placeholders.origin}/.well-known/oauth-protected-resource"`;
2919
+ }
2920
+ function serviceEnvironmentBootRefusalsLine(placeholders) {
2921
+ return `[fatal] ${placeholders.refusal}`;
2922
+ }
2923
+ function serviceEnvironmentBootRefusalsRefusalsUnnamed(placeholders) {
2924
+ return `The ${placeholders.service}'s configuration document is not named: start it with --config <path>`;
2925
+ }
2926
+ function serviceEnvironmentBootRefusalsRefusalsUnreadable(placeholders) {
2927
+ return `Cannot read the ${placeholders.service}'s configuration document at ${placeholders.path} (${placeholders.reason}). The launcher writes it; a ${placeholders.service} started another way is given one (${placeholders.schema} in protocol/specs/).`;
2928
+ }
2929
+ function serviceEnvironmentBootRefusalsRefusalsNotJson(placeholders) {
2930
+ return `${placeholders.path} is not JSON: ${placeholders.reason}`;
2931
+ }
2932
+ function serviceEnvironmentBootRefusalsRefusalsInvalid(placeholders) {
2933
+ return `${placeholders.path} is not a ${placeholders.service} configuration document (${placeholders.schema}):
2934
+ ${placeholders.members}`;
2935
+ }
2936
+ function serviceEnvironmentBootRefusalsRefusalsNoServiceAccount(placeholders) {
2937
+ return `${placeholders.missing} not set \u2014 this ${placeholders.service} has no service account to sign in with.
2938
+ The launcher passes both for each service it starts; a ${placeholders.service} started another way needs the client its realm registers for it (XYNOLOG_OIDC_CLIENT_ID=xynolog-${placeholders.service}).`;
2939
+ }
2940
+ function serviceEnvironmentBootRefusalsRefusalsUnset(placeholders) {
2941
+ return `${placeholders.field} names the environment variable ${placeholders.name}, which is not set`;
2942
+ }
2943
+ function serviceEnvironmentBootRefusalsMembersMissing(placeholders) {
2944
+ return ` ${placeholders.pointer} is missing ${placeholders.member}`;
2945
+ }
2946
+ function serviceEnvironmentBootRefusalsMembersUndeclared(placeholders) {
2947
+ return ` ${placeholders.pointer} does not declare ${placeholders.members}`;
2948
+ }
2949
+ function serviceEnvironmentBootRefusalsMembersOther(placeholders) {
2950
+ return ` ${placeholders.pointer} ${placeholders.why}`;
2951
+ }
2952
+ function serviceTelemetryLogLinesLoggerSimple(placeholders) {
2953
+ return `${placeholders.timestamp} [${placeholders.level}] ${placeholders.message}`;
2954
+ }
2955
+ function serviceTelemetryLogLinesSupervisorLine(placeholders) {
2956
+ return `[supervise ${placeholders.time}] starting ${placeholders.name} (rapid failures so far: ${placeholders.count})`;
2957
+ }
2958
+ function serviceTelemetryLogLinesSupervisorCounted(placeholders) {
2959
+ return `starting ${placeholders.name}`;
2960
+ }
2961
+ function serviceTelemetryMessagesLoggedConfirmedFieldsDomain(placeholders) {
2962
+ return `${placeholders.domain}`;
2963
+ }
2964
+ function serviceTelemetryMessagesLoggedConfirmedFieldsDid(placeholders) {
2965
+ return `${placeholders.did}`;
2966
+ }
2967
+ function serviceTelemetryTelemetryResourceServiceName(placeholders) {
2968
+ return `xynolog-${placeholders.service}`;
2969
+ }
2970
+ function smelterMessagesRefusalsRebuildIncomplete(placeholders) {
2971
+ return `${placeholders.failed} of ${placeholders.total} resources failed to re-anchor: see the Smelter's log`;
2972
+ }
2973
+ function smelterMessagesLoggedNotIndexedFieldsResourceId(placeholders) {
2974
+ return `${placeholders.resourceId}`;
2975
+ }
2976
+ function smelterMessagesLoggedNotIndexedFieldsReason(placeholders) {
2977
+ return `${placeholders.reason}`;
2978
+ }
2979
+ function smelterMessagesLoggedNotIndexedFieldsContentType(placeholders) {
2980
+ return `${placeholders.mediaType}`;
2981
+ }
2982
+ function smelterMessagesLoggedNotIndexedFieldsContentChecksum(placeholders) {
2983
+ return `${placeholders.checksum}`;
2984
+ }
2985
+ function smelterMessagesLoggedContentUnreadFieldsResourceId(placeholders) {
2986
+ return `${placeholders.resourceId}`;
2987
+ }
2988
+ function smelterMessagesLoggedEventFailedFieldsResourceId(placeholders) {
2989
+ return `${placeholders.resourceId}`;
2990
+ }
2991
+ function smelterMessagesLoggedEventFailedFieldsProvider(placeholders) {
2992
+ return `${placeholders.provider}`;
2993
+ }
2994
+ function smelterMessagesLoggedEventFailedFieldsModel(placeholders) {
2995
+ return `${placeholders.model}`;
2996
+ }
2997
+ function smelterMessagesLoggedEventFailedFieldsStatus(placeholders) {
2998
+ return `${placeholders.status}`;
2999
+ }
3000
+ function workerMessagesBootInvalid(placeholders) {
3001
+ return `${placeholders.path} is not a worker configuration document (WorkerConfig):
3002
+ ${placeholders.reasons}`;
3003
+ }
3004
+ function workerMessagesBootKeyUnset() {
3005
+ return "XYNOLOG_OIDC_CLIENT_KEY is not set in the worker's environment: a worker signs in as a service account";
3006
+ }
3007
+ function workerMessagesBootKeyUnreadable() {
3008
+ return "XYNOLOG_OIDC_CLIENT_KEY in the worker's environment is not an unencrypted PEM private key";
3009
+ }
3010
+ function workerMessagesBootKeyNotRsa() {
3011
+ return "XYNOLOG_OIDC_CLIENT_KEY in the worker's environment is not an RSA key: a worker signs its assertions with RS256";
3012
+ }
3013
+ function workerMessagesBootApiKeyUnset(placeholders) {
3014
+ return `knowledgeBases[${placeholders.knowledgeBase}].engines[${placeholders.engine}].apiKeyEnv names a variable that is not set in the worker's environment`;
3015
+ }
3016
+ function workerMessagesBootDomainTwice(placeholders) {
3017
+ return `knowledgeBases[${placeholders.later}].domain is the domain of knowledgeBases[${placeholders.earlier}]: a worker serves a knowledge base once`;
3018
+ }
3019
+ function workerMessagesBootNoneAdmits() {
3020
+ return "No knowledge base admits this worker: each of its knowledgeBases refused it";
3021
+ }
3022
+ function workerMessagesBootCannotListen(placeholders) {
3023
+ return `Cannot listen on port ${placeholders.port}: ${placeholders.why}`;
3024
+ }
3025
+ function workerMessagesReasonsMissing(placeholders) {
3026
+ return ` Missing required property: ${placeholders.member}`;
3027
+ }
3028
+ function workerMessagesReasonsOther(placeholders) {
3029
+ return ` ${placeholders.member}: is not what the schema states`;
3030
+ }
3031
+ function workerMessagesJobMark(placeholders) {
3032
+ return `mark (${placeholders.motivation})`;
3033
+ }
3034
+ function workerMessagesErrorsUnextractable(placeholders) {
3035
+ return `Cannot run ${placeholders.job} on resource ${placeholders.resourceId}: media type '${placeholders.mediaType}' has no extractable text to analyze`;
3036
+ }
3037
+ function workerMessagesErrorsNotSettled(placeholders) {
3038
+ return `Anchored text not yet derived for resource ${placeholders.resourceId} \u2014 Smelter has not settled; retrying`;
3039
+ }
3040
+ function workerMessagesErrorsAnchoredDeclined(placeholders) {
3041
+ return `Cannot run ${placeholders.job} on resource ${placeholders.resourceId}: anchored-text consult returned '${placeholders.declined}'`;
3042
+ }
3043
+ function workerMessagesErrorsNotServed(placeholders) {
3044
+ return `Worker not configured for job: ${placeholders.job}`;
3045
+ }
3046
+ function workerMessagesErrorsNoProcessor(placeholders) {
3047
+ return `No processor for job: ${placeholders.job}`;
3048
+ }
3049
+ function workerMessagesErrorsWindowTooSmall(placeholders) {
3050
+ return `Inference window too small for detection: context ${placeholders.contextTokens} tokens minus scaffold ${placeholders.scaffoldTokens} leaves an input budget of ${placeholders.inputBudget} (need > 64). Use a model with a larger context window or reduce the prompt scaffold.`;
3051
+ }
3052
+ function workerMessagesErrorsOllamaRefused(placeholders) {
3053
+ return `Ollama API error (${placeholders.status}): ${placeholders.body}`;
3054
+ }
3055
+ function workerMessagesErrorsAnthropicRefused(placeholders) {
3056
+ return `${placeholders.said}`;
3057
+ }
3058
+ function workerMessagesErrorsUnreadable(placeholders) {
3059
+ return `Structured response could not be read: ${placeholders.detail} (stop_reason: ${placeholders.stopReason})`;
3060
+ }
3061
+ function workerMessagesErrorsWaitStated(placeholders) {
3062
+ return `${placeholders.failure}; the provider said to wait (${placeholders.said}), which is longer than the 120 seconds this driver waits`;
3063
+ }
3064
+ function workerMessagesErrorsWithheld(placeholders) {
3065
+ return `The provider withheld its answer: refusal${placeholders.why}`;
3066
+ }
3067
+ function workerMessagesErrorsNoStructuredOutputs(placeholders) {
3068
+ return `Model '${placeholders.model}' does not report support for strict structured outputs (Models API capabilities.structured_outputs). It is refused: a generation the provider does not hold to the schema can come back unreadable. Give the agent that does this work a model that reports supported: true.`;
3069
+ }
3070
+ function workerMessagesErrorsOllamaLimitsRefused(placeholders) {
3071
+ return `Failed to discover model limits for '${placeholders.model}' from Ollama's /api/show: refused with status ${placeholders.status}: ${placeholders.said}`;
3072
+ }
3073
+ function workerMessagesErrorsAnthropicLimitsRefused(placeholders) {
3074
+ return `Failed to discover model limits for '${placeholders.model}' from the Models API: refused with status ${placeholders.status}: ${placeholders.said}`;
3075
+ }
3076
+ function workerMessagesErrorsNoContextLength(placeholders) {
3077
+ return `/api/show reports no context length for '${placeholders.model}'`;
3078
+ }
3079
+ function workerMessagesErrorsUnsupportedOutput(placeholders) {
3080
+ return `Unsupported outputMediaType for generation: ${placeholders.mediaType}. Generation produces ${placeholders.generatable}.`;
3081
+ }
3082
+ function workerMessagesErrorsOverWindow(placeholders) {
3083
+ return `The prompt (~${placeholders.promptTokens} tokens) and the ${placeholders.maxTokens} tokens asked for are together over the context window of '${placeholders.model}' (${placeholders.contextTokens} tokens)`;
3084
+ }
3085
+ function workerMessagesDetailsNotJson() {
3086
+ return "response is not valid JSON";
3087
+ }
3088
+ function workerMessagesDetailsNotArray(placeholders) {
3089
+ return `parsed to ${placeholders.kind}, not an array`;
3090
+ }
3091
+ function workerMessagesDetailsEmpty() {
3092
+ return "response is empty";
3093
+ }
3094
+ function workerMessagesWaitsSeconds(placeholders) {
3095
+ return `retry-after: ${placeholders.seconds}`;
3096
+ }
3097
+ function workerMessagesWaitsMilliseconds(placeholders) {
3098
+ return `retry-after-ms: ${placeholders.milliseconds}`;
3099
+ }
3100
+ function workerMessagesLoggedRefusedFieldsDomain(placeholders) {
3101
+ return `${placeholders.domain}`;
3102
+ }
3103
+ function workerMessagesLoggedTroubleFieldsDomain(placeholders) {
3104
+ return `${placeholders.domain}`;
3105
+ }
3106
+
3107
+ // src/sign-in.ts
2214
3108
  var OWNER_ONLY_DIRECTORY_MODE = 448;
2215
3109
  var OWNER_ONLY_FILE_MODE = 384;
2216
3110
  function ownerOnlyDirectoryAccessList(owner) {
@@ -3534,16 +4428,18 @@ function kbResource(domain) {
3534
4428
  return `https://${domain.split(":").join("/")}`;
3535
4429
  }
3536
4430
 
3537
- // src/client-assertion.ts
4431
+ // src/client-assertion-facts.ts
3538
4432
  var JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
3539
4433
  var LIFETIME_SECONDS = 60;
4434
+
4435
+ // src/client-assertion.ts
3540
4436
  var RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
3541
4437
  var PKCS8_PEM = /^-----BEGIN PRIVATE KEY-----([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----$/;
3542
4438
  var NOT_PKCS8_PEM = "The key is not a PKCS#8 PEM private key: one that begins `-----BEGIN PRIVATE KEY-----`";
3543
4439
  var NOT_RSA = "The PEM holds no RSA private key: a service account signs its assertions with RS256";
3544
4440
  var NOT_RS256 = "The key does not sign RS256 (RSASSA-PKCS1-v1_5 with SHA-256): read it with `privateKeyFromPem`";
3545
4441
  var utf8 = new TextEncoder();
3546
- var segment = (value) => base64url(utf8.encode(JSON.stringify(value)));
4442
+ var segment = (value) => base64url(utf8.encode(JSON.stringify(value, refuseNonFinite)));
3547
4443
  function thumbprint({ n, e }) {
3548
4444
  return base64url(sha256(utf8.encode(`{"e":"${e}","kty":"RSA","n":"${n}"}`)));
3549
4445
  }
@@ -3618,6 +4514,45 @@ var SignInError = class extends Error {
3618
4514
  status;
3619
4515
  };
3620
4516
 
4517
+ // src/token-renewal.ts
4518
+ function decodeBase64Url(segment2) {
4519
+ const base64 = segment2.replace(/-/g, "+").replace(/_/g, "/");
4520
+ const padded = base64.padEnd(
4521
+ base64.length + (4 - base64.length % 4) % 4,
4522
+ "="
4523
+ );
4524
+ const binary = atob(padded);
4525
+ const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
4526
+ return new TextDecoder().decode(bytes);
4527
+ }
4528
+ function jwtPayload(token) {
4529
+ try {
4530
+ const parts = token.split(".");
4531
+ if (parts.length !== 3 || !parts[1]) return null;
4532
+ return JSON.parse(decodeBase64Url(parts[1]));
4533
+ } catch {
4534
+ return null;
4535
+ }
4536
+ }
4537
+ function secondsClaim(token, name) {
4538
+ const payload = jwtPayload(token);
4539
+ if (!isObject(payload)) return void 0;
4540
+ const claim = payload[name];
4541
+ return typeof claim === "number" && Number.isFinite(claim) ? claim : void 0;
4542
+ }
4543
+ function renewalDelayMs(lifetimeMs, remainingMs) {
4544
+ const marginMs = Math.min(REFRESH_BEFORE_EXP_MS, Math.max(0, lifetimeMs) / 2);
4545
+ return Math.max(MIN_REFRESH_DELAY_MS, remainingMs - marginMs);
4546
+ }
4547
+ function refreshDelayMs(token, now = Date.now()) {
4548
+ const exp = secondsClaim(token, "exp");
4549
+ if (!exp) return null;
4550
+ const expMs = exp * 1e3;
4551
+ const iat = secondsClaim(token, "iat");
4552
+ const lifetimeMs = iat ? (exp - iat) * 1e3 : expMs - now;
4553
+ return renewalDelayMs(lifetimeMs, expMs - now);
4554
+ }
4555
+
3621
4556
  // src/unanswered.ts
3622
4557
  var IDENTIFIER = /^[A-Za-z][A-Za-z0-9_]*$/;
3623
4558
  function kind(value) {
@@ -3628,7 +4563,7 @@ function whyUnanswered(error) {
3628
4563
  const cause = isObject(error["cause"]) ? error["cause"] : void 0;
3629
4564
  return kind(cause?.["code"]) ?? kind(cause?.["name"]) ?? kind(error["name"]) ?? "Error";
3630
4565
  }
3631
- var UnansweredError = class extends XynologError {
4566
+ var UnansweredError = class extends TransportError {
3632
4567
  /** `what` names the request. `error` is what `fetch`, or the read of its answer's body, rejected with. */
3633
4568
  constructor(what, error) {
3634
4569
  super(`${what} got no answer: ${whyUnanswered(error)}`, "unavailable");
@@ -3649,7 +4584,6 @@ async function jsonOf(response, unanswered) {
3649
4584
  function fetchOf(given) {
3650
4585
  return (...request) => (given ?? globalThis.fetch)(...request);
3651
4586
  }
3652
- var RENEW_BEFORE_EXPIRY_MS = 3e4;
3653
4587
  async function proof(credential, endpoint) {
3654
4588
  if ("clientSecret" in credential) {
3655
4589
  return new URLSearchParams({
@@ -3674,11 +4608,13 @@ async function proof(credential, endpoint) {
3674
4608
  });
3675
4609
  }
3676
4610
  var ServiceToken = class {
3677
- constructor(credential, fetch) {
4611
+ constructor(credential, timing, fetch) {
3678
4612
  this.credential = credential;
4613
+ this.timing = timing;
3679
4614
  this.fetch = fetch;
3680
4615
  }
3681
4616
  credential;
4617
+ timing;
3682
4618
  fetch;
3683
4619
  endpoint = null;
3684
4620
  held = null;
@@ -3696,7 +4632,7 @@ var ServiceToken = class {
3696
4632
  );
3697
4633
  const unanswered = (error) => new UnansweredError(`OIDC discovery for ${issuer}`, error);
3698
4634
  const document = await withinDeadline(
3699
- HTTP_REQUEST_TIMEOUT_MS,
4635
+ this.timing.httpRequestTimeoutMs,
3700
4636
  async (signal) => {
3701
4637
  const response = await fetchOf(this.fetch)(url, { signal }).catch(
3702
4638
  (error) => {
@@ -3736,8 +4672,9 @@ var ServiceToken = class {
3736
4672
  * carrying the status the issuer answered with; a request that got no
3737
4673
  * answer is an `UnansweredError`.
3738
4674
  *
3739
- * Both requests, the issuer's discovery and the grant, are bounded by
3740
- * `httpRequestTimeoutMs` (protocol/specs/src/client/timing.json): an issuer that
4675
+ * Both requests, the issuer's discovery and the grant, are bounded by the
4676
+ * `httpRequestTimeoutMs` of the timing this was made with
4677
+ * (protocol/specs/src/client/timing.json): an issuer that
3741
4678
  * accepts a connection and never answers would otherwise hold a process's
3742
4679
  * start, and every renewal after it, for as long as the process lives. Both
3743
4680
  * are sent with the `fetch` this was made with, or the runtime's own.
@@ -3753,7 +4690,7 @@ var ServiceToken = class {
3753
4690
  /** `token`, in its turn. */
3754
4691
  async granted(renewed) {
3755
4692
  const { issuer, clientId } = this.credential;
3756
- if (!renewed && this.held && this.held.expiresAt - RENEW_BEFORE_EXPIRY_MS > Date.now()) {
4693
+ if (!renewed && this.held && this.held.renewAt > Date.now()) {
3757
4694
  return this.held.token;
3758
4695
  }
3759
4696
  const endpoint = await this.tokenEndpoint();
@@ -3763,7 +4700,7 @@ var ServiceToken = class {
3763
4700
  error
3764
4701
  );
3765
4702
  const body = await withinDeadline(
3766
- HTTP_REQUEST_TIMEOUT_MS,
4703
+ this.timing.httpRequestTimeoutMs,
3767
4704
  async (signal) => {
3768
4705
  const response = await fetchOf(this.fetch)(endpoint, {
3769
4706
  method: "POST",
@@ -3791,11 +4728,34 @@ var ServiceToken = class {
3791
4728
  }
3792
4729
  const token = body["access_token"];
3793
4730
  const expiresIn = body["expires_in"];
3794
- this.held = typeof expiresIn === "number" && Number.isFinite(expiresIn) ? { token, expiresAt: Date.now() + expiresIn * 1e3 } : null;
4731
+ const now = Date.now();
4732
+ const lifetimeMs = typeof expiresIn === "number" && Number.isFinite(expiresIn) && expiresIn >= 0 ? expiresIn * 1e3 : void 0;
4733
+ const renewInMs = refreshDelayMs(token, now) ?? (lifetimeMs === void 0 ? null : renewalDelayMs(lifetimeMs, lifetimeMs));
4734
+ this.held = renewInMs === null ? null : {
4735
+ token,
4736
+ renewAt: now + (lifetimeMs === void 0 ? renewInMs : Math.min(renewInMs, lifetimeMs))
4737
+ };
3795
4738
  return token;
3796
4739
  }
3797
4740
  };
3798
4741
 
4742
+ // src/binary-text.ts
4743
+ function binaryText(bytes) {
4744
+ let binary = "";
4745
+ for (const byte of bytes) binary += String.fromCharCode(byte);
4746
+ return btoa(binary);
4747
+ }
4748
+ function binaryOf(text) {
4749
+ let binary;
4750
+ try {
4751
+ binary = atob(text);
4752
+ } catch {
4753
+ return void 0;
4754
+ }
4755
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
4756
+ return binaryText(bytes) === text ? bytes : void 0;
4757
+ }
4758
+
3799
4759
  // src/knowledge-graph-views.ts
3800
4760
  function deriveViews(graph, mainResourceId, focalAnnotationId) {
3801
4761
  const nodeById = new Map(
@@ -3847,11 +4807,6 @@ function deriveViews(graph, mainResourceId, focalAnnotationId) {
3847
4807
  function equalJitter(cap) {
3848
4808
  return cap / 2 + Math.random() * (cap / 2);
3849
4809
  }
3850
- var STARTUP_FETCH_RETRY = {
3851
- attempts: 8,
3852
- initialDelayMs: 1e3,
3853
- maxDelayMs: 8e3
3854
- };
3855
4810
  function isTransientFetchError(error) {
3856
4811
  if (!(error instanceof TypeError)) return false;
3857
4812
  if (error.message === "fetch failed") return true;
@@ -3867,7 +4822,7 @@ function isRetryableRequestError(error) {
3867
4822
  if (typeof error !== "object" || error === null) return false;
3868
4823
  if (error.name === "TimeoutError") return true;
3869
4824
  const status = error.status;
3870
- return typeof status === "number" && RETRY_RULES.boot.retryable({ status });
4825
+ return typeof status === "number" && RETRY_RULES2.boot.retryable({ status });
3871
4826
  }
3872
4827
  function waited(ms, signal) {
3873
4828
  return new Promise((resolve) => {
@@ -3886,7 +4841,7 @@ function waited(ms, signal) {
3886
4841
  signal?.addEventListener("abort", cutShort, { once: true });
3887
4842
  });
3888
4843
  }
3889
- async function retryWithBackoff(fn, isRetryable, policy, onRetry, signal) {
4844
+ async function retryWithBackoff(fn, isRetryable, policy, signal) {
3890
4845
  signal?.throwIfAborted();
3891
4846
  let cap = policy.initialDelayMs;
3892
4847
  for (let attempt = 1; ; attempt++) {
@@ -3900,7 +4855,6 @@ async function retryWithBackoff(fn, isRetryable, policy, onRetry, signal) {
3900
4855
  equalJitter(cap),
3901
4856
  typeof stated === "number" ? stated : 0
3902
4857
  );
3903
- onRetry?.({ attempt, attempts: policy.attempts, delayMs, error });
3904
4858
  if (!await waited(delayMs, signal)) throw error;
3905
4859
  cap = Math.min(cap * 2, policy.maxDelayMs);
3906
4860
  }
@@ -3910,6 +4864,6 @@ async function retryWithBackoff(fn, isRetryable, policy, onRetry, signal) {
3910
4864
  // src/discovery.ts
3911
4865
  var DISCOVERY_URL_PATH = "/discovery/kbs.json";
3912
4866
 
3913
- export { AUTHORABLE_MEDIA_TYPES, BROWSER_CLIENT_ID, CACHE_PER, CACHE_QUERIES, CACHE_REFRESH, CACHE_REFRESH_CHANNELS, CACHE_VALUES, CHANNEL_ATTRS, DISCOVERY_URL_PATH, GENERATABLE_MEDIA_TYPES, JOBS_BUCKET, JOBS_CONSUMER, JOBS_STREAM, JOBS_STREAM_SUBJECTS, JOBS_SUBJECT_ROOT, JOB_TYPES, JWTTokenSchema, LIMITS_OPERATIONS, LOCALES, LOCALE_CODES, MARK_MOTIVATIONS, MEDIA_TYPES, OWNER_ONLY_DIRECTORY_MODE, OWNER_ONLY_FILE_MODE, PERSISTED_EVENT_TYPES, PERSISTED_QUERIES, RETRY_RULES, SCRIPT_CLIENT_ID, SIGN_IN_SCOPE, SIGN_IN_STORE_FILE, SIGN_IN_STORE_LOCK, SIGN_IN_STORE_WINDOWS_OFFSET_HIGH, STARTUP_FETCH_RETRY, ServiceToken, SignInError, SpanRefusedError, UnansweredError, anchorAnnotation, annotationOfResource, annotationOfSpan, baseMediaType, capabilitiesOf, channelAttrsOf, channelWrites, cloneFormat, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, decodeRepresentation, decodeWithCharset, deriveStorageUri, deriveViews, derivesTextOf, equalJitter, extensionForMediaType, extractContext, folderOf, formatLocaleDisplay, gatewayApiKeys, gatewayHeaders, gatewayRoutes, getAnnotationExactText, getAnnotationIdFromEvent, getBodySource, getCommentText, getEntityTypes, getExactText, getFragmentSelector, getLanguage, getPrimaryMediaType, getPrimaryRepresentation, getResourceEntityTypes, getResourceId, getStorageUri, getSvgSelector, getTagCategory, getTagSchemaId, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, isArchived, isAssessment, isBodyResolved, isComment, isDraft, isHighlight, isReference, isResolvedReference, isRetryableRequestError, isSignIn, isStubReference, isSupportedMediaType, isTag, isValidEmail, jobMatchesFilter, jobSubject, jsonOf, kbDid, kbResource, locate, mediaTypeForExtension, ownerOnlyDirectoryAccessList, ownerOnlyFileAccessList, parseFragmentSelector, parseSvgSelector, privateKeyFromPem, proposeStoragePath, reconcile, retryAfterMs, retryWithBackoff, scaleSvgToNative, storageFileName, textOffsets, textSourceOf, textUnder, validateData, watched, whyUnanswered, withinDeadline, yieldsGeometryOf };
4867
+ export { ACTIVE_KEY, AUTHORABLE_MEDIA_TYPES, BROWSER_CLIENT_ID, CACHE_DOCUMENT_VERSION, CACHE_KEY_PREFIX, CACHE_PER, CACHE_QUERIES, CACHE_REFRESH, CACHE_REFRESH_CHANNELS, CACHE_VALUES, CHANNEL_ATTRS, CONTROL_API_VERSION, CONTROL_METHODS, CONTROL_NOTIFICATIONS, CONTROL_SERVICE_GROUPS, DISCOVERY_URL_PATH, GENERATABLE_MEDIA_TYPES, JOBS_BUCKET, JOBS_CONSUMER, JOBS_STREAM, JOBS_STREAM_SUBJECTS, JOBS_SUBJECT_ROOT, JOB_TYPES, JWTTokenSchema, LAST_EVENT_ID_KEY_PREFIX, LAST_VIEWED_RESOURCE_BY_KB_KEY, LIMITS_OPERATIONS, LOCALES, LOCALE_CODES, MARK_MOTIVATIONS, MEDIA_TYPES, OPEN_RESOURCES_BY_KB_KEY, OWNER_ONLY_DIRECTORY_MODE, OWNER_ONLY_FILE_MODE, PENDING_AUTHORIZATION_KEY, PERSISTED_EVENT_PAYLOADS, PERSISTED_EVENT_TYPES, PERSISTED_QUERIES, RETRY_RULES2 as RETRY_RULES, SCRIPT_CLIENT_ID, SESSION_KEY_PREFIX, SIGN_IN_SCOPE, SIGN_IN_STORE_FILE, SIGN_IN_STORE_LOCK, SIGN_IN_STORE_WINDOWS_OFFSET_HIGH, STORAGE_KEY, ServiceToken, SignInError, SpanRefusedError, UnansweredError, WHOLE_KEY, anchorAnnotation, annotationOfResource, annotationOfSpan, archivistLayoutAnchoredTextEntryPath, archivistLayoutEventFileName, archivistLayoutEventStreamPath, archivistLayoutStorageUriIndexPath, archivistLayoutViewPath, archivistMessagesBootGatewayElsewhere, archivistMessagesBootGatewaySilent, archivistMessagesBootNoProjectFile, archivistMessagesBootNotACheckout, archivistMessagesHttpAnchoredTextNoEntry, archivistMessagesHttpAnchoredTextNotAWrite, archivistMessagesHttpAnchoredTextReadFailed, archivistMessagesHttpAnchoredTextStoredNotFound, archivistMessagesHttpAnchoredTextWriteNotFound, archivistMessagesHttpAnnotationsNotFound, archivistMessagesHttpContentNoRepresentation, archivistMessagesHttpContentNoResource, archivistMessagesHttpContentReadFailed, archivistMessagesHttpEventReadFailed, archivistMessagesHttpEventsBadRequest, archivistMessagesHttpJsonldNotFound, archivistMessagesHttpStreamListingFailed, archivistMessagesHttpUploadKeyReused, archivistMessagesHttpUploadNotMultipart, archivistMessagesHttpUploadRefused, archivistMessagesHttpUploadUnattributed, archivistMessagesHttpUploadUnsupportedMedia, archivistMessagesLoggedNotAnEventFieldsWhat, archivistMessagesRefusalsAnnotationNotFound, archivistMessagesRefusalsAnnotationWithCreator, archivistMessagesRefusalsChecksumMismatch, archivistMessagesRefusalsCloneContentNotFound, archivistMessagesRefusalsCloneSourceNotFound, archivistMessagesRefusalsEntityTypeNotRegistered, archivistMessagesRefusalsExecutorNotSoftware, archivistMessagesRefusalsGeneratorNotExecutor, archivistMessagesRefusalsInvalidToken, archivistMessagesRefusalsMultiAgentAnnotation, archivistMessagesRefusalsMultiAgentCreate, archivistMessagesRefusalsNotAnnotatable, archivistMessagesRefusalsNotTheHolder, archivistMessagesRefusalsPathEscapes, archivistMessagesRefusalsPathNotFound, archivistMessagesRefusalsResourceNotFound, archivistMessagesRefusalsSourcelessCreate, archivistMessagesRefusalsStorageUriOutside, archivistMessagesRefusalsStorageUriScheme, archivistMessagesRefusalsTokenExpired, archivistMessagesRefusalsTokenSourceNotFound, archivistMessagesRefusalsUnarchiveWithoutFile, archivistMessagesRefusalsUnassignedJob, archivistMessagesRefusalsUncitedWorker, archivistMessagesUnsentNotSent, archivistMessagesUnsentTooLarge, archivistRoutes, base64url, baseMediaType, binaryOf, binaryText, byteSourceOf, capabilitiesOf, channelAttrsOf, channelWrites, cloneFormat, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, decodeRepresentation, decodeWithCharset, deriveStorageUri, deriveViews, derivesTextOf, dispatcherMessagesErrorsPresumedDead, dispatcherMessagesRefusalsClaimWithoutUser, dispatcherMessagesRefusalsCreateWithoutUser, dispatcherMessagesRefusalsEntityTypeNotRegistered, dispatcherMessagesRefusalsJobNotFound, dispatcherMessagesRefusalsNonePending, dispatcherMessagesRefusalsNotAWorker, dispatcherMessagesRefusalsTagSchemaNotRegistered, dispatcherMessagesRefusalsYieldParameter, equalJitter, extensionForMediaType, extractContext, folderOf, formatLocaleDisplay, gatewayApiKeys, gatewayMediaTokenClaimsIss, gatewayMediaTokenClaimsSub, gatewayMessagesChallengesNoCredential, gatewayMessagesChallengesRefused, gatewayMessagesFailuresPeerUnavailable, gatewayMessagesMessagesCapacity, gatewayMessagesMessagesContentStoreUnavailable, gatewayMessagesMessagesCorrelationClaimed, gatewayMessagesMessagesCorrelationWithoutClient, gatewayMessagesMessagesDuplicateScope, gatewayMessagesMessagesEmitRate, gatewayMessagesMessagesIdempotencyKeyLength, gatewayMessagesMessagesIdempotencyKeyNotText, gatewayMessagesMessagesIdempotencyKeyReused, gatewayMessagesMessagesInternal, gatewayMessagesMessagesInvalidPayload, gatewayMessagesMessagesNoCredential, gatewayMessagesMessagesNoIdempotencyKey, gatewayMessagesMessagesNoSubscription, gatewayMessagesMessagesNotFound, gatewayMessagesMessagesNotJson, gatewayMessagesMessagesPlaneUnavailable, gatewayMessagesMessagesRefusalRate, gatewayMessagesMessagesRefusedMediaToken, gatewayMessagesMessagesRefusedToken, gatewayMessagesMessagesRepresentationNotFound, gatewayMessagesMessagesResourceNotFound, gatewayMessagesMessagesStreams, gatewayMessagesMessagesTooLarge, gatewayMessagesMessagesUnansweredRequests, gatewayMessagesMessagesUnknownChannel, gatewayRequestHeaders, gatewayResponseHeaders, gatewayRoutes, getAnnotationExactText, getAnnotationIdFromEvent, getBodySource, getCommentText, getEntityTypes, getExactText, getFragmentSelector, getLanguage, getPrimaryMediaType, getPrimaryRepresentation, getResourceEntityTypes, getResourceId, getStorageUri, getSvgSelector, getTagCategory, getTagSchemaId, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, heldOf, isArchived, isAssessment, isBodyResolved, isComment, isDraft, isHighlight, isReference, isResolvedReference, isRetryableRequestError, isStubReference, isSupportedMediaType, isTag, isValidEmail, jobMatchesFilter, jobSubject, jsonOf, jwtPayload, kbDid, kbResource, lengthOf, locate, mediaTypeForExtension, openSource, ownerOnlyDirectoryAccessList, ownerOnlyFileAccessList, parseFragmentSelector, parseSvgSelector, privateKeyFromPem, proposeStoragePath, reconcile, refreshDelayMs, refuseNonFinite, releaseFailure, renewalDelayMs, retryAfterMs, retryWithBackoff, scaleSvgToNative, secondsClaim, serviceEnvironmentBootRefusalsLine, serviceEnvironmentBootRefusalsMembersMissing, serviceEnvironmentBootRefusalsMembersOther, serviceEnvironmentBootRefusalsMembersUndeclared, serviceEnvironmentBootRefusalsRefusalsInvalid, serviceEnvironmentBootRefusalsRefusalsNoServiceAccount, serviceEnvironmentBootRefusalsRefusalsNotJson, serviceEnvironmentBootRefusalsRefusalsUnnamed, serviceEnvironmentBootRefusalsRefusalsUnreadable, serviceEnvironmentBootRefusalsRefusalsUnset, serviceTelemetryLogLinesLoggerSimple, serviceTelemetryLogLinesSupervisorCounted, serviceTelemetryLogLinesSupervisorLine, serviceTelemetryMessagesLoggedConfirmedFieldsDid, serviceTelemetryMessagesLoggedConfirmedFieldsDomain, serviceTelemetryTelemetryResourceServiceName, sha256, smelterMessagesLoggedContentUnreadFieldsResourceId, smelterMessagesLoggedEventFailedFieldsModel, smelterMessagesLoggedEventFailedFieldsProvider, smelterMessagesLoggedEventFailedFieldsResourceId, smelterMessagesLoggedEventFailedFieldsStatus, smelterMessagesLoggedNotIndexedFieldsContentChecksum, smelterMessagesLoggedNotIndexedFieldsContentType, smelterMessagesLoggedNotIndexedFieldsReason, smelterMessagesLoggedNotIndexedFieldsResourceId, smelterMessagesRefusalsRebuildIncomplete, sourceFailure, storageFileName, textOffsets, textSourceOf, textUnder, validateData, watched, whyUnanswered, withinDeadline, workerMessagesBootApiKeyUnset, workerMessagesBootCannotListen, workerMessagesBootDomainTwice, workerMessagesBootInvalid, workerMessagesBootKeyNotRsa, workerMessagesBootKeyUnreadable, workerMessagesBootKeyUnset, workerMessagesBootNoneAdmits, workerMessagesDetailsEmpty, workerMessagesDetailsNotArray, workerMessagesDetailsNotJson, workerMessagesErrorsAnchoredDeclined, workerMessagesErrorsAnthropicLimitsRefused, workerMessagesErrorsAnthropicRefused, workerMessagesErrorsNoContextLength, workerMessagesErrorsNoProcessor, workerMessagesErrorsNoStructuredOutputs, workerMessagesErrorsNotServed, workerMessagesErrorsNotSettled, workerMessagesErrorsOllamaLimitsRefused, workerMessagesErrorsOllamaRefused, workerMessagesErrorsOverWindow, workerMessagesErrorsUnextractable, workerMessagesErrorsUnreadable, workerMessagesErrorsUnsupportedOutput, workerMessagesErrorsWaitStated, workerMessagesErrorsWindowTooSmall, workerMessagesErrorsWithheld, workerMessagesJobMark, workerMessagesLoggedRefusedFieldsDomain, workerMessagesLoggedTroubleFieldsDomain, workerMessagesReasonsMissing, workerMessagesReasonsOther, workerMessagesWaitsMilliseconds, workerMessagesWaitsSeconds, yieldsGeometryOf };
3914
4868
  //# sourceMappingURL=index.js.map
3915
4869
  //# sourceMappingURL=index.js.map