@xiashe/sdk 0.1.40 → 0.1.42
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 +9 -1
- package/agentTaskRunner.mjs +154 -0
- package/alipayWallet.mjs +87 -165
- package/index.mjs +34 -11
- package/package.json +1 -1
- package/paymentErrors.mjs +46 -0
package/README.md
CHANGED
|
@@ -12,13 +12,21 @@ The SDK wraps:
|
|
|
12
12
|
|
|
13
13
|
It stores local CLI state in `~/.xiashe/config.json` by default.
|
|
14
14
|
|
|
15
|
+
## Local task execution (0.1.41)
|
|
16
|
+
|
|
17
|
+
`agentCompleteTask(taskId, { content, error, idempotencyKey }, state)` sends the canonical `status/content/error` envelope; the server also accepts the previously published `state/output` envelope. Successful completion requires nonempty text. REST bases returned by claims are joined without duplicating `/agent-gateway`.
|
|
18
|
+
|
|
19
|
+
`createCodexTaskExecutor({ workdir, directory, command, model, timeoutMs })` invokes the installed Codex CLI with the workspace-write sandbox and returns its final message. `runAgentTaskCycle(client, { directory, execute, signal, onEvent })` receives one text task, renews its lease, executes it, and durably reports the result. Interrupted work is not replayed, and uncertain result delivery retries only the saved answer. Attachments require a dedicated receiving adapter and are rejected by the automatic text executor. Host credentials and compatible model access must be verified separately.
|
|
20
|
+
|
|
21
|
+
CN staging/production acceptance verified real Codex CLI 0.160.1 task completion into chat and missing-host failure. CN production also passed one explicitly authorized Firecrawl read-only credit query and temporary-account cleanup. These checks do not certify all providers, all published Skill versions, Global deployments, or other Agent products.
|
|
22
|
+
|
|
15
23
|
## Superconnector runtime preview
|
|
16
24
|
|
|
17
25
|
Version `0.1.35-superconnector.1` adds user-owned non-OAuth credential connection APIs alongside existing OAuth connections, explicit action grants, immutable runtime releases, verified installation, foreground Agent/script execution, remote hosts and result-only recovery. SaaS credentials remain in the platform gateway.
|
|
18
26
|
|
|
19
27
|
Runtime exports include `installRuntimePackage`, `runRuntimeScript`, `createRuntimeAgentSession`, `createRuntimeAgentHost`, `serveRuntimeScriptHost`, `serveRuntimeMcp`, `retryRuntimeResults` and `retryRuntimeHostResults`. Script execution requires Docker and a pre-pulled official Node image pinned by SHA-256. Runtime container helper files are included in the package.
|
|
20
28
|
|
|
21
|
-
|
|
29
|
+
New providers, releases and hosts still require their own real acceptance; protocol discovery alone does not certify them. See the repository's `docs/platform/superconnector/development.md` for setup and acceptance procedures.
|
|
22
30
|
|
|
23
31
|
`createRuntimeRelease({ ..., signature })` optionally imports a public BYOA v1 P-256 package proof. The backend verifies every delivered file and preserves existing creator ownership and runtime review. Private signing material is rejected before transmission. Sign the exact filtered package; source-package proofs cannot survive changed files.
|
|
24
32
|
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readFile, readdir, open, rm, stat } from 'node:fs/promises';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import { privateDirectory, checkPrivateFile, atomicPrivateJson, withPrivateLock } from './privateState.mjs';
|
|
7
|
+
import { rememberSecrets, safeOutput } from './outputSafety.mjs';
|
|
8
|
+
|
|
9
|
+
const unwrap = value => value?.result ?? value;
|
|
10
|
+
const terminal = state => ['completed', 'failed', 'cancelled'].includes(state);
|
|
11
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
12
|
+
|
|
13
|
+
// Each task has a permanent receipt. A network retry only resends a saved result.
|
|
14
|
+
// A live local worker owns its task by PID; interrupted work is failed, never replayed.
|
|
15
|
+
export async function runAgentTaskCycle(client, { directory, execute, capabilities = [{ key: 'chat.receive', status: 'enabled' }, { key: 'chat.respond', status: 'enabled' }, { key: 'tasks.ack', status: 'enabled' }, { key: 'files.receive', status: 'disabled', details: { reason: 'ATTACHMENTS_UNSUPPORTED' } }], heartbeatMs = 20_000, signal, onEvent = () => {} } = {}) {
|
|
16
|
+
if (!directory || typeof execute !== 'function') throw Error('AGENT_EXECUTOR_REQUIRED');
|
|
17
|
+
rememberSecrets(client.profile);
|
|
18
|
+
await privateDirectory(directory);
|
|
19
|
+
const namespace = hash(`${new URL(client.profile.actionsUrl).origin}\n${client.profile.agent?.agentConnectionId || client.profile.agent?.runtimeToken || ''}`);
|
|
20
|
+
const root = path.join(directory, namespace);
|
|
21
|
+
await privateDirectory(root);
|
|
22
|
+
const report = async (file, receipt) => {
|
|
23
|
+
const response = unwrap(await client.agentCompleteTask(receipt.taskId, receipt.output, receipt.status));
|
|
24
|
+
if (!terminal(response.state)) throw Error('AGENT_RESULT_NOT_ACCEPTED');
|
|
25
|
+
receipt.phase = 'reported'; receipt.serverState = response.state;
|
|
26
|
+
await atomicPrivateJson(file, receipt);
|
|
27
|
+
onEvent({ type: 'task_result', taskId: receipt.taskId, state: response.state });
|
|
28
|
+
};
|
|
29
|
+
// Recover the outbox independently of pendingTaskCount: running tasks are not polled.
|
|
30
|
+
for (const name of await readdir(root)) {
|
|
31
|
+
if (!name.endsWith('.json')) continue;
|
|
32
|
+
const file = path.join(root, name);
|
|
33
|
+
await checkPrivateFile(file);
|
|
34
|
+
const receipt = JSON.parse(await readFile(file, 'utf8'));
|
|
35
|
+
if (receipt.phase === 'reported') continue;
|
|
36
|
+
if (receipt.phase === 'executing') {
|
|
37
|
+
if (receipt.hostname !== os.hostname()) throw Error('AGENT_RECEIPT_HOST_MISMATCH');
|
|
38
|
+
let alive = true;
|
|
39
|
+
try { process.kill(receipt.pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; else throw error; }
|
|
40
|
+
if (alive) continue;
|
|
41
|
+
if (receipt.childPid) {
|
|
42
|
+
try { process.kill(receipt.childPid, 0); throw Error('AGENT_EXECUTION_ORPHANED: inspect the saved receipt and stop the prior executor before restarting'); }
|
|
43
|
+
catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
44
|
+
}
|
|
45
|
+
receipt.phase = 'pending'; receipt.status = 'failed';
|
|
46
|
+
receipt.output = { error: 'LOCAL_EXECUTION_INTERRUPTED: inspect local work before submitting a new task.' };
|
|
47
|
+
await withPrivateLock(file, () => atomicPrivateJson(file, receipt));
|
|
48
|
+
}
|
|
49
|
+
if (receipt.phase === 'pending') await withPrivateLock(file, () => report(file, receipt));
|
|
50
|
+
}
|
|
51
|
+
if (signal?.aborted) return;
|
|
52
|
+
await client.agentHeartbeat({ capabilities });
|
|
53
|
+
const listed = unwrap(await client.agentListTasks({ limit: 1 }));
|
|
54
|
+
for (const task of listed.tasks || []) {
|
|
55
|
+
const taskId = task.taskId || task.id;
|
|
56
|
+
if (!taskId) continue;
|
|
57
|
+
const file = path.join(root, `${hash(taskId)}.json`);
|
|
58
|
+
// Exclusive creation claims before ack or spawning, including concurrent loops.
|
|
59
|
+
let handle;
|
|
60
|
+
try { handle = await open(file, 'wx', 0o600); }
|
|
61
|
+
catch (error) { if (error.code === 'EEXIST') continue; throw error; }
|
|
62
|
+
const receipt = { taskId, phase: 'executing', pid: process.pid, hostname: os.hostname(), startedAt: Date.now() };
|
|
63
|
+
try { await handle.writeFile(JSON.stringify(receipt)); await handle.sync(); } finally { await handle.close(); }
|
|
64
|
+
let timer, renewing = false;
|
|
65
|
+
const controller = new AbortController();
|
|
66
|
+
const abort = () => controller.abort(Error('AGENT_EXECUTOR_STOPPED'));
|
|
67
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
68
|
+
if (signal?.aborted) abort();
|
|
69
|
+
try {
|
|
70
|
+
const ack = unwrap(await client.agentAckTask(taskId, 'running'));
|
|
71
|
+
if (terminal(ack.state)) {
|
|
72
|
+
receipt.phase = 'reported'; receipt.serverState = ack.state;
|
|
73
|
+
await withPrivateLock(file, () => atomicPrivateJson(file, receipt));
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (ack.state !== 'running') throw Error('AGENT_TASK_ACK_REJECTED');
|
|
77
|
+
onEvent({ type: 'task_started', taskId });
|
|
78
|
+
timer = setInterval(async () => {
|
|
79
|
+
if (renewing) return;
|
|
80
|
+
renewing = true;
|
|
81
|
+
try {
|
|
82
|
+
await client.agentHeartbeat({ capabilities });
|
|
83
|
+
const current = unwrap(await client.agentAckTask(taskId, 'running'));
|
|
84
|
+
if (terminal(current.state)) controller.abort(Error(`AGENT_TASK_${current.state.toUpperCase()}`));
|
|
85
|
+
} catch { controller.abort(Error('AGENT_TASK_LEASE_LOST')); }
|
|
86
|
+
finally { renewing = false; }
|
|
87
|
+
}, heartbeatMs);
|
|
88
|
+
// Attachments require an explicit receiving adapter; never silently omit them.
|
|
89
|
+
if (task.attachments?.length) throw Error('AGENT_EXECUTOR_ATTACHMENTS_UNSUPPORTED');
|
|
90
|
+
const content = safeOutput(String(await execute(task, { signal: controller.signal, onSpawn: async childPid => {
|
|
91
|
+
receipt.childPid = childPid;
|
|
92
|
+
await withPrivateLock(file, () => atomicPrivateJson(file, receipt));
|
|
93
|
+
} }) || '').trim());
|
|
94
|
+
if (controller.signal.aborted) throw controller.signal.reason || Error('AGENT_EXECUTOR_ABORTED');
|
|
95
|
+
if (!content) throw Error('AGENT_EXECUTOR_EMPTY_RESULT');
|
|
96
|
+
if (content.length > 40_000) throw Error('AGENT_EXECUTOR_RESULT_TOO_LARGE: result exceeds 40000 characters');
|
|
97
|
+
receipt.status = 'completed'; receipt.output = { content };
|
|
98
|
+
} catch (error) {
|
|
99
|
+
receipt.status = 'failed'; receipt.output = { error: safeOutput(String(error.message || error)).slice(0, 1000) };
|
|
100
|
+
} finally { clearInterval(timer); signal?.removeEventListener('abort', abort); }
|
|
101
|
+
receipt.phase = 'pending'; receipt.finishedAt = Date.now();
|
|
102
|
+
await withPrivateLock(file, () => atomicPrivateJson(file, receipt));
|
|
103
|
+
await withPrivateLock(file, () => report(file, receipt));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function createCodexTaskExecutor({ workdir = process.cwd(), directory, timeoutMs = 15 * 60_000, command = 'codex', model } = {}) {
|
|
108
|
+
if (!directory || !Number.isFinite(timeoutMs) || timeoutMs <= 0) throw Error('AGENT_EXECUTOR_CONFIG_INVALID');
|
|
109
|
+
return async (task, { signal, onSpawn } = {}) => {
|
|
110
|
+
if (signal?.aborted) throw signal.reason || Error('AGENT_EXECUTOR_ABORTED');
|
|
111
|
+
const cwd = path.resolve(workdir);
|
|
112
|
+
if (!(await stat(cwd)).isDirectory()) throw Error('AGENT_EXECUTOR_WORKDIR_INVALID');
|
|
113
|
+
await privateDirectory(directory);
|
|
114
|
+
const output = path.join(directory, `codex-${randomUUID()}.txt`);
|
|
115
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(XIASHE_|AGENTPIE_|CONVEX_|SUPERCONNECTOR_)/.test(key)));
|
|
116
|
+
const args = ['exec', '--sandbox', 'workspace-write', '-c', 'approval_policy="never"', '--skip-git-repo-check', '--color', 'never', '--output-last-message', output, '-'];
|
|
117
|
+
if (model) args.splice(1, 0, '--model', String(model));
|
|
118
|
+
const prompt = `Complete the user's task in the configured local workspace. Return the actual outcome in the user's language. Do not claim success without executing and checking the work.\n\n${task.prompt || task.content || ''}`;
|
|
119
|
+
try {
|
|
120
|
+
await new Promise((resolve, reject) => {
|
|
121
|
+
const child = spawn(command, args, { cwd, env, stdio: ['pipe', 'ignore', 'pipe'], detached: process.platform !== 'win32' });
|
|
122
|
+
let finished = false, progress = '', timedOut = false, killTimer, spawnError, stopping = false;
|
|
123
|
+
const stop = () => {
|
|
124
|
+
if (stopping) return; stopping = true;
|
|
125
|
+
try { if (process.platform !== 'win32') process.kill(-child.pid, 'SIGTERM'); else child.kill(); } catch { /* Already exited. */ }
|
|
126
|
+
killTimer = setTimeout(() => {
|
|
127
|
+
try { if (process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL'); else child.kill('SIGKILL'); } catch { /* Already exited. */ }
|
|
128
|
+
}, 2000);
|
|
129
|
+
};
|
|
130
|
+
const timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs);
|
|
131
|
+
const abort = () => stop();
|
|
132
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
133
|
+
if (signal?.aborted) stop();
|
|
134
|
+
// Progress can include user data; it is never echoed or submitted as an answer.
|
|
135
|
+
child.stderr.on('data', chunk => { progress = (progress + chunk.toString()).slice(-4000); });
|
|
136
|
+
child.stdin.on('error', () => {});
|
|
137
|
+
child.once('spawn', async () => {
|
|
138
|
+
try { await onSpawn?.(child.pid); if (signal?.aborted) stop(); else child.stdin.end(prompt); }
|
|
139
|
+
catch (error) { spawnError = error; stop(); child.stdin.destroy(); }
|
|
140
|
+
});
|
|
141
|
+
const done = error => {
|
|
142
|
+
if (finished) return; finished = true;
|
|
143
|
+
clearTimeout(timer); clearTimeout(killTimer); signal?.removeEventListener('abort', abort);
|
|
144
|
+
error ? reject(error) : resolve();
|
|
145
|
+
};
|
|
146
|
+
child.on('error', error => done(Error(`AGENT_EXECUTOR_START_FAILED: ${error.code || 'unknown'}`)));
|
|
147
|
+
child.on('close', (code, killedSignal) => done(spawnError || (signal?.aborted ? signal.reason || Error('AGENT_EXECUTOR_ABORTED') : timedOut ? Error('AGENT_EXECUTOR_TIMEOUT') : code === 0 ? null : Object.assign(Error(`AGENT_EXECUTOR_FAILED: exit=${code} signal=${killedSignal || 'none'}`), { diagnostics: safeOutput(progress).slice(-800) }))));
|
|
148
|
+
});
|
|
149
|
+
const info = await checkPrivateFile(output);
|
|
150
|
+
if (!info || info.size > 160_000) throw Error('AGENT_EXECUTOR_RESULT_TOO_LARGE_OR_MISSING');
|
|
151
|
+
return await readFile(output, 'utf8');
|
|
152
|
+
} finally { await rm(output, { force: true }); }
|
|
153
|
+
};
|
|
154
|
+
}
|
package/alipayWallet.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { paymentCustomerError, formatPaymentCustomerError } from './paymentErrors.mjs';
|
|
2
|
+
import { privateDirectory, checkPrivateFile, withPrivateLock, atomicPrivateJson } from './privateState.mjs';
|
|
1
3
|
import { createHash } from 'node:crypto';
|
|
2
4
|
import { execFile } from 'node:child_process';
|
|
3
|
-
import { chmod,
|
|
5
|
+
import { chmod, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
4
6
|
import os from 'node:os';
|
|
5
7
|
import path from 'node:path';
|
|
6
8
|
|
|
@@ -8,7 +10,6 @@ const DEFAULT_TIMEOUT_MS = 8 * 60 * 1000;
|
|
|
8
10
|
const RESOURCE_FETCH_TIMEOUT_MS = 20 * 1000;
|
|
9
11
|
const MAX_OUTPUT_BYTES = 32 * 1024;
|
|
10
12
|
const SENSITIVE_OUTPUT = /payment[-_ ]?proof|payment[-_ ]?needed|seller_signature|runtimeToken|authorization\s*:/i;
|
|
11
|
-
const SENSITIVE_USER_OUTPUT = /payment[-_ ]?proof|payment[-_ ]?needed|seller_signature|runtimeToken|authorization\s*:|trade[_ -]?no|交易(?:流水)?号|订单号|查询单号|out[_ -]?shake|client[_ -]?session|payguard|validateclientparent|agentfamily/i;
|
|
12
13
|
const DEFAULT_STATE_DIR = path.join(os.homedir(), '.xiashe', 'alipay-402');
|
|
13
14
|
const OFFICIAL_MEDIA_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp']);
|
|
14
15
|
const MAX_OFFICIAL_MEDIA_BYTES = 8 * 1024 * 1024;
|
|
@@ -55,75 +56,75 @@ const SAFE_OFFICIAL_ERROR_MESSAGE = /^(?!.*(?:https?:\/\/|payment[-_ ]?needed|pa
|
|
|
55
56
|
const OFFICIAL_ERROR_DIAGNOSES = {
|
|
56
57
|
PAYMENT_NEEDED_REJECTED: {
|
|
57
58
|
stage: 'alipay_bill_validation',
|
|
58
|
-
nextStep: '
|
|
59
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
59
60
|
},
|
|
60
61
|
CLIENT_SESSION_IS_EMPTY: {
|
|
61
62
|
stage: 'merchant_payment_proof_verification',
|
|
62
|
-
nextStep: '
|
|
63
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
63
64
|
},
|
|
64
65
|
PAYMENT_PROOF_AGENT_MISMATCH: {
|
|
65
66
|
stage: 'merchant_payment_proof_verification',
|
|
66
|
-
nextStep: '
|
|
67
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
67
68
|
},
|
|
68
69
|
PAYMENT_PROOF_BUYER_MISMATCH: {
|
|
69
70
|
stage: 'merchant_payment_proof_verification',
|
|
70
|
-
nextStep: '
|
|
71
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
71
72
|
},
|
|
72
73
|
PAYMENT_PROOF_ID_MISMATCH: {
|
|
73
74
|
stage: 'merchant_payment_proof_verification',
|
|
74
|
-
nextStep: '
|
|
75
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
75
76
|
},
|
|
76
77
|
PAYMENT_PROOF_EMPTY: {
|
|
77
78
|
stage: 'merchant_payment_proof_verification',
|
|
78
|
-
nextStep: '
|
|
79
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
79
80
|
},
|
|
80
81
|
PAYMENT_PROOF_INVALID: {
|
|
81
82
|
stage: 'merchant_payment_proof_verification',
|
|
82
|
-
nextStep: '
|
|
83
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
83
84
|
},
|
|
84
85
|
PAYMENT_PROOF_NOT_FOUND: {
|
|
85
86
|
stage: 'merchant_payment_proof_verification',
|
|
86
|
-
nextStep: '
|
|
87
|
+
nextStep: '支付凭证不存在或已过期;保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
87
88
|
},
|
|
88
89
|
PAYMENT_PROOF_STATUS_INVALID: {
|
|
89
90
|
stage: 'merchant_payment_proof_verification',
|
|
90
|
-
nextStep: '
|
|
91
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
91
92
|
},
|
|
92
93
|
PAYMENT_PROOF_TRADE_NO_MISMATCH: {
|
|
93
94
|
stage: 'merchant_payment_proof_verification',
|
|
94
|
-
nextStep: '
|
|
95
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
95
96
|
},
|
|
96
97
|
TRADE_NOT_FOUND: {
|
|
97
98
|
stage: 'merchant_payment_proof_verification',
|
|
98
|
-
nextStep: '
|
|
99
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
99
100
|
},
|
|
100
101
|
TRADE_NO_EMPTY: {
|
|
101
102
|
stage: 'merchant_payment_proof_verification',
|
|
102
|
-
nextStep: '
|
|
103
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
103
104
|
},
|
|
104
105
|
TRADE_NO_INVALID: {
|
|
105
106
|
stage: 'merchant_payment_proof_verification',
|
|
106
|
-
nextStep: '
|
|
107
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
107
108
|
},
|
|
108
109
|
TRADE_STATUS_CLOSED: {
|
|
109
110
|
stage: 'merchant_payment_proof_verification',
|
|
110
|
-
nextStep: '
|
|
111
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
111
112
|
},
|
|
112
113
|
TRADE_STATUS_UNPAID: {
|
|
113
114
|
stage: 'merchant_payment_proof_verification',
|
|
114
|
-
nextStep: '
|
|
115
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
115
116
|
},
|
|
116
117
|
SELLER_IDENTITY_MISMATCH: {
|
|
117
118
|
stage: 'merchant_fulfillment_confirmation',
|
|
118
|
-
nextStep: '
|
|
119
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
119
120
|
},
|
|
120
121
|
SELLER_ID_EMPTY: {
|
|
121
122
|
stage: 'merchant_fulfillment_confirmation',
|
|
122
|
-
nextStep: '
|
|
123
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
123
124
|
},
|
|
124
125
|
TRADE_STATUS_INVALID: {
|
|
125
126
|
stage: 'merchant_fulfillment_confirmation',
|
|
126
|
-
nextStep: '
|
|
127
|
+
nextStep: '保留原订单和查询凭据,先查询同一交易并核对付款结果;未确认终态前不得新建订单或再次付款。'
|
|
127
128
|
}
|
|
128
129
|
};
|
|
129
130
|
|
|
@@ -264,43 +265,42 @@ function statePaths(resourceUrl, options = {}) {
|
|
|
264
265
|
}
|
|
265
266
|
|
|
266
267
|
async function ensurePrivateDirectory(directory) {
|
|
267
|
-
await
|
|
268
|
-
// mkdir does not change permissions of an existing directory.
|
|
269
|
-
await chmod(directory, 0o700);
|
|
268
|
+
await privateDirectory(directory);
|
|
270
269
|
}
|
|
271
270
|
|
|
272
271
|
async function writePrivateFile(filePath, contents) {
|
|
273
|
-
await
|
|
272
|
+
await checkPrivateFile(filePath);
|
|
273
|
+
await writeFile(filePath, contents, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
274
274
|
await chmod(filePath, 0o600);
|
|
275
275
|
}
|
|
276
276
|
|
|
277
277
|
async function readPaymentState(resourceUrl, options = {}) {
|
|
278
278
|
const { statePath } = statePaths(resourceUrl, options);
|
|
279
279
|
try {
|
|
280
|
+
await checkPrivateFile(statePath);
|
|
280
281
|
const parsed = JSON.parse(await readFile(statePath, 'utf8'));
|
|
281
282
|
if (!parsed || parsed.version !== 1 || parsed.resourceDigest !== digest(resourceUrl)) {
|
|
282
|
-
|
|
283
|
+
throw Error('PAYMENT_STATE_IDENTITY_MISMATCH');
|
|
283
284
|
}
|
|
284
285
|
// Earlier bridge releases accidentally kept the host business session in
|
|
285
286
|
// the local retry state. It is required only for the initial official
|
|
286
287
|
// wallet invocation; status queries use their separate query credential.
|
|
287
|
-
//
|
|
288
|
+
// Drop it in memory; the next locked atomic save removes it from disk.
|
|
288
289
|
if (Object.prototype.hasOwnProperty.call(parsed, 'sessionId')) {
|
|
289
290
|
const { sessionId: _legacySessionId, ...withoutSession } = parsed;
|
|
290
|
-
await writePrivateFile(statePath, `${JSON.stringify(withoutSession)}\n`);
|
|
291
291
|
return withoutSession;
|
|
292
292
|
}
|
|
293
293
|
return parsed;
|
|
294
294
|
} catch (error) {
|
|
295
295
|
if (error?.code === 'ENOENT') return null;
|
|
296
|
-
throw new AlipayWalletError('ALIPAY_PAYMENT_STATE_INVALID', '
|
|
296
|
+
throw new AlipayWalletError('ALIPAY_PAYMENT_STATE_INVALID', '本地支付宝付款状态无法读取;请保留原交易并联系支持核对,勿重复付款。');
|
|
297
297
|
}
|
|
298
298
|
}
|
|
299
299
|
|
|
300
300
|
async function writePaymentState(state, options = {}) {
|
|
301
301
|
const { directory, statePath } = statePaths(state.resourceUrl, options);
|
|
302
302
|
await ensurePrivateDirectory(directory);
|
|
303
|
-
await
|
|
303
|
+
await atomicPrivateJson(statePath, state);
|
|
304
304
|
}
|
|
305
305
|
|
|
306
306
|
function defaultRunFile(command, args, options) {
|
|
@@ -410,16 +410,6 @@ function paymentStatusFromOutput(stdout, stderr) {
|
|
|
410
410
|
};
|
|
411
411
|
}
|
|
412
412
|
|
|
413
|
-
function userVisibleWalletOutput(stdout, stderr) {
|
|
414
|
-
const lines = `${stdout}\n${stderr}`
|
|
415
|
-
.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, '')
|
|
416
|
-
.split(/\r?\n/)
|
|
417
|
-
.map((line) => line.trim())
|
|
418
|
-
.filter((line) => line && !line.startsWith('MEDIA:') && !SENSITIVE_USER_OUTPUT.test(line))
|
|
419
|
-
.slice(0, 12);
|
|
420
|
-
return lines.length ? lines.join('\n').slice(0, 1_200) : null;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
413
|
/** Preserve only an image emitted by the official wallet in this invocation. */
|
|
424
414
|
async function officialWalletMedia(stdout, stderr) {
|
|
425
415
|
const mediaLine = `${stdout}\n${stderr}`.split(/\r?\n/).find((line) => line.trim().startsWith('MEDIA:'));
|
|
@@ -502,14 +492,14 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
|
|
|
502
492
|
merchantDiagnostic,
|
|
503
493
|
nextStep: fulfillment
|
|
504
494
|
? 'Skill 权益已交付;运营方应按商家验证诊断处理履约回执,买家无需重复付款。'
|
|
505
|
-
: '
|
|
495
|
+
: '商家已返回支付宝验凭证诊断;不要手工补造凭证,按诊断修复后查询原交易,勿重复付款。'
|
|
506
496
|
};
|
|
507
497
|
}
|
|
508
498
|
if (failureCode === 'payment_needed_rejected') {
|
|
509
499
|
return {
|
|
510
500
|
...base,
|
|
511
501
|
stage: 'alipay_bill_validation',
|
|
512
|
-
nextStep: '核对支付宝平台中该 APPID 的应用公钥、service_id、收款方 2088 seller_id
|
|
502
|
+
nextStep: '核对支付宝平台中该 APPID 的应用公钥、service_id、收款方 2088 seller_id 和线上接入状态;修复后先核对原交易,勿重复付款。',
|
|
513
503
|
...(officialCode ? { officialCode } : {})
|
|
514
504
|
};
|
|
515
505
|
}
|
|
@@ -525,7 +515,7 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
|
|
|
525
515
|
return {
|
|
526
516
|
...base,
|
|
527
517
|
stage: 'buyer_identity_validation',
|
|
528
|
-
nextStep: '
|
|
518
|
+
nextStep: '支付宝钱包的买家身份未通过校验;通过官方流程处理后,核对原交易,勿重复付款。',
|
|
529
519
|
...(officialCode ? { officialCode } : {})
|
|
530
520
|
};
|
|
531
521
|
}
|
|
@@ -533,7 +523,7 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
|
|
|
533
523
|
return {
|
|
534
524
|
...base,
|
|
535
525
|
stage: 'wallet_authorization',
|
|
536
|
-
nextStep: '
|
|
526
|
+
nextStep: '支付宝钱包未完成授权或未启用;按官方流程处理并核对原交易,勿重复付款。',
|
|
537
527
|
...(officialCode ? { officialCode } : {})
|
|
538
528
|
};
|
|
539
529
|
}
|
|
@@ -541,7 +531,7 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
|
|
|
541
531
|
return {
|
|
542
532
|
...base,
|
|
543
533
|
stage: 'wallet_network',
|
|
544
|
-
nextStep: '
|
|
534
|
+
nextStep: '钱包或网络请求没有完成;先检查网络并查询原交易,勿重复付款。',
|
|
545
535
|
...(officialCode ? { officialCode } : {})
|
|
546
536
|
};
|
|
547
537
|
}
|
|
@@ -559,50 +549,11 @@ function paymentFailureDiagnosis(failureCode, stdout, stderr) {
|
|
|
559
549
|
};
|
|
560
550
|
}
|
|
561
551
|
|
|
562
|
-
function paymentFailureUserVisible(diagnosis) {
|
|
563
|
-
const lines = [
|
|
564
|
-
diagnosis.stage === 'merchant_payment_proof_verification'
|
|
565
|
-
? '商家未能验证本次支付宝付款凭证,尚未授予付费 Skill 权益。'
|
|
566
|
-
: diagnosis.code === 'wallet_query_credential_missing'
|
|
567
|
-
? '支付宝钱包未返回可继续查询的交易凭据,当前付款状态无法确认。'
|
|
568
|
-
: '支付宝付款未创建可确认交易。',
|
|
569
|
-
`诊断代码:${diagnosis.code}`,
|
|
570
|
-
`失败阶段:${diagnosis.stage}`,
|
|
571
|
-
...(diagnosis.officialCode ? [`官方返回代码:${diagnosis.officialCode}`] : []),
|
|
572
|
-
...(diagnosis.officialSubCode ? [`官方子码:${diagnosis.officialSubCode}`] : []),
|
|
573
|
-
...(diagnosis.officialMessage ? [`官方消息:${diagnosis.officialMessage}`] : []),
|
|
574
|
-
...(diagnosis.officialRequestId ? [`官方请求标识:${diagnosis.officialRequestId}`] : []),
|
|
575
|
-
...(diagnosis.officialTraceId ? [`官方追踪标识:${diagnosis.officialTraceId}`] : []),
|
|
576
|
-
...(diagnosis.merchantDiagnostic ? [`商家验证诊断:${diagnosis.merchantDiagnostic}`] : []),
|
|
577
|
-
`下一步:${diagnosis.nextStep}`
|
|
578
|
-
];
|
|
579
|
-
return lines.join('\n');
|
|
580
|
-
}
|
|
581
|
-
|
|
582
552
|
function paymentMessage(status) {
|
|
583
553
|
if (status === 'completed') return '支付宝钱包显示本次付款已完成;正在由服务端确认权益。';
|
|
584
554
|
if (status === 'pending_confirmation') return '支付宝已发起本次付款确认;请打开支付宝 App 完成确认,然后运行 status。';
|
|
585
555
|
if (status === 'failed') return '支付宝钱包显示本次付款未完成;未授予付费 Skill 权益。';
|
|
586
|
-
return '
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
function paymentFailureMessage(failureCode) {
|
|
590
|
-
if (failureCode === 'merchant_payment_proof_verification_failed') {
|
|
591
|
-
return '商家未能验证支付宝付款凭证,未授予付费 Skill 权益;请勿重放旧凭证或重复付款。';
|
|
592
|
-
}
|
|
593
|
-
if (failureCode === 'wallet_query_credential_missing') {
|
|
594
|
-
return '支付宝钱包返回待确认,但未返回可继续查询的交易凭据。无法确认是否已付款,因此不会授予付费 Skill 权益;请勿再次付款。';
|
|
595
|
-
}
|
|
596
|
-
if (failureCode === 'wallet_trade_progress_failed') {
|
|
597
|
-
return '支付宝钱包未能创建可确认的交易;未授予付费 Skill 权益。官方钱包没有给出可归因的原因,不能据此判断为 Agent 不受支持、账单签名错误或已扣款;请勿重复付款。';
|
|
598
|
-
}
|
|
599
|
-
if (failureCode === 'wallet_runtime_not_supported') {
|
|
600
|
-
return '当前 Agent 运行环境不支持支付宝 AI付;未授予付费 Skill 权益。';
|
|
601
|
-
}
|
|
602
|
-
if (failureCode === 'payment_needed_rejected') {
|
|
603
|
-
return '支付宝端拒绝了本次付款账单,未创建交易、未扣款。请确认该 APPID 已在支付宝完成 AI按量付费的服务注册、密钥配置、技术集成确认与线上验证前置步骤;若这些均已完成,请提交支付宝问题反馈并附上本次发生时间。';
|
|
604
|
-
}
|
|
605
|
-
return '支付宝官方钱包没有生成可确认的付款状态;未授予付费 Skill 权益。';
|
|
556
|
+
return '支付宝官方钱包已被调用,但尚未返回可确认的付款状态;请查询原交易或联系支持,勿重复付款。';
|
|
606
557
|
}
|
|
607
558
|
|
|
608
559
|
async function fetchPaymentNeeded(resourceUrl, options = {}) {
|
|
@@ -733,21 +684,18 @@ export async function preflightAlipay402Resource(input, options = {}) {
|
|
|
733
684
|
}
|
|
734
685
|
|
|
735
686
|
function publicPaymentResult(state, status, diagnostic, options = {}) {
|
|
736
|
-
const commandFailed = options.commandFailed === true;
|
|
737
687
|
const failureCode = options.failureCode || 'official_cli_nonzero_exit';
|
|
738
688
|
const failed = status === 'failed' || status === 'wallet_command_failed';
|
|
739
|
-
const
|
|
689
|
+
const customerError = failed || status === 'unknown' ? paymentCustomerError(failureCode, { stage: 'payment', reference: `alipay-402:${state.resourceDigest.slice(0, 16)}` }) : null;
|
|
740
690
|
return {
|
|
741
691
|
ok: !failed,
|
|
742
692
|
status,
|
|
743
693
|
provider: 'alipay-agent-payment',
|
|
744
694
|
attemptId: `alipay-402:${state.resourceDigest.slice(0, 16)}`,
|
|
745
695
|
walletInvoked: true,
|
|
746
|
-
message:
|
|
747
|
-
|
|
748
|
-
...(
|
|
749
|
-
...(failed && diagnosis ? { userVisible: paymentFailureUserVisible(diagnosis), diagnosis } : {}),
|
|
750
|
-
...(!failed && options.userVisible ? { userVisible: options.userVisible } : {}),
|
|
696
|
+
message: customerError ? customerError.message : paymentMessage(status),
|
|
697
|
+
userVisible: customerError ? formatPaymentCustomerError(customerError) : paymentMessage(status),
|
|
698
|
+
...(customerError ? { customerError } : {}),
|
|
751
699
|
...(options.officialMedia ? { officialMedia: options.officialMedia } : {}),
|
|
752
700
|
...(options.queryCredentialSource ? { queryCredentialSource: options.queryCredentialSource } : {}),
|
|
753
701
|
...(status === 'pending_confirmation'
|
|
@@ -804,6 +752,27 @@ export async function getAlipayWalletBridgeInfo(options = {}) {
|
|
|
804
752
|
* a stable session id. No protocol data leaves this module.
|
|
805
753
|
*/
|
|
806
754
|
export async function payAlipay402Resource(input, options = {}) {
|
|
755
|
+
if (input?.confirm !== true) throw new AlipayWalletError('ALIPAY_CONFIRMATION_REQUIRED', '付款操作必须由用户明确确认。');
|
|
756
|
+
const resourceUrl = normalizeResourceUrl(input?.resourceUrl);
|
|
757
|
+
const paths = statePaths(resourceUrl, options);
|
|
758
|
+
await ensurePrivateDirectory(paths.directory);
|
|
759
|
+
return withPrivateLock(paths.statePath, async () => {
|
|
760
|
+
const previous = await readPaymentState(resourceUrl, options);
|
|
761
|
+
if (previous) {
|
|
762
|
+
if (previous.status === 'completed') {
|
|
763
|
+
const resource = await fetchPaymentNeeded(resourceUrl, options);
|
|
764
|
+
if (resource.alreadyPaid) return publicPaymentResult(previous, 'completed', 'resource_already_available');
|
|
765
|
+
}
|
|
766
|
+
if (previous.queryCredential?.value) return queryAlipay402ResourceUnlocked(input, options);
|
|
767
|
+
return { ok: false, status: 'payment_result_unconfirmed', provider: 'alipay-agent-payment', walletInvoked: false, retryPayment: false,
|
|
768
|
+
customerError: paymentCustomerError('PAYMENT_RESULT_UNCONFIRMED', { stage: 'local_state', reference: `alipay-402:${previous.resourceDigest.slice(0, 16)}` }),
|
|
769
|
+
message: '原付款尝试尚未核实,已阻止再次付款。请查询原交易或联系支持,勿删除本地记录后重付。' };
|
|
770
|
+
}
|
|
771
|
+
return payAlipay402ResourceUnlocked(input, options);
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
async function payAlipay402ResourceUnlocked(input, options = {}) {
|
|
807
776
|
if (input?.confirm !== true) {
|
|
808
777
|
throw new AlipayWalletError('ALIPAY_CONFIRMATION_REQUIRED', '付款操作必须由用户明确确认。请在展示付款用途后使用 --confirm。');
|
|
809
778
|
}
|
|
@@ -888,12 +857,7 @@ export async function payAlipay402Resource(input, options = {}) {
|
|
|
888
857
|
return publicPaymentResult(state, status, result.diagnostic, {
|
|
889
858
|
commandFailed: failed,
|
|
890
859
|
failureCode,
|
|
891
|
-
|
|
892
|
-
userVisible: ['pending_confirmation', 'completed'].includes(status)
|
|
893
|
-
? userVisibleWalletOutput(walletInvocation.stdout, walletInvocation.stderr)
|
|
894
|
-
: null,
|
|
895
|
-
officialMedia,
|
|
896
|
-
merchantResource: state.merchantResource
|
|
860
|
+
officialMedia
|
|
897
861
|
});
|
|
898
862
|
}
|
|
899
863
|
|
|
@@ -904,6 +868,13 @@ export async function payAlipay402Resource(input, options = {}) {
|
|
|
904
868
|
* local state, initiate a payment, or acknowledge fulfillment.
|
|
905
869
|
*/
|
|
906
870
|
export async function queryAlipay402Resource(input, options = {}) {
|
|
871
|
+
const resourceUrl = normalizeResourceUrl(input?.resourceUrl);
|
|
872
|
+
const paths = statePaths(resourceUrl, options);
|
|
873
|
+
await ensurePrivateDirectory(paths.directory);
|
|
874
|
+
return withPrivateLock(paths.statePath, () => queryAlipay402ResourceUnlocked(input, options));
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
async function queryAlipay402ResourceUnlocked(input, options = {}) {
|
|
907
878
|
const resourceUrl = normalizeResourceUrl(input?.resourceUrl);
|
|
908
879
|
const suppliedOutShakeNo = input?.outShakeNo || input?.businessNo
|
|
909
880
|
? normalizeOutShakeNo(input?.outShakeNo || input?.businessNo)
|
|
@@ -922,7 +893,7 @@ export async function queryAlipay402Resource(input, options = {}) {
|
|
|
922
893
|
provider: 'alipay-agent-payment',
|
|
923
894
|
walletInvoked: false,
|
|
924
895
|
confirmation: { source: 'official_alipay_wallet', required: false },
|
|
925
|
-
message: '
|
|
896
|
+
message: '没有可查询的本地交易凭据;请联系支持核对原交易,勿重复付款或把付款凭证粘贴到对话中。',
|
|
926
897
|
diagnostic: 'payment_state_not_found'
|
|
927
898
|
};
|
|
928
899
|
}
|
|
@@ -972,10 +943,6 @@ export async function queryAlipay402Resource(input, options = {}) {
|
|
|
972
943
|
return publicPaymentResult(state, status, result.diagnostic, {
|
|
973
944
|
commandFailed: failed,
|
|
974
945
|
failureCode,
|
|
975
|
-
diagnosis: failed ? paymentFailureDiagnosis(failureCode, walletInvocation.stdout, walletInvocation.stderr) : undefined,
|
|
976
|
-
userVisible: ['pending_confirmation', 'completed'].includes(status)
|
|
977
|
-
? userVisibleWalletOutput(walletInvocation.stdout, walletInvocation.stderr)
|
|
978
|
-
: null,
|
|
979
946
|
officialMedia,
|
|
980
947
|
...(suppliedOutShakeNo ? { queryCredentialSource: 'supplied_out_shake_no' } : {})
|
|
981
948
|
});
|
|
@@ -997,40 +964,21 @@ export async function diagnoseAlipay402Resource(input, options = {}) {
|
|
|
997
964
|
message: '没有找到本地付款尝试;请不要因此重复付款。'
|
|
998
965
|
};
|
|
999
966
|
}
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
967
|
+
// Build from fixed fields only. Historical local snapshots are private data,
|
|
968
|
+
// not a public response schema; never spread or echo them.
|
|
969
|
+
const statuses = new Set(['started', 'unknown', 'failed', 'wallet_command_failed', 'pending_confirmation', 'completed']);
|
|
970
|
+
const status = statuses.has(state.status) ? state.status : 'unknown';
|
|
971
|
+
const customerError = status === 'completed' || status === 'pending_confirmation' ? null
|
|
972
|
+
: paymentCustomerError(state.lastFailureCode, { reference: `alipay-402:${state.resourceDigest.slice(0, 16)}` });
|
|
973
|
+
return {
|
|
974
|
+
ok: status === 'completed' || status === 'pending_confirmation',
|
|
975
|
+
status, provider: 'alipay-agent-payment', walletInvoked: false,
|
|
1004
976
|
attemptId: `alipay-402:${state.resourceDigest.slice(0, 16)}`,
|
|
1005
|
-
walletInvoked: state.status !== 'started',
|
|
1006
977
|
queryAvailable: Boolean(state.queryCredential?.value),
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
...(
|
|
1010
|
-
...(state.lastDiagnosis ? {
|
|
1011
|
-
diagnosis: state.lastDiagnosis,
|
|
1012
|
-
userVisible: paymentFailureUserVisible(state.lastDiagnosis)
|
|
1013
|
-
} : {}),
|
|
1014
|
-
updatedAt: state.updatedAt || null
|
|
978
|
+
message: customerError ? customerError.message : paymentMessage(status),
|
|
979
|
+
userVisible: customerError ? formatPaymentCustomerError(customerError) : paymentMessage(status),
|
|
980
|
+
...(customerError ? { customerError, retryPayment: false } : {})
|
|
1015
981
|
};
|
|
1016
|
-
// TRADE_PROGRESS_FAILED is deliberately generic in the official wallet
|
|
1017
|
-
// output. Attach a redacted report to the one diagnose command an Agent is
|
|
1018
|
-
// already required to run, rather than relying on it to remember a second
|
|
1019
|
-
// optional command after a failed payment.
|
|
1020
|
-
if (state.lastFailureCode === 'wallet_trade_progress_failed') {
|
|
1021
|
-
const support = await createAlipay402SupportReport({ resourceUrl }, options);
|
|
1022
|
-
if (support.ok && support.report) {
|
|
1023
|
-
result.supportReport = support.report;
|
|
1024
|
-
// Some Agents intentionally present only `userVisible` from a bridge
|
|
1025
|
-
// result. Put the already-redacted support text there as well so the
|
|
1026
|
-
// only useful evidence from this generic upstream error is not silently
|
|
1027
|
-
// dropped by a client-side response mapper.
|
|
1028
|
-
result.userVisible = [result.userVisible, '', '支付宝支持诊断:', support.report.text]
|
|
1029
|
-
.filter((line) => typeof line === 'string' && line.length > 0)
|
|
1030
|
-
.join('\n');
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
return result;
|
|
1034
982
|
}
|
|
1035
983
|
|
|
1036
984
|
/**
|
|
@@ -1054,40 +1002,14 @@ export async function createAlipay402SupportReport(input, options = {}) {
|
|
|
1054
1002
|
};
|
|
1055
1003
|
}
|
|
1056
1004
|
|
|
1057
|
-
const
|
|
1058
|
-
const diagnosis = state.lastDiagnosis || null;
|
|
1059
|
-
const failedBeforeConfirmation = !state.queryCredential?.value &&
|
|
1060
|
-
['failed', 'wallet_command_failed'].includes(state.status);
|
|
1061
|
-
const { stdout, stderr } = await runOfficialCli(['--version'], options);
|
|
1062
|
-
const runtimeVersion = safeRuntimeVersion(stdout, stderr) || null;
|
|
1063
|
-
const lines = [
|
|
1064
|
-
'[环节]:402 支付 / 官方钱包创建交易',
|
|
1065
|
-
`[结果]:${failedBeforeConfirmation ? '未创建可确认交易,未获得 Payment-Proof' : '请以本地诊断状态为准'}`,
|
|
1066
|
-
`[桥接诊断]:${diagnosis?.code || failureCode || 'unknown'}`,
|
|
1067
|
-
`[官方代码]:${diagnosis?.officialCode || '未返回'}`,
|
|
1068
|
-
`[官方运行时]:${runtimeVersion || '未知'}`,
|
|
1069
|
-
`[发生时间]:${state.updatedAt || state.createdAt || '未知'}`,
|
|
1070
|
-
'[已确认]:卖方资源返回字段结构有效的 402 账单;本次未生成可查询交易凭证。',
|
|
1071
|
-
'[请协助]:返回本次 TRADE_PROGRESS_FAILED 的子码、requestId/traceId,以及交易创建被拒绝的具体校验项。'
|
|
1072
|
-
];
|
|
1005
|
+
const customerError = paymentCustomerError(state.lastFailureCode, { reference: `alipay-402:${state.resourceDigest.slice(0, 16)}` });
|
|
1073
1006
|
return {
|
|
1074
|
-
ok: true,
|
|
1075
|
-
status: 'support_report_ready',
|
|
1076
|
-
provider: 'alipay-agent-payment',
|
|
1077
|
-
walletInvoked: false,
|
|
1007
|
+
ok: true, status: 'support_report_ready', provider: 'alipay-agent-payment', walletInvoked: false,
|
|
1078
1008
|
report: {
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
officialRuntimeVersion: runtimeVersion,
|
|
1083
|
-
failureCode,
|
|
1084
|
-
...(diagnosis?.officialCode ? { officialCode: diagnosis.officialCode } : {}),
|
|
1085
|
-
...(diagnosis?.officialSubCode ? { officialSubCode: diagnosis.officialSubCode } : {}),
|
|
1086
|
-
billShapeValidated: state.merchantResource?.billShapeValidated === true,
|
|
1087
|
-
paymentNeededReceived: state.merchantResource?.paymentNeededReceived === true,
|
|
1088
|
-
queryCredentialCreated: Boolean(state.queryCredential?.value),
|
|
1089
|
-
text: lines.join('\n')
|
|
1009
|
+
code: state.status === 'completed' ? 'PAYMENT_COMPLETED' : state.status === 'pending_confirmation' ? 'PAYMENT_CONFIRMATION_PENDING' : customerError.code,
|
|
1010
|
+
supportReference: customerError.supportReference,
|
|
1011
|
+
text: state.status === 'completed' || state.status === 'pending_confirmation' ? paymentMessage(state.status) : formatPaymentCustomerError(customerError)
|
|
1090
1012
|
},
|
|
1091
|
-
message: '
|
|
1013
|
+
message: '请向支持提供此摘要;无需提供密码或付款凭据。'
|
|
1092
1014
|
};
|
|
1093
1015
|
}
|
package/index.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { paymentCustomerError, formatPaymentCustomerError } from './paymentErrors.mjs';
|
|
1
2
|
import { privateDirectory, checkPrivateFile, withPrivateLock, atomicPrivateJson } from './privateState.mjs';
|
|
2
3
|
import { boundedJsonRequest } from './http.mjs';
|
|
3
4
|
import { createHash, randomUUID } from 'node:crypto';
|
|
@@ -11,13 +12,14 @@ export { verifyDirectory as verifyRuntimePackageDirectory, inspectRuntimeArchive
|
|
|
11
12
|
export { reportRuntimeResult, retryRuntimeResults } from './runtimeOutbox.mjs';
|
|
12
13
|
export { runRuntimeScript } from './runtimeScript.mjs';
|
|
13
14
|
export { serveRuntimeScriptHost, retryRuntimeHostResults } from './runtimeHost.mjs';
|
|
15
|
+
export { runAgentTaskCycle, createCodexTaskExecutor } from './agentTaskRunner.mjs';
|
|
14
16
|
export { createRuntimeAgentHost } from './runtimeAgentHost.mjs';
|
|
15
17
|
export { createRuntimeAgentSession } from './runtimeAgent.mjs';
|
|
16
18
|
export { serveRuntimeMcp } from './runtimeMcp.mjs';
|
|
17
19
|
|
|
18
20
|
export { safeOutput as redactCredentials } from './outputSafety.mjs';
|
|
19
21
|
|
|
20
|
-
export const VERSION = '0.1.
|
|
22
|
+
export const VERSION = '0.1.42';
|
|
21
23
|
export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
|
|
22
24
|
|
|
23
25
|
export const DEFAULTS = {
|
|
@@ -447,11 +449,11 @@ export class XiasheClient {
|
|
|
447
449
|
}
|
|
448
450
|
|
|
449
451
|
async signInWithPassword(email, password) {
|
|
450
|
-
return this.mutation(api.auth.signInWithPassword, { email, password });
|
|
452
|
+
return requireAuthSession(await this.mutation(api.auth.signInWithPassword, { email, password }));
|
|
451
453
|
}
|
|
452
454
|
|
|
453
455
|
async registerWithPassword(email, password, displayName = '', verificationCode = '') {
|
|
454
|
-
return this.mutation(api.auth.registerWithPassword, { email, password, displayName, verificationCode });
|
|
456
|
+
return requireAuthSession(await this.mutation(api.auth.registerWithPassword, { email, password, displayName, verificationCode }));
|
|
455
457
|
}
|
|
456
458
|
|
|
457
459
|
async requestEmailCode(email, mode = 'login') {
|
|
@@ -459,7 +461,7 @@ export class XiasheClient {
|
|
|
459
461
|
}
|
|
460
462
|
|
|
461
463
|
async verifyEmailCode(email, code, mode = 'login', displayName = '') {
|
|
462
|
-
return this.mutation(api.auth.verifyEmailCode, { email, code, mode, displayName });
|
|
464
|
+
return requireAuthSession(await this.mutation(api.auth.verifyEmailCode, { email, code, mode, displayName }));
|
|
463
465
|
}
|
|
464
466
|
|
|
465
467
|
/**
|
|
@@ -1518,7 +1520,12 @@ export class XiasheClient {
|
|
|
1518
1520
|
code: 'AGENT_RUNTIME_TOKEN_REQUIRED'
|
|
1519
1521
|
});
|
|
1520
1522
|
}
|
|
1521
|
-
const
|
|
1523
|
+
const route = pathname.startsWith('/') ? pathname : `/${pathname}`;
|
|
1524
|
+
// Claims return a REST base ending in /agent-gateway; method paths include
|
|
1525
|
+
// that prefix too. Join it once, while retaining origin-only legacy profiles.
|
|
1526
|
+
const suffix = new URL(baseUrl).pathname === '/agent-gateway' && route.startsWith('/agent-gateway/')
|
|
1527
|
+
? route.slice('/agent-gateway'.length) : route;
|
|
1528
|
+
const url = `${baseUrl}${suffix}`;
|
|
1522
1529
|
return postJson(url, body, {
|
|
1523
1530
|
timeoutMs: this.timeoutMs,
|
|
1524
1531
|
headers: { authorization: `Bearer ${runtimeToken}` }
|
|
@@ -1570,7 +1577,12 @@ export class XiasheClient {
|
|
|
1570
1577
|
}
|
|
1571
1578
|
|
|
1572
1579
|
async agentCompleteTask(taskId, output = {}, state = 'completed') {
|
|
1573
|
-
|
|
1580
|
+
if (!['completed', 'failed'].includes(state)) throw new Error('AGENT_TASK_STATUS_INVALID');
|
|
1581
|
+
const value = typeof output === 'string' ? { content: output } : output;
|
|
1582
|
+
return this.agentRest('/agent-gateway/tasks/complete', {
|
|
1583
|
+
taskId, status: state, content: value.content || value.response,
|
|
1584
|
+
error: value.error, idempotencyKey: value.idempotencyKey
|
|
1585
|
+
});
|
|
1574
1586
|
}
|
|
1575
1587
|
|
|
1576
1588
|
async agentListPeers() {
|
|
@@ -1612,7 +1624,16 @@ export class XiasheClient {
|
|
|
1612
1624
|
}
|
|
1613
1625
|
}
|
|
1614
1626
|
|
|
1627
|
+
function requireAuthSession(value) {
|
|
1628
|
+
if (typeof value?.error === 'string' && value.error) throw new XiasheError(value.error, { code: 'AUTH_FAILED' });
|
|
1629
|
+
if (!value || typeof value.userId !== 'string' || !value.userId || typeof value.sessionToken !== 'string' || !value.sessionToken) {
|
|
1630
|
+
throw new XiasheError('Authentication did not return a valid session.', { code: 'AUTH_SESSION_MISSING' });
|
|
1631
|
+
}
|
|
1632
|
+
return value;
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1615
1635
|
export async function saveLoginSession(profileName, authResult, authenticatedProfile) {
|
|
1636
|
+
requireAuthSession(authResult);
|
|
1616
1637
|
const session = {
|
|
1617
1638
|
userId: authResult.userId,
|
|
1618
1639
|
email: authResult.email,
|
|
@@ -1648,10 +1669,10 @@ export async function saveAgentSession(profileName, claimResult, authenticatedPr
|
|
|
1648
1669
|
}
|
|
1649
1670
|
|
|
1650
1671
|
export function printableAgentPrompt(issue) {
|
|
1651
|
-
const claimUrl = issue.claimUrl || issue.restBaseUrl?.replace(/\/+$/, '') + '/agent-gateway/claim';
|
|
1672
|
+
const claimUrl = issue.claimUrl || issue.restBaseUrl?.replace(/\/+$/, '').replace(/\/agent-gateway$/, '') + '/agent-gateway/claim';
|
|
1652
1673
|
const receiverCommand = DEFAULT_ENV === 'global'
|
|
1653
|
-
? 'npx -y @agentpie/cli agent
|
|
1654
|
-
: 'npx -y @xiashe/cli agent
|
|
1674
|
+
? 'npx -y @agentpie/cli agent receiver --ack'
|
|
1675
|
+
: 'npx -y @xiashe/cli agent receiver --ack';
|
|
1655
1676
|
if (DEFAULT_ENV === 'global') {
|
|
1656
1677
|
return [
|
|
1657
1678
|
'Connect this Agent to AgentPie. Please complete the setup automatically or call the HTTP endpoint directly. Do not expose the token to the end user.',
|
|
@@ -1679,7 +1700,8 @@ export function printableAgentPrompt(issue) {
|
|
|
1679
1700
|
'',
|
|
1680
1701
|
'Persistent Agents may run a lightweight receiver loop with MCP or REST tool calls only; no long-lived socket is required. The loop should send heartbeat, inspect pendingTaskCount/pendingTransferCount, and only call a model when work is present. Default cadence is about 30s while idle, 10s while work is active, and up to 2 minutes after long idle periods. Use recommendedNextHeartbeatMs with jitter/backoff. Temporary sandbox Agents should not run a loop; reconnect when work is needed.',
|
|
1681
1702
|
'',
|
|
1682
|
-
`
|
|
1703
|
+
`Manual receiver for shell-capable runtimes: ${receiverCommand}`,
|
|
1704
|
+
'This receiver does not invoke a model. An installed, authenticated Codex host can use agent run --executor codex --workdir <local-directory>; verify with run --check first. Text tasks are supported; file transfers require a separate adapter.',
|
|
1683
1705
|
'',
|
|
1684
1706
|
'If you support MCP, add the MCP URL as a tool server and use the runtimeToken as a Bearer token.',
|
|
1685
1707
|
'',
|
|
@@ -1717,7 +1739,8 @@ export function printableAgentPrompt(issue) {
|
|
|
1717
1739
|
'',
|
|
1718
1740
|
'常驻 Agent 可以使用 MCP 或 REST 工具调用运行轻量任务接收循环,不需要长连接:发送心跳,查看 pendingTaskCount/pendingTransferCount;只有存在任务时才拉取任务、确认 running、执行并 complete 回虾舍。默认节奏是空闲约 30 秒一次、有任务约 10 秒一次、长时间空闲后最多约 2 分钟一次。',
|
|
1719
1741
|
'',
|
|
1720
|
-
`如果运行环境可以执行 shell
|
|
1742
|
+
`如果运行环境可以执行 shell,手动接收命令:${receiverCommand}`,
|
|
1743
|
+
'此接收器不会调用模型。已安装并登录 Codex 的宿主可使用 agent run --executor codex --workdir <本地目录>;先运行 run --check。自动执行支持文本任务,文件传输需要单独适配。',
|
|
1721
1744
|
'',
|
|
1722
1745
|
'如果你支持 MCP,请把下面的 MCP URL 加为工具服务,并在调用时使用 runtimeToken 作为 Bearer Token。',
|
|
1723
1746
|
'',
|
package/package.json
CHANGED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Pure, portable presentation shared by the server and CLI. Never serialize an
|
|
2
|
+
// arbitrary exception, provider message, request, or credential into this object.
|
|
3
|
+
const support = '保留原会话,联系支持并提供错误代码及参考号(如有);不要提供密码、密钥或付款凭据。';
|
|
4
|
+
const original = '回到原 Agent 会话,查询原支付宝交易。若已扣款,请勿再次付款;查询仍异常时联系支持。';
|
|
5
|
+
const cases = [
|
|
6
|
+
{ match: ['RUNTIME_SESSION_REQUIRED'], code: 'SKILL_DELIVERY_SESSION_REQUIRED', title: '需要恢复原交付会话', message: '当前环境找不到可用的原交付授权。', stage: 'delivery', nextAction: 'resume_original_delivery', nextStep: '回到原购买账号与 Agent 会话恢复交付;不要删除状态、重复首次接入或再次购买。' },
|
|
7
|
+
{ match: ['ALIPAY_CONFIRMATION_REQUIRED'], code: 'PAYMENT_CONFIRMATION_REQUIRED', title: '需要确认付款用途', message: '当前操作缺少明确的付款确认。', stage: 'payment', nextAction: 'confirm_original_intent', nextStep: '先向用户展示原订单的付款用途并获得确认;已有付款尝试时先查询原交易,不要重复付款。' },
|
|
8
|
+
{ match: ['ALIPAY_RESOURCE_URL_INVALID', 'ALIPAY_RESOURCE_URL_UNSAFE', 'ALIPAY_OUT_SHAKE_NO_INVALID', 'ALIPAY_OUT_SHAKE_NO_CONFLICT', 'ALIPAY_SESSION_ID_INVALID', 'ALIPAY_INTENT_SUMMARY_REQUIRED'], code: 'PAYMENT_INPUT_INVALID', title: '付款参数需要检查', message: '付款入口、查询参数或用途摘要未通过检查。', stage: 'local_state', nextAction: 'restore_original_agent', nextStep: '回原 Agent 会话恢复原订单和查询参数;不要自行拼接链接或查询凭据。' },
|
|
9
|
+
{ match: ['SKILL_PAYMENT_EXPIRED_REQUIRES_RECONCILIATION'], code: 'PAYMENT_WINDOW_EXPIRED', title: '付款窗口已结束', message: '此订单不能继续付款,原交易结果仍需核对。', stage: 'verification', nextAction: 'check_original_payment', nextStep: original },
|
|
10
|
+
{ match: ['SKILL_PAYMENT_MULTIPLE_UNRESOLVED_ORDERS'], code: 'PAYMENT_MULTIPLE_ATTEMPTS_PENDING', title: '发现多笔未决购买', message: '系统已暂停新的付款,避免重复收费。', stage: 'verification', nextAction: 'contact_support', nextStep: support },
|
|
11
|
+
{ match: ['SKILL_PAYMENT_HISTORY_REVIEW_REQUIRED'], code: 'PAYMENT_HISTORY_SYNCING', title: '历史购买记录正在核对', message: '历史记录核对完成前,暂不开放新的付款。', stage: 'verification', nextAction: 'wait_and_resume', nextStep: '稍后在原会话恢复获取;持续未恢复时联系支持,不要换会话重复购买。' },
|
|
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 },
|
|
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
|
+
{ match: ['wallet_not_ready', 'WALLET_NOT_READY'], code: 'PAYMENT_AUTHORIZATION_REQUIRED', title: '支付宝授权尚未完成', message: '需要按官方付款流程完成授权确认。', stage: 'payment', nextAction: 'complete_official_authorization', nextStep: '回原会话按支付宝官方提示处理授权,然后查询原交易,不要新建付款。' },
|
|
16
|
+
{ match: ['buyer_identity_rejected', 'BUYER_IDENTITY_REJECTED'], code: 'PAYMENT_IDENTITY_CHECK_REQUIRED', title: '买家身份未通过核验', message: '当前支付宝身份与原交易的核验结果不一致。', stage: 'payment', nextAction: 'check_original_identity', nextStep: '确认使用原付款账号和原 Agent 会话;仍失败时联系支持,不要发送身份凭据。' },
|
|
17
|
+
{ match: ['insufficient_balance'], code: 'PAYMENT_BALANCE_INSUFFICIENT', title: '付款余额不足', message: '支付宝报告可用余额不足,原订单仍需核对。', stage: 'payment', nextAction: 'check_original_payment', nextStep: '先在支付宝中查看原交易及余额,再按官方提示处理;不要另建订单。' },
|
|
18
|
+
{ match: ['DELIVERY_RECOVERY_REQUIRED', 'DELIVERY_DOWNLOAD_FAILED', 'DELIVERY_NOT_READY'], code: 'SKILL_DELIVERY_INTERRUPTED', title: 'Skill 尚未完成交付', message: '完整包暂未就绪或下载未完成,不需要重新购买。', stage: 'delivery', nextAction: 'resume_original_delivery', nextStep: '使用同一账号和原 Agent 会话恢复交付;若已自动恢复仍失败,请联系支持。' },
|
|
19
|
+
{ match: ['PAYMENT_ORDER_NOT_FOUND'], code: 'PAYMENT_ORDER_UNAVAILABLE', title: '当前入口找不到订单', message: '可能使用了过期入口或不同环境的链接,不能据此判断未付款。', stage: 'verification', nextAction: 'restore_original_agent', nextStep: '回到原购买会话确认账号和入口;不要在另一个环境重新付款。' },
|
|
20
|
+
];
|
|
21
|
+
const configuration = new Set(['payment_needed_rejected', 'ALIPAY_AI_COLLECT_SERVICE_NOT_READY', 'ALIPAY_AI_COLLECT_SERVICE_ID_REQUIRED', 'ALIPAY_AI_COLLECT_SERVICE_ID_CONFLICT', 'ALIPAY_AI_COLLECT_SERVICE_BINDING_DUPLICATED', 'ALIPAY_AI_COLLECT_SERVICE_BINDING_INVALID', 'ALIPAY_AI_COLLECT_REREGISTRATION_REQUIRED', 'CREATOR_ALIPAY_APP_REQUIRED', 'CREATOR_ALIPAY_APP_KEYS_NOT_VERIFIED', 'ALIPAY_PUBLIC_KEY_REQUIRED', 'ALIPAY_RESPONSE_SIGN_INVALID', 'ALIPAY_BILL_SIGNATURE_SELF_CHECK_FAILED', 'ALIPAY_APP_ID_INVALID', 'ALIPAY_AI_COLLECT_DISABLED', 'PAID_SKILL_PLAN_REQUIRED']);
|
|
22
|
+
|
|
23
|
+
/** @param {unknown} input @param {{stage?: string, reference?: string}} [options] */
|
|
24
|
+
export function paymentCustomerError(input, options = {}) {
|
|
25
|
+
const value = input && typeof input === 'object' ? /** @type {Record<string, unknown>} */ (input) : {};
|
|
26
|
+
const raw = typeof input === 'string' ? input : typeof value.code === 'string' ? value.code : typeof value.message === 'string' ? value.message : '';
|
|
27
|
+
// Only read the first normalized error token. No prose/JSON/body is forwarded.
|
|
28
|
+
const token = /^([A-Za-z][A-Za-z0-9_]{2,180})(?=[:\s]|$)/.exec(raw)?.[1] ?? '';
|
|
29
|
+
const selected = cases.find(item => item.match.includes(token));
|
|
30
|
+
const seller = configuration.has(token);
|
|
31
|
+
const reference = typeof options.reference === 'string' && /^(?:pay_[0-9a-f-]{36}|alipay-402:[0-9a-f]{16})$/.test(options.reference) ? options.reference : undefined;
|
|
32
|
+
return {
|
|
33
|
+
code: selected?.code ?? (seller ? 'PAYMENT_SELLER_CONFIGURATION_REQUIRED' : 'PAYMENT_RESULT_UNCONFIRMED'),
|
|
34
|
+
title: selected?.title ?? (seller ? '收款配置需要处理' : '付款结果尚未确认'),
|
|
35
|
+
message: selected?.message ?? (seller ? '创作者的收款配置或支付签名未通过检查,当前不能继续付款。' : '尚未取得可信的付款结果,系统不会因此认定未扣款。'),
|
|
36
|
+
nextAction: selected?.nextAction ?? (seller ? 'contact_creator' : 'check_original_payment'),
|
|
37
|
+
nextStep: selected?.nextStep ?? (seller ? '请联系创作者检查服务登记、应用配置和签名。买家无需修改密钥;保留原交易,勿重复付款。' : original),
|
|
38
|
+
retryPayment: false,
|
|
39
|
+
...(reference ? { supportReference: reference } : {})
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @param {ReturnType<typeof paymentCustomerError>} error */
|
|
44
|
+
export function formatPaymentCustomerError(error) {
|
|
45
|
+
return [error.title, error.message, `下一步:${error.nextStep}`, ...(error.supportReference ? [`支持参考号:${error.supportReference}`] : [])].join('\n');
|
|
46
|
+
}
|