@c4a/daemon 0.4.12-alpha.3 → 0.4.12-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +905 -75
  2. package/package.json +3 -2
  3. package/scheduler/index.js +14170 -0
package/index.js CHANGED
@@ -8794,6 +8794,7 @@ var RelationType;
8794
8794
  RelationType2["Triggers"] = "TRIGGERS";
8795
8795
  RelationType2["References"] = "REFERENCES";
8796
8796
  RelationType2["Corresponds"] = "CORRESPONDS";
8797
+ RelationType2["Mentions"] = "MENTIONS";
8797
8798
  })(RelationType ||= {});
8798
8799
  var AtomField;
8799
8800
  ((AtomField2) => {
@@ -8811,6 +8812,7 @@ var AtomField;
8811
8812
  AtomField2["Constraints"] = "constraints";
8812
8813
  AtomField2["Comparisons"] = "comparisons";
8813
8814
  AtomField2["Boundaries"] = "boundaries";
8815
+ AtomField2["Claims"] = "claims";
8814
8816
  })(AtomField ||= {});
8815
8817
  var Kind;
8816
8818
  ((Kind2) => {
@@ -8823,6 +8825,161 @@ var Perspective;
8823
8825
  Perspective2["Business"] = "business";
8824
8826
  Perspective2["Technical"] = "technical";
8825
8827
  })(Perspective ||= {});
8828
+ // ../core/src/types/edgeSyncRules.ts
8829
+ var EDGE_SYNC_RULES = [
8830
+ {
8831
+ field: "container_id",
8832
+ sourceEntityType: "component" /* Component */,
8833
+ edgeType: "CONTAINS" /* Contains */,
8834
+ direction: "reverse",
8835
+ writeGraph: true
8836
+ },
8837
+ {
8838
+ field: "system_id",
8839
+ sourceEntityType: "container" /* Container */,
8840
+ edgeType: "CONTAINS" /* Contains */,
8841
+ direction: "reverse",
8842
+ writeGraph: true
8843
+ },
8844
+ {
8845
+ field: "ref_sor",
8846
+ sourceEntityType: "sor" /* SoR */,
8847
+ edgeType: "REFERENCES" /* References */,
8848
+ direction: "forward",
8849
+ writeGraph: true
8850
+ },
8851
+ {
8852
+ field: "product_refs",
8853
+ sourceEntityType: "epic" /* Epic */,
8854
+ edgeType: "REFERENCES" /* References */,
8855
+ direction: "forward",
8856
+ writeGraph: true
8857
+ },
8858
+ {
8859
+ field: "atoms.entities.ref",
8860
+ sourceEntityType: "any",
8861
+ edgeType: "MENTIONS" /* Mentions */,
8862
+ direction: "forward",
8863
+ writeGraph: true
8864
+ },
8865
+ {
8866
+ field: "atoms.behaviors.ref",
8867
+ sourceEntityType: "any",
8868
+ edgeType: "MENTIONS" /* Mentions */,
8869
+ direction: "forward",
8870
+ writeGraph: true
8871
+ },
8872
+ {
8873
+ field: "product_id",
8874
+ sourceEntityType: "sor" /* SoR */,
8875
+ edgeType: null,
8876
+ direction: "forward",
8877
+ writeGraph: false
8878
+ },
8879
+ {
8880
+ field: "process_id",
8881
+ sourceEntityType: "sor" /* SoR */,
8882
+ edgeType: "PRODUCES" /* Produces */,
8883
+ direction: "reverse",
8884
+ writeGraph: true
8885
+ }
8886
+ ];
8887
+ // ../core/src/types/serverConfig.ts
8888
+ var DEFAULT_SERVER_CONFIG = {
8889
+ server: {
8890
+ port: 5100,
8891
+ host: "::"
8892
+ },
8893
+ git_hosts: [],
8894
+ daemon_scheduler: {
8895
+ enabled: true,
8896
+ host: "localhost",
8897
+ port: 5110,
8898
+ workspace: "./data/daemon-workspace",
8899
+ max_daemons: 20
8900
+ },
8901
+ doc_db: {
8902
+ provider: "sqlite",
8903
+ sqlite: {
8904
+ path: "./data/c4a.db"
8905
+ },
8906
+ mongodb: {
8907
+ uri: "mongodb://localhost:27017/c4a?directConnection=true",
8908
+ database: "c4a"
8909
+ }
8910
+ },
8911
+ graph_db: {
8912
+ provider: "neo4j",
8913
+ neo4j: {
8914
+ uri: "bolt://localhost:7687",
8915
+ username: "neo4j",
8916
+ password: ""
8917
+ },
8918
+ nebulagraph: {
8919
+ uri: "localhost:9669",
8920
+ username: "root",
8921
+ password: "nebula",
8922
+ space: "c4a"
8923
+ },
8924
+ duckdb: {
8925
+ path: "./data/c4a-graph.duckdb"
8926
+ }
8927
+ },
8928
+ vector_db: {
8929
+ provider: "lancedb",
8930
+ collection_prefix: "c4a_",
8931
+ qdrant: {
8932
+ url: "http://localhost:6333",
8933
+ api_key: ""
8934
+ },
8935
+ milvus: {
8936
+ address: "localhost:19530"
8937
+ },
8938
+ lancedb: {
8939
+ path: "./data/lancedb"
8940
+ }
8941
+ },
8942
+ llm: {
8943
+ provider: "openai",
8944
+ openai: {
8945
+ api_key: "",
8946
+ base_url: "",
8947
+ default_model: "gpt-5.3-codex"
8948
+ },
8949
+ anthropic: {
8950
+ api_key: "",
8951
+ base_url: "",
8952
+ default_model: "claude-opus-4-6"
8953
+ },
8954
+ google: {
8955
+ api_key: "",
8956
+ base_url: "",
8957
+ default_model: "gemini-3-pro-preview"
8958
+ }
8959
+ },
8960
+ embedding: {
8961
+ provider: "huggingface",
8962
+ huggingface: {
8963
+ model_id: "Xenova/all-MiniLM-L6-v2",
8964
+ dtype: "q8",
8965
+ cache_dir: "./models/embedding"
8966
+ },
8967
+ xenova: {
8968
+ model_id: "Xenova/bge-m3",
8969
+ dtype: "q8",
8970
+ cache_dir: "./models/embedding"
8971
+ },
8972
+ openai: {
8973
+ api_key: "",
8974
+ base_url: "",
8975
+ model_id: "text-embedding-3-small"
8976
+ },
8977
+ google: {
8978
+ api_key: "",
8979
+ model_id: "text-embedding-004"
8980
+ }
8981
+ }
8982
+ };
8826
8983
  // ../core/src/types/daemon.ts
8827
8984
  var CODE_PACKAGE_FILES = new Set([
8828
8985
  "package.json",
@@ -12867,7 +13024,7 @@ var atomFieldSchema = exports_external.enum(Object.values(AtomField));
12867
13024
  var kindSchema = exports_external.enum(Object.values(Kind));
12868
13025
  var scopeSchema = exports_external.literal("project");
12869
13026
  var perspectiveSchema = exports_external.enum(Object.values(Perspective));
12870
- var confidenceSchema = exports_external.object({
13027
+ var extractionConfidenceSchema = exports_external.object({
12871
13028
  structural: exports_external.number().min(0).max(1),
12872
13029
  semantic: exports_external.number().min(0).max(1)
12873
13030
  });
@@ -12875,13 +13032,29 @@ var metadataSchema = exports_external.object({
12875
13032
  created_at: exports_external.string().datetime(),
12876
13033
  updated_at: exports_external.string().datetime(),
12877
13034
  version_tag: exports_external.string().optional(),
12878
- confidence: confidenceSchema.optional()
12879
- });
13035
+ extraction_confidence: extractionConfidenceSchema.optional(),
13036
+ confidence: exports_external.number().min(0).max(1).optional(),
13037
+ aliases: exports_external.array(exports_external.string()).optional(),
13038
+ rank: exports_external.number().optional(),
13039
+ community_id: exports_external.string().optional(),
13040
+ community_level: exports_external.number().optional()
13041
+ });
13042
+ var entityRefPointerSchema = exports_external.string().regex(/^ref:entity:.+$/, "must be a ref pointer in format ref:entity:<id>");
13043
+ var sourceRefSpanSchema = exports_external.object({
13044
+ start: exports_external.number().int().min(1),
13045
+ end: exports_external.number().int().min(1)
13046
+ });
13047
+ var sourceRefSchema = exports_external.object({
13048
+ ref: exports_external.string(),
13049
+ span: sourceRefSpanSchema.optional()
13050
+ });
13051
+ var sourceRefsSchema = exports_external.array(sourceRefSchema).optional();
12880
13052
  // ../core/src/schemas/atomsSchema.ts
12881
13053
  var confidenceAtomSchema = exports_external.number().min(0).max(1).optional();
12882
13054
  var entityAtomSchema = exports_external.object({
12883
13055
  name: exports_external.string(),
12884
13056
  kind: kindSchema.optional(),
13057
+ ref: exports_external.string().optional(),
12885
13058
  confidence: confidenceAtomSchema
12886
13059
  });
12887
13060
  var relationAtomSchema = exports_external.object({
@@ -12895,6 +13068,8 @@ var behaviorAtomSchema = exports_external.object({
12895
13068
  name: exports_external.string(),
12896
13069
  signature: exports_external.string().optional(),
12897
13070
  description: exports_external.string().optional(),
13071
+ performed_by: exports_external.array(exports_external.string()).optional(),
13072
+ ref: exports_external.string().optional(),
12898
13073
  confidence: confidenceAtomSchema
12899
13074
  });
12900
13075
  var attributeAtomSchema = exports_external.object({
@@ -12935,6 +13110,7 @@ var decisionPhaseSchema = exports_external.object({
12935
13110
  rationale: exports_external.string().optional()
12936
13111
  });
12937
13112
  var decisionAtomSchema = exports_external.object({
13113
+ name: exports_external.string().optional(),
12938
13114
  description: exports_external.string(),
12939
13115
  rationale: exports_external.string(),
12940
13116
  alternatives: exports_external.array(exports_external.string()).optional(),
@@ -12957,9 +13133,9 @@ var metricAtomSchema = exports_external.object({
12957
13133
  });
12958
13134
  var roleAtomSchema = exports_external.object({
12959
13135
  name: exports_external.string(),
12960
- kind: exports_external.enum(["internal", "external"]),
13136
+ kind: exports_external.enum(["human", "team", "persona"]),
12961
13137
  performs: exports_external.array(exports_external.string()).optional(),
12962
- confidence: confidenceAtomSchema
13138
+ description: exports_external.string().optional()
12963
13139
  });
12964
13140
  var constraintAtomSchema = exports_external.object({
12965
13141
  description: exports_external.string(),
@@ -12990,6 +13166,16 @@ var comparisonAtomSchema = exports_external.object({
12990
13166
  decision_ref: exports_external.string().optional(),
12991
13167
  confidence: confidenceAtomSchema
12992
13168
  });
13169
+ var claimAtomSchema = exports_external.object({
13170
+ claim_type: exports_external.string(),
13171
+ description: exports_external.string(),
13172
+ status: exports_external.enum(["active", "deprecated", "proposed"]),
13173
+ valid_from: exports_external.string(),
13174
+ valid_until: exports_external.string().optional(),
13175
+ session_ref: exports_external.string().optional(),
13176
+ changed_by: exports_external.string(),
13177
+ confidence: confidenceAtomSchema
13178
+ });
12993
13179
  var dataAtomsSchema = exports_external.object({
12994
13180
  entities: exports_external.array(entityAtomSchema).optional(),
12995
13181
  relations: exports_external.array(relationAtomSchema).optional(),
@@ -13004,31 +13190,115 @@ var dataAtomsSchema = exports_external.object({
13004
13190
  roles: exports_external.array(roleAtomSchema).optional(),
13005
13191
  constraints: exports_external.array(constraintAtomSchema).optional(),
13006
13192
  comparisons: exports_external.array(comparisonAtomSchema).optional(),
13007
- boundaries: exports_external.array(boundaryAtomSchema).optional()
13193
+ boundaries: exports_external.array(boundaryAtomSchema).optional(),
13194
+ claims: exports_external.array(claimAtomSchema).optional()
13008
13195
  }).superRefine((atoms2, ctx) => {
13009
- if (!atoms2.transitions || atoms2.transitions.length === 0) {
13010
- return;
13011
- }
13012
13196
  const stateValues = new Set;
13197
+ const stateNames = new Set;
13013
13198
  for (const state of atoms2.states ?? []) {
13199
+ stateNames.add(state.name);
13014
13200
  for (const value of state.values) {
13015
13201
  stateValues.add(value);
13016
13202
  }
13017
13203
  }
13018
- for (const transition of atoms2.transitions) {
13019
- if (!stateValues.has(transition.from)) {
13020
- ctx.addIssue({
13021
- code: exports_external.ZodIssueCode.custom,
13022
- path: ["transitions"],
13023
- message: `transition.from references unknown state: ${transition.from}`
13024
- });
13204
+ const behaviorNames = new Set;
13205
+ for (const behavior of atoms2.behaviors ?? []) {
13206
+ behaviorNames.add(behavior.name);
13207
+ }
13208
+ const roleNames = new Set;
13209
+ for (const role of atoms2.roles ?? []) {
13210
+ roleNames.add(role.name);
13211
+ }
13212
+ const eventNames = new Set;
13213
+ for (const event of atoms2.events ?? []) {
13214
+ eventNames.add(event.name);
13215
+ }
13216
+ const metricNames = new Set;
13217
+ for (const metric of atoms2.metrics ?? []) {
13218
+ metricNames.add(metric.name);
13219
+ }
13220
+ if (atoms2.transitions && atoms2.transitions.length > 0) {
13221
+ for (const transition of atoms2.transitions) {
13222
+ if (!stateValues.has(transition.from)) {
13223
+ ctx.addIssue({
13224
+ code: exports_external.ZodIssueCode.custom,
13225
+ path: ["transitions"],
13226
+ message: `transition.from references unknown state: ${transition.from}`
13227
+ });
13228
+ }
13229
+ if (!stateValues.has(transition.to)) {
13230
+ ctx.addIssue({
13231
+ code: exports_external.ZodIssueCode.custom,
13232
+ path: ["transitions"],
13233
+ message: `transition.to references unknown state: ${transition.to}`
13234
+ });
13235
+ }
13236
+ const hasEvents = eventNames.size > 0;
13237
+ const hasBehaviors = behaviorNames.size > 0;
13238
+ if (hasEvents || hasBehaviors) {
13239
+ const triggerMatchesEvent = hasEvents && eventNames.has(transition.trigger);
13240
+ const triggerMatchesBehavior = hasBehaviors && behaviorNames.has(transition.trigger);
13241
+ if (!triggerMatchesEvent && !triggerMatchesBehavior) {
13242
+ ctx.addIssue({
13243
+ code: exports_external.ZodIssueCode.custom,
13244
+ path: ["transitions"],
13245
+ message: `transition.trigger references unknown event/behavior: ${transition.trigger}`
13246
+ });
13247
+ }
13248
+ }
13025
13249
  }
13026
- if (!stateValues.has(transition.to)) {
13027
- ctx.addIssue({
13028
- code: exports_external.ZodIssueCode.custom,
13029
- path: ["transitions"],
13030
- message: `transition.to references unknown state: ${transition.to}`
13031
- });
13250
+ }
13251
+ if (atoms2.roles && atoms2.roles.length > 0) {
13252
+ for (const [index, role] of atoms2.roles.entries()) {
13253
+ for (const perform of role.performs ?? []) {
13254
+ if (!behaviorNames.has(perform)) {
13255
+ ctx.addIssue({
13256
+ code: exports_external.ZodIssueCode.custom,
13257
+ path: ["roles", index, "performs"],
13258
+ message: `role.performs references unknown behavior: ${perform}`
13259
+ });
13260
+ }
13261
+ }
13262
+ }
13263
+ }
13264
+ if (atoms2.behaviors && atoms2.behaviors.length > 0) {
13265
+ for (const [index, behavior] of atoms2.behaviors.entries()) {
13266
+ for (const performer of behavior.performed_by ?? []) {
13267
+ if (!roleNames.has(performer)) {
13268
+ ctx.addIssue({
13269
+ code: exports_external.ZodIssueCode.custom,
13270
+ path: ["behaviors", index, "performed_by"],
13271
+ message: `behavior.performed_by references unknown role: ${performer}`
13272
+ });
13273
+ }
13274
+ }
13275
+ }
13276
+ }
13277
+ if (atoms2.rules && atoms2.rules.length > 0) {
13278
+ const allowedDependsOn = new Set([...stateNames, ...metricNames]);
13279
+ for (const [index, rule] of atoms2.rules.entries()) {
13280
+ for (const dependency of rule.depends_on ?? []) {
13281
+ if (!allowedDependsOn.has(dependency)) {
13282
+ ctx.addIssue({
13283
+ code: exports_external.ZodIssueCode.custom,
13284
+ path: ["rules", index, "depends_on"],
13285
+ message: `rule.depends_on references unknown state/metric: ${dependency}`
13286
+ });
13287
+ }
13288
+ }
13289
+ }
13290
+ }
13291
+ if (atoms2.events && atoms2.events.length > 0) {
13292
+ for (const [index, event] of atoms2.events.entries()) {
13293
+ for (const behaviorName of event.trigger_for ?? []) {
13294
+ if (!behaviorNames.has(behaviorName)) {
13295
+ ctx.addIssue({
13296
+ code: exports_external.ZodIssueCode.custom,
13297
+ path: ["events", index, "trigger_for"],
13298
+ message: `event.trigger_for references unknown behavior: ${behaviorName}`
13299
+ });
13300
+ }
13301
+ }
13032
13302
  }
13033
13303
  }
13034
13304
  });
@@ -13044,7 +13314,8 @@ var atomsWhitelistByEntityType = {
13044
13314
  "states" /* States */,
13045
13315
  "rules" /* Rules */,
13046
13316
  "transitions" /* Transitions */,
13047
- "events" /* Events */
13317
+ "events" /* Events */,
13318
+ "claims" /* Claims */
13048
13319
  ]),
13049
13320
  ["process" /* Process */]: new Set,
13050
13321
  ["sor" /* SoR */]: new Set([
@@ -13060,7 +13331,8 @@ var atomsWhitelistByEntityType = {
13060
13331
  "metrics" /* Metrics */,
13061
13332
  "roles" /* Roles */,
13062
13333
  "constraints" /* Constraints */,
13063
- "comparisons" /* Comparisons */
13334
+ "comparisons" /* Comparisons */,
13335
+ "claims" /* Claims */
13064
13336
  ]),
13065
13337
  ["contract" /* Contract */]: new Set,
13066
13338
  ["epic" /* Epic */]: new Set([
@@ -13068,7 +13340,8 @@ var atomsWhitelistByEntityType = {
13068
13340
  "metrics" /* Metrics */,
13069
13341
  "roles" /* Roles */,
13070
13342
  "constraints" /* Constraints */,
13071
- "comparisons" /* Comparisons */
13343
+ "comparisons" /* Comparisons */,
13344
+ "claims" /* Claims */
13072
13345
  ]),
13073
13346
  ["document" /* Document */]: new Set
13074
13347
  };
@@ -13093,7 +13366,8 @@ var baseEntitySchema = exports_external.object({
13093
13366
  kind: kindSchema,
13094
13367
  scope: scopeSchema,
13095
13368
  perspective: perspectiveSchema,
13096
- metadata: metadataSchema
13369
+ metadata: metadataSchema,
13370
+ source_refs: sourceRefsSchema
13097
13371
  });
13098
13372
  var productDataSchema = exports_external.object({
13099
13373
  description: exports_external.string().optional(),
@@ -13107,7 +13381,8 @@ var productEntitySchema = baseEntitySchema.extend({
13107
13381
  });
13108
13382
  var systemDataSchema = exports_external.object({
13109
13383
  description: exports_external.string().optional(),
13110
- corresponds_to: exports_external.string().optional()
13384
+ corresponds_to: exports_external.string().optional(),
13385
+ atoms: exports_external.undefined().optional()
13111
13386
  });
13112
13387
  var systemEntitySchema = baseEntitySchema.extend({
13113
13388
  type: exports_external.literal("system" /* System */),
@@ -13153,9 +13428,10 @@ var sorEntitySchema = baseEntitySchema.extend({
13153
13428
  data: sorDataSchema
13154
13429
  });
13155
13430
  var contractDataSchema = exports_external.object({
13156
- format: exports_external.enum(["openapi", "asyncapi", "proto"]),
13431
+ format: exports_external.enum(["openapi", "asyncapi", "proto", "graphql", "custom"]),
13157
13432
  spec: exports_external.string(),
13158
- component_id: exports_external.string().optional()
13433
+ version: exports_external.string().optional(),
13434
+ description: exports_external.string().optional()
13159
13435
  });
13160
13436
  var contractEntitySchema = baseEntitySchema.extend({
13161
13437
  type: exports_external.literal("contract" /* Contract */),
@@ -13163,7 +13439,7 @@ var contractEntitySchema = baseEntitySchema.extend({
13163
13439
  });
13164
13440
  var epicDataSchema = exports_external.object({
13165
13441
  description: exports_external.string().optional(),
13166
- product_refs: exports_external.array(exports_external.string()).optional(),
13442
+ product_refs: exports_external.array(entityRefPointerSchema).optional(),
13167
13443
  atoms: dataAtomsSchema.optional()
13168
13444
  });
13169
13445
  var epicEntitySchema = baseEntitySchema.extend({
@@ -13239,18 +13515,45 @@ var entitySchema = exports_external.discriminatedUnion("type", [
13239
13515
  });
13240
13516
  }
13241
13517
  }
13518
+ if (entity2.type === "sor" /* SoR */ && entity2.data.atoms) {
13519
+ const { constraints, rules } = entity2.data.atoms;
13520
+ const hasConstraints = Array.isArray(constraints) && constraints.length > 0;
13521
+ const hasRules = Array.isArray(rules) && rules.length > 0;
13522
+ if (!hasConstraints && !hasRules) {
13523
+ ctx.addIssue({
13524
+ code: exports_external.ZodIssueCode.custom,
13525
+ path: ["data", "atoms"],
13526
+ message: "SoR must have at least one constraint or rule"
13527
+ });
13528
+ }
13529
+ }
13530
+ if (entity2.type === "epic" /* Epic */ && entity2.data.atoms) {
13531
+ const { decisions } = entity2.data.atoms;
13532
+ const hasDecisions = Array.isArray(decisions) && decisions.length > 0;
13533
+ if (!hasDecisions) {
13534
+ ctx.addIssue({
13535
+ code: exports_external.ZodIssueCode.custom,
13536
+ path: ["data", "atoms"],
13537
+ message: "Epic must have at least one decision"
13538
+ });
13539
+ }
13540
+ }
13242
13541
  });
13243
13542
  // ../core/src/schemas/relationSchema.ts
13244
13543
  var relationDataSchema = exports_external.object({
13245
- description: exports_external.string().optional()
13544
+ description: exports_external.string().optional(),
13545
+ _source: exports_external.literal("field_sync").optional()
13246
13546
  });
13247
13547
  var relationSchema = exports_external.object({
13248
13548
  id: exports_external.string(),
13249
13549
  type: relationTypeSchema,
13250
13550
  from: exports_external.string(),
13251
13551
  to: exports_external.string(),
13552
+ weight: exports_external.number().optional(),
13553
+ confidence: exports_external.number().min(0).max(1).optional(),
13252
13554
  data: relationDataSchema.optional(),
13253
- metadata: metadataSchema.optional()
13555
+ metadata: metadataSchema.optional(),
13556
+ source_refs: sourceRefsSchema
13254
13557
  });
13255
13558
  // ../core/src/errors/httpStatus.ts
13256
13559
  var ERROR_CODE_HTTP_STATUS = {
@@ -13270,6 +13573,10 @@ var ERROR_CODE_HTTP_STATUS = {
13270
13573
  ["ENTITY_DUPLICATE" /* ENTITY_DUPLICATE */]: 409,
13271
13574
  ["API_UNAUTHORIZED" /* API_UNAUTHORIZED */]: 401,
13272
13575
  ["LLM_AUTH_FAILED" /* LLM_AUTH_FAILED */]: 401,
13576
+ ["AUTH_REQUIRED" /* AUTH_REQUIRED */]: 401,
13577
+ ["AUTH_INVALID_TOKEN" /* AUTH_INVALID_TOKEN */]: 401,
13578
+ ["AUTH_INVALID_API_KEY" /* AUTH_INVALID_API_KEY */]: 401,
13579
+ ["AUTH_RESERVED_NAME" /* AUTH_RESERVED_NAME */]: 400,
13273
13580
  ["API_RATE_LIMITED" /* API_RATE_LIMITED */]: 429,
13274
13581
  ["API_NOT_IMPLEMENTED" /* API_NOT_IMPLEMENTED */]: 501,
13275
13582
  ["BATCH_PARTIAL_FAILURE" /* BATCH_PARTIAL_FAILURE */]: 200,
@@ -13282,29 +13589,135 @@ var ERROR_CODE_HTTP_STATUS = {
13282
13589
  ["PURGE_FAILED" /* PURGE_FAILED */]: 500,
13283
13590
  ["EMBEDDING_NOT_AVAILABLE" /* EMBEDDING_NOT_AVAILABLE */]: 503,
13284
13591
  ["LLM_NOT_AVAILABLE" /* LLM_NOT_AVAILABLE */]: 503,
13285
- ["UNKNOWN" /* UNKNOWN */]: 500
13592
+ ["AUTH_PROVIDER_ERROR" /* AUTH_PROVIDER_ERROR */]: 502,
13593
+ ["UNKNOWN" /* UNKNOWN */]: 500,
13594
+ ["WORKSPACE_ISOLATION" /* WORKSPACE_ISOLATION */]: 400
13286
13595
  };
13287
13596
  // ../core/src/utils/yaml.ts
13288
13597
  var import_yaml = __toESM(require_dist(), 1);
13289
13598
  // ../core/src/constants.ts
13290
13599
  var DAEMON_HEARTBEAT_INTERVAL = 30000;
13600
+ var CLOUD_DAEMON_IDLE_TIMEOUT = 300000;
13601
+ // ../core/src/contentTypeRegistry.ts
13602
+ var DEFAULT_CONTENT_TYPES = [
13603
+ {
13604
+ id: "markdown",
13605
+ category: "doc",
13606
+ match: { extensions: [".md", ".txt"] },
13607
+ cas: { encoding: "utf8", hashInput: "content" },
13608
+ pipeline: { digest: ["summary", "outline"], extraction: ["entities", "relations"] },
13609
+ display: { icon: "\uD83D\uDCC4", renderer: "text" }
13610
+ },
13611
+ {
13612
+ id: "typescript",
13613
+ category: "code",
13614
+ match: { extensions: [".ts", ".tsx"] },
13615
+ cas: { encoding: "utf8", hashInput: "content" },
13616
+ pipeline: { digest: ["ast", "summary"], extraction: ["entities", "relations"] },
13617
+ display: { icon: "\uD83D\uDCDC", renderer: "code" }
13618
+ },
13619
+ {
13620
+ id: "package",
13621
+ category: "package",
13622
+ match: { filenames: ["package.json", "go.mod", "pyproject.toml", "Cargo.toml", "pom.xml"] },
13623
+ cas: { encoding: "utf8", hashInput: "identity" },
13624
+ pipeline: { digest: ["summary"], extraction: ["entities", "relations"] },
13625
+ display: { icon: "\uD83D\uDCE6", renderer: "package-card" }
13626
+ },
13627
+ {
13628
+ id: "pdf",
13629
+ category: "binary",
13630
+ match: { extensions: [".pdf"] },
13631
+ cas: { encoding: "base64", hashInput: "content" },
13632
+ pipeline: { digest: [], extraction: [] },
13633
+ display: { icon: "\uD83D\uDCD5", renderer: "binary-preview" }
13634
+ },
13635
+ {
13636
+ id: "msword",
13637
+ category: "binary",
13638
+ match: { extensions: [".doc", ".docx"] },
13639
+ cas: { encoding: "base64", hashInput: "content" },
13640
+ pipeline: { digest: [], extraction: [] },
13641
+ display: { icon: "\uD83D\uDCD8", renderer: "binary-preview" }
13642
+ },
13643
+ {
13644
+ id: "mspowerpoint",
13645
+ category: "binary",
13646
+ match: { extensions: [".ppt", ".pptx"] },
13647
+ cas: { encoding: "base64", hashInput: "content" },
13648
+ pipeline: { digest: [], extraction: [] },
13649
+ display: { icon: "\uD83D\uDCD9", renderer: "binary-preview" }
13650
+ }
13651
+ ];
13652
+ var normalizeExtension = (ext) => ext.trim().toLowerCase();
13653
+ var normalizeFilename = (name) => name.trim().toLowerCase();
13654
+
13655
+ class ContentTypeRegistry {
13656
+ definitions;
13657
+ extensionIndex;
13658
+ filenameIndex;
13659
+ constructor(definitions) {
13660
+ this.definitions = definitions;
13661
+ this.extensionIndex = new Map;
13662
+ this.filenameIndex = new Map;
13663
+ for (const def of definitions) {
13664
+ for (const ext of def.match.extensions ?? []) {
13665
+ this.extensionIndex.set(normalizeExtension(ext), def);
13666
+ }
13667
+ for (const name of def.match.filenames ?? []) {
13668
+ this.filenameIndex.set(normalizeFilename(name), def);
13669
+ }
13670
+ }
13671
+ }
13672
+ resolve(filename) {
13673
+ const baseName = filename.includes("/") ? filename.split("/").pop() ?? filename : filename;
13674
+ const normalized = normalizeFilename(baseName);
13675
+ const byName = this.filenameIndex.get(normalized);
13676
+ if (byName)
13677
+ return byName;
13678
+ const dot = normalized.lastIndexOf(".");
13679
+ if (dot < 0)
13680
+ return null;
13681
+ const ext = normalizeExtension(normalized.slice(dot));
13682
+ return this.extensionIndex.get(ext) ?? null;
13683
+ }
13684
+ getManifestFilenames() {
13685
+ const names = new Set;
13686
+ for (const def of this.definitions) {
13687
+ if (def.category !== "package")
13688
+ continue;
13689
+ for (const name of def.match.filenames ?? []) {
13690
+ names.add(normalizeFilename(name));
13691
+ }
13692
+ }
13693
+ return Array.from(names);
13694
+ }
13695
+ getDefinitions() {
13696
+ return [...this.definitions];
13697
+ }
13698
+ }
13699
+ var defaultRegistry = new ContentTypeRegistry(DEFAULT_CONTENT_TYPES);
13700
+ var DEFAULT_CONTENT_TYPE_DEFINITIONS = DEFAULT_CONTENT_TYPES;
13291
13701
  // ../core/src/fileTypes.ts
13292
- var INDEXABLE_CODE_EXTENSIONS = new Set([".ts", ".tsx"]);
13293
- var INDEXABLE_DOC_EXTENSIONS = new Set([".md"]);
13702
+ var collectExtensions = (predicate) => {
13703
+ const extensions = new Set;
13704
+ for (const definition of DEFAULT_CONTENT_TYPE_DEFINITIONS) {
13705
+ if (!predicate(definition))
13706
+ continue;
13707
+ for (const ext of definition.match.extensions ?? []) {
13708
+ extensions.add(ext.toLowerCase());
13709
+ }
13710
+ }
13711
+ return extensions;
13712
+ };
13713
+ var INDEXABLE_CODE_EXTENSIONS = collectExtensions((definition) => definition.category === "code");
13714
+ var INDEXABLE_DOC_EXTENSIONS = collectExtensions((definition) => definition.category === "doc");
13294
13715
  var INDEXABLE_EXTENSIONS = new Set([
13295
13716
  ...INDEXABLE_CODE_EXTENSIONS,
13296
13717
  ...INDEXABLE_DOC_EXTENSIONS
13297
13718
  ]);
13298
- var UPLOAD_ALLOWED_EXTENSIONS = new Set([
13299
- ".md",
13300
- ".doc",
13301
- ".docx",
13302
- ".pdf",
13303
- ".ppt",
13304
- ".pptx",
13305
- ".txt"
13306
- ]);
13307
- var TEXT_EXTENSIONS = new Set([".md", ".txt"]);
13719
+ var UPLOAD_ALLOWED_EXTENSIONS = collectExtensions(() => true);
13720
+ var TEXT_EXTENSIONS = collectExtensions((definition) => definition.cas.encoding === "utf8");
13308
13721
  var UPLOAD_MAX_FILE_SIZE = 5 * 1024 * 1024;
13309
13722
  // src/handlers/utils.ts
13310
13723
  import path2 from "node:path";
@@ -13385,18 +13798,22 @@ function resolveServerUrl(input) {
13385
13798
  }
13386
13799
  const isLocal = host.startsWith("localhost") || host.startsWith("127.0.0.1") || host.startsWith("0.0.0.0");
13387
13800
  const protocol = isLocal ? "ws" : "wss";
13388
- const base2 = host.replace(/^localhost/, "127.0.0.1").replace(/\/+$/, "");
13801
+ const base2 = host.replace(/\/+$/, "");
13389
13802
  return `${protocol}://${base2}${WS_DAEMON_PATH}`;
13390
13803
  }
13391
- var parseAllowedPaths = (input) => {
13804
+ var parseAllowedPaths = (input, extraPath) => {
13392
13805
  if (!input) {
13393
- return ["*"];
13806
+ return extraPath ? ["*", extraPath] : ["*"];
13394
13807
  }
13395
13808
  const parts = input.split(",").map((s) => s.trim()).filter(Boolean);
13396
13809
  if (parts.includes("*")) {
13397
- return ["*"];
13810
+ return extraPath ? ["*", extraPath] : ["*"];
13398
13811
  }
13399
- return normalizeAllowedPaths(parts);
13812
+ const normalized = normalizeAllowedPaths(parts);
13813
+ if (extraPath && !normalized.includes("*")) {
13814
+ normalized.push(extraPath);
13815
+ }
13816
+ return normalizeAllowedPaths(normalized);
13400
13817
  };
13401
13818
 
13402
13819
  // src/handshake.ts
@@ -13429,8 +13846,8 @@ var readPackageVersion = (packageRoot = getPackageRoot()) => {
13429
13846
  const parsed = JSON.parse(raw);
13430
13847
  return parsed.version ?? "0.0.0";
13431
13848
  };
13432
- var buildHandshakePayload = (allowedPaths) => {
13433
- const machineId = os.hostname();
13849
+ var buildHandshakePayload = (allowedPaths, machineIdOverride) => {
13850
+ const machineId = machineIdOverride?.trim() || os.hostname();
13434
13851
  return {
13435
13852
  machine_id: machineId,
13436
13853
  machine_name: machineId,
@@ -13713,12 +14130,41 @@ var createFsReadFileHandler = (allowedPaths) => async (params) => {
13713
14130
  // src/handlers/fsRepoStatus.ts
13714
14131
  var REPO_STATUS_CACHE_TTL_MS = 1e4;
13715
14132
  var repoStatusCache = new Map;
14133
+ var parseForEachRef = (raw) => {
14134
+ const entries = [];
14135
+ for (const line of raw.split(`
14136
+ `)) {
14137
+ if (!line.trim())
14138
+ continue;
14139
+ const [name, commit] = line.split(" ");
14140
+ if (name && commit)
14141
+ entries.push({ name, commit });
14142
+ }
14143
+ return entries;
14144
+ };
14145
+ var parseLogOutput = (raw) => {
14146
+ const entries = [];
14147
+ for (const line of raw.split(`
14148
+ `)) {
14149
+ if (!line.trim())
14150
+ continue;
14151
+ const spaceIdx = line.indexOf(" ");
14152
+ if (spaceIdx === -1) {
14153
+ entries.push({ hash: line.trim(), message: "" });
14154
+ } else {
14155
+ entries.push({ hash: line.slice(0, spaceIdx), message: line.slice(spaceIdx + 1) });
14156
+ }
14157
+ }
14158
+ return entries;
14159
+ };
13716
14160
  var createFsRepoStatusHandler = (allowedPaths) => async (params) => {
13717
14161
  const now = Date.now();
13718
14162
  const payload = params;
13719
14163
  const rawPath = ensureString(payload?.path, "path");
14164
+ const requestedBranch = typeof payload?.branch === "string" ? payload.branch : "";
13720
14165
  const targetPath = assertAllowedPath(rawPath, allowedPaths);
13721
- const cached = repoStatusCache.get(targetPath);
14166
+ const cacheKey = `${targetPath}:${requestedBranch}`;
14167
+ const cached = repoStatusCache.get(cacheKey);
13722
14168
  if (cached?.value && cached.expiresAt > now) {
13723
14169
  return cached.value;
13724
14170
  }
@@ -13726,26 +14172,36 @@ var createFsRepoStatusHandler = (allowedPaths) => async (params) => {
13726
14172
  return cached.inflight;
13727
14173
  }
13728
14174
  const inflight = (async () => {
13729
- const [branch, headHash, remoteResult] = await Promise.all([
14175
+ const [branch, headHash, remoteResult, branchesRaw, tagsRaw] = await Promise.all([
13730
14176
  runGit(["rev-parse", "--abbrev-ref", "HEAD"], targetPath),
13731
14177
  runGit(["rev-parse", "HEAD"], targetPath),
13732
- tryRunGit(["config", "--get", "remote.origin.url"], targetPath)
14178
+ tryRunGit(["config", "--get", "remote.origin.url"], targetPath),
14179
+ runGit(["for-each-ref", "refs/heads", "--format=%(refname:short) %(objectname)"], targetPath),
14180
+ runGit(["for-each-ref", "refs/tags", "--format=%(refname:short) %(objectname)"], targetPath)
13733
14181
  ]);
13734
14182
  const dirtyResult = await tryRunGit(["diff-index", "--quiet", "HEAD", "--"], targetPath);
14183
+ const branches = parseForEachRef(branchesRaw);
14184
+ const tags = parseForEachRef(tagsRaw);
14185
+ const logBranch = requestedBranch || branch;
14186
+ const logResult = await tryRunGit(["log", logBranch, "--format=%H %s", "-n", "30"], targetPath);
14187
+ const commits = logResult.ok ? parseLogOutput(logResult.stdout) : [];
13735
14188
  return {
13736
14189
  branch,
13737
14190
  head_hash: headHash,
13738
14191
  is_dirty: !dirtyResult.ok,
13739
- remote_url: remoteResult.ok ? remoteResult.stdout.trim() || undefined : undefined
14192
+ remote_url: remoteResult.ok ? remoteResult.stdout.trim() || undefined : undefined,
14193
+ branches,
14194
+ tags,
14195
+ commits
13740
14196
  };
13741
14197
  })();
13742
- repoStatusCache.set(targetPath, { expiresAt: now + REPO_STATUS_CACHE_TTL_MS, inflight });
14198
+ repoStatusCache.set(cacheKey, { expiresAt: now + REPO_STATUS_CACHE_TTL_MS, inflight });
13743
14199
  try {
13744
14200
  const value = await inflight;
13745
- repoStatusCache.set(targetPath, { expiresAt: Date.now() + REPO_STATUS_CACHE_TTL_MS, value });
14201
+ repoStatusCache.set(cacheKey, { expiresAt: Date.now() + REPO_STATUS_CACHE_TTL_MS, value });
13746
14202
  return value;
13747
14203
  } finally {
13748
- const entry = repoStatusCache.get(targetPath);
14204
+ const entry = repoStatusCache.get(cacheKey);
13749
14205
  if (entry?.inflight) {
13750
14206
  delete entry.inflight;
13751
14207
  }
@@ -13753,8 +14209,6 @@ var createFsRepoStatusHandler = (allowedPaths) => async (params) => {
13753
14209
  };
13754
14210
 
13755
14211
  // src/handlers/fsRepoScan.ts
13756
- import { readFile as readFile4 } from "node:fs/promises";
13757
- import path7 from "node:path";
13758
14212
  var DEFAULT_INCLUDE2 = ["manifests", "docs"];
13759
14213
  var matchesFilter2 = (filePath, include) => {
13760
14214
  if (include.includes("*"))
@@ -13816,8 +14270,7 @@ var createFsRepoScanHandler = (allowedPaths) => async (params) => {
13816
14270
  if (!fileName || !CODE_PACKAGE_FILES.has(fileName.toLowerCase()))
13817
14271
  continue;
13818
14272
  try {
13819
- const fullPath = path7.join(targetPath, file.path);
13820
- const content = await readFile4(fullPath, "utf-8");
14273
+ const content = await runGit(["show", `${hash2}:${file.path}`], targetPath);
13821
14274
  if (!isValidManifest(file.path, content))
13822
14275
  continue;
13823
14276
  manifests.push({ path: file.path, content });
@@ -13858,8 +14311,362 @@ var createFsRepoTreeHandler = (allowedPaths) => async (params) => {
13858
14311
  return { files };
13859
14312
  };
13860
14313
 
14314
+ // src/handlers/configSetAuth.ts
14315
+ import { chmod, mkdir, writeFile } from "node:fs/promises";
14316
+
14317
+ // src/handlers/vcsUtils.ts
14318
+ import { execFile as execFile2, spawn } from "node:child_process";
14319
+ import path7 from "node:path";
14320
+ var stripAuthFromUrl = (rawUrl) => {
14321
+ try {
14322
+ const parsed = new URL(rawUrl);
14323
+ if (parsed.username || parsed.password) {
14324
+ parsed.username = "";
14325
+ parsed.password = "";
14326
+ }
14327
+ return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
14328
+ } catch {
14329
+ return rawUrl;
14330
+ }
14331
+ };
14332
+ var gitConfigPath = (workDir) => path7.join(workDir, ".git-daemon.config");
14333
+ var gitCredentialsPath = (workDir) => path7.join(workDir, ".git-daemon.credentials");
14334
+ var createGitEnv = (workDir) => {
14335
+ const base2 = {
14336
+ ...process.env,
14337
+ LANG: "C",
14338
+ LC_ALL: "C",
14339
+ GIT_TERMINAL_PROMPT: "0"
14340
+ };
14341
+ if (!workDir)
14342
+ return base2;
14343
+ return { ...base2, GIT_CONFIG_GLOBAL: gitConfigPath(workDir) };
14344
+ };
14345
+ var parseGitVersion = (raw) => {
14346
+ const match = raw.match(/git version (\d+)\.(\d+)\.(\d+)/i);
14347
+ if (!match)
14348
+ return null;
14349
+ return {
14350
+ major: Number(match[1]),
14351
+ minor: Number(match[2]),
14352
+ patch: Number(match[3])
14353
+ };
14354
+ };
14355
+ var isGitVersionAtLeast = (version, target) => {
14356
+ if (version.major !== target.major)
14357
+ return version.major > target.major;
14358
+ if (version.minor !== target.minor)
14359
+ return version.minor > target.minor;
14360
+ return version.patch >= target.patch;
14361
+ };
14362
+ var getGitVersion = async (env) => new Promise((resolve) => {
14363
+ execFile2("git", ["--version"], { env }, (error, stdout) => {
14364
+ if (error) {
14365
+ console.log(`[getGitVersion] execFile error: ${error.message}`);
14366
+ return resolve(null);
14367
+ }
14368
+ const raw = stdout.trim();
14369
+ const parsed = parseGitVersion(raw);
14370
+ console.log(`[getGitVersion] raw="${raw}" parsed=${JSON.stringify(parsed)}`);
14371
+ resolve(parsed);
14372
+ });
14373
+ });
14374
+ var EXEC_GIT_MAX_BUFFER = 20 * 1024 * 1024;
14375
+ var execGit = async (args, options = {}) => new Promise((resolve, reject) => {
14376
+ execFile2("git", args, { cwd: options.cwd, env: options.env, maxBuffer: EXEC_GIT_MAX_BUFFER }, (error, stdout, stderr) => {
14377
+ if (error) {
14378
+ reject(error);
14379
+ return;
14380
+ }
14381
+ resolve({ stdout: stdout.toString(), stderr: stderr.toString() });
14382
+ });
14383
+ });
14384
+ var GIT_PROGRESS_RE = /(Enumerating|Receiving|Counting|Compressing|Resolving) (?:objects|deltas):\s+(\d+)%\s*(?:\([^)]*\))?/;
14385
+ var GIT_PHASE_WEIGHTS = {
14386
+ Enumerating: [0, 3],
14387
+ Counting: [3, 6],
14388
+ Compressing: [6, 10],
14389
+ Receiving: [10, 90],
14390
+ Resolving: [90, 100]
14391
+ };
14392
+ var weightedPercent = (phase, rawPercent) => {
14393
+ const [start, end] = GIT_PHASE_WEIGHTS[phase] ?? [0, 100];
14394
+ return Math.round(start + rawPercent / 100 * (end - start));
14395
+ };
14396
+ var runGitWithProgress = async (args, options) => new Promise((resolve, reject) => {
14397
+ console.log(`[runGitWithProgress] spawn: git ${args.join(" ")}`);
14398
+ const child = spawn("git", args, {
14399
+ cwd: options.cwd,
14400
+ env: options.env,
14401
+ stdio: ["ignore", "pipe", "pipe"]
14402
+ });
14403
+ let lastWeighted = null;
14404
+ let stderrBuf = "";
14405
+ child.stderr.on("data", (chunk) => {
14406
+ const text = chunk.toString();
14407
+ stderrBuf += text;
14408
+ const lines = stderrBuf.split(/[\r\n]+/);
14409
+ stderrBuf = lines.pop() ?? "";
14410
+ for (const line of lines) {
14411
+ const trimmed = line.trim();
14412
+ if (!trimmed)
14413
+ continue;
14414
+ options.onStderr?.(trimmed);
14415
+ const match = trimmed.match(GIT_PROGRESS_RE);
14416
+ if (match) {
14417
+ const phase = match[1];
14418
+ const raw = Number(match[2]);
14419
+ if (!Number.isNaN(raw)) {
14420
+ const weighted = weightedPercent(phase, raw);
14421
+ if (weighted !== lastWeighted) {
14422
+ lastWeighted = weighted;
14423
+ options.onProgress?.({ percent: weighted, label: trimmed });
14424
+ }
14425
+ }
14426
+ }
14427
+ }
14428
+ });
14429
+ child.on("error", (error) => {
14430
+ reject(error);
14431
+ });
14432
+ child.on("close", (code) => {
14433
+ if (stderrBuf.trim()) {
14434
+ options.onStderr?.(stderrBuf.trim());
14435
+ }
14436
+ if (code === 0) {
14437
+ console.log("[runGitWithProgress] finished successfully");
14438
+ resolve();
14439
+ } else {
14440
+ reject(new Error(`git ${args.join(" ")} failed with code ${code}`));
14441
+ }
14442
+ });
14443
+ });
14444
+
14445
+ // src/handlers/configSetAuth.ts
14446
+ var ensureWorkDir = (workDir) => {
14447
+ if (!workDir) {
14448
+ throw new RpcError(JSON_RPC_ERROR_CODES.INVALID_PARAMS, "Work dir not configured");
14449
+ }
14450
+ return workDir;
14451
+ };
14452
+ var formatCredentialLines = (hosts) => hosts.map((host) => {
14453
+ const authUser = host.auth_user ?? "oauth2";
14454
+ return `https://${authUser}:${host.token}@${host.host}`;
14455
+ });
14456
+ var createConfigSetAuthHandler = (workDir) => async (params, _context) => {
14457
+ const payload = params;
14458
+ const hosts = Array.isArray(payload?.hosts) ? payload.hosts : null;
14459
+ if (!hosts) {
14460
+ throw new RpcError(JSON_RPC_ERROR_CODES.INVALID_PARAMS, "Invalid hosts");
14461
+ }
14462
+ for (const entry of hosts) {
14463
+ ensureString(entry?.host, "host");
14464
+ ensureString(entry?.auth_user, "auth_user");
14465
+ ensureString(entry?.token, "token");
14466
+ }
14467
+ const rootDir = ensureWorkDir(workDir);
14468
+ await mkdir(rootDir, { recursive: true });
14469
+ const configPath = gitConfigPath(rootDir);
14470
+ const credentialsPath = gitCredentialsPath(rootDir);
14471
+ const configContent = `[credential]
14472
+ helper = store --file ${credentialsPath}
14473
+ `;
14474
+ await writeFile(configPath, configContent, "utf-8");
14475
+ const lines = formatCredentialLines(hosts);
14476
+ await writeFile(credentialsPath, `${lines.join(`
14477
+ `)}
14478
+ `, "utf-8");
14479
+ await chmod(credentialsPath, 384);
14480
+ return { ok: true };
14481
+ };
14482
+
14483
+ // src/handlers/vcsClone.ts
14484
+ import { mkdir as mkdir2, rename, rm } from "node:fs/promises";
14485
+ import path8 from "node:path";
14486
+ var MIN_GIT_VERSION = { major: 2, minor: 5, patch: 0 };
14487
+ var ensureWorkDir2 = (workDir) => {
14488
+ if (!workDir) {
14489
+ throw new RpcError(JSON_RPC_ERROR_CODES.INVALID_PARAMS, "Work dir not configured");
14490
+ }
14491
+ return workDir;
14492
+ };
14493
+ var extractRepoNameFromUrl = (url) => {
14494
+ try {
14495
+ const parsed = new URL(url);
14496
+ const name = parsed.pathname.split("/").filter(Boolean).pop() ?? "repo";
14497
+ return name.replace(/\.git$/i, "") || "repo";
14498
+ } catch {
14499
+ return "repo";
14500
+ }
14501
+ };
14502
+ var getRepoDir = (workDir, repoName) => path8.join(workDir, "repos", repoName);
14503
+ var notifyProgress = (notify, percent, detail) => {
14504
+ if (!notify)
14505
+ return;
14506
+ const payload = {
14507
+ stage: "cloning",
14508
+ label: "cloning",
14509
+ percent,
14510
+ ...detail ? { detail } : {}
14511
+ };
14512
+ notify("task/progress", payload);
14513
+ };
14514
+ var getRemoteUrl = async (repoDir, env) => {
14515
+ try {
14516
+ const result = await execGit(["-C", repoDir, "config", "--get", "remote.origin.url"], { env });
14517
+ const url = result.stdout.trim();
14518
+ return url.length > 0 ? url : null;
14519
+ } catch {
14520
+ return null;
14521
+ }
14522
+ };
14523
+ var getHeadCommit = async (repoDir, env) => {
14524
+ const result = await execGit(["-C", repoDir, "rev-parse", "HEAD"], { env });
14525
+ return result.stdout.trim();
14526
+ };
14527
+ var createVcsCloneHandler = (workDir) => async (params, context) => {
14528
+ const payload = params;
14529
+ const url = ensureString(payload?.url, "url");
14530
+ const ref = payload?.ref;
14531
+ const commit = payload?.commit;
14532
+ if (ref !== undefined) {
14533
+ ensureString(ref, "ref");
14534
+ }
14535
+ if (commit !== undefined) {
14536
+ ensureString(commit, "commit");
14537
+ }
14538
+ const rootDir = ensureWorkDir2(workDir);
14539
+ const repoName = payload?.repo_name || extractRepoNameFromUrl(url);
14540
+ const repoDir = getRepoDir(rootDir, repoName);
14541
+ const env = createGitEnv(rootDir);
14542
+ if (commit) {
14543
+ const version = await getGitVersion(env);
14544
+ console.log(`[vcs/clone] git version check: parsed=${JSON.stringify(version)}, env.PATH=${env?.PATH ?? process.env.PATH}`);
14545
+ if (!version || !isGitVersionAtLeast(version, MIN_GIT_VERSION)) {
14546
+ const current = version ? `${version.major}.${version.minor}.${version.patch}` : "unknown";
14547
+ throw new RpcError(JSON_RPC_ERROR_CODES.INVALID_PARAMS, `Commit hash checkout requires Git 2.5+, current version: ${current}. Please use branch/tag selection instead.`);
14548
+ }
14549
+ }
14550
+ await mkdir2(rootDir, { recursive: true });
14551
+ const legacyRepoDir = path8.join(rootDir, "repo");
14552
+ const hasNewDir = await execGit(["-C", repoDir, "rev-parse", "--git-dir"], { env }).then(() => true).catch(() => false);
14553
+ if (!hasNewDir) {
14554
+ const hasLegacy = await execGit(["-C", legacyRepoDir, "rev-parse", "--git-dir"], { env }).then(() => true).catch(() => false);
14555
+ if (hasLegacy) {
14556
+ const legacyRemote = await getRemoteUrl(legacyRepoDir, env);
14557
+ if (legacyRemote && stripAuthFromUrl(legacyRemote) === stripAuthFromUrl(url)) {
14558
+ await mkdir2(path8.dirname(repoDir), { recursive: true });
14559
+ await rename(legacyRepoDir, repoDir);
14560
+ }
14561
+ }
14562
+ }
14563
+ const hasGitDir = await execGit(["-C", repoDir, "rev-parse", "--git-dir"], { env }).then(() => true).catch(() => false);
14564
+ if (hasGitDir) {
14565
+ const remoteUrl = await getRemoteUrl(repoDir, env);
14566
+ if (remoteUrl && stripAuthFromUrl(remoteUrl) === stripAuthFromUrl(url)) {
14567
+ if (commit) {
14568
+ await runGitWithProgress(["-C", repoDir, "fetch", "--depth=1", "--progress", "origin", commit], {
14569
+ env,
14570
+ onProgress: ({ percent, label }) => notifyProgress(context?.notify, percent, label),
14571
+ onStderr: (text) => console.log(`[vcs/clone] git: ${text}`)
14572
+ });
14573
+ await execGit(["-C", repoDir, "checkout", commit], { env });
14574
+ } else {
14575
+ const refToUse = ref ?? "HEAD";
14576
+ await runGitWithProgress(["-C", repoDir, "fetch", "--depth=1", "--progress", "origin", refToUse], {
14577
+ env,
14578
+ onProgress: ({ percent, label }) => notifyProgress(context?.notify, percent, label),
14579
+ onStderr: (text) => console.log(`[vcs/clone] git: ${text}`)
14580
+ });
14581
+ await execGit(["-C", repoDir, "checkout", "FETCH_HEAD"], { env });
14582
+ }
14583
+ } else {
14584
+ await rm(repoDir, { recursive: true, force: true });
14585
+ }
14586
+ }
14587
+ const repoExists = await execGit(["-C", repoDir, "rev-parse", "--git-dir"], { env }).then(() => true).catch(() => false);
14588
+ if (!repoExists) {
14589
+ if (commit) {
14590
+ await mkdir2(repoDir, { recursive: true });
14591
+ await execGit(["-C", repoDir, "init"], { env });
14592
+ await execGit(["-C", repoDir, "remote", "add", "origin", url], { env });
14593
+ await runGitWithProgress(["-C", repoDir, "fetch", "--depth=1", "--progress", "origin", commit], {
14594
+ env,
14595
+ onProgress: ({ percent, label }) => notifyProgress(context?.notify, percent, label),
14596
+ onStderr: (text) => console.log(`[vcs/clone] git: ${text}`)
14597
+ });
14598
+ await execGit(["-C", repoDir, "checkout", commit], { env });
14599
+ } else if (ref) {
14600
+ await runGitWithProgress(["clone", "--depth=1", "--branch", ref, "--progress", url, repoDir], {
14601
+ env,
14602
+ onProgress: ({ percent, label }) => notifyProgress(context?.notify, percent, label),
14603
+ onStderr: (text) => console.log(`[vcs/clone] git: ${text}`)
14604
+ });
14605
+ } else {
14606
+ await runGitWithProgress(["clone", "--depth=1", "--progress", url, repoDir], {
14607
+ env,
14608
+ onProgress: ({ percent, label }) => notifyProgress(context?.notify, percent, label),
14609
+ onStderr: (text) => console.log(`[vcs/clone] git: ${text}`)
14610
+ });
14611
+ }
14612
+ }
14613
+ const commitHash = await getHeadCommit(repoDir, env);
14614
+ return { path: repoDir, commit_hash: commitHash };
14615
+ };
14616
+
14617
+ // src/handlers/vcsRefs.ts
14618
+ var parseLsRemoteOutput = (raw) => {
14619
+ const entries = [];
14620
+ const lines = raw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
14621
+ for (const line of lines) {
14622
+ if (line.startsWith("ref: "))
14623
+ continue;
14624
+ const [commit, ref] = line.split(/\s+/);
14625
+ if (!commit || !ref)
14626
+ continue;
14627
+ if (ref.endsWith("^{}"))
14628
+ continue;
14629
+ entries.push({ name: ref, commit });
14630
+ }
14631
+ return entries;
14632
+ };
14633
+ var extractDefaultBranch = (raw) => {
14634
+ const line = raw.split(/\r?\n/).find((item) => item.startsWith("ref: "));
14635
+ if (!line)
14636
+ return null;
14637
+ const match = line.match(/^ref: refs\/heads\/(.+?)\s+HEAD/);
14638
+ return match?.[1] ?? null;
14639
+ };
14640
+ var splitRefs = (entries) => {
14641
+ const branches = [];
14642
+ const tags = [];
14643
+ for (const entry of entries) {
14644
+ if (entry.name.startsWith("refs/heads/")) {
14645
+ branches.push({ name: entry.name.replace("refs/heads/", ""), commit: entry.commit });
14646
+ } else if (entry.name.startsWith("refs/tags/")) {
14647
+ tags.push({ name: entry.name.replace("refs/tags/", ""), commit: entry.commit });
14648
+ }
14649
+ }
14650
+ return { branches, tags };
14651
+ };
14652
+ var createVcsRefsHandler = (workDir) => async (params, _context) => {
14653
+ const payload = params;
14654
+ const url = ensureString(payload?.url, "url");
14655
+ const env = createGitEnv(workDir);
14656
+ try {
14657
+ const out = await execGit(["ls-remote", "--symref", url, "HEAD", "refs/heads/*", "refs/tags/*"], { env });
14658
+ const defaultBranch = extractDefaultBranch(out.stdout) ?? "HEAD";
14659
+ const parsed = parseLsRemoteOutput(out.stdout);
14660
+ const { branches, tags } = splitRefs(parsed);
14661
+ return { branches, tags, default: defaultBranch };
14662
+ } catch (error) {
14663
+ const message = error instanceof Error ? error.message : "Failed to list refs";
14664
+ throw new RpcError(JSON_RPC_ERROR_CODES.INTERNAL_ERROR, message);
14665
+ }
14666
+ };
14667
+
13861
14668
  // src/handlers/index.ts
13862
- var createFsHandlers = (allowedPaths) => ({
14669
+ var createDaemonHandlers = (allowedPaths, workDir) => ({
13863
14670
  "fs/listTree": createFsListTreeHandler(allowedPaths),
13864
14671
  "fs/dirScan": createFsDirScanHandler(allowedPaths),
13865
14672
  "fs/exists": createFsExistsHandler(allowedPaths),
@@ -13869,7 +14676,10 @@ var createFsHandlers = (allowedPaths) => ({
13869
14676
  "fs/repoStatus": createFsRepoStatusHandler(allowedPaths),
13870
14677
  "fs/commitExists": createFsCommitExistsHandler(allowedPaths),
13871
14678
  "fs/repoTree": createFsRepoTreeHandler(allowedPaths),
13872
- "fs/repoScan": createFsRepoScanHandler(allowedPaths)
14679
+ "fs/repoScan": createFsRepoScanHandler(allowedPaths),
14680
+ "config/setAuth": createConfigSetAuthHandler(workDir),
14681
+ "vcs/clone": createVcsCloneHandler(workDir),
14682
+ "vcs/refs": createVcsRefsHandler(workDir)
13873
14683
  });
13874
14684
 
13875
14685
  // src/rpcHandler.ts
@@ -13889,8 +14699,10 @@ var buildError = (code, message, data) => ({
13889
14699
 
13890
14700
  class RpcHandler {
13891
14701
  handlers;
13892
- constructor(handlers) {
14702
+ context;
14703
+ constructor(handlers, context = {}) {
13893
14704
  this.handlers = new Map(Object.entries(handlers));
14705
+ this.context = context;
13894
14706
  }
13895
14707
  async handleMessage(raw) {
13896
14708
  let payload;
@@ -13929,7 +14741,7 @@ class RpcHandler {
13929
14741
  };
13930
14742
  }
13931
14743
  try {
13932
- const result = await handler(request.params);
14744
+ const result = await handler(request.params, this.context);
13933
14745
  if (request.id === undefined) {
13934
14746
  return null;
13935
14747
  }
@@ -13962,6 +14774,7 @@ class WebSocketClient {
13962
14774
  onError;
13963
14775
  reconnectMinDelayMs;
13964
14776
  reconnectMaxDelayMs;
14777
+ maxReconnectAttempts;
13965
14778
  socket = null;
13966
14779
  shouldReconnect = true;
13967
14780
  reconnectAttempt = 0;
@@ -13975,6 +14788,7 @@ class WebSocketClient {
13975
14788
  this.onError = options.onError;
13976
14789
  this.reconnectMinDelayMs = options.reconnectMinDelayMs ?? 1000;
13977
14790
  this.reconnectMaxDelayMs = options.reconnectMaxDelayMs ?? 30000;
14791
+ this.maxReconnectAttempts = options.maxReconnectAttempts ?? 64;
13978
14792
  }
13979
14793
  connect() {
13980
14794
  this.shouldReconnect = true;
@@ -14086,6 +14900,11 @@ class WebSocketClient {
14086
14900
  this.socket.send(JSON.stringify(response));
14087
14901
  }
14088
14902
  scheduleReconnect() {
14903
+ if (this.maxReconnectAttempts > 0 && this.reconnectAttempt >= this.maxReconnectAttempts) {
14904
+ console.error(`[WebSocketClient] Max reconnect attempts (${this.maxReconnectAttempts}) reached, giving up`);
14905
+ this.shouldReconnect = false;
14906
+ return;
14907
+ }
14089
14908
  const delay = Math.min(this.reconnectMaxDelayMs, this.reconnectMinDelayMs * 2 ** this.reconnectAttempt);
14090
14909
  this.reconnectAttempt += 1;
14091
14910
  setTimeout(() => {
@@ -14105,7 +14924,7 @@ class WebSocketClient {
14105
14924
 
14106
14925
  // src/index.ts
14107
14926
  import { readFileSync as readFileSync2 } from "node:fs";
14108
- import { join, dirname } from "node:path";
14927
+ import { join, dirname, resolve } from "node:path";
14109
14928
  import { fileURLToPath as fileURLToPath2 } from "node:url";
14110
14929
  function readVersion() {
14111
14930
  try {
@@ -14121,13 +14940,24 @@ function readVersion() {
14121
14940
  return "unknown";
14122
14941
  }
14123
14942
  var program2 = new Command;
14124
- program2.name("c4a-daemon").description("C4A daemon for local filesystem access").version(readVersion(), "-V, --version").option("--server <host>", "Server host (e.g. localhost:5100, example.com/prefix)", DEFAULT_SERVER_HOST).option("--allow <paths>", "Comma-separated allowed paths (default: all directories)").parse(process.argv);
14943
+ program2.name("c4a-daemon").description("C4A daemon for local filesystem access").version(readVersion(), "-V, --version").option("--server <host>", "Server host (e.g. localhost:5100, example.com/prefix)", DEFAULT_SERVER_HOST).option("--allow <paths>", "Comma-separated allowed paths (default: all directories)").option("--machine-id <id>", "Override daemon machine id (default: hostname)").option("--work-dir <dir>", "Working directory for daemon operations").parse(process.argv);
14125
14944
  var options = program2.opts();
14126
14945
  var serverUrl = resolveServerUrl(options.server);
14127
- var allowedPaths = parseAllowedPaths(options.allow);
14946
+ var resolvedWorkDir = options.workDir ? resolve(options.workDir) : undefined;
14947
+ var allowedPaths = parseAllowedPaths(options.allow, resolvedWorkDir);
14128
14948
  console.log(`Server: ${serverUrl}`);
14129
14949
  console.log(`Allowed: ${allowedPaths.join(", ")}`);
14130
- var rpcHandler = new RpcHandler(createFsHandlers(allowedPaths));
14950
+ if (resolvedWorkDir) {
14951
+ console.log(`WorkDir: ${resolvedWorkDir}`);
14952
+ }
14953
+ var client;
14954
+ var rpcHandler = new RpcHandler(createDaemonHandlers(allowedPaths, resolvedWorkDir), {
14955
+ notify: (method, params) => {
14956
+ try {
14957
+ client.sendNotification(method, params);
14958
+ } catch {}
14959
+ }
14960
+ });
14131
14961
  var heartbeatTimer = null;
14132
14962
  var stopHeartbeat = () => {
14133
14963
  if (heartbeatTimer) {
@@ -14135,18 +14965,18 @@ var stopHeartbeat = () => {
14135
14965
  heartbeatTimer = null;
14136
14966
  }
14137
14967
  };
14138
- var startHeartbeat = (client, machineId) => {
14968
+ var startHeartbeat = (client2, machineId) => {
14139
14969
  stopHeartbeat();
14140
14970
  heartbeatTimer = setInterval(() => {
14141
- client.sendNotification("daemon/heartbeat", { machine_id: machineId, timestamp: Date.now() });
14971
+ client2.sendNotification("daemon/heartbeat", { machine_id: machineId, timestamp: Date.now() });
14142
14972
  }, DAEMON_HEARTBEAT_INTERVAL);
14143
14973
  };
14144
- var client = new WebSocketClient({
14974
+ client = new WebSocketClient({
14145
14975
  url: serverUrl,
14146
14976
  onRequest: (request) => rpcHandler.handleRequest(request),
14147
14977
  onOpen: async () => {
14148
14978
  try {
14149
- const handshakePayload = buildHandshakePayload(allowedPaths);
14979
+ const handshakePayload = buildHandshakePayload(allowedPaths, options.machineId);
14150
14980
  const response = await client.sendRpcRequest("daemon/handshake", handshakePayload);
14151
14981
  if ("error" in response) {
14152
14982
  console.error(`Handshake error: ${response.error.message}`);