From af3ac55d752765d0643a013ed9bec1b432bb634f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20M=2E=20Wo=C5=BAniak?= Date: Sat, 21 Nov 2026 12:34:47 +0100 Subject: [PATCH] Update T3 contract to 9f9ebf6 --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- pins.json | 2 +- plugins/pstack/.claude-plugin/plugin.json | 2 +- plugins/pstack/.codex-plugin/plugin.json | 2 +- .../poteto-mode/references/t3-adapter.md | 4 +- .../src/mcp/toolkits/orchestrator/tools.ts | 6 +- .../server/src/mcp/toolkits/project/tools.ts | 8 +- .../src/mcp/toolkits/pullRequests/tools.ts | 117 ++++++++++-------- .../server/src/mcp/toolkits/thread/tools.ts | 16 ++- .../src/provider/Drivers/ClaudeSkills.ts | 54 ++++++-- .../packages/contracts/src/orchestratorMcp.ts | 43 +++++++ .../src/server/orchestrationInstructions.ts | 25 ++-- .../src/server/runtimeInstructions.ts | 69 ++++++++++- 14 files changed, 269 insertions(+), 83 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 2c994db..ff50ce3 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "pstack", "source": "./plugins/pstack", "description": "Cursor pstack for T3 Code: poteto-mode, principles, and the verified agent workflows, adapted to T3 orchestration for Claude and Codex.", - "version": "0.17.2", + "version": "0.17.3", "author": { "name": "Lauren Tan (pstack), pmwoz (T3 Code port)" }, diff --git a/package.json b/package.json index d80406a..1031010 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "t3-pstack", - "version": "0.17.2", + "version": "0.17.3", "private": true, "type": "module", "scripts": { diff --git a/pins.json b/pins.json index ad8c7c7..bf6c1f4 100644 --- a/pins.json +++ b/pins.json @@ -23,7 +23,7 @@ }, "t3": { "repo": "pingdotgg/t3code", - "commit": "59651c1761f6c63e9b6056839067066968e6a406", + "commit": "9f9ebf61fbdb63df16ce6785283af6f0b38d690a", "paths": [ "apps/server/src/mcp/McpToolExposure.ts", "apps/server/src/mcp/toolkits/attachment/tools.ts", diff --git a/plugins/pstack/.claude-plugin/plugin.json b/plugins/pstack/.claude-plugin/plugin.json index a768fe9..42b4cdd 100644 --- a/plugins/pstack/.claude-plugin/plugin.json +++ b/plugins/pstack/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "pstack", "displayName": "pstack", - "version": "0.17.2", + "version": "0.17.3", "description": "Cursor pstack for T3 Code: poteto-mode, principles, and the verified agent workflows, adapted to T3 orchestration for Claude and Codex.", "author": { "name": "Lauren Tan (pstack), pmwoz (T3 Code port)" diff --git a/plugins/pstack/.codex-plugin/plugin.json b/plugins/pstack/.codex-plugin/plugin.json index 9c9efd8..b619214 100644 --- a/plugins/pstack/.codex-plugin/plugin.json +++ b/plugins/pstack/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "pstack", - "version": "0.17.2", + "version": "0.17.3", "description": "Cursor pstack for T3 Code: poteto-mode, principles, and the verified agent workflows, adapted to T3 orchestration for Claude and Codex.", "author": { "name": "Lauren Tan (pstack), pmwoz (T3 Code port)" diff --git a/plugins/pstack/skills/poteto-mode/references/t3-adapter.md b/plugins/pstack/skills/poteto-mode/references/t3-adapter.md index a317a19..acbb488 100644 --- a/plugins/pstack/skills/poteto-mode/references/t3-adapter.md +++ b/plugins/pstack/skills/poteto-mode/references/t3-adapter.md @@ -92,8 +92,8 @@ T3 has no cloud agents. Every lane is a `delegate_task` child on this machine or - **PR tools.** T3 lists the `pull_request_*` tools, `ci_logs`, and `ci_rerun` when it can reach the thread's forge, to delegated children too. When they are listed, use them, not `gh` or `origin`, wherever a playbook reads, lists, opens, edits, reviews, replies on, closes, or merges a PR, or reads or re-runs its checks. Without them, the playbooks' forge commands apply. `pull_request_update` cannot change a PR's base, so Shipping's retarget to trunk stays on `gh pr edit --base` or `origin pr edit --base`. - **Shipping verdicts.** A verifier posts its verdict with `pull_request_review` and `verdict: "comment"`. The `body` holds `PASS`, `PASS+NOTES`, or `FAIL` and the head SHA it ran, and each finding with a file and line goes in `comments`. It never sends `approve` or `request-changes`, because T3 agents act as the user's forge account and a verdict is not a forge approval. - **Landing (Shipping step 4).** Merge with `pull_request_merge`, `method: "squash"`, and `expectedHeadSha` set to the full head SHA the verdict covers, so T3 refuses a head that moved. When the run is layers of a native GitHub stack (`stack.kind` is `native` in `list_thread_pull_requests`), land it with one call on the ceiling with `stack: true`, in place of one merge per PR. T3 pins each lower layer to its current head, not to its verdict, so run step 3's check on every layer first. A derived stack merges one PR at a time. Arm auto-merge with `auto: true` under step 4's rule, never with `stack`. A result `state` of `open` means auto-merge or a merge queue holds the PR. Read each PR back with `pull_request_read`. A landed PR reads `merged` with trunk as `baseBranch`. -- **Babysit threads and CI.** Read review threads with `pull_request_read` and `sections: ["conversation"]`, and page with `cursor` until `nextCursor` is null. Reply with `pull_request_respond` and the thread's `reviewThreadId`. Set `resolved: true` on a bot's thread once the reply cites the fixing commit or a disproof. Leave escalated threads and human reviewers' threads open. Read a failing check with `ci_logs`, and spend a flake's one fresh build as `ci_rerun` with that `check`. -- **Opening a PR.** `pull_request_create` is the run's PR tool. Push the branch, then call it with `draft: false`, and with `base` for a stacked layer. It opens the PR from the calling thread's pushed branch and links it to that thread. Without it, create the PR with the resolved forge (`gh` or `origin`), ready for review, never draft. The root links every PR, each stack layer included, with `link_pull_request` for one PR or `link_pull_requests` for several in one call. A child that opens a PR returns its URL and head SHA, and the root links it. +- **Babysit threads and CI.** Read review threads with `pull_request_read` and `include: ["threads"]`, and page with `cursor` until `nextCursor` is null. Reply with `pull_request_respond` and the thread's `reviewThreadId`. Set `resolved: true` on a bot's thread once the reply cites the fixing commit or a disproof. Leave escalated threads and human reviewers' threads open. Read a failing check with `ci_logs`, and spend a flake's one fresh build as `ci_rerun` with that `check`. +- **Opening a PR.** `pull_request_create` is the run's PR tool. Call it with `draft: false`, and with `base` for a stacked layer. It pushes the calling thread's branch when the remote lacks commits, opens the PR, and links it to that thread. Without it, create the PR with the resolved forge (`gh` or `origin`), ready for review, never draft. The root links every PR, each stack layer included, with `link_pull_request` for one PR or `link_pull_requests` for several in one call. A child that opens a PR returns its URL and head SHA, and the root links it. - **Linking issues.** The root links every issue the run works on or files, such as the tracker issue in benny's reproduce automation, with `link_issue`, so T3 shows it beside the thread. A child that works on or files an issue returns its URL, and the root links it. - **A merged dependency PR can end the run.** T3 settles a thread at a turn end once every PR linked to it has merged. Settling ends the session and kills its background commands, such as a push through a pre-push gate. A run that merges a dependency PR in another repo before it opens its own PR is exposed. Open and link the run's own PR before the dependency PR merges. If the dependency merged first, unlink it before you end a turn that still waits on work. Call `unlink_pull_requests` with `states: ["merged"]`, then `unlink_pull_request` on any merged dependency missing from its `unlinked` list, because the call trusts T3's last known state. Link them again after the run's own PR is linked. - **Review guides.** When the root hands PRs to the user for review or merge, it reads each with `read_pull_request_guide`. Then it calls `write_pull_request_guides` once for every PR whose guide is missing or `stale`. A run takes minutes, so do not wait for it. The user reads the guide in the PR's Guide tab. Pass each PR as `repository` and `number`, because the `url` form can fail to find the project's checkout. A PR whose outcome is `failed`, for example because guides are off in T3's Source Control settings, gets no guide. Give its `detail` in the reply and go on. diff --git a/t3/contract/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/t3/contract/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 629a535..b2866bb 100644 --- a/t3/contract/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/t3/contract/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -145,7 +145,7 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", { const BackgroundWaitTool = Tool.make("t3_background_wait", { description: - "Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks. Claude/OpenCode only.", + "Keep this thread in Working while background work runs. Pass its task ID once started. Not for work left running (dev server, watcher). `waiting=false` clears. Doesn't stop tasks.", parameters: Schema.Struct({ taskIds: Schema.Array(TrimmedNonEmptyString).check( Schema.isMinLength(1), @@ -165,7 +165,7 @@ const BackgroundWaitTool = Tool.make("t3_background_wait", { // Only marks which tasks keep the thread Working; Claude Plan mode blocks tools without this. .annotate(Tool.Readonly, true) .annotate(Tool.Destructive, false) - .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWithoutBackgroundWait); const ScheduleTaskTool = Tool.make("schedule_task", { description: @@ -208,7 +208,7 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", { const RequestSecretTool = Tool.make("request_secret", { description: - 'Ask for one secret per single-line card; never combine values. Open it, don\'t offer it. Returns one-use `secretRef`, or `delivery: "file"` a file read only in its command, e.g. `adb pair "$(cat )"`. Asked how: call now. Sign-in link: `url`. Pasted secret for child/script: `value`. Never from an old thread.', + 'Ask for secrets in a private card, one value per single-line input; never combine values in one. Open it, don\'t offer it. Returns one-use `secretRef`, or `delivery: "file"` a file read only in its command, e.g. `adb pair "$(cat )"`. Asked how: call now. Sign-in link: `url`. Pasted secret for child/script: `value`. Never from an old thread.', parameters: OrchestratorMcpRequestSecretInput, success: OrchestratorMcpRequestSecretResult, failure: OrchestratorMcpFailure, diff --git a/t3/contract/apps/server/src/mcp/toolkits/project/tools.ts b/t3/contract/apps/server/src/mcp/toolkits/project/tools.ts index 57ba446..52e9b77 100644 --- a/t3/contract/apps/server/src/mcp/toolkits/project/tools.ts +++ b/t3/contract/apps/server/src/mcp/toolkits/project/tools.ts @@ -130,7 +130,7 @@ const ProjectCloneTool = Tool.make("t3_project_clone", { const ThreadLaunchTool = Tool.make("t3_thread_launch", { ...shared, description: - "Create one new top-level thread, bound to its workspace before the agent starts. Task in `message`. Omit `projectId`, model and modes to inherit yours (outside a thread, pass `projectId` or `scratch`); modes cannot exceed yours. After an error or lost reply, retry with the same `clientRequestId`. Follow it with `t3_thread_read` or `t3_thread_wait`. Mention it with its `link`.", + "Create a top-level thread in its workspace before starting. Task in `message`. Omit `projectId`, model and modes to inherit yours (outside a thread, pass `projectId` or `scratch`); modes cannot exceed yours. On error or lost reply, reuse `clientRequestId`. Follow it with `t3_thread_read` or `t3_thread_wait`. Mention it with its `link`.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, projectId: Schema.optional(ProjectId), @@ -141,6 +141,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { }), ), title: TrimmedNonEmptyString, + generateTitle: Schema.optional(Schema.Boolean), modelSelection: Schema.optional(ModelSelection), runtimeMode: Schema.optional(RuntimeMode), interactionMode: Schema.optional(ProviderInteractionMode), @@ -156,6 +157,11 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { }), ), attachments: Schema.optional(Schema.Array(McpAttachmentInput).check(Schema.isMaxLength(8))), + outputSchema: Schema.optional( + Schema.Record(Schema.String, Schema.Json).annotate({ + description: "As in `t3_thread_send`. Needs `message`.", + }), + ), clientRequestId: Schema.optional(OrchestratorMcpClientRequestId), /** Set by a linked environment launching its agent's delegated task here; ignored otherwise. */ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), diff --git a/t3/contract/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/t3/contract/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 5a4b671..71d0a28 100644 --- a/t3/contract/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/t3/contract/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -186,7 +186,6 @@ export const PullRequestToolError = Schema.Union([ PullRequestListFailedError, PullRequestWatchService.PullRequestWatchFailedError, PullRequestUnavailableError, - PullRequestWatchService.PullRequestNotOpenError, PullRequestWatchService.PullRequestWatchFromSubagentError, PullRequestProjectNotFoundError, PullRequestGuideFailedError, @@ -258,9 +257,18 @@ export const WatchPullRequestResult = Schema.Struct({ ...PullRequestIdentity, watching: Schema.Boolean, wasWatching: Schema.Boolean, + state: Schema.optional( + Schema.Literals(["merged", "closed"]).annotate({ + description: "The PR already ended, so nothing was watched.", + }), + ), + next: Schema.optional(Schema.String), }); export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; +export const alreadyEndedWatchNext = (state: "merged" | "closed") => + `This PR is already ${state}, so there is nothing to watch. Report that and end your turn.`; + export const ThreadPullRequestEntry = Schema.Struct({ ...PullRequestIdentity, source: ThreadPullRequestLinkSource, @@ -383,14 +391,14 @@ const WatchPullRequestInput = Schema.Struct({ until: Schema.optional( PullRequestWatchUntil.annotate({ description: - 'How long this thread stays working. Omit it to keep the current value; a new watch starts at "checks". "checks": until checks finish, for a PR you hand to the user. "merged": until it merges or closes or you unwatch it, when you will act on it yourself, such as merging after someone else approves.', + 'How long this thread stays working. Omit to keep the current value; a new watch starts at "checks". "checks": until checks finish, for a PR you hand to the user. "merged": until it merges, closes or is unwatched, when you act on it yourself, such as merging after approval.', }), ), }); const WatchPullRequestTool = Tool.make("watch_pull_request", { description: - "Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself.", + "Watch an open PR for this thread, linking it if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, conflicts, and once on merge or close unless you did it via CLI. Handle old comments first; only new ones wake you. After this call, end your turn. The watch stays on: do not call this again on a wake. A wake is not a merge decision. Check readiness yourself.", parameters: WatchPullRequestInput, success: WatchPullRequestResult, failure: PullRequestToolError, @@ -490,9 +498,10 @@ export const ThreadPullRequestInput = Schema.Struct({ export type ThreadPullRequestInput = typeof ThreadPullRequestInput.Type; export const PullRequestReadSection = Schema.Literals([ - "summary", + "body", "checks", - "conversation", + "threads", + "comments", "diff", ]); export type PullRequestReadSection = typeof PullRequestReadSection.Type; @@ -505,50 +514,56 @@ const ReadComment = Schema.Struct({ export const ReadPullRequestResult = Schema.Struct({ ...PullRequestIdentity, - summary: Schema.optional( - Schema.Struct({ - title: Schema.String, - body: Schema.String, - state: PullRequestState, - isDraft: Schema.Boolean, - author: Schema.NullOr(Schema.String), - headBranch: Schema.String, - baseBranch: Schema.String, - headSha: Schema.NullOr(Schema.String), - mergeability: PullRequestMergeability, - behindBy: Schema.NullOr(Schema.Int), - autoMergeEnabled: Schema.NullOr(Schema.Boolean), - additions: Schema.Int, - deletions: Schema.Int, - changedFiles: Schema.Int, - labels: Schema.Array(Schema.String), - reviewers: Schema.Array(Schema.String), + title: Schema.String, + state: PullRequestState, + isDraft: Schema.Boolean, + author: Schema.NullOr(Schema.String), + headBranch: Schema.String, + baseBranch: Schema.String, + headSha: Schema.NullOr(Schema.String), + mergeability: PullRequestMergeability, + behindBy: Schema.NullOr(Schema.Int), + autoMergeEnabled: Schema.NullOr(Schema.Boolean), + checks: Schema.Struct({ + passed: Schema.Int, + pending: Schema.Int, + failed: Schema.Array(Schema.String), + incomplete: Schema.optional(Schema.Literal(true)).annotate({ + description: "The host could not list some checks; checkRuns says which.", }), - ), - checks: Schema.optional(Schema.Array(PullRequestCheck)), + }), + unresolvedThreads: Schema.Int, + unresolvedThreadsTruncated: Schema.optional(Schema.Literal(true)).annotate({ + description: "unresolvedThreads is a lower bound.", + }), + body: Schema.optional(Schema.String), + checkRuns: Schema.optional(Schema.Array(PullRequestCheck)), conversation: Schema.optional( Schema.Struct({ - comments: Schema.Array( - Schema.Struct({ - ...ReadComment.fields, - id: Schema.String, - kind: PullRequestCommentKind, - path: Schema.NullOr(Schema.String), - reviewState: Schema.NullOr(Schema.String), - }), + reviewThreads: Schema.optional( + Schema.Array( + Schema.Struct({ + id: Schema.String, + path: Schema.String, + line: Schema.NullOr(Schema.Int), + isResolved: Schema.Boolean, + isOutdated: Schema.Boolean, + comments: Schema.Array(ReadComment), + moreComments: Schema.Boolean, + }), + ), ), - reviewThreads: Schema.Array( - Schema.Struct({ - id: Schema.String, - path: Schema.String, - line: Schema.NullOr(Schema.Int), - isResolved: Schema.Boolean, - isOutdated: Schema.Boolean, - comments: Schema.Array(ReadComment), - moreComments: Schema.Boolean, - }), + comments: Schema.optional( + Schema.Array( + Schema.Struct({ + ...ReadComment.fields, + id: Schema.String, + kind: PullRequestCommentKind, + path: Schema.NullOr(Schema.String), + reviewState: Schema.NullOr(Schema.String), + }), + ), ), - hiddenResolvedThreads: Schema.Int, truncated: Schema.Boolean, nextCursor: Schema.NullOr(Schema.String), }), @@ -609,12 +624,12 @@ export const MergePullRequestResult = Schema.Struct({ export type MergePullRequestResult = typeof MergePullRequestResult.Type; const ReadPullRequestTool = Tool.make("pull_request_read", { - description: "Read a PR's state, checks, review comments, or diff. Use instead of gh or cafe.", + description: "Read a PR's state and check counts. `include` adds detail.", parameters: Schema.Struct({ ...ThreadPullRequestInput.fields, - sections: Schema.optional( + include: Schema.optional( Schema.Array(PullRequestReadSection).annotate({ - description: "Default: summary, checks. conversation has review threads.", + description: "threads: unresolved review threads.", }), ), includeResolved: Schema.optional(Schema.Boolean), @@ -653,7 +668,7 @@ const ListPullRequestsTool = Tool.make("pull_request_list", { .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWithoutForge); const CreatePullRequestTool = Tool.make("pull_request_create", { - description: "Open a PR from this thread's pushed branch and link it, or return its open PR.", + description: "Push this thread's branch, then open its PR and link it, or return its open PR.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, title: TrimmedNonEmptyString, @@ -757,7 +772,8 @@ const ReviewPullRequestTool = Tool.make("pull_request_review", { .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWithoutForge); const MergePullRequestTool = Tool.make("pull_request_merge", { - description: "Merge a PR. Refuses if the head moved from expectedHeadSha (summary.headSha).", + description: + "Merge a PR. Refuses if the head moved from expectedHeadSha (headSha in pull_request_read).", parameters: Schema.Struct({ ...ThreadPullRequestInput.fields, expectedHeadSha: TrimmedNonEmptyString, @@ -811,8 +827,7 @@ export const RerunChecksResult = Schema.Struct({ export type RerunChecksResult = typeof RerunChecksResult.Type; const CheckLogsTool = Tool.make("ci_logs", { - description: - "Read the tail of a PR's failing check logs, or one named check's. Use instead of gh run view.", + description: "Read the tail of a PR's failing check logs, or one named check's.", parameters: Schema.Struct({ ...ThreadPullRequestInput.fields, check: Schema.optional(TrimmedNonEmptyString), diff --git a/t3/contract/apps/server/src/mcp/toolkits/thread/tools.ts b/t3/contract/apps/server/src/mcp/toolkits/thread/tools.ts index d6c9a34..9803e8b 100644 --- a/t3/contract/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/t3/contract/apps/server/src/mcp/toolkits/thread/tools.ts @@ -23,7 +23,7 @@ import { } from "@t3tools/contracts"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Schema from "effect/Schema"; -import { Tool, Toolkit } from "effect/ai"; +import { McpSchema, Tool, Toolkit } from "effect/ai"; import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts"; @@ -241,6 +241,19 @@ const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", { .annotate(Tool.Destructive, true) .annotate(Tool.OpenWorld, true); +const SubmitOutputTool = Tool.make("t3_submit_output", { + ...commandTool, + description: + "Return this turn's result as data, when the message asked for one. `json`: JSON text matching the schema it gave. A rejection says what did not fit; fix it and call again.", + // Stored on the run, which every client of the thread holds. + parameters: Schema.Struct({ json: Schema.String.check(Schema.isMaxLength(200000)) }), + success: Schema.Struct({ runId: RunId }), +}) + // It writes only the caller's own run, so a read-only or plan-mode agent can still answer. + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + export const ThreadToolkit = Toolkit.make( ScheduledTaskRunTool, ThreadSearchTool, @@ -249,4 +262,5 @@ export const ThreadToolkit = Toolkit.make( ThreadOrganizeTool, PendingRequestTool, QueueTool, + SubmitOutputTool, ); diff --git a/t3/contract/apps/server/src/provider/Drivers/ClaudeSkills.ts b/t3/contract/apps/server/src/provider/Drivers/ClaudeSkills.ts index 4fdd356..ae020bf 100644 --- a/t3/contract/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/t3/contract/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -485,9 +485,14 @@ const expandInlinePluginDirectory = Effect.fn("expandInlinePluginDirectory")(fun ); }); -/** Plugin folders Claude Code loads inline from CLAUDE_CODE_PLUGIN_DIRS, and their plugin names. */ +/** + * Plugin folders Claude Code loads inline, from --plugin-dir launch arguments and then + * CLAUDE_CODE_PLUGIN_DIRS, and their plugin names. + */ const discoverInlinePluginSkillRoots = Effect.fn("discoverInlinePluginSkillRoots")(function* ( - pluginDirectories: string | undefined, + launchArgPluginDirectories: ReadonlyArray, + environmentPluginDirectories: string | undefined, + cwd: string | undefined, enabledPlugins: ReadonlyMap, managedPluginNames: ReadonlySet, ) { @@ -497,11 +502,20 @@ const discoverInlinePluginSkillRoots = Effect.fn("discoverInlinePluginSkillRoots const roots: Array = []; const names = new Set(); const seen = new Set(); - for (const entry of (pluginDirectories ?? "").split(platform === "win32" ? ";" : ":")) { - const directory = expandHomePath(entry.trim(), home); - // Claude skips relative entries rather than resolving them against its cwd. - if (!directory || !path.isAbsolute(directory)) continue; - for (const installPath of yield* expandInlinePluginDirectory(path.resolve(directory))) { + const directories = [ + // Claude resolves a relative --plugin-dir against its cwd and expands no `~` in it. + ...launchArgPluginDirectories + .filter((directory) => directory && (cwd || path.isAbsolute(directory))) + .map((directory) => path.resolve(cwd ?? ".", directory)), + // Claude skips relative CLAUDE_CODE_PLUGIN_DIRS entries rather than resolving them. + ...(environmentPluginDirectories ?? "") + .split(platform === "win32" ? ";" : ":") + .map((entry) => expandHomePath(entry.trim(), home)) + .filter((directory) => directory && path.isAbsolute(directory)) + .map((directory) => path.resolve(directory)), + ]; + for (const directory of directories) { + for (const installPath of yield* expandInlinePluginDirectory(directory)) { if (seen.has(installPath)) continue; seen.add(installPath); const manifest = yield* readPluginManifest(installPath); @@ -717,6 +731,30 @@ export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray { + const tokens = tokenizeCliArgs(launchArgs); + const directories: string[] = []; + for (let index = 0; index < tokens.length && tokens[index] !== "--"; index++) { + const token = tokens[index]!; + if (!token.startsWith("--") || token.includes("=")) { + if (token.startsWith("--plugin-dir=")) directories.push(token.slice("--plugin-dir=".length)); + continue; + } + const next = tokens[index + 1]; + const takesNext = + next !== undefined && + (!next.startsWith("--") || claudeLaunchArgParseOptions.valueFlags.includes(token.slice(2))); + if (!takesNext) continue; + if (token === "--plugin-dir") directories.push(next); + index++; + } + return directories; +} + /** First name wins: managed skills, then user skills, then project skills. */ export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* ( config: Pick & Partial>, @@ -744,7 +782,9 @@ export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (yield* readClaudeSettingsEnv(config, cwd, env)).CLAUDE_CODE_PLUGIN_DIRS ?? env.CLAUDE_CODE_PLUGIN_DIRS; const inlinePlugins = yield* discoverInlinePluginSkillRoots( + claudeLaunchArgPluginDirectories(config.launchArgs), inlinePluginDirectories, + cwd, enabledPlugins, managedPluginNames, ); diff --git a/t3/contract/packages/contracts/src/orchestratorMcp.ts b/t3/contract/packages/contracts/src/orchestratorMcp.ts index d7c6077..e042bcf 100644 --- a/t3/contract/packages/contracts/src/orchestratorMcp.ts +++ b/t3/contract/packages/contracts/src/orchestratorMcp.ts @@ -561,6 +561,12 @@ export const OrchestratorMcpThreadSendInput = Schema.Struct({ "Start a new provider session without the thread's earlier context, like /clear. Never steers.", }), ), + outputSchema: Schema.optional( + Schema.Record(Schema.String, Schema.Json).annotate({ + description: + "JSON Schema for a result the turn must return as data, read back as `output` from `t3_thread_wait`. Never steers.", + }), + ), clientRequestId: Schema.optional(OrchestratorMcpClientRequestId), }); export type OrchestratorMcpThreadSendInput = typeof OrchestratorMcpThreadSendInput.Type; @@ -587,6 +593,12 @@ export const OrchestratorMcpThreadWaitInput = Schema.Struct({ "Also wait for its delegated and background tasks and their completions to settle. `resultRun` then names the run with its final answer.", }), ), + untilOutput: Schema.optional( + Schema.Boolean.annotate({ + description: + "Also wait for the `output` the run was asked for, which a later turn may submit.", + }), + ), }); export type OrchestratorMcpThreadWaitInput = typeof OrchestratorMcpThreadWaitInput.Type; @@ -598,6 +610,8 @@ export const OrchestratorMcpThreadWaitResult = Schema.Struct({ next: Schema.optional(OrchestratorMcpRunningTaskNext), /** With untilDelegatedWorkSettled, once settled: the run whose reply is the thread's result. */ resultRun: Schema.optional(Schema.Struct({ runId: RunId, status: OrchestrationV2RunStatus })), + /** What the run returned against the `outputSchema` it was sent with. Absent until submitted. */ + output: Schema.optional(Schema.Json), }); export type OrchestratorMcpThreadWaitResult = typeof OrchestratorMcpThreadWaitResult.Type; @@ -801,6 +815,25 @@ const PastedSecretValue = Schema.String.check( Schema.makeFilter((value: string) => value.length > 0, { expected: "a non-empty string" }), ); +const RequestSecretFields = Schema.Array( + Schema.Struct({ + name: TrimmedNonEmptyString.check(Schema.isPattern(/^[A-Za-z][A-Za-z0-9_]{0,31}$/)), + label: TrimmedNonEmptyString, + placeholder: Schema.optional(TrimmedNonEmptyString), + secret: Schema.optional(Schema.Boolean).annotate({ + description: "false shows the typed value, e.g. an email.", + }), + }), +) + .check(Schema.isMinLength(1), Schema.isMaxLength(8)) + .check( + Schema.makeFilter((fields) => + new Set(fields.map((field) => field.name)).size === fields.length + ? true + : "Field names must be unique.", + ), + ); + export const OrchestratorMcpRequestSecretInput = Schema.Struct({ label: TrimmedNonEmptyString.annotate({ description: "Card title, such as 'GitHub webhook secret'.", @@ -821,6 +854,10 @@ export const OrchestratorMcpRequestSecretInput = Schema.Struct({ delivery: Schema.optional(Schema.Literals(["secretRef", "file"])).annotate({ description: "secretRef (default) for a T3 tool; file for a command.", }), + fields: Schema.optional(RequestSecretFields).annotate({ + description: + 'Values only the user has, in one card, e.g. email + password, with delivery "file". Returns `files` by name.', + }), value: Schema.optional(PastedSecretValue).annotate({ description: "Pasted in this thread; no card.", }), @@ -848,6 +885,12 @@ export const OrchestratorMcpRequestSecretResult = Schema.Union([ "Owner-only file with the value. Read it inside commands and never print it. Deleted after 24 hours.", }), }), + Schema.Struct({ + status: Schema.Literal("saved"), + files: Schema.Record(Schema.String, Schema.String).annotate({ + description: "One file per field name, used like `file`.", + }), + }), Schema.Struct({ status: Schema.Literals(["declined", "cancelled", "timed_out"]).annotate({ description: diff --git a/t3/contract/packages/provider-core/src/server/orchestrationInstructions.ts b/t3/contract/packages/provider-core/src/server/orchestrationInstructions.ts index 4ce08d7..3f97035 100644 --- a/t3/contract/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/t3/contract/packages/provider-core/src/server/orchestrationInstructions.ts @@ -57,7 +57,7 @@ export const T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH = deviceToolInstr // ACP only: some ACP agents accept the injected MCP server but never expose // its tools, so they need the terminal transport other harnesses never use. -const T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS = `ACP fallback: if the T3 tools are absent and \`T3_ACP_MCP_NODE\` is present, call them through the terminal: \`ELECTRON_RUN_AS_NODE=1 "$T3_ACP_MCP_NODE" \${T3_ACP_MCP_ENTRYPOINT:+"$T3_ACP_MCP_ENTRYPOINT"} acp-mcp-call orchestrator_capabilities '{}'\` (\`T3_ACP_MCP_ENTRYPOINT\` is unset for a standalone executable). Delegate with \`acp-mcp-call delegate_task '{"task":"...","target":{"providerInstanceId":"...","model":"..."},"mode":"async","clientRequestId":"..."}'\`.`; +const T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS = `ACP fallback: if the T3 tools are absent and \`T3_ACP_MCP_NODE\` is present, call them through the terminal: \`ELECTRON_RUN_AS_NODE=1 "$T3_ACP_MCP_NODE" \${T3_ACP_MCP_ENTRYPOINT:+"$T3_ACP_MCP_ENTRYPOINT"} acp-mcp-call orchestrator_capabilities '{}'\` (\`T3_ACP_MCP_ENTRYPOINT\` is unset for a standalone executable). Delegate with \`acp-mcp-call delegate_task '{"task":"...","target":{"providerInstanceId":"...","model":"..."},"mode":"async","clientRequestId":"..."}'\`. On Windows, run \`T3_ACP_MCP_CALL\` instead and pipe the JSON to stdin, as in PowerShell \`'{}' | & $env:T3_ACP_MCP_CALL orchestrator_capabilities -\`, writing non-ASCII characters as \`\\uXXXX\` escapes.`; const T3_CODE_ACP_DEFAULT_MODE_INSTRUCTIONS = `## T3 Code interaction mode: Default @@ -120,17 +120,22 @@ export function t3OrchestrationPrompt(input: { readonly hasDeviceTools: boolean; readonly orchestrationDelivered: boolean; readonly deviceInstructionsDelivered: boolean; + /** Guidance for this provider's own tools, sent until `providerInstructionsDelivered`. */ + readonly providerInstructions?: string; + readonly providerInstructionsDelivered?: boolean; }): string { if (!input.hasT3Mcp) return input.prompt; - if (!input.orchestrationDelivered) { - return prependT3OrchestrationInstructions( - input.prompt, - orchestrationInstructions(input.hasDeviceTools), - ); - } - return input.hasDeviceTools && !input.deviceInstructionsDelivered - ? prependT3OrchestrationInstructions(input.prompt, T3_CODE_DEVICE_TOOL_INSTRUCTIONS) - : input.prompt; + const instructions = [ + !input.orchestrationDelivered + ? orchestrationInstructions(input.hasDeviceTools) + : input.hasDeviceTools && !input.deviceInstructionsDelivered + ? T3_CODE_DEVICE_TOOL_INSTRUCTIONS + : undefined, + input.providerInstructionsDelivered === true ? undefined : input.providerInstructions, + ].flatMap((part) => (part === undefined ? [] : [part.trim()])); + return instructions.length === 0 + ? input.prompt + : prependT3OrchestrationInstructions(input.prompt, instructions.join("\n\n")); } export function t3OrchestrationSystemPrompt( diff --git a/t3/contract/packages/provider-core/src/server/runtimeInstructions.ts b/t3/contract/packages/provider-core/src/server/runtimeInstructions.ts index 82e6466..4631485 100644 --- a/t3/contract/packages/provider-core/src/server/runtimeInstructions.ts +++ b/t3/contract/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,3 +1,5 @@ +import type { ProviderAdapterV2RuntimePolicy } from "./ProviderAdapter.ts"; + /** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */ export const PULL_REQUEST_LINKING_INSTRUCTIONS = ` Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. When pull_request_* tools are listed, use them, not gh or cafe, to read, list, open, edit, review, reply on, close, or merge PRs, and ci_logs and ci_rerun for their checks. pull_request_create links for you. @@ -12,6 +14,8 @@ export function buildRuntimeInstructions(runtime: { readonly reasoningEffort?: string | undefined; /** False when the session's system prompt already carries the linking instructions. */ readonly pullRequestLinking?: boolean; + /** Adds the folder list of a multi-folder thread. */ + readonly runtimePolicy?: Pick | undefined; }): string { const harness = toSingleLine(runtime.harness); const model = toSingleLine(runtime.model ?? ""); @@ -22,11 +26,70 @@ export function buildRuntimeInstructions(runtime: { const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : ""; const effortInfo = effort ? ` with ${effort} reasoning effort` : ""; const runtimeInfo = `In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.`; - return runtime.pullRequestLinking === false - ? runtimeInfo - : `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`; + const workspace = + runtime.runtimePolicy === undefined ? "" : buildWorkspaceInstructions(runtime.runtimePolicy); + return [ + runtimeInfo, + ...(runtime.pullRequestLinking === false ? [] : [PULL_REQUEST_LINKING_INSTRUCTIONS]), + ...(workspace === "" ? [] : [workspace]), + ].join("\n\n"); } function toSingleLine(value: string): string { return value.replaceAll(/\s+/g, " ").trim(); } + +// Codex truncates context entries over 4,000 bytes, and this block is sent as its own entry. +const WORKSPACE_INSTRUCTIONS_MAX_BYTES = 3_600; +const FOLDER_NAME_MAX_LENGTH = 64; +// Control characters and Unicode line separators would let a name or path add lines. +const LINE_BREAKING = /[\p{Cc}\p{Zl}\p{Zp}]/gu; +const textEncoder = new TextEncoder(); + +const byteLength = (value: string) => textEncoder.encode(value).length; + +/** Names come from users and disk; keep each one a short label that cannot close the block. */ +function folderLabel(name: string): string { + const label = Array.from( + name.replaceAll(LINE_BREAKING, " ").replaceAll(/[<>`]/g, " ").replaceAll(/\s+/g, " ").trim(), + ); + if (label.length === 0) return "folder"; + return label.length > FOLDER_NAME_MAX_LENGTH + ? `${label.slice(0, FOLDER_NAME_MAX_LENGTH - 1).join("")}…` + : label.join(""); +} + +const folderPath = (value: string) => + value.replaceAll(LINE_BREAKING, "?").replaceAll("<", "‹").replaceAll(">", "›"); + +/** Lists a multi-folder thread's folders. Empty for single-folder threads, so their text is unchanged. */ +export function buildWorkspaceInstructions( + runtimePolicy: Pick, +): string { + const workspace = runtimePolicy.workspace; + if (workspace === undefined || workspace.folders.length === 0) return ""; + const head = [ + "", + "This project spans several folders. Each Git repository has its own history and branches: run Git commands inside the repository you change, and commit each one separately.", + ...(runtimePolicy.cwd === null + ? [] + : [`- Your working directory: ${folderPath(runtimePolicy.cwd)}`]), + ]; + const tail = [""]; + const entries = workspace.folders.map( + (folder) => + `- ${folderLabel(folder.name)} (${folder.isGitRepository ? "Git repository" : "folder"}): ${folderPath(folder.path)}`, + ); + // Reserve room for the line that counts folders left out. + let budget = WORKSPACE_INSTRUCTIONS_MAX_BYTES - byteLength([...head, ...tail].join("\n")) - 32; + const shown: Array = []; + for (const entry of entries) { + budget -= byteLength(entry) + 1; + if (budget < 0) break; + shown.push(entry); + } + const hidden = entries.length - shown.length; + return [...head, ...shown, ...(hidden > 0 ? [`- Not listed: ${hidden} more`] : []), ...tail].join( + "\n", + ); +}