承接 sk-wang/hao-code 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sk-wang/hao-code

Composer 安装命令:

composer require sk-wang/hao-code

包简介

PHP agent SDK for Anthropic, OpenAI Responses, and OpenAI Chat Completions APIs.

README 文档

README

A framework-free PHP Agent SDK for Anthropic, OpenAI Responses, and OpenAI Chat Completions-compatible APIs.

hao-code lets PHP applications embed an AI coding agent with tools, skills, streaming output, multi-turn sessions, structured JSON results, cost tracking, abort control, credential pools, and isolated runtime storage.

For the complete SDK reference, see docs/SDK.md.

Install

composer require sk-wang/hao-code

Quick Start

<?php

require __DIR__.'/vendor/autoload.php';

use HaoCode\Sdk\HaoCode;
use HaoCode\Sdk\HaoCodeConfig;

$result = HaoCode::query('Explain this repository', new HaoCodeConfig(
    apiKey: getenv('ANTHROPIC_API_KEY') ?: '',
    cwd: __DIR__,
    allowedTools: ['Read', 'Grep', 'Glob'],
));

echo $result->text;

What It Provides

AreaCapability
Agent executionOne-shot queries, streaming responses, multi-turn conversations, session resume, continue latest session
ProvidersAnthropic, OpenAI Responses API, OpenAI Chat Completions-compatible gateways
ToolsBuilt-in file, search, patch, shell, web, MCP, task, memory, and planning tools, plus custom PHP tools
SandboxOptional temporary filesystem for Read, Write, Glob, Grep, and sandboxed Bash
SkillsPrompt-packaged domain guidance through SdkSkill
Structured outputJSON schema guided responses via HaoCode::structured()
Runtime controlWorking directory, allowed tools, denied tools, permission mode, max turns, max tokens, thinking options
OperationsCost budget, usage metadata, abort controller, callbacks for text/tool/turn events
StateSession IDs, conversation handles, memory summary levels, custom memory storage path
ReliabilityCredential pools, rate-limit tracking, provider abstraction, SDK-only runtime without Laravel dependency

Main APIs

NeedAPI
One-shot queryHaoCode::query()
Streaming messagesHaoCode::stream()
Multi-turn conversationHaoCode::conversation()
Resume a sessionHaoCode::resume()
Continue latest sessionHaoCode::continueLatest()
Structured JSON resultHaoCode::structured()

Configuration

Pass HaoCodeConfig when you need explicit runtime configuration:

use HaoCode\Sdk\HaoCodeConfig;

$config = new HaoCodeConfig(
    apiKey: getenv('OPENAI_API_KEY') ?: '',
    providerType: 'openai_chat',
    baseUrl: 'https://api.openai.com',
    model: 'gpt-4.1',
    maxTokens: 4096,
    cwd: __DIR__,
    maxTurns: 30,
    permissionMode: 'bypass_permissions',
    allowedTools: ['Read', 'Grep', 'Glob'],
    disallowedTools: ['Bash'],
);

If no explicit config is provided, the SDK reads environment and settings values such as ANTHROPIC_API_KEY, HAOCODE_MODEL, HAOCODE_API_BASE_URL, and HAOCODE_MAX_TOKENS.

Sandbox Runtime

Use a sandbox when the agent needs file or shell tools but must not mutate the PHP host project directory. Sandbox mode replaces Read, Write, Glob, and Grep with sandbox-scoped tools. Set mode: 'full' to also replace Bash with a sandbox-scoped shell. Host-only tools such as Edit, apply_patch, NotebookEdit, Lsp, worktree tools, and sub-agent messaging are disabled while sandbox mode is active.

use HaoCode\Sdk\HaoCode;
use HaoCode\Sdk\HaoCodeConfig;
use HaoCode\Sdk\Sandbox\SandboxConfig;

$result = HaoCode::query('Review this project and write notes to notes.md', new HaoCodeConfig(
    cwd: __DIR__,
    sandbox: SandboxConfig::local(
        mode: 'filesystem',  // Read/Write/Glob/Grep only; Bash disabled
        sync: 'upload-cwd',  // copy cwd snapshot into /workspace
    ),
    allowedTools: ['Read', 'Write', 'Grep', 'Glob'],
));

Alibaba Cloud AgentRun

SandboxConfig::agentRun() uses Alibaba Cloud AgentRun as a remote temporary filesystem and execution environment. Use it when the PHP server should not touch local files or run untrusted commands locally.

export AGENTRUN_ACCOUNT_ID=1887527099427005
export AGENTRUN_API_KEY=ak_xxx
export AGENTRUN_TEMPLATE_NAME=sandbox-lagal
export AGENTRUN_REGION=cn-hangzhou
php scripts/agentrun-verify.php

Use AGENTRUN_TEMPLATE_NAME to create a fresh temporary sandbox from a template. Only set AGENTRUN_SANDBOX_ID when you already have a live sandbox instance ID; a template ID is not a sandbox instance ID.

$config = new HaoCodeConfig(
    sandbox: SandboxConfig::agentRun(
        accountId: getenv('AGENTRUN_ACCOUNT_ID'),
        templateName: getenv('AGENTRUN_TEMPLATE_NAME') ?: 'sandbox-lagal',
        apiKey: getenv('AGENTRUN_API_KEY'),
        mode: 'full',
        remoteCwd: '/tmp',
    ),
    allowedTools: ['Read', 'Write', 'Bash'],
);

For the current AgentRun code-interpreter template, write demo files under /tmp/workspace; creating /workspace at the filesystem root can be denied by the container. See examples/agentrun-ml-clustering-agent.php for a complete agent-generated data + Python k-means demo.

Streaming

Use HaoCode::stream() when the caller needs incremental output:

foreach (HaoCode::stream('Summarize the current project') as $message) {
    if ($message->isError()) {
        throw new RuntimeException($message->error);
    }

    if ($message->text !== null) {
        echo $message->text;
    }
}

Conversations

Use a conversation handle when later prompts should keep the same message history and session:

$conversation = HaoCode::conversation(new HaoCodeConfig(cwd: __DIR__));

$conversation->send('Read the service layer and remember the architecture.');
$result = $conversation->send('Now review the newest changes.');

echo $result->text;
echo $conversation->getSessionId();

Structured Output

Use structured() for machine-readable results:

$result = HaoCode::structured('Classify: "payment failed"', [
    'type' => 'object',
    'properties' => [
        'category' => ['type' => 'string'],
        'priority' => ['type' => 'string', 'enum' => ['low', 'medium', 'high']],
    ],
    'required' => ['category', 'priority'],
]);

echo $result->category;

Custom Tools

Define domain-specific PHP tools by extending SdkTool:

use HaoCode\Sdk\HaoCode;
use HaoCode\Sdk\HaoCodeConfig;
use HaoCode\Sdk\SdkTool;

$lookupOrder = new class extends SdkTool {
    public function name(): string { return 'LookupOrder'; }
    public function description(): string { return 'Look up an order by ID.'; }
    public function parameters(): array
    {
        return [
            'order_id' => ['type' => 'string', 'required' => true],
        ];
    }
    public function handle(array $input): string
    {
        return json_encode(['status' => 'paid']);
    }
};

$result = HaoCode::query('Check order A123', new HaoCodeConfig(
    tools: [$lookupOrder],
));

By default SdkTool is treated as read-only. Override isReadOnly() and return false for stateful or mutating tools.

Custom Skills

Use SdkSkill to package reusable prompt guidance:

use HaoCode\Sdk\SdkSkill;

$skill = new SdkSkill(
    name: 'security-review',
    description: 'Review code for common security risks.',
    prompt: 'Check $ARGUMENTS for injection, auth bypass, secrets, and unsafe IO.',
    allowedTools: ['Read', 'Grep'],
);

$result = HaoCode::query('Use security-review on app/Auth.php', new HaoCodeConfig(
    skills: [$skill],
));

Credentials And Budgets

Use credential pools when you have multiple API keys, and cost budgets when the caller needs a hard spending guard:

use HaoCode\Sdk\Credential;
use HaoCode\Sdk\CredentialPool;

$pool = new CredentialPool([
    new Credential(apiKey: getenv('ANTHROPIC_API_KEY_1') ?: ''),
    new Credential(apiKey: getenv('ANTHROPIC_API_KEY_2') ?: ''),
]);

$config = new HaoCodeConfig(
    credentialPool: $pool,
    maxBudgetUsd: 1.00,
);

Callbacks And Abort

HaoCodeConfig supports callbacks for text deltas, tool starts, tool completions, and turn starts. It also supports AbortController for external cancellation:

use HaoCode\Sdk\AbortController;

$abort = new AbortController();

$config = new HaoCodeConfig(
    abortController: $abort,
    onText: fn (string $delta) => print $delta,
    onToolStart: fn (string $name, array $input) => error_log("tool: {$name}"),
);

Storage And Memory

Runtime data is stored under ~/.haocode/storage by default when installed through Composer. Set HAOCODE_STORAGE_PATH for an application-specific runtime directory.

Session memory can be customized with memorySummaryLevel and memoryStoragePath:

$config = new HaoCodeConfig(
    memorySummaryLevel: 'l1',
    memoryStoragePath: __DIR__.'/var/haocode-memory.json',
);

Examples

ExamplePurpose
examples/code-review-agent.phpCode review workflow
examples/agentrun-ml-clustering-agent.phpAgentRun sandbox ML clustering demo
examples/support-ops-agent.phpEnd-to-end support operations agent
examples/weather-agent.phpCustom tool example
examples/sdk-suite/Focused examples for query, streaming, conversation, structured output, abort, credential pools, patching, MCP, and provider matrix

Documentation

Version

v1.0.0 is the first SDK-only release.

License

MIT

sk-wang/hao-code 适用场景与选型建议

sk-wang/hao-code 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 80 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 04 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「sdk」 「Agent」 「ai」 「openai」 「anthropic」 「agent-sdk」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 sk-wang/hao-code 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 sk-wang/hao-code 我们能提供哪些服务?
定制开发 / 二次开发

基于 sk-wang/hao-code 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 80
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 40
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-04