@shumai-one/shumai 0.3.2 → 0.3.4

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.
Files changed (191) hide show
  1. package/bin/{chunk-qmtvy2j4.js → chunk-03pw611p.js} +2 -2
  2. package/bin/{chunk-1nh6xgek.js → chunk-05m8w09t.js} +1 -1
  3. package/bin/chunk-0ark0qrm.js +1 -0
  4. package/bin/{chunk-arpna31w.js → chunk-1apsnd7e.js} +1 -1
  5. package/bin/{chunk-g2dk56e7.js → chunk-1bfrnc6b.js} +1 -1
  6. package/bin/chunk-21h9kgp5.js +1 -0
  7. package/bin/{chunk-na2nympm.js → chunk-2967rnmn.js} +1 -1
  8. package/bin/chunk-2errtbmb.js +2 -0
  9. package/bin/{chunk-hrzm70wg.js → chunk-2jnyk045.js} +1 -1
  10. package/bin/{chunk-etces6ff.js → chunk-2mr99scd.js} +2 -2
  11. package/bin/chunk-2pxev94x.js +2 -0
  12. package/bin/chunk-2y9t0qxp.js +45 -0
  13. package/bin/{chunk-s7qpj715.js → chunk-2ydhnafa.js} +2 -2
  14. package/bin/chunk-38hp9gfh.js +2 -0
  15. package/bin/chunk-3t7v2de9.js +307 -0
  16. package/bin/{chunk-20y3wte3.js → chunk-3vbx3x11.js} +2 -2
  17. package/bin/{chunk-d3s00sn0.js → chunk-3xfhbvar.js} +2 -2
  18. package/bin/chunk-4153rke8.js +12 -0
  19. package/bin/{chunk-7jjc175m.js → chunk-4a185tez.js} +3 -3
  20. package/bin/{chunk-zxpef55w.js → chunk-4rexdetz.js} +3 -3
  21. package/bin/{chunk-1dawjfk8.js → chunk-58y9bagr.js} +2 -2
  22. package/bin/chunk-5dqn7egd.js +11 -0
  23. package/bin/{chunk-9p2d0mk1.js → chunk-5e48saab.js} +1 -1
  24. package/bin/{chunk-vnfmh5ke.js → chunk-5qwzveck.js} +2 -2
  25. package/bin/chunk-61hfhfce.js +2 -0
  26. package/bin/chunk-6ab9eftx.js +3 -0
  27. package/bin/chunk-6b0f3d07.js +2 -0
  28. package/bin/chunk-6gjn8trh.js +3 -0
  29. package/bin/{chunk-gn8snrnk.js → chunk-75x3w5hx.js} +1 -1
  30. package/bin/chunk-7e39zmss.js +1 -0
  31. package/bin/chunk-7h1m1e0b.js +1 -0
  32. package/bin/chunk-7kdz1eng.js +3 -0
  33. package/bin/chunk-7pcba64w.js +1 -0
  34. package/bin/{chunk-s05f0v9t.js → chunk-7xfx7741.js} +1 -1
  35. package/bin/chunk-898hrxwq.js +2 -0
  36. package/bin/{chunk-ph3e1bpp.js → chunk-89chaa11.js} +2 -2
  37. package/bin/chunk-8btfb5g6.js +2 -0
  38. package/bin/{chunk-gvn079hy.js → chunk-8pa1n500.js} +2 -2
  39. package/bin/{chunk-vy24ncn2.js → chunk-8qe7cpbr.js} +1 -1
  40. package/bin/{chunk-ws07a9kv.js → chunk-8tnq43k9.js} +1 -1
  41. package/bin/{chunk-1d22tysv.js → chunk-8wzepzp3.js} +2 -2
  42. package/bin/chunk-9deae0n7.js +3 -0
  43. package/bin/{chunk-3rcc5s99.js → chunk-ankkm2wz.js} +2 -2
  44. package/bin/chunk-ardp3pze.js +2 -0
  45. package/bin/chunk-axe5rq99.js +7 -0
  46. package/bin/chunk-bagxeg82.js +2 -0
  47. package/bin/{chunk-ss45w8ks.js → chunk-bhqrqt97.js} +2 -2
  48. package/bin/chunk-bn1sts8x.js +3 -0
  49. package/bin/{chunk-31mjcykb.js → chunk-bpb0szs5.js} +2 -2
  50. package/bin/{chunk-tsncwscz.js → chunk-c1j58ekb.js} +2 -2
  51. package/bin/chunk-c4nenmry.js +2 -0
  52. package/bin/chunk-c9f6n4sf.js +3 -0
  53. package/bin/chunk-cwh21vfb.js +2 -0
  54. package/bin/chunk-cwpmf8tx.js +2 -0
  55. package/bin/{chunk-ejfmxjw6.js → chunk-d2xrh0vv.js} +2 -2
  56. package/bin/chunk-d4sg0z3y.js +2 -0
  57. package/bin/chunk-d4sjezbk.js +8 -0
  58. package/bin/{chunk-vgb8bzcg.js → chunk-ddfx823h.js} +2 -2
  59. package/bin/chunk-dtjx1097.js +2 -0
  60. package/bin/chunk-e32bzfza.js +1 -0
  61. package/bin/chunk-e6rmqgzv.js +2 -0
  62. package/bin/chunk-ersxsrz8.js +62 -0
  63. package/bin/chunk-gg1wfpm8.js +3 -0
  64. package/bin/{chunk-qc6dmzn0.js → chunk-gg8dmkwd.js} +2 -2
  65. package/bin/chunk-gnx9g8px.js +2 -0
  66. package/bin/{chunk-xawwxdq9.js → chunk-h0k9zw29.js} +2 -2
  67. package/bin/chunk-htrzgs2a.css +1 -0
  68. package/bin/chunk-j2jdrmaa.js +2 -0
  69. package/bin/{chunk-v2kfr8fx.js → chunk-j5dejr3e.js} +2 -2
  70. package/bin/{chunk-wap08p4j.js → chunk-j5q3t199.js} +2 -2
  71. package/bin/chunk-jgxhv36z.js +3 -0
  72. package/bin/{chunk-dwswqq3g.js → chunk-jnx8p6kj.js} +1 -1
  73. package/bin/chunk-k41vt2gq.js +1 -0
  74. package/bin/chunk-k78m3rar.js +2 -0
  75. package/bin/chunk-kfbztymc.js +4 -0
  76. package/bin/chunk-kgr3ytpb.js +5 -0
  77. package/bin/chunk-khc3dydj.js +2 -0
  78. package/bin/chunk-krpr6g8a.js +1 -0
  79. package/bin/chunk-m8tnsds1.js +2 -0
  80. package/bin/chunk-mfmcsdd7.js +1 -0
  81. package/bin/chunk-msjv1ykh.js +2 -0
  82. package/bin/chunk-n73dbqps.js +1 -0
  83. package/bin/{chunk-5vqan9c4.js → chunk-n7cmya8k.js} +2 -2
  84. package/bin/{chunk-hfp4hpca.js → chunk-nabagpah.js} +2 -2
  85. package/bin/chunk-nn5qpr0q.js +1 -0
  86. package/bin/{chunk-ve7v8wtv.js → chunk-pew69nxg.js} +2 -2
  87. package/bin/{chunk-7eycsyk6.js → chunk-q2shr586.js} +1 -1
  88. package/bin/chunk-q7v8sj72.js +1 -0
  89. package/bin/chunk-q9tm2d21.js +8 -0
  90. package/bin/{chunk-mcxsk75h.js → chunk-qw5yjhab.js} +3 -3
  91. package/bin/{chunk-j0p1peav.js → chunk-r9thyg31.js} +2 -2
  92. package/bin/{chunk-h2wsm7h3.js → chunk-s584wxzj.js} +2 -2
  93. package/bin/{chunk-wr5byz6r.js → chunk-s5s1rk4n.js} +1 -1
  94. package/bin/{chunk-zs9b0f3z.js → chunk-scfbmsy7.js} +2 -2
  95. package/bin/{chunk-k20bhxed.js → chunk-sddrv3ep.js} +1 -1
  96. package/bin/{chunk-amsb41z5.js → chunk-sfmhbk59.js} +1 -1
  97. package/bin/chunk-tbdgkpgw.js +2 -0
  98. package/bin/chunk-twhj7h73.js +1 -0
  99. package/bin/{chunk-mahxw48e.js → chunk-v5zdafv4.js} +2 -2
  100. package/bin/{chunk-3t7mjvdv.js → chunk-vzx1r87y.js} +2 -2
  101. package/bin/{chunk-a76c5r3c.js → chunk-w3xzd86e.js} +2 -2
  102. package/bin/{chunk-nzy3pjjm.js → chunk-xkh6b42h.js} +2 -2
  103. package/bin/chunk-yn7mxpmb.js +7 -0
  104. package/bin/{chunk-yahb7wan.js → chunk-z544s59c.js} +2 -2
  105. package/bin/{chunk-f8cn9m28.js → chunk-zned6mj8.js} +1 -1
  106. package/bin/{chunk-08mxv0sm.js → chunk-zpq34g0w.js} +2 -2
  107. package/bin/shumai-app.html +1 -1
  108. package/bin/shumai-app.js +495 -372
  109. package/package.json +7 -7
  110. package/prisma/migrations/20260801065040_add_audit_log/migration.sql +33 -0
  111. package/prisma/migrations/20260805021613_add_asset_autofill_context/migration.sql +2 -0
  112. package/prisma/migrations/20260806082136_add_sharelink_watermark/migration.sql +69 -0
  113. package/prisma/migrations/20260806085643_add_watermark_file_status/migration.sql +7 -0
  114. package/prisma/migrations/20260807140837_clean_media_remove_raw_transcodes_and_original_download_url/migration.sql +86 -0
  115. package/prisma/migrations/20260808014542_add_sharelink_allow_download/migration.sql +2 -0
  116. package/prisma/schema.prisma +93 -0
  117. package/bin/chunk-08dr94gp.js +0 -2
  118. package/bin/chunk-0t4z17qr.js +0 -2
  119. package/bin/chunk-2ynx0den.js +0 -8
  120. package/bin/chunk-31a3k77j.js +0 -2
  121. package/bin/chunk-3jdef7n4.js +0 -6
  122. package/bin/chunk-4ahve1nf.js +0 -2
  123. package/bin/chunk-4hdnrwh1.js +0 -1
  124. package/bin/chunk-4hdx2tv0.js +0 -2
  125. package/bin/chunk-4htdb0xp.js +0 -1
  126. package/bin/chunk-4p7xpfey.js +0 -2
  127. package/bin/chunk-5f81c951.js +0 -1
  128. package/bin/chunk-5zntjzxw.js +0 -3
  129. package/bin/chunk-6a2eb3b5.js +0 -3
  130. package/bin/chunk-6t3gdd7e.js +0 -2
  131. package/bin/chunk-7d5kep8c.js +0 -2
  132. package/bin/chunk-7kzqkp5z.js +0 -1
  133. package/bin/chunk-7sh6409h.js +0 -1
  134. package/bin/chunk-7y8dng8t.js +0 -2
  135. package/bin/chunk-8e5zvy88.js +0 -307
  136. package/bin/chunk-8m6zg15c.js +0 -4
  137. package/bin/chunk-8qyke29r.js +0 -7
  138. package/bin/chunk-90et6bwm.js +0 -3
  139. package/bin/chunk-9c7fxjej.js +0 -2
  140. package/bin/chunk-a10tf0d8.js +0 -3
  141. package/bin/chunk-b10meywb.js +0 -2
  142. package/bin/chunk-b1e3tec3.js +0 -62
  143. package/bin/chunk-bdjhb77e.js +0 -2
  144. package/bin/chunk-beay9amy.js +0 -1
  145. package/bin/chunk-c3fvs0bv.js +0 -4
  146. package/bin/chunk-c5my1b3k.js +0 -7
  147. package/bin/chunk-dhekxndw.js +0 -3
  148. package/bin/chunk-dwaj1yn4.js +0 -2
  149. package/bin/chunk-er1rb6yj.js +0 -1
  150. package/bin/chunk-etqpzc9e.js +0 -3
  151. package/bin/chunk-fdpjw17x.js +0 -7
  152. package/bin/chunk-gqh4ttjh.js +0 -3
  153. package/bin/chunk-hz31j0hk.js +0 -4
  154. package/bin/chunk-jm6bxtzt.js +0 -41
  155. package/bin/chunk-jstc7pka.js +0 -2
  156. package/bin/chunk-k0a35mg9.js +0 -2
  157. package/bin/chunk-k9w6mk9d.js +0 -3
  158. package/bin/chunk-kgb16ggd.css +0 -1
  159. package/bin/chunk-m4py21f3.js +0 -2
  160. package/bin/chunk-mm1j72a8.js +0 -7
  161. package/bin/chunk-nr89225z.js +0 -2
  162. package/bin/chunk-nrf5r23d.js +0 -1
  163. package/bin/chunk-nt9tfjx6.js +0 -12
  164. package/bin/chunk-p396vw9h.js +0 -8
  165. package/bin/chunk-p9xfyqh1.js +0 -2
  166. package/bin/chunk-pj0fgb2x.js +0 -6
  167. package/bin/chunk-pp072ksj.js +0 -2
  168. package/bin/chunk-q5cdjzbv.js +0 -3
  169. package/bin/chunk-qn96vbke.js +0 -2
  170. package/bin/chunk-qvgc9e08.js +0 -3
  171. package/bin/chunk-rrxjvewm.js +0 -2
  172. package/bin/chunk-s5rfya1p.js +0 -1
  173. package/bin/chunk-scsy69bp.js +0 -1
  174. package/bin/chunk-sf6fwvrs.js +0 -8
  175. package/bin/chunk-t2txvzkp.js +0 -3
  176. package/bin/chunk-td54rdfj.js +0 -8
  177. package/bin/chunk-vb9m47z9.js +0 -1
  178. package/bin/chunk-vf066xwh.js +0 -3
  179. package/bin/chunk-w3a50kz8.js +0 -3
  180. package/bin/chunk-w9w5301f.js +0 -4
  181. package/bin/chunk-wny0qagx.js +0 -3
  182. package/bin/chunk-wqhk76de.js +0 -14
  183. package/bin/chunk-wrz9e73c.js +0 -2
  184. package/bin/chunk-x5dcgk62.js +0 -6
  185. package/bin/chunk-xwmsxg5x.js +0 -1
  186. package/bin/chunk-y2nw8rbx.js +0 -4
  187. package/bin/chunk-y9ttm07y.js +0 -3
  188. package/bin/chunk-z0ej44ak.js +0 -3
  189. package/bin/chunk-zemgtnk0.js +0 -1
  190. package/bin/chunk-zg0vm233.js +0 -2
  191. package/bin/chunk-zhd2mkbr.js +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumai-one/shumai",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "A fullstack AI-powered media workspace and workflow engine",
5
5
  "type": "module",
6
6
  "bin": {
@@ -27,12 +27,12 @@
27
27
  "zod": "4.4.3"
28
28
  },
29
29
  "optionalDependencies": {
30
- "@shumai-one/shumai-darwin-arm64": "0.3.2",
31
- "@shumai-one/shumai-darwin-x64": "0.3.2",
32
- "@shumai-one/shumai-linux-arm64": "0.3.2",
33
- "@shumai-one/shumai-linux-x64": "0.3.2",
34
- "@shumai-one/shumai-win32-arm64": "0.3.2",
35
- "@shumai-one/shumai-win32-x64": "0.3.2"
30
+ "@shumai-one/shumai-darwin-arm64": "0.3.4",
31
+ "@shumai-one/shumai-darwin-x64": "0.3.4",
32
+ "@shumai-one/shumai-linux-arm64": "0.3.4",
33
+ "@shumai-one/shumai-linux-x64": "0.3.4",
34
+ "@shumai-one/shumai-win32-arm64": "0.3.4",
35
+ "@shumai-one/shumai-win32-x64": "0.3.4"
36
36
  },
37
37
  "repository": {
38
38
  "type": "git",
@@ -0,0 +1,33 @@
1
+ -- CreateTable
2
+ CREATE TABLE "audit_logs" (
3
+ "id" TEXT NOT NULL,
4
+ "action" TEXT NOT NULL,
5
+ "team_id" TEXT NOT NULL,
6
+ "user_id" TEXT,
7
+ "project_id" TEXT,
8
+ "item_id" TEXT,
9
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
10
+
11
+ CONSTRAINT "audit_logs_pkey" PRIMARY KEY ("id")
12
+ );
13
+
14
+ -- CreateIndex
15
+ CREATE INDEX "audit_logs_team_id_id_idx" ON "audit_logs"("team_id", "id" DESC);
16
+
17
+ -- CreateIndex
18
+ CREATE INDEX "audit_logs_user_id_idx" ON "audit_logs"("user_id");
19
+
20
+ -- CreateIndex
21
+ CREATE INDEX "audit_logs_action_idx" ON "audit_logs"("action");
22
+
23
+ -- CreateIndex
24
+ CREATE INDEX "audit_logs_item_id_idx" ON "audit_logs"("item_id");
25
+
26
+ -- AddForeignKey
27
+ ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
28
+
29
+ -- AddForeignKey
30
+ ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
31
+
32
+ -- AddForeignKey
33
+ ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
1
+ -- AlterTable
2
+ ALTER TABLE "assets" ADD COLUMN "autofill_context" TEXT;
@@ -0,0 +1,69 @@
1
+ -- CreateEnum
2
+ CREATE TYPE "WatermarkStatus" AS ENUM ('disabled', 'processing', 'ready', 'failed');
3
+
4
+ -- AlterEnum
5
+ ALTER TYPE "WorkflowTaskType" ADD VALUE 'transcode_watermark';
6
+
7
+ -- AlterTable
8
+ ALTER TABLE "share_links" ADD COLUMN "watermark_config_id" TEXT,
9
+ ADD COLUMN "watermark_status" "WatermarkStatus" NOT NULL DEFAULT 'disabled';
10
+
11
+ -- CreateTable
12
+ CREATE TABLE "watermark_configs" (
13
+ "id" TEXT NOT NULL,
14
+ "config" JSONB NOT NULL,
15
+ "hash" TEXT NOT NULL,
16
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
17
+ "updated_at" TIMESTAMP(3) NOT NULL,
18
+
19
+ CONSTRAINT "watermark_configs_pkey" PRIMARY KEY ("id")
20
+ );
21
+
22
+ -- CreateTable
23
+ CREATE TABLE "watermark_templates" (
24
+ "id" TEXT NOT NULL,
25
+ "name" TEXT NOT NULL,
26
+ "config" JSONB NOT NULL,
27
+ "team_id" TEXT,
28
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
29
+ "updated_at" TIMESTAMP(3) NOT NULL,
30
+
31
+ CONSTRAINT "watermark_templates_pkey" PRIMARY KEY ("id")
32
+ );
33
+
34
+ -- CreateTable
35
+ CREATE TABLE "watermark_files" (
36
+ "id" TEXT NOT NULL,
37
+ "asset_id" TEXT NOT NULL,
38
+ "watermark_config_id" TEXT NOT NULL,
39
+ "media" JSONB,
40
+ "status" "WorkflowTaskStatus" NOT NULL DEFAULT 'pending',
41
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
42
+ "updated_at" TIMESTAMP(3) NOT NULL,
43
+
44
+ CONSTRAINT "watermark_files_pkey" PRIMARY KEY ("id")
45
+ );
46
+
47
+ -- CreateIndex
48
+ CREATE UNIQUE INDEX "watermark_configs_hash_key" ON "watermark_configs"("hash");
49
+
50
+ -- CreateIndex
51
+ CREATE INDEX "watermark_templates_team_id_idx" ON "watermark_templates"("team_id");
52
+
53
+ -- CreateIndex
54
+ CREATE INDEX "watermark_files_watermark_config_id_idx" ON "watermark_files"("watermark_config_id");
55
+
56
+ -- CreateIndex
57
+ CREATE UNIQUE INDEX "watermark_files_asset_id_watermark_config_id_key" ON "watermark_files"("asset_id", "watermark_config_id");
58
+
59
+ -- AddForeignKey
60
+ ALTER TABLE "share_links" ADD CONSTRAINT "share_links_watermark_config_id_fkey" FOREIGN KEY ("watermark_config_id") REFERENCES "watermark_configs"("id") ON DELETE SET NULL ON UPDATE CASCADE;
61
+
62
+ -- AddForeignKey
63
+ ALTER TABLE "watermark_templates" ADD CONSTRAINT "watermark_templates_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
64
+
65
+ -- AddForeignKey
66
+ ALTER TABLE "watermark_files" ADD CONSTRAINT "watermark_files_asset_id_fkey" FOREIGN KEY ("asset_id") REFERENCES "assets"("id") ON DELETE CASCADE ON UPDATE CASCADE;
67
+
68
+ -- AddForeignKey
69
+ ALTER TABLE "watermark_files" ADD CONSTRAINT "watermark_files_watermark_config_id_fkey" FOREIGN KEY ("watermark_config_id") REFERENCES "watermark_configs"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,7 @@
1
+ -- CreateEnum
2
+ CREATE TYPE "WatermarkFileStatus" AS ENUM ('pending', 'processing', 'completed', 'failed');
3
+
4
+ -- AlterTable
5
+ ALTER TABLE "watermark_files" ALTER COLUMN "status" DROP DEFAULT;
6
+ ALTER TABLE "watermark_files" ALTER COLUMN "status" TYPE "WatermarkFileStatus" USING ("status"::text::"WatermarkFileStatus");
7
+ ALTER TABLE "watermark_files" ALTER COLUMN "status" SET DEFAULT 'pending';
@@ -0,0 +1,86 @@
1
+ -- Data cleanup: remove legacy media JSON fields that are no longer used.
2
+ --
3
+ -- WebUI now displays transcoded proxies only and never falls back to the raw
4
+ -- original file:
5
+ -- 1. Drop the raw-original marker entries (`isRaw: true`) from
6
+ -- videoTranscodes / imageTranscodes. They pointed at the original file
7
+ -- key and were only consumed by the removed display fallbacks and the
8
+ -- download-menu entries, which now use media.original.key directly.
9
+ -- 2. Strip the now-removed `isRaw` field from remaining transcode entries.
10
+ -- 3. Drop `original.downloadUrl` (removed from the AssetInfo DTO; downloads
11
+ -- resolve a fresh presigned URL from `key` via the download-url APIs).
12
+
13
+ UPDATE "assets"
14
+ SET "media" = jsonb_set(
15
+ jsonb_set(
16
+ CASE WHEN jsonb_typeof("media"->'original') = 'object'
17
+ THEN "media" #- '{original,downloadUrl}'
18
+ ELSE "media" END,
19
+ '{videoTranscodes}',
20
+ COALESCE(
21
+ (SELECT jsonb_agg(elem - 'isRaw')
22
+ FROM jsonb_array_elements("media"->'videoTranscodes') elem
23
+ WHERE jsonb_typeof(elem) = 'object'
24
+ AND NOT COALESCE((elem->>'isRaw')::boolean, false)),
25
+ '[]'::jsonb
26
+ )
27
+ ),
28
+ '{imageTranscodes}',
29
+ COALESCE(
30
+ (SELECT jsonb_agg(elem - 'isRaw')
31
+ FROM jsonb_array_elements("media"->'imageTranscodes') elem
32
+ WHERE jsonb_typeof(elem) = 'object'
33
+ AND NOT COALESCE((elem->>'isRaw')::boolean, false)),
34
+ '[]'::jsonb
35
+ )
36
+ )
37
+ WHERE "media" IS NOT NULL
38
+ AND (
39
+ (jsonb_typeof("media"->'original') = 'object' AND "media"->'original' ? 'downloadUrl')
40
+ OR EXISTS (
41
+ SELECT 1 FROM jsonb_array_elements(COALESCE("media"->'videoTranscodes', '[]'::jsonb)) e
42
+ WHERE jsonb_typeof(e) = 'object' AND e ? 'isRaw'
43
+ )
44
+ OR EXISTS (
45
+ SELECT 1 FROM jsonb_array_elements(COALESCE("media"->'imageTranscodes', '[]'::jsonb)) e
46
+ WHERE jsonb_typeof(e) = 'object' AND e ? 'isRaw'
47
+ )
48
+ );
49
+
50
+ -- Same cleanup for watermarked proxy media.
51
+ UPDATE "watermark_files"
52
+ SET "media" = jsonb_set(
53
+ jsonb_set(
54
+ CASE WHEN jsonb_typeof("media"->'original') = 'object'
55
+ THEN "media" #- '{original,downloadUrl}'
56
+ ELSE "media" END,
57
+ '{videoTranscodes}',
58
+ COALESCE(
59
+ (SELECT jsonb_agg(elem - 'isRaw')
60
+ FROM jsonb_array_elements("media"->'videoTranscodes') elem
61
+ WHERE jsonb_typeof(elem) = 'object'
62
+ AND NOT COALESCE((elem->>'isRaw')::boolean, false)),
63
+ '[]'::jsonb
64
+ )
65
+ ),
66
+ '{imageTranscodes}',
67
+ COALESCE(
68
+ (SELECT jsonb_agg(elem - 'isRaw')
69
+ FROM jsonb_array_elements("media"->'imageTranscodes') elem
70
+ WHERE jsonb_typeof(elem) = 'object'
71
+ AND NOT COALESCE((elem->>'isRaw')::boolean, false)),
72
+ '[]'::jsonb
73
+ )
74
+ )
75
+ WHERE "media" IS NOT NULL
76
+ AND (
77
+ (jsonb_typeof("media"->'original') = 'object' AND "media"->'original' ? 'downloadUrl')
78
+ OR EXISTS (
79
+ SELECT 1 FROM jsonb_array_elements(COALESCE("media"->'videoTranscodes', '[]'::jsonb)) e
80
+ WHERE jsonb_typeof(e) = 'object' AND e ? 'isRaw'
81
+ )
82
+ OR EXISTS (
83
+ SELECT 1 FROM jsonb_array_elements(COALESCE("media"->'imageTranscodes', '[]'::jsonb)) e
84
+ WHERE jsonb_typeof(e) = 'object' AND e ? 'isRaw'
85
+ )
86
+ );
@@ -0,0 +1,2 @@
1
+ -- AlterTable
2
+ ALTER TABLE "share_links" ADD COLUMN "allow_download" BOOLEAN NOT NULL DEFAULT true;
@@ -106,6 +106,7 @@ enum WorkflowTaskType {
106
106
  transcode_pdf_pages
107
107
  transcode_screenshot
108
108
  transcode_image_annotation
109
+ transcode_watermark
109
110
  ai_metadata_autofill
110
111
  chat
111
112
  ai_embedding
@@ -120,6 +121,20 @@ enum WorkflowTaskStatus {
120
121
  failed
121
122
  }
122
123
 
124
+ enum WatermarkStatus {
125
+ disabled
126
+ processing
127
+ ready
128
+ failed
129
+ }
130
+
131
+ enum WatermarkFileStatus {
132
+ pending
133
+ processing
134
+ completed
135
+ failed
136
+ }
137
+
123
138
  // ----------------------------------------------------------------------
124
139
  // Models
125
140
  // ----------------------------------------------------------------------
@@ -156,6 +171,7 @@ model User {
156
171
  shareLinks ShareLink[] @relation("UserToShareLink")
157
172
  apiTokens ApiToken[] @relation("UserToApiToken")
158
173
  aiUsages AiUsage[] @relation("UserToAiUsage")
174
+ auditLogs AuditLog[] @relation("UserToAuditLog")
159
175
 
160
176
  @@map("users")
161
177
  }
@@ -239,6 +255,8 @@ model Team {
239
255
  sandbox Sandbox? @relation("TeamToSandbox")
240
256
  agents Agent[] @relation("TeamToAgent")
241
257
  aiUsages AiUsage[] @relation("TeamToAiUsage")
258
+ auditLogs AuditLog[] @relation("TeamToAuditLog")
259
+ watermarkTemplates WatermarkTemplate[] @relation("TeamToWatermarkTemplate")
242
260
 
243
261
  @@map("teams")
244
262
  }
@@ -322,6 +340,7 @@ model Project {
322
340
  notifications Notification[] @relation("ProjectToNotification")
323
341
  shareLinks ShareLink[] @relation("ProjectToShareLink")
324
342
  collections Collection[] @relation("ProjectToCollection")
343
+ auditLogs AuditLog[] @relation("ProjectToAuditLog")
325
344
 
326
345
  @@map("projects")
327
346
  @@index([createdAt])
@@ -348,6 +367,7 @@ model ShareLink {
348
367
  expireAt DateTime? @map("expire_at")
349
368
  password String?
350
369
  isDisabled Boolean @default(false) @map("is_disabled")
370
+ allowDownload Boolean @default(true) @map("allow_download")
351
371
  defaultSortOrder String? @map("default_sort_order")
352
372
  viewMode String? @map("view_mode")
353
373
  /// [ShareLinkFieldVisibility]
@@ -364,9 +384,59 @@ model ShareLink {
364
384
  creatorId String? @map("creator_id")
365
385
  creator User? @relation("UserToShareLink", fields: [creatorId], references: [id])
366
386
 
387
+ watermarkConfigId String? @map("watermark_config_id")
388
+ watermarkStatus WatermarkStatus @default(disabled) @map("watermark_status")
389
+ watermarkConfig WatermarkConfig? @relation(fields: [watermarkConfigId], references: [id], onDelete: SetNull)
390
+
367
391
  @@map("share_links")
368
392
  }
369
393
 
394
+ model WatermarkConfig {
395
+ id String @id @default(ulid())
396
+ /// [WatermarkConfigSpec]
397
+ config Json
398
+ hash String @unique
399
+ createdAt DateTime @default(now()) @map("created_at")
400
+ updatedAt DateTime @updatedAt @map("updated_at")
401
+
402
+ shareLinks ShareLink[]
403
+ watermarkFiles WatermarkFile[]
404
+
405
+ @@map("watermark_configs")
406
+ }
407
+
408
+ model WatermarkTemplate {
409
+ id String @id @default(ulid())
410
+ name String
411
+ /// [WatermarkConfigSpec]
412
+ config Json
413
+ teamId String? @map("team_id")
414
+ team Team? @relation("TeamToWatermarkTemplate", fields: [teamId], references: [id], onDelete: Cascade)
415
+ createdAt DateTime @default(now()) @map("created_at")
416
+ updatedAt DateTime @updatedAt @map("updated_at")
417
+
418
+ @@index([teamId])
419
+ @@map("watermark_templates")
420
+ }
421
+
422
+ model WatermarkFile {
423
+ id String @id @default(ulid())
424
+ assetId String @map("asset_id")
425
+ watermarkConfigId String @map("watermark_config_id")
426
+ /// [MediaInfo]
427
+ media Json?
428
+ status WatermarkFileStatus @default(pending)
429
+ createdAt DateTime @default(now()) @map("created_at")
430
+ updatedAt DateTime @updatedAt @map("updated_at")
431
+
432
+ asset Asset @relation("AssetToWatermarkFile", fields: [assetId], references: [id], onDelete: Cascade)
433
+ watermarkConfig WatermarkConfig @relation(fields: [watermarkConfigId], references: [id], onDelete: Cascade)
434
+
435
+ @@unique([assetId, watermarkConfigId])
436
+ @@index([watermarkConfigId])
437
+ @@map("watermark_files")
438
+ }
439
+
370
440
  model Asset {
371
441
  id String @id @default(ulid())
372
442
  name String @default("")
@@ -379,6 +449,7 @@ model Asset {
379
449
  transcodeTaskId String? @map("transcode_task_id")
380
450
  /// [MediaInfo]
381
451
  media Json?
452
+ autofillContext String? @map("autofill_context")
382
453
  isDeleted Boolean @default(false) @map("is_deleted")
383
454
  deletedAt DateTime? @map("deleted_at")
384
455
  sortIndex String? @map("sort_index")
@@ -417,6 +488,7 @@ model Asset {
417
488
  projectShareRoot Project? @relation("ProjectToShareRoot")
418
489
  shareLinkRootFolder ShareLink? @relation("ShareLinkToRootFolder")
419
490
  agentSessions AgentSession[] @relation("AssetToAgentSession")
491
+ watermarkFiles WatermarkFile[] @relation("AssetToWatermarkFile")
420
492
 
421
493
  @@map("assets")
422
494
  @@index([type])
@@ -845,3 +917,24 @@ model AiUsage {
845
917
  @@index([teamId, userId, periodStart])
846
918
  }
847
919
 
920
+ model AuditLog {
921
+ id String @id @default(ulid())
922
+ action String
923
+ teamId String @map("team_id")
924
+ userId String? @map("user_id")
925
+ projectId String? @map("project_id")
926
+ itemId String? @map("item_id")
927
+ createdAt DateTime @default(now()) @map("created_at")
928
+
929
+ team Team @relation("TeamToAuditLog", fields: [teamId], references: [id], onDelete: Cascade)
930
+ user User? @relation("UserToAuditLog", fields: [userId], references: [id], onDelete: SetNull)
931
+ project Project? @relation("ProjectToAuditLog", fields: [projectId], references: [id], onDelete: SetNull)
932
+
933
+ @@index([teamId, id(sort: Desc)])
934
+ @@index([userId])
935
+ @@index([action])
936
+ @@index([itemId])
937
+ @@map("audit_logs")
938
+ }
939
+
940
+
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{gc as b,hc as E}from"./chunk-w3a50kz8.js";import{mc as S}from"./chunk-amsb41z5.js";import{nc as L,oc as M}from"./chunk-gn8snrnk.js";import{zk as I}from"./chunk-k20bhxed.js";import"./chunk-ws07a9kv.js";var P=async(B,J,D)=>{let F={api:B.api,provider:B.provider,model:B.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let G=D?.apiKey;if(!G)throw Error(`No API key for provider: ${B.provider}`);let V=v(B,G,D?.headers),Q=z(B,J),X=await D?.onPayload?.(Q,B);if(X!==void 0)Q=X;let N={...D?.signal?{signal:D.signal}:{},...D?.timeoutMs!==void 0?{timeout:D.timeoutMs}:{},maxRetries:D?.maxRetries??0},{data:O,response:q}=await V.chat.completions.create(Q,N).withResponse();await D?.onResponse?.({status:q.status,headers:L(q.headers)},B);let Y=O;if(F.responseId=Y.id,Y.usage)F.usage=C(Y.usage,B);let Z=Y.choices[0];if(Z){let _=Z.message.content;if(typeof _==="string"&&_.length>0)F.output.push({type:"text",text:_});for(let $ of Z.message.images??[]){let A=typeof $.image_url==="string"?$.image_url:$.image_url?.url;if(!A?.startsWith("data:"))continue;let f=A.match(/^data:([^;]+);base64,(.+)$/);if(!f)continue;F.output.push({type:"image",mimeType:f[1],data:f[2]})}}return F}catch(G){return F.stopReason=D?.signal?.aborted?"aborted":"error",F.errorMessage=E(b(G)),F}};function v(B,J,D){return new I({apiKey:J,baseURL:B.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:M({...B.headers,...D})})}function z(B,J){let D=J.input.map((F)=>{if(F.type==="text")return{type:"text",text:S(F.text)};return{type:"image_url",image_url:{url:`data:${F.mimeType};base64,${F.data}`}}});return{model:B.id,messages:[{role:"user",content:D}],stream:!1,modalities:B.output.includes("text")?["image","text"]:["image"]}}function C(B,J){let D=B.prompt_tokens||0,F=B.prompt_tokens_details?.cached_tokens||0,G=B.prompt_tokens_details?.cache_write_tokens||0,V=G>0?Math.max(0,F-G):F,Q=Math.max(0,D-V-G),X=B.completion_tokens||0,N={input:Q,output:X,cacheRead:V,cacheWrite:G,totalTokens:Q+X+V+G,cost:{input:J.cost.input/1e6*Q,output:J.cost.output/1e6*X,cacheRead:J.cost.cacheRead/1e6*V,cacheWrite:J.cost.cacheWrite/1e6*G,total:0}};return N.cost.total=N.cost.input+N.cost.output+N.cost.cacheRead+N.cost.cacheWrite,N}export{P as generateImages};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{uk as S,vk as T,wk as C}from"./chunk-wqhk76de.js";import"./chunk-dhekxndw.js";import{yk as D}from"./chunk-etqpzc9e.js";import{Ak as Z}from"./chunk-k20bhxed.js";import"./chunk-c3fvs0bv.js";import"./chunk-hz31j0hk.js";import{Ek as k}from"./chunk-90et6bwm.js";import{Qk as f}from"./chunk-5zntjzxw.js";import{Uk as M,Vk as V}from"./chunk-vf066xwh.js";import"./chunk-qvgc9e08.js";import"./chunk-ws07a9kv.js";var j="v1",E=new Set(["openai","openai-codex","opencode","azure-openai-responses"]);function K(G){let Q=new Map;if(!G)return Q;for(let w of G.split(",")){let W=w.trim();if(!W)continue;let[X,J]=W.split("=",2);if(!X||!J)continue;Q.set(X.trim(),J.trim())}return Q}function g(G,Q){if(Q?.azureDeploymentName)return Q.azureDeploymentName;return K(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(G.id)||G.id}function B(G){if(G instanceof Error){let Q=G.status,w=typeof Q==="number"?Q:void 0;if(w!==void 0)return`Azure OpenAI API error (${w}): ${G.message}`;return G.message}try{return JSON.stringify(G)}catch{return String(G)}}var I=(G,Q,w)=>{let W=new V;return(async()=>{let X=g(G,w),J={role:"assistant",content:[],api:"azure-openai-responses",provider:G.provider,model:G.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let Y=w?.apiKey;if(!Y)throw Error(`No API key for provider: ${G.provider}`);let $=z(G,Y,w),q=b(G,Q,w,X),F=await w?.onPayload?.(q,G);if(F!==void 0)q=F;let L={...w?.signal?{signal:w.signal}:{},...w?.timeoutMs!==void 0?{timeout:w.timeoutMs}:{},maxRetries:w?.maxRetries??0},{data:_,response:H}=await $.responses.create(q,L).withResponse();if(await w?.onResponse?.({status:H.status,headers:k(H.headers)},G),W.push({type:"start",partial:J}),await C(_,J,W,G),w?.signal?.aborted)throw Error("Request was aborted");if(J.stopReason==="aborted"||J.stopReason==="error")throw Error("An unknown error occurred");W.push({type:"done",reason:J.stopReason,message:J}),W.end()}catch(Y){for(let $ of J.content)delete $.index,delete $.partialJson;J.stopReason=w?.signal?.aborted?"aborted":"error",J.errorMessage=B(Y),W.push({type:"error",reason:J.stopReason,error:J}),W.end()}})(),W},c=(G,Q,w)=>{let W=w?.apiKey;if(!W)throw Error(`No API key for provider: ${G.provider}`);let X=f(G,w,W),J=w?.reasoning?M(G,w.reasoning):void 0;return I(G,Q,{...X,reasoningEffort:J==="off"?void 0:J})};function P(G){let Q=G.trim().replace(/\/+$/,""),w;try{w=new URL(Q)}catch{throw Error(`Invalid Azure OpenAI base URL: ${G}`)}let W=w.hostname.endsWith(".openai.azure.com")||w.hostname.endsWith(".cognitiveservices.azure.com"),X=w.pathname.replace(/\/+$/,"");if(W&&(X===""||X==="/"||X==="/openai"))w.pathname="/openai/v1",w.search="";return w.toString().replace(/\/+$/,"")}function O(G){return`https://${G}.openai.azure.com/openai/v1`}function h(G,Q){let w=Q?.azureApiVersion||process.env.AZURE_OPENAI_API_VERSION||j,W=Q?.azureBaseUrl?.trim()||process.env.AZURE_OPENAI_BASE_URL?.trim()||void 0,X=Q?.azureResourceName||process.env.AZURE_OPENAI_RESOURCE_NAME,J=W;if(!J&&X)J=O(X);if(!J&&G.baseUrl)J=G.baseUrl;if(!J)throw Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return{baseUrl:P(J),apiVersion:w}}function z(G,Q,w){let W={...G.headers};if(w?.headers)Object.assign(W,w.headers);let{baseUrl:X,apiVersion:J}=h(G,w);return new Z({apiKey:Q,apiVersion:J,dangerouslyAllowBrowser:!0,defaultHeaders:W,baseURL:X})}function b(G,Q,w,W){let X=S(G,Q,E),J={model:W,input:X,stream:!0,prompt_cache_key:D(w?.sessionId)};if(w?.maxTokens)J.max_output_tokens=w?.maxTokens;if(w?.temperature!==void 0)J.temperature=w?.temperature;if(Q.tools&&Q.tools.length>0)J.tools=T(Q.tools);if(G.reasoning){if(w?.reasoningEffort||w?.reasoningSummary){let Y=w?.reasoningEffort?G.thinkingLevelMap?.[w.reasoningEffort]??w.reasoningEffort:"medium";J.reasoning={effort:Y,summary:w?.reasoningSummary||"auto"},J.include=["reasoning.encrypted_content"]}else if(G.thinkingLevelMap?.off!==null)J.reasoning={effort:G.thinkingLevelMap?.off??"none"}}return J}export{c as streamSimpleAzureOpenAIResponses,I as streamAzureOpenAIResponses};
@@ -1,8 +0,0 @@
1
- // @bun
2
- import{Tb as $Q}from"./chunk-s05f0v9t.js";import{Wb as c,Xb as XQ,Yb as l}from"./chunk-nt9tfjx6.js";import"./chunk-vy24ncn2.js";import{_b as VQ}from"./chunk-wr5byz6r.js";import{$b as g}from"./chunk-ss45w8ks.js";import{gc as GQ,hc as FQ}from"./chunk-w3a50kz8.js";import{jc as YQ}from"./chunk-6a2eb3b5.js";import"./chunk-amsb41z5.js";import{nc as u}from"./chunk-gn8snrnk.js";import{me as NQ}from"./chunk-t2txvzkp.js";import{ne as x,oe as JQ,pe as zQ}from"./chunk-a10tf0d8.js";import"./chunk-w9w5301f.js";import{cf as ZQ}from"./chunk-k9w6mk9d.js";import{df as QQ}from"./chunk-wny0qagx.js";import"./chunk-hz31j0hk.js";import"./chunk-ws07a9kv.js";function i(Q){let $=Q.filter((G)=>G!==void 0);if($.length===0)return{cleanup:()=>{}};if($.length===1)return{signal:$[0],cleanup:()=>{}};let Z=new AbortController,Y=[],F=(G)=>{if(!Z.signal.aborted)Z.abort(G.reason)};for(let G of $){if(G.aborted){F(G);break}let V=()=>F(G);G.addEventListener("abort",V,{once:!0}),Y.push({signal:G,listener:V})}return{signal:Z.signal,cleanup:()=>{for(let{signal:G,listener:V}of Y)G.removeEventListener("abort",V)}}}var PQ={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function v(Q,$){let Z=Q.toLowerCase(),Y=Q.toUpperCase();return $?.[Z]||$?.[Y]||g(Z)||g(Y)||""}function AQ(Q){if(Q instanceof URL)return Q;try{return new URL(Q)}catch{return}}function UQ(Q,$,Z){let Y=v("no_proxy",Z).toLowerCase();if(!Y)return!0;if(Y==="*")return!1;return Y.split(/[,\s]/).every((F)=>{if(!F)return!0;let G=F.match(/^(.+):(\d+)$/),V=G?G[1]:F,j=G?Number.parseInt(G[2],10):0;if(j&&j!==$)return!0;if(!/^[.*]/.test(V))return Q!==V;if(V.startsWith("*"))V=V.slice(1);return!Q.endsWith(V)})}function wQ(Q,$){let Z=AQ(Q);if(!Z?.protocol||!Z.host)return"";let Y=Z.protocol.split(":",1)[0],F=Z.host.replace(/:\d*$/,""),G=Number.parseInt(Z.port,10)||PQ[Y]||0;if(!UQ(F,G,$))return"";let V=v(`${Y}_proxy`,$)||v("all_proxy",$);if(V&&!V.includes("://"))V=`${Y}://${V}`;return V}var CQ="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function a(Q,$){let Z=wQ(Q,$);if(!Z)return;let Y;try{Y=new URL(Z)}catch(F){throw Error(`Invalid proxy URL ${JSON.stringify(Z)}: ${F instanceof Error?F.message:String(F)}`)}if(Y.protocol!=="http:"&&Y.protocol!=="https:")throw Error(`${CQ} Got ${Y.protocol}`);return Y}function EQ(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var T=EQ(),fQ="https://chatgpt.com/backend-api",MQ="https://api.openai.com/auth",SQ=0,n=1000,TQ=60000,hQ=15000,IQ=3,jQ=new Set(["openai","openai-codex","opencode"]),xQ=1009,kQ="websocket_connection_limit_reached",bQ=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function gQ(Q){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(Q)}function vQ(Q,$){if(Q===429&&gQ($))return!1;if(Q===429||Q===500||Q===502||Q===503||Q===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test($)}function yQ(Q){let $=Q.get("retry-after-ms");if($!==null){let G=Number($);if(Number.isFinite(G))return Math.max(0,G)}let Z=Q.get("retry-after");if(!Z)return;let Y=Number(Z);if(Number.isFinite(Y))return Math.max(0,Y*1000);let F=Date.parse(Z);if(!Number.isNaN(F))return Math.max(0,F-Date.now());return}function mQ(Q,$){let Z=$?.maxRetryDelayMs??TQ;return Z>0?Math.min(Q,Z):Q}function r(Q,$){return new Promise((Z,Y)=>{if($?.aborted){Y(Error("Request was aborted"));return}let F=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(F),Y(Error("Request was aborted"))})})}function t(Q){if(Q===void 0)return;if(!Number.isFinite(Q)||Q<0)throw Error(`Invalid timeoutMs: ${String(Q)}`);return Math.floor(Q)}function uQ(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function cQ(Q){let $=uQ();if(!$||typeof $.zstdCompressSync!=="function")return null;try{let Z=$.zstdCompressSync(Q,{params:{[$.constants.ZSTD_c_compressionLevel]:IQ}});return new Uint8Array(Z.buffer,Z.byteOffset,Z.byteLength)}catch{return null}}var lQ=(Q,$,Z)=>{let Y=new QQ;return(async()=>{let F={role:"assistant",content:[],api:"openai-codex-responses",provider:Q.provider,model:Q.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let G=Z?.apiKey;if(!G)throw Error(`No API key for provider: ${Q.provider}`);let V=qZ(G),j=pQ(Q,$,Z),N=await Z?.onPayload?.(j,Q);if(N!==void 0)j=N;let X=Z?.sessionId||_Z(),W=OZ(Q.headers,Z?.headers,V,G,Z?.sessionId),J=RZ(Q.headers,Z?.headers,V,G,X),_=JSON.stringify(j),z=t(Z?.timeoutMs),q=t(Z?.websocketConnectTimeoutMs),D=Z?.transport||"auto",B=D!=="sse"&&BQ(Z?.sessionId);if(B)s(Z?.sessionId);if(D!=="sse"&&!B){let O=!1,H=!1;while(!0){O=!1;try{if(await WZ(iQ(Q.baseUrl),j,J,F,Y,Q,()=>{O=!0},z,q,Z),Z?.signal?.aborted)throw Error("Request was aborted");Y.push({type:"done",reason:F.stopReason,message:F}),Y.end();return}catch(A){let C=Z?.signal?.aborted,S=!O&&rQ(A);if(!C&&S&&!H){H=!0;continue}if(C||nQ(A)&&!S)throw A;if(zQ(F,JQ("provider_transport_failure",A,{configuredTransport:D,fallbackTransport:O?void 0:"sse",eventsEmitted:O,phase:O?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(_).byteLength})),YZ(Z?.sessionId,A),O)throw A;s(Z?.sessionId);break}}}let R=cQ(_);if(R)W.set("content-encoding","zstd");let K=R??_,L,w,b=Z?.maxRetries??SQ;for(let O=0;O<=b;O++){if(Z?.signal?.aborted)throw Error("Request was aborted");try{let H=z!==void 0&&z>0?AbortSignal.timeout(z):void 0,A=i([Z?.signal,H]);try{L=await fetch(DQ(Q.baseUrl),{method:"POST",headers:W,body:K,signal:A.signal})}catch(E){if(H?.aborted&&!Z?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${z}ms`);throw E}finally{A.cleanup()}if(await Z?.onResponse?.({status:L.status,headers:u(L.headers)},Q),L.ok)break;let C=await L.text();if(O<b&&vQ(L.status,C)){let E=yQ(L.headers),HQ=E===void 0?n*2**O:L.status===429?mQ(E,Z):E;await r(HQ,Z?.signal);continue}let S=new Response(C,{status:L.status,statusText:L.statusText}),d=await BZ(S);throw Error(d.friendlyMessage||d.message)}catch(H){if(H instanceof Error){if(H.name==="AbortError"||H.message==="Request was aborted")throw Error("Request was aborted")}if(w=H instanceof Error?H:Error(String(H)),O<b&&!w.message.includes("usage limit")){let A=n*2**O;await r(A,Z?.signal);continue}throw w}}if(!L?.ok)throw w??Error("Failed after retries");if(!L.body)throw Error("No response body");if(Y.push({type:"start",partial:F}),await aQ(L,F,Y,Q,Z),Z?.signal?.aborted)throw Error("Request was aborted");Y.push({type:"done",reason:F.stopReason,message:F}),Y.end()}catch(G){for(let V of F.content)delete V.partialJson;F.stopReason=Z?.signal?.aborted?"aborted":"error",F.errorMessage=FQ(GQ(G)),Y.push({type:"error",reason:F.stopReason,error:F}),Y.end()}})(),Y},bZ=(Q,$,Z)=>{let Y=Z?.apiKey;if(!Y)throw Error(`No API key for provider: ${Q.provider}`);let F=YQ(Q,$,Z,Y),G=Z?.reasoning?ZQ(Q,Z.reasoning):void 0;return lQ(Q,$,{...F,reasoningEffort:G==="off"?void 0:G})};function pQ(Q,$,Z){let Y=$Q($,Q.compat?.supportsToolSearch??!1),F=c(Q,$,jQ,{includeSystemPrompt:!1,deferredTools:Y.deferred}),G={model:Q.id,store:!1,stream:!0,instructions:$.systemPrompt||"You are a helpful assistant.",input:F,text:{verbosity:Z?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:VQ(Z?.sessionId),tool_choice:Z?.toolChoice??"auto",parallel_tool_calls:!0};if(Z?.temperature!==void 0)G.temperature=Z.temperature;if(Z?.serviceTier!==void 0)G.service_tier=Z.serviceTier;if(Y.immediate.length>0)G.tools=XQ(Y.immediate,{strict:null});if(Z?.reasoningEffort!==void 0){let V=Z.reasoningEffort==="none"?Q.thinkingLevelMap?.off??"none":Q.thinkingLevelMap?.[Z.reasoningEffort]??Z.reasoningEffort;if(V!==null)G.reasoning={effort:V,summary:Z.reasoningSummary??"auto"}}return G}function dQ(Q,$){switch($){case"flex":return 0.5;case"priority":return Q.id==="gpt-5.5"?2.5:2;default:return 1}}function KQ(Q,$,Z){let Y=dQ(Z,$);if(Y===1)return;Q.cost.input*=Y,Q.cost.output*=Y,Q.cost.cacheRead*=Y,Q.cost.cacheWrite*=Y,Q.cost.total=Q.cost.input+Q.cost.output+Q.cost.cacheRead+Q.cost.cacheWrite}function LQ(Q,$){if(Q==="default"&&($==="flex"||$==="priority"))return $;return Q??$}function DQ(Q){let Z=(Q&&Q.trim().length>0?Q:fQ).replace(/\/+$/,"");if(Z.endsWith("/codex/responses"))return Z;if(Z.endsWith("/codex"))return`${Z}/responses`;return`${Z}/codex/responses`}function iQ(Q){let $=new URL(DQ(Q));if($.protocol==="https:")$.protocol="wss:";if($.protocol==="http:")$.protocol="ws:";return $.toString()}async function aQ(Q,$,Z,Y,F){await l(WQ(oQ(Q,F?.signal)),$,Z,Y,{serviceTier:F?.serviceTier,resolveServiceTier:LQ,applyServiceTierPricing:(G,V)=>KQ(G,V,Y)})}class f extends Error{code;payload;constructor(Q,$){super(Q);this.name="CodexApiError",this.code=$?.code,this.payload=$?.payload,this.cause=$?.cause}}class k extends Error{payload;constructor(Q,$){super(Q);this.name="CodexProtocolError",this.payload=$?.payload,this.cause=$?.cause}}function nQ(Q){return Q instanceof f||Q instanceof k}function rQ(Q){return Q instanceof f&&Q.code===kQ}function tQ(Q){let $=Q.error&&typeof Q.error==="object"?Q.error:void 0;return{code:typeof Q.code==="string"?Q.code:typeof $?.code==="string"?$.code:void 0,message:typeof Q.message==="string"?Q.message:typeof $?.message==="string"?$.message:void 0}}async function*WQ(Q){for await(let $ of Q){let Z=typeof $.type==="string"?$.type:void 0;if(!Z)continue;if(Z==="error"){let{code:Y,message:F}=tQ($);throw new f(`Codex error: ${F||Y||JSON.stringify($)}`,{code:Y,payload:$})}if(Z==="response.failed"){let Y=$.response,F=Y?.error?.code,G=Y?.error?.message;throw new f(G||"Codex response failed",{code:F,payload:$})}if(Z==="response.done"||Z==="response.completed"||Z==="response.incomplete"){let Y=$.response,F=Y?{...Y,status:sQ(Y.status)}:Y;yield{...$,type:"response.completed",response:F};return}yield $}}function sQ(Q){if(typeof Q!=="string")return;return bQ.has(Q)?Q:void 0}async function*oQ(Q,$){if(!Q.body)return;let Z=Q.body.getReader(),Y=new TextDecoder,F="",G=()=>{Z.cancel().catch(()=>{})};$?.addEventListener("abort",G,{once:!0});try{while(!0){if($?.aborted)throw Error("Request was aborted");let{done:V,value:j}=await Z.read();if($?.aborted)throw Error("Request was aborted");if(V)break;F+=Y.decode(j,{stream:!0});let N=F.indexOf(`
3
-
4
- `);while(N!==-1){let X=F.slice(0,N);F=F.slice(N+2);let W=X.split(`
5
- `).filter((J)=>J.startsWith("data:")).map((J)=>J.slice(5).trim());if(W.length>0){let J=W.join(`
6
- `).trim();if(J&&J!=="[DONE]")try{yield JSON.parse(J)}catch(_){throw new k(`Invalid Codex SSE JSON: ${x(_)}`,{cause:_,payload:J})}}N=F.indexOf(`
7
-
8
- `)}}}finally{$?.removeEventListener("abort",G);try{await Z.cancel()}catch{}try{Z.releaseLock()}catch{}}}var eQ="responses_websockets=2026-02-06",QZ=300000,ZZ=3300000,P=new Map,M=new Map,I=new Set;function p(Q){let $=M.get(Q);if(!$)$={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},M.set(Q,$);return $}function gZ(Q){let $=M.get(Q);return $?{...$}:void 0}function vZ(Q){if(Q){M.delete(Q),I.delete(Q);return}M.clear(),I.clear()}function $Z(Q){let $=(Z)=>{if(Z.idleTimer)clearTimeout(Z.idleTimer);U(Z.socket,1000,"debug_close")};if(Q){let Z=P.get(Q);if(Z)$(Z);P.delete(Q);return}for(let Z of P.values())$(Z);P.clear()}NQ($Z);function BQ(Q){return Q?I.has(Q):!1}function s(Q){if(!Q)return;let $=p(Q);$.sseFallbacks++,$.websocketFallbackActive=BQ(Q)}function YZ(Q,$){if(!Q)return;I.add(Q);let Z=p(Q);Z.websocketFailures++,Z.lastWebSocketError=x($),Z.websocketFallbackActive=!0}var y=null;async function GZ(Q){if(!Q&&y)return y;if(typeof process<"u"&&process.versions?.bun){let Z=class extends WebSocket{constructor(Y,F){let G={};if(Array.isArray(F)||typeof F==="string")G={protocols:F};else G={...F};let V=a(Y.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),Q);super(Y,{...G,...V?{proxy:V.toString()}:{}})}};if(!Q)y=Z;return Z}let $=globalThis.WebSocket;if(typeof $!=="function")return null;return $}class qQ extends Error{code;reason;wasClean;constructor(Q,$){super(Q);this.name="WebSocketCloseError",this.code=$?.code,this.reason=$?.reason,this.wasClean=$?.wasClean}}function FZ(Q){let $=Q.readyState;return typeof $==="number"?$:void 0}function h(Q){let $=FZ(Q);return $===void 0||$===1}function VZ(Q){return Date.now()-Q.createdAt>=ZZ}function U(Q,$=1000,Z="done"){try{Q.close($,Z)}catch{}}function o(Q,$){if($.idleTimer)clearTimeout($.idleTimer);$.idleTimer=setTimeout(()=>{if($.busy)return;U($.socket,1000,"idle_timeout"),P.delete(Q)},QZ)}async function m(Q,$,Z,Y=hQ,F){let G=await GZ(F);if(!G)throw Error("WebSocket transport is not available in this runtime");let V=u($);return delete V["OpenAI-Beta"],new Promise((j,N)=>{let X=!1,W,J;try{J=new G(Q,{headers:V})}catch(K){N(K instanceof Error?K:Error(String(K)));return}let _=()=>{if(W)clearTimeout(W),W=void 0;J.removeEventListener("open",q),J.removeEventListener("error",D),J.removeEventListener("close",B),Z?.removeEventListener("abort",R)},z=(K,L)=>{if(X)return;if(X=!0,_(),L)U(J,1000,L);N(K)},q=()=>{if(X)return;X=!0,_(),j(J)},D=(K)=>{z(_Q(K))},B=(K)=>{z(OQ(K))},R=()=>{z(Error("Request was aborted"),"aborted")};if(J.addEventListener("open",q),J.addEventListener("error",D),J.addEventListener("close",B),Z?.addEventListener("abort",R),Y>0)W=setTimeout(()=>{z(Error(`WebSocket connect timeout after ${Y}ms`),"connect_timeout")},Y);if(Z?.aborted)R()})}async function XZ(Q,$,Z,Y,F,G){if(!Z){let X=await m(Q,$,Y,F,G);return{socket:X,reused:!1,release:()=>U(X)}}let V=P.get(Z);if(V){if(V.idleTimer)clearTimeout(V.idleTimer),V.idleTimer=void 0;if(!V.busy&&VZ(V))U(V.socket,1000,"connection_age_limit"),P.delete(Z);else if(!V.busy&&h(V.socket))return V.busy=!0,{socket:V.socket,entry:V,reused:!0,release:({keep:X}={})=>{if(!X||!h(V.socket)){U(V.socket),P.delete(Z);return}V.busy=!1,o(Z,V)}};if(V.busy){let X=await m(Q,$,Y,F,G);return{socket:X,reused:!1,release:()=>{U(X)}}}if(!h(V.socket))U(V.socket),P.delete(Z)}let j=await m(Q,$,Y,F,G),N={socket:j,busy:!0,createdAt:Date.now()};return P.set(Z,N),{socket:j,entry:N,reused:!1,release:({keep:X}={})=>{if(!X||!h(N.socket)){if(U(N.socket),N.idleTimer)clearTimeout(N.idleTimer);if(P.get(Z)===N)P.delete(Z);return}N.busy=!1,o(Z,N)}}}function _Q(Q){if(Q&&typeof Q==="object"){let $="message"in Q?Q.message:void 0;if(typeof $==="string"&&$.length>0)return Error($);let Z="error"in Q?Q.error:void 0;if(Z instanceof Error&&Z.message.length>0)return Z;if(Z&&typeof Z==="object"&&"message"in Z){let Y=Z.message;if(typeof Y==="string"&&Y.length>0)return Error(Y)}}return Error("WebSocket error")}function OQ(Q){if(Q&&typeof Q==="object"){let $="code"in Q?Q.code:void 0,Z="reason"in Q?Q.reason:void 0,Y="wasClean"in Q?Q.wasClean:void 0,F=typeof $==="number"?` ${$}`:"",G=typeof Z==="string"&&Z.length>0?` ${Z}`:"";if(!G&&$===xQ)G=" message too big";return new qQ(`WebSocket closed${F}${G}`.trim(),{code:typeof $==="number"?$:void 0,reason:typeof Z==="string"&&Z.length>0?Z:void 0,wasClean:typeof Y==="boolean"?Y:void 0})}return Error("WebSocket closed")}async function NZ(Q){if(typeof Q==="string")return Q;if(Q instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(Q));if(ArrayBuffer.isView(Q)){let $=Q;return new TextDecoder().decode(new Uint8Array($.buffer,$.byteOffset,$.byteLength))}if(Q&&typeof Q==="object"&&"arrayBuffer"in Q){let Z=await Q.arrayBuffer();return new TextDecoder().decode(new Uint8Array(Z))}return null}async function*JZ(Q,$,Z){let Y=[],F=null,G=!1,V=null,j=!1,N=()=>{if(!F)return;let z=F;F=null,z()},X=(z)=>{(async()=>{let q=null;try{if(!z||typeof z!=="object"||!("data"in z))return;if(q=await NZ(z.data),!q)return;let D=JSON.parse(q),B=typeof D.type==="string"?D.type:"";if(B==="response.completed"||B==="response.done"||B==="response.incomplete")j=!0,G=!0;Y.push(D),N()}catch(D){V=new k(`Invalid Codex WebSocket JSON: ${x(D)}`,{cause:D,payload:q}),G=!0,N()}})()},W=(z)=>{V=_Q(z),G=!0,N()},J=(z)=>{if(j){G=!0,N();return}if(!V)V=OQ(z);G=!0,N()},_=()=>{V=Error("Request was aborted"),G=!0,N()};Q.addEventListener("message",X),Q.addEventListener("error",W),Q.addEventListener("close",J),$?.addEventListener("abort",_);try{while(!0){if($?.aborted)throw Error("Request was aborted");if(Y.length>0){yield Y.shift();continue}if(G)break;let z;await new Promise((q,D)=>{if(F=q,Z!==void 0&&Z>0)z=setTimeout(()=>{let B=Error(`WebSocket idle timeout after ${Z}ms`);V=B,G=!0,F=null,U(Q,1000,"idle_timeout"),D(B)},Z)}).finally(()=>{if(z)clearTimeout(z)})}if(V)throw V;if(!j)throw Error("WebSocket stream closed before response.completed")}finally{Q.removeEventListener("message",X),Q.removeEventListener("error",W),Q.removeEventListener("close",J),$?.removeEventListener("abort",_)}}function e(Q){let{input:$,previous_response_id:Z,...Y}=Q;return Y}function zZ(Q,$){return JSON.stringify(Q??[])===JSON.stringify($??[])}function jZ(Q,$){return JSON.stringify(e(Q))===JSON.stringify(e($))}function KZ(Q,$){if(!jZ(Q,$.lastRequestBody))return;let Z=Q.input??[],Y=[...$.lastRequestBody.input??[],...$.lastResponseItems];if(Z.length<Y.length)return;let F=Z.slice(0,Y.length);if(!zZ(F,Y))return;return Z.slice(Y.length)}function LZ(Q,$){let Z=Q.continuation;if(!Z)return $;let Y=KZ($,Z);if(!Y||!Z.lastResponseId)return Q.continuation=void 0,$;return{...$,previous_response_id:Z.lastResponseId,input:Y}}async function*DZ(Q,$,Z,Y){let F=!1;for await(let G of Q){if(!F)F=!0,Y(),Z.push({type:"start",partial:$});yield G}}async function WZ(Q,$,Z,Y,F,G,V,j,N,X){let{socket:W,entry:J,reused:_,release:z}=await XZ(Q,Z,X?.sessionId,X?.signal,N,X?.env),q=!0,D=X?.transport==="websocket-cached"||X?.transport==="auto",B=$,R=D&&J?LZ(J,B):B,K=X?.sessionId?p(X.sessionId):void 0;if(K){if(K.requests++,_)K.connectionsReused++;else K.connectionsCreated++;if(D)K.cachedContextRequests++;if(R.store===!0)K.storeTrueRequests++;if(K.lastInputItems=R.input?.length??0,R.previous_response_id)K.deltaRequests++,K.lastDeltaInputItems=R.input?.length??0,K.lastPreviousResponseId=R.previous_response_id;else K.fullContextRequests++,K.lastDeltaInputItems=void 0,K.lastPreviousResponseId=void 0}try{if(W.send(JSON.stringify({type:"response.create",...R})),await l(DZ(WQ(JZ(W,X?.signal,j)),Y,F,V),Y,F,G,{serviceTier:X?.serviceTier,resolveServiceTier:LQ,applyServiceTierPricing:(L,w)=>KQ(L,w,G)}),X?.signal?.aborted)q=!1;else if(D&&J&&Y.responseId){let L=c(G,{messages:[Y]},jQ,{includeSystemPrompt:!1}).filter((w)=>w.type!=="function_call_output");J.continuation={lastRequestBody:B,lastResponseId:Y.responseId,lastResponseItems:L}}}catch(L){if(J)J.continuation=void 0;throw q=!1,L}finally{z({keep:q})}}async function BZ(Q){let $=await Q.text(),Z=$||Q.statusText||"Request failed",Y;try{let G=JSON.parse($)?.error;if(G){let V=G.code||G.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(V)||Q.status===429){let j=G.plan_type?` (${G.plan_type.toLowerCase()} plan)`:"",N=G.resets_at?Math.max(0,Math.round((G.resets_at*1000-Date.now())/60000)):void 0,X=N!==void 0?` Try again in ~${N} min.`:"";Y=`You have hit your ChatGPT usage limit${j}.${X}`.trim()}Z=G.message||Y||Z}}catch{}return{message:Z,friendlyMessage:Y}}function qZ(Q){try{let $=Q.split(".");if($.length!==3)throw Error("Invalid token");let Y=JSON.parse(atob($[1]))?.[MQ]?.chatgpt_account_id;if(!Y)throw Error("No account ID in token");return Y}catch{throw Error("Failed to extract accountId from token")}}function _Z(){if(typeof globalThis.crypto?.randomUUID==="function")return globalThis.crypto.randomUUID();return`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function RQ(Q,$,Z,Y){let F=new Headers(Q);for(let[V,j]of Object.entries($||{}))if(j===null)F.delete(V);else F.set(V,j);F.set("Authorization",`Bearer ${Y}`),F.set("chatgpt-account-id",Z),F.set("originator","pi");let G=T?`pi (${T.platform()} ${T.release()}; ${T.arch()})`:"pi (browser)";return F.set("User-Agent",G),F}function OZ(Q,$,Z,Y,F){let G=RQ(Q,$,Z,Y);if(G.set("OpenAI-Beta","responses=experimental"),G.set("accept","text/event-stream"),G.set("content-type","application/json"),F)G.set("session-id",F),G.set("x-client-request-id",F);return G}function RZ(Q,$,Z,Y,F){let G=RQ(Q,$,Z,Y);return G.delete("accept"),G.delete("content-type"),G.delete("OpenAI-Beta"),G.delete("openai-beta"),G.set("OpenAI-Beta",eQ),G.set("x-client-request-id",F),G.set("session-id",F),G}export{bZ as streamSimple,lQ as stream,vZ as resetOpenAICodexWebSocketDebugStats,gZ as getOpenAICodexWebSocketDebugStats,$Z as closeOpenAICodexWebSocketSessions};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{ac as I,bc as z,cc as M,dc as b,ec as B,fc as h}from"./chunk-y2nw8rbx.js";import{gc as v,hc as C}from"./chunk-w3a50kz8.js";import{jc as T}from"./chunk-6a2eb3b5.js";import{mc as G}from"./chunk-amsb41z5.js";import{oc as P}from"./chunk-gn8snrnk.js";import{bf as y,cf as j}from"./chunk-k9w6mk9d.js";import{df as S}from"./chunk-wny0qagx.js";import{Pk as O}from"./chunk-zxpef55w.js";import"./chunk-ws07a9kv.js";var k=0,F=(w,Q,J)=>{let N=new S;return(async()=>{let q={role:"assistant",content:[],api:"google-generative-ai",provider:w.provider,model:w.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let X=J?.apiKey;if(!X)throw Error(`No API key for provider: ${w.provider}`);let $=g(w,X,J?.headers),Y=a(w,Q,J),L=await J?.onPayload?.(Y,w);if(L!==void 0)Y=L;let f=await $.models.generateContentStream(Y);N.push({type:"start",partial:q});let V=null,R=q.content,Z=()=>R.length-1;for await(let _ of f){q.responseId||=_.responseId;let U=_.candidates?.[0];if(U?.content?.parts)for(let W of U.content.parts){if(W.text!==void 0){let D=I(W);if(!V||D&&V.type!=="thinking"||!D&&V.type!=="text"){if(V)if(V.type==="text")N.push({type:"text_end",contentIndex:R.length-1,content:V.text,partial:q});else N.push({type:"thinking_end",contentIndex:Z(),content:V.thinking,partial:q});if(D)V={type:"thinking",thinking:"",thinkingSignature:void 0},q.content.push(V),N.push({type:"thinking_start",contentIndex:Z(),partial:q});else V={type:"text",text:""},q.content.push(V),N.push({type:"text_start",contentIndex:Z(),partial:q})}if(V.type==="thinking")V.thinking+=W.text,V.thinkingSignature=z(V.thinkingSignature,W.thoughtSignature),N.push({type:"thinking_delta",contentIndex:Z(),delta:W.text,partial:q});else V.text+=W.text,V.textSignature=z(V.textSignature,W.thoughtSignature),N.push({type:"text_delta",contentIndex:Z(),delta:W.text,partial:q})}if(W.functionCall){if(V){if(V.type==="text")N.push({type:"text_end",contentIndex:Z(),content:V.text,partial:q});else N.push({type:"thinking_end",contentIndex:Z(),content:V.thinking,partial:q});V=null}let D=W.functionCall.id,A={type:"toolCall",id:!D||q.content.some((K)=>K.type==="toolCall"&&K.id===D)?`${W.functionCall.name}_${Date.now()}_${++k}`:D,name:W.functionCall.name||"",arguments:W.functionCall.args??{},...W.thoughtSignature&&{thoughtSignature:W.thoughtSignature}};q.content.push(A),N.push({type:"toolcall_start",contentIndex:Z(),partial:q}),N.push({type:"toolcall_delta",contentIndex:Z(),delta:JSON.stringify(A.arguments),partial:q}),N.push({type:"toolcall_end",contentIndex:Z(),toolCall:A,partial:q})}}if(U?.finishReason){if(q.stopReason=h(U.finishReason),q.content.some((W)=>W.type==="toolCall"))q.stopReason="toolUse"}if(_.usageMetadata)q.usage={input:(_.usageMetadata.promptTokenCount||0)-(_.usageMetadata.cachedContentTokenCount||0),output:(_.usageMetadata.candidatesTokenCount||0)+(_.usageMetadata.thoughtsTokenCount||0),cacheRead:_.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:_.usageMetadata.thoughtsTokenCount||0,totalTokens:_.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},y(w,q.usage)}if(V)if(V.type==="text")N.push({type:"text_end",contentIndex:Z(),content:V.text,partial:q});else N.push({type:"thinking_end",contentIndex:Z(),content:V.thinking,partial:q});if(J?.signal?.aborted)throw Error("Request was aborted");if(q.stopReason==="aborted"||q.stopReason==="error")throw Error("An unknown error occurred");N.push({type:"done",reason:q.stopReason,message:q}),N.end()}catch(X){for(let $ of q.content)if("index"in $)delete $.index;q.stopReason=J?.signal?.aborted?"aborted":"error",q.errorMessage=C(v(X)),N.push({type:"error",reason:q.stopReason,error:q}),N.end()}})(),N},qq=(w,Q,J)=>{let N=J?.apiKey;if(!N)throw Error(`No API key for provider: ${w.provider}`);let q=T(w,Q,J,N);if(!J?.reasoning)return F(w,Q,{...q,thinking:{enabled:!1}});let X=j(w,J.reasoning),$=X==="off"?"high":X,Y=w;if(H(Y)||x(Y)||E(Y))return F(w,Q,{...q,thinking:{enabled:!0,level:u($,Y)}});return F(w,Q,{...q,thinking:{enabled:!0,budgetTokens:c(Y,$,J.thinkingBudgets)}})};function g(w,Q,J){let N={};if(w.baseUrl)N.baseUrl=w.baseUrl,N.apiVersion="";let q=P({...w.headers,...J});if(q)N.headers=q;return new O({apiKey:Q,httpOptions:Object.keys(N).length>0?N:void 0})}function a(w,Q,J={}){let N=M(w,Q),q={};if(J.temperature!==void 0)q.temperature=J.temperature;if(J.maxTokens!==void 0)q.maxOutputTokens=J.maxTokens;let X={...Object.keys(q).length>0&&q,...Q.systemPrompt&&{systemInstruction:G(Q.systemPrompt)},...Q.tools&&Q.tools.length>0&&{tools:b(Q.tools)}};if(Q.tools&&Q.tools.length>0&&J.toolChoice)X.toolConfig={functionCallingConfig:{mode:B(J.toolChoice)}};else X.toolConfig=void 0;if(J.thinking?.enabled&&w.reasoning){let Y={includeThoughts:!0};if(J.thinking.level!==void 0)Y.thinkingLevel=J.thinking.level;else if(J.thinking.budgetTokens!==void 0)Y.thinkingBudget=J.thinking.budgetTokens;X.thinkingConfig=Y}else if(w.reasoning&&J.thinking&&!J.thinking.enabled)X.thinkingConfig=m(w);if(J.signal){if(J.signal.aborted)throw Error("Request aborted");X.abortSignal=J.signal}return{model:w.id,contents:N,config:X}}function E(w){return/gemma-?4/.test(w.id.toLowerCase())}function H(w){return/gemini-3(?:\.\d+)?-pro/.test(w.id.toLowerCase())}function x(w){let Q=w.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(Q)||Q==="gemini-flash-latest"||Q==="gemini-flash-lite-latest"}function m(w){if(H(w))return{thinkingLevel:"LOW"};if(x(w))return{thinkingLevel:"MINIMAL"};if(E(w))return{thinkingLevel:"MINIMAL"};return{thinkingBudget:0}}function u(w,Q){if(H(Q))switch(w){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(E(Q))switch(w){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(w){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function c(w,Q,J){if(J?.[Q]!==void 0)return J[Q];if(w.id.includes("2.5-pro"))return{minimal:128,low:2048,medium:8192,high:32768}[Q];if(w.id.includes("2.5-flash-lite"))return{minimal:512,low:2048,medium:8192,high:24576}[Q];if(w.id.includes("2.5-flash"))return{minimal:128,low:2048,medium:8192,high:24576}[Q];return-1}export{qq as streamSimple,F as stream};
@@ -1,6 +0,0 @@
1
- // @bun
2
- import{qk as S,rk as I,sk as C}from"./chunk-y9ttm07y.js";import{tk as L}from"./chunk-jm6bxtzt.js";import{Bk as y,Ck as F}from"./chunk-c3fvs0bv.js";import"./chunk-hz31j0hk.js";import{Ek as T}from"./chunk-90et6bwm.js";import{Qk as f,Rk as h,Sk as g}from"./chunk-5zntjzxw.js";import{Tk as O,Vk as A}from"./chunk-vf066xwh.js";import{Wk as E}from"./chunk-qvgc9e08.js";import"./chunk-ws07a9kv.js";function v(Q){if(Q)return Q;if(typeof process<"u"&&process.env.PI_CACHE_RETENTION==="long")return"long";return"short"}function u(Q,Z){let Y=v(Z);if(Y==="none")return{retention:Y};let _=Y==="long"&&z(Q).supportsLongCacheRetention?"1h":void 0;return{retention:Y,cacheControl:{type:"ephemeral",..._&&{ttl:_}}}}var d="2.1.75",p=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],m=new Map(p.map((Q)=>[Q.toLowerCase(),Q])),x=(Q)=>m.get(Q.toLowerCase())??Q,c=(Q,Z)=>{if(Z&&Z.length>0){let Y=Q.toLowerCase(),_=Z.find((X)=>X.name.toLowerCase()===Y);if(_)return _.name}return Q};function M(Q){if(!Q.some((X)=>X.type==="image"))return E(Q.map((X)=>X.text).join(`
3
- `));let Y=Q.map((X)=>{if(X.type==="text")return{type:"text",text:E(X.text)};return{type:"image",source:{type:"base64",media_type:X.mimeType,data:X.data}}});if(!Y.some((X)=>X.type==="text"))Y.unshift({type:"text",text:"(see attached image)"});return Y}var r="fine-grained-tool-streaming-2025-05-14",i="interleaved-thinking-2025-05-14";function z(Q){let Z=Q.provider==="fireworks",Y=Q.provider==="cloudflare-ai-gateway"&&Q.baseUrl.includes("anthropic");return{supportsEagerToolInputStreaming:Q.compat?.supportsEagerToolInputStreaming??!Z,supportsLongCacheRetention:Q.compat?.supportsLongCacheRetention??!Z,sendSessionAffinityHeaders:Q.compat?.sendSessionAffinityHeaders??!!(Z||Y),supportsCacheControlOnTools:Q.compat?.supportsCacheControlOnTools??!Z,allowEmptySignature:Q.compat?.allowEmptySignature??!1}}function H(...Q){let Z={};for(let Y of Q)if(Y)Object.assign(Z,Y);return Z}var l=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function k(Q){if(!Q.event&&Q.data.length===0)return null;let Z={event:Q.event,data:Q.data.join(`
4
- `),raw:[...Q.raw]};return Q.event=null,Q.data=[],Q.raw=[],Z}function w(Q,Z){if(Q==="")return k(Z);if(Z.raw.push(Q),Q.startsWith(":"))return null;let Y=Q.indexOf(":"),_=Y===-1?Q:Q.slice(0,Y),X=Y===-1?"":Q.slice(Y+1);if(X.startsWith(" "))X=X.slice(1);if(_==="event")Z.event=X;else if(_==="data")Z.data.push(X);return null}function a(Q){let Z=Q.indexOf("\r"),Y=Q.indexOf(`
5
- `);if(Z===-1)return Y;if(Y===-1)return Z;return Math.min(Z,Y)}function R(Q){let Z=a(Q);if(Z===-1)return null;let Y=Z+1;if(Q[Z]==="\r"&&Q[Y]===`
6
- `)Y+=1;return{line:Q.slice(0,Z),rest:Q.slice(Y)}}async function*n(Q,Z){let Y=Q.getReader(),_=new TextDecoder,X={event:null,data:[],raw:[]},$="";try{while(!0){if(Z?.aborted)throw Error("Request was aborted");let{value:V,done:N}=await Y.read();if(N)break;$+=_.decode(V,{stream:!0});let D=R($);while(D){$=D.rest;let J=w(D.line,X);if(J)yield J;D=R($)}}$+=_.decode();let W=R($);while(W){$=W.rest;let V=w(W.line,X);if(V)yield V;W=R($)}if($.length>0){let V=w($,X);if(V)yield V}let G=k(X);if(G)yield G}finally{Y.releaseLock()}}async function*s(Q,Z){if(!Q.body)throw Error("Attempted to iterate over an Anthropic response with no body");let Y=!1,_=!1;for await(let X of n(Q.body,Z)){if(X.event==="error")throw Error(X.data);if(!l.has(X.event??""))continue;try{let $=y(X.data);if($.type==="message_start")Y=!0;else if($.type==="message_stop")_=!0;yield $}catch($){let W=$ instanceof Error?$.message:String($);throw Error(`Could not parse Anthropic SSE event ${X.event}: ${W}; data=${X.data}; raw=${X.raw.join("\\n")}`)}}if(Y&&!_)throw Error("Anthropic stream ended before message_stop")}var K=(Q,Z,Y)=>{let _=new A;return(async()=>{let X={role:"assistant",content:[],api:Q.api,provider:Q.provider,model:Q.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let $,W;if(Y?.client)$=Y.client,W=!1;else{let q=Y?.apiKey;if(!q)throw Error(`No API key for provider: ${Q.provider}`);let P;if(Q.provider==="github-copilot"){let b=I(Z.messages);P=C({messages:Z.messages,hasImages:b})}let j=(Y?.cacheRetention??v())==="none"?void 0:Y?.sessionId,B=e(Q,q,Y?.interleavedThinking??!0,ZQ(Q,Z),Y?.headers,P,j);$=B.client,W=B.isOAuthToken}let G=QQ(Q,Z,W,Y),V=await Y?.onPayload?.(G,Q);if(V!==void 0)G=V;let N={...Y?.signal?{signal:Y.signal}:{},...Y?.timeoutMs!==void 0?{timeout:Y.timeoutMs}:{},maxRetries:Y?.maxRetries??0},D=await $.messages.create({...G,stream:!0},N).asResponse();await Y?.onResponse?.({status:D.status,headers:T(D.headers)},Q),_.push({type:"start",partial:X});let J=X.content;for await(let q of s(D,Y?.signal))if(q.type==="message_start")X.responseId=q.message.id,X.usage.input=q.message.usage.input_tokens||0,X.usage.output=q.message.usage.output_tokens||0,X.usage.cacheRead=q.message.usage.cache_read_input_tokens||0,X.usage.cacheWrite=q.message.usage.cache_creation_input_tokens||0,X.usage.totalTokens=X.usage.input+X.usage.output+X.usage.cacheRead+X.usage.cacheWrite,O(Q,X.usage);else if(q.type==="content_block_start"){if(q.content_block.type==="text"){let P={type:"text",text:"",index:q.index};X.content.push(P),_.push({type:"text_start",contentIndex:X.content.length-1,partial:X})}else if(q.content_block.type==="thinking"){let P={type:"thinking",thinking:"",thinkingSignature:"",index:q.index};X.content.push(P),_.push({type:"thinking_start",contentIndex:X.content.length-1,partial:X})}else if(q.content_block.type==="redacted_thinking"){let P={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:q.content_block.data,redacted:!0,index:q.index};X.content.push(P),_.push({type:"thinking_start",contentIndex:X.content.length-1,partial:X})}else if(q.content_block.type==="tool_use"){let P={type:"toolCall",id:q.content_block.id,name:W?c(q.content_block.name,Z.tools):q.content_block.name,arguments:q.content_block.input??{},partialJson:"",index:q.index};X.content.push(P),_.push({type:"toolcall_start",contentIndex:X.content.length-1,partial:X})}}else if(q.type==="content_block_delta"){if(q.delta.type==="text_delta"){let P=J.findIndex((j)=>j.index===q.index),U=J[P];if(U&&U.type==="text")U.text+=q.delta.text,_.push({type:"text_delta",contentIndex:P,delta:q.delta.text,partial:X})}else if(q.delta.type==="thinking_delta"){let P=J.findIndex((j)=>j.index===q.index),U=J[P];if(U&&U.type==="thinking")U.thinking+=q.delta.thinking,_.push({type:"thinking_delta",contentIndex:P,delta:q.delta.thinking,partial:X})}else if(q.delta.type==="input_json_delta"){let P=J.findIndex((j)=>j.index===q.index),U=J[P];if(U&&U.type==="toolCall")U.partialJson+=q.delta.partial_json,U.arguments=F(U.partialJson),_.push({type:"toolcall_delta",contentIndex:P,delta:q.delta.partial_json,partial:X})}else if(q.delta.type==="signature_delta"){let P=J.findIndex((j)=>j.index===q.index),U=J[P];if(U&&U.type==="thinking")U.thinkingSignature=U.thinkingSignature||"",U.thinkingSignature+=q.delta.signature}}else if(q.type==="content_block_stop"){let P=J.findIndex((j)=>j.index===q.index),U=J[P];if(U){if(delete U.index,U.type==="text")_.push({type:"text_end",contentIndex:P,content:U.text,partial:X});else if(U.type==="thinking")_.push({type:"thinking_end",contentIndex:P,content:U.thinking,partial:X});else if(U.type==="toolCall")U.arguments=F(U.partialJson),delete U.partialJson,_.push({type:"toolcall_end",contentIndex:P,toolCall:U,partial:X})}}else if(q.type==="message_delta"){if(q.delta.stop_reason)X.stopReason=$Q(q.delta.stop_reason);if(q.usage.input_tokens!=null)X.usage.input=q.usage.input_tokens;if(q.usage.output_tokens!=null)X.usage.output=q.usage.output_tokens;if(q.usage.cache_read_input_tokens!=null)X.usage.cacheRead=q.usage.cache_read_input_tokens;if(q.usage.cache_creation_input_tokens!=null)X.usage.cacheWrite=q.usage.cache_creation_input_tokens;X.usage.totalTokens=X.usage.input+X.usage.output+X.usage.cacheRead+X.usage.cacheWrite,O(Q,X.usage)}if(Y?.signal?.aborted)throw Error("Request was aborted");if(X.stopReason==="aborted"||X.stopReason==="error")throw Error("An unknown error occurred");_.push({type:"done",reason:X.stopReason,message:X}),_.end()}catch($){for(let W of X.content)delete W.index,delete W.partialJson;X.stopReason=Y?.signal?.aborted?"aborted":"error",X.errorMessage=$ instanceof Error?$.message:JSON.stringify($),_.push({type:"error",reason:X.stopReason,error:X}),_.end()}})(),_};function t(Q,Z){let Y=Z?Q.thinkingLevelMap?.[Z]:void 0;if(typeof Y==="string")return Y;switch(Z){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var EQ=(Q,Z,Y)=>{let _=Y?.apiKey;if(!_)throw Error(`No API key for provider: ${Q.provider}`);let X=f(Q,Y,_);if(!Y?.reasoning)return K(Q,Z,{...X,thinkingEnabled:!1});if(Q.compat?.forceAdaptiveThinking===!0){let W=t(Q,Y.reasoning);return K(Q,Z,{...X,thinkingEnabled:!0,effort:W})}let $=h(X.maxTokens,Q.maxTokens,Y.reasoning,Y.thinkingBudgets);return K(Q,Z,{...X,maxTokens:$.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:$.thinkingBudget})};function o(Q){return Q.includes("sk-ant-oat")}function e(Q,Z,Y,_,X,$,W){let G=Y&&Q.compat?.forceAdaptiveThinking!==!0,V=[];if(_)V.push(r);if(G)V.push(i);if(Q.provider==="cloudflare-ai-gateway")return{client:new L({apiKey:null,authToken:null,baseURL:S(Q),dangerouslyAllowBrowser:!0,defaultHeaders:H({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","cf-aig-authorization":`Bearer ${Z}`,"x-api-key":null,Authorization:null,...V.length>0?{"anthropic-beta":V.join(",")}:{}},Q.headers,X)}),isOAuthToken:!1};if(Q.provider==="github-copilot")return{client:new L({apiKey:null,authToken:Z,baseURL:Q.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:H({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...V.length>0?{"anthropic-beta":V.join(",")}:{}},Q.headers,$,X)}),isOAuthToken:!1};if(o(Z))return{client:new L({apiKey:null,authToken:Z,baseURL:Q.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:H({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":["claude-code-20250219","oauth-2025-04-20",...V].join(","),"user-agent":`claude-cli/${d}`,"x-app":"cli"},Q.headers,X)}),isOAuthToken:!0};let N=W&&z(Q).sendSessionAffinityHeaders?{"x-session-affinity":W}:{};return{client:new L({apiKey:Z,authToken:null,baseURL:Q.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:H({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...V.length>0?{"anthropic-beta":V.join(",")}:{}},N,Q.headers,X)}),isOAuthToken:!1}}function QQ(Q,Z,Y,_){let{cacheControl:X}=u(Q,_?.cacheRetention),$={model:Q.id,messages:YQ(Z.messages,Q,Y,X,z(Q).allowEmptySignature),max_tokens:_?.maxTokens??Q.maxTokens,stream:!0};if(Y){if($.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...X?{cache_control:X}:{}}],Z.systemPrompt)$.system.push({type:"text",text:E(Z.systemPrompt),...X?{cache_control:X}:{}})}else if(Z.systemPrompt)$.system=[{type:"text",text:E(Z.systemPrompt),...X?{cache_control:X}:{}}];if(_?.temperature!==void 0&&!_?.thinkingEnabled)$.temperature=_.temperature;if(Z.tools&&Z.tools.length>0){let W=z(Q);$.tools=_Q(Z.tools,Y,W.supportsEagerToolInputStreaming,W.supportsCacheControlOnTools?X:void 0)}if(Q.reasoning){if(_?.thinkingEnabled){let W=_.thinkingDisplay??"summarized";if(Q.compat?.forceAdaptiveThinking===!0){if($.thinking={type:"adaptive",display:W},_.effort)$.output_config=_.effort==="xhigh"?{effort:_.effort}:{effort:_.effort}}else $.thinking={type:"enabled",budget_tokens:_.thinkingBudgetTokens||1024,display:W}}else if(_?.thinkingEnabled===!1)$.thinking={type:"disabled"}}if(_?.metadata){let W=_.metadata.user_id;if(typeof W==="string")$.metadata={user_id:W}}if(_?.toolChoice)if(typeof _.toolChoice==="string")$.tool_choice={type:_.toolChoice};else $.tool_choice=_.toolChoice;return $}function XQ(Q){return Q.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function YQ(Q,Z,Y,_,X=!1){let $=[],W=g(Q,Z,XQ);for(let G=0;G<W.length;G++){let V=W[G];if(V.role==="user")if(typeof V.content==="string"){if(V.content.trim().length>0)$.push({role:"user",content:E(V.content)})}else{let D=V.content.map((J)=>{if(J.type==="text")return{type:"text",text:E(J.text)};else return{type:"image",source:{type:"base64",media_type:J.mimeType,data:J.data}}}).filter((J)=>{if(J.type==="text")return J.text.trim().length>0;return!0});if(D.length===0)continue;$.push({role:"user",content:D})}else if(V.role==="assistant"){let N=[];for(let D of V.content)if(D.type==="text"){if(D.text.trim().length===0)continue;N.push({type:"text",text:E(D.text)})}else if(D.type==="thinking"){if(D.redacted){N.push({type:"redacted_thinking",data:D.thinkingSignature});continue}if(D.thinking.trim().length===0)continue;if(!D.thinkingSignature||D.thinkingSignature.trim().length===0)N.push(X?{type:"thinking",thinking:E(D.thinking),signature:""}:{type:"text",text:E(D.thinking)});else N.push({type:"thinking",thinking:E(D.thinking),signature:D.thinkingSignature})}else if(D.type==="toolCall")N.push({type:"tool_use",id:D.id,name:Y?x(D.name):D.name,input:D.arguments??{}});if(N.length===0)continue;$.push({role:"assistant",content:N})}else if(V.role==="toolResult"){let N=[];N.push({type:"tool_result",tool_use_id:V.toolCallId,content:M(V.content),is_error:V.isError});let D=G+1;while(D<W.length&&W[D].role==="toolResult"){let J=W[D];N.push({type:"tool_result",tool_use_id:J.toolCallId,content:M(J.content),is_error:J.isError}),D++}G=D-1,$.push({role:"user",content:N})}}if(_&&$.length>0){let G=$[$.length-1];if(G.role==="user"){if(Array.isArray(G.content)){let V=G.content[G.content.length-1];if(V&&(V.type==="text"||V.type==="image"||V.type==="tool_result"))V.cache_control=_}else if(typeof G.content==="string")G.content=[{type:"text",text:G.content,cache_control:_}]}}return $}function ZQ(Q,Z){return!!Z.tools?.length&&!z(Q).supportsEagerToolInputStreaming}function _Q(Q,Z,Y,_){if(!Q)return[];return Q.map((X,$)=>{let W=X.parameters;return{name:Z?x(X.name):X.name,description:X.description,...Y?{eager_input_streaming:!0}:{},input_schema:{type:"object",properties:W.properties??{},required:W.required??[]},..._&&$===Q.length-1?{cache_control:_}:{}}})}function $Q(Q){switch(Q){case"end_turn":return"stop";case"max_tokens":return"length";case"tool_use":return"toolUse";case"refusal":return"error";case"pause_turn":return"stop";case"stop_sequence":return"stop";case"sensitive":return"error";default:throw Error(`Unhandled stop reason: ${Q}`)}}export{EQ as streamSimpleAnthropic,K as streamAnthropic};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{zk as b}from"./chunk-k20bhxed.js";import{Ek as q}from"./chunk-90et6bwm.js";import{Wk as A}from"./chunk-qvgc9e08.js";import"./chunk-ws07a9kv.js";var j=async(f,E,v)=>{let B={api:f.api,provider:f.provider,model:f.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let D=v?.apiKey;if(!D)throw Error(`No API key for provider: ${f.provider}`);let J=L(f,D,v?.headers),G=M(f,E),N=await v?.onPayload?.(G,f);if(N!==void 0)G=N;let F={...v?.signal?{signal:v.signal}:{},...v?.timeoutMs!==void 0?{timeout:v.timeoutMs}:{},maxRetries:v?.maxRetries??0},{data:I,response:_}=await J.chat.completions.create(G,F).withResponse();await v?.onResponse?.({status:_.status,headers:q(_.headers)},f);let Q=I;if(B.responseId=Q.id,Q.usage)B.usage=S(Q.usage,f);let V=Q.choices[0];if(V){let X=V.message.content;if(typeof X==="string"&&X.length>0)B.output.push({type:"text",text:X});for(let Y of V.message.images??[]){let $=typeof Y.image_url==="string"?Y.image_url:Y.image_url?.url;if(!$?.startsWith("data:"))continue;let Z=$.match(/^data:([^;]+);base64,(.+)$/);if(!Z)continue;B.output.push({type:"image",mimeType:Z[1],data:Z[2]})}}return B}catch(D){return B.stopReason=v?.signal?.aborted?"aborted":"error",B.errorMessage=D instanceof Error?D.message:JSON.stringify(D),B}};function L(f,E,v){return new b({apiKey:E,baseURL:f.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{...f.headers,...v}})}function M(f,E){let v=E.input.map((B)=>{if(B.type==="text")return{type:"text",text:A(B.text)};return{type:"image_url",image_url:{url:`data:${B.mimeType};base64,${B.data}`}}});return{model:f.id,messages:[{role:"user",content:v}],stream:!1,modalities:f.output.includes("text")?["image","text"]:["image"]}}function S(f,E){let v=f.prompt_tokens||0,B=f.prompt_tokens_details?.cached_tokens||0,D=f.prompt_tokens_details?.cache_write_tokens||0,J=D>0?Math.max(0,B-D):B,G=Math.max(0,v-J-D),N=f.completion_tokens||0,F={input:G,output:N,cacheRead:J,cacheWrite:D,totalTokens:G+N+J+D,cost:{input:E.cost.input/1e6*G,output:E.cost.output/1e6*N,cacheRead:E.cost.cacheRead/1e6*J,cacheWrite:E.cost.cacheWrite/1e6*D,total:0}};return F.cost.total=F.cost.input+F.cost.output+F.cost.cacheRead+F.cost.cacheWrite,F}export{j as generateImagesOpenRouter};
@@ -1 +0,0 @@
1
- import{g as B}from"./chunk-jstc7pka.js";import"./chunk-rrxjvewm.js";import"./chunk-8e5zvy88.js";import"./chunk-nzy3pjjm.js";import"./chunk-mm1j72a8.js";import"./chunk-9c7fxjej.js";import"./chunk-zhd2mkbr.js";import"./chunk-bdjhb77e.js";import"./chunk-p9xfyqh1.js";import"./chunk-31mjcykb.js";import"./chunk-hfp4hpca.js";import"./chunk-wrz9e73c.js";import"./chunk-1nh6xgek.js";import"./chunk-3rcc5s99.js";import"./chunk-20y3wte3.js";import"./chunk-6t3gdd7e.js";import"./chunk-ejfmxjw6.js";import"./chunk-7y8dng8t.js";import"./chunk-3t7mjvdv.js";import"./chunk-z0ej44ak.js";import"./chunk-tsncwscz.js";import"./chunk-h2wsm7h3.js";import"./chunk-etces6ff.js";import"./chunk-yahb7wan.js";import"./chunk-mahxw48e.js";import"./chunk-wap08p4j.js";import"./chunk-nr89225z.js";import{Ah as w,ih as q}from"./chunk-b1e3tec3.js";import"./chunk-ws07a9kv.js";function O(){let{shareId:C,fileId:D}=k.useParams(),{start:E,version:G,compare:H,cmpLeft:J,cmpRight:K,cmpActive:N}=k.useSearch();return q(B,{shareId:C,initialFileId:D,startTime:E,versionId:G,compare:H,compareLeftId:J,compareRightId:K,compareActiveSide:N})}var k=w("/share/$shareId/files/$fileId")({component:O});export{k as Route};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Fk as T,Gk as A,Hk as G,Ik as C,Jk as I,Kk as M}from"./chunk-8m6zg15c.js";import{Pk as v}from"./chunk-zxpef55w.js";import{Qk as P}from"./chunk-5zntjzxw.js";import{Tk as K,Uk as O,Vk as S}from"./chunk-vf066xwh.js";import{Wk as y}from"./chunk-qvgc9e08.js";import"./chunk-ws07a9kv.js";var B=0,z=(q,V,J)=>{let N=new S;return(async()=>{let w={role:"assistant",content:[],api:"google-generative-ai",provider:q.provider,model:q.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let X=J?.apiKey;if(!X)throw Error(`No API key for provider: ${q.provider}`);let $=x(q,X,J?.headers),Y=f(q,V,J),H=await J?.onPayload?.(Y,q);if(H!==void 0)Y=H;let h=await $.models.generateContentStream(Y);N.push({type:"start",partial:w});let Q=null,R=w.content,Z=()=>R.length-1;for await(let _ of h){w.responseId||=_.responseId;let E=_.candidates?.[0];if(E?.content?.parts)for(let W of E.content.parts){if(W.text!==void 0){let D=T(W);if(!Q||D&&Q.type!=="thinking"||!D&&Q.type!=="text"){if(Q)if(Q.type==="text")N.push({type:"text_end",contentIndex:R.length-1,content:Q.text,partial:w});else N.push({type:"thinking_end",contentIndex:Z(),content:Q.thinking,partial:w});if(D)Q={type:"thinking",thinking:"",thinkingSignature:void 0},w.content.push(Q),N.push({type:"thinking_start",contentIndex:Z(),partial:w});else Q={type:"text",text:""},w.content.push(Q),N.push({type:"text_start",contentIndex:Z(),partial:w})}if(Q.type==="thinking")Q.thinking+=W.text,Q.thinkingSignature=A(Q.thinkingSignature,W.thoughtSignature),N.push({type:"thinking_delta",contentIndex:Z(),delta:W.text,partial:w});else Q.text+=W.text,Q.textSignature=A(Q.textSignature,W.thoughtSignature),N.push({type:"text_delta",contentIndex:Z(),delta:W.text,partial:w})}if(W.functionCall){if(Q){if(Q.type==="text")N.push({type:"text_end",contentIndex:Z(),content:Q.text,partial:w});else N.push({type:"thinking_end",contentIndex:Z(),content:Q.thinking,partial:w});Q=null}let D=W.functionCall.id,U={type:"toolCall",id:!D||w.content.some((j)=>j.type==="toolCall"&&j.id===D)?`${W.functionCall.name}_${Date.now()}_${++B}`:D,name:W.functionCall.name||"",arguments:W.functionCall.args??{},...W.thoughtSignature&&{thoughtSignature:W.thoughtSignature}};w.content.push(U),N.push({type:"toolcall_start",contentIndex:Z(),partial:w}),N.push({type:"toolcall_delta",contentIndex:Z(),delta:JSON.stringify(U.arguments),partial:w}),N.push({type:"toolcall_end",contentIndex:Z(),toolCall:U,partial:w})}}if(E?.finishReason){if(w.stopReason=M(E.finishReason),w.content.some((W)=>W.type==="toolCall"))w.stopReason="toolUse"}if(_.usageMetadata)w.usage={input:(_.usageMetadata.promptTokenCount||0)-(_.usageMetadata.cachedContentTokenCount||0),output:(_.usageMetadata.candidatesTokenCount||0)+(_.usageMetadata.thoughtsTokenCount||0),cacheRead:_.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:_.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},K(q,w.usage)}if(Q)if(Q.type==="text")N.push({type:"text_end",contentIndex:Z(),content:Q.text,partial:w});else N.push({type:"thinking_end",contentIndex:Z(),content:Q.thinking,partial:w});if(J?.signal?.aborted)throw Error("Request was aborted");if(w.stopReason==="aborted"||w.stopReason==="error")throw Error("An unknown error occurred");N.push({type:"done",reason:w.stopReason,message:w}),N.end()}catch(X){for(let $ of w.content)if("index"in $)delete $.index;w.stopReason=J?.signal?.aborted?"aborted":"error",w.errorMessage=X instanceof Error?X.message:JSON.stringify(X),N.push({type:"error",reason:w.stopReason,error:w}),N.end()}})(),N},l=(q,V,J)=>{let N=J?.apiKey;if(!N)throw Error(`No API key for provider: ${q.provider}`);let w=P(q,J,N);if(!J?.reasoning)return z(q,V,{...w,thinking:{enabled:!1}});let X=O(q,J.reasoning),$=X==="off"?"high":X,Y=q;if(L(Y)||b(Y)||F(Y))return z(q,V,{...w,thinking:{enabled:!0,level:g($,Y)}});return z(q,V,{...w,thinking:{enabled:!0,budgetTokens:a(Y,$,J.thinkingBudgets)}})};function x(q,V,J){let N={};if(q.baseUrl)N.baseUrl=q.baseUrl,N.apiVersion="";if(q.headers||J)N.headers={...q.headers,...J};return new v({apiKey:V,httpOptions:Object.keys(N).length>0?N:void 0})}function f(q,V,J={}){let N=G(q,V),w={};if(J.temperature!==void 0)w.temperature=J.temperature;if(J.maxTokens!==void 0)w.maxOutputTokens=J.maxTokens;let X={...Object.keys(w).length>0&&w,...V.systemPrompt&&{systemInstruction:y(V.systemPrompt)},...V.tools&&V.tools.length>0&&{tools:C(V.tools)}};if(V.tools&&V.tools.length>0&&J.toolChoice)X.toolConfig={functionCallingConfig:{mode:I(J.toolChoice)}};else X.toolConfig=void 0;if(J.thinking?.enabled&&q.reasoning){let Y={includeThoughts:!0};if(J.thinking.level!==void 0)Y.thinkingLevel=J.thinking.level;else if(J.thinking.budgetTokens!==void 0)Y.thinkingBudget=J.thinking.budgetTokens;X.thinkingConfig=Y}else if(q.reasoning&&J.thinking&&!J.thinking.enabled)X.thinkingConfig=k(q);if(J.signal){if(J.signal.aborted)throw Error("Request aborted");X.abortSignal=J.signal}return{model:q.id,contents:N,config:X}}function F(q){return/gemma-?4/.test(q.id.toLowerCase())}function L(q){return/gemini-3(?:\.\d+)?-pro/.test(q.id.toLowerCase())}function b(q){return/gemini-3(?:\.\d+)?-flash/.test(q.id.toLowerCase())}function k(q){if(L(q))return{thinkingLevel:"LOW"};if(b(q))return{thinkingLevel:"MINIMAL"};if(F(q))return{thinkingLevel:"MINIMAL"};return{thinkingBudget:0}}function g(q,V){if(L(V))switch(q){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(F(V))switch(q){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(q){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function a(q,V,J){if(J?.[V]!==void 0)return J[V];if(q.id.includes("2.5-pro"))return{minimal:128,low:2048,medium:8192,high:32768}[V];if(q.id.includes("2.5-flash-lite"))return{minimal:512,low:2048,medium:8192,high:24576}[V];if(q.id.includes("2.5-flash"))return{minimal:128,low:2048,medium:8192,high:24576}[V];return-1}export{l as streamSimpleGoogle,z as streamGoogle};
@@ -1 +0,0 @@
1
- import{j as V}from"./chunk-k0a35mg9.js";import"./chunk-qn96vbke.js";import"./chunk-d3s00sn0.js";import"./chunk-8e5zvy88.js";import"./chunk-nzy3pjjm.js";import"./chunk-mm1j72a8.js";import"./chunk-9c7fxjej.js";import"./chunk-zhd2mkbr.js";import"./chunk-bdjhb77e.js";import"./chunk-p9xfyqh1.js";import"./chunk-31mjcykb.js";import"./chunk-hfp4hpca.js";import"./chunk-wrz9e73c.js";import"./chunk-1nh6xgek.js";import"./chunk-3rcc5s99.js";import"./chunk-20y3wte3.js";import{jf as U}from"./chunk-ph3e1bpp.js";import"./chunk-qc6dmzn0.js";import{Bf as N}from"./chunk-ve7v8wtv.js";import"./chunk-7y8dng8t.js";import"./chunk-3t7mjvdv.js";import"./chunk-z0ej44ak.js";import"./chunk-tsncwscz.js";import"./chunk-h2wsm7h3.js";import"./chunk-etces6ff.js";import"./chunk-yahb7wan.js";import"./chunk-mahxw48e.js";import"./chunk-wap08p4j.js";import{bh as K}from"./chunk-nr89225z.js";import{Ah as H,Mh as J,gh as Z,ih as q,nh as B,oh as G}from"./chunk-b1e3tec3.js";import{Xk as Y}from"./chunk-ws07a9kv.js";var W=Y(Z(),1);function _(){let{projectId:h}=$.useParams(),{teamId:v,ensureTeamIdForProject:w}=K();W.useEffect(()=>{w(h)},[h,w]);let{data:A}=G(U(h)),b=A?.rootFolder,{data:X}=B({queryKey:["folders",b],queryFn:()=>(async()=>{return await(await J.api.folders[":folderId"].$get({param:{folderId:b}})).json()})(),enabled:!!b});if(!v||!b||!X)return q(N,{});return q(V,{teamId:v,projectId:h,projectName:A.name??"",assetId:"recently-deleted",rootFolderId:b})}var $=H("/projects/$projectId/recently-deleted")({component:_});export{$ as Route};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Rb as a}from"./chunk-5vqan9c4.js";import"./chunk-ws07a9kv.js";export default a();
@@ -1 +0,0 @@
1
- import{a as d,b as x,c as r,d as D,e as G,f as M}from"./chunk-s7qpj715.js";import{ga as m}from"./chunk-p9xfyqh1.js";import{Wa as p}from"./chunk-31mjcykb.js";import"./chunk-hfp4hpca.js";import"./chunk-20y3wte3.js";import{nf as I}from"./chunk-08mxv0sm.js";import{Bf as g}from"./chunk-ve7v8wtv.js";import{qg as u}from"./chunk-etces6ff.js";import{rg as f}from"./chunk-yahb7wan.js";import{bh as b}from"./chunk-nr89225z.js";import{Ah as L,Mh as N,Qi as S,Wh as h,dk as F,ek as P,fk as T,gh as o,hh as y,ih as q,ik as Y,jh as K,ji as z,ni as C,oh as R,qh as k,vh as v}from"./chunk-b1e3tec3.js";import{Xk as t}from"./chunk-ws07a9kv.js";var Z=t(o(),1);var s=(X)=>{if(!X)return"??";return X.split(" ").map((_)=>_[0]).slice(0,2).join("").toUpperCase()};function e(){let{projectId:X}=qq.useParams(),{teamId:_,ensureTeamIdForProject:E}=b(),j=v();Z.useEffect(()=>{E(X)},[X,E]);let{data:O}=R(I(X)),W=O?.rootFolder,[n,i]=Z.useState(240),{fileListLeftSidebarCollapsed:A,setFileListLeftSidebarCollapsed:c}=u(),{data:B,isLoading:a,fetchNextPage:Q,hasNextPage:V,isFetchingNextPage:U}=k({queryKey:["collections",X],queryFn:async({pageParam:J})=>{let $=await N.api.projects[":projectId"].collections.$get({param:{projectId:X},query:{first:"20",after:J}});if(!$.ok)throw Error("Failed to fetch collections");return await $.json()},initialPageParam:"",getNextPageParam:(J)=>J.pageInfo?.cursor||void 0,enabled:!!X}),{ref:l,inView:H}=f();Z.useEffect(()=>{if(H&&V&&!U)Q()},[H,V,U,Q]);let w=Z.useMemo(()=>B?.pages.flatMap((J)=>J.data)||[],[B]);if(!_||!W||!O)return q(g,{});return q("div",{className:"flex flex-1 flex-col bg-background min-h-0",children:K("div",{className:"flex flex-1 overflow-hidden relative",children:[!A&&q("div",{className:"md:hidden fixed inset-0 bg-black/50 z-40",onClick:()=>c(!0)}),!A&&K(y,{children:[q("div",{className:"bg-background",style:{width:n},children:q(m,{teamId:_,projectId:X,projectName:O.name??"",rootFolderId:W})}),q(p,{onResize:(J)=>{i(($)=>Math.max(180,Math.min(400,$+J)))},className:"hidden md:block"})]}),K("div",{className:"flex-1 flex flex-col min-h-0 bg-card overflow-hidden",children:[q("header",{className:"h-14 border-b flex items-center justify-between px-6 shrink-0 bg-background/50 backdrop-blur-sm sticky top-0 z-10",children:K("div",{className:"flex items-center gap-2",children:[q(z,{className:"h-5 w-5 text-primary"}),q("h1",{className:"font-bold text-lg text-foreground",children:Y.all_collections()})]})}),q("div",{className:"flex-1 overflow-y-auto p-6",children:a?q("div",{className:"flex justify-center items-center h-64",children:q("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}):w.length===0?K("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground gap-3",children:[q(S,{className:"h-10 w-10 text-muted-foreground/50"}),q("p",{children:Y.no_collections_yet()})]}):K("div",{className:"border border-border rounded-xl bg-background overflow-hidden shadow-xs",children:[K(d,{children:[q(x,{children:K(D,{className:"hover:bg-transparent bg-muted/20",children:[q(G,{className:"font-semibold px-4 py-3",children:Y.collection_name()}),q(G,{className:"font-semibold px-4 py-3",children:Y.creator()}),q(G,{className:"font-semibold px-4 py-3 w-[200px]",children:Y.created_date()})]})}),q(r,{children:w.map((J)=>K(D,{className:"hover:bg-muted/10 transition-colors cursor-pointer",onClick:()=>j({to:"/projects/$projectId/collections/$collectionId",params:{projectId:X,collectionId:J.id}}),children:[q(M,{className:"font-medium px-4 py-3.5",children:K("div",{className:"flex items-center gap-2",children:[q(z,{className:"h-4 w-4 text-primary shrink-0"}),q("span",{className:"text-foreground font-semibold hover:underline",children:J.name})]})}),q(M,{className:"px-4 py-3.5",children:K("div",{className:"flex items-center gap-2",children:[K(F,{className:"h-6 w-6",children:[J.creator?.image&&q(P,{src:J.creator.image,alt:J.creator.name,className:"object-cover"}),q(T,{className:"text-[10px]",children:s(J.creator?.name)})]}),q("span",{className:"text-sm font-medium text-foreground truncate max-w-[200px]",children:J.creator?.name||Y.unknown()})]})}),q(M,{className:"px-4 py-3.5 text-muted-foreground text-sm",children:K("div",{className:"flex items-center gap-2",children:[q(C,{className:"h-3.5 w-3.5 text-muted-foreground/70"}),q("span",{children:new Date(J.createdAt).toLocaleDateString()})]})})]},J.id))})]}),q("div",{ref:l,className:"h-10 w-full flex items-center justify-center",children:U&&q(h,{className:"h-6 w-6 animate-spin text-primary"})})]})})]})]})})}var qq=L("/projects/$projectId/collections/")({component:e});export{qq as Route};
@@ -1,3 +0,0 @@
1
- // @bun
2
- function L(G,q,D){return{temperature:q?.temperature,maxTokens:q?.maxTokens,signal:q?.signal,apiKey:D||q?.apiKey,transport:q?.transport,cacheRetention:q?.cacheRetention,sessionId:q?.sessionId,headers:q?.headers,onPayload:q?.onPayload,onResponse:q?.onResponse,timeoutMs:q?.timeoutMs,websocketConnectTimeoutMs:q?.websocketConnectTimeoutMs,maxRetries:q?.maxRetries,maxRetryDelayMs:q?.maxRetryDelayMs,metadata:q?.metadata}}function K(G){return G==="xhigh"?"high":G}function y(G,q,D,N){let _={...{minimal:1024,low:2048,medium:8192,high:16384},...N},O=1024,V=K(D),J=_[V],Q=G===void 0?q:Math.min(G+J,q);if(Q<=J)J=Math.max(0,Q-1024);return{maxTokens:Q,thinkingBudget:J}}function j(G,q){let D=[],N=!1;for(let Y of G){if(Y.type==="image"){if(!N)D.push({type:"text",text:q});N=!0;continue}D.push(Y),N=Y.text===q}return D}function U(G,q){if(q.input.includes("image"))return G;return G.map((D)=>{if(D.role==="user"&&Array.isArray(D.content))return{...D,content:j(D.content,"(image omitted: model does not support images)")};if(D.role==="toolResult")return{...D,content:j(D.content,"(tool image omitted: model does not support images)")};return D})}function W(G,q,D){let N=new Map,_=U(G,q).map((E)=>{if(E.role==="user")return E;if(E.role==="toolResult"){let A=N.get(E.toolCallId);if(A&&A!==E.toolCallId)return{...E,toolCallId:A};return E}if(E.role==="assistant"){let A=E,H=A.provider===q.provider&&A.api===q.api&&A.model===q.id,$=A.content.flatMap((F)=>{if(F.type==="thinking"){if(F.redacted)return H?F:[];if(H&&F.thinkingSignature)return F;if(!F.thinking||F.thinking.trim()==="")return[];if(H)return F;return{type:"text",text:F.thinking}}if(F.type==="text"){if(H)return F;return{type:"text",text:F.text}}if(F.type==="toolCall"){let X=F,Z=X;if(!H&&X.thoughtSignature)Z={...X},delete Z.thoughtSignature;if(!H&&D){let w=D(X.id,q,A);if(w!==X.id)N.set(X.id,w),Z={...Z,id:w}}return Z}return F});return{...A,content:$}}return E}),O=[],V=[],J=new Set,Q=()=>{if(V.length>0){for(let E of V)if(!J.has(E.id))O.push({role:"toolResult",toolCallId:E.id,toolName:E.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});V=[],J=new Set}};for(let E=0;E<_.length;E++){let A=_[E];if(A.role==="assistant"){Q();let H=A;if(H.stopReason==="error"||H.stopReason==="aborted")continue;let $=H.content.filter((F)=>F.type==="toolCall");if($.length>0)V=$,J=new Set;O.push(A)}else if(A.role==="toolResult")J.add(A.toolCallId),O.push(A);else if(A.role==="user")Q(),O.push(A);else O.push(A)}return Q(),O}
3
- export{L as Qk,y as Rk,W as Sk};
@@ -1,3 +0,0 @@
1
- // @bun
2
- function _(q){return q.totalTokens||q.input+q.output+q.cacheRead+q.cacheWrite}function N(q){try{return JSON.stringify(q)??"undefined"}catch{return"[unserializable]"}}function z(q){if(typeof q==="string")return q.length;let G=0;for(let D of q)G+=D.type==="text"?D.text.length:4800;return G}function P(q){return Math.ceil(q.length/4)}function E(q){return Math.ceil(z(q)/4)}function K(q){let G=0;if(q.role==="user")return E(q.content);if(q.role==="toolResult")return E(q.content);for(let D of q.content)if(D.type==="text")G+=D.text.length;else if(D.type==="thinking")G+=D.thinking.length;else G+=D.name.length+N(D.arguments).length;return Math.ceil(G/4)}function h(q){let G=Number.NEGATIVE_INFINITY,D;for(let H=0;H<q.length;H++){let Z=q[H];if(Z.role==="assistant"){let V=Z;if(V.timestamp>=G&&V.stopReason!=="aborted"&&V.stopReason!=="error"&&_(V.usage)>0)D={usage:V.usage,index:H}}G=Math.max(G,Z.timestamp)}return D}function W(q){let G=h(q);if(G){let H=_(G.usage),Z=0;for(let V=G.index+1;V<q.length;V++)Z+=K(q[V]);return{tokens:H+Z,usageTokens:H,trailingTokens:Z,lastUsageIndex:G.index}}let D=0;for(let H of q)D+=K(H);return{tokens:D,usageTokens:0,trailingTokens:D,lastUsageIndex:null}}function B(q){if(!q||q.length===0)return 0;return P(N(q))}function f(q){return Array.isArray(q)}function R(q){if(f(q))return W(q);let G=W(q.messages);if(G.lastUsageIndex!==null){let H=new Set(q.messages.slice(G.lastUsageIndex+1).filter((V)=>V.role==="toolResult").flatMap((V)=>V.addedToolNames??[])),Z=B(q.tools?.filter((V)=>H.has(V.name)));return{tokens:G.tokens+Z,usageTokens:G.usageTokens,trailingTokens:G.trailingTokens+Z,lastUsageIndex:G.lastUsageIndex}}let D=(q.systemPrompt?P(q.systemPrompt):0)+B(q.tools);return{tokens:G.tokens+D,usageTokens:G.usageTokens,trailingTokens:G.trailingTokens+D,lastUsageIndex:G.lastUsageIndex}}var I=4096,v=1;function C(q,G,D){if(q.contextWindow<=0)return Math.max(v,D);let H=q.contextWindow-R(G).tokens-I;return Math.min(D,Math.max(v,H))}function T(q,G,D,H){return{temperature:D?.temperature,maxTokens:C(q,G,D?.maxTokens??q.maxTokens),signal:D?.signal,apiKey:H||D?.apiKey,transport:D?.transport,cacheRetention:D?.cacheRetention,sessionId:D?.sessionId,headers:D?.headers,onPayload:D?.onPayload,onResponse:D?.onResponse,timeoutMs:D?.timeoutMs,websocketConnectTimeoutMs:D?.websocketConnectTimeoutMs,maxRetries:D?.maxRetries,maxRetryDelayMs:D?.maxRetryDelayMs,metadata:D?.metadata,env:D?.env}}function M(q){return q==="xhigh"||q==="max"?"high":q}function p(q,G,D,H){let V={...{minimal:1024,low:2048,medium:8192,high:16384},...H},L=1024,Y=M(D),F=V[Y],j=q===void 0?G:Math.min(q+F,G);if(j<=F)F=Math.max(0,j-1024);return{maxTokens:j,thinkingBudget:F}}function S(q,G){let D=[],H=!1;for(let Z of q){if(Z.type==="image"){if(!H)D.push({type:"text",text:G});H=!0;continue}D.push(Z),H=Z.text===G}return D}function b(q,G){if(G.input.includes("image"))return q;return q.map((D)=>{if(D.role==="user"&&Array.isArray(D.content))return{...D,content:S(D.content,"(image omitted: model does not support images)")};if(D.role==="toolResult")return{...D,content:S(D.content,"(tool image omitted: model does not support images)")};return D})}function k(q,G,D){let H=new Map,Z=q.map((J)=>J.content==null?{...J,content:[]}:J),L=b(Z,G).map((J)=>{if(J.role==="user")return J;if(J.role==="toolResult"){let Q=H.get(J.toolCallId);if(Q&&Q!==J.toolCallId)return{...J,toolCallId:Q};return J}if(J.role==="assistant"){let Q=J,w=Q.provider===G.provider&&Q.api===G.api&&Q.model===G.id,O=Q.content.flatMap(($)=>{if($.type==="thinking"){if($.redacted)return w?$:[];if(w&&$.thinkingSignature)return $;if(!$.thinking||$.thinking.trim()==="")return[];if(w)return $;return{type:"text",text:$.thinking}}if($.type==="text"){if(w)return $;return{type:"text",text:$.text}}if($.type==="toolCall"){let U=$,X=U;if(!w&&U.thoughtSignature)X={...U},delete X.thoughtSignature;if(!w&&D){let A=D(U.id,G,Q);if(A!==U.id)H.set(U.id,A),X={...X,id:A}}return X}return $});return{...Q,content:O}}return J}),Y=[],F=[],j=new Set,y=()=>{if(F.length>0){for(let J of F)if(!j.has(J.id))Y.push({role:"toolResult",toolCallId:J.id,toolName:J.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});F=[],j=new Set}};for(let J=0;J<L.length;J++){let Q=L[J];if(Q.role==="assistant"){y();let w=Q;if(w.stopReason==="error"||w.stopReason==="aborted")continue;let O=w.content.filter(($)=>$.type==="toolCall");if(O.length>0)F=O,j=new Set;Y.push(Q)}else if(Q.role==="toolResult")j.add(Q.toolCallId),Y.push(Q);else if(Q.role==="user")y(),Y.push(Q);else Y.push(Q)}return y(),Y}
3
- export{C as ic,T as jc,p as kc,k as lc};