Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion .claude/skills/env-reference/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ by the read-only cron-liveness check.

### Human Input and Web Push

- `HUMAN_INPUT_TIMEOUT_MS` — Initial needs-input response window (default: `7200000`)
- The question window is the admin setting `inbox.questionTimeoutMinutes` (slice G); the three `HUMAN_INPUT_*` variables below apply only to questions asked before it, held as attention markers
- `HUMAN_INPUT_ESCALATION_FRACTIONS` — Comma-separated reminder points within the initial window (default: `0.25,0.75`)
- `HUMAN_INPUT_UNDELIVERED_GRACE_MS` — Extension when no push delivery was confirmed (default: `7200000`)
- `HUMAN_INPUT_MAX_WAIT_MS` — Hard maximum needs-input marker lifetime (default: `86400000`)
Expand Down
2 changes: 0 additions & 2 deletions .github/workflows/deploy-reusable.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,6 @@ jobs:
CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS: ${{ vars.CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS }}
TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS: ${{ vars.TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS }}
TASK_RUNNER_BOOT_MAX_REPLACEMENTS: ${{ vars.TASK_RUNNER_BOOT_MAX_REPLACEMENTS }}
HUMAN_INPUT_TIMEOUT_MS: ${{ vars.HUMAN_INPUT_TIMEOUT_MS }}
HUMAN_INPUT_ESCALATION_FRACTIONS: ${{ vars.HUMAN_INPUT_ESCALATION_FRACTIONS }}
HUMAN_INPUT_UNDELIVERED_GRACE_MS: ${{ vars.HUMAN_INPUT_UNDELIVERED_GRACE_MS }}
HUMAN_INPUT_MAX_WAIT_MS: ${{ vars.HUMAN_INPUT_MAX_WAIT_MS }}
Expand Down Expand Up @@ -1901,7 +1900,6 @@ jobs:
CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS: ${{ vars.CLOUD_INIT_CERT_REQUEST_TIMEOUT_SECONDS }}
TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS: ${{ vars.TASK_RUNNER_FIRST_HEARTBEAT_TIMEOUT_MS }}
TASK_RUNNER_BOOT_MAX_REPLACEMENTS: ${{ vars.TASK_RUNNER_BOOT_MAX_REPLACEMENTS }}
HUMAN_INPUT_TIMEOUT_MS: ${{ vars.HUMAN_INPUT_TIMEOUT_MS }}
HUMAN_INPUT_ESCALATION_FRACTIONS: ${{ vars.HUMAN_INPUT_ESCALATION_FRACTIONS }}
HUMAN_INPUT_UNDELIVERED_GRACE_MS: ${{ vars.HUMAN_INPUT_UNDELIVERED_GRACE_MS }}
HUMAN_INPUT_MAX_WAIT_MS: ${{ vars.HUMAN_INPUT_MAX_WAIT_MS }}
Expand Down
1 change: 0 additions & 1 deletion apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -1280,7 +1280,6 @@ INFOMANIAK_IP_POLL_INTERVAL_MS=3000
# NOTIFICATION_PROGRESS_BATCH_WINDOW_MS=300000 # Batch window for progress notifications (5 min)
# NOTIFICATION_DEDUP_WINDOW_MS=60000 # Dedup window for task_complete notifications (60s)
# NOTIFICATION_FULL_BODY_LENGTH=5000 # Max chars stored as fullMessage in notification metadata
# HUMAN_INPUT_TIMEOUT_MS=7200000 # Initial needs-input response window (2h)
# HUMAN_INPUT_ESCALATION_FRACTIONS=0.25,0.75 # Reminder points within the initial window
# HUMAN_INPUT_UNDELIVERED_GRACE_MS=7200000 # Extension without confirmed push delivery (2h)
# HUMAN_INPUT_MAX_WAIT_MS=86400000 # Hard needs-input marker lifetime (24h)
Expand Down
29 changes: 29 additions & 0 deletions apps/api/src/db/migrations/0247_asks_questions.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
-- Inbox slice G (idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9): a question an agent asks with
-- request_human_input is one `asks` row (kind 'question') instead of a ProjectData attention
-- marker. These columns carry what the marker carried for the question's reminders and expiry
-- (`apps/api/src/services/inbox/sweep.ts`):
-- source_workspace_id the asking agent's workspace (the expiry outcome stops its task run)
-- category the request_human_input category
-- notification_id the notification sent for it (reminders resend its push; expiry
-- checks its delivery receipt)
-- next_escalation_at next reminder, NULL when none is left
-- escalation_count reminders sent
-- max_expires_at hard limit for extending an ask whose push was never delivered
--
-- Additive only: nullable columns, one integer column with a default, two partial indexes.
-- Existing rows (reviews, tasks, errors filed since slice A) keep NULL / 0 and are unaffected:
-- the reminder sweep selects only rows with next_escalation_at set.
ALTER TABLE asks ADD COLUMN source_workspace_id TEXT;
ALTER TABLE asks ADD COLUMN category TEXT;
ALTER TABLE asks ADD COLUMN notification_id TEXT;
ALTER TABLE asks ADD COLUMN next_escalation_at INTEGER;
ALTER TABLE asks ADD COLUMN escalation_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE asks ADD COLUMN max_expires_at INTEGER;

-- Due reminders.
CREATE INDEX idx_asks_open_escalation ON asks (next_escalation_at)
WHERE status = 'open' AND next_escalation_at IS NOT NULL;
-- Open questions per project and chat: the chat list, the check-in hold and the stall guard
-- read only these rows (`packages/worker-core/src/question-asks.ts`).
CREATE INDEX idx_asks_open_question ON asks (project_id, source_session_id, created_at)
WHERE kind = 'question' AND status = 'open';
1 change: 0 additions & 1 deletion apps/api/src/durable-objects/project-data/attention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@
// worker's existing importers are unchanged.
export {
ATTENTION_ARCHIVE_CLAIM,
computeHumanInputSchedule,
parseAttentionOptions,
} from '@simple-agent-manager/project-data';
1 change: 0 additions & 1 deletion apps/api/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -992,7 +992,6 @@ export interface Env
ORCHESTRATOR_STOP_CAS_MAX_ATTEMPTS?: string; // Max task-status CAS attempts after a hard stop (default: 2)
ORCHESTRATOR_MESSAGE_MAX_LENGTH?: string; // Max length for injected messages to child agents (default: 32768)
// Attention markers
HUMAN_INPUT_TIMEOUT_MS?: string; // Attention marker expiry for needs_input (default: 7200000 = 2 hours)
HUMAN_INPUT_ESCALATION_FRACTIONS?: string; // Comma-separated fractions of initial window (default: 0.25,0.75)
HUMAN_INPUT_UNDELIVERED_GRACE_MS?: string; // Extension without confirmed delivery (default: 7200000)
HUMAN_INPUT_MAX_WAIT_MS?: string; // Hard marker residence limit (default: 86400000)
Expand Down
108 changes: 100 additions & 8 deletions apps/api/src/routes/chat-attention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/
import { HUMAN_INPUT_CATEGORIES, type HumanInputCategory } from '@simple-agent-manager/shared';
import { drizzle } from 'drizzle-orm/d1';
import type { Hono } from 'hono';
import type { Context, Hono } from 'hono';

import * as schema from '../db/schema';
import {
Expand All @@ -28,6 +28,12 @@ import {
import { parseOptionalBody, ResolveAttentionAnswerSchema } from '../schemas';
import { authorizeAgentWake } from '../services/agent-wake-authorization';
import { readAskContext } from '../services/inbox/ask-context';
import {
answerQuestionAsk,
loadQuestionAsk,
type QuestionAsk,
questionAskRequestState,
} from '../services/inbox/question-asks';
import * as projectDataService from '../services/project-data';
import { recordSharedSessionAnswer } from '../services/session-access';
import { preparePromptForLiveAgent, sendPreparedPromptToLiveAgent } from './chat-prompt-forward';
Expand All @@ -45,6 +51,27 @@ function parseAttentionCategory(metadata: string | null): HumanInputCategory | n
}
}

/**
* Whether the viewer may answer the agent in this chat: the owner, or an active grantee whose
* owner can still write, holding `task:write` themselves. One rule for a question held as a
* marker and one held in `asks`.
*/
async function isChatWriter(
db: ReturnType<typeof drizzle<typeof schema>>,
projectId: string,
role: string,
access: { role?: string | null; ownerUserId?: string | null; grant?: unknown }
): Promise<boolean> {
return (
Boolean(access.ownerUserId) &&
projectRoleHasCapability(role, 'task:write') &&
(access.role === 'owner' ||
(access.role === 'grantee' &&
Boolean(access.grant) &&
(await hasProjectCapability(db, projectId, access.ownerUserId ?? '', 'task:write'))))
);
}

/**
* One attention marker with what this viewer may do with it. Shared by the attention read below
* and the inbox (`services/inbox/port.ts`), so both answer "can this person answer?" the same way.
Expand All @@ -65,13 +92,7 @@ export async function loadAttentionForViewer(
markerId,
userId
);
const writer =
Boolean(access.ownerUserId) &&
projectRoleHasCapability(membership.role, 'task:write') &&
(access.role === 'owner' ||
(access.role === 'grantee' &&
Boolean(access.grant) &&
(await hasProjectCapability(db, projectId, access.ownerUserId ?? '', 'task:write'))));
const writer = await isChatWriter(db, projectId, membership.role, access);
return {
canRead:
Boolean(session) && access.found && projectRoleHasCapability(membership.role, 'task:read'),
Expand All @@ -82,6 +103,67 @@ export async function loadAttentionForViewer(
};
}

/**
* The chat card's read of a question held in D1 `asks`, in the shape a marker read had. Who may
* read and answer is decided as for a marker: any reader of the chat reads it, a writer of the
* chat (owner, or a grantee whose owner can still write) answers it.
*/
async function questionAskAttentionResponse(
c: Context<{ Bindings: Env }>,
ask: QuestionAsk,
role: string,
userId: string
) {
const db = drizzle(c.env.DATABASE, { schema });
const { session, access } = await projectDataService.getSessionAccess(
c.env,
ask.projectId,
ask.sessionId,
userId
);
if (!session || !access.found || !projectRoleHasCapability(role, 'task:read'))
throw errors.notFound('Chat session');
const writer = await isChatWriter(db, ask.projectId, role, access);
const now = Date.now();
const state = questionAskRequestState(ask, now);
const context =
c.req.query('context') === 'true'
? await readAskContext(c.env, {
projectId: ask.projectId,
sessionId: ask.sessionId,
askedAt: ask.createdAt,
requestedLimit: Number(c.req.query('limit')),
})
: null;
return {
request: {
id: ask.id,
reason: ask.reason,
options: ask.options,
category: ask.category,
createdAt: ask.createdAt,
resolvedAt: state.resolvedAt,
resolvedAnswer: state.resolvedAnswer,
expired: state.expired,
canAnswer: ask.status === 'open' && !state.expired && writer,
},
session: {
id: ask.sessionId,
topic: typeof session.topic === 'string' ? session.topic : null,
},
messages: (context?.before ?? []).map((message) => ({
id: message.id,
sessionId: ask.sessionId,
role: message.role,
content: message.content,
createdAt: message.createdAt,
toolMetadata: null,
truncated: message.truncated,
})),
since: context?.since ?? null,
};
}

export function registerChatAttentionRoute(chatRoutes: Hono<{ Bindings: Env }>): void {
// Read-only: no runtime contact or whole-conversation fetch. Context is opt-in.
chatRoutes.get('/:sessionId/attention/:markerId', async (c) => {
Expand All @@ -93,6 +175,9 @@ export function registerChatAttentionRoute(chatRoutes: Hono<{ Bindings: Env }>):
const { membership } = await requireActiveProjectMembership(db, projectId, userId);
if (!projectRoleHasCapability(membership.role, 'task:read'))
throw errors.forbidden('Project capability is required');
// A question asked since inbox slice G is an `asks` row; one asked before is a marker.
const ask = await loadQuestionAsk(c.env, projectId, sessionId, markerId);
if (ask) return c.json(await questionAskAttentionResponse(c, ask, membership.role, userId));
const { session, marker, writer, canRead } = await loadAttentionForViewer(
c.env,
projectId,
Expand Down Expand Up @@ -187,6 +272,13 @@ export async function answerAttention(

if (!answer) throw markRejectedBeforeEffects(errors.badRequest('answer is required'));

// A question asked since inbox slice G is an `asks` row: one compare-and-set, then a durable
// prompt (`services/inbox/question-asks.ts`). One asked before is still a marker, below.
const ask = await loadQuestionAsk(env, projectId, sessionId, markerId);
if (ask) {
return answerQuestionAsk(env, { ask, answer, userId, authorization: { writer, wake } });
}

const prepared = await projectDataService.prepareAttentionAnswer(
env,
projectId,
Expand Down
66 changes: 38 additions & 28 deletions apps/api/src/routes/mcp/human-input-tool.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/**
* MCP request_human_input — records a user decision request as a durable
* attention marker and notifies the user. The tool call itself is non-blocking.
* MCP request_human_input — files the question as one D1 `asks` row (kind `question`, inbox slice
* G, idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9) and notifies the user. The tool call itself is non-blocking.
*/
import { OperationError } from '@simple-agent-manager/operations';
import type { HumanInputCategory } from '@simple-agent-manager/shared';
import {
HUMAN_INPUT_CATEGORIES,
Expand All @@ -10,11 +11,10 @@ import {
MAX_HUMAN_INPUT_OPTIONS_COUNT,
} from '@simple-agent-manager/shared';

import { computeHumanInputSchedule } from '../../durable-objects/project-data/attention';
import type { Env } from '../../env';
import { log } from '../../lib/logger';
import { fileQuestionAsk, linkQuestionNotification } from '../../services/inbox/question-asks';
import * as notificationService from '../../services/notification';
import * as projectDataService from '../../services/project-data';
import {
INTERNAL_ERROR,
INVALID_PARAMS,
Expand Down Expand Up @@ -49,7 +49,14 @@ export async function handleRequestHumanInput(
}

// Sanitize context: strip null bytes, Unicode bidi overrides, and C0/C1 control chars (except \n, \t)
const sanitizedContext = sanitizeUserInput(context.trim());
const sanitizedContext = sanitizeUserInput(context.trim()).trim();
if (!sanitizedContext) {
return jsonRpcError(
requestId,
INVALID_PARAMS,
'context is required and must be a non-empty string'
);
}

// Validate category if provided
let category: HumanInputCategory | null = null;
Expand Down Expand Up @@ -78,7 +85,9 @@ export async function handleRequestHumanInput(
}
options = (params.options as string[])
.slice(0, MAX_HUMAN_INPUT_OPTIONS_COUNT)
.map((o) => sanitizeUserInput(o).slice(0, MAX_HUMAN_INPUT_OPTION_LENGTH));
.map((o) => sanitizeUserInput(o).trim().slice(0, MAX_HUMAN_INPUT_OPTION_LENGTH))
// An option that is empty once cleaned cannot be picked; leave it out.
.filter((o) => o.length > 0);
if (options.length === 0) options = null;
}

Expand Down Expand Up @@ -124,25 +133,31 @@ export async function handleRequestHumanInput(
);
}

const schedule = computeHumanInputSchedule(env);
let marker: Awaited<ReturnType<typeof projectDataService.createAttentionMarker>>;
let question: Awaited<ReturnType<typeof fileQuestionAsk>>;
try {
marker = await projectDataService.createAttentionMarker(env, tokenData.projectId, {
question = await fileQuestionAsk(env, {
projectId: tokenData.projectId,
sessionId,
taskId: tokenData.taskId,
workspaceId: tokenData.workspaceId,
kind: 'needs_input',
source: 'request_human_input',
notificationUserId: tokenData.userId,
reason: sanitizedContext,
metadata: category || options ? JSON.stringify({ category, options }) : null,
...schedule,
userId: tokenData.userId,
context: sanitizedContext,
category,
options,
});
} catch (err) {
log.error('mcp.request_human_input.attention_marker_failed', {
log.error('mcp.request_human_input.ask_failed', {
taskId: tokenData.taskId,
error: err instanceof Error ? err.message : String(err),
});
// The per-chat cap and length limits are the inbox's; say which one the agent hit.
if (err instanceof OperationError && ['rate_limited', 'invalid_input'].includes(err.code)) {
return jsonRpcError(requestId, INVALID_PARAMS, err.message);
}
// A shape the inbox refuses: the agent can fix its call (the details stay in the log).
if (err instanceof Error && err.name === 'ValiError') {
return jsonRpcError(requestId, INVALID_PARAMS, 'Human input request is not valid');
}
return jsonRpcError(
requestId,
INTERNAL_ERROR,
Expand All @@ -163,22 +178,16 @@ export async function handleRequestHumanInput(
category,
options,
sessionId,
attentionMarkerId: marker.id,
attentionMarkerId: question.id,
});
notificationScheduled = notification.id !== 'suppressed';
if (notificationScheduled) {
await projectDataService.linkAttentionNotification(
env,
tokenData.projectId,
marker.id,
tokenData.userId,
notification.id
);
await linkQuestionNotification(env, tokenData.projectId, question.id, notification.id);
}
} catch (err) {
log.warn('mcp.request_human_input.notification_failed', {
taskId: tokenData.taskId,
markerId: marker.id,
askId: question.id,
error: err instanceof Error ? err.message : String(err),
});
}
Expand All @@ -191,13 +200,14 @@ export async function handleRequestHumanInput(
hasOptions: options !== null,
});

// JSON so the chat can render this call as an answerable card: the card reads the question
// from the attention marker by ID (see HumanInputCard in apps/web), never from chat text.
// JSON so the chat can render this call as an answerable card: the card reads the question by
// ID through the attention route (see HumanInputCard in apps/web), never from chat text. The ID
// is the `asks` row's; the route reads it there (`routes/chat-attention.ts`).
const payload = {
message: notificationScheduled
? 'Human input request recorded. Notification delivery has been scheduled. You may continue working or end your turn.'
: 'Human input request recorded, but notification delivery was not scheduled. SAM will keep the task alive while waiting for delivery. You may continue working.',
humanInputRequest: { id: marker.id, sessionId },
humanInputRequest: { id: question.id, sessionId },
notificationScheduled,
};
return jsonRpcSuccess(requestId, {
Expand Down
Loading
Loading