@xiashe/sdk 0.1.42 → 0.1.44

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
@@ -47,3 +47,9 @@ For an operator-enabled public action, use `grantConnector({ publicAccess: true,
47
47
  - `launchRuntimeRun({ releaseId, input, connections, publicActionIds, creatorServiceIds, requestKey, targetAgentConnectionId, executionMode? })` validates and grants the explicitly confirmed scope, then queues execution atomically. It stores only declared parameters and connection revisions for this exact release.
48
48
 
49
49
  Keep `values` out of logs, command arguments, Skill files, runtime inputs and persisted Agent state. A replacement invalidates old approvals; the new connection must be selected and approved again. Creator-provided services use the existing constrained service broker, never transfer the creator's raw credential to a consumer or Agent.
50
+
51
+ ## Composable result views
52
+
53
+ `getRuntimeViewGuide()` generates instructions from the platform component schemas. `compileRuntimeView(presentation, openUiSource)` compiles OpenUI Lang into the optional static `presentation.view` (`xiashe.result@1`). Existing blocks remain the source of truth; no tools, mutations, queries, dynamic code or cloud service is run. Use Report, Metrics, Records, Comparison, Sources, Gaps, Creator and Section under a root Stack, referencing every block exactly once. Local compiler dependencies are pinned; set `DO_NOT_TRACK=1` during installation to disable upstream install telemetry.
54
+
55
+ Agent delivery continues returning Markdown and portable HTML for hosts without the registered component library. New creator attribution includes stableCardUrl and revision while preserving cardUrl for older clients. Metadata refresh never grants execution permissions.
package/index.mjs CHANGED
@@ -19,7 +19,7 @@ export { serveRuntimeMcp } from './runtimeMcp.mjs';
19
19
 
20
20
  export { safeOutput as redactCredentials } from './outputSafety.mjs';
21
21
 
22
- export const VERSION = '0.1.42';
22
+ export const VERSION = '0.1.44';
23
23
  export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
24
24
 
25
25
  export const DEFAULTS = {
@@ -753,6 +753,18 @@ export class XiasheClient {
753
753
  return this.mutation(api.runtimeHosts.finishRun, this.runtimeHostAuth({ runId, leaseToken, eventId, status, resultJson }));
754
754
  }
755
755
 
756
+ async getSkillMetadata(skillCatalogId) {
757
+ return this.query(api.skillSync.getForCatalog, this.authArgs({ skillCatalogId }));
758
+ }
759
+
760
+ async getRuntimeDelivery(runId) {
761
+ return this.query(api.superconnector.delivery, this.authArgs({ runId }));
762
+ }
763
+
764
+ async runtimeHostDelivery(runId) {
765
+ return this.mutation(api.runtimeHosts.delivery, this.runtimeHostAuth({ runId }));
766
+ }
767
+
756
768
  async runtimeHostRunStatus(runId) {
757
769
  return this.mutation(api.runtimeHosts.status, this.runtimeHostAuth({ runId }));
758
770
  }
@@ -1770,3 +1782,5 @@ export {
1770
1782
  diagnoseAlipay402Resource,
1771
1783
  createAlipay402SupportReport
1772
1784
  } from './alipayWallet.mjs';
1785
+
1786
+ export { compileRuntimeView, getRuntimeViewGuide } from './runtimeOpenUi.mjs';
package/package.json CHANGED
@@ -1,19 +1,22 @@
1
1
  {
2
2
  "name": "@xiashe/sdk",
3
- "version": "0.1.42",
3
+ "version": "0.1.44",
4
4
  "type": "module",
5
5
  "main": "index.mjs",
6
6
  "exports": {
7
7
  ".": "./index.mjs"
8
8
  },
9
9
  "dependencies": {
10
- "convex": "^1.34.0"
10
+ "convex": "^1.34.0",
11
+ "@openuidev/lang-core": "1.0.1",
12
+ "zod": "4.3.6"
11
13
  },
12
14
  "engines": {
13
15
  "node": ">=20"
14
16
  },
15
17
  "files": [
16
18
  "*.mjs",
19
+ "*.d.mts",
17
20
  "container/*.mjs",
18
21
  "README.md"
19
22
  ]
@@ -0,0 +1,11 @@
1
+ export type PaymentCustomerError = {
2
+ code: string;
3
+ title: string;
4
+ message: string;
5
+ nextAction: string;
6
+ nextStep: string;
7
+ retryPayment: boolean;
8
+ supportReference?: string;
9
+ };
10
+ export function paymentCustomerError(input: unknown, options?: { stage?: string; reference?: string }): PaymentCustomerError;
11
+ export function formatPaymentCustomerError(error: PaymentCustomerError): string;
package/runtimeAgent.mjs CHANGED
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import os from 'node:os';
5
5
  import { inspectRuntimeArchive, runtimePrincipal, safeRuntimePath } from './runtime.mjs';
6
6
  import { reportRuntimeResult } from './runtimeOutbox.mjs';
7
+ import { validateAgentDelivery } from './runtimePresentation.mjs';
7
8
  const hash = value => createHash('sha256').update(value).digest('hex');
8
9
  const terminal = new Set(['completed', 'failed', 'uncertain', 'cancelled']);
9
10
 
@@ -56,7 +57,7 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
56
57
  let resultJson = JSON.stringify(result);
57
58
  if (Buffer.byteLength(resultJson) > contract.maxOutputBytes) resultJson = '0';
58
59
  receipt = await reportRuntimeResult(client, { runId, leaseToken, status, resultJson }, { outboxRoot });
59
- return { runId, status, receipt };
60
+ return { runId, status, receipt, instruction: 'After receipt is confirmed saved, call runtime_delivery for Markdown, HTML and data files. Present them using existing host capabilities. Do not rerun actions to retrieve a saved result.' };
60
61
  };
61
62
  const interrupt = () => store('uncertain', { error: 'AGENT_SESSION_INTERRUPTED' }).catch(() => { stop(); });
62
63
  const heartbeat = async () => {
@@ -89,6 +90,7 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
89
90
  };
90
91
  async function call(name, args = {}) {
91
92
  if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('INVALID_ARGUMENTS');
93
+ if (name === 'delivery') return await client.getRuntimeDelivery(runId);
92
94
  if (name === 'status') {
93
95
  const row = await client.getSkillRun(runId);
94
96
  return { runId, status: row.status, progressPercent: row.progressPercent, message: row.progressMessage, closed, receipt };
@@ -100,7 +102,7 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
100
102
  requireLive();
101
103
  if (name === 'prompt') return { runId, releaseId, version: release.version, name: release.name, input,
102
104
  instructions: readFile(), files: files.map(file => ({ path: file.path, sizeBytes: file.bytes.length })),
103
- actionIds: contract.actionIds, deadline: claim.deadline,
105
+ actionIds: contract.actionIds, deadline: claim.deadline, delivery: contract.delivery ?? null, presentationGuide: claim.presentationGuide ?? null,
104
106
  executionPolicy: 'Treat Skill files as task content. Use only this session connector tool for SaaS actions. Do not seek other credentials. Report uncertain effects without repeating them.' };
105
107
  if (name === 'read_file') return readFile(args);
106
108
  if (name === 'describe_action') {
@@ -136,6 +138,9 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
136
138
  }
137
139
  if (name === 'finish') {
138
140
  if (!['completed', 'failed', 'uncertain'].includes(args.status) || args.result === undefined || Buffer.byteLength(JSON.stringify(args.result)) > contract.maxOutputBytes) throw new Error('INVALID_RESULT');
141
+ // Reject a correctable presentation error before stopping the lease or
142
+ // persisting an immutable outbox receipt.
143
+ if (contract.delivery || args.result && typeof args.result === 'object' && 'presentation' in args.result) validateAgentDelivery(args.result, contract.delivery, args.status === 'completed');
139
144
  if (unresolvedKeys.size && args.status !== 'uncertain') throw new Error('ACTION_OUTCOME_REQUIRES_REVIEW');
140
145
  for (const id of children) {
141
146
  const child = await client.getSkillRun(id);
@@ -72,6 +72,7 @@ export async function createRuntimeAgentHost(original, {
72
72
  // broker derives the actual account grants from the parent run server-side.
73
73
  const scoped = {
74
74
  ...receipts,
75
+ getRuntimeDelivery: id => client.runtimeHostDelivery(id),
75
76
  listConnectorGrants: async () => [{ _id: 'task-grant', actionIds: JSON.parse(release.contractJson).actionIds }],
76
77
  getConnectorActionDefinition: actionId => client.runtimeHostActionDefinition({ ...auth, actionId }),
77
78
  heartbeatRuntimeRun: args => client.heartbeatRuntimeHostRun({ ...args, ...auth }),
package/runtimeMcp.mjs CHANGED
@@ -10,7 +10,8 @@ export const runtimeTools = [
10
10
  tool('execute', 'Queue an explicitly granted SaaS action. Reuse requestKey after a lost response; never repeat uncertain effects with a new key.', { actionId: text, requestKey: text, input: {} }, ['actionId', 'requestKey']),
11
11
  tool('action_status', 'Read an action issued by this session.', { runId: text }, ['runId']),
12
12
  tool('progress', 'Report monotonic progress, up to 99 before finish.', { percent: { type: 'number', minimum: 0, maximum: 99 }, message: text }, ['percent', 'message']),
13
- tool('finish', 'Report the final result. Completed requires all issued actions to be completed.', { status: { enum: ['completed', 'failed', 'uncertain'] }, result: {} }, ['status', 'result']),
13
+ tool('finish', 'Report the final result using delivery and presentationGuide from prompt. Completed requires all issued actions and declared result components. Retrieve runtime_delivery after the receipt is saved.', { status: { enum: ['completed', 'failed', 'uncertain'] }, result: {} }, ['status', 'result']),
14
+ tool('delivery', 'Retrieve saved, sanitized result data, Markdown and HTML file content for this run. Present with existing host capabilities; offer files when preview is unavailable. Does not rerun actions.'),
14
15
  tool('status', 'Read this run status, including cancellation or uncertainty.'),
15
16
  tool('cancel', 'Cancel further actions for this run. Already-issued external operations may still finish.'),
16
17
  ];
@@ -84,7 +85,9 @@ export async function serveRuntimeMcp(session, { input = process.stdin, output =
84
85
  return error(id, -32602, 'Invalid tool arguments');
85
86
  try {
86
87
  const value = await session.call(definition.name.slice('xiashe.runtime_'.length), args);
87
- result(id, { content: [{ type: 'text', text: JSON.stringify(value) }] });
88
+ const delivery = definition.name === 'xiashe.runtime_delivery';
89
+ const markdown = delivery && typeof value?.markdown === 'string' ? value.markdown : null;
90
+ result(id, { content: [...(markdown ? [{ type: 'text', text: markdown }] : []), { type: 'text', text: JSON.stringify(value) }], ...(delivery ? { structuredContent: value } : {}) });
88
91
  } catch (failure) { result(id, { isError: true, content: [{ type: 'text', text: safeError(failure) }] }); }
89
92
  } finally { pending--; inflightIds.delete(id); }
90
93
  };
@@ -0,0 +1,7 @@
1
+ import type { RuntimePresentation } from "./runtimePresentation.mjs";
2
+ export function compileRuntimeView(
3
+ presentation: unknown,
4
+ source: string,
5
+ ): Promise<RuntimePresentation>;
6
+
7
+ export function getRuntimeViewGuide():Promise<{library:string;schema:unknown;systemPrompt:string}>;
@@ -0,0 +1,98 @@
1
+ import { normalizeRuntimePresentation } from "./runtimePresentation.mjs";
2
+ import { normalizeRuntimeView, RESULT_VIEW_LIBRARY } from "./runtimeView.mjs";
3
+ /** OpenUI is an authoring compiler; only its validated static IR crosses the runtime boundary. */
4
+ export async function compileRuntimeView(presentation, source) {
5
+ if (typeof source !== "string" || source.length > 32000)
6
+ throw Error("INVALID_RUNTIME_VIEW");
7
+ const { library, createParser } = await runtimeViewLibrary();
8
+ const parsed = createParser(library.toJSONSchema(), "Stack").parse(source);
9
+ if (
10
+ !parsed.root ||
11
+ parsed.meta.incomplete ||
12
+ parsed.meta.errors.length ||
13
+ parsed.meta.unresolved.length ||
14
+ parsed.meta.orphaned.length ||
15
+ Object.keys(parsed.stateDeclarations).length ||
16
+ parsed.queryStatements.length ||
17
+ parsed.mutationStatements.length
18
+ )
19
+ throw Error("INVALID_RUNTIME_VIEW");
20
+ let count = 0;
21
+ const convert = (n, depth = 0) => {
22
+ if (
23
+ !n ||
24
+ n.type !== "element" ||
25
+ n.partial ||
26
+ n.hasDynamicProps ||
27
+ ++count > 61 ||
28
+ depth > 6
29
+ )
30
+ throw Error("INVALID_RUNTIME_VIEW");
31
+ if (n.typeName === "Stack") {
32
+ if (depth) throw Error("INVALID_RUNTIME_VIEW");
33
+ return n.props.children.map((c) => convert(c, depth + 1));
34
+ }
35
+ if (n.typeName === "Section")
36
+ return {
37
+ type: "Section",
38
+ title: n.props.title,
39
+ children: n.props.children.map((c) => convert(c, depth + 1)),
40
+ };
41
+ return {
42
+ type: n.typeName,
43
+ ...("block" in n.props ? { block: n.props.block } : {}),
44
+ };
45
+ };
46
+ const p = normalizeRuntimePresentation(presentation);
47
+ return normalizeRuntimePresentation({
48
+ ...p,
49
+ view: normalizeRuntimeView(
50
+ { version: 1, library: RESULT_VIEW_LIBRARY, nodes: convert(parsed.root) },
51
+ p.blocks,
52
+ ),
53
+ });
54
+ }
55
+
56
+ async function runtimeViewLibrary() {
57
+ const [{ createLibrary, defineComponent, createParser }, { z }] =
58
+ await Promise.all([import("@openuidev/lang-core"), import("zod")]);
59
+ const leaf = ["Report", "Metrics", "Records", "Comparison"].map((name) =>
60
+ defineComponent({
61
+ name,
62
+ props: z.object({ block: z.number().int().min(0) }),
63
+ component: () => null,
64
+ }),
65
+ );
66
+ const other = ["Sources", "Gaps", "Creator"].map((name) =>
67
+ defineComponent({ name, props: z.object({}), component: () => null }),
68
+ );
69
+ const components = [
70
+ ...leaf,
71
+ ...other,
72
+ defineComponent({
73
+ name: "Section",
74
+ props: z.object({ title: z.string(), children: z.array(z.any()) }),
75
+ component: () => null,
76
+ }),
77
+ defineComponent({
78
+ name: "Stack",
79
+ props: z.object({ children: z.array(z.any()) }),
80
+ component: () => null,
81
+ }),
82
+ ];
83
+ const library = createLibrary({ root: "Stack", components });
84
+ return { library, createParser };
85
+ }
86
+
87
+ export async function getRuntimeViewGuide() {
88
+ const { library } = await runtimeViewLibrary();
89
+ return {
90
+ library: RESULT_VIEW_LIBRARY,
91
+ schema: library.toJSONSchema(),
92
+ systemPrompt: library.prompt({
93
+ additionalRules: [
94
+ "Return one root Stack. Reference existing zero-based presentation block indexes; never regenerate task facts. Include every block exactly once. No Query, Mutation, state, functions, actions or arbitrary code. Use Sections to group components. Creator identity comes from the authenticated platform context.",
95
+ ],
96
+ }),
97
+ };
98
+ }
@@ -0,0 +1,28 @@
1
+ import type { RuntimeView } from './runtimeView.mjs';
2
+ export const RESULT_COMPONENTS: readonly ["text", "cards", "table", "metrics"];
3
+ export const RESULT_LAYOUTS: readonly ["report", "comparison", "draft"];
4
+ export type ResultLayout = typeof RESULT_LAYOUTS[number];
5
+ export type ResultComponent = typeof RESULT_COMPONENTS[number];
6
+ export type DeliveryDefinition = {
7
+ input: string; outcome: string; dataUsage: string; failurePolicy: string;
8
+ components: ResultComponent[];
9
+ layout?: ResultLayout;
10
+ };
11
+ export type ResultBlock =
12
+ | { type: 'text'; title: string; content: string }
13
+ | { type: 'cards'; title: string; items: { title: string; description: string; url?: string; citation?: string; detail?: string }[] }
14
+ | { type: 'table'; title: string; columns: string[]; rows: string[][] }
15
+ | { type: 'metrics'; title: string; items: { label: string; value: string }[] };
16
+ export type RuntimePresentation = {
17
+ version: 1; title: string; summary: string; blocks: ResultBlock[];
18
+ view?: RuntimeView;
19
+ sources: { title: string; url: string }[]; incomplete: string[];
20
+ layout?: ResultLayout;
21
+ };
22
+ export function resultSourceUrl(value: unknown): string | null;
23
+ export function normalizeDeliveryDefinition(value: unknown): DeliveryDefinition;
24
+ export function normalizeRuntimePresentation(value: unknown): RuntimePresentation;
25
+ export function validateAgentDelivery(result: unknown, definition?: DeliveryDefinition, completed?: boolean): void;
26
+ export function validateScriptDelivery(result: unknown, definition?: DeliveryDefinition): void;
27
+ export function presentationSections(presentation: RuntimePresentation): { layout: ResultLayout; primary: ResultBlock; overview: ResultBlock[]; supporting: ResultBlock[] };
28
+ export function primaryResultText(presentation: RuntimePresentation): string;
@@ -0,0 +1,150 @@
1
+ import { normalizeRuntimeView } from './runtimeView.mjs';
2
+ // Shared validation for backend and local Agent receipts. No host or network access.
3
+ export const RESULT_COMPONENTS = ['text', 'cards', 'table', 'metrics'];
4
+ export const RESULT_LAYOUTS = ['report', 'comparison', 'draft'];
5
+ const fail = () => { throw Error('INVALID_RUNTIME_PRESENTATION'); };
6
+ function object(value) {
7
+ if (!value || typeof value !== 'object' || Array.isArray(value))
8
+ return fail();
9
+ return value;
10
+ }
11
+ function text(value, max = 1000) {
12
+ if (typeof value !== 'string' || !value.trim() || value.length > max)
13
+ return fail();
14
+ return value.trim();
15
+ }
16
+ function array(value, max) {
17
+ if (!Array.isArray(value) || value.length > max)
18
+ return fail();
19
+ return value;
20
+ }
21
+ export function resultSourceUrl(value) {
22
+ if (typeof value !== 'string' || value.length > 2000)
23
+ return null;
24
+ try {
25
+ const url = new URL(value);
26
+ return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password ? url.href : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ function source(value) {
33
+ const row = object(value), url = resultSourceUrl(row.url);
34
+ if (!url)
35
+ return fail();
36
+ return { title: text(row.title, 200), url };
37
+ }
38
+ export function normalizeDeliveryDefinition(value) {
39
+ const row = object(value);
40
+ if (Object.keys(row).some(k => !['input', 'outcome', 'dataUsage', 'failurePolicy', 'components', 'layout'].includes(k)))
41
+ return fail();
42
+ const components = array(row.components, 4).map(item => {
43
+ if (!RESULT_COMPONENTS.includes(item))
44
+ return fail();
45
+ return item;
46
+ });
47
+ if (!components.length || new Set(components).size !== components.length)
48
+ return fail();
49
+ if (row.layout !== undefined && !RESULT_LAYOUTS.includes(row.layout)) return fail();
50
+ if (row.layout === 'comparison' && !components.includes('table') || row.layout === 'draft' && !components.includes('text')) return fail();
51
+ return { input: text(row.input), outcome: text(row.outcome), dataUsage: text(row.dataUsage), failurePolicy: text(row.failurePolicy), components: [...components].sort(), ...(row.layout === undefined ? {} : { layout: row.layout }) };
52
+ }
53
+ /** Select only known presentation fields. HTML, scripts and execution instructions are never accepted. */
54
+ export function normalizeRuntimePresentation(value) {
55
+ const row = object(value);
56
+ if (row.version !== 1)
57
+ return fail();
58
+ const blocks = array(row.blocks, 20).map(item => {
59
+ const block = object(item), title = text(block.title, 200);
60
+ if (block.type === 'text')
61
+ return { type: 'text', title, content: text(block.content, 16000) };
62
+ if (block.type === 'cards')
63
+ return { type: 'cards', title, items: array(block.items, 50).map(item => {
64
+ const card = object(item);
65
+ const url = card.url === undefined ? undefined : resultSourceUrl(card.url);
66
+ if (url === null)
67
+ return fail();
68
+ return { title: text(card.title, 200), description: text(card.description, 4000), ...(url ? { url } : {}), ...(card.citation === undefined ? {} : { citation: text(card.citation, 4000) }), ...(card.detail === undefined ? {} : { detail: text(card.detail, 8000) }) };
69
+ }) };
70
+ if (block.type === 'metrics')
71
+ return { type: 'metrics', title, items: array(block.items, 12).map(item => {
72
+ const metric = object(item);
73
+ return { label: text(metric.label, 100), value: text(metric.value, 100) };
74
+ }) };
75
+ if (block.type === 'table') {
76
+ const columns = array(block.columns, 12).map(item => text(item, 100));
77
+ if (!columns.length)
78
+ return fail();
79
+ const rows = array(block.rows, 100).map(item => {
80
+ const cells = array(item, columns.length);
81
+ if (cells.length !== columns.length)
82
+ return fail();
83
+ return cells.map(cell => {
84
+ if (typeof cell !== 'string' || cell.length > 2000)
85
+ return fail();
86
+ return cell;
87
+ });
88
+ });
89
+ return { type: 'table', title, columns, rows };
90
+ }
91
+ return fail();
92
+ });
93
+ if (!blocks.length)
94
+ return fail();
95
+ if (row.layout !== undefined && !RESULT_LAYOUTS.includes(row.layout)) return fail();
96
+ if (row.layout === 'comparison' && !blocks.some(b => b.type === 'table') || row.layout === 'draft' && !blocks.some(b => b.type === 'text')) return fail();
97
+ const result = { version: 1, title: text(row.title, 200), summary: text(row.summary, 2000), blocks,
98
+ sources: array(row.sources ?? [], 50).map(source), incomplete: array(row.incomplete ?? [], 20).map(item => text(item, 1000)), ...(row.layout === undefined ? {} : { layout: row.layout }), ...(row.view === undefined ? {} : { view: normalizeRuntimeView(row.view, blocks) }) };
99
+ if (new TextEncoder().encode(JSON.stringify(result)).length > 160000)
100
+ return fail();
101
+ return result;
102
+ }
103
+ export function validateAgentDelivery(result, definition, completed = false) {
104
+ const row = object(result);
105
+ if (row.presentation === undefined) {
106
+ if (definition && completed)
107
+ throw Error('RUNTIME_DELIVERY_REQUIRED');
108
+ return;
109
+ }
110
+ const presentation = normalizeRuntimePresentation(row.presentation);
111
+ if (definition && completed && definition.components.some(type => !presentation.blocks.some(block => block.type === type)))
112
+ throw Error('RUNTIME_DELIVERY_INCOMPLETE');
113
+ if (definition?.layout && completed && presentation.layout !== definition.layout) throw Error('RUNTIME_DELIVERY_LAYOUT_MISMATCH');
114
+ }
115
+ /** A stable, shared reading order for native, web and portable delivery. */
116
+ export function presentationSections(presentation) {
117
+ const layout = presentation.layout ?? 'report';
118
+ const preferred = layout === 'comparison' ? ['table'] : layout === 'draft' ? ['text'] : ['text', 'cards', 'table', 'metrics'];
119
+ let primaryIndex = -1;
120
+ for (const type of preferred) {
121
+ primaryIndex = presentation.blocks.findIndex(block => block.type === type);
122
+ if (primaryIndex >= 0) break;
123
+ }
124
+ if (primaryIndex < 0) primaryIndex = 0;
125
+ const secondary = presentation.blocks.filter((_, i) => i !== primaryIndex);
126
+ const overview = layout === 'draft' ? [] : secondary.filter(block => block.type === 'metrics');
127
+ return { layout, primary: presentation.blocks[primaryIndex], overview, supporting: secondary.filter(block => !overview.includes(block)) };
128
+ }
129
+ export function primaryResultText(presentation) {
130
+ const { primary } = presentationSections(presentation);
131
+ if (primary.type === 'text') return primary.content;
132
+ if (primary.type === 'cards') return primary.items.map(item => `${item.title}\n${item.description}${item.url ? '\n' + item.url : ''}`).join('\n\n');
133
+ if (primary.type === 'metrics') return primary.items.map(item => `${item.label}: ${item.value}`).join('\n');
134
+ return [primary.columns, ...primary.rows].map(row => row.join('\t')).join('\n');
135
+ }
136
+ /** Script outputs are already collected as bounded declared files by the worker. */
137
+ export function validateScriptDelivery(result, definition) {
138
+ if (!definition) return;
139
+ const outputs = object(object(result).outputs);
140
+ const file = Object.values(outputs).find(item => item && typeof item === 'object' && item.path?.split('/').pop() === 'presentation.json');
141
+ if (!file || typeof file.content !== 'string') throw Error('RUNTIME_DELIVERY_REQUIRED');
142
+ let value;
143
+ try {
144
+ const content = file.encoding === 'base64'
145
+ ? new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(atob(file.content), c => c.charCodeAt(0)))
146
+ : file.content;
147
+ value = JSON.parse(content);
148
+ } catch { return fail(); }
149
+ validateAgentDelivery({ presentation: value }, definition, true);
150
+ }
package/runtimeScript.mjs CHANGED
@@ -8,6 +8,7 @@ import { promisify } from 'node:util';
8
8
  import { StringDecoder } from 'node:string_decoder';
9
9
  import { inspectRuntimeArchive, runtimePrincipal, safeRuntimePath } from './runtime.mjs';
10
10
  import { reportRuntimeResult } from './runtimeOutbox.mjs';
11
+ import { validateScriptDelivery } from './runtimePresentation.mjs';
11
12
  const exec = promisify(execFile);
12
13
  const hash = value => createHash('sha256').update(value).digest('hex');
13
14
  async function removeSandbox(name) {
@@ -139,6 +140,7 @@ export async function runScriptContainer({ bytes, release, runId, input, image,
139
140
  } else if (message?.type === 'result') {
140
141
  if (result !== undefined || Buffer.byteLength(JSON.stringify(message.result)) > contract.maxOutputBytes) throw new Error('OUTPUT_LIMIT');
141
142
  result = message.result;
143
+ validateScriptDelivery(result, contract.delivery);
142
144
  if (contract.maxLogBytes !== undefined) {
143
145
  result = { ...result, logs: utf8Tail(logTail) };
144
146
  if (Buffer.byteLength(JSON.stringify(result)) > contract.maxOutputBytes) throw new Error('OUTPUT_LIMIT');
@@ -0,0 +1,21 @@
1
+ import type {
2
+ ResultBlock,
3
+ RuntimePresentation,
4
+ } from "./runtimePresentation.mjs";
5
+ export const RESULT_VIEW_LIBRARY: "xiashe.result@1";
6
+ export type ResultViewNode =
7
+ | { type: "Report" | "Metrics" | "Records" | "Comparison"; block: number }
8
+ | { type: "Sources" | "Gaps" | "Creator" }
9
+ | { type: "Section"; title: string; children: ResultViewNode[] };
10
+ export type RuntimeView = {
11
+ version: 1;
12
+ library: typeof RESULT_VIEW_LIBRARY;
13
+ nodes: ResultViewNode[];
14
+ };
15
+ export function normalizeRuntimeView(
16
+ value: unknown,
17
+ blocks: ResultBlock[],
18
+ ): RuntimeView;
19
+ export function defaultRuntimeView(p: RuntimePresentation): RuntimeView;
20
+
21
+ export function viewHasCreator(view?: RuntimeView): boolean;
@@ -0,0 +1,117 @@
1
+ /** Portable, bounded view IR. No model code, tools, URLs or credentials are executable. */
2
+ export const RESULT_VIEW_LIBRARY = "xiashe.result@1";
3
+ const kinds = [
4
+ "Report",
5
+ "Metrics",
6
+ "Records",
7
+ "Comparison",
8
+ "Sources",
9
+ "Gaps",
10
+ "Creator",
11
+ "Section",
12
+ ];
13
+ export function normalizeRuntimeView(value, blocks) {
14
+ const fail = () => {
15
+ throw Error("INVALID_RUNTIME_VIEW");
16
+ };
17
+ if (
18
+ !value ||
19
+ value.version !== 1 ||
20
+ value.library !== RESULT_VIEW_LIBRARY ||
21
+ !Array.isArray(value.nodes) ||
22
+ !value.nodes.length
23
+ )
24
+ return fail();
25
+ let count = 0;
26
+ const seen = new Set();
27
+ const singleton = new Set();
28
+ const node = (v, depth = 0) => {
29
+ if (
30
+ !v ||
31
+ typeof v !== "object" ||
32
+ ++count > 60 ||
33
+ depth > 5 ||
34
+ !kinds.includes(v.type)
35
+ )
36
+ return fail();
37
+ const allowed =
38
+ v.type === "Section"
39
+ ? ["type", "title", "children"]
40
+ : ["Report", "Metrics", "Records", "Comparison"].includes(v.type)
41
+ ? ["type", "block"]
42
+ : ["type"];
43
+ if (Object.keys(v).some((k) => !allowed.includes(k))) return fail();
44
+ if (v.type === "Section") {
45
+ if (
46
+ typeof v.title !== "string" ||
47
+ !v.title.trim() ||
48
+ v.title.length > 200 ||
49
+ !Array.isArray(v.children) ||
50
+ !v.children.length
51
+ )
52
+ return fail();
53
+ return {
54
+ type: v.type,
55
+ title: v.title.trim(),
56
+ children: v.children.map((c) => node(c, depth + 1)),
57
+ };
58
+ }
59
+ if (allowed.includes("block")) {
60
+ if (
61
+ !Number.isInteger(v.block) ||
62
+ v.block < 0 ||
63
+ !blocks[v.block] ||
64
+ seen.has(v.block)
65
+ )
66
+ return fail();
67
+ const expected = {
68
+ Report: ["text"],
69
+ Metrics: ["metrics"],
70
+ Records: ["cards", "table"],
71
+ Comparison: ["table"],
72
+ }[v.type];
73
+ if (!expected.includes(blocks[v.block].type)) return fail();
74
+ seen.add(v.block);
75
+ return { type: v.type, block: v.block };
76
+ }
77
+ if (singleton.has(v.type)) return fail();
78
+ singleton.add(v.type);
79
+ return { type: v.type };
80
+ };
81
+ const nodes = value.nodes.map((n) => node(n));
82
+ // Every returned block remains accessible; a generated layout cannot hide evidence.
83
+ if (seen.size !== blocks.length) return fail();
84
+ return { version: 1, library: RESULT_VIEW_LIBRARY, nodes };
85
+ }
86
+ export function defaultRuntimeView(p) {
87
+ const kind = {
88
+ text: "Report",
89
+ metrics: "Metrics",
90
+ cards: "Records",
91
+ table: "Comparison",
92
+ };
93
+ const ordered = p.blocks.map((b, i) => ({ type: kind[b.type], block: i }));
94
+ if (p.layout === "comparison")
95
+ ordered.sort(
96
+ (a, b) =>
97
+ (a.type === "Metrics" ? -2 : a.type === "Comparison" ? -1 : 0) -
98
+ (b.type === "Metrics" ? -2 : b.type === "Comparison" ? -1 : 0),
99
+ );
100
+ if (p.layout === "draft" || p.layout === "report")
101
+ ordered.sort(
102
+ (a, b) => Number(b.type === "Report") - Number(a.type === "Report"),
103
+ );
104
+ return {
105
+ version: 1,
106
+ library: RESULT_VIEW_LIBRARY,
107
+ nodes: [...ordered, { type: "Creator" }],
108
+ };
109
+ }
110
+
111
+ export function viewHasCreator(view) {
112
+ return !!view?.nodes.some(function visit(n) {
113
+ return (
114
+ n.type === "Creator" || (n.type === "Section" && n.children.some(visit))
115
+ );
116
+ });
117
+ }