diff --git a/apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts index 30304449c0f0..15910cf1f527 100644 --- a/apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts @@ -29,6 +29,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; import * as TestClock from "effect/testing/TestClock"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import type * as EffectAcpSchema from "effect-acp/compat"; @@ -57,8 +58,10 @@ import { KIRO_PROVIDER, kiroApprovalOptions, kiroAutopilotValue, + type KiroSkills, kiroPermissionDisposition, makeKiroAdapterV2, + makeKiroSkills, } from "@t3tools/provider-kiro/testing"; const testLayer = Layer.mergeAll( @@ -307,6 +310,14 @@ const runKiroScript = Effect.fn("runKiroScript")(function* (input: { readonly wrapCancel?: ( send: AcpSessionRuntime.AcpSessionRuntime["Service"]["cancel"], ) => AcpSessionRuntime.AcpSessionRuntime["Service"]["cancel"]; + /** Wraps the runtime's `session/prompt` send. */ + readonly wrapPrompt?: ( + send: AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"], + ) => AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"]; + /** The user's message text for every turn. */ + readonly text?: string; + /** Where the adapter records advertised skills. */ + readonly skills?: KiroSkills; readonly drive: (session: { readonly events: Stream.Stream; readonly startTurn: Effect.Effect; @@ -360,13 +371,14 @@ const runKiroScript = Effect.fn("runKiroScript")(function* (input: { fileSystem, ...(input.replayGate === undefined ? {} : { replayGate: input.replayGate }), })(runtimeInput).pipe( - Effect.map((runtime) => - input.wrapCancel === undefined - ? runtime - : { ...runtime, cancel: input.wrapCancel(runtime.cancel) }, - ), + Effect.map((runtime) => ({ + ...runtime, + ...(input.wrapCancel === undefined ? {} : { cancel: input.wrapCancel(runtime.cancel) }), + ...(input.wrapPrompt === undefined ? {} : { prompt: input.wrapPrompt(runtime.prompt) }), + })), ), ...(input.testHooks === undefined ? {} : { testHooks: input.testHooks }), + ...(input.skills === undefined ? {} : { skills: input.skills }), }); // Held frames must not outlive a failed drive and wedge teardown. yield* Effect.addFinalizer(() => Effect.sync(() => input.replayGate?.releaseAll())); @@ -428,7 +440,7 @@ const runKiroScript = Effect.fn("runKiroScript")(function* (input: { createdBy: "user", creationSource: "web", messageId: MessageId.make(`message:${suffix}`), - text: "Say hello", + text: input.text ?? "Say hello", attachments: [], }, modelSelection: turnSelection, @@ -831,6 +843,73 @@ describe("KiroAdapterV2", () => { ); }); +describe("KiroAdapterV2 skills", () => { + const userSkill = (name: string) => ({ + name, + description: "A probe skill that checks skill discovery over ACP.", + input: { hint: "optional context" }, + _meta: { + kiro: { + type: "skill", + resource: { resourceType: "skill", source: { origin: "user" } }, + originalName: name, + }, + }, + }); + // Shaped like kiro-cli 2.37.1's second `available_commands_update` after + // `session/new` with `~/.kiro/skills/probe-skill/SKILL.md` installed. + const skillCommands = update({ + sessionUpdate: "available_commands_update", + availableCommands: [userSkill("probe-skill")], + }); + + const recordPrompts = (sent: Array) => + ((send) => (payload, options) => { + for (const block of payload.prompt) { + if (block.type === "text") sent.push(block.text); + } + return send(payload, options); + }) satisfies NonNullable[0]["wrapPrompt"]>; + + // The store holds the session's updates in order, so seeing `name` means every earlier one landed. + const awaitSkill = (skills: KiroSkills, name: string) => + SubscriptionRef.changes(skills).pipe( + Stream.takeUntil((current) => current.some((skill) => skill.name === name)), + Stream.runDrain, + ); + + // Kiro runs a command only from a leading `/name`; T3's `$` picker inserts `$name`. + it.effect("sends a $ skill mention as the /command Kiro runs", () => + Effect.gen(function* () { + const sent: Array = []; + const skills = yield* makeKiroSkills(); + yield* runKiroScript({ + scenario: "skill-mention", + text: "$probe-skill rest", + skills, + frames: [ + ...openSessionFrames({ + initialize: KIRO_V3_INITIALIZE, + configOptions: [modeOption, autopilotOption("on")], + }), + skillCommands, + turnPrompt, + answer("session/prompt", { stopReason: "end_turn" }), + ...closeSession, + ], + wrapPrompt: recordPrompts(sent), + drive: ({ events, startTurn }) => + Effect.gen(function* () { + yield* awaitSkill(skills, "probe-skill"); + yield* startTurn; + assert.equal(terminalStatus(yield* collectTurn(events)), "completed"); + assert.deepEqual(sent, ["/probe-skill rest"]); + }), + }); + }).pipe(Effect.provide(testLayer), Effect.scoped), + ); +}); + describe("KiroAdapterV2 agents", () => { // A user agent from `~/.kiro/agents` whose config sets `"model": "claude-sonnet-4.5"`. const agentModeOption = (currentValue: string) => ({ diff --git a/apps/server/src/provider/KiroProvider.test.ts b/apps/server/src/provider/KiroProvider.test.ts index 1877c131e315..a9e41ea934ce 100644 --- a/apps/server/src/provider/KiroProvider.test.ts +++ b/apps/server/src/provider/KiroProvider.test.ts @@ -1,12 +1,30 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; +import { + MessageId, + NodeId, + ProjectId, + ProviderInstanceId, + ProviderSessionId, + RunAttemptId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import { ProviderAdapterV2RuntimePolicy } from "@t3tools/provider-core/server/ProviderAdapter"; +import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import { KiroDriver } from "@t3tools/provider-kiro/server"; import { KiroSettings } from "@t3tools/provider-kiro/settings"; +import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import type * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; @@ -58,12 +76,15 @@ const decodeRequest = Schema.decodeUnknownSync( Schema.Struct({ id: Schema.Union([Schema.String, Schema.Number]), method: Schema.String }), ), ); +const KIRO_SESSION_ID = "sess_kiro-skills"; /** * A `kiro-cli acp` that answers `initialize` and `_kiro/config/template` and - * fails anything else, so a probe that opened a session would fail. + * fails anything else, so a probe that opened a session would fail. Given + * `afterSessionNew`, it also opens sessions, sends those updates right after + * `session/new`, and answers each prompt with one line of text. */ -const acpProcess = (template: unknown) => +const acpProcess = (template: unknown, afterSessionNew?: ReadonlyArray) => Effect.gen(function* () { const output = yield* Queue.unbounded(); const exited = yield* Deferred.make(); @@ -71,34 +92,53 @@ const acpProcess = (template: unknown) => Effect.andThen(Queue.shutdown(output)), Effect.asVoid, ); - const reply = (line: string) => { + let pending = ""; + const send = (message: object) => + Queue.offer(output, encoder.encode(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`)); + const sessionUpdate = (update: unknown) => + send({ + method: "session/update", + params: { sessionId: KIRO_SESSION_ID, update }, + }); + const reply = Effect.fnUntraced(function* (line: string) { const request = decodeRequest(line); + const sessions = afterSessionNew !== undefined; + if (sessions && request.method === "session/new") { + yield* send({ id: request.id, result: { sessionId: KIRO_SESSION_ID } }); + yield* Effect.forEach(afterSessionNew, sessionUpdate); + return; + } + if (sessions && request.method === "session/prompt") { + yield* sessionUpdate({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "ok" }, + }); + yield* send({ id: request.id, result: { stopReason: "end_turn" } }); + return; + } const response = request.method === "initialize" ? { result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } } : request.method === "_kiro/config/template" ? { result: template } : { error: { code: -32601, message: `${request.method} is not scripted` } }; - return Queue.offer( - output, - encoder.encode(`${JSON.stringify({ jsonrpc: "2.0", id: request.id, ...response })}\n`), - ); - }; + yield* send({ id: request.id, ...response }); + }); return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(900_000_003), exitCode: Deferred.await(exited), isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)), kill: () => terminate, unref: Effect.succeed(Effect.void), - stdin: Sink.forEach((bytes: Uint8Array) => - Effect.forEach( - new TextDecoder() - .decode(bytes) - .split("\n") - .filter((line) => line.trim().length > 0), + stdin: Sink.forEach((bytes: Uint8Array) => { + // A prompt can arrive split across writes. + const lines = (pending + new TextDecoder().decode(bytes)).split("\n"); + pending = lines.pop() ?? ""; + return Effect.forEach( + lines.filter((line) => line.trim().length > 0), reply, - ), - ), + ); + }), stdout: Stream.fromQueue(output), stderr: Stream.empty, all: Stream.empty, @@ -108,13 +148,17 @@ const acpProcess = (template: unknown) => }); /** Answers `kiro-cli` invocations by their arguments and records which ran. */ -function kiroCli(outputs: Record, template?: unknown) { +function kiroCli( + outputs: Record, + template?: unknown, + afterSessionNew?: ReadonlyArray, +) { const invoked: Array = []; const spawner = ChildProcessSpawner.make((command) => { const args = ChildProcess.isStandardCommand(command) ? command.args.join(" ") : ""; invoked.push(args); - return args === KIRO_ACP_ARGS && template !== undefined - ? acpProcess(template) + return args === KIRO_ACP_ARGS && (template !== undefined || afterSessionNew !== undefined) + ? acpProcess(template, afterSessionNew) : Effect.succeed(processHandle(outputs[args] ?? { stdout: "", code: 127 })); }); return { invoked, spawner }; @@ -484,4 +528,144 @@ describe("KiroProvider", () => { ); }), ); + + // Shaped like kiro-cli 2.37.1's second `available_commands_update` after + // `session/new` with `~/.kiro/skills/probe-skill/SKILL.md` installed. + it.effect("lists the skills a Kiro session advertises", () => + Effect.gen(function* () { + const cli = kiroCli( + { + "--version": { stdout: "kiro-cli 2.37.1\n", code: 0 }, + "whoami --format json": { stdout: "", code: 2 }, + }, + undefined, + [ + { + sessionUpdate: "available_commands_update", + availableCommands: [ + { + name: "probe-skill", + description: "A probe skill that checks skill discovery over ACP.", + input: { hint: "optional context" }, + _meta: { + kiro: { + type: "skill", + resource: { resourceType: "skill", source: { origin: "user" } }, + originalName: "probe-skill", + }, + }, + }, + ], + }, + ], + ); + yield* Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("kiro"); + const instance = yield* KiroDriver.create({ + instanceId, + displayName: "Kiro", + accentColor: undefined, + enabled: true, + environment: [], + config: settings, + }); + // Subscribed before the session opens, so the publish cannot slip past it. + const advertised = yield* instance.snapshot.streamChanges.pipe( + Stream.takeUntil((snapshot) => + snapshot.skills.some(({ name }) => name === "probe-skill"), + ), + Stream.runLast, + Effect.forkChild({ startImmediately: true }), + ); + const threadId = ThreadId.make("thread-kiro-skills"); + const modelSelection = { instanceId, model: "default" }; + const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", + }); + const session = yield* instance.orchestrationAdapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-kiro-skills"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-kiro-skills"), + title: "Kiro skills", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: runtimePolicy.runtimeMode, + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-kiro-skills"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-kiro-skills"), + rootNodeId: NodeId.make("node-kiro-skills"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-kiro-skills"), + text: "Say hello", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + const snapshot = yield* Fiber.join(advertised); + assert.deepEqual( + Option.map(snapshot, ({ skills }) => + skills.map((skill) => ({ name: skill.name, enabled: skill.enabled })), + ), + Option.some([{ name: "probe-skill", enabled: true }]), + ); + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, cli.spawner), + Effect.scoped, + ); + }).pipe( + Effect.provide( + TestProviderHost.layer().pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + Layer.provideMerge(IdAllocator.layer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provideMerge( + Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ), + ), + ), + ), + ); }); diff --git a/docs/user/providers-kiro.md b/docs/user/providers-kiro.md index 6b94ca14f2e5..dab61d925d8c 100644 --- a/docs/user/providers-kiro.md +++ b/docs/user/providers-kiro.md @@ -38,6 +38,14 @@ not listed yet. Refresh the Kiro provider after adding or removing an agent. The thread's model still applies when an agent sets its own `model`. An agent that was removed leaves the thread on Kiro's current agent. +## Skills + +Your Kiro skills in `~/.kiro/skills` appear in the `/` and `$` menus once a Kiro session has started +on this server, for example after the first message in a Kiro thread. Skills in a project's +`.kiro/skills` are not listed in the menus. Kiro runs a skill only when it starts the message, so +put the skill first. A skill you add later appears after a Kiro session reports it, and one you +remove stays listed until the server restarts. + ## Permission Modes Kiro asks before tool calls such as writes and commands, and T3 Code answers by the permission mode: diff --git a/packages/provider-kiro/src/server/adapter.ts b/packages/provider-kiro/src/server/adapter.ts index 6815b60e8f22..ee5f92b2c11c 100644 --- a/packages/provider-kiro/src/server/adapter.ts +++ b/packages/provider-kiro/src/server/adapter.ts @@ -50,6 +50,12 @@ import { kiroPermissionDisposition, makeKiroAcpRuntime, } from "./acpSupport.ts"; +import { + type KiroSkills, + kiroSkillCommandText, + makeKiroSkills, + recordKiroSkills, +} from "./skills.ts"; export const KIRO_PROVIDER = ProviderDriverKind.make("kiro"); /** T3's slug for "Kiro default", and Kiro's documented default model id. */ @@ -193,6 +199,8 @@ export interface KiroAdapterV2Options { * default). Absent, it is `auto`. */ readonly defaultModel?: Effect.Effect; + /** Where the adapter records the skills Kiro sessions advertise; the driver publishes them. */ + readonly skills?: KiroSkills; /** Replaces the `kiro-cli` launch (replay tests). Kiro's session setup still applies. */ readonly makeRuntime?: ( input: AcpAdapterV2RuntimeInput, @@ -523,7 +531,10 @@ function kiroPromptFailure(cause: unknown) { }); } -function makeKiroAcpAdapterFlavor(options: KiroAdapterV2Options): AcpAdapterV2Flavor { +function makeKiroAcpAdapterFlavor( + options: KiroAdapterV2Options, + skills: KiroSkills, +): AcpAdapterV2Flavor { const makeRuntime = options.makeRuntime ?? ((input: AcpAdapterV2RuntimeInput) => { @@ -549,6 +560,8 @@ function makeKiroAcpAdapterFlavor(options: KiroAdapterV2Options): AcpAdapterV2Fl normalizeSessionUpdate: (notification) => stripSteeringNote(normalizeKiroSessionUpdate(notification)), extractSubagentUpdate: extractKiroSubagentUpdate, + onAvailableCommandsUpdate: (commands) => recordKiroSkills(skills, commands), + rewriteUserText: (text) => kiroSkillCommandText(skills, text), // See applyKiroModelSelection: `model` arrives after session/new. modelOptionArrivesLate: true, applyModelSelection: applyKiroModelSelection( @@ -581,7 +594,7 @@ export const makeKiroAdapterV2 = Effect.fn("makeKiroAdapterV2")(function* ( ) { return yield* makeAcpAdapterV2({ instanceId: options.instanceId, - flavor: makeKiroAcpAdapterFlavor(options), + flavor: makeKiroAcpAdapterFlavor(options, options.skills ?? (yield* makeKiroSkills())), selfInvocation: options.selfInvocation, ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }), ...(options.testHooks === undefined ? {} : { testHooks: options.testHooks }), @@ -601,6 +614,7 @@ export type KiroAdapterV2DriverEnv = /** `defaultModel` reads Kiro's id for "Kiro default" from the provider snapshot. */ export const makeKiroAdapterV2Driver = ( defaultModel: Effect.Effect, + skills: KiroSkills, ): ProviderAdapterDriver => ({ driverKind: KIRO_PROVIDER, configSchema: KiroSettings, @@ -617,6 +631,7 @@ export const makeKiroAdapterV2Driver = ( environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment), selfInvocation, defaultModel, + skills, nativeLogging: (threadId) => makeNativeLogger({ nativeEventLogger: providerEventLoggers.native, diff --git a/packages/provider-kiro/src/server/driver.ts b/packages/provider-kiro/src/server/driver.ts index c62bf3ddd7b3..14ec48bb3940 100644 --- a/packages/provider-kiro/src/server/driver.ts +++ b/packages/provider-kiro/src/server/driver.ts @@ -4,6 +4,8 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; @@ -29,6 +31,7 @@ import { checkKiroProviderStatus, kiroDefaultModelId, } from "./status.ts"; +import { makeKiroSkills } from "./skills.ts"; const DRIVER_KIND = ProviderDriverKind.make("kiro"); const decodeKiroSettings = Schema.decodeSync(KiroSettings); @@ -98,6 +101,8 @@ export const KiroDriver: ProviderDriver = { }); const effectiveConfig = { ...config, enabled } satisfies KiroSettings; const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); + // Kiro lists skills only to a running session, so status checks keep what sessions advertised. + const skills = yield* makeKiroSkills(); const snapshot = yield* makeManagedServerProvider>({ resolveMaintenance: () => Effect.succeed(MAINTENANCE), getSettings: snapshotSettings.getSettings, @@ -107,9 +112,22 @@ export const KiroDriver: ProviderDriver = { buildInitialKiroProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)), checkProvider: checkKiroProviderStatus(effectiveConfig, processEnv).pipe( Effect.map(stampIdentity), + Effect.flatMap((checked) => + SubscriptionRef.get(skills).pipe( + Effect.map((current) => ({ ...checked, skills: current })), + ), + ), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(SecureRandom.SecureRandom, crypto), ), + enrichSnapshot: ({ getSnapshot, publishSnapshot }) => + SubscriptionRef.changes(skills).pipe( + Stream.runForEach((current) => + getSnapshot.pipe( + Effect.flatMap((snapshot) => publishSnapshot({ ...snapshot, skills: current })), + ), + ), + ), }).pipe( Effect.mapError( (cause) => @@ -126,6 +144,7 @@ export const KiroDriver: ProviderDriver = { // "Kiro default" selects the default the snapshot read from Kiro's model list. const orchestrationAdapter = yield* makeKiroAdapterV2Driver( snapshot.getSnapshot.pipe(Effect.map((current) => kiroDefaultModelId(current.models))), + skills, ) .create({ instanceId, displayName, accentColor, environment, enabled, config }) .pipe( diff --git a/packages/provider-kiro/src/server/skills.test.ts b/packages/provider-kiro/src/server/skills.test.ts new file mode 100644 index 000000000000..99f590c7c215 --- /dev/null +++ b/packages/provider-kiro/src/server/skills.test.ts @@ -0,0 +1,84 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import { kiroSkillCommandText, makeKiroSkills, recordKiroSkills } from "./skills.ts"; + +const skill = (name: string, source?: { readonly origin: string; readonly root?: string }) => ({ + name, + description: `${name} skill`, + _meta: { + kiro: { + type: "skill", + ...(source === undefined ? {} : { resource: { resourceType: "skill", source } }), + }, + }, +}); +const agent = (name: string) => ({ + name, + description: "", + _meta: { kiro: { type: "custom-agent" } }, +}); + +describe("recordKiroSkills", () => { + it.effect("keeps only skill commands, once each", () => + Effect.gen(function* () { + const skills = yield* makeKiroSkills(); + yield* recordKiroSkills(skills, [ + skill("deploy"), + skill("Deploy"), + agent("reviewer"), + { name: "compact", description: "Compact the conversation" }, + ]); + assert.deepEqual( + (yield* SubscriptionRef.get(skills)).map(({ name, path }) => ({ name, path })), + [{ name: "deploy", path: "acp://skill/deploy" }], + ); + }), + ); + + // Shaped like kiro-cli 3.0.0, which lists `/.kiro/skills` beside `~/.kiro/skills`. + it.effect("leaves out skills Kiro scopes to a workspace", () => + Effect.gen(function* () { + const skills = yield* makeKiroSkills(); + yield* recordKiroSkills(skills, [ + skill("project-skill", { origin: "workspace", root: "/abs/project/path" }), + skill("user-skill", { origin: "user" }), + ]); + assert.deepEqual( + (yield* SubscriptionRef.get(skills)).map(({ name }) => name), + ["user-skill"], + ); + assert.equal(yield* kiroSkillCommandText(skills, "$project-skill x"), "$project-skill x"); + assert.equal(yield* kiroSkillCommandText(skills, "$user-skill x"), "/user-skill x"); + }), + ); + + it.effect("keeps skills from earlier sessions and updates without skills", () => + Effect.gen(function* () { + const skills = yield* makeKiroSkills(); + yield* recordKiroSkills(skills, [skill("deploy-a")]); + yield* recordKiroSkills(skills, [skill("deploy-b")]); + const merged = yield* SubscriptionRef.get(skills); + yield* recordKiroSkills(skills, [agent("reviewer")]); + assert.strictEqual(yield* SubscriptionRef.get(skills), merged); + assert.deepEqual( + merged.map(({ name }) => name), + ["deploy-a", "deploy-b"], + ); + }), + ); +}); + +describe("kiroSkillCommandText", () => { + it.effect("rewrites only a leading mention of an advertised skill", () => + Effect.gen(function* () { + const skills = yield* makeKiroSkills(); + yield* recordKiroSkills(skills, [skill("deploy")]); + assert.equal(yield* kiroSkillCommandText(skills, " $deploy now"), "/deploy now"); + assert.equal(yield* kiroSkillCommandText(skills, "$deployer now"), "$deployer now"); + assert.equal(yield* kiroSkillCommandText(skills, "$25 please"), "$25 please"); + assert.equal(yield* kiroSkillCommandText(skills, "run $deploy"), "run $deploy"); + }), + ); +}); diff --git a/packages/provider-kiro/src/server/skills.ts b/packages/provider-kiro/src/server/skills.ts new file mode 100644 index 000000000000..e17222f8e304 --- /dev/null +++ b/packages/provider-kiro/src/server/skills.ts @@ -0,0 +1,120 @@ +import type { ServerProviderSkill } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import type * as EffectAcpSchema from "effect-acp/compat"; + +const MAX_SKILLS = 128; +const MAX_NAME_LENGTH = 128; +const MAX_DESCRIPTION_LENGTH = 1_024; +// Anchored and unambiguous (`\s*` then a literal `$`), so it scans the text once. +const LEADING_MENTION = /^\s*\$(\S+)/; + +/** + * Every global skill the instance's Kiro sessions have advertised since the + * server started. Kiro reports them only as `available_commands_update` entries + * with `_meta.kiro.type: "skill"`, and some updates carry none. + */ +export type KiroSkills = SubscriptionRef.SubscriptionRef>; + +export const makeKiroSkills = (): Effect.Effect => + SubscriptionRef.make>([]); + +const decodeKiroSkillMeta = Schema.decodeUnknownOption( + Schema.Struct({ + kiro: Schema.Struct({ + type: Schema.Literal("skill"), + resource: Schema.optional( + Schema.Struct({ + source: Schema.optional( + Schema.Struct({ + origin: Schema.optional(Schema.Unknown), + root: Schema.optional(Schema.Unknown), + }), + ), + }), + ), + }), + }), +); + +// The store is shared by every project, so a skill Kiro scopes to one workspace stays out. +const isKiroGlobalSkill = (meta: unknown) => + Option.match(decodeKiroSkillMeta(meta), { + onNone: () => false, + onSome: ({ kiro }) => { + const source = kiro.resource?.source; + return source?.origin !== "workspace" && source?.root === undefined; + }, + }); + +function kiroSkillsFromCommands( + commands: ReadonlyArray, +): ReadonlyArray { + const seen = new Set(); + const skills: Array = []; + for (const command of commands) { + if (skills.length === MAX_SKILLS) break; + if (!isKiroGlobalSkill(command._meta)) continue; + const { name } = command; + if (name.length === 0 || name.length > MAX_NAME_LENGTH || name !== name.trim()) continue; + const key = name.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + const description = command.description.trim().slice(0, MAX_DESCRIPTION_LENGTH); + skills.push({ + name, + ...(description ? { description } : {}), + path: `acp://skill/${encodeURIComponent(name)}`, + scope: "agent", + enabled: true, + }); + } + return skills; +} + +function mergeKiroSkills( + current: ReadonlyArray, + incoming: ReadonlyArray, +): Option.Option> { + let merged: Array | undefined; + for (const skill of incoming) { + const list = merged ?? current; + const key = skill.name.toLowerCase(); + const index = list.findIndex((existing) => existing.name.toLowerCase() === key); + const existing = list[index]; + if (existing === undefined && list.length === MAX_SKILLS) continue; + if (existing?.name === skill.name && existing.description === skill.description) continue; + merged ??= [...current]; + if (existing === undefined) merged.push(skill); + else merged[index] = skill; + } + return Option.fromUndefinedOr(merged); +} + +/** Adds an update's skills, replacing same-named ones in place; publishes only on a change. */ +export const recordKiroSkills = ( + skills: KiroSkills, + commands: ReadonlyArray, +): Effect.Effect => + SubscriptionRef.updateSome(skills, (current) => + mergeKiroSkills(current, kiroSkillsFromCommands(commands)), + ); + +/** + * Kiro runs a command only from a leading `/name`, while T3's `$` picker + * inserts `$name`. Only advertised skills are rewritten, so `$25` stays text. + */ +export const kiroSkillCommandText = (skills: KiroSkills, text: string): Effect.Effect => { + const match = LEADING_MENTION.exec(text); + const name = match?.[1]; + if (match === null || name === undefined) return Effect.succeed(text); + return SubscriptionRef.get(skills).pipe( + Effect.map((current) => + current.some((skill) => skill.name === name) + ? `/${name}${text.slice(match[0].length)}` + : text, + ), + ); +}; diff --git a/packages/provider-kiro/src/testing.ts b/packages/provider-kiro/src/testing.ts index 3f18a713ad8c..1eced470f298 100644 --- a/packages/provider-kiro/src/testing.ts +++ b/packages/provider-kiro/src/testing.ts @@ -5,6 +5,7 @@ export { kiroPermissionDisposition, makeKiroAcpRuntime, } from "./server/acpSupport.ts"; +export { type KiroSkills, makeKiroSkills } from "./server/skills.ts"; export { checkKiroProviderStatus, kiroAgentDescriptor,