sailfork / t3code-github / packages/ provider-kiro/ src/ server/ acpSupport.ts

import type * as EffectAcpSchema from "effect-acp/compat";
import type { ProviderApprovalOption, RuntimeMode } from "@t3tools/contracts";
import type { KiroSettings } from "../settings.ts";
import type * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type * as Scope from "effect/Scope";
import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import type * as EffectAcpErrors from "effect-acp/errors";

import {
  acpPermissionDisposition,
  type AcpPermissionDisposition,
  type AcpRuntimePolicy,
} from "@t3tools/provider-acp/server/clientPolicy";
import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";

/**
 * Kiro's default engine is a v2 server this driver does not speak, so V3 is
 * requested. `--auth-method=cli` keeps access tokens inside Kiro. V3 rejects the
 * v2 launch flags; mode and model are set per session with `session/set_config_option`.
 */
const KIRO_ACP_ARGS = ["acp", "--agent-engine=v3", "--auth-method=cli"] as const;

/**
 * Kiro's `autopilot` session option. Off (Supervised), Kiro also asks the user
 * to review a turn's file changes before it ends. Sessions start "on", so T3
 * sets it from the thread's runtime mode.
 */
export const KIRO_AUTOPILOT_CONFIG_ID = "autopilot";

/** Kiro's model session option (`configId: "model"` in the V3 migration guide). */
export const KIRO_MODEL_CONFIG_ID = "model";

/**
 * Kiro's reasoning effort session option (`configId: "effortLevel"` in the V3
 * migration guide). Kiro advertises it only while a model with effort runs.
 */
export const KIRO_EFFORT_CONFIG_ID = "effortLevel";

/**
 * Kiro's agent session option. Kiro V3 offers its agents (the bundled ones,
 * `~/.kiro/agents`, and the workspace's `.kiro/agents`) as the choices of its
 * `mode` select, and the thread's choice is stored under the same id.
 */
export const KIRO_AGENT_CONFIG_ID = "mode";

/**
 * Kiro offers two permission postures, Supervised and Autopilot, which T3's
 * Supervised and Full access select. Any other mode runs Supervised.
 */
export const KIRO_SUPPORTED_RUNTIME_MODES = [
  "approval-required",
  "full-access",
] as const satisfies ReadonlyArray<RuntimeMode>;

/**
 * Autopilot is on only for an unrestricted Full access thread. An explicit
 * approval or sandbox override keeps Kiro Supervised, so its end-of-turn
 * review still reaches the user and every tool prompt reaches T3's policy
 * check (the same rule as Grok's `grokLaunchRuntimeMode`).
 */
export function kiroAutopilotValue(policy: {
  readonly runtimeMode: RuntimeMode;
  readonly approvalPolicy?: unknown;
  readonly sandboxPolicy?: unknown;
}): "on" | "off" {
  return policy.runtimeMode === "full-access" &&
    policy.approvalPolicy === undefined &&
    policy.sandboxPolicy === undefined
    ? "on"
    : "off";
}

type KiroAcpRuntimeSettings = Pick<KiroSettings, "binaryPath">;

export function buildKiroAcpSpawnInput(
  settings: KiroAcpRuntimeSettings | null | undefined,
  cwd: string,
  environment?: NodeJS.ProcessEnv,
): AcpSessionRuntime.AcpSpawnInput {
  return {
    command: settings?.binaryPath || "kiro-cli",
    args: [...KIRO_ACP_ARGS],
    cwd,
    ...(environment === undefined ? {} : { env: environment }),
  };
}

/**
 * Approval choices a Kiro permission request can honor; V3's options are
 * authoritative. Its `allow_always` saves a consent rule for the workspace or
 * wider, so it is offered, as "Always allow", only without a one-time choice.
 */
export function kiroApprovalOptions(
  request: EffectAcpSchema.RequestPermissionRequest,
): ReadonlyArray<ProviderApprovalOption> {
  const has = (kind: EffectAcpSchema.PermissionOption["kind"]) =>
    request.options.some((option) => option.kind === kind && option.optionId.trim().length > 0);
  return [
    ...(has("allow_once")
      ? [{ decision: "accept", label: "Allow once" } as const]
      : has("allow_always")
        ? [{ decision: "acceptForSession", label: "Always allow" } as const]
        : []),
    ...(has("reject_once") ? [{ decision: "decline", label: "Deny" } as const] : []),
    { decision: "cancel", label: "Cancel" },
  ];
}

/**
 * T3's answer to a Kiro permission request. A policy approval may only use
 * Kiro's `allow_once`: its `allow_always` saves a consent rule for the whole
 * workspace or wider, which would outlive the thread. When Kiro offers no
 * one-time choice, the request goes to the user instead of persisting a grant.
 */
export function kiroPermissionDisposition(
  policy: AcpRuntimePolicy,
  request: EffectAcpSchema.RequestPermissionRequest,
): AcpPermissionDisposition {
  const disposition = acpPermissionDisposition(policy, request);
  const offersOnce = request.options.some(
    (option) => option.kind === "allow_once" && option.optionId.trim().length > 0,
  );
  return disposition === "allow" && !offersOnce ? "ask" : disposition;
}

export interface KiroAcpRuntimeInput extends Omit<
  AcpSessionRuntime.AcpSessionRuntimeOptions,
  "authMethodId" | "spawn"
> {
  readonly settings: KiroAcpRuntimeSettings | null | undefined;
  readonly environment?: NodeJS.ProcessEnv;
}

export const makeKiroAcpRuntime = Effect.fn("KiroAcpSupport.makeKiroAcpRuntime")(function* (
  input: KiroAcpRuntimeInput,
): Effect.fn.Return<
  AcpSessionRuntime.AcpSessionRuntime["Service"],
  EffectAcpErrors.AcpError,
  ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
> {
  const { settings, environment, ...runtimeOptions } = input;
  const context = yield* Layer.build(
    AcpSessionRuntime.layer({
      ...runtimeOptions,
      spawn: buildKiroAcpSpawnInput(settings, input.cwd, environment),
    }),
  );
  return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(Effect.provide(context));
});