#!/usr/bin/env node
import {
  atomicWriteFileSync
} from "./chunk-NQDJ6QAM.js";
import {
  sessionPaths
} from "./chunk-7RSBFN2G.js";

// src/common/seq-counter.ts
import { mkdirSync, readFileSync, existsSync } from "fs";
var RESERVATION_BATCH = 100;
var SeqCounter = class {
  seq = 0;
  // 已持久化的高水位; seq <= reservedUpTo 时 next() 不需要写盘
  reservedUpTo = 0;
  filePath;
  constructor(sessionId, baseDir) {
    const dir = baseDir ?? sessionPaths(sessionId).dir;
    mkdirSync(dir, { recursive: true });
    this.filePath = `${dir}/seq`;
    this.load();
  }
  next() {
    this.seq++;
    if (this.seq > this.reservedUpTo) {
      this.reservedUpTo = this.seq + RESERVATION_BATCH - 1;
      this.save();
    }
    return this.seq;
  }
  current() {
    return this.seq;
  }
  // 显式持久化当前 seq, 不再保留 batch——优雅退出时调用, 让重启续号尽量贴近真实进度。
  flush() {
    if (this.seq !== this.reservedUpTo) {
      this.reservedUpTo = this.seq;
      this.save();
    }
  }
  load() {
    if (!existsSync(this.filePath)) return;
    const content = readFileSync(this.filePath, "utf-8").trim();
    const parsed = parseInt(content, 10);
    if (isNaN(parsed) || parsed < 0) {
      throw new Error(`Corrupt seq file: ${this.filePath} contains "${content}"`);
    }
    this.seq = parsed;
    this.reservedUpTo = parsed;
  }
  save() {
    atomicWriteFileSync(this.filePath, String(this.reservedUpTo));
  }
};
var seqCounterCache = /* @__PURE__ */ new Map();
function getSeqCounterFor(sessionId, baseDir) {
  let counter = seqCounterCache.get(sessionId);
  if (!counter) {
    counter = new SeqCounter(sessionId, baseDir);
    seqCounterCache.set(sessionId, counter);
  }
  return counter;
}
function disposeSeqCounter(sessionId) {
  seqCounterCache.delete(sessionId);
}

// src/common/approval-request-id.ts
function createApprovalRequestIdFactory(scope, now = Date.now) {
  let seq = 0;
  return () => `${scope}-${now()}-${seq++}`;
}
function createScopedApprovalRequestIdFactory(now = Date.now) {
  let seq = 0;
  return (scope) => `${scope}-${now()}-${seq++}`;
}

// src/common/stream-json-schema.ts
import { z } from "zod";
var TextBlockSchema = z.object({
  type: z.literal("text"),
  text: z.string()
}).passthrough();
var ThinkingBlockSchema = z.object({
  type: z.literal("thinking"),
  thinking: z.string(),
  signature: z.string().optional()
}).passthrough();
var ToolUseBlockSchema = z.object({
  type: z.literal("tool_use"),
  id: z.string(),
  name: z.string(),
  input: z.record(z.string(), z.unknown())
}).passthrough();
var ToolResultBlockSchema = z.object({
  type: z.literal("tool_result"),
  tool_use_id: z.string(),
  content: z.unknown(),
  is_error: z.boolean().optional()
}).passthrough();
var KnownContentBlockSchema = z.discriminatedUnion("type", [
  TextBlockSchema,
  ThinkingBlockSchema,
  ToolUseBlockSchema,
  ToolResultBlockSchema
]);
var AssistantEventSchema = z.object({
  type: z.literal("assistant"),
  message: z.object({
    content: z.array(z.unknown())
  }).passthrough()
}).passthrough();
var UserEventSchema = z.object({
  type: z.literal("user"),
  message: z.object({
    content: z.union([z.array(z.unknown()), z.string()])
  }).passthrough()
}).passthrough();
var ResultEventSchema = z.object({
  type: z.literal("result"),
  subtype: z.string(),
  is_error: z.boolean().optional()
}).passthrough();
var SystemEventSchema = z.object({
  type: z.literal("system"),
  subtype: z.string().optional(),
  status: z.string().optional(),
  content: z.unknown().optional()
}).passthrough();
var TextDeltaSchema = z.object({
  type: z.literal("text_delta"),
  text: z.string()
}).passthrough();
var ThinkingDeltaSchema = z.object({
  type: z.literal("thinking_delta"),
  thinking: z.string()
}).passthrough();
var SignatureDeltaSchema = z.object({
  type: z.literal("signature_delta"),
  signature: z.string()
}).passthrough();
var ContentBlockDeltaSchema = z.object({
  type: z.literal("content_block_delta"),
  index: z.number(),
  delta: z.discriminatedUnion("type", [
    TextDeltaSchema,
    ThinkingDeltaSchema,
    SignatureDeltaSchema
  ])
}).passthrough();
var StreamEventSchema = z.object({
  type: z.literal("stream_event"),
  event: z.object({ type: z.string() }).passthrough()
}).passthrough();
var CanUseToolRequestSchema = z.object({
  subtype: z.literal("can_use_tool"),
  tool_name: z.string(),
  input: z.record(z.string(), z.unknown())
}).passthrough();
var ControlRequestEventSchema = z.object({
  type: z.literal("control_request"),
  request_id: z.string(),
  request: CanUseToolRequestSchema
}).passthrough();
var ControlResponseEventSchema = z.object({
  type: z.literal("control_response"),
  response: z.object({
    subtype: z.literal("success"),
    request_id: z.string(),
    response: z.discriminatedUnion("behavior", [
      z.object({
        behavior: z.literal("allow"),
        updatedInput: z.record(z.string(), z.unknown())
      }).passthrough(),
      z.object({
        behavior: z.literal("deny"),
        message: z.string()
      }).passthrough()
    ])
  }).passthrough()
}).passthrough();
var StreamJsonEventSchema = z.discriminatedUnion("type", [
  AssistantEventSchema,
  UserEventSchema,
  ResultEventSchema,
  SystemEventSchema,
  StreamEventSchema,
  ControlRequestEventSchema,
  ControlResponseEventSchema
]);
var IGNORED_EVENT_TYPES = /* @__PURE__ */ new Set(["rate_limit_event"]);

export {
  KnownContentBlockSchema,
  ContentBlockDeltaSchema,
  ControlRequestEventSchema,
  StreamJsonEventSchema,
  IGNORED_EVENT_TYPES,
  SeqCounter,
  getSeqCounterFor,
  disposeSeqCounter,
  createApprovalRequestIdFactory,
  createScopedApprovalRequestIdFactory
};
//# sourceMappingURL=chunk-NXELIU46.js.map