mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
feat(plugin): add experimental model HTTP hooks
This commit is contained in:
parent
05d347d750
commit
f77940167c
11 changed files with 227 additions and 47 deletions
|
|
@ -5,13 +5,15 @@ import type { DecisionRequest, DecisionResult, ImageRequest, ImageResult } from
|
|||
import { Money } from "@opencode/schema/money"
|
||||
import { SessionID } from "@opencode/schema/session-id"
|
||||
import { Context, Effect, Layer, Schema } from "effect"
|
||||
import { RequestExecutor } from "@opencode/ai/route"
|
||||
import { RequestExecutor, type HttpMiddleware } from "@opencode/ai/route"
|
||||
import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { llmClient, requestExecutor } from "./effect/app-node-platform.js"
|
||||
import { Integration } from "./integration.js"
|
||||
import { ModelResolver } from "./model-resolver.js"
|
||||
import { Model } from "./model.js"
|
||||
import { ModelHttp } from "./model-http.js"
|
||||
import { ModelRetry } from "./model-retry.js"
|
||||
import { PluginHooks } from "./plugin/hooks.js"
|
||||
|
||||
export interface TextInput {
|
||||
readonly prompt: string
|
||||
|
|
@ -78,7 +80,6 @@ export interface Interface {
|
|||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/Generate") {}
|
||||
|
||||
// Image and decision clients are built here, on the shared request executor, so only Generate depends on them.
|
||||
export const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
|
|
@ -86,8 +87,15 @@ export const layer = Layer.effect(
|
|||
const resolver = yield* ModelResolver.Service
|
||||
const models = yield* Model.Service
|
||||
const executor = yield* RequestExecutor.Service
|
||||
const images = yield* ImageClient.Service
|
||||
const decisionClient = yield* DecisionClient.Service
|
||||
const hooks = yield* PluginHooks.Service
|
||||
// Image and decision clients are built per call so the model HTTP hooks wrap every provider request they make.
|
||||
const clients = (http: HttpMiddleware | undefined) =>
|
||||
Layer.provide(
|
||||
Layer.merge(ImageClient.layer, DecisionClient.layer),
|
||||
http === undefined
|
||||
? Layer.succeed(RequestExecutor.Service, executor)
|
||||
: RequestExecutor.middleware(http, Layer.succeed(RequestExecutor.Service, executor)),
|
||||
)
|
||||
|
||||
const runText = Effect.fn("Generate.text")(function* (input: TextInput) {
|
||||
const resolved = yield* resolver.resolve(input.model).pipe(
|
||||
|
|
@ -111,6 +119,7 @@ export const layer = Layer.effect(
|
|||
if (!resolved && input.model) return yield* missing(input.model, "chat")
|
||||
if (!resolved)
|
||||
return yield* new UnavailableError({ message: "No model specified and no supported model is available" })
|
||||
const http = yield* ModelHttp.middleware(hooks, { model: resolved.ref, kind: "text" })
|
||||
const response = yield* llm
|
||||
.generate(
|
||||
ai.request({
|
||||
|
|
@ -119,6 +128,7 @@ export const layer = Layer.effect(
|
|||
// Gateways require session attribution even for a stateless call; no Session is stored.
|
||||
headers: { "x-opencode-session": SessionID.create() },
|
||||
}),
|
||||
http === undefined ? undefined : { http },
|
||||
)
|
||||
.pipe(
|
||||
ModelRetry.retryOneShot,
|
||||
|
|
@ -151,6 +161,7 @@ export const layer = Layer.effect(
|
|||
.resolveImage(input.model)
|
||||
.pipe(Effect.mapError((error) => resolutionError(input.model, "image", error)))
|
||||
if (!model) return yield* missing(input.model, "image")
|
||||
const http = yield* ModelHttp.middleware(hooks, { model: input.model, kind: "image" })
|
||||
// `ai.image.generate` turns an invalid request into a typed error; building it with `ai.image.request` would throw.
|
||||
const response = yield* ai.image.generate({
|
||||
model,
|
||||
|
|
@ -160,7 +171,7 @@ export const layer = Layer.effect(
|
|||
aspect: input.aspect,
|
||||
resolution: input.resolution,
|
||||
}).pipe(
|
||||
Effect.provideService(ImageClient.Service, images),
|
||||
Effect.provide(clients(http)),
|
||||
ModelRetry.retryOneShot,
|
||||
Effect.mapError((error) => providerError(input.model, error)),
|
||||
)
|
||||
|
|
@ -190,6 +201,7 @@ export const layer = Layer.effect(
|
|||
.resolveDecision(input.model)
|
||||
.pipe(Effect.mapError((error) => resolutionError(input.model, "decision", error)))
|
||||
if (!model) return yield* missing(input.model, "decision")
|
||||
const http = yield* ModelHttp.middleware(hooks, { model: input.model, kind: "decision" })
|
||||
const response = yield* ai.decision.generate({
|
||||
model,
|
||||
input: input.input.map((part) =>
|
||||
|
|
@ -199,7 +211,7 @@ export const layer = Layer.effect(
|
|||
),
|
||||
questions: input.questions,
|
||||
}).pipe(
|
||||
Effect.provideService(DecisionClient.Service, decisionClient),
|
||||
Effect.provide(clients(http)),
|
||||
ModelRetry.retryOneShot,
|
||||
Effect.mapError((error) => providerError(input.model, error)),
|
||||
)
|
||||
|
|
@ -228,7 +240,7 @@ export const layer = Layer.effect(
|
|||
decisions: (input) => credentials(decisions(input)),
|
||||
})
|
||||
}),
|
||||
).pipe(Layer.provide([ImageClient.layer, DecisionClient.layer]))
|
||||
)
|
||||
|
||||
// Provider metadata may hold undefined fields, which the JSON response schema rejects.
|
||||
function plainJson(value: Record<string, unknown>): Record<string, unknown> {
|
||||
|
|
@ -277,5 +289,5 @@ function failureReason(tag: AIError["reason"]["_tag"], status: number | undefine
|
|||
export const node = makeLocationNode({
|
||||
service: Service,
|
||||
layer,
|
||||
deps: [ModelResolver.node, Model.node, llmClient, requestExecutor],
|
||||
deps: [ModelResolver.node, Model.node, PluginHooks.node, llmClient, requestExecutor],
|
||||
})
|
||||
|
|
|
|||
68
packages/core/src/model-http.ts
Normal file
68
packages/core/src/model-http.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
export * as ModelHttp from "./model-http.js"
|
||||
|
||||
import type { HttpMiddleware } from "@opencode/ai/route"
|
||||
import type { SessionRequestKind } from "@opencode/plugin/effect/session"
|
||||
import type { Agent } from "@opencode/schema/agent"
|
||||
import type { Model } from "@opencode/schema/model"
|
||||
import type { Session } from "@opencode/schema/session"
|
||||
import { Effect, Stream } from "effect"
|
||||
import { HttpClientRequest, HttpClientResponse } from "effect/http"
|
||||
import type { PluginHooks } from "./plugin/hooks.js"
|
||||
|
||||
export type Scope = { readonly model: Model.Ref } & (
|
||||
| { readonly kind: SessionRequestKind; readonly sessionID: Session.ID; readonly agent: Agent.ID }
|
||||
| { readonly kind: "text" | "image" | "decision" }
|
||||
)
|
||||
|
||||
/**
|
||||
* Per-call middleware that runs the model `experimental.http.*` hooks, and the session `http.*` hooks when a Session
|
||||
* makes the request. Model hooks wrap session hooks. Undefined when no hook applies.
|
||||
*/
|
||||
export const middleware = Effect.fnUntraced(function* (hooks: PluginHooks.Interface, scope: Scope) {
|
||||
const providerID = scope.model.providerID
|
||||
const session = "sessionID" in scope ? scope : undefined
|
||||
const any = [
|
||||
yield* hooks.has("model", "experimental.http.request", providerID),
|
||||
yield* hooks.has("model", "experimental.http.response", providerID),
|
||||
session !== undefined && (yield* hooks.has("session", "http.request", providerID)),
|
||||
session !== undefined && (yield* hooks.has("session", "http.response", providerID)),
|
||||
].some(Boolean)
|
||||
if (!any) return undefined
|
||||
const http: HttpMiddleware = (req, handler) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpClientRequest.toWeb(req)
|
||||
const outer = yield* hooks.trigger("model", "experimental.http.request", { ...scope, request })
|
||||
const before =
|
||||
session === undefined
|
||||
? outer
|
||||
: yield* hooks.trigger("session", "http.request", { ...session, request: outer.request })
|
||||
// A hook that kept the request object cannot have replaced its body, so the original body is sent as is.
|
||||
// Reading it back would hold a second full copy of the request, screenshots included, for the whole call.
|
||||
const sent =
|
||||
before.request === request
|
||||
? HttpClientRequest.setBody(HttpClientRequest.fromWeb(request), req.body)
|
||||
: before.request.body
|
||||
? HttpClientRequest.bodyUint8Array(
|
||||
HttpClientRequest.fromWeb(before.request),
|
||||
new Uint8Array(yield* Effect.promise(() => before.request.clone().arrayBuffer())),
|
||||
before.request.headers.get("content-type") ?? undefined,
|
||||
)
|
||||
: HttpClientRequest.fromWeb(before.request)
|
||||
const res = yield* handler(sent)
|
||||
const response = new Response(
|
||||
[204, 205, 304].includes(res.status) ? null : yield* Stream.toReadableStreamEffect(res.stream),
|
||||
{ status: res.status, headers: res.headers },
|
||||
)
|
||||
const inner =
|
||||
session === undefined
|
||||
? { response }
|
||||
: yield* hooks.trigger("session", "http.response", { ...session, request: before.request, response })
|
||||
const after = yield* hooks.trigger("model", "experimental.http.response", {
|
||||
...scope,
|
||||
request: before.request,
|
||||
response: inner.response,
|
||||
})
|
||||
return HttpClientResponse.fromWeb(sent, after.response)
|
||||
})
|
||||
return http
|
||||
})
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
export * as PluginHooks from "./hooks.js"
|
||||
|
||||
import type { AISDKHooks } from "@opencode/plugin/effect/aisdk"
|
||||
import type { ModelRequestHooks } from "@opencode/plugin/effect/model"
|
||||
import type { SessionHooks } from "@opencode/plugin/effect/session"
|
||||
import type { ShellHooks } from "@opencode/plugin/effect/shell"
|
||||
import type { ToolFailures, ToolHooks } from "@opencode/plugin/effect/tool"
|
||||
|
|
@ -12,6 +13,7 @@ import { State } from "../state.js"
|
|||
|
||||
export interface Domains {
|
||||
readonly aisdk: AISDKHooks
|
||||
readonly model: ModelRequestHooks
|
||||
readonly session: SessionHooks
|
||||
readonly permission: PermissionHooks
|
||||
readonly shell: ShellHooks
|
||||
|
|
@ -23,6 +25,7 @@ type NoFailures<Spec> = { readonly [Name in keyof Spec]: never }
|
|||
// Failure channel for each hook event. Only tool execute.before may fail: a Tool.Error rejects the call before it runs.
|
||||
interface Failures extends Record<keyof Domains, unknown> {
|
||||
readonly aisdk: NoFailures<AISDKHooks>
|
||||
readonly model: NoFailures<ModelRequestHooks>
|
||||
readonly session: NoFailures<SessionHooks>
|
||||
readonly permission: NoFailures<PermissionHooks>
|
||||
readonly shell: NoFailures<ShellHooks>
|
||||
|
|
|
|||
|
|
@ -235,6 +235,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick<Interfa
|
|||
}),
|
||||
},
|
||||
model: {
|
||||
hook: (name, callback, options) => hooks.register("model", name, callback, options),
|
||||
list: (input) => response(models.available(input?.types)),
|
||||
default: () => response(models.default()),
|
||||
reload: models.reload,
|
||||
|
|
|
|||
|
|
@ -29,10 +29,10 @@ import type {
|
|||
import type { Agent } from "@opencode/schema/agent"
|
||||
import type { Model } from "@opencode/schema/model"
|
||||
import type { Content } from "@opencode/schema/tool"
|
||||
import { Cause, Context, Effect, Layer, Result, Stream } from "effect"
|
||||
import { HttpClientRequest, HttpClientResponse } from "effect/http"
|
||||
import { Cause, Context, Effect, Layer, Result } from "effect"
|
||||
import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { App } from "../app.js"
|
||||
import { ModelHttp } from "../model-http.js"
|
||||
import { Instructions } from "../instructions/index.js"
|
||||
import { Permission } from "../permission.js"
|
||||
import { PluginHooks } from "../plugin/hooks.js"
|
||||
|
|
@ -349,38 +349,7 @@ export const layer = Layer.effect(
|
|||
model: route === base.model.route ? base.model : LanguageModel.update(base.model, { route }),
|
||||
headers: Object.keys(modelHook.headers).length === 0 ? undefined : modelHook.headers,
|
||||
}
|
||||
const hasHttpHooks =
|
||||
(yield* hooks.has("session", "http.request", model.ref.providerID)) ||
|
||||
(yield* hooks.has("session", "http.response", model.ref.providerID))
|
||||
const http: StreamOptions["http"] = hasHttpHooks
|
||||
? (req, handler) =>
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpClientRequest.toWeb(req)
|
||||
const before = yield* hooks.trigger("session", "http.request", { ...scope, request })
|
||||
// A hook that kept the request object cannot have replaced its body, so the original body is sent as is.
|
||||
// Reading it back would hold a second full copy of the request, screenshots included, for the whole call.
|
||||
const sent =
|
||||
before.request === request
|
||||
? HttpClientRequest.setBody(HttpClientRequest.fromWeb(request), req.body)
|
||||
: before.request.body
|
||||
? HttpClientRequest.bodyUint8Array(
|
||||
HttpClientRequest.fromWeb(before.request),
|
||||
new Uint8Array(yield* Effect.promise(() => before.request.clone().arrayBuffer())),
|
||||
before.request.headers.get("content-type") ?? undefined,
|
||||
)
|
||||
: HttpClientRequest.fromWeb(before.request)
|
||||
const res = yield* handler(sent)
|
||||
const after = yield* hooks.trigger("session", "http.response", {
|
||||
...scope,
|
||||
request: before.request,
|
||||
response: new Response(
|
||||
[204, 205, 304].includes(res.status) ? null : yield* Stream.toReadableStreamEffect(res.stream),
|
||||
{ status: res.status, headers: res.headers },
|
||||
),
|
||||
})
|
||||
return HttpClientResponse.fromWeb(sent, after.response)
|
||||
})
|
||||
: undefined
|
||||
const http = yield* ModelHttp.middleware(hooks, scope)
|
||||
// HTTP hooks wrap every HTTP request, including the WebSocket fallback path. The route decides
|
||||
// which transport actually carries the request, so both hook families are always offered.
|
||||
const webSocket =
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import { Integration } from "@opencode/core/integration"
|
|||
import { IntegrationConnection } from "@opencode/core/integration/connection"
|
||||
import { ModelResolver } from "@opencode/core/model-resolver"
|
||||
import { ModelsDev } from "@opencode/core/models-dev"
|
||||
import { PluginHooks } from "@opencode/core/plugin/hooks"
|
||||
import { ID, Info, Model, Ref, VariantID } from "@opencode/core/model"
|
||||
import { Provider } from "@opencode/core/provider"
|
||||
import { Variant } from "@opencode/core/variant"
|
||||
|
|
@ -82,7 +83,8 @@ const aisdk = Layer.mock(AISDK.Service, {
|
|||
const client = TestLLM.testLayer({ fallback: TestLLM.text("OK", "generate") })
|
||||
|
||||
const resolver = ModelResolver.layer.pipe(Layer.provide(Layer.mergeAll(providers, models, integrations, npm, aisdk)))
|
||||
const generateDeps = Layer.mergeAll(models, RequestExecutor.fetchLayer)
|
||||
const hooks = Layer.mock(PluginHooks.Service, { has: () => Effect.succeed(false) })
|
||||
const generateDeps = Layer.mergeAll(models, hooks, RequestExecutor.fetchLayer)
|
||||
const it = testEffect(Generate.layer.pipe(Layer.provide(Layer.mergeAll(resolver, client, generateDeps))))
|
||||
const resolverIt = testEffect(resolver)
|
||||
const retryIt = testEffect(
|
||||
|
|
@ -268,7 +270,7 @@ testEffect(Layer.empty).effect("attributes each stateless completion without cre
|
|||
}),
|
||||
).toBe("OK")
|
||||
}
|
||||
}).pipe(Effect.provide(Generate.layer.pipe(Layer.provide(Layer.mergeAll(resolver, native, models, executor)))))
|
||||
}).pipe(Effect.provide(Generate.layer.pipe(Layer.provide(Layer.mergeAll(resolver, native, models, hooks, executor)))))
|
||||
expect(sessions).toHaveLength(2)
|
||||
expect(sessions[0]).toStartWith("ses_")
|
||||
expect(sessions[1]).not.toBe(sessions[0])
|
||||
|
|
@ -420,7 +422,7 @@ describe("image and decision generation", () => {
|
|||
Layer.provide(Layer.mergeAll(mediaProviders, mediaModels, mediaIntegrations, npm, aisdk)),
|
||||
)
|
||||
const mediaIt = testEffect(
|
||||
Generate.layer.pipe(Layer.provide(Layer.mergeAll(mediaResolver, client, mediaModels, executor))),
|
||||
Generate.layer.pipe(Layer.provide(Layer.mergeAll(mediaResolver, client, mediaModels, hooks, executor))),
|
||||
)
|
||||
const ref = (providerID: string, id: string, variant?: string) =>
|
||||
Ref.make({
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ export function host(overrides: Overrides = {}): Plugin.Context {
|
|||
reload: () => Effect.die("unused provider.reload"),
|
||||
},
|
||||
model: overrides.model ?? {
|
||||
hook: () => Effect.die("unused model.hook"),
|
||||
list: () => Effect.die("unused model.list"),
|
||||
default: () => Effect.die("unused model.default"),
|
||||
transform: () => Effect.die("unused model.transform"),
|
||||
|
|
@ -291,6 +292,7 @@ export const noProviders: Plugin.Context["provider"] = {
|
|||
|
||||
export function modelHost(models: Model.Interface): Plugin.Context["model"] {
|
||||
return {
|
||||
hook: () => Effect.die("unused model.hook"),
|
||||
list: () => models.available().pipe(Effect.map(located)),
|
||||
default: () => models.default().pipe(Effect.map(located)),
|
||||
reload: models.reload,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import type { ModelApi } from "@opencode/client/effect/api"
|
||||
import type { Agent } from "@opencode/schema/agent"
|
||||
import type { Model } from "@opencode/schema/model"
|
||||
import type { Session } from "@opencode/schema/session"
|
||||
import type { Effect, Types } from "effect"
|
||||
import type { ProviderRecord } from "./provider.js"
|
||||
import type { Transform } from "./registration.js"
|
||||
import type { ModelHooks, Transform } from "./registration.js"
|
||||
|
||||
export interface ModelEditor {
|
||||
/** Candidates from available providers, including models disabled by earlier transforms. */
|
||||
|
|
@ -22,7 +24,42 @@ export interface ModelEditor {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a model request is being made. Session requests use `primary`, `compaction`, `title` and `generate`; the
|
||||
* stateless generate API uses `text`, `image` and `decision`. Experimental.
|
||||
*/
|
||||
export type ModelRequestKind = "primary" | "compaction" | "title" | "generate" | "text" | "image" | "decision"
|
||||
|
||||
/** Who is making a model request. `sessionID` and `agent` are set only when a Session makes it. Experimental. */
|
||||
export interface ModelRequestScope {
|
||||
readonly model: Model.Ref
|
||||
readonly kind: ModelRequestKind
|
||||
readonly sessionID?: Session.ID
|
||||
readonly agent?: Agent.ID
|
||||
}
|
||||
|
||||
/** An HTTP request to a model provider, before it is sent. Replace `request` to change it. Experimental. */
|
||||
export interface ModelHttpRequest extends ModelRequestScope {
|
||||
request: Request
|
||||
}
|
||||
|
||||
/** The provider's HTTP response to `request`. Replace `response` to change what the model client reads. Experimental. */
|
||||
export interface ModelHttpResponse extends ModelRequestScope {
|
||||
readonly request: Request
|
||||
response: Response
|
||||
}
|
||||
|
||||
/**
|
||||
* Hooks on every model request, whichever Session or API makes it: Session steps, compaction and titles, and
|
||||
* `generate` text, image and decision calls.
|
||||
*/
|
||||
export interface ModelRequestHooks {
|
||||
readonly "experimental.http.request": ModelHttpRequest
|
||||
readonly "experimental.http.response": ModelHttpResponse
|
||||
}
|
||||
|
||||
export interface ModelDomain extends ModelApi<unknown> {
|
||||
readonly hook: ModelHooks<ModelRequestHooks>
|
||||
readonly transform: Transform<ModelEditor>
|
||||
readonly reload: () => Effect.Effect<void>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -377,6 +377,10 @@ export function fromPromise(plugin: Plugin) {
|
|||
text: adaptApiMethod(GenerateEndpoints["generate.text"], host.generate.text),
|
||||
},
|
||||
model: {
|
||||
hook: (name, callback, options) =>
|
||||
register(
|
||||
host.model.hook(name, (event) => Effect.promise(() => Promise.resolve(callback(event))), options),
|
||||
),
|
||||
list: adaptApiMethod(ModelEndpoints["model.list"], host.model.list),
|
||||
default: adaptApiMethod(ModelEndpoints["model.default"], host.model.default),
|
||||
transform: transform(host.model),
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import type { ModelApi } from "@opencode/client/promise/api"
|
||||
import type { Agent } from "@opencode/schema/agent"
|
||||
import type { Model } from "@opencode/schema/model"
|
||||
import type { Session } from "@opencode/schema/session"
|
||||
import type { Types } from "effect"
|
||||
import type { ProviderRecord } from "./provider.js"
|
||||
import type { Transform } from "./registration.js"
|
||||
import type { ModelHooks, Transform } from "./registration.js"
|
||||
|
||||
export interface ModelEditor {
|
||||
/** Candidates from available providers, including models disabled by earlier transforms. */
|
||||
|
|
@ -22,7 +24,42 @@ export interface ModelEditor {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a model request is being made. Session requests use `primary`, `compaction`, `title` and `generate`; the
|
||||
* stateless generate API uses `text`, `image` and `decision`. Experimental.
|
||||
*/
|
||||
export type ModelRequestKind = "primary" | "compaction" | "title" | "generate" | "text" | "image" | "decision"
|
||||
|
||||
/** Who is making a model request. `sessionID` and `agent` are set only when a Session makes it. Experimental. */
|
||||
export interface ModelRequestScope {
|
||||
readonly model: Model.Ref
|
||||
readonly kind: ModelRequestKind
|
||||
readonly sessionID?: Session.ID
|
||||
readonly agent?: Agent.ID
|
||||
}
|
||||
|
||||
/** An HTTP request to a model provider, before it is sent. Replace `request` to change it. Experimental. */
|
||||
export interface ModelHttpRequest extends ModelRequestScope {
|
||||
request: Request
|
||||
}
|
||||
|
||||
/** The provider's HTTP response to `request`. Replace `response` to change what the model client reads. Experimental. */
|
||||
export interface ModelHttpResponse extends ModelRequestScope {
|
||||
readonly request: Request
|
||||
response: Response
|
||||
}
|
||||
|
||||
/**
|
||||
* Hooks on every model request, whichever Session or API makes it: Session steps, compaction and titles, and
|
||||
* `generate` text, image and decision calls.
|
||||
*/
|
||||
export interface ModelRequestHooks {
|
||||
readonly "experimental.http.request": ModelHttpRequest
|
||||
readonly "experimental.http.response": ModelHttpResponse
|
||||
}
|
||||
|
||||
export interface ModelDomain extends ModelApi {
|
||||
readonly hook: ModelHooks<ModelRequestHooks>
|
||||
readonly transform: Transform<ModelEditor>
|
||||
readonly reload: () => Promise<void>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1704,6 +1704,51 @@ interface SessionHookContext {
|
|||
}
|
||||
```
|
||||
|
||||
### Models (experimental)
|
||||
|
||||
Model HTTP hooks see every HTTP request to a model provider, whichever Session or API makes it: Session steps,
|
||||
compaction and titles, and [Generate](#generate-experimental) text, image and decision calls. They work like the
|
||||
session [Native HTTP](#native-http) hooks and wrap them: a model request hook runs before the session one, and a model
|
||||
response hook runs after it.
|
||||
|
||||
`event.kind` is `"primary"`, `"compaction"`, `"title"` or `"generate"` for Session requests, and `"text"`, `"image"`
|
||||
or `"decision"` for Generate. `sessionID` and `agent` are set only for Session requests. Generate calls made through
|
||||
the HTTP API run in the global config location, so only globally configured plugins see them.
|
||||
|
||||
```ts
|
||||
await ctx.model.hook(
|
||||
"experimental.http.request",
|
||||
(event) => {
|
||||
event.request.headers.set("x-request-kind", event.kind)
|
||||
},
|
||||
{ providerID: "openai" },
|
||||
)
|
||||
```
|
||||
|
||||
#### Reference
|
||||
|
||||
```ts
|
||||
interface ModelHookContext {
|
||||
hook<Name extends "experimental.http.request" | "experimental.http.response">(
|
||||
name: Name,
|
||||
callback: (event: ModelRequestHooks[Name]) => Promise<void> | void,
|
||||
options?: { providerID?: string },
|
||||
): Promise<Registration>
|
||||
}
|
||||
|
||||
interface ModelRequestScope {
|
||||
model: { providerID: string; id: string }
|
||||
kind: "primary" | "compaction" | "title" | "generate" | "text" | "image" | "decision"
|
||||
sessionID?: string
|
||||
agent?: string
|
||||
}
|
||||
|
||||
interface ModelRequestHooks {
|
||||
"experimental.http.request": ModelRequestScope & { request: Request }
|
||||
"experimental.http.response": ModelRequestScope & { request: Request; response: Response }
|
||||
}
|
||||
```
|
||||
|
||||
### Permissions
|
||||
|
||||
Review permission decisions after configured rules are evaluated and before an
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue