File size: 11,442 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import { randomUUID } from "node:crypto";
import {
  CloudAgentBase,
  type AgentCredentials,
  type CreateTaskParams,
  type GetStatusResult,
} from "../baseAgent.ts";
import { buildJulesApiUrl, JULES_API_BASE_URL } from "../julesApi.ts";
import type {
  CloudAgentTask,
  CloudAgentActivity,
  CloudAgentStatus,
  CloudAgentResult,
} from "../types.ts";
import { CLOUD_AGENT_STATUS } from "../types.ts";

function julesHeaders(apiKey: string, json = false): Record<string, string> {
  const headers: Record<string, string> = {
    "X-Goog-Api-Key": apiKey,
  };
  if (json) {
    headers["Content-Type"] = "application/json";
  }
  return headers;
}

function parseGithubOwnerRepo(repoUrl: string, repoName: string): { owner: string; repo: string } {
  const normalized = repoUrl.includes("://") ? repoUrl : `https://${repoUrl}`;
  try {
    const url = new URL(normalized);
    const parts = url.pathname.split("/").filter(Boolean);
    if (parts.length >= 2) {
      return {
        owner: parts[0],
        repo: parts[1].replace(/\.git$/i, ""),
      };
    }
  } catch {
    // fall through to string split for non-URL inputs
  }
  const parts = repoUrl.split("/").filter(Boolean);
  const owner = parts.length >= 2 ? parts[parts.length - 2] : "";
  const repo = parts.length >= 2 ? parts[parts.length - 1].replace(/\.git$/i, "") : repoName.trim();
  return { owner, repo: repo || repoName.trim() };
}

function buildJulesSourceResourceName(owner: string, repo: string): string {
  return `sources/github/${owner}/${repo}`;
}

function normalizeJulesSessionId(externalId: string): string {
  const trimmed = externalId.trim();
  return trimmed.startsWith("sessions/") ? trimmed.slice("sessions/".length) : trimmed;
}

function mapJulesActivity(act: Record<string, unknown>): CloudAgentActivity {
  const progress = act.progressUpdated as Record<string, unknown> | undefined;
  const planGenerated = act.planGenerated as Record<string, unknown> | undefined;
  let type: CloudAgentActivity["type"] = "command";
  let content = "";

  if (act.planGenerated) {
    type = "plan";
    const plan = planGenerated?.plan as Record<string, unknown> | undefined;
    const steps = Array.isArray(plan?.steps) ? plan.steps : [];
    content = steps
      .map((step) => {
        const row = step as Record<string, unknown>;
        return typeof row.title === "string" ? row.title : "";
      })
      .filter(Boolean)
      .join("\n");
  } else if (act.sessionCompleted) {
    type = "completion";
    content = "Session completed";
  } else if (act.planApproved) {
    type = "message";
    content = "Plan approved";
  } else if (progress) {
    content = [progress.title, progress.description].filter(Boolean).join(": ");
  }

  return {
    id: (act.id as string) || randomUUID(),
    type,
    content,
    timestamp: (act.createTime as string) || new Date().toISOString(),
  };
}

function extractJulesResult(outputs: unknown): CloudAgentResult | undefined {
  if (!Array.isArray(outputs)) return undefined;

  for (const item of outputs) {
    const output = item as Record<string, unknown>;
    const pullRequest = output.pullRequest as Record<string, unknown> | undefined;
    if (pullRequest?.url) {
      return {
        prUrl: String(pullRequest.url),
        commitMessage:
          typeof pullRequest.description === "string" ? pullRequest.description : undefined,
        summary: typeof pullRequest.title === "string" ? pullRequest.title : undefined,
      };
    }
  }

  return undefined;
}

function readJulesErrorMessage(data: Record<string, unknown>): string {
  if (typeof data.error === "string" && data.error.trim()) {
    return data.error.trim();
  }
  if (data.error && typeof data.error === "object") {
    const record = data.error as Record<string, unknown>;
    const message = record.message;
    if (typeof message === "string" && message.trim()) {
      return message.trim();
    }
  }
  return "";
}

function inferJulesStatus(
  data: Record<string, unknown>,
  activities: Record<string, unknown>[]
): CloudAgentStatus {
  if (extractJulesResult(data.outputs)) {
    return CLOUD_AGENT_STATUS.COMPLETED;
  }
  if (activities.some((act) => act.sessionCompleted)) {
    return CLOUD_AGENT_STATUS.COMPLETED;
  }
  if (activities.some((act) => act.planGenerated) && !activities.some((act) => act.planApproved)) {
    return CLOUD_AGENT_STATUS.AWAITING_APPROVAL;
  }

  if (readJulesErrorMessage(data)) {
    return CLOUD_AGENT_STATUS.FAILED;
  }

  const state = typeof data.state === "string" ? data.state.toLowerCase() : "";
  if (state.includes("failed") || state.includes("error")) {
    return CLOUD_AGENT_STATUS.FAILED;
  }
  if (state.includes("cancelled") || state.includes("canceled")) {
    return CLOUD_AGENT_STATUS.CANCELLED;
  }
  if (state.includes("completed") || state.includes("done")) {
    return CLOUD_AGENT_STATUS.COMPLETED;
  }
  if (state.includes("pending") || state.includes("queued")) {
    return CLOUD_AGENT_STATUS.QUEUED;
  }
  if (state.includes("running") || state.includes("active")) {
    return CLOUD_AGENT_STATUS.RUNNING;
  }

  if (activities.some((act) => act.progressUpdated)) {
    return CLOUD_AGENT_STATUS.RUNNING;
  }

  return CLOUD_AGENT_STATUS.QUEUED;
}

function readJulesSourceBranch(source: Record<string, unknown>): string | undefined {
  const githubRepo = source.githubRepo as Record<string, unknown> | undefined;
  const githubRepoContext = source.githubRepoContext as Record<string, unknown> | undefined;

  const candidates = [
    githubRepoContext?.startingBranch,
    githubRepoContext?.defaultBranch,
    githubRepo?.defaultBranch,
    source.defaultBranch,
  ];

  for (const candidate of candidates) {
    if (typeof candidate === "string" && candidate.trim()) {
      return candidate.trim();
    }
  }

  return undefined;
}

export class JulesAgent extends CloudAgentBase {
  readonly providerId = "jules";
  readonly baseUrl = JULES_API_BASE_URL;

  async createTask(
    params: CreateTaskParams,
    credentials: AgentCredentials
  ): Promise<CloudAgentTask> {
    const taskId = this.generateTaskId();
    const { owner, repo } = parseGithubOwnerRepo(params.source.repoUrl, params.source.repoName);
    const sourceResource = buildJulesSourceResourceName(owner, repo);

    const body: Record<string, unknown> = {
      prompt: params.prompt,
      title: params.source.repoName || repo,
      sourceContext: {
        source: sourceResource,
        githubRepoContext: {
          startingBranch: params.source.branch || "main",
        },
      },
    };

    if (params.options.autoCreatePr) {
      body.automationMode = "AUTO_CREATE_PR";
    }
    if (params.options.planApprovalRequired) {
      body.requirePlanApproval = true;
    }

    const response = await fetch(buildJulesApiUrl("/sessions"), {
      method: "POST",
      headers: julesHeaders(credentials.apiKey, true),
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`Jules create task failed: ${response.status} ${error}`);
    }

    const data = (await response.json()) as Record<string, unknown>;
    const sessionId =
      (typeof data.id === "string" && data.id) ||
      (typeof data.name === "string" ? normalizeJulesSessionId(data.name) : "") ||
      taskId;

    return {
      id: taskId,
      providerId: this.providerId,
      externalId: sessionId,
      status: CLOUD_AGENT_STATUS.QUEUED,
      prompt: params.prompt,
      source: params.source,
      options: params.options,
      activities: [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
  }

  async getStatus(externalId: string, credentials: AgentCredentials): Promise<GetStatusResult> {
    const sessionId = normalizeJulesSessionId(externalId);

    const [sessionRes, activitiesRes] = await Promise.all([
      fetch(buildJulesApiUrl(`/sessions/${sessionId}`), {
        headers: julesHeaders(credentials.apiKey),
      }),
      fetch(buildJulesApiUrl(`/sessions/${sessionId}/activities?pageSize=30`), {
        headers: julesHeaders(credentials.apiKey),
      }),
    ]);

    if (!sessionRes.ok) {
      const error = await sessionRes.text();
      throw new Error(`Jules get status failed: ${sessionRes.status} ${error}`);
    }

    const data = (await sessionRes.json()) as Record<string, unknown>;
    let rawActivities: Record<string, unknown>[] = [];
    if (activitiesRes.ok) {
      const activitiesPayload = (await activitiesRes.json()) as Record<string, unknown>;
      rawActivities = Array.isArray(activitiesPayload.activities)
        ? (activitiesPayload.activities as Record<string, unknown>[])
        : [];
    }

    const activities = rawActivities.map(mapJulesActivity);
    const status = inferJulesStatus(data, rawActivities);
    const result = extractJulesResult(data.outputs);
    const errorMessage = readJulesErrorMessage(data);

    return {
      status,
      externalId: sessionId,
      result,
      activities,
      error: errorMessage || undefined,
    };
  }

  async approvePlan(externalId: string, credentials: AgentCredentials): Promise<void> {
    const sessionId = normalizeJulesSessionId(externalId);
    const response = await fetch(buildJulesApiUrl(`/sessions/${sessionId}:approvePlan`), {
      method: "POST",
      headers: julesHeaders(credentials.apiKey, true),
      body: "{}",
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`Jules approve plan failed: ${response.status} ${error}`);
    }
  }

  async sendMessage(
    externalId: string,
    message: string,
    credentials: AgentCredentials
  ): Promise<CloudAgentActivity> {
    const sessionId = normalizeJulesSessionId(externalId);
    const response = await fetch(buildJulesApiUrl(`/sessions/${sessionId}:sendMessage`), {
      method: "POST",
      headers: julesHeaders(credentials.apiKey, true),
      body: JSON.stringify({ prompt: message }),
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`Jules send message failed: ${response.status} ${error}`);
    }

    return {
      id: this.generateActivityId(),
      type: "message",
      content: message,
      timestamp: new Date().toISOString(),
    };
  }

  async listSources(
    credentials: AgentCredentials
  ): Promise<{ name: string; url: string; branch?: string }[]> {
    const response = await fetch(buildJulesApiUrl("/sources"), {
      headers: julesHeaders(credentials.apiKey),
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`Jules list sources failed: ${response.status} ${error}`);
    }

    const data = (await response.json()) as Record<string, unknown>;
    return (Array.isArray(data.sources) ? data.sources : []).map(
      (source: Record<string, unknown>) => {
        const githubRepo = source.githubRepo as Record<string, unknown> | undefined;
        const owner = typeof githubRepo?.owner === "string" ? githubRepo.owner : "";
        const repo = typeof githubRepo?.repo === "string" ? githubRepo.repo : "";
        const branch = readJulesSourceBranch(source);

        return {
          name: typeof source.name === "string" ? source.name : `${owner}/${repo}`,
          url: owner && repo ? `https://github.com/${owner}/${repo}` : "",
          ...(branch ? { branch } : {}),
        };
      }
    );
  }
}