Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Improve automatic operation diagnostics and timeout handling
  • Loading branch information
Alanxtl committed Sep 1, 2026
commit 1d4e7262fcbae7ade583a7d427a0a223fee88cb9
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,10 @@ def _post_json(
result = json.loads(_read_response(response, deadline=request_deadline))
except HTTPError as error:
try:
error_body = error.read(_MAX_RESPONSE_BYTES + 1)
except (OSError, TimeoutError):
error_body = _read_response(error, deadline=request_deadline, chunk_bytes=1)
except TimeoutError as timeout:
raise _ServerUnavailableError from timeout
except OSError:
error_body = b""
raise _HttpStatusError(error.code, path, _decode_error_code(error_body)) from error
except TimeoutError as error:
Expand All @@ -363,14 +365,19 @@ def _request_headers(settings: ClaudeCodePluginSettings) -> dict[str, str]:
return headers


def _read_response(response: _Response, *, deadline: float) -> bytes:
def _read_response(
response: _Response,
*,
deadline: float,
chunk_bytes: int = _READ_CHUNK_BYTES,
) -> bytes:
"""Read one response under a wall-clock deadline and a hard size bound."""

content = bytearray()
while True:
_set_response_timeout(response, _remaining_time(deadline))
remaining_bytes = _MAX_RESPONSE_BYTES + 1 - len(content)
chunk = response.read(min(_READ_CHUNK_BYTES, remaining_bytes))
chunk = response.read(min(chunk_bytes, remaining_bytes))
if not chunk:
return bytes(content)
content.extend(chunk)
Expand Down
15 changes: 11 additions & 4 deletions integrations/codex/plugins/powercontext/hooks/recall.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,8 +351,10 @@ def _post_json(
result = json.loads(_read_response(response, deadline=request_deadline))
except HTTPError as error:
try:
error_body = error.read(_MAX_RESPONSE_BYTES + 1)
except (OSError, TimeoutError):
error_body = _read_response(error, deadline=request_deadline, chunk_bytes=1)
except TimeoutError as timeout:
raise _ServerUnavailableError from timeout
except OSError:
error_body = b""
raise _HttpStatusError(error.code, path, _decode_error_code(error_body)) from error
except TimeoutError as error:
Expand All @@ -373,14 +375,19 @@ def _request_headers(settings: CodexPluginSettings) -> dict[str, str]:
return headers


def _read_response(response: _Response, *, deadline: float) -> bytes:
def _read_response(
response: _Response,
*,
deadline: float,
chunk_bytes: int = _READ_CHUNK_BYTES,
) -> bytes:
"""Read one response under a wall-clock deadline and a hard size bound."""

content = bytearray()
while True:
_set_response_timeout(response, _remaining_time(deadline))
remaining_bytes = _MAX_RESPONSE_BYTES + 1 - len(content)
chunk = response.read(min(_READ_CHUNK_BYTES, remaining_bytes))
chunk = response.read(min(chunk_bytes, remaining_bytes))
if not chunk:
return bytes(content)
content.extend(chunk)
Expand Down
60 changes: 34 additions & 26 deletions integrations/dsh/plugins/powercontext/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1015,33 +1015,32 @@ const COMPATIBILITY_OR_AVAILABILITY_PATHS = new Set([
"/v1/capabilities",
"/v1/context/prepare"
]);
const AUTOMATIC_OPERATION_PATHS = new Map([
["context_prepare", "/v1/context/prepare"],
["capture_content_source", "/v1/sources/content"],
["flush_memory", "/v1/memory/flush"]
]);
function responseDiagnostic(event, outcome, error) {
return {
event,
outcome,
http_status: error.statusCode,
...error.code ? { error_code: error.code } : {}
};
}
function isDomainStatus(status) {
return status === 404 || status === 409 || status === 422;
}
function failureEvent(event, error) {
if (error instanceof ServerResponseError) {
if (error.statusCode === 401) return {
event,
outcome: "authentication_failed",
http_status: 401
};
if (error.statusCode === 404 && COMPATIBILITY_OR_AVAILABILITY_PATHS.has(error.path)) return {
event,
outcome: "version_mismatch",
http_status: 404
};
if (error.statusCode === 401) return responseDiagnostic(event, "authentication_failed", error);
if (error.statusCode === 404 && COMPATIBILITY_OR_AVAILABILITY_PATHS.has(error.path) && error.code === void 0) return responseDiagnostic(event, "version_mismatch", error);
if (error.statusCode === 503) return {
event,
outcome: "server_unavailable",
http_status: 503,
...responseDiagnostic(event, "server_unavailable", error),
recovery: "powercontext doctor"
};
if (isDomainStatus(error.statusCode)) return void 0;
return {
event,
outcome: "invalid_response",
http_status: error.statusCode
};
if (isDomainStatus(error.statusCode) && AUTOMATIC_OPERATION_PATHS.get(event) !== error.path) return void 0;
return responseDiagnostic(event, "invalid_response", error);
}
if (error instanceof TransportError) return {
event,
Expand Down Expand Up @@ -1133,6 +1132,8 @@ async function captureUserPrompt(input) {
});
return;
}
let position;
let captureStatus = 202;
try {
const result = await input.client.request("capture_content_source", {
scope_id: input.scopeId,
Expand All @@ -1146,17 +1147,24 @@ async function captureUserPrompt(input) {
turn_id: input.turnId
}
}, input.signal);
const position = result.kind === "json" ? sourcePosition(result.value) : void 0;
if (input.config.flushOnCapture && position !== void 0) await flushThrough(input.client, input.config, input.scopeId, position, input.signal);
input.log({
event: "capture_content_source",
outcome: "ok",
status: result.status
});
position = result.kind === "json" ? sourcePosition(result.value) : void 0;
captureStatus = result.status;
} catch (error) {
const diagnostic = failureEvent("capture_content_source", error);
if (diagnostic) input.log(diagnostic);
return;
}
if (input.config.flushOnCapture && position !== void 0) try {
await flushThrough(input.client, input.config, input.scopeId, position, input.signal);
} catch (error) {
const diagnostic = failureEvent("flush_memory", error);
if (diagnostic) input.log(diagnostic);
}
input.log({
event: "capture_content_source",
outcome: "ok",
status: captureStatus
});
}

//#endregion
Expand Down
20 changes: 15 additions & 5 deletions integrations/dsh/plugins/powercontext/src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ export async function captureUserPrompt(input: CaptureInput): Promise<void> {
input.log({ event: 'capture_content_source', outcome: 'skipped' })
return
}
let position: number | undefined
let captureStatus = 202
try {
const result = await input.client.request('capture_content_source', {
scope_id: input.scopeId,
Expand All @@ -80,13 +82,21 @@ export async function captureUserPrompt(input: CaptureInput): Promise<void> {
turn_id: input.turnId,
},
}, input.signal)
const position = result.kind === 'json' ? sourcePosition(result.value) : undefined
if (input.config.flushOnCapture && position !== undefined) {
await flushThrough(input.client, input.config, input.scopeId, position, input.signal)
}
input.log({ event: 'capture_content_source', outcome: 'ok', status: result.status })
position = result.kind === 'json' ? sourcePosition(result.value) : undefined
captureStatus = result.status
} catch (error) {
const diagnostic = failureEvent('capture_content_source', error)
if (diagnostic) input.log(diagnostic)
return
}

if (input.config.flushOnCapture && position !== undefined) {
try {
await flushThrough(input.client, input.config, input.scopeId, position, input.signal)
} catch (error) {
const diagnostic = failureEvent('flush_memory', error)
if (diagnostic) input.log(diagnostic)
}
}
input.log({ event: 'capture_content_source', outcome: 'ok', status: captureStatus })
}
31 changes: 25 additions & 6 deletions integrations/dsh/plugins/powercontext/src/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface DiagnosticEvent {
event: string
outcome: string
http_status?: number
error_code?: string
recovery?: string
[key: string]: unknown
}
Expand All @@ -31,21 +32,39 @@ const COMPATIBILITY_OR_AVAILABILITY_PATHS = new Set([
'/v1/context/prepare',
])

const AUTOMATIC_OPERATION_PATHS = new Map([
['context_prepare', '/v1/context/prepare'],
['capture_content_source', '/v1/sources/content'],
['flush_memory', '/v1/memory/flush'],
])

function responseDiagnostic(event: string, outcome: string, error: ServerResponseError): DiagnosticEvent {
return {
event,
outcome,
http_status: error.statusCode,
...(error.code ? { error_code: error.code } : {}),
}
}

function isDomainStatus(status: number): boolean {
return status === 404 || status === 409 || status === 422
}

export function failureEvent(event: string, error: unknown): DiagnosticEvent | undefined {
if (error instanceof ServerResponseError) {
if (error.statusCode === 401) return { event, outcome: 'authentication_failed', http_status: 401 }
if (error.statusCode === 404 && COMPATIBILITY_OR_AVAILABILITY_PATHS.has(error.path)) {
return { event, outcome: 'version_mismatch', http_status: 404 }
if (error.statusCode === 401) return responseDiagnostic(event, 'authentication_failed', error)
if (error.statusCode === 404 && COMPATIBILITY_OR_AVAILABILITY_PATHS.has(error.path) && error.code === undefined) {
return responseDiagnostic(event, 'version_mismatch', error)
}
if (error.statusCode === 503) {
return { event, outcome: 'server_unavailable', http_status: 503, recovery: 'powercontext doctor' }
return {
...responseDiagnostic(event, 'server_unavailable', error),
recovery: 'powercontext doctor',
}
}
if (isDomainStatus(error.statusCode)) return undefined
return { event, outcome: 'invalid_response', http_status: error.statusCode }
if (isDomainStatus(error.statusCode) && AUTOMATIC_OPERATION_PATHS.get(event) !== error.path) return undefined
return responseDiagnostic(event, 'invalid_response', error)
}
if (error instanceof TransportError) {
return { event, outcome: 'server_unavailable', recovery: 'powercontext doctor' }
Expand Down
42 changes: 42 additions & 0 deletions integrations/dsh/plugins/powercontext/tests/diagnostics.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,54 @@ describe('host-visible diagnostic classification', () => {
}))).toBeUndefined()
})

it('keeps automatic domain failures visible at their actual endpoints', () => {
const automaticOperations = [
['context_prepare', '/v1/context/prepare'],
['capture_content_source', '/v1/sources/content'],
['flush_memory', '/v1/memory/flush'],
] as const
const failures = [
[404, 'not_found'],
[409, 'conflict'],
[422, 'invalid_request'],
] as const

for (const [event, path] of automaticOperations) {
for (const [statusCode, code] of failures) {
expect(failureEvent(event, new ServerResponseError({
statusCode,
path,
code,
}))).toEqual({
event,
outcome: 'invalid_response',
http_status: statusCode,
error_code: code,
})
}
}
})

it('does not emit availability diagnostics for direct domain errors', () => {
for (const statusCode of [404, 409, 422]) {
expect(failureEvent('tool_call', new ServerResponseError({
statusCode,
path: '/v1/memory/entries/get',
code: statusCode === 404 ? 'memory_not_found' : statusCode === 409 ? 'conflict' : 'invalid_request',
}))).toBeUndefined()
}
})

it('does not treat a coded compatibility response as a version mismatch', () => {
expect(failureEvent('context_prepare', new ServerResponseError({
statusCode: 404,
path: '/v1/context/prepare',
code: 'invalid_request',
}))).toEqual({
event: 'context_prepare',
outcome: 'invalid_response',
http_status: 404,
error_code: 'invalid_request',
})
})
})
Loading