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: 2 additions & 0 deletions harness-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ alongside `harness-node` over the iii bus.
| `src/models-catalog/` | `models::list`, `models::get`, `models::supports` | Static model metadata. |
| `src/provider-anthropic/` | `provider::anthropic::stream`, `provider::anthropic::complete` | Anthropic SSE → channel writer. |
| `src/provider-openai/` | `provider::openai::stream`, `provider::openai::complete` | OpenAI SSE → channel writer. |
| `src/provider-kimi/` | `provider::kimi::stream`, `provider::kimi::complete` | Kimi (Moonshot) Chat Completions SSE → channel writer. |
| `src/context-compaction/` | (none — pure side-car on `agent::events`) | Optional out-of-band session-history compactor. |

## Quickstart
Expand All @@ -39,6 +40,7 @@ node dist/auth-credentials/main.js --url ws://127.0.0.1:49134 --config ./co
node dist/models-catalog/main.js --url ws://127.0.0.1:49134
node dist/provider-anthropic/main.js --url ws://127.0.0.1:49134 --config ./config.yaml
node dist/provider-openai/main.js --url ws://127.0.0.1:49134 --config ./config.yaml
node dist/provider-kimi/main.js --url ws://127.0.0.1:49134 --config ./config.yaml
node dist/llm-budget/main.js --url ws://127.0.0.1:49134
# Optional side-car:
node dist/context-compaction/main.js --url ws://127.0.0.1:49134
Expand Down
5 changes: 5 additions & 0 deletions harness-node/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,8 @@ provider_anthropic:
provider_openai:
default_max_tokens: 8192
default_api_url: "https://api.openai.com/v1/chat/completions"

# provider-kimi
provider_kimi:
default_max_tokens: 8192
default_api_url: "https://api.moonshot.ai/v1/chat/completions"
7 changes: 7 additions & 0 deletions harness-node/docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ workers.
| models-catalog | [src/models-catalog/](harness-node/src/models-catalog/) | Static model-capability catalogue (state-first, embedded fallback). | [workers/models-catalog.md](harness-node/docs/workers/models-catalog.md) |
| provider-anthropic | [src/provider-anthropic/](harness-node/src/provider-anthropic/) | Anthropic Messages API SSE → channel writer. | [workers/provider-anthropic.md](harness-node/docs/workers/provider-anthropic.md) |
| provider-openai | [src/provider-openai/](harness-node/src/provider-openai/) | OpenAI Chat Completions SSE → channel writer. | [workers/provider-openai.md](harness-node/docs/workers/provider-openai.md) |
| provider-kimi | [src/provider-kimi/](harness-node/src/provider-kimi/) | Kimi Chat Completions SSE → channel writer. | [workers/provider-kimi.md](harness-node/docs/workers/provider-kimi.md) |
| context-compaction | [src/context-compaction/](harness-node/src/context-compaction/) | Optional `agent::events` side-car that compacts session history when running token count crosses a threshold. | [workers/context-compaction.md](harness-node/docs/workers/context-compaction.md) |

## System diagram
Expand All @@ -47,6 +48,7 @@ flowchart LR
models[models-catalog]
provAnth[provider-anthropic]
provOAI[provider-openai]
provKimi[provider-kimi]
compact[context-compaction]
end

Expand All @@ -62,6 +64,7 @@ flowchart LR

turnOrch -- "provider::*::stream" --> provAnth
turnOrch -- "provider::*::stream" --> provOAI
turnOrch -- "provider::*::stream" --> provKimi
turnOrch -- "consultBefore: policy::check_permissions" --> harness
turnOrch -- "agent::call → hook-fanout::publish_collect (after-hook)" --> hook
turnOrch -- "session-tree::* mirror" --> session
Expand All @@ -74,6 +77,7 @@ flowchart LR

provAnth -- "auth::get_token" --> auth
provOAI -- "auth::get_token" --> auth
provKimi -- "auth::get_token" --> auth

state -- "agent::events stream" --> harness
state -- "agent::events stream" --> compact
Expand Down Expand Up @@ -209,12 +213,15 @@ flowchart TD
session --> turnOrch
auth[auth-credentials] --> provAnth[provider-anthropic]
auth --> provOAI[provider-openai]
auth --> provKimi[provider-kimi]
provAnth --> turnOrch
provOAI --> turnOrch
provKimi --> turnOrch
hook[hook-fanout] --> approval
session --> compact[context-compaction]
provAnth --> compact
provOAI --> compact
provKimi --> compact
budget[llm-budget]
```

Expand Down
6 changes: 4 additions & 2 deletions harness-node/docs/workers/context-compaction.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,12 @@ All knobs are env-driven; no `config.yaml` fields are read.
| `COMPACT_TOOL_OUTPUT_MAX_CHARS` | `2000` | Per-output character cap applied before sending to the summariser. |
| `COMPACT_BUSY_TIMEOUT_MS` | `30000` | Max ms `compact_now` / `compact_session` waits for the compaction lease before returning `{ status: 'busy' }`. Sized to cover a typical summariser stream (10–30s) so user-initiated `/compact` doesn't race the async TurnEnd path. |
| `COMPACT_PRUNE_PROTECTED_TOOLS` | _(empty)_ | Comma-separated function IDs whose outputs are never pruned. |
| `COMPACT_SUMMARIZER_PROVIDER` | `anthropic` | `anthropic` or `openai` — picks the streaming provider. |
| `COMPACT_SUMMARIZER_MODEL` | _(model in use)_ | Model id passed to the provider stream. Defaults to the same model as the session. |
| `COMPACT_TRIGGER_TOKENS` | _(deprecated)_ | If set, caps `usable()` to this value. Preserves pre-v2 behaviour. Prefer `COMPACT_RESERVED_TOKENS` instead. |

The summariser provider and model are always inherited from the session's
own selection. Routing goes through `turn-orchestrator/provider-router`,
so adding a provider there automatically covers `/compact`.

## State keys

All keys live under iii state scope `agent`:
Expand Down
75 changes: 75 additions & 0 deletions harness-node/docs/workers/provider-kimi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# provider-kimi

Kimi (Moonshot) Chat Completions streaming provider; exposes
`provider::kimi::stream` and `provider::kimi::complete` on the iii bus.

## Purpose

The iii-side bridge to Moonshot's Chat Completions API. It pulls a
credential from the auth worker (`auth::get_token`, provider `kimi`),
Comment on lines +8 to +9

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Documentation inconsistency with implementation.

The documentation states the worker calls auth::get_token with provider: 'kimi', but according to the PR objectives, the actual implementation in provider-kimi/auth.ts uses provider: 'kimi-coding' as a runtime workaround. Update this line to reflect the current implementation or add a note about the temporary workaround.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@harness-node/docs/workers/provider-kimi.md` around lines 8 - 9, Update the
docs to match the runtime workaround: change the reference to the auth worker
call from auth::get_token with provider 'kimi' to the actual implementation used
at runtime (provider 'kimi-coding'), or add a short note explaining that
provider-kimi/auth.ts currently uses 'kimi-coding' as a temporary workaround;
reference the auth::get_token call and the provider-kimi/auth.ts module so
readers can find the implementation.

issues a streaming `chat/completions` request, parses the SSE response
into `AssistantMessageEvent` frames, and forwards each frame to the
caller-supplied channel. Mirrors the shape of
[provider-openai](harness-node/docs/workers/provider-openai.md) so the
orchestrator can swap providers without touching the FSM.

`provider::kimi::stream` is the modern channel-writer surface;
`provider::kimi::complete` is the legacy drain-and-return helper.

Tool calls are translated to/from the OpenAI function/tool wire format in
[src/provider-kimi/wire-tools.ts](harness-node/src/provider-kimi/wire-tools.ts);
message translation (text, tool-call, tool-result, system) lives in
[src/provider-kimi/wire-messages.ts](harness-node/src/provider-kimi/wire-messages.ts).

## Registered functions

- `provider::kimi::stream` — Stream a single assistant turn from Kimi
Chat Completions into the caller-supplied channel.
- `provider::kimi::complete` — Legacy: drain a streamed Kimi
chat-completion and return the final `AssistantMessage`.

## Triggers

None.

## State keys

None — the worker is stateless.

## Configuration

From the `provider_kimi` section of
[config.yaml](harness-node/config.yaml):

- `default_max_tokens` (default `8192`) — upper bound for the request's
`max_completion_tokens` field when the caller omits it.
- `default_api_url` (default
`https://api.moonshot.ai/v1/chat/completions`) — endpoint for outbound
calls. Override to target Moonshot's China endpoint
(`https://api.moonshot.cn/v1/chat/completions`) or any Chat-Completions
compatible gateway; `auth-credentials` looks up the credential by the
`provider` field, so adjust the gateway and the credential together.

## Dependencies

From
[src/provider-kimi/iii.worker.yaml](harness-node/src/provider-kimi/iii.worker.yaml):
`auth-credentials ^0.2.0`. The worker also calls the SDK-provided
`ChannelWriter` injected into the `writer_ref` field of the stream input.

## Source layout

| File | Purpose |
|---|---|
| [src/provider-kimi/main.ts](harness-node/src/provider-kimi/main.ts) | Binary entry point (`iii-provider-kimi`). |
| [src/provider-kimi/register.ts](harness-node/src/provider-kimi/register.ts) | Registers both functions. |
| [src/provider-kimi/config.ts](harness-node/src/provider-kimi/config.ts) | Loads the `provider_kimi` section. |
| [src/provider-kimi/types.ts](harness-node/src/provider-kimi/types.ts) | `ChatCompletionsConfig` + `configFromCredential` builder. |
| [src/provider-kimi/auth.ts](harness-node/src/provider-kimi/auth.ts) | `fetchCredential` (calls `auth::get_token`) + `buildConfig`. |
| [src/provider-kimi/stream.ts](harness-node/src/provider-kimi/stream.ts) | `streamKimi` async generator: builds the request body, fetches SSE, yields `AssistantMessageEvent`s. |
| [src/provider-kimi/sse.ts](harness-node/src/provider-kimi/sse.ts) | SSE parser. |
| [src/provider-kimi/wire-messages.ts](harness-node/src/provider-kimi/wire-messages.ts) | `AgentMessage[]` → Kimi `messages` translation. |
| [src/provider-kimi/wire-tools.ts](harness-node/src/provider-kimi/wire-tools.ts) | `AgentFunction[]` → Kimi `tools` translation. |
| [src/provider-kimi/stream-fn.ts](harness-node/src/provider-kimi/stream-fn.ts) | `provider::kimi::stream` handler. |
| [src/provider-kimi/complete.ts](harness-node/src/provider-kimi/complete.ts) | `provider::kimi::complete` handler (legacy drain-and-return). |
| [src/provider-kimi/iii.worker.yaml](harness-node/src/provider-kimi/iii.worker.yaml) | Worker manifest. |
2 changes: 2 additions & 0 deletions harness-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"dev:models-catalog": "tsx src/models-catalog/main.ts",
"dev:provider-anthropic": "tsx src/provider-anthropic/main.ts",
"dev:provider-openai": "tsx src/provider-openai/main.ts",
"dev:provider-kimi": "tsx src/provider-kimi/main.ts",
"dev:context-compaction": "tsx src/context-compaction/main.ts"
},
"bin": {
Expand All @@ -44,6 +45,7 @@
"iii-models-catalog": "./dist/models-catalog/main.js",
"iii-provider-anthropic": "./dist/provider-anthropic/main.js",
"iii-provider-openai": "./dist/provider-openai/main.js",
"iii-provider-kimi": "./dist/provider-kimi/main.js",
"iii-context-compaction": "./dist/context-compaction/main.js"
},
"dependencies": {
Expand Down
1 change: 1 addition & 0 deletions harness-node/src/auth-credentials/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export const ENV_VAR_MAP: ReadonlyArray<readonly [string, string]> = [
['minimax', 'MINIMAX_API_KEY'],
['huggingface', 'HF_TOKEN'],
['fireworks', 'FIREWORKS_API_KEY'],
['kimi', 'MOONSHOT_API_KEY'],
['kimi-coding', 'MOONSHOT_API_KEY'],
['opencode-zen', 'OPENCODE_ZEN_API_KEY'],
['opencode-go', 'OPENCODE_GO_API_KEY'],
Expand Down
8 changes: 0 additions & 8 deletions harness-node/src/context-compaction/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,6 @@ export function pruneProtectedTools(): string[] {
.filter(Boolean);
}

export function summarizerProvider(): string | undefined {
return process.env.COMPACT_SUMMARIZER_PROVIDER || undefined;
}

export function summarizerModel(): string | undefined {
return process.env.COMPACT_SUMMARIZER_MODEL || undefined;
}

// Deprecated. Hard upper bound on usable() to keep existing deployments
// from regressing. One-shot warning on first read.
let deprecatedTriggerTokensWarned = false;
Expand Down
28 changes: 13 additions & 15 deletions harness-node/src/context-compaction/summarize.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
import type { ISdk } from '../runtime/iii.js';
import { logger } from '../runtime/otel.js';
import { decide, targetFunctionId } from '../turn-orchestrator/provider-router.js';
import type { AgentMessage, AssistantMessage } from '../types/agent-message.js';
import {
preserveRecentTokensOverride,
summarizerModel,
summarizerProvider,
tailTurns,
toolOutputMaxChars,
} from './config.js';
import { preserveRecentTokensOverride, tailTurns, toolOutputMaxChars } from './config.js';
import { stampLastCompaction } from './lease.js';
import { type ModelLimit, preserveRecentBudget } from './overflow.js';
import {
Expand Down Expand Up @@ -46,7 +41,11 @@ export type SummarizeOutcome = SummarizeOk | SummarizeFailure | 'empty';
export function isRetryableStreamError(err: unknown): boolean {
if (!(err instanceof Error)) return true;
const msg = err.message.toLowerCase();
if (/\b(40[01345]|auth|unauthorized|forbidden|invalid[_ ]?(api[_ ]?key|key|request)|malformed)\b/.test(msg)) {
if (
/\b(40[01345]|auth|unauthorized|forbidden|invalid[_ ]?(api[_ ]?key|key|request)|malformed)\b/.test(
msg,
)
) {
return false;
}
return true;
Expand Down Expand Up @@ -163,13 +162,12 @@ export async function summarizeAndAppend(
const systemPrompt = buildPrompt({ previousSummary, context: [] });
const userPrompt = renderUserPrompt(stripped);

// Default to the session's provider, NOT a hardcoded 'anthropic'.
// Otherwise an OpenAI session ends up calling Anthropic with an OpenAI
// model id (e.g. gpt-5-mini) and the provider returns not_found_error.
const providerName = summarizerProvider() ?? model.providerID;
const summariserId =
providerName === 'openai' ? 'provider::openai::stream' : 'provider::anthropic::stream';
const modelId = summarizerModel() ?? model.modelID;
// Always use the session's own provider/model; route through the
// canonical provider-router so adding a provider covers /compact too.
const summariserId = targetFunctionId(
decide({ provider: model.providerID, model: model.modelID }),
);
const modelId = model.modelID;

// One 250ms retry for transient failures (429/5xx/network). Permanent
// failures (auth, malformed request) skip the retry to release the lease
Expand Down
7 changes: 7 additions & 0 deletions harness-node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { register as registerHookFanout } from './hook-fanout/register.js';
import { register as registerLlmBudget } from './llm-budget/register.js';
import { register as registerModelsCatalog } from './models-catalog/register.js';
import { register as registerProviderAnthropic } from './provider-anthropic/register.js';
import { register as registerProviderKimi } from './provider-kimi/register.js';
import { register as registerProviderOpenai } from './provider-openai/register.js';
import { logger } from './runtime/otel.js';
import {
Expand Down Expand Up @@ -82,6 +83,12 @@ const WORKERS: readonly WorkerDefinition[] = [
'OpenAI Chat Completions streaming provider on the iii bus (provider::openai::stream + ::complete).',
register: (iii, ctx) => registerProviderOpenai(iii, ctx),
},
{
name: 'provider-kimi',
description:
'Kimi (Moonshot) Chat Completions streaming provider on the iii bus (provider::kimi::stream + ::complete).',
register: (iii, ctx) => registerProviderKimi(iii, ctx),
},
{
name: 'llm-budget',
description: 'LLM spend caps with alerts, forecast, period rollover (budget::*).',
Expand Down
28 changes: 28 additions & 0 deletions harness-node/src/models-catalog/models.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,34 @@
"supports_vision": false,
"supports_cache": false,
"transports": ["sse"]
},
{
"id": "kimi-k2.6",
"provider": "kimi",
"api": "openai-completions",
"display_name": "Kimi K2.6",
"context_window": 256000,
"max_output_tokens": 16384,
"supports_thinking": true,
"supports_xhigh": false,
"supports_tools": true,
"supports_vision": true,
"supports_cache": true,
"transports": ["sse"]
},
{
"id": "kimi-k2.5",
"provider": "kimi",
"api": "openai-completions",
"display_name": "Kimi K2.5",
"context_window": 256000,
"max_output_tokens": 16384,
"supports_thinking": true,
"supports_xhigh": false,
"supports_tools": true,
"supports_vision": true,
"supports_cache": true,
"transports": ["sse"]
}
]
}
40 changes: 40 additions & 0 deletions harness-node/src/provider-kimi/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { Credential } from '../auth-credentials/types.js';
import type { ISdk } from '../runtime/iii.js';
import type { WorkerConfig } from './config.js';
import { type ChatCompletionsConfig, configFromCredential } from './types.js';

// Look up the credential under `kimi-coding`. The compiled Rust
// auth-credentials worker (the live handler on most engines today) maps
// `kimi-coding → MOONSHOT_API_KEY` but does not know the bare `kimi` slug
// our node port added. `kimi-coding` is the portable slug; the user-facing
// provider name on the AssistantMessage stays `kimi` (see buildConfig).
const CREDENTIAL_PROVIDER_SLUG = 'kimi-coding';

export async function fetchCredential(iii: ISdk): Promise<Credential> {
const cred = await iii.trigger<unknown, Credential | null>({
function_id: 'auth::get_token',
payload: { provider: CREDENTIAL_PROVIDER_SLUG },
timeoutMs: 5_000,
});
if (!cred || typeof cred !== 'object' || !('type' in cred)) {
throw new Error(
`auth::get_token returned no credential for provider=${CREDENTIAL_PROVIDER_SLUG} (set MOONSHOT_API_KEY)`,
);
}
return cred;
}

export async function buildConfig(
iii: ISdk,
worker: WorkerConfig,
model: string,
): Promise<ChatCompletionsConfig> {
const cred = await fetchCredential(iii);
return configFromCredential(
worker.default_api_url,
'kimi',
model,
cred,
worker.default_max_tokens,
);
}
26 changes: 26 additions & 0 deletions harness-node/src/provider-kimi/complete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { requireString } from '../runtime/handler.js';
import type { ISdk } from '../runtime/iii.js';
import type { AgentMessage } from '../types/agent-message.js';
import type { AgentFunction } from '../types/function.js';
import { buildConfig } from './auth.js';
import type { WorkerConfig } from './config.js';
import { collect, streamKimi } from './stream.js';

export function register(iii: ISdk, worker: WorkerConfig): void {
iii.registerFunction(
'provider::kimi::complete',
async (payload: unknown) => {
const obj = (payload ?? {}) as Record<string, unknown>;
const model = requireString(obj, 'model');
const system_prompt = typeof obj.system_prompt === 'string' ? obj.system_prompt : '';
const messages = Array.isArray(obj.messages) ? (obj.messages as AgentMessage[]) : [];
const tools = Array.isArray(obj.tools) ? (obj.tools as AgentFunction[]) : [];
const cfg = await buildConfig(iii, worker, model);
return await collect(streamKimi({ cfg, system_prompt, messages, tools }));
},
{
description:
'Legacy: drain a streamed Kimi chat-completion and return the final AssistantMessage.',
},
);
}
16 changes: 16 additions & 0 deletions harness-node/src/provider-kimi/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { getNumber, getSection, getString } from '../runtime/config.js';

export type WorkerConfig = {
default_max_tokens: number;
default_api_url: string;
};

export const DEFAULT_API_URL = 'https://api.moonshot.ai/v1/chat/completions';

export function loadWorkerConfig(cfg: Record<string, unknown>): WorkerConfig {
const section = getSection(cfg, 'provider_kimi');
return {
default_max_tokens: getNumber(section, 'default_max_tokens', 8192),
default_api_url: getString(section, 'default_api_url', DEFAULT_API_URL),
};
}
Loading
Loading