@hosty-sdk/app 0.55.0 → 0.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/agent-client.d.ts +8 -0
- package/dist/agent-client.js +31 -6
- package/dist/agent-schemas.js +18 -6
- package/dist/agent-server.d.ts +7 -1
- package/dist/agent-server.js +35 -6
- package/dist/agent-sessions.d.ts +1 -0
- package/dist/agent.d.ts +15 -2
- package/dist/providers-server.d.ts +1 -1
- package/dist/providers-server.js +6 -3
- package/dist/providers.d.ts +15 -0
- package/dist/providers.js +43 -0
- package/package.json +1 -1
- package/schemas/agent-event-v1.schema.json +143 -2
- package/schemas/{agent-v1.fixtures.json → agent-v2.fixtures.json} +45 -7
- package/schemas/{agent-v1.openapi.json → agent-v2.openapi.json} +665 -70
package/README.md
CHANGED
|
@@ -310,6 +310,14 @@ static and named entries. Keep the installation, key and implementation ID with
|
|
|
310
310
|
`displayName` is the current human-readable label. Pass the selection to `speechCapabilities`
|
|
311
311
|
and `transcribe`, or to `textToSpeechCapabilities` and `synthesize(selected, { text }, signal)`.
|
|
312
312
|
Synthesis returns a streaming fetch Response. Abort or cancel its body to stop the request.
|
|
313
|
+
|
|
314
|
+
For translated read-aloud, call `resolveSpeechTargetLanguage(requested, preferences, capabilities)`
|
|
315
|
+
from `@hosty-sdk/app/providers` before playback and pass the returned tag as `targetLanguage`
|
|
316
|
+
to `synthesize`. The resolver checks an explicit target first, then the acting user's
|
|
317
|
+
`{ preferredLanguage, autoTranslateReadAloud }` preferences. An unsupported explicit target raises
|
|
318
|
+
`speech_target_language_unsupported`. An unavailable automatic target resolves to `undefined`,
|
|
319
|
+
which retains the original-language request. Reuse the resolved target for all chunks of one
|
|
320
|
+
playback.
|
|
313
321
|
The provider backend publishes with `publishImplementations` and resolves the exact implementation
|
|
314
322
|
from `validate` on each request. See the [app manifest guide](../../skills/hosty-app-skill/references/app-manifest.md#named-provider-implementations).
|
|
315
323
|
|
package/dist/agent-client.d.ts
CHANGED
|
@@ -49,7 +49,10 @@ export declare class AgentClient {
|
|
|
49
49
|
configureSession(sessionId: string, configurationId: string, input: AgentConfigurationCreate, options?: AgentRequestOptions): Promise<AgentSession>;
|
|
50
50
|
startRun(sessionId: string, runId: string, input: AgentRunInput, options?: AgentRequestOptions): Promise<AgentRunSnapshot>;
|
|
51
51
|
run(runId: string, options?: AgentRequestOptions): Promise<AgentRunSnapshot>;
|
|
52
|
+
closure(runId: string, options?: AgentRequestOptions): Promise<import("./agent.js").AgentRunClosure>;
|
|
53
|
+
discardDelivery(runId: string, requestId: string, options?: AgentRequestOptions): Promise<import("./agent.js").AgentDiscardReceipt>;
|
|
52
54
|
respond(runId: string, input: AgentResponseInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
|
|
55
|
+
stop(runId: string, requestId?: string, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
|
|
53
56
|
cancel(runId: string, input: AgentCancelInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
|
|
54
57
|
control(runId: string, requestId: string, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
|
|
55
58
|
runControl(runId: string, input: AgentRunControlInput, options?: AgentRequestOptions): Promise<AgentControlReceipt>;
|
|
@@ -97,6 +100,11 @@ export declare function watchAgentHistory(options: AgentHistoryOptions): AsyncGe
|
|
|
97
100
|
export declare function watchLiveAgentHistory(options: AgentHistoryOptions & {
|
|
98
101
|
onReady: (boundary: string) => void | Promise<void>;
|
|
99
102
|
}): AsyncGenerator<AgentHistoryObservation>;
|
|
103
|
+
export declare function acknowledgeAgentHistory(options: AgentHistoryOptions, receipt: {
|
|
104
|
+
sessionId: string;
|
|
105
|
+
epoch: string;
|
|
106
|
+
through: number;
|
|
107
|
+
}): Promise<void>;
|
|
100
108
|
export declare function readAgentHistoryStates(options: AgentHistoryOptions & HistoryPageOptions & {
|
|
101
109
|
afterSession?: string;
|
|
102
110
|
}): Promise<{
|
package/dist/agent-client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { AgentApiError, } from "./agent.js";
|
|
3
|
-
import { agentReplayCursor, validateAgentEvent, validateAgentRunSnapshot, validateAgentRequest, validateAgentSession, validateAgentCapabilities, validateAgentControlReceipt } from "./agent-server.js";
|
|
3
|
+
import { agentReplayCursor, validateAgentEvent, validateAgentRunClosure, validateAgentRunSnapshot, validateAgentRequest, validateAgentSession, validateAgentCapabilities, validateAgentControlReceipt } from "./agent-server.js";
|
|
4
4
|
const MAX_BYTES = 1024 * 1024;
|
|
5
5
|
const sha = (body) => createHash("sha256").update(body, "utf8").digest("hex");
|
|
6
6
|
const segment = (id) => {
|
|
@@ -22,7 +22,7 @@ export const prepareAgentSessionCreate = (sessionId, input) => prepareAgentReque
|
|
|
22
22
|
export const prepareAgentConfiguration = (sessionId, configurationId, input) => prepareAgentRequest("sessions.configure", "PUT", `/sessions/${segment(sessionId)}/configurations/${segment(configurationId)}`, input, { sessionId });
|
|
23
23
|
export const prepareAgentRun = (sessionId, runId, input) => prepareAgentRequest("runs.start", "PUT", `/sessions/${segment(sessionId)}/runs/${segment(runId)}`, input, { sessionId, runId, resources: input.resources, ceiling: { mcp: input.mcp, resources: input.resources, configurationRevision: input.configurationRevision } });
|
|
24
24
|
export const prepareAgentResponse = (runId, input) => prepareAgentRequest("runs.respond", "POST", `/runs/${segment(runId)}/responses`, input, { runId });
|
|
25
|
-
export const prepareAgentCancel = (runId, input) => prepareAgentRequest("runs.cancel", "
|
|
25
|
+
export const prepareAgentCancel = (runId, input) => prepareAgentRequest("runs.cancel", "PUT", `/runs/${segment(runId)}/stop`, input, { runId, ...(input.fenceIfNotAdmitted ? { sessionId: input.fenceIfNotAdmitted.sessionId } : {}) });
|
|
26
26
|
export const prepareAgentControl = (runId, input) => prepareAgentRequest("runs.control", "POST", `/runs/${segment(runId)}/controls`, input, { runId });
|
|
27
27
|
export const prepareAgentAttachmentChunk = (attachmentId, index, input) => prepareAgentRequest("attachments.write", "PUT", `/attachments/${segment(attachmentId)}/chunks/${index}`, input);
|
|
28
28
|
/** Backend-to-backend transport. The authorizer talks to Core; only its scoped token reaches the provider. */
|
|
@@ -108,7 +108,25 @@ export class AgentClient {
|
|
|
108
108
|
this.checkSnapshot(value, runId);
|
|
109
109
|
return value;
|
|
110
110
|
}
|
|
111
|
+
async closure(runId, options) {
|
|
112
|
+
const value = await this.get("runs.closure", `/runs/${segment(runId)}/closure`, options, { runId });
|
|
113
|
+
validateAgentRunClosure(value);
|
|
114
|
+
if (value.ref.id !== runId || !sameProvider(this.options.provider, value.ref.provider)
|
|
115
|
+
|| value.pendingContinuations?.some(c => !sameProvider(this.options.provider, c.run.provider)))
|
|
116
|
+
throw new AgentApiError("response_invalid", "The closure belongs to another attempt or provider.", 502);
|
|
117
|
+
return value;
|
|
118
|
+
}
|
|
119
|
+
async discardDelivery(runId, requestId, options) {
|
|
120
|
+
const command = prepareAgentRequest("runs.discard", "PUT", `/runs/${segment(runId)}/discard`, { requestId }, { runId });
|
|
121
|
+
const value = await this.execute(command, options);
|
|
122
|
+
if (value?.requestId !== requestId || value.runId !== runId || value.state !== "discarded")
|
|
123
|
+
throw new AgentApiError("response_invalid", "The provider returned a different discard receipt.", 502);
|
|
124
|
+
return value;
|
|
125
|
+
}
|
|
111
126
|
respond(runId, input, options) { return this.execute(prepareAgentResponse(runId, input), options); }
|
|
127
|
+
stop(runId, requestId = runId, options) {
|
|
128
|
+
return this.cancel(runId, { requestId }, options);
|
|
129
|
+
}
|
|
112
130
|
cancel(runId, input, options) { return this.execute(prepareAgentCancel(runId, input), options); }
|
|
113
131
|
control(runId, requestId, options) { return this.get("runs.controls.read", `/runs/${segment(runId)}/controls/${segment(requestId)}`, options, { runId }); }
|
|
114
132
|
runControl(runId, input, options) { return this.execute(prepareAgentControl(runId, input), options); }
|
|
@@ -304,6 +322,7 @@ async function historyResponse(options, accept, page, endpoint, parameters) {
|
|
|
304
322
|
url.searchParams.set("limit", String(page.limit));
|
|
305
323
|
}
|
|
306
324
|
const response = await (options.fetch ?? globalThis.fetch)(url, {
|
|
325
|
+
method: endpoint === "ack" ? "POST" : "GET",
|
|
307
326
|
headers: { accept, authorization: `Bearer ${options.token}` },
|
|
308
327
|
signal: options.signal, redirect: "error", cache: "no-store",
|
|
309
328
|
});
|
|
@@ -410,8 +429,7 @@ export async function* watchLiveAgentHistory(options) {
|
|
|
410
429
|
if (frame.event !== "observation")
|
|
411
430
|
throw new AgentApiError("event_invalid", "Unexpected live history frame.", 502);
|
|
412
431
|
const observation = historyObservation(value, frame.id, options.provider);
|
|
413
|
-
|
|
414
|
-
if (!observation.epoch || transient !== (observation.sessionPosition === undefined))
|
|
432
|
+
if (!observation.epoch || !historyPosition(observation.sessionPosition))
|
|
415
433
|
throw new AgentApiError("event_invalid", "Invalid live record position.", 502);
|
|
416
434
|
yield observation;
|
|
417
435
|
}
|
|
@@ -423,6 +441,14 @@ export async function* watchLiveAgentHistory(options) {
|
|
|
423
441
|
if (!ready)
|
|
424
442
|
throw new AgentApiError("stream_closed", "The stream closed before its live boundary.", 503, true);
|
|
425
443
|
}
|
|
444
|
+
export async function acknowledgeAgentHistory(options, receipt) {
|
|
445
|
+
if (!historyIdentity(receipt.sessionId) || !historyIdentity(receipt.epoch) || !historyPosition(receipt.through))
|
|
446
|
+
throw new AgentApiError("invalid_input", "Invalid durable history receipt.", 400);
|
|
447
|
+
const response = await historyResponse({ ...options, cursor: undefined }, "application/json", undefined, "ack", receipt);
|
|
448
|
+
const value = JSON.parse(await boundedText(response, 1024));
|
|
449
|
+
if (!historyObject(value) || value.through !== receipt.through)
|
|
450
|
+
throw new AgentApiError("response_invalid", "Invalid history acknowledgement.", 502);
|
|
451
|
+
}
|
|
426
452
|
export async function readAgentHistoryStates(options) {
|
|
427
453
|
const response = await historyResponse({ ...options, cursor: undefined }, "application/json", options, "states", { afterSession: options.afterSession });
|
|
428
454
|
const page = JSON.parse(await boundedText(response, 2 * MAX_BYTES + 32768));
|
|
@@ -461,8 +487,7 @@ export async function readAgentHistoryRange(options) {
|
|
|
461
487
|
throw new AgentApiError("response_invalid", "Invalid session history range page.", 502);
|
|
462
488
|
const observations = page.observations.map((value, index) => {
|
|
463
489
|
const item = historyObservation(value, value?.cursor, options.provider);
|
|
464
|
-
if (item.sessionId !== sessionId || item.epoch !== epoch || item.sessionPosition !== from + index || item.sessionPosition > to
|
|
465
|
-
|| item.item.kind === "event" && ["message.delta", "tool.output"].includes(item.item.event.type))
|
|
490
|
+
if (item.sessionId !== sessionId || item.epoch !== epoch || item.sessionPosition !== from + index || item.sessionPosition > to)
|
|
466
491
|
throw new AgentApiError("response_invalid", "Invalid durable session record or range ordering.", 502);
|
|
467
492
|
return item;
|
|
468
493
|
});
|
package/dist/agent-schemas.js
CHANGED
|
@@ -47,7 +47,9 @@ export const AGENT_SCHEMAS = {
|
|
|
47
47
|
DecisionResponse: { oneOf: [object({ kind: { const: "approval" }, decision: { enum: ["allow", "deny"] }, message: { type: "string", maxLength: 65536 } }, ["kind", "decision"]),
|
|
48
48
|
object({ kind: { const: "question" }, answers: { type: "object", maxProperties: 128, propertyNames: id, additionalProperties: { oneOf: [{ type: "string", maxLength: 65536 }, list({ type: "string", maxLength: 65536 }, 128)] } } })] },
|
|
49
49
|
ResponseInput: object({ ...baseControl, decisionId: id, decisionRevision: revision, response: ref("DecisionResponse") }),
|
|
50
|
-
|
|
50
|
+
DiscardInput: object({ requestId: uuid }),
|
|
51
|
+
DiscardReceipt: object({ requestId: uuid, runId: uuid, state: { const: "discarded" } }),
|
|
52
|
+
CancelInput: { oneOf: [object({ requestId: uuid }), object(baseControl), object({ requestId: uuid, fenceIfNotAdmitted: object({ sessionId: id, startDigest: digest }) })] },
|
|
51
53
|
ControlInput: { oneOf: [
|
|
52
54
|
object({ ...baseControl, command: { const: "park" }, decisionId: id, decisionRevision: revision, reason: text(8192) }, [...Object.keys(baseControl), "command", "decisionId", "decisionRevision"]),
|
|
53
55
|
object({ ...baseControl, command: { const: "barrier" }, barrierId: id, kind: { enum: ["task_adoption", "child_wait", "source_rebind", "limits", "human_input"] }, generation: revision, acknowledgedSequence: sequence, snapshot: text(8192) }, [...Object.keys(baseControl), "command", "barrierId", "kind", "generation", "acknowledgedSequence"]),
|
|
@@ -68,7 +70,7 @@ export const AGENT_SCHEMAS = {
|
|
|
68
70
|
Tool: object({ id, source: ref("Source"), name: text(), input: {}, output: { type: "string", maxLength: 1048576 }, state: { enum: ["running", "completed", "failed", "cancelled", "unknown"] }, truncated: boolean,
|
|
69
71
|
command: object({ status: { enum: ["completed", "failed", "cancelled", "unknown"] }, exitCode: { type: "integer" }, durationMs: { type: "integer", minimum: 0 }, summary: text(65536) }, ["status"]) }, ["id", "name", "state"], true),
|
|
70
72
|
RunSnapshot: object({ ref: ref("QualifiedRef"), sessionId: id, generation: uuid, revision: sequence,
|
|
71
|
-
state: { enum: terminalStates }, phase: { enum: phases }, stopConfirmed: boolean, freshness: { enum: ["current", "last_known", "unavailable"] }, observedAt: { type: "string", format: "date-time" },
|
|
73
|
+
state: { enum: terminalStates }, phase: { enum: phases }, stopConfirmed: boolean, writerScopeClosed: boolean, freshness: { enum: ["current", "last_known", "unavailable"] }, observedAt: { type: "string", format: "date-time" },
|
|
72
74
|
configurationRevision: revision, lastSequence: sequence, cursor: text(8192), pending: list(ref("PendingDecision"), 256),
|
|
73
75
|
effects: object({ certainty: { enum: ["known", "unknown"] }, unresolvedCallIds: unique(id, 1024) }), result: ref("Result"), messages: list(ref("Message"), 4096), tools: list(ref("Tool"), 4096),
|
|
74
76
|
agents: list(ref("ChildAgent"), 1024),
|
|
@@ -81,7 +83,7 @@ export const AGENT_SCHEMAS = {
|
|
|
81
83
|
pendingContinuations: list(object({ requestId: uuid, run: ref("QualifiedRef"), state: { enum: ["pending", "awaiting_authorization", "admitted", "superseded"] } }), 256) }, ["ref", "sessionId", "generation", "revision", "state", "phase", "stopConfirmed", "freshness", "observedAt", "configurationRevision", "lastSequence", "cursor", "pending", "effects"], true),
|
|
82
84
|
HistoryObservation: object(historyObservation),
|
|
83
85
|
LiveHistoryReady: object({ through: text(8192) }),
|
|
84
|
-
LiveHistoryObservation: object({ ...historyObservation, epoch: uuid, sessionPosition: positive, sourceHistoryIncomplete: { const: true } }, [...Object.keys(historyObservation), "epoch"]),
|
|
86
|
+
LiveHistoryObservation: object({ ...historyObservation, epoch: uuid, sessionPosition: positive, sourceHistoryIncomplete: { const: true } }, [...Object.keys(historyObservation), "epoch", "sessionPosition"]),
|
|
85
87
|
HistoryStates: object({ through: text(8192), nextSession: nullableText, sessions: list(object({
|
|
86
88
|
sessionId: id, userId: text(512), principalId: text(512), epoch: uuid, head: positive, snapshot: ref("RunSnapshot"), sourceHistoryIncomplete: { const: true },
|
|
87
89
|
}, ["sessionId", "userId", "principalId", "epoch", "head", "snapshot"]), 100) }),
|
|
@@ -92,13 +94,17 @@ export const AGENT_SCHEMAS = {
|
|
|
92
94
|
Session: object({ ref: ref("QualifiedRef"), revision, configurationRevision: revision, configurationDigest: digest,
|
|
93
95
|
nativeState: { enum: ["not_created", "available", "missing", "unavailable", "unknown"] }, activeRun: { oneOf: [ref("QualifiedRef"), { type: "null" }] },
|
|
94
96
|
resolvedSkills: list(object({ skillId: digest, digest }), 202), configuration: ref("Configuration"), correlation: object({ conversation: ref("QualifiedRef"), task: ref("QualifiedRef") }, []) }, ["ref", "revision", "configurationRevision", "configurationDigest", "nativeState", "activeRun", "resolvedSkills"], true),
|
|
97
|
+
Closure: object({ ref: ref("QualifiedRef"), sessionId: id, generation: uuid, revision: sequence,
|
|
98
|
+
state: { enum: terminalStates }, phase: { enum: phases }, stopConfirmed: boolean, writerScopeClosed: boolean,
|
|
99
|
+
pendingContinuations: list(object({ requestId: uuid, run: ref("QualifiedRef"), state: { enum: ["pending", "awaiting_authorization", "admitted", "superseded"] } }), 256)
|
|
100
|
+
}, ["ref", "sessionId", "generation", "revision", "state", "phase", "stopConfirmed"]),
|
|
95
101
|
ControlReceipt: object({ requestId: uuid, state: { enum: ["accepted", "applied", "rejected", "superseded", "unknown"] }, run: ref("QualifiedRef"), revision: sequence, generation: uuid, error: ref("ErrorDetail"),
|
|
96
102
|
continuation: object({ run: ref("QualifiedRef"), state: { enum: ["pending", "awaiting_authorization", "admitted", "superseded"] } }) }, ["requestId", "state", "run", "revision"], true),
|
|
97
103
|
ErrorDetail: object({ code: text(), message: { type: "string", maxLength: 8192 }, retryable: boolean, requestId: uuid, details: { type: "object", additionalProperties: true } }, ["code", "message", "retryable"], true),
|
|
98
104
|
Error: object({ error: ref("ErrorDetail") }),
|
|
99
105
|
Connection: object({ id, revision, name: text(), ready: boolean, reason: text(8192), capabilities: capability }, ["id", "revision", "name", "ready"], true),
|
|
100
106
|
ModelCatalog: object({ revision: text(256), models: list(object({ id: text(), name: text(), reasoningEfforts: list(nullableText), defaultReasoningEffort: nullableText, capabilities: capability, unavailableReason: text(8192) }, ["id", "reasoningEfforts"], true), 1000), defaultModel: nullableText, nextCursor: { type: ["string", "null"], maxLength: 8192 } }, ["revision", "models", "defaultModel"], true),
|
|
101
|
-
Capabilities: object({ version: { const:
|
|
107
|
+
Capabilities: object({ version: { const: 2 }, eventVersions: unique(text(), 16), capabilities: capability,
|
|
102
108
|
limits: object({ maxCommandBytes: positive, maxEventBytes: positive, maxSnapshotBytes: positive, maxReplayBytes: positive, replayRetentionMs: positive, maxControls: positive, maxPageSize: positive, maxDurationMs: positive, maxSkillSnapshotBytes: positive, maxSkillSnapshotFiles: positive }, ["maxCommandBytes", "maxEventBytes", "maxSnapshotBytes", "maxReplayBytes", "replayRetentionMs", "maxControls", "maxPageSize"], true), configuration: object({ resumeCompatible: unique(text(), 32) }) }, ["version", "eventVersions", "capabilities", "limits", "configuration"], true),
|
|
103
109
|
};
|
|
104
110
|
const eventNames = ["run.updated", "session.bound", "selection.updated", "message.started", "message.delta", "message.completed", "tool.started", "tool.output", "tool.completed", "decision.requested", "decision.updated", "decision.resolved", "control.updated", "result.available", "usage.updated", "context.updated", "agent.updated", "warning", "extension"];
|
|
@@ -129,13 +135,17 @@ const historySecurity = [{ installationHistory: [] }];
|
|
|
129
135
|
const historyParam = (name, schema, required = false) => ({ name, in: "query", schema, required });
|
|
130
136
|
const pageLimit = historyParam("limit", { type: "integer", minimum: 1, maximum: 100 });
|
|
131
137
|
export const AGENT_OPENAPI = {
|
|
132
|
-
openapi: "3.1.0", info: { title: "Hosty Agent Execution API", version: "
|
|
138
|
+
openapi: "3.1.0", info: { title: "Hosty Agent Execution API", version: "2.0.0", description: "Independent provider execution. Paths are relative to the current Core-declared interface base. Exact UTF-8 command bytes and stable mutation UUIDs are retained across retries. No Harness dependency or raw native session IDs." },
|
|
133
139
|
paths: {
|
|
134
140
|
"/history/live": { get: { operationId: "history.live", security: historySecurity, parameters: [historyParam("after", text(8192))],
|
|
135
141
|
description: "Open a fresh live subscription. The optional previous cursor checks archive ancestry. The ready event returns the subscribed boundary. Subsequent observation events carry an SSE id and every durable record carries its session position.",
|
|
136
142
|
responses: { ...errors, "200": { description: "Ready boundary followed by live observations.", content: {
|
|
137
143
|
"text/event-stream": { schema: { type: "string" }, "x-event-schemas": { ready: ref("LiveHistoryReady"), observation: ref("LiveHistoryObservation") } },
|
|
138
144
|
} } } } },
|
|
145
|
+
"/history/ack": { post: { operationId: "history.ack", security: historySecurity,
|
|
146
|
+
description: "Commit the receiver's contiguous durable session position. Requires explicit acknowledgement authority for the consuming installation.",
|
|
147
|
+
parameters: [historyParam("sessionId", id, true), historyParam("epoch", uuid, true), historyParam("through", positive, true)],
|
|
148
|
+
responses: { ...errors, "200": { description: "Acknowledged contiguous position.", content: { "application/json": { schema: object({ through: positive }) } } } } } },
|
|
139
149
|
"/history/states": { get: { operationId: "history.states", security: historySecurity,
|
|
140
150
|
parameters: [historyParam("through", text(8192)), historyParam("afterSession", id), pageLimit],
|
|
141
151
|
description: "List sessions with retained runs and their state and durable session head at the supplied or current installation boundary. Pass the returned boundary on later pages.",
|
|
@@ -163,7 +173,9 @@ export const AGENT_OPENAPI = {
|
|
|
163
173
|
description: "At-least-once SSE. after and Last-Event-ID must agree. Persisted Event envelopes use event: agent and an opaque id cursor. 410 replay_expired requires installing a fresh atomic snapshot before following its cursor. Disconnect never cancels execution.",
|
|
164
174
|
responses: { ...errors, "200": { description: "Persisted agent event stream.", content: { "text/event-stream": { schema: { type: "string" }, "x-event-schema": ref("Event") } } } } } },
|
|
165
175
|
"/runs/{runId}/responses": { post: operation("runs.respond", "ControlReceipt", "ResponseInput", ["runId"], [200, 202]) },
|
|
166
|
-
"/runs/{runId}/
|
|
176
|
+
"/runs/{runId}/closure": { get: operation("runs.closure", "Closure", undefined, ["runId"]) },
|
|
177
|
+
"/runs/{runId}/discard": { put: operation("runs.discard", "DiscardReceipt", "DiscardInput", ["runId"]) },
|
|
178
|
+
"/runs/{runId}/stop": { put: operation("runs.cancel", "ControlReceipt", "CancelInput", ["runId"], [200, 202]) },
|
|
167
179
|
"/runs/{runId}/controls": { post: { ...operation("runs.control", "ControlReceipt", "ControlInput", ["runId"], [200, 202]), description: "Optional controls require their advertised capabilities. Reconcile input is an attestation, never proof of actual native exit. Retirement requires provider-owned evidence of native process exit. Its applied receipt records retirement of the exact run and preserves unresolved tool outcomes." } },
|
|
168
180
|
"/runs/{runId}/controls/{requestId}": { get: operation("runs.controls.read", "ControlReceipt", undefined, ["runId", "requestId"]) },
|
|
169
181
|
}, components: { securitySchemes: { installationHistory: { type: "http", scheme: "bearer", description: "Core-issued installation history credential." }, coreOperation: { type: "http", scheme: "bearer", description: "Fresh Core exact-operation credential, never the caller's service/user token." } }, schemas: AGENT_SCHEMAS },
|
package/dist/agent-server.d.ts
CHANGED
|
@@ -27,6 +27,11 @@ export type AgentParsedRequest = AgentParsedBase & ({
|
|
|
27
27
|
} | {
|
|
28
28
|
operation: "runs.respond";
|
|
29
29
|
input: AgentResponseInput;
|
|
30
|
+
} | {
|
|
31
|
+
operation: "runs.discard";
|
|
32
|
+
input: {
|
|
33
|
+
requestId: string;
|
|
34
|
+
};
|
|
30
35
|
} | {
|
|
31
36
|
operation: "runs.cancel";
|
|
32
37
|
input: AgentCancelInput;
|
|
@@ -37,7 +42,7 @@ export type AgentParsedRequest = AgentParsedBase & ({
|
|
|
37
42
|
operation: "attachments.write";
|
|
38
43
|
input: AgentAttachmentChunk;
|
|
39
44
|
} | {
|
|
40
|
-
operation: Exclude<AgentOperation, "sessions.create" | "sessions.configure" | "runs.start" | "runs.respond" | "runs.cancel" | "runs.control" | "attachments.write">;
|
|
45
|
+
operation: Exclude<AgentOperation, "sessions.create" | "sessions.configure" | "runs.start" | "runs.respond" | "runs.cancel" | "runs.discard" | "runs.control" | "attachments.write">;
|
|
41
46
|
input: undefined;
|
|
42
47
|
});
|
|
43
48
|
export declare function validateAgentMcpSelection(value: unknown): asserts value is AgentMcpSelection;
|
|
@@ -54,6 +59,7 @@ export declare function validateAgentRunControlInput(value: unknown): asserts va
|
|
|
54
59
|
export declare function validateAgentRequest(method: string, path: string, body: string | Uint8Array, expectedOperation?: AgentOperation): AgentParsedRequest;
|
|
55
60
|
export declare function agentReplayCursor(after?: string | null, lastEventId?: string | null): string | undefined;
|
|
56
61
|
export declare function validateAgentPendingDecision(value: unknown): asserts value is AgentPendingDecision;
|
|
62
|
+
export declare function validateAgentRunClosure(value: unknown): asserts value is import("./agent.js").AgentRunClosure;
|
|
57
63
|
export declare function validateAgentRunSnapshot(value: unknown): asserts value is AgentRunSnapshot;
|
|
58
64
|
export declare function validateAgentEvent(value: unknown): asserts value is AgentEvent;
|
|
59
65
|
export declare function validateAgentCapabilities(value: unknown): asserts value is AgentCapabilities;
|
package/dist/agent-server.js
CHANGED
|
@@ -254,7 +254,7 @@ export function validateAgentCancelInput(value) {
|
|
|
254
254
|
if (!opaque(value.fenceIfNotAdmitted.sessionId) || !digest(value.fenceIfNotAdmitted.startDigest) || value.expectedRevision !== undefined || value.expectedGeneration !== undefined)
|
|
255
255
|
fail("A delayed-start fence requires only the exact intended session/digest.");
|
|
256
256
|
}
|
|
257
|
-
else
|
|
257
|
+
else if (value.expectedRevision !== undefined || value.expectedGeneration !== undefined)
|
|
258
258
|
controlBase(value);
|
|
259
259
|
}
|
|
260
260
|
/** This validates an attestation's shape only. Providers must independently confirm actual native exit. */
|
|
@@ -286,7 +286,7 @@ export function validateAgentRequest(method, path, body, expectedOperation) {
|
|
|
286
286
|
const url = new URL(path, "http://agent.invalid"), route = url.pathname, query = {};
|
|
287
287
|
let operation, sessionId, runId, requestId, connectionId, attachmentId, chunkIndex;
|
|
288
288
|
const attachment = /^\/attachments\/([A-Za-z0-9_-]{1,256})\/chunks\/(0|[1-9][0-9]?)$/.exec(route);
|
|
289
|
-
const match = /^\/(sessions|runs|connections)(?:\/([A-Za-z0-9_-]{1,256}))?(?:\/(configurations|runs|events|responses|
|
|
289
|
+
const match = /^\/(sessions|runs|connections)(?:\/([A-Za-z0-9_-]{1,256}))?(?:\/(configurations|runs|events|closure|discard|responses|stop|controls|models|usage))?(?:\/([A-Za-z0-9_-]{1,256}))?$/.exec(route);
|
|
290
290
|
if (route === "/capabilities" && method === "GET")
|
|
291
291
|
operation = "capabilities";
|
|
292
292
|
else if (attachment && method === "PUT") {
|
|
@@ -319,11 +319,15 @@ export function validateAgentRequest(method, path, body, expectedOperation) {
|
|
|
319
319
|
runId = id;
|
|
320
320
|
if (!sub && method === "GET")
|
|
321
321
|
operation = "runs.read";
|
|
322
|
+
else if (sub === "closure" && !child && method === "GET")
|
|
323
|
+
operation = "runs.closure";
|
|
322
324
|
else if (sub === "events" && !child && method === "GET")
|
|
323
325
|
operation = "runs.events";
|
|
324
326
|
else if (sub === "responses" && !child && method === "POST")
|
|
325
327
|
operation = "runs.respond";
|
|
326
|
-
else if (sub === "
|
|
328
|
+
else if (sub === "discard" && !child && method === "PUT")
|
|
329
|
+
operation = "runs.discard";
|
|
330
|
+
else if (sub === "stop" && !child && method === "PUT")
|
|
327
331
|
operation = "runs.cancel";
|
|
328
332
|
else if (sub === "controls" && !child && method === "POST")
|
|
329
333
|
operation = "runs.control";
|
|
@@ -343,7 +347,7 @@ export function validateAgentRequest(method, path, body, expectedOperation) {
|
|
|
343
347
|
}
|
|
344
348
|
}
|
|
345
349
|
if (!operation || expectedOperation !== undefined && expectedOperation !== operation)
|
|
346
|
-
fail("Use a declared agent
|
|
350
|
+
fail("Use a declared agent v2 operation.", 422, "unsupported_operation");
|
|
347
351
|
const allowed = operation === "runs.events" ? ["after"] : ["sessions.list", "connections.list"].includes(operation) ? ["cursor", "limit"] : [];
|
|
348
352
|
for (const [key, value] of url.searchParams) {
|
|
349
353
|
if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1)
|
|
@@ -387,6 +391,11 @@ export function validateAgentRequest(method, path, body, expectedOperation) {
|
|
|
387
391
|
validateAgentRunInput(input);
|
|
388
392
|
else if (operation === "runs.respond")
|
|
389
393
|
validateAgentResponseInput(input);
|
|
394
|
+
else if (operation === "runs.discard") {
|
|
395
|
+
shape(input, ["requestId"], "delivery discard");
|
|
396
|
+
if (!uuid(input.requestId))
|
|
397
|
+
fail("A discard request UUID is required.");
|
|
398
|
+
}
|
|
390
399
|
else if (operation === "runs.cancel")
|
|
391
400
|
validateAgentCancelInput(input);
|
|
392
401
|
else if (operation === "runs.control")
|
|
@@ -443,6 +452,25 @@ export function validateAgentPendingDecision(value) {
|
|
|
443
452
|
}
|
|
444
453
|
}
|
|
445
454
|
}
|
|
455
|
+
export function validateAgentRunClosure(value) {
|
|
456
|
+
if (!object(value))
|
|
457
|
+
responseProblem("Missing execution closure.");
|
|
458
|
+
qualified(value.ref);
|
|
459
|
+
if (!opaque(value.sessionId) || !uuid(value.generation) || !decimal(value.revision, true) || typeof value.stopConfirmed !== "boolean"
|
|
460
|
+
|| value.writerScopeClosed !== undefined && (typeof value.writerScopeClosed !== "boolean" || value.writerScopeClosed && !value.stopConfirmed)
|
|
461
|
+
|| !["queued", "running", "waiting_for_input", "succeeded", "failed", "cancelled", "unknown"].includes(String(value.state))
|
|
462
|
+
|| !["preparing", "executing", "waiting", "finalizing", "cancelling", "parked", "interrupted", "terminal"].includes(String(value.phase))
|
|
463
|
+
|| ["succeeded", "failed", "cancelled"].includes(String(value.state)) && !value.stopConfirmed)
|
|
464
|
+
responseProblem("Invalid execution closure.");
|
|
465
|
+
if (value.pendingContinuations !== undefined) {
|
|
466
|
+
array(value.pendingContinuations, 256, "continuation references");
|
|
467
|
+
for (const item of value.pendingContinuations) {
|
|
468
|
+
if (!object(item) || !uuid(item.requestId) || !["pending", "awaiting_authorization", "admitted", "superseded"].includes(String(item.state)))
|
|
469
|
+
responseProblem("Invalid continuation receipt.");
|
|
470
|
+
qualified(item.run);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
446
474
|
export function validateAgentRunSnapshot(value) {
|
|
447
475
|
if (!object(value))
|
|
448
476
|
responseProblem("A run snapshot is required.");
|
|
@@ -450,7 +478,8 @@ export function validateAgentRunSnapshot(value) {
|
|
|
450
478
|
if (!opaque(value.sessionId) || !uuid(value.generation) || !decimal(value.revision, true) || !decimal(value.configurationRevision) || !decimal(value.lastSequence, true)
|
|
451
479
|
|| !["queued", "running", "waiting_for_input", "succeeded", "failed", "cancelled", "unknown"].includes(String(value.state))
|
|
452
480
|
|| !["preparing", "executing", "waiting", "finalizing", "cancelling", "parked", "interrupted", "terminal"].includes(String(value.phase))
|
|
453
|
-
|| typeof value.stopConfirmed !== "boolean"
|
|
481
|
+
|| typeof value.stopConfirmed !== "boolean"
|
|
482
|
+
|| value.writerScopeClosed !== undefined && (typeof value.writerScopeClosed !== "boolean" || value.writerScopeClosed && !value.stopConfirmed) || !["current", "last_known", "unavailable"].includes(String(value.freshness)) || !bounded(value.observedAt) || !Number.isFinite(Date.parse(value.observedAt)) || !bounded(value.cursor, 8192)
|
|
454
483
|
|| !Array.isArray(value.pending) || value.pending.length > 256 || !object(value.effects) || !["known", "unknown"].includes(String(value.effects.certainty)))
|
|
455
484
|
responseProblem("Invalid atomic run snapshot.");
|
|
456
485
|
for (const decision of value.pending)
|
|
@@ -572,7 +601,7 @@ export function validateAgentEvent(value) {
|
|
|
572
601
|
responseProblem("Event byte allowance exceeded.");
|
|
573
602
|
}
|
|
574
603
|
export function validateAgentCapabilities(value) {
|
|
575
|
-
if (!object(value) || value.version !==
|
|
604
|
+
if (!object(value) || value.version !== 2 || !Array.isArray(value.eventVersions) || !value.eventVersions.includes(AGENT_EVENT_VERSION) || !object(value.limits) || !object(value.configuration))
|
|
576
605
|
responseProblem("Unsupported agent contract.");
|
|
577
606
|
strings(value.capabilities, 128);
|
|
578
607
|
strings(value.configuration.resumeCompatible, 32);
|
package/dist/agent-sessions.d.ts
CHANGED
package/dist/agent.d.ts
CHANGED
|
@@ -46,7 +46,7 @@ export type AgentLimits = {
|
|
|
46
46
|
maxSkillSnapshotFiles?: number;
|
|
47
47
|
};
|
|
48
48
|
export type AgentCapabilities = {
|
|
49
|
-
version:
|
|
49
|
+
version: 2;
|
|
50
50
|
eventVersions: string[];
|
|
51
51
|
capabilities: AgentCapability[];
|
|
52
52
|
limits: AgentLimits;
|
|
@@ -308,7 +308,10 @@ export type AgentRunSnapshot = {
|
|
|
308
308
|
revision: Revision;
|
|
309
309
|
state: AgentRunState;
|
|
310
310
|
phase: AgentRunPhase;
|
|
311
|
+
/** The observed root agent has exited or was fenced before launch. */
|
|
311
312
|
stopConfirmed: boolean;
|
|
313
|
+
/** Whether a qualified writer scope has closed. Omitted when the provider has no such evidence. */
|
|
314
|
+
writerScopeClosed?: boolean;
|
|
312
315
|
freshness: "current" | "last_known" | "unavailable";
|
|
313
316
|
observedAt: string;
|
|
314
317
|
configurationRevision: Revision;
|
|
@@ -368,6 +371,12 @@ export type AgentRunSnapshot = {
|
|
|
368
371
|
state: "pending" | "awaiting_authorization" | "admitted" | "superseded";
|
|
369
372
|
}>;
|
|
370
373
|
};
|
|
374
|
+
export type AgentDiscardReceipt = {
|
|
375
|
+
requestId: string;
|
|
376
|
+
runId: string;
|
|
377
|
+
state: "discarded";
|
|
378
|
+
};
|
|
379
|
+
export type AgentRunClosure = Pick<AgentRunSnapshot, "ref" | "sessionId" | "generation" | "revision" | "state" | "phase" | "stopConfirmed" | "writerScopeClosed" | "pendingContinuations">;
|
|
371
380
|
export type AgentApprovalResponse = {
|
|
372
381
|
kind: "approval";
|
|
373
382
|
decision: "allow" | "deny";
|
|
@@ -388,6 +397,10 @@ export type AgentResponseInput = {
|
|
|
388
397
|
export type AgentCancelInput = {
|
|
389
398
|
requestId: string;
|
|
390
399
|
} & ({
|
|
400
|
+
expectedGeneration?: never;
|
|
401
|
+
expectedRevision?: never;
|
|
402
|
+
fenceIfNotAdmitted?: never;
|
|
403
|
+
} | {
|
|
391
404
|
expectedGeneration: string;
|
|
392
405
|
expectedRevision: Revision;
|
|
393
406
|
fenceIfNotAdmitted?: never;
|
|
@@ -503,7 +516,7 @@ export declare class AgentApiError extends Error {
|
|
|
503
516
|
readonly requestId?: string | undefined;
|
|
504
517
|
constructor(code: string, message: string, status: number, retryable?: boolean, details?: Record<string, unknown> | undefined, requestId?: string | undefined);
|
|
505
518
|
}
|
|
506
|
-
export type AgentOperation = "capabilities" | "connections.list" | "connections.models" | "connections.usage" | "attachments.write" | "sessions.create" | "sessions.configure" | "sessions.read" | "sessions.list" | "runs.start" | "runs.read" | "runs.events" | "runs.respond" | "runs.cancel" | "runs.control" | "runs.controls.read";
|
|
519
|
+
export type AgentOperation = "capabilities" | "connections.list" | "connections.models" | "connections.usage" | "attachments.write" | "sessions.create" | "sessions.configure" | "sessions.read" | "sessions.list" | "runs.start" | "runs.read" | "runs.closure" | "runs.discard" | "runs.events" | "runs.respond" | "runs.cancel" | "runs.control" | "runs.controls.read";
|
|
507
520
|
/** Core transport names for the optional consumer-bound task workflow, without general Core tools. */
|
|
508
521
|
export declare const AGENT_SESSION_WORKFLOW_TOOLS: readonly ["task_executor_options", "task_options", "task_list", "task_get", "task_create", "task_edit", "task_action", "task_result", "task_fail", "task_request_input", "task_adopt", "task_prepare_executor", "task_delegate", "task_wait", "task_plan", "task_bind_workspace", "task_execution_get"];
|
|
509
522
|
/** Optional business workflow owned by the invoking consumer, separate from native execution. */
|
|
@@ -46,7 +46,7 @@ export declare class ProviderClient {
|
|
|
46
46
|
timeoutMs?: number;
|
|
47
47
|
}): Promise<SpeechResult>;
|
|
48
48
|
textToSpeechCapabilities(provider: ProviderSelection, signal?: AbortSignal): Promise<TextToSpeechCapabilities>;
|
|
49
|
-
/** Stream 24 kHz mono
|
|
49
|
+
/** Stream 24 kHz mono PCM using a target resolved against the selected implementation, when provided. Cancel the signal or response body to stop. */
|
|
50
50
|
synthesize(provider: ProviderSelection, input: SpeechSynthesisRequest, signal?: AbortSignal): Promise<Response>;
|
|
51
51
|
translationCapabilities(provider: ProviderSelection, signal?: AbortSignal, options?: {
|
|
52
52
|
connection: {
|
package/dist/providers-server.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { Agent, fetch as speechFetch } from "undici";
|
|
3
3
|
import { AssistantClient } from "@hosty-sdk/app/assistant";
|
|
4
|
-
import { ProviderError } from "@hosty-sdk/app/providers";
|
|
4
|
+
import { normalizeLanguageTag, ProviderError } from "@hosty-sdk/app/providers";
|
|
5
5
|
/** Server-only provider client. Its app service token must never be sent to a browser or provider. */
|
|
6
6
|
export class ProviderClient {
|
|
7
7
|
appId;
|
|
@@ -111,16 +111,19 @@ export class ProviderClient {
|
|
|
111
111
|
return read(await fetch(`${binding.url}/capabilities`, { redirect: "error", signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
|
|
112
112
|
headers: { authorization: `Bearer ${binding.token}` } }));
|
|
113
113
|
}
|
|
114
|
-
/** Stream 24 kHz mono
|
|
114
|
+
/** Stream 24 kHz mono PCM using a target resolved against the selected implementation, when provided. Cancel the signal or response body to stop. */
|
|
115
115
|
async synthesize(provider, input, signal) {
|
|
116
116
|
if (typeof input.text !== "string" || !input.text.trim() || input.text.length > 4000)
|
|
117
117
|
throw new ProviderError("speech_text_invalid", "Provide between 1 and 4000 UTF-16 code units of text.", 400);
|
|
118
|
+
const targetLanguage = normalizeLanguageTag(input.targetLanguage)?.tag;
|
|
119
|
+
if (input.targetLanguage !== undefined && targetLanguage === undefined)
|
|
120
|
+
throw new ProviderError("speech_target_language_invalid", "Provide a valid target language tag.", 400);
|
|
118
121
|
const timeout = AbortSignal.timeout(300_000);
|
|
119
122
|
const deadline = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
120
123
|
const binding = await this.connect({ ...provider, kind: "text-to-speech" }, deadline);
|
|
121
124
|
const response = await fetch(`${binding.url}/speech`, { method: "POST", redirect: "error", signal: deadline,
|
|
122
125
|
headers: { authorization: `Bearer ${binding.token}`, "content-type": "application/json", accept: "audio/pcm" },
|
|
123
|
-
body: JSON.stringify({ text: input.text }) });
|
|
126
|
+
body: JSON.stringify({ text: input.text, targetLanguage }) });
|
|
124
127
|
if (!response.ok)
|
|
125
128
|
await read(response);
|
|
126
129
|
if (!response.body || !/^audio\/pcm\s*;\s*rate=24000\s*$/i.test(response.headers.get("content-type") ?? "")) {
|
package/dist/providers.d.ts
CHANGED
|
@@ -105,9 +105,17 @@ export type TextToSpeechCapabilities = {
|
|
|
105
105
|
maxCharacters: number;
|
|
106
106
|
backend: string;
|
|
107
107
|
ready: boolean;
|
|
108
|
+
supportsTranslation?: boolean;
|
|
109
|
+
/** When omitted by a translation-capable provider, there is no advertised language restriction. */
|
|
110
|
+
targetLanguages?: string[];
|
|
108
111
|
};
|
|
109
112
|
export type SpeechSynthesisRequest = {
|
|
110
113
|
text: string;
|
|
114
|
+
targetLanguage?: string;
|
|
115
|
+
};
|
|
116
|
+
export type SpeechLanguagePreferences = {
|
|
117
|
+
preferredLanguage?: string | null;
|
|
118
|
+
autoTranslateReadAloud?: boolean;
|
|
111
119
|
};
|
|
112
120
|
export type TranslationRequest = {
|
|
113
121
|
text: string;
|
|
@@ -138,6 +146,13 @@ export declare class ProviderError extends Error {
|
|
|
138
146
|
readonly status: number;
|
|
139
147
|
constructor(code: string, message: string, status: number);
|
|
140
148
|
}
|
|
149
|
+
/** @internal Shared language-tag validation for provider client and transport. */
|
|
150
|
+
export declare function normalizeLanguageTag(value: unknown): {
|
|
151
|
+
tag: string;
|
|
152
|
+
withoutRegion: string;
|
|
153
|
+
} | undefined;
|
|
154
|
+
/** Resolve the language once for playback using the selected implementation's capabilities. */
|
|
155
|
+
export declare function resolveSpeechTargetLanguage(requested: string | undefined, preferences: SpeechLanguagePreferences | undefined, capabilities: Pick<TextToSpeechCapabilities, "supportsTranslation" | "targetLanguages">): string | undefined;
|
|
141
156
|
/** Non-secret receipt reference. Only its reviewed source and executor installations can use it. */
|
|
142
157
|
export type TaskDispatchRef = {
|
|
143
158
|
userId: string;
|
package/dist/providers.js
CHANGED
|
@@ -8,3 +8,46 @@ export class ProviderError extends Error {
|
|
|
8
8
|
this.status = status;
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
|
+
// Keep the language-tag grammar and casing aligned with the .NET SDK's LanguageTag.cs.
|
|
12
|
+
const languageTag = /^([a-z]{2,3}(?:-[a-z]{3}){0,3}|[a-z]{4,8})(-[a-z]{4})?(-(?:[a-z]{2}|[0-9]{3}))?((?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)((?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)(-x(?:-[a-z0-9]{1,8})+)?$/;
|
|
13
|
+
/** @internal Shared language-tag validation for provider client and transport. */
|
|
14
|
+
export function normalizeLanguageTag(value) {
|
|
15
|
+
if (typeof value !== "string")
|
|
16
|
+
return undefined;
|
|
17
|
+
// Match .NET's Unicode whitespace trimming, which retains a BOM for validation to reject.
|
|
18
|
+
const tag = value.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, "");
|
|
19
|
+
if (tag.length > 63 || !/^[A-Za-z0-9-]+$/.test(tag))
|
|
20
|
+
return undefined;
|
|
21
|
+
const match = languageTag.exec(tag.toLowerCase());
|
|
22
|
+
if (!match)
|
|
23
|
+
return undefined;
|
|
24
|
+
const [, language = "", script = "", region = "", variants = "", extensions = "", privateUse = ""] = match;
|
|
25
|
+
const variantTags = variants.split("-").slice(1);
|
|
26
|
+
const extensionKeys = extensions.split("-").filter(part => part.length === 1);
|
|
27
|
+
if (new Set(variantTags).size !== variantTags.length || new Set(extensionKeys).size !== extensionKeys.length)
|
|
28
|
+
return undefined;
|
|
29
|
+
const prefix = script ? language + "-" + script[1].toUpperCase() + script.slice(2) : language;
|
|
30
|
+
const suffix = variants + extensions + privateUse;
|
|
31
|
+
return { tag: prefix + region.toUpperCase() + suffix, withoutRegion: prefix + suffix };
|
|
32
|
+
}
|
|
33
|
+
/** Resolve the language once for playback using the selected implementation's capabilities. */
|
|
34
|
+
export function resolveSpeechTargetLanguage(requested, preferences, capabilities) {
|
|
35
|
+
const explicit = requested !== undefined;
|
|
36
|
+
const preferred = preferences?.autoTranslateReadAloud === true ? preferences.preferredLanguage : undefined;
|
|
37
|
+
const language = normalizeLanguageTag(explicit ? requested : preferred);
|
|
38
|
+
if (!language) {
|
|
39
|
+
if (explicit)
|
|
40
|
+
throw new ProviderError("speech_target_language_invalid", "Provide a valid target language tag.", 400);
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
const targets = capabilities.targetLanguages;
|
|
44
|
+
if (capabilities.supportsTranslation === true && (targets == null ||
|
|
45
|
+
Array.isArray(targets) && targets.some(target => {
|
|
46
|
+
const advertised = normalizeLanguageTag(target)?.tag;
|
|
47
|
+
return advertised === language.tag || advertised === language.withoutRegion;
|
|
48
|
+
})))
|
|
49
|
+
return language.tag;
|
|
50
|
+
if (explicit)
|
|
51
|
+
throw new ProviderError("speech_target_language_unsupported", "The selected speech provider does not support this target language.", 400);
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
package/package.json
CHANGED