SLOPSHOPPER

otomatik-devir

Orkestra modu: /otomatik-devir:devir-otonom <görev> yazılan sohbet ana sohbet olur; iş, eşikte devir dosyası yazan iç içe alt sohbetlere tıklamasız ve sırayla…

bandguardcommandtoaststatusprompt
A shopper browsing a rack in a slop shop
Preview could not run: the mod kept running for 20s in the preview session (a hold loop or a long wait); no drawing was captured
README

Claude Code Araçları

Kendi işimde her gün kullandığım Claude Code modları. Kod yazmadan, Claude'a anlatarak yaptırdım; burada herkes için paylaşıyorum.

🎥 Videoda nasıl çalıştıklarını gösterdim: https://youtu.be/-B0hXhOzuUI 🏫 Soru, destek ve yeni araçlar için ücretsiz Skool topluluğu: https://www.skool.com/mustafa-dikmen-ile-yapay-zeka-1691/about

ModNe yapar
otomatik-devirOrkestra modu: /otomatik-devir:devir-otonom <görev> yazdığınız sohbet ana sohbet olur; iş, bağlamı dolunca devam notu yazan iç içe alt sohbetlere tıklamasız ve sırayla bölünür, zincir bitince ana sohbet bir özet yazar. Normal sohbetler devredilmez.
ilerleme-cubuguSüren işin ilerlemesini yazı kutusunun üstünde çubuk olarak gösterir: kaç adımın bittiği, yüzde kaç olduğu ve şu an hangi adımda olunduğu.

"Mod", Claude Code'un içine takılan küçük bir eklentidir. Claude Code'un görünüşünü ve davranışını değiştirir.

Kurulum

Gerekli: Claude Code 2.1.287 veya üstü. Terminalde claude --version yazıp bakın; eskiyse claude update.

Yol 1: Claude'a kurdurun (en kolayı)

Claude Code'u açın ve şu metni olduğu gibi yapıştırın. Komut çalıştırma izni isteyecek, onaylayın.

Şu 3 komutu sırayla çalıştır, başka hiçbir şey kurma veya değiştirme: (1) claude plugin marketplace add muctebadikmen/claude-code-araclari (2) claude plugin install otomatik-devir@muctebadikmen --scope user (3) claude plugin install ilerleme-cubugu@muctebadikmen --scope user. Sonunda claude plugin list çalıştır ve 2 modun da "enabled" olduğunu söyle. Hata olursa dur ve bana hatayı anlat.

Yol 2: Terminalden

claude plugin marketplace add muctebadikmen/claude-code-araclari
claude plugin install otomatik-devir@muctebadikmen --scope user
claude plugin install ilerleme-cubugu@muctebadikmen --scope user
claude plugin list

--scope user "tüm projelerimde geçerli olsun" demektir. Listede ikisini de "enabled" görmelisiniz. Sonra Claude Code'da yeni bir sohbet açın ya da /reload-plugins yazın.

İsterseniz yalnız birini kurabilirsiniz; iki mod birbirinden bağımsız çalışır.

Skill'ler: my-skills

Her gün kullandığım iş akışı skill'leri. Ana sohbet işi yönetir, alt ajanlar işi yapar; durum .workflow/ klasöründe tutulur, böylece iş yeni bir sohbette kaldığı yerden sürer.

SkillNe yapar
my-skill-orchestrateDiğer tüm skill'lerin uyduğu kurallar: işi alt ajanlara dağıtır, .workflow/STATE.md'yi güncel tutar
my-skill-initProjeyi başlatır: STATE.md, AGENTS.md kuralları, .gitignore
my-skill-auditKoddaki gerçek sorunları bulur ve önem sırasına dizer
my-skill-researchKodu ve web'i araştırıp tek bir öneri çıkarır
my-skill-masterplanDoğrulanmış, paralel adımlara bölünmüş plan yazar
my-skill-executePlanı alt ajanlarla uygular, her işi geri dönüşte kontrol eder
my-skill-handoffİlerlemeyi dondurur, yeni sohbet için devam prompt'u yazar
my-skill-shipGizli bilgi taraması, doğrulama, commit ve push

Akışlar: Hata için audit → masterplan → execute → ship. Yeni özellik için research → masterplan → execute → ship. handoff her an kullanılabilir.

Kurmak için:

claude plugin marketplace add muctebadikmen/claude-code-araclari
claude plugin install my-skills@muctebadikmen --scope user

Kullanmak için Claude'a doğrudan yazın: "projeyi başlat", "bu projeyi denetle", "şunu araştır", "bunun planını yap" gibi. Ya da /my-skills:my-skill-audit şeklinde çağırın.

Güncelleme

Modları geliştirdikçe buraya yüklüyorum. Yeni sürümü almak için:

claude plugin marketplace update muctebadikmen
claude plugin update otomatik-devir@muctebadikmen
claude plugin update ilerleme-cubugu@muctebadikmen
claude plugin update my-skills@muctebadikmen

Sonra Claude Code'u yeniden başlatın.

Nasıl kullanılır

otomatik-devir

Sürüm 1.1.0. Otomatik devir artık yalnızca orkestra alt sohbetlerinde çalışır. Normal bir sohbet hiç devredilmez ve Devir: durum satırı göstermez; orada /devir yazarsanız tek satırla burada devir olmadığını söyler. Alt sohbet eşikte devir dosyasını yazar, sıradaki alt sohbeti ana sohbet açar. Devir tıklamasızdır: tek bir kurulum yolu, seçilecek bir mod yok.

Devir sırasında alt ajanları bekleyen tur sonu koruması. Alt sohbette eşik aşılıp devir başladıktan sonra Claude, alt ajanlar ve Workflow'lar çalışırken turu bitirmez; her seferinde en fazla 5 dakikalık beklemelerle bekler ve sonra turu bitirmeyi yeniden dener. Devir yokken ve "Devir hazır" durumunda (dosya yazılmış) çalışan alt ajanlar ve Workflow'lar turun bitmesini engellemez. Arka plan Bash, Monitor ve geliştirme sunucuları hiç beklenmez. Esc bu beklemeyi her zaman durdurur.

Bir alt sohbette devir başlamamışken sistem prompt'una bir bölüm ekler: Claude bağlam büyüdü diye kendi başına devir yapmaz (my-skill-orchestrate/execute'un "uzun sohbet" devri dahil); devri eşikte mod yapar. Alt sohbette modelin kendi başına my-skill-handoff çağırması engellenir. Yeni sohbet açmayı da mod yasaklar: sıradakini ana sohbet açar.

Eşiğe gelince (alt sohbette):

  1. Mod Claude'a turun içinde tek bir talimat verir: elindeki adımı bitir, yeni iş başlatma, devir dosyasını yazdır (my-skill-handoff auto; beceri yoksa modun kendi devir talimatı). Dosyanın başına Kalan: var ya da Kalan: yok satırı konur.
  2. Çalışan alt ajanlar bitene kadar sistem yeni alt ajan, Workflow, Task ya da alt ajana mesaj başlatmayı koda bağlı olarak reddeder (bu yalnızca talimat değil, araç çağrısı reddedilir). Durum satırında Devir: N alt ajan bitiyor görünür.
  3. 30 dakika içinde bitmeyen işleri Claude TaskStop ile durdurur ve devir dosyasında "Yeniden çalıştır" başlığı altında listeler.
  4. Devir dosyası .workflow/handoff/<oturum-kimliği>.md yoluna yazılır. Her sohbetin kendi dosyası olduğu için aynı klasördeki sohbetler birbirinin dosyasını ezmez. Yeni alt sohbete yalnızca bu dosyayı okuması söylenir; eski .workflow/HANDOFF.md ya da STATE.md dosyalarına yönlendirilmez.
  5. Alt sohbet dosyayı yazıp turu bitirir; durum satırında Devir hazır görünür. Sıradaki alt sohbeti ana sohbet açar.

Orkestra modu (v1.1). /otomatik-devir:devir-otonom <görev> yazın; o sohbet ana sohbet olur. Ana sohbet işin kendisini yapmaz: iç içe alt sohbetleri <görev> · 1, · 2 adlarıyla tıklamasız açar ve her birini bekler. Her alt sohbet eşikte devir dosyasını yazar, ana sohbet sıradakini o dosyadan açar. Zincir şu durumlarda durur ve ana sohbet bir özet yazar: Kalan: yok, biten bir alt sohbet, yanıt vermeyi bırakan bir alt sohbet, /devir otonom dur ya da sınır. Sınır varsayılan 100 alt sohbettir; /devir otonom limit <n> ile değişir (1-1000), yalnızca bu zincir için geçerlidir ve zincir sürerken de ayarlanabilir. Esc, çökme ya da yeniden başlatma olursa şeritte Orkestra duraklatıldı: devam etmek için bir mesaj yaz. çıkar; sonraki mesajınız zinciri sürdürür. Her alt sohbet kendi çok adımlı işini my-skill-orchestrate becerisiyle alt ajanlara dağıtır (model seçimi o becerideki yönlendirmeye göre, varsayılan sonnet). Ana sohbette (ya da /otomatik-devir:devir-otonom yazmadan önce o sohbette) yazılan /devir dene alt sohbetlere uygulanır. /devir ac gerekmez: /otomatik-devir:devir-otonom <görev> yazmak yeter. Eşik, sınır ve /devir kapat ana sohbette ya da bir alt sohbette yazılınca yalnızca o zinciri etkiler; başka zincirleri ve normal sohbetleri etkilemez. /devir kapat bu zinciri durdurur: ana sohbet özet yazar, yeni alt sohbet açılmaz, süren alt sohbet devri iptal edilir. Komut listesinde kısa /devir-otonom adı görünmez; /devir ise sohbetin ilk mesajından sonra çıkar (hemen gerekirse önce herhangi bir mesaj yazın).

Mevcut kurulumunuzda eski sürümden kalan otomatik-devir-* zamanlanmış görevleri varsa mod bunları ilk yüklemede bir kez siler (görevlerin çalıştırma sohbetleri arşivlenir; arşivden geri alınabilir) ve eski kayıt anahtarlarını temizler.

KomutNe yapar
/devirDurumu gösterir; normal sohbette tek satırla burada devir olmadığını söyler
/otomatik-devir:devir-otonom <görev>Otonom zinciri başlatır; bu sohbet ana sohbet olur
/devir otonomOrkestra durumunu ve sınırı gösterir
/devir otonom durZinciri şu anki alt sohbetten sonra durdurur
/devir otonom limit <n>Bu zincirin alt sohbet sınırını ayarlar (1-1000, varsayılan 100)
/devir esik 70Bu zincirin alt sohbet eşiğini %70 yapar, ana ya da alt sohbette (1-99, varsayılan 60); başka zincirleri ve sohbetleri etkilemez; normal sohbette hiçbir şey değiştirmez
/devir dene 20Bu sohbetin deneme eşiği; alt sohbette onun, ana sohbette ya da başlatmadan önce yazılınca zincirin alt sohbetlerinin; /devir dene yazınca kaldırır
/devir simdiAlt sohbette devri hemen başlatır; normal sohbette devir yoktur
/devir kapat / /devir acAcil durdurma: yazıldığı zinciri durdurur ve süren alt sohbet devrini iptal eder; başka zincirleri ve sohbetleri etkilemez; normal sohbette hiçbir şey değiştirmez. Yazılmış devir dosyası yerinde kalır. /devir ac hiçbir şey yazmaz, kapatılan ya da biten zinciri sürdürmez: yeni zincir /otomatik-devir:devir-otonom <görev> ile başlar.

v0.x'teki mod ve geçiş komutları v1.0'da kaldırıldı. Eski komutları yazarsanız mod bunu söyleyen bir yanıt verir. Zinciri durdurmak için /devir kapat.

Kendi devir becerisi (my-skill-handoff) olanlarda mod onu kullanır. Olmayanlarda kendi hazır devir talimatını gönderir; ekstra bir şey kurmanız gerekmez.

ilerleme-cubugu

İki kaynaktan çubuk çizer:

  1. Claude'un görev listesi. Claude bir işi adımlara bölüp görev listesi tuttuğunda çubuk kendiliğinden çıkar.
  2. Plan dosyası. PLAN.md, .workflow/PLAN.md, .workflow/STATE.md ya da .workflow/plans/<klasör>/PLAN.md. Kutucuklar (- [x], - [ ]), numaralı adımlar ve - id: T1 biçimli planlar okunur. Plan dosyasının çubuğu o dosyalardan bahseden sohbete bağlanır: mesajınızda PLAN.md ya da STATE.md geçtiğinde ya da Claude bu dosyaları okuyup yazdığında çubuk çıkar. Aynı projede açtığınız alakasız bir sohbette eski plan görünmez.
  3. İlerleme kaydı. Planın klasöründe .workflow/plans/<klasör>/PROGRESS.md varsa adımların durumu oradan okunur: [ ] bekliyor, [~] sürüyor, [x] bitti, [!] engelli, [-] iptal (toplama katılmaz). Kayıt yoksa durum STATE.md'den okunur; oradan da okunamazsa çubukta ⚠ ilerleme kaydı okunamadı uyarısı çıkar.

Videodaki gibi başlatmak için örnek mesaj:

.workflow/PLAN.md ve .workflow/STATE.md: benim için bu formatta bir plan yap ve bu planı uygula. <işin tarifi>

Çubuk tek adım sürüyorsa Şu an: <adım>, birden fazla adım aynı anda sürüyorsa Şu an N iş üzerinde çalışılıyor, hiçbiri sürmüyorsa Sıradaki: <adım> yazar.

Çubuğa tıklarsanız adım listesi açılır: ✓ biten, ● süren, ○ bekleyen.

KomutNe yapar
/ilerleme detayAdım listesini açar / kapatır (çubuğa tıklamak da aynı işi yapar)
/ilerleme gizleÇubuğu gizler
/ilerleme gosterÇubuğu geri getirir

İki mod birlikte çalışır: devirden sonra yeni sohbete yapıştırılan devam prompt'u plan ya da devir dosyalarından (PLAN.md, STATE.md, HANDOFF.md) bahsettiğinde çubuk yeni sohbette de geri gelir. Bahsetmiyorsa Claude o dosyaları okuduğu anda gelir.

Kaldırma

claude plugin uninstall otomatik-devir@muctebadikmen --scope user
claude plugin uninstall ilerleme-cubugu@muctebadikmen --scope user
claude plugin uninstall my-skills@muctebadikmen --scope user
claude plugin marketplace remove muctebadikmen

Güvenlik

Modlar Claude Code'un içinde sizin yetkilerinizle çalışır, bu yüzden kurmadan önce bakmanız doğru. Kodun tamamı bu depoda; modlar/<mod>/hooks/ klasörlerinde okuyabilirsiniz. Depoyu indirip bir modu kendiniz de denetleyebilirsiniz:

claude plugin validate modlar/otomatik-devir
claude plugin validate modlar/ilerleme-cubugu

Çıktı, modun hangi işlemleri yaptığını listeler. İki modun listesinde de ağ çağrısı yoktur. ilerleme-cubugu yalnızca proje klasöründeki plan dosyalarını okur, hiçbir dosyaya yazmaz. otomatik-devir devam notunu Claude'a yazdırır (.workflow/handoff/<oturum-kimliği>.md); kendisi mod açıkken sistem prompt'una devri kendisinin yönettiğini söyleyen bir bölüm ekler, eşikte Claude'un süren turuna talimat ekler, alt ajan ve Workflow başlatmayı eşikten sonra reddeder ve devir sürerken alt ajanlar ya da Workflow'lar çalışıyorsa turun bitmesini engeller. Alt sohbetleri ana sohbetteki Claude'a masaüstü uygulamasının oturum aracıyla (start_session) açtırır. Orkestra modu bu sohbet için get_session çağırır ve küçük JSON kayıtlarını ~/.claude/plugins/data/otomatik-devir/orkestra/ altına yazar. Her zincirin eşiğini, sınırını ve durdurma bayrağını ana sohbetin kimliğiyle anahtarlanan tek bir küçük ayar kaydında tutar (dosya olarak ayar-<kimlik>.json, aynı klasörde); genel esik/acik anahtarları artık kullanılmaz. İlk yüklemede eski sürümün otomatik-devir-* zamanlanmış görevlerini siler.

Bilinen sınırlar

  • otomatik-devir: Alt komutlar Türkçe harfsiz yazılır: esik, simdi (eşik çalışmaz). Tur sonu koruması yalnızca alt ajanları ve Workflow'ları bekler; arka plan Bash, Monitor ve geliştirme sunucuları beklenmez. 30 dakikada bitmeyen alt ajanlar durdurulur ve devir dosyasında "Yeniden çalıştır" olarak kalır.
  • Zincir /otomatik-devir:devir-otonom <görev> ile başlar: komut listesinde kısa /devir-otonom adı görünmez; /devir sohbetin ilk mesajından sonra çıkar.
  • Ana sohbet yazdığınız turun içinde kalmalıdır; tur kapanırsa zincir duraklar.
  • Devir dosyasını yazmadan ve bitmeden çalışmayı bırakan alt sohbet yaklaşık 10 dakikada fark edilir: zincir Orkestra durdu: alt sohbet N yanıt vermiyor ile durur ve ana sohbet özet yazar.
  • Hâlâ çalışırken takılan alt sohbet ana sohbeti bekletir (Esc, sonra /devir otonom dur).
  • Başlatma çağrısının tam ortasında bir çökme aynı alt sohbetin iki kez açılmasına yol açabilir.
  • /devir kapat kendi zincirini ana sohbetin sonraki adımında durdurur; devir dışında çalışan bir alt sohbet o anki turunu bitirir (öldürülmez).
  • Ana sohbetin kendi bağlamı %80'e gelirse zincir sıradaki alt sohbet sınırında bir özetle biter; özet, hazır devir dosyasından yeni bir zincirde nasıl devam edileceğini söyler.
  • Ayarlar zincire özgüdür: bir zincirin eşiği, sınırı ya da durdurması o zincirin ana sohbetinde ya da alt sohbetlerinden birinde yazılmalıdır. Bir alt sohbet devir yaparken durumu Devir hazır görünür; /devir kapat o devri iptal eder ve ana sohbet sonraki adımında durur.
  • ilerleme-cubugu: Plan dosyasını editörde elle değiştirirseniz çubuğun güncellenmesi birkaç saniye sürebilir. Plan çubuğu yalnız o dosyalardan bahseden sohbette görünür. İş bitince çubuk kısa bir süre "✓ Tamamlandı" gösterip kaybolur.
  • Yazı kutusunun üstündeki şerit paylaşılır: iki mod (ve varsa başka modlar) aynı şeride çizer. Başka modun düğmeleri (ör. "Geç / Bekle") her zaman üstte kalır; adım listesi açıkken bile onları ekrandan itmez.

Geliştirenler için

Her modun testleri modlar/<mod>/tests/ içinde. Çalıştırmak için mod klasöründe:

claude plugin test .

Lisans

MIT. Kullanın, değiştirin, paylaşın. Sorun görürseniz bir issue açın ya da Skool topluluğunda yazın.

Source 2 files
hooks/register.tsx 2666 lines
1import { atom, read, update } from 'claude-code'
2import type {
3  AgentInfo,
4  EngineInterface,
5  PromptSubmitInput,
6  PromptSubmitResult,
7  Register,
8  ToolCallArgs,
9} from 'claude-code'
10
11import type {
12  OrkestraAlt,
13  OrkestraAna,
14  OrkestraAyar,
15  OrkestraRecord,
16  OrkestraRole,
17  OtomatikDevirConv,
18  OtomatikDevirPhase,
19} from '../types'
20
21// ---------------------------------------------------------------------------
22// Settings ($.store, across sessions) and the per-conversation record ($.state)
23// ---------------------------------------------------------------------------
24
25const conv = atom({ plugin: 'otomatik-devir', key: 'conv' } as const, null)
26
27const SKILL = 'my-skill-handoff'
28const DEFAULT_THRESHOLD = 60
29
30// Claude desktop's session tools: the continuation runs in a new chat nested
31// under this one (Decision 9: no detach).
32const START_SESSION = 'mcp__ccd_session__start_session'
33const HAND_OFF = 'mcp__ccd_session__hand_off_to_session'
34const TITLE_LIMIT = 59
35const CONTINUE_SUFFIX = ' (devam)'
36const CONTINUE_BACKGROUND =
37  "Önceki sohbet bağlam eşiğine ulaştı; iş otomatik devirle bu yeni sohbete aktarıldı. Bu prompt, kaldığı yerden sürdürülecek iştir: önce onu oku, sonra devam et."
38
39// Subagents in these states still owe the main loop a result (Decision 15:
40// `waiting` never ends by itself, so it is not waited on).
41const ACTIVE_AGENT: ReadonlySet<AgentInfo['status']> = new Set(['pending', 'running'])
42
43/**
44 * Turkish dative suffix for a whole number 1-99 as it is read aloud ("yüzde
45 * altmış'a", "yüzde yetmiş'e", "yüzde elli'ye"): vowel harmony and the
46 * buffer y follow the last spoken word, so a fixed "'a" is wrong for 70, 50...
47 */
48const dative = (n: number): string => {
49  const units = ['', "'e", "'ye", "'e", "'e", "'e", "'ya", "'ye", "'e", "'a"]
50  const tens = ['', "'a", "'ye", "'a", "'a", "'ye", "'a", "'e", "'e", "'a"]
51  const unit = n % 10
52
53  return unit !== 0 ? (units[unit] ?? "'a") : (tens[Math.floor(n / 10) % 10] ?? "'a")
54}
55
56// The v0.4/v0.5 scheduled tasks, deleted once by the v1 cleanup (S11).
57const DELETE_TASK = 'mcp__scheduled-tasks__delete_scheduled_task'
58const LIST_TASKS = 'mcp__scheduled-tasks__list_scheduled_tasks'
59const GET_SESSION = 'mcp__ccd_session_mgmt__get_session'
60// Exactly the mod's own task ids (any folder's): the v0.4 pair `-a`/`-b` and
61// the v0.5 generations `-<gen>a`/`-<gen>b`, so a person's own
62// `otomatik-devir-...` task is left alone.
63const OWN_TASK = /^otomatik-devir-[0-9a-f]{8}-(?:[1-9]\d*)?[ab]$/
64
65const isOwnTask = (id: unknown): id is string => typeof id === 'string' && OWN_TASK.test(id)
66
67// Durable store keys (S2): the running handoff, and the handed-off flag that
68// keeps a second child from ever starting for this session.
69export const HANDED_PREFIX = 'devredildi:'
70export const RUN_PREFIX = 'devir:'
71export const CLEANUP_FLAG = 'temizlik-v1'
72const CLEANUP_LOCK = 'temizlik-kilit'
73export const DRAIN_TIMEOUT_MS = 30 * 60 * 1000
74export const MAX_HANDOFF_BLOCKS = 4
75// Blocks with timeoutText per handoff, and with fileMissingText per turn when the gate is closed.
76const MAX_TIMEOUT_BLOCKS = 2
77export const MAX_MISSING_BLOCKS = 2
78
79/** The per-session handoff file: `<cwd>/.workflow/handoff/<sid>.md`. */
80export const handoffFile = (cwd: string, sid: string): string =>
81  `${cwd.replace(/\/+$/, '')}/.workflow/handoff/${sid}.md`
82
83// ---------------------------------------------------------------------------
84// Texts the model reads (Contract)
85// ---------------------------------------------------------------------------
86
87/**
88 * v1.0.1: the child reads only this handoff's own file, never an older
89 * project-wide handoff or state file (a real child once resumed from a
90 * 13-hour-stale one).
91 */
92const RESUME_ONLY = (file: string): string =>
93  `devam prompt'u yeni sohbete yalnızca ${file} dosyasını okumasını söylesin; başka bir devir ya da durum dosyasına yönlendirmesin`
94
95/** How the handoff file gets written: the skill's inline auto mode, or the built-in steps. */
96const writeStep = (file: string, hasSkill: boolean): string =>
97  hasSkill
98    ? `Skill aracıyla /${SKILL} becerisini \`auto ${file}\` argümanıyla çalıştır (alt ajan yok, soru yok); devir dosyasını o yazar. Dosyadaki ${RESUME_ONLY(file)}.`
99    : `Devir notunu ${file} dosyasına yaz (klasör yoksa oluştur): hedef, yapılanlar, kalanlar, alınan kararlar ve dikkat edilecekler; durdurulan işler varsa "Yeniden çalıştır:" altında. En sona \`## Devam prompt'u\` başlığını koy ve altına yeni sohbetin ilk mesajı olacak devam prompt'unu düz metin olarak yaz; bu ${RESUME_ONLY(file)}.`
100
101const NO_NEW_WORK =
102  "Yeni alt ajan, Workflow, alt ajana mesaj ya da yeni bir iş BAŞLATMA (mod bunları reddeder); çalışan alt ajanların ve Workflow'ların sonuçlarını geldikçe işle."
103
104const START_CALL = `${START_SESSION} aracını bir kez çağır: initiation "user_asked", context "fresh", background = bu sohbetin neden devredildiğini anlatan en az 80 karakter; prompt'u mod devir dosyasından doldurur. cwd, model, effort ve permission_mode verme. Kullanıcı otomatik devri açtı; bu çağrı onun isteğidir. Çağrı reddedilirse yeniden deneme, own_initiative ya da proposal_id ile kart açma: ne yapacağını mod söyler. Başarılı olunca bu sohbete yalnızca yeni sohbetin açıldığını söyleyen tek bir satır yaz.`
105
106/**
107 * (a) The threshold tripped inside a turn the person typed: finish, start
108 * nothing new, write the file, then start the nested child before this turn ends.
109 */
110export const inTurnHandoff = (threshold: number, file: string, hasSkill = true): string =>
111  `Bağlam %${threshold}${dative(threshold)} ulaştı (bağlam sınırı): otomatik devir bu turda yapılacak. Elindeki adımı güvenli bir noktada tamamla (yarım dosya bırakma). ${NO_NEW_WORK} Çalışan iş varken turu bitirmeye çalışırsan mod seni bekletir. Her şey bitince: ${writeStep(file, hasSkill)} Dosya yazılınca turu bitirmeden ${START_CALL}`
112
113/**
114 * (b) The threshold tripped in a turn no person typed (a notification, an
115 * auto-resume): the app refuses start_session there, so the file is written
116 * now and the person's next typed message opens the chat.
117 */
118export const closedTurnHandoff = (threshold: number, file: string, hasSkill = true): string =>
119  `Bağlam %${threshold}${dative(threshold)} ulaştı (bağlam sınırı) ve bu tur kullanıcının yazdığı bir tur değil: yeni sohbet bu turda açılamaz. Elindeki adımı güvenli bir noktada tamamla. ${NO_NEW_WORK} Her şey bitince: ${writeStep(file, hasSkill)} ${START_SESSION} ve ${HAND_OFF} çağırma, kart açma: yeni sohbet kullanıcının bir sonraki mesajıyla açılır. Dosyayı yazınca turu bitir.`
120
121/** Context on the person's typed message while a handoff waits for it (S8). */
122export const nextMessageNote = (file: string, isFileReady: boolean, hasSkill = true): string =>
123  `otomatik-devir: bağlam eşiği geçildi; devir bu mesajla, bu turda yapılacak. Kullanıcının bu mesajındaki isteği bu sohbette YAPMA: yeni sohbetin ilk işi o olacak (mod onu devam prompt'unun altına ekler). ` +
124  (isFileReady
125    ? `Devir dosyası hazır (${file}); yeniden yazma.`
126    : `${NO_NEW_WORK} Her şey bitince: ${writeStep(file, hasSkill)}`) +
127  ` Sonra turu bitirmeden ${START_CALL}`
128
129type Running = { id: string; description: string }[]
130
131const runningList = (running: Running): string =>
132  running.map(work => `${work.id} (${work.description})`).join(', ')
133
134/**
135 * Decision 16: the system-prompt section that tells the model the mod owns the
136 * long-chat handoff. The bare id is accepted at runtime (the engine's section
137 * check wants only a non-empty, unique id).
138 */
139export const LONG_CHAT_SECTION_ID = 'otomatik-devir:long-chat'
140export const longChatNote = (threshold: number): string =>
141  `otomatik-devir bu oturumda açık: devri mod yönetir. Bağlam büyüdü diye kendiliğinden devir yapma, my-skill-handoff çağırma, yeni sohbet ya da devam prompt'u önerme; işe devam et. Bağlam %${threshold}${dative(threshold)} ulaşınca mod talimat verir, o talimata uy. Kullanıcı açıkça devir isterse: /devir simdi.`
142
143/** Stop block while subagents or Workflows run during a handoff (`handoff_running`): wait inside the turn (v1.0.1: only then). */
144export const waitText = (running: Running): string =>
145  `otomatik-devir: turu henüz bitirme; çalışan işler var: ${runningList(running)}. Sonuçlarını bu turun içinde bekle: Bash aracıyla \`perl -e 'select(undef,undef,undef,120)'\` çalıştır (120 saniye; tek bir bekleme en çok 5 dakika olsun), gelen sonuçları işle ve hiçbiri çalışmıyorsa turu yeniden bitirmeyi dene. Yeni alt ajan ya da Workflow başlatma.`
146
147/** Stop block once the drain ran 30 minutes (Decision 4). */
148export const timeoutText = (running: Running): string =>
149  `otomatik-devir: çalışan işler 30 dakikadır bitmedi: ${runningList(running)}. Her birini TaskStop aracıyla durdur ve devir dosyasında "Yeniden çalıştır:" altında listele (kimlik, açıklama, neyin yeniden çalıştırılacağı). Sonra devri tamamla.`
150
151/** Stop block when the handoff file is missing, empty or older than this handoff. */
152export const fileMissingText = (file: string, isOpenTurn: boolean): string =>
153  `otomatik-devir: devir dosyası yok ya da bu devirden eski: ${file}. Turu bitirmeden önce dosyayı yaz (/${SKILL} \`auto ${file}\`, ya da hedef/yapılanlar/kalanlar/kararlar/dikkat ve en sonda \`## Devam prompt'u\`; ${RESUME_ONLY(file)}). ` +
154  (isOpenTurn
155    ? `Sonra turu bitirmeden ${START_SESSION} aracını initiation "user_asked" ve context "fresh" ile bir kez çağır.`
156    : `${START_SESSION} çağırma: yeni sohbet kullanıcının bir sonraki mesajıyla açılır. Dosyayı yazınca turu bitir.`)
157
158/** Stop block in an open typed turn once the file is written. */
159export const START_NOW = `otomatik-devir: devir dosyası hazır. Turu bitirme: şimdi ${START_CALL}`
160
161export const DRAIN_DENY =
162  'otomatik-devir: devir sürüyor; yeni alt ajan, Workflow ya da alt ajana mesaj başlatılamaz. Çalışan işlerin sonuçlarını işle ve devri tamamla.'
163
164/** Decision 16: the model's own my-skill-handoff call is refused while the mod is on. */
165export const SKILL_HANDOFF_DENY =
166  'otomatik-devir açık: devri mod yönetir, eşikte kendisi başlatır. Kendiliğinden devir yapma, işe devam et. Kullanıcı devir isterse: /devir simdi.'
167
168/** A typed message that asks for a handoff itself. */
169const HANDOFF_ASK = /handoff|devir|yeni (sohbet|chat)|new chat|continue in a new/i
170
171export const READY_BAND = 'Devir hazır: bir sonraki mesajınla yeni sohbet açılacak.'
172
173const MACHINE_TURN_DENY = `otomatik-devir: bu tur kullanıcının yazdığı bir tur değil; yeni sohbet bu turda açılamaz. Yeniden deneme, kart açma: kullanıcının bir sonraki mesajı yeni sohbeti açacak. Devir dosyasını yazdıysan turu bitir.`
174const CARD_DENY = `otomatik-devir: devir için kart açma (own_initiative, proposal_id); ${START_SESSION} aracını initiation "user_asked" ile çağır.`
175const HAND_OFF_DENY = `otomatik-devir: devir için ${HAND_OFF} kullanma; devir dosyasını yaz ve ${START_SESSION} aracını initiation "user_asked" ile çağır.`
176const REMOVED_VERB = "v1.0'da kaldırıldı; tek mod otomatik. Kapatmak için: /devir kapat"
177const USAGE = 'Kullanım: /devir [esik <n> | dene <n> | simdi | kapat | ac | otonom [dur | limit <n>]]'
178
179// ---------------------------------------------------------------------------
180// v1.1 orkestra modu (Contract): the main chat starts managed sub-chats one
181// after another and waits for each; a sub-chat hands off by writing its file.
182// ---------------------------------------------------------------------------
183
184/** The prompt-type command that starts a chain (Decision 1), bare and namespaced. */
185export const OTONOM_COMMANDS: readonly string[] = ['devir-otonom', 'otomatik-devir:devir-otonom']
186/** The first line of the command's rendered body (Decision 17). */
187export const OTONOM_MARKER = '<!-- otomatik-devir:otonom -->'
188const OTONOM_LINE = /^\s*\/(otomatik-devir:)?devir-otonom\b/
189
190/** Sub-chats per chain (Decision 18): default, and the clamp of `/devir otonom limit <n>`. */
191export const DEFAULT_LIMIT = 100
192export const LIMIT_MIN = 1
193export const LIMIT_MAX = 1000
194
195/** The integer part of `x`, clamped to LIMIT_MIN-LIMIT_MAX (not a number: DEFAULT_LIMIT). */
196export const clampLimit = (x: number): number =>
197  Number.isNaN(x) ? DEFAULT_LIMIT : Math.min(LIMIT_MAX, Math.max(LIMIT_MIN, Math.trunc(x)))
198
199/** The main chat's system-prompt section (O2); the v1 long-chat note keeps its own id. */
200export const ORKESTRA_SECTION_ID = 'otomatik-devir:orkestra'
201
202/** At a relay point with its own context at this fill or more, the main chat ends the chain (O22). */
203export const MAIN_FULL_PERCENT = 80
204
205/** How the person starts a chain (store-probe.md `TRIGGER: command`). */
206export const START_HINT = '/otomatik-devir:devir-otonom <görev>'
207
208/** The one-line answer of `/devir`, `esik`, `kapat`, `ac` and `simdi` in a normal chat (O20, Decision 22). */
209export const NORMAL_INFO =
210  'Normal sohbet: burada otomatik devir yok, bu sohbet devredilmez ve buradaki ayar hiçbir zinciri değiştirmez. Zincir için ' +
211  START_HINT +
212  ' yaz; eşik ve kapatma o zincirin ana ya da alt sohbetinde ayarlanır.'
213
214/** `/devir dene <n>` in a normal chat: kept in this chat for a chain started here later (Decision 20). */
215export const normalDeneText = (n: number): string =>
216  `Normal sohbet devredilmez. Deneme eşiği %${n} kaydedildi: bu sohbette ${START_HINT} ile başlatılan zincirin alt sohbetleri bunu kullanır.`
217
218/** Appended to the `/devir kapat` reply in a chain (O21). */
219export const KAPAT_CHAIN =
220  'Bu zincir durur: ana sohbet bir sonraki adımda özet yazar, yeni alt sohbet açılmaz; başka sohbetler etkilenmez.'
221
222/** `/devir esik <n>` in a chain (Decision 22). */
223export const chainEsikText = (n: number): string =>
224  `Bu zincirin devir eşiği %${n}: ana sohbet ve alt sohbetleri için geçerli; başka sohbetleri etkilemez.`
225
226/** `/devir ac` in a chain: it writes nothing (Decisions 20, 22). */
227export const AC_CHAIN_OPEN = 'Bu zincir açık; durdurmak için /devir kapat.'
228export const AC_CHAIN_STOPPED = 'Bu zincir durdu ve sürdürülmez; yeni zincir için ' + START_HINT + ' yaz.'
229
230/** The prefix trigger (`orkestra: <görev>`): an undocumented alias of `/devir-otonom`. */
231export const ORKESTRA_RE = /^\s*orkestra:\s*/i
232/** Store key prefix of an orchestration record (backend `store`). */
233export const ORKESTRA_PREFIX = 'orkestra:'
234/** `kimlik:<sid>` = this chat's local id (O16). */
235export const KIMLIK_PREFIX = 'kimlik:'
236/** The managed handoff file's "no remaining work" line (Decision 12). */
237export const NONE_LEFT_RE = /^\s*Kalan:\s*yok\s*$/im
238/** A child whose id the start_session result did not name. */
239export const UNKNOWN_CHILD = 'bilinmiyor'
240/** An in-flight start older than this is a crash mid-start (O4). */
241export const STARTING_STALE_MS = 120_000
242/** Stalled child (O19): checks at least this far apart, this many in a row. */
243export const STALL_GAP_MS = 240_000
244export const STALL_CYCLES = 2
245
246/** Where the records live (store-probe.md `BACKEND: file`: the store is stale across sessions). */
247export const RECORD_BACKEND: 'store' | 'file' = 'file'
248
249const ORKESTRA_DIR = (home: string): string => `${home}/.claude/plugins/data/otomatik-devir/orkestra`
250
251/** An orchestration record's file (backend `file`). */
252export const orkestraRecordFile = (home: string, localId: string): string => `${ORKESTRA_DIR(home)}/${localId}.json`
253
254/** The sub-chat title: the task's first line, whitespace collapsed, cut to 40 chars, + ` · n`. */
255export const childTitle = (task: string, n: number): string => {
256  const head = (task.trim().split(/\r?\n/)[0] ?? '').replace(/\s+/g, ' ').slice(0, 40).trim()
257
258  return `${head === '' ? 'Orkestra' : head} · ${n}`
259}
260
261/** The start instruction for the main chat (O1, O1b, O5 `start`). */
262export const orkestraStartNote = (title: string): string =>
263  `otomatik-devir orkestra: bu sohbet otonom bir zincirin ANA sohbeti. Burada gerçek iş yapma (kod düzenleme, dosya yazma, işi yapan alt ajan yok): işi yönetilen alt sohbetler yapar. Görevi (ya da kullanıcının talimatlarından uyarlanmış kısa bir brifi) alt sohbet 1'in prompt'u olarak ver: ${START_SESSION} aracını bir kez çağır, initiation "user_asked", context "fresh", title "${title}". Sonra otomatik-devir'in notlarına uy (bekle, sıradaki alt sohbeti aç, zincir bitince özet yaz).`
264
265/** The main chat's system-prompt section (O2). */
266export const ORKESTRA_SECTION = (task: string): string =>
267  `otomatik-devir orkestra modu: bu sohbet otonom bir zincirin ana sohbeti. Burada gerçek iş yapma: işi yönetilen alt sohbetler yapar. Senin işin alt sohbetleri ${START_SESSION} ile açmak, beklemek, sıradakini açmak ve zincir bitince kullanıcıya özet yazmak; mod her adımda ne yapacağını söyler. Kendiliğinden devir yapma. Görev: ${task.slice(0, 1000)}`
268
269/** Stop block while the child runs (O5 `wait`, Decision 6); kept short (O22). */
270export const orkestraWaitText = (n: number): string =>
271  `otomatik-devir orkestra: alt sohbet ${n} çalışıyor; turu bitirme. Bash aracıyla \`perl -e 'select(undef,undef,undef,300)'\` çalıştır (5 dakika bekler); Bash aracının timeout parametresini 330000 yap (bu bir araç parametresi, kabuk komutu değil). Sonra turu yeniden bitirmeyi dene; başka iş yapma.`
272
273/** The relay to the next child (O5/O6 `relay`; n = the next child); kept short (O22). */
274export const orkestraRelayText = (n: number, title: string): string =>
275  `otomatik-devir orkestra: alt sohbet ${n - 1} devir dosyasını yazdı. Turu bitirmeden sıradaki alt sohbeti (${n}) aç: ${START_SESSION} aracını bir kez çağır, initiation "user_asked", context "fresh", title "${title}"; prompt tek satır olsun, gerisini mod doldurur (devir dosyası).`
276
277/** Why a chain ended (types/index.d.ts `OrkestraEnd`). */
278type EndKind = NonNullable<OrkestraAna['ended']>
279
280/** The chain is over (O5/O6 `end`, O19 `durdu`): the main chat summarises and opens nothing. */
281export const orkestraEndText = (
282  kind: EndKind,
283  n: number,
284  report?: string,
285  file?: string,
286  childId?: string,
287  limit?: number,
288): string => {
289  const reasons: Record<EndKind, string> = {
290    bitti: 'zincir bitti, kalan iş yok',
291    sinir: `zincir sınır ${limit ?? DEFAULT_LIMIT} alt sohbete ulaştı`,
292    durduruldu: 'zincir kullanıcının isteğiyle durduruldu (/devir otonom dur)',
293    durdu: `alt sohbet ${n} yanıt vermiyor (${childId ?? UNKNOWN_CHILD}); zincir durdu`,
294    kapatildi: 'otomatik devir kapatıldı (/devir kapat); zincir durdu',
295    dolu: `ana sohbet dolu (bağlam %${MAIN_FULL_PERCENT} ya da fazlası); zincir burada bitiyor`,
296  }
297  const where =
298    (file === undefined ? '' : ` Kalan iş için son devir dosyası: ${file}.`) +
299    (kind === 'dolu'
300      ? ` Kullanıcıya söyle: devam etmek için yeni bir sohbette ${START_HINT} yazsın, görev olarak "${file ?? 'son devir dosyası'} dosyasından devam et".`
301      : '')
302  const what =
303    report !== undefined && report.trim() !== ''
304      ? ` Son alt sohbetin raporu:\n${report}\n`
305      : ` Son alt sohbetin ne yaptığını mcp__ccd_session_mgmt__list_events ile oku (session_id ${childId ?? UNKNOWN_CHILD}).`
306
307  return `otomatik-devir orkestra: ${reasons[kind]}. Bu zincirde ${n} alt sohbet açıldı.${where}${what} Kullanıcıya kısa bir özet yaz (ne yapıldı, ne kaldı); yeni sohbet açma, özeti yazınca turu bitir.`
308}
309
310/** The status line and band of a stalled chain (O19). */
311export const orkestraStalledBand = (n: number): string => `Orkestra durdu: alt sohbet ${n} yanıt vermiyor`
312
313export const ORKESTRA_END_DENY =
314  'otomatik-devir orkestra: zincir bitti; yeni sohbet açma. Kullanıcıya özet yaz ve turu bitir.'
315
316/** Context on a typed message in a live main chat (O7). */
317export const orkestraResumeNote = (n: number, state: string): string =>
318  `otomatik-devir: orkestra devam ediyor (alt sohbet ${n}: ${state}). Kullanıcının bu mesajındaki işi burada YAPMA: mod onu sıradaki alt sohbete not olarak iletir. otomatik-devir'in notlarına uy: bekle ya da sıradaki alt sohbeti aç.`
319
320/** Appended to every child's prompt (O4). */
321export const managedChildNote = (n: number, limit: number): string =>
322  `\n\n## otomatik-devir\nBu sohbet otonom bir zincirin yönetilen alt sohbeti (${n}/${limit}). Kullanıcıya soru sorma, onay bekleme: kararları kendin ver ve gerekçesini yaz. Yeni sohbet açma, kendiliğinden devir yapma: bağlam eşiğe ulaşınca mod talimat verir. Çok adımlı işi my-skill-orchestrate becerisiyle alt ajanlara dağıt; model seçimi o becerideki yönlendirmeye göre (varsayılan sonnet). İş bitince sonucu kısaca raporla.`
323
324/** A managed sub-chat's handoff (O12): the file only, the main chat starts the next one. */
325export const managedHandoff = (threshold: number, file: string, hasSkill = true): string =>
326  `Bağlam %${threshold}${dative(threshold)} ulaştı (bağlam sınırı): bu yönetilen alt sohbet devredilecek. Elindeki adımı güvenli bir noktada tamamla (yarım dosya bırakma). ${NO_NEW_WORK} Her şey bitince: ${writeStep(file, hasSkill)} Dosyanın en üstünde tek satır olsun: iş tamamen bittiyse \`Kalan: yok\`, kalan iş varsa \`Kalan: var\`. ${START_SESSION} ve ${HAND_OFF} çağırma, kart açma: sıradaki sohbeti ana sohbet açar. Dosyayı yazınca turu bitir.`
327
328export const MANAGED_START_DENY =
329  'otomatik-devir orkestra: bu yönetilen bir alt sohbet; yeni sohbet açma. Devir dosyasını yaz ve turu bitir; sıradakini ana sohbet açar.'
330
331export const ORKESTRA_PAUSED_BAND = 'Orkestra duraklatıldı: devam etmek için bir mesaj yaz.'
332export const ORKESTRA_PAUSED_DENY =
333  'otomatik-devir orkestra: zincir duraklatıldı (ana sohbetin turu kapandı); yeni alt sohbet şimdi açılamaz. Turu bitir: kullanıcının bir sonraki mesajı zinciri sürdürür.'
334
335export const orkestraBusyDeny = (n: number): string =>
336  `otomatik-devir orkestra: alt sohbet ${n} çalışıyor ya da açılıyor; ikinci kez açma. Bekle: sıradakini ne zaman açacağını mod söyler.`
337
338// O4 answers a start at the chain's limit with orkestraCapDeny(limit), and a
339// chain that ended there (`sinir`) with orkestraCapDeny too: it names the verb
340// that raises the limit.
341export const orkestraCapDeny = (limit: number): string =>
342  `otomatik-devir orkestra: zincir sınırına (${limit} alt sohbet) ulaşıldı; yeni sohbet açma. Sınırı kullanıcı /devir otonom limit <n> ile yükseltebilir. Kullanıcıya özet yaz ve turu bitir.`
343
344/** The child's background when the model's own is shorter than 80 chars (O4). */
345export const ORKESTRA_BACKGROUND =
346  "Otonom bir zincirin (otomatik-devir orkestra modu) yönetilen alt sohbeti: iş ana sohbetten ya da önceki alt sohbetin devir dosyasından devralındı. Prompt'u oku ve işe devam et."
347
348// ---------------------------------------------------------------------------
349// Records under BACKEND file (O16, Decision 10): JSON files read and written
350// with $.fs. $.fs has no rename, so a reader can catch a file mid-write: an
351// existing file that does not parse is read once more at once, and still
352// unparsable it is "not readable now" (`torn`), never "missing".
353// ---------------------------------------------------------------------------
354
355type FileRead = { kind: 'ok'; value: Record<string, unknown> } | { kind: 'missing' } | { kind: 'torn' }
356
357const readJsonFile = async ($: EngineInterface, path: string | undefined): Promise<FileRead> => {
358  if (path === undefined) return { kind: 'missing' }
359  for (let attempt = 0; attempt < 2; attempt += 1) {
360    let text: string
361    try {
362      text = await $.fs.read(path)
363    } catch {
364      return { kind: 'missing' }
365    }
366    try {
367      const got = record(JSON.parse(text))
368      if (got !== undefined) return { kind: 'ok', value: got }
369    } catch {
370      // cut or empty JSON: read it once more
371    }
372  }
373
374  return { kind: 'torn' }
375}
376
377const homeOf = async ($: EngineInterface): Promise<string | undefined> => nonEmpty(await $.env.get('HOME'))
378
379/** Store key prefix of a chain's settings (backend `store`); not `zincir:`, which the v1 cleanup deletes. */
380export const ZINCIR_AYAR_PREFIX = 'ayar:'
381
382/** A chain's settings file (backend `file`), keyed by its main chat's local id. */
383export const zincirAyarFile = (home: string, localId: string): string => `${ORKESTRA_DIR(home)}/ayar-${localId}.json`
384
385// The last chain settings this engine read or wrote, per chain: a torn read
386// returns it, so a chain's `esik`/`limit` never turn into the defaults for one
387// measurement (O16). Reset at session.start (O18).
388let lastAyar: Record<string, OrkestraAyar> = {}
389
390const toAyar = (got: Record<string, unknown>): OrkestraAyar => ({
391  esik: typeof got.esik === 'number' ? got.esik : undefined,
392  limit: typeof got.limit === 'number' ? got.limit : undefined,
393  isClosed: got.isClosed === true ? true : undefined,
394  at: typeof got.at === 'number' ? got.at : 0,
395})
396
397/** A chain's settings (Decision 22), or undefined when none were written. */
398export const readChainSettings = async ($: EngineInterface, mainLocalId: string): Promise<OrkestraAyar | undefined> => {
399  const home = await homeOf($)
400  const got = await readJsonFile($, home === undefined ? undefined : zincirAyarFile(home, mainLocalId))
401  if (got.kind === 'torn') return lastAyar[mainLocalId]
402  if (got.kind === 'missing') return undefined
403  const ayar = toAyar(got.value)
404  lastAyar[mainLocalId] = ayar
405
406  return ayar
407}
408
409/** That chain's limit (Decision 22): its settings' `limit` clamped, unset or invalid the default. */
410export const orkestraLimit = async ($: EngineInterface, mainLocalId: string): Promise<number> => {
411  const limit = (await readChainSettings($, mainLocalId).catch(() => undefined))?.limit
412
413  return typeof limit === 'number' && Number.isFinite(limit) ? clampLimit(limit) : DEFAULT_LIMIT
414}
415
416/** `/devir otonom …` outside a chain (Decision 22: no chain settings, so the default limit). */
417const NOT_ORCHESTRATED = `Bu sohbet orkestra modunda değil (sınır ${DEFAULT_LIMIT} alt sohbet). Başlatmak için ${START_HINT} yaz.`
418
419type SelfSettings = { effort?: string; model?: string; permissionMode?: string }
420type Settings = { threshold: number; isEnabled: boolean }
421
422const isThreshold = (n: unknown): n is number =>
423  typeof n === 'number' && Number.isInteger(n) && n >= 1 && n <= 99
424
425/**
426 * This chat's chain settings (Decision 22), from the cached conv role (never
427 * `currentConv`): a main chat's own chain, a sub-chat's parent's. A normal
428 * chat (role `yok` or unresolved) has none: the default threshold, off.
429 */
430const readSettings = async ($: EngineInterface): Promise<Settings> => {
431  const sid = await $.session.id()
432  const held = await read($, conv)
433  const chainId =
434    held === null || held.sid !== sid
435      ? undefined
436      : held.role === 'ana'
437        ? held.localId
438        : held.role === 'alt'
439          ? held.parentId
440          : undefined
441  if (chainId === undefined) return { threshold: DEFAULT_THRESHOLD, isEnabled: false }
442  const ayar = await readChainSettings($, chainId).catch(() => lastAyar[chainId])
443  const esik = ayar?.esik
444
445  return {
446    threshold: isThreshold(esik) ? esik : DEFAULT_THRESHOLD,
447    isEnabled: ayar?.isClosed !== true,
448  }
449}
450
451/** The threshold this chat trips at: its own `/devir dene` value, else its chain's `esik`. */
452const thresholdOf = (settings: Settings, held: OtomatikDevirConv | null): number =>
453  held?.testThreshold ?? settings.threshold
454
455/** Context fill as a whole percentage, or undefined before the first response. */
456const contextPercent = async ($: EngineInterface): Promise<number | undefined> => {
457  const { context } = await $.session.usage()
458  if (typeof context.percent === 'number') return context.percent
459  if (typeof context.tokens === 'number' && context.window > 0) {
460    return Math.round((context.tokens / context.window) * 100)
461  }
462
463  return undefined
464}
465
466const isDrainPhase = (phase: OtomatikDevirPhase): boolean => phase === 'handoff_running' || phase === 'ready'
467
468/** This chat's part in a chain, for the status line (O9). */
469type OrkestraStatus =
470  | { role: 'ana'; main: OrkestraAna; child?: OrkestraAlt; isPaused: boolean }
471  | { role: 'alt'; n: number }
472
473/** The main chat's status line (Contract). */
474const mainStatusText = ({ main, child, isPaused }: { main: OrkestraAna; child?: OrkestraAlt; isPaused: boolean }) => {
475  if (main.ended === 'durdu') return orkestraStalledBand(main.n)
476  if (main.ended !== undefined) return `Orkestra bitti (${main.n} alt sohbet)`
477  if (isPaused || !main.isHeld) return 'Orkestra duraklatıldı'
478  if (main.n === 0) return 'Orkestra: alt sohbet 1 açılıyor'
479
480  return child?.status === 'ready' ? `Orkestra: alt sohbet ${main.n} hazır` : `Orkestra: alt sohbet ${main.n} çalışıyor`
481}
482
483const statusText = (
484  settings: Settings,
485  percent: number | undefined,
486  held: OtomatikDevirConv | null,
487  running: number,
488  orkestra?: OrkestraStatus,
489): string => {
490  if (orkestra?.role === 'ana') return mainStatusText(orkestra)
491  const text = v1StatusText(settings, percent, held, running)
492
493  return orkestra?.role === 'alt' ? `Orkestra alt sohbet ${orkestra.n} · ${text}` : text
494}
495
496const v1StatusText = (
497  settings: Settings,
498  percent: number | undefined,
499  held: OtomatikDevirConv | null,
500  running: number,
501): string => {
502  if (!settings.isEnabled) return 'Devir: kapalı'
503  if (held?.phase === 'ready') return 'Devir hazır'
504  if (held?.phase === 'handoff_running' && running > 0) return `Devir: ${running} alt ajan bitiyor`
505
506  return `Devir: %${percent ?? 0} / eşik %${thresholdOf(settings, held)}${
507    held?.testThreshold !== undefined ? ' (bu sohbet)' : ''
508  }`
509}
510
511/** This chat's chain part from its cached role (O9): the main record and child, or the child's number. */
512const orkestraStatusOf = async ($: EngineInterface, held: OtomatikDevirConv): Promise<OrkestraStatus | undefined> => {
513  if (held.role === 'alt') return { role: 'alt', n: held.childN ?? 1 }
514  if (held.role !== 'ana' || held.localId === undefined) return undefined
515  const main = await readMain($, held.localId).catch(() => undefined)
516  if (main === undefined) return undefined
517  const child = main.n >= 1 ? await readChild($, main.childId) : undefined
518
519  return { role: 'ana', main, child, isPaused: held.isPaused === true }
520}
521
522const refreshStatus = async ($: EngineInterface, percent?: number): Promise<void> => {
523  const held = await currentConv($)
524  // O20: a normal chat (cached role `yok` or unresolved) shows nothing.
525  if (held.role !== 'ana' && held.role !== 'alt') {
526    $.ui.status(undefined)
527
528    return
529  }
530  const settings = await readSettings($)
531  const running = held.phase === 'handoff_running' ? (await activeAgents($)).length : 0
532  const orkestra = await orkestraStatusOf($, held)
533  $.ui.status(statusText(settings, percent ?? (await contextPercent($)), held, running, orkestra))
534}
535
536// ---------------------------------------------------------------------------
537// Durable state (S2): `devir:<sid>` while a handoff runs, `devredildi:<sid>`
538// once its child started. $.state is lost on a reload; the store is not.
539// ---------------------------------------------------------------------------
540
541type RunRecord = { handoffId: string; file: string; handoffAt: number; phase: 'handoff_running' | 'ready' }
542type HandedRecord = { handoffId: string; startedId: string; file: string; at: number }
543
544const record = (value: unknown): Record<string, unknown> | undefined =>
545  value !== null && typeof value === 'object' && !Array.isArray(value)
546    ? (value as Record<string, unknown>)
547    : undefined
548
549const nonEmpty = (value: unknown): string | undefined =>
550  typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
551
552/** The handed-off flag of this session, when its child already started. */
553const handedOf = async ($: EngineInterface, sid: string): Promise<HandedRecord | undefined> => {
554  const got = record(await $.store.get(`${HANDED_PREFIX}${sid}`).catch(() => undefined))
555  if (got === undefined) return undefined
556
557  return {
558    handoffId: nonEmpty(got.handoffId) ?? '',
559    startedId: nonEmpty(got.startedId) ?? '',
560    file: nonEmpty(got.file) ?? '',
561    at: typeof got.at === 'number' ? got.at : 0,
562  }
563}
564
565const runOf = async ($: EngineInterface, sid: string): Promise<RunRecord | undefined> => {
566  const got = record(await $.store.get(`${RUN_PREFIX}${sid}`).catch(() => undefined))
567  const handoffId = nonEmpty(got?.handoffId)
568  const file = nonEmpty(got?.file)
569  if (got === undefined || handoffId === undefined || file === undefined) return undefined
570  if (got.phase !== 'handoff_running' && got.phase !== 'ready') return undefined
571
572  return { handoffId, file, handoffAt: typeof got.handoffAt === 'number' ? got.handoffAt : 0, phase: got.phase }
573}
574
575// Mirrors whether this session's handoff drains (handoff_running or ready);
576// the guards' `.catch` reads it when the hook itself failed (S4).
577let isDraining = false
578
579/**
580 * Writes this session's record to the store after a claim or a phase change:
581 * `devir:<sid>` while it drains, deleted otherwise (`done` writes
582 * `devredildi:<sid>` itself, before this runs).
583 */
584const syncStore = async ($: EngineInterface, sid: string): Promise<void> => {
585  const held = await read($, conv)
586  if (held === null || held.sid !== sid) return
587  isDraining = isDrainPhase(held.phase)
588  const key = `${RUN_PREFIX}${sid}`
589  if (isDraining && held.handoffId !== undefined && held.file !== undefined) {
590    const run: RunRecord = {
591      handoffId: held.handoffId,
592      file: held.file,
593      handoffAt: held.handoffAt ?? 0,
594      phase: held.phase as RunRecord['phase'],
595    }
596    await $.store.set(key, run)
597  } else {
598    await $.store.delete(key).catch(() => undefined)
599  }
600  // O14: a managed sub-chat's record follows its phase.
601  if (held.role === 'alt') await syncChild($, held)
602}
603
604/**
605 * O14: a managed sub-chat's own record, `working` (idle, handoff_running) or
606 * `ready` with its file. A `finished` record stays; `done` (consumed) leaves it.
607 */
608const syncChild = async ($: EngineInterface, held: OtomatikDevirConv): Promise<void> => {
609  if (held.localId === undefined || held.phase === 'done') return
610  const base = await childBase($, held)
611  if (base === undefined || base.status === 'finished' || base.status === 'cancelled') return
612  const isReady = held.phase === 'ready'
613  await writeRecord($, held.localId, {
614    ...base,
615    status: isReady ? 'ready' : 'working',
616    file: isReady ? held.file : undefined,
617    at: await $.clock.now(),
618  })
619}
620
621/**
622 * A managed sub-chat's own record, else (its first write failed) one rebuilt
623 * from conv as `working`; undefined without a local id or parent.
624 */
625const childBase = async ($: EngineInterface, held: OtomatikDevirConv): Promise<OrkestraAlt | undefined> => {
626  if (held.localId === undefined) return undefined
627  const own = await readRecord($, held.localId)
628  if (own?.role === 'alt') return own
629  if (held.parentId === undefined) return undefined
630
631  return {
632    role: 'alt',
633    parent: held.parentId,
634    n: held.childN ?? 1,
635    sid: held.sid,
636    localId: held.localId,
637    status: 'working',
638    at: 0,
639  }
640}
641
642/**
643 * O15: a `ready` sub-chat whose parent moved on (a later child, or the chain
644 * ended) is consumed: `done`, so its drain lifts.
645 */
646const consumeChild = async ($: EngineInterface, held: OtomatikDevirConv): Promise<OtomatikDevirConv> => {
647  if (held.parentId === undefined) return held
648  const parent = await readRecord($, held.parentId).catch(() => undefined)
649  if (parent?.role !== 'ana' || !(parent.n > (held.childN ?? 0) || parent.ended !== undefined)) return held
650  // O21 over O15 also when the chain settings were not readable now: a main
651  // chat that ended `kapatildi` was closed, so its ready child is cancelled.
652  if (parent.ended === 'kapatildi') return cancelHandoff($, held.sid, true)
653  await setPhase($, held.sid, 'done')
654  const now = await read($, conv)
655
656  return now !== null && now.sid === held.sid ? now : held
657}
658
659/** The record of this sid, rebuilt from the store when $.state has none (a reload). */
660const restoreConv = async ($: EngineInterface, sid: string): Promise<OtomatikDevirConv> => {
661  const base = await restoreHandoff($, sid)
662  // O16: a reload keeps this chat's orchestration role (its local id and own record).
663  const localId = nonEmpty(await $.store.get(`${KIMLIK_PREFIX}${sid}`).catch(() => undefined))
664  if (localId === undefined) return base
665  const own = await readRecord($, localId).catch(() => undefined)
666  if (own === undefined) return { ...base, localId }
667  if (own.role === 'ana') {
668    return {
669      ...base,
670      localId,
671      role: 'ana',
672      childN: own.n,
673      isPaused: !own.isHeld && own.ended === undefined ? true : undefined,
674    }
675  }
676
677  return { ...base, localId, role: 'alt', parentId: own.parent, childN: own.n }
678}
679
680const restoreHandoff = async ($: EngineInterface, sid: string): Promise<OtomatikDevirConv> => {
681  const handed = await handedOf($, sid)
682  if (handed !== undefined) {
683    return { sid, phase: 'done', handoffId: handed.handoffId, startedId: handed.startedId, file: handed.file }
684  }
685  const run = await runOf($, sid)
686  if (run !== undefined) {
687    return {
688      sid,
689      phase: run.phase,
690      handoffId: run.handoffId,
691      file: run.file,
692      handoffAt: run.handoffAt,
693      isGateClosed: true,
694    }
695  }
696
697  return { sid, phase: 'idle' }
698}
699
700/**
701 * Cancels this chat's handoff whose child has not started (v1.0.1): back to
702 * `idle`, only the handoff fields cleared (O21: the role, ids, chain fields,
703 * `/devir dene`, last typed message and noted settings kept), `devir:<sid>`
704 * deleted, the drain lifted, the band and status redrawn. `/devir kapat` runs
705 * it, and so does any chat that sees its chain closed (`isNoticed`: a toast
706 * says so). A finished handoff (`done`, `devredildi:<sid>`) is never undone; a
707 * handoff file already written stays on disk. A managed sub-chat whose drain
708 * it cancelled records itself `cancelled` (never relayed).
709 */
710const cancelHandoff = async ($: EngineInterface, sid: string, isNoticed: boolean): Promise<OtomatikDevirConv> => {
711  let now: OtomatikDevirConv = { sid, phase: 'idle' }
712  let wasDrain = false
713  await update($, conv, (held): OtomatikDevirConv | null => {
714    if (held !== null && held.sid !== sid) return held
715    if (held?.phase === 'done') {
716      now = held
717      return held
718    }
719    wasDrain = held !== null && isDrainPhase(held.phase)
720    now = {
721      ...held,
722      sid,
723      phase: 'idle',
724      handoffId: undefined,
725      handoffAt: undefined,
726      file: undefined,
727      isGateClosed: undefined,
728      isForced: undefined,
729      starting: undefined,
730      pendingMessage: undefined,
731      instructNext: undefined,
732      instructedTurn: undefined,
733      notedTurn: undefined,
734    }
735    return now
736  })
737  if (now.phase === 'done') return now
738  isDraining = false
739  await $.store.delete(`${RUN_PREFIX}${sid}`).catch(() => undefined)
740  // O14, O21: the cancelled drain of a managed sub-chat; its main chat ends `kapatildi`.
741  if (wasDrain && now.role === 'alt' && now.localId !== undefined) {
742    const own = await childBase($, now).catch(() => undefined)
743    if (own !== undefined && own.status !== 'finished' && own.status !== 'cancelled') {
744      await writeRecord($, own.localId, { ...own, status: 'cancelled', file: undefined, at: await $.clock.now() })
745    }
746  }
747  later($, async () => {
748    try {
749      $.ui.invalidate('ui.render')
750    } catch {
751      // the band redraws on the next prop change anyway
752    }
753    if (isNoticed) $.ui.toast('Otomatik devir kapalı: bu sohbetin devri iptal edildi.')
754    await refreshStatus($).catch(() => undefined)
755  })
756
757  return now
758}
759
760/**
761 * The record of the conversation now running; a new session id restores it
762 * from the store. A handoff not yet handed off is dropped once the mod is
763 * off, in whichever chat turned it off (v1.0.1).
764 */
765const currentConv = async ($: EngineInterface): Promise<OtomatikDevirConv> => {
766  const sid = await $.session.id()
767  const held = await read($, conv)
768  let now: OtomatikDevirConv
769  if (held !== null && held.sid === sid) {
770    now = held
771  } else {
772    now = await restoreConv($, sid)
773    const restored = now
774    await update($, conv, () => restored)
775  }
776  // O21 before O15: a closed chain cancels its ready sub-chat (below), never consumes it.
777  if (now.phase === 'ready' && now.role === 'alt' && (await readSettings($)).isEnabled) now = await consumeChild($, now)
778  isDraining = isDrainPhase(now.phase)
779  if (isDraining) {
780    // O20: only a managed sub-chat drains; a leftover elsewhere goes silently.
781    if ((await roleOf($)) !== 'alt') return cancelHandoff($, sid, false)
782    if (!(await readSettings($)).isEnabled) return cancelHandoff($, sid, true)
783  }
784
785  return now
786}
787
788const patchConv = async (
789  $: EngineInterface,
790  sid: string,
791  patch: Partial<OtomatikDevirConv>,
792): Promise<void> => {
793  await update($, conv, (held): OtomatikDevirConv =>
794    held !== null && held.sid === sid ? { ...held, ...patch } : { sid, phase: 'idle', ...patch },
795  )
796  if (patch.phase !== undefined || patch.handoffId !== undefined) await syncStore($, sid)
797}
798
799const setPhase = ($: EngineInterface, sid: string, phase: OtomatikDevirPhase) =>
800  patchConv($, sid, { phase })
801
802/**
803 * Check-and-set in one `update` (ifVersion, retried on a miss): applies `patch`
804 * only when `may` allows the record as it stands, and says whether this call
805 * won. Two racing callers (parallel tool results, a double press, `/devir simdi`
806 * landing beside a turn end) cannot both pass. A record of another sid is
807 * left alone.
808 */
809const claim = async (
810  $: EngineInterface,
811  sid: string,
812  may: (held: OtomatikDevirConv) => boolean,
813  patch: Partial<OtomatikDevirConv>,
814): Promise<boolean> => {
815  let isClaimed = false
816  await update($, conv, (held): OtomatikDevirConv | null => {
817    if (held !== null && held.sid !== sid) {
818      isClaimed = false
819      return held
820    }
821    const now: OtomatikDevirConv = held ?? { sid, phase: 'idle' }
822    isClaimed = may(now)
823    return isClaimed ? { ...now, ...patch } : held
824  })
825  if (isClaimed && (patch.phase !== undefined || patch.handoffId !== undefined)) await syncStore($, sid)
826
827  return isClaimed
828}
829
830// ---------------------------------------------------------------------------
831// Due and claim (S3)
832// ---------------------------------------------------------------------------
833
834/**
835 * The trip is due: this is a managed sub-chat whose parent chain is live and
836 * open, this session never handed off, and either `/devir simdi` forced it or
837 * the fill reached this chat's threshold.
838 */
839const isDue = async ($: EngineInterface, held: OtomatikDevirConv): Promise<{ threshold: number } | undefined> => {
840  // O3, O20: only a managed sub-chat hands off by threshold; a normal chat and
841  // the main chat never measure for a trip.
842  if ((await roleOf($)) !== 'alt') return undefined
843  const chainId = await chainIdOf($)
844  const parent = chainId === undefined ? undefined : await readRecord($, chainId).catch(() => undefined)
845  if (parent?.role !== 'ana' || parent.ended !== undefined) return undefined
846  const settings = await readSettings($)
847  if (!settings.isEnabled) return undefined
848  if ((await handedOf($, held.sid)) !== undefined) return undefined
849  const threshold = thresholdOf(settings, held)
850  if (held.isForced === true) return { threshold }
851  const percent = await contextPercent($)
852  if (percent === undefined || percent < threshold) return undefined
853
854  return { threshold }
855}
856
857const newHandoffId = (sid: string, now: number): string => `${sid.slice(0, 8)}-${now.toString(36)}`
858
859/**
860 * Starts a handoff: `handoff_running` with a new id, its time and file, and the
861 * gate closed unless the person typed the running turn. Returns the claimed
862 * record, or undefined when another caller won (or `may` refused).
863 */
864const claimHandoff = async (
865  $: EngineInterface,
866  sid: string,
867  may: (held: OtomatikDevirConv) => boolean,
868  extra: Partial<OtomatikDevirConv> = {},
869): Promise<OtomatikDevirConv | undefined> => {
870  const now = await $.clock.now()
871  const file = handoffFile(await $.session.cwd(), sid)
872  // O12: a managed sub-chat only writes its file; the main chat starts the next one.
873  const isManaged = (await roleOf($)) === 'alt'
874  const isClaimed = await claim($, sid, may, {
875    phase: 'handoff_running',
876    handoffId: newHandoffId(sid, now),
877    handoffAt: now,
878    file,
879    isGateClosed: isManaged || !isPersonTurn,
880    isForced: false,
881    starting: undefined,
882    notedTurn: undefined,
883    ...extra,
884  })
885  if (!isClaimed) return undefined
886  later($, () => noteSelf($, sid))
887  const held = await read($, conv)
888
889  return held !== null && held.sid === sid ? held : undefined
890}
891
892/**
893 * The handoff instruction for this chat (O12): a managed sub-chat writes its
894 * file only; else in-turn when the person typed the turn, the closed-turn text otherwise.
895 */
896const handoffTextFor = (held: OtomatikDevirConv, threshold: number, file: string, hasSkill: boolean): string =>
897  held.role === 'alt'
898    ? managedHandoff(threshold, file, hasSkill)
899    : isPersonTurn
900      ? inTurnHandoff(threshold, file, hasSkill)
901      : closedTurnHandoff(threshold, file, hasSkill)
902
903/** The handoff file's text, when it was written for this handoff (not before `since`). */
904const readFresh = async ($: EngineInterface, file: string | undefined, since: number | undefined) => {
905  if (file === undefined) return undefined
906  try {
907    const stat = await $.fs.stat(file)
908    if (stat.kind !== 'file' || (since !== undefined && stat.mtimeMs < since)) return undefined
909    const body = (await $.fs.read(file)).trim()
910
911    return body === '' ? undefined : body
912  } catch {
913    return undefined
914  }
915}
916
917const isFresh = async ($: EngineInterface, file: string | undefined, since: number | undefined) =>
918  (await readFresh($, file, since)) !== undefined
919
920const hasHandoffSkill = async ($: EngineInterface): Promise<boolean> => {
921  try {
922    if ((await $.command.list()).some(command => command.name === SKILL)) return true
923  } catch {
924    // fall through to the file checks
925  }
926  const home = await $.env.get('HOME')
927  const places = [
928    home === undefined ? undefined : `${home}/.claude/skills/${SKILL}/SKILL.md`,
929    `${await $.session.root()}/.claude/skills/${SKILL}/SKILL.md`,
930  ]
931  for (const place of places) {
932    if (place !== undefined && (await $.fs.exists(place).catch(() => false))) return true
933  }
934
935  return false
936}
937
938/**
939 * `$.tool.call` for a tool the saved MCP typings may not declare yet (they list
940 * the tools connected when the mod was last saved): the input goes through
941 * loosely typed.
942 */
943const callTool = ($: EngineInterface, input: { tool: string } & Record<string, unknown>) =>
944  $.tool.call(input as unknown as ToolCallArgs)
945
946type SelfSession = SelfSettings & { id?: string; title?: string; parentId?: string }
947
948/** This chat's own desktop session: its id (local_...), parent (local_...), title, effort, model and permission mode. */
949const selfSession = async ($: EngineInterface): Promise<SelfSession> => {
950  try {
951    const got = await $.tool.call({ tool: GET_SESSION, session_id: 'self' })
952    if (got.deny !== undefined || got.isError === true || got.text === undefined) return {}
953    const info = JSON.parse(got.text) as Record<string, unknown>
954
955    return {
956      id: nonEmpty(info.sessionId),
957      parentId: nonEmpty(info.parentSessionId),
958      title: nonEmpty(info.title),
959      effort: nonEmpty(info.effort),
960      model: nonEmpty(info.model),
961      permissionMode: nonEmpty(info.permissionMode),
962    }
963  } catch {
964    return {}
965  }
966}
967
968/** This chat's title + " (devam)", kept under 60 characters; "Devam" when unknown. */
969const continueTitle = (title: string | undefined): string => {
970  if (title === undefined) return 'Devam'
971  const room = TITLE_LIMIT - CONTINUE_SUFFIX.length
972
973  return `${title.slice(0, room).trimEnd()}${CONTINUE_SUFFIX}`
974}
975
976/** The new session's id from a start_session result, when it started one. */
977const startedId = (result: { deny?: string; isError?: boolean; text?: string }): string | undefined =>
978  result.deny !== undefined || result.isError === true
979    ? undefined
980    : /\b(local_[A-Za-z0-9-]+)/.exec(result.text ?? '')?.[1]
981
982/** Work that must not run inside the dispatch the turn waits on. */
983const later = ($: EngineInterface, work: () => Promise<void>): void => {
984  $.clock.after(50, () => {
985    work().catch(error => $.ui.log(`otomatik-devir: ${String(error)}`, { to: 'debug' }))
986  })
987}
988
989/** Subagents still running (or about to); fails open to none. */
990const activeAgents = async ($: EngineInterface): Promise<AgentInfo[]> => {
991  try {
992    return (await $.agent.list()).filter(agent => ACTIVE_AGENT.has(agent.status))
993  } catch (error) {
994    $.ui.log(`otomatik-devir: ajan listesi okunamadı: ${String(error)}`, { to: 'debug' })
995
996    return []
997  }
998}
999
1000// Who typed the running main turn. prompt.submit's `origin` (engine-stamped,
1001// a closed set) is read for the turn it starts and kept until that turn ends;
1002// a turn no prompt.submit of a person opened (a task notification, a
1003// continuation) is not the person's.
1004let isPersonTurn = false
1005let isNextTurnPerson = false
1006let runningTurnId: string | undefined
1007
1008/**
1009 * The person's own message: Enter at the terminal, the Remote Control bridge,
1010 * or the SDK host's turn (Claude desktop writes the person's composer message
1011 * to the engine as its SDK host). Every other origin is a machine's.
1012 */
1013const PERSON_ORIGINS: ReadonlySet<string> = new Set(['composer', 'bridge', 'sdk'])
1014
1015/** A person's own submission: a person origin, not one the engine marks isMeta. */
1016const isPersonSubmit = (e: { origin: { kind: string }; isMeta?: true }): boolean =>
1017  PERSON_ORIGINS.has(e.origin.kind) && e.isMeta !== true
1018
1019/** Notes the continuation title and this chat's settings for the start_session call. */
1020const noteSelf = async ($: EngineInterface, sid: string): Promise<void> => {
1021  const self = await selfSession($)
1022  await patchConv($, sid, {
1023    title: continueTitle(self.title),
1024    selfId: self.id,
1025    effort: self.effort,
1026    model: self.model,
1027    permissionMode: self.permissionMode,
1028  })
1029}
1030
1031// ---------------------------------------------------------------------------
1032// Orchestration records, ids and roles (O10, O11, O16). Records are keyed by
1033// local id (Corrections): the main chat knows its child only by the
1034// start_session result, the child its parent only by `parentSessionId`.
1035// Each record has one writer: the main chat its own, a child its own.
1036// ---------------------------------------------------------------------------
1037
1038type RecordRead = { kind: 'ok'; rec: OrkestraRecord } | { kind: 'missing' } | { kind: 'torn' }
1039
1040/** A parsed record; anything else (an O1 tombstone `{ gone }` too) is no record. */
1041const toRecord = (got: Record<string, unknown>): OrkestraRecord | undefined => {
1042  if (typeof got.localId !== 'string' || typeof got.n !== 'number') return undefined
1043  if (got.role === 'ana' && typeof got.task === 'string') return got as unknown as OrkestraAna
1044  if (got.role === 'alt' && typeof got.parent === 'string') return got as unknown as OrkestraAlt
1045
1046  return undefined
1047}
1048
1049const readRecordState = async ($: EngineInterface, localId: string): Promise<RecordRead> => {
1050  const home = await homeOf($)
1051  const got = await readJsonFile($, home === undefined ? undefined : orkestraRecordFile(home, localId))
1052  if (got.kind !== 'ok') return got
1053  const rec = toRecord(got.value)
1054
1055  return rec === undefined ? { kind: 'missing' } : { kind: 'ok', rec }
1056}
1057
1058/** The record of `localId`; missing, invalid or not readable now: undefined (O16). */
1059const readRecord = async ($: EngineInterface, localId: string): Promise<OrkestraRecord | undefined> => {
1060  const got = await readRecordState($, localId)
1061
1062  return got.kind === 'ok' ? got.rec : undefined
1063}
1064
1065/** Writes the whole record file ($.fs.write creates the folder). */
1066const writeRecord = async (
1067  $: EngineInterface,
1068  localId: string,
1069  rec: OrkestraRecord | { gone: true; at: number },
1070): Promise<void> => {
1071  const home = await homeOf($)
1072  if (home === undefined) return
1073  await $.fs.write(orkestraRecordFile(home, localId), JSON.stringify(rec))
1074}
1075
1076// The main chat's own record as this engine last read or wrote it: the main
1077// chat is its only writer, so the copy stays true (prompt.compose and the band
1078// read it on every render). Reset at session.start.
1079let ownMain: OrkestraAna | undefined
1080
1081const readMain = async ($: EngineInterface, localId: string): Promise<OrkestraAna | undefined> => {
1082  if (ownMain?.localId === localId) return ownMain
1083  const rec = await readRecord($, localId)
1084  if (rec?.role !== 'ana') return undefined
1085  ownMain = rec
1086
1087  return rec
1088}
1089
1090const writeMain = async ($: EngineInterface, rec: OrkestraAna): Promise<void> => {
1091  await writeRecord($, rec.localId, rec)
1092  // Cached once written: a failed write leaves the copy true to the file.
1093  ownMain = rec
1094}
1095
1096/** Read, merge, write this main chat's record; undefined when it has none. */
1097const patchMain = async (
1098  $: EngineInterface,
1099  localId: string,
1100  patch: Partial<OrkestraAna>,
1101): Promise<OrkestraAna | undefined> => {
1102  const base = await readMain($, localId)
1103  if (base === undefined) return undefined
1104  const rec: OrkestraAna = { ...base, ...patch, at: await $.clock.now() }
1105  await writeMain($, rec)
1106
1107  return rec
1108}
1109
1110const readChild = async ($: EngineInterface, childId: string | undefined): Promise<OrkestraAlt | undefined> => {
1111  if (childId === undefined || childId === UNKNOWN_CHILD) return undefined
1112  const rec = await readRecord($, childId).catch(() => undefined)
1113
1114  return rec?.role === 'alt' ? rec : undefined
1115}
1116
1117/** Writes a chain's settings whole (Decision 22). */
1118export const writeChainSettings = async ($: EngineInterface, mainLocalId: string, rec: OrkestraAyar): Promise<void> => {
1119  const home = await homeOf($)
1120  if (home === undefined) return
1121  lastAyar[mainLocalId] = rec
1122  await $.fs.write(zincirAyarFile(home, mainLocalId), JSON.stringify(rec))
1123}
1124
1125/** Read, merge, write a chain's settings (a torn or missing read merges over lastAyar). */
1126export const patchChainSettings = async (
1127  $: EngineInterface,
1128  mainLocalId: string,
1129  patch: Partial<OrkestraAyar>,
1130): Promise<OrkestraAyar> => {
1131  const base = (await readChainSettings($, mainLocalId)) ?? lastAyar[mainLocalId]
1132  const rec: OrkestraAyar = { ...base, ...patch, at: await $.clock.now() }
1133  await writeChainSettings($, mainLocalId, rec)
1134
1135  return rec
1136}
1137
1138// This engine's one `get_session self` answer per conversation (O16, O17): the
1139// local id and the parent come from the same call. A failed GET is not kept.
1140let selfInfo: { sid: string; info: SelfSession } | undefined
1141
1142const selfOnce = async ($: EngineInterface, sid: string): Promise<SelfSession> => {
1143  if (selfInfo?.sid === sid) return selfInfo.info
1144  const info = await selfSession($)
1145  if (info.id !== undefined) selfInfo = { sid, info }
1146
1147  return info
1148}
1149
1150/** $.state holds this sid's record, rebuilt from the store first (a reload), so a role patch never hides a running handoff. */
1151const ensureConv = async ($: EngineInterface, sid: string): Promise<void> => {
1152  const held = await read($, conv)
1153  if (held !== null && held.sid === sid) return
1154  const restored = await restoreConv($, sid)
1155  await update($, conv, now => (now !== null && now.sid === sid ? now : restored))
1156}
1157
1158/** This chat's local id: conv, else `kimlik:<sid>`, else `get_session self` (then kept in both). */
1159const selfLocal = async ($: EngineInterface): Promise<string | undefined> => {
1160  const sid = await $.session.id()
1161  await ensureConv($, sid)
1162  const held = await read($, conv)
1163  if (held !== null && held.sid === sid && held.localId !== undefined) return held.localId
1164  const stored = nonEmpty(await $.store.get(`${KIMLIK_PREFIX}${sid}`).catch(() => undefined))
1165  const id = stored ?? (await selfOnce($, sid)).id
1166  if (id === undefined) return undefined
1167  if (stored === undefined) await $.store.set(`${KIMLIK_PREFIX}${sid}`, id).catch(() => undefined)
1168  await patchConv($, sid, { localId: id })
1169
1170  return id
1171}
1172
1173/**
1174 * This chat's role (O10), cached in conv. Its own record names it; else the
1175 * parent from `get_session self` makes it `alt` when the parent's live main
1176 * record points at this chat (or is starting one), and the child writes its
1177 * own record. A failed GET or a torn file: `yok` for this call, not cached.
1178 * Reads conv with `read`, never `currentConv` (O16).
1179 */
1180const roleOf = async ($: EngineInterface): Promise<OrkestraRole> => {
1181  const sid = await $.session.id()
1182  await ensureConv($, sid)
1183  const held = await read($, conv)
1184  if (held !== null && held.sid === sid && held.role !== undefined) return held.role
1185
1186  return (await resolveRole($, sid)) ?? 'yok'
1187}
1188
1189const resolveRole = async ($: EngineInterface, sid: string): Promise<OrkestraRole | undefined> => {
1190  const localId = await selfLocal($)
1191  if (localId === undefined) return undefined
1192  const own = await readRecordState($, localId)
1193  if (own.kind === 'torn') return undefined
1194  if (own.kind === 'ok') {
1195    const rec = own.rec
1196    await patchConv(
1197      $,
1198      sid,
1199      rec.role === 'ana' ? { role: 'ana', childN: rec.n } : { role: 'alt', parentId: rec.parent, childN: rec.n },
1200    )
types/index.d.ts 151 lines
1export type OtomatikDevirPhase =
2  | 'idle'
3  /** The threshold tripped: running work drains, the handoff file gets written, the child starts. */
4  | 'handoff_running'
5  /** The file is written but no typed turn was open: the person's next message opens the child. */
6  | 'ready'
7  /** The child started; `devredildi:<sid>` keeps a second one from starting. */
8  | 'done'
9
10/** This chat's part in an orchestration: the main chat, a child, or none. */
11export type OrkestraRole = 'ana' | 'alt' | 'yok'
12
13/** Why a chain ended: finished, hit the limit, stopped by the person, stalled, closed by `/devir kapat`, or the main chat's own context full. */
14export type OrkestraEnd = 'bitti' | 'sinir' | 'durduruldu' | 'durdu' | 'kapatildi' | 'dolu'
15
16/** The main chat's orchestration record, keyed by its local id. */
17export type OrkestraAna = {
18  /** Marks the main chat's record. */
19  role: 'ana'
20  /** The main chat's conversation (transcript) id. */
21  sid: string
22  /** The main chat's local session id; the record's key. */
23  localId: string
24  /** The task the person gave the orchestration. */
25  task: string
26  /** The main chat's title; children are titled from it. */
27  title: string
28  /** How many children have been started so far. */
29  n: number
30  /** The latest child's local id. */
31  childId?: string
32  /** True while a start of the next child is in flight. */
33  starting?: true
34  /** Clock ms when the in-flight start began; an old one counts as stale. */
35  startingAt?: number
36  /** The main chat is held: its turns end without finishing until the chain ends. */
37  isHeld: boolean
38  /** The person asked the chain to stop. */
39  isStopRequested?: boolean
40  /** Set when the chain ended, with the reason. */
41  ended?: OrkestraEnd
42  /** Consecutive Stop cycles that found the child not running. */
43  stallCount?: number
44  /** Clock ms of the last stall check. */
45  stallAt?: number
46  /** The person's message waiting to be handed to the next child. */
47  pendingMessage?: string
48  /** This chain's own threshold, copied from the chat's `testThreshold`. */
49  testThreshold?: number
50  /** Clock ms when the orchestration started. */
51  startedAt: number
52  /** Clock ms of the last write to this record. */
53  at: number
54}
55
56/** A child chat's orchestration record, keyed by its local id. */
57export type OrkestraAlt = {
58  /** Marks a child's record. */
59  role: 'alt'
60  /** The parent's local id. */
61  parent: string
62  /** This child's number in the chain (1-based). */
63  n: number
64  /** The child's conversation (transcript) id. */
65  sid: string
66  /** The child's local session id; the record's key. */
67  localId: string
68  /** Where the child stands: working, handoff file ready, the whole task finished, or its handoff cancelled by `/devir kapat` (never relayed). */
69  status: 'working' | 'ready' | 'finished' | 'cancelled'
70  /** The handoff file the child wrote, once ready. */
71  file?: string
72  /** The child's final report, once finished. */
73  report?: string
74  /** The child was aborted before it could hand off. */
75  isAborted?: boolean
76  /** Clock ms of the last write to this record. */
77  at: number
78}
79
80/** A chain's settings (Decision 22), keyed by the main chat's local id; shared by the main chat and its sub-chats. */
81export type OrkestraAyar = {
82  /** This chain's threshold; unset is the default (60). */
83  esik?: number
84  /** This chain's limit of sub-chats; unset is the default (100). */
85  limit?: number
86  /** `/devir kapat` in this chain: its emergency stop. */
87  isClosed?: true
88  /** Clock ms of the last write to this record. */
89  at: number
90}
91
92/** Either side of an orchestration record. */
93export type OrkestraRecord = OrkestraAna | OrkestraAlt
94
95export type OtomatikDevirConv = {
96  /** The conversation (session id) this record belongs to; a /clear mints a new one. */
97  sid: string
98  phase: OtomatikDevirPhase
99  /** This handoff's id: `<sid first 8>-<clock ms base36>`. */
100  handoffId?: string
101  /** Clock ms when the handoff was claimed; the file must be newer. */
102  handoffAt?: number
103  /** The handoff file, `<cwd>/.workflow/handoff/<sid>.md`. */
104  file?: string
105  /** The continuation chat's title ("<this title> (devam)") and this chat's id. */
106  title?: string
107  selfId?: string
108  /** This chat's effort, model and permission mode (noted, never passed to start_session). */
109  effort?: string
110  model?: string
111  permissionMode?: string
112  /** The session the model started for this handoff. */
113  startedId?: string
114  /** A start_session of the model's is in flight (one at a time). */
115  starting?: string
116  /** The main turn the handoff instruction rode on through a typed message. */
117  instructedTurn?: string
118  /** The instruction rides on a submitted message: the next main turn is the instructed one. */
119  instructNext?: boolean
120  /** No typed turn is open for the handoff: start_session cannot run until the person types. */
121  isGateClosed?: boolean
122  /** `/devir simdi`: due whatever the fill. */
123  isForced?: boolean
124  /** The person's message that opens the child; appended to its prompt as its first job. */
125  pendingMessage?: string
126  /** The machine turn that got the closed-turn text (once per turn). */
127  notedTurn?: string
128  /** `/devir dene <n>`: this chat's own threshold, over the store's `esik`. */
129  testThreshold?: number
130  /** The person's latest typed message (composer/bridge/sdk), read to tell a user-asked handoff from the model's own. */
131  lastTyped?: string
132  /** This chat's orchestration role; unset is the same as `yok`. */
133  role?: OrkestraRole
134  /** This chat's local session id (the key of its orchestration record). */
135  localId?: string
136  /** A child's parent, as a local id. */
137  parentId?: string
138  /** The main chat's count of children started. */
139  childN?: number
140  /** The main chat is paused: the chain does not start a new child until resumed. */
141  isPaused?: boolean
142  /** The main chat's running count of stalled-child Stop cycles. */
143  stalledN?: number
144}
145
146declare module 'claude-code' {
147  interface PluginState {
148    'otomatik-devir': { conv: OtomatikDevirConv | null }
149  }
150}
151