@hugex/artifact 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -162,6 +162,27 @@ require a new OAuth consent. The dedicated Workers consent labels must be integr
162
162
  owner before release.
163
163
 
164
164
 
165
+ ## First view
166
+
167
+ `artifact.json` may set `loading`. Without it, the artifact shows the generic overlay (`mode: "auto"`) until `window` `load` or `hx.ready()`, and Tailwind plus the catalog scripts keep the previous blocking order. `defer` is applied only when `loading` is present and its mode is not `none`. An invalid `loading` value on an already published version is ignored; `libs` and `theme` still apply, and that version can be rolled back. A write or publish of new content still rejects invalid `loading`.
168
+
169
+ ```json
170
+ { "title": "Demo", "libs": [], "loading": { "mode": "auto", "page": "loading.html" } }
171
+ ```
172
+
173
+ - `auto`: the overlay leaves on `load` (10s cap) or sooner when the page calls `hx.ready()`. SPAs should call `hx.ready()` after the first useful render.
174
+ - `manual`: only `hx.ready()` removes it (15s cap). The cap logs `hx.ready() not called (manual)`.
175
+ - `none`: no overlay.
176
+ - `page` is opt-in. A file named `loading.html` is served as a normal file until the manifest names it. The page must be `.html`, not `index.html`, `server.js`, `artifact.json` or anything under `__hx/`, UTF-8, and at most 32 KiB. It is shown in a sandboxed iframe (`srcdoc`, no scripts, no forms, no same origin). Relative image URLs resolve against the artifact `<base>` without `crossorigin`; `data:` URLs also work.
177
+ - The overlay is mounted from an inline script before the Tailwind CDN script. Colors follow `theme` (`hugex` or `none`) and `prefers-color-scheme`. The status string is chosen from `Accept-Language` (`es` or `en`) on the server.
178
+
179
+ ## Usage stats
180
+
181
+ GET document navigations (not HEAD, POST, prefetch, prerender or iframes) record `view`. Bots increment `view_bot` instead, and do not move `view`, `view_key` or `lastViewDay`. From this change onward, days also store dimensions (country, region, device, browser, os, referrer, language; top values plus `other`) and a daily unique count. `uniques` in a range is the sum of those days, not a cross-day dedupe. `series[].coverage` is false for days that predate capture, so a zero is not "no traffic". `dimensionsSince` is the first day with dimensions. A referrer that is an IPv4 or IPv6 literal is stored as `other`.
182
+
183
+ Usage statistics do not store IP or User-Agent. Uniques use a daily identifier derived from them with a salt that rotates at the next UTC midnight. Request headers, including IP and User-Agent, are still forwarded to `server.js`. What the artifact's own code writes to logs is the author's responsibility. The salt and the day's hashes are deleted on the next wake after midnight, including for an idle artifact. Storage stays under 10 MB (90 days, 30 values per dimension, 20 000 visitors per day).
184
+
185
+
165
186
  ## Package version
166
187
 
167
188
  `runtimeId` includes the package version. The build defines the identifier `__ARTIFACT_PKG_VERSION__` from `ora/scripts/artifact-version.json`. Runtime code should use:
@@ -10,8 +10,24 @@ import type { AllowsWorkerInput, AllowsWorkerResult, ArtifactEnv, ArtifactFile,
10
10
  export declare class ArtifactDO extends DurableObject<ArtifactEnv> implements ArtifactRpc {
11
11
  /** Bumped when an activation window expires so a late health check cannot publish. */
12
12
  private activationGen;
13
+ /** Bumped at the start of every activation or deletion to invalidate in-flight lazy facet starts. */
14
+ private facetEpoch;
15
+ /** Emits `boot failed:` at most once per DO instance for the first failing current boot. */
16
+ private bootFailureLogged;
17
+ /** In-flight coordinated facet startup keyed by `(uuid, activeVersion, facetEpoch)`. */
18
+ private facetStart;
13
19
  /** UTC day of the last `daily_stat` prune, so `bump()` prunes at most once per day per instance. */
14
20
  private statsPrunedDay;
21
+ /** High-water mark so a replacement salt never reuses an epoch held by an in-flight hash. */
22
+ private saltEpochMem;
23
+ /** After a failed salt purge, the alarm waits until this absolute time. Cleared on a successful purge, a replacement, or a salt that is still valid. */
24
+ private saltPurgeBackoffMs;
25
+ private saltPurgeNotBefore;
26
+ /** Absolute index/ora retry deadlines. Recomputed only when a flush fails or on the first arm after a restart. */
27
+ private indexRetryAt;
28
+ private oraRetryAt;
29
+ /** `expiresAt` of the salt whose alarm was successfully armed. Null means the next view must try again. */
30
+ private saltAlarmExpiresAt;
15
31
  constructor(ctx: DurableObjectState, env: ArtifactEnv);
16
32
  alarm(): Promise<void>;
17
33
  create(input: CreateArtifactInput): Promise<{
@@ -86,7 +102,7 @@ export declare class ArtifactDO extends DurableObject<ArtifactEnv> implements Ar
86
102
  blobCount: number;
87
103
  versionCount: number;
88
104
  } | null>;
89
- private startFacetForDb;
105
+ private runFacetDbCall;
90
106
  query(sql: string, opts?: QueryOptions): Promise<QueryResult>;
91
107
  schema(opts?: SchemaOptions): Promise<SchemaResult>;
92
108
  fetch(request: Request): Promise<Response>;
@@ -123,14 +139,34 @@ export declare class ArtifactDO extends DurableObject<ArtifactEnv> implements Ar
123
139
  private runtimeId;
124
140
  private loadApp;
125
141
  private facetOf;
126
- /** Attach to the running facet, or start it. Does not abort. */
127
- private ensureFacet;
142
+ private sameFacetKey;
143
+ private facetKeyMatchesCurrent;
144
+ private accessChanged;
145
+ private logBootFailureOnce;
146
+ /**
147
+ * Coordinated lazy facet startup keyed by `(uuid, activeVersion, facetEpoch)`.
148
+ * Never aborts an active facet; discards stale results if an activation or deletion intervenes.
149
+ */
150
+ private startCurrentFacet;
128
151
  /** Replace the facet isolate. Class load happens before abort so a bad module leaves the previous facet up. */
129
152
  private swapFacet;
130
153
  private abortFacet;
131
154
  private allow;
155
+ /**
156
+ * Authorizes `snapshot` and adopts it only when it is still current after `allow`.
157
+ * A newer row is not treated as authorized.
158
+ */
159
+ private confirmAccess;
160
+ /** One retry for non-API routes. `/api` uses its own budget inside `forwardApi`. */
161
+ private authorizeSnapshot;
132
162
  private acceptReload;
133
163
  private serveHtml;
164
+ /**
165
+ * Theme and libs always come from a parseable manifest. Invalid `loading` is ignored.
166
+ * Tailwind stays blocking unless the manifest declares a `loading` mode other than `none`.
167
+ */
168
+ private renderHtml;
169
+ private rejectLoading;
134
170
  private serveFile;
135
171
  private forwardApi;
136
172
  private broadcastReload;
@@ -139,6 +175,32 @@ export declare class ArtifactDO extends DurableObject<ArtifactEnv> implements Ar
139
175
  private destroyFacet;
140
176
  private browserLogAllowed;
141
177
  private writeLog;
178
+ /**
179
+ * Document view: counters and dimensions commit first. A new salt is stored only after
180
+ * `txn.setAlarm` in the same storage transaction. If that fails, the view and dimensions
181
+ * stay and the unique (and its coverage) are omitted. The visitor hash runs after the digest.
182
+ * A failure here must not change the HTML response.
183
+ */
184
+ private recordDocumentView;
185
+ private finishUnique;
186
+ private resetSaltBackoff;
187
+ private rotateSaltOnAlarm;
188
+ private purgeStaleVisitors;
189
+ /** Bytes for today's salt. A new salt is not written here; `commitSalt` arms the alarm first. */
190
+ private planSalt;
191
+ /**
192
+ * Arm the scheduler minimum (keeping a sooner alarm already set), then persist a new salt.
193
+ * `storage.transaction` commits SQL and `txn.setAlarm` together; a rejection rolls both back.
194
+ * An existing salt still counts its unique when re-arming fails.
195
+ */
196
+ private commitSalt;
197
+ private readSalt;
198
+ /** One read of the day's named values, then the rows for a single multi-row upsert. */
199
+ private dimensionRows;
200
+ private upsertCounters;
201
+ private upsertDims;
202
+ private markUniquesCapped;
203
+ private sqlWrite;
142
204
  /** One daily counter. Like `writeLog`, a counter must never break a response. */
143
205
  private bump;
144
206
  /** Drops counters older than `LIMITS.statsDays` UTC days (today included). */
@@ -151,8 +213,19 @@ export declare class ArtifactDO extends DurableObject<ArtifactEnv> implements Ar
151
213
  private flushIndex;
152
214
  private flushLocalIndex;
153
215
  private flushOraIndex;
154
- /** Shared alarm for index retries and the soonest open draft. The earlier deadline wins. */
216
+ private retryDelayMs;
217
+ /** Stores an absolute retry time from the persisted retry count. Does not move an existing future deadline. */
218
+ private noteRetryDeadline;
219
+ /**
220
+ * Shared alarm. Deadlines are absolute: salt expiry, draft expiry, and the retry time captured
221
+ * when a flush failed. A deadline already due (`at <= now`) is scheduled immediately instead of
222
+ * dropped. `preserve` skips deleting the alarm when nothing is due yet, so a flush that has not
223
+ * finished cannot drop the next local wake.
224
+ */
155
225
  private armIndexAlarm;
226
+ /** Minimum wake. A due deadline counts as `now` so a later draft cannot postpone a purge. */
227
+ private earliestDeadline;
228
+ private noteSaltAlarm;
156
229
  private indexEntry;
157
230
  private readMeta;
158
231
  private toPublic;
@@ -1,5 +1,6 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
2
  import type { ArtifactEnv, ArtifactIndexEntry, ArtifactIndexRpc } from "../types";
3
+ import { type ToolRunAdmitInput, type ToolRunAdmitResult, type ToolRunFinishInput, type ToolRunLogEntry } from "../mcp/toolRunContract";
3
4
  export { INDEX_UPSERT_SQL } from "./index-upsert";
4
5
  /**
5
6
  * One instance per tenant (`idFromName('index')`).
@@ -7,6 +8,17 @@ export { INDEX_UPSERT_SQL } from "./index-upsert";
7
8
  */
8
9
  export declare class ArtifactIndexDO extends DurableObject<ArtifactEnv> implements ArtifactIndexRpc {
9
10
  constructor(ctx: DurableObjectState, env: ArtifactEnv);
11
+ /** Additive, idempotent. Separate tables: never touches artifact rows. */
12
+ private ensureToolRunSchema;
13
+ admitToolRun(input: ToolRunAdmitInput): Promise<ToolRunAdmitResult>;
14
+ finishToolRun(input: ToolRunFinishInput): Promise<boolean>;
15
+ listToolRuns(opts?: {
16
+ actor?: string;
17
+ limit?: number;
18
+ }): Promise<ToolRunLogEntry[]>;
19
+ /** Marks expired pending runs unknown and purges rows older than 30 days, in bounded batches. */
20
+ alarm(): Promise<void>;
21
+ private recordDenial;
10
22
  put(entry: ArtifactIndexEntry): Promise<void>;
11
23
  remove(slug: string): Promise<void>;
12
24
  get(slug: string): Promise<ArtifactIndexEntry | null>;
@@ -45,4 +45,4 @@ export declare function routeArtifactRequest(input: RouteInput): ArtifactRoute;
45
45
  */
46
46
  export declare function buildForwardRequest(request: Request, route: Extract<ArtifactRoute, {
47
47
  kind: "forward";
48
- }>): Request;
48
+ }>, visitHeader?: string | null): Request;
@@ -3,3 +3,4 @@ export { ArtifactIndexDO } from "./do/ArtifactIndexDO";
3
3
  export { handleArtifactHost } from "./host";
4
4
  export { ARTIFACT_PKG_VERSION } from "./version";
5
5
  export * from "./types";
6
+ export type { ToolRunExecutor, ToolRunOutcome, ToolRunSpec, ToolRunLogEntry } from "./mcp/toolRunContract";
@@ -1,3 +1,4 @@
1
+ import type { ArtifactLoadingConfig } from "./validate";
1
2
  export declare function frameAncestorsDirective(raw: string | undefined): string;
2
3
  export declare function artifactCsp(frameAncestors?: string): string;
3
4
  /** Default CSP when `ARTIFACT_FRAME_ANCESTORS` is empty: `frame-ancestors 'none'`. */
@@ -29,6 +30,11 @@ export interface InjectOptions {
29
30
  tailwindUrl: string;
30
31
  tailwindIntegrity: string;
31
32
  theme?: "hugex" | "none";
33
+ title?: string;
34
+ lang?: "es" | "en";
35
+ loading?: ArtifactLoadingConfig;
36
+ loadingPageHtml?: string | null;
37
+ deferTailwind?: boolean;
32
38
  stylesheets?: {
33
39
  url: string;
34
40
  integrity: string;
@@ -39,10 +45,16 @@ export interface InjectOptions {
39
45
  defer?: boolean;
40
46
  }[];
41
47
  }
42
- /** Insert `<base>`, the process shim, the import map, stylesheets, scripts, Tailwind, theme tokens, and the reload client. */
48
+ /** Insert `<base>`, boot overlay, the process shim, the import map, stylesheets, scripts, Tailwind, theme tokens, and the reload client. */
43
49
  export declare function injectHtml(html: string, options: InjectOptions): string;
44
50
  /** Resolve `libs` and `theme` from artifact.json and inject. Unknown libs are ignored here; write() reports them. */
45
- export declare function injectArtifactHtml(html: string, baseHref: string, libs: readonly string[], theme?: "hugex" | "none"): string;
51
+ export declare function injectArtifactHtml(html: string, baseHref: string, libs: readonly string[], theme?: "hugex" | "none", extra?: {
52
+ title?: string;
53
+ lang?: "es" | "en";
54
+ loading?: ArtifactLoadingConfig;
55
+ loadingPageHtml?: string | null;
56
+ deferTailwind?: boolean;
57
+ }): string;
46
58
  export declare function contentType(path: string): string;
47
59
  /** Referrer-Policy, nosniff, no-transform, and the artifact CSP on every response. No Set-Cookie. */
48
60
  export declare function applySecurityHeaders(response: Response, frameAncestors?: string): Response;
@@ -9,6 +9,8 @@ export declare const LIMITS: {
9
9
  readonly logMessageBytes: 2048;
10
10
  readonly browserLogsPerSecond: 20;
11
11
  readonly pathMaxChars: 200;
12
+ /** Maximum UTF-8 byte size for a manifest-declared `loading.page` HTML file (32 KiB). */
13
+ readonly loadingPageBytes: 32768;
12
14
  /** Shared deadline for facet load, health, and restore. An expired activation cannot publish. */
13
15
  readonly healthTimeoutMs: 5000;
14
16
  /** Non-active version rows kept by created_at (plus active and log-referenced versions). */
@@ -17,6 +19,15 @@ export declare const LIMITS: {
17
19
  readonly statsDays: 90;
18
20
  /** Default window for `stats()`. */
19
21
  readonly statsDefaultDays: 30;
22
+ /** Named dimension values per day before the rest collapses into "other" (29 + other = 30). */
23
+ readonly statsDimValues: 30;
24
+ /** Distinct visitor hashes kept for the current UTC day. */
25
+ readonly statsVisitorsPerDay: 20000;
26
+ /**
27
+ * Upper bound for stats storage in one DO: 90 days × 7 dims × 30 values,
28
+ * plus at most 20_000 visitor hashes of 16 bytes. Well under 10 MB.
29
+ */
30
+ readonly statsBudgetBytes: 10000000;
20
31
  };
21
32
  /**
22
33
  * Local caps for `artifact_publish`. Pending bytes are UTF-8 staged content
@@ -2,6 +2,7 @@ import type { ArtifactEnv } from '../types';
2
2
  import type { ArtifactAccess } from './authz';
3
3
  import type { ArtifactIdentity } from './auth';
4
4
  import type { ConnectionSummary } from './oauth/contract';
5
+ import type { ToolRunExecutor } from './toolRunContract';
5
6
  /**
6
7
  * Which artifact-to-Worker paths this tenant wires. `server`: the tenant exports
7
8
  * `ArtifactWorkerGateway` (artifact `env.HX`); `browser`: `handleArtifactHost` got an
@@ -26,4 +27,8 @@ export interface McpRequestContext {
26
27
  }>;
27
28
  revokeConnection?: (grantId: string) => Promise<boolean>;
28
29
  workerConnections?: WorkerConnectionSupport;
30
+ /** Injected by the tenant through `handleArtifactHost` options. Without it `tool_run` is unavailable. */
31
+ toolRunExecutor?: ToolRunExecutor;
32
+ /** OAuth grant id (from the access token format `userId:grantId:secret`); audit only. */
33
+ grantId?: string;
29
34
  }
@@ -0,0 +1,22 @@
1
+ import type { McpRequestContext } from '../context';
2
+ import type { ToolDefinition, ToolTextResult } from '../tools';
3
+ import { type Row } from './read';
4
+ export declare const toolTools: ToolDefinition[];
5
+ /** Byte, depth and node limits for client JSON. */
6
+ export declare function jsonWithin(value: unknown, maxBytes: number, maxDepth?: number, maxNodes?: number): boolean;
7
+ export type SkillRevisionFn = (context: McpRequestContext, skillId: string) => Promise<string | null>;
8
+ export type SkillProjectionFn = (context: McpRequestContext, skillId: string) => Promise<{
9
+ revision: string;
10
+ name: string;
11
+ instructions: string;
12
+ references: {
13
+ id: string;
14
+ name: string;
15
+ description: string;
16
+ content: string;
17
+ }[];
18
+ } | null>;
19
+ export declare function executeToolDomainTool(name: string, args: Row, context: McpRequestContext, skills: {
20
+ revision: SkillRevisionFn;
21
+ projection: SkillProjectionFn;
22
+ }): Promise<ToolTextResult>;
@@ -4,4 +4,20 @@ import type { McpDomain } from './artifacts';
4
4
  import { type Row } from './read';
5
5
  export declare const toolsDomain: McpDomain;
6
6
  export declare const skillsDomain: McpDomain;
7
+ type RefRow = {
8
+ id: string;
9
+ name: string;
10
+ description: string;
11
+ content: string;
12
+ };
13
+ /** Current skill_get revision (legacy content hash), or null. */
14
+ export declare function skillRevision(context: McpRequestContext, skillId: string): Promise<string | null>;
15
+ /** Fresh skill projection for tool_run (no runtime cache). */
16
+ export declare function skillProjection(context: McpRequestContext, skillId: string): Promise<{
17
+ revision: string;
18
+ name: string;
19
+ instructions: string;
20
+ references: RefRow[];
21
+ } | null>;
7
22
  export declare function executeCatalogTool(name: string, args: Row, context: McpRequestContext): Promise<ToolTextResult>;
23
+ export {};
@@ -5,7 +5,7 @@ import type { ArtifactEnv } from '../types';
5
5
  import type { McpRequestContext } from './context';
6
6
  export declare const MAX_BODY_BYTES: number;
7
7
  export declare const SERVER_NAME = "hugex";
8
- export declare const SERVER_VERSION = "2.4.0";
8
+ export declare const SERVER_VERSION = "2.5.0";
9
9
  export declare const DEFAULT_PROTOCOL_VERSION = "2025-11-25";
10
10
  export declare const SUPPORTED_PROTOCOL_VERSIONS: readonly ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'];
11
11
  export type AccessMode = 'phase1' | 'rbac';
@@ -1,4 +1,7 @@
1
1
  import type { ArtifactEnv } from '../../types';
2
2
  import type { WorkerConnectionSupport } from '../context';
3
+ import type { ToolRunExecutor } from '../toolRunContract';
3
4
  export type { McpAccessTokenProps } from './contract';
4
- export declare function handleOAuthRequest(request: Request, env: ArtifactEnv, ctx: ExecutionContext, workerConnections?: WorkerConnectionSupport): Promise<Response>;
5
+ export declare function handleOAuthRequest(request: Request, env: ArtifactEnv, ctx: ExecutionContext, workerConnections?: WorkerConnectionSupport, toolRunExecutor?: ToolRunExecutor): Promise<Response>;
6
+ /** workers-oauth-provider tokens are `userId:grantId:secret`. Only the grant id is kept (audit). */
7
+ export declare function grantIdFromBearer(authorization: string | null): string | undefined;
@@ -8,11 +8,13 @@ export declare const SKILL_READ_SCOPE = "skills:read";
8
8
  export declare const SKILL_WRITE_SCOPE = "skills:write";
9
9
  export declare const SKILL_SCOPES: readonly ["skills:read", "skills:write"];
10
10
  export declare const TOOL_READ_SCOPE = "tools:read";
11
+ export declare const TOOL_WRITE_SCOPE = "tools:write";
12
+ export declare const TOOL_RUN_SCOPE = "tools:run";
11
13
  export declare const MEMO_READ_SCOPE = "memos:read";
12
14
  export declare const SECRET_READ_SCOPE = "secrets:read";
13
15
  export declare const SECRET_WRITE_SCOPE = "secrets:write";
14
16
  export declare const SECRET_SCOPES: readonly ["secrets:read", "secrets:write"];
15
- export declare const MCP_SCOPES: readonly ["artifacts:read", "artifacts:write", "workers:read", "workers:run", "workers:write", "skills:read", "skills:write", "tools:read", "memos:read", "secrets:read", "secrets:write"];
17
+ export declare const MCP_SCOPES: readonly ["artifacts:read", "artifacts:write", "workers:read", "workers:run", "workers:write", "skills:read", "skills:write", "tools:read", "memos:read", "secrets:read", "secrets:write", "tools:write", "tools:run"];
16
18
  /** Any authenticated grant may call this tool. It is not an OAuth scope. */
17
19
  export declare const GUIDE_TOOL_NAME = "hugex_guide";
18
20
  /**
@@ -23,6 +25,10 @@ export declare const NO_OAUTH_SCOPE = "";
23
25
  export declare const SKILL_WRITE_TOOLS: Set<string>;
24
26
  /** Authoring tools. Each one needs the workers:read + workers:write pair. */
25
27
  export declare const WORKER_WRITE_TOOLS: Set<string>;
28
+ /** Tool authoring. Each one needs the tools:read + tools:write pair (`tool_get` only with view authoring). */
29
+ export declare const TOOL_WRITE_TOOLS: Set<string>;
30
+ /** Direct execution. Needs the tools:read + tools:run pair. */
31
+ export declare const TOOL_RUN_TOOLS: Set<string>;
26
32
  /** `secret_set` needs the secrets:read + secrets:write pair. `secret_list` stays read-only. */
27
33
  export declare const SECRET_WRITE_TOOLS: Set<string>;
28
34
  export declare function effectiveScopes(scopes: ReadonlySet<string>): ReadonlySet<string>;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * `tool_run` executor contract. Structural on purpose: the tenant injects an implementation from
3
+ * `@hugex/ai` (`toolRunExecutor`) through `handleArtifactHost` options, so `@hugex/artifact`
4
+ * never imports the agent runtime. Mirrored in `lib/server/types/artifact.ts`.
5
+ */
6
+ export interface ToolRunSpec {
7
+ runId: string;
8
+ tenant: string;
9
+ user: {
10
+ sub: string;
11
+ email: string;
12
+ org: string;
13
+ };
14
+ tool: {
15
+ id: string;
16
+ name: string;
17
+ kind: 'http' | 'composio' | 'mcp';
18
+ status: string;
19
+ revision: string;
20
+ inputSchema: unknown;
21
+ execution: unknown;
22
+ output: unknown;
23
+ };
24
+ selector: {
25
+ toolSlug?: string;
26
+ toolVersion?: string;
27
+ remoteToolName?: string;
28
+ };
29
+ args: Record<string, unknown>;
30
+ /** Only referenced vault secrets the user can access. */
31
+ secrets: Record<string, string>;
32
+ /** Org service credentials for a provider adapter (COMPOSIO_API_KEY). */
33
+ serviceSecrets: Record<string, string>;
34
+ timeoutMs: number;
35
+ maxResultBytes: number;
36
+ signal: AbortSignal;
37
+ /** Validate selector, arguments and configuration only: no secrets, no network. */
38
+ dryRun?: boolean;
39
+ }
40
+ export interface ToolRunOutcome {
41
+ status: 'completed' | 'failed' | 'unknown';
42
+ result?: unknown;
43
+ truncated?: boolean;
44
+ omitted?: string[];
45
+ bytes?: number;
46
+ httpStatus?: number;
47
+ error?: {
48
+ code: string;
49
+ message?: string;
50
+ };
51
+ /** dryRun: what would run (selector, credential reference names). Never resolved values. */
52
+ preview?: {
53
+ action?: string;
54
+ remoteToolName?: string;
55
+ toolSlug?: string;
56
+ toolVersion?: string;
57
+ credentialRefs?: string[];
58
+ };
59
+ }
60
+ export type ToolRunExecutor = (spec: ToolRunSpec, env: unknown) => Promise<ToolRunOutcome>;
61
+ /** Admission/audit rows kept by ArtifactIndexDO (`tool_run_log`, 30 days). Never args or output. */
62
+ export interface ToolRunAdmitInput {
63
+ runId: string;
64
+ actor: string;
65
+ grantId: string | null;
66
+ org: string;
67
+ toolKey: string;
68
+ kind: string;
69
+ revision: string | null;
70
+ selector: string | null;
71
+ dryRun: boolean;
72
+ deadlineMs: number;
73
+ }
74
+ export type ToolRunAdmitResult = {
75
+ ok: true;
76
+ } | {
77
+ ok: false;
78
+ code: 'rate_limited';
79
+ retryAfterSec: number;
80
+ scope: 'tool' | 'user';
81
+ };
82
+ export interface ToolRunFinishInput {
83
+ runId: string;
84
+ status: 'preview' | 'completed' | 'failed' | 'unknown';
85
+ code: string | null;
86
+ bytes: number;
87
+ }
88
+ export interface ToolRunLogEntry {
89
+ runId: string;
90
+ actor: string;
91
+ grantId: string | null;
92
+ org: string;
93
+ toolKey: string;
94
+ kind: string;
95
+ revision: string | null;
96
+ selector: string | null;
97
+ dryRun: boolean;
98
+ status: string;
99
+ code: string | null;
100
+ bytes: number;
101
+ startedAt: number;
102
+ finishedAt: number | null;
103
+ durationMs: number | null;
104
+ }
105
+ export declare const TOOL_RUN_LIMITS: {
106
+ readonly perToolPerMinute: 10;
107
+ readonly perUserPerMinute: 60;
108
+ readonly windowMs: 60000;
109
+ readonly retentionMs: number;
110
+ };
@@ -1,3 +1,4 @@
1
+ import type { ToolRunAdmitInput, ToolRunAdmitResult, ToolRunExecutor, ToolRunFinishInput, ToolRunLogEntry } from './mcp/toolRunContract';
1
2
  /**
2
3
  * Contract shared by the @hugex/artifact runtime (ArtifactDO, ArtifactIndexDO, host routing) and the MCP layer.
3
4
  * Owned by the orchestrator: workers must not change these shapes without updating plans/notes/artifacts-design.md (§10 contract, workspace root).
@@ -66,6 +67,8 @@ export type ArtifactAgentProxy = (request: Request, env: any, ctx: ExecutionCont
66
67
  export interface ArtifactHostOptions {
67
68
  /** Without it, `__hx/agent/...` is a 404. */
68
69
  agentProxy?: ArtifactAgentProxy;
70
+ /** Turns on `tool_run` in the HugeX MCP server (for example `toolRunExecutor` from `@hugex/ai`). */
71
+ toolRunExecutor?: ToolRunExecutor;
69
72
  }
70
73
  /** A flow the artifact owner allowed this artifact to talk to. */
71
74
  export interface WorkerGrant {
@@ -74,20 +77,45 @@ export interface WorkerGrant {
74
77
  grantedAt: string;
75
78
  }
76
79
  /** Daily counters kept by ArtifactDO in `daily_stat` (UTC days, 90 days retained). */
77
- export type ArtifactStatMetric = 'view' | 'view_key' | 'api' | 'api_error' | 'error' | 'browser_error' | 'worker_browser' | 'worker_server' | 'worker_denied';
80
+ export type ArtifactStatMetric = 'view' | 'view_key' | 'view_bot' | 'api' | 'api_error' | 'error' | 'browser_error' | 'worker_browser' | 'worker_server' | 'worker_denied' | 'uniques';
78
81
  export declare const ARTIFACT_STAT_METRICS: readonly ArtifactStatMetric[];
82
+ export declare const ARTIFACT_STAT_DIMS: readonly ['country', 'region', 'device', 'browser', 'os', 'referrer', 'lang'];
83
+ export type ArtifactStatDim = (typeof ARTIFACT_STAT_DIMS)[number];
84
+ export interface ArtifactStatCoverage {
85
+ /** At least one view that day carried a valid visit header. */
86
+ dims: boolean;
87
+ /** At least one non-bot view that day had a usable IP and was counted after the hash. */
88
+ uniques: boolean;
89
+ }
79
90
  export interface ArtifactStats {
80
91
  days: number;
81
92
  /** 'YYYY-MM-DD' UTC, inclusive. */
82
93
  from: string;
83
94
  /** 'YYYY-MM-DD' UTC (today), inclusive. */
84
95
  to: string;
85
- /** Ascending, one row per day, zeros included. */
96
+ /**
97
+ * Ascending, one row per day, zeros included.
98
+ * `view` and `view_key` exclude bots (`view_bot`). `uniques` is that day's distinct visitors.
99
+ * `coverage` is false on days from before capture existed, so zero is not "no traffic".
100
+ */
86
101
  series: Array<{
87
102
  day: string;
88
- } & Record<ArtifactStatMetric, number>>;
103
+ } & Record<ArtifactStatMetric, number> & {
104
+ uniquesCapped: boolean;
105
+ coverage: ArtifactStatCoverage;
106
+ }>;
107
+ /** `uniques` sums daily counts and does not dedupe across days. */
89
108
  totals: Record<ArtifactStatMetric, number>;
90
- /** Last day with view > 0 within the 90 retained days. */
109
+ /** True when any day in the requested window hit the visitor cap. */
110
+ uniquesCapped: boolean;
111
+ /** Top 10 values in the window, then `other` for the rest (including daily `other`). */
112
+ dimensions: Record<ArtifactStatDim, Array<{
113
+ value: string;
114
+ n: number;
115
+ }>>;
116
+ /** First UTC day with dimension capture, or null when none exists in retention. */
117
+ dimensionsSince: string | null;
118
+ /** Last day with view > 0 within the 90 retained days. Bots do not move this. */
91
119
  lastViewDay: string | null;
92
120
  storage: {
93
121
  databaseSize: number;
@@ -326,6 +354,8 @@ export interface SettingsInput {
326
354
  export interface QueryOptions {
327
355
  limit?: number;
328
356
  offset?: number;
357
+ /** UUID the caller already authorized. The DO rejects the call when the artifact was recreated. */
358
+ expectUuid?: string;
329
359
  }
330
360
  export type QueryResult = {
331
361
  ok: true;
@@ -344,6 +374,8 @@ export interface SchemaColumn {
344
374
  }
345
375
  export interface SchemaOptions {
346
376
  counts?: boolean;
377
+ /** UUID the caller already authorized. The DO rejects the call when the artifact was recreated. */
378
+ expectUuid?: string;
347
379
  }
348
380
  export interface SchemaTable {
349
381
  name: string;
@@ -484,12 +516,23 @@ export interface ArtifactIndexRpc {
484
516
  list(opts?: {
485
517
  owner?: string;
486
518
  }): Promise<ArtifactIndexEntry[]>;
519
+ /** `tool_run` admission: sliding-window quotas + initial audit row in one transaction. */
520
+ admitToolRun(input: ToolRunAdmitInput): Promise<ToolRunAdmitResult>;
521
+ /** Closes the audit row. `false` when the run is unknown (audit_incomplete). */
522
+ finishToolRun(input: ToolRunFinishInput): Promise<boolean>;
523
+ /** Administrative read of the audit log (newest first). */
524
+ listToolRuns(opts?: {
525
+ actor?: string;
526
+ limit?: number;
527
+ }): Promise<ToolRunLogEntry[]>;
487
528
  }
488
529
  /**
489
530
  * Headers the host router sets when forwarding a browser request to ArtifactDO.fetch().
490
531
  * The DO never trusts anything else from the client for access decisions.
491
532
  */
492
533
  export declare const HX_HEADER_KEY = "x-hx-artifact-key";
534
+ /** Trusted visit dimensions. The host sets it; the DO strips it before the facet. */
535
+ export declare const HX_HEADER_VISIT = "x-hx-artifact-visit";
493
536
  /** Public base path of the artifact including trailing slash, e.g. `/demo/k/abc/` or `/app/demo/`. */
494
537
  export declare const HX_HEADER_BASE = "x-hx-artifact-base";
495
538
  export {};
@@ -15,12 +15,29 @@ export declare const WORKER_SESSION_ID_RE: RegExp;
15
15
  export declare function isWorkerFlowId(value: unknown): value is string;
16
16
  export declare function isWorkerSessionId(value: unknown): value is string;
17
17
  export type ArtifactTheme = "hugex" | "none";
18
+ export type ArtifactLoadingMode = "auto" | "manual" | "none";
19
+ export interface ArtifactLoadingConfig {
20
+ mode: ArtifactLoadingMode;
21
+ page?: string;
22
+ }
18
23
  export type ArtifactManifest = {
19
24
  title: string;
20
25
  libs: string[];
21
26
  theme: ArtifactTheme;
27
+ loading?: ArtifactLoadingConfig;
22
28
  };
23
- export declare function parseArtifactManifest(text: string): {
29
+ /** Validates `loading.page` path rules (E3): valid relative path, `.html`, not reserved or under `__hx/`. */
30
+ export declare function validateLoadingPagePath(path: string): string | null;
31
+ /** Validates effective `loading.page` existence and 32 KiB UTF-8 size limit. */
32
+ export declare function validateLoadingConfig(manifest: ArtifactManifest, readFile: (path: string) => string | null): {
33
+ ok: true;
34
+ } | {
35
+ ok: false;
36
+ error: string;
37
+ };
38
+ export declare function parseArtifactManifest(text: string, opts?: {
39
+ ignoreInvalidLoading?: boolean;
40
+ }): {
24
41
  ok: true;
25
42
  manifest: ArtifactManifest;
26
43
  } | {
@@ -1,2 +1,2 @@
1
1
  /** Package version mixed into `runtimeId`. Bump when the Dynamic Worker contract changes. */
2
- export declare const ARTIFACT_PKG_VERSION = "0.1.0";
2
+ export declare const ARTIFACT_PKG_VERSION = "0.8.0";
@@ -0,0 +1,38 @@
1
+ import { HX_HEADER_VISIT, type ArtifactStatDim } from "./types";
2
+ export { HX_HEADER_VISIT };
3
+ export interface ArtifactVisit {
4
+ country: string | null;
5
+ region: string | null;
6
+ device: "mobile" | "tablet" | "desktop" | "bot";
7
+ browser: string;
8
+ os: string;
9
+ referrer: string;
10
+ lang: string;
11
+ }
12
+ /**
13
+ * Top-level document navigation. Prefetch and prerender are not views.
14
+ * Iframes fail the `Sec-Fetch-Dest: document` check.
15
+ */
16
+ export declare function isDocumentView(request: Request): boolean;
17
+ export declare function classifyVisit(request: Request): ArtifactVisit;
18
+ /** base64url(JSON), or null when the header would exceed 512 ASCII bytes. */
19
+ export declare function encodeVisit(visit: ArtifactVisit): string | null;
20
+ export declare function buildVisitHeader(request: Request): string | null;
21
+ export declare function decodeVisit(header: string | null): ArtifactVisit | null;
22
+ /** Collapse a dimension value to ASCII ≤ 64 chars, or `other`. */
23
+ export declare function normalizeStatValue(value: string): string;
24
+ export declare function dimensionValue(visit: ArtifactVisit, dim: ArtifactStatDim): string;
25
+ export declare function rankDimensionValues(rows: Array<{
26
+ value: string;
27
+ n: number;
28
+ }>, limit?: number): Array<{
29
+ value: string;
30
+ n: number;
31
+ }>;
32
+ export declare function emptyDimensions(): Record<ArtifactStatDim, Array<{
33
+ value: string;
34
+ n: number;
35
+ }>>;
36
+ /** First 16 bytes of SHA-256(salt ‖ 0x00 ‖ ip ‖ 0x00 ‖ ua). */
37
+ export declare function visitorHash(salt: Uint8Array, ip: string, ua: string): Promise<Uint8Array>;
38
+ export declare function bytesEqual(a: Uint8Array, b: Uint8Array): boolean;