-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
490 lines (464 loc) · 18.3 KB
/
Copy pathplugin.js
File metadata and controls
490 lines (464 loc) · 18.3 KB
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { tool } from "@opencode-ai/plugin";
import { config as dotenvConfig } from "dotenv";
const __dirname = dirname(fileURLToPath(import.meta.url));
const JULES_BASE = "https://jules.googleapis.com/v1alpha";
function getKey() {
return process.env.JULES_API_KEY || process.env.jules_api || "";
}
function getDefaultSource() {
return process.env.JULES_SOURCE || "";
}
async function julesRequest(method, path, body) {
const key = getKey();
if (!key) {
return {
error: {
status: 0,
body: "JULES_API_KEY is not set. Add it to your .env file or export it in your shell.",
},
};
}
const url = `${JULES_BASE}${path}`;
const headers = {
"Content-Type": "application/json",
"X-Goog-Api-Key": key,
};
const init = { method, headers };
if (body) init.body = JSON.stringify(body);
try {
const res = await fetch(url, init);
if (!res.ok) {
const text = await res.text();
return { error: { status: res.status, body: text } };
}
return res.json().catch(() => ({ status: "empty" }));
} catch (err) {
return {
error: {
status: 0,
body: `Network error: ${err.message}`,
},
};
}
}
export default async ({ directory }) => {
dotenvConfig({ path: join(directory, ".env") });
return {
config: (cfg) => {
const skillsPath = join(__dirname, "skills");
if (!cfg.skills) cfg.skills = {};
if (!cfg.skills.paths) cfg.skills.paths = [];
if (!cfg.skills.paths.includes(skillsPath)) {
cfg.skills.paths.push(skillsPath);
}
},
"shell.env": async (_input, output) => {
if (process.env.JULES_API_KEY) {
output.env.JULES_API_KEY = process.env.JULES_API_KEY;
}
if (process.env.JULES_SOURCE) {
output.env.JULES_SOURCE = process.env.JULES_SOURCE;
}
},
tool: {
jules_create: tool({
description:
"Delegates work to Jules (Google's AI coding agent) as a background task. " +
"Jules will work asynchronously on a GitHub repo. Use this for PR reviews, " +
"feature implementation, bug fixes, or any coding task you want done in the " +
"background. Returns a session ID you can poll with jules_status.",
args: {
prompt: tool.schema
.string()
.describe(
"Detailed instructions for Jules. Be specific about what to " +
"check, review, implement, or fix. Include file paths, acceptance " +
"criteria, and any technical constraints."
),
source: tool.schema
.string()
.optional()
.describe(
'GitHub source name (e.g. "sources/github/owner/repo"). ' +
"Defaults to the JULES_SOURCE env var if set. Run jules_list_sources " +
"to see available sources."
),
branch: tool.schema
.string()
.optional()
.describe(
"Base branch to work from (e.g. 'main' or 'master'). " +
"Omit to use the repo's default branch."
),
title: tool.schema
.string()
.optional()
.describe("Short descriptive title for the session."),
automationMode: tool.schema
.enum(["AUTO_CREATE_PR"])
.optional()
.describe(
"Set to AUTO_CREATE_PR to have Jules automatically create a pull request. " +
"Omit for no automation."
),
requirePlanApproval: tool.schema
.boolean()
.optional()
.describe(
"If true, Jules will ask for plan approval before starting work."
),
},
async execute(args, context) {
const { prompt, source, branch, title, automationMode, requirePlanApproval } = args;
const src = source || getDefaultSource();
if (!src) {
return "Error: No source provided. Pass 'source' or set JULES_SOURCE env var. " +
"Use jules_list_sources to see available sources.";
}
const body = {
prompt,
sourceContext: {
source: src,
githubRepoContext: {},
},
};
if (branch) body.sourceContext.githubRepoContext.startingBranch = branch;
if (title) body.title = title;
if (automationMode) body.automationMode = automationMode;
if (requirePlanApproval) body.requirePlanApproval = true;
const result = await julesRequest("POST", "/sessions", body);
if (result.error) {
return `Jules API error (${result.error.status}): ${result.error.body}`;
}
const id = result.id || result.name?.split("/").pop() || "?";
return JSON.stringify({
sessionId: id,
title: result.title || "(no title)",
prompt: (result.prompt || "").slice(0, 100) + "...",
status: "created",
poll: `Call jules_status({ sessionId: "${id}" }) to check progress.`,
}, null, 2);
},
}),
jules_status: tool({
description:
"Checks progress of a background Jules session. Returns current state, " +
"activity timeline (messages, plan steps, progress, failures), " +
"artifacts summary (code patches, bash output), PR URL, and completion status.",
args: {
sessionId: tool.schema
.string()
.describe("The Jules session ID returned by jules_create."),
pageToken: tool.schema
.string()
.optional()
.describe("Page token for paginating activities (from a previous jules_status response)."),
},
async execute(args) {
const { sessionId, pageToken } = args;
const actsQs = new URLSearchParams();
actsQs.set("pageSize", "20");
if (pageToken) actsQs.set("pageToken", pageToken);
const [session, activities] = await Promise.all([
julesRequest("GET", `/sessions/${sessionId}`),
julesRequest("GET", `/sessions/${sessionId}/activities?${actsQs.toString()}`),
]);
if (session.error) {
return `Jules API error (${session.error.status}): ${session.error.body}`;
}
const timeline = [];
if (activities.error) {
timeline.push(`[WARNING] Could not fetch activities: ${activities.error.body}`);
}
let prUrl = null;
let prTitle = null;
let prDescription = null;
let completed = false;
let failed = false;
let failedReason = null;
if (session.outputs) {
for (const out of session.outputs) {
if (out.pullRequest) {
prUrl = out.pullRequest.url;
prTitle = out.pullRequest.title;
prDescription = out.pullRequest.description;
}
}
}
if (activities.activities) {
for (const act of activities.activities) {
const ts = act.createTime ? act.createTime.slice(11, 19) : "";
if (act.planGenerated) {
timeline.push(`[PLAN] ${ts} ${act.description || "Plan generated"}`);
for (const step of act.planGenerated.plan.steps || []) {
timeline.push(` Step ${step.index || "?"}: ${step.title}`);
}
}
if (act.planApproved) {
timeline.push(`[PLAN_APPROVED] ${ts} Plan ${act.planApproved.planId} approved`);
}
if (act.progressUpdated) {
const title = act.progressUpdated.title || act.progressUpdated.description || act.description || "";
if (title) timeline.push(`[WORKING] ${ts} ${title}`);
}
if (act.agentMessaged) {
timeline.push(`[AGENT] ${ts} ${act.agentMessaged.agentMessage}`);
}
if (act.userMessaged) {
timeline.push(`[USER] ${ts} ${act.userMessaged.userMessage}`);
}
if (act.sessionCompleted) {
completed = true;
timeline.push(`[COMPLETED] ${ts} Session finished`);
}
if (act.sessionFailed) {
failed = true;
failedReason = act.sessionFailed.reason;
timeline.push(`[FAILED] ${ts} ${act.sessionFailed.reason}`);
}
if (act.artifacts?.length) {
for (const a of act.artifacts) {
if (a.changeSet?.gitPatch) {
const lines = a.changeSet.gitPatch.unidiffPatch?.split("\n").length || "?";
timeline.push(`[ARTIFACT] ${ts} Git patch — ${lines} lines`);
}
if (a.bashOutput) {
const cmd = a.bashOutput.command;
const code = a.bashOutput.exitCode;
timeline.push(`[ARTIFACT] ${ts} bash: \`${cmd}\` (exit ${code})`);
}
if (a.media) {
timeline.push(`[ARTIFACT] ${ts} Media: ${a.media.mimeType}`);
}
}
}
}
}
return JSON.stringify({
sessionId,
title: session.title || "(no title)",
state: session.state || "UNKNOWN",
createTime: session.createTime || null,
updateTime: session.updateTime || null,
completed,
failed,
failedReason,
prUrl,
prTitle,
prDescription,
timeline: timeline.slice(-30),
activityCount: activities.activities?.length || 0,
nextPageToken: activities.nextPageToken || null,
}, null, 2);
},
}),
jules_list: tool({
description:
"Lists recent Jules sessions. Use to see all background tasks and their IDs.",
args: {
pageSize: tool.schema
.number()
.int()
.optional()
.describe("Number of sessions to list (max 100, default 30)."),
pageToken: tool.schema
.string()
.optional()
.describe("Page token from a previous jules_list response for pagination."),
},
async execute(args) {
const { pageSize, pageToken } = args;
const params = new URLSearchParams();
if (pageSize) params.set("pageSize", pageSize);
if (pageToken) params.set("pageToken", pageToken);
const qs = params.toString();
const result = await julesRequest("GET", `/sessions${qs ? "?" + qs : ""}`);
if (result.error) {
return `Jules API error (${result.error.status}): ${result.error.body}`;
}
if (!result.sessions) return "No Jules sessions found.";
return JSON.stringify({
sessions: result.sessions.map((s) => ({
sessionId: s.id || s.name?.split("/").pop() || "?",
title: s.title || "(no title)",
state: s.state || "UNKNOWN",
prompt: (s.prompt || "").slice(0, 80),
createTime: s.createTime || null,
updateTime: s.updateTime || null,
prUrl:
s.outputs?.find((o) => o.pullRequest)?.pullRequest?.url || null,
})),
nextPageToken: result.nextPageToken || null,
}, null, 2);
},
}),
jules_list_sources: tool({
description:
"Lists available GitHub sources (repos) connected to Jules. " +
"Call this first to discover source names for jules_create.",
args: {
pageSize: tool.schema
.number()
.int()
.optional()
.describe("Number of sources to return (max 100, default 30)."),
pageToken: tool.schema
.string()
.optional()
.describe("Page token from a previous jules_list_sources response."),
filter: tool.schema
.string()
.optional()
.describe('Filter expression (e.g. "name=sources/github-owner-repo").'),
},
async execute(args) {
const { pageSize, pageToken, filter } = args;
const params = new URLSearchParams();
if (pageSize) params.set("pageSize", pageSize);
if (pageToken) params.set("pageToken", pageToken);
if (filter) params.set("filter", filter);
const qs = params.toString();
const result = await julesRequest("GET", `/sources${qs ? "?" + qs : ""}`);
if (result.error) {
return `Jules API error (${result.error.status}): ${result.error.body}`;
}
if (!result.sources) return "No sources found. Install the Jules GitHub app first.";
return JSON.stringify({
sources: result.sources.map((s) => ({
name: s.name,
id: s.id,
repo: `${s.githubRepo?.owner}/${s.githubRepo?.repo}`,
isPrivate: s.githubRepo?.isPrivate,
defaultBranch: s.githubRepo?.defaultBranch?.displayName || "?",
})),
nextPageToken: result.nextPageToken || null,
}, null, 2);
},
}),
jules_delete: tool({
description:
"Cancels and deletes a Jules session. The session must be in a state that " +
"allows deletion (not actively running).",
args: {
sessionId: tool.schema
.string()
.describe("The Jules session ID to delete."),
},
async execute(args) {
const { sessionId } = args;
const result = await julesRequest("DELETE", `/sessions/${sessionId}`);
if (result.error) {
return `Jules API error (${result.error.status}): ${result.error.body}`;
}
return JSON.stringify({ sessionId, deleted: true }, null, 2);
},
}),
jules_message: tool({
description:
"Sends a message from the user to an active Jules session. " +
"Use this to provide feedback, answer questions, or give additional " +
"instructions while Jules is working.",
args: {
sessionId: tool.schema
.string()
.describe("The Jules session ID to send a message to."),
prompt: tool.schema
.string()
.describe("The message to send to Jules."),
},
async execute(args) {
const { sessionId, prompt } = args;
const result = await julesRequest("POST", `/sessions/${sessionId}:sendMessage`, { prompt });
if (result.error) {
return `Jules API error (${result.error.status}): ${result.error.body}`;
}
return JSON.stringify({ sessionId, sent: true }, null, 2);
},
}),
jules_approve: tool({
description:
"Approves a pending plan in a Jules session. Only needed when the session " +
"was created with requirePlanApproval=true.",
args: {
sessionId: tool.schema
.string()
.describe("The Jules session ID to approve the plan for."),
},
async execute(args) {
const { sessionId } = args;
const result = await julesRequest("POST", `/sessions/${sessionId}:approvePlan`, {});
if (result.error) {
return `Jules API error (${result.error.status}): ${result.error.body}`;
}
return JSON.stringify({ sessionId, approved: true }, null, 2);
},
}),
jules_activity: tool({
description:
"Gets a single activity from a Jules session by ID. Returns full activity " +
"details including artifacts like code changes (git patches), bash output, " +
"or media files.",
args: {
sessionId: tool.schema
.string()
.describe("The Jules session ID."),
activityId: tool.schema
.string()
.describe("The activity ID to fetch."),
},
async execute(args) {
const { sessionId, activityId } = args;
const result = await julesRequest("GET", `/sessions/${sessionId}/activities/${activityId}`);
if (result.error) {
return `Jules API error (${result.error.status}): ${result.error.body}`;
}
return JSON.stringify({
id: result.id,
originator: result.originator,
description: result.description,
createTime: result.createTime,
planGenerated: result.planGenerated || null,
planApproved: result.planApproved || null,
userMessaged: result.userMessaged || null,
agentMessaged: result.agentMessaged || null,
progressUpdated: result.progressUpdated || null,
sessionCompleted: result.sessionCompleted || null,
sessionFailed: result.sessionFailed || null,
artifacts: result.artifacts || [],
}, null, 2);
},
}),
jules_get_source: tool({
description:
"Gets detailed information about a single source (GitHub repo) including " +
"all available branches. Use this to discover branch names before creating " +
"a session.",
args: {
sourceName: tool.schema
.string()
.describe(
"The source resource name (e.g. 'sources/github-owner-repo') or just " +
"the source ID (e.g. 'github-owner-repo')."
),
},
async execute(args) {
const { sourceName } = args;
const sourceId = sourceName.startsWith("sources/") ? sourceName.replace("sources/", "") : sourceName;
const result = await julesRequest("GET", `/sources/${sourceId}`);
if (result.error) {
return `Jules API error (${result.error.status}): ${result.error.body}`;
}
return JSON.stringify({
name: result.name,
repo: `${result.githubRepo?.owner}/${result.githubRepo?.repo}`,
isPrivate: result.githubRepo?.isPrivate,
defaultBranch: result.githubRepo?.defaultBranch?.displayName || "?",
branches: (result.githubRepo?.branches || []).map((b) => b.displayName),
}, null, 2);
},
}),
},
};
};