@xiashe/sdk 0.1.42 → 0.1.43
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/index.mjs +9 -1
- package/package.json +2 -1
- package/paymentErrors.d.mts +11 -0
- package/runtimeAgent.mjs +7 -2
- package/runtimeAgentHost.mjs +1 -0
- package/runtimeMcp.mjs +5 -2
- package/runtimePresentation.d.mts +26 -0
- package/runtimePresentation.mjs +149 -0
- package/runtimeScript.mjs +2 -0
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.
|
|
22
|
+
export const VERSION = '0.1.43';
|
|
23
23
|
export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
|
|
24
24
|
|
|
25
25
|
export const DEFAULTS = {
|
|
@@ -753,6 +753,14 @@ export class XiasheClient {
|
|
|
753
753
|
return this.mutation(api.runtimeHosts.finishRun, this.runtimeHostAuth({ runId, leaseToken, eventId, status, resultJson }));
|
|
754
754
|
}
|
|
755
755
|
|
|
756
|
+
async getRuntimeDelivery(runId) {
|
|
757
|
+
return this.query(api.superconnector.delivery, this.authArgs({ runId }));
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
async runtimeHostDelivery(runId) {
|
|
761
|
+
return this.mutation(api.runtimeHosts.delivery, this.runtimeHostAuth({ runId }));
|
|
762
|
+
}
|
|
763
|
+
|
|
756
764
|
async runtimeHostRunStatus(runId) {
|
|
757
765
|
return this.mutation(api.runtimeHosts.status, this.runtimeHostAuth({ runId }));
|
|
758
766
|
}
|
package/package.json
CHANGED
|
@@ -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);
|
package/runtimeAgentHost.mjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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,26 @@
|
|
|
1
|
+
export const RESULT_COMPONENTS: readonly ["text", "cards", "table", "metrics"];
|
|
2
|
+
export const RESULT_LAYOUTS: readonly ["report", "comparison", "draft"];
|
|
3
|
+
export type ResultLayout = typeof RESULT_LAYOUTS[number];
|
|
4
|
+
export type ResultComponent = typeof RESULT_COMPONENTS[number];
|
|
5
|
+
export type DeliveryDefinition = {
|
|
6
|
+
input: string; outcome: string; dataUsage: string; failurePolicy: string;
|
|
7
|
+
components: ResultComponent[];
|
|
8
|
+
layout?: ResultLayout;
|
|
9
|
+
};
|
|
10
|
+
export type ResultBlock =
|
|
11
|
+
| { type: 'text'; title: string; content: string }
|
|
12
|
+
| { type: 'cards'; title: string; items: { title: string; description: string; url?: string }[] }
|
|
13
|
+
| { type: 'table'; title: string; columns: string[]; rows: string[][] }
|
|
14
|
+
| { type: 'metrics'; title: string; items: { label: string; value: string }[] };
|
|
15
|
+
export type RuntimePresentation = {
|
|
16
|
+
version: 1; title: string; summary: string; blocks: ResultBlock[];
|
|
17
|
+
sources: { title: string; url: string }[]; incomplete: string[];
|
|
18
|
+
layout?: ResultLayout;
|
|
19
|
+
};
|
|
20
|
+
export function resultSourceUrl(value: unknown): string | null;
|
|
21
|
+
export function normalizeDeliveryDefinition(value: unknown): DeliveryDefinition;
|
|
22
|
+
export function normalizeRuntimePresentation(value: unknown): RuntimePresentation;
|
|
23
|
+
export function validateAgentDelivery(result: unknown, definition?: DeliveryDefinition, completed?: boolean): void;
|
|
24
|
+
export function validateScriptDelivery(result: unknown, definition?: DeliveryDefinition): void;
|
|
25
|
+
export function presentationSections(presentation: RuntimePresentation): { layout: ResultLayout; primary: ResultBlock; overview: ResultBlock[]; supporting: ResultBlock[] };
|
|
26
|
+
export function primaryResultText(presentation: RuntimePresentation): string;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// Shared validation for backend and local Agent receipts. No host or network access.
|
|
2
|
+
export const RESULT_COMPONENTS = ['text', 'cards', 'table', 'metrics'];
|
|
3
|
+
export const RESULT_LAYOUTS = ['report', 'comparison', 'draft'];
|
|
4
|
+
const fail = () => { throw Error('INVALID_RUNTIME_PRESENTATION'); };
|
|
5
|
+
function object(value) {
|
|
6
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
7
|
+
return fail();
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
function text(value, max = 1000) {
|
|
11
|
+
if (typeof value !== 'string' || !value.trim() || value.length > max)
|
|
12
|
+
return fail();
|
|
13
|
+
return value.trim();
|
|
14
|
+
}
|
|
15
|
+
function array(value, max) {
|
|
16
|
+
if (!Array.isArray(value) || value.length > max)
|
|
17
|
+
return fail();
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
export function resultSourceUrl(value) {
|
|
21
|
+
if (typeof value !== 'string' || value.length > 2000)
|
|
22
|
+
return null;
|
|
23
|
+
try {
|
|
24
|
+
const url = new URL(value);
|
|
25
|
+
return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password ? url.href : null;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function source(value) {
|
|
32
|
+
const row = object(value), url = resultSourceUrl(row.url);
|
|
33
|
+
if (!url)
|
|
34
|
+
return fail();
|
|
35
|
+
return { title: text(row.title, 200), url };
|
|
36
|
+
}
|
|
37
|
+
export function normalizeDeliveryDefinition(value) {
|
|
38
|
+
const row = object(value);
|
|
39
|
+
if (Object.keys(row).some(k => !['input', 'outcome', 'dataUsage', 'failurePolicy', 'components', 'layout'].includes(k)))
|
|
40
|
+
return fail();
|
|
41
|
+
const components = array(row.components, 4).map(item => {
|
|
42
|
+
if (!RESULT_COMPONENTS.includes(item))
|
|
43
|
+
return fail();
|
|
44
|
+
return item;
|
|
45
|
+
});
|
|
46
|
+
if (!components.length || new Set(components).size !== components.length)
|
|
47
|
+
return fail();
|
|
48
|
+
if (row.layout !== undefined && !RESULT_LAYOUTS.includes(row.layout)) return fail();
|
|
49
|
+
if (row.layout === 'comparison' && !components.includes('table') || row.layout === 'draft' && !components.includes('text')) return fail();
|
|
50
|
+
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 }) };
|
|
51
|
+
}
|
|
52
|
+
/** Select only known presentation fields. HTML, scripts and execution instructions are never accepted. */
|
|
53
|
+
export function normalizeRuntimePresentation(value) {
|
|
54
|
+
const row = object(value);
|
|
55
|
+
if (row.version !== 1)
|
|
56
|
+
return fail();
|
|
57
|
+
const blocks = array(row.blocks, 20).map(item => {
|
|
58
|
+
const block = object(item), title = text(block.title, 200);
|
|
59
|
+
if (block.type === 'text')
|
|
60
|
+
return { type: 'text', title, content: text(block.content, 16000) };
|
|
61
|
+
if (block.type === 'cards')
|
|
62
|
+
return { type: 'cards', title, items: array(block.items, 50).map(item => {
|
|
63
|
+
const card = object(item);
|
|
64
|
+
const url = card.url === undefined ? undefined : resultSourceUrl(card.url);
|
|
65
|
+
if (url === null)
|
|
66
|
+
return fail();
|
|
67
|
+
return { title: text(card.title, 200), description: text(card.description, 4000), ...(url ? { url } : {}) };
|
|
68
|
+
}) };
|
|
69
|
+
if (block.type === 'metrics')
|
|
70
|
+
return { type: 'metrics', title, items: array(block.items, 12).map(item => {
|
|
71
|
+
const metric = object(item);
|
|
72
|
+
return { label: text(metric.label, 100), value: text(metric.value, 100) };
|
|
73
|
+
}) };
|
|
74
|
+
if (block.type === 'table') {
|
|
75
|
+
const columns = array(block.columns, 12).map(item => text(item, 100));
|
|
76
|
+
if (!columns.length)
|
|
77
|
+
return fail();
|
|
78
|
+
const rows = array(block.rows, 100).map(item => {
|
|
79
|
+
const cells = array(item, columns.length);
|
|
80
|
+
if (cells.length !== columns.length)
|
|
81
|
+
return fail();
|
|
82
|
+
return cells.map(cell => {
|
|
83
|
+
if (typeof cell !== 'string' || cell.length > 2000)
|
|
84
|
+
return fail();
|
|
85
|
+
return cell;
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
return { type: 'table', title, columns, rows };
|
|
89
|
+
}
|
|
90
|
+
return fail();
|
|
91
|
+
});
|
|
92
|
+
if (!blocks.length)
|
|
93
|
+
return fail();
|
|
94
|
+
if (row.layout !== undefined && !RESULT_LAYOUTS.includes(row.layout)) return fail();
|
|
95
|
+
if (row.layout === 'comparison' && !blocks.some(b => b.type === 'table') || row.layout === 'draft' && !blocks.some(b => b.type === 'text')) return fail();
|
|
96
|
+
const result = { version: 1, title: text(row.title, 200), summary: text(row.summary, 2000), blocks,
|
|
97
|
+
sources: array(row.sources ?? [], 50).map(source), incomplete: array(row.incomplete ?? [], 20).map(item => text(item, 1000)), ...(row.layout === undefined ? {} : { layout: row.layout }) };
|
|
98
|
+
if (new TextEncoder().encode(JSON.stringify(result)).length > 160000)
|
|
99
|
+
return fail();
|
|
100
|
+
return result;
|
|
101
|
+
}
|
|
102
|
+
export function validateAgentDelivery(result, definition, completed = false) {
|
|
103
|
+
const row = object(result);
|
|
104
|
+
if (row.presentation === undefined) {
|
|
105
|
+
if (definition && completed)
|
|
106
|
+
throw Error('RUNTIME_DELIVERY_REQUIRED');
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const presentation = normalizeRuntimePresentation(row.presentation);
|
|
110
|
+
if (definition && completed && definition.components.some(type => !presentation.blocks.some(block => block.type === type)))
|
|
111
|
+
throw Error('RUNTIME_DELIVERY_INCOMPLETE');
|
|
112
|
+
if (definition?.layout && completed && presentation.layout !== definition.layout) throw Error('RUNTIME_DELIVERY_LAYOUT_MISMATCH');
|
|
113
|
+
}
|
|
114
|
+
/** A stable, shared reading order for native, web and portable delivery. */
|
|
115
|
+
export function presentationSections(presentation) {
|
|
116
|
+
const layout = presentation.layout ?? 'report';
|
|
117
|
+
const preferred = layout === 'comparison' ? ['table'] : layout === 'draft' ? ['text'] : ['text', 'cards', 'table', 'metrics'];
|
|
118
|
+
let primaryIndex = -1;
|
|
119
|
+
for (const type of preferred) {
|
|
120
|
+
primaryIndex = presentation.blocks.findIndex(block => block.type === type);
|
|
121
|
+
if (primaryIndex >= 0) break;
|
|
122
|
+
}
|
|
123
|
+
if (primaryIndex < 0) primaryIndex = 0;
|
|
124
|
+
const secondary = presentation.blocks.filter((_, i) => i !== primaryIndex);
|
|
125
|
+
const overview = layout === 'draft' ? [] : secondary.filter(block => block.type === 'metrics');
|
|
126
|
+
return { layout, primary: presentation.blocks[primaryIndex], overview, supporting: secondary.filter(block => !overview.includes(block)) };
|
|
127
|
+
}
|
|
128
|
+
export function primaryResultText(presentation) {
|
|
129
|
+
const { primary } = presentationSections(presentation);
|
|
130
|
+
if (primary.type === 'text') return primary.content;
|
|
131
|
+
if (primary.type === 'cards') return primary.items.map(item => `${item.title}\n${item.description}${item.url ? '\n' + item.url : ''}`).join('\n\n');
|
|
132
|
+
if (primary.type === 'metrics') return primary.items.map(item => `${item.label}: ${item.value}`).join('\n');
|
|
133
|
+
return [primary.columns, ...primary.rows].map(row => row.join('\t')).join('\n');
|
|
134
|
+
}
|
|
135
|
+
/** Script outputs are already collected as bounded declared files by the worker. */
|
|
136
|
+
export function validateScriptDelivery(result, definition) {
|
|
137
|
+
if (!definition) return;
|
|
138
|
+
const outputs = object(object(result).outputs);
|
|
139
|
+
const file = Object.values(outputs).find(item => item && typeof item === 'object' && item.path?.split('/').pop() === 'presentation.json');
|
|
140
|
+
if (!file || typeof file.content !== 'string') throw Error('RUNTIME_DELIVERY_REQUIRED');
|
|
141
|
+
let value;
|
|
142
|
+
try {
|
|
143
|
+
const content = file.encoding === 'base64'
|
|
144
|
+
? new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(atob(file.content), c => c.charCodeAt(0)))
|
|
145
|
+
: file.content;
|
|
146
|
+
value = JSON.parse(content);
|
|
147
|
+
} catch { return fail(); }
|
|
148
|
+
validateAgentDelivery({ presentation: value }, definition, true);
|
|
149
|
+
}
|
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');
|