@xiashe/sdk 0.1.40 → 0.1.41

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
@@ -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
- This is a local test prerelease. Real non-OAuth staging acceptance and native interaction validation remain release gates for this delivery. See the repository's `docs/platform/superconnector/development.md` for setup and acceptance procedures.
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/index.mjs CHANGED
@@ -11,13 +11,14 @@ export { verifyDirectory as verifyRuntimePackageDirectory, inspectRuntimeArchive
11
11
  export { reportRuntimeResult, retryRuntimeResults } from './runtimeOutbox.mjs';
12
12
  export { runRuntimeScript } from './runtimeScript.mjs';
13
13
  export { serveRuntimeScriptHost, retryRuntimeHostResults } from './runtimeHost.mjs';
14
+ export { runAgentTaskCycle, createCodexTaskExecutor } from './agentTaskRunner.mjs';
14
15
  export { createRuntimeAgentHost } from './runtimeAgentHost.mjs';
15
16
  export { createRuntimeAgentSession } from './runtimeAgent.mjs';
16
17
  export { serveRuntimeMcp } from './runtimeMcp.mjs';
17
18
 
18
19
  export { safeOutput as redactCredentials } from './outputSafety.mjs';
19
20
 
20
- export const VERSION = '0.1.40';
21
+ export const VERSION = '0.1.41';
21
22
  export { probeRuntimeGateway, runtimeSetupTemplate } from './runtimeSetup.mjs';
22
23
 
23
24
  export const DEFAULTS = {
@@ -447,11 +448,11 @@ export class XiasheClient {
447
448
  }
448
449
 
449
450
  async signInWithPassword(email, password) {
450
- return this.mutation(api.auth.signInWithPassword, { email, password });
451
+ return requireAuthSession(await this.mutation(api.auth.signInWithPassword, { email, password }));
451
452
  }
452
453
 
453
454
  async registerWithPassword(email, password, displayName = '', verificationCode = '') {
454
- return this.mutation(api.auth.registerWithPassword, { email, password, displayName, verificationCode });
455
+ return requireAuthSession(await this.mutation(api.auth.registerWithPassword, { email, password, displayName, verificationCode }));
455
456
  }
456
457
 
457
458
  async requestEmailCode(email, mode = 'login') {
@@ -459,7 +460,7 @@ export class XiasheClient {
459
460
  }
460
461
 
461
462
  async verifyEmailCode(email, code, mode = 'login', displayName = '') {
462
- return this.mutation(api.auth.verifyEmailCode, { email, code, mode, displayName });
463
+ return requireAuthSession(await this.mutation(api.auth.verifyEmailCode, { email, code, mode, displayName }));
463
464
  }
464
465
 
465
466
  /**
@@ -1518,7 +1519,12 @@ export class XiasheClient {
1518
1519
  code: 'AGENT_RUNTIME_TOKEN_REQUIRED'
1519
1520
  });
1520
1521
  }
1521
- const url = `${baseUrl}${pathname.startsWith('/') ? pathname : `/${pathname}`}`;
1522
+ const route = pathname.startsWith('/') ? pathname : `/${pathname}`;
1523
+ // Claims return a REST base ending in /agent-gateway; method paths include
1524
+ // that prefix too. Join it once, while retaining origin-only legacy profiles.
1525
+ const suffix = new URL(baseUrl).pathname === '/agent-gateway' && route.startsWith('/agent-gateway/')
1526
+ ? route.slice('/agent-gateway'.length) : route;
1527
+ const url = `${baseUrl}${suffix}`;
1522
1528
  return postJson(url, body, {
1523
1529
  timeoutMs: this.timeoutMs,
1524
1530
  headers: { authorization: `Bearer ${runtimeToken}` }
@@ -1570,7 +1576,12 @@ export class XiasheClient {
1570
1576
  }
1571
1577
 
1572
1578
  async agentCompleteTask(taskId, output = {}, state = 'completed') {
1573
- return this.agentRest('/agent-gateway/tasks/complete', { taskId, state, output });
1579
+ if (!['completed', 'failed'].includes(state)) throw new Error('AGENT_TASK_STATUS_INVALID');
1580
+ const value = typeof output === 'string' ? { content: output } : output;
1581
+ return this.agentRest('/agent-gateway/tasks/complete', {
1582
+ taskId, status: state, content: value.content || value.response,
1583
+ error: value.error, idempotencyKey: value.idempotencyKey
1584
+ });
1574
1585
  }
1575
1586
 
1576
1587
  async agentListPeers() {
@@ -1612,7 +1623,16 @@ export class XiasheClient {
1612
1623
  }
1613
1624
  }
1614
1625
 
1626
+ function requireAuthSession(value) {
1627
+ if (typeof value?.error === 'string' && value.error) throw new XiasheError(value.error, { code: 'AUTH_FAILED' });
1628
+ if (!value || typeof value.userId !== 'string' || !value.userId || typeof value.sessionToken !== 'string' || !value.sessionToken) {
1629
+ throw new XiasheError('Authentication did not return a valid session.', { code: 'AUTH_SESSION_MISSING' });
1630
+ }
1631
+ return value;
1632
+ }
1633
+
1615
1634
  export async function saveLoginSession(profileName, authResult, authenticatedProfile) {
1635
+ requireAuthSession(authResult);
1616
1636
  const session = {
1617
1637
  userId: authResult.userId,
1618
1638
  email: authResult.email,
@@ -1648,10 +1668,10 @@ export async function saveAgentSession(profileName, claimResult, authenticatedPr
1648
1668
  }
1649
1669
 
1650
1670
  export function printableAgentPrompt(issue) {
1651
- const claimUrl = issue.claimUrl || issue.restBaseUrl?.replace(/\/+$/, '') + '/agent-gateway/claim';
1671
+ const claimUrl = issue.claimUrl || issue.restBaseUrl?.replace(/\/+$/, '').replace(/\/agent-gateway$/, '') + '/agent-gateway/claim';
1652
1672
  const receiverCommand = DEFAULT_ENV === 'global'
1653
- ? 'npx -y @agentpie/cli agent run --ack'
1654
- : 'npx -y @xiashe/cli agent run --ack';
1673
+ ? 'npx -y @agentpie/cli agent receiver --ack'
1674
+ : 'npx -y @xiashe/cli agent receiver --ack';
1655
1675
  if (DEFAULT_ENV === 'global') {
1656
1676
  return [
1657
1677
  '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 +1699,8 @@ export function printableAgentPrompt(issue) {
1679
1699
  '',
1680
1700
  '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
1701
  '',
1682
- `Recommended receiver command for shell-capable runtimes: ${receiverCommand}`,
1702
+ `Manual receiver for shell-capable runtimes: ${receiverCommand}`,
1703
+ '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
1704
  '',
1684
1705
  'If you support MCP, add the MCP URL as a tool server and use the runtimeToken as a Bearer token.',
1685
1706
  '',
@@ -1717,7 +1738,8 @@ export function printableAgentPrompt(issue) {
1717
1738
  '',
1718
1739
  '常驻 Agent 可以使用 MCP 或 REST 工具调用运行轻量任务接收循环,不需要长连接:发送心跳,查看 pendingTaskCount/pendingTransferCount;只有存在任务时才拉取任务、确认 running、执行并 complete 回虾舍。默认节奏是空闲约 30 秒一次、有任务约 10 秒一次、长时间空闲后最多约 2 分钟一次。',
1719
1740
  '',
1720
- `如果运行环境可以执行 shell,推荐接收命令:${receiverCommand}`,
1741
+ `如果运行环境可以执行 shell,手动接收命令:${receiverCommand}`,
1742
+ '此接收器不会调用模型。已安装并登录 Codex 的宿主可使用 agent run --executor codex --workdir <本地目录>;先运行 run --check。自动执行支持文本任务,文件传输需要单独适配。',
1721
1743
  '',
1722
1744
  '如果你支持 MCP,请把下面的 MCP URL 加为工具服务,并在调用时使用 runtimeToken 作为 Bearer Token。',
1723
1745
  '',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiashe/sdk",
3
- "version": "0.1.40",
3
+ "version": "0.1.41",
4
4
  "type": "module",
5
5
  "main": "index.mjs",
6
6
  "exports": {