@xiashe/sdk 0.1.45 → 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/http.mjs CHANGED
@@ -1,4 +1,12 @@
1
1
  const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
2
+ export function responseError(response, code) {
3
+ const safeCode = typeof code === 'string' && /^[A-Z][A-Z0-9_]{2,100}$/.test(code) ? code : `HTTP_${response.status}`;
4
+ const error = Object.assign(Error(safeCode), { code: safeCode, status: response.status });
5
+ const retry = response.headers.get('retry-after');
6
+ const seconds = retry && /^\d+$/.test(retry) ? Number(retry) : retry ? Math.ceil((Date.parse(retry) - Date.now()) / 1000) : NaN;
7
+ if (Number.isFinite(seconds) && seconds >= 0) error.retryAfterSeconds = Math.min(86400, Math.max(1, seconds));
8
+ return error;
9
+ }
2
10
  export function requestUrl(value) {
3
11
  let url;
4
12
  try { url = new URL(value); } catch { throw Error('HTTP_TARGET_INVALID'); }
@@ -6,14 +14,15 @@ export function requestUrl(value) {
6
14
  if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || url.username || url.password || url.hash) throw Error('HTTP_TARGET_INVALID');
7
15
  return url;
8
16
  }
9
- export async function boundedJsonRequest(url, body, { timeoutMs = 20000, headers = {}, maxResponseBytes = MAX_RESPONSE_BYTES, method = 'POST' } = {}) {
17
+ export async function boundedJsonRequest(url, body, { timeoutMs = 20000, headers = {}, maxResponseBytes = MAX_RESPONSE_BYTES, method = 'POST', fetchImpl = fetch } = {}) {
10
18
  requestUrl(url);
11
19
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || !Number.isSafeInteger(maxResponseBytes) || maxResponseBytes <= 0) throw Error('HTTP_LIMIT_INVALID');
12
20
  const controller = new AbortController();
13
21
  let timer;
14
22
  const deadline = new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(Error('REQUEST_TIMEOUT')); }, timeoutMs); });
23
+ let response;
15
24
  const request = async () => {
16
- const response = await fetch(url, { method, redirect: 'manual', signal: controller.signal,
25
+ response = await fetchImpl(url, { method, redirect: 'manual', signal: controller.signal,
17
26
  headers: { 'content-type': 'application/json', ...headers }, ...(method === 'GET' ? {} : { body: JSON.stringify(body ?? {}) }) });
18
27
  if (response.status >= 300 && response.status < 400) { await response.body?.cancel(); throw Error('HTTP_REDIRECT_REFUSED'); }
19
28
  if (Number(response.headers.get('content-length')) > maxResponseBytes) { controller.abort(); throw Error('HTTP_RESPONSE_TOO_LARGE'); }
@@ -33,6 +42,22 @@ export async function boundedJsonRequest(url, body, { timeoutMs = 20000, headers
33
42
  return { response, payload };
34
43
  };
35
44
  try { return await Promise.race([request(), deadline]); }
36
- catch (error) { if (controller.signal.aborted && error.message !== 'HTTP_RESPONSE_TOO_LARGE') throw Error('REQUEST_TIMEOUT'); if (error instanceof TypeError && /fetch failed|terminated|network/i.test(error.message)) throw Error('HTTP_NETWORK_ERROR'); throw error; }
45
+ catch (error) {
46
+ let failure = error;
47
+ if (controller.signal.aborted && error.message !== 'HTTP_RESPONSE_TOO_LARGE') failure = Error('REQUEST_TIMEOUT');
48
+ else if (error instanceof TypeError && /fetch failed|terminated|network/i.test(error.message)) failure = Error('HTTP_NETWORK_ERROR');
49
+ // Retain transport status even when a gateway body is malformed or interrupted.
50
+ if (response) Object.assign(failure, responseError(response, failure.message));
51
+ failure.code ??= failure.message;
52
+ throw failure;
53
+ }
37
54
  finally { clearTimeout(timer); }
38
55
  }
56
+
57
+ /** Fixed protocol objects only. Never echo a remote error body or replay a POST. */
58
+ export async function protocolJsonRequest(url, body, options = {}) {
59
+ const { response, payload } = await boundedJsonRequest(url, body, options);
60
+ if (!response.ok) throw responseError(response, payload?.error);
61
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw responseError(response, 'HTTP_RESPONSE_INVALID');
62
+ return payload;
63
+ }
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
- import { boundedJsonRequest } from './http.mjs';
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.45';
27
+ export const VERSION = '0.1.47';
23
28
  export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
24
29
 
25
30
  export const DEFAULTS = {
@@ -61,7 +66,10 @@ export class XiasheError extends Error {
61
66
  this.name = 'XiasheError';
62
67
  this.code = options.code || message;
63
68
  this.status = options.status;
69
+ this.retryAfterSeconds = options.retryAfterSeconds;
64
70
  this.details = options.details;
71
+ this.uncertain = options.uncertain;
72
+ this.nextAction = options.nextAction;
65
73
  }
66
74
  }
67
75
 
@@ -276,6 +284,8 @@ function normalizeConvexError(error) {
276
284
  if (/ArgumentValidationError/.test(message)) {
277
285
  return new XiasheError('The server rejected the request arguments.', { code: 'CONVEX_INVALID_ARGUMENTS' });
278
286
  }
287
+ const failure = runtimeFailure(error);
288
+ if (failure.code !== 'RUNTIME_REQUEST_FAILED') return new XiasheError(failure.code, { ...failure, details: failure });
279
289
  if (/fetch failed|failed to fetch|network request failed|econnrefused|enotfound|eai_again/i.test(message)) {
280
290
  return new XiasheError('Unable to reach Convex deployment.', {
281
291
  code: 'CONVEX_NETWORK_UNAVAILABLE',
@@ -335,12 +345,13 @@ export async function postJson(url, body, options = {}) {
335
345
  HTTP_BAD_JSON: 'The server returned an invalid JSON response. Check service health and verify the operation status before retrying.',
336
346
  REQUEST_TIMEOUT: 'The request timed out. Its outcome may be unknown; check status before retrying an operation.',
337
347
  };
338
- throw new XiasheError(messages[error.message] ? `${error.message}: ${messages[error.message]}` : error.message, { code: error.message });
348
+ throw new XiasheError(messages[error.message] ? `${error.message}: ${messages[error.message]}` : error.message, { code: error.code || error.message, status: error.status, retryAfterSeconds: error.retryAfterSeconds });
339
349
  }
340
350
  const { response, payload } = result;
341
- if (!response.ok) throw new XiasheError(payload?.error || payload?.message || `HTTP ${response.status}`, {
342
- code: payload?.error || `HTTP_${response.status}`, status: response.status
343
- });
351
+ if (!response.ok) {
352
+ const failure = responseError(response, payload?.error);
353
+ throw new XiasheError(failure.message, failure);
354
+ }
344
355
  return payload;
345
356
  }
346
357
 
@@ -368,6 +379,12 @@ export async function mcpCall(mcpUrl, runtimeToken, method, params = {}, timeout
368
379
  }
369
380
 
370
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;
371
388
  const text = result?.content?.find?.((item) => item?.type === 'text')?.text;
372
389
  if (typeof text !== 'string') {
373
390
  return result;
@@ -485,17 +502,18 @@ export class XiasheClient {
485
502
  const pairs = new Map([
486
503
  ['https://actions.xiashe.chat', 'https://api.xiashe.chat'],
487
504
  ['https://actions.projectphenix.site', 'https://api.projectphenix.site'],
488
- ['https://agentpie.app', DEFAULTS.global.convexUrl]
505
+ ['https://agentpie.app', DEFAULTS.global.convexUrl],
506
+ ['https://staging.agentpie.app', 'https://keen-echidna-553.convex.cloud']
489
507
  ]);
490
508
  const actions = normalizeBaseUrl(this.profile.actionsUrl);
491
- if (this.profile.market !== (actions === 'https://agentpie.app' ? 'intl' : 'cn') || !pairs.has(actions) || pairs.get(actions) !== normalizeBaseUrl(this.profile.convexUrl)) {
509
+ if (this.profile.market !== (['https://agentpie.app', 'https://staging.agentpie.app'].includes(actions) ? 'intl' : 'cn') || !pairs.has(actions) || pairs.get(actions) !== normalizeBaseUrl(this.profile.convexUrl)) {
492
510
  throw new XiasheError('Skill numbers require matching official XiaShe backend and actions URLs.', { code: 'NUMBER_ENVIRONMENT_INVALID' });
493
511
  }
494
512
  }
495
513
 
496
514
  async resolveSkillNumber(number) {
497
515
  this.assertNumbersEnvironment();
498
- return this.query(api.skillNumbers.resolve, { number: String(number) });
516
+ return this.mutation(api.skillNumbers.resolve, { number: String(number) });
499
517
  }
500
518
  async skillNumberAnalytics(number) {
501
519
  this.assertNumbersEnvironment();
@@ -764,6 +782,12 @@ export class XiasheClient {
764
782
  async runtimeHostDelivery(runId) {
765
783
  return this.mutation(api.runtimeHosts.delivery, this.runtimeHostAuth({ runId }));
766
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
+ }
767
791
 
768
792
  async runtimeHostRunStatus(runId) {
769
793
  return this.mutation(api.runtimeHosts.status, this.runtimeHostAuth({ runId }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiashe/sdk",
3
- "version": "0.1.45",
3
+ "version": "0.1.47",
4
4
  "type": "module",
5
5
  "main": "index.mjs",
6
6
  "exports": {
package/paymentErrors.mjs CHANGED
@@ -10,7 +10,7 @@ const cases = [
10
10
  { match: ['SKILL_PAYMENT_MULTIPLE_UNRESOLVED_ORDERS'], code: 'PAYMENT_MULTIPLE_ATTEMPTS_PENDING', title: '发现多笔未决购买', message: '系统已暂停新的付款,避免重复收费。', stage: 'verification', nextAction: 'contact_support', nextStep: support },
11
11
  { match: ['SKILL_PAYMENT_HISTORY_REVIEW_REQUIRED'], code: 'PAYMENT_HISTORY_SYNCING', title: '历史购买记录正在核对', message: '历史记录核对完成前,暂不开放新的付款。', stage: 'verification', nextAction: 'wait_and_resume', nextStep: '稍后在原会话恢复获取;持续未恢复时联系支持,不要换会话重复购买。' },
12
12
  { match: ['PRIVATE_STATE_BUSY', 'ACCESS_STATE_BUSY'], code: 'PAYMENT_OPERATION_IN_PROGRESS', title: '原操作仍在处理', message: '另一个进程正在处理同一授权或交易,当前请求已停止。', stage: 'local_state', nextAction: 'wait_existing_operation', nextStep: '等待原窗口的操作结束。若曾异常退出,请联系支持检查恢复状态,不要删除交易记录后重付。' },
13
- { match: ['ALIPAY_PAYMENT_STATE_INVALID', 'PRIVATE_STATE_UNSAFE_FILE', 'PRIVATE_STATE_UNSAFE_DIRECTORY'], code: 'PAYMENT_LOCAL_STATE_UNREADABLE', title: '交易恢复记录无法读取', message: '无法安全读取本地交易状态,已阻止再次付款。', stage: 'local_state', nextAction: 'contact_support', nextStep: support },
13
+ { match: ['ALIPAY_PAYMENT_STATE_INVALID', 'PRIVATE_STATE_UNSAFE_FILE', 'PRIVATE_STATE_UNSAFE_DIRECTORY', 'ACCESS_STATE_INVALID', 'ACCESS_STATE_UNSAFE_FILE', 'ACCESS_STATE_UNSAFE_PATH', 'ACCESS_STATE_ENVIRONMENT_MISMATCH'], code: 'PAYMENT_LOCAL_STATE_UNREADABLE', title: '交易恢复记录无法读取', message: '无法安全读取本地交易状态,已阻止再次付款。', stage: 'local_state', nextAction: 'contact_support', nextStep: support },
14
14
  { match: ['ALIPAY_BOT_NOT_INSTALLED', 'ALIPAY_SESSION_ID_REQUIRED', 'HOST_BUSINESS_SESSION_UNAVAILABLE', 'wallet_runtime_not_supported'], code: 'PAYMENT_AGENT_SETUP_REQUIRED', title: '当前 Agent 暂不能完成付款', message: '当前 Agent 缺少受支持的支付宝付款能力或原任务会话。', stage: 'payment', nextAction: 'restore_original_agent', nextStep: '在原 Agent 中安装或更新官方支付宝支付能力后恢复原交易;不要手工填写会话标识。' },
15
15
  { match: ['wallet_not_ready', 'WALLET_NOT_READY'], code: 'PAYMENT_AUTHORIZATION_REQUIRED', title: '支付宝授权尚未完成', message: '需要按官方付款流程完成授权确认。', stage: 'payment', nextAction: 'complete_official_authorization', nextStep: '回原会话按支付宝官方提示处理授权,然后查询原交易,不要新建付款。' },
16
16
  { match: ['buyer_identity_rejected', 'BUYER_IDENTITY_REJECTED'], code: 'PAYMENT_IDENTITY_CHECK_REQUIRED', title: '买家身份未通过核验', message: '当前支付宝身份与原交易的核验结果不一致。', stage: 'payment', nextAction: 'check_original_identity', nextStep: '确认使用原付款账号和原 Agent 会话;仍失败时联系支持,不要发送身份凭据。' },
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('ACTION_LIMIT');
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');
@@ -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,2 @@
1
+ export type RuntimeArtifact = { name: string; sizeBytes: number; sha256: string; location: 'agent' };
2
+ export function normalizeRuntimeArtifacts(value: unknown): RuntimeArtifact[];
@@ -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, { isError: true, content: [{ type: 'text', text: safeError(failure) }] }); }
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.' };
@@ -0,0 +1,2 @@
1
+ export const SERVICE_RELEASE: string;
2
+ export const SERVICE_HEALTH_PROTOCOL: string;
@@ -0,0 +1,3 @@
1
+ /** Public backend release identity, shared with deployment verification. */
2
+ export const SERVICE_RELEASE = '2026-11-01-byoa-0.1.47';
3
+ export const SERVICE_HEALTH_PROTOCOL = 'xiashe.service-health.v1';