@xiashe/sdk 0.1.44 → 0.1.46

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
@@ -52,4 +52,4 @@ Keep `values` out of logs, command arguments, Skill files, runtime inputs and pe
52
52
 
53
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
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.
55
+ Agent delivery continues returning Markdown and portable HTML for hosts without the registered component library. Creator attribution uses cardUrl (the current saved handle URL) for display and sharing; stableCardUrl remains a persistent identity entry for older links and cached clients. Use current metadata or the used receipt rather than a package's older profile snapshot. Metadata refresh never grants execution permissions.
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,6 @@
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
4
  import { createHash, randomUUID } from 'node:crypto';
5
5
  import { existsSync } from 'node:fs';
6
6
  import { mkdir, readFile, writeFile, stat } from 'node:fs/promises';
@@ -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.44';
22
+ export const VERSION = '0.1.46';
23
23
  export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
24
24
 
25
25
  export const DEFAULTS = {
@@ -61,6 +61,7 @@ export class XiasheError extends Error {
61
61
  this.name = 'XiasheError';
62
62
  this.code = options.code || message;
63
63
  this.status = options.status;
64
+ this.retryAfterSeconds = options.retryAfterSeconds;
64
65
  this.details = options.details;
65
66
  }
66
67
  }
@@ -335,12 +336,13 @@ export async function postJson(url, body, options = {}) {
335
336
  HTTP_BAD_JSON: 'The server returned an invalid JSON response. Check service health and verify the operation status before retrying.',
336
337
  REQUEST_TIMEOUT: 'The request timed out. Its outcome may be unknown; check status before retrying an operation.',
337
338
  };
338
- throw new XiasheError(messages[error.message] ? `${error.message}: ${messages[error.message]}` : error.message, { code: error.message });
339
+ 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
340
  }
340
341
  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
- });
342
+ if (!response.ok) {
343
+ const failure = responseError(response, payload?.error);
344
+ throw new XiasheError(failure.message, failure);
345
+ }
344
346
  return payload;
345
347
  }
346
348
 
@@ -485,17 +487,18 @@ export class XiasheClient {
485
487
  const pairs = new Map([
486
488
  ['https://actions.xiashe.chat', 'https://api.xiashe.chat'],
487
489
  ['https://actions.projectphenix.site', 'https://api.projectphenix.site'],
488
- ['https://agentpie.app', DEFAULTS.global.convexUrl]
490
+ ['https://agentpie.app', DEFAULTS.global.convexUrl],
491
+ ['https://staging.agentpie.app', 'https://keen-echidna-553.convex.cloud']
489
492
  ]);
490
493
  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)) {
494
+ 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
495
  throw new XiasheError('Skill numbers require matching official XiaShe backend and actions URLs.', { code: 'NUMBER_ENVIRONMENT_INVALID' });
493
496
  }
494
497
  }
495
498
 
496
499
  async resolveSkillNumber(number) {
497
500
  this.assertNumbersEnvironment();
498
- return this.query(api.skillNumbers.resolve, { number: String(number) });
501
+ return this.mutation(api.skillNumbers.resolve, { number: String(number) });
499
502
  }
500
503
  async skillNumberAnalytics(number) {
501
504
  this.assertNumbersEnvironment();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiashe/sdk",
3
- "version": "0.1.44",
3
+ "version": "0.1.46",
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 会话;仍失败时联系支持,不要发送身份凭据。' },