### Install Dependencies and Start MCP Server Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/custom-mcp-server/README.md Installs project dependencies, sets the Jules API key, and starts the MCP server. Ensure JULES_API_KEY is set in your environment. ```bash npm install export JULES_API_KEY="your-api-key" bun run start ``` -------------------------------- ### Quick Start Installation and Running Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/express/README.md Instructions for installing dependencies, setting up environment variables, and running the Express server. ```APIDOC ## Quick Start 1. **Install Dependencies:** ```bash npm install ``` 2. **Set API Key:** ```bash export JULES_API_KEY="your-api-key" ``` 3. **Set Port (Optional):** ```bash export PORT=3000 ``` 4. **Run the Server:** ```bash bun run index.ts ``` This will start the server, perform a self-test request, and then shut down. ``` -------------------------------- ### Jules MCP Server Setup and Execution Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/mcp/README.md Instructions for installing and running the Jules MCP Server, including environment variable setup. ```APIDOC ## Installation ```bash npm i @google/jules-mcp export JULES_API_KEY= ``` ## Run the server ```bash npx @google/jules-mcp ``` ## Connect an AI assistant to Jules ```json { "mcpServers": { "jules": { "command": "npx", "args": ["@google/jules-mcp"], "env": { "JULES_API_KEY": "" } } } } ``` ``` -------------------------------- ### Install and Run Express Server Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/express/README.md Install dependencies, set the Jules API key, and start the Express server. The server defaults to port 3000 if not specified. ```bash npm install export JULES_API_KEY="your-api-key" export PORT=3000 # optional, defaults to 3000 bun run index.ts ``` -------------------------------- ### Install and Set Up Jules SDK Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/nextjs/README.md Install the SDK and set your API key. This command runs a self-test without a full Next.js server. ```bash npm install export JULES_API_KEY="your-api-key" bun run index.ts ``` -------------------------------- ### Install and Run Scheduler Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/cron-jobs/README.md Install dependencies, set API keys and project ID as environment variables, and run the scheduler using bun. ```bash npm install export JULES_API_KEY="your-api-key" export STITCH_API_KEY="your-stitch-key" export STITCH_PROJECT_ID="your-project-id" bun run index.ts ``` -------------------------------- ### Install Dependencies and Set Up Environment Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/file-system-events/README.md Installs project dependencies, sets the Jules API key, and optionally defines the directory to watch. Ensure JULES_API_KEY is set to your actual API key. ```bash npm install export JULES_API_KEY="your-api-key" export WATCH_DIR="watched-directory" # optional, defaults to watched-directory bun run index.ts ``` -------------------------------- ### Install Dependencies and Set API Keys Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/stitch/README.md Installs project dependencies, sets the Jules and Stitch API keys as environment variables, and runs the main script. ```bash npm install export JULES_API_KEY="your-api-key" export STITCH_API_KEY="your-stitch-key" bun run index.ts ``` -------------------------------- ### Install and Run MCP Server Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Commands to install the MCP server package and set the API key environment variable, followed by running the server. ```bash # Install and run the MCP server npm i @google/jules-mcp export JULES_API_KEY= npx @google/jules-mcp ``` -------------------------------- ### Install Dependencies and Set API Keys Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/ai-sdk/README.md Install npm packages and set environment variables for Jules and Google AI API keys before running the agent. ```bash npm install export JULES_API_KEY="your-api-key" export GOOGLE_GENERATIVE_AI_API_KEY="your-google-ai-key" ``` -------------------------------- ### Install Jules SDK and Set API Key Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/README.md Installs the Jules SDK using npm and sets the JULES_API_KEY environment variable, which is required for authentication. ```bash npm i @google/jules-sdk export JULES_API_KEY= ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Installs project dependencies using the Bun package manager. Keep this running during development to automatically update. ```bash cd packages/merge bun install ``` -------------------------------- ### Start MCP Server Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/README.md Start the MCP (Multi-Cloud Platform) server for Jules Merge, which exposes 7 tools for reconciliation tasks. ```bash jules-merge mcp ``` -------------------------------- ### Install Jules Merge CLI Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/README.md Install the Jules Merge command-line interface using npm. ```bash npm i @google/jules-merge ``` -------------------------------- ### Install Jules MCP Package Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/mcp/README.md Install the Jules MCP package using npm and set the JULES_API_KEY environment variable. ```bash npm i @google/jules-mcp export JULES_API_KEY= ``` -------------------------------- ### MCP Client Configuration for Jules Plan Server Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/mcp-plan-generation/README.md Configuration example for connecting an MCP client to the Jules Plan Generation Server. Ensure the path to the index.ts file and the JULES_API_KEY are correctly set. ```json { "mcpServers": { "jules-plan": { "command": "bun", "args": ["run", "/path/to/examples/mcp-plan-generation/index.ts"], "env": { "JULES_API_KEY": "your-key" } } } } ``` -------------------------------- ### Import Style Example Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Demonstrates the required import style using `.js` extensions for relative imports, as per NodeNext resolution. ```typescript import { ok } from '../shared/result.js'; ``` -------------------------------- ### Start an Interactive Session Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/README.md Initiates an interactive session for workflows requiring observation and feedback. Use this when you need to guide the agent's process step-by-step. ```typescript const session = await jules.session({ prompt: 'Refactor the user authentication module.', source: { github: 'your-org/your-repo', baseBranch: 'develop' }, }); console.log(`Session created: ${session.id}`); await session.waitFor('awaitingPlanApproval'); console.log('Plan is ready. Approving it now.'); await session.approve(); const reply = await session.ask( 'Start with the first step and let me know when it is done.', ); console.log(`[AGENT] ${reply.message}`); const outcome = await session.result(); console.log(`Session finished with state: ${outcome.state}`); ``` -------------------------------- ### Create a Fleet of Agent Sessions in Parallel Source: https://github.com/google-labs-code/jules-sdk/blob/main/README.md Processes multiple tasks concurrently using `jules.all()`, similar to `Promise.all()` but with built-in concurrency control. This example shows creating sessions for a list of to-do items. ```javascript const todos = ['Fix login bug', 'Update README', 'Refactor tests']; const sessions = await jules.all(todos, (task) => ({ prompt: task, source: { github: 'user/repo', baseBranch: 'main' }, })); console.log(`Created ${sessions.length} sessions.`); ``` -------------------------------- ### Expected Pre-Push Conflict Output Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Example JSON output indicating a merge conflict during pre-push validation. Shows the status, a message, and details about the conflicting files. ```json { "status": "conflict", "message": "The remote main branch has advanced. Rebase required for src/auth/middleware.ts.", "conflicts": [ { "filePath": "src/auth/middleware.ts", "conflictReason": "Remote commit modified this file since branch creation.", "remoteShadowContent": "export async function verifyToken(token, options) { ... }" } ] } ``` -------------------------------- ### Unified Diff Format Example Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/gitpatch-improve/README.md Illustrates the standard unified diff format used for GitPatches, similar to what `git diff` produces. This format is used to represent code changes. ```diff --- a/src/auth.ts +++ b/src/auth.ts @@ -12,7 +12,10 @@ export async function validateToken(token: string) { - const decoded = jwt.verify(token, SECRET); - return decoded; + try { + const decoded = jwt.verify(token, SECRET); + return { valid: true, payload: decoded }; + } catch (err) { + return { valid: false, error: err.message }; + } } ``` -------------------------------- ### List and Get Agent Sources Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/README.md Provides methods to list all connected agent sources and retrieve a specific source by its GitHub repository details. Useful for managing context for agent sessions. ```typescript // List all connected sources for await (const source of jules.sources()) { if (source.type === 'githubRepo') { console.log(`${source.githubRepo.owner}/${source.githubRepo.repo}`); console.log(` Private: ${source.githubRepo.isPrivate}`); } } // Get a specific source const myRepo = await jules.sources.get({ github: 'my-org/my-project' }); if (myRepo) { console.log(`Found: ${myRepo.id}`); } ``` -------------------------------- ### Jules Session Prompt for Serverless Compute Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/custom-cli/README.md Configure a Jules session to act as an autonomous Cloud Compute Agent. The prompt instructs the agent to use a full Linux environment, install dependencies, run scripts, and write the final output to 'final_output.txt'. ```typescript const session = await jules.session({ prompt: `You are an autonomous Cloud Compute Agent with a full Linux environment. ## Objective ${instruction} ## Rules 1. Write and run scripts yourself. Install dependencies as needed. 2. Write the final result to final_output.txt . `, }); ``` -------------------------------- ### Run Repoless Cloud Functions Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/README.md Executes a Jules session without a GitHub repository, acting as a preconfigured serverless function. This example demonstrates passing context from a database query and user input to an agent for processing. ```typescript import { jules } from '@google/jules-sdk'; import { sql } from 'drizzle-orm'; const longDocumentsNobodyWantsToRead = await sql`SELECT * FROM documents`; const userPrompt = process.argv[2]; const session = await jules.session({ prompt: `You are a assistant that can read long documents and answer questions about them. ## The user's question ${userPrompt} ## The documents ${longDocumentsNobodyWantsToRead.map((e) => e.title).join(' ')} ## Answer Format Create a markdown response with the following sections: - Summary - Answer - Sources Cited `, }); const result = await session.result(); const files = result.generatedFiles(); const answer = files.get('answer.md'); console.log(answer?.content); // Call the script as CLI // node index.js "Review the policies and explain to me delivery timelines like I'm 7 years old." ``` -------------------------------- ### Initialize Jules Fleet Repository Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/fleet/README.md Use the CLI command to set up a new repository with Jules Fleet. This command initiates an interactive wizard to configure authentication, secrets, and workflow files. ```bash npx @google/jules-fleet init ``` -------------------------------- ### Run Jules CLI with Google Doc Context Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/google-docs/README.md Execute a Jules repoless session using a Google Doc ID and a prompt. Ensure JULES_API_KEY is set. ```bash export JULES_API_KEY="your-api-key" # Analyze a Google Doc bun run start --document-id "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2ktIg" \ --prompt "Summarize the key points" ``` -------------------------------- ### Initialize a Fleet Repository Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/fleet/README.md Scaffolds a new repository for fleet workflows by creating a pull request with necessary configuration files and labels. ```bash jules-fleet init [options] Options: --repo Repository (auto-detected from git remote) --base Base branch for the PR (default: main) --interval Pipeline cadence in minutes (default: 360) --non-interactive Disable wizard prompts — all inputs via flags/env vars --dry-run Show what would be created without making changes --upload-secrets Upload secrets to GitHub Actions (default: true) ``` -------------------------------- ### jules.with() - Custom Configuration Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Create new client instances with different configurations for multi-tenant or specialized use cases, such as using different API keys or custom network timeouts. ```APIDOC ## jules.with() - Custom Configuration Create new client instances with different configurations for multi-tenant or specialized use cases. ### Method `jules.with(options)` ### Parameters #### Options Object - **apiKey** (string) - Optional - The API key to use for the new client instance. - **config** (object) - Optional - Configuration object for network and polling settings. - **pollingIntervalMs** (number) - Optional - The interval in milliseconds for polling operations. - **requestTimeoutMs** (number) - Optional - The timeout in milliseconds for individual requests. - **rateLimitRetry** (object) - Optional - Configuration for rate limit retries. - **maxRetryTimeMs** (number) - Maximum time in milliseconds to retry. - **baseDelayMs** (number) - Base delay in milliseconds for exponential backoff. - **maxDelayMs** (number) - Maximum delay in milliseconds for exponential backoff. ### Request Example (API Key) ```typescript const teamClient = jules.with({ apiKey: 'team-api-key' }); ``` ### Request Example (Custom Timeouts) ```typescript const slowClient = jules.with({ config: { pollingIntervalMs: 10000, // Poll every 10 seconds requestTimeoutMs: 60000, // 60 second request timeout rateLimitRetry: { maxRetryTimeMs: 600000, // Retry for up to 10 minutes baseDelayMs: 2000, maxDelayMs: 60000, }, }, }); // Use the customized client const session = await slowClient.session({ prompt: 'Complex refactoring task...', source: { github: 'org/large-repo', baseBranch: 'main' }, }); ``` ### Alternative: `jules.connect()` Provides an alternative factory method for creating client instances with custom configurations. **Parameters** - **apiKey** (string) - Required - The API key for authentication. - **baseUrl** (string) - Optional - The base URL for the Jules API endpoint. ### Request Example (`connect()`) ```typescript const newClient = jules.connect({ apiKey: 'another-api-key', baseUrl: 'https://custom-endpoint.example.com/v1alpha', }); ``` ``` -------------------------------- ### Set API Key and Run Session Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/advanced-session/README.md Set your Jules API key as an environment variable and execute the main session script using Bun. ```bash export JULES_API_KEY="your-api-key" bun run index.ts ``` -------------------------------- ### Get the Full Snapshot with `toJSON()` Source: https://github.com/google-labs-code/jules-sdk/blob/main/docs/snapshot.md To retrieve all fields of the snapshot without any masking, pass an empty options object `{}` to the `toJSON()` method. ```typescript const full = snapshot.toJSON({}); console.log(full.activities?.length); // 15 (all activities) console.log(full.generatedFiles?.length); // 3 (all generated files) ``` -------------------------------- ### Customize Cron Schedule Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/cron-jobs/README.md Modify the cron expression in index.ts to change the polling frequency. Examples show a nightly schedule and an every-30-minutes schedule. ```typescript cron.schedule('0 0 * * *', ...); // nightly ``` ```typescript cron.schedule('*/30 * * * *', ...); // every 30 minutes ``` -------------------------------- ### Jules Merge Programmatic API Usage Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/README.md Example of using the Jules Merge programmatic API to scan PRs. All handlers require an Octokit instance. ```typescript import { scanHandler, getContentsHandler, stageResolutionHandler, statusHandler, pushHandler, mergeHandler, createMergeOctokit, } from '@google/jules-merge'; const octokit = createMergeOctokit(); const scan = await scanHandler(octokit, { prs: [10, 11], repo: 'owner/repo' }); ``` -------------------------------- ### Run the Jules MCP Server Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/mcp/README.md Execute the Jules MCP server using npx. ```bash npx @google/jules-mcp ``` -------------------------------- ### Create Custom Jules SDK Client Instances Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Use `jules.with()` or `jules.connect()` to create new client instances with custom configurations, such as different API keys, base URLs, or advanced timeout and retry settings. ```typescript import { jules } from '@google/jules-sdk'; // Create a client with a different API key const teamClient = jules.with({ apiKey: 'team-api-key' }); // Create a client with custom timeouts const slowClient = jules.with({ config: { pollingIntervalMs: 10000, // Poll every 10 seconds requestTimeoutMs: 60000, // 60 second request timeout rateLimitRetry: { maxRetryTimeMs: 600000, // Retry for up to 10 minutes baseDelayMs: 2000, maxDelayMs: 60000, }, }, }); // Use the customized client const session = await slowClient.session({ prompt: 'Complex refactoring task...', source: { github: 'org/large-repo', baseBranch: 'main' }, }); ``` ```typescript // Alternative: connect() factory method const newClient = jules.connect({ apiKey: 'another-api-key', baseUrl: 'https://custom-endpoint.example.com/v1alpha', }); ``` -------------------------------- ### Jules-Merge Conflict Detection Output Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/use-case.md Example JSON output from `jules-merge check-conflicts`, detailing files with merge conflicts and the conflict markers found within them. ```json { "success": true, "data": { "taskDirective": "MERGE CONFLICT RESOLUTION REQUIRED for PR #1...", "priority": "critical", "affectedFiles": [ { "filePath": "packages/fleet/src/cli/init.command.ts", "gitConflictMarkers": "<<<<<<< HEAD\nimport { getGitRepoInfo }...\n=======\nimport { createRenderer, createEmitter, isInteractive }...\n>>>>>>> origin/main" } ] } } ``` -------------------------------- ### Run Vitest Watch Mode Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Start Vitest in watch mode to automatically re-run tests on file changes. Keep this running throughout the development process. ```bash bunx vitest --watch ``` -------------------------------- ### Run Instruction and Save Output Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/custom-cli/README.md Execute a command with Jules and save the results to a specified file. Ensure the JULES_API_KEY environment variable is set. ```bash export JULES_API_KEY="your-api-key" # Run an instruction and save the output bun run start run \ --instruction="Scrape headlines from Hacker News" \ --output-file="./hn.json" ``` -------------------------------- ### Run Jules SDK with Spreadsheet Data Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/google-sheets/README.md Execute the Jules SDK from the command line to analyze spreadsheet data. Requires setting the JULES_API_KEY environment variable. ```bash export JULES_API_KEY="your-api-key" # Analyze spreadsheet data bun run start --spreadsheet-id "your-spreadsheet-id" \ --range "Sheet1!A1:D10" \ --prompt "Generate a chart from this data" ``` -------------------------------- ### Get Session Status by ID using curl Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/hono/README.md Use curl to retrieve the status of an existing session by providing its ID in the URL. This reconnects to the session and returns its current state. ```bash curl http://localhost:3000/api/sessions/SESSION_ID/status ``` -------------------------------- ### Set API Key and Run CLI Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/gitpatch-goals/README.md Set your Jules API key and run the CLI tool to generate and review code against a prompt. A dry run option is available to simulate the process without creating sessions. ```bash export JULES_API_KEY="your-api-key" # Generate and review code against a prompt bun run start --prompt "Add input validation to the login form" # Dry run (returns mock data without creating sessions) bun run start --prompt "Add error handling" --dry-run ``` -------------------------------- ### Create a Session Snapshot Source: https://github.com/google-labs-code/jules-sdk/blob/main/docs/snapshot.md Instantiate a session and create a snapshot. You can choose to load all activities or create a lighter snapshot without them. ```typescript import { jules } from '@google/jules-sdk'; const session = jules.session('existing-session-id'); // Create a snapshot with activities loaded const snapshot = await session.snapshot({ activities: true }); // Or without activities (lighter weight) const lightSnapshot = await session.snapshot({ activities: false }); ``` -------------------------------- ### Observe Agent Progress with Reactive Streams Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/README.md Uses the `.stream()` method to get an `AsyncIterator` for observing agent progress in real-time. Handles different activity types like plan generation and messages. ```typescript for await (const activity of session.stream()) { switch (activity.type) { case 'planGenerated': console.log( 'Plan:', activity.plan.steps.map((s) => s.title), ); break; case 'agentMessaged': console.log('Agent says:', activity.message); break; case 'sessionCompleted': console.log('Session complete!'); break; } } ``` -------------------------------- ### Configuration and Environment Variables Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/express/README.md Details on how to configure the Express server using environment variables. ```APIDOC ## Configuration ### Environment Variables | Variable | Required | Default | Description | |-----------------|----------|---------|-------------------------------------------| | `JULES_API_KEY` | Yes | — | API key for Jules authentication. | | `PORT` | No | `3000` | Port on which the Express server listens. | ``` -------------------------------- ### Configure Jules SDK with Custom Options Source: https://github.com/google-labs-code/jules-sdk/blob/main/README.md Instantiate the Jules SDK with custom configurations using the `jules.with()` method. This allows setting API keys, polling intervals, and timeouts programmatically. ```typescript import { jules } from '@google/jules-sdk'; // Multiple API keys const customJules = jules.with({ apiKey: 'other-api-key' }); ``` ```typescript // Polling & timeouts const customJules = jules.with({ pollingIntervalMs: 2000, timeout: 60000, }); ``` -------------------------------- ### List and Get Agent Sources Source: https://github.com/google-labs-code/jules-sdk/blob/main/README.md Access agent sources using `jules.sources()` to iterate over connected sources, or `jules.sources.get()` to retrieve a specific source by its identifier. Supports filtering by GitHub repository details. ```typescript // List all connected sources for await (const source of jules.sources()) { if (source.type === 'githubRepo') { console.log(`${source.githubRepo.owner}/${source.githubRepo.repo}`); console.log(` Private: ${source.githubRepo.isPrivate}`); } } ``` ```typescript // Get a specific source const myRepo = await jules.sources.get({ github: 'my-org/my-project' }); if (myRepo) { console.log(`Found: ${myRepo.id}`); } ``` -------------------------------- ### Run GitPatch Review Pipeline Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/gitpatch-review/README.md Execute the pipeline with a prompt and target repository. Options include JSON output and dry runs. ```bash export JULES_API_KEY="your-api-key" # Generate code and review it bun run start --prompt "Add error handling" --repo owner/repo # JSON output for programmatic use bun run start --prompt "Fix the bug" --repo owner/repo --json # Dry run bun run start --prompt "Refactor utils" --repo owner/repo --dry-run ``` -------------------------------- ### Run AI Agent with Different Prompts Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/ai-sdk/README.md Execute the AI agent with various prompts to perform coding tasks, target specific repositories, get JSON output, or perform a dry run. ```bash bun start start --prompt "Write a Python script that sorts a list of numbers" ``` ```bash bun start start --prompt "Add input validation" --repo owner/repo ``` ```bash bun start start --prompt "Fix the bug in auth.ts" --output json ``` ```bash bun start start --prompt "Refactor the utils module" --dry-run ``` -------------------------------- ### Build Project Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Compile the project. This command is typically run during the final verification phase to ensure the build process is successful. ```bash bun run build ``` -------------------------------- ### Describe CLI Schema Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/gitpatch-local/SKILL.md Use the `--describe` flag to inspect the JSON schema for this CLI. This is useful for understanding input and output formats. ```bash bun run index.ts "" --describe ``` -------------------------------- ### Initialize Fleet for Continuous Analysis Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Command to initialize the Fleet continuous analysis pipeline in a repository, specifying the repository owner/name and the analysis interval. ```bash # Initialize fleet in a repository npx @google/jules-fleet init --repo owner/repo --interval 360 ``` -------------------------------- ### Handle Session Results Non-Blockingly Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/basic-session/README.md Use `session.result()` to get a promise that resolves with the final session outcome. Attach a `.then()` handler to process the state, PR URL, and generated files without halting the activity stream. ```typescript session.result().then(outcome => { console.log(`State: ${outcome.state}`); console.log(`PR: ${outcome.pullRequest?.url ?? 'none'}`); console.log(`Files: ${outcome.generatedFiles().all().length}`); }); ``` -------------------------------- ### Get Changed Files in Jules Session Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Retrieves a list of changed files for a given Jules session. It handles both busy (in-progress) and stable (completed) session states by aggregating change set artifacts or using the session outcome. ```typescript import { type JulesClient, type ChangeSetArtifact, type Activity } from '@google/jules-sdk'; export interface SessionFileInfo { path: string; changeType: 'created' | 'modified' | 'deleted'; } /** * Get the list of files changed in a Jules session. * * Dual-mode: * - If session is busy (in-progress): aggregates changeSet artifacts from activities * - If session is stable (completed): uses the session outcome's changeSet */ export async function getSessionChangedFiles( client: JulesClient, sessionId: string, ): Promise { const session = client.session(sessionId); await session.activities.hydrate(); const snapshot = await session.snapshot(); const isBusy = isBusyState(snapshot.state); if (isBusy) { return aggregateFromActivities(snapshot.activities); } // Stable: use outcome changeSet const changeSet = snapshot.changeSet(); if (!changeSet) return []; const parsed = changeSet.parsed(); return parsed.files.map(f => ({ path: f.path, changeType: f.changeType })); } function isBusyState(state: string): boolean { const busy = new Set(['queued', 'planning', 'inProgress', 'in_progress']); return busy.has(state); } function aggregateFromActivities(activities: readonly Activity[]): SessionFileInfo[] { const fileMap = new Map(); for (const activity of activities) { for (const artifact of activity.artifacts) { if (artifact.type === 'changeSet') { const parsed = (artifact as ChangeSetArtifact).parsed(); for (const file of parsed.files) { const existing = fileMap.get(file.path); if (existing) { existing.latestChangeType = file.changeType; } else { fileMap.set(file.path, { firstChangeType: file.changeType, latestChangeType: file.changeType, }); } } } } } const result: SessionFileInfo[] = []; for (const [path, info] of fileMap) { // created → deleted = net no change, skip if (info.firstChangeType === 'created' && info.latestChangeType === 'deleted') continue; const netType = info.firstChangeType === 'created' ? 'created' : info.latestChangeType; result.push({ path, changeType: netType }); } return result; } /** * Create a JulesClient from environment. * Expects JULES_API_KEY to be set. */ export { jules as createJulesClient } from '@google/jules-sdk'; ``` -------------------------------- ### Bun Build Script Configuration Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Configuration for the Bun build script, specifying library and CLI entry points, and defining external dependencies. ```typescript // ./build.ts // Library entry: ./src/index.ts // CLI entries: ./src/cli/index.ts + auto-discovered ./src/cli/*.command.ts // Externals: @google/jules-sdk, @octokit/rest, citty, zod, @modelcontextprotocol/sdk ``` -------------------------------- ### Batch Processing with jules.all() Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Process multiple tasks in parallel using jules.all(), which offers built-in concurrency control similar to Promise.all(). Configure concurrency limits, error handling, and delays between task starts. Requires importing the 'jules' SDK. ```typescript import { jules } from '@google/jules-sdk'; const tasks = [ { issue: '#123', description: 'Fix login bug' }, { issue: '#124', description: 'Update README' }, { issue: '#125', description: 'Refactor tests' }, { issue: '#126', description: 'Add dark mode' }, ]; // Process all tasks with concurrency control const sessions = await jules.all( tasks, (task) => ({ prompt: `Fix issue ${task.issue}: ${task.description}`, source: { github: 'user/repo', baseBranch: 'main' }, title: `Fix ${task.issue}`, }), { concurrency: 3, // Max 3 concurrent sessions stopOnError: false, // Continue if one fails delayMs: 500, // 500ms between starts } ); console.log(`Created ${sessions.length} sessions`); // Wait for all results const results = await Promise.all(sessions.map(s => s.result())); for (const outcome of results) { console.log(`${outcome.title}: ${outcome.state} - ${outcome.pullRequest?.url ?? 'no PR'}`); } ``` -------------------------------- ### Jules SDK Observation Methods Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/README.md Explains how to observe and query session activities and state. ```APIDOC ## Observation ### Description Methods for observing and querying session activities and state. ### Methods - `session.stream()`: Returns an asynchronous iterator for all session activities. - `session.history()`: Provides a stream of cached activities within the session. - `session.updates()`: Returns a stream of live, real-time activities. - `session.select(query)`: Queries the local cache for specific data using a query. - `session.info()`: Fetches the latest state information for the session. ``` -------------------------------- ### Create and Manage Interactive Session with Jules SDK Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Create a new interactive session for tasks requiring human oversight or rehydrate an existing one by ID. Interactive sessions default to requiring plan approval before execution. Use `session.ask()` for conversation and `session.result()` to get the final outcome. ```typescript import { jules } from '@google/jules-sdk'; // Create a new interactive session with a GitHub source const session = await jules.session({ prompt: 'Refactor the user authentication module.', source: { github: 'your-org/your-repo', baseBranch: 'develop' }, title: 'Auth Module Refactor', requireApproval: true, // default for interactive sessions autoPr: true, }); console.log(`Session created: ${session.id}`); // Wait for the plan to be ready, then approve it await session.waitFor('awaitingPlanApproval'); console.log('Plan is ready. Approving...'); await session.approve(); // Have a conversation with the agent const reply = await session.ask('Start with the first step and let me know when done.'); console.log(`[AGENT] ${reply.message}`); // Get final outcome const outcome = await session.result(); console.log(`Session finished: ${outcome.state}`); if (outcome.pullRequest) { console.log(`PR: ${outcome.pullRequest.url}`); } // Rehydrate an existing session by ID (useful in serverless) const existingSession = jules.session('existing-session-id'); const info = await existingSession.info(); console.log(`Reconnected to session in state: ${info.state}`); ``` -------------------------------- ### Set up Git Worktree for jules-merge Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Instructions for creating and navigating to a new Git worktree for the jules-merge package development. This isolates work from the main branch. ```bash cd /Users/deast/google-labs-code/jules-sdk git worktree add ../jules-sdk-merge feat/jules-merge cd ../jules-sdk-merge ``` ```bash cd packages/merge bun install ``` ```bash cd /Users/deast/google-labs-code/jules-sdk git worktree remove ../jules-sdk-merge ``` -------------------------------- ### Run Repoless Session with Document Context Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/google-docs/README.md Initiate a repoless session with Jules, appending the extracted Google Doc content to the user's prompt. This function requires the `runRepolessSession` helper. ```typescript const outcome = await runRepolessSession( `${input.prompt}\n\n## Source Document Content\n${docText}`, ); ``` -------------------------------- ### Resolving Repository and Branch from GitHub Actions Context Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/github-action-agentskills/README.md This TypeScript code snippet demonstrates how to robustly resolve the repository owner and base branch from the GitHub Actions context and environment variables. It prioritizes context variables and falls back to environment variables, ensuring compatibility with different GitHub Actions setups. ```typescript const owner = context.repo.owner || process.env.GITHUB_REPOSITORY?.split('/')[0]; const baseBranch = (context.ref || process.env.GITHUB_REF || 'refs/heads/main').replace('refs/heads/', ''); ``` -------------------------------- ### Initialize MCP Server and Register Tools Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/AGENT_CONTEXT.md Initializes the Model Context Protocol (MCP) server using stdio transport. It registers two tools: 'validate_branch_for_conflicts' for pre-push checks and 'extract_ci_failure_context' for processing CI failures. Both tools parse input using specific schemas and execute corresponding handlers. ```typescript import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; ``` -------------------------------- ### jules-fleet init Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/fleet/README.md Scaffolds a repository for fleet workflows by creating a Pull Request with necessary files and labels. ```APIDOC ## jules-fleet init ### Description Scaffold a repository for fleet workflows by creating a PR with the necessary files. ### Method CLI Command ### Endpoint jules-fleet init [options] ### Parameters #### Query Parameters - **--repo** (string) - Optional - Repository (auto-detected from git remote) - **--base** (string) - Optional - Base branch for the PR (default: main) - **--interval** (minutes) - Optional - Pipeline cadence in minutes (default: 360) - **--non-interactive** (boolean) - Optional - Disable wizard prompts — all inputs via flags/env vars - **--dry-run** (boolean) - Optional - Show what would be created without making changes - **--upload-secrets** (boolean) - Optional - Upload secrets to GitHub Actions (default: true) ### Request Example ```bash jules-fleet init --repo owner/repo --base develop ``` ### Response #### Success Response (200) - **Files added**: `.github/workflows/fleet-analyze.yml`, `.github/workflows/fleet-dispatch.yml`, `.github/workflows/fleet-merge.yml`, `.fleet/goals/example.md` - **Labels created**: `fleet`, `fleet-merge-ready` #### Response Example ``` PR created successfully. Files added: - .github/workflows/fleet-analyze.yml - .github/workflows/fleet-dispatch.yml - .github/workflows/fleet-merge.yml - .fleet/goals/example.md Labels created: - fleet - fleet-merge-ready ``` ``` -------------------------------- ### jules.sessions() - List Sessions with Pagination Source: https://context7.com/google-labs-code/jules-sdk/llms.txt List sessions with a fluent, pagination-friendly API using cursors. ```APIDOC ## jules.sessions() ### Description List sessions with a fluent, pagination-friendly API using cursors. ### Method GET ### Endpoint `/jules-sdk/sessions` ### Parameters #### Query Parameters - **pageSize** (number) - Optional - The number of sessions to return per page. Defaults to a reasonable value. - **pageToken** (string) - Optional - A token for retrieving the next page of results. ### Request Example ```typescript import { jules } from '@google/jules-sdk'; // Get first page of sessions const firstPage = await jules.sessions({ pageSize: 10 }); console.log(`First page: ${firstPage.items.length} sessions`); // Iterate through all sessions (auto-pagination) for await (const session of jules.sessions({ pageSize: 25 })) { console.log(`${session.id}: ${session.title} - ${session.state}`); } // Manual pagination with tokens let cursor = jules.sessions({ pageSize: 5 }); let page = await cursor; while (page.items.length > 0) { for (const session of page.items) { console.log(`Processing: ${session.id}`); } if (!page.nextPageToken) break; cursor = jules.sessions({ pageSize: 5, pageToken: page.nextPageToken }); page = await cursor; } ``` ### Response #### Success Response (200) - **items** (array) - An array of session objects. - **nextPageToken** (string) - A token to retrieve the next page of results, if available. #### Response Example ```json { "items": [ { "id": "session-abc", "title": "User Onboarding", "state": "completed", "createTime": "2023-10-26T14:30:00Z" } ], "nextPageToken": "some-opaque-token" } ``` ``` -------------------------------- ### Jules SDK Core Functionalities Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/README.md Provides an overview of the core client initialization and configuration methods. ```APIDOC ## Jules SDK Core ### Description Core functionalities for initializing and configuring the Jules client. ### Methods - `jules`: Initializes the pre-configured client. - `jules.with(options)`: Creates a new client instance with custom configuration options. - `jules.run(options)`: Initiates an automated session with specified options. - `jules.session(options)`: Creates or rehydrates an interactive session. - `jules.all(items, mapFn, options)`: Performs batch processing on a collection of items using a mapping function and options. ``` -------------------------------- ### Run Repoless Session with Spreadsheet Context Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/google-sheets/README.md Appends fetched spreadsheet data to the user's prompt and initiates a repoless session with Jules. Assumes `sheetData` contains the formatted data. ```typescript const outcome = await runRepolessSession( `${input.prompt}\n\n## Source Data\n${sheetData}`, ); ``` -------------------------------- ### Synchronize Local Cache with jules.sync() Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Synchronize the local cache with the server using incremental sync and tiered caching. Options include depth, limit, incremental sync, concurrency, progress callbacks, and resumable sync with checkpointing. ```typescript import { jules } from '@google/jules-sdk'; // Basic sync - metadata only const stats = await jules.sync(); console.log(`Synced ${stats.sessionsIngested} sessions in ${stats.durationMs}ms`); // Full sync with activities const fullStats = await jules.sync({ depth: 'activities', // Fetch all activity logs limit: 100, // Max sessions to process incremental: true, // Stop at already-cached records concurrency: 3, // Parallel hydration jobs onProgress: (p) => { console.log(`[${p.phase}] ${p.current}/${p.total ?? '?'}`); }, }); // Targeted sync for a specific session await jules.sync({ sessionId: 'specific-session-id' }); // Resumable sync with checkpointing const controller = new AbortController(); setTimeout(() => controller.abort(), 30000); // 30s timeout const partialStats = await jules.sync({ depth: 'activities', checkpoint: true, // Save progress to disk signal: controller.signal, }); if (!partialStats.isComplete) { console.log('Sync interrupted, will resume from checkpoint next time'); } ``` -------------------------------- ### List and Find Connected GitHub Repositories with Jules SDK Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Use `jules.sources()` to list all connected repositories and `jules.sources.get()` to find a specific one by its GitHub path. Supports filtering by name and pagination. ```typescript import { jules } from '@google/jules-sdk'; // List all connected sources console.log('Connected repositories:'); for await (const source of jules.sources()) { if (source.type === 'githubRepo') { const repo = source.githubRepo; console.log(` ${repo.owner}/${repo.repo}`); console.log(` Private: ${repo.isPrivate}`); console.log(` Default branch: ${repo.defaultBranch}`); console.log(` Branches: ${repo.branches?.join(', ')}`); } } ``` ```typescript // Find a specific repository const myRepo = await jules.sources.get({ github: 'my-org/my-project' }); if (myRepo) { console.log(`Found source: ${myRepo.name}`); console.log(`Source ID: ${myRepo.id}`); } else { console.log('Repository not connected to Jules'); } ``` ```typescript // Filter sources for await (const source of jules.sources({ filter: 'name="sources/github/my-org/my-repo"', pageSize: 50 })) { console.log(`Matched: ${source.id}`); } ``` -------------------------------- ### Run GitPatch Analysis CLI Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/gitpatch-improve/README.md Execute the CLI to analyze the most recent GitPatch. Set the JULES_API_KEY environment variable first. You can also target a specific repository and increase the search limit for historical data. ```bash export JULES_API_KEY="your-api-key" # Analyze the most recent GitPatch bun run start # Target a specific repo and search more history bun run start --repo your-org/your-repo --limit 20 ``` -------------------------------- ### Command Reference: scan Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/merge/SKILL.md Detects conflicts and builds the manifest. Requires PR numbers and repository information. ```APIDOC ## `scan` Command ### Description Detect conflicts and build the manifest. ### Method Not applicable (CLI command) ### Endpoint Not applicable (CLI command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Command Arguments - **prs** (array of PR numbers) - Required - The list of pull request numbers to scan. - **repo** (string) - Required - The owner and repository name (e.g., "owner/repo"). - **base** (string) - Optional - The base branch name (defaults to "main"). - **includeClean** (boolean) - Optional - Whether to include clean files in the scan. ``` -------------------------------- ### Configure GitHub Action for Jules Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/core/examples/github-actions/README.md Add this YAML to your .github/workflows/jules.yml file to enable the Jules agent. Ensure JULES_API_KEY is set in your repository secrets. ```yaml name: Jules Agent on: issue_comment: types: [created] jobs: jules: if: contains(github.event.comment.body, '/jules') runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: ./packages/core/examples/github-actions env: JULES_API_KEY: ${{ secrets.JULES_API_KEY }} ``` -------------------------------- ### Configure MCP Servers for Jules Source: https://github.com/google-labs-code/jules-sdk/blob/main/packages/mcp/README.md Configuration for connecting an AI assistant to Jules MCP servers. Ensure your JULES_API_KEY is set in the environment variables. ```json { "mcpServers": { "jules": { "command": "npx", "args": ["@google/jules-mcp"], "env": { "JULES_API_KEY": "" } } } } ``` -------------------------------- ### Create and Monitor Automated Session with Jules SDK Source: https://context7.com/google-labs-code/jules-sdk/llms.txt Execute a task in fully automated mode using `jules.run()`. This 'fire-and-forget' approach optionally creates a PR upon completion. You can stream activities in real-time or wait for the final result. ```typescript import { jules } from '@google/jules-sdk'; // Create an automated session const run = await jules.run({ prompt: `Fix visibility issues in the examples/nextjs app. **Visibility issues** - White text on white backgrounds - Low contrast on button hover **Instructions** - Update the global styles to a dark theme with the shadcn zinc palette.`, source: { github: 'davideast/dataprompt', baseBranch: 'main' }, autoPr: true, // default for automated runs requireApproval: false, // default for automated runs }); console.log(`Started automated session: ${run.id}`); // Option 1: Stream activities in real-time for await (const activity of run.stream()) { switch (activity.type) { case 'planGenerated': console.log(`Plan: ${activity.plan.steps.map(s => s.title).join(', ')}`); break; case 'progressUpdated': console.log(`Progress: ${activity.title}`); break; case 'agentMessaged': console.log(`Agent: ${activity.message}`); break; case 'sessionCompleted': console.log('Session completed!'); break; } } // Option 2: Just wait for the final result const outcome = await run.result(); console.log(`State: ${outcome.state}`); console.log(`PR URL: ${outcome.pullRequest?.url ?? 'none'}`); ```