> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 큐·스케줄·작업

> SessionRpc로 큐, 스케줄, 백그라운드 작업을 다루는 사용 예시입니다.

## 큐·스케줄·작업

대상: SessionRpc (Session에 연결된 세션 단위 작업)

RPC 전체 개요와 페이지 목록은 [RPC](https://kawax.biz/ko/packages/laravel-copilot-sdk/rpc.md)를 참조하세요.

```php theme={null}
// queue: 큐에 쌓인 사용자 대상 항목 확인·관리
$pending = $session->rpc()->queue()->pendingItems();
// $pending->items - QueuePendingItems 의 배열
// $pending->items[0]->kind - QueuePendingItemsKind(Command / Message)

$removed = $session->rpc()->queue()->removeMostRecent();
// $removed->removed - 가장 최근 항목을 삭제했는지 여부

$session->rpc()->queue()->clear();

// 지정 위치에 항목 삽입(position 은 0부터 시작)
use Revolution\Copilot\Types\Rpc\QueueInsertAtRequest;
use Revolution\Copilot\Types\Rpc\QueueInsertMessage;

$queue = $session->rpc()->queue();
$inserted = $queue->insertAt(new QueueInsertAtRequest(
    position: 0,
    message: new QueueInsertMessage(prompt: 'Review the changes'),
));
// $inserted->id - 삽입된 항목의 ID

$queue->moveItem(['id' => $inserted->id, 'toPosition' => 1]);
$duplicated = $queue->duplicateAt(['id' => $inserted->id]);
$queue->updateText(['id' => $duplicated->id, 'prompt' => 'Review and test the changes']);
$removedAt = $queue->removeAt(['id' => $duplicated->id]);
// $removedAt->removed - 항목을 삭제했는지 여부

$sent = $queue->sendNow(['id' => $inserted->id]);
// $sent->steered - 실행 중인 턴으로 전송되었는지 여부

// 드레인을 일시 중지한다. 일시 중지는 자동으로 해제되지 않으므로 반드시 false 로 재개한다
$queue->setDrainPaused(['paused' => true]);
$queue->setDrainPaused(['paused' => false]);

// schedule (experimental: 예약된 프롬프트 관리)
$schedule = $session->rpc()->schedule()->list();
// $schedule->entries - ScheduleEntry 의 배열

use Revolution\Copilot\Types\Rpc\ScheduleStopRequest;

$stopped = $session->rpc()->schedule()->stop(new ScheduleStopRequest(id: 1));
// $stopped->stopped - 중지에 성공했는지 여부

// tasks (experimental: 백그라운드 작업 관리)
// 에이전트 작업을 시작하고 ID 를 가져옴
use Revolution\Copilot\Types\Rpc\TasksStartAgentRequest;

$result = $session->rpc()->tasks()->startAgent(new TasksStartAgentRequest(
    agentType: 'explore',
    prompt: 'Search for all TODO comments in the codebase',
    name: 'todo-search',
    description: 'Find TODO items', // 선택 사항
    model: 'gpt-4o', // 선택 사항
));
// $result->agentId - 백그라운드 작업의 ID

// 현재 작업 목록 가져오기
$list = $session->rpc()->tasks()->list();
// $list->tasks - TaskAgentInfo, TaskShellInfo, TaskClientInfo 의 배열

// 분리된 셸의 출력을 커서로 증분 읽기
use Revolution\Copilot\Types\Rpc\TasksReadOutputRequest;

$cursor = null;
do {
    $output = $session->rpc()->tasks()->readOutput(new TasksReadOutputRequest(
        id: 'shell-1',
        cursor: $cursor,
        waitMs: 1000,
    ));
    echo $output->text;
    $cursor = $output->cursor;
} while ($output->exit === null);
// $output->exit->status - 작업의 종료 상태
// $output->exit->exitCode - 프로세스 종료 코드(nullable)

// 1회 읽기는 최대 64 KiB. waitMs 는 기본값 0, 최대 30000ms.
// stdout 과 stderr 는 통합된다. 커서가 무효가 된 경우 커서 없이 다시 읽는다.

// 애플리케이션 소유 작업을 태스크로 등록
use Revolution\Copilot\Types\Rpc\TasksRegisterRequest;

$registered = $session->rpc()->tasks()->register(new TasksRegisterRequest(
    clientTaskId: 'import-123',
    description: 'Import customer data',
    cancellable: true,
    displayName: 'Customer import', // 선택 사항
));
// $registered->task->id - CLI 가 할당한 작업 ID
// $registered->created / $registered->reclaimed - 새로 생성·고립된 작업의 재취득 상태

// 클라이언트 소유 작업의 진행 상황 업데이트
use Revolution\Copilot\Enums\TaskClientActiveStatus;
use Revolution\Copilot\Enums\TaskClientUpdateKind;
use Revolution\Copilot\Types\Rpc\TaskClientUpdate;
use Revolution\Copilot\Types\Rpc\TasksUpdateRequest;

$updated = $session->rpc()->tasks()->update(new TasksUpdateRequest(
    id: $registered->task->id,
    sequence: 1,
    update: new TaskClientUpdate(
        kind: TaskClientUpdateKind::Progress,
        status: TaskClientActiveStatus::Running,
        phase: 'importing',
        percentage: 25,
    ),
));
// sequence 는 업데이트할 때마다 증가시킨다

// 완료 보고
$completed = $session->rpc()->tasks()->update(new TasksUpdateRequest(
    id: $registered->task->id,
    sequence: 2,
    update: new TaskClientUpdate(
        kind: TaskClientUpdateKind::Completed,
        result: ['imported' => 100],
    ),
));

// 작업 진행 상황 가져오기(추적되지 않는 경우 null)
$progress = $session->rpc()->tasks()->getProgress(['id' => $registered->task->id])->progress;
// TaskAgentProgress, TaskClientProgress, TaskShellProgress 또는 null

// 분리된 셸의 상태를 갱신하고 백그라운드 작업 완료를 기다림
$session->rpc()->tasks()->refresh();
$session->rpc()->tasks()->waitForPending();

// 현재 백그라운드로 전환할 수 있는 작업을 가져오거나, 그 작업을 즉시 백그라운드로 전환
$promotable = $session->rpc()->tasks()->getCurrentPromotable()->task;
$promotedCurrent = $session->rpc()->tasks()->promoteCurrentToBackground()->task;

// 작업을 백그라운드 모드로 전환(동기 대기 해제)
use Revolution\Copilot\Types\Rpc\TasksPromoteToBackgroundRequest;

$promoted = $session->rpc()->tasks()->promoteToBackground(
    new TasksPromoteToBackgroundRequest(id: $result->agentId)
);
// $promoted->promoted - 전환에 성공했는지 여부

// 작업 취소
use Revolution\Copilot\Types\Rpc\TasksCancelRequest;

$cancelled = $session->rpc()->tasks()->cancel(
    new TasksCancelRequest(id: $result->agentId)
);
// $cancelled->cancelled - 취소에 성공했는지 여부

// 완료되었거나 취소된 작업 삭제
use Revolution\Copilot\Types\Rpc\TasksRemoveRequest;

$removed = $session->rpc()->tasks()->remove(
    new TasksRemoveRequest(id: $result->agentId)
);
// $removed->removed - 삭제에 성공했는지 여부

// 실행 중인 에이전트 작업에 메시지 전송(스티어링)
use Revolution\Copilot\Types\Rpc\TasksSendMessageRequest;

$sent = $session->rpc()->tasks()->sendMessage(
    new TasksSendMessageRequest(id: $result->agentId, message: 'Please search other directories too')
);
// $sent->sent - 메시지가 정상적으로 전송되었는지 여부
// $sent->error - 전송 실패 시 오류 메시지(nullable)

// 메인 턴만 중단하고, 큐에 있는 프롬프트는 다음 턴을 위해 유지
use Revolution\Copilot\Types\Rpc\InterruptMainTurnRequest;

$interrupted = $session->rpc()->interruptMainTurn(
    new InterruptMainTurnRequest(flushQueued: true)
);
// $interrupted->interrupted - 실행 중인 메인 턴을 중단했는지 여부

// 메인 턴은 중단하지 않고 실행 중인 백그라운드 에이전트를 모두 취소
$cancelledCount = $session->rpc()->cancelAllBackgroundAgents();
// 취소된 에이전트 수
```


## Related topics

- [RPC(Remote Procedure Call)](https://kawax.biz/ko/packages/laravel-copilot-sdk/rpc.md)
- [태스크 스케줄링](https://kawax.biz/ko/scheduling.md)
- [Artisan 콘솔](https://kawax.biz/ko/artisan.md)
- [Laravel Nightwatch 입문](https://kawax.biz/ko/blog/nightwatch-introduction.md)
- [InteractsWithTime 트레이트](https://kawax.biz/ko/advanced/interacts-with-time.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.