sera-code 0.1.0 → 0.1.3

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.
@@ -41,6 +41,14 @@ import {
41
41
  policyFromEnv,
42
42
  policyLabel,
43
43
  } from "./approval.ts";
44
+ import {
45
+ isEnabled as autoMemoryOn,
46
+ buildContext,
47
+ hafizaCommand,
48
+ loadData as loadAutoMemory,
49
+ messagesFromEntries,
50
+ summarizeSession,
51
+ } from "./auto-memory.ts";
44
52
  import { BudgetGovernor } from "./budget.ts";
45
53
  import { classifyToolCall } from "./command-policy.ts";
46
54
  import { loadConfig, type SeraConfig } from "./config.ts";
@@ -56,7 +64,7 @@ import { githubYedek } from "./github-yedek.ts";
56
64
  import { GOAL_USAGE, type GoalState, goalNudge, newGoal, parseGoalCommand, shouldContinue } from "./goal.ts";
57
65
  import { buildForkPrompt, buildHandoff, HANDOFF_COMMAND, HANDOFF_NOTIFY_PREFIX, type HandoffEntry } from "./handoff.ts";
58
66
  import { HookRunner, loadHooks, TrustStore } from "./hooks.ts";
59
- import { registerImageTool } from "./image-tool.ts";
67
+ import { registerImageTool, registerStillerCommand } from "./image-tool.ts";
60
68
  import { briefEnabledFromEnv, makeBriefRuntime } from "./intake-brief.ts";
61
69
  import { runIntakeBriefed } from "./intake-hook.ts";
62
70
  import { registerIosBuildTool } from "./ios-build-tool.ts";
@@ -79,6 +87,7 @@ import {
79
87
  } from "./mcp-bridge.ts";
80
88
  import { checkRemoteMcpUrl } from "./mcp-ssrf.ts";
81
89
  import { capMessages, capNoteText, maxMessagesFromEnv } from "./message-cap.ts";
90
+ import { modelLabelSync } from "./model-list.ts";
82
91
  import { NoProgress, noProgressNote, noProgressStop, type TurnInfo } from "./no-progress.ts";
83
92
  import { registerNotebookTool } from "./notebook-tool.ts";
84
93
  import {
@@ -176,7 +185,7 @@ import {
176
185
  wrapUntrusted,
177
186
  } from "./untrusted.ts";
178
187
  import { registerVideoEditTool } from "./video-edit-tool.ts";
179
- import { registerVideoTool } from "./video-tool.ts";
188
+ import { registerVideoTool, resolveSeraToken } from "./video-tool.ts";
180
189
  import { registerWebTools } from "./web-tools.ts";
181
190
  import { registerZeroKnowledge } from "./zk.ts";
182
191
 
@@ -188,13 +197,6 @@ const UNTRUSTED_TAGS = /<<<(SON_)?GUVENILMEZ_ARAC_CIKTISI[^>\n]*(>>>)?/g;
188
197
  * Lives entirely in the extension API - no changes to Pi core.
189
198
  * Load: pi -e packages/sera-core/src/extension.ts (or via the "pi" manifest in package.json)
190
199
  */
191
- const SERA_MODEL_LABELS: Record<string, string> = {
192
- // Sahip 2026-11-15: web/mobil seçicisiyle birebir (Mini, Zen, Sensei; Core kaldırıldı).
193
- "sera-mini": "Mini",
194
- "sera-zen": "Zen",
195
- "sera-max": "Sensei",
196
- };
197
-
198
200
  export default async function seraCore(pi: ExtensionAPI) {
199
201
  // Motor ic degiskenleri (PI_*) kullanici komutlarina gitmez (coding-agent bash.ts SERA_HIDE_SESSION_ENV).
200
202
  process.env.SERA_HIDE_SESSION_ENV ??= "1";
@@ -805,7 +807,7 @@ export default async function seraCore(pi: ExtensionAPI) {
805
807
  // Kimlik (sahip 2026-11-12): "hangi modelsin" sorusu icin modelin Sera adi istemin SONUNDA (onbellek dostu); model env dokmez.
806
808
  {
807
809
  const id = String((ctx as { model?: { id?: string } }).model?.id ?? "");
808
- const label = SERA_MODEL_LABELS[id.replace(/^sera\//, "")];
810
+ const label = modelLabelSync(id);
809
811
  if (label) {
810
812
  const o = opts as { sections?: Record<string, string> };
811
813
  o.sections = { ...(o.sections ?? {}), kimlik: `Sera model: ${label}` };
@@ -853,6 +855,50 @@ export default async function seraCore(pi: ExtensionAPI) {
853
855
 
854
856
  // /limit, /kullanim: kullanim sayfasiyla ayni bilgi (sunucu /api/usage); modele gitmez.
855
857
  registerLimitCommand(pi, regCmd, say);
858
+
859
+ // --- Sera hafızası (web hz* karşılığı; auto-memory.ts): oturum kapanınca özet, yeni oturumda ilgili özet bağlamı.
860
+ // Oturum kapanışı: session_shutdown (quit/new/resume/fork/reload). Bağlam: ilk 2 kullanıcı turunda before_agent_start.
861
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") {
862
+ pi.on("session_shutdown", async (_e, ctx) => {
863
+ try {
864
+ if (!autoMemoryOn(seraHome)) return;
865
+ const sm = ctx.sessionManager;
866
+ const msgs = messagesFromEntries(sm.getEntries());
867
+ if (msgs.length < 4) return;
868
+ const token = await resolveSeraToken(ctx);
869
+ if (!token) return;
870
+ await summarizeSession(
871
+ { id: sm.getSessionId(), title: sm.getSessionName?.() ?? undefined, msgs },
872
+ { token, dir: seraHome },
873
+ AbortSignal.timeout(8000),
874
+ );
875
+ } catch {
876
+ // hafıza asla oturum kapanışını bozmaz
877
+ }
878
+ });
879
+ pi.on("before_agent_start", (event, ctx) => {
880
+ if (event.messageType !== "user" || !autoMemoryOn(seraHome)) return;
881
+ try {
882
+ const prior = messagesFromEntries(ctx.sessionManager.getEntries()).filter((m) => m.r === "u");
883
+ if (prior.length > 2) return;
884
+ const block = buildContext(
885
+ loadAutoMemory(seraHome),
886
+ [...prior.map((m) => m.t), event.prompt].join(" "),
887
+ ctx.sessionManager.getSessionId(),
888
+ );
889
+ if (!block) return;
890
+ const opts = event.systemPromptOptions as { contextFiles?: { path: string; content: string }[] };
891
+ opts.contextFiles = [...(opts.contextFiles ?? []), { path: "sera-hafiza", content: block }];
892
+ } catch {
893
+ // bağlam eklenemezse sessizce geç
894
+ }
895
+ });
896
+ regCmd("hafiza", {
897
+ description: "Sera hafızası: /hafiza | sil <no|hepsi> | kapat | ac",
898
+ handler: async (args, ctx) => say(ctx, hafizaCommand(args, seraHome), "info"),
899
+ });
900
+ }
901
+ registerStillerCommand(regCmd, say);
856
902
  regCmd("bellek", {
857
903
  description: "Sera: kalici notlari listele (bu proje + tum projeler)",
858
904
  handler: async (args, ctx) => {
@@ -216,7 +216,9 @@ export async function globFiles(
216
216
  for await (const rel of walkFiles(root, {
217
217
  signal,
218
218
  deadline: Date.now() + SCAN_TIME_LIMIT_MS,
219
- onStop: () => (timedOut = true),
219
+ onStop: () => {
220
+ timedOut = true;
221
+ },
220
222
  })) {
221
223
  if (!match(rel)) continue;
222
224
  let t = 0;
@@ -276,7 +278,9 @@ export async function grepPath(
276
278
  ? walkFiles(target, {
277
279
  signal: o.signal,
278
280
  deadline: Date.now() + SCAN_TIME_LIMIT_MS,
279
- onStop: () => (timedOut = true),
281
+ onStop: () => {
282
+ timedOut = true;
283
+ },
280
284
  })
281
285
  : [target.slice(root.length + 1)];
282
286
  for await (const rel of files) {
@@ -1,13 +1,14 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
1
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
2
  import { dirname, extname, isAbsolute, join, resolve } from "node:path";
3
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { Type } from "typebox";
5
5
  import { deviceId } from "./device-id.ts";
6
6
  import { rareExposure } from "./exposure.ts";
7
+ import { expandPath, isInside, isSensitivePath, resolveReal } from "./path-guard.ts";
7
8
  import { formatServerError, networkErrorText } from "./server-error.ts";
8
9
 
9
10
  // `image` araci: metin -> gorsel uretimi (Grok Imagine). Web ile AYNI sunucu ucunu kullanir (sera-web/api/image.ts):
10
- // kota (aylik: Mini 10 / Core 50 / Max 100), icerik guvenligi ve harcama kesici sunucuda; CLI yalniz cagirir (web = CLI esitligi).
11
+ // kota (sayilar/plan sunucuda; GET /api/usage media), icerik guvenligi ve harcama kesici sunucuda; CLI yalniz cagirir (web = CLI esitligi).
11
12
  // Gorsel diske kaydedilir, yol yazilir. Yeni modul yalniz arac cagrilinca is yapar (tembel yukleme ilkesi): kayit ucuzdur.
12
13
 
13
14
  export interface ImageOpts {
@@ -17,6 +18,96 @@ export interface ImageOpts {
17
18
  /** Cikti dizini (varsayilan: calisma dizini). */
18
19
  outDir?: string;
19
20
  now?: () => number;
21
+ /** Fotograf (image_path) okuma koku: yalniz bunun icinden okunur (varsayilan: calisma dizini). */
22
+ root?: string;
23
+ }
24
+
25
+ export const MAX_PHOTO_BYTES = 9 * 1024 * 1024;
26
+ const PHOTO_MIME: Record<string, string> = {
27
+ ".jpg": "image/jpeg",
28
+ ".jpeg": "image/jpeg",
29
+ ".png": "image/png",
30
+ ".webp": "image/webp",
31
+ };
32
+
33
+ /** Proje icindeki fotografi okuyup data: URL yapar; proje disi/duyarli/buyuk/desteksiz ise hata atar. */
34
+ export function readPhotoDataUrl(rawPath: string, root: string): string {
35
+ const abs = resolveReal(resolve(root, expandPath(rawPath.trim())));
36
+ if (!isInside(resolveReal(root), abs) || isSensitivePath(abs))
37
+ throw new Error("Fotoğraf proje klasörünün dışında; yalnız proje içindeki dosyalar okunur.");
38
+ const mime = PHOTO_MIME[extname(abs).toLowerCase()];
39
+ if (!mime) throw new Error("Fotoğraf .jpg, .jpeg, .png veya .webp olmalı.");
40
+ let size: number;
41
+ try {
42
+ size = statSync(abs).size;
43
+ } catch {
44
+ throw new Error(`Fotoğraf bulunamadı: ${rawPath}`);
45
+ }
46
+ if (size > MAX_PHOTO_BYTES) throw new Error("Fotoğraf çok büyük (en fazla 9 MB). Küçültüp tekrar dene.");
47
+ return `data:${mime};base64,${readFileSync(abs).toString("base64")}`;
48
+ }
49
+
50
+ export interface ImagePreset {
51
+ id: string;
52
+ label: string;
53
+ group?: string;
54
+ hint?: string;
55
+ arg?: string;
56
+ }
57
+
58
+ /** Komut katalogu (sunucu = tek kaynak, GET /api/image). Asla firlatmaz. */
59
+ export async function fetchImagePresets(
60
+ deps: { fetch?: typeof fetch; baseUrl?: string } = {},
61
+ signal?: AbortSignal,
62
+ ): Promise<{ ok: true; presets: ImagePreset[] } | { ok: false; text: string }> {
63
+ const base = (deps.baseUrl ?? process.env.SERA_WEB_URL ?? "https://ssera.online").replace(/\/+$/, "");
64
+ try {
65
+ const res = await (deps.fetch ?? fetch)(`${base}/api/image`, { signal });
66
+ const j = (await res.json().catch(() => null)) as { presets?: unknown } | null;
67
+ if (!res.ok || !Array.isArray(j?.presets))
68
+ return { ok: false, text: "Görsel komut listesi alınamadı — biraz sonra tekrar dene." };
69
+ const presets = (j.presets as any[])
70
+ .filter((x) => x && typeof x.id === "string" && typeof x.label === "string")
71
+ .map((x) => ({ id: x.id, label: x.label, group: x.group, hint: x.hint, arg: x.arg }) as ImagePreset);
72
+ return { ok: true, presets };
73
+ } catch {
74
+ return { ok: false, text: networkErrorText("Görsel komut listesi") };
75
+ }
76
+ }
77
+
78
+ export function formatImagePresets(presets: ImagePreset[]): string {
79
+ if (!presets.length) return "Şu an görsel komutu yok.";
80
+ const groups = new Map<string, ImagePreset[]>();
81
+ for (const p of presets) {
82
+ const g = p.group || "Diğer";
83
+ groups.set(g, [...(groups.get(g) ?? []), p]);
84
+ }
85
+ const lines: string[] = [];
86
+ for (const [g, items] of groups) {
87
+ lines.push(`${g}:`);
88
+ for (const p of items)
89
+ lines.push(` /${p.id} — ${p.label}${p.hint ? `: ${p.hint}` : ""}${p.arg ? ` (ek metin: ${p.arg})` : ""}`);
90
+ }
91
+ return lines.join("\n");
92
+ }
93
+
94
+ export function registerStillerCommand(
95
+ regCmd: ExtensionAPI["registerCommand"],
96
+ say: (ctx: ExtensionContext, msg: string, level?: "info" | "warning" | "error") => void,
97
+ deps: { fetch?: typeof fetch; baseUrl?: string } = {},
98
+ ): void {
99
+ regCmd("stiller", {
100
+ description: "Sera: fotoğraf stil/görsel komutları (sunucudan liste)",
101
+ handler: async (_args: string, ctx: ExtensionContext) => {
102
+ const r = await fetchImagePresets(deps, ctx.signal);
103
+ if (!r.ok) return say(ctx, `[Sera] ${r.text}`, "warning");
104
+ say(
105
+ ctx,
106
+ `${formatImagePresets(r.presets)}\nKullanım: görevde fotoğraf yolunu ve komutu söyle (image aracı preset + image_path).`,
107
+ "info",
108
+ );
109
+ },
110
+ });
20
111
  }
21
112
 
22
113
  export const IMAGE_ASPECTS = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"] as const;
@@ -41,10 +132,19 @@ export function registerImageTool(pi: ExtensionAPI, opts: ImageOpts = {}): void
41
132
  exposure: rareExposure(),
42
133
  label: "Gorsel uret",
43
134
  description:
44
- "Metinden gorsel uretir (Grok Imagine; web ile ayni kota: aylik Mini 10 / Core 50 / Max 100). Gorseli diske kaydeder ve yolunu dondurur. Hak dolunca sunucu yenilenme tarihini bildirir. `sera login` gerekir. Cinsel/cocuk icerikli istekler reddedilir.",
135
+ "Metinden gorsel uretir (Grok Imagine; web ile ayni kota; hak plana gore sunucuda belirlenir, kalan icin /limit). Gorseli diske kaydeder ve yolunu dondurur. Hak dolunca sunucu yenilenme tarihini bildirir. `sera login` gerekir. Cinsel/cocuk icerikli istekler reddedilir. Hazir komutlar: `preset` (komut id'si; liste sunucudadir, kullaniciya /stiller gosterir) + `image_path` (proje icindeki fotograf yolu) + ops. `arg` (ek metin); bu modda prompt gerekmez.",
45
136
  promptSnippet: "Metinden gorsel uret (prompt, ops. aspect, ops. out) ve dosya yolunu yaz",
46
137
  parameters: Type.Object({
47
- prompt: Type.String({ description: "Gorselin tarifi (en fazla 1500 karakter)" }),
138
+ prompt: Type.Optional(
139
+ Type.String({ description: "Gorselin tarifi (en fazla 1500 karakter); preset kullaniliyorsa gerekmez" }),
140
+ ),
141
+ preset: Type.Optional(
142
+ Type.String({ description: "Hazir komut id'si (liste icin /stiller); image_path ile birlikte" }),
143
+ ),
144
+ image_path: Type.Optional(
145
+ Type.String({ description: "Fotograf yolu (.jpg/.png/.webp, <=9 MB, proje icinden)" }),
146
+ ),
147
+ arg: Type.Optional(Type.String({ description: "Komuta ek metin (ops.)" })),
48
148
  aspect: Type.Optional(Type.String({ description: IMAGE_ASPECTS.join(" | ") })),
49
149
  out: Type.Optional(
50
150
  Type.String({
@@ -56,7 +156,14 @@ export function registerImageTool(pi: ExtensionAPI, opts: ImageOpts = {}): void
56
156
  const doFetch = opts.fetch ?? fetch;
57
157
  const base = (opts.baseUrl ?? process.env.SERA_WEB_URL ?? "https://ssera.online").replace(/\/+$/, "");
58
158
  const p = params as Record<string, any>;
59
- const body = buildImageBody(p);
159
+ const presetId = typeof p.preset === "string" ? p.preset.trim() : "";
160
+ let body: Record<string, unknown>;
161
+ if (presetId) {
162
+ if (typeof p.image_path !== "string" || !p.image_path.trim())
163
+ throw new Error("Önce bir fotoğraf yolu ver (image_path).");
164
+ body = { preset: presetId, image: readPhotoDataUrl(p.image_path, opts.root ?? process.cwd()) };
165
+ if (typeof p.arg === "string" && p.arg.trim()) body.arg = p.arg.trim();
166
+ } else body = buildImageBody(p);
60
167
  const token = opts.token ? opts.token() : process.env.SERA_AUTH_TOKEN || undefined;
61
168
  if (!token) throw new Error(LOGIN_MSG);
62
169
 
@@ -36,8 +36,8 @@ export async function fetchLimitText(deps: LimitDeps, signal?: AbortSignal): Pro
36
36
  }
37
37
 
38
38
  export function registerLimitCommand(
39
- pi: ExtensionAPI,
40
- regCmd: typeof pi.registerCommand,
39
+ _pi: ExtensionAPI,
40
+ regCmd: ExtensionAPI["registerCommand"],
41
41
  say: (ctx: ExtensionContext, msg: string, level?: "info" | "warning" | "error") => void,
42
42
  deps: LimitDeps = {},
43
43
  ): void {
@@ -0,0 +1,108 @@
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+
5
+ // Model listesi TEK KAYNAK = sunucu (sera-web GET /api/v1/models, lib/model-catalog.ts). Sabit liste YOK:
6
+ // 1) sunucudan canli liste, 2) alinamazsa ~/.sera/models-cache.json (son basarili), 3) hic yoksa FALLBACK_MODELS.
7
+ // Sunucu yaniti baglam/fiyat vermez; bunlar yalniz bilinen kimlikler icin FALLBACK_MODELS'ten alinir (yeni kimlik: genel varsayilan).
8
+
9
+ export interface SeraModel {
10
+ id: string;
11
+ name: string;
12
+ context: number;
13
+ out: number;
14
+ price: { in: number; out: number };
15
+ }
16
+
17
+ /** YALNIZ SON CARE YEDEK (ag yok + onbellek yok): sunucu katalogunun (lib/model-catalog.ts) bilinen kopyasi. Normal akista KULLANILMAZ. */
18
+ export const FALLBACK_MODELS: readonly SeraModel[] = [
19
+ { id: "sera-mini", name: "Mini", context: 100_000, out: 16_000, price: { in: 0.15, out: 0.5 } },
20
+ { id: "sera-zen", name: "Zen", context: 1_000_000, out: 16_000, price: { in: 0.1, out: 0.2 } },
21
+ { id: "sera-max", name: "Sensei", context: 200_000, out: 16_000, price: { in: 1.25, out: 4.25 } },
22
+ ];
23
+ const UNKNOWN_DEFAULTS = { context: 128_000, out: 16_000, price: { in: 0, out: 0 } };
24
+
25
+ export function modelCachePath(): string {
26
+ return join(process.env.SERA_MEMORY_DIR || join(homedir(), ".sera"), "models-cache.json");
27
+ }
28
+
29
+ /** Sunucu yanitini (OpenAI uyumlu liste) modellere cevirir; gecersizse bos dizi. */
30
+ export function parseModelList(json: unknown): SeraModel[] {
31
+ const data = (json as { data?: unknown } | null)?.data;
32
+ if (!Array.isArray(data)) return [];
33
+ const out: SeraModel[] = [];
34
+ for (const m of data) {
35
+ const id = typeof (m as { id?: unknown })?.id === "string" ? (m as { id: string }).id : "";
36
+ if (!/^sera-[a-z0-9-]+$/.test(id)) continue;
37
+ const nm = (m as { name?: unknown }).name;
38
+ const name = typeof nm === "string" && nm.trim() ? nm.trim() : id;
39
+ const known = FALLBACK_MODELS.find((f) => f.id === id);
40
+ out.push({
41
+ id,
42
+ name,
43
+ ...(known ? { context: known.context, out: known.out, price: known.price } : UNKNOWN_DEFAULTS),
44
+ });
45
+ }
46
+ return out;
47
+ }
48
+
49
+ export function readModelCache(path = modelCachePath()): SeraModel[] {
50
+ try {
51
+ return parseModelList({ data: (JSON.parse(readFileSync(path, "utf8")) as { data?: unknown }).data });
52
+ } catch {
53
+ return [];
54
+ }
55
+ }
56
+
57
+ function writeModelCache(models: SeraModel[], path: string): void {
58
+ try {
59
+ mkdirSync(dirname(path), { recursive: true });
60
+ const tmp = `${path}.${process.pid}.tmp`;
61
+ writeFileSync(tmp, JSON.stringify({ at: Date.now(), data: models.map((m) => ({ id: m.id, name: m.name })) }));
62
+ renameSync(tmp, path);
63
+ } catch {
64
+ // onbellek yazilamazsa sessizce gec
65
+ }
66
+ }
67
+
68
+ export interface ModelListDeps {
69
+ fetch?: typeof fetch;
70
+ apiUrl?: string;
71
+ cachePath?: string;
72
+ timeoutMs?: number;
73
+ }
74
+
75
+ /** Sunucudan liste; basarisizsa onbellek; o da yoksa son care yedek. Asla firlatmaz. */
76
+ export async function loadModelList(
77
+ deps: ModelListDeps = {},
78
+ ): Promise<{ models: SeraModel[]; source: "server" | "cache" | "fallback" }> {
79
+ const cachePath = deps.cachePath ?? modelCachePath();
80
+ const base = (
81
+ deps.apiUrl ??
82
+ process.env.SERA_API_URL ??
83
+ `${(process.env.SERA_WEB_URL || "https://ssera.online").replace(/\/+$/, "")}/api/v1`
84
+ ).replace(/\/+$/, "");
85
+ try {
86
+ const res = await (deps.fetch ?? fetch)(`${base}/models`, {
87
+ signal: AbortSignal.timeout(deps.timeoutMs ?? 3000),
88
+ });
89
+ if (res.ok) {
90
+ const models = parseModelList(await res.json().catch(() => null));
91
+ if (models.length) {
92
+ writeModelCache(models, cachePath);
93
+ return { models, source: "server" };
94
+ }
95
+ }
96
+ } catch {
97
+ // ag yok: onbellege dus
98
+ }
99
+ const cached = readModelCache(cachePath);
100
+ if (cached.length) return { models: cached, source: "cache" };
101
+ return { models: [...FALLBACK_MODELS], source: "fallback" };
102
+ }
103
+
104
+ /** Kimlik istemi icin ad: onbellek/yedek (senkron, ag yok). */
105
+ export function modelLabelSync(id: string, cachePath?: string): string | undefined {
106
+ const key = id.replace(/^sera\//, "");
107
+ return (readModelCache(cachePath).find((m) => m.id === key) ?? FALLBACK_MODELS.find((m) => m.id === key))?.name;
108
+ }
@@ -358,7 +358,7 @@ export function panoMetni(pano: OfisGorev[], ayrinti = false): string {
358
358
  .join("\n");
359
359
  }
360
360
 
361
- /** Rol → model. Varsayılanlar: çalışan/şef = Mini (2026-11-14: Core kaldırıldı), danışman = Max. Env ile değişir. */
361
+ /** Rol → model. Varsayılanlar: çalışan/şef = Mini (2026-11-14: eski ara paket kaldırıldı), danışman = Max. Env ile değişir. */
362
362
  export function rolModeli(
363
363
  rol: OfisRol,
364
364
  env: Record<string, string | undefined>,
@@ -69,6 +69,25 @@ export function defaultDenyRead(home: string = homedir()): string[] {
69
69
  ];
70
70
  }
71
71
 
72
+ /**
73
+ * Sera'nın KENDİ ve paket araçlarının kimlik DOSYALARI (tek tek dosya — klasör değil). Windows'ta runtime'ın yerleşik dışlaması
74
+ * bunları BİLMİYOR: 2026-11-16 gerçek denemede (srt-win, bu PC) sandbox içinden ~/.local/share/sera-code/auth.json (Sera oturum
75
+ * anahtarı), ~/.npmrc ve ~/.pi/agent/auth.json OKUNABİLDİ; .ssh/.aws/gh/Chrome engelliydi. Tek dosya denyRead profil ağacı
76
+ * ACL yürüyüşü doğurmaz (yalnız o dosya). Var olmayanlar SandboxRunner'da ayıklanır.
77
+ */
78
+ export function credentialFiles(home: string = homedir()): string[] {
79
+ const j = (...p: string[]) => join(home, ...p);
80
+ return [
81
+ j(".local", "share", "sera-code", "auth.json"),
82
+ j(".pi", "agent", "auth.json"),
83
+ j(".pi", "agent", "models.json"),
84
+ j(".npmrc"),
85
+ j(".pypirc"),
86
+ j(".netrc"),
87
+ j(".git-credentials"),
88
+ ];
89
+ }
90
+
72
91
  /** Sandbox açıkken bile asla yazılmaması gereken gizli yollar (allowWrite cwd'yi açsa bile bunlar engellenir). */
73
92
  export const DEFAULT_DENY_WRITE: readonly string[] = [
74
93
  ".env",
@@ -171,7 +190,13 @@ export function buildRuntimeConfig(
171
190
  ): SandboxRuntimeConfig {
172
191
  // Windows: sandbox-runtime kimlik bilgisi depolarını (.ssh .aws .gnupg ... ) KENDİ yerleşik dışlamasıyla korur; ayrıca
173
192
  // denyRead vermek profil ağacında çok pahalı/takılan ACL yürüyüşü doğurur (ölçüldü). Yalnız kullanıcının kendi eki geçer.
174
- const baseRead = (opts.platform ?? process.platform) === "win32" ? [] : defaultDenyRead(opts.home);
193
+ // Linux/macOS: Sera'nın kendi kimlik dosyaları da eklenir. Windows'ta TEK DOSYA bile denyRead sandbox başlatmasını
194
+ // 60 sn+ sürdürüp sandbox'ı KAPATTI (2026-11-16 ölçüm, 2 deneme) → Windows'ta verilmez; oradaki Sera sırları dosyada değil
195
+ // Windows Kimlik Kasası'ndadır (core/util/sera-secret.ts), auth.json yalnız işaret tutar.
196
+ const baseRead =
197
+ (opts.platform ?? process.platform) === "win32"
198
+ ? []
199
+ : [...defaultDenyRead(opts.home), ...credentialFiles(opts.home)];
175
200
  return {
176
201
  filesystem: {
177
202
  allowWrite: uniq([
@@ -280,6 +305,8 @@ export interface RunnerOptions {
280
305
  exists?: (p: string) => boolean;
281
306
  /** initialize() zaman aşımı (ms; vars. 60000). Aşılırsa sandbox yok sayılır + Türkçe neden (donma önleme). */
282
307
  initTimeoutMs?: number;
308
+ /** Ev klasörü (vars. os.homedir(); testler için). */
309
+ home?: string;
283
310
  /** Sandbox'a geçirilecek işaret ortamı kaynağı (vars. process.env; testler için). */
284
311
  env?: Record<string, string | undefined>;
285
312
  }
@@ -322,8 +349,12 @@ export class SandboxRunner {
322
349
  this.platform = opts.platform ?? process.platform;
323
350
  this.loader = opts.loader ?? defaultLoader;
324
351
  this.exists = opts.exists ?? ((p) => existsSync(p));
325
- const rt = buildRuntimeConfig(opts.cwd, cfg, { platform: this.platform });
352
+ const rt = buildRuntimeConfig(opts.cwd, cfg, { platform: this.platform, home: opts.home });
326
353
  rt.filesystem.denyWrite = existingDenyWrite(opts.cwd, rt.filesystem.denyWrite, this.exists);
354
+ // Var olmayan kimlik DOSYASI verilmez (runtime yok yola "taş" yaratabiliyor — denyWrite ile aynı neden). Yalnız
355
+ // credentialFiles süzülür; gizli KLASÖRLER (.ssh .aws ...) eskisi gibi her zaman verilir (davranış değişmez).
356
+ const credSet = new Set(credentialFiles(opts.home));
357
+ rt.filesystem.denyRead = rt.filesystem.denyRead.filter((p) => !credSet.has(p) || this.exists(p));
327
358
  this.rt = rt;
328
359
  this.bash = opts.bashPath;
329
360
  this.initTimeoutMs = opts.initTimeoutMs ?? 60_000;
@@ -25,7 +25,8 @@ const NOUN = new RegExp(
25
25
  "iu",
26
26
  );
27
27
  /** Saf aciklama sorusu: sozlesmeyi YUKLEME. Proje fiili+ismi yoksa zaten yuklenmez. */
28
- const QUESTION_ONLY = /^\s*(nedir|ne demek|nas[ıi]l [cç]al[ıi][sş][ıi]r|what is|how does|explain|a[cç][ıi]kla)(?![\p{L}])/iu;
28
+ const QUESTION_ONLY =
29
+ /^\s*(nedir|ne demek|nas[ıi]l [cç]al[ıi][sş][ıi]r|what is|how does|explain|a[cç][ıi]kla)(?![\p{L}])/iu;
29
30
 
30
31
  /** Niyet: ilk 1500 karakterde bir "yap/yaz/olustur/build..." fiili VE bir proje ismi (program/uygulama/panel/site...). */
31
32
  export function isProjectRequest(text: string): boolean {
@@ -130,7 +130,7 @@ export function registerVideoTool(pi: ExtensionAPI, opts: VideoToolOpts = {}): v
130
130
  exposure: rareExposure(),
131
131
  label: "Video",
132
132
  description:
133
- "Sera video studyosunda yapay zeka ile video uretir (web'deki studyo ile ayni). Core ve ustu uyelik ve `sera login` gerekir. Uretim birkac dakika surer; bitince video baglantisini dondurur.",
133
+ "Sera video studyosunda yapay zeka ile video uretir (web'deki studyo ile ayni). `sera login` gerekir; hak sunucuda uyelige gore belirlenir (dolunca sunucu yenilenme zamanini soyler, /limit). Uretim birkac dakika surer; bitince video baglantisini dondurur.",
134
134
  promptSnippet: "Metinden (ve istege bagli gorsellerden) Sera video studyosunda video uret, video URL'sini al",
135
135
  parameters: Type.Object({
136
136
  prompt: Type.String({ description: "Nasil bir video istendigi (8-3000 karakter)" }),