@xiashe/sdk 0.1.46 → 0.1.47
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 +22 -1
- package/package.json +1 -1
- package/runtimeAgent.mjs +9 -4
- package/runtimeAgentHost.mjs +1 -0
- package/runtimeArtifactFiles.mjs +21 -0
- package/runtimeArtifacts.d.mts +2 -0
- package/runtimeArtifacts.mjs +14 -0
- package/runtimeHost.mjs +1 -0
- package/runtimeHttpRecovery.mjs +66 -0
- package/runtimeMcp.mjs +3 -2
- package/runtimeOutbox.mjs +5 -3
- package/runtimeProtocol.d.mts +5 -0
- package/runtimeProtocol.mjs +32 -0
- package/runtimeScript.mjs +1 -1
- package/runtimeSetup.mjs +1 -1
- package/serviceRelease.d.mts +2 -0
- package/serviceRelease.mjs +3 -0
package/index.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { paymentCustomerError, formatPaymentCustomerError } from './paymentErrors.mjs';
|
|
2
2
|
import { privateDirectory, checkPrivateFile, withPrivateLock, atomicPrivateJson } from './privateState.mjs';
|
|
3
3
|
import { boundedJsonRequest, responseError } from './http.mjs';
|
|
4
|
+
import { runtimeFailure } from './runtimeProtocol.mjs';
|
|
4
5
|
import { createHash, randomUUID } from 'node:crypto';
|
|
5
6
|
import { existsSync } from 'node:fs';
|
|
6
7
|
import { mkdir, readFile, writeFile, stat } from 'node:fs/promises';
|
|
@@ -16,10 +17,14 @@ export { runAgentTaskCycle, createCodexTaskExecutor } from './agentTaskRunner.mj
|
|
|
16
17
|
export { createRuntimeAgentHost } from './runtimeAgentHost.mjs';
|
|
17
18
|
export { createRuntimeAgentSession } from './runtimeAgent.mjs';
|
|
18
19
|
export { serveRuntimeMcp } from './runtimeMcp.mjs';
|
|
20
|
+
export { runtimeFailure, RUNTIME_PROTOCOL } from './runtimeProtocol.mjs';
|
|
21
|
+
export { describeRuntimeArtifact } from './runtimeArtifactFiles.mjs';
|
|
22
|
+
export { normalizeRuntimeArtifacts } from './runtimeArtifacts.mjs';
|
|
23
|
+
export { createRuntimeHttpRecovery } from './runtimeHttpRecovery.mjs';
|
|
19
24
|
|
|
20
25
|
export { safeOutput as redactCredentials } from './outputSafety.mjs';
|
|
21
26
|
|
|
22
|
-
export const VERSION = '0.1.
|
|
27
|
+
export const VERSION = '0.1.47';
|
|
23
28
|
export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
|
|
24
29
|
|
|
25
30
|
export const DEFAULTS = {
|
|
@@ -63,6 +68,8 @@ export class XiasheError extends Error {
|
|
|
63
68
|
this.status = options.status;
|
|
64
69
|
this.retryAfterSeconds = options.retryAfterSeconds;
|
|
65
70
|
this.details = options.details;
|
|
71
|
+
this.uncertain = options.uncertain;
|
|
72
|
+
this.nextAction = options.nextAction;
|
|
66
73
|
}
|
|
67
74
|
}
|
|
68
75
|
|
|
@@ -277,6 +284,8 @@ function normalizeConvexError(error) {
|
|
|
277
284
|
if (/ArgumentValidationError/.test(message)) {
|
|
278
285
|
return new XiasheError('The server rejected the request arguments.', { code: 'CONVEX_INVALID_ARGUMENTS' });
|
|
279
286
|
}
|
|
287
|
+
const failure = runtimeFailure(error);
|
|
288
|
+
if (failure.code !== 'RUNTIME_REQUEST_FAILED') return new XiasheError(failure.code, { ...failure, details: failure });
|
|
280
289
|
if (/fetch failed|failed to fetch|network request failed|econnrefused|enotfound|eai_again/i.test(message)) {
|
|
281
290
|
return new XiasheError('Unable to reach Convex deployment.', {
|
|
282
291
|
code: 'CONVEX_NETWORK_UNAVAILABLE',
|
|
@@ -370,6 +379,12 @@ export async function mcpCall(mcpUrl, runtimeToken, method, params = {}, timeout
|
|
|
370
379
|
}
|
|
371
380
|
|
|
372
381
|
export function decodeMcpToolResult(result) {
|
|
382
|
+
if (result?.isError) {
|
|
383
|
+
let failure = result.structuredContent?.error;
|
|
384
|
+
if (!failure) { try { failure = JSON.parse(result.content?.find(item => item.type === 'text')?.text); } catch {} }
|
|
385
|
+
throw new XiasheError(failure?.code || 'RUNTIME_REQUEST_FAILED', { ...failure, details: failure });
|
|
386
|
+
}
|
|
387
|
+
if (result?.structuredContent) return result.structuredContent;
|
|
373
388
|
const text = result?.content?.find?.((item) => item?.type === 'text')?.text;
|
|
374
389
|
if (typeof text !== 'string') {
|
|
375
390
|
return result;
|
|
@@ -767,6 +782,12 @@ export class XiasheClient {
|
|
|
767
782
|
async runtimeHostDelivery(runId) {
|
|
768
783
|
return this.mutation(api.runtimeHosts.delivery, this.runtimeHostAuth({ runId }));
|
|
769
784
|
}
|
|
785
|
+
async runtimeHostAcknowledgeResult(runId) {
|
|
786
|
+
return this.mutation(api.runtimeHosts.acknowledgeResult, this.runtimeHostAuth({ runId }));
|
|
787
|
+
}
|
|
788
|
+
async acknowledgeRuntimeResult(runId, client = 'sdk') {
|
|
789
|
+
return this.mutation(api.superconnector.acknowledgeResult, this.authArgs({ runId, client }));
|
|
790
|
+
}
|
|
770
791
|
|
|
771
792
|
async runtimeHostRunStatus(runId) {
|
|
772
793
|
return this.mutation(api.runtimeHosts.status, this.runtimeHostAuth({ runId }));
|
package/package.json
CHANGED
package/runtimeAgent.mjs
CHANGED
|
@@ -5,6 +5,8 @@ import os from 'node:os';
|
|
|
5
5
|
import { inspectRuntimeArchive, runtimePrincipal, safeRuntimePath } from './runtime.mjs';
|
|
6
6
|
import { reportRuntimeResult } from './runtimeOutbox.mjs';
|
|
7
7
|
import { validateAgentDelivery } from './runtimePresentation.mjs';
|
|
8
|
+
import { normalizeRuntimeArtifacts } from './runtimeArtifacts.mjs';
|
|
9
|
+
import { runtimeFailure } from './runtimeProtocol.mjs';
|
|
8
10
|
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
9
11
|
const terminal = new Set(['completed', 'failed', 'uncertain', 'cancelled']);
|
|
10
12
|
|
|
@@ -57,7 +59,7 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
|
|
|
57
59
|
let resultJson = JSON.stringify(result);
|
|
58
60
|
if (Buffer.byteLength(resultJson) > contract.maxOutputBytes) resultJson = '0';
|
|
59
61
|
receipt = await reportRuntimeResult(client, { runId, leaseToken, status, resultJson }, { outboxRoot });
|
|
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.' };
|
|
62
|
+
return { runId, status: receipt.serverStatus ?? status, resultSaved: receipt.delivered, 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.' };
|
|
61
63
|
};
|
|
62
64
|
const interrupt = () => store('uncertain', { error: 'AGENT_SESSION_INTERRUPTED' }).catch(() => { stop(); });
|
|
63
65
|
const heartbeat = async () => {
|
|
@@ -91,9 +93,10 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
|
|
|
91
93
|
async function call(name, args = {}) {
|
|
92
94
|
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('INVALID_ARGUMENTS');
|
|
93
95
|
if (name === 'delivery') return await client.getRuntimeDelivery(runId);
|
|
96
|
+
if (name === 'ack_delivery') return await client.acknowledgeRuntimeResult(runId, 'agent');
|
|
94
97
|
if (name === 'status') {
|
|
95
98
|
const row = await client.getSkillRun(runId);
|
|
96
|
-
return { runId, status: row.status, progressPercent: row.progressPercent, message: row.progressMessage, closed, receipt };
|
|
99
|
+
return { runId, status: row.status, deliveryState: row.deliveryState, progressPercent: row.progressPercent, message: row.progressMessage, closed, receipt };
|
|
97
100
|
}
|
|
98
101
|
if (name === 'finish' && submittedResult) {
|
|
99
102
|
if (args.status !== submittedResult.status || JSON.stringify(args.result) !== submittedResult.resultJson) throw new Error('OUTBOX_RESULT_CONFLICT');
|
|
@@ -114,7 +117,7 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
|
|
|
114
117
|
}
|
|
115
118
|
if (name === 'execute') {
|
|
116
119
|
if (!contract.actionIds.includes(args.actionId) || typeof args.requestKey !== 'string' || !/^[A-Za-z0-9_.:-]{1,80}$/.test(args.requestKey)) throw new Error('ACTION_NOT_ALLOWED');
|
|
117
|
-
if (!actionKeys.has(args.requestKey) && actionKeys.size >= 50) throw new Error('
|
|
120
|
+
if (!actionKeys.has(args.requestKey) && actionKeys.size >= (contract.maxApiCalls ?? 50)) throw new Error('RUNTIME_ACTION_LIMIT');
|
|
118
121
|
const grant = grants.find(grant => grant.actionIds.includes(args.actionId));
|
|
119
122
|
if (!grant) throw new Error('ACTION_NOT_ALLOWED');
|
|
120
123
|
actionKeys.add(args.requestKey);
|
|
@@ -128,7 +131,8 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
|
|
|
128
131
|
if (name === 'action_status') {
|
|
129
132
|
if (!children.has(args.runId)) throw new Error('ACTION_RUN_NOT_FOUND');
|
|
130
133
|
const row = await client.getSkillRun(args.runId);
|
|
131
|
-
return { runId: row._id, status: row.status, result: row.resultJson === undefined ? undefined : JSON.parse(row.resultJson), errorCode: row.errorCode
|
|
134
|
+
return { runId: row._id, status: row.status, result: row.resultJson === undefined ? undefined : JSON.parse(row.resultJson), errorCode: row.errorCode,
|
|
135
|
+
failure: row.errorCode ? row.failure ?? runtimeFailure({ code: row.errorCode }, { uncertain: row.status === 'uncertain', retryAfterSeconds: row.retryAfterSeconds }) : null };
|
|
132
136
|
}
|
|
133
137
|
if (name === 'progress') {
|
|
134
138
|
if (!Number.isFinite(args.percent) || args.percent < progressPercent || args.percent > 99 || typeof args.message !== 'string' || args.message.length > 500) throw new Error('INVALID_PROGRESS');
|
|
@@ -138,6 +142,7 @@ export async function createLeasedRuntimeAgentSession(client, { release, bytes,
|
|
|
138
142
|
}
|
|
139
143
|
if (name === 'finish') {
|
|
140
144
|
if (!['completed', 'failed', 'uncertain'].includes(args.status) || args.result === undefined || Buffer.byteLength(JSON.stringify(args.result)) > contract.maxOutputBytes) throw new Error('INVALID_RESULT');
|
|
145
|
+
normalizeRuntimeArtifacts(args.result?.artifacts);
|
|
141
146
|
// Reject a correctable presentation error before stopping the lease or
|
|
142
147
|
// persisting an immutable outbox receipt.
|
|
143
148
|
if (contract.delivery || args.result && typeof args.result === 'object' && 'presentation' in args.result) validateAgentDelivery(args.result, contract.delivery, args.status === 'completed');
|
package/runtimeAgentHost.mjs
CHANGED
|
@@ -73,6 +73,7 @@ export async function createRuntimeAgentHost(original, {
|
|
|
73
73
|
const scoped = {
|
|
74
74
|
...receipts,
|
|
75
75
|
getRuntimeDelivery: id => client.runtimeHostDelivery(id),
|
|
76
|
+
acknowledgeRuntimeResult: id => client.runtimeHostAcknowledgeResult(id),
|
|
76
77
|
listConnectorGrants: async () => [{ _id: 'task-grant', actionIds: JSON.parse(release.contractJson).actionIds }],
|
|
77
78
|
getConnectorActionDefinition: actionId => client.runtimeHostActionDefinition({ ...auth, actionId }),
|
|
78
79
|
heartbeatRuntimeRun: args => client.heartbeatRuntimeHostRun({ ...args, ...auth }),
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { open, lstat } from 'node:fs/promises';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { normalizeRuntimeArtifacts } from './runtimeArtifacts.mjs';
|
|
5
|
+
/** Hash as a stream, never buffer a large result or send it to the business API. */
|
|
6
|
+
export async function describeRuntimeArtifact(filePath) {
|
|
7
|
+
const before = await lstat(filePath);
|
|
8
|
+
if (!before.isFile() || before.isSymbolicLink()) throw new Error('RUNTIME_ARTIFACT_FILE_INVALID');
|
|
9
|
+
normalizeRuntimeArtifacts([{ name: path.basename(filePath), sizeBytes: before.size, sha256: '0'.repeat(64), location: 'agent' }]);
|
|
10
|
+
const handle = await open(filePath, 'r');
|
|
11
|
+
try {
|
|
12
|
+
const opened = await handle.stat();
|
|
13
|
+
if (opened.ino !== before.ino || opened.dev !== before.dev) throw new Error('RUNTIME_ARTIFACT_FILE_CHANGED');
|
|
14
|
+
const hash = createHash('sha256');
|
|
15
|
+
const stream = handle.createReadStream({ autoClose: false });
|
|
16
|
+
for await (const chunk of stream) hash.update(chunk);
|
|
17
|
+
const after = await handle.stat();
|
|
18
|
+
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) throw new Error('RUNTIME_ARTIFACT_FILE_CHANGED');
|
|
19
|
+
return normalizeRuntimeArtifacts([{ name: path.basename(filePath), sizeBytes: after.size, sha256: hash.digest('hex'), location: 'agent' }])[0];
|
|
20
|
+
} finally { await handle.close(); }
|
|
21
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Large files stay on the executing Agent. This manifest contains no bytes, local paths or credentials. */
|
|
2
|
+
export function normalizeRuntimeArtifacts(value) {
|
|
3
|
+
if (value === undefined) return [];
|
|
4
|
+
if (!Array.isArray(value) || value.length > 20) throw new Error('RUNTIME_ARTIFACT_MANIFEST_INVALID');
|
|
5
|
+
const names = new Set();
|
|
6
|
+
return value.map(item => {
|
|
7
|
+
if (!item || typeof item !== 'object' || Array.isArray(item) || Object.keys(item).some(key => !['name', 'sizeBytes', 'sha256', 'location'].includes(key)) ||
|
|
8
|
+
typeof item.name !== 'string' || !item.name.trim() || item.name.length > 180 || /[\\/\u0000-\u001f]/.test(item.name) || ['.', '..'].includes(item.name) || names.has(item.name) ||
|
|
9
|
+
!Number.isSafeInteger(item.sizeBytes) || item.sizeBytes < 0 || item.sizeBytes > 10 * 1024 ** 3 ||
|
|
10
|
+
typeof item.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(item.sha256) || item.location !== 'agent') throw new Error('RUNTIME_ARTIFACT_MANIFEST_INVALID');
|
|
11
|
+
names.add(item.name);
|
|
12
|
+
return { name: item.name, sizeBytes: item.sizeBytes, sha256: item.sha256, location: 'agent' };
|
|
13
|
+
});
|
|
14
|
+
}
|
package/runtimeHost.mjs
CHANGED
|
@@ -123,6 +123,7 @@ export async function serveRuntimeScriptHost(original, { image, once = false } =
|
|
|
123
123
|
let resultJson = JSON.stringify(result);
|
|
124
124
|
if (!Number.isSafeInteger(maxOutputBytes) || Buffer.byteLength(resultJson) > maxOutputBytes) resultJson = '0';
|
|
125
125
|
const receipt = await reportRuntimeResult(receipts, { runId, leaseToken, status, resultJson }, { outboxRoot });
|
|
126
|
+
status = receipt.serverStatus ?? status;
|
|
126
127
|
onEvent({ type: 'result', runId, status, receipt });
|
|
127
128
|
if (once) return { runId, status, receipt };
|
|
128
129
|
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { privateDirectory, checkPrivateFile, atomicPrivateJson, withPrivateLock } from './privateState.mjs';
|
|
6
|
+
import { normalizeRuntimeArtifacts } from './runtimeArtifacts.mjs';
|
|
7
|
+
import { runtimeFailure } from './runtimeProtocol.mjs';
|
|
8
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
9
|
+
|
|
10
|
+
/** Recovery-only adapter. Deliberately has no start/execute method or business retry loop. */
|
|
11
|
+
export function createRuntimeHttpRecovery({ mcpUrl, runtimeToken, callTool }, { stateRoot = path.join(os.homedir(), '.xiashe', 'http-runtime-outbox') } = {}) {
|
|
12
|
+
if (typeof runtimeToken !== 'string' || !runtimeToken || typeof callTool !== 'function') throw Error('RUNTIME_AUTH_REQUIRED');
|
|
13
|
+
const url = new URL(mcpUrl);
|
|
14
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.hash || url.search) throw Error('RUNTIME_ENDPOINT_INVALID');
|
|
15
|
+
const scope = digest(`${url.href}:${runtimeToken}`);
|
|
16
|
+
const directory = path.join(path.resolve(stateRoot), scope);
|
|
17
|
+
const fileFor = runId => {
|
|
18
|
+
if (typeof runId !== 'string' || !runId || runId.length > 128) throw Error('RUNTIME_RUN_INVALID');
|
|
19
|
+
return path.join(directory, digest(runId) + '.json');
|
|
20
|
+
};
|
|
21
|
+
const invoke = (operation, args) => callTool(`xiashe.runtime_${operation}`, args);
|
|
22
|
+
async function read(file, runId) {
|
|
23
|
+
const info = await checkPrivateFile(file);
|
|
24
|
+
if (!info) return null;
|
|
25
|
+
if (info.size > 500000) throw Error('INVALID_OUTBOX_RECORD');
|
|
26
|
+
const row = JSON.parse(await readFile(file, 'utf8'));
|
|
27
|
+
if (row.scope !== scope || row.runId !== runId || typeof row.eventId !== 'string' || !['completed', 'failed', 'uncertain'].includes(row.status) ||
|
|
28
|
+
!['queued', 'saved'].includes(row.phase) || typeof row.resultJson !== 'string' || Buffer.byteLength(row.resultJson) > 200000) throw Error('INVALID_OUTBOX_RECORD');
|
|
29
|
+
normalizeRuntimeArtifacts(JSON.parse(row.resultJson)?.artifacts);
|
|
30
|
+
return row;
|
|
31
|
+
}
|
|
32
|
+
async function send(file, row) {
|
|
33
|
+
if (row.phase === 'saved') return { runId: row.runId, saved: true, replayed: true };
|
|
34
|
+
try {
|
|
35
|
+
const receipt = await invoke('finish', { runId: row.runId, eventId: row.eventId, status: row.status, result: JSON.parse(row.resultJson) });
|
|
36
|
+
await atomicPrivateJson(file, { ...row, phase: 'saved' });
|
|
37
|
+
return { runId: row.runId, saved: true, receipt };
|
|
38
|
+
} catch (error) { return { runId: row.runId, saved: false, failure: runtimeFailure(error, { uncertain: true }) }; }
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
async report({ runId, status, result }) {
|
|
42
|
+
const file = fileFor(runId), resultJson = JSON.stringify(result);
|
|
43
|
+
if (!['completed', 'failed', 'uncertain'].includes(status) || typeof resultJson !== 'string' || Buffer.byteLength(resultJson) > 200000) throw Error('OUTPUT_LIMIT');
|
|
44
|
+
normalizeRuntimeArtifacts(result?.artifacts);
|
|
45
|
+
await privateDirectory(directory);
|
|
46
|
+
return withPrivateLock(file, async () => {
|
|
47
|
+
let row = await read(file, runId);
|
|
48
|
+
if (row && (row.status !== status || row.resultJson !== resultJson)) throw Error('OUTBOX_RESULT_CONFLICT');
|
|
49
|
+
if (!row) { row = { scope, runId, status, resultJson, eventId: randomUUID(), phase: 'queued' }; await atomicPrivateJson(file, row); }
|
|
50
|
+
return send(file, row);
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
async retry(runId) {
|
|
54
|
+
const file = fileFor(runId);
|
|
55
|
+
await privateDirectory(directory);
|
|
56
|
+
return withPrivateLock(file, async () => {
|
|
57
|
+
const row = await read(file, runId);
|
|
58
|
+
if (!row) throw Error('RUNTIME_RESULT_NOT_FOUND');
|
|
59
|
+
return send(file, row);
|
|
60
|
+
});
|
|
61
|
+
},
|
|
62
|
+
status: (runId, recoveryKey) => invoke('status', { runId, ...(recoveryKey ? { recoveryKey } : {}) }),
|
|
63
|
+
delivery: (runId, recoveryKey) => invoke('delivery', { runId, ...(recoveryKey ? { recoveryKey } : {}) }),
|
|
64
|
+
acknowledge: (runId, recoveryKey) => invoke('ack_delivery', { runId, ...(recoveryKey ? { recoveryKey } : {}) }),
|
|
65
|
+
};
|
|
66
|
+
}
|
package/runtimeMcp.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { StringDecoder } from 'node:string_decoder';
|
|
2
|
+
import { runtimeToolError } from './runtimeProtocol.mjs';
|
|
2
3
|
const object = properties => ({ type: 'object', properties, additionalProperties: false });
|
|
3
4
|
const text = { type: 'string' };
|
|
4
5
|
const tool = (name, description, properties = {}, required = []) => ({ name: 'xiashe.runtime_' + name, description,
|
|
@@ -12,10 +13,10 @@ export const runtimeTools = [
|
|
|
12
13
|
tool('progress', 'Report monotonic progress, up to 99 before finish.', { percent: { type: 'number', minimum: 0, maximum: 99 }, message: text }, ['percent', 'message']),
|
|
13
14
|
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
15
|
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.'),
|
|
16
|
+
tool('ack_delivery', 'Acknowledge this host actually received the saved result. Never implies delivery to every client.'),
|
|
15
17
|
tool('status', 'Read this run status, including cancellation or uncertainty.'),
|
|
16
18
|
tool('cancel', 'Cancel further actions for this run. Already-issued external operations may still finish.'),
|
|
17
19
|
];
|
|
18
|
-
const safeError = error => /^[A-Z][A-Z_]{1,100}$/.test(error?.message) ? error.message : 'RUNTIME_REQUEST_FAILED';
|
|
19
20
|
|
|
20
21
|
/** MCP 2025-06-18 stdio: newline-delimited JSON-RPC, bounded input, no stdout logs. */
|
|
21
22
|
export async function serveRuntimeMcp(session, { input = process.stdin, output = process.stdout, signal } = {}) {
|
|
@@ -88,7 +89,7 @@ export async function serveRuntimeMcp(session, { input = process.stdin, output =
|
|
|
88
89
|
const delivery = definition.name === 'xiashe.runtime_delivery';
|
|
89
90
|
const markdown = delivery && typeof value?.markdown === 'string' ? value.markdown : null;
|
|
90
91
|
result(id, { content: [...(markdown ? [{ type: 'text', text: markdown }] : []), { type: 'text', text: JSON.stringify(value) }], ...(delivery ? { structuredContent: value } : {}) });
|
|
91
|
-
} catch (failure) { result(id,
|
|
92
|
+
} catch (failure) { result(id, runtimeToolError(failure)); }
|
|
92
93
|
} finally { pending--; inflightIds.delete(id); }
|
|
93
94
|
};
|
|
94
95
|
function consume(chunk) {
|
package/runtimeOutbox.mjs
CHANGED
|
@@ -3,6 +3,8 @@ import { link, lstat, mkdir, open, readFile, readdir, rm } from 'node:fs/promise
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import { runtimePrincipal, writeRuntimeRecord } from './runtime.mjs';
|
|
6
|
+
import { normalizeRuntimeArtifacts } from './runtimeArtifacts.mjs';
|
|
7
|
+
import { runtimeFailure } from './runtimeProtocol.mjs';
|
|
6
8
|
|
|
7
9
|
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
8
10
|
const states = new Set(['completed', 'failed', 'uncertain']);
|
|
@@ -13,7 +15,7 @@ function validate(record, principal) {
|
|
|
13
15
|
typeof record.eventId !== 'string' || !record.eventId || record.eventId.length > 128 || !/^[a-f0-9]{64}$/.test(record.leaseToken) || !states.has(record.status) ||
|
|
14
16
|
typeof record.resultJson !== 'string' || Buffer.byteLength(record.resultJson) > 200000 || !['queued', 'delivered'].includes(record.phase))
|
|
15
17
|
throw new Error('INVALID_OUTBOX_RECORD');
|
|
16
|
-
JSON.parse(record.resultJson);
|
|
18
|
+
normalizeRuntimeArtifacts(JSON.parse(record.resultJson)?.artifacts);
|
|
17
19
|
return record;
|
|
18
20
|
}
|
|
19
21
|
async function readRecord(file, principal) {
|
|
@@ -32,13 +34,13 @@ async function publishOnce(file, record) {
|
|
|
32
34
|
} finally { await rm(temp, { force: true }); }
|
|
33
35
|
}
|
|
34
36
|
async function deliver(client, file, record) {
|
|
35
|
-
if (record.phase === 'delivered') return { runId: record.runId, delivered: true, replayed: true };
|
|
37
|
+
if (record.phase === 'delivered') return { runId: record.runId, delivered: true, replayed: true, serverStatus: record.serverStatus };
|
|
36
38
|
try {
|
|
37
39
|
const receipt = await client.finishRuntimeRun({ runId: record.runId, leaseToken: record.leaseToken,
|
|
38
40
|
eventId: record.eventId, status: record.status, resultJson: record.resultJson });
|
|
39
41
|
await writeRuntimeRecord(file, { ...record, phase: 'delivered', deliveredAt: Date.now(), serverStatus: receipt.status });
|
|
40
42
|
return { runId: record.runId, delivered: true, serverStatus: receipt.status };
|
|
41
|
-
} catch { return { runId: record.runId, delivered: false }; }
|
|
43
|
+
} catch (error) { return { runId: record.runId, delivered: false, failure: runtimeFailure(error, { uncertain: true }) }; }
|
|
42
44
|
}
|
|
43
45
|
|
|
44
46
|
/** Persist before sending. This module has no path to start or execute a business operation. */
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export const RUNTIME_PROTOCOL: string;
|
|
2
|
+
export type RuntimeFailure = { protocol: string; code: string; status: number; uncertain: boolean; retryAfterSeconds: number | null; nextAction: string; retryable: boolean; instruction: string };
|
|
3
|
+
export function runtimeFailure(error: unknown, options?: { uncertain?: boolean; retryAfterSeconds?: number }): RuntimeFailure;
|
|
4
|
+
export function runtimeToolError(error: unknown, options?: { uncertain?: boolean; retryAfterSeconds?: number }): { isError: boolean; content: { type: 'text'; text: string }[]; structuredContent: { error: RuntimeFailure } };
|
|
5
|
+
export function runtimeDeliveryState(run: { status: string; resultJson?: string; lateResult?: boolean }): { execution: string; saved: boolean; late: boolean; instruction: string };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Shared wire semantics for HTTP MCP, stdio and SDK consumers. Never expose raw errors. */
|
|
2
|
+
export const RUNTIME_PROTOCOL = 'xiashe.runtime.v1';
|
|
3
|
+
export function runtimeFailure(error, options = {}) {
|
|
4
|
+
const data = error && typeof error === 'object' && error.data && typeof error.data === 'object' ? error.data : error;
|
|
5
|
+
const message = typeof data?.code === 'string' ? data.code : typeof error === 'string' ? error : String(error?.message ?? '');
|
|
6
|
+
let code = message.match(/\b(?:(?:RUNTIME|RUN|ACTION|SKILL|CREATOR_SERVICE|RELEASE|CONNECTION|CONNECTOR|INPUT|OUTPUT|INVALID|IDEMPOTENCY|GATEWAY|SERVICE|HOST|HTTP)_[A-Z0-9_]{1,80}|REQUEST_TIMEOUT|AUTH_REQUIRED)\b/)?.[0] ?? 'RUNTIME_REQUEST_FAILED';
|
|
7
|
+
if (data?.kind === 'RateLimited') code = 'RUNTIME_RATE_LIMITED';
|
|
8
|
+
const limited = /RATE_LIMIT|CONCURRENCY_LIMIT|QUEUE_FULL|HTTP_429/.test(code) || data?.status === 429;
|
|
9
|
+
const quota = /QUOTA|ACTION_LIMIT|CALL_LIMIT|DAILY_LIMIT/.test(code);
|
|
10
|
+
const uncertain = options.uncertain === true || data?.uncertain === true || code === 'RUNTIME_REQUEST_FAILED' || /UNCERTAIN|REQUEST_TIMEOUT/.test(code);
|
|
11
|
+
const platformSetup = /GATEWAY_AUTH_FAILED|MCP_DISABLED|CONNECTOR_DISABLED/.test(code);
|
|
12
|
+
const status = limited ? 429 : platformSetup ? 503 : quota || /ACTION_NOT_ALLOWED|PERMISSION_REQUIRED|ENTITLEMENT_REQUIRED/.test(code) ? 403 : /SESSION_EXPIRED|AUTH_REQUIRED|AUTH_FAILED/.test(code) ? 401
|
|
13
|
+
: /NOT_FOUND/.test(code) ? 404 : /IDEMPOTENCY_CONFLICT|ALREADY_FINISHED|REVIEW_CHANGED|LEASE_INVALID|RUN_CLOSED|RUN_TIMEOUT/.test(code) ? 409
|
|
14
|
+
: /INPUT_LIMIT|OUTPUT_LIMIT/.test(code) ? 413 : code === 'REQUEST_TIMEOUT' ? 504 : /UNAVAILABLE|PROTOCOL_ERROR|REQUEST_FAILED|MCP_DISABLED/.test(code) ? 503
|
|
15
|
+
: /^HTTP_[45]\d{2}$/.test(code) ? Number(code.slice(5)) : 400;
|
|
16
|
+
const delay = options.retryAfterSeconds ?? data?.retryAfterSeconds ?? (typeof data?.retryAfter === 'number' ? data.retryAfter / 1000 : undefined);
|
|
17
|
+
const retryAfterSeconds = limited ? Math.max(1, Math.min(3600, Math.ceil(Number.isFinite(delay) ? delay : 30))) : null;
|
|
18
|
+
const nextAction = uncertain || /LEASE_INVALID|RUN_CLOSED|RUN_TIMEOUT/.test(code) ? 'check_status' : limited ? 'wait' : platformSetup ? 'contact_support' : /REAUTH|ACCOUNT_SELECTION/.test(code) ? 'repair_connection'
|
|
19
|
+
: /CAPABILIT|PACKAGE.*REQUIRED/.test(code) ? 'change_host' : /ACTION_LIMIT|CALL_LIMIT/.test(code) ? 'reduce_scope' : quota || code === 'CREATOR_SERVICE_UNAVAILABLE' ? 'contact_creator' : /SESSION|AUTH/.test(code) ? 'reauthenticate' : 'review_request';
|
|
20
|
+
return { protocol: RUNTIME_PROTOCOL, code, status, uncertain, retryAfterSeconds, nextAction,
|
|
21
|
+
retryable: limited && !uncertain, instruction: uncertain ? 'Check the original run and action IDs. Do not repeat external effects with a new request key.'
|
|
22
|
+
: limited ? 'Wait for retryAfterSeconds. Preserve the original request key and check status before resubmitting.'
|
|
23
|
+
: 'Keep the task, inputs and purchase entitlement. Resolve the indicated problem before continuing.' };
|
|
24
|
+
}
|
|
25
|
+
export function runtimeToolError(error, options) {
|
|
26
|
+
const failure = runtimeFailure(error, options);
|
|
27
|
+
return { isError: true, content: [{ type: 'text', text: JSON.stringify(failure) }], structuredContent: { error: failure } };
|
|
28
|
+
}
|
|
29
|
+
export function runtimeDeliveryState(run) {
|
|
30
|
+
return { execution: run.status, saved: typeof run.resultJson === 'string', late: run.lateResult === true,
|
|
31
|
+
instruction: 'Saved is not confirmation that every client received the result. Retrieve delivery without repeating API calls.' };
|
|
32
|
+
}
|
package/runtimeScript.mjs
CHANGED
|
@@ -240,5 +240,5 @@ export async function runRuntimeScript(client, { releaseId, input = {}, grantIds
|
|
|
240
240
|
// Even a contract with a one-byte output limit can retain an uncertainty receipt.
|
|
241
241
|
if (Buffer.byteLength(resultJson) > JSON.parse(downloaded.release.contractJson).maxOutputBytes) resultJson = '0';
|
|
242
242
|
const receipt = await reportRuntimeResult(client, { runId, leaseToken, status, resultJson }, { outboxRoot });
|
|
243
|
-
return { runId, status, result, receipt };
|
|
243
|
+
return { runId, status: receipt.serverStatus ?? status, resultSaved: receipt.delivered, result, receipt };
|
|
244
244
|
}
|
package/runtimeSetup.mjs
CHANGED
|
@@ -19,7 +19,7 @@ export async function probeRuntimeGateway(endpoint, { fetchImpl = fetch } = {})
|
|
|
19
19
|
await post('ping');
|
|
20
20
|
const listing = await post('tools/list');
|
|
21
21
|
const tools = new Set(Array.isArray(listing.tools) ? listing.tools.map(item => item.name) : []);
|
|
22
|
-
const missingTools = ['prepare', 'start', 'prompt', 'describe_action', 'execute', 'action_status', 'status', 'finish'].map(name => `xiashe.runtime_${name}`).filter(name => !tools.has(name));
|
|
22
|
+
const missingTools = ['prepare', 'start', 'prompt', 'package_ready', 'describe_action', 'execute', 'action_status', 'status', 'finish', 'delivery', 'ack_delivery'].map(name => `xiashe.runtime_${name}`).filter(name => !tools.has(name));
|
|
23
23
|
return { ok: notificationAccepted && missingTools.length === 0, protocolVersion: initialized.protocolVersion, notificationAccepted, missingTools,
|
|
24
24
|
businessCalls: 0, clientExecutionVerified: false,
|
|
25
25
|
nextStep: missingTools.length ? 'Check both Superconnector feature flags on this environment.' : 'Gateway discovery passed. Verify package handling, user confirmation and result recovery in the actual Agent before claiming a fresh ticket.' };
|