Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/monorepo",
"version": "0.12.3",
"version": "0.12.4",
"private": true,
"type": "module",
"packageManager": "pnpm@10.23.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-cli/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-cli",
"version": "0.12.3",
"version": "0.12.4",
"description": "Product-neutral command line for a Steerable host. Products supply the bin name and brand.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-client/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-client",
"version": "0.12.3",
"version": "0.12.4",
"description": "In-process client for a Steerable host: HTTP-shaped requests, turn streams, and approval replies.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-harness/py/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "steerable-agent-harness"
version = "0.12.3"
version = "0.12.4"
description = "Steerable harness helpers for Python"
license = { text = "Apache-2.0" }
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-harness/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-harness",
"version": "0.12.3",
"version": "0.12.4",
"description": "Steerable framework Tier 2 \u2014 TypeScript facade over the Python harness (policy, budget, retry, completion, tracing) used for cross-language conformance tests. Production code should depend on the Python harness.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-protocol/py/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "steerable-agent-protocol"
version = "0.12.3"
version = "0.12.4"
description = "Steerable protocol schemas for Python"
license = { text = "Apache-2.0" }
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-protocol/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-protocol",
"version": "0.12.3",
"version": "0.12.4",
"description": "Steerable framework Tier 1 \u2014 wire-format types (SSEEvent, ChatMessage, ToolCall, ToolResult, AgentSession, HarnessTrace, sidecar JSON-RPC) shared by every Steerable client and server.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-runtime/py/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "steerable-agent-runtime"
version = "0.12.3"
version = "0.12.4"
description = "Steerable agent runtime: LLM, tool, storage, and transport adapters."
license = { text = "Apache-2.0" }
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-runtime/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-runtime",
"version": "0.12.3",
"version": "0.12.4",
"description": "Steerable framework \u2014 official TypeScript production runtime. Owns the embedded Python sidecar lifecycle (spawn / ready handshake / health / bounded auto-restart / graceful drain) and exposes the CoreLoop-level API over the sidecar JSON-RPC surface. There is no TS CoreLoop; this package drives the same Rust CoreLoop the server uses (via the Python sidecar facade), so cross-language conformance holds by construction.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-shell/tauri/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-shell-tauri",
"version": "0.12.3",
"version": "0.12.4",
"description": "Reusable Tauri Rust host source for @steerable/agent-shell",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent-shell/ts/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@steerable/agent-shell",
"version": "0.12.3",
"version": "0.12.4",
"description": "Steerable framework \u2014 product-neutral Node HostRuntime and headless HTTP server shared by Tauri desktop and browser deployments; scenario packs extend it through @steerable/pack-sdk.",
"license": "Apache-2.0",
"homepage": "https://steerableframework.com/",
Expand Down
14 changes: 13 additions & 1 deletion packages/agent-shell/ts/src/local-backend/pack-backend-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,25 @@
*/

import type {
PackBackendAnyResponse,
PackBackendBinaryBytesResponse,
PackBackendBinaryFileResponse,
PackBackendBinaryResponse,
PackBackendRoute,
PackBackendRouteRequest,
PackBackendRouteResponse,
} from '@steerable/pack-sdk';

// 类型单一真源在 @steerable/pack-sdk(阶段 2.2);re-export 兼容既有调用方。
export type { PackBackendRoute, PackBackendRouteRequest, PackBackendRouteResponse };
export type {
PackBackendAnyResponse,
PackBackendBinaryBytesResponse,
PackBackendBinaryFileResponse,
PackBackendBinaryResponse,
PackBackendRoute,
PackBackendRouteRequest,
PackBackendRouteResponse,
};

interface RegisteredPackBackendRoute extends PackBackendRoute {
readonly packId: string;
Expand Down
25 changes: 22 additions & 3 deletions packages/agent-shell/ts/src/local-backend/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ import {
collectPackForcedSkillVars,
collectPackWorldState,
} from './pack-turn-hooks.js';
import { matchPackBackendRoute } from './pack-backend-routes.js';
import { matchPackBackendRoute, type PackBackendBinaryResponse } from './pack-backend-routes.js';
import { invokePackHttpRoute } from '../host/http-routes.js';
import { installProductCli } from '../cli-install.js';
import { collectTurnFiles } from './turn-files.js';
Expand All @@ -164,6 +164,8 @@ export interface LocalBackendRequest {
method: string;
path: string;
body?: unknown;
/** 原始请求头(HTTP 模式下透传)。 */
headers?: Record<string, string | string[] | undefined>;
/** Authenticated identity supplied by the BS HTTP layer. */
principal?: Principal;
}
Expand All @@ -173,6 +175,10 @@ export interface LocalBackendResponse<T = unknown> {
data: T;
}

export type LocalBackendRawResponse<T = unknown> =
| LocalBackendResponse<T>
| PackBackendBinaryResponse;

function stringRecord(value: unknown): Record<string, string> {
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
return Object.fromEntries(
Expand Down Expand Up @@ -586,14 +592,26 @@ export class LocalBackendRouter {
return this.store;
}

handle(request: LocalBackendRequest): Promise<LocalBackendResponse> {
async handle(request: LocalBackendRequest): Promise<LocalBackendResponse> {
const response = await this.handleRaw(request);
if ('kind' in response) {
return {
status: 406,
data: { detail: 'binary response requires HTTP transport' },
};
}
return response;
}

/** 与 handle() 相同,但保留包路由返回的二进制流/字节响应供 HTTP 层直接输出。 */
handleRaw(request: LocalBackendRequest): Promise<LocalBackendRawResponse> {
return this.storeContext.run(
this.resolveStore(request.principal),
() => this.handleScoped(request),
);
}

private async handleScoped(request: LocalBackendRequest): Promise<LocalBackendResponse> {
private async handleScoped(request: LocalBackendRequest): Promise<LocalBackendRawResponse> {
const { method } = request;
const url = new URL(request.path, 'http://local.backend');
const pathname = url.pathname;
Expand Down Expand Up @@ -2670,6 +2688,7 @@ export class LocalBackendRouter {
params: packMatch.params,
query: url.searchParams,
body: request.body,
...(request.headers ? { headers: request.headers } : {}),
});
}

Expand Down
4 changes: 4 additions & 0 deletions packages/agent-shell/ts/src/scenario/pack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ export type {
CliCommandIO,
CliCommandSpec,
ScenarioPack,
PackBackendAnyResponse,
PackBackendBinaryBytesResponse,
PackBackendBinaryFileResponse,
PackBackendBinaryResponse,
PackBackendRouteResponse,
PackBackendRouteRequest,
PackBackendRoute,
Expand Down
152 changes: 147 additions & 5 deletions packages/agent-shell/ts/src/server/http-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@
*/
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import { randomBytes } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { readFile, stat } from 'node:fs/promises';
import { createReadStream, existsSync } from 'node:fs';
import path from 'node:path';
import { log } from '../log.js';
import type { LocalBackendRouter } from '../local-backend/router.js';
import type { PackBackendBinaryResponse } from '../local-backend/pack-backend-routes.js';
import { getActiveCoreLoopStreamId } from '../local-backend/coreloop-stream.js';
import { getSidecarSupervisor } from '../llm/index.js';
import type { ScopedStore } from '../storage/scoped-store.js';
Expand Down Expand Up @@ -129,6 +130,140 @@ function sendJson(res: ServerResponse, status: number, data: unknown): void {
res.end(body);
}

type ParsedByteRange =
| { kind: 'none' }
| { kind: 'invalid' }
| { kind: 'range'; start: number; end: number };

function parseByteRange(header: string | string[] | undefined, size: number): ParsedByteRange {
if (header === undefined) return { kind: 'none' };
const raw = Array.isArray(header) ? header[0] : header;
if (!raw) return { kind: 'none' };
const match = /^bytes=(\d*)-(\d*)$/i.exec(raw.trim());
if (!match) return { kind: 'invalid' };
const [, startText, endText] = match;
if (!startText && !endText) return { kind: 'invalid' };
if (size <= 0) return { kind: 'invalid' };
if (!startText) {
const suffix = Number(endText);
if (!Number.isSafeInteger(suffix) || suffix <= 0) return { kind: 'invalid' };
const start = Math.max(0, size - suffix);
return { kind: 'range', start, end: size - 1 };
}
const start = Number(startText);
if (!Number.isSafeInteger(start) || start < 0 || start >= size) return { kind: 'invalid' };
if (!endText) return { kind: 'range', start, end: size - 1 };
const requestedEnd = Number(endText);
if (!Number.isSafeInteger(requestedEnd) || requestedEnd < start) return { kind: 'invalid' };
return { kind: 'range', start, end: Math.min(requestedEnd, size - 1) };
}

function contentDispositionInline(fileName: string | undefined): string | undefined {
if (!fileName) return undefined;
const ascii = fileName.replace(/[^\x20-\x7E]+/g, '_').replace(/["\\]/g, '_');
const encoded = encodeURIComponent(fileName);
return `inline; filename="${ascii}"; filename*=UTF-8''${encoded}`;
}

async function sendBinaryResponse(
req: IncomingMessage,
res: ServerResponse,
response: PackBackendBinaryResponse,
): Promise<void> {
const disposition = contentDispositionInline(response.fileName);
if (response.kind === 'bytes') {
const headers: Record<string, string | number> = {
'Content-Type': response.contentType,
'Content-Length': response.body.byteLength,
'Cache-Control': response.cacheControl ?? 'private, no-store',
};
if (disposition) headers['Content-Disposition'] = disposition;
res.writeHead(response.status, headers);
res.end(req.method === 'HEAD' ? undefined : response.body);
return;
}

let fileStat;
try {
fileStat = await stat(response.filePath);
} catch {
sendJson(res, 404, { detail: 'file not found' });
return;
}
if (!fileStat.isFile()) {
sendJson(res, 404, { detail: 'file not found' });
return;
}

const size = fileStat.size;
const etag = response.etag ?? `W/"${size}-${Math.round(fileStat.mtimeMs)}"`;
const range = response.status === 200 ? parseByteRange(req.headers.range, size) : { kind: 'none' as const };
if (range.kind === 'invalid') {
res.writeHead(416, {
'Content-Range': `bytes */${size}`,
'Accept-Ranges': 'bytes',
'Cache-Control': 'no-store',
});
res.end();
return;
}

const headers: Record<string, string | number> = {
'Content-Type': response.contentType,
'Accept-Ranges': 'bytes',
'Cache-Control': response.cacheControl ?? 'private, no-cache',
ETag: etag,
};
if (disposition) headers['Content-Disposition'] = disposition;

if (range.kind === 'range') {
headers['Content-Range'] = `bytes ${range.start}-${range.end}/${size}`;
headers['Content-Length'] = range.end - range.start + 1;
res.writeHead(206, headers);
} else {
headers['Content-Length'] = size;
res.writeHead(response.status, headers);
}

if (req.method === 'HEAD' || size === 0) {
res.end();
return;
}

const stream = createReadStream(
response.filePath,
range.kind === 'range' ? { start: range.start, end: range.end } : undefined,
);
const onResClose = () => {
if (!stream.destroyed) stream.destroy();
};
res.on('close', onResClose);
await new Promise<void>((resolve, reject) => {
let settled = false;
const done = () => {
if (settled) return;
settled = true;
res.off('close', onResClose);
resolve();
};
stream.on('error', (err) => {
if (settled) return;
settled = true;
res.off('close', onResClose);
if (!res.headersSent) {
sendJson(res, 500, { detail: 'failed to read file' });
resolve();
return;
}
res.destroy(err);
reject(err);
});
stream.on('close', done);
res.on('finish', done);
stream.pipe(res);
});
}

async function readJsonBody(req: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
let size = 0;
Expand Down Expand Up @@ -215,12 +350,19 @@ export function createBsServer(deps: BsServerDeps): Server {
}

try {
const response = await localBackendRouter.handle(request);
const response = typeof localBackendRouter.handleRaw === 'function'
? await localBackendRouter.handleRaw({ ...request, headers: req.headers })
: await localBackendRouter.handle(request);
log.info(`[bs] ${request.method} ${pathname} -> ${response.status}`);
sendJson(res, response.status, response.data);
if ('kind' in response) {
await sendBinaryResponse(req, res, response);
} else {
sendJson(res, response.status, response.data);
}
} catch (err) {
log.error(`[bs] ${request.method} ${pathname} threw`, err);
sendJson(res, 500, { detail: 'internal error' });
if (!res.headersSent) sendJson(res, 500, { detail: 'internal error' });
else res.end();
}
}

Expand Down
Loading
Loading