dalang-cli 0.5.0 → 0.6.0

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.
package/bundle/cli.js CHANGED
@@ -2,18 +2,18 @@ import { spawn } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import fastifyStatic from "@fastify/static";
6
- import fastifyWebsocket from "@fastify/websocket";
7
- import Fastify from "fastify";
8
5
  import { z } from "zod";
9
6
  import os from "node:os";
10
7
  import { integer, primaryKey, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
11
8
  import crypto from "node:crypto";
12
9
  import Database from "better-sqlite3";
10
+ import { and, asc, desc, eq, gte, inArray, ne, or } from "drizzle-orm";
13
11
  import { drizzle } from "drizzle-orm/better-sqlite3";
14
12
  import { EventEmitter } from "node:events";
15
- import { and, asc, desc, eq, gte, inArray, ne, or } from "drizzle-orm";
16
13
  import { simpleGit } from "simple-git";
14
+ import fastifyStatic from "@fastify/static";
15
+ import fastifyWebsocket from "@fastify/websocket";
16
+ import Fastify from "fastify";
17
17
  // \0rolldown/runtime.js
18
18
  var __defProp = Object.defineProperty;
19
19
  var __exportAll = (all, no_symbols) => {
@@ -26,6 +26,8 @@ var __exportAll = (all, no_symbols) => {
26
26
  return target;
27
27
  };
28
28
  // ../shared/dist/schemas.js
29
+ const DALANG_VERSION = "0.6.0";
30
+ const UiLanguageSchema = z.enum(["en", "id"]);
29
31
  const ProviderIdSchema = z.enum([
30
32
  "claude-code",
31
33
  "codex",
@@ -298,7 +300,7 @@ const CreateOrOpenProjectInputSchema = z.object({
298
300
  path: z.string().min(1),
299
301
  stackHint: z.string().optional(),
300
302
  initGitIfMissing: z.boolean().default(false),
301
- leadProvider: ProviderIdSchema.default("claude-code"),
303
+ leadProvider: ProviderIdSchema.optional(),
302
304
  leadModel: z.string().optional()
303
305
  });
304
306
  const DiscussMessageInputSchema = z.object({
@@ -362,6 +364,17 @@ function splitEffortModel(model) {
362
364
  level: m[2].toLowerCase()
363
365
  } : null;
364
366
  }
367
+ /**
368
+ * Where work goes when the primary CLI cannot run it: another CLI, model, and effort. It is not a
369
+ * profile, so the fallback run keeps the primary profile's role instructions and limits.
370
+ */
371
+ const FallbackTargetSchema = z.object({
372
+ provider: ProviderIdSchema,
373
+ model: z.string().trim().max(120),
374
+ effort: EffortLevelSchema,
375
+ /** A second account of the same CLI (its config directory), or null for the default account. */
376
+ configDir: z.string().trim().max(500).nullable()
377
+ });
365
378
  const ProfileBaseFieldsSchema = z.object({
366
379
  name: z.string().trim().min(1).max(64).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, "Profile name must use letters, digits, \".\", \"-\" or \"_\""),
367
380
  provider: ProviderIdSchema,
@@ -373,7 +386,7 @@ const ProfileBaseFieldsSchema = z.object({
373
386
  idleTimeoutMs: z.number().int().min(5e3).max(36e5),
374
387
  maxParallel: z.number().int().min(1).max(16),
375
388
  maxReviewRounds: z.number().int().min(1).max(3),
376
- fallbackProfileId: z.string().min(1).nullable(),
389
+ fallback: FallbackTargetSchema.nullable(),
377
390
  configDir: z.string().trim().max(500).nullable()
378
391
  });
379
392
  const CreateProfileInputSchema = z.object({
@@ -387,7 +400,7 @@ const CreateProfileInputSchema = z.object({
387
400
  idleTimeoutMs: ProfileBaseFieldsSchema.shape.idleTimeoutMs.default(18e4),
388
401
  maxParallel: ProfileBaseFieldsSchema.shape.maxParallel.default(1),
389
402
  maxReviewRounds: ProfileBaseFieldsSchema.shape.maxReviewRounds.default(2),
390
- fallbackProfileId: ProfileBaseFieldsSchema.shape.fallbackProfileId.default(null),
403
+ fallback: ProfileBaseFieldsSchema.shape.fallback.default(null),
391
404
  configDir: ProfileBaseFieldsSchema.shape.configDir.default(null)
392
405
  });
393
406
  const UpdateProfileInputSchema = ProfileBaseFieldsSchema.partial();
@@ -395,13 +408,13 @@ const RoutingRuleBaseFieldsSchema = z.object({
395
408
  role: TaskRoleSchema,
396
409
  complexity: TaskComplexitySchema.nullable(),
397
410
  profileId: z.string().min(1),
398
- fallbackProfileId: z.string().min(1).nullable()
411
+ fallback: FallbackTargetSchema.nullable()
399
412
  });
400
413
  const CreateRoutingRuleInputSchema = z.object({
401
414
  role: TaskRoleSchema,
402
415
  complexity: TaskComplexitySchema.nullable().default(null),
403
416
  profileId: z.string().min(1),
404
- fallbackProfileId: z.string().min(1).nullable().default(null)
417
+ fallback: FallbackTargetSchema.nullable().default(null)
405
418
  });
406
419
  const UpdateRoutingRuleInputSchema = RoutingRuleBaseFieldsSchema.partial();
407
420
  const ReorderRoutingRulesInputSchema = z.object({ ruleIds: z.array(z.string().min(1)).min(1) });
@@ -437,7 +450,11 @@ const RunIntegrationInputSchema = z.object({
437
450
  command: z.string().trim().min(1).max(500).optional(),
438
451
  allowUnconfined: z.boolean().default(false)
439
452
  });
440
- const UpdateSettingsInputSchema = z.object({ antigravityKeyringAccess: z.boolean().optional() });
453
+ const UpdateSettingsInputSchema = z.object({
454
+ antigravityKeyringAccess: z.boolean().optional(),
455
+ language: UiLanguageSchema.optional(),
456
+ checkForUpdates: z.boolean().optional()
457
+ });
441
458
  // ../core/dist/paths.js
442
459
  /**
443
460
  * Global DALANG home directory (`~/.dalang` by default, overridable via `DALANG_HOME`).
@@ -590,7 +607,10 @@ const agentProfiles = sqliteTable("agent_profiles", {
590
607
  idleTimeoutMs: integer("idle_timeout_ms").notNull().default(18e4),
591
608
  maxParallel: integer("max_parallel").notNull().default(1),
592
609
  maxReviewRounds: integer("max_review_rounds").notNull().default(2),
593
- fallbackProfileId: text("fallback_profile_id"),
610
+ fallbackProvider: text("fallback_provider"),
611
+ fallbackModel: text("fallback_model"),
612
+ fallbackEffort: text("fallback_effort"),
613
+ fallbackConfigDir: text("fallback_config_dir"),
594
614
  configDir: text("config_dir"),
595
615
  isDefault: integer("is_default", { mode: "boolean" }).notNull().default(false),
596
616
  createdAt: text("created_at").notNull()
@@ -601,7 +621,10 @@ const routingRules = sqliteTable("routing_rules", {
601
621
  role: text("role").notNull(),
602
622
  complexity: text("complexity"),
603
623
  profileId: text("profile_id").notNull().references(() => agentProfiles.id, { onDelete: "cascade" }),
604
- fallbackProfileId: text("fallback_profile_id").references(() => agentProfiles.id, { onDelete: "set null" })
624
+ fallbackProvider: text("fallback_provider"),
625
+ fallbackModel: text("fallback_model"),
626
+ fallbackEffort: text("fallback_effort"),
627
+ fallbackConfigDir: text("fallback_config_dir")
605
628
  });
606
629
  const providerEvents = sqliteTable("provider_events", {
607
630
  id: text("id").primaryKey(),
@@ -686,7 +709,7 @@ const dbDataDirs = /* @__PURE__ */ new WeakMap();
686
709
  function getDbDataDir(db) {
687
710
  return dbDataDirs.get(db) ?? null;
688
711
  }
689
- const SCHEMA_VERSION = 7;
712
+ const SCHEMA_VERSION = 8;
690
713
  const BOOTSTRAP_SQL = `
691
714
  PRAGMA journal_mode = WAL;
692
715
  PRAGMA foreign_keys = ON;
@@ -795,6 +818,10 @@ CREATE TABLE IF NOT EXISTS agent_profiles (
795
818
  max_parallel INTEGER NOT NULL DEFAULT 1,
796
819
  max_review_rounds INTEGER NOT NULL DEFAULT 2,
797
820
  fallback_profile_id TEXT,
821
+ fallback_provider TEXT,
822
+ fallback_model TEXT,
823
+ fallback_effort TEXT,
824
+ fallback_config_dir TEXT,
798
825
  config_dir TEXT,
799
826
  is_default INTEGER NOT NULL DEFAULT 0,
800
827
  created_at TEXT NOT NULL
@@ -806,7 +833,11 @@ CREATE TABLE IF NOT EXISTS routing_rules (
806
833
  role TEXT NOT NULL,
807
834
  complexity TEXT,
808
835
  profile_id TEXT NOT NULL REFERENCES agent_profiles(id) ON DELETE CASCADE,
809
- fallback_profile_id TEXT REFERENCES agent_profiles(id) ON DELETE SET NULL
836
+ fallback_profile_id TEXT REFERENCES agent_profiles(id) ON DELETE SET NULL,
837
+ fallback_provider TEXT,
838
+ fallback_model TEXT,
839
+ fallback_effort TEXT,
840
+ fallback_config_dir TEXT
810
841
  );
811
842
 
812
843
  CREATE TABLE IF NOT EXISTS provider_events (
@@ -892,6 +923,24 @@ CREATE TABLE IF NOT EXISTS integration_runs (
892
923
  finished_at TEXT NOT NULL
893
924
  );
894
925
  `;
926
+ /** Role instructions of the seeded profiles. Earlier releases seeded shorter text; see refreshDefaultRolePrompts. */
927
+ const DEFAULT_ROLE_PROMPTS = {
928
+ "profile-lead": "You are the Lead: the architect and planner of this project, not its coder.\n- Clarify before you plan. Ask only questions whose answers change what gets built, one decision per question, and offer concrete options with the trade-off of each.\n- Write briefs a stranger could build from: goal, scope, non-goals, constraints, and measurable done-criteria. Never invent requirements the user did not state; mark your own assumptions as assumptions.\n- Split work into small tasks that one agent can finish and verify on its own. Give every task a precise goal, acceptance criteria that can be checked, the narrowest files_allowed that still works, dependencies only when one task truly needs another's output, and a verify command that fails when the work is wrong.\n- Keep tasks that touch the same files apart in time, not in parallel. Mark a task needs_split instead of handing a vague or oversized one to a coder.\n- Read PROJECT.md and the existing code before deciding on structure. Follow the project's conventions and reuse what exists before proposing something new.",
929
+ "profile-coder-small": "You are a focused engineer working a small, well-scoped task.\n- Do exactly what the goal and acceptance criteria ask, with the smallest change that satisfies them. No refactors, renames, or cleanups outside the task, and no new dependencies.\n- Read PROJECT.md and the code around your change first. Match the existing style, naming, and patterns, and reuse existing helpers.\n- Stay inside files_allowed. If the task needs a file outside it, stop and report it as blocked instead of editing it.\n- Cover the new or changed behaviour with a test when the project has tests, then run the verify command and fix what it reports. Never weaken or delete a test to make it pass.\n- Report honestly: what you changed, which commands you ran and their results, and anything left undone. If the goal is ambiguous, contradictory, or larger than described, stop and report blocked with the reason rather than guessing.",
930
+ "profile-coder-heavy": "You are a senior engineer taking on multi-file or high-complexity work.\n- Understand before you edit: read the relevant modules, trace the data flow and the callers of anything you change, and form a short plan first. Prefer the root cause over a patch on the symptom.\n- Keep the change cohesive. Put logic where it belongs, preserve public interfaces and existing behaviour that the task does not mention, and reuse existing abstractions before adding new ones. Add a dependency only when it clearly lowers total complexity.\n- Handle the edge cases: empty and invalid input, error paths, concurrency, partial failure, and data loss. Validate at trust boundaries and never log or commit secrets.\n- Write tests for the behaviour you add or change, including the failure cases, and update docs or types the change touches. Run the verify command and fix real causes; never weaken or delete a test to get green.\n- Stay inside files_allowed. If correctness needs a change beyond it, stop and report blocked with the exact file and reason. Finish by summarising what changed, how you verified it, and the risks or follow-ups that remain.",
931
+ "profile-reviewer": "You are an independent reviewer. You did not write this code and you do not fix it; you judge it.\n- Start from the acceptance criteria. Check each one against the actual diff and, where possible, against real behaviour. Run the verify command yourself and report its real output; do not trust the coder's summary.\n- Check that every changed file is inside files_allowed and that nothing unrelated slipped in.\n- Hunt for real defects: logic errors, unhandled edge cases and error paths, race conditions, resource leaks, broken or missing tests, regressions in untouched callers, and security problems such as injection, path traversal, unsafe deserialisation, and leaked secrets.\n- Rate each finding honestly: critical (breaks correctness or security), major (a likely bug or a missed criterion), minor (small and safe to defer), info (an observation). Fail the review only for unmet acceptance criteria or critical and major defects. Do not fail on style or personal preference.\n- Every finding names the file and line, says what goes wrong and when, and suggests a concrete fix. No speculation and no vague advice. Never modify files."
932
+ };
933
+ /** Prompts written by earlier releases. A profile still holding one of these was never customised. */
934
+ const PREVIOUS_ROLE_PROMPTS = {
935
+ "profile-lead": "Lead architect: clarify goals, author concise briefs, and decompose tasks with clear verify commands.",
936
+ "profile-coder-small": "Focused engineer for well-scoped, low-complexity tasks.",
937
+ "profile-coder-heavy": "Senior engineer for multi-file or high-complexity tasks.",
938
+ "profile-reviewer": "Independent reviewer verifying acceptance criteria and running test commands."
939
+ };
940
+ /** Upgrades untouched seeded profiles to the current role instructions; edited ones are left alone. */
941
+ function refreshDefaultRolePrompts(db) {
942
+ for (const [id, previous] of Object.entries(PREVIOUS_ROLE_PROMPTS)) db.update(agentProfiles).set({ rolePrompt: DEFAULT_ROLE_PROMPTS[id] }).where(and(eq(agentProfiles.id, id), eq(agentProfiles.rolePrompt, previous))).run();
943
+ }
895
944
  function seedDefaults(db) {
896
945
  if (db.select().from(agentProfiles).all().length > 0) return;
897
946
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -902,7 +951,7 @@ function seedDefaults(db) {
902
951
  provider: "claude-code",
903
952
  model: "",
904
953
  effort: "high",
905
- rolePrompt: "Lead architect: clarify goals, author concise briefs, and decompose tasks with clear verify commands.",
954
+ rolePrompt: DEFAULT_ROLE_PROMPTS["profile-lead"],
906
955
  permissionMode: "workspace-write",
907
956
  timeoutMs: 18e5,
908
957
  idleTimeoutMs: 18e4,
@@ -917,7 +966,7 @@ function seedDefaults(db) {
917
966
  provider: "codex",
918
967
  model: "",
919
968
  effort: "low",
920
- rolePrompt: "Focused engineer for well-scoped, low-complexity tasks.",
969
+ rolePrompt: DEFAULT_ROLE_PROMPTS["profile-coder-small"],
921
970
  permissionMode: "workspace-write",
922
971
  timeoutMs: 18e5,
923
972
  idleTimeoutMs: 18e4,
@@ -932,7 +981,7 @@ function seedDefaults(db) {
932
981
  provider: "claude-code",
933
982
  model: "",
934
983
  effort: "high",
935
- rolePrompt: "Senior engineer for multi-file or high-complexity tasks.",
984
+ rolePrompt: DEFAULT_ROLE_PROMPTS["profile-coder-heavy"],
936
985
  permissionMode: "workspace-write",
937
986
  timeoutMs: 18e5,
938
987
  idleTimeoutMs: 18e4,
@@ -947,7 +996,7 @@ function seedDefaults(db) {
947
996
  provider: "antigravity",
948
997
  model: "gemini-4-hydrogen-high",
949
998
  effort: "high",
950
- rolePrompt: "Independent reviewer verifying acceptance criteria and running test commands.",
999
+ rolePrompt: DEFAULT_ROLE_PROMPTS["profile-reviewer"],
951
1000
  permissionMode: "read-only",
952
1001
  timeoutMs: 12e5,
953
1002
  idleTimeoutMs: 18e4,
@@ -965,7 +1014,9 @@ function seedDefaults(db) {
965
1014
  role: "lead",
966
1015
  complexity: null,
967
1016
  profileId: "profile-lead",
968
- fallbackProfileId: null
1017
+ fallbackProvider: null,
1018
+ fallbackModel: null,
1019
+ fallbackEffort: null
969
1020
  },
970
1021
  {
971
1022
  id: crypto.randomUUID(),
@@ -973,7 +1024,10 @@ function seedDefaults(db) {
973
1024
  role: "engineer",
974
1025
  complexity: "low",
975
1026
  profileId: "profile-coder-small",
976
- fallbackProfileId: "profile-coder-heavy"
1027
+ fallbackProvider: "claude-code",
1028
+ fallbackModel: "",
1029
+ fallbackEffort: "high",
1030
+ fallbackConfigDir: null
977
1031
  },
978
1032
  {
979
1033
  id: crypto.randomUUID(),
@@ -981,7 +1035,10 @@ function seedDefaults(db) {
981
1035
  role: "engineer",
982
1036
  complexity: "medium",
983
1037
  profileId: "profile-coder-heavy",
984
- fallbackProfileId: "profile-lead"
1038
+ fallbackProvider: "codex",
1039
+ fallbackModel: "",
1040
+ fallbackEffort: "high",
1041
+ fallbackConfigDir: null
985
1042
  },
986
1043
  {
987
1044
  id: crypto.randomUUID(),
@@ -989,7 +1046,10 @@ function seedDefaults(db) {
989
1046
  role: "engineer",
990
1047
  complexity: "high",
991
1048
  profileId: "profile-coder-heavy",
992
- fallbackProfileId: "profile-lead"
1049
+ fallbackProvider: "codex",
1050
+ fallbackModel: "",
1051
+ fallbackEffort: "high",
1052
+ fallbackConfigDir: null
993
1053
  },
994
1054
  {
995
1055
  id: crypto.randomUUID(),
@@ -997,7 +1057,10 @@ function seedDefaults(db) {
997
1057
  role: "qa",
998
1058
  complexity: null,
999
1059
  profileId: "profile-reviewer",
1000
- fallbackProfileId: "profile-lead"
1060
+ fallbackProvider: "claude-code",
1061
+ fallbackModel: "",
1062
+ fallbackEffort: "high",
1063
+ fallbackConfigDir: null
1001
1064
  },
1002
1065
  {
1003
1066
  id: crypto.randomUUID(),
@@ -1005,7 +1068,10 @@ function seedDefaults(db) {
1005
1068
  role: "reviewer",
1006
1069
  complexity: null,
1007
1070
  profileId: "profile-reviewer",
1008
- fallbackProfileId: "profile-lead"
1071
+ fallbackProvider: "claude-code",
1072
+ fallbackModel: "",
1073
+ fallbackEffort: "high",
1074
+ fallbackConfigDir: null
1009
1075
  }
1010
1076
  ]).run();
1011
1077
  }
@@ -1035,7 +1101,12 @@ function seedReviewerRule(db) {
1035
1101
  role: "reviewer",
1036
1102
  complexity: null,
1037
1103
  profileId: reviewer.id,
1038
- fallbackProfileId: lead && lead.id !== reviewer.id ? lead.id : null
1104
+ ...lead && lead.id !== reviewer.id ? {
1105
+ fallbackProvider: lead.provider,
1106
+ fallbackModel: lead.model,
1107
+ fallbackEffort: lead.effort,
1108
+ fallbackConfigDir: lead.configDir
1109
+ } : {}
1039
1110
  }).run();
1040
1111
  }
1041
1112
  }
@@ -1051,7 +1122,12 @@ function migrateV1ToV2(db) {
1051
1122
  role: "engineer",
1052
1123
  complexity: "medium",
1053
1124
  profileId: heavy.id,
1054
- fallbackProfileId: lead ? lead.id : null
1125
+ ...lead ? {
1126
+ fallbackProvider: lead.provider,
1127
+ fallbackModel: lead.model,
1128
+ fallbackEffort: lead.effort,
1129
+ fallbackConfigDir: lead.configDir
1130
+ } : {}
1055
1131
  }).run();
1056
1132
  }
1057
1133
  function migrateToV5(sqlite) {
@@ -1078,6 +1154,39 @@ function migrateToV7(sqlite) {
1078
1154
  addColumnIfMissing(sqlite, "runs", "estimated_cost_usd", "REAL");
1079
1155
  addColumnIfMissing(sqlite, "runs", "cost_source", "TEXT");
1080
1156
  }
1157
+ /**
1158
+ * v8: a fallback is a CLI, model, and effort instead of a profile, and the seeded engineer rules
1159
+ * run low, medium, high (an older upgrade left medium after high).
1160
+ */
1161
+ function migrateToV8(sqlite) {
1162
+ for (const table of ["agent_profiles", "routing_rules"]) {
1163
+ addColumnIfMissing(sqlite, table, "fallback_provider", "TEXT");
1164
+ addColumnIfMissing(sqlite, table, "fallback_model", "TEXT");
1165
+ addColumnIfMissing(sqlite, table, "fallback_effort", "TEXT");
1166
+ addColumnIfMissing(sqlite, table, "fallback_config_dir", "TEXT");
1167
+ sqlite.exec(`
1168
+ UPDATE ${table} SET
1169
+ fallback_provider = (SELECT f.provider FROM agent_profiles f WHERE f.id = ${table}.fallback_profile_id),
1170
+ fallback_model = (SELECT f.model FROM agent_profiles f WHERE f.id = ${table}.fallback_profile_id),
1171
+ fallback_effort = (SELECT f.effort FROM agent_profiles f WHERE f.id = ${table}.fallback_profile_id),
1172
+ fallback_config_dir = (SELECT f.config_dir FROM agent_profiles f WHERE f.id = ${table}.fallback_profile_id)
1173
+ WHERE fallback_profile_id IS NOT NULL AND fallback_provider IS NULL
1174
+ AND EXISTS (SELECT 1 FROM agent_profiles f WHERE f.id = ${table}.fallback_profile_id);
1175
+ `);
1176
+ }
1177
+ const tiers = sqlite.prepare(`SELECT id, complexity, sort_order FROM routing_rules WHERE role = 'engineer' AND complexity IN ('low', 'medium', 'high')`).all();
1178
+ const rank = {
1179
+ low: 0,
1180
+ medium: 1,
1181
+ high: 2
1182
+ };
1183
+ const slots = tiers.map((r) => r.sort_order).sort((a, b) => a - b);
1184
+ const ordered = [...tiers].sort((a, b) => rank[a.complexity] - rank[b.complexity]);
1185
+ const update = sqlite.prepare("UPDATE routing_rules SET sort_order = ? WHERE id = ?");
1186
+ ordered.forEach((r, i) => update.run(slots[i], r.id));
1187
+ sqlite.prepare(`SELECT id FROM routing_rules ORDER BY sort_order,
1188
+ CASE complexity WHEN 'low' THEN 0 WHEN 'medium' THEN 1 WHEN 'high' THEN 2 ELSE 3 END, rowid`).all().forEach((r, i) => update.run(i + 1, r.id));
1189
+ }
1081
1190
  function openDatabase(dbFilePath = getDbPath()) {
1082
1191
  const dataDir = dbFilePath !== ":memory:" ? path.dirname(dbFilePath) : null;
1083
1192
  if (dataDir) ensureDir(dataDir);
@@ -1093,9 +1202,11 @@ function openDatabase(dbFilePath = getDbPath()) {
1093
1202
  if (upgrading && storedVersion < 5) migrateToV5(sqlite);
1094
1203
  if (upgrading && storedVersion < 6) migrateToV6(sqlite);
1095
1204
  if (upgrading && storedVersion < 7) migrateToV7(sqlite);
1205
+ if (upgrading && storedVersion < 8) migrateToV8(sqlite);
1096
1206
  const db = drizzle(sqlite, { schema: schema_exports });
1097
1207
  dbDataDirs.set(db, dataDir);
1098
1208
  seedDefaults(db);
1209
+ refreshDefaultRolePrompts(db);
1099
1210
  if (storedVersion > 0 && storedVersion < 2) migrateV1ToV2(db);
1100
1211
  if (upgrading && storedVersion < 4) seedReviewerRule(db);
1101
1212
  sqlite.pragma(`user_version = ${SCHEMA_VERSION}`);
@@ -2147,7 +2258,7 @@ var CodexAdapter = class {
2147
2258
  method: "initialize",
2148
2259
  params: { clientInfo: {
2149
2260
  name: "dalang",
2150
- version: "0.5.0"
2261
+ version: DALANG_VERSION
2151
2262
  } }
2152
2263
  }) + "\n" + JSON.stringify({
2153
2264
  jsonrpc: "2.0",
@@ -3637,7 +3748,7 @@ var ProjectService = class {
3637
3748
  name: derivedName,
3638
3749
  path: resolvedPath,
3639
3750
  mainBranch,
3640
- leadProvider: input.leadProvider ?? "claude-code",
3751
+ leadProvider: input.leadProvider ?? this.defaultLeadProvider(),
3641
3752
  leadModel: input.leadModel?.trim() || null,
3642
3753
  createdAt: now,
3643
3754
  updatedAt: now
@@ -3647,6 +3758,10 @@ var ProjectService = class {
3647
3758
  listProjects() {
3648
3759
  return this.db.select().from(projects).orderBy(desc(projects.updatedAt)).all().map((row) => this.toSummary(row));
3649
3760
  }
3761
+ /** The provider of the profile the Lead routing rule points at, so new projects follow the team setup. */
3762
+ defaultLeadProvider() {
3763
+ return this.db.select({ provider: agentProfiles.provider }).from(routingRules).innerJoin(agentProfiles, eq(routingRules.profileId, agentProfiles.id)).where(eq(routingRules.role, "lead")).orderBy(routingRules.sortOrder).limit(1).get()?.provider ?? "claude-code";
3764
+ }
3650
3765
  getProject(id) {
3651
3766
  const row = this.db.select().from(projects).where(eq(projects.id, id)).get();
3652
3767
  if (!row) throw new Error(`Project not found: ${id}`);
@@ -3733,6 +3848,45 @@ var ProjectService = class {
3733
3848
  }
3734
3849
  };
3735
3850
  // ../core/dist/services/profiles.js
3851
+ /** Reads the three nullable fallback columns back into one target. */
3852
+ function targetFromColumns(row) {
3853
+ if (!row.fallbackProvider) return null;
3854
+ return {
3855
+ provider: row.fallbackProvider,
3856
+ model: row.fallbackModel ?? "",
3857
+ effort: row.fallbackEffort ?? "medium",
3858
+ configDir: row.fallbackConfigDir ?? null
3859
+ };
3860
+ }
3861
+ function targetToColumns(target) {
3862
+ return {
3863
+ fallbackProvider: target?.provider ?? null,
3864
+ fallbackModel: target ? target.model : null,
3865
+ fallbackEffort: target?.effort ?? null,
3866
+ fallbackConfigDir: target?.configDir?.trim() || null
3867
+ };
3868
+ }
3869
+ /** Two routes are the same when they would start the same CLI with the same model. */
3870
+ function sameRoute(a, b) {
3871
+ return a.provider === b.provider && a.model === b.model;
3872
+ }
3873
+ /**
3874
+ * The fallback run: the primary profile (role instructions, limits, permissions) started on another
3875
+ * CLI, model, and effort. Null when the target would not change anything.
3876
+ */
3877
+ function withFallbackTarget(primary, target) {
3878
+ if (!target) return null;
3879
+ const configDir = target.configDir ?? (target.provider === primary.provider ? primary.configDir : null);
3880
+ if (sameRoute(primary, target) && primary.effort === target.effort && configDir === primary.configDir) return null;
3881
+ return {
3882
+ ...primary,
3883
+ provider: target.provider,
3884
+ model: target.model,
3885
+ effort: target.effort,
3886
+ configDir,
3887
+ fallback: null
3888
+ };
3889
+ }
3736
3890
  var ProfileService = class {
3737
3891
  db;
3738
3892
  constructor(db) {
@@ -3748,7 +3902,7 @@ var ProfileService = class {
3748
3902
  }
3749
3903
  createProfile(input) {
3750
3904
  if (this.db.select().from(agentProfiles).where(eq(agentProfiles.name, input.name)).get()) throw new Error(`An agent profile named "${input.name}" already exists.`);
3751
- const dirError = configDirError(input.configDir);
3905
+ const dirError = configDirError(input.configDir) ?? configDirError(input.fallback?.configDir);
3752
3906
  if (dirError) throw new Error(dirError);
3753
3907
  const id = `profile-${crypto.randomUUID().slice(0, 8)}`;
3754
3908
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -3764,7 +3918,7 @@ var ProfileService = class {
3764
3918
  idleTimeoutMs: input.idleTimeoutMs,
3765
3919
  maxParallel: input.maxParallel,
3766
3920
  maxReviewRounds: input.maxReviewRounds,
3767
- fallbackProfileId: this.checkedFallbackId(input.fallbackProfileId, null),
3921
+ ...targetToColumns(input.fallback),
3768
3922
  configDir: input.configDir?.trim() || null,
3769
3923
  isDefault: false,
3770
3924
  createdAt: now
@@ -3773,7 +3927,7 @@ var ProfileService = class {
3773
3927
  }
3774
3928
  updateProfile(id, input) {
3775
3929
  const current = this.getProfile(id);
3776
- const dirError = configDirError(input.configDir);
3930
+ const dirError = configDirError(input.configDir) ?? configDirError(input.fallback?.configDir);
3777
3931
  if (dirError) throw new Error(dirError);
3778
3932
  if (input.name && input.name !== current.name) {
3779
3933
  const conflict = this.db.select().from(agentProfiles).where(eq(agentProfiles.name, input.name)).get();
@@ -3790,24 +3944,15 @@ var ProfileService = class {
3790
3944
  ...input.idleTimeoutMs !== void 0 ? { idleTimeoutMs: input.idleTimeoutMs } : {},
3791
3945
  ...input.maxParallel !== void 0 ? { maxParallel: input.maxParallel } : {},
3792
3946
  ...input.maxReviewRounds !== void 0 ? { maxReviewRounds: input.maxReviewRounds } : {},
3793
- ...input.fallbackProfileId !== void 0 ? { fallbackProfileId: this.checkedFallbackId(input.fallbackProfileId, id) } : {},
3947
+ ...input.fallback !== void 0 ? targetToColumns(input.fallback) : {},
3794
3948
  ...input.configDir !== void 0 ? { configDir: input.configDir?.trim() || null } : {}
3795
3949
  }).where(eq(agentProfiles.id, id)).run();
3796
3950
  return this.getProfile(id);
3797
3951
  }
3798
- checkedFallbackId(fallbackId, selfId) {
3799
- if (!fallbackId) return null;
3800
- if (fallbackId === selfId) throw new Error("A profile cannot be its own fallback.");
3801
- this.getProfile(fallbackId);
3802
- return fallbackId;
3803
- }
3804
3952
  deleteProfile(id) {
3805
3953
  const target = this.getProfile(id);
3806
- const all = this.listProfiles();
3807
- if (all.length <= 1) throw new Error("Cannot delete the last remaining agent profile.");
3808
- if (this.db.select().from(routingRules).where(or(eq(routingRules.profileId, id), eq(routingRules.fallbackProfileId, id))).all().length > 0) throw new Error(`Cannot delete "${target.name}" while routing rules point to it. Update or remove those rules first.`);
3809
- const usedAsFallback = all.filter((p) => p.fallbackProfileId === id);
3810
- if (usedAsFallback.length > 0) throw new Error(`Cannot delete "${target.name}" while it is the fallback of ${usedAsFallback.map((p) => `"${p.name}"`).join(", ")}. Change that fallback first.`);
3954
+ if (this.listProfiles().length <= 1) throw new Error("Cannot delete the last remaining agent profile.");
3955
+ if (this.db.select().from(routingRules).where(eq(routingRules.profileId, id)).all().length > 0) throw new Error(`Cannot delete "${target.name}" while routing rules point to it. Update or remove those rules first.`);
3811
3956
  if (this.db.select().from(tasks).where(or(eq(tasks.profileOverride, id), eq(tasks.profileOverride, target.name))).get()) throw new Error(`Cannot delete "${target.name}" while a task is assigned to it.`);
3812
3957
  if (this.db.select().from(runs).where(eq(runs.profileId, id)).get()) throw new Error(`Cannot delete "${target.name}" because existing task runs reference it.`);
3813
3958
  this.db.delete(agentProfiles).where(eq(agentProfiles.id, id)).run();
@@ -3822,16 +3967,13 @@ var ProfileService = class {
3822
3967
  complexity: rule.complexity ?? null,
3823
3968
  profileId: rule.profileId,
3824
3969
  profileName: byId.get(rule.profileId)?.name ?? rule.profileId,
3825
- fallbackProfileId: rule.fallbackProfileId ?? null,
3826
- fallbackProfileName: rule.fallbackProfileId ? byId.get(rule.fallbackProfileId)?.name ?? rule.fallbackProfileId : null
3970
+ fallback: targetFromColumns(rule)
3827
3971
  }));
3828
3972
  }
3829
3973
  createRoutingRule(input) {
3830
3974
  this.getProfile(input.profileId);
3831
- if (input.fallbackProfileId) {
3832
- if (input.fallbackProfileId === input.profileId) throw new Error("Fallback profile must differ from primary profile.");
3833
- this.getProfile(input.fallbackProfileId);
3834
- }
3975
+ const dirError = configDirError(input.fallback?.configDir);
3976
+ if (dirError) throw new Error(dirError);
3835
3977
  const nextOrder = this.db.select().from(routingRules).all().reduce((max, r) => Math.max(max, r.sortOrder), 0) + 1;
3836
3978
  const id = crypto.randomUUID();
3837
3979
  this.db.insert(routingRules).values({
@@ -3840,7 +3982,7 @@ var ProfileService = class {
3840
3982
  role: input.role,
3841
3983
  complexity: input.complexity ?? null,
3842
3984
  profileId: input.profileId,
3843
- fallbackProfileId: input.fallbackProfileId ?? null
3985
+ ...targetToColumns(input.fallback)
3844
3986
  }).run();
3845
3987
  return this.listRoutingRules().find((r) => r.id === id);
3846
3988
  }
@@ -3848,17 +3990,15 @@ var ProfileService = class {
3848
3990
  const current = this.db.select().from(routingRules).where(eq(routingRules.id, id)).get();
3849
3991
  if (!current) throw new Error(`Routing rule not found: ${id}`);
3850
3992
  const nextProfileId = input.profileId ?? current.profileId;
3851
- const nextFallback = input.fallbackProfileId !== void 0 ? input.fallbackProfileId : current.fallbackProfileId;
3993
+ const nextFallback = input.fallback !== void 0 ? input.fallback : targetFromColumns(current);
3852
3994
  this.getProfile(nextProfileId);
3853
- if (nextFallback) {
3854
- if (nextFallback === nextProfileId) throw new Error("Fallback profile must differ from primary profile.");
3855
- this.getProfile(nextFallback);
3856
- }
3995
+ const dirError = configDirError(input.fallback?.configDir);
3996
+ if (dirError) throw new Error(dirError);
3857
3997
  this.db.update(routingRules).set({
3858
3998
  ...input.role !== void 0 ? { role: input.role } : {},
3859
3999
  ...input.complexity !== void 0 ? { complexity: input.complexity } : {},
3860
4000
  profileId: nextProfileId,
3861
- fallbackProfileId: nextFallback ?? null
4001
+ ...targetToColumns(nextFallback)
3862
4002
  }).where(eq(routingRules.id, id)).run();
3863
4003
  return this.listRoutingRules().find((r) => r.id === id);
3864
4004
  }
@@ -3889,36 +4029,35 @@ var ProfileService = class {
3889
4029
  const byId = new Map(profiles.map((p) => [p.id, p]));
3890
4030
  const byName = new Map(profiles.map((p) => [p.name, p]));
3891
4031
  const rules = this.db.select().from(routingRules).orderBy(asc(routingRules.sortOrder)).all();
3892
- const ownFallback = (ruleFallbackId, primary) => {
3893
- const f = byId.get(ruleFallbackId || primary.fallbackProfileId || "");
3894
- return f && f.id !== primary.id ? f : null;
3895
- };
4032
+ const lead = byId.get("profile-lead") ?? null;
4033
+ const leadTarget = lead ? {
4034
+ provider: lead.provider,
4035
+ model: lead.model,
4036
+ effort: lead.effort,
4037
+ configDir: lead.configDir
4038
+ } : null;
4039
+ const ownFallback = (ruleTarget, primary) => withFallbackTarget(primary, ruleTarget ?? primary.fallback) ?? withFallbackTarget(primary, leadTarget);
3896
4040
  const matchedRule = rules.find((r) => r.role === input.role && (r.complexity === null || r.complexity === input.complexity)) ?? null;
3897
4041
  if (input.profileOverride) {
3898
4042
  const overrideProfile = byId.get(input.profileOverride) ?? byName.get(input.profileOverride);
3899
- if (overrideProfile) {
3900
- const ruleFallback = ownFallback(matchedRule?.fallbackProfileId, overrideProfile);
3901
- const defaultFallback = byId.get("profile-lead") ?? null;
3902
- return {
3903
- primary: overrideProfile,
3904
- fallback: ruleFallback && ruleFallback.id !== overrideProfile.id ? ruleFallback : defaultFallback && defaultFallback.id !== overrideProfile.id ? defaultFallback : null,
3905
- source: "override"
3906
- };
3907
- }
4043
+ if (overrideProfile) return {
4044
+ primary: overrideProfile,
4045
+ fallback: ownFallback(matchedRule ? targetFromColumns(matchedRule) : null, overrideProfile),
4046
+ source: "override"
4047
+ };
3908
4048
  }
3909
4049
  if (matchedRule) {
3910
4050
  const primary = byId.get(matchedRule.profileId);
3911
4051
  if (primary) return {
3912
4052
  primary,
3913
- fallback: ownFallback(matchedRule.fallbackProfileId, primary),
4053
+ fallback: ownFallback(targetFromColumns(matchedRule), primary),
3914
4054
  source: "routing_rule"
3915
4055
  };
3916
4056
  }
3917
4057
  const fallbackDefault = (input.role === "qa" ? byId.get("profile-reviewer") : byId.get("profile-coder-heavy")) ?? byId.get("profile-lead") ?? profiles[0];
3918
- const lead = byId.get("profile-lead") ?? null;
3919
4058
  return {
3920
4059
  primary: fallbackDefault,
3921
- fallback: ownFallback(null, fallbackDefault) ?? (lead && lead.id !== fallbackDefault.id ? lead : null),
4060
+ fallback: ownFallback(null, fallbackDefault),
3922
4061
  source: "default"
3923
4062
  };
3924
4063
  }
@@ -3932,11 +4071,17 @@ var ProfileService = class {
3932
4071
  const rules = this.db.select().from(routingRules).orderBy(asc(routingRules.sortOrder)).all();
3933
4072
  const reviewerRule = rules.find((r) => r.role === "reviewer") ?? rules.find((r) => r.role === "qa") ?? null;
3934
4073
  const configuredPrimary = (reviewerRule ? byId.get(reviewerRule.profileId) : void 0) ?? byId.get("profile-reviewer") ?? byId.get("profile-lead") ?? profiles[0];
3935
- const configuredFallback = (reviewerRule?.fallbackProfileId ? byId.get(reviewerRule.fallbackProfileId) : void 0) ?? (configuredPrimary.fallbackProfileId ? byId.get(configuredPrimary.fallbackProfileId) : void 0) ?? byId.get("profile-lead") ?? null;
4074
+ const lead = byId.get("profile-lead") ?? null;
4075
+ const configuredFallback = withFallbackTarget(configuredPrimary, reviewerRule ? targetFromColumns(reviewerRule) : null) ?? withFallbackTarget(configuredPrimary, configuredPrimary.fallback) ?? (lead ? withFallbackTarget(configuredPrimary, {
4076
+ provider: lead.provider,
4077
+ model: lead.model,
4078
+ effort: lead.effort,
4079
+ configDir: lead.configDir
4080
+ }) : null);
3936
4081
  const isUsable = (p) => Boolean(p && !input.registry.providerBlockedReason(p.provider, input.sandboxReady));
3937
4082
  const blockedReason = input.registry.providerBlockedReason(configuredPrimary.provider, input.sandboxReady);
3938
4083
  let chosen = isUsable(configuredPrimary) ? configuredPrimary : null;
3939
- let fallback = configuredFallback && isUsable(configuredFallback) && configuredFallback.id !== chosen?.id ? configuredFallback : null;
4084
+ let fallback = configuredFallback && isUsable(configuredFallback) && !(chosen && sameRoute(configuredFallback, chosen)) ? configuredFallback : null;
3940
4085
  let note = null;
3941
4086
  if (!chosen) {
3942
4087
  if (isUsable(configuredFallback)) {
@@ -3960,7 +4105,7 @@ var ProfileService = class {
3960
4105
  if (crossCandidate) {
3961
4106
  const previous = chosen;
3962
4107
  chosen = crossCandidate;
3963
- fallback = isUsable(previous) && previous.id !== chosen.id ? previous : fallback;
4108
+ fallback = isUsable(previous) && !sameRoute(previous, chosen) ? previous : fallback;
3964
4109
  note = `Cross-model review: switched from ${previous.name} (${previous.provider}) to ${chosen.name} (${chosen.provider}) because coder used ${input.coderProvider}.`;
3965
4110
  } else note = note ?? `Cross-model review unavailable (no other usable provider besides ${input.coderProvider}); reviewing with ${chosen.name}.`;
3966
4111
  }
@@ -3974,7 +4119,7 @@ var ProfileService = class {
3974
4119
  } : null;
3975
4120
  return {
3976
4121
  primary: effectiveChosen,
3977
- fallback: effectiveFallback && effectiveFallback.id !== effectiveChosen.id ? effectiveFallback : null,
4122
+ fallback: effectiveFallback && !sameRoute(effectiveFallback, effectiveChosen) ? effectiveFallback : null,
3978
4123
  note,
3979
4124
  blocked: null
3980
4125
  };
@@ -3993,7 +4138,7 @@ function toDTO(row) {
3993
4138
  idleTimeoutMs: row.idleTimeoutMs,
3994
4139
  maxParallel: row.maxParallel,
3995
4140
  maxReviewRounds: row.maxReviewRounds ?? 2,
3996
- fallbackProfileId: row.fallbackProfileId ?? null,
4141
+ fallback: targetFromColumns(row),
3997
4142
  configDir: row.configDir ?? null,
3998
4143
  isDefault: Boolean(row.isDefault),
3999
4144
  createdAt: row.createdAt
@@ -4001,38 +4146,179 @@ function toDTO(row) {
4001
4146
  }
4002
4147
  // ../core/dist/services/settings.js
4003
4148
  const AGY_KEYRING_KEY = "antigravity_keyring_access";
4149
+ const LANGUAGE_KEY = "ui_language";
4150
+ const CHECK_UPDATES_KEY = "check_for_updates";
4151
+ const UPDATE_LATEST_KEY = "update_check_latest";
4152
+ const UPDATE_CHECKED_AT_KEY = "update_check_at";
4004
4153
  /**
4005
- * Global switches. Every one defaults to off, and the v0.3 agent profile editor is where they get
4006
- * a proper home; until then they are changed from the Providers page.
4154
+ * Global DALANG settings persisted in the SQLite `settings` table.
4007
4155
  */
4008
4156
  var SettingsService = class {
4009
4157
  db;
4010
4158
  constructor(db) {
4011
4159
  this.db = db;
4012
4160
  }
4013
- getBool(key) {
4014
- return this.db.select().from(settings).where(eq(settings.key, key)).get()?.value === "true";
4161
+ getValue(key) {
4162
+ return this.db.select().from(settings).where(eq(settings.key, key)).get()?.value ?? null;
4015
4163
  }
4016
- setBool(key, value) {
4164
+ setValue(key, value) {
4017
4165
  this.db.insert(settings).values({
4018
4166
  key,
4019
- value: String(value)
4167
+ value
4020
4168
  }).onConflictDoUpdate({
4021
4169
  target: settings.key,
4022
- set: { value: String(value) }
4170
+ set: { value }
4023
4171
  }).run();
4024
4172
  }
4173
+ getBool(key, defaultValue = false) {
4174
+ const raw = this.getValue(key);
4175
+ if (raw === null) return defaultValue;
4176
+ return raw === "true";
4177
+ }
4178
+ setBool(key, value) {
4179
+ this.setValue(key, String(value));
4180
+ }
4025
4181
  antigravityKeyringAccess() {
4026
- return this.getBool(AGY_KEYRING_KEY);
4182
+ return this.getBool(AGY_KEYRING_KEY, false);
4183
+ }
4184
+ language() {
4185
+ const raw = this.getValue(LANGUAGE_KEY);
4186
+ if (!raw) return null;
4187
+ const parsed = UiLanguageSchema.safeParse(raw);
4188
+ return parsed.success ? parsed.data : null;
4189
+ }
4190
+ resolvedLanguage() {
4191
+ return this.language() ?? "en";
4192
+ }
4193
+ checkForUpdates() {
4194
+ return this.getBool(CHECK_UPDATES_KEY, true);
4195
+ }
4196
+ getUpdateCache() {
4197
+ return {
4198
+ latestVersion: this.getValue(UPDATE_LATEST_KEY),
4199
+ checkedAt: this.getValue(UPDATE_CHECKED_AT_KEY)
4200
+ };
4201
+ }
4202
+ /** Records an attempt; a failed check passes `null` and keeps the last known version. */
4203
+ setUpdateCache(latestVersion, checkedAt) {
4204
+ if (latestVersion) this.setValue(UPDATE_LATEST_KEY, latestVersion);
4205
+ this.setValue(UPDATE_CHECKED_AT_KEY, checkedAt);
4027
4206
  }
4028
4207
  getAll() {
4029
- return { antigravityKeyringAccess: this.antigravityKeyringAccess() };
4208
+ return {
4209
+ antigravityKeyringAccess: this.antigravityKeyringAccess(),
4210
+ language: this.language(),
4211
+ checkForUpdates: this.checkForUpdates()
4212
+ };
4030
4213
  }
4031
4214
  update(input) {
4032
4215
  if (input.antigravityKeyringAccess !== void 0) this.setBool(AGY_KEYRING_KEY, input.antigravityKeyringAccess);
4216
+ if (input.language !== void 0) this.setValue(LANGUAGE_KEY, input.language);
4217
+ if (input.checkForUpdates !== void 0) this.setBool(CHECK_UPDATES_KEY, input.checkForUpdates);
4033
4218
  return this.getAll();
4034
4219
  }
4035
4220
  };
4221
+ // ../core/dist/services/update-check.js
4222
+ const NPM_REGISTRY_LATEST_URL = "https://registry.npmjs.org/dalang-cli/latest";
4223
+ const RELEASE_NOTES_URL = "https://github.com/azmifauzan/dalang/blob/main/CHANGELOG.md";
4224
+ /**
4225
+ * Compares two semver strings (e.g. "0.6.0" vs "0.7.0").
4226
+ * Returns > 0 if `a` is newer than `b`, < 0 if older, 0 if equal.
4227
+ */
4228
+ function compareSemver(a, b) {
4229
+ const parse = (v) => {
4230
+ const [core, prerelease = ""] = v.trim().replace(/^v/i, "").split("-", 2);
4231
+ const parts = core.split(".").map((n) => Number.parseInt(n, 10) || 0);
4232
+ return {
4233
+ major: parts[0] ?? 0,
4234
+ minor: parts[1] ?? 0,
4235
+ patch: parts[2] ?? 0,
4236
+ prerelease
4237
+ };
4238
+ };
4239
+ const pa = parse(a);
4240
+ const pb = parse(b);
4241
+ if (pa.major !== pb.major) return pa.major - pb.major;
4242
+ if (pa.minor !== pb.minor) return pa.minor - pb.minor;
4243
+ if (pa.patch !== pb.patch) return pa.patch - pb.patch;
4244
+ if (!pa.prerelease && pb.prerelease) return 1;
4245
+ if (pa.prerelease && !pb.prerelease) return -1;
4246
+ return pa.prerelease.localeCompare(pb.prerelease);
4247
+ }
4248
+ async function fetchLatestNpmVersion(timeoutMs = 4e3) {
4249
+ const controller = new AbortController();
4250
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
4251
+ try {
4252
+ const res = await fetch(NPM_REGISTRY_LATEST_URL, {
4253
+ method: "GET",
4254
+ headers: { Accept: "application/json" },
4255
+ signal: controller.signal
4256
+ });
4257
+ if (!res.ok) return null;
4258
+ const data = await res.json();
4259
+ return typeof data.version === "string" && data.version.trim() ? data.version.trim() : null;
4260
+ } catch {
4261
+ return null;
4262
+ } finally {
4263
+ clearTimeout(timer);
4264
+ }
4265
+ }
4266
+ /**
4267
+ * Checks npm registry at most once every 24h for a newer `dalang-cli` release, caching
4268
+ * the result in the SQLite `settings` table. Sends no project, account, or usage data,
4269
+ * and fails silently when offline or when disabled.
4270
+ */
4271
+ var UpdateCheckService = class {
4272
+ settings;
4273
+ currentVersion;
4274
+ fetcher;
4275
+ now;
4276
+ ttlMs;
4277
+ inFlight = null;
4278
+ constructor(settings, options = {}) {
4279
+ this.settings = settings;
4280
+ this.currentVersion = options.currentVersion ?? "0.6.0";
4281
+ this.fetcher = options.fetcher ?? fetchLatestNpmVersion;
4282
+ this.now = options.now ?? (() => Date.now());
4283
+ this.ttlMs = options.ttlMs ?? 864e5;
4284
+ }
4285
+ async getStatus(opts = {}) {
4286
+ if (!this.settings.checkForUpdates()) return {
4287
+ currentVersion: this.currentVersion,
4288
+ latestVersion: null,
4289
+ updateAvailable: false,
4290
+ checkedAt: null,
4291
+ checkEnabled: false,
4292
+ releaseNotesUrl: RELEASE_NOTES_URL
4293
+ };
4294
+ const cache = this.settings.getUpdateCache();
4295
+ const checkedMs = cache.checkedAt ? Date.parse(cache.checkedAt) : NaN;
4296
+ if (!opts.force && Number.isFinite(checkedMs) && this.now() - checkedMs < this.ttlMs) return this.statusFrom(cache.latestVersion, cache.checkedAt);
4297
+ if (!this.inFlight) this.inFlight = this.runFetch(cache).finally(() => {
4298
+ this.inFlight = null;
4299
+ });
4300
+ return this.inFlight;
4301
+ }
4302
+ statusFrom(latest, checkedAt) {
4303
+ return {
4304
+ currentVersion: this.currentVersion,
4305
+ latestVersion: latest,
4306
+ updateAvailable: latest !== null && compareSemver(latest, this.currentVersion) > 0,
4307
+ checkedAt,
4308
+ checkEnabled: true,
4309
+ releaseNotesUrl: RELEASE_NOTES_URL
4310
+ };
4311
+ }
4312
+ async runFetch(cache) {
4313
+ let latest = null;
4314
+ try {
4315
+ latest = await this.fetcher();
4316
+ } catch {}
4317
+ const checkedAt = new Date(this.now()).toISOString();
4318
+ this.settings.setUpdateCache(latest, checkedAt);
4319
+ return this.statusFrom(latest ?? cache.latestVersion, checkedAt);
4320
+ }
4321
+ };
4036
4322
  // ../core/dist/services/contract.js
4037
4323
  function isLink(target) {
4038
4324
  try {
@@ -4144,15 +4430,21 @@ function hasDependencyCycle(edges, sourceId, candidateDeps) {
4144
4430
  };
4145
4431
  return dfs(sourceId);
4146
4432
  }
4433
+ function buildLanguageInstruction(language) {
4434
+ if (language === "id") return "Language: Write all human-readable prose (questions, options, reasons, summaries, brief fields, milestone titles and descriptions, task titles, goals, and acceptance criteria) in clear, natural Indonesian (Bahasa Indonesia). Keep JSON keys, enum values, code, file paths, and verify commands in English.";
4435
+ return "Language: Write all human-readable prose in clear English. Keep JSON keys, enum values, code, file paths, and verify commands in English.";
4436
+ }
4147
4437
  var LeadService = class {
4148
4438
  db;
4149
4439
  registry;
4150
4440
  events;
4441
+ getLanguage;
4151
4442
  activeTurns = /* @__PURE__ */ new Set();
4152
- constructor(db, registry, events) {
4443
+ constructor(db, registry, events, getLanguage = () => "en") {
4153
4444
  this.db = db;
4154
4445
  this.registry = registry;
4155
4446
  this.events = events;
4447
+ this.getLanguage = getLanguage;
4156
4448
  }
4157
4449
  /** One Lead turn per project at a time: turns share a CLI session and write numbered artifacts. */
4158
4450
  async exclusiveTurn(projectId, run) {
@@ -4293,6 +4585,7 @@ var LeadService = class {
4293
4585
  const projectContext = fs.existsSync(projectMdPath) ? readArtifactFile(project.path, projectMdPath) : "";
4294
4586
  const prompt = [
4295
4587
  `You are the Lead architect in DALANG's Discuss phase.`,
4588
+ buildLanguageInstruction(this.getLanguage()),
4296
4589
  `Project: ${project.name} (${project.path})`,
4297
4590
  projectContext ? `\nCurrent PROJECT.md:\n${projectContext}\n` : "",
4298
4591
  `User input:\n${userText}`,
@@ -4376,6 +4669,7 @@ var LeadService = class {
4376
4669
  const transcriptSummary = this.getDiscussState(projectId).messages.map((m) => `[${m.role}/${m.type}] ${typeof m.content === "string" ? m.content : JSON.stringify(m.content)}`).join("\n");
4377
4670
  const prompt = [
4378
4671
  `The user has ended the Discuss Q&A ("enough, write the brief").`,
4672
+ buildLanguageInstruction(this.getLanguage()),
4379
4673
  `Synthesize everything discussed so far into a concrete, testable Project Brief.`,
4380
4674
  transcriptSummary ? `\nDiscussion transcript:\n${transcriptSummary}\n` : "",
4381
4675
  `Write the brief JSON directly to "${relBriefPath}" with version = ${nextVersion}.`,
@@ -4496,6 +4790,7 @@ var LeadService = class {
4496
4790
  const relBriefPath = path.relative(project.path, briefFilePath);
4497
4791
  const prompt = [
4498
4792
  `Revise the project brief based on the user's feedback note.`,
4793
+ buildLanguageInstruction(this.getLanguage()),
4499
4794
  `Previous brief (v${version}):\n${JSON.stringify(prevBrief.content, null, 2)}`,
4500
4795
  `User revision note:\n${note}`,
4501
4796
  ``,
@@ -4600,6 +4895,7 @@ var LeadService = class {
4600
4895
  const relDraftPath = path.relative(project.path, draftFilePath);
4601
4896
  const prompt = [
4602
4897
  `Break the approved project brief into concrete milestones and small, verifiable tasks.`,
4898
+ buildLanguageInstruction(this.getLanguage()),
4603
4899
  `Approved Brief (v${briefDto.version}):\n${JSON.stringify(briefDto.content, null, 2)}`,
4604
4900
  ``,
4605
4901
  `Task design rules:`,
@@ -4724,6 +5020,7 @@ var LeadService = class {
4724
5020
  const relSplitFile = path.relative(opts.projectPath, splitTargetFile);
4725
5021
  const prompt = [
4726
5022
  `Task "${item.task.id}" (${item.task.title}) has needs_split: true.`,
5023
+ buildLanguageInstruction(this.getLanguage()),
4727
5024
  `Split this task into 2 to 4 smaller, concrete subtasks (depth ${depth + 1} of 2).`,
4728
5025
  depth + 1 >= 2 ? `This is the maximum split depth (2), so every subtask MUST set "needs_split": false.` : `Only set "needs_split": true if a subtask is still genuinely too large.`,
4729
5026
  `Original task:\n${JSON.stringify(item.task, null, 2)}`,
@@ -5204,8 +5501,10 @@ function buildReviewPrompt(opts) {
5204
5501
  const jsonSchema = z.toJSONSchema(ReviewContractSchema);
5205
5502
  const isReadOnly = opts.profile.permissionMode === "read-only";
5206
5503
  const diffSnippet = opts.rawDiff.length > MAX_DIFF_PROMPT_CHARS ? `${opts.rawDiff.slice(0, MAX_DIFF_PROMPT_CHARS)}\n\n... [diff truncated for prompt; inspect repository files directly if needed]` : opts.rawDiff;
5504
+ const languageLine = opts.language === "id" ? `Language: Write the review "summary" and each finding "note" in clear, natural Indonesian (Bahasa Indonesia). Keep JSON keys, enum values ("pass", "fail", severities), file paths, and code identifiers in English.` : `Language: Write the review "summary" and each finding "note" in clear English. Keep JSON keys, enum values, file paths, and code identifiers in English.`;
5207
5505
  return [
5208
5506
  `You are performing code review round ${opts.round} of ${opts.maxRounds} for task ${opts.task.externalId}: "${opts.task.title}".`,
5507
+ languageLine,
5209
5508
  opts.profile.rolePrompt ? `Role instructions: ${opts.profile.rolePrompt}` : "",
5210
5509
  isReadOnly ? `Permission mode: READ-ONLY. Do NOT modify or create any files in the repository.` : `Do not modify application source files; only write the review output.`,
5211
5510
  ``,
@@ -5940,6 +6239,10 @@ function usageDbFields(provider, fallbackModel, usage) {
5940
6239
  costSource: est.source
5941
6240
  };
5942
6241
  }
6242
+ /** "codex · gpt-5" for a fallback run: the role stays the same, so the CLI and model are what differ. */
6243
+ function routeLabel(p) {
6244
+ return p.model ? `${p.provider} · ${p.model}` : p.provider;
6245
+ }
5943
6246
  var ExecutionService = class {
5944
6247
  db;
5945
6248
  registry;
@@ -5948,6 +6251,7 @@ var ExecutionService = class {
5948
6251
  profiles;
5949
6252
  worktreesRoot;
5950
6253
  quotaCooldownMs;
6254
+ getLanguage;
5951
6255
  limiter = new ProviderLimiter();
5952
6256
  activeTasks = /* @__PURE__ */ new Map();
5953
6257
  projectQueues = /* @__PURE__ */ new Map();
@@ -5960,6 +6264,7 @@ var ExecutionService = class {
5960
6264
  this.profiles = new ProfileService(db);
5961
6265
  this.worktreesRoot = options.worktreesRoot ?? getWorktreesRoot(getDbDataDir(db));
5962
6266
  this.quotaCooldownMs = options.quotaCooldownMs ?? DEFAULT_QUOTA_COOLDOWN_MS;
6267
+ this.getLanguage = options.getLanguage ?? (() => "en");
5963
6268
  this.reconcileInterruptedRuns();
5964
6269
  }
5965
6270
  /**
@@ -6085,12 +6390,17 @@ var ExecutionService = class {
6085
6390
  configDir: null,
6086
6391
  accountKey: provider
6087
6392
  }));
6088
- for (const prof of allProfiles) {
6089
- const dir = prof.configDir?.trim() || null;
6393
+ const named = [
6394
+ ...allProfiles,
6395
+ ...allProfiles.flatMap((p) => p.fallback ? [p.fallback] : []),
6396
+ ...this.profiles.listRoutingRules().flatMap((r) => r.fallback ? [r.fallback] : [])
6397
+ ];
6398
+ for (const entry of named) {
6399
+ const dir = entry.configDir?.trim() || null;
6090
6400
  if (!dir) continue;
6091
- const key = buildAccountKey(prof.provider, dir);
6401
+ const key = buildAccountKey(entry.provider, dir);
6092
6402
  if (!accounts.some((a) => a.accountKey === key)) accounts.push({
6093
- provider: prof.provider,
6403
+ provider: entry.provider,
6094
6404
  configDir: dir,
6095
6405
  accountKey: key
6096
6406
  });
@@ -6193,14 +6503,14 @@ var ExecutionService = class {
6193
6503
  ...routing,
6194
6504
  primary: backup,
6195
6505
  fallback: null,
6196
- note: `${routing.primary.name} routes to Antigravity, which is off. Running on ${backup.name} (${backup.provider}) instead. Enable keyring access in the Antigravity profile editor to use it.`,
6506
+ note: `${routing.primary.name} routes to Antigravity, which is off. Running on ${routeLabel(backup)} instead. Enable keyring access in the Antigravity profile editor to use it.`,
6197
6507
  quotaReroutedReason: null,
6198
6508
  proactiveFallback: false,
6199
6509
  skippedPrimaryProvider: null,
6200
6510
  skippedPrimaryConfigDir: null,
6201
6511
  blocked: null
6202
6512
  };
6203
- const reasonText = `${routing.primary.name} (${routing.primary.provider}) skipped (${primaryStatus.reason}); proactively routed to backup ${backup.name} (${backup.provider}).`;
6513
+ const reasonText = `${routing.primary.name} (${routing.primary.provider}) skipped (${primaryStatus.reason}); proactively routed to the fallback ${routeLabel(backup)}.`;
6204
6514
  return {
6205
6515
  ...routing,
6206
6516
  primary: backup,
@@ -6269,8 +6579,12 @@ var ExecutionService = class {
6269
6579
  resolvedProfileName: routing.primary.name,
6270
6580
  resolvedProvider: routing.primary.provider,
6271
6581
  resolvedModel: routing.primary.model,
6272
- fallbackProfileId: routing.fallback?.id ?? null,
6273
- fallbackProfileName: routing.fallback?.name ?? null,
6582
+ fallback: routing.fallback ? {
6583
+ provider: routing.fallback.provider,
6584
+ model: routing.fallback.model,
6585
+ effort: routing.fallback.effort,
6586
+ configDir: routing.fallback.configDir
6587
+ } : null,
6274
6588
  selectionSource: routing.source,
6275
6589
  selectionNote: routing.note,
6276
6590
  quotaReroutedReason: routing.quotaReroutedReason
@@ -7085,7 +7399,7 @@ var ExecutionService = class {
7085
7399
  profileName: opts.fallbackProfile.name,
7086
7400
  provider: opts.fallbackProfile.provider
7087
7401
  });
7088
- const fallbackBanner = `[dalang] Fallback triggered after ${opts.initialProfile.name} failed (${primaryOutcome.failureReason ?? "error"}). Switching to "${opts.fallbackProfile.name}" (${opts.fallbackProfile.provider}).`;
7402
+ const fallbackBanner = `[dalang] Fallback triggered after ${opts.initialProfile.name} failed (${primaryOutcome.failureReason ?? "error"}). Switching to ${routeLabel(opts.fallbackProfile)}.`;
7089
7403
  this.recordProviderEvent(opts.initialProfile.provider, "quota_fallback", fallbackBanner, opts.initialProfile.configDir);
7090
7404
  this.appendDalangLog(fbAbsLog, fallbackBanner);
7091
7405
  this.events?.emitEvent({
@@ -7133,7 +7447,7 @@ var ExecutionService = class {
7133
7447
  if (this.evaluateProviderUsability(resolved.fallback.provider, resolved.fallback.model || null, sandboxReady, resolved.fallback.configDir).usable) return {
7134
7448
  primary: resolved.fallback,
7135
7449
  fallback: null,
7136
- note: `${resolved.primary.name} (${resolved.primary.provider}) skipped (${primaryUsable.reason}); reviewing with ${resolved.fallback.name} (${resolved.fallback.provider}).`,
7450
+ note: `${resolved.primary.name} (${resolved.primary.provider}) skipped (${primaryUsable.reason}); reviewing with ${routeLabel(resolved.fallback)}.`,
7137
7451
  blocked: null
7138
7452
  };
7139
7453
  }
@@ -7272,7 +7586,7 @@ var ExecutionService = class {
7272
7586
  let fixNote = `Fix round ${round} addressing ${reviewData.findings.length} review finding(s).`;
7273
7587
  if (!coderUsability.usable && activeCoderFallback) {
7274
7588
  if (this.evaluateProviderUsability(activeCoderFallback.provider, activeCoderFallback.model || null, ctx.sandboxReady, activeCoderFallback.configDir).usable) {
7275
- fixNote = `Fix round ${round}: ${activeCoderProfile.name} skipped (${coderUsability.reason}); switched to ${activeCoderFallback.name}.`;
7589
+ fixNote = `Fix round ${round}: ${activeCoderProfile.name} skipped (${coderUsability.reason}); switched to ${routeLabel(activeCoderFallback)}.`;
7276
7590
  this.recordProviderEvent(activeCoderProfile.provider, "quota_fallback", fixNote, activeCoderProfile.configDir);
7277
7591
  activeCoderProfile = activeCoderFallback;
7278
7592
  activeCoderFallback = null;
@@ -7497,7 +7811,8 @@ var ExecutionService = class {
7497
7811
  changedFiles: opts.changedFiles,
7498
7812
  scopeWarnings: opts.scopeWarnings,
7499
7813
  rawDiff: opts.rawDiff,
7500
- coderResult: opts.coderResult
7814
+ coderResult: opts.coderResult,
7815
+ language: this.getLanguage()
7501
7816
  });
7502
7817
  let currentSessionId = null;
7503
7818
  let currentPrompt = initialPrompt;
@@ -8420,12 +8735,16 @@ async function createDalangServer(options = {}) {
8420
8735
  const conn = openDatabase(options.dbPath);
8421
8736
  const runner = options.runner ?? new NodeCliRunner();
8422
8737
  const settingsService = new SettingsService(conn.db);
8738
+ const updateCheckService = new UpdateCheckService(settingsService, {
8739
+ currentVersion: options.currentVersion ?? "0.6.0",
8740
+ fetcher: options.updateFetcher
8741
+ });
8423
8742
  const registry = new ProviderRegistry(runner, { antigravityKeyringAccess: () => settingsService.antigravityKeyringAccess() });
8424
8743
  const events = new DalangEventBus();
8425
8744
  const projectService = new ProjectService(conn.db);
8426
8745
  const profileService = new ProfileService(conn.db);
8427
- const leadService = new LeadService(conn.db, registry, events);
8428
- const executionService = new ExecutionService(conn.db, registry, leadService, events);
8746
+ const leadService = new LeadService(conn.db, registry, events, () => settingsService.resolvedLanguage());
8747
+ const executionService = new ExecutionService(conn.db, registry, leadService, events, { getLanguage: () => settingsService.resolvedLanguage() });
8429
8748
  const statsService = new StatisticsService(conn.db, () => executionService.getProviderRuntimeStates());
8430
8749
  let cachedProviderStatuses = null;
8431
8750
  let statusRefreshInFlight = null;
@@ -8462,8 +8781,18 @@ async function createDalangServer(options = {}) {
8462
8781
  });
8463
8782
  app.get("/api/health", async () => ({
8464
8783
  ok: true,
8465
- version: "0.5.0"
8784
+ version: options.currentVersion ?? "0.6.0"
8466
8785
  }));
8786
+ app.get("/api/update-status", async (req) => {
8787
+ const query = z.object({ force: z.enum([
8788
+ "0",
8789
+ "1",
8790
+ "true",
8791
+ "false"
8792
+ ]).optional() }).parse(req.query ?? {});
8793
+ const force = query.force === "1" || query.force === "true";
8794
+ return { update: await updateCheckService.getStatus({ force }) };
8795
+ });
8467
8796
  app.get("/ws", { websocket: true }, (socket) => {
8468
8797
  const unsubscribe = events.onEvent((event) => {
8469
8798
  if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(event));
@@ -8718,7 +9047,9 @@ async function startDalangServer(opts = {}) {
8718
9047
  const { app, close } = await createDalangServer({
8719
9048
  dbPath: opts.dbPath,
8720
9049
  staticDir: opts.staticDir,
8721
- runner: opts.runner
9050
+ runner: opts.runner,
9051
+ updateFetcher: opts.updateFetcher,
9052
+ currentVersion: opts.currentVersion
8722
9053
  });
8723
9054
  await app.listen({
8724
9055
  host: "127.0.0.1",
@@ -8737,6 +9068,21 @@ async function startDalangServer(opts = {}) {
8737
9068
  };
8738
9069
  }
8739
9070
  // dist/doctor.js
9071
+ /** Honors the Config → General toggle; a fresh install (no database yet) keeps the default, on. */
9072
+ function updateCheckEnabled(dataDir) {
9073
+ const dbFile = path.join(dataDir, "dalang.db");
9074
+ if (!fs.existsSync(dbFile)) return true;
9075
+ try {
9076
+ const conn = openDatabase(dbFile);
9077
+ try {
9078
+ return new SettingsService(conn.db).checkForUpdates();
9079
+ } finally {
9080
+ conn.close();
9081
+ }
9082
+ } catch {
9083
+ return true;
9084
+ }
9085
+ }
8740
9086
  async function runDoctorChecks(runner = new NodeCliRunner(), opts = {}) {
8741
9087
  const platform = opts.platform ?? process.platform;
8742
9088
  const checks = [];
@@ -8881,15 +9227,37 @@ async function runDoctorChecks(runner = new NodeCliRunner(), opts = {}) {
8881
9227
  detail: "None of claude, codex, or agy is installed and logged in.",
8882
9228
  fix: "Install and sign in to at least one CLI (`claude auth login`, `codex login`, or `agy`)."
8883
9229
  });
9230
+ const currentVersion = opts.currentVersion ?? "0.6.0";
9231
+ let latestVersion = null;
9232
+ let updateAvailable = false;
9233
+ if (opts.checkUpdates ?? updateCheckEnabled(dataDir)) {
9234
+ const fetcher = opts.updateFetcher ?? (() => fetchLatestNpmVersion(2500));
9235
+ try {
9236
+ latestVersion = await fetcher();
9237
+ if (latestVersion && compareSemver(latestVersion, currentVersion) > 0) {
9238
+ updateAvailable = true;
9239
+ checks.push({
9240
+ id: "update",
9241
+ label: "DALANG version",
9242
+ status: "warn",
9243
+ detail: `v${currentVersion} installed; v${latestVersion} is available on npm.`,
9244
+ fix: "Run `npx dalang-cli@latest` or `npm install -g dalang-cli@latest`."
9245
+ });
9246
+ }
9247
+ } catch {}
9248
+ }
8884
9249
  return {
8885
9250
  ok: !checks.some((c) => c.status === "fail"),
8886
9251
  platform,
8887
9252
  nodeVersion,
9253
+ version: currentVersion,
9254
+ latestVersion,
9255
+ updateAvailable,
8888
9256
  checks
8889
9257
  };
8890
9258
  }
8891
9259
  function formatDoctorReport(report) {
8892
- const lines = [`DALANG Doctor (platform=${report.platform}, node=v${report.nodeVersion})`, ""];
9260
+ const lines = [`DALANG Doctor v${report.version} (platform=${report.platform}, node=v${report.nodeVersion})`, ""];
8893
9261
  for (const item of report.checks) {
8894
9262
  const tag = item.status === "pass" ? "[PASS]" : item.status === "warn" ? "[WARN]" : "[FAIL]";
8895
9263
  lines.push(`${tag} ${item.label}: ${item.detail}`);
@@ -8900,7 +9268,6 @@ function formatDoctorReport(report) {
8900
9268
  return lines.join("\n");
8901
9269
  }
8902
9270
  // dist/cli.js
8903
- const DALANG_VERSION = "0.5.0";
8904
9271
  function resolveWebDistDir() {
8905
9272
  const here = path.dirname(fileURLToPath(import.meta.url));
8906
9273
  return [path.resolve(here, "../web-dist"), path.resolve(here, "../../web/dist")].find((dir) => fs.existsSync(path.join(dir, "index.html")));