@loucompanion/forge-bridge 0.1.1-dev.7d43998c4521 → 0.1.1-dev.895607f4402a

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 (40) hide show
  1. package/README.md +1 -0
  2. package/dist/bridge/bridge.service.js +84 -12
  3. package/dist/bridge/bridge.types.d.ts +16 -0
  4. package/dist/cli/cli.service.d.ts +27 -2
  5. package/dist/cli/cli.service.js +406 -16
  6. package/dist/cli/local-config.d.ts +4 -1
  7. package/dist/cli/local-config.js +60 -8
  8. package/dist/session/index.d.ts +2 -0
  9. package/dist/session/index.js +1 -0
  10. package/dist/session/internals.d.ts +5 -3
  11. package/dist/session/internals.js +2 -1
  12. package/dist/session/phase-completion.d.ts +111 -0
  13. package/dist/session/phase-completion.js +2350 -0
  14. package/dist/session/provider-cli/index.d.ts +2 -2
  15. package/dist/session/provider-cli/index.js +1 -1
  16. package/dist/session/provider-cli/provider-cli.base.d.ts +2 -2
  17. package/dist/session/provider-cli/provider-cli.service.d.ts +48 -3
  18. package/dist/session/provider-cli/provider-cli.service.js +1807 -48
  19. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  20. package/dist/session/provider-cli/provider-usage.d.ts +25 -0
  21. package/dist/session/provider-cli/provider-usage.js +64 -0
  22. package/dist/session/qa-sidecar-validation.d.ts +3 -0
  23. package/dist/session/qa-sidecar-validation.js +44 -0
  24. package/dist/session/session.service.js +57 -12
  25. package/dist/session/session.types.d.ts +66 -0
  26. package/dist/session/session.types.js +165 -2
  27. package/dist/shared/cursor-agent/cursor-agent.launch.d.ts +9 -0
  28. package/dist/shared/cursor-agent/cursor-agent.launch.js +66 -0
  29. package/dist/version.d.ts +1 -1
  30. package/dist/version.js +1 -1
  31. package/dist/worktree/artifact-injector.d.ts +12 -0
  32. package/dist/worktree/artifact-injector.js +133 -0
  33. package/dist/worktree/dependency-warmer.d.ts +32 -0
  34. package/dist/worktree/dependency-warmer.js +297 -0
  35. package/dist/worktree/index.d.ts +2 -0
  36. package/dist/worktree/index.js +1 -0
  37. package/dist/worktree/worktree.service.d.ts +4 -0
  38. package/dist/worktree/worktree.service.js +175 -11
  39. package/dist/worktree/worktree.types.d.ts +7 -1
  40. package/package.json +8 -3
@@ -3,10 +3,12 @@ import type { WorktreeHandle } from "../../worktree/worktree.types.js";
3
3
  export interface ProviderCliRunContext {
4
4
  readonly dispatch: RunOnceDispatchPacket;
5
5
  readonly worktree: WorktreeHandle;
6
+ readonly signal?: AbortSignal;
6
7
  emit(event: RunnerDispatchEvent): Promise<void>;
7
8
  }
8
9
  export interface ProviderCliRunResult {
9
10
  readonly summary: string;
10
11
  readonly spec?: RunnerDispatchSpec | null;
11
12
  readonly artifact?: RunnerDispatchArtifact | null;
13
+ readonly artifacts?: readonly RunnerDispatchArtifact[] | null;
12
14
  }
@@ -0,0 +1,25 @@
1
+ import type { RunOnceDispatchPacket, RunnerDispatchEvent } from "../session.types.js";
2
+ export type UsageSource = "provider_reported" | "cli_reported" | "estimated" | "unknown";
3
+ /**
4
+ * Normalized, provider-agnostic token usage accumulated for a dispatch. Cost is never computed
5
+ * here; the API recomputes cost from these tokens x model rates (ADR-0006).
6
+ */
7
+ export interface ProviderUsage {
8
+ readonly inputTokens: number;
9
+ readonly outputTokens: number;
10
+ readonly cacheReadTokens: number;
11
+ readonly cacheCreationTokens: number;
12
+ readonly reasoningOutputTokens: number;
13
+ readonly providerDurationMs: number | null;
14
+ readonly source: UsageSource;
15
+ }
16
+ export declare function emptyUsage(source?: UsageSource): ProviderUsage;
17
+ export declare function addUsage(base: ProviderUsage, next: Partial<ProviderUsage>): ProviderUsage;
18
+ export declare function totalTokens(usage: ProviderUsage): number;
19
+ export declare function hasUsage(usage: ProviderUsage | null): usage is ProviderUsage;
20
+ /**
21
+ * Builds the durable `provider_usage` event. Token numbers travel as a structured `data` JSON
22
+ * string (snake_case) that the API parses into a usage_event row.
23
+ */
24
+ export declare function buildProviderUsageEvent(dispatch: RunOnceDispatchPacket, usage: ProviderUsage): RunnerDispatchEvent;
25
+ export declare function readUsageNumber(source: Record<string, unknown>, key: string): number;
@@ -0,0 +1,64 @@
1
+ export function emptyUsage(source = "unknown") {
2
+ return {
3
+ inputTokens: 0,
4
+ outputTokens: 0,
5
+ cacheReadTokens: 0,
6
+ cacheCreationTokens: 0,
7
+ reasoningOutputTokens: 0,
8
+ providerDurationMs: null,
9
+ source
10
+ };
11
+ }
12
+ export function addUsage(base, next) {
13
+ return {
14
+ inputTokens: base.inputTokens + nonNegative(next.inputTokens),
15
+ outputTokens: base.outputTokens + nonNegative(next.outputTokens),
16
+ cacheReadTokens: base.cacheReadTokens + nonNegative(next.cacheReadTokens),
17
+ cacheCreationTokens: base.cacheCreationTokens + nonNegative(next.cacheCreationTokens),
18
+ reasoningOutputTokens: base.reasoningOutputTokens + nonNegative(next.reasoningOutputTokens),
19
+ providerDurationMs: next.providerDurationMs ?? base.providerDurationMs,
20
+ source: next.source ?? base.source
21
+ };
22
+ }
23
+ export function totalTokens(usage) {
24
+ return usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.cacheCreationTokens;
25
+ }
26
+ export function hasUsage(usage) {
27
+ return usage !== null && totalTokens(usage) > 0;
28
+ }
29
+ /**
30
+ * Builds the durable `provider_usage` event. Token numbers travel as a structured `data` JSON
31
+ * string (snake_case) that the API parses into a usage_event row.
32
+ */
33
+ export function buildProviderUsageEvent(dispatch, usage) {
34
+ const data = {
35
+ provider: dispatch.execution.provider,
36
+ model: dispatch.execution.model,
37
+ lane: dispatch.execution.lane,
38
+ phase: dispatch.cycleRun.phase,
39
+ attempt: dispatch.cycleRun.attempt,
40
+ input_tokens: usage.inputTokens,
41
+ output_tokens: usage.outputTokens,
42
+ cache_read_tokens: usage.cacheReadTokens,
43
+ cache_creation_tokens: usage.cacheCreationTokens,
44
+ reasoning_output_tokens: usage.reasoningOutputTokens,
45
+ metered: dispatch.execution.authKind === "api_key",
46
+ usage_source: usage.source,
47
+ provider_duration_ms: usage.providerDurationMs
48
+ };
49
+ const total = totalTokens(usage);
50
+ return {
51
+ role: "runner",
52
+ kind: "checkpoint",
53
+ content: `Provider usage: ${total} tokens (${usage.inputTokens} in / ${usage.outputTokens} out) for ${dispatch.execution.model}.`,
54
+ eventType: "provider_usage",
55
+ data: JSON.stringify(data)
56
+ };
57
+ }
58
+ export function readUsageNumber(source, key) {
59
+ const value = source[key];
60
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
61
+ }
62
+ function nonNegative(value) {
63
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
64
+ }
@@ -0,0 +1,3 @@
1
+ export declare function isPathUnderRoot(root: string, target: string): boolean;
2
+ export declare function ensureNoSymbolicLinkPathSegments(root: string, targetDirectory: string, errorMessage: string): Promise<void>;
3
+ export declare function sha256File(filePath: string): Promise<string>;
@@ -0,0 +1,44 @@
1
+ import crypto from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ export function isPathUnderRoot(root, target) {
6
+ const relative = path.relative(path.resolve(root), path.resolve(target));
7
+ return Boolean(relative)
8
+ && relative !== ".."
9
+ && !relative.startsWith(`..${path.sep}`)
10
+ && !path.isAbsolute(relative);
11
+ }
12
+ export async function ensureNoSymbolicLinkPathSegments(root, targetDirectory, errorMessage) {
13
+ const resolvedRoot = path.resolve(root);
14
+ const resolvedTargetDirectory = path.resolve(targetDirectory);
15
+ const relative = path.relative(resolvedRoot, resolvedTargetDirectory);
16
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
17
+ throw new Error(errorMessage);
18
+ }
19
+ let current = resolvedRoot;
20
+ const rootStat = await fs.lstat(current);
21
+ if (rootStat.isSymbolicLink()) {
22
+ throw new Error(errorMessage);
23
+ }
24
+ if (!relative) {
25
+ return;
26
+ }
27
+ for (const segment of relative.split(path.sep)) {
28
+ if (!segment) {
29
+ continue;
30
+ }
31
+ current = path.join(current, segment);
32
+ const stat = await fs.lstat(current);
33
+ if (stat.isSymbolicLink()) {
34
+ throw new Error(errorMessage);
35
+ }
36
+ }
37
+ }
38
+ export async function sha256File(filePath) {
39
+ const hash = crypto.createHash("sha256");
40
+ for await (const chunk of createReadStream(filePath)) {
41
+ hash.update(chunk);
42
+ }
43
+ return hash.digest("hex");
44
+ }
@@ -1,10 +1,10 @@
1
1
  import { redactSecrets } from "../shared/redaction/redaction.js";
2
- import { DeterministicProviderCliService } from "./provider-cli/provider-cli.service.js";
2
+ import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.js";
3
3
  import { GitWorktreeService } from "../worktree/worktree.service.js";
4
4
  export class BridgeSessionService {
5
5
  worktrees;
6
6
  providerCli;
7
- constructor(worktrees = new GitWorktreeService(), providerCli = new DeterministicProviderCliService()) {
7
+ constructor(worktrees = new GitWorktreeService(), providerCli = new RoutingProviderCliService()) {
8
8
  this.worktrees = worktrees;
9
9
  this.providerCli = providerCli;
10
10
  }
@@ -13,7 +13,9 @@ export class BridgeSessionService {
13
13
  const redactionSecrets = exactSecrets(dispatch);
14
14
  const events = [];
15
15
  const emit = async (event) => {
16
- throwIfAborted(signal);
16
+ if (signal?.aborted) {
17
+ return;
18
+ }
17
19
  const redacted = redactSecrets(event, redactionSecrets);
18
20
  events.push(redacted);
19
21
  await sink.emit(redacted);
@@ -29,8 +31,12 @@ export class BridgeSessionService {
29
31
  repo: dispatch.repo,
30
32
  workItem: dispatch.workItem,
31
33
  baseBranch: dispatch.cycleRun.baseBranch || dispatch.cycleRun.requestedBase,
34
+ lane: dispatch.execution.lane,
35
+ phase: dispatch.cycleRun.phase,
32
36
  allowedRepoRoot: dispatch.serverLocal.repoRoot,
33
- cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees
37
+ cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
38
+ artifacts: dispatch.artifacts,
39
+ warmPathOverrides: dispatch.warmPathOverrides
34
40
  });
35
41
  throwIfAborted(signal);
36
42
  await emit({
@@ -39,23 +45,36 @@ export class BridgeSessionService {
39
45
  content: `Prepared worktree ${worktree.branchName}.`,
40
46
  eventType: "worktree_prepared"
41
47
  });
48
+ if (worktree.dependencyWarm) {
49
+ await emitDependencyWarmEvents(worktree.dependencyWarm, emit);
50
+ }
42
51
  try {
43
52
  throwIfAborted(signal);
44
- const isQa = dispatch.execution.role.toLowerCase() === "qa" || dispatch.execution.lane.toLowerCase() === "qa";
53
+ const lane = dispatch.execution.lane.toLowerCase();
54
+ const role = dispatch.execution.role.toLowerCase();
55
+ const isQa = role === "qa" || lane === "qa";
56
+ const isConflictResolve = role === "conflict_resolve" || lane === "conflict_resolve";
57
+ const context = {
58
+ dispatch,
59
+ worktree,
60
+ emit,
61
+ signal
62
+ };
45
63
  const run = isQa
46
- ? await this.providerCli.runQa(dispatch, emit)
47
- : await this.providerCli.runImplementation({
48
- dispatch,
49
- worktree,
50
- emit
51
- });
64
+ ? await this.providerCli.runQa(context)
65
+ : isConflictResolve
66
+ ? await this.providerCli.runConflictResolve(context)
67
+ : await this.providerCli.runImplementation(context);
68
+ throwIfAborted(signal);
69
+ const phaseArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
52
70
  return redactSecrets({
53
71
  schemaVersion: 1,
54
72
  exitCode: 0,
55
73
  summary: run.summary,
56
74
  events,
57
75
  spec: run.spec ?? null,
58
- artifact: run.artifact ?? null
76
+ artifact: run.artifact ?? null,
77
+ artifacts: phaseArtifacts
59
78
  }, redactionSecrets);
60
79
  }
61
80
  finally {
@@ -90,3 +109,29 @@ function validateApiKeySecretGrant(dispatch) {
90
109
  function exactSecrets(dispatch) {
91
110
  return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
92
111
  }
112
+ async function emitDependencyWarmEvents(warm, emit) {
113
+ if (warm.linked.length > 0) {
114
+ await emit({
115
+ role: "runner",
116
+ kind: "checkpoint",
117
+ content: `Warmed dependencies via link: ${warm.linked.join(", ")}.`,
118
+ eventType: "dependencies_warmed"
119
+ });
120
+ }
121
+ for (const fallback of warm.fallbacks) {
122
+ await emit({
123
+ role: "runner",
124
+ kind: "checkpoint",
125
+ content: `Dependency install fallback (${fallback.ecosystem}): ${fallback.reason} Ran \`${fallback.command}\` in ${fallback.packageRoot}.`,
126
+ eventType: "dependencies_install_fallback"
127
+ });
128
+ }
129
+ if (warm.skipped.length > 0) {
130
+ await emit({
131
+ role: "runner",
132
+ kind: "checkpoint",
133
+ content: `Skipped warming missing dependency paths: ${warm.skipped.join(", ")}.`,
134
+ eventType: "dependencies_warm_skipped"
135
+ });
136
+ }
137
+ }
@@ -8,7 +8,60 @@ export interface RunOnceDispatchPacket {
8
8
  readonly lease: DispatchLease;
9
9
  readonly execution: DispatchExecution;
10
10
  readonly serverLocal: DispatchServerLocalConfig;
11
+ readonly pullRequest?: DispatchPullRequestContext | null;
11
12
  readonly apiKeySecretGrant?: ApiKeySecretGrant | null;
13
+ readonly artifacts: readonly DispatchResolvedArtifact[];
14
+ readonly warmPathOverrides?: readonly string[];
15
+ readonly qaBrowser?: DispatchQaBrowserContext | null;
16
+ readonly qaRework?: DispatchQaReworkContext | null;
17
+ }
18
+ export interface DispatchQaBrowserContext {
19
+ readonly required: boolean;
20
+ readonly launchTarget?: DispatchQaAppLaunchTarget | null;
21
+ readonly artifactsPath: string;
22
+ readonly missingTargetReason?: string | null;
23
+ }
24
+ export interface DispatchQaAppLaunchTarget {
25
+ readonly url?: string | null;
26
+ readonly command?: string | null;
27
+ readonly working_directory?: string | null;
28
+ readonly ready_url?: string | null;
29
+ readonly routes: readonly string[];
30
+ readonly notes?: string | null;
31
+ }
32
+ export interface DispatchQaReworkContext {
33
+ readonly attempt: number;
34
+ readonly maxAttempts: number;
35
+ readonly packetPath: string;
36
+ readonly packetJson: string;
37
+ readonly findingIds: readonly string[];
38
+ readonly findings: readonly Record<string, unknown>[];
39
+ }
40
+ export interface DispatchPullRequestContext {
41
+ readonly number: number;
42
+ readonly provider: string;
43
+ readonly title: string;
44
+ readonly sourceBranch: string;
45
+ readonly targetBranch: string;
46
+ readonly url: string;
47
+ readonly state: string;
48
+ readonly checkState: string;
49
+ readonly mergeState: string;
50
+ readonly requiredChecksPassed: number;
51
+ readonly requiredChecksTotal: number;
52
+ readonly unresolvedThreads: number;
53
+ readonly humanApproved: boolean;
54
+ readonly hasMergeConflicts: boolean;
55
+ }
56
+ export interface DispatchResolvedArtifact {
57
+ readonly kind: string;
58
+ readonly slug: string;
59
+ readonly scope: string;
60
+ readonly body: string;
61
+ readonly contentHash: string;
62
+ readonly version: number;
63
+ readonly lane?: string | null;
64
+ readonly event?: string | null;
12
65
  }
13
66
  export interface DispatchWorkItem {
14
67
  readonly id: string;
@@ -29,6 +82,9 @@ export interface DispatchRepo {
29
82
  }
30
83
  export interface DispatchCycleRun {
31
84
  readonly id: string;
85
+ readonly ownerType?: string | null;
86
+ readonly ownerId?: string | null;
87
+ readonly workItemId?: string | null;
32
88
  readonly kind: string;
33
89
  readonly phase: string;
34
90
  readonly requestedBase: string;
@@ -44,6 +100,9 @@ export interface DispatchSession {
44
100
  }
45
101
  export interface DispatchLease {
46
102
  readonly id: string;
103
+ readonly ownerType?: string | null;
104
+ readonly ownerId?: string | null;
105
+ readonly workItemId?: string | null;
47
106
  readonly worktreeKey: string;
48
107
  readonly lane: string;
49
108
  readonly fencingToken: string;
@@ -59,6 +118,7 @@ export interface DispatchExecution {
59
118
  readonly role: string;
60
119
  readonly lane: string;
61
120
  readonly requiresApiKeySecretGrant: boolean;
121
+ readonly runnerRepoLocalPath?: string | null;
62
122
  }
63
123
  export interface ApiKeySecretGrant {
64
124
  readonly grantId: string;
@@ -75,6 +135,10 @@ export interface RunnerDispatchEvent {
75
135
  readonly kind: string;
76
136
  readonly content: string;
77
137
  readonly eventType: string;
138
+ /** Provider/runner-reported event time (ISO-8601) when available, preserved for accurate durations. */
139
+ readonly occurredAt?: string | null;
140
+ /** Optional structured telemetry payload (JSON string), e.g. token usage for provider_usage events. */
141
+ readonly data?: string | null;
78
142
  }
79
143
  export interface RunnerDispatchSpec {
80
144
  readonly repoPath: string;
@@ -90,6 +154,7 @@ export interface RunnerDispatchArtifact {
90
154
  readonly report: string;
91
155
  readonly producedBy: string;
92
156
  readonly status: string;
157
+ readonly phase?: string | null;
93
158
  }
94
159
  export interface RunOnceResultPacket {
95
160
  readonly schemaVersion: 1;
@@ -98,6 +163,7 @@ export interface RunOnceResultPacket {
98
163
  readonly events: readonly RunnerDispatchEvent[];
99
164
  readonly spec?: RunnerDispatchSpec | null;
100
165
  readonly artifact?: RunnerDispatchArtifact | null;
166
+ readonly artifacts?: readonly RunnerDispatchArtifact[] | null;
101
167
  }
102
168
  export interface RunnerEventLine {
103
169
  readonly type: "runner_event";
@@ -1,3 +1,4 @@
1
+ import path from "node:path";
1
2
  export function parseRunOnceDispatchPacket(value) {
2
3
  const packet = asObject(value, "dispatch packet");
3
4
  const schemaVersion = requiredNumber(packet, "schemaVersion");
@@ -14,7 +15,12 @@ export function parseRunOnceDispatchPacket(value) {
14
15
  lease: parseLease(packet.lease),
15
16
  execution: parseExecution(packet.execution),
16
17
  serverLocal: parseServerLocal(packet.serverLocal),
17
- apiKeySecretGrant: parseApiKeySecretGrant(packet.apiKeySecretGrant)
18
+ pullRequest: parsePullRequest(packet.pullRequest),
19
+ apiKeySecretGrant: parseApiKeySecretGrant(packet.apiKeySecretGrant),
20
+ artifacts: parseArtifacts(packet.artifacts),
21
+ warmPathOverrides: parseWarmPathOverrides(packet.warmPathOverrides),
22
+ qaBrowser: parseQaBrowser(packet.qaBrowser),
23
+ qaRework: parseQaRework(packet.qaRework)
18
24
  };
19
25
  }
20
26
  export function failureResult(summary, events = []) {
@@ -52,6 +58,9 @@ function parseCycleRun(value) {
52
58
  const cycle = asObject(value, "cycleRun");
53
59
  return {
54
60
  id: requiredString(cycle, "id"),
61
+ ownerType: optionalString(cycle, "ownerType"),
62
+ ownerId: optionalString(cycle, "ownerId"),
63
+ workItemId: optionalString(cycle, "workItemId"),
55
64
  kind: requiredString(cycle, "kind"),
56
65
  phase: requiredString(cycle, "phase"),
57
66
  requestedBase: optionalString(cycle, "requestedBase") ?? "develop",
@@ -73,6 +82,9 @@ function parseLease(value) {
73
82
  const lease = asObject(value, "lease");
74
83
  return {
75
84
  id: requiredString(lease, "id"),
85
+ ownerType: optionalString(lease, "ownerType"),
86
+ ownerId: optionalString(lease, "ownerId"),
87
+ workItemId: optionalString(lease, "workItemId"),
76
88
  worktreeKey: requiredString(lease, "worktreeKey"),
77
89
  lane: requiredString(lease, "lane"),
78
90
  fencingToken: requiredString(lease, "fencingToken"),
@@ -90,7 +102,8 @@ function parseExecution(value) {
90
102
  repoId: requiredString(execution, "repoId"),
91
103
  role: requiredString(execution, "role"),
92
104
  lane: requiredString(execution, "lane"),
93
- requiresApiKeySecretGrant: requiredBoolean(execution, "requiresApiKeySecretGrant")
105
+ requiresApiKeySecretGrant: requiredBoolean(execution, "requiresApiKeySecretGrant"),
106
+ runnerRepoLocalPath: optionalString(execution, "runnerRepoLocalPath")
94
107
  };
95
108
  }
96
109
  function parseApiKeySecretGrant(value) {
@@ -112,6 +125,136 @@ function parseServerLocal(value) {
112
125
  cleanupWorktrees: requiredBoolean(serverLocal, "cleanupWorktrees")
113
126
  };
114
127
  }
128
+ function parsePullRequest(value) {
129
+ if (value === undefined || value === null) {
130
+ return null;
131
+ }
132
+ const pullRequest = asObject(value, "pullRequest");
133
+ return {
134
+ number: requiredNumber(pullRequest, "number"),
135
+ provider: requiredString(pullRequest, "provider"),
136
+ title: optionalString(pullRequest, "title") ?? "",
137
+ sourceBranch: requiredString(pullRequest, "sourceBranch"),
138
+ targetBranch: requiredString(pullRequest, "targetBranch"),
139
+ url: optionalString(pullRequest, "url") ?? "",
140
+ state: requiredString(pullRequest, "state"),
141
+ checkState: requiredString(pullRequest, "checkState"),
142
+ mergeState: requiredString(pullRequest, "mergeState"),
143
+ requiredChecksPassed: requiredNumber(pullRequest, "requiredChecksPassed"),
144
+ requiredChecksTotal: requiredNumber(pullRequest, "requiredChecksTotal"),
145
+ unresolvedThreads: requiredNumber(pullRequest, "unresolvedThreads"),
146
+ humanApproved: requiredBoolean(pullRequest, "humanApproved"),
147
+ hasMergeConflicts: requiredBoolean(pullRequest, "hasMergeConflicts")
148
+ };
149
+ }
150
+ function parseWarmPathOverrides(value) {
151
+ if (value === undefined || value === null) {
152
+ return [];
153
+ }
154
+ if (!Array.isArray(value)) {
155
+ throw new Error("warmPathOverrides must be an array when provided.");
156
+ }
157
+ return value.map((entry, index) => parseWarmPathOverride(entry, index));
158
+ }
159
+ function parseWarmPathOverride(entry, index) {
160
+ if (typeof entry !== "string" || entry.trim().length === 0) {
161
+ throw new Error(`warmPathOverrides[${index}] must be a non-empty string.`);
162
+ }
163
+ const trimmed = entry.trim();
164
+ if (path.isAbsolute(trimmed) || path.posix.isAbsolute(trimmed) || path.win32.isAbsolute(trimmed)) {
165
+ throw new Error(`warmPathOverrides[${index}] must be a relative path.`);
166
+ }
167
+ const segments = trimmed.split(/[\\/]+/).filter(Boolean);
168
+ if (segments.length === 0 || segments.some((segment) => segment === "." || segment === "..")) {
169
+ throw new Error(`warmPathOverrides[${index}] must not contain path traversal.`);
170
+ }
171
+ return segments.join("/");
172
+ }
173
+ function parseQaBrowser(value) {
174
+ if (value === undefined || value === null) {
175
+ return null;
176
+ }
177
+ const qaBrowser = asObject(value, "qaBrowser");
178
+ return {
179
+ required: optionalBoolean(qaBrowser, "required") ?? false,
180
+ launchTarget: parseQaAppLaunchTarget(qaBrowser.launchTarget ?? qaBrowser.launch_target),
181
+ artifactsPath: optionalString(qaBrowser, "artifactsPath") ?? optionalString(qaBrowser, "artifacts_path") ?? "",
182
+ missingTargetReason: optionalString(qaBrowser, "missingTargetReason") ?? optionalString(qaBrowser, "missing_target_reason")
183
+ };
184
+ }
185
+ function parseQaAppLaunchTarget(value) {
186
+ if (value === undefined || value === null) {
187
+ return null;
188
+ }
189
+ const launchTarget = asObject(value, "qaBrowser.launchTarget");
190
+ const routes = launchTarget.routes;
191
+ if (routes !== undefined && routes !== null && !Array.isArray(routes)) {
192
+ throw new Error("qaBrowser.launchTarget.routes must be an array when provided.");
193
+ }
194
+ return {
195
+ url: optionalString(launchTarget, "url"),
196
+ command: optionalString(launchTarget, "command"),
197
+ working_directory: optionalString(launchTarget, "working_directory"),
198
+ ready_url: optionalString(launchTarget, "ready_url"),
199
+ routes: Array.isArray(routes)
200
+ ? routes.map((entry, index) => {
201
+ if (typeof entry !== "string") {
202
+ throw new Error(`qaBrowser.launchTarget.routes[${index}] must be a string.`);
203
+ }
204
+ return entry;
205
+ }).filter((entry) => entry.trim().length > 0)
206
+ : [],
207
+ notes: optionalString(launchTarget, "notes")
208
+ };
209
+ }
210
+ function parseQaRework(value) {
211
+ if (value === undefined || value === null) {
212
+ return null;
213
+ }
214
+ const qaRework = asObject(value, "qaRework");
215
+ const findingIdsValue = qaRework.findingIds;
216
+ if (!Array.isArray(findingIdsValue)) {
217
+ throw new Error("qaRework.findingIds must be an array.");
218
+ }
219
+ const findingsValue = qaRework.findings;
220
+ if (!Array.isArray(findingsValue)) {
221
+ throw new Error("qaRework.findings must be an array.");
222
+ }
223
+ return {
224
+ attempt: requiredNumber(qaRework, "attempt"),
225
+ maxAttempts: requiredNumber(qaRework, "maxAttempts"),
226
+ packetPath: requiredString(qaRework, "packetPath"),
227
+ packetJson: requiredString(qaRework, "packetJson"),
228
+ findingIds: findingIdsValue.map((entry, index) => {
229
+ if (typeof entry !== "string" || entry.trim().length === 0) {
230
+ throw new Error(`qaRework.findingIds[${index}] must be a non-empty string.`);
231
+ }
232
+ return entry;
233
+ }),
234
+ findings: findingsValue.map((entry, index) => asObject(entry, `qaRework.findings[${index}]`))
235
+ };
236
+ }
237
+ function parseArtifacts(value) {
238
+ if (value === undefined || value === null) {
239
+ return [];
240
+ }
241
+ if (!Array.isArray(value)) {
242
+ throw new Error("artifacts must be an array when provided.");
243
+ }
244
+ return value.map((entry, index) => {
245
+ const artifact = asObject(entry, `artifacts[${index}]`);
246
+ return {
247
+ kind: requiredString(artifact, "kind"),
248
+ slug: requiredString(artifact, "slug"),
249
+ scope: requiredString(artifact, "scope"),
250
+ body: optionalString(artifact, "body") ?? "",
251
+ contentHash: requiredString(artifact, "contentHash"),
252
+ version: optionalPositiveInteger(artifact, "version") ?? 1,
253
+ lane: optionalString(artifact, "lane"),
254
+ event: optionalString(artifact, "event")
255
+ };
256
+ });
257
+ }
115
258
  function asObject(value, label) {
116
259
  if (!value || typeof value !== "object" || Array.isArray(value)) {
117
260
  throw new Error(`${label} must be an object.`);
@@ -142,6 +285,26 @@ function requiredBoolean(source, key) {
142
285
  }
143
286
  return value;
144
287
  }
288
+ function optionalBoolean(source, key) {
289
+ const value = source[key];
290
+ if (value === undefined || value === null) {
291
+ return null;
292
+ }
293
+ if (typeof value !== "boolean") {
294
+ throw new Error(`${key} must be a boolean when provided.`);
295
+ }
296
+ return value;
297
+ }
298
+ function optionalPositiveInteger(source, key) {
299
+ const value = source[key];
300
+ if (value === undefined || value === null) {
301
+ return null;
302
+ }
303
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
304
+ throw new Error(`${key} must be a positive integer when provided.`);
305
+ }
306
+ return value;
307
+ }
145
308
  function requiredNumber(source, key) {
146
309
  const value = source[key];
147
310
  if (typeof value !== "number" || !Number.isFinite(value)) {
@@ -0,0 +1,9 @@
1
+ export interface CursorAgentLaunch {
2
+ readonly command: string;
3
+ readonly args: readonly string[];
4
+ }
5
+ export declare function isCursorAgentCommand(command: string): boolean;
6
+ export declare function resolveCursorAgentDirectLaunch(command: string, args: readonly string[]): Promise<CursorAgentLaunch | null>;
7
+ export declare function findLatestCursorAgentVersionDir(versionsRoot: string): Promise<string | null>;
8
+ export declare function compareCursorAgentVersionDirNames(left: string, right: string): number;
9
+ export declare function parseCursorAgentVersionSortKey(name: string): number;
@@ -0,0 +1,66 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ const cursorAgentVersionDirPattern = /^\d{4}\.\d{1,2}\.\d{1,2}-.+/;
4
+ export function isCursorAgentCommand(command) {
5
+ const normalized = command.trim().toLowerCase();
6
+ return normalized === "cursor-agent" || normalized === "agent";
7
+ }
8
+ export async function resolveCursorAgentDirectLaunch(command, args) {
9
+ if (!isCursorAgentCommand(command)) {
10
+ return null;
11
+ }
12
+ const localAppData = process.env.LOCALAPPDATA;
13
+ if (!localAppData) {
14
+ return null;
15
+ }
16
+ const versionDir = await findLatestCursorAgentVersionDir(path.join(localAppData, "cursor-agent", "versions"));
17
+ if (!versionDir) {
18
+ return null;
19
+ }
20
+ const nodePath = path.join(versionDir, "node.exe");
21
+ const indexPath = path.join(versionDir, "index.js");
22
+ if (!(await fileExists(nodePath)) || !(await fileExists(indexPath))) {
23
+ return null;
24
+ }
25
+ return {
26
+ command: nodePath,
27
+ args: [indexPath, ...args]
28
+ };
29
+ }
30
+ export async function findLatestCursorAgentVersionDir(versionsRoot) {
31
+ let entries;
32
+ try {
33
+ entries = await fs.readdir(versionsRoot);
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ const latestName = entries
39
+ .filter((name) => cursorAgentVersionDirPattern.test(name))
40
+ .sort(compareCursorAgentVersionDirNames)
41
+ .at(-1);
42
+ return latestName ? path.join(versionsRoot, latestName) : null;
43
+ }
44
+ export function compareCursorAgentVersionDirNames(left, right) {
45
+ const leftKey = parseCursorAgentVersionSortKey(left);
46
+ const rightKey = parseCursorAgentVersionSortKey(right);
47
+ if (leftKey !== rightKey) {
48
+ return leftKey - rightKey;
49
+ }
50
+ return left.localeCompare(right);
51
+ }
52
+ export function parseCursorAgentVersionSortKey(name) {
53
+ const datePart = name.split("-")[0] ?? "";
54
+ const parts = datePart.split(".");
55
+ if (parts.length !== 3) {
56
+ return 0;
57
+ }
58
+ const year = parts[0] ?? "";
59
+ const month = (parts[1] ?? "").padStart(2, "0");
60
+ const day = (parts[2] ?? "").padStart(2, "0");
61
+ const numeric = Number(`${year}${month}${day}`);
62
+ return Number.isFinite(numeric) ? numeric : 0;
63
+ }
64
+ async function fileExists(inputPath) {
65
+ return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
66
+ }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.1-dev.7d43998c4521";
1
+ export declare const forgeBridgeVersion = "0.1.1-dev.895607f4402a";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.1-dev.7d43998c4521";
1
+ export const forgeBridgeVersion = "0.1.1-dev.895607f4402a";