mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-28 05:57:13 +00:00
feat(peer): spawn-peer remit + rename-proof Parent UUID stamps (#1922)
* feat(cli): spawn-peer with required remit and MCP spawn_peer Machine spawn creates an empty composer; stuffing message into that JSON is stripped. Add hapi spawn-peer and MCP spawn_peer that spawn, rename, deliver via the ping-peer path, and fail closed unless the remit is on the new session. Reject message/prompt/text on machine spawn with 400. Do not auto-approve spawn_peer in default/read-only. Fixes #1509 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): reject overlong spawn-peer names before spawn Hub rename max is 255; continuing past PATCH 400 left a live session under a different title. MCP/steer copy now says the hub 400s a spawn-body remit instead of stripping it. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): wait for fresh spawn-peer child instead of resuming it Machine spawn can return while the hub row is still inactive. ping-peer then POSTed /resume, which can launch a second agent because the original spawn has no existingSessionId for runner dedupe. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): reject flavor-illegal permissionMode before spawn-peer Codex + bypassPermissions (and Pi + any mode) used to reach the runner and fail after a child existed, or silently drop the mode. Check isPermissionModeAllowedForFlavor when both agent and mode are explicit. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): treat omitted spawn-peer agent as Claude for permissionMode Hub and runner default agent to claude when spawn omits it. Validate permissionMode against that effective flavor so yolo/read-only fail closed before a child starts. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): resolve spawn-peer dir locally and archive failed children Relative --dir values were forwarded unchanged, so the runner resolved them against daemon cwd. Remit delivery failures also left the new session running, so a retry spawned a duplicate. Resolve in the caller and best-effort archive the child before rethrowing. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): verify remit before archiving a failed spawn-peer child A timed-out ping-peer POST can still land the remit. Check the transcript before archive, and only say the child was archived when the hub returns ok. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): swallow spawn-peer transcript GET errors and skip unapplied names A thrown messages GET after spawn skipped archive and leaked a live child. Treat transport errors as a miss so the verify loop can retry, then clean up. Also do not return a requested name the hub never applied. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(spawn-peer): hub peerSpawnDefaults + model/effort spawn surface Add hub settings peerSpawnDefaults (agent, permissionMode, per-flavor models) with stock claude/yolo/sonnet fallbacks. spawnPeer resolves explicit args → hub settings → stock, maps yolo to flavor equivalents, and forwards model/effort into machine spawn. Settings UI under General → Agents; MCP/CLI optional overrides. Co-authored-by: Cursor <cursoragent@cursor.com> * test(hub): use cursor-valid permission mode in peer spawn defaults test Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): teach spawn_peer that omit permissionMode means yolo MCP copy said "pass permissionMode only when the operator asked", so agents omitted it and got hub/stock whatever was stored — often approval-gated default. Clarify omit = yolo via peerSpawnDefaults/stock; pass only to tighten. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub,web): apply peerSpawnDefaults to machine spawn and New Session POST /api/machines/:id/spawn now resolves omitted agent/permissionMode/model from hub Settings, and New Session seeds from the same peerSpawnDefaults so UI create and peer spawn share one authoritative default (stock yolo). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): NewSession hub seed respects sticky prefs + QueryClient in tests Sticky localStorage last-used agent wins over hub seed; machine spawn still applies peerSpawnDefaults server-side. Tests provide QueryClientProvider. Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): mock CREATABLE_AGENT_FLAVORS for settings general peerSpawn UI Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): stabilize NewSession tests after hub peerSpawnDefaults seed Wrap remaining mounts in QueryClientProvider, pre-seed hub settings so a late useQuery resolve cannot wipe in-test model picks, and use neutral stock permission defaults in the fixture. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(spawn-peer): address tip Codex Majors for peerSpawnDefaults Preserve explicit yolo booleans on machine spawn, fail closed when hub defaults cannot load, validate permission modes against the resolved agent, remap auto-approval across flavors, and stop late hub settings from wiping New Session edits. Reject retired agents in spawn defaults and restore the CLI executable build docs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(spawn-peer): address follow-up tip Codex Majors Stop absent Yolo localStorage from beating hub defaults, track New Session edits before late hub seed, reject incompatible machine-spawn permissions, resolve MCP spawn_peer paths against the session working directory, and hide unsupported Codex safe-yolo from Settings spawn defaults. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(spawn-peer): clear tip-2 CI and follow-up Codex Majors Omit permissionMode for Pi/DSH, preserve explicit Yolo-off across delayed hub seed, fix settings test mocks for launch permission helpers, and restore unrelated CLI README lifecycle/ACP docs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(spawn-peer): tip-3 Majors for seed edits and launchable modes Skip hub agent seed after permission edits, resolve inherited modes via the launch catalog (AGY request-review fallback), preserve hub Cursor models through preference restore, and restore Codex auth README nuance. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): tip Minors for Cursor/Grok hub permission seeding Give Cursor the native permission select so Plan/Ask survive machine spawn, and re-apply Grok hub permissions after agent-init resets. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(spawn-peer): tip Minors for Cursor select and hub seed remap Map hub permission through resolvePermissionModeForFlavor, keep native Default when agent is explicit without a model, and assert Cursor Plan/Ask Mode labels. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): tip Minors for delayed hub seed and Default model Apply hub permission/model to unset fields even with a sticky agent, preserve explicitly saved auto models, and seed OpenCode/AGY selectors from hub defaults. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(spawn-peer): tip Minors for model edit sticky and clear override Mark OpenCode/AGY model picks as edited so delayed hub seed cannot overwrite them, and treat empty hub model values as clear sentinels. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(spawn-peer): tip Majors for models patch typing and remit page scan Type the models patch as NonNullable and paginate transcript verification oldest-ward so a busy child is not archived when the remit leaves page 1. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): tip Minor — keep agent after explicit model pick Do not apply a late hub default agent when the operator already chose a model; otherwise preference restore drops that selection. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(spawn-peer): tip Cursor YOLO migrate and Codex effort map Bridge Cursor's saved YOLO toggle (incl. false) into native Default over hub yolo, and send Codex/OpenCode --effort as modelReasoningEffort. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): tip Majors — scoped YOLO bridge and catalog fallback Keep unsupported saved permission modes at Default instead of hub yolo, and apply delayed YOLO migration only when the sticky bridge agent matches. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): drop rebase conflict markers in startHappyServer Both sessionDisplayRename and spawnPeer imports are required after rebasing onto upstream rename work; markers had slipped into tip. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): wrap Kimi NewSession tests in QueryClientProvider Hub settings useQuery requires a provider; upstream Kimi catalog tests rendered bare and broke after the spawn-peer rebase onto main. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(peer): rename-proof Parent UUID stamp on spawn remits Orchestrated spawn_peer / spawn-peer remits now auto-stamp a durable [title](/sessions/<uuid>) Parent chip (fail-closed in-session). MCP copy forbids inventing titles; UUID stays identity after parent rename. Refs heavygee/hapi#175 Co-authored-by: Cursor <cursoragent@cursor.com> * style(peer): plain hyphen in Parent-stamp warning and test comment Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): reject blank remit before Parent stamp Codex review on #1922: stamping first turned empty remits non-empty and bypassed the idle-session guard. Also only treat ## Parent blocks as already-present so bare /sessions citations still get the chip. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): gate New Session Create on hub defaults; require Parent chip Codex tip review on #1922: block Create while getHubSettings is pending so stock mount defaults cannot bypass restrictive hub peerSpawnDefaults; skip Parent stamp only when ## Parent already has a markdown session chip; clarify codex resume takes a native thread id. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): resolve MCP spawn cwd; Agents settings section Codex Major on #1922: spawn_peer relative directories now prefer the launcher cwd (Codex --cd), then skillLookup, then session metadata.path. Move peerSpawnDefaults UI into the unused Agents settings section. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): pass session cwd to MCP spawn_peer; Agents settings section Codex tip review on #1922: resolve relative spawn_peer directories from the launcher working directory (Codex --cd), skillLookup, then metadata.path; move peerSpawnDefaults UI into the Agents settings section. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): skip archive on unread transcript; validate startingMode after hub agent Codex tip review: do not archive a child when remit verification cannot read the transcript; run AGY/DSH remote-only startingMode checks against the resolved hub agent; update MCP bridge test expectations for workingDirectory. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): treat exhausted remit pagination as unverifiable Hitting the messages page cap with hasMore still true must not count as an observed-empty transcript — that would archive a child whose remit may still exist on older pages. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(cli): list HAPI_API_URL as optional with localhost default Codex tip review: the README had moved HAPI_API_URL under Required even though configuration defaults it to http://localhost:3006 (and settings can supply a URL). Also drop trailing whitespace flagged by git diff --check. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): re-verify empty transcript before archiving failed spawn An earlier observed-absent page plus later unread GETs must not archive a child whose remit may have landed after the first empty read. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): never auto-archive on spawnPeer failure path Timed-out remit POSTs and empty-read/archive TOCTOU races can still land work on the child. Leave the session running with its id for inspection instead of terminating an in-flight peer. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): classify empty_session from final remit verify An earlier empty transcript read must not stick as empty_session once later message GETs become unavailable — report verify_failed instead. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): recognize escaped brackets in Parent chip labels Titles with ] were escaped in the chip label but the idempotency regex stopped at the first raw bracket and re-stamped a second Parent block. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): avoid Parent chip regex backtracking on backslashes Exclude \\ from the single-char label alternative so escaped pairs have one parse path — long nonmatching backslash runs no longer explode. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(cli): MCP/CLI spawn_peer --machine for cross-host remits Wire optional machine (UUID or hostname via GET /api/machines) through MCP spawn_peer and hapi spawn-peer into existing spawnPeer({ machineId }). Skip local directory existence checks for cross-host targets to match the estate wrapper; keep fail-closed remit verify. Fixes tiann/hapi#1931 Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): reject ambiguous spawn --machine label matches Tip bot Major on #1922: hostname/displayName selectors that match more than one online runner now fail closed with ambiguous + UUID guidance. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): preserve cross-OS absolute dirs for spawn --machine path.resolve on the caller OS was rewriting foreign absolute roots (C:\… on Linux, /srv/… on Windows) before the hub spawn POST. Detect POSIX or Windows absolute paths and only resolve relative directories. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(peer): resolve spawn dirs after local vs remote is known Defer directory resolution until the target machine is selected. Remote spawns still preserve foreign absolute roots; local spawns use native path.resolve so Windows drive-less paths like \repo bind to the caller drive. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): apply delayed DSH model defaults without replacing edits * fix(web): preserve hub permission defaults across form remounts --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: weishu <twsxtd@gmail.com>
This commit is contained in:
co-authored by
Cursor
weishu
parent
dc08608fdc
commit
7f5d6b17f3
@@ -1,18 +1,18 @@
|
||||
/**
|
||||
* Kill switch for the peer-session MCP tools (`list_peers` / `inspect_peer` /
|
||||
* `ping_peer`).
|
||||
* `ping_peer` / `spawn_peer`).
|
||||
*
|
||||
* Set `HAPI_DISABLE_PEER_TOOLS=1` in the runner environment to stop wrapped
|
||||
* agents from browsing or messaging other HAPI sessions (peer pollution):
|
||||
* agents from browsing, messaging, or spawning other HAPI sessions:
|
||||
* the tools are not registered on the session MCP server, not advertised via
|
||||
* `--allowedTools` / `--tools`, and the peer steer block is dropped from
|
||||
* flavor system prompts. The core module refuses as defense in depth, so
|
||||
* `hapi ping-peer` / `inspect-peer` from inside a wrapped agent shell fails
|
||||
* `hapi ping-peer` / `inspect-peer` / `spawn-peer` from inside a wrapped agent shell fails
|
||||
* loudly instead of silently bypassing the switch. Operators who keep the
|
||||
* variable unset in their interactive shell keep full CLI access.
|
||||
*/
|
||||
|
||||
export const PEER_TOOL_NAMES = ['list_peers', 'ping_peer', 'inspect_peer'] as const;
|
||||
export const PEER_TOOL_NAMES = ['list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'] as const;
|
||||
|
||||
export function isPeerToolsDisabled(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
return ['true', '1', 'yes'].includes((env.HAPI_DISABLE_PEER_TOOLS ?? '').toLowerCase());
|
||||
|
||||
@@ -62,6 +62,26 @@ describe('resolveToolAutoApprovalDecision ping_peer', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveToolAutoApprovalDecision spawn_peer', () => {
|
||||
it.each([
|
||||
'spawn_peer',
|
||||
'mcp__hapi__spawn_peer',
|
||||
'hapi_spawn_peer',
|
||||
'Spawn Peer Session'
|
||||
])('does not auto-approve %s in default mode', (toolName) => {
|
||||
expect(resolveToolAutoApprovalDecision('default', toolName, 'call-1')).toBeNull()
|
||||
})
|
||||
|
||||
it.each([
|
||||
'spawn_peer',
|
||||
'mcp__hapi__spawn_peer',
|
||||
'hapi_spawn_peer',
|
||||
'Spawn Peer Session'
|
||||
])('does not auto-approve %s in read-only mode', (toolName) => {
|
||||
expect(resolveToolAutoApprovalDecision('read-only', toolName, 'call-1')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveToolAutoApprovalDecision inspect_peer', () => {
|
||||
it.each([
|
||||
'inspect_peer',
|
||||
|
||||
@@ -39,17 +39,20 @@ const AUTO_APPROVE_EXACT_TOOL_NAMES = new Set([
|
||||
// ACP permission requests often surface MCP tool title, not the snake_case name.
|
||||
'list peer sessions'
|
||||
]);
|
||||
// ping_peer / inspect_peer intentionally omitted from always-approve: they can
|
||||
// resume+inject into another session or read peer histories, so permission
|
||||
// modes must still gate them. Treat both as write-like in read-only so ACP
|
||||
// titles such as "Ping Peer Session" / "Inspect Peer Session" also require
|
||||
// approval. list_peers is discovery-only and is auto-approved above.
|
||||
// ping_peer / inspect_peer / spawn_peer intentionally omitted from always-approve:
|
||||
// they can resume+inject into another session, read peer histories, or create a
|
||||
// new session with an injected remit, so permission modes must still gate them.
|
||||
// Treat them as write-like in read-only so ACP titles such as "Ping Peer Session"
|
||||
// / "Inspect Peer Session" / "Spawn Peer Session" also require approval.
|
||||
// list_peers is discovery-only and is auto-approved above.
|
||||
const AUTO_APPROVE_TOOL_ID_HINTS = ['change_title', 'save_memory'];
|
||||
const SENSITIVE_TOOL_NAME_HINTS = [
|
||||
'ping_peer',
|
||||
'ping peer',
|
||||
'inspect_peer',
|
||||
'inspect peer',
|
||||
'spawn_peer',
|
||||
'spawn peer',
|
||||
];
|
||||
const AUTO_APPROVE_WRITE_TOOL_HINTS = [
|
||||
'write',
|
||||
|
||||
@@ -347,6 +347,117 @@ describe('pingPeer', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('delivers to a known sessionId without listing sessions', async () => {
|
||||
const sessionId = 'dddddddd-1111-1111-1111-111111111111'
|
||||
const http = createHttpMock({
|
||||
post: (url, body) => {
|
||||
if (url.endsWith('/api/auth')) {
|
||||
return { status: 200, data: { token: 'jwt' } }
|
||||
}
|
||||
if (url.endsWith(`/api/sessions/${sessionId}/messages`)) {
|
||||
expect(body).toEqual({ text: 'remit', localId: expect.stringMatching(/^ping-peer-/) })
|
||||
return { status: 200, data: { ok: true } }
|
||||
}
|
||||
throw new Error(`unexpected POST ${url}`)
|
||||
},
|
||||
get: (url) => {
|
||||
if (url.endsWith('/api/sessions') && !url.includes(sessionId)) {
|
||||
throw new Error('list must not be called when sessionId is known')
|
||||
}
|
||||
if (url.endsWith(`/api/sessions/${sessionId}`)) {
|
||||
return {
|
||||
status: 200,
|
||||
data: {
|
||||
session: {
|
||||
id: sessionId,
|
||||
active: true,
|
||||
metadata: { name: 'Spawned', flavor: 'cursor' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error(`unexpected GET ${url}`)
|
||||
}
|
||||
})
|
||||
|
||||
const result = await pingPeer({
|
||||
sessionId,
|
||||
message: 'remit',
|
||||
accessToken: 'tok',
|
||||
apiUrl: 'http://hub.test',
|
||||
http: http as never
|
||||
})
|
||||
expect(result).toEqual({
|
||||
sessionId,
|
||||
name: 'Spawned',
|
||||
resumed: false,
|
||||
delivery: 'accepted',
|
||||
localId: expect.stringMatching(/^ping-peer-/),
|
||||
})
|
||||
})
|
||||
|
||||
it('waitForInitialActive polls until active without posting /resume', async () => {
|
||||
const sessionId = 'eeeeeeee-1111-1111-1111-111111111111'
|
||||
let active = false
|
||||
let polls = 0
|
||||
let resumeCalls = 0
|
||||
|
||||
const http = createHttpMock({
|
||||
post: (url) => {
|
||||
if (url.endsWith('/api/auth')) {
|
||||
return { status: 200, data: { token: 'jwt' } }
|
||||
}
|
||||
if (url.endsWith(`/api/sessions/${sessionId}/resume`)) {
|
||||
resumeCalls += 1
|
||||
throw new Error('resume must not run for a just-spawned session')
|
||||
}
|
||||
if (url.endsWith(`/api/sessions/${sessionId}/messages`)) {
|
||||
expect(active).toBe(true)
|
||||
return { status: 200, data: { ok: true } }
|
||||
}
|
||||
throw new Error(`unexpected POST ${url}`)
|
||||
},
|
||||
get: (url) => {
|
||||
if (url.endsWith(`/api/sessions/${sessionId}`)) {
|
||||
polls += 1
|
||||
if (polls >= 3) {
|
||||
active = true
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
data: {
|
||||
session: {
|
||||
id: sessionId,
|
||||
active,
|
||||
metadata: { name: 'Fresh', flavor: 'claude' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error(`unexpected GET ${url}`)
|
||||
}
|
||||
})
|
||||
|
||||
const result = await pingPeer({
|
||||
sessionId,
|
||||
message: 'remit',
|
||||
waitForInitialActive: true,
|
||||
waitActiveSecs: 10,
|
||||
accessToken: 'tok',
|
||||
apiUrl: 'http://hub.test',
|
||||
http: http as never,
|
||||
now: () => nowMs,
|
||||
sleep: async (ms) => {
|
||||
sleepCalls.push(ms)
|
||||
nowMs += ms
|
||||
}
|
||||
})
|
||||
|
||||
expect(result.resumed).toBe(false)
|
||||
expect(resumeCalls).toBe(0)
|
||||
expect(sleepCalls.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('maps resume failures to resume_failed', async () => {
|
||||
const sessionId = 'deadbeef-1111-1111-1111-111111111111'
|
||||
const http = createHttpMock({
|
||||
|
||||
@@ -80,10 +80,19 @@ export type PingPeerSessionSummary = {
|
||||
}
|
||||
|
||||
export type PingPeerOptions = {
|
||||
sessionIdPrefix: string
|
||||
sessionIdPrefix?: string
|
||||
/** When set, skip list+prefix resolve and load this session directly. */
|
||||
sessionId?: string
|
||||
message: string
|
||||
deliveryMode?: PeerDeliveryMode
|
||||
waitActiveSecs?: number
|
||||
/**
|
||||
* Fresh spawn: poll until active instead of POST /resume on the first
|
||||
* inactive snapshot. Machine spawn can return before the hub row is
|
||||
* active; resume would launch a second child (no existingSessionId on
|
||||
* the original spawn, so runner dedupe does not coalesce).
|
||||
*/
|
||||
waitForInitialActive?: boolean
|
||||
apiUrl?: string
|
||||
accessToken?: string
|
||||
http?: AxiosInstance
|
||||
@@ -568,9 +577,10 @@ function getSteeringUnavailableReason(session: PingPeerSessionSummary): string |
|
||||
|
||||
export async function pingPeer(options: PingPeerOptions): Promise<PingPeerResult> {
|
||||
assertPeerToolsEnabled()
|
||||
const prefix = normalizeSessionIdPrefix(options.sessionIdPrefix ?? '')
|
||||
const knownSessionId = (options.sessionId ?? '').trim()
|
||||
const prefix = knownSessionId ? '' : normalizeSessionIdPrefix(options.sessionIdPrefix ?? '')
|
||||
const message = options.message ?? ''
|
||||
if (!prefix) {
|
||||
if (!knownSessionId && !prefix) {
|
||||
throw new PingPeerError('bad_args', 'session id prefix is required')
|
||||
}
|
||||
if (!message) {
|
||||
@@ -595,8 +605,9 @@ export async function pingPeer(options: PingPeerOptions): Promise<PingPeerResult
|
||||
const onProgress = options.onProgress
|
||||
|
||||
const jwt = await exchangeJwt(apiUrl, accessToken, http)
|
||||
const sessions = await listSessions(apiUrl, jwt, http)
|
||||
const matched = resolveSessionByPrefix(sessions, prefix)
|
||||
const matched = knownSessionId
|
||||
? await getSession(apiUrl, jwt, knownSessionId, http)
|
||||
: resolveSessionByPrefix(await listSessions(apiUrl, jwt, http), prefix)
|
||||
const name = resolvePeerSessionLabel(matched)
|
||||
onProgress?.(`resolved ${matched.id} active=${matched.active} name="${name}"`)
|
||||
|
||||
@@ -620,7 +631,13 @@ export async function pingPeer(options: PingPeerOptions): Promise<PingPeerResult
|
||||
// Prefer the list snapshot for the first resume decision, then re-check before
|
||||
// send so a flip to inactive between list and POST cannot 409 (#1195).
|
||||
if (!matched.active) {
|
||||
await ensureActive('requesting resume...')
|
||||
if (options.waitForInitialActive) {
|
||||
onProgress?.('waiting for newly spawned session to become active...')
|
||||
await waitUntilActive(apiUrl, jwt, matched.id, waitActiveSecs, http, sleep, now, onProgress)
|
||||
onProgress?.('session active')
|
||||
} else {
|
||||
await ensureActive('requesting resume...')
|
||||
}
|
||||
}
|
||||
|
||||
let live = await ensureActive('session went inactive before send; requesting resume...')
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
AmbiguousSpawnMachineError,
|
||||
isUuidMachineSelector,
|
||||
resolveSpawnMachineIdFromList,
|
||||
} from './resolveSpawnMachineId'
|
||||
|
||||
const MACHINES = [
|
||||
{
|
||||
id: '5f5a87e8-25b2-4732-ba4c-aba95f695bd7',
|
||||
metadata: { host: 'oos-linux' },
|
||||
},
|
||||
{
|
||||
id: 'f9bb3c9e-43fd-41ca-9e4f-a0b0414b9026',
|
||||
metadata: { host: 'proxmox', name: 'homelab' },
|
||||
},
|
||||
{
|
||||
id: 'Teemo',
|
||||
hostname: 'Teemo',
|
||||
metadata: { host: 'Teemo', displayName: 'windows-box' },
|
||||
},
|
||||
]
|
||||
|
||||
describe('resolveSpawnMachineIdFromList', () => {
|
||||
it('returns exact UUID id matches', () => {
|
||||
expect(resolveSpawnMachineIdFromList(
|
||||
'5f5a87e8-25b2-4732-ba4c-aba95f695bd7',
|
||||
MACHINES
|
||||
)).toBe('5f5a87e8-25b2-4732-ba4c-aba95f695bd7')
|
||||
})
|
||||
|
||||
it('passthrough UUID when not in the online list', () => {
|
||||
expect(resolveSpawnMachineIdFromList(
|
||||
'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',
|
||||
MACHINES
|
||||
)).toBe('aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee')
|
||||
})
|
||||
|
||||
it('resolves hostname via metadata.host', () => {
|
||||
expect(resolveSpawnMachineIdFromList('oos-linux', MACHINES))
|
||||
.toBe('5f5a87e8-25b2-4732-ba4c-aba95f695bd7')
|
||||
})
|
||||
|
||||
it('resolves metadata.name and displayName', () => {
|
||||
expect(resolveSpawnMachineIdFromList('homelab', MACHINES))
|
||||
.toBe('f9bb3c9e-43fd-41ca-9e4f-a0b0414b9026')
|
||||
expect(resolveSpawnMachineIdFromList('windows-box', MACHINES))
|
||||
.toBe('Teemo')
|
||||
})
|
||||
|
||||
it('resolves non-UUID machine ids by exact id', () => {
|
||||
expect(resolveSpawnMachineIdFromList('Teemo', MACHINES)).toBe('Teemo')
|
||||
})
|
||||
|
||||
it('returns null for unknown hostnames', () => {
|
||||
expect(resolveSpawnMachineIdFromList('no-such-host', MACHINES)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects ambiguous hostname / displayName matches', () => {
|
||||
const dupHosts = [
|
||||
{
|
||||
id: 'aaaaaaaa-bbbb-4ccc-8ddd-111111111111',
|
||||
metadata: { host: 'shared-lab', displayName: 'lab' },
|
||||
},
|
||||
{
|
||||
id: 'aaaaaaaa-bbbb-4ccc-8ddd-222222222222',
|
||||
metadata: { host: 'other', name: 'shared-lab' },
|
||||
},
|
||||
]
|
||||
expect(() => resolveSpawnMachineIdFromList('shared-lab', dupHosts))
|
||||
.toThrow(AmbiguousSpawnMachineError)
|
||||
expect(() => resolveSpawnMachineIdFromList('shared-lab', dupHosts))
|
||||
.toThrow(/matches 2 online runners/i)
|
||||
})
|
||||
|
||||
it('trims whitespace', () => {
|
||||
expect(resolveSpawnMachineIdFromList(' oos-linux ', MACHINES))
|
||||
.toBe('5f5a87e8-25b2-4732-ba4c-aba95f695bd7')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isUuidMachineSelector', () => {
|
||||
it('accepts RFC-shaped UUIDs', () => {
|
||||
expect(isUuidMachineSelector('5f5a87e8-25b2-4732-ba4c-aba95f695bd7')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects hostnames', () => {
|
||||
expect(isUuidMachineSelector('oos-linux')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Resolve a spawn-peer `--machine` / MCP `machine` selector to a hub machine id.
|
||||
*
|
||||
* Matches estate `hapi-spawn-peer.sh`: UUID (or exact id) passthrough; otherwise
|
||||
* hostname / metadata.host / metadata.name via GET /api/machines.
|
||||
* Label matches that hit more than one online machine fail closed (hub does
|
||||
* not enforce unique hostnames / display names).
|
||||
*/
|
||||
|
||||
export type HubMachineListEntry = {
|
||||
id?: unknown
|
||||
hostname?: unknown
|
||||
host?: unknown
|
||||
metadata?: {
|
||||
host?: unknown
|
||||
hostname?: unknown
|
||||
name?: unknown
|
||||
displayName?: unknown
|
||||
} | null
|
||||
}
|
||||
|
||||
const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/
|
||||
|
||||
export class AmbiguousSpawnMachineError extends Error {
|
||||
readonly matches: string[]
|
||||
|
||||
constructor(selector: string, matches: string[]) {
|
||||
const unique = [...new Set(matches)]
|
||||
super(
|
||||
`machine=${selector} matches ${unique.length} online runners `
|
||||
+ `(${unique.join(', ')}). Use a machine UUID instead.`
|
||||
)
|
||||
this.name = 'AmbiguousSpawnMachineError'
|
||||
this.matches = unique
|
||||
}
|
||||
}
|
||||
|
||||
function asNonEmptyString(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function machineLabelCandidates(entry: HubMachineListEntry): string[] {
|
||||
const meta = entry.metadata && typeof entry.metadata === 'object' ? entry.metadata : null
|
||||
return [
|
||||
asNonEmptyString(entry.id),
|
||||
asNonEmptyString(entry.hostname),
|
||||
asNonEmptyString(entry.host),
|
||||
asNonEmptyString(meta?.host),
|
||||
asNonEmptyString(meta?.hostname),
|
||||
asNonEmptyString(meta?.name),
|
||||
asNonEmptyString(meta?.displayName),
|
||||
].filter(Boolean)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure resolver against an already-fetched machine list.
|
||||
* Returns the machine id, or null when no match.
|
||||
* Throws AmbiguousSpawnMachineError when a non-id label matches 2+ machines.
|
||||
*/
|
||||
export function resolveSpawnMachineIdFromList(
|
||||
want: string,
|
||||
machines: HubMachineListEntry[]
|
||||
): string | null {
|
||||
const needle = want.trim()
|
||||
if (!needle) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Exact id match (UUID or non-UUID ids like "Teemo")
|
||||
for (const entry of machines) {
|
||||
const id = asNonEmptyString(entry.id)
|
||||
if (id && id === needle) {
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
// UUID-shaped selectors may target a briefly offline machine; passthrough
|
||||
// like the estate wrapper (spawn will 404 if truly unknown).
|
||||
if (UUID_RE.test(needle)) {
|
||||
return needle
|
||||
}
|
||||
|
||||
const matches: string[] = []
|
||||
for (const entry of machines) {
|
||||
const id = asNonEmptyString(entry.id)
|
||||
if (!id) continue
|
||||
const labels = machineLabelCandidates(entry)
|
||||
if (labels.some((label) => label === needle)) {
|
||||
matches.push(id)
|
||||
}
|
||||
}
|
||||
|
||||
const unique = [...new Set(matches)]
|
||||
if (unique.length > 1) {
|
||||
throw new AmbiguousSpawnMachineError(needle, unique)
|
||||
}
|
||||
if (unique.length === 1) {
|
||||
return unique[0]!
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function isUuidMachineSelector(want: string): boolean {
|
||||
return UUID_RE.test(want.trim())
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,770 @@
|
||||
/**
|
||||
* Spawn a new HAPI session with a required first user message (remit).
|
||||
*
|
||||
* Machine spawn (`POST /api/machines/:id/spawn`) creates an idle composer.
|
||||
* A spawn body with `message`/`prompt`/`text` is HTTP 400
|
||||
* (`spawn_remit_not_supported`). This module is the fail-closed path:
|
||||
* spawn → optional rename → ping-peer delivery → verify at least one
|
||||
* user message. HTTP 200 + sessionId with 0 messages is a failed spawn
|
||||
* (tiann/hapi#1509).
|
||||
*
|
||||
* Shared by `hapi spawn-peer` and MCP `spawn_peer`. Same hub JWT /
|
||||
* namespace as ping-peer. Callers must not invent parallel auth.
|
||||
*/
|
||||
|
||||
import { existsSync, statSync } from 'node:fs'
|
||||
import { posix, resolve as resolvePath, win32 } from 'node:path'
|
||||
import axios, { type AxiosInstance } from 'axios'
|
||||
import { isObject, SESSION_NAME_MAX_LENGTH } from '@hapi/protocol'
|
||||
import {
|
||||
CREATABLE_AGENT_FLAVORS,
|
||||
getPermissionModesForFlavor,
|
||||
type AgentFlavor,
|
||||
type PermissionMode
|
||||
} from '@hapi/protocol/modes'
|
||||
import {
|
||||
resolvePeerSpawnConfig,
|
||||
ResolvedPeerSpawnDefaultsSchema,
|
||||
type PeerSpawnDefaults,
|
||||
type ResolvedPeerSpawnDefaults
|
||||
} from '@hapi/protocol/peerSpawnDefaults'
|
||||
import {
|
||||
ParentStampError,
|
||||
ensureParentStamp,
|
||||
type PeerParentIdentity,
|
||||
} from '@hapi/protocol/peerParentStamp'
|
||||
import { configuration } from '@/configuration'
|
||||
import { isPeerToolsDisabled } from '@/modules/common/peerTools'
|
||||
import { getAuthToken } from '@/api/auth'
|
||||
import { buildHubRequestHeaders } from '@/api/hubExtraHeaders'
|
||||
import { readSettings } from '@/persistence'
|
||||
import {
|
||||
PingPeerError,
|
||||
extractInspectMessageSnippet,
|
||||
pingPeer
|
||||
} from '@/modules/pingPeer/pingPeer'
|
||||
import {
|
||||
AmbiguousSpawnMachineError,
|
||||
isUuidMachineSelector,
|
||||
resolveSpawnMachineIdFromList,
|
||||
type HubMachineListEntry,
|
||||
} from '@/modules/spawnPeer/resolveSpawnMachineId'
|
||||
|
||||
export type SpawnPeerErrorCode =
|
||||
| 'bad_args'
|
||||
| 'disabled'
|
||||
| 'auth_failed'
|
||||
| 'spawn_failed'
|
||||
| 'empty_session'
|
||||
| 'verify_failed'
|
||||
| 'not_found'
|
||||
| 'ambiguous'
|
||||
| 'resume_failed'
|
||||
| 'timeout'
|
||||
| 'send_failed'
|
||||
| 'apply_failed'
|
||||
|
||||
export class SpawnPeerError extends Error {
|
||||
readonly code: SpawnPeerErrorCode
|
||||
|
||||
constructor(code: SpawnPeerErrorCode, message: string) {
|
||||
super(message)
|
||||
this.name = 'SpawnPeerError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
export type SpawnPeerOptions = {
|
||||
directory: string
|
||||
message: string
|
||||
name?: string
|
||||
agent?: AgentFlavor
|
||||
model?: string
|
||||
effort?: string
|
||||
sessionType?: 'simple' | 'worktree'
|
||||
worktreeName?: string
|
||||
permissionMode?: PermissionMode
|
||||
/**
|
||||
* Already-resolved hub machine id. Prefer this in tests.
|
||||
* When omitted, falls back to `machine` then local settings.machineId.
|
||||
*/
|
||||
machineId?: string
|
||||
/**
|
||||
* Optional machine selector: UUID or hostname / metadata.host / displayName.
|
||||
* Resolved via GET /api/machines (tiann/hapi#1931).
|
||||
*/
|
||||
machine?: string
|
||||
/**
|
||||
* Local runner machine id (defaults to settings.machineId). Used to decide
|
||||
* cross-host dir checks and progress notes.
|
||||
*/
|
||||
localMachineId?: string
|
||||
waitActiveSecs?: number
|
||||
apiUrl?: string
|
||||
accessToken?: string
|
||||
/** Skip hub settings fetch (tests). */
|
||||
hubPeerSpawnDefaults?: PeerSpawnDefaults | null
|
||||
/**
|
||||
* Base directory for relative `directory` paths (MCP session cwd).
|
||||
* Absolute directories are unchanged. Defaults to process.cwd().
|
||||
*/
|
||||
cwd?: string
|
||||
/**
|
||||
* Orchestrator identity for rename-proof Parent stamp (heavygee/hapi#175).
|
||||
* When omitted, falls back to `HAPI_SESSION_ID` / `HAPI_SESSION_NAME` /
|
||||
* `HAPI_AGENT_SESSION_ID` env (in-session CLI).
|
||||
*/
|
||||
parent?: PeerParentIdentity | null
|
||||
/**
|
||||
* MCP / in-session: fail closed when parent id is missing.
|
||||
* Outside-session CLI leaves this false and warns instead.
|
||||
*/
|
||||
requireParent?: boolean
|
||||
http?: AxiosInstance
|
||||
sleep?: (ms: number) => Promise<void>
|
||||
now?: () => number
|
||||
onProgress?: (message: string) => void
|
||||
}
|
||||
|
||||
export type SpawnPeerResult = {
|
||||
sessionId: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const DEFAULT_WAIT_ACTIVE_SECS = 60
|
||||
const POLL_VERIFY_MS = 1_000
|
||||
|
||||
const AUTH_RECOVERY_HINT =
|
||||
'On a remote runner, set HAPI_API_URL to the runner hub, and set CLI_API_TOKEN ' +
|
||||
'or run `hapi auth login` to save the token. Inside a HAPI session prefer MCP ' +
|
||||
'`spawn_peer`, which uses the session CLI credentials.'
|
||||
|
||||
function defaultSleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
/** Resolve parent identity from in-session env when callers omit `parent`. */
|
||||
export function parentIdentityFromEnv(
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): PeerParentIdentity | null {
|
||||
const sessionId = (env.HAPI_SESSION_ID ?? '').trim()
|
||||
if (!sessionId) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
sessionId,
|
||||
name: (env.HAPI_SESSION_NAME ?? '').trim() || null,
|
||||
agentSessionId: (env.HAPI_AGENT_SESSION_ID ?? '').trim() || null,
|
||||
}
|
||||
}
|
||||
|
||||
function resolveApiUrl(apiUrl?: string): string {
|
||||
const raw = (apiUrl ?? configuration.apiUrl).trim().replace(/\/+$/, '')
|
||||
if (!raw) {
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
`HAPI API URL is empty. ${AUTH_RECOVERY_HINT}`
|
||||
)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
function resolveAccessToken(accessToken?: string): string {
|
||||
let token = ''
|
||||
try {
|
||||
token = (accessToken ?? getAuthToken()).trim()
|
||||
} catch {
|
||||
token = (accessToken ?? '').trim()
|
||||
}
|
||||
if (!token) {
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
`CLI_API_TOKEN is required (run \`hapi auth login\`). ${AUTH_RECOVERY_HINT}`
|
||||
)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
function authHeaders(jwt: string): Record<string, string> {
|
||||
return buildHubRequestHeaders({
|
||||
Authorization: `Bearer ${jwt}`,
|
||||
'Content-Type': 'application/json'
|
||||
})
|
||||
}
|
||||
|
||||
async function exchangeJwt(
|
||||
apiUrl: string,
|
||||
accessToken: string,
|
||||
http: AxiosInstance
|
||||
): Promise<string> {
|
||||
try {
|
||||
const response = await http.post(
|
||||
`${apiUrl}/api/auth`,
|
||||
{ accessToken },
|
||||
{
|
||||
headers: buildHubRequestHeaders({ 'Content-Type': 'application/json' }),
|
||||
timeout: 10_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
)
|
||||
const token = typeof response.data?.token === 'string' ? response.data.token : ''
|
||||
if (response.status < 200 || response.status >= 300 || !token) {
|
||||
const detail = typeof response.data?.error === 'string'
|
||||
? response.data.error
|
||||
: `HTTP ${response.status}`
|
||||
throw new SpawnPeerError(
|
||||
'auth_failed',
|
||||
`failed to exchange access token for JWT (${detail}). Hub URL: ${apiUrl}. ${AUTH_RECOVERY_HINT}`
|
||||
)
|
||||
}
|
||||
return token
|
||||
} catch (error) {
|
||||
if (error instanceof SpawnPeerError) {
|
||||
throw error
|
||||
}
|
||||
throw new SpawnPeerError(
|
||||
'auth_failed',
|
||||
`failed to exchange access token for JWT (${error instanceof Error ? error.message : String(error)}). Hub URL: ${apiUrl}. ${AUTH_RECOVERY_HINT}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchHubMachines(
|
||||
apiUrl: string,
|
||||
jwt: string,
|
||||
http: AxiosInstance
|
||||
): Promise<HubMachineListEntry[]> {
|
||||
try {
|
||||
const response = await http.get(`${apiUrl}/api/machines`, {
|
||||
headers: authHeaders(jwt),
|
||||
timeout: 10_000,
|
||||
validateStatus: () => true
|
||||
})
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
throw new SpawnPeerError(
|
||||
'spawn_failed',
|
||||
`GET /api/machines failed (HTTP ${response.status})`
|
||||
)
|
||||
}
|
||||
const payload = response.data as { machines?: unknown } | unknown
|
||||
const list = isObject(payload) && Array.isArray(payload.machines)
|
||||
? payload.machines
|
||||
: Array.isArray(payload)
|
||||
? payload
|
||||
: null
|
||||
if (!list) {
|
||||
throw new SpawnPeerError('spawn_failed', 'GET /api/machines returned no machines list')
|
||||
}
|
||||
return list as HubMachineListEntry[]
|
||||
} catch (error) {
|
||||
if (error instanceof SpawnPeerError) {
|
||||
throw error
|
||||
}
|
||||
throw new SpawnPeerError(
|
||||
'spawn_failed',
|
||||
`GET /api/machines failed (${error instanceof Error ? error.message : String(error)})`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveTargetMachineId(options: {
|
||||
machineId?: string
|
||||
machine?: string
|
||||
localMachineId: string
|
||||
apiUrl: string
|
||||
jwt: string
|
||||
http: AxiosInstance
|
||||
}): Promise<string> {
|
||||
const direct = (options.machineId ?? '').trim()
|
||||
if (direct) {
|
||||
return direct
|
||||
}
|
||||
|
||||
const selector = (options.machine ?? '').trim()
|
||||
if (selector) {
|
||||
// UUID passthrough without a list round-trip (matches estate wrapper).
|
||||
if (isUuidMachineSelector(selector)) {
|
||||
return selector
|
||||
}
|
||||
const machines = await fetchHubMachines(options.apiUrl, options.jwt, options.http)
|
||||
try {
|
||||
const resolved = resolveSpawnMachineIdFromList(selector, machines)
|
||||
if (!resolved) {
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
`no hub machine matched machine=${selector} (try UUID or hostname from GET /api/machines)`
|
||||
)
|
||||
}
|
||||
return resolved
|
||||
} catch (error) {
|
||||
if (error instanceof AmbiguousSpawnMachineError) {
|
||||
throw new SpawnPeerError('ambiguous', error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
if (options.localMachineId) {
|
||||
return options.localMachineId
|
||||
}
|
||||
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
`machineId is required (run \`hapi auth login\` / start the runner). ${AUTH_RECOVERY_HINT}`
|
||||
)
|
||||
}
|
||||
|
||||
function assertLocalSpawnDirectory(directory: string): void {
|
||||
try {
|
||||
if (!existsSync(directory) || !statSync(directory).isDirectory()) {
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
`directory not found on this host: ${directory}`
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof SpawnPeerError) {
|
||||
throw error
|
||||
}
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
`directory not found on this host: ${directory}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `value` is absolute on POSIX or Windows.
|
||||
* Used for remote spawns so caller-platform `path.resolve` does not rewrite
|
||||
* foreign absolute roots (Linux→`C:\repo`, Windows→`/srv/repo`).
|
||||
*/
|
||||
export function isCrossPlatformAbsolutePath(value: string): boolean {
|
||||
return posix.isAbsolute(value) || win32.isAbsolute(value)
|
||||
}
|
||||
|
||||
export type ResolveSpawnPeerDirectoryOptions = {
|
||||
cwd?: string
|
||||
/**
|
||||
* When true, preserve POSIX/Windows absolute roots for the target host.
|
||||
* When false (local spawn), use native `path.resolve` so Windows drive-less
|
||||
* rooted paths like `\repo` bind to the caller's current drive.
|
||||
*/
|
||||
crossHost: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve spawn `directory` for CLI/MCP after the target machine is known.
|
||||
*/
|
||||
export function resolveSpawnPeerDirectory(
|
||||
rawDirectory: string,
|
||||
options: ResolveSpawnPeerDirectoryOptions
|
||||
): string {
|
||||
const trimmed = rawDirectory.trim()
|
||||
if (!trimmed) {
|
||||
return trimmed
|
||||
}
|
||||
const cwd = options.cwd
|
||||
if (options.crossHost && isCrossPlatformAbsolutePath(trimmed)) {
|
||||
return trimmed
|
||||
}
|
||||
return cwd ? resolvePath(cwd, trimmed) : resolvePath(trimmed)
|
||||
}
|
||||
|
||||
async function fetchHubPeerSpawnDefaults(
|
||||
apiUrl: string,
|
||||
jwt: string,
|
||||
http: AxiosInstance
|
||||
): Promise<ResolvedPeerSpawnDefaults> {
|
||||
try {
|
||||
const response = await http.get(`${apiUrl}/api/hub-settings`, {
|
||||
headers: authHeaders(jwt),
|
||||
timeout: 10_000,
|
||||
validateStatus: () => true
|
||||
})
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
throw new SpawnPeerError('spawn_failed', 'Cannot load hub spawn defaults')
|
||||
}
|
||||
return ResolvedPeerSpawnDefaultsSchema.parse(
|
||||
(response.data as { peerSpawnDefaults?: unknown } | undefined)?.peerSpawnDefaults
|
||||
)
|
||||
} catch (error) {
|
||||
if (error instanceof SpawnPeerError) {
|
||||
throw error
|
||||
}
|
||||
throw new SpawnPeerError('spawn_failed', 'Cannot load valid hub spawn defaults')
|
||||
}
|
||||
}
|
||||
|
||||
function collapsedRemitNeedle(message: string): string {
|
||||
return message.replace(/\s+/g, ' ').trim().slice(0, 800)
|
||||
}
|
||||
|
||||
type RemitVerifyResult = 'found' | 'absent' | 'unavailable'
|
||||
|
||||
async function verifySessionRemit(
|
||||
apiUrl: string,
|
||||
jwt: string,
|
||||
sessionId: string,
|
||||
message: string,
|
||||
http: AxiosInstance
|
||||
): Promise<RemitVerifyResult> {
|
||||
const needle = collapsedRemitNeedle(message)
|
||||
if (!needle) {
|
||||
return 'absent'
|
||||
}
|
||||
// Paginate oldest-ward: a busy child can push the remit off the latest
|
||||
// 50-row page before verification runs. Cap pages so a broken cursor cannot
|
||||
// loop forever (50 × 40 = 2000 messages).
|
||||
const pageLimit = 50
|
||||
const maxPages = 40
|
||||
let beforeAt: number | undefined
|
||||
let beforeSeq: number | undefined
|
||||
for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {
|
||||
let response: {
|
||||
status: number
|
||||
data?: {
|
||||
messages?: unknown
|
||||
page?: {
|
||||
hasMore?: unknown
|
||||
nextBeforeAt?: unknown
|
||||
nextBeforeSeq?: unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
response = await http.get(
|
||||
`${apiUrl}/api/sessions/${encodeURIComponent(sessionId)}/messages`,
|
||||
{
|
||||
headers: authHeaders(jwt),
|
||||
params: {
|
||||
limit: pageLimit,
|
||||
...(beforeAt !== undefined && beforeSeq !== undefined
|
||||
? { beforeAt, beforeSeq }
|
||||
: {})
|
||||
},
|
||||
timeout: 20_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
)
|
||||
} catch {
|
||||
return 'unavailable'
|
||||
}
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
return 'unavailable'
|
||||
}
|
||||
const rows = Array.isArray(response.data?.messages) ? response.data.messages : []
|
||||
for (const row of rows) {
|
||||
if (!isObject(row)) continue
|
||||
const snippet = extractInspectMessageSnippet(row.content)
|
||||
if (snippet?.role === 'user' && snippet.text.includes(needle)) {
|
||||
return 'found'
|
||||
}
|
||||
}
|
||||
const page = response.data?.page
|
||||
const hasMore = page?.hasMore === true
|
||||
const nextBeforeAt = typeof page?.nextBeforeAt === 'number' ? page.nextBeforeAt : null
|
||||
const nextBeforeSeq = typeof page?.nextBeforeSeq === 'number' ? page.nextBeforeSeq : null
|
||||
if (!hasMore || nextBeforeAt === null || nextBeforeSeq === null) {
|
||||
return 'absent'
|
||||
}
|
||||
beforeAt = nextBeforeAt
|
||||
beforeSeq = nextBeforeSeq
|
||||
}
|
||||
// Page cap hit while hasMore remained true — remit may still exist older.
|
||||
// Do not treat as observed-absent (would archive a live child).
|
||||
return 'unavailable'
|
||||
}
|
||||
|
||||
export async function spawnPeer(options: SpawnPeerOptions): Promise<SpawnPeerResult> {
|
||||
if (isPeerToolsDisabled()) {
|
||||
throw new SpawnPeerError(
|
||||
'disabled',
|
||||
'peer session tools are disabled on this machine (HAPI_DISABLE_PEER_TOOLS is set)'
|
||||
)
|
||||
}
|
||||
const rawDirectory = (options.directory ?? '').trim()
|
||||
const onProgress = options.onProgress
|
||||
if (!rawDirectory) {
|
||||
throw new SpawnPeerError('bad_args', 'directory is required')
|
||||
}
|
||||
|
||||
const parent = options.parent !== undefined
|
||||
? options.parent
|
||||
: parentIdentityFromEnv()
|
||||
// Reject blank remits before Parent stamping. Stamping an empty body would
|
||||
// produce a non-empty "## Parent" remit and bypass the idle-session guard.
|
||||
const rawMessage = options.message ?? ''
|
||||
if (!rawMessage.trim()) {
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
'message is required; empty remit would create an idle session'
|
||||
)
|
||||
}
|
||||
let message: string
|
||||
try {
|
||||
const stamped = ensureParentStamp(rawMessage, parent, {
|
||||
requireParent: options.requireParent === true,
|
||||
})
|
||||
message = stamped.message
|
||||
if (stamped.stamped) {
|
||||
onProgress?.(
|
||||
`stamped Parent chip /sessions/${(parent?.sessionId ?? '').trim()}`
|
||||
)
|
||||
} else if (!(parent?.sessionId ?? '').trim()) {
|
||||
onProgress?.(
|
||||
'WARNING: no parent session id - remit unattributed '
|
||||
+ '(outside-session OK; in-session set HAPI_SESSION_ID or use MCP spawn_peer)'
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ParentStampError) {
|
||||
throw new SpawnPeerError('bad_args', error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
const requestedName = (options.name ?? '').trim()
|
||||
if (requestedName.length > SESSION_NAME_MAX_LENGTH) {
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
`name must be at most ${SESSION_NAME_MAX_LENGTH} characters (hub rename max)`
|
||||
)
|
||||
}
|
||||
|
||||
if (options.agent && !(CREATABLE_AGENT_FLAVORS as readonly string[]).includes(options.agent)) {
|
||||
throw new SpawnPeerError('bad_args', `unsupported agent: ${options.agent}`)
|
||||
}
|
||||
|
||||
const waitActiveSecs = options.waitActiveSecs ?? DEFAULT_WAIT_ACTIVE_SECS
|
||||
if (!Number.isFinite(waitActiveSecs) || waitActiveSecs <= 0) {
|
||||
throw new SpawnPeerError('bad_args', 'waitActiveSecs must be a positive number')
|
||||
}
|
||||
|
||||
const sessionType = options.sessionType ?? 'simple'
|
||||
const apiUrl = resolveApiUrl(options.apiUrl)
|
||||
const accessToken = resolveAccessToken(options.accessToken)
|
||||
const http = options.http ?? axios
|
||||
const sleep = options.sleep ?? defaultSleep
|
||||
const now = options.now ?? Date.now
|
||||
|
||||
const settings = await readSettings()
|
||||
const localMachineId = (options.localMachineId ?? settings.machineId ?? '').trim()
|
||||
const jwt = await exchangeJwt(apiUrl, accessToken, http)
|
||||
const machineId = await resolveTargetMachineId({
|
||||
machineId: options.machineId,
|
||||
machine: options.machine,
|
||||
localMachineId,
|
||||
apiUrl,
|
||||
jwt,
|
||||
http,
|
||||
})
|
||||
// Match estate hapi-spawn-peer.sh (`MACHINE != LOCAL_MACHINE`): empty local
|
||||
// settings.machineId still counts as not-equal, so explicit remote targets
|
||||
// skip the local dir check.
|
||||
const crossHost = machineId !== localMachineId
|
||||
// Resolve directory only after local vs remote is known:
|
||||
// - remote: preserve foreign absolute roots (mixed-OS --machine)
|
||||
// - local: native path.resolve so Windows `\repo` binds to caller drive
|
||||
// Relative paths always anchor here (MCP cwd / process.cwd), not runner cwd.
|
||||
const directory = resolveSpawnPeerDirectory(rawDirectory, {
|
||||
cwd: options.cwd,
|
||||
crossHost,
|
||||
})
|
||||
if (crossHost) {
|
||||
onProgress?.(
|
||||
`cross-machine spawn: local=${localMachineId || '(unset)'} target=${machineId} `
|
||||
+ `(dir must exist on TARGET)`
|
||||
)
|
||||
} else {
|
||||
assertLocalSpawnDirectory(directory)
|
||||
}
|
||||
|
||||
const hubDefaults = options.hubPeerSpawnDefaults !== undefined
|
||||
? options.hubPeerSpawnDefaults
|
||||
: await fetchHubPeerSpawnDefaults(apiUrl, jwt, http)
|
||||
const resolved = resolvePeerSpawnConfig({
|
||||
agent: options.agent,
|
||||
permissionMode: options.permissionMode,
|
||||
model: options.model,
|
||||
effort: options.effort
|
||||
}, hubDefaults)
|
||||
|
||||
// Validate explicit permission against the resolved agent (hub default when
|
||||
// agent is omitted) — not a Claude preview before settings load.
|
||||
if (
|
||||
options.permissionMode
|
||||
&& !getPermissionModesForFlavor(resolved.agent).includes(options.permissionMode)
|
||||
) {
|
||||
throw new SpawnPeerError(
|
||||
'bad_args',
|
||||
`permission mode ${options.permissionMode} is not supported by ${resolved.agent}`
|
||||
)
|
||||
}
|
||||
|
||||
const spawnBody: Record<string, unknown> = {
|
||||
directory,
|
||||
sessionType,
|
||||
agent: resolved.agent
|
||||
}
|
||||
// Pi/DSH have empty launch-permission catalogs — omit permissionMode so the
|
||||
// machine route does not 400 invalid_permission_mode on inherited default.
|
||||
if (getPermissionModesForFlavor(resolved.agent).length > 0) {
|
||||
spawnBody.permissionMode = resolved.permissionMode
|
||||
}
|
||||
if (options.worktreeName) {
|
||||
spawnBody.worktreeName = options.worktreeName
|
||||
}
|
||||
if (resolved.model) {
|
||||
spawnBody.model = resolved.model
|
||||
}
|
||||
if (resolved.effort) {
|
||||
if (resolved.agent === 'codex' || resolved.agent === 'opencode') {
|
||||
spawnBody.modelReasoningEffort = resolved.effort
|
||||
} else {
|
||||
spawnBody.effort = resolved.effort
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.(`spawning agent=${resolved.agent} permission=${resolved.permissionMode} type=${sessionType} dir=${directory}`)
|
||||
const spawnResponse = await http.post(
|
||||
`${apiUrl}/api/machines/${encodeURIComponent(machineId)}/spawn`,
|
||||
spawnBody,
|
||||
{
|
||||
headers: authHeaders(jwt),
|
||||
timeout: 60_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
)
|
||||
const spawnData = spawnResponse.data as { type?: string; sessionId?: string; message?: string; error?: string } | undefined
|
||||
const sessionId = typeof spawnData?.sessionId === 'string' ? spawnData.sessionId : ''
|
||||
if (
|
||||
spawnResponse.status < 200
|
||||
|| spawnResponse.status >= 300
|
||||
|| spawnData?.type === 'error'
|
||||
|| !sessionId
|
||||
) {
|
||||
const detail = spawnData?.message
|
||||
|| spawnData?.error
|
||||
|| (spawnData?.type === 'success' && !sessionId ? 'spawn returned no sessionId' : `HTTP ${spawnResponse.status}`)
|
||||
throw new SpawnPeerError('spawn_failed', `spawn failed: ${detail}`)
|
||||
}
|
||||
onProgress?.(`spawned ${sessionId}`)
|
||||
|
||||
let renamed = false
|
||||
if (requestedName) {
|
||||
try {
|
||||
const renameResponse = await http.patch(
|
||||
`${apiUrl}/api/sessions/${encodeURIComponent(sessionId)}`,
|
||||
{ name: requestedName },
|
||||
{
|
||||
headers: authHeaders(jwt),
|
||||
timeout: 10_000,
|
||||
validateStatus: () => true
|
||||
}
|
||||
)
|
||||
if (renameResponse.status >= 200 && renameResponse.status < 300 && renameResponse.data?.ok === true) {
|
||||
renamed = true
|
||||
onProgress?.(`renamed → ${requestedName}`)
|
||||
} else {
|
||||
onProgress?.('rename failed (continuing to deliver remit)')
|
||||
}
|
||||
} catch {
|
||||
onProgress?.('rename failed (continuing to deliver remit)')
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.(`delivering remit (${message.length} chars) via ping-peer path...`)
|
||||
let pingResult: { sessionId: string; name: string } | undefined
|
||||
let deliveryError: unknown
|
||||
try {
|
||||
pingResult = await pingPeer({
|
||||
sessionId,
|
||||
message,
|
||||
waitActiveSecs,
|
||||
waitForInitialActive: true,
|
||||
apiUrl,
|
||||
accessToken,
|
||||
http,
|
||||
sleep,
|
||||
now,
|
||||
onProgress
|
||||
})
|
||||
} catch (error) {
|
||||
deliveryError = error
|
||||
}
|
||||
|
||||
const deadline = now() + waitActiveSecs * 1000
|
||||
// Failure path never auto-archives (remit POST may still land). Poll only
|
||||
// to recover a late-visible remit; unread GETs must not look like success.
|
||||
// Classify from the *final* verify result: an earlier empty read must not
|
||||
// stick as empty_session once later transcript GETs become unavailable.
|
||||
let lastVerify: Exclude<RemitVerifyResult, 'found'> | null = null
|
||||
while (now() <= deadline) {
|
||||
const verify = await verifySessionRemit(apiUrl, jwt, sessionId, message, http)
|
||||
if (verify === 'found') {
|
||||
return {
|
||||
sessionId,
|
||||
name: renamed
|
||||
? requestedName
|
||||
: pingResult?.name || sessionId.slice(0, 8)
|
||||
}
|
||||
}
|
||||
lastVerify = verify
|
||||
if (now() >= deadline) {
|
||||
break
|
||||
}
|
||||
await sleep(POLL_VERIFY_MS)
|
||||
}
|
||||
|
||||
if (lastVerify !== 'absent') {
|
||||
throw new SpawnPeerError(
|
||||
'verify_failed',
|
||||
`could not verify remit for ${sessionId} (transcript unread); `
|
||||
+ `left child running - inspect or archive ${sessionId} before retrying spawn-peer`
|
||||
)
|
||||
}
|
||||
|
||||
// Never auto-archive on the failure path. A timed-out remit POST (or a
|
||||
// TOCTOU gap between an empty read and archive) can still land work on
|
||||
// the child; killing it would destroy an in-flight peer. Leave the id
|
||||
// for the caller to inspect / archive.
|
||||
const leaveRunning =
|
||||
`left child running - inspect or archive ${sessionId} before retrying spawn-peer`
|
||||
if (deliveryError) {
|
||||
if (deliveryError instanceof SpawnPeerError) {
|
||||
throw new SpawnPeerError(deliveryError.code, `${deliveryError.message}; ${leaveRunning}`)
|
||||
}
|
||||
if (deliveryError instanceof PingPeerError) {
|
||||
throw new SpawnPeerError(deliveryError.code, `${deliveryError.message}; ${leaveRunning}`)
|
||||
}
|
||||
throw new SpawnPeerError(
|
||||
'send_failed',
|
||||
`${deliveryError instanceof Error ? deliveryError.message : String(deliveryError)}; ${leaveRunning}`
|
||||
)
|
||||
}
|
||||
throw new SpawnPeerError(
|
||||
'empty_session',
|
||||
`session ${sessionId} still has no user message after remit delivery (empty shell); ${leaveRunning}`
|
||||
)
|
||||
}
|
||||
|
||||
export function exitCodeForSpawnPeerError(error: SpawnPeerError): number {
|
||||
switch (error.code) {
|
||||
case 'bad_args':
|
||||
case 'disabled':
|
||||
case 'auth_failed':
|
||||
case 'not_found':
|
||||
case 'ambiguous':
|
||||
return 2
|
||||
case 'spawn_failed':
|
||||
case 'resume_failed':
|
||||
return 3
|
||||
case 'timeout':
|
||||
case 'send_failed':
|
||||
case 'apply_failed':
|
||||
case 'empty_session':
|
||||
case 'verify_failed':
|
||||
return 4
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user