安装方式
手动下载安装
下载 ZIP 后解压到技能目录即可安装。若在桌面客户端 WebView中直接下载出现异常,本站会改为提示页 + 原始链接,请按页内说明操作。
下载 ZIP (shub-javascript-sdk-v1.0.0.zip)触发指令
/javascript-sdk
跨平台安装指引
该技能声明兼容以下 1 个平台,将 ZIP 解压到对应目录即可被识别。
unzip shub-javascript-sdk-v1.0.0.zip -d ~/.claude/skills/
mkdir -p 创建;启用 Skill 后请重启对应 Agent 让配置生效。
使用指南
JavaScript SDK 集成
围绕 JavaScript SDK 集成:在浏览器或 Node 中集成第三方 JS SDK 的模式、错误重试与类型声明。 无需在每次任务前把零散英文说明手工拼进上下文,也 减少 与客户端默认行为脱节的试错;具体命令、钩子与 JSON 参数仍以 ZIP 包内 SKILL.md 为权威。下文结构与站内 MCP CLI 类专题稿相同:何时用、前置、流程、速查与故障。
何时使用
- 在浏览器或 Node 中集成第三方 JS SDK 的模式、错误重试与类型声明
- 已获取本技能 ZIP,并准备在 Claude Code / OpenClaw 中按 SKILL.md 挂载。
- 希望用中文专题稿快速判断「该不该启用」,再深入英文 SKILL 查参数与边界。
- 需要与团队对齐同一套触发方式、目录约定或回调格式时。
前置条件
- 通用:可运行 Claude Code 或文档要求的客户端;有可读写的项目工作区(或 SKILL.md 指定的沙箱目录)。
- 权威细节:API Key / OAuth、钩子路径、环境变量以 ZIP 内 SKILL.md 为准。
典型流程
- 从 ClawHub / 站内分发获取技能 ZIP,校验版本与校验和(若提供)。
- 阅读 SKILL.md 的安装段落:目录落点、客户端类型(Claude Code / OpenClaw / 脚本)。
- 用文档中的最小示例完成第一次调用(单文件修改、单次查询或单次委派)。
- 确认工作目录、权限边界与输出路径后,再处理多文件或长耗时任务。
- 需要回调 / Webhook / 通知时,按 SKILL.md 配置端点并在测试环境先验通。
与 ZIP / SKILL.md 的关系
站内专题稿与 MCP CLI 类 oss 稿同样:概括何时用、怎么接、怎么排错;命令模板、钩子名、JSON 字段、版本矩阵一律以 ZIP 内 SKILL.md 与 ClawHub 上游为准。
命令示例(摘自包内 SKILL.md)
以下为从上游 SKILL.md(或入库正文)自动抽取的终端/脚本片段;路径、环境变量与参数以当前 ZIP 与官方说明为准。
ClawHub slug:javascript-sdk(安装命令以 SKILL.md / claw CLI 为准)。
npm install @inferencesh/sdk
npm install @inferencesh/sdk
# or
yarn add @inferencesh/sdk
# or
pnpm add @inferencesh/sdk
# Python SDK
npx skills add inference-sh/skills@python-sdk
# Full platform skill (all 150+ apps via CLI)
npx skills add inference-sh/skills@inference-sh
# LLM models
npx skills add inference-sh/skills@llm-models
# Image generation
npx skills add inference-sh/skills@ai-image-generation
站内入库时的触发命令(完整语义见 ZIP):
# 使用本技能时可在对话中引用或执行上述指令;完整参数与示例见下载包内 SKILL.md。
/javascript-sdk
最佳实践
- 先 SKILL.md 再猜参数;站内专题稿不替代 schema 与必填字段说明。
- 委派任务时写清验收标准(命令、文件路径、测试命令),减少来回追问。
- 长任务用文档推荐的回调 / 日志落盘代替高频轮询,省 Token 也省机器负载。
- 多技能同时启用时,注意钩子加载顺序与重复工具调用(以 SKILL.md 冲突说明为准)。
调试与排错
- 打开 stderr 与客户端日志;PTY/tmux 场景同时看面板最后几十行输出。
- 参数错误时对照 SKILL.md 中的 JSON/CLI 示例(引号、转义、工作目录)。
- 网络类失败:查代理、防火墙、MCP 传输方式(stdio / HTTP / SSE)。
速查
| 动作 | 说明 |
|------|------|
| 获取技能包 | ClawHub / 站内 ZIP,核对版本 |
| 权威步骤 | 优先阅读 ZIP 内 SKILL.md |
| 首次试跑 | 使用 SKILL.md 最小示例 |
| 验收 | 对照路径、测试命令或回调负载 |
常见故障
- 无输出或立即退出 → 工作目录错误、依赖未装、或 Claude Code 未登录;按 SKILL.md 自检清单执行。
- 权限被拒绝 → 检查沙箱路径、
--permission-mode与工具白名单。 - 与简介不符 → 以英文 SKILL 与上游仓库为准,站内稿仅作结构化导读。
# JavaScript SDK
Build AI applications with the [inference.sh](https://inference.sh) JavaScript/TypeScript SDK.

## Quick Start
```bash
npm install @inferencesh/sdk
```
```typescript
import { inference } from '@inferencesh/sdk';
const client = inference({ apiKey: 'inf_your_key' });
// Run an AI app
const result = await client.run({
app: 'infsh/flux-schnell',
input: { prompt: 'A sunset over mountains' }
});
console.log(result.output);
```
## Installation
```bash
npm install @inferencesh/sdk
# or
yarn add @inferencesh/sdk
# or
pnpm add @inferencesh/sdk
```
**Requirements:** Node.js 18.0.0+ (or modern browser with fetch)
## Authentication
```typescript
import { inference } from '@inferencesh/sdk';
// Direct API key
const client = inference({ apiKey: 'inf_your_key' });
// From environment variable (recommended)
const client = inference({ apiKey: process.env.INFERENCE_API_KEY });
// For frontend apps (use proxy)
const client = inference({ proxyUrl: '/api/inference/proxy' });
```
Get your API key: Settings → API Keys → Create API Key
## Running Apps
### Basic Execution
```typescript
const result = await client.run({
app: 'infsh/flux-schnell',
input: { prompt: 'A cat astronaut' }
});
console.log(result.status); // "completed"
console.log(result.output); // Output data
```
### Fire and Forget
```typescript
const task = await client.run({
app: 'google/veo-3-1-fast',
input: { prompt: 'Drone flying over mountains' }
}, { wait: false });
console.log(`Task ID: ${task.id}`);
// Check later with client.getTask(task.id)
```
### Streaming Progress
```typescript
const stream = await client.run({
app: 'google/veo-3-1-fast',
input: { prompt: 'Ocean waves at sunset' }
}, { stream: true });
for await (const update of stream) {
console.log(`Status: ${update.status}`);
if (update.logs?.length) {
console.log(update.logs.at(-1));
}
}
```
### Run Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `app` | string | App ID (namespace/name@version) |
| `input` | object | Input matching app schema |
| `setup` | object | Hidden setup configuration |
| `infra` | string | 'cloud' or 'private' |
| `session` | string | Session ID for stateful execution |
| `session_timeout` | number | Idle timeout (1-3600 seconds) |
## File Handling
### Automatic Upload
```typescript
const result = await client.run({
app: 'image-processor',
input: {
image: '/path/to/image.png' // Auto-uploaded
}
});
```
### Manual Upload
```typescript
// Basic upload
const file = await client.uploadFile('/path/to/image.png');
// With options
const file = await client.uploadFile('/path/to/image.png', {
filename: 'custom_name.png',
contentType: 'image/png',
public: true
});
const result = await client.run({
app: 'image-processor',
input: { image: file.uri }
});
```
### Browser File Upload
```typescript
const input = document.querySelector('input[type="file"]');
const file = await client.uploadFile(input.files[0]);
```
## Sessions (Stateful Execution)
Keep workers warm across multiple calls:
```typescript
// Start new session
const result = await client.run({
app: 'my-app',
input: { action: 'init' },
session: 'new',
session_timeout: 300 // 5 minutes
});
const sessionId = result.session_id;
// Continue in same session
const result2 = await client.run({
app: 'my-app',
input: { action: 'process' },
session: sessionId
});
```
## Agent SDK
### Template Agents
Use pre-built agents from your workspace:
```typescript
const agent = client.agent('my-team/support-agent@latest');
// Send message
const response = await agent.sendMessage('Hello!');
console.log(response.text);
// Multi-turn conversation
const response2 = await agent.sendMessage('Tell me more');
// Reset conversation
agent.reset();
// Get chat history
const chat = await agent.getChat();
```
### Ad-hoc Agents
Create custom agents programmatically:
```typescript
import { tool, string, number, appTool } from '@inferencesh/sdk';
// Define tools
const calculator = tool('calculate')
.describe('Perform a calculation')
.param('expression', string('Math expression'))
.build();
const imageGen = appTool('generate_image', 'infsh/flux-schnell@latest')
.describe('Generate an image')
.param('prompt', string('Image description'))
.build();
// Create agent
const agent = client.agent({
core_app: { ref: 'infsh/claude-sonnet-4@latest' },
system_prompt: 'You are a helpful assistant.',
tools: [calculator, imageGen],
temperature: 0.7,
max_tokens: 4096
});
const response = await agent.sendMessage('What is 25 * 4?');
```
### Available Core Apps
| Model | App Reference |
|-------|---------------|
| Claude Sonnet 4 | `infsh/claude-sonnet-4@latest` |
| Claude 3.5 Haiku | `infsh/claude-haiku-35@latest` |
| GPT-4o | `infsh/gpt-4o@latest` |
| GPT-4o Mini | `infsh/gpt-4o-mini@latest` |
## Tool Builder API
### Parameter Types
```typescript
import {
string, number, integer, boolean,
enumOf, array, obj, optional
} from '@inferencesh/sdk';
const name = string('User\'s name');
const age = integer('Age in years');
const score = number('Score 0-1');
const active = boolean('Is active');
const priority = enumOf(['low', 'medium', 'high'], 'Priority');
const tags = array(string('Tag'), 'List of tags');
const address = obj({
street: string('Street'),
city: string('City'),
zip: optional(string('ZIP'))
}, 'Address');
```
### Client Tools (Run in Your Code)
```typescript
const greet = tool('greet')
.display('Greet User')
.describe('Greets a user by name')
.param('name', string('Name to greet'))
.requireApproval()
.build();
```
### App Tools (Call AI Apps)
```typescript
const generate = appTool('generate_image', 'infsh/flux-schnell@latest')
.describe('Generate an image from text')
.param('prompt', string('Image description'))
.setup({ model: 'schnell' })
.input({ steps: 20 })
.requireApproval()
.build();
```
### Agent Tools (Delegate to Sub-agents)
```typescript
import { agentTool } from '@inferencesh/sdk';
const researcher = agentTool('research', 'my-org/researcher@v1')
.describe('Research a topic')
.param('topic', string('Topic to research'))
.build();
```
### Webhook Tools (Call External APIs)
```typescript
import { webhookTool } from '@inferencesh/sdk';
const notify = webhookTool('slack', 'https://hooks.slack.com/...')
.describe('Send Slack notification')
.secret('SLACK_SECRET')
.param('channel', string('Channel'))
.param('message', string('Message'))
.build();
```
### Internal Tools (Built-in Capabilities)
```typescript
import { internalTools } from '@inferencesh/sdk';
const config = internalTools()
.plan()
.memory()
.webSearch(true)
.codeExecution(true)
.imageGeneration({
enabled: true,
appRef: 'infsh/flux@latest'
})
.build();
const agent = client.agent({
core_app: { ref: 'infsh/claude-sonnet-4@latest' },
internal_tools: config
});
```
## Streaming Agent Responses
```typescript
const response = await agent.sendMessage('Explain quantum computing', {
onMessage: (msg) => {
if (msg.content) {
process.stdout.write(msg.content);
}
},
onToolCall: async (call) => {
console.log(`\n[Tool: ${call.name}]`);
const result = await executeTool(call.name, call.args);
agent.submitToolResult(call.id, result);
}
});
```
## File Attachments
```typescript
// From file path (Node.js)
import { readFileSync } from 'fs';
const response = await agent.sendMessage('What\'s in this image?', {
files: [readFileSync('image.png')]
});
// From base64
const response = await agent.sendMessage('Analyze this', {
files: ['data:image/png;base64,iVBORw0KGgo...']
});
// From browser File object
const input = document.querySelector('input[type="file"]');
const response = await agent.sendMessage('Describe this', {
files: [input.files[0]]
});
```
## Skills (Reusable Context)
```typescript
const agent = client.agent({
core_app: { ref: 'infsh/claude-sonnet-4@latest' },
skills: [
{
name: 'code-review',
description: 'Code review guidelines',
content: '# Code Review\n\n1. Check security\n2. Check performance...'
},
{
name: 'api-docs',
description: 'API documentation',
url: 'https://example.com/skills/api-docs.md'
}
]
});
```
## Server Proxy (Frontend Apps)
For browser apps, proxy through your backend to keep API keys secure:
### Client Setup
```typescript
const client = inference({
proxyUrl: '/api/inference/proxy'
// No apiKey needed on frontend
});
```
### Next.js Proxy (App Router)
```typescript
// app/api/inference/proxy/route.ts
import { createRouteHandler } from '@inferencesh/sdk/proxy/nextjs';
const route = createRouteHandler({
apiKey: process.env.INFERENCE_API_KEY
});
export const POST = route.POST;
```
### Express Proxy
```typescript
import express from 'express';
import { createProxyMiddleware } from '@inferencesh/sdk/proxy/express';
const app = express();
app.use('/api/inference/proxy', createProxyMiddleware({
apiKey: process.env.INFERENCE_API_KEY
}));
```
### Supported Frameworks
- Next.js (App Router & Pages Router)
- Express
- Hono
- Remix
- SvelteKit
## TypeScript Support
Full type definitions included:
```typescript
import type {
TaskDTO,
ChatDTO,
ChatMessageDTO,
AgentTool,
TaskStatusCompleted,
TaskStatusFailed
} from '@inferencesh/sdk';
if (result.status === TaskStatusCompleted) {
console.log('Done!');
} else if (result.status === TaskStatusFailed) {
console.log('Failed:', result.error);
}
```
## Error Handling
```typescript
import { RequirementsNotMetException, InferenceError } from '@inferencesh/sdk';
try {
const result = await client.run({ app: 'my-app', input: {...} });
} catch (e) {
if (e instanceof RequirementsNotMetException) {
console.log('Missing requirements:');
for (const err of e.errors) {
console.log(` - ${err.type}: ${err.key}`);
}
} else if (e instanceof InferenceError) {
console.log('API error:', e.message);
}
}
```
## Human Approval Workflows
```typescript
const response = await agent.sendMessage('Delete all temp files', {
onToolCall: async (call) => {
if (call.requiresApproval) {
const approved = await promptUser(`Allow ${call.name}?`);
if (approved) {
const result = await executeTool(call.name, call.args);
agent.submitToolResult(call.id, result);
} else {
agent.submitToolResult(call.id, { error: 'Denied by user' });
}
}
}
});
```
## CommonJS Support
```javascript
const { inference, tool, string } = require('@inferencesh/sdk');
const client = inference({ apiKey: 'inf_...' });
const result = await client.run({...});
```
## Reference Files
- [Agent Patterns](references/agent-patterns.md) - Multi-agent, RAG, batch processing patterns
- [Tool Builder](references/tool-builder.md) - Complete tool builder API reference
- [Server Proxy](references/server-proxy.md) - Next.js, Express, Hono, Remix, SvelteKit setup
- [Streaming](references/streaming.md) - Real-time progress updates and SSE handling
- [File Handling](references/files.md) - Upload, download, and manage files
- [Sessions](references/sessions.md) - Stateful execution with warm workers
- [TypeScript](references/typescript.md) - Type definitions and type-safe patterns
- [React Integration](references/react-integration.md) - Hooks, components, and patterns
## Related Skills
```bash
# Python SDK
npx skills add inference-sh/skills@python-sdk
# Full platform skill (all 150+ apps via CLI)
npx skills add inference-sh/skills@inference-sh
# LLM models
npx skills add inference-sh/skills@llm-models
# Image generation
npx skills add inference-sh/skills@ai-image-generation
```
## Documentation
- [JavaScript SDK Reference](https://inference.sh/docs/api/sdk-javascript) - Full API documentation
- [Agent SDK Overview](https://inference.sh/docs/api/agent-sdk) - Building agents
- [Tool Builder Reference](https://inference.sh/docs/api/agent-tools) - Creating tools
- [Server Proxy Setup](https://inference.sh/docs/api/sdk/server-proxy) - Frontend integration
- [Authentication](https://inference.sh/docs/api/authentication) - API key setup
- [Streaming](https://inference.sh/docs/api/sdk/streaming) - Real-time updates
- [File Uploads](https://inference.sh/docs/api/sdk/files) - File handling